コミットを比較
| 作成者 | SHA1 | 日付 | |
|---|---|---|---|
|
|
937f1fddae
|
||
|
|
78a6ae7aa5
|
||
|
|
16b97860ab
|
||
|
|
2a622d647d
|
||
|
|
1c5bb168d6
|
||
|
|
670c2a5f5a
|
||
|
|
4dcdf283aa
|
||
|
|
66c76fb566
|
||
|
|
a89d02f57c
|
||
|
|
3294c8fc8f
|
||
|
|
ac22cf48a1
|
||
|
|
0ad23e25f4
|
||
|
|
42c7585bd0
|
||
|
|
a618eb0986
|
||
|
|
2fd4629ffe
|
||
|
|
41261aea5f
|
||
|
|
eafaec9d2e
|
||
|
|
2f576a251e
|
||
|
|
887e375e5f
|
||
|
|
08be582b86
|
||
|
|
d13649596f
|
||
|
|
533a7cabf3
|
||
|
|
1f81f8a7dd
|
||
|
|
3a087d2fec
|
||
|
|
ed0660842c
|
||
|
|
32b1b776a9
|
||
|
|
4625e62ed2
|
||
|
|
c8b4435fa6
|
||
|
|
35f654975d
|
||
|
|
e0a21459d7
|
||
|
|
b575081821
|
||
|
|
29fdd72733
|
||
|
|
ebdf054a9e
|
||
|
|
b61b855858
|
||
|
|
b4a9c977ee
|
||
|
|
f0f2b6c062
|
||
|
|
b20285cff7
|
||
|
|
b3d3f406c6
|
||
|
|
46380000c1
|
||
|
|
5ba03a5201
|
||
|
|
bfb9f1304a
|
||
|
|
4a167b4e88
|
||
|
|
cdabada2e4
|
||
|
|
c540c53d5c
|
||
|
|
744d5ec5e1
|
||
|
|
4b929df70c
|
||
|
|
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
|
||
|
|
c78764e367
|
||
|
|
711519fe4f
|
||
|
|
ca6269d242
|
||
|
|
e547e0f838
|
||
|
|
2434dbf08b
|
||
|
|
06ba0070e9
|
||
|
|
a2c727e49e
|
||
|
|
8a1ac6d12d
|
||
|
|
78d5debe2c
|
||
|
|
d432576ed7
|
||
|
|
cb80cb8c52
|
||
|
|
ecc7fa8dce
|
||
|
|
6ad9426585
|
||
|
|
6c11e5163f
|
||
|
|
9ba6a57f33
|
||
|
|
5951976c33
|
||
|
|
c99609652d
|
||
|
|
cb569934fc
|
||
|
|
388a87939c
|
||
|
|
dd34a3ea04
|
||
|
|
d613d19212
|
||
|
|
420edde566
|
||
|
|
f37e36fe35
|
||
|
|
fba34baa18
|
||
|
|
b9a60aa6fa
|
||
|
|
02b43f9da8
|
||
|
|
2bec5d056b
|
||
|
|
cdbfc60672
|
||
|
|
7b314acfad
|
||
|
|
71084fa9b9
|
||
|
|
ab1722b1e0
|
||
|
|
f24dabd2d5
|
||
|
|
653323bccb
|
||
|
|
799aa5077e
|
||
|
|
69dd1fa432
|
||
|
|
9756e46973
|
||
|
|
ebfd783d36
|
||
|
|
62081f8d66
|
||
|
|
18f2b0c69e
|
||
|
|
f2be0c4caf
|
||
|
|
b23e19e9e7
|
||
|
|
49f92bd04b
|
||
|
|
ae95c982d8
|
||
|
|
e9ea7a75e3
|
||
|
|
8e2008de5e
|
||
|
|
2d869f44e1
|
||
|
|
13063805b2
|
||
|
|
d7fadec397
|
||
|
|
5b6753f94c
|
||
|
|
c7c1823b70
|
||
|
|
d59bef2e0b
|
||
|
|
af2160e932
|
||
|
|
75611dd793
|
||
|
|
eba665280d
|
||
|
|
f5350538c4
|
||
|
|
f7819c57de
|
||
|
|
349e431bba
|
||
|
|
d8808fff1f
|
||
|
|
bb59aef5df
|
||
|
|
8917f43c01
|
||
|
|
ffb1581cc1
|
||
|
|
a02d3fb184
|
||
|
|
9db005ec89
|
||
|
|
f8f97ea516
|
||
|
|
89e5abf1f9
|
||
|
|
d9f1a4164d
|
||
|
|
5e77119a6a
|
||
|
|
1ae02a0b8e
|
||
|
|
2b5d061aa0
|
||
|
|
6f58900e99
|
||
|
|
96e6dff673
|
||
|
|
c5e307ec60
|
||
|
|
d0b83ae33d
|
||
|
|
2bd390d65a
|
||
|
|
4615d21d8f
|
||
|
|
37f6b55d06
|
||
|
|
170aac3247
|
||
|
|
24b7706056
|
||
|
|
3bd102f907
|
||
|
|
5b90d5b12a
|
||
|
|
04e7311be3
|
||
|
|
b326d5da2d
|
||
|
|
e04ef2c60e
|
||
|
|
92ea407e23
|
||
|
|
5327df5954
|
||
|
|
f624be38fd
|
||
|
|
16308d7d0d
|
||
|
|
a8177bbf00
|
||
|
|
2d14865acf
|
||
|
|
ef78373bef
|
||
|
|
c9b3ef87d6
|
検索条件に一致するファイルはありません
@@ -0,0 +1,13 @@
|
||||
{
|
||||
"version": 1,
|
||||
"isRoot": true,
|
||||
"tools": {
|
||||
"dotnet-stryker": {
|
||||
"version": "5.0.0",
|
||||
"commands": [
|
||||
"dotnet-stryker"
|
||||
],
|
||||
"rollForward": false
|
||||
}
|
||||
}
|
||||
}
|
||||
+77
@@ -0,0 +1,77 @@
|
||||
root = true
|
||||
|
||||
[*]
|
||||
indent_style = space
|
||||
indent_size = 4
|
||||
tab_width = 4
|
||||
end_of_line = crlf
|
||||
charset = utf-8
|
||||
trim_trailing_whitespace = true
|
||||
insert_final_newline = true
|
||||
|
||||
[*.{json,yml,yaml}]
|
||||
indent_size = 2
|
||||
|
||||
[*.{csproj,props,targets,vcxproj,filters,slnx,resx,xml}]
|
||||
charset = unset
|
||||
indent_style = unset
|
||||
indent_size = unset
|
||||
|
||||
[*.md]
|
||||
trim_trailing_whitespace = false
|
||||
|
||||
[*.cs]
|
||||
dotnet_separate_import_directive_groups = false
|
||||
dotnet_sort_system_directives_first = true
|
||||
|
||||
dotnet_style_qualification_for_field = false:error
|
||||
dotnet_style_qualification_for_property = false:error
|
||||
dotnet_style_qualification_for_method = false:error
|
||||
dotnet_style_qualification_for_event = false:error
|
||||
dotnet_style_predefined_type_for_locals_parameters_members = true:error
|
||||
dotnet_style_predefined_type_for_member_access = true:error
|
||||
dotnet_style_readonly_field = true:warning
|
||||
dotnet_style_coalesce_expression = true:suggestion
|
||||
dotnet_style_null_propagation = true:suggestion
|
||||
dotnet_style_object_initializer = true:suggestion
|
||||
dotnet_style_collection_initializer = true:suggestion
|
||||
dotnet_style_prefer_is_null_check_over_reference_equality_method = true:warning
|
||||
dotnet_style_operator_placement_when_wrapping = beginning_of_line
|
||||
dotnet_code_quality_unused_parameters = all:warning
|
||||
|
||||
csharp_style_namespace_declarations = file_scoped:error
|
||||
csharp_using_directive_placement = outside_namespace:error
|
||||
csharp_prefer_braces = when_multiline:silent
|
||||
csharp_style_var_for_built_in_types = true:silent
|
||||
csharp_style_var_when_type_is_apparent = true:silent
|
||||
csharp_style_var_elsewhere = true:silent
|
||||
csharp_style_expression_bodied_methods = when_on_single_line:silent
|
||||
csharp_style_expression_bodied_properties = true:silent
|
||||
csharp_style_expression_bodied_accessors = true:silent
|
||||
csharp_style_prefer_pattern_matching = true:suggestion
|
||||
csharp_style_prefer_not_pattern = true:suggestion
|
||||
csharp_style_prefer_switch_expression = true:suggestion
|
||||
csharp_style_prefer_readonly_struct = true:warning
|
||||
csharp_style_prefer_readonly_struct_member = true:warning
|
||||
csharp_prefer_static_local_function = true:warning
|
||||
csharp_style_prefer_primary_constructors = true:silent
|
||||
|
||||
csharp_new_line_before_open_brace = all
|
||||
csharp_new_line_before_else = true
|
||||
csharp_new_line_before_catch = true
|
||||
csharp_new_line_before_finally = true
|
||||
|
||||
dotnet_diagnostic.IDE0005.severity = warning
|
||||
dotnet_diagnostic.IDE0055.severity = warning
|
||||
dotnet_diagnostic.IDE0161.severity = error
|
||||
|
||||
[{YMM4-ComputeGuard,YMM4-GitHubUpdateNotifier,YMM4-Telemetry,YukkuriMovieMaker.Generator}/**]
|
||||
dotnet_diagnostic.IDE0005.severity = none
|
||||
dotnet_diagnostic.IDE0055.severity = none
|
||||
dotnet_diagnostic.IDE0161.severity = none
|
||||
|
||||
[*.{g.cs,designer.cs}]
|
||||
generated_code = true
|
||||
dotnet_diagnostic.IDE0005.severity = none
|
||||
dotnet_diagnostic.IDE0055.severity = none
|
||||
dotnet_diagnostic.IDE0161.severity = none
|
||||
@@ -1,430 +0,0 @@
|
||||
# v1.0.0 - 波動光学 for YMM4
|
||||
|
||||
YukkuriMovieMaker4 向けの波動光学エフェクトプラグインの初回リリースです。
|
||||
フラウンホーファー回折理論に基づいて点像分布関数(PSF)を計算し、Direct2D カスタムシェーダーで
|
||||
映像を畳み込む映像エフェクトプラグインです。
|
||||
波長・F値・画素ピッチ・開口形状・ゼルニケ波面収差係数をパラメータとして持ち、
|
||||
円形開口・正多角形開口・中央遮蔽・6 種類の波面収差項に対応します。
|
||||
8 言語対応 UI を備えます。
|
||||
|
||||
---
|
||||
|
||||
## 新機能
|
||||
|
||||
### 1. 公開コントラクト(WaveOptics.Abstractions)
|
||||
|
||||
`WaveOptics.Abstractions` は主プラグインから独立したライブラリとして提供されます。
|
||||
|
||||
#### ApertureShape
|
||||
|
||||
開口形状を表す列挙体です。
|
||||
|
||||
| 値 | 意味 |
|
||||
|---|---|
|
||||
| `Circular` | 円形開口 |
|
||||
| `RegularPolygon` | 正多角形開口 |
|
||||
|
||||
#### OpticalApiVersion
|
||||
|
||||
`readonly record struct OpticalApiVersion(int Major, int Minor)` で宣言されます。
|
||||
`Current` 静的プロパティは `new(1, 0)` を返却します。
|
||||
|
||||
#### OpticalCapabilities
|
||||
|
||||
PSF 生成器の対応機能を表す `[Flags]` 列挙体です。
|
||||
|
||||
| 値 | 意味 |
|
||||
|---|---|
|
||||
| `None` | 0 |
|
||||
| `MonochromaticPsf` | 単色 PSF 生成 |
|
||||
| `CircularAperture` | 円形開口 |
|
||||
| `RegularPolygonAperture` | 正多角形開口 |
|
||||
| `CentralObstruction` | 中央遮蔽 |
|
||||
| `ZernikeAberration` | ゼルニケ収差 |
|
||||
| `DirectConvolution` | 直接畳み込み |
|
||||
|
||||
#### WavefrontAberration
|
||||
|
||||
8 つの収差係数を保持する `readonly struct` で、`IEquatable<WavefrontAberration>` を実装します。
|
||||
|
||||
| フィールド | 説明 |
|
||||
|---|---|
|
||||
| `DefocusWaves` | デフォーカス係数(-10〜10 waves) |
|
||||
| `AstigmatismVerticalWaves` | 縦横非点収差係数 |
|
||||
| `AstigmatismObliqueWaves` | 斜め非点収差係数 |
|
||||
| `ComaHorizontalWaves` | 水平コマ収差係数 |
|
||||
| `ComaVerticalWaves` | 垂直コマ収差係数 |
|
||||
| `TrefoilHorizontalWaves` | 水平トレフォイル係数 |
|
||||
| `TrefoilVerticalWaves` | 垂直トレフォイル係数 |
|
||||
| `SphericalWaves` | 球面収差係数 |
|
||||
|
||||
コンストラクターは各係数を `ValidateFiniteRange(-10, 10)` で検証します。
|
||||
`==`・`!=` 演算子および `GetHashCode` を実装します。
|
||||
|
||||
#### PsfDescriptor
|
||||
|
||||
PSF 計算パラメータを保持する `sealed` クラスで、`IEquatable<PsfDescriptor>` を実装します。
|
||||
|
||||
コンストラクターが受け取るパラメータと検証条件は以下のとおりです。
|
||||
|
||||
| パラメータ | 型 | 検証条件 |
|
||||
|---|---|---|
|
||||
| `pupilGridSize` | `int` | 64〜2048、かつ 2 の冪 |
|
||||
| `pupilDiameterSamples` | `int` | 16〜`pupilGridSize / 2` |
|
||||
| `kernelSize` | `int` | 3〜255、かつ奇数 |
|
||||
| `wavelengthNanometers` | `double` | 有限値、380〜780 |
|
||||
| `fNumber` | `double` | 有限値、0.5〜64 |
|
||||
| `sensorPixelPitchMicrometers` | `double` | 有限値、0.25〜100 |
|
||||
| `apertureShape` | `ApertureShape` | 定義済み列挙値 |
|
||||
| `bladeCount` | `int` | 3〜32 |
|
||||
| `bladeRotationDegrees` | `double` | 有限値、-360〜360 |
|
||||
| `centralObstructionRatio` | `double` | 有限値、0〜0.95 |
|
||||
| `aberration` | `WavefrontAberration` | — |
|
||||
|
||||
`Equals` はすべてのフィールドの完全一致で判定します。`GetHashCode` は `HashCode.Combine` を 2 段に分けて計算します。
|
||||
|
||||
#### PsfKernel
|
||||
|
||||
PSF カーネルデータを保持する `sealed` クラスです。
|
||||
|
||||
コンストラクターは `size`(奇数正整数)と `values`(`size × size` 長、全要素非負有限)を受け取り、
|
||||
合計値が正であることを検証してから値の総和で正規化します。入力配列は内部にコピーします。
|
||||
|
||||
`Sum` メソッドはカハン補償加算でエラー累積を抑えた合計値を返却します。
|
||||
|
||||
| メンバー | 説明 |
|
||||
|---|---|
|
||||
| `Size` | カーネルの一辺の画素数 |
|
||||
| `Values` | 正規化済み値の `ReadOnlyMemory<double>` |
|
||||
| `this[int x, int y]` | 範囲検証付きインデクサー |
|
||||
| `ToArray()` | 内部配列のクローン |
|
||||
|
||||
#### PsfDiagnostics
|
||||
|
||||
`readonly record struct PsfDiagnostics` で以下の診断値を保持します。
|
||||
|
||||
| フィールド | 説明 |
|
||||
|---|---|
|
||||
| `OpenPupilSampleCount` | 開口内の有効サンプル数 |
|
||||
| `FocalPlaneSamplePitchMicrometers` | 焦点面サンプル間隔(μm) |
|
||||
| `UnnormalizedKernelEnergy` | 正規化前のカーネルエネルギー |
|
||||
| `PeakIntensity` | カーネルの最大強度値 |
|
||||
|
||||
#### PsfGenerationResult
|
||||
|
||||
`sealed record PsfGenerationResult(PsfKernel Kernel, PsfDiagnostics Diagnostics)` で宣言されます。
|
||||
|
||||
#### IPsfGenerator
|
||||
|
||||
```csharp
|
||||
public interface IPsfGenerator
|
||||
{
|
||||
OpticalApiVersion ApiVersion { get; }
|
||||
OpticalCapabilities Capabilities { get; }
|
||||
PsfGenerationResult Generate(PsfDescriptor descriptor);
|
||||
}
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
### 2. 高速フーリエ変換(FastFourierTransform)
|
||||
|
||||
`internal static class FastFourierTransform` は 1 次元および 2 次元の FFT・逆 FFT を提供します。
|
||||
|
||||
| メソッド | 説明 |
|
||||
|---|---|
|
||||
| `Forward(Span<Complex>)` | 1 次元前進 FFT |
|
||||
| `Inverse(Span<Complex>)` | 1 次元逆 FFT(1/N スケール適用) |
|
||||
| `Forward2D(Complex[], int, int)` | 2 次元前進 FFT(行→列の順) |
|
||||
| `Inverse2D(Complex[], int, int)` | 2 次元逆 FFT |
|
||||
|
||||
1 次元実装はクーリー・テューキーアルゴリズムに基づく入力サイズ 2 の冪専用の再帰なし実装です。ビット反転置換を前処理として行い、以降を長さ倍増ループで処理します。逆変換では最後に `1/count` を乗算します。
|
||||
|
||||
2 次元実装は各行・各列に独立して 1 次元変換を適用します。列方向の処理には作業用配列 `new Complex[height]` を確保します。
|
||||
|
||||
---
|
||||
|
||||
### 3. ゼルニケ波面評価(ZernikeWavefront)
|
||||
|
||||
`internal static class ZernikeWavefront` は正規化ゼルニケ多項式による波面位相を評価します。
|
||||
|
||||
`Evaluate(double x, double y, WavefrontAberration aberration)` は以下の項の線形結合を返却します。
|
||||
|
||||
| 項 | 式 |
|
||||
|---|---|
|
||||
| デフォーカス | `√3 × (2ρ² − 1)` |
|
||||
| 縦横非点収差 | `√6 × (x² − y²)` |
|
||||
| 斜め非点収差 | `2√6 × xy` |
|
||||
| 水平コマ収差 | `√8 × (3ρ² − 2) × x` |
|
||||
| 垂直コマ収差 | `√8 × (3ρ² − 2) × y` |
|
||||
| 水平トレフォイル | `√8 × x × (x² − 3y²)` |
|
||||
| 垂直トレフォイル | `√8 × y × (3x² − y²)` |
|
||||
| 球面収差 | `√5 × (6ρ⁴ − 6ρ² + 1)` |
|
||||
|
||||
`WavefrontAberration` の `TrefoilHorizontalWaves`・`TrefoilVerticalWaves` は`WaveOpticsEffect` の UI には公開されておらず、常に 0 として扱われます。
|
||||
|
||||
---
|
||||
|
||||
### 4. フラウンホーファーPSF生成器(FraunhoferPsfGenerator)
|
||||
|
||||
`public sealed class FraunhoferPsfGenerator : IPsfGenerator` を実装します。
|
||||
|
||||
`Capabilities` は以下のフラグを返却します。
|
||||
`MonochromaticPsf | CircularAperture | RegularPolygonAperture | CentralObstruction | ZernikeAberration | DirectConvolution`
|
||||
|
||||
#### Generate メソッド
|
||||
|
||||
1. `gridSize × gridSize` の `Complex[]` 配列を確保します。
|
||||
2. グリッド中心を基準に各サンプル `(x, y)` を正規化座標 `(normalizedX, normalizedY)` に変換し、
|
||||
`IsInsideAperture` で開口内を判定します。
|
||||
3. 開口内のサンプルに対して `ZernikeWavefront.Evaluate` で波面位相 `φ` を計算し、
|
||||
`Complex.FromPolarCoordinates(1d, 2π × φ)` を瞳関数値として設定します。
|
||||
4. `FastFourierTransform.Forward2D` を適用します。
|
||||
5. 変換後の値の二乗絶対値(強度)を計算し、FFT のゼロ周波数が中心に来るよう DC シフトして
|
||||
`double[]` 配列に格納します。全強度の和で正規化します。
|
||||
6. 焦点面サンプルピッチ `λ × F × D / N`(μm)を計算し、カーネルの各画素に対応する
|
||||
焦点面座標を求めて `SampleBilinear` で強度を取得します。
|
||||
7. `new PsfKernel(kernelSize, kernel)` を生成して返却します。
|
||||
|
||||
#### IsInsideAperture メソッド
|
||||
|
||||
- 正規化半径の二乗が 1 超 → 開口外。
|
||||
- 正規化半径の二乗が `obstructionRatio²` 未満 → 遮蔽領域。
|
||||
- 円形開口の場合は上記を満たせば開口内。
|
||||
- 正多角形の場合:`Math.Atan2(y, x) - rotation` を `2π / bladeCount` で折り畳み、境界距離
|
||||
`cos(π / bladeCount) / cos(folded)` と半径を比較します。
|
||||
|
||||
#### SampleBilinear メソッド
|
||||
|
||||
双線形補間でグリッド外を 0 として返却します。
|
||||
|
||||
---
|
||||
|
||||
### 5. PSFビットマップ生成(PsfBitmapFactory)
|
||||
|
||||
`internal static class PsfBitmapFactory` の `Create(ID2D1DeviceContext, PsfKernel)` は
|
||||
PSF カーネルの各値を RGBA 4 チャンネルの `float[]` に展開(R=G=B=値, A=1)し、
|
||||
ピン留めポインタを使って `ID2D1DeviceContext1.CreateBitmap` を呼び出します。
|
||||
ピクセルフォーマットは `Format.R32G32B32A32_Float` / `AlphaMode.Ignore` / 96 DPI です。
|
||||
|
||||
---
|
||||
|
||||
### 6. カスタムシェーダーエフェクト(WaveOpticsConvolutionEffect)
|
||||
|
||||
`internal sealed class WaveOpticsConvolutionEffect : D2D1CustomShaderEffectBase` は
|
||||
`[CustomEffect(2)]` の 2 入力エフェクトとして宣言されます(入力 0: ソース画像、入力 1: PSF ビットマップ)。
|
||||
|
||||
定数は以下のとおりです。
|
||||
|
||||
| 定数 | 値 |
|
||||
|---|---|
|
||||
| `MaximumKernelSize` | `31` |
|
||||
|
||||
公開プロパティは `GetIntValue`・`GetFloatValue`・`SetValue` を介して `EffectImpl` へ転送します。
|
||||
|
||||
| プロパティ | 型 | 説明 |
|
||||
|---|---|---|
|
||||
| `KernelSize` | `int` | カーネルサイズ(奇数にクランプ、最大 31) |
|
||||
| `Amount` | `float` | 適用量(0〜1) |
|
||||
| `Gain` | `float` | 利得(0〜4) |
|
||||
|
||||
`SetSource(ID2D1Image?)` は入力 0 を設定します。`SetKernel(ID2D1Image?)` は入力 1 を設定します。
|
||||
|
||||
#### EffectImpl(内部 sealed クラス)
|
||||
|
||||
`ConstantBuffer` 構造体(`LayoutKind.Sequential`)のレイアウトは以下のとおりです。
|
||||
|
||||
| フィールド | 型 | 説明 |
|
||||
|---|---|---|
|
||||
| `KernelSize` | `int` | カーネルサイズ |
|
||||
| `Amount` | `float` | 適用量 |
|
||||
| `Gain` | `float` | 利得 |
|
||||
| `Padding` | `float` | アライメント用 |
|
||||
| `InputBounds` | `Vector4` | 入力矩形(Left, Top, Right, Bottom) |
|
||||
|
||||
コンストラクターは `constants.KernelSize = 1`・`constants.Gain = 1` を初期値として設定します。
|
||||
|
||||
`MapInputRectsToOutputRect` は `inputRect` と `inputBounds` を更新した後、
|
||||
`Inflate(inputRect, GetRadius())` を出力矩形に設定します。
|
||||
|
||||
`GetRadius` は `Amount > 0` かつ `KernelSize > 1` のとき `KernelSize / 2` を、それ以外は `0` を返却します。
|
||||
|
||||
#### HLSLシェーダー(WaveOpticsConvolution.hlsl)
|
||||
|
||||
`t0`(ソース画像)・`t1`(PSF ビットマップ)・`b0`(定数バッファー)を持つピクセルシェーダーです。
|
||||
|
||||
- `amount <= 0` または `kernelSize <= 1` の場合はソースをそのまま返却します。
|
||||
- ループ範囲は固定 `-MaximumRadius`〜`MaximumRadius`(= -15〜15)で、
|
||||
`abs(x) > radius` または `abs(y) > radius` のサンプルは `continue` でスキップします。
|
||||
- PSF の重みは `KernelTexture.Load(int3(x + radius, y + radius, 0)).r` で取得します。
|
||||
- 入力矩形外のサンプルは黒として扱います。
|
||||
- `lerp(source, convolved * gain, amount)` で出力します。
|
||||
|
||||
---
|
||||
|
||||
### 7. エフェクト定義(WaveOpticsEffect)
|
||||
|
||||
`public sealed class WaveOpticsEffect : VideoEffectBase` を継承します。
|
||||
|
||||
`[VideoEffect]` 属性は以下のパラメーターで宣言されます。
|
||||
|
||||
- 表示名:`Texts.EffectName`(ローカライズキー)
|
||||
- カテゴリー:`VideoEffectCategories.Filtering`
|
||||
- 検索タグ:`TagDiffraction`・`TagLens`・`TagPsf`・`TagOptics`(「回折」・「レンズ」・「点像分布関数」・「光学」)
|
||||
- `IsAviUtlSupported = false` により AviUtl 向け EXO 出力は非対応
|
||||
- `ResourceType = typeof(Texts)` でローカライズリソースを指定
|
||||
|
||||
`Label` プロパティは `Texts.EffectName` を返却します。
|
||||
|
||||
公開プロパティは以下のとおりです。
|
||||
|
||||
**出力グループ**
|
||||
|
||||
| プロパティ | 型 | デフォルト | 内部範囲 |
|
||||
|---|---|---|---|
|
||||
| `Amount` | `Animation` | 100 | 0〜100 |
|
||||
| `Gain` | `Animation` | 100 | 0〜400 |
|
||||
|
||||
**光学系グループ**
|
||||
|
||||
| プロパティ | 型 | デフォルト | 内部範囲 |
|
||||
|---|---|---|---|
|
||||
| `Wavelength` | `Animation` | 550 | 380〜780 |
|
||||
| `FNumber` | `Animation` | 8 | 0.5〜64 |
|
||||
| `PixelPitch` | `Animation` | 4 | 0.25〜100 |
|
||||
| `KernelRadius` | `int` | 15 | 1〜15 |
|
||||
| `Quality` | `WaveOpticsQuality` | `Standard` | — |
|
||||
|
||||
**開口グループ**
|
||||
|
||||
| プロパティ | 型 | デフォルト | 内部範囲 |
|
||||
|---|---|---|---|
|
||||
| `ApertureShape` | `WaveOpticsApertureShape` | `Circular` | — |
|
||||
| `BladeCount` | `int` | 6 | 3〜32 |
|
||||
| `BladeRotation` | `Animation` | 0 | -360〜360 |
|
||||
| `Obstruction` | `Animation` | 0 | 0〜95 |
|
||||
|
||||
**波面収差グループ**
|
||||
|
||||
| プロパティ | 型 | デフォルト | 内部範囲 |
|
||||
|---|---|---|---|
|
||||
| `Defocus` | `Animation` | 0 | -10〜10 |
|
||||
| `AstigmatismVertical` | `Animation` | 0 | -10〜10 |
|
||||
| `AstigmatismOblique` | `Animation` | 0 | -10〜10 |
|
||||
| `ComaHorizontal` | `Animation` | 0 | -10〜10 |
|
||||
| `ComaVertical` | `Animation` | 0 | -10〜10 |
|
||||
| `Spherical` | `Animation` | 0 | -10〜10 |
|
||||
|
||||
`GetAnimatables` は `Amount`・`Gain`・`Wavelength`・`FNumber`・`PixelPitch`・`BladeRotation`・
|
||||
`Obstruction`・`Defocus`・`AstigmatismVertical`・`AstigmatismOblique`・`ComaHorizontal`・
|
||||
`ComaVertical`・`Spherical` を yield します。
|
||||
|
||||
---
|
||||
|
||||
### 8. エフェクトプロセッサー(WaveOpticsEffectProcessor)
|
||||
|
||||
`internal sealed class WaveOpticsEffectProcessor : VideoEffectProcessorBase` を継承します。
|
||||
|
||||
#### Update メソッド
|
||||
|
||||
`IsPassThroughEffect || effect is null` の場合は `effectDescription.DrawDescription` をそのまま返却します。
|
||||
|
||||
各フレームで以下の値を計算します。
|
||||
|
||||
| パラメーター | クランプ範囲 | フォールバック |
|
||||
|---|---|---|
|
||||
| `amount` | 0〜1 | 0 |
|
||||
| `gain` | 0〜4 | 1 |
|
||||
| `wavelength` | 380〜780 | 550 |
|
||||
| `fNumber` | 0.5〜64 | 8 |
|
||||
| `pixelPitch` | 0.25〜100 | 4 |
|
||||
| `obstruction / 100` | 0〜0.95 | 0 |
|
||||
| 各収差係数 | -10〜10 | 0 |
|
||||
|
||||
`Parameters` レコードとして前フレームの値と比較し、変化があった場合のみ `UpdateKernel` を呼び出します。
|
||||
`Amount`・`Gain` も同様に差分検出して `effect` のプロパティを更新します。
|
||||
|
||||
#### UpdateKernel メソッド
|
||||
|
||||
`WavefrontAberration` と `PsfDescriptor` を構築して `FraunhoferPsfGenerator.Generate` を呼び出します。
|
||||
|
||||
品質から FFT 格子サイズへの変換は以下のとおりです。
|
||||
|
||||
| `WaveOpticsQuality` | FFT 格子サイズ |
|
||||
|---|---|
|
||||
| `Draft` | 128 |
|
||||
| `High` | 512 |
|
||||
| その他(`Standard`) | 256 |
|
||||
|
||||
`PsfDescriptor` の `pupilDiameterSamples` は `gridSize / 4` に固定されます。
|
||||
`kernelSize` は `KernelRadius * 2 + 1` です。
|
||||
|
||||
`PsfBitmapFactory.Create` で新しいビットマップを作成し、`disposer.RemoveAndDispose` で旧ビットマップを破棄してから新ビットマップを `effect` に設定します。
|
||||
|
||||
#### CreateEffect / setInput / ClearEffectChain
|
||||
|
||||
`CreateEffect` は `WaveOpticsConvolutionEffect` を生成し、`IsEnabled` が false の場合は破棄して
|
||||
`null` を返却します。有効な場合は `disposer` に収集し、`Output` を取得して返却します。
|
||||
|
||||
`setInput` は `effect?.SetSource(input)` を呼び出します。
|
||||
|
||||
`ClearEffectChain` は `effect?.SetSource(null)`・`effect?.SetKernel(null)` を呼び出し、
|
||||
`currentParameters = null`・`isFirst = true` にリセットします。
|
||||
|
||||
---
|
||||
|
||||
### 9. 公開API(WaveOpticsApi)
|
||||
|
||||
`public static class WaveOpticsApi` を提供します。
|
||||
|
||||
| メンバー | 説明 |
|
||||
|---|---|
|
||||
| `Version` | `OpticalApiVersion.Current` を返却します |
|
||||
| `CreatePsfGenerator()` | `new FraunhoferPsfGenerator()` を返却します |
|
||||
|
||||
---
|
||||
|
||||
### 10. ローカライズ(Texts)
|
||||
|
||||
`Texts` クラスは `[AutoGenLocalizer]` 属性を持つ `partial` クラスとして宣言されます。
|
||||
`YukkuriMovieMaker.Generator` のソースジェネレーターが `Texts.csv` を処理し、
|
||||
各ロケールのリソースファイルを自動生成します。
|
||||
|
||||
対応言語:日本語(`ja-jp`)・英語(`en-us`)・中国語簡体字(`zh-cn`)・中国語繁体字(`zh-tw`)・
|
||||
韓国語(`ko-kr`)・スペイン語(`es-es`)・アラビア語(`ar-sa`)・インドネシア語(`id-id`)
|
||||
|
||||
ローカライズキーの一覧は以下のとおりです。
|
||||
|
||||
| キー | ja-jp |
|
||||
|---|---|
|
||||
| `EffectName` | 波動光学 |
|
||||
| `OutputGroup` | 出力 |
|
||||
| `OpticsGroup` | 光学系 |
|
||||
| `ApertureGroup` | 開口 |
|
||||
| `AberrationGroup` | 波面収差 |
|
||||
| `AmountName` | 適用量 |
|
||||
| `GainName` | 利得 |
|
||||
| `WavelengthName` | 波長 |
|
||||
| `FNumberName` | F値 |
|
||||
| `PixelPitchName` | 画素ピッチ |
|
||||
| `KernelRadiusName` | カーネル半径 |
|
||||
| `QualityName` | 品質 |
|
||||
| `QualityDraft` | 高速 |
|
||||
| `QualityStandard` | 標準 |
|
||||
| `QualityHigh` | 高精度 |
|
||||
| `ApertureShapeName` | 開口形状 |
|
||||
| `CircularAperture` | 円形 |
|
||||
| `RegularPolygonAperture` | 正多角形 |
|
||||
| `BladeCountName` | 羽根枚数 |
|
||||
| `BladeRotationName` | 開口回転 |
|
||||
| `ObstructionName` | 中央遮蔽 |
|
||||
| `DefocusName` | デフォーカス |
|
||||
| `AstigmatismVerticalName` | 縦横非点収差 |
|
||||
| `AstigmatismObliqueName` | 斜め非点収差 |
|
||||
| `ComaHorizontalName` | 水平コマ収差 |
|
||||
| `ComaVerticalName` | 垂直コマ収差 |
|
||||
| `SphericalName` | 球面収差 |
|
||||
| `TagDiffraction` | 回折 |
|
||||
| `TagLens` | レンズ |
|
||||
| `TagPsf` | 点像分布関数 |
|
||||
| `TagOptics` | 光学 |
|
||||
@@ -0,0 +1 @@
|
||||
github: routersys
|
||||
@@ -0,0 +1,102 @@
|
||||
name: 不具合の報告
|
||||
description: エラーが出る、強制終了する、出力が乱れる、README と違う動きをする、といった不具合を報告します。
|
||||
title: "[Bug] "
|
||||
labels: ["bug"]
|
||||
body:
|
||||
- type: markdown
|
||||
attributes:
|
||||
value: |
|
||||
脆弱性はここに書かず、リポジトリのセキュリティポリシーに従って非公開で報告してください。
|
||||
README と実際の動きが違い、文書のほうが誤りだと考えるときは、文書の不備を使ってください。
|
||||
|
||||
- type: input
|
||||
id: plugin-version
|
||||
attributes:
|
||||
label: プラグインのバージョン
|
||||
description: GitHub のリリースか、配布パッケージの Readme.txt の見出しで確かめられます。
|
||||
placeholder: v1.0.0
|
||||
validations:
|
||||
required: true
|
||||
|
||||
- type: input
|
||||
id: ymm4-version
|
||||
attributes:
|
||||
label: YukkuriMovieMaker4 のバージョン
|
||||
description: YukkuriMovieMaker4 のメインウィンドウのタイトルに表示されるバージョンを、そのまま書いてください。
|
||||
placeholder: v4.56.1.0 Lite
|
||||
validations:
|
||||
required: true
|
||||
|
||||
- type: input
|
||||
id: os
|
||||
attributes:
|
||||
label: Windows のバージョン
|
||||
description: winver を実行し、ビルド番号まで書いてください。
|
||||
placeholder: Windows 11 24H2, 26100.2605
|
||||
validations:
|
||||
required: true
|
||||
|
||||
- type: input
|
||||
id: gpu
|
||||
attributes:
|
||||
label: GPU とドライバー
|
||||
description: 描画や GPU に関わる不具合では必ず書いてください。デバイスマネージャーか dxdiag に表示される GPU の名前と、ドライバーのバージョンです。
|
||||
|
||||
- type: textarea
|
||||
id: expected
|
||||
attributes:
|
||||
label: 期待した動き
|
||||
description: 何が起きると考えたか。README に根拠があれば、その箇所も書いてください。
|
||||
validations:
|
||||
required: true
|
||||
|
||||
- type: textarea
|
||||
id: actual
|
||||
attributes:
|
||||
label: 実際の動き
|
||||
description: 実際に起きたこと。エラー画面が出たときは、その内容を省略せずに貼ってください。
|
||||
validations:
|
||||
required: true
|
||||
|
||||
- type: textarea
|
||||
id: steps
|
||||
attributes:
|
||||
label: 再現の手順
|
||||
description: |
|
||||
新しいプロジェクトから不具合が起きるまでの操作を、番号を付けて書いてください。変えた設定の項目と値も書いてください。
|
||||
プロジェクトファイルや素材は、zip に圧縮して添付できます。添付したファイルは誰でも見られます。プロジェクトファイルには素材を置いたフォルダーのパスが記録されるので、公開できない情報が無いかを確かめてください。
|
||||
placeholder: |
|
||||
1. 新しいプロジェクトを作る
|
||||
2. アイテムを置き、本プラグインを使う
|
||||
3. 設定を変える
|
||||
4. 不具合が起きる
|
||||
validations:
|
||||
required: true
|
||||
|
||||
- type: dropdown
|
||||
id: frequency
|
||||
attributes:
|
||||
label: 起きる頻度
|
||||
description: ときどき起きるときは、何回試して何回起きたかを、下の「その他」の欄に書いてください。
|
||||
options:
|
||||
- 毎回起きる
|
||||
- ときどき起きる
|
||||
- 一度だけ起きた
|
||||
validations:
|
||||
required: true
|
||||
|
||||
- type: textarea
|
||||
id: context
|
||||
attributes:
|
||||
label: その他
|
||||
description: 一緒に使っているほかのプラグインや、関係すると思われることを書いてください。
|
||||
|
||||
- type: checkboxes
|
||||
id: checks
|
||||
attributes:
|
||||
label: 報告の前に
|
||||
options:
|
||||
- label: 最新のリリースを使っています。
|
||||
required: true
|
||||
- label: 既存の Issue を検索し、同じ報告が無いことを確かめました。
|
||||
required: true
|
||||
@@ -0,0 +1,5 @@
|
||||
blank_issues_enabled: false
|
||||
contact_links:
|
||||
- name: YukkuriMovieMaker4 本体の不具合
|
||||
url: https://manjubox.net/contact/
|
||||
about: 本体に原因がある不具合は、YukkuriMovieMaker4 の「ヘルプ」の「フィードバックを送信」か、公式サイトのお問い合わせから報告してください。
|
||||
@@ -0,0 +1,63 @@
|
||||
name: 文書の不備
|
||||
description: 誤り、書き漏れ、実際の動きとの食い違いがある文書を報告します。
|
||||
title: "[Docs] "
|
||||
labels: ["documentation"]
|
||||
body:
|
||||
- type: markdown
|
||||
attributes:
|
||||
value: |
|
||||
実際の動きと文書が食い違うときは、ここで報告して構いません。動きのほうが誤りだと考えるときは、不具合の報告を使ってください。
|
||||
|
||||
- type: dropdown
|
||||
id: location
|
||||
attributes:
|
||||
label: 文書
|
||||
options:
|
||||
- README
|
||||
- 配布パッケージの Readme.txt
|
||||
- 設定の項目の名前や説明
|
||||
- 貢献の手引き、セキュリティポリシー、行動規範
|
||||
- その他
|
||||
validations:
|
||||
required: true
|
||||
|
||||
- type: input
|
||||
id: reference
|
||||
attributes:
|
||||
label: 文書の中の位置
|
||||
description: 見出し、行番号、設定の項目の名前のどれかを書いてください。
|
||||
placeholder: README の「制限事項」の 2 つ目の項目
|
||||
validations:
|
||||
required: true
|
||||
|
||||
- type: textarea
|
||||
id: says
|
||||
attributes:
|
||||
label: 今の記述
|
||||
description: そのまま引用してください。元の文書を開かずに検討できるようにするためです。
|
||||
validations:
|
||||
required: true
|
||||
|
||||
- type: textarea
|
||||
id: problem
|
||||
attributes:
|
||||
label: どこが問題か
|
||||
description: |
|
||||
誤り、書き漏れ、曖昧さのどれに当たるかを書いてください。それによって読む人が何を取り違えるかも書いてください。
|
||||
実際の動きと食い違っているときは、文書と動きのどちらを直すべきと考えるかも書いてください。
|
||||
validations:
|
||||
required: true
|
||||
|
||||
- type: textarea
|
||||
id: suggestion
|
||||
attributes:
|
||||
label: 提案する文面
|
||||
description: 具体的な文面があると、早く直せます。
|
||||
|
||||
- type: checkboxes
|
||||
id: checks
|
||||
attributes:
|
||||
label: 報告の前に
|
||||
options:
|
||||
- label: 最新のリリースか、既定のブランチの最新の文書で確かめました。
|
||||
required: true
|
||||
@@ -0,0 +1,42 @@
|
||||
name: 機能の提案
|
||||
description: 新しい機能や設定の項目、既存の動きの変更を提案します。
|
||||
title: "[Proposal] "
|
||||
labels: ["enhancement"]
|
||||
body:
|
||||
- type: textarea
|
||||
id: problem
|
||||
attributes:
|
||||
label: 困っていること
|
||||
description: 今のプラグインでできないことや、手間がかかることを、利用者の立場で書いてください。
|
||||
validations:
|
||||
required: true
|
||||
|
||||
- type: textarea
|
||||
id: workaround
|
||||
attributes:
|
||||
label: 今はどうしているか
|
||||
description: 今の回避策と、それにかかる手間を書いてください。回避策が無ければ、その旨を書いてください。
|
||||
validations:
|
||||
required: true
|
||||
|
||||
- type: textarea
|
||||
id: proposal
|
||||
attributes:
|
||||
label: 提案する動き
|
||||
description: どう動いてほしいかを書いてください。設定の項目を増やす提案では、項目の名前、範囲、既定値の案も書いてください。
|
||||
|
||||
- type: textarea
|
||||
id: alternatives
|
||||
attributes:
|
||||
label: 検討したほかの方法
|
||||
description: ほかに考えた方法があれば、それでは足りない理由と一緒に書いてください。
|
||||
|
||||
- type: checkboxes
|
||||
id: checks
|
||||
attributes:
|
||||
label: 提案の前に
|
||||
options:
|
||||
- label: 既存の Issue を検索し、同じ提案が無いことを確かめました。
|
||||
required: true
|
||||
- label: 最新のリリースに同じ機能が無いことを確かめました。
|
||||
required: true
|
||||
@@ -0,0 +1,49 @@
|
||||
name: 使い方の質問
|
||||
description: 使い方や、実際の動きが仕様どおりかを尋ねます。
|
||||
title: "[Question] "
|
||||
labels: ["question"]
|
||||
body:
|
||||
- type: markdown
|
||||
attributes:
|
||||
value: |
|
||||
プラグインの不具合だと分かっているときは、不具合の報告を使ってください。
|
||||
|
||||
- type: textarea
|
||||
id: question
|
||||
attributes:
|
||||
label: 質問
|
||||
description: 背景を書く前に、質問を 1 文か 2 文で書いてください。
|
||||
validations:
|
||||
required: true
|
||||
|
||||
- type: textarea
|
||||
id: goal
|
||||
attributes:
|
||||
label: 何をしようとしているか
|
||||
description: つまずいている操作だけでなく、最終的に何を作りたいかを書いてください。
|
||||
validations:
|
||||
required: true
|
||||
|
||||
- type: textarea
|
||||
id: tried
|
||||
attributes:
|
||||
label: 試したこと
|
||||
description: 試した設定と、そのとき実際に起きたことを書いてください。
|
||||
|
||||
- type: input
|
||||
id: plugin-version
|
||||
attributes:
|
||||
label: プラグインのバージョン
|
||||
placeholder: v1.0.0
|
||||
validations:
|
||||
required: true
|
||||
|
||||
- type: checkboxes
|
||||
id: checks
|
||||
attributes:
|
||||
label: 質問の前に
|
||||
options:
|
||||
- label: README の該当する節を読みました。
|
||||
required: true
|
||||
- label: 既存の Issue を検索し、同じ質問が無いことを確かめました。
|
||||
required: true
|
||||
@@ -0,0 +1,21 @@
|
||||
MIT License
|
||||
|
||||
Copyright (c) 2024 Sergio Pedri
|
||||
|
||||
Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||
of this software and associated documentation files (the "Software"), to deal
|
||||
in the Software without restriction, including without limitation the rights
|
||||
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
||||
copies of the Software, and to permit persons to whom the Software is
|
||||
furnished to do so, subject to the following conditions:
|
||||
|
||||
The above copyright notice and this permission notice shall be included in all
|
||||
copies or substantial portions of the Software.
|
||||
|
||||
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
||||
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
||||
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
||||
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
||||
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
||||
SOFTWARE.
|
||||
+368
-23
@@ -1,49 +1,394 @@
|
||||
========================================
|
||||
波動光学 for YMM4 v1.0.0
|
||||
波動光学 for YMM4 v3.1.0
|
||||
========================================
|
||||
YukkuriMovieMaker4(YMM4)上で動作する、フラウンホーファー回折理論に基づいて計算した
|
||||
点像分布関数(PSF)で映像を畳み込む映像エフェクトプラグインです。
|
||||
波長・F値・画素ピッチ・開口形状・ゼルニケ波面収差係数をパラメータとして設定でき、
|
||||
円形開口・正多角形開口・中央遮蔽・6 種類の波面収差項に対応します。
|
||||
各パラメータはアニメーションに対応しています。
|
||||
YukkuriMovieMaker4上で動作する、素材を回折も収差もない理想の像とみなし、
|
||||
レンズの開口と波面収差から求めた点像分布関数で畳み込んで、
|
||||
回折と収差によるにじみを描画する映像エフェクトプラグインです。
|
||||
点像分布関数は、1点から出た光が撮像面でどう広がるかを表す関数です。
|
||||
開口は、レンズの中で光が通る穴です。回折は、光が開口の縁を回り込んで広がる
|
||||
現象です。光の波の山をつないだ面を波面と呼び、
|
||||
波面が理想の形からずれることを波面収差と呼びます。
|
||||
畳み込みは、素材の各画素の光を点像分布関数の形に広げて足し合わせる計算です。
|
||||
瞳関数は、開口の各点を通る光の振幅と位相を表す関数です。
|
||||
振幅は波の揺れの大きさ、位相は波の進み具合です。
|
||||
本プラグインは、瞳関数のフラウンホーファー回折を高速フーリエ変換で解いて
|
||||
点像分布関数を求めます。フラウンホーファー回折は、開口から十分に遠い面や、
|
||||
レンズの焦点面で見る回折です。高速フーリエ変換は、画像や波形を周波数ごとの成分に
|
||||
分けて表す変換を、速く計算する方法です。
|
||||
履歴フレーム、参照画像、深度情報、学習済みモデルは使用しません。
|
||||
にじみの形は光学系と収差の設定から決定論的に決まり、同じ設定では常に
|
||||
同じ形になります。
|
||||
適用量、利得、ハイライトのしきい値、ハイライトの強さ、波長、F値、画素ピッチ、
|
||||
開口回転、中央遮蔽、デフォーカス、縦横非点収差、斜め非点収差、水平コマ収差、
|
||||
垂直コマ収差、球面収差の15項目はアニメーションに対応しています。
|
||||
畳み込みはGPUで計算します。畳み込みを計算し直したフレームでは、その結果を
|
||||
画面に出す前に検査します。GPUを使えないときと、検査で誤りを見つけたときは、
|
||||
CPUで計算します。
|
||||
「線形光」をオンにすると、
|
||||
画素の値を光の強さに比例する値へ直してから畳み込みます。
|
||||
「ハイライトの強さ」を上げると、光源のような明るい部分を持ち上げて、
|
||||
回折の筋のような小さな光を見えるようにできます。
|
||||
エフェクトの種類一覧では「波動光学」として表示されます。
|
||||
--------------------------------------------------------------------------------
|
||||
■ 動作要件
|
||||
--------------------------------------------------------------------------------
|
||||
- OS : Windows 10 バージョン 2004 (ビルド 19041) 以降 / Windows 11 (64bit)
|
||||
- YMM4 : YukkuriMovieMaker4(最新版を推奨)
|
||||
- OS : Windows 10 バージョン2004(ビルド19041)以降、または
|
||||
64ビット版のWindows 11
|
||||
- YMM4 : YukkuriMovieMaker4の最新版を推奨します
|
||||
- ランタイム : .NET 10.0
|
||||
- GPU : Direct3D 12とDirect3D 11・12間の共有テクスチャおよび
|
||||
共有フェンスを利用できるGPUを推奨します。
|
||||
利用できない場合は、CPUで計算します。
|
||||
--------------------------------------------------------------------------------
|
||||
■ 注意事項
|
||||
--------------------------------------------------------------------------------
|
||||
- AviUtl 非対応: 本プラグインは AviUtl 形式(.exo)への出力に対応していません。
|
||||
- AviUtl非対応: 本プラグインはAviUtl向けのEXO出力に対応していません。
|
||||
|
||||
- 品質と計算負荷: 品質「高精度」では FFT 格子サイズが 512 になるため、パラメータ変更
|
||||
時の計算負荷が増加します。リアルタイムプレビュー中にパラメータを頻繁に変更する
|
||||
場合は「高速」への切り替えを検討してください。
|
||||
- デフォルトの設定: 追加した直後は、映像はわずかにやわらぐだけです。
|
||||
にじみを大きくするには、デフォーカスの絶対値かF値を上げてください。
|
||||
デフォーカスは、焦点の位置のずれを表す項目です。単位のwavesは、
|
||||
波長を1とした量です。
|
||||
|
||||
- カーネル半径と出力サイズ: 適用量が 0% より大きい場合、出力矩形は入力矩形よりも
|
||||
カーネル半径分だけ拡張されます。
|
||||
- 品質と収差: 品質は、瞳関数を置く格子の大きさを切り替えます。
|
||||
格子は瞳関数の値を縦横に並べた表で、1つ1つの値を標本と呼びます。
|
||||
格子が粗いと、大きな波面収差で位相が急に変わる所を表しきれず、
|
||||
点像分布関数の形が崩れます。波面収差の絶対値を大きくするときは、
|
||||
品質を上げてください。
|
||||
|
||||
- 適用量が 0% の場合: 畳み込みは実行されず、入力がそのまま出力されます。
|
||||
- カーネル半径: 1〜63画素で、デフォルトは15画素です。カーネルは、
|
||||
畳み込みの重みを正方形に並べたものです。正方形は、
|
||||
中心から上下左右にカーネル半径の画素数まで広がります。
|
||||
正方形の外に届く光は捨て、カーネルの値の和が1になるように正規化します。
|
||||
デフォーカスの絶対値を大きくするときは、カーネル半径を上げてください。
|
||||
デフォルトの波長、F値、画素ピッチで標準の品質のとき、
|
||||
にじみは中心から約35画素までしか広がりません。それより大きなにじみには、
|
||||
品質も上げてください。品質を上げるほど、点像分布関数の計算が重くなります。
|
||||
カーネル半径と計算の重さの関係は、処理負荷の項目にあります。
|
||||
|
||||
- 計算モデルの制限: 計算は単色のフラウンホーファー回折に限定されます。
|
||||
白色光や多色光のシミュレーションには対応していません。
|
||||
- 利得: 利得は、畳み込んだ結果に掛ける倍率です。100%で、
|
||||
丸める前の値の総和を保ちます。利得を掛けた結果は、入力映像と混ぜる前に、
|
||||
各成分が表せる最大の値で打ち切り、
|
||||
さらに色の成分が不透明度を超えないように抑えます。
|
||||
|
||||
- カーネル半径の範囲: カーネル半径は 1 〜 15 px の範囲で指定できます
|
||||
(カーネルサイズ最大 31×31)。
|
||||
- 線形光: 画素の値は、光の強さに比例していません。光の強さに比例する値を、
|
||||
線形の値と呼びます。線形光をオンにすると、
|
||||
素材の画素の値を線形の値へ直してから畳み込み、結果を画素の値へ戻します。
|
||||
光の回折とにじみは、光の強さを足し合わせる現象なので、
|
||||
線形の値で畳み込むほうが実際の光に合います。
|
||||
白と黒の画素が1画素ずつ交互に並ぶ市松模様を大きくぼかしたときの平均は、
|
||||
画素の値のままでは約128、線形光では約188です。半透明の画素は、
|
||||
素材の色を不透明度で割って元の色に戻してから変換し、
|
||||
変換した値に不透明度を掛け直します。オフのときは、
|
||||
画素の値をそのまま畳み込みます。
|
||||
|
||||
- 本プラグインを使用する前に、YMM4 プロジェクトファイルのバックアップを
|
||||
作成することを推奨します。
|
||||
- ハイライト: ハイライトのしきい値と強さは、線形光がオンのときだけ働きます。
|
||||
素材は8ビットで、光源の画素の値は1.0で頭打ちです。
|
||||
回折の筋のように中心よりはるかに小さい光は、
|
||||
そのままでは出力の1階調に届きません。強さを上げると、
|
||||
明るい画素を持ち上げてから畳み込むので、そうした光が見えるようになります。
|
||||
画素の最も明るいチャンネルの値をmとし、しきい値をtとします。
|
||||
mがt以下の画素は持ち上げません。mがtを超えると、倍率は、
|
||||
(m - t) / (1 - t)の2乗に比例して上がります。mが1のとき、倍率は強さの値です。
|
||||
倍率は、色と不透明度のすべての成分に掛けます。強さが1倍のときと、
|
||||
しきい値が100%のときは、持ち上げません。持ち上げた分の光が加わるので、
|
||||
出力の総和は素材より大きくなります。明るさを戻すには、利得を下げてください。
|
||||
光源の本当の明るさは復元せず、指定した倍率で光を足す処理です。
|
||||
|
||||
- ディザ: 出力は8ビットに丸めます。点のような小さな明るい部分では、
|
||||
広がった光のうちの小さな値が0に丸められて、
|
||||
出力の総和が素材より少なくなります。ディザをオンにすると、丸める前の値に、
|
||||
0以上1未満の値を足してから、小数を切り捨てます。足す値は、
|
||||
画素の位置だけで決まります。1つの画素の赤、緑、青、不透明度には、
|
||||
同じ値を足します。同じ設定では、同じ画素に毎回同じ値を足すので、
|
||||
フレームが変わってもちらつきません。カーネル半径を変えると、
|
||||
計算領域の余白が変わるので、模様は動きます。黒と白は変わりません。
|
||||
測定の条件は、F値16、画素ピッチ2μm、カーネル半径63画素です。
|
||||
黒い背景の半径2画素の白い円の出力の総和は、ディザなしで素材の91.1%、
|
||||
ディザありで100.2%でした。ディザありの値は、模様により2%ほど動きます。
|
||||
|
||||
- 適用量0%: 適用量は、入力映像と、利得を掛けた結果を混ぜる割合です。
|
||||
適用量が0%のときは入力を変更せず、畳み込みの計算も行いません。
|
||||
|
||||
- アダプター: 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が浮動小数点数で足して求めます。そのため、2つ目の検査は、
|
||||
素材を直す計算の誤りを見つけません。この誤りは、3つ目の検査が見つけます。
|
||||
利得だけを変えたフレームのうち、
|
||||
キャッシュの項目にある保存した値にGPUで利得を掛け直すフレームでは、
|
||||
その計算を検査しません。
|
||||
|
||||
- GPUの異常: 自己試験か検査で不合格になったこと、GPUが突然使えなくなったこと、
|
||||
GPUの経路で想定していない例外が起きたことを、GPUの異常と呼びます。
|
||||
メモリを確保できなかったことは、GPUのメモリでもシステムメモリでも、
|
||||
GPUの異常に含めません。自己試験の最中にメモリを確保できなかったときだけは、
|
||||
自己試験の不合格として扱い、GPUの異常に含めます。
|
||||
GPUの異常が起きたときは、そのフレームをCPUの経路で計算し直します。
|
||||
異常を起こしたアダプターでは、一時的な不具合でも、
|
||||
YMM4を終了するまでCPUの経路で計算し、共有テクスチャなど、
|
||||
GPUの資源を解放します。GPUの経路でメモリを確保できなかったときも、
|
||||
YMM4を終了するまでCPUの経路で計算します。
|
||||
|
||||
- 異常の送信: GPUの異常の内容は、開発者へ自動で送信します。送信は、
|
||||
YMM4の起動中にアダプターごとに1回だけです。
|
||||
GPUの経路でメモリを確保できなかったときは、送信しません。
|
||||
自己試験の最中にメモリを確保できなかったときだけは、
|
||||
自己試験の不合格として送信します。
|
||||
送信する報告の数には、さらに上限があります。
|
||||
上限は、「不具合の報告」で説明しています。
|
||||
|
||||
- 処理対象: 畳み込みには現在のフレームの色と不透明度だけを使用します。
|
||||
履歴フレーム、外部画像、深度情報、学習済みモデルは使用しません。
|
||||
素材のすべての画素が透明なときは、エフェクトを適用せず入力映像を表示します。
|
||||
|
||||
- 計算モデル: 計算は単色のフラウンホーファー回折に限ります。
|
||||
白色光のように波長の混ざった光は扱いません。
|
||||
点像分布関数は画面のどこでも同じで、
|
||||
像の位置や素材の奥行きで変わるにじみは扱いません。畳み込みは、既定では、
|
||||
画素の値をそのまま重み付けして足し合わせます。線形光をオンにしたときだけ、
|
||||
画素の値を光の強さに比例する値へ直してから畳み込みます。
|
||||
|
||||
- 計算領域: 透明な部分も含む素材全体の矩形の上下左右に余白を加えた大きさを
|
||||
計算領域とし、長辺は8192画素が上限です。余白は、
|
||||
カーネル半径を4画素単位に切り上げた画素数で、16画素を下回りません。
|
||||
素材の長辺の上限は、8192画素から余白の2倍を引いた値です。
|
||||
カーネル半径が16画素以下なら8160画素、63画素なら8064画素になります。
|
||||
素材の長辺がこの上限を超える場合は、エフェクトを適用せず入力映像を
|
||||
表示します。
|
||||
|
||||
- 中央遮蔽: 中央遮蔽で開口をほとんどふさぎ、瞳関数の格子に光の通る標本が
|
||||
1つも無くなる設定では、エフェクトを適用せず入力映像を表示します。
|
||||
品質を上げると起きにくくなります。
|
||||
|
||||
- 処理負荷: 畳み込む範囲が大きいほど、計算は重くなります。畳み込む範囲は、
|
||||
素材の透明でない画素をすべて囲む最小の矩形をカーネル半径だけ広げ、
|
||||
外側の4画素の倍数の位置へそろえた範囲です。
|
||||
広げた範囲が計算領域の外へ出るときは、計算領域の端で切ります。
|
||||
畳み込む範囲を正方形のタイルに分け、
|
||||
タイルごとに高速フーリエ変換で畳み込みます。タイルの一辺Tは、
|
||||
カーネル半径が23画素以下なら128画素、24画素以上なら512画素です。
|
||||
タイルの縁からカーネル半径の幅の値は捨てるので、カーネル半径を上げるほど、
|
||||
1枚のタイルが出力できる範囲は狭まります。カーネル半径を上げても、Tが同じなら、
|
||||
必要なタイルの枚数は減らず、増えることがあります。枚数が増えるほど、
|
||||
計算は重くなります。カーネル半径を23画素から24画素に上げると、
|
||||
タイルが大きくなり、出力できる範囲が広がります。そのため、
|
||||
畳み込む範囲が大きい素材では計算が軽くなることがあり、
|
||||
小さい素材ではかえって重くなることがあります。収差を入れても、
|
||||
畳み込みの計算量は変わりません。CPUの経路は、全く透明な行と、
|
||||
全く透明なタイルを省くので、素材の中身によっても時間が変わります。
|
||||
品質を上げると、点像分布関数の計算が重くなります。線形光をオンにすると、
|
||||
CPUの経路では、素材を線形の値へ直す計算が増えます。そのため、
|
||||
素材が変わるフレームの時間が長くなります。GPUの経路では、
|
||||
ほとんど変わりません。
|
||||
|
||||
- メモリ: エフェクト1つあたり、GPUの経路では、2つの共有テクスチャをGPUに
|
||||
確保します。素材を入れる共有テクスチャは、素材の1画素につき4バイトです。
|
||||
結果を入れる共有テクスチャは、畳み込む範囲の1画素につき4バイトです。
|
||||
畳み込む範囲が入りきらなくなったときだけ、結果を入れる共有テクスチャを、
|
||||
そのときの範囲の大きさで作り直します。
|
||||
|
||||
- 作業領域: GPUの経路では、共有テクスチャのほかに、
|
||||
16MB以下のタイルの作業領域、カーネルを高速フーリエ変換したスペクトル、
|
||||
検査に使う値を書くバッファーを確保します。CPUの経路では、素材の画素の配列、
|
||||
出力の画素の配列、作業スレッドの作業領域をシステムメモリに確保します。
|
||||
作業領域のうち、タイルの分は合計で64MB以下です。このほかに、
|
||||
素材を読むためのDirect2Dのビットマップと、出力を書くためのDirect2Dの
|
||||
ビットマップも確保します。出力を書くためのビットマップは、
|
||||
畳み込む範囲を収められる大きさで、収まらなくなったときだけ作り直します。
|
||||
どちらの経路でも、利得だけを変えたフレームの後は、
|
||||
畳み込む範囲の1画素につき16バイトを追加で確保します。この領域は、
|
||||
キャッシュの項目にある保存した値のためのものです。
|
||||
|
||||
- キャッシュ: 素材の大きさと色と不透明度が変わらず、
|
||||
「利得」と「適用量」と「ディザ」以外の項目も変わらないフレームでは、
|
||||
畳み込みの計算を再利用します。利得かディザだけを変えたフレームでは、
|
||||
最初の1回だけ畳み込みを計算し直し、利得を掛ける前の値を保存します。
|
||||
2回目からは、保存した値に利得とディザを反映して描き直します。素材か、
|
||||
「利得」と「適用量」と「ディザ」以外の項目が変わると、保存した値を破棄します。
|
||||
ただし、線形光がオフのときは、ハイライトの2項目が変わっても破棄しません。
|
||||
適用量だけを変えたフレームでは、混ぜる割合だけを変えます。
|
||||
動画や口パクのように素材の内容が変わるフレームと、
|
||||
「利得」と「適用量」と「ディザ」以外の項目をアニメーションで変えたフレームでは
|
||||
、毎回計算し直すので処理が重くなります。素材が変わったかどうかを調べる計算は、
|
||||
再利用するフレームでも毎フレーム行います。開口形状が円形のときは、
|
||||
「羽根枚数」と「開口回転」を変えても、計算し直しません。
|
||||
|
||||
- 再現性: 計算は決定論的で、時間値や乱数を使用しません。
|
||||
同じ素材と同じ設定から常に同じ結果になるのは、同じ経路で、GPU、ドライバー、
|
||||
CPU、Windows、.NETの組が同じときです。GPUの経路でも結果にCPUが関わるのは、
|
||||
点像分布関数とカーネルのスペクトルをCPUで求めるためです。
|
||||
GPUの経路とCPUの経路では、結果がわずかに違います。
|
||||
GPUの異常でCPUの経路に切り替わったときも、同じ設定で結果がわずかに
|
||||
変わります。
|
||||
|
||||
- 透明部分: 畳み込みは不透明度にも掛かるので、素材の縁の外にも半透明の
|
||||
にじみが広がります。出力の範囲は、素材の範囲と畳み込む範囲を合わせた
|
||||
ものです。適用量が0%のときは、素材の範囲のままです。
|
||||
|
||||
- 更新通知: エフェクトを最初に生成したときに、YMM4の実行中に一度だけ
|
||||
新しい正式版を確認します。更新情報を取得できない場合は通知せず、
|
||||
そのまま動作します。プレリリースは通知の対象に含めません。
|
||||
|
||||
- 本プラグインを使用する前に、YMM4のプロジェクトファイルのバックアップを
|
||||
作成することを推奨します。
|
||||
--------------------------------------------------------------------------------
|
||||
■ 不具合の報告
|
||||
--------------------------------------------------------------------------------
|
||||
本プラグインは、想定していない例外が起きたときと、GPUの異常でCPUの経路に
|
||||
切り替えたときに、その内容を開発者へ自動で送信します。同意は求めず、
|
||||
常に送信します。
|
||||
|
||||
送信する情報は次のとおりです。
|
||||
例外 : 型の完全名、メッセージ、スタックトレース
|
||||
発生位置 : モジュール名、関数名、ファイル名、行番号
|
||||
プラグイン : アセンブリ名、バージョン
|
||||
実行環境 : OSの名前とバージョン、.NETのバージョン、
|
||||
CPUのアーキテクチャ、論理プロセッサ数
|
||||
識別子 : YMM4の起動ごとに決まるセッション識別子、報告ごとの識別子
|
||||
GPUの異常 : 切り替えた理由、不合格になった検査の名前と測定値と
|
||||
参照値と許容値、アダプターの名前、ベンダーIDと
|
||||
デバイスIDとサブシステムIDとリビジョン、
|
||||
ドライバーのバージョン、ソフトウェア アダプターかどうか、
|
||||
計算領域の幅と高さ、必要なGPUメモリの見積もり
|
||||
|
||||
映像の中身とプロジェクトの内容は送信しません。継続して個人を追跡する
|
||||
識別子も持ちません。セッション識別子はYMM4を起動し直すと別の値に
|
||||
なります。メッセージとファイル名に含まれる利用者名などの文字列は、送信の
|
||||
前に置き換えます。送信元のIPアドレスは受信側へ渡す手前で取り除いています。
|
||||
|
||||
送信するのは、想定していない例外と、GPUの異常でCPUの経路に
|
||||
切り替えたことだけです。GPUの異常は、注意事項の「GPUの異常」の項目で
|
||||
説明しています。YMM4が本プラグインのエフェクトを作るとき、
|
||||
フレームごとに更新するとき、入力をつなぎ直すとき、破棄するときと、
|
||||
Direct2Dがシェーダーの定数を書き込むときに起きた例外を報告し、
|
||||
その後はYMM4へそのまま渡します。ただし、GPUの経路の計算中に起きた例外は、
|
||||
YMM4へは渡さず、そのフレームをCPUの経路で計算し直します。
|
||||
この例外は、GPUの異常として報告しますが、メモリを確保できなかったものは
|
||||
報告しません。自己試験の最中に確保できなかったときだけは、
|
||||
自己試験の不合格として報告します。
|
||||
GPUの異常の報告は、YMM4の起動中にアダプターごとに1回だけです。
|
||||
|
||||
更新の確認では、更新情報の取得と比較で起きた例外は報告しません。
|
||||
通知の文を組み立てて表示するときに起きた例外は報告し、YMM4へは渡しません。
|
||||
画面の操作やバックグラウンドの処理で未処理になった例外も報告しますが、
|
||||
本プラグインのコードが関わる例外に限ります。本プラグインの外で起きた例外は
|
||||
送信しません。
|
||||
|
||||
次の失敗は送信しません。
|
||||
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を起動したあと、本プラグインのエフェクトを生成するか、
|
||||
同じくYMM4-Telemetryで報告する別のプラグインが動き始めると、
|
||||
退避した報告を1回の起動で10件まで送り直します。
|
||||
送信も再送も非同期に行うため、通信を待って起動と描画が遅くなることは
|
||||
ありません。
|
||||
|
||||
上限を超えて捨てた報告は、退避も再送もしません。
|
||||
再送は、どちらの上限の件数にも入れません。
|
||||
--------------------------------------------------------------------------------
|
||||
■ 免責事項
|
||||
--------------------------------------------------------------------------------
|
||||
本プラグインは MIT ライセンスのもとで公開されています。
|
||||
本ソフトウェアは「現状のまま」提供されており、明示・黙示を問わず、
|
||||
本プラグインはMITライセンスのもとで公開されています。
|
||||
本ソフトウェアは「現状のまま」提供されており、明示または黙示を問わず、
|
||||
商品性、特定目的への適合性、および権利非侵害に関する保証を含む、
|
||||
いかなる種類の保証も行いません。
|
||||
作者は、本プラグインの使用または使用不能に起因するいかなる損害についても、
|
||||
一切の責任を負いません。
|
||||
ご利用は自己責任でお願いします。
|
||||
--------------------------------------------------------------------------------
|
||||
■ サードパーティライセンス
|
||||
--------------------------------------------------------------------------------
|
||||
本プラグインはComputeWeave(MIT License)を同梱しています。
|
||||
ライセンスの全文は同梱のLICENSEフォルダー(ComputeWeave.txt)に収録しています。
|
||||
ComputeWeave : Copyright (c) 2024 Sergio Pedri
|
||||
--------------------------------------------------------------------------------
|
||||
■ ライセンス
|
||||
--------------------------------------------------------------------------------
|
||||
|
||||
@@ -0,0 +1,87 @@
|
||||
<!--
|
||||
当てはまらない節は消してください。「関連する Issue」と「動きの変更」の節は残し、該当しないときは「なし」と書いてください。
|
||||
-->
|
||||
|
||||
## 概要
|
||||
|
||||
<!--
|
||||
何をどう変えたか。なぜその変更が必要か。
|
||||
-->
|
||||
|
||||
## 関連する Issue
|
||||
|
||||
<!--
|
||||
新しい機能、設定の項目や既定値の変更、大きめの不具合の修正、意図して出力を変える変更、互換性を損なう変更、コードの構成を大きく変える変更は、先に Issue で合意してください。
|
||||
Issue が無い変更では、下の行を「なし」に書き換えてください。
|
||||
-->
|
||||
|
||||
Closes #
|
||||
|
||||
## 変更の種類
|
||||
|
||||
<!-- 当てはまるものを残してください。 -->
|
||||
|
||||
- 不具合の修正
|
||||
- 機能の追加
|
||||
- 動きの変更
|
||||
- 性能の改善
|
||||
- テストの追加
|
||||
- 依存関係の更新
|
||||
- 文書
|
||||
- ビルド、リリース
|
||||
|
||||
## 動きの変更
|
||||
|
||||
<!--
|
||||
利用者から見て何が変わるか。設定の項目、既定値、出力の結果、エラーの出方の変化も含みます。
|
||||
保存済みのプロジェクトの結果が変わるなら、必ず書いてください。
|
||||
-->
|
||||
|
||||
## 検証
|
||||
|
||||
<!--
|
||||
手元で実際に確かめた結果を書いてください。
|
||||
- ビルドの結果と、テストのプロジェクトがあればテストの結果
|
||||
- YukkuriMovieMaker4 で実際に動かして確かめたこと
|
||||
- 実行できなかったテストと、その理由
|
||||
実際に動かして観察したこと、コードを読んで判断したこと、推測したことを分けて書いてください。
|
||||
-->
|
||||
|
||||
使った YukkuriMovieMaker4 のバージョン:
|
||||
|
||||
GPU に関わる変更では、使った GPU とドライバー:
|
||||
|
||||
## 確認
|
||||
|
||||
<!-- テストのプロジェクトが無いリポジトリでは、実装とテストを分ける項目を消してください。 -->
|
||||
|
||||
- [ ] 1 つの目的の変更だけを含み、関係の無い整理や整形を含めていない。
|
||||
- [ ] どのコミットも、それ単独でビルドが通る。
|
||||
- [ ] 実装の変更と、それを確かめるテストを、別のコミットに分けた。
|
||||
- [ ] コミットの件名は日本語で書き、50 文字以内に収め、「〜する」の形で終えた。日本語で書けない場合は、その旨を「レビューで見てほしい点」に書いた。
|
||||
- [ ] コミットの本文は、リリースノートでの変更の分類を指定する行を求められたときだけ書いた。
|
||||
- [ ] 変更する箇所で既に使われている実装のパターンに従った。
|
||||
- [ ] 新しく書いたコードにコメントを入れず、コメントアウトしたコードも残していない。既存のコメントとドキュメントコメントは残した。
|
||||
- [ ] 自分の変更で増えたビルドの警告を直した。
|
||||
- [ ] 出力を変えるつもりの無い変更では、変更前と変更後で出力が一致することを確かめた。
|
||||
- [ ] この変更と関係の無い依存関係の更新を含めていない。
|
||||
- [ ] 動きを変えた場合、README を直した。`.github/Plugin_Readme.txt` があるリポジトリでは、それも直した。
|
||||
- [ ] バージョンを上げる変更を含めていない。
|
||||
|
||||
## 性能の改善を主張する場合
|
||||
|
||||
<!-- それ以外の場合は、この節ごと消してください。 -->
|
||||
|
||||
- [ ] 同じ機材、ドライバー、設定、電源の条件で、変更前と変更後のビルドを交互に繰り返し測った。
|
||||
- [ ] 測定の間を空け、ほかのプロセスが GPU を使っていない状態で測った。
|
||||
- [ ] 正しさの確認と性能の測定を、別々に実行した。
|
||||
|
||||
<!--
|
||||
測定の条件と、測定値。
|
||||
-->
|
||||
|
||||
## レビューで見てほしい点
|
||||
|
||||
<!--
|
||||
判断に迷った点、意見を聞きたい点、意図して外した部分とその理由。
|
||||
-->
|
||||
+321
-33
@@ -14,29 +14,18 @@ jobs:
|
||||
|
||||
steps:
|
||||
- name: ソースコードのチェックアウト
|
||||
uses: actions/checkout@v4
|
||||
uses: actions/checkout@v7
|
||||
with:
|
||||
submodules: recursive
|
||||
fetch-depth: 0
|
||||
|
||||
- name: .NET SDK のセットアップ
|
||||
uses: actions/setup-dotnet@v4
|
||||
uses: actions/setup-dotnet@v6
|
||||
with:
|
||||
dotnet-version: '10.0.x'
|
||||
|
||||
- name: fxc.exe の検索
|
||||
id: fxc
|
||||
shell: pwsh
|
||||
run: |
|
||||
$fxc = Get-ChildItem "C:\Program Files (x86)\Windows Kits\10\bin" -Recurse -Filter "fxc.exe" |
|
||||
Where-Object { $_.FullName -like "*x64*" } |
|
||||
Sort-Object FullName -Descending |
|
||||
Select-Object -First 1
|
||||
if (-not $fxc) {
|
||||
Write-Error "fxc.exe が見つかりませんでした。"
|
||||
exit 1
|
||||
}
|
||||
Write-Host "fxc.exe の場所: $($fxc.FullName)"
|
||||
echo "FXC_PATH=$($fxc.FullName)" >> $env:GITHUB_OUTPUT
|
||||
- name: MSBuild のセットアップ
|
||||
uses: microsoft/setup-msbuild@v3
|
||||
|
||||
- name: YMM4 最新リリースの取得と解凍
|
||||
id: ymm4
|
||||
@@ -64,25 +53,53 @@ jobs:
|
||||
echo "TAG=$tag" >> $env:GITHUB_OUTPUT
|
||||
echo "VERSION=$($tag.TrimStart('v'))" >> $env:GITHUB_OUTPUT
|
||||
|
||||
- name: resx ファイルの生成(初回ビルド)
|
||||
- name: バージョン記載の照合
|
||||
shell: pwsh
|
||||
run: |
|
||||
$proj = "Wave Optics/WaveOptics.csproj"
|
||||
dotnet build "$proj" `
|
||||
-c Release `
|
||||
-p:YMM4DirPath="${{ steps.ymm4.outputs.YMM4_DIR }}" `
|
||||
-p:FxcPath="${{ steps.fxc.outputs.FXC_PATH }}" `
|
||||
-p:Platform=x64 `
|
||||
-p:SkipPluginDeploy=true
|
||||
$tag = "${{ steps.version.outputs.TAG }}"
|
||||
$version = "${{ steps.version.outputs.VERSION }}"
|
||||
$problems = @()
|
||||
|
||||
$csprojPath = "WaveOptics/WaveOptics.csproj"
|
||||
$csproj = Get-Content $csprojPath -Raw
|
||||
if (-not $csproj.Contains("<Version>$version</Version>")) {
|
||||
$current = if ($csproj -match '<Version>([^<]*)</Version>') { $Matches[1] } else { "記載なし" }
|
||||
$problems += "$csprojPath の <Version> が $current です。$version にしてください。"
|
||||
}
|
||||
|
||||
$readmePath = ".github/Plugin_Readme.txt"
|
||||
$readme = Get-Content $readmePath -Raw
|
||||
if (-not $readme.Contains(" 波動光学 for YMM4 $tag")) {
|
||||
$current = if ($readme -match '(?m)^ 波動光学 for YMM4 (\S+)') { $Matches[1] } else { "記載なし" }
|
||||
$problems += "$readmePath の見出しが $current です。$tag にしてください。"
|
||||
}
|
||||
|
||||
if ($problems.Count -eq 0) {
|
||||
Write-Host "バージョン記載は $tag と一致しています"
|
||||
exit 0
|
||||
}
|
||||
|
||||
foreach ($problem in $problems) {
|
||||
Write-Host "::error::$problem"
|
||||
}
|
||||
Write-Host "::error::リリースの対象は $tag が指すコミットです。タグを付けた後で main へ訂正を積んでも、その訂正はリリースに入りません。タグを削除し、記載を直したコミットを積んでから付け直してください。"
|
||||
exit 1
|
||||
|
||||
- name: シェーダーのビルド
|
||||
shell: pwsh
|
||||
run: |
|
||||
msbuild WaveOptics.Shader/WaveOptics.Shader.vcxproj `
|
||||
/p:Configuration=Release `
|
||||
/p:Platform=Win32 `
|
||||
/nologo
|
||||
|
||||
- name: プロジェクトのビルド
|
||||
shell: pwsh
|
||||
run: |
|
||||
$proj = "Wave Optics/WaveOptics.csproj"
|
||||
$proj = "WaveOptics/WaveOptics.csproj"
|
||||
dotnet build "$proj" `
|
||||
-c Release `
|
||||
-p:YMM4DirPath="${{ steps.ymm4.outputs.YMM4_DIR }}" `
|
||||
-p:FxcPath="${{ steps.fxc.outputs.FXC_PATH }}" `
|
||||
-p:Platform=x64 `
|
||||
-p:SkipPluginDeploy=true
|
||||
|
||||
@@ -92,8 +109,8 @@ jobs:
|
||||
dotnet build WaveOptics.Tests/WaveOptics.Tests.csproj `
|
||||
-c Release `
|
||||
-p:YMM4DirPath="${{ steps.ymm4.outputs.YMM4_DIR }}" `
|
||||
-p:FxcPath="${{ steps.fxc.outputs.FXC_PATH }}" `
|
||||
-p:Platform=x64 `
|
||||
-p:SkipPluginDeploy=true `
|
||||
-maxcpucount:1
|
||||
|
||||
- name: テストの実行
|
||||
@@ -101,22 +118,45 @@ jobs:
|
||||
run: |
|
||||
dotnet test WaveOptics.Tests/WaveOptics.Tests.csproj `
|
||||
--no-build `
|
||||
--no-restore `
|
||||
-c Release `
|
||||
-p:Platform=x64
|
||||
-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
|
||||
run: |
|
||||
$version = "${{ steps.version.outputs.TAG }}"
|
||||
$outDir = "Wave Optics/bin/x64/Release/net10.0-windows10.0.19041.0"
|
||||
$outDir = "WaveOptics/bin/x64/Release/net10.0-windows10.0.19041.0"
|
||||
$stageRoot = "stage/WaveOptics"
|
||||
$pkgName = "WaveOptics_$version.ymme"
|
||||
|
||||
New-Item -ItemType Directory -Path $stageRoot -Force | Out-Null
|
||||
New-Item -ItemType Directory -Path "$stageRoot/LICENSE" -Force | Out-Null
|
||||
|
||||
Copy-Item "$outDir/WaveOptics.dll" "$stageRoot/"
|
||||
Copy-Item "$outDir/WaveOptics.Abstractions.dll" "$stageRoot/"
|
||||
foreach ($dll in @("$outDir/plugin/WaveOptics.dll", "$outDir/WaveOptics.Abstractions.dll")) {
|
||||
if (-not (Test-Path $dll)) {
|
||||
Write-Error "ビルド結果に $(Split-Path $dll -Leaf) が見つかりませんでした: $dll"
|
||||
exit 1
|
||||
}
|
||||
Copy-Item $dll "$stageRoot/"
|
||||
}
|
||||
|
||||
foreach ($lang in @("ar-sa", "en-us", "es-es", "id-id", "ko-kr", "zh-cn", "zh-tw")) {
|
||||
$src = "$outDir/$lang"
|
||||
@@ -126,16 +166,264 @@ jobs:
|
||||
}
|
||||
}
|
||||
|
||||
Copy-Item ".github/LICENSE/*.txt" "$stageRoot/LICENSE/"
|
||||
Copy-Item ".github/Plugin_Readme.txt" "$stageRoot/Readme.txt"
|
||||
|
||||
$readme = Get-Content "$stageRoot/Readme.txt" -Raw
|
||||
if (-not $readme.Contains(" 波動光学 for YMM4 $version")) {
|
||||
Write-Error "同梱する Readme.txt の見出しが $version と一致しません"
|
||||
exit 1
|
||||
}
|
||||
|
||||
Compress-Archive -Path "stage/*" -DestinationPath $pkgName -CompressionLevel Optimal
|
||||
echo "PKG_NAME=$pkgName" >> $env:GITHUB_OUTPUT
|
||||
|
||||
- name: 変更履歴の作成
|
||||
id: changelog
|
||||
shell: pwsh
|
||||
env:
|
||||
GH_TOKEN: ${{ github.token }}
|
||||
TAG: ${{ steps.version.outputs.TAG }}
|
||||
REPOSITORY: ${{ github.repository }}
|
||||
SERVER_URL: ${{ github.server_url }}
|
||||
PACKAGE: ${{ steps.package.outputs.PKG_NAME }}
|
||||
run: |
|
||||
$tag = $env:TAG
|
||||
$repository = $env:REPOSITORY
|
||||
$server = $env:SERVER_URL
|
||||
$code = [char]0x60
|
||||
$fence = [string]::new($code, 3)
|
||||
$unit = [char]0x1f
|
||||
$record = [char]0x1e
|
||||
|
||||
$previous = ""
|
||||
$candidates = @(git tag --list "v*" --merged $tag --sort=-creatordate | Where-Object { $_ -ne $tag })
|
||||
if ($candidates.Count -gt 0) {
|
||||
$previous = $candidates[0]
|
||||
}
|
||||
Write-Host "直前のタグ: $previous"
|
||||
|
||||
$range = if ($previous) { "$previous..$tag" } else { $tag }
|
||||
$log = (@(git log "--format=%H%x1f%s%x1f%an%x1f%ad%x1f%b%x1e" --date=short $range) -join "`n") -split $record
|
||||
|
||||
$commits = @()
|
||||
foreach ($entry in $log) {
|
||||
if (-not $entry.Trim()) { continue }
|
||||
$fields = $entry.TrimStart("`n") -split $unit
|
||||
if ($fields.Count -lt 5) { continue }
|
||||
$commits += [pscustomobject]@{
|
||||
Sha = $fields[0]
|
||||
Subject = $fields[1]
|
||||
Name = $fields[2]
|
||||
Date = $fields[3]
|
||||
Body = $fields[4]
|
||||
Login = ""
|
||||
Avatar = ""
|
||||
}
|
||||
}
|
||||
Write-Host "コミット数: $($commits.Count)"
|
||||
|
||||
$categories = [ordered]@{
|
||||
A = @{ Title = "追加"; Symbol = "+"; Items = [System.Collections.Generic.List[pscustomobject]]::new() }
|
||||
M = @{ Title = "変更"; Symbol = "~"; Items = [System.Collections.Generic.List[pscustomobject]]::new() }
|
||||
D = @{ Title = "削除"; Symbol = "-"; Items = [System.Collections.Generic.List[pscustomobject]]::new() }
|
||||
F = @{ Title = "修正"; Symbol = "!"; Items = [System.Collections.Generic.List[pscustomobject]]::new() }
|
||||
}
|
||||
foreach ($commit in $commits) {
|
||||
if (-not $commit.Body) { continue }
|
||||
foreach ($bodyLine in ($commit.Body -split "`n")) {
|
||||
$trimmed = $bodyLine.Trim()
|
||||
if ($trimmed -notmatch '^・(.+)-([AMDF])$') { continue }
|
||||
$categories[$Matches[2]].Items.Add([pscustomobject]@{ Text = $Matches[1]; Sha = $commit.Sha })
|
||||
}
|
||||
}
|
||||
|
||||
$pending = [System.Collections.Generic.HashSet[string]]::new()
|
||||
foreach ($commit in $commits) {
|
||||
[void]$pending.Add($commit.Sha)
|
||||
}
|
||||
|
||||
$accounts = @{}
|
||||
$page = 1
|
||||
while ($pending.Count -gt 0 -and $page -le 20) {
|
||||
$rows = @()
|
||||
try {
|
||||
$rows = @(gh api "repos/$repository/commits?sha=$tag&per_page=100&page=$page" --jq '.[] | [.sha, (.author.login // ""), (.author.avatar_url // "")] | @tsv')
|
||||
}
|
||||
catch {
|
||||
Write-Host "コミットの作者を取得できませんでした: $($_.Exception.Message)"
|
||||
break
|
||||
}
|
||||
if ($LASTEXITCODE -ne 0 -or $rows.Count -eq 0) { break }
|
||||
|
||||
foreach ($row in $rows) {
|
||||
$fields = $row -split "`t"
|
||||
if ($fields.Count -lt 3) { continue }
|
||||
if ($pending.Remove($fields[0])) {
|
||||
$accounts[$fields[0]] = @{ Login = $fields[1]; Avatar = $fields[2] }
|
||||
}
|
||||
}
|
||||
|
||||
if ($rows.Count -lt 100) { break }
|
||||
$page++
|
||||
}
|
||||
|
||||
foreach ($commit in $commits) {
|
||||
if ($accounts.ContainsKey($commit.Sha)) {
|
||||
$commit.Login = $accounts[$commit.Sha].Login
|
||||
$commit.Avatar = $accounts[$commit.Sha].Avatar
|
||||
}
|
||||
}
|
||||
|
||||
$emptyTree = "4b825dc642cb6eb9a060e54bf8d69288fbee4904"
|
||||
$base = if ($previous) { $previous } else { $emptyTree }
|
||||
$shortstat = (@(git diff --shortstat $base $tag) -join " ")
|
||||
$changedFiles = 0
|
||||
$insertions = 0
|
||||
$deletions = 0
|
||||
if ($shortstat -match "(\d+) file") { $changedFiles = [int]$Matches[1] }
|
||||
if ($shortstat -match "(\d+) insertion") { $insertions = [int]$Matches[1] }
|
||||
if ($shortstat -match "(\d+) deletion") { $deletions = [int]$Matches[1] }
|
||||
$diffStat = @(git diff --stat $base $tag)
|
||||
$tagDate = (git log -1 "--format=%ad" --date=short $tag)
|
||||
|
||||
$contributors = @($commits |
|
||||
Group-Object -Property { if ($_.Login) { $_.Login } else { $_.Name } } |
|
||||
Sort-Object -Property Count -Descending)
|
||||
|
||||
function Get-Icon($avatar, $login, $size) {
|
||||
if (-not $avatar) { return "" }
|
||||
$sized = if ($avatar.Contains("?")) { "$avatar&s=$($size * 2)" } else { "$avatar" + "?s=$($size * 2)" }
|
||||
return "<img src=""$sized"" width=""$size"" height=""$size"" alt=""$login""> "
|
||||
}
|
||||
|
||||
$package = Get-Item $env:PACKAGE
|
||||
$size = [math]::Round($package.Length / 1MB, 2)
|
||||
|
||||
$body = [System.Collections.Generic.List[string]]::new()
|
||||
$body.Add("## 概要")
|
||||
$body.Add("")
|
||||
$body.Add("| 項目 | 内容 |")
|
||||
$body.Add("|---|---|")
|
||||
$body.Add("| タグ | [$tag]($server/$repository/tree/$tag) |")
|
||||
$body.Add("| 公開日 | $tagDate |")
|
||||
if ($previous) {
|
||||
$body.Add("| 直前のリリース | [$previous]($server/$repository/releases/tag/$previous) |")
|
||||
}
|
||||
$body.Add("| コミット数 | $($commits.Count) |")
|
||||
$body.Add("| 貢献者 | $($contributors.Count) 名 |")
|
||||
$body.Add("| 変更されたファイル | $changedFiles |")
|
||||
$body.Add("| 追加された行 | $insertions |")
|
||||
$body.Add("| 削除された行 | $deletions |")
|
||||
|
||||
$hasHighlights = ($categories.Values | ForEach-Object { $_.Items.Count } | Measure-Object -Sum).Sum -gt 0
|
||||
if ($hasHighlights) {
|
||||
$body.Add("")
|
||||
$body.Add("## 主な変更")
|
||||
foreach ($key in $categories.Keys) {
|
||||
$category = $categories[$key]
|
||||
if ($category.Items.Count -eq 0) { continue }
|
||||
$body.Add("")
|
||||
$body.Add("### [$($category.Symbol)] $($category.Title)")
|
||||
$body.Add("")
|
||||
foreach ($item in $category.Items) {
|
||||
$short = $item.Sha.Substring(0, 7)
|
||||
$body.Add("- $($item.Text) ([$code$short$code]($server/$repository/commit/$($item.Sha)))")
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
$body.Add("")
|
||||
$body.Add("## ダウンロード")
|
||||
$body.Add("")
|
||||
$body.Add("| ファイル | サイズ |")
|
||||
$body.Add("|---|---|")
|
||||
$body.Add("| $($package.Name) | $size MB |")
|
||||
|
||||
$body.Add("")
|
||||
$body.Add("## 貢献者")
|
||||
$body.Add("")
|
||||
$body.Add("| 貢献者 | コミット数 |")
|
||||
$body.Add("|---|---|")
|
||||
foreach ($contributor in $contributors) {
|
||||
$first = $contributor.Group[0]
|
||||
if ($first.Login) {
|
||||
$name = (Get-Icon $first.Avatar $first.Login 40) + "[@$($first.Login)]($server/$($first.Login))"
|
||||
}
|
||||
else {
|
||||
$name = $first.Name
|
||||
}
|
||||
$body.Add("| $name | $($contributor.Count) |")
|
||||
}
|
||||
|
||||
$body.Add("")
|
||||
$body.Add("## 変更履歴")
|
||||
$body.Add("")
|
||||
$body.Add("| コミット | 内容 | 貢献者 | 日付 |")
|
||||
$body.Add("|---|---|---|---|")
|
||||
$maximumCommits = 300
|
||||
$listed = 0
|
||||
foreach ($commit in $commits) {
|
||||
if ($listed -ge $maximumCommits) { break }
|
||||
$short = $commit.Sha.Substring(0, 7)
|
||||
$subject = $commit.Subject -replace '\|', '\|'
|
||||
if ($commit.Login) {
|
||||
$author = (Get-Icon $commit.Avatar $commit.Login 20) + "[@$($commit.Login)]($server/$($commit.Login))"
|
||||
}
|
||||
else {
|
||||
$author = $commit.Name
|
||||
}
|
||||
$body.Add("| [$code$short$code]($server/$repository/commit/$($commit.Sha)) | $subject | $author | $($commit.Date) |")
|
||||
$listed++
|
||||
}
|
||||
if ($commits.Count -gt $maximumCommits) {
|
||||
$body.Add("")
|
||||
$body.Add("残り $($commits.Count - $maximumCommits) 件のコミットは省略しました。")
|
||||
}
|
||||
|
||||
if ($diffStat.Count -gt 0) {
|
||||
$body.Add("")
|
||||
$body.Add("## 変更されたファイル")
|
||||
$body.Add("")
|
||||
$body.Add("<details>")
|
||||
$body.Add("<summary>差分の統計</summary>")
|
||||
$body.Add("")
|
||||
$body.Add($fence)
|
||||
$maximumStatLines = 200
|
||||
$shown = 0
|
||||
foreach ($line in $diffStat) {
|
||||
if ($shown -ge $maximumStatLines) { break }
|
||||
$body.Add($line)
|
||||
$shown++
|
||||
}
|
||||
if ($diffStat.Count -gt $maximumStatLines) {
|
||||
$body.Add("... 残り $($diffStat.Count - $maximumStatLines) 行は省略しました。")
|
||||
}
|
||||
$body.Add($fence)
|
||||
$body.Add("")
|
||||
$body.Add("</details>")
|
||||
}
|
||||
|
||||
if ($previous) {
|
||||
$body.Add("")
|
||||
$body.Add("## 全ての変更")
|
||||
$body.Add("")
|
||||
$body.Add("$server/$repository/compare/$previous...$tag")
|
||||
}
|
||||
|
||||
$path = "release-body.md"
|
||||
Set-Content -Path $path -Value ($body -join "`n") -Encoding utf8NoBOM
|
||||
if (-not (Test-Path $path)) {
|
||||
throw "変更履歴を作成できませんでした。"
|
||||
}
|
||||
Write-Host "変更履歴の行数: $($body.Count)"
|
||||
$global:LASTEXITCODE = 0
|
||||
|
||||
- name: GitHub リリースの作成
|
||||
uses: softprops/action-gh-release@v2
|
||||
uses: softprops/action-gh-release@v3
|
||||
with:
|
||||
name: ${{ steps.version.outputs.TAG }}
|
||||
body_path: .github/CHANGELOG.md
|
||||
body_path: release-body.md
|
||||
files: ${{ steps.package.outputs.PKG_NAME }}
|
||||
draft: false
|
||||
prerelease: false
|
||||
+3
-1
@@ -362,4 +362,6 @@ MigrationBackup/
|
||||
.ionide/
|
||||
|
||||
# Fody - auto-generated XML schema
|
||||
FodyWeavers.xsd
|
||||
FodyWeavers.xsd
|
||||
# Stryker.NET
|
||||
StrykerOutput/
|
||||
@@ -1,3 +1,12 @@
|
||||
[submodule "YukkuriMovieMaker.Generator"]
|
||||
path = YukkuriMovieMaker.Generator
|
||||
url = https://github.com/manju-summoner/YukkuriMovieMaker.Generator.git
|
||||
[submodule "YMM4-GitHubUpdateNotifier"]
|
||||
path = YMM4-GitHubUpdateNotifier
|
||||
url = https://github.com/routersys/YMM4-GitHubUpdateNotifier.git
|
||||
[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
|
||||
@@ -0,0 +1,81 @@
|
||||
# Contributor Covenant 行動規範
|
||||
|
||||
## 私たちの約束
|
||||
|
||||
メンバー、貢献者、リーダーである私たちは、年齢、体格、目に見える障害と目に見えない障害、民族、性的特徴、性自認と性表現、経験の程度、教育、社会経済的地位、国籍、外見、人種、宗教、性的アイデンティティと性的指向を問わず、コミュニティへの参加を誰にとっても嫌がらせの無いものにすることを誓います。
|
||||
|
||||
私たちは、開かれていて誰もが歓迎される、多様で包摂的な、健全なコミュニティを作るように行動し、交流することを誓います。
|
||||
|
||||
## 私たちの基準
|
||||
|
||||
コミュニティのよい環境を作る行動の例は、次のとおりです。
|
||||
|
||||
- ほかの人に共感と思いやりを示す
|
||||
- 異なる意見、視点、経験を尊重する
|
||||
- 建設的な意見を伝え、また快く受け入れる
|
||||
- 自分たちの誤りに責任を持ち、影響を受けた人に謝り、その経験から学ぶ
|
||||
- 自分個人にとってだけでなく、コミュニティ全体にとって最善のことを考える
|
||||
|
||||
受け入れられない行動の例は、次のとおりです。
|
||||
|
||||
- 性的な言葉や画像を使うこと、どのような形であれ、相手に性的な関心を向けることや言い寄ること
|
||||
- 荒らし、侮辱的または軽蔑的な発言、個人攻撃や政治的な攻撃
|
||||
- 公の場か私的な場かを問わない嫌がらせ
|
||||
- 住所やメールアドレスなど、ほかの人の個人情報を明示の許可なく公開すること
|
||||
- 仕事の場で不適切と合理的に考えられるその他の行為
|
||||
|
||||
## 執行の責任
|
||||
|
||||
コミュニティリーダーは、受け入れられる行動の基準を明確にし、それを守らせる責任を負います。不適切、脅迫的、攻撃的、または有害と判断した行動には、適切で公正な是正措置をとります。
|
||||
|
||||
コミュニティリーダーは、この行動規範に沿わないコメント、コミット、コード、Wiki の編集、Issue、その他の貢献を削除、編集、または却下する権利と責任を持ちます。モデレーションの判断については、適切な場合に理由を伝えます。
|
||||
|
||||
## 適用範囲
|
||||
|
||||
この行動規範は、コミュニティのあらゆる場で適用されます。個人が公の場でコミュニティを公式に代表しているときにも適用されます。コミュニティを代表しているときとは、たとえば、公式のメールアドレスを使うとき、公式のソーシャルメディアのアカウントから投稿するとき、オンラインやオフラインのイベントで任命された代表として行動するときです。
|
||||
|
||||
## 執行
|
||||
|
||||
虐待的な言動、嫌がらせ、その他の受け入れられない行動は、執行を担当するコミュニティリーダーへ github.routersys@gmail.com で報告できます。コミュニティリーダーは、すべての苦情を速やかかつ公正に確認し、調査します。
|
||||
|
||||
すべてのコミュニティリーダーは、事案を報告した人のプライバシーと安全を尊重する義務を負います。
|
||||
|
||||
## 執行のガイドライン
|
||||
|
||||
コミュニティリーダーは、この行動規範に違反すると判断した行動への処置を決めるとき、次に示すコミュニティへの影響に応じたガイドラインに従います。
|
||||
|
||||
### 1. 是正
|
||||
|
||||
コミュニティへの影響: 不適切な言葉づかいや、コミュニティの中で、仕事の場にふさわしくない、または歓迎されないと判断されるその他の行動。
|
||||
|
||||
処置: コミュニティリーダーが、非公開の書面による警告を送ります。違反の内容を明らかにし、その行動がなぜ不適切だったかを説明します。公の場での謝罪を求めることがあります。
|
||||
|
||||
### 2. 警告
|
||||
|
||||
コミュニティへの影響: 1 回の出来事、または一連の行動による違反。
|
||||
|
||||
処置: 行動が続いた場合の処置を示した警告を送ります。警告を受けた人は、定められた期間、関係する人々とやり取りしてはいけません。行動規範を執行する人々へ、求められていないのに接触することも、これに含まれます。コミュニティの場だけでなく、ソーシャルメディアなど外部の場でのやり取りも避けなければなりません。これらの条件に違反すると、一時的または永久的な参加禁止につながることがあります。
|
||||
|
||||
### 3. 一時的な参加禁止
|
||||
|
||||
コミュニティへの影響: 不適切な行動を続けることを含む、コミュニティの基準への重大な違反。
|
||||
|
||||
処置: 定められた期間、コミュニティとのあらゆるやり取りと、コミュニティに向けた公の発信を禁止します。この期間中は、公の場か私的な場かを問わず、関係する人々とのやり取りを認めません。行動規範を執行する人々へ、求められていないのに接触することも、これに含まれます。これらの条件に違反すると、永久的な参加禁止につながることがあります。
|
||||
|
||||
### 4. 永久的な参加禁止
|
||||
|
||||
コミュニティへの影響: コミュニティの基準に繰り返し違反すること。不適切な行動を続けること、個人への嫌がらせ、特定の属性を持つ人々への攻撃や中傷も、これに当たります。
|
||||
|
||||
処置: コミュニティの中でのあらゆる公のやり取りを、永久に禁止します。
|
||||
|
||||
## 出典
|
||||
|
||||
この行動規範は、[Contributor Covenant][homepage] のバージョン 2.0 を基にしています。原文は https://www.contributor-covenant.org/version/2/0/code_of_conduct.html にあります。日本語の文は、公式の日本語訳 https://www.contributor-covenant.org/ja/version/2/0/code_of_conduct/ を基に、原文と照らし合わせて改めたものです。
|
||||
|
||||
Contributor Covenant は、[クリエイティブ・コモンズ 表示 4.0 国際 ライセンス](https://creativecommons.org/licenses/by/4.0/deed.ja)のもとで提供されています。
|
||||
|
||||
コミュニティへの影響に応じたガイドラインは、[Mozilla の行動規範の執行の段階](https://github.com/mozilla/diversity)に着想を得ています。
|
||||
|
||||
[homepage]: https://www.contributor-covenant.org
|
||||
|
||||
この行動規範についてのよくある質問と回答は、https://www.contributor-covenant.org/faq にあります。ほかの言語の訳は、https://www.contributor-covenant.org/translations にあります。
|
||||
+168
@@ -0,0 +1,168 @@
|
||||
# 貢献の手引き
|
||||
|
||||
本プラグインへの貢献に関心を持っていただき、ありがとうございます。この手引きは、Issue の立て方、プルリクエストの作り方、変更の確かめ方、コードとコミットの書き方を定めます。
|
||||
|
||||
本プラグインでできることとできないことは、[README](README.md) に書いてあります。まず README を読んでください。
|
||||
|
||||
---
|
||||
|
||||
## 目次
|
||||
|
||||
1. [貢献の進め方](#貢献の進め方)
|
||||
2. [開発環境](#開発環境)
|
||||
3. [Issue](#issue)
|
||||
4. [プルリクエスト](#プルリクエスト)
|
||||
5. [検証](#検証)
|
||||
6. [コードの規約](#コードの規約)
|
||||
7. [コミットの規約](#コミットの規約)
|
||||
8. [行動規範](#行動規範)
|
||||
|
||||
---
|
||||
|
||||
## 貢献の進め方
|
||||
|
||||
誤字の修正、文書の修正、軽微な不具合の修正は、そのままプルリクエストを送ってください。
|
||||
|
||||
新しい機能、設定の項目や既定値の変更、大きめの不具合の修正、意図して出力を変える変更、互換性を損なう変更、コードの構成を大きく変える変更は、先に Issue を立ててください。実装を始める前に、意図する動きと変更の範囲について合意するためです。どちらに当たるか迷ったときも、Issue を立ててください。
|
||||
|
||||
脆弱性は Issue に書かず、[セキュリティポリシー](SECURITY.md)に従って非公開で報告してください。
|
||||
|
||||
Issue とプルリクエストは、日本語か英語で書いてください。
|
||||
|
||||
---
|
||||
|
||||
## 開発環境
|
||||
|
||||
| 項目 | 要件 |
|
||||
|---|---|
|
||||
| OS | Windows 10 バージョン 2004 以降の 64bit 版 |
|
||||
| SDK | .NET 10 |
|
||||
| YukkuriMovieMaker4 | ビルドがインストール先の DLL を参照するため、手元に入れておく |
|
||||
| シェーダーのビルド | HLSL をビルドのときにコンパイルするリポジトリでは Windows SDK が要る。シェーダーを `.vcxproj` でビルドするリポジトリでは、Visual Studio 2026 の「C++ によるデスクトップ開発」も要る |
|
||||
|
||||
### 取得
|
||||
|
||||
リポジトリをフォークし、自分のフォークをクローンしてください。リポジトリはサブモジュールを含むことがあるので、`--recursive` を付けます。
|
||||
|
||||
```console
|
||||
git clone --recursive https://github.com/<自分のアカウント>/<リポジトリ名>.git
|
||||
```
|
||||
|
||||
`--recursive` を付けずにクローンしたときは、後から次のコマンドでサブモジュールを取得できます。
|
||||
|
||||
```console
|
||||
git submodule update --init --recursive
|
||||
```
|
||||
|
||||
作業は `main` から切ったブランチで行ってください。
|
||||
|
||||
### YukkuriMovieMaker4 の場所
|
||||
|
||||
YukkuriMovieMaker4 のインストール先は、MSBuild のプロパティ `YMM4DirPath` で渡します。値の末尾には `\` を付けてください。
|
||||
|
||||
- コマンドラインでは、`-p:YMM4DirPath="<インストール先>\"` を付けてビルドします。PowerShell 7 以降で実行してください。Windows PowerShell 5.1 と cmd では、末尾の `\"` が正しく渡らないため、末尾を `\\"` と書いてください。
|
||||
- Visual Studio でビルドするときは、プラグインのプロジェクトのフォルダーか、その上のフォルダーに `Directory.Build.props` があれば、その `YMM4DirPath` を手元で書き換えます。無ければ、環境変数 `YMM4DirPath` を設定します。書き換えた `Directory.Build.props` はコミットに含めないでください。サブモジュールの中にある `Directory.Build.props` は書き換えないでください。
|
||||
|
||||
### ビルド
|
||||
|
||||
ソリューションを開き、Release でビルドしてください。
|
||||
|
||||
シェーダーを `.vcxproj` でビルドするリポジトリでは、コマンドラインのビルドに Visual Studio の MSBuild を使ってください。.NET SDK の `dotnet` コマンドは `.vcxproj` を扱えません。テストは、`dotnet test <名前>.Tests\<名前>.Tests.csproj` のようにテストのプロジェクトのファイルを指定して実行してください。ビルドの手順は、`.github/workflows/release.yml` があればそこに書いてあります。
|
||||
|
||||
多くのリポジトリでは、ビルドの後にプラグインが YukkuriMovieMaker4 の `user\plugin` フォルダーへ自動でコピーされます。
|
||||
|
||||
- YukkuriMovieMaker4 を起動したままだと、コピーの段階で失敗します。ビルドの前に終了してください。
|
||||
- 配布版のプラグインを入れているときは、同じ名前のファイルが上書きされます。
|
||||
- コマンドラインでソリューションをビルドしたときはコピーしないリポジトリがあります。その場合は、プラグインのプロジェクトを指定してビルドしてください。
|
||||
- `.csproj` に `SkipPluginDeploy` の条件があるリポジトリでは、`-p:SkipPluginDeploy=true` を付けるとコピーせずにビルドできます。
|
||||
|
||||
---
|
||||
|
||||
## Issue
|
||||
|
||||
Issue はテンプレートから立ててください。不具合の報告、文書の不備、機能の提案、使い方の質問の 4 つがあります。
|
||||
|
||||
不具合の報告には、次の内容を書いてください。
|
||||
|
||||
- 期待した動きと、実際の動き
|
||||
- 再現の手順。できれば、問題が起きる最小のプロジェクトファイルや素材
|
||||
- プラグインのバージョン、YukkuriMovieMaker4 のバージョン、Windows のバージョン
|
||||
- 描画や GPU に関わる不具合では、GPU の名前とドライバーのバージョン
|
||||
- エラー画面に出た内容。省略せずに貼ってください
|
||||
|
||||
ときどきしか起きない不具合も、確実な再現の手順が無いまま報告して構いません。何回試して何回起きたかと、どの操作の後に起きたかを書いてください。
|
||||
|
||||
コードを読んで見つけた不具合を報告するときは、実際に再現を確かめたかどうかも書いてください。
|
||||
|
||||
Issue に添付したファイルは、誰でも見られます。プロジェクトファイルには、素材を置いたフォルダーのパスが記録されています。パスにユーザー名が含まれることがあるので、公開できない情報が無いかを確かめてから添付してください。
|
||||
|
||||
不具合の情報を自動で送信するプラグインでも、Issue での報告には意味があります。自動で送られるのは、例外の内容と実行環境の一部です。そこに至った操作、YukkuriMovieMaker4 のバージョン、GPU、例外を伴わない描画の乱れは届きません。
|
||||
|
||||
---
|
||||
|
||||
## プルリクエスト
|
||||
|
||||
1 つのプルリクエストには、1 つの目的の変更だけを含めてください。関係の無い整理、整形、依存関係の更新を含めないでください。依存関係を更新するのは、必要な機能を使うため、不具合やセキュリティの問題を直すため、互換性を保つためなど、具体的な理由があるときだけにしてください。
|
||||
|
||||
特に注意が要るのは、次の箇所です。
|
||||
|
||||
- 設定の項目と、その既定値と範囲。保存済みのプロジェクトの結果が変わるおそれがある
|
||||
- 出力の結果。変えるつもりの無い変更で、映像や音が変わっていないか
|
||||
- GPU のリソース、ファイル、ハンドルの寿命
|
||||
- 破棄の処理と、失敗したときの処理
|
||||
- YukkuriMovieMaker4 の内部に手を入れるプラグインでは、YukkuriMovieMaker4 のバージョンによる違い
|
||||
|
||||
動きを変えたときは、同じプルリクエストで README を直してください。`.github/Plugin_Readme.txt` があるリポジトリでは、それも直してください。`Plugin_Readme.txt` は配布パッケージに `Readme.txt` として入り、利用者の手元に残ります。
|
||||
|
||||
バージョンを上げる変更は、プルリクエストに含めないでください。バージョンの更新とリリースは、開発者が行います。
|
||||
|
||||
レビューを受けて直すときは、コミットを目的ごとのまとまりに保つため、ブランチの履歴を組み直して強制プッシュして構いません。
|
||||
|
||||
プルリクエストを送った時点で、その貢献をリポジトリと同じライセンスで提供することに同意したものとみなします。リポジトリのライセンスは、リポジトリの直下にあるライセンスのファイルに書いてあります。
|
||||
|
||||
---
|
||||
|
||||
## 検証
|
||||
|
||||
プルリクエストには、手元で実際に確かめた結果を書いてください。
|
||||
|
||||
- ビルドの結果と、テストのプロジェクトがあればテストの結果
|
||||
- YukkuriMovieMaker4 で実際に動かして確かめたこと。使った YukkuriMovieMaker4 のバージョンを添え、GPU に関わる変更では GPU の名前とドライバーのバージョンも添えてください
|
||||
- 実行できなかったテストと、その理由
|
||||
|
||||
実際に動かして観察したこと、コードを読んで判断したこと、推測したことを分けて書いてください。
|
||||
|
||||
出力を変えるつもりの無い変更では、変更前と変更後で出力が一致することを確かめてください。`--golden` と `--verify` を持つハーネスのプロジェクトがあるリポジトリでは、それで描画を比べられます。基準値は、手元の環境で変更前のコミットから作り直し、作り直した基準値はコミットに含めないでください。そのようなハーネスが無いリポジトリでは、変更前と変更後の出力を比べてください。サブモジュールの中にあるハーネスは、この確認には使いません。
|
||||
|
||||
性能の改善を主張するときは、1 回の測定で判断しないでください。
|
||||
|
||||
- 同じ機材、ドライバー、設定、電源の条件で、変更前と変更後のビルドを交互に繰り返し測ってください。
|
||||
- GPU と CPU の温度で値が変わるため、測定の間を空けてください。
|
||||
- ほかのプロセスが GPU を使っていない状態で測ってください。
|
||||
- 正しさの確認と性能の測定は、別々に実行してください。確認のための処理が、測定値を変えるためです。
|
||||
|
||||
---
|
||||
|
||||
## コードの規約
|
||||
|
||||
変更する箇所で既に使われている実装のパターンと書き方に従ってください。既存の実装どうしが食い違っているときは、どちらかを機械的にまねず、README とテストに照らして意図された動きを確かめ、それに合うほうへ揃えてください。
|
||||
|
||||
自分の変更で増えたビルドの警告は、放置せず原因を直してください。
|
||||
|
||||
新しく書くコードには、コメントを入れず、コメントアウトしたコードも残さないでください。既存のコードにあるコメントとドキュメントコメントは残してください。
|
||||
|
||||
---
|
||||
|
||||
## コミットの規約
|
||||
|
||||
- 1 つのコミットは、目的ごとのまとまりを保てる範囲で、できるだけ小さくしてください。どのコミットも、それ単独でビルドが通るようにしてください。
|
||||
- 実装の変更と、それを確かめるテストは、別のコミットに分けてください。
|
||||
- 件名は日本語で書き、50 文字以内に収め、「〜する」の形で終えてください。「〜を追加する」「〜を直す」はよい例です。「〜の追加」「〜を修正」のように名詞で終える形は使いません。
|
||||
- 件名を日本語で書けないときは、プルリクエストにその旨を書いてください。
|
||||
- 本文は書かないでください。例外は、リリースノートでの変更の分類を指定する行だけです。この行が要るときは、書き方をレビューで伝えます。
|
||||
|
||||
---
|
||||
|
||||
## 行動規範
|
||||
|
||||
貢献するすべての人に、[行動規範](CODE_OF_CONDUCT.md)に従うことを求めます。
|
||||
@@ -1,15 +1,5 @@
|
||||
<Project>
|
||||
<PropertyGroup>
|
||||
<YMM4DirPath>C:\Program Files\YukkuriMovieMaker_v4_Lite_Dev\</YMM4DirPath>
|
||||
|
||||
<WindowsKitRoot>C:\Program Files (x86)\Windows Kits\10\bin</WindowsKitRoot>
|
||||
|
||||
<FxcPath Condition="'$(FxcPath)' == '' AND Exists('$(WindowsKitRoot)\10.0.26100.0\x64\fxc.exe')">$(WindowsKitRoot)\10.0.26100.0\x64\fxc.exe</FxcPath>
|
||||
<FxcPath Condition="'$(FxcPath)' == '' AND Exists('$(WindowsKitRoot)\10.0.22621.0\x64\fxc.exe')">$(WindowsKitRoot)\10.0.22621.0\x64\fxc.exe</FxcPath>
|
||||
<FxcPath Condition="'$(FxcPath)' == '' AND Exists('$(WindowsKitRoot)\10.0.19041.0\x64\fxc.exe')">$(WindowsKitRoot)\10.0.19041.0\x64\fxc.exe</FxcPath>
|
||||
<FxcPath Condition="'$(FxcPath)' == '' AND Exists('$(WindowsKitRoot)\10.0.18362.0\x64\fxc.exe')">$(WindowsKitRoot)\10.0.18362.0\x64\fxc.exe</FxcPath>
|
||||
<FxcPath Condition="'$(FxcPath)' == '' AND Exists('$(WindowsKitRoot)\10.0.17763.0\x64\fxc.exe')">$(WindowsKitRoot)\10.0.17763.0\x64\fxc.exe</FxcPath>
|
||||
|
||||
<FxcPath Condition="'$(FxcPath)' == ''">fxc.exe</FxcPath>
|
||||
</PropertyGroup>
|
||||
</Project>
|
||||
@@ -6,9 +6,15 @@
|
||||
|
||||
---
|
||||
|
||||
YukkuriMovieMaker4(YMM4)上で動作する、**フラウンホーファー回折理論に基づいて計算した点像分布関数(PSF)で映像を畳み込む映像エフェクトプラグイン**です。
|
||||
波長・F値・画素ピッチ・開口形状・ゼルニケ波面収差係数をパラメータとして設定でき、円形開口・正多角形開口・中央遮蔽・6 種類の波面収差項に対応します。
|
||||
PSF の計算品質は FFT 格子サイズで切り替え可能で、各パラメータはアニメーションに対応しています。
|
||||
YukkuriMovieMaker4(YMM4)上で動作する、素材を回折も収差もない理想の像とみなし、レンズの開口と波面収差から求めた点像分布関数で畳み込んで、回折と収差によるにじみを描画する映像エフェクトプラグインです。
|
||||
点像分布関数は、瞳関数のフラウンホーファー回折を高速フーリエ変換で解いて求めます。
|
||||
履歴フレーム、参照画像、学習済みモデルを使わず、入力された一枚の映像だけを処理します。
|
||||
にじみの形は光学系と収差の設定から決定論的に決まり、同じ設定では常に同じ形になります。
|
||||
適用量、利得、ハイライトのしきい値、ハイライトの強さ、波長、F値、画素ピッチ、開口回転、中央遮蔽、デフォーカス、縦横非点収差、斜め非点収差、水平コマ収差、垂直コマ収差、球面収差の15項目はアニメーションに対応しています。
|
||||
畳み込みはGPUで計算します。畳み込みを計算し直したフレームでは、その結果を画面に出す前に検査します。GPUを使えないときと、検査で誤りを見つけたときは、CPUで計算します。
|
||||
「線形光」をオンにすると、画素の値を光の強さに比例する値へ直してから畳み込みます。「ハイライトの強さ」を上げると、光源のような明るい部分を持ち上げて、回折の筋のような小さな光を見えるようにできます。
|
||||
|
||||

|
||||
|
||||
---
|
||||
|
||||
@@ -18,10 +24,15 @@ PSF の計算品質は FFT 格子サイズで切り替え可能で、各パラ
|
||||
2. [動作要件](#動作要件)
|
||||
3. [インストール方法](#インストール方法)
|
||||
4. [主な機能](#主な機能)
|
||||
- [1. フラウンホーファー回折によるPSF計算](#1-フラウンホーファー回折によるpsf計算)
|
||||
- [2. ゼルニケ多項式による波面収差](#2-ゼルニケ多項式による波面収差)
|
||||
- [3. D2D1カスタムシェーダーによる畳み込み](#3-d2d1カスタムシェーダーによる畳み込み)
|
||||
- [4. アニメーション対応パラメータ](#4-アニメーション対応パラメータ)
|
||||
- [1. 点像分布関数の計算](#1-点像分布関数の計算)
|
||||
- [2. 光学系の項目とにじみの大きさ](#2-光学系の項目とにじみの大きさ)
|
||||
- [3. 開口の形と中央遮蔽](#3-開口の形と中央遮蔽)
|
||||
- [4. ゼルニケ多項式による波面収差](#4-ゼルニケ多項式による波面収差)
|
||||
- [5. タイルごとの高速フーリエ変換による畳み込み](#5-タイルごとの高速フーリエ変換による畳み込み)
|
||||
- [6. 利得と適用量](#6-利得と適用量)
|
||||
- [7. 線形光とハイライトとディザ](#7-線形光とハイライトとディザ)
|
||||
- [8. 品質の選択](#8-品質の選択)
|
||||
- [9. GPUの計算の検査とCPUの経路](#9-gpuの計算の検査とcpuの経路)
|
||||
5. [パラメータ一覧](#パラメータ一覧)
|
||||
- [出力グループ](#出力グループ)
|
||||
- [光学系グループ](#光学系グループ)
|
||||
@@ -29,20 +40,32 @@ PSF の計算品質は FFT 格子サイズで切り替え可能で、各パラ
|
||||
- [波面収差グループ](#波面収差グループ)
|
||||
6. [制限事項](#制限事項)
|
||||
7. [注意事項](#注意事項)
|
||||
8. [免責事項](#免責事項)
|
||||
9. [ライセンス](#ライセンス)
|
||||
8. [不具合の報告](#不具合の報告)
|
||||
9. [免責事項](#免責事項)
|
||||
10. [サードパーティライセンス](#サードパーティライセンス)
|
||||
11. [ライセンス](#ライセンス)
|
||||
|
||||
---
|
||||
|
||||
## 概要
|
||||
|
||||
本プラグインは YMM4 の「映像エフェクト」として動作し、エフェクトの種類一覧では「波動光学」として表示されます。
|
||||
本プラグインはYMM4の映像エフェクトとして動作し、エフェクトの種類一覧では「波動光学」として表示されます。カテゴリは加工です。
|
||||
|
||||
瞳関数を FFT で変換して強度分布(PSF)を計算し、得られた PSF カーネルを Direct2D カスタムピクセルシェーダーで映像に畳み込むことで、回折・収差による像のにじみを物理的に再現します。PSF はエネルギーが保存されるよう正規化され、「利得」パラメータで表示輝度を調整できます。
|
||||
レンズで撮った写真では、1点から出た光が1点に写らず、わずかに広がって写ります。この広がり方を表す関数を、点像分布関数と呼びます。光が広がる原因の1つは回折です。回折は、光が開口の縁を回り込んで広がる現象で、開口はレンズの中で光が通る穴です。もう1つの原因は波面収差です。光の波の山をつないだ面を波面と呼び、波面が理想の形からずれることを波面収差と呼びます。本プラグインは、素材の各画素の光を点像分布関数の形に広げて足し合わせます。この計算を畳み込みと呼びます。
|
||||
|
||||
PSF の計算には単色のフラウンホーファー回折を仮定します。白色光や多色光のシミュレーションには対応していません。
|
||||
畳み込んだ結果は、「利得」を掛けてから、「適用量」の割合で入力映像と混ぜ合わせて出力します。
|
||||
|
||||
このエフェクトは AviUtl 向けの EXO 出力(`.exo`)には対応していません。
|
||||
畳み込みは、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が求めます。
|
||||
|
||||
素材が変わらず、「利得」と「適用量」と「ディザ」以外の項目も変わらないフレームでは、畳み込みの計算を再利用します。
|
||||
|
||||
このエフェクトはAviUtl向けのEXO出力には対応していません。
|
||||
|
||||
---
|
||||
|
||||
@@ -50,61 +73,257 @@ PSF の計算には単色のフラウンホーファー回折を仮定します
|
||||
|
||||
| 項目 | 要件 |
|
||||
|---|---|
|
||||
| OS | Windows 10 バージョン 2004(ビルド 19041)以降 / Windows 11(64bit) |
|
||||
| OS | Windows 10 バージョン2004(ビルド19041)以降 / Windows 11(64bit) |
|
||||
| YukkuriMovieMaker4 | 最新版を推奨 |
|
||||
| ランタイム | .NET 10.0 |
|
||||
| GPU | Direct3D 12とDirect3D 11・12間の共有テクスチャおよび共有フェンスを利用できるGPUを推奨します。利用できない場合は、CPUで計算します |
|
||||
|
||||
---
|
||||
|
||||
## インストール方法
|
||||
|
||||
1. [Releases](https://github.com/routersys/YMM4-WaveOptics/releases/latest) ページから最新のプラグインファイル(`.ymme`)をダウンロードしてください。
|
||||
2. YMM4 が起動していないことを確認し、ダウンロードしたファイルを実行(ダブルクリック)してインストールします。
|
||||
3. YMM4 を起動し、タイムライン上のアイテムに映像エフェクトを追加します。
|
||||
4. 映像エフェクトの種類として **「波動光学」** を選択してください。
|
||||
1. [Releases](https://github.com/routersys/YMM4-WaveOptics/releases/latest)ページから最新のプラグインファイル(`.ymme`)をダウンロードしてください。
|
||||
2. YMM4が起動していないことを確認し、ダウンロードしたファイルを実行してインストールします。
|
||||
3. YMM4を起動し、タイムライン上のアイテムに映像エフェクトを追加します。
|
||||
4. 映像エフェクトの種類として「波動光学」を選択してください。
|
||||
|
||||
追加した直後は、映像はわずかにやわらぐだけです。にじみを大きくするには、「デフォーカス」の絶対値を上げるか、「F値」を上げます。詳しくは「光学系の項目とにじみの大きさ」の節にあります。
|
||||
|
||||
---
|
||||
|
||||
## 主な機能
|
||||
|
||||
### 1. フラウンホーファー回折によるPSF計算
|
||||
### 1. 点像分布関数の計算
|
||||
|
||||
瞳関数のグリッド上の各サンプルに対してゼルニケ収差で変調した位相を与え、FFT を適用して焦点面の強度分布(PSF)を計算します。PSF は双線形補間でカーネルにサンプリングされ、エネルギーが保存されるよう正規化されます。
|
||||
点像分布関数は、瞳関数から求めます。瞳関数は、開口の各点を通る光の振幅と位相を表す関数です。振幅は波の揺れの大きさ、位相は波の進み具合です。開口の内側では振幅を1、外側では0とし、位相には波面収差を与えます。高速フーリエ変換は、画像や波形を周波数ごとの成分に分けて表す変換を、速く計算する方法です。開口から十分に遠い面や、レンズの焦点面で見る回折を、フラウンホーファー回折と呼びます。瞳関数の高速フーリエ変換を求め、その絶対値の2乗を点像分布関数とする計算は、フラウンホーファー回折の式に当たります。
|
||||
|
||||
計算品質は「品質」パラメータの FFT 格子サイズで切り替えられます。
|
||||
畳み込みの重みは、点像分布関数から値を取り出して作ります。取り出すのは、中心から上下左右に「カーネル半径」の画素数までの正方形の範囲です。重みをこの正方形に並べたものを、カーネルと呼びます。カーネルの各画素の値は、画素の中心の位置で点像分布関数を補間した値で、画素の面積にわたる平均ではありません。カーネルの値の和は1になるように正規化します。カーネルの外に届く光は捨てるため、正規化によってカーネルの値がその分だけ大きくなります。
|
||||
|
||||
| 品質 | FFT 格子サイズ |
|
||||
点像分布関数とカーネルと、カーネルを高速フーリエ変換したスペクトルは、光学系グループと開口グループと波面収差グループのどれかの項目が変わったフレームでだけ、CPUで作り直します。
|
||||
|
||||
### 2. 光学系の項目とにじみの大きさ
|
||||
|
||||
円形の開口で収差がないときの点像分布関数は、エアリーパターンと呼ばれる、明るい円盤と周りの薄い輪の形になります。明るい円盤の半径は、波長とF値の積の1.22倍です。デフォルトの波長550nm、F値8、画素ピッチ4μmでは、明るい円盤の半径は約5.4μmで、約1.3画素です。そのため、デフォルトの設定では、映像はわずかにやわらぐだけです。にじみを大きくするには、F値か波長を上げるか、画素ピッチを下げます。
|
||||
|
||||
「波長」は、単色光として計算する光の波長です。長いほど回折による広がりが大きくなります。赤、緑、青の成分と不透明度は同じ点像分布関数で畳み込むので、波長を変えても映像の色は変わりません。
|
||||
|
||||
「F値」は、開口の直径に対する焦点距離の比です。大きいほど開口が小さくなり、回折による広がりが大きくなります。
|
||||
|
||||
「画素ピッチ」は、撮像面での1画素の間隔です。小さいほど、同じ広がりが多くの画素にまたがります。にじみの大きさは素材の画素を単位に決まるため、画素数の多い素材ほど、映像の全体に対するにじみは小さく見えます。
|
||||
|
||||
「カーネル半径」は、カーネルの正方形が中心から上下左右に何画素まで広がるかを決めます。設定できるのは1〜63画素で、デフォルトは15画素です。
|
||||
|
||||
点像分布関数がカーネルの正方形の外まで広がる設定では、外側の輪やにじみの端が切り取られます。デフォーカスは、波面収差グループの項目で、焦点の位置のずれを表します。単位のwavesは、波長を1とした量です。デフォルトの光学系でデフォーカスを1 wavesにすると、にじみは中心から約15画素まで広がります。デフォーカスの絶対値を大きくするときは、カーネル半径を上げてください。
|
||||
|
||||
「品質」は、瞳関数を置く格子の大きさを選ぶ項目で、「品質の選択」で説明します。点像分布関数を求める範囲は、「品質」と、波長とF値の積で決まります。カーネルのうち、この範囲の外になる画素は0になります。デフォルトの波長550nmとF値8で、標準の品質のとき、範囲は中心から上下左右に約141μmです。画素ピッチ4μmでは、約35画素です。カーネル半径がこの範囲を超えるときは、品質を上げてください。範囲の大きさは「品質の選択」の表にあります。品質を上げるほど、点像分布関数の計算は重くなります。カーネル半径と計算の重さの関係は、「タイルごとの高速フーリエ変換による畳み込み」にあります。
|
||||
|
||||
### 3. 開口の形と中央遮蔽
|
||||
|
||||
「開口形状」は、円形と正多角形から選びます。正多角形は、カメラの絞りの羽根が作る開口をまねた形で、頂点は円形の開口と同じ直径の円の上にあります。頂点までの距離を開口の半径とします。辺の数は「羽根枚数」で、向きは「開口回転」で決めます。正多角形の開口では、点像分布関数が辺と垂直な向きへ伸びます。デフォーカスでにじみが大きいときは、にじみが、開口と同じ辺の数の正多角形の形になります。にじみが切り取られないよう、カーネル半径と品質を上げてください。「羽根枚数」と「開口回転」は、開口形状が正多角形のときだけ働きます。
|
||||
|
||||
「中央遮蔽」は、反射望遠鏡の副鏡のように開口の中央をふさぐ円の大きさで、開口の半径に対する割合です。値を上げると中心の明るさが下がり、周りの輪へ光が移ります。中央遮蔽は、どちらの開口形状でも、中央を円でふさぎます。
|
||||
|
||||
### 4. ゼルニケ多項式による波面収差
|
||||
|
||||
波面収差グループの6項目は、ゼルニケ多項式の6つの項の係数です。ゼルニケ多項式は、円形の開口の上の波面収差を、互いに直交する基本の形の和で表す多項式です。係数の単位はwavesで、波長を1とした量です。本プラグインの各項は、開口と同じ半径の円の内側全体で、二乗平均平方根が1になるように正規化しています。二乗平均平方根は、値の2乗を円の内側全体で平均して平方根を取ったもので、波面収差の大きさの目安です。円形で中央遮蔽の無い開口では、係数1 wavesの項による波面収差は、二乗平均平方根で波長1つ分です。正多角形の開口と中央遮蔽のある開口では、光の通る部分だけで測ると、この値からずれます。
|
||||
|
||||
表のρは開口の半径を1とした中心からの距離、θは水平方向から測った角度です。
|
||||
|
||||
| 項目 | 多項式 | 意味 |
|
||||
|---|---|---|
|
||||
| デフォーカス | √3(2ρ²-1) | 焦点の位置のずれ |
|
||||
| 縦横非点収差 | √6ρ²cos2θ | 水平方向と垂直方向で焦点の位置が違うずれ |
|
||||
| 斜め非点収差 | √6ρ²sin2θ | 45度傾いた2つの方向で焦点の位置が違うずれ |
|
||||
| 水平コマ収差 | √8(3ρ³-2ρ)cosθ | 像が水平方向の片側へ尾を引くずれ |
|
||||
| 垂直コマ収差 | √8(3ρ³-2ρ)sinθ | 像が垂直方向の片側へ尾を引くずれ |
|
||||
| 球面収差 | √5(6ρ⁴-6ρ²+1) | 開口の中心と縁で焦点の位置が違うずれ |
|
||||
|
||||
### 5. タイルごとの高速フーリエ変換による畳み込み
|
||||
|
||||
畳み込む範囲を、一辺T画素の正方形のタイルに分けて畳み込みます。Tは、カーネル半径が23画素以下なら128、24画素以上なら512です。1枚のタイルは、一辺T画素の範囲の素材を読み、高速フーリエ変換で畳み込みます。この畳み込みでは、タイルの縁の近くに、反対側の縁の値が回り込んで混ざります。そのため、タイルの縁からカーネル半径の幅の値は捨て、中央の正方形だけを出力します。この正方形の一辺は、Tからカーネル半径の2倍を引いた画素数です。このようにタイルの縁を捨てて中央だけを使う方法を、オーバーラップセーブ法と呼びます。
|
||||
|
||||
高速フーリエ変換では、赤と緑、青と不透明度をそれぞれ1つの複素数にまとめ、1回の変換で2つの成分を計算します。
|
||||
|
||||
GPUの経路の畳み込みの計算量は、カーネルの形によらず、畳み込む範囲の大きさとカーネル半径で決まります。収差を入れても、畳み込みの計算は重くなりません。ただし、収差を変えるたびに、点像分布関数とカーネルのスペクトルを作り直す時間がかかります。CPUの経路は、全く透明な行と、全く透明なタイルの計算を省くので、素材の中身によっても時間が変わります。
|
||||
|
||||
Tが同じなら、カーネル半径を上げるほど、1枚のタイルが出力できる範囲は狭まります。そのため、必要なタイルの枚数は減らず、増えることがあります。枚数が増えるほど、計算は重くなります。カーネル半径が24画素以上になるとTが512に変わり、出力できる範囲が広がります。このため、畳み込む範囲が大きい素材では、GPUの経路で、カーネル半径が31画素のときの時間が、15画素のときとほぼ同じになります。畳み込む範囲が小さい素材では、24画素以上にするとかえって重くなることがありますが、この場合の実測値は表にありません。畳み込む範囲が大きい素材の実測値は、次の計算時間の表にあります。
|
||||
|
||||
計算時間は、試験用に作った1920×1080の画像で測りました。測った環境は、Intel Core i7-1360PのCPUと、Intel Iris Xe GraphicsのGPUです。CPUの論理プロセッサの数は16です。画像の透明でない部分は、1455×778画素の矩形に収まります。畳み込む範囲は、カーネル半径が15画素のとき1488×808画素、31画素のとき1520×840画素、63画素のとき1584×904画素です。画面全体が透明でない映像では、畳み込む範囲がこれより広くなるので、時間は表より長くなります。
|
||||
|
||||
測定は、続けて5回行いました。1回の測定では、表の行ごとに12フレームを計算し、フレームごとの時間を短い順に並べて、7番目の値を求めました。この値は、12フレームの中央に近い値です。表には、5回の測定で得た5つの値の、最小値から最大値までを示します。機器が温まるにつれて、後の回ほど遅くなる傾向があり、同じ行でも回によって最大で1.5倍ほど違います。そのため、行どうしの比べ方は、表を分けた組の中で、同じ回の値どうしにしてください。組の中の行は、同じ回の中で、順番を無作為に入れ替えて測っています。品質はどの行も標準で、ほかの項目はデフォルトです。ただし、カーネル半径31画素と63画素の行は、デフォーカス2 waves、水平コマ収差1 wavesにしています。「変えたもの」の列は、1フレームごとに値を入れ替えた項目です。入れ替えた値は、次のとおりです。
|
||||
|
||||
- 素材: 元の画像と、その左右を反転した画像
|
||||
- デフォーカス: 0と0.1 waves
|
||||
- 利得: 100%と150%
|
||||
|
||||
2つ目の表の「素材」の行は、1つ目の表の「素材」の行と同じ設定の、比べるための行です。素材の線形光の行は、線形光をオンにして、素材を「素材」の行と同じように入れ替えています。素材の線形光とハイライトの行は、さらにハイライトのしきい値を70%、強さを30倍にしています。合成した画像の画素の最も明るいチャンネルの値は、最大で0.9なので、しきい値を70%にしました。
|
||||
|
||||
表の時間は、素材が変わったかどうかの判定と、畳み込みの計算を合わせた値です。デフォーカスの行は、点像分布関数とカーネルのスペクトルをCPUで求める時間と、GPUへ送る時間も含みます。利得の行は、保存した値に利得を掛け直す時間です。保存した値は、「利得と適用量」の節で説明しています。「検査あり」の行は、畳み込みを計算し直すたびの検査を含みます。検査は、GPUが書いた値を読み戻して、CPUで求めた値と比べる処理です。ほかのGPUの行は、検査を含みません。実際のフレームでは、検査が毎回行われます。GPUの経路の時間に含まないものは、YMM4との間で素材と結果を受け渡す時間です。CPUの経路の時間に含まないものは、Direct2Dのビットマップとの間で画素を読み書きする時間です。表に含まない時間は、実際のフレームでは別にかかります。
|
||||
|
||||
| 変えたもの | カーネル半径 | GPUの経路 | CPUの経路 |
|
||||
|---|---:|---:|---:|
|
||||
| 素材 | 15画素 | 7.7〜8.6ミリ秒 | 9.3〜12.1ミリ秒 |
|
||||
| 素材 | 31画素 | 8.5〜9.5ミリ秒 | 測っていません |
|
||||
| 素材 | 63画素 | 14.9〜19.5ミリ秒 | 24.2〜39.8ミリ秒 |
|
||||
| 素材(検査あり) | 15画素 | 8.2〜10.4ミリ秒 | |
|
||||
| デフォーカス | 15画素 | 8.4〜12.1ミリ秒 | 測っていません |
|
||||
| 利得 | 15画素 | 2.2〜2.7ミリ秒 | 2.4〜2.9ミリ秒 |
|
||||
|
||||
| 変えたもの | カーネル半径 | GPUの経路 | CPUの経路 |
|
||||
|---|---:|---:|---:|
|
||||
| 素材 | 15画素 | 7.5〜8.3ミリ秒 | 15.8〜19.7ミリ秒 |
|
||||
| 素材(検査あり) | 15画素 | 8.6〜9.8ミリ秒 | |
|
||||
| 素材の線形光 | 15画素 | 7.7〜8.4ミリ秒 | 17.6〜21.9ミリ秒 |
|
||||
| 素材の線形光(検査あり) | 15画素 | 8.1〜9.2ミリ秒 | |
|
||||
| 素材の線形光とハイライト | 15画素 | 7.3〜8.2ミリ秒 | 22.7〜28.6ミリ秒 |
|
||||
|
||||
2つ目の表では、同じ回の「素材」の行より、線形光の行は、GPUの経路で1〜6%、CPUの経路で9〜24%長くなりました。ハイライトも加えると、CPUの経路は24〜63%長くなりました。2つ目の表は1つ目の表より後に測るので、機器が温まっていて、CPUの経路の「素材」の行が1つ目の表より遅くなっています。
|
||||
|
||||
素材と設定が変わらず、畳み込みを再利用するフレームでは、GPUの経路で1.2〜1.6ミリ秒でした。この時間は、素材が変わったかどうかの判定の時間です。
|
||||
|
||||
素材と利得の行は、前のバージョン(v3.0.0)の同じ行と、同じ時間帯に交互に測って比べました。GPUの経路の行とCPUの経路の行は、別々に測りました。GPUの経路は、前のバージョンの0.99〜1.04倍で、差は測定のばらつきの範囲です。CPUの経路は、素材15画素で約0.35倍、素材63画素で約0.36倍、利得で約0.23倍の時間でした。
|
||||
|
||||
高速フーリエ変換による畳み込みは、画素の値にカーネルの重みを掛けて直接足し合わせる畳み込みと、同じ結果になるはずの計算です。32ビットの浮動小数点数で計算するため、値の丸めによる誤差が生じます。誤差の上限は、タイルの一辺Tごとに導いてあります。導出の全文は、このリポジトリの畳み込みのライブラリ[SpectralConvolution](SpectralConvolution/README.md)の説明にあります。タイルの全画素が不透明な白という最悪の場合について、誤差の上限を、8ビットの値の1階調分を単位にして示します。小数第2位まで切り上げた値です。
|
||||
|
||||
| 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%で、丸める前の値の総和を保ち、上げるほど明るく、下げるほど暗くなります。出力は8ビットに丸めるので、丸めた後の総和は、小さな明るい点で素材より少なくなることがあります。これは「線形光とハイライトとディザ」で説明します。利得を掛けた結果は、色と不透明度の各成分が表せる最大の値で打ち切り、さらに色の成分が不透明度を超えないように抑えます。
|
||||
|
||||
利得かディザだけを変えたときは、最初の1回だけ畳み込みを計算し直し、利得を掛ける前の結果を保存します。2回目からは、保存した値に利得とディザを反映して描き直します。
|
||||
|
||||
「適用量」は、入力映像と、利得を掛けた結果を混ぜる割合です。0%では入力を変更せず、100%では利得を掛けた結果だけを出力します。
|
||||
|
||||
### 7. 線形光とハイライトとディザ
|
||||
|
||||
画素の値は、光の強さに比例していません。光の強さに比例する値を、線形の値と呼びます。sRGBでは、画素の値vから線形の値xを、次の式で求めます。線形の値から画素の値へ戻すときは、この式の逆を使います。
|
||||
|
||||
```
|
||||
v ≤ 0.04045 のとき x = v / 12.92
|
||||
v > 0.04045 のとき x = ((v + 0.055) / 1.055)^2.4
|
||||
```
|
||||
|
||||
光の回折とにじみは、光の強さを足し合わせる現象です。そのため、線形の値で畳み込むほうが、実際の光に合います。白と黒の画素が1画素ずつ交互に並ぶ市松模様を、大きくぼかす場合を考えます。光の強さの平均は白の半分で、これを画素の値に直すと約0.735、8ビットで約188です。画素の値をそのまま平均すると0.5、8ビットで約128になり、実際の光より暗くなります。
|
||||
|
||||
「線形光」をオンにすると、素材の画素の値を線形の値へ直してから畳み込み、結果を画素の値へ戻します。オフのときは、画素の値をそのまま畳み込みます。半透明の画素は、素材の色を不透明度で割って元の色に戻してから変換し、変換した値に不透明度を掛け直します。畳み込んだ結果には、まず利得を掛けます。次に、色と不透明度の各成分を0〜1に打ち切り、色の成分が不透明度を超えないように抑えます。最後に、画素の値へ戻し、不透明度を掛け直して、8ビットに丸めます。
|
||||
|
||||
「ハイライトのしきい値」と「ハイライトの強さ」は、線形光がオンのときだけ働きます。素材は8ビットなので、光源の画素の値は1.0で頭打ちです。実際の光源はもっと明るいはずですが、その明るさは素材に残っていません。回折の筋のように中心よりはるかに小さい光は、そのままでは、出力の8ビットの1階調に届きません。ハイライトの強さを上げると、明るい画素を持ち上げてから畳み込むので、そうした光が見えるようになります。ただし、これは光源の本当の明るさを復元する処理ではなく、指定した倍率で光を足す処理です。
|
||||
|
||||
持ち上げる倍率は、素材の画素ごとに決めます。画素の最も明るいチャンネルの値をmとします。半透明の画素では、素材の色を不透明度で割って元の色に戻した値を使います。しきい値をt、強さをsとすると、倍率は次の式で求めます。
|
||||
|
||||
```
|
||||
e = (m - t) / (1 - t) を0〜1に打ち切った値
|
||||
倍率 = 1 + (s - 1) e^2
|
||||
```
|
||||
|
||||
mがt以下の画素の倍率は1で、持ち上げません。mが1の画素の倍率は、強さsです。倍率は、色と不透明度のすべての成分に同じ値を掛けるので、色の比は変わりません。強さが1倍のときと、しきい値が100%のときは、持ち上げません。持ち上げた分の光が加わるので、出力の総和は素材の総和より大きくなります。明るさを元に戻すには、利得を下げてください。
|
||||
|
||||
ハイライトの効果を測りました。素材は、黒い背景の中央に、半径5画素の白い円を置いた映像です。F値16、画素ピッチ2μm、カーネル半径63画素、品質は標準、開口は6枚の羽根の正多角形で、ハイライトのしきい値は90%です。表の値は、出力の緑の成分を0〜255で表し、円の中心から25〜50画素離れた範囲で平均したものです。開口回転が0°のとき、点像分布関数は、中心から見て0°、60°、120°のように60°おきの向きへ、筋のように伸びます。筋の上は、この向きとの角度の差が3度以内の画素です。筋の間は、隣り合う筋の真ん中の向きとの角度の差が3度以内の画素です。
|
||||
|
||||
| 設定 | 筋の上 | 筋の間 |
|
||||
|---|---:|---:|
|
||||
| 線形光とハイライトをオフ | 0.0 | 0.0 |
|
||||
| 線形光とハイライトをオフ、利得400% | 1.0 | 0.0 |
|
||||
| 線形光をオン | 2.7 | 0.0 |
|
||||
| 線形光をオン、ハイライトの強さ30倍 | 41.5 | 3.7 |
|
||||
| 線形光をオン、ハイライトの強さ300倍 | 130.8 | 24.2 |
|
||||
|
||||
出力は8ビットに丸めます。点のような小さな明るい部分では、広がった光のうちの小さな値が0に丸められて、出力の総和が素材より少なくなります。「ディザ」をオンにすると、丸める前の値に、0以上1未満の値を足してから、小数を切り捨てます。足す値は、画素の位置だけで決まります。小さな値は、その大きさに応じた確率で1として残るので、総和が保たれます。具体的には、計算領域の中の画素の位置を、整数のハッシュに通して求めます。1つの画素の赤、緑、青、不透明度には、同じ値を足します。そのため、丸めたあとも、色が不透明度を超えることはありません。同じ設定では、同じ画素に毎回同じ値を足すので、フレームが変わってもちらつきません。カーネル半径を変えると、計算領域の余白が変わるので、模様は動きます。値が0の黒と、値が255の白は、変わりません。
|
||||
|
||||
ディザの効果を測りました。素材は、黒い背景に白い円を置いた映像です。円は、画素の中心が円の内側にある画素を白にしました。F値16、画素ピッチ2μm、カーネル半径63画素、品質は標準、開口は円形、利得100%で、線形光はオフです。表の値は、円の中心から上下左右に100画素の範囲で、出力の緑の成分の総和を素材の総和と比べた割合です。
|
||||
|
||||
| 円の半径 | ディザなし | ディザあり |
|
||||
|---:|---:|---:|
|
||||
| 2画素 | 91.1% | 100.2% |
|
||||
| 4画素 | 96.0% | 100.1% |
|
||||
| 8画素 | 97.9% | 100.0% |
|
||||
|
||||
「線形光」と「ハイライトのしきい値」と「ハイライトの強さ」を変えると、畳み込みを計算し直します。ただし、線形光がオフのときは、ハイライトの2項目を変えても、計算し直しません。線形光がオンでも、ハイライトの強さが1倍のときと、しきい値が100%のときは、持ち上げません。この場合、ハイライトの値の違いでは計算し直しません。利得とディザだけを変えたときは、「利得と適用量」で説明した保存した値から描き直します。
|
||||
|
||||
線形光をオンにすると、畳み込みは、変換した値に対して同じ手順で行います。そのため、誤差は、変換した値の2ノルムに比例します。ハイライトを持ち上げると2ノルムが大きくなり、誤差の上限も同じ割合で大きくなります。誤差の上限は、素材の値が0〜1のときの値です。上限は、「GPUの計算の検査とCPUの経路」と、[SpectralConvolution](SpectralConvolution/README.md)の説明にあります。実際の誤差は、上限よりはるかに小さいです。次の条件で測りました。素材は、黒い背景に半径2〜5画素の白い円を置いた映像です。カーネル半径は15画素と63画素、ハイライトの強さは1倍、10倍、100倍、1000倍です。無作為に選んだ1500か所の出力を、倍精度で直接足し合わせた値から求めた出力と比べました。GPUとCPUのどちらも、差は0階調でした。
|
||||
|
||||
線形光は、GPUの経路では、素材が変わるフレームの時間をほとんど増やしませんでした。CPUの経路では、素材を線形の値へ直す計算が増えて、時間が長くなりました。測った値は、「タイルごとの高速フーリエ変換による畳み込み」の計算時間の表にあります。
|
||||
|
||||
### 8. 品質の選択
|
||||
|
||||
「品質」は、瞳関数を置く格子の大きさを切り替えます。格子は瞳関数の値を縦横に並べた表で、1つ1つの値を標本と呼びます。開口の直径は格子の一辺の4分の1です。格子が大きいほど、開口の縁と波面収差の位相を細かく表せます。
|
||||
|
||||
点像分布関数の標本の間隔は、波長とF値の積の4分の1で、品質によらず同じです。格子が大きいほど点像分布関数を求める範囲が広がります。カーネルのうち、この範囲の外になる画素は0になります。
|
||||
|
||||
| 品質 | 瞳関数の格子 | 開口の直径 | 点像分布関数を求める範囲 |
|
||||
|---|---:|---:|---:|
|
||||
| 高速 | 128×128 | 32標本 | 中心から上下左右に約70μm |
|
||||
| 標準 | 256×256 | 64標本 | 中心から上下左右に約141μm |
|
||||
| 高精度 | 512×512 | 128標本 | 中心から上下左右に約282μm |
|
||||
|
||||
表の範囲は波長550nm、F値8のときの値で、波長とF値の積に比例します。
|
||||
|
||||
格子が粗いと、大きな波面収差で位相が急に変わる所を表しきれず、点像分布関数の形が崩れます。水平コマ収差を2 wavesにし、品質ごとに求めたカーネルを、格子が2048×2048のときのカーネルと比べました。ほかの項目はデフォルトです。カーネルの各画素の値の差の絶対値を全画素で足すと、高速で約0.87、標準で約0.38、高精度で約0.03でした。カーネルの値の和は1です。波面収差の絶対値を大きくするときは、品質を上げてください。
|
||||
|
||||
品質を上げると、点像分布関数の計算が重くなります。光学系グループと開口グループと波面収差グループの項目をアニメーションで変えるときは、フレームごとに点像分布関数を計算し直すので、品質を下げると処理が軽くなります。ただし、開口形状が円形のときは、「羽根枚数」と「開口回転」を変えても、計算し直しません。
|
||||
|
||||
### 9. 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は、計算の失敗で生じる、数として扱えない値です。
|
||||
|
||||
| 検査 | 内容 |
|
||||
|---|---|
|
||||
| 高速 | 128 × 128 |
|
||||
| 標準 | 256 × 256 |
|
||||
| 高精度 | 512 × 512 |
|
||||
| NaNと無限大 | 利得を掛ける前のタイルの値に、NaNか無限大が1つでもあれば不合格。捨てる縁の値も数える |
|
||||
| 総和 | 色と不透明度のそれぞれで、利得を掛ける前の出力の総和を素材の総和と比べる |
|
||||
| 抜き取り | 利得を掛ける前の出力の16か所の値を、倍精度で直接足し合わせた値と比べる |
|
||||
|
||||
瞳関数の直径は FFT 格子サイズの 1/4 です。開口形状は円形と正多角形から選択でき、正多角形では羽根枚数(3〜32)と回転角を設定できます。中央遮蔽(開口半径に対する割合 0〜95%)にも対応します。
|
||||
検査では、GPUの結果から求めた値を、測定値と呼びます。参照値は、測定値と比べる値で、素材の値から求めた値か、0のように初めから分かっている値です。許容値は、測定値と参照値の差として許す最大の値です。測定値と参照値の差が許容値以下なら合格とします。総和と抜き取りの許容値は、どちらも丸めの誤差の上限から導いた値で、実際に測った誤差に合わせて広げてはいません。抜き取る16か所のうち、畳み込む範囲の四隅と中央の5か所は固定で、残りの11か所は素材から決まります。そのため、同じ素材と同じ設定では毎回同じ位置になります。
|
||||
|
||||
### 2. ゼルニケ多項式による波面収差
|
||||
線形光かディザをオンにしたフレームでは、検査の材料の一部が変わります。GPUは、素材を線形の値などに直した値の総和と2乗和を、タイルごとに求めます。素材が8ビットの整数のままなら整数で足せますが、直した値は整数ではないので、浮動小数点数で足します。総和の参照値は、GPUが足した素材の総和です。そのため、総和の検査は、畳み込みの誤りを見つけますが、素材を直す計算の誤りは見つけません。この誤りは、抜き取りが見つけます。抜き取りの参照値は、次の手順で求めます。抜き取る位置の周りの素材の8ビットの値を、CPUで同じ式で直し、倍精度で足し合わせます。足し合わせの丸めの誤差は、許容値に入れています。許容値には、GPUとCPUのべき乗の計算の差の分として、タイルの2ノルムの2^-16倍を加えます。Intel Iris Xe Graphicsで測ったべき乗の相対誤差は、最大でも約5×10^-7で、2^-16の約30分の1でした。
|
||||
|
||||
以下の 6 種類のゼルニケ収差係数を独立して設定できます。各係数の単位は波数(waves)で、設定範囲は -10〜+10 waves です。
|
||||
GPUの異常が起きたときは、そのフレームをCPUの経路で計算し直します。異常を起こしたアダプターでは、YMM4を終了するまでCPUの経路で計算し、共有テクスチャやタイルの作業領域など、GPUの資源を解放します。
|
||||
|
||||
| 収差項 | 方向 |
|
||||
|---|---|
|
||||
| デフォーカス | — |
|
||||
| 縦横非点収差 | 0 度 |
|
||||
| 斜め非点収差 | 45 度 |
|
||||
| 水平コマ収差 | 水平方向 |
|
||||
| 垂直コマ収差 | 垂直方向 |
|
||||
| 球面収差 | — |
|
||||
GPUの異常の内容は、ほかのプラグインと共通のライブラリである[YMM4-Telemetry](https://github.com/routersys/YMM4-Telemetry)で、開発者へ自動で送信します。送信は、YMM4の起動中にアダプターごとに1回だけです。送信する内容と、送信する報告の数の上限は、「不具合の報告」にあります。
|
||||
|
||||
### 3. D2D1カスタムシェーダーによる畳み込み
|
||||
GPUの経路でメモリを確保できなかったときは、YMM4を終了するまでCPUの経路で計算しますが、送信しません。自己試験の最中に確保できなかったときだけは、自己試験の不合格として送信します。
|
||||
|
||||
PSF カーネルを R32G32B32A32_Float 形式のビットマップとして Direct2D デバイスコンテキストへ渡し、HLSL ピクセルシェーダーで畳み込みを行います。カーネル最大サイズは 31×31(半径 15 px)です。
|
||||
CPUの経路は、論理プロセッサの数までのスレッドで計算します。畳み込むときに、1つのスレッドは、タイル1枚分の作業領域を使います。同時に動かすスレッドは、タイルの作業領域の合計が64MBを超えない数に抑えます。Tが512のときは16スレッドまでです。
|
||||
|
||||
適用量が 0% の場合、または出力矩形の計算で半径が 0 になる場合は畳み込みを省略してパススルーとなります。畳み込み後に「利得」を乗算することでピーク輝度を調整できます。
|
||||
GPUの経路とCPUの経路の出力は、1ビット単位では一致しません。差は、開発で使う検証用のプログラムで確かめました。このプログラムを、ハーネスと呼びます。ハーネスは、リポジトリの`WaveOptics.Harness`にあります。ハーネスが合成した640×480の画像に、設定とフレームを変えてエフェクトを適用すると、2つの経路の出力の差は、測った範囲では最大2階調でした。この差には、2つの経路が8ビットに丸める分の、最大1階調を含みます。線形光とハイライトとディザを使う場面を加えても、最大2階調でした。
|
||||
|
||||
### 4. アニメーション対応パラメータ
|
||||
|
||||
適用量・利得・波長・F値・画素ピッチ・開口回転・中央遮蔽・6 種類の収差係数はすべてアニメーション対応であり、キーフレームを設定することで時間に応じて値を変化させることができます。
|
||||
|
||||
パラメータの変更を検出した場合のみ PSF を再計算します。
|
||||
[YMM4-ComputeGuard](https://github.com/routersys/YMM4-ComputeGuard)は、計算の経路を選び、検査の合否を判定します。[SpectralConvolution](SpectralConvolution/README.md)は、このリポジトリのフォルダーにあるライブラリで、畳み込みを計算します。YMM4-ComputeGuardは、サブモジュールとして取り込んでいます。
|
||||
|
||||
---
|
||||
|
||||
@@ -114,68 +333,146 @@ PSF カーネルを R32G32B32A32_Float 形式のビットマップとして Dire
|
||||
|
||||
| パラメータ名 | 型 | デフォルト | スライダー表示範囲 | アニメーション | 説明 |
|
||||
|---|---|---|---|---|---|
|
||||
| 適用量 | 数値 | 100% | 0 〜 100% | ✔ | 波動光学処理の適用量を調整します。0% では入力を変更しません。 |
|
||||
| 利得 | 数値 | 100% | 0 〜 400% | ✔ | エネルギー保存された畳み込み結果へ乗算する表示用利得です。 |
|
||||
| 適用量 | 数値 | 100% | 0〜100% | 対応 | 入力映像と、利得を掛けた結果を混ぜる割合です。0%では入力を変更しません。 |
|
||||
| 利得 | 数値 | 100% | 0〜400% | 対応 | 畳み込んだ結果に掛ける倍率です。100%で、丸める前の値の総和を保ちます。 |
|
||||
| 線形光 | 切り替え | オフ | オフ / オン | 非対応 | 画素の値を光の強さに比例する値へ直してから畳み込み、結果を画素の値へ戻します。 |
|
||||
| ハイライトのしきい値 | 数値 | 95% | 0〜100% | 対応 | 線形光がオンのとき、素材の画素の最も明るいチャンネルがこの割合を超えると、持ち上げ始めます。 |
|
||||
| ハイライトの強さ | 数値 | 1倍 | 1〜100倍 | 対応 | 線形光がオンのとき、最も明るい画素を持ち上げる倍率です。1倍では持ち上げません。直接入力では1000倍まで指定できます。 |
|
||||
| ディザ | 切り替え | オフ | オフ / オン | 非対応 | 8ビットに丸めるとき、画素の位置だけで決まる値を足します。 |
|
||||
|
||||
### 光学系グループ
|
||||
|
||||
| パラメータ名 | 型 | デフォルト | スライダー表示範囲 | アニメーション | 説明 |
|
||||
|---|---|---|---|---|---|
|
||||
| 波長 | 数値 | 550 nm | 380 〜 780 nm | ✔ | 単色光として計算する真空中の波長を指定します。設定範囲は 380 〜 780 nm です。 |
|
||||
| F値 | 数値 | 8 | 0.5 〜 32 | ✔ | 開口径に対する焦点距離の比を指定します。設定範囲は 0.5 〜 64 です。 |
|
||||
| 画素ピッチ | 数値 | 4 μm | 0.5 〜 20 μm | ✔ | 撮像面上の 1 画素の物理的な間隔を指定します。設定範囲は 0.25 〜 100 μm です。 |
|
||||
| カーネル半径 | 整数 | 15 px | 1 〜 15 px | ✗ | PSF を畳み込む画素半径を指定します。カーネルサイズは 2×半径+1 です。 |
|
||||
| 品質 | 列挙 | 標準 | — | ✗ | 瞳関数と PSF を計算する FFT 格子の大きさを指定します。 |
|
||||
| 波長 | 数値 | 550nm | 380〜780nm | 対応 | 単色光として計算する真空中の波長です。 |
|
||||
| F値 | 数値 | 8 | 0.5〜32 | 対応 | 開口の直径に対する焦点距離の比です。直接入力では64まで指定できます。 |
|
||||
| 画素ピッチ | 数値 | 4μm | 0.5〜20μm | 対応 | 撮像面での1画素の間隔です。直接入力では0.25〜100μmを指定できます。 |
|
||||
| カーネル半径 | 整数 | 15画素 | 1〜63画素 | 非対応 | カーネルが中心から上下左右に広がる画素数です。カーネルの外に届く光は捨てます。 |
|
||||
| 品質 | 列挙 | 標準 | 高速 / 標準 / 高精度 | 非対応 | 瞳関数を置く格子の大きさを選択します。 |
|
||||
|
||||
### 開口グループ
|
||||
|
||||
| パラメータ名 | 型 | デフォルト | スライダー表示範囲 | アニメーション | 説明 |
|
||||
|---|---|---|---|---|---|
|
||||
| 開口形状 | 列挙 | 円形 | — | ✗ | 瞳関数の外周形状を指定します。 |
|
||||
| 羽根枚数 | 整数 | 6 | 3 〜 16 | ✗ | 正多角形開口の辺数を指定します。設定範囲は 3 〜 32 です。 |
|
||||
| 開口回転 | 数値 | 0° | -180 〜 180° | ✔ | 正多角形開口の回転角を指定します。設定範囲は -360 〜 360° です。 |
|
||||
| 中央遮蔽 | 数値 | 0% | 0 〜 95% | ✔ | 開口半径に対する中央遮蔽半径の割合を指定します。 |
|
||||
| 開口形状 | 列挙 | 円形 | 円形 / 正多角形 | 非対応 | 開口の外周の形です。 |
|
||||
| 羽根枚数 | 整数 | 6 | 3〜16 | 非対応 | 正多角形の開口の辺の数です。直接入力では32まで指定できます。 |
|
||||
| 開口回転 | 数値 | 0° | -180〜180° | 対応 | 正多角形の開口の回転角です。直接入力では-360〜360°を指定できます。 |
|
||||
| 中央遮蔽 | 数値 | 0% | 0〜95% | 対応 | 開口の中央をふさぐ円の半径で、開口の半径に対する割合です。 |
|
||||
|
||||
### 波面収差グループ
|
||||
|
||||
| パラメータ名 | 型 | デフォルト | スライダー表示範囲 | アニメーション | 説明 |
|
||||
|---|---|---|---|---|---|
|
||||
| デフォーカス | 数値 | 0 waves | -3 〜 3 waves | ✔ | 正規化 Zernike デフォーカス係数を波数で指定します。設定範囲は -10 〜 10 waves です。 |
|
||||
| 縦横非点収差 | 数値 | 0 waves | -3 〜 3 waves | ✔ | 0 度方向の正規化 Zernike 非点収差係数を指定します。 |
|
||||
| 斜め非点収差 | 数値 | 0 waves | -3 〜 3 waves | ✔ | 45 度方向の正規化 Zernike 非点収差係数を指定します。 |
|
||||
| 水平コマ収差 | 数値 | 0 waves | -3 〜 3 waves | ✔ | 水平方向の正規化 Zernike コマ収差係数を指定します。 |
|
||||
| 垂直コマ収差 | 数値 | 0 waves | -3 〜 3 waves | ✔ | 垂直方向の正規化 Zernike コマ収差係数を指定します。 |
|
||||
| 球面収差 | 数値 | 0 waves | -3 〜 3 waves | ✔ | 正規化 Zernike 球面収差係数を指定します。設定範囲は -10 〜 10 waves です。 |
|
||||
| デフォーカス | 数値 | 0 waves | -3〜3 waves | 対応 | 焦点の位置のずれの係数です。 |
|
||||
| 縦横非点収差 | 数値 | 0 waves | -3〜3 waves | 対応 | 水平方向と垂直方向で焦点の位置が違うずれの係数です。 |
|
||||
| 斜め非点収差 | 数値 | 0 waves | -3〜3 waves | 対応 | 45度傾いた2つの方向で焦点の位置が違うずれの係数です。 |
|
||||
| 水平コマ収差 | 数値 | 0 waves | -3〜3 waves | 対応 | 像が水平方向の片側へ尾を引くずれの係数です。 |
|
||||
| 垂直コマ収差 | 数値 | 0 waves | -3〜3 waves | 対応 | 像が垂直方向の片側へ尾を引くずれの係数です。 |
|
||||
| 球面収差 | 数値 | 0 waves | -3〜3 waves | 対応 | 開口の中心と縁で焦点の位置が違うずれの係数です。 |
|
||||
|
||||
波面収差グループの6項目は、どれも直接入力では-10〜10 wavesの範囲で指定できます。
|
||||
|
||||
---
|
||||
|
||||
## 制限事項
|
||||
|
||||
- カーネル半径は 1 〜 15 px の範囲で指定できます(カーネルサイズ最大 31×31)。
|
||||
- 波長の設定範囲は 380 〜 780 nm(可視光域)です。
|
||||
- 計算は単色のフラウンホーファー回折に限定されます。白色光や多色光には対応していません。
|
||||
- AviUtl 向けの EXO 出力(`.exo`)には対応していません。
|
||||
- AviUtl向けのEXO出力には対応していません。
|
||||
- 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の資源は解放します。
|
||||
- 畳み込みには現在のフレームの色と不透明度だけを使用します。履歴フレーム、外部画像、学習済みモデルは使用しません。素材のすべての画素が透明なときは、エフェクトを適用せず入力映像を表示します。
|
||||
- 計算は単色のフラウンホーファー回折に限ります。白色光のように波長の混ざった光は扱いません。点像分布関数は画面のどこでも同じで、像の位置や素材の奥行きで変わるにじみは扱いません。
|
||||
- 畳み込みは、既定では、画素の値をそのまま重み付けして足し合わせます。「線形光」をオンにしたときだけ、画素の値を光の強さに比例する値へ直してから畳み込みます。
|
||||
- ハイライトは、指定した倍率で明るい画素の光を足す処理です。素材は8ビットで、頭打ちの画素の元の明るさは分からないので、光源の本当の明るさは復元しません。
|
||||
- カーネル半径は1〜63画素です。
|
||||
- 中央遮蔽で開口をほとんどふさぎ、瞳関数の格子に光の通る標本が1つも無くなる設定では、エフェクトを適用せず入力映像を表示します。品質を上げると起きにくくなります。
|
||||
- 計算領域は、透明な部分も含む素材全体の矩形の上下左右に余白を加えた大きさで、長辺は8192画素が上限です。余白は、カーネル半径を4画素単位に切り上げた画素数で、16画素を下回りません。素材の長辺の上限は、8192画素から余白の2倍を引いた値です。カーネル半径が16画素以下なら8160画素、63画素なら8064画素になります。素材の長辺がこの上限を超える場合は、エフェクトを適用せず入力映像を表示します。
|
||||
- エフェクト1つあたり、GPUの経路では、2つの共有テクスチャをGPUに確保します。素材を入れる共有テクスチャは、素材の1画素につき4バイトです。結果を入れる共有テクスチャは、畳み込む範囲の1画素につき4バイトです。結果を入れる共有テクスチャは、畳み込む範囲が入りきらなくなったときだけ、そのときの範囲の大きさで作り直します。
|
||||
- GPUの経路では、共有テクスチャのほかに、16MB以下のタイルの作業領域、カーネルのスペクトル、検査に使う値を書くバッファーを確保します。スペクトルは、Tが128なら128KB、512なら2MBです。検査に使う値を書くバッファーは、畳み込む範囲の大きさとカーネル半径に応じて増えます。利得だけを変えたフレームの後は、畳み込む範囲の1画素につき16バイトを追加で確保します。この領域は、「注意事項」のキャッシュの項目にある、保存した値のためのものです。
|
||||
- エフェクト1つあたり、CPUの経路では、素材の画素の配列、出力の画素の配列、作業スレッドの作業領域をシステムメモリに確保します。作業領域のうち、タイルの分は合計で64MB以下です。素材を読むためのDirect2Dのビットマップは2枚あり、どちらも素材の大きさです。出力を書くためのDirect2Dのビットマップは、畳み込む範囲を収められる大きさで、収まらなくなったときだけ作り直します。利得だけを変えたフレームの後は、畳み込む範囲の1画素につき16バイトを追加で確保します。
|
||||
|
||||
---
|
||||
|
||||
## 注意事項
|
||||
|
||||
- **品質と計算負荷**: 品質「高精度」では FFT 格子サイズが 512 になるため、パラメータ変更時の計算負荷が増加します。リアルタイムプレビュー中にパラメータを頻繁に変更する場合は「高速」への切り替えを検討してください。
|
||||
- **カーネル半径と出力サイズ**: 適用量が 0% より大きい場合、出力矩形は入力矩形よりもカーネル半径分だけ拡張されます。
|
||||
- **適用量が 0% の場合**: 畳み込みは実行されず、入力がそのまま出力されます。
|
||||
- **AviUtl 非対応**: 本プラグインは AviUtl 向けの EXO 出力(`.exo`)に対応していません。
|
||||
- **本プラグインを使用する前に、YMM4 プロジェクトファイルのバックアップを作成することを推奨します。**
|
||||
- 処理負荷: 畳み込む範囲が大きいほど、計算は重くなります。カーネル半径を上げたときの重さの変わり方は、「タイルごとの高速フーリエ変換による畳み込み」にあります。品質を上げた場合は、点像分布関数の計算量が増えます。収差を入れても、畳み込みの計算量は変わりません。ソフトウェア アダプターではないGPUを使える環境では、CPUの経路のほうが、一般に計算が遅くなります。
|
||||
- 品質と収差: 波面収差の絶対値を大きくするときは、品質を上げてください。格子が粗いと点像分布関数の形が崩れます。崩れ方の目安は「品質の選択」にあります。
|
||||
- キャッシュ: 素材の大きさと色と不透明度が変わらず、「利得」と「適用量」と「ディザ」以外の項目も変わらないフレームでは、畳み込みの計算を再利用します。利得かディザだけを変えたフレームでは、最初の1回だけ畳み込みを計算し直し、利得を掛ける前の値を保存します。2回目からは、保存した値に利得とディザを反映して描き直します。素材か、「利得」と「適用量」と「ディザ」以外の項目が変わると、保存した値を破棄します。ただし、線形光がオフのときは、ハイライトの2項目が変わっても破棄しません。適用量だけを変えたフレームでは、混ぜる割合だけを変えます。動画や口パクのように素材の内容が変わるフレームと、「利得」と「適用量」と「ディザ」以外の項目をアニメーションで変えたフレームでは、毎回計算し直すので処理が重くなります。素材が変わったかどうかを調べる計算は、再利用するフレームでも毎フレーム行います。開口形状が円形のときは、「羽根枚数」と「開口回転」を変えても、計算し直しません。
|
||||
- 適用量0%: 適用量が0%のときは入力を変更せず、畳み込みの計算も行いません。
|
||||
- 再現性: 計算は決定論的で、時間値や乱数を使用しません。同じ素材と同じ設定から常に同じ結果になるのは、同じ経路で、GPU、ドライバー、CPU、Windows、.NETの組が同じときです。GPUの経路でも結果にCPUが関わるのは、点像分布関数とカーネルのスペクトルをCPUで求めるためです。GPUの経路とCPUの経路では、結果がわずかに違います。GPUの異常でCPUの経路に切り替わったときも、同じ設定で結果がわずかに変わります。
|
||||
- 透明部分: 畳み込みは不透明度にも掛かるので、素材の縁の外にも半透明のにじみが広がります。出力の範囲は、素材の範囲と畳み込む範囲を合わせたものです。適用量が0%のときは、素材の範囲のままです。
|
||||
- 更新通知: エフェクトを最初に生成したときに、YMM4の実行中に一度だけ新しい正式版を確認します。更新情報を取得できない場合は通知せず、そのまま動作します。プレリリースは通知の対象に含めません。
|
||||
- 不具合の自動送信: 想定していない例外が起きたときと、GPUの異常でCPUの経路に切り替えたときは、その内容を開発者へ自動で送信します。内容は「不具合の報告」に書いています。
|
||||
- 本プラグインを使用する前に、YMM4のプロジェクトファイルのバックアップを作成することを推奨します。
|
||||
|
||||
---
|
||||
|
||||
## 不具合の報告
|
||||
|
||||
本プラグインは、想定していない例外が起きたときと、GPUの異常でCPUの経路に切り替えたときに、その内容を開発者へ自動で送信します。同意は求めず、常に送信します。
|
||||
|
||||
送信する情報は次のとおりです。
|
||||
|
||||
| 種類 | 内容 |
|
||||
|---|---|
|
||||
| 例外 | 型の完全名、メッセージ、スタックトレース |
|
||||
| 発生位置 | モジュール名、関数名、ファイル名、行番号 |
|
||||
| プラグイン | アセンブリ名、バージョン |
|
||||
| 実行環境 | OSの名前とバージョン、.NETのバージョン、CPUのアーキテクチャ、論理プロセッサ数 |
|
||||
| 識別子 | YMM4の起動ごとに決まるセッション識別子、報告ごとの識別子 |
|
||||
| GPUの異常のとき | 切り替えた理由、不合格になった検査の名前と測定値と参照値と許容値、アダプターの名前、ベンダーIDとデバイスIDとサブシステムIDとリビジョン、ドライバーのバージョン、ソフトウェア アダプターかどうか、計算領域の幅と高さ、必要なGPUメモリの見積もり |
|
||||
|
||||
メッセージとファイル名は、送信の前に置き換えを通します。置き換えるのは、Windowsのユーザー名、ユーザーフォルダー、AppDataのパス、マシン名、ドメイン名、メールアドレス、IPv4アドレスです。送信元のIPアドレスは受信側へ渡す手前で取り除いています。
|
||||
|
||||
映像の中身とプロジェクトの内容は送信しません。継続して個人を追跡する識別子も持ちません。セッション識別子はYMM4を起動し直すと別の値になります。
|
||||
|
||||
送信するのは、想定していない例外と、GPUの異常でCPUの経路に切り替えたことだけです。GPUの異常は、「GPUの計算の検査とCPUの経路」で説明しています。YMM4が本プラグインのエフェクトを作るとき、フレームごとに更新するとき、入力をつなぎ直すとき、破棄するときと、Direct2Dがシェーダーの定数を書き込むときに起きた例外を報告し、その後はYMM4へそのまま渡します。ただし、GPUの経路の計算中に起きた例外は、YMM4へは渡さず、そのフレームをCPUの経路で計算し直します。この例外は、GPUの異常として報告しますが、メモリを確保できなかったものは報告しません。自己試験の最中に確保できなかったときだけは、自己試験の不合格として報告します。GPUの異常の報告は、YMM4の起動中にアダプターごとに1回だけです。
|
||||
|
||||
更新の確認では、更新情報の取得と比較で起きた例外は報告しません。通知の文を組み立てて表示するときに起きた例外は報告し、YMM4へは渡しません。画面の操作やバックグラウンドの処理で未処理になった例外も報告しますが、本プラグインのコードが関わる例外に限ります。本プラグインの外で起きた例外は送信しません。
|
||||
|
||||
次の失敗は送信しません。
|
||||
|
||||
| 種類 | 例 |
|
||||
|---|---|
|
||||
| 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) をサブモジュールとして取り込んでいます。GPUの異常の報告の内容は[YMM4-ComputeGuard](https://github.com/routersys/YMM4-ComputeGuard)が組み立てます。
|
||||
|
||||
---
|
||||
|
||||
## 免責事項
|
||||
|
||||
本プラグインは MIT ライセンスのもとで公開されています。
|
||||
本プラグインはMITライセンスのもとで公開されています。
|
||||
|
||||
**本ソフトウェアは「現状のまま」提供されており、明示・黙示を問わず、商品性、特定目的への適合性、および権利非侵害に関する保証を含む、いかなる種類の保証も行いません。**
|
||||
本ソフトウェアは「現状のまま」提供されており、明示または黙示を問わず、商品性、特定目的への適合性、および権利非侵害に関する保証を含む、いかなる種類の保証も行いません。
|
||||
|
||||
作者は、本プラグインの使用または使用不能に起因するいかなる損害についても、一切の責任を負いません。
|
||||
ご利用は自己責任でお願いします。
|
||||
作者は、本プラグインの使用または使用不能に起因するいかなる損害についても、一切の責任を負いません。ご利用は自己責任でお願いします。
|
||||
|
||||
---
|
||||
|
||||
## サードパーティライセンス
|
||||
|
||||
本プラグインは以下のサードパーティソフトウェアを同梱・使用しています。ライセンスの全文は、リポジトリの [`.github/LICENSE/ComputeWeave.txt`](.github/LICENSE/ComputeWeave.txt) と、配布パッケージの `LICENSE` フォルダーに収録しています。
|
||||
|
||||
| ソフトウェア | 用途 | ライセンス | 著作権表示 |
|
||||
|---|---|---|---|
|
||||
| [ComputeWeave](https://github.com/routersys/ComputeWeave) | Direct3D 12計算シェーダーとDirect3D 11・12共有処理 | MIT License | Copyright (c) 2024 Sergio Pedri |
|
||||
|
||||
---
|
||||
|
||||
|
||||
+46
@@ -0,0 +1,46 @@
|
||||
# セキュリティポリシー
|
||||
|
||||
## サポートするバージョン
|
||||
|
||||
セキュリティの修正は、最新のリリースだけを対象にします。
|
||||
|
||||
| バージョン | サポート |
|
||||
|---|---|
|
||||
| 最新のリリース | 対象 |
|
||||
| それより前のリリース | 対象外 |
|
||||
|
||||
修正は、最新のリリースの次のバージョンとして公開します。報告する前に、最新のリリースでも問題が起きるかを確かめてください。
|
||||
|
||||
## 対象とする問題
|
||||
|
||||
本プラグインのコードと配布パッケージに原因がある問題を対象にします。たとえば次のようなものです。
|
||||
|
||||
- 細工したプロジェクトファイルや素材を開くと、意図しない処理が実行される
|
||||
- 更新の確認などで行う通信の内容を、第三者が書き換えられる
|
||||
- 不具合の情報を自動で送信するプラグインで、個人を特定できる情報が伏せられないまま送信される
|
||||
|
||||
配布パッケージに同梱したライブラリの脆弱性は、本プラグインを通じて悪用できる場合に対象にします。
|
||||
|
||||
YukkuriMovieMaker4 本体や、ほかのプラグインに原因がある問題は対象外です。それぞれの開発者へ報告してください。
|
||||
|
||||
## 報告の方法
|
||||
|
||||
脆弱性は、公開の Issue に書かないでください。修正を公開する前に悪用されるおそれがあります。
|
||||
|
||||
1. リポジトリの URL の末尾に `/security` を付けたページを開き、「Report a vulnerability」から非公開で報告してください。報告の内容を見られるのは、開発者と報告した人、開発者が招いた人だけです。
|
||||
2. この方法が使えないときは、github.routersys@gmail.com へメールで報告してください。
|
||||
|
||||
報告には、次の内容を書いてください。分からない項目は書かなくて構いません。
|
||||
|
||||
| 項目 | 内容 |
|
||||
|---|---|
|
||||
| バージョン | 問題を確かめたプラグインのバージョンと、YukkuriMovieMaker4 のバージョン |
|
||||
| 再現の手順 | 問題を起こす操作と、使ったプロジェクトファイルや素材 |
|
||||
| 影響 | 問題によって何ができてしまうか |
|
||||
| 回避策 | 分かっていれば、修正までの間に被害を避ける方法 |
|
||||
|
||||
## 報告の後
|
||||
|
||||
開発者は、報告を受け取ったら内容を確かめ、修正の見込みを返信します。
|
||||
|
||||
報告した人は、修正を含むバージョンが出るまで、報告の内容を明かさないでください。問題の詳細は、修正版の公開後に開発者が公表します。
|
||||
@@ -0,0 +1,689 @@
|
||||
# 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-自己試験)
|
||||
- [7. 線形光とハイライトとディザ](#7-線形光とハイライトとディザ)
|
||||
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` | 倍精度の高速フーリエ変換。カーネルのスペクトルに使う |
|
||||
| `LightOptions` | 線形光、ディザ、ハイライトの設定 |
|
||||
| `LightTransform` | 線形光とハイライトで素材を直す変換と、出力を 8 ビットにする変換。CPU の経路と、検査の参照値に使う |
|
||||
|
||||
表の 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-の経路)で説明します。
|
||||
|
||||
線形光とハイライトとディザを使うときは、`LightOptions` を渡します。CPU の経路は `Convolve` の最後の引数、GPU の経路は `Prepare` の最後の引数です。保存した値から描き直す `CpuTileConvolver.RenderStored` と `GpuTileConvolver.RecordStored` にも渡します。渡さないと既定になり、これまでと同じ動きです。詳しくは、[線形光とハイライトとディザ](#7-線形光とハイライトとディザ)にあります。
|
||||
|
||||
```csharp
|
||||
var light = new LightOptions(true, false, 0.9f, 30f);
|
||||
cpu.Convolve(source, sourceX, sourceY, sourceWidth, sourceHeight, spectrum, plan, output, gain, store, light);
|
||||
```
|
||||
|
||||
GPU の経路では、素材と出力のテクスチャを使う処理を、ComputeWeave のコンテキストに記録します。ComputeWeave では、`GraphicsDevice` から作った `ComputeContext` に、計算シェーダーの実行を記録します。
|
||||
|
||||
```csharp
|
||||
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 の列の計算で連続して読めるよう、列ごとに並べます。
|
||||
|
||||
実際の計算では、値のある 2r + 1 行だけを行ごとに変換し、列ごとの変換は、横方向の周波数が 0 から T / 2 までの T / 2 + 1 列だけにします。カーネルは実数なので、スペクトルの周波数 (u, v) の値は、周波数 (-u, -v) の値の複素共役になります。周波数は T を周期とします。残りの列は、この対称を使い、float に丸めた値の複素共役を写して求めます。
|
||||
|
||||
2^-126 は float の正の正規化数の最小値で、0 でなく絶対値がこれより小さい値を非正規化数と呼びます。回転因子とスペクトルの非正規化数は、符号を残して 0 にします。GPU は非正規化数を 0 にすることがあるので、CPU の側で先に 0 にそろえておきます。
|
||||
|
||||
### 2. 2 つのチャンネルをまとめる複素数
|
||||
|
||||
素材の 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 を足し、端数を切り捨てます。
|
||||
|
||||
変換の 1 段の計算、スペクトルを掛ける計算、出力を 8 ビットにする計算は、`System.Runtime.Intrinsics` のベクトル演算で行います。1 回のバタフライは、2 つの複素数(赤と緑、青と不透明度)に同じ回転因子を掛け、足し引きする計算です。4 つの float を 1 つのベクトルに置いて計算します。AVX2 を使えるときは、同じ段で隣り合う 2 つの回転因子の分を、1 つの 256 ビットのベクトルにまとめます。足し算、引き算、掛け算の順番と回数は、スカラーで書いた式と同じで、融合積和は使いません。そのため、結果はスカラーの式と 1 ビットも違いません。`CpuTileConvolver.ButterfliesScalar` が、基準にするスカラーの式です。試験は、`Butterflies` の結果をこの式の結果と、ビットごとに比べます。素材を行に置くときの、8 ビットの値を 255 で割る計算は、256 個の値の表で行います。表の値は、同じ割り算の結果なので、割り算と同じ値です。
|
||||
|
||||
ゲインだけを変えるときは、畳み込みをやり直さずに出力できます。そのために、`Convolve` の最後の引数 `convolvedValues` に配列を渡します。渡した配列に、ゲインを掛ける前の値が float で保存されます。保存する値は、画素ごとに R、G、B、A の順の float 4 つで、出力の BGRA とは順が違います。配列の長さは、畳み込む範囲の幅 × 高さ × 4 以上です。
|
||||
|
||||
`RenderStored` は、保存した値に別のゲインを掛けて出力し直します。結果は、そのゲインで畳み込みと同時に出力した場合と 1 ビットも違いません。`RenderStored` は、16384 画素を 1 単位として、スレッドに割り当てます。
|
||||
|
||||
素材の外にある行と、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` に当たり、精度を緩める最適化を許しません。
|
||||
|
||||
`ForwardRowShader` と `InverseRowShader` は、グループの 512 個の値が必ず 1 枚のタイルの中にあることを使って、タイルの位置を求める割り算を、スレッドごとに 1 回だけ行います。`InverseRowShader` は、抜き取る位置があるタイルでだけ、抜き取る位置を探します。抜き取る位置を渡すバッファー(`Samples`)には、先頭の `MaximumSamples` 個に抜き取る位置を並べ、続けてタイルごとに 1 ビットの印を並べます。印は 64 タイルを 1 要素に入れ、X の下位ビットから順に 32 タイル、Y の下位ビットから順に 32 タイルです。抜き取る位置があるタイルの印が 1 です。`Prepare` が、抜き取る位置を渡すたびに、位置と印を書き込みます。
|
||||
|
||||
出力のテクスチャには、ゲインを掛けた値を書きます。`Prepare` の最後の引数に `true` を渡すと、ゲインを掛ける前の値を、畳み込む範囲の 1 画素につき 16 バイトのバッファーに保存します。`RecordStored` は、保存した値に別のゲインを掛けて出力し直します。結果は、そのゲインで畳み込みと同時に出力した場合と 1 ビットも違いません。保存に使うバッファーは、`ReleaseStore` か `Dispose` を呼ぶまで持ち続けます。
|
||||
|
||||
### 5. 検査の材料と検査
|
||||
|
||||
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 か所です。全画素の比較に小さなカーネルを使うのは、倍精度の直接の計算を軽く保つためです。高速フーリエ変換の各段の計算はカーネルの大きさによらないので、小さなカーネルでも変換のすべての段を通ります。
|
||||
|
||||
### 7. 線形光とハイライトとディザ
|
||||
|
||||
素材の読み方と出力の書き方は、`LightOptions` で変えます。`LightOptions` は、次の 4 つの値を持ちます。
|
||||
|
||||
| 値 | 意味 |
|
||||
|---|---|
|
||||
| `Linear` | 真なら、素材の値を線形の値へ直して畳み込み、結果を sRGB の値へ戻す |
|
||||
| `Dither` | 真なら、出力を 8 ビットに丸めるとき、画素の位置で決まる 0 以上 1 未満の値を足してから切り捨てる |
|
||||
| `Threshold` | ハイライトのしきい値 t。0 以上 1 以下 |
|
||||
| `Boost` | ハイライトの強さ s。0 以上 1000 以下 |
|
||||
|
||||
線形の値は、光の強さに比例する値です。`Linear` と `Dither` がどちらも偽の `default` が既定です。既定では、この節の処理は何も行わず、[CPU の経路](#3-cpu-の経路)と [GPU の経路](#4-gpu-の経路)の説明のとおりに動きます。ハイライトを持ち上げるのは、`Linear` が真で、s が 1 より大きく、t が 1 未満のときです。`LightOptions.Validate` は、t か s が範囲の外か有限でないと、`ArgumentOutOfRangeException` を投げます。
|
||||
|
||||
素材の変換は、`LightTransform.FromBytes` です。素材の画素 (r, g, b, a) は、premultiplied alpha の 8 ビットの値です。`Linear` が偽なら、各値を 255 で割った float を返します。真のときは、次の順に求めます。計算はすべて float です。
|
||||
|
||||
1. a が 0 なら、4 つとも 0 を返す。
|
||||
2. 不透明度 α を a / 255 とする。色の各成分は、不透明度で割って元の色に戻した sRGB の値 c にする。a が 255 のときは 255 で割り、そうでないときは a で割って、1 を超えたら 1 とする。
|
||||
3. c を線形の値へ直す(`LightTransform.Decode`)。c が 0.04045 以下なら c / 12.92、1 以上なら 1、それ以外は ((c + 0.055) / 1.055)^2.4 とする。
|
||||
4. ハイライトがあるときは、3 つの c の最大値を m とし、e を (m - t) / (1 - t) を 0〜1 に打ち切った値として、倍率 w を 1 + (s - 1) × e × e とする。ないときは、w を 1 とする。
|
||||
5. 戻す値は、線形の値の 3 つに α × w を掛けた値と、α × w とする。
|
||||
|
||||
出力の変換は、`LightTransform.ToBytes` です。畳み込んだ値の赤、緑、青、不透明度と、ゲイン g、画素の位置 (x, y) を受け取り、BGRA の 8 ビットを返します。`Linear` が偽のときは、各成分に g を掛けて 0〜1 に打ち切り(NaN は 0)、丸めます。真のときは、次の順に求めます。
|
||||
|
||||
1. 不透明度に g を掛けて 0〜1 に打ち切り(NaN は 0)、A とする。A が 0 なら、色は 0 とする。
|
||||
2. 色の各成分に g を掛けて 0〜1 に打ち切り、A を超える分を A に抑える。A で割った値を、画素の値へ戻す(`LightTransform.Encode`)。線形の値が 0.0031308 以下なら 12.92 を掛け、1 以上なら 1、それ以外は 1.055 × 値^(1/2.4) - 0.055 とする。
|
||||
3. 戻した値に A を掛ける。
|
||||
4. 8 ビットに丸める。
|
||||
|
||||
丸めは、`Dither` が偽なら、255 を掛けて 0.5 を足し、小数を切り捨てます。真なら、255 を掛けた値に、画素の位置で決まる θ を足し、255 を上限として小数を切り捨てます。上限が要るのは、値が 1 で θ が 1 にごく近いと、float の足し算の結果が 256 になり、byte へ変えると 0 に戻るためです。θ は、1 つの画素の 4 つの値(赤、緑、青、不透明度)に同じ値を使います。θ が同じなら、丸めは値の大小を保ちます。そのため、丸める前に色が不透明度を超えていない画素は、丸めたあとも超えません。チャンネルごとに別の θ を使うと、色が不透明度を 1 階調だけ超える画素が出て、premultiplied alpha として正しくなくなります。θ は、`LightTransform.DitherThreshold` が、x と y から、次の整数のハッシュで求めます。符号なしの 32 ビットの計算で、桁あふれは捨てます。
|
||||
|
||||
```
|
||||
h = (x × 0x9E3779B1) xor (y × 0x85EBCA77)
|
||||
h = h xor (h >> 16)
|
||||
h = h × 0x7FEB352D
|
||||
h = h xor (h >> 15)
|
||||
h = h × 0x846CA68B
|
||||
h = h xor (h >> 16)
|
||||
θ = (h >> 8) / 2^24
|
||||
```
|
||||
|
||||
画素の位置は、畳み込む範囲と同じ座標系です。
|
||||
|
||||
`Decode` と `Encode` のべき乗は、CPU では、表の補間で求めます。表は、値と傾きの組を並べたもので、変換する float のビットを添字にします。そのため、暗い値でも明るい値でも、刻みの細かさは相対的に同じです。`Encode` は、2 のべき乗ごとに 256 刻みで、2^-9 から 1 までの表を持ちます。`Decode` は、2 のべき乗ごとに 1024 刻みで、2^-4 から 1 までの表を持ちます。どちらも相対誤差は 5 × 10^-7 以下です。この大きさは、GPU の `Hlsl.Pow` の誤差と同じです。素材の 8 ビットの値 256 通りを `Decode` した値は、表にして持ちます。
|
||||
|
||||
CPU の経路は、素材を行に置くときに `FromBytes` を通します。出力の書き込みと `RenderStored` は、画素 1 つ分をベクトルに置く `LightTransform.ToPacked` を通します。`ToPacked` は、`ToBytes` と同じ演算を同じ順に行うので、返すバイトは `ToBytes` と同じです。試験が、乱数と端の値で比べます。`RenderStored` には、画素の位置を求めるために、畳み込む範囲の幅と左上の座標も渡します。ディザが偽なら、幅と座標は使いません。ゲインを掛ける前に保存する値は、線形光のときは線形の値で、ハイライトの持ち上げを含みます。
|
||||
|
||||
GPU の経路は、`LightOptions` が既定でないときだけ、別のシェーダーを使います。既定のときは、これまでのシェーダーのままです。別のシェーダーは、`ForwardRowLightShader`、`InverseRowLightShader`、`StoredRenderLightShader` の 3 つで、`ColumnShader` と `GatherShader` は共通です。変換と丸めは、`LightTransform` と同じ順に float で書き、べき乗は `Hlsl.Pow` で求めます。`GpuTileJob` の `Light` には、`Prepare` の最後の引数が入ります。`RecordStored` には、`LightOptions` と、畳み込む範囲の左上の座標を渡します。
|
||||
|
||||
既定でないときは、検査の材料が次の 2 点で変わります。1 つ目は、素材の和と 2 乗の和です。変換した値は整数ではないので、整数のアトミック加算では足せません。`ForwardRowLightShader` は、スレッドごとに 2 個の値を足し、グループの中を深さ 8 の二分木で足して、float のビットを `uint` に入れて書きます。置き場所と並びは変わりません。2 つ目は、`GatherShader` が集める近傍で、変換する前の 8 ビットの値のままです。変換は CPU が行います。
|
||||
|
||||
`GpuTileCheck.Evaluate` は、`job.Light` が既定でないとき、次のように変わります。
|
||||
|
||||
- 素材の和の参照値は、グループごとの float を倍精度で足した値です。255 では割りません。足し合わせの丸めの誤差は、演算 16 回分として、許容値に Gamma(16, 2^-23) / (1 - Gamma(16, 2^-23)) を参照値に掛けた値を足します。
|
||||
- タイルの 2 ノルムは、2 乗の和の float を倍精度で足した値に 1 / (1 - Gamma(16, 2^-23)) を掛け、平方根を取った値です。
|
||||
- 抜き取りの参照値は、`DirectCorrelation.Evaluate` に `LightOptions` を渡して求めます。近傍の 8 ビットの値を `FromBytes` で直し、倍精度で足し合わせます。
|
||||
- `Linear` が真のときは、GPU と CPU のべき乗の差の分として、タイルの 2 ノルムの 2^-16 倍を、抜き取りの許容値に足します。差は、GPU のべき乗の誤差(Intel Iris Xe Graphics で測った最大で約 5 × 10^-7)と、CPU の表の補間の誤差(5 × 10^-7 以下)の和で、約 10^-6 以下です。2^-16 は、その約 15 倍です。
|
||||
|
||||
素材の和の参照値は GPU が足した値なので、総和の検査は、素材を直す計算の誤りを見つけません。この誤りは、抜き取りが見つけます。
|
||||
|
||||
---
|
||||
|
||||
## 誤差の上限
|
||||
|
||||
ここでは、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`、`Math.Sin`、`Math.Cos` | 返す値の誤差は、各成分で 2^-51 以下 |
|
||||
| カーネル | 値はすべて 0 以上で、和で割って 1 にそろえてある。実際の和は 1 からわずかにずれる |
|
||||
|
||||
カーネルが 0 以上で和が 1 であるという前提から、スペクトルの絶対値はどこでも 1 以下になり、カーネルの 2 ノルムも 1 以下になります。実際の和は 1 から γ_ker までずれます。γ_ker は、次の記号の表で定義します。このずれの扱いは、[式に入れていない誤差と上限の余裕](#10-式に入れていない誤差と上限の余裕)で説明します。
|
||||
|
||||
この上限の数値は、`Linear` と `Dither` が偽で、素材の値が 0〜1 のときの値です。`Linear` が真のときは、畳み込みの入力が、素材の値ではなく変換した値になります。1 タイルの上限の式は、入力の 2 ノルムに比例する形なので、変換した値の 2 ノルムで成り立ちます。ただし、ハイライトで入力が 1 を超えるため、2 ノルムが大きくなり、上限は同じ割合で大きくなります。GPU が素材を変換する計算の誤差は、上限に入れず、[検査の材料と検査](#5-検査の材料と検査)の許容値に別に加えます。
|
||||
|
||||
### 記号
|
||||
|
||||
| 記号 | 意味 |
|
||||
|---|---|
|
||||
| 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 乗の和は、整数のアトミック加算で数えます。整数の加算は順序に左右されないので、毎回同じ値になります。
|
||||
- `LightOptions` が既定でないとき、素材の和と 2 乗の和は、グループの中では決まった木の形で足した float です。同じデバイスで同じ入力を 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`、`Math.Sin`、`Math.Cos` の精度は .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 ビットも違わないこと。線形光、ハイライト、ディザを使うときも同じです。
|
||||
- 線形光の変換が、値の両端を保ち、標準の曲線に従い、すべての 8 ビットの値を往復して元に戻ること。ハイライトが、しきい値以下を持ち上げず、倍率が強さまで上がり、色の比を保つこと
|
||||
- 線形光とハイライトとディザの結果が、変換した素材からの `DirectCorrelation` の値との差で上限に収まり、GPU の検査にすべて合格すること。ハイライトを間違えると、抜き取りで不合格になること
|
||||
- ディザの値が 0 以上 1 未満で、毎回同じ値になり、平均が 0.5 になること。値が 1 のときに 0 へ戻らないこと。不透明な白の素材が、ディザで黒く欠けないこと。値が、この説明のハッシュの式と一致すること
|
||||
- 色が不透明度を超えない画素の出力が、ディザのときも、色が不透明度を超えないこと。CPU と GPU の両方で、半透明の素材を使って確かめます。
|
||||
- ハイライトの倍率が、画素の最も明るいチャンネルで決まること。それが赤、緑、青のどれでも同じです。しきい値よりはるかに暗い画素は、持ち上げません。
|
||||
- `Encode` の相対誤差が、標準の曲線に対して 10^-6 以下であること。しきい値の前後と、1 の直前を含みます。
|
||||
- `ToPacked` の結果が、乱数と端の値(NaN、無限大、負の値、1 を超える値)で、`ToBytes` の結果と一致すること
|
||||
- `Butterflies` の結果が、スカラーの式 `ButterfliesScalar` の結果と、T が 2 から 512 のすべてでビットごとに一致すること。保存した値の 8 ビットへの変換が、`ToUnorm` と一致すること
|
||||
- GPU の出力が、保存した値を `ToBytes` で変換した値と、ほぼすべての値で一致すること。違う値は 1 階調以内で、全体の 0.05% 以下です。
|
||||
- `Samples` バッファーの印が、抜き取る位置があるタイルだけに付くこと。次の呼び出しでは、前の位置の印が消えること
|
||||
- CPU の経路で持ち続ける作業領域が、計算したスレッドの分だけで、T が変わると捨てられること
|
||||
- GPU に渡すスペクトルを 1.0005 倍すると、総和の検査で不合格になること
|
||||
- スペクトルの虚部の符号を反転すると、抜き取りの検査で不合格になり、総和の検査は合格のままであること。この反転は、カーネルの上下と左右を反転することに当たります。
|
||||
- スペクトルに 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,208 @@
|
||||
namespace SpectralConvolution.Tests;
|
||||
|
||||
internal sealed class ConvolutionScene
|
||||
{
|
||||
(double RedGreen, double BlueAlpha)[]? tileNorms;
|
||||
float[]? transformed;
|
||||
|
||||
ConvolutionScene(byte[] source, int sourceX, int sourceY, int sourceWidth, int sourceHeight, KernelSpectrum spectrum, TilePlan plan, LightOptions light)
|
||||
{
|
||||
Light = light;
|
||||
Source = source;
|
||||
SourceX = sourceX;
|
||||
SourceY = sourceY;
|
||||
SourceWidth = sourceWidth;
|
||||
SourceHeight = sourceHeight;
|
||||
Spectrum = spectrum;
|
||||
Plan = plan;
|
||||
}
|
||||
|
||||
public LightOptions Light { get; }
|
||||
|
||||
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, LightOptions light = default)
|
||||
{
|
||||
var spectrum = new KernelSpectrum();
|
||||
spectrum.Update(AsymmetricKernel(radius), radius, size);
|
||||
var plan = TilePlan.Create(size, radius, 0, 0, sourceWidth + margin * 2, sourceHeight + margin * 2);
|
||||
return new ConvolutionScene(source, margin, margin, sourceWidth, sourceHeight, spectrum, plan, light);
|
||||
}
|
||||
|
||||
// The region starts at (regionX, regionY) of the canvas, and the source lies inside it at (sourceX, sourceY).
|
||||
// The helpers that compare with the exact correlation assume a region at the origin, so a scene made
|
||||
// here is only for comparing two implementations with each other.
|
||||
public static ConvolutionScene CreateShifted(
|
||||
byte[] source, int sourceX, int sourceY, int sourceWidth, int sourceHeight,
|
||||
int regionX, int regionY, int regionWidth, int regionHeight, int radius, int size, LightOptions light = default)
|
||||
{
|
||||
var spectrum = new KernelSpectrum();
|
||||
spectrum.Update(AsymmetricKernel(radius), radius, size);
|
||||
var plan = TilePlan.Create(size, radius, regionX, regionY, regionWidth, regionHeight);
|
||||
return new ConvolutionScene(source, sourceX, sourceY, sourceWidth, sourceHeight, spectrum, plan, light);
|
||||
}
|
||||
|
||||
public void Reference(int x, int y, Span<double> result)
|
||||
{
|
||||
if (!Light.Linear)
|
||||
{
|
||||
DirectCorrelation.Evaluate(Source, SourceWidth, SourceHeight, Spectrum.Kernel, Spectrum.Radius, x - SourceX, y - SourceY, result);
|
||||
return;
|
||||
}
|
||||
|
||||
var values = Transformed();
|
||||
var radius = Spectrum.Radius;
|
||||
var kernelSize = radius * 2 + 1;
|
||||
var kernel = Spectrum.Kernel;
|
||||
result[..4].Clear();
|
||||
for (var offsetY = -radius; offsetY <= radius; offsetY++)
|
||||
{
|
||||
var sourceY = y - SourceY + offsetY;
|
||||
if (sourceY < 0 || sourceY >= SourceHeight)
|
||||
continue;
|
||||
for (var offsetX = -radius; offsetX <= radius; offsetX++)
|
||||
{
|
||||
var sourceX = x - SourceX + offsetX;
|
||||
if (sourceX < 0 || sourceX >= SourceWidth)
|
||||
continue;
|
||||
var weight = kernel[(offsetY + radius) * kernelSize + offsetX + radius];
|
||||
var offset = (sourceY * SourceWidth + sourceX) * 4;
|
||||
for (var channel = 0; channel < 4; channel++)
|
||||
result[channel] += values[offset + channel] * weight;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
public (double RedGreen, double BlueAlpha) Norms(int x, int y)
|
||||
{
|
||||
tileNorms ??= [.. Enumerable.Range(0, Plan.TileCount).Select(TileNorms)];
|
||||
return tileNorms[Plan.TileAt(x, y)];
|
||||
}
|
||||
|
||||
public float[] Transformed()
|
||||
{
|
||||
if (transformed is null)
|
||||
{
|
||||
var values = new float[SourceWidth * SourceHeight * 4];
|
||||
for (var index = 0; index < SourceWidth * SourceHeight; index++)
|
||||
{
|
||||
var (red, green, blue, alpha) = LightTransform.FromBytes(Source[index * 4 + 2], Source[index * 4 + 1], Source[index * 4], Source[index * 4 + 3], Light);
|
||||
values[index * 4] = red;
|
||||
values[index * 4 + 1] = green;
|
||||
values[index * 4 + 2] = blue;
|
||||
values[index * 4 + 3] = alpha;
|
||||
}
|
||||
|
||||
transformed = values;
|
||||
}
|
||||
|
||||
return transformed;
|
||||
}
|
||||
|
||||
(double RedGreen, double BlueAlpha) TileNorms(int tile)
|
||||
{
|
||||
if (!Light.Linear)
|
||||
return TileInput.Norms(Source, SourceX, SourceY, SourceWidth, SourceHeight, Plan, tile);
|
||||
|
||||
var values = Transformed();
|
||||
var left = Plan.OriginX(tile) - Plan.Radius;
|
||||
var top = Plan.OriginY(tile) - Plan.Radius;
|
||||
var redGreen = 0d;
|
||||
var blueAlpha = 0d;
|
||||
var lastY = Math.Min(top + Plan.Size, SourceY + SourceHeight);
|
||||
var lastX = Math.Min(left + Plan.Size, SourceX + SourceWidth);
|
||||
for (var y = Math.Max(top, SourceY); y < lastY; y++)
|
||||
{
|
||||
for (var x = Math.Max(left, SourceX); x < lastX; x++)
|
||||
{
|
||||
var offset = ((y - SourceY) * SourceWidth + x - SourceX) * 4;
|
||||
redGreen += (double)values[offset] * values[offset] + (double)values[offset + 1] * values[offset + 1];
|
||||
blueAlpha += (double)values[offset + 2] * values[offset + 2] + (double)values[offset + 3] * values[offset + 3];
|
||||
}
|
||||
}
|
||||
|
||||
return (Math.Sqrt(redGreen), Math.Sqrt(blueAlpha));
|
||||
}
|
||||
|
||||
public double WorstRatio(ReadOnlySpan<float> convolved, double operationError)
|
||||
{
|
||||
var reference = new double[4];
|
||||
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,611 @@
|
||||
using ComputeWeave;
|
||||
|
||||
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);
|
||||
}
|
||||
|
||||
static (byte[] Output, float[] Convolved) RunLight(ConvolutionScene scene, int threads, float gain)
|
||||
{
|
||||
var output = new byte[scene.RegionLength];
|
||||
var convolved = new float[scene.RegionLength];
|
||||
using var convolver = new CpuTileConvolver(threads);
|
||||
convolver.Convolve(scene.Source, scene.SourceX, scene.SourceY, scene.SourceWidth, scene.SourceHeight, scene.Spectrum, scene.Plan, output, gain, convolved, scene.Light);
|
||||
return (output, convolved);
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[InlineData(64, 5, 150, 97, 11, 0f, 0f)]
|
||||
[InlineData(128, 23, 140, 90, 24, 0.9f, 20f)]
|
||||
[InlineData(64, 0, 70, 70, 3, 0.5f, 1000f)]
|
||||
public void ALinearLightConvolutionStaysWithinTheBoundOfTheExactCorrelation(int size, int radius, int width, int height, int margin, float threshold, float boost)
|
||||
{
|
||||
var light = new LightOptions(true, false, threshold, boost);
|
||||
var scene = ConvolutionScene.Create(ConvolutionScene.RandomSource(width, height, size + radius, 0.4), width, height, margin, radius, size, light);
|
||||
|
||||
var (_, convolved) = RunLight(scene, 3, 1f);
|
||||
|
||||
Assert.True(scene.Plan.TileCount > 1);
|
||||
Assert.InRange(scene.WorstRatio(convolved, ConvolutionBound.CpuOperationError), 0d, 1d);
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[InlineData(false, 1f)]
|
||||
[InlineData(true, 1f)]
|
||||
[InlineData(true, 2.5f)]
|
||||
public void TheLinearOutputIsTheTransformOfTheConvolution(bool dither, float gain)
|
||||
{
|
||||
var light = new LightOptions(true, dither, 0.8f, 8f);
|
||||
var scene = ConvolutionScene.Create(ConvolutionScene.RandomSource(90, 60, 9, 0.7), 90, 60, 8, 4, 64, light);
|
||||
|
||||
var (output, convolved) = RunLight(scene, 2, gain);
|
||||
|
||||
for (var y = 0; y < scene.Plan.RegionHeight; y++)
|
||||
{
|
||||
for (var x = 0; x < scene.Plan.RegionWidth; x++)
|
||||
{
|
||||
var index = (y * scene.Plan.RegionWidth + x) * 4;
|
||||
var expected = LightTransform.ToBytes(convolved[index], convolved[index + 1], convolved[index + 2], convolved[index + 3], gain, light, scene.Plan.RegionX + x, scene.Plan.RegionY + y);
|
||||
Assert.Equal((expected.Blue, expected.Green, expected.Red, expected.Alpha), (output[index], output[index + 1], output[index + 2], output[index + 3]));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[InlineData(false, false, 1f)]
|
||||
[InlineData(true, false, 2.75f)]
|
||||
[InlineData(true, true, 0.3f)]
|
||||
[InlineData(false, true, 1.5f)]
|
||||
public void RenderingTheStoreMatchesTheLightConvolutionBitForBit(bool linear, bool dither, float gain)
|
||||
{
|
||||
var light = new LightOptions(linear, dither, 0.85f, linear ? 12f : 0f);
|
||||
var scene = ConvolutionScene.Create(ConvolutionScene.RandomSource(130, 90, 13, 0.6), 130, 90, 8, 4, 64, light);
|
||||
var (expected, _) = RunLight(scene, 3, gain);
|
||||
var (_, stored) = RunLight(scene, 3, 1f);
|
||||
var output = new byte[scene.RegionLength];
|
||||
using var convolver = new CpuTileConvolver(3);
|
||||
|
||||
convolver.RenderStored(stored, scene.Plan.RegionWidth * scene.Plan.RegionHeight, gain, output, light, scene.Plan.RegionWidth, scene.Plan.RegionX, scene.Plan.RegionY);
|
||||
|
||||
Assert.Equal(expected, output);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void TheLinearResultDoesNotDependOnTheNumberOfThreads()
|
||||
{
|
||||
var light = new LightOptions(true, true, 0.9f, 30f);
|
||||
var scene = ConvolutionScene.Create(ConvolutionScene.RandomSource(300, 170, 5, 0.6), 300, 170, 16, 9, 64, light);
|
||||
|
||||
var single = RunLight(scene, 1, 1.75f);
|
||||
var many = RunLight(scene, 16, 1.75f);
|
||||
|
||||
Assert.Equal(single.Output, many.Output);
|
||||
Assert.Equal(single.Convolved, many.Convolved);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void AnOpaqueWhiteSceneStaysWhiteInLinearLight()
|
||||
{
|
||||
var light = new LightOptions(true, true, 0f, 0f);
|
||||
var scene = ConvolutionScene.Create(ConvolutionScene.Uniform(120, 120, 255), 120, 120, 8, 7, 64, light);
|
||||
|
||||
var (output, convolved) = RunLight(scene, 2, 1f);
|
||||
|
||||
Assert.InRange(scene.WorstRatio(convolved, ConvolutionBound.CpuOperationError), 0d, 1d);
|
||||
var center = ((scene.Plan.RegionHeight / 2) * scene.Plan.RegionWidth + scene.Plan.RegionWidth / 2) * 4;
|
||||
Assert.Equal([255, 255, 255, 255], output.AsSpan(center, 4).ToArray());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void ABrightPointSpreadsFartherWithHighlights()
|
||||
{
|
||||
var pixels = new byte[61 * 61 * 4];
|
||||
var center = (30 * 61 + 30) * 4;
|
||||
pixels[center] = 255;
|
||||
pixels[center + 1] = 255;
|
||||
pixels[center + 2] = 255;
|
||||
pixels[center + 3] = 255;
|
||||
var plain = new LightOptions(true, false, 0f, 0f);
|
||||
var boosted = new LightOptions(true, false, 0.9f, 400f);
|
||||
var spectrum = new KernelSpectrum();
|
||||
spectrum.Update(ConvolutionScene.AsymmetricKernel(20), 20, 128);
|
||||
var plan = TilePlan.Create(128, 20, 0, 0, 101, 101);
|
||||
using var convolver = new CpuTileConvolver(2);
|
||||
var plainOutput = new byte[101 * 101 * 4];
|
||||
var boostedOutput = new byte[101 * 101 * 4];
|
||||
|
||||
convolver.Convolve(pixels, 20, 20, 61, 61, spectrum, plan, plainOutput, 1f, null, plain);
|
||||
convolver.Convolve(pixels, 20, 20, 61, 61, spectrum, plan, boostedOutput, 1f, null, boosted);
|
||||
|
||||
var plainLit = plainOutput.Where((value, index) => index % 4 == 1 && value > 0).Count();
|
||||
var boostedLit = boostedOutput.Where((value, index) => index % 4 == 1 && value > 0).Count();
|
||||
Assert.True(boostedLit > plainLit * 2, $"{plainLit} {boostedLit}");
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void ARegionWithDitheringNeedsAWidthToRenderTheStore()
|
||||
{
|
||||
using var convolver = new CpuTileConvolver(1);
|
||||
|
||||
Assert.Throws<ArgumentOutOfRangeException>(() => convolver.RenderStored(new float[8], 2, 1f, new byte[8], new LightOptions(false, true, 0f, 0f)));
|
||||
convolver.RenderStored(new float[8], 2, 1f, new byte[8], new LightOptions(false, true, 0f, 0f), 2);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void InvalidLightOptionsAreRejected()
|
||||
{
|
||||
var scene = ConvolutionScene.Create(ConvolutionScene.RandomSource(40, 40, 1, 0.5), 40, 40, 4, 2, 64);
|
||||
using var convolver = new CpuTileConvolver(1);
|
||||
var output = new byte[scene.RegionLength];
|
||||
|
||||
Assert.Throws<ArgumentOutOfRangeException>(() => convolver.Convolve(
|
||||
scene.Source, scene.SourceX, scene.SourceY, scene.SourceWidth, scene.SourceHeight, scene.Spectrum, scene.Plan, output, 1f, null, new LightOptions(true, false, 2f, 5f)));
|
||||
Assert.Throws<ArgumentOutOfRangeException>(() => convolver.RenderStored(new float[8], 2, 1f, output, new LightOptions(true, false, 0.5f, 5000f)));
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[InlineData(false)]
|
||||
[InlineData(true)]
|
||||
public void ADitheredOpaqueWhiteSceneNeverDropsToBlackAnywhere(bool linear)
|
||||
{
|
||||
var light = new LightOptions(linear, true, 0f, 0f);
|
||||
var scene = ConvolutionScene.Create(ConvolutionScene.Uniform(1100, 700, 255), 1100, 700, 8, 3, 512, light);
|
||||
|
||||
var (output, _) = RunLight(scene, 4, 1f);
|
||||
|
||||
var wrong = 0;
|
||||
for (var y = 8 + 4; y < 8 + 700 - 4; y++)
|
||||
{
|
||||
for (var x = 8 + 4; x < 8 + 1100 - 4; x++)
|
||||
{
|
||||
var index = (y * scene.Plan.RegionWidth + x) * 4;
|
||||
if (output[index] < 250 || output[index + 1] < 250 || output[index + 2] < 250 || output[index + 3] < 250)
|
||||
wrong++;
|
||||
}
|
||||
}
|
||||
|
||||
Assert.Equal(0, wrong);
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[InlineData(1)]
|
||||
[InlineData(2)]
|
||||
[InlineData(3)]
|
||||
[InlineData(4)]
|
||||
[InlineData(5)]
|
||||
[InlineData(6)]
|
||||
[InlineData(7)]
|
||||
[InlineData(8)]
|
||||
[InlineData(9)]
|
||||
public void TheVectorButterfliesMatchTheScalarOnesBitForBit(int log2)
|
||||
{
|
||||
var size = 1 << log2;
|
||||
var twiddles = new Float2[Math.Max(size / 2, 1)];
|
||||
for (var index = 0; index < twiddles.Length; index++)
|
||||
{
|
||||
var angle = -2d * Math.PI * index / size;
|
||||
twiddles[index] = new Float2((float)Math.Cos(angle), (float)Math.Sin(angle));
|
||||
}
|
||||
|
||||
var random = new Random(log2 * 101);
|
||||
foreach (var direction in new[] { 1f, -1f })
|
||||
{
|
||||
var expected = new float[size * 4];
|
||||
for (var index = 0; index < expected.Length; index++)
|
||||
{
|
||||
expected[index] = random.Next(7) switch
|
||||
{
|
||||
0 => 0f,
|
||||
1 => -0f,
|
||||
2 => (float)(random.NextDouble() * 1e-30),
|
||||
3 => (float)(random.NextDouble() * 1e6 - 5e5),
|
||||
_ => (float)(random.NextDouble() * 2 - 1),
|
||||
};
|
||||
}
|
||||
|
||||
var actual = (float[])expected.Clone();
|
||||
|
||||
var narrow = (float[])expected.Clone();
|
||||
|
||||
CpuTileConvolver.ButterfliesScalar(expected, log2, twiddles, direction);
|
||||
CpuTileConvolver.Butterflies(actual, log2, twiddles, direction);
|
||||
CpuTileConvolver.Butterflies(narrow, log2, twiddles, direction, allowWide: false);
|
||||
|
||||
Assert.Equal(expected.Select(BitConverter.SingleToInt32Bits), actual.Select(BitConverter.SingleToInt32Bits));
|
||||
Assert.Equal(expected.Select(BitConverter.SingleToInt32Bits), narrow.Select(BitConverter.SingleToInt32Bits));
|
||||
}
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void TheButterfliesRefuseALineThatIsTooShort()
|
||||
{
|
||||
var twiddles = new Float2[4];
|
||||
|
||||
Assert.Throws<ArgumentException>(() => CpuTileConvolver.Butterflies(new float[8 * 4 - 1], 3, twiddles, 1f));
|
||||
Assert.Throws<ArgumentException>(() => CpuTileConvolver.Butterflies(new float[8 * 4], 3, twiddles.AsSpan(0, 3), 1f));
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[InlineData(1f)]
|
||||
[InlineData(0f)]
|
||||
[InlineData(1.75f)]
|
||||
[InlineData(400f)]
|
||||
public void TheStoredValuesBecomeBytesLikeTheScalarConversion(float gain)
|
||||
{
|
||||
float[] edges =
|
||||
[
|
||||
0f, -0f, 1e-12f, 0.5f / 255f, 0.5f / 255f + 1e-7f, 1f / 255f, 127.5f / 255f, 254.5f / 255f, 254.5f / 255f + 1e-7f,
|
||||
0.999f, 1f, 1.0000001f, 2f, 1e9f, -1e-12f, -0.25f, -1e9f, float.NaN, float.PositiveInfinity, float.NegativeInfinity,
|
||||
float.Epsilon, float.MaxValue, float.MinValue,
|
||||
];
|
||||
var pixels = edges.Length;
|
||||
var stored = new float[pixels * 4];
|
||||
for (var pixel = 0; pixel < pixels; pixel++)
|
||||
{
|
||||
for (var channel = 0; channel < 4; channel++)
|
||||
stored[pixel * 4 + channel] = edges[(pixel + channel * 5) % edges.Length];
|
||||
}
|
||||
|
||||
var output = new byte[stored.Length];
|
||||
using var convolver = new CpuTileConvolver(2);
|
||||
|
||||
convolver.RenderStored(stored, pixels, gain, output);
|
||||
|
||||
for (var pixel = 0; pixel < pixels; pixel++)
|
||||
{
|
||||
Assert.Equal(CpuTileConvolver.ToUnorm(stored[pixel * 4 + 2] * gain), output[pixel * 4]);
|
||||
Assert.Equal(CpuTileConvolver.ToUnorm(stored[pixel * 4 + 1] * gain), output[pixel * 4 + 1]);
|
||||
Assert.Equal(CpuTileConvolver.ToUnorm(stored[pixel * 4] * gain), output[pixel * 4 + 2]);
|
||||
Assert.Equal(CpuTileConvolver.ToUnorm(stored[pixel * 4 + 3] * gain), output[pixel * 4 + 3]);
|
||||
}
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[InlineData(false, 1f)]
|
||||
[InlineData(true, 1f)]
|
||||
[InlineData(true, 1.8f)]
|
||||
[InlineData(false, 2.5f)]
|
||||
public void ADitheredTranslucentSceneKeepsEveryColorBelowItsOpacity(bool linear, float gain)
|
||||
{
|
||||
var light = new LightOptions(linear, true, 0f, 0f);
|
||||
var scene = ConvolutionScene.Create(ConvolutionScene.Uniform(240, 160, 128), 240, 160, 8, 3, 64, light);
|
||||
|
||||
var (output, _) = RunLight(scene, 3, gain);
|
||||
|
||||
var exceeding = 0;
|
||||
var translucent = 0;
|
||||
for (var index = 0; index < output.Length; index += 4)
|
||||
{
|
||||
if (output[index + 3] is > 0 and < 255)
|
||||
translucent++;
|
||||
if (output[index] > output[index + 3] || output[index + 1] > output[index + 3] || output[index + 2] > output[index + 3])
|
||||
exceeding++;
|
||||
}
|
||||
|
||||
Assert.True(translucent > 1000, $"{translucent}");
|
||||
Assert.Equal(0, exceeding);
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[InlineData(true, true, 1.3f)]
|
||||
[InlineData(false, true, 2f)]
|
||||
[InlineData(true, false, 0.8f)]
|
||||
public void RenderingTheStoreMatchesTheLightConvolutionForARegionAwayFromTheOrigin(bool linear, bool dither, float gain)
|
||||
{
|
||||
var light = new LightOptions(linear, dither, 0.85f, linear ? 12f : 0f);
|
||||
var source = ConvolutionScene.RandomSource(120, 80, 78, 0.5);
|
||||
var scene = ConvolutionScene.CreateShifted(source, 43, 29, 120, 80, 37, 23, 132, 92, 4, 64, light);
|
||||
var plan = scene.Plan;
|
||||
var (expected, _) = RunLight(scene, 3, gain);
|
||||
var (_, stored) = RunLight(scene, 3, 1f);
|
||||
var output = new byte[scene.RegionLength];
|
||||
using var convolver = new CpuTileConvolver(3);
|
||||
|
||||
convolver.RenderStored(stored, plan.RegionWidth * plan.RegionHeight, gain, output, light, plan.RegionWidth, plan.RegionX, plan.RegionY);
|
||||
|
||||
Assert.Equal(expected, output);
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[InlineData(true, 1f)]
|
||||
[InlineData(false, 1f)]
|
||||
public void ADitheredRegionAwayFromTheOriginUsesTheCanvasPosition(bool linear, float gain)
|
||||
{
|
||||
var light = new LightOptions(linear, true, 0f, 0f);
|
||||
var source = ConvolutionScene.RandomSource(120, 80, 79, 0.5);
|
||||
var scene = ConvolutionScene.CreateShifted(source, 43, 29, 120, 80, 37, 23, 132, 92, 4, 64, light);
|
||||
var plan = scene.Plan;
|
||||
var (output, convolved) = RunLight(scene, 3, gain);
|
||||
|
||||
for (var y = 0; y < plan.RegionHeight; y += 3)
|
||||
{
|
||||
for (var x = 0; x < plan.RegionWidth; x += 2)
|
||||
{
|
||||
var index = (y * plan.RegionWidth + x) * 4;
|
||||
var expected = LightTransform.ToBytes(convolved[index], convolved[index + 1], convolved[index + 2], convolved[index + 3], gain, light, plan.RegionX + x, plan.RegionY + y);
|
||||
Assert.Equal((expected.Blue, expected.Green, expected.Red, expected.Alpha), (output[index], output[index + 1], output[index + 2], output[index + 3]));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[InlineData(true)]
|
||||
[InlineData(false)]
|
||||
public void RenderingASeveralChunkStoreAwayFromTheOriginKeepsEveryPosition(bool linear)
|
||||
{
|
||||
var light = new LightOptions(linear, true, 0.85f, linear ? 12f : 0f);
|
||||
var source = ConvolutionScene.RandomSource(100, 60, 80, 0.5);
|
||||
var scene = ConvolutionScene.CreateShifted(source, 103, 59, 100, 60, 97, 53, 313, 207, 4, 64, light);
|
||||
var plan = scene.Plan;
|
||||
Assert.True(plan.RegionWidth * plan.RegionHeight > CpuTileConvolver.StoredChunkPixels * 3);
|
||||
Assert.NotEqual(0, CpuTileConvolver.StoredChunkPixels % plan.RegionWidth);
|
||||
var (expected, _) = RunLight(scene, 3, 1.2f);
|
||||
var (_, stored) = RunLight(scene, 3, 1f);
|
||||
var output = new byte[scene.RegionLength];
|
||||
using var convolver = new CpuTileConvolver(4);
|
||||
|
||||
convolver.RenderStored(stored, plan.RegionWidth * plan.RegionHeight, 1.2f, output, light, plan.RegionWidth, plan.RegionX, plan.RegionY);
|
||||
|
||||
Assert.Equal(expected, output);
|
||||
}
|
||||
}
|
||||
@@ -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));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,90 @@
|
||||
namespace SpectralConvolution.Tests;
|
||||
|
||||
public sealed class FastFourierTransformTests
|
||||
{
|
||||
[Fact]
|
||||
public void ForwardOfImpulseIsConstant()
|
||||
{
|
||||
var real = new double[16];
|
||||
var imaginary = new double[16];
|
||||
real[0] = 1;
|
||||
|
||||
FastFourierTransform.Forward(real, imaginary);
|
||||
|
||||
for (var index = 0; index < real.Length; index++)
|
||||
{
|
||||
Assert.True(Math.Abs(real[index] - 1) < 1e-12);
|
||||
Assert.True(Math.Abs(imaginary[index]) < 1e-12);
|
||||
}
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void OneDimensionalRoundTripRestoresInput()
|
||||
{
|
||||
var random = new Random(12345);
|
||||
var real = new double[256];
|
||||
var imaginary = new double[256];
|
||||
for (var index = 0; index < real.Length; index++)
|
||||
{
|
||||
real[index] = random.NextDouble() * 2 - 1;
|
||||
imaginary[index] = random.NextDouble() * 2 - 1;
|
||||
}
|
||||
var expectedReal = (double[])real.Clone();
|
||||
var expectedImaginary = (double[])imaginary.Clone();
|
||||
|
||||
FastFourierTransform.Forward(real, imaginary);
|
||||
FastFourierTransform.Inverse(real, imaginary);
|
||||
|
||||
AssertMaximumError(expectedReal, expectedImaginary, real, imaginary, 1e-11);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void TwoDimensionalRoundTripRestoresInput()
|
||||
{
|
||||
var random = new Random(67890);
|
||||
var length = 64 * 32;
|
||||
var real = new double[length];
|
||||
var imaginary = new double[length];
|
||||
for (var index = 0; index < length; index++)
|
||||
{
|
||||
real[index] = random.NextDouble();
|
||||
imaginary[index] = random.NextDouble();
|
||||
}
|
||||
var expectedReal = (double[])real.Clone();
|
||||
var expectedImaginary = (double[])imaginary.Clone();
|
||||
|
||||
FastFourierTransform.Forward2D(real, imaginary, 64, 32);
|
||||
FastFourierTransform.Inverse2D(real, imaginary, 64, 32);
|
||||
|
||||
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 minimum = AllocationProbe.MinimumAllocatedBytes(() =>
|
||||
{
|
||||
FastFourierTransform.Forward(real, imaginary);
|
||||
FastFourierTransform.Inverse(real, imaginary);
|
||||
}, 64);
|
||||
|
||||
Assert.Equal(0L, minimum);
|
||||
}
|
||||
|
||||
static void AssertMaximumError(double[] expectedReal, double[] expectedImaginary, double[] actualReal, double[] actualImaginary, double tolerance)
|
||||
{
|
||||
var maximum = 0d;
|
||||
for (var index = 0; index < expectedReal.Length; index++)
|
||||
{
|
||||
var realError = Math.Abs(expectedReal[index] - actualReal[index]);
|
||||
var imaginaryError = Math.Abs(expectedImaginary[index] - actualImaginary[index]);
|
||||
maximum = Math.Max(maximum, Math.Max(realError, imaginaryError));
|
||||
}
|
||||
Assert.True(maximum <= tolerance, $"{maximum:R}");
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,740 @@
|
||||
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, Int2[]? chosenSamples = null)
|
||||
{
|
||||
using var convolver = new GpuTileConvolver(device);
|
||||
return Run(device, convolver, scene, gain, tamper, chosenSamples);
|
||||
}
|
||||
|
||||
static GpuRun Run(GraphicsDevice device, GpuTileConvolver convolver, ConvolutionScene scene, float gain = 1f, Func<float[], float[]>? tamper = null, Int2[]? chosenSamples = null)
|
||||
{
|
||||
var plan = scene.Plan;
|
||||
var samples = chosenSamples ?? Samples(plan);
|
||||
convolver.Upload(scene.Spectrum);
|
||||
var spectrum = MemoryMarshal.Cast<Float2, float>(scene.Spectrum.Spectrum).ToArray();
|
||||
if (tamper is not null)
|
||||
{
|
||||
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, scene.Light);
|
||||
using var source = device.AllocateReadWriteTexture2D<Bgra32, Float4>(scene.SourceWidth, scene.SourceHeight);
|
||||
source.CopyFrom(MemoryMarshal.Cast<byte, Bgra32>(scene.Source));
|
||||
using var output = device.AllocateReadWriteTexture2D<Bgra32, Float4>(plan.RegionWidth, plan.RegionHeight);
|
||||
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));
|
||||
}
|
||||
|
||||
static ConvolutionScene LightScene(int size, int radius, int width, int height, int margin, int seed, LightOptions light)
|
||||
=> ConvolutionScene.Create(ConvolutionScene.RandomSource(width, height, seed, 0.45), width, height, margin, radius, size, light);
|
||||
|
||||
[Theory]
|
||||
[InlineData(64, 5, 150, 97, 11, false, true, 0f, 0f)]
|
||||
[InlineData(64, 5, 150, 97, 11, true, false, 0f, 0f)]
|
||||
[InlineData(128, 23, 140, 90, 24, true, true, 0.9f, 20f)]
|
||||
[InlineData(512, 3, 1100, 560, 8, true, false, 0.8f, 100f)]
|
||||
public void ALightRunPassesEveryCheckAndStaysWithinTheBound(int size, int radius, int width, int height, int margin, bool linear, bool dither, float threshold, float boost)
|
||||
{
|
||||
var scene = LightScene(size, radius, width, height, margin, size + radius, new LightOptions(linear, dither, threshold, boost));
|
||||
|
||||
var run = Run(HardwareOrDefault(), scene);
|
||||
|
||||
Assert.InRange(scene.WorstRatio(run.Store, ConvolutionBound.GpuOperationError), 0d, 1d);
|
||||
Assert.All(Measure(scene, run), measurement => Assert.True(measurement.Passes, $"{measurement}"));
|
||||
}
|
||||
|
||||
static void AssertOutputIsTheTransformOfTheStore(ConvolutionScene scene, GpuRun run, float gain, LightOptions light)
|
||||
{
|
||||
var width = scene.Plan.RegionWidth;
|
||||
var differing = 0;
|
||||
for (var y = 0; y < scene.Plan.RegionHeight; y++)
|
||||
{
|
||||
for (var x = 0; x < width; x++)
|
||||
{
|
||||
var index = (y * width + x) * 4;
|
||||
var expected = LightTransform.ToBytes(run.Store[index], run.Store[index + 1], run.Store[index + 2], run.Store[index + 3], gain, light, scene.Plan.RegionX + x, scene.Plan.RegionY + y);
|
||||
Assert.InRange(run.Output[index] - expected.Blue, -1, 1);
|
||||
Assert.InRange(run.Output[index + 1] - expected.Green, -1, 1);
|
||||
Assert.InRange(run.Output[index + 2] - expected.Red, -1, 1);
|
||||
Assert.InRange(run.Output[index + 3] - expected.Alpha, -1, 1);
|
||||
differing += (run.Output[index] != expected.Blue ? 1 : 0) + (run.Output[index + 1] != expected.Green ? 1 : 0)
|
||||
+ (run.Output[index + 2] != expected.Red ? 1 : 0) + (run.Output[index + 3] != expected.Alpha ? 1 : 0);
|
||||
}
|
||||
}
|
||||
|
||||
// The power function of the GPU differs from the table of the CPU by a few millionths, which moves the
|
||||
// rounded value by one step in a few of ten thousand places. A wrong threshold or a wrong rounding
|
||||
// moves it in about a third of them.
|
||||
Assert.InRange(differing, 0, run.Output.Length / 2000);
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[InlineData(true, false, 1f)]
|
||||
[InlineData(true, true, 1f)]
|
||||
[InlineData(true, true, 2.5f)]
|
||||
[InlineData(false, true, 1f)]
|
||||
[InlineData(false, true, 1.7f)]
|
||||
public void TheLightOutputIsTheTransformOfTheStoredValue(bool linear, bool dither, float gain)
|
||||
{
|
||||
var light = new LightOptions(linear, dither, 0.8f, linear ? 8f : 0f);
|
||||
var scene = LightScene(64, 4, 90, 60, 8, 9, light);
|
||||
|
||||
var run = Run(HardwareOrDefault(), scene, gain);
|
||||
|
||||
AssertOutputIsTheTransformOfTheStore(scene, run, gain, light);
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[InlineData(false, true, 1f)]
|
||||
[InlineData(true, false, 2.75f)]
|
||||
[InlineData(true, true, 0.3f)]
|
||||
public void RenderingTheStoreMatchesTheLightConvolutionBitForBit(bool linear, bool dither, float gain)
|
||||
{
|
||||
var light = new LightOptions(linear, dither, 0.85f, linear ? 12f : 0f);
|
||||
var scene = LightScene(64, 5, 150, 97, 11, 47, light);
|
||||
var device = HardwareOrDefault();
|
||||
var fused = Run(device, scene, gain);
|
||||
using var convolver = new GpuTileConvolver(device);
|
||||
var stored = Run(device, convolver, scene, 1f);
|
||||
var width = scene.Plan.RegionWidth;
|
||||
var height = scene.Plan.RegionHeight;
|
||||
using var output = device.AllocateReadWriteTexture2D<Bgra32, Float4>(width, height);
|
||||
|
||||
using (var context = device.CreateComputeContext())
|
||||
GpuTileConvolver.RecordStored(in context, convolver.StoreFor(stored.Job), output, width, height, gain, in light, scene.Plan.RegionX, scene.Plan.RegionY);
|
||||
|
||||
var pixels = new Bgra32[width * height];
|
||||
output.CopyTo(pixels);
|
||||
Assert.Equal(fused.Output, MemoryMarshal.Cast<Bgra32, byte>(pixels).ToArray());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void TheLightStatisticsDescribeTheTransformedSource()
|
||||
{
|
||||
var light = new LightOptions(true, false, 0.9f, 20f);
|
||||
var scene = LightScene(64, 5, 150, 97, 11, 3, light);
|
||||
|
||||
var run = Run(HardwareOrDefault(), scene);
|
||||
|
||||
for (var tile = 0; tile < scene.Plan.TileCount; tile++)
|
||||
{
|
||||
var (redGreen, blueAlpha) = scene.Norms(scene.Plan.RegionX + tile % scene.Plan.TilesX * scene.Plan.ValidSize, scene.Plan.RegionY + tile / scene.Plan.TilesX * scene.Plan.ValidSize);
|
||||
var measured = GpuTileCheck.Norms(run.Report, scene.Plan, tile, true);
|
||||
Assert.InRange(measured.RedGreen, redGreen * (1d - 1e-4), redGreen * (1d + 1e-3));
|
||||
Assert.InRange(measured.BlueAlpha, blueAlpha * (1d - 1e-4), blueAlpha * (1d + 1e-3));
|
||||
}
|
||||
|
||||
var measurements = Measure(scene, run);
|
||||
var values = scene.Transformed();
|
||||
var totals = new double[4];
|
||||
for (var index = 0; index < scene.SourceWidth * scene.SourceHeight; index++)
|
||||
{
|
||||
for (var channel = 0; channel < 4; channel++)
|
||||
totals[channel] += values[index * 4 + channel];
|
||||
}
|
||||
for (var channel = 0; channel < 4; channel++)
|
||||
Assert.Equal(totals[channel], measurements[1 + channel].Reference, totals[channel] * 1e-5);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void AScaledSpectrumFailsTheLightSumCheck()
|
||||
{
|
||||
var scene = LightScene(64, 5, 150, 97, 11, 21, new LightOptions(true, false, 0.9f, 20f));
|
||||
|
||||
var measurements = Measure(scene, Run(HardwareOrDefault(), scene, tamper: spectrum => [.. spectrum.Select(value => value * 1.0005f)]));
|
||||
|
||||
Assert.Contains(measurements, measurement => measurement.Name.StartsWith("sum.", StringComparison.Ordinal) && !measurement.Passes);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void AMirroredKernelFailsTheLightSpotCheck()
|
||||
{
|
||||
var scene = LightScene(64, 5, 150, 97, 16, 23, new LightOptions(true, false, 0.9f, 20f));
|
||||
|
||||
var measurements = Measure(scene, Run(HardwareOrDefault(), scene, tamper: spectrum =>
|
||||
{
|
||||
var mirrored = (float[])spectrum.Clone();
|
||||
for (var index = 1; index < mirrored.Length; index += 2)
|
||||
mirrored[index] = -mirrored[index];
|
||||
return mirrored;
|
||||
}));
|
||||
|
||||
Assert.Contains(measurements, measurement => measurement.Name.StartsWith("spot.", StringComparison.Ordinal) && !measurement.Passes);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void AWrongHighlightFailsTheLightSpotCheck()
|
||||
{
|
||||
var claimed = new LightOptions(true, false, 0.9f, 20f);
|
||||
var actual = LightScene(64, 5, 150, 97, 16, 25, new LightOptions(true, false, 0.9f, 2f));
|
||||
|
||||
var run = Run(HardwareOrDefault(), actual);
|
||||
var measurements = new ConvolutionMeasurement[GpuTileCheck.MeasurementCount(run.Samples.Length)];
|
||||
GpuTileCheck.Evaluate(run.Report, run.Job with { Light = claimed }, run.Samples, actual.Spectrum.Kernel, measurements);
|
||||
|
||||
Assert.Contains(measurements, measurement => !measurement.Passes);
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[InlineData(false)]
|
||||
[InlineData(true)]
|
||||
public void ADitheredOpaqueWhiteSceneNeverDropsToBlackAnywhere(bool linear)
|
||||
{
|
||||
var light = new LightOptions(linear, true, 0f, 0f);
|
||||
var scene = ConvolutionScene.Create(ConvolutionScene.Uniform(1100, 700, 255), 1100, 700, 8, 3, 512, light);
|
||||
|
||||
var run = Run(HardwareOrDefault(), scene);
|
||||
|
||||
var wrong = 0;
|
||||
for (var y = 8 + 4; y < 8 + 700 - 4; y++)
|
||||
{
|
||||
for (var x = 8 + 4; x < 8 + 1100 - 4; x++)
|
||||
{
|
||||
var index = (y * scene.Plan.RegionWidth + x) * 4;
|
||||
if (run.Output[index] < 250 || run.Output[index + 1] < 250 || run.Output[index + 2] < 250 || run.Output[index + 3] < 250)
|
||||
wrong++;
|
||||
}
|
||||
}
|
||||
|
||||
Assert.Equal(0, wrong);
|
||||
}
|
||||
|
||||
static bool Marked(Int2[] entries, int tile)
|
||||
{
|
||||
var entry = entries[GpuTileConvolver.MaximumSamples + (tile >> 6)];
|
||||
return (((tile & 32) == 0 ? entry.X : entry.Y) >> (tile & 31) & 1) != 0;
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[InlineData(false)]
|
||||
[InlineData(true)]
|
||||
public void TheSamplesBufferMarksTheTilesThatHoldASample(bool linear)
|
||||
{
|
||||
var light = new LightOptions(linear, false, 0f, 0f);
|
||||
var scene = ConvolutionScene.Create(ConvolutionScene.RandomSource(1400, 900, 5, 0.4), 1400, 900, 8, 5, 128, light);
|
||||
var plan = scene.Plan;
|
||||
using var convolver = new GpuTileConvolver(HardwareOrDefault());
|
||||
convolver.Upload(scene.Spectrum);
|
||||
var samples = Samples(plan);
|
||||
|
||||
convolver.Prepare(plan, scene.SourceX, scene.SourceY, scene.SourceWidth, scene.SourceHeight, 1f, samples, false, light);
|
||||
|
||||
var entries = new Int2[convolver.Samples.Length];
|
||||
convolver.Samples.CopyTo(entries);
|
||||
Assert.True(plan.TileCount > 64);
|
||||
Assert.Equal(samples, entries.Take(GpuTileConvolver.MaximumSamples));
|
||||
var expected = new HashSet<int>(samples.Select(sample => plan.TileAt(plan.RegionX + sample.X, plan.RegionY + sample.Y)));
|
||||
Assert.True(expected.Count > 1);
|
||||
for (var tile = 0; tile < (plan.TileCount + 63) / 64 * 64; tile++)
|
||||
Assert.Equal(expected.Contains(tile), Marked(entries, tile));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void TheMarksFollowTheSamplesOfTheLatestJob()
|
||||
{
|
||||
var scene = ConvolutionScene.Create(ConvolutionScene.RandomSource(1400, 900, 6, 0.4), 1400, 900, 8, 5, 128);
|
||||
var plan = scene.Plan;
|
||||
using var convolver = new GpuTileConvolver(HardwareOrDefault());
|
||||
convolver.Upload(scene.Spectrum);
|
||||
Int2[] first = [new(0, 0)];
|
||||
Int2[] second = [new(plan.RegionWidth - 1, plan.RegionHeight - 1)];
|
||||
|
||||
convolver.Prepare(plan, scene.SourceX, scene.SourceY, scene.SourceWidth, scene.SourceHeight, 1f, first, false);
|
||||
convolver.Prepare(plan, scene.SourceX, scene.SourceY, scene.SourceWidth, scene.SourceHeight, 1f, second, false);
|
||||
|
||||
var entries = new Int2[convolver.Samples.Length];
|
||||
convolver.Samples.CopyTo(entries);
|
||||
var lastTile = plan.TileAt(plan.RegionX + second[0].X, plan.RegionY + second[0].Y);
|
||||
for (var tile = 0; tile < (plan.TileCount + 63) / 64 * 64; tile++)
|
||||
Assert.Equal(tile == lastTile, Marked(entries, tile));
|
||||
Assert.Equal(second[0], entries[0]);
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[InlineData(false, 1f)]
|
||||
[InlineData(true, 1f)]
|
||||
[InlineData(true, 1.8f)]
|
||||
public void ADitheredTranslucentSceneKeepsEveryColorBelowItsOpacity(bool linear, float gain)
|
||||
{
|
||||
var light = new LightOptions(linear, true, 0f, 0f);
|
||||
var scene = ConvolutionScene.Create(ConvolutionScene.Uniform(240, 160, 128), 240, 160, 8, 3, 64, light);
|
||||
|
||||
var run = Run(HardwareOrDefault(), scene, gain);
|
||||
|
||||
var exceeding = 0;
|
||||
var translucent = 0;
|
||||
for (var index = 0; index < run.Output.Length; index += 4)
|
||||
{
|
||||
if (run.Output[index + 3] is > 0 and < 255)
|
||||
translucent++;
|
||||
if (run.Output[index] > run.Output[index + 3] || run.Output[index + 1] > run.Output[index + 3] || run.Output[index + 2] > run.Output[index + 3])
|
||||
exceeding++;
|
||||
}
|
||||
|
||||
Assert.True(translucent > 1000, $"{translucent}");
|
||||
Assert.Equal(0, exceeding);
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[InlineData(true, false, 1f)]
|
||||
[InlineData(false, true, 1.7f)]
|
||||
[InlineData(true, true, 1f)]
|
||||
[InlineData(true, true, 2.2f)]
|
||||
public void ARegionAwayFromTheOriginDrawsTheSameLightImageAsTheCpu(bool linear, bool dither, float gain)
|
||||
{
|
||||
var light = new LightOptions(linear, dither, 0.8f, linear ? 8f : 0f);
|
||||
var source = ConvolutionScene.RandomSource(120, 80, 77, 0.5);
|
||||
var scene = ConvolutionScene.CreateShifted(source, 43, 29, 120, 80, 37, 23, 132, 92, 4, 64, light);
|
||||
var plan = scene.Plan;
|
||||
var cpu = new byte[scene.RegionLength];
|
||||
using (var convolver = new CpuTileConvolver(3))
|
||||
convolver.Convolve(scene.Source, scene.SourceX, scene.SourceY, scene.SourceWidth, scene.SourceHeight, scene.Spectrum, plan, cpu, gain, null, light);
|
||||
|
||||
var run = Run(HardwareOrDefault(), scene, gain);
|
||||
|
||||
var differing = 0;
|
||||
for (var index = 0; index < cpu.Length; index++)
|
||||
{
|
||||
Assert.InRange(run.Output[index] - cpu[index], -1, 1);
|
||||
if (run.Output[index] != cpu[index])
|
||||
differing++;
|
||||
}
|
||||
|
||||
Assert.InRange(differing, 0, cpu.Length / 2000);
|
||||
Assert.All(Measure(scene, run), measurement => Assert.True(measurement.Passes, $"{measurement}"));
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[InlineData(true, true, 1.3f)]
|
||||
[InlineData(false, true, 2f)]
|
||||
public void RenderingTheStoreMatchesTheLightConvolutionForARegionAwayFromTheOrigin(bool linear, bool dither, float gain)
|
||||
{
|
||||
var light = new LightOptions(linear, dither, 0.85f, linear ? 12f : 0f);
|
||||
var source = ConvolutionScene.RandomSource(120, 80, 78, 0.5);
|
||||
var scene = ConvolutionScene.CreateShifted(source, 43, 29, 120, 80, 37, 23, 132, 92, 4, 64, light);
|
||||
var device = HardwareOrDefault();
|
||||
var fused = Run(device, scene, gain);
|
||||
using var convolver = new GpuTileConvolver(device);
|
||||
var stored = Run(device, convolver, scene, 1f);
|
||||
var width = scene.Plan.RegionWidth;
|
||||
var height = scene.Plan.RegionHeight;
|
||||
using var output = device.AllocateReadWriteTexture2D<Bgra32, Float4>(width, height);
|
||||
|
||||
using (var context = device.CreateComputeContext())
|
||||
GpuTileConvolver.RecordStored(in context, convolver.StoreFor(stored.Job), output, width, height, gain, in light, scene.Plan.RegionX, scene.Plan.RegionY);
|
||||
|
||||
var pixels = new Bgra32[width * height];
|
||||
output.CopyTo(pixels);
|
||||
Assert.Equal(fused.Output, MemoryMarshal.Cast<Bgra32, byte>(pixels).ToArray());
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[InlineData(false)]
|
||||
[InlineData(true)]
|
||||
public void EverySampledTileReportsItsSpotWhateverItsIndex(bool linear)
|
||||
{
|
||||
var light = new LightOptions(linear, false, 0f, 0f);
|
||||
var scene = ConvolutionScene.Create(ConvolutionScene.RandomSource(1400, 900, 12, 0.6), 1400, 900, 8, 5, 128, light);
|
||||
var plan = scene.Plan;
|
||||
Assert.True(plan.TileCount > 90);
|
||||
int[] tiles = [0, 31, 32, 33, 63, 64, 65, 95];
|
||||
var samples = tiles.Select(tile => new Int2(
|
||||
Math.Min(tile % plan.TilesX * plan.ValidSize + plan.ValidSize / 2, plan.RegionWidth - 1),
|
||||
Math.Min(tile / plan.TilesX * plan.ValidSize + plan.ValidSize / 2, plan.RegionHeight - 1))).ToArray();
|
||||
Assert.Equal(tiles, samples.Select(sample => plan.TileAt(plan.RegionX + sample.X, plan.RegionY + sample.Y)).ToArray());
|
||||
|
||||
var run = Run(HardwareOrDefault(), scene, 1f, null, samples);
|
||||
|
||||
var measurements = Measure(scene, run);
|
||||
Assert.All(measurements, measurement => Assert.True(measurement.Passes, $"{measurement}"));
|
||||
for (var sample = 0; sample < samples.Length; sample++)
|
||||
Assert.True(measurements[1 + 4 + sample * 4 + 3].Measured > 0d, $"tile {tiles[sample]}");
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[InlineData(true, false)]
|
||||
[InlineData(true, true)]
|
||||
public void ADarkSceneStaysWithinTheBoundInLinearLight(bool linear, bool dither)
|
||||
{
|
||||
var random = new Random(5);
|
||||
var source = new byte[150 * 97 * 4];
|
||||
for (var index = 0; index < source.Length; index += 4)
|
||||
{
|
||||
source[index] = (byte)random.Next(0, 9);
|
||||
source[index + 1] = (byte)random.Next(0, 9);
|
||||
source[index + 2] = (byte)random.Next(0, 9);
|
||||
source[index + 3] = 255;
|
||||
}
|
||||
|
||||
var light = new LightOptions(linear, dither, 0f, 0f);
|
||||
var scene = ConvolutionScene.Create(source, 150, 97, 11, 5, 64, light);
|
||||
|
||||
var run = Run(HardwareOrDefault(), scene);
|
||||
|
||||
Assert.All(Measure(scene, run), measurement => Assert.True(measurement.Passes, $"{measurement}"));
|
||||
Assert.InRange(scene.WorstRatio(run.Store, ConvolutionBound.GpuOperationError + GpuTileCheck.LightTransformError), 0d, 1d);
|
||||
AssertOutputIsTheTransformOfTheStore(scene, run, 1f, light);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void PreparingInvalidLightOptionsIsRejected()
|
||||
{
|
||||
var scene = ConvolutionScene.Create(ConvolutionScene.RandomSource(100, 60, 3, 0.5), 100, 60, 8, 4, 64);
|
||||
var plan = scene.Plan;
|
||||
using var convolver = new GpuTileConvolver(HardwareOrDefault());
|
||||
convolver.Upload(scene.Spectrum);
|
||||
|
||||
Assert.Throws<ArgumentOutOfRangeException>(() => convolver.Prepare(plan, 8, 8, 100, 60, 1f, [], false, new LightOptions(true, false, 1.5f, 5f)));
|
||||
Assert.Throws<ArgumentOutOfRangeException>(() => convolver.Prepare(plan, 8, 8, 100, 60, 1f, [], false, new LightOptions(true, false, 0.5f, 2000f)));
|
||||
convolver.Prepare(plan, 8, 8, 100, 60, 1f, [], false, new LightOptions(true, false, 0.5f, 5f));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void TheLinearLightToleranceExceedsTheOtherOneByTheTransformError()
|
||||
{
|
||||
var scene = ConvolutionScene.Create(ConvolutionScene.RandomSource(150, 97, 31, 0.45), 150, 97, 11, 5, 64, new LightOptions(true, false, 0f, 0f));
|
||||
var run = Run(HardwareOrDefault(), scene);
|
||||
var plan = scene.Plan;
|
||||
var sampleCount = run.Samples.Length;
|
||||
var linear = new ConvolutionMeasurement[GpuTileCheck.MeasurementCount(sampleCount)];
|
||||
var plain = new ConvolutionMeasurement[linear.Length];
|
||||
var linearJob = run.Job with { Light = new LightOptions(true, true, 0f, 0f) };
|
||||
var plainJob = run.Job with { Light = new LightOptions(false, true, 0f, 0f) };
|
||||
|
||||
GpuTileCheck.Evaluate(run.Report, linearJob, run.Samples, scene.Spectrum.Kernel, linear);
|
||||
GpuTileCheck.Evaluate(run.Report, plainJob, run.Samples, scene.Spectrum.Kernel, plain);
|
||||
|
||||
for (var sample = 0; sample < sampleCount; sample++)
|
||||
{
|
||||
var tile = plan.TileAt(plan.RegionX + run.Samples[sample].X, plan.RegionY + run.Samples[sample].Y);
|
||||
var (redGreen, blueAlpha) = GpuTileCheck.Norms(run.Report, plan, tile, true);
|
||||
for (var channel = 0; channel < 4; channel++)
|
||||
{
|
||||
var index = 1 + 4 + sample * 4 + channel;
|
||||
var norm = channel < 2 ? redGreen : blueAlpha;
|
||||
Assert.Equal(GpuTileCheck.LightTransformError * norm, linear[index].Tolerance - plain[index].Tolerance, norm * 1e-12);
|
||||
}
|
||||
}
|
||||
|
||||
Assert.Equal(Math.ScaleB(1d, -16), GpuTileCheck.LightTransformError);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,214 @@
|
||||
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}");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[InlineData(5, 64)]
|
||||
[InlineData(20, 128)]
|
||||
[InlineData(63, 512)]
|
||||
public void EveryElementOfTheSpectrumAgreesWithAFullTwoDimensionalTransform(int radius, int size)
|
||||
{
|
||||
var values = AsymmetricKernel(radius);
|
||||
var spectrum = new KernelSpectrum();
|
||||
|
||||
spectrum.Update(values, radius, size);
|
||||
|
||||
var kernelSize = radius * 2 + 1;
|
||||
var sum = values.Sum();
|
||||
var mask = size - 1;
|
||||
var real = new double[size * size];
|
||||
var imaginary = new double[size * size];
|
||||
for (var offsetY = -radius; offsetY <= radius; offsetY++)
|
||||
{
|
||||
for (var offsetX = -radius; offsetX <= radius; offsetX++)
|
||||
real[(-offsetY & mask) * size + (-offsetX & mask)] = values[(offsetY + radius) * kernelSize + offsetX + radius] / sum;
|
||||
}
|
||||
|
||||
FastFourierTransform.Forward2D(real, imaginary, size, size);
|
||||
|
||||
var excess = double.NegativeInfinity;
|
||||
for (var frequencyY = 0; frequencyY < size; frequencyY++)
|
||||
{
|
||||
for (var frequencyX = 0; frequencyX < size; frequencyX++)
|
||||
{
|
||||
var value = spectrum.Spectrum[frequencyX * size + frequencyY];
|
||||
var index = frequencyY * size + frequencyX;
|
||||
excess = Math.Max(excess, Math.Abs(value.X - real[index]) - (1e-12 + Math.Abs(real[index]) * 1e-6));
|
||||
excess = Math.Max(excess, Math.Abs(value.Y - imaginary[index]) - (1e-12 + Math.Abs(imaginary[index]) * 1e-6));
|
||||
}
|
||||
}
|
||||
|
||||
Assert.True(excess <= 0d, $"{excess}");
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void TheSpectrumAtZeroFrequencyIsTheKernelSum()
|
||||
{
|
||||
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,556 @@
|
||||
using System.Runtime.Intrinsics;
|
||||
|
||||
namespace SpectralConvolution.Tests;
|
||||
|
||||
public sealed class LightTransformTests
|
||||
{
|
||||
static readonly LightOptions Linear = new(true, false, 0f, 0f);
|
||||
|
||||
static double ReferenceDecode(double encoded)
|
||||
=> encoded <= 0.04045 ? encoded / 12.92 : Math.Pow((encoded + 0.055) / 1.055, 2.4);
|
||||
|
||||
static double ReferenceEncode(double linear)
|
||||
=> linear <= 0.0031308 ? linear * 12.92 : 1.055 * Math.Pow(linear, 1d / 2.4) - 0.055;
|
||||
|
||||
[Fact]
|
||||
public void TheEndpointsAreFixed()
|
||||
{
|
||||
Assert.Equal(0f, LightTransform.Decode(0f));
|
||||
Assert.Equal(1f, LightTransform.Decode(1f));
|
||||
Assert.Equal(0f, LightTransform.Encode(0f));
|
||||
Assert.Equal(1f, LightTransform.Encode(1f));
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[InlineData(0.01f)]
|
||||
[InlineData(0.04045f)]
|
||||
[InlineData(0.05f)]
|
||||
[InlineData(0.2f)]
|
||||
[InlineData(0.5f)]
|
||||
[InlineData(0.8f)]
|
||||
public void DecodeFollowsTheStandardCurve(float encoded)
|
||||
{
|
||||
var expected = ReferenceDecode(encoded);
|
||||
|
||||
Assert.Equal(expected, LightTransform.Decode(encoded), expected * 1e-6);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void EncodeReturnsEveryByteThatDecodeStarted()
|
||||
{
|
||||
for (var value = 0; value < 256; value++)
|
||||
{
|
||||
var encoded = LightTransform.Encode(LightTransform.Decode(value / 255f));
|
||||
|
||||
Assert.Equal(value, (byte)(encoded * 255f + 0.5f));
|
||||
}
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void WithoutLinearLightTheBytesPassThrough()
|
||||
{
|
||||
var (red, green, blue, alpha) = LightTransform.FromBytes(10, 200, 33, 128, default);
|
||||
|
||||
Assert.Equal(10 / 255f, red);
|
||||
Assert.Equal(200 / 255f, green);
|
||||
Assert.Equal(33 / 255f, blue);
|
||||
Assert.Equal(128 / 255f, alpha);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void AnOpaquePixelIsDecodedChannelByChannel()
|
||||
{
|
||||
var (red, green, blue, alpha) = LightTransform.FromBytes(10, 128, 255, 255, Linear);
|
||||
|
||||
Assert.Equal(LightTransform.Decode(10 / 255f), red);
|
||||
Assert.Equal(LightTransform.Decode(128 / 255f), green);
|
||||
Assert.Equal(1f, blue);
|
||||
Assert.Equal(1f, alpha);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void ATranslucentPixelIsDecodedFromItsStraightColorAndPremultipliedAgain()
|
||||
{
|
||||
var (red, green, blue, alpha) = LightTransform.FromBytes(128, 64, 32, 128, Linear);
|
||||
|
||||
var opacity = 128 / 255f;
|
||||
Assert.Equal(opacity, alpha);
|
||||
Assert.Equal(1.0, red / opacity, 1e-6);
|
||||
Assert.Equal(ReferenceDecode(64 / 128d), green / opacity, 1e-6);
|
||||
Assert.Equal(ReferenceDecode(32 / 128d), blue / opacity, 1e-6);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void AFullyTransparentPixelIsZeroWhateverItsColor()
|
||||
{
|
||||
Assert.Equal((0f, 0f, 0f, 0f), LightTransform.FromBytes(200, 100, 50, 0, Linear));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void HighlightsRaiseAWhitePixelByTheBoost()
|
||||
{
|
||||
var options = new LightOptions(true, false, 0.9f, 10f);
|
||||
|
||||
var (red, green, blue, alpha) = LightTransform.FromBytes(255, 255, 255, 255, options);
|
||||
|
||||
Assert.Equal(10f, red);
|
||||
Assert.Equal(10f, green);
|
||||
Assert.Equal(10f, blue);
|
||||
Assert.Equal(10f, alpha);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void HighlightsLeaveAPixelAtOrBelowTheThresholdAlone()
|
||||
{
|
||||
var options = new LightOptions(true, false, 230 / 255f, 10f);
|
||||
|
||||
var raised = LightTransform.FromBytes(230, 230, 230, 255, options);
|
||||
var plain = LightTransform.FromBytes(230, 230, 230, 255, Linear);
|
||||
|
||||
Assert.Equal(plain, raised);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void HighlightsRaiseByTheSquareOfTheExcess()
|
||||
{
|
||||
var options = new LightOptions(true, false, 0.9f, 10f);
|
||||
var peak = 242 / 255d;
|
||||
var expectedWeight = 1d + 9d * Math.Pow((peak - 0.9f) / (1d - 0.9f), 2d);
|
||||
|
||||
var raised = LightTransform.FromBytes(242, 242, 242, 255, options);
|
||||
var plain = LightTransform.FromBytes(242, 242, 242, 255, Linear);
|
||||
|
||||
Assert.Equal(expectedWeight, raised.Red / plain.Red, expectedWeight * 1e-3);
|
||||
Assert.Equal(raised.Red / plain.Red, raised.Alpha / plain.Alpha, 1e-3);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void HighlightsKeepTheRatioBetweenTheChannels()
|
||||
{
|
||||
var options = new LightOptions(true, false, 0.5f, 30f);
|
||||
|
||||
var raised = LightTransform.FromBytes(255, 128, 64, 255, options);
|
||||
var plain = LightTransform.FromBytes(255, 128, 64, 255, Linear);
|
||||
|
||||
Assert.Equal(raised.Red / plain.Red, raised.Green / plain.Green, 1e-4);
|
||||
Assert.Equal(raised.Red / plain.Red, raised.Blue / plain.Blue, 1e-4);
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[InlineData(1f, 0.5f)]
|
||||
[InlineData(0f, 0.5f)]
|
||||
[InlineData(10f, 1f)]
|
||||
public void HighlightsDoNothingWithoutABoostAboveOneOrAThresholdBelowOne(float boost, float threshold)
|
||||
{
|
||||
var options = new LightOptions(true, false, threshold, boost);
|
||||
|
||||
Assert.False(options.Highlights);
|
||||
Assert.Equal(LightTransform.FromBytes(255, 200, 100, 255, Linear), LightTransform.FromBytes(255, 200, 100, 255, options));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void HighlightsNeedLinearLight()
|
||||
{
|
||||
var options = new LightOptions(false, false, 0.5f, 10f);
|
||||
|
||||
Assert.False(options.Highlights);
|
||||
Assert.Equal(LightTransform.FromBytes(255, 200, 100, 255, default), LightTransform.FromBytes(255, 200, 100, 255, options));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void ForTheConvolutionOnlyTheInputAffectingFieldsRemain()
|
||||
{
|
||||
Assert.Equal(new LightOptions(true, false, 0.9f, 10f), new LightOptions(true, true, 0.9f, 10f).ForConvolution());
|
||||
Assert.Equal(new LightOptions(true, false, 0f, 0f), new LightOptions(true, true, 0.9f, 1f).ForConvolution());
|
||||
Assert.Equal(new LightOptions(false, false, 0f, 0f), new LightOptions(false, true, 0.9f, 10f).ForConvolution());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void EveryOpaqueByteSurvivesTheRoundTrip()
|
||||
{
|
||||
for (var value = 0; value < 256; value++)
|
||||
{
|
||||
var (red, green, blue, alpha) = LightTransform.FromBytes((byte)value, (byte)value, (byte)value, 255, Linear);
|
||||
var (outputBlue, outputGreen, outputRed, outputAlpha) = LightTransform.ToBytes(red, green, blue, alpha, 1f, Linear, 0, 0);
|
||||
|
||||
Assert.Equal((byte)value, outputRed);
|
||||
Assert.Equal((byte)value, outputGreen);
|
||||
Assert.Equal((byte)value, outputBlue);
|
||||
Assert.Equal((byte)255, outputAlpha);
|
||||
}
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void ATranslucentPixelSurvivesTheRoundTripWithinOneStep()
|
||||
{
|
||||
for (var alpha = 1; alpha < 256; alpha += 7)
|
||||
{
|
||||
for (var value = 0; value <= alpha; value += 5)
|
||||
{
|
||||
var (red, green, blue, opacity) = LightTransform.FromBytes((byte)value, (byte)(value / 2), (byte)(value / 3), (byte)alpha, Linear);
|
||||
var (outputBlue, outputGreen, outputRed, outputAlpha) = LightTransform.ToBytes(red, green, blue, opacity, 1f, Linear, 0, 0);
|
||||
|
||||
Assert.InRange(outputRed, value - 1, value + 1);
|
||||
Assert.InRange(outputGreen, value / 2 - 1, value / 2 + 1);
|
||||
Assert.InRange(outputBlue, value / 3 - 1, value / 3 + 1);
|
||||
Assert.Equal((byte)alpha, outputAlpha);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void TheGainBrightensAndSaturates()
|
||||
{
|
||||
var half = LightTransform.Decode(0.5f);
|
||||
|
||||
var doubled = LightTransform.ToBytes(half, half, half, 1f, 2f, Linear, 0, 0);
|
||||
var saturated = LightTransform.ToBytes(half, half, half, 1f, 100f, Linear, 0, 0);
|
||||
|
||||
Assert.Equal((byte)(LightTransform.Encode(MathF.Min(half * 2f, 1f)) * 255f + 0.5f), doubled.Red);
|
||||
Assert.Equal(((byte)255, (byte)255, (byte)255, (byte)255), saturated);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void AColorBeyondTheOpacityIsHeldAtTheOpacity()
|
||||
{
|
||||
var (blue, green, red, alpha) = LightTransform.ToBytes(2f, 0.1f, 0f, 0.5f, 1f, Linear, 0, 0);
|
||||
|
||||
Assert.Equal((byte)128, alpha);
|
||||
Assert.Equal((byte)128, red);
|
||||
Assert.True(green < 128);
|
||||
Assert.Equal((byte)0, blue);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void WithoutLinearLightTheOutputIsTheClampedValue()
|
||||
{
|
||||
float[] values = [float.NaN, -1f, 0f, 0.2f, 0.5f, 0.999f, 1f, 2f, float.PositiveInfinity];
|
||||
foreach (var value in values)
|
||||
{
|
||||
var (blue, green, red, alpha) = LightTransform.ToBytes(value, value, value, value, 1.5f, default, 3, 4);
|
||||
|
||||
var expected = CpuTileConvolver.ToUnorm(value * 1.5f);
|
||||
Assert.Equal(expected, red);
|
||||
Assert.Equal(expected, green);
|
||||
Assert.Equal(expected, blue);
|
||||
Assert.Equal(expected, alpha);
|
||||
}
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void TheDitherThresholdStaysBelowOneAndAveragesOneHalf()
|
||||
{
|
||||
var sum = 0d;
|
||||
var count = 0;
|
||||
for (var y = 0; y < 300; y++)
|
||||
{
|
||||
for (var x = 0; x < 300; x++)
|
||||
{
|
||||
var threshold = LightTransform.DitherThreshold(x, y);
|
||||
Assert.InRange(threshold, 0f, 0.99999994f);
|
||||
sum += threshold;
|
||||
count++;
|
||||
}
|
||||
}
|
||||
|
||||
Assert.Equal(0.5, sum / count, 0.01);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void TheDitherThresholdIsDeterministicAndDiffersByPosition()
|
||||
{
|
||||
Assert.Equal(LightTransform.DitherThreshold(12, 34), LightTransform.DitherThreshold(12, 34));
|
||||
var differing = 0;
|
||||
for (var x = 0; x < 64; x++)
|
||||
{
|
||||
if (LightTransform.DitherThreshold(x, 7) != LightTransform.DitherThreshold(x + 1, 7)
|
||||
&& LightTransform.DitherThreshold(x, 7) != LightTransform.DitherThreshold(x, 8))
|
||||
differing++;
|
||||
}
|
||||
|
||||
Assert.True(differing > 60);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void ADitheredValueKeepsItsFractionOnAverage()
|
||||
{
|
||||
var options = new LightOptions(false, true, 0f, 0f);
|
||||
var value = 100.3f / 255f;
|
||||
var sum = 0d;
|
||||
var count = 0;
|
||||
for (var y = 0; y < 200; y++)
|
||||
{
|
||||
for (var x = 0; x < 200; x++)
|
||||
{
|
||||
var (_, _, red, _) = LightTransform.ToBytes(value, 0f, 0f, 1f, 1f, options, x, y);
|
||||
Assert.InRange(red, 100, 101);
|
||||
sum += red;
|
||||
count++;
|
||||
}
|
||||
}
|
||||
|
||||
Assert.Equal(100.3, sum / count, 0.02);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void ADitheredBlackAndWhiteAreUnchanged()
|
||||
{
|
||||
var options = new LightOptions(false, true, 0f, 0f);
|
||||
for (var y = 0; y < 100; y++)
|
||||
{
|
||||
for (var x = 0; x < 100; x++)
|
||||
{
|
||||
Assert.Equal(((byte)0, (byte)0, (byte)0, (byte)255), LightTransform.ToBytes(0f, 0f, 0f, 1f, 1f, options, x, y));
|
||||
Assert.Equal(((byte)255, (byte)255, (byte)255, (byte)255), LightTransform.ToBytes(1f, 1f, 1f, 1f, 1f, options, x, y));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void ALinearWhiteStaysWhiteWhenDithered()
|
||||
{
|
||||
var options = new LightOptions(true, true, 0f, 0f);
|
||||
for (var y = 0; y < 100; y++)
|
||||
{
|
||||
for (var x = 0; x < 100; x++)
|
||||
Assert.Equal(((byte)255, (byte)255, (byte)255, (byte)255), LightTransform.ToBytes(1f, 1f, 1f, 1f, 1f, options, x, y));
|
||||
}
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[InlineData(float.NaN, 0f)]
|
||||
[InlineData(-0.1f, 0f)]
|
||||
[InlineData(1.1f, 0f)]
|
||||
[InlineData(0.5f, float.NaN)]
|
||||
[InlineData(0.5f, -1f)]
|
||||
[InlineData(0.5f, 1001f)]
|
||||
public void InvalidOptionsAreRejected(float threshold, float boost)
|
||||
{
|
||||
Assert.Throws<ArgumentOutOfRangeException>(() => new LightOptions(true, false, threshold, boost).Validate());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void TheDefaultOptionsAreValidAndDefault()
|
||||
{
|
||||
var options = default(LightOptions);
|
||||
|
||||
options.Validate();
|
||||
Assert.True(options.IsDefault);
|
||||
Assert.False(options.Highlights);
|
||||
Assert.False(new LightOptions(true, false, 0f, 0f).IsDefault);
|
||||
Assert.False(new LightOptions(false, true, 0f, 0f).IsDefault);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void ADitheredFullValueNeverWrapsAroundWhateverTheThreshold()
|
||||
{
|
||||
var options = new LightOptions(false, true, 0f, 0f);
|
||||
var nearOne = 0;
|
||||
for (var y = 0; y < 2048; y++)
|
||||
{
|
||||
for (var x = 0; x < 2048; x++)
|
||||
{
|
||||
if (LightTransform.DitherThreshold(x, y) < 0.99999f)
|
||||
continue;
|
||||
|
||||
nearOne++;
|
||||
var (_, _, red, alpha) = LightTransform.ToBytes(1f, 1f, 1f, 1f, 1f, options, x, y);
|
||||
Assert.Equal(((byte)255, (byte)255), (red, alpha));
|
||||
}
|
||||
}
|
||||
|
||||
Assert.True(nearOne > 10, $"{nearOne}");
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void EncodeStaysWithinAMillionthOfTheStandardCurve()
|
||||
{
|
||||
var first = BitConverter.SingleToInt32Bits(0.0031308f) - 1000;
|
||||
var last = BitConverter.SingleToInt32Bits(1f);
|
||||
var worst = 0d;
|
||||
for (var bits = first; bits <= last; bits += 331)
|
||||
{
|
||||
var linear = BitConverter.Int32BitsToSingle(bits);
|
||||
var expected = ReferenceEncode(linear);
|
||||
|
||||
worst = Math.Max(worst, Math.Abs(LightTransform.Encode(linear) - expected) / expected);
|
||||
}
|
||||
|
||||
Assert.InRange(worst, 0d, 1e-6);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void EncodeIsExactAtTheJointsOfItsTable()
|
||||
{
|
||||
for (var exponent = -8; exponent < 0; exponent++)
|
||||
{
|
||||
for (var step = 0; step < 256; step += 17)
|
||||
{
|
||||
var linear = (float)(Math.Pow(2d, exponent) * (1d + step / 256d));
|
||||
if (linear <= 0.0031308f)
|
||||
continue;
|
||||
|
||||
Assert.Equal(ReferenceEncode(linear), LightTransform.Encode(linear), 1e-6);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void EncodeHandlesTheValuesOutsideTheCurve()
|
||||
{
|
||||
Assert.True(float.IsNaN(LightTransform.Encode(float.NaN)));
|
||||
Assert.Equal(1f, LightTransform.Encode(float.PositiveInfinity));
|
||||
Assert.Equal(1f, LightTransform.Encode(1.0000001f));
|
||||
Assert.Equal(-12.92f, LightTransform.Encode(-1f));
|
||||
Assert.Equal(0.0031308f * 12.92f, LightTransform.Encode(0.0031308f));
|
||||
Assert.Equal(ReferenceEncode(0.0031309f), LightTransform.Encode(0.0031309f), 1e-6);
|
||||
Assert.Equal(ReferenceEncode(0.99999994f), LightTransform.Encode(0.99999994f), 1e-6);
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[InlineData(false, false, 1f)]
|
||||
[InlineData(true, false, 1f)]
|
||||
[InlineData(true, false, 2.5f)]
|
||||
[InlineData(true, false, 0f)]
|
||||
[InlineData(false, true, 1.7f)]
|
||||
[InlineData(true, true, 1f)]
|
||||
[InlineData(true, true, 400f)]
|
||||
public void TheVectorConversionReturnsTheBytesOfTheScalarOne(bool linear, bool dither, float gain)
|
||||
{
|
||||
float[] specials =
|
||||
[
|
||||
0f, -0f, 0.5f / 255f, 1f, 1.5f, -0.5f, float.NaN, float.PositiveInfinity, float.NegativeInfinity, 1e-30f,
|
||||
0.0031308f, 0.0031309f, 0.9999999f, 0.25f, 0.5f,
|
||||
];
|
||||
var options = new LightOptions(linear, dither, 0f, 0f);
|
||||
var random = new Random(97);
|
||||
float Pick() => random.Next(4) switch
|
||||
{
|
||||
0 => specials[random.Next(specials.Length)],
|
||||
_ => (float)(random.NextDouble() * 1.3),
|
||||
};
|
||||
|
||||
for (var index = 0; index < 150_000; index++)
|
||||
{
|
||||
var alpha = Pick();
|
||||
var scale = random.Next(3) == 0 ? 1f : (float)random.NextDouble();
|
||||
var red = random.Next(3) == 0 ? Pick() : alpha * scale * (float)random.NextDouble();
|
||||
var green = random.Next(3) == 0 ? Pick() : alpha * scale * (float)random.NextDouble();
|
||||
var blue = random.Next(3) == 0 ? Pick() : alpha * scale * (float)random.NextDouble();
|
||||
var x = random.Next(-100, 5000);
|
||||
var y = random.Next(-100, 5000);
|
||||
|
||||
var expected = LightTransform.ToBytes(red, green, blue, alpha, gain, options, x, y);
|
||||
var packed = LightTransform.ToPacked(Vector128.Create(red, green, blue, alpha), gain, options, x, y);
|
||||
|
||||
Assert.Equal(
|
||||
(expected.Blue, expected.Green, expected.Red, expected.Alpha),
|
||||
((byte)packed, (byte)(packed >> 8), (byte)(packed >> 16), (byte)(packed >> 24)));
|
||||
}
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[InlineData(false, true, 1f)]
|
||||
[InlineData(false, true, 3f)]
|
||||
[InlineData(true, true, 1f)]
|
||||
[InlineData(true, true, 2f)]
|
||||
[InlineData(true, false, 1f)]
|
||||
public void AColorNeverExceedsItsOpacityEvenWhenDithered(bool linear, bool dither, float gain)
|
||||
{
|
||||
var options = new LightOptions(linear, dither, 0f, 0f);
|
||||
var random = new Random(31);
|
||||
for (var index = 0; index < 100_000; index++)
|
||||
{
|
||||
var alpha = (float)random.NextDouble();
|
||||
var red = random.Next(3) == 0 ? alpha : alpha * (float)random.NextDouble();
|
||||
var green = random.Next(3) == 0 ? alpha : alpha * (float)random.NextDouble();
|
||||
var blue = random.Next(3) == 0 ? alpha : alpha * (float)random.NextDouble();
|
||||
var x = random.Next(0, 4000);
|
||||
var y = random.Next(0, 4000);
|
||||
|
||||
var expected = LightTransform.ToBytes(red, green, blue, alpha, gain, options, x, y);
|
||||
|
||||
Assert.InRange(expected.Red, 0, expected.Alpha);
|
||||
Assert.InRange(expected.Green, 0, expected.Alpha);
|
||||
Assert.InRange(expected.Blue, 0, expected.Alpha);
|
||||
}
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void ATranslucentWhiteStaysPremultipliedWhenDithered()
|
||||
{
|
||||
var options = new LightOptions(false, true, 0f, 0f);
|
||||
for (var y = 0; y < 100; y++)
|
||||
{
|
||||
for (var x = 0; x < 100; x++)
|
||||
{
|
||||
var (blue, green, red, alpha) = LightTransform.ToBytes(127.5f / 255f, 127.5f / 255f, 127.5f / 255f, 127.5f / 255f, 1f, options, x, y);
|
||||
|
||||
Assert.InRange(red, 0, alpha);
|
||||
Assert.InRange(green, 0, alpha);
|
||||
Assert.InRange(blue, 0, alpha);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[InlineData(0)]
|
||||
[InlineData(1)]
|
||||
[InlineData(2)]
|
||||
public void HighlightsFollowTheBrightestChannelWhicheverItIs(int brightest)
|
||||
{
|
||||
var options = new LightOptions(true, false, 0.5f, 10f);
|
||||
byte[] channels = [40, 40, 40];
|
||||
channels[brightest] = 230;
|
||||
|
||||
var raised = LightTransform.FromBytes(channels[0], channels[1], channels[2], 255, options);
|
||||
|
||||
var excess = (230 / 255d - 0.5) / 0.5;
|
||||
Assert.Equal(1d + 9d * excess * excess, raised.Alpha, 1e-4);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void HighlightsLeaveADarkPixelFarBelowTheThresholdAlone()
|
||||
{
|
||||
var options = new LightOptions(true, false, 0.9f, 100f);
|
||||
|
||||
var raised = LightTransform.FromBytes(30, 30, 30, 255, options);
|
||||
|
||||
Assert.Equal(LightTransform.FromBytes(30, 30, 30, 255, Linear), raised);
|
||||
Assert.Equal(1f, raised.Alpha);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void TheDitherThresholdFollowsTheDocumentedHash()
|
||||
{
|
||||
static float Documented(int x, int y)
|
||||
{
|
||||
var h = unchecked((uint)x * 0x9E3779B1u ^ (uint)y * 0x85EBCA77u);
|
||||
h ^= h >> 16;
|
||||
h = unchecked(h * 0x7FEB352Du);
|
||||
h ^= h >> 15;
|
||||
h = unchecked(h * 0x846CA68Bu);
|
||||
h ^= h >> 16;
|
||||
return (h >> 8) / 16777216f;
|
||||
}
|
||||
|
||||
Assert.Equal(0f, LightTransform.DitherThreshold(0, 0));
|
||||
for (var y = -40; y < 300; y += 7)
|
||||
{
|
||||
for (var x = -40; x < 300; x += 3)
|
||||
Assert.Equal(Documented(x, y), LightTransform.DitherThreshold(x, y));
|
||||
}
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void AThresholdOfOneIsValidButRaisesNothing()
|
||||
{
|
||||
var options = new LightOptions(true, false, 1f, 5f);
|
||||
|
||||
options.Validate();
|
||||
|
||||
Assert.False(options.Highlights);
|
||||
new LightOptions(true, false, 0f, 5f).Validate();
|
||||
new LightOptions(true, false, 0.5f, LightOptions.MaximumBoost).Validate();
|
||||
}
|
||||
}
|
||||
@@ -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,657 @@
|
||||
using System.Runtime.CompilerServices;
|
||||
using System.Runtime.ExceptionServices;
|
||||
using System.Runtime.InteropServices;
|
||||
using System.Runtime.Intrinsics;
|
||||
using ComputeWeave;
|
||||
|
||||
namespace SpectralConvolution;
|
||||
|
||||
internal sealed class CpuTileConvolver : IDisposable
|
||||
{
|
||||
public const long WorkingBudgetBytes = 64L << 20;
|
||||
public const int StoredChunkPixels = 16384;
|
||||
const int Channels = 4;
|
||||
|
||||
static readonly float[] Units = BuildUnits();
|
||||
|
||||
readonly Worker[] workers;
|
||||
readonly Thread[] threads;
|
||||
readonly SemaphoreSlim start = new(0);
|
||||
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;
|
||||
LightOptions light;
|
||||
float[]? convolved;
|
||||
float[]? stored;
|
||||
int storedPixels;
|
||||
int storedChunks;
|
||||
int storedWidth;
|
||||
int storedOriginX;
|
||||
int storedOriginY;
|
||||
|
||||
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,
|
||||
LightOptions lightOptions = default)
|
||||
{
|
||||
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));
|
||||
lightOptions.Validate();
|
||||
|
||||
ObjectDisposedException.ThrowIf(disposed, this);
|
||||
EnsureReversal(tilePlan.Size, tilePlan.Log2Size);
|
||||
EnsureWorkingSize(tilePlan.Size);
|
||||
var active = Math.Min(ActiveThreads(workers.Length, tilePlan.Size), tilePlan.TileCount);
|
||||
|
||||
source = sourcePixels;
|
||||
sourceX = sourceLeft;
|
||||
sourceY = sourceTop;
|
||||
sourceWidth = sourceColumns;
|
||||
sourceHeight = sourceRows;
|
||||
spectrum = kernelSpectrum;
|
||||
plan = tilePlan;
|
||||
output = outputPixels;
|
||||
gain = outputGain;
|
||||
light = lightOptions;
|
||||
convolved = convolvedValues;
|
||||
try
|
||||
{
|
||||
Dispatch(active);
|
||||
}
|
||||
finally
|
||||
{
|
||||
source = [];
|
||||
spectrum = null;
|
||||
output = [];
|
||||
convolved = null;
|
||||
}
|
||||
}
|
||||
|
||||
public void RenderStored(
|
||||
float[] storedValues,
|
||||
int pixels,
|
||||
float outputGain,
|
||||
byte[] outputPixels,
|
||||
LightOptions lightOptions = default,
|
||||
int regionWidth = 0,
|
||||
int regionX = 0,
|
||||
int regionY = 0)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(storedValues);
|
||||
ArgumentNullException.ThrowIfNull(outputPixels);
|
||||
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));
|
||||
lightOptions.Validate();
|
||||
if (lightOptions.Dither && pixels > 0)
|
||||
ArgumentOutOfRangeException.ThrowIfNegativeOrZero(regionWidth);
|
||||
|
||||
ObjectDisposedException.ThrowIf(disposed, this);
|
||||
var chunks = (pixels + StoredChunkPixels - 1) / StoredChunkPixels;
|
||||
if (chunks == 0)
|
||||
return;
|
||||
|
||||
stored = storedValues;
|
||||
storedPixels = pixels;
|
||||
storedChunks = chunks;
|
||||
storedWidth = regionWidth;
|
||||
storedOriginX = regionX;
|
||||
storedOriginY = regionY;
|
||||
output = outputPixels;
|
||||
gain = outputGain;
|
||||
light = lightOptions;
|
||||
try
|
||||
{
|
||||
Dispatch(Math.Min(workers.Length, chunks));
|
||||
}
|
||||
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);
|
||||
}
|
||||
|
||||
static float[] BuildUnits()
|
||||
{
|
||||
var units = new float[256];
|
||||
for (var level = 0; level < units.Length; level++)
|
||||
units[level] = level / 255f;
|
||||
return units;
|
||||
}
|
||||
|
||||
public static byte ToUnorm(float value)
|
||||
{
|
||||
if (float.IsNaN(value))
|
||||
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(row, order, sourceRow, left, first, last))
|
||||
{
|
||||
row.Clear();
|
||||
continue;
|
||||
}
|
||||
|
||||
lit = true;
|
||||
Butterflies(row, log2, twiddles, 1f);
|
||||
}
|
||||
|
||||
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;
|
||||
}
|
||||
|
||||
ref var workStart = ref MemoryMarshal.GetReference(work);
|
||||
ref var lineStart = ref MemoryMarshal.GetReference(line);
|
||||
ref var spareStart = ref MemoryMarshal.GetReference(spare);
|
||||
for (var column = 0; column < size; column++)
|
||||
{
|
||||
for (var y = 0; y < size; y++)
|
||||
Copy(ref workStart, (y * size + column) * Channels, ref lineStart, order[y] * Channels);
|
||||
|
||||
Butterflies(line, log2, twiddles, 1f);
|
||||
Multiply(line, spare, order, values.Slice(column * size, size));
|
||||
Butterflies(spare, log2, twiddles, -1f);
|
||||
for (var y = 0; y < size; y++)
|
||||
Copy(ref spareStart, y * Channels, ref workStart, (y * size + column) * Channels);
|
||||
}
|
||||
|
||||
var scale = 1f / (size * size);
|
||||
var light = this.light;
|
||||
var outputOrigin = plan.RegionX + regionLeft;
|
||||
for (var y = radius; y < radius + validHeight; y++)
|
||||
{
|
||||
var row = work.Slice(y * rowLength, rowLength);
|
||||
ref var rowStart = ref MemoryMarshal.GetReference(row);
|
||||
for (var x = 0; x < size; x++)
|
||||
Copy(ref rowStart, x * Channels, ref lineStart, order[x] * Channels);
|
||||
|
||||
Butterflies(line, log2, twiddles, -1f);
|
||||
var outputRow = regionTop + y - radius;
|
||||
var index = (outputRow * plan.RegionWidth + regionLeft) * Channels;
|
||||
var pixels = line.Slice(radius * Channels, validWidth * Channels);
|
||||
var bytes = output.AsSpan(index, validWidth * Channels);
|
||||
var store = convolved is { } convolvedValues ? convolvedValues.AsSpan(index, validWidth * Channels) : default;
|
||||
if (light.IsDefault)
|
||||
Emit(pixels, scale, gain, bytes, store);
|
||||
else
|
||||
Emit(pixels, scale, gain, in light, outputOrigin, plan.RegionY + outputRow, bytes, store);
|
||||
}
|
||||
}
|
||||
|
||||
static void Emit(ReadOnlySpan<float> pixels, float scale, float gain, Span<byte> bytes, Span<float> store)
|
||||
{
|
||||
var count = pixels.Length / Channels;
|
||||
if (bytes.Length < count * Channels || (!store.IsEmpty && store.Length < count * Channels))
|
||||
throw new ArgumentException(null, nameof(bytes));
|
||||
|
||||
ref var from = ref MemoryMarshal.GetReference(pixels);
|
||||
ref var to = ref MemoryMarshal.GetReference(bytes);
|
||||
ref var kept = ref MemoryMarshal.GetReference(store);
|
||||
var scaleVector = Vector128.Create(scale);
|
||||
var gainVector = Vector128.Create(gain);
|
||||
var keep = !store.IsEmpty;
|
||||
for (var pixel = 0; pixel < count; pixel++)
|
||||
{
|
||||
var value = Vector128.LoadUnsafe(ref from, (nuint)(pixel * Channels)) * scaleVector;
|
||||
if (keep)
|
||||
value.StoreUnsafe(ref kept, (nuint)(pixel * Channels));
|
||||
Unsafe.WriteUnaligned(ref Unsafe.Add(ref to, pixel * Channels), PackBgra(value * gainVector));
|
||||
}
|
||||
}
|
||||
|
||||
static void Emit(ReadOnlySpan<float> pixels, float scale, float gain, in LightOptions light, int x, int y, Span<byte> bytes, Span<float> store)
|
||||
{
|
||||
var count = pixels.Length / Channels;
|
||||
if (bytes.Length < count * Channels || (!store.IsEmpty && store.Length < count * Channels))
|
||||
throw new ArgumentException(null, nameof(bytes));
|
||||
|
||||
ref var from = ref MemoryMarshal.GetReference(pixels);
|
||||
ref var to = ref MemoryMarshal.GetReference(bytes);
|
||||
ref var kept = ref MemoryMarshal.GetReference(store);
|
||||
var scaleVector = Vector128.Create(scale);
|
||||
var keep = !store.IsEmpty;
|
||||
for (var pixel = 0; pixel < count; pixel++)
|
||||
{
|
||||
var value = Vector128.LoadUnsafe(ref from, (nuint)(pixel * Channels)) * scaleVector;
|
||||
if (keep)
|
||||
value.StoreUnsafe(ref kept, (nuint)(pixel * Channels));
|
||||
Unsafe.WriteUnaligned(ref Unsafe.Add(ref to, pixel * Channels), LightTransform.ToPacked(value, gain, in light, x + pixel, y));
|
||||
}
|
||||
}
|
||||
|
||||
[MethodImpl(MethodImplOptions.AggressiveInlining)]
|
||||
static uint PackBgra(Vector128<float> rgba)
|
||||
{
|
||||
var ordered = Vector128.Shuffle(rgba, Vector128.Create(2, 1, 0, 3));
|
||||
ordered = Vector128.ConditionalSelect(Vector128.Equals(ordered, ordered), ordered, Vector128<float>.Zero);
|
||||
var clamped = Vector128.Min(Vector128.Max(ordered, Vector128<float>.Zero), Vector128<float>.One);
|
||||
var levels = Vector128.ConvertToInt32(clamped * Vector128.Create(255f) + Vector128.Create(0.5f)).AsUInt32();
|
||||
var words = Vector128.Narrow(levels, levels);
|
||||
return Vector128.Narrow(words, words).AsUInt32().ToScalar();
|
||||
}
|
||||
|
||||
[MethodImpl(MethodImplOptions.AggressiveInlining)]
|
||||
static void Copy(ref float from, int fromIndex, ref float to, int toIndex)
|
||||
=> Vector128.LoadUnsafe(ref from, (nuint)fromIndex).StoreUnsafe(ref to, (nuint)toIndex);
|
||||
|
||||
static void Multiply(ReadOnlySpan<float> line, Span<float> spare, ReadOnlySpan<int> order, ReadOnlySpan<Float2> weights)
|
||||
{
|
||||
var size = weights.Length;
|
||||
if (line.Length < size * Channels || spare.Length < size * Channels || order.Length < size)
|
||||
throw new ArgumentException(null, nameof(weights));
|
||||
|
||||
ref var from = ref MemoryMarshal.GetReference(line);
|
||||
ref var to = ref MemoryMarshal.GetReference(spare);
|
||||
for (var frequency = 0; frequency < size; frequency++)
|
||||
{
|
||||
var weight = weights[frequency];
|
||||
var value = Vector128.LoadUnsafe(ref from, (nuint)(frequency * Channels));
|
||||
var product = value * Vector128.Create(weight.X)
|
||||
+ Vector128.Shuffle(value, Vector128.Create(1, 0, 3, 2)) * Vector128.Create(-weight.Y, weight.Y, -weight.Y, weight.Y);
|
||||
product.StoreUnsafe(ref to, (nuint)(order[frequency] * Channels));
|
||||
}
|
||||
}
|
||||
|
||||
void RenderChunk(float[] values, int chunk)
|
||||
{
|
||||
var first = chunk * StoredChunkPixels;
|
||||
var count = Math.Min(first + StoredChunkPixels, storedPixels) - first;
|
||||
var light = this.light;
|
||||
var pixels = values.AsSpan(first * Channels, count * Channels);
|
||||
var bytes = output.AsSpan(first * Channels, count * Channels);
|
||||
if (light.IsDefault)
|
||||
{
|
||||
Emit(pixels, 1f, gain, bytes, default);
|
||||
return;
|
||||
}
|
||||
|
||||
var column = storedWidth > 0 ? first % storedWidth : 0;
|
||||
var row = storedWidth > 0 ? first / storedWidth : 0;
|
||||
for (var done = 0; done < count;)
|
||||
{
|
||||
var run = storedWidth > 0 ? Math.Min(count - done, storedWidth - column) : count - done;
|
||||
Emit(pixels.Slice(done * Channels, run * Channels), 1f, gain, in light, storedOriginX + column, storedOriginY + row,
|
||||
bytes.Slice(done * Channels, run * Channels), default);
|
||||
done += run;
|
||||
column = 0;
|
||||
row++;
|
||||
}
|
||||
}
|
||||
|
||||
bool LoadRow(Span<float> row, ReadOnlySpan<int> order, int sourceRow, int left, int first, int last)
|
||||
{
|
||||
row.Clear();
|
||||
var lit = false;
|
||||
var pixels = source.AsSpan(sourceRow * sourceWidth * Channels, sourceWidth * Channels);
|
||||
var light = this.light;
|
||||
var units = Units;
|
||||
for (var x = first; x < last; x++)
|
||||
{
|
||||
var offset = (left + x - sourceX) * Channels;
|
||||
var blue = pixels[offset];
|
||||
var green = pixels[offset + 1];
|
||||
var red = pixels[offset + 2];
|
||||
var alpha = pixels[offset + 3];
|
||||
if ((blue | green | red | alpha) == 0)
|
||||
continue;
|
||||
|
||||
var target = order[x] * Channels;
|
||||
if (light.Linear)
|
||||
{
|
||||
var (linearRed, linearGreen, linearBlue, linearAlpha) = LightTransform.FromBytes(red, green, blue, alpha, in light);
|
||||
row[target] = linearRed;
|
||||
row[target + 1] = linearGreen;
|
||||
row[target + 2] = linearBlue;
|
||||
row[target + 3] = linearAlpha;
|
||||
}
|
||||
else
|
||||
{
|
||||
row[target] = units[red];
|
||||
row[target + 1] = units[green];
|
||||
row[target + 2] = units[blue];
|
||||
row[target + 3] = units[alpha];
|
||||
}
|
||||
lit = true;
|
||||
}
|
||||
|
||||
return lit;
|
||||
}
|
||||
|
||||
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();
|
||||
}
|
||||
}
|
||||
|
||||
internal static void Butterflies(Span<float> line, int log2, ReadOnlySpan<Float2> twiddles, float direction, bool allowWide = true)
|
||||
{
|
||||
var size = 1 << log2;
|
||||
if (line.Length < size * Channels || twiddles.Length < size / 2)
|
||||
throw new ArgumentException(null, nameof(line));
|
||||
|
||||
ref var data = ref MemoryMarshal.GetReference(line);
|
||||
ref var table = ref MemoryMarshal.GetReference(twiddles);
|
||||
for (var stage = 0; stage < log2; stage++)
|
||||
{
|
||||
var half = 1 << stage;
|
||||
var shift = log2 - 1 - stage;
|
||||
var distance = (nuint)(half * Channels);
|
||||
if (allowWide && Vector256.IsHardwareAccelerated && half >= 2)
|
||||
{
|
||||
// Two neighboring positions of a block share one load. Every butterfly is the same
|
||||
// arithmetic as the scalar form, so the results match it bit for bit.
|
||||
for (var position = 0; position < half; position += 2)
|
||||
{
|
||||
var near = Unsafe.Add(ref table, position << shift);
|
||||
var far = Unsafe.Add(ref table, (position + 1) << shift);
|
||||
var nearImaginary = near.Y * direction;
|
||||
var farImaginary = far.Y * direction;
|
||||
var real = Vector256.Create(near.X, near.X, near.X, near.X, far.X, far.X, far.X, far.X);
|
||||
var imaginary = Vector256.Create(-nearImaginary, nearImaginary, -nearImaginary, nearImaginary, -farImaginary, farImaginary, -farImaginary, farImaginary);
|
||||
for (var block = 0; block < size; block += half * 2)
|
||||
{
|
||||
var even = (nuint)((block + position) * Channels);
|
||||
var evenValue = Vector256.LoadUnsafe(ref data, even);
|
||||
var oddValue = Vector256.LoadUnsafe(ref data, even + distance);
|
||||
var product = oddValue * real + Vector256.Shuffle(oddValue, Vector256.Create(1, 0, 3, 2, 5, 4, 7, 6)) * imaginary;
|
||||
(evenValue + product).StoreUnsafe(ref data, even);
|
||||
(evenValue - product).StoreUnsafe(ref data, even + distance);
|
||||
}
|
||||
}
|
||||
|
||||
continue;
|
||||
}
|
||||
|
||||
for (var position = 0; position < half; position++)
|
||||
{
|
||||
var twiddle = Unsafe.Add(ref table, position << shift);
|
||||
var imaginaryPart = twiddle.Y * direction;
|
||||
var real = Vector128.Create(twiddle.X);
|
||||
var imaginary = Vector128.Create(-imaginaryPart, imaginaryPart, -imaginaryPart, imaginaryPart);
|
||||
for (var block = 0; block < size; block += half * 2)
|
||||
{
|
||||
var even = (nuint)((block + position) * Channels);
|
||||
var evenValue = Vector128.LoadUnsafe(ref data, even);
|
||||
var oddValue = Vector128.LoadUnsafe(ref data, even + distance);
|
||||
var product = oddValue * real + Vector128.Shuffle(oddValue, Vector128.Create(1, 0, 3, 2)) * imaginary;
|
||||
(evenValue + product).StoreUnsafe(ref data, even);
|
||||
(evenValue - product).StoreUnsafe(ref data, even + distance);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
internal static void ButterfliesScalar(Span<float> line, int log2, ReadOnlySpan<Float2> twiddles, float direction)
|
||||
{
|
||||
var pairs = 1 << (log2 - 1);
|
||||
for (var stage = 0; stage < log2; stage++)
|
||||
{
|
||||
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,116 @@
|
||||
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<uint> neighborhood, ReadOnlySpan<double> kernel, in LightOptions light, Span<double> result)
|
||||
{
|
||||
if (!light.Linear)
|
||||
{
|
||||
Evaluate(neighborhood, kernel, result);
|
||||
return;
|
||||
}
|
||||
|
||||
if (neighborhood.Length != kernel.Length)
|
||||
throw new ArgumentException(null, nameof(neighborhood));
|
||||
if (result.Length < Channels)
|
||||
throw new ArgumentException(null, nameof(result));
|
||||
|
||||
var red = 0d;
|
||||
var green = 0d;
|
||||
var blue = 0d;
|
||||
var alpha = 0d;
|
||||
for (var index = 0; index < kernel.Length; index++)
|
||||
{
|
||||
var packed = neighborhood[index];
|
||||
var weight = kernel[index];
|
||||
var (linearRed, linearGreen, linearBlue, linearAlpha) = LightTransform.FromBytes(
|
||||
(byte)(packed & 255u), (byte)(packed >> 8 & 255u), (byte)(packed >> 16 & 255u), (byte)(packed >> 24), in light);
|
||||
red += linearRed * weight;
|
||||
green += linearGreen * weight;
|
||||
blue += linearBlue * weight;
|
||||
alpha += linearAlpha * weight;
|
||||
}
|
||||
|
||||
result[0] = red;
|
||||
result[1] = green;
|
||||
result[2] = blue;
|
||||
result[3] = alpha;
|
||||
}
|
||||
|
||||
public static void Evaluate(ReadOnlySpan<byte> bgra, int width, int height, ReadOnlySpan<double> kernel, int radius, int x, int y, Span<double> result)
|
||||
{
|
||||
var kernelSize = radius * 2 + 1;
|
||||
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);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,219 @@
|
||||
using System.Buffers;
|
||||
using System.Collections.Concurrent;
|
||||
using System.Numerics;
|
||||
using System.Runtime.CompilerServices;
|
||||
using System.Runtime.InteropServices;
|
||||
|
||||
namespace SpectralConvolution;
|
||||
|
||||
internal static class FastFourierTransform
|
||||
{
|
||||
static readonly ConcurrentDictionary<long, Twiddles> TwiddleCache = new();
|
||||
|
||||
public static void Forward(Span<double> real, Span<double> imaginary) => Transform(real, imaginary, false);
|
||||
|
||||
public static void Inverse(Span<double> real, Span<double> imaginary) => Transform(real, imaginary, true);
|
||||
|
||||
public static void Forward2D(double[] real, double[] imaginary, int width, int height) => Transform2D(real, imaginary, width, height, false);
|
||||
|
||||
public static void Inverse2D(double[] real, double[] imaginary, int width, int height) => Transform2D(real, imaginary, width, height, true);
|
||||
|
||||
static void Transform(Span<double> real, Span<double> imaginary, bool inverse)
|
||||
{
|
||||
var count = real.Length;
|
||||
if (count == 0 || imaginary.Length != count || !BitOperations.IsPow2((uint)count))
|
||||
throw new ArgumentException(nameof(real));
|
||||
|
||||
var twiddles = GetTwiddles(count, inverse);
|
||||
Reorder(real, imaginary, twiddles.Swaps);
|
||||
Butterflies(real, imaginary, twiddles);
|
||||
if (inverse)
|
||||
Scale(real, imaginary, 1d / count);
|
||||
}
|
||||
|
||||
static void Transform2D(double[] real, double[] imaginary, int width, int height, bool inverse)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(real);
|
||||
ArgumentNullException.ThrowIfNull(imaginary);
|
||||
var area = width * height;
|
||||
if (real.Length < area || imaginary.Length < area)
|
||||
throw new ArgumentException(nameof(real));
|
||||
if (!BitOperations.IsPow2((uint)width) || !BitOperations.IsPow2((uint)height))
|
||||
throw new ArgumentException(nameof(width));
|
||||
|
||||
for (var y = 0; y < height; y++)
|
||||
{
|
||||
var offset = y * width;
|
||||
Transform(real.AsSpan(offset, width), imaginary.AsSpan(offset, width), inverse);
|
||||
}
|
||||
|
||||
var columnReal = ArrayPool<double>.Shared.Rent(height);
|
||||
var columnImaginary = ArrayPool<double>.Shared.Rent(height);
|
||||
try
|
||||
{
|
||||
var rowReal = real.AsSpan(0, area);
|
||||
var rowImaginary = imaginary.AsSpan(0, area);
|
||||
for (var x = 0; x < width; x++)
|
||||
{
|
||||
for (var y = 0; y < height; y++)
|
||||
{
|
||||
var index = y * width + x;
|
||||
columnReal[y] = rowReal[index];
|
||||
columnImaginary[y] = rowImaginary[index];
|
||||
}
|
||||
Transform(columnReal.AsSpan(0, height), columnImaginary.AsSpan(0, height), inverse);
|
||||
for (var y = 0; y < height; y++)
|
||||
{
|
||||
var index = y * width + x;
|
||||
rowReal[index] = columnReal[y];
|
||||
rowImaginary[index] = columnImaginary[y];
|
||||
}
|
||||
}
|
||||
}
|
||||
finally
|
||||
{
|
||||
ArrayPool<double>.Shared.Return(columnReal);
|
||||
ArrayPool<double>.Shared.Return(columnImaginary);
|
||||
}
|
||||
}
|
||||
|
||||
static void Reorder(Span<double> real, Span<double> imaginary, int[] swaps)
|
||||
{
|
||||
for (var index = 0; index < swaps.Length; index += 2)
|
||||
{
|
||||
var source = swaps[index];
|
||||
var target = swaps[index + 1];
|
||||
(real[source], real[target]) = (real[target], real[source]);
|
||||
(imaginary[source], imaginary[target]) = (imaginary[target], imaginary[source]);
|
||||
}
|
||||
}
|
||||
|
||||
static void Butterflies(Span<double> real, Span<double> imaginary, Twiddles twiddles)
|
||||
{
|
||||
var count = real.Length;
|
||||
ref var realBase = ref MemoryMarshal.GetReference(real);
|
||||
ref var imaginaryBase = ref MemoryMarshal.GetReference(imaginary);
|
||||
var width = Vector<double>.Count;
|
||||
|
||||
for (int length = 2, stage = 0; length <= count; length <<= 1, stage++)
|
||||
{
|
||||
var half = length >> 1;
|
||||
var cos = twiddles.Cos[stage];
|
||||
var sin = twiddles.Sin[stage];
|
||||
ref var cosBase = ref MemoryMarshal.GetArrayDataReference(cos);
|
||||
ref var sinBase = ref MemoryMarshal.GetArrayDataReference(sin);
|
||||
var vectorized = Vector.IsHardwareAccelerated && half >= width;
|
||||
|
||||
for (var offset = 0; offset < count; offset += length)
|
||||
{
|
||||
var index = 0;
|
||||
if (vectorized)
|
||||
{
|
||||
for (; index + width <= half; index += width)
|
||||
{
|
||||
var even = offset + index;
|
||||
var odd = even + half;
|
||||
var evenReal = Vector.LoadUnsafe(ref Unsafe.Add(ref realBase, even));
|
||||
var evenImaginary = Vector.LoadUnsafe(ref Unsafe.Add(ref imaginaryBase, even));
|
||||
var oddReal = Vector.LoadUnsafe(ref Unsafe.Add(ref realBase, odd));
|
||||
var oddImaginary = Vector.LoadUnsafe(ref Unsafe.Add(ref imaginaryBase, odd));
|
||||
var weightReal = Vector.LoadUnsafe(ref Unsafe.Add(ref cosBase, index));
|
||||
var weightImaginary = Vector.LoadUnsafe(ref Unsafe.Add(ref sinBase, index));
|
||||
var productReal = oddReal * weightReal - oddImaginary * weightImaginary;
|
||||
var productImaginary = oddReal * weightImaginary + oddImaginary * weightReal;
|
||||
(evenReal + productReal).StoreUnsafe(ref Unsafe.Add(ref realBase, even));
|
||||
(evenImaginary + productImaginary).StoreUnsafe(ref Unsafe.Add(ref imaginaryBase, even));
|
||||
(evenReal - productReal).StoreUnsafe(ref Unsafe.Add(ref realBase, odd));
|
||||
(evenImaginary - productImaginary).StoreUnsafe(ref Unsafe.Add(ref imaginaryBase, odd));
|
||||
}
|
||||
}
|
||||
for (; index < half; index++)
|
||||
{
|
||||
var even = offset + index;
|
||||
var odd = even + half;
|
||||
var weightReal = Unsafe.Add(ref cosBase, index);
|
||||
var weightImaginary = Unsafe.Add(ref sinBase, index);
|
||||
var oddReal = Unsafe.Add(ref realBase, odd);
|
||||
var oddImaginary = Unsafe.Add(ref imaginaryBase, odd);
|
||||
var productReal = oddReal * weightReal - oddImaginary * weightImaginary;
|
||||
var productImaginary = oddReal * weightImaginary + oddImaginary * weightReal;
|
||||
var evenReal = Unsafe.Add(ref realBase, even);
|
||||
var evenImaginary = Unsafe.Add(ref imaginaryBase, even);
|
||||
Unsafe.Add(ref realBase, even) = evenReal + productReal;
|
||||
Unsafe.Add(ref imaginaryBase, even) = evenImaginary + productImaginary;
|
||||
Unsafe.Add(ref realBase, odd) = evenReal - productReal;
|
||||
Unsafe.Add(ref imaginaryBase, odd) = evenImaginary - productImaginary;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
static void Scale(Span<double> real, Span<double> imaginary, double factor)
|
||||
{
|
||||
var count = real.Length;
|
||||
ref var realBase = ref MemoryMarshal.GetReference(real);
|
||||
ref var imaginaryBase = ref MemoryMarshal.GetReference(imaginary);
|
||||
var index = 0;
|
||||
if (Vector.IsHardwareAccelerated)
|
||||
{
|
||||
var scale = new Vector<double>(factor);
|
||||
var width = Vector<double>.Count;
|
||||
for (; index + width <= count; index += width)
|
||||
{
|
||||
(Vector.LoadUnsafe(ref Unsafe.Add(ref realBase, index)) * scale).StoreUnsafe(ref Unsafe.Add(ref realBase, index));
|
||||
(Vector.LoadUnsafe(ref Unsafe.Add(ref imaginaryBase, index)) * scale).StoreUnsafe(ref Unsafe.Add(ref imaginaryBase, index));
|
||||
}
|
||||
}
|
||||
for (; index < count; index++)
|
||||
{
|
||||
Unsafe.Add(ref realBase, index) *= factor;
|
||||
Unsafe.Add(ref imaginaryBase, index) *= factor;
|
||||
}
|
||||
}
|
||||
|
||||
static Twiddles GetTwiddles(int count, bool inverse) =>
|
||||
TwiddleCache.GetOrAdd(((long)count << 1) | (inverse ? 1L : 0L), static key => new Twiddles((int)(key >> 1), (key & 1L) != 0));
|
||||
|
||||
sealed class Twiddles
|
||||
{
|
||||
public double[][] Cos { get; }
|
||||
public double[][] Sin { get; }
|
||||
public int[] Swaps { get; }
|
||||
|
||||
public Twiddles(int count, bool inverse)
|
||||
{
|
||||
var swaps = new List<int>();
|
||||
for (int source = 1, target = 0; source < count; source++)
|
||||
{
|
||||
var bit = count >> 1;
|
||||
for (; (target & bit) != 0; bit >>= 1)
|
||||
target ^= bit;
|
||||
target ^= bit;
|
||||
if (source < target)
|
||||
{
|
||||
swaps.Add(source);
|
||||
swaps.Add(target);
|
||||
}
|
||||
}
|
||||
Swaps = [.. swaps];
|
||||
var stages = BitOperations.TrailingZeroCount(count);
|
||||
Cos = new double[stages][];
|
||||
Sin = new double[stages][];
|
||||
var sign = inverse ? 1d : -1d;
|
||||
for (int length = 2, stage = 0; stage < stages; length <<= 1, stage++)
|
||||
{
|
||||
var half = length >> 1;
|
||||
var cos = new double[half];
|
||||
var sin = new double[half];
|
||||
for (var index = 0; index < half; index++)
|
||||
{
|
||||
var (sinValue, cosValue) = Math.SinCos(sign * 2d * Math.PI * index / length);
|
||||
cos[index] = cosValue;
|
||||
sin[index] = sinValue;
|
||||
}
|
||||
Cos[stage] = cos;
|
||||
Sin[stage] = sin;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,494 @@
|
||||
using ComputeWeave;
|
||||
|
||||
namespace SpectralConvolution;
|
||||
|
||||
internal static class LightShaderMath
|
||||
{
|
||||
public static float Decode(float encoded)
|
||||
{
|
||||
if (encoded <= 0.04045f)
|
||||
return encoded / 12.92f;
|
||||
if (encoded >= 1f)
|
||||
return 1f;
|
||||
return Hlsl.Pow((encoded + 0.055f) / 1.055f, 2.4f);
|
||||
}
|
||||
|
||||
public static float Encode(float linear)
|
||||
{
|
||||
if (linear <= 0.0031308f)
|
||||
return 12.92f * linear;
|
||||
if (linear >= 1f)
|
||||
return 1f;
|
||||
return 1.055f * Hlsl.Pow(linear, 0.41666666f) - 0.055f;
|
||||
}
|
||||
}
|
||||
|
||||
internal static class LightShaderOutput
|
||||
{
|
||||
public static float DitherThreshold(int x, int y)
|
||||
{
|
||||
var hash = (uint)x * 0x9E3779B1u ^ (uint)y * 0x85EBCA77u;
|
||||
hash ^= hash >> 16;
|
||||
hash *= 0x7FEB352Du;
|
||||
hash ^= hash >> 15;
|
||||
hash *= 0x846CA68Bu;
|
||||
hash ^= hash >> 16;
|
||||
return (hash >> 8) * (1f / 16777216f);
|
||||
}
|
||||
|
||||
public static float Quantize(float value, int dither, float threshold)
|
||||
{
|
||||
if (dither == 0)
|
||||
return Hlsl.Floor(value * 255f + 0.5f);
|
||||
return Hlsl.Min(Hlsl.Floor(value * 255f + threshold), 255f);
|
||||
}
|
||||
|
||||
public static Float4 Convert(Float4 value, float gain, int linear, int dither, int x, int y)
|
||||
{
|
||||
var red = 0f;
|
||||
var green = 0f;
|
||||
var blue = 0f;
|
||||
var alpha = 0f;
|
||||
if (linear != 0)
|
||||
{
|
||||
alpha = Hlsl.Saturate(value.W * gain);
|
||||
if (alpha > 0f)
|
||||
{
|
||||
red = LightShaderMath.Encode(Hlsl.Min(Hlsl.Saturate(value.X * gain), alpha) / alpha) * alpha;
|
||||
green = LightShaderMath.Encode(Hlsl.Min(Hlsl.Saturate(value.Y * gain), alpha) / alpha) * alpha;
|
||||
blue = LightShaderMath.Encode(Hlsl.Min(Hlsl.Saturate(value.Z * gain), alpha) / alpha) * alpha;
|
||||
}
|
||||
}
|
||||
else
|
||||
{
|
||||
red = Hlsl.Saturate(value.X * gain);
|
||||
green = Hlsl.Saturate(value.Y * gain);
|
||||
blue = Hlsl.Saturate(value.Z * gain);
|
||||
alpha = Hlsl.Saturate(value.W * gain);
|
||||
}
|
||||
|
||||
var threshold = 0f;
|
||||
if (dither != 0)
|
||||
threshold = DitherThreshold(x, y);
|
||||
return new Float4(
|
||||
Quantize(red, dither, threshold) / 255f,
|
||||
Quantize(green, dither, threshold) / 255f,
|
||||
Quantize(blue, dither, threshold) / 255f,
|
||||
Quantize(alpha, dither, threshold) / 255f);
|
||||
}
|
||||
}
|
||||
|
||||
[ThreadGroupSize(DefaultThreadGroupSizes.XY)]
|
||||
[GeneratedComputeShaderDescriptor]
|
||||
[CompileOptions(CompileOptions.Default | CompileOptions.IeeeStrictness)]
|
||||
internal readonly partial struct StoredRenderLightShader(
|
||||
ReadWriteBuffer<Float4> store,
|
||||
ReadWriteTexture2D<Bgra32, Float4> output,
|
||||
int width,
|
||||
int height,
|
||||
float gain,
|
||||
int linear,
|
||||
int dither,
|
||||
int originX,
|
||||
int originY) : IComputeShader
|
||||
{
|
||||
private readonly ReadWriteBuffer<Float4> store = store;
|
||||
private readonly ReadWriteTexture2D<Bgra32, Float4> output = output;
|
||||
private readonly int width = width;
|
||||
private readonly int height = height;
|
||||
private readonly float gain = gain;
|
||||
private readonly int linear = linear;
|
||||
private readonly int dither = dither;
|
||||
private readonly int originX = originX;
|
||||
private readonly int originY = originY;
|
||||
|
||||
public void Execute()
|
||||
{
|
||||
if (ThreadIds.X >= width || ThreadIds.Y >= height)
|
||||
return;
|
||||
output[ThreadIds.XY] = LightShaderOutput.Convert(
|
||||
store[ThreadIds.Y * width + ThreadIds.X], gain, linear, dither, originX + ThreadIds.X, originY + ThreadIds.Y);
|
||||
}
|
||||
}
|
||||
|
||||
[ThreadGroupSize(256, 1, 1)]
|
||||
[GeneratedComputeShaderDescriptor]
|
||||
[CompileOptions(CompileOptions.Default | CompileOptions.IeeeStrictness)]
|
||||
internal readonly partial struct ForwardRowLightShader(
|
||||
ReadWriteTexture2D<Bgra32, Float4> source,
|
||||
ReadWriteBuffer<Float4> tiles,
|
||||
ReadOnlyBuffer<Float2> twiddles,
|
||||
ReadWriteBuffer<uint> report,
|
||||
int log2Size,
|
||||
int radius,
|
||||
int validSize,
|
||||
int tilesX,
|
||||
int batchStart,
|
||||
int regionX,
|
||||
int regionY,
|
||||
int regionWidth,
|
||||
int regionHeight,
|
||||
int sourceX,
|
||||
int sourceY,
|
||||
int sourceWidth,
|
||||
int sourceHeight,
|
||||
int statisticsOffset,
|
||||
int groupStart,
|
||||
int linear,
|
||||
int highlights,
|
||||
float threshold,
|
||||
float boost) : IComputeShader
|
||||
{
|
||||
private readonly ReadWriteTexture2D<Bgra32, Float4> source = source;
|
||||
private readonly ReadWriteBuffer<Float4> tiles = tiles;
|
||||
private readonly ReadOnlyBuffer<Float2> twiddles = twiddles;
|
||||
private readonly ReadWriteBuffer<uint> report = report;
|
||||
private readonly int log2Size = log2Size;
|
||||
private readonly int radius = radius;
|
||||
private readonly int validSize = validSize;
|
||||
private readonly int tilesX = tilesX;
|
||||
private readonly int batchStart = batchStart;
|
||||
private readonly int regionX = regionX;
|
||||
private readonly int regionY = regionY;
|
||||
private readonly int regionWidth = regionWidth;
|
||||
private readonly int regionHeight = regionHeight;
|
||||
private readonly int sourceX = sourceX;
|
||||
private readonly int sourceY = sourceY;
|
||||
private readonly int sourceWidth = sourceWidth;
|
||||
private readonly int sourceHeight = sourceHeight;
|
||||
private readonly int statisticsOffset = statisticsOffset;
|
||||
private readonly int groupStart = groupStart;
|
||||
private readonly int linear = linear;
|
||||
private readonly int highlights = highlights;
|
||||
private readonly float threshold = threshold;
|
||||
private readonly float boost = boost;
|
||||
|
||||
[GroupShared(512)]
|
||||
private static readonly Float4[] row = null!;
|
||||
|
||||
[GroupShared(256)]
|
||||
private static readonly Float4[] partialSums = null!;
|
||||
|
||||
[GroupShared(256)]
|
||||
private static readonly Float2[] partialSquares = null!;
|
||||
|
||||
public void Execute()
|
||||
{
|
||||
var local = GroupIds.X;
|
||||
var groupBase = (ThreadIds.X - local) * 2;
|
||||
var size = (int)(1u << log2Size);
|
||||
var mask = size - 1;
|
||||
var shift = 32 - log2Size;
|
||||
|
||||
// A group of 512 elements never lies in two tiles, so one division serves the whole group.
|
||||
var tileIndex = batchStart + (groupBase >> (log2Size * 2));
|
||||
var tileRow = tileIndex / tilesX;
|
||||
var originX = regionX + (tileIndex - tileRow * tilesX) * validSize - radius;
|
||||
var originY = regionY + tileRow * validSize - radius;
|
||||
|
||||
var sums = new Float4(0f, 0f, 0f, 0f);
|
||||
var squares = new Float2(0f, 0f);
|
||||
for (var pair = 0; pair < 2; pair++)
|
||||
{
|
||||
var element = local * 2 + pair;
|
||||
var flat = groupBase + element;
|
||||
var rest = flat & (size * size - 1);
|
||||
var y = rest >> log2Size;
|
||||
var x = rest & mask;
|
||||
var canvasX = originX + x;
|
||||
var canvasY = originY + y;
|
||||
var value = new Float4(0f, 0f, 0f, 0f);
|
||||
var column = canvasX - sourceX;
|
||||
var line = canvasY - sourceY;
|
||||
if (column >= 0 && column < sourceWidth && line >= 0 && line < sourceHeight)
|
||||
{
|
||||
value = Transform(source[new Int2(column, line)]);
|
||||
squares = new Float2(
|
||||
squares.X + (value.X * value.X + value.Y * value.Y),
|
||||
squares.Y + (value.Z * value.Z + value.W * value.W));
|
||||
if (x >= radius && x < size - radius && y >= radius && y < size - radius
|
||||
&& canvasX < regionX + regionWidth && canvasY < regionY + regionHeight)
|
||||
sums = sums + value;
|
||||
}
|
||||
|
||||
var reversed = (int)(Hlsl.ReverseBits((uint)x) >> shift);
|
||||
row[((element >> log2Size) << log2Size) + reversed] = value;
|
||||
}
|
||||
|
||||
partialSums[local] = sums;
|
||||
partialSquares[local] = squares;
|
||||
Hlsl.GroupMemoryBarrierWithGroupSync();
|
||||
for (var stride = 128; stride > 0; stride >>= 1)
|
||||
{
|
||||
if (local < stride)
|
||||
{
|
||||
partialSums[local] = partialSums[local] + partialSums[local + stride];
|
||||
partialSquares[local] = partialSquares[local] + partialSquares[local + stride];
|
||||
}
|
||||
|
||||
Hlsl.GroupMemoryBarrierWithGroupSync();
|
||||
}
|
||||
|
||||
if (local == 0)
|
||||
{
|
||||
var offset = statisticsOffset + (groupStart + (ThreadIds.X >> 8)) * 6;
|
||||
report[offset] = Hlsl.AsUInt(partialSums[0].X);
|
||||
report[offset + 1] = Hlsl.AsUInt(partialSums[0].Y);
|
||||
report[offset + 2] = Hlsl.AsUInt(partialSums[0].Z);
|
||||
report[offset + 3] = Hlsl.AsUInt(partialSums[0].W);
|
||||
report[offset + 4] = Hlsl.AsUInt(partialSquares[0].X);
|
||||
report[offset + 5] = Hlsl.AsUInt(partialSquares[0].Y);
|
||||
}
|
||||
|
||||
Butterflies(local, 1f);
|
||||
|
||||
tiles[groupBase + local * 2] = row[local * 2];
|
||||
tiles[groupBase + local * 2 + 1] = row[local * 2 + 1];
|
||||
}
|
||||
|
||||
private Float4 Transform(Float4 value)
|
||||
{
|
||||
if (linear == 0)
|
||||
return value;
|
||||
|
||||
var red = (float)(uint)(value.X * 255f + 0.5f);
|
||||
var green = (float)(uint)(value.Y * 255f + 0.5f);
|
||||
var blue = (float)(uint)(value.Z * 255f + 0.5f);
|
||||
var alpha = (float)(uint)(value.W * 255f + 0.5f);
|
||||
if (alpha == 0f)
|
||||
return new Float4(0f, 0f, 0f, 0f);
|
||||
|
||||
var opacity = alpha / 255f;
|
||||
var straightRed = red / 255f;
|
||||
var straightGreen = green / 255f;
|
||||
var straightBlue = blue / 255f;
|
||||
if (alpha != 255f)
|
||||
{
|
||||
straightRed = Hlsl.Min(red / alpha, 1f);
|
||||
straightGreen = Hlsl.Min(green / alpha, 1f);
|
||||
straightBlue = Hlsl.Min(blue / alpha, 1f);
|
||||
}
|
||||
|
||||
var linearRed = LightShaderMath.Decode(straightRed);
|
||||
var linearGreen = LightShaderMath.Decode(straightGreen);
|
||||
var linearBlue = LightShaderMath.Decode(straightBlue);
|
||||
var weight = 1f;
|
||||
if (highlights != 0)
|
||||
{
|
||||
var peak = Hlsl.Max(Hlsl.Max(straightRed, straightGreen), straightBlue);
|
||||
var excess = Hlsl.Min(Hlsl.Max((peak - threshold) / (1f - threshold), 0f), 1f);
|
||||
weight = 1f + (boost - 1f) * excess * excess;
|
||||
}
|
||||
|
||||
var scale = opacity * weight;
|
||||
return new Float4(linearRed * scale, linearGreen * scale, linearBlue * scale, scale);
|
||||
}
|
||||
|
||||
private void Butterflies(int local, float direction)
|
||||
{
|
||||
var halfSize = (int)(1u << (log2Size - 1));
|
||||
var rowBase = (local >> (log2Size - 1)) << log2Size;
|
||||
var pair = local & (halfSize - 1);
|
||||
for (var stage = 0; stage < log2Size; stage++)
|
||||
{
|
||||
var half = (int)(1u << stage);
|
||||
var position = pair & (half - 1);
|
||||
var even = rowBase + ((pair >> stage) << (stage + 1)) + position;
|
||||
var odd = even + half;
|
||||
var twiddle = twiddles[position << (log2Size - 1 - stage)];
|
||||
var real = twiddle.X;
|
||||
var imaginary = twiddle.Y * direction;
|
||||
var evenValue = row[even];
|
||||
var oddValue = row[odd];
|
||||
var product = new Float4(
|
||||
oddValue.X * real - oddValue.Y * imaginary,
|
||||
oddValue.X * imaginary + oddValue.Y * real,
|
||||
oddValue.Z * real - oddValue.W * imaginary,
|
||||
oddValue.Z * imaginary + oddValue.W * real);
|
||||
row[even] = evenValue + product;
|
||||
row[odd] = evenValue - product;
|
||||
Hlsl.GroupMemoryBarrierWithGroupSync();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
[ThreadGroupSize(256, 1, 1)]
|
||||
[GeneratedComputeShaderDescriptor]
|
||||
[CompileOptions(CompileOptions.Default | CompileOptions.IeeeStrictness)]
|
||||
internal readonly partial struct InverseRowLightShader(
|
||||
ReadWriteBuffer<Float4> tiles,
|
||||
ReadOnlyBuffer<Float2> twiddles,
|
||||
ReadWriteTexture2D<Bgra32, Float4> output,
|
||||
ReadWriteBuffer<uint> report,
|
||||
ReadOnlyBuffer<Int2> samples,
|
||||
ReadWriteBuffer<Float4> store,
|
||||
int log2Size,
|
||||
int radius,
|
||||
int validSize,
|
||||
int tilesX,
|
||||
int batchStart,
|
||||
int regionX,
|
||||
int regionY,
|
||||
int regionWidth,
|
||||
int regionHeight,
|
||||
float scale,
|
||||
float gain,
|
||||
int sampleCount,
|
||||
int sumsOffset,
|
||||
int spotsOffset,
|
||||
int groupStart,
|
||||
int storeValues,
|
||||
int linear,
|
||||
int dither,
|
||||
int sampleTilesOffset) : IComputeShader
|
||||
{
|
||||
private readonly ReadWriteBuffer<Float4> tiles = tiles;
|
||||
private readonly ReadOnlyBuffer<Float2> twiddles = twiddles;
|
||||
private readonly ReadWriteTexture2D<Bgra32, Float4> output = output;
|
||||
private readonly ReadWriteBuffer<uint> report = report;
|
||||
private readonly ReadOnlyBuffer<Int2> samples = samples;
|
||||
private readonly ReadWriteBuffer<Float4> store = store;
|
||||
private readonly int log2Size = log2Size;
|
||||
private readonly int radius = radius;
|
||||
private readonly int validSize = validSize;
|
||||
private readonly int tilesX = tilesX;
|
||||
private readonly int batchStart = batchStart;
|
||||
private readonly int regionX = regionX;
|
||||
private readonly int regionY = regionY;
|
||||
private readonly int regionWidth = regionWidth;
|
||||
private readonly int regionHeight = regionHeight;
|
||||
private readonly float scale = scale;
|
||||
private readonly float gain = gain;
|
||||
private readonly int sampleCount = sampleCount;
|
||||
private readonly int sumsOffset = sumsOffset;
|
||||
private readonly int spotsOffset = spotsOffset;
|
||||
private readonly int groupStart = groupStart;
|
||||
private readonly int storeValues = storeValues;
|
||||
private readonly int linear = linear;
|
||||
private readonly int dither = dither;
|
||||
private readonly int sampleTilesOffset = sampleTilesOffset;
|
||||
|
||||
[GroupShared(512)]
|
||||
private static readonly Float4[] row = null!;
|
||||
|
||||
[GroupShared(256)]
|
||||
private static readonly Float4[] partial = null!;
|
||||
|
||||
public void Execute()
|
||||
{
|
||||
var local = GroupIds.X;
|
||||
var groupBase = (ThreadIds.X - local) * 2;
|
||||
var size = (int)(1u << log2Size);
|
||||
var mask = size - 1;
|
||||
var shift = 32 - log2Size;
|
||||
var element0 = local * 2;
|
||||
var element1 = local * 2 + 1;
|
||||
row[((element0 >> log2Size) << log2Size) + (int)(Hlsl.ReverseBits((uint)(element0 & mask)) >> shift)] = tiles[groupBase + element0];
|
||||
row[((element1 >> log2Size) << log2Size) + (int)(Hlsl.ReverseBits((uint)(element1 & mask)) >> shift)] = tiles[groupBase + element1];
|
||||
Hlsl.GroupMemoryBarrierWithGroupSync();
|
||||
|
||||
Butterflies(local, -1f);
|
||||
|
||||
// A group of 512 elements never lies in two tiles, so one division serves the whole group. The
|
||||
// samples buffer lists the sample positions first and then, one bit per tile, the tiles that hold a
|
||||
// sample, so that only the threads of those tiles look for samples.
|
||||
var tileIndex = batchStart + (groupBase >> (log2Size * 2));
|
||||
var tileRow = tileIndex / tilesX;
|
||||
var originX = (tileIndex - tileRow * tilesX) * validSize - radius;
|
||||
var originY = tileRow * validSize - radius;
|
||||
var sampled = sampleCount > 0 && IsSampled(tileIndex);
|
||||
partial[local] = Emit(groupBase + element0, row[element0] * scale, size, mask, originX, originY, sampled)
|
||||
+ Emit(groupBase + element1, row[element1] * scale, size, mask, originX, originY, sampled);
|
||||
Hlsl.GroupMemoryBarrierWithGroupSync();
|
||||
for (var stride = 128; stride > 0; stride >>= 1)
|
||||
{
|
||||
if (local < stride)
|
||||
partial[local] = partial[local] + partial[local + stride];
|
||||
Hlsl.GroupMemoryBarrierWithGroupSync();
|
||||
}
|
||||
|
||||
if (local == 0)
|
||||
{
|
||||
var sum = partial[0];
|
||||
var offset = sumsOffset + (groupStart + (ThreadIds.X >> 8)) * 4;
|
||||
report[offset] = Hlsl.AsUInt(sum.X);
|
||||
report[offset + 1] = Hlsl.AsUInt(sum.Y);
|
||||
report[offset + 2] = Hlsl.AsUInt(sum.Z);
|
||||
report[offset + 3] = Hlsl.AsUInt(sum.W);
|
||||
}
|
||||
}
|
||||
|
||||
private bool IsSampled(int tileIndex)
|
||||
{
|
||||
var entry = samples[sampleTilesOffset + (tileIndex >> 6)];
|
||||
var bits = (tileIndex & 32) == 0 ? (uint)entry.X : (uint)entry.Y;
|
||||
return ((bits >> (tileIndex & 31)) & 1u) != 0u;
|
||||
}
|
||||
|
||||
private Float4 Emit(int flat, Float4 value, int size, int mask, int originX, int originY, bool sampled)
|
||||
{
|
||||
if (IsNonFinite(value.X) || IsNonFinite(value.Y) || IsNonFinite(value.Z) || IsNonFinite(value.W))
|
||||
Hlsl.InterlockedAdd(ref report[0], 1u);
|
||||
|
||||
var rest = flat & (size * size - 1);
|
||||
var y = rest >> log2Size;
|
||||
var x = rest & mask;
|
||||
if (x < radius || x >= size - radius || y < radius || y >= size - radius)
|
||||
return new Float4(0f, 0f, 0f, 0f);
|
||||
|
||||
var outputX = originX + x;
|
||||
var outputY = originY + y;
|
||||
if (outputX >= regionWidth || outputY >= regionHeight)
|
||||
return new Float4(0f, 0f, 0f, 0f);
|
||||
|
||||
output[new Int2(outputX, outputY)] = LightShaderOutput.Convert(value, gain, linear, dither, regionX + outputX, regionY + outputY);
|
||||
if (storeValues != 0)
|
||||
store[outputY * regionWidth + outputX] = value;
|
||||
if (sampled)
|
||||
{
|
||||
for (var sample = 0; sample < sampleCount; sample++)
|
||||
{
|
||||
var position = samples[sample];
|
||||
if (position.X == outputX && position.Y == outputY)
|
||||
{
|
||||
report[spotsOffset + sample * 4] = Hlsl.AsUInt(value.X);
|
||||
report[spotsOffset + sample * 4 + 1] = Hlsl.AsUInt(value.Y);
|
||||
report[spotsOffset + sample * 4 + 2] = Hlsl.AsUInt(value.Z);
|
||||
report[spotsOffset + sample * 4 + 3] = Hlsl.AsUInt(value.W);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return value;
|
||||
}
|
||||
|
||||
private static bool IsNonFinite(float value)
|
||||
=> (Hlsl.AsUInt(value) & 0x7F800000u) == 0x7F800000u;
|
||||
|
||||
private void Butterflies(int local, float direction)
|
||||
{
|
||||
var halfSize = (int)(1u << (log2Size - 1));
|
||||
var rowBase = (local >> (log2Size - 1)) << log2Size;
|
||||
var pair = local & (halfSize - 1);
|
||||
for (var stage = 0; stage < log2Size; stage++)
|
||||
{
|
||||
var half = (int)(1u << stage);
|
||||
var position = pair & (half - 1);
|
||||
var even = rowBase + ((pair >> stage) << (stage + 1)) + position;
|
||||
var odd = even + half;
|
||||
var twiddle = twiddles[position << (log2Size - 1 - stage)];
|
||||
var real = twiddle.X;
|
||||
var imaginary = twiddle.Y * direction;
|
||||
var evenValue = row[even];
|
||||
var oddValue = row[odd];
|
||||
var product = new Float4(
|
||||
oddValue.X * real - oddValue.Y * imaginary,
|
||||
oddValue.X * imaginary + oddValue.Y * real,
|
||||
oddValue.Z * real - oddValue.W * imaginary,
|
||||
oddValue.Z * imaginary + oddValue.W * real);
|
||||
row[even] = evenValue + product;
|
||||
row[odd] = evenValue - product;
|
||||
Hlsl.GroupMemoryBarrierWithGroupSync();
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,143 @@
|
||||
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;
|
||||
public const int InputStatisticsOperations = 16;
|
||||
public static readonly double LightTransformError = Math.ScaleB(1d, -16);
|
||||
|
||||
static readonly string[] SumNames = ["sum.red", "sum.green", "sum.blue", "sum.alpha"];
|
||||
static readonly string[] SpotNames = ["spot.red", "spot.green", "spot.blue", "spot.alpha"];
|
||||
|
||||
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 light = job.Light;
|
||||
var floating = !light.IsDefault;
|
||||
var relative = ConvolutionBound.Relative(plan.Size, ConvolutionBound.GpuOperationError);
|
||||
var flushed = ConvolutionBound.FlushedOperations(plan.Size) * ConvolutionBound.SmallestNormal;
|
||||
measurements[0] = new ConvolutionMeasurement(NonFiniteName, report[GpuTileLayout.CountOffset], 0d, 0d);
|
||||
|
||||
Span<ulong> totals = stackalloc ulong[4];
|
||||
Span<double> floatTotals = stackalloc double[4];
|
||||
Span<double> errors = stackalloc double[4];
|
||||
for (var tile = 0; tile < plan.TileCount; tile++)
|
||||
{
|
||||
var (redGreen, blueAlpha) = Norms(report, plan, tile, floating);
|
||||
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++)
|
||||
{
|
||||
if (floating)
|
||||
floatTotals[channel] += BitConverter.UInt32BitsToSingle(report[offset + channel]);
|
||||
else
|
||||
totals[channel] += report[offset + channel];
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
var groupRounding = ConvolutionBound.Gamma(GroupAdditions, ConvolutionBound.GpuOperationError);
|
||||
var kernelRounding = ConvolutionBound.Gamma(job.KernelArea + 1, ConvolutionBound.DoubleRounding);
|
||||
var accumulation = ConvolutionBound.Gamma(plan.GroupCount, ConvolutionBound.DoubleRounding);
|
||||
var groupFlushes = (double)plan.GroupCount * (GroupElements - 1) * ConvolutionBound.SmallestNormal;
|
||||
var inputRounding = ConvolutionBound.Gamma(InputStatisticsOperations, ConvolutionBound.GpuOperationError);
|
||||
for (var channel = 0; channel < 4; channel++)
|
||||
{
|
||||
var measured = 0d;
|
||||
for (var group = 0; group < plan.GroupCount; group++)
|
||||
measured += BitConverter.UInt32BitsToSingle(report[layout.SumsOffset + group * GpuTileLayout.SumsPerGroup + channel]);
|
||||
|
||||
var reference = floating ? floatTotals[channel] : totals[channel] / 255d;
|
||||
var magnitude = reference * (1d + kernelRounding) + errors[channel];
|
||||
var tolerance = errors[channel] + groupRounding * magnitude + groupFlushes
|
||||
+ accumulation * ((1d + groupRounding) * magnitude + groupFlushes) + reference * kernelRounding;
|
||||
if (floating)
|
||||
tolerance += reference * inputRounding / (1d - inputRounding);
|
||||
measurements[1 + channel] = new ConvolutionMeasurement(SumNames[channel], measured, reference, tolerance);
|
||||
}
|
||||
|
||||
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, floating);
|
||||
DirectCorrelation.Evaluate(report.Slice(layout.GatheredOffset + sample * job.KernelArea, job.KernelArea), kernel, light, expected);
|
||||
for (var channel = 0; channel < 4; channel++)
|
||||
{
|
||||
var norm = channel < 2 ? redGreen : blueAlpha;
|
||||
var measured = BitConverter.UInt32BitsToSingle(report[layout.SpotsOffset + sample * GpuTileLayout.ValuesPerSpot + channel]);
|
||||
var tolerance = relative * norm + flushed + referenceError;
|
||||
if (light.Linear)
|
||||
tolerance += LightTransformError * norm;
|
||||
measurements[1 + SumNames.Length + sample * 4 + channel] = new ConvolutionMeasurement(SpotNames[channel], measured, expected[channel], tolerance);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
public static (double RedGreen, double BlueAlpha) Norms(ReadOnlySpan<uint> report, in TilePlan plan, int tile, bool floating)
|
||||
{
|
||||
if (!floating)
|
||||
return Norms(report, plan, tile);
|
||||
|
||||
var redGreenSquares = 0d;
|
||||
var blueAlphaSquares = 0d;
|
||||
for (var group = tile * plan.GroupsPerTile; group < (tile + 1) * plan.GroupsPerTile; group++)
|
||||
{
|
||||
var offset = GpuTileLayout.StatisticsOffset + group * GpuTileLayout.StatisticsPerGroup;
|
||||
redGreenSquares += BitConverter.UInt32BitsToSingle(report[offset + 4]);
|
||||
blueAlphaSquares += BitConverter.UInt32BitsToSingle(report[offset + 5]);
|
||||
}
|
||||
|
||||
var rounding = ConvolutionBound.Gamma(InputStatisticsOperations, ConvolutionBound.GpuOperationError);
|
||||
var inflate = 1d / (1d - rounding);
|
||||
return (Math.Sqrt(redGreenSquares * inflate), Math.Sqrt(blueAlphaSquares * inflate));
|
||||
}
|
||||
|
||||
public static (double RedGreen, double BlueAlpha) Norms(ReadOnlySpan<uint> report, in TilePlan plan, int tile)
|
||||
{
|
||||
var redGreen = 0UL;
|
||||
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,327 @@
|
||||
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,
|
||||
LightOptions Light = default)
|
||||
{
|
||||
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 ReadWriteBuffer<Float4> spare;
|
||||
ReadOnlyBuffer<Int2> samples;
|
||||
Int2[] sampleStaging = [];
|
||||
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,
|
||||
LightOptions light = default)
|
||||
{
|
||||
if (plan.Size != spectrumSize || plan.Radius != spectrumRadius)
|
||||
throw new InvalidOperationException();
|
||||
light.Validate();
|
||||
ArgumentOutOfRangeException.ThrowIfNegativeOrZero(sourceWidth);
|
||||
ArgumentOutOfRangeException.ThrowIfNegativeOrZero(sourceHeight);
|
||||
if (!float.IsFinite(gain))
|
||||
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, light);
|
||||
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)
|
||||
UploadSamples(sampleValues, plan);
|
||||
return job;
|
||||
}
|
||||
|
||||
// The samples buffer lists the sample positions, then one bit per tile, 64 tiles to an entry, that is set
|
||||
// for the tiles holding a sample. The shaders look for samples only in those tiles.
|
||||
void UploadSamples(ReadOnlySpan<Int2> sampleValues, in TilePlan plan)
|
||||
{
|
||||
var length = MaximumSamples + (plan.TileCount + 63) / 64;
|
||||
if (samples.Length < length)
|
||||
{
|
||||
samples.Dispose();
|
||||
samples = device.AllocateReadOnlyBuffer<Int2>(length);
|
||||
}
|
||||
|
||||
if (sampleStaging.Length < length)
|
||||
sampleStaging = new Int2[length];
|
||||
var staging = sampleStaging.AsSpan(0, length);
|
||||
staging.Clear();
|
||||
sampleValues.CopyTo(staging);
|
||||
foreach (var sample in sampleValues)
|
||||
{
|
||||
var tile = plan.TileAt(plan.RegionX + sample.X, plan.RegionY + sample.Y);
|
||||
ref var entry = ref staging[MaximumSamples + (tile >> 6)];
|
||||
if ((tile & 32) == 0)
|
||||
entry.X |= 1 << (tile & 31);
|
||||
else
|
||||
entry.Y |= 1 << (tile & 31);
|
||||
}
|
||||
|
||||
samples.CopyFrom(staging);
|
||||
}
|
||||
|
||||
public ReadWriteBuffer<Float4> StoreFor(in GpuTileJob job)
|
||||
=> job.Store ? store ?? throw new InvalidOperationException() : spare;
|
||||
|
||||
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;
|
||||
if (job.Light.IsDefault)
|
||||
{
|
||||
context.For(threads, new ForwardRowShader(
|
||||
source, tiles, twiddles, report, plan.Log2Size, plan.Radius, plan.ValidSize, plan.TilesX, start,
|
||||
plan.RegionX, plan.RegionY, plan.RegionWidth, plan.RegionHeight,
|
||||
job.SourceX, job.SourceY, job.SourceWidth, job.SourceHeight, GpuTileLayout.StatisticsOffset, groupStart));
|
||||
context.Barrier(tiles);
|
||||
context.For(threads, new ColumnShader(tiles, twiddles, spectrum, plan.Log2Size));
|
||||
context.Barrier(tiles);
|
||||
context.For(threads, new InverseRowShader(
|
||||
tiles, twiddles, output, report, samples, store, plan.Log2Size, plan.Radius, plan.ValidSize, plan.TilesX, start,
|
||||
plan.RegionWidth, plan.RegionHeight, scale, job.Gain, job.SampleCount, layout.SumsOffset, layout.SpotsOffset,
|
||||
groupStart, job.Store ? 1 : 0, MaximumSamples));
|
||||
context.Barrier(tiles);
|
||||
}
|
||||
else
|
||||
{
|
||||
var light = job.Light;
|
||||
context.For(threads, new ForwardRowLightShader(
|
||||
source, tiles, twiddles, report, plan.Log2Size, plan.Radius, plan.ValidSize, plan.TilesX, start,
|
||||
plan.RegionX, plan.RegionY, plan.RegionWidth, plan.RegionHeight,
|
||||
job.SourceX, job.SourceY, job.SourceWidth, job.SourceHeight, GpuTileLayout.StatisticsOffset, groupStart,
|
||||
light.Linear ? 1 : 0, light.Highlights ? 1 : 0, light.Threshold, light.Boost));
|
||||
context.Barrier(tiles);
|
||||
context.For(threads, new ColumnShader(tiles, twiddles, spectrum, plan.Log2Size));
|
||||
context.Barrier(tiles);
|
||||
context.For(threads, new InverseRowLightShader(
|
||||
tiles, twiddles, output, report, samples, store, plan.Log2Size, plan.Radius, plan.ValidSize, plan.TilesX, start,
|
||||
plan.RegionX, plan.RegionY, plan.RegionWidth, plan.RegionHeight, scale, job.Gain, job.SampleCount, layout.SumsOffset, layout.SpotsOffset,
|
||||
groupStart, job.Store ? 1 : 0, light.Linear ? 1 : 0, light.Dither ? 1 : 0, MaximumSamples));
|
||||
context.Barrier(tiles);
|
||||
}
|
||||
}
|
||||
|
||||
context.Barrier(report);
|
||||
}
|
||||
|
||||
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 static void RecordStored(
|
||||
in ComputeContext context,
|
||||
ReadWriteBuffer<Float4> store,
|
||||
ReadWriteTexture2D<Bgra32, Float4> output,
|
||||
int width,
|
||||
int height,
|
||||
float gain,
|
||||
in LightOptions light,
|
||||
int originX,
|
||||
int originY)
|
||||
{
|
||||
if (light.IsDefault)
|
||||
context.For(width, height, new StoredRenderShader(store, output, width, height, gain));
|
||||
else
|
||||
context.For(width, height, new StoredRenderLightShader(store, output, width, height, gain, light.Linear ? 1 : 0, light.Dither ? 1 : 0, originX, originY));
|
||||
}
|
||||
|
||||
public void Dispose()
|
||||
{
|
||||
tiles?.Dispose();
|
||||
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,516 @@
|
||||
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();
|
||||
|
||||
// A group of 512 elements never lies in two tiles, so one division serves the whole group.
|
||||
var tileIndex = batchStart + (groupBase >> (log2Size * 2));
|
||||
var tileRow = tileIndex / tilesX;
|
||||
var originX = regionX + (tileIndex - tileRow * tilesX) * validSize - radius;
|
||||
var originY = regionY + tileRow * validSize - radius;
|
||||
|
||||
var sumRed = 0u;
|
||||
var sumGreen = 0u;
|
||||
var sumBlue = 0u;
|
||||
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 rest = flat & (size * size - 1);
|
||||
var y = rest >> log2Size;
|
||||
var x = rest & mask;
|
||||
var canvasX = originX + x;
|
||||
var canvasY = originY + y;
|
||||
var value = new Float4(0f, 0f, 0f, 0f);
|
||||
var column = canvasX - sourceX;
|
||||
var line = canvasY - sourceY;
|
||||
if (column >= 0 && column < sourceWidth && line >= 0 && line < sourceHeight)
|
||||
{
|
||||
value = 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,
|
||||
int sampleTilesOffset) : IComputeShader
|
||||
{
|
||||
private readonly ReadWriteBuffer<Float4> tiles = tiles;
|
||||
private readonly ReadOnlyBuffer<Float2> twiddles = twiddles;
|
||||
private readonly ReadWriteTexture2D<Bgra32, Float4> output = output;
|
||||
private readonly ReadWriteBuffer<uint> report = report;
|
||||
private readonly ReadOnlyBuffer<Int2> samples = samples;
|
||||
private readonly ReadWriteBuffer<Float4> store = store;
|
||||
private readonly int log2Size = log2Size;
|
||||
private readonly int radius = radius;
|
||||
private readonly int validSize = validSize;
|
||||
private readonly int tilesX = tilesX;
|
||||
private readonly int batchStart = batchStart;
|
||||
private readonly int regionWidth = regionWidth;
|
||||
private readonly int regionHeight = regionHeight;
|
||||
private readonly float scale = scale;
|
||||
private readonly float gain = gain;
|
||||
private readonly int sampleCount = sampleCount;
|
||||
private readonly int sumsOffset = sumsOffset;
|
||||
private readonly int spotsOffset = spotsOffset;
|
||||
private readonly int groupStart = groupStart;
|
||||
private readonly int storeValues = storeValues;
|
||||
private readonly int sampleTilesOffset = sampleTilesOffset;
|
||||
|
||||
[GroupShared(512)]
|
||||
private static readonly Float4[] row = null!;
|
||||
|
||||
[GroupShared(256)]
|
||||
private static readonly Float4[] partial = null!;
|
||||
|
||||
public void Execute()
|
||||
{
|
||||
var local = GroupIds.X;
|
||||
var groupBase = (ThreadIds.X - local) * 2;
|
||||
var size = (int)(1u << log2Size);
|
||||
var mask = size - 1;
|
||||
var shift = 32 - log2Size;
|
||||
var element0 = local * 2;
|
||||
var element1 = local * 2 + 1;
|
||||
row[((element0 >> log2Size) << log2Size) + (int)(Hlsl.ReverseBits((uint)(element0 & mask)) >> shift)] = tiles[groupBase + element0];
|
||||
row[((element1 >> log2Size) << log2Size) + (int)(Hlsl.ReverseBits((uint)(element1 & mask)) >> shift)] = tiles[groupBase + element1];
|
||||
Hlsl.GroupMemoryBarrierWithGroupSync();
|
||||
|
||||
Butterflies(local, -1f);
|
||||
|
||||
// A group of 512 elements never lies in two tiles, so one division serves the whole group. The
|
||||
// samples buffer lists the sample positions first and then, one bit per tile, the tiles that hold a
|
||||
// sample, so that only the threads of those tiles look for samples.
|
||||
var tileIndex = batchStart + (groupBase >> (log2Size * 2));
|
||||
var tileRow = tileIndex / tilesX;
|
||||
var originX = (tileIndex - tileRow * tilesX) * validSize - radius;
|
||||
var originY = tileRow * validSize - radius;
|
||||
var sampled = sampleCount > 0 && IsSampled(tileIndex);
|
||||
partial[local] = Emit(groupBase + element0, row[element0] * scale, size, mask, originX, originY, sampled)
|
||||
+ Emit(groupBase + element1, row[element1] * scale, size, mask, originX, originY, sampled);
|
||||
Hlsl.GroupMemoryBarrierWithGroupSync();
|
||||
for (var stride = 128; stride > 0; stride >>= 1)
|
||||
{
|
||||
if (local < stride)
|
||||
partial[local] = partial[local] + partial[local + stride];
|
||||
Hlsl.GroupMemoryBarrierWithGroupSync();
|
||||
}
|
||||
|
||||
if (local == 0)
|
||||
{
|
||||
var sum = partial[0];
|
||||
var offset = sumsOffset + (groupStart + (ThreadIds.X >> 8)) * 4;
|
||||
report[offset] = Hlsl.AsUInt(sum.X);
|
||||
report[offset + 1] = Hlsl.AsUInt(sum.Y);
|
||||
report[offset + 2] = Hlsl.AsUInt(sum.Z);
|
||||
report[offset + 3] = Hlsl.AsUInt(sum.W);
|
||||
}
|
||||
}
|
||||
|
||||
private bool IsSampled(int tileIndex)
|
||||
{
|
||||
var entry = samples[sampleTilesOffset + (tileIndex >> 6)];
|
||||
var bits = (tileIndex & 32) == 0 ? (uint)entry.X : (uint)entry.Y;
|
||||
return ((bits >> (tileIndex & 31)) & 1u) != 0u;
|
||||
}
|
||||
|
||||
private Float4 Emit(int flat, Float4 value, int size, int mask, int originX, int originY, bool sampled)
|
||||
{
|
||||
if (IsNonFinite(value.X) || IsNonFinite(value.Y) || IsNonFinite(value.Z) || IsNonFinite(value.W))
|
||||
Hlsl.InterlockedAdd(ref report[0], 1u);
|
||||
|
||||
var rest = flat & (size * size - 1);
|
||||
var y = rest >> log2Size;
|
||||
var x = rest & mask;
|
||||
if (x < radius || x >= size - radius || y < radius || y >= size - radius)
|
||||
return new Float4(0f, 0f, 0f, 0f);
|
||||
|
||||
var outputX = originX + x;
|
||||
var outputY = originY + y;
|
||||
if (outputX >= regionWidth || outputY >= regionHeight)
|
||||
return new Float4(0f, 0f, 0f, 0f);
|
||||
|
||||
output[new Int2(outputX, outputY)] = value * gain;
|
||||
if (storeValues != 0)
|
||||
store[outputY * regionWidth + outputX] = value;
|
||||
if (sampled)
|
||||
{
|
||||
for (var sample = 0; sample < sampleCount; sample++)
|
||||
{
|
||||
var position = samples[sample];
|
||||
if (position.X == outputX && position.Y == outputY)
|
||||
{
|
||||
report[spotsOffset + sample * 4] = Hlsl.AsUInt(value.X);
|
||||
report[spotsOffset + sample * 4 + 1] = Hlsl.AsUInt(value.Y);
|
||||
report[spotsOffset + sample * 4 + 2] = Hlsl.AsUInt(value.Z);
|
||||
report[spotsOffset + sample * 4 + 3] = Hlsl.AsUInt(value.W);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return value;
|
||||
}
|
||||
|
||||
private static bool IsNonFinite(float value)
|
||||
=> (Hlsl.AsUInt(value) & 0x7F800000u) == 0x7F800000u;
|
||||
|
||||
private void Butterflies(int local, float direction)
|
||||
{
|
||||
var halfSize = (int)(1u << (log2Size - 1));
|
||||
var rowBase = (local >> (log2Size - 1)) << log2Size;
|
||||
var pair = local & (halfSize - 1);
|
||||
for (var stage = 0; stage < log2Size; stage++)
|
||||
{
|
||||
var half = (int)(1u << stage);
|
||||
var position = pair & (half - 1);
|
||||
var even = rowBase + ((pair >> stage) << (stage + 1)) + position;
|
||||
var odd = even + half;
|
||||
var twiddle = twiddles[position << (log2Size - 1 - stage)];
|
||||
var real = twiddle.X;
|
||||
var imaginary = twiddle.Y * direction;
|
||||
var evenValue = row[even];
|
||||
var oddValue = row[odd];
|
||||
var product = new Float4(
|
||||
oddValue.X * real - oddValue.Y * imaginary,
|
||||
oddValue.X * imaginary + oddValue.Y * real,
|
||||
oddValue.Z * real - oddValue.W * imaginary,
|
||||
oddValue.Z * imaginary + oddValue.W * real);
|
||||
row[even] = evenValue + product;
|
||||
row[odd] = evenValue - product;
|
||||
Hlsl.GroupMemoryBarrierWithGroupSync();
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,123 @@
|
||||
using ComputeWeave;
|
||||
|
||||
namespace SpectralConvolution;
|
||||
|
||||
internal sealed class KernelSpectrum
|
||||
{
|
||||
double[] kernel = [];
|
||||
double[] rowReal = [];
|
||||
double[] rowImaginary = [];
|
||||
double[] columnReal = [];
|
||||
double[] columnImaginary = [];
|
||||
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 rowArea = kernelSize * size;
|
||||
Size = 0;
|
||||
Radius = 0;
|
||||
if (kernel.Length < kernelArea)
|
||||
kernel = new double[kernelArea];
|
||||
if (rowReal.Length < rowArea)
|
||||
{
|
||||
rowReal = new double[rowArea];
|
||||
rowImaginary = new double[rowArea];
|
||||
}
|
||||
if (columnReal.Length < size)
|
||||
{
|
||||
columnReal = new double[size];
|
||||
columnImaginary = new double[size];
|
||||
}
|
||||
if (spectrum.Length < size * size)
|
||||
spectrum = new Float2[size * size];
|
||||
if (twiddles.Length < size / 2)
|
||||
twiddles = new Float2[size / 2];
|
||||
|
||||
for (var index = 0; index < kernelArea; index++)
|
||||
kernel[index] = values[index] / sum;
|
||||
|
||||
for (var index = 0; index < size / 2; index++)
|
||||
{
|
||||
var angle = -2d * Math.PI * index / size;
|
||||
twiddles[index] = new Float2(Flush((float)Math.Cos(angle)), Flush((float)Math.Sin(angle)));
|
||||
}
|
||||
|
||||
var mask = size - 1;
|
||||
for (var row = 0; row < kernelSize; row++)
|
||||
{
|
||||
var realLine = rowReal.AsSpan(row * size, size);
|
||||
var imaginaryLine = rowImaginary.AsSpan(row * size, size);
|
||||
realLine.Clear();
|
||||
imaginaryLine.Clear();
|
||||
for (var offsetX = -radius; offsetX <= radius; offsetX++)
|
||||
realLine[-offsetX & mask] = kernel[row * kernelSize + offsetX + radius];
|
||||
|
||||
FastFourierTransform.Forward(realLine, imaginaryLine);
|
||||
}
|
||||
|
||||
var half = size / 2;
|
||||
var real = columnReal.AsSpan(0, size);
|
||||
var imaginary = columnImaginary.AsSpan(0, size);
|
||||
for (var frequencyX = 0; frequencyX <= half; frequencyX++)
|
||||
{
|
||||
real.Clear();
|
||||
imaginary.Clear();
|
||||
for (var row = 0; row < kernelSize; row++)
|
||||
{
|
||||
var target = radius - row & mask;
|
||||
real[target] = rowReal[row * size + frequencyX];
|
||||
imaginary[target] = rowImaginary[row * size + frequencyX];
|
||||
}
|
||||
|
||||
FastFourierTransform.Forward(real, imaginary);
|
||||
var stored = spectrum.AsSpan(frequencyX * size, size);
|
||||
for (var frequencyY = 0; frequencyY < size; frequencyY++)
|
||||
stored[frequencyY] = new Float2(Flush((float)real[frequencyY]), Flush((float)imaginary[frequencyY]));
|
||||
}
|
||||
|
||||
for (var frequencyX = half + 1; frequencyX < size; frequencyX++)
|
||||
{
|
||||
var source = spectrum.AsSpan((size - frequencyX) * size, size);
|
||||
var stored = spectrum.AsSpan(frequencyX * size, size);
|
||||
for (var frequencyY = 0; frequencyY < size; frequencyY++)
|
||||
{
|
||||
var conjugate = source[size - frequencyY & mask];
|
||||
stored[frequencyY] = new Float2(conjugate.X, -conjugate.Y);
|
||||
}
|
||||
}
|
||||
|
||||
Size = size;
|
||||
Radius = radius;
|
||||
}
|
||||
|
||||
public static float Flush(float value) => float.IsSubnormal(value) ? float.CopySign(0f, value) : value;
|
||||
}
|
||||
@@ -0,0 +1,21 @@
|
||||
namespace SpectralConvolution;
|
||||
|
||||
internal readonly record struct LightOptions(bool Linear, bool Dither, float Threshold, float Boost)
|
||||
{
|
||||
public const float MaximumBoost = 1000f;
|
||||
|
||||
public bool IsDefault => !Linear && !Dither;
|
||||
|
||||
public bool Highlights => Linear && Boost > 1f && Threshold < 1f;
|
||||
|
||||
public LightOptions ForConvolution()
|
||||
=> new(Linear, false, Highlights ? Threshold : 0f, Highlights ? Boost : 0f);
|
||||
|
||||
public void Validate()
|
||||
{
|
||||
if (!float.IsFinite(Threshold) || Threshold < 0f || Threshold > 1f)
|
||||
throw new ArgumentOutOfRangeException(nameof(Threshold));
|
||||
if (!float.IsFinite(Boost) || Boost < 0f || Boost > MaximumBoost)
|
||||
throw new ArgumentOutOfRangeException(nameof(Boost));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,235 @@
|
||||
using System.Runtime.CompilerServices;
|
||||
using System.Runtime.InteropServices;
|
||||
using System.Runtime.Intrinsics;
|
||||
|
||||
namespace SpectralConvolution;
|
||||
|
||||
internal static class LightTransform
|
||||
{
|
||||
public const int Channels = 4;
|
||||
public const float DecodeToeLimit = 0.04045f;
|
||||
public const float EncodeToeLimit = 0.0031308f;
|
||||
public const float ToeSlope = 12.92f;
|
||||
public const float Offset = 0.055f;
|
||||
public const float Scale = 1.055f;
|
||||
public const float DecodeExponent = 2.4f;
|
||||
public const float EncodeExponent = 0.41666666f;
|
||||
|
||||
// Encode and Decode read tables of value and slope pairs and interpolate between the entries, because
|
||||
// the power function costs more than everything else the CPU does for one pixel. The tables are
|
||||
// indexed by the bits of the float that is converted, so the steps are as fine in the darks as in the
|
||||
// brights. Encode has 256 steps per power of two from 2^-9 up to 1, and its relative error stays
|
||||
// below 5e-7. Decode has 1024 steps per power of two from 2^-4 up to 1, with the same error.
|
||||
// That is as large as the error of the power function on the GPU, and about 30 times smaller than
|
||||
// the error the checks allow.
|
||||
const int EncodeFractionBits = 15;
|
||||
const int EncodeFirstStep = 0x3B000000 >> EncodeFractionBits;
|
||||
const int EncodeSteps = (0x3F800000 >> EncodeFractionBits) - EncodeFirstStep;
|
||||
const int DecodeFractionBits = 13;
|
||||
const int DecodeFirstStep = 0x3D800000 >> DecodeFractionBits;
|
||||
const int DecodeSteps = (0x3F800000 >> DecodeFractionBits) - DecodeFirstStep;
|
||||
const float EncodeFractionScale = 1f / (1 << EncodeFractionBits);
|
||||
const float DecodeFractionScale = 1f / (1 << DecodeFractionBits);
|
||||
|
||||
static readonly float[] EncodePairs = BuildPairs(EncodeFractionBits, EncodeFirstStep, EncodeSteps, linear => Scale * Math.Pow(linear, EncodeExponent) - Offset);
|
||||
static readonly float[] DecodePairs = BuildPairs(DecodeFractionBits, DecodeFirstStep, DecodeSteps, power => Math.Pow(power, DecodeExponent));
|
||||
static readonly float[] OpaqueDecode = BuildOpaqueDecode();
|
||||
static readonly Vector128<float> AlphaLane = Vector128.Create(0, 0, 0, -1).AsSingle();
|
||||
|
||||
public static float Decode(float encoded)
|
||||
{
|
||||
if (!(encoded > DecodeToeLimit))
|
||||
return encoded / ToeSlope;
|
||||
if (encoded >= 1f)
|
||||
return 1f;
|
||||
|
||||
var bits = BitConverter.SingleToInt32Bits((encoded + Offset) / Scale);
|
||||
var step = (bits >> DecodeFractionBits) - DecodeFirstStep;
|
||||
var fraction = (bits & ((1 << DecodeFractionBits) - 1)) * DecodeFractionScale;
|
||||
ref var pair = ref Unsafe.Add(ref MemoryMarshal.GetArrayDataReference(DecodePairs), step * 2);
|
||||
return pair + Unsafe.Add(ref pair, 1) * fraction;
|
||||
}
|
||||
|
||||
public static float Encode(float linear)
|
||||
{
|
||||
if (!(linear > EncodeToeLimit))
|
||||
return ToeSlope * linear;
|
||||
if (linear >= 1f)
|
||||
return 1f;
|
||||
|
||||
var bits = BitConverter.SingleToInt32Bits(linear);
|
||||
var step = (bits >> EncodeFractionBits) - EncodeFirstStep;
|
||||
var fraction = (bits & ((1 << EncodeFractionBits) - 1)) * EncodeFractionScale;
|
||||
ref var pair = ref Unsafe.Add(ref MemoryMarshal.GetArrayDataReference(EncodePairs), step * 2);
|
||||
return pair + Unsafe.Add(ref pair, 1) * fraction;
|
||||
}
|
||||
|
||||
public static (float Red, float Green, float Blue, float Alpha) FromBytes(byte red, byte green, byte blue, byte alpha, in LightOptions options)
|
||||
{
|
||||
if (!options.Linear)
|
||||
return (red / 255f, green / 255f, blue / 255f, alpha / 255f);
|
||||
if (alpha == 0)
|
||||
return default;
|
||||
|
||||
var opacity = alpha / 255f;
|
||||
float straightRed;
|
||||
float straightGreen;
|
||||
float straightBlue;
|
||||
float linearRed;
|
||||
float linearGreen;
|
||||
float linearBlue;
|
||||
if (alpha == 255)
|
||||
{
|
||||
straightRed = red / 255f;
|
||||
straightGreen = green / 255f;
|
||||
straightBlue = blue / 255f;
|
||||
linearRed = OpaqueDecode[red];
|
||||
linearGreen = OpaqueDecode[green];
|
||||
linearBlue = OpaqueDecode[blue];
|
||||
}
|
||||
else
|
||||
{
|
||||
straightRed = MathF.Min(red / (float)alpha, 1f);
|
||||
straightGreen = MathF.Min(green / (float)alpha, 1f);
|
||||
straightBlue = MathF.Min(blue / (float)alpha, 1f);
|
||||
linearRed = Decode(straightRed);
|
||||
linearGreen = Decode(straightGreen);
|
||||
linearBlue = Decode(straightBlue);
|
||||
}
|
||||
|
||||
var weight = 1f;
|
||||
if (options.Highlights)
|
||||
{
|
||||
var peak = MathF.Max(MathF.Max(straightRed, straightGreen), straightBlue);
|
||||
var excess = MathF.Min(MathF.Max((peak - options.Threshold) / (1f - options.Threshold), 0f), 1f);
|
||||
weight = 1f + (options.Boost - 1f) * excess * excess;
|
||||
}
|
||||
|
||||
var scale = opacity * weight;
|
||||
return (linearRed * scale, linearGreen * scale, linearBlue * scale, scale);
|
||||
}
|
||||
|
||||
public static (byte Blue, byte Green, byte Red, byte Alpha) ToBytes(
|
||||
float red,
|
||||
float green,
|
||||
float blue,
|
||||
float alpha,
|
||||
float gain,
|
||||
in LightOptions options,
|
||||
int x,
|
||||
int y)
|
||||
{
|
||||
float outputRed;
|
||||
float outputGreen;
|
||||
float outputBlue;
|
||||
float outputAlpha;
|
||||
if (options.Linear)
|
||||
{
|
||||
outputAlpha = Saturate(alpha * gain);
|
||||
if (outputAlpha > 0f)
|
||||
{
|
||||
outputRed = Encode(MathF.Min(Saturate(red * gain), outputAlpha) / outputAlpha) * outputAlpha;
|
||||
outputGreen = Encode(MathF.Min(Saturate(green * gain), outputAlpha) / outputAlpha) * outputAlpha;
|
||||
outputBlue = Encode(MathF.Min(Saturate(blue * gain), outputAlpha) / outputAlpha) * outputAlpha;
|
||||
}
|
||||
else
|
||||
{
|
||||
outputRed = 0f;
|
||||
outputGreen = 0f;
|
||||
outputBlue = 0f;
|
||||
}
|
||||
}
|
||||
else
|
||||
{
|
||||
outputRed = Saturate(red * gain);
|
||||
outputGreen = Saturate(green * gain);
|
||||
outputBlue = Saturate(blue * gain);
|
||||
outputAlpha = Saturate(alpha * gain);
|
||||
}
|
||||
|
||||
// One threshold serves the four values of a pixel. Rounding is monotonic for a shared threshold, so a
|
||||
// color that does not exceed the opacity before rounding does not exceed it after rounding either.
|
||||
var threshold = options.Dither ? DitherThreshold(x, y) : 0f;
|
||||
return (
|
||||
Quantize(outputBlue, options.Dither, threshold),
|
||||
Quantize(outputGreen, options.Dither, threshold),
|
||||
Quantize(outputRed, options.Dither, threshold),
|
||||
Quantize(outputAlpha, options.Dither, threshold));
|
||||
}
|
||||
|
||||
// The same conversion as ToBytes for one pixel held in a vector (red, green, blue, alpha), returned as
|
||||
// the four bytes (blue, green, red, alpha). Every step is the same IEEE operation in the same order,
|
||||
// so the bytes are the ones ToBytes returns.
|
||||
public static uint ToPacked(Vector128<float> value, float gain, in LightOptions options, int x, int y)
|
||||
{
|
||||
var saturated = Saturate(value * Vector128.Create(gain));
|
||||
var color = saturated;
|
||||
if (options.Linear)
|
||||
{
|
||||
var alpha = Vector128.Shuffle(saturated, Vector128.Create(3, 3, 3, 3));
|
||||
var visible = Vector128.GreaterThan(alpha, Vector128<float>.Zero);
|
||||
var encoded = Encode(Vector128.Min(saturated, alpha) / alpha) * alpha;
|
||||
color = Vector128.ConditionalSelect(AlphaLane, saturated, Vector128.ConditionalSelect(visible, encoded, Vector128<float>.Zero));
|
||||
}
|
||||
|
||||
var scaled = color * Vector128.Create(255f);
|
||||
var levels = options.Dither
|
||||
? Vector128.ConvertToInt32(Vector128.Min(scaled + Vector128.Create(DitherThreshold(x, y)), Vector128.Create(255f)))
|
||||
: Vector128.ConvertToInt32(scaled + Vector128.Create(0.5f));
|
||||
var ordered = Vector128.Shuffle(levels, Vector128.Create(2, 1, 0, 3)).AsUInt32();
|
||||
var words = Vector128.Narrow(ordered, ordered);
|
||||
return Vector128.Narrow(words, words).AsUInt32().ToScalar();
|
||||
}
|
||||
|
||||
static Vector128<float> Encode(Vector128<float> linear)
|
||||
=> Vector128.Create(Encode(linear.GetElement(0)), Encode(linear.GetElement(1)), Encode(linear.GetElement(2)), 0f);
|
||||
|
||||
static Vector128<float> Saturate(Vector128<float> value)
|
||||
{
|
||||
value = Vector128.ConditionalSelect(Vector128.Equals(value, value), value, Vector128<float>.Zero);
|
||||
return Vector128.Min(Vector128.Max(value, Vector128<float>.Zero), Vector128<float>.One);
|
||||
}
|
||||
|
||||
public static float DitherThreshold(int x, int y)
|
||||
{
|
||||
var hash = unchecked((uint)x * 0x9E3779B1u ^ (uint)y * 0x85EBCA77u);
|
||||
hash ^= hash >> 16;
|
||||
hash = unchecked(hash * 0x7FEB352Du);
|
||||
hash ^= hash >> 15;
|
||||
hash = unchecked(hash * 0x846CA68Bu);
|
||||
hash ^= hash >> 16;
|
||||
return (hash >> 8) * (1f / 16777216f);
|
||||
}
|
||||
|
||||
static byte Quantize(float value, bool dither, float threshold)
|
||||
=> dither
|
||||
? (byte)MathF.Min(value * 255f + threshold, 255f)
|
||||
: (byte)(value * 255f + 0.5f);
|
||||
|
||||
static float Saturate(float value)
|
||||
=> float.IsNaN(value) ? 0f : Math.Clamp(value, 0f, 1f);
|
||||
|
||||
static float[] BuildOpaqueDecode()
|
||||
{
|
||||
var table = new float[256];
|
||||
for (var index = 0; index < table.Length; index++)
|
||||
table[index] = Decode(index / 255f);
|
||||
return table;
|
||||
}
|
||||
|
||||
static float[] BuildPairs(int fractionBits, int firstStep, int steps, Func<double, double> curve)
|
||||
{
|
||||
var values = new float[steps + 1];
|
||||
for (var index = 0; index < values.Length; index++)
|
||||
values[index] = (float)curve(BitConverter.Int32BitsToSingle((firstStep + index) << fractionBits));
|
||||
|
||||
var pairs = new float[(steps + 1) * 2];
|
||||
for (var index = 0; index <= steps; index++)
|
||||
{
|
||||
pairs[index * 2] = values[index];
|
||||
pairs[index * 2 + 1] = index < steps ? values[index + 1] - values[index] : 0f;
|
||||
}
|
||||
|
||||
return pairs;
|
||||
}
|
||||
}
|
||||
@@ -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));
|
||||
}
|
||||
@@ -1,49 +0,0 @@
|
||||
Key,Parameter,ja-jp,en-us,zh-cn,zh-tw,ko-kr,es-es,ar-sa,id-id
|
||||
EffectName,,波動光学,Wave Optics,波动光学,波動光學,파동 광학,Óptica de ondas,البصريات الموجية,Optik Gelombang
|
||||
OutputGroup,,出力,Output,输出,輸出,출력,Salida,الإخراج,Keluaran
|
||||
OpticsGroup,,光学系,Optical System,光学系统,光學系統,광학 시스템,Sistema óptico,النظام البصري,Sistem Optik
|
||||
ApertureGroup,,開口,Aperture,光圈,光圈,조리개,Apertura,الفتحة,Apertur
|
||||
AberrationGroup,,波面収差,Wavefront Aberration,波前像差,波前像差,파면 수차,Aberración de frente de onda,انحراف جبهة الموجة,Aberasi Muka Gelombang
|
||||
AmountName,,適用量,Amount,适用量,適用量,적용량,Cantidad,الكمية,Jumlah
|
||||
AmountDesc,,波動光学処理の適用量を調整します。0%では入力を変更しません。,Adjusts the amount of wave optics processing. The input is unchanged at 0%.,调整波动光学处理的适用量。0%时输入不变。,調整波動光學處理的適用量。0%時輸入不變。,파동 광학 처리의 적용량을 조정합니다. 0%에서는 입력이 변경되지 않습니다.,Ajusta la cantidad de procesamiento de óptica de ondas. La entrada no cambia al 0%.,يضبط مقدار معالجة البصريات الموجية. يبقى الإدخال دون تغيير عند 0%.,Menyesuaikan jumlah pemrosesan optik gelombang. Input tidak berubah pada 0%.
|
||||
GainName,,利得,Gain,增益,增益,이득,Ganancia,الكسب,Penguatan
|
||||
GainDesc,,エネルギー保存された畳み込み結果へ乗算する表示用利得です。,Sets the display gain applied after the energy preserving convolution.,设置能量守恒卷积后应用的显示增益。,設定能量守恆卷積後應用的顯示增益。,에너지 보존 컨볼루션 후 적용되는 표시 이득을 설정합니다.,Establece la ganancia de visualización aplicada tras la convolución de conservación de energía.,يضبط كسب العرض المطبق بعد الالتفاف الحافظ للطاقة.,Mengatur penguatan tampilan yang diterapkan setelah konvolusi pelestarian energi.
|
||||
WavelengthName,,波長,Wavelength,波长,波長,파장,Longitud de onda,الطول الموجي,Panjang Gelombang
|
||||
WavelengthDesc,,単色光として計算する真空中の波長を指定します。,Sets the vacuum wavelength used for the monochromatic calculation.,设置单色光计算使用的真空波长。,設定單色光計算使用的真空波長。,단색광 계산에 사용되는 진공 파장을 설정합니다.,Establece la longitud de onda en el vacío utilizada para el cálculo monocromático.,يضبط الطول الموجي في الفراغ المستخدم للحساب أحادي اللون.,Mengatur panjang gelombang vakum yang digunakan untuk perhitungan monokromatik.
|
||||
FNumberName,,F値,F-number,F值,F值,F값,Número F,رقم F,Angka F
|
||||
FNumberDesc,,開口径に対する焦点距離の比を指定します。,Sets the ratio of focal length to aperture diameter.,设置焦距与光圈直径的比值。,設定焦距與光圈直徑的比值。,초점 거리와 조리개 직경의 비율을 설정합니다.,Establece la relación entre la longitud focal y el diámetro de la apertura.,يضبط نسبة البعد البؤري إلى قطر الفتحة.,Mengatur rasio panjang fokus terhadap diameter apertur.
|
||||
PixelPitchName,,画素ピッチ,Pixel Pitch,像素间距,像素間距,픽셀 피치,Paso de píxel,خطوة البكسل,Jarak Piksel
|
||||
PixelPitchDesc,,撮像面上の1画素の物理的な間隔を指定します。,Sets the physical spacing of one pixel on the image plane.,设置图像平面上一个像素的物理间距。,設定影像平面上一個像素的物理間距。,이미지 평면의 픽셀 하나의 물리적 간격을 설정합니다.,Establece el espaciado físico de un píxel en el plano de imagen.,يضبط التباعد المادي لبكسل واحد على مستوى الصورة.,Mengatur jarak fisik satu piksel pada bidang gambar.
|
||||
KernelRadiusName,,カーネル半径,Kernel Radius,核半径,核半徑,커널 반지름,Radio de kernel,نصف قطر النواة,Radius Kernel
|
||||
KernelRadiusDesc,,PSFを畳み込む画素半径を指定します。,Sets the pixel radius used to convolve the PSF.,设置用于卷积PSF的像素半径。,設定用於卷積PSF的像素半徑。,PSF를 컨볼루션하는 픽셀 반지름을 설정합니다.,Establece el radio de píxel utilizado para convolucionar la PSF.,يضبط نصف قطر البكسل المستخدم لالتفاف PSF.,Mengatur radius piksel yang digunakan untuk mengkonvolusikan PSF.
|
||||
QualityName,,品質,Quality,质量,品質,품질,Calidad,الجودة,Kualitas
|
||||
QualityDesc,,瞳関数とPSFを計算するFFT格子の大きさを指定します。,Sets the FFT grid size used to calculate the pupil function and PSF.,设置用于计算瞳孔函数和PSF的FFT格点大小。,設定用於計算瞳孔函數和PSF的FFT格點大小。,동공 함수와 PSF를 계산하는 FFT 격자 크기를 설정합니다.,Establece el tamaño de la cuadrícula FFT utilizada para calcular la función pupilar y la PSF.,يضبط حجم شبكة FFT المستخدمة لحساب دالة الحدقة وPSF.,Mengatur ukuran kisi FFT yang digunakan untuk menghitung fungsi pupil dan PSF.
|
||||
QualityDraft,,高速,Draft,草稿,草稿,초안,Borrador,مسودة,Draf
|
||||
QualityStandard,,標準,Standard,标准,標準,표준,Estándar,قياسي,Standar
|
||||
QualityHigh,,高精度,High,高精度,高精度,높음,Alto,مرتفع,Tinggi
|
||||
ApertureShapeName,,開口形状,Aperture Shape,光圈形状,光圈形狀,조리개 형태,Forma de apertura,شكل الفتحة,Bentuk Apertur
|
||||
ApertureShapeDesc,,瞳関数の外周形状を指定します。,Sets the outer shape of the pupil function.,设置瞳孔函数的外部形状。,設定瞳孔函數的外部形狀。,동공 함수의 외부 형태를 설정합니다.,Establece la forma exterior de la función pupilar.,يضبط الشكل الخارجي لدالة الحدقة.,Mengatur bentuk luar fungsi pupil.
|
||||
CircularAperture,,円形,Circular,圆形,圓形,원형,Circular,دائري,Melingkar
|
||||
RegularPolygonAperture,,正多角形,Regular Polygon,正多边形,正多邊形,정다각형,Polígono regular,مضلع منتظم,Poligon Beraturan
|
||||
BladeCountName,,羽根枚数,Blade Count,叶片数,葉片數,날개 수,Número de láminas,عدد الشفرات,Jumlah Bilah
|
||||
BladeCountDesc,,正多角形開口の辺数を指定します。,Sets the number of sides in the regular polygon aperture.,设置正多边形光圈的边数。,設定正多邊形光圈的邊數。,정다각형 조리개의 변의 수를 설정합니다.,Establece el número de lados en la apertura de polígono regular.,يضبط عدد أضلاع فتحة المضلع المنتظم.,Mengatur jumlah sisi pada apertur poligon beraturan.
|
||||
BladeRotationName,,開口回転,Aperture Rotation,光圈旋转,光圈旋轉,조리개 회전,Rotación de apertura,دوران الفتحة,Rotasi Apertur
|
||||
BladeRotationDesc,,正多角形開口の回転角を指定します。,Sets the rotation angle of the regular polygon aperture.,设置正多边形光圈的旋转角度。,設定正多邊形光圈的旋轉角度。,정다각형 조리개의 회전 각도를 설정합니다.,Establece el ángulo de rotación de la apertura de polígono regular.,يضبط زاوية دوران فتحة المضلع المنتظم.,Mengatur sudut rotasi apertur poligon beraturan.
|
||||
ObstructionName,,中央遮蔽,Central Obstruction,中央遮蔽,中央遮蔽,중앙 차폐,Obstrucción central,الحجب المركزي,Obstruksi Tengah
|
||||
ObstructionDesc,,開口半径に対する中央遮蔽半径の割合を指定します。,Sets the central obstruction radius relative to the aperture radius.,设置中央遮蔽半径相对于光圈半径的比例。,設定中央遮蔽半徑相對於光圈半徑的比例。,조리개 반지름에 대한 중앙 차폐 반지름의 비율을 설정합니다.,Establece el radio de obstrucción central en relación al radio de apertura.,يضبط نصف قطر الحجب المركزي بالنسبة لنصف قطر الفتحة.,Mengatur radius obstruksi tengah relatif terhadap radius apertur.
|
||||
DefocusName,,デフォーカス,Defocus,离焦,離焦,디포커스,Desenfoque,إزالة التركيز,Defokus
|
||||
DefocusDesc,,正規化Zernikeデフォーカス係数を波数で指定します。,Sets the normalized Zernike defocus coefficient in waves.,以波数为单位设置归一化Zernike离焦系数。,以波數為單位設定歸一化Zernike離焦係數。,파수 단위로 정규화된 Zernike 디포커스 계수를 설정합니다.,Establece el coeficiente de desenfoque de Zernike normalizado en ondas.,يضبط معامل إزالة التركيز لـZernike المعياري بالأمواج.,Mengatur koefisien defokus Zernike ternormalisasi dalam satuan gelombang.
|
||||
AstigmatismVerticalName,,縦横非点収差,Vertical Astigmatism,垂直散光,垂直散光,수직 난시,Astigmatismo vertical,الاستجماتيزم الرأسي,Astigmatisme Vertikal
|
||||
AstigmatismVerticalDesc,,0度方向の正規化Zernike非点収差係数を指定します。,Sets the normalized Zernike astigmatism coefficient at zero degrees.,设置0度方向的归一化Zernike散光系数。,設定0度方向的歸一化Zernike散光係數。,0도 방향의 정규화된 Zernike 난시 계수를 설정합니다.,Establece el coeficiente de astigmatismo de Zernike normalizado en cero grados.,يضبط معامل الاستجماتيزم لـZernike المعياري عند صفر درجة.,Mengatur koefisien astigmatisme Zernike ternormalisasi pada nol derajat.
|
||||
AstigmatismObliqueName,,斜め非点収差,Oblique Astigmatism,斜向散光,斜向散光,사선 난시,Astigmatismo oblicuo,الاستجماتيزم المائل,Astigmatisme Miring
|
||||
AstigmatismObliqueDesc,,45度方向の正規化Zernike非点収差係数を指定します。,Sets the normalized Zernike astigmatism coefficient at 45 degrees.,设置45度方向的归一化Zernike散光系数。,設定45度方向的歸一化Zernike散光係數。,45도 방향의 정규화된 Zernike 난시 계수를 설정합니다.,Establece el coeficiente de astigmatismo de Zernike normalizado en 45 grados.,يضبط معامل الاستجماتيزم لـZernike المعياري عند 45 درجة.,Mengatur koefisien astigmatisme Zernike ternormalisasi pada 45 derajat.
|
||||
ComaHorizontalName,,水平コマ収差,Horizontal Coma,水平彗差,水平彗差,수평 코마,Coma horizontal,الكوما الأفقية,Koma Horizontal
|
||||
ComaHorizontalDesc,,水平方向の正規化Zernikeコマ収差係数を指定します。,Sets the normalized horizontal Zernike coma coefficient.,设置归一化水平Zernike彗差系数。,設定歸一化水平Zernike彗差係數。,정규화된 수평 Zernike 코마 계수를 설정합니다.,Establece el coeficiente de coma de Zernike horizontal normalizado.,يضبط معامل الكوما الأفقي لـZernike المعياري.,Mengatur koefisien koma Zernike horizontal ternormalisasi.
|
||||
ComaVerticalName,,垂直コマ収差,Vertical Coma,垂直彗差,垂直彗差,수직 코마,Coma vertical,الكوما الرأسية,Koma Vertikal
|
||||
ComaVerticalDesc,,垂直方向の正規化Zernikeコマ収差係数を指定します。,Sets the normalized vertical Zernike coma coefficient.,设置归一化垂直Zernike彗差系数。,設定歸一化垂直Zernike彗差係數。,정규화된 수직 Zernike 코마 계수를 설정합니다.,Establece el coeficiente de coma de Zernike vertical normalizado.,يضبط معامل الكوما الرأسي لـZernike المعياري.,Mengatur koefisien koma Zernike vertikal ternormalisasi.
|
||||
SphericalName,,球面収差,Spherical Aberration,球面像差,球面像差,구면 수차,Aberración esférica,الانحراف الكروي,Aberasi Sferis
|
||||
SphericalDesc,,正規化Zernike球面収差係数を指定します。,Sets the normalized Zernike spherical aberration coefficient.,设置归一化Zernike球面像差系数。,設定歸一化Zernike球面像差係數。,정규화된 Zernike 구면 수차 계수를 설정합니다.,Establece el coeficiente de aberración esférica de Zernike normalizado.,يضبط معامل الانحراف الكروي لـZernike المعياري.,Mengatur koefisien aberasi sferis Zernike ternormalisasi.
|
||||
TagDiffraction,,回折,diffraction,衍射,衍射,회절,difracción,الحيود,difraksi
|
||||
TagLens,,レンズ,lens,镜头,鏡頭,렌즈,lente,العدسة,lensa
|
||||
TagPsf,,点像分布関数,point spread function,点扩散函数,點擴散函數,점 확산 함수,función de dispersión puntual,دالة انتشار النقطة,fungsi penyebaran titik
|
||||
TagOptics,,光学,optics,光学,光學,광학,óptica,البصريات,optik
|
||||
|
@@ -1,112 +0,0 @@
|
||||
using System.ComponentModel;
|
||||
using System.ComponentModel.DataAnnotations;
|
||||
using YukkuriMovieMaker.Commons;
|
||||
using YukkuriMovieMaker.Controls;
|
||||
using YukkuriMovieMaker.Exo;
|
||||
using YukkuriMovieMaker.Player.Video;
|
||||
using YukkuriMovieMaker.Plugin.Effects;
|
||||
|
||||
namespace WaveOptics.Effects;
|
||||
|
||||
[VideoEffect(nameof(Texts.EffectName), [VideoEffectCategories.Filtering], [nameof(Texts.TagDiffraction), nameof(Texts.TagLens), nameof(Texts.TagPsf), nameof(Texts.TagOptics)], IsAviUtlSupported = false, ResourceType = typeof(Texts))]
|
||||
public sealed class WaveOpticsEffect : VideoEffectBase
|
||||
{
|
||||
public override string Label => Texts.EffectName;
|
||||
|
||||
[Display(GroupName = nameof(Texts.OutputGroup), Name = nameof(Texts.AmountName), Description = nameof(Texts.AmountDesc), Order = 0, ResourceType = typeof(Texts))]
|
||||
[AnimationSlider("F1", "%", 0, 100)]
|
||||
public Animation Amount { get; } = new(100, 0, 100);
|
||||
|
||||
[Display(GroupName = nameof(Texts.OutputGroup), Name = nameof(Texts.GainName), Description = nameof(Texts.GainDesc), Order = 1, ResourceType = typeof(Texts))]
|
||||
[AnimationSlider("F1", "%", 0, 400)]
|
||||
public Animation Gain { get; } = new(100, 0, 400);
|
||||
|
||||
[Display(GroupName = nameof(Texts.OpticsGroup), Name = nameof(Texts.WavelengthName), Description = nameof(Texts.WavelengthDesc), Order = 10, ResourceType = typeof(Texts))]
|
||||
[AnimationSlider("F1", "nm", 380, 780)]
|
||||
public Animation Wavelength { get; } = new(550, 380, 780);
|
||||
|
||||
[Display(GroupName = nameof(Texts.OpticsGroup), Name = nameof(Texts.FNumberName), Description = nameof(Texts.FNumberDesc), Order = 11, ResourceType = typeof(Texts))]
|
||||
[AnimationSlider("F2", "", 0.5, 32)]
|
||||
public Animation FNumber { get; } = new(8, 0.5, 64);
|
||||
|
||||
[Display(GroupName = nameof(Texts.OpticsGroup), Name = nameof(Texts.PixelPitchName), Description = nameof(Texts.PixelPitchDesc), Order = 12, ResourceType = typeof(Texts))]
|
||||
[AnimationSlider("F2", "μm", 0.5, 20)]
|
||||
public Animation PixelPitch { get; } = new(4, 0.25, 100);
|
||||
|
||||
[Display(GroupName = nameof(Texts.OpticsGroup), Name = nameof(Texts.KernelRadiusName), Description = nameof(Texts.KernelRadiusDesc), Order = 13, ResourceType = typeof(Texts))]
|
||||
[TextBoxSlider("F0", "px", 1, 15)]
|
||||
[Range(1, 15)]
|
||||
[DefaultValue(15)]
|
||||
public int KernelRadius { get => kernelRadius; set => Set(ref kernelRadius, Math.Clamp(value, 1, 15)); }
|
||||
int kernelRadius = 15;
|
||||
|
||||
[Display(GroupName = nameof(Texts.OpticsGroup), Name = nameof(Texts.QualityName), Description = nameof(Texts.QualityDesc), Order = 14, ResourceType = typeof(Texts))]
|
||||
[EnumComboBox]
|
||||
public WaveOpticsQuality Quality { get => quality; set => Set(ref quality, value); }
|
||||
WaveOpticsQuality quality = WaveOpticsQuality.Standard;
|
||||
|
||||
[Display(GroupName = nameof(Texts.ApertureGroup), Name = nameof(Texts.ApertureShapeName), Description = nameof(Texts.ApertureShapeDesc), Order = 20, ResourceType = typeof(Texts))]
|
||||
[EnumComboBox]
|
||||
public WaveOpticsApertureShape ApertureShape { get => apertureShape; set => Set(ref apertureShape, value); }
|
||||
WaveOpticsApertureShape apertureShape;
|
||||
|
||||
[Display(GroupName = nameof(Texts.ApertureGroup), Name = nameof(Texts.BladeCountName), Description = nameof(Texts.BladeCountDesc), Order = 21, ResourceType = typeof(Texts))]
|
||||
[TextBoxSlider("F0", "", 3, 16)]
|
||||
[Range(3, 32)]
|
||||
[DefaultValue(6)]
|
||||
public int BladeCount { get => bladeCount; set => Set(ref bladeCount, Math.Clamp(value, 3, 32)); }
|
||||
int bladeCount = 6;
|
||||
|
||||
[Display(GroupName = nameof(Texts.ApertureGroup), Name = nameof(Texts.BladeRotationName), Description = nameof(Texts.BladeRotationDesc), Order = 22, ResourceType = typeof(Texts))]
|
||||
[AnimationSlider("F1", "°", -180, 180)]
|
||||
public Animation BladeRotation { get; } = new(0, -360, 360);
|
||||
|
||||
[Display(GroupName = nameof(Texts.ApertureGroup), Name = nameof(Texts.ObstructionName), Description = nameof(Texts.ObstructionDesc), Order = 23, ResourceType = typeof(Texts))]
|
||||
[AnimationSlider("F1", "%", 0, 95)]
|
||||
public Animation Obstruction { get; } = new(0, 0, 95);
|
||||
|
||||
[Display(GroupName = nameof(Texts.AberrationGroup), Name = nameof(Texts.DefocusName), Description = nameof(Texts.DefocusDesc), Order = 30, ResourceType = typeof(Texts))]
|
||||
[AnimationSlider("F3", "waves", -3, 3)]
|
||||
public Animation Defocus { get; } = new(0, -10, 10);
|
||||
|
||||
[Display(GroupName = nameof(Texts.AberrationGroup), Name = nameof(Texts.AstigmatismVerticalName), Description = nameof(Texts.AstigmatismVerticalDesc), Order = 31, ResourceType = typeof(Texts))]
|
||||
[AnimationSlider("F3", "waves", -3, 3)]
|
||||
public Animation AstigmatismVertical { get; } = new(0, -10, 10);
|
||||
|
||||
[Display(GroupName = nameof(Texts.AberrationGroup), Name = nameof(Texts.AstigmatismObliqueName), Description = nameof(Texts.AstigmatismObliqueDesc), Order = 32, ResourceType = typeof(Texts))]
|
||||
[AnimationSlider("F3", "waves", -3, 3)]
|
||||
public Animation AstigmatismOblique { get; } = new(0, -10, 10);
|
||||
|
||||
[Display(GroupName = nameof(Texts.AberrationGroup), Name = nameof(Texts.ComaHorizontalName), Description = nameof(Texts.ComaHorizontalDesc), Order = 33, ResourceType = typeof(Texts))]
|
||||
[AnimationSlider("F3", "waves", -3, 3)]
|
||||
public Animation ComaHorizontal { get; } = new(0, -10, 10);
|
||||
|
||||
[Display(GroupName = nameof(Texts.AberrationGroup), Name = nameof(Texts.ComaVerticalName), Description = nameof(Texts.ComaVerticalDesc), Order = 34, ResourceType = typeof(Texts))]
|
||||
[AnimationSlider("F3", "waves", -3, 3)]
|
||||
public Animation ComaVertical { get; } = new(0, -10, 10);
|
||||
|
||||
[Display(GroupName = nameof(Texts.AberrationGroup), Name = nameof(Texts.SphericalName), Description = nameof(Texts.SphericalDesc), Order = 35, ResourceType = typeof(Texts))]
|
||||
[AnimationSlider("F3", "waves", -3, 3)]
|
||||
public Animation Spherical { get; } = new(0, -10, 10);
|
||||
|
||||
public override IEnumerable<string> CreateExoVideoFilters(int keyFrameIndex, ExoOutputDescription exoOutputDescription) => [];
|
||||
|
||||
public override IVideoEffectProcessor CreateVideoEffect(IGraphicsDevicesAndContext devices) => new WaveOpticsEffectProcessor(devices, this);
|
||||
|
||||
protected override IEnumerable<IAnimatable> GetAnimatables()
|
||||
{
|
||||
yield return Amount;
|
||||
yield return Gain;
|
||||
yield return Wavelength;
|
||||
yield return FNumber;
|
||||
yield return PixelPitch;
|
||||
yield return BladeRotation;
|
||||
yield return Obstruction;
|
||||
yield return Defocus;
|
||||
yield return AstigmatismVertical;
|
||||
yield return AstigmatismOblique;
|
||||
yield return ComaHorizontal;
|
||||
yield return ComaVertical;
|
||||
yield return Spherical;
|
||||
}
|
||||
}
|
||||
@@ -1,162 +0,0 @@
|
||||
using Vortice.Direct2D1;
|
||||
using WaveOptics.Abstractions;
|
||||
using WaveOptics.Optics;
|
||||
using WaveOptics.Rendering;
|
||||
using YukkuriMovieMaker.Commons;
|
||||
using YukkuriMovieMaker.Player.Video;
|
||||
using YukkuriMovieMaker.Player.Video.Effects;
|
||||
|
||||
namespace WaveOptics.Effects;
|
||||
|
||||
internal sealed class WaveOpticsEffectProcessor(IGraphicsDevicesAndContext devices, WaveOpticsEffect item) : VideoEffectProcessorBase(devices)
|
||||
{
|
||||
readonly IGraphicsDevicesAndContext devices = devices;
|
||||
readonly WaveOpticsEffect item = item;
|
||||
readonly FraunhoferPsfGenerator generator = new();
|
||||
|
||||
WaveOpticsConvolutionEffect? effect;
|
||||
ID2D1Bitmap? kernelBitmap;
|
||||
Parameters? currentParameters;
|
||||
float amount;
|
||||
float gain;
|
||||
bool isFirst = true;
|
||||
|
||||
public override DrawDescription Update(EffectDescription effectDescription)
|
||||
{
|
||||
if (IsPassThroughEffect || effect is null)
|
||||
return effectDescription.DrawDescription;
|
||||
|
||||
var frame = effectDescription.ItemPosition.Frame;
|
||||
var length = effectDescription.ItemDuration.Frame;
|
||||
var fps = effectDescription.FPS;
|
||||
var amount = Sanitize(item.Amount.GetValue(frame, length, fps) / 100d, 0, 1, 0);
|
||||
var gain = Sanitize(item.Gain.GetValue(frame, length, fps) / 100d, 0, 4, 1);
|
||||
var parameters = new Parameters(
|
||||
GetGridSize(item.Quality),
|
||||
item.KernelRadius * 2 + 1,
|
||||
Sanitize(item.Wavelength.GetValue(frame, length, fps), 380, 780, 550),
|
||||
Sanitize(item.FNumber.GetValue(frame, length, fps), 0.5, 64, 8),
|
||||
Sanitize(item.PixelPitch.GetValue(frame, length, fps), 0.25, 100, 4),
|
||||
item.ApertureShape,
|
||||
Math.Clamp(item.BladeCount, 3, 32),
|
||||
Sanitize(item.BladeRotation.GetValue(frame, length, fps), -360, 360, 0),
|
||||
Sanitize(item.Obstruction.GetValue(frame, length, fps) / 100d, 0, 0.95, 0),
|
||||
Sanitize(item.Defocus.GetValue(frame, length, fps), -10, 10, 0),
|
||||
Sanitize(item.AstigmatismVertical.GetValue(frame, length, fps), -10, 10, 0),
|
||||
Sanitize(item.AstigmatismOblique.GetValue(frame, length, fps), -10, 10, 0),
|
||||
Sanitize(item.ComaHorizontal.GetValue(frame, length, fps), -10, 10, 0),
|
||||
Sanitize(item.ComaVertical.GetValue(frame, length, fps), -10, 10, 0),
|
||||
Sanitize(item.Spherical.GetValue(frame, length, fps), -10, 10, 0));
|
||||
|
||||
if (currentParameters != parameters)
|
||||
UpdateKernel(parameters);
|
||||
if (isFirst || this.amount != amount)
|
||||
effect.Amount = amount;
|
||||
if (isFirst || this.gain != gain)
|
||||
effect.Gain = gain;
|
||||
|
||||
isFirst = false;
|
||||
this.amount = amount;
|
||||
this.gain = gain;
|
||||
currentParameters = parameters;
|
||||
return effectDescription.DrawDescription;
|
||||
}
|
||||
|
||||
void UpdateKernel(Parameters parameters)
|
||||
{
|
||||
if (effect is null)
|
||||
return;
|
||||
|
||||
var aberration = new WavefrontAberration(
|
||||
defocusWaves: parameters.Defocus,
|
||||
astigmatismVerticalWaves: parameters.AstigmatismVertical,
|
||||
astigmatismObliqueWaves: parameters.AstigmatismOblique,
|
||||
comaHorizontalWaves: parameters.ComaHorizontal,
|
||||
comaVerticalWaves: parameters.ComaVertical,
|
||||
sphericalWaves: parameters.Spherical);
|
||||
var descriptor = new PsfDescriptor(
|
||||
parameters.GridSize,
|
||||
parameters.GridSize / 4,
|
||||
parameters.KernelSize,
|
||||
parameters.Wavelength,
|
||||
parameters.FNumber,
|
||||
parameters.PixelPitch,
|
||||
parameters.ApertureShape == WaveOpticsApertureShape.Circular ? ApertureShape.Circular : ApertureShape.RegularPolygon,
|
||||
parameters.BladeCount,
|
||||
parameters.BladeRotation,
|
||||
parameters.Obstruction,
|
||||
aberration);
|
||||
var result = generator.Generate(descriptor);
|
||||
var nextBitmap = PsfBitmapFactory.Create(devices.DeviceContext, result.Kernel);
|
||||
|
||||
effect.SetKernel(null);
|
||||
disposer.RemoveAndDispose(ref kernelBitmap);
|
||||
kernelBitmap = nextBitmap;
|
||||
disposer.Collect(kernelBitmap);
|
||||
effect.KernelSize = result.Kernel.Size;
|
||||
effect.SetKernel(kernelBitmap);
|
||||
}
|
||||
|
||||
static int GetGridSize(WaveOpticsQuality quality)
|
||||
{
|
||||
return quality switch
|
||||
{
|
||||
WaveOpticsQuality.Draft => 128,
|
||||
WaveOpticsQuality.High => 512,
|
||||
_ => 256,
|
||||
};
|
||||
}
|
||||
|
||||
static float Sanitize(double value, double minimum, double maximum, double fallback)
|
||||
{
|
||||
if (!double.IsFinite(value))
|
||||
return (float)fallback;
|
||||
return (float)Math.Clamp(value, minimum, maximum);
|
||||
}
|
||||
|
||||
protected override ID2D1Image? CreateEffect(IGraphicsDevicesAndContext devices)
|
||||
{
|
||||
effect = new WaveOpticsConvolutionEffect(devices);
|
||||
if (!effect.IsEnabled)
|
||||
{
|
||||
effect.Dispose();
|
||||
effect = null;
|
||||
return null;
|
||||
}
|
||||
disposer.Collect(effect);
|
||||
|
||||
var output = effect.Output;
|
||||
disposer.Collect(output);
|
||||
return output;
|
||||
}
|
||||
|
||||
protected override void setInput(ID2D1Image? input)
|
||||
{
|
||||
effect?.SetSource(input);
|
||||
}
|
||||
|
||||
protected override void ClearEffectChain()
|
||||
{
|
||||
effect?.SetSource(null);
|
||||
effect?.SetKernel(null);
|
||||
currentParameters = null;
|
||||
isFirst = true;
|
||||
}
|
||||
|
||||
readonly record struct Parameters(
|
||||
int GridSize,
|
||||
int KernelSize,
|
||||
float Wavelength,
|
||||
float FNumber,
|
||||
float PixelPitch,
|
||||
WaveOpticsApertureShape ApertureShape,
|
||||
int BladeCount,
|
||||
float BladeRotation,
|
||||
float Obstruction,
|
||||
float Defocus,
|
||||
float AstigmatismVertical,
|
||||
float AstigmatismOblique,
|
||||
float ComaHorizontal,
|
||||
float ComaVertical,
|
||||
float Spherical);
|
||||
}
|
||||
@@ -1,92 +0,0 @@
|
||||
using System.Numerics;
|
||||
|
||||
namespace WaveOptics.Fourier;
|
||||
|
||||
internal static class FastFourierTransform
|
||||
{
|
||||
public static void Forward(Span<Complex> values) => Transform(values, false);
|
||||
|
||||
public static void Inverse(Span<Complex> values) => Transform(values, true);
|
||||
|
||||
public static void Forward2D(Complex[] values, int width, int height) => Transform2D(values, width, height, false);
|
||||
|
||||
public static void Inverse2D(Complex[] values, int width, int height) => Transform2D(values, width, height, true);
|
||||
|
||||
static void Transform(Span<Complex> values, bool inverse)
|
||||
{
|
||||
var count = values.Length;
|
||||
if (count == 0 || !BitOperations.IsPow2((uint)count))
|
||||
throw new ArgumentException(nameof(values));
|
||||
|
||||
var target = 0;
|
||||
for (var source = 1; source < count; source++)
|
||||
{
|
||||
var bit = count >> 1;
|
||||
while ((target & bit) != 0)
|
||||
{
|
||||
target ^= bit;
|
||||
bit >>= 1;
|
||||
}
|
||||
target ^= bit;
|
||||
if (source < target)
|
||||
(values[source], values[target]) = (values[target], values[source]);
|
||||
}
|
||||
|
||||
for (var length = 2; length <= count; length <<= 1)
|
||||
{
|
||||
var angle = (inverse ? 2d : -2d) * Math.PI / length;
|
||||
var step = Complex.FromPolarCoordinates(1d, angle);
|
||||
var half = length >> 1;
|
||||
for (var offset = 0; offset < count; offset += length)
|
||||
{
|
||||
var factor = Complex.One;
|
||||
for (var index = 0; index < half; index++)
|
||||
{
|
||||
var even = values[offset + index];
|
||||
var odd = values[offset + index + half] * factor;
|
||||
values[offset + index] = even + odd;
|
||||
values[offset + index + half] = even - odd;
|
||||
factor *= step;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if (!inverse)
|
||||
return;
|
||||
|
||||
var scale = 1d / count;
|
||||
for (var index = 0; index < count; index++)
|
||||
values[index] *= scale;
|
||||
}
|
||||
|
||||
static void Transform2D(Complex[] values, int width, int height, bool inverse)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(values);
|
||||
if (values.Length != width * height)
|
||||
throw new ArgumentException(nameof(values));
|
||||
if (!BitOperations.IsPow2((uint)width) || !BitOperations.IsPow2((uint)height))
|
||||
throw new ArgumentException(nameof(width));
|
||||
|
||||
for (var y = 0; y < height; y++)
|
||||
{
|
||||
var row = values.AsSpan(y * width, width);
|
||||
if (inverse)
|
||||
Inverse(row);
|
||||
else
|
||||
Forward(row);
|
||||
}
|
||||
|
||||
var column = new Complex[height];
|
||||
for (var x = 0; x < width; x++)
|
||||
{
|
||||
for (var y = 0; y < height; y++)
|
||||
column[y] = values[y * width + x];
|
||||
if (inverse)
|
||||
Inverse(column);
|
||||
else
|
||||
Forward(column);
|
||||
for (var y = 0; y < height; y++)
|
||||
values[y * width + x] = column[y];
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,139 +0,0 @@
|
||||
using System.Numerics;
|
||||
using WaveOptics.Abstractions;
|
||||
using WaveOptics.Fourier;
|
||||
|
||||
namespace WaveOptics.Optics;
|
||||
|
||||
public sealed class FraunhoferPsfGenerator : IPsfGenerator
|
||||
{
|
||||
const double TwoPi = 2 * Math.PI;
|
||||
|
||||
public OpticalApiVersion ApiVersion => OpticalApiVersion.Current;
|
||||
|
||||
public OpticalCapabilities Capabilities => OpticalCapabilities.MonochromaticPsf
|
||||
| OpticalCapabilities.CircularAperture
|
||||
| OpticalCapabilities.RegularPolygonAperture
|
||||
| OpticalCapabilities.CentralObstruction
|
||||
| OpticalCapabilities.ZernikeAberration
|
||||
| OpticalCapabilities.DirectConvolution;
|
||||
|
||||
public PsfGenerationResult Generate(PsfDescriptor descriptor)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(descriptor);
|
||||
|
||||
var gridSize = descriptor.PupilGridSize;
|
||||
var pupilDiameter = descriptor.PupilDiameterSamples;
|
||||
var pupil = new Complex[gridSize * gridSize];
|
||||
var center = gridSize / 2;
|
||||
var pupilRadius = pupilDiameter / 2d;
|
||||
var rotation = descriptor.BladeRotationDegrees * Math.PI / 180d;
|
||||
var openSampleCount = 0;
|
||||
|
||||
for (var y = 0; y < gridSize; y++)
|
||||
{
|
||||
var normalizedY = (y - center) / pupilRadius;
|
||||
for (var x = 0; x < gridSize; x++)
|
||||
{
|
||||
var normalizedX = (x - center) / pupilRadius;
|
||||
if (!IsInsideAperture(normalizedX, normalizedY, descriptor, rotation))
|
||||
continue;
|
||||
|
||||
var waves = ZernikeWavefront.Evaluate(normalizedX, normalizedY, descriptor.Aberration);
|
||||
pupil[y * gridSize + x] = Complex.FromPolarCoordinates(1d, TwoPi * waves);
|
||||
openSampleCount++;
|
||||
}
|
||||
}
|
||||
|
||||
if (openSampleCount == 0)
|
||||
throw new InvalidOperationException();
|
||||
|
||||
FastFourierTransform.Forward2D(pupil, gridSize, gridSize);
|
||||
var intensity = new double[pupil.Length];
|
||||
var fullEnergy = 0d;
|
||||
for (var y = 0; y < gridSize; y++)
|
||||
{
|
||||
var sourceY = (y + center) % gridSize;
|
||||
for (var x = 0; x < gridSize; x++)
|
||||
{
|
||||
var sourceX = (x + center) % gridSize;
|
||||
var value = pupil[sourceY * gridSize + sourceX].Magnitude;
|
||||
value *= value;
|
||||
intensity[y * gridSize + x] = value;
|
||||
fullEnergy += value;
|
||||
}
|
||||
}
|
||||
|
||||
if (!double.IsFinite(fullEnergy) || fullEnergy <= 0)
|
||||
throw new InvalidOperationException();
|
||||
|
||||
var inverseEnergy = 1d / fullEnergy;
|
||||
for (var index = 0; index < intensity.Length; index++)
|
||||
intensity[index] *= inverseEnergy;
|
||||
|
||||
var wavelengthMicrometers = descriptor.WavelengthNanometers / 1000d;
|
||||
var focalPlaneSamplePitch = wavelengthMicrometers * descriptor.FNumber * pupilDiameter / gridSize;
|
||||
var kernel = new double[descriptor.KernelSize * descriptor.KernelSize];
|
||||
var kernelRadius = descriptor.KernelSize / 2;
|
||||
var unnormalizedKernelEnergy = 0d;
|
||||
|
||||
for (var y = 0; y < descriptor.KernelSize; y++)
|
||||
{
|
||||
var physicalY = (y - kernelRadius) * descriptor.SensorPixelPitchMicrometers;
|
||||
var sampleY = center + physicalY / focalPlaneSamplePitch;
|
||||
for (var x = 0; x < descriptor.KernelSize; x++)
|
||||
{
|
||||
var physicalX = (x - kernelRadius) * descriptor.SensorPixelPitchMicrometers;
|
||||
var sampleX = center + physicalX / focalPlaneSamplePitch;
|
||||
var value = SampleBilinear(intensity, gridSize, sampleX, sampleY);
|
||||
kernel[y * descriptor.KernelSize + x] = value;
|
||||
unnormalizedKernelEnergy += value;
|
||||
}
|
||||
}
|
||||
|
||||
if (!double.IsFinite(unnormalizedKernelEnergy) || unnormalizedKernelEnergy <= 0)
|
||||
throw new InvalidOperationException();
|
||||
|
||||
var psfKernel = new PsfKernel(descriptor.KernelSize, kernel);
|
||||
var diagnostics = new PsfDiagnostics(
|
||||
openSampleCount,
|
||||
focalPlaneSamplePitch,
|
||||
unnormalizedKernelEnergy,
|
||||
psfKernel.Values.Span.ToArray().Max());
|
||||
return new PsfGenerationResult(psfKernel, diagnostics);
|
||||
}
|
||||
|
||||
static bool IsInsideAperture(double x, double y, PsfDescriptor descriptor, double rotation)
|
||||
{
|
||||
var radiusSquared = x * x + y * y;
|
||||
var obstructionSquared = descriptor.CentralObstructionRatio * descriptor.CentralObstructionRatio;
|
||||
if (radiusSquared > 1d || radiusSquared < obstructionSquared)
|
||||
return false;
|
||||
if (descriptor.ApertureShape == ApertureShape.Circular)
|
||||
return true;
|
||||
|
||||
var radius = Math.Sqrt(radiusSquared);
|
||||
if (radius == 0)
|
||||
return descriptor.CentralObstructionRatio == 0;
|
||||
var sector = TwoPi / descriptor.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);
|
||||
return radius <= boundary;
|
||||
}
|
||||
|
||||
static double SampleBilinear(double[] values, int size, double x, double y)
|
||||
{
|
||||
if (x < 0 || y < 0 || x > size - 1 || y > size - 1)
|
||||
return 0;
|
||||
|
||||
var x0 = (int)Math.Floor(x);
|
||||
var y0 = (int)Math.Floor(y);
|
||||
var x1 = Math.Min(x0 + 1, size - 1);
|
||||
var y1 = Math.Min(y0 + 1, size - 1);
|
||||
var tx = x - x0;
|
||||
var ty = y - y0;
|
||||
var top = values[y0 * size + x0] * (1 - tx) + values[y0 * size + x1] * tx;
|
||||
var bottom = values[y1 * size + x0] * (1 - tx) + values[y1 * size + x1] * tx;
|
||||
return top * (1 - ty) + bottom * ty;
|
||||
}
|
||||
}
|
||||
@@ -1,45 +0,0 @@
|
||||
using System.Runtime.InteropServices;
|
||||
using Vortice.DCommon;
|
||||
using Vortice.Direct2D1;
|
||||
using Vortice.DXGI;
|
||||
using Vortice.Mathematics;
|
||||
using WaveOptics.Abstractions;
|
||||
|
||||
namespace WaveOptics.Rendering;
|
||||
|
||||
internal static class PsfBitmapFactory
|
||||
{
|
||||
public static ID2D1Bitmap Create(ID2D1DeviceContext deviceContext, PsfKernel kernel)
|
||||
{
|
||||
var values = kernel.Values.Span;
|
||||
var pixels = new float[values.Length * 4];
|
||||
for (var index = 0; index < values.Length; index++)
|
||||
{
|
||||
var value = (float)values[index];
|
||||
var offset = index * 4;
|
||||
pixels[offset] = value;
|
||||
pixels[offset + 1] = value;
|
||||
pixels[offset + 2] = value;
|
||||
pixels[offset + 3] = 1;
|
||||
}
|
||||
|
||||
var handle = GCHandle.Alloc(pixels, GCHandleType.Pinned);
|
||||
try
|
||||
{
|
||||
var properties = new BitmapProperties1(
|
||||
new PixelFormat(Format.R32G32B32A32_Float, Vortice.DCommon.AlphaMode.Ignore),
|
||||
96,
|
||||
96,
|
||||
BitmapOptions.None);
|
||||
return ((ID2D1DeviceContext1)deviceContext).CreateBitmap(
|
||||
new SizeI(kernel.Size, kernel.Size),
|
||||
handle.AddrOfPinnedObject(),
|
||||
kernel.Size * 4 * sizeof(float),
|
||||
properties);
|
||||
}
|
||||
finally
|
||||
{
|
||||
handle.Free();
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,133 +0,0 @@
|
||||
using System.Numerics;
|
||||
using System.Runtime.InteropServices;
|
||||
using Vortice;
|
||||
using Vortice.Direct2D1;
|
||||
using YukkuriMovieMaker.Commons;
|
||||
using YukkuriMovieMaker.Player.Video;
|
||||
|
||||
namespace WaveOptics.Rendering;
|
||||
|
||||
internal sealed class WaveOpticsConvolutionEffect(IGraphicsDevicesAndContext devices)
|
||||
: D2D1CustomShaderEffectBase(Create<EffectImpl>(devices))
|
||||
{
|
||||
public const int MaximumKernelSize = 31;
|
||||
|
||||
public int KernelSize
|
||||
{
|
||||
get => GetIntValue((int)EffectImpl.Properties.KernelSize);
|
||||
set => SetValue((int)EffectImpl.Properties.KernelSize, value);
|
||||
}
|
||||
|
||||
public float Amount
|
||||
{
|
||||
get => GetFloatValue((int)EffectImpl.Properties.Amount);
|
||||
set => SetValue((int)EffectImpl.Properties.Amount, value);
|
||||
}
|
||||
|
||||
public float Gain
|
||||
{
|
||||
get => GetFloatValue((int)EffectImpl.Properties.Gain);
|
||||
set => SetValue((int)EffectImpl.Properties.Gain, value);
|
||||
}
|
||||
|
||||
public void SetSource(ID2D1Image? image) => SetInput(0, image, true);
|
||||
public void SetKernel(ID2D1Image? image) => SetInput(1, image, true);
|
||||
|
||||
[CustomEffect(2)]
|
||||
sealed class EffectImpl : D2D1CustomShaderEffectImplBase<EffectImpl>
|
||||
{
|
||||
ConstantBuffer constants;
|
||||
RawRect kernelRect;
|
||||
|
||||
[CustomEffectProperty(PropertyType.Int32, (int)Properties.KernelSize)]
|
||||
public int KernelSize
|
||||
{
|
||||
get => constants.KernelSize;
|
||||
set
|
||||
{
|
||||
var clamped = Math.Clamp(value, 1, MaximumKernelSize);
|
||||
constants.KernelSize = (clamped & 1) == 0 ? clamped - 1 : clamped;
|
||||
UpdateConstants();
|
||||
}
|
||||
}
|
||||
|
||||
[CustomEffectProperty(PropertyType.Float, (int)Properties.Amount)]
|
||||
public float Amount
|
||||
{
|
||||
get => constants.Amount;
|
||||
set
|
||||
{
|
||||
constants.Amount = float.IsFinite(value) ? Math.Clamp(value, 0, 1) : 0;
|
||||
UpdateConstants();
|
||||
}
|
||||
}
|
||||
|
||||
[CustomEffectProperty(PropertyType.Float, (int)Properties.Gain)]
|
||||
public float Gain
|
||||
{
|
||||
get => constants.Gain;
|
||||
set
|
||||
{
|
||||
constants.Gain = float.IsFinite(value) ? Math.Clamp(value, 0, 4) : 1;
|
||||
UpdateConstants();
|
||||
}
|
||||
}
|
||||
|
||||
public EffectImpl() : base(ShaderResourceUri.Get("WaveOpticsConvolution"))
|
||||
{
|
||||
constants.KernelSize = 1;
|
||||
constants.Gain = 1;
|
||||
}
|
||||
|
||||
protected override void UpdateConstants()
|
||||
{
|
||||
drawInformation?.SetPixelShaderConstantBuffer(constants);
|
||||
}
|
||||
|
||||
public override void MapInputRectsToOutputRect(RawRect[] inputRects, RawRect[] inputOpaqueSubRects, out RawRect outputRect, out RawRect outputOpaqueSubRect)
|
||||
{
|
||||
inputRect = inputRects[0];
|
||||
kernelRect = inputRects[1];
|
||||
constants.InputBounds = new Vector4(inputRect.Left, inputRect.Top, inputRect.Right, inputRect.Bottom);
|
||||
UpdateConstants();
|
||||
outputRect = Inflate(inputRect, GetRadius());
|
||||
outputOpaqueSubRect = default;
|
||||
}
|
||||
|
||||
public override void MapOutputRectToInputRects(RawRect outputRect, RawRect[] inputRects)
|
||||
{
|
||||
inputRects[0] = Inflate(outputRect, GetRadius());
|
||||
inputRects[1] = kernelRect;
|
||||
}
|
||||
|
||||
int GetRadius() => constants.Amount > 0 ? constants.KernelSize / 2 : 0;
|
||||
|
||||
static RawRect Inflate(RawRect rect, int radius)
|
||||
{
|
||||
return new RawRect(
|
||||
Saturate((long)rect.Left - radius),
|
||||
Saturate((long)rect.Top - radius),
|
||||
Saturate((long)rect.Right + radius),
|
||||
Saturate((long)rect.Bottom + radius));
|
||||
}
|
||||
|
||||
static int Saturate(long value) => (int)Math.Clamp(value, int.MinValue, int.MaxValue);
|
||||
|
||||
[StructLayout(LayoutKind.Sequential)]
|
||||
struct ConstantBuffer
|
||||
{
|
||||
public int KernelSize;
|
||||
public float Amount;
|
||||
public float Gain;
|
||||
public float Padding;
|
||||
public Vector4 InputBounds;
|
||||
}
|
||||
|
||||
public enum Properties
|
||||
{
|
||||
KernelSize,
|
||||
Amount,
|
||||
Gain,
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,55 +0,0 @@
|
||||
Texture2D InputTexture : register(t0);
|
||||
Texture2D KernelTexture : register(t1);
|
||||
SamplerState InputSampler : register(s0);
|
||||
|
||||
static const int MaximumRadius = 15;
|
||||
|
||||
cbuffer Constants : register(b0)
|
||||
{
|
||||
int kernelSize : packoffset(c0.x);
|
||||
float amount : packoffset(c0.y);
|
||||
float gain : packoffset(c0.z);
|
||||
float4 inputBounds : packoffset(c1);
|
||||
};
|
||||
|
||||
float4 SampleInput(float2 uv, float2 scenePosition)
|
||||
{
|
||||
if (scenePosition.x < inputBounds.x || scenePosition.y < inputBounds.y ||
|
||||
scenePosition.x >= inputBounds.z || scenePosition.y >= inputBounds.w)
|
||||
return (float4)0;
|
||||
return InputTexture.SampleLevel(InputSampler, uv, 0);
|
||||
}
|
||||
|
||||
float4 main(
|
||||
float4 position : SV_POSITION,
|
||||
float4 scenePosition : SCENE_POSITION,
|
||||
float4 uv0 : TEXCOORD0,
|
||||
float4 uv1 : TEXCOORD1
|
||||
) : SV_TARGET
|
||||
{
|
||||
float4 source = SampleInput(uv0.xy, scenePosition.xy);
|
||||
if (amount <= 0.0f || kernelSize <= 1)
|
||||
return source;
|
||||
|
||||
int radius = clamp(kernelSize / 2, 0, MaximumRadius);
|
||||
float4 convolved = (float4)0;
|
||||
|
||||
[loop]
|
||||
for (int y = -MaximumRadius; y <= MaximumRadius; y++)
|
||||
{
|
||||
if (abs(y) > radius)
|
||||
continue;
|
||||
[loop]
|
||||
for (int x = -MaximumRadius; x <= MaximumRadius; x++)
|
||||
{
|
||||
if (abs(x) > radius)
|
||||
continue;
|
||||
float weight = KernelTexture.Load(int3(x + radius, y + radius, 0)).r;
|
||||
float2 offset = float2(x, y);
|
||||
convolved += SampleInput(uv0.xy + offset * uv0.zw, scenePosition.xy + offset) * weight;
|
||||
}
|
||||
}
|
||||
|
||||
convolved *= gain;
|
||||
return lerp(source, convolved, amount);
|
||||
}
|
||||
@@ -0,0 +1,57 @@
|
||||
using System.IO;
|
||||
using System.Reflection;
|
||||
using System.Text.Encodings.Web;
|
||||
using System.Text.Json;
|
||||
|
||||
namespace WaveOptics.Harness;
|
||||
|
||||
internal sealed record GoldenCase(string Name, IReadOnlyList<int> Frames, string Hash);
|
||||
|
||||
internal sealed record Golden(string Adapter, string Driver, string Input, string Canvas, IReadOnlyList<GoldenCase> Cases)
|
||||
{
|
||||
const string FileName = "golden";
|
||||
const string Extension = ".json";
|
||||
const string CpuSuffix = "-cpu";
|
||||
const string DirectoryKey = "HarnessDirectory";
|
||||
|
||||
static readonly JsonSerializerOptions Options = new()
|
||||
{
|
||||
Encoder = JavaScriptEncoder.UnsafeRelaxedJsonEscaping,
|
||||
PropertyNamingPolicy = JsonNamingPolicy.CamelCase,
|
||||
WriteIndented = true,
|
||||
NewLine = "\n",
|
||||
};
|
||||
|
||||
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)
|
||||
{
|
||||
if (!File.Exists(path))
|
||||
throw new HarnessException($"基準値がありません。先に --golden で書いてください。{path}");
|
||||
Golden? golden;
|
||||
try
|
||||
{
|
||||
golden = JsonSerializer.Deserialize<Golden>(File.ReadAllBytes(path), Options);
|
||||
}
|
||||
catch (JsonException exception)
|
||||
{
|
||||
throw new HarnessException($"基準値を読めません。{path} {exception.Message}");
|
||||
}
|
||||
|
||||
if (golden is not { Adapter: not null, Driver: not null, Input: not null, Canvas: not null, Cases: not null }
|
||||
|| golden.Cases.Any(item => item is not { Name: not null, Frames: not null, Hash: not null }))
|
||||
throw new HarnessException($"基準値の項目が足りません。{path}");
|
||||
if (golden.Cases.Select(item => item.Name).Distinct(StringComparer.Ordinal).Count() != golden.Cases.Count)
|
||||
throw new HarnessException($"基準値のケース名が重複しています。{path}");
|
||||
return golden;
|
||||
}
|
||||
|
||||
public void Save(string path) => File.WriteAllBytes(path, JsonSerializer.SerializeToUtf8Bytes(this, Options));
|
||||
|
||||
static string ReadDirectory()
|
||||
=> typeof(Golden).Assembly
|
||||
.GetCustomAttributes<AssemblyMetadataAttribute>()
|
||||
.FirstOrDefault(attribute => string.Equals(attribute.Key, DirectoryKey, StringComparison.Ordinal))
|
||||
?.Value ?? throw new HarnessException($"アセンブリに {DirectoryKey} がありません。");
|
||||
}
|
||||
@@ -0,0 +1,63 @@
|
||||
using System.Diagnostics;
|
||||
using Vortice.Direct3D11;
|
||||
|
||||
namespace WaveOptics.Harness;
|
||||
|
||||
internal sealed class GpuTimer : IDisposable
|
||||
{
|
||||
static readonly TimeSpan ResolveTimeout = TimeSpan.FromSeconds(5);
|
||||
|
||||
readonly ID3D11DeviceContext context;
|
||||
readonly ID3D11Query disjoint;
|
||||
readonly ID3D11Query start;
|
||||
readonly ID3D11Query stop;
|
||||
|
||||
public GpuTimer(ID3D11Device device, ID3D11DeviceContext context)
|
||||
{
|
||||
this.context = context;
|
||||
disjoint = device.CreateQuery(new QueryDescription(QueryType.TimestampDisjoint, QueryFlags.None));
|
||||
start = device.CreateQuery(new QueryDescription(QueryType.Timestamp, QueryFlags.None));
|
||||
stop = device.CreateQuery(new QueryDescription(QueryType.Timestamp, QueryFlags.None));
|
||||
}
|
||||
|
||||
public void Begin()
|
||||
{
|
||||
context.Begin(disjoint);
|
||||
context.End(start);
|
||||
}
|
||||
|
||||
public void End()
|
||||
{
|
||||
context.End(stop);
|
||||
context.End(disjoint);
|
||||
}
|
||||
|
||||
public TimeSpan? Resolve()
|
||||
{
|
||||
if (!Wait<QueryDataTimestampDisjoint>(disjoint, out var timing) || timing.Disjoint || timing.Frequency == 0UL)
|
||||
return null;
|
||||
if (!Wait<ulong>(start, out var began) || !Wait<ulong>(stop, out var ended) || ended < began)
|
||||
return null;
|
||||
return TimeSpan.FromSeconds((ended - began) / (double)timing.Frequency);
|
||||
}
|
||||
|
||||
bool Wait<T>(ID3D11Query query, out T value) where T : unmanaged
|
||||
{
|
||||
var elapsed = Stopwatch.StartNew();
|
||||
while (!context.GetData(query, out value))
|
||||
{
|
||||
if (elapsed.Elapsed > ResolveTimeout)
|
||||
return false;
|
||||
Thread.Yield();
|
||||
}
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
public void Dispose()
|
||||
{
|
||||
stop.Dispose();
|
||||
start.Dispose();
|
||||
disjoint.Dispose();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,100 @@
|
||||
namespace WaveOptics.Harness;
|
||||
|
||||
internal sealed class HarnessException(string message) : Exception(message);
|
||||
|
||||
internal enum HarnessMode
|
||||
{
|
||||
Render,
|
||||
Golden,
|
||||
Verify,
|
||||
Transition,
|
||||
Compare,
|
||||
Benchmark,
|
||||
Convolution,
|
||||
}
|
||||
|
||||
internal sealed record HarnessArguments(HarnessMode Mode, string? Input, string? OutputDirectory, string? Before, string? After, bool Cpu)
|
||||
{
|
||||
public const string Usage = """
|
||||
使い方:
|
||||
[<出力先>] [--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++)
|
||||
{
|
||||
var argument = arguments[index];
|
||||
switch (argument)
|
||||
{
|
||||
case "--golden":
|
||||
mode = Select(mode, HarnessMode.Golden);
|
||||
break;
|
||||
case "--verify":
|
||||
mode = Select(mode, HarnessMode.Verify);
|
||||
break;
|
||||
case "--transition":
|
||||
mode = Select(mode, HarnessMode.Transition);
|
||||
break;
|
||||
case "--compare":
|
||||
mode = Select(mode, HarnessMode.Compare);
|
||||
break;
|
||||
case "--benchmark":
|
||||
mode = Select(mode, HarnessMode.Benchmark);
|
||||
break;
|
||||
case "--convolution":
|
||||
mode = Select(mode, HarnessMode.Convolution);
|
||||
break;
|
||||
case "--cpu":
|
||||
cpu = true;
|
||||
break;
|
||||
case "--input":
|
||||
if (index + 1 >= arguments.Length)
|
||||
throw new HarnessException("--input には画像のパスを続けてください。");
|
||||
input = arguments[++index];
|
||||
break;
|
||||
default:
|
||||
if (argument.StartsWith('-'))
|
||||
throw new HarnessException($"不明なオプションです。{argument}");
|
||||
positionals.Add(argument);
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
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:
|
||||
if (positionals.Count != 2)
|
||||
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], 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, cpu);
|
||||
default:
|
||||
if (positionals.Count > 0)
|
||||
throw new HarnessException($"余分な引数です。{positionals[0]}");
|
||||
return new HarnessArguments(selected, input, null, null, null, cpu);
|
||||
}
|
||||
}
|
||||
|
||||
static HarnessMode Select(HarnessMode? current, HarnessMode next)
|
||||
=> current is null ? next : throw new HarnessException("モードは 1 つだけ指定してください。");
|
||||
}
|
||||
@@ -0,0 +1,178 @@
|
||||
using System.Globalization;
|
||||
using WaveOptics.Effects;
|
||||
using YukkuriMovieMaker.Commons;
|
||||
using YukkuriMovieMaker.Json;
|
||||
|
||||
namespace WaveOptics.Harness;
|
||||
|
||||
internal static class HarnessCases
|
||||
{
|
||||
public static IEnumerable<(string Name, WaveOpticsEffect Effect, IReadOnlyList<int> Frames)> All()
|
||||
{
|
||||
yield return ("default", Create(), [0]);
|
||||
yield return ("default-frames-0-8", Create(), Enumerable.Range(0, 9).ToArray());
|
||||
yield return ("amount-0", Create(effect => effect.Amount.Values[0].Value = 0), [0]);
|
||||
yield return ("amount-50", Create(effect => effect.Amount.Values[0].Value = 50), [0]);
|
||||
yield return ("gain-50", Create(effect => effect.Gain.Values[0].Value = 50), [0]);
|
||||
yield return ("gain-400", Create(effect => effect.Gain.Values[0].Value = 400), [0]);
|
||||
yield return ("gain-400-amount-50", Create(effect =>
|
||||
{
|
||||
effect.Gain.Values[0].Value = 400;
|
||||
effect.Amount.Values[0].Value = 50;
|
||||
}), [0]);
|
||||
yield return ("wavelength-380", Create(effect => effect.Wavelength.Values[0].Value = 380), [0]);
|
||||
yield return ("wavelength-780", Create(effect => effect.Wavelength.Values[0].Value = 780), [0]);
|
||||
yield return ("f-number-4", Create(effect => effect.FNumber.Values[0].Value = 4), [0]);
|
||||
yield return ("f-number-64", Create(effect => effect.FNumber.Values[0].Value = 64), [0]);
|
||||
yield return ("pixel-pitch-0.25", Create(effect => effect.PixelPitch.Values[0].Value = 0.25), [0]);
|
||||
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]);
|
||||
yield return ("blade-count-3", Create(effect =>
|
||||
{
|
||||
effect.ApertureShape = WaveOpticsApertureShape.RegularPolygon;
|
||||
effect.BladeCount = 3;
|
||||
}), [0]);
|
||||
yield return ("blade-count-32", Create(effect =>
|
||||
{
|
||||
effect.ApertureShape = WaveOpticsApertureShape.RegularPolygon;
|
||||
effect.BladeCount = 32;
|
||||
}), [0]);
|
||||
yield return ("blade-rotation-30", Create(effect =>
|
||||
{
|
||||
effect.ApertureShape = WaveOpticsApertureShape.RegularPolygon;
|
||||
effect.BladeRotation.Values[0].Value = 30;
|
||||
}), [0]);
|
||||
yield return ("obstruction-50", Create(effect => effect.Obstruction.Values[0].Value = 50), [0]);
|
||||
yield return ("defocus-1", Create(effect => effect.Defocus.Values[0].Value = 1), [0]);
|
||||
yield return ("astigmatism-vertical-1", Create(effect => effect.AstigmatismVertical.Values[0].Value = 1), [0]);
|
||||
yield return ("astigmatism-oblique-1", Create(effect => effect.AstigmatismOblique.Values[0].Value = 1), [0]);
|
||||
yield return ("coma-horizontal-1", Create(effect => effect.ComaHorizontal.Values[0].Value = 1), [0]);
|
||||
yield return ("coma-vertical-1", Create(effect => effect.ComaVertical.Values[0].Value = 1), [0]);
|
||||
yield return ("spherical-1", Create(effect => effect.Spherical.Values[0].Value = 1), [0]);
|
||||
yield return ("defocus-animated-frames-0-8", Create(effect => effect.Defocus.CopyFrom(Linear(0d, 3d))), Enumerable.Range(0, 9).ToArray());
|
||||
yield return ("linear", Create(effect => effect.Linear = true), [0]);
|
||||
yield return ("linear-gain-150", Create(effect =>
|
||||
{
|
||||
effect.Linear = true;
|
||||
effect.Gain.Values[0].Value = 150;
|
||||
}), [0]);
|
||||
yield return ("linear-highlight-boost-30", Create(effect =>
|
||||
{
|
||||
effect.Linear = true;
|
||||
effect.HighlightThreshold.Values[0].Value = 70;
|
||||
effect.HighlightBoost.Values[0].Value = 30;
|
||||
}), [0]);
|
||||
yield return ("linear-highlight-threshold-50-boost-8", Create(effect =>
|
||||
{
|
||||
effect.Linear = true;
|
||||
effect.HighlightThreshold.Values[0].Value = 50;
|
||||
effect.HighlightBoost.Values[0].Value = 8;
|
||||
}), [0]);
|
||||
yield return ("dither", Create(effect => effect.Dither = true), [0]);
|
||||
yield return ("linear-dither-defocus-1", Create(effect =>
|
||||
{
|
||||
effect.Linear = true;
|
||||
effect.Dither = true;
|
||||
effect.Defocus.Values[0].Value = 1;
|
||||
}), [0]);
|
||||
yield return ("linear-highlight-polygon-defocus-2-radius-40", Create(effect =>
|
||||
{
|
||||
effect.Linear = true;
|
||||
effect.HighlightThreshold.Values[0].Value = 70;
|
||||
effect.HighlightBoost.Values[0].Value = 20;
|
||||
effect.ApertureShape = WaveOpticsApertureShape.RegularPolygon;
|
||||
effect.KernelRadius = 40;
|
||||
effect.Defocus.Values[0].Value = 2;
|
||||
}), [0]);
|
||||
yield return ("linear-highlight-animated-frames-0-8", Create(effect =>
|
||||
{
|
||||
effect.Linear = true;
|
||||
effect.HighlightThreshold.Values[0].Value = 70;
|
||||
effect.HighlightBoost.CopyFrom(Linear(1d, 40d));
|
||||
}), Enumerable.Range(0, 9).ToArray());
|
||||
}
|
||||
|
||||
public static IEnumerable<(string Name, Func<WaveOpticsEffect> Create, Action<WaveOpticsEffect> Change, int Frame)> Transitions()
|
||||
{
|
||||
yield return ("amount-100-to-50", () => Create(), effect => effect.Amount.Values[0].Value = 50, 0);
|
||||
yield return ("gain-100-to-400", () => Create(), effect => effect.Gain.Values[0].Value = 400, 0);
|
||||
yield return ("wavelength-550-to-780", () => Create(), effect => effect.Wavelength.Values[0].Value = 780, 0);
|
||||
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);
|
||||
yield return ("blade-rotation-0-to-30", () => Create(effect => effect.ApertureShape = WaveOpticsApertureShape.RegularPolygon), effect => effect.BladeRotation.Values[0].Value = 30, 0);
|
||||
yield return ("obstruction-0-to-50", () => Create(), effect => effect.Obstruction.Values[0].Value = 50, 0);
|
||||
yield return ("defocus-0-to-1", () => Create(), effect => effect.Defocus.Values[0].Value = 1, 0);
|
||||
yield return ("astigmatism-vertical-0-to-1", () => Create(), effect => effect.AstigmatismVertical.Values[0].Value = 1, 0);
|
||||
yield return ("astigmatism-oblique-0-to-1", () => Create(), effect => effect.AstigmatismOblique.Values[0].Value = 1, 0);
|
||||
yield return ("coma-horizontal-0-to-1", () => Create(), effect => effect.ComaHorizontal.Values[0].Value = 1, 0);
|
||||
yield return ("coma-vertical-0-to-1", () => Create(), effect => effect.ComaVertical.Values[0].Value = 1, 0);
|
||||
yield return ("spherical-0-to-1", () => Create(), effect => effect.Spherical.Values[0].Value = 1, 0);
|
||||
yield return ("amount-100-to-0", () => Create(), effect => effect.Amount.Values[0].Value = 0, 0);
|
||||
yield return ("linear-off-to-on", () => Create(), effect => effect.Linear = true, 0);
|
||||
yield return ("linear-on-to-off", () => Create(effect => effect.Linear = true), effect => effect.Linear = false, 0);
|
||||
yield return ("dither-off-to-on", () => Create(), effect => effect.Dither = true, 0);
|
||||
yield return ("dither-on-to-off", () => Create(effect => effect.Dither = true), effect => effect.Dither = false, 0);
|
||||
yield return ("highlight-boost-1-to-30", () => Create(effect =>
|
||||
{
|
||||
effect.Linear = true;
|
||||
effect.HighlightThreshold.Values[0].Value = 70;
|
||||
}), effect => effect.HighlightBoost.Values[0].Value = 30, 0);
|
||||
yield return ("highlight-threshold-95-to-50", () => Create(effect =>
|
||||
{
|
||||
effect.Linear = true;
|
||||
effect.HighlightBoost.Values[0].Value = 8;
|
||||
}), effect => effect.HighlightThreshold.Values[0].Value = 50, 0);
|
||||
yield return ("linear-gain-100-to-150", () => Create(effect => effect.Linear = true), effect => effect.Gain.Values[0].Value = 150, 0);
|
||||
}
|
||||
|
||||
public static IEnumerable<(string Name, WaveOpticsEffect Effect)> Benchmarks()
|
||||
{
|
||||
yield return ("quality-draft", Create(effect => effect.Quality = WaveOpticsQuality.Draft));
|
||||
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));
|
||||
}
|
||||
|
||||
static Animation Linear(double from, double to)
|
||||
=> Json.LoadFromText<Animation>(string.Create(CultureInfo.InvariantCulture, $$"""{"AnimationType":"直線移動","Values":[{"Value":{{from}}},{"Value":{{to}}}]}""")) ?? throw new HarnessException("アニメーションを読み込めません。");
|
||||
|
||||
public static WaveOpticsEffect Create(Action<WaveOpticsEffect>? configure = null)
|
||||
{
|
||||
var effect = new WaveOpticsEffect();
|
||||
configure?.Invoke(effect);
|
||||
return effect;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,59 @@
|
||||
using System.IO;
|
||||
using System.Security.Cryptography;
|
||||
using System.Windows.Media;
|
||||
using System.Windows.Media.Imaging;
|
||||
|
||||
namespace WaveOptics.Harness;
|
||||
|
||||
internal sealed record HarnessImage(int Width, int Height, byte[] Pixels, string Identity, string? Key)
|
||||
{
|
||||
public const int BytesPerPixel = 4;
|
||||
const int KeyLength = 16;
|
||||
|
||||
public static HarnessImage Synthetic(int width, int height)
|
||||
{
|
||||
var pixels = SyntheticImage.Create(width, height);
|
||||
return new HarnessImage(width, height, pixels, $"synthetic {width}x{height} {Convert.ToHexString(SHA256.HashData(pixels))[..KeyLength]}", null);
|
||||
}
|
||||
|
||||
public static HarnessImage Load(string path)
|
||||
{
|
||||
if (!File.Exists(path))
|
||||
throw new HarnessException($"入力の画像がありません。{path}");
|
||||
|
||||
var bytes = File.ReadAllBytes(path);
|
||||
var (width, height, pixels) = Decode(bytes, path);
|
||||
var hash = Convert.ToHexString(SHA256.HashData(bytes));
|
||||
return new HarnessImage(width, height, pixels, $"{hash} {width}x{height}", hash[..KeyLength]);
|
||||
}
|
||||
|
||||
public static (int Width, int Height, byte[] Pixels) LoadPremultiplied(string path) => Decode(File.ReadAllBytes(path), path);
|
||||
|
||||
public static void Save(string path, byte[] pixels, int width, int height)
|
||||
{
|
||||
var source = BitmapSource.Create(width, height, 96, 96, PixelFormats.Pbgra32, null, pixels, width * BytesPerPixel);
|
||||
var encoder = new PngBitmapEncoder();
|
||||
encoder.Frames.Add(BitmapFrame.Create(source));
|
||||
using var stream = File.Create(path);
|
||||
encoder.Save(stream);
|
||||
}
|
||||
|
||||
static (int Width, int Height, byte[] Pixels) Decode(byte[] bytes, string path)
|
||||
{
|
||||
using var stream = new MemoryStream(bytes);
|
||||
BitmapDecoder decoder;
|
||||
try
|
||||
{
|
||||
decoder = BitmapDecoder.Create(stream, BitmapCreateOptions.PreservePixelFormat, BitmapCacheOption.OnLoad);
|
||||
}
|
||||
catch (Exception exception) when (exception is NotSupportedException or FileFormatException)
|
||||
{
|
||||
throw new HarnessException($"画像として読めません。{path}");
|
||||
}
|
||||
|
||||
var converted = new FormatConvertedBitmap(decoder.Frames[0], PixelFormats.Pbgra32, null, 0d);
|
||||
var pixels = new byte[converted.PixelWidth * converted.PixelHeight * BytesPerPixel];
|
||||
converted.CopyPixels(pixels, converted.PixelWidth * BytesPerPixel, 0);
|
||||
return (converted.PixelWidth, converted.PixelHeight, pixels);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,280 @@
|
||||
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;
|
||||
using Vortice.DXGI;
|
||||
using Vortice.Mathematics;
|
||||
using YukkuriMovieMaker.Commons;
|
||||
using YukkuriMovieMaker.Player.Video;
|
||||
using YukkuriMovieMaker.Plugin.Effects;
|
||||
|
||||
namespace WaveOptics.Harness;
|
||||
|
||||
internal sealed class HarnessRenderer : IDisposable
|
||||
{
|
||||
const int Fps = 30;
|
||||
const int Length = 300;
|
||||
const int WarmupUpdates = 2000;
|
||||
const int UpdateRepeats = 20;
|
||||
const float Dpi = 96f;
|
||||
|
||||
static readonly PixelFormat PixelFormat = new(Format.B8G8R8A8_UNorm, Vortice.DCommon.AlphaMode.Premultiplied);
|
||||
|
||||
readonly GraphicsDevices devices;
|
||||
readonly IGraphicsDevicesAndContext context;
|
||||
readonly ID2D1Bitmap1 image;
|
||||
readonly ID2D1Bitmap1 target;
|
||||
readonly ID2D1Bitmap1 readback;
|
||||
readonly ID2D1Bitmap1 sync;
|
||||
readonly GpuTimer timer;
|
||||
readonly AffineTransform2D placement;
|
||||
readonly ID2D1Image centered;
|
||||
|
||||
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;
|
||||
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);
|
||||
target = CreateBitmap(deviceContext, canvasWidth, canvasHeight, BitmapOptions.Target);
|
||||
readback = CreateBitmap(deviceContext, canvasWidth, canvasHeight, BitmapOptions.CpuRead | BitmapOptions.CannotDraw);
|
||||
sync = CreateBitmap(deviceContext, 1, 1, BitmapOptions.CpuRead | BitmapOptions.CannotDraw);
|
||||
timer = new GpuTimer(devices.D3D.Device, devices.D3D.DeviceContext);
|
||||
|
||||
placement = new AffineTransform2D(deviceContext)
|
||||
{
|
||||
TransformMatrix = Matrix3x2.CreateTranslation(-source.Width * 0.5f, -source.Height * 0.5f),
|
||||
};
|
||||
placement.SetInput(0, image, true);
|
||||
centered = placement.Output;
|
||||
}
|
||||
|
||||
public int CanvasWidth { get; }
|
||||
|
||||
public int CanvasHeight { get; }
|
||||
|
||||
public string Adapter { get; }
|
||||
|
||||
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 = CreateProcessor(effect);
|
||||
processor.SetInput(centered);
|
||||
try
|
||||
{
|
||||
var rendered = new byte[frames.Count][];
|
||||
for (var index = 0; index < frames.Count; index++)
|
||||
{
|
||||
processor.Update(Describe(frames[index]));
|
||||
rendered[index] = Capture(processor.Output);
|
||||
}
|
||||
|
||||
return rendered;
|
||||
}
|
||||
finally
|
||||
{
|
||||
processor.ClearInput();
|
||||
}
|
||||
}
|
||||
|
||||
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
|
||||
{
|
||||
var settled = create();
|
||||
change(settled);
|
||||
var direct = Render(settled, [frame])[0];
|
||||
|
||||
var live = create();
|
||||
using var processor = CreateProcessor(live);
|
||||
processor.SetInput(centered);
|
||||
try
|
||||
{
|
||||
processor.Update(Describe(frame));
|
||||
_ = Capture(processor.Output);
|
||||
change(live);
|
||||
processor.Update(Describe(frame));
|
||||
return (direct, Capture(processor.Output));
|
||||
}
|
||||
finally
|
||||
{
|
||||
processor.ClearInput();
|
||||
}
|
||||
}
|
||||
|
||||
public Measurement Measure(IVideoEffect effect, int frames, bool moving)
|
||||
{
|
||||
var descriptions = new EffectDescription[frames];
|
||||
for (var frame = 0; frame < frames; frame++)
|
||||
descriptions[frame] = Describe(moving ? frame : 0);
|
||||
|
||||
using var processor = CreateProcessor(effect);
|
||||
processor.SetInput(centered);
|
||||
var output = processor.Output;
|
||||
try
|
||||
{
|
||||
for (var index = 0; index < WarmupUpdates; index++)
|
||||
processor.Update(descriptions[index % frames]);
|
||||
for (var frame = 0; frame < frames; frame++)
|
||||
{
|
||||
processor.Update(descriptions[frame]);
|
||||
Submit(output);
|
||||
}
|
||||
Synchronize();
|
||||
|
||||
var cpu = TimeSpan.MaxValue;
|
||||
for (var frame = 0; frame < frames; frame++)
|
||||
{
|
||||
var elapsed = Stopwatch.StartNew();
|
||||
processor.Update(descriptions[frame]);
|
||||
Submit(output);
|
||||
elapsed.Stop();
|
||||
cpu = elapsed.Elapsed < cpu ? elapsed.Elapsed : cpu;
|
||||
}
|
||||
Synchronize();
|
||||
|
||||
TimeSpan? gpu = null;
|
||||
for (var frame = 0; frame < frames; frame++)
|
||||
{
|
||||
processor.Update(descriptions[frame]);
|
||||
timer.Begin();
|
||||
Submit(output);
|
||||
timer.End();
|
||||
if (timer.Resolve() is { } resolved && (gpu is null || resolved < gpu))
|
||||
gpu = resolved;
|
||||
}
|
||||
Synchronize();
|
||||
|
||||
var repeats = frames * UpdateRepeats;
|
||||
var updates = Stopwatch.StartNew();
|
||||
for (var index = 0; index < repeats; index++)
|
||||
processor.Update(descriptions[index % frames]);
|
||||
updates.Stop();
|
||||
|
||||
GC.Collect();
|
||||
GC.WaitForPendingFinalizers();
|
||||
GC.Collect();
|
||||
var before = GC.GetAllocatedBytesForCurrentThread();
|
||||
var collections = GC.CollectionCount(0);
|
||||
for (var frame = 0; frame < frames; frame++)
|
||||
processor.Update(descriptions[frame]);
|
||||
var allocated = (GC.GetAllocatedBytesForCurrentThread() - before) / frames;
|
||||
var gen0 = GC.CollectionCount(0) - collections;
|
||||
|
||||
return new Measurement(gpu, cpu, updates.Elapsed / repeats, allocated, gen0);
|
||||
}
|
||||
finally
|
||||
{
|
||||
processor.ClearInput();
|
||||
}
|
||||
}
|
||||
|
||||
byte[] Capture(ID2D1Image output)
|
||||
{
|
||||
Submit(output);
|
||||
readback.CopyFromBitmap(target);
|
||||
|
||||
var stride = CanvasWidth * HarnessImage.BytesPerPixel;
|
||||
var pixels = new byte[stride * CanvasHeight];
|
||||
var mapped = readback.Map(MapOptions.Read);
|
||||
try
|
||||
{
|
||||
for (var y = 0; y < CanvasHeight; y++)
|
||||
Marshal.Copy(mapped.Bits + y * (int)mapped.Pitch, pixels, y * stride, stride);
|
||||
}
|
||||
finally
|
||||
{
|
||||
readback.Unmap();
|
||||
}
|
||||
|
||||
return pixels;
|
||||
}
|
||||
|
||||
void Submit(ID2D1Image output)
|
||||
{
|
||||
var deviceContext = context.DeviceContext;
|
||||
deviceContext.Target = target;
|
||||
deviceContext.BeginDraw();
|
||||
deviceContext.Clear(new Color4(0f, 0f, 0f, 0f));
|
||||
deviceContext.DrawImage(output, new Vector2(CanvasWidth * 0.5f, CanvasHeight * 0.5f), null, InterpolationMode.NearestNeighbor, CompositeMode.SourceOver);
|
||||
deviceContext.EndDraw();
|
||||
deviceContext.Target = null;
|
||||
}
|
||||
|
||||
void Synchronize()
|
||||
{
|
||||
sync.CopyFromBitmap(Int2.Zero, target, new RectI(0, 0, 1, 1));
|
||||
_ = sync.Map(MapOptions.Read);
|
||||
sync.Unmap();
|
||||
}
|
||||
|
||||
EffectDescription Describe(int frame)
|
||||
{
|
||||
var timeline = new TimelineSourceDescription(
|
||||
new System.Drawing.Size(CanvasWidth, CanvasHeight),
|
||||
new YukkuriMovieMaker.Player.Video.FrameTime(frame, Fps),
|
||||
new YukkuriMovieMaker.Player.Video.FrameTime(Length, Fps),
|
||||
Fps,
|
||||
TimelineSourceUsage.Playing,
|
||||
Guid.Empty,
|
||||
[]);
|
||||
var item = new TimelineItemSourceDescription(timeline, frame, Length, 0);
|
||||
var draw = new DrawDescription(Vector3.Zero, Vector2.Zero, Vector2.One, Vector3.Zero, Matrix4x4.Identity, InterpolationMode.Linear, 1d, false, []);
|
||||
return new EffectDescription(item, draw, 0, 1, 0, 1);
|
||||
}
|
||||
|
||||
static ID2D1Bitmap1 CreateBitmap(ID2D1DeviceContext6 deviceContext, int width, int height, BitmapOptions options)
|
||||
=> deviceContext.CreateBitmap(
|
||||
new SizeI(width, height), nint.Zero, width * HarnessImage.BytesPerPixel,
|
||||
new BitmapProperties1(PixelFormat, Dpi, Dpi, options));
|
||||
|
||||
static string FormatDriverVersion(long version)
|
||||
=> $"{(version >> 48) & 0xFFFF}.{(version >> 32) & 0xFFFF}.{(version >> 16) & 0xFFFF}.{version & 0xFFFF}";
|
||||
|
||||
public void Dispose()
|
||||
{
|
||||
placement.SetInput(0, null, true);
|
||||
centered.Dispose();
|
||||
placement.Dispose();
|
||||
timer.Dispose();
|
||||
sync.Dispose();
|
||||
readback.Dispose();
|
||||
target.Dispose();
|
||||
image.Dispose();
|
||||
context.Dispose();
|
||||
devices.Dispose();
|
||||
}
|
||||
|
||||
public readonly record struct Measurement(TimeSpan? Gpu, TimeSpan Cpu, TimeSpan Update, long Allocated, int Gen0);
|
||||
}
|
||||
@@ -0,0 +1,37 @@
|
||||
using System.IO;
|
||||
using System.Reflection;
|
||||
using System.Runtime.CompilerServices;
|
||||
|
||||
namespace WaveOptics.Harness;
|
||||
|
||||
internal static class HostAssemblyResolver
|
||||
{
|
||||
const string MetadataKey = "HostDirectory";
|
||||
const string AssemblyExtension = ".dll";
|
||||
|
||||
public static string Directory { get; } = ReadDirectory();
|
||||
|
||||
public static bool IsConfigured => Directory.Length != 0 && System.IO.Directory.Exists(Directory);
|
||||
|
||||
[ModuleInitializer]
|
||||
internal static void Initialize()
|
||||
{
|
||||
if (!IsConfigured)
|
||||
return;
|
||||
|
||||
AppDomain.CurrentDomain.AssemblyResolve += (_, arguments) =>
|
||||
{
|
||||
var name = new AssemblyName(arguments.Name).Name;
|
||||
if (name is null)
|
||||
return null;
|
||||
|
||||
var candidate = Path.Combine(Directory, name + AssemblyExtension);
|
||||
return File.Exists(candidate) ? Assembly.LoadFrom(candidate) : null;
|
||||
};
|
||||
}
|
||||
|
||||
static string ReadDirectory() => typeof(HostAssemblyResolver).Assembly
|
||||
.GetCustomAttributes<AssemblyMetadataAttribute>()
|
||||
.FirstOrDefault(attribute => string.Equals(attribute.Key, MetadataKey, StringComparison.Ordinal))
|
||||
?.Value ?? string.Empty;
|
||||
}
|
||||
@@ -0,0 +1,46 @@
|
||||
namespace WaveOptics.Harness;
|
||||
|
||||
internal readonly record struct ImageDifference(int Differing, int MaxDelta, int Left, int Top, int Right, int Bottom)
|
||||
{
|
||||
public bool IsEmpty => Differing == 0;
|
||||
|
||||
public override string ToString()
|
||||
=> IsEmpty ? "一致" : $"differing={Differing} maxDelta={MaxDelta} box=({Left},{Top})-({Right},{Bottom})";
|
||||
}
|
||||
|
||||
internal static class ImageComparison
|
||||
{
|
||||
public static ImageDifference Of(byte[] first, byte[] second, int width, int height)
|
||||
{
|
||||
if (first.Length != second.Length || first.Length != width * height * HarnessImage.BytesPerPixel)
|
||||
throw new ArgumentException("画像の寸法が一致しません。");
|
||||
|
||||
var differing = 0;
|
||||
var maxDelta = 0;
|
||||
var left = width;
|
||||
var top = height;
|
||||
var right = -1;
|
||||
var bottom = -1;
|
||||
for (var y = 0; y < height; y++)
|
||||
{
|
||||
for (var x = 0; x < width; x++)
|
||||
{
|
||||
var offset = (y * width + x) * HarnessImage.BytesPerPixel;
|
||||
var delta = 0;
|
||||
for (var channel = 0; channel < HarnessImage.BytesPerPixel; channel++)
|
||||
delta = Math.Max(delta, Math.Abs(first[offset + channel] - second[offset + channel]));
|
||||
if (delta == 0)
|
||||
continue;
|
||||
|
||||
differing++;
|
||||
maxDelta = Math.Max(maxDelta, delta);
|
||||
left = Math.Min(left, x);
|
||||
top = Math.Min(top, y);
|
||||
right = Math.Max(right, x);
|
||||
bottom = Math.Max(bottom, y);
|
||||
}
|
||||
}
|
||||
|
||||
return differing == 0 ? default : new ImageDifference(differing, maxDelta, left, top, right, bottom);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,538 @@
|
||||
using System.Diagnostics;
|
||||
using System.IO;
|
||||
using System.IO.Packaging;
|
||||
using System.Runtime.InteropServices;
|
||||
using System.Security.Cryptography;
|
||||
using ComputeWeave;
|
||||
using WaveOptics.Effects;
|
||||
using WaveOptics.Harness;
|
||||
using WaveOptics.Rendering;
|
||||
using SharpGen.Runtime;
|
||||
|
||||
const int CanvasWidth = 1280;
|
||||
const int CanvasHeight = 720;
|
||||
const int ImageWidth = 640;
|
||||
const int ImageHeight = 480;
|
||||
const int FullHdWidth = 1920;
|
||||
const int FullHdHeight = 1080;
|
||||
|
||||
_ = PackUriHelper.UriSchemePack;
|
||||
|
||||
HarnessArguments arguments;
|
||||
try
|
||||
{
|
||||
arguments = HarnessArguments.Parse(args);
|
||||
}
|
||||
catch (HarnessException exception)
|
||||
{
|
||||
Console.Error.WriteLine(exception.Message);
|
||||
Console.Error.WriteLine(HarnessArguments.Usage);
|
||||
return 2;
|
||||
}
|
||||
|
||||
try
|
||||
{
|
||||
if (arguments.Mode == HarnessMode.Compare)
|
||||
return Compare(arguments.Before!, arguments.After!);
|
||||
|
||||
if (arguments.Mode == HarnessMode.Convolution)
|
||||
{
|
||||
var convolutionImage = arguments.Input is { } convolutionInput ? HarnessImage.Load(convolutionInput) : HarnessImage.Synthetic(FullHdWidth, FullHdHeight);
|
||||
return Convolution(convolutionImage);
|
||||
}
|
||||
|
||||
var outputDirectory = arguments.OutputDirectory ?? Path.Combine(AppContext.BaseDirectory, "harness-output");
|
||||
if (arguments.Mode == HarnessMode.Benchmark)
|
||||
{
|
||||
if (arguments.Input is { } benchmarkInput)
|
||||
{
|
||||
Benchmark(HarnessImage.Load(benchmarkInput), arguments.Cpu);
|
||||
}
|
||||
else
|
||||
{
|
||||
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, arguments.Cpu);
|
||||
return arguments.Mode switch
|
||||
{
|
||||
HarnessMode.Golden => WriteGolden(renderer, image),
|
||||
HarnessMode.Verify => Verify(renderer, image),
|
||||
HarnessMode.Transition => Transition(renderer, outputDirectory),
|
||||
_ => Render(renderer, outputDirectory),
|
||||
};
|
||||
}
|
||||
catch (Exception exception) when (exception is HarnessException or SharpGenException)
|
||||
{
|
||||
Console.Error.WriteLine(exception.Message);
|
||||
return 2;
|
||||
}
|
||||
|
||||
static int Render(HarnessRenderer renderer, string outputDirectory)
|
||||
{
|
||||
Directory.CreateDirectory(outputDirectory);
|
||||
var failures = 0;
|
||||
var cases = Evaluate(renderer, (golden, files, frames) =>
|
||||
{
|
||||
Console.WriteLine($"{golden.Name}: {golden.Hash}");
|
||||
for (var index = 0; index < files.Length; index++)
|
||||
{
|
||||
HarnessImage.Save(Path.Combine(outputDirectory, files[index]), frames[index], renderer.CanvasWidth, renderer.CanvasHeight);
|
||||
var opaque = CountOpaque(frames[index]);
|
||||
Console.WriteLine($" {files[index]} opaque={opaque}");
|
||||
if (opaque == 0)
|
||||
{
|
||||
Console.Error.WriteLine($"{files[index]}: 出力が完全に透明です。");
|
||||
failures++;
|
||||
}
|
||||
}
|
||||
});
|
||||
Console.WriteLine($"-> {outputDirectory}");
|
||||
return failures + CountDuplicates(cases) == 0 ? 0 : 1;
|
||||
}
|
||||
|
||||
static int WriteGolden(HarnessRenderer renderer, HarnessImage image)
|
||||
{
|
||||
var cases = Evaluate(renderer, null);
|
||||
if (CountDuplicates(cases) != 0)
|
||||
return 1;
|
||||
if (cases.Count == 0)
|
||||
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, renderer.Cpu);
|
||||
golden.Save(path);
|
||||
Console.WriteLine($"adapter: {golden.Adapter} (driver {golden.Driver})");
|
||||
Console.WriteLine($"input: {golden.Input}");
|
||||
foreach (var (name, _, hash) in cases)
|
||||
Console.WriteLine($"{name}: {hash}");
|
||||
Console.WriteLine($"-> {path}");
|
||||
return 0;
|
||||
}
|
||||
|
||||
static int Verify(HarnessRenderer renderer, HarnessImage 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)
|
||||
{
|
||||
Console.Error.WriteLine($"基準値は入力 {golden.Input} とキャンバス {golden.Canvas} で書かれています。今回は入力 {image.Identity} とキャンバス {canvas} です。");
|
||||
return 1;
|
||||
}
|
||||
|
||||
if (golden.Adapter != renderer.Adapter || golden.Driver != renderer.Driver)
|
||||
Console.Error.WriteLine($"基準値は {golden.Adapter} (driver {golden.Driver}) で書かれています。今回は {renderer.Adapter} (driver {renderer.Driver}) です。画素の差はこの違いから来ることがあります。");
|
||||
|
||||
var failures = 0;
|
||||
var current = Evaluate(renderer, null).ToDictionary(item => item.Name, StringComparer.Ordinal);
|
||||
if (golden.Cases.Count == 0 && current.Count == 0)
|
||||
Console.Error.WriteLine("ケースがありません。HarnessCases に書き足してください。");
|
||||
foreach (var (name, frames, hash) in golden.Cases)
|
||||
{
|
||||
if (!current.Remove(name, out var actual))
|
||||
{
|
||||
Console.Error.WriteLine($"{name}: ケースがありません。基準値を書き直してください。");
|
||||
failures++;
|
||||
}
|
||||
else if (!actual.Frames.SequenceEqual(frames))
|
||||
{
|
||||
Console.Error.WriteLine($"{name}: フレームが違います。基準値 [{string.Join(", ", frames)}]、今回 [{string.Join(", ", actual.Frames)}]。基準値を書き直してください。");
|
||||
failures++;
|
||||
}
|
||||
else if (actual.Hash != hash)
|
||||
{
|
||||
Console.Error.WriteLine($"{name}: 一致しません。基準値 {hash}、今回 {actual.Hash}");
|
||||
failures++;
|
||||
}
|
||||
else
|
||||
{
|
||||
Console.WriteLine($"{name}: 一致");
|
||||
}
|
||||
}
|
||||
|
||||
foreach (var name in current.Keys)
|
||||
{
|
||||
Console.Error.WriteLine($"{name}: 基準値にありません。基準値を書き直してください。");
|
||||
failures++;
|
||||
}
|
||||
|
||||
return failures == 0 ? 0 : 1;
|
||||
}
|
||||
|
||||
static int Transition(HarnessRenderer renderer, string outputDirectory)
|
||||
{
|
||||
var failures = 0;
|
||||
foreach (var (name, create, change, frame) in HarnessCases.Transitions())
|
||||
{
|
||||
var (direct, transitioned) = renderer.RenderTransition(create, change, frame);
|
||||
var difference = ImageComparison.Of(direct, transitioned, renderer.CanvasWidth, renderer.CanvasHeight);
|
||||
if (difference.IsEmpty)
|
||||
{
|
||||
Console.WriteLine($"{name}: 一致");
|
||||
continue;
|
||||
}
|
||||
|
||||
failures++;
|
||||
Directory.CreateDirectory(outputDirectory);
|
||||
HarnessImage.Save(Path.Combine(outputDirectory, name + "-direct.png"), direct, renderer.CanvasWidth, renderer.CanvasHeight);
|
||||
HarnessImage.Save(Path.Combine(outputDirectory, name + "-transitioned.png"), transitioned, renderer.CanvasWidth, renderer.CanvasHeight);
|
||||
Console.Error.WriteLine($"{name}: {difference}。設定を変えた後の描画が作り直した場合と違います。-> {outputDirectory}");
|
||||
}
|
||||
|
||||
if (!HarnessCases.Transitions().Any() && !HarnessCases.All().Any(item => item.Frames.Count > 1))
|
||||
Console.Error.WriteLine("ケースがありません。HarnessCases に書き足してください。");
|
||||
|
||||
foreach (var (name, effect, frames) in HarnessCases.All())
|
||||
{
|
||||
if (frames.Count < 2)
|
||||
continue;
|
||||
|
||||
var sequential = renderer.Render(effect, frames);
|
||||
for (var index = 0; index < frames.Count; index++)
|
||||
{
|
||||
var fresh = renderer.Render(effect, [frames[index]])[0];
|
||||
var difference = ImageComparison.Of(fresh, sequential[index], renderer.CanvasWidth, renderer.CanvasHeight);
|
||||
var label = $"{name}-f{frames[index]:D3}";
|
||||
if (difference.IsEmpty)
|
||||
{
|
||||
Console.WriteLine($"{label}: 一致");
|
||||
continue;
|
||||
}
|
||||
|
||||
failures++;
|
||||
Directory.CreateDirectory(outputDirectory);
|
||||
HarnessImage.Save(Path.Combine(outputDirectory, label + "-direct.png"), fresh, renderer.CanvasWidth, renderer.CanvasHeight);
|
||||
HarnessImage.Save(Path.Combine(outputDirectory, label + "-transitioned.png"), sequential[index], renderer.CanvasWidth, renderer.CanvasHeight);
|
||||
Console.Error.WriteLine($"{label}: {difference}。前のフレームから進めた描画が作り直した場合と違います。-> {outputDirectory}");
|
||||
}
|
||||
}
|
||||
|
||||
return failures == 0 ? 0 : 1;
|
||||
}
|
||||
|
||||
static int Convolution(HarnessImage image)
|
||||
{
|
||||
const int Rounds = 12;
|
||||
const int Seed = 17;
|
||||
|
||||
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);
|
||||
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));
|
||||
WaveOpticsPipeline.Parameters Radius(int radius) => parameters with { Psf = parameters.Psf with { KernelRadius = radius, Defocus = 2f, ComaHorizontal = 1f } };
|
||||
|
||||
var subjects = new List<IDisposable>();
|
||||
GpuSubject Gpu(bool check = false)
|
||||
{
|
||||
var subject = new GpuSubject(WaveOpticsPipeline.TryCreate(device) ?? throw new HarnessException("Direct3D 12を利用できません。"), output, image.Width, image.Height, check);
|
||||
subjects.Add(subject);
|
||||
return subject;
|
||||
}
|
||||
CpuSubject Cpu()
|
||||
{
|
||||
var subject = new CpuSubject(image.Width, image.Height);
|
||||
subjects.Add(subject);
|
||||
return subject;
|
||||
}
|
||||
|
||||
void Measure(string title, Func<(string Name, Action<bool> Run)[]> create)
|
||||
{
|
||||
try
|
||||
{
|
||||
var variants = create();
|
||||
var samples = new List<double>[variants.Length];
|
||||
for (var index = 0; index < samples.Length; index++)
|
||||
samples[index] = new List<double>(Rounds);
|
||||
|
||||
foreach (var (_, run) in variants)
|
||||
{
|
||||
run(true);
|
||||
run(false);
|
||||
}
|
||||
|
||||
var stopwatch = new Stopwatch();
|
||||
var order = Enumerable.Range(0, variants.Length).ToArray();
|
||||
var random = new Random(Seed);
|
||||
for (var round = 0; round < Rounds; round++)
|
||||
{
|
||||
for (var index = order.Length - 1; index > 0; index--)
|
||||
{
|
||||
var swap = random.Next(index + 1);
|
||||
(order[index], order[swap]) = (order[swap], order[index]);
|
||||
}
|
||||
|
||||
foreach (var index in order)
|
||||
{
|
||||
var flip = round % 2 == 0;
|
||||
stopwatch.Restart();
|
||||
variants[index].Run(flip);
|
||||
stopwatch.Stop();
|
||||
samples[index].Add(stopwatch.Elapsed.TotalMilliseconds);
|
||||
}
|
||||
}
|
||||
|
||||
Console.WriteLine($"{title}");
|
||||
for (var index = 0; index < variants.Length; index++)
|
||||
{
|
||||
var sorted = samples[index].OrderBy(static value => value).ToArray();
|
||||
var median = sorted[sorted.Length / 2];
|
||||
Console.WriteLine($" {variants[index].Name,-20} min={sorted[0],7:F2} median={median,7:F2} max={sorted[^1],7:F2}");
|
||||
}
|
||||
}
|
||||
finally
|
||||
{
|
||||
foreach (var subject in subjects)
|
||||
subject.Dispose();
|
||||
subjects.Clear();
|
||||
}
|
||||
}
|
||||
|
||||
Console.WriteLine($"convolution recompute at {image.Width}x{image.Height} over {Rounds} interleaved rounds (ms)");
|
||||
|
||||
// Each set owns its pipelines while it runs. Keeping the pipelines of the other set alive would
|
||||
// change the memory the GPU has left and slow every row down.
|
||||
Measure("default options", () =>
|
||||
{
|
||||
var cached = Gpu();
|
||||
var gain = Gpu();
|
||||
var source = Gpu();
|
||||
var checkedSource = Gpu(true);
|
||||
var defocus = Gpu();
|
||||
var qualityHigh = Gpu();
|
||||
var source31 = Gpu();
|
||||
var source63 = Gpu();
|
||||
var cpuSource = Cpu();
|
||||
var cpuGain = Cpu();
|
||||
var cpuSource63 = Cpu();
|
||||
return
|
||||
[
|
||||
("cached", _ => cached.Frame(original, parameters)),
|
||||
("gain", flip => gain.Frame(original, parameters with { Gain = flip ? 1.5f : 1f })),
|
||||
("source", flip => source.Frame(flip ? mirrored : original, parameters)),
|
||||
("source-checked", flip => checkedSource.Frame(flip ? mirrored : original, parameters)),
|
||||
("defocus", flip => defocus.Frame(original, parameters with { Psf = parameters.Psf with { Defocus = flip ? 0.1f : 0f } })),
|
||||
("quality-high", flip => qualityHigh.Frame(original, parameters with { Psf = parameters.Psf with { Quality = flip ? WaveOpticsQuality.High : WaveOpticsQuality.Standard } })),
|
||||
("source-r31", flip => source31.Frame(flip ? mirrored : original, Radius(31))),
|
||||
("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 linearLight = new SpectralConvolution.LightOptions(true, false, 0f, 0f);
|
||||
var highlightLight = new SpectralConvolution.LightOptions(true, false, 0.7f, 30f);
|
||||
Measure("light options", () =>
|
||||
{
|
||||
var source = Gpu();
|
||||
var checkedSource = Gpu(true);
|
||||
var linear = Gpu();
|
||||
var checkedLinear = Gpu(true);
|
||||
var linearHighlight = Gpu();
|
||||
var cpuSource = Cpu();
|
||||
var cpuLinear = Cpu();
|
||||
var cpuLinearHighlight = Cpu();
|
||||
return
|
||||
[
|
||||
("source", flip => source.Frame(flip ? mirrored : original, parameters)),
|
||||
("source-checked", flip => checkedSource.Frame(flip ? mirrored : original, parameters)),
|
||||
("linear", flip => linear.Frame(flip ? mirrored : original, parameters with { Light = linearLight })),
|
||||
("linear-checked", flip => checkedLinear.Frame(flip ? mirrored : original, parameters with { Light = linearLight })),
|
||||
("linear-highlight", flip => linearHighlight.Frame(flip ? mirrored : original, parameters with { Light = highlightLight })),
|
||||
("cpu-source", flip => cpuSource.Frame(flip ? mirroredBytes : originalBytes, parameters)),
|
||||
("cpu-linear", flip => cpuLinear.Frame(flip ? mirroredBytes : originalBytes, parameters with { Light = linearLight })),
|
||||
("cpu-linear-highlight", flip => cpuLinearHighlight.Frame(flip ? mirroredBytes : originalBytes, parameters with { Light = highlightLight })),
|
||||
];
|
||||
});
|
||||
|
||||
return 0;
|
||||
}
|
||||
|
||||
static Bgra32[] ToPixels(HarnessImage image, bool mirror)
|
||||
{
|
||||
var pixels = new Bgra32[image.Width * image.Height];
|
||||
for (var y = 0; y < image.Height; y++)
|
||||
{
|
||||
for (var x = 0; x < image.Width; x++)
|
||||
{
|
||||
var offset = (y * image.Width + (mirror ? image.Width - 1 - x : x)) * HarnessImage.BytesPerPixel;
|
||||
pixels[y * image.Width + x] = new Bgra32(image.Pixels[offset + 2], image.Pixels[offset + 1], image.Pixels[offset], image.Pixels[offset + 3]);
|
||||
}
|
||||
}
|
||||
|
||||
return pixels;
|
||||
}
|
||||
|
||||
static int Compare(string beforeDirectory, string afterDirectory)
|
||||
{
|
||||
if (!Directory.Exists(beforeDirectory) || !Directory.Exists(afterDirectory))
|
||||
throw new HarnessException("比べる出力先がありません。");
|
||||
|
||||
var failures = 0;
|
||||
var names = Directory.EnumerateFiles(beforeDirectory, "*.png")
|
||||
.Concat(Directory.EnumerateFiles(afterDirectory, "*.png"))
|
||||
.Select(path => Path.GetFileName(path))
|
||||
.Distinct(StringComparer.OrdinalIgnoreCase)
|
||||
.Order(StringComparer.OrdinalIgnoreCase)
|
||||
.ToArray();
|
||||
if (names.Length == 0)
|
||||
throw new HarnessException("比べる PNG がありません。");
|
||||
|
||||
foreach (var name in names)
|
||||
{
|
||||
var before = Path.Combine(beforeDirectory, name);
|
||||
var after = Path.Combine(afterDirectory, name);
|
||||
if (!File.Exists(before) || !File.Exists(after))
|
||||
{
|
||||
Console.Error.WriteLine($"{name}: {(File.Exists(before) ? "後" : "前")}にありません。");
|
||||
failures++;
|
||||
continue;
|
||||
}
|
||||
|
||||
var (beforeWidth, beforeHeight, beforePixels) = HarnessImage.LoadPremultiplied(before);
|
||||
var (afterWidth, afterHeight, afterPixels) = HarnessImage.LoadPremultiplied(after);
|
||||
if (beforeWidth != afterWidth || beforeHeight != afterHeight)
|
||||
{
|
||||
Console.Error.WriteLine($"{name}: 寸法が違います。前 {beforeWidth}x{beforeHeight}、後 {afterWidth}x{afterHeight}");
|
||||
failures++;
|
||||
continue;
|
||||
}
|
||||
|
||||
var difference = ImageComparison.Of(beforePixels, afterPixels, beforeWidth, beforeHeight);
|
||||
Console.WriteLine($"{name}: {difference}");
|
||||
if (!difference.IsEmpty)
|
||||
failures++;
|
||||
}
|
||||
|
||||
return failures == 0 ? 0 : 1;
|
||||
}
|
||||
|
||||
static void Benchmark(HarnessImage image, bool cpu)
|
||||
{
|
||||
const int Frames = 60;
|
||||
|
||||
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())
|
||||
{
|
||||
Report(image, name, "still", renderer.Measure(effect, Frames, moving: false));
|
||||
Report(image, name, "moving", renderer.Measure(effect, Frames, moving: true));
|
||||
}
|
||||
}
|
||||
|
||||
static void Report(HarnessImage image, string name, string motion, HarnessRenderer.Measurement measurement)
|
||||
=> Console.WriteLine(
|
||||
$"{image.Width}x{image.Height} {name,-15} {motion,-6} " +
|
||||
$"gpu={(measurement.Gpu is { } gpu ? gpu.TotalMilliseconds.ToString("F3") : "n/a"),7} " +
|
||||
$"cpu={measurement.Cpu.TotalMilliseconds,7:F3} " +
|
||||
$"update={measurement.Update.TotalMilliseconds,6:F3} " +
|
||||
$"alloc={measurement.Allocated,6} gen0={measurement.Gen0}");
|
||||
|
||||
static List<GoldenCase> Evaluate(HarnessRenderer renderer, Action<GoldenCase, string[], byte[][]>? report)
|
||||
{
|
||||
var cases = new List<GoldenCase>();
|
||||
var names = new HashSet<string>(StringComparer.Ordinal);
|
||||
foreach (var (name, effect, frames) in HarnessCases.All())
|
||||
{
|
||||
if (!names.Add(name))
|
||||
throw new HarnessException($"ケース名が重複しています。{name}");
|
||||
|
||||
var rendered = renderer.Render(effect, frames);
|
||||
var files = new string[frames.Count];
|
||||
using var hash = IncrementalHash.CreateHash(HashAlgorithmName.SHA256);
|
||||
for (var index = 0; index < frames.Count; index++)
|
||||
{
|
||||
hash.AppendData(rendered[index]);
|
||||
files[index] = frames.Count == 1 ? name + ".png" : $"{name}-f{frames[index]:D3}.png";
|
||||
}
|
||||
|
||||
var golden = new GoldenCase(name, frames, Convert.ToHexString(hash.GetHashAndReset()));
|
||||
cases.Add(golden);
|
||||
report?.Invoke(golden, files, rendered);
|
||||
}
|
||||
|
||||
return cases;
|
||||
}
|
||||
|
||||
static int CountDuplicates(IReadOnlyList<GoldenCase> cases)
|
||||
{
|
||||
var duplicates = 0;
|
||||
var seen = new Dictionary<string, string>(StringComparer.Ordinal);
|
||||
foreach (var (name, _, hash) in cases)
|
||||
{
|
||||
if (seen.TryGetValue(hash, out var first))
|
||||
{
|
||||
Console.Error.WriteLine($"{name}: {first} と出力が一致します。設定がシェーダーへ届いていません。");
|
||||
duplicates++;
|
||||
}
|
||||
else
|
||||
{
|
||||
seen.Add(hash, name);
|
||||
}
|
||||
}
|
||||
|
||||
return duplicates;
|
||||
}
|
||||
|
||||
static int CountOpaque(byte[] pixels)
|
||||
{
|
||||
var count = 0;
|
||||
for (var offset = HarnessImage.BytesPerPixel - 1; offset < pixels.Length; offset += HarnessImage.BytesPerPixel)
|
||||
{
|
||||
if (pixels[offset] != 0)
|
||||
count++;
|
||||
}
|
||||
|
||||
return count;
|
||||
}
|
||||
|
||||
sealed class GpuSubject(WaveOpticsPipeline pipeline, ReadWriteTexture2D<Bgra32, Float4> output, int width, int height, bool check) : IDisposable
|
||||
{
|
||||
readonly SpectralConvolution.ConvolutionMeasurement[] measurements = check ? new SpectralConvolution.ConvolutionMeasurement[WaveOpticsPipeline.MeasurementCount] : [];
|
||||
float renderedGain = float.NaN;
|
||||
|
||||
public void Frame(ReadWriteTexture2D<Bgra32, Float4> source, in WaveOpticsPipeline.Parameters parameters)
|
||||
{
|
||||
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, measurements);
|
||||
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,51 @@
|
||||
namespace WaveOptics.Harness;
|
||||
|
||||
internal static class SyntheticImage
|
||||
{
|
||||
const int GridPitch = 32;
|
||||
|
||||
public static byte[] Create(int width, int height)
|
||||
{
|
||||
var pixels = new byte[width * height * HarnessImage.BytesPerPixel];
|
||||
var plateLeft = width * 0.10f;
|
||||
var plateRight = width * 0.56f;
|
||||
var plateTop = height * 0.14f;
|
||||
var plateBottom = height * 0.86f;
|
||||
var discCenterX = width * 0.70f;
|
||||
var discCenterY = height * 0.50f;
|
||||
var discRadius = MathF.Min(width, height) * 0.28f;
|
||||
|
||||
for (var y = 0; y < height; y++)
|
||||
{
|
||||
for (var x = 0; x < width; x++)
|
||||
{
|
||||
var positionX = x + 0.5f;
|
||||
var positionY = y + 0.5f;
|
||||
var plateInset = MathF.Min(MathF.Min(positionX - plateLeft, plateRight - positionX), MathF.Min(positionY - plateTop, plateBottom - positionY));
|
||||
var plateCoverage = Math.Clamp(plateInset + 0.5f, 0f, 1f);
|
||||
var distance = MathF.Sqrt((positionX - discCenterX) * (positionX - discCenterX) + (positionY - discCenterY) * (positionY - discCenterY));
|
||||
var discCoverage = Math.Clamp(discRadius - distance + 0.5f, 0f, 1f);
|
||||
if (plateCoverage == 0f && discCoverage == 0f)
|
||||
continue;
|
||||
|
||||
var onGrid = x % GridPitch == 0 || y % GridPitch == 0;
|
||||
var plateWeight = plateCoverage * (1f - discCoverage);
|
||||
var shade = 1f - distance / discRadius * 0.5f;
|
||||
var red = (onGrid ? 0.25f : 0.82f) * plateWeight + 0.90f * shade * discCoverage;
|
||||
var green = (onGrid ? 0.30f : 0.86f) * plateWeight + 0.45f * shade * discCoverage;
|
||||
var blue = (onGrid ? 0.40f : 0.90f) * plateWeight + 0.30f * shade * discCoverage;
|
||||
var alpha = plateWeight + discCoverage;
|
||||
|
||||
var offset = (y * width + x) * HarnessImage.BytesPerPixel;
|
||||
pixels[offset] = ToByte(blue);
|
||||
pixels[offset + 1] = ToByte(green);
|
||||
pixels[offset + 2] = ToByte(red);
|
||||
pixels[offset + 3] = ToByte(alpha);
|
||||
}
|
||||
}
|
||||
|
||||
return pixels;
|
||||
}
|
||||
|
||||
static byte ToByte(float premultiplied) => (byte)MathF.Round(Math.Clamp(premultiplied, 0f, 1f) * byte.MaxValue);
|
||||
}
|
||||
@@ -0,0 +1,62 @@
|
||||
<Project Sdk="Microsoft.NET.Sdk">
|
||||
|
||||
<PropertyGroup>
|
||||
<OutputType>Exe</OutputType>
|
||||
<TargetFramework>net10.0-windows10.0.19041.0</TargetFramework>
|
||||
<UseWPF>true</UseWPF>
|
||||
<ImplicitUsings>enable</ImplicitUsings>
|
||||
<Nullable>enable</Nullable>
|
||||
<IsPackable>false</IsPackable>
|
||||
<AssemblyName>WaveOptics.Harness</AssemblyName>
|
||||
<RootNamespace>WaveOptics.Harness</RootNamespace>
|
||||
<PlatformTarget>x64</PlatformTarget>
|
||||
<TieredCompilation>false</TieredCompilation>
|
||||
</PropertyGroup>
|
||||
|
||||
<ItemGroup>
|
||||
<ProjectReference Include="..\WaveOptics\WaveOptics.csproj" SetConfiguration="Configuration=$(Configuration)" SetPlatform="Platform=x64">
|
||||
<AdditionalProperties Condition="'$(BuildingSolutionFile)' != 'true'">SkipPluginDeploy=true</AdditionalProperties>
|
||||
</ProjectReference>
|
||||
</ItemGroup>
|
||||
|
||||
<ItemGroup>
|
||||
<AssemblyMetadata Include="HostDirectory" Value="$(YMM4DirPath)" />
|
||||
<AssemblyMetadata Include="HarnessDirectory" Value="$(MSBuildProjectDirectory)" />
|
||||
</ItemGroup>
|
||||
|
||||
<ItemGroup>
|
||||
<Reference Include="SharpGen.Runtime">
|
||||
<HintPath>$(YMM4DirPath)SharpGen.Runtime.dll</HintPath>
|
||||
<Private>false</Private>
|
||||
</Reference>
|
||||
<Reference Include="Vortice.Direct2D1">
|
||||
<HintPath>$(YMM4DirPath)Vortice.Direct2D1.dll</HintPath>
|
||||
<Private>false</Private>
|
||||
</Reference>
|
||||
<Reference Include="Vortice.Direct3D11">
|
||||
<HintPath>$(YMM4DirPath)Vortice.Direct3D11.dll</HintPath>
|
||||
<Private>false</Private>
|
||||
</Reference>
|
||||
<Reference Include="Vortice.DirectX">
|
||||
<HintPath>$(YMM4DirPath)Vortice.DirectX.dll</HintPath>
|
||||
<Private>false</Private>
|
||||
</Reference>
|
||||
<Reference Include="Vortice.DXGI">
|
||||
<HintPath>$(YMM4DirPath)Vortice.DXGI.dll</HintPath>
|
||||
<Private>false</Private>
|
||||
</Reference>
|
||||
<Reference Include="Vortice.Mathematics">
|
||||
<HintPath>$(YMM4DirPath)Vortice.Mathematics.dll</HintPath>
|
||||
<Private>false</Private>
|
||||
</Reference>
|
||||
<Reference Include="YukkuriMovieMaker.Controls">
|
||||
<HintPath>$(YMM4DirPath)YukkuriMovieMaker.Controls.dll</HintPath>
|
||||
<Private>false</Private>
|
||||
</Reference>
|
||||
<Reference Include="YukkuriMovieMaker.Plugin">
|
||||
<HintPath>$(YMM4DirPath)YukkuriMovieMaker.Plugin.dll</HintPath>
|
||||
<Private>false</Private>
|
||||
</Reference>
|
||||
</ItemGroup>
|
||||
|
||||
</Project>
|
||||
@@ -0,0 +1,305 @@
|
||||
{
|
||||
"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"
|
||||
},
|
||||
{
|
||||
"name": "linear",
|
||||
"frames": [
|
||||
0
|
||||
],
|
||||
"hash": "3EED06FE0B0B59C46C20E7328748B3252A83C416A667530987DFDAFAD3812C99"
|
||||
},
|
||||
{
|
||||
"name": "linear-gain-150",
|
||||
"frames": [
|
||||
0
|
||||
],
|
||||
"hash": "54954AC3C99C0E5A3399EAA19660E68AB3CB94A453CEB649238A7BBEC88B97B8"
|
||||
},
|
||||
{
|
||||
"name": "linear-highlight-boost-30",
|
||||
"frames": [
|
||||
0
|
||||
],
|
||||
"hash": "1989982E87CF8A3446FD889A893466C6FD5419E66F3EE4498959A3E5F9539AC7"
|
||||
},
|
||||
{
|
||||
"name": "linear-highlight-threshold-50-boost-8",
|
||||
"frames": [
|
||||
0
|
||||
],
|
||||
"hash": "FF7DD316FBB2745168837D079820FD392115A774385FFE8B99144C5AC9080901"
|
||||
},
|
||||
{
|
||||
"name": "dither",
|
||||
"frames": [
|
||||
0
|
||||
],
|
||||
"hash": "A4E7E124F0D854BEC41C70597C27434E2F92228543008429736B209F419EEE50"
|
||||
},
|
||||
{
|
||||
"name": "linear-dither-defocus-1",
|
||||
"frames": [
|
||||
0
|
||||
],
|
||||
"hash": "FFB41C48B77A347074828F587F22793595BD366574941519FDE46AB65AEBBA6C"
|
||||
},
|
||||
{
|
||||
"name": "linear-highlight-polygon-defocus-2-radius-40",
|
||||
"frames": [
|
||||
0
|
||||
],
|
||||
"hash": "33CE14E973508DD57A569BC2AB7BF0DAD9952A9A0182D3EFACD9C5CADD379E3D"
|
||||
},
|
||||
{
|
||||
"name": "linear-highlight-animated-frames-0-8",
|
||||
"frames": [
|
||||
0,
|
||||
1,
|
||||
2,
|
||||
3,
|
||||
4,
|
||||
5,
|
||||
6,
|
||||
7,
|
||||
8
|
||||
],
|
||||
"hash": "0DDC7963278242EB3888A81D542BBCD02D8552E2A2C71C560F5D62DAAE2B080E"
|
||||
}
|
||||
]
|
||||
}
|
||||
@@ -0,0 +1,305 @@
|
||||
{
|
||||
"adapter": "Intel(R) Iris(R) Xe Graphics",
|
||||
"driver": "32.0.101.7085",
|
||||
"input": "synthetic 640x480 89838D8976198E40",
|
||||
"canvas": "1280x720",
|
||||
"cases": [
|
||||
{
|
||||
"name": "default",
|
||||
"frames": [
|
||||
0
|
||||
],
|
||||
"hash": "B71481CC55FAC4F415BF590D7623D8973DA2EEFC9864D376D6D2BEC07D7A53EC"
|
||||
},
|
||||
{
|
||||
"name": "default-frames-0-8",
|
||||
"frames": [
|
||||
0,
|
||||
1,
|
||||
2,
|
||||
3,
|
||||
4,
|
||||
5,
|
||||
6,
|
||||
7,
|
||||
8
|
||||
],
|
||||
"hash": "7A46C7D2CDA1F9ABB24C7887993ECC5EA84EBF935B1C9C728FC1A123ECBDB382"
|
||||
},
|
||||
{
|
||||
"name": "amount-0",
|
||||
"frames": [
|
||||
0
|
||||
],
|
||||
"hash": "0A700F76CEDDBAD7C4B6A2C19D46939C1A93940E86C6EFEF1E5A53DB48D2A020"
|
||||
},
|
||||
{
|
||||
"name": "amount-50",
|
||||
"frames": [
|
||||
0
|
||||
],
|
||||
"hash": "E61EAF07F3AD9B803C0CC66D2081ABFBB9CF8E636139831AF9C07FBE720AE829"
|
||||
},
|
||||
{
|
||||
"name": "gain-50",
|
||||
"frames": [
|
||||
0
|
||||
],
|
||||
"hash": "04F6DF30B38FF4F091D1160CD8E58DC9C162DC70B9A7C1A1AED5CBA5CD8B95C9"
|
||||
},
|
||||
{
|
||||
"name": "gain-400",
|
||||
"frames": [
|
||||
0
|
||||
],
|
||||
"hash": "92533C9D79403C5E18C6BEA3F900247FC7C30255810851413A319DFBA435FAC6"
|
||||
},
|
||||
{
|
||||
"name": "gain-400-amount-50",
|
||||
"frames": [
|
||||
0
|
||||
],
|
||||
"hash": "8D92DC9C871DC8ADE21A72C4E50E0330A7B3F01655FC50FA008B70DA17458AAE"
|
||||
},
|
||||
{
|
||||
"name": "wavelength-380",
|
||||
"frames": [
|
||||
0
|
||||
],
|
||||
"hash": "4E475FC56B2F720262560ECC6CE7FF947B440345ED07EEDA5AC7FFFC1B9E2A3C"
|
||||
},
|
||||
{
|
||||
"name": "wavelength-780",
|
||||
"frames": [
|
||||
0
|
||||
],
|
||||
"hash": "61674C04EDE9E19E97609C5EEB4FEAD8E2AF41DDF2808BFEBD3278119457986F"
|
||||
},
|
||||
{
|
||||
"name": "f-number-4",
|
||||
"frames": [
|
||||
0
|
||||
],
|
||||
"hash": "59F2E23935AB662D7D6D40C392B2FEAD59FFEC6B6C7466DA01F2A3970099AC2C"
|
||||
},
|
||||
{
|
||||
"name": "f-number-64",
|
||||
"frames": [
|
||||
0
|
||||
],
|
||||
"hash": "A0B2BDF726B96A4F71583D67F3FFF03BE5F053EAA757A169D02762045FE3054B"
|
||||
},
|
||||
{
|
||||
"name": "pixel-pitch-0.25",
|
||||
"frames": [
|
||||
0
|
||||
],
|
||||
"hash": "E561DDA367AF61F78A35949F686F7AA4DC11FC0C2B9F50FDC501E997EA023555"
|
||||
},
|
||||
{
|
||||
"name": "pixel-pitch-2",
|
||||
"frames": [
|
||||
0
|
||||
],
|
||||
"hash": "427043F6DA302D72D5C015CB6FDB691710E55824B66B60971386A6A6DA5A2B52"
|
||||
},
|
||||
{
|
||||
"name": "kernel-radius-1",
|
||||
"frames": [
|
||||
0
|
||||
],
|
||||
"hash": "D898D9F66BD5566A55D8570BE5F2CD1210F30BED8ECC23B6152805B35280E58E"
|
||||
},
|
||||
{
|
||||
"name": "kernel-radius-5",
|
||||
"frames": [
|
||||
0
|
||||
],
|
||||
"hash": "5AC78F10ABFEB6703327409AF5021676BFADBC8B8271FCBFC9A825C4D54DE3D8"
|
||||
},
|
||||
{
|
||||
"name": "kernel-radius-40-defocus-2",
|
||||
"frames": [
|
||||
0
|
||||
],
|
||||
"hash": "1B90715CC1735FD7B87D16800698B5FE6AAB65E47B38FDE5A1A71733A85662E6"
|
||||
},
|
||||
{
|
||||
"name": "kernel-radius-63-polygon-defocus-3",
|
||||
"frames": [
|
||||
0
|
||||
],
|
||||
"hash": "544F004B4E6DE4EF2BBB554F7CC8B6A98A3128413642BE0953331BBD1E290285"
|
||||
},
|
||||
{
|
||||
"name": "quality-draft",
|
||||
"frames": [
|
||||
0
|
||||
],
|
||||
"hash": "BFDF5C15934DCE96B2FBC3F32671D3619E3A4863D0F6B6C886003EE137E208EA"
|
||||
},
|
||||
{
|
||||
"name": "quality-high",
|
||||
"frames": [
|
||||
0
|
||||
],
|
||||
"hash": "EE9CA6EA1570279FB7FE22615DF9832D3B891F59A2C88A0B46895E23286889E6"
|
||||
},
|
||||
{
|
||||
"name": "aperture-polygon",
|
||||
"frames": [
|
||||
0
|
||||
],
|
||||
"hash": "63714DFA7EF012D7AB6B818E538427DD55BAA4392BD0B3171C325D52BEA727D3"
|
||||
},
|
||||
{
|
||||
"name": "blade-count-3",
|
||||
"frames": [
|
||||
0
|
||||
],
|
||||
"hash": "F9B3EA9580C95536258728CF01E885A4308B4A61B3F68861B8BEA4B45CC093B5"
|
||||
},
|
||||
{
|
||||
"name": "blade-count-32",
|
||||
"frames": [
|
||||
0
|
||||
],
|
||||
"hash": "62218C4D673DD03C558F0F3A0AB6699A1AF4A33A0E814DFF52F452B61C720A50"
|
||||
},
|
||||
{
|
||||
"name": "blade-rotation-30",
|
||||
"frames": [
|
||||
0
|
||||
],
|
||||
"hash": "0842E055F3DD3518FFE25A2F3ABB1A205310AAB60C2CD9804C221FE024CA4D38"
|
||||
},
|
||||
{
|
||||
"name": "obstruction-50",
|
||||
"frames": [
|
||||
0
|
||||
],
|
||||
"hash": "9F86A17BC9EA4E362F6C785B8672B93C21DEB5748064456058C34E8B1B52E800"
|
||||
},
|
||||
{
|
||||
"name": "defocus-1",
|
||||
"frames": [
|
||||
0
|
||||
],
|
||||
"hash": "BF6533B30E4130242CAB252FB7370F6097D10CC85DEA926E8A44273B2706CB12"
|
||||
},
|
||||
{
|
||||
"name": "astigmatism-vertical-1",
|
||||
"frames": [
|
||||
0
|
||||
],
|
||||
"hash": "0AEC6A3A9070BF1F0AD08118DAFCEA6E6C8D55B35555EA8DF918B8D2E127A2EC"
|
||||
},
|
||||
{
|
||||
"name": "astigmatism-oblique-1",
|
||||
"frames": [
|
||||
0
|
||||
],
|
||||
"hash": "15E642C87F192398DA4E38275DD9467D162C31B67E7D02FDA22B820752213AC9"
|
||||
},
|
||||
{
|
||||
"name": "coma-horizontal-1",
|
||||
"frames": [
|
||||
0
|
||||
],
|
||||
"hash": "931357CB85EF96F0BED2AFB7F49BADC130C354EACCF3B3815441CD64F472041C"
|
||||
},
|
||||
{
|
||||
"name": "coma-vertical-1",
|
||||
"frames": [
|
||||
0
|
||||
],
|
||||
"hash": "2A85D748133BBD1C015892C2C1183D9D069A6FA353CB3D14DEEAED7CAE4C378F"
|
||||
},
|
||||
{
|
||||
"name": "spherical-1",
|
||||
"frames": [
|
||||
0
|
||||
],
|
||||
"hash": "5CE0E3BEE95CAF4E585036FC6048CA63F0B3D42C3F1FC23A83D045A41C700FD8"
|
||||
},
|
||||
{
|
||||
"name": "defocus-animated-frames-0-8",
|
||||
"frames": [
|
||||
0,
|
||||
1,
|
||||
2,
|
||||
3,
|
||||
4,
|
||||
5,
|
||||
6,
|
||||
7,
|
||||
8
|
||||
],
|
||||
"hash": "B16C68AB33DE6B661BFF623AE9D3AE7264EF75CF3427AFF0FCA5E16E96BC998A"
|
||||
},
|
||||
{
|
||||
"name": "linear",
|
||||
"frames": [
|
||||
0
|
||||
],
|
||||
"hash": "E7A46523EADA5966E9655FFB991D6C600B747FE81EBAD746BA7EADD8AA1E1689"
|
||||
},
|
||||
{
|
||||
"name": "linear-gain-150",
|
||||
"frames": [
|
||||
0
|
||||
],
|
||||
"hash": "DFDD975BC7310F9D59900C3132D5E226360CE26DB836CA11AF2FAC838B247EFD"
|
||||
},
|
||||
{
|
||||
"name": "linear-highlight-boost-30",
|
||||
"frames": [
|
||||
0
|
||||
],
|
||||
"hash": "4F3DA5EF23F20E5621AAECA7BEA99B9484F203411F033A06BF8398A26F92E512"
|
||||
},
|
||||
{
|
||||
"name": "linear-highlight-threshold-50-boost-8",
|
||||
"frames": [
|
||||
0
|
||||
],
|
||||
"hash": "4324A1C29CD13435ABD4E65647A9A076E83CF66FBFE93F831C5CA0962FBAD468"
|
||||
},
|
||||
{
|
||||
"name": "dither",
|
||||
"frames": [
|
||||
0
|
||||
],
|
||||
"hash": "620506E95C258C25FDB2106809F2F376C61BE750A1AC26A4046198AE32CB9140"
|
||||
},
|
||||
{
|
||||
"name": "linear-dither-defocus-1",
|
||||
"frames": [
|
||||
0
|
||||
],
|
||||
"hash": "D311BDC0B33B1D1082108CDB8B4C0150C2878DAB55B3E8CE97C5F035F47026F7"
|
||||
},
|
||||
{
|
||||
"name": "linear-highlight-polygon-defocus-2-radius-40",
|
||||
"frames": [
|
||||
0
|
||||
],
|
||||
"hash": "1EF8C3B15AC95EB5469B32226052E1D4B7DDB808B2A94CD66DD951D2FC402921"
|
||||
},
|
||||
{
|
||||
"name": "linear-highlight-animated-frames-0-8",
|
||||
"frames": [
|
||||
0,
|
||||
1,
|
||||
2,
|
||||
3,
|
||||
4,
|
||||
5,
|
||||
6,
|
||||
7,
|
||||
8
|
||||
],
|
||||
"hash": "BF21AA5A0124E008B4BA51D538A225F90C9F94465BD5A238BF69B3E1F7513CE9"
|
||||
}
|
||||
]
|
||||
}
|
||||
@@ -0,0 +1,157 @@
|
||||
<?xml version="1.0" encoding="utf-8"?>
|
||||
<Project DefaultTargets="Build" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
|
||||
<ItemGroup Label="ProjectConfigurations">
|
||||
<ProjectConfiguration Include="Debug|Win32">
|
||||
<Configuration>Debug</Configuration>
|
||||
<Platform>Win32</Platform>
|
||||
</ProjectConfiguration>
|
||||
<ProjectConfiguration Include="Release|Win32">
|
||||
<Configuration>Release</Configuration>
|
||||
<Platform>Win32</Platform>
|
||||
</ProjectConfiguration>
|
||||
<ProjectConfiguration Include="Debug|x64">
|
||||
<Configuration>Debug</Configuration>
|
||||
<Platform>x64</Platform>
|
||||
</ProjectConfiguration>
|
||||
<ProjectConfiguration Include="Release|x64">
|
||||
<Configuration>Release</Configuration>
|
||||
<Platform>x64</Platform>
|
||||
</ProjectConfiguration>
|
||||
</ItemGroup>
|
||||
<PropertyGroup Label="Globals">
|
||||
<VCProjectVersion>17.0</VCProjectVersion>
|
||||
<Keyword>Win32Proj</Keyword>
|
||||
<ProjectGuid>{E48EC0C8-23EC-46AC-9EC1-E1457E919BB0}</ProjectGuid>
|
||||
<RootNamespace>WaveOpticsShader</RootNamespace>
|
||||
<WindowsTargetPlatformVersion>10.0</WindowsTargetPlatformVersion>
|
||||
</PropertyGroup>
|
||||
<Import Project="$(VCTargetsPath)\Microsoft.Cpp.Default.props" />
|
||||
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'" Label="Configuration">
|
||||
<ConfigurationType>Application</ConfigurationType>
|
||||
<UseDebugLibraries>true</UseDebugLibraries>
|
||||
<PlatformToolset>v145</PlatformToolset>
|
||||
<CharacterSet>Unicode</CharacterSet>
|
||||
</PropertyGroup>
|
||||
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Release|Win32'" Label="Configuration">
|
||||
<ConfigurationType>Application</ConfigurationType>
|
||||
<UseDebugLibraries>false</UseDebugLibraries>
|
||||
<PlatformToolset>v145</PlatformToolset>
|
||||
<WholeProgramOptimization>true</WholeProgramOptimization>
|
||||
<CharacterSet>Unicode</CharacterSet>
|
||||
</PropertyGroup>
|
||||
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|x64'" Label="Configuration">
|
||||
<ConfigurationType>Application</ConfigurationType>
|
||||
<UseDebugLibraries>true</UseDebugLibraries>
|
||||
<PlatformToolset>v145</PlatformToolset>
|
||||
<CharacterSet>Unicode</CharacterSet>
|
||||
</PropertyGroup>
|
||||
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Release|x64'" Label="Configuration">
|
||||
<ConfigurationType>Application</ConfigurationType>
|
||||
<UseDebugLibraries>false</UseDebugLibraries>
|
||||
<PlatformToolset>v145</PlatformToolset>
|
||||
<WholeProgramOptimization>true</WholeProgramOptimization>
|
||||
<CharacterSet>Unicode</CharacterSet>
|
||||
</PropertyGroup>
|
||||
<Import Project="$(VCTargetsPath)\Microsoft.Cpp.props" />
|
||||
<ImportGroup Label="ExtensionSettings">
|
||||
</ImportGroup>
|
||||
<ImportGroup Label="Shared">
|
||||
</ImportGroup>
|
||||
<ImportGroup Label="PropertySheets" Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">
|
||||
<Import Project="$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props" Condition="exists('$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props')" Label="LocalAppDataPlatform" />
|
||||
</ImportGroup>
|
||||
<ImportGroup Label="PropertySheets" Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">
|
||||
<Import Project="$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props" Condition="exists('$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props')" Label="LocalAppDataPlatform" />
|
||||
</ImportGroup>
|
||||
<ImportGroup Label="PropertySheets" Condition="'$(Configuration)|$(Platform)'=='Debug|x64'">
|
||||
<Import Project="$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props" Condition="exists('$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props')" Label="LocalAppDataPlatform" />
|
||||
</ImportGroup>
|
||||
<ImportGroup Label="PropertySheets" Condition="'$(Configuration)|$(Platform)'=='Release|x64'">
|
||||
<Import Project="$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props" Condition="exists('$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props')" Label="LocalAppDataPlatform" />
|
||||
</ImportGroup>
|
||||
<PropertyGroup Label="UserMacros" />
|
||||
<PropertyGroup>
|
||||
<OutDir>$(MSBuildThisFileDirectory)..\Release\</OutDir>
|
||||
</PropertyGroup>
|
||||
<ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">
|
||||
<ClCompile>
|
||||
<WarningLevel>Level3</WarningLevel>
|
||||
<SDLCheck>true</SDLCheck>
|
||||
<PreprocessorDefinitions>WIN32;_DEBUG;_CONSOLE;%(PreprocessorDefinitions)</PreprocessorDefinitions>
|
||||
<ConformanceMode>true</ConformanceMode>
|
||||
</ClCompile>
|
||||
<Link>
|
||||
<SubSystem>Console</SubSystem>
|
||||
<GenerateDebugInformation>true</GenerateDebugInformation>
|
||||
</Link>
|
||||
<FxCompile>
|
||||
<ShaderModel>4.1</ShaderModel>
|
||||
</FxCompile>
|
||||
</ItemDefinitionGroup>
|
||||
<ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">
|
||||
<ClCompile>
|
||||
<WarningLevel>Level3</WarningLevel>
|
||||
<FunctionLevelLinking>true</FunctionLevelLinking>
|
||||
<IntrinsicFunctions>true</IntrinsicFunctions>
|
||||
<SDLCheck>true</SDLCheck>
|
||||
<PreprocessorDefinitions>WIN32;NDEBUG;_CONSOLE;%(PreprocessorDefinitions)</PreprocessorDefinitions>
|
||||
<ConformanceMode>true</ConformanceMode>
|
||||
</ClCompile>
|
||||
<Link>
|
||||
<SubSystem>Console</SubSystem>
|
||||
<EnableCOMDATFolding>true</EnableCOMDATFolding>
|
||||
<OptimizeReferences>true</OptimizeReferences>
|
||||
<GenerateDebugInformation>true</GenerateDebugInformation>
|
||||
</Link>
|
||||
<FxCompile>
|
||||
<ShaderModel>4.1</ShaderModel>
|
||||
<CompileD2DCustomEffect>
|
||||
</CompileD2DCustomEffect>
|
||||
</FxCompile>
|
||||
</ItemDefinitionGroup>
|
||||
<ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Debug|x64'">
|
||||
<ClCompile>
|
||||
<WarningLevel>Level3</WarningLevel>
|
||||
<SDLCheck>true</SDLCheck>
|
||||
<PreprocessorDefinitions>_DEBUG;_CONSOLE;%(PreprocessorDefinitions)</PreprocessorDefinitions>
|
||||
<ConformanceMode>true</ConformanceMode>
|
||||
</ClCompile>
|
||||
<Link>
|
||||
<SubSystem>Console</SubSystem>
|
||||
<GenerateDebugInformation>true</GenerateDebugInformation>
|
||||
</Link>
|
||||
<FxCompile>
|
||||
<ShaderModel>4.1</ShaderModel>
|
||||
</FxCompile>
|
||||
</ItemDefinitionGroup>
|
||||
<ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Release|x64'">
|
||||
<ClCompile>
|
||||
<WarningLevel>Level3</WarningLevel>
|
||||
<FunctionLevelLinking>true</FunctionLevelLinking>
|
||||
<IntrinsicFunctions>true</IntrinsicFunctions>
|
||||
<SDLCheck>true</SDLCheck>
|
||||
<PreprocessorDefinitions>NDEBUG;_CONSOLE;%(PreprocessorDefinitions)</PreprocessorDefinitions>
|
||||
<ConformanceMode>true</ConformanceMode>
|
||||
</ClCompile>
|
||||
<Link>
|
||||
<SubSystem>Console</SubSystem>
|
||||
<EnableCOMDATFolding>true</EnableCOMDATFolding>
|
||||
<OptimizeReferences>true</OptimizeReferences>
|
||||
<GenerateDebugInformation>true</GenerateDebugInformation>
|
||||
</Link>
|
||||
<FxCompile>
|
||||
<ShaderModel>4.1</ShaderModel>
|
||||
</FxCompile>
|
||||
</ItemDefinitionGroup>
|
||||
<ItemGroup>
|
||||
<FxCompile Include="WaveOptics.hlsl">
|
||||
<ShaderType Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">Pixel</ShaderType>
|
||||
<ShaderType Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">Pixel</ShaderType>
|
||||
<ShaderType Condition="'$(Configuration)|$(Platform)'=='Debug|x64'">Pixel</ShaderType>
|
||||
<ShaderType Condition="'$(Configuration)|$(Platform)'=='Release|x64'">Pixel</ShaderType>
|
||||
</FxCompile>
|
||||
</ItemGroup>
|
||||
<Import Project="$(VCTargetsPath)\Microsoft.Cpp.targets" />
|
||||
<ImportGroup Label="ExtensionTargets">
|
||||
</ImportGroup>
|
||||
</Project>
|
||||
@@ -0,0 +1,22 @@
|
||||
<?xml version="1.0" encoding="utf-8"?>
|
||||
<Project ToolsVersion="4.0" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
|
||||
<ItemGroup>
|
||||
<Filter Include="ソース ファイル">
|
||||
<UniqueIdentifier>{4FC737F1-C7A5-4376-A066-2A32D752A2FF}</UniqueIdentifier>
|
||||
<Extensions>cpp;c;cc;cxx;c++;cppm;ixx;def;odl;idl;hpj;bat;asm;asmx</Extensions>
|
||||
</Filter>
|
||||
<Filter Include="ヘッダー ファイル">
|
||||
<UniqueIdentifier>{93995380-89BD-4b04-88EB-625FBE52EBFB}</UniqueIdentifier>
|
||||
<Extensions>h;hh;hpp;hxx;h++;hm;inl;inc;ipp;xsd</Extensions>
|
||||
</Filter>
|
||||
<Filter Include="リソース ファイル">
|
||||
<UniqueIdentifier>{67DA6AB6-F800-4c08-8B7A-83BB121AAD01}</UniqueIdentifier>
|
||||
<Extensions>rc;ico;cur;bmp;dlg;rc2;rct;bin;rgs;gif;jpg;jpeg;jpe;resx;tiff;tif;png;wav;mfcribbon-ms</Extensions>
|
||||
</Filter>
|
||||
</ItemGroup>
|
||||
<ItemGroup>
|
||||
<FxCompile Include="WaveOptics.hlsl">
|
||||
<Filter>ソース ファイル</Filter>
|
||||
</FxCompile>
|
||||
</ItemGroup>
|
||||
</Project>
|
||||
@@ -0,0 +1,28 @@
|
||||
Texture2D SourceTexture : register(t0);
|
||||
SamplerState SourceSampler : register(s0);
|
||||
Texture2D ConvolvedTexture : register(t1);
|
||||
SamplerState ConvolvedSampler : register(s1);
|
||||
|
||||
cbuffer Constants : register(b0)
|
||||
{
|
||||
float amount : packoffset(c0.x);
|
||||
float pad0 : packoffset(c0.y);
|
||||
float pad1 : packoffset(c0.z);
|
||||
float pad2 : packoffset(c0.w);
|
||||
};
|
||||
|
||||
float4 main(
|
||||
float4 position : SV_POSITION,
|
||||
float4 scenePosition : SCENE_POSITION,
|
||||
float4 uv0 : TEXCOORD0,
|
||||
float4 uv1 : TEXCOORD1
|
||||
) : SV_TARGET
|
||||
{
|
||||
float4 source = SourceTexture.SampleLevel(SourceSampler, uv0.xy, 0);
|
||||
if (amount <= 0.0)
|
||||
return source;
|
||||
|
||||
float4 convolved = ConvolvedTexture.SampleLevel(ConvolvedSampler, uv1.xy, 0);
|
||||
convolved.rgb = min(convolved.rgb, convolved.a.xxx);
|
||||
return lerp(source, convolved, amount);
|
||||
}
|
||||
@@ -0,0 +1,12 @@
|
||||
namespace WaveOptics.Tests;
|
||||
|
||||
internal readonly record struct Bgra(byte Blue, byte Green, byte Red, byte Alpha)
|
||||
{
|
||||
public static Bgra Transparent => default;
|
||||
|
||||
public static Bgra Opaque(byte blue, byte green, byte red) => new(blue, green, red, byte.MaxValue);
|
||||
|
||||
public Bgra Premultiplied() => new(Premultiply(Blue), Premultiply(Green), Premultiply(Red), Alpha);
|
||||
|
||||
byte Premultiply(byte value) => (byte)Math.Round(value * (double)Alpha / byte.MaxValue, MidpointRounding.AwayFromZero);
|
||||
}
|
||||
@@ -0,0 +1,28 @@
|
||||
using System.Drawing;
|
||||
using System.Numerics;
|
||||
using Vortice.Direct2D1;
|
||||
using YukkuriMovieMaker.Player.Video;
|
||||
|
||||
namespace WaveOptics.Tests;
|
||||
|
||||
internal static class EffectDescriptions
|
||||
{
|
||||
public const int Fps = 30;
|
||||
|
||||
static readonly Size ScreenSize = new(1920, 1080);
|
||||
|
||||
public static EffectDescription At(int frame, int length)
|
||||
{
|
||||
var timeline = new TimelineSourceDescription(
|
||||
ScreenSize,
|
||||
new FrameTime(frame, Fps),
|
||||
new FrameTime(length, Fps),
|
||||
Fps,
|
||||
TimelineSourceUsage.Playing,
|
||||
Guid.Empty,
|
||||
[]);
|
||||
var item = new TimelineItemSourceDescription(timeline, frame, length, 0);
|
||||
var draw = new DrawDescription(Vector3.Zero, Vector2.Zero, Vector2.One, Vector3.Zero, Matrix4x4.Identity, InterpolationMode.Linear, 1d, false, []);
|
||||
return new EffectDescription(item, draw, 0, 1, 0, 1);
|
||||
}
|
||||
}
|
||||
@@ -1,57 +0,0 @@
|
||||
using System.Numerics;
|
||||
using WaveOptics.Fourier;
|
||||
|
||||
namespace WaveOptics.Tests.Fourier;
|
||||
|
||||
public sealed class FastFourierTransformTests
|
||||
{
|
||||
[Fact]
|
||||
public void ForwardOfImpulseIsConstant()
|
||||
{
|
||||
var values = new Complex[16];
|
||||
values[0] = Complex.One;
|
||||
|
||||
FastFourierTransform.Forward(values);
|
||||
|
||||
foreach (var value in values)
|
||||
Assert.True(Complex.Abs(value - Complex.One) < 1e-12);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void OneDimensionalRoundTripRestoresInput()
|
||||
{
|
||||
var random = new Random(12345);
|
||||
var values = Enumerable.Range(0, 256)
|
||||
.Select(_ => new Complex(random.NextDouble() * 2 - 1, random.NextDouble() * 2 - 1))
|
||||
.ToArray();
|
||||
var expected = (Complex[])values.Clone();
|
||||
|
||||
FastFourierTransform.Forward(values);
|
||||
FastFourierTransform.Inverse(values);
|
||||
|
||||
AssertMaximumError(expected, values, 1e-11);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void TwoDimensionalRoundTripRestoresInput()
|
||||
{
|
||||
var random = new Random(67890);
|
||||
var values = Enumerable.Range(0, 64 * 32)
|
||||
.Select(_ => new Complex(random.NextDouble(), random.NextDouble()))
|
||||
.ToArray();
|
||||
var expected = (Complex[])values.Clone();
|
||||
|
||||
FastFourierTransform.Forward2D(values, 64, 32);
|
||||
FastFourierTransform.Inverse2D(values, 64, 32);
|
||||
|
||||
AssertMaximumError(expected, values, 1e-10);
|
||||
}
|
||||
|
||||
static void AssertMaximumError(Complex[] expected, Complex[] actual, double tolerance)
|
||||
{
|
||||
var maximum = 0d;
|
||||
for (var index = 0; index < expected.Length; index++)
|
||||
maximum = Math.Max(maximum, Complex.Abs(expected[index] - actual[index]));
|
||||
Assert.True(maximum <= tolerance, $"{maximum:R}");
|
||||
}
|
||||
}
|
||||
@@ -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);
|
||||
}
|
||||
}
|
||||
@@ -81,6 +81,25 @@ public sealed class FraunhoferPsfGeneratorTests
|
||||
Assert.True(obstructed[center, center] < unobstructed[center, center]);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void AnApertureWithoutAnOpenSampleYieldsNoPsf()
|
||||
{
|
||||
var descriptor = CreateBlockedDescriptor();
|
||||
|
||||
var generated = generator.TryGenerate(descriptor, out var result);
|
||||
|
||||
Assert.False(generated);
|
||||
Assert.Null(result);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void GeneratingFromAnApertureWithoutAnOpenSampleStillThrows()
|
||||
{
|
||||
var descriptor = CreateBlockedDescriptor();
|
||||
|
||||
Assert.Throws<InvalidOperationException>(() => generator.Generate(descriptor));
|
||||
}
|
||||
|
||||
static int FindFirstMinimum(PsfKernel kernel, int center)
|
||||
{
|
||||
for (var radius = 1; radius < center - 1; radius++)
|
||||
@@ -94,6 +113,9 @@ public sealed class FraunhoferPsfGeneratorTests
|
||||
throw new InvalidOperationException();
|
||||
}
|
||||
|
||||
static PsfDescriptor CreateBlockedDescriptor()
|
||||
=> new(128, 32, 31, 550, 8, 4, ApertureShape.RegularPolygon, 4, -357.5, 0.95, default);
|
||||
|
||||
static PsfDescriptor CreateDescriptor(
|
||||
double wavelengthNanometers = 550,
|
||||
double fNumber = 8,
|
||||
|
||||
@@ -0,0 +1,37 @@
|
||||
using System.IO;
|
||||
using System.Reflection;
|
||||
using System.Runtime.CompilerServices;
|
||||
|
||||
namespace WaveOptics.Tests;
|
||||
|
||||
internal static class HostAssemblyResolver
|
||||
{
|
||||
const string MetadataKey = "HostDirectory";
|
||||
const string AssemblyExtension = ".dll";
|
||||
|
||||
public static string Directory { get; } = ReadDirectory();
|
||||
|
||||
public static bool IsConfigured => Directory.Length != 0 && System.IO.Directory.Exists(Directory);
|
||||
|
||||
[ModuleInitializer]
|
||||
internal static void Initialize()
|
||||
{
|
||||
if (!IsConfigured)
|
||||
return;
|
||||
|
||||
AppDomain.CurrentDomain.AssemblyResolve += (_, arguments) =>
|
||||
{
|
||||
var name = new AssemblyName(arguments.Name).Name;
|
||||
if (name is null)
|
||||
return null;
|
||||
|
||||
var candidate = Path.Combine(Directory, name + AssemblyExtension);
|
||||
return File.Exists(candidate) ? Assembly.LoadFrom(candidate) : null;
|
||||
};
|
||||
}
|
||||
|
||||
static string ReadDirectory() => typeof(HostAssemblyResolver).Assembly
|
||||
.GetCustomAttributes<AssemblyMetadataAttribute>()
|
||||
.FirstOrDefault(attribute => string.Equals(attribute.Key, MetadataKey, StringComparison.Ordinal))
|
||||
?.Value ?? string.Empty;
|
||||
}
|
||||
@@ -0,0 +1,31 @@
|
||||
using System.Windows;
|
||||
using Telemetry;
|
||||
using WaveOptics.Effects;
|
||||
|
||||
namespace WaveOptics.Tests;
|
||||
|
||||
public sealed class HostIntegrationTests
|
||||
{
|
||||
[Fact]
|
||||
public void OutsideAWpfApplicationNoTelemetryIsStartedOrSent()
|
||||
{
|
||||
Assert.Null(Application.Current);
|
||||
|
||||
WaveOpticsTelemetry.EnsureStartedOnce();
|
||||
WaveOpticsTelemetry.Report(new InvalidOperationException());
|
||||
|
||||
Assert.Null(ProcessState.Read("DrainClaimed"));
|
||||
Assert.Null(ProcessState.Read("SentCount"));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void OutsideAWpfApplicationTheEffectCanStillBeCreated()
|
||||
{
|
||||
Assert.Null(Application.Current);
|
||||
|
||||
var effect = new WaveOpticsEffect();
|
||||
|
||||
Assert.Equal(Texts.WaveOptics, effect.Label);
|
||||
Assert.Null(ProcessState.Read("DrainClaimed"));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,10 @@
|
||||
using System.IO.Packaging;
|
||||
using System.Runtime.CompilerServices;
|
||||
|
||||
namespace WaveOptics.Tests;
|
||||
|
||||
internal static class PackUriScheme
|
||||
{
|
||||
[ModuleInitializer]
|
||||
internal static void Register() => _ = PackUriHelper.UriSchemePack;
|
||||
}
|
||||
@@ -0,0 +1,95 @@
|
||||
using System.Numerics;
|
||||
using System.Runtime.InteropServices;
|
||||
using Vortice.Direct2D1;
|
||||
using Vortice.Mathematics;
|
||||
using YukkuriMovieMaker.Commons;
|
||||
|
||||
namespace WaveOptics.Tests;
|
||||
|
||||
internal sealed class Rendering
|
||||
{
|
||||
readonly byte[] pixels;
|
||||
|
||||
public int Left { get; }
|
||||
|
||||
public int Top { get; }
|
||||
|
||||
public int Width { get; }
|
||||
|
||||
public int Height { get; }
|
||||
|
||||
public int Right => Left + Width;
|
||||
|
||||
public int Bottom => Top + Height;
|
||||
|
||||
Rendering(int left, int top, int width, int height, byte[] pixels)
|
||||
{
|
||||
Left = left;
|
||||
Top = top;
|
||||
Width = width;
|
||||
Height = height;
|
||||
this.pixels = pixels;
|
||||
}
|
||||
|
||||
public static Rendering Capture(IGraphicsDevicesAndContext devices, ID2D1Image image)
|
||||
{
|
||||
var context = devices.DeviceContext;
|
||||
var bounds = context.GetImageLocalBounds(image);
|
||||
var left = (int)Math.Floor(bounds.Left);
|
||||
var top = (int)Math.Floor(bounds.Top);
|
||||
var width = (int)Math.Ceiling(bounds.Right) - left;
|
||||
var height = (int)Math.Ceiling(bounds.Bottom) - top;
|
||||
var stride = width * SourceImage.BytesPerPixel;
|
||||
var size = new SizeI(width, height);
|
||||
|
||||
using var target = context.CreateBitmap(size, nint.Zero, stride,
|
||||
new BitmapProperties1(SourceImage.PixelFormat, SourceImage.Dpi, SourceImage.Dpi, BitmapOptions.Target));
|
||||
using var readback = context.CreateBitmap(size, nint.Zero, stride,
|
||||
new BitmapProperties1(SourceImage.PixelFormat, SourceImage.Dpi, SourceImage.Dpi, BitmapOptions.CpuRead | BitmapOptions.CannotDraw));
|
||||
|
||||
context.Target = target;
|
||||
context.BeginDraw();
|
||||
context.Clear(new Color4(0f, 0f, 0f, 0f));
|
||||
context.DrawImage(image, new Vector2(-left, -top), null, InterpolationMode.NearestNeighbor, CompositeMode.SourceCopy);
|
||||
context.EndDraw();
|
||||
context.Target = null;
|
||||
|
||||
readback.CopyFromBitmap(target);
|
||||
var pixels = new byte[stride * height];
|
||||
var mapped = readback.Map(MapOptions.Read);
|
||||
try
|
||||
{
|
||||
for (var y = 0; y < height; y++)
|
||||
Marshal.Copy(mapped.Bits + y * (int)mapped.Pitch, pixels, y * stride, stride);
|
||||
}
|
||||
finally
|
||||
{
|
||||
readback.Unmap();
|
||||
}
|
||||
|
||||
return new Rendering(left, top, width, height, pixels);
|
||||
}
|
||||
|
||||
public Bgra this[int x, int y]
|
||||
{
|
||||
get
|
||||
{
|
||||
var offset = ((y - Top) * Width + (x - Left)) * SourceImage.BytesPerPixel;
|
||||
return new Bgra(pixels[offset], pixels[offset + 1], pixels[offset + 2], pixels[offset + 3]);
|
||||
}
|
||||
}
|
||||
|
||||
public bool Contains(int x, int y) => x >= Left && y >= Top && x < Right && y < Bottom;
|
||||
|
||||
public bool SamePixelsAs(Rendering other)
|
||||
=> Left == other.Left && Top == other.Top && Width == other.Width && Height == other.Height && pixels.AsSpan().SequenceEqual(other.pixels);
|
||||
|
||||
public IEnumerable<(int X, int Y)> Coordinates()
|
||||
{
|
||||
for (var y = Top; y < Bottom; y++)
|
||||
{
|
||||
for (var x = Left; x < Right; x++)
|
||||
yield return (x, y);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,59 @@
|
||||
using Vortice.DCommon;
|
||||
using Vortice.Direct2D1;
|
||||
using Vortice.DXGI;
|
||||
using Vortice.Mathematics;
|
||||
using YukkuriMovieMaker.Commons;
|
||||
|
||||
namespace WaveOptics.Tests;
|
||||
|
||||
internal sealed class SourceImage : IDisposable
|
||||
{
|
||||
public const float Dpi = 96f;
|
||||
public const int BytesPerPixel = 4;
|
||||
|
||||
public static readonly PixelFormat PixelFormat = new(Format.B8G8R8A8_UNorm, Vortice.DCommon.AlphaMode.Premultiplied);
|
||||
|
||||
readonly Func<int, int, Bgra> pixelOf;
|
||||
|
||||
public int Width { get; }
|
||||
|
||||
public int Height { get; }
|
||||
|
||||
public ID2D1Bitmap1 Bitmap { get; }
|
||||
|
||||
public SourceImage(IGraphicsDevicesAndContext devices, int width, int height, Func<int, int, Bgra> pixelOf)
|
||||
{
|
||||
this.pixelOf = pixelOf;
|
||||
Width = width;
|
||||
Height = height;
|
||||
|
||||
var stride = width * BytesPerPixel;
|
||||
var pixels = new byte[stride * height];
|
||||
for (var y = 0; y < height; y++)
|
||||
{
|
||||
for (var x = 0; x < width; x++)
|
||||
{
|
||||
var (blue, green, red, alpha) = pixelOf(x, y).Premultiplied();
|
||||
var offset = y * stride + x * BytesPerPixel;
|
||||
pixels[offset] = blue;
|
||||
pixels[offset + 1] = green;
|
||||
pixels[offset + 2] = red;
|
||||
pixels[offset + 3] = alpha;
|
||||
}
|
||||
}
|
||||
|
||||
Bitmap = devices.DeviceContext.CreateBitmap(
|
||||
new SizeI(width, height), nint.Zero, stride,
|
||||
new BitmapProperties1(PixelFormat, Dpi, Dpi, BitmapOptions.None));
|
||||
Bitmap.CopyFromMemory(pixels, stride);
|
||||
}
|
||||
|
||||
public static SourceImage Solid(IGraphicsDevicesAndContext devices, int width, int height, Bgra color)
|
||||
=> new(devices, width, height, (_, _) => color);
|
||||
|
||||
public Bgra this[int x, int y] => pixelOf(x, y).Premultiplied();
|
||||
|
||||
public bool Contains(int x, int y) => x >= 0 && y >= 0 && x < Width && y < Height;
|
||||
|
||||
public void Dispose() => Bitmap.Dispose();
|
||||
}
|
||||
@@ -0,0 +1,68 @@
|
||||
using System.Collections;
|
||||
using System.Globalization;
|
||||
using System.Reflection;
|
||||
using System.Resources;
|
||||
using WaveOptics.Effects;
|
||||
|
||||
namespace WaveOptics.Tests;
|
||||
|
||||
public sealed class TextsTests
|
||||
{
|
||||
const string NeutralCulture = "ja-JP";
|
||||
|
||||
public static readonly TheoryData<string> Cultures = [NeutralCulture, "en-US", "zh-CN", "zh-TW", "ko-KR", "es-ES", "ar-SA", "id-ID"];
|
||||
|
||||
static readonly string[] Keys = typeof(Texts)
|
||||
.GetProperties(BindingFlags.Public | BindingFlags.Static)
|
||||
.Where(property => property.PropertyType == typeof(string) && property.Name != nameof(Texts.CurrentCulture))
|
||||
.Select(property => property.Name)
|
||||
.ToArray();
|
||||
|
||||
static ResourceSet ResourcesOf(string culture)
|
||||
=> Texts.ResourceManager.GetResourceSet(culture == NeutralCulture ? CultureInfo.InvariantCulture : CultureInfo.GetCultureInfo(culture), true, false)!;
|
||||
|
||||
[Fact]
|
||||
public void EveryLocalizedKeyHasAProperty()
|
||||
{
|
||||
var resources = Texts.ResourceManager.GetResourceSet(CultureInfo.InvariantCulture, true, false)!;
|
||||
var keys = resources.Cast<DictionaryEntry>().Select(entry => (string)entry.Key).Where(key => key != nameof(Texts.CurrentCulture));
|
||||
|
||||
Assert.Equal(keys.Order(), Keys.Order());
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[MemberData(nameof(Cultures))]
|
||||
public void EveryKeyIsTranslated(string culture)
|
||||
{
|
||||
var resources = ResourcesOf(culture);
|
||||
|
||||
Assert.All(Keys, key => Assert.False(string.IsNullOrWhiteSpace(resources.GetString(key)), key));
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[MemberData(nameof(Cultures))]
|
||||
public void EveryCultureCarriesItsOwnTranslations(string culture)
|
||||
{
|
||||
var cultureInfo = CultureInfo.GetCultureInfo(culture);
|
||||
|
||||
Assert.Equal(culture.ToLowerInvariant(), Texts.ResourceManager.GetString(nameof(Texts.CurrentCulture), cultureInfo));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void JapaneseIsTheNeutralLanguage()
|
||||
{
|
||||
var neutral = Texts.ResourceManager.GetString(nameof(Texts.WaveOptics), CultureInfo.InvariantCulture);
|
||||
|
||||
Assert.Equal("波動光学", neutral);
|
||||
Assert.Equal(neutral, Texts.ResourceManager.GetString(nameof(Texts.WaveOptics), CultureInfo.GetCultureInfo(NeutralCulture)));
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[MemberData(nameof(Cultures))]
|
||||
public void TheUpdateMessageEmbedsTheVersion(string culture)
|
||||
{
|
||||
var message = string.Format(CultureInfo.InvariantCulture, ResourcesOf(culture).GetString(nameof(Texts.UpdateAvailableMessage))!, "v1.2.3");
|
||||
|
||||
Assert.Contains("v1.2.3", message);
|
||||
}
|
||||
}
|
||||
@@ -2,6 +2,7 @@
|
||||
|
||||
<PropertyGroup>
|
||||
<TargetFramework>net10.0-windows10.0.19041.0</TargetFramework>
|
||||
<UseWPF>true</UseWPF>
|
||||
<ImplicitUsings>enable</ImplicitUsings>
|
||||
<Nullable>enable</Nullable>
|
||||
<IsPackable>false</IsPackable>
|
||||
@@ -12,20 +13,69 @@
|
||||
|
||||
<ItemGroup>
|
||||
<PackageReference Include="coverlet.collector" Version="10.0.1">
|
||||
<PrivateAssets>all</PrivateAssets>
|
||||
<IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets>
|
||||
</PackageReference>
|
||||
<PackageReference Include="Microsoft.NET.Test.Sdk" Version="18.6.0" />
|
||||
<PackageReference Include="xunit.runner.visualstudio" Version="3.1.5">
|
||||
<PrivateAssets>all</PrivateAssets>
|
||||
<IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets>
|
||||
</PackageReference>
|
||||
<PackageReference Include="xunit.v3" Version="3.2.2" />
|
||||
<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="..\WaveOptics.Abstractions\WaveOptics.Abstractions.csproj" />
|
||||
<ProjectReference Include="..\Wave Optics\WaveOptics.csproj" AdditionalProperties="SkipPluginDeploy=true" />
|
||||
<ProjectReference Include="..\WaveOptics\WaveOptics.csproj" SetConfiguration="Configuration=$(Configuration)">
|
||||
<AdditionalProperties Condition="'$(BuildingSolutionFile)' != 'true'">SkipPluginDeploy=true</AdditionalProperties>
|
||||
</ProjectReference>
|
||||
</ItemGroup>
|
||||
|
||||
<ItemGroup>
|
||||
<AssemblyMetadata Include="HostDirectory" Value="$(YMM4DirPath)" />
|
||||
</ItemGroup>
|
||||
|
||||
<ItemGroup>
|
||||
<Reference Include="Newtonsoft.Json">
|
||||
<HintPath>$(YMM4DirPath)Newtonsoft.Json.dll</HintPath>
|
||||
<Private>false</Private>
|
||||
</Reference>
|
||||
<Reference Include="SharpGen.Runtime">
|
||||
<HintPath>$(YMM4DirPath)SharpGen.Runtime.dll</HintPath>
|
||||
<Private>false</Private>
|
||||
</Reference>
|
||||
<Reference Include="SharpGen.Runtime.COM">
|
||||
<HintPath>$(YMM4DirPath)SharpGen.Runtime.COM.dll</HintPath>
|
||||
<Private>false</Private>
|
||||
</Reference>
|
||||
<Reference Include="Vortice.Direct2D1">
|
||||
<HintPath>$(YMM4DirPath)Vortice.Direct2D1.dll</HintPath>
|
||||
<Private>false</Private>
|
||||
</Reference>
|
||||
<Reference Include="Vortice.Direct3D11">
|
||||
<HintPath>$(YMM4DirPath)Vortice.Direct3D11.dll</HintPath>
|
||||
<Private>false</Private>
|
||||
</Reference>
|
||||
<Reference Include="Vortice.DirectX">
|
||||
<HintPath>$(YMM4DirPath)Vortice.DirectX.dll</HintPath>
|
||||
<Private>false</Private>
|
||||
</Reference>
|
||||
<Reference Include="Vortice.DXGI">
|
||||
<HintPath>$(YMM4DirPath)Vortice.DXGI.dll</HintPath>
|
||||
<Private>false</Private>
|
||||
</Reference>
|
||||
<Reference Include="Vortice.Mathematics">
|
||||
<HintPath>$(YMM4DirPath)Vortice.Mathematics.dll</HintPath>
|
||||
<Private>false</Private>
|
||||
</Reference>
|
||||
<Reference Include="YukkuriMovieMaker.Controls">
|
||||
<HintPath>$(YMM4DirPath)YukkuriMovieMaker.Controls.dll</HintPath>
|
||||
<Private>false</Private>
|
||||
</Reference>
|
||||
<Reference Include="YukkuriMovieMaker.Plugin">
|
||||
<HintPath>$(YMM4DirPath)YukkuriMovieMaker.Plugin.dll</HintPath>
|
||||
<Private>false</Private>
|
||||
</Reference>
|
||||
</ItemGroup>
|
||||
|
||||
<ItemGroup>
|
||||
|
||||
@@ -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,215 @@
|
||||
using System.Numerics;
|
||||
using Vortice.Direct2D1;
|
||||
using Vortice.Direct2D1.Effects;
|
||||
using Vortice.Mathematics;
|
||||
using WaveOptics.Rendering;
|
||||
using YukkuriMovieMaker.Commons;
|
||||
|
||||
namespace WaveOptics.Tests;
|
||||
|
||||
[Collection("Direct2D")]
|
||||
public sealed class WaveOpticsCustomEffectTests
|
||||
{
|
||||
const int AmountIndex = 0;
|
||||
const int Width = 40;
|
||||
const int Height = 24;
|
||||
|
||||
static readonly Bgra Blue = Bgra.Opaque(255, 0, 0);
|
||||
static readonly Bgra HalfConvolved = new(0, 0, 0, 128);
|
||||
|
||||
static Rendering Render(IGraphicsDevicesAndContext devices, ID2D1Image source, ID2D1Image convolved, float amount)
|
||||
{
|
||||
using var effect = new WaveOpticsCustomEffect(devices);
|
||||
effect.SetInput(0, source, true);
|
||||
effect.SetInput(1, convolved, true);
|
||||
effect.Amount = amount;
|
||||
using var output = effect.Output;
|
||||
return Rendering.Capture(devices, output);
|
||||
}
|
||||
|
||||
static AffineTransform2D Translate(IGraphicsDevicesAndContext devices, ID2D1Image image, float dx, float dy)
|
||||
{
|
||||
var transform = new AffineTransform2D(devices.DeviceContext)
|
||||
{
|
||||
InterPolationMode = AffineTransform2DInterpolationMode.NearestNeighbor,
|
||||
BorderMode = BorderMode.Hard,
|
||||
TransformMatrix = Matrix3x2.CreateTranslation(dx, dy),
|
||||
};
|
||||
transform.SetInput(0, image, true);
|
||||
return transform;
|
||||
}
|
||||
|
||||
static ID2D1Bitmap1 RawBitmap(IGraphicsDevicesAndContext devices, int width, int height, Bgra premultiplied)
|
||||
{
|
||||
var stride = width * SourceImage.BytesPerPixel;
|
||||
var pixels = new byte[stride * height];
|
||||
for (var offset = 0; offset < pixels.Length; offset += SourceImage.BytesPerPixel)
|
||||
{
|
||||
pixels[offset] = premultiplied.Blue;
|
||||
pixels[offset + 1] = premultiplied.Green;
|
||||
pixels[offset + 2] = premultiplied.Red;
|
||||
pixels[offset + 3] = premultiplied.Alpha;
|
||||
}
|
||||
|
||||
var bitmap = devices.DeviceContext.CreateBitmap(
|
||||
new SizeI(width, height), nint.Zero, stride,
|
||||
new BitmapProperties1(SourceImage.PixelFormat, SourceImage.Dpi, SourceImage.Dpi, BitmapOptions.None));
|
||||
bitmap.CopyFromMemory(pixels, stride);
|
||||
return bitmap;
|
||||
}
|
||||
|
||||
static bool WithinRounding(Bgra expected, Bgra actual)
|
||||
=> Math.Abs(expected.Blue - actual.Blue) <= 1 && Math.Abs(expected.Green - actual.Green) <= 1 && Math.Abs(expected.Red - actual.Red) <= 1 && Math.Abs(expected.Alpha - actual.Alpha) <= 1;
|
||||
|
||||
static Bgra Mix(Bgra convolved, Bgra source, float amount)
|
||||
{
|
||||
byte Channel(byte convolvedValue, byte sourceValue) => (byte)Math.Round(convolvedValue * amount + sourceValue * (1d - amount), MidpointRounding.AwayFromZero);
|
||||
return new Bgra(Channel(convolved.Blue, source.Blue), Channel(convolved.Green, source.Green), Channel(convolved.Red, source.Red), Channel(convolved.Alpha, source.Alpha));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void TheEffectIsEnabledOnceCreated()
|
||||
{
|
||||
using var devices = new GraphicsDevices();
|
||||
using var context = devices.CreateContext();
|
||||
using var effect = new WaveOpticsCustomEffect(context);
|
||||
|
||||
Assert.True(effect.IsEnabled);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void TheAmountStartsFromZero()
|
||||
{
|
||||
using var devices = new GraphicsDevices();
|
||||
using var context = devices.CreateContext();
|
||||
using var effect = new WaveOpticsCustomEffect(context);
|
||||
|
||||
Assert.Equal(0f, effect.GetFloatValue(AmountIndex));
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[InlineData(-0.5f, 0f)]
|
||||
[InlineData(0f, 0f)]
|
||||
[InlineData(0.4f, 0.4f)]
|
||||
[InlineData(1f, 1f)]
|
||||
[InlineData(1.5f, 1f)]
|
||||
[InlineData(float.MaxValue, 1f)]
|
||||
public void TheAmountIsClampedToTheUnitRange(float value, float expected)
|
||||
{
|
||||
using var devices = new GraphicsDevices();
|
||||
using var context = devices.CreateContext();
|
||||
using var effect = new WaveOpticsCustomEffect(context);
|
||||
|
||||
effect.Amount = value;
|
||||
|
||||
Assert.Equal(expected, effect.GetFloatValue(AmountIndex));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void TheOutputBoundsCoverTheSourceAndTheConvolution()
|
||||
{
|
||||
using var devices = new GraphicsDevices();
|
||||
using var context = devices.CreateContext();
|
||||
using var source = SourceImage.Solid(context, Width, Height, Blue);
|
||||
using var convolved = SourceImage.Solid(context, 8, 8, HalfConvolved);
|
||||
using var moved = Translate(context, convolved.Bitmap, 50f, -6f);
|
||||
using var movedOutput = moved.Output;
|
||||
using var effect = new WaveOpticsCustomEffect(context);
|
||||
effect.SetInput(0, source.Bitmap, true);
|
||||
effect.SetInput(1, movedOutput, true);
|
||||
effect.Amount = 1f;
|
||||
using var output = effect.Output;
|
||||
|
||||
var bounds = context.DeviceContext.GetImageLocalBounds(output);
|
||||
|
||||
Assert.Equal(0f, bounds.Left);
|
||||
Assert.Equal(-6f, bounds.Top);
|
||||
Assert.Equal(58f, bounds.Right);
|
||||
Assert.Equal((float)Height, bounds.Bottom);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void WithoutAmountTheOutputBoundsAreThoseOfTheSource()
|
||||
{
|
||||
using var devices = new GraphicsDevices();
|
||||
using var context = devices.CreateContext();
|
||||
using var source = SourceImage.Solid(context, Width, Height, Blue);
|
||||
using var convolved = SourceImage.Solid(context, 8, 8, HalfConvolved);
|
||||
using var moved = Translate(context, convolved.Bitmap, 50f, -6f);
|
||||
using var movedOutput = moved.Output;
|
||||
using var effect = new WaveOpticsCustomEffect(context);
|
||||
effect.SetInput(0, source.Bitmap, true);
|
||||
effect.SetInput(1, movedOutput, true);
|
||||
effect.Amount = 1f;
|
||||
using var output = effect.Output;
|
||||
context.DeviceContext.GetImageLocalBounds(output);
|
||||
|
||||
effect.Amount = 0f;
|
||||
var bounds = context.DeviceContext.GetImageLocalBounds(output);
|
||||
|
||||
Assert.Equal((0f, 0f, (float)Width, (float)Height), (bounds.Left, bounds.Top, bounds.Right, bounds.Bottom));
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[InlineData(0f)]
|
||||
[InlineData(-1f)]
|
||||
public void WithoutAmountTheSourcePassesThroughUntouched(float amount)
|
||||
{
|
||||
using var devices = new GraphicsDevices();
|
||||
using var context = devices.CreateContext();
|
||||
using var source = SourceImage.Solid(context, Width, Height, Blue);
|
||||
using var convolved = SourceImage.Solid(context, Width, Height, HalfConvolved);
|
||||
|
||||
var rendering = Render(context, source.Bitmap, convolved.Bitmap, amount);
|
||||
|
||||
Assert.All(rendering.Coordinates(), point => Assert.Equal(source[point.X, point.Y], rendering[point.X, point.Y]));
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[InlineData(1f)]
|
||||
[InlineData(0.5f)]
|
||||
[InlineData(0.25f)]
|
||||
public void TheSourceGivesWayToTheConvolutionByTheAmount(float amount)
|
||||
{
|
||||
using var devices = new GraphicsDevices();
|
||||
using var context = devices.CreateContext();
|
||||
using var source = SourceImage.Solid(context, Width, Height, Blue);
|
||||
using var convolved = SourceImage.Solid(context, Width, Height, HalfConvolved);
|
||||
var expected = Mix(HalfConvolved.Premultiplied(), Blue.Premultiplied(), amount);
|
||||
|
||||
var rendering = Render(context, source.Bitmap, convolved.Bitmap, amount);
|
||||
|
||||
Assert.All(rendering.Coordinates(), point => Assert.True(WithinRounding(expected, rendering[point.X, point.Y]), $"({point.X}, {point.Y}) {rendering[point.X, point.Y]}"));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void AtTheFullAmountOnlyTheConvolutionIsDrawn()
|
||||
{
|
||||
using var devices = new GraphicsDevices();
|
||||
using var context = devices.CreateContext();
|
||||
using var source = SourceImage.Solid(context, Width, Height, Blue);
|
||||
using var convolved = SourceImage.Solid(context, 8, 8, HalfConvolved);
|
||||
using var moved = Translate(context, convolved.Bitmap, 50f, 4f);
|
||||
using var movedOutput = moved.Output;
|
||||
var expected = Mix(HalfConvolved.Premultiplied(), Bgra.Transparent, 1f);
|
||||
|
||||
var rendering = Render(context, source.Bitmap, movedOutput, 1f);
|
||||
|
||||
Assert.True(WithinRounding(expected, rendering[53, 7]), $"{rendering[53, 7]}");
|
||||
Assert.Equal(Bgra.Transparent, rendering[10, 10]);
|
||||
Assert.Equal(Bgra.Transparent, rendering[45, 10]);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void AConvolvedColorAboveItsAlphaIsCappedAtTheAlpha()
|
||||
{
|
||||
using var devices = new GraphicsDevices();
|
||||
using var context = devices.CreateContext();
|
||||
using var source = SourceImage.Solid(context, Width, Height, Bgra.Transparent);
|
||||
using var convolved = RawBitmap(context, Width, Height, new Bgra(200, 160, 120, 100));
|
||||
|
||||
var rendering = Render(context, source.Bitmap, convolved, 1f);
|
||||
|
||||
Assert.All(rendering.Coordinates(), point => Assert.True(WithinRounding(new Bgra(100, 100, 100, 100), rendering[point.X, point.Y]), $"({point.X}, {point.Y}) {rendering[point.X, point.Y]}"));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,294 @@
|
||||
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]));
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[InlineData(false)]
|
||||
[InlineData(true)]
|
||||
public void OnTheCpuAProcessorThatOnlyToggledTheDitherDrawsLikeAFreshOne(bool linear)
|
||||
{
|
||||
using var devices = new GraphicsDevices();
|
||||
using var context = devices.CreateContext();
|
||||
using var source = new SourceImage(context, Size, Size, Shape);
|
||||
var effect = Effect();
|
||||
effect.Linear = linear;
|
||||
effect.Gain.Values[0].Value = 60d;
|
||||
using var processor = Processor(context, effect, new Reports().CreateGuardian(), false);
|
||||
processor.SetInput(source.Bitmap);
|
||||
|
||||
foreach (var dither in new[] { false, true, false, true })
|
||||
{
|
||||
effect.Dither = dither;
|
||||
var expected = CpuReference(context, source, effect, 0);
|
||||
|
||||
var reused = RenderFrame(context, processor, 0);
|
||||
|
||||
Assert.True(reused.SamePixelsAs(expected), $"dither {dither}");
|
||||
}
|
||||
}
|
||||
|
||||
static Bgra TwoTone(int x, int y)
|
||||
=> x is >= 20 and < 52 && y is >= 18 and < 50 ? (x < 36 ? Bgra.Opaque(255, 255, 255) : Bgra.Opaque(0, 0, 0)) : Bgra.Transparent;
|
||||
|
||||
[Fact]
|
||||
public void OnTheCpuTheLightSettingsReachTheEffect()
|
||||
{
|
||||
using var devices = new GraphicsDevices();
|
||||
using var context = devices.CreateContext();
|
||||
using var source = new SourceImage(context, Size, Size, TwoTone);
|
||||
var effect = Effect();
|
||||
using var processor = Processor(context, effect, new Reports().CreateGuardian(), false);
|
||||
processor.SetInput(source.Bitmap);
|
||||
var plain = RenderFrame(context, processor, 0);
|
||||
|
||||
effect.Linear = true;
|
||||
var linear = RenderFrame(context, processor, 0);
|
||||
effect.HighlightThreshold.Values[0].Value = 40d;
|
||||
effect.HighlightBoost.Values[0].Value = 30d;
|
||||
var boosted = RenderFrame(context, processor, 0);
|
||||
|
||||
Assert.False(plain.SamePixelsAs(linear), "plain linear");
|
||||
Assert.False(linear.SamePixelsAs(boosted), "linear boosted");
|
||||
Assert.True(boosted.SamePixelsAs(CpuReference(context, source, effect, 0)));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,522 @@
|
||||
using System.Globalization;
|
||||
using System.Numerics;
|
||||
using ComputeWeave;
|
||||
using Vortice.Direct2D1;
|
||||
using Vortice.Direct2D1.Effects;
|
||||
using WaveOptics.Effects;
|
||||
using WaveOptics.Rendering;
|
||||
using YukkuriMovieMaker.Commons;
|
||||
using YukkuriMovieMaker.Json;
|
||||
using YukkuriMovieMaker.Player.Video;
|
||||
|
||||
namespace WaveOptics.Tests;
|
||||
|
||||
[Collection("Direct2D")]
|
||||
public sealed class WaveOpticsEffectProcessorTests
|
||||
{
|
||||
const int Size = 64;
|
||||
const int Length = 30;
|
||||
const int Start = 16;
|
||||
const int End = 48;
|
||||
|
||||
static readonly Bgra Gray = Bgra.Opaque(192, 192, 192);
|
||||
|
||||
static Bgra CenteredSquare(int x, int y) => x is >= Start and < End && y is >= Start and < End ? Gray : Bgra.Transparent;
|
||||
|
||||
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 Animation Linear(double from, double to)
|
||||
=> Json.LoadFromText<Animation>(string.Create(CultureInfo.InvariantCulture, $$"""{"AnimationType":"直線移動","Values":[{"Value":{{from}}},{"Value":{{to}}}]}"""))!;
|
||||
|
||||
static Rendering RenderFrame(IGraphicsDevicesAndContext devices, IVideoEffectProcessor processor, int frame)
|
||||
{
|
||||
processor.Update(EffectDescriptions.At(frame, Length));
|
||||
return Rendering.Capture(devices, processor.Output);
|
||||
}
|
||||
|
||||
static void AssertSameAsSource(Rendering rendering, SourceImage source)
|
||||
{
|
||||
Assert.Equal((0, 0, source.Width, source.Height), (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]));
|
||||
}
|
||||
|
||||
static Bgra PixelAt(Rendering rendering, int x, int y) => rendering.Contains(x, y) ? rendering[x, y] : Bgra.Transparent;
|
||||
|
||||
static bool HasLightOutside(Rendering rendering, SourceImage source)
|
||||
=> rendering.Coordinates().Any(point => (!source.Contains(point.X, point.Y) || source[point.X, point.Y].Alpha == 0) && rendering[point.X, point.Y].Alpha > 0);
|
||||
|
||||
static int DistanceFromSquare(int x, int y)
|
||||
=> Math.Max(Math.Max(Math.Max(Start - x, x - (End - 1)), Math.Max(Start - y, y - (End - 1))), 0);
|
||||
|
||||
static bool WithinRounding(Bgra expected, Bgra actual)
|
||||
=> Math.Abs(expected.Blue - actual.Blue) <= 1 && Math.Abs(expected.Green - actual.Green) <= 1 && Math.Abs(expected.Red - actual.Red) <= 1 && Math.Abs(expected.Alpha - actual.Alpha) <= 1;
|
||||
|
||||
[Fact]
|
||||
public void TheProcessorHandsTheDrawDescriptionBackUnchanged()
|
||||
{
|
||||
using var devices = new GraphicsDevices();
|
||||
using var context = devices.CreateContext();
|
||||
using var source = new SourceImage(context, Size, Size, CenteredSquare);
|
||||
using var processor = new WaveOpticsEffect().CreateVideoEffect(context);
|
||||
processor.SetInput(source.Bitmap);
|
||||
var description = EffectDescriptions.At(0, Length);
|
||||
|
||||
var draw = processor.Update(description);
|
||||
|
||||
Assert.Same(description.DrawDescription, draw);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void TheBlurSpreadsOutToTheKernelRadius()
|
||||
{
|
||||
using var devices = new GraphicsDevices();
|
||||
using var context = devices.CreateContext();
|
||||
RequireInterop(context);
|
||||
using var source = new SourceImage(context, Size, Size, CenteredSquare);
|
||||
var effect = new WaveOpticsEffect { KernelRadius = 4 };
|
||||
effect.FNumber.Values[0].Value = 32d;
|
||||
using var processor = effect.CreateVideoEffect(context);
|
||||
processor.SetInput(source.Bitmap);
|
||||
|
||||
var rendering = RenderFrame(context, processor, 0);
|
||||
|
||||
Assert.Contains(rendering.Coordinates(), point => DistanceFromSquare(point.X, point.Y) == effect.KernelRadius && rendering[point.X, point.Y].Alpha > 0);
|
||||
Assert.All(rendering.Coordinates(), point =>
|
||||
{
|
||||
var pixel = rendering[point.X, point.Y];
|
||||
Assert.InRange(pixel.Blue, 0, pixel.Alpha);
|
||||
Assert.InRange(pixel.Green, 0, pixel.Alpha);
|
||||
Assert.InRange(pixel.Red, 0, pixel.Alpha);
|
||||
if (DistanceFromSquare(point.X, point.Y) > effect.KernelRadius)
|
||||
Assert.Equal(Bgra.Transparent, pixel);
|
||||
});
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void TheBlurIsCenteredOnTheSource()
|
||||
{
|
||||
using var devices = new GraphicsDevices();
|
||||
using var context = devices.CreateContext();
|
||||
RequireInterop(context);
|
||||
using var source = new SourceImage(context, Size, Size, CenteredSquare);
|
||||
using var processor = new WaveOpticsEffect().CreateVideoEffect(context);
|
||||
processor.SetInput(source.Bitmap);
|
||||
|
||||
var rendering = RenderFrame(context, processor, 0);
|
||||
|
||||
Assert.True(HasLightOutside(rendering, source));
|
||||
Assert.All(rendering.Coordinates(), point =>
|
||||
{
|
||||
var pixel = rendering[point.X, point.Y];
|
||||
Assert.True(WithinRounding(pixel, PixelAt(rendering, Size - 1 - point.X, point.Y)), $"({point.X}, {point.Y}) {pixel}");
|
||||
Assert.True(WithinRounding(pixel, PixelAt(rendering, point.X, Size - 1 - point.Y)), $"({point.X}, {point.Y}) {pixel}");
|
||||
});
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[InlineData(100, 50)]
|
||||
[InlineData(-37, 21)]
|
||||
public void TheBlurTravelsWithTheImage(int dx, int dy)
|
||||
{
|
||||
using var devices = new GraphicsDevices();
|
||||
using var context = devices.CreateContext();
|
||||
RequireInterop(context);
|
||||
using var source = new SourceImage(context, Size, Size, CenteredSquare);
|
||||
using var moved = new AffineTransform2D(context.DeviceContext)
|
||||
{
|
||||
InterPolationMode = AffineTransform2DInterpolationMode.NearestNeighbor,
|
||||
BorderMode = BorderMode.Hard,
|
||||
TransformMatrix = Matrix3x2.CreateTranslation(dx, dy),
|
||||
};
|
||||
moved.SetInput(0, source.Bitmap, true);
|
||||
using var movedOutput = moved.Output;
|
||||
using var inPlaceProcessor = new WaveOpticsEffect().CreateVideoEffect(context);
|
||||
inPlaceProcessor.SetInput(source.Bitmap);
|
||||
var inPlace = RenderFrame(context, inPlaceProcessor, 0);
|
||||
using var travelledProcessor = new WaveOpticsEffect().CreateVideoEffect(context);
|
||||
travelledProcessor.SetInput(movedOutput);
|
||||
|
||||
var travelled = RenderFrame(context, travelledProcessor, 0);
|
||||
|
||||
Assert.Equal((inPlace.Left + dx, inPlace.Top + dy, inPlace.Width, inPlace.Height), (travelled.Left, travelled.Top, travelled.Width, travelled.Height));
|
||||
Assert.All(inPlace.Coordinates(), point => Assert.True(inPlace[point.X, point.Y] == travelled[point.X + dx, point.Y + dy], $"({point.X}, {point.Y})"));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void AZeroAmountPassesTheImageThrough()
|
||||
{
|
||||
using var devices = new GraphicsDevices();
|
||||
using var context = devices.CreateContext();
|
||||
using var source = new SourceImage(context, Size, Size, CenteredSquare);
|
||||
var effect = new WaveOpticsEffect();
|
||||
effect.Amount.Values[0].Value = 0d;
|
||||
using var processor = effect.CreateVideoEffect(context);
|
||||
processor.SetInput(source.Bitmap);
|
||||
|
||||
var rendering = RenderFrame(context, processor, 0);
|
||||
|
||||
AssertSameAsSource(rendering, source);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void AZeroAmountAfterABlurredFramePassesTheImageThrough()
|
||||
{
|
||||
using var devices = new GraphicsDevices();
|
||||
using var context = devices.CreateContext();
|
||||
RequireInterop(context);
|
||||
using var source = SourceImage.Solid(context, Size, Size, Gray);
|
||||
var effect = new WaveOpticsEffect();
|
||||
using var processor = effect.CreateVideoEffect(context);
|
||||
processor.SetInput(source.Bitmap);
|
||||
var blurred = RenderFrame(context, processor, 0);
|
||||
effect.Amount.Values[0].Value = 0d;
|
||||
|
||||
var passed = RenderFrame(context, processor, 0);
|
||||
|
||||
Assert.True(HasLightOutside(blurred, source));
|
||||
AssertSameAsSource(passed, source);
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[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();
|
||||
using var context = devices.CreateContext();
|
||||
if (blurred)
|
||||
RequireInterop(context);
|
||||
using var source = SourceImage.Solid(context, width, 8, Gray);
|
||||
using var processor = new WaveOpticsEffect().CreateVideoEffect(context);
|
||||
processor.SetInput(source.Bitmap);
|
||||
|
||||
var rendering = RenderFrame(context, processor, 0);
|
||||
|
||||
if (blurred)
|
||||
Assert.True(HasLightOutside(rendering, source));
|
||||
else
|
||||
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)) },
|
||||
{ nameof(WaveOpticsEffect.Gain), effect => effect.Gain.CopyFrom(Linear(50d, 150d)) },
|
||||
{ nameof(WaveOpticsEffect.Defocus), effect => effect.Defocus.CopyFrom(Linear(0d, 2d)) },
|
||||
{ nameof(WaveOpticsEffect.HighlightBoost), effect => { effect.Linear = true; effect.Gain.Values[0].Value = 5d; effect.HighlightThreshold.Values[0].Value = 50d; effect.HighlightBoost.CopyFrom(Linear(1d, 20d)); } },
|
||||
{ nameof(WaveOpticsEffect.HighlightThreshold), effect => { effect.Linear = true; effect.Gain.Values[0].Value = 5d; effect.HighlightBoost.Values[0].Value = 20d; effect.HighlightThreshold.CopyFrom(Linear(30d, 95d)); } },
|
||||
};
|
||||
|
||||
[Theory]
|
||||
[MemberData(nameof(Animations))]
|
||||
public void ReturningToAFrameReproducesItExactly(string setting, Action<WaveOpticsEffect> animate)
|
||||
{
|
||||
using var devices = new GraphicsDevices();
|
||||
using var context = devices.CreateContext();
|
||||
RequireInterop(context);
|
||||
using var source = new SourceImage(context, Size, Size, CenteredSquare);
|
||||
var effect = new WaveOpticsEffect();
|
||||
animate(effect);
|
||||
using var processor = effect.CreateVideoEffect(context);
|
||||
processor.SetInput(source.Bitmap);
|
||||
|
||||
var first = RenderFrame(context, processor, 4);
|
||||
var other = RenderFrame(context, processor, 24);
|
||||
var again = RenderFrame(context, processor, 4);
|
||||
|
||||
Assert.False(first.SamePixelsAs(other), setting);
|
||||
Assert.True(first.SamePixelsAs(again), setting);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void ANewProcessorDrawsTheSameBlur()
|
||||
{
|
||||
using var devices = new GraphicsDevices();
|
||||
using var context = devices.CreateContext();
|
||||
RequireInterop(context);
|
||||
using var source = new SourceImage(context, Size, Size, CenteredSquare);
|
||||
var effect = new WaveOpticsEffect { ApertureShape = WaveOpticsApertureShape.RegularPolygon };
|
||||
effect.Defocus.Values[0].Value = 0.5d;
|
||||
using var firstProcessor = effect.CreateVideoEffect(context);
|
||||
firstProcessor.SetInput(source.Bitmap);
|
||||
var first = RenderFrame(context, firstProcessor, 0);
|
||||
using var secondProcessor = effect.CreateVideoEffect(context);
|
||||
secondProcessor.SetInput(source.Bitmap);
|
||||
|
||||
var second = RenderFrame(context, secondProcessor, 0);
|
||||
|
||||
Assert.True(first.SamePixelsAs(second));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void AnimatedAmountIsReadAtEachFrame()
|
||||
{
|
||||
using var devices = new GraphicsDevices();
|
||||
using var context = devices.CreateContext();
|
||||
RequireInterop(context);
|
||||
using var source = new SourceImage(context, Size, Size, CenteredSquare);
|
||||
var effect = new WaveOpticsEffect();
|
||||
effect.Amount.CopyFrom(Linear(0d, 100d));
|
||||
using var processor = effect.CreateVideoEffect(context);
|
||||
processor.SetInput(source.Bitmap);
|
||||
|
||||
var start = RenderFrame(context, processor, 0);
|
||||
var end = RenderFrame(context, processor, Length - 1);
|
||||
|
||||
AssertSameAsSource(start, source);
|
||||
Assert.True(HasLightOutside(end, source));
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[InlineData(15, 3)]
|
||||
[InlineData(3, 15)]
|
||||
public void AProcessorThatDrewAnotherRadiusDrawsLikeAFreshOne(int firstRadius, int secondRadius)
|
||||
{
|
||||
using var devices = new GraphicsDevices();
|
||||
using var context = devices.CreateContext();
|
||||
RequireInterop(context);
|
||||
using var source = new SourceImage(context, Size, Size, CenteredSquare);
|
||||
var effect = new WaveOpticsEffect { KernelRadius = firstRadius };
|
||||
effect.FNumber.Values[0].Value = 32d;
|
||||
using var processor = effect.CreateVideoEffect(context);
|
||||
processor.SetInput(source.Bitmap);
|
||||
RenderFrame(context, processor, 0);
|
||||
effect.KernelRadius = secondRadius;
|
||||
using var fresh = effect.CreateVideoEffect(context);
|
||||
fresh.SetInput(source.Bitmap);
|
||||
var expected = RenderFrame(context, fresh, 0);
|
||||
|
||||
var reused = RenderFrame(context, processor, 0);
|
||||
|
||||
Assert.True(reused.SamePixelsAs(expected));
|
||||
}
|
||||
|
||||
public static readonly TheoryData<string, Action<WaveOpticsEffect>> LaterChanges = new()
|
||||
{
|
||||
{ nameof(WaveOpticsEffect.Amount), effect => effect.Amount.Values[0].Value = 50d },
|
||||
{ nameof(WaveOpticsEffect.Gain), effect => effect.Gain.Values[0].Value = 50d },
|
||||
{ nameof(WaveOpticsEffect.Wavelength), effect => effect.Wavelength.Values[0].Value = 700d },
|
||||
{ nameof(WaveOpticsEffect.FNumber), effect => effect.FNumber.Values[0].Value = 16d },
|
||||
{ nameof(WaveOpticsEffect.PixelPitch), effect => effect.PixelPitch.Values[0].Value = 2d },
|
||||
{ nameof(WaveOpticsEffect.KernelRadius), effect => effect.KernelRadius = 2 },
|
||||
{ nameof(WaveOpticsEffect.Quality), effect => effect.Quality = WaveOpticsQuality.Draft },
|
||||
{ nameof(WaveOpticsEffect.ApertureShape), effect => effect.ApertureShape = WaveOpticsApertureShape.Circular },
|
||||
{ nameof(WaveOpticsEffect.BladeCount), effect => effect.BladeCount = 3 },
|
||||
{ nameof(WaveOpticsEffect.BladeRotation), effect => effect.BladeRotation.Values[0].Value = 30d },
|
||||
{ nameof(WaveOpticsEffect.Obstruction), effect => effect.Obstruction.Values[0].Value = 50d },
|
||||
{ nameof(WaveOpticsEffect.Defocus), effect => effect.Defocus.Values[0].Value = 1d },
|
||||
{ nameof(WaveOpticsEffect.AstigmatismVertical), effect => effect.AstigmatismVertical.Values[0].Value = 1d },
|
||||
{ nameof(WaveOpticsEffect.AstigmatismOblique), effect => effect.AstigmatismOblique.Values[0].Value = 1d },
|
||||
{ nameof(WaveOpticsEffect.ComaHorizontal), effect => effect.ComaHorizontal.Values[0].Value = 1d },
|
||||
{ nameof(WaveOpticsEffect.ComaVertical), effect => effect.ComaVertical.Values[0].Value = 1d },
|
||||
{ nameof(WaveOpticsEffect.Spherical), effect => effect.Spherical.Values[0].Value = 1d },
|
||||
{ nameof(WaveOpticsEffect.Linear), effect => effect.Linear = true },
|
||||
{ nameof(WaveOpticsEffect.Dither), effect => { effect.Dither = true; effect.Gain.Values[0].Value = 50d; } },
|
||||
};
|
||||
|
||||
public static readonly TheoryData<string, Action<WaveOpticsEffect>> LaterLightChanges = new()
|
||||
{
|
||||
{ nameof(WaveOpticsEffect.Linear), effect => effect.Linear = false },
|
||||
{ nameof(WaveOpticsEffect.Dither), effect => effect.Dither = true },
|
||||
{ nameof(WaveOpticsEffect.HighlightThreshold), effect => effect.HighlightThreshold.Values[0].Value = 90d },
|
||||
{ nameof(WaveOpticsEffect.HighlightBoost), effect => effect.HighlightBoost.Values[0].Value = 500d },
|
||||
};
|
||||
|
||||
static Bgra TwoTone(int x, int y)
|
||||
=> x is >= Start and < End && y is >= Start and < End ? (x < Size / 2 ? Bgra.Opaque(190, 190, 190) : Bgra.Opaque(40, 40, 40)) : Bgra.Transparent;
|
||||
|
||||
[Theory]
|
||||
[MemberData(nameof(LaterLightChanges))]
|
||||
public void EveryLightSettingChangedAfterTheFirstFrameReachesTheEffect(string setting, Action<WaveOpticsEffect> change)
|
||||
{
|
||||
using var devices = new GraphicsDevices();
|
||||
using var context = devices.CreateContext();
|
||||
RequireInterop(context);
|
||||
using var source = new SourceImage(context, Size, Size, TwoTone);
|
||||
var effect = new WaveOpticsEffect { ApertureShape = WaveOpticsApertureShape.RegularPolygon, Linear = true };
|
||||
effect.Gain.Values[0].Value = 3d;
|
||||
effect.HighlightThreshold.Values[0].Value = 50d;
|
||||
effect.HighlightBoost.Values[0].Value = 100d;
|
||||
using var processor = effect.CreateVideoEffect(context);
|
||||
processor.SetInput(source.Bitmap);
|
||||
|
||||
var before = RenderFrame(context, processor, 0);
|
||||
change(effect);
|
||||
var after = RenderFrame(context, processor, 0);
|
||||
|
||||
Assert.False(before.SamePixelsAs(after), setting);
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[InlineData(false)]
|
||||
[InlineData(true)]
|
||||
public void AProcessorThatOnlyToggledTheDitherDrawsLikeAFreshOne(bool linear)
|
||||
{
|
||||
using var devices = new GraphicsDevices();
|
||||
using var context = devices.CreateContext();
|
||||
RequireInterop(context);
|
||||
using var source = new SourceImage(context, Size, Size, CenteredSquare);
|
||||
var effect = new WaveOpticsEffect { Linear = linear };
|
||||
effect.Gain.Values[0].Value = 60d;
|
||||
using var processor = effect.CreateVideoEffect(context);
|
||||
processor.SetInput(source.Bitmap);
|
||||
|
||||
foreach (var dither in new[] { false, true, false, true })
|
||||
{
|
||||
effect.Dither = dither;
|
||||
using var fresh = effect.CreateVideoEffect(context);
|
||||
fresh.SetInput(source.Bitmap);
|
||||
var expected = RenderFrame(context, fresh, 0);
|
||||
|
||||
var reused = RenderFrame(context, processor, 0);
|
||||
|
||||
Assert.True(reused.SamePixelsAs(expected), $"dither {dither}");
|
||||
}
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[MemberData(nameof(LaterChanges))]
|
||||
public void EverySettingChangedAfterTheFirstFrameReachesTheEffect(string setting, Action<WaveOpticsEffect> change)
|
||||
{
|
||||
using var devices = new GraphicsDevices();
|
||||
using var context = devices.CreateContext();
|
||||
RequireInterop(context);
|
||||
using var source = new SourceImage(context, Size, Size, CenteredSquare);
|
||||
var effect = new WaveOpticsEffect { ApertureShape = WaveOpticsApertureShape.RegularPolygon };
|
||||
using var processor = effect.CreateVideoEffect(context);
|
||||
processor.SetInput(source.Bitmap);
|
||||
|
||||
var before = RenderFrame(context, processor, 0);
|
||||
change(effect);
|
||||
var after = RenderFrame(context, processor, 0);
|
||||
|
||||
Assert.False(before.SamePixelsAs(after), setting);
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[InlineData(32, 128)]
|
||||
[InlineData(128, 32)]
|
||||
public void AResizedSourceKeepsBeingBlurred(int firstSize, int secondSize)
|
||||
{
|
||||
using var devices = new GraphicsDevices();
|
||||
using var context = devices.CreateContext();
|
||||
RequireInterop(context);
|
||||
using var first = SourceImage.Solid(context, firstSize, firstSize, Gray);
|
||||
using var second = SourceImage.Solid(context, secondSize, secondSize, Gray);
|
||||
using var processor = new WaveOpticsEffect().CreateVideoEffect(context);
|
||||
processor.SetInput(first.Bitmap);
|
||||
var before = RenderFrame(context, processor, 0);
|
||||
|
||||
processor.SetInput(second.Bitmap);
|
||||
var after = RenderFrame(context, processor, 0);
|
||||
|
||||
Assert.True(HasLightOutside(before, first));
|
||||
Assert.True(HasLightOutside(after, second));
|
||||
Assert.Equal(secondSize > firstSize, after.Width > before.Width);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void TheBlurAppearsOnceATransparentSourceTakesShape()
|
||||
{
|
||||
using var devices = new GraphicsDevices();
|
||||
using var context = devices.CreateContext();
|
||||
RequireInterop(context);
|
||||
using var empty = SourceImage.Solid(context, Size, Size, Bgra.Transparent);
|
||||
using var source = new SourceImage(context, Size, Size, CenteredSquare);
|
||||
using var processor = new WaveOpticsEffect().CreateVideoEffect(context);
|
||||
processor.SetInput(empty.Bitmap);
|
||||
var before = RenderFrame(context, processor, 0);
|
||||
|
||||
processor.SetInput(source.Bitmap);
|
||||
var after = RenderFrame(context, processor, 0);
|
||||
|
||||
AssertSameAsSource(before, empty);
|
||||
Assert.True(HasLightOutside(after, source));
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[InlineData(Size, Size, false)]
|
||||
[InlineData(WaveOpticsSettings.MaximumCanvasSize - WaveOpticsSettings.DefaultCanvasMargin * 2 + 1, 8, true)]
|
||||
public void TheBlurReturnsAfterAnImageThatPassedThrough(int width, int height, bool opaque)
|
||||
{
|
||||
using var devices = new GraphicsDevices();
|
||||
using var context = devices.CreateContext();
|
||||
RequireInterop(context);
|
||||
using var source = new SourceImage(context, Size, Size, CenteredSquare);
|
||||
using var passing = SourceImage.Solid(context, width, height, opaque ? Gray : Bgra.Transparent);
|
||||
using var processor = new WaveOpticsEffect().CreateVideoEffect(context);
|
||||
processor.SetInput(source.Bitmap);
|
||||
var before = RenderFrame(context, processor, 0);
|
||||
processor.SetInput(passing.Bitmap);
|
||||
var between = RenderFrame(context, processor, 0);
|
||||
|
||||
processor.SetInput(source.Bitmap);
|
||||
var after = RenderFrame(context, processor, 0);
|
||||
|
||||
Assert.True(HasLightOutside(before, source));
|
||||
AssertSameAsSource(between, passing);
|
||||
Assert.True(after.SamePixelsAs(before));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void AnApertureWithoutAnOpenSamplePassesTheImageThroughUntilItOpens()
|
||||
{
|
||||
using var devices = new GraphicsDevices();
|
||||
using var context = devices.CreateContext();
|
||||
RequireInterop(context);
|
||||
using var source = new SourceImage(context, Size, Size, CenteredSquare);
|
||||
var effect = new WaveOpticsEffect { Quality = WaveOpticsQuality.Draft, ApertureShape = WaveOpticsApertureShape.RegularPolygon, BladeCount = 4 };
|
||||
effect.BladeRotation.Values[0].Value = -357.5d;
|
||||
using var processor = effect.CreateVideoEffect(context);
|
||||
processor.SetInput(source.Bitmap);
|
||||
var open = RenderFrame(context, processor, 0);
|
||||
effect.Obstruction.Values[0].Value = 95d;
|
||||
var blocked = RenderFrame(context, processor, 0);
|
||||
effect.Obstruction.Values[0].Value = 0d;
|
||||
|
||||
var reopened = RenderFrame(context, processor, 0);
|
||||
|
||||
Assert.True(HasLightOutside(open, source));
|
||||
AssertSameAsSource(blocked, source);
|
||||
Assert.True(reopened.SamePixelsAs(open));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void AFailureWhileUpdatingIsNotSwallowed()
|
||||
{
|
||||
using var devices = new GraphicsDevices();
|
||||
using var context = devices.CreateContext();
|
||||
using var processor = new WaveOpticsEffect().CreateVideoEffect(context);
|
||||
|
||||
Assert.ThrowsAny<Exception>(() => processor.Update(null!));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,343 @@
|
||||
using System.ComponentModel;
|
||||
using System.ComponentModel.DataAnnotations;
|
||||
using System.Reflection;
|
||||
using WaveOptics.Effects;
|
||||
using YukkuriMovieMaker.Commons;
|
||||
using YukkuriMovieMaker.Controls;
|
||||
using YukkuriMovieMaker.Exo;
|
||||
using YukkuriMovieMaker.Json;
|
||||
using YukkuriMovieMaker.Plugin.Effects;
|
||||
using YukkuriMovieMaker.Project;
|
||||
|
||||
namespace WaveOptics.Tests;
|
||||
|
||||
public sealed class WaveOpticsEffectTests
|
||||
{
|
||||
static PropertyInfo Property(string name) => typeof(WaveOpticsEffect).GetProperty(name)!;
|
||||
|
||||
static T Attribute<T>(string property) where T : Attribute => Property(property).GetCustomAttribute<T>()!;
|
||||
|
||||
static Animation[] Animations(WaveOpticsEffect effect)
|
||||
=> [effect.Amount, effect.Gain, effect.Wavelength, effect.FNumber, effect.PixelPitch, effect.BladeRotation, effect.Obstruction, effect.Defocus, effect.AstigmatismVertical, effect.AstigmatismOblique, effect.ComaHorizontal, effect.ComaVertical, effect.Spherical, effect.HighlightThreshold, effect.HighlightBoost];
|
||||
|
||||
[Theory]
|
||||
[InlineData(nameof(WaveOpticsEffect.Amount), 100d, 0d, 100d)]
|
||||
[InlineData(nameof(WaveOpticsEffect.Gain), 100d, 0d, 400d)]
|
||||
[InlineData(nameof(WaveOpticsEffect.Wavelength), 550d, 380d, 780d)]
|
||||
[InlineData(nameof(WaveOpticsEffect.FNumber), 8d, 0.5d, 64d)]
|
||||
[InlineData(nameof(WaveOpticsEffect.PixelPitch), 4d, 0.25d, 100d)]
|
||||
[InlineData(nameof(WaveOpticsEffect.BladeRotation), 0d, -360d, 360d)]
|
||||
[InlineData(nameof(WaveOpticsEffect.Obstruction), 0d, 0d, 95d)]
|
||||
[InlineData(nameof(WaveOpticsEffect.Defocus), 0d, -10d, 10d)]
|
||||
[InlineData(nameof(WaveOpticsEffect.AstigmatismVertical), 0d, -10d, 10d)]
|
||||
[InlineData(nameof(WaveOpticsEffect.AstigmatismOblique), 0d, -10d, 10d)]
|
||||
[InlineData(nameof(WaveOpticsEffect.ComaHorizontal), 0d, -10d, 10d)]
|
||||
[InlineData(nameof(WaveOpticsEffect.ComaVertical), 0d, -10d, 10d)]
|
||||
[InlineData(nameof(WaveOpticsEffect.Spherical), 0d, -10d, 10d)]
|
||||
[InlineData(nameof(WaveOpticsEffect.HighlightThreshold), 95d, 0d, 100d)]
|
||||
[InlineData(nameof(WaveOpticsEffect.HighlightBoost), 1d, 1d, 1000d)]
|
||||
public void AnimatedParametersStartFromTheirDefaultsWithinTheirRange(string name, double defaultValue, double minimum, double maximum)
|
||||
{
|
||||
var effect = new WaveOpticsEffect();
|
||||
|
||||
var animation = (Animation)Property(name).GetValue(effect)!;
|
||||
|
||||
Assert.Equal(defaultValue, animation.DefaultValue);
|
||||
Assert.Equal(minimum, animation.MinValue);
|
||||
Assert.Equal(maximum, animation.MaxValue);
|
||||
Assert.Equal(defaultValue, animation.GetValue(0, 1, EffectDescriptions.Fps));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void LinearLightAndDitherAreOffByDefault()
|
||||
{
|
||||
var effect = new WaveOpticsEffect();
|
||||
|
||||
Assert.False(effect.Linear);
|
||||
Assert.False(effect.Dither);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void KernelRadiusQualityApertureAndBladesStartFromTheirDefaults()
|
||||
{
|
||||
var effect = new WaveOpticsEffect();
|
||||
|
||||
Assert.Equal(15, effect.KernelRadius);
|
||||
Assert.Equal(WaveOpticsQuality.Standard, effect.Quality);
|
||||
Assert.Equal(WaveOpticsApertureShape.Circular, effect.ApertureShape);
|
||||
Assert.Equal(6, effect.BladeCount);
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[InlineData(int.MinValue, 1)]
|
||||
[InlineData(0, 1)]
|
||||
[InlineData(1, 1)]
|
||||
[InlineData(7, 7)]
|
||||
[InlineData(15, 15)]
|
||||
[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 };
|
||||
|
||||
effect.KernelRadius = value;
|
||||
|
||||
Assert.Equal(expected, effect.KernelRadius);
|
||||
Assert.False(effect.HasErrors);
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[InlineData(int.MinValue, 3)]
|
||||
[InlineData(2, 3)]
|
||||
[InlineData(3, 3)]
|
||||
[InlineData(12, 12)]
|
||||
[InlineData(32, 32)]
|
||||
[InlineData(33, 32)]
|
||||
[InlineData(int.MaxValue, 32)]
|
||||
public void BladeCountStaysBetweenThreeAndThirtyTwo(int value, int expected)
|
||||
{
|
||||
var effect = new WaveOpticsEffect { BladeCount = 5 };
|
||||
|
||||
effect.BladeCount = value;
|
||||
|
||||
Assert.Equal(expected, effect.BladeCount);
|
||||
Assert.False(effect.HasErrors);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void ChangingTheSettingsThatDoNotAnimateNotifiesTheEditor()
|
||||
{
|
||||
var effect = new WaveOpticsEffect();
|
||||
var changed = new List<string?>();
|
||||
effect.PropertyChanged += (_, e) => changed.Add(e.PropertyName);
|
||||
|
||||
effect.KernelRadius = 7;
|
||||
effect.Quality = WaveOpticsQuality.High;
|
||||
effect.ApertureShape = WaveOpticsApertureShape.RegularPolygon;
|
||||
effect.BladeCount = 9;
|
||||
effect.Linear = true;
|
||||
effect.Dither = true;
|
||||
|
||||
Assert.Equal([nameof(WaveOpticsEffect.KernelRadius), nameof(WaveOpticsEffect.Quality), nameof(WaveOpticsEffect.ApertureShape), nameof(WaveOpticsEffect.BladeCount), nameof(WaveOpticsEffect.Linear), nameof(WaveOpticsEffect.Dither)], changed);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void AssigningAnUnchangedOrClampedValueDoesNotNotify()
|
||||
{
|
||||
var effect = new WaveOpticsEffect { KernelRadius = WaveOpticsSettings.MaximumKernelRadius, Linear = true, Dither = true };
|
||||
var changed = new List<string?>();
|
||||
effect.PropertyChanged += (_, e) => changed.Add(e.PropertyName);
|
||||
|
||||
effect.KernelRadius = WaveOpticsSettings.MaximumKernelRadius;
|
||||
effect.KernelRadius = WaveOpticsSettings.MaximumKernelRadius + 1;
|
||||
effect.Quality = WaveOpticsQuality.Standard;
|
||||
effect.ApertureShape = WaveOpticsApertureShape.Circular;
|
||||
effect.BladeCount = 6;
|
||||
effect.Linear = true;
|
||||
effect.Dither = true;
|
||||
|
||||
Assert.Empty(changed);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void TheLabelIsTheLocalizedEffectName()
|
||||
{
|
||||
var effect = new WaveOpticsEffect();
|
||||
|
||||
Assert.Equal(Texts.WaveOptics, effect.Label);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void TheFifteenNumericParametersReceiveTheAnimationParameters()
|
||||
{
|
||||
var effect = new WaveOpticsEffect();
|
||||
|
||||
effect.SetAnimationParameters(120, EffectDescriptions.Fps);
|
||||
|
||||
Assert.All(Animations(effect), animation => Assert.Equal(120, animation.Length));
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[InlineData(0)]
|
||||
[InlineData(1)]
|
||||
[InlineData(int.MaxValue)]
|
||||
public void NoExoFilterIsWrittenForAviUtl(int keyFrameIndex)
|
||||
{
|
||||
var effect = new WaveOpticsEffect();
|
||||
|
||||
var description = new ExoOutputDescription(new VideoInfo(), string.Empty, new AviUtlDirectories(string.Empty, string.Empty));
|
||||
|
||||
Assert.Empty(effect.CreateExoVideoFilters(keyFrameIndex, description));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void TheEffectIsRegisteredForFilteringWithoutAviUtlSupport()
|
||||
{
|
||||
var attribute = typeof(WaveOpticsEffect).GetCustomAttribute<VideoEffectAttribute>()!;
|
||||
|
||||
Assert.Equal(nameof(Texts.WaveOptics), attribute.Name);
|
||||
Assert.Equal([VideoEffectCategories.Filtering], attribute.Categories);
|
||||
Assert.Equal([nameof(Texts.TagDiffraction), nameof(Texts.TagLens), nameof(Texts.TagPsf), nameof(Texts.TagOptics)], attribute.Keywords);
|
||||
Assert.False(attribute.IsAviUtlSupported);
|
||||
Assert.True(attribute.IsEffectItemSupported);
|
||||
Assert.Equal(typeof(Texts), attribute.ResourceType);
|
||||
Assert.Equal(Texts.WaveOptics, attribute.GetName());
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[InlineData(nameof(WaveOpticsEffect.Amount), nameof(Texts.OutputGroup), nameof(Texts.Amount), nameof(Texts.AmountDescription), 0)]
|
||||
[InlineData(nameof(WaveOpticsEffect.Gain), nameof(Texts.OutputGroup), nameof(Texts.Gain), nameof(Texts.GainDescription), 1)]
|
||||
[InlineData(nameof(WaveOpticsEffect.Linear), nameof(Texts.OutputGroup), nameof(Texts.Linear), nameof(Texts.LinearDescription), 2)]
|
||||
[InlineData(nameof(WaveOpticsEffect.HighlightThreshold), nameof(Texts.OutputGroup), nameof(Texts.HighlightThreshold), nameof(Texts.HighlightThresholdDescription), 3)]
|
||||
[InlineData(nameof(WaveOpticsEffect.HighlightBoost), nameof(Texts.OutputGroup), nameof(Texts.HighlightBoost), nameof(Texts.HighlightBoostDescription), 4)]
|
||||
[InlineData(nameof(WaveOpticsEffect.Dither), nameof(Texts.OutputGroup), nameof(Texts.Dither), nameof(Texts.DitherDescription), 5)]
|
||||
[InlineData(nameof(WaveOpticsEffect.Wavelength), nameof(Texts.OpticsGroup), nameof(Texts.Wavelength), nameof(Texts.WavelengthDescription), 10)]
|
||||
[InlineData(nameof(WaveOpticsEffect.FNumber), nameof(Texts.OpticsGroup), nameof(Texts.FNumber), nameof(Texts.FNumberDescription), 11)]
|
||||
[InlineData(nameof(WaveOpticsEffect.PixelPitch), nameof(Texts.OpticsGroup), nameof(Texts.PixelPitch), nameof(Texts.PixelPitchDescription), 12)]
|
||||
[InlineData(nameof(WaveOpticsEffect.KernelRadius), nameof(Texts.OpticsGroup), nameof(Texts.KernelRadius), nameof(Texts.KernelRadiusDescription), 13)]
|
||||
[InlineData(nameof(WaveOpticsEffect.Quality), nameof(Texts.OpticsGroup), nameof(Texts.Quality), nameof(Texts.QualityDescription), 14)]
|
||||
[InlineData(nameof(WaveOpticsEffect.ApertureShape), nameof(Texts.ApertureGroup), nameof(Texts.ApertureShape), nameof(Texts.ApertureShapeDescription), 20)]
|
||||
[InlineData(nameof(WaveOpticsEffect.BladeCount), nameof(Texts.ApertureGroup), nameof(Texts.BladeCount), nameof(Texts.BladeCountDescription), 21)]
|
||||
[InlineData(nameof(WaveOpticsEffect.BladeRotation), nameof(Texts.ApertureGroup), nameof(Texts.BladeRotation), nameof(Texts.BladeRotationDescription), 22)]
|
||||
[InlineData(nameof(WaveOpticsEffect.Obstruction), nameof(Texts.ApertureGroup), nameof(Texts.Obstruction), nameof(Texts.ObstructionDescription), 23)]
|
||||
[InlineData(nameof(WaveOpticsEffect.Defocus), nameof(Texts.AberrationGroup), nameof(Texts.Defocus), nameof(Texts.DefocusDescription), 30)]
|
||||
[InlineData(nameof(WaveOpticsEffect.AstigmatismVertical), nameof(Texts.AberrationGroup), nameof(Texts.AstigmatismVertical), nameof(Texts.AstigmatismVerticalDescription), 31)]
|
||||
[InlineData(nameof(WaveOpticsEffect.AstigmatismOblique), nameof(Texts.AberrationGroup), nameof(Texts.AstigmatismOblique), nameof(Texts.AstigmatismObliqueDescription), 32)]
|
||||
[InlineData(nameof(WaveOpticsEffect.ComaHorizontal), nameof(Texts.AberrationGroup), nameof(Texts.ComaHorizontal), nameof(Texts.ComaHorizontalDescription), 33)]
|
||||
[InlineData(nameof(WaveOpticsEffect.ComaVertical), nameof(Texts.AberrationGroup), nameof(Texts.ComaVertical), nameof(Texts.ComaVerticalDescription), 34)]
|
||||
[InlineData(nameof(WaveOpticsEffect.Spherical), nameof(Texts.AberrationGroup), nameof(Texts.Spherical), nameof(Texts.SphericalDescription), 35)]
|
||||
public void EveryParameterIsDisplayedInItsGroupInOrder(string property, string group, string name, string description, int order)
|
||||
{
|
||||
var display = Attribute<DisplayAttribute>(property);
|
||||
|
||||
Assert.Equal(group, display.GroupName);
|
||||
Assert.Equal(name, display.Name);
|
||||
Assert.Equal(description, display.Description);
|
||||
Assert.Equal(order, display.Order);
|
||||
Assert.Equal(typeof(Texts), display.ResourceType);
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[InlineData(nameof(WaveOpticsEffect.Amount), "F1", "%", 0d, 100d)]
|
||||
[InlineData(nameof(WaveOpticsEffect.Gain), "F1", "%", 0d, 400d)]
|
||||
[InlineData(nameof(WaveOpticsEffect.Wavelength), "F1", "nm", 380d, 780d)]
|
||||
[InlineData(nameof(WaveOpticsEffect.FNumber), "F2", "", 0.5d, 32d)]
|
||||
[InlineData(nameof(WaveOpticsEffect.PixelPitch), "F2", "μm", 0.5d, 20d)]
|
||||
[InlineData(nameof(WaveOpticsEffect.BladeRotation), "F1", "°", -180d, 180d)]
|
||||
[InlineData(nameof(WaveOpticsEffect.Obstruction), "F1", "%", 0d, 95d)]
|
||||
[InlineData(nameof(WaveOpticsEffect.Defocus), "F3", "waves", -3d, 3d)]
|
||||
[InlineData(nameof(WaveOpticsEffect.AstigmatismVertical), "F3", "waves", -3d, 3d)]
|
||||
[InlineData(nameof(WaveOpticsEffect.AstigmatismOblique), "F3", "waves", -3d, 3d)]
|
||||
[InlineData(nameof(WaveOpticsEffect.ComaHorizontal), "F3", "waves", -3d, 3d)]
|
||||
[InlineData(nameof(WaveOpticsEffect.ComaVertical), "F3", "waves", -3d, 3d)]
|
||||
[InlineData(nameof(WaveOpticsEffect.Spherical), "F3", "waves", -3d, 3d)]
|
||||
[InlineData(nameof(WaveOpticsEffect.HighlightThreshold), "F1", "%", 0d, 100d)]
|
||||
[InlineData(nameof(WaveOpticsEffect.HighlightBoost), "F1", "x", 1d, 100d)]
|
||||
public void AnimatedParametersAreEditedWithAnimationSliders(string property, string format, string unit, double minimum, double maximum)
|
||||
{
|
||||
var slider = Attribute<AnimationSliderAttribute>(property);
|
||||
|
||||
Assert.Equal(format, slider.StringFormat);
|
||||
Assert.Equal(unit, slider.UnitText);
|
||||
Assert.Equal(minimum, slider.DefaultMin);
|
||||
Assert.Equal(maximum, slider.DefaultMax);
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[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)
|
||||
{
|
||||
var slider = Attribute<TextBoxSliderAttribute>(property);
|
||||
var range = Attribute<RangeAttribute>(property);
|
||||
|
||||
Assert.Equal("F0", slider.StringFormat);
|
||||
Assert.Equal(unit, slider.UnitText);
|
||||
Assert.Equal(sliderMinimum, slider.DefaultMin);
|
||||
Assert.Equal(sliderMaximum, slider.DefaultMax);
|
||||
Assert.Equal(minimum, range.Minimum);
|
||||
Assert.Equal(maximum, range.Maximum);
|
||||
Assert.Equal(defaultValue, Attribute<DefaultValueAttribute>(property).Value);
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[InlineData(nameof(WaveOpticsEffect.Linear))]
|
||||
[InlineData(nameof(WaveOpticsEffect.Dither))]
|
||||
public void TheLightSwitchesAreEditedWithToggleSliders(string property)
|
||||
{
|
||||
Assert.NotNull(Property(property).GetCustomAttribute<ToggleSliderAttribute>());
|
||||
Assert.Equal(typeof(bool), Property(property).PropertyType);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void TheQualityAndTheApertureShapeAreChosenFromCombos()
|
||||
{
|
||||
Assert.NotNull(Attribute<EnumComboBoxAttribute>(nameof(WaveOpticsEffect.Quality)));
|
||||
Assert.NotNull(Attribute<EnumComboBoxAttribute>(nameof(WaveOpticsEffect.ApertureShape)));
|
||||
Assert.Equal([WaveOpticsQuality.Draft, WaveOpticsQuality.Standard, WaveOpticsQuality.High], Enum.GetValues<WaveOpticsQuality>());
|
||||
Assert.Equal([WaveOpticsApertureShape.Circular, WaveOpticsApertureShape.RegularPolygon], Enum.GetValues<WaveOpticsApertureShape>());
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[InlineData(typeof(WaveOpticsQuality), nameof(WaveOpticsQuality.Draft), nameof(Texts.QualityDraft))]
|
||||
[InlineData(typeof(WaveOpticsQuality), nameof(WaveOpticsQuality.Standard), nameof(Texts.QualityStandard))]
|
||||
[InlineData(typeof(WaveOpticsQuality), nameof(WaveOpticsQuality.High), nameof(Texts.QualityHigh))]
|
||||
[InlineData(typeof(WaveOpticsApertureShape), nameof(WaveOpticsApertureShape.Circular), nameof(Texts.CircularAperture))]
|
||||
[InlineData(typeof(WaveOpticsApertureShape), nameof(WaveOpticsApertureShape.RegularPolygon), nameof(Texts.RegularPolygonAperture))]
|
||||
public void EveryChoiceIsDisplayedWithItsLocalizedName(Type type, string value, string name)
|
||||
{
|
||||
var display = type.GetField(value)!.GetCustomAttribute<DisplayAttribute>()!;
|
||||
|
||||
Assert.Equal(name, display.Name);
|
||||
Assert.Equal(typeof(Texts), display.ResourceType);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void EverySettingSurvivesAProjectRoundTrip()
|
||||
{
|
||||
var effect = new WaveOpticsEffect { KernelRadius = 7, Quality = WaveOpticsQuality.High, ApertureShape = WaveOpticsApertureShape.RegularPolygon, BladeCount = 9, Linear = true, Dither = true };
|
||||
var values = new[] { 55d, 150d, 620d, 5.6d, 2.5d, 30d, 40d, 1.5d, -0.5d, 0.25d, -1d, 0.75d, 2d, 80d, 12d };
|
||||
foreach (var (animation, value) in Animations(effect).Zip(values))
|
||||
animation.Values[0].Value = value;
|
||||
|
||||
var clone = Json.GetClone(effect)!;
|
||||
|
||||
Assert.NotSame(effect, clone);
|
||||
Assert.Equal(7, clone.KernelRadius);
|
||||
Assert.Equal(WaveOpticsQuality.High, clone.Quality);
|
||||
Assert.Equal(WaveOpticsApertureShape.RegularPolygon, clone.ApertureShape);
|
||||
Assert.Equal(9, clone.BladeCount);
|
||||
Assert.True(clone.Linear);
|
||||
Assert.True(clone.Dither);
|
||||
Assert.Equal(values, Animations(clone).Select(animation => animation.GetValue(0, 1, EffectDescriptions.Fps)));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void ProjectsSavedWithTheSettingNamesStillLoad()
|
||||
{
|
||||
const string saved = """{"KernelRadius":7,"Quality":"High","ApertureShape":"RegularPolygon","BladeCount":9,"Defocus":{"Values":[{"Value":1.5}]}}""";
|
||||
|
||||
var effect = Json.LoadFromText<WaveOpticsEffect>(saved)!;
|
||||
|
||||
Assert.Equal(7, effect.KernelRadius);
|
||||
Assert.Equal(WaveOpticsQuality.High, effect.Quality);
|
||||
Assert.Equal(WaveOpticsApertureShape.RegularPolygon, effect.ApertureShape);
|
||||
Assert.Equal(9, effect.BladeCount);
|
||||
Assert.Equal(1.5d, effect.Defocus.GetValue(0, 1, EffectDescriptions.Fps));
|
||||
Assert.False(effect.Linear);
|
||||
Assert.False(effect.Dither);
|
||||
Assert.Equal(95d, effect.HighlightThreshold.GetValue(0, 1, EffectDescriptions.Fps));
|
||||
Assert.Equal(1d, effect.HighlightBoost.GetValue(0, 1, EffectDescriptions.Fps));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void TheEffectKeepsTheTypeNameThatProjectsStore()
|
||||
{
|
||||
var type = typeof(WaveOpticsEffect);
|
||||
|
||||
Assert.Equal("WaveOptics.Effects.WaveOpticsEffect", type.FullName);
|
||||
Assert.Equal("WaveOptics", type.Assembly.GetName().Name);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,168 @@
|
||||
using System.Numerics;
|
||||
using ComputeWeave;
|
||||
using Vortice.Direct2D1;
|
||||
using WaveOptics.Effects;
|
||||
using WaveOptics.Rendering;
|
||||
using YukkuriMovieMaker.Commons;
|
||||
|
||||
namespace WaveOptics.Tests;
|
||||
|
||||
[Collection("Direct2D")]
|
||||
public sealed class WaveOpticsInteropTests
|
||||
{
|
||||
static readonly Bgra Gray = Bgra.Opaque(192, 192, 192);
|
||||
|
||||
static WaveOpticsPipeline.Parameters Parameters()
|
||||
=> new(1f, new WaveOpticsPipeline.PsfParameters(
|
||||
WaveOpticsQuality.Standard, 15, 550f, 8f, 4f, WaveOpticsApertureShape.Circular, 6, 0f, 0f, 1f, 0f, 0f, 0f, 0f, 0f));
|
||||
|
||||
static Func<int, int, Bgra> CenteredSquare(int size, int square)
|
||||
{
|
||||
var start = (size - square) / 2;
|
||||
return (x, y) => x >= start && x < start + square && y >= start && y < start + square ? Gray : Bgra.Transparent;
|
||||
}
|
||||
|
||||
sealed class Interop : IDisposable
|
||||
{
|
||||
readonly ComputeExternalQueueScheduler scheduler;
|
||||
readonly WaveOpticsInteropProvider provider;
|
||||
readonly ComputeInteropDomain domain;
|
||||
|
||||
public WaveOpticsResourceSet Resources { get; }
|
||||
|
||||
public WaveOpticsPipeline Pipeline { get; }
|
||||
|
||||
Interop(ComputeExternalQueueScheduler scheduler, WaveOpticsInteropProvider provider, GraphicsDevice device)
|
||||
{
|
||||
this.scheduler = scheduler;
|
||||
this.provider = provider;
|
||||
domain = device.RegisterExternalDomain(provider);
|
||||
Resources = WaveOpticsResourceSet.Create(device, domain);
|
||||
Pipeline = WaveOpticsPipeline.TryCreate(device)!;
|
||||
}
|
||||
|
||||
public static Interop Create(IGraphicsDevicesAndContext devices)
|
||||
{
|
||||
var scheduler = ComputeExternalQueueScheduler.Create();
|
||||
var provider = WaveOpticsInteropProvider.TryCreate(devices, scheduler, out var device);
|
||||
if (provider is null || device is null)
|
||||
{
|
||||
scheduler.Dispose();
|
||||
Assert.Skip("Direct3D 11 and Direct3D 12 sharing is unavailable.");
|
||||
}
|
||||
|
||||
return new Interop(scheduler, provider, device);
|
||||
}
|
||||
|
||||
public void Draw(ID2D1Image image)
|
||||
{
|
||||
var context = provider.RenderContext;
|
||||
using var borrow = Resources.BeginSourceExternalOperation();
|
||||
var previousTarget = context.Target;
|
||||
using var target = new ID2D1Bitmap1(borrow.DangerousGetView().AddRefBitmap());
|
||||
context.Target = target;
|
||||
context.BeginDraw();
|
||||
context.Clear(null);
|
||||
context.DrawImage(image, Vector2.Zero, null, InterpolationMode.NearestNeighbor, CompositeMode.SourceCopy);
|
||||
context.EndDraw();
|
||||
context.Target = previousTarget;
|
||||
}
|
||||
|
||||
public Rendering CaptureOutput(IGraphicsDevicesAndContext devices, out int width, out int height)
|
||||
{
|
||||
using var lease = Resources.AcquireOutputExternalViewLease();
|
||||
width = lease.Width;
|
||||
height = lease.Height;
|
||||
using var bitmap = new ID2D1Bitmap1(lease.DangerousGetView().AddRefBitmap());
|
||||
return Rendering.Capture(devices, bitmap);
|
||||
}
|
||||
|
||||
public void Dispose()
|
||||
{
|
||||
Pipeline.Dispose();
|
||||
Resources.Dispose();
|
||||
Resources.WaitForDisposal();
|
||||
domain.Dispose();
|
||||
domain.WaitForDisposal();
|
||||
provider.Dispose();
|
||||
scheduler.Dispose();
|
||||
}
|
||||
}
|
||||
|
||||
static int LitPixels(Rendering rendering, WaveOpticsPipeline.PixelRect visible)
|
||||
{
|
||||
var lit = 0;
|
||||
for (var y = 0; y < visible.Height; y++)
|
||||
{
|
||||
for (var x = 0; x < visible.Width; x++)
|
||||
{
|
||||
var pixel = rendering[x, y];
|
||||
Assert.InRange(pixel.Blue, 0, pixel.Alpha);
|
||||
Assert.InRange(pixel.Green, 0, pixel.Alpha);
|
||||
Assert.InRange(pixel.Red, 0, pixel.Alpha);
|
||||
if (pixel.Alpha > 0)
|
||||
lit++;
|
||||
}
|
||||
}
|
||||
|
||||
return lit;
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void TheBlurIsDrawnAfterTheOutputGrowsToFullHd()
|
||||
{
|
||||
using var devices = new GraphicsDevices();
|
||||
using var context = devices.CreateContext();
|
||||
using var interop = Interop.Create(context);
|
||||
using var source = new SourceImage(context, 96, 96, CenteredSquare(96, 32));
|
||||
var parameters = Parameters();
|
||||
Assert.True(interop.Resources.TryEnsureSource(96, 96, out _));
|
||||
WaveOpticsPipeline.PixelRect RenderInto(Func<WaveOpticsPipeline.PixelRect, (int Width, int Height)> outputSize)
|
||||
{
|
||||
interop.Draw(source.Bitmap);
|
||||
interop.Pipeline.Simulate(interop.Resources.GetSourceComputeBinding(), 96, 96, 0, 0, 96, 96, in parameters);
|
||||
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.GetSourceComputeBinding(), interop.Resources.GetOutputComputeBinding(), visible, in parameters);
|
||||
return visible;
|
||||
}
|
||||
|
||||
var first = RenderInto(visible => (visible.Width, visible.Height));
|
||||
interop.CaptureOutput(context, out var firstWidth, out var firstHeight);
|
||||
var second = RenderInto(_ => (1920, 1080));
|
||||
var output = interop.CaptureOutput(context, out var secondWidth, out var secondHeight);
|
||||
|
||||
Assert.Equal((first.Width, first.Height), (firstWidth, firstHeight));
|
||||
Assert.Equal((1920, 1080), (secondWidth, secondHeight));
|
||||
Assert.True(LitPixels(output, second) > 0);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void TheBlurIsDrawnAfterTheSourceIsReplacedByALargerOne()
|
||||
{
|
||||
using var devices = new GraphicsDevices();
|
||||
using var context = devices.CreateContext();
|
||||
using var interop = Interop.Create(context);
|
||||
var parameters = Parameters();
|
||||
var previous = default(WaveOpticsPipeline.PixelRect);
|
||||
|
||||
foreach (var (size, square) in new[] { (96, 32), (128, 64) })
|
||||
{
|
||||
using var source = new SourceImage(context, size, size, CenteredSquare(size, square));
|
||||
Assert.True(interop.Resources.TryEnsureSource(size, size, out var sourceChanged));
|
||||
interop.Draw(source.Bitmap);
|
||||
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.GetSourceComputeBinding(), interop.Resources.GetOutputComputeBinding(), visible, in parameters);
|
||||
var output = interop.CaptureOutput(context, out var width, out var height);
|
||||
|
||||
Assert.True(sourceChanged);
|
||||
Assert.True(visible.Width > previous.Width && visible.Height > previous.Height);
|
||||
Assert.Equal((visible.Width, visible.Height), (width, height));
|
||||
Assert.True(LitPixels(output, visible) > square * square);
|
||||
previous = visible;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,356 @@
|
||||
using ComputeWeave;
|
||||
using System.Runtime.InteropServices;
|
||||
using SpectralConvolution;
|
||||
using WaveOptics.Effects;
|
||||
using WaveOptics.Rendering;
|
||||
|
||||
namespace WaveOptics.Tests;
|
||||
|
||||
[Collection("Direct3D12")]
|
||||
public sealed class WaveOpticsLightTests
|
||||
{
|
||||
const int Black = unchecked((int)0xFF000000);
|
||||
const int White = unchecked((int)0xFFFFFFFF);
|
||||
|
||||
static WaveOpticsPipeline.Parameters Parameters(LightOptions light = default, float gain = 1f, float defocus = 0f, int kernelRadius = 15)
|
||||
=> new(gain, new WaveOpticsPipeline.PsfParameters(
|
||||
WaveOpticsQuality.Standard, kernelRadius, 550f, 8f, 4f, WaveOpticsApertureShape.Circular, 6, 0f, 0f, defocus, 0f, 0f, 0f, 0f, 0f), light);
|
||||
|
||||
static int[] Checkerboard(int width, int height)
|
||||
{
|
||||
var pixels = new int[width * height];
|
||||
for (var y = 0; y < height; y++)
|
||||
{
|
||||
for (var x = 0; x < width; x++)
|
||||
pixels[y * width + x] = (x + y & 1) == 0 ? White : Black;
|
||||
}
|
||||
|
||||
return pixels;
|
||||
}
|
||||
|
||||
static int[] BrightPoint(int width, int height)
|
||||
{
|
||||
var pixels = new int[width * height];
|
||||
Array.Fill(pixels, Black);
|
||||
pixels[(height / 2) * width + width / 2] = White;
|
||||
return pixels;
|
||||
}
|
||||
|
||||
static byte[] Bytes(int[] pixels) => MemoryMarshal.AsBytes(pixels.AsSpan()).ToArray();
|
||||
|
||||
static int GreenAt(int[] pixels, int width, int x, int y) => (pixels[y * width + x] >> 8) & 255;
|
||||
|
||||
static int LitCount(int[] pixels) => pixels.Count(pixel => ((pixel >> 8) & 255) > 0);
|
||||
|
||||
static int[] RenderGpu(int[] source, int width, int height, in WaveOpticsPipeline.Parameters parameters)
|
||||
{
|
||||
using var pipeline = WaveOpticsPipeline.TryCreate();
|
||||
Assert.NotNull(pipeline);
|
||||
var destination = new int[source.Length];
|
||||
pipeline.Process(source, destination, width, height, in parameters);
|
||||
return destination;
|
||||
}
|
||||
|
||||
static int[] RenderCpu(int[] source, int width, int height, in WaveOpticsPipeline.Parameters parameters)
|
||||
{
|
||||
using var pipeline = new WaveOpticsCpuPipeline(3);
|
||||
var destination = new int[source.Length];
|
||||
pipeline.Process(source, destination, width, height, in parameters);
|
||||
return destination;
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void LinearLightAveragesABlackAndWhiteCheckerboardByLightIntensity()
|
||||
{
|
||||
var source = Checkerboard(160, 160);
|
||||
var plain = Parameters(defocus: 3f, kernelRadius: 40);
|
||||
var linear = Parameters(new LightOptions(true, false, 0f, 0f), defocus: 3f, kernelRadius: 40);
|
||||
|
||||
foreach (var render in new Func<int[], WaveOpticsPipeline.Parameters, int[]>[]
|
||||
{
|
||||
(pixels, parameters) => RenderGpu(pixels, 160, 160, in parameters),
|
||||
(pixels, parameters) => RenderCpu(pixels, 160, 160, in parameters),
|
||||
})
|
||||
{
|
||||
var gamma = GreenAt(render(source, plain), 160, 80, 80);
|
||||
var light = GreenAt(render(source, linear), 160, 80, 80);
|
||||
|
||||
Assert.InRange(gamma, 116, 140);
|
||||
Assert.InRange(light, 176, 200);
|
||||
}
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void HighlightsSpreadABrightPointFartherOnBothRoutes()
|
||||
{
|
||||
var source = BrightPoint(121, 121);
|
||||
var plain = Parameters(new LightOptions(true, false, 0f, 0f), kernelRadius: 20);
|
||||
var boosted = Parameters(new LightOptions(true, false, 0.9f, 400f), kernelRadius: 20);
|
||||
|
||||
var gpuPlain = LitCount(RenderGpu(source, 121, 121, in plain));
|
||||
var gpuBoosted = LitCount(RenderGpu(source, 121, 121, in boosted));
|
||||
var cpuPlain = LitCount(RenderCpu(source, 121, 121, in plain));
|
||||
var cpuBoosted = LitCount(RenderCpu(source, 121, 121, in boosted));
|
||||
|
||||
Assert.True(gpuBoosted > gpuPlain * 2, $"{gpuPlain} {gpuBoosted}");
|
||||
Assert.True(cpuBoosted > cpuPlain * 2, $"{cpuPlain} {cpuBoosted}");
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[InlineData(false, true, 0f, 0f)]
|
||||
[InlineData(true, false, 0f, 0f)]
|
||||
[InlineData(true, true, 0.8f, 10f)]
|
||||
public void TheCpuAndTheGpuDrawTheSameLightImageWithinTwoLevels(bool linear, bool dither, float threshold, float boost)
|
||||
{
|
||||
var random = new Random(9);
|
||||
var source = new int[128 * 128];
|
||||
for (var index = 0; index < source.Length; index++)
|
||||
{
|
||||
if (random.NextDouble() < 0.25)
|
||||
{
|
||||
var value = random.Next(40, 256);
|
||||
source[index] = unchecked((int)(0xFF000000u | (uint)value << 16 | (uint)Math.Max(0, value - random.Next(60)) << 8 | (uint)Math.Max(0, value - random.Next(120))));
|
||||
}
|
||||
else
|
||||
source[index] = Black;
|
||||
}
|
||||
|
||||
var parameters = Parameters(new LightOptions(linear, dither, threshold, boost), 1.3f, 0.7f);
|
||||
|
||||
var expected = Bytes(RenderGpu(source, 128, 128, in parameters));
|
||||
var actual = Bytes(RenderCpu(source, 128, 128, in parameters));
|
||||
|
||||
for (var index = 0; index < expected.Length; index++)
|
||||
Assert.InRange(actual[index] - expected[index], -2, 2);
|
||||
Assert.Contains(actual, value => value > 0);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void DitheringChangesTheOutputByAtMostOneLevelAndRepeats()
|
||||
{
|
||||
var source = BrightPoint(121, 121);
|
||||
var plain = Parameters(defocus: 1f);
|
||||
var dithered = Parameters(new LightOptions(false, true, 0f, 0f), defocus: 1f);
|
||||
|
||||
var rounded = Bytes(RenderCpu(source, 121, 121, in plain));
|
||||
var first = Bytes(RenderCpu(source, 121, 121, in dithered));
|
||||
var second = Bytes(RenderCpu(source, 121, 121, in dithered));
|
||||
|
||||
Assert.Equal(first, second);
|
||||
Assert.NotEqual(rounded, first);
|
||||
for (var index = 0; index < rounded.Length; index++)
|
||||
Assert.InRange(first[index] - rounded[index], -1, 1);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void ChangingOnlyTheDitherDrawsFromTheStoreAndMatchesAFreshConvolution()
|
||||
{
|
||||
using var pipeline = new WaveOpticsCpuPipeline(2);
|
||||
var source = Bytes(BrightPoint(96, 96));
|
||||
var plain = Parameters(new LightOptions(true, false, 0.9f, 30f), defocus: 0.5f);
|
||||
pipeline.Simulate(source, 128, 128, 16, 16, 96, 96, in plain);
|
||||
Assert.True(pipeline.TryGetVisibleBounds(128, 128, in plain, out var rect));
|
||||
pipeline.RenderVisible(rect, in plain);
|
||||
|
||||
foreach (var dither in new[] { true, false, true })
|
||||
{
|
||||
var changed = plain with { Light = plain.Light with { Dither = dither } };
|
||||
Assert.False(pipeline.Simulate(source, 128, 128, 16, 16, 96, 96, in changed));
|
||||
var reused = pipeline.RenderVisible(rect, in changed).ToArray();
|
||||
using var fresh = new WaveOpticsCpuPipeline(2);
|
||||
fresh.Simulate(source, 128, 128, 16, 16, 96, 96, in changed);
|
||||
fresh.TryGetVisibleBounds(128, 128, in changed, out var freshRect);
|
||||
var expected = fresh.RenderVisible(freshRect, in changed).ToArray();
|
||||
|
||||
Assert.True(pipeline.HasStore);
|
||||
Assert.Equal(expected, reused);
|
||||
}
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void TheConvolutionIsRecomputedOnlyWhenTheLightSettingsAffectTheInput()
|
||||
{
|
||||
using var pipeline = new WaveOpticsCpuPipeline(2);
|
||||
var source = Bytes(BrightPoint(96, 96));
|
||||
var parameters = Parameters();
|
||||
|
||||
Assert.True(pipeline.Simulate(source, 128, 128, 16, 16, 96, 96, in parameters));
|
||||
var dither = parameters with { Light = new LightOptions(false, true, 0.9f, 20f) };
|
||||
Assert.False(pipeline.Simulate(source, 128, 128, 16, 16, 96, 96, in dither));
|
||||
var linear = parameters with { Light = new LightOptions(true, false, 0.9f, 20f) };
|
||||
Assert.True(pipeline.Simulate(source, 128, 128, 16, 16, 96, 96, in linear));
|
||||
var dithered = linear with { Light = linear.Light with { Dither = true } };
|
||||
Assert.False(pipeline.Simulate(source, 128, 128, 16, 16, 96, 96, in dithered));
|
||||
var otherBoost = linear with { Light = linear.Light with { Boost = 40f } };
|
||||
Assert.True(pipeline.Simulate(source, 128, 128, 16, 16, 96, 96, in otherBoost));
|
||||
var unusedBoost = otherBoost with { Light = new LightOptions(true, false, 0.9f, 1f) };
|
||||
Assert.True(pipeline.Simulate(source, 128, 128, 16, 16, 96, 96, in unusedBoost));
|
||||
var unusedThreshold = unusedBoost with { Light = unusedBoost.Light with { Threshold = 0.5f } };
|
||||
Assert.False(pipeline.Simulate(source, 128, 128, 16, 16, 96, 96, in unusedThreshold));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void TheGpuRedrawsFromTheStoreWhenOnlyTheDitherChanges()
|
||||
{
|
||||
using var pipeline = WaveOpticsPipeline.TryCreate();
|
||||
Assert.NotNull(pipeline);
|
||||
var device = ComputeWeave.GraphicsDevice.GetDefault();
|
||||
var source = BrightPoint(96, 96);
|
||||
using var texture = device.AllocateReadWriteTexture2D<ComputeWeave.Bgra32, ComputeWeave.Float4>(96, 96);
|
||||
texture.CopyFrom(source.Select(pixel => new ComputeWeave.Bgra32 { PackedValue = unchecked((uint)pixel) }).ToArray());
|
||||
var plain = Parameters(new LightOptions(true, false, 0.9f, 30f), defocus: 0.5f);
|
||||
|
||||
int[] Draw(WaveOpticsPipeline.Parameters parameters, out bool convolved)
|
||||
{
|
||||
convolved = pipeline.Simulate(texture, 128, 128, 16, 16, 96, 96, in parameters);
|
||||
Assert.True(pipeline.TryGetVisibleBounds(128, 128, in parameters, out var rect));
|
||||
using var output = device.AllocateReadWriteTexture2D<ComputeWeave.Bgra32, ComputeWeave.Float4>(rect.Width, rect.Height);
|
||||
pipeline.RenderVisible(texture, output, rect, in parameters);
|
||||
var pixels = new ComputeWeave.Bgra32[rect.Width * rect.Height];
|
||||
output.CopyTo(pixels);
|
||||
return pixels.Select(pixel => unchecked((int)pixel.PackedValue)).ToArray();
|
||||
}
|
||||
|
||||
var first = Draw(plain, out var firstConvolved);
|
||||
Assert.False(pipeline.HasStore);
|
||||
var dithered = plain with { Light = plain.Light with { Dither = true } };
|
||||
var second = Draw(dithered, out var secondConvolved);
|
||||
Assert.True(pipeline.HasStore);
|
||||
var third = Draw(plain, out var thirdConvolved);
|
||||
var fourth = Draw(dithered, out var fourthConvolved);
|
||||
|
||||
Assert.True(firstConvolved);
|
||||
Assert.False(secondConvolved);
|
||||
Assert.False(thirdConvolved);
|
||||
Assert.False(fourthConvolved);
|
||||
Assert.NotEqual(first, second);
|
||||
Assert.Equal(first, third);
|
||||
Assert.Equal(second, fourth);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void TheGpuConvolutionIsRecomputedOnlyWhenTheLightSettingsAffectTheInput()
|
||||
{
|
||||
using var pipeline = WaveOpticsPipeline.TryCreate();
|
||||
Assert.NotNull(pipeline);
|
||||
var device = ComputeWeave.GraphicsDevice.GetDefault();
|
||||
var source = BrightPoint(96, 96);
|
||||
using var texture = device.AllocateReadWriteTexture2D<ComputeWeave.Bgra32, ComputeWeave.Float4>(96, 96);
|
||||
texture.CopyFrom(source.Select(pixel => new ComputeWeave.Bgra32 { PackedValue = unchecked((uint)pixel) }).ToArray());
|
||||
var parameters = Parameters();
|
||||
|
||||
Assert.True(pipeline.Simulate(texture, 128, 128, 16, 16, 96, 96, in parameters));
|
||||
var dither = parameters with { Light = new LightOptions(false, true, 0.9f, 20f) };
|
||||
Assert.False(pipeline.Simulate(texture, 128, 128, 16, 16, 96, 96, in dither));
|
||||
var linear = parameters with { Light = new LightOptions(true, false, 0.9f, 20f) };
|
||||
Assert.True(pipeline.Simulate(texture, 128, 128, 16, 16, 96, 96, in linear));
|
||||
var dithered = linear with { Light = linear.Light with { Dither = true } };
|
||||
Assert.False(pipeline.Simulate(texture, 128, 128, 16, 16, 96, 96, in dithered));
|
||||
var otherBoost = linear with { Light = linear.Light with { Boost = 40f } };
|
||||
Assert.True(pipeline.Simulate(texture, 128, 128, 16, 16, 96, 96, in otherBoost));
|
||||
var otherThreshold = otherBoost with { Light = otherBoost.Light with { Threshold = 0.5f } };
|
||||
Assert.True(pipeline.Simulate(texture, 128, 128, 16, 16, 96, 96, in otherThreshold));
|
||||
var unusedBoost = otherThreshold with { Light = new LightOptions(true, false, 0.9f, 1f) };
|
||||
Assert.True(pipeline.Simulate(texture, 128, 128, 16, 16, 96, 96, in unusedBoost));
|
||||
var unusedThreshold = unusedBoost with { Light = unusedBoost.Light with { Threshold = 0.5f } };
|
||||
Assert.False(pipeline.Simulate(texture, 128, 128, 16, 16, 96, 96, in unusedThreshold));
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[InlineData(true)]
|
||||
[InlineData(false)]
|
||||
public void AStoredDitherUsesTheCanvasPositionOfTheVisibleRegion(bool linear)
|
||||
{
|
||||
using var pipeline = new WaveOpticsCpuPipeline(2);
|
||||
var source = Bytes(BrightPoint(96, 96));
|
||||
var plain = Parameters(new LightOptions(linear, false, 0f, 0f), 0.4f, 0.5f);
|
||||
pipeline.Simulate(source, 200, 200, 52, 52, 96, 96, in plain);
|
||||
Assert.True(pipeline.TryGetVisibleBounds(200, 200, in plain, out var rect));
|
||||
Assert.True(rect.X > 0 && rect.Y > 0);
|
||||
pipeline.RenderVisible(rect, in plain);
|
||||
|
||||
foreach (var dither in new[] { true, false, true })
|
||||
{
|
||||
var changed = plain with { Light = plain.Light with { Dither = dither } };
|
||||
pipeline.Simulate(source, 200, 200, 52, 52, 96, 96, in changed);
|
||||
var reused = pipeline.RenderVisible(rect, in changed).ToArray();
|
||||
using var fresh = new WaveOpticsCpuPipeline(2);
|
||||
fresh.Simulate(source, 200, 200, 52, 52, 96, 96, in changed);
|
||||
fresh.TryGetVisibleBounds(200, 200, in changed, out var freshRect);
|
||||
var expected = fresh.RenderVisible(freshRect, in changed).ToArray();
|
||||
|
||||
Assert.True(pipeline.HasStore);
|
||||
Assert.Equal(expected, reused);
|
||||
}
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void AWarmLightPipelineAllocatesNoManagedMemory()
|
||||
{
|
||||
using var pipeline = WaveOpticsPipeline.TryCreate();
|
||||
Assert.NotNull(pipeline);
|
||||
var source = BrightPoint(64, 64);
|
||||
var destination = new int[source.Length];
|
||||
var parameters = Parameters(new LightOptions(true, true, 0.9f, 30f));
|
||||
for (var iteration = 0; iteration < 4; iteration++)
|
||||
pipeline.Process(source, destination, 64, 64, in parameters);
|
||||
GC.Collect();
|
||||
GC.WaitForPendingFinalizers();
|
||||
GC.Collect();
|
||||
|
||||
var minimum = long.MaxValue;
|
||||
for (var iteration = 0; iteration < 16; iteration++)
|
||||
{
|
||||
var before = GC.GetAllocatedBytesForCurrentThread();
|
||||
pipeline.Process(source, destination, 64, 64, in parameters);
|
||||
minimum = Math.Min(minimum, GC.GetAllocatedBytesForCurrentThread() - before);
|
||||
}
|
||||
|
||||
Assert.Equal(0, minimum);
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[InlineData(2)]
|
||||
[InlineData(4)]
|
||||
public void DitheringKeepsTheTotalLightOfASmallSpot(int radius)
|
||||
{
|
||||
const int Size = 400;
|
||||
var source = new int[Size * Size];
|
||||
Array.Fill(source, Black);
|
||||
for (var y = 0; y < Size; y++)
|
||||
{
|
||||
for (var x = 0; x < Size; x++)
|
||||
{
|
||||
var dx = x - Size / 2 + 0.5;
|
||||
var dy = y - Size / 2 + 0.5;
|
||||
if (dx * dx + dy * dy <= radius * radius)
|
||||
source[y * Size + x] = White;
|
||||
}
|
||||
}
|
||||
|
||||
static double Total(int[] pixels)
|
||||
{
|
||||
var sum = 0d;
|
||||
for (var y = 100; y < 300; y++)
|
||||
{
|
||||
for (var x = 100; x < 300; x++)
|
||||
sum += GreenAt(pixels, Size, x, y);
|
||||
}
|
||||
|
||||
return sum;
|
||||
}
|
||||
|
||||
var parameters = new WaveOpticsPipeline.Parameters(1f, new WaveOpticsPipeline.PsfParameters(
|
||||
WaveOpticsQuality.Standard, 63, 550f, 16f, 2f, WaveOpticsApertureShape.Circular, 6, 0f, 0f, 0f, 0f, 0f, 0f, 0f, 0f));
|
||||
var dithered = parameters with { Light = new LightOptions(false, true, 0f, 0f) };
|
||||
|
||||
var reference = Total(source);
|
||||
var plain = Total(RenderCpu(source, Size, Size, in parameters)) / reference;
|
||||
var kept = Total(RenderCpu(source, Size, Size, in dithered)) / reference;
|
||||
|
||||
// Each rounding error is about 0.3 of a level, and the sum of the 40000 errors is a few percent of
|
||||
// the light of the spot at most. Without dithering, the faint tails are rounded down to nothing.
|
||||
Assert.InRange(plain, 0.88, 0.97);
|
||||
Assert.InRange(kept, 0.97, 1.03);
|
||||
}
|
||||
}
|
||||
@@ -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);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,567 @@
|
||||
using ComputeWeave;
|
||||
using ComputeWeave.Interop;
|
||||
using WaveOptics.Abstractions;
|
||||
using WaveOptics.Effects;
|
||||
using WaveOptics.Optics;
|
||||
using WaveOptics.Rendering;
|
||||
|
||||
namespace WaveOptics.Tests;
|
||||
|
||||
[Collection("Direct3D12")]
|
||||
public sealed class WaveOpticsPipelineTests
|
||||
{
|
||||
const int Opaque = unchecked((int)0xFFC0C0C0);
|
||||
const int White = unchecked((int)0xFFFFFFFF);
|
||||
|
||||
static readonly bool Direct3D12IsAvailable = GraphicsDevice.EnumerateDevices().Any();
|
||||
|
||||
static WaveOpticsPipeline CreatePipeline()
|
||||
{
|
||||
if (!Direct3D12IsAvailable)
|
||||
Assert.Skip("Direct3D 12 is unavailable.");
|
||||
var pipeline = WaveOpticsPipeline.TryCreate();
|
||||
Assert.NotNull(pipeline);
|
||||
return pipeline;
|
||||
}
|
||||
|
||||
static WaveOpticsPipeline.Parameters Parameters(
|
||||
float gain = 1f,
|
||||
WaveOpticsQuality quality = WaveOpticsQuality.Standard,
|
||||
int kernelRadius = 15,
|
||||
float fNumber = 8f,
|
||||
float pixelPitch = 4f,
|
||||
float obstruction = 0f,
|
||||
float defocus = 0f,
|
||||
float comaHorizontal = 0f)
|
||||
=> new(gain, new WaveOpticsPipeline.PsfParameters(
|
||||
quality, kernelRadius, 550f, fNumber, pixelPitch, WaveOpticsApertureShape.Circular, 6, 0f, obstruction,
|
||||
defocus, 0f, 0f, comaHorizontal, 0f, 0f));
|
||||
|
||||
static int[] Square(int width, int height, int left, int top, int squareWidth, int squareHeight, int color = Opaque)
|
||||
{
|
||||
var pixels = new int[width * height];
|
||||
for (var y = Math.Max(top, 0); y < Math.Min(top + squareHeight, height); y++)
|
||||
{
|
||||
for (var x = Math.Max(left, 0); x < Math.Min(left + squareWidth, width); x++)
|
||||
pixels[y * width + x] = color;
|
||||
}
|
||||
|
||||
return pixels;
|
||||
}
|
||||
|
||||
static int Alpha(int pixel) => (pixel >> 24) & 255;
|
||||
|
||||
static int Channel(int pixel, int shift) => (pixel >> shift) & 255;
|
||||
|
||||
static (int Left, int Top, int Right, int Bottom) LitBounds(int[] pixels, int width)
|
||||
{
|
||||
var (left, top, right, bottom) = (int.MaxValue, int.MaxValue, int.MinValue, int.MinValue);
|
||||
for (var index = 0; index < pixels.Length; index++)
|
||||
{
|
||||
if (pixels[index] == 0)
|
||||
continue;
|
||||
left = Math.Min(left, index % width);
|
||||
top = Math.Min(top, index / width);
|
||||
right = Math.Max(right, index % width + 1);
|
||||
bottom = Math.Max(bottom, index / width + 1);
|
||||
}
|
||||
|
||||
return (left, top, right, bottom);
|
||||
}
|
||||
|
||||
static void Upload(ReadWriteTexture2D<Bgra32, Float4> texture, int[] pixels)
|
||||
=> texture.CopyFrom(pixels.Select(pixel => new Bgra32 { PackedValue = unchecked((uint)pixel) }).ToArray());
|
||||
|
||||
static int[] Render(WaveOpticsPipeline pipeline, int[] source, int width, int height, WaveOpticsPipeline.Parameters parameters)
|
||||
{
|
||||
var destination = new int[source.Length];
|
||||
pipeline.Process(source, destination, width, height, in parameters);
|
||||
return destination;
|
||||
}
|
||||
|
||||
static int[] RenderSplit(WaveOpticsPipeline pipeline, ReadWriteTexture2D<Bgra32, Float4> source, int width, int height, WaveOpticsPipeline.Parameters parameters)
|
||||
{
|
||||
var device = GraphicsDevice.GetDefault();
|
||||
var pixels = new int[width * height];
|
||||
pipeline.Simulate(source, width, height, 0, 0, width, height, in parameters);
|
||||
if (!pipeline.TryGetVisibleBounds(width, height, in parameters, out var rect))
|
||||
return pixels;
|
||||
|
||||
using var output = device.AllocateReadWriteTexture2D<Bgra32, Float4>(rect.Width, rect.Height);
|
||||
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++)
|
||||
{
|
||||
for (var x = 0; x < rect.Width; x++)
|
||||
pixels[(rect.Y + y) * width + rect.X + x] = unchecked((int)visible[y * rect.Width + x].PackedValue);
|
||||
}
|
||||
|
||||
return pixels;
|
||||
}
|
||||
|
||||
static PsfKernel Kernel(WaveOpticsPipeline.PsfParameters psf)
|
||||
{
|
||||
var gridSize = WaveOpticsSettings.GetPupilGridSize(psf.Quality);
|
||||
var descriptor = new PsfDescriptor(
|
||||
gridSize,
|
||||
WaveOpticsSettings.GetPupilDiameterSamples(gridSize),
|
||||
WaveOpticsSettings.GetKernelSize(psf.KernelRadius),
|
||||
psf.Wavelength,
|
||||
psf.FNumber,
|
||||
psf.PixelPitch,
|
||||
ApertureShape.Circular,
|
||||
psf.BladeCount,
|
||||
psf.BladeRotation,
|
||||
psf.Obstruction,
|
||||
new WavefrontAberration(defocusWaves: psf.Defocus, comaHorizontalWaves: psf.ComaHorizontal));
|
||||
return new FraunhoferPsfGenerator().Generate(descriptor).Kernel;
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void ATransparentSourceStaysTransparent()
|
||||
{
|
||||
using var pipeline = CreatePipeline();
|
||||
var destination = Enumerable.Repeat(-1, 64 * 64).ToArray();
|
||||
var parameters = Parameters();
|
||||
|
||||
pipeline.Process(new int[64 * 64], destination, 64, 64, in parameters);
|
||||
|
||||
Assert.All(destination, pixel => Assert.Equal(0, pixel));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void AZeroGainLeavesNothing()
|
||||
{
|
||||
using var pipeline = CreatePipeline();
|
||||
var destination = Enumerable.Repeat(-1, 96 * 96).ToArray();
|
||||
var parameters = Parameters(gain: 0f);
|
||||
|
||||
pipeline.Process(Square(96, 96, 32, 32, 32, 32), destination, 96, 96, in parameters);
|
||||
|
||||
Assert.All(destination, pixel => Assert.Equal(0, pixel));
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[InlineData(16, 16)]
|
||||
[InlineData(0, 0)]
|
||||
[InlineData(32, 32)]
|
||||
[InlineData(3, 29)]
|
||||
public void AnImpulseSpreadsIntoTheKernelScaledToKeepItsLight(int impulseX, int impulseY)
|
||||
{
|
||||
using var pipeline = CreatePipeline();
|
||||
var parameters = Parameters(kernelRadius: 6, pixelPitch: 1.5f, comaHorizontal: 0.4f);
|
||||
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);
|
||||
|
||||
for (var y = 0; y < 33; y++)
|
||||
{
|
||||
for (var x = 0; x < 33; x++)
|
||||
{
|
||||
var row = impulseY - y + radius;
|
||||
var column = impulseX - x + radius;
|
||||
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);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void AnImpulseSpreadsIntoAComaticPsfItself()
|
||||
{
|
||||
const int Size = 47;
|
||||
const int Center = Size / 2;
|
||||
const float Gain = 4f;
|
||||
using var pipeline = CreatePipeline();
|
||||
var parameters = Parameters(gain: Gain, comaHorizontal: 3f);
|
||||
var kernel = Kernel(parameters.Psf);
|
||||
var radius = kernel.Size / 2;
|
||||
var source = Square(Size, Size, Center, Center, 1, 1, White);
|
||||
|
||||
var rendering = Render(pipeline, source, Size, Size, parameters);
|
||||
|
||||
for (var y = 0; y < Size; y++)
|
||||
{
|
||||
for (var x = 0; x < Size; x++)
|
||||
{
|
||||
var column = Center - x + radius;
|
||||
var row = Center - y + radius;
|
||||
var expected = column >= 0 && column < kernel.Size && row >= 0 && row < kernel.Size ? kernel[column, row] : 0d;
|
||||
var value = (int)Math.Round(Math.Clamp(expected * Gain, 0d, 1d) * 255d, MidpointRounding.ToEven);
|
||||
Assert.InRange(Alpha(rendering[y * Size + x]), value - 1, value + 1);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void TheBlurKeepsTheLightOfTheSource()
|
||||
{
|
||||
using var pipeline = CreatePipeline();
|
||||
var source = Square(128, 128, 48, 48, 32, 32);
|
||||
|
||||
var rendering = Render(pipeline, source, 128, 128, Parameters(defocus: 1f));
|
||||
|
||||
var before = source.Sum(pixel => (long)Alpha(pixel));
|
||||
var after = rendering.Sum(pixel => (long)Alpha(pixel));
|
||||
Assert.InRange(after / (double)before, 0.99, 1.01);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void AUniformAreaKeepsItsBrightness()
|
||||
{
|
||||
using var pipeline = CreatePipeline();
|
||||
var source = Square(96, 96, 16, 16, 64, 64);
|
||||
|
||||
var rendering = Render(pipeline, source, 96, 96, Parameters(fNumber: 16f, pixelPitch: 10f, obstruction: 0.5f));
|
||||
|
||||
var center = rendering[48 * 96 + 48];
|
||||
Assert.InRange(Alpha(center), 254, 255);
|
||||
Assert.InRange(Channel(center, 16), 191, 193);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void TheBlurReachesNoFurtherThanTheKernelRadius()
|
||||
{
|
||||
using var pipeline = CreatePipeline();
|
||||
var source = Square(96, 96, 40, 40, 16, 16);
|
||||
|
||||
var bounds = LitBounds(Render(pipeline, source, 96, 96, Parameters(kernelRadius: 5, pixelPitch: 0.25f)), 96);
|
||||
|
||||
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()
|
||||
{
|
||||
using var pipeline = CreatePipeline();
|
||||
var source = Square(96, 96, 32, 32, 32, 32);
|
||||
|
||||
var full = Render(pipeline, source, 96, 96, Parameters(defocus: 1f));
|
||||
var half = Render(pipeline, source, 96, 96, Parameters(gain: 0.5f, defocus: 1f));
|
||||
|
||||
Assert.All(full.Zip(half), pair =>
|
||||
{
|
||||
foreach (var shift in new[] { 0, 8, 16, 24 })
|
||||
Assert.InRange(Channel(pair.Second, shift), Channel(pair.First, shift) / 2 - 1, Channel(pair.First, shift) / 2 + 1);
|
||||
});
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void TheSameSettingsAlwaysProduceTheSameImage()
|
||||
{
|
||||
using var pipeline = CreatePipeline();
|
||||
var source = Square(128, 128, 48, 48, 32, 32);
|
||||
|
||||
var first = Render(pipeline, source, 128, 128, Parameters(defocus: 0.5f));
|
||||
var second = Render(pipeline, source, 128, 128, Parameters(defocus: 0.5f));
|
||||
|
||||
Assert.Equal(first, second);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void DifferentOpticsBlurDifferently()
|
||||
{
|
||||
using var pipeline = CreatePipeline();
|
||||
var source = Square(128, 128, 48, 48, 32, 32);
|
||||
|
||||
var sharp = Render(pipeline, source, 128, 128, Parameters());
|
||||
var defocused = Render(pipeline, source, 128, 128, Parameters(defocus: 1f));
|
||||
|
||||
Assert.NotEqual(sharp, defocused);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void AWarmPipelineAllocatesNoManagedMemory()
|
||||
{
|
||||
using var pipeline = CreatePipeline();
|
||||
var source = Square(64, 64, 24, 24, 16, 16);
|
||||
var destination = new int[source.Length];
|
||||
var parameters = Parameters();
|
||||
for (var iteration = 0; iteration < 4; iteration++)
|
||||
pipeline.Process(source, destination, 64, 64, in parameters);
|
||||
GC.Collect();
|
||||
GC.WaitForPendingFinalizers();
|
||||
GC.Collect();
|
||||
|
||||
var minimum = long.MaxValue;
|
||||
for (var iteration = 0; iteration < 16; iteration++)
|
||||
{
|
||||
var before = GC.GetAllocatedBytesForCurrentThread();
|
||||
pipeline.Process(source, destination, 64, 64, in parameters);
|
||||
minimum = Math.Min(minimum, GC.GetAllocatedBytesForCurrentThread() - before);
|
||||
}
|
||||
|
||||
Assert.Equal(0, minimum);
|
||||
}
|
||||
|
||||
[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()
|
||||
{
|
||||
using var pipeline = CreatePipeline();
|
||||
var source = Square(96, 96, 32, 32, 32, 32);
|
||||
var parameters = Parameters(defocus: 0.7f);
|
||||
var expected = Render(pipeline, source, 96, 96, parameters);
|
||||
var device = GraphicsDevice.GetDefault();
|
||||
using var sourceTexture = InteropServices.AllocateSharedReadWriteTexture2D<Bgra32, Float4>(device, 96, 96);
|
||||
using var outputTexture = InteropServices.AllocateSharedReadWriteTexture2D<Bgra32, Float4>(device, 96, 96);
|
||||
Upload(sourceTexture, source);
|
||||
|
||||
pipeline.ProcessSharedAndWait(sourceTexture, outputTexture, 96, 96, in parameters);
|
||||
var result = new Bgra32[source.Length];
|
||||
outputTexture.CopyTo(result);
|
||||
|
||||
Assert.Equal(expected.Select(pixel => unchecked((uint)pixel)), result.Select(pixel => pixel.PackedValue));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void RepeatedSharedTextureSubmissionsAllocateNoManagedMemory()
|
||||
{
|
||||
using var pipeline = CreatePipeline();
|
||||
var device = GraphicsDevice.GetDefault();
|
||||
using var source = InteropServices.AllocateSharedReadWriteTexture2D<Bgra32, Float4>(device, 64, 64);
|
||||
using var destination = InteropServices.AllocateSharedReadWriteTexture2D<Bgra32, Float4>(device, 64, 64);
|
||||
var parameters = Parameters();
|
||||
for (var iteration = 0; iteration < 4; iteration++)
|
||||
pipeline.Process(source, destination, 64, 64, in parameters);
|
||||
pipeline.WaitForCompletion();
|
||||
GC.Collect();
|
||||
GC.WaitForPendingFinalizers();
|
||||
GC.Collect();
|
||||
|
||||
var minimum = long.MaxValue;
|
||||
for (var iteration = 0; iteration < 16; iteration++)
|
||||
{
|
||||
var before = GC.GetAllocatedBytesForCurrentThread();
|
||||
pipeline.Process(source, destination, 64, 64, in parameters);
|
||||
minimum = Math.Min(minimum, GC.GetAllocatedBytesForCurrentThread() - before);
|
||||
}
|
||||
pipeline.WaitForCompletion();
|
||||
|
||||
Assert.Equal(0, minimum);
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[InlineData(15, 0f)]
|
||||
[InlineData(5, 1f)]
|
||||
[InlineData(1, 0f)]
|
||||
public void TheVisibleBoundsHoldTheWholeBlurAndRenderTheSameImage(int kernelRadius, float defocus)
|
||||
{
|
||||
using var pipeline = CreatePipeline();
|
||||
var source = Square(160, 144, 60, 52, 32, 24);
|
||||
var parameters = Parameters(kernelRadius: kernelRadius, defocus: defocus);
|
||||
var full = Render(pipeline, source, 160, 144, parameters);
|
||||
var device = GraphicsDevice.GetDefault();
|
||||
using var sourceTexture = device.AllocateReadWriteTexture2D<Bgra32, Float4>(160, 144);
|
||||
Upload(sourceTexture, source);
|
||||
|
||||
var split = RenderSplit(pipeline, sourceTexture, 160, 144, parameters);
|
||||
|
||||
Assert.Equal(full, split);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void TheVisibleBoundsHugTheSourceOnAFourPixelGrid()
|
||||
{
|
||||
using var pipeline = CreatePipeline();
|
||||
var device = GraphicsDevice.GetDefault();
|
||||
using var sourceTexture = device.AllocateReadWriteTexture2D<Bgra32, Float4>(160, 160);
|
||||
Upload(sourceTexture, Square(160, 160, 62, 59, 30, 21));
|
||||
var parameters = Parameters(kernelRadius: 9);
|
||||
|
||||
pipeline.Simulate(sourceTexture, 160, 160, 0, 0, 160, 160, in parameters);
|
||||
Assert.True(pipeline.TryGetVisibleBounds(160, 160, in parameters, out var rect));
|
||||
|
||||
Assert.Equal((0, 0, 0, 0), (rect.X % 4, rect.Y % 4, rect.Width % 4, rect.Height % 4));
|
||||
Assert.InRange(62 - 9 - rect.X, 0, 3);
|
||||
Assert.InRange(59 - 9 - rect.Y, 0, 3);
|
||||
Assert.InRange(rect.X + rect.Width - (62 + 30 + 9), 0, 3);
|
||||
Assert.InRange(rect.Y + rect.Height - (59 + 21 + 9), 0, 3);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void ASmallerKernelRadiusNarrowsTheVisibleBounds()
|
||||
{
|
||||
using var pipeline = CreatePipeline();
|
||||
var device = GraphicsDevice.GetDefault();
|
||||
using var sourceTexture = device.AllocateReadWriteTexture2D<Bgra32, Float4>(160, 160);
|
||||
Upload(sourceTexture, Square(160, 160, 64, 64, 32, 32));
|
||||
var wide = Parameters(kernelRadius: 15);
|
||||
var narrow = Parameters(kernelRadius: 3);
|
||||
|
||||
pipeline.Simulate(sourceTexture, 160, 160, 0, 0, 160, 160, in wide);
|
||||
Assert.True(pipeline.TryGetVisibleBounds(160, 160, in wide, out var wideRect));
|
||||
Assert.True(pipeline.TryGetVisibleBounds(160, 160, in narrow, out var narrowRect));
|
||||
|
||||
Assert.True(narrowRect.X > wideRect.X && narrowRect.Y > wideRect.Y);
|
||||
Assert.True(narrowRect.X + narrowRect.Width < wideRect.X + wideRect.Width && narrowRect.Y + narrowRect.Height < wideRect.Y + wideRect.Height);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void NothingIsVisibleForATransparentSource()
|
||||
{
|
||||
using var pipeline = CreatePipeline();
|
||||
var device = GraphicsDevice.GetDefault();
|
||||
using var sourceTexture = device.AllocateReadWriteTexture2D<Bgra32, Float4>(128, 128);
|
||||
Upload(sourceTexture, new int[128 * 128]);
|
||||
var parameters = Parameters();
|
||||
|
||||
pipeline.Simulate(sourceTexture, 128, 128, 0, 0, 128, 128, in parameters);
|
||||
|
||||
Assert.False(pipeline.TryGetVisibleBounds(128, 128, in parameters, out _));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void APipelineUsedAtAnotherSizeDrawsLikeAFreshOne()
|
||||
{
|
||||
using var pipeline = CreatePipeline();
|
||||
using var fresh = CreatePipeline();
|
||||
var parameters = Parameters(defocus: 0.5f);
|
||||
Render(pipeline, Square(128, 64, 48, 16, 32, 32), 128, 64, parameters);
|
||||
var source = Square(64, 64, 16, 16, 32, 32);
|
||||
|
||||
var reused = Render(pipeline, source, 64, 64, parameters);
|
||||
var expected = Render(fresh, source, 64, 64, parameters);
|
||||
|
||||
Assert.Equal(expected, reused);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void ARunOfTheWholePipelineIsNotMistakenForTheCachedConvolution()
|
||||
{
|
||||
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 parameters = Parameters(defocus: 1f);
|
||||
pipeline.Simulate(sourceTexture, 96, 96, 0, 0, 96, 96, in parameters);
|
||||
Render(pipeline, Square(96, 96, 8, 8, 16, 16), 96, 96, parameters);
|
||||
|
||||
var reused = RenderSplit(pipeline, sourceTexture, 96, 96, parameters);
|
||||
var expected = RenderSplit(fresh, freshTexture, 96, 96, parameters);
|
||||
|
||||
Assert.Equal(expected, reused);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void TheConvolutionIsRecomputedOnlyWhenTheSourceOrTheOpticsChange()
|
||||
{
|
||||
using var pipeline = CreatePipeline();
|
||||
var device = GraphicsDevice.GetDefault();
|
||||
using var sourceTexture = device.AllocateReadWriteTexture2D<Bgra32, Float4>(128, 128);
|
||||
Upload(sourceTexture, Square(128, 128, 48, 48, 32, 32));
|
||||
var parameters = Parameters();
|
||||
|
||||
Assert.True(pipeline.Simulate(sourceTexture, 128, 128, 0, 0, 128, 128, in parameters));
|
||||
Assert.False(pipeline.Simulate(sourceTexture, 128, 128, 0, 0, 128, 128, in parameters));
|
||||
|
||||
var gainChanged = parameters with { Gain = 2f };
|
||||
Assert.False(pipeline.Simulate(sourceTexture, 128, 128, 0, 0, 128, 128, in gainChanged));
|
||||
|
||||
var opticsChanged = parameters with { Psf = parameters.Psf with { Defocus = 0.5f } };
|
||||
Assert.True(pipeline.Simulate(sourceTexture, 128, 128, 0, 0, 128, 128, in opticsChanged));
|
||||
|
||||
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);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,121 @@
|
||||
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);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void ChangingTheDitherStoresLikeAGainChange()
|
||||
{
|
||||
var tracker = new WaveOpticsRenderTracker();
|
||||
tracker.Next(First, Rect, 1f, false, out _);
|
||||
|
||||
Assert.Equal(WaveOpticsRenderMode.ConvolveAndStore, tracker.Next(First, Rect, 1f, true, out _));
|
||||
Assert.True(tracker.HasStore);
|
||||
Assert.Equal(WaveOpticsRenderMode.Stored, tracker.Next(First, Rect, 1f, false, out _));
|
||||
Assert.Equal(WaveOpticsRenderMode.Stored, tracker.Next(First, Rect, 1f, false, out _));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void TheSameDitherWithoutAStoreConvolvesAgain()
|
||||
{
|
||||
var tracker = new WaveOpticsRenderTracker();
|
||||
tracker.Next(First, Rect, 1f, true, out _);
|
||||
|
||||
Assert.Equal(WaveOpticsRenderMode.Convolve, tracker.Next(First, Rect, 1f, true, out _));
|
||||
Assert.False(tracker.HasStore);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void AnotherLightSettingIsAnotherConvolution()
|
||||
{
|
||||
var tracker = new WaveOpticsRenderTracker();
|
||||
tracker.Next(First, Rect, 1f, out _);
|
||||
tracker.Next(First, Rect, 1.5f, out _);
|
||||
var light = First with { Light = new SpectralConvolution.LightOptions(true, false, 0.9f, 10f) };
|
||||
|
||||
Assert.Equal(WaveOpticsRenderMode.Convolve, tracker.Next(light, Rect, 1.5f, out var release));
|
||||
Assert.True(release);
|
||||
Assert.False(tracker.HasStore);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,105 @@
|
||||
using SpectralConvolution;
|
||||
using WaveOptics.Abstractions;
|
||||
using WaveOptics.Effects;
|
||||
using WaveOptics.Optics;
|
||||
|
||||
namespace WaveOptics.Tests;
|
||||
|
||||
public sealed class WaveOpticsSettingsTests
|
||||
{
|
||||
[Theory]
|
||||
[InlineData(WaveOpticsQuality.Draft, 128)]
|
||||
[InlineData(WaveOpticsQuality.Standard, 256)]
|
||||
[InlineData(WaveOpticsQuality.High, 512)]
|
||||
public void EveryQualityChoosesItsPupilGrid(WaveOpticsQuality quality, int gridSize)
|
||||
=> Assert.Equal(gridSize, WaveOpticsSettings.GetPupilGridSize(quality));
|
||||
|
||||
[Theory]
|
||||
[InlineData(128, 32)]
|
||||
[InlineData(256, 64)]
|
||||
[InlineData(512, 128)]
|
||||
public void ThePupilSpansAQuarterOfTheGrid(int gridSize, int diameter)
|
||||
=> Assert.Equal(diameter, WaveOpticsSettings.GetPupilDiameterSamples(gridSize));
|
||||
|
||||
[Theory]
|
||||
[InlineData(1, 3)]
|
||||
[InlineData(7, 15)]
|
||||
[InlineData(15, 31)]
|
||||
public void TheKernelSpansTheRadiusOnBothSidesOfTheCenter(int radius, int size)
|
||||
=> Assert.Equal(size, WaveOpticsSettings.GetKernelSize(radius));
|
||||
|
||||
[Fact]
|
||||
public void TheLargestKernelFitsInTheLargestTile()
|
||||
{
|
||||
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()
|
||||
{
|
||||
{ "defocus", new WavefrontAberration(defocusWaves: 1) },
|
||||
{ "astigmatism", new WavefrontAberration(astigmatismObliqueWaves: 1) },
|
||||
{ "coma", new WavefrontAberration(comaHorizontalWaves: 3) },
|
||||
{ "spherical", new WavefrontAberration(sphericalWaves: 1) },
|
||||
{ "every term at the limit", new WavefrontAberration(defocusWaves: 10, astigmatismVerticalWaves: 10, astigmatismObliqueWaves: 10, comaHorizontalWaves: 10, comaVerticalWaves: 10, sphericalWaves: 10) },
|
||||
};
|
||||
|
||||
[Theory]
|
||||
[MemberData(nameof(Aberrations))]
|
||||
public void EveryAberrationGivesAKernelTheConvolutionAccepts(string aberrationName, WavefrontAberration aberration)
|
||||
{
|
||||
var gridSize = WaveOpticsSettings.GetPupilGridSize(WaveOpticsQuality.Standard);
|
||||
var descriptor = new PsfDescriptor(
|
||||
gridSize,
|
||||
WaveOpticsSettings.GetPupilDiameterSamples(gridSize),
|
||||
WaveOpticsSettings.MaximumKernelSize,
|
||||
550, 8, 4, ApertureShape.Circular, 6, 0, 0, aberration);
|
||||
var kernel = new FraunhoferPsfGenerator().Generate(descriptor).Kernel;
|
||||
var spectrum = new KernelSpectrum();
|
||||
|
||||
spectrum.Update(kernel.Values.Span, WaveOpticsSettings.MaximumKernelRadius, TilePlan.SelectSize(WaveOpticsSettings.MaximumKernelRadius));
|
||||
|
||||
Assert.True(Math.Abs(spectrum.Spectrum[0].X - 1f) <= 1e-6f, aberrationName);
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[InlineData(WaveOpticsSettings.MinimumKernelRadius)]
|
||||
[InlineData(WaveOpticsSettings.DefaultKernelRadius)]
|
||||
[InlineData(16)]
|
||||
[InlineData(17)]
|
||||
[InlineData(48)]
|
||||
[InlineData(WaveOpticsSettings.MaximumKernelRadius)]
|
||||
public void TheCanvasMarginHoldsTheBlurOnAFourPixelGrid(int radius)
|
||||
{
|
||||
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()
|
||||
{
|
||||
int[] slots =
|
||||
[
|
||||
WaveOpticsSettings.ScratchLitCount,
|
||||
WaveOpticsSettings.ScratchBoundsMinX,
|
||||
WaveOpticsSettings.ScratchBoundsMinY,
|
||||
WaveOpticsSettings.ScratchBoundsMaxX,
|
||||
WaveOpticsSettings.ScratchBoundsMaxY,
|
||||
WaveOpticsSettings.ScratchHashSum,
|
||||
WaveOpticsSettings.ScratchHashMix,
|
||||
];
|
||||
|
||||
Assert.Equal(slots.Length, slots.Distinct().Count());
|
||||
Assert.All(slots, slot => Assert.InRange(slot, 0, WaveOpticsSettings.ScratchLength - 1));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,123 @@
|
||||
using System.Runtime.InteropServices;
|
||||
using System.Runtime.Intrinsics;
|
||||
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));
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[InlineData(1, 1, 0.0)]
|
||||
[InlineData(1, 5, 1.0)]
|
||||
[InlineData(7, 3, 0.5)]
|
||||
[InlineData(8, 4, 0.01)]
|
||||
[InlineData(9, 4, 0.3)]
|
||||
[InlineData(15, 6, 1.0)]
|
||||
[InlineData(16, 6, 0.0)]
|
||||
[InlineData(17, 3, 0.02)]
|
||||
[InlineData(63, 9, 0.6)]
|
||||
[InlineData(64, 9, 1.0)]
|
||||
[InlineData(1000, 7, 0.001)]
|
||||
[InlineData(1000, 7, 0.9)]
|
||||
public void TheVectorHashMatchesTheScalarOneBitForBit(int width, int height, double litFraction)
|
||||
{
|
||||
var pixels = RandomPixels(width, height, width * 31 + height, litFraction);
|
||||
var bytes = MemoryMarshal.AsBytes(pixels.AsSpan());
|
||||
|
||||
var expected = WaveOpticsSourceHash.ComputeScalar(bytes, 12, 7, width, height);
|
||||
var actual = WaveOpticsSourceHash.Compute(bytes, 12, 7, width, height);
|
||||
|
||||
Assert.Equal(expected, actual);
|
||||
if (Vector256.IsHardwareAccelerated)
|
||||
Assert.Equal(expected, WaveOpticsSourceHash.ComputeVector(bytes, 12, 7, width, height));
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[InlineData(19)]
|
||||
[InlineData(32)]
|
||||
public void ASingleLitPixelIsFoundWhereverItSits(int width)
|
||||
{
|
||||
const int Height = 3;
|
||||
for (var y = 0; y < Height; y++)
|
||||
{
|
||||
for (var x = 0; x < width; x++)
|
||||
{
|
||||
var pixels = new int[width * Height];
|
||||
pixels[y * width + x] = 0x01020304;
|
||||
var bytes = MemoryMarshal.AsBytes(pixels.AsSpan());
|
||||
|
||||
var expected = WaveOpticsSourceHash.ComputeScalar(bytes, 5, 9, width, Height);
|
||||
var actual = Vector256.IsHardwareAccelerated ? WaveOpticsSourceHash.ComputeVector(bytes, 5, 9, width, Height) : WaveOpticsSourceHash.Compute(bytes, 5, 9, width, Height);
|
||||
|
||||
Assert.Equal(expected, actual);
|
||||
Assert.Equal((1, 5 + x, 9 + y, 5 + x, 9 + y), (actual.LitCount, actual.MinimumX, actual.MinimumY, actual.MaximumX, actual.MaximumY));
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,27 @@
|
||||
{
|
||||
"stryker-config": {
|
||||
"project": "WaveOptics.csproj",
|
||||
"test-runner": "mtp",
|
||||
"coverage-analysis": "off",
|
||||
"concurrency": 4,
|
||||
"additional-timeout": 30000,
|
||||
"mutate": [
|
||||
"**/*.cs",
|
||||
"!**/YMM4-ComputeGuard/**",
|
||||
"!**/YMM4-GitHubUpdateNotifier/**",
|
||||
"!**/YMM4-Telemetry/**",
|
||||
"!**/WaveOpticsTelemetry.cs",
|
||||
"!**/WaveOpticsUpdateNotifier.cs"
|
||||
],
|
||||
"reporters": [
|
||||
"progress",
|
||||
"cleartext",
|
||||
"html"
|
||||
],
|
||||
"thresholds": {
|
||||
"high": 80,
|
||||
"low": 60,
|
||||
"break": 60
|
||||
}
|
||||
}
|
||||
}
|
||||
+18
-1
@@ -3,10 +3,27 @@
|
||||
<Platform Name="Any CPU" />
|
||||
<Platform Name="x64" />
|
||||
</Configurations>
|
||||
<Project Path="Wave Optics/WaveOptics.csproj">
|
||||
<Folder Name="/Solution Items/">
|
||||
<File Path=".editorconfig" />
|
||||
<File Path=".gitattributes" />
|
||||
<File Path=".gitignore" />
|
||||
<File Path=".gitmodules" />
|
||||
<File Path="Directory.Build.props" />
|
||||
<File Path="LICENSE.txt" />
|
||||
<File Path="README.md" />
|
||||
</Folder>
|
||||
<Project Path="WaveOptics/WaveOptics.csproj">
|
||||
<Platform Solution="*|x64" Project="x64" />
|
||||
<BuildDependency Project="WaveOptics.Shader/WaveOptics.Shader.vcxproj" />
|
||||
</Project>
|
||||
<Project Path="WaveOptics.Abstractions/WaveOptics.Abstractions.csproj" />
|
||||
<Project Path="WaveOptics.Tests/WaveOptics.Tests.csproj" />
|
||||
<Project Path="WaveOptics.Harness/WaveOptics.Harness.csproj" />
|
||||
<Project Path="WaveOptics.Shader/WaveOptics.Shader.vcxproj">
|
||||
<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>
|
||||
132ファイル中100ファイルを読み込みました。 変更されたファイルが多すぎるため、それ以降のファイルは表示していません。
さらに表示
新しいイシューから参照
ユーザーをブロックする