コミットを比較
| 作成者 | SHA1 | 日付 | |
|---|---|---|---|
|
|
63db918409
|
||
|
|
84c0f1f127
|
||
|
|
3b21f94f04
|
||
|
|
5064b6069e
|
||
|
|
16cef956f1
|
||
|
|
a1c305a42d
|
||
|
|
aa2ed6c765
|
||
|
|
e3bce7d562
|
||
|
|
68c08d3cd8
|
||
|
|
35de4fc1b0
|
||
|
|
1ff603fcda
|
||
|
|
2882c1ffc3
|
||
|
|
4042882530
|
||
|
|
3ea398f82b
|
||
|
|
dc7a2c9466
|
||
|
|
580b80aa87
|
||
|
|
6684c4913f
|
||
|
|
36faac26d2
|
||
|
|
ae0e17ed1b
|
||
|
|
0662ea7111
|
||
|
|
46a6f21e03
|
||
|
|
1a2870444d
|
||
|
|
95e43dd280
|
||
|
|
ac5f2aa043
|
||
|
|
6c583fe3e7
|
||
|
|
35849274c6
|
||
|
|
d04fe25274
|
||
|
|
cf9bc38d81
|
||
|
|
56600ecd99
|
||
|
|
4e3e91226e
|
検索条件に一致するファイルはありません
+1
-1
@@ -65,7 +65,7 @@ dotnet_diagnostic.IDE0005.severity = warning
|
||||
dotnet_diagnostic.IDE0055.severity = warning
|
||||
dotnet_diagnostic.IDE0161.severity = error
|
||||
|
||||
[{YMM4-GitHubUpdateNotifier,YMM4-Telemetry,YukkuriMovieMaker.Generator}/**]
|
||||
[{YMM4-ComputeGuard,YMM4-GitHubUpdateNotifier,YMM4-Telemetry,YukkuriMovieMaker.Generator}/**]
|
||||
dotnet_diagnostic.IDE0005.severity = none
|
||||
dotnet_diagnostic.IDE0055.severity = none
|
||||
dotnet_diagnostic.IDE0161.severity = none
|
||||
|
||||
+242
-71
@@ -1,20 +1,29 @@
|
||||
========================================
|
||||
波動光学 for YMM4 v2.1.0
|
||||
波動光学 for YMM4 v3.0.0
|
||||
========================================
|
||||
YukkuriMovieMaker4上で動作する、素材を回折も収差もない理想の像とみなし、
|
||||
レンズの開口と波面収差から求めた点像分布関数で畳み込んで、
|
||||
回折と収差によるにじみを描画する映像エフェクトプラグインです。
|
||||
点像分布関数は、1点から出た光が撮像面でどう広がるかを表す関数です。
|
||||
開口は、レンズの中で光が通る穴です。回折は、光が開口の縁を回り込んで広がる
|
||||
現象です。光の波の山をつないだ面を波面と呼び、
|
||||
波面が理想の形からずれることを波面収差と呼びます。
|
||||
畳み込みは、素材の各画素の光を点像分布関数の形に広げて足し合わせる計算です。
|
||||
瞳関数は、開口の各点を通る光の振幅と位相を表す関数です。
|
||||
振幅は波の揺れの大きさ、位相は波の進み具合です。
|
||||
本プラグインは、瞳関数のフラウンホーファー回折を高速フーリエ変換で解いて
|
||||
点像分布関数を求めます。
|
||||
点像分布関数を求めます。フラウンホーファー回折は、開口から十分に遠い面や、
|
||||
レンズの焦点面で見る回折です。高速フーリエ変換は、画像や波形を周波数ごとの成分に
|
||||
分けて表す変換を、速く計算する方法です。
|
||||
履歴フレーム、参照画像、深度情報、学習済みモデルは使用しません。
|
||||
にじみの形は光学系と収差の設定から決定論的に決まり、同じ設定では常に
|
||||
同じ形になります。
|
||||
適用量、利得、波長、F値、画素ピッチ、開口回転、中央遮蔽、デフォーカス、
|
||||
縦横非点収差、斜め非点収差、水平コマ収差、垂直コマ収差、球面収差の
|
||||
13項目はアニメーションに対応しています。
|
||||
畳み込みはGPUで計算します。畳み込みを計算し直したフレームでは、その結果を
|
||||
画面に出す前に検査します。GPUを使えないときと、検査で誤りを見つけたときは、
|
||||
CPUで計算します。
|
||||
エフェクトの種類一覧では「波動光学」として表示されます。
|
||||
--------------------------------------------------------------------------------
|
||||
■ 動作要件
|
||||
@@ -24,21 +33,110 @@ YukkuriMovieMaker4上で動作する、素材を回折も収差もない理想
|
||||
- YMM4 : YukkuriMovieMaker4の最新版を推奨します
|
||||
- ランタイム : .NET 10.0
|
||||
- GPU : Direct3D 12とDirect3D 11・12間の共有テクスチャおよび
|
||||
共有フェンスを利用できるGPU
|
||||
共有フェンスを利用できるGPUを推奨します。
|
||||
利用できない場合は、CPUで計算します。
|
||||
--------------------------------------------------------------------------------
|
||||
■ 注意事項
|
||||
--------------------------------------------------------------------------------
|
||||
- AviUtl非対応: 本プラグインはAviUtl向けのEXO出力に対応していません。
|
||||
|
||||
- GPU非対応時: Direct3D 12デバイスを取得できない場合と、YMM4が使う
|
||||
Direct3D 11デバイスが相互運用に必要なインターフェースを持たない場合は、
|
||||
エフェクトを適用せず入力映像を表示します。GPUメモリが足りず
|
||||
共有テクスチャを確保できない場合も同じです。
|
||||
- デフォルトの設定: 追加した直後は、映像はわずかにやわらぐだけです。
|
||||
にじみを大きくするには、デフォーカスの絶対値かF値を上げてください。
|
||||
デフォーカスは、焦点の位置のずれを表す項目です。単位のwavesは、
|
||||
波長を1とした量です。
|
||||
|
||||
- 品質と収差: 品質は、瞳関数を置く格子の大きさを切り替えます。
|
||||
格子は瞳関数の値を縦横に並べた表で、1つ1つの値を標本と呼びます。
|
||||
格子が粗いと、大きな波面収差で位相が急に変わる所を表しきれず、
|
||||
点像分布関数の形が崩れます。波面収差の絶対値を大きくするときは、
|
||||
品質を上げてください。
|
||||
|
||||
- カーネル半径: 1〜63画素で、デフォルトは15画素です。カーネルは、
|
||||
畳み込みの重みを正方形に並べたものです。正方形は、
|
||||
中心から上下左右にカーネル半径の画素数まで広がります。
|
||||
正方形の外に届く光は捨て、カーネルの値の和が1になるように正規化します。
|
||||
デフォーカスの絶対値を大きくするときは、カーネル半径を上げてください。
|
||||
デフォルトの波長、F値、画素ピッチで標準の品質のとき、
|
||||
にじみは中心から約35画素までしか広がりません。それより大きなにじみには、
|
||||
品質も上げてください。品質を上げるほど、点像分布関数の計算が重くなります。
|
||||
カーネル半径と計算の重さの関係は、処理負荷の項目にあります。
|
||||
|
||||
- 利得: 利得は、畳み込んだ結果に掛ける倍率です。
|
||||
100%で画素の値の総和を保ちます。利得を掛けた結果は、入力映像と混ぜる前に、
|
||||
各成分が表せる最大の値で打ち切り、さらに色の成分が不透明度を超えないように
|
||||
抑えます。
|
||||
|
||||
- 適用量0%: 適用量は、入力映像と、利得を掛けた結果を混ぜる割合です。
|
||||
適用量が0%のときは入力を変更せず、畳み込みの計算も行いません。
|
||||
|
||||
- アダプター: Windowsが認識しているGPUと、GPUの命令をCPUで
|
||||
実行するソフトウェアを、まとめてアダプターと呼びます。
|
||||
後者をソフトウェア アダプターと呼び、Microsoft Basic Render Driverがこれに
|
||||
当たります。アダプターの容量は、CPUとGPUが同じメモリを使う構成では共有の
|
||||
システムメモリの大きさ、それ以外では専用のビデオメモリの大きさです。
|
||||
必要なGPUメモリは、素材の大きさとカーネル半径から見積もります。
|
||||
|
||||
- 計算の経路: 畳み込みは、GPUで計算する道筋と、CPUで計算する道筋のどちらかで
|
||||
行います。以下では、前者をGPUの経路、後者をCPUの経路と呼びます。
|
||||
CPUの経路で計算するのは、次の場合です。1つ目は、
|
||||
Direct3D 12デバイスを取得できない場合です。2つ目は、
|
||||
YMM4が使うDirect3D 11デバイスが、相互運用に必要なインターフェースを
|
||||
持たない場合です。3つ目は、Direct3D 11・12間の共有の準備に失敗した場合か、
|
||||
GPUで計算するための準備に失敗した場合です。4つ目は、
|
||||
YMM4が使うアダプターがソフトウェア アダプターの場合です。5つ目は、
|
||||
必要なGPUメモリがアダプターの容量の4分の1を超える場合です。このほかに、
|
||||
GPUの異常が起きたときと、GPUの経路でメモリを確保できなかったときも、
|
||||
YMM4を終了するまでCPUの経路で計算します。GPUの異常と、メモリの確保の失敗は、
|
||||
後の項目で説明します。ソフトウェア アダプターでは、
|
||||
CPUの経路のほうが速いです。ソフトウェア アダプターではないGPUを
|
||||
使える環境では、CPUの経路のほうが、一般に計算が遅くなります。
|
||||
|
||||
- GPUの自己試験: GPUは、ドライバーやハードウェアの不具合で誤った値を
|
||||
返すことがあります。そのため、YMM4を起動するたびに、
|
||||
CPUの経路で計算する場合のどれにも当たらない最初のフレームで、
|
||||
アダプターごとに1回だけ自己試験を行います。自己試験は、
|
||||
決まったカーネルと決まった模様をGPUで畳み込み、
|
||||
倍精度で計算した値と比べる処理です。倍精度は、
|
||||
64ビットの浮動小数点数による計算で、GPUで使う32ビットの計算より誤差が
|
||||
小さくなります。同じ計算を2回行い、結果が1ビットも違わないことも確かめます。
|
||||
自己試験にかかった時間は、Intel Iris Xe Graphicsで0.7〜0.8秒でした。
|
||||
|
||||
- GPUの検査: GPUの経路で畳み込みを計算し直したフレームでは、
|
||||
出力を画面に出す前に、次の3つを調べます。1つ目は、
|
||||
NaNか無限大が無いことです。NaNは、計算の失敗で生じる、
|
||||
数として扱えない値です。2つ目は、利得を掛ける前の出力の総和が、
|
||||
素材の総和と合うことです。3つ目は、利得を掛ける前の出力の16か所の値が、
|
||||
倍精度で計算した値と合うことです。測定値は、GPUの結果から求めた値です。
|
||||
参照値は、測定値と比べる値で、素材の値から求めた値か、
|
||||
0のように初めから分かっている値です。許容値は、差として許す最大の値です。
|
||||
2つ目と3つ目の許容値は、丸めの誤差の上限から導いた値です。
|
||||
測定値と参照値の差が許容値以下なら合格、超えれば不合格とします。
|
||||
見つけられるのは、この3つに表れた誤りだけです。
|
||||
利得だけを変えたフレームのうち、キャッシュの項目にある保存した値に
|
||||
GPUで利得を掛け直すフレームでは、その計算を検査しません。
|
||||
|
||||
- GPUの異常: 自己試験か検査で不合格になったこと、GPUが突然使えなくなったこと、
|
||||
GPUの経路で想定していない例外が起きたことを、GPUの異常と呼びます。
|
||||
メモリを確保できなかったことは、GPUのメモリでもシステムメモリでも、
|
||||
GPUの異常に含めません。自己試験の最中にメモリを確保できなかったときだけは、
|
||||
自己試験の不合格として扱い、GPUの異常に含めます。
|
||||
GPUの異常が起きたときは、そのフレームをCPUの経路で計算し直します。
|
||||
異常を起こしたアダプターでは、一時的な不具合でも、
|
||||
YMM4を終了するまでCPUの経路で計算し、共有テクスチャなど、
|
||||
GPUの資源を解放します。GPUの経路でメモリを確保できなかったときも、
|
||||
YMM4を終了するまでCPUの経路で計算します。
|
||||
|
||||
- 異常の送信: GPUの異常の内容は、開発者へ自動で送信します。送信は、
|
||||
YMM4の起動中にアダプターごとに1回だけです。
|
||||
GPUの経路でメモリを確保できなかったときは、送信しません。
|
||||
自己試験の最中にメモリを確保できなかったときだけは、
|
||||
自己試験の不合格として送信します。
|
||||
送信する報告の数には、さらに上限があります。
|
||||
上限は、「不具合の報告」で説明しています。
|
||||
|
||||
- 処理対象: 畳み込みには現在のフレームの色と不透明度だけを使用します。
|
||||
履歴フレーム、外部画像、深度情報、学習済みモデルは使用しません。
|
||||
素材に透明でない画素が無いときは、エフェクトを適用せず入力映像を
|
||||
表示します。
|
||||
素材のすべての画素が透明なときは、エフェクトを適用せず入力映像を表示します。
|
||||
|
||||
- 計算モデル: 計算は単色のフラウンホーファー回折に限ります。白色光の
|
||||
ように波長の混ざった光は扱いません。点像分布関数は画面のどこでも同じで、
|
||||
@@ -46,56 +144,74 @@ YukkuriMovieMaker4上で動作する、素材を回折も収差もない理想
|
||||
そのまま重み付けして足し合わせます。画素の値を光の強さに比例する値へ
|
||||
直してから畳み込む処理はしません。
|
||||
|
||||
- 品質と収差: 品質は、瞳関数を置く格子の大きさを切り替えます。格子は
|
||||
瞳関数の値を縦横に並べた表で、1つ1つの値を標本と呼びます。格子が粗いと、
|
||||
大きな波面収差で位相が急に変わる所を表しきれず、点像分布関数の形が
|
||||
崩れます。波面収差を大きくするときは、品質を上げてください。
|
||||
|
||||
- カーネル半径: 1〜63画素で、デフォルトは15画素です。カーネルは、畳み込みの
|
||||
重みを正方形に並べたものです。正方形は、中心から上下左右にカーネル半径の
|
||||
画素数まで広がります。正方形の外に届く光は捨て、カーネルの値の和が1に
|
||||
なるように正規化します。デフォーカスを大きくするときは、カーネル半径と
|
||||
品質を上げてください。上げるほど計算が重くなります。
|
||||
|
||||
- 計算領域: 透明な部分も含む素材全体の矩形の上下左右に余白を加えた
|
||||
大きさを計算領域とし、長辺は8192画素が上限です。余白は、カーネル半径を
|
||||
4画素単位に切り上げた画素数で、16画素を下回りません。素材の長辺の
|
||||
上限は、8192画素から余白の2倍を引いた値です。カーネル半径が16画素以下
|
||||
なら8160画素、63画素なら8064画素になります。素材の長辺がこの上限を
|
||||
超える場合は、エフェクトを適用せず入力映像を表示します。
|
||||
- 計算領域: 透明な部分も含む素材全体の矩形の上下左右に余白を加えた大きさを
|
||||
計算領域とし、長辺は8192画素が上限です。余白は、
|
||||
カーネル半径を4画素単位に切り上げた画素数で、16画素を下回りません。
|
||||
素材の長辺の上限は、8192画素から余白の2倍を引いた値です。
|
||||
カーネル半径が16画素以下なら8160画素、63画素なら8064画素になります。
|
||||
素材の長辺がこの上限を超える場合は、エフェクトを適用せず入力映像を
|
||||
表示します。
|
||||
|
||||
- 中央遮蔽: 中央遮蔽で開口をほとんどふさぎ、瞳関数の格子に光の通る標本が
|
||||
1つも無くなる設定では、エフェクトを適用せず入力映像を表示します。
|
||||
品質を上げると起きにくくなります。
|
||||
|
||||
- 処理負荷: GPUメモリ使用量は、計算領域の大きさに応じて増えます。
|
||||
作業用のバッファーとして、計算領域の1画素につき32バイトをGPUに
|
||||
確保します。処理量は、素材全体の大きさと畳み込む範囲の大きさに応じて
|
||||
増えます。畳み込む範囲は、透明でない画素をすべて囲む最小の矩形を
|
||||
カーネル半径だけ広げ、外側へ4画素単位にそろえた範囲です。畳み込みは、
|
||||
横方向と縦方向の1次元の重みを1組とした、何組かの和で近似して行います。
|
||||
収差を入れると組の数が増え、カーネル半径を上げると1組あたりの計算量が
|
||||
増えるので、どちらも計算が重くなります。品質を上げると、点像分布関数の
|
||||
計算が重くなります。
|
||||
- 処理負荷: 畳み込む範囲が大きいほど、計算は重くなります。畳み込む範囲は、
|
||||
素材の透明でない画素をすべて囲む最小の矩形をカーネル半径だけ広げ、
|
||||
外側の4画素の倍数の位置へそろえた範囲です。広げた範囲が計算領域の外へ
|
||||
出るときは、計算領域の端で切ります。
|
||||
畳み込む範囲を正方形のタイルに分け、タイルごとに高速フーリエ変換で
|
||||
畳み込みます。タイルの一辺Tは、カーネル半径が23画素以下なら128画素、
|
||||
24画素以上なら512画素です。
|
||||
タイルの縁からカーネル半径の幅の値は捨てるので、カーネル半径を上げるほど、
|
||||
1枚のタイルが出力できる範囲は狭まります。カーネル半径を上げても、
|
||||
Tが同じなら、必要なタイルの枚数は減らず、増えることがあります。
|
||||
枚数が増えるほど、計算は重くなります。カーネル半径を23画素から24画素に
|
||||
上げると、タイルが大きくなり、出力できる範囲が広がります。そのため、
|
||||
畳み込む範囲が大きい素材では計算が軽くなることがあり、
|
||||
小さい素材ではかえって重くなることがあります。収差を入れても、
|
||||
畳み込みの計算量は変わりません。CPUの経路は、全く透明な行と、
|
||||
全く透明なタイルを省くので、素材の中身によっても時間が変わります。
|
||||
品質を上げると、点像分布関数の計算が重くなります。
|
||||
|
||||
- キャッシュ: 素材の大きさと色と不透明度が変わらず、「利得」と「適用量」
|
||||
以外の項目も変わらないフレームでは、畳み込みの計算を再利用します。
|
||||
利得だけを変えたフレームでは、再利用した畳み込みに利得を掛け直します。
|
||||
適用量だけを変えたフレームでは、混ぜる割合だけを変えます。動画や口パクの
|
||||
ように素材の内容が変わるフレームと、「利得」と「適用量」以外の項目を
|
||||
アニメーションで変えたフレームでは、毎回計算し直すので処理が重く
|
||||
なります。素材が変わったかどうかを調べる計算は、再利用するフレームでも
|
||||
毎フレーム行います。
|
||||
- メモリ: エフェクト1つあたり、GPUの経路では、2つの共有テクスチャをGPUに
|
||||
確保します。素材を入れる共有テクスチャは、素材の1画素につき4バイトです。
|
||||
結果を入れる共有テクスチャは、畳み込む範囲の1画素につき4バイトです。
|
||||
畳み込む範囲が入りきらなくなったときだけ、結果を入れる共有テクスチャを、
|
||||
そのときの範囲の大きさで作り直します。
|
||||
|
||||
- 適用量0%: 適用量は、入力映像と、利得を掛けた結果を混ぜる割合です。
|
||||
適用量が0%のときは入力を変更せず、畳み込みの計算も行いません。
|
||||
- 作業領域: GPUの経路では、共有テクスチャのほかに、
|
||||
16MB以下のタイルの作業領域、カーネルを高速フーリエ変換したスペクトル、
|
||||
検査に使う値を書くバッファーを確保します。CPUの経路では、素材の画素の配列、
|
||||
出力の画素の配列、作業スレッドの作業領域をシステムメモリに確保します。
|
||||
作業領域のうち、タイルの分は合計で64MB以下です。このほかに、
|
||||
素材を読むためのDirect2Dのビットマップと、出力を書くためのDirect2Dの
|
||||
ビットマップも確保します。出力を書くためのビットマップは、
|
||||
畳み込む範囲を収められる大きさで、収まらなくなったときだけ作り直します。
|
||||
どちらの経路でも、利得だけを変えたフレームの後は、
|
||||
畳み込む範囲の1画素につき16バイトを追加で確保します。この領域は、
|
||||
キャッシュの項目にある保存した値のためのものです。
|
||||
|
||||
- 利得: 利得は、畳み込んだ結果に掛ける倍率です。100%で画素の値の総和を
|
||||
保ちます。利得を掛けた結果は、入力映像と混ぜる前に、各成分が表せる
|
||||
最大の値で打ち切ります。
|
||||
- キャッシュ: 素材の大きさと色と不透明度が変わらず、
|
||||
「利得」と「適用量」以外の項目も変わらないフレームでは、
|
||||
畳み込みの計算を再利用します。利得だけを変えたフレームでは、
|
||||
最初の1回だけ畳み込みを計算し直し、利得を掛ける前の値を保存します。
|
||||
2回目からは、保存した値に利得を掛け直します。素材か、
|
||||
「利得」と「適用量」以外の項目が変わると、保存した値を破棄します。
|
||||
適用量だけを変えたフレームでは、混ぜる割合だけを変えます。
|
||||
動画や口パクのように素材の内容が変わるフレームと、
|
||||
「利得」と「適用量」以外の項目をアニメーションで変えたフレームでは、
|
||||
毎回計算し直すので処理が重くなります。素材が変わったかどうかを調べる計算は、
|
||||
再利用するフレームでも毎フレーム行います。開口形状が円形のときは、
|
||||
「羽根枚数」と「開口回転」を変えても、計算し直しません。
|
||||
|
||||
- 再現性: 計算は決定論的で、時間値や乱数を使用しません。同じGPUと
|
||||
ドライバーでは、同じ素材と同じ設定から常に同じ結果になります。
|
||||
- 再現性: 計算は決定論的で、時間値や乱数を使用しません。
|
||||
同じ素材と同じ設定から常に同じ結果になるのは、同じ経路で、GPU、ドライバー、
|
||||
CPU、Windows、.NETの組が同じときです。GPUの経路でも結果にCPUが関わるのは、
|
||||
点像分布関数とカーネルのスペクトルをCPUで求めるためです。
|
||||
GPUの経路とCPUの経路では、結果がわずかに違います。
|
||||
GPUの異常でCPUの経路に切り替わったときも、同じ設定で結果がわずかに
|
||||
変わります。
|
||||
|
||||
- 透明部分: 畳み込みは不透明度にも掛かるので、素材の縁の外にも半透明の
|
||||
にじみが広がります。出力の範囲は、素材の範囲と畳み込む範囲を合わせた
|
||||
@@ -110,8 +226,9 @@ YukkuriMovieMaker4上で動作する、素材を回折も収差もない理想
|
||||
--------------------------------------------------------------------------------
|
||||
■ 不具合の報告
|
||||
--------------------------------------------------------------------------------
|
||||
本プラグインは、想定していない例外が起きたときに、その内容を開発者へ自動で
|
||||
送信します。同意は求めず、常に送信します。
|
||||
本プラグインは、想定していない例外が起きたときと、GPUの異常でCPUの経路に
|
||||
切り替えたときに、その内容を開発者へ自動で送信します。同意は求めず、
|
||||
常に送信します。
|
||||
|
||||
送信する情報は次のとおりです。
|
||||
例外 : 型の完全名、メッセージ、スタックトレース
|
||||
@@ -120,33 +237,84 @@ YukkuriMovieMaker4上で動作する、素材を回折も収差もない理想
|
||||
実行環境 : OSの名前とバージョン、.NETのバージョン、
|
||||
CPUのアーキテクチャ、論理プロセッサ数
|
||||
識別子 : YMM4の起動ごとに決まるセッション識別子、報告ごとの識別子
|
||||
GPUの異常 : 切り替えた理由、不合格になった検査の名前と測定値と
|
||||
参照値と許容値、アダプターの名前、ベンダーIDと
|
||||
デバイスIDとサブシステムIDとリビジョン、
|
||||
ドライバーのバージョン、ソフトウェア アダプターかどうか、
|
||||
計算領域の幅と高さ、必要なGPUメモリの見積もり
|
||||
|
||||
映像の中身とプロジェクトの内容は送信しません。継続して個人を追跡する
|
||||
識別子も持ちません。セッション識別子はYMM4を起動し直すと別の値に
|
||||
なります。メッセージとファイル名に含まれる利用者名などの文字列は、送信の
|
||||
前に置き換えます。送信元のIPアドレスは受信側へ渡す手前で取り除いています。
|
||||
|
||||
送信するのは想定していない例外だけです。YMM4が本プラグインのエフェクトを
|
||||
作るとき、フレームごとに更新するとき、入力をつなぎ直すとき、破棄するときと、
|
||||
Direct2Dがシェーダーの定数を書き込むときに起きた例外を報告し、その後は
|
||||
YMM4へそのまま渡します。更新の確認では、更新情報の取得と比較で起きた例外は
|
||||
報告しません。通知の文を組み立てて表示するときに起きた例外は報告し、
|
||||
YMM4へは渡しません。画面の操作やバックグラウンドの処理で未処理になった
|
||||
例外も報告しますが、本プラグインのコードが関わる例外に限ります。
|
||||
本プラグインの外で起きた例外は送信しません。
|
||||
送信するのは、想定していない例外と、GPUの異常でCPUの経路に
|
||||
切り替えたことだけです。GPUの異常は、注意事項の「GPUの異常」の項目で
|
||||
説明しています。YMM4が本プラグインのエフェクトを作るとき、
|
||||
フレームごとに更新するとき、入力をつなぎ直すとき、破棄するときと、
|
||||
Direct2Dがシェーダーの定数を書き込むときに起きた例外を報告し、
|
||||
その後はYMM4へそのまま渡します。ただし、GPUの経路の計算中に起きた例外は、
|
||||
YMM4へは渡さず、そのフレームをCPUの経路で計算し直します。
|
||||
この例外は、GPUの異常として報告しますが、メモリを確保できなかったものは
|
||||
報告しません。自己試験の最中に確保できなかったときだけは、
|
||||
自己試験の不合格として報告します。
|
||||
GPUの異常の報告は、YMM4の起動中にアダプターごとに1回だけです。
|
||||
|
||||
更新の確認では、更新情報の取得と比較で起きた例外は報告しません。
|
||||
通知の文を組み立てて表示するときに起きた例外は報告し、YMM4へは渡しません。
|
||||
画面の操作やバックグラウンドの処理で未処理になった例外も報告しますが、
|
||||
本プラグインのコードが関わる例外に限ります。本プラグインの外で起きた例外は
|
||||
送信しません。
|
||||
|
||||
次の失敗は送信しません。
|
||||
効果をかけないだけで済ませるもの : Direct3D 12デバイスを取得できない、
|
||||
YMM4のDirect3D 11デバイスが
|
||||
相互運用に必要なインターフェースを
|
||||
持たない、GPUメモリが足りず
|
||||
共有テクスチャを確保できない、
|
||||
計算領域が8192画素に収まらない、
|
||||
開口に光の通る標本が無いときに、
|
||||
エフェクトを適用せず入力映像を
|
||||
表示したとき
|
||||
更新の確認の通信の失敗 : manjubox.netとGitHubのどちらへも
|
||||
接続できない
|
||||
CPUの経路で計算するだけで済ませるもの : Direct3D 12デバイスを取得できない、
|
||||
YMM4のDirect3D 11デバイスが
|
||||
相互運用に必要なインターフェースを
|
||||
持たない、
|
||||
Direct3D 11・12間の共有の準備に
|
||||
失敗した、
|
||||
GPUで計算するための準備に失敗した、
|
||||
アダプターが
|
||||
ソフトウェア アダプターである、
|
||||
必要なGPUメモリが容量の
|
||||
4分の1を超える、
|
||||
GPUの経路でメモリを確保できない。
|
||||
ただし、自己試験の最中に
|
||||
メモリを確保できなかったときは
|
||||
送信する
|
||||
効果をかけないだけで済ませるもの : 計算領域が8192画素に収まらないか、
|
||||
開口に光の通る標本が無くて、
|
||||
エフェクトを適用せず入力映像を
|
||||
表示したとき
|
||||
更新の確認の通信の失敗 : manjubox.netとGitHubのどちらへも
|
||||
接続できない
|
||||
|
||||
報告の送信には、ほかのプラグインと共通のライブラリであるYMM4-Telemetryを
|
||||
使います。GPUの異常の報告の内容は、同じく共通のライブラリである
|
||||
YMM4-ComputeGuardが組み立てます。送信する報告の数には、GPUの異常を
|
||||
アダプターごとに1回だけ報告する制限のほかに、2つの上限があります。
|
||||
|
||||
1つ目の上限は、同じ報告を1回の起動で3件までとするものです。
|
||||
同じ報告とみなすのは、例外の型と、スタックトレースのうち本プラグインの
|
||||
関数を呼び出し順に並べたものが、どちらも一致する場合です。
|
||||
例外が別の例外を原因として持つときは、原因の例外についても、
|
||||
型と本プラグインの関数を比べます。原因の例外を含めて本プラグインの
|
||||
関数が1つも無い報告は、スタックトレースのすべての関数を
|
||||
呼び出し順に並べて比べます。比べる関数は、原因の例外の分も合わせて
|
||||
先頭の20個までです。例外は、原因の例外を含めて5個までたどります。
|
||||
|
||||
原因の例外が無いGPUの異常の報告は、例外の型がどれも同じで、
|
||||
スタックトレースもありません。そのため、切り替えた理由が違っても、
|
||||
同じ報告になります。別のプラグインがYMM4-ComputeGuardを使って
|
||||
報告する、原因の例外が無いGPUの異常の報告も、これと同じ報告です。
|
||||
1つ目の上限の件数は、それらと合わせて数えます。
|
||||
|
||||
2つ目の上限は、新たに送る報告の合計を、1回の起動で20件までとするものです。
|
||||
合計には、この「不具合の報告」で説明するすべての報告を数えます。
|
||||
この上限の件数は、YMM4-Telemetryで報告する別のプラグインの報告と
|
||||
合わせて数えます。
|
||||
|
||||
どちらかの上限を超える報告は、送信せずに捨てます。
|
||||
|
||||
送信できなかった報告はYMM4のユーザーフォルダーへ退避します。
|
||||
次にYMM4を起動したあと、本プラグインのエフェクトを生成するか、
|
||||
@@ -154,6 +322,9 @@ YukkuriMovieMaker4上で動作する、素材を回折も収差もない理想
|
||||
退避した報告を1回の起動で10件まで送り直します。
|
||||
送信も再送も非同期に行うため、通信を待って起動と描画が遅くなることは
|
||||
ありません。
|
||||
|
||||
上限を超えて捨てた報告は、退避も再送もしません。
|
||||
再送は、どちらの上限の件数にも入れません。
|
||||
--------------------------------------------------------------------------------
|
||||
■ 免責事項
|
||||
--------------------------------------------------------------------------------
|
||||
|
||||
@@ -123,6 +123,21 @@ jobs:
|
||||
-p:Platform=x64 `
|
||||
-p:SkipPluginDeploy=true
|
||||
|
||||
- name: 数値の部品の試験のビルド
|
||||
shell: pwsh
|
||||
run: |
|
||||
dotnet build SpectralConvolution/SpectralConvolution.Tests/SpectralConvolution.Tests.csproj `
|
||||
-c Release `
|
||||
-maxcpucount:1
|
||||
|
||||
- name: 数値の部品の試験の実行
|
||||
shell: pwsh
|
||||
run: |
|
||||
dotnet test SpectralConvolution/SpectralConvolution.Tests/SpectralConvolution.Tests.csproj `
|
||||
--no-build `
|
||||
--no-restore `
|
||||
-c Release
|
||||
|
||||
- name: パッケージの作成
|
||||
id: package
|
||||
shell: pwsh
|
||||
|
||||
@@ -7,3 +7,6 @@
|
||||
[submodule "YMM4-Telemetry"]
|
||||
path = YMM4-Telemetry
|
||||
url = https://github.com/routersys/YMM4-Telemetry.git
|
||||
[submodule "YMM4-ComputeGuard"]
|
||||
path = YMM4-ComputeGuard
|
||||
url = https://github.com/routersys/YMM4-ComputeGuard.git
|
||||
@@ -11,6 +11,7 @@ YukkuriMovieMaker4(YMM4)上で動作する、素材を回折も収差もな
|
||||
履歴フレーム、参照画像、学習済みモデルを使わず、入力された一枚の映像だけを処理します。
|
||||
にじみの形は光学系と収差の設定から決定論的に決まり、同じ設定では常に同じ形になります。
|
||||
適用量、利得、波長、F値、画素ピッチ、開口回転、中央遮蔽、デフォーカス、縦横非点収差、斜め非点収差、水平コマ収差、垂直コマ収差、球面収差の13項目はアニメーションに対応しています。
|
||||
畳み込みはGPUで計算します。畳み込みを計算し直したフレームでは、その結果を画面に出す前に検査します。GPUを使えないときと、検査で誤りを見つけたときは、CPUで計算します。
|
||||
|
||||
---
|
||||
|
||||
@@ -24,9 +25,10 @@ YukkuriMovieMaker4(YMM4)上で動作する、素材を回折も収差もな
|
||||
- [2. 光学系の項目とにじみの大きさ](#2-光学系の項目とにじみの大きさ)
|
||||
- [3. 開口の形と中央遮蔽](#3-開口の形と中央遮蔽)
|
||||
- [4. ゼルニケ多項式による波面収差](#4-ゼルニケ多項式による波面収差)
|
||||
- [5. 分離可能な畳み込み](#5-分離可能な畳み込み)
|
||||
- [5. タイルごとの高速フーリエ変換による畳み込み](#5-タイルごとの高速フーリエ変換による畳み込み)
|
||||
- [6. 利得と適用量](#6-利得と適用量)
|
||||
- [7. 品質の選択](#7-品質の選択)
|
||||
- [8. GPUの計算の検査とCPUの経路](#8-gpuの計算の検査とcpuの経路)
|
||||
5. [パラメータ一覧](#パラメータ一覧)
|
||||
- [出力グループ](#出力グループ)
|
||||
- [光学系グループ](#光学系グループ)
|
||||
@@ -49,7 +51,13 @@ YukkuriMovieMaker4(YMM4)上で動作する、素材を回折も収差もな
|
||||
|
||||
畳み込んだ結果は、「利得」を掛けてから、「適用量」の割合で入力映像と混ぜ合わせて出力します。
|
||||
|
||||
畳み込みの計算はComputeWeaveの計算シェーダーがDirect3D 12で実行します。点像分布関数と畳み込みの重みは、CPUで求めます。YMM4のDirect3D 11側とComputeWeaveのDirect3D 12側は、素材と畳み込んだ結果を共有テクスチャと共有フェンスで受け渡します。通常のフレーム処理では、CPUへの画素の読み戻しを行わず、7個の整数だけを読み戻します。7個の整数は、素材の色と不透明度から作る2個のハッシュと、透明でない画素の数と、外接矩形の位置を表す4個の値です。外接矩形は、透明でない画素をすべて囲む最小の矩形です。ハッシュは素材が変わったかどうかの判定に、外接矩形は畳み込む範囲を決めるのに使います。畳み込む範囲は、外接矩形を「カーネル半径」の画素数だけ広げ、外側へ4画素単位にそろえた範囲です。「カーネル半径」は、にじみが上下左右に届く画素数の上限です。
|
||||
畳み込みは、GPUで計算する道筋と、CPUで計算する道筋のどちらかで行います。以下では、前者をGPUの経路、後者をCPUの経路と呼びます。経路の選び方は「GPUの計算の検査とCPUの経路」にあります。点像分布関数と、畳み込みの重みを並べたカーネルは、どちらの経路でもCPUで求めます。
|
||||
|
||||
GPUの経路では、ComputeWeaveの計算シェーダーがDirect3D 12で計算します。YMM4のDirect3D 11側とComputeWeaveのDirect3D 12側は、素材と畳み込んだ結果を共有テクスチャと共有フェンスで受け渡します。CPUの経路では、素材をDirect2Dのビットマップから読み、作業スレッドで計算して、結果をDirect2Dのビットマップに書きます。
|
||||
|
||||
外接矩形は、素材の透明でない画素をすべて囲む最小の矩形です。「カーネル半径」は、にじみが上下左右に届く画素数の上限です。畳み込む範囲は、外接矩形を「カーネル半径」の画素数だけ広げ、外側の4画素の倍数の位置へそろえた範囲です。広げた範囲が、透明な部分も含む素材全体の矩形に余白を加えた計算領域の外へ出るときは、計算領域の端で切ります。計算領域は「制限事項」にあります。
|
||||
|
||||
GPUにある値をCPUが読み取ることを、読み戻しと呼びます。GPUの経路では、フレームごとに読み戻すのは、素材の全画素ではなく、7個の整数です。7個の整数は、素材の色と不透明度から作る2個のハッシュ、透明でない画素の数、外接矩形の位置を表す4個の値です。ハッシュは、素材の内容を短い数値にまとめた値で、素材が変わったかどうかの判定に使います。畳み込みを計算し直すフレームでは、これに加えて、検査に使う値も読み戻します。検査に使う値には、出力の16か所の値と、各か所の周りの素材の値が含まれます。検査は「GPUの計算の検査とCPUの経路」にあります。CPUの経路では、素材の画素を毎フレーム読み込み、ハッシュと外接矩形を、GPUの経路と同じ定義でCPUが求めます。
|
||||
|
||||
素材が変わらず、「利得」と「適用量」以外の項目も変わらないフレームでは、畳み込みの計算を再利用します。
|
||||
|
||||
@@ -64,7 +72,7 @@ YukkuriMovieMaker4(YMM4)上で動作する、素材を回折も収差もな
|
||||
| OS | Windows 10 バージョン2004(ビルド19041)以降 / Windows 11(64bit) |
|
||||
| YukkuriMovieMaker4 | 最新版を推奨 |
|
||||
| ランタイム | .NET 10.0 |
|
||||
| GPU | Direct3D 12とDirect3D 11・12間の共有テクスチャおよび共有フェンスを利用できるGPU |
|
||||
| GPU | Direct3D 12とDirect3D 11・12間の共有テクスチャおよび共有フェンスを利用できるGPUを推奨します。利用できない場合は、CPUで計算します |
|
||||
|
||||
---
|
||||
|
||||
@@ -75,17 +83,19 @@ YukkuriMovieMaker4(YMM4)上で動作する、素材を回折も収差もな
|
||||
3. YMM4を起動し、タイムライン上のアイテムに映像エフェクトを追加します。
|
||||
4. 映像エフェクトの種類として「波動光学」を選択してください。
|
||||
|
||||
追加した直後は、映像はわずかにやわらぐだけです。にじみを大きくするには、「デフォーカス」の絶対値を上げるか、「F値」を上げます。詳しくは「光学系の項目とにじみの大きさ」の節にあります。
|
||||
|
||||
---
|
||||
|
||||
## 主な機能
|
||||
|
||||
### 1. 点像分布関数の計算
|
||||
|
||||
点像分布関数は、瞳関数から求めます。瞳関数は、開口の各点を通る光の振幅と位相を表す関数です。振幅は波の揺れの大きさ、位相は波の進み具合です。開口の内側では振幅を1、外側では0とし、位相には波面収差を与えます。瞳関数の高速フーリエ変換を求め、その絶対値の2乗を点像分布関数とします。開口から十分に遠い面や、レンズの焦点面で見る回折を、フラウンホーファー回折と呼びます。この計算は、フラウンホーファー回折の式に当たります。
|
||||
点像分布関数は、瞳関数から求めます。瞳関数は、開口の各点を通る光の振幅と位相を表す関数です。振幅は波の揺れの大きさ、位相は波の進み具合です。開口の内側では振幅を1、外側では0とし、位相には波面収差を与えます。高速フーリエ変換は、画像や波形を周波数ごとの成分に分けて表す変換を、速く計算する方法です。開口から十分に遠い面や、レンズの焦点面で見る回折を、フラウンホーファー回折と呼びます。瞳関数の高速フーリエ変換を求め、その絶対値の2乗を点像分布関数とする計算は、フラウンホーファー回折の式に当たります。
|
||||
|
||||
畳み込みの重みは、点像分布関数から値を取り出して作ります。取り出すのは、中心から上下左右に「カーネル半径」の画素数までの正方形の範囲です。重みをこの正方形に並べたものを、カーネルと呼びます。カーネルの各画素の値は、画素の中心の位置で点像分布関数を補間した値で、画素の面積にわたる平均ではありません。カーネルの値の和は1になるように正規化します。カーネルの外に届く光は捨てるため、正規化によってカーネルの値がその分だけ大きくなります。
|
||||
|
||||
点像分布関数とカーネルは、「利得」と「適用量」以外のどれかの項目が変わったフレームでだけ、CPUで作り直します。
|
||||
点像分布関数とカーネルと、カーネルを高速フーリエ変換したスペクトルは、「利得」と「適用量」以外のどれかの項目が変わったフレームでだけ、CPUで作り直します。
|
||||
|
||||
### 2. 光学系の項目とにじみの大きさ
|
||||
|
||||
@@ -97,13 +107,17 @@ YukkuriMovieMaker4(YMM4)上で動作する、素材を回折も収差もな
|
||||
|
||||
「画素ピッチ」は、撮像面での1画素の間隔です。小さいほど、同じ広がりが多くの画素にまたがります。にじみの大きさは素材の画素を単位に決まるため、画素数の多い素材ほど、映像の全体に対するにじみは小さく見えます。
|
||||
|
||||
「カーネル半径」は、カーネルの正方形が中心から上下左右に何画素まで広がるかを決めます。設定できるのは1〜63画素で、デフォルトは15画素です。点像分布関数がカーネルの正方形の外まで広がる設定では、外側の輪やにじみが切り取られます。デフォルトの光学系でデフォーカスを1 wavesにすると、にじみは中心から約15画素まで広がります。デフォーカスを大きくするときは、カーネル半径を上げてください。点像分布関数を求める範囲より外のカーネルの画素は0になるので、範囲を広げるには品質も上げてください。範囲は「品質の選択」にあります。カーネル半径と品質を上げるほど、計算は重くなります。
|
||||
「カーネル半径」は、カーネルの正方形が中心から上下左右に何画素まで広がるかを決めます。設定できるのは1〜63画素で、デフォルトは15画素です。
|
||||
|
||||
点像分布関数がカーネルの正方形の外まで広がる設定では、外側の輪やにじみの端が切り取られます。デフォーカスは、波面収差グループの項目で、焦点の位置のずれを表します。単位のwavesは、波長を1とした量です。デフォルトの光学系でデフォーカスを1 wavesにすると、にじみは中心から約15画素まで広がります。デフォーカスの絶対値を大きくするときは、カーネル半径を上げてください。
|
||||
|
||||
「品質」は、瞳関数を置く格子の大きさを選ぶ項目で、「品質の選択」で説明します。点像分布関数を求める範囲は、「品質」と、波長とF値の積で決まります。カーネルのうち、この範囲の外になる画素は0になります。デフォルトの波長550nmとF値8で、標準の品質のとき、範囲は中心から上下左右に約141μmです。画素ピッチ4μmでは、約35画素です。カーネル半径がこの範囲を超えるときは、品質を上げてください。範囲の大きさは「品質の選択」の表にあります。品質を上げるほど、点像分布関数の計算は重くなります。カーネル半径と計算の重さの関係は、「タイルごとの高速フーリエ変換による畳み込み」にあります。
|
||||
|
||||
### 3. 開口の形と中央遮蔽
|
||||
|
||||
「開口形状」は、円形と正多角形から選びます。正多角形は、カメラの絞りの羽根が作る開口をまねた形で、頂点は円形の開口と同じ直径の円の上にあります。正多角形の開口では、頂点までの距離を開口の半径とします。辺の数は「羽根枚数」で、向きは「開口回転」で決めます。正多角形の開口では、点像分布関数が辺と垂直な向きへ伸びます。デフォーカスでにじみが大きいときは、にじみが開口と辺の数が同じ正多角形の形になります。にじみが切り取られないよう、カーネル半径と品質を上げてください。「羽根枚数」と「開口回転」は、開口形状が正多角形のときだけ働きます。
|
||||
「開口形状」は、円形と正多角形から選びます。正多角形は、カメラの絞りの羽根が作る開口をまねた形で、頂点は円形の開口と同じ直径の円の上にあります。頂点までの距離を開口の半径とします。辺の数は「羽根枚数」で、向きは「開口回転」で決めます。正多角形の開口では、点像分布関数が辺と垂直な向きへ伸びます。デフォーカスでにじみが大きいときは、にじみが、開口と同じ辺の数の正多角形の形になります。にじみが切り取られないよう、カーネル半径と品質を上げてください。「羽根枚数」と「開口回転」は、開口形状が正多角形のときだけ働きます。
|
||||
|
||||
「中央遮蔽」は、反射望遠鏡の副鏡のように開口の中央をふさぐ円の大きさで、開口の半径に対する割合です。値を上げると中心の明るさが下がり、周りの輪へ光が移ります。中央遮蔽は、どちらの開口形状でも円でふさぎます。
|
||||
「中央遮蔽」は、反射望遠鏡の副鏡のように開口の中央をふさぐ円の大きさで、開口の半径に対する割合です。値を上げると中心の明るさが下がり、周りの輪へ光が移ります。中央遮蔽は、どちらの開口形状でも、中央を円でふさぎます。
|
||||
|
||||
### 4. ゼルニケ多項式による波面収差
|
||||
|
||||
@@ -120,30 +134,63 @@ YukkuriMovieMaker4(YMM4)上で動作する、素材を回折も収差もな
|
||||
| 垂直コマ収差 | √8(3ρ³-2ρ)sinθ | 像が垂直方向の片側へ尾を引くずれ |
|
||||
| 球面収差 | √5(6ρ⁴-6ρ²+1) | 開口の中心と縁で焦点の位置が違うずれ |
|
||||
|
||||
### 5. 分離可能な畳み込み
|
||||
### 5. タイルごとの高速フーリエ変換による畳み込み
|
||||
|
||||
本プラグインは、カーネルを何組かの和で近似して畳み込みます。1組は、横方向の1次元の重みと縦方向の1次元の重みの対です。組ごとに横と縦の1次元の畳み込みを行い、足し合わせます。カーネルは一辺が「カーネル半径」の2倍に1を足した画素数の正方形で、カーネル半径が15画素なら31×31画素です。この大きさの畳み込みをそのまま計算すると、1画素ごとに961回の掛け算が要ります。1組の畳み込みは、1画素ごとに横31回と縦31回の掛け算で済むので、組の数が15以下なら掛け算は961回より少なくなります。
|
||||
畳み込む範囲を、一辺T画素の正方形のタイルに分けて畳み込みます。Tは、カーネル半径が23画素以下なら128、24画素以上なら512です。1枚のタイルは、一辺T画素の範囲の素材を読み、高速フーリエ変換で畳み込みます。この畳み込みでは、タイルの縁の近くに、反対側の縁の値が回り込んで混ざります。そのため、タイルの縁からカーネル半径の幅の値は捨て、中央の正方形だけを出力します。この正方形の一辺は、Tからカーネル半径の2倍を引いた画素数です。このようにタイルの縁を捨てて中央だけを使う方法を、オーバーラップセーブ法と呼びます。
|
||||
|
||||
組は特異値分解で求めます。特異値分解は、行列を縦と横の重みの組の和に分け、寄与の大きい順に並べる計算です。組の和と元のカーネルとの差の値の2乗の和が、カーネル全体の値の2乗の和の0.01%以下になるまで組を増やします。組の数の上限は、カーネルの一辺の画素数です。組の和は元のカーネルとわずかに違うため、その値の和も1から少しずれます。そこで、組の和をその値の和で割り、値の和を1にそろえます。そのため、利得が100%のときの畳み込みは、画素の値の総和を保ちます。
|
||||
高速フーリエ変換では、赤と緑、青と不透明度をそれぞれ1つの複素数にまとめ、1回の変換で2つの成分を計算します。
|
||||
|
||||
組の数は点像分布関数の形で決まります。カーネル半径15画素、品質「標準」で23通りの設定を測りました。組の数は、収差がないときは1〜6組、収差を入れると5〜16組でした。組が増えるほど、畳み込みの計算は重くなります。
|
||||
GPUの経路の畳み込みの計算量は、カーネルの形によらず、畳み込む範囲の大きさとカーネル半径で決まります。収差を入れても、畳み込みの計算は重くなりません。ただし、収差を変えるたびに、点像分布関数とカーネルのスペクトルを作り直す時間がかかります。CPUの経路は、全く透明な行と、全く透明なタイルの計算を省くので、素材の中身によっても時間が変わります。
|
||||
|
||||
計算時間は、試験用に作った1920×1080の画像を使い、Intel Iris Xe Graphicsで測りました。素材が変わって畳み込みを計算し直すフレームの時間は、次のとおりでした。
|
||||
Tが同じなら、カーネル半径を上げるほど、1枚のタイルが出力できる範囲は狭まります。そのため、必要なタイルの枚数は減らず、増えることがあります。枚数が増えるほど、計算は重くなります。カーネル半径が24画素以上になるとTが512に変わり、出力できる範囲が広がります。このため、畳み込む範囲が大きい素材では、GPUの経路で、カーネル半径が31画素のときの時間が、15画素のときとほぼ同じになります。畳み込む範囲が小さい素材では、24画素以上にするとかえって重くなることがありますが、この場合の実測値は表にありません。畳み込む範囲が大きい素材の実測値は、次の計算時間の表にあります。
|
||||
|
||||
| カーネル半径 | 品質 | 収差 | 組の数 | 時間 |
|
||||
|---:|---|---|---:|---:|
|
||||
| 15画素 | 標準 | なし | 3 | 約11ミリ秒 |
|
||||
| 15画素 | 標準 | デフォーカス1 waves | 11 | 約34ミリ秒 |
|
||||
| 15画素 | 標準 | 水平コマ収差1 waves | 16 | 約57ミリ秒 |
|
||||
| 63画素 | 高精度 | デフォーカス2 waves | 19 | 約190ミリ秒 |
|
||||
| 63画素 | 高精度 | 水平コマ収差2 waves | 35 | 約360ミリ秒 |
|
||||
計算時間は、試験用に作った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画素です。画面全体が透明でない映像では、畳み込む範囲がこれより広くなるので、時間は表より長くなります。
|
||||
|
||||
素材と設定が変わらず、畳み込みを再利用するフレームでは約1ミリ秒でした。
|
||||
測定は3回行いました。1回の測定では、表の行ごとに12フレームを計算し、フレームごとの時間を短い順に並べて、7番目の値を求めました。この値は、12フレームの中央に近い値です。表には、3回の測定で得た3つの値の、最小値から最大値までを示します。品質はどの行も標準で、ほかの項目はデフォルトです。ただし、カーネル半径31画素と63画素の行は、デフォーカス2 waves、水平コマ収差1 wavesにしています。「変えたもの」の列は、1フレームごとに値を入れ替えた項目です。入れ替えた値は、次のとおりです。
|
||||
|
||||
- 素材: 元の画像と、その左右を反転した画像
|
||||
- デフォーカス: 0と0.1 waves
|
||||
- 利得: 100%と150%
|
||||
|
||||
表の時間は、素材が変わったかどうかの判定と、畳み込みの計算を合わせた値です。デフォーカスの行は、点像分布関数とカーネルのスペクトルをCPUで求める時間と、GPUへ送る時間も含みます。利得の行は、保存した値に利得を掛け直す時間です。保存した値は、「利得と適用量」の節で説明しています。GPUの経路の時間に含まないものは、2つあります。1つは、畳み込みを計算し直すたびの検査で、値を読み戻して比べる時間です。もう1つは、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ミリ秒 |
|
||||
|
||||
素材と設定が変わらず、畳み込みを再利用するフレームでは、GPUの経路で1.4〜1.9ミリ秒でした。この時間は、素材が変わったかどうかの判定の時間です。
|
||||
|
||||
高速フーリエ変換による畳み込みは、画素の値にカーネルの重みを掛けて直接足し合わせる畳み込みと、同じ結果になるはずの計算です。32ビットの浮動小数点数で計算するため、値の丸めによる誤差が生じます。誤差の上限は、タイルの一辺Tごとに導いてあります。導出の全文は、このリポジトリの畳み込みのライブラリ[SpectralConvolution](SpectralConvolution/README.md)の説明にあります。タイルの全画素が不透明な白という最悪の場合について、誤差の上限を、8ビットの値の1階調分を単位にして示します。小数第2位まで切り上げた値です。
|
||||
|
||||
| T | GPUの経路(階調) | CPUの経路(階調) |
|
||||
|---:|---:|---:|
|
||||
| 128 | 0.69 | 0.39 |
|
||||
| 512 | 3.52 | 1.97 |
|
||||
|
||||
表の値は、8ビットに丸める前の出力の誤差の上限で、8ビットに丸めるときの誤差を含みません。利得は100%としています。実際の素材の誤差は、利得が100%のとき、表の値以下になります。
|
||||
|
||||
利得を掛けた値の誤差の上限は、掛ける前の上限に利得を掛けた値です。利得の最大値は400%で、このときのGPUの経路の上限は、表の値のほぼ4倍です。Tが128なら約2.8階調、512なら約14階調です。この上限には、利得を掛けるときの浮動小数点数の丸めと、8ビットに丸めるときの誤差を含みません。
|
||||
|
||||
誤差も利得に比例して大きくなるので、実際の素材の誤差が上限を超えないことを、最大の利得400%で確かめました。192×160の画像の中央の72×60画素に、画素を約6割の確率で置いた素材を作りました。置いた画素の不透明度は64〜255で、色の成分は0から不透明度までの、乱数で決めた値です。この素材を、利得400%で、次の5通りの設定で畳み込みました。
|
||||
|
||||
- デフォルトの設定
|
||||
- 中央遮蔽を50%にした設定
|
||||
- F値を4にした設定
|
||||
- デフォーカスを1 wavesにした設定
|
||||
- カーネル半径を40画素にして、デフォーカスを2 wavesにした設定
|
||||
|
||||
品質はどれも標準です。この5通りの畳み込みは、リポジトリに含めていない試験で行い、GPUの経路の出力を、倍精度で直接足し合わせた値と比べました。倍精度は、64ビットの浮動小数点数による計算で、GPUで使う32ビットの計算より誤差が小さくなります。比べる値は、どちらも利得を掛けて、色と不透明度の各成分が表せる最大の値で打ち切った後の値です。この打ち切りは「利得と適用量」の節で説明しています。打ち切られた画素では、2つの値が同じ値になるので、誤差を確かめられません。そのほかの画素の差は、どの設定でも0.51階調以下で、利得400%の上限より小さい値でした。この差には、8ビットに丸める分の0.5階調を含みます。
|
||||
|
||||
### 6. 利得と適用量
|
||||
|
||||
「利得」は、畳み込んだ結果に掛ける倍率です。100%で画素の値の総和を保ち、上げるほど明るく、下げるほど暗くなります。利得を掛けた結果は、色と不透明度の各成分が表せる最大の値で打ち切り、さらに色の成分が不透明度を超えないように抑えます。
|
||||
|
||||
利得だけを変えたときは、最初の1回だけ畳み込みを計算し直し、利得を掛ける前の結果を保存します。2回目からは、保存した値に利得を掛け直します。
|
||||
|
||||
「適用量」は、入力映像と、利得を掛けた結果を混ぜる割合です。0%では入力を変更せず、100%では利得を掛けた結果だけを出力します。
|
||||
|
||||
### 7. 品質の選択
|
||||
@@ -160,9 +207,52 @@ YukkuriMovieMaker4(YMM4)上で動作する、素材を回折も収差もな
|
||||
|
||||
表の範囲は波長550nm、F値8のときの値で、波長とF値の積に比例します。
|
||||
|
||||
格子が粗いと、大きな波面収差で位相が急に変わる所を表しきれず、点像分布関数の形が崩れます。水平コマ収差を2 wavesにし、品質ごとに求めたカーネルを、格子が2048×2048のときのカーネルと比べました。ほかの項目はデフォルトです。カーネルの各画素の値の差の絶対値を全画素で足すと、高速で約0.87、標準で約0.38、高精度で約0.03でした。カーネルの値の和は1です。波面収差を大きくするときは、品質を上げてください。
|
||||
格子が粗いと、大きな波面収差で位相が急に変わる所を表しきれず、点像分布関数の形が崩れます。水平コマ収差を2 wavesにし、品質ごとに求めたカーネルを、格子が2048×2048のときのカーネルと比べました。ほかの項目はデフォルトです。カーネルの各画素の値の差の絶対値を全画素で足すと、高速で約0.87、標準で約0.38、高精度で約0.03でした。カーネルの値の和は1です。波面収差の絶対値を大きくするときは、品質を上げてください。
|
||||
|
||||
品質を上げると、点像分布関数の計算が重くなります。「利得」と「適用量」以外の項目をアニメーションで変えるときは、フレームごとに点像分布関数を計算し直すので、品質を下げると処理が軽くなります。
|
||||
品質を上げると、点像分布関数の計算が重くなります。「利得」と「適用量」以外の項目をアニメーションで変えるときは、フレームごとに点像分布関数を計算し直すので、品質を下げると処理が軽くなります。ただし、開口形状が円形のときは、「羽根枚数」と「開口回転」を変えても、計算し直しません。
|
||||
|
||||
### 8. GPUの計算の検査とCPUの経路
|
||||
|
||||
GPUの計算は、ドライバーやハードウェアの不具合で誤った値を返すことがあります。以下では、Windowsが認識しているGPUと、GPUの命令をCPUで実行するソフトウェアを、まとめてアダプターと呼びます。後者をソフトウェア アダプターと呼び、Microsoft Basic Render Driverがこれに当たります。本プラグインは、アダプターが正しく計算できるかを、自己試験と検査で確かめます。自己試験は、決まった入力を計算させて、答えを確かめる処理です。検査は、素材を畳み込んだ結果を確かめる処理です。どちらの詳細も、この節の後半にあります。
|
||||
|
||||
自己試験か検査で不合格になったこと、GPUのデバイスが失われたこと、GPUの経路で想定していない例外が起きたことを、GPUの異常と呼びます。GPUのデバイスが失われたとは、GPUが突然使えなくなったことです。メモリを確保できなかったことは、GPUのメモリでもシステムメモリでも、GPUの異常に含めません。自己試験の最中にメモリを確保できなかったときだけは、自己試験の不合格として扱い、GPUの異常に含めます。
|
||||
|
||||
アダプターの容量は、CPUとGPUが同じメモリを使う構成では共有のシステムメモリの大きさ、それ以外では専用のビデオメモリの大きさです。必要なGPUメモリは、素材の大きさとカーネル半径から見積もります。本プラグインは、次の表の条件を上から順に調べ、計算する経路を決めます。条件1は、エフェクトを最初に使うときに1回だけ調べ、条件2以下はフレームごとに調べます。
|
||||
|
||||
| 順 | 条件 | 経路 |
|
||||
|---|---|---|
|
||||
| 1 | Direct3D 12デバイスを取得できない、YMM4のDirect3D 11デバイスが相互運用に必要なインターフェースを持たない、Direct3D 11・12間の共有の準備に失敗した、またはGPUで計算するための準備に失敗した | CPU |
|
||||
| 2 | 以前のフレームで、GPUの異常が起きたか、GPUの経路でメモリを確保できなかったため、YMM4の起動中はCPUで計算すると決めてある | CPU |
|
||||
| 3 | YMM4が使うアダプターがソフトウェア アダプター | CPU |
|
||||
| 4 | 必要なGPUメモリが、アダプターの容量の4分の1を超える | CPU |
|
||||
| 5 | このフレームで行った自己試験に不合格だった | CPU |
|
||||
| 6 | 1〜5のどれにも該当しない | GPU |
|
||||
|
||||
ソフトウェア アダプターでは、CPUの経路のほうが速いので、CPUで計算します。素材が大きいと、必要なGPUメモリが容量の4分の1を超えて、CPUの経路になることがあります。
|
||||
|
||||
自己試験は、YMM4を起動するたびに、表の1〜4のどれにも該当しない最初のフレームで、アダプターごとに1回行います。自己試験では、決まったカーネルを使い、決まった模様をGPUで畳み込み、倍精度で計算した値と比べます。同じ計算を2回行い、結果が1ビットも違わないことも確かめます。Intel Iris Xe Graphicsでは、自己試験に0.7〜0.8秒かかりました。
|
||||
|
||||
GPUの経路で畳み込みを計算し直したフレームでは、出力を画面に出す前に、次の検査を行います。NaNは、計算の失敗で生じる、数として扱えない値です。
|
||||
|
||||
| 検査 | 内容 |
|
||||
|---|---|
|
||||
| NaNと無限大 | 利得を掛ける前のタイルの値に、NaNか無限大が1つでもあれば不合格。捨てる縁の値も数える |
|
||||
| 総和 | 色と不透明度のそれぞれで、利得を掛ける前の出力の総和を素材の総和と比べる |
|
||||
| 抜き取り | 利得を掛ける前の出力の16か所の値を、倍精度で直接足し合わせた値と比べる |
|
||||
|
||||
検査では、GPUの結果から求めた値を、測定値と呼びます。参照値は、測定値と比べる値で、素材の値から求めた値か、0のように初めから分かっている値です。許容値は、測定値と参照値の差として許す最大の値です。測定値と参照値の差が許容値以下なら合格とします。総和と抜き取りの許容値は、どちらも丸めの誤差の上限から導いた値で、実際に測った誤差に合わせて広げてはいません。抜き取る16か所のうち、畳み込む範囲の四隅と中央の5か所は固定で、残りの11か所は素材から決まります。そのため、同じ素材と同じ設定では毎回同じ位置になります。
|
||||
|
||||
GPUの異常が起きたときは、そのフレームをCPUの経路で計算し直します。異常を起こしたアダプターでは、YMM4を終了するまでCPUの経路で計算し、共有テクスチャやタイルの作業領域など、GPUの資源を解放します。
|
||||
|
||||
GPUの異常の内容は、ほかのプラグインと共通のライブラリである[YMM4-Telemetry](https://github.com/routersys/YMM4-Telemetry)で、開発者へ自動で送信します。送信は、YMM4の起動中にアダプターごとに1回だけです。送信する内容と、送信する報告の数の上限は、「不具合の報告」にあります。
|
||||
|
||||
GPUの経路でメモリを確保できなかったときは、YMM4を終了するまでCPUの経路で計算しますが、送信しません。自己試験の最中に確保できなかったときだけは、自己試験の不合格として送信します。
|
||||
|
||||
CPUの経路は、論理プロセッサの数までのスレッドで計算します。畳み込むときに、1つのスレッドは、タイル1枚分の作業領域を使います。同時に動かすスレッドは、タイルの作業領域の合計が64MBを超えない数に抑えます。Tが512のときは16スレッドまでです。
|
||||
|
||||
GPUの経路とCPUの経路の出力は、1ビット単位では一致しません。差は、開発で使う検証用のプログラムで確かめました。このプログラムを、ハーネスと呼びます。ハーネスは、リポジトリの`WaveOptics.Harness`にあります。ハーネスが合成した640×480の画像に、設定とフレームを変えてエフェクトを適用すると、2つの経路の出力の差は、測った範囲では最大2階調でした。この差には、2つの経路が8ビットに丸める分の、最大1階調を含みます。
|
||||
|
||||
[YMM4-ComputeGuard](https://github.com/routersys/YMM4-ComputeGuard)は、計算の経路を選び、検査の合否を判定します。[SpectralConvolution](SpectralConvolution/README.md)は、このリポジトリのフォルダーにあるライブラリで、畳み込みを計算します。YMM4-ComputeGuardは、サブモジュールとして取り込んでいます。
|
||||
|
||||
---
|
||||
|
||||
@@ -182,7 +272,7 @@ YukkuriMovieMaker4(YMM4)上で動作する、素材を回折も収差もな
|
||||
| 波長 | 数値 | 550nm | 380〜780nm | 対応 | 単色光として計算する真空中の波長です。 |
|
||||
| F値 | 数値 | 8 | 0.5〜32 | 対応 | 開口の直径に対する焦点距離の比です。直接入力では64まで指定できます。 |
|
||||
| 画素ピッチ | 数値 | 4μm | 0.5〜20μm | 対応 | 撮像面での1画素の間隔です。直接入力では0.25〜100μmを指定できます。 |
|
||||
| カーネル半径 | 整数 | 15px | 1〜63px | 非対応 | カーネルが中心から上下左右に広がる画素数です。カーネルの外に届く光は捨てます。 |
|
||||
| カーネル半径 | 整数 | 15画素 | 1〜63画素 | 非対応 | カーネルが中心から上下左右に広がる画素数です。カーネルの外に届く光は捨てます。 |
|
||||
| 品質 | 列挙 | 標準 | 高速 / 標準 / 高精度 | 非対応 | 瞳関数を置く格子の大きさを選択します。 |
|
||||
|
||||
### 開口グループ
|
||||
@@ -205,41 +295,45 @@ YukkuriMovieMaker4(YMM4)上で動作する、素材を回折も収差もな
|
||||
| 垂直コマ収差 | 数値 | 0 waves | -3〜3 waves | 対応 | 像が垂直方向の片側へ尾を引くずれの係数です。 |
|
||||
| 球面収差 | 数値 | 0 waves | -3〜3 waves | 対応 | 開口の中心と縁で焦点の位置が違うずれの係数です。 |
|
||||
|
||||
波面収差グループの6項目は、どれも直接入力では-10〜10 wavesまで指定できます。
|
||||
波面収差グループの6項目は、どれも直接入力では-10〜10 wavesの範囲で指定できます。
|
||||
|
||||
---
|
||||
|
||||
## 制限事項
|
||||
|
||||
- AviUtl向けのEXO出力には対応していません。
|
||||
- Direct3D 12デバイスを取得できない場合と、YMM4が使うDirect3D 11デバイスが相互運用に必要なインターフェースを持たない場合は、エフェクトを適用せず入力映像を表示します。GPUメモリが足りず共有テクスチャを確保できない場合も同じです。
|
||||
- 畳み込みには現在のフレームの色と不透明度だけを使用します。履歴フレーム、外部画像、学習済みモデルは使用しません。素材に透明でない画素が無いときは、エフェクトを適用せず入力映像を表示します。
|
||||
- Direct3D 12デバイスを取得できない場合と、YMM4が使うDirect3D 11デバイスが相互運用に必要なインターフェースを持たない場合は、CPUの経路で計算します。Direct3D 11・12間の共有の準備に失敗した場合と、GPUで計算するための準備に失敗した場合も、CPUの経路で計算します。YMM4が使うアダプターがソフトウェア アダプターの場合と、必要なGPUメモリがアダプターの容量の4分の1を超える場合も同様です。ソフトウェア アダプターではないGPUを使える環境では、CPUの経路のほうが、一般に計算が遅くなります。
|
||||
- GPUの結果の検査で見つけられるのは、NaNと無限大、総和、16か所の抜き取りに表れた誤りだけです。利得だけを変えたフレームで、保存した値にGPUで利得を掛け直す計算は、検査しません。
|
||||
- GPUの異常が起きたアダプターと、GPUの経路でメモリを確保できなかったアダプターは、原因が一時的な不具合でも、YMM4を終了するまでCPUの経路で計算します。このとき、共有テクスチャやタイルの作業領域など、GPUの資源は解放します。
|
||||
- 畳み込みには現在のフレームの色と不透明度だけを使用します。履歴フレーム、外部画像、学習済みモデルは使用しません。素材のすべての画素が透明なときは、エフェクトを適用せず入力映像を表示します。
|
||||
- 計算は単色のフラウンホーファー回折に限ります。白色光のように波長の混ざった光は扱いません。点像分布関数は画面のどこでも同じで、像の位置や素材の奥行きで変わるにじみは扱いません。
|
||||
- 畳み込みは、画素の値をそのまま重み付けして足し合わせます。画素の値を光の強さに比例する値へ直してから畳み込む処理はしません。
|
||||
- カーネル半径は1〜63画素です。
|
||||
- 中央遮蔽で開口をほとんどふさぎ、瞳関数の格子に光の通る標本が1つも無くなる設定では、エフェクトを適用せず入力映像を表示します。品質を上げると起きにくくなります。
|
||||
- 計算領域は、透明な部分も含む素材全体の矩形の上下左右に余白を加えた大きさで、長辺は8192画素が上限です。余白は、カーネル半径を4画素単位に切り上げた画素数で、16画素を下回りません。素材の長辺の上限は、8192画素から余白の2倍を引いた値です。カーネル半径が16画素以下なら8160画素、63画素なら8064画素になります。素材の長辺がこの上限を超える場合は、エフェクトを適用せず入力映像を表示します。
|
||||
- GPUメモリ使用量は、計算領域の大きさに応じて増えます。作業用のバッファーとして、計算領域の1画素につき32バイトをGPUに確保します。処理量は、素材全体の大きさと畳み込む範囲の大きさに応じて増えます。
|
||||
- エフェクト1つあたり、GPUの経路では、2つの共有テクスチャをGPUに確保します。素材を入れる共有テクスチャは、素材の1画素につき4バイトです。結果を入れる共有テクスチャは、畳み込む範囲の1画素につき4バイトです。結果を入れる共有テクスチャは、畳み込む範囲が入りきらなくなったときだけ、そのときの範囲の大きさで作り直します。
|
||||
- GPUの経路では、共有テクスチャのほかに、16MB以下のタイルの作業領域、カーネルのスペクトル、検査に使う値を書くバッファーを確保します。スペクトルは、Tが128なら128KB、512なら2MBです。検査に使う値を書くバッファーは、畳み込む範囲の大きさとカーネル半径に応じて増えます。利得だけを変えたフレームの後は、畳み込む範囲の1画素につき16バイトを追加で確保します。この領域は、「注意事項」のキャッシュの項目にある、保存した値のためのものです。
|
||||
- エフェクト1つあたり、CPUの経路では、素材の画素の配列、出力の画素の配列、作業スレッドの作業領域をシステムメモリに確保します。作業領域のうち、タイルの分は合計で64MB以下です。素材を読むためのDirect2Dのビットマップは2枚あり、どちらも素材の大きさです。出力を書くためのDirect2Dのビットマップは、畳み込む範囲を収められる大きさで、収まらなくなったときだけ作り直します。利得だけを変えたフレームの後は、畳み込む範囲の1画素につき16バイトを追加で確保します。
|
||||
|
||||
---
|
||||
|
||||
## 注意事項
|
||||
|
||||
- 処理負荷: 収差を入れると、畳み込みに使う組の数が増えて計算が重くなります。カーネル半径を上げた場合は、1組あたりの畳み込みの計算量と、組を求める特異値分解の計算量が増えます。品質を上げた場合は、点像分布関数の計算量が増えます。畳み込みの時間の目安は「分離可能な畳み込み」にあります。
|
||||
- 品質と収差: 波面収差を大きくするときは、品質を上げてください。格子が粗いと点像分布関数の形が崩れます。崩れ方の目安は「品質の選択」にあります。
|
||||
- キャッシュ: 素材の大きさと色と不透明度が変わらず、「利得」と「適用量」以外の項目も変わらないフレームでは、畳み込みの計算を再利用します。利得だけを変えたフレームでは、再利用した畳み込みに利得を掛け直します。適用量だけを変えたフレームでは、混ぜる割合だけを変えます。動画や口パクのように素材の内容が変わるフレームと、「利得」と「適用量」以外の項目をアニメーションで変えたフレームでは、毎回計算し直すので処理が重くなります。素材が変わったかどうかを調べる計算は、再利用するフレームでも毎フレーム行います。
|
||||
- 処理負荷: 畳み込む範囲が大きいほど、計算は重くなります。カーネル半径を上げたときの重さの変わり方は、「タイルごとの高速フーリエ変換による畳み込み」にあります。品質を上げた場合は、点像分布関数の計算量が増えます。収差を入れても、畳み込みの計算量は変わりません。ソフトウェア アダプターではないGPUを使える環境では、CPUの経路のほうが、一般に計算が遅くなります。
|
||||
- 品質と収差: 波面収差の絶対値を大きくするときは、品質を上げてください。格子が粗いと点像分布関数の形が崩れます。崩れ方の目安は「品質の選択」にあります。
|
||||
- キャッシュ: 素材の大きさと色と不透明度が変わらず、「利得」と「適用量」以外の項目も変わらないフレームでは、畳み込みの計算を再利用します。利得だけを変えたフレームでは、最初の1回だけ畳み込みを計算し直し、利得を掛ける前の値を保存します。2回目からは、保存した値に利得を掛け直します。素材か、「利得」と「適用量」以外の項目が変わると、保存した値を破棄します。適用量だけを変えたフレームでは、混ぜる割合だけを変えます。動画や口パクのように素材の内容が変わるフレームと、「利得」と「適用量」以外の項目をアニメーションで変えたフレームでは、毎回計算し直すので処理が重くなります。素材が変わったかどうかを調べる計算は、再利用するフレームでも毎フレーム行います。開口形状が円形のときは、「羽根枚数」と「開口回転」を変えても、計算し直しません。
|
||||
- 適用量0%: 適用量が0%のときは入力を変更せず、畳み込みの計算も行いません。
|
||||
- 再現性: 計算は決定論的で、時間値や乱数を使用しません。同じGPUとドライバーでは、同じ素材と同じ設定から常に同じ結果になります。
|
||||
- 再現性: 計算は決定論的で、時間値や乱数を使用しません。同じ素材と同じ設定から常に同じ結果になるのは、同じ経路で、GPU、ドライバー、CPU、Windows、.NETの組が同じときです。GPUの経路でも結果にCPUが関わるのは、点像分布関数とカーネルのスペクトルをCPUで求めるためです。GPUの経路とCPUの経路では、結果がわずかに違います。GPUの異常でCPUの経路に切り替わったときも、同じ設定で結果がわずかに変わります。
|
||||
- 透明部分: 畳み込みは不透明度にも掛かるので、素材の縁の外にも半透明のにじみが広がります。出力の範囲は、素材の範囲と畳み込む範囲を合わせたものです。適用量が0%のときは、素材の範囲のままです。
|
||||
- 更新通知: エフェクトを最初に生成したときに、YMM4の実行中に一度だけ新しい正式版を確認します。更新情報を取得できない場合は通知せず、そのまま動作します。プレリリースは通知の対象に含めません。
|
||||
- 不具合の自動送信: 想定していない例外が起きたときは、その内容を開発者へ自動で送信します。内容は「不具合の報告」に書いています。
|
||||
- 不具合の自動送信: 想定していない例外が起きたときと、GPUの異常でCPUの経路に切り替えたときは、その内容を開発者へ自動で送信します。内容は「不具合の報告」に書いています。
|
||||
- 本プラグインを使用する前に、YMM4のプロジェクトファイルのバックアップを作成することを推奨します。
|
||||
|
||||
---
|
||||
|
||||
## 不具合の報告
|
||||
|
||||
本プラグインは、想定していない例外が起きたときに、その内容を開発者へ自動で送信します。同意は求めず、常に送信します。
|
||||
本プラグインは、想定していない例外が起きたときと、GPUの異常でCPUの経路に切り替えたときに、その内容を開発者へ自動で送信します。同意は求めず、常に送信します。
|
||||
|
||||
送信する情報は次のとおりです。
|
||||
|
||||
@@ -250,23 +344,39 @@ YukkuriMovieMaker4(YMM4)上で動作する、素材を回折も収差もな
|
||||
| プラグイン | アセンブリ名、バージョン |
|
||||
| 実行環境 | OSの名前とバージョン、.NETのバージョン、CPUのアーキテクチャ、論理プロセッサ数 |
|
||||
| 識別子 | YMM4の起動ごとに決まるセッション識別子、報告ごとの識別子 |
|
||||
| GPUの異常のとき | 切り替えた理由、不合格になった検査の名前と測定値と参照値と許容値、アダプターの名前、ベンダーIDとデバイスIDとサブシステムIDとリビジョン、ドライバーのバージョン、ソフトウェア アダプターかどうか、計算領域の幅と高さ、必要なGPUメモリの見積もり |
|
||||
|
||||
メッセージとファイル名は、送信の前に置き換えを通します。置き換えるのは、Windowsのユーザー名、ユーザーフォルダー、AppDataのパス、マシン名、ドメイン名、メールアドレス、IPv4アドレスです。送信元のIPアドレスは受信側へ渡す手前で取り除いています。
|
||||
|
||||
映像の中身とプロジェクトの内容は送信しません。継続して個人を追跡する識別子も持ちません。セッション識別子はYMM4を起動し直すと別の値になります。
|
||||
|
||||
送信するのは想定していない例外だけです。YMM4が本プラグインのエフェクトを作るとき、フレームごとに更新するとき、入力をつなぎ直すとき、破棄するときと、Direct2Dがシェーダーの定数を書き込むときに起きた例外を報告し、その後はYMM4へそのまま渡します。更新の確認では、更新情報の取得と比較で起きた例外は報告しません。通知の文を組み立てて表示するときに起きた例外は報告し、YMM4へは渡しません。画面の操作やバックグラウンドの処理で未処理になった例外も報告しますが、本プラグインのコードが関わる例外に限ります。本プラグインの外で起きた例外は送信しません。
|
||||
送信するのは、想定していない例外と、GPUの異常でCPUの経路に切り替えたことだけです。GPUの異常は、「GPUの計算の検査とCPUの経路」で説明しています。YMM4が本プラグインのエフェクトを作るとき、フレームごとに更新するとき、入力をつなぎ直すとき、破棄するときと、Direct2Dがシェーダーの定数を書き込むときに起きた例外を報告し、その後はYMM4へそのまま渡します。ただし、GPUの経路の計算中に起きた例外は、YMM4へは渡さず、そのフレームをCPUの経路で計算し直します。この例外は、GPUの異常として報告しますが、メモリを確保できなかったものは報告しません。自己試験の最中に確保できなかったときだけは、自己試験の不合格として報告します。GPUの異常の報告は、YMM4の起動中にアダプターごとに1回だけです。
|
||||
|
||||
更新の確認では、更新情報の取得と比較で起きた例外は報告しません。通知の文を組み立てて表示するときに起きた例外は報告し、YMM4へは渡しません。画面の操作やバックグラウンドの処理で未処理になった例外も報告しますが、本プラグインのコードが関わる例外に限ります。本プラグインの外で起きた例外は送信しません。
|
||||
|
||||
次の失敗は送信しません。
|
||||
|
||||
| 種類 | 例 |
|
||||
|---|---|
|
||||
| 効果をかけないだけで済ませるもの | Direct3D 12デバイスを取得できない、YMM4のDirect3D 11デバイスが相互運用に必要なインターフェースを持たない、GPUメモリが足りず共有テクスチャを確保できない、計算領域が8192画素に収まらない、開口に光の通る標本が無いときに、エフェクトを適用せず入力映像を表示したとき |
|
||||
| CPUの経路で計算するだけで済ませるもの | Direct3D 12デバイスを取得できない、YMM4のDirect3D 11デバイスが相互運用に必要なインターフェースを持たない、Direct3D 11・12間の共有の準備に失敗した、GPUで計算するための準備に失敗した、アダプターがソフトウェア アダプターである、必要なGPUメモリが容量の4分の1を超える、GPUの経路でメモリを確保できない。ただし、自己試験の最中にメモリを確保できなかったときは送信する |
|
||||
| 効果をかけないだけで済ませるもの | 計算領域が8192画素に収まらないか、開口に光の通る標本が無くて、エフェクトを適用せず入力映像を表示したとき |
|
||||
| 更新の確認の通信の失敗 | manjubox.netとGitHubのどちらへも接続できない |
|
||||
|
||||
報告の送信には、ほかのプラグインと共通のライブラリであるYMM4-Telemetryを使います。送信する報告の数には、GPUの異常をアダプターごとに1回だけ報告する制限のほかに、2つの上限があります。
|
||||
|
||||
1つ目の上限は、同じ報告を1回の起動で3件までとするものです。同じ報告とみなすのは、例外の型と、スタックトレースのうち本プラグインの関数を呼び出し順に並べたものが、どちらも一致する場合です。例外が別の例外を原因として持つときは、原因の例外についても、型と本プラグインの関数を比べます。原因の例外を含めて本プラグインの関数が1つも無い報告は、スタックトレースのすべての関数を呼び出し順に並べて比べます。比べる関数は、原因の例外の分も合わせて先頭の20個までです。例外は、原因の例外を含めて5個までたどります。
|
||||
|
||||
原因の例外が無いGPUの異常の報告は、例外の型がどれも同じで、スタックトレースもありません。そのため、切り替えた理由が違っても、同じ報告になります。別のプラグインがYMM4-ComputeGuardを使って報告する、原因の例外が無いGPUの異常の報告も、これと同じ報告です。1つ目の上限の件数は、それらと合わせて数えます。
|
||||
|
||||
2つ目の上限は、新たに送る報告の合計を、1回の起動で20件までとするものです。合計には、この節で説明するすべての報告を数えます。この上限の件数は、YMM4-Telemetryで報告する別のプラグインの報告と合わせて数えます。
|
||||
|
||||
どちらかの上限を超える報告は、送信せずに捨てます。
|
||||
|
||||
送信できなかった報告はYMM4のユーザーフォルダーへ退避します。次にYMM4を起動したあと、本プラグインのエフェクトを生成するか、同じくYMM4-Telemetryで報告する別のプラグインが動き始めると、退避した報告を1回の起動で10件まで送り直します。送信も再送も非同期に行うため、通信を待って起動と描画が遅くなることはありません。
|
||||
|
||||
実装は [YMM4-Telemetry](https://github.com/routersys/YMM4-Telemetry) をサブモジュールとして取り込んでいます。
|
||||
上限を超えて捨てた報告は、退避も再送もしません。再送は、どちらの上限の件数にも入れません。
|
||||
|
||||
実装は [YMM4-Telemetry](https://github.com/routersys/YMM4-Telemetry) をサブモジュールとして取り込んでいます。GPUの異常の報告の内容は[YMM4-ComputeGuard](https://github.com/routersys/YMM4-ComputeGuard)が組み立てます。
|
||||
|
||||
---
|
||||
|
||||
|
||||
@@ -0,0 +1,601 @@
|
||||
# SpectralConvolution for YMM4
|
||||
|
||||
[](#)
|
||||
[](#)
|
||||
|
||||
---
|
||||
|
||||
YMM4 のプラグインが、画像とカーネルの畳み込みを、CPU と GPU で同じ手順で計算するためのライブラリです。
|
||||
画像を正方形のタイルに分け、高速フーリエ変換で畳み込みます。あわせて、その計算の誤差の上限を求める機能も持ちます。
|
||||
計算をどちらで行うかの選択と、GPU の結果の判定は行いません。
|
||||
今は Wave Optics のリポジトリの中に置いています。ほかのプラグインでも使うようになったら、別のリポジトリへ移します。
|
||||
|
||||
---
|
||||
|
||||
## 目次
|
||||
|
||||
1. [概要](#概要)
|
||||
2. [動作要件](#動作要件)
|
||||
3. [導入方法](#導入方法)
|
||||
4. [使い方](#使い方)
|
||||
5. [主な機能](#主な機能)
|
||||
- [1. タイルに分けた畳み込み](#1-タイルに分けた畳み込み)
|
||||
- [2. 2 つのチャンネルをまとめる複素数](#2-2-つのチャンネルをまとめる複素数)
|
||||
- [3. CPU の経路](#3-cpu-の経路)
|
||||
- [4. GPU の経路](#4-gpu-の経路)
|
||||
- [5. 検査の材料と検査](#5-検査の材料と検査)
|
||||
- [6. 自己試験](#6-自己試験)
|
||||
6. [誤差の上限](#誤差の上限)
|
||||
- [前提](#前提)
|
||||
- [記号](#記号)
|
||||
- [1. 回転因子とスペクトル](#1-回転因子とスペクトル)
|
||||
- [2. 変換の 1 段](#2-変換の-1-段)
|
||||
- [3. 2 次元の変換](#3-2-次元の変換)
|
||||
- [4. スペクトルとの掛け算](#4-スペクトルとの掛け算)
|
||||
- [5. 逆変換と 1 タイルの上限](#5-逆変換と-1-タイルの上限)
|
||||
- [6. 0 にされる値](#6-0-にされる値)
|
||||
- [7. 1 画素の上限](#7-1-画素の上限)
|
||||
- [8. 総和の上限](#8-総和の上限)
|
||||
- [9. 参照値の誤差](#9-参照値の誤差)
|
||||
- [10. 式に入れていない誤差と上限の余裕](#10-式に入れていない誤差と上限の余裕)
|
||||
7. [決定論](#決定論)
|
||||
8. [メモリ](#メモリ)
|
||||
9. [動作の上限値](#動作の上限値)
|
||||
10. [制限事項](#制限事項)
|
||||
11. [動作の確認](#動作の確認)
|
||||
12. [免責事項](#免責事項)
|
||||
13. [ライセンス](#ライセンス)
|
||||
|
||||
---
|
||||
|
||||
## 概要
|
||||
|
||||
畳み込みは、元の画像の各画素の値を、周りの画素の値の重み付きの和に置き換える計算です。以下では、元の画像を素材と呼びます。重みを正方形に並べたものをカーネルと呼びます。カーネルの半径を r とすると、正方形の一辺は 2r + 1 画素です。src は素材の値、k はカーネルの値です。d は、縦と横がそれぞれ -r〜r の範囲の 2 次元のずれです。本ライブラリは、出力の画素 p の値を式 (1) で求めます。
|
||||
|
||||
```
|
||||
out(p) = Σ_d src(p + d) × k(d) (1)
|
||||
```
|
||||
|
||||
数学の定義の畳み込みは src(p - d) を使うので、式 (1) とはカーネルの向きが逆です。src(p + d) を使う式 (1) の計算は、数学では相互相関と呼ばれます。本ライブラリでは、この計算を畳み込みと呼びます。型の名前の `DirectCorrelation` は、相互相関を表しています。左右か上下に非対称なカーネルを渡すときは、向きに注意してください。
|
||||
|
||||
本ライブラリが扱うのは、次の 3 つです。
|
||||
|
||||
- 畳み込みを、CPU と GPU で同じ手順で計算すること
|
||||
- その計算の誤差の上限を求めること
|
||||
- GPU の結果を確かめる検査と、自己試験の検査を作ること
|
||||
|
||||
以下では、CPU で計算する道筋を CPU の経路、GPU で計算する道筋を GPU の経路と呼びます。
|
||||
|
||||
検査は、GPU の結果から求めた測定値を参照値と比べ、差が許容値に収まるかを見るものです。検査 1 件は `ConvolutionMeasurement` で表し、名前、測定値、参照値、許容値を持ちます。測定値と参照値の差の絶対値が許容値以下なら合格で、`Passes` が真になります。自己試験は、決まった模様と決まったカーネルを GPU で畳み込み、その結果から検査を作る処理です。
|
||||
|
||||
計算をどちらで行うかの選択、検査の合否による判定、異常の報告は扱いません。Wave Optics では、これらを [YMM4-ComputeGuard](https://github.com/routersys/YMM4-ComputeGuard) が受け持ちます。Wave Optics は、[WaveOpticsCompute.cs](../WaveOptics/Rendering/WaveOpticsCompute.cs) の `ToCheck` で、本ライブラリの `ConvolutionMeasurement` を YMM4-ComputeGuard の `ComputeCheck` に変換し、YMM4-ComputeGuard の判定へ渡します。本ライブラリは YMM4-ComputeGuard を参照しません。
|
||||
|
||||
GPU の計算には、C# で書いた計算シェーダーを Direct3D 12 で動かすライブラリである [ComputeWeave](https://github.com/routersys/ComputeWeave) を使います。
|
||||
|
||||
---
|
||||
|
||||
## 動作要件
|
||||
|
||||
| 項目 | 要件 |
|
||||
|---|---|
|
||||
| 対象フレームワーク | .NET 10.0 |
|
||||
| 対象プラットフォーム | Windows 10 バージョン 2004(ビルド 19041)以降 / Windows 11(64bit) |
|
||||
| 参照するパッケージ | ComputeWeave 2.6.0 |
|
||||
| GPU の経路 | ComputeWeave が使える Direct3D 12 のデバイス |
|
||||
|
||||
CPU の経路は、GPU が無くても使えます。
|
||||
|
||||
---
|
||||
|
||||
## 導入方法
|
||||
|
||||
プラグインのプロジェクトで、`SpectralConvolution.props` を読み込みます。
|
||||
|
||||
```xml
|
||||
<Import Project="..\SpectralConvolution\SpectralConvolution.props" />
|
||||
```
|
||||
|
||||
フォルダーは、次のとおりです。
|
||||
|
||||
```
|
||||
SpectralConvolution/ 外側
|
||||
README.md
|
||||
SpectralConvolution.props
|
||||
SpectralConvolution/ 内側。ソース
|
||||
SpectralConvolution.Tests/ 単体試験
|
||||
```
|
||||
|
||||
`SpectralConvolution.props` が指すのは、内側の `SpectralConvolution` フォルダーです。その中のソースが、プラグインのアセンブリに取り込まれます。現在は、Wave Optics のリポジトリにあります。ほかのプラグインで使うときは、外側の `SpectralConvolution` フォルダーをそのプラグインのリポジトリへコピーし、`Import` のパスを合わせます。プラグインのプロジェクトには、次の設定が要ります。
|
||||
|
||||
| 設定 | 理由 |
|
||||
|---|---|
|
||||
| ComputeWeave 2.6.0 の NuGet パッケージを参照する | GPU のシェーダーと、`Float2` などの型を使うため。シェーダーは、ComputeWeave のソースジェネレーターがプラグインのビルドの中で作る |
|
||||
| `AllowUnsafeBlocks` を `true` にする | ComputeWeave のソースジェネレーターが求めるため |
|
||||
| `ImplicitUsings` を `enable` にする | ソースが `System.Threading` などの名前空間を `using` なしで使うため |
|
||||
| `Nullable` を `enable` にする | ソースが null 許容の注釈を使うため。`disable` にすると警告が出る |
|
||||
|
||||
取り込んだ型はどれも `internal` で、プラグインのアセンブリの外からは見えません。
|
||||
|
||||
---
|
||||
|
||||
## 使い方
|
||||
|
||||
本ライブラリの主な型は、次のとおりです。
|
||||
|
||||
| 型 | 役割 |
|
||||
|---|---|
|
||||
| `TilePlan` | 畳み込む範囲のタイルへの分け方 |
|
||||
| `KernelSpectrum` | 和を 1 にそろえたカーネルと、タイルの大きさに合わせた回転因子とスペクトル |
|
||||
| `CpuTileConvolver` | CPU の経路の畳み込み |
|
||||
| `GpuTileConvolver` | GPU の経路の資源と、ComputeWeave のコンテキストへの記録 |
|
||||
| `GpuTileJob` | GPU の経路の 1 回分の畳み込みの設定。`GpuTileConvolver.Prepare` が返す |
|
||||
| `GpuTileCheck` | GPU が書き出した値から作る検査 |
|
||||
| `ConvolutionMeasurement` | 検査 1 件 |
|
||||
| `SpectralSelfTest` | 決まった模様と決まったカーネルで GPU を確かめる自己試験 |
|
||||
| `ConvolutionBound` | 誤差の上限 |
|
||||
| `DirectCorrelation` | 式 (1) を倍精度でそのまま足し合わせる計算。検査の参照値に使う |
|
||||
| `TileInput` | タイルが読む素材の 2 ノルム。8 ビットの値を 255 で割った値で求める |
|
||||
| `FastFourierTransform` | 倍精度の高速フーリエ変換。カーネルのスペクトルに使う |
|
||||
|
||||
表の 2 ノルムは、素材の 8 ビットの値を 255 で割った値の 2 乗の和の平方根です。赤と緑、青と不透明度の 2 組ごとに求めます。スペクトルは、カーネルを高速フーリエ変換した値です。回転因子とスペクトルは、[タイルに分けた畳み込み](#1-タイルに分けた畳み込み)で説明します。
|
||||
|
||||
カーネルのスペクトルは、カーネルの値か半径、タイルの一辺 T が変わったときだけ作り直します。
|
||||
|
||||
```csharp
|
||||
var spectrum = new KernelSpectrum();
|
||||
spectrum.Update(kernel, radius, TilePlan.SelectSize(radius));
|
||||
var plan = TilePlan.Create(radius, regionX, regionY, regionWidth, regionHeight);
|
||||
```
|
||||
|
||||
`kernel` は、一辺 2r + 1 の正方形を行ごとに並べた `double` の配列です。`radius` は、カーネルの半径 r です。`kernel` の値は 0 以上の有限の数で、値の和は 0 より大きくなければなりません。`KernelSpectrum` は、値を和で割ってから使います。
|
||||
|
||||
畳み込む範囲は、出力を求める矩形です。`regionX` と `regionY` はその左上の座標で、`regionWidth` と `regionHeight` は幅と高さです。座標系は呼び出し側が決めます。CPU の経路の出力の配列と、GPU の経路の出力のテクスチャは、この範囲の大きさにします。範囲は、0 でない素材の画素を囲む矩形を、上下左右に少なくとも r 画素ずつ広げたものにしてください。これより狭いと、総和の検査が正常な GPU でも不合格になることがあります。詳しくは[検査の材料と検査](#5-検査の材料と検査)にあります。素材の外は 0 として扱うので、範囲は素材の外へはみ出してかまいません。
|
||||
|
||||
CPU の経路では、BGRA の順に並んだ 8 ビットの素材から、BGRA の 8 ビットの出力を作ります。
|
||||
|
||||
```csharp
|
||||
using var cpu = new CpuTileConvolver();
|
||||
cpu.Convolve(source, sourceX, sourceY, sourceWidth, sourceHeight, spectrum, plan, output, gain, null);
|
||||
```
|
||||
|
||||
`sourceX` と `sourceY` は素材の左上の座標で、畳み込む範囲と同じ座標系で渡します。`sourceWidth` と `sourceHeight` は素材の幅と高さです。`source` と `output` は `byte[]` で、画素を行ごとに隙間なく並べます。長さは、画素数 × 4 バイト以上です。出力は畳み込む範囲の大きさで、左上が範囲の左上に当たります。`gain` は出力に掛ける倍率で、以下ではゲインと呼びます。Wave Optics の「利得」に当たります。最後の引数 `null` は、ゲインを掛ける前の値を保存しない指定です。保存は、[CPU の経路](#3-cpu-の経路)で説明します。
|
||||
|
||||
GPU の経路では、素材と出力のテクスチャを使う処理を、ComputeWeave のコンテキストに記録します。ComputeWeave では、`GraphicsDevice` から作った `ComputeContext` に、計算シェーダーの実行を記録します。
|
||||
|
||||
```csharp
|
||||
using var gpu = new GpuTileConvolver(device);
|
||||
gpu.Upload(spectrum);
|
||||
var job = gpu.Prepare(plan, sourceX, sourceY, sourceWidth, sourceHeight, gain, samples, false);
|
||||
using (var context = device.CreateComputeContext())
|
||||
{
|
||||
GpuTileConvolver.Record(
|
||||
in context, sourceTexture, outputTexture, gpu.Tiles, gpu.Twiddles, gpu.Spectrum,
|
||||
gpu.Report, gpu.Samples, gpu.StoreFor(job), job);
|
||||
}
|
||||
|
||||
var measurements = new ConvolutionMeasurement[GpuTileCheck.MeasurementCount(samples.Length)];
|
||||
GpuTileCheck.Evaluate(gpu.ReadReport(job), job, samples, spectrum.Kernel, measurements);
|
||||
```
|
||||
|
||||
`device` は ComputeWeave の `GraphicsDevice` です。`sourceTexture` と `outputTexture` は、どちらも `ReadWriteTexture2D<Bgra32, Float4>` です。素材のテクスチャは `sourceWidth` × `sourceHeight` 画素、出力のテクスチャは畳み込む範囲と同じ大きさにします。`gpu.Tiles`、`gpu.Twiddles`、`gpu.Spectrum`、`gpu.Report`、`gpu.Samples` の 5 つは、`GpuTileConvolver` が確保した資源で、そのまま `Record` に渡します。
|
||||
|
||||
スペクトルは、`plan` と同じ T と r で `Update` してから `Upload` し、その後に `Prepare` を呼びます。`using` ブロックを抜けるときに、記録した処理が GPU へ送られます。`ReadReport` は、その後に呼びます。
|
||||
|
||||
`Prepare` の最後の引数は、ゲインを掛ける前の値を保存するかどうかです。`true` を渡すと、`StoreFor(job)` は保存用のバッファーを返します。`false` を渡すと、代わりのバッファーを返します。代わりのバッファーは、`Record` の保存用の引数に渡すだけで、中身は使いません。大きさは 16 バイトです。保存を求めたときは、`ReadStore` で保存した値も読み戻せます。保存は、[GPU の経路](#4-gpu-の経路)で説明します。
|
||||
|
||||
`samples` は、検査で値を抜き取る出力の位置を並べた `Int2` の配列かスパンです。最大 16 か所で、畳み込む範囲の左上を原点とした座標で渡します。`GpuTileCheck.Evaluate` は、`ReadReport` で読み戻した値から検査を作り、`measurements` に書きます。読み戻す値は、[検査の材料](#5-検査の材料と検査)です。`measurements` の長さは、`GpuTileCheck.MeasurementCount` で求めます。`spectrum.Kernel` は、和で割った後のカーネルです。`Evaluate` は、これを使って、抜き取った位置の参照値を求めます。
|
||||
|
||||
ComputeWeave の `[ComputePipelineHost]` を付けた `partial` クラスで、`[ComputePipeline]` を付けたメソッドから `Record` を呼ぶこともできます。メソッドの先頭の引数は、`in ComputeContext` にします。`Record` に渡す資源は、すべて、そのメソッドの引数として宣言します。`GpuTileJob` は資源ではないので、`[ComputeResource]` を付けずに、通常の引数として宣言します。Wave Optics は、この形で使っています。実例は、[WaveOpticsPipelineHost.cs](../WaveOptics/Rendering/WaveOpticsPipelineHost.cs) にあります。この形には `using` ブロックが無く、生成されたメソッドは `ComputeSubmission` を返します。`ComputeSubmission` の `Wait` を呼んでから、`ReadReport` や `ReadStore` を呼びます。資源の引数には、次の表のアクセスで `[ComputeResource]` を付けます。
|
||||
|
||||
| 資源 | アクセス |
|
||||
|---|---|
|
||||
| 素材のテクスチャ、出力のテクスチャ、`Tiles`、`Report`、`StoreFor(job)` の戻り値 | `ComputeResourceAccess.ReadWrite` |
|
||||
| `Twiddles`、`Spectrum`、`Samples` | `ComputeResourceAccess.Read` |
|
||||
|
||||
自己試験は、GPU の経路を初めて使う前に行います。
|
||||
|
||||
```csharp
|
||||
var measurements = new ConvolutionMeasurement[SpectralSelfTest.MeasurementCount];
|
||||
var count = SpectralSelfTest.Run(device, maximumRadius, measurements);
|
||||
```
|
||||
|
||||
`maximumRadius` は、プラグインが使う最大のカーネルの半径です。戻り値の `count` は、`measurements` の先頭から書き込んだ件数です。この `count` 件が、自己試験の検査です。Wave Optics は、[WaveOpticsCompute.cs](../WaveOptics/Rendering/WaveOpticsCompute.cs) で、これを YMM4-ComputeGuard の検査へ変換して渡しています。
|
||||
|
||||
---
|
||||
|
||||
## 主な機能
|
||||
|
||||
### 1. タイルに分けた畳み込み
|
||||
|
||||
畳み込む範囲を、一辺 T 画素の正方形のタイルに分けます。T は 2 のべき乗で、`TilePlan.SelectSize` がカーネルの半径から次の規則で決めます。
|
||||
|
||||
| 半径 | T | 1 枚のタイルが出力する範囲 |
|
||||
|---|---|---|
|
||||
| 0〜23 | 128 | 一辺 128 - 2r 画素 |
|
||||
| 24〜255 | 512 | 一辺 512 - 2r 画素 |
|
||||
|
||||
`TilePlan.Create` に T を直接渡すと、64 と 256 も使えます。どの T でも、2r は T より小さくなければなりません。
|
||||
|
||||
1 枚のタイルが出力する範囲は、一辺 T - 2r 画素です。タイルは、この範囲を上下左右に r 画素ずつ広げた、T × T 画素の範囲の素材を読みます。畳み込む範囲の端にあって、出力が T - 2r 画素に満たないタイルも、T × T 画素を読みます。タイルごとに 2 次元の高速フーリエ変換を求め、カーネルのスペクトルを掛け、逆変換します。この計算は巡回畳み込みです。巡回畳み込みは、タイルの右端の次に左端が、下端の次に上端が続くとみなして畳み込む計算です。そのため、縁から r 画素以内の値は、反対側の縁にある素材の影響を受けます。その r 画素の幅の値を捨て、中央の (T - 2r) × (T - 2r) 画素だけを出力します。この方法をオーバーラップセーブ法と呼びます。
|
||||
|
||||
畳み込む範囲全体を 1 回で変換せずにタイルに分けるのは、作業領域の大きさと誤差の上限を、範囲の大きさによらず決めるためです。タイルどうしは互いに独立しているので、どの順に計算しても結果は同じです。
|
||||
|
||||
変換は、基数 2 の時間間引きの高速フーリエ変換です。行に変換をかけてから列に変換をかけ、逆変換は列、行の順に行います。変換に使う回転因子は、j を 0 から T / 2 - 1 までの整数として、exp(-2πi j / T) で表される値です。この値を並べた表を作ります。表の値は、倍精度の `Math.SinCos` で求めた値を float に丸めたものです。CPU と GPU は同じ表を使い、GPU では三角関数を使いません。
|
||||
|
||||
カーネルのスペクトルは、カーネルを T × T の配列に置いて、2 次元の高速フーリエ変換をかけたものです。倍精度で求めてから、float に丸めます。高速フーリエ変換で求まるのは数学の定義の畳み込みなので、式 (1) の向きにそろえるために、カーネルの値 k(d) を位置 -d に置きます。位置は T を周期として折り返し、残りは 0 にします。値は、GPU の列の計算で連続して読めるよう、列ごとに並べます。
|
||||
|
||||
2^-126 は float の正の正規化数の最小値で、0 でなく絶対値がこれより小さい値を非正規化数と呼びます。回転因子とスペクトルの非正規化数は、符号を残して 0 にします。GPU は非正規化数を 0 にすることがあるので、CPU の側で先に 0 にそろえておきます。
|
||||
|
||||
### 2. 2 つのチャンネルをまとめる複素数
|
||||
|
||||
素材の 4 つのチャンネルを、赤と緑、青と不透明度の 2 組に分けます。組の一方を実部、もう一方を虚部とした複素数で変換します。カーネルは実数なので、逆変換の実部と虚部が、そのまま 2 つのチャンネルの畳み込みになります。1 回の複素数の変換で 2 つのチャンネルを計算できます。
|
||||
|
||||
### 3. CPU の経路
|
||||
|
||||
コンストラクターに渡すスレッド数を N とします。`CpuTileConvolver` は、生成するときに N - 1 本の作業スレッドを作り、`Dispose` するまで使い回します。`Convolve` を呼んだスレッドも計算に加わるので、計算するスレッドは最大で N 本です。タイルは、これらのスレッドに割り当てます。N を渡さないときは、論理プロセッサーの数になります。
|
||||
|
||||
1 回の畳み込みで同時に計算するスレッドの数は、次の 3 つのうち最も小さい数です。
|
||||
|
||||
- N
|
||||
- タイルの枚数
|
||||
- タイルの作業領域の合計が 64 MB を超えない最大のスレッド数
|
||||
|
||||
タイルの作業領域は、T × T の 4 チャンネルの float で、16 T² バイトです。そのため、T が 512 のときは 16 スレッド、128 のときは 256 スレッドが上限です。MB は 2^20 バイトです。
|
||||
|
||||
計算するスレッドは、それぞれ 1 組の作業領域を使います。1 組は、タイル用の 16 T² バイトと、1 行分の配列 2 つ用の 32 T バイトです。作業領域は初めて使うときに確保し、T が変わるまで持ち続けます。T が変わると、すべての作業領域を捨てます。持ち続けるのは同じ T の作業領域だけで、その数は上のスレッド数で抑えられるので、タイルの分は合計で 64 MB 以下です。同じ T の呼び出しが続くあいだは、同時に計算するスレッドが前より増えたときだけ、新しいメモリを確保します。
|
||||
|
||||
出力では、畳み込んだ値にゲインを掛け、Direct3D の規則と同じ式で 8 ビットへ変えます。NaN は 0 にし、0〜1 に切り詰め、255 倍して 0.5 を足し、端数を切り捨てます。
|
||||
|
||||
ゲインだけを変えるときは、畳み込みをやり直さずに出力できます。そのために、`Convolve` の最後の引数 `convolvedValues` に配列を渡します。渡した配列に、ゲインを掛ける前の値が float で保存されます。保存する値は、画素ごとに R、G、B、A の順の float 4 つで、出力の BGRA とは順が違います。配列の長さは、畳み込む範囲の幅 × 高さ × 4 以上です。
|
||||
|
||||
`RenderStored` は、保存した値に別のゲインを掛けて出力し直します。結果は、そのゲインで畳み込みと同時に出力した場合と 1 ビットも違いません。`RenderStored` は、16384 画素を 1 単位として、スレッドに割り当てます。
|
||||
|
||||
素材の外にある行と、4 つのチャンネルがすべて 0 の画素だけからなる行は、行の変換を省きます。タイルが読む T × T の範囲のどの行もそうなら、タイルの計算をすべて省き、出力と保存する値に 0 を書きます。どちらも、変換した場合と同じ値になります。
|
||||
|
||||
### 4. GPU の経路
|
||||
|
||||
`GpuTileConvolver.Record` は、計算シェーダーの実行をコンテキストに記録します。計算シェーダーを 1 回起動することを、ディスパッチと呼びます。まず `ReportResetShader` で、`Report` の先頭にある NaN と無限大の個数を 0 にします。`Report` は、[検査の材料](#5-検査の材料と検査)を書くバッファーです。抜き取る位置があるときは、続けて `GatherShader` で、その周りの素材を集めます。
|
||||
|
||||
そのあと、タイルを計算します。作業領域が 16 MB に収まる枚数のタイルをまとめて計算し、このまとまりをバッチと呼びます。1 つのバッチのタイルは、T が 512 のときは 4 枚まで、128 のときは 64 枚までです。バッチごとに、次の 3 回のディスパッチを記録します。
|
||||
|
||||
| 順 | シェーダー | 処理 |
|
||||
|---|---|---|
|
||||
| 1 | `ForwardRowShader` | 素材を読み、行に変換をかける。素材の和と 2 乗の和も書く |
|
||||
| 2 | `ColumnShader` | 列に変換をかけ、スペクトルを掛け、列に逆変換をかける |
|
||||
| 3 | `InverseRowShader` | 行に逆変換をかけ、出力に書く。NaN と無限大の個数、出力の和、抜き取った出力も書く |
|
||||
|
||||
1 つのスレッドグループは 256 スレッドで、512 個の値を受け持ちます。以下では、スレッドグループを単にグループと呼びます。値はグループ共有メモリに置きます。`ColumnShader` は、列を転置せずにその場で変換します。
|
||||
|
||||
浮動小数点数を計算するシェーダーは、ComputeWeave の `CompileOptions.IeeeStrictness` を付けてコンパイルします。これは、シェーダーのコンパイラーである DXC の `-Gis` に当たり、精度を緩める最適化を許しません。
|
||||
|
||||
出力のテクスチャには、ゲインを掛けた値を書きます。`Prepare` の最後の引数に `true` を渡すと、ゲインを掛ける前の値を、畳み込む範囲の 1 画素につき 16 バイトのバッファーに保存します。`RecordStored` は、保存した値に別のゲインを掛けて出力し直します。結果は、そのゲインで畳み込みと同時に出力した場合と 1 ビットも違いません。保存に使うバッファーは、`ReleaseStore` か `Dispose` を呼ぶまで持ち続けます。
|
||||
|
||||
### 5. 検査の材料と検査
|
||||
|
||||
GPU は、検査の材料を 1 つの `uint` のバッファー(`Report`)に書きます。呼び出し側は、これを `ReadReport` で 1 回で読み戻します。アトミック加算は、複数のスレッドが同じ場所に足しても、足し漏れが起きない加算です。
|
||||
|
||||
| 値 | 書くシェーダー | 中身 |
|
||||
|---|---|---|
|
||||
| NaN と無限大の個数 | `InverseRowShader` | タイルが逆変換で得た T × T 個の画素のうち、ゲインを掛ける前の 4 つのチャンネルのどれかが NaN か無限大のものの数。どの画素の NaN も GPU の異常を示すので、捨てる縁と、畳み込む範囲の外の画素も数える。指数部のビットで判定し、整数のアトミック加算で数える |
|
||||
| 素材の和 | `ForwardRowShader` | タイルが出力する範囲のうち、畳み込む範囲の中にある素材の 8 ビットの値の和。チャンネルごと |
|
||||
| 素材の 2 乗の和 | `ForwardRowShader` | タイルが読む T × T の範囲の素材の、8 ビットの値の 2 乗の和。赤と緑、青と不透明度の 2 組 |
|
||||
| 出力の和 | `InverseRowShader` | ゲインを掛ける前の出力の値を、スレッドグループの 512 個ずつ、深さ 9 の二分木で足した値。捨てる縁の値と、畳み込む範囲の外の値は 0 として足す |
|
||||
| 抜き取った出力 | `InverseRowShader` | 抜き取る位置の、ゲインを掛ける前の 4 つのチャンネルの値 |
|
||||
| 抜き取った近傍 | `GatherShader` | 抜き取る位置の周りの (2r + 1) × (2r + 1) 画素の、素材の 8 ビットの値 |
|
||||
|
||||
`GpuTileCheck.Evaluate` は、これらから次の検査を作ります。S は抜き取る位置の数で、最大 16 です。
|
||||
|
||||
| 名前 | 測定値 | 参照値 | 許容値 |
|
||||
|---|---|---|---|
|
||||
| `nonfinite` | NaN と無限大の個数 | 0 | 0 |
|
||||
| `sum.red` など 4 件 | 出力の和を、グループの順に倍精度で足した値 | 素材の和を 255 で割った値 | [総和の上限](#8-総和の上限)で導いた値 |
|
||||
| `spot.red` など S × 4 件 | 抜き取った出力の値 | 抜き取った近傍から `DirectCorrelation` で求めた値 | タイルの誤差の上限([1 画素の上限](#7-1-画素の上限))と、参照値の誤差の上限([参照値の誤差](#9-参照値の誤差))の和 |
|
||||
|
||||
総和の検査は、素材の画素の位置によっては、正常な GPU でも不合格になることがあります。素材の 1 画素は、その画素を中心とする一辺 2r + 1 画素の正方形に含まれる出力の画素に寄与します。
|
||||
|
||||
総和の検査の参照値は、畳み込む範囲の中にある素材の和を 255 で割った値です。ある条件が成り立つとき、誤差の無い、ゲインを掛ける前の出力の和は、この参照値の σ 倍と等しくなります。σ は、和で割った後のカーネルの値の和で、丸めのために 1 とわずかに異なります。条件は、値が 0 でない素材の画素ごとに、その画素を中心とする一辺 2r + 1 画素の正方形が、畳み込む範囲に完全に含まれるか、範囲とまったく重ならないことです。これは、等しくなるための十分条件です。
|
||||
|
||||
素材の画素の座標を、畳み込む範囲と同じ座標系で (qx, qy) とします。値が 0 でない画素ごとに、次のどちらかの場合に当てはまることが、その条件です。
|
||||
|
||||
- 縁から r 画素以上内側にある: `regionX` + r ≤ qx ≤ `regionX` + `regionWidth` - 1 - r、かつ `regionY` + r ≤ qy ≤ `regionY` + `regionHeight` - 1 - r。
|
||||
- 範囲の外で、縁から r 画素を超えて離れている: qx < `regionX` - r、qx > `regionX` + `regionWidth` - 1 + r、qy < `regionY` - r、qy > `regionY` + `regionHeight` - 1 + r のどれか。
|
||||
|
||||
上の 2 つの場合のどちらにも当てはまらない画素があると、その画素の値の一部が、範囲の外へ出るか、範囲の外から入ることがあります。カーネルの値が 0 でない位置を通って、出入りするためです。この出入りの分は、許容値に含めていません。そのため、正常な GPU でも、総和の検査で不合格になることがあります。畳み込む範囲は、この条件を満たすように決めてください。
|
||||
|
||||
許容値は、[総和の上限](#8-総和の上限)の式で求めます。条件を満たすときの、計算した出力の和と参照値の差は、σ が 1 からずれる分と、計算で生じる分です。式の最後の項が前者を、それより前の項が後者を見込んでいます。
|
||||
|
||||
### 6. 自己試験
|
||||
|
||||
`SpectralSelfTest.Run` は、T が 128 と 512 のそれぞれで次の 2 つの場面を GPU で計算し、検査を引数の `measurements` に書き込みます。戻り値は、書き込んだ件数です。`measurements` には、`SpectralSelfTest.MeasurementCount`(280)件以上の長さが要ります。
|
||||
|
||||
1. 半径 3 のカーネルで、2 × 2 枚のタイルにまたがる模様を 2 回畳み込みます。2 回の結果でビットが違う値の個数を、`selftest.determinism` の測定値にします。全画素の値を `DirectCorrelation` の値と比べ、差を誤差の上限で割った値の最大を、`selftest.full` の測定値にします。1 回目の結果からは、[検査の材料と検査](#5-検査の材料と検査)の表と同じ検査も作ります。
|
||||
2. 半径は、T が 128 のときは `maximumRadius` と 23 の小さいほう、512 のときは `maximumRadius` と 255 の小さいほうにします。この半径のカーネルで、模様を 1 回畳み込み、[検査の材料と検査](#5-検査の材料と検査)の表と同じ検査を作ります。23 は、`TilePlan.SelectSize` が T に 128 を選ぶ半径の上限です。255 は、本ライブラリが扱える半径の上限です。
|
||||
|
||||
`selftest.determinism` は測定値が 0 のときだけ、`selftest.full` は測定値が 1 以下のときだけ合格です。`maximumRadius` が 3 より小さいと、`ArgumentOutOfRangeException` を投げます。
|
||||
|
||||
模様には、値が 0 の領域、不透明な細い線、さまざまな不透明度の画素を入れます。カーネルは、左右にも上下にも非対称な形にします。抜き取る位置は、四隅と中央の 5 か所、タイルの継ぎ目の両側の 2 か所、決まった式で決めた 9 か所です。全画素の比較に小さなカーネルを使うのは、倍精度の直接の計算を軽く保つためです。高速フーリエ変換の各段の計算はカーネルの大きさによらないので、小さなカーネルでも変換のすべての段を通ります。
|
||||
|
||||
---
|
||||
|
||||
## 誤差の上限
|
||||
|
||||
ここでは、float で計算した畳み込みの値と、厳密な値との差の上限を導きます。差は素材の 2 ノルムに対する相対誤差で追い、1 タイル、1 画素、総和の順に上限を求めます。
|
||||
|
||||
### 前提
|
||||
|
||||
上限は次の前提の上で成り立ちます。
|
||||
|
||||
| 前提 | 中身 |
|
||||
|---|---|
|
||||
| GPU の演算 | [Direct3D 11 の浮動小数点数の規則](https://learn.microsoft.com/en-us/windows/win32/direct3d11/floating-point-rules)に従う。加算、減算、乗算の相対誤差は 2^-23 未満。演算の結果が非正規化数になると、符号を残して 0 にする |
|
||||
| CPU の演算 | IEEE 754 の最も近い値への丸めに従い、相対誤差は 2^-24 以下 |
|
||||
| 倍精度の演算 | 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 以下 |
|
||||
| カーネル | 値はすべて 0 以上で、和で割って 1 にそろえてある。実際の和は 1 からわずかにずれる |
|
||||
|
||||
カーネルが 0 以上で和が 1 であるという前提から、スペクトルの絶対値はどこでも 1 以下になり、カーネルの 2 ノルムも 1 以下になります。実際の和は 1 から γ_ker までずれます。γ_ker は、次の記号の表で定義します。このずれの扱いは、[式に入れていない誤差と上限の余裕](#10-式に入れていない誤差と上限の余裕)で説明します。
|
||||
|
||||
### 記号
|
||||
|
||||
| 記号 | 意味 |
|
||||
|---|---|
|
||||
| u | 1 回の演算の相対誤差の上限。GPU では 2^-23、CPU では 2^-24。倍精度の演算では 2^-53 |
|
||||
| L | log₂T |
|
||||
| γ_n(ε) | n ε / (1 - n ε)。1 回の相対誤差が ε 以下の丸めを n 回重ねたときの、相対誤差の上限 |
|
||||
| μ | float の回転因子の誤差の上限 |
|
||||
| κ | float のスペクトルの誤差の上限 |
|
||||
| ‖x‖ | 素材の値を 255 で割った値 x の、タイルが読む T × T の 2 ノルム。赤と緑、青と不透明度の組ごとに求める |
|
||||
| x̂ | float に変えた後の素材 |
|
||||
| n_k | カーネルの値の数 |
|
||||
| γ_ker | γ_(n_k+1)(2^-53)。`DirectCorrelation` の丸めの回数の根拠は[参照値の誤差](#9-参照値の誤差)に、カーネルを和で割る丸めの根拠は[式に入れていない誤差と上限の余裕](#10-式に入れていない誤差と上限の余裕)にあります |
|
||||
|
||||
μ_d、η_d、α_d の添字 d は、倍精度(double)を表します。ほかの記号は、各節で導くときに説明します。T は[タイルに分けた畳み込み](#1-タイルに分けた畳み込み)で、r は概要で定義しています。
|
||||
|
||||
### 1. 回転因子とスペクトル
|
||||
|
||||
回転因子は exp(-2πi j / T) です。角度が δ ずれると、回転因子は複素数の絶対値で δ 以下だけずれます。倍精度で求めるとき、角度の誤差は π × 2^-51 以下とし、`Math.SinCos` の誤差は複素数の絶対値で √2 × 2^-51 以下とします。倍精度の回転因子の誤差 μ_d は、この 2 つの和です。
|
||||
|
||||
```
|
||||
μ_d = (π + √2) × 2^-51
|
||||
```
|
||||
|
||||
角度の誤差の実際の値は、π × 2^-51 より小さくなります。これは、[式に入れていない誤差と上限の余裕](#10-式に入れていない誤差と上限の余裕)で説明します。float に丸めると、誤差は次の μ 以下になります。
|
||||
|
||||
```
|
||||
μ = 2^-24 (1 + μ_d) + μ_d
|
||||
```
|
||||
|
||||
回転因子の成分は、0 でないとき絶対値が約 6 × 10^-17 以上で、2^-126 より大きいので、μ には、非正規化数を 0 にそろえる分を入れません。
|
||||
|
||||
スペクトルは、倍精度の 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
|
||||
α_d = (1 + η_d)^(2L) - 1
|
||||
```
|
||||
|
||||
T × T の 2 次元の変換は、2 ノルムを T 倍にします。カーネルの 2 ノルムは 1 以下なので、倍精度のスペクトルの各値の絶対誤差は α_d T 以下です。倍精度のスペクトルの絶対値は 1 + α_d T 以下なので、float に丸めると、2^-24 (1 + α_d T) 以下の誤差が加わります。スペクトルの値のうち、非正規化数を 0 にそろえた値では、実部と虚部がそれぞれ 2^-126 未満だけ変わるので、複素数の絶対値で √2 × 2^-126 未満の誤差が加わります。これらを足して、次の κ を得ます。
|
||||
|
||||
```
|
||||
κ = 2^-24 (1 + α_d T) + α_d T + √2 × 2^-126
|
||||
```
|
||||
|
||||
### 2. 変換の 1 段
|
||||
|
||||
変換の 1 段では、2 つの値 v₀ と v₁ の組ごとに、v₀ + w v₁ と v₀ - w v₁ を求めます。w は回転因子で、この計算をバタフライと呼びます。m を √2 γ_2(u) とすると、w × v₁ の複素数の掛け算の相対誤差は m 以下です。回転因子の誤差を加えると、この相対誤差は μ + (1 + μ) m 以下です。最後の加算と減算の丸めを加えると、1 段の出力の誤差の 2 ノルムは、正確な出力の 2 ノルムに対して次の η 以下です。
|
||||
|
||||
```
|
||||
η = (1 + u)(μ + (1 + μ) m) + u
|
||||
```
|
||||
|
||||
### 3. 2 次元の変換
|
||||
|
||||
2 次元の変換は 2L 段です。各段は、正確に計算すれば、2 ノルムをちょうど √2 倍にします。そのため、s 段目までの相対誤差を e_s とすると、1 + e_(s+1) ≤ (1 + η)(1 + e_s) が成り立ちます。変換全体の相対誤差は、次の α 以下です。
|
||||
|
||||
```
|
||||
α = (1 + η)^(2L) - 1
|
||||
```
|
||||
|
||||
### 4. スペクトルとの掛け算
|
||||
|
||||
変換した値 X に、スペクトル K を掛けます。K の絶対値は 1 以下で、float のスペクトルの誤差は κ 以下です。複素数の掛け算の丸めを加えると、掛けた結果の誤差の 2 ノルムは、正確な X の 2 ノルムに対して次の c 以下です。
|
||||
|
||||
```
|
||||
c = α (1 + κ)(1 + m) + κ (1 + m) + m
|
||||
```
|
||||
|
||||
### 5. 逆変換と 1 タイルの上限
|
||||
|
||||
逆変換も 2L 段で、相対誤差は α 以下です。最後に掛ける 1 / T² は 2 のべき乗なので、結果が非正規化数になる場合を除いて丸めの誤差がありません。順変換は 2 ノルムを T 倍にし、逆変換と 1 / T² を合わせると 1 / T 倍になるので、2 つの倍率は打ち消し合います。そのため、float の計算が x̂ に対して生む誤差の 2 ノルムは、x̂ の 2 ノルムに、次の b を掛けた値以下です。
|
||||
|
||||
```
|
||||
b = c + α (1 + c)
|
||||
```
|
||||
|
||||
‖x̂‖ は、変える前の ‖x‖ の (1 + 2^-24) 倍以下です。素材を float に変える丸めは、スペクトルの絶対値が 1 以下なので、出力に 2^-24 ‖x‖ 以下の差を生みます。したがって、出力の誤差は b (1 + 2^-24) ‖x‖ + 2^-24 ‖x‖ 以下で、1 タイルの相対の上限 B は次のとおりです。
|
||||
|
||||
```
|
||||
B = b + 2^-24 (1 + b)
|
||||
```
|
||||
|
||||
### 6. 0 にされる値
|
||||
|
||||
GPU は、演算の結果が非正規化数になると、その値を 0 にします。1 回で値が変わる量は 2^-126 未満です。1 段で、1 つの複素数の実部と虚部は、それぞれ最大 4 回の演算の結果になります。そのため、1 段で 1 つの複素数が受ける変化は 4√2 × 2^-126 未満で、タイルの T² 個の値の 2 ノルムでは 4√2 × T × 2^-126 未満です。
|
||||
|
||||
どの段で生じた変化も、出力に届くまでに大きくなりません。順変換の s 段目で生じた変化は、残りの段と逆変換で (√2)^(4L - s) 倍になり、最後の 1 / T² を掛けると 2^(-s/2) 倍以下になります。掛け算で生じた変化は出力で 1 / T 倍になり、逆変換の段と最後の倍率で生じた変化は 1 倍以下です。後の段の丸めとスペクトルの絶対値で変化が増える分は、合わせて 2 倍未満です。
|
||||
|
||||
段の数は、順変換と逆変換で 4L です。これに、掛け算と最後の倍率の 2 段を加えて、4L + 2 段になります。したがって、出力の誤差の 2 ノルムへの寄与は、次の F 以下です。
|
||||
|
||||
```
|
||||
F = 2 (4L + 2) × 4√2 × T × 2^-126
|
||||
```
|
||||
|
||||
`ConvolutionBound.FlushedOperations` は、2^-126 に掛ける係数を整数に切り上げた値を返します。T が 512 のとき F は約 2.6 × 10^-33 で、8 ビットの値の 1 階調分にあたる 1/255 に比べて無視できる大きさです。CPU は 0 にしませんが、非正規化数の範囲の丸めの誤差は 1 回で 2^-150 以下なので、同じ式で押さえられます。
|
||||
|
||||
### 7. 1 画素の上限
|
||||
|
||||
1 画素の各チャンネルの誤差は、出力の誤差の 2 ノルムを超えません。したがって、次の式が成り立ちます。
|
||||
|
||||
```
|
||||
|ŷ - y| ≤ B ‖x‖ + F
|
||||
```
|
||||
|
||||
ŷ は、ゲインを掛ける前の、float で計算した値です。y は、数学的に厳密に求めた値です。式 (1) の src に x を、k に和で割った後のカーネルを入れて求めます。和で割った後のカーネルは、`KernelSpectrum.Kernel` で読めます。`ConvolutionBound.Absolute` が、上の式の右辺を返します。
|
||||
|
||||
素材の 8 ビットの値がすべて 255 のタイルでは、255 で割った値がすべて 1 になり、‖x‖ は最大の √2 T になります。B ‖x‖ + F は、255 で割った値に対する誤差の上限です。255 倍すると、8 ビットの値の 1 階調を 1 とする値になります。B ‖x‖ + F の ‖x‖ に √2 T を入れて 255 倍し、小数第 2 位まで切り上げた値を、T ごとに次の表に示します。切り上げるので、表の値も上限のままです。
|
||||
|
||||
| T | GPU の経路(階調) | CPU の経路(階調) |
|
||||
|---:|---:|---:|
|
||||
| 64 | 0.30 | 0.17 |
|
||||
| 128 | 0.69 | 0.39 |
|
||||
| 256 | 1.57 | 0.88 |
|
||||
| 512 | 3.52 | 1.97 |
|
||||
|
||||
1 つ目の表の値は、ゲインを掛ける前の値に対する上限です。‖x‖ は √2 T を超えないので、どのタイルの上限も 1 つ目の表の値以下です。‖x‖ が √2 T より小さいタイルでは、上限は 1 つ目の表の値より小さくなります。ゲイン g を掛けた値の上限は、ゲインを掛ける前の上限の |g| 倍です。ゲインを掛ける float の丸めと、8 ビットへの丸めによる誤差は、この上限に含みません。
|
||||
|
||||
[動作の確認](#動作の確認)で比べるため、B ‖x‖ の ‖x‖ に √2 T を入れて 255 倍し、小数第 3 位までに四捨五入した値を、2 つ目の表に示します。F の項は含みません。F は 10^-30 より小さく、この表の値にも影響しません。2 つ目の表の値は四捨五入しているので、上限としては使えません。
|
||||
|
||||
| T | GPU の経路(階調、四捨五入) | CPU の経路(階調、四捨五入) |
|
||||
|---:|---:|---:|
|
||||
| 64 | 0.296 | 0.166 |
|
||||
| 128 | 0.688 | 0.385 |
|
||||
| 256 | 1.566 | 0.877 |
|
||||
| 512 | 3.514 | 1.966 |
|
||||
|
||||
### 8. 総和の上限
|
||||
|
||||
タイル t が出力する画素の数を n_t、タイル t が読む素材の 2 ノルムを ‖x_t‖ とします。出力の誤差の 2 ノルムが B ‖x_t‖ + F 以下なので、n_t 個の誤差の絶対値の和は、√n_t × (B ‖x_t‖ + F) 以下です。これをすべてのタイルで足したものを E とします。E は、赤と緑の組と、青と不透明度の組で別々に求めます。
|
||||
|
||||
GPU は、出力の値を 512 個ずつ、深さ 9 の二分木で足します。その誤差は、足す値の絶対値の和に対して γ_9(u) 以下です。木の 511 回の加算で 0 にされる値の分として、グループごとに 511 × 2^-126 を加えます。グループの和は、CPU が倍精度でグループの順に足します。カーネルの和を 1 にそろえるときの丸めの分も加えて、許容値を組み立てます。
|
||||
|
||||
G は、畳み込む範囲を覆うすべてのタイルのグループの数で、タイル数 × T² / 512 に等しい数です。Z は、木の加算で 0 にされる値の分です。
|
||||
|
||||
参照値は、畳み込む範囲の中にある素材の和を 255 で割った値です。A は、float で計算した出力 ŷ の、範囲全体にわたる絶対値の和の上限です。厳密な出力 y は、カーネルも素材も 0 以上なので、0 以上です。そのため、y の絶対値の和は、y の和に等しくなります。[総和の検査の条件](#5-検査の材料と検査)が成り立つとき、y の和は参照値に 1 + γ_ker を掛けた値を超えません。E は、ŷ と y の差の絶対値の和の上限です。したがって、ŷ の絶対値の和は、参照値に 1 + γ_ker を掛けた値に E を加えた値を超えません。この値を A とします。
|
||||
|
||||
次の式では、γ_9 = γ_9(u)、γ_G = γ_G(2^-53) と略記します。γ_ker は、記号の表のとおりです。
|
||||
|
||||
```
|
||||
A = 参照値 × (1 + γ_ker) + E
|
||||
Z = G × 511 × 2^-126
|
||||
許容値 = E + γ_9 A + Z + γ_G ((1 + γ_9) A + Z) + 参照値 × γ_ker
|
||||
```
|
||||
|
||||
### 9. 参照値の誤差
|
||||
|
||||
`DirectCorrelation` は、n_k 個の積を倍精度で順に足します。1 個の積では、8 ビットの値を 255 で割るときと、カーネルの値を掛けるときの 2 回丸めます。足し算の丸めは、最初の 0 との和を除いた n_k - 1 回です。したがって、1 個の積に重なる丸めは、最大で n_k + 1 回です。素材の値は 1 以下で、積はどれも 0 以上なので、誤差はカーネルの値の和の γ_ker 倍以下です。
|
||||
|
||||
カーネルの値の和は 1 + γ_ker 以下なので、誤差は γ_ker (1 + γ_ker) 以下です。このうち γ_ker² は 10^-21 未満です。γ_(n_k+2)(2^-53) と γ_ker の差は 2^-53 以上なので、この誤差は γ_(n_k+2)(2^-53) を超えません。`DirectCorrelation.ErrorBound` は γ_(n_k+2)(2^-53) を返します。この値は、半径 255 のカーネルでも、3 × 10^-11 未満です。
|
||||
|
||||
### 10. 式に入れていない誤差と上限の余裕
|
||||
|
||||
[1 画素の上限](#7-1-画素の上限)までの式は、カーネルの値の和がちょうど 1 で、式の値を正確に求められるとして導いています。実際には、次の 2 つのずれがあります。
|
||||
|
||||
1. `KernelSpectrum` はカーネルの値を倍精度で足して和を求め、各値をその和で割ります。割った後の値の和が 1 からずれる幅は、次の手順で、γ_ker 以下と示せます。
|
||||
- 和は、足し算の丸めを n_k - 1 回受けます。真の和に対する計算した和の相対誤差を θ とすると、|θ| ≤ γ_(n_k-1)(2^-53) です。
|
||||
- 割り算の丸めの相対誤差は、1 回ごとに 2^-53 以下です。この相対誤差の重み付き平均を ρ とします。ρ の重みは、各値が真の和に占める割合です。重みは 0 以上で、足すと 1 になります。そのため、|ρ| ≤ 2^-53 です。
|
||||
- 割った後の和は、(真の和 / 計算した和) × (1 + ρ) です。真の和 / 計算した和 = 1 / (1 + θ) なので、割った後の和は、1 に (1 + ρ) / (1 + θ) を掛けた値です。最悪は θ = -γ_(n_k-1)(2^-53)、ρ = 2^-53 のときで、1 からのずれは次の D 以下です。
|
||||
|
||||
```
|
||||
D = (2^-53 + γ_(n_k-1)(2^-53)) / (1 - γ_(n_k-1)(2^-53))
|
||||
```
|
||||
|
||||
1 つの値に重なる丸めは、足し算の最大 n_k - 1 回と、割り算 1 回で、合わせて n_k 回です。この回数から決まる素朴な上限は、γ_(n_k)(2^-53) です。D は、半径 1 以上で、この素朴な上限をわずかに超えます。超える幅は (n_k × 2^-53)² の程度で、半径 255 でも 10^-21 未満です。γ_(n_k+1)(2^-53) と γ_(n_k)(2^-53) の差は 2^-53 以上あるので、D は γ_(n_k+1)(2^-53) 以下です。この γ_(n_k+1)(2^-53) が、記号の表の γ_ker です。
|
||||
|
||||
そのため、スペクトルの絶対値は 1 + γ_ker 以下としか言えません。カーネルの 2 ノルムも、1 + γ_ker 以下としか言えません。この 2 つの上限を、1 から 1 + γ_ker に替えて b と B を求め直すと、B はほぼ 1 + γ_ker 倍になります。増え方は相対で約 γ_ker で、2γ_ker 未満です。γ_ker は、T が 512 で半径が 255 のときでも 3 × 10^-11 未満です。[総和の上限](#8-総和の上限)と[参照値の誤差](#9-参照値の誤差)の式は、この 1 つ目のずれのうち、カーネルの和が 1 からずれる分を γ_ker として含めています。B が増える分は式に入れず、次の余裕で受けます。
|
||||
2. 上限と許容値の計算と、検査の比較は倍精度で行うので、丸めで数学的な値からずれます。畳み込む範囲のタイルが 10^6 枚以下なら、ずれは相対で 10^-9 未満です。
|
||||
|
||||
一方、回転因子の角度の誤差には、実際の上限より大きい π × 2^-51 を使っています。角度 -2π j / T は、倍精度で計算します。その丸めは π × 2^-53 以下で、倍精度の π の誤差は 1.3 × 10^-16 未満なので、実際の角度の誤差は 4.8 × 10^-16 以下です。π × 2^-51 は約 1.4 × 10^-15 で、実際の上限 4.8 × 10^-16 の約 3 倍です。角度の誤差に実際の上限を使って B を求め直した値を、B' とします。B は、B' より相対で 5.6 × 10^-8 以上大きくなっています。この差を余裕と呼びます。余裕が最小になるのは、T が 64 の GPU の経路で、余裕の大半は、κ の α_d T の項から生じます。
|
||||
|
||||
2 つのずれの合計は、2γ_ker が 6 × 10^-11 未満、倍精度の計算の丸めが 10^-9 未満なので、1.1 × 10^-9 未満です。余裕はこの合計の 50 倍を超えるので、上限はずれを含めても成り立ちます。
|
||||
|
||||
---
|
||||
|
||||
## 決定論
|
||||
|
||||
- タイルどうしは互いに独立しています。CPU の経路では、スレッド数と、どのスレッドがどのタイルを受け持つかを変えても、結果は 1 ビットも変わりません。
|
||||
- GPU の経路では、同じデバイスで同じ入力を 2 回計算すると、結果は 1 ビットも変わりません。単体試験と自己試験で確かめています。
|
||||
- 出力の和は、グループの中では決まった木の形で、グループどうしは CPU が決まった順で足します。NaN と無限大の個数、素材の和と 2 乗の和は、整数のアトミック加算で数えます。整数の加算は順序に左右されないので、毎回同じ値になります。
|
||||
- CPU の経路と GPU の経路は、結果が 1 ビット単位では一致するとは限りません。Direct3D の規則では、GPU は加算、減算、乗算の結果を、最も近い値へ丸める代わりに切り捨てることも許されているためです。2 つの経路の差は、それぞれの誤差の上限の和を超えません。
|
||||
|
||||
---
|
||||
|
||||
## メモリ
|
||||
|
||||
GPU の経路で `GpuTileConvolver` が確保するメモリは、次のとおりです。素材と出力のテクスチャは、呼び出し側が用意します。G は、畳み込む範囲を覆うすべてのタイルのグループの数で、タイル数 × T² / 512 に等しい数です。S は、抜き取る位置の数です。
|
||||
|
||||
| 資源 | 大きさ |
|
||||
|---|---|
|
||||
| タイルのバッチ | 16 MB 以下 |
|
||||
| スペクトル | 8 T² バイト。T が 512 のとき 2 MB |
|
||||
| 回転因子 | 4 T バイト |
|
||||
| 検査の材料 | (1 + 10 G + 4 S + S (2r + 1)²) × 4 バイト。CPU から読める写しを含めて、その 2 倍 |
|
||||
| 抜き取る位置 | 128 バイト |
|
||||
| 保存しないときの代わりのバッファー | 16 バイト |
|
||||
| 保存した値 | 畳み込む範囲の 1 画素につき 16 バイト。保存を求めたときだけ |
|
||||
|
||||
タイルのバッチと検査の材料は、それまでで最も大きかった大きさを持ち続けます。
|
||||
|
||||
CPU の経路で `CpuTileConvolver` が持つメモリは、計算したスレッドごとに 16 T² + 32 T バイトです。タイルの分の合計は 64 MB 以下で、T が変わると捨てます。`WorkingBytes` は、いま持っている作業領域のバイト数を返します。ほかに、高速フーリエ変換の要素の並べ替えに使う順序の表を、それまでで最も大きかった T について 4 T バイト持ちます。素材、出力、保存する値の配列は、呼び出し側が用意します。
|
||||
|
||||
---
|
||||
|
||||
## 動作の上限値
|
||||
|
||||
| 項目 | 値 |
|
||||
|---|---|
|
||||
| タイルの一辺 | 64、128、256、512。半径から選ぶのは 128 と 512 |
|
||||
| カーネルの半径 | 2r が T より小さいこと。T が 512 のとき 255 まで |
|
||||
| 抜き取る位置 | 16 か所まで |
|
||||
| GPU のタイルのバッチ | 16 MB まで |
|
||||
| CPU のタイルの作業領域 | 合計 64 MB まで |
|
||||
| CPU の、保存した値から描くときの 1 単位 | 16384 画素 |
|
||||
|
||||
---
|
||||
|
||||
## 制限事項
|
||||
|
||||
- 検査で見つけられるのは、NaN と無限大、総和、16 か所までの抜き取りに表れた誤りだけです。抜き取った位置の外の誤りで、総和が変わらないものは見逃します。
|
||||
- 総和の検査には条件があります。条件を外れる素材の画素があると、正常な GPU でも総和の検査で不合格になることがあります。条件は、[検査の材料と検査](#5-検査の材料と検査)にあります。
|
||||
- カーネルの値は 0 以上でなければなりません。負の値を含むカーネルでは、スペクトルの絶対値が 1 を超えることがあり、上限の導出が成り立たないためです。`KernelSpectrum.Update` は、負の値があると `ArgumentOutOfRangeException` を投げます。
|
||||
- 誤差の上限は、[前提](#前提)が成り立つときの値です。`Math.SinCos` の精度は .NET の仕様で保証されていないため、前提として置いています。
|
||||
- 型はどれも 1 つのスレッドから使う前提です。`CpuTileConvolver` の呼び出しを、複数のスレッドから同時に行わないでください。
|
||||
|
||||
---
|
||||
|
||||
## 動作の確認
|
||||
|
||||
単体試験は xUnit v3 と Microsoft.Testing.Platform で動きます。Wave Optics のリポジトリの直下で、次のコマンドを実行します。
|
||||
|
||||
```bash
|
||||
dotnet test SpectralConvolution/SpectralConvolution.Tests/SpectralConvolution.Tests.csproj -c Release
|
||||
```
|
||||
|
||||
単体試験は次のことを確かめます。
|
||||
|
||||
- CPU と GPU の結果が、`DirectCorrelation` の値との差で上限に収まること。素材の 8 ビットの値がすべて 255 の場面も含みます。
|
||||
- GPU の命令を CPU で実行するソフトウェア アダプターである Microsoft Basic Render Driver でも、上限に収まり、検査に合格すること
|
||||
- CPU の結果がスレッド数によらないこと。GPU の結果が 2 回で 1 ビットも違わないこと
|
||||
- 保存した値から描いた結果が、畳み込みと同時に出力した結果と 1 ビットも違わないこと
|
||||
- CPU の経路で持ち続ける作業領域が、計算したスレッドの分だけで、T が変わると捨てられること
|
||||
- GPU に渡すスペクトルを 1.0005 倍すると、総和の検査で不合格になること
|
||||
- スペクトルの虚部の符号を反転すると、抜き取りの検査で不合格になり、総和の検査は合格のままであること。この反転は、カーネルの上下と左右を反転することに当たります。
|
||||
- スペクトルに NaN を入れると、`nonfinite` の検査で不合格になること
|
||||
- ‖x‖ に √2 T を入れた B ‖x‖ を 255 倍して、小数第 3 位までに四捨五入した値が、[1 画素の上限](#7-1-画素の上限)の 2 つ目の表の値と一致すること。F の項は含みません。
|
||||
|
||||
---
|
||||
|
||||
## 免責事項
|
||||
|
||||
本ライブラリは MIT ライセンスのもとで公開されています。
|
||||
|
||||
本ソフトウェアは「現状のまま」提供されており、明示または黙示を問わず、商品性、特定目的への適合性、および権利非侵害に関する保証を含む、いかなる種類の保証も行いません。
|
||||
|
||||
作者は、本ライブラリの使用または使用不能に起因するいかなる損害についても、一切の責任を負いません。ご利用は自己責任でお願いします。
|
||||
|
||||
---
|
||||
|
||||
## ライセンス
|
||||
|
||||
[MIT License](../LICENSE.txt)
|
||||
@@ -0,0 +1,17 @@
|
||||
namespace SpectralConvolution.Tests;
|
||||
|
||||
internal static class AllocationProbe
|
||||
{
|
||||
public static long MinimumAllocatedBytes(Action action, int rounds)
|
||||
{
|
||||
var minimum = long.MaxValue;
|
||||
for (var round = 0; round < rounds; round++)
|
||||
{
|
||||
var before = GC.GetAllocatedBytesForCurrentThread();
|
||||
action();
|
||||
minimum = Math.Min(minimum, GC.GetAllocatedBytesForCurrentThread() - before);
|
||||
}
|
||||
|
||||
return minimum;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,95 @@
|
||||
namespace SpectralConvolution.Tests;
|
||||
|
||||
public sealed class ConvolutionBoundTests
|
||||
{
|
||||
[Theory]
|
||||
[InlineData(64, 0.296, 0.166)]
|
||||
[InlineData(128, 0.688, 0.385)]
|
||||
[InlineData(256, 1.566, 0.877)]
|
||||
[InlineData(512, 3.514, 1.966)]
|
||||
public void TheWorstCaseTileStaysWithinTheDerivedNumberOfLevels(int size, double gpuLevels, double cpuLevels)
|
||||
{
|
||||
var norm = Math.Sqrt(2d * size * size);
|
||||
|
||||
Assert.Equal(gpuLevels, ConvolutionBound.Relative(size, ConvolutionBound.GpuOperationError) * norm * 255d, 3);
|
||||
Assert.Equal(cpuLevels, ConvolutionBound.Relative(size, ConvolutionBound.CpuOperationError) * norm * 255d, 3);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void TheBoundGrowsWithTheTileAndTheOperationError()
|
||||
{
|
||||
int[] sizes = [64, 128, 256, 512];
|
||||
for (var index = 1; index < sizes.Length; index++)
|
||||
{
|
||||
Assert.True(ConvolutionBound.Relative(sizes[index], ConvolutionBound.GpuOperationError)
|
||||
> ConvolutionBound.Relative(sizes[index - 1], ConvolutionBound.GpuOperationError));
|
||||
Assert.True(ConvolutionBound.FlushedOperations(sizes[index]) > ConvolutionBound.FlushedOperations(sizes[index - 1]));
|
||||
}
|
||||
|
||||
foreach (var size in sizes)
|
||||
Assert.True(ConvolutionBound.Relative(size, ConvolutionBound.GpuOperationError) > ConvolutionBound.Relative(size, ConvolutionBound.CpuOperationError));
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[InlineData(64)]
|
||||
[InlineData(512)]
|
||||
public void TheSpectrumErrorIsDominatedBySingleRounding(int size)
|
||||
{
|
||||
var error = ConvolutionBound.SpectrumError(size);
|
||||
|
||||
Assert.True(error > ConvolutionBound.SingleRounding);
|
||||
Assert.True(error < ConvolutionBound.SingleRounding + 1e-10);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void TheTwiddleErrorCoversRoundingToSinglePrecision()
|
||||
{
|
||||
Assert.True(ConvolutionBound.SingleTwiddleError > ConvolutionBound.SingleRounding);
|
||||
Assert.True(ConvolutionBound.DoubleTwiddleError > ConvolutionBound.TwiddleAngleError);
|
||||
Assert.True(ConvolutionBound.DoubleTwiddleError < 1e-14);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void GammaMatchesItsDefinition()
|
||||
{
|
||||
Assert.Equal(0d, ConvolutionBound.Gamma(0, ConvolutionBound.GpuOperationError));
|
||||
var unit = ConvolutionBound.GpuOperationError;
|
||||
Assert.Equal(3d * unit / (1d - 3d * unit), ConvolutionBound.Gamma(3, unit));
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[InlineData(-1, 0.1)]
|
||||
[InlineData(10, 0.1)]
|
||||
[InlineData(1, -0.1)]
|
||||
[InlineData(1, double.NaN)]
|
||||
public void GammaRejectsMeaninglessArguments(int operations, double unit)
|
||||
{
|
||||
Assert.Throws<ArgumentOutOfRangeException>(() => ConvolutionBound.Gamma(operations, unit));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void FlushingAddsFarLessThanOneLevel()
|
||||
{
|
||||
Assert.True(ConvolutionBound.FlushedOperations(512) * ConvolutionBound.SmallestNormal < 1e-30);
|
||||
Assert.True(ConvolutionBound.Absolute(512, ConvolutionBound.GpuOperationError, 0d) > 0d);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void TheAbsoluteBoundScalesWithTheNorm()
|
||||
{
|
||||
var size = 128;
|
||||
var flush = ConvolutionBound.FlushedOperations(size) * ConvolutionBound.SmallestNormal;
|
||||
var relative = ConvolutionBound.Relative(size, ConvolutionBound.GpuOperationError);
|
||||
|
||||
Assert.Equal(relative * 3d + flush, ConvolutionBound.Absolute(size, ConvolutionBound.GpuOperationError, 3d));
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[InlineData(-1d)]
|
||||
[InlineData(double.NaN)]
|
||||
[InlineData(double.PositiveInfinity)]
|
||||
public void AnInvalidNormIsRejected(double norm)
|
||||
{
|
||||
Assert.Throws<ArgumentOutOfRangeException>(() => ConvolutionBound.Absolute(128, ConvolutionBound.GpuOperationError, norm));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,118 @@
|
||||
namespace SpectralConvolution.Tests;
|
||||
|
||||
internal sealed class ConvolutionScene
|
||||
{
|
||||
(double RedGreen, double BlueAlpha)[]? tileNorms;
|
||||
|
||||
ConvolutionScene(byte[] source, int sourceX, int sourceY, int sourceWidth, int sourceHeight, KernelSpectrum spectrum, TilePlan plan)
|
||||
{
|
||||
Source = source;
|
||||
SourceX = sourceX;
|
||||
SourceY = sourceY;
|
||||
SourceWidth = sourceWidth;
|
||||
SourceHeight = sourceHeight;
|
||||
Spectrum = spectrum;
|
||||
Plan = plan;
|
||||
}
|
||||
|
||||
public byte[] Source { get; }
|
||||
|
||||
public int SourceX { get; }
|
||||
|
||||
public int SourceY { get; }
|
||||
|
||||
public int SourceWidth { get; }
|
||||
|
||||
public int SourceHeight { get; }
|
||||
|
||||
public KernelSpectrum Spectrum { get; }
|
||||
|
||||
public TilePlan Plan { get; }
|
||||
|
||||
public int RegionLength => Plan.RegionWidth * Plan.RegionHeight * 4;
|
||||
|
||||
public static double[] AsymmetricKernel(int radius)
|
||||
{
|
||||
var size = radius * 2 + 1;
|
||||
var values = new double[size * size];
|
||||
for (var y = 0; y < size; y++)
|
||||
{
|
||||
for (var x = 0; x < size; x++)
|
||||
{
|
||||
var dx = x - radius * 0.6;
|
||||
var dy = y - radius * 1.3;
|
||||
values[y * size + x] = Math.Exp(-(dx * dx * 0.4 + dy * dy * 0.15) / (radius * radius + 1d)) + (x == 0 && y == size - 1 ? 0.5 : 0d);
|
||||
}
|
||||
}
|
||||
|
||||
return values;
|
||||
}
|
||||
|
||||
public static byte[] RandomSource(int width, int height, int seed, double litFraction)
|
||||
{
|
||||
var random = new Random(seed);
|
||||
var pixels = new byte[width * height * 4];
|
||||
for (var index = 0; index < width * height; index++)
|
||||
{
|
||||
if (random.NextDouble() >= litFraction)
|
||||
continue;
|
||||
var alpha = (byte)random.Next(1, 256);
|
||||
pixels[index * 4] = (byte)random.Next(alpha + 1);
|
||||
pixels[index * 4 + 1] = (byte)random.Next(alpha + 1);
|
||||
pixels[index * 4 + 2] = (byte)random.Next(alpha + 1);
|
||||
pixels[index * 4 + 3] = alpha;
|
||||
}
|
||||
|
||||
return pixels;
|
||||
}
|
||||
|
||||
public static byte[] Uniform(int width, int height, byte value)
|
||||
{
|
||||
var pixels = new byte[width * height * 4];
|
||||
Array.Fill(pixels, value);
|
||||
return pixels;
|
||||
}
|
||||
|
||||
public static ConvolutionScene Create(byte[] source, int sourceWidth, int sourceHeight, int margin, int radius, int size)
|
||||
{
|
||||
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);
|
||||
}
|
||||
|
||||
public void Reference(int x, int y, Span<double> result)
|
||||
=> DirectCorrelation.Evaluate(Source, SourceWidth, SourceHeight, Spectrum.Kernel, Spectrum.Radius, x - SourceX, y - SourceY, result);
|
||||
|
||||
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))];
|
||||
return tileNorms[Plan.TileAt(x, y)];
|
||||
}
|
||||
|
||||
public double WorstRatio(ReadOnlySpan<float> convolved, double operationError)
|
||||
{
|
||||
var reference = new double[4];
|
||||
var worst = 0d;
|
||||
var referenceError = DirectCorrelation.ErrorBound(Spectrum.Kernel.Length);
|
||||
for (var y = 0; y < Plan.RegionHeight; y++)
|
||||
{
|
||||
for (var x = 0; x < Plan.RegionWidth; x++)
|
||||
{
|
||||
var canvasX = Plan.RegionX + x;
|
||||
var canvasY = Plan.RegionY + y;
|
||||
Reference(canvasX, canvasY, reference);
|
||||
var (redGreen, blueAlpha) = Norms(canvasX, canvasY);
|
||||
var index = (y * Plan.RegionWidth + x) * 4;
|
||||
for (var channel = 0; channel < 4; channel++)
|
||||
{
|
||||
var norm = channel < 2 ? redGreen : blueAlpha;
|
||||
var bound = ConvolutionBound.Absolute(Plan.Size, operationError, norm) + referenceError;
|
||||
worst = Math.Max(worst, Math.Abs(convolved[index + channel] - reference[channel]) / bound);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return worst;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,265 @@
|
||||
namespace SpectralConvolution.Tests;
|
||||
|
||||
public sealed class CpuTileConvolverTests
|
||||
{
|
||||
static (byte[] Output, float[] Convolved) Run(ConvolutionScene scene, int threads, float gain = 1f)
|
||||
{
|
||||
var output = new byte[scene.RegionLength];
|
||||
var convolved = new float[scene.RegionLength];
|
||||
using var convolver = new CpuTileConvolver(threads);
|
||||
convolver.Convolve(scene.Source, scene.SourceX, scene.SourceY, scene.SourceWidth, scene.SourceHeight, scene.Spectrum, scene.Plan, output, gain, convolved);
|
||||
return (output, convolved);
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[InlineData(64, 5, 150, 97, 11)]
|
||||
[InlineData(128, 23, 140, 90, 24)]
|
||||
[InlineData(64, 0, 70, 70, 3)]
|
||||
public void TheResultStaysWithinTheBoundOfTheExactCorrelation(int size, int radius, int width, int height, int margin)
|
||||
{
|
||||
var scene = ConvolutionScene.Create(ConvolutionScene.RandomSource(width, height, size + radius, 0.4), width, height, margin, radius, size);
|
||||
|
||||
var (_, convolved) = Run(scene, 3);
|
||||
|
||||
Assert.True(scene.Plan.TileCount > 1);
|
||||
Assert.InRange(scene.WorstRatio(convolved, ConvolutionBound.CpuOperationError), 0d, 1d);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void AnOpaqueWhiteSceneStaysWithinTheBound()
|
||||
{
|
||||
var scene = ConvolutionScene.Create(ConvolutionScene.Uniform(120, 120, 255), 120, 120, 8, 7, 64);
|
||||
|
||||
var (output, convolved) = Run(scene, 2);
|
||||
|
||||
Assert.InRange(scene.WorstRatio(convolved, ConvolutionBound.CpuOperationError), 0d, 1d);
|
||||
var center = ((scene.Plan.RegionHeight / 2) * scene.Plan.RegionWidth + scene.Plan.RegionWidth / 2) * 4;
|
||||
Assert.Equal([255, 255, 255, 255], output.AsSpan(center, 4).ToArray());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void TheResultDoesNotDependOnTheNumberOfThreads()
|
||||
{
|
||||
var scene = ConvolutionScene.Create(ConvolutionScene.RandomSource(300, 170, 5, 0.6), 300, 170, 16, 9, 64);
|
||||
|
||||
var single = Run(scene, 1, 1.75f);
|
||||
var several = Run(scene, 3, 1.75f);
|
||||
var many = Run(scene, 16, 1.75f);
|
||||
|
||||
Assert.Equal(single.Output, several.Output);
|
||||
Assert.Equal(single.Output, many.Output);
|
||||
Assert.Equal(single.Convolved, several.Convolved);
|
||||
Assert.Equal(single.Convolved, many.Convolved);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void TheOutputIsTheGainAppliedToTheConvolution()
|
||||
{
|
||||
var scene = ConvolutionScene.Create(ConvolutionScene.RandomSource(90, 60, 9, 0.7), 90, 60, 8, 4, 64);
|
||||
|
||||
var (output, convolved) = Run(scene, 2, 2.5f);
|
||||
|
||||
for (var index = 0; index < output.Length; index += 4)
|
||||
{
|
||||
Assert.Equal(CpuTileConvolver.ToUnorm(convolved[index + 2] * 2.5f), output[index]);
|
||||
Assert.Equal(CpuTileConvolver.ToUnorm(convolved[index + 1] * 2.5f), output[index + 1]);
|
||||
Assert.Equal(CpuTileConvolver.ToUnorm(convolved[index] * 2.5f), output[index + 2]);
|
||||
Assert.Equal(CpuTileConvolver.ToUnorm(convolved[index + 3] * 2.5f), output[index + 3]);
|
||||
}
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void ARegionAwayFromTheSourceIsClearedToZero()
|
||||
{
|
||||
var spectrum = new KernelSpectrum();
|
||||
spectrum.Update(ConvolutionScene.AsymmetricKernel(3), 3, 64);
|
||||
var plan = TilePlan.Create(64, 3, 500, 500, 130, 70);
|
||||
var output = new byte[plan.RegionWidth * plan.RegionHeight * 4];
|
||||
var convolved = new float[output.Length];
|
||||
Array.Fill(output, (byte)7);
|
||||
Array.Fill(convolved, 7f);
|
||||
using var convolver = new CpuTileConvolver(2);
|
||||
|
||||
convolver.Convolve(ConvolutionScene.Uniform(40, 40, 255), 0, 0, 40, 40, spectrum, plan, output, 1f, convolved);
|
||||
|
||||
Assert.All(output, value => Assert.Equal(0, value));
|
||||
Assert.All(convolved, value => Assert.Equal(0f, value));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void TheStoreIsOptional()
|
||||
{
|
||||
var scene = ConvolutionScene.Create(ConvolutionScene.RandomSource(80, 50, 3, 0.5), 80, 50, 8, 4, 64);
|
||||
var expected = Run(scene, 2).Output;
|
||||
var output = new byte[scene.RegionLength];
|
||||
using var convolver = new CpuTileConvolver(2);
|
||||
|
||||
convolver.Convolve(scene.Source, scene.SourceX, scene.SourceY, scene.SourceWidth, scene.SourceHeight, scene.Spectrum, scene.Plan, output, 1f, null);
|
||||
|
||||
Assert.Equal(expected, output);
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[InlineData(1f)]
|
||||
[InlineData(2.75f)]
|
||||
[InlineData(0.3f)]
|
||||
public void RenderingTheStoreMatchesTheConvolutionBitForBit(float gain)
|
||||
{
|
||||
var scene = ConvolutionScene.Create(ConvolutionScene.RandomSource(130, 90, 13, 0.6), 130, 90, 8, 4, 64);
|
||||
var (expected, _) = Run(scene, 3, gain);
|
||||
var (_, stored) = Run(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);
|
||||
|
||||
Assert.Equal(expected, output);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void RenderingTheStoreDoesNotDependOnTheNumberOfThreads()
|
||||
{
|
||||
var pixels = CpuTileConvolver.StoredChunkPixels * 3 + 17;
|
||||
var random = new Random(3);
|
||||
var stored = new float[pixels * 4];
|
||||
for (var index = 0; index < stored.Length; index++)
|
||||
stored[index] = (float)(random.NextDouble() * 1.2 - 0.1);
|
||||
var single = new byte[stored.Length];
|
||||
var several = new byte[stored.Length];
|
||||
using (var convolver = new CpuTileConvolver(1))
|
||||
convolver.RenderStored(stored, pixels, 1.3f, single);
|
||||
using (var convolver = new CpuTileConvolver(6))
|
||||
convolver.RenderStored(stored, pixels, 1.3f, several);
|
||||
|
||||
Assert.Equal(single, several);
|
||||
for (var pixel = 0; pixel < pixels; pixel++)
|
||||
{
|
||||
Assert.Equal(CpuTileConvolver.ToUnorm(stored[pixel * 4 + 2] * 1.3f), single[pixel * 4]);
|
||||
Assert.Equal(CpuTileConvolver.ToUnorm(stored[pixel * 4] * 1.3f), single[pixel * 4 + 2]);
|
||||
}
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void RenderingTheStoreRejectsShortBuffers()
|
||||
{
|
||||
using var convolver = new CpuTileConvolver(2);
|
||||
|
||||
Assert.Throws<ArgumentException>(() => convolver.RenderStored(new float[7], 2, 1f, new byte[8]));
|
||||
Assert.Throws<ArgumentException>(() => convolver.RenderStored(new float[8], 2, 1f, new byte[7]));
|
||||
Assert.Throws<ArgumentOutOfRangeException>(() => convolver.RenderStored(new float[8], 2, float.PositiveInfinity, new byte[8]));
|
||||
convolver.RenderStored([], 0, 1f, []);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void AWarmStoredRenderAllocatesNothingOnTheCallingThread()
|
||||
{
|
||||
var pixels = CpuTileConvolver.StoredChunkPixels * 4;
|
||||
var stored = new float[pixels * 4];
|
||||
var output = new byte[pixels * 4];
|
||||
using var convolver = new CpuTileConvolver(4);
|
||||
for (var warmUp = 0; warmUp < 3; warmUp++)
|
||||
convolver.RenderStored(stored, pixels, 1f, output);
|
||||
|
||||
var minimum = AllocationProbe.MinimumAllocatedBytes(() => convolver.RenderStored(stored, pixels, 1f, output), 20);
|
||||
|
||||
Assert.Equal(0L, minimum);
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[InlineData(float.NaN, 0)]
|
||||
[InlineData(-0.25f, 0)]
|
||||
[InlineData(0f, 0)]
|
||||
[InlineData(1f / 255f, 1)]
|
||||
[InlineData(0.5f, 128)]
|
||||
[InlineData(1f, 255)]
|
||||
[InlineData(3f, 255)]
|
||||
[InlineData(float.PositiveInfinity, 255)]
|
||||
public void ConversionFollowsTheDirect3DRule(float value, byte expected)
|
||||
{
|
||||
Assert.Equal(expected, CpuTileConvolver.ToUnorm(value));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void MismatchedArgumentsAreRejected()
|
||||
{
|
||||
var scene = ConvolutionScene.Create(ConvolutionScene.Uniform(20, 20, 9), 20, 20, 4, 2, 64);
|
||||
using var convolver = new CpuTileConvolver(1);
|
||||
var output = new byte[scene.RegionLength];
|
||||
var otherSpectrum = new KernelSpectrum();
|
||||
otherSpectrum.Update(ConvolutionScene.AsymmetricKernel(3), 3, 64);
|
||||
|
||||
Assert.Throws<ArgumentException>(() => convolver.Convolve(scene.Source, 4, 4, 20, 20, otherSpectrum, scene.Plan, output, 1f, null));
|
||||
Assert.Throws<ArgumentException>(() => convolver.Convolve(scene.Source, 4, 4, 20, 21, scene.Spectrum, scene.Plan, output, 1f, null));
|
||||
Assert.Throws<ArgumentException>(() => convolver.Convolve(scene.Source, 4, 4, 20, 20, scene.Spectrum, scene.Plan, new byte[output.Length - 1], 1f, null));
|
||||
Assert.Throws<ArgumentException>(() => convolver.Convolve(scene.Source, 4, 4, 20, 20, scene.Spectrum, scene.Plan, output, 1f, new float[output.Length - 1]));
|
||||
Assert.Throws<ArgumentOutOfRangeException>(() => convolver.Convolve(scene.Source, 4, 4, 20, 20, scene.Spectrum, scene.Plan, output, float.NaN, null));
|
||||
Assert.Throws<ArgumentOutOfRangeException>(() => new CpuTileConvolver(0));
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[InlineData(1)]
|
||||
[InlineData(4)]
|
||||
public void AWarmConvolutionAllocatesNothingOnTheCallingThread(int threads)
|
||||
{
|
||||
var scene = ConvolutionScene.Create(ConvolutionScene.RandomSource(200, 120, 1, 0.3), 200, 120, 12, 6, 64);
|
||||
var output = new byte[scene.RegionLength];
|
||||
var convolved = new float[scene.RegionLength];
|
||||
using var convolver = new CpuTileConvolver(threads);
|
||||
for (var warmUp = 0; warmUp < 3; warmUp++)
|
||||
convolver.Convolve(scene.Source, scene.SourceX, scene.SourceY, scene.SourceWidth, scene.SourceHeight, scene.Spectrum, scene.Plan, output, 1f, convolved);
|
||||
|
||||
var minimum = AllocationProbe.MinimumAllocatedBytes(
|
||||
() => convolver.Convolve(scene.Source, scene.SourceX, scene.SourceY, scene.SourceWidth, scene.SourceHeight, scene.Spectrum, scene.Plan, output, 1f, convolved),
|
||||
40);
|
||||
|
||||
Assert.Equal(0L, minimum);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void ADisposedConvolverRefusesWork()
|
||||
{
|
||||
var scene = ConvolutionScene.Create(ConvolutionScene.Uniform(20, 20, 9), 20, 20, 4, 2, 64);
|
||||
var convolver = new CpuTileConvolver(3);
|
||||
convolver.Convolve(scene.Source, 4, 4, 20, 20, scene.Spectrum, scene.Plan, new byte[scene.RegionLength], 1f, null);
|
||||
|
||||
convolver.Dispose();
|
||||
convolver.Dispose();
|
||||
|
||||
Assert.Throws<ObjectDisposedException>(() => convolver.Convolve(scene.Source, 4, 4, 20, 20, scene.Spectrum, scene.Plan, new byte[scene.RegionLength], 1f, null));
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[InlineData(128, 256)]
|
||||
[InlineData(512, 16)]
|
||||
public void TheWorkingSetLimitsTheThreads(int size, int expected)
|
||||
{
|
||||
Assert.Equal(expected, CpuTileConvolver.ActiveThreads(1000, size));
|
||||
Assert.Equal(3, CpuTileConvolver.ActiveThreads(3, size));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void OnlyTheThreadsThatComputeKeepAWorkingAreaOfTheCurrentSize()
|
||||
{
|
||||
static long PerThread(int size) => ((long)size * size * 4 + size * 4 * 2) * sizeof(float);
|
||||
static void Convolve(CpuTileConvolver convolver, int size, int radius, int regionSide)
|
||||
{
|
||||
var spectrum = new KernelSpectrum();
|
||||
spectrum.Update(ConvolutionScene.AsymmetricKernel(radius), radius, size);
|
||||
var plan = TilePlan.Create(size, radius, 0, 0, regionSide, regionSide);
|
||||
var source = ConvolutionScene.Uniform(16, 16, 200);
|
||||
for (var run = 0; run < 4; run++)
|
||||
convolver.Convolve(source, 40, 40, 16, 16, spectrum, plan, new byte[plan.RegionWidth * plan.RegionHeight * 4], 1f, null);
|
||||
}
|
||||
|
||||
using var convolver = new CpuTileConvolver(24);
|
||||
|
||||
Convolve(convolver, 512, 24, 600);
|
||||
Assert.Equal(4 * PerThread(512), convolver.WorkingBytes);
|
||||
|
||||
Convolve(convolver, 512, 24, 2000);
|
||||
Assert.Equal(16 * PerThread(512), convolver.WorkingBytes);
|
||||
|
||||
Convolve(convolver, 128, 3, 610);
|
||||
Assert.Equal(24 * PerThread(128), convolver.WorkingBytes);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,146 @@
|
||||
namespace SpectralConvolution.Tests;
|
||||
|
||||
public sealed class DirectCorrelationTests
|
||||
{
|
||||
static double[] Kernel(int radius)
|
||||
{
|
||||
var size = radius * 2 + 1;
|
||||
var values = new double[size * size];
|
||||
for (var index = 0; index < values.Length; index++)
|
||||
values[index] = index + 1d;
|
||||
var sum = values.Sum();
|
||||
for (var index = 0; index < values.Length; index++)
|
||||
values[index] /= sum;
|
||||
return values;
|
||||
}
|
||||
|
||||
static byte[] Image(int width, int height, int x, int y, byte blue, byte green, byte red, byte alpha)
|
||||
{
|
||||
var pixels = new byte[width * height * 4];
|
||||
var offset = (y * width + x) * 4;
|
||||
pixels[offset] = blue;
|
||||
pixels[offset + 1] = green;
|
||||
pixels[offset + 2] = red;
|
||||
pixels[offset + 3] = alpha;
|
||||
return pixels;
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void PackingPutsRedInTheLowestByte()
|
||||
{
|
||||
Assert.Equal(0x44332211u, DirectCorrelation.Pack(0x11, 0x22, 0x33, 0x44));
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[InlineData(10, 10)]
|
||||
[InlineData(9, 11)]
|
||||
[InlineData(12, 8)]
|
||||
public void AnImpulseReadsTheKernelAtTheOffsetFromThePoint(int x, int y)
|
||||
{
|
||||
const int radius = 2;
|
||||
var kernel = Kernel(radius);
|
||||
var image = Image(20, 20, 10, 10, 0, 0, 255, 0);
|
||||
var result = new double[4];
|
||||
|
||||
DirectCorrelation.Evaluate(image, 20, 20, kernel, radius, x, y, result);
|
||||
|
||||
var offsetX = 10 - x;
|
||||
var offsetY = 10 - y;
|
||||
Assert.Equal(kernel[(offsetY + radius) * 5 + offsetX + radius], result[0], 15);
|
||||
Assert.Equal(0d, result[1]);
|
||||
Assert.Equal(0d, result[2]);
|
||||
Assert.Equal(0d, result[3]);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void ChannelsKeepTheirOrder()
|
||||
{
|
||||
const int radius = 1;
|
||||
var kernel = Kernel(radius);
|
||||
var image = Image(3, 3, 1, 1, 30, 20, 10, 40);
|
||||
var result = new double[4];
|
||||
|
||||
DirectCorrelation.Evaluate(image, 3, 3, kernel, radius, 1, 1, result);
|
||||
|
||||
var center = kernel[4];
|
||||
Assert.Equal(10 / 255d * center, result[0], 15);
|
||||
Assert.Equal(20 / 255d * center, result[1], 15);
|
||||
Assert.Equal(30 / 255d * center, result[2], 15);
|
||||
Assert.Equal(40 / 255d * center, result[3], 15);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void PixelsOutsideTheImageCountAsZero()
|
||||
{
|
||||
const int radius = 2;
|
||||
var kernel = Kernel(radius);
|
||||
var image = new byte[4 * 4 * 4];
|
||||
Array.Fill(image, (byte)255);
|
||||
var result = new double[4];
|
||||
|
||||
DirectCorrelation.Evaluate(image, 4, 4, kernel, radius, 0, 0, result);
|
||||
|
||||
var expected = 0d;
|
||||
for (var offsetY = 0; offsetY <= radius; offsetY++)
|
||||
{
|
||||
for (var offsetX = 0; offsetX <= radius; offsetX++)
|
||||
expected += kernel[(offsetY + radius) * 5 + offsetX + radius];
|
||||
}
|
||||
Assert.Equal(expected, result[3], 14);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void AGatheredNeighborhoodGivesTheSameValueAsTheImage()
|
||||
{
|
||||
const int radius = 3;
|
||||
const int width = 23;
|
||||
const int height = 17;
|
||||
var kernel = Kernel(radius);
|
||||
var random = new Random(7);
|
||||
var image = new byte[width * height * 4];
|
||||
random.NextBytes(image);
|
||||
var neighborhood = new uint[kernel.Length];
|
||||
const int x = 2;
|
||||
const int y = 15;
|
||||
for (var offsetY = -radius; offsetY <= radius; offsetY++)
|
||||
{
|
||||
for (var offsetX = -radius; offsetX <= radius; offsetX++)
|
||||
{
|
||||
var sourceX = x + offsetX;
|
||||
var sourceY = y + offsetY;
|
||||
if (sourceX < 0 || sourceX >= width || sourceY < 0 || sourceY >= height)
|
||||
continue;
|
||||
var offset = (sourceY * width + sourceX) * 4;
|
||||
neighborhood[(offsetY + radius) * 7 + offsetX + radius] = DirectCorrelation.Pack(image[offset + 2], image[offset + 1], image[offset], image[offset + 3]);
|
||||
}
|
||||
}
|
||||
var fromImage = new double[4];
|
||||
var fromNeighborhood = new double[4];
|
||||
|
||||
DirectCorrelation.Evaluate(image, width, height, kernel, radius, x, y, fromImage);
|
||||
DirectCorrelation.Evaluate(neighborhood, kernel, fromNeighborhood);
|
||||
|
||||
Assert.Equal(fromImage, fromNeighborhood);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void MismatchedLengthsAreRejected()
|
||||
{
|
||||
var kernel = Kernel(1);
|
||||
|
||||
Assert.Throws<ArgumentException>(() => DirectCorrelation.Evaluate(new uint[8], kernel, new double[4]));
|
||||
Assert.Throws<ArgumentException>(() => DirectCorrelation.Evaluate(new uint[9], kernel, new double[3]));
|
||||
Assert.Throws<ArgumentException>(() => DirectCorrelation.Evaluate(new byte[16], 2, 2, kernel, 2, 0, 0, new double[4]));
|
||||
Assert.Throws<ArgumentException>(() => DirectCorrelation.Evaluate(new byte[15], 2, 2, kernel, 1, 0, 0, new double[4]));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void TheReferenceErrorIsTiny()
|
||||
{
|
||||
var bound = DirectCorrelation.ErrorBound(127 * 127);
|
||||
|
||||
Assert.True(bound > 0d);
|
||||
Assert.True(bound < 1e-11);
|
||||
Assert.Throws<ArgumentOutOfRangeException>(() => DirectCorrelation.ErrorBound(0));
|
||||
}
|
||||
}
|
||||
+4
-7
@@ -1,6 +1,4 @@
|
||||
using WaveOptics.Fourier;
|
||||
|
||||
namespace WaveOptics.Tests.Fourier;
|
||||
namespace SpectralConvolution.Tests;
|
||||
|
||||
public sealed class FastFourierTransformTests
|
||||
{
|
||||
@@ -69,14 +67,13 @@ public sealed class FastFourierTransformTests
|
||||
FastFourierTransform.Forward(real, imaginary);
|
||||
FastFourierTransform.Inverse(real, imaginary);
|
||||
|
||||
var before = GC.GetAllocatedBytesForCurrentThread();
|
||||
for (var index = 0; index < 16; index++)
|
||||
var minimum = AllocationProbe.MinimumAllocatedBytes(() =>
|
||||
{
|
||||
FastFourierTransform.Forward(real, imaginary);
|
||||
FastFourierTransform.Inverse(real, imaginary);
|
||||
}
|
||||
}, 64);
|
||||
|
||||
Assert.Equal(0, GC.GetAllocatedBytesForCurrentThread() - before);
|
||||
Assert.Equal(0L, minimum);
|
||||
}
|
||||
|
||||
static void AssertMaximumError(double[] expectedReal, double[] expectedImaginary, double[] actualReal, double[] actualImaginary, double tolerance)
|
||||
@@ -0,0 +1,346 @@
|
||||
using System.Runtime.InteropServices;
|
||||
using ComputeWeave;
|
||||
|
||||
namespace SpectralConvolution.Tests;
|
||||
|
||||
[Collection("Direct3D12")]
|
||||
public sealed class GpuTileConvolverTests
|
||||
{
|
||||
sealed record GpuRun(byte[] Output, float[] Store, uint[] Report, GpuTileJob Job, Int2[] Samples, float[] Spectrum);
|
||||
|
||||
static GraphicsDevice HardwareOrDefault() => GraphicsDevice.GetDefault();
|
||||
|
||||
static GraphicsDevice Software() => GraphicsDevice.EnumerateDevices().First(device => !device.IsHardwareAccelerated);
|
||||
|
||||
static Int2[] Samples(in TilePlan plan)
|
||||
{
|
||||
var width = plan.RegionWidth;
|
||||
var height = plan.RegionHeight;
|
||||
var valid = plan.ValidSize;
|
||||
List<Int2> samples =
|
||||
[
|
||||
new(0, 0), new(width - 1, 0), new(0, height - 1), new(width - 1, height - 1), new(width / 2, height / 2),
|
||||
new(Math.Min(valid - 1, width - 1), Math.Min(valid - 1, height - 1)), new(Math.Min(valid, width - 1), Math.Min(valid, height - 1)),
|
||||
];
|
||||
var random = new Random(width * 31 + height);
|
||||
while (samples.Count < GpuTileConvolver.MaximumSamples)
|
||||
samples.Add(new Int2(random.Next(width), random.Next(height)));
|
||||
return [.. samples];
|
||||
}
|
||||
|
||||
static GpuRun Run(GraphicsDevice device, ConvolutionScene scene, float gain = 1f, Func<float[], float[]>? tamper = null)
|
||||
{
|
||||
using var convolver = new GpuTileConvolver(device);
|
||||
return Run(device, convolver, scene, gain, tamper);
|
||||
}
|
||||
|
||||
static GpuRun Run(GraphicsDevice device, GpuTileConvolver convolver, ConvolutionScene scene, float gain = 1f, Func<float[], float[]>? tamper = null)
|
||||
{
|
||||
var plan = scene.Plan;
|
||||
var samples = Samples(plan);
|
||||
convolver.Upload(scene.Spectrum);
|
||||
var spectrum = MemoryMarshal.Cast<Float2, float>(scene.Spectrum.Spectrum).ToArray();
|
||||
if (tamper is not null)
|
||||
{
|
||||
spectrum = tamper(spectrum);
|
||||
convolver.Spectrum.CopyFrom(MemoryMarshal.Cast<float, Float2>(spectrum));
|
||||
}
|
||||
|
||||
var job = convolver.Prepare(plan, scene.SourceX, scene.SourceY, scene.SourceWidth, scene.SourceHeight, gain, samples, true);
|
||||
using var source = device.AllocateReadWriteTexture2D<Bgra32, Float4>(scene.SourceWidth, scene.SourceHeight);
|
||||
source.CopyFrom(MemoryMarshal.Cast<byte, Bgra32>(scene.Source));
|
||||
using var output = device.AllocateReadWriteTexture2D<Bgra32, Float4>(plan.RegionWidth, plan.RegionHeight);
|
||||
using (var context = device.CreateComputeContext())
|
||||
{
|
||||
GpuTileConvolver.Record(
|
||||
in context, source, output, convolver.Tiles, convolver.Twiddles, convolver.Spectrum,
|
||||
convolver.Report, convolver.Samples, convolver.StoreFor(job), job);
|
||||
}
|
||||
|
||||
var report = convolver.ReadReport(job).ToArray();
|
||||
var store = new Float4[plan.RegionWidth * plan.RegionHeight];
|
||||
convolver.ReadStore(job, store);
|
||||
var pixels = new Bgra32[plan.RegionWidth * plan.RegionHeight];
|
||||
output.CopyTo(pixels);
|
||||
return new GpuRun(
|
||||
MemoryMarshal.Cast<Bgra32, byte>(pixels).ToArray(),
|
||||
MemoryMarshal.Cast<Float4, float>(store).ToArray(),
|
||||
report,
|
||||
job,
|
||||
samples,
|
||||
spectrum);
|
||||
}
|
||||
|
||||
static ConvolutionMeasurement[] Measure(ConvolutionScene scene, GpuRun run)
|
||||
{
|
||||
var measurements = new ConvolutionMeasurement[GpuTileCheck.MeasurementCount(run.Samples.Length)];
|
||||
GpuTileCheck.Evaluate(run.Report, run.Job, run.Samples, scene.Spectrum.Kernel, measurements);
|
||||
return measurements;
|
||||
}
|
||||
|
||||
static ConvolutionScene Scene(int size, int radius, int width, int height, int margin, int seed)
|
||||
=> ConvolutionScene.Create(ConvolutionScene.RandomSource(width, height, seed, 0.45), width, height, margin, radius, size);
|
||||
|
||||
[Theory]
|
||||
[InlineData(64, 5, 150, 97, 11)]
|
||||
[InlineData(128, 23, 140, 90, 24)]
|
||||
[InlineData(512, 3, 1100, 560, 8)]
|
||||
public void TheResultStaysWithinTheBoundOfTheExactCorrelation(int size, int radius, int width, int height, int margin)
|
||||
{
|
||||
var scene = Scene(size, radius, width, height, margin, size + radius);
|
||||
|
||||
var run = Run(HardwareOrDefault(), scene);
|
||||
|
||||
Assert.True(scene.Plan.TileCount > 1);
|
||||
Assert.InRange(scene.WorstRatio(run.Store, ConvolutionBound.GpuOperationError), 0d, 1d);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void SeveralBatchesProduceEveryTile()
|
||||
{
|
||||
var scene = Scene(512, 3, 1100, 560, 8, 2);
|
||||
|
||||
Assert.True(scene.Plan.TileCount > scene.Plan.BatchTiles);
|
||||
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}"));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void AnOpaqueWhiteSceneStaysWithinTheBound()
|
||||
{
|
||||
var scene = ConvolutionScene.Create(ConvolutionScene.Uniform(120, 120, 255), 120, 120, 8, 7, 64);
|
||||
|
||||
var run = Run(HardwareOrDefault(), scene);
|
||||
|
||||
Assert.InRange(scene.WorstRatio(run.Store, ConvolutionBound.GpuOperationError), 0d, 1d);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void TwoRunsAgreeBitForBit()
|
||||
{
|
||||
var scene = Scene(128, 9, 300, 170, 16, 5);
|
||||
|
||||
var first = Run(HardwareOrDefault(), scene, 1.5f);
|
||||
var second = Run(HardwareOrDefault(), scene, 1.5f);
|
||||
|
||||
Assert.Equal(first.Output, second.Output);
|
||||
Assert.Equal(first.Store, second.Store);
|
||||
Assert.Equal(first.Report, second.Report);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void TheOutputIsTheGainAppliedToTheStoredValue()
|
||||
{
|
||||
var scene = Scene(64, 4, 90, 60, 8, 9);
|
||||
|
||||
var run = Run(HardwareOrDefault(), scene, 2.5f);
|
||||
|
||||
for (var index = 0; index < run.Output.Length; index += 4)
|
||||
{
|
||||
Assert.InRange(run.Output[index] - CpuTileConvolver.ToUnorm(run.Store[index + 2] * 2.5f), -1, 1);
|
||||
Assert.InRange(run.Output[index + 1] - CpuTileConvolver.ToUnorm(run.Store[index + 1] * 2.5f), -1, 1);
|
||||
Assert.InRange(run.Output[index + 2] - CpuTileConvolver.ToUnorm(run.Store[index] * 2.5f), -1, 1);
|
||||
Assert.InRange(run.Output[index + 3] - CpuTileConvolver.ToUnorm(run.Store[index + 3] * 2.5f), -1, 1);
|
||||
}
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[InlineData(1f)]
|
||||
[InlineData(2.75f)]
|
||||
[InlineData(0.3f)]
|
||||
public void RenderingTheStoreMatchesTheConvolutionBitForBit(float gain)
|
||||
{
|
||||
var scene = Scene(64, 5, 150, 97, 11, 47);
|
||||
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);
|
||||
|
||||
var pixels = new Bgra32[width * height];
|
||||
output.CopyTo(pixels);
|
||||
Assert.Equal(fused.Output, MemoryMarshal.Cast<Bgra32, byte>(pixels).ToArray());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void TheStatisticsDescribeTheSource()
|
||||
{
|
||||
var scene = Scene(64, 5, 150, 97, 11, 3);
|
||||
|
||||
var run = Run(HardwareOrDefault(), scene);
|
||||
|
||||
for (var tile = 0; tile < scene.Plan.TileCount; tile++)
|
||||
{
|
||||
var expected = TileInput.Norms(scene.Source, scene.SourceX, scene.SourceY, scene.SourceWidth, scene.SourceHeight, scene.Plan, tile);
|
||||
Assert.Equal(expected, GpuTileCheck.Norms(run.Report, scene.Plan, tile));
|
||||
}
|
||||
|
||||
var measurements = Measure(scene, run);
|
||||
var totals = new ulong[4];
|
||||
for (var index = 0; index < scene.SourceWidth * scene.SourceHeight; index++)
|
||||
{
|
||||
totals[0] += scene.Source[index * 4 + 2];
|
||||
totals[1] += scene.Source[index * 4 + 1];
|
||||
totals[2] += scene.Source[index * 4];
|
||||
totals[3] += scene.Source[index * 4 + 3];
|
||||
}
|
||||
for (var channel = 0; channel < 4; channel++)
|
||||
Assert.Equal(totals[channel] / 255d, measurements[1 + channel].Reference);
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[InlineData(64, 5, 150, 97, 11)]
|
||||
[InlineData(128, 23, 140, 90, 24)]
|
||||
public void AHealthyRunPassesEveryCheck(int size, int radius, int width, int height, int margin)
|
||||
{
|
||||
var scene = Scene(size, radius, width, height, margin, 17);
|
||||
|
||||
var measurements = Measure(scene, Run(HardwareOrDefault(), scene));
|
||||
|
||||
Assert.Equal(GpuTileCheck.NonFiniteName, measurements[0].Name);
|
||||
Assert.Equal(0d, measurements[0].Measured);
|
||||
Assert.All(measurements, measurement => Assert.True(measurement.Passes, $"{measurement}"));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void AScaledSpectrumFailsTheSumCheck()
|
||||
{
|
||||
var scene = Scene(64, 5, 150, 97, 11, 21);
|
||||
|
||||
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 AMirroredKernelFailsTheSpotCheckButKeepsTheSum()
|
||||
{
|
||||
var scene = Scene(64, 5, 150, 97, 16, 23);
|
||||
|
||||
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);
|
||||
Assert.All(measurements.Where(measurement => measurement.Name.StartsWith("sum.", StringComparison.Ordinal)), measurement => Assert.True(measurement.Passes, $"{measurement}"));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void ANaNIsCounted()
|
||||
{
|
||||
var scene = Scene(64, 5, 150, 97, 11, 29);
|
||||
|
||||
var measurements = Measure(scene, Run(HardwareOrDefault(), scene, tamper: spectrum =>
|
||||
{
|
||||
var broken = (float[])spectrum.Clone();
|
||||
broken[10] = float.NaN;
|
||||
return broken;
|
||||
}));
|
||||
|
||||
Assert.True(measurements[0].Measured > 0d);
|
||||
Assert.False(measurements[0].Passes);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void AReusedConvolverCountsOnlyTheCurrentRun()
|
||||
{
|
||||
var scene = Scene(64, 5, 150, 97, 11, 29);
|
||||
var device = HardwareOrDefault();
|
||||
using var convolver = new GpuTileConvolver(device);
|
||||
|
||||
var broken = Run(device, convolver, scene, tamper: spectrum =>
|
||||
{
|
||||
var values = (float[])spectrum.Clone();
|
||||
values[10] = float.NaN;
|
||||
return values;
|
||||
});
|
||||
var healthy = Run(device, convolver, scene);
|
||||
|
||||
Assert.True(broken.Report[GpuTileLayout.CountOffset] > 0u);
|
||||
Assert.Equal(0u, healthy.Report[GpuTileLayout.CountOffset]);
|
||||
Assert.All(Measure(scene, healthy), measurement => Assert.True(measurement.Passes, $"{measurement}"));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void TheSoftwareRendererStaysWithinTheBound()
|
||||
{
|
||||
var scene = Scene(64, 3, 70, 50, 4, 31);
|
||||
|
||||
var run = Run(Software(), scene);
|
||||
|
||||
Assert.InRange(scene.WorstRatio(run.Store, ConvolutionBound.GpuOperationError), 0d, 1d);
|
||||
Assert.All(Measure(scene, run), measurement => Assert.True(measurement.Passes, $"{measurement}"));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void TheGpuAndTheCpuDifferByLessThanBothBounds()
|
||||
{
|
||||
var scene = Scene(128, 12, 200, 130, 16, 37);
|
||||
|
||||
var gpu = Run(HardwareOrDefault(), scene);
|
||||
var cpu = new float[scene.RegionLength];
|
||||
using (var convolver = new CpuTileConvolver(2))
|
||||
convolver.Convolve(scene.Source, scene.SourceX, scene.SourceY, scene.SourceWidth, scene.SourceHeight, scene.Spectrum, scene.Plan, new byte[scene.RegionLength], 1f, cpu);
|
||||
|
||||
for (var y = 0; y < scene.Plan.RegionHeight; y++)
|
||||
{
|
||||
for (var x = 0; x < scene.Plan.RegionWidth; x++)
|
||||
{
|
||||
var (redGreen, blueAlpha) = scene.Norms(scene.Plan.RegionX + x, scene.Plan.RegionY + y);
|
||||
for (var channel = 0; channel < 4; channel++)
|
||||
{
|
||||
var norm = channel < 2 ? redGreen : blueAlpha;
|
||||
var bound = ConvolutionBound.Absolute(128, ConvolutionBound.GpuOperationError, norm) + ConvolutionBound.Absolute(128, ConvolutionBound.CpuOperationError, norm);
|
||||
var index = (y * scene.Plan.RegionWidth + x) * 4 + channel;
|
||||
Assert.True(Math.Abs(gpu.Store[index] - cpu[index]) <= bound);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void PreparationRejectsInconsistentRequests()
|
||||
{
|
||||
var scene = Scene(64, 5, 40, 30, 6, 41);
|
||||
using var convolver = new GpuTileConvolver(HardwareOrDefault());
|
||||
var samples = Samples(scene.Plan);
|
||||
|
||||
Assert.Throws<InvalidOperationException>(() => convolver.Prepare(scene.Plan, 6, 6, 40, 30, 1f, samples, false));
|
||||
convolver.Upload(scene.Spectrum);
|
||||
var other = TilePlan.Create(64, 4, 0, 0, 52, 42);
|
||||
Assert.Throws<InvalidOperationException>(() => convolver.Prepare(other, 6, 6, 40, 30, 1f, samples, false));
|
||||
Assert.Throws<ArgumentOutOfRangeException>(() => convolver.Prepare(scene.Plan, 6, 6, 40, 30, float.NaN, samples, false));
|
||||
Assert.Throws<ArgumentOutOfRangeException>(() => convolver.Prepare(scene.Plan, 6, 6, 40, 30, 1f, new Int2[GpuTileConvolver.MaximumSamples + 1], false));
|
||||
Assert.Throws<ArgumentOutOfRangeException>(() => convolver.Prepare(scene.Plan, 6, 6, 40, 30, 1f, [new Int2(scene.Plan.RegionWidth, 0)], false));
|
||||
Assert.Throws<ArgumentOutOfRangeException>(() => convolver.Prepare(scene.Plan, 6, 6, 0, 30, 1f, samples, false));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void TheStoreExistsOnlyWhileItIsRequested()
|
||||
{
|
||||
var scene = Scene(64, 5, 40, 30, 6, 43);
|
||||
using var convolver = new GpuTileConvolver(HardwareOrDefault());
|
||||
convolver.Upload(scene.Spectrum);
|
||||
|
||||
var without = convolver.Prepare(scene.Plan, 6, 6, 40, 30, 1f, [], false);
|
||||
Assert.False(convolver.HasStore);
|
||||
var with = convolver.Prepare(scene.Plan, 6, 6, 40, 30, 1f, [], true);
|
||||
Assert.True(convolver.HasStore);
|
||||
Assert.NotSame(convolver.StoreFor(without), convolver.StoreFor(with));
|
||||
convolver.ReleaseStore();
|
||||
|
||||
Assert.False(convolver.HasStore);
|
||||
Assert.Throws<InvalidOperationException>(() => convolver.StoreFor(with));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,175 @@
|
||||
namespace SpectralConvolution.Tests;
|
||||
|
||||
public sealed class KernelSpectrumTests
|
||||
{
|
||||
static double[] AsymmetricKernel(int radius)
|
||||
{
|
||||
var size = radius * 2 + 1;
|
||||
var values = new double[size * size];
|
||||
for (var y = 0; y < size; y++)
|
||||
{
|
||||
for (var x = 0; x < size; x++)
|
||||
values[y * size + x] = 1d + x * 0.75 + y * y * 0.125 + (x == size - 1 && y == 0 ? 9d : 0d);
|
||||
}
|
||||
|
||||
return values;
|
||||
}
|
||||
|
||||
static (double Real, double Imaginary) NaiveSpectrum(ReadOnlySpan<double> kernel, int radius, int size, int frequencyX, int frequencyY)
|
||||
{
|
||||
var kernelSize = radius * 2 + 1;
|
||||
var real = 0d;
|
||||
var imaginary = 0d;
|
||||
for (var offsetY = -radius; offsetY <= radius; offsetY++)
|
||||
{
|
||||
for (var offsetX = -radius; offsetX <= radius; offsetX++)
|
||||
{
|
||||
var weight = kernel[(offsetY + radius) * kernelSize + offsetX + radius];
|
||||
var angle = 2d * Math.PI * (frequencyX * offsetX + frequencyY * offsetY) / size;
|
||||
real += weight * Math.Cos(angle);
|
||||
imaginary += weight * Math.Sin(angle);
|
||||
}
|
||||
}
|
||||
|
||||
return (real, imaginary);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void TheKernelIsScaledToSumToOne()
|
||||
{
|
||||
var values = AsymmetricKernel(3);
|
||||
var spectrum = new KernelSpectrum();
|
||||
|
||||
spectrum.Update(values, 3, 64);
|
||||
|
||||
var sum = values.Sum();
|
||||
Assert.Equal(1d, spectrum.Kernel.ToArray().Sum(), 12);
|
||||
for (var index = 0; index < values.Length; index++)
|
||||
Assert.Equal(values[index] / sum, spectrum.Kernel[index]);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void TheTwiddlesAreTheRoundedRootsOfUnity()
|
||||
{
|
||||
var spectrum = new KernelSpectrum();
|
||||
|
||||
spectrum.Update(AsymmetricKernel(1), 1, 128);
|
||||
|
||||
Assert.Equal(64, spectrum.Twiddles.Length);
|
||||
for (var index = 0; index < 64; index++)
|
||||
{
|
||||
var (sin, cos) = Math.SinCos(-2d * Math.PI * index / 128);
|
||||
Assert.Equal(KernelSpectrum.Flush((float)cos), spectrum.Twiddles[index].X);
|
||||
Assert.Equal(KernelSpectrum.Flush((float)sin), spectrum.Twiddles[index].Y);
|
||||
}
|
||||
Assert.Equal(1f, spectrum.Twiddles[0].X);
|
||||
Assert.Equal(0f, spectrum.Twiddles[0].Y);
|
||||
Assert.Equal(-1f, spectrum.Twiddles[32].Y);
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[InlineData(2, 64)]
|
||||
[InlineData(5, 128)]
|
||||
public void TheSpectrumIsTheTransformOfTheReversedKernelStoredByColumn(int radius, int size)
|
||||
{
|
||||
var spectrum = new KernelSpectrum();
|
||||
|
||||
spectrum.Update(AsymmetricKernel(radius), radius, size);
|
||||
|
||||
var bound = ConvolutionBound.SpectrumError(size) + 1e-12;
|
||||
for (var frequencyY = 0; frequencyY < size; frequencyY += 7)
|
||||
{
|
||||
for (var frequencyX = 0; frequencyX < size; frequencyX += 5)
|
||||
{
|
||||
var (real, imaginary) = NaiveSpectrum(spectrum.Kernel, radius, size, frequencyX, frequencyY);
|
||||
var value = spectrum.Spectrum[frequencyX * size + frequencyY];
|
||||
Assert.True(Math.Abs(value.X - real) <= bound, $"({frequencyX}, {frequencyY}) real {value.X} {real}");
|
||||
Assert.True(Math.Abs(value.Y - imaginary) <= bound, $"({frequencyX}, {frequencyY}) imaginary {value.Y} {imaginary}");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void TheSpectrumAtZeroFrequencyIsTheKernelSum()
|
||||
{
|
||||
var spectrum = new KernelSpectrum();
|
||||
|
||||
spectrum.Update(AsymmetricKernel(4), 4, 64);
|
||||
|
||||
Assert.Equal(1f, spectrum.Spectrum[0].X);
|
||||
Assert.Equal(0f, spectrum.Spectrum[0].Y);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void AReusedSpectrumMatchesAFreshOne()
|
||||
{
|
||||
var reused = new KernelSpectrum();
|
||||
reused.Update(AsymmetricKernel(20), 20, 512);
|
||||
reused.Update(AsymmetricKernel(3), 3, 64);
|
||||
var fresh = new KernelSpectrum();
|
||||
fresh.Update(AsymmetricKernel(3), 3, 64);
|
||||
|
||||
Assert.Equal(fresh.Size, reused.Size);
|
||||
Assert.Equal(fresh.Radius, reused.Radius);
|
||||
Assert.Equal(fresh.Kernel.ToArray(), reused.Kernel.ToArray());
|
||||
Assert.Equal(fresh.Twiddles.ToArray(), reused.Twiddles.ToArray());
|
||||
Assert.Equal(fresh.Spectrum.ToArray(), reused.Spectrum.ToArray());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void ANegativeWeightIsRejected()
|
||||
{
|
||||
var values = AsymmetricKernel(1);
|
||||
values[4] = -1e-9;
|
||||
|
||||
Assert.Throws<ArgumentOutOfRangeException>(() => new KernelSpectrum().Update(values, 1, 64));
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[InlineData(double.NaN)]
|
||||
[InlineData(double.PositiveInfinity)]
|
||||
public void ANonFiniteWeightIsRejected(double weight)
|
||||
{
|
||||
var values = AsymmetricKernel(1);
|
||||
values[0] = weight;
|
||||
|
||||
Assert.Throws<ArgumentOutOfRangeException>(() => new KernelSpectrum().Update(values, 1, 64));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void AnAllZeroKernelIsRejected()
|
||||
{
|
||||
Assert.Throws<ArgumentOutOfRangeException>(() => new KernelSpectrum().Update(new double[9], 1, 64));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void AKernelOfTheWrongLengthIsRejected()
|
||||
{
|
||||
Assert.Throws<ArgumentException>(() => new KernelSpectrum().Update(new double[8], 1, 64));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void ARejectedKernelKeepsThePreviousSpectrum()
|
||||
{
|
||||
var spectrum = new KernelSpectrum();
|
||||
spectrum.Update(AsymmetricKernel(1), 1, 64);
|
||||
|
||||
Assert.Throws<ArgumentOutOfRangeException>(() => spectrum.Update(new double[9], 1, 64));
|
||||
|
||||
Assert.Equal(64, spectrum.Size);
|
||||
Assert.Throws<ArgumentOutOfRangeException>(() => spectrum.Update(AsymmetricKernel(40), 40, 64));
|
||||
Assert.Equal(64, spectrum.Size);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void SubnormalValuesBecomeSignedZero()
|
||||
{
|
||||
var subnormal = float.Epsilon * 3;
|
||||
|
||||
Assert.Equal(0f, KernelSpectrum.Flush(subnormal));
|
||||
Assert.False(float.IsNegative(KernelSpectrum.Flush(subnormal)));
|
||||
Assert.True(float.IsNegative(KernelSpectrum.Flush(-subnormal)));
|
||||
Assert.Equal(1.5e-38f, KernelSpectrum.Flush(1.5e-38f));
|
||||
Assert.Equal(-0.25f, KernelSpectrum.Flush(-0.25f));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,32 @@
|
||||
<Project Sdk="Microsoft.NET.Sdk">
|
||||
|
||||
<PropertyGroup>
|
||||
<TargetFramework>net10.0-windows10.0.19041.0</TargetFramework>
|
||||
<ImplicitUsings>enable</ImplicitUsings>
|
||||
<Nullable>enable</Nullable>
|
||||
<IsPackable>false</IsPackable>
|
||||
<PlatformTarget>x64</PlatformTarget>
|
||||
</PropertyGroup>
|
||||
|
||||
<ItemGroup>
|
||||
<PackageReference Include="coverlet.collector" Version="10.0.1">
|
||||
<IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets>
|
||||
<PrivateAssets>all</PrivateAssets>
|
||||
</PackageReference>
|
||||
<PackageReference Include="Microsoft.NET.Test.Sdk" Version="18.10.0" />
|
||||
<PackageReference Include="xunit.runner.visualstudio" Version="4.0.0">
|
||||
<IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets>
|
||||
<PrivateAssets>all</PrivateAssets>
|
||||
</PackageReference>
|
||||
<PackageReference Include="xunit.v3" Version="4.0.1" />
|
||||
</ItemGroup>
|
||||
|
||||
<ItemGroup>
|
||||
<ProjectReference Include="..\SpectralConvolution\SpectralConvolution.csproj" />
|
||||
</ItemGroup>
|
||||
|
||||
<ItemGroup>
|
||||
<Using Include="Xunit" />
|
||||
</ItemGroup>
|
||||
|
||||
</Project>
|
||||
@@ -0,0 +1,95 @@
|
||||
using ComputeWeave;
|
||||
|
||||
namespace SpectralConvolution.Tests;
|
||||
|
||||
[Collection("Direct3D12")]
|
||||
public sealed class SpectralSelfTestTests
|
||||
{
|
||||
static ConvolutionMeasurement[] Run(GraphicsDevice device, int maximumRadius)
|
||||
{
|
||||
var measurements = new ConvolutionMeasurement[SpectralSelfTest.MeasurementCount];
|
||||
var written = SpectralSelfTest.Run(device, maximumRadius, measurements);
|
||||
Assert.Equal(SpectralSelfTest.MeasurementCount, written);
|
||||
return measurements;
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void AHealthyDevicePassesEveryMeasurement()
|
||||
{
|
||||
var measurements = Run(GraphicsDevice.GetDefault(), 63);
|
||||
|
||||
Assert.All(measurements, measurement => Assert.True(measurement.Passes, $"{measurement}"));
|
||||
Assert.Equal(2, measurements.Count(measurement => measurement.Name == SpectralSelfTest.DeterminismName));
|
||||
Assert.Equal(2, measurements.Count(measurement => measurement.Name == SpectralSelfTest.FullName));
|
||||
Assert.All(measurements.Where(measurement => measurement.Name == SpectralSelfTest.DeterminismName), measurement => Assert.Equal(0d, measurement.Measured));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void TheSoftwareRendererPassesEveryMeasurement()
|
||||
{
|
||||
var device = GraphicsDevice.EnumerateDevices().First(candidate => !candidate.IsHardwareAccelerated);
|
||||
|
||||
var measurements = Run(device, 15);
|
||||
|
||||
Assert.All(measurements, measurement => Assert.True(measurement.Passes, $"{measurement}"));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void ThePatternIsPremultipliedAndHoldsTransparentAndOpaqueAreas()
|
||||
{
|
||||
var pattern = SpectralSelfTest.Pattern(200, 150, 7);
|
||||
|
||||
var transparent = 0;
|
||||
var opaque = 0;
|
||||
for (var index = 0; index < pattern.Length; index += 4)
|
||||
{
|
||||
Assert.True(pattern[index] <= pattern[index + 3]);
|
||||
Assert.True(pattern[index + 1] <= pattern[index + 3]);
|
||||
Assert.True(pattern[index + 2] <= pattern[index + 3]);
|
||||
if (pattern[index + 3] == 0)
|
||||
transparent++;
|
||||
if (pattern[index + 3] == 255)
|
||||
opaque++;
|
||||
}
|
||||
|
||||
Assert.True(transparent > 1000);
|
||||
Assert.True(opaque > 1000);
|
||||
Assert.Equal(pattern, SpectralSelfTest.Pattern(200, 150, 7));
|
||||
Assert.NotEqual(pattern, SpectralSelfTest.Pattern(200, 150, 8));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void TheKernelIsPositiveAndAsymmetric()
|
||||
{
|
||||
var kernel = SpectralSelfTest.Kernel(5);
|
||||
|
||||
Assert.All(kernel, value => Assert.True(value > 0d));
|
||||
Assert.NotEqual(kernel[0], kernel[10]);
|
||||
Assert.NotEqual(kernel[0], kernel[110]);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void TheSamplesIncludeTheCornersTheCenterAndATileSeam()
|
||||
{
|
||||
var samples = new Int2[GpuTileConvolver.MaximumSamples];
|
||||
|
||||
SpectralSelfTest.Samples(300, 200, 122, samples);
|
||||
|
||||
Assert.Contains(new Int2(0, 0), samples);
|
||||
Assert.Contains(new Int2(299, 199), samples);
|
||||
Assert.Contains(new Int2(150, 100), samples);
|
||||
Assert.Contains(new Int2(121, 121), samples);
|
||||
Assert.Contains(new Int2(122, 122), samples);
|
||||
Assert.All(samples, sample => Assert.True(sample.X is >= 0 and < 300 && sample.Y is >= 0 and < 200));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void InvalidRequestsAreRejected()
|
||||
{
|
||||
var device = GraphicsDevice.GetDefault();
|
||||
|
||||
Assert.Throws<ArgumentOutOfRangeException>(() => SpectralSelfTest.Run(device, SpectralSelfTest.FullRadius - 1, new ConvolutionMeasurement[SpectralSelfTest.MeasurementCount]));
|
||||
Assert.Throws<ArgumentException>(() => SpectralSelfTest.Run(device, 15, new ConvolutionMeasurement[SpectralSelfTest.MeasurementCount - 1]));
|
||||
Assert.Throws<ArgumentException>(() => SpectralSelfTest.Samples(10, 10, 5, new Int2[3]));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,40 @@
|
||||
namespace SpectralConvolution.Tests;
|
||||
|
||||
public sealed class TileInputTests
|
||||
{
|
||||
[Fact]
|
||||
public void TheNormsCoverTheWholeTileIncludingItsApron()
|
||||
{
|
||||
var source = new byte[10 * 10 * 4];
|
||||
source[0] = 3;
|
||||
source[1] = 4;
|
||||
source[2] = 12;
|
||||
source[3] = 5;
|
||||
var plan = TilePlan.Create(64, 2, 2, 2, 100, 100);
|
||||
|
||||
var (redGreen, blueAlpha) = TileInput.Norms(source, 0, 0, 10, 10, plan, 0);
|
||||
|
||||
Assert.Equal(Math.Sqrt(12 * 12 + 4 * 4) / 255d, redGreen);
|
||||
Assert.Equal(Math.Sqrt(3 * 3 + 5 * 5) / 255d, blueAlpha);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void PixelsOutsideTheTileAreIgnored()
|
||||
{
|
||||
var source = ConvolutionScene.Uniform(200, 10, 255);
|
||||
var plan = TilePlan.Create(64, 2, 0, 0, 200, 10);
|
||||
|
||||
var (redGreen, _) = TileInput.Norms(source, 0, 0, 200, 10, plan, 1);
|
||||
|
||||
var columns = Math.Min(64, 200 - (plan.OriginX(1) - 2));
|
||||
Assert.Equal(Math.Sqrt(2d * columns * 10), redGreen, 12);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void AShortSourceIsRejected()
|
||||
{
|
||||
var plan = TilePlan.Create(64, 2, 0, 0, 10, 10);
|
||||
|
||||
Assert.Throws<ArgumentException>(() => TileInput.Norms(new byte[10], 0, 0, 2, 2, plan, 0));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,148 @@
|
||||
namespace SpectralConvolution.Tests;
|
||||
|
||||
public sealed class TilePlanTests
|
||||
{
|
||||
[Theory]
|
||||
[InlineData(0, 128)]
|
||||
[InlineData(1, 128)]
|
||||
[InlineData(23, 128)]
|
||||
[InlineData(24, 512)]
|
||||
[InlineData(63, 512)]
|
||||
[InlineData(255, 512)]
|
||||
public void TheTileSizeFollowsTheRadius(int radius, int expected)
|
||||
{
|
||||
Assert.Equal(expected, TilePlan.SelectSize(radius));
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[InlineData(-1)]
|
||||
[InlineData(256)]
|
||||
public void ARadiusOutsideTheLargestTileIsRejected(int radius)
|
||||
{
|
||||
Assert.Throws<ArgumentOutOfRangeException>(() => TilePlan.SelectSize(radius));
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[InlineData(32)]
|
||||
[InlineData(96)]
|
||||
[InlineData(1024)]
|
||||
public void AnUnsupportedTileSizeIsRejected(int size)
|
||||
{
|
||||
Assert.False(TilePlan.IsSupportedSize(size));
|
||||
Assert.Throws<ArgumentOutOfRangeException>(() => TilePlan.Create(size, 1, 0, 0, 10, 10));
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[InlineData(64)]
|
||||
[InlineData(128)]
|
||||
[InlineData(256)]
|
||||
[InlineData(512)]
|
||||
public void EverySupportedTileSizeIsAccepted(int size)
|
||||
{
|
||||
Assert.True(TilePlan.IsSupportedSize(size));
|
||||
var plan = TilePlan.Create(size, 1, 0, 0, 10, 10);
|
||||
Assert.Equal(size, 1 << plan.Log2Size);
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[InlineData(64, 32)]
|
||||
[InlineData(128, 64)]
|
||||
public void AKernelAsWideAsTheTileIsRejected(int size, int radius)
|
||||
{
|
||||
Assert.Throws<ArgumentOutOfRangeException>(() => TilePlan.Create(size, radius, 0, 0, 10, 10));
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[InlineData(0, 10)]
|
||||
[InlineData(10, 0)]
|
||||
[InlineData(-1, 10)]
|
||||
public void AnEmptyRegionIsRejected(int width, int height)
|
||||
{
|
||||
Assert.Throws<ArgumentOutOfRangeException>(() => TilePlan.Create(128, 1, 0, 0, width, height));
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[InlineData(128, 15, 1, 1)]
|
||||
[InlineData(128, 15, 98, 98)]
|
||||
[InlineData(128, 15, 99, 97)]
|
||||
[InlineData(512, 63, 1952, 1112)]
|
||||
[InlineData(64, 0, 64, 65)]
|
||||
public void TheTilesCoverTheRegionWithoutASpareTile(int size, int radius, int width, int height)
|
||||
{
|
||||
var plan = TilePlan.Create(size, radius, 5, 7, width, height);
|
||||
|
||||
Assert.Equal(size - 2 * radius, plan.ValidSize);
|
||||
Assert.True((plan.TilesX - 1) * plan.ValidSize < width);
|
||||
Assert.True(plan.TilesX * plan.ValidSize >= width);
|
||||
Assert.True((plan.TilesY - 1) * plan.ValidSize < height);
|
||||
Assert.True(plan.TilesY * plan.ValidSize >= height);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void TileOriginsStepByTheValidSize()
|
||||
{
|
||||
var plan = TilePlan.Create(128, 15, 5, 7, 300, 200);
|
||||
|
||||
Assert.Equal(5, plan.OriginX(0));
|
||||
Assert.Equal(7, plan.OriginY(0));
|
||||
Assert.Equal(5 + 98, plan.OriginX(1));
|
||||
Assert.Equal(7, plan.OriginY(1));
|
||||
Assert.Equal(5, plan.OriginX(plan.TilesX));
|
||||
Assert.Equal(7 + 98, plan.OriginY(plan.TilesX));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void EveryPixelOfTheRegionBelongsToTheTileWhoseValidAreaHoldsIt()
|
||||
{
|
||||
var plan = TilePlan.Create(64, 5, 3, 4, 157, 121);
|
||||
var covered = new int[plan.RegionWidth * plan.RegionHeight];
|
||||
|
||||
for (var tile = 0; tile < plan.TileCount; tile++)
|
||||
{
|
||||
for (var y = plan.OriginY(tile); y < plan.OriginY(tile) + plan.ValidHeight(tile); y++)
|
||||
{
|
||||
for (var x = plan.OriginX(tile); x < plan.OriginX(tile) + plan.ValidWidth(tile); x++)
|
||||
{
|
||||
Assert.Equal(tile, plan.TileAt(x, y));
|
||||
covered[(y - plan.RegionY) * plan.RegionWidth + x - plan.RegionX]++;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
Assert.All(covered, count => Assert.Equal(1, count));
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[InlineData(64, 256)]
|
||||
[InlineData(128, 64)]
|
||||
[InlineData(256, 16)]
|
||||
[InlineData(512, 4)]
|
||||
public void TheBatchFitsTheWorkingBudget(int size, int expected)
|
||||
{
|
||||
var plan = TilePlan.Create(size, 1, 0, 0, 8192, 8192);
|
||||
|
||||
Assert.Equal(expected, plan.BatchTiles);
|
||||
Assert.True((long)plan.BatchTiles * plan.TileElements * TilePlan.ElementBytes <= TilePlan.BatchBudgetBytes);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void TheBatchNeverExceedsTheTileCount()
|
||||
{
|
||||
var plan = TilePlan.Create(128, 1, 0, 0, 10, 10);
|
||||
|
||||
Assert.Equal(1, plan.TileCount);
|
||||
Assert.Equal(1, plan.BatchTiles);
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[InlineData(64, 8)]
|
||||
[InlineData(128, 32)]
|
||||
[InlineData(512, 512)]
|
||||
public void GroupsSplitEachTileIntoEqualParts(int size, int expected)
|
||||
{
|
||||
var plan = TilePlan.Create(size, 1, 0, 0, 200, 100);
|
||||
|
||||
Assert.Equal(expected, plan.GroupsPerTile);
|
||||
Assert.Equal(plan.TileCount * expected, plan.GroupCount);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,9 @@
|
||||
<Project>
|
||||
|
||||
<ItemGroup>
|
||||
<Compile Include="$(MSBuildThisFileDirectory)SpectralConvolution\**\*.cs"
|
||||
Exclude="$(MSBuildThisFileDirectory)SpectralConvolution\bin\**;$(MSBuildThisFileDirectory)SpectralConvolution\obj\**"
|
||||
LinkBase="SpectralConvolution" />
|
||||
</ItemGroup>
|
||||
|
||||
</Project>
|
||||
@@ -0,0 +1,67 @@
|
||||
namespace SpectralConvolution;
|
||||
|
||||
internal static class ConvolutionBound
|
||||
{
|
||||
public static readonly double GpuOperationError = Math.ScaleB(1d, -23);
|
||||
public static readonly double CpuOperationError = Math.ScaleB(1d, -24);
|
||||
public static readonly double SingleRounding = Math.ScaleB(1d, -24);
|
||||
public static readonly double DoubleRounding = Math.ScaleB(1d, -53);
|
||||
public static readonly double SmallestNormal = Math.ScaleB(1d, -126);
|
||||
public static readonly double TrigonometricError = Math.ScaleB(1d, -51);
|
||||
|
||||
public static double TwiddleAngleError => Math.PI * TrigonometricError;
|
||||
|
||||
public static double DoubleTwiddleError => TwiddleAngleError + Math.Sqrt(2d) * TrigonometricError;
|
||||
|
||||
public static double SingleTwiddleError => SingleRounding * (1d + DoubleTwiddleError) + DoubleTwiddleError;
|
||||
|
||||
public static double Gamma(int operations, double unit)
|
||||
{
|
||||
ArgumentOutOfRangeException.ThrowIfNegative(operations);
|
||||
if (!double.IsFinite(unit) || unit < 0d)
|
||||
throw new ArgumentOutOfRangeException(nameof(unit));
|
||||
var product = operations * unit;
|
||||
if (product >= 1d)
|
||||
throw new ArgumentOutOfRangeException(nameof(operations));
|
||||
return product / (1d - product);
|
||||
}
|
||||
|
||||
public static double ComplexMultiplication(double unit) => Math.Sqrt(2d) * Gamma(2, unit);
|
||||
|
||||
public static double Stage(double unit, double twiddleError)
|
||||
=> (1d + unit) * (twiddleError + (1d + twiddleError) * ComplexMultiplication(unit)) + unit;
|
||||
|
||||
public static double Transform(int stages, double unit, double twiddleError)
|
||||
=> double.ExpM1(stages * double.LogP1(Stage(unit, twiddleError)));
|
||||
|
||||
public static double SpectrumError(int size)
|
||||
{
|
||||
var plan = TilePlan.Create(size, 0, 0, 0, 1, 1);
|
||||
var transform = Transform(2 * plan.Log2Size, DoubleRounding, DoubleTwiddleError) * size;
|
||||
return SingleRounding * (1d + transform) + transform + Math.Sqrt(2d) * SmallestNormal;
|
||||
}
|
||||
|
||||
public static double Relative(int size, double operationError)
|
||||
{
|
||||
var plan = TilePlan.Create(size, 0, 0, 0, 1, 1);
|
||||
var multiplication = ComplexMultiplication(operationError);
|
||||
var transform = Transform(2 * plan.Log2Size, operationError, SingleTwiddleError);
|
||||
var spectrum = SpectrumError(size);
|
||||
var product = transform * (1d + spectrum) * (1d + multiplication) + spectrum * (1d + multiplication) + multiplication;
|
||||
var convolution = product + transform * (1d + product);
|
||||
return convolution + SingleRounding * (1d + convolution);
|
||||
}
|
||||
|
||||
public static int FlushedOperations(int size)
|
||||
{
|
||||
var plan = TilePlan.Create(size, 0, 0, 0, 1, 1);
|
||||
return (int)Math.Ceiling(2d * (4 * plan.Log2Size + 2) * 4d * Math.Sqrt(2d) * size);
|
||||
}
|
||||
|
||||
public static double Absolute(int size, double operationError, double norm)
|
||||
{
|
||||
if (!double.IsFinite(norm) || norm < 0d)
|
||||
throw new ArgumentOutOfRangeException(nameof(norm));
|
||||
return Relative(size, operationError) * norm + FlushedOperations(size) * SmallestNormal;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,486 @@
|
||||
using System.Runtime.ExceptionServices;
|
||||
using ComputeWeave;
|
||||
|
||||
namespace SpectralConvolution;
|
||||
|
||||
internal sealed class CpuTileConvolver : IDisposable
|
||||
{
|
||||
public const long WorkingBudgetBytes = 64L << 20;
|
||||
public const int StoredChunkPixels = 16384;
|
||||
const int Channels = 4;
|
||||
|
||||
readonly Worker[] workers;
|
||||
readonly Thread[] threads;
|
||||
readonly SemaphoreSlim start = new(0);
|
||||
readonly SemaphoreSlim finished = new(0);
|
||||
bool disposed;
|
||||
int[] reversal = [];
|
||||
int reversalSize;
|
||||
int next;
|
||||
int claimed;
|
||||
int workingSize;
|
||||
Exception? failure;
|
||||
byte[] source = [];
|
||||
int sourceX;
|
||||
int sourceY;
|
||||
int sourceWidth;
|
||||
int sourceHeight;
|
||||
KernelSpectrum? spectrum;
|
||||
TilePlan plan;
|
||||
byte[] output = [];
|
||||
float gain;
|
||||
float[]? convolved;
|
||||
float[]? stored;
|
||||
int storedPixels;
|
||||
int storedChunks;
|
||||
|
||||
public CpuTileConvolver()
|
||||
: this(Environment.ProcessorCount)
|
||||
{
|
||||
}
|
||||
|
||||
public CpuTileConvolver(int threadCount)
|
||||
{
|
||||
ArgumentOutOfRangeException.ThrowIfNegativeOrZero(threadCount);
|
||||
workers = new Worker[threadCount];
|
||||
for (var index = 0; index < threadCount; index++)
|
||||
workers[index] = new Worker();
|
||||
threads = new Thread[threadCount - 1];
|
||||
for (var index = 0; index < threads.Length; index++)
|
||||
{
|
||||
threads[index] = new Thread(Serve) { IsBackground = true, Name = nameof(CpuTileConvolver) };
|
||||
threads[index].Start();
|
||||
}
|
||||
}
|
||||
|
||||
public int Threads => workers.Length;
|
||||
|
||||
public long WorkingBytes
|
||||
{
|
||||
get
|
||||
{
|
||||
var bytes = 0L;
|
||||
foreach (var worker in workers)
|
||||
bytes += worker.Bytes;
|
||||
return bytes;
|
||||
}
|
||||
}
|
||||
|
||||
public static int ActiveThreads(int threads, int size)
|
||||
=> (int)Math.Clamp(WorkingBudgetBytes / ((long)size * size * Channels * sizeof(float)), 1L, threads);
|
||||
|
||||
public void Convolve(
|
||||
byte[] sourcePixels,
|
||||
int sourceLeft,
|
||||
int sourceTop,
|
||||
int sourceColumns,
|
||||
int sourceRows,
|
||||
KernelSpectrum kernelSpectrum,
|
||||
in TilePlan tilePlan,
|
||||
byte[] outputPixels,
|
||||
float outputGain,
|
||||
float[]? convolvedValues)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(sourcePixels);
|
||||
ArgumentNullException.ThrowIfNull(kernelSpectrum);
|
||||
ArgumentNullException.ThrowIfNull(outputPixels);
|
||||
ArgumentOutOfRangeException.ThrowIfNegative(sourceColumns);
|
||||
ArgumentOutOfRangeException.ThrowIfNegative(sourceRows);
|
||||
if (sourcePixels.Length < (long)sourceColumns * sourceRows * Channels)
|
||||
throw new ArgumentException(null, nameof(sourcePixels));
|
||||
if (kernelSpectrum.Size != tilePlan.Size || kernelSpectrum.Radius != tilePlan.Radius)
|
||||
throw new ArgumentException(null, nameof(kernelSpectrum));
|
||||
var regionLength = (long)tilePlan.RegionWidth * tilePlan.RegionHeight * Channels;
|
||||
if (outputPixels.Length < regionLength)
|
||||
throw new ArgumentException(null, nameof(outputPixels));
|
||||
if (convolvedValues is not null && convolvedValues.Length < regionLength)
|
||||
throw new ArgumentException(null, nameof(convolvedValues));
|
||||
if (!float.IsFinite(outputGain))
|
||||
throw new ArgumentOutOfRangeException(nameof(outputGain));
|
||||
|
||||
ObjectDisposedException.ThrowIf(disposed, this);
|
||||
EnsureReversal(tilePlan.Size, tilePlan.Log2Size);
|
||||
EnsureWorkingSize(tilePlan.Size);
|
||||
var active = Math.Min(ActiveThreads(workers.Length, tilePlan.Size), tilePlan.TileCount);
|
||||
|
||||
source = sourcePixels;
|
||||
sourceX = sourceLeft;
|
||||
sourceY = sourceTop;
|
||||
sourceWidth = sourceColumns;
|
||||
sourceHeight = sourceRows;
|
||||
spectrum = kernelSpectrum;
|
||||
plan = tilePlan;
|
||||
output = outputPixels;
|
||||
gain = outputGain;
|
||||
convolved = convolvedValues;
|
||||
try
|
||||
{
|
||||
Dispatch(active);
|
||||
}
|
||||
finally
|
||||
{
|
||||
source = [];
|
||||
spectrum = null;
|
||||
output = [];
|
||||
convolved = null;
|
||||
}
|
||||
}
|
||||
|
||||
public void RenderStored(float[] storedValues, int pixels, float outputGain, byte[] outputPixels)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(storedValues);
|
||||
ArgumentNullException.ThrowIfNull(outputPixels);
|
||||
ArgumentOutOfRangeException.ThrowIfNegative(pixels);
|
||||
if (storedValues.Length < (long)pixels * Channels)
|
||||
throw new ArgumentException(null, nameof(storedValues));
|
||||
if (outputPixels.Length < (long)pixels * Channels)
|
||||
throw new ArgumentException(null, nameof(outputPixels));
|
||||
if (!float.IsFinite(outputGain))
|
||||
throw new ArgumentOutOfRangeException(nameof(outputGain));
|
||||
|
||||
ObjectDisposedException.ThrowIf(disposed, this);
|
||||
var chunks = (pixels + StoredChunkPixels - 1) / StoredChunkPixels;
|
||||
if (chunks == 0)
|
||||
return;
|
||||
|
||||
stored = storedValues;
|
||||
storedPixels = pixels;
|
||||
storedChunks = chunks;
|
||||
output = outputPixels;
|
||||
gain = outputGain;
|
||||
try
|
||||
{
|
||||
Dispatch(Math.Min(workers.Length, chunks));
|
||||
}
|
||||
finally
|
||||
{
|
||||
stored = null;
|
||||
output = [];
|
||||
}
|
||||
}
|
||||
|
||||
void Dispatch(int active)
|
||||
{
|
||||
next = 0;
|
||||
claimed = 0;
|
||||
failure = null;
|
||||
if (active > 1)
|
||||
start.Release(active - 1);
|
||||
Drain();
|
||||
for (var index = 0; index < active; index++)
|
||||
finished.Wait();
|
||||
|
||||
if (failure is { } exception)
|
||||
ExceptionDispatchInfo.Throw(exception);
|
||||
}
|
||||
|
||||
public static byte ToUnorm(float value)
|
||||
{
|
||||
if (float.IsNaN(value))
|
||||
return 0;
|
||||
return (byte)(Math.Clamp(value, 0f, 1f) * 255f + 0.5f);
|
||||
}
|
||||
|
||||
public void Dispose()
|
||||
{
|
||||
if (disposed)
|
||||
return;
|
||||
disposed = true;
|
||||
if (threads.Length > 0)
|
||||
start.Release(threads.Length);
|
||||
foreach (var thread in threads)
|
||||
thread.Join();
|
||||
start.Dispose();
|
||||
finished.Dispose();
|
||||
}
|
||||
|
||||
void Serve()
|
||||
{
|
||||
while (true)
|
||||
{
|
||||
start.Wait();
|
||||
if (disposed)
|
||||
return;
|
||||
Drain();
|
||||
}
|
||||
}
|
||||
|
||||
void EnsureReversal(int size, int log2)
|
||||
{
|
||||
if (reversalSize == size)
|
||||
return;
|
||||
if (reversal.Length < size)
|
||||
reversal = new int[size];
|
||||
var shift = 32 - log2;
|
||||
for (var index = 0; index < size; index++)
|
||||
reversal[index] = (int)(ReverseBits((uint)index) >> shift);
|
||||
reversalSize = size;
|
||||
}
|
||||
|
||||
void EnsureWorkingSize(int size)
|
||||
{
|
||||
if (workingSize == size)
|
||||
return;
|
||||
foreach (var worker in workers)
|
||||
worker.Release();
|
||||
workingSize = size;
|
||||
}
|
||||
|
||||
void Drain()
|
||||
{
|
||||
try
|
||||
{
|
||||
if (stored is { } values)
|
||||
{
|
||||
int chunk;
|
||||
while ((chunk = Interlocked.Increment(ref next) - 1) < storedChunks)
|
||||
RenderChunk(values, chunk);
|
||||
}
|
||||
else
|
||||
{
|
||||
var worker = workers[Interlocked.Increment(ref claimed) - 1];
|
||||
worker.Prepare(plan.Size);
|
||||
int tile;
|
||||
while ((tile = Interlocked.Increment(ref next) - 1) < plan.TileCount)
|
||||
ConvolveTile(tile, worker);
|
||||
}
|
||||
}
|
||||
catch (Exception exception)
|
||||
{
|
||||
Interlocked.CompareExchange(ref failure, exception, null);
|
||||
}
|
||||
finally
|
||||
{
|
||||
finished.Release();
|
||||
}
|
||||
}
|
||||
|
||||
void ConvolveTile(int tile, Worker worker)
|
||||
{
|
||||
var size = plan.Size;
|
||||
var log2 = plan.Log2Size;
|
||||
var radius = plan.Radius;
|
||||
var left = plan.OriginX(tile) - radius;
|
||||
var top = plan.OriginY(tile) - radius;
|
||||
var rowLength = size * Channels;
|
||||
var work = worker.Tile.AsSpan(0, size * rowLength);
|
||||
var line = worker.Line.AsSpan(0, rowLength);
|
||||
var spare = worker.Spare.AsSpan(0, rowLength);
|
||||
var order = reversal.AsSpan(0, size);
|
||||
var twiddles = spectrum!.Twiddles;
|
||||
var values = spectrum.Spectrum;
|
||||
|
||||
var lit = false;
|
||||
var first = Math.Max(0, sourceX - left);
|
||||
var last = Math.Min(size, sourceX + sourceWidth - left);
|
||||
for (var y = 0; y < size; y++)
|
||||
{
|
||||
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))
|
||||
{
|
||||
row.Clear();
|
||||
continue;
|
||||
}
|
||||
|
||||
lit = true;
|
||||
Butterflies(line, log2, twiddles, 1f);
|
||||
line.CopyTo(row);
|
||||
}
|
||||
|
||||
var regionLeft = plan.OriginX(tile) - plan.RegionX;
|
||||
var regionTop = plan.OriginY(tile) - plan.RegionY;
|
||||
var validWidth = plan.ValidWidth(tile);
|
||||
var validHeight = plan.ValidHeight(tile);
|
||||
if (!lit)
|
||||
{
|
||||
ClearValid(regionLeft, regionTop, validWidth, validHeight);
|
||||
return;
|
||||
}
|
||||
|
||||
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));
|
||||
|
||||
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;
|
||||
}
|
||||
|
||||
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));
|
||||
}
|
||||
|
||||
var scale = 1f / (size * size);
|
||||
for (var y = radius; y < radius + validHeight; y++)
|
||||
{
|
||||
var row = work.Slice(y * rowLength, rowLength);
|
||||
for (var x = 0; x < size; x++)
|
||||
row.Slice(x * Channels, Channels).CopyTo(line.Slice(order[x] * Channels, 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;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
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 index = pixel * Channels;
|
||||
output[index] = ToUnorm(values[index + 2] * gain);
|
||||
output[index + 1] = ToUnorm(values[index + 1] * gain);
|
||||
output[index + 2] = ToUnorm(values[index] * gain);
|
||||
output[index + 3] = ToUnorm(values[index + 3] * gain);
|
||||
}
|
||||
}
|
||||
|
||||
bool LoadRow(Span<float> line, ReadOnlySpan<int> order, int sourceRow, int left, int first, int last)
|
||||
{
|
||||
line.Clear();
|
||||
var lit = false;
|
||||
var pixels = source.AsSpan(sourceRow * sourceWidth * Channels, sourceWidth * Channels);
|
||||
for (var x = first; x < last; x++)
|
||||
{
|
||||
var offset = (left + x - sourceX) * Channels;
|
||||
var blue = pixels[offset];
|
||||
var green = pixels[offset + 1];
|
||||
var red = pixels[offset + 2];
|
||||
var alpha = pixels[offset + 3];
|
||||
if ((blue | green | red | alpha) == 0)
|
||||
continue;
|
||||
|
||||
var target = order[x] * Channels;
|
||||
line[target] = red / 255f;
|
||||
line[target + 1] = green / 255f;
|
||||
line[target + 2] = blue / 255f;
|
||||
line[target + 3] = alpha / 255f;
|
||||
lit = true;
|
||||
}
|
||||
|
||||
return lit;
|
||||
}
|
||||
|
||||
void ClearValid(int regionLeft, int regionTop, int validWidth, int validHeight)
|
||||
{
|
||||
for (var y = 0; y < validHeight; y++)
|
||||
{
|
||||
var index = ((regionTop + y) * plan.RegionWidth + regionLeft) * Channels;
|
||||
output.AsSpan(index, validWidth * Channels).Clear();
|
||||
convolved?.AsSpan(index, validWidth * Channels).Clear();
|
||||
}
|
||||
}
|
||||
|
||||
static void Butterflies(Span<float> line, int log2, ReadOnlySpan<Float2> twiddles, float direction)
|
||||
{
|
||||
var pairs = 1 << (log2 - 1);
|
||||
for (var stage = 0; stage < log2; stage++)
|
||||
{
|
||||
var half = 1 << stage;
|
||||
var shift = log2 - 1 - stage;
|
||||
for (var pair = 0; pair < pairs; pair++)
|
||||
{
|
||||
var position = pair & (half - 1);
|
||||
var even = (((pair >> stage) << (stage + 1)) + position) * Channels;
|
||||
var odd = even + half * Channels;
|
||||
var twiddle = twiddles[position << shift];
|
||||
var real = twiddle.X;
|
||||
var imaginary = twiddle.Y * direction;
|
||||
var odd0 = line[odd];
|
||||
var odd1 = line[odd + 1];
|
||||
var odd2 = line[odd + 2];
|
||||
var odd3 = line[odd + 3];
|
||||
var product0 = odd0 * real - odd1 * imaginary;
|
||||
var product1 = odd0 * imaginary + odd1 * real;
|
||||
var product2 = odd2 * real - odd3 * imaginary;
|
||||
var product3 = odd2 * imaginary + odd3 * real;
|
||||
var even0 = line[even];
|
||||
var even1 = line[even + 1];
|
||||
var even2 = line[even + 2];
|
||||
var even3 = line[even + 3];
|
||||
line[even] = even0 + product0;
|
||||
line[even + 1] = even1 + product1;
|
||||
line[even + 2] = even2 + product2;
|
||||
line[even + 3] = even3 + product3;
|
||||
line[odd] = even0 - product0;
|
||||
line[odd + 1] = even1 - product1;
|
||||
line[odd + 2] = even2 - product2;
|
||||
line[odd + 3] = even3 - product3;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
static uint ReverseBits(uint value)
|
||||
{
|
||||
value = ((value >> 1) & 0x55555555u) | ((value & 0x55555555u) << 1);
|
||||
value = ((value >> 2) & 0x33333333u) | ((value & 0x33333333u) << 2);
|
||||
value = ((value >> 4) & 0x0F0F0F0Fu) | ((value & 0x0F0F0F0Fu) << 4);
|
||||
value = ((value >> 8) & 0x00FF00FFu) | ((value & 0x00FF00FFu) << 8);
|
||||
return (value >> 16) | (value << 16);
|
||||
}
|
||||
|
||||
sealed class Worker
|
||||
{
|
||||
public float[] Tile { get; private set; } = [];
|
||||
|
||||
public float[] Line { get; private set; } = [];
|
||||
|
||||
public float[] Spare { get; private set; } = [];
|
||||
|
||||
public long Bytes => ((long)Tile.Length + Line.Length + Spare.Length) * sizeof(float);
|
||||
|
||||
public void Prepare(int size)
|
||||
{
|
||||
var rowLength = size * Channels;
|
||||
if (Tile.Length < size * rowLength)
|
||||
Tile = new float[size * rowLength];
|
||||
if (Line.Length < rowLength)
|
||||
{
|
||||
Line = new float[rowLength];
|
||||
Spare = new float[rowLength];
|
||||
}
|
||||
}
|
||||
|
||||
public void Release()
|
||||
{
|
||||
Tile = [];
|
||||
Line = [];
|
||||
Spare = [];
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,81 @@
|
||||
namespace SpectralConvolution;
|
||||
|
||||
internal static class DirectCorrelation
|
||||
{
|
||||
public const int Channels = 4;
|
||||
|
||||
public static uint Pack(byte red, byte green, byte blue, byte alpha)
|
||||
=> red | (uint)green << 8 | (uint)blue << 16 | (uint)alpha << 24;
|
||||
|
||||
public static void Evaluate(ReadOnlySpan<uint> neighborhood, ReadOnlySpan<double> kernel, Span<double> result)
|
||||
{
|
||||
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];
|
||||
red += (packed & 255u) / 255d * weight;
|
||||
green += (packed >> 8 & 255u) / 255d * weight;
|
||||
blue += (packed >> 16 & 255u) / 255d * weight;
|
||||
alpha += (packed >> 24) / 255d * 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;
|
||||
if (kernel.Length != kernelSize * kernelSize)
|
||||
throw new ArgumentException(null, nameof(kernel));
|
||||
if (bgra.Length < width * height * Channels)
|
||||
throw new ArgumentException(null, nameof(bgra));
|
||||
if (result.Length < Channels)
|
||||
throw new ArgumentException(null, nameof(result));
|
||||
|
||||
var red = 0d;
|
||||
var green = 0d;
|
||||
var blue = 0d;
|
||||
var alpha = 0d;
|
||||
for (var offsetY = -radius; offsetY <= radius; offsetY++)
|
||||
{
|
||||
var sourceY = y + offsetY;
|
||||
if (sourceY < 0 || sourceY >= height)
|
||||
continue;
|
||||
for (var offsetX = -radius; offsetX <= radius; offsetX++)
|
||||
{
|
||||
var sourceX = x + offsetX;
|
||||
if (sourceX < 0 || sourceX >= width)
|
||||
continue;
|
||||
var weight = kernel[(offsetY + radius) * kernelSize + offsetX + radius];
|
||||
var offset = (sourceY * width + sourceX) * Channels;
|
||||
red += bgra[offset + 2] / 255d * weight;
|
||||
green += bgra[offset + 1] / 255d * weight;
|
||||
blue += bgra[offset] / 255d * weight;
|
||||
alpha += bgra[offset + 3] / 255d * weight;
|
||||
}
|
||||
}
|
||||
|
||||
result[0] = red;
|
||||
result[1] = green;
|
||||
result[2] = blue;
|
||||
result[3] = alpha;
|
||||
}
|
||||
|
||||
public static double ErrorBound(int kernelLength)
|
||||
{
|
||||
ArgumentOutOfRangeException.ThrowIfNegativeOrZero(kernelLength);
|
||||
return ConvolutionBound.Gamma(kernelLength + 2, ConvolutionBound.DoubleRounding);
|
||||
}
|
||||
}
|
||||
+1
-1
@@ -4,7 +4,7 @@ using System.Numerics;
|
||||
using System.Runtime.CompilerServices;
|
||||
using System.Runtime.InteropServices;
|
||||
|
||||
namespace WaveOptics.Fourier;
|
||||
namespace SpectralConvolution;
|
||||
|
||||
internal static class FastFourierTransform
|
||||
{
|
||||
@@ -0,0 +1,109 @@
|
||||
using ComputeWeave;
|
||||
|
||||
namespace SpectralConvolution;
|
||||
|
||||
internal readonly record struct ConvolutionMeasurement(string Name, double Measured, double Reference, double Tolerance)
|
||||
{
|
||||
public bool Passes => Math.Abs(Measured - Reference) <= Tolerance;
|
||||
}
|
||||
|
||||
internal static class GpuTileCheck
|
||||
{
|
||||
public const string NonFiniteName = "nonfinite";
|
||||
public const int GroupAdditions = 9;
|
||||
public const int GroupElements = TilePlan.GroupElements;
|
||||
|
||||
static readonly string[] SumNames = ["sum.red", "sum.green", "sum.blue", "sum.alpha"];
|
||||
static readonly string[] SpotNames = ["spot.red", "spot.green", "spot.blue", "spot.alpha"];
|
||||
|
||||
public static int MeasurementCount(int sampleCount) => 1 + SumNames.Length + sampleCount * SpotNames.Length;
|
||||
|
||||
public static void Evaluate(
|
||||
ReadOnlySpan<uint> report,
|
||||
in GpuTileJob job,
|
||||
ReadOnlySpan<Int2> samples,
|
||||
ReadOnlySpan<double> kernel,
|
||||
Span<ConvolutionMeasurement> measurements)
|
||||
{
|
||||
var plan = job.Plan;
|
||||
var layout = job.Layout;
|
||||
if (report.Length < layout.Length)
|
||||
throw new ArgumentException(null, nameof(report));
|
||||
if (samples.Length != job.SampleCount)
|
||||
throw new ArgumentException(null, nameof(samples));
|
||||
if (kernel.Length != job.KernelArea)
|
||||
throw new ArgumentException(null, nameof(kernel));
|
||||
if (measurements.Length < MeasurementCount(job.SampleCount))
|
||||
throw new ArgumentException(null, nameof(measurements));
|
||||
|
||||
var relative = ConvolutionBound.Relative(plan.Size, ConvolutionBound.GpuOperationError);
|
||||
var flushed = ConvolutionBound.FlushedOperations(plan.Size) * ConvolutionBound.SmallestNormal;
|
||||
measurements[0] = new ConvolutionMeasurement(NonFiniteName, report[GpuTileLayout.CountOffset], 0d, 0d);
|
||||
|
||||
Span<ulong> totals = stackalloc ulong[4];
|
||||
Span<double> errors = stackalloc double[4];
|
||||
for (var tile = 0; tile < plan.TileCount; tile++)
|
||||
{
|
||||
var (redGreen, blueAlpha) = Norms(report, plan, tile);
|
||||
var root = Math.Sqrt((double)plan.ValidWidth(tile) * plan.ValidHeight(tile));
|
||||
errors[0] += root * (relative * redGreen + flushed);
|
||||
errors[1] += root * (relative * redGreen + flushed);
|
||||
errors[2] += root * (relative * blueAlpha + flushed);
|
||||
errors[3] += root * (relative * blueAlpha + flushed);
|
||||
for (var group = tile * plan.GroupsPerTile; group < (tile + 1) * plan.GroupsPerTile; group++)
|
||||
{
|
||||
var offset = GpuTileLayout.StatisticsOffset + group * GpuTileLayout.StatisticsPerGroup;
|
||||
for (var channel = 0; channel < 4; channel++)
|
||||
totals[channel] += report[offset + channel];
|
||||
}
|
||||
}
|
||||
|
||||
var groupRounding = ConvolutionBound.Gamma(GroupAdditions, ConvolutionBound.GpuOperationError);
|
||||
var kernelRounding = ConvolutionBound.Gamma(job.KernelArea + 1, ConvolutionBound.DoubleRounding);
|
||||
var accumulation = ConvolutionBound.Gamma(plan.GroupCount, ConvolutionBound.DoubleRounding);
|
||||
var groupFlushes = (double)plan.GroupCount * (GroupElements - 1) * ConvolutionBound.SmallestNormal;
|
||||
for (var channel = 0; channel < 4; channel++)
|
||||
{
|
||||
var 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 magnitude = reference * (1d + kernelRounding) + errors[channel];
|
||||
var tolerance = errors[channel] + groupRounding * magnitude + groupFlushes
|
||||
+ accumulation * ((1d + groupRounding) * magnitude + groupFlushes) + reference * kernelRounding;
|
||||
measurements[1 + channel] = new ConvolutionMeasurement(SumNames[channel], measured, reference, tolerance);
|
||||
}
|
||||
|
||||
Span<double> expected = stackalloc double[4];
|
||||
var referenceError = DirectCorrelation.ErrorBound(kernel.Length);
|
||||
for (var sample = 0; sample < job.SampleCount; sample++)
|
||||
{
|
||||
var position = samples[sample];
|
||||
var tile = plan.TileAt(plan.RegionX + position.X, plan.RegionY + position.Y);
|
||||
var (redGreen, blueAlpha) = Norms(report, plan, tile);
|
||||
DirectCorrelation.Evaluate(report.Slice(layout.GatheredOffset + sample * job.KernelArea, job.KernelArea), kernel, expected);
|
||||
for (var channel = 0; channel < 4; channel++)
|
||||
{
|
||||
var norm = channel < 2 ? redGreen : blueAlpha;
|
||||
var measured = BitConverter.UInt32BitsToSingle(report[layout.SpotsOffset + sample * GpuTileLayout.ValuesPerSpot + channel]);
|
||||
var tolerance = relative * norm + flushed + referenceError;
|
||||
measurements[1 + SumNames.Length + sample * 4 + channel] = new ConvolutionMeasurement(SpotNames[channel], measured, expected[channel], tolerance);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
public static (double RedGreen, double BlueAlpha) Norms(ReadOnlySpan<uint> report, in TilePlan plan, int tile)
|
||||
{
|
||||
var redGreen = 0UL;
|
||||
var blueAlpha = 0UL;
|
||||
for (var group = tile * plan.GroupsPerTile; group < (tile + 1) * plan.GroupsPerTile; group++)
|
||||
{
|
||||
var offset = GpuTileLayout.StatisticsOffset + group * GpuTileLayout.StatisticsPerGroup;
|
||||
redGreen += report[offset + 4];
|
||||
blueAlpha += report[offset + 5];
|
||||
}
|
||||
|
||||
return (Math.Sqrt(redGreen) / 255d, Math.Sqrt(blueAlpha) / 255d);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,257 @@
|
||||
using ComputeWeave;
|
||||
|
||||
namespace SpectralConvolution;
|
||||
|
||||
internal readonly record struct GpuTileLayout(int GroupCount, int SampleCount, int KernelArea)
|
||||
{
|
||||
public const int CountOffset = 0;
|
||||
public const int StatisticsOffset = 1;
|
||||
public const int StatisticsPerGroup = 6;
|
||||
public const int SumsPerGroup = 4;
|
||||
public const int ValuesPerSpot = 4;
|
||||
|
||||
public int SumsOffset => StatisticsOffset + GroupCount * StatisticsPerGroup;
|
||||
|
||||
public int SpotsOffset => SumsOffset + GroupCount * SumsPerGroup;
|
||||
|
||||
public int GatheredOffset => SpotsOffset + SampleCount * ValuesPerSpot;
|
||||
|
||||
public int Length => GatheredOffset + SampleCount * KernelArea;
|
||||
}
|
||||
|
||||
internal readonly record struct GpuTileJob(
|
||||
TilePlan Plan,
|
||||
int SourceX,
|
||||
int SourceY,
|
||||
int SourceWidth,
|
||||
int SourceHeight,
|
||||
float Gain,
|
||||
int SampleCount,
|
||||
bool Store)
|
||||
{
|
||||
public int KernelArea => (Plan.Radius * 2 + 1) * (Plan.Radius * 2 + 1);
|
||||
|
||||
public GpuTileLayout Layout => new(Plan.GroupCount, SampleCount, KernelArea);
|
||||
}
|
||||
|
||||
internal sealed class GpuTileConvolver : IDisposable
|
||||
{
|
||||
public const int MaximumSamples = 16;
|
||||
|
||||
readonly GraphicsDevice device;
|
||||
readonly ReadOnlyBuffer<Int2> samples;
|
||||
readonly ReadWriteBuffer<Float4> spare;
|
||||
ReadWriteBuffer<Float4>? tiles;
|
||||
ReadOnlyBuffer<Float2>? twiddles;
|
||||
ReadOnlyBuffer<Float2>? spectrum;
|
||||
ReadWriteBuffer<uint>? report;
|
||||
ReadBackBuffer<uint>? readBack;
|
||||
ReadWriteBuffer<Float4>? store;
|
||||
int spectrumSize;
|
||||
int spectrumRadius = -1;
|
||||
|
||||
public GpuTileConvolver(GraphicsDevice device)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(device);
|
||||
this.device = device;
|
||||
samples = device.AllocateReadOnlyBuffer<Int2>(MaximumSamples);
|
||||
spare = device.AllocateReadWriteBuffer<Float4>(1);
|
||||
}
|
||||
|
||||
public ReadWriteBuffer<Float4> Tiles => tiles ?? throw new InvalidOperationException();
|
||||
|
||||
public ReadOnlyBuffer<Float2> Twiddles => twiddles ?? throw new InvalidOperationException();
|
||||
|
||||
public ReadOnlyBuffer<Float2> Spectrum => spectrum ?? throw new InvalidOperationException();
|
||||
|
||||
public ReadWriteBuffer<uint> Report => report ?? throw new InvalidOperationException();
|
||||
|
||||
public ReadOnlyBuffer<Int2> Samples => samples;
|
||||
|
||||
public bool HasStore => store is not null;
|
||||
|
||||
public void Upload(KernelSpectrum kernelSpectrum)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(kernelSpectrum);
|
||||
if (kernelSpectrum.Size == 0)
|
||||
throw new ArgumentException(null, nameof(kernelSpectrum));
|
||||
|
||||
spectrumRadius = -1;
|
||||
if (spectrumSize != kernelSpectrum.Size)
|
||||
{
|
||||
twiddles?.Dispose();
|
||||
spectrum?.Dispose();
|
||||
twiddles = null;
|
||||
spectrum = null;
|
||||
spectrumSize = 0;
|
||||
twiddles = device.AllocateReadOnlyBuffer<Float2>(kernelSpectrum.Size / 2);
|
||||
spectrum = device.AllocateReadOnlyBuffer<Float2>(kernelSpectrum.Size * kernelSpectrum.Size);
|
||||
spectrumSize = kernelSpectrum.Size;
|
||||
}
|
||||
|
||||
twiddles!.CopyFrom(kernelSpectrum.Twiddles);
|
||||
spectrum!.CopyFrom(kernelSpectrum.Spectrum);
|
||||
spectrumRadius = kernelSpectrum.Radius;
|
||||
}
|
||||
|
||||
public GpuTileJob Prepare(
|
||||
in TilePlan plan,
|
||||
int sourceX,
|
||||
int sourceY,
|
||||
int sourceWidth,
|
||||
int sourceHeight,
|
||||
float gain,
|
||||
ReadOnlySpan<Int2> sampleValues,
|
||||
bool storeValues)
|
||||
{
|
||||
if (plan.Size != spectrumSize || plan.Radius != spectrumRadius)
|
||||
throw new InvalidOperationException();
|
||||
ArgumentOutOfRangeException.ThrowIfNegativeOrZero(sourceWidth);
|
||||
ArgumentOutOfRangeException.ThrowIfNegativeOrZero(sourceHeight);
|
||||
if (!float.IsFinite(gain))
|
||||
throw new ArgumentOutOfRangeException(nameof(gain));
|
||||
if (sampleValues.Length > MaximumSamples)
|
||||
throw new ArgumentOutOfRangeException(nameof(sampleValues));
|
||||
foreach (var sample in sampleValues)
|
||||
{
|
||||
if (sample.X < 0 || sample.X >= plan.RegionWidth || sample.Y < 0 || sample.Y >= plan.RegionHeight)
|
||||
throw new ArgumentOutOfRangeException(nameof(sampleValues));
|
||||
}
|
||||
|
||||
var job = new GpuTileJob(plan, sourceX, sourceY, sourceWidth, sourceHeight, gain, sampleValues.Length, storeValues);
|
||||
var tileLength = (long)plan.BatchTiles * plan.TileElements;
|
||||
if (tiles is null || tiles.Length < tileLength)
|
||||
{
|
||||
tiles?.Dispose();
|
||||
tiles = null;
|
||||
tiles = device.AllocateReadWriteBuffer<Float4>(checked((int)tileLength));
|
||||
}
|
||||
|
||||
var reportLength = job.Layout.Length;
|
||||
if (report is null || report.Length < reportLength)
|
||||
{
|
||||
report?.Dispose();
|
||||
readBack?.Dispose();
|
||||
report = null;
|
||||
readBack = null;
|
||||
report = device.AllocateReadWriteBuffer<uint>(reportLength);
|
||||
readBack = device.AllocateReadBackBuffer<uint>(reportLength);
|
||||
}
|
||||
|
||||
if (storeValues)
|
||||
{
|
||||
var storeLength = checked(plan.RegionWidth * plan.RegionHeight);
|
||||
if (store is null || store.Length < storeLength)
|
||||
{
|
||||
store?.Dispose();
|
||||
store = null;
|
||||
store = device.AllocateReadWriteBuffer<Float4>(storeLength);
|
||||
}
|
||||
}
|
||||
|
||||
if (sampleValues.Length > 0)
|
||||
samples.CopyFrom(sampleValues);
|
||||
return job;
|
||||
}
|
||||
|
||||
public ReadWriteBuffer<Float4> StoreFor(in GpuTileJob job)
|
||||
=> job.Store ? store ?? throw new InvalidOperationException() : spare;
|
||||
|
||||
public ReadOnlySpan<uint> ReadReport(in GpuTileJob job)
|
||||
{
|
||||
var length = job.Layout.Length;
|
||||
if (report is null || readBack is null || report.Length < length)
|
||||
throw new InvalidOperationException();
|
||||
readBack.CopyFrom(report, 0, 0, length);
|
||||
return readBack.Span[..length];
|
||||
}
|
||||
|
||||
public void ReadStore(in GpuTileJob job, Span<Float4> destination)
|
||||
{
|
||||
var length = job.Plan.RegionWidth * job.Plan.RegionHeight;
|
||||
if (!job.Store || store is null || destination.Length < length)
|
||||
throw new InvalidOperationException();
|
||||
store.CopyTo(destination[..length], 0);
|
||||
}
|
||||
|
||||
public void ReleaseStore()
|
||||
{
|
||||
store?.Dispose();
|
||||
store = null;
|
||||
}
|
||||
|
||||
public static void Record(
|
||||
in ComputeContext context,
|
||||
ReadWriteTexture2D<Bgra32, Float4> source,
|
||||
ReadWriteTexture2D<Bgra32, Float4> output,
|
||||
ReadWriteBuffer<Float4> tiles,
|
||||
ReadOnlyBuffer<Float2> twiddles,
|
||||
ReadOnlyBuffer<Float2> spectrum,
|
||||
ReadWriteBuffer<uint> report,
|
||||
ReadOnlyBuffer<Int2> samples,
|
||||
ReadWriteBuffer<Float4> store,
|
||||
in GpuTileJob job)
|
||||
{
|
||||
var plan = job.Plan;
|
||||
var layout = job.Layout;
|
||||
context.For(1, new ReportResetShader(report));
|
||||
context.Barrier(report);
|
||||
if (job.SampleCount > 0)
|
||||
{
|
||||
context.For(layout.KernelArea, job.SampleCount, new GatherShader(
|
||||
source, samples, report, layout.GatheredOffset, plan.Radius, job.SampleCount,
|
||||
plan.RegionX, plan.RegionY, job.SourceX, job.SourceY, job.SourceWidth, job.SourceHeight));
|
||||
}
|
||||
|
||||
var scale = 1f / plan.TileElements;
|
||||
for (var start = 0; start < plan.TileCount; start += plan.BatchTiles)
|
||||
{
|
||||
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);
|
||||
}
|
||||
|
||||
context.Barrier(report);
|
||||
}
|
||||
|
||||
public static void RecordStored(
|
||||
in ComputeContext context,
|
||||
ReadWriteBuffer<Float4> store,
|
||||
ReadWriteTexture2D<Bgra32, Float4> output,
|
||||
int width,
|
||||
int height,
|
||||
float gain)
|
||||
=> context.For(width, height, new StoredRenderShader(store, output, width, height, gain));
|
||||
|
||||
public void Dispose()
|
||||
{
|
||||
tiles?.Dispose();
|
||||
twiddles?.Dispose();
|
||||
spectrum?.Dispose();
|
||||
report?.Dispose();
|
||||
readBack?.Dispose();
|
||||
store?.Dispose();
|
||||
samples.Dispose();
|
||||
spare.Dispose();
|
||||
tiles = null;
|
||||
twiddles = null;
|
||||
spectrum = null;
|
||||
report = null;
|
||||
readBack = null;
|
||||
store = null;
|
||||
spectrumSize = 0;
|
||||
spectrumRadius = -1;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,493 @@
|
||||
using ComputeWeave;
|
||||
|
||||
namespace SpectralConvolution;
|
||||
|
||||
[ThreadGroupSize(DefaultThreadGroupSizes.X)]
|
||||
[GeneratedComputeShaderDescriptor]
|
||||
internal readonly partial struct ReportResetShader(
|
||||
ReadWriteBuffer<uint> report) : IComputeShader
|
||||
{
|
||||
private readonly ReadWriteBuffer<uint> report = report;
|
||||
|
||||
public void Execute()
|
||||
{
|
||||
if (ThreadIds.X == 0)
|
||||
report[0] = 0u;
|
||||
}
|
||||
}
|
||||
|
||||
[ThreadGroupSize(DefaultThreadGroupSizes.XY)]
|
||||
[GeneratedComputeShaderDescriptor]
|
||||
[CompileOptions(CompileOptions.Default | CompileOptions.IeeeStrictness)]
|
||||
internal readonly partial struct StoredRenderShader(
|
||||
ReadWriteBuffer<Float4> store,
|
||||
ReadWriteTexture2D<Bgra32, Float4> output,
|
||||
int width,
|
||||
int height,
|
||||
float gain) : 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;
|
||||
|
||||
public void Execute()
|
||||
{
|
||||
if (ThreadIds.X >= width || ThreadIds.Y >= height)
|
||||
return;
|
||||
output[ThreadIds.XY] = store[ThreadIds.Y * width + ThreadIds.X] * gain;
|
||||
}
|
||||
}
|
||||
|
||||
[ThreadGroupSize(DefaultThreadGroupSizes.XY)]
|
||||
[GeneratedComputeShaderDescriptor]
|
||||
[CompileOptions(CompileOptions.Default | CompileOptions.IeeeStrictness)]
|
||||
internal readonly partial struct GatherShader(
|
||||
ReadWriteTexture2D<Bgra32, Float4> source,
|
||||
ReadOnlyBuffer<Int2> samples,
|
||||
ReadWriteBuffer<uint> report,
|
||||
int gatheredOffset,
|
||||
int radius,
|
||||
int sampleCount,
|
||||
int regionX,
|
||||
int regionY,
|
||||
int sourceX,
|
||||
int sourceY,
|
||||
int sourceWidth,
|
||||
int sourceHeight) : IComputeShader
|
||||
{
|
||||
private readonly ReadWriteTexture2D<Bgra32, Float4> source = source;
|
||||
private readonly ReadOnlyBuffer<Int2> samples = samples;
|
||||
private readonly ReadWriteBuffer<uint> report = report;
|
||||
private readonly int gatheredOffset = gatheredOffset;
|
||||
private readonly int radius = radius;
|
||||
private readonly int sampleCount = sampleCount;
|
||||
private readonly int regionX = regionX;
|
||||
private readonly int regionY = regionY;
|
||||
private readonly int sourceX = sourceX;
|
||||
private readonly int sourceY = sourceY;
|
||||
private readonly int sourceWidth = sourceWidth;
|
||||
private readonly int sourceHeight = sourceHeight;
|
||||
|
||||
public void Execute()
|
||||
{
|
||||
var kernelSize = radius * 2 + 1;
|
||||
var area = kernelSize * kernelSize;
|
||||
var index = ThreadIds.X;
|
||||
var sample = ThreadIds.Y;
|
||||
if (index >= area || sample >= sampleCount)
|
||||
return;
|
||||
|
||||
var position = samples[sample];
|
||||
var x = regionX + position.X + index % kernelSize - radius - sourceX;
|
||||
var y = regionY + position.Y + index / kernelSize - radius - sourceY;
|
||||
var packed = 0u;
|
||||
if (x >= 0 && x < sourceWidth && y >= 0 && y < sourceHeight)
|
||||
{
|
||||
var value = source[new Int2(x, y)];
|
||||
packed = (uint)(value.X * 255f + 0.5f)
|
||||
| ((uint)(value.Y * 255f + 0.5f) << 8)
|
||||
| ((uint)(value.Z * 255f + 0.5f) << 16)
|
||||
| ((uint)(value.W * 255f + 0.5f) << 24);
|
||||
}
|
||||
|
||||
report[gatheredOffset + sample * area + index] = packed;
|
||||
}
|
||||
}
|
||||
|
||||
[ThreadGroupSize(256, 1, 1)]
|
||||
[GeneratedComputeShaderDescriptor]
|
||||
[CompileOptions(CompileOptions.Default | CompileOptions.IeeeStrictness)]
|
||||
internal readonly partial struct ForwardRowShader(
|
||||
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) : 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;
|
||||
|
||||
[GroupShared(512)]
|
||||
private static readonly Float4[] row = null!;
|
||||
|
||||
[GroupShared(6)]
|
||||
private static readonly uint[] statistics = 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;
|
||||
if (local < 6)
|
||||
statistics[local] = 0u;
|
||||
Hlsl.GroupMemoryBarrierWithGroupSync();
|
||||
|
||||
var sumRed = 0u;
|
||||
var sumGreen = 0u;
|
||||
var sumBlue = 0u;
|
||||
var sumAlpha = 0u;
|
||||
var squareRedGreen = 0u;
|
||||
var squareBlueAlpha = 0u;
|
||||
for (var pair = 0; pair < 2; pair++)
|
||||
{
|
||||
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 value = new Float4(0f, 0f, 0f, 0f);
|
||||
var column = canvasX - sourceX;
|
||||
var line = canvasY - sourceY;
|
||||
if (column >= 0 && column < sourceWidth && line >= 0 && line < sourceHeight)
|
||||
{
|
||||
value = source[new Int2(column, line)];
|
||||
var red = (uint)(value.X * 255f + 0.5f);
|
||||
var green = (uint)(value.Y * 255f + 0.5f);
|
||||
var blue = (uint)(value.Z * 255f + 0.5f);
|
||||
var alpha = (uint)(value.W * 255f + 0.5f);
|
||||
squareRedGreen += red * red + green * green;
|
||||
squareBlueAlpha += blue * blue + alpha * alpha;
|
||||
if (x >= radius && x < size - radius && y >= radius && y < size - radius
|
||||
&& canvasX < regionX + regionWidth && canvasY < regionY + regionHeight)
|
||||
{
|
||||
sumRed += red;
|
||||
sumGreen += green;
|
||||
sumBlue += blue;
|
||||
sumAlpha += alpha;
|
||||
}
|
||||
}
|
||||
|
||||
var reversed = (int)(Hlsl.ReverseBits((uint)x) >> shift);
|
||||
row[((element >> log2Size) << log2Size) + reversed] = value;
|
||||
}
|
||||
|
||||
Hlsl.InterlockedAdd(ref statistics[0], sumRed);
|
||||
Hlsl.InterlockedAdd(ref statistics[1], sumGreen);
|
||||
Hlsl.InterlockedAdd(ref statistics[2], sumBlue);
|
||||
Hlsl.InterlockedAdd(ref statistics[3], sumAlpha);
|
||||
Hlsl.InterlockedAdd(ref statistics[4], squareRedGreen);
|
||||
Hlsl.InterlockedAdd(ref statistics[5], squareBlueAlpha);
|
||||
Hlsl.GroupMemoryBarrierWithGroupSync();
|
||||
if (local < 6)
|
||||
report[statisticsOffset + (groupStart + (ThreadIds.X >> 8)) * 6 + local] = statistics[local];
|
||||
|
||||
Butterflies(local, 1f);
|
||||
|
||||
tiles[groupBase + local * 2] = row[local * 2];
|
||||
tiles[groupBase + local * 2 + 1] = row[local * 2 + 1];
|
||||
}
|
||||
|
||||
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 ColumnShader(
|
||||
ReadWriteBuffer<Float4> tiles,
|
||||
ReadOnlyBuffer<Float2> twiddles,
|
||||
ReadOnlyBuffer<Float2> spectrum,
|
||||
int log2Size) : IComputeShader
|
||||
{
|
||||
private readonly ReadWriteBuffer<Float4> tiles = tiles;
|
||||
private readonly ReadOnlyBuffer<Float2> twiddles = twiddles;
|
||||
private readonly ReadOnlyBuffer<Float2> spectrum = spectrum;
|
||||
private readonly int log2Size = log2Size;
|
||||
|
||||
[GroupShared(512)]
|
||||
private static readonly Float4[] row = null!;
|
||||
|
||||
public void Execute()
|
||||
{
|
||||
var local = GroupIds.X;
|
||||
var group = ThreadIds.X >> 8;
|
||||
var mask = (int)(1u << log2Size) - 1;
|
||||
var shift = 32 - log2Size;
|
||||
var log2Columns = 9 - log2Size;
|
||||
var columnMask = (int)(1u << log2Columns) - 1;
|
||||
var groupsPerTile = (int)(1u << (log2Size - log2Columns));
|
||||
var tile = group / groupsPerTile;
|
||||
var firstColumn = (group % groupsPerTile) << log2Columns;
|
||||
var tileBase = tile << (log2Size * 2);
|
||||
|
||||
var element0 = local * 2;
|
||||
var element1 = local * 2 + 1;
|
||||
var y0 = element0 >> log2Columns;
|
||||
var column0 = element0 & columnMask;
|
||||
var y1 = element1 >> log2Columns;
|
||||
var column1 = element1 & columnMask;
|
||||
var global0 = tileBase + (y0 << log2Size) + firstColumn + column0;
|
||||
var global1 = tileBase + (y1 << log2Size) + firstColumn + column1;
|
||||
row[(column0 << log2Size) + (int)(Hlsl.ReverseBits((uint)y0) >> shift)] = tiles[global0];
|
||||
row[(column1 << log2Size) + (int)(Hlsl.ReverseBits((uint)y1) >> shift)] = tiles[global1];
|
||||
Hlsl.GroupMemoryBarrierWithGroupSync();
|
||||
|
||||
Butterflies(local, 1f);
|
||||
|
||||
var frequency0 = element0 & mask;
|
||||
var frequency1 = element1 & mask;
|
||||
var product0 = Multiply(row[element0], spectrum[((firstColumn + (element0 >> log2Size)) << log2Size) + frequency0]);
|
||||
var product1 = Multiply(row[element1], spectrum[((firstColumn + (element1 >> log2Size)) << log2Size) + frequency1]);
|
||||
Hlsl.GroupMemoryBarrierWithGroupSync();
|
||||
row[((element0 >> log2Size) << log2Size) + (int)(Hlsl.ReverseBits((uint)frequency0) >> shift)] = product0;
|
||||
row[((element1 >> log2Size) << log2Size) + (int)(Hlsl.ReverseBits((uint)frequency1) >> shift)] = product1;
|
||||
Hlsl.GroupMemoryBarrierWithGroupSync();
|
||||
|
||||
Butterflies(local, -1f);
|
||||
|
||||
tiles[global0] = row[(column0 << log2Size) + y0];
|
||||
tiles[global1] = row[(column1 << log2Size) + y1];
|
||||
}
|
||||
|
||||
private static Float4 Multiply(Float4 value, Float2 weight)
|
||||
=> new(
|
||||
value.X * weight.X - value.Y * weight.Y,
|
||||
value.X * weight.Y + value.Y * weight.X,
|
||||
value.Z * weight.X - value.W * weight.Y,
|
||||
value.Z * weight.Y + value.W * weight.X);
|
||||
|
||||
private void Butterflies(int local, float direction)
|
||||
{
|
||||
var halfSize = (int)(1u << (log2Size - 1));
|
||||
var rowBase = (local >> (log2Size - 1)) << log2Size;
|
||||
var pair = local & (halfSize - 1);
|
||||
for (var stage = 0; stage < log2Size; stage++)
|
||||
{
|
||||
var 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 InverseRowShader(
|
||||
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 regionWidth,
|
||||
int regionHeight,
|
||||
float scale,
|
||||
float gain,
|
||||
int sampleCount,
|
||||
int sumsOffset,
|
||||
int spotsOffset,
|
||||
int groupStart,
|
||||
int storeValues) : 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 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;
|
||||
|
||||
[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);
|
||||
|
||||
partial[local] = Emit(groupBase + element0, row[element0] * scale, size, mask) + Emit(groupBase + element1, row[element1] * scale, size, mask);
|
||||
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 Float4 Emit(int flat, Float4 value, int size, int mask)
|
||||
{
|
||||
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;
|
||||
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++)
|
||||
{
|
||||
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();
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,90 @@
|
||||
using ComputeWeave;
|
||||
|
||||
namespace SpectralConvolution;
|
||||
|
||||
internal sealed class KernelSpectrum
|
||||
{
|
||||
double[] kernel = [];
|
||||
double[] real = [];
|
||||
double[] imaginary = [];
|
||||
Float2[] twiddles = [];
|
||||
Float2[] spectrum = [];
|
||||
|
||||
public int Size { get; private set; }
|
||||
|
||||
public int Radius { get; private set; }
|
||||
|
||||
public int KernelSize => Radius * 2 + 1;
|
||||
|
||||
public ReadOnlySpan<double> Kernel => kernel.AsSpan(0, Size == 0 ? 0 : KernelSize * KernelSize);
|
||||
|
||||
public ReadOnlySpan<Float2> Twiddles => twiddles.AsSpan(0, Size / 2);
|
||||
|
||||
public ReadOnlySpan<Float2> Spectrum => spectrum.AsSpan(0, Size * Size);
|
||||
|
||||
public void Update(ReadOnlySpan<double> values, int radius, int size)
|
||||
{
|
||||
_ = TilePlan.Create(size, radius, 0, 0, 1, 1);
|
||||
var kernelSize = radius * 2 + 1;
|
||||
var kernelArea = kernelSize * kernelSize;
|
||||
if (values.Length != kernelArea)
|
||||
throw new ArgumentException(null, nameof(values));
|
||||
|
||||
var sum = 0d;
|
||||
foreach (var value in values)
|
||||
{
|
||||
if (!double.IsFinite(value) || value < 0d)
|
||||
throw new ArgumentOutOfRangeException(nameof(values));
|
||||
sum += value;
|
||||
}
|
||||
if (!double.IsFinite(sum) || sum <= 0d)
|
||||
throw new ArgumentOutOfRangeException(nameof(values));
|
||||
|
||||
var area = size * size;
|
||||
Size = 0;
|
||||
Radius = 0;
|
||||
if (kernel.Length < kernelArea)
|
||||
kernel = new double[kernelArea];
|
||||
if (real.Length < area)
|
||||
{
|
||||
real = new double[area];
|
||||
imaginary = new double[area];
|
||||
spectrum = new Float2[area];
|
||||
}
|
||||
if (twiddles.Length < size / 2)
|
||||
twiddles = new Float2[size / 2];
|
||||
|
||||
for (var index = 0; index < kernelArea; index++)
|
||||
kernel[index] = values[index] / sum;
|
||||
|
||||
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));
|
||||
}
|
||||
|
||||
real.AsSpan(0, area).Clear();
|
||||
imaginary.AsSpan(0, area).Clear();
|
||||
var mask = size - 1;
|
||||
for (var offsetY = -radius; offsetY <= radius; offsetY++)
|
||||
{
|
||||
for (var offsetX = -radius; offsetX <= radius; offsetX++)
|
||||
real[(-offsetY & mask) * size + (-offsetX & mask)] = kernel[(offsetY + radius) * kernelSize + offsetX + radius];
|
||||
}
|
||||
|
||||
FastFourierTransform.Forward2D(real, imaginary, size, size);
|
||||
for (var frequencyY = 0; frequencyY < size; frequencyY++)
|
||||
{
|
||||
for (var frequencyX = 0; frequencyX < size; frequencyX++)
|
||||
{
|
||||
var index = frequencyY * size + frequencyX;
|
||||
spectrum[frequencyX * size + frequencyY] = new Float2(Flush((float)real[index]), Flush((float)imaginary[index]));
|
||||
}
|
||||
}
|
||||
|
||||
Size = size;
|
||||
Radius = radius;
|
||||
}
|
||||
|
||||
public static float Flush(float value) => float.IsSubnormal(value) ? float.CopySign(0f, value) : value;
|
||||
}
|
||||
@@ -0,0 +1,22 @@
|
||||
<Project Sdk="Microsoft.NET.Sdk">
|
||||
|
||||
<PropertyGroup>
|
||||
<TargetFramework>net10.0-windows10.0.19041.0</TargetFramework>
|
||||
<ImplicitUsings>enable</ImplicitUsings>
|
||||
<Nullable>enable</Nullable>
|
||||
<PlatformTarget>x64</PlatformTarget>
|
||||
<AllowUnsafeBlocks>true</AllowUnsafeBlocks>
|
||||
<Version>1.0.0</Version>
|
||||
</PropertyGroup>
|
||||
|
||||
<ItemGroup>
|
||||
<PackageReference Include="ComputeWeave" Version="2.6.0" />
|
||||
</ItemGroup>
|
||||
|
||||
<ItemGroup>
|
||||
<AssemblyAttribute Include="System.Runtime.CompilerServices.InternalsVisibleToAttribute">
|
||||
<_Parameter1>SpectralConvolution.Tests</_Parameter1>
|
||||
</AssemblyAttribute>
|
||||
</ItemGroup>
|
||||
|
||||
</Project>
|
||||
@@ -0,0 +1,196 @@
|
||||
using System.Runtime.InteropServices;
|
||||
using ComputeWeave;
|
||||
|
||||
namespace SpectralConvolution;
|
||||
|
||||
internal static class SpectralSelfTest
|
||||
{
|
||||
public const string DeterminismName = "selftest.determinism";
|
||||
public const string FullName = "selftest.full";
|
||||
public const int FullRadius = 3;
|
||||
public const int Margin = 4;
|
||||
|
||||
static readonly int[] Sizes = [TilePlan.SmallSize, TilePlan.LargeSize];
|
||||
|
||||
public static int MeasurementCount => Sizes.Length * (2 + 2 * GpuTileCheck.MeasurementCount(GpuTileConvolver.MaximumSamples));
|
||||
|
||||
public static int Run(GraphicsDevice device, int maximumRadius, Span<ConvolutionMeasurement> measurements)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(device);
|
||||
ArgumentOutOfRangeException.ThrowIfLessThan(maximumRadius, FullRadius);
|
||||
if (measurements.Length < MeasurementCount)
|
||||
throw new ArgumentException(null, nameof(measurements));
|
||||
|
||||
var written = 0;
|
||||
using var convolver = new GpuTileConvolver(device);
|
||||
foreach (var size in Sizes)
|
||||
{
|
||||
written += RunFull(device, convolver, size, measurements[written..]);
|
||||
var radius = Math.Min(maximumRadius, size == TilePlan.SmallSize ? TilePlan.SmallSizeRadiusLimit : TilePlan.MaximumRadius);
|
||||
written += RunChecked(device, convolver, size, Math.Min(radius, (size - 2) / 2), measurements[written..]);
|
||||
}
|
||||
|
||||
return written;
|
||||
}
|
||||
|
||||
public static double[] Kernel(int radius)
|
||||
{
|
||||
var kernelSize = radius * 2 + 1;
|
||||
var values = new double[kernelSize * kernelSize];
|
||||
var scale = radius * radius + 1d;
|
||||
for (var y = 0; y < kernelSize; y++)
|
||||
{
|
||||
for (var x = 0; x < kernelSize; x++)
|
||||
{
|
||||
var dx = x - radius * 0.6;
|
||||
var dy = y - radius * 1.3;
|
||||
values[y * kernelSize + x] = Math.Exp(-(dx * dx * 0.4 + dy * dy * 0.15) / scale);
|
||||
}
|
||||
}
|
||||
|
||||
values[(kernelSize - 1) * kernelSize] += 0.5;
|
||||
return values;
|
||||
}
|
||||
|
||||
public static byte[] Pattern(int width, int height, int seed)
|
||||
{
|
||||
var pixels = new byte[width * height * 4];
|
||||
for (var y = 0; y < height; y++)
|
||||
{
|
||||
for (var x = 0; x < width; x++)
|
||||
{
|
||||
if ((x / 37 + y / 23) % 5 == 0)
|
||||
continue;
|
||||
|
||||
var hash = Hash((uint)x, (uint)y, (uint)seed);
|
||||
var alpha = x % 61 < 3 ? 255u : hash & 255u;
|
||||
var offset = (y * width + x) * 4;
|
||||
pixels[offset] = (byte)(alpha * (hash >> 8 & 255u) / 255u);
|
||||
pixels[offset + 1] = (byte)(alpha * (hash >> 16 & 255u) / 255u);
|
||||
pixels[offset + 2] = (byte)(alpha * (hash >> 24) / 255u);
|
||||
pixels[offset + 3] = (byte)alpha;
|
||||
}
|
||||
}
|
||||
|
||||
return pixels;
|
||||
}
|
||||
|
||||
public static void Samples(int width, int height, int validSize, Span<Int2> samples)
|
||||
{
|
||||
if (samples.Length < GpuTileConvolver.MaximumSamples)
|
||||
throw new ArgumentException(null, nameof(samples));
|
||||
samples[0] = new Int2(0, 0);
|
||||
samples[1] = new Int2(width - 1, 0);
|
||||
samples[2] = new Int2(0, height - 1);
|
||||
samples[3] = new Int2(width - 1, height - 1);
|
||||
samples[4] = new Int2(width / 2, height / 2);
|
||||
samples[5] = new Int2(Math.Min(validSize - 1, width - 1), Math.Min(validSize - 1, height - 1));
|
||||
samples[6] = new Int2(Math.Min(validSize, width - 1), Math.Min(validSize, height - 1));
|
||||
for (var index = 7; index < GpuTileConvolver.MaximumSamples; index++)
|
||||
samples[index] = new Int2((int)(index * 7919L % width), (int)(index * 104729L % height));
|
||||
}
|
||||
|
||||
static int RunFull(GraphicsDevice device, GpuTileConvolver convolver, int size, Span<ConvolutionMeasurement> measurements)
|
||||
{
|
||||
var spectrum = new KernelSpectrum();
|
||||
spectrum.Update(Kernel(FullRadius), FullRadius, size);
|
||||
var validSize = size - FullRadius * 2;
|
||||
var sourceWidth = validSize + 17;
|
||||
var sourceHeight = validSize + 13;
|
||||
var plan = TilePlan.Create(size, FullRadius, 0, 0, sourceWidth + Margin * 2, sourceHeight + Margin * 2);
|
||||
var source = Pattern(sourceWidth, sourceHeight, size);
|
||||
var first = Convolve(device, convolver, spectrum, plan, source, sourceWidth, sourceHeight, measurements[2..]);
|
||||
var second = Convolve(device, convolver, spectrum, plan, source, sourceWidth, sourceHeight, []);
|
||||
|
||||
var different = 0;
|
||||
for (var index = 0; index < first.Length; index++)
|
||||
{
|
||||
if (BitConverter.SingleToUInt32Bits(first[index]) != BitConverter.SingleToUInt32Bits(second[index]))
|
||||
different++;
|
||||
}
|
||||
measurements[0] = new ConvolutionMeasurement(DeterminismName, different, 0d, 0d);
|
||||
|
||||
var norms = new (double RedGreen, double BlueAlpha)[plan.TileCount];
|
||||
for (var tile = 0; tile < plan.TileCount; tile++)
|
||||
norms[tile] = TileInput.Norms(source, Margin, Margin, sourceWidth, sourceHeight, plan, tile);
|
||||
|
||||
Span<double> expected = stackalloc double[4];
|
||||
var relative = ConvolutionBound.Relative(size, ConvolutionBound.GpuOperationError);
|
||||
var absolute = ConvolutionBound.FlushedOperations(size) * ConvolutionBound.SmallestNormal + DirectCorrelation.ErrorBound(spectrum.Kernel.Length);
|
||||
var worst = 0d;
|
||||
for (var y = 0; y < plan.RegionHeight; y++)
|
||||
{
|
||||
for (var x = 0; x < plan.RegionWidth; x++)
|
||||
{
|
||||
DirectCorrelation.Evaluate(source, sourceWidth, sourceHeight, spectrum.Kernel, FullRadius, x - Margin, y - Margin, expected);
|
||||
var (redGreen, blueAlpha) = norms[plan.TileAt(x, y)];
|
||||
for (var channel = 0; channel < 4; channel++)
|
||||
{
|
||||
var bound = relative * (channel < 2 ? redGreen : blueAlpha) + absolute;
|
||||
var error = Math.Abs(first[(y * plan.RegionWidth + x) * 4 + channel] - expected[channel]);
|
||||
worst = Math.Max(worst, double.IsNaN(error) ? double.PositiveInfinity : error / bound);
|
||||
}
|
||||
}
|
||||
}
|
||||
measurements[1] = new ConvolutionMeasurement(FullName, worst, 0d, 1d);
|
||||
return 2 + GpuTileCheck.MeasurementCount(GpuTileConvolver.MaximumSamples);
|
||||
}
|
||||
|
||||
static int RunChecked(GraphicsDevice device, GpuTileConvolver convolver, int size, int radius, Span<ConvolutionMeasurement> measurements)
|
||||
{
|
||||
var spectrum = new KernelSpectrum();
|
||||
spectrum.Update(Kernel(radius), radius, size);
|
||||
var validSize = size - radius * 2;
|
||||
var sourceWidth = validSize + 9;
|
||||
var sourceHeight = validSize + 5;
|
||||
var margin = radius + Margin;
|
||||
var plan = TilePlan.Create(size, radius, 0, 0, sourceWidth + margin * 2, sourceHeight + margin * 2);
|
||||
var source = Pattern(sourceWidth, sourceHeight, size + radius);
|
||||
_ = Convolve(device, convolver, spectrum, plan, source, sourceWidth, sourceHeight, measurements, margin);
|
||||
return GpuTileCheck.MeasurementCount(GpuTileConvolver.MaximumSamples);
|
||||
}
|
||||
|
||||
static float[] Convolve(
|
||||
GraphicsDevice device,
|
||||
GpuTileConvolver convolver,
|
||||
KernelSpectrum spectrum,
|
||||
in TilePlan plan,
|
||||
byte[] source,
|
||||
int sourceWidth,
|
||||
int sourceHeight,
|
||||
Span<ConvolutionMeasurement> measurements,
|
||||
int margin = Margin)
|
||||
{
|
||||
Span<Int2> samples = stackalloc Int2[GpuTileConvolver.MaximumSamples];
|
||||
Samples(plan.RegionWidth, plan.RegionHeight, plan.ValidSize, samples);
|
||||
convolver.Upload(spectrum);
|
||||
var job = convolver.Prepare(plan, margin, margin, sourceWidth, sourceHeight, 1f, samples, true);
|
||||
using var sourceTexture = device.AllocateReadWriteTexture2D<Bgra32, Float4>(sourceWidth, sourceHeight);
|
||||
sourceTexture.CopyFrom(MemoryMarshal.Cast<byte, Bgra32>(source));
|
||||
using var output = device.AllocateReadWriteTexture2D<Bgra32, Float4>(plan.RegionWidth, plan.RegionHeight);
|
||||
using (var context = device.CreateComputeContext())
|
||||
{
|
||||
GpuTileConvolver.Record(
|
||||
in context, sourceTexture, output, convolver.Tiles, convolver.Twiddles, convolver.Spectrum,
|
||||
convolver.Report, convolver.Samples, convolver.StoreFor(job), job);
|
||||
}
|
||||
|
||||
if (!measurements.IsEmpty)
|
||||
GpuTileCheck.Evaluate(convolver.ReadReport(job), job, samples, spectrum.Kernel, measurements);
|
||||
var values = new Float4[plan.RegionWidth * plan.RegionHeight];
|
||||
convolver.ReadStore(job, values);
|
||||
convolver.ReleaseStore();
|
||||
return MemoryMarshal.Cast<Float4, float>(values.AsSpan()).ToArray();
|
||||
}
|
||||
|
||||
static uint Hash(uint x, uint y, uint seed)
|
||||
{
|
||||
var value = x * 0x9E3779B9u ^ y * 0x85EBCA6Bu ^ seed * 0xC2B2AE35u;
|
||||
value ^= value >> 16;
|
||||
value *= 0x7FEB352Du;
|
||||
value ^= value >> 15;
|
||||
value *= 0x846CA68Bu;
|
||||
value ^= value >> 16;
|
||||
return value;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,41 @@
|
||||
namespace SpectralConvolution;
|
||||
|
||||
internal static class TileInput
|
||||
{
|
||||
const int Channels = 4;
|
||||
|
||||
public static (double RedGreen, double BlueAlpha) Norms(
|
||||
ReadOnlySpan<byte> bgra,
|
||||
int sourceX,
|
||||
int sourceY,
|
||||
int sourceWidth,
|
||||
int sourceHeight,
|
||||
in TilePlan plan,
|
||||
int tile)
|
||||
{
|
||||
if (bgra.Length < (long)sourceWidth * sourceHeight * Channels)
|
||||
throw new ArgumentException(null, nameof(bgra));
|
||||
|
||||
var left = plan.OriginX(tile) - plan.Radius;
|
||||
var top = plan.OriginY(tile) - plan.Radius;
|
||||
var redGreen = 0L;
|
||||
var blueAlpha = 0L;
|
||||
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) * Channels;
|
||||
long blue = bgra[offset];
|
||||
long green = bgra[offset + 1];
|
||||
long red = bgra[offset + 2];
|
||||
long alpha = bgra[offset + 3];
|
||||
redGreen += red * red + green * green;
|
||||
blueAlpha += blue * blue + alpha * alpha;
|
||||
}
|
||||
}
|
||||
|
||||
return (Math.Sqrt(redGreen) / 255d, Math.Sqrt(blueAlpha) / 255d);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,93 @@
|
||||
using System.Numerics;
|
||||
|
||||
namespace SpectralConvolution;
|
||||
|
||||
internal readonly record struct TilePlan
|
||||
{
|
||||
public const int MinimumSize = 64;
|
||||
public const int MaximumSize = 512;
|
||||
public const int SmallSize = 128;
|
||||
public const int LargeSize = 512;
|
||||
public const int SmallSizeRadiusLimit = 23;
|
||||
public const int MaximumRadius = (LargeSize - 1) / 2;
|
||||
public const int GroupElements = 512;
|
||||
public const int ElementBytes = 16;
|
||||
public const long BatchBudgetBytes = 16L << 20;
|
||||
|
||||
TilePlan(int size, int radius, int regionX, int regionY, int regionWidth, int regionHeight)
|
||||
{
|
||||
Size = size;
|
||||
Log2Size = BitOperations.Log2((uint)size);
|
||||
Radius = radius;
|
||||
RegionX = regionX;
|
||||
RegionY = regionY;
|
||||
RegionWidth = regionWidth;
|
||||
RegionHeight = regionHeight;
|
||||
TilesX = (regionWidth + ValidSize - 1) / ValidSize;
|
||||
TilesY = (regionHeight + ValidSize - 1) / ValidSize;
|
||||
}
|
||||
|
||||
public int Size { get; }
|
||||
|
||||
public int Log2Size { get; }
|
||||
|
||||
public int Radius { get; }
|
||||
|
||||
public int RegionX { get; }
|
||||
|
||||
public int RegionY { get; }
|
||||
|
||||
public int RegionWidth { get; }
|
||||
|
||||
public int RegionHeight { get; }
|
||||
|
||||
public int TilesX { get; }
|
||||
|
||||
public int TilesY { get; }
|
||||
|
||||
public int ValidSize => Size - 2 * Radius;
|
||||
|
||||
public int TileCount => TilesX * TilesY;
|
||||
|
||||
public int TileElements => Size * Size;
|
||||
|
||||
public int GroupsPerTile => TileElements / GroupElements;
|
||||
|
||||
public int GroupCount => TileCount * GroupsPerTile;
|
||||
|
||||
public int BatchTiles => (int)Math.Min(TileCount, Math.Max(1L, BatchBudgetBytes / ((long)ElementBytes * TileElements)));
|
||||
|
||||
public static int SelectSize(int radius)
|
||||
{
|
||||
ArgumentOutOfRangeException.ThrowIfNegative(radius);
|
||||
ArgumentOutOfRangeException.ThrowIfGreaterThan(radius, MaximumRadius);
|
||||
return radius <= SmallSizeRadiusLimit ? SmallSize : LargeSize;
|
||||
}
|
||||
|
||||
public static TilePlan Create(int radius, int regionX, int regionY, int regionWidth, int regionHeight)
|
||||
=> Create(SelectSize(radius), radius, regionX, regionY, regionWidth, regionHeight);
|
||||
|
||||
public static TilePlan Create(int size, int radius, int regionX, int regionY, int regionWidth, int regionHeight)
|
||||
{
|
||||
if (!IsSupportedSize(size))
|
||||
throw new ArgumentOutOfRangeException(nameof(size));
|
||||
ArgumentOutOfRangeException.ThrowIfNegative(radius);
|
||||
ArgumentOutOfRangeException.ThrowIfGreaterThanOrEqual(radius * 2, size);
|
||||
ArgumentOutOfRangeException.ThrowIfNegativeOrZero(regionWidth);
|
||||
ArgumentOutOfRangeException.ThrowIfNegativeOrZero(regionHeight);
|
||||
return new TilePlan(size, radius, regionX, regionY, regionWidth, regionHeight);
|
||||
}
|
||||
|
||||
public static bool IsSupportedSize(int size)
|
||||
=> size is >= MinimumSize and <= MaximumSize && BitOperations.IsPow2(size);
|
||||
|
||||
public int OriginX(int tile) => RegionX + tile % TilesX * ValidSize;
|
||||
|
||||
public int OriginY(int tile) => RegionY + tile / TilesX * ValidSize;
|
||||
|
||||
public int TileAt(int x, int y) => (y - RegionY) / ValidSize * TilesX + (x - RegionX) / ValidSize;
|
||||
|
||||
public int ValidWidth(int tile) => Math.Min(ValidSize, RegionX + RegionWidth - OriginX(tile));
|
||||
|
||||
public int ValidHeight(int tile) => Math.Min(ValidSize, RegionY + RegionHeight - OriginY(tile));
|
||||
}
|
||||
@@ -9,7 +9,9 @@ internal sealed record GoldenCase(string Name, IReadOnlyList<int> Frames, string
|
||||
|
||||
internal sealed record Golden(string Adapter, string Driver, string Input, string Canvas, IReadOnlyList<GoldenCase> Cases)
|
||||
{
|
||||
const string FileName = "golden.json";
|
||||
const string FileName = "golden";
|
||||
const string Extension = ".json";
|
||||
const string CpuSuffix = "-cpu";
|
||||
const string DirectoryKey = "HarnessDirectory";
|
||||
|
||||
static readonly JsonSerializerOptions Options = new()
|
||||
@@ -20,8 +22,8 @@ internal sealed record Golden(string Adapter, string Driver, string Input, strin
|
||||
NewLine = "\n",
|
||||
};
|
||||
|
||||
public static string PathFor(HarnessImage image)
|
||||
=> Path.Combine(ReadDirectory(), image.Key is null ? FileName : $"golden-{image.Key}.json");
|
||||
public static string PathFor(HarnessImage image, bool cpu)
|
||||
=> Path.Combine(ReadDirectory(), (image.Key is null ? FileName : $"{FileName}-{image.Key}") + (cpu ? CpuSuffix : string.Empty) + Extension);
|
||||
|
||||
public static Golden Load(string path)
|
||||
{
|
||||
|
||||
@@ -13,23 +13,25 @@ internal enum HarnessMode
|
||||
Convolution,
|
||||
}
|
||||
|
||||
internal sealed record HarnessArguments(HarnessMode Mode, string? Input, string? OutputDirectory, string? Before, string? After)
|
||||
internal sealed record HarnessArguments(HarnessMode Mode, string? Input, string? OutputDirectory, string? Before, string? After, bool Cpu)
|
||||
{
|
||||
public const string Usage = """
|
||||
使い方:
|
||||
[<出力先>] [--input <画像>] ケースを描き、PNG とハッシュを出します
|
||||
--golden [--input <画像>] 基準値を golden.json に書きます
|
||||
--verify [--input <画像>] 基準値と照合します
|
||||
--transition [<出力先>] [--input <画像>] 設定を変えた後とフレームを進めた後の描画を、作り直した描画と照合します
|
||||
--compare <前> <後> 2 つの出力先の PNG を画素ごとに比べます
|
||||
--benchmark [--input <画像>] 描画を計測します
|
||||
--convolution [--input <画像>] 畳み込みの計算し直しに掛かる時間を、変えた値ごとに計測します
|
||||
[<出力先>] [--input <画像>] [--cpu] ケースを描き、PNG とハッシュを出します
|
||||
--golden [--input <画像>] [--cpu] 基準値を golden.json に書きます
|
||||
--verify [--input <画像>] [--cpu] 基準値と照合します
|
||||
--transition [<出力先>] [--input <画像>] [--cpu] 設定を変えた後とフレームを進めた後の描画を、作り直した描画と照合します
|
||||
--compare <前> <後> 2 つの出力先の PNG を画素ごとに比べます
|
||||
--benchmark [--input <画像>] [--cpu] 描画を計測します
|
||||
--convolution [--input <画像>] 畳み込みの計算し直しに掛かる時間を、変えた値と経路ごとに計測します
|
||||
--cpu を付けると、GPU を使わずに CPU の経路で描きます。基準値は golden-cpu.json に分けて持ちます。
|
||||
""";
|
||||
|
||||
public static HarnessArguments Parse(string[] arguments)
|
||||
{
|
||||
HarnessMode? mode = null;
|
||||
string? input = null;
|
||||
var cpu = false;
|
||||
var positionals = new List<string>();
|
||||
for (var index = 0; index < arguments.Length; index++)
|
||||
{
|
||||
@@ -54,6 +56,9 @@ internal sealed record HarnessArguments(HarnessMode Mode, string? Input, string?
|
||||
case "--convolution":
|
||||
mode = Select(mode, HarnessMode.Convolution);
|
||||
break;
|
||||
case "--cpu":
|
||||
cpu = true;
|
||||
break;
|
||||
case "--input":
|
||||
if (index + 1 >= arguments.Length)
|
||||
throw new HarnessException("--input には画像のパスを続けてください。");
|
||||
@@ -68,6 +73,8 @@ internal sealed record HarnessArguments(HarnessMode Mode, string? Input, string?
|
||||
}
|
||||
|
||||
var selected = mode ?? HarnessMode.Render;
|
||||
if (cpu && selected is HarnessMode.Compare or HarnessMode.Convolution)
|
||||
throw new HarnessException("--cpu は --compare と --convolution には使えません。");
|
||||
switch (selected)
|
||||
{
|
||||
case HarnessMode.Compare:
|
||||
@@ -75,16 +82,16 @@ internal sealed record HarnessArguments(HarnessMode Mode, string? Input, string?
|
||||
throw new HarnessException("--compare には前と後の出力先を続けてください。");
|
||||
if (input is not null)
|
||||
throw new HarnessException("--compare に --input は使えません。");
|
||||
return new HarnessArguments(HarnessMode.Compare, null, null, positionals[0], positionals[1]);
|
||||
return new HarnessArguments(HarnessMode.Compare, null, null, positionals[0], positionals[1], false);
|
||||
case HarnessMode.Render:
|
||||
case HarnessMode.Transition:
|
||||
if (positionals.Count > 1)
|
||||
throw new HarnessException($"余分な引数です。{positionals[1]}");
|
||||
return new HarnessArguments(selected, input, positionals.FirstOrDefault(), null, null);
|
||||
return new HarnessArguments(selected, input, positionals.FirstOrDefault(), null, null, cpu);
|
||||
default:
|
||||
if (positionals.Count > 0)
|
||||
throw new HarnessException($"余分な引数です。{positionals[0]}");
|
||||
return new HarnessArguments(selected, input, null, null, null);
|
||||
return new HarnessArguments(selected, input, null, null, null, cpu);
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -1,6 +1,8 @@
|
||||
using System.Diagnostics;
|
||||
using System.Numerics;
|
||||
using System.Runtime.InteropServices;
|
||||
using WaveOptics.Effects;
|
||||
using WaveOptics.Rendering;
|
||||
using Vortice.DCommon;
|
||||
using Vortice.Direct2D1;
|
||||
using Vortice.Direct2D1.Effects;
|
||||
@@ -32,17 +34,26 @@ internal sealed class HarnessRenderer : IDisposable
|
||||
readonly AffineTransform2D placement;
|
||||
readonly ID2D1Image centered;
|
||||
|
||||
public HarnessRenderer(int canvasWidth, int canvasHeight, HarnessImage source)
|
||||
public HarnessRenderer(int canvasWidth, int canvasHeight, HarnessImage source, bool cpu)
|
||||
{
|
||||
CanvasWidth = canvasWidth;
|
||||
CanvasHeight = canvasHeight;
|
||||
Cpu = cpu;
|
||||
|
||||
devices = new GraphicsDevices();
|
||||
context = devices.CreateContext();
|
||||
var deviceContext = context.DeviceContext;
|
||||
var adapter = devices.DXGI.Adapter;
|
||||
Adapter = adapter.Description.Description;
|
||||
Driver = adapter.CheckInterfaceSupport<IDXGIDevice>(out var version) ? FormatDriverVersion(version) : "不明";
|
||||
if (cpu)
|
||||
{
|
||||
Adapter = $"CPU {Environment.GetEnvironmentVariable("PROCESSOR_IDENTIFIER") ?? "不明"}";
|
||||
Driver = $"{RuntimeInformation.FrameworkDescription} / {RuntimeInformation.OSDescription}";
|
||||
}
|
||||
else
|
||||
{
|
||||
Adapter = adapter.Description.Description;
|
||||
Driver = adapter.CheckInterfaceSupport<IDXGIDevice>(out var version) ? FormatDriverVersion(version) : "不明";
|
||||
}
|
||||
|
||||
image = CreateBitmap(deviceContext, source.Width, source.Height, BitmapOptions.None);
|
||||
image.CopyFromMemory(source.Pixels, source.Width * HarnessImage.BytesPerPixel);
|
||||
@@ -67,12 +78,14 @@ internal sealed class HarnessRenderer : IDisposable
|
||||
|
||||
public string Driver { get; }
|
||||
|
||||
public bool Cpu { get; }
|
||||
|
||||
public byte[][] Render(IVideoEffect effect, IReadOnlyList<int> frames)
|
||||
{
|
||||
if (frames.Count == 0)
|
||||
throw new ArgumentException("フレームを 1 つ以上指定してください。", nameof(frames));
|
||||
|
||||
using var processor = effect.CreateVideoEffect(context);
|
||||
using var processor = CreateProcessor(effect);
|
||||
processor.SetInput(centered);
|
||||
try
|
||||
{
|
||||
@@ -91,6 +104,11 @@ internal sealed class HarnessRenderer : IDisposable
|
||||
}
|
||||
}
|
||||
|
||||
IVideoEffectProcessor CreateProcessor(IVideoEffect effect)
|
||||
=> Cpu && effect is WaveOpticsEffect waveOptics
|
||||
? new WaveOpticsEffectProcessor(context, waveOptics, WaveOpticsCompute.Guardian, null, false)
|
||||
: effect.CreateVideoEffect(context);
|
||||
|
||||
public (byte[] Direct, byte[] Transitioned) RenderTransition<TEffect>(Func<TEffect> create, Action<TEffect> change, int frame)
|
||||
where TEffect : IVideoEffect
|
||||
{
|
||||
@@ -99,7 +117,7 @@ internal sealed class HarnessRenderer : IDisposable
|
||||
var direct = Render(settled, [frame])[0];
|
||||
|
||||
var live = create();
|
||||
using var processor = live.CreateVideoEffect(context);
|
||||
using var processor = CreateProcessor(live);
|
||||
processor.SetInput(centered);
|
||||
try
|
||||
{
|
||||
@@ -121,7 +139,7 @@ internal sealed class HarnessRenderer : IDisposable
|
||||
for (var frame = 0; frame < frames; frame++)
|
||||
descriptions[frame] = Describe(moving ? frame : 0);
|
||||
|
||||
using var processor = effect.CreateVideoEffect(context);
|
||||
using var processor = CreateProcessor(effect);
|
||||
processor.SetInput(centered);
|
||||
var output = processor.Output;
|
||||
try
|
||||
|
||||
+125
-64
@@ -1,6 +1,7 @@
|
||||
using System.Diagnostics;
|
||||
using System.IO;
|
||||
using System.IO.Packaging;
|
||||
using System.Runtime.InteropServices;
|
||||
using System.Security.Cryptography;
|
||||
using ComputeWeave;
|
||||
using WaveOptics.Effects;
|
||||
@@ -45,19 +46,19 @@ try
|
||||
{
|
||||
if (arguments.Input is { } benchmarkInput)
|
||||
{
|
||||
Benchmark(HarnessImage.Load(benchmarkInput));
|
||||
Benchmark(HarnessImage.Load(benchmarkInput), arguments.Cpu);
|
||||
}
|
||||
else
|
||||
{
|
||||
Benchmark(HarnessImage.Synthetic(CanvasWidth, CanvasHeight));
|
||||
Benchmark(HarnessImage.Synthetic(FullHdWidth, FullHdHeight));
|
||||
Benchmark(HarnessImage.Synthetic(CanvasWidth, CanvasHeight), arguments.Cpu);
|
||||
Benchmark(HarnessImage.Synthetic(FullHdWidth, FullHdHeight), arguments.Cpu);
|
||||
}
|
||||
|
||||
return 0;
|
||||
}
|
||||
|
||||
var image = arguments.Input is { } input ? HarnessImage.Load(input) : HarnessImage.Synthetic(ImageWidth, ImageHeight);
|
||||
using var renderer = new HarnessRenderer(CanvasWidth, CanvasHeight, image);
|
||||
using var renderer = new HarnessRenderer(CanvasWidth, CanvasHeight, image, arguments.Cpu);
|
||||
return arguments.Mode switch
|
||||
{
|
||||
HarnessMode.Golden => WriteGolden(renderer, image),
|
||||
@@ -104,7 +105,7 @@ static int WriteGolden(HarnessRenderer renderer, HarnessImage image)
|
||||
Console.Error.WriteLine("ケースがありません。HarnessCases に書き足してください。");
|
||||
|
||||
var golden = new Golden(renderer.Adapter, renderer.Driver, image.Identity, $"{renderer.CanvasWidth}x{renderer.CanvasHeight}", cases);
|
||||
var path = Golden.PathFor(image);
|
||||
var path = Golden.PathFor(image, renderer.Cpu);
|
||||
golden.Save(path);
|
||||
Console.WriteLine($"adapter: {golden.Adapter} (driver {golden.Driver})");
|
||||
Console.WriteLine($"input: {golden.Input}");
|
||||
@@ -116,7 +117,7 @@ static int WriteGolden(HarnessRenderer renderer, HarnessImage image)
|
||||
|
||||
static int Verify(HarnessRenderer renderer, HarnessImage image)
|
||||
{
|
||||
var golden = Golden.Load(Golden.PathFor(image));
|
||||
var golden = Golden.Load(Golden.PathFor(image, renderer.Cpu));
|
||||
var canvas = $"{renderer.CanvasWidth}x{renderer.CanvasHeight}";
|
||||
if (golden.Input != image.Identity || golden.Canvas != canvas)
|
||||
{
|
||||
@@ -219,83 +220,107 @@ static int Convolution(HarnessImage image)
|
||||
const int Rounds = 12;
|
||||
const int Seed = 17;
|
||||
|
||||
using var pipeline = WaveOpticsPipeline.TryCreate();
|
||||
if (pipeline is null)
|
||||
throw new HarnessException("Direct3D 12を利用できません。");
|
||||
|
||||
var device = GraphicsDevice.GetDefault();
|
||||
using var original = device.AllocateReadWriteTexture2D<Bgra32, Float4>(image.Width, image.Height);
|
||||
using var mirrored = device.AllocateReadWriteTexture2D<Bgra32, Float4>(image.Width, image.Height);
|
||||
using var output = device.AllocateReadWriteTexture2D<Bgra32, Float4>(image.Width, image.Height);
|
||||
original.CopyFrom(ToPixels(image, false));
|
||||
mirrored.CopyFrom(ToPixels(image, true));
|
||||
var originalPixels = ToPixels(image, false);
|
||||
var mirroredPixels = ToPixels(image, true);
|
||||
original.CopyFrom(originalPixels);
|
||||
mirrored.CopyFrom(mirroredPixels);
|
||||
var originalBytes = MemoryMarshal.AsBytes(originalPixels.AsSpan()).ToArray();
|
||||
var mirroredBytes = MemoryMarshal.AsBytes(mirroredPixels.AsSpan()).ToArray();
|
||||
|
||||
var parameters = new WaveOpticsPipeline.Parameters(1f, new WaveOpticsPipeline.PsfParameters(
|
||||
WaveOpticsQuality.Standard, 15, 550f, 8f, 4f, WaveOpticsApertureShape.Circular, 6, 0f, 0f, 0f, 0f, 0f, 0f, 0f, 0f));
|
||||
var variants = new (string Name, Func<bool, (ReadWriteTexture2D<Bgra32, Float4> Source, WaveOpticsPipeline.Parameters Parameters)> Make)[]
|
||||
{
|
||||
("cached", _ => (original, parameters)),
|
||||
("gain", flip => (original, parameters with { Gain = flip ? 1.5f : 1f })),
|
||||
("source", flip => (flip ? mirrored : original, parameters)),
|
||||
("defocus", flip => (original, parameters with { Psf = parameters.Psf with { Defocus = flip ? 0.1f : 0f } })),
|
||||
("quality-high", flip => (original, parameters with { Psf = parameters.Psf with { Quality = flip ? WaveOpticsQuality.High : WaveOpticsQuality.Standard } })),
|
||||
};
|
||||
WaveOpticsPipeline.Parameters Radius(int radius) => parameters with { Psf = parameters.Psf with { KernelRadius = radius, Defocus = 2f, ComaHorizontal = 1f } };
|
||||
|
||||
var renderedGain = float.NaN;
|
||||
void Frame(ReadWriteTexture2D<Bgra32, Float4> source, in WaveOpticsPipeline.Parameters frameParameters)
|
||||
var subjects = new List<IDisposable>();
|
||||
GpuSubject Gpu()
|
||||
{
|
||||
var changed = pipeline.Simulate(source, image.Width, image.Height, 0, 0, image.Width, image.Height, in frameParameters);
|
||||
if ((changed || renderedGain != frameParameters.Gain) && pipeline.TryGetVisibleBounds(image.Width, image.Height, in frameParameters, out var rect))
|
||||
{
|
||||
pipeline.RenderVisible(output, rect, in frameParameters);
|
||||
renderedGain = frameParameters.Gain;
|
||||
}
|
||||
pipeline.WaitForCompletion();
|
||||
var subject = new GpuSubject(WaveOpticsPipeline.TryCreate(device) ?? throw new HarnessException("Direct3D 12を利用できません。"), output, image.Width, image.Height);
|
||||
subjects.Add(subject);
|
||||
return subject;
|
||||
}
|
||||
CpuSubject Cpu()
|
||||
{
|
||||
var subject = new CpuSubject(image.Width, image.Height);
|
||||
subjects.Add(subject);
|
||||
return subject;
|
||||
}
|
||||
|
||||
var samples = new List<double>[variants.Length];
|
||||
for (var index = 0; index < samples.Length; index++)
|
||||
samples[index] = new List<double>(Rounds);
|
||||
|
||||
foreach (var (_, make) in variants)
|
||||
try
|
||||
{
|
||||
var (warmupSource, warmupParameters) = make(true);
|
||||
Frame(warmupSource, in warmupParameters);
|
||||
}
|
||||
|
||||
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 cached = Gpu();
|
||||
var gain = Gpu();
|
||||
var source = Gpu();
|
||||
var defocus = Gpu();
|
||||
var qualityHigh = Gpu();
|
||||
var source31 = Gpu();
|
||||
var source63 = Gpu();
|
||||
var cpuSource = Cpu();
|
||||
var cpuGain = Cpu();
|
||||
var cpuSource63 = Cpu();
|
||||
var variants = new (string Name, Action<bool> Run)[]
|
||||
{
|
||||
var swap = random.Next(index + 1);
|
||||
(order[index], order[swap]) = (order[swap], order[index]);
|
||||
("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)),
|
||||
("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))),
|
||||
("source-r63", flip => source63.Frame(flip ? mirrored : original, Radius(63))),
|
||||
("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);
|
||||
}
|
||||
|
||||
foreach (var index in order)
|
||||
var stopwatch = new Stopwatch();
|
||||
var order = Enumerable.Range(0, variants.Length).ToArray();
|
||||
var random = new Random(Seed);
|
||||
for (var round = 0; round < Rounds; round++)
|
||||
{
|
||||
var (settledSource, settledParameters) = variants[index].Make(false);
|
||||
Frame(settledSource, in settledParameters);
|
||||
for (var index = order.Length - 1; index > 0; index--)
|
||||
{
|
||||
var swap = random.Next(index + 1);
|
||||
(order[index], order[swap]) = (order[swap], order[index]);
|
||||
}
|
||||
|
||||
var (measuredSource, measuredParameters) = variants[index].Make(true);
|
||||
stopwatch.Restart();
|
||||
Frame(measuredSource, in measuredParameters);
|
||||
stopwatch.Stop();
|
||||
samples[index].Add(stopwatch.Elapsed.TotalMilliseconds);
|
||||
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++)
|
||||
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 sorted = samples[index].OrderBy(static value => value).ToArray();
|
||||
var median = sorted[sorted.Length / 2];
|
||||
Console.WriteLine($" {variants[index].Name,-12} min={sorted[0],7:F2} median={median,7:F2} max={sorted[^1],7:F2}");
|
||||
foreach (var subject in subjects)
|
||||
subject.Dispose();
|
||||
}
|
||||
|
||||
return 0;
|
||||
}
|
||||
|
||||
static Bgra32[] ToPixels(HarnessImage image, bool mirror)
|
||||
@@ -357,11 +382,11 @@ static int Compare(string beforeDirectory, string afterDirectory)
|
||||
return failures == 0 ? 0 : 1;
|
||||
}
|
||||
|
||||
static void Benchmark(HarnessImage image)
|
||||
static void Benchmark(HarnessImage image, bool cpu)
|
||||
{
|
||||
const int Frames = 60;
|
||||
|
||||
using var renderer = new HarnessRenderer(image.Width, image.Height, image);
|
||||
using var renderer = new HarnessRenderer(image.Width, image.Height, image, cpu);
|
||||
Console.WriteLine($"adapter: {renderer.Adapter} (driver {renderer.Driver})");
|
||||
foreach (var (name, effect) in HarnessCases.Benchmarks())
|
||||
{
|
||||
@@ -435,3 +460,39 @@ static int CountOpaque(byte[] pixels)
|
||||
|
||||
return count;
|
||||
}
|
||||
|
||||
sealed class GpuSubject(WaveOpticsPipeline pipeline, ReadWriteTexture2D<Bgra32, Float4> output, int width, int height) : IDisposable
|
||||
{
|
||||
float renderedGain = float.NaN;
|
||||
|
||||
public void Frame(ReadWriteTexture2D<Bgra32, Float4> source, in WaveOpticsPipeline.Parameters parameters)
|
||||
{
|
||||
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);
|
||||
renderedGain = parameters.Gain;
|
||||
}
|
||||
pipeline.WaitForCompletion();
|
||||
}
|
||||
|
||||
public void Dispose() => pipeline.Dispose();
|
||||
}
|
||||
|
||||
sealed class CpuSubject(int width, int height) : IDisposable
|
||||
{
|
||||
readonly WaveOpticsCpuPipeline pipeline = new();
|
||||
float renderedGain = float.NaN;
|
||||
|
||||
public void Frame(byte[] source, in WaveOpticsPipeline.Parameters parameters)
|
||||
{
|
||||
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(rect, in parameters);
|
||||
renderedGain = parameters.Gain;
|
||||
}
|
||||
}
|
||||
|
||||
public void Dispose() => pipeline.Dispose();
|
||||
}
|
||||
@@ -0,0 +1,241 @@
|
||||
{
|
||||
"adapter": "CPU Intel64 Family 6 Model 186 Stepping 2, GenuineIntel",
|
||||
"driver": ".NET 10.0.12 / Microsoft Windows 10.0.26200",
|
||||
"input": "synthetic 640x480 89838D8976198E40",
|
||||
"canvas": "1280x720",
|
||||
"cases": [
|
||||
{
|
||||
"name": "default",
|
||||
"frames": [
|
||||
0
|
||||
],
|
||||
"hash": "335A7EDF4421E5EADAFBA9AC470195C17D37193D5CDD3FBE5E16635641CA2000"
|
||||
},
|
||||
{
|
||||
"name": "default-frames-0-8",
|
||||
"frames": [
|
||||
0,
|
||||
1,
|
||||
2,
|
||||
3,
|
||||
4,
|
||||
5,
|
||||
6,
|
||||
7,
|
||||
8
|
||||
],
|
||||
"hash": "4BCC9906BE721791FA1A589AD4FF87476899C5FFD19550A287B181AD93C143D3"
|
||||
},
|
||||
{
|
||||
"name": "amount-0",
|
||||
"frames": [
|
||||
0
|
||||
],
|
||||
"hash": "0A700F76CEDDBAD7C4B6A2C19D46939C1A93940E86C6EFEF1E5A53DB48D2A020"
|
||||
},
|
||||
{
|
||||
"name": "amount-50",
|
||||
"frames": [
|
||||
0
|
||||
],
|
||||
"hash": "59A831E6D8D2F8F04D5C14FCACB9D4DE7CBEEAD6521556F097751B5E51B65917"
|
||||
},
|
||||
{
|
||||
"name": "gain-50",
|
||||
"frames": [
|
||||
0
|
||||
],
|
||||
"hash": "B2A8D84D38C5E2068835AC9CBCC47B0673995F69074D88E04D47CC4C9BD1D02F"
|
||||
},
|
||||
{
|
||||
"name": "gain-400",
|
||||
"frames": [
|
||||
0
|
||||
],
|
||||
"hash": "5D4C21C28390B7B2DD3C8BD846C8B4F21FD0B79B0678BD0D7005C72256D55C6E"
|
||||
},
|
||||
{
|
||||
"name": "gain-400-amount-50",
|
||||
"frames": [
|
||||
0
|
||||
],
|
||||
"hash": "AC5CCEE4CF89E12027C75289923C1F13A3630D2ED0D4326527DD7AC591548A6E"
|
||||
},
|
||||
{
|
||||
"name": "wavelength-380",
|
||||
"frames": [
|
||||
0
|
||||
],
|
||||
"hash": "DB7E004C25B816C05B9FF55DC6EC9CFA0C0E294CC4D796BA4F3EB6BD04A0DDA5"
|
||||
},
|
||||
{
|
||||
"name": "wavelength-780",
|
||||
"frames": [
|
||||
0
|
||||
],
|
||||
"hash": "B7A203C5A553312AAFC25539186EDEEFF6A2D38EFE62D41E70A9CFD3CFBB4DC0"
|
||||
},
|
||||
{
|
||||
"name": "f-number-4",
|
||||
"frames": [
|
||||
0
|
||||
],
|
||||
"hash": "DBD880A49D55B5621CFCD51BF6F62642880F249985620C80D882C89D551452CB"
|
||||
},
|
||||
{
|
||||
"name": "f-number-64",
|
||||
"frames": [
|
||||
0
|
||||
],
|
||||
"hash": "8E92CD7906CEB43A7A357702DD32EF75BABA650D9ECFD6D7F159A23CCA848372"
|
||||
},
|
||||
{
|
||||
"name": "pixel-pitch-0.25",
|
||||
"frames": [
|
||||
0
|
||||
],
|
||||
"hash": "6DC31FF8C0A66826F5E660D0A163478F9F448EDDF97C57F51DE9625D6AAAC4DA"
|
||||
},
|
||||
{
|
||||
"name": "pixel-pitch-2",
|
||||
"frames": [
|
||||
0
|
||||
],
|
||||
"hash": "720332F6487B0EC51EF6885456FC59D121099251F407D90836CCCBF540A43860"
|
||||
},
|
||||
{
|
||||
"name": "kernel-radius-1",
|
||||
"frames": [
|
||||
0
|
||||
],
|
||||
"hash": "6A4098552BECB9B59315B90DDA88EE5A4AB9A18237748A5ED0903E23E0AEC764"
|
||||
},
|
||||
{
|
||||
"name": "kernel-radius-5",
|
||||
"frames": [
|
||||
0
|
||||
],
|
||||
"hash": "39FC1F7C8FDCCAC5BFCD667A8A66F648640E11FBD309E408711EA74F106136DA"
|
||||
},
|
||||
{
|
||||
"name": "kernel-radius-40-defocus-2",
|
||||
"frames": [
|
||||
0
|
||||
],
|
||||
"hash": "5F551E58F4E8B8C0B9E6ACE235F4B106E881A463CAD5B380C74E3E49C024CC42"
|
||||
},
|
||||
{
|
||||
"name": "kernel-radius-63-polygon-defocus-3",
|
||||
"frames": [
|
||||
0
|
||||
],
|
||||
"hash": "9A1FE43381BC00C4C5A9CEDE38D825E8D28B090CDDFDF339F4E70D2692C54812"
|
||||
},
|
||||
{
|
||||
"name": "quality-draft",
|
||||
"frames": [
|
||||
0
|
||||
],
|
||||
"hash": "B5CA29BD021EFFE66905975A1397FCADD8A8DCFE5A7DFCDFB298A2CA10A9BAD2"
|
||||
},
|
||||
{
|
||||
"name": "quality-high",
|
||||
"frames": [
|
||||
0
|
||||
],
|
||||
"hash": "62D830A59A4630F04E12794E0F20384BF7EEDE296D647497BBCF8E6572BE07BC"
|
||||
},
|
||||
{
|
||||
"name": "aperture-polygon",
|
||||
"frames": [
|
||||
0
|
||||
],
|
||||
"hash": "8E76BA550310DBCA0117644EDF8B94D8CA87237C8ABA63E35D8328EE155752C2"
|
||||
},
|
||||
{
|
||||
"name": "blade-count-3",
|
||||
"frames": [
|
||||
0
|
||||
],
|
||||
"hash": "C4FEB6AEF689CAA38DCD24080B212AC0F4BFB824161EAAAF9CEADD1092F6AD0A"
|
||||
},
|
||||
{
|
||||
"name": "blade-count-32",
|
||||
"frames": [
|
||||
0
|
||||
],
|
||||
"hash": "86F1B3B544707F5BB7B3196B75E7E843CC9B18FB44389F80285198C757BF1575"
|
||||
},
|
||||
{
|
||||
"name": "blade-rotation-30",
|
||||
"frames": [
|
||||
0
|
||||
],
|
||||
"hash": "9F3BD8948ED2EB59FE9CF15FB773D9F3615EDC54995AB5E9433A71674910725E"
|
||||
},
|
||||
{
|
||||
"name": "obstruction-50",
|
||||
"frames": [
|
||||
0
|
||||
],
|
||||
"hash": "5A492E7ED5AC9DC8D20E81E4BE404F4B59179E1F744A9824C782E13BF22ECB4D"
|
||||
},
|
||||
{
|
||||
"name": "defocus-1",
|
||||
"frames": [
|
||||
0
|
||||
],
|
||||
"hash": "46E15FCF306869F6274DE3F4FF087EE61100654F751A5BD96F059335F46D32BA"
|
||||
},
|
||||
{
|
||||
"name": "astigmatism-vertical-1",
|
||||
"frames": [
|
||||
0
|
||||
],
|
||||
"hash": "1BA6DD9DF17B6D0CD3C727753081B188975551DA28B22B61AD058452DA66F3FC"
|
||||
},
|
||||
{
|
||||
"name": "astigmatism-oblique-1",
|
||||
"frames": [
|
||||
0
|
||||
],
|
||||
"hash": "FEDFAAED039BA81909111756EEE6232BA3B37B1D5EDA253FF2D0129258474BFD"
|
||||
},
|
||||
{
|
||||
"name": "coma-horizontal-1",
|
||||
"frames": [
|
||||
0
|
||||
],
|
||||
"hash": "06184A49141FC314947F8FDA508AFA0EE82EB166D5A15E7F1A56FF081BA5B188"
|
||||
},
|
||||
{
|
||||
"name": "coma-vertical-1",
|
||||
"frames": [
|
||||
0
|
||||
],
|
||||
"hash": "5E2F38E6AC4A92AEFCFBADD93A238FF4492C1030E5ADF804006DEEFCC9951B8C"
|
||||
},
|
||||
{
|
||||
"name": "spherical-1",
|
||||
"frames": [
|
||||
0
|
||||
],
|
||||
"hash": "7429DB703FCBB1BED690F91E6B70185B8D566B09C706E67CF3ADD69A4C1F8C4F"
|
||||
},
|
||||
{
|
||||
"name": "defocus-animated-frames-0-8",
|
||||
"frames": [
|
||||
0,
|
||||
1,
|
||||
2,
|
||||
3,
|
||||
4,
|
||||
5,
|
||||
6,
|
||||
7,
|
||||
8
|
||||
],
|
||||
"hash": "EA104F2B819F36C8D21E9098D98EC52899812D88905EA708CC1FD5594F9E04FC"
|
||||
}
|
||||
]
|
||||
}
|
||||
@@ -9,7 +9,7 @@
|
||||
"frames": [
|
||||
0
|
||||
],
|
||||
"hash": "9B93219016A028453BF7CCAB7FBC7E3658B363FC51850286BE23B7A388C368BF"
|
||||
"hash": "B71481CC55FAC4F415BF590D7623D8973DA2EEFC9864D376D6D2BEC07D7A53EC"
|
||||
},
|
||||
{
|
||||
"name": "default-frames-0-8",
|
||||
@@ -24,7 +24,7 @@
|
||||
7,
|
||||
8
|
||||
],
|
||||
"hash": "A77359A34F3A6C78E616953C1D66DF1CD05595E662E3DE38E68EB2FC81D11AE4"
|
||||
"hash": "7A46C7D2CDA1F9ABB24C7887993ECC5EA84EBF935B1C9C728FC1A123ECBDB382"
|
||||
},
|
||||
{
|
||||
"name": "amount-0",
|
||||
@@ -38,189 +38,189 @@
|
||||
"frames": [
|
||||
0
|
||||
],
|
||||
"hash": "E854AFBFE739475EE665D3D4C672BEF9A631A1479E094E339B87D18C38BA50B0"
|
||||
"hash": "E61EAF07F3AD9B803C0CC66D2081ABFBB9CF8E636139831AF9C07FBE720AE829"
|
||||
},
|
||||
{
|
||||
"name": "gain-50",
|
||||
"frames": [
|
||||
0
|
||||
],
|
||||
"hash": "9032893550EE7D03B58762F9BD8BE6608929D45DA0BFD474E5AF410A1C4C3328"
|
||||
"hash": "04F6DF30B38FF4F091D1160CD8E58DC9C162DC70B9A7C1A1AED5CBA5CD8B95C9"
|
||||
},
|
||||
{
|
||||
"name": "gain-400",
|
||||
"frames": [
|
||||
0
|
||||
],
|
||||
"hash": "95886976629306C5E0A2BB93208B5E627E3C78A9CFCD6263202248E0E363A2A7"
|
||||
"hash": "92533C9D79403C5E18C6BEA3F900247FC7C30255810851413A319DFBA435FAC6"
|
||||
},
|
||||
{
|
||||
"name": "gain-400-amount-50",
|
||||
"frames": [
|
||||
0
|
||||
],
|
||||
"hash": "C579D45C3F216492D6219DA8C5CDF1C9B2357B51AA1376C53A6CBE051C3F6F1A"
|
||||
"hash": "8D92DC9C871DC8ADE21A72C4E50E0330A7B3F01655FC50FA008B70DA17458AAE"
|
||||
},
|
||||
{
|
||||
"name": "wavelength-380",
|
||||
"frames": [
|
||||
0
|
||||
],
|
||||
"hash": "A5B889290FAB95A7BB5B00922B36B504AFA660DDF0F7E3EF3F4829D4E4AA8C75"
|
||||
"hash": "4E475FC56B2F720262560ECC6CE7FF947B440345ED07EEDA5AC7FFFC1B9E2A3C"
|
||||
},
|
||||
{
|
||||
"name": "wavelength-780",
|
||||
"frames": [
|
||||
0
|
||||
],
|
||||
"hash": "7F8CB99C84EEED6C7ADF4E138085B08A53C3454160EF08A135405F1018B4272D"
|
||||
"hash": "61674C04EDE9E19E97609C5EEB4FEAD8E2AF41DDF2808BFEBD3278119457986F"
|
||||
},
|
||||
{
|
||||
"name": "f-number-4",
|
||||
"frames": [
|
||||
0
|
||||
],
|
||||
"hash": "9526105CC4F77E47D4174A86A7FB6E50A270CDBDCB5C59C14615A2751AB10AD7"
|
||||
"hash": "59F2E23935AB662D7D6D40C392B2FEAD59FFEC6B6C7466DA01F2A3970099AC2C"
|
||||
},
|
||||
{
|
||||
"name": "f-number-64",
|
||||
"frames": [
|
||||
0
|
||||
],
|
||||
"hash": "28CD10EE5F789E7D99BBD48E2A2967636E33BF4A4A57253E8F62A0FCD4668733"
|
||||
"hash": "A0B2BDF726B96A4F71583D67F3FFF03BE5F053EAA757A169D02762045FE3054B"
|
||||
},
|
||||
{
|
||||
"name": "pixel-pitch-0.25",
|
||||
"frames": [
|
||||
0
|
||||
],
|
||||
"hash": "0A35D27FBC8670D8C1F9E75581CE5AA7FC23466D5E64141D5E78AFF3631CB0BF"
|
||||
"hash": "E561DDA367AF61F78A35949F686F7AA4DC11FC0C2B9F50FDC501E997EA023555"
|
||||
},
|
||||
{
|
||||
"name": "pixel-pitch-2",
|
||||
"frames": [
|
||||
0
|
||||
],
|
||||
"hash": "39B4E14378BAABB03A364D7824BC0C999E1C7D9FD292090A2A8995D6C0890D8E"
|
||||
"hash": "427043F6DA302D72D5C015CB6FDB691710E55824B66B60971386A6A6DA5A2B52"
|
||||
},
|
||||
{
|
||||
"name": "kernel-radius-1",
|
||||
"frames": [
|
||||
0
|
||||
],
|
||||
"hash": "7873F5E5B2AC64FC73E65746900E0C249E6335A533DFD17E0FE97A4EFE9C36A2"
|
||||
"hash": "D898D9F66BD5566A55D8570BE5F2CD1210F30BED8ECC23B6152805B35280E58E"
|
||||
},
|
||||
{
|
||||
"name": "kernel-radius-5",
|
||||
"frames": [
|
||||
0
|
||||
],
|
||||
"hash": "34B3BCEC95C18658E45A8832AEB2BE00F0716E2FD78CE45CBA36F644DA5945B9"
|
||||
"hash": "5AC78F10ABFEB6703327409AF5021676BFADBC8B8271FCBFC9A825C4D54DE3D8"
|
||||
},
|
||||
{
|
||||
"name": "kernel-radius-40-defocus-2",
|
||||
"frames": [
|
||||
0
|
||||
],
|
||||
"hash": "6908E7DFE146500A209D47AD18FF5932FF9B80F8FCD976036179F4CA8503C89C"
|
||||
"hash": "1B90715CC1735FD7B87D16800698B5FE6AAB65E47B38FDE5A1A71733A85662E6"
|
||||
},
|
||||
{
|
||||
"name": "kernel-radius-63-polygon-defocus-3",
|
||||
"frames": [
|
||||
0
|
||||
],
|
||||
"hash": "55D4485AD5176D4AB6C7BE4BBBDD97343002B675AB0742D8F8224FD57A9296A5"
|
||||
"hash": "544F004B4E6DE4EF2BBB554F7CC8B6A98A3128413642BE0953331BBD1E290285"
|
||||
},
|
||||
{
|
||||
"name": "quality-draft",
|
||||
"frames": [
|
||||
0
|
||||
],
|
||||
"hash": "0E16A02AE2360DBAB4FD57C28A95E51C61C2C33B81D46076D6D6E4FF81636A22"
|
||||
"hash": "BFDF5C15934DCE96B2FBC3F32671D3619E3A4863D0F6B6C886003EE137E208EA"
|
||||
},
|
||||
{
|
||||
"name": "quality-high",
|
||||
"frames": [
|
||||
0
|
||||
],
|
||||
"hash": "B28685A19BA25205B8F2716831687D3D63958AE24C65311E39D5F585D1750D82"
|
||||
"hash": "EE9CA6EA1570279FB7FE22615DF9832D3B891F59A2C88A0B46895E23286889E6"
|
||||
},
|
||||
{
|
||||
"name": "aperture-polygon",
|
||||
"frames": [
|
||||
0
|
||||
],
|
||||
"hash": "876C1DD8767A405F4C24ED6EE289513CFE155FA811E6D6F15A8C0E8F21624948"
|
||||
"hash": "63714DFA7EF012D7AB6B818E538427DD55BAA4392BD0B3171C325D52BEA727D3"
|
||||
},
|
||||
{
|
||||
"name": "blade-count-3",
|
||||
"frames": [
|
||||
0
|
||||
],
|
||||
"hash": "3EC07AD240914F5CD7C0AAA8F0BEF5C76772922E932853B39AD38FC290C493E8"
|
||||
"hash": "F9B3EA9580C95536258728CF01E885A4308B4A61B3F68861B8BEA4B45CC093B5"
|
||||
},
|
||||
{
|
||||
"name": "blade-count-32",
|
||||
"frames": [
|
||||
0
|
||||
],
|
||||
"hash": "7D5D5A10503525D51000E4CE2BF538E88878E77893D885B9B195C7FFCBDBCB50"
|
||||
"hash": "62218C4D673DD03C558F0F3A0AB6699A1AF4A33A0E814DFF52F452B61C720A50"
|
||||
},
|
||||
{
|
||||
"name": "blade-rotation-30",
|
||||
"frames": [
|
||||
0
|
||||
],
|
||||
"hash": "7DF481B8A4E5263100A7C30EF3070BC55D497A9F39CF09FEA1E56E4058D19658"
|
||||
"hash": "0842E055F3DD3518FFE25A2F3ABB1A205310AAB60C2CD9804C221FE024CA4D38"
|
||||
},
|
||||
{
|
||||
"name": "obstruction-50",
|
||||
"frames": [
|
||||
0
|
||||
],
|
||||
"hash": "D1F583FF2F287987F3D97D48B5C3D0B80A647EECCF0F08C15387C745AFA41069"
|
||||
"hash": "9F86A17BC9EA4E362F6C785B8672B93C21DEB5748064456058C34E8B1B52E800"
|
||||
},
|
||||
{
|
||||
"name": "defocus-1",
|
||||
"frames": [
|
||||
0
|
||||
],
|
||||
"hash": "7B699943FCC55D026212D9D842F2BFE436F992AD1010B23B41A54A9C643120EC"
|
||||
"hash": "BF6533B30E4130242CAB252FB7370F6097D10CC85DEA926E8A44273B2706CB12"
|
||||
},
|
||||
{
|
||||
"name": "astigmatism-vertical-1",
|
||||
"frames": [
|
||||
0
|
||||
],
|
||||
"hash": "AB5FACB67EC980806B6FFEE0627161CBE3EEE0F288194C1819072F6C108E372B"
|
||||
"hash": "0AEC6A3A9070BF1F0AD08118DAFCEA6E6C8D55B35555EA8DF918B8D2E127A2EC"
|
||||
},
|
||||
{
|
||||
"name": "astigmatism-oblique-1",
|
||||
"frames": [
|
||||
0
|
||||
],
|
||||
"hash": "FE7398B928F43E7C3E9722D12F0B2550EA275DF9EB26E02E990DFCF21ECC98AE"
|
||||
"hash": "15E642C87F192398DA4E38275DD9467D162C31B67E7D02FDA22B820752213AC9"
|
||||
},
|
||||
{
|
||||
"name": "coma-horizontal-1",
|
||||
"frames": [
|
||||
0
|
||||
],
|
||||
"hash": "EB2235CF182171F8D07EE8651D111D8A7483DFFAF934F51CC855E2A595FCAB5D"
|
||||
"hash": "931357CB85EF96F0BED2AFB7F49BADC130C354EACCF3B3815441CD64F472041C"
|
||||
},
|
||||
{
|
||||
"name": "coma-vertical-1",
|
||||
"frames": [
|
||||
0
|
||||
],
|
||||
"hash": "AA3FFDF4A62272DC0BD0E7A0EF8A4E4ECE03B27C90C665F71A991C2B65F72CC6"
|
||||
"hash": "2A85D748133BBD1C015892C2C1183D9D069A6FA353CB3D14DEEAED7CAE4C378F"
|
||||
},
|
||||
{
|
||||
"name": "spherical-1",
|
||||
"frames": [
|
||||
0
|
||||
],
|
||||
"hash": "91CF9F66CC46831C357D898E0367814285FE4D62959AB717B54146F8E8CE0D6F"
|
||||
"hash": "5CE0E3BEE95CAF4E585036FC6048CA63F0B3D42C3F1FC23A83D045A41C700FD8"
|
||||
},
|
||||
{
|
||||
"name": "defocus-animated-frames-0-8",
|
||||
@@ -235,7 +235,7 @@
|
||||
7,
|
||||
8
|
||||
],
|
||||
"hash": "B0D6919D7AD63BBFC378CD8578033D0F6322EF479EA564385A4E6F50C4905F14"
|
||||
"hash": "B16C68AB33DE6B661BFF623AE9D3AE7264EF75CF3427AFF0FCA5E16E96BC998A"
|
||||
}
|
||||
]
|
||||
}
|
||||
@@ -1,158 +0,0 @@
|
||||
using WaveOptics.Optics;
|
||||
|
||||
namespace WaveOptics.Tests.Optics;
|
||||
|
||||
public sealed class SeparableKernelTests
|
||||
{
|
||||
[Fact]
|
||||
public void FullRankReconstructionMatchesOriginal()
|
||||
{
|
||||
const int size = 15;
|
||||
var random = new Random(2024);
|
||||
var kernel = new double[size * size];
|
||||
for (var index = 0; index < kernel.Length; index++)
|
||||
kernel[index] = random.NextDouble();
|
||||
|
||||
var separable = SeparableKernel.Decompose(kernel, size, 0d, size);
|
||||
var maximumError = ReconstructionError(separable, kernel);
|
||||
|
||||
Assert.Equal(size, separable.Rank);
|
||||
Assert.True(maximumError < 1e-5, $"{maximumError:R}");
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void OuterProductKernelIsRankOne()
|
||||
{
|
||||
const int size = 11;
|
||||
var vertical = new double[size];
|
||||
var horizontal = new double[size];
|
||||
for (var i = 0; i < size; i++)
|
||||
{
|
||||
vertical[i] = Math.Exp(-0.2 * (i - 5) * (i - 5));
|
||||
horizontal[i] = Math.Exp(-0.35 * (i - 5) * (i - 5));
|
||||
}
|
||||
var kernel = new double[size * size];
|
||||
for (var y = 0; y < size; y++)
|
||||
{
|
||||
for (var x = 0; x < size; x++)
|
||||
kernel[y * size + x] = vertical[y] * horizontal[x];
|
||||
}
|
||||
|
||||
var separable = SeparableKernel.Decompose(kernel, size, 1e-6, size);
|
||||
var maximumError = ReconstructionError(separable, kernel);
|
||||
|
||||
Assert.Equal(1, separable.Rank);
|
||||
Assert.True(maximumError < 1e-5, $"{maximumError:R}");
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void LowRankApproximationHonorsResidualBudget()
|
||||
{
|
||||
const int size = 21;
|
||||
var center = size / 2;
|
||||
var kernel = new double[size * size];
|
||||
var sum = 0d;
|
||||
for (var y = 0; y < size; y++)
|
||||
{
|
||||
for (var x = 0; x < size; x++)
|
||||
{
|
||||
var radiusSquared = (x - center) * (x - center) + (y - center) * (y - center);
|
||||
var value = Math.Exp(-0.12 * radiusSquared);
|
||||
kernel[y * size + x] = value;
|
||||
sum += value;
|
||||
}
|
||||
}
|
||||
for (var index = 0; index < kernel.Length; index++)
|
||||
kernel[index] /= sum;
|
||||
|
||||
var separable = SeparableKernel.Decompose(kernel, size, 1e-4, size);
|
||||
var energy = 0d;
|
||||
var residual = 0d;
|
||||
for (var y = 0; y < size; y++)
|
||||
{
|
||||
for (var x = 0; x < size; x++)
|
||||
{
|
||||
var original = kernel[y * size + x];
|
||||
var approximation = Reconstruct(separable, x, y);
|
||||
energy += original * original;
|
||||
residual += (original - approximation) * (original - approximation);
|
||||
}
|
||||
}
|
||||
|
||||
Assert.True(separable.Rank < size);
|
||||
Assert.True(residual <= 1e-4 * energy, $"{residual / energy:R}");
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void SumIsTheSumOfTheApproximation()
|
||||
{
|
||||
const int size = 21;
|
||||
var center = size / 2;
|
||||
var kernel = new double[size * size];
|
||||
for (var y = 0; y < size; y++)
|
||||
{
|
||||
for (var x = 0; x < size; x++)
|
||||
kernel[y * size + x] = Math.Exp(-0.3 * Math.Sqrt((x - center) * (x - center) + (y - center) * (y - center)));
|
||||
}
|
||||
|
||||
var separable = SeparableKernel.Decompose(kernel, size, 1e-4, 2);
|
||||
var sum = 0d;
|
||||
for (var y = 0; y < size; y++)
|
||||
{
|
||||
for (var x = 0; x < size; x++)
|
||||
sum += Reconstruct(separable, x, y);
|
||||
}
|
||||
|
||||
Assert.Equal(sum, separable.Sum, 5);
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[InlineData(21, 9)]
|
||||
[InlineData(9, 21)]
|
||||
[InlineData(13, 13)]
|
||||
public void AReusedDecompositionMatchesAFreshOne(int previousSize, int size)
|
||||
{
|
||||
var random = new Random(previousSize * 100 + size);
|
||||
var previous = new double[previousSize * previousSize];
|
||||
for (var index = 0; index < previous.Length; index++)
|
||||
previous[index] = random.NextDouble();
|
||||
var kernel = new double[size * size];
|
||||
for (var index = 0; index < kernel.Length; index++)
|
||||
kernel[index] = random.NextDouble() * random.NextDouble();
|
||||
var reused = new SeparableKernel();
|
||||
reused.Update(previous, previousSize, 1e-4, previousSize);
|
||||
|
||||
reused.Update(kernel, size, 1e-4, size);
|
||||
var fresh = SeparableKernel.Decompose(kernel, size, 1e-4, size);
|
||||
|
||||
Assert.Equal((fresh.Size, fresh.Rank), (reused.Size, reused.Rank));
|
||||
Assert.Equal(BitConverter.DoubleToInt64Bits(fresh.Sum), BitConverter.DoubleToInt64Bits(reused.Sum));
|
||||
Assert.Equal(BitConverter.DoubleToInt64Bits(fresh.ResidualEnergyRatio), BitConverter.DoubleToInt64Bits(reused.ResidualEnergyRatio));
|
||||
Assert.Equal(fresh.Horizontal.ToArray(), reused.Horizontal.ToArray());
|
||||
Assert.Equal(fresh.Vertical.ToArray(), reused.Vertical.ToArray());
|
||||
}
|
||||
|
||||
static double Reconstruct(SeparableKernel separable, int x, int y)
|
||||
{
|
||||
var size = separable.Size;
|
||||
var value = 0d;
|
||||
for (var term = 0; term < separable.Rank; term++)
|
||||
value += separable.Vertical[term * size + y] * separable.Horizontal[term * size + x];
|
||||
return value;
|
||||
}
|
||||
|
||||
static double ReconstructionError(SeparableKernel separable, double[] kernel)
|
||||
{
|
||||
var size = separable.Size;
|
||||
var maximumError = 0d;
|
||||
for (var y = 0; y < size; y++)
|
||||
{
|
||||
for (var x = 0; x < size; x++)
|
||||
{
|
||||
var error = Math.Abs(kernel[y * size + x] - Reconstruct(separable, x, y));
|
||||
maximumError = Math.Max(maximumError, error);
|
||||
}
|
||||
}
|
||||
return maximumError;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,180 @@
|
||||
using System.Runtime.InteropServices;
|
||||
using WaveOptics.Effects;
|
||||
using WaveOptics.Rendering;
|
||||
|
||||
namespace WaveOptics.Tests;
|
||||
|
||||
[Collection("Direct3D12")]
|
||||
public sealed class WaveOpticsCpuPipelineTests
|
||||
{
|
||||
const int Opaque = unchecked((int)0xFFC0C0C0);
|
||||
|
||||
static WaveOpticsPipeline.Parameters Parameters(float gain = 1f, float defocus = 0f)
|
||||
=> new(gain, new WaveOpticsPipeline.PsfParameters(
|
||||
WaveOpticsQuality.Standard, 15, 550f, 8f, 4f, WaveOpticsApertureShape.Circular, 6, 0f, 0f, defocus, 0f, 0f, 0f, 0f, 0f));
|
||||
|
||||
static int[] Square(int width, int height, int left, int top, int size)
|
||||
{
|
||||
var pixels = new int[width * height];
|
||||
for (var y = top; y < top + size; y++)
|
||||
{
|
||||
for (var x = left; x < left + size; x++)
|
||||
pixels[y * width + x] = Opaque;
|
||||
}
|
||||
|
||||
return pixels;
|
||||
}
|
||||
|
||||
static byte[] Bytes(int[] pixels) => MemoryMarshal.AsBytes(pixels.AsSpan()).ToArray();
|
||||
|
||||
static byte[] RenderFrame(WaveOpticsCpuPipeline pipeline, byte[] source, int width, int height, int margin, in WaveOpticsPipeline.Parameters parameters, out WaveOpticsPipeline.PixelRect rect)
|
||||
{
|
||||
pipeline.Simulate(source, width + margin * 2, height + margin * 2, margin, margin, width, height, in parameters);
|
||||
Assert.True(pipeline.TryGetVisibleBounds(width + margin * 2, height + margin * 2, in parameters, out rect));
|
||||
return pipeline.RenderVisible(rect, in parameters).ToArray();
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void TheCpuAndTheGpuDrawTheSameImageWithinTwoLevels()
|
||||
{
|
||||
using var cpu = new WaveOpticsCpuPipeline(3);
|
||||
using var gpu = WaveOpticsPipeline.TryCreate();
|
||||
Assert.NotNull(gpu);
|
||||
var source = Square(128, 128, 40, 44, 40);
|
||||
var parameters = Parameters(defocus: 0.7f);
|
||||
var expected = new int[source.Length];
|
||||
var actual = new int[source.Length];
|
||||
|
||||
gpu.Process(source, expected, 128, 128, in parameters);
|
||||
cpu.Process(source, actual, 128, 128, in parameters);
|
||||
|
||||
var expectedBytes = MemoryMarshal.AsBytes(expected.AsSpan());
|
||||
var actualBytes = MemoryMarshal.AsBytes(actual.AsSpan());
|
||||
for (var index = 0; index < expectedBytes.Length; index++)
|
||||
Assert.InRange(actualBytes[index] - expectedBytes[index], -2, 2);
|
||||
Assert.Contains(actualBytes.ToArray(), value => value > 0);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void TheImageDoesNotDependOnTheNumberOfThreads()
|
||||
{
|
||||
using var single = new WaveOpticsCpuPipeline(1);
|
||||
using var several = new WaveOpticsCpuPipeline(5);
|
||||
var source = Bytes(Square(150, 120, 30, 20, 70));
|
||||
var parameters = Parameters(gain: 1.5f, defocus: 1f);
|
||||
|
||||
var first = RenderFrame(single, source, 150, 120, 16, in parameters, out _);
|
||||
var second = RenderFrame(several, source, 150, 120, 16, in parameters, out _);
|
||||
|
||||
Assert.Equal(first, second);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void TheConvolutionIsRecomputedOnlyWhenTheSourceOrTheOpticsChange()
|
||||
{
|
||||
using var pipeline = new WaveOpticsCpuPipeline(2);
|
||||
var source = Bytes(Square(96, 96, 32, 32, 32));
|
||||
var parameters = Parameters();
|
||||
|
||||
Assert.True(pipeline.Simulate(source, 128, 128, 16, 16, 96, 96, in parameters));
|
||||
Assert.False(pipeline.Simulate(source, 128, 128, 16, 16, 96, 96, in parameters));
|
||||
var gainChanged = parameters with { Gain = 2f };
|
||||
Assert.False(pipeline.Simulate(source, 128, 128, 16, 16, 96, 96, in gainChanged));
|
||||
var bladesChanged = parameters with { Psf = parameters.Psf with { BladeCount = 9 } };
|
||||
Assert.False(pipeline.Simulate(source, 128, 128, 16, 16, 96, 96, in bladesChanged));
|
||||
var opticsChanged = parameters with { Psf = parameters.Psf with { Defocus = 0.5f } };
|
||||
Assert.True(pipeline.Simulate(source, 128, 128, 16, 16, 96, 96, in opticsChanged));
|
||||
var moved = Bytes(Square(96, 96, 31, 32, 32));
|
||||
Assert.True(pipeline.Simulate(moved, 128, 128, 16, 16, 96, 96, in opticsChanged));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void ChangingOnlyTheGainDrawsTheSameImageAsAFreshConvolution()
|
||||
{
|
||||
using var pipeline = new WaveOpticsCpuPipeline(2);
|
||||
var source = Bytes(Square(96, 96, 30, 28, 36));
|
||||
var first = Parameters(defocus: 0.5f);
|
||||
RenderFrame(pipeline, source, 96, 96, 16, in first, out var rect);
|
||||
|
||||
foreach (var gain in new[] { 2.5f, 0.75f, 1f })
|
||||
{
|
||||
var changed = first with { Gain = gain };
|
||||
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);
|
||||
var expected = RenderFrame(fresh, source, 96, 96, 16, in changed, out _);
|
||||
|
||||
Assert.True(pipeline.HasStore);
|
||||
Assert.Equal(expected, reused);
|
||||
}
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void ANewSourceLetsTheStoreGo()
|
||||
{
|
||||
using var pipeline = new WaveOpticsCpuPipeline(2);
|
||||
var source = Bytes(Square(96, 96, 30, 28, 36));
|
||||
var parameters = Parameters();
|
||||
RenderFrame(pipeline, source, 96, 96, 16, in parameters, out var rect);
|
||||
var brighter = parameters with { Gain = 2f };
|
||||
pipeline.Simulate(source, 128, 128, 16, 16, 96, 96, in brighter);
|
||||
pipeline.RenderVisible(rect, in brighter);
|
||||
Assert.True(pipeline.HasStore);
|
||||
|
||||
RenderFrame(pipeline, Bytes(Square(96, 96, 20, 28, 36)), 96, 96, 16, in brighter, out _);
|
||||
|
||||
Assert.False(pipeline.HasStore);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void NothingIsVisibleForATransparentSource()
|
||||
{
|
||||
using var pipeline = new WaveOpticsCpuPipeline(1);
|
||||
var parameters = Parameters();
|
||||
|
||||
Assert.False(pipeline.Simulate(new byte[64 * 64 * 4], 96, 96, 16, 16, 64, 64, in parameters));
|
||||
Assert.False(pipeline.TryGetVisibleBounds(96, 96, in parameters, out _));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void AClosedApertureLeavesNoKernel()
|
||||
{
|
||||
using var pipeline = new WaveOpticsCpuPipeline(1);
|
||||
var source = Bytes(Square(64, 64, 20, 20, 20));
|
||||
var open = Parameters();
|
||||
var closed = open with { Psf = open.Psf with { Quality = WaveOpticsQuality.Draft, ApertureShape = WaveOpticsApertureShape.RegularPolygon, BladeCount = 4, BladeRotation = -357.5f, Obstruction = 0.95f } };
|
||||
|
||||
Assert.False(pipeline.Simulate(source, 96, 96, 16, 16, 64, 64, in closed));
|
||||
Assert.False(pipeline.HasKernel);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void AWarmFrameAllocatesNothingOnTheCallingThread()
|
||||
{
|
||||
using var pipeline = new WaveOpticsCpuPipeline(3);
|
||||
var sources = new[] { Bytes(Square(96, 96, 30, 28, 36)), Bytes(Square(96, 96, 31, 28, 36)) };
|
||||
var parameters = Parameters();
|
||||
for (var warmUp = 0; warmUp < 4; warmUp++)
|
||||
RenderFrame(pipeline, sources[warmUp % 2], 96, 96, 16, in parameters, out _);
|
||||
|
||||
var before = GC.GetAllocatedBytesForCurrentThread();
|
||||
for (var frame = 0; frame < 8; frame++)
|
||||
{
|
||||
pipeline.Simulate(sources[frame % 2], 128, 128, 16, 16, 96, 96, in parameters);
|
||||
pipeline.TryGetVisibleBounds(128, 128, in parameters, out var rect);
|
||||
pipeline.RenderVisible(rect, in parameters);
|
||||
}
|
||||
var allocated = GC.GetAllocatedBytesForCurrentThread() - before;
|
||||
|
||||
Assert.Equal(0L, allocated);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void RenderingBeforeAConvolutionIsRejected()
|
||||
{
|
||||
using var pipeline = new WaveOpticsCpuPipeline(1);
|
||||
var parameters = Parameters();
|
||||
|
||||
Assert.Throws<InvalidOperationException>(() => pipeline.RenderVisible(new WaveOpticsPipeline.PixelRect(0, 0, 4, 4), in parameters));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,244 @@
|
||||
using ComputeGuard;
|
||||
using ComputeWeave;
|
||||
using WaveOptics.Effects;
|
||||
using WaveOptics.Rendering;
|
||||
using YukkuriMovieMaker.Commons;
|
||||
using YukkuriMovieMaker.Player.Video;
|
||||
|
||||
namespace WaveOptics.Tests;
|
||||
|
||||
[Collection("Direct2D")]
|
||||
public sealed class WaveOpticsEffectProcessorRouteTests
|
||||
{
|
||||
const int Size = 72;
|
||||
const int Length = 30;
|
||||
|
||||
static readonly Bgra Warm = Bgra.Opaque(220, 160, 90);
|
||||
|
||||
static Bgra Shape(int x, int y)
|
||||
=> x is >= 20 and < 52 && y is >= 18 and < 50 && (x + 2 * y) % 9 != 0 ? Warm : Bgra.Transparent;
|
||||
|
||||
sealed class Reports
|
||||
{
|
||||
public List<ComputeAnomalyException> Received { get; } = [];
|
||||
|
||||
public ComputeGuardian CreateGuardian() => new(new ComputeGuardianOptions { Report = Received.Add });
|
||||
}
|
||||
|
||||
static void RequireInterop(IGraphicsDevicesAndContext devices)
|
||||
{
|
||||
using var scheduler = ComputeExternalQueueScheduler.Create();
|
||||
using var provider = WaveOpticsInteropProvider.TryCreate(devices, scheduler, out var device);
|
||||
if (provider is null || device is null)
|
||||
Assert.Skip("Direct3D 11 and Direct3D 12 sharing is unavailable.");
|
||||
}
|
||||
|
||||
static void RequireHardware(WaveOpticsEffectProcessor processor)
|
||||
{
|
||||
if (processor.Device is not { IsSoftware: false })
|
||||
Assert.Skip("The GPU route needs a hardware adapter.");
|
||||
}
|
||||
|
||||
static WaveOpticsEffect Effect()
|
||||
{
|
||||
var effect = new WaveOpticsEffect { KernelRadius = 9 };
|
||||
effect.Defocus.Values[0].Value = 0.6d;
|
||||
effect.ComaHorizontal.Values[0].Value = 0.8d;
|
||||
return effect;
|
||||
}
|
||||
|
||||
static WaveOpticsEffectProcessor Processor(IGraphicsDevicesAndContext devices, WaveOpticsEffect effect, ComputeGuardian guardian, bool allowGpu, Func<ComputeDevice, IReadOnlyList<ComputeCheck>>? selfTest = null)
|
||||
=> new(devices, effect, guardian, selfTest, allowGpu);
|
||||
|
||||
static Rendering RenderFrame(IGraphicsDevicesAndContext devices, IVideoEffectProcessor processor, int frame)
|
||||
{
|
||||
processor.Update(EffectDescriptions.At(frame, Length));
|
||||
return Rendering.Capture(devices, processor.Output);
|
||||
}
|
||||
|
||||
static Rendering CpuReference(IGraphicsDevicesAndContext devices, SourceImage source, WaveOpticsEffect effect, int frame)
|
||||
{
|
||||
using var processor = Processor(devices, effect, new Reports().CreateGuardian(), false);
|
||||
processor.SetInput(source.Bitmap);
|
||||
return RenderFrame(devices, processor, frame);
|
||||
}
|
||||
|
||||
static ComputeCheck FailingCheck => ComputeCheck.Count("broken", 1);
|
||||
|
||||
[Fact]
|
||||
public void WithoutTheGpuTheBlurIsDrawnOnTheCpuCloseToTheGpu()
|
||||
{
|
||||
using var devices = new GraphicsDevices();
|
||||
using var context = devices.CreateContext();
|
||||
RequireInterop(context);
|
||||
using var source = new SourceImage(context, Size, Size, Shape);
|
||||
var reports = new Reports();
|
||||
var effect = Effect();
|
||||
using var gpu = Processor(context, effect, reports.CreateGuardian(), true);
|
||||
using var cpu = Processor(context, effect, reports.CreateGuardian(), false);
|
||||
gpu.SetInput(source.Bitmap);
|
||||
cpu.SetInput(source.Bitmap);
|
||||
var gpuDevice = gpu.Device;
|
||||
|
||||
var expected = RenderFrame(context, gpu, 0);
|
||||
var actual = RenderFrame(context, cpu, 0);
|
||||
|
||||
Assert.Null(cpu.Device);
|
||||
Assert.NotNull(gpuDevice);
|
||||
Assert.Equal(gpuDevice.Value.IsSoftware, gpu.Pipeline is null);
|
||||
Assert.Equal((expected.Left, expected.Top, expected.Width, expected.Height), (actual.Left, actual.Top, actual.Width, actual.Height));
|
||||
Assert.All(expected.Coordinates(), point =>
|
||||
{
|
||||
var a = expected[point.X, point.Y];
|
||||
var b = actual[point.X, point.Y];
|
||||
Assert.InRange(a.Blue - b.Blue, -2, 2);
|
||||
Assert.InRange(a.Green - b.Green, -2, 2);
|
||||
Assert.InRange(a.Red - b.Red, -2, 2);
|
||||
Assert.InRange(a.Alpha - b.Alpha, -2, 2);
|
||||
});
|
||||
Assert.Contains(actual.Coordinates(), point => Shape(point.X, point.Y).Alpha == 0 && actual[point.X, point.Y].Alpha > 0);
|
||||
Assert.Empty(reports.Received);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void AHealthyAdapterIsTrustedWithoutAReport()
|
||||
{
|
||||
using var devices = new GraphicsDevices();
|
||||
using var context = devices.CreateContext();
|
||||
RequireInterop(context);
|
||||
using var source = new SourceImage(context, Size, Size, Shape);
|
||||
var reports = new Reports();
|
||||
var guardian = reports.CreateGuardian();
|
||||
using var processor = Processor(context, Effect(), guardian, true);
|
||||
RequireHardware(processor);
|
||||
processor.SetInput(source.Bitmap);
|
||||
|
||||
RenderFrame(context, processor, 0);
|
||||
|
||||
Assert.Equal(ComputeHealth.Trusted, guardian.HealthOf(processor.Device!.Value.Luid));
|
||||
Assert.Empty(reports.Received);
|
||||
}
|
||||
|
||||
public static readonly TheoryData<string, Func<Float2[], Float2[]>> Faults = new()
|
||||
{
|
||||
{ "nan", spectrum => { var broken = (Float2[])spectrum.Clone(); broken[5] = new Float2(float.NaN, 0f); return broken; } },
|
||||
{ "scale", spectrum => [.. spectrum.Select(value => new Float2(value.X * 1.002f, value.Y * 1.002f))] },
|
||||
{ "mirror", spectrum => [.. spectrum.Select(value => new Float2(value.X, -value.Y))] },
|
||||
};
|
||||
|
||||
[Theory]
|
||||
[MemberData(nameof(Faults))]
|
||||
public void AFrameThatFailsItsChecksShowsTheCpuResultPinsTheAdapterAndReportsOnce(string fault, Func<Float2[], Float2[]> tamper)
|
||||
{
|
||||
using var devices = new GraphicsDevices();
|
||||
using var context = devices.CreateContext();
|
||||
RequireInterop(context);
|
||||
using var source = new SourceImage(context, Size, Size, Shape);
|
||||
var reports = new Reports();
|
||||
var guardian = reports.CreateGuardian();
|
||||
var effect = Effect();
|
||||
using var processor = Processor(context, effect, guardian, true);
|
||||
RequireHardware(processor);
|
||||
var luid = processor.Device!.Value.Luid;
|
||||
processor.SetInput(source.Bitmap);
|
||||
processor.Pipeline!.SpectrumTamper = tamper;
|
||||
|
||||
var first = RenderFrame(context, processor, 0);
|
||||
effect.Gain.Values[0].Value = 150d;
|
||||
var second = RenderFrame(context, processor, 1);
|
||||
|
||||
Assert.True(first.SamePixelsAs(CpuReference(context, source, Effect(), 0)), fault);
|
||||
var brighter = Effect();
|
||||
brighter.Gain.Values[0].Value = 150d;
|
||||
Assert.True(second.SamePixelsAs(CpuReference(context, source, brighter, 1)), fault);
|
||||
Assert.Equal(ComputeHealth.Pinned, guardian.HealthOf(luid));
|
||||
Assert.Null(processor.Pipeline);
|
||||
var report = Assert.Single(reports.Received);
|
||||
Assert.Equal(ComputeFailure.CheckFailed, report.Anomaly.Failure);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void AFailedSelfTestStartsOnTheCpuAndReportsOnce()
|
||||
{
|
||||
using var devices = new GraphicsDevices();
|
||||
using var context = devices.CreateContext();
|
||||
RequireInterop(context);
|
||||
using var source = new SourceImage(context, Size, Size, Shape);
|
||||
var reports = new Reports();
|
||||
var guardian = reports.CreateGuardian();
|
||||
using var processor = Processor(context, Effect(), guardian, true, _ => [FailingCheck]);
|
||||
RequireHardware(processor);
|
||||
var luid = processor.Device!.Value.Luid;
|
||||
processor.SetInput(source.Bitmap);
|
||||
|
||||
var first = RenderFrame(context, processor, 0);
|
||||
var second = RenderFrame(context, processor, 1);
|
||||
|
||||
Assert.True(first.SamePixelsAs(CpuReference(context, source, Effect(), 0)));
|
||||
Assert.True(second.SamePixelsAs(first));
|
||||
Assert.Equal(ComputeHealth.Pinned, guardian.HealthOf(luid));
|
||||
Assert.Null(processor.Pipeline);
|
||||
var report = Assert.Single(reports.Received);
|
||||
Assert.Equal(ComputeFailure.SelfTestFailed, report.Anomaly.Failure);
|
||||
Assert.Equal("broken", report.Anomaly.Check?.Name);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void ASelfTestThatThrowsStartsOnTheCpu()
|
||||
{
|
||||
using var devices = new GraphicsDevices();
|
||||
using var context = devices.CreateContext();
|
||||
RequireInterop(context);
|
||||
using var source = new SourceImage(context, Size, Size, Shape);
|
||||
var reports = new Reports();
|
||||
var guardian = reports.CreateGuardian();
|
||||
using var processor = Processor(context, Effect(), guardian, true, _ => throw new InvalidOperationException("self-test"));
|
||||
RequireHardware(processor);
|
||||
processor.SetInput(source.Bitmap);
|
||||
|
||||
var rendering = RenderFrame(context, processor, 0);
|
||||
|
||||
Assert.True(rendering.SamePixelsAs(CpuReference(context, source, Effect(), 0)));
|
||||
var report = Assert.Single(reports.Received);
|
||||
Assert.Equal(ComputeFailure.SelfTestFailed, report.Anomaly.Failure);
|
||||
Assert.IsType<InvalidOperationException>(report.InnerException);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void ReturningToAFrameOnTheCpuReproducesItExactly()
|
||||
{
|
||||
using var devices = new GraphicsDevices();
|
||||
using var context = devices.CreateContext();
|
||||
using var source = new SourceImage(context, Size, Size, Shape);
|
||||
var effect = Effect();
|
||||
using var processor = Processor(context, effect, new Reports().CreateGuardian(), false);
|
||||
processor.SetInput(source.Bitmap);
|
||||
|
||||
var before = RenderFrame(context, processor, 0);
|
||||
effect.Gain.Values[0].Value = 250d;
|
||||
RenderFrame(context, processor, 0);
|
||||
effect.Gain.Values[0].Value = 60d;
|
||||
RenderFrame(context, processor, 0);
|
||||
effect.Gain.Values[0].Value = 100d;
|
||||
var after = RenderFrame(context, processor, 0);
|
||||
|
||||
Assert.True(after.SamePixelsAs(before));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void AZeroAmountOnTheCpuPassesTheImageThrough()
|
||||
{
|
||||
using var devices = new GraphicsDevices();
|
||||
using var context = devices.CreateContext();
|
||||
using var source = new SourceImage(context, Size, Size, Shape);
|
||||
var effect = Effect();
|
||||
effect.Amount.Values[0].Value = 0d;
|
||||
using var processor = Processor(context, effect, new Reports().CreateGuardian(), false);
|
||||
processor.SetInput(source.Bitmap);
|
||||
|
||||
var rendering = RenderFrame(context, processor, 0);
|
||||
|
||||
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]));
|
||||
}
|
||||
}
|
||||
@@ -124,7 +124,7 @@ public sealed class WaveOpticsInteropTests
|
||||
Assert.True(interop.Pipeline.TryGetVisibleBounds(96, 96, in parameters, out var visible));
|
||||
var (width, height) = outputSize(visible);
|
||||
Assert.True(interop.Resources.TryEnsureOutput(width, height, out _));
|
||||
interop.Pipeline.RenderVisible(interop.Resources.GetOutputComputeBinding(), visible, in parameters);
|
||||
interop.Pipeline.RenderVisible(interop.Resources.GetSourceComputeBinding(), interop.Resources.GetOutputComputeBinding(), visible, in parameters);
|
||||
return visible;
|
||||
}
|
||||
|
||||
@@ -155,7 +155,7 @@ public sealed class WaveOpticsInteropTests
|
||||
Assert.True(interop.Pipeline.Simulate(interop.Resources.GetSourceComputeBinding(), size, size, 0, 0, size, size, in parameters));
|
||||
Assert.True(interop.Pipeline.TryGetVisibleBounds(size, size, in parameters, out var visible));
|
||||
Assert.True(interop.Resources.TryEnsureOutput(visible.Width, visible.Height, out _));
|
||||
interop.Pipeline.RenderVisible(interop.Resources.GetOutputComputeBinding(), visible, in parameters);
|
||||
interop.Pipeline.RenderVisible(interop.Resources.GetSourceComputeBinding(), interop.Resources.GetOutputComputeBinding(), visible, in parameters);
|
||||
var output = interop.CaptureOutput(context, out var width, out var height);
|
||||
|
||||
Assert.True(sourceChanged);
|
||||
|
||||
@@ -0,0 +1,135 @@
|
||||
using System.Runtime.InteropServices;
|
||||
using ComputeWeave;
|
||||
using SpectralConvolution;
|
||||
using WaveOptics.Effects;
|
||||
using WaveOptics.Rendering;
|
||||
|
||||
namespace WaveOptics.Tests;
|
||||
|
||||
[Collection("Direct3D12")]
|
||||
public sealed class WaveOpticsPipelineCheckTests
|
||||
{
|
||||
const int Width = 160;
|
||||
const int Height = 144;
|
||||
const int Opaque = unchecked((int)0xFFC0A080);
|
||||
|
||||
static WaveOpticsPipeline.Parameters Parameters(float gain = 1f, int kernelRadius = 15, float defocus = 0.5f)
|
||||
=> new(gain, new WaveOpticsPipeline.PsfParameters(
|
||||
WaveOpticsQuality.Standard, kernelRadius, 550f, 8f, 4f, WaveOpticsApertureShape.Circular, 6, 0f, 0f, defocus, 0f, 0f, 0.3f, 0f, 0f));
|
||||
|
||||
sealed class Scene : IDisposable
|
||||
{
|
||||
public Scene()
|
||||
{
|
||||
var pixels = new int[Width * Height];
|
||||
for (var y = 50; y < 90; y++)
|
||||
{
|
||||
for (var x = 40; x < 110; x++)
|
||||
pixels[y * Width + x] = (x + y) % 7 == 0 ? 0 : Opaque;
|
||||
}
|
||||
|
||||
var device = GraphicsDevice.GetDefault();
|
||||
Source = device.AllocateReadWriteTexture2D<Bgra32, Float4>(Width, Height);
|
||||
Source.CopyFrom(MemoryMarshal.Cast<int, Bgra32>(pixels.AsSpan()));
|
||||
Output = device.AllocateReadWriteTexture2D<Bgra32, Float4>(Width, Height);
|
||||
}
|
||||
|
||||
public ReadWriteTexture2D<Bgra32, Float4> Source { get; }
|
||||
|
||||
public ReadWriteTexture2D<Bgra32, Float4> Output { get; }
|
||||
|
||||
public void Dispose()
|
||||
{
|
||||
Source.Dispose();
|
||||
Output.Dispose();
|
||||
}
|
||||
}
|
||||
|
||||
static ConvolutionMeasurement[] Render(WaveOpticsPipeline pipeline, Scene scene, in WaveOpticsPipeline.Parameters parameters, out int count)
|
||||
{
|
||||
var measurements = new ConvolutionMeasurement[WaveOpticsPipeline.MeasurementCount];
|
||||
pipeline.Simulate(scene.Source, Width, Height, 0, 0, Width, Height, in parameters);
|
||||
Assert.True(pipeline.TryGetVisibleBounds(Width, Height, in parameters, out var rect));
|
||||
count = pipeline.RenderVisible(scene.Source, scene.Output, rect, in parameters, measurements);
|
||||
return measurements;
|
||||
}
|
||||
|
||||
static WaveOpticsPipeline Create()
|
||||
{
|
||||
var pipeline = WaveOpticsPipeline.TryCreate();
|
||||
Assert.NotNull(pipeline);
|
||||
return pipeline;
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[InlineData(15)]
|
||||
[InlineData(40)]
|
||||
public void AHealthyConvolutionPassesEveryCheck(int kernelRadius)
|
||||
{
|
||||
using var pipeline = Create();
|
||||
using var scene = new Scene();
|
||||
|
||||
var measurements = Render(pipeline, scene, Parameters(kernelRadius: kernelRadius), out var count);
|
||||
|
||||
Assert.Equal(WaveOpticsPipeline.MeasurementCount, count);
|
||||
Assert.All(measurements, measurement => Assert.True(measurement.Passes, $"{measurement}"));
|
||||
Assert.False(pipeline.IsDeviceLost);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void DrawingFromTheStoreReturnsNoMeasurements()
|
||||
{
|
||||
using var pipeline = Create();
|
||||
using var scene = new Scene();
|
||||
Render(pipeline, scene, Parameters(), out _);
|
||||
Render(pipeline, scene, Parameters(gain: 2f), out var storing);
|
||||
|
||||
Render(pipeline, scene, Parameters(gain: 3f), out var stored);
|
||||
|
||||
Assert.Equal(WaveOpticsPipeline.MeasurementCount, storing);
|
||||
Assert.Equal(0, stored);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void TheSamePictureIsCheckedAtTheSamePlaces()
|
||||
{
|
||||
using var first = Create();
|
||||
using var second = Create();
|
||||
using var scene = new Scene();
|
||||
|
||||
var a = Render(first, scene, Parameters(), out _);
|
||||
var b = Render(second, scene, Parameters(), out _);
|
||||
|
||||
Assert.Equal(a.Select(measurement => (measurement.Name, measurement.Reference, measurement.Tolerance)), b.Select(measurement => (measurement.Name, measurement.Reference, measurement.Tolerance)));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void AScaledSpectrumFailsTheChecks()
|
||||
{
|
||||
using var pipeline = Create();
|
||||
using var scene = new Scene();
|
||||
pipeline.SpectrumTamper = spectrum => [.. spectrum.Select(value => new Float2(value.X * 1.001f, value.Y * 1.001f))];
|
||||
|
||||
var measurements = Render(pipeline, scene, Parameters(), out _);
|
||||
|
||||
Assert.Contains(measurements, measurement => !measurement.Passes);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void ANaNInTheSpectrumIsCounted()
|
||||
{
|
||||
using var pipeline = Create();
|
||||
using var scene = new Scene();
|
||||
pipeline.SpectrumTamper = spectrum =>
|
||||
{
|
||||
var broken = (Float2[])spectrum.Clone();
|
||||
broken[3] = new Float2(float.NaN, 0f);
|
||||
return broken;
|
||||
};
|
||||
|
||||
var measurements = Render(pipeline, scene, Parameters(), out _);
|
||||
|
||||
Assert.Equal(GpuTileCheck.NonFiniteName, measurements[0].Name);
|
||||
Assert.False(measurements[0].Passes);
|
||||
}
|
||||
}
|
||||
@@ -88,7 +88,7 @@ public sealed class WaveOpticsPipelineTests
|
||||
return pixels;
|
||||
|
||||
using var output = device.AllocateReadWriteTexture2D<Bgra32, Float4>(rect.Width, rect.Height);
|
||||
pipeline.RenderVisible(output, rect, in parameters);
|
||||
pipeline.RenderVisible(source, output, rect, in parameters);
|
||||
var visible = new Bgra32[rect.Width * rect.Height];
|
||||
output.CopyTo(visible);
|
||||
for (var y = 0; y < rect.Height; y++)
|
||||
@@ -118,12 +118,6 @@ public sealed class WaveOpticsPipelineTests
|
||||
return new FraunhoferPsfGenerator().Generate(descriptor).Kernel;
|
||||
}
|
||||
|
||||
static SeparableKernel Decompose(WaveOpticsPipeline.PsfParameters psf)
|
||||
{
|
||||
var kernel = Kernel(psf);
|
||||
return SeparableKernel.Decompose(kernel.Values.Span, kernel.Size, WaveOpticsSettings.SeparableResidualRatio, WaveOpticsSettings.MaximumRank);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void ATransparentSourceStaysTransparent()
|
||||
{
|
||||
@@ -153,12 +147,13 @@ public sealed class WaveOpticsPipelineTests
|
||||
[InlineData(0, 0)]
|
||||
[InlineData(32, 32)]
|
||||
[InlineData(3, 29)]
|
||||
public void AnImpulseSpreadsIntoTheSeparableKernel(int impulseX, int impulseY)
|
||||
public void AnImpulseSpreadsIntoTheKernelScaledToKeepItsLight(int impulseX, int impulseY)
|
||||
{
|
||||
using var pipeline = CreatePipeline();
|
||||
var parameters = Parameters(kernelRadius: 6, pixelPitch: 1.5f, comaHorizontal: 0.4f);
|
||||
var separable = Decompose(parameters.Psf);
|
||||
var radius = separable.Size / 2;
|
||||
var kernel = Kernel(parameters.Psf);
|
||||
var sum = kernel.Values.ToArray().Sum();
|
||||
var radius = kernel.Size / 2;
|
||||
var source = Square(33, 33, impulseX, impulseY, 1, 1, White);
|
||||
|
||||
var rendering = Render(pipeline, source, 33, 33, parameters);
|
||||
@@ -167,16 +162,10 @@ public sealed class WaveOpticsPipelineTests
|
||||
{
|
||||
for (var x = 0; x < 33; x++)
|
||||
{
|
||||
var expected = 0f;
|
||||
var row = impulseY - y + radius;
|
||||
var column = impulseX - x + radius;
|
||||
if (row >= 0 && row < separable.Size && column >= 0 && column < separable.Size)
|
||||
{
|
||||
for (var term = 0; term < separable.Rank; term++)
|
||||
expected += separable.Horizontal[term * separable.Size + column] * separable.Vertical[term * separable.Size + row];
|
||||
}
|
||||
|
||||
var value = (int)Math.Round(Math.Clamp(expected / separable.Sum, 0d, 1d) * 255d, MidpointRounding.ToEven);
|
||||
var expected = row >= 0 && row < kernel.Size && column >= 0 && column < kernel.Size ? kernel[column, row] / sum : 0d;
|
||||
var value = (int)Math.Round(Math.Clamp(expected, 0d, 1d) * 255d, MidpointRounding.ToEven);
|
||||
Assert.InRange(Alpha(rendering[y * 33 + x]), value - 1, value + 1);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,86 @@
|
||||
using WaveOptics.Effects;
|
||||
using WaveOptics.Rendering;
|
||||
|
||||
namespace WaveOptics.Tests;
|
||||
|
||||
public sealed class WaveOpticsRenderTrackerTests
|
||||
{
|
||||
static readonly WaveOpticsPipeline.PsfParameters Psf = new(
|
||||
WaveOpticsQuality.Standard, 15, 550f, 8f, 4f, WaveOpticsApertureShape.Circular, 6, 0f, 0f, 0f, 0f, 0f, 0f, 0f, 0f);
|
||||
|
||||
static readonly WaveOpticsConvolutionKey First = new(1, 2, 100, 100, new WaveOpticsPipeline.PixelRect(16, 16, 68, 68), Psf);
|
||||
|
||||
static readonly WaveOpticsConvolutionKey Second = First with { HashSum = 3 };
|
||||
|
||||
static readonly WaveOpticsPipeline.PixelRect Rect = new(0, 0, 100, 100);
|
||||
|
||||
[Fact]
|
||||
public void ANewConvolutionIsComputedWithoutAStore()
|
||||
{
|
||||
var tracker = new WaveOpticsRenderTracker();
|
||||
|
||||
Assert.Equal(WaveOpticsRenderMode.Convolve, tracker.Next(First, Rect, 1f, out var release));
|
||||
|
||||
Assert.False(release);
|
||||
Assert.False(tracker.HasStore);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void TheFirstGainChangeStoresAndLaterOnesDrawFromTheStore()
|
||||
{
|
||||
var tracker = new WaveOpticsRenderTracker();
|
||||
tracker.Next(First, Rect, 1f, out _);
|
||||
|
||||
Assert.Equal(WaveOpticsRenderMode.ConvolveAndStore, tracker.Next(First, Rect, 1.5f, out _));
|
||||
Assert.True(tracker.HasStore);
|
||||
Assert.Equal(WaveOpticsRenderMode.Stored, tracker.Next(First, Rect, 2f, out _));
|
||||
Assert.Equal(WaveOpticsRenderMode.Stored, tracker.Next(First, Rect, 2f, out _));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void RedrawingTheSameFrameWithoutAStoreConvolvesAgain()
|
||||
{
|
||||
var tracker = new WaveOpticsRenderTracker();
|
||||
tracker.Next(First, Rect, 1f, out _);
|
||||
|
||||
Assert.Equal(WaveOpticsRenderMode.Convolve, tracker.Next(First, Rect, 1f, out _));
|
||||
Assert.False(tracker.HasStore);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void ANewSourceOrRectangleLetsTheStoreGo()
|
||||
{
|
||||
var tracker = new WaveOpticsRenderTracker();
|
||||
tracker.Next(First, Rect, 1f, out _);
|
||||
tracker.Next(First, Rect, 2f, out _);
|
||||
|
||||
Assert.Equal(WaveOpticsRenderMode.Convolve, tracker.Next(Second, Rect, 2f, out var releasedForSource));
|
||||
Assert.True(releasedForSource);
|
||||
Assert.False(tracker.HasStore);
|
||||
|
||||
tracker.Next(Second, Rect, 3f, out _);
|
||||
Assert.Equal(WaveOpticsRenderMode.Convolve, tracker.Next(Second, Rect with { Width = 96 }, 3f, out var releasedForRect));
|
||||
Assert.True(releasedForRect);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void AResetForgetsTheFrameAndReportsTheStore()
|
||||
{
|
||||
var tracker = new WaveOpticsRenderTracker();
|
||||
tracker.Next(First, Rect, 1f, out _);
|
||||
tracker.Next(First, Rect, 2f, out _);
|
||||
|
||||
Assert.True(tracker.Reset());
|
||||
Assert.False(tracker.Reset());
|
||||
Assert.Equal(WaveOpticsRenderMode.Convolve, tracker.Next(First, Rect, 2f, out var release));
|
||||
Assert.False(release);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void TheSamplingKeyComesFromTheSourceHash()
|
||||
{
|
||||
Assert.Equal(1UL << 32 | 2UL, First.SamplingKey);
|
||||
Assert.NotEqual(First.SamplingKey, Second.SamplingKey);
|
||||
Assert.Equal(First.SamplingKey, (First with { Psf = Psf with { Defocus = 1f } }).SamplingKey);
|
||||
}
|
||||
}
|
||||
@@ -1,3 +1,4 @@
|
||||
using SpectralConvolution;
|
||||
using WaveOptics.Abstractions;
|
||||
using WaveOptics.Effects;
|
||||
using WaveOptics.Optics;
|
||||
@@ -28,21 +29,11 @@ public sealed class WaveOpticsSettingsTests
|
||||
=> Assert.Equal(size, WaveOpticsSettings.GetKernelSize(radius));
|
||||
|
||||
[Fact]
|
||||
public void TheLargestKernelFitsInEveryWeightSlot()
|
||||
=> Assert.Equal(WaveOpticsSettings.MaximumKernelSize, WaveOpticsSettings.GetKernelSize(WaveOpticsSettings.MaximumKernelRadius));
|
||||
|
||||
[Fact]
|
||||
public void EveryTermAndAxisOwnsItsOwnWeightSlot()
|
||||
public void TheLargestKernelFitsInTheLargestTile()
|
||||
{
|
||||
var offsets = Enumerable.Range(0, WaveOpticsSettings.MaximumRank)
|
||||
.SelectMany(term => new[] { WaveOpticsSettings.GetWeightOffset(term, 0), WaveOpticsSettings.GetWeightOffset(term, 1) })
|
||||
.Order()
|
||||
.ToArray();
|
||||
|
||||
Assert.Equal(WaveOpticsSettings.MaximumRank * 2, offsets.Distinct().Count());
|
||||
Assert.Equal(0, offsets[0]);
|
||||
Assert.All(offsets.Zip(offsets.Skip(1)), pair => Assert.Equal(WaveOpticsSettings.MaximumKernelSize, pair.Second - pair.First));
|
||||
Assert.Equal(WaveOpticsSettings.WeightsLength, offsets[^1] + WaveOpticsSettings.MaximumKernelSize);
|
||||
Assert.Equal(WaveOpticsSettings.MaximumKernelSize, WaveOpticsSettings.GetKernelSize(WaveOpticsSettings.MaximumKernelRadius));
|
||||
Assert.True(WaveOpticsSettings.MaximumKernelRadius <= TilePlan.MaximumRadius);
|
||||
Assert.Equal(TilePlan.LargeSize, TilePlan.SelectSize(WaveOpticsSettings.MaximumKernelRadius));
|
||||
}
|
||||
|
||||
public static readonly TheoryData<string, WavefrontAberration> Aberrations = new()
|
||||
@@ -56,7 +47,7 @@ public sealed class WaveOpticsSettingsTests
|
||||
|
||||
[Theory]
|
||||
[MemberData(nameof(Aberrations))]
|
||||
public void TheRankLimitKeepsEveryAberrationWithinTheResidualBudget(string aberrationName, WavefrontAberration aberration)
|
||||
public void EveryAberrationGivesAKernelTheConvolutionAccepts(string aberrationName, WavefrontAberration aberration)
|
||||
{
|
||||
var gridSize = WaveOpticsSettings.GetPupilGridSize(WaveOpticsQuality.Standard);
|
||||
var descriptor = new PsfDescriptor(
|
||||
@@ -65,10 +56,11 @@ public sealed class WaveOpticsSettingsTests
|
||||
WaveOpticsSettings.MaximumKernelSize,
|
||||
550, 8, 4, ApertureShape.Circular, 6, 0, 0, aberration);
|
||||
var kernel = new FraunhoferPsfGenerator().Generate(descriptor).Kernel;
|
||||
var spectrum = new KernelSpectrum();
|
||||
|
||||
var separable = SeparableKernel.Decompose(kernel.Values.Span, kernel.Size, WaveOpticsSettings.SeparableResidualRatio, WaveOpticsSettings.MaximumRank);
|
||||
spectrum.Update(kernel.Values.Span, WaveOpticsSettings.MaximumKernelRadius, TilePlan.SelectSize(WaveOpticsSettings.MaximumKernelRadius));
|
||||
|
||||
Assert.True(separable.ResidualEnergyRatio <= WaveOpticsSettings.SeparableResidualRatio, $"{aberrationName}: {separable.ResidualEnergyRatio}");
|
||||
Assert.True(Math.Abs(spectrum.Spectrum[0].X - 1f) <= 1e-6f, aberrationName);
|
||||
}
|
||||
|
||||
[Theory]
|
||||
|
||||
@@ -0,0 +1,73 @@
|
||||
using System.Runtime.InteropServices;
|
||||
using ComputeWeave;
|
||||
using WaveOptics.Effects;
|
||||
using WaveOptics.Rendering;
|
||||
|
||||
namespace WaveOptics.Tests;
|
||||
|
||||
[Collection("Direct3D12")]
|
||||
public sealed class WaveOpticsSourceHashTests
|
||||
{
|
||||
static readonly WaveOpticsPipeline.Parameters Defaults = new(1f, new WaveOpticsPipeline.PsfParameters(
|
||||
WaveOpticsQuality.Draft, 3, 550f, 8f, 4f, WaveOpticsApertureShape.Circular, 6, 0f, 0f, 0f, 0f, 0f, 0f, 0f, 0f));
|
||||
|
||||
static int[] RandomPixels(int width, int height, int seed, double litFraction)
|
||||
{
|
||||
var random = new Random(seed);
|
||||
var pixels = new int[width * height];
|
||||
for (var index = 0; index < pixels.Length; index++)
|
||||
{
|
||||
if (random.NextDouble() < litFraction)
|
||||
pixels[index] = random.Next(int.MinValue, int.MaxValue) | 1;
|
||||
}
|
||||
|
||||
return pixels;
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[InlineData(37, 21, 0, 0, 0.3)]
|
||||
[InlineData(64, 48, 16, 12, 0.05)]
|
||||
[InlineData(19, 33, 4, 8, 1.0)]
|
||||
public void TheCpuHashMatchesTheGpuHash(int width, int height, int offsetX, int offsetY, double litFraction)
|
||||
{
|
||||
using var pipeline = WaveOpticsPipeline.TryCreate();
|
||||
Assert.NotNull(pipeline);
|
||||
var pixels = RandomPixels(width, height, width * height, litFraction);
|
||||
using var texture = GraphicsDevice.GetDefault().AllocateReadWriteTexture2D<Bgra32, Float4>(width, height);
|
||||
texture.CopyFrom(MemoryMarshal.Cast<int, Bgra32>(pixels.AsSpan()));
|
||||
var parameters = Defaults;
|
||||
|
||||
pipeline.Simulate(texture, width + offsetX * 2, height + offsetY * 2, offsetX, offsetY, width, height, in parameters);
|
||||
|
||||
var cpu = WaveOpticsSourceHash.Compute(MemoryMarshal.AsBytes(pixels.AsSpan()), offsetX, offsetY, width, height);
|
||||
Assert.Equal(pipeline.SourceHash, cpu);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void ATransparentSourceHasNothingToShow()
|
||||
{
|
||||
var hash = WaveOpticsSourceHash.Compute(new byte[16 * 16 * 4], 4, 4, 16, 16);
|
||||
|
||||
Assert.Equal(0, hash.LitCount);
|
||||
Assert.False(hash.TryGetVisibleBounds(24, 24, 3, out _));
|
||||
Assert.Equal(WaveOpticsSourceHash.Empty, hash);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void TheBoundsAreReportedInCanvasCoordinates()
|
||||
{
|
||||
var pixels = new int[10 * 8];
|
||||
pixels[2 * 10 + 3] = -1;
|
||||
pixels[5 * 10 + 7] = 1 << 24;
|
||||
|
||||
var hash = WaveOpticsSourceHash.Compute(MemoryMarshal.AsBytes(pixels.AsSpan()), 20, 30, 10, 8);
|
||||
|
||||
Assert.Equal((2, 23, 32, 27, 35), (hash.LitCount, hash.MinimumX, hash.MinimumY, hash.MaximumX, hash.MaximumY));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void AShortSourceIsRejected()
|
||||
{
|
||||
Assert.Throws<ArgumentException>(() => WaveOpticsSourceHash.Compute(new byte[15], 0, 0, 2, 2));
|
||||
}
|
||||
}
|
||||
@@ -7,6 +7,7 @@
|
||||
"additional-timeout": 30000,
|
||||
"mutate": [
|
||||
"**/*.cs",
|
||||
"!**/YMM4-ComputeGuard/**",
|
||||
"!**/YMM4-GitHubUpdateNotifier/**",
|
||||
"!**/YMM4-Telemetry/**",
|
||||
"!**/WaveOpticsTelemetry.cs",
|
||||
|
||||
@@ -23,5 +23,7 @@
|
||||
<BuildType Solution="*|*" Project="Release" />
|
||||
<Platform Solution="*|*" Project="Win32" />
|
||||
</Project>
|
||||
<Project Path="SpectralConvolution/SpectralConvolution/SpectralConvolution.csproj" />
|
||||
<Project Path="SpectralConvolution/SpectralConvolution.Tests/SpectralConvolution.Tests.csproj" />
|
||||
<Project Path="YukkuriMovieMaker.Generator/YukkuriMovieMaker.Generator/YukkuriMovieMaker.Generator.csproj" />
|
||||
</Solution>
|
||||
@@ -1,6 +1,8 @@
|
||||
using System.ComponentModel;
|
||||
using System.Numerics;
|
||||
using ComputeGuard;
|
||||
using ComputeWeave;
|
||||
using SpectralConvolution;
|
||||
using Vortice.Direct2D1;
|
||||
using Vortice.Direct2D1.Effects;
|
||||
using WaveOptics.Rendering;
|
||||
@@ -14,12 +16,22 @@ internal sealed class WaveOpticsEffectProcessor : VideoEffectProcessorBase
|
||||
{
|
||||
private readonly IGraphicsDevicesAndContext _devices;
|
||||
private readonly WaveOpticsEffect _item;
|
||||
private readonly ComputeGuardian _guardian;
|
||||
private readonly Func<ComputeDevice, IReadOnlyList<ComputeCheck>> _selfTest;
|
||||
private readonly bool _allowGpu;
|
||||
private readonly ConvolutionMeasurement[] _measurements = new ConvolutionMeasurement[WaveOpticsPipeline.MeasurementCount];
|
||||
private readonly ComputeCheck[] _checks = new ComputeCheck[WaveOpticsPipeline.MeasurementCount];
|
||||
private ComputeExternalQueueScheduler? _scheduler;
|
||||
private WaveOpticsInteropProvider? _interopProvider;
|
||||
private ComputeInteropDomain? _interopDomain;
|
||||
private WaveOpticsResourceSet? _resourceSet;
|
||||
private ExternalTextureLease<ExternalDirect3D11TextureView>? _outputLease;
|
||||
private WaveOpticsPipeline? _pipeline;
|
||||
private GraphicsDevice? _graphicsDevice;
|
||||
private ComputeDevice? _computeDevice;
|
||||
private bool _gpuAttempted;
|
||||
private WaveOpticsCpuPipeline? _cpuPipeline;
|
||||
private WaveOpticsCpuSurface? _cpuSurface;
|
||||
private WaveOpticsCustomEffect? _effect;
|
||||
private Crop? _outputCrop;
|
||||
private ID2D1Image? _outputCropOutput;
|
||||
@@ -30,16 +42,48 @@ internal sealed class WaveOpticsEffectProcessor : VideoEffectProcessorBase
|
||||
private bool _hasOutputOffset;
|
||||
private bool _hasCropRect;
|
||||
private bool _hasRenderState;
|
||||
private OutputKind _outputKind;
|
||||
private Vector2 _outputOffset;
|
||||
private Vector4 _cropRect;
|
||||
private float _amount;
|
||||
private RenderState _renderState;
|
||||
|
||||
public WaveOpticsEffectProcessor(IGraphicsDevicesAndContext devices, WaveOpticsEffect item)
|
||||
: this(devices, item, WaveOpticsCompute.Guardian, null, true)
|
||||
{
|
||||
}
|
||||
|
||||
internal WaveOpticsEffectProcessor(
|
||||
IGraphicsDevicesAndContext devices,
|
||||
WaveOpticsEffect item,
|
||||
ComputeGuardian guardian,
|
||||
Func<ComputeDevice, IReadOnlyList<ComputeCheck>>? selfTest,
|
||||
bool allowGpu)
|
||||
: base(devices)
|
||||
{
|
||||
_devices = devices;
|
||||
_item = item;
|
||||
_guardian = guardian;
|
||||
_selfTest = selfTest ?? RunSelfTest;
|
||||
_allowGpu = allowGpu;
|
||||
}
|
||||
|
||||
internal WaveOpticsPipeline? Pipeline
|
||||
{
|
||||
get
|
||||
{
|
||||
EnsureGpu();
|
||||
return _pipeline;
|
||||
}
|
||||
}
|
||||
|
||||
internal ComputeDevice? Device
|
||||
{
|
||||
get
|
||||
{
|
||||
EnsureGpu();
|
||||
return _pipeline is null ? null : _computeDevice;
|
||||
}
|
||||
}
|
||||
|
||||
public override DrawDescription Update(EffectDescription effectDescription)
|
||||
@@ -57,7 +101,7 @@ internal sealed class WaveOpticsEffectProcessor : VideoEffectProcessorBase
|
||||
|
||||
private DrawDescription UpdateCore(EffectDescription effectDescription)
|
||||
{
|
||||
if (IsPassThroughEffect || _effect is null || _outputCrop is null || _outputTransform is null || _outputTransformOutput is null || _resourceSet is null || _interopProvider is null || _pipeline is null || input is null)
|
||||
if (IsPassThroughEffect || _effect is null || _outputCrop is null || _outputTransform is null || _outputTransformOutput is null || input is null)
|
||||
return effectDescription.DrawDescription;
|
||||
|
||||
var frame = effectDescription.ItemPosition.Frame;
|
||||
@@ -114,31 +158,29 @@ internal sealed class WaveOpticsEffectProcessor : VideoEffectProcessorBase
|
||||
_isFirst = true;
|
||||
return effectDescription.DrawDescription;
|
||||
}
|
||||
var canvasWidth = (int)widthValue + margin * 2;
|
||||
var canvasHeight = (int)heightValue + margin * 2;
|
||||
var itemWidth = (int)widthValue;
|
||||
var itemHeight = (int)heightValue;
|
||||
|
||||
if (!EnsureSource(itemWidth, itemHeight))
|
||||
{
|
||||
_effect.Amount = 0f;
|
||||
_isFirst = true;
|
||||
return effectDescription.DrawDescription;
|
||||
}
|
||||
|
||||
RenderInput(new Vortice.RawRectF(bounds.Left, bounds.Top, bounds.Left + itemWidth, bounds.Top + itemHeight));
|
||||
|
||||
var convolutionChanged = _pipeline.Simulate(
|
||||
_resourceSet.GetSourceComputeBinding(),
|
||||
canvasWidth,
|
||||
canvasHeight,
|
||||
var geometry = new FrameGeometry(
|
||||
bounds.Left,
|
||||
bounds.Top,
|
||||
(int)widthValue,
|
||||
(int)heightValue,
|
||||
margin,
|
||||
margin,
|
||||
itemWidth,
|
||||
itemHeight,
|
||||
in parameters);
|
||||
(int)widthValue + margin * 2,
|
||||
(int)heightValue + margin * 2);
|
||||
|
||||
if (!_pipeline.HasKernel || !_pipeline.TryGetVisibleBounds(canvasWidth, canvasHeight, in parameters, out var rect))
|
||||
EnsureGpu();
|
||||
var workload = WaveOpticsCompute.Workload(geometry.CanvasWidth, geometry.CanvasHeight, parameters.Psf.KernelRadius);
|
||||
var device = _pipeline is null ? null : _computeDevice;
|
||||
var decision = _guardian.Select(device, workload, _selfTest);
|
||||
if (decision.Reason is ComputeRouteReason.Pinned or ComputeRouteReason.SoftwareAdapter)
|
||||
ReleaseInterop();
|
||||
var outcome = decision.Route == ComputeRoute.Gpu && device is { } gpuDevice
|
||||
? RenderGpu(in geometry, in parameters, gpuDevice, in workload)
|
||||
: FrameOutcome.Fallback;
|
||||
if (outcome == FrameOutcome.Fallback)
|
||||
outcome = RenderCpu(in geometry, in parameters);
|
||||
|
||||
if (outcome == FrameOutcome.PassThrough)
|
||||
{
|
||||
_effect.Amount = 0f;
|
||||
_amount = amount;
|
||||
@@ -147,32 +189,7 @@ internal sealed class WaveOpticsEffectProcessor : VideoEffectProcessorBase
|
||||
return effectDescription.DrawDescription;
|
||||
}
|
||||
|
||||
if (!OutputCovers(rect.Width, rect.Height))
|
||||
_outputCrop.SetInput(0, null, true);
|
||||
if (!EnsureOutput(rect.Width, rect.Height, out var outputChanged))
|
||||
{
|
||||
_effect.Amount = 0f;
|
||||
_amount = amount;
|
||||
_isFirst = true;
|
||||
_hasRenderState = false;
|
||||
return effectDescription.DrawDescription;
|
||||
}
|
||||
var renderState = new RenderState(parameters.Gain, rect);
|
||||
if (convolutionChanged || outputChanged || !_hasOutput || !_hasRenderState || _renderState != renderState)
|
||||
{
|
||||
_pipeline.RenderVisible(_resourceSet.GetOutputComputeBinding(), rect, in parameters);
|
||||
_renderState = renderState;
|
||||
_hasRenderState = true;
|
||||
}
|
||||
|
||||
_outputLease ??= _resourceSet.AcquireOutputExternalViewLease();
|
||||
|
||||
if (outputChanged || !_hasOutput)
|
||||
{
|
||||
using var outputBitmap = new ID2D1Bitmap1(_outputLease.DangerousGetView().AddRefBitmap());
|
||||
_outputCrop.SetInput(0, outputBitmap, true);
|
||||
_effect.SetInput(1, _outputTransformOutput, true);
|
||||
}
|
||||
var rect = _renderState.Rect;
|
||||
var cropRect = new Vector4(0f, 0f, rect.Width, rect.Height);
|
||||
if (!_hasCropRect || _cropRect != cropRect)
|
||||
{
|
||||
@@ -180,7 +197,7 @@ internal sealed class WaveOpticsEffectProcessor : VideoEffectProcessorBase
|
||||
_cropRect = cropRect;
|
||||
_hasCropRect = true;
|
||||
}
|
||||
var outputOffset = new Vector2(bounds.Left - margin + rect.X, bounds.Top - margin + rect.Y);
|
||||
var outputOffset = new Vector2(geometry.Left - margin + rect.X, geometry.Top - margin + rect.Y);
|
||||
if (!_hasOutputOffset || _outputOffset != outputOffset)
|
||||
{
|
||||
_outputTransform.TransformMatrix = Matrix3x2.CreateTranslation(outputOffset);
|
||||
@@ -193,9 +210,153 @@ internal sealed class WaveOpticsEffectProcessor : VideoEffectProcessorBase
|
||||
return effectDescription.DrawDescription;
|
||||
}
|
||||
|
||||
private bool EnsureSource(int width, int height)
|
||||
private FrameOutcome RenderGpu(in FrameGeometry geometry, in WaveOpticsPipeline.Parameters parameters, ComputeDevice device, in ComputeWorkload workload)
|
||||
{
|
||||
return _resourceSet!.TryEnsureSource(width, height, out _);
|
||||
var pipeline = _pipeline!;
|
||||
var resourceSet = _resourceSet!;
|
||||
try
|
||||
{
|
||||
if (!resourceSet.TryEnsureSource(geometry.ItemWidth, geometry.ItemHeight, out _))
|
||||
{
|
||||
_guardian.Fail(device, workload, ComputeFailure.ResourceExhausted, null);
|
||||
return FrameOutcome.Fallback;
|
||||
}
|
||||
|
||||
RenderInput(new Vortice.RawRectF(geometry.Left, geometry.Top, geometry.Left + geometry.ItemWidth, geometry.Top + geometry.ItemHeight));
|
||||
var convolutionChanged = pipeline.Simulate(
|
||||
resourceSet.GetSourceComputeBinding(),
|
||||
geometry.CanvasWidth,
|
||||
geometry.CanvasHeight,
|
||||
geometry.Margin,
|
||||
geometry.Margin,
|
||||
geometry.ItemWidth,
|
||||
geometry.ItemHeight,
|
||||
in parameters);
|
||||
|
||||
if (!pipeline.HasKernel || !pipeline.TryGetVisibleBounds(geometry.CanvasWidth, geometry.CanvasHeight, in parameters, out var rect))
|
||||
return FrameOutcome.PassThrough;
|
||||
|
||||
if (!OutputCovers(rect.Width, rect.Height))
|
||||
_outputCrop!.SetInput(0, null, true);
|
||||
if (!EnsureOutput(rect.Width, rect.Height, out var outputChanged))
|
||||
{
|
||||
_guardian.Fail(device, workload, ComputeFailure.ResourceExhausted, null);
|
||||
return FrameOutcome.Fallback;
|
||||
}
|
||||
|
||||
var kindChanged = _outputKind != OutputKind.Gpu;
|
||||
var renderState = new RenderState(parameters.Gain, rect);
|
||||
if (convolutionChanged || outputChanged || kindChanged || !_hasOutput || !_hasRenderState || _renderState != renderState)
|
||||
{
|
||||
var count = pipeline.RenderVisible(resourceSet.GetSourceComputeBinding(), resourceSet.GetOutputComputeBinding(), rect, in parameters, _measurements);
|
||||
if (count > 0)
|
||||
{
|
||||
for (var index = 0; index < count; index++)
|
||||
_checks[index] = WaveOpticsCompute.ToCheck(_measurements[index]);
|
||||
if (!_guardian.Judge(device, workload, _checks.AsSpan(0, count)))
|
||||
return FrameOutcome.Fallback;
|
||||
}
|
||||
|
||||
_renderState = renderState;
|
||||
_hasRenderState = true;
|
||||
}
|
||||
|
||||
_outputLease ??= resourceSet.AcquireOutputExternalViewLease();
|
||||
if (outputChanged || kindChanged || !_hasOutput)
|
||||
{
|
||||
using var outputBitmap = new ID2D1Bitmap1(_outputLease.DangerousGetView().AddRefBitmap());
|
||||
_outputCrop!.SetInput(0, outputBitmap, true);
|
||||
_effect!.SetInput(1, _outputTransformOutput, true);
|
||||
_outputKind = OutputKind.Gpu;
|
||||
}
|
||||
|
||||
return FrameOutcome.Rendered;
|
||||
}
|
||||
catch (Exception exception)
|
||||
{
|
||||
_guardian.Fail(device, workload, WaveOpticsCompute.Classify(exception, pipeline.IsDeviceLost), exception);
|
||||
return FrameOutcome.Fallback;
|
||||
}
|
||||
}
|
||||
|
||||
private FrameOutcome RenderCpu(in FrameGeometry geometry, in WaveOpticsPipeline.Parameters parameters)
|
||||
{
|
||||
var surface = _cpuSurface ??= new WaveOpticsCpuSurface(_devices.D2D.Device);
|
||||
var pipeline = _cpuPipeline ??= new WaveOpticsCpuPipeline();
|
||||
var pixels = surface.Read(input!, new Vector2(-geometry.Left, -geometry.Top), geometry.ItemWidth, geometry.ItemHeight);
|
||||
var convolutionChanged = pipeline.Simulate(
|
||||
pixels,
|
||||
geometry.CanvasWidth,
|
||||
geometry.CanvasHeight,
|
||||
geometry.Margin,
|
||||
geometry.Margin,
|
||||
geometry.ItemWidth,
|
||||
geometry.ItemHeight,
|
||||
in parameters);
|
||||
|
||||
if (!pipeline.HasKernel || !pipeline.TryGetVisibleBounds(geometry.CanvasWidth, geometry.CanvasHeight, in parameters, out var rect))
|
||||
return FrameOutcome.PassThrough;
|
||||
|
||||
var kindChanged = _outputKind != OutputKind.Cpu;
|
||||
var renderState = new RenderState(parameters.Gain, rect);
|
||||
var outputChanged = false;
|
||||
if (convolutionChanged || kindChanged || !_hasOutput || !_hasRenderState || _renderState != renderState)
|
||||
{
|
||||
var output = pipeline.RenderVisible(rect, in parameters);
|
||||
surface.Write(output, rect.Width, rect.Height, out outputChanged);
|
||||
_renderState = renderState;
|
||||
_hasRenderState = true;
|
||||
}
|
||||
|
||||
if (outputChanged || kindChanged || !_hasOutput)
|
||||
{
|
||||
_outputCrop!.SetInput(0, surface.Output, true);
|
||||
_effect!.SetInput(1, _outputTransformOutput, true);
|
||||
_outputKind = OutputKind.Cpu;
|
||||
}
|
||||
|
||||
return FrameOutcome.Rendered;
|
||||
}
|
||||
|
||||
private IReadOnlyList<ComputeCheck> RunSelfTest(ComputeDevice device)
|
||||
=> WaveOpticsCompute.SelfTest(_graphicsDevice ?? throw new InvalidOperationException());
|
||||
|
||||
private void EnsureGpu()
|
||||
{
|
||||
if (_gpuAttempted || !_allowGpu || IsPassThroughEffect)
|
||||
return;
|
||||
_gpuAttempted = true;
|
||||
|
||||
var scheduler = ComputeExternalQueueScheduler.Create();
|
||||
var interopProvider = WaveOpticsInteropProvider.TryCreate(_devices, scheduler, out var interopDevice);
|
||||
if (interopProvider is null || interopDevice is null)
|
||||
{
|
||||
scheduler.Dispose();
|
||||
return;
|
||||
}
|
||||
|
||||
_scheduler = scheduler;
|
||||
try
|
||||
{
|
||||
_interopProvider = interopProvider;
|
||||
_interopDomain = interopDevice.RegisterExternalDomain(interopProvider);
|
||||
_resourceSet = WaveOpticsResourceSet.Create(interopDevice, _interopDomain);
|
||||
_pipeline = WaveOpticsPipeline.TryCreate(interopDevice);
|
||||
_computeDevice = WaveOpticsCompute.DescribeDevice(_devices);
|
||||
_graphicsDevice = interopDevice;
|
||||
}
|
||||
catch (Win32Exception)
|
||||
{
|
||||
ReleaseInterop();
|
||||
}
|
||||
catch
|
||||
{
|
||||
ReleaseInterop();
|
||||
throw;
|
||||
}
|
||||
|
||||
if (_pipeline is null)
|
||||
ReleaseInterop();
|
||||
}
|
||||
|
||||
private bool OutputCovers(int width, int height)
|
||||
@@ -242,6 +403,12 @@ internal sealed class WaveOpticsEffectProcessor : VideoEffectProcessorBase
|
||||
|
||||
private void ReleaseInterop()
|
||||
{
|
||||
if (_outputKind == OutputKind.Gpu)
|
||||
{
|
||||
_outputCrop?.SetInput(0, null, true);
|
||||
_outputKind = OutputKind.None;
|
||||
_hasOutput = false;
|
||||
}
|
||||
_outputLease?.Dispose();
|
||||
_outputLease = null;
|
||||
_pipeline?.Dispose();
|
||||
@@ -256,44 +423,20 @@ internal sealed class WaveOpticsEffectProcessor : VideoEffectProcessorBase
|
||||
_interopProvider = null;
|
||||
_scheduler?.Dispose();
|
||||
_scheduler = null;
|
||||
_graphicsDevice = null;
|
||||
_computeDevice = null;
|
||||
}
|
||||
|
||||
private void ReleaseCpu()
|
||||
{
|
||||
_cpuPipeline?.Dispose();
|
||||
_cpuPipeline = null;
|
||||
_cpuSurface?.Dispose();
|
||||
_cpuSurface = null;
|
||||
}
|
||||
|
||||
protected override ID2D1Image? CreateEffect(IGraphicsDevicesAndContext devices)
|
||||
{
|
||||
var scheduler = ComputeExternalQueueScheduler.Create();
|
||||
var interopProvider = WaveOpticsInteropProvider.TryCreate(devices, scheduler, out var interopDevice);
|
||||
if (interopProvider is null || interopDevice is null)
|
||||
{
|
||||
scheduler.Dispose();
|
||||
return null;
|
||||
}
|
||||
|
||||
_scheduler = scheduler;
|
||||
|
||||
try
|
||||
{
|
||||
_interopProvider = interopProvider;
|
||||
_interopDomain = interopDevice.RegisterExternalDomain(interopProvider);
|
||||
_resourceSet = WaveOpticsResourceSet.Create(interopDevice, _interopDomain);
|
||||
_pipeline = WaveOpticsPipeline.TryCreate(interopDevice);
|
||||
}
|
||||
catch (Win32Exception)
|
||||
{
|
||||
ReleaseInterop();
|
||||
return null;
|
||||
}
|
||||
catch
|
||||
{
|
||||
ReleaseInterop();
|
||||
throw;
|
||||
}
|
||||
|
||||
if (_pipeline is null)
|
||||
{
|
||||
ReleaseInterop();
|
||||
return null;
|
||||
}
|
||||
|
||||
WaveOpticsCustomEffect? effect = null;
|
||||
Crop? outputCrop = null;
|
||||
ID2D1Image? outputCropOutput = null;
|
||||
@@ -306,7 +449,6 @@ internal sealed class WaveOpticsEffectProcessor : VideoEffectProcessorBase
|
||||
if (!effect.IsEnabled)
|
||||
{
|
||||
effect.Dispose();
|
||||
ReleaseInterop();
|
||||
return null;
|
||||
}
|
||||
outputCrop = new Crop(devices.DeviceContext);
|
||||
@@ -339,7 +481,6 @@ internal sealed class WaveOpticsEffectProcessor : VideoEffectProcessorBase
|
||||
outputCropOutput?.Dispose();
|
||||
outputCrop?.Dispose();
|
||||
effect?.Dispose();
|
||||
ReleaseInterop();
|
||||
throw;
|
||||
}
|
||||
}
|
||||
@@ -374,6 +515,7 @@ internal sealed class WaveOpticsEffectProcessor : VideoEffectProcessorBase
|
||||
_hasOutputOffset = false;
|
||||
_hasCropRect = false;
|
||||
_hasRenderState = false;
|
||||
_outputKind = OutputKind.None;
|
||||
}
|
||||
|
||||
protected override void Dispose(bool disposing)
|
||||
@@ -384,6 +526,7 @@ internal sealed class WaveOpticsEffectProcessor : VideoEffectProcessorBase
|
||||
{
|
||||
ClearEffectChain();
|
||||
ReleaseInterop();
|
||||
ReleaseCpu();
|
||||
}
|
||||
}
|
||||
catch (Exception exception)
|
||||
@@ -397,6 +540,29 @@ internal sealed class WaveOpticsEffectProcessor : VideoEffectProcessorBase
|
||||
}
|
||||
}
|
||||
|
||||
private enum OutputKind
|
||||
{
|
||||
None,
|
||||
Gpu,
|
||||
Cpu,
|
||||
}
|
||||
|
||||
private enum FrameOutcome
|
||||
{
|
||||
Rendered,
|
||||
PassThrough,
|
||||
Fallback,
|
||||
}
|
||||
|
||||
private readonly record struct FrameGeometry(
|
||||
float Left,
|
||||
float Top,
|
||||
int ItemWidth,
|
||||
int ItemHeight,
|
||||
int Margin,
|
||||
int CanvasWidth,
|
||||
int CanvasHeight);
|
||||
|
||||
private readonly record struct RenderState(
|
||||
float Gain,
|
||||
WaveOpticsPipeline.PixelRect Rect);
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
using WaveOptics.Fourier;
|
||||
using SpectralConvolution;
|
||||
|
||||
namespace WaveOptics.Optics;
|
||||
|
||||
|
||||
@@ -3,8 +3,8 @@ using System.Diagnostics.CodeAnalysis;
|
||||
using System.Numerics;
|
||||
using System.Runtime.CompilerServices;
|
||||
using System.Runtime.InteropServices;
|
||||
using SpectralConvolution;
|
||||
using WaveOptics.Abstractions;
|
||||
using WaveOptics.Fourier;
|
||||
|
||||
namespace WaveOptics.Optics;
|
||||
|
||||
|
||||
@@ -1,201 +0,0 @@
|
||||
using System.Numerics;
|
||||
|
||||
namespace WaveOptics.Optics;
|
||||
|
||||
internal sealed class SeparableKernel
|
||||
{
|
||||
readonly Comparison<int> descending;
|
||||
double[] work = [];
|
||||
double[] basis = [];
|
||||
double[] singularValues = [];
|
||||
int[] order = [];
|
||||
float[] horizontal = [];
|
||||
float[] vertical = [];
|
||||
|
||||
public SeparableKernel()
|
||||
{
|
||||
descending = (left, right) => singularValues[right].CompareTo(singularValues[left]);
|
||||
}
|
||||
|
||||
public int Size { get; private set; }
|
||||
public int Rank { get; private set; }
|
||||
public double ResidualEnergyRatio { get; private set; }
|
||||
public double Sum { get; private set; }
|
||||
public ReadOnlySpan<float> Horizontal => horizontal.AsSpan(0, Rank * Size);
|
||||
public ReadOnlySpan<float> Vertical => vertical.AsSpan(0, Rank * Size);
|
||||
|
||||
public static SeparableKernel Decompose(ReadOnlySpan<double> kernel, int size, double residualEnergyRatio, int maximumRank)
|
||||
{
|
||||
var separable = new SeparableKernel();
|
||||
separable.Update(kernel, size, residualEnergyRatio, maximumRank);
|
||||
return separable;
|
||||
}
|
||||
|
||||
public void Update(ReadOnlySpan<double> kernel, int size, double residualEnergyRatio, int maximumRank)
|
||||
{
|
||||
var area = size * size;
|
||||
if (work.Length < area)
|
||||
{
|
||||
work = new double[area];
|
||||
basis = new double[area];
|
||||
horizontal = new float[area];
|
||||
vertical = new float[area];
|
||||
}
|
||||
if (order.Length != size)
|
||||
{
|
||||
singularValues = new double[size];
|
||||
order = new int[size];
|
||||
}
|
||||
|
||||
for (var row = 0; row < size; row++)
|
||||
{
|
||||
for (var column = 0; column < size; column++)
|
||||
work[column * size + row] = kernel[row * size + column];
|
||||
}
|
||||
Array.Clear(basis, 0, area);
|
||||
for (var i = 0; i < size; i++)
|
||||
basis[i * size + i] = 1d;
|
||||
|
||||
OrthogonalizeColumns(work, basis, size);
|
||||
|
||||
var totalEnergy = 0d;
|
||||
for (var column = 0; column < size; column++)
|
||||
{
|
||||
var norm = 0d;
|
||||
for (var row = 0; row < size; row++)
|
||||
{
|
||||
var value = work[column * size + row];
|
||||
norm += value * value;
|
||||
}
|
||||
singularValues[column] = Math.Sqrt(norm);
|
||||
order[column] = column;
|
||||
totalEnergy += norm;
|
||||
}
|
||||
|
||||
Array.Sort(order, descending);
|
||||
|
||||
var largest = singularValues[order[0]];
|
||||
var significant = 0;
|
||||
var threshold = largest * 1e-12;
|
||||
for (var i = 0; i < size && singularValues[order[i]] > threshold; i++)
|
||||
significant++;
|
||||
significant = Math.Max(significant, 1);
|
||||
|
||||
var rank = significant;
|
||||
if (residualEnergyRatio > 0 && totalEnergy > 0)
|
||||
{
|
||||
var retained = 0d;
|
||||
var target = (1d - residualEnergyRatio) * totalEnergy;
|
||||
rank = 0;
|
||||
for (var i = 0; i < significant; i++)
|
||||
{
|
||||
retained += singularValues[order[i]] * singularValues[order[i]];
|
||||
rank++;
|
||||
if (retained >= target)
|
||||
break;
|
||||
}
|
||||
}
|
||||
rank = Math.Clamp(rank, 1, Math.Min(maximumRank, significant));
|
||||
|
||||
var retainedEnergy = 0d;
|
||||
for (var i = 0; i < rank; i++)
|
||||
retainedEnergy += singularValues[order[i]] * singularValues[order[i]];
|
||||
var residual = totalEnergy > 0 ? Math.Max(0d, (totalEnergy - retainedEnergy) / totalEnergy) : 0d;
|
||||
|
||||
var sum = 0d;
|
||||
for (var term = 0; term < rank; term++)
|
||||
{
|
||||
var column = order[term];
|
||||
var singularValue = singularValues[column];
|
||||
var inverse = singularValue > 0 ? 1d / singularValue : 0d;
|
||||
var horizontalBase = term * size;
|
||||
var horizontalSum = 0d;
|
||||
var verticalSum = 0d;
|
||||
for (var k = 0; k < size; k++)
|
||||
{
|
||||
horizontal[horizontalBase + k] = (float)(basis[column * size + k]);
|
||||
vertical[horizontalBase + k] = (float)(work[column * size + k] * inverse * singularValue);
|
||||
horizontalSum += horizontal[horizontalBase + k];
|
||||
verticalSum += vertical[horizontalBase + k];
|
||||
}
|
||||
sum += horizontalSum * verticalSum;
|
||||
}
|
||||
|
||||
Size = size;
|
||||
Rank = rank;
|
||||
ResidualEnergyRatio = residual;
|
||||
Sum = sum;
|
||||
}
|
||||
|
||||
static void OrthogonalizeColumns(double[] work, double[] basis, int size)
|
||||
{
|
||||
const int maximumSweeps = 60;
|
||||
const double tolerance = 1e-15;
|
||||
for (var sweep = 0; sweep < maximumSweeps; sweep++)
|
||||
{
|
||||
var converged = true;
|
||||
for (var p = 0; p < size - 1; p++)
|
||||
{
|
||||
var workP = work.AsSpan(p * size, size);
|
||||
var basisP = basis.AsSpan(p * size, size);
|
||||
for (var q = p + 1; q < size; q++)
|
||||
{
|
||||
var workQ = work.AsSpan(q * size, size);
|
||||
var alpha = 0d;
|
||||
var beta = 0d;
|
||||
var gamma = 0d;
|
||||
for (var k = 0; k < size; k++)
|
||||
{
|
||||
var wp = workP[k];
|
||||
var wq = workQ[k];
|
||||
alpha += wp * wp;
|
||||
beta += wq * wq;
|
||||
gamma += wp * wq;
|
||||
}
|
||||
|
||||
if (Math.Abs(gamma) <= tolerance * Math.Sqrt(alpha * beta))
|
||||
continue;
|
||||
|
||||
converged = false;
|
||||
var zeta = (beta - alpha) / (2d * gamma);
|
||||
var t = Math.Sign(zeta) / (Math.Abs(zeta) + Math.Sqrt(1d + zeta * zeta));
|
||||
if (zeta == 0d)
|
||||
t = 1d;
|
||||
var c = 1d / Math.Sqrt(1d + t * t);
|
||||
var s = c * t;
|
||||
|
||||
var basisQ = basis.AsSpan(q * size, size);
|
||||
Rotate(workP, workQ, c, s);
|
||||
Rotate(basisP, basisQ, c, s);
|
||||
}
|
||||
}
|
||||
if (converged)
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
static void Rotate(Span<double> first, Span<double> second, double c, double s)
|
||||
{
|
||||
var index = 0;
|
||||
var width = Vector<double>.Count;
|
||||
if (Vector.IsHardwareAccelerated && first.Length >= width)
|
||||
{
|
||||
var cosine = new Vector<double>(c);
|
||||
var sine = new Vector<double>(s);
|
||||
for (; index + width <= first.Length; index += width)
|
||||
{
|
||||
var a = new Vector<double>(first[index..]);
|
||||
var b = new Vector<double>(second[index..]);
|
||||
(cosine * a - sine * b).CopyTo(first[index..]);
|
||||
(sine * a + cosine * b).CopyTo(second[index..]);
|
||||
}
|
||||
}
|
||||
for (; index < first.Length; index++)
|
||||
{
|
||||
var a = first[index];
|
||||
var b = second[index];
|
||||
first[index] = c * a - s * b;
|
||||
second[index] = s * a + c * b;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,60 @@
|
||||
using ComputeGuard;
|
||||
using ComputeWeave;
|
||||
using SpectralConvolution;
|
||||
using Vortice.Direct3D11;
|
||||
using YukkuriMovieMaker.Commons;
|
||||
|
||||
namespace WaveOptics.Rendering;
|
||||
|
||||
internal static class WaveOpticsCompute
|
||||
{
|
||||
private const int ColorBytes = 4;
|
||||
private const int StoredBytes = 16;
|
||||
|
||||
public static ComputeGuardian Guardian { get; } = new(new ComputeGuardianOptions { Report = WaveOpticsTelemetry.Report });
|
||||
|
||||
public static ComputeDevice DescribeDevice(IGraphicsDevicesAndContext devices)
|
||||
{
|
||||
var options = devices.D3D.Device.CheckFeatureOptions2();
|
||||
return ComputeDevice.FromAdapter(devices.DXGI.Adapter, options.UnifiedMemoryArchitecture);
|
||||
}
|
||||
|
||||
public static ComputeWorkload Workload(int canvasWidth, int canvasHeight, int kernelRadius)
|
||||
=> new(canvasWidth, canvasHeight, GpuMemoryBytes(canvasWidth, canvasHeight, kernelRadius));
|
||||
|
||||
public static long GpuMemoryBytes(int canvasWidth, int canvasHeight, int kernelRadius)
|
||||
{
|
||||
var plan = TilePlan.Create(kernelRadius, 0, 0, canvasWidth, canvasHeight);
|
||||
var pixels = (long)canvasWidth * canvasHeight;
|
||||
var kernelArea = (kernelRadius * 2 + 1) * (kernelRadius * 2 + 1);
|
||||
var layout = new GpuTileLayout(plan.GroupCount, GpuTileConvolver.MaximumSamples, kernelArea);
|
||||
return pixels * (ColorBytes * 2 + StoredBytes)
|
||||
+ (long)plan.BatchTiles * plan.TileElements * TilePlan.ElementBytes
|
||||
+ (long)plan.TileElements * sizeof(float) * 2
|
||||
+ (long)plan.Size / 2 * sizeof(float) * 2
|
||||
+ (long)layout.Length * sizeof(uint) * 2
|
||||
+ WaveOpticsSettings.ScratchLength * sizeof(int) * 2;
|
||||
}
|
||||
|
||||
public static ComputeFailure Classify(Exception exception, bool deviceLost)
|
||||
{
|
||||
if (deviceLost)
|
||||
return ComputeFailure.DeviceLost;
|
||||
return exception is GraphicsMemoryAllocationException or OutOfMemoryException
|
||||
? ComputeFailure.ResourceExhausted
|
||||
: ComputeFailure.UnexpectedException;
|
||||
}
|
||||
|
||||
public static ComputeCheck ToCheck(in ConvolutionMeasurement measurement)
|
||||
=> new(measurement.Name, measurement.Measured, measurement.Reference, new ComputeTolerance(measurement.Tolerance / ComputeErrorModel.UnitInLastPlace, 1d, 0));
|
||||
|
||||
public static IReadOnlyList<ComputeCheck> SelfTest(GraphicsDevice device)
|
||||
{
|
||||
var measurements = new ConvolutionMeasurement[SpectralSelfTest.MeasurementCount];
|
||||
var count = SpectralSelfTest.Run(device, WaveOpticsSettings.MaximumKernelRadius, measurements);
|
||||
var checks = new ComputeCheck[count];
|
||||
for (var index = 0; index < count; index++)
|
||||
checks[index] = ToCheck(measurements[index]);
|
||||
return checks;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,137 @@
|
||||
using System.Runtime.InteropServices;
|
||||
using SpectralConvolution;
|
||||
|
||||
namespace WaveOptics.Rendering;
|
||||
|
||||
internal sealed class WaveOpticsCpuPipeline : IDisposable
|
||||
{
|
||||
private const int Channels = 4;
|
||||
|
||||
private readonly CpuTileConvolver _convolver;
|
||||
private readonly WaveOpticsKernel _kernel = new();
|
||||
private readonly WaveOpticsRenderTracker _tracker = new();
|
||||
private WaveOpticsConvolutionKey? _convolutionKey;
|
||||
private WaveOpticsSourceHash _sourceHash = WaveOpticsSourceHash.Empty;
|
||||
private WaveOpticsPipeline.PixelRect _sourceRect;
|
||||
private int _canvasWidth;
|
||||
private int _canvasHeight;
|
||||
private byte[] _source = [];
|
||||
private byte[] _packed = [];
|
||||
private byte[] _output = [];
|
||||
private float[] _store = [];
|
||||
|
||||
public WaveOpticsCpuPipeline()
|
||||
: this(Environment.ProcessorCount)
|
||||
{
|
||||
}
|
||||
|
||||
public WaveOpticsCpuPipeline(int threads)
|
||||
{
|
||||
_convolver = new CpuTileConvolver(threads);
|
||||
}
|
||||
|
||||
public bool HasKernel => _kernel.IsValid;
|
||||
|
||||
public bool HasStore => _tracker.HasStore;
|
||||
|
||||
public WaveOpticsSourceHash SourceHash => _sourceHash;
|
||||
|
||||
public void Process(ReadOnlySpan<int> source, Span<int> destination, int width, int height, in WaveOpticsPipeline.Parameters parameters)
|
||||
{
|
||||
var length = checked(width * height * Channels);
|
||||
if (!_kernel.TryUpdate(parameters.Psf))
|
||||
throw new InvalidOperationException();
|
||||
if (_packed.Length < length)
|
||||
_packed = new byte[length];
|
||||
if (_output.Length < length)
|
||||
_output = new byte[length];
|
||||
MemoryMarshal.AsBytes(source[..(width * height)]).CopyTo(_packed);
|
||||
var plan = TilePlan.Create(_kernel.Spectrum.Size, _kernel.Spectrum.Radius, 0, 0, width, height);
|
||||
_convolver.Convolve(_packed, 0, 0, width, height, _kernel.Spectrum, plan, _output, parameters.Gain, null);
|
||||
_output.AsSpan(0, length).CopyTo(MemoryMarshal.AsBytes(destination[..(width * height)]));
|
||||
}
|
||||
|
||||
public bool Simulate(
|
||||
byte[] source,
|
||||
int canvasWidth,
|
||||
int canvasHeight,
|
||||
int sourceOffsetX,
|
||||
int sourceOffsetY,
|
||||
int sourceWidth,
|
||||
int sourceHeight,
|
||||
in WaveOpticsPipeline.Parameters parameters)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(source);
|
||||
if (_canvasWidth != canvasWidth || _canvasHeight != canvasHeight)
|
||||
{
|
||||
_canvasWidth = canvasWidth;
|
||||
_canvasHeight = canvasHeight;
|
||||
_convolutionKey = null;
|
||||
if (_tracker.Reset())
|
||||
_store = [];
|
||||
}
|
||||
|
||||
_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));
|
||||
if (_convolutionKey == key || !TryGetVisibleBounds(canvasWidth, canvasHeight, in parameters, out _))
|
||||
return false;
|
||||
|
||||
if (!_kernel.TryUpdate(parameters.Psf))
|
||||
{
|
||||
_convolutionKey = null;
|
||||
return false;
|
||||
}
|
||||
|
||||
_convolutionKey = key;
|
||||
_sourceRect = sourceRect;
|
||||
return true;
|
||||
}
|
||||
|
||||
public bool TryGetVisibleBounds(int canvasWidth, int canvasHeight, in WaveOpticsPipeline.Parameters parameters, out WaveOpticsPipeline.PixelRect rect)
|
||||
=> _sourceHash.TryGetVisibleBounds(canvasWidth, canvasHeight, parameters.Psf.KernelRadius, out rect);
|
||||
|
||||
public ReadOnlySpan<byte> RenderVisible(WaveOpticsPipeline.PixelRect rect, in WaveOpticsPipeline.Parameters parameters)
|
||||
{
|
||||
if (_convolutionKey is not { } key || !_kernel.IsValid)
|
||||
throw new InvalidOperationException();
|
||||
|
||||
var mode = _tracker.Next(key, rect, parameters.Gain, out var releaseStore);
|
||||
if (releaseStore)
|
||||
_store = [];
|
||||
|
||||
var length = checked(rect.Width * rect.Height * Channels);
|
||||
if (_output.Length < length)
|
||||
_output = new byte[length];
|
||||
|
||||
if (mode == WaveOpticsRenderMode.Stored)
|
||||
{
|
||||
_convolver.RenderStored(_store, rect.Width * rect.Height, parameters.Gain, _output);
|
||||
return _output.AsSpan(0, length);
|
||||
}
|
||||
|
||||
float[]? store = null;
|
||||
if (mode == WaveOpticsRenderMode.ConvolveAndStore)
|
||||
{
|
||||
if (_store.Length < length)
|
||||
_store = new float[length];
|
||||
store = _store;
|
||||
}
|
||||
|
||||
var plan = TilePlan.Create(_kernel.Spectrum.Size, _kernel.Spectrum.Radius, rect.X, rect.Y, rect.Width, rect.Height);
|
||||
_convolver.Convolve(_source, _sourceRect.X, _sourceRect.Y, _sourceRect.Width, _sourceRect.Height, _kernel.Spectrum, plan, _output, parameters.Gain, store);
|
||||
return _output.AsSpan(0, length);
|
||||
}
|
||||
|
||||
public void Dispose()
|
||||
{
|
||||
_convolver.Dispose();
|
||||
_source = [];
|
||||
_packed = [];
|
||||
_output = [];
|
||||
_store = [];
|
||||
_convolutionKey = null;
|
||||
_tracker.Reset();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,113 @@
|
||||
using System.Numerics;
|
||||
using Vortice.DCommon;
|
||||
using Vortice.Direct2D1;
|
||||
using Vortice.Mathematics;
|
||||
|
||||
namespace WaveOptics.Rendering;
|
||||
|
||||
internal sealed class WaveOpticsCpuSurface : IDisposable
|
||||
{
|
||||
private const int Channels = 4;
|
||||
private const float Dpi = 96f;
|
||||
|
||||
private static readonly PixelFormat SurfaceFormat = new(Vortice.DXGI.Format.B8G8R8A8_UNorm, AlphaMode.Premultiplied);
|
||||
|
||||
private readonly ID2D1DeviceContext _context;
|
||||
private ID2D1Bitmap1? _target;
|
||||
private ID2D1Bitmap1? _readBack;
|
||||
private ID2D1Bitmap1? _output;
|
||||
private int _sourceWidth;
|
||||
private int _sourceHeight;
|
||||
private int _outputWidth;
|
||||
private int _outputHeight;
|
||||
private byte[] _pixels = [];
|
||||
|
||||
public WaveOpticsCpuSurface(ID2D1Device device)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(device);
|
||||
_context = device.CreateDeviceContext(DeviceContextOptions.EnableMultithreadedOptimizations);
|
||||
}
|
||||
|
||||
public ID2D1Bitmap1? Output => _output;
|
||||
|
||||
public byte[] Read(ID2D1Image input, Vector2 offset, int width, int height)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(input);
|
||||
var (target, readBack) = EnsureSource(width, height);
|
||||
|
||||
var previousTarget = _context.Target;
|
||||
_context.Target = target;
|
||||
_context.BeginDraw();
|
||||
_context.Clear(null);
|
||||
_context.DrawImage(input, offset, null, InterpolationMode.NearestNeighbor, CompositeMode.SourceCopy);
|
||||
_context.EndDraw();
|
||||
_context.Target = previousTarget;
|
||||
|
||||
readBack.CopyFromBitmap(target);
|
||||
var mapped = readBack.Map(MapOptions.Read);
|
||||
try
|
||||
{
|
||||
var stride = width * Channels;
|
||||
for (var y = 0; y < height; y++)
|
||||
CopyRow(mapped.Bits + y * mapped.Pitch, _pixels.AsSpan(y * stride, stride));
|
||||
}
|
||||
finally
|
||||
{
|
||||
readBack.Unmap();
|
||||
}
|
||||
|
||||
return _pixels;
|
||||
}
|
||||
|
||||
public ID2D1Bitmap1 Write(ReadOnlySpan<byte> pixels, int width, int height, out bool changed)
|
||||
{
|
||||
changed = false;
|
||||
if (_output is null || _outputWidth < width || _outputHeight < height)
|
||||
{
|
||||
_output?.Dispose();
|
||||
_output = null;
|
||||
_output = _context.CreateBitmap(new SizeI(width, height), new BitmapProperties1(SurfaceFormat, Dpi, Dpi, BitmapOptions.None));
|
||||
_outputWidth = width;
|
||||
_outputHeight = height;
|
||||
changed = true;
|
||||
}
|
||||
|
||||
_output.CopyFromMemory(new RectI(0, 0, width, height), pixels, width * Channels);
|
||||
return _output;
|
||||
}
|
||||
|
||||
public void Dispose()
|
||||
{
|
||||
_target?.Dispose();
|
||||
_readBack?.Dispose();
|
||||
_output?.Dispose();
|
||||
_target = null;
|
||||
_readBack = null;
|
||||
_output = null;
|
||||
_context.Dispose();
|
||||
}
|
||||
|
||||
private (ID2D1Bitmap1 Target, ID2D1Bitmap1 ReadBack) EnsureSource(int width, int height)
|
||||
{
|
||||
if (_target is { } currentTarget && _readBack is { } currentReadBack && _sourceWidth == width && _sourceHeight == height)
|
||||
return (currentTarget, currentReadBack);
|
||||
|
||||
_target?.Dispose();
|
||||
_readBack?.Dispose();
|
||||
_target = null;
|
||||
_readBack = null;
|
||||
var size = new SizeI(width, height);
|
||||
var target = _context.CreateBitmap(size, new BitmapProperties1(SurfaceFormat, Dpi, Dpi, BitmapOptions.Target));
|
||||
_target = target;
|
||||
var readBack = _context.CreateBitmap(size, new BitmapProperties1(SurfaceFormat, Dpi, Dpi, BitmapOptions.CpuRead | BitmapOptions.CannotDraw));
|
||||
_readBack = readBack;
|
||||
if (_pixels.Length < width * height * Channels)
|
||||
_pixels = new byte[width * height * Channels];
|
||||
_sourceWidth = width;
|
||||
_sourceHeight = height;
|
||||
return (target, readBack);
|
||||
}
|
||||
|
||||
private static unsafe void CopyRow(nint source, Span<byte> destination)
|
||||
=> new ReadOnlySpan<byte>((void*)source, destination.Length).CopyTo(destination);
|
||||
}
|
||||
@@ -105,287 +105,3 @@ internal readonly partial struct SourceHashShader(
|
||||
Hlsl.InterlockedMax(ref scratch[WaveOpticsSettings.ScratchBoundsMaxY], sourceY + y);
|
||||
}
|
||||
}
|
||||
|
||||
[ThreadGroupSize(DefaultThreadGroupSizes.XY)]
|
||||
[GeneratedComputeShaderDescriptor]
|
||||
internal readonly partial struct HorizontalPassShader(
|
||||
ReadWriteTexture2D<Bgra32, Float4> source,
|
||||
ReadOnlyBuffer<float> weights,
|
||||
ReadWriteBuffer<Float4> horizontal,
|
||||
int weightOffset,
|
||||
int radius,
|
||||
int regionX,
|
||||
int regionY,
|
||||
int regionWidth,
|
||||
int regionHeight,
|
||||
int canvasWidth,
|
||||
int sourceX,
|
||||
int sourceY,
|
||||
int sourceWidth) : IComputeShader
|
||||
{
|
||||
private readonly ReadWriteTexture2D<Bgra32, Float4> source = source;
|
||||
private readonly ReadOnlyBuffer<float> weights = weights;
|
||||
private readonly ReadWriteBuffer<Float4> horizontal = horizontal;
|
||||
private readonly int weightOffset = weightOffset;
|
||||
private readonly int radius = radius;
|
||||
private readonly int regionX = regionX;
|
||||
private readonly int regionY = regionY;
|
||||
private readonly int regionWidth = regionWidth;
|
||||
private readonly int regionHeight = regionHeight;
|
||||
private readonly int canvasWidth = canvasWidth;
|
||||
private readonly int sourceX = sourceX;
|
||||
private readonly int sourceY = sourceY;
|
||||
private readonly int sourceWidth = sourceWidth;
|
||||
|
||||
public void Execute()
|
||||
{
|
||||
var offsetX = ThreadIds.X * WaveOpticsSettings.HorizontalConvolutionBlock;
|
||||
if (offsetX >= regionWidth || ThreadIds.Y >= regionHeight)
|
||||
return;
|
||||
|
||||
var x = regionX + offsetX;
|
||||
var y = regionY + ThreadIds.Y;
|
||||
var column = x - sourceX;
|
||||
var row = y - sourceY;
|
||||
var first = Hlsl.Max(-radius, -column);
|
||||
var last = Hlsl.Min(radius + WaveOpticsSettings.HorizontalConvolutionBlock - 1, sourceWidth - 1 - column);
|
||||
var weight0 = Weight(first - 1);
|
||||
var weight1 = Weight(first - 2);
|
||||
var weight2 = Weight(first - 3);
|
||||
var weight3 = Weight(first - 4);
|
||||
var weight4 = Weight(first - 5);
|
||||
var weight5 = Weight(first - 6);
|
||||
var weight6 = Weight(first - 7);
|
||||
var weight7 = Weight(first - 8);
|
||||
var weight8 = Weight(first - 9);
|
||||
var weight9 = Weight(first - 10);
|
||||
var weight10 = Weight(first - 11);
|
||||
var weight11 = Weight(first - 12);
|
||||
var weight12 = Weight(first - 13);
|
||||
var weight13 = Weight(first - 14);
|
||||
var weight14 = Weight(first - 15);
|
||||
var sum0 = new Float4(0f, 0f, 0f, 0f);
|
||||
var sum1 = sum0;
|
||||
var sum2 = sum0;
|
||||
var sum3 = sum0;
|
||||
var sum4 = sum0;
|
||||
var sum5 = sum0;
|
||||
var sum6 = sum0;
|
||||
var sum7 = sum0;
|
||||
var sum8 = sum0;
|
||||
var sum9 = sum0;
|
||||
var sum10 = sum0;
|
||||
var sum11 = sum0;
|
||||
var sum12 = sum0;
|
||||
var sum13 = sum0;
|
||||
var sum14 = sum0;
|
||||
var sum15 = sum0;
|
||||
for (var offset = first; offset <= last; offset++)
|
||||
{
|
||||
var weight15 = weight14;
|
||||
weight14 = weight13;
|
||||
weight13 = weight12;
|
||||
weight12 = weight11;
|
||||
weight11 = weight10;
|
||||
weight10 = weight9;
|
||||
weight9 = weight8;
|
||||
weight8 = weight7;
|
||||
weight7 = weight6;
|
||||
weight6 = weight5;
|
||||
weight5 = weight4;
|
||||
weight4 = weight3;
|
||||
weight3 = weight2;
|
||||
weight2 = weight1;
|
||||
weight1 = weight0;
|
||||
weight0 = Weight(offset);
|
||||
var texel = source[new Int2(column + offset, row)];
|
||||
sum0 += texel * weight0;
|
||||
sum1 += texel * weight1;
|
||||
sum2 += texel * weight2;
|
||||
sum3 += texel * weight3;
|
||||
sum4 += texel * weight4;
|
||||
sum5 += texel * weight5;
|
||||
sum6 += texel * weight6;
|
||||
sum7 += texel * weight7;
|
||||
sum8 += texel * weight8;
|
||||
sum9 += texel * weight9;
|
||||
sum10 += texel * weight10;
|
||||
sum11 += texel * weight11;
|
||||
sum12 += texel * weight12;
|
||||
sum13 += texel * weight13;
|
||||
sum14 += texel * weight14;
|
||||
sum15 += texel * weight15;
|
||||
}
|
||||
|
||||
var index = y * canvasWidth + x;
|
||||
horizontal[index] = sum0;
|
||||
if (offsetX + 1 < regionWidth)
|
||||
horizontal[index + 1] = sum1;
|
||||
if (offsetX + 2 < regionWidth)
|
||||
horizontal[index + 2] = sum2;
|
||||
if (offsetX + 3 < regionWidth)
|
||||
horizontal[index + 3] = sum3;
|
||||
if (offsetX + 4 < regionWidth)
|
||||
horizontal[index + 4] = sum4;
|
||||
if (offsetX + 5 < regionWidth)
|
||||
horizontal[index + 5] = sum5;
|
||||
if (offsetX + 6 < regionWidth)
|
||||
horizontal[index + 6] = sum6;
|
||||
if (offsetX + 7 < regionWidth)
|
||||
horizontal[index + 7] = sum7;
|
||||
if (offsetX + 8 < regionWidth)
|
||||
horizontal[index + 8] = sum8;
|
||||
if (offsetX + 9 < regionWidth)
|
||||
horizontal[index + 9] = sum9;
|
||||
if (offsetX + 10 < regionWidth)
|
||||
horizontal[index + 10] = sum10;
|
||||
if (offsetX + 11 < regionWidth)
|
||||
horizontal[index + 11] = sum11;
|
||||
if (offsetX + 12 < regionWidth)
|
||||
horizontal[index + 12] = sum12;
|
||||
if (offsetX + 13 < regionWidth)
|
||||
horizontal[index + 13] = sum13;
|
||||
if (offsetX + 14 < regionWidth)
|
||||
horizontal[index + 14] = sum14;
|
||||
if (offsetX + 15 < regionWidth)
|
||||
horizontal[index + 15] = sum15;
|
||||
}
|
||||
|
||||
private float Weight(int offset)
|
||||
=> offset >= -radius && offset <= radius ? weights[weightOffset + radius + offset] : 0f;
|
||||
}
|
||||
|
||||
[ThreadGroupSize(DefaultThreadGroupSizes.XY)]
|
||||
[GeneratedComputeShaderDescriptor]
|
||||
internal readonly partial struct VerticalPassShader(
|
||||
ReadWriteBuffer<Float4> horizontal,
|
||||
ReadOnlyBuffer<float> weights,
|
||||
ReadWriteBuffer<Float4> convolved,
|
||||
int weightOffset,
|
||||
int radius,
|
||||
int rectX,
|
||||
int rectY,
|
||||
int rectWidth,
|
||||
int rectHeight,
|
||||
int canvasWidth,
|
||||
int sourceY,
|
||||
int sourceHeight,
|
||||
bool accumulate) : IComputeShader
|
||||
{
|
||||
private readonly ReadWriteBuffer<Float4> horizontal = horizontal;
|
||||
private readonly ReadOnlyBuffer<float> weights = weights;
|
||||
private readonly ReadWriteBuffer<Float4> convolved = convolved;
|
||||
private readonly int weightOffset = weightOffset;
|
||||
private readonly int radius = radius;
|
||||
private readonly int rectX = rectX;
|
||||
private readonly int rectY = rectY;
|
||||
private readonly int rectWidth = rectWidth;
|
||||
private readonly int rectHeight = rectHeight;
|
||||
private readonly int canvasWidth = canvasWidth;
|
||||
private readonly int sourceY = sourceY;
|
||||
private readonly int sourceHeight = sourceHeight;
|
||||
private readonly bool accumulate = accumulate;
|
||||
|
||||
public void Execute()
|
||||
{
|
||||
var offsetY = ThreadIds.Y * WaveOpticsSettings.VerticalConvolutionBlock;
|
||||
if (ThreadIds.X >= rectWidth || offsetY >= rectHeight)
|
||||
return;
|
||||
|
||||
var x = rectX + ThreadIds.X;
|
||||
var y = rectY + offsetY;
|
||||
var row = y - sourceY;
|
||||
var first = Hlsl.Max(-radius, -row);
|
||||
var last = Hlsl.Min(radius + WaveOpticsSettings.VerticalConvolutionBlock - 1, sourceHeight - 1 - row);
|
||||
var weight0 = Weight(first - 1);
|
||||
var weight1 = Weight(first - 2);
|
||||
var weight2 = Weight(first - 3);
|
||||
var weight3 = Weight(first - 4);
|
||||
var weight4 = Weight(first - 5);
|
||||
var weight5 = Weight(first - 6);
|
||||
var weight6 = Weight(first - 7);
|
||||
var sum0 = new Float4(0f, 0f, 0f, 0f);
|
||||
var sum1 = sum0;
|
||||
var sum2 = sum0;
|
||||
var sum3 = sum0;
|
||||
var sum4 = sum0;
|
||||
var sum5 = sum0;
|
||||
var sum6 = sum0;
|
||||
var sum7 = sum0;
|
||||
for (var offset = first; offset <= last; offset++)
|
||||
{
|
||||
var weight7 = weight6;
|
||||
weight6 = weight5;
|
||||
weight5 = weight4;
|
||||
weight4 = weight3;
|
||||
weight3 = weight2;
|
||||
weight2 = weight1;
|
||||
weight1 = weight0;
|
||||
weight0 = Weight(offset);
|
||||
var value = horizontal[(y + offset) * canvasWidth + x];
|
||||
sum0 += value * weight0;
|
||||
sum1 += value * weight1;
|
||||
sum2 += value * weight2;
|
||||
sum3 += value * weight3;
|
||||
sum4 += value * weight4;
|
||||
sum5 += value * weight5;
|
||||
sum6 += value * weight6;
|
||||
sum7 += value * weight7;
|
||||
}
|
||||
|
||||
var index = y * canvasWidth + x;
|
||||
Store(index, sum0);
|
||||
if (offsetY + 1 < rectHeight)
|
||||
Store(index + canvasWidth, sum1);
|
||||
if (offsetY + 2 < rectHeight)
|
||||
Store(index + canvasWidth * 2, sum2);
|
||||
if (offsetY + 3 < rectHeight)
|
||||
Store(index + canvasWidth * 3, sum3);
|
||||
if (offsetY + 4 < rectHeight)
|
||||
Store(index + canvasWidth * 4, sum4);
|
||||
if (offsetY + 5 < rectHeight)
|
||||
Store(index + canvasWidth * 5, sum5);
|
||||
if (offsetY + 6 < rectHeight)
|
||||
Store(index + canvasWidth * 6, sum6);
|
||||
if (offsetY + 7 < rectHeight)
|
||||
Store(index + canvasWidth * 7, sum7);
|
||||
}
|
||||
|
||||
private float Weight(int offset)
|
||||
=> offset >= -radius && offset <= radius ? weights[weightOffset + radius + offset] : 0f;
|
||||
|
||||
private void Store(int index, Float4 sum)
|
||||
{
|
||||
convolved[index] = accumulate ? convolved[index] + sum : sum;
|
||||
}
|
||||
}
|
||||
|
||||
[ThreadGroupSize(DefaultThreadGroupSizes.XY)]
|
||||
[GeneratedComputeShaderDescriptor]
|
||||
internal readonly partial struct RenderShader(
|
||||
ReadWriteBuffer<Float4> convolved,
|
||||
ReadWriteTexture2D<Bgra32, Float4> output,
|
||||
int rectX,
|
||||
int rectY,
|
||||
int rectWidth,
|
||||
int rectHeight,
|
||||
int canvasWidth,
|
||||
float gain) : IComputeShader
|
||||
{
|
||||
private readonly ReadWriteBuffer<Float4> convolved = convolved;
|
||||
private readonly ReadWriteTexture2D<Bgra32, Float4> output = output;
|
||||
private readonly int rectX = rectX;
|
||||
private readonly int rectY = rectY;
|
||||
private readonly int rectWidth = rectWidth;
|
||||
private readonly int rectHeight = rectHeight;
|
||||
private readonly int canvasWidth = canvasWidth;
|
||||
private readonly float gain = gain;
|
||||
|
||||
public void Execute()
|
||||
{
|
||||
if (ThreadIds.X >= rectWidth || ThreadIds.Y >= rectHeight)
|
||||
return;
|
||||
|
||||
output[ThreadIds.XY] = convolved[(rectY + ThreadIds.Y) * canvasWidth + rectX + ThreadIds.X] * gain;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,70 @@
|
||||
using SpectralConvolution;
|
||||
using WaveOptics.Abstractions;
|
||||
using WaveOptics.Effects;
|
||||
using WaveOptics.Optics;
|
||||
|
||||
namespace WaveOptics.Rendering;
|
||||
|
||||
internal sealed class WaveOpticsKernel
|
||||
{
|
||||
private readonly double[] _values = new double[WaveOpticsSettings.MaximumKernelSize * WaveOpticsSettings.MaximumKernelSize];
|
||||
private readonly FraunhoferKernelSampler _sampler = new();
|
||||
private readonly KernelSpectrum _spectrum = new();
|
||||
private WaveOpticsPipeline.PsfParameters? _key;
|
||||
private bool _isValid;
|
||||
private int _version;
|
||||
|
||||
public KernelSpectrum Spectrum => _spectrum;
|
||||
|
||||
public bool IsValid => _isValid;
|
||||
|
||||
public int Version => _version;
|
||||
|
||||
public bool TryUpdate(in WaveOpticsPipeline.PsfParameters psf)
|
||||
{
|
||||
var key = KeyOf(psf);
|
||||
if (_key == key)
|
||||
return _isValid;
|
||||
|
||||
_key = key;
|
||||
_isValid = false;
|
||||
_version++;
|
||||
var pupilGridSize = WaveOpticsSettings.GetPupilGridSize(psf.Quality);
|
||||
var aberration = new WavefrontAberration(
|
||||
defocusWaves: psf.Defocus,
|
||||
astigmatismVerticalWaves: psf.AstigmatismVertical,
|
||||
astigmatismObliqueWaves: psf.AstigmatismOblique,
|
||||
comaHorizontalWaves: psf.ComaHorizontal,
|
||||
comaVerticalWaves: psf.ComaVertical,
|
||||
sphericalWaves: psf.Spherical);
|
||||
var specification = new PsfSpecification(
|
||||
pupilGridSize,
|
||||
WaveOpticsSettings.GetPupilDiameterSamples(pupilGridSize),
|
||||
WaveOpticsSettings.GetKernelSize(psf.KernelRadius),
|
||||
psf.Wavelength,
|
||||
psf.FNumber,
|
||||
psf.PixelPitch,
|
||||
psf.ApertureShape == WaveOpticsApertureShape.Circular ? ApertureShape.Circular : ApertureShape.RegularPolygon,
|
||||
psf.BladeCount,
|
||||
psf.BladeRotation,
|
||||
psf.Obstruction,
|
||||
aberration);
|
||||
var size = specification.KernelSize;
|
||||
var values = _values.AsSpan(0, size * size);
|
||||
if (!_sampler.TrySample(in specification, values))
|
||||
return false;
|
||||
|
||||
var sum = 0d;
|
||||
foreach (var value in values)
|
||||
sum += value;
|
||||
if (!double.IsFinite(sum) || sum <= 0d)
|
||||
return false;
|
||||
|
||||
_spectrum.Update(values, psf.KernelRadius, TilePlan.SelectSize(psf.KernelRadius));
|
||||
_isValid = true;
|
||||
return true;
|
||||
}
|
||||
|
||||
public static WaveOpticsPipeline.PsfParameters KeyOf(in WaveOpticsPipeline.PsfParameters psf)
|
||||
=> psf.ApertureShape == WaveOpticsApertureShape.Circular ? psf with { BladeCount = 0, BladeRotation = 0f } : psf;
|
||||
}
|
||||
@@ -1,9 +1,9 @@
|
||||
using System.ComponentModel;
|
||||
using System.Runtime.InteropServices;
|
||||
using ComputeGuard;
|
||||
using ComputeWeave;
|
||||
using WaveOptics.Abstractions;
|
||||
using SpectralConvolution;
|
||||
using WaveOptics.Effects;
|
||||
using WaveOptics.Optics;
|
||||
|
||||
namespace WaveOptics.Rendering;
|
||||
|
||||
@@ -13,25 +13,22 @@ internal sealed class WaveOpticsPipeline : IDisposable
|
||||
private readonly WaveOpticsPipelineHost _host;
|
||||
private readonly ReadWriteBuffer<int> _scratch;
|
||||
private readonly ReadBackBuffer<int> _scratchReadBack;
|
||||
private readonly ReadOnlyBuffer<float> _weights;
|
||||
private readonly float[] _weightValues = new float[WaveOpticsSettings.WeightsLength];
|
||||
private readonly double[] _kernelValues = new double[WaveOpticsSettings.MaximumKernelSize * WaveOpticsSettings.MaximumKernelSize];
|
||||
private readonly FraunhoferKernelSampler _sampler = new();
|
||||
private readonly SeparableKernel _separable = new();
|
||||
private PsfParameters? _kernelPsf;
|
||||
private Kernel _kernel;
|
||||
private ConvolutionKey? _convolutionKey;
|
||||
private int _cachedLitCount;
|
||||
private int _cachedBoundsMinX;
|
||||
private int _cachedBoundsMinY;
|
||||
private int _cachedBoundsMaxX;
|
||||
private int _cachedBoundsMaxY;
|
||||
private readonly GpuTileConvolver _convolver;
|
||||
private readonly WaveOpticsKernel _kernel = new();
|
||||
private readonly WaveOpticsRenderTracker _tracker = new();
|
||||
private int _uploadedKernelVersion;
|
||||
private WaveOpticsConvolutionKey? _convolutionKey;
|
||||
private GpuTileJob _storedJob;
|
||||
private PixelRect _sourceRect;
|
||||
private WaveOpticsSourceHash _sourceHash = WaveOpticsSourceHash.Empty;
|
||||
private int _canvasWidth;
|
||||
private int _canvasHeight;
|
||||
private ReadWriteTexture2D<Bgra32, Float4>? _packedSource;
|
||||
private ReadWriteTexture2D<Bgra32, Float4>? _packedOutput;
|
||||
private int _packedWidth;
|
||||
private int _packedHeight;
|
||||
private Func<Float2[], Float2[]>? _spectrumTamper;
|
||||
private bool _deviceLost;
|
||||
|
||||
private WaveOpticsPipeline(GraphicsDevice device, WaveOpticsPipelineHost host)
|
||||
{
|
||||
@@ -39,7 +36,22 @@ internal sealed class WaveOpticsPipeline : IDisposable
|
||||
_host = host;
|
||||
_scratch = device.AllocateReadWriteBuffer<int>(WaveOpticsSettings.ScratchLength);
|
||||
_scratchReadBack = device.AllocateReadBackBuffer<int>(WaveOpticsSettings.ScratchLength);
|
||||
_weights = device.AllocateReadOnlyBuffer<float>(WaveOpticsSettings.WeightsLength);
|
||||
_convolver = new GpuTileConvolver(device);
|
||||
device.DeviceLost += OnDeviceLost;
|
||||
}
|
||||
|
||||
public static int MeasurementCount => GpuTileCheck.MeasurementCount(GpuTileConvolver.MaximumSamples);
|
||||
|
||||
internal bool IsDeviceLost => Volatile.Read(ref _deviceLost);
|
||||
|
||||
internal Func<Float2[], Float2[]>? SpectrumTamper
|
||||
{
|
||||
get => _spectrumTamper;
|
||||
set
|
||||
{
|
||||
_spectrumTamper = value;
|
||||
_uploadedKernelVersion = 0;
|
||||
}
|
||||
}
|
||||
|
||||
public static WaveOpticsPipeline? TryCreate()
|
||||
@@ -123,11 +135,7 @@ internal sealed class WaveOpticsPipeline : IDisposable
|
||||
{
|
||||
var sourceRect = BeginSimulate(canvasWidth, canvasHeight, sourceOffsetX, sourceOffsetY, sourceWidth, sourceHeight);
|
||||
_host.RecordSourceHash(source, _scratch, in sourceRect).Wait();
|
||||
if (!TryBeginConvolution(in sourceRect, in parameters, out var rect))
|
||||
return false;
|
||||
|
||||
_host.RecordConvolution(source, _weights, in sourceRect, in rect, _canvasWidth, in _kernel).Wait();
|
||||
return true;
|
||||
return TryBeginConvolution(in sourceRect, in parameters);
|
||||
}
|
||||
|
||||
internal bool Simulate(
|
||||
@@ -142,11 +150,7 @@ internal sealed class WaveOpticsPipeline : IDisposable
|
||||
{
|
||||
var sourceRect = BeginSimulate(canvasWidth, canvasHeight, sourceOffsetX, sourceOffsetY, sourceWidth, sourceHeight);
|
||||
_host.RecordSharedSourceHash(source, _scratch, in sourceRect).Wait();
|
||||
if (!TryBeginConvolution(in sourceRect, in parameters, out var rect))
|
||||
return false;
|
||||
|
||||
_host.RecordSharedConvolution(source, _weights, in sourceRect, in rect, _canvasWidth, in _kernel).Wait();
|
||||
return true;
|
||||
return TryBeginConvolution(in sourceRect, in parameters);
|
||||
}
|
||||
|
||||
private PixelRect BeginSimulate(int canvasWidth, int canvasHeight, int sourceOffsetX, int sourceOffsetY, int sourceWidth, int sourceHeight)
|
||||
@@ -155,70 +159,154 @@ internal sealed class WaveOpticsPipeline : IDisposable
|
||||
return new PixelRect(sourceOffsetX, sourceOffsetY, sourceWidth, sourceHeight);
|
||||
}
|
||||
|
||||
private bool TryBeginConvolution(in PixelRect sourceRect, in Parameters parameters, out PixelRect rect)
|
||||
private bool TryBeginConvolution(in PixelRect sourceRect, in Parameters parameters)
|
||||
{
|
||||
_scratchReadBack.CopyFrom(_scratch);
|
||||
var hashed = _scratchReadBack.Span;
|
||||
_cachedLitCount = hashed[WaveOpticsSettings.ScratchLitCount];
|
||||
_cachedBoundsMinX = hashed[WaveOpticsSettings.ScratchBoundsMinX];
|
||||
_cachedBoundsMinY = hashed[WaveOpticsSettings.ScratchBoundsMinY];
|
||||
_cachedBoundsMaxX = hashed[WaveOpticsSettings.ScratchBoundsMaxX];
|
||||
_cachedBoundsMaxY = hashed[WaveOpticsSettings.ScratchBoundsMaxY];
|
||||
_sourceHash = WaveOpticsSourceHash.FromScratch(_scratchReadBack.Span);
|
||||
|
||||
var key = new ConvolutionKey(
|
||||
hashed[WaveOpticsSettings.ScratchHashSum],
|
||||
hashed[WaveOpticsSettings.ScratchHashMix],
|
||||
var key = new WaveOpticsConvolutionKey(
|
||||
_sourceHash.Sum,
|
||||
_sourceHash.Mix,
|
||||
_canvasWidth,
|
||||
_canvasHeight,
|
||||
sourceRect,
|
||||
KernelKey(parameters.Psf));
|
||||
if (_convolutionKey == key || !TryGetVisibleBounds(_canvasWidth, _canvasHeight, in parameters, out rect))
|
||||
{
|
||||
rect = default;
|
||||
WaveOpticsKernel.KeyOf(parameters.Psf));
|
||||
if (_convolutionKey == key || !TryGetVisibleBounds(_canvasWidth, _canvasHeight, in parameters, out _))
|
||||
return false;
|
||||
}
|
||||
|
||||
if (!TryEnsureKernel(parameters.Psf))
|
||||
if (!_kernel.TryUpdate(parameters.Psf))
|
||||
{
|
||||
_convolutionKey = null;
|
||||
rect = default;
|
||||
return false;
|
||||
}
|
||||
|
||||
_convolutionKey = key;
|
||||
_sourceRect = sourceRect;
|
||||
return true;
|
||||
}
|
||||
|
||||
internal bool HasKernel => _kernel.Rank > 0;
|
||||
internal bool HasKernel => _kernel.IsValid;
|
||||
|
||||
internal WaveOpticsSourceHash SourceHash => _sourceHash;
|
||||
|
||||
internal bool TryGetVisibleBounds(int canvasWidth, int canvasHeight, in Parameters parameters, out PixelRect rect)
|
||||
=> _sourceHash.TryGetVisibleBounds(canvasWidth, canvasHeight, parameters.Psf.KernelRadius, out rect);
|
||||
|
||||
internal void RenderVisible(
|
||||
ReadWriteTexture2D<Bgra32, Float4> source,
|
||||
ReadWriteTexture2D<Bgra32, Float4> output,
|
||||
PixelRect rect,
|
||||
in Parameters parameters)
|
||||
=> RenderVisible(source, output, rect, in parameters, []);
|
||||
|
||||
internal int RenderVisible(
|
||||
ReadWriteTexture2D<Bgra32, Float4> source,
|
||||
ReadWriteTexture2D<Bgra32, Float4> output,
|
||||
PixelRect rect,
|
||||
in Parameters parameters,
|
||||
Span<ConvolutionMeasurement> measurements)
|
||||
{
|
||||
rect = default;
|
||||
if (_cachedLitCount <= 0 || _cachedBoundsMinX > _cachedBoundsMaxX)
|
||||
return false;
|
||||
var mode = BeginRender(rect, parameters.Gain);
|
||||
if (mode == WaveOpticsRenderMode.Stored)
|
||||
{
|
||||
_host.RecordStoredRender(_convolver.StoreFor(_storedJob), output, in rect, parameters.Gain).Wait();
|
||||
return 0;
|
||||
}
|
||||
|
||||
var radius = parameters.Psf.KernelRadius;
|
||||
var left = Math.Clamp((_cachedBoundsMinX - radius) & ~3, 0, canvasWidth);
|
||||
var top = Math.Clamp((_cachedBoundsMinY - radius) & ~3, 0, canvasHeight);
|
||||
var right = Math.Clamp(_cachedBoundsMaxX + 1 + radius, 0, canvasWidth);
|
||||
var bottom = Math.Clamp(_cachedBoundsMaxY + 1 + radius, 0, canvasHeight);
|
||||
var width = Math.Min((right - left + 3) & ~3, canvasWidth - left);
|
||||
var height = Math.Min((bottom - top + 3) & ~3, canvasHeight - top);
|
||||
if (width <= 0 || height <= 0)
|
||||
return false;
|
||||
|
||||
rect = new PixelRect(left, top, width, height);
|
||||
return true;
|
||||
Span<Int2> samples = stackalloc Int2[GpuTileConvolver.MaximumSamples];
|
||||
var job = PrepareConvolution(rect, parameters.Gain, mode == WaveOpticsRenderMode.ConvolveAndStore, measurements.IsEmpty ? [] : samples);
|
||||
_host.RecordConvolution(
|
||||
source, output, _convolver.Tiles, _convolver.Twiddles, _convolver.Spectrum,
|
||||
_convolver.Report, _convolver.Samples, _convolver.StoreFor(job), in job).Wait();
|
||||
return Measure(in job, samples[..job.SampleCount], measurements);
|
||||
}
|
||||
|
||||
internal void RenderVisible(ReadWriteTexture2D<Bgra32, Float4> output, PixelRect rect, in Parameters parameters)
|
||||
internal void RenderVisible(
|
||||
ComputeResourceBinding<ReadWriteTexture2D<Bgra32, Float4>> source,
|
||||
ComputeResourceBinding<ReadWriteTexture2D<Bgra32, Float4>> output,
|
||||
PixelRect rect,
|
||||
in Parameters parameters)
|
||||
=> RenderVisible(source, output, rect, in parameters, []);
|
||||
|
||||
internal int RenderVisible(
|
||||
ComputeResourceBinding<ReadWriteTexture2D<Bgra32, Float4>> source,
|
||||
ComputeResourceBinding<ReadWriteTexture2D<Bgra32, Float4>> output,
|
||||
PixelRect rect,
|
||||
in Parameters parameters,
|
||||
Span<ConvolutionMeasurement> measurements)
|
||||
{
|
||||
_host.RecordRender(output, in rect, _canvasWidth, parameters.Gain).Wait();
|
||||
var mode = BeginRender(rect, parameters.Gain);
|
||||
if (mode == WaveOpticsRenderMode.Stored)
|
||||
{
|
||||
_host.RecordSharedStoredRender(_convolver.StoreFor(_storedJob), output, in rect, parameters.Gain).Wait();
|
||||
return 0;
|
||||
}
|
||||
|
||||
Span<Int2> samples = stackalloc Int2[GpuTileConvolver.MaximumSamples];
|
||||
var job = PrepareConvolution(rect, parameters.Gain, mode == WaveOpticsRenderMode.ConvolveAndStore, measurements.IsEmpty ? [] : samples);
|
||||
_host.RecordSharedConvolution(
|
||||
source, output, _convolver.Tiles, _convolver.Twiddles, _convolver.Spectrum,
|
||||
_convolver.Report, _convolver.Samples, _convolver.StoreFor(job), in job).Wait();
|
||||
return Measure(in job, samples[..job.SampleCount], measurements);
|
||||
}
|
||||
|
||||
internal void RenderVisible(ComputeResourceBinding<ReadWriteTexture2D<Bgra32, Float4>> output, PixelRect rect, in Parameters parameters)
|
||||
private int Measure(in GpuTileJob job, ReadOnlySpan<Int2> samples, Span<ConvolutionMeasurement> measurements)
|
||||
{
|
||||
_host.RecordSharedRender(output, in rect, _canvasWidth, parameters.Gain).Wait();
|
||||
if (measurements.IsEmpty)
|
||||
return 0;
|
||||
|
||||
var count = GpuTileCheck.MeasurementCount(job.SampleCount);
|
||||
GpuTileCheck.Evaluate(_convolver.ReadReport(in job), in job, samples, _kernel.Spectrum.Kernel, measurements[..count]);
|
||||
return count;
|
||||
}
|
||||
|
||||
private WaveOpticsRenderMode BeginRender(PixelRect rect, float gain)
|
||||
{
|
||||
if (_convolutionKey is not { } key || !_kernel.IsValid)
|
||||
throw new InvalidOperationException();
|
||||
|
||||
var mode = _tracker.Next(key, rect, gain, out var releaseStore);
|
||||
if (releaseStore)
|
||||
ReleaseStoreBuffer();
|
||||
return mode;
|
||||
}
|
||||
|
||||
private GpuTileJob PrepareConvolution(PixelRect rect, float gain, bool store, Span<Int2> samples)
|
||||
{
|
||||
if (_uploadedKernelVersion != _kernel.Version)
|
||||
{
|
||||
_convolver.Upload(_kernel.Spectrum);
|
||||
if (_spectrumTamper is { } tamper)
|
||||
_convolver.Spectrum.CopyFrom(tamper(_kernel.Spectrum.Spectrum.ToArray()));
|
||||
_uploadedKernelVersion = _kernel.Version;
|
||||
}
|
||||
|
||||
if (!samples.IsEmpty)
|
||||
{
|
||||
Span<ComputeSample> picks = stackalloc ComputeSample[GpuTileConvolver.MaximumSamples];
|
||||
ComputeSampling.Fill(_convolutionKey!.Value.SamplingKey, rect.Width, rect.Height, picks);
|
||||
for (var index = 0; index < picks.Length; index++)
|
||||
samples[index] = new Int2(picks[index].X, picks[index].Y);
|
||||
}
|
||||
|
||||
var plan = TilePlan.Create(_kernel.Spectrum.Size, _kernel.Spectrum.Radius, rect.X, rect.Y, rect.Width, rect.Height);
|
||||
var job = _convolver.Prepare(plan, _sourceRect.X, _sourceRect.Y, _sourceRect.Width, _sourceRect.Height, gain, samples, store);
|
||||
if (store)
|
||||
_storedJob = job;
|
||||
|
||||
return job;
|
||||
}
|
||||
|
||||
private void ResetRendering()
|
||||
{
|
||||
if (_tracker.Reset())
|
||||
ReleaseStoreBuffer();
|
||||
}
|
||||
|
||||
private void ReleaseStoreBuffer()
|
||||
{
|
||||
_convolver.ReleaseStore();
|
||||
_storedJob = default;
|
||||
}
|
||||
|
||||
private ComputeSubmission SubmitFullPipeline(
|
||||
@@ -229,81 +317,25 @@ internal sealed class WaveOpticsPipeline : IDisposable
|
||||
in Parameters parameters)
|
||||
{
|
||||
EnsureCanvas(width, height);
|
||||
if (!TryEnsureKernel(parameters.Psf))
|
||||
if (!_kernel.TryUpdate(parameters.Psf))
|
||||
throw new InvalidOperationException();
|
||||
_convolutionKey = null;
|
||||
var sourceRect = new PixelRect(0, 0, width, height);
|
||||
return _host.RecordFullPipeline(source, output, _weights, in sourceRect, in _kernel, parameters.Gain);
|
||||
ResetRendering();
|
||||
_sourceRect = new PixelRect(0, 0, width, height);
|
||||
var job = PrepareConvolution(_sourceRect, parameters.Gain, false, []);
|
||||
return _host.RecordConvolution(
|
||||
source, output, _convolver.Tiles, _convolver.Twiddles, _convolver.Spectrum,
|
||||
_convolver.Report, _convolver.Samples, _convolver.StoreFor(job), in job);
|
||||
}
|
||||
|
||||
private bool TryEnsureKernel(in PsfParameters psf)
|
||||
{
|
||||
var key = KernelKey(psf);
|
||||
if (_kernelPsf == key)
|
||||
return HasKernel;
|
||||
|
||||
var pupilGridSize = WaveOpticsSettings.GetPupilGridSize(psf.Quality);
|
||||
var aberration = new WavefrontAberration(
|
||||
defocusWaves: psf.Defocus,
|
||||
astigmatismVerticalWaves: psf.AstigmatismVertical,
|
||||
astigmatismObliqueWaves: psf.AstigmatismOblique,
|
||||
comaHorizontalWaves: psf.ComaHorizontal,
|
||||
comaVerticalWaves: psf.ComaVertical,
|
||||
sphericalWaves: psf.Spherical);
|
||||
var specification = new PsfSpecification(
|
||||
pupilGridSize,
|
||||
WaveOpticsSettings.GetPupilDiameterSamples(pupilGridSize),
|
||||
WaveOpticsSettings.GetKernelSize(psf.KernelRadius),
|
||||
psf.Wavelength,
|
||||
psf.FNumber,
|
||||
psf.PixelPitch,
|
||||
psf.ApertureShape == WaveOpticsApertureShape.Circular ? ApertureShape.Circular : ApertureShape.RegularPolygon,
|
||||
psf.BladeCount,
|
||||
psf.BladeRotation,
|
||||
psf.Obstruction,
|
||||
aberration);
|
||||
var size = specification.KernelSize;
|
||||
var kernel = _kernelValues.AsSpan(0, size * size);
|
||||
if (!_sampler.TrySample(in specification, kernel))
|
||||
{
|
||||
_kernel = default;
|
||||
_kernelPsf = key;
|
||||
return false;
|
||||
}
|
||||
|
||||
_separable.Update(kernel, size, WaveOpticsSettings.SeparableResidualRatio, WaveOpticsSettings.MaximumRank);
|
||||
var scale = 1d / _separable.Sum;
|
||||
for (var term = 0; term < _separable.Rank; term++)
|
||||
{
|
||||
_separable.Horizontal.Slice(term * size, size).CopyTo(_weightValues.AsSpan(WaveOpticsSettings.GetWeightOffset(term, 0)));
|
||||
var verticalOffset = WaveOpticsSettings.GetWeightOffset(term, 1);
|
||||
for (var k = 0; k < size; k++)
|
||||
_weightValues[verticalOffset + k] = (float)(_separable.Vertical[term * size + k] * scale);
|
||||
}
|
||||
_weights.CopyFrom(_weightValues.AsSpan(0, WaveOpticsSettings.GetWeightOffset(_separable.Rank, 0)));
|
||||
_kernel = new Kernel(_separable.Rank, size / 2);
|
||||
_kernelPsf = key;
|
||||
return true;
|
||||
}
|
||||
|
||||
private static PsfParameters KernelKey(in PsfParameters psf)
|
||||
=> psf.ApertureShape == WaveOpticsApertureShape.Circular ? psf with { BladeCount = 0, BladeRotation = 0f } : psf;
|
||||
|
||||
private void EnsureCanvas(int canvasWidth, int canvasHeight)
|
||||
{
|
||||
if (_canvasWidth == canvasWidth && _canvasHeight == canvasHeight)
|
||||
return;
|
||||
|
||||
var canvasLength = canvasWidth * canvasHeight;
|
||||
if (!_host.TryEnsureCanvas(new WaveOpticsCanvasResources.Plan(canvasLength, canvasLength), out _))
|
||||
throw new InvalidOperationException();
|
||||
|
||||
_cachedLitCount = 0;
|
||||
_cachedBoundsMinX = int.MaxValue;
|
||||
_cachedBoundsMinY = int.MaxValue;
|
||||
_cachedBoundsMaxX = int.MinValue;
|
||||
_cachedBoundsMaxY = int.MinValue;
|
||||
_sourceHash = WaveOpticsSourceHash.Empty;
|
||||
_convolutionKey = null;
|
||||
ResetRendering();
|
||||
_canvasWidth = canvasWidth;
|
||||
_canvasHeight = canvasHeight;
|
||||
}
|
||||
@@ -321,8 +353,12 @@ internal sealed class WaveOpticsPipeline : IDisposable
|
||||
_packedHeight = height;
|
||||
}
|
||||
|
||||
private void OnDeviceLost(object? sender, DeviceLostEventArgs e)
|
||||
=> Volatile.Write(ref _deviceLost, true);
|
||||
|
||||
public void Dispose()
|
||||
{
|
||||
_device.DeviceLost -= OnDeviceLost;
|
||||
_host.Dispose();
|
||||
_host.WaitForDisposal();
|
||||
_packedSource?.Dispose();
|
||||
@@ -331,27 +367,17 @@ internal sealed class WaveOpticsPipeline : IDisposable
|
||||
_packedOutput = null;
|
||||
_packedWidth = 0;
|
||||
_packedHeight = 0;
|
||||
_kernelPsf = null;
|
||||
_convolutionKey = null;
|
||||
_tracker.Reset();
|
||||
_canvasWidth = 0;
|
||||
_canvasHeight = 0;
|
||||
_weights.Dispose();
|
||||
_convolver.Dispose();
|
||||
_scratchReadBack.Dispose();
|
||||
_scratch.Dispose();
|
||||
}
|
||||
|
||||
internal readonly record struct PixelRect(int X, int Y, int Width, int Height);
|
||||
|
||||
internal readonly record struct Kernel(int Rank, int Radius);
|
||||
|
||||
private readonly record struct ConvolutionKey(
|
||||
int HashSum,
|
||||
int HashMix,
|
||||
int CanvasWidth,
|
||||
int CanvasHeight,
|
||||
PixelRect Source,
|
||||
PsfParameters Psf);
|
||||
|
||||
internal readonly record struct PsfParameters(
|
||||
WaveOpticsQuality Quality,
|
||||
int KernelRadius,
|
||||
|
||||
@@ -1,42 +1,13 @@
|
||||
using ComputeWeave;
|
||||
using SpectralConvolution;
|
||||
|
||||
namespace WaveOptics.Rendering;
|
||||
|
||||
[ComputeResourceGroup]
|
||||
internal sealed partial class WaveOpticsCanvasResources
|
||||
{
|
||||
[ComputePipelineResource(ComputeResourceAccess.ReadWrite)]
|
||||
internal ReadWriteBuffer<Float4> Horizontal { get; }
|
||||
|
||||
[ComputePipelineResource(ComputeResourceAccess.ReadWrite)]
|
||||
internal ReadWriteBuffer<Float4> Convolved { get; }
|
||||
}
|
||||
|
||||
[ComputePipelineHost("_device", 1)]
|
||||
internal sealed partial class WaveOpticsPipelineHost
|
||||
{
|
||||
private readonly GraphicsDevice _device;
|
||||
|
||||
[ComputePipelineResource(ComputeResourceAccess.ReadWrite, ComputeResourceRecovery.Recompute)]
|
||||
private readonly ComputeResourceGroupSlot<WaveOpticsCanvasResources> _canvas = new();
|
||||
|
||||
[ComputePipeline]
|
||||
private void RecordFullPipeline(
|
||||
in ComputeContext context,
|
||||
[ComputeOwnedResource(nameof(_canvas))] WaveOpticsCanvasResources canvas,
|
||||
[ComputeResource(ComputeResourceAccess.ReadWrite)] ReadWriteTexture2D<Bgra32, Float4> source,
|
||||
[ComputeResource(ComputeResourceAccess.ReadWrite)] ReadWriteTexture2D<Bgra32, Float4> output,
|
||||
[ComputeResource(ComputeResourceAccess.Read)] ReadOnlyBuffer<float> weights,
|
||||
in WaveOpticsPipeline.PixelRect sourceRect,
|
||||
in WaveOpticsPipeline.Kernel kernel,
|
||||
float gain)
|
||||
{
|
||||
_ = _device;
|
||||
|
||||
RecordConvolutionStage(in context, canvas, source, weights, in sourceRect, in sourceRect, sourceRect.Width, in kernel);
|
||||
RecordRenderStage(in context, canvas, output, in sourceRect, sourceRect.Width, gain);
|
||||
}
|
||||
|
||||
[ComputePipeline]
|
||||
private void RecordSourceHash(
|
||||
in ComputeContext context,
|
||||
@@ -65,63 +36,65 @@ internal sealed partial class WaveOpticsPipelineHost
|
||||
[ComputePipeline]
|
||||
private void RecordConvolution(
|
||||
in ComputeContext context,
|
||||
[ComputeOwnedResource(nameof(_canvas))] WaveOpticsCanvasResources canvas,
|
||||
[ComputeResource(ComputeResourceAccess.ReadWrite)] ReadWriteTexture2D<Bgra32, Float4> source,
|
||||
[ComputeResource(ComputeResourceAccess.Read)] ReadOnlyBuffer<float> weights,
|
||||
in WaveOpticsPipeline.PixelRect sourceRect,
|
||||
in WaveOpticsPipeline.PixelRect rect,
|
||||
int canvasWidth,
|
||||
in WaveOpticsPipeline.Kernel kernel)
|
||||
[ComputeResource(ComputeResourceAccess.ReadWrite)] ReadWriteTexture2D<Bgra32, Float4> output,
|
||||
[ComputeResource(ComputeResourceAccess.ReadWrite)] ReadWriteBuffer<Float4> tiles,
|
||||
[ComputeResource(ComputeResourceAccess.Read)] ReadOnlyBuffer<Float2> twiddles,
|
||||
[ComputeResource(ComputeResourceAccess.Read)] ReadOnlyBuffer<Float2> spectrum,
|
||||
[ComputeResource(ComputeResourceAccess.ReadWrite)] ReadWriteBuffer<uint> report,
|
||||
[ComputeResource(ComputeResourceAccess.Read)] ReadOnlyBuffer<Int2> samples,
|
||||
[ComputeResource(ComputeResourceAccess.ReadWrite)] ReadWriteBuffer<Float4> store,
|
||||
in GpuTileJob job)
|
||||
{
|
||||
_ = _device;
|
||||
|
||||
RecordConvolutionStage(in context, canvas, source, weights, in sourceRect, in rect, canvasWidth, in kernel);
|
||||
GpuTileConvolver.Record(in context, source, output, tiles, twiddles, spectrum, report, samples, store, in job);
|
||||
}
|
||||
|
||||
[ComputePipeline]
|
||||
[ComputeInterop]
|
||||
private void RecordSharedConvolution(
|
||||
in ComputeContext context,
|
||||
[ComputeOwnedResource(nameof(_canvas))] WaveOpticsCanvasResources canvas,
|
||||
[ComputeResource(ComputeResourceAccess.ReadWrite, Sharing = ComputeResourceSharing.External)] ReadWriteTexture2D<Bgra32, Float4> source,
|
||||
[ComputeResource(ComputeResourceAccess.Read)] ReadOnlyBuffer<float> weights,
|
||||
in WaveOpticsPipeline.PixelRect sourceRect,
|
||||
in WaveOpticsPipeline.PixelRect rect,
|
||||
int canvasWidth,
|
||||
in WaveOpticsPipeline.Kernel kernel)
|
||||
[ComputeResource(ComputeResourceAccess.ReadWrite, Sharing = ComputeResourceSharing.External)] ReadWriteTexture2D<Bgra32, Float4> output,
|
||||
[ComputeResource(ComputeResourceAccess.ReadWrite)] ReadWriteBuffer<Float4> tiles,
|
||||
[ComputeResource(ComputeResourceAccess.Read)] ReadOnlyBuffer<Float2> twiddles,
|
||||
[ComputeResource(ComputeResourceAccess.Read)] ReadOnlyBuffer<Float2> spectrum,
|
||||
[ComputeResource(ComputeResourceAccess.ReadWrite)] ReadWriteBuffer<uint> report,
|
||||
[ComputeResource(ComputeResourceAccess.Read)] ReadOnlyBuffer<Int2> samples,
|
||||
[ComputeResource(ComputeResourceAccess.ReadWrite)] ReadWriteBuffer<Float4> store,
|
||||
in GpuTileJob job)
|
||||
{
|
||||
_ = _device;
|
||||
|
||||
RecordConvolutionStage(in context, canvas, source, weights, in sourceRect, in rect, canvasWidth, in kernel);
|
||||
GpuTileConvolver.Record(in context, source, output, tiles, twiddles, spectrum, report, samples, store, in job);
|
||||
}
|
||||
|
||||
[ComputePipeline]
|
||||
private void RecordRender(
|
||||
private void RecordStoredRender(
|
||||
in ComputeContext context,
|
||||
[ComputeOwnedResource(nameof(_canvas))] WaveOpticsCanvasResources canvas,
|
||||
[ComputeResource(ComputeResourceAccess.ReadWrite)] ReadWriteBuffer<Float4> store,
|
||||
[ComputeResource(ComputeResourceAccess.ReadWrite)] ReadWriteTexture2D<Bgra32, Float4> output,
|
||||
in WaveOpticsPipeline.PixelRect rect,
|
||||
int canvasWidth,
|
||||
float gain)
|
||||
{
|
||||
_ = _device;
|
||||
|
||||
RecordRenderStage(in context, canvas, output, in rect, canvasWidth, gain);
|
||||
GpuTileConvolver.RecordStored(in context, store, output, rect.Width, rect.Height, gain);
|
||||
}
|
||||
|
||||
[ComputePipeline]
|
||||
[ComputeInterop]
|
||||
private void RecordSharedRender(
|
||||
private void RecordSharedStoredRender(
|
||||
in ComputeContext context,
|
||||
[ComputeOwnedResource(nameof(_canvas))] WaveOpticsCanvasResources canvas,
|
||||
[ComputeResource(ComputeResourceAccess.ReadWrite)] ReadWriteBuffer<Float4> store,
|
||||
[ComputeResource(ComputeResourceAccess.ReadWrite, Sharing = ComputeResourceSharing.External)] ReadWriteTexture2D<Bgra32, Float4> output,
|
||||
in WaveOpticsPipeline.PixelRect rect,
|
||||
int canvasWidth,
|
||||
float gain)
|
||||
{
|
||||
_ = _device;
|
||||
|
||||
RecordRenderStage(in context, canvas, output, in rect, canvasWidth, gain);
|
||||
GpuTileConvolver.RecordStored(in context, store, output, rect.Width, rect.Height, gain);
|
||||
}
|
||||
|
||||
private static void RecordSourceHashStage(
|
||||
@@ -137,48 +110,6 @@ internal sealed partial class WaveOpticsPipelineHost
|
||||
context.Barrier(scratch);
|
||||
}
|
||||
|
||||
private static void RecordConvolutionStage(
|
||||
in ComputeContext context,
|
||||
WaveOpticsCanvasResources canvas,
|
||||
ReadWriteTexture2D<Bgra32, Float4> source,
|
||||
ReadOnlyBuffer<float> weights,
|
||||
in WaveOpticsPipeline.PixelRect sourceRect,
|
||||
in WaveOpticsPipeline.PixelRect rect,
|
||||
int canvasWidth,
|
||||
in WaveOpticsPipeline.Kernel kernel)
|
||||
{
|
||||
var top = Math.Max(rect.Y - kernel.Radius, sourceRect.Y);
|
||||
var bottom = Math.Min(rect.Y + rect.Height + kernel.Radius, sourceRect.Y + sourceRect.Height);
|
||||
for (var term = 0; term < kernel.Rank; term++)
|
||||
{
|
||||
context.For(GetBlockCount(rect.Width, WaveOpticsSettings.HorizontalConvolutionBlock), bottom - top, new HorizontalPassShader(
|
||||
source, weights, canvas.Horizontal,
|
||||
WaveOpticsSettings.GetWeightOffset(term, 0), kernel.Radius,
|
||||
rect.X, top, rect.Width, bottom - top, canvasWidth,
|
||||
sourceRect.X, sourceRect.Y, sourceRect.Width));
|
||||
context.Barrier(canvas.Horizontal);
|
||||
context.For(rect.Width, GetBlockCount(rect.Height, WaveOpticsSettings.VerticalConvolutionBlock), new VerticalPassShader(
|
||||
canvas.Horizontal, weights, canvas.Convolved,
|
||||
WaveOpticsSettings.GetWeightOffset(term, 1), kernel.Radius,
|
||||
rect.X, rect.Y, rect.Width, rect.Height, canvasWidth,
|
||||
sourceRect.Y, sourceRect.Height, term > 0));
|
||||
context.Barrier(canvas.Horizontal);
|
||||
context.Barrier(canvas.Convolved);
|
||||
}
|
||||
}
|
||||
|
||||
private static int GetBlockCount(int length, int block)
|
||||
=> (length + block - 1) / block;
|
||||
|
||||
private static void RecordRenderStage(
|
||||
in ComputeContext context,
|
||||
WaveOpticsCanvasResources canvas,
|
||||
ReadWriteTexture2D<Bgra32, Float4> output,
|
||||
in WaveOpticsPipeline.PixelRect rect,
|
||||
int canvasWidth,
|
||||
float gain)
|
||||
{
|
||||
context.For(rect.Width, rect.Height, new RenderShader(
|
||||
canvas.Convolved, output, rect.X, rect.Y, rect.Width, rect.Height, canvasWidth, gain));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,62 @@
|
||||
namespace WaveOptics.Rendering;
|
||||
|
||||
internal readonly record struct WaveOpticsConvolutionKey(
|
||||
int HashSum,
|
||||
int HashMix,
|
||||
int CanvasWidth,
|
||||
int CanvasHeight,
|
||||
WaveOpticsPipeline.PixelRect Source,
|
||||
WaveOpticsPipeline.PsfParameters Psf)
|
||||
{
|
||||
public ulong SamplingKey => (ulong)(uint)HashSum << 32 | (uint)HashMix;
|
||||
}
|
||||
|
||||
internal enum WaveOpticsRenderMode
|
||||
{
|
||||
Convolve,
|
||||
ConvolveAndStore,
|
||||
Stored,
|
||||
}
|
||||
|
||||
internal sealed class WaveOpticsRenderTracker
|
||||
{
|
||||
private WaveOpticsConvolutionKey? _renderedKey;
|
||||
private WaveOpticsPipeline.PixelRect _renderedRect;
|
||||
private float _renderedGain;
|
||||
|
||||
public bool HasStore { get; private set; }
|
||||
|
||||
public WaveOpticsRenderMode Next(in WaveOpticsConvolutionKey key, WaveOpticsPipeline.PixelRect rect, float gain, out bool releaseStore)
|
||||
{
|
||||
WaveOpticsRenderMode mode;
|
||||
releaseStore = false;
|
||||
if (_renderedKey != key || _renderedRect != rect)
|
||||
{
|
||||
releaseStore = HasStore;
|
||||
HasStore = false;
|
||||
mode = WaveOpticsRenderMode.Convolve;
|
||||
}
|
||||
else if (HasStore)
|
||||
mode = WaveOpticsRenderMode.Stored;
|
||||
else if (gain != _renderedGain)
|
||||
{
|
||||
HasStore = true;
|
||||
mode = WaveOpticsRenderMode.ConvolveAndStore;
|
||||
}
|
||||
else
|
||||
mode = WaveOpticsRenderMode.Convolve;
|
||||
|
||||
_renderedKey = key;
|
||||
_renderedRect = rect;
|
||||
_renderedGain = gain;
|
||||
return mode;
|
||||
}
|
||||
|
||||
public bool Reset()
|
||||
{
|
||||
var hadStore = HasStore;
|
||||
_renderedKey = null;
|
||||
HasStore = false;
|
||||
return hadStore;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,73 @@
|
||||
namespace WaveOptics.Rendering;
|
||||
|
||||
internal readonly record struct WaveOpticsSourceHash(int LitCount, int MinimumX, int MinimumY, int MaximumX, int MaximumY, int Sum, int Mix)
|
||||
{
|
||||
public static WaveOpticsSourceHash Empty { get; } = new(0, int.MaxValue, int.MaxValue, int.MinValue, int.MinValue, 0, 0);
|
||||
|
||||
public static WaveOpticsSourceHash FromScratch(ReadOnlySpan<int> scratch)
|
||||
=> new(
|
||||
scratch[WaveOpticsSettings.ScratchLitCount],
|
||||
scratch[WaveOpticsSettings.ScratchBoundsMinX],
|
||||
scratch[WaveOpticsSettings.ScratchBoundsMinY],
|
||||
scratch[WaveOpticsSettings.ScratchBoundsMaxX],
|
||||
scratch[WaveOpticsSettings.ScratchBoundsMaxY],
|
||||
scratch[WaveOpticsSettings.ScratchHashSum],
|
||||
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));
|
||||
|
||||
var count = 0;
|
||||
var sum = 0;
|
||||
var mix = 0;
|
||||
var minimumX = int.MaxValue;
|
||||
var minimumY = int.MaxValue;
|
||||
var maximumX = int.MinValue;
|
||||
var maximumY = int.MinValue;
|
||||
for (var y = 0; y < sourceHeight; y++)
|
||||
{
|
||||
var row = bgra.Slice(y * sourceWidth * 4, sourceWidth * 4);
|
||||
for (var x = 0; x < sourceWidth; x++)
|
||||
{
|
||||
var quantized = (uint)row[x * 4 + 2] << 24 | (uint)row[x * 4 + 1] << 16 | (uint)row[x * 4] << 8 | row[x * 4 + 3];
|
||||
if (quantized == 0u)
|
||||
continue;
|
||||
|
||||
var mixed = unchecked((uint)(y * sourceWidth + x) * 0x9E3779B9u ^ quantized * 0x85EBCA6Bu);
|
||||
mixed ^= mixed >> 16;
|
||||
mixed = unchecked(mixed * 0x85EBCA6Bu);
|
||||
mixed ^= mixed >> 13;
|
||||
sum = unchecked(sum + (int)mixed);
|
||||
mix ^= unchecked((int)(mixed * 0xC2B2AE35u));
|
||||
count++;
|
||||
minimumX = Math.Min(minimumX, sourceX + x);
|
||||
maximumX = Math.Max(maximumX, sourceX + x);
|
||||
minimumY = Math.Min(minimumY, sourceY + y);
|
||||
maximumY = Math.Max(maximumY, sourceY + y);
|
||||
}
|
||||
}
|
||||
|
||||
return new WaveOpticsSourceHash(count, minimumX, minimumY, maximumX, maximumY, sum, mix);
|
||||
}
|
||||
|
||||
public bool TryGetVisibleBounds(int canvasWidth, int canvasHeight, int radius, out WaveOpticsPipeline.PixelRect rect)
|
||||
{
|
||||
rect = default;
|
||||
if (LitCount <= 0 || MinimumX > MaximumX)
|
||||
return false;
|
||||
|
||||
var left = Math.Clamp((MinimumX - radius) & ~3, 0, canvasWidth);
|
||||
var top = Math.Clamp((MinimumY - radius) & ~3, 0, canvasHeight);
|
||||
var right = Math.Clamp(MaximumX + 1 + radius, 0, canvasWidth);
|
||||
var bottom = Math.Clamp(MaximumY + 1 + radius, 0, canvasHeight);
|
||||
var width = Math.Min((right - left + 3) & ~3, canvasWidth - left);
|
||||
var height = Math.Min((bottom - top + 3) & ~3, canvasHeight - top);
|
||||
if (width <= 0 || height <= 0)
|
||||
return false;
|
||||
|
||||
rect = new WaveOpticsPipeline.PixelRect(left, top, width, height);
|
||||
return true;
|
||||
}
|
||||
}
|
||||
@@ -7,7 +7,7 @@
|
||||
<Nullable>enable</Nullable>
|
||||
<AssemblyName>WaveOptics</AssemblyName>
|
||||
<RootNamespace>WaveOptics</RootNamespace>
|
||||
<Version>2.1.0</Version>
|
||||
<Version>3.0.0</Version>
|
||||
<Platforms>AnyCPU;x64</Platforms>
|
||||
<PlatformTarget>x64</PlatformTarget>
|
||||
<AllowUnsafeBlocks>true</AllowUnsafeBlocks>
|
||||
@@ -72,6 +72,10 @@
|
||||
|
||||
<Import Project="..\YMM4-Telemetry\Telemetry.props" />
|
||||
|
||||
<Import Project="..\YMM4-ComputeGuard\ComputeGuard.props" />
|
||||
|
||||
<Import Project="..\SpectralConvolution\SpectralConvolution.props" />
|
||||
|
||||
<ItemGroup>
|
||||
<PackageReference Include="ComputeWeave" Version="2.6.0" />
|
||||
<PackageReference Include="ILRepack" Version="2.0.48" PrivateAssets="all" ExcludeAssets="all" GeneratePathProperty="true" />
|
||||
|
||||
@@ -8,11 +8,6 @@ internal static class WaveOpticsSettings
|
||||
public const int DefaultKernelRadius = 15;
|
||||
public const int MaximumKernelRadius = 63;
|
||||
public const int MaximumKernelSize = MaximumKernelRadius * 2 + 1;
|
||||
public const int MaximumRank = MaximumKernelSize;
|
||||
public const double SeparableResidualRatio = 1e-4;
|
||||
public const int WeightsLength = MaximumRank * 2 * MaximumKernelSize;
|
||||
public const int HorizontalConvolutionBlock = 16;
|
||||
public const int VerticalConvolutionBlock = 8;
|
||||
public const int SourceHashSpan = 16;
|
||||
public const int DefaultCanvasMargin = (DefaultKernelRadius + 3) & ~3;
|
||||
public const int MaximumCanvasSize = 8192;
|
||||
@@ -39,6 +34,4 @@ internal static class WaveOpticsSettings
|
||||
public static int GetKernelSize(int kernelRadius) => kernelRadius * 2 + 1;
|
||||
|
||||
public static int GetCanvasMargin(int kernelRadius) => Math.Max(DefaultCanvasMargin, (kernelRadius + 3) & ~3);
|
||||
|
||||
public static int GetWeightOffset(int term, int axis) => (term * 2 + axis) * MaximumKernelSize;
|
||||
}
|
||||
サブモジュール
+1
サブモジュール YMM4-ComputeGuard が 8ba949afdd で追加されました。
新しいイシューから参照
ユーザーをブロックする