コミットを比較
| 作成者 | SHA1 | 日付 | |
|---|---|---|---|
|
|
4a3bf17a5b
|
||
|
|
be6072cce6
|
||
|
|
09076e30b4
|
||
|
|
b8bb676071
|
||
|
|
d24468eb9c
|
||
|
|
364e2c2192
|
||
|
|
31c1410af1
|
||
|
|
8e6966cd37
|
||
|
|
25ed291a6e
|
検索条件に一致するファイルはありません
@@ -1,13 +0,0 @@
|
||||
{
|
||||
"version": 1,
|
||||
"isRoot": true,
|
||||
"tools": {
|
||||
"dotnet-stryker": {
|
||||
"version": "5.0.0",
|
||||
"commands": [
|
||||
"dotnet-stryker"
|
||||
],
|
||||
"rollForward": false
|
||||
}
|
||||
}
|
||||
}
|
||||
-77
@@ -1,77 +0,0 @@
|
||||
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-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,63 +0,0 @@
|
||||
###############################################################################
|
||||
# Set default behavior to automatically normalize line endings.
|
||||
###############################################################################
|
||||
* text=auto
|
||||
|
||||
###############################################################################
|
||||
# Set default behavior for command prompt diff.
|
||||
#
|
||||
# This is need for earlier builds of msysgit that does not have it on by
|
||||
# default for csharp files.
|
||||
# Note: This is only used by command line
|
||||
###############################################################################
|
||||
#*.cs diff=csharp
|
||||
|
||||
###############################################################################
|
||||
# Set the merge driver for project and solution files
|
||||
#
|
||||
# Merging from the command prompt will add diff markers to the files if there
|
||||
# are conflicts (Merging from VS is not affected by the settings below, in VS
|
||||
# the diff markers are never inserted). Diff markers may cause the following
|
||||
# file extensions to fail to load in VS. An alternative would be to treat
|
||||
# these files as binary and thus will always conflict and require user
|
||||
# intervention with every merge. To do so, just uncomment the entries below
|
||||
###############################################################################
|
||||
#*.sln merge=binary
|
||||
#*.csproj merge=binary
|
||||
#*.vbproj merge=binary
|
||||
#*.vcxproj merge=binary
|
||||
#*.vcproj merge=binary
|
||||
#*.dbproj merge=binary
|
||||
#*.fsproj merge=binary
|
||||
#*.lsproj merge=binary
|
||||
#*.wixproj merge=binary
|
||||
#*.modelproj merge=binary
|
||||
#*.sqlproj merge=binary
|
||||
#*.wwaproj merge=binary
|
||||
|
||||
###############################################################################
|
||||
# behavior for image files
|
||||
#
|
||||
# image files are treated as binary by default.
|
||||
###############################################################################
|
||||
#*.jpg binary
|
||||
#*.png binary
|
||||
#*.gif binary
|
||||
|
||||
###############################################################################
|
||||
# diff behavior for common document formats
|
||||
#
|
||||
# Convert binary document formats to text before diffing them. This feature
|
||||
# is only available from the command line. Turn it on by uncommenting the
|
||||
# entries below.
|
||||
###############################################################################
|
||||
#*.doc diff=astextplain
|
||||
#*.DOC diff=astextplain
|
||||
#*.docx diff=astextplain
|
||||
#*.DOCX diff=astextplain
|
||||
#*.dot diff=astextplain
|
||||
#*.DOT diff=astextplain
|
||||
#*.pdf diff=astextplain
|
||||
#*.PDF diff=astextplain
|
||||
#*.rtf diff=astextplain
|
||||
#*.RTF diff=astextplain
|
||||
@@ -1 +0,0 @@
|
||||
github: routersys
|
||||
@@ -1,102 +0,0 @@
|
||||
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
|
||||
@@ -1,5 +0,0 @@
|
||||
blank_issues_enabled: false
|
||||
contact_links:
|
||||
- name: YukkuriMovieMaker4 本体の不具合
|
||||
url: https://manjubox.net/contact/
|
||||
about: 本体に原因がある不具合は、YukkuriMovieMaker4 の「ヘルプ」の「フィードバックを送信」か、公式サイトのお問い合わせから報告してください。
|
||||
@@ -1,63 +0,0 @@
|
||||
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
|
||||
@@ -1,42 +0,0 @@
|
||||
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
|
||||
@@ -1,49 +0,0 @@
|
||||
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
|
||||
@@ -1,21 +0,0 @@
|
||||
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.
|
||||
@@ -1,178 +0,0 @@
|
||||
========================================
|
||||
波動光学 for YMM4 v2.1.0
|
||||
========================================
|
||||
YukkuriMovieMaker4上で動作する、素材を回折も収差もない理想の像とみなし、
|
||||
レンズの開口と波面収差から求めた点像分布関数で畳み込んで、
|
||||
回折と収差によるにじみを描画する映像エフェクトプラグインです。
|
||||
点像分布関数は、1点から出た光が撮像面でどう広がるかを表す関数です。
|
||||
瞳関数は、開口の各点を通る光の振幅と位相を表す関数です。
|
||||
振幅は波の揺れの大きさ、位相は波の進み具合です。
|
||||
本プラグインは、瞳関数のフラウンホーファー回折を高速フーリエ変換で解いて
|
||||
点像分布関数を求めます。
|
||||
履歴フレーム、参照画像、深度情報、学習済みモデルは使用しません。
|
||||
にじみの形は光学系と収差の設定から決定論的に決まり、同じ設定では常に
|
||||
同じ形になります。
|
||||
適用量、利得、波長、F値、画素ピッチ、開口回転、中央遮蔽、デフォーカス、
|
||||
縦横非点収差、斜め非点収差、水平コマ収差、垂直コマ収差、球面収差の
|
||||
13項目はアニメーションに対応しています。
|
||||
エフェクトの種類一覧では「波動光学」として表示されます。
|
||||
--------------------------------------------------------------------------------
|
||||
■ 動作要件
|
||||
--------------------------------------------------------------------------------
|
||||
- OS : Windows 10 バージョン2004(ビルド19041)以降、または
|
||||
64ビット版のWindows 11
|
||||
- YMM4 : YukkuriMovieMaker4の最新版を推奨します
|
||||
- ランタイム : .NET 10.0
|
||||
- GPU : Direct3D 12とDirect3D 11・12間の共有テクスチャおよび
|
||||
共有フェンスを利用できるGPU
|
||||
--------------------------------------------------------------------------------
|
||||
■ 注意事項
|
||||
--------------------------------------------------------------------------------
|
||||
- AviUtl非対応: 本プラグインはAviUtl向けのEXO出力に対応していません。
|
||||
|
||||
- GPU非対応時: Direct3D 12デバイスを取得できない場合と、YMM4が使う
|
||||
Direct3D 11デバイスが相互運用に必要なインターフェースを持たない場合は、
|
||||
エフェクトを適用せず入力映像を表示します。GPUメモリが足りず
|
||||
共有テクスチャを確保できない場合も同じです。
|
||||
|
||||
- 処理対象: 畳み込みには現在のフレームの色と不透明度だけを使用します。
|
||||
履歴フレーム、外部画像、深度情報、学習済みモデルは使用しません。
|
||||
素材に透明でない画素が無いときは、エフェクトを適用せず入力映像を
|
||||
表示します。
|
||||
|
||||
- 計算モデル: 計算は単色のフラウンホーファー回折に限ります。白色光の
|
||||
ように波長の混ざった光は扱いません。点像分布関数は画面のどこでも同じで、
|
||||
像の位置や素材の奥行きで変わるにじみは扱いません。畳み込みは、画素の値を
|
||||
そのまま重み付けして足し合わせます。画素の値を光の強さに比例する値へ
|
||||
直してから畳み込む処理はしません。
|
||||
|
||||
- 品質と収差: 品質は、瞳関数を置く格子の大きさを切り替えます。格子は
|
||||
瞳関数の値を縦横に並べた表で、1つ1つの値を標本と呼びます。格子が粗いと、
|
||||
大きな波面収差で位相が急に変わる所を表しきれず、点像分布関数の形が
|
||||
崩れます。波面収差を大きくするときは、品質を上げてください。
|
||||
|
||||
- カーネル半径: 1〜63画素で、デフォルトは15画素です。カーネルは、畳み込みの
|
||||
重みを正方形に並べたものです。正方形は、中心から上下左右にカーネル半径の
|
||||
画素数まで広がります。正方形の外に届く光は捨て、カーネルの値の和が1に
|
||||
なるように正規化します。デフォーカスを大きくするときは、カーネル半径と
|
||||
品質を上げてください。上げるほど計算が重くなります。
|
||||
|
||||
- 計算領域: 透明な部分も含む素材全体の矩形の上下左右に余白を加えた
|
||||
大きさを計算領域とし、長辺は8192画素が上限です。余白は、カーネル半径を
|
||||
4画素単位に切り上げた画素数で、16画素を下回りません。素材の長辺の
|
||||
上限は、8192画素から余白の2倍を引いた値です。カーネル半径が16画素以下
|
||||
なら8160画素、63画素なら8064画素になります。素材の長辺がこの上限を
|
||||
超える場合は、エフェクトを適用せず入力映像を表示します。
|
||||
|
||||
- 中央遮蔽: 中央遮蔽で開口をほとんどふさぎ、瞳関数の格子に光の通る標本が
|
||||
1つも無くなる設定では、エフェクトを適用せず入力映像を表示します。
|
||||
品質を上げると起きにくくなります。
|
||||
|
||||
- 処理負荷: GPUメモリ使用量は、計算領域の大きさに応じて増えます。
|
||||
作業用のバッファーとして、計算領域の1画素につき32バイトをGPUに
|
||||
確保します。処理量は、素材全体の大きさと畳み込む範囲の大きさに応じて
|
||||
増えます。畳み込む範囲は、透明でない画素をすべて囲む最小の矩形を
|
||||
カーネル半径だけ広げ、外側へ4画素単位にそろえた範囲です。畳み込みは、
|
||||
横方向と縦方向の1次元の重みを1組とした、何組かの和で近似して行います。
|
||||
収差を入れると組の数が増え、カーネル半径を上げると1組あたりの計算量が
|
||||
増えるので、どちらも計算が重くなります。品質を上げると、点像分布関数の
|
||||
計算が重くなります。
|
||||
|
||||
- キャッシュ: 素材の大きさと色と不透明度が変わらず、「利得」と「適用量」
|
||||
以外の項目も変わらないフレームでは、畳み込みの計算を再利用します。
|
||||
利得だけを変えたフレームでは、再利用した畳み込みに利得を掛け直します。
|
||||
適用量だけを変えたフレームでは、混ぜる割合だけを変えます。動画や口パクの
|
||||
ように素材の内容が変わるフレームと、「利得」と「適用量」以外の項目を
|
||||
アニメーションで変えたフレームでは、毎回計算し直すので処理が重く
|
||||
なります。素材が変わったかどうかを調べる計算は、再利用するフレームでも
|
||||
毎フレーム行います。
|
||||
|
||||
- 適用量0%: 適用量は、入力映像と、利得を掛けた結果を混ぜる割合です。
|
||||
適用量が0%のときは入力を変更せず、畳み込みの計算も行いません。
|
||||
|
||||
- 利得: 利得は、畳み込んだ結果に掛ける倍率です。100%で画素の値の総和を
|
||||
保ちます。利得を掛けた結果は、入力映像と混ぜる前に、各成分が表せる
|
||||
最大の値で打ち切ります。
|
||||
|
||||
- 再現性: 計算は決定論的で、時間値や乱数を使用しません。同じGPUと
|
||||
ドライバーでは、同じ素材と同じ設定から常に同じ結果になります。
|
||||
|
||||
- 透明部分: 畳み込みは不透明度にも掛かるので、素材の縁の外にも半透明の
|
||||
にじみが広がります。出力の範囲は、素材の範囲と畳み込む範囲を合わせた
|
||||
ものです。適用量が0%のときは、素材の範囲のままです。
|
||||
|
||||
- 更新通知: エフェクトを最初に生成したときに、YMM4の実行中に一度だけ
|
||||
新しい正式版を確認します。更新情報を取得できない場合は通知せず、
|
||||
そのまま動作します。プレリリースは通知の対象に含めません。
|
||||
|
||||
- 本プラグインを使用する前に、YMM4のプロジェクトファイルのバックアップを
|
||||
作成することを推奨します。
|
||||
--------------------------------------------------------------------------------
|
||||
■ 不具合の報告
|
||||
--------------------------------------------------------------------------------
|
||||
本プラグインは、想定していない例外が起きたときに、その内容を開発者へ自動で
|
||||
送信します。同意は求めず、常に送信します。
|
||||
|
||||
送信する情報は次のとおりです。
|
||||
例外 : 型の完全名、メッセージ、スタックトレース
|
||||
発生位置 : モジュール名、関数名、ファイル名、行番号
|
||||
プラグイン : アセンブリ名、バージョン
|
||||
実行環境 : OSの名前とバージョン、.NETのバージョン、
|
||||
CPUのアーキテクチャ、論理プロセッサ数
|
||||
識別子 : YMM4の起動ごとに決まるセッション識別子、報告ごとの識別子
|
||||
|
||||
映像の中身とプロジェクトの内容は送信しません。継続して個人を追跡する
|
||||
識別子も持ちません。セッション識別子はYMM4を起動し直すと別の値に
|
||||
なります。メッセージとファイル名に含まれる利用者名などの文字列は、送信の
|
||||
前に置き換えます。送信元のIPアドレスは受信側へ渡す手前で取り除いています。
|
||||
|
||||
送信するのは想定していない例外だけです。YMM4が本プラグインのエフェクトを
|
||||
作るとき、フレームごとに更新するとき、入力をつなぎ直すとき、破棄するときと、
|
||||
Direct2Dがシェーダーの定数を書き込むときに起きた例外を報告し、その後は
|
||||
YMM4へそのまま渡します。更新の確認では、更新情報の取得と比較で起きた例外は
|
||||
報告しません。通知の文を組み立てて表示するときに起きた例外は報告し、
|
||||
YMM4へは渡しません。画面の操作やバックグラウンドの処理で未処理になった
|
||||
例外も報告しますが、本プラグインのコードが関わる例外に限ります。
|
||||
本プラグインの外で起きた例外は送信しません。
|
||||
|
||||
次の失敗は送信しません。
|
||||
効果をかけないだけで済ませるもの : Direct3D 12デバイスを取得できない、
|
||||
YMM4のDirect3D 11デバイスが
|
||||
相互運用に必要なインターフェースを
|
||||
持たない、GPUメモリが足りず
|
||||
共有テクスチャを確保できない、
|
||||
計算領域が8192画素に収まらない、
|
||||
開口に光の通る標本が無いときに、
|
||||
エフェクトを適用せず入力映像を
|
||||
表示したとき
|
||||
更新の確認の通信の失敗 : manjubox.netとGitHubのどちらへも
|
||||
接続できない
|
||||
|
||||
送信できなかった報告はYMM4のユーザーフォルダーへ退避します。
|
||||
次にYMM4を起動したあと、本プラグインのエフェクトを生成するか、
|
||||
同じくYMM4-Telemetryで報告する別のプラグインが動き始めると、
|
||||
退避した報告を1回の起動で10件まで送り直します。
|
||||
送信も再送も非同期に行うため、通信を待って起動と描画が遅くなることは
|
||||
ありません。
|
||||
--------------------------------------------------------------------------------
|
||||
■ 免責事項
|
||||
--------------------------------------------------------------------------------
|
||||
本プラグインはMITライセンスのもとで公開されています。
|
||||
本ソフトウェアは「現状のまま」提供されており、明示または黙示を問わず、
|
||||
商品性、特定目的への適合性、および権利非侵害に関する保証を含む、
|
||||
いかなる種類の保証も行いません。
|
||||
作者は、本プラグインの使用または使用不能に起因するいかなる損害についても、
|
||||
一切の責任を負いません。
|
||||
ご利用は自己責任でお願いします。
|
||||
--------------------------------------------------------------------------------
|
||||
■ サードパーティライセンス
|
||||
--------------------------------------------------------------------------------
|
||||
本プラグインはComputeWeave(MIT License)を同梱しています。
|
||||
ライセンスの全文は同梱のLICENSEフォルダー(ComputeWeave.txt)に収録しています。
|
||||
ComputeWeave : Copyright (c) 2024 Sergio Pedri
|
||||
--------------------------------------------------------------------------------
|
||||
■ ライセンス
|
||||
--------------------------------------------------------------------------------
|
||||
MIT License
|
||||
https://github.com/routersys/YMM4-WaveOptics
|
||||
========================================
|
||||
@@ -1,87 +0,0 @@
|
||||
<!--
|
||||
当てはまらない節は消してください。「関連する Issue」と「動きの変更」の節は残し、該当しないときは「なし」と書いてください。
|
||||
-->
|
||||
|
||||
## 概要
|
||||
|
||||
<!--
|
||||
何をどう変えたか。なぜその変更が必要か。
|
||||
-->
|
||||
|
||||
## 関連する Issue
|
||||
|
||||
<!--
|
||||
新しい機能、設定の項目や既定値の変更、大きめの不具合の修正、意図して出力を変える変更、互換性を損なう変更、コードの構成を大きく変える変更は、先に Issue で合意してください。
|
||||
Issue が無い変更では、下の行を「なし」に書き換えてください。
|
||||
-->
|
||||
|
||||
Closes #
|
||||
|
||||
## 変更の種類
|
||||
|
||||
<!-- 当てはまるものを残してください。 -->
|
||||
|
||||
- 不具合の修正
|
||||
- 機能の追加
|
||||
- 動きの変更
|
||||
- 性能の改善
|
||||
- テストの追加
|
||||
- 依存関係の更新
|
||||
- 文書
|
||||
- ビルド、リリース
|
||||
|
||||
## 動きの変更
|
||||
|
||||
<!--
|
||||
利用者から見て何が変わるか。設定の項目、既定値、出力の結果、エラーの出方の変化も含みます。
|
||||
保存済みのプロジェクトの結果が変わるなら、必ず書いてください。
|
||||
-->
|
||||
|
||||
## 検証
|
||||
|
||||
<!--
|
||||
手元で実際に確かめた結果を書いてください。
|
||||
- ビルドの結果と、テストのプロジェクトがあればテストの結果
|
||||
- YukkuriMovieMaker4 で実際に動かして確かめたこと
|
||||
- 実行できなかったテストと、その理由
|
||||
実際に動かして観察したこと、コードを読んで判断したこと、推測したことを分けて書いてください。
|
||||
-->
|
||||
|
||||
使った YukkuriMovieMaker4 のバージョン:
|
||||
|
||||
GPU に関わる変更では、使った GPU とドライバー:
|
||||
|
||||
## 確認
|
||||
|
||||
<!-- テストのプロジェクトが無いリポジトリでは、実装とテストを分ける項目を消してください。 -->
|
||||
|
||||
- [ ] 1 つの目的の変更だけを含み、関係の無い整理や整形を含めていない。
|
||||
- [ ] どのコミットも、それ単独でビルドが通る。
|
||||
- [ ] 実装の変更と、それを確かめるテストを、別のコミットに分けた。
|
||||
- [ ] コミットの件名は日本語で書き、50 文字以内に収め、「〜する」の形で終えた。日本語で書けない場合は、その旨を「レビューで見てほしい点」に書いた。
|
||||
- [ ] コミットの本文は、リリースノートでの変更の分類を指定する行を求められたときだけ書いた。
|
||||
- [ ] 変更する箇所で既に使われている実装のパターンに従った。
|
||||
- [ ] 新しく書いたコードにコメントを入れず、コメントアウトしたコードも残していない。既存のコメントとドキュメントコメントは残した。
|
||||
- [ ] 自分の変更で増えたビルドの警告を直した。
|
||||
- [ ] 出力を変えるつもりの無い変更では、変更前と変更後で出力が一致することを確かめた。
|
||||
- [ ] この変更と関係の無い依存関係の更新を含めていない。
|
||||
- [ ] 動きを変えた場合、README を直した。`.github/Plugin_Readme.txt` があるリポジトリでは、それも直した。
|
||||
- [ ] バージョンを上げる変更を含めていない。
|
||||
|
||||
## 性能の改善を主張する場合
|
||||
|
||||
<!-- それ以外の場合は、この節ごと消してください。 -->
|
||||
|
||||
- [ ] 同じ機材、ドライバー、設定、電源の条件で、変更前と変更後のビルドを交互に繰り返し測った。
|
||||
- [ ] 測定の間を空け、ほかのプロセスが GPU を使っていない状態で測った。
|
||||
- [ ] 正しさの確認と性能の測定を、別々に実行した。
|
||||
|
||||
<!--
|
||||
測定の条件と、測定値。
|
||||
-->
|
||||
|
||||
## レビューで見てほしい点
|
||||
|
||||
<!--
|
||||
判断に迷った点、意見を聞きたい点、意図して外した部分とその理由。
|
||||
-->
|
||||
@@ -1,414 +0,0 @@
|
||||
name: リリース
|
||||
|
||||
on:
|
||||
push:
|
||||
tags:
|
||||
- 'v*'
|
||||
|
||||
permissions:
|
||||
contents: write
|
||||
|
||||
jobs:
|
||||
build-and-release:
|
||||
runs-on: windows-latest
|
||||
|
||||
steps:
|
||||
- name: ソースコードのチェックアウト
|
||||
uses: actions/checkout@v7
|
||||
with:
|
||||
submodules: recursive
|
||||
fetch-depth: 0
|
||||
|
||||
- name: .NET SDK のセットアップ
|
||||
uses: actions/setup-dotnet@v6
|
||||
with:
|
||||
dotnet-version: '10.0.x'
|
||||
|
||||
- name: MSBuild のセットアップ
|
||||
uses: microsoft/setup-msbuild@v3
|
||||
|
||||
- name: YMM4 最新リリースの取得と解凍
|
||||
id: ymm4
|
||||
shell: pwsh
|
||||
run: |
|
||||
$release = Invoke-RestMethod -Uri "https://api.github.com/repos/manju-summoner/YukkuriMovieMaker4/releases/latest" `
|
||||
-Headers @{ "User-Agent" = "WaveOptics-CI" }
|
||||
$asset = $release.assets | Where-Object { $_.name -like "*_Lite.zip" } | Select-Object -First 1
|
||||
if (-not $asset) {
|
||||
$asset = $release.assets | Where-Object { $_.name -like "*.zip" } | Select-Object -First 1
|
||||
}
|
||||
Write-Host "ダウンロード対象: $($asset.name)"
|
||||
Invoke-WebRequest -Uri $asset.browser_download_url -OutFile "ymm4.zip"
|
||||
Expand-Archive -Path "ymm4.zip" -DestinationPath "ymm4_extracted" -Force
|
||||
$ymm4Dir = (Get-ChildItem -Path "ymm4_extracted" -Recurse -Filter "YukkuriMovieMaker.dll" |
|
||||
Select-Object -First 1).DirectoryName
|
||||
Write-Host "YMM4 DLL ディレクトリ: $ymm4Dir"
|
||||
echo "YMM4_DIR=$ymm4Dir\" >> $env:GITHUB_OUTPUT
|
||||
|
||||
- name: タグ名からバージョンを取得
|
||||
id: version
|
||||
shell: pwsh
|
||||
run: |
|
||||
$tag = "${{ github.ref_name }}"
|
||||
echo "TAG=$tag" >> $env:GITHUB_OUTPUT
|
||||
echo "VERSION=$($tag.TrimStart('v'))" >> $env:GITHUB_OUTPUT
|
||||
|
||||
- name: バージョン記載の照合
|
||||
shell: pwsh
|
||||
run: |
|
||||
$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 = "WaveOptics/WaveOptics.csproj"
|
||||
dotnet build "$proj" `
|
||||
-c Release `
|
||||
-p:YMM4DirPath="${{ steps.ymm4.outputs.YMM4_DIR }}" `
|
||||
-p:Platform=x64 `
|
||||
-p:SkipPluginDeploy=true
|
||||
|
||||
- name: テストプロジェクトのビルド
|
||||
shell: pwsh
|
||||
run: |
|
||||
dotnet build WaveOptics.Tests/WaveOptics.Tests.csproj `
|
||||
-c Release `
|
||||
-p:YMM4DirPath="${{ steps.ymm4.outputs.YMM4_DIR }}" `
|
||||
-p:Platform=x64 `
|
||||
-p:SkipPluginDeploy=true `
|
||||
-maxcpucount:1
|
||||
|
||||
- name: テストの実行
|
||||
shell: pwsh
|
||||
run: |
|
||||
dotnet test WaveOptics.Tests/WaveOptics.Tests.csproj `
|
||||
--no-build `
|
||||
--no-restore `
|
||||
-c Release `
|
||||
-p:Platform=x64 `
|
||||
-p:SkipPluginDeploy=true
|
||||
|
||||
- name: パッケージの作成
|
||||
id: package
|
||||
shell: pwsh
|
||||
run: |
|
||||
$version = "${{ steps.version.outputs.TAG }}"
|
||||
$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
|
||||
|
||||
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"
|
||||
if (Test-Path $src) {
|
||||
New-Item -ItemType Directory -Path "$stageRoot/$lang" -Force | Out-Null
|
||||
Copy-Item "$src/*.dll" "$stageRoot/$lang/"
|
||||
}
|
||||
}
|
||||
|
||||
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@v3
|
||||
with:
|
||||
name: ${{ steps.version.outputs.TAG }}
|
||||
body_path: release-body.md
|
||||
files: ${{ steps.package.outputs.PKG_NAME }}
|
||||
draft: false
|
||||
prerelease: false
|
||||
-367
@@ -1,367 +0,0 @@
|
||||
## Ignore Visual Studio temporary files, build results, and
|
||||
## files generated by popular Visual Studio add-ons.
|
||||
##
|
||||
## Get latest from https://github.com/github/gitignore/blob/master/VisualStudio.gitignore
|
||||
|
||||
# User-specific files
|
||||
*.rsuser
|
||||
*.suo
|
||||
*.user
|
||||
*.userosscache
|
||||
*.sln.docstates
|
||||
*.cso
|
||||
*.resx
|
||||
|
||||
# User-specific files (MonoDevelop/Xamarin Studio)
|
||||
*.userprefs
|
||||
|
||||
# Mono auto generated files
|
||||
mono_crash.*
|
||||
|
||||
# Build results
|
||||
[Dd]ebug/
|
||||
[Dd]ebugPublic/
|
||||
[Rr]elease/
|
||||
[Rr]eleases/
|
||||
x64/
|
||||
x86/
|
||||
[Ww][Ii][Nn]32/
|
||||
[Aa][Rr][Mm]/
|
||||
[Aa][Rr][Mm]64/
|
||||
bld/
|
||||
[Bb]in/
|
||||
[Oo]bj/
|
||||
[Oo]ut/
|
||||
[Ll]og/
|
||||
[Ll]ogs/
|
||||
|
||||
# Visual Studio 2015/2017 cache/options directory
|
||||
.vs/
|
||||
# Uncomment if you have tasks that create the project's static files in wwwroot
|
||||
#wwwroot/
|
||||
|
||||
# Visual Studio 2017 auto generated files
|
||||
Generated\ Files/
|
||||
|
||||
# MSTest test Results
|
||||
[Tt]est[Rr]esult*/
|
||||
[Bb]uild[Ll]og.*
|
||||
|
||||
# NUnit
|
||||
*.VisualState.xml
|
||||
TestResult.xml
|
||||
nunit-*.xml
|
||||
|
||||
# Build Results of an ATL Project
|
||||
[Dd]ebugPS/
|
||||
[Rr]eleasePS/
|
||||
dlldata.c
|
||||
|
||||
# Benchmark Results
|
||||
BenchmarkDotNet.Artifacts/
|
||||
|
||||
# .NET Core
|
||||
project.lock.json
|
||||
project.fragment.lock.json
|
||||
artifacts/
|
||||
|
||||
# ASP.NET Scaffolding
|
||||
ScaffoldingReadMe.txt
|
||||
|
||||
# StyleCop
|
||||
StyleCopReport.xml
|
||||
|
||||
# Files built by Visual Studio
|
||||
*_i.c
|
||||
*_p.c
|
||||
*_h.h
|
||||
*.ilk
|
||||
*.meta
|
||||
*.obj
|
||||
*.iobj
|
||||
*.pch
|
||||
*.pdb
|
||||
*.ipdb
|
||||
*.pgc
|
||||
*.pgd
|
||||
*.rsp
|
||||
*.sbr
|
||||
*.tlb
|
||||
*.tli
|
||||
*.tlh
|
||||
*.tmp
|
||||
*.tmp_proj
|
||||
*_wpftmp.csproj
|
||||
*.log
|
||||
*.vspscc
|
||||
*.vssscc
|
||||
.builds
|
||||
*.pidb
|
||||
*.svclog
|
||||
*.scc
|
||||
|
||||
# Chutzpah Test files
|
||||
_Chutzpah*
|
||||
|
||||
# Visual C++ cache files
|
||||
ipch/
|
||||
*.aps
|
||||
*.ncb
|
||||
*.opendb
|
||||
*.opensdf
|
||||
*.sdf
|
||||
*.cachefile
|
||||
*.VC.db
|
||||
*.VC.VC.opendb
|
||||
|
||||
# Visual Studio profiler
|
||||
*.psess
|
||||
*.vsp
|
||||
*.vspx
|
||||
*.sap
|
||||
|
||||
# Visual Studio Trace Files
|
||||
*.e2e
|
||||
|
||||
# TFS 2012 Local Workspace
|
||||
$tf/
|
||||
|
||||
# Guidance Automation Toolkit
|
||||
*.gpState
|
||||
|
||||
# ReSharper is a .NET coding add-in
|
||||
_ReSharper*/
|
||||
*.[Rr]e[Ss]harper
|
||||
*.DotSettings.user
|
||||
|
||||
# TeamCity is a build add-in
|
||||
_TeamCity*
|
||||
|
||||
# DotCover is a Code Coverage Tool
|
||||
*.dotCover
|
||||
|
||||
# AxoCover is a Code Coverage Tool
|
||||
.axoCover/*
|
||||
!.axoCover/settings.json
|
||||
|
||||
# Coverlet is a free, cross platform Code Coverage Tool
|
||||
coverage*.json
|
||||
coverage*.xml
|
||||
coverage*.info
|
||||
|
||||
# Visual Studio code coverage results
|
||||
*.coverage
|
||||
*.coveragexml
|
||||
|
||||
# NCrunch
|
||||
_NCrunch_*
|
||||
.*crunch*.local.xml
|
||||
nCrunchTemp_*
|
||||
|
||||
# MightyMoose
|
||||
*.mm.*
|
||||
AutoTest.Net/
|
||||
|
||||
# Web workbench (sass)
|
||||
.sass-cache/
|
||||
|
||||
# Installshield output folder
|
||||
[Ee]xpress/
|
||||
|
||||
# DocProject is a documentation generator add-in
|
||||
DocProject/buildhelp/
|
||||
DocProject/Help/*.HxT
|
||||
DocProject/Help/*.HxC
|
||||
DocProject/Help/*.hhc
|
||||
DocProject/Help/*.hhk
|
||||
DocProject/Help/*.hhp
|
||||
DocProject/Help/Html2
|
||||
DocProject/Help/html
|
||||
|
||||
# Click-Once directory
|
||||
publish/
|
||||
|
||||
# Publish Web Output
|
||||
*.[Pp]ublish.xml
|
||||
*.azurePubxml
|
||||
# Note: Comment the next line if you want to checkin your web deploy settings,
|
||||
# but database connection strings (with potential passwords) will be unencrypted
|
||||
*.pubxml
|
||||
*.publishproj
|
||||
|
||||
# Microsoft Azure Web App publish settings. Comment the next line if you want to
|
||||
# checkin your Azure Web App publish settings, but sensitive information contained
|
||||
# in these scripts will be unencrypted
|
||||
PublishScripts/
|
||||
|
||||
# NuGet Packages
|
||||
*.nupkg
|
||||
# NuGet Symbol Packages
|
||||
*.snupkg
|
||||
# The packages folder can be ignored because of Package Restore
|
||||
**/[Pp]ackages/*
|
||||
# except build/, which is used as an MSBuild target.
|
||||
!**/[Pp]ackages/build/
|
||||
# Uncomment if necessary however generally it will be regenerated when needed
|
||||
#!**/[Pp]ackages/repositories.config
|
||||
# NuGet v3's project.json files produces more ignorable files
|
||||
*.nuget.props
|
||||
*.nuget.targets
|
||||
|
||||
# Microsoft Azure Build Output
|
||||
csx/
|
||||
*.build.csdef
|
||||
|
||||
# Microsoft Azure Emulator
|
||||
ecf/
|
||||
rcf/
|
||||
|
||||
# Windows Store app package directories and files
|
||||
AppPackages/
|
||||
BundleArtifacts/
|
||||
Package.StoreAssociation.xml
|
||||
_pkginfo.txt
|
||||
*.appx
|
||||
*.appxbundle
|
||||
*.appxupload
|
||||
|
||||
# Visual Studio cache files
|
||||
# files ending in .cache can be ignored
|
||||
*.[Cc]ache
|
||||
# but keep track of directories ending in .cache
|
||||
!?*.[Cc]ache/
|
||||
|
||||
# Others
|
||||
ClientBin/
|
||||
~$*
|
||||
*~
|
||||
*.dbmdl
|
||||
*.dbproj.schemaview
|
||||
*.jfm
|
||||
*.pfx
|
||||
*.publishsettings
|
||||
orleans.codegen.cs
|
||||
|
||||
# Including strong name files can present a security risk
|
||||
# (https://github.com/github/gitignore/pull/2483#issue-259490424)
|
||||
#*.snk
|
||||
|
||||
# Since there are multiple workflows, uncomment next line to ignore bower_components
|
||||
# (https://github.com/github/gitignore/pull/1529#issuecomment-104372622)
|
||||
#bower_components/
|
||||
|
||||
# RIA/Silverlight projects
|
||||
Generated_Code/
|
||||
|
||||
# Backup & report files from converting an old project file
|
||||
# to a newer Visual Studio version. Backup files are not needed,
|
||||
# because we have git ;-)
|
||||
_UpgradeReport_Files/
|
||||
Backup*/
|
||||
UpgradeLog*.XML
|
||||
UpgradeLog*.htm
|
||||
ServiceFabricBackup/
|
||||
*.rptproj.bak
|
||||
|
||||
# SQL Server files
|
||||
*.mdf
|
||||
*.ldf
|
||||
*.ndf
|
||||
|
||||
# Business Intelligence projects
|
||||
*.rdl.data
|
||||
*.bim.layout
|
||||
*.bim_*.settings
|
||||
*.rptproj.rsuser
|
||||
*- [Bb]ackup.rdl
|
||||
*- [Bb]ackup ([0-9]).rdl
|
||||
*- [Bb]ackup ([0-9][0-9]).rdl
|
||||
|
||||
# Microsoft Fakes
|
||||
FakesAssemblies/
|
||||
|
||||
# GhostDoc plugin setting file
|
||||
*.GhostDoc.xml
|
||||
|
||||
# Node.js Tools for Visual Studio
|
||||
.ntvs_analysis.dat
|
||||
node_modules/
|
||||
|
||||
# Visual Studio 6 build log
|
||||
*.plg
|
||||
|
||||
# Visual Studio 6 workspace options file
|
||||
*.opt
|
||||
|
||||
# Visual Studio 6 auto-generated workspace file (contains which files were open etc.)
|
||||
*.vbw
|
||||
|
||||
# Visual Studio LightSwitch build output
|
||||
**/*.HTMLClient/GeneratedArtifacts
|
||||
**/*.DesktopClient/GeneratedArtifacts
|
||||
**/*.DesktopClient/ModelManifest.xml
|
||||
**/*.Server/GeneratedArtifacts
|
||||
**/*.Server/ModelManifest.xml
|
||||
_Pvt_Extensions
|
||||
|
||||
# Paket dependency manager
|
||||
.paket/paket.exe
|
||||
paket-files/
|
||||
|
||||
# FAKE - F# Make
|
||||
.fake/
|
||||
|
||||
# CodeRush personal settings
|
||||
.cr/personal
|
||||
|
||||
# Python Tools for Visual Studio (PTVS)
|
||||
__pycache__/
|
||||
*.pyc
|
||||
|
||||
# Cake - Uncomment if you are using it
|
||||
# tools/**
|
||||
# !tools/packages.config
|
||||
|
||||
# Tabs Studio
|
||||
*.tss
|
||||
|
||||
# Telerik's JustMock configuration file
|
||||
*.jmconfig
|
||||
|
||||
# BizTalk build output
|
||||
*.btp.cs
|
||||
*.btm.cs
|
||||
*.odx.cs
|
||||
*.xsd.cs
|
||||
|
||||
# OpenCover UI analysis results
|
||||
OpenCover/
|
||||
|
||||
# Azure Stream Analytics local run output
|
||||
ASALocalRun/
|
||||
|
||||
# MSBuild Binary and Structured Log
|
||||
*.binlog
|
||||
|
||||
# NVidia Nsight GPU debugger configuration file
|
||||
*.nvuser
|
||||
|
||||
# MFractors (Xamarin productivity tool) working folder
|
||||
.mfractor/
|
||||
|
||||
# Local History for Visual Studio
|
||||
.localhistory/
|
||||
|
||||
# BeatPulse healthcheck temp database
|
||||
healthchecksdb
|
||||
|
||||
# Backup folder for Package Reference Convert tool in Visual Studio 2017
|
||||
MigrationBackup/
|
||||
|
||||
# Ionide (cross platform F# VS Code tools) working folder
|
||||
.ionide/
|
||||
|
||||
# Fody - auto-generated XML schema
|
||||
FodyWeavers.xsd
|
||||
# Stryker.NET
|
||||
StrykerOutput/
|
||||
@@ -1,9 +0,0 @@
|
||||
[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
|
||||
@@ -0,0 +1,23 @@
|
||||
<!doctype html>
|
||||
<html lang="ja">
|
||||
<head>
|
||||
<meta charset="utf-8">
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1">
|
||||
<title>ページが見つかりません | 波動光学 for YMM4</title>
|
||||
<meta name="robots" content="noindex">
|
||||
<style>:root{color-scheme:light dark;--kinari:#fbfaf5;--shironeri:#f3f3f2;--haijiro:#e9e4d4;--shiraai:#c1e4e9;--karasuba:#180614;--sumi:#595857;--ai:#165e83;--konjou:#192f60;--kodaimurasaki:#895b8a;--ginnezumi:#afafb0;--yamabuki:#f8b500;--nureba:#000b00;--tetsuonando:#455765;--byakugun:#83ccd2;--fuji:#bbbcde;--outer:light-dark(var(--konjou),var(--nureba));--frame:light-dark(var(--ai),var(--nureba));--frametext:var(--kinari);--framelink:light-dark(var(--shiraai),var(--byakugun));--edge:light-dark(var(--ai),var(--sumi));--panel:light-dark(var(--kinari),var(--nureba));--text:light-dark(var(--karasuba),var(--kinari));--muted:light-dark(var(--sumi),var(--ginnezumi));--line:light-dark(var(--ginnezumi),var(--sumi));--bar:light-dark(var(--shironeri),var(--tetsuonando));--bartext:light-dark(var(--konjou),var(--kinari));--head:light-dark(var(--haijiro),var(--tetsuonando));--link:light-dark(var(--ai),var(--byakugun));--visited:light-dark(var(--kodaimurasaki),var(--fuji))}*{box-sizing:border-box}body{margin:0;background:var(--outer);color:var(--text);font:16px/1.85 Verdana,'Hiragino Kaku Gothic ProN','Hiragino Sans',Meiryo,'Noto Sans JP',sans-serif}a{color:var(--link)}a:visited{color:var(--visited)}.wrap{max-width:76rem;margin:0 auto;background:var(--frame);display:grid;grid-template-columns:14rem minmax(0,1fr);align-items:start}header{padding:1.2rem 1rem;color:var(--frametext)}.site{margin:0 0 1rem;font:400 1.3rem/1.5 Georgia,'Hiragino Mincho ProN','Yu Mincho',YuMincho,'Noto Serif JP',serif}.site a,.site a:visited{color:var(--frametext);text-decoration:none}header ul{list-style:none;margin:0;padding:0}header li{padding:.15rem 0}header a,header a:visited{color:var(--framelink)}header b{color:var(--frametext)}.dl{margin:1.2rem 0 0}main{min-width:0;background:var(--panel);border:1px solid var(--edge);padding:1.2rem 2rem 2rem}h1,h2,h3{font-family:Georgia,'Hiragino Mincho ProN','Yu Mincho',YuMincho,'Noto Serif JP',serif;background:var(--bar);color:var(--bartext);border-bottom:1px solid var(--line);margin:1.8rem -2rem .8rem;padding:.2rem 2rem;line-height:1.5}h1{margin-top:0;font-size:1.9rem}h2{font-size:1.5rem}h3{font-size:1.2rem}p,ul,ol{margin:.8rem 0}img{max-width:100%;height:auto}figure{margin:1.2rem 0}figcaption{font-size:.9em;color:var(--muted)}table{border-collapse:collapse}caption{padding-bottom:.3rem;text-align:left;font-size:.9em;color:var(--muted)}th,td{border:1px solid var(--line);padding:.3rem .7rem;text-align:left;vertical-align:top}th{background:var(--head)}.t{overflow-x:auto;margin:1rem 0}.n{text-align:right}.k{white-space:nowrap}code{background:var(--bar);font-family:Consolas,'Courier New',monospace;font-size:.95em}.g{display:flex;flex-wrap:wrap;justify-content:center;gap:1rem;margin:1.2rem 0}.g figure{margin:0;flex:1 1 13rem;max-width:24rem;text-align:center}.g figure:has(.p){max-width:17.5rem}.g img{width:100%}.g.w figure{flex:0 1 calc(50% - .5rem);max-width:none}blockquote{margin:1rem 0;padding:.4rem 1rem;background:var(--bar);border:1px solid var(--line)}.p{image-rendering:pixelated}footer{grid-column:2;padding:.8rem 1rem 1.2rem;font-size:.85em;color:var(--frametext)}footer p{margin:.2rem 0}footer a,footer a:visited{color:var(--framelink)}.c.j{position:relative;display:grid;grid-template-columns:minmax(0,1fr);margin:1.2rem 0;overflow:hidden}.c.j>*{grid-area:1/1;margin:0}.c.j img{width:100%}.c.j .b{clip-path:inset(0 calc(100% - var(--p,50%)) 0 0);z-index:1}.c.j figcaption{position:absolute;top:.4em;padding:0 .5em;background:var(--karasuba);color:var(--kinari);opacity:.85;font-size:.8em}.c.j .b figcaption{left:.4em}.c.j .a figcaption{right:.4em}.c.j::after{content:'';grid-area:1/1;z-index:1;justify-self:start;width:2px;margin-left:calc(var(--p,50%) - 1px);background:var(--yamabuki);pointer-events:none}.c.j input{z-index:2;width:100%;height:100%;opacity:0;cursor:ew-resize}@media(min-width:52rem){caption{white-space:nowrap}main p,main li{text-align:justify}}@media(max-width:52rem){.wrap{display:block}header{padding:.8rem 1rem}header li{display:inline-block;margin-right:1rem}.dl{margin-top:.5rem}.g figure{flex-basis:9.5rem}.g figure:has(.p){flex-basis:15rem}.t table:has(th:nth-child(3)){min-width:28rem}.t table:has(th:nth-child(4)){min-width:40rem}th,td{padding:.25rem .5rem}main{border-left:0;border-right:0;padding:1rem}h1,h2,h3{margin-left:-1rem;margin-right:-1rem;padding-left:1rem;padding-right:1rem}h1{font-size:1.5rem}h2{font-size:1.25rem}h3{font-size:1.1rem}footer{padding:.8rem 1rem 1.2rem}}@media(max-width:30rem){.g.w figure{flex-basis:100%}}</style>
|
||||
</head>
|
||||
<body>
|
||||
<div class="wrap">
|
||||
<header>
|
||||
<p class="site"><a href="https://ymm4.routersys.com/YMM4-WaveOptics/index.html">波動光学 for YMM4</a></p>
|
||||
<nav aria-label="主要なページ"><ul><li><a href="https://ymm4.routersys.com/YMM4-WaveOptics/index.html">ホーム</a></li><li><a href="https://ymm4.routersys.com/YMM4-WaveOptics/how-it-works.html">しくみ</a></li><li><a href="https://ymm4.routersys.com/YMM4-WaveOptics/recipes.html">作例</a></li><li><a href="https://ymm4.routersys.com/YMM4-WaveOptics/guide.html">設定の選び方</a></li><li><a href="https://ymm4.routersys.com/YMM4-WaveOptics/faq.html">よくある質問</a></li><li><a href="https://ymm4.routersys.com/YMM4-WaveOptics/trust.html">確かめ方</a></li><li><a href="https://ymm4.routersys.com/YMM4-WaveOptics/changelog.html">更新履歴</a></li></ul></nav>
|
||||
<p class="dl"><a href="https://github.com/routersys/YMM4-WaveOptics/releases/latest">最新版をダウンロード</a></p>
|
||||
</header>
|
||||
<main>
|
||||
<h1>ページが見つかりません</h1>
|
||||
<p>アドレスが違うか、ページが移動した可能性があります。左の一覧から、見たいページを選んでください。</p>
|
||||
</main>
|
||||
</div>
|
||||
</body>
|
||||
</html>
|
||||
@@ -1,81 +0,0 @@
|
||||
# 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
@@ -1,168 +0,0 @@
|
||||
# 貢献の手引き
|
||||
|
||||
本プラグインへの貢献に関心を持っていただき、ありがとうございます。この手引きは、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,5 +0,0 @@
|
||||
<Project>
|
||||
<PropertyGroup>
|
||||
<YMM4DirPath>C:\Program Files\YukkuriMovieMaker_v4_Lite_Dev\</YMM4DirPath>
|
||||
</PropertyGroup>
|
||||
</Project>
|
||||
-21
@@ -1,21 +0,0 @@
|
||||
MIT License
|
||||
|
||||
Copyright (c) 2026 routersys
|
||||
|
||||
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.
|
||||
@@ -1,295 +0,0 @@
|
||||
# 波動光学 for YMM4
|
||||
|
||||
[](#)
|
||||
[](#)
|
||||
[](https://github.com/routersys/YMM4-WaveOptics/releases)
|
||||
|
||||
---
|
||||
|
||||
YukkuriMovieMaker4(YMM4)上で動作する、素材を回折も収差もない理想の像とみなし、レンズの開口と波面収差から求めた点像分布関数で畳み込んで、回折と収差によるにじみを描画する映像エフェクトプラグインです。
|
||||
点像分布関数は、瞳関数のフラウンホーファー回折を高速フーリエ変換で解いて求めます。
|
||||
履歴フレーム、参照画像、学習済みモデルを使わず、入力された一枚の映像だけを処理します。
|
||||
にじみの形は光学系と収差の設定から決定論的に決まり、同じ設定では常に同じ形になります。
|
||||
適用量、利得、波長、F値、画素ピッチ、開口回転、中央遮蔽、デフォーカス、縦横非点収差、斜め非点収差、水平コマ収差、垂直コマ収差、球面収差の13項目はアニメーションに対応しています。
|
||||
|
||||
---
|
||||
|
||||
## 目次
|
||||
|
||||
1. [概要](#概要)
|
||||
2. [動作要件](#動作要件)
|
||||
3. [インストール方法](#インストール方法)
|
||||
4. [主な機能](#主な機能)
|
||||
- [1. 点像分布関数の計算](#1-点像分布関数の計算)
|
||||
- [2. 光学系の項目とにじみの大きさ](#2-光学系の項目とにじみの大きさ)
|
||||
- [3. 開口の形と中央遮蔽](#3-開口の形と中央遮蔽)
|
||||
- [4. ゼルニケ多項式による波面収差](#4-ゼルニケ多項式による波面収差)
|
||||
- [5. 分離可能な畳み込み](#5-分離可能な畳み込み)
|
||||
- [6. 利得と適用量](#6-利得と適用量)
|
||||
- [7. 品質の選択](#7-品質の選択)
|
||||
5. [パラメータ一覧](#パラメータ一覧)
|
||||
- [出力グループ](#出力グループ)
|
||||
- [光学系グループ](#光学系グループ)
|
||||
- [開口グループ](#開口グループ)
|
||||
- [波面収差グループ](#波面収差グループ)
|
||||
6. [制限事項](#制限事項)
|
||||
7. [注意事項](#注意事項)
|
||||
8. [不具合の報告](#不具合の報告)
|
||||
9. [免責事項](#免責事項)
|
||||
10. [サードパーティライセンス](#サードパーティライセンス)
|
||||
11. [ライセンス](#ライセンス)
|
||||
|
||||
---
|
||||
|
||||
## 概要
|
||||
|
||||
本プラグインはYMM4の映像エフェクトとして動作し、エフェクトの種類一覧では「波動光学」として表示されます。カテゴリは加工です。
|
||||
|
||||
レンズで撮った写真では、1点から出た光が1点に写らず、わずかに広がって写ります。この広がり方を表す関数を、点像分布関数と呼びます。光が広がる原因の1つは回折です。回折は、光が開口の縁を回り込んで広がる現象で、開口はレンズの中で光が通る穴です。もう1つの原因は波面収差です。光の波の山をつないだ面を波面と呼び、波面が理想の形からずれることを波面収差と呼びます。本プラグインは、素材の各画素の光を点像分布関数の形に広げて足し合わせます。この計算を畳み込みと呼びます。
|
||||
|
||||
畳み込んだ結果は、「利得」を掛けてから、「適用量」の割合で入力映像と混ぜ合わせて出力します。
|
||||
|
||||
畳み込みの計算はComputeWeaveの計算シェーダーがDirect3D 12で実行します。点像分布関数と畳み込みの重みは、CPUで求めます。YMM4のDirect3D 11側とComputeWeaveのDirect3D 12側は、素材と畳み込んだ結果を共有テクスチャと共有フェンスで受け渡します。通常のフレーム処理では、CPUへの画素の読み戻しを行わず、7個の整数だけを読み戻します。7個の整数は、素材の色と不透明度から作る2個のハッシュと、透明でない画素の数と、外接矩形の位置を表す4個の値です。外接矩形は、透明でない画素をすべて囲む最小の矩形です。ハッシュは素材が変わったかどうかの判定に、外接矩形は畳み込む範囲を決めるのに使います。畳み込む範囲は、外接矩形を「カーネル半径」の画素数だけ広げ、外側へ4画素単位にそろえた範囲です。「カーネル半径」は、にじみが上下左右に届く画素数の上限です。
|
||||
|
||||
素材が変わらず、「利得」と「適用量」以外の項目も変わらないフレームでは、畳み込みの計算を再利用します。
|
||||
|
||||
このエフェクトはAviUtl向けのEXO出力には対応していません。
|
||||
|
||||
---
|
||||
|
||||
## 動作要件
|
||||
|
||||
| 項目 | 要件 |
|
||||
|---|---|
|
||||
| OS | Windows 10 バージョン2004(ビルド19041)以降 / Windows 11(64bit) |
|
||||
| YukkuriMovieMaker4 | 最新版を推奨 |
|
||||
| ランタイム | .NET 10.0 |
|
||||
| GPU | Direct3D 12とDirect3D 11・12間の共有テクスチャおよび共有フェンスを利用できるGPU |
|
||||
|
||||
---
|
||||
|
||||
## インストール方法
|
||||
|
||||
1. [Releases](https://github.com/routersys/YMM4-WaveOptics/releases/latest)ページから最新のプラグインファイル(`.ymme`)をダウンロードしてください。
|
||||
2. YMM4が起動していないことを確認し、ダウンロードしたファイルを実行してインストールします。
|
||||
3. YMM4を起動し、タイムライン上のアイテムに映像エフェクトを追加します。
|
||||
4. 映像エフェクトの種類として「波動光学」を選択してください。
|
||||
|
||||
---
|
||||
|
||||
## 主な機能
|
||||
|
||||
### 1. 点像分布関数の計算
|
||||
|
||||
点像分布関数は、瞳関数から求めます。瞳関数は、開口の各点を通る光の振幅と位相を表す関数です。振幅は波の揺れの大きさ、位相は波の進み具合です。開口の内側では振幅を1、外側では0とし、位相には波面収差を与えます。瞳関数の高速フーリエ変換を求め、その絶対値の2乗を点像分布関数とします。開口から十分に遠い面や、レンズの焦点面で見る回折を、フラウンホーファー回折と呼びます。この計算は、フラウンホーファー回折の式に当たります。
|
||||
|
||||
畳み込みの重みは、点像分布関数から値を取り出して作ります。取り出すのは、中心から上下左右に「カーネル半径」の画素数までの正方形の範囲です。重みをこの正方形に並べたものを、カーネルと呼びます。カーネルの各画素の値は、画素の中心の位置で点像分布関数を補間した値で、画素の面積にわたる平均ではありません。カーネルの値の和は1になるように正規化します。カーネルの外に届く光は捨てるため、正規化によってカーネルの値がその分だけ大きくなります。
|
||||
|
||||
点像分布関数とカーネルは、「利得」と「適用量」以外のどれかの項目が変わったフレームでだけ、CPUで作り直します。
|
||||
|
||||
### 2. 光学系の項目とにじみの大きさ
|
||||
|
||||
円形の開口で収差がないときの点像分布関数は、エアリーパターンと呼ばれる、明るい円盤と周りの薄い輪の形になります。明るい円盤の半径は、波長とF値の積の1.22倍です。デフォルトの波長550nm、F値8、画素ピッチ4μmでは、明るい円盤の半径は約5.4μmで、約1.3画素です。そのため、デフォルトの設定では、映像はわずかにやわらぐだけです。にじみを大きくするには、F値か波長を上げるか、画素ピッチを下げます。
|
||||
|
||||
「波長」は、単色光として計算する光の波長です。長いほど回折による広がりが大きくなります。赤、緑、青の成分と不透明度は同じ点像分布関数で畳み込むので、波長を変えても映像の色は変わりません。
|
||||
|
||||
「F値」は、開口の直径に対する焦点距離の比です。大きいほど開口が小さくなり、回折による広がりが大きくなります。
|
||||
|
||||
「画素ピッチ」は、撮像面での1画素の間隔です。小さいほど、同じ広がりが多くの画素にまたがります。にじみの大きさは素材の画素を単位に決まるため、画素数の多い素材ほど、映像の全体に対するにじみは小さく見えます。
|
||||
|
||||
「カーネル半径」は、カーネルの正方形が中心から上下左右に何画素まで広がるかを決めます。設定できるのは1〜63画素で、デフォルトは15画素です。点像分布関数がカーネルの正方形の外まで広がる設定では、外側の輪やにじみが切り取られます。デフォルトの光学系でデフォーカスを1 wavesにすると、にじみは中心から約15画素まで広がります。デフォーカスを大きくするときは、カーネル半径を上げてください。点像分布関数を求める範囲より外のカーネルの画素は0になるので、範囲を広げるには品質も上げてください。範囲は「品質の選択」にあります。カーネル半径と品質を上げるほど、計算は重くなります。
|
||||
|
||||
### 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. 分離可能な畳み込み
|
||||
|
||||
本プラグインは、カーネルを何組かの和で近似して畳み込みます。1組は、横方向の1次元の重みと縦方向の1次元の重みの対です。組ごとに横と縦の1次元の畳み込みを行い、足し合わせます。カーネルは一辺が「カーネル半径」の2倍に1を足した画素数の正方形で、カーネル半径が15画素なら31×31画素です。この大きさの畳み込みをそのまま計算すると、1画素ごとに961回の掛け算が要ります。1組の畳み込みは、1画素ごとに横31回と縦31回の掛け算で済むので、組の数が15以下なら掛け算は961回より少なくなります。
|
||||
|
||||
組は特異値分解で求めます。特異値分解は、行列を縦と横の重みの組の和に分け、寄与の大きい順に並べる計算です。組の和と元のカーネルとの差の値の2乗の和が、カーネル全体の値の2乗の和の0.01%以下になるまで組を増やします。組の数の上限は、カーネルの一辺の画素数です。組の和は元のカーネルとわずかに違うため、その値の和も1から少しずれます。そこで、組の和をその値の和で割り、値の和を1にそろえます。そのため、利得が100%のときの畳み込みは、画素の値の総和を保ちます。
|
||||
|
||||
組の数は点像分布関数の形で決まります。カーネル半径15画素、品質「標準」で23通りの設定を測りました。組の数は、収差がないときは1〜6組、収差を入れると5〜16組でした。組が増えるほど、畳み込みの計算は重くなります。
|
||||
|
||||
計算時間は、試験用に作った1920×1080の画像を使い、Intel Iris Xe Graphicsで測りました。素材が変わって畳み込みを計算し直すフレームの時間は、次のとおりでした。
|
||||
|
||||
| カーネル半径 | 品質 | 収差 | 組の数 | 時間 |
|
||||
|---:|---|---|---:|---:|
|
||||
| 15画素 | 標準 | なし | 3 | 約11ミリ秒 |
|
||||
| 15画素 | 標準 | デフォーカス1 waves | 11 | 約34ミリ秒 |
|
||||
| 15画素 | 標準 | 水平コマ収差1 waves | 16 | 約57ミリ秒 |
|
||||
| 63画素 | 高精度 | デフォーカス2 waves | 19 | 約190ミリ秒 |
|
||||
| 63画素 | 高精度 | 水平コマ収差2 waves | 35 | 約360ミリ秒 |
|
||||
|
||||
素材と設定が変わらず、畳み込みを再利用するフレームでは約1ミリ秒でした。
|
||||
|
||||
### 6. 利得と適用量
|
||||
|
||||
「利得」は、畳み込んだ結果に掛ける倍率です。100%で画素の値の総和を保ち、上げるほど明るく、下げるほど暗くなります。利得を掛けた結果は、色と不透明度の各成分が表せる最大の値で打ち切り、さらに色の成分が不透明度を超えないように抑えます。
|
||||
|
||||
「適用量」は、入力映像と、利得を掛けた結果を混ぜる割合です。0%では入力を変更せず、100%では利得を掛けた結果だけを出力します。
|
||||
|
||||
### 7. 品質の選択
|
||||
|
||||
「品質」は、瞳関数を置く格子の大きさを切り替えます。格子は瞳関数の値を縦横に並べた表で、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です。波面収差を大きくするときは、品質を上げてください。
|
||||
|
||||
品質を上げると、点像分布関数の計算が重くなります。「利得」と「適用量」以外の項目をアニメーションで変えるときは、フレームごとに点像分布関数を計算し直すので、品質を下げると処理が軽くなります。
|
||||
|
||||
---
|
||||
|
||||
## パラメータ一覧
|
||||
|
||||
### 出力グループ
|
||||
|
||||
| パラメータ名 | 型 | デフォルト | スライダー表示範囲 | アニメーション | 説明 |
|
||||
|---|---|---|---|---|---|
|
||||
| 適用量 | 数値 | 100% | 0〜100% | 対応 | 入力映像と、利得を掛けた結果を混ぜる割合です。0%では入力を変更しません。 |
|
||||
| 利得 | 数値 | 100% | 0〜400% | 対応 | 畳み込んだ結果に掛ける倍率です。100%で画素の値の総和を保ちます。 |
|
||||
|
||||
### 光学系グループ
|
||||
|
||||
| パラメータ名 | 型 | デフォルト | スライダー表示範囲 | アニメーション | 説明 |
|
||||
|---|---|---|---|---|---|
|
||||
| 波長 | 数値 | 550nm | 380〜780nm | 対応 | 単色光として計算する真空中の波長です。 |
|
||||
| F値 | 数値 | 8 | 0.5〜32 | 対応 | 開口の直径に対する焦点距離の比です。直接入力では64まで指定できます。 |
|
||||
| 画素ピッチ | 数値 | 4μm | 0.5〜20μm | 対応 | 撮像面での1画素の間隔です。直接入力では0.25〜100μmを指定できます。 |
|
||||
| カーネル半径 | 整数 | 15px | 1〜63px | 非対応 | カーネルが中心から上下左右に広がる画素数です。カーネルの外に届く光は捨てます。 |
|
||||
| 品質 | 列挙 | 標準 | 高速 / 標準 / 高精度 | 非対応 | 瞳関数を置く格子の大きさを選択します。 |
|
||||
|
||||
### 開口グループ
|
||||
|
||||
| パラメータ名 | 型 | デフォルト | スライダー表示範囲 | アニメーション | 説明 |
|
||||
|---|---|---|---|---|---|
|
||||
| 開口形状 | 列挙 | 円形 | 円形 / 正多角形 | 非対応 | 開口の外周の形です。 |
|
||||
| 羽根枚数 | 整数 | 6 | 3〜16 | 非対応 | 正多角形の開口の辺の数です。直接入力では32まで指定できます。 |
|
||||
| 開口回転 | 数値 | 0° | -180〜180° | 対応 | 正多角形の開口の回転角です。直接入力では-360〜360°を指定できます。 |
|
||||
| 中央遮蔽 | 数値 | 0% | 0〜95% | 対応 | 開口の中央をふさぐ円の半径で、開口の半径に対する割合です。 |
|
||||
|
||||
### 波面収差グループ
|
||||
|
||||
| パラメータ名 | 型 | デフォルト | スライダー表示範囲 | アニメーション | 説明 |
|
||||
|---|---|---|---|---|---|
|
||||
| デフォーカス | 数値 | 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まで指定できます。
|
||||
|
||||
---
|
||||
|
||||
## 制限事項
|
||||
|
||||
- AviUtl向けのEXO出力には対応していません。
|
||||
- Direct3D 12デバイスを取得できない場合と、YMM4が使うDirect3D 11デバイスが相互運用に必要なインターフェースを持たない場合は、エフェクトを適用せず入力映像を表示します。GPUメモリが足りず共有テクスチャを確保できない場合も同じです。
|
||||
- 畳み込みには現在のフレームの色と不透明度だけを使用します。履歴フレーム、外部画像、学習済みモデルは使用しません。素材に透明でない画素が無いときは、エフェクトを適用せず入力映像を表示します。
|
||||
- 計算は単色のフラウンホーファー回折に限ります。白色光のように波長の混ざった光は扱いません。点像分布関数は画面のどこでも同じで、像の位置や素材の奥行きで変わるにじみは扱いません。
|
||||
- 畳み込みは、画素の値をそのまま重み付けして足し合わせます。画素の値を光の強さに比例する値へ直してから畳み込む処理はしません。
|
||||
- カーネル半径は1〜63画素です。
|
||||
- 中央遮蔽で開口をほとんどふさぎ、瞳関数の格子に光の通る標本が1つも無くなる設定では、エフェクトを適用せず入力映像を表示します。品質を上げると起きにくくなります。
|
||||
- 計算領域は、透明な部分も含む素材全体の矩形の上下左右に余白を加えた大きさで、長辺は8192画素が上限です。余白は、カーネル半径を4画素単位に切り上げた画素数で、16画素を下回りません。素材の長辺の上限は、8192画素から余白の2倍を引いた値です。カーネル半径が16画素以下なら8160画素、63画素なら8064画素になります。素材の長辺がこの上限を超える場合は、エフェクトを適用せず入力映像を表示します。
|
||||
- GPUメモリ使用量は、計算領域の大きさに応じて増えます。作業用のバッファーとして、計算領域の1画素につき32バイトをGPUに確保します。処理量は、素材全体の大きさと畳み込む範囲の大きさに応じて増えます。
|
||||
|
||||
---
|
||||
|
||||
## 注意事項
|
||||
|
||||
- 処理負荷: 収差を入れると、畳み込みに使う組の数が増えて計算が重くなります。カーネル半径を上げた場合は、1組あたりの畳み込みの計算量と、組を求める特異値分解の計算量が増えます。品質を上げた場合は、点像分布関数の計算量が増えます。畳み込みの時間の目安は「分離可能な畳み込み」にあります。
|
||||
- 品質と収差: 波面収差を大きくするときは、品質を上げてください。格子が粗いと点像分布関数の形が崩れます。崩れ方の目安は「品質の選択」にあります。
|
||||
- キャッシュ: 素材の大きさと色と不透明度が変わらず、「利得」と「適用量」以外の項目も変わらないフレームでは、畳み込みの計算を再利用します。利得だけを変えたフレームでは、再利用した畳み込みに利得を掛け直します。適用量だけを変えたフレームでは、混ぜる割合だけを変えます。動画や口パクのように素材の内容が変わるフレームと、「利得」と「適用量」以外の項目をアニメーションで変えたフレームでは、毎回計算し直すので処理が重くなります。素材が変わったかどうかを調べる計算は、再利用するフレームでも毎フレーム行います。
|
||||
- 適用量0%: 適用量が0%のときは入力を変更せず、畳み込みの計算も行いません。
|
||||
- 再現性: 計算は決定論的で、時間値や乱数を使用しません。同じGPUとドライバーでは、同じ素材と同じ設定から常に同じ結果になります。
|
||||
- 透明部分: 畳み込みは不透明度にも掛かるので、素材の縁の外にも半透明のにじみが広がります。出力の範囲は、素材の範囲と畳み込む範囲を合わせたものです。適用量が0%のときは、素材の範囲のままです。
|
||||
- 更新通知: エフェクトを最初に生成したときに、YMM4の実行中に一度だけ新しい正式版を確認します。更新情報を取得できない場合は通知せず、そのまま動作します。プレリリースは通知の対象に含めません。
|
||||
- 不具合の自動送信: 想定していない例外が起きたときは、その内容を開発者へ自動で送信します。内容は「不具合の報告」に書いています。
|
||||
- 本プラグインを使用する前に、YMM4のプロジェクトファイルのバックアップを作成することを推奨します。
|
||||
|
||||
---
|
||||
|
||||
## 不具合の報告
|
||||
|
||||
本プラグインは、想定していない例外が起きたときに、その内容を開発者へ自動で送信します。同意は求めず、常に送信します。
|
||||
|
||||
送信する情報は次のとおりです。
|
||||
|
||||
| 種類 | 内容 |
|
||||
|---|---|
|
||||
| 例外 | 型の完全名、メッセージ、スタックトレース |
|
||||
| 発生位置 | モジュール名、関数名、ファイル名、行番号 |
|
||||
| プラグイン | アセンブリ名、バージョン |
|
||||
| 実行環境 | OSの名前とバージョン、.NETのバージョン、CPUのアーキテクチャ、論理プロセッサ数 |
|
||||
| 識別子 | YMM4の起動ごとに決まるセッション識別子、報告ごとの識別子 |
|
||||
|
||||
メッセージとファイル名は、送信の前に置き換えを通します。置き換えるのは、Windowsのユーザー名、ユーザーフォルダー、AppDataのパス、マシン名、ドメイン名、メールアドレス、IPv4アドレスです。送信元のIPアドレスは受信側へ渡す手前で取り除いています。
|
||||
|
||||
映像の中身とプロジェクトの内容は送信しません。継続して個人を追跡する識別子も持ちません。セッション識別子はYMM4を起動し直すと別の値になります。
|
||||
|
||||
送信するのは想定していない例外だけです。YMM4が本プラグインのエフェクトを作るとき、フレームごとに更新するとき、入力をつなぎ直すとき、破棄するときと、Direct2Dがシェーダーの定数を書き込むときに起きた例外を報告し、その後はYMM4へそのまま渡します。更新の確認では、更新情報の取得と比較で起きた例外は報告しません。通知の文を組み立てて表示するときに起きた例外は報告し、YMM4へは渡しません。画面の操作やバックグラウンドの処理で未処理になった例外も報告しますが、本プラグインのコードが関わる例外に限ります。本プラグインの外で起きた例外は送信しません。
|
||||
|
||||
次の失敗は送信しません。
|
||||
|
||||
| 種類 | 例 |
|
||||
|---|---|
|
||||
| 効果をかけないだけで済ませるもの | Direct3D 12デバイスを取得できない、YMM4のDirect3D 11デバイスが相互運用に必要なインターフェースを持たない、GPUメモリが足りず共有テクスチャを確保できない、計算領域が8192画素に収まらない、開口に光の通る標本が無いときに、エフェクトを適用せず入力映像を表示したとき |
|
||||
| 更新の確認の通信の失敗 | manjubox.netとGitHubのどちらへも接続できない |
|
||||
|
||||
送信できなかった報告はYMM4のユーザーフォルダーへ退避します。次にYMM4を起動したあと、本プラグインのエフェクトを生成するか、同じくYMM4-Telemetryで報告する別のプラグインが動き始めると、退避した報告を1回の起動で10件まで送り直します。送信も再送も非同期に行うため、通信を待って起動と描画が遅くなることはありません。
|
||||
|
||||
実装は [YMM4-Telemetry](https://github.com/routersys/YMM4-Telemetry) をサブモジュールとして取り込んでいます。
|
||||
|
||||
---
|
||||
|
||||
## 免責事項
|
||||
|
||||
本プラグインは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 |
|
||||
|
||||
---
|
||||
|
||||
## ライセンス
|
||||
|
||||
[MIT License](LICENSE.txt)
|
||||
-46
@@ -1,46 +0,0 @@
|
||||
# セキュリティポリシー
|
||||
|
||||
## サポートするバージョン
|
||||
|
||||
セキュリティの修正は、最新のリリースだけを対象にします。
|
||||
|
||||
| バージョン | サポート |
|
||||
|---|---|
|
||||
| 最新のリリース | 対象 |
|
||||
| それより前のリリース | 対象外 |
|
||||
|
||||
修正は、最新のリリースの次のバージョンとして公開します。報告する前に、最新のリリースでも問題が起きるかを確かめてください。
|
||||
|
||||
## 対象とする問題
|
||||
|
||||
本プラグインのコードと配布パッケージに原因がある問題を対象にします。たとえば次のようなものです。
|
||||
|
||||
- 細工したプロジェクトファイルや素材を開くと、意図しない処理が実行される
|
||||
- 更新の確認などで行う通信の内容を、第三者が書き換えられる
|
||||
- 不具合の情報を自動で送信するプラグインで、個人を特定できる情報が伏せられないまま送信される
|
||||
|
||||
配布パッケージに同梱したライブラリの脆弱性は、本プラグインを通じて悪用できる場合に対象にします。
|
||||
|
||||
YukkuriMovieMaker4 本体や、ほかのプラグインに原因がある問題は対象外です。それぞれの開発者へ報告してください。
|
||||
|
||||
## 報告の方法
|
||||
|
||||
脆弱性は、公開の Issue に書かないでください。修正を公開する前に悪用されるおそれがあります。
|
||||
|
||||
1. リポジトリの URL の末尾に `/security` を付けたページを開き、「Report a vulnerability」から非公開で報告してください。報告の内容を見られるのは、開発者と報告した人、開発者が招いた人だけです。
|
||||
2. この方法が使えないときは、github.routersys@gmail.com へメールで報告してください。
|
||||
|
||||
報告には、次の内容を書いてください。分からない項目は書かなくて構いません。
|
||||
|
||||
| 項目 | 内容 |
|
||||
|---|---|
|
||||
| バージョン | 問題を確かめたプラグインのバージョンと、YukkuriMovieMaker4 のバージョン |
|
||||
| 再現の手順 | 問題を起こす操作と、使ったプロジェクトファイルや素材 |
|
||||
| 影響 | 問題によって何ができてしまうか |
|
||||
| 回避策 | 分かっていれば、修正までの間に被害を避ける方法 |
|
||||
|
||||
## 報告の後
|
||||
|
||||
開発者は、報告を受け取ったら内容を確かめ、修正の見込みを返信します。
|
||||
|
||||
報告した人は、修正を含むバージョンが出るまで、報告の内容を明かさないでください。問題の詳細は、修正版の公開後に開発者が公表します。
|
||||
@@ -1,7 +0,0 @@
|
||||
namespace WaveOptics.Abstractions;
|
||||
|
||||
public enum ApertureShape
|
||||
{
|
||||
Circular,
|
||||
RegularPolygon,
|
||||
}
|
||||
@@ -1,8 +0,0 @@
|
||||
namespace WaveOptics.Abstractions;
|
||||
|
||||
public interface IPsfGenerator
|
||||
{
|
||||
OpticalApiVersion ApiVersion { get; }
|
||||
OpticalCapabilities Capabilities { get; }
|
||||
PsfGenerationResult Generate(PsfDescriptor descriptor);
|
||||
}
|
||||
@@ -1,6 +0,0 @@
|
||||
namespace WaveOptics.Abstractions;
|
||||
|
||||
public readonly record struct OpticalApiVersion(int Major, int Minor)
|
||||
{
|
||||
public static OpticalApiVersion Current { get; } = new(1, 0);
|
||||
}
|
||||
@@ -1,13 +0,0 @@
|
||||
namespace WaveOptics.Abstractions;
|
||||
|
||||
[Flags]
|
||||
public enum OpticalCapabilities
|
||||
{
|
||||
None = 0,
|
||||
MonochromaticPsf = 1,
|
||||
CircularAperture = 2,
|
||||
RegularPolygonAperture = 4,
|
||||
CentralObstruction = 8,
|
||||
ZernikeAberration = 16,
|
||||
DirectConvolution = 32,
|
||||
}
|
||||
@@ -1,96 +0,0 @@
|
||||
using System.Numerics;
|
||||
|
||||
namespace WaveOptics.Abstractions;
|
||||
|
||||
public sealed class PsfDescriptor : IEquatable<PsfDescriptor>
|
||||
{
|
||||
public int PupilGridSize { get; }
|
||||
public int PupilDiameterSamples { get; }
|
||||
public int KernelSize { get; }
|
||||
public double WavelengthNanometers { get; }
|
||||
public double FNumber { get; }
|
||||
public double SensorPixelPitchMicrometers { get; }
|
||||
public ApertureShape ApertureShape { get; }
|
||||
public int BladeCount { get; }
|
||||
public double BladeRotationDegrees { get; }
|
||||
public double CentralObstructionRatio { get; }
|
||||
public WavefrontAberration Aberration { get; }
|
||||
|
||||
public PsfDescriptor(
|
||||
int pupilGridSize,
|
||||
int pupilDiameterSamples,
|
||||
int kernelSize,
|
||||
double wavelengthNanometers,
|
||||
double fNumber,
|
||||
double sensorPixelPitchMicrometers,
|
||||
ApertureShape apertureShape,
|
||||
int bladeCount,
|
||||
double bladeRotationDegrees,
|
||||
double centralObstructionRatio,
|
||||
WavefrontAberration aberration)
|
||||
{
|
||||
ArgumentOutOfRangeException.ThrowIfLessThan(pupilGridSize, 64);
|
||||
ArgumentOutOfRangeException.ThrowIfGreaterThan(pupilGridSize, 2048);
|
||||
if (!BitOperations.IsPow2((uint)pupilGridSize))
|
||||
throw new ArgumentException(nameof(pupilGridSize));
|
||||
ArgumentOutOfRangeException.ThrowIfLessThan(pupilDiameterSamples, 16);
|
||||
ArgumentOutOfRangeException.ThrowIfGreaterThan(pupilDiameterSamples, pupilGridSize / 2);
|
||||
ArgumentOutOfRangeException.ThrowIfLessThan(kernelSize, 3);
|
||||
ArgumentOutOfRangeException.ThrowIfGreaterThan(kernelSize, 255);
|
||||
if ((kernelSize & 1) == 0)
|
||||
throw new ArgumentException(nameof(kernelSize));
|
||||
ValidateFiniteRange(wavelengthNanometers, 380, 780, nameof(wavelengthNanometers));
|
||||
ValidateFiniteRange(fNumber, 0.5, 64, nameof(fNumber));
|
||||
ValidateFiniteRange(sensorPixelPitchMicrometers, 0.25, 100, nameof(sensorPixelPitchMicrometers));
|
||||
if (!Enum.IsDefined(apertureShape))
|
||||
throw new ArgumentOutOfRangeException(nameof(apertureShape));
|
||||
ArgumentOutOfRangeException.ThrowIfLessThan(bladeCount, 3);
|
||||
ArgumentOutOfRangeException.ThrowIfGreaterThan(bladeCount, 32);
|
||||
ValidateFiniteRange(bladeRotationDegrees, -360, 360, nameof(bladeRotationDegrees));
|
||||
ValidateFiniteRange(centralObstructionRatio, 0, 0.95, nameof(centralObstructionRatio));
|
||||
|
||||
PupilGridSize = pupilGridSize;
|
||||
PupilDiameterSamples = pupilDiameterSamples;
|
||||
KernelSize = kernelSize;
|
||||
WavelengthNanometers = wavelengthNanometers;
|
||||
FNumber = fNumber;
|
||||
SensorPixelPitchMicrometers = sensorPixelPitchMicrometers;
|
||||
ApertureShape = apertureShape;
|
||||
BladeCount = bladeCount;
|
||||
BladeRotationDegrees = bladeRotationDegrees;
|
||||
CentralObstructionRatio = centralObstructionRatio;
|
||||
Aberration = aberration;
|
||||
}
|
||||
|
||||
static void ValidateFiniteRange(double value, double minimum, double maximum, string name)
|
||||
{
|
||||
ArgumentOutOfRangeException.ThrowIfNotEqual(double.IsFinite(value), true, name);
|
||||
ArgumentOutOfRangeException.ThrowIfLessThan(value, minimum, name);
|
||||
ArgumentOutOfRangeException.ThrowIfGreaterThan(value, maximum, name);
|
||||
}
|
||||
|
||||
public bool Equals(PsfDescriptor? other)
|
||||
{
|
||||
return other is not null
|
||||
&& PupilGridSize == other.PupilGridSize
|
||||
&& PupilDiameterSamples == other.PupilDiameterSamples
|
||||
&& KernelSize == other.KernelSize
|
||||
&& WavelengthNanometers.Equals(other.WavelengthNanometers)
|
||||
&& FNumber.Equals(other.FNumber)
|
||||
&& SensorPixelPitchMicrometers.Equals(other.SensorPixelPitchMicrometers)
|
||||
&& ApertureShape == other.ApertureShape
|
||||
&& BladeCount == other.BladeCount
|
||||
&& BladeRotationDegrees.Equals(other.BladeRotationDegrees)
|
||||
&& CentralObstructionRatio.Equals(other.CentralObstructionRatio)
|
||||
&& Aberration.Equals(other.Aberration);
|
||||
}
|
||||
|
||||
public override bool Equals(object? obj) => Equals(obj as PsfDescriptor);
|
||||
|
||||
public override int GetHashCode()
|
||||
{
|
||||
var first = HashCode.Combine(PupilGridSize, PupilDiameterSamples, KernelSize, WavelengthNanometers, FNumber, SensorPixelPitchMicrometers);
|
||||
var second = HashCode.Combine(ApertureShape, BladeCount, BladeRotationDegrees, CentralObstructionRatio, Aberration);
|
||||
return HashCode.Combine(first, second);
|
||||
}
|
||||
}
|
||||
@@ -1,7 +0,0 @@
|
||||
namespace WaveOptics.Abstractions;
|
||||
|
||||
public readonly record struct PsfDiagnostics(
|
||||
int OpenPupilSampleCount,
|
||||
double FocalPlaneSamplePitchMicrometers,
|
||||
double UnnormalizedKernelEnergy,
|
||||
double PeakIntensity);
|
||||
@@ -1,3 +0,0 @@
|
||||
namespace WaveOptics.Abstractions;
|
||||
|
||||
public sealed record PsfGenerationResult(PsfKernel Kernel, PsfDiagnostics Diagnostics);
|
||||
@@ -1,63 +0,0 @@
|
||||
namespace WaveOptics.Abstractions;
|
||||
|
||||
public sealed class PsfKernel
|
||||
{
|
||||
readonly double[] values;
|
||||
|
||||
public int Size { get; }
|
||||
public ReadOnlyMemory<double> Values => values;
|
||||
|
||||
public double this[int x, int y]
|
||||
{
|
||||
get
|
||||
{
|
||||
ArgumentOutOfRangeException.ThrowIfNegative(x);
|
||||
ArgumentOutOfRangeException.ThrowIfGreaterThanOrEqual(x, Size);
|
||||
ArgumentOutOfRangeException.ThrowIfNegative(y);
|
||||
ArgumentOutOfRangeException.ThrowIfGreaterThanOrEqual(y, Size);
|
||||
return values[y * Size + x];
|
||||
}
|
||||
}
|
||||
|
||||
public PsfKernel(int size, ReadOnlySpan<double> values)
|
||||
{
|
||||
ArgumentOutOfRangeException.ThrowIfLessThan(size, 1);
|
||||
if ((size & 1) == 0)
|
||||
throw new ArgumentException(nameof(size));
|
||||
if (values.Length != size * size)
|
||||
throw new ArgumentException(nameof(values));
|
||||
|
||||
this.values = values.ToArray();
|
||||
for (var index = 0; index < this.values.Length; index++)
|
||||
{
|
||||
var value = this.values[index];
|
||||
if (!double.IsFinite(value) || value < 0)
|
||||
throw new ArgumentOutOfRangeException(nameof(values));
|
||||
}
|
||||
|
||||
var sum = this.values.Sum();
|
||||
if (!double.IsFinite(sum) || sum <= 0)
|
||||
throw new ArgumentOutOfRangeException(nameof(values));
|
||||
|
||||
for (var index = 0; index < this.values.Length; index++)
|
||||
this.values[index] /= sum;
|
||||
|
||||
Size = size;
|
||||
}
|
||||
|
||||
public double Sum()
|
||||
{
|
||||
var sum = 0d;
|
||||
var compensation = 0d;
|
||||
foreach (var value in values)
|
||||
{
|
||||
var corrected = value - compensation;
|
||||
var next = sum + corrected;
|
||||
compensation = next - sum - corrected;
|
||||
sum = next;
|
||||
}
|
||||
return sum;
|
||||
}
|
||||
|
||||
public double[] ToArray() => (double[])values.Clone();
|
||||
}
|
||||
@@ -1,12 +0,0 @@
|
||||
<Project Sdk="Microsoft.NET.Sdk">
|
||||
|
||||
<PropertyGroup>
|
||||
<TargetFramework>net10.0</TargetFramework>
|
||||
<ImplicitUsings>enable</ImplicitUsings>
|
||||
<Nullable>enable</Nullable>
|
||||
<AssemblyName>WaveOptics.Abstractions</AssemblyName>
|
||||
<RootNamespace>WaveOptics.Abstractions</RootNamespace>
|
||||
<Version>1.0.0</Version>
|
||||
</PropertyGroup>
|
||||
|
||||
</Project>
|
||||
@@ -1,65 +0,0 @@
|
||||
namespace WaveOptics.Abstractions;
|
||||
|
||||
public readonly struct WavefrontAberration : IEquatable<WavefrontAberration>
|
||||
{
|
||||
public double DefocusWaves { get; }
|
||||
public double AstigmatismVerticalWaves { get; }
|
||||
public double AstigmatismObliqueWaves { get; }
|
||||
public double ComaHorizontalWaves { get; }
|
||||
public double ComaVerticalWaves { get; }
|
||||
public double TrefoilHorizontalWaves { get; }
|
||||
public double TrefoilVerticalWaves { get; }
|
||||
public double SphericalWaves { get; }
|
||||
|
||||
public WavefrontAberration(
|
||||
double defocusWaves = 0,
|
||||
double astigmatismVerticalWaves = 0,
|
||||
double astigmatismObliqueWaves = 0,
|
||||
double comaHorizontalWaves = 0,
|
||||
double comaVerticalWaves = 0,
|
||||
double trefoilHorizontalWaves = 0,
|
||||
double trefoilVerticalWaves = 0,
|
||||
double sphericalWaves = 0)
|
||||
{
|
||||
DefocusWaves = Validate(defocusWaves, nameof(defocusWaves));
|
||||
AstigmatismVerticalWaves = Validate(astigmatismVerticalWaves, nameof(astigmatismVerticalWaves));
|
||||
AstigmatismObliqueWaves = Validate(astigmatismObliqueWaves, nameof(astigmatismObliqueWaves));
|
||||
ComaHorizontalWaves = Validate(comaHorizontalWaves, nameof(comaHorizontalWaves));
|
||||
ComaVerticalWaves = Validate(comaVerticalWaves, nameof(comaVerticalWaves));
|
||||
TrefoilHorizontalWaves = Validate(trefoilHorizontalWaves, nameof(trefoilHorizontalWaves));
|
||||
TrefoilVerticalWaves = Validate(trefoilVerticalWaves, nameof(trefoilVerticalWaves));
|
||||
SphericalWaves = Validate(sphericalWaves, nameof(sphericalWaves));
|
||||
}
|
||||
|
||||
static double Validate(double value, string name)
|
||||
{
|
||||
ArgumentOutOfRangeException.ThrowIfNotEqual(double.IsFinite(value), true, name);
|
||||
ArgumentOutOfRangeException.ThrowIfLessThan(value, -10, name);
|
||||
ArgumentOutOfRangeException.ThrowIfGreaterThan(value, 10, name);
|
||||
return value;
|
||||
}
|
||||
|
||||
public bool Equals(WavefrontAberration other)
|
||||
{
|
||||
return DefocusWaves.Equals(other.DefocusWaves)
|
||||
&& AstigmatismVerticalWaves.Equals(other.AstigmatismVerticalWaves)
|
||||
&& AstigmatismObliqueWaves.Equals(other.AstigmatismObliqueWaves)
|
||||
&& ComaHorizontalWaves.Equals(other.ComaHorizontalWaves)
|
||||
&& ComaVerticalWaves.Equals(other.ComaVerticalWaves)
|
||||
&& TrefoilHorizontalWaves.Equals(other.TrefoilHorizontalWaves)
|
||||
&& TrefoilVerticalWaves.Equals(other.TrefoilVerticalWaves)
|
||||
&& SphericalWaves.Equals(other.SphericalWaves);
|
||||
}
|
||||
|
||||
public override bool Equals(object? obj) => obj is WavefrontAberration other && Equals(other);
|
||||
|
||||
public override int GetHashCode()
|
||||
{
|
||||
var first = HashCode.Combine(DefocusWaves, AstigmatismVerticalWaves, AstigmatismObliqueWaves, ComaHorizontalWaves);
|
||||
var second = HashCode.Combine(ComaVerticalWaves, TrefoilHorizontalWaves, TrefoilVerticalWaves, SphericalWaves);
|
||||
return HashCode.Combine(first, second);
|
||||
}
|
||||
|
||||
public static bool operator ==(WavefrontAberration left, WavefrontAberration right) => left.Equals(right);
|
||||
public static bool operator !=(WavefrontAberration left, WavefrontAberration right) => !left.Equals(right);
|
||||
}
|
||||
@@ -1,55 +0,0 @@
|
||||
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.json";
|
||||
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)
|
||||
=> Path.Combine(ReadDirectory(), image.Key is null ? FileName : $"golden-{image.Key}.json");
|
||||
|
||||
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} がありません。");
|
||||
}
|
||||
@@ -1,63 +0,0 @@
|
||||
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();
|
||||
}
|
||||
}
|
||||
@@ -1,93 +0,0 @@
|
||||
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)
|
||||
{
|
||||
public const string Usage = """
|
||||
使い方:
|
||||
[<出力先>] [--input <画像>] ケースを描き、PNG とハッシュを出します
|
||||
--golden [--input <画像>] 基準値を golden.json に書きます
|
||||
--verify [--input <画像>] 基準値と照合します
|
||||
--transition [<出力先>] [--input <画像>] 設定を変えた後とフレームを進めた後の描画を、作り直した描画と照合します
|
||||
--compare <前> <後> 2 つの出力先の PNG を画素ごとに比べます
|
||||
--benchmark [--input <画像>] 描画を計測します
|
||||
--convolution [--input <画像>] 畳み込みの計算し直しに掛かる時間を、変えた値ごとに計測します
|
||||
""";
|
||||
|
||||
public static HarnessArguments Parse(string[] arguments)
|
||||
{
|
||||
HarnessMode? mode = null;
|
||||
string? input = null;
|
||||
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 "--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;
|
||||
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]);
|
||||
case HarnessMode.Render:
|
||||
case HarnessMode.Transition:
|
||||
if (positionals.Count > 1)
|
||||
throw new HarnessException($"余分な引数です。{positionals[1]}");
|
||||
return new HarnessArguments(selected, input, positionals.FirstOrDefault(), null, null);
|
||||
default:
|
||||
if (positionals.Count > 0)
|
||||
throw new HarnessException($"余分な引数です。{positionals[0]}");
|
||||
return new HarnessArguments(selected, input, null, null, null);
|
||||
}
|
||||
}
|
||||
|
||||
static HarnessMode Select(HarnessMode? current, HarnessMode next)
|
||||
=> current is null ? next : throw new HarnessException("モードは 1 つだけ指定してください。");
|
||||
}
|
||||
@@ -1,123 +0,0 @@
|
||||
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());
|
||||
}
|
||||
|
||||
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);
|
||||
}
|
||||
|
||||
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;
|
||||
}
|
||||
}
|
||||
@@ -1,59 +0,0 @@
|
||||
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);
|
||||
}
|
||||
}
|
||||
@@ -1,262 +0,0 @@
|
||||
using System.Diagnostics;
|
||||
using System.Numerics;
|
||||
using System.Runtime.InteropServices;
|
||||
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)
|
||||
{
|
||||
CanvasWidth = canvasWidth;
|
||||
CanvasHeight = canvasHeight;
|
||||
|
||||
devices = new GraphicsDevices();
|
||||
context = devices.CreateContext();
|
||||
var deviceContext = context.DeviceContext;
|
||||
var adapter = devices.DXGI.Adapter;
|
||||
Adapter = adapter.Description.Description;
|
||||
Driver = adapter.CheckInterfaceSupport<IDXGIDevice>(out var version) ? FormatDriverVersion(version) : "不明";
|
||||
|
||||
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 byte[][] Render(IVideoEffect effect, IReadOnlyList<int> frames)
|
||||
{
|
||||
if (frames.Count == 0)
|
||||
throw new ArgumentException("フレームを 1 つ以上指定してください。", nameof(frames));
|
||||
|
||||
using var processor = effect.CreateVideoEffect(context);
|
||||
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();
|
||||
}
|
||||
}
|
||||
|
||||
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 = live.CreateVideoEffect(context);
|
||||
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 = effect.CreateVideoEffect(context);
|
||||
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);
|
||||
}
|
||||
@@ -1,37 +0,0 @@
|
||||
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;
|
||||
}
|
||||
@@ -1,46 +0,0 @@
|
||||
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);
|
||||
}
|
||||
}
|
||||
@@ -1,437 +0,0 @@
|
||||
using System.Diagnostics;
|
||||
using System.IO;
|
||||
using System.IO.Packaging;
|
||||
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));
|
||||
}
|
||||
else
|
||||
{
|
||||
Benchmark(HarnessImage.Synthetic(CanvasWidth, CanvasHeight));
|
||||
Benchmark(HarnessImage.Synthetic(FullHdWidth, FullHdHeight));
|
||||
}
|
||||
|
||||
return 0;
|
||||
}
|
||||
|
||||
var image = arguments.Input is { } input ? HarnessImage.Load(input) : HarnessImage.Synthetic(ImageWidth, ImageHeight);
|
||||
using var renderer = new HarnessRenderer(CanvasWidth, CanvasHeight, image);
|
||||
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);
|
||||
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));
|
||||
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;
|
||||
|
||||
using var pipeline = WaveOpticsPipeline.TryCreate();
|
||||
if (pipeline is null)
|
||||
throw new HarnessException("Direct3D 12を利用できません。");
|
||||
|
||||
var device = GraphicsDevice.GetDefault();
|
||||
using var original = device.AllocateReadWriteTexture2D<Bgra32, Float4>(image.Width, image.Height);
|
||||
using var mirrored = device.AllocateReadWriteTexture2D<Bgra32, Float4>(image.Width, image.Height);
|
||||
using var output = device.AllocateReadWriteTexture2D<Bgra32, Float4>(image.Width, image.Height);
|
||||
original.CopyFrom(ToPixels(image, false));
|
||||
mirrored.CopyFrom(ToPixels(image, true));
|
||||
|
||||
var parameters = new WaveOpticsPipeline.Parameters(1f, new WaveOpticsPipeline.PsfParameters(
|
||||
WaveOpticsQuality.Standard, 15, 550f, 8f, 4f, WaveOpticsApertureShape.Circular, 6, 0f, 0f, 0f, 0f, 0f, 0f, 0f, 0f));
|
||||
var variants = new (string Name, Func<bool, (ReadWriteTexture2D<Bgra32, Float4> Source, WaveOpticsPipeline.Parameters Parameters)> Make)[]
|
||||
{
|
||||
("cached", _ => (original, parameters)),
|
||||
("gain", flip => (original, parameters with { Gain = flip ? 1.5f : 1f })),
|
||||
("source", flip => (flip ? mirrored : original, parameters)),
|
||||
("defocus", flip => (original, parameters with { Psf = parameters.Psf with { Defocus = flip ? 0.1f : 0f } })),
|
||||
("quality-high", flip => (original, parameters with { Psf = parameters.Psf with { Quality = flip ? WaveOpticsQuality.High : WaveOpticsQuality.Standard } })),
|
||||
};
|
||||
|
||||
var renderedGain = float.NaN;
|
||||
void Frame(ReadWriteTexture2D<Bgra32, Float4> source, in WaveOpticsPipeline.Parameters frameParameters)
|
||||
{
|
||||
var changed = pipeline.Simulate(source, image.Width, image.Height, 0, 0, image.Width, image.Height, in frameParameters);
|
||||
if ((changed || renderedGain != frameParameters.Gain) && pipeline.TryGetVisibleBounds(image.Width, image.Height, in frameParameters, out var rect))
|
||||
{
|
||||
pipeline.RenderVisible(output, rect, in frameParameters);
|
||||
renderedGain = frameParameters.Gain;
|
||||
}
|
||||
pipeline.WaitForCompletion();
|
||||
}
|
||||
|
||||
var samples = new List<double>[variants.Length];
|
||||
for (var index = 0; index < samples.Length; index++)
|
||||
samples[index] = new List<double>(Rounds);
|
||||
|
||||
foreach (var (_, make) in variants)
|
||||
{
|
||||
var (warmupSource, warmupParameters) = make(true);
|
||||
Frame(warmupSource, in warmupParameters);
|
||||
}
|
||||
|
||||
var stopwatch = new Stopwatch();
|
||||
var order = Enumerable.Range(0, variants.Length).ToArray();
|
||||
var random = new Random(Seed);
|
||||
for (var round = 0; round < Rounds; round++)
|
||||
{
|
||||
for (var index = order.Length - 1; index > 0; index--)
|
||||
{
|
||||
var swap = random.Next(index + 1);
|
||||
(order[index], order[swap]) = (order[swap], order[index]);
|
||||
}
|
||||
|
||||
foreach (var index in order)
|
||||
{
|
||||
var (settledSource, settledParameters) = variants[index].Make(false);
|
||||
Frame(settledSource, in settledParameters);
|
||||
|
||||
var (measuredSource, measuredParameters) = variants[index].Make(true);
|
||||
stopwatch.Restart();
|
||||
Frame(measuredSource, in measuredParameters);
|
||||
stopwatch.Stop();
|
||||
samples[index].Add(stopwatch.Elapsed.TotalMilliseconds);
|
||||
}
|
||||
}
|
||||
|
||||
Console.WriteLine($"convolution recompute at {image.Width}x{image.Height} over {Rounds} interleaved rounds (ms)");
|
||||
for (var index = 0; index < variants.Length; index++)
|
||||
{
|
||||
var sorted = samples[index].OrderBy(static value => value).ToArray();
|
||||
var median = sorted[sorted.Length / 2];
|
||||
Console.WriteLine($" {variants[index].Name,-12} min={sorted[0],7:F2} median={median,7:F2} max={sorted[^1],7:F2}");
|
||||
}
|
||||
|
||||
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)
|
||||
{
|
||||
const int Frames = 60;
|
||||
|
||||
using var renderer = new HarnessRenderer(image.Width, image.Height, image);
|
||||
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;
|
||||
}
|
||||
@@ -1,51 +0,0 @@
|
||||
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);
|
||||
}
|
||||
@@ -1,62 +0,0 @@
|
||||
<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>
|
||||
@@ -1,241 +0,0 @@
|
||||
{
|
||||
"adapter": "Intel(R) Iris(R) Xe Graphics",
|
||||
"driver": "32.0.101.7085",
|
||||
"input": "synthetic 640x480 89838D8976198E40",
|
||||
"canvas": "1280x720",
|
||||
"cases": [
|
||||
{
|
||||
"name": "default",
|
||||
"frames": [
|
||||
0
|
||||
],
|
||||
"hash": "9B93219016A028453BF7CCAB7FBC7E3658B363FC51850286BE23B7A388C368BF"
|
||||
},
|
||||
{
|
||||
"name": "default-frames-0-8",
|
||||
"frames": [
|
||||
0,
|
||||
1,
|
||||
2,
|
||||
3,
|
||||
4,
|
||||
5,
|
||||
6,
|
||||
7,
|
||||
8
|
||||
],
|
||||
"hash": "A77359A34F3A6C78E616953C1D66DF1CD05595E662E3DE38E68EB2FC81D11AE4"
|
||||
},
|
||||
{
|
||||
"name": "amount-0",
|
||||
"frames": [
|
||||
0
|
||||
],
|
||||
"hash": "0A700F76CEDDBAD7C4B6A2C19D46939C1A93940E86C6EFEF1E5A53DB48D2A020"
|
||||
},
|
||||
{
|
||||
"name": "amount-50",
|
||||
"frames": [
|
||||
0
|
||||
],
|
||||
"hash": "E854AFBFE739475EE665D3D4C672BEF9A631A1479E094E339B87D18C38BA50B0"
|
||||
},
|
||||
{
|
||||
"name": "gain-50",
|
||||
"frames": [
|
||||
0
|
||||
],
|
||||
"hash": "9032893550EE7D03B58762F9BD8BE6608929D45DA0BFD474E5AF410A1C4C3328"
|
||||
},
|
||||
{
|
||||
"name": "gain-400",
|
||||
"frames": [
|
||||
0
|
||||
],
|
||||
"hash": "95886976629306C5E0A2BB93208B5E627E3C78A9CFCD6263202248E0E363A2A7"
|
||||
},
|
||||
{
|
||||
"name": "gain-400-amount-50",
|
||||
"frames": [
|
||||
0
|
||||
],
|
||||
"hash": "C579D45C3F216492D6219DA8C5CDF1C9B2357B51AA1376C53A6CBE051C3F6F1A"
|
||||
},
|
||||
{
|
||||
"name": "wavelength-380",
|
||||
"frames": [
|
||||
0
|
||||
],
|
||||
"hash": "A5B889290FAB95A7BB5B00922B36B504AFA660DDF0F7E3EF3F4829D4E4AA8C75"
|
||||
},
|
||||
{
|
||||
"name": "wavelength-780",
|
||||
"frames": [
|
||||
0
|
||||
],
|
||||
"hash": "7F8CB99C84EEED6C7ADF4E138085B08A53C3454160EF08A135405F1018B4272D"
|
||||
},
|
||||
{
|
||||
"name": "f-number-4",
|
||||
"frames": [
|
||||
0
|
||||
],
|
||||
"hash": "9526105CC4F77E47D4174A86A7FB6E50A270CDBDCB5C59C14615A2751AB10AD7"
|
||||
},
|
||||
{
|
||||
"name": "f-number-64",
|
||||
"frames": [
|
||||
0
|
||||
],
|
||||
"hash": "28CD10EE5F789E7D99BBD48E2A2967636E33BF4A4A57253E8F62A0FCD4668733"
|
||||
},
|
||||
{
|
||||
"name": "pixel-pitch-0.25",
|
||||
"frames": [
|
||||
0
|
||||
],
|
||||
"hash": "0A35D27FBC8670D8C1F9E75581CE5AA7FC23466D5E64141D5E78AFF3631CB0BF"
|
||||
},
|
||||
{
|
||||
"name": "pixel-pitch-2",
|
||||
"frames": [
|
||||
0
|
||||
],
|
||||
"hash": "39B4E14378BAABB03A364D7824BC0C999E1C7D9FD292090A2A8995D6C0890D8E"
|
||||
},
|
||||
{
|
||||
"name": "kernel-radius-1",
|
||||
"frames": [
|
||||
0
|
||||
],
|
||||
"hash": "7873F5E5B2AC64FC73E65746900E0C249E6335A533DFD17E0FE97A4EFE9C36A2"
|
||||
},
|
||||
{
|
||||
"name": "kernel-radius-5",
|
||||
"frames": [
|
||||
0
|
||||
],
|
||||
"hash": "34B3BCEC95C18658E45A8832AEB2BE00F0716E2FD78CE45CBA36F644DA5945B9"
|
||||
},
|
||||
{
|
||||
"name": "kernel-radius-40-defocus-2",
|
||||
"frames": [
|
||||
0
|
||||
],
|
||||
"hash": "6908E7DFE146500A209D47AD18FF5932FF9B80F8FCD976036179F4CA8503C89C"
|
||||
},
|
||||
{
|
||||
"name": "kernel-radius-63-polygon-defocus-3",
|
||||
"frames": [
|
||||
0
|
||||
],
|
||||
"hash": "55D4485AD5176D4AB6C7BE4BBBDD97343002B675AB0742D8F8224FD57A9296A5"
|
||||
},
|
||||
{
|
||||
"name": "quality-draft",
|
||||
"frames": [
|
||||
0
|
||||
],
|
||||
"hash": "0E16A02AE2360DBAB4FD57C28A95E51C61C2C33B81D46076D6D6E4FF81636A22"
|
||||
},
|
||||
{
|
||||
"name": "quality-high",
|
||||
"frames": [
|
||||
0
|
||||
],
|
||||
"hash": "B28685A19BA25205B8F2716831687D3D63958AE24C65311E39D5F585D1750D82"
|
||||
},
|
||||
{
|
||||
"name": "aperture-polygon",
|
||||
"frames": [
|
||||
0
|
||||
],
|
||||
"hash": "876C1DD8767A405F4C24ED6EE289513CFE155FA811E6D6F15A8C0E8F21624948"
|
||||
},
|
||||
{
|
||||
"name": "blade-count-3",
|
||||
"frames": [
|
||||
0
|
||||
],
|
||||
"hash": "3EC07AD240914F5CD7C0AAA8F0BEF5C76772922E932853B39AD38FC290C493E8"
|
||||
},
|
||||
{
|
||||
"name": "blade-count-32",
|
||||
"frames": [
|
||||
0
|
||||
],
|
||||
"hash": "7D5D5A10503525D51000E4CE2BF538E88878E77893D885B9B195C7FFCBDBCB50"
|
||||
},
|
||||
{
|
||||
"name": "blade-rotation-30",
|
||||
"frames": [
|
||||
0
|
||||
],
|
||||
"hash": "7DF481B8A4E5263100A7C30EF3070BC55D497A9F39CF09FEA1E56E4058D19658"
|
||||
},
|
||||
{
|
||||
"name": "obstruction-50",
|
||||
"frames": [
|
||||
0
|
||||
],
|
||||
"hash": "D1F583FF2F287987F3D97D48B5C3D0B80A647EECCF0F08C15387C745AFA41069"
|
||||
},
|
||||
{
|
||||
"name": "defocus-1",
|
||||
"frames": [
|
||||
0
|
||||
],
|
||||
"hash": "7B699943FCC55D026212D9D842F2BFE436F992AD1010B23B41A54A9C643120EC"
|
||||
},
|
||||
{
|
||||
"name": "astigmatism-vertical-1",
|
||||
"frames": [
|
||||
0
|
||||
],
|
||||
"hash": "AB5FACB67EC980806B6FFEE0627161CBE3EEE0F288194C1819072F6C108E372B"
|
||||
},
|
||||
{
|
||||
"name": "astigmatism-oblique-1",
|
||||
"frames": [
|
||||
0
|
||||
],
|
||||
"hash": "FE7398B928F43E7C3E9722D12F0B2550EA275DF9EB26E02E990DFCF21ECC98AE"
|
||||
},
|
||||
{
|
||||
"name": "coma-horizontal-1",
|
||||
"frames": [
|
||||
0
|
||||
],
|
||||
"hash": "EB2235CF182171F8D07EE8651D111D8A7483DFFAF934F51CC855E2A595FCAB5D"
|
||||
},
|
||||
{
|
||||
"name": "coma-vertical-1",
|
||||
"frames": [
|
||||
0
|
||||
],
|
||||
"hash": "AA3FFDF4A62272DC0BD0E7A0EF8A4E4ECE03B27C90C665F71A991C2B65F72CC6"
|
||||
},
|
||||
{
|
||||
"name": "spherical-1",
|
||||
"frames": [
|
||||
0
|
||||
],
|
||||
"hash": "91CF9F66CC46831C357D898E0367814285FE4D62959AB717B54146F8E8CE0D6F"
|
||||
},
|
||||
{
|
||||
"name": "defocus-animated-frames-0-8",
|
||||
"frames": [
|
||||
0,
|
||||
1,
|
||||
2,
|
||||
3,
|
||||
4,
|
||||
5,
|
||||
6,
|
||||
7,
|
||||
8
|
||||
],
|
||||
"hash": "B0D6919D7AD63BBFC378CD8578033D0F6322EF479EA564385A4E6F50C4905F14"
|
||||
}
|
||||
]
|
||||
}
|
||||
@@ -1,157 +0,0 @@
|
||||
<?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>
|
||||
@@ -1,22 +0,0 @@
|
||||
<?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>
|
||||
@@ -1,28 +0,0 @@
|
||||
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);
|
||||
}
|
||||
@@ -1,12 +0,0 @@
|
||||
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);
|
||||
}
|
||||
@@ -1,28 +0,0 @@
|
||||
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,93 +0,0 @@
|
||||
using WaveOptics.Fourier;
|
||||
|
||||
namespace WaveOptics.Tests.Fourier;
|
||||
|
||||
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 before = GC.GetAllocatedBytesForCurrentThread();
|
||||
for (var index = 0; index < 16; index++)
|
||||
{
|
||||
FastFourierTransform.Forward(real, imaginary);
|
||||
FastFourierTransform.Inverse(real, imaginary);
|
||||
}
|
||||
|
||||
Assert.Equal(0, GC.GetAllocatedBytesForCurrentThread() - before);
|
||||
}
|
||||
|
||||
static void AssertMaximumError(double[] expectedReal, double[] expectedImaginary, double[] actualReal, double[] actualImaginary, double tolerance)
|
||||
{
|
||||
var maximum = 0d;
|
||||
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}");
|
||||
}
|
||||
}
|
||||
@@ -1,108 +0,0 @@
|
||||
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);
|
||||
}
|
||||
}
|
||||
@@ -1,139 +0,0 @@
|
||||
using WaveOptics.Abstractions;
|
||||
using WaveOptics.Optics;
|
||||
|
||||
namespace WaveOptics.Tests.Psf;
|
||||
|
||||
public sealed class FraunhoferPsfGeneratorTests
|
||||
{
|
||||
readonly FraunhoferPsfGenerator generator = new();
|
||||
|
||||
[Fact]
|
||||
public void IdealCircularPsfIsFiniteNonnegativeAndNormalized()
|
||||
{
|
||||
var result = generator.Generate(CreateDescriptor());
|
||||
|
||||
Assert.Equal(1, result.Kernel.Sum(), 12);
|
||||
foreach (var value in result.Kernel.Values.Span)
|
||||
{
|
||||
Assert.True(double.IsFinite(value));
|
||||
Assert.True(value >= 0);
|
||||
}
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void IdealCircularPsfIsCentrallySymmetric()
|
||||
{
|
||||
var kernel = generator.Generate(CreateDescriptor()).Kernel;
|
||||
var last = kernel.Size - 1;
|
||||
var maximumError = 0d;
|
||||
|
||||
for (var y = 0; y < kernel.Size; y++)
|
||||
{
|
||||
for (var x = 0; x < kernel.Size; x++)
|
||||
maximumError = Math.Max(maximumError, Math.Abs(kernel[x, y] - kernel[last - x, last - y]));
|
||||
}
|
||||
|
||||
Assert.True(maximumError < 1e-10, $"{maximumError:R}");
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void FirstAiryMinimumMatchesDiffractionFormula()
|
||||
{
|
||||
const double wavelengthMicrometers = 0.55;
|
||||
const double fNumber = 8;
|
||||
const double pixelPitch = 2;
|
||||
var descriptor = CreateDescriptor(
|
||||
wavelengthNanometers: wavelengthMicrometers * 1000,
|
||||
fNumber: fNumber,
|
||||
pixelPitch: pixelPitch);
|
||||
var kernel = generator.Generate(descriptor).Kernel;
|
||||
var center = kernel.Size / 2;
|
||||
var measured = FindFirstMinimum(kernel, center);
|
||||
var expected = 1.22 * wavelengthMicrometers * fNumber / pixelPitch;
|
||||
|
||||
Assert.InRange(measured, expected - 1, expected + 1);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void HorizontalComaBreaksCentralSymmetry()
|
||||
{
|
||||
var aberration = new WavefrontAberration(comaHorizontalWaves: 0.75);
|
||||
var kernel = generator.Generate(CreateDescriptor(aberration: aberration)).Kernel;
|
||||
var last = kernel.Size - 1;
|
||||
var difference = 0d;
|
||||
|
||||
for (var y = 0; y < kernel.Size; y++)
|
||||
{
|
||||
for (var x = 0; x < kernel.Size; x++)
|
||||
difference += Math.Abs(kernel[x, y] - kernel[last - x, last - y]);
|
||||
}
|
||||
|
||||
Assert.True(difference > 1e-4, $"{difference:R}");
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void CentralObstructionReducesCentralPeak()
|
||||
{
|
||||
var unobstructed = generator.Generate(CreateDescriptor()).Kernel;
|
||||
var obstructed = generator.Generate(CreateDescriptor(obstruction: 0.5)).Kernel;
|
||||
var center = unobstructed.Size / 2;
|
||||
|
||||
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++)
|
||||
{
|
||||
var previous = kernel[center + radius - 1, center];
|
||||
var current = kernel[center + radius, center];
|
||||
var next = kernel[center + radius + 1, center];
|
||||
if (current <= previous && current <= next)
|
||||
return radius;
|
||||
}
|
||||
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,
|
||||
double pixelPitch = 2,
|
||||
double obstruction = 0,
|
||||
WavefrontAberration aberration = default)
|
||||
{
|
||||
return new PsfDescriptor(
|
||||
512,
|
||||
128,
|
||||
31,
|
||||
wavelengthNanometers,
|
||||
fNumber,
|
||||
pixelPitch,
|
||||
ApertureShape.Circular,
|
||||
6,
|
||||
0,
|
||||
obstruction,
|
||||
aberration);
|
||||
}
|
||||
}
|
||||
@@ -1,37 +0,0 @@
|
||||
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;
|
||||
}
|
||||
@@ -1,31 +0,0 @@
|
||||
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"));
|
||||
}
|
||||
}
|
||||
@@ -1,10 +0,0 @@
|
||||
using System.IO.Packaging;
|
||||
using System.Runtime.CompilerServices;
|
||||
|
||||
namespace WaveOptics.Tests;
|
||||
|
||||
internal static class PackUriScheme
|
||||
{
|
||||
[ModuleInitializer]
|
||||
internal static void Register() => _ = PackUriHelper.UriSchemePack;
|
||||
}
|
||||
@@ -1,60 +0,0 @@
|
||||
using WaveOptics.Abstractions;
|
||||
|
||||
namespace WaveOptics.Tests.Contracts;
|
||||
|
||||
public sealed class PsfDescriptorTests
|
||||
{
|
||||
[Fact]
|
||||
public void ConstructorAcceptsValidDescriptor()
|
||||
{
|
||||
var descriptor = CreateDescriptor();
|
||||
|
||||
Assert.Equal(256, descriptor.PupilGridSize);
|
||||
Assert.Equal(64, descriptor.PupilDiameterSamples);
|
||||
Assert.Equal(31, descriptor.KernelSize);
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[InlineData(63)]
|
||||
[InlineData(96)]
|
||||
[InlineData(257)]
|
||||
public void ConstructorRejectsNonPowerOfTwoGrid(int gridSize)
|
||||
{
|
||||
Assert.ThrowsAny<ArgumentException>(() => CreateDescriptor(gridSize: gridSize));
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[InlineData(2)]
|
||||
[InlineData(30)]
|
||||
[InlineData(256)]
|
||||
public void ConstructorRejectsInvalidKernelSize(int kernelSize)
|
||||
{
|
||||
Assert.ThrowsAny<ArgumentException>(() => CreateDescriptor(kernelSize: kernelSize));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void EqualDescriptorsHaveEqualHashCodes()
|
||||
{
|
||||
var first = CreateDescriptor();
|
||||
var second = CreateDescriptor();
|
||||
|
||||
Assert.Equal(first, second);
|
||||
Assert.Equal(first.GetHashCode(), second.GetHashCode());
|
||||
}
|
||||
|
||||
static PsfDescriptor CreateDescriptor(int gridSize = 256, int kernelSize = 31)
|
||||
{
|
||||
return new PsfDescriptor(
|
||||
gridSize,
|
||||
Math.Min(64, gridSize / 2),
|
||||
kernelSize,
|
||||
550,
|
||||
8,
|
||||
4,
|
||||
ApertureShape.Circular,
|
||||
6,
|
||||
0,
|
||||
0,
|
||||
new WavefrontAberration());
|
||||
}
|
||||
}
|
||||
@@ -1,40 +0,0 @@
|
||||
using WaveOptics.Abstractions;
|
||||
|
||||
namespace WaveOptics.Tests.Contracts;
|
||||
|
||||
public sealed class PsfKernelTests
|
||||
{
|
||||
[Fact]
|
||||
public void ConstructorNormalizesKernel()
|
||||
{
|
||||
var values = new double[9];
|
||||
values[4] = 2;
|
||||
|
||||
var kernel = new PsfKernel(3, values);
|
||||
|
||||
Assert.Equal(1, kernel.Sum(), 12);
|
||||
Assert.Equal(1, kernel[1, 1], 12);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void ConstructorCopiesInput()
|
||||
{
|
||||
var values = new double[9];
|
||||
values[4] = 1;
|
||||
var kernel = new PsfKernel(3, values);
|
||||
|
||||
values[4] = 0;
|
||||
|
||||
Assert.Equal(1, kernel[1, 1], 12);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void ConstructorRejectsNegativeValues()
|
||||
{
|
||||
var values = new double[9];
|
||||
values[4] = 1;
|
||||
values[0] = -0.1;
|
||||
|
||||
Assert.Throws<ArgumentOutOfRangeException>(() => new PsfKernel(3, values));
|
||||
}
|
||||
}
|
||||
@@ -1,95 +0,0 @@
|
||||
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);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,158 +0,0 @@
|
||||
using WaveOptics.Optics;
|
||||
|
||||
namespace WaveOptics.Tests.Optics;
|
||||
|
||||
public sealed class SeparableKernelTests
|
||||
{
|
||||
[Fact]
|
||||
public void FullRankReconstructionMatchesOriginal()
|
||||
{
|
||||
const int size = 15;
|
||||
var random = new Random(2024);
|
||||
var kernel = new double[size * size];
|
||||
for (var index = 0; index < kernel.Length; index++)
|
||||
kernel[index] = random.NextDouble();
|
||||
|
||||
var separable = SeparableKernel.Decompose(kernel, size, 0d, size);
|
||||
var maximumError = ReconstructionError(separable, kernel);
|
||||
|
||||
Assert.Equal(size, separable.Rank);
|
||||
Assert.True(maximumError < 1e-5, $"{maximumError:R}");
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void OuterProductKernelIsRankOne()
|
||||
{
|
||||
const int size = 11;
|
||||
var vertical = new double[size];
|
||||
var horizontal = new double[size];
|
||||
for (var i = 0; i < size; i++)
|
||||
{
|
||||
vertical[i] = Math.Exp(-0.2 * (i - 5) * (i - 5));
|
||||
horizontal[i] = Math.Exp(-0.35 * (i - 5) * (i - 5));
|
||||
}
|
||||
var kernel = new double[size * size];
|
||||
for (var y = 0; y < size; y++)
|
||||
{
|
||||
for (var x = 0; x < size; x++)
|
||||
kernel[y * size + x] = vertical[y] * horizontal[x];
|
||||
}
|
||||
|
||||
var separable = SeparableKernel.Decompose(kernel, size, 1e-6, size);
|
||||
var maximumError = ReconstructionError(separable, kernel);
|
||||
|
||||
Assert.Equal(1, separable.Rank);
|
||||
Assert.True(maximumError < 1e-5, $"{maximumError:R}");
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void LowRankApproximationHonorsResidualBudget()
|
||||
{
|
||||
const int size = 21;
|
||||
var center = size / 2;
|
||||
var kernel = new double[size * size];
|
||||
var sum = 0d;
|
||||
for (var y = 0; y < size; y++)
|
||||
{
|
||||
for (var x = 0; x < size; x++)
|
||||
{
|
||||
var radiusSquared = (x - center) * (x - center) + (y - center) * (y - center);
|
||||
var value = Math.Exp(-0.12 * radiusSquared);
|
||||
kernel[y * size + x] = value;
|
||||
sum += value;
|
||||
}
|
||||
}
|
||||
for (var index = 0; index < kernel.Length; index++)
|
||||
kernel[index] /= sum;
|
||||
|
||||
var separable = SeparableKernel.Decompose(kernel, size, 1e-4, size);
|
||||
var energy = 0d;
|
||||
var residual = 0d;
|
||||
for (var y = 0; y < size; y++)
|
||||
{
|
||||
for (var x = 0; x < size; x++)
|
||||
{
|
||||
var original = kernel[y * size + x];
|
||||
var approximation = Reconstruct(separable, x, y);
|
||||
energy += original * original;
|
||||
residual += (original - approximation) * (original - approximation);
|
||||
}
|
||||
}
|
||||
|
||||
Assert.True(separable.Rank < size);
|
||||
Assert.True(residual <= 1e-4 * energy, $"{residual / energy:R}");
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void SumIsTheSumOfTheApproximation()
|
||||
{
|
||||
const int size = 21;
|
||||
var center = size / 2;
|
||||
var kernel = new double[size * size];
|
||||
for (var y = 0; y < size; y++)
|
||||
{
|
||||
for (var x = 0; x < size; x++)
|
||||
kernel[y * size + x] = Math.Exp(-0.3 * Math.Sqrt((x - center) * (x - center) + (y - center) * (y - center)));
|
||||
}
|
||||
|
||||
var separable = SeparableKernel.Decompose(kernel, size, 1e-4, 2);
|
||||
var sum = 0d;
|
||||
for (var y = 0; y < size; y++)
|
||||
{
|
||||
for (var x = 0; x < size; x++)
|
||||
sum += Reconstruct(separable, x, y);
|
||||
}
|
||||
|
||||
Assert.Equal(sum, separable.Sum, 5);
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[InlineData(21, 9)]
|
||||
[InlineData(9, 21)]
|
||||
[InlineData(13, 13)]
|
||||
public void AReusedDecompositionMatchesAFreshOne(int previousSize, int size)
|
||||
{
|
||||
var random = new Random(previousSize * 100 + size);
|
||||
var previous = new double[previousSize * previousSize];
|
||||
for (var index = 0; index < previous.Length; index++)
|
||||
previous[index] = random.NextDouble();
|
||||
var kernel = new double[size * size];
|
||||
for (var index = 0; index < kernel.Length; index++)
|
||||
kernel[index] = random.NextDouble() * random.NextDouble();
|
||||
var reused = new SeparableKernel();
|
||||
reused.Update(previous, previousSize, 1e-4, previousSize);
|
||||
|
||||
reused.Update(kernel, size, 1e-4, size);
|
||||
var fresh = SeparableKernel.Decompose(kernel, size, 1e-4, size);
|
||||
|
||||
Assert.Equal((fresh.Size, fresh.Rank), (reused.Size, reused.Rank));
|
||||
Assert.Equal(BitConverter.DoubleToInt64Bits(fresh.Sum), BitConverter.DoubleToInt64Bits(reused.Sum));
|
||||
Assert.Equal(BitConverter.DoubleToInt64Bits(fresh.ResidualEnergyRatio), BitConverter.DoubleToInt64Bits(reused.ResidualEnergyRatio));
|
||||
Assert.Equal(fresh.Horizontal.ToArray(), reused.Horizontal.ToArray());
|
||||
Assert.Equal(fresh.Vertical.ToArray(), reused.Vertical.ToArray());
|
||||
}
|
||||
|
||||
static double Reconstruct(SeparableKernel separable, int x, int y)
|
||||
{
|
||||
var size = separable.Size;
|
||||
var value = 0d;
|
||||
for (var term = 0; term < separable.Rank; term++)
|
||||
value += separable.Vertical[term * size + y] * separable.Horizontal[term * size + x];
|
||||
return value;
|
||||
}
|
||||
|
||||
static double ReconstructionError(SeparableKernel separable, double[] kernel)
|
||||
{
|
||||
var size = separable.Size;
|
||||
var maximumError = 0d;
|
||||
for (var y = 0; y < size; y++)
|
||||
{
|
||||
for (var x = 0; x < size; x++)
|
||||
{
|
||||
var error = Math.Abs(kernel[y * size + x] - Reconstruct(separable, x, y));
|
||||
maximumError = Math.Max(maximumError, error);
|
||||
}
|
||||
}
|
||||
return maximumError;
|
||||
}
|
||||
}
|
||||
@@ -1,59 +0,0 @@
|
||||
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();
|
||||
}
|
||||
@@ -1,68 +0,0 @@
|
||||
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);
|
||||
}
|
||||
}
|
||||
@@ -1,85 +0,0 @@
|
||||
<Project Sdk="Microsoft.NET.Sdk">
|
||||
|
||||
<PropertyGroup>
|
||||
<TargetFramework>net10.0-windows10.0.19041.0</TargetFramework>
|
||||
<UseWPF>true</UseWPF>
|
||||
<ImplicitUsings>enable</ImplicitUsings>
|
||||
<Nullable>enable</Nullable>
|
||||
<IsPackable>false</IsPackable>
|
||||
<AssemblyName>WaveOptics.Tests</AssemblyName>
|
||||
<RootNamespace>WaveOptics.Tests</RootNamespace>
|
||||
<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="..\WaveOptics.Abstractions\WaveOptics.Abstractions.csproj" />
|
||||
<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>
|
||||
<Using Include="Xunit" />
|
||||
</ItemGroup>
|
||||
|
||||
</Project>
|
||||
@@ -1,215 +0,0 @@
|
||||
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]}"));
|
||||
}
|
||||
}
|
||||
@@ -1,458 +0,0 @@
|
||||
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)) },
|
||||
};
|
||||
|
||||
[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 },
|
||||
};
|
||||
|
||||
[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!));
|
||||
}
|
||||
}
|
||||
@@ -1,307 +0,0 @@
|
||||
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];
|
||||
|
||||
[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)]
|
||||
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 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;
|
||||
|
||||
Assert.Equal([nameof(WaveOpticsEffect.KernelRadius), nameof(WaveOpticsEffect.Quality), nameof(WaveOpticsEffect.ApertureShape), nameof(WaveOpticsEffect.BladeCount)], changed);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void AssigningAnUnchangedOrClampedValueDoesNotNotify()
|
||||
{
|
||||
var effect = new WaveOpticsEffect { KernelRadius = WaveOpticsSettings.MaximumKernelRadius };
|
||||
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;
|
||||
|
||||
Assert.Empty(changed);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void TheLabelIsTheLocalizedEffectName()
|
||||
{
|
||||
var effect = new WaveOpticsEffect();
|
||||
|
||||
Assert.Equal(Texts.WaveOptics, effect.Label);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void TheThirteenNumericParametersReceiveTheAnimationParameters()
|
||||
{
|
||||
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.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)]
|
||||
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);
|
||||
}
|
||||
|
||||
[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 };
|
||||
var values = new[] { 55d, 150d, 620d, 5.6d, 2.5d, 30d, 40d, 1.5d, -0.5d, 0.25d, -1d, 0.75d, 2d };
|
||||
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.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));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void TheEffectKeepsTheTypeNameThatProjectsStore()
|
||||
{
|
||||
var type = typeof(WaveOpticsEffect);
|
||||
|
||||
Assert.Equal("WaveOptics.Effects.WaveOpticsEffect", type.FullName);
|
||||
Assert.Equal("WaveOptics", type.Assembly.GetName().Name);
|
||||
}
|
||||
}
|
||||
@@ -1,168 +0,0 @@
|
||||
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.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.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;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,578 +0,0 @@
|
||||
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(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;
|
||||
}
|
||||
|
||||
static SeparableKernel Decompose(WaveOpticsPipeline.PsfParameters psf)
|
||||
{
|
||||
var kernel = Kernel(psf);
|
||||
return SeparableKernel.Decompose(kernel.Values.Span, kernel.Size, WaveOpticsSettings.SeparableResidualRatio, WaveOpticsSettings.MaximumRank);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void ATransparentSourceStaysTransparent()
|
||||
{
|
||||
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 AnImpulseSpreadsIntoTheSeparableKernel(int impulseX, int impulseY)
|
||||
{
|
||||
using var pipeline = CreatePipeline();
|
||||
var parameters = Parameters(kernelRadius: 6, pixelPitch: 1.5f, comaHorizontal: 0.4f);
|
||||
var separable = Decompose(parameters.Psf);
|
||||
var radius = separable.Size / 2;
|
||||
var 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 expected = 0f;
|
||||
var row = impulseY - y + radius;
|
||||
var column = impulseX - x + radius;
|
||||
if (row >= 0 && row < separable.Size && column >= 0 && column < separable.Size)
|
||||
{
|
||||
for (var term = 0; term < separable.Rank; term++)
|
||||
expected += separable.Horizontal[term * separable.Size + column] * separable.Vertical[term * separable.Size + row];
|
||||
}
|
||||
|
||||
var value = (int)Math.Round(Math.Clamp(expected / separable.Sum, 0d, 1d) * 255d, MidpointRounding.ToEven);
|
||||
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);
|
||||
}
|
||||
}
|
||||
@@ -1,113 +0,0 @@
|
||||
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 TheLargestKernelFitsInEveryWeightSlot()
|
||||
=> Assert.Equal(WaveOpticsSettings.MaximumKernelSize, WaveOpticsSettings.GetKernelSize(WaveOpticsSettings.MaximumKernelRadius));
|
||||
|
||||
[Fact]
|
||||
public void EveryTermAndAxisOwnsItsOwnWeightSlot()
|
||||
{
|
||||
var offsets = Enumerable.Range(0, WaveOpticsSettings.MaximumRank)
|
||||
.SelectMany(term => new[] { WaveOpticsSettings.GetWeightOffset(term, 0), WaveOpticsSettings.GetWeightOffset(term, 1) })
|
||||
.Order()
|
||||
.ToArray();
|
||||
|
||||
Assert.Equal(WaveOpticsSettings.MaximumRank * 2, offsets.Distinct().Count());
|
||||
Assert.Equal(0, offsets[0]);
|
||||
Assert.All(offsets.Zip(offsets.Skip(1)), pair => Assert.Equal(WaveOpticsSettings.MaximumKernelSize, pair.Second - pair.First));
|
||||
Assert.Equal(WaveOpticsSettings.WeightsLength, offsets[^1] + WaveOpticsSettings.MaximumKernelSize);
|
||||
}
|
||||
|
||||
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 TheRankLimitKeepsEveryAberrationWithinTheResidualBudget(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 separable = SeparableKernel.Decompose(kernel.Values.Span, kernel.Size, WaveOpticsSettings.SeparableResidualRatio, WaveOpticsSettings.MaximumRank);
|
||||
|
||||
Assert.True(separable.ResidualEnergyRatio <= WaveOpticsSettings.SeparableResidualRatio, $"{aberrationName}: {separable.ResidualEnergyRatio}");
|
||||
}
|
||||
|
||||
[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));
|
||||
}
|
||||
}
|
||||
@@ -1,26 +0,0 @@
|
||||
{
|
||||
"stryker-config": {
|
||||
"project": "WaveOptics.csproj",
|
||||
"test-runner": "mtp",
|
||||
"coverage-analysis": "off",
|
||||
"concurrency": 4,
|
||||
"additional-timeout": 30000,
|
||||
"mutate": [
|
||||
"**/*.cs",
|
||||
"!**/YMM4-GitHubUpdateNotifier/**",
|
||||
"!**/YMM4-Telemetry/**",
|
||||
"!**/WaveOpticsTelemetry.cs",
|
||||
"!**/WaveOpticsUpdateNotifier.cs"
|
||||
],
|
||||
"reporters": [
|
||||
"progress",
|
||||
"cleartext",
|
||||
"html"
|
||||
],
|
||||
"thresholds": {
|
||||
"high": 80,
|
||||
"low": 60,
|
||||
"break": 60
|
||||
}
|
||||
}
|
||||
}
|
||||
バイナリ
バイナリファイルは表示されません。
|
変更後 幅: | 高さ: | サイズ: 868 KiB |
@@ -1,27 +0,0 @@
|
||||
<Solution>
|
||||
<Configurations>
|
||||
<Platform Name="Any CPU" />
|
||||
<Platform Name="x64" />
|
||||
</Configurations>
|
||||
<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="YukkuriMovieMaker.Generator/YukkuriMovieMaker.Generator/YukkuriMovieMaker.Generator.csproj" />
|
||||
</Solution>
|
||||
@@ -1,8 +0,0 @@
|
||||
using YukkuriMovieMaker.Generator;
|
||||
|
||||
namespace WaveOptics.Effects;
|
||||
|
||||
[AutoGenLocalizer]
|
||||
partial class Texts
|
||||
{
|
||||
}
|
||||
@@ -1,50 +0,0 @@
|
||||
Key,Parameter,ja-jp,en-us,zh-cn,zh-tw,ko-kr,es-es,ar-sa,id-id
|
||||
WaveOptics,,波動光学,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
|
||||
Amount,,適用量,Amount,适用量,適用量,적용량,Cantidad,الكمية,Jumlah
|
||||
AmountDescription,,波動光学処理の適用量を調整します。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%.
|
||||
Gain,,利得,Gain,增益,增益,이득,Ganancia,الكسب,Penguatan
|
||||
GainDescription,,エネルギー保存された畳み込み結果へ乗算する表示用利得です。,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.
|
||||
Wavelength,,波長,Wavelength,波长,波長,파장,Longitud de onda,الطول الموجي,Panjang Gelombang
|
||||
WavelengthDescription,,単色光として計算する真空中の波長を指定します。,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.
|
||||
FNumber,,F値,F-number,F值,F值,F값,Número F,رقم F,Angka F
|
||||
FNumberDescription,,開口径に対する焦点距離の比を指定します。,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.
|
||||
PixelPitch,,画素ピッチ,Pixel Pitch,像素间距,像素間距,픽셀 피치,Paso de píxel,خطوة البكسل,Jarak Piksel
|
||||
PixelPitchDescription,,撮像面上の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.
|
||||
KernelRadius,,カーネル半径,Kernel Radius,核半径,核半徑,커널 반지름,Radio de kernel,نصف قطر النواة,Radius Kernel
|
||||
KernelRadiusDescription,,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.
|
||||
Quality,,品質,Quality,质量,品質,품질,Calidad,الجودة,Kualitas
|
||||
QualityDescription,,瞳関数と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
|
||||
ApertureShape,,開口形状,Aperture Shape,光圈形状,光圈形狀,조리개 형태,Forma de apertura,شكل الفتحة,Bentuk Apertur
|
||||
ApertureShapeDescription,,瞳関数の外周形状を指定します。,Sets the outer shape of the pupil function.,设置瞳孔函数的外部形状。,設定瞳孔函數的外部形狀。,동공 함수의 외부 형태를 설정합니다.,Establece la forma exterior de la función pupilar.,يضبط الشكل الخارجي لدالة الحدقة.,Mengatur bentuk luar fungsi pupil.
|
||||
CircularAperture,,円形,Circular,圆形,圓形,원형,Circular,دائري,Melingkar
|
||||
RegularPolygonAperture,,正多角形,Regular Polygon,正多边形,正多邊形,정다각형,Polígono regular,مضلع منتظم,Poligon Beraturan
|
||||
BladeCount,,羽根枚数,Blade Count,叶片数,葉片數,날개 수,Número de láminas,عدد الشفرات,Jumlah Bilah
|
||||
BladeCountDescription,,正多角形開口の辺数を指定します。,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.
|
||||
BladeRotation,,開口回転,Aperture Rotation,光圈旋转,光圈旋轉,조리개 회전,Rotación de apertura,دوران الفتحة,Rotasi Apertur
|
||||
BladeRotationDescription,,正多角形開口の回転角を指定します。,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.
|
||||
Obstruction,,中央遮蔽,Central Obstruction,中央遮蔽,中央遮蔽,중앙 차폐,Obstrucción central,الحجب المركزي,Obstruksi Tengah
|
||||
ObstructionDescription,,開口半径に対する中央遮蔽半径の割合を指定します。,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.
|
||||
Defocus,,デフォーカス,Defocus,离焦,離焦,디포커스,Desenfoque,إزالة التركيز,Defokus
|
||||
DefocusDescription,,正規化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.
|
||||
AstigmatismVertical,,縦横非点収差,Vertical Astigmatism,垂直散光,垂直散光,수직 난시,Astigmatismo vertical,الاستجماتيزم الرأسي,Astigmatisme Vertikal
|
||||
AstigmatismVerticalDescription,,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.
|
||||
AstigmatismOblique,,斜め非点収差,Oblique Astigmatism,斜向散光,斜向散光,사선 난시,Astigmatismo oblicuo,الاستجماتيزم المائل,Astigmatisme Miring
|
||||
AstigmatismObliqueDescription,,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.
|
||||
ComaHorizontal,,水平コマ収差,Horizontal Coma,水平彗差,水平彗差,수평 코마,Coma horizontal,الكوما الأفقية,Koma Horizontal
|
||||
ComaHorizontalDescription,,水平方向の正規化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.
|
||||
ComaVertical,,垂直コマ収差,Vertical Coma,垂直彗差,垂直彗差,수직 코마,Coma vertical,الكوما الرأسية,Koma Vertikal
|
||||
ComaVerticalDescription,,垂直方向の正規化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.
|
||||
Spherical,,球面収差,Spherical Aberration,球面像差,球面像差,구면 수차,Aberración esférica,الانحراف الكروي,Aberasi Sferis
|
||||
SphericalDescription,,正規化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
|
||||
UpdateAvailableMessage,,新しいバージョン {0} が公開されています。,A new version {0} is available.,新版本 {0} 已发布。,新版本 {0} 已發布。,새 버전 {0}이(가) 공개되었습니다.,La nueva versión {0} ya está disponible.,تم إصدار نسخة جديدة {0}.,Versi baru {0} telah dirilis.
|
||||
|
@@ -1,12 +0,0 @@
|
||||
using System.ComponentModel.DataAnnotations;
|
||||
|
||||
namespace WaveOptics.Effects;
|
||||
|
||||
public enum WaveOpticsApertureShape
|
||||
{
|
||||
[Display(Name = nameof(Texts.CircularAperture), ResourceType = typeof(Texts))]
|
||||
Circular,
|
||||
|
||||
[Display(Name = nameof(Texts.RegularPolygonAperture), ResourceType = typeof(Texts))]
|
||||
RegularPolygon,
|
||||
}
|
||||
@@ -1,117 +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.WaveOptics), [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.WaveOptics;
|
||||
|
||||
public WaveOpticsEffect()
|
||||
{
|
||||
WaveOpticsTelemetry.EnsureStartedOnce();
|
||||
WaveOpticsUpdateNotifier.EnsureCheckedOnce();
|
||||
}
|
||||
|
||||
[Display(GroupName = nameof(Texts.OutputGroup), Name = nameof(Texts.Amount), Description = nameof(Texts.AmountDescription), 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.Gain), Description = nameof(Texts.GainDescription), 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.Wavelength), Description = nameof(Texts.WavelengthDescription), 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.FNumber), Description = nameof(Texts.FNumberDescription), 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.PixelPitch), Description = nameof(Texts.PixelPitchDescription), 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.KernelRadius), Description = nameof(Texts.KernelRadiusDescription), Order = 13, ResourceType = typeof(Texts))]
|
||||
[TextBoxSlider("F0", "px", WaveOpticsSettings.MinimumKernelRadius, WaveOpticsSettings.MaximumKernelRadius)]
|
||||
[Range(WaveOpticsSettings.MinimumKernelRadius, WaveOpticsSettings.MaximumKernelRadius)]
|
||||
[DefaultValue(WaveOpticsSettings.DefaultKernelRadius)]
|
||||
public int KernelRadius { get => _kernelRadius; set => Set(ref _kernelRadius, Math.Clamp(value, WaveOpticsSettings.MinimumKernelRadius, WaveOpticsSettings.MaximumKernelRadius)); }
|
||||
private int _kernelRadius = WaveOpticsSettings.DefaultKernelRadius;
|
||||
|
||||
[Display(GroupName = nameof(Texts.OpticsGroup), Name = nameof(Texts.Quality), Description = nameof(Texts.QualityDescription), Order = 14, ResourceType = typeof(Texts))]
|
||||
[EnumComboBox]
|
||||
public WaveOpticsQuality Quality { get => _quality; set => Set(ref _quality, value); }
|
||||
private WaveOpticsQuality _quality = WaveOpticsQuality.Standard;
|
||||
|
||||
[Display(GroupName = nameof(Texts.ApertureGroup), Name = nameof(Texts.ApertureShape), Description = nameof(Texts.ApertureShapeDescription), Order = 20, ResourceType = typeof(Texts))]
|
||||
[EnumComboBox]
|
||||
public WaveOpticsApertureShape ApertureShape { get => _apertureShape; set => Set(ref _apertureShape, value); }
|
||||
private WaveOpticsApertureShape _apertureShape;
|
||||
|
||||
[Display(GroupName = nameof(Texts.ApertureGroup), Name = nameof(Texts.BladeCount), Description = nameof(Texts.BladeCountDescription), Order = 21, ResourceType = typeof(Texts))]
|
||||
[TextBoxSlider("F0", "", 3, 16)]
|
||||
[Range(3, 32)]
|
||||
[DefaultValue(6)]
|
||||
public int BladeCount { get => _bladeCount; set => Set(ref _bladeCount, Math.Clamp(value, 3, 32)); }
|
||||
private int _bladeCount = 6;
|
||||
|
||||
[Display(GroupName = nameof(Texts.ApertureGroup), Name = nameof(Texts.BladeRotation), Description = nameof(Texts.BladeRotationDescription), 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.Obstruction), Description = nameof(Texts.ObstructionDescription), 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.Defocus), Description = nameof(Texts.DefocusDescription), 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.AstigmatismVertical), Description = nameof(Texts.AstigmatismVerticalDescription), 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.AstigmatismOblique), Description = nameof(Texts.AstigmatismObliqueDescription), 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.ComaHorizontal), Description = nameof(Texts.ComaHorizontalDescription), 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.ComaVertical), Description = nameof(Texts.ComaVerticalDescription), 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.Spherical), Description = nameof(Texts.SphericalDescription), Order = 35, ResourceType = typeof(Texts))]
|
||||
[AnimationSlider("F3", "waves", -3, 3)]
|
||||
public Animation Spherical { get; } = new(0, -10, 10);
|
||||
|
||||
private IAnimatable[]? _animatables;
|
||||
|
||||
public override IEnumerable<string> CreateExoVideoFilters(int keyFrameIndex, ExoOutputDescription exoOutputDescription) => [];
|
||||
|
||||
public override IVideoEffectProcessor CreateVideoEffect(IGraphicsDevicesAndContext devices)
|
||||
{
|
||||
try
|
||||
{
|
||||
return new WaveOpticsEffectProcessor(devices, this);
|
||||
}
|
||||
catch (Exception exception)
|
||||
{
|
||||
WaveOpticsTelemetry.Report(exception);
|
||||
throw;
|
||||
}
|
||||
}
|
||||
|
||||
protected override IEnumerable<IAnimatable> GetAnimatables()
|
||||
=> _animatables ??= [Amount, Gain, Wavelength, FNumber, PixelPitch, BladeRotation, Obstruction, Defocus, AstigmatismVertical, AstigmatismOblique, ComaHorizontal, ComaVertical, Spherical];
|
||||
}
|
||||
@@ -1,403 +0,0 @@
|
||||
using System.ComponentModel;
|
||||
using System.Numerics;
|
||||
using ComputeWeave;
|
||||
using Vortice.Direct2D1;
|
||||
using Vortice.Direct2D1.Effects;
|
||||
using WaveOptics.Rendering;
|
||||
using YukkuriMovieMaker.Commons;
|
||||
using YukkuriMovieMaker.Player.Video;
|
||||
using YukkuriMovieMaker.Player.Video.Effects;
|
||||
|
||||
namespace WaveOptics.Effects;
|
||||
|
||||
internal sealed class WaveOpticsEffectProcessor : VideoEffectProcessorBase
|
||||
{
|
||||
private readonly IGraphicsDevicesAndContext _devices;
|
||||
private readonly WaveOpticsEffect _item;
|
||||
private ComputeExternalQueueScheduler? _scheduler;
|
||||
private WaveOpticsInteropProvider? _interopProvider;
|
||||
private ComputeInteropDomain? _interopDomain;
|
||||
private WaveOpticsResourceSet? _resourceSet;
|
||||
private ExternalTextureLease<ExternalDirect3D11TextureView>? _outputLease;
|
||||
private WaveOpticsPipeline? _pipeline;
|
||||
private WaveOpticsCustomEffect? _effect;
|
||||
private Crop? _outputCrop;
|
||||
private ID2D1Image? _outputCropOutput;
|
||||
private AffineTransform2D? _outputTransform;
|
||||
private ID2D1Image? _outputTransformOutput;
|
||||
private bool _isFirst = true;
|
||||
private bool _hasOutput;
|
||||
private bool _hasOutputOffset;
|
||||
private bool _hasCropRect;
|
||||
private bool _hasRenderState;
|
||||
private Vector2 _outputOffset;
|
||||
private Vector4 _cropRect;
|
||||
private float _amount;
|
||||
private RenderState _renderState;
|
||||
|
||||
public WaveOpticsEffectProcessor(IGraphicsDevicesAndContext devices, WaveOpticsEffect item)
|
||||
: base(devices)
|
||||
{
|
||||
_devices = devices;
|
||||
_item = item;
|
||||
}
|
||||
|
||||
public override DrawDescription Update(EffectDescription effectDescription)
|
||||
{
|
||||
try
|
||||
{
|
||||
return UpdateCore(effectDescription);
|
||||
}
|
||||
catch (Exception exception)
|
||||
{
|
||||
WaveOpticsTelemetry.Report(exception);
|
||||
throw;
|
||||
}
|
||||
}
|
||||
|
||||
private DrawDescription UpdateCore(EffectDescription effectDescription)
|
||||
{
|
||||
if (IsPassThroughEffect || _effect is null || _outputCrop is null || _outputTransform is null || _outputTransformOutput is null || _resourceSet is null || _interopProvider is null || _pipeline is null || input is null)
|
||||
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 parameters = new WaveOpticsPipeline.Parameters(
|
||||
Sanitize(_item.Gain.GetValue(frame, length, fps) / 100d, 0, 4, 1),
|
||||
new WaveOpticsPipeline.PsfParameters(
|
||||
_item.Quality,
|
||||
Math.Clamp(_item.KernelRadius, WaveOpticsSettings.MinimumKernelRadius, WaveOpticsSettings.MaximumKernelRadius),
|
||||
Sanitize(_item.Wavelength.GetValue(frame, length, fps), 380, 780, 550),
|
||||
Sanitize(_item.FNumber.GetValue(frame, length, fps), 0.5, 64, 8),
|
||||
Sanitize(_item.PixelPitch.GetValue(frame, length, fps), 0.25, 100, 4),
|
||||
_item.ApertureShape,
|
||||
Math.Clamp(_item.BladeCount, 3, 32),
|
||||
Sanitize(_item.BladeRotation.GetValue(frame, length, fps), -360, 360, 0),
|
||||
Sanitize(_item.Obstruction.GetValue(frame, length, fps) / 100d, 0, 0.95, 0),
|
||||
Sanitize(_item.Defocus.GetValue(frame, length, fps), -10, 10, 0),
|
||||
Sanitize(_item.AstigmatismVertical.GetValue(frame, length, fps), -10, 10, 0),
|
||||
Sanitize(_item.AstigmatismOblique.GetValue(frame, length, fps), -10, 10, 0),
|
||||
Sanitize(_item.ComaHorizontal.GetValue(frame, length, fps), -10, 10, 0),
|
||||
Sanitize(_item.ComaVertical.GetValue(frame, length, fps), -10, 10, 0),
|
||||
Sanitize(_item.Spherical.GetValue(frame, length, fps), -10, 10, 0)));
|
||||
|
||||
if (_isFirst || _amount != amount)
|
||||
_effect.Amount = amount;
|
||||
|
||||
if (amount <= 0f)
|
||||
{
|
||||
_effect.Amount = 0f;
|
||||
_amount = amount;
|
||||
_isFirst = true;
|
||||
return effectDescription.DrawDescription;
|
||||
}
|
||||
|
||||
var bounds = _devices.DeviceContext.GetImageLocalBounds(input);
|
||||
var widthValue = Math.Ceiling((double)bounds.Right - bounds.Left);
|
||||
var heightValue = Math.Ceiling((double)bounds.Bottom - bounds.Top);
|
||||
if (!double.IsFinite(widthValue) || !double.IsFinite(heightValue) ||
|
||||
!float.IsFinite(bounds.Left) || !float.IsFinite(bounds.Top) ||
|
||||
widthValue <= 0d || heightValue <= 0d)
|
||||
{
|
||||
_effect.Amount = 0f;
|
||||
_isFirst = true;
|
||||
return effectDescription.DrawDescription;
|
||||
}
|
||||
|
||||
var margin = WaveOpticsSettings.GetCanvasMargin(parameters.Psf.KernelRadius);
|
||||
var longSide = Math.Max(widthValue, heightValue);
|
||||
if ((WaveOpticsSettings.MaximumCanvasSize - longSide) / 2d < margin)
|
||||
{
|
||||
_effect.Amount = 0f;
|
||||
_isFirst = true;
|
||||
return effectDescription.DrawDescription;
|
||||
}
|
||||
var canvasWidth = (int)widthValue + margin * 2;
|
||||
var canvasHeight = (int)heightValue + margin * 2;
|
||||
var itemWidth = (int)widthValue;
|
||||
var itemHeight = (int)heightValue;
|
||||
|
||||
if (!EnsureSource(itemWidth, itemHeight))
|
||||
{
|
||||
_effect.Amount = 0f;
|
||||
_isFirst = true;
|
||||
return effectDescription.DrawDescription;
|
||||
}
|
||||
|
||||
RenderInput(new Vortice.RawRectF(bounds.Left, bounds.Top, bounds.Left + itemWidth, bounds.Top + itemHeight));
|
||||
|
||||
var convolutionChanged = _pipeline.Simulate(
|
||||
_resourceSet.GetSourceComputeBinding(),
|
||||
canvasWidth,
|
||||
canvasHeight,
|
||||
margin,
|
||||
margin,
|
||||
itemWidth,
|
||||
itemHeight,
|
||||
in parameters);
|
||||
|
||||
if (!_pipeline.HasKernel || !_pipeline.TryGetVisibleBounds(canvasWidth, canvasHeight, in parameters, out var rect))
|
||||
{
|
||||
_effect.Amount = 0f;
|
||||
_amount = amount;
|
||||
_isFirst = true;
|
||||
_hasRenderState = false;
|
||||
return effectDescription.DrawDescription;
|
||||
}
|
||||
|
||||
if (!OutputCovers(rect.Width, rect.Height))
|
||||
_outputCrop.SetInput(0, null, true);
|
||||
if (!EnsureOutput(rect.Width, rect.Height, out var outputChanged))
|
||||
{
|
||||
_effect.Amount = 0f;
|
||||
_amount = amount;
|
||||
_isFirst = true;
|
||||
_hasRenderState = false;
|
||||
return effectDescription.DrawDescription;
|
||||
}
|
||||
var renderState = new RenderState(parameters.Gain, rect);
|
||||
if (convolutionChanged || outputChanged || !_hasOutput || !_hasRenderState || _renderState != renderState)
|
||||
{
|
||||
_pipeline.RenderVisible(_resourceSet.GetOutputComputeBinding(), rect, in parameters);
|
||||
_renderState = renderState;
|
||||
_hasRenderState = true;
|
||||
}
|
||||
|
||||
_outputLease ??= _resourceSet.AcquireOutputExternalViewLease();
|
||||
|
||||
if (outputChanged || !_hasOutput)
|
||||
{
|
||||
using var outputBitmap = new ID2D1Bitmap1(_outputLease.DangerousGetView().AddRefBitmap());
|
||||
_outputCrop.SetInput(0, outputBitmap, true);
|
||||
_effect.SetInput(1, _outputTransformOutput, true);
|
||||
}
|
||||
var cropRect = new Vector4(0f, 0f, rect.Width, rect.Height);
|
||||
if (!_hasCropRect || _cropRect != cropRect)
|
||||
{
|
||||
_outputCrop.Rectangle = cropRect;
|
||||
_cropRect = cropRect;
|
||||
_hasCropRect = true;
|
||||
}
|
||||
var outputOffset = new Vector2(bounds.Left - margin + rect.X, bounds.Top - margin + rect.Y);
|
||||
if (!_hasOutputOffset || _outputOffset != outputOffset)
|
||||
{
|
||||
_outputTransform.TransformMatrix = Matrix3x2.CreateTranslation(outputOffset);
|
||||
_outputOffset = outputOffset;
|
||||
_hasOutputOffset = true;
|
||||
}
|
||||
_hasOutput = true;
|
||||
_amount = amount;
|
||||
_isFirst = false;
|
||||
return effectDescription.DrawDescription;
|
||||
}
|
||||
|
||||
private bool EnsureSource(int width, int height)
|
||||
{
|
||||
return _resourceSet!.TryEnsureSource(width, height, out _);
|
||||
}
|
||||
|
||||
private bool OutputCovers(int width, int height)
|
||||
=> _outputLease is { IsDisposed: false } lease &&
|
||||
lease.Width >= width &&
|
||||
lease.Height >= height;
|
||||
|
||||
private bool EnsureOutput(int width, int height, out bool changed)
|
||||
{
|
||||
changed = false;
|
||||
if (OutputCovers(width, height))
|
||||
return true;
|
||||
|
||||
_outputLease?.Dispose();
|
||||
_outputLease = null;
|
||||
return _resourceSet!.TryEnsureOutput(width, height, out changed);
|
||||
}
|
||||
|
||||
private void RenderInput(Vortice.RawRectF bounds)
|
||||
{
|
||||
var renderContext = _interopProvider!.RenderContext;
|
||||
using var borrow = _resourceSet!.BeginSourceExternalOperation();
|
||||
var previousTarget = renderContext.Target;
|
||||
using var sourceBitmap = new ID2D1Bitmap1(borrow.DangerousGetView().AddRefBitmap());
|
||||
renderContext.Target = sourceBitmap;
|
||||
renderContext.BeginDraw();
|
||||
renderContext.Clear(null);
|
||||
renderContext.DrawImage(
|
||||
input,
|
||||
new Vector2(-bounds.Left, -bounds.Top),
|
||||
null,
|
||||
InterpolationMode.NearestNeighbor,
|
||||
CompositeMode.SourceCopy);
|
||||
renderContext.EndDraw();
|
||||
renderContext.Target = previousTarget;
|
||||
}
|
||||
|
||||
private 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);
|
||||
}
|
||||
|
||||
private void ReleaseInterop()
|
||||
{
|
||||
_outputLease?.Dispose();
|
||||
_outputLease = null;
|
||||
_pipeline?.Dispose();
|
||||
_pipeline = null;
|
||||
_resourceSet?.Dispose();
|
||||
_resourceSet?.WaitForDisposal();
|
||||
_resourceSet = null;
|
||||
_interopDomain?.Dispose();
|
||||
_interopDomain?.WaitForDisposal();
|
||||
_interopDomain = null;
|
||||
_interopProvider?.Dispose();
|
||||
_interopProvider = null;
|
||||
_scheduler?.Dispose();
|
||||
_scheduler = null;
|
||||
}
|
||||
|
||||
protected override ID2D1Image? CreateEffect(IGraphicsDevicesAndContext devices)
|
||||
{
|
||||
var scheduler = ComputeExternalQueueScheduler.Create();
|
||||
var interopProvider = WaveOpticsInteropProvider.TryCreate(devices, scheduler, out var interopDevice);
|
||||
if (interopProvider is null || interopDevice is null)
|
||||
{
|
||||
scheduler.Dispose();
|
||||
return null;
|
||||
}
|
||||
|
||||
_scheduler = scheduler;
|
||||
|
||||
try
|
||||
{
|
||||
_interopProvider = interopProvider;
|
||||
_interopDomain = interopDevice.RegisterExternalDomain(interopProvider);
|
||||
_resourceSet = WaveOpticsResourceSet.Create(interopDevice, _interopDomain);
|
||||
_pipeline = WaveOpticsPipeline.TryCreate(interopDevice);
|
||||
}
|
||||
catch (Win32Exception)
|
||||
{
|
||||
ReleaseInterop();
|
||||
return null;
|
||||
}
|
||||
catch
|
||||
{
|
||||
ReleaseInterop();
|
||||
throw;
|
||||
}
|
||||
|
||||
if (_pipeline is null)
|
||||
{
|
||||
ReleaseInterop();
|
||||
return null;
|
||||
}
|
||||
|
||||
WaveOpticsCustomEffect? effect = null;
|
||||
Crop? outputCrop = null;
|
||||
ID2D1Image? outputCropOutput = null;
|
||||
AffineTransform2D? outputTransform = null;
|
||||
ID2D1Image? outputTransformOutput = null;
|
||||
ID2D1Image? output = null;
|
||||
try
|
||||
{
|
||||
effect = new WaveOpticsCustomEffect(devices);
|
||||
if (!effect.IsEnabled)
|
||||
{
|
||||
effect.Dispose();
|
||||
ReleaseInterop();
|
||||
return null;
|
||||
}
|
||||
outputCrop = new Crop(devices.DeviceContext);
|
||||
outputCropOutput = outputCrop.Output;
|
||||
outputTransform = new AffineTransform2D(devices.DeviceContext)
|
||||
{
|
||||
BorderMode = BorderMode.Hard,
|
||||
};
|
||||
outputTransform.SetInput(0, outputCropOutput, true);
|
||||
outputTransformOutput = outputTransform.Output;
|
||||
output = effect.Output;
|
||||
_effect = effect;
|
||||
_outputCrop = outputCrop;
|
||||
_outputCropOutput = outputCropOutput;
|
||||
_outputTransform = outputTransform;
|
||||
_outputTransformOutput = outputTransformOutput;
|
||||
disposer.Collect(effect);
|
||||
disposer.Collect(outputCrop);
|
||||
disposer.Collect(outputCropOutput);
|
||||
disposer.Collect(outputTransform);
|
||||
disposer.Collect(outputTransformOutput);
|
||||
disposer.Collect(output);
|
||||
return output;
|
||||
}
|
||||
catch
|
||||
{
|
||||
output?.Dispose();
|
||||
outputTransformOutput?.Dispose();
|
||||
outputTransform?.Dispose();
|
||||
outputCropOutput?.Dispose();
|
||||
outputCrop?.Dispose();
|
||||
effect?.Dispose();
|
||||
ReleaseInterop();
|
||||
throw;
|
||||
}
|
||||
}
|
||||
|
||||
protected override void setInput(ID2D1Image? inputImage)
|
||||
{
|
||||
try
|
||||
{
|
||||
SetInputCore(inputImage);
|
||||
}
|
||||
catch (Exception exception)
|
||||
{
|
||||
WaveOpticsTelemetry.Report(exception);
|
||||
throw;
|
||||
}
|
||||
}
|
||||
|
||||
private void SetInputCore(ID2D1Image? inputImage)
|
||||
{
|
||||
_effect?.SetInput(0, inputImage, true);
|
||||
if (!_hasOutput)
|
||||
_effect?.SetInput(1, inputImage, true);
|
||||
}
|
||||
|
||||
protected override void ClearEffectChain()
|
||||
{
|
||||
_effect?.SetInput(0, null, true);
|
||||
_effect?.SetInput(1, null, true);
|
||||
_outputCrop?.SetInput(0, null, true);
|
||||
_isFirst = true;
|
||||
_hasOutput = false;
|
||||
_hasOutputOffset = false;
|
||||
_hasCropRect = false;
|
||||
_hasRenderState = false;
|
||||
}
|
||||
|
||||
protected override void Dispose(bool disposing)
|
||||
{
|
||||
try
|
||||
{
|
||||
if (disposing)
|
||||
{
|
||||
ClearEffectChain();
|
||||
ReleaseInterop();
|
||||
}
|
||||
}
|
||||
catch (Exception exception)
|
||||
{
|
||||
WaveOpticsTelemetry.Report(exception);
|
||||
throw;
|
||||
}
|
||||
finally
|
||||
{
|
||||
base.Dispose(disposing);
|
||||
}
|
||||
}
|
||||
|
||||
private readonly record struct RenderState(
|
||||
float Gain,
|
||||
WaveOpticsPipeline.PixelRect Rect);
|
||||
}
|
||||
@@ -1,15 +0,0 @@
|
||||
using System.ComponentModel.DataAnnotations;
|
||||
|
||||
namespace WaveOptics.Effects;
|
||||
|
||||
public enum WaveOpticsQuality
|
||||
{
|
||||
[Display(Name = nameof(Texts.QualityDraft), ResourceType = typeof(Texts))]
|
||||
Draft,
|
||||
|
||||
[Display(Name = nameof(Texts.QualityStandard), ResourceType = typeof(Texts))]
|
||||
Standard,
|
||||
|
||||
[Display(Name = nameof(Texts.QualityHigh), ResourceType = typeof(Texts))]
|
||||
High,
|
||||
}
|
||||
@@ -1,210 +0,0 @@
|
||||
using System.Buffers;
|
||||
using System.Collections.Concurrent;
|
||||
using System.Numerics;
|
||||
using System.Runtime.CompilerServices;
|
||||
using System.Runtime.InteropServices;
|
||||
|
||||
namespace WaveOptics.Fourier;
|
||||
|
||||
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);
|
||||
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)
|
||||
{
|
||||
var count = real.Length;
|
||||
for (int source = 1, target = 0; source < count; source++)
|
||||
{
|
||||
var bit = count >> 1;
|
||||
for (; (target & bit) != 0; bit >>= 1)
|
||||
target ^= bit;
|
||||
target ^= bit;
|
||||
if (source < target)
|
||||
{
|
||||
(real[source], real[target]) = (real[target], real[source]);
|
||||
(imaginary[source], imaginary[target]) = (imaginary[target], imaginary[source]);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
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 Twiddles(int count, bool inverse)
|
||||
{
|
||||
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;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,95 +0,0 @@
|
||||
using WaveOptics.Fourier;
|
||||
|
||||
namespace WaveOptics.Optics;
|
||||
|
||||
internal sealed class FraunhoferKernelSampler
|
||||
{
|
||||
double[] real = [];
|
||||
double[] imaginary = [];
|
||||
double[] intensity = [];
|
||||
double[] columnReal = [];
|
||||
double[] columnImaginary = [];
|
||||
bool[] sampledColumns = [];
|
||||
|
||||
public bool TrySample(in PsfSpecification specification, Span<double> kernel)
|
||||
{
|
||||
var gridSize = specification.PupilGridSize;
|
||||
EnsureCapacity(gridSize);
|
||||
|
||||
var center = gridSize / 2;
|
||||
var reach = (int)(specification.PupilDiameterSamples / 2d);
|
||||
var firstRow = Math.Max(center - reach, 0);
|
||||
var lastRow = Math.Min(center + reach, gridSize - 1);
|
||||
if (FraunhoferPsfGenerator.BuildPupil(in specification, real, imaginary, firstRow, lastRow) == 0)
|
||||
return false;
|
||||
|
||||
for (var row = firstRow; row <= lastRow; row++)
|
||||
FastFourierTransform.Forward(real.AsSpan(row * gridSize, gridSize), imaginary.AsSpan(row * gridSize, gridSize));
|
||||
|
||||
MarkSampledColumns(in specification, center);
|
||||
for (var shiftedColumn = 0; shiftedColumn < gridSize; shiftedColumn++)
|
||||
{
|
||||
if (!sampledColumns[shiftedColumn])
|
||||
continue;
|
||||
|
||||
var column = (shiftedColumn + center) % gridSize;
|
||||
for (var row = 0; row < gridSize; row++)
|
||||
{
|
||||
var open = row >= firstRow && row <= lastRow;
|
||||
columnReal[row] = open ? real[row * gridSize + column] : 0d;
|
||||
columnImaginary[row] = open ? imaginary[row * gridSize + column] : 0d;
|
||||
}
|
||||
|
||||
FastFourierTransform.Forward(columnReal.AsSpan(0, gridSize), columnImaginary.AsSpan(0, gridSize));
|
||||
for (var row = 0; row < gridSize; row++)
|
||||
{
|
||||
var a = columnReal[row];
|
||||
var b = columnImaginary[row];
|
||||
intensity[(row + center) % gridSize * gridSize + shiftedColumn] = a * a + b * b;
|
||||
}
|
||||
}
|
||||
|
||||
var energy = FraunhoferPsfGenerator.SampleKernel(in specification, intensity, kernel);
|
||||
if (!double.IsFinite(energy) || energy <= 0)
|
||||
return false;
|
||||
|
||||
for (var index = 0; index < kernel.Length; index++)
|
||||
kernel[index] /= energy;
|
||||
return true;
|
||||
}
|
||||
|
||||
void MarkSampledColumns(in PsfSpecification specification, int center)
|
||||
{
|
||||
var gridSize = specification.PupilGridSize;
|
||||
var focalPlaneSamplePitch = FraunhoferPsfGenerator.FocalPlaneSamplePitch(in specification);
|
||||
var kernelRadius = specification.KernelSize / 2;
|
||||
Array.Clear(sampledColumns, 0, gridSize);
|
||||
for (var index = 0; index < specification.KernelSize; index++)
|
||||
{
|
||||
var position = FraunhoferPsfGenerator.SamplePosition(index, kernelRadius, center, specification.SensorPixelPitchMicrometers, focalPlaneSamplePitch);
|
||||
if (position < 0 || position > gridSize - 1)
|
||||
continue;
|
||||
|
||||
var lower = (int)Math.Floor(position);
|
||||
sampledColumns[lower] = true;
|
||||
sampledColumns[Math.Min(lower + 1, gridSize - 1)] = true;
|
||||
}
|
||||
}
|
||||
|
||||
void EnsureCapacity(int gridSize)
|
||||
{
|
||||
var area = gridSize * gridSize;
|
||||
if (real.Length < area)
|
||||
{
|
||||
real = new double[area];
|
||||
imaginary = new double[area];
|
||||
intensity = new double[area];
|
||||
}
|
||||
if (columnReal.Length < gridSize)
|
||||
{
|
||||
columnReal = new double[gridSize];
|
||||
columnImaginary = new double[gridSize];
|
||||
sampledColumns = new bool[gridSize];
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,243 +0,0 @@
|
||||
using System.Buffers;
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
using System.Numerics;
|
||||
using System.Runtime.CompilerServices;
|
||||
using System.Runtime.InteropServices;
|
||||
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)
|
||||
{
|
||||
if (!TryGenerate(descriptor, out var result))
|
||||
throw new InvalidOperationException();
|
||||
return result;
|
||||
}
|
||||
|
||||
public bool TryGenerate(PsfDescriptor descriptor, [NotNullWhen(true)] out PsfGenerationResult? result)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(descriptor);
|
||||
|
||||
result = null;
|
||||
var specification = PsfSpecification.Of(descriptor);
|
||||
var gridSize = specification.PupilGridSize;
|
||||
var area = gridSize * gridSize;
|
||||
var real = ArrayPool<double>.Shared.Rent(area);
|
||||
var imaginary = ArrayPool<double>.Shared.Rent(area);
|
||||
var intensity = ArrayPool<double>.Shared.Rent(area);
|
||||
try
|
||||
{
|
||||
var openSampleCount = BuildPupil(in specification, real, imaginary, 0, gridSize - 1);
|
||||
if (openSampleCount == 0)
|
||||
return false;
|
||||
|
||||
FastFourierTransform.Forward2D(real, imaginary, gridSize, gridSize);
|
||||
|
||||
var fullEnergy = ComputeShiftedIntensity(real, imaginary, intensity, gridSize);
|
||||
if (!double.IsFinite(fullEnergy) || fullEnergy <= 0)
|
||||
return false;
|
||||
|
||||
var kernelSize = specification.KernelSize;
|
||||
var kernel = new double[kernelSize * kernelSize];
|
||||
var rawKernelEnergy = SampleKernel(in specification, intensity, kernel);
|
||||
if (!double.IsFinite(rawKernelEnergy) || rawKernelEnergy <= 0)
|
||||
return false;
|
||||
|
||||
var psfKernel = new PsfKernel(kernelSize, kernel);
|
||||
var diagnostics = new PsfDiagnostics(
|
||||
openSampleCount,
|
||||
FocalPlaneSamplePitch(in specification),
|
||||
rawKernelEnergy / fullEnergy,
|
||||
Peak(psfKernel.Values.Span));
|
||||
result = new PsfGenerationResult(psfKernel, diagnostics);
|
||||
return true;
|
||||
}
|
||||
finally
|
||||
{
|
||||
ArrayPool<double>.Shared.Return(real);
|
||||
ArrayPool<double>.Shared.Return(imaginary);
|
||||
ArrayPool<double>.Shared.Return(intensity);
|
||||
}
|
||||
}
|
||||
|
||||
internal static int BuildPupil(in PsfSpecification specification, double[] real, double[] imaginary, int firstRow, int lastRow)
|
||||
{
|
||||
var gridSize = specification.PupilGridSize;
|
||||
var center = gridSize / 2;
|
||||
var pupilRadius = specification.PupilDiameterSamples / 2d;
|
||||
var rotation = specification.BladeRotationDegrees * Math.PI / 180d;
|
||||
var openSampleCount = 0;
|
||||
|
||||
for (var y = firstRow; y <= lastRow; y++)
|
||||
{
|
||||
var normalizedY = (y - center) / pupilRadius;
|
||||
var row = y * gridSize;
|
||||
for (var x = 0; x < gridSize; x++)
|
||||
{
|
||||
var index = row + x;
|
||||
var normalizedX = (x - center) / pupilRadius;
|
||||
if (IsInsideAperture(normalizedX, normalizedY, in specification, rotation))
|
||||
{
|
||||
var waves = ZernikeWavefront.Evaluate(normalizedX, normalizedY, specification.Aberration);
|
||||
var (sin, cos) = Math.SinCos(TwoPi * waves);
|
||||
real[index] = cos;
|
||||
imaginary[index] = sin;
|
||||
openSampleCount++;
|
||||
}
|
||||
else
|
||||
{
|
||||
real[index] = 0;
|
||||
imaginary[index] = 0;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return openSampleCount;
|
||||
}
|
||||
|
||||
internal static double FocalPlaneSamplePitch(in PsfSpecification specification)
|
||||
{
|
||||
var wavelengthMicrometers = specification.WavelengthNanometers / 1000d;
|
||||
return wavelengthMicrometers * specification.FNumber * specification.PupilDiameterSamples / specification.PupilGridSize;
|
||||
}
|
||||
|
||||
internal static double SamplePosition(int index, int kernelRadius, int center, double pixelPitch, double focalPlaneSamplePitch)
|
||||
=> center + (index - kernelRadius) * pixelPitch / focalPlaneSamplePitch;
|
||||
|
||||
internal static double SampleKernel(in PsfSpecification specification, double[] intensity, Span<double> kernel)
|
||||
{
|
||||
var gridSize = specification.PupilGridSize;
|
||||
var focalPlaneSamplePitch = FocalPlaneSamplePitch(in specification);
|
||||
var center = gridSize / 2;
|
||||
var kernelSize = specification.KernelSize;
|
||||
var kernelRadius = kernelSize / 2;
|
||||
var rawKernelEnergy = 0d;
|
||||
|
||||
for (var y = 0; y < kernelSize; y++)
|
||||
{
|
||||
var sampleY = SamplePosition(y, kernelRadius, center, specification.SensorPixelPitchMicrometers, focalPlaneSamplePitch);
|
||||
for (var x = 0; x < kernelSize; x++)
|
||||
{
|
||||
var sampleX = SamplePosition(x, kernelRadius, center, specification.SensorPixelPitchMicrometers, focalPlaneSamplePitch);
|
||||
var value = SampleBilinear(intensity, gridSize, sampleX, sampleY);
|
||||
kernel[y * kernelSize + x] = value;
|
||||
rawKernelEnergy += value;
|
||||
}
|
||||
}
|
||||
|
||||
return rawKernelEnergy;
|
||||
}
|
||||
|
||||
static double ComputeShiftedIntensity(double[] real, double[] imaginary, double[] intensity, int gridSize)
|
||||
{
|
||||
var center = gridSize / 2;
|
||||
var fullEnergy = 0d;
|
||||
for (var y = 0; y < gridSize; y++)
|
||||
{
|
||||
var sourceRow = ((y + center) % gridSize) * gridSize;
|
||||
var destinationRow = y * gridSize;
|
||||
fullEnergy += Power(
|
||||
real.AsSpan(sourceRow + center, gridSize - center),
|
||||
imaginary.AsSpan(sourceRow + center, gridSize - center),
|
||||
intensity.AsSpan(destinationRow, gridSize - center));
|
||||
fullEnergy += Power(
|
||||
real.AsSpan(sourceRow, center),
|
||||
imaginary.AsSpan(sourceRow, center),
|
||||
intensity.AsSpan(destinationRow + gridSize - center, center));
|
||||
}
|
||||
return fullEnergy;
|
||||
}
|
||||
|
||||
static double Power(ReadOnlySpan<double> real, ReadOnlySpan<double> imaginary, Span<double> intensity)
|
||||
{
|
||||
var count = real.Length;
|
||||
ref var realBase = ref MemoryMarshal.GetReference(real);
|
||||
ref var imaginaryBase = ref MemoryMarshal.GetReference(imaginary);
|
||||
ref var intensityBase = ref MemoryMarshal.GetReference(intensity);
|
||||
var sum = 0d;
|
||||
var index = 0;
|
||||
if (Vector.IsHardwareAccelerated)
|
||||
{
|
||||
var accumulator = Vector<double>.Zero;
|
||||
var width = Vector<double>.Count;
|
||||
for (; index + width <= count; index += width)
|
||||
{
|
||||
var a = Vector.LoadUnsafe(ref Unsafe.Add(ref realBase, index));
|
||||
var b = Vector.LoadUnsafe(ref Unsafe.Add(ref imaginaryBase, index));
|
||||
var power = a * a + b * b;
|
||||
power.StoreUnsafe(ref Unsafe.Add(ref intensityBase, index));
|
||||
accumulator += power;
|
||||
}
|
||||
sum += Vector.Sum(accumulator);
|
||||
}
|
||||
for (; index < count; index++)
|
||||
{
|
||||
var a = Unsafe.Add(ref realBase, index);
|
||||
var b = Unsafe.Add(ref imaginaryBase, index);
|
||||
var power = a * a + b * b;
|
||||
Unsafe.Add(ref intensityBase, index) = power;
|
||||
sum += power;
|
||||
}
|
||||
return sum;
|
||||
}
|
||||
|
||||
static double Peak(ReadOnlySpan<double> values)
|
||||
{
|
||||
var peak = 0d;
|
||||
foreach (var value in values)
|
||||
{
|
||||
if (value > peak)
|
||||
peak = value;
|
||||
}
|
||||
return peak;
|
||||
}
|
||||
|
||||
static bool IsInsideAperture(double x, double y, in PsfSpecification specification, double rotation)
|
||||
{
|
||||
var radiusSquared = x * x + y * y;
|
||||
var obstructionSquared = specification.CentralObstructionRatio * specification.CentralObstructionRatio;
|
||||
if (radiusSquared > 1d || radiusSquared < obstructionSquared)
|
||||
return false;
|
||||
if (specification.ApertureShape == ApertureShape.Circular)
|
||||
return true;
|
||||
|
||||
var radius = Math.Sqrt(radiusSquared);
|
||||
if (radius == 0)
|
||||
return specification.CentralObstructionRatio == 0;
|
||||
var sector = TwoPi / specification.BladeCount;
|
||||
var angle = Math.Atan2(y, x) - rotation;
|
||||
var folded = angle - sector * Math.Round(angle / sector);
|
||||
var boundary = Math.Cos(Math.PI / specification.BladeCount) / Math.Cos(folded);
|
||||
return radius <= boundary;
|
||||
}
|
||||
|
||||
static double SampleBilinear(double[] values, int size, double x, double y)
|
||||
{
|
||||
if (x < 0 || y < 0 || x > size - 1 || y > size - 1)
|
||||
return 0;
|
||||
|
||||
var x0 = (int)Math.Floor(x);
|
||||
var y0 = (int)Math.Floor(y);
|
||||
var x1 = Math.Min(x0 + 1, size - 1);
|
||||
var y1 = Math.Min(y0 + 1, size - 1);
|
||||
var tx = x - x0;
|
||||
var ty = y - y0;
|
||||
var top = values[y0 * size + x0] * (1 - tx) + values[y0 * size + x1] * tx;
|
||||
var bottom = values[y1 * size + x0] * (1 - tx) + values[y1 * size + x1] * tx;
|
||||
return top * (1 - ty) + bottom * ty;
|
||||
}
|
||||
}
|
||||
@@ -1,31 +0,0 @@
|
||||
using WaveOptics.Abstractions;
|
||||
|
||||
namespace WaveOptics.Optics;
|
||||
|
||||
internal readonly record struct PsfSpecification(
|
||||
int PupilGridSize,
|
||||
int PupilDiameterSamples,
|
||||
int KernelSize,
|
||||
double WavelengthNanometers,
|
||||
double FNumber,
|
||||
double SensorPixelPitchMicrometers,
|
||||
ApertureShape ApertureShape,
|
||||
int BladeCount,
|
||||
double BladeRotationDegrees,
|
||||
double CentralObstructionRatio,
|
||||
WavefrontAberration Aberration)
|
||||
{
|
||||
public static PsfSpecification Of(PsfDescriptor descriptor)
|
||||
=> new(
|
||||
descriptor.PupilGridSize,
|
||||
descriptor.PupilDiameterSamples,
|
||||
descriptor.KernelSize,
|
||||
descriptor.WavelengthNanometers,
|
||||
descriptor.FNumber,
|
||||
descriptor.SensorPixelPitchMicrometers,
|
||||
descriptor.ApertureShape,
|
||||
descriptor.BladeCount,
|
||||
descriptor.BladeRotationDegrees,
|
||||
descriptor.CentralObstructionRatio,
|
||||
descriptor.Aberration);
|
||||
}
|
||||
@@ -1,201 +0,0 @@
|
||||
using System.Numerics;
|
||||
|
||||
namespace WaveOptics.Optics;
|
||||
|
||||
internal sealed class SeparableKernel
|
||||
{
|
||||
readonly Comparison<int> descending;
|
||||
double[] work = [];
|
||||
double[] basis = [];
|
||||
double[] singularValues = [];
|
||||
int[] order = [];
|
||||
float[] horizontal = [];
|
||||
float[] vertical = [];
|
||||
|
||||
public SeparableKernel()
|
||||
{
|
||||
descending = (left, right) => singularValues[right].CompareTo(singularValues[left]);
|
||||
}
|
||||
|
||||
public int Size { get; private set; }
|
||||
public int Rank { get; private set; }
|
||||
public double ResidualEnergyRatio { get; private set; }
|
||||
public double Sum { get; private set; }
|
||||
public ReadOnlySpan<float> Horizontal => horizontal.AsSpan(0, Rank * Size);
|
||||
public ReadOnlySpan<float> Vertical => vertical.AsSpan(0, Rank * Size);
|
||||
|
||||
public static SeparableKernel Decompose(ReadOnlySpan<double> kernel, int size, double residualEnergyRatio, int maximumRank)
|
||||
{
|
||||
var separable = new SeparableKernel();
|
||||
separable.Update(kernel, size, residualEnergyRatio, maximumRank);
|
||||
return separable;
|
||||
}
|
||||
|
||||
public void Update(ReadOnlySpan<double> kernel, int size, double residualEnergyRatio, int maximumRank)
|
||||
{
|
||||
var area = size * size;
|
||||
if (work.Length < area)
|
||||
{
|
||||
work = new double[area];
|
||||
basis = new double[area];
|
||||
horizontal = new float[area];
|
||||
vertical = new float[area];
|
||||
}
|
||||
if (order.Length != size)
|
||||
{
|
||||
singularValues = new double[size];
|
||||
order = new int[size];
|
||||
}
|
||||
|
||||
for (var row = 0; row < size; row++)
|
||||
{
|
||||
for (var column = 0; column < size; column++)
|
||||
work[column * size + row] = kernel[row * size + column];
|
||||
}
|
||||
Array.Clear(basis, 0, area);
|
||||
for (var i = 0; i < size; i++)
|
||||
basis[i * size + i] = 1d;
|
||||
|
||||
OrthogonalizeColumns(work, basis, size);
|
||||
|
||||
var totalEnergy = 0d;
|
||||
for (var column = 0; column < size; column++)
|
||||
{
|
||||
var norm = 0d;
|
||||
for (var row = 0; row < size; row++)
|
||||
{
|
||||
var value = work[column * size + row];
|
||||
norm += value * value;
|
||||
}
|
||||
singularValues[column] = Math.Sqrt(norm);
|
||||
order[column] = column;
|
||||
totalEnergy += norm;
|
||||
}
|
||||
|
||||
Array.Sort(order, descending);
|
||||
|
||||
var largest = singularValues[order[0]];
|
||||
var significant = 0;
|
||||
var threshold = largest * 1e-12;
|
||||
for (var i = 0; i < size && singularValues[order[i]] > threshold; i++)
|
||||
significant++;
|
||||
significant = Math.Max(significant, 1);
|
||||
|
||||
var rank = significant;
|
||||
if (residualEnergyRatio > 0 && totalEnergy > 0)
|
||||
{
|
||||
var retained = 0d;
|
||||
var target = (1d - residualEnergyRatio) * totalEnergy;
|
||||
rank = 0;
|
||||
for (var i = 0; i < significant; i++)
|
||||
{
|
||||
retained += singularValues[order[i]] * singularValues[order[i]];
|
||||
rank++;
|
||||
if (retained >= target)
|
||||
break;
|
||||
}
|
||||
}
|
||||
rank = Math.Clamp(rank, 1, Math.Min(maximumRank, significant));
|
||||
|
||||
var retainedEnergy = 0d;
|
||||
for (var i = 0; i < rank; i++)
|
||||
retainedEnergy += singularValues[order[i]] * singularValues[order[i]];
|
||||
var residual = totalEnergy > 0 ? Math.Max(0d, (totalEnergy - retainedEnergy) / totalEnergy) : 0d;
|
||||
|
||||
var sum = 0d;
|
||||
for (var term = 0; term < rank; term++)
|
||||
{
|
||||
var column = order[term];
|
||||
var singularValue = singularValues[column];
|
||||
var inverse = singularValue > 0 ? 1d / singularValue : 0d;
|
||||
var horizontalBase = term * size;
|
||||
var horizontalSum = 0d;
|
||||
var verticalSum = 0d;
|
||||
for (var k = 0; k < size; k++)
|
||||
{
|
||||
horizontal[horizontalBase + k] = (float)(basis[column * size + k]);
|
||||
vertical[horizontalBase + k] = (float)(work[column * size + k] * inverse * singularValue);
|
||||
horizontalSum += horizontal[horizontalBase + k];
|
||||
verticalSum += vertical[horizontalBase + k];
|
||||
}
|
||||
sum += horizontalSum * verticalSum;
|
||||
}
|
||||
|
||||
Size = size;
|
||||
Rank = rank;
|
||||
ResidualEnergyRatio = residual;
|
||||
Sum = sum;
|
||||
}
|
||||
|
||||
static void OrthogonalizeColumns(double[] work, double[] basis, int size)
|
||||
{
|
||||
const int maximumSweeps = 60;
|
||||
const double tolerance = 1e-15;
|
||||
for (var sweep = 0; sweep < maximumSweeps; sweep++)
|
||||
{
|
||||
var converged = true;
|
||||
for (var p = 0; p < size - 1; p++)
|
||||
{
|
||||
var workP = work.AsSpan(p * size, size);
|
||||
var basisP = basis.AsSpan(p * size, size);
|
||||
for (var q = p + 1; q < size; q++)
|
||||
{
|
||||
var workQ = work.AsSpan(q * size, size);
|
||||
var alpha = 0d;
|
||||
var beta = 0d;
|
||||
var gamma = 0d;
|
||||
for (var k = 0; k < size; k++)
|
||||
{
|
||||
var wp = workP[k];
|
||||
var wq = workQ[k];
|
||||
alpha += wp * wp;
|
||||
beta += wq * wq;
|
||||
gamma += wp * wq;
|
||||
}
|
||||
|
||||
if (Math.Abs(gamma) <= tolerance * Math.Sqrt(alpha * beta))
|
||||
continue;
|
||||
|
||||
converged = false;
|
||||
var zeta = (beta - alpha) / (2d * gamma);
|
||||
var t = Math.Sign(zeta) / (Math.Abs(zeta) + Math.Sqrt(1d + zeta * zeta));
|
||||
if (zeta == 0d)
|
||||
t = 1d;
|
||||
var c = 1d / Math.Sqrt(1d + t * t);
|
||||
var s = c * t;
|
||||
|
||||
var basisQ = basis.AsSpan(q * size, size);
|
||||
Rotate(workP, workQ, c, s);
|
||||
Rotate(basisP, basisQ, c, s);
|
||||
}
|
||||
}
|
||||
if (converged)
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
static void Rotate(Span<double> first, Span<double> second, double c, double s)
|
||||
{
|
||||
var index = 0;
|
||||
var width = Vector<double>.Count;
|
||||
if (Vector.IsHardwareAccelerated && first.Length >= width)
|
||||
{
|
||||
var cosine = new Vector<double>(c);
|
||||
var sine = new Vector<double>(s);
|
||||
for (; index + width <= first.Length; index += width)
|
||||
{
|
||||
var a = new Vector<double>(first[index..]);
|
||||
var b = new Vector<double>(second[index..]);
|
||||
(cosine * a - sine * b).CopyTo(first[index..]);
|
||||
(sine * a + cosine * b).CopyTo(second[index..]);
|
||||
}
|
||||
}
|
||||
for (; index < first.Length; index++)
|
||||
{
|
||||
var a = first[index];
|
||||
var b = second[index];
|
||||
first[index] = c * a - s * b;
|
||||
second[index] = s * a + c * b;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,34 +0,0 @@
|
||||
using WaveOptics.Abstractions;
|
||||
|
||||
namespace WaveOptics.Optics;
|
||||
|
||||
internal static class ZernikeWavefront
|
||||
{
|
||||
static readonly double Sqrt3 = Math.Sqrt(3);
|
||||
static readonly double Sqrt5 = Math.Sqrt(5);
|
||||
static readonly double Sqrt6 = Math.Sqrt(6);
|
||||
static readonly double Sqrt8 = Math.Sqrt(8);
|
||||
|
||||
public static double Evaluate(double x, double y, WavefrontAberration aberration)
|
||||
{
|
||||
var radiusSquared = x * x + y * y;
|
||||
var radiusFourth = radiusSquared * radiusSquared;
|
||||
var defocus = Sqrt3 * (2 * radiusSquared - 1);
|
||||
var astigmatismVertical = Sqrt6 * (x * x - y * y);
|
||||
var astigmatismOblique = 2 * Sqrt6 * x * y;
|
||||
var comaHorizontal = Sqrt8 * (3 * radiusSquared - 2) * x;
|
||||
var comaVertical = Sqrt8 * (3 * radiusSquared - 2) * y;
|
||||
var trefoilHorizontal = Sqrt8 * x * (x * x - 3 * y * y);
|
||||
var trefoilVertical = Sqrt8 * y * (3 * x * x - y * y);
|
||||
var spherical = Sqrt5 * (6 * radiusFourth - 6 * radiusSquared + 1);
|
||||
|
||||
return aberration.DefocusWaves * defocus
|
||||
+ aberration.AstigmatismVerticalWaves * astigmatismVertical
|
||||
+ aberration.AstigmatismObliqueWaves * astigmatismOblique
|
||||
+ aberration.ComaHorizontalWaves * comaHorizontal
|
||||
+ aberration.ComaVerticalWaves * comaVertical
|
||||
+ aberration.TrefoilHorizontalWaves * trefoilHorizontal
|
||||
+ aberration.TrefoilVerticalWaves * trefoilVertical
|
||||
+ aberration.SphericalWaves * spherical;
|
||||
}
|
||||
}
|
||||
@@ -1,6 +0,0 @@
|
||||
namespace WaveOptics.Rendering;
|
||||
|
||||
internal static class ShaderResourceUri
|
||||
{
|
||||
public static Uri Get(string shaderName) => new($"pack://application:,,,/WaveOptics;component/Resources/Shader/{shaderName}.cso", UriKind.Absolute);
|
||||
}
|
||||
@@ -1,98 +0,0 @@
|
||||
using System.Runtime.InteropServices;
|
||||
using Vortice;
|
||||
using Vortice.Direct2D1;
|
||||
using YukkuriMovieMaker.Commons;
|
||||
using YukkuriMovieMaker.Player.Video;
|
||||
|
||||
namespace WaveOptics.Rendering;
|
||||
|
||||
internal sealed class WaveOpticsCustomEffect(IGraphicsDevicesAndContext devices)
|
||||
: D2D1CustomShaderEffectBase(Create<EffectImpl>(devices))
|
||||
{
|
||||
public float Amount { set => SetValue((int)EffectImpl.Properties.Amount, value); }
|
||||
|
||||
[CustomEffect(2)]
|
||||
private sealed class EffectImpl : D2D1CustomShaderEffectImplBase<EffectImpl>
|
||||
{
|
||||
private ConstantBuffer _cb;
|
||||
|
||||
[CustomEffectProperty(PropertyType.Float, (int)Properties.Amount)]
|
||||
public float Amount
|
||||
{
|
||||
get => _cb.Amount;
|
||||
set
|
||||
{
|
||||
_cb.Amount = Math.Clamp(value, 0f, 1f);
|
||||
UpdateConstants();
|
||||
}
|
||||
}
|
||||
|
||||
public EffectImpl() : base(ShaderResourceUri.Get("WaveOptics"))
|
||||
{
|
||||
}
|
||||
|
||||
protected override void UpdateConstants()
|
||||
{
|
||||
if (drawInformation is null)
|
||||
return;
|
||||
|
||||
try
|
||||
{
|
||||
drawInformation.SetPixelShaderConstantBuffer(_cb);
|
||||
}
|
||||
catch (Exception exception)
|
||||
{
|
||||
WaveOpticsTelemetry.Report(exception);
|
||||
throw;
|
||||
}
|
||||
}
|
||||
|
||||
public override void MapInputRectsToOutputRect(
|
||||
RawRect[] inputRects,
|
||||
RawRect[] inputOpaqueSubRects,
|
||||
out RawRect outputRect,
|
||||
out RawRect outputOpaqueSubRect)
|
||||
{
|
||||
if (inputRects.Length == 0)
|
||||
{
|
||||
outputRect = default;
|
||||
outputOpaqueSubRect = default;
|
||||
return;
|
||||
}
|
||||
|
||||
var union = inputRects[0];
|
||||
var inputCount = _cb.Amount <= 0f ? 1 : inputRects.Length;
|
||||
for (var i = 1; i < inputCount; i++)
|
||||
{
|
||||
var rect = inputRects[i];
|
||||
union = new RawRect(
|
||||
Math.Min(union.Left, rect.Left),
|
||||
Math.Min(union.Top, rect.Top),
|
||||
Math.Max(union.Right, rect.Right),
|
||||
Math.Max(union.Bottom, rect.Bottom));
|
||||
}
|
||||
outputRect = union;
|
||||
outputOpaqueSubRect = default;
|
||||
}
|
||||
|
||||
public override void MapOutputRectToInputRects(RawRect outputRect, RawRect[] inputRects)
|
||||
{
|
||||
for (var i = 0; i < inputRects.Length; i++)
|
||||
inputRects[i] = outputRect;
|
||||
}
|
||||
|
||||
[StructLayout(LayoutKind.Sequential)]
|
||||
private struct ConstantBuffer
|
||||
{
|
||||
public float Amount;
|
||||
public float Pad0;
|
||||
public float Pad1;
|
||||
public float Pad2;
|
||||
}
|
||||
|
||||
public enum Properties
|
||||
{
|
||||
Amount = 0,
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,89 +0,0 @@
|
||||
using ComputeWeave;
|
||||
using Vortice.Direct2D1;
|
||||
using Vortice.Direct3D11;
|
||||
using YukkuriMovieMaker.Commons;
|
||||
|
||||
namespace WaveOptics.Rendering;
|
||||
|
||||
internal sealed class WaveOpticsInteropProvider : ComputeExternalDirect3D11Provider
|
||||
{
|
||||
private readonly ID2D1DeviceContext6 _renderContext;
|
||||
|
||||
private WaveOpticsInteropProvider(
|
||||
ID3D11Device1 device,
|
||||
ID3D11DeviceContext4 context,
|
||||
ID2D1DeviceContext6 renderContext,
|
||||
ComputeExternalQueueScheduler scheduler)
|
||||
: base(device.NativePointer, context.NativePointer, renderContext.NativePointer, scheduler)
|
||||
{
|
||||
_renderContext = renderContext;
|
||||
}
|
||||
|
||||
public ID2D1DeviceContext6 RenderContext => _renderContext;
|
||||
|
||||
public static WaveOpticsInteropProvider? TryCreate(
|
||||
IGraphicsDevicesAndContext devices,
|
||||
ComputeExternalQueueScheduler scheduler,
|
||||
out GraphicsDevice? graphicsDevice)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(scheduler);
|
||||
|
||||
graphicsDevice = null;
|
||||
|
||||
ID3D11Device1? device = null;
|
||||
ID3D11DeviceContext4? context = null;
|
||||
ID2D1DeviceContext6? renderContext = null;
|
||||
try
|
||||
{
|
||||
if (!GraphicsDevice.TryGetDevice(new ExternalAdapterIdentity(devices.DXGI.Adapter.Description.Luid), out graphicsDevice))
|
||||
return null;
|
||||
|
||||
device = devices.D3D.Device.QueryInterface<ID3D11Device1>();
|
||||
context = devices.D3D.DeviceContext.QueryInterface<ID3D11DeviceContext4>();
|
||||
renderContext = devices.D2D.Device.CreateDeviceContext(DeviceContextOptions.EnableMultithreadedOptimizations);
|
||||
var provider = new WaveOpticsInteropProvider(device, context, renderContext, scheduler);
|
||||
renderContext = null;
|
||||
return provider;
|
||||
}
|
||||
catch
|
||||
{
|
||||
graphicsDevice = null;
|
||||
return null;
|
||||
}
|
||||
finally
|
||||
{
|
||||
renderContext?.Dispose();
|
||||
context?.Dispose();
|
||||
device?.Dispose();
|
||||
}
|
||||
}
|
||||
|
||||
protected override void DisposeCore()
|
||||
{
|
||||
_renderContext.Dispose();
|
||||
}
|
||||
}
|
||||
|
||||
[ComputeInteropResourceSet]
|
||||
internal sealed partial class WaveOpticsResourceSet
|
||||
{
|
||||
[ComputeSharedTexture(
|
||||
ComputeResourceResizePolicy.Exact,
|
||||
ComputeResourceAccess.ReadWrite,
|
||||
ExternalResourceAccess.Write,
|
||||
ExternalTextureUsage.RenderTarget,
|
||||
ComputeAlphaMode.Premultiplied,
|
||||
ComputeSharedTextureInitialOwner.External,
|
||||
ComputeResourceRecovery.RecreateFromHost)]
|
||||
private readonly SharedTextureSlot<Bgra32, Float4, ExternalDirect3D11TextureView> _source;
|
||||
|
||||
[ComputeSharedTexture(
|
||||
ComputeResourceResizePolicy.GrowOnly,
|
||||
ComputeResourceAccess.ReadWrite,
|
||||
ExternalResourceAccess.Read,
|
||||
ExternalTextureUsage.Sampled,
|
||||
ComputeAlphaMode.Premultiplied,
|
||||
ComputeSharedTextureInitialOwner.Compute,
|
||||
ComputeResourceRecovery.Recompute)]
|
||||
private readonly SharedTextureSlot<Bgra32, Float4, ExternalDirect3D11TextureView> _output;
|
||||
}
|
||||
@@ -1,391 +0,0 @@
|
||||
using ComputeWeave;
|
||||
|
||||
namespace WaveOptics.Rendering;
|
||||
|
||||
[ThreadGroupSize(DefaultThreadGroupSizes.X)]
|
||||
[GeneratedComputeShaderDescriptor]
|
||||
internal readonly partial struct FillIntShader(
|
||||
ReadWriteBuffer<int> values,
|
||||
int length,
|
||||
int value) : IComputeShader
|
||||
{
|
||||
private readonly ReadWriteBuffer<int> values = values;
|
||||
private readonly int length = length;
|
||||
private readonly int value = value;
|
||||
|
||||
public void Execute()
|
||||
{
|
||||
var index = ThreadIds.X;
|
||||
if (index >= length)
|
||||
return;
|
||||
values[index] = value;
|
||||
}
|
||||
}
|
||||
|
||||
[ThreadGroupSize(DefaultThreadGroupSizes.X)]
|
||||
[GeneratedComputeShaderDescriptor]
|
||||
internal readonly partial struct SourceHashResetShader(
|
||||
ReadWriteBuffer<int> scratch) : IComputeShader
|
||||
{
|
||||
private readonly ReadWriteBuffer<int> scratch = scratch;
|
||||
|
||||
public void Execute()
|
||||
{
|
||||
if (ThreadIds.X != 0)
|
||||
return;
|
||||
scratch[WaveOpticsSettings.ScratchLitCount] = 0;
|
||||
scratch[WaveOpticsSettings.ScratchBoundsMinX] = 2147483647;
|
||||
scratch[WaveOpticsSettings.ScratchBoundsMinY] = 2147483647;
|
||||
scratch[WaveOpticsSettings.ScratchBoundsMaxX] = -2147483648;
|
||||
scratch[WaveOpticsSettings.ScratchBoundsMaxY] = -2147483648;
|
||||
scratch[WaveOpticsSettings.ScratchHashSum] = 0;
|
||||
scratch[WaveOpticsSettings.ScratchHashMix] = 0;
|
||||
}
|
||||
}
|
||||
|
||||
[ThreadGroupSize(DefaultThreadGroupSizes.XY)]
|
||||
[GeneratedComputeShaderDescriptor]
|
||||
internal readonly partial struct SourceHashShader(
|
||||
ReadWriteTexture2D<Bgra32, Float4> source,
|
||||
ReadWriteBuffer<int> scratch,
|
||||
int sourceX,
|
||||
int sourceY,
|
||||
int sourceWidth,
|
||||
int sourceHeight) : IComputeShader
|
||||
{
|
||||
private readonly ReadWriteTexture2D<Bgra32, Float4> source = source;
|
||||
private readonly ReadWriteBuffer<int> scratch = scratch;
|
||||
private readonly int sourceX = sourceX;
|
||||
private readonly int sourceY = sourceY;
|
||||
private readonly int sourceWidth = sourceWidth;
|
||||
private readonly int sourceHeight = sourceHeight;
|
||||
|
||||
public void Execute()
|
||||
{
|
||||
var first = ThreadIds.X * WaveOpticsSettings.SourceHashSpan;
|
||||
var y = ThreadIds.Y;
|
||||
if (first >= sourceWidth || y >= sourceHeight)
|
||||
return;
|
||||
|
||||
var count = 0;
|
||||
var sum = 0;
|
||||
var mix = 0;
|
||||
var minimumX = 2147483647;
|
||||
var maximumX = -2147483648;
|
||||
var last = Hlsl.Min(first + WaveOpticsSettings.SourceHashSpan, sourceWidth);
|
||||
for (var x = first; x < last; x++)
|
||||
{
|
||||
var color = source[new Int2(x, y)];
|
||||
var quantized = ((uint)(color.X * 255f + 0.5f) << 24)
|
||||
| ((uint)(color.Y * 255f + 0.5f) << 16)
|
||||
| ((uint)(color.Z * 255f + 0.5f) << 8)
|
||||
| (uint)(color.W * 255f + 0.5f);
|
||||
if (quantized == 0u)
|
||||
continue;
|
||||
|
||||
var mixed = ((uint)(y * sourceWidth + x) * 0x9E3779B9u) ^ (quantized * 0x85EBCA6Bu);
|
||||
mixed ^= mixed >> 16;
|
||||
mixed *= 0x85EBCA6Bu;
|
||||
mixed ^= mixed >> 13;
|
||||
sum += (int)mixed;
|
||||
mix ^= (int)(mixed * 0xC2B2AE35u);
|
||||
count++;
|
||||
minimumX = Hlsl.Min(minimumX, sourceX + x);
|
||||
maximumX = Hlsl.Max(maximumX, sourceX + x);
|
||||
}
|
||||
|
||||
if (count == 0)
|
||||
return;
|
||||
Hlsl.InterlockedAdd(ref scratch[WaveOpticsSettings.ScratchHashSum], sum);
|
||||
Hlsl.InterlockedXor(ref scratch[WaveOpticsSettings.ScratchHashMix], mix);
|
||||
Hlsl.InterlockedAdd(ref scratch[WaveOpticsSettings.ScratchLitCount], count);
|
||||
Hlsl.InterlockedMin(ref scratch[WaveOpticsSettings.ScratchBoundsMinX], minimumX);
|
||||
Hlsl.InterlockedMin(ref scratch[WaveOpticsSettings.ScratchBoundsMinY], sourceY + y);
|
||||
Hlsl.InterlockedMax(ref scratch[WaveOpticsSettings.ScratchBoundsMaxX], maximumX);
|
||||
Hlsl.InterlockedMax(ref scratch[WaveOpticsSettings.ScratchBoundsMaxY], sourceY + y);
|
||||
}
|
||||
}
|
||||
|
||||
[ThreadGroupSize(DefaultThreadGroupSizes.XY)]
|
||||
[GeneratedComputeShaderDescriptor]
|
||||
internal readonly partial struct HorizontalPassShader(
|
||||
ReadWriteTexture2D<Bgra32, Float4> source,
|
||||
ReadOnlyBuffer<float> weights,
|
||||
ReadWriteBuffer<Float4> horizontal,
|
||||
int weightOffset,
|
||||
int radius,
|
||||
int regionX,
|
||||
int regionY,
|
||||
int regionWidth,
|
||||
int regionHeight,
|
||||
int canvasWidth,
|
||||
int sourceX,
|
||||
int sourceY,
|
||||
int sourceWidth) : IComputeShader
|
||||
{
|
||||
private readonly ReadWriteTexture2D<Bgra32, Float4> source = source;
|
||||
private readonly ReadOnlyBuffer<float> weights = weights;
|
||||
private readonly ReadWriteBuffer<Float4> horizontal = horizontal;
|
||||
private readonly int weightOffset = weightOffset;
|
||||
private readonly int radius = radius;
|
||||
private readonly int regionX = regionX;
|
||||
private readonly int regionY = regionY;
|
||||
private readonly int regionWidth = regionWidth;
|
||||
private readonly int regionHeight = regionHeight;
|
||||
private readonly int canvasWidth = canvasWidth;
|
||||
private readonly int sourceX = sourceX;
|
||||
private readonly int sourceY = sourceY;
|
||||
private readonly int sourceWidth = sourceWidth;
|
||||
|
||||
public void Execute()
|
||||
{
|
||||
var offsetX = ThreadIds.X * WaveOpticsSettings.HorizontalConvolutionBlock;
|
||||
if (offsetX >= regionWidth || ThreadIds.Y >= regionHeight)
|
||||
return;
|
||||
|
||||
var x = regionX + offsetX;
|
||||
var y = regionY + ThreadIds.Y;
|
||||
var column = x - sourceX;
|
||||
var row = y - sourceY;
|
||||
var first = Hlsl.Max(-radius, -column);
|
||||
var last = Hlsl.Min(radius + WaveOpticsSettings.HorizontalConvolutionBlock - 1, sourceWidth - 1 - column);
|
||||
var weight0 = Weight(first - 1);
|
||||
var weight1 = Weight(first - 2);
|
||||
var weight2 = Weight(first - 3);
|
||||
var weight3 = Weight(first - 4);
|
||||
var weight4 = Weight(first - 5);
|
||||
var weight5 = Weight(first - 6);
|
||||
var weight6 = Weight(first - 7);
|
||||
var weight7 = Weight(first - 8);
|
||||
var weight8 = Weight(first - 9);
|
||||
var weight9 = Weight(first - 10);
|
||||
var weight10 = Weight(first - 11);
|
||||
var weight11 = Weight(first - 12);
|
||||
var weight12 = Weight(first - 13);
|
||||
var weight13 = Weight(first - 14);
|
||||
var weight14 = Weight(first - 15);
|
||||
var sum0 = new Float4(0f, 0f, 0f, 0f);
|
||||
var sum1 = sum0;
|
||||
var sum2 = sum0;
|
||||
var sum3 = sum0;
|
||||
var sum4 = sum0;
|
||||
var sum5 = sum0;
|
||||
var sum6 = sum0;
|
||||
var sum7 = sum0;
|
||||
var sum8 = sum0;
|
||||
var sum9 = sum0;
|
||||
var sum10 = sum0;
|
||||
var sum11 = sum0;
|
||||
var sum12 = sum0;
|
||||
var sum13 = sum0;
|
||||
var sum14 = sum0;
|
||||
var sum15 = sum0;
|
||||
for (var offset = first; offset <= last; offset++)
|
||||
{
|
||||
var weight15 = weight14;
|
||||
weight14 = weight13;
|
||||
weight13 = weight12;
|
||||
weight12 = weight11;
|
||||
weight11 = weight10;
|
||||
weight10 = weight9;
|
||||
weight9 = weight8;
|
||||
weight8 = weight7;
|
||||
weight7 = weight6;
|
||||
weight6 = weight5;
|
||||
weight5 = weight4;
|
||||
weight4 = weight3;
|
||||
weight3 = weight2;
|
||||
weight2 = weight1;
|
||||
weight1 = weight0;
|
||||
weight0 = Weight(offset);
|
||||
var texel = source[new Int2(column + offset, row)];
|
||||
sum0 += texel * weight0;
|
||||
sum1 += texel * weight1;
|
||||
sum2 += texel * weight2;
|
||||
sum3 += texel * weight3;
|
||||
sum4 += texel * weight4;
|
||||
sum5 += texel * weight5;
|
||||
sum6 += texel * weight6;
|
||||
sum7 += texel * weight7;
|
||||
sum8 += texel * weight8;
|
||||
sum9 += texel * weight9;
|
||||
sum10 += texel * weight10;
|
||||
sum11 += texel * weight11;
|
||||
sum12 += texel * weight12;
|
||||
sum13 += texel * weight13;
|
||||
sum14 += texel * weight14;
|
||||
sum15 += texel * weight15;
|
||||
}
|
||||
|
||||
var index = y * canvasWidth + x;
|
||||
horizontal[index] = sum0;
|
||||
if (offsetX + 1 < regionWidth)
|
||||
horizontal[index + 1] = sum1;
|
||||
if (offsetX + 2 < regionWidth)
|
||||
horizontal[index + 2] = sum2;
|
||||
if (offsetX + 3 < regionWidth)
|
||||
horizontal[index + 3] = sum3;
|
||||
if (offsetX + 4 < regionWidth)
|
||||
horizontal[index + 4] = sum4;
|
||||
if (offsetX + 5 < regionWidth)
|
||||
horizontal[index + 5] = sum5;
|
||||
if (offsetX + 6 < regionWidth)
|
||||
horizontal[index + 6] = sum6;
|
||||
if (offsetX + 7 < regionWidth)
|
||||
horizontal[index + 7] = sum7;
|
||||
if (offsetX + 8 < regionWidth)
|
||||
horizontal[index + 8] = sum8;
|
||||
if (offsetX + 9 < regionWidth)
|
||||
horizontal[index + 9] = sum9;
|
||||
if (offsetX + 10 < regionWidth)
|
||||
horizontal[index + 10] = sum10;
|
||||
if (offsetX + 11 < regionWidth)
|
||||
horizontal[index + 11] = sum11;
|
||||
if (offsetX + 12 < regionWidth)
|
||||
horizontal[index + 12] = sum12;
|
||||
if (offsetX + 13 < regionWidth)
|
||||
horizontal[index + 13] = sum13;
|
||||
if (offsetX + 14 < regionWidth)
|
||||
horizontal[index + 14] = sum14;
|
||||
if (offsetX + 15 < regionWidth)
|
||||
horizontal[index + 15] = sum15;
|
||||
}
|
||||
|
||||
private float Weight(int offset)
|
||||
=> offset >= -radius && offset <= radius ? weights[weightOffset + radius + offset] : 0f;
|
||||
}
|
||||
|
||||
[ThreadGroupSize(DefaultThreadGroupSizes.XY)]
|
||||
[GeneratedComputeShaderDescriptor]
|
||||
internal readonly partial struct VerticalPassShader(
|
||||
ReadWriteBuffer<Float4> horizontal,
|
||||
ReadOnlyBuffer<float> weights,
|
||||
ReadWriteBuffer<Float4> convolved,
|
||||
int weightOffset,
|
||||
int radius,
|
||||
int rectX,
|
||||
int rectY,
|
||||
int rectWidth,
|
||||
int rectHeight,
|
||||
int canvasWidth,
|
||||
int sourceY,
|
||||
int sourceHeight,
|
||||
bool accumulate) : IComputeShader
|
||||
{
|
||||
private readonly ReadWriteBuffer<Float4> horizontal = horizontal;
|
||||
private readonly ReadOnlyBuffer<float> weights = weights;
|
||||
private readonly ReadWriteBuffer<Float4> convolved = convolved;
|
||||
private readonly int weightOffset = weightOffset;
|
||||
private readonly int radius = radius;
|
||||
private readonly int rectX = rectX;
|
||||
private readonly int rectY = rectY;
|
||||
private readonly int rectWidth = rectWidth;
|
||||
private readonly int rectHeight = rectHeight;
|
||||
private readonly int canvasWidth = canvasWidth;
|
||||
private readonly int sourceY = sourceY;
|
||||
private readonly int sourceHeight = sourceHeight;
|
||||
private readonly bool accumulate = accumulate;
|
||||
|
||||
public void Execute()
|
||||
{
|
||||
var offsetY = ThreadIds.Y * WaveOpticsSettings.VerticalConvolutionBlock;
|
||||
if (ThreadIds.X >= rectWidth || offsetY >= rectHeight)
|
||||
return;
|
||||
|
||||
var x = rectX + ThreadIds.X;
|
||||
var y = rectY + offsetY;
|
||||
var row = y - sourceY;
|
||||
var first = Hlsl.Max(-radius, -row);
|
||||
var last = Hlsl.Min(radius + WaveOpticsSettings.VerticalConvolutionBlock - 1, sourceHeight - 1 - row);
|
||||
var weight0 = Weight(first - 1);
|
||||
var weight1 = Weight(first - 2);
|
||||
var weight2 = Weight(first - 3);
|
||||
var weight3 = Weight(first - 4);
|
||||
var weight4 = Weight(first - 5);
|
||||
var weight5 = Weight(first - 6);
|
||||
var weight6 = Weight(first - 7);
|
||||
var sum0 = new Float4(0f, 0f, 0f, 0f);
|
||||
var sum1 = sum0;
|
||||
var sum2 = sum0;
|
||||
var sum3 = sum0;
|
||||
var sum4 = sum0;
|
||||
var sum5 = sum0;
|
||||
var sum6 = sum0;
|
||||
var sum7 = sum0;
|
||||
for (var offset = first; offset <= last; offset++)
|
||||
{
|
||||
var weight7 = weight6;
|
||||
weight6 = weight5;
|
||||
weight5 = weight4;
|
||||
weight4 = weight3;
|
||||
weight3 = weight2;
|
||||
weight2 = weight1;
|
||||
weight1 = weight0;
|
||||
weight0 = Weight(offset);
|
||||
var value = horizontal[(y + offset) * canvasWidth + x];
|
||||
sum0 += value * weight0;
|
||||
sum1 += value * weight1;
|
||||
sum2 += value * weight2;
|
||||
sum3 += value * weight3;
|
||||
sum4 += value * weight4;
|
||||
sum5 += value * weight5;
|
||||
sum6 += value * weight6;
|
||||
sum7 += value * weight7;
|
||||
}
|
||||
|
||||
var index = y * canvasWidth + x;
|
||||
Store(index, sum0);
|
||||
if (offsetY + 1 < rectHeight)
|
||||
Store(index + canvasWidth, sum1);
|
||||
if (offsetY + 2 < rectHeight)
|
||||
Store(index + canvasWidth * 2, sum2);
|
||||
if (offsetY + 3 < rectHeight)
|
||||
Store(index + canvasWidth * 3, sum3);
|
||||
if (offsetY + 4 < rectHeight)
|
||||
Store(index + canvasWidth * 4, sum4);
|
||||
if (offsetY + 5 < rectHeight)
|
||||
Store(index + canvasWidth * 5, sum5);
|
||||
if (offsetY + 6 < rectHeight)
|
||||
Store(index + canvasWidth * 6, sum6);
|
||||
if (offsetY + 7 < rectHeight)
|
||||
Store(index + canvasWidth * 7, sum7);
|
||||
}
|
||||
|
||||
private float Weight(int offset)
|
||||
=> offset >= -radius && offset <= radius ? weights[weightOffset + radius + offset] : 0f;
|
||||
|
||||
private void Store(int index, Float4 sum)
|
||||
{
|
||||
convolved[index] = accumulate ? convolved[index] + sum : sum;
|
||||
}
|
||||
}
|
||||
|
||||
[ThreadGroupSize(DefaultThreadGroupSizes.XY)]
|
||||
[GeneratedComputeShaderDescriptor]
|
||||
internal readonly partial struct RenderShader(
|
||||
ReadWriteBuffer<Float4> convolved,
|
||||
ReadWriteTexture2D<Bgra32, Float4> output,
|
||||
int rectX,
|
||||
int rectY,
|
||||
int rectWidth,
|
||||
int rectHeight,
|
||||
int canvasWidth,
|
||||
float gain) : IComputeShader
|
||||
{
|
||||
private readonly ReadWriteBuffer<Float4> convolved = convolved;
|
||||
private readonly ReadWriteTexture2D<Bgra32, Float4> output = output;
|
||||
private readonly int rectX = rectX;
|
||||
private readonly int rectY = rectY;
|
||||
private readonly int rectWidth = rectWidth;
|
||||
private readonly int rectHeight = rectHeight;
|
||||
private readonly int canvasWidth = canvasWidth;
|
||||
private readonly float gain = gain;
|
||||
|
||||
public void Execute()
|
||||
{
|
||||
if (ThreadIds.X >= rectWidth || ThreadIds.Y >= rectHeight)
|
||||
return;
|
||||
|
||||
output[ThreadIds.XY] = convolved[(rectY + ThreadIds.Y) * canvasWidth + rectX + ThreadIds.X] * gain;
|
||||
}
|
||||
}
|
||||
@@ -1,373 +0,0 @@
|
||||
using System.ComponentModel;
|
||||
using System.Runtime.InteropServices;
|
||||
using ComputeWeave;
|
||||
using WaveOptics.Abstractions;
|
||||
using WaveOptics.Effects;
|
||||
using WaveOptics.Optics;
|
||||
|
||||
namespace WaveOptics.Rendering;
|
||||
|
||||
internal sealed class WaveOpticsPipeline : IDisposable
|
||||
{
|
||||
private readonly GraphicsDevice _device;
|
||||
private readonly WaveOpticsPipelineHost _host;
|
||||
private readonly ReadWriteBuffer<int> _scratch;
|
||||
private readonly ReadBackBuffer<int> _scratchReadBack;
|
||||
private readonly ReadOnlyBuffer<float> _weights;
|
||||
private readonly float[] _weightValues = new float[WaveOpticsSettings.WeightsLength];
|
||||
private readonly double[] _kernelValues = new double[WaveOpticsSettings.MaximumKernelSize * WaveOpticsSettings.MaximumKernelSize];
|
||||
private readonly FraunhoferKernelSampler _sampler = new();
|
||||
private readonly SeparableKernel _separable = new();
|
||||
private PsfParameters? _kernelPsf;
|
||||
private Kernel _kernel;
|
||||
private ConvolutionKey? _convolutionKey;
|
||||
private int _cachedLitCount;
|
||||
private int _cachedBoundsMinX;
|
||||
private int _cachedBoundsMinY;
|
||||
private int _cachedBoundsMaxX;
|
||||
private int _cachedBoundsMaxY;
|
||||
private int _canvasWidth;
|
||||
private int _canvasHeight;
|
||||
private ReadWriteTexture2D<Bgra32, Float4>? _packedSource;
|
||||
private ReadWriteTexture2D<Bgra32, Float4>? _packedOutput;
|
||||
private int _packedWidth;
|
||||
private int _packedHeight;
|
||||
|
||||
private WaveOpticsPipeline(GraphicsDevice device, WaveOpticsPipelineHost host)
|
||||
{
|
||||
_device = device;
|
||||
_host = host;
|
||||
_scratch = device.AllocateReadWriteBuffer<int>(WaveOpticsSettings.ScratchLength);
|
||||
_scratchReadBack = device.AllocateReadBackBuffer<int>(WaveOpticsSettings.ScratchLength);
|
||||
_weights = device.AllocateReadOnlyBuffer<float>(WaveOpticsSettings.WeightsLength);
|
||||
}
|
||||
|
||||
public static WaveOpticsPipeline? TryCreate()
|
||||
{
|
||||
try
|
||||
{
|
||||
return TryCreate(GraphicsDevice.GetDefault());
|
||||
}
|
||||
catch
|
||||
{
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
public static WaveOpticsPipeline? TryCreate(GraphicsDevice device)
|
||||
{
|
||||
WaveOpticsPipelineHost? host = null;
|
||||
try
|
||||
{
|
||||
host = WaveOpticsPipelineHost.Create(device, WaveOpticsSettings.MaximumPendingSubmissions);
|
||||
var pipeline = new WaveOpticsPipeline(device, host);
|
||||
host = null;
|
||||
return pipeline;
|
||||
}
|
||||
catch (Win32Exception)
|
||||
{
|
||||
return null;
|
||||
}
|
||||
finally
|
||||
{
|
||||
host?.Dispose();
|
||||
host?.WaitForDisposal();
|
||||
}
|
||||
}
|
||||
|
||||
internal void WaitForCompletion()
|
||||
{
|
||||
_device.For(1, new FillIntShader(_scratch, 0, 0));
|
||||
}
|
||||
|
||||
public void Process(ReadOnlySpan<int> source, Span<int> destination, int width, int height, in Parameters parameters)
|
||||
{
|
||||
var pixelCount = checked(width * height);
|
||||
EnsurePackedTextures(width, height);
|
||||
var sourceTexture = _packedSource!;
|
||||
var outputTexture = _packedOutput!;
|
||||
sourceTexture.CopyFrom(MemoryMarshal.Cast<int, Bgra32>(source[..pixelCount]));
|
||||
SubmitFullPipeline(sourceTexture, outputTexture, width, height, in parameters).Wait();
|
||||
outputTexture.CopyTo(MemoryMarshal.Cast<int, Bgra32>(destination[..pixelCount]));
|
||||
}
|
||||
|
||||
public void Process(
|
||||
ReadWriteTexture2D<Bgra32, Float4> source,
|
||||
ReadWriteTexture2D<Bgra32, Float4> destination,
|
||||
int width,
|
||||
int height,
|
||||
in Parameters parameters)
|
||||
{
|
||||
_ = SubmitFullPipeline(source, destination, width, height, in parameters);
|
||||
}
|
||||
|
||||
internal void ProcessSharedAndWait(
|
||||
ReadWriteTexture2D<Bgra32, Float4> source,
|
||||
ReadWriteTexture2D<Bgra32, Float4> destination,
|
||||
int width,
|
||||
int height,
|
||||
in Parameters parameters)
|
||||
{
|
||||
SubmitFullPipeline(source, destination, width, height, in parameters).Wait();
|
||||
}
|
||||
|
||||
internal bool Simulate(
|
||||
ReadWriteTexture2D<Bgra32, Float4> source,
|
||||
int canvasWidth,
|
||||
int canvasHeight,
|
||||
int sourceOffsetX,
|
||||
int sourceOffsetY,
|
||||
int sourceWidth,
|
||||
int sourceHeight,
|
||||
in Parameters parameters)
|
||||
{
|
||||
var sourceRect = BeginSimulate(canvasWidth, canvasHeight, sourceOffsetX, sourceOffsetY, sourceWidth, sourceHeight);
|
||||
_host.RecordSourceHash(source, _scratch, in sourceRect).Wait();
|
||||
if (!TryBeginConvolution(in sourceRect, in parameters, out var rect))
|
||||
return false;
|
||||
|
||||
_host.RecordConvolution(source, _weights, in sourceRect, in rect, _canvasWidth, in _kernel).Wait();
|
||||
return true;
|
||||
}
|
||||
|
||||
internal bool Simulate(
|
||||
ComputeResourceBinding<ReadWriteTexture2D<Bgra32, Float4>> source,
|
||||
int canvasWidth,
|
||||
int canvasHeight,
|
||||
int sourceOffsetX,
|
||||
int sourceOffsetY,
|
||||
int sourceWidth,
|
||||
int sourceHeight,
|
||||
in Parameters parameters)
|
||||
{
|
||||
var sourceRect = BeginSimulate(canvasWidth, canvasHeight, sourceOffsetX, sourceOffsetY, sourceWidth, sourceHeight);
|
||||
_host.RecordSharedSourceHash(source, _scratch, in sourceRect).Wait();
|
||||
if (!TryBeginConvolution(in sourceRect, in parameters, out var rect))
|
||||
return false;
|
||||
|
||||
_host.RecordSharedConvolution(source, _weights, in sourceRect, in rect, _canvasWidth, in _kernel).Wait();
|
||||
return true;
|
||||
}
|
||||
|
||||
private PixelRect BeginSimulate(int canvasWidth, int canvasHeight, int sourceOffsetX, int sourceOffsetY, int sourceWidth, int sourceHeight)
|
||||
{
|
||||
EnsureCanvas(canvasWidth, canvasHeight);
|
||||
return new PixelRect(sourceOffsetX, sourceOffsetY, sourceWidth, sourceHeight);
|
||||
}
|
||||
|
||||
private bool TryBeginConvolution(in PixelRect sourceRect, in Parameters parameters, out PixelRect rect)
|
||||
{
|
||||
_scratchReadBack.CopyFrom(_scratch);
|
||||
var hashed = _scratchReadBack.Span;
|
||||
_cachedLitCount = hashed[WaveOpticsSettings.ScratchLitCount];
|
||||
_cachedBoundsMinX = hashed[WaveOpticsSettings.ScratchBoundsMinX];
|
||||
_cachedBoundsMinY = hashed[WaveOpticsSettings.ScratchBoundsMinY];
|
||||
_cachedBoundsMaxX = hashed[WaveOpticsSettings.ScratchBoundsMaxX];
|
||||
_cachedBoundsMaxY = hashed[WaveOpticsSettings.ScratchBoundsMaxY];
|
||||
|
||||
var key = new ConvolutionKey(
|
||||
hashed[WaveOpticsSettings.ScratchHashSum],
|
||||
hashed[WaveOpticsSettings.ScratchHashMix],
|
||||
_canvasWidth,
|
||||
_canvasHeight,
|
||||
sourceRect,
|
||||
KernelKey(parameters.Psf));
|
||||
if (_convolutionKey == key || !TryGetVisibleBounds(_canvasWidth, _canvasHeight, in parameters, out rect))
|
||||
{
|
||||
rect = default;
|
||||
return false;
|
||||
}
|
||||
|
||||
if (!TryEnsureKernel(parameters.Psf))
|
||||
{
|
||||
_convolutionKey = null;
|
||||
rect = default;
|
||||
return false;
|
||||
}
|
||||
|
||||
_convolutionKey = key;
|
||||
return true;
|
||||
}
|
||||
|
||||
internal bool HasKernel => _kernel.Rank > 0;
|
||||
|
||||
internal bool TryGetVisibleBounds(int canvasWidth, int canvasHeight, in Parameters parameters, out PixelRect rect)
|
||||
{
|
||||
rect = default;
|
||||
if (_cachedLitCount <= 0 || _cachedBoundsMinX > _cachedBoundsMaxX)
|
||||
return false;
|
||||
|
||||
var radius = parameters.Psf.KernelRadius;
|
||||
var left = Math.Clamp((_cachedBoundsMinX - radius) & ~3, 0, canvasWidth);
|
||||
var top = Math.Clamp((_cachedBoundsMinY - radius) & ~3, 0, canvasHeight);
|
||||
var right = Math.Clamp(_cachedBoundsMaxX + 1 + radius, 0, canvasWidth);
|
||||
var bottom = Math.Clamp(_cachedBoundsMaxY + 1 + radius, 0, canvasHeight);
|
||||
var width = Math.Min((right - left + 3) & ~3, canvasWidth - left);
|
||||
var height = Math.Min((bottom - top + 3) & ~3, canvasHeight - top);
|
||||
if (width <= 0 || height <= 0)
|
||||
return false;
|
||||
|
||||
rect = new PixelRect(left, top, width, height);
|
||||
return true;
|
||||
}
|
||||
|
||||
internal void RenderVisible(ReadWriteTexture2D<Bgra32, Float4> output, PixelRect rect, in Parameters parameters)
|
||||
{
|
||||
_host.RecordRender(output, in rect, _canvasWidth, parameters.Gain).Wait();
|
||||
}
|
||||
|
||||
internal void RenderVisible(ComputeResourceBinding<ReadWriteTexture2D<Bgra32, Float4>> output, PixelRect rect, in Parameters parameters)
|
||||
{
|
||||
_host.RecordSharedRender(output, in rect, _canvasWidth, parameters.Gain).Wait();
|
||||
}
|
||||
|
||||
private ComputeSubmission SubmitFullPipeline(
|
||||
ReadWriteTexture2D<Bgra32, Float4> source,
|
||||
ReadWriteTexture2D<Bgra32, Float4> output,
|
||||
int width,
|
||||
int height,
|
||||
in Parameters parameters)
|
||||
{
|
||||
EnsureCanvas(width, height);
|
||||
if (!TryEnsureKernel(parameters.Psf))
|
||||
throw new InvalidOperationException();
|
||||
_convolutionKey = null;
|
||||
var sourceRect = new PixelRect(0, 0, width, height);
|
||||
return _host.RecordFullPipeline(source, output, _weights, in sourceRect, in _kernel, parameters.Gain);
|
||||
}
|
||||
|
||||
private bool TryEnsureKernel(in PsfParameters psf)
|
||||
{
|
||||
var key = KernelKey(psf);
|
||||
if (_kernelPsf == key)
|
||||
return HasKernel;
|
||||
|
||||
var pupilGridSize = WaveOpticsSettings.GetPupilGridSize(psf.Quality);
|
||||
var aberration = new WavefrontAberration(
|
||||
defocusWaves: psf.Defocus,
|
||||
astigmatismVerticalWaves: psf.AstigmatismVertical,
|
||||
astigmatismObliqueWaves: psf.AstigmatismOblique,
|
||||
comaHorizontalWaves: psf.ComaHorizontal,
|
||||
comaVerticalWaves: psf.ComaVertical,
|
||||
sphericalWaves: psf.Spherical);
|
||||
var specification = new PsfSpecification(
|
||||
pupilGridSize,
|
||||
WaveOpticsSettings.GetPupilDiameterSamples(pupilGridSize),
|
||||
WaveOpticsSettings.GetKernelSize(psf.KernelRadius),
|
||||
psf.Wavelength,
|
||||
psf.FNumber,
|
||||
psf.PixelPitch,
|
||||
psf.ApertureShape == WaveOpticsApertureShape.Circular ? ApertureShape.Circular : ApertureShape.RegularPolygon,
|
||||
psf.BladeCount,
|
||||
psf.BladeRotation,
|
||||
psf.Obstruction,
|
||||
aberration);
|
||||
var size = specification.KernelSize;
|
||||
var kernel = _kernelValues.AsSpan(0, size * size);
|
||||
if (!_sampler.TrySample(in specification, kernel))
|
||||
{
|
||||
_kernel = default;
|
||||
_kernelPsf = key;
|
||||
return false;
|
||||
}
|
||||
|
||||
_separable.Update(kernel, size, WaveOpticsSettings.SeparableResidualRatio, WaveOpticsSettings.MaximumRank);
|
||||
var scale = 1d / _separable.Sum;
|
||||
for (var term = 0; term < _separable.Rank; term++)
|
||||
{
|
||||
_separable.Horizontal.Slice(term * size, size).CopyTo(_weightValues.AsSpan(WaveOpticsSettings.GetWeightOffset(term, 0)));
|
||||
var verticalOffset = WaveOpticsSettings.GetWeightOffset(term, 1);
|
||||
for (var k = 0; k < size; k++)
|
||||
_weightValues[verticalOffset + k] = (float)(_separable.Vertical[term * size + k] * scale);
|
||||
}
|
||||
_weights.CopyFrom(_weightValues.AsSpan(0, WaveOpticsSettings.GetWeightOffset(_separable.Rank, 0)));
|
||||
_kernel = new Kernel(_separable.Rank, size / 2);
|
||||
_kernelPsf = key;
|
||||
return true;
|
||||
}
|
||||
|
||||
private static PsfParameters KernelKey(in PsfParameters psf)
|
||||
=> psf.ApertureShape == WaveOpticsApertureShape.Circular ? psf with { BladeCount = 0, BladeRotation = 0f } : psf;
|
||||
|
||||
private void EnsureCanvas(int canvasWidth, int canvasHeight)
|
||||
{
|
||||
if (_canvasWidth == canvasWidth && _canvasHeight == canvasHeight)
|
||||
return;
|
||||
|
||||
var canvasLength = canvasWidth * canvasHeight;
|
||||
if (!_host.TryEnsureCanvas(new WaveOpticsCanvasResources.Plan(canvasLength, canvasLength), out _))
|
||||
throw new InvalidOperationException();
|
||||
|
||||
_cachedLitCount = 0;
|
||||
_cachedBoundsMinX = int.MaxValue;
|
||||
_cachedBoundsMinY = int.MaxValue;
|
||||
_cachedBoundsMaxX = int.MinValue;
|
||||
_cachedBoundsMaxY = int.MinValue;
|
||||
_convolutionKey = null;
|
||||
_canvasWidth = canvasWidth;
|
||||
_canvasHeight = canvasHeight;
|
||||
}
|
||||
|
||||
private void EnsurePackedTextures(int width, int height)
|
||||
{
|
||||
if (_packedWidth == width && _packedHeight == height)
|
||||
return;
|
||||
|
||||
_packedSource?.Dispose();
|
||||
_packedOutput?.Dispose();
|
||||
_packedSource = _device.AllocateReadWriteTexture2D<Bgra32, Float4>(width, height);
|
||||
_packedOutput = _device.AllocateReadWriteTexture2D<Bgra32, Float4>(width, height);
|
||||
_packedWidth = width;
|
||||
_packedHeight = height;
|
||||
}
|
||||
|
||||
public void Dispose()
|
||||
{
|
||||
_host.Dispose();
|
||||
_host.WaitForDisposal();
|
||||
_packedSource?.Dispose();
|
||||
_packedOutput?.Dispose();
|
||||
_packedSource = null;
|
||||
_packedOutput = null;
|
||||
_packedWidth = 0;
|
||||
_packedHeight = 0;
|
||||
_kernelPsf = null;
|
||||
_convolutionKey = null;
|
||||
_canvasWidth = 0;
|
||||
_canvasHeight = 0;
|
||||
_weights.Dispose();
|
||||
_scratchReadBack.Dispose();
|
||||
_scratch.Dispose();
|
||||
}
|
||||
|
||||
internal readonly record struct PixelRect(int X, int Y, int Width, int Height);
|
||||
|
||||
internal readonly record struct Kernel(int Rank, int Radius);
|
||||
|
||||
private readonly record struct ConvolutionKey(
|
||||
int HashSum,
|
||||
int HashMix,
|
||||
int CanvasWidth,
|
||||
int CanvasHeight,
|
||||
PixelRect Source,
|
||||
PsfParameters Psf);
|
||||
|
||||
internal readonly record struct PsfParameters(
|
||||
WaveOpticsQuality Quality,
|
||||
int KernelRadius,
|
||||
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);
|
||||
|
||||
internal readonly record struct Parameters(float Gain, PsfParameters Psf);
|
||||
}
|
||||
@@ -1,184 +0,0 @@
|
||||
using ComputeWeave;
|
||||
|
||||
namespace WaveOptics.Rendering;
|
||||
|
||||
[ComputeResourceGroup]
|
||||
internal sealed partial class WaveOpticsCanvasResources
|
||||
{
|
||||
[ComputePipelineResource(ComputeResourceAccess.ReadWrite)]
|
||||
internal ReadWriteBuffer<Float4> Horizontal { get; }
|
||||
|
||||
[ComputePipelineResource(ComputeResourceAccess.ReadWrite)]
|
||||
internal ReadWriteBuffer<Float4> Convolved { get; }
|
||||
}
|
||||
|
||||
[ComputePipelineHost("_device", 1)]
|
||||
internal sealed partial class WaveOpticsPipelineHost
|
||||
{
|
||||
private readonly GraphicsDevice _device;
|
||||
|
||||
[ComputePipelineResource(ComputeResourceAccess.ReadWrite, ComputeResourceRecovery.Recompute)]
|
||||
private readonly ComputeResourceGroupSlot<WaveOpticsCanvasResources> _canvas = new();
|
||||
|
||||
[ComputePipeline]
|
||||
private void RecordFullPipeline(
|
||||
in ComputeContext context,
|
||||
[ComputeOwnedResource(nameof(_canvas))] WaveOpticsCanvasResources canvas,
|
||||
[ComputeResource(ComputeResourceAccess.ReadWrite)] ReadWriteTexture2D<Bgra32, Float4> source,
|
||||
[ComputeResource(ComputeResourceAccess.ReadWrite)] ReadWriteTexture2D<Bgra32, Float4> output,
|
||||
[ComputeResource(ComputeResourceAccess.Read)] ReadOnlyBuffer<float> weights,
|
||||
in WaveOpticsPipeline.PixelRect sourceRect,
|
||||
in WaveOpticsPipeline.Kernel kernel,
|
||||
float gain)
|
||||
{
|
||||
_ = _device;
|
||||
|
||||
RecordConvolutionStage(in context, canvas, source, weights, in sourceRect, in sourceRect, sourceRect.Width, in kernel);
|
||||
RecordRenderStage(in context, canvas, output, in sourceRect, sourceRect.Width, gain);
|
||||
}
|
||||
|
||||
[ComputePipeline]
|
||||
private void RecordSourceHash(
|
||||
in ComputeContext context,
|
||||
[ComputeResource(ComputeResourceAccess.ReadWrite)] ReadWriteTexture2D<Bgra32, Float4> source,
|
||||
[ComputeResource(ComputeResourceAccess.ReadWrite)] ReadWriteBuffer<int> scratch,
|
||||
in WaveOpticsPipeline.PixelRect sourceRect)
|
||||
{
|
||||
_ = _device;
|
||||
|
||||
RecordSourceHashStage(in context, source, scratch, in sourceRect);
|
||||
}
|
||||
|
||||
[ComputePipeline]
|
||||
[ComputeInterop]
|
||||
private void RecordSharedSourceHash(
|
||||
in ComputeContext context,
|
||||
[ComputeResource(ComputeResourceAccess.ReadWrite, Sharing = ComputeResourceSharing.External)] ReadWriteTexture2D<Bgra32, Float4> source,
|
||||
[ComputeResource(ComputeResourceAccess.ReadWrite)] ReadWriteBuffer<int> scratch,
|
||||
in WaveOpticsPipeline.PixelRect sourceRect)
|
||||
{
|
||||
_ = _device;
|
||||
|
||||
RecordSourceHashStage(in context, source, scratch, in sourceRect);
|
||||
}
|
||||
|
||||
[ComputePipeline]
|
||||
private void RecordConvolution(
|
||||
in ComputeContext context,
|
||||
[ComputeOwnedResource(nameof(_canvas))] WaveOpticsCanvasResources canvas,
|
||||
[ComputeResource(ComputeResourceAccess.ReadWrite)] ReadWriteTexture2D<Bgra32, Float4> source,
|
||||
[ComputeResource(ComputeResourceAccess.Read)] ReadOnlyBuffer<float> weights,
|
||||
in WaveOpticsPipeline.PixelRect sourceRect,
|
||||
in WaveOpticsPipeline.PixelRect rect,
|
||||
int canvasWidth,
|
||||
in WaveOpticsPipeline.Kernel kernel)
|
||||
{
|
||||
_ = _device;
|
||||
|
||||
RecordConvolutionStage(in context, canvas, source, weights, in sourceRect, in rect, canvasWidth, in kernel);
|
||||
}
|
||||
|
||||
[ComputePipeline]
|
||||
[ComputeInterop]
|
||||
private void RecordSharedConvolution(
|
||||
in ComputeContext context,
|
||||
[ComputeOwnedResource(nameof(_canvas))] WaveOpticsCanvasResources canvas,
|
||||
[ComputeResource(ComputeResourceAccess.ReadWrite, Sharing = ComputeResourceSharing.External)] ReadWriteTexture2D<Bgra32, Float4> source,
|
||||
[ComputeResource(ComputeResourceAccess.Read)] ReadOnlyBuffer<float> weights,
|
||||
in WaveOpticsPipeline.PixelRect sourceRect,
|
||||
in WaveOpticsPipeline.PixelRect rect,
|
||||
int canvasWidth,
|
||||
in WaveOpticsPipeline.Kernel kernel)
|
||||
{
|
||||
_ = _device;
|
||||
|
||||
RecordConvolutionStage(in context, canvas, source, weights, in sourceRect, in rect, canvasWidth, in kernel);
|
||||
}
|
||||
|
||||
[ComputePipeline]
|
||||
private void RecordRender(
|
||||
in ComputeContext context,
|
||||
[ComputeOwnedResource(nameof(_canvas))] WaveOpticsCanvasResources canvas,
|
||||
[ComputeResource(ComputeResourceAccess.ReadWrite)] ReadWriteTexture2D<Bgra32, Float4> output,
|
||||
in WaveOpticsPipeline.PixelRect rect,
|
||||
int canvasWidth,
|
||||
float gain)
|
||||
{
|
||||
_ = _device;
|
||||
|
||||
RecordRenderStage(in context, canvas, output, in rect, canvasWidth, gain);
|
||||
}
|
||||
|
||||
[ComputePipeline]
|
||||
[ComputeInterop]
|
||||
private void RecordSharedRender(
|
||||
in ComputeContext context,
|
||||
[ComputeOwnedResource(nameof(_canvas))] WaveOpticsCanvasResources canvas,
|
||||
[ComputeResource(ComputeResourceAccess.ReadWrite, Sharing = ComputeResourceSharing.External)] ReadWriteTexture2D<Bgra32, Float4> output,
|
||||
in WaveOpticsPipeline.PixelRect rect,
|
||||
int canvasWidth,
|
||||
float gain)
|
||||
{
|
||||
_ = _device;
|
||||
|
||||
RecordRenderStage(in context, canvas, output, in rect, canvasWidth, gain);
|
||||
}
|
||||
|
||||
private static void RecordSourceHashStage(
|
||||
in ComputeContext context,
|
||||
ReadWriteTexture2D<Bgra32, Float4> source,
|
||||
ReadWriteBuffer<int> scratch,
|
||||
in WaveOpticsPipeline.PixelRect sourceRect)
|
||||
{
|
||||
context.For(1, new SourceHashResetShader(scratch));
|
||||
context.Barrier(scratch);
|
||||
context.For(GetBlockCount(sourceRect.Width, WaveOpticsSettings.SourceHashSpan), sourceRect.Height, new SourceHashShader(
|
||||
source, scratch, sourceRect.X, sourceRect.Y, sourceRect.Width, sourceRect.Height));
|
||||
context.Barrier(scratch);
|
||||
}
|
||||
|
||||
private static void RecordConvolutionStage(
|
||||
in ComputeContext context,
|
||||
WaveOpticsCanvasResources canvas,
|
||||
ReadWriteTexture2D<Bgra32, Float4> source,
|
||||
ReadOnlyBuffer<float> weights,
|
||||
in WaveOpticsPipeline.PixelRect sourceRect,
|
||||
in WaveOpticsPipeline.PixelRect rect,
|
||||
int canvasWidth,
|
||||
in WaveOpticsPipeline.Kernel kernel)
|
||||
{
|
||||
var top = Math.Max(rect.Y - kernel.Radius, sourceRect.Y);
|
||||
var bottom = Math.Min(rect.Y + rect.Height + kernel.Radius, sourceRect.Y + sourceRect.Height);
|
||||
for (var term = 0; term < kernel.Rank; term++)
|
||||
{
|
||||
context.For(GetBlockCount(rect.Width, WaveOpticsSettings.HorizontalConvolutionBlock), bottom - top, new HorizontalPassShader(
|
||||
source, weights, canvas.Horizontal,
|
||||
WaveOpticsSettings.GetWeightOffset(term, 0), kernel.Radius,
|
||||
rect.X, top, rect.Width, bottom - top, canvasWidth,
|
||||
sourceRect.X, sourceRect.Y, sourceRect.Width));
|
||||
context.Barrier(canvas.Horizontal);
|
||||
context.For(rect.Width, GetBlockCount(rect.Height, WaveOpticsSettings.VerticalConvolutionBlock), new VerticalPassShader(
|
||||
canvas.Horizontal, weights, canvas.Convolved,
|
||||
WaveOpticsSettings.GetWeightOffset(term, 1), kernel.Radius,
|
||||
rect.X, rect.Y, rect.Width, rect.Height, canvasWidth,
|
||||
sourceRect.Y, sourceRect.Height, term > 0));
|
||||
context.Barrier(canvas.Horizontal);
|
||||
context.Barrier(canvas.Convolved);
|
||||
}
|
||||
}
|
||||
|
||||
private static int GetBlockCount(int length, int block)
|
||||
=> (length + block - 1) / block;
|
||||
|
||||
private static void RecordRenderStage(
|
||||
in ComputeContext context,
|
||||
WaveOpticsCanvasResources canvas,
|
||||
ReadWriteTexture2D<Bgra32, Float4> output,
|
||||
in WaveOpticsPipeline.PixelRect rect,
|
||||
int canvasWidth,
|
||||
float gain)
|
||||
{
|
||||
context.For(rect.Width, rect.Height, new RenderShader(
|
||||
canvas.Convolved, output, rect.X, rect.Y, rect.Width, rect.Height, canvasWidth, gain));
|
||||
}
|
||||
}
|
||||
@@ -1,105 +0,0 @@
|
||||
<Project Sdk="Microsoft.NET.Sdk">
|
||||
|
||||
<PropertyGroup>
|
||||
<TargetFramework>net10.0-windows10.0.19041.0</TargetFramework>
|
||||
<UseWPF>true</UseWPF>
|
||||
<ImplicitUsings>enable</ImplicitUsings>
|
||||
<Nullable>enable</Nullable>
|
||||
<AssemblyName>WaveOptics</AssemblyName>
|
||||
<RootNamespace>WaveOptics</RootNamespace>
|
||||
<Version>2.1.0</Version>
|
||||
<Platforms>AnyCPU;x64</Platforms>
|
||||
<PlatformTarget>x64</PlatformTarget>
|
||||
<AllowUnsafeBlocks>true</AllowUnsafeBlocks>
|
||||
<CopyLocalLockFileAssemblies>true</CopyLocalLockFileAssemblies>
|
||||
<ShaderDirPath>..\Release\</ShaderDirPath>
|
||||
</PropertyGroup>
|
||||
|
||||
<ItemGroup>
|
||||
<Resource Include="$(ShaderDirPath)WaveOptics.cso" Link="Resources\Shader\WaveOptics.cso" />
|
||||
</ItemGroup>
|
||||
|
||||
<ItemGroup>
|
||||
<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">
|
||||
<HintPath>$(YMM4DirPath)YukkuriMovieMaker.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>
|
||||
<Reference Include="Newtonsoft.Json">
|
||||
<HintPath>$(YMM4DirPath)Newtonsoft.Json.dll</HintPath>
|
||||
<Private>false</Private>
|
||||
</Reference>
|
||||
</ItemGroup>
|
||||
|
||||
<ItemGroup>
|
||||
<Compile Include="..\YMM4-GitHubUpdateNotifier\GitHubUpdateNotifier\*.cs" LinkBase="GitHubUpdateNotifier" />
|
||||
</ItemGroup>
|
||||
|
||||
<Import Project="..\YMM4-Telemetry\Telemetry.props" />
|
||||
|
||||
<ItemGroup>
|
||||
<PackageReference Include="ComputeWeave" Version="2.6.0" />
|
||||
<PackageReference Include="ILRepack" Version="2.0.48" PrivateAssets="all" ExcludeAssets="all" GeneratePathProperty="true" />
|
||||
<PackageReference Include="Microsoft.Xaml.Behaviors.Wpf" Version="1.1.142" />
|
||||
</ItemGroup>
|
||||
|
||||
<ItemGroup>
|
||||
<ProjectReference Include="..\WaveOptics.Abstractions\WaveOptics.Abstractions.csproj" />
|
||||
<ProjectReference Include="..\YukkuriMovieMaker.Generator\YukkuriMovieMaker.Generator\YukkuriMovieMaker.Generator.csproj" SetConfiguration="Configuration=$(Configuration)" SetPlatform="Platform=AnyCPU" GlobalPropertiesToRemove="SkipPluginDeploy" OutputItemType="Analyzer" ReferenceOutputAssembly="false" />
|
||||
<AdditionalFiles Include="**\*.csv" />
|
||||
</ItemGroup>
|
||||
|
||||
<ItemGroup>
|
||||
<AssemblyAttribute Include="System.Runtime.CompilerServices.InternalsVisibleToAttribute">
|
||||
<_Parameter1>WaveOptics.Tests</_Parameter1>
|
||||
</AssemblyAttribute>
|
||||
<AssemblyAttribute Include="System.Runtime.CompilerServices.InternalsVisibleToAttribute">
|
||||
<_Parameter1>WaveOptics.Harness</_Parameter1>
|
||||
</AssemblyAttribute>
|
||||
</ItemGroup>
|
||||
|
||||
<Target Name="MergePluginAssembly" AfterTargets="PostBuildEvent" Inputs="$(TargetPath);$(TargetDir)ComputeWeave.dll;$(TargetDir)ComputeWeave.Core.dll" Outputs="$(TargetDir)plugin\$(TargetFileName)">
|
||||
<MakeDir Directories="$(TargetDir)plugin" />
|
||||
<Exec Command=""$(PkgILRepack)\tools\ILRepack.exe" /out:"$(TargetDir)plugin\$(TargetFileName)" /lib:"$([System.IO.Path]::GetDirectoryName('$(TargetPath)'))" /lib:"$([System.IO.Path]::GetDirectoryName('$(YMM4DirPath)'))" /internalize "$(TargetPath)" "$(TargetDir)ComputeWeave.dll" "$(TargetDir)ComputeWeave.Core.dll"" />
|
||||
</Target>
|
||||
|
||||
<Target Name="PostBuild" AfterTargets="MergePluginAssembly" Condition="'$(SkipPluginDeploy)' != 'true' AND '$(BuildingSolutionFile)' != 'true'">
|
||||
<Exec Command="mkdir "$(YMM4DirPath)user\plugin\$(ProjectName)" > NUL 2>&1
copy "$(TargetDir)WaveOptics.Abstractions.dll" "$(YMM4DirPath)user\plugin\$(ProjectName)\" && copy "$(TargetDir)plugin\$(TargetFileName)" "$(YMM4DirPath)user\plugin\$(ProjectName)\"" />
|
||||
</Target>
|
||||
|
||||
</Project>
|
||||
@@ -1,11 +0,0 @@
|
||||
using WaveOptics.Abstractions;
|
||||
using WaveOptics.Optics;
|
||||
|
||||
namespace WaveOptics;
|
||||
|
||||
public static class WaveOpticsApi
|
||||
{
|
||||
public static OpticalApiVersion Version => OpticalApiVersion.Current;
|
||||
|
||||
public static IPsfGenerator CreatePsfGenerator() => new FraunhoferPsfGenerator();
|
||||
}
|
||||
@@ -1,44 +0,0 @@
|
||||
using WaveOptics.Effects;
|
||||
|
||||
namespace WaveOptics;
|
||||
|
||||
internal static class WaveOpticsSettings
|
||||
{
|
||||
public const int MinimumKernelRadius = 1;
|
||||
public const int DefaultKernelRadius = 15;
|
||||
public const int MaximumKernelRadius = 63;
|
||||
public const int MaximumKernelSize = MaximumKernelRadius * 2 + 1;
|
||||
public const int MaximumRank = MaximumKernelSize;
|
||||
public const double SeparableResidualRatio = 1e-4;
|
||||
public const int WeightsLength = MaximumRank * 2 * MaximumKernelSize;
|
||||
public const int HorizontalConvolutionBlock = 16;
|
||||
public const int VerticalConvolutionBlock = 8;
|
||||
public const int SourceHashSpan = 16;
|
||||
public const int DefaultCanvasMargin = (DefaultKernelRadius + 3) & ~3;
|
||||
public const int MaximumCanvasSize = 8192;
|
||||
public const int ScratchLength = 7;
|
||||
public const int ScratchLitCount = 0;
|
||||
public const int ScratchBoundsMinX = 1;
|
||||
public const int ScratchBoundsMinY = 2;
|
||||
public const int ScratchBoundsMaxX = 3;
|
||||
public const int ScratchBoundsMaxY = 4;
|
||||
public const int ScratchHashSum = 5;
|
||||
public const int ScratchHashMix = 6;
|
||||
public const int MaximumPendingSubmissions = 32;
|
||||
|
||||
public static int GetPupilGridSize(WaveOpticsQuality quality)
|
||||
=> quality switch
|
||||
{
|
||||
WaveOpticsQuality.Draft => 128,
|
||||
WaveOpticsQuality.High => 512,
|
||||
_ => 256,
|
||||
};
|
||||
|
||||
public static int GetPupilDiameterSamples(int pupilGridSize) => pupilGridSize / 4;
|
||||
|
||||
public static int GetKernelSize(int kernelRadius) => kernelRadius * 2 + 1;
|
||||
|
||||
public static int GetCanvasMargin(int kernelRadius) => Math.Max(DefaultCanvasMargin, (kernelRadius + 3) & ~3);
|
||||
|
||||
public static int GetWeightOffset(int term, int axis) => (term * 2 + axis) * MaximumKernelSize;
|
||||
}
|
||||
@@ -1,102 +0,0 @@
|
||||
using System.Diagnostics;
|
||||
using System.Reflection;
|
||||
using System.Windows;
|
||||
using System.Windows.Threading;
|
||||
using Telemetry;
|
||||
|
||||
namespace WaveOptics;
|
||||
|
||||
internal static class WaveOpticsTelemetry
|
||||
{
|
||||
private const int MaxChainLength = 5;
|
||||
private const int MaxFrames = 100;
|
||||
|
||||
private static readonly Assembly Own = typeof(WaveOpticsTelemetry).Assembly;
|
||||
private static int _started;
|
||||
|
||||
public static void EnsureStartedOnce()
|
||||
{
|
||||
var application = Application.Current;
|
||||
if (application is null || Interlocked.Exchange(ref _started, 1) != 0)
|
||||
return;
|
||||
|
||||
AppDomain.CurrentDomain.UnhandledException += OnUnhandledException;
|
||||
TaskScheduler.UnobservedTaskException += OnUnobservedTaskException;
|
||||
application.DispatcherUnhandledException += OnDispatcherUnhandledException;
|
||||
|
||||
TelemetryReporter.Start();
|
||||
}
|
||||
|
||||
public static void Report(Exception exception)
|
||||
{
|
||||
if (Volatile.Read(ref _started) != 0)
|
||||
TelemetryReporter.Report(exception);
|
||||
}
|
||||
|
||||
private static void OnUnhandledException(object sender, UnhandledExceptionEventArgs e)
|
||||
=> ReportOwn(e.ExceptionObject as Exception);
|
||||
|
||||
private static void OnUnobservedTaskException(object? sender, UnobservedTaskExceptionEventArgs e)
|
||||
=> ReportOwn(e.Exception);
|
||||
|
||||
private static void OnDispatcherUnhandledException(object sender, DispatcherUnhandledExceptionEventArgs e)
|
||||
=> ReportOwn(e.Exception);
|
||||
|
||||
private static void ReportOwn(Exception? exception)
|
||||
{
|
||||
if (exception is not null && IsOwn(exception))
|
||||
TelemetryReporter.Report(exception);
|
||||
}
|
||||
|
||||
private static bool IsOwn(Exception exception)
|
||||
{
|
||||
var current = exception;
|
||||
for (var depth = 0; current is not null && depth < MaxChainLength; depth++)
|
||||
{
|
||||
if (HasOwnFrame(current))
|
||||
return true;
|
||||
|
||||
current = current is AggregateException aggregate && aggregate.InnerExceptions.Count > 0
|
||||
? aggregate.InnerExceptions[0]
|
||||
: current.InnerException;
|
||||
}
|
||||
|
||||
return false;
|
||||
}
|
||||
|
||||
private static bool HasOwnFrame(Exception exception)
|
||||
{
|
||||
StackFrame[]? frames;
|
||||
|
||||
try
|
||||
{
|
||||
frames = new StackTrace(exception, false).GetFrames();
|
||||
}
|
||||
catch (Exception)
|
||||
{
|
||||
return false;
|
||||
}
|
||||
|
||||
if (frames is null)
|
||||
return false;
|
||||
|
||||
for (var index = 0; index < Math.Min(frames.Length, MaxFrames); index++)
|
||||
{
|
||||
MethodBase? method;
|
||||
|
||||
try
|
||||
{
|
||||
method = frames[index].GetMethod();
|
||||
}
|
||||
catch (Exception)
|
||||
{
|
||||
continue;
|
||||
}
|
||||
|
||||
if (method?.DeclaringType is { } declaringType && ReferenceEquals(declaringType.Assembly, Own))
|
||||
return true;
|
||||
}
|
||||
|
||||
return false;
|
||||
}
|
||||
}
|
||||
@@ -1,53 +0,0 @@
|
||||
using System.Windows;
|
||||
using GitHubUpdateNotifier;
|
||||
using WaveOptics.Effects;
|
||||
using YukkuriMovieMaker.Plugin.Update;
|
||||
using Notifier = GitHubUpdateNotifier.GitHubUpdateNotifier;
|
||||
|
||||
namespace WaveOptics;
|
||||
|
||||
internal static class WaveOpticsUpdateNotifier
|
||||
{
|
||||
private const string Owner = "routersys";
|
||||
private const string Repository = "YMM4-WaveOptics";
|
||||
private static int _started;
|
||||
|
||||
public static void EnsureCheckedOnce()
|
||||
{
|
||||
if (Application.Current is null || Interlocked.Exchange(ref _started, 1) != 0)
|
||||
return;
|
||||
_ = RunAsync();
|
||||
}
|
||||
|
||||
private static async Task RunAsync()
|
||||
{
|
||||
try
|
||||
{
|
||||
var options = new UpdateNotifierOptions
|
||||
{
|
||||
CurrentVersion = PluginVersion.FromAssemblyInformationalVersion(typeof(WaveOpticsUpdateNotifier)),
|
||||
IncludePrerelease = false,
|
||||
MessageFormatter = FormatMessage,
|
||||
NotificationHandler = ShowNotificationAsync,
|
||||
};
|
||||
await new Notifier(Owner, Repository, options).NotifyAsync().ConfigureAwait(false);
|
||||
}
|
||||
catch (Exception exception)
|
||||
{
|
||||
if (exception is not UpdateCheckException)
|
||||
WaveOpticsTelemetry.Report(exception);
|
||||
}
|
||||
}
|
||||
|
||||
private static string FormatMessage(UpdateInfo update)
|
||||
=> string.Format(Texts.UpdateAvailableMessage, update.TagName) + Environment.NewLine + update.ReleaseUrl;
|
||||
|
||||
private static Task ShowNotificationAsync(UpdateNotification notification, CancellationToken cancellationToken)
|
||||
{
|
||||
var application = Application.Current;
|
||||
if (application is null)
|
||||
return Task.CompletedTask;
|
||||
return application.Dispatcher.InvokeAsync(() =>
|
||||
MessageBox.Show(notification.Message, Texts.WaveOptics, MessageBoxButton.OK, MessageBoxImage.Information)).Task;
|
||||
}
|
||||
}
|
||||
サブモジュール YMM4-GitHubUpdateNotifier が ca66e0f21d から削除されました。
サブモジュール YMM4-Telemetry が 04010903ca から削除されました。
サブモジュール YukkuriMovieMaker.Generator が 371bb51a6b から削除されました。
@@ -0,0 +1,8 @@
|
||||
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 64 64" role="img" aria-label="波動光学">
|
||||
<rect width="64" height="64" rx="14" fill="#0d1230"/>
|
||||
<g stroke="#ffe9b0" stroke-width="2.2" stroke-linecap="round" opacity="0.9">
|
||||
<path d="M32 7v50M10.4 19.5l43.2 25M10.4 44.5l43.2-25"/>
|
||||
</g>
|
||||
<circle cx="32" cy="32" r="12" fill="none" stroke="#7aa7ff" stroke-width="1.6" opacity="0.75"/>
|
||||
<circle cx="32" cy="32" r="5.2" fill="#ffffff"/>
|
||||
</svg>
|
||||
|
変更後 幅: | 高さ: | サイズ: 457 B |
バイナリファイルは表示されません。
|
変更後 幅: | 高さ: | サイズ: 191 KiB |
160ファイル中100ファイルを読み込みました。 変更されたファイルが多すぎるため、それ以降のファイルは表示していません。
さらに表示
新しいイシューから参照
ユーザーをブロックする