コミットを比較
| 作成者 | SHA1 | 日付 | |
|---|---|---|---|
|
|
c78764e367
|
||
|
|
711519fe4f
|
||
|
|
ca6269d242
|
||
|
|
e547e0f838
|
||
|
|
2434dbf08b
|
||
|
|
06ba0070e9
|
||
|
|
a2c727e49e
|
||
|
|
8a1ac6d12d
|
||
|
|
78d5debe2c
|
||
|
|
d432576ed7
|
||
|
|
cb80cb8c52
|
||
|
|
ecc7fa8dce
|
||
|
|
6ad9426585
|
||
|
|
6c11e5163f
|
||
|
|
9ba6a57f33
|
||
|
|
5951976c33
|
||
|
|
c99609652d
|
||
|
|
cb569934fc
|
||
|
|
388a87939c
|
||
|
|
dd34a3ea04
|
||
|
|
d613d19212
|
検索条件に一致するファイルはありません
+18
-13
@@ -1,5 +1,5 @@
|
||||
========================================
|
||||
波動光学 for YMM4 v2.0.0
|
||||
波動光学 for YMM4 v2.1.0
|
||||
========================================
|
||||
YukkuriMovieMaker4上で動作する、素材を回折も収差もない理想の像とみなし、
|
||||
レンズの開口と波面収差から求めた点像分布関数で畳み込んで、
|
||||
@@ -46,20 +46,24 @@ YukkuriMovieMaker4上で動作する、素材を回折も収差もない理想
|
||||
そのまま重み付けして足し合わせます。画素の値を光の強さに比例する値へ
|
||||
直してから畳み込む処理はしません。
|
||||
|
||||
- 計算領域: 透明な部分も含む素材全体の矩形の上下左右に16画素の余白を
|
||||
加えた大きさを計算領域とし、長辺は8192画素が上限です。素材の長辺が
|
||||
8160画素を超える場合は、エフェクトを適用せず入力映像を表示します。
|
||||
|
||||
- カーネル半径: 1〜15画素です。カーネルは、畳み込みの重みを正方形に
|
||||
並べたものです。正方形は、中心から上下左右にカーネル半径の画素数まで
|
||||
広がります。正方形の外に届く光は捨て、カーネルの値の和が1になるように
|
||||
正規化します。
|
||||
|
||||
- 品質と収差: 品質は、瞳関数を置く格子の大きさを切り替えます。格子は
|
||||
瞳関数の値を縦横に並べた表で、1つ1つの値を標本と呼びます。格子が粗いと、
|
||||
大きな波面収差で位相が急に変わる所を表しきれず、点像分布関数の形が
|
||||
崩れます。波面収差を大きくするときは、品質を上げてください。
|
||||
|
||||
- カーネル半径: 1〜63画素で、デフォルトは15画素です。カーネルは、畳み込みの
|
||||
重みを正方形に並べたものです。正方形は、中心から上下左右にカーネル半径の
|
||||
画素数まで広がります。正方形の外に届く光は捨て、カーネルの値の和が1に
|
||||
なるように正規化します。デフォーカスを大きくするときは、カーネル半径と
|
||||
品質を上げてください。上げるほど計算が重くなります。
|
||||
|
||||
- 計算領域: 透明な部分も含む素材全体の矩形の上下左右に余白を加えた
|
||||
大きさを計算領域とし、長辺は8192画素が上限です。余白は、カーネル半径を
|
||||
4画素単位に切り上げた画素数で、16画素を下回りません。素材の長辺の
|
||||
上限は、8192画素から余白の2倍を引いた値です。カーネル半径が16画素以下
|
||||
なら8160画素、63画素なら8064画素になります。素材の長辺がこの上限を
|
||||
超える場合は、エフェクトを適用せず入力映像を表示します。
|
||||
|
||||
- 中央遮蔽: 中央遮蔽で開口をほとんどふさぎ、瞳関数の格子に光の通る標本が
|
||||
1つも無くなる設定では、エフェクトを適用せず入力映像を表示します。
|
||||
品質を上げると起きにくくなります。
|
||||
@@ -70,8 +74,9 @@ YukkuriMovieMaker4上で動作する、素材を回折も収差もない理想
|
||||
増えます。畳み込む範囲は、透明でない画素をすべて囲む最小の矩形を
|
||||
カーネル半径だけ広げ、外側へ4画素単位にそろえた範囲です。畳み込みは、
|
||||
横方向と縦方向の1次元の重みを1組とした、何組かの和で近似して行います。
|
||||
収差を入れると組の数が増えて、計算が重くなります。品質を上げると、
|
||||
点像分布関数の計算が重くなります。
|
||||
収差を入れると組の数が増え、カーネル半径を上げると1組あたりの計算量が
|
||||
増えるので、どちらも計算が重くなります。品質を上げると、点像分布関数の
|
||||
計算が重くなります。
|
||||
|
||||
- キャッシュ: 素材の大きさと色と不透明度が変わらず、「利得」と「適用量」
|
||||
以外の項目も変わらないフレームでは、畳み込みの計算を再利用します。
|
||||
@@ -136,7 +141,7 @@ YukkuriMovieMaker4上で動作する、素材を回折も収差もない理想
|
||||
相互運用に必要なインターフェースを
|
||||
持たない、GPUメモリが足りず
|
||||
共有テクスチャを確保できない、
|
||||
素材の長辺が8160画素を超える、
|
||||
計算領域が8192画素に収まらない、
|
||||
開口に光の通る標本が無いときに、
|
||||
エフェクトを適用せず入力映像を
|
||||
表示したとき
|
||||
|
||||
@@ -97,11 +97,11 @@ YukkuriMovieMaker4(YMM4)上で動作する、素材を回折も収差もな
|
||||
|
||||
「画素ピッチ」は、撮像面での1画素の間隔です。小さいほど、同じ広がりが多くの画素にまたがります。にじみの大きさは素材の画素を単位に決まるため、画素数の多い素材ほど、映像の全体に対するにじみは小さく見えます。
|
||||
|
||||
「カーネル半径」は、カーネルの正方形が中心から上下左右に何画素まで広がるかを決めます。設定できるのは1〜15画素です。点像分布関数がカーネルの正方形の外まで広がる設定では、外側の輪やにじみが切り取られます。
|
||||
「カーネル半径」は、カーネルの正方形が中心から上下左右に何画素まで広がるかを決めます。設定できるのは1〜63画素で、デフォルトは15画素です。点像分布関数がカーネルの正方形の外まで広がる設定では、外側の輪やにじみが切り取られます。デフォルトの光学系でデフォーカスを1 wavesにすると、にじみは中心から約15画素まで広がります。デフォーカスを大きくするときは、カーネル半径を上げてください。点像分布関数を求める範囲より外のカーネルの画素は0になるので、範囲を広げるには品質も上げてください。範囲は「品質の選択」にあります。カーネル半径と品質を上げるほど、計算は重くなります。
|
||||
|
||||
### 3. 開口の形と中央遮蔽
|
||||
|
||||
「開口形状」は、円形と正多角形から選びます。正多角形は、カメラの絞りの羽根が作る開口をまねた形で、頂点は円形の開口と同じ直径の円の上にあります。正多角形の開口では、頂点までの距離を開口の半径とします。辺の数は「羽根枚数」で、向きは「開口回転」で決めます。正多角形の開口では、点像分布関数が辺と垂直な向きへ伸びます。「羽根枚数」と「開口回転」は、開口形状が正多角形のときだけ働きます。
|
||||
「開口形状」は、円形と正多角形から選びます。正多角形は、カメラの絞りの羽根が作る開口をまねた形で、頂点は円形の開口と同じ直径の円の上にあります。正多角形の開口では、頂点までの距離を開口の半径とします。辺の数は「羽根枚数」で、向きは「開口回転」で決めます。正多角形の開口では、点像分布関数が辺と垂直な向きへ伸びます。デフォーカスでにじみが大きいときは、にじみが開口と辺の数が同じ正多角形の形になります。にじみが切り取られないよう、カーネル半径と品質を上げてください。「羽根枚数」と「開口回転」は、開口形状が正多角形のときだけ働きます。
|
||||
|
||||
「中央遮蔽」は、反射望遠鏡の副鏡のように開口の中央をふさぐ円の大きさで、開口の半径に対する割合です。値を上げると中心の明るさが下がり、周りの輪へ光が移ります。中央遮蔽は、どちらの開口形状でも円でふさぎます。
|
||||
|
||||
@@ -128,7 +128,17 @@ YukkuriMovieMaker4(YMM4)上で動作する、素材を回折も収差もな
|
||||
|
||||
組の数は点像分布関数の形で決まります。カーネル半径15画素、品質「標準」で23通りの設定を測りました。組の数は、収差がないときは1〜6組、収差を入れると5〜16組でした。組が増えるほど、畳み込みの計算は重くなります。
|
||||
|
||||
計算時間は、試験用に作った1920×1080の画像を使い、Intel Iris Xe Graphicsで測りました。素材が変わって畳み込みを計算し直すフレームでは、収差がないときに約11ミリ秒、デフォーカスを1 wavesにすると約34ミリ秒、水平コマ収差を1 wavesにすると約50ミリ秒でした。素材と設定が変わらず、畳み込みを再利用するフレームでは約1.3ミリ秒でした。
|
||||
計算時間は、試験用に作った1920×1080の画像を使い、Intel Iris Xe Graphicsで測りました。素材が変わって畳み込みを計算し直すフレームの時間は、次のとおりでした。
|
||||
|
||||
| カーネル半径 | 品質 | 収差 | 組の数 | 時間 |
|
||||
|---:|---|---|---:|---:|
|
||||
| 15画素 | 標準 | なし | 3 | 約11ミリ秒 |
|
||||
| 15画素 | 標準 | デフォーカス1 waves | 11 | 約34ミリ秒 |
|
||||
| 15画素 | 標準 | 水平コマ収差1 waves | 16 | 約57ミリ秒 |
|
||||
| 63画素 | 高精度 | デフォーカス2 waves | 19 | 約190ミリ秒 |
|
||||
| 63画素 | 高精度 | 水平コマ収差2 waves | 35 | 約360ミリ秒 |
|
||||
|
||||
素材と設定が変わらず、畳み込みを再利用するフレームでは約1ミリ秒でした。
|
||||
|
||||
### 6. 利得と適用量
|
||||
|
||||
@@ -172,7 +182,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〜15px | 非対応 | カーネルが中心から上下左右に広がる画素数です。カーネルの外に届く光は捨てます。 |
|
||||
| カーネル半径 | 整数 | 15px | 1〜63px | 非対応 | カーネルが中心から上下左右に広がる画素数です。カーネルの外に届く光は捨てます。 |
|
||||
| 品質 | 列挙 | 標準 | 高速 / 標準 / 高精度 | 非対応 | 瞳関数を置く格子の大きさを選択します。 |
|
||||
|
||||
### 開口グループ
|
||||
@@ -206,16 +216,16 @@ YukkuriMovieMaker4(YMM4)上で動作する、素材を回折も収差もな
|
||||
- 畳み込みには現在のフレームの色と不透明度だけを使用します。履歴フレーム、外部画像、学習済みモデルは使用しません。素材に透明でない画素が無いときは、エフェクトを適用せず入力映像を表示します。
|
||||
- 計算は単色のフラウンホーファー回折に限ります。白色光のように波長の混ざった光は扱いません。点像分布関数は画面のどこでも同じで、像の位置や素材の奥行きで変わるにじみは扱いません。
|
||||
- 畳み込みは、画素の値をそのまま重み付けして足し合わせます。画素の値を光の強さに比例する値へ直してから畳み込む処理はしません。
|
||||
- カーネル半径は1〜15画素です。
|
||||
- カーネル半径は1〜63画素です。
|
||||
- 中央遮蔽で開口をほとんどふさぎ、瞳関数の格子に光の通る標本が1つも無くなる設定では、エフェクトを適用せず入力映像を表示します。品質を上げると起きにくくなります。
|
||||
- 計算領域は、透明な部分も含む素材全体の矩形の上下左右に16画素の余白を加えた大きさで、長辺は8192画素が上限です。素材の長辺が8160画素を超える場合は、エフェクトを適用せず入力映像を表示します。
|
||||
- 計算領域は、透明な部分も含む素材全体の矩形の上下左右に余白を加えた大きさで、長辺は8192画素が上限です。余白は、カーネル半径を4画素単位に切り上げた画素数で、16画素を下回りません。素材の長辺の上限は、8192画素から余白の2倍を引いた値です。カーネル半径が16画素以下なら8160画素、63画素なら8064画素になります。素材の長辺がこの上限を超える場合は、エフェクトを適用せず入力映像を表示します。
|
||||
- GPUメモリ使用量は、計算領域の大きさに応じて増えます。作業用のバッファーとして、計算領域の1画素につき32バイトをGPUに確保します。処理量は、素材全体の大きさと畳み込む範囲の大きさに応じて増えます。
|
||||
|
||||
---
|
||||
|
||||
## 注意事項
|
||||
|
||||
- 処理負荷: 収差を入れると、畳み込みに使う組の数が増えて計算が重くなります。時間の目安は「分離可能な畳み込み」にあります。品質を上げると、点像分布関数の計算が重くなります。
|
||||
- 処理負荷: 収差を入れると、畳み込みに使う組の数が増えて計算が重くなります。カーネル半径を上げた場合は、1組あたりの畳み込みの計算量と、組を求める特異値分解の計算量が増えます。品質を上げた場合は、点像分布関数の計算量が増えます。畳み込みの時間の目安は「分離可能な畳み込み」にあります。
|
||||
- 品質と収差: 波面収差を大きくするときは、品質を上げてください。格子が粗いと点像分布関数の形が崩れます。崩れ方の目安は「品質の選択」にあります。
|
||||
- キャッシュ: 素材の大きさと色と不透明度が変わらず、「利得」と「適用量」以外の項目も変わらないフレームでは、畳み込みの計算を再利用します。利得だけを変えたフレームでは、再利用した畳み込みに利得を掛け直します。適用量だけを変えたフレームでは、混ぜる割合だけを変えます。動画や口パクのように素材の内容が変わるフレームと、「利得」と「適用量」以外の項目をアニメーションで変えたフレームでは、毎回計算し直すので処理が重くなります。素材が変わったかどうかを調べる計算は、再利用するフレームでも毎フレーム行います。
|
||||
- 適用量0%: 適用量が0%のときは入力を変更せず、畳み込みの計算も行いません。
|
||||
@@ -251,7 +261,7 @@ YukkuriMovieMaker4(YMM4)上で動作する、素材を回折も収差もな
|
||||
|
||||
| 種類 | 例 |
|
||||
|---|---|
|
||||
| 効果をかけないだけで済ませるもの | Direct3D 12デバイスを取得できない、YMM4のDirect3D 11デバイスが相互運用に必要なインターフェースを持たない、GPUメモリが足りず共有テクスチャを確保できない、素材の長辺が8160画素を超える、開口に光の通る標本が無いときに、エフェクトを適用せず入力映像を表示したとき |
|
||||
| 効果をかけないだけで済ませるもの | Direct3D 12デバイスを取得できない、YMM4のDirect3D 11デバイスが相互運用に必要なインターフェースを持たない、GPUメモリが足りず共有テクスチャを確保できない、計算領域が8192画素に収まらない、開口に光の通る標本が無いときに、エフェクトを適用せず入力映像を表示したとき |
|
||||
| 更新の確認の通信の失敗 | manjubox.netとGitHubのどちらへも接続できない |
|
||||
|
||||
送信できなかった報告はYMM4のユーザーフォルダーへ退避します。次にYMM4を起動したあと、本プラグインのエフェクトを生成するか、同じくYMM4-Telemetryで報告する別のプラグインが動き始めると、退避した報告を1回の起動で10件まで送り直します。送信も再送も非同期に行うため、通信を待って起動と描画が遅くなることはありません。
|
||||
|
||||
@@ -28,6 +28,18 @@ internal static class HarnessCases
|
||||
yield return ("pixel-pitch-2", Create(effect => effect.PixelPitch.Values[0].Value = 2), [0]);
|
||||
yield return ("kernel-radius-1", Create(effect => effect.KernelRadius = 1), [0]);
|
||||
yield return ("kernel-radius-5", Create(effect => effect.KernelRadius = 5), [0]);
|
||||
yield return ("kernel-radius-40-defocus-2", Create(effect =>
|
||||
{
|
||||
effect.KernelRadius = 40;
|
||||
effect.Defocus.Values[0].Value = 2;
|
||||
}), [0]);
|
||||
yield return ("kernel-radius-63-polygon-defocus-3", Create(effect =>
|
||||
{
|
||||
effect.KernelRadius = WaveOpticsSettings.MaximumKernelRadius;
|
||||
effect.Quality = WaveOpticsQuality.High;
|
||||
effect.ApertureShape = WaveOpticsApertureShape.RegularPolygon;
|
||||
effect.Defocus.Values[0].Value = 3;
|
||||
}), [0]);
|
||||
yield return ("quality-draft", Create(effect => effect.Quality = WaveOpticsQuality.Draft), [0]);
|
||||
yield return ("quality-high", Create(effect => effect.Quality = WaveOpticsQuality.High), [0]);
|
||||
yield return ("aperture-polygon", Create(effect => effect.ApertureShape = WaveOpticsApertureShape.RegularPolygon), [0]);
|
||||
@@ -64,6 +76,12 @@ internal static class HarnessCases
|
||||
yield return ("f-number-8-to-32", () => Create(), effect => effect.FNumber.Values[0].Value = 32, 0);
|
||||
yield return ("pixel-pitch-4-to-2", () => Create(), effect => effect.PixelPitch.Values[0].Value = 2, 0);
|
||||
yield return ("kernel-radius-15-to-5", () => Create(), effect => effect.KernelRadius = 5, 0);
|
||||
yield return ("kernel-radius-15-to-40", () => Create(effect => effect.Defocus.Values[0].Value = 2), effect => effect.KernelRadius = 40, 0);
|
||||
yield return ("kernel-radius-40-to-15", () => Create(effect =>
|
||||
{
|
||||
effect.KernelRadius = 40;
|
||||
effect.Defocus.Values[0].Value = 2;
|
||||
}), effect => effect.KernelRadius = 15, 0);
|
||||
yield return ("quality-standard-to-high", () => Create(), effect => effect.Quality = WaveOpticsQuality.High, 0);
|
||||
yield return ("aperture-circular-to-polygon", () => Create(), effect => effect.ApertureShape = WaveOpticsApertureShape.RegularPolygon, 0);
|
||||
yield return ("blade-count-6-to-5", () => Create(effect => effect.ApertureShape = WaveOpticsApertureShape.RegularPolygon), effect => effect.BladeCount = 5, 0);
|
||||
@@ -84,6 +102,11 @@ internal static class HarnessCases
|
||||
yield return ("default", Create());
|
||||
yield return ("quality-high", Create(effect => effect.Quality = WaveOpticsQuality.High));
|
||||
yield return ("kernel-radius-5", Create(effect => effect.KernelRadius = 5));
|
||||
yield return ("kernel-radius-40", Create(effect =>
|
||||
{
|
||||
effect.KernelRadius = 40;
|
||||
effect.Defocus.Values[0].Value = 2;
|
||||
}));
|
||||
yield return ("defocus-animated", Create(effect => effect.Defocus.CopyFrom(Linear(0d, 3d))));
|
||||
yield return ("amount-0", Create(effect => effect.Amount.Values[0].Value = 0));
|
||||
}
|
||||
|
||||
@@ -117,6 +117,20 @@
|
||||
],
|
||||
"hash": "34B3BCEC95C18658E45A8832AEB2BE00F0716E2FD78CE45CBA36F644DA5945B9"
|
||||
},
|
||||
{
|
||||
"name": "kernel-radius-40-defocus-2",
|
||||
"frames": [
|
||||
0
|
||||
],
|
||||
"hash": "6908E7DFE146500A209D47AD18FF5932FF9B80F8FCD976036179F4CA8503C89C"
|
||||
},
|
||||
{
|
||||
"name": "kernel-radius-63-polygon-defocus-3",
|
||||
"frames": [
|
||||
0
|
||||
],
|
||||
"hash": "55D4485AD5176D4AB6C7BE4BBBDD97343002B675AB0742D8F8224FD57A9296A5"
|
||||
},
|
||||
{
|
||||
"name": "quality-draft",
|
||||
"frames": [
|
||||
|
||||
@@ -61,6 +61,24 @@ public sealed class FastFourierTransformTests
|
||||
AssertMaximumError(expectedReal, expectedImaginary, real, imaginary, 1e-10);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void AWarmTransformAllocatesNoManagedMemory()
|
||||
{
|
||||
var real = new double[256];
|
||||
var imaginary = new double[256];
|
||||
FastFourierTransform.Forward(real, imaginary);
|
||||
FastFourierTransform.Inverse(real, imaginary);
|
||||
|
||||
var before = GC.GetAllocatedBytesForCurrentThread();
|
||||
for (var index = 0; index < 16; index++)
|
||||
{
|
||||
FastFourierTransform.Forward(real, imaginary);
|
||||
FastFourierTransform.Inverse(real, imaginary);
|
||||
}
|
||||
|
||||
Assert.Equal(0, GC.GetAllocatedBytesForCurrentThread() - before);
|
||||
}
|
||||
|
||||
static void AssertMaximumError(double[] expectedReal, double[] expectedImaginary, double[] actualReal, double[] actualImaginary, double tolerance)
|
||||
{
|
||||
var maximum = 0d;
|
||||
|
||||
@@ -0,0 +1,108 @@
|
||||
using WaveOptics.Abstractions;
|
||||
using WaveOptics.Optics;
|
||||
|
||||
namespace WaveOptics.Tests.Psf;
|
||||
|
||||
public sealed class FraunhoferKernelSamplerTests
|
||||
{
|
||||
readonly FraunhoferPsfGenerator generator = new();
|
||||
readonly FraunhoferKernelSampler sampler = new();
|
||||
readonly double[] kernel = new double[255 * 255];
|
||||
|
||||
static PsfDescriptor Descriptor(
|
||||
int gridSize = 256,
|
||||
int diameter = 64,
|
||||
int kernelRadius = 15,
|
||||
double wavelength = 550,
|
||||
double fNumber = 8,
|
||||
double pixelPitch = 4,
|
||||
ApertureShape shape = ApertureShape.Circular,
|
||||
int blades = 6,
|
||||
double rotation = 0,
|
||||
double obstruction = 0,
|
||||
WavefrontAberration aberration = default)
|
||||
=> new(gridSize, diameter, kernelRadius * 2 + 1, wavelength, fNumber, pixelPitch, shape, blades, rotation, obstruction, aberration);
|
||||
|
||||
static IEnumerable<(string Name, PsfDescriptor Descriptor)> Cases()
|
||||
{
|
||||
yield return ("default", Descriptor());
|
||||
yield return ("high", Descriptor(gridSize: 512, diameter: 128));
|
||||
yield return ("draft after high", Descriptor(gridSize: 128, diameter: 32));
|
||||
yield return ("smallest grid", Descriptor(gridSize: 64, diameter: 16, kernelRadius: 3));
|
||||
yield return ("odd diameter", Descriptor(gridSize: 128, diameter: 17, aberration: new WavefrontAberration(comaVerticalWaves: 0.7)));
|
||||
yield return ("widest diameter", Descriptor(gridSize: 128, diameter: 64, kernelRadius: 9));
|
||||
yield return ("samples beyond the grid", Descriptor(pixelPitch: 100, fNumber: 0.5));
|
||||
yield return ("samples near the center", Descriptor(pixelPitch: 0.25, fNumber: 64, wavelength: 780));
|
||||
yield return ("polygon", Descriptor(shape: ApertureShape.RegularPolygon, blades: 5, rotation: 17, obstruction: 0.3));
|
||||
yield return ("closed aperture", Descriptor(gridSize: 128, diameter: 32, shape: ApertureShape.RegularPolygon, blades: 4, rotation: -357.5, obstruction: 0.95));
|
||||
yield return ("strong defocus", Descriptor(aberration: new WavefrontAberration(defocusWaves: -10)));
|
||||
yield return ("every term", Descriptor(gridSize: 512, diameter: 128, kernelRadius: 40, aberration: new WavefrontAberration(1.5, -0.8, 0.6, 2.2, -1.1, 0, 0, -0.9)));
|
||||
|
||||
var random = new Random(29);
|
||||
for (var trial = 0; trial < 120; trial++)
|
||||
{
|
||||
var gridSize = 64 << random.Next(4);
|
||||
var aberration = new WavefrontAberration(
|
||||
defocusWaves: random.NextDouble() * 6 - 3,
|
||||
astigmatismVerticalWaves: random.NextDouble() * 4 - 2,
|
||||
astigmatismObliqueWaves: random.NextDouble() * 4 - 2,
|
||||
comaHorizontalWaves: random.NextDouble() * 4 - 2,
|
||||
comaVerticalWaves: random.NextDouble() * 4 - 2,
|
||||
sphericalWaves: random.NextDouble() * 4 - 2);
|
||||
yield return ($"random {trial}", Descriptor(
|
||||
gridSize,
|
||||
16 + random.Next(gridSize / 2 - 15),
|
||||
1 + random.Next(30),
|
||||
380 + random.NextDouble() * 400,
|
||||
0.5 + random.NextDouble() * 63.5,
|
||||
0.25 + random.NextDouble() * 30,
|
||||
random.Next(2) == 0 ? ApertureShape.Circular : ApertureShape.RegularPolygon,
|
||||
3 + random.Next(30),
|
||||
random.NextDouble() * 720 - 360,
|
||||
random.NextDouble() * 0.95,
|
||||
aberration));
|
||||
}
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void TheSampledKernelIsTheGeneratedKernel()
|
||||
{
|
||||
var mismatches = new List<string>();
|
||||
foreach (var (name, descriptor) in Cases())
|
||||
{
|
||||
var size = descriptor.KernelSize;
|
||||
var sampled = kernel.AsSpan(0, size * size);
|
||||
var sampledOk = sampler.TrySample(PsfSpecification.Of(descriptor), sampled);
|
||||
var generatedOk = generator.TryGenerate(descriptor, out var result);
|
||||
|
||||
if (sampledOk != generatedOk || (generatedOk && !sampled.SequenceEqual(result!.Kernel.Values.Span)))
|
||||
mismatches.Add(name);
|
||||
}
|
||||
|
||||
Assert.Empty(mismatches);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void AClosedApertureIsNotSampled()
|
||||
{
|
||||
var descriptor = Descriptor(gridSize: 128, diameter: 32, shape: ApertureShape.RegularPolygon, blades: 4, rotation: -357.5, obstruction: 0.95);
|
||||
|
||||
Assert.False(sampler.TrySample(PsfSpecification.Of(descriptor), kernel.AsSpan(0, 31 * 31)));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void AWarmSamplerAllocatesNoManagedMemory()
|
||||
{
|
||||
var specification = PsfSpecification.Of(Descriptor());
|
||||
sampler.TrySample(in specification, kernel.AsSpan(0, 31 * 31));
|
||||
|
||||
var before = GC.GetAllocatedBytesForCurrentThread();
|
||||
for (var step = 0; step < 4; step++)
|
||||
{
|
||||
var animated = specification with { Aberration = new WavefrontAberration(defocusWaves: step * 0.25) };
|
||||
sampler.TrySample(in animated, kernel.AsSpan(0, 31 * 31));
|
||||
}
|
||||
|
||||
Assert.Equal(0, GC.GetAllocatedBytesForCurrentThread() - before);
|
||||
}
|
||||
}
|
||||
@@ -106,6 +106,32 @@ public sealed class SeparableKernelTests
|
||||
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;
|
||||
|
||||
@@ -184,8 +184,8 @@ public sealed class WaveOpticsEffectProcessorTests
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[InlineData(WaveOpticsSettings.MaximumCanvasSize - WaveOpticsSettings.CanvasMargin * 2, true)]
|
||||
[InlineData(WaveOpticsSettings.MaximumCanvasSize - WaveOpticsSettings.CanvasMargin * 2 + 1, false)]
|
||||
[InlineData(WaveOpticsSettings.MaximumCanvasSize - WaveOpticsSettings.DefaultCanvasMargin * 2, true)]
|
||||
[InlineData(WaveOpticsSettings.MaximumCanvasSize - WaveOpticsSettings.DefaultCanvasMargin * 2 + 1, false)]
|
||||
public void OnlyAnImageThatLeavesRoomForTheMarginIsBlurred(int width, bool blurred)
|
||||
{
|
||||
using var devices = new GraphicsDevices();
|
||||
@@ -204,6 +204,29 @@ public sealed class WaveOpticsEffectProcessorTests
|
||||
AssertSameAsSource(rendering, source);
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[InlineData(40, 8192 - 40 * 2, true)]
|
||||
[InlineData(40, 8192 - 40 * 2 + 1, false)]
|
||||
[InlineData(63, 8192 - 64 * 2, true)]
|
||||
[InlineData(63, 8192 - 64 * 2 + 1, false)]
|
||||
public void AWideKernelRadiusKeepsRoomForItsOwnMargin(int radius, int width, bool blurred)
|
||||
{
|
||||
using var devices = new GraphicsDevices();
|
||||
using var context = devices.CreateContext();
|
||||
if (blurred)
|
||||
RequireInterop(context);
|
||||
using var source = SourceImage.Solid(context, width, 8, Gray);
|
||||
using var processor = new WaveOpticsEffect { KernelRadius = radius }.CreateVideoEffect(context);
|
||||
processor.SetInput(source.Bitmap);
|
||||
|
||||
var rendering = RenderFrame(context, processor, 0);
|
||||
|
||||
if (blurred)
|
||||
Assert.True(HasLightOutside(rendering, source));
|
||||
else
|
||||
AssertSameAsSource(rendering, source);
|
||||
}
|
||||
|
||||
public static readonly TheoryData<string, Action<WaveOpticsEffect>> Animations = new()
|
||||
{
|
||||
{ nameof(WaveOpticsEffect.Amount), effect => effect.Amount.CopyFrom(Linear(20d, 100d)) },
|
||||
@@ -378,7 +401,7 @@ public sealed class WaveOpticsEffectProcessorTests
|
||||
|
||||
[Theory]
|
||||
[InlineData(Size, Size, false)]
|
||||
[InlineData(WaveOpticsSettings.MaximumCanvasSize - WaveOpticsSettings.CanvasMargin * 2 + 1, 8, true)]
|
||||
[InlineData(WaveOpticsSettings.MaximumCanvasSize - WaveOpticsSettings.DefaultCanvasMargin * 2 + 1, 8, true)]
|
||||
public void TheBlurReturnsAfterAnImageThatPassedThrough(int width, int height, bool opaque)
|
||||
{
|
||||
using var devices = new GraphicsDevices();
|
||||
|
||||
@@ -63,9 +63,11 @@ public sealed class WaveOpticsEffectTests
|
||||
[InlineData(1, 1)]
|
||||
[InlineData(7, 7)]
|
||||
[InlineData(15, 15)]
|
||||
[InlineData(16, 15)]
|
||||
[InlineData(int.MaxValue, 15)]
|
||||
public void KernelRadiusStaysBetweenOneAndFifteenPixels(int value, int expected)
|
||||
[InlineData(16, 16)]
|
||||
[InlineData(63, 63)]
|
||||
[InlineData(64, 63)]
|
||||
[InlineData(int.MaxValue, 63)]
|
||||
public void KernelRadiusStaysBetweenOneAndSixtyThreePixels(int value, int expected)
|
||||
{
|
||||
var effect = new WaveOpticsEffect { KernelRadius = 8 };
|
||||
|
||||
@@ -111,12 +113,12 @@ public sealed class WaveOpticsEffectTests
|
||||
[Fact]
|
||||
public void AssigningAnUnchangedOrClampedValueDoesNotNotify()
|
||||
{
|
||||
var effect = new WaveOpticsEffect();
|
||||
var effect = new WaveOpticsEffect { KernelRadius = WaveOpticsSettings.MaximumKernelRadius };
|
||||
var changed = new List<string?>();
|
||||
effect.PropertyChanged += (_, e) => changed.Add(e.PropertyName);
|
||||
|
||||
effect.KernelRadius = 15;
|
||||
effect.KernelRadius = 16;
|
||||
effect.KernelRadius = WaveOpticsSettings.MaximumKernelRadius;
|
||||
effect.KernelRadius = WaveOpticsSettings.MaximumKernelRadius + 1;
|
||||
effect.Quality = WaveOpticsQuality.Standard;
|
||||
effect.ApertureShape = WaveOpticsApertureShape.Circular;
|
||||
effect.BladeCount = 6;
|
||||
@@ -223,7 +225,7 @@ public sealed class WaveOpticsEffectTests
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[InlineData(nameof(WaveOpticsEffect.KernelRadius), "px", 1d, 15d, 1, 15, 15)]
|
||||
[InlineData(nameof(WaveOpticsEffect.KernelRadius), "px", 1d, 63d, 1, 63, 15)]
|
||||
[InlineData(nameof(WaveOpticsEffect.BladeCount), "", 3d, 16d, 3, 32, 6)]
|
||||
public void WholeNumberParametersAreEditedWithTextBoxSliders(string property, string unit, double sliderMinimum, double sliderMaximum, int minimum, int maximum, int defaultValue)
|
||||
{
|
||||
|
||||
@@ -246,6 +246,21 @@ public sealed class WaveOpticsPipelineTests
|
||||
Assert.Equal((40 - 5, 40 - 5, 56 + 5, 56 + 5), bounds);
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[InlineData(40)]
|
||||
[InlineData(WaveOpticsSettings.MaximumKernelRadius)]
|
||||
public void AWideKernelRadiusCarriesTheBlurToItsEdge(int radius)
|
||||
{
|
||||
using var pipeline = CreatePipeline();
|
||||
var start = radius + 8;
|
||||
var size = start * 2 + 32;
|
||||
var source = Square(size, size, start, start, 32, 32);
|
||||
|
||||
var bounds = LitBounds(Render(pipeline, source, size, size, Parameters(gain: 4f, kernelRadius: radius, fNumber: 32f, pixelPitch: 0.25f)), size);
|
||||
|
||||
Assert.Equal((start - radius, start - radius, start + 32 + radius, start + 32 + radius), bounds);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void TheGainScalesTheBlurredImage()
|
||||
{
|
||||
@@ -310,6 +325,33 @@ public sealed class WaveOpticsPipelineTests
|
||||
Assert.Equal(0, minimum);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void ChangingTheOpticsOnAWarmPipelineAllocatesNoManagedMemory()
|
||||
{
|
||||
using var pipeline = CreatePipeline();
|
||||
var source = Square(64, 64, 24, 24, 16, 16);
|
||||
var destination = new int[source.Length];
|
||||
for (var iteration = 0; iteration < 4; iteration++)
|
||||
{
|
||||
var parameters = Parameters(defocus: 0.25f * iteration);
|
||||
pipeline.Process(source, destination, 64, 64, in parameters);
|
||||
}
|
||||
GC.Collect();
|
||||
GC.WaitForPendingFinalizers();
|
||||
GC.Collect();
|
||||
|
||||
var minimum = long.MaxValue;
|
||||
for (var iteration = 0; iteration < 16; iteration++)
|
||||
{
|
||||
var parameters = Parameters(defocus: 0.25f * (iteration % 4), comaHorizontal: 0.1f * (iteration % 3));
|
||||
var before = GC.GetAllocatedBytesForCurrentThread();
|
||||
pipeline.Process(source, destination, 64, 64, in parameters);
|
||||
minimum = Math.Min(minimum, GC.GetAllocatedBytesForCurrentThread() - before);
|
||||
}
|
||||
|
||||
Assert.Equal(0, minimum);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void SharedTexturesProduceTheSameImageAsPackedBuffers()
|
||||
{
|
||||
@@ -483,4 +525,54 @@ public sealed class WaveOpticsPipelineTests
|
||||
Upload(sourceTexture, Square(128, 128, 32, 32, 32, 32));
|
||||
Assert.True(pipeline.Simulate(sourceTexture, 128, 128, 0, 0, 128, 128, in opticsChanged));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void TheBladesOfACircularApertureDoNotRedoTheConvolution()
|
||||
{
|
||||
using var pipeline = CreatePipeline();
|
||||
using var fresh = CreatePipeline();
|
||||
var device = GraphicsDevice.GetDefault();
|
||||
using var sourceTexture = device.AllocateReadWriteTexture2D<Bgra32, Float4>(96, 96);
|
||||
using var freshTexture = device.AllocateReadWriteTexture2D<Bgra32, Float4>(96, 96);
|
||||
var source = Square(96, 96, 32, 32, 32, 32);
|
||||
Upload(sourceTexture, source);
|
||||
Upload(freshTexture, source);
|
||||
var circular = Parameters(defocus: 0.5f);
|
||||
Assert.True(pipeline.Simulate(sourceTexture, 96, 96, 0, 0, 96, 96, in circular));
|
||||
|
||||
var bladesChanged = circular with { Psf = circular.Psf with { BladeCount = 9, BladeRotation = 40f } };
|
||||
Assert.False(pipeline.Simulate(sourceTexture, 96, 96, 0, 0, 96, 96, in bladesChanged));
|
||||
Assert.Equal(RenderSplit(fresh, freshTexture, 96, 96, bladesChanged), RenderSplit(pipeline, sourceTexture, 96, 96, bladesChanged));
|
||||
|
||||
var polygon = bladesChanged with { Psf = bladesChanged.Psf with { ApertureShape = WaveOpticsApertureShape.RegularPolygon } };
|
||||
Assert.True(pipeline.Simulate(sourceTexture, 96, 96, 0, 0, 96, 96, in polygon));
|
||||
var polygonBladesChanged = polygon with { Psf = polygon.Psf with { BladeCount = 5 } };
|
||||
Assert.True(pipeline.Simulate(sourceTexture, 96, 96, 0, 0, 96, 96, in polygonBladesChanged));
|
||||
var polygonRotated = polygonBladesChanged with { Psf = polygonBladesChanged.Psf with { BladeRotation = 10f } };
|
||||
Assert.True(pipeline.Simulate(sourceTexture, 96, 96, 0, 0, 96, 96, in polygonRotated));
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[InlineData(36, 20)]
|
||||
[InlineData(16, 0)]
|
||||
[InlineData(15, 7)]
|
||||
public void ASinglePixelAnywhereInARowIsNoticed(int x, int y)
|
||||
{
|
||||
using var pipeline = CreatePipeline();
|
||||
var device = GraphicsDevice.GetDefault();
|
||||
using var sourceTexture = device.AllocateReadWriteTexture2D<Bgra32, Float4>(37, 21);
|
||||
var pixels = new int[37 * 21];
|
||||
pixels[10 * 37 + 20] = Opaque;
|
||||
Upload(sourceTexture, pixels);
|
||||
var parameters = Parameters(kernelRadius: 1);
|
||||
Assert.True(pipeline.Simulate(sourceTexture, 37, 21, 0, 0, 37, 21, in parameters));
|
||||
|
||||
pixels[y * 37 + x] = Opaque;
|
||||
Upload(sourceTexture, pixels);
|
||||
|
||||
Assert.True(pipeline.Simulate(sourceTexture, 37, 21, 0, 0, 37, 21, in parameters));
|
||||
Assert.True(pipeline.TryGetVisibleBounds(37, 21, in parameters, out var rect));
|
||||
Assert.InRange(x, rect.X, rect.X + rect.Width - 1);
|
||||
Assert.InRange(y, rect.Y, rect.Y + rect.Height - 1);
|
||||
}
|
||||
}
|
||||
@@ -71,13 +71,28 @@ public sealed class WaveOpticsSettingsTests
|
||||
Assert.True(separable.ResidualEnergyRatio <= WaveOpticsSettings.SeparableResidualRatio, $"{aberrationName}: {separable.ResidualEnergyRatio}");
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void TheCanvasMarginHoldsTheWidestBlurOnAFourPixelGrid()
|
||||
[Theory]
|
||||
[InlineData(WaveOpticsSettings.MinimumKernelRadius)]
|
||||
[InlineData(WaveOpticsSettings.DefaultKernelRadius)]
|
||||
[InlineData(16)]
|
||||
[InlineData(17)]
|
||||
[InlineData(48)]
|
||||
[InlineData(WaveOpticsSettings.MaximumKernelRadius)]
|
||||
public void TheCanvasMarginHoldsTheBlurOnAFourPixelGrid(int radius)
|
||||
{
|
||||
Assert.True(WaveOpticsSettings.CanvasMargin >= WaveOpticsSettings.MaximumKernelRadius);
|
||||
Assert.Equal(0, WaveOpticsSettings.CanvasMargin % 4);
|
||||
var margin = WaveOpticsSettings.GetCanvasMargin(radius);
|
||||
|
||||
Assert.InRange(margin, radius, Math.Max(radius + 3, WaveOpticsSettings.DefaultCanvasMargin));
|
||||
Assert.Equal(0, margin % 4);
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[InlineData(1)]
|
||||
[InlineData(5)]
|
||||
[InlineData(15)]
|
||||
public void UpToTheDefaultRadiusTheCanvasKeepsItsMargin(int radius)
|
||||
=> Assert.Equal(16, WaveOpticsSettings.GetCanvasMargin(radius));
|
||||
|
||||
[Fact]
|
||||
public void EveryScratchValueHasItsOwnSlot()
|
||||
{
|
||||
|
||||
@@ -42,9 +42,9 @@ public sealed class WaveOpticsEffect : VideoEffectBase
|
||||
[Display(GroupName = nameof(Texts.OpticsGroup), Name = nameof(Texts.KernelRadius), Description = nameof(Texts.KernelRadiusDescription), Order = 13, ResourceType = typeof(Texts))]
|
||||
[TextBoxSlider("F0", "px", WaveOpticsSettings.MinimumKernelRadius, WaveOpticsSettings.MaximumKernelRadius)]
|
||||
[Range(WaveOpticsSettings.MinimumKernelRadius, WaveOpticsSettings.MaximumKernelRadius)]
|
||||
[DefaultValue(WaveOpticsSettings.MaximumKernelRadius)]
|
||||
[DefaultValue(WaveOpticsSettings.DefaultKernelRadius)]
|
||||
public int KernelRadius { get => _kernelRadius; set => Set(ref _kernelRadius, Math.Clamp(value, WaveOpticsSettings.MinimumKernelRadius, WaveOpticsSettings.MaximumKernelRadius)); }
|
||||
private int _kernelRadius = WaveOpticsSettings.MaximumKernelRadius;
|
||||
private int _kernelRadius = WaveOpticsSettings.DefaultKernelRadius;
|
||||
|
||||
[Display(GroupName = nameof(Texts.OpticsGroup), Name = nameof(Texts.Quality), Description = nameof(Texts.QualityDescription), Order = 14, ResourceType = typeof(Texts))]
|
||||
[EnumComboBox]
|
||||
|
||||
@@ -106,7 +106,7 @@ internal sealed class WaveOpticsEffectProcessor : VideoEffectProcessorBase
|
||||
return effectDescription.DrawDescription;
|
||||
}
|
||||
|
||||
var margin = WaveOpticsSettings.CanvasMargin;
|
||||
var margin = WaveOpticsSettings.GetCanvasMargin(parameters.Psf.KernelRadius);
|
||||
var longSide = Math.Max(widthValue, heightValue);
|
||||
if ((WaveOpticsSettings.MaximumCanvasSize - longSide) / 2d < margin)
|
||||
{
|
||||
|
||||
@@ -178,7 +178,7 @@ internal static class FastFourierTransform
|
||||
}
|
||||
|
||||
static Twiddles GetTwiddles(int count, bool inverse) =>
|
||||
TwiddleCache.GetOrAdd(((long)count << 1) | (inverse ? 1L : 0L), _ => new Twiddles(count, inverse));
|
||||
TwiddleCache.GetOrAdd(((long)count << 1) | (inverse ? 1L : 0L), static key => new Twiddles((int)(key >> 1), (key & 1L) != 0));
|
||||
|
||||
sealed class Twiddles
|
||||
{
|
||||
|
||||
@@ -0,0 +1,95 @@
|
||||
using WaveOptics.Fourier;
|
||||
|
||||
namespace WaveOptics.Optics;
|
||||
|
||||
internal sealed class FraunhoferKernelSampler
|
||||
{
|
||||
double[] real = [];
|
||||
double[] imaginary = [];
|
||||
double[] intensity = [];
|
||||
double[] columnReal = [];
|
||||
double[] columnImaginary = [];
|
||||
bool[] sampledColumns = [];
|
||||
|
||||
public bool TrySample(in PsfSpecification specification, Span<double> kernel)
|
||||
{
|
||||
var gridSize = specification.PupilGridSize;
|
||||
EnsureCapacity(gridSize);
|
||||
|
||||
var center = gridSize / 2;
|
||||
var reach = (int)(specification.PupilDiameterSamples / 2d);
|
||||
var firstRow = Math.Max(center - reach, 0);
|
||||
var lastRow = Math.Min(center + reach, gridSize - 1);
|
||||
if (FraunhoferPsfGenerator.BuildPupil(in specification, real, imaginary, firstRow, lastRow) == 0)
|
||||
return false;
|
||||
|
||||
for (var row = firstRow; row <= lastRow; row++)
|
||||
FastFourierTransform.Forward(real.AsSpan(row * gridSize, gridSize), imaginary.AsSpan(row * gridSize, gridSize));
|
||||
|
||||
MarkSampledColumns(in specification, center);
|
||||
for (var shiftedColumn = 0; shiftedColumn < gridSize; shiftedColumn++)
|
||||
{
|
||||
if (!sampledColumns[shiftedColumn])
|
||||
continue;
|
||||
|
||||
var column = (shiftedColumn + center) % gridSize;
|
||||
for (var row = 0; row < gridSize; row++)
|
||||
{
|
||||
var open = row >= firstRow && row <= lastRow;
|
||||
columnReal[row] = open ? real[row * gridSize + column] : 0d;
|
||||
columnImaginary[row] = open ? imaginary[row * gridSize + column] : 0d;
|
||||
}
|
||||
|
||||
FastFourierTransform.Forward(columnReal.AsSpan(0, gridSize), columnImaginary.AsSpan(0, gridSize));
|
||||
for (var row = 0; row < gridSize; row++)
|
||||
{
|
||||
var a = columnReal[row];
|
||||
var b = columnImaginary[row];
|
||||
intensity[(row + center) % gridSize * gridSize + shiftedColumn] = a * a + b * b;
|
||||
}
|
||||
}
|
||||
|
||||
var energy = FraunhoferPsfGenerator.SampleKernel(in specification, intensity, kernel);
|
||||
if (!double.IsFinite(energy) || energy <= 0)
|
||||
return false;
|
||||
|
||||
for (var index = 0; index < kernel.Length; index++)
|
||||
kernel[index] /= energy;
|
||||
return true;
|
||||
}
|
||||
|
||||
void MarkSampledColumns(in PsfSpecification specification, int center)
|
||||
{
|
||||
var gridSize = specification.PupilGridSize;
|
||||
var focalPlaneSamplePitch = FraunhoferPsfGenerator.FocalPlaneSamplePitch(in specification);
|
||||
var kernelRadius = specification.KernelSize / 2;
|
||||
Array.Clear(sampledColumns, 0, gridSize);
|
||||
for (var index = 0; index < specification.KernelSize; index++)
|
||||
{
|
||||
var position = FraunhoferPsfGenerator.SamplePosition(index, kernelRadius, center, specification.SensorPixelPitchMicrometers, focalPlaneSamplePitch);
|
||||
if (position < 0 || position > gridSize - 1)
|
||||
continue;
|
||||
|
||||
var lower = (int)Math.Floor(position);
|
||||
sampledColumns[lower] = true;
|
||||
sampledColumns[Math.Min(lower + 1, gridSize - 1)] = true;
|
||||
}
|
||||
}
|
||||
|
||||
void EnsureCapacity(int gridSize)
|
||||
{
|
||||
var area = gridSize * gridSize;
|
||||
if (real.Length < area)
|
||||
{
|
||||
real = new double[area];
|
||||
imaginary = new double[area];
|
||||
intensity = new double[area];
|
||||
}
|
||||
if (columnReal.Length < gridSize)
|
||||
{
|
||||
columnReal = new double[gridSize];
|
||||
columnImaginary = new double[gridSize];
|
||||
sampledColumns = new bool[gridSize];
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -33,14 +33,15 @@ public sealed class FraunhoferPsfGenerator : IPsfGenerator
|
||||
ArgumentNullException.ThrowIfNull(descriptor);
|
||||
|
||||
result = null;
|
||||
var gridSize = descriptor.PupilGridSize;
|
||||
var specification = PsfSpecification.Of(descriptor);
|
||||
var gridSize = specification.PupilGridSize;
|
||||
var area = gridSize * gridSize;
|
||||
var real = ArrayPool<double>.Shared.Rent(area);
|
||||
var imaginary = ArrayPool<double>.Shared.Rent(area);
|
||||
var intensity = ArrayPool<double>.Shared.Rent(area);
|
||||
try
|
||||
{
|
||||
var openSampleCount = BuildPupil(descriptor, real, imaginary);
|
||||
var openSampleCount = BuildPupil(in specification, real, imaginary, 0, gridSize - 1);
|
||||
if (openSampleCount == 0)
|
||||
return false;
|
||||
|
||||
@@ -50,33 +51,16 @@ public sealed class FraunhoferPsfGenerator : IPsfGenerator
|
||||
if (!double.IsFinite(fullEnergy) || fullEnergy <= 0)
|
||||
return false;
|
||||
|
||||
var wavelengthMicrometers = descriptor.WavelengthNanometers / 1000d;
|
||||
var focalPlaneSamplePitch = wavelengthMicrometers * descriptor.FNumber * descriptor.PupilDiameterSamples / gridSize;
|
||||
var center = gridSize / 2;
|
||||
var kernelSize = descriptor.KernelSize;
|
||||
var kernelRadius = kernelSize / 2;
|
||||
var kernelSize = specification.KernelSize;
|
||||
var kernel = new double[kernelSize * kernelSize];
|
||||
var rawKernelEnergy = 0d;
|
||||
|
||||
for (var y = 0; y < kernelSize; y++)
|
||||
{
|
||||
var sampleY = center + (y - kernelRadius) * descriptor.SensorPixelPitchMicrometers / focalPlaneSamplePitch;
|
||||
for (var x = 0; x < kernelSize; x++)
|
||||
{
|
||||
var sampleX = center + (x - kernelRadius) * descriptor.SensorPixelPitchMicrometers / focalPlaneSamplePitch;
|
||||
var value = SampleBilinear(intensity, gridSize, sampleX, sampleY);
|
||||
kernel[y * kernelSize + x] = value;
|
||||
rawKernelEnergy += value;
|
||||
}
|
||||
}
|
||||
|
||||
var rawKernelEnergy = SampleKernel(in specification, intensity, kernel);
|
||||
if (!double.IsFinite(rawKernelEnergy) || rawKernelEnergy <= 0)
|
||||
return false;
|
||||
|
||||
var psfKernel = new PsfKernel(kernelSize, kernel);
|
||||
var diagnostics = new PsfDiagnostics(
|
||||
openSampleCount,
|
||||
focalPlaneSamplePitch,
|
||||
FocalPlaneSamplePitch(in specification),
|
||||
rawKernelEnergy / fullEnergy,
|
||||
Peak(psfKernel.Values.Span));
|
||||
result = new PsfGenerationResult(psfKernel, diagnostics);
|
||||
@@ -90,15 +74,15 @@ public sealed class FraunhoferPsfGenerator : IPsfGenerator
|
||||
}
|
||||
}
|
||||
|
||||
static int BuildPupil(PsfDescriptor descriptor, double[] real, double[] imaginary)
|
||||
internal static int BuildPupil(in PsfSpecification specification, double[] real, double[] imaginary, int firstRow, int lastRow)
|
||||
{
|
||||
var gridSize = descriptor.PupilGridSize;
|
||||
var gridSize = specification.PupilGridSize;
|
||||
var center = gridSize / 2;
|
||||
var pupilRadius = descriptor.PupilDiameterSamples / 2d;
|
||||
var rotation = descriptor.BladeRotationDegrees * Math.PI / 180d;
|
||||
var pupilRadius = specification.PupilDiameterSamples / 2d;
|
||||
var rotation = specification.BladeRotationDegrees * Math.PI / 180d;
|
||||
var openSampleCount = 0;
|
||||
|
||||
for (var y = 0; y < gridSize; y++)
|
||||
for (var y = firstRow; y <= lastRow; y++)
|
||||
{
|
||||
var normalizedY = (y - center) / pupilRadius;
|
||||
var row = y * gridSize;
|
||||
@@ -106,9 +90,9 @@ public sealed class FraunhoferPsfGenerator : IPsfGenerator
|
||||
{
|
||||
var index = row + x;
|
||||
var normalizedX = (x - center) / pupilRadius;
|
||||
if (IsInsideAperture(normalizedX, normalizedY, descriptor, rotation))
|
||||
if (IsInsideAperture(normalizedX, normalizedY, in specification, rotation))
|
||||
{
|
||||
var waves = ZernikeWavefront.Evaluate(normalizedX, normalizedY, descriptor.Aberration);
|
||||
var waves = ZernikeWavefront.Evaluate(normalizedX, normalizedY, specification.Aberration);
|
||||
var (sin, cos) = Math.SinCos(TwoPi * waves);
|
||||
real[index] = cos;
|
||||
imaginary[index] = sin;
|
||||
@@ -125,6 +109,39 @@ public sealed class FraunhoferPsfGenerator : IPsfGenerator
|
||||
return openSampleCount;
|
||||
}
|
||||
|
||||
internal static double FocalPlaneSamplePitch(in PsfSpecification specification)
|
||||
{
|
||||
var wavelengthMicrometers = specification.WavelengthNanometers / 1000d;
|
||||
return wavelengthMicrometers * specification.FNumber * specification.PupilDiameterSamples / specification.PupilGridSize;
|
||||
}
|
||||
|
||||
internal static double SamplePosition(int index, int kernelRadius, int center, double pixelPitch, double focalPlaneSamplePitch)
|
||||
=> center + (index - kernelRadius) * pixelPitch / focalPlaneSamplePitch;
|
||||
|
||||
internal static double SampleKernel(in PsfSpecification specification, double[] intensity, Span<double> kernel)
|
||||
{
|
||||
var gridSize = specification.PupilGridSize;
|
||||
var focalPlaneSamplePitch = FocalPlaneSamplePitch(in specification);
|
||||
var center = gridSize / 2;
|
||||
var kernelSize = specification.KernelSize;
|
||||
var kernelRadius = kernelSize / 2;
|
||||
var rawKernelEnergy = 0d;
|
||||
|
||||
for (var y = 0; y < kernelSize; y++)
|
||||
{
|
||||
var sampleY = SamplePosition(y, kernelRadius, center, specification.SensorPixelPitchMicrometers, focalPlaneSamplePitch);
|
||||
for (var x = 0; x < kernelSize; x++)
|
||||
{
|
||||
var sampleX = SamplePosition(x, kernelRadius, center, specification.SensorPixelPitchMicrometers, focalPlaneSamplePitch);
|
||||
var value = SampleBilinear(intensity, gridSize, sampleX, sampleY);
|
||||
kernel[y * kernelSize + x] = value;
|
||||
rawKernelEnergy += value;
|
||||
}
|
||||
}
|
||||
|
||||
return rawKernelEnergy;
|
||||
}
|
||||
|
||||
static double ComputeShiftedIntensity(double[] real, double[] imaginary, double[] intensity, int gridSize)
|
||||
{
|
||||
var center = gridSize / 2;
|
||||
@@ -189,22 +206,22 @@ public sealed class FraunhoferPsfGenerator : IPsfGenerator
|
||||
return peak;
|
||||
}
|
||||
|
||||
static bool IsInsideAperture(double x, double y, PsfDescriptor descriptor, double rotation)
|
||||
static bool IsInsideAperture(double x, double y, in PsfSpecification specification, double rotation)
|
||||
{
|
||||
var radiusSquared = x * x + y * y;
|
||||
var obstructionSquared = descriptor.CentralObstructionRatio * descriptor.CentralObstructionRatio;
|
||||
var obstructionSquared = specification.CentralObstructionRatio * specification.CentralObstructionRatio;
|
||||
if (radiusSquared > 1d || radiusSquared < obstructionSquared)
|
||||
return false;
|
||||
if (descriptor.ApertureShape == ApertureShape.Circular)
|
||||
if (specification.ApertureShape == ApertureShape.Circular)
|
||||
return true;
|
||||
|
||||
var radius = Math.Sqrt(radiusSquared);
|
||||
if (radius == 0)
|
||||
return descriptor.CentralObstructionRatio == 0;
|
||||
var sector = TwoPi / descriptor.BladeCount;
|
||||
return specification.CentralObstructionRatio == 0;
|
||||
var sector = TwoPi / specification.BladeCount;
|
||||
var angle = Math.Atan2(y, x) - rotation;
|
||||
var folded = angle - sector * Math.Round(angle / sector);
|
||||
var boundary = Math.Cos(Math.PI / descriptor.BladeCount) / Math.Cos(folded);
|
||||
var boundary = Math.Cos(Math.PI / specification.BladeCount) / Math.Cos(folded);
|
||||
return radius <= boundary;
|
||||
}
|
||||
|
||||
|
||||
@@ -0,0 +1,31 @@
|
||||
using WaveOptics.Abstractions;
|
||||
|
||||
namespace WaveOptics.Optics;
|
||||
|
||||
internal readonly record struct PsfSpecification(
|
||||
int PupilGridSize,
|
||||
int PupilDiameterSamples,
|
||||
int KernelSize,
|
||||
double WavelengthNanometers,
|
||||
double FNumber,
|
||||
double SensorPixelPitchMicrometers,
|
||||
ApertureShape ApertureShape,
|
||||
int BladeCount,
|
||||
double BladeRotationDegrees,
|
||||
double CentralObstructionRatio,
|
||||
WavefrontAberration Aberration)
|
||||
{
|
||||
public static PsfSpecification Of(PsfDescriptor descriptor)
|
||||
=> new(
|
||||
descriptor.PupilGridSize,
|
||||
descriptor.PupilDiameterSamples,
|
||||
descriptor.KernelSize,
|
||||
descriptor.WavelengthNanometers,
|
||||
descriptor.FNumber,
|
||||
descriptor.SensorPixelPitchMicrometers,
|
||||
descriptor.ApertureShape,
|
||||
descriptor.BladeCount,
|
||||
descriptor.BladeRotationDegrees,
|
||||
descriptor.CentralObstructionRatio,
|
||||
descriptor.Aberration);
|
||||
}
|
||||
@@ -1,44 +1,70 @@
|
||||
using System.Numerics;
|
||||
|
||||
namespace WaveOptics.Optics;
|
||||
|
||||
internal readonly struct SeparableKernel
|
||||
internal sealed class SeparableKernel
|
||||
{
|
||||
public int Size { get; }
|
||||
public int Rank { get; }
|
||||
public double ResidualEnergyRatio { get; }
|
||||
public double Sum { get; }
|
||||
public float[] Horizontal { get; }
|
||||
public float[] Vertical { get; }
|
||||
readonly Comparison<int> descending;
|
||||
double[] work = [];
|
||||
double[] basis = [];
|
||||
double[] singularValues = [];
|
||||
int[] order = [];
|
||||
float[] horizontal = [];
|
||||
float[] vertical = [];
|
||||
|
||||
SeparableKernel(int size, int rank, double residualEnergyRatio, double sum, float[] horizontal, float[] vertical)
|
||||
public SeparableKernel()
|
||||
{
|
||||
Size = size;
|
||||
Rank = rank;
|
||||
ResidualEnergyRatio = residualEnergyRatio;
|
||||
Sum = sum;
|
||||
Horizontal = horizontal;
|
||||
Vertical = vertical;
|
||||
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 work = new double[size * size];
|
||||
for (var index = 0; index < work.Length; index++)
|
||||
work[index] = kernel[index];
|
||||
var basis = new double[size * size];
|
||||
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 singularValues = new double[size];
|
||||
var order = new int[size];
|
||||
var totalEnergy = 0d;
|
||||
for (var column = 0; column < size; column++)
|
||||
{
|
||||
var norm = 0d;
|
||||
for (var row = 0; row < size; row++)
|
||||
{
|
||||
var value = work[row * size + column];
|
||||
var value = work[column * size + row];
|
||||
norm += value * value;
|
||||
}
|
||||
singularValues[column] = Math.Sqrt(norm);
|
||||
@@ -46,7 +72,7 @@ internal readonly struct SeparableKernel
|
||||
totalEnergy += norm;
|
||||
}
|
||||
|
||||
Array.Sort(order, (left, right) => singularValues[right].CompareTo(singularValues[left]));
|
||||
Array.Sort(order, descending);
|
||||
|
||||
var largest = singularValues[order[0]];
|
||||
var significant = 0;
|
||||
@@ -76,8 +102,6 @@ internal readonly struct SeparableKernel
|
||||
retainedEnergy += singularValues[order[i]] * singularValues[order[i]];
|
||||
var residual = totalEnergy > 0 ? Math.Max(0d, (totalEnergy - retainedEnergy) / totalEnergy) : 0d;
|
||||
|
||||
var horizontal = new float[rank * size];
|
||||
var vertical = new float[rank * size];
|
||||
var sum = 0d;
|
||||
for (var term = 0; term < rank; term++)
|
||||
{
|
||||
@@ -89,15 +113,18 @@ internal readonly struct SeparableKernel
|
||||
var verticalSum = 0d;
|
||||
for (var k = 0; k < size; k++)
|
||||
{
|
||||
horizontal[horizontalBase + k] = (float)(basis[k * size + column]);
|
||||
vertical[horizontalBase + k] = (float)(work[k * size + column] * inverse * singularValue);
|
||||
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;
|
||||
}
|
||||
|
||||
return new SeparableKernel(size, rank, residual, sum, horizontal, vertical);
|
||||
Size = size;
|
||||
Rank = rank;
|
||||
ResidualEnergyRatio = residual;
|
||||
Sum = sum;
|
||||
}
|
||||
|
||||
static void OrthogonalizeColumns(double[] work, double[] basis, int size)
|
||||
@@ -109,15 +136,18 @@ internal readonly struct SeparableKernel
|
||||
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 = work[k * size + p];
|
||||
var wq = work[k * size + q];
|
||||
var wp = workP[k];
|
||||
var wq = workQ[k];
|
||||
alpha += wp * wp;
|
||||
beta += wq * wq;
|
||||
gamma += wp * wq;
|
||||
@@ -134,22 +164,38 @@ internal readonly struct SeparableKernel
|
||||
var c = 1d / Math.Sqrt(1d + t * t);
|
||||
var s = c * t;
|
||||
|
||||
for (var k = 0; k < size; k++)
|
||||
{
|
||||
var index = k * size;
|
||||
var wp = work[index + p];
|
||||
var wq = work[index + q];
|
||||
work[index + p] = c * wp - s * wq;
|
||||
work[index + q] = s * wp + c * wq;
|
||||
var vp = basis[index + p];
|
||||
var vq = basis[index + q];
|
||||
basis[index + p] = c * vp - s * vq;
|
||||
basis[index + q] = s * vp + c * vq;
|
||||
}
|
||||
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;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -62,29 +62,46 @@ internal readonly partial struct SourceHashShader(
|
||||
|
||||
public void Execute()
|
||||
{
|
||||
var x = ThreadIds.X;
|
||||
var first = ThreadIds.X * WaveOpticsSettings.SourceHashSpan;
|
||||
var y = ThreadIds.Y;
|
||||
if (x >= sourceWidth || y >= sourceHeight)
|
||||
if (first >= sourceWidth || y >= sourceHeight)
|
||||
return;
|
||||
|
||||
var color = source[ThreadIds.XY];
|
||||
var quantized = ((uint)(color.X * 255f + 0.5f) << 24)
|
||||
| ((uint)(color.Y * 255f + 0.5f) << 16)
|
||||
| ((uint)(color.Z * 255f + 0.5f) << 8)
|
||||
| (uint)(color.W * 255f + 0.5f);
|
||||
if (quantized == 0u)
|
||||
return;
|
||||
var count = 0;
|
||||
var sum = 0;
|
||||
var mix = 0;
|
||||
var minimumX = 2147483647;
|
||||
var maximumX = -2147483648;
|
||||
var last = Hlsl.Min(first + WaveOpticsSettings.SourceHashSpan, sourceWidth);
|
||||
for (var x = first; x < last; x++)
|
||||
{
|
||||
var color = source[new Int2(x, y)];
|
||||
var quantized = ((uint)(color.X * 255f + 0.5f) << 24)
|
||||
| ((uint)(color.Y * 255f + 0.5f) << 16)
|
||||
| ((uint)(color.Z * 255f + 0.5f) << 8)
|
||||
| (uint)(color.W * 255f + 0.5f);
|
||||
if (quantized == 0u)
|
||||
continue;
|
||||
|
||||
var mixed = ((uint)(y * sourceWidth + x) * 0x9E3779B9u) ^ (quantized * 0x85EBCA6Bu);
|
||||
mixed ^= mixed >> 16;
|
||||
mixed *= 0x85EBCA6Bu;
|
||||
mixed ^= mixed >> 13;
|
||||
Hlsl.InterlockedAdd(ref scratch[WaveOpticsSettings.ScratchHashSum], (int)mixed);
|
||||
Hlsl.InterlockedXor(ref scratch[WaveOpticsSettings.ScratchHashMix], (int)(mixed * 0xC2B2AE35u));
|
||||
Hlsl.InterlockedAdd(ref scratch[WaveOpticsSettings.ScratchLitCount], 1);
|
||||
Hlsl.InterlockedMin(ref scratch[WaveOpticsSettings.ScratchBoundsMinX], sourceX + x);
|
||||
var mixed = ((uint)(y * sourceWidth + x) * 0x9E3779B9u) ^ (quantized * 0x85EBCA6Bu);
|
||||
mixed ^= mixed >> 16;
|
||||
mixed *= 0x85EBCA6Bu;
|
||||
mixed ^= mixed >> 13;
|
||||
sum += (int)mixed;
|
||||
mix ^= (int)(mixed * 0xC2B2AE35u);
|
||||
count++;
|
||||
minimumX = Hlsl.Min(minimumX, sourceX + x);
|
||||
maximumX = Hlsl.Max(maximumX, sourceX + x);
|
||||
}
|
||||
|
||||
if (count == 0)
|
||||
return;
|
||||
Hlsl.InterlockedAdd(ref scratch[WaveOpticsSettings.ScratchHashSum], sum);
|
||||
Hlsl.InterlockedXor(ref scratch[WaveOpticsSettings.ScratchHashMix], mix);
|
||||
Hlsl.InterlockedAdd(ref scratch[WaveOpticsSettings.ScratchLitCount], count);
|
||||
Hlsl.InterlockedMin(ref scratch[WaveOpticsSettings.ScratchBoundsMinX], minimumX);
|
||||
Hlsl.InterlockedMin(ref scratch[WaveOpticsSettings.ScratchBoundsMinY], sourceY + y);
|
||||
Hlsl.InterlockedMax(ref scratch[WaveOpticsSettings.ScratchBoundsMaxX], sourceX + x);
|
||||
Hlsl.InterlockedMax(ref scratch[WaveOpticsSettings.ScratchBoundsMaxX], maximumX);
|
||||
Hlsl.InterlockedMax(ref scratch[WaveOpticsSettings.ScratchBoundsMaxY], sourceY + y);
|
||||
}
|
||||
}
|
||||
@@ -122,7 +139,7 @@ internal readonly partial struct HorizontalPassShader(
|
||||
|
||||
public void Execute()
|
||||
{
|
||||
var offsetX = ThreadIds.X * WaveOpticsSettings.ConvolutionBlock;
|
||||
var offsetX = ThreadIds.X * WaveOpticsSettings.HorizontalConvolutionBlock;
|
||||
if (offsetX >= regionWidth || ThreadIds.Y >= regionHeight)
|
||||
return;
|
||||
|
||||
@@ -131,7 +148,7 @@ internal readonly partial struct HorizontalPassShader(
|
||||
var column = x - sourceX;
|
||||
var row = y - sourceY;
|
||||
var first = Hlsl.Max(-radius, -column);
|
||||
var last = Hlsl.Min(radius + WaveOpticsSettings.ConvolutionBlock - 1, sourceWidth - 1 - 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);
|
||||
@@ -139,6 +156,14 @@ internal readonly partial struct HorizontalPassShader(
|
||||
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;
|
||||
@@ -147,9 +172,25 @@ internal readonly partial struct HorizontalPassShader(
|
||||
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 weight7 = weight6;
|
||||
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;
|
||||
@@ -166,6 +207,14 @@ internal readonly partial struct HorizontalPassShader(
|
||||
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;
|
||||
@@ -184,6 +233,22 @@ internal readonly partial struct HorizontalPassShader(
|
||||
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)
|
||||
@@ -223,7 +288,7 @@ internal readonly partial struct VerticalPassShader(
|
||||
|
||||
public void Execute()
|
||||
{
|
||||
var offsetY = ThreadIds.Y * WaveOpticsSettings.ConvolutionBlock;
|
||||
var offsetY = ThreadIds.Y * WaveOpticsSettings.VerticalConvolutionBlock;
|
||||
if (ThreadIds.X >= rectWidth || offsetY >= rectHeight)
|
||||
return;
|
||||
|
||||
@@ -231,7 +296,7 @@ internal readonly partial struct VerticalPassShader(
|
||||
var y = rectY + offsetY;
|
||||
var row = y - sourceY;
|
||||
var first = Hlsl.Max(-radius, -row);
|
||||
var last = Hlsl.Min(radius + WaveOpticsSettings.ConvolutionBlock - 1, sourceHeight - 1 - 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);
|
||||
|
||||
@@ -15,7 +15,9 @@ internal sealed class WaveOpticsPipeline : IDisposable
|
||||
private readonly ReadBackBuffer<int> _scratchReadBack;
|
||||
private readonly ReadOnlyBuffer<float> _weights;
|
||||
private readonly float[] _weightValues = new float[WaveOpticsSettings.WeightsLength];
|
||||
private readonly FraunhoferPsfGenerator _generator = new();
|
||||
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;
|
||||
@@ -169,7 +171,7 @@ internal sealed class WaveOpticsPipeline : IDisposable
|
||||
_canvasWidth,
|
||||
_canvasHeight,
|
||||
sourceRect,
|
||||
parameters.Psf);
|
||||
KernelKey(parameters.Psf));
|
||||
if (_convolutionKey == key || !TryGetVisibleBounds(_canvasWidth, _canvasHeight, in parameters, out rect))
|
||||
{
|
||||
rect = default;
|
||||
@@ -236,7 +238,8 @@ internal sealed class WaveOpticsPipeline : IDisposable
|
||||
|
||||
private bool TryEnsureKernel(in PsfParameters psf)
|
||||
{
|
||||
if (_kernelPsf == psf)
|
||||
var key = KernelKey(psf);
|
||||
if (_kernelPsf == key)
|
||||
return HasKernel;
|
||||
|
||||
var pupilGridSize = WaveOpticsSettings.GetPupilGridSize(psf.Quality);
|
||||
@@ -247,7 +250,7 @@ internal sealed class WaveOpticsPipeline : IDisposable
|
||||
comaHorizontalWaves: psf.ComaHorizontal,
|
||||
comaVerticalWaves: psf.ComaVertical,
|
||||
sphericalWaves: psf.Spherical);
|
||||
var descriptor = new PsfDescriptor(
|
||||
var specification = new PsfSpecification(
|
||||
pupilGridSize,
|
||||
WaveOpticsSettings.GetPupilDiameterSamples(pupilGridSize),
|
||||
WaveOpticsSettings.GetKernelSize(psf.KernelRadius),
|
||||
@@ -259,30 +262,33 @@ internal sealed class WaveOpticsPipeline : IDisposable
|
||||
psf.BladeRotation,
|
||||
psf.Obstruction,
|
||||
aberration);
|
||||
if (!_generator.TryGenerate(descriptor, out var result))
|
||||
var size = specification.KernelSize;
|
||||
var kernel = _kernelValues.AsSpan(0, size * size);
|
||||
if (!_sampler.TrySample(in specification, kernel))
|
||||
{
|
||||
_kernel = default;
|
||||
_kernelPsf = psf;
|
||||
_kernelPsf = key;
|
||||
return false;
|
||||
}
|
||||
|
||||
var separable = SeparableKernel.Decompose(result.Kernel.Values.Span, result.Kernel.Size, WaveOpticsSettings.SeparableResidualRatio, WaveOpticsSettings.MaximumRank);
|
||||
|
||||
var size = separable.Size;
|
||||
var scale = 1d / separable.Sum;
|
||||
for (var term = 0; term < separable.Rank; term++)
|
||||
_separable.Update(kernel, size, WaveOpticsSettings.SeparableResidualRatio, WaveOpticsSettings.MaximumRank);
|
||||
var scale = 1d / _separable.Sum;
|
||||
for (var term = 0; term < _separable.Rank; term++)
|
||||
{
|
||||
separable.Horizontal.AsSpan(term * size, size).CopyTo(_weightValues.AsSpan(WaveOpticsSettings.GetWeightOffset(term, 0)));
|
||||
_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);
|
||||
_weightValues[verticalOffset + k] = (float)(_separable.Vertical[term * size + k] * scale);
|
||||
}
|
||||
_weights.CopyFrom(_weightValues);
|
||||
_kernel = new Kernel(separable.Rank, size / 2);
|
||||
_kernelPsf = psf;
|
||||
_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)
|
||||
|
||||
@@ -132,7 +132,7 @@ internal sealed partial class WaveOpticsPipelineHost
|
||||
{
|
||||
context.For(1, new SourceHashResetShader(scratch));
|
||||
context.Barrier(scratch);
|
||||
context.For(sourceRect.Width, sourceRect.Height, new SourceHashShader(
|
||||
context.For(GetBlockCount(sourceRect.Width, WaveOpticsSettings.SourceHashSpan), sourceRect.Height, new SourceHashShader(
|
||||
source, scratch, sourceRect.X, sourceRect.Y, sourceRect.Width, sourceRect.Height));
|
||||
context.Barrier(scratch);
|
||||
}
|
||||
@@ -151,13 +151,13 @@ internal sealed partial class WaveOpticsPipelineHost
|
||||
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), bottom - top, new HorizontalPassShader(
|
||||
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), new VerticalPassShader(
|
||||
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,
|
||||
@@ -167,8 +167,8 @@ internal sealed partial class WaveOpticsPipelineHost
|
||||
}
|
||||
}
|
||||
|
||||
private static int GetBlockCount(int length)
|
||||
=> (length + WaveOpticsSettings.ConvolutionBlock - 1) / WaveOpticsSettings.ConvolutionBlock;
|
||||
private static int GetBlockCount(int length, int block)
|
||||
=> (length + block - 1) / block;
|
||||
|
||||
private static void RecordRenderStage(
|
||||
in ComputeContext context,
|
||||
|
||||
@@ -7,7 +7,7 @@
|
||||
<Nullable>enable</Nullable>
|
||||
<AssemblyName>WaveOptics</AssemblyName>
|
||||
<RootNamespace>WaveOptics</RootNamespace>
|
||||
<Version>2.0.0</Version>
|
||||
<Version>2.1.0</Version>
|
||||
<Platforms>AnyCPU;x64</Platforms>
|
||||
<PlatformTarget>x64</PlatformTarget>
|
||||
<AllowUnsafeBlocks>true</AllowUnsafeBlocks>
|
||||
|
||||
@@ -5,13 +5,16 @@ namespace WaveOptics;
|
||||
internal static class WaveOpticsSettings
|
||||
{
|
||||
public const int MinimumKernelRadius = 1;
|
||||
public const int MaximumKernelRadius = 15;
|
||||
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 ConvolutionBlock = 8;
|
||||
public const int CanvasMargin = (MaximumKernelRadius + 3) & ~3;
|
||||
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;
|
||||
public const int ScratchLength = 7;
|
||||
public const int ScratchLitCount = 0;
|
||||
@@ -35,5 +38,7 @@ 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;
|
||||
}
|
||||
新しいイシューから参照
ユーザーをブロックする