81 コミット
作成者 SHA1 メッセージ 日付
routersys 1ae9d03f30 バージョンをv1.1.1へ更新する
リリース / build-and-release (workflow_dispatch) Actions がタグ v1.1.1 のコミットから作成しました
2026-10-04 09:46:00 +09:00
routersys 18e81d7828 光源形状「面」の説明を実際の範囲に合わせる
・光源形状「面」の説明が、実際に光が広がる範囲と違っていた不具合を修正-F
2026-10-04 09:36:24 +09:00
routersys 1ea860f431 更新の確認で報告する例外の記載を実装に合わせる 2026-10-04 09:24:07 +09:00
routersys 8631d6127a 輸送と描画を再利用する条件を追記する 2026-10-04 04:55:57 +09:00
routersys ddcbacd873 仕組みと不透明度の説明を実装に合わせて書き直す 2026-10-04 04:55:48 +09:00
routersys 2bf019a1ad 更新の確認の通信の失敗の例を実装に合わせる 2026-10-04 04:55:34 +09:00
routersys f67608e9d4 カテゴリの表記をYMM4の表示に合わせる 2026-10-04 04:55:16 +09:00
routersys 6aa784d1fa バージョンをv1.1.0へ更新する
リリース / build-and-release (workflow_dispatch) Actions がタグ v1.1.0 のコミットから作成しました
2026-10-03 17:22:50 +09:00
routersys d0982fd9e8 回収の後の相互運用の描画の試験に制限時間を設ける 2026-10-03 17:21:48 +09:00
routersys c1dcbe93f4 格子の資源が回収された後に輸送を計算し直す試験を追加する 2026-10-03 17:18:23 +09:00
routersys 2c2ec7e82a 変化が収まった後に輸送を使い回す試験を追加する 2026-10-03 14:30:46 +09:00
routersys 45099026ca 入力や光源が変わり続けるときは判定を待たずに輸送を進める
・開口や光の形のアニメーション、動画の素材などで光の輸送を毎フレーム計算し直すときの処理を高速化-M
2026-10-03 14:30:45 +09:00
routersys fb3e9b4eab ベンチマークに開口を動かす場面を加える 2026-10-03 13:55:08 +09:00
routersys 0f4ddba5c4 粗い格子の解法と反復のまとめ方の設定値の試験を追加する 2026-10-03 13:54:20 +09:00
routersys ff7f5f0036 細かい格子の反復を数回分ずつ1回のディスパッチで進める
・光の輸送を計算し直すときの処理をさらに高速化-M
2026-10-03 13:53:16 +09:00
routersys 5963640b2a 粗い格子の反復を1回のディスパッチで解く
・入力や光源を変えたときの光の輸送の計算を高速化-M
2026-10-03 13:43:34 +09:00
routersys f941a41fb7 区画の外まで広がる光の試験を追加する 2026-10-03 12:47:04 +09:00
routersys 1b5c151389 光を散らす段のタイルを先頭の画素の行き先に置く
・光を散らす計算を高速化-M
2026-10-03 12:40:58 +09:00
routersys 52b780ff46 描画の計算の完了を待たずに処理を戻す
・描画の計算でCPUとGPUの処理を重ねて待ち時間を短縮-M
2026-10-03 12:27:52 +09:00
routersys 6c6bd8886c 中身だけが変わる入力の描画の試験を追加する 2026-10-03 12:24:26 +09:00
routersys e7a871e5a6 描き直しを描画の設定が変わったときに限る
・入力と設定が変わらないフレームの描画を高速化-M
2026-10-03 12:23:37 +09:00
routersys 0dfc9e0bff 輸送の計算を省く経路の試験を追加する 2026-10-03 12:23:37 +09:00
routersys 5c6ef0eff8 輸送の計算を入力と光源が変わったときに限る
・入力と光源の設定が変わらないフレームで、光の輸送を計算し直さないよう高速化-M
2026-10-03 12:23:37 +09:00
routersys b7ea295cba 格子の資源が回収された後の描画の試験を追加する 2026-10-03 12:16:11 +09:00
routersys 98f995b325 回収された格子の資源を描画の前に作り直す
・GPUのメモリが逼迫して資源が回収された後に、描画が失敗し続ける不具合を修正-F
2026-10-03 12:16:11 +09:00
routersys 869cf397c1 ignoreの記載を既存群に揃える 2026-10-03 08:55:02 +09:00
routersys 4e8bfd2ba9 Plugin_Readmeへ不具合の報告を追記する 2026-10-03 08:54:49 +09:00
routersys 0b5edfedd7 READMEへ不具合の報告を追記する 2026-10-03 08:54:48 +09:00
routersys dadbd5f3e7 不要なusingを取り除く 2026-10-03 08:53:38 +09:00
routersys c14452bce9 WPFアプリケーションの外でテレメトリーを送らない試験を追加する 2026-10-03 08:51:15 +09:00
routersys ae1a23f4bb テレメトリーを変異試験の対象から外す 2026-10-03 08:50:19 +09:00
routersys f8f0cd35c9 更新確認で例外を握り潰さず報告する 2026-10-03 08:50:18 +09:00
routersys 1248d2f205 ホストとDirect2Dからの呼び出し口で例外を報告する
・想定していない例外を開発者へ自動で報告する機能を追加-A
2026-10-03 08:49:36 +09:00
routersys b4721d9e6e CausticTransportTelemetryを追加する 2026-10-03 08:48:55 +09:00
routersys 308cd49e19 Telemetryをコンパイルに含める 2026-10-03 08:47:58 +09:00
routersys a70ecd5874 YMM4-Telemetryサブモジュールを追加する 2026-10-03 08:47:15 +09:00
routersys 3959dad74e 未対応の大きさの後に描く試験を追加する 2026-10-03 08:45:16 +09:00
routersys 8513733c7a 入力の無い処理器の試験を追加する 2026-10-03 08:45:16 +09:00
routersys 77ab1c2889 巨大な画像を小さな絞りへ集める試験を追加する 2026-10-03 08:45:16 +09:00
routersys 09b5da5a00 画素数が溢れる寸法を拒む試験を追加する 2026-10-03 08:45:16 +09:00
routersys a0a1082702 描画前のパイプラインへ共有テクスチャを渡す試験を追加する 2026-10-03 08:45:15 +09:00
routersys f70b312f3b 寸法を一部だけ変えた後の描画の試験を追加する 2026-10-03 08:45:15 +09:00
routersys 6851793b4c スケジューラーの無い提供者の試験を追加する 2026-10-03 08:45:15 +09:00
routersys c7ce22e27c 入力が無いときの出力範囲の試験を追加する 2026-10-03 08:45:15 +09:00
routersys a368a37362 量を変えた後の描画の試験を追加する 2026-10-03 08:45:15 +09:00
routersys 3b6e0fea25 アニメーション対象の使い回しの試験を追加する 2026-10-03 08:45:15 +09:00
routersys 3909840dd7 寸法の境界の試験を追加する 2026-10-03 08:45:15 +09:00
routersys 1919da4952 シェーダーを変異試験の対象から外す 2026-10-03 08:45:14 +09:00
routersys 6fe0496a21 WPFアプリケーションの外での挙動の試験を追加する 2026-10-03 08:45:14 +09:00
routersys b9e27b4d1d 更新確認をWPF起動中に限り行う 2026-10-03 08:45:14 +09:00
routersys 8315567f0e 処理器の試験を追加する 2026-10-03 08:45:14 +09:00
routersys f5511dece5 カスタムエフェクトの試験を追加する 2026-10-03 08:45:14 +09:00
routersys 8554ea4207 文言の試験を追加する 2026-10-03 08:45:14 +09:00
routersys 890b0a3df3 パラメータの試験を既存群の形で書き直す 2026-10-03 08:45:13 +09:00
routersys ce47bd3678 相互運用の試験を土台の上に書き直す 2026-10-03 08:45:13 +09:00
routersys e338ab71f1 輸送計算の試験を分ける 2026-10-03 08:45:13 +09:00
routersys 8547abc39e 設定値の試験を分ける 2026-10-03 08:45:13 +09:00
routersys d1daf4ce6e 試験の土台を追加する 2026-10-03 08:45:13 +09:00
routersys 4603ff4954 テストプロジェクトの設定を既存群に揃える 2026-10-03 08:45:13 +09:00
routersys df95a369ad Stryker.NETで変異試験を行う 2026-10-03 08:45:13 +09:00
routersys 1a1990117b テストの依存関係を最新にする 2026-10-03 08:45:13 +09:00
routersys 2fc60fe578 ルートファイルをSolution Itemsへ加える 2026-10-03 08:45:12 +09:00
routersys 99b4861da1 サードパーティの表記をComputeWeaveにする 2026-10-03 08:44:59 +09:00
routersys 923f514524 リリースワークフローを既存群と同一の構成にする 2026-10-03 08:44:59 +09:00
routersys 3031f222ac 使われなくなったFxcPathの設定を取り除く 2026-10-03 08:44:59 +09:00
routersys 0bf36cb796 シェーダーの生成をCausticTransport.Shaderへ切り出す 2026-10-03 08:44:59 +09:00
routersys 88a8312928 スプラットのディスパッチ切り上げをComputeWeaveへ委ねる 2026-10-03 08:44:59 +09:00
routersys f939998d5f 相互運用を外部提供者と共有テクスチャ集合へ移す 2026-10-03 08:44:59 +09:00
routersys 8db4babae2 輸送格子の資源を生成ホストの所有スロットへ移す 2026-10-03 08:44:59 +09:00
routersys 2ac57bdd46 ComputeWeaveを配布DLLへ統合し衝突を防ぐ
・配布物をCausticTransport.dllの1つに統合-M
2026-10-03 08:44:59 +09:00
routersys 9421b1c83e ComputeSharpサブモジュールの登録を外す 2026-10-03 08:44:59 +09:00
routersys 8e8a57273a ComputeWeaveをNuGet参照へ移行する 2026-10-03 08:44:58 +09:00
routersys d751ee1af3 ハーネスを実機描画によるゴールデン検証基盤にする 2026-10-03 08:44:44 +09:00
routersys c60793e69c Textsの名前空間をファイル形式にする 2026-09-26 00:28:37 +09:00
routersys 783b04dc70 エディターのコード規則を追加する 2026-09-26 00:28:37 +09:00
routersys a595b9ead4 プルリクエストのテンプレートを追加する 2026-09-23 13:56:12 +09:00
routersys 4e93ec4a34 Issueのテンプレートを追加する 2026-09-23 13:56:11 +09:00
routersys 9b22712b2c スポンサーの設定を追加する 2026-09-23 13:56:11 +09:00
routersys 12d6d9cefa 貢献の手引きを追加する 2026-09-23 13:56:11 +09:00
routersys 56071dfe9c セキュリティポリシーを追加する 2026-09-23 13:56:10 +09:00
routersys 62db033072 行動規範を追加する 2026-09-23 13:56:10 +09:00
72個のファイルの変更、6755行の追加、1560行の削除

検索条件に一致するファイルはありません

+13
ファイルの表示
@@ -0,0 +1,13 @@
{
"version": 1,
"isRoot": true,
"tools": {
"dotnet-stryker": {
"version": "5.0.0",
"commands": [
"dotnet-stryker"
],
"rollForward": false
}
}
}
+77
ファイルの表示
@@ -0,0 +1,77 @@
root = true
[*]
indent_style = space
indent_size = 4
tab_width = 4
end_of_line = crlf
charset = utf-8
trim_trailing_whitespace = true
insert_final_newline = true
[*.{json,yml,yaml}]
indent_size = 2
[*.{csproj,props,targets,vcxproj,filters,slnx,resx,xml}]
charset = unset
indent_style = unset
indent_size = unset
[*.md]
trim_trailing_whitespace = false
[*.cs]
dotnet_separate_import_directive_groups = false
dotnet_sort_system_directives_first = true
dotnet_style_qualification_for_field = false:error
dotnet_style_qualification_for_property = false:error
dotnet_style_qualification_for_method = false:error
dotnet_style_qualification_for_event = false:error
dotnet_style_predefined_type_for_locals_parameters_members = true:error
dotnet_style_predefined_type_for_member_access = true:error
dotnet_style_readonly_field = true:warning
dotnet_style_coalesce_expression = true:suggestion
dotnet_style_null_propagation = true:suggestion
dotnet_style_object_initializer = true:suggestion
dotnet_style_collection_initializer = true:suggestion
dotnet_style_prefer_is_null_check_over_reference_equality_method = true:warning
dotnet_style_operator_placement_when_wrapping = beginning_of_line
dotnet_code_quality_unused_parameters = all:warning
csharp_style_namespace_declarations = file_scoped:error
csharp_using_directive_placement = outside_namespace:error
csharp_prefer_braces = when_multiline:silent
csharp_style_var_for_built_in_types = true:silent
csharp_style_var_when_type_is_apparent = true:silent
csharp_style_var_elsewhere = true:silent
csharp_style_expression_bodied_methods = when_on_single_line:silent
csharp_style_expression_bodied_properties = true:silent
csharp_style_expression_bodied_accessors = true:silent
csharp_style_prefer_pattern_matching = true:suggestion
csharp_style_prefer_not_pattern = true:suggestion
csharp_style_prefer_switch_expression = true:suggestion
csharp_style_prefer_readonly_struct = true:warning
csharp_style_prefer_readonly_struct_member = true:warning
csharp_prefer_static_local_function = true:warning
csharp_style_prefer_primary_constructors = true:silent
csharp_new_line_before_open_brace = all
csharp_new_line_before_else = true
csharp_new_line_before_catch = true
csharp_new_line_before_finally = true
dotnet_diagnostic.IDE0005.severity = warning
dotnet_diagnostic.IDE0055.severity = warning
dotnet_diagnostic.IDE0161.severity = error
[{YMM4-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
-95
ファイルの表示
@@ -1,95 +0,0 @@
# v1.0.1 - 光輸送結像 for YMM4
光輸送結像エフェクトプラグインの修正と改善のリリースです。
画素数が1048560を超える映像で例外が発生し、アイテムの更新に失敗していた不具合を修正しました。合わせて対応する大きさの上限を定め、3840×2160と4096×2160を処理できるようにしました。
色の積算をグループ共有メモリでタイル化し、1フレームあたりの処理時間を短縮しました。1024×1000ではv1.0.0の13.71msから9.09msへ、v1.0.0では例外で処理できなかった3840×2160では、修正だけを適用した状態の74.50msから44.71msへ短縮しました。
積算の固定小数点の倍率が変わるため、出力の画素値はv1.0.0と完全には一致しません。タイル化の前後では全画素が一致します。根拠は「改善 3. 等価性の検証」に記載します。
---
## 修正
### 1. 積算バッファーのクリアがスレッドグループ数の上限を超える不具合
プレビューの再生中に`System.ArgumentOutOfRangeException`が発生し、アイテムの更新に失敗する不具合を修正しました。
原因は、色の積算バッファーのゼロ初期化を、要素数をそのまま反復数とする1次元のディスパッチで実行していたことです。このシェーダーのスレッドグループは64スレッドであり、積算バッファーの要素数は画素数の4倍であるため、ディスパッチするスレッドグループ数は画素数の16分の1になります。ComputeSharpが検証するスレッドグループ数の上限は1次元あたり65535であるため、画素数が1048560を超えると超過します。1920×1080では129600になり、報告された例外の値202500は3240000画素に対応します。
ゼロ初期化を、ComputeSharpの`ComputeContext.Clear`へ変更しました。この操作は`ClearUnorderedAccessViewUint`を発行するため、ディスパッチを伴わず、スレッドグループ数の上限の制約を受けません。輸送格子とマルチグリッドの最粗階層のゼロ初期化も同じ操作へ統一し、そのための専用シェーダー2種類を削除しました。
### 2. 対応する大きさの上限と上限超過時の素通し
色の積算は`Hlsl.InterlockedAdd`で加算するため固定小数点で行います。1つの積算先が受け取る値の上界は画素数と倍率の積であり、桁あふれしない条件は、この積が積算バッファーの型の最大値以下であることです。倍率の下限は256、余裕は1.5倍として算出しているため、符号付き32ビットでの上限は5592405画素でした。3840×2160の8294400画素はこの上限を超えており、桁あふれしない保証がありませんでした。
- 積算バッファーを符号付き32ビットから符号なし32ビットへ変更しました。積算へ加える値は、画素値と双線形の重みと分散時のアルファ配分のいずれも非負であるため、符号ビットは使用していませんでした。桁が2倍になり、上限は11184810画素へ広がります。4096×2160の8847360画素もこの範囲に含まれます。
- 倍率の算出の基準も符号なし32ビットの最大値へ改めました。3840×2160の倍率は256から345へ上がり、8ビット出力の量子化幅である255分の1より細かい刻みを保ちます。
- 桁あふれを隠していた`ResolveShader`の負値の切り上げを削除しました。符号なし32ビットの積算値は常に0以上です。
- 対応する大きさの判定を`CausticTransportSettings.IsSupportedSize`へ集約しました。辺が8192画素以下、かつ総画素数が11184810以下です。上限を超える入力にはカスタムシェーダーの`Amount`を0にし、入力映像をそのまま表示します。従来の判定は`int.MaxValue`を基準としており、テクスチャの確保がComputeSharpの検証で例外になる大きさを通していました。
- 辺の上限は、Direct3D 12のTexture2Dの上限である16384に対して余裕を取り、8192としました。本プラグインは共有テクスチャからDirect2Dのビットマップを作成するため、Direct2Dのビットマップの上限も効きます。この上限は機能レベルに依存します。
| 項目 | v1.0.0 | v1.0.1 |
|---|---|---|
| 積算バッファーの型 | 符号付き32ビット | 符号なし32ビット |
| 桁あふれしない画素数の上限 | 5592405 | 11184810 |
| 3840×2160の倍率 | 256 | 345 |
| 対応する辺の上限 | `int.MaxValue` | 8192 |
| 上限超過時の動作 | テクスチャの確保で例外 | 入力映像をそのまま表示 |
---
## 改善
### 1. スプラットのグループ共有メモリによるタイル化
スプラットは、各画素の色を輸送写像の移動先へ双線形の4点で加算する処理です。分散が0%のときは1画素につき4点×4成分で16回、分散が有効なときは色ごとに移動先が異なるため3色×4点×2成分で24回の大域アトミック加算を発行していました。分散が有効な3840×2160では1フレームあたり199065600回に達します。
段ごとに外して測ると、不透明な高周波の素材、3840×2160、標準品質、分散30%の1フレーム100.79msのうち、スプラットが88msを占めていました。輸送反復は1.4ms、解決とクリアは測定の変動に埋もれる水準です。スプラットの内訳は、変位のサンプリングを含む演算が8ms、残りが大域アトミック加算です。別の測定では、加算16回になる分散0%の経路が76.06ms、24回になる分散30%の経路が103.93msであり、処理時間は加算の回数にほぼ比例していました。
8×8画素のスレッドグループごとに、書き込み先の範囲を`InterlockedMin`と`InterlockedMax`で求め、範囲が10×10画素のタイルに収まる場合はグループ共有メモリへ加算してから、値が0でないセルだけを大域へ1回ずつ反映するようにしました。
- 隣り合う画素の移動先は重なるため、グループ内で合算した後の大域アトミック加算は、収まる場合に1画素あたり16回または24回から数回へ減ります。範囲がタイルに収まらない場合は従来どおり大域へ直接加算します。判定はグループ内で一様です。
- 分散が有効なときは色ごとに移動先が離れるため、色ごとの3段に分け、各段で範囲の算出とタイルの集約を行います。
- グループ共有メモリは10×10画素×4成分の400要素で1.6KBです。タイルのクリアと反映は、実際に使う範囲だけを走査します。
- グループ共有メモリを使うシェーダーは、グループ内のすべてのスレッドが同期に到達する必要があります。ComputeSharpが生成するシェーダーの入口は`For`へ渡した反復数を上限としてスレッドを間引くため、画像の寸法のままディスパッチすると端のグループの一部のスレッドが同期に到達しません。この状態ではGPUが停止し、デバイスが失われることを16×12の入力で確認しました。スプラットのディスパッチ範囲は`CausticTransportSettings.GetSplatDispatchSize`で8の倍数へ切り上げ、画像の範囲の判定をシェーダー内へ移しています。切り上げで増えたスレッドは範囲外として何も加算しません。
### 2. 性能
検証ハーネス、Releaseビルドによる実測値です。GPUはIntel Iris Xe Graphicsです。素材は検証ハーネスが生成するテスト画像で、外周5%が透明です。共有テクスチャの経路で20フレームの平均を1標本として12標本を取得し、その中央値を1回の実行の値とします。3つのリビジョンの実行ファイルを別々に用意し、交互に3回ずつ実行した最小値を記載します。この環境は連続測定で温度が上がると同じ実行ファイルでも33%遅くなるため、交互実行で熱状態の影響をそろえています。品質は高品質、集光度50%、光源サイズ50%、分散30%、面粗さ20%です。
| 項目 | v1.0.0 | 修正だけを適用 | v1.0.1 |
|---|---:|---:|---:|
| 1024×1000 面光源の1フレーム | 13.71ms | 13.94ms | 9.09ms |
| 1024×1000 円光源の1フレーム | 14.10ms | 13.77ms | 8.63ms |
| 1920×1080 面光源の1フレーム | 例外 | 20.54ms | 13.87ms |
| 1920×1080 円光源の1フレーム | 例外 | 20.64ms | 13.34ms |
| 3840×2160 面光源の1フレーム | 例外 | 74.50ms | 44.71ms |
| 3840×2160 円光源の1フレーム | 例外 | 76.86ms | 45.13ms |
v1.0.0は画素数が1048560を超えると例外で停止するため、1920×1080と3840×2160を測定できません。検証ハーネスも1024×1000の測定を終えた直後に同じ例外で停止します。1024×1000でv1.0.0と修正だけを適用した状態が同水準であることから、この短縮はタイル化によるものです。倍率は1024×1000で1.53倍から1.60倍、1920×1080で1.48倍から1.55倍、3840×2160で1.67倍から1.70倍です。
倍率は素材によって変わります。移動先の範囲がタイルに収まる割合が高いほど大域アトミック加算の削減が大きくなるためです。全画素が不透明な高周波の素材では、テストプロジェクトへ一時的に追加した同じ12標本の中央値の計測で、1920×1080が2.14倍から2.25倍、3840×2160が2.06倍から2.46倍でした。この計測は交互実行ではないため、熱状態の影響を含みます。
### 3. 等価性の検証
- タイル化の前後の出力は全画素で一致します。6種類の寸法、光源形状4種類、集光度3水準、分散3水準、光源サイズ、面粗さ、品質3段階を組み合わせた3276条件について、出力全画素のFNV-1a 64のハッシュを比較し、すべて一致しました。
- 一致する理由は、加える値が従来と同じ丸めを経た整数であり、整数の加算が結合的かつ可換であることです。集約の順序によらず合計は同一になります。値が0の加算を省く箇所も合計を変えません。浮動小数点の加算は導入していません。
- 出力の画素値はv1.0.0とは完全には一致しません。積算バッファーの型を変えたことで固定小数点の倍率が変わるためです。倍率は1024×1000で1398から2796、3840×2160で256から345へ上がるため、量子化は細かくなる方向です。
- xUnitテスト57件がすべて成功し、クリーンビルドの警告は0です。スレッドグループの境界に合わない5×3、9×1、1×9、17×15の入力を処理する検証と、ディスパッチ範囲が8の倍数へ切り上がる検証を追加しました。
### 4. 採用しなかった構成
同じ試みを繰り返さないように、測定して採用しなかった構成を記録します。いずれも3840×2160の1フレームの実測値で、素材は全画素が不透明な高周波の画像です。タイル寸法の比較は集光度50%と集光度90%の2条件で、20フレームの平均を3回取った最小値です。スレッドグループの比較はタイル化を行う前の実装での10フレームの平均です。
| 構成 | 測定結果 |
|---|---|
| スレッドグループを16×16へ拡大 | 91.41msから97.01msへ悪化 |
| タイルを8×8 | 集光度50%で42.36ms、集光度90%で87.16ms |
| タイルを9×9 | 集光度50%で37.70ms、集光度90%で41.92ms |
| タイルを12×12 | 集光度50%で38.95ms、集光度90%で41.62ms |
| タイルを16×16 | 集光度50%で45.23ms、集光度90%で49.81ms |
採用した10×10は集光度50%で36.31ms、集光度90%で39.75msです。8×8では、移動量が小さいときの書き込み先の範囲が8×8画素の移動と双線形の1画素で9×9画素になり、タイルに収まらないため集約されません。16×16ではグループ共有メモリが4KBになり、占有率が下がります。
### 5. 検証ハーネスの測定手法の変更
共有テクスチャの経路の測定を、1280×720で品質3段階を20フレームの平均1回で測る形から、1024×1000と1920×1080と3840×2160の3寸法について面光源と円光源を、20フレームの平均を1標本とする12標本の中央値で測る形へ変更しました。従来の1回の平均は、GPUのクロック状態と温度の影響を受け、同じ実行ファイルでも実行ごとに33%ばらつくことがあります。本リリースの性能表はこの手法で測定した値です。
+1
ファイルの表示
@@ -0,0 +1 @@
github: routersys
+102
ファイルの表示
@@ -0,0 +1,102 @@
name: 不具合の報告
description: エラーが出る、強制終了する、出力が乱れる、README と違う動きをする、といった不具合を報告します。
title: "[Bug] "
labels: ["bug"]
body:
- type: markdown
attributes:
value: |
脆弱性はここに書かず、リポジトリのセキュリティポリシーに従って非公開で報告してください。
README と実際の動きが違い、文書のほうが誤りだと考えるときは、文書の不備を使ってください。
- type: input
id: plugin-version
attributes:
label: プラグインのバージョン
description: GitHub のリリースか、配布パッケージの Readme.txt の見出しで確かめられます。
placeholder: v1.0.0
validations:
required: true
- type: input
id: ymm4-version
attributes:
label: YukkuriMovieMaker4 のバージョン
description: YukkuriMovieMaker4 のメインウィンドウのタイトルに表示されるバージョンを、そのまま書いてください。
placeholder: v4.56.1.0 Lite
validations:
required: true
- type: input
id: os
attributes:
label: Windows のバージョン
description: winver を実行し、ビルド番号まで書いてください。
placeholder: Windows 11 24H2, 26100.2605
validations:
required: true
- type: input
id: gpu
attributes:
label: GPU とドライバー
description: 描画や GPU に関わる不具合では必ず書いてください。デバイスマネージャーか dxdiag に表示される GPU の名前と、ドライバーのバージョンです。
- type: textarea
id: expected
attributes:
label: 期待した動き
description: 何が起きると考えたか。README に根拠があれば、その箇所も書いてください。
validations:
required: true
- type: textarea
id: actual
attributes:
label: 実際の動き
description: 実際に起きたこと。エラー画面が出たときは、その内容を省略せずに貼ってください。
validations:
required: true
- type: textarea
id: steps
attributes:
label: 再現の手順
description: |
新しいプロジェクトから不具合が起きるまでの操作を、番号を付けて書いてください。変えた設定の項目と値も書いてください。
プロジェクトファイルや素材は、zip に圧縮して添付できます。添付したファイルは誰でも見られます。プロジェクトファイルには素材を置いたフォルダーのパスが記録されるので、公開できない情報が無いかを確かめてください。
placeholder: |
1. 新しいプロジェクトを作る
2. アイテムを置き、本プラグインを使う
3. 設定を変える
4. 不具合が起きる
validations:
required: true
- type: dropdown
id: frequency
attributes:
label: 起きる頻度
description: ときどき起きるときは、何回試して何回起きたかを、下の「その他」の欄に書いてください。
options:
- 毎回起きる
- ときどき起きる
- 一度だけ起きた
validations:
required: true
- type: textarea
id: context
attributes:
label: その他
description: 一緒に使っているほかのプラグインや、関係すると思われることを書いてください。
- type: checkboxes
id: checks
attributes:
label: 報告の前に
options:
- label: 最新のリリースを使っています。
required: true
- label: 既存の Issue を検索し、同じ報告が無いことを確かめました。
required: true
+5
ファイルの表示
@@ -0,0 +1,5 @@
blank_issues_enabled: false
contact_links:
- name: YukkuriMovieMaker4 本体の不具合
url: https://manjubox.net/contact/
about: 本体に原因がある不具合は、YukkuriMovieMaker4 の「ヘルプ」の「フィードバックを送信」か、公式サイトのお問い合わせから報告してください。
+63
ファイルの表示
@@ -0,0 +1,63 @@
name: 文書の不備
description: 誤り、書き漏れ、実際の動きとの食い違いがある文書を報告します。
title: "[Docs] "
labels: ["documentation"]
body:
- type: markdown
attributes:
value: |
実際の動きと文書が食い違うときは、ここで報告して構いません。動きのほうが誤りだと考えるときは、不具合の報告を使ってください。
- type: dropdown
id: location
attributes:
label: 文書
options:
- README
- 配布パッケージの Readme.txt
- 設定の項目の名前や説明
- 貢献の手引き、セキュリティポリシー、行動規範
- その他
validations:
required: true
- type: input
id: reference
attributes:
label: 文書の中の位置
description: 見出し、行番号、設定の項目の名前のどれかを書いてください。
placeholder: README の「制限事項」の 2 つ目の項目
validations:
required: true
- type: textarea
id: says
attributes:
label: 今の記述
description: そのまま引用してください。元の文書を開かずに検討できるようにするためです。
validations:
required: true
- type: textarea
id: problem
attributes:
label: どこが問題か
description: |
誤り、書き漏れ、曖昧さのどれに当たるかを書いてください。それによって読む人が何を取り違えるかも書いてください。
実際の動きと食い違っているときは、文書と動きのどちらを直すべきと考えるかも書いてください。
validations:
required: true
- type: textarea
id: suggestion
attributes:
label: 提案する文面
description: 具体的な文面があると、早く直せます。
- type: checkboxes
id: checks
attributes:
label: 報告の前に
options:
- label: 最新のリリースか、既定のブランチの最新の文書で確かめました。
required: true
+42
ファイルの表示
@@ -0,0 +1,42 @@
name: 機能の提案
description: 新しい機能や設定の項目、既存の動きの変更を提案します。
title: "[Proposal] "
labels: ["enhancement"]
body:
- type: textarea
id: problem
attributes:
label: 困っていること
description: 今のプラグインでできないことや、手間がかかることを、利用者の立場で書いてください。
validations:
required: true
- type: textarea
id: workaround
attributes:
label: 今はどうしているか
description: 今の回避策と、それにかかる手間を書いてください。回避策が無ければ、その旨を書いてください。
validations:
required: true
- type: textarea
id: proposal
attributes:
label: 提案する動き
description: どう動いてほしいかを書いてください。設定の項目を増やす提案では、項目の名前、範囲、既定値の案も書いてください。
- type: textarea
id: alternatives
attributes:
label: 検討したほかの方法
description: ほかに考えた方法があれば、それでは足りない理由と一緒に書いてください。
- type: checkboxes
id: checks
attributes:
label: 提案の前に
options:
- label: 既存の Issue を検索し、同じ提案が無いことを確かめました。
required: true
- label: 最新のリリースに同じ機能が無いことを確かめました。
required: true
+49
ファイルの表示
@@ -0,0 +1,49 @@
name: 使い方の質問
description: 使い方や、実際の動きが仕様どおりかを尋ねます。
title: "[Question] "
labels: ["question"]
body:
- type: markdown
attributes:
value: |
プラグインの不具合だと分かっているときは、不具合の報告を使ってください。
- type: textarea
id: question
attributes:
label: 質問
description: 背景を書く前に、質問を 1 文か 2 文で書いてください。
validations:
required: true
- type: textarea
id: goal
attributes:
label: 何をしようとしているか
description: つまずいている操作だけでなく、最終的に何を作りたいかを書いてください。
validations:
required: true
- type: textarea
id: tried
attributes:
label: 試したこと
description: 試した設定と、そのとき実際に起きたことを書いてください。
- type: input
id: plugin-version
attributes:
label: プラグインのバージョン
placeholder: v1.0.0
validations:
required: true
- type: checkboxes
id: checks
attributes:
label: 質問の前に
options:
- label: README の該当する節を読みました。
required: true
- label: 既存の Issue を検索し、同じ質問が無いことを確かめました。
required: true
ファイルの表示
差分なしでファイル名を変更。
+99 -18
ファイルの表示
@@ -1,13 +1,17 @@
========================================
光輸送結像 for YMM4 v1.0.1
光輸送結像 for YMM4 v1.1.1
========================================
YukkuriMovieMaker4上で動作する、現在のフレームの明るさを光の分布として
輸送格子へ集め、選択した光源形状へ広げた光を元映像へ結像させる映像
エフェクトプラグインです。
輸送格子へ集め、選択した光源形状へ広げた光を元映像へ結像させる
映像エフェクトプラグインです。
履歴フレーム、参照画像、深度情報、学習済みモデルは使用しません。
結果は入力映像と設定から決定論的に決まり、
同じ環境と設定では常に同じ結果になります。
面、円、横スリット、縦スリットの4種類から光源形状を選択できます。
強さ、集光度、光源サイズ、分散、面粗さの5項目はアニメーションに
対応しています。
集光度をアニメーションで変えると、光源形状へ広がった光から入力映像が
立ち上がる遷移や、入力映像が光源形状へ崩れる遷移を作れます。
エフェクトの種類一覧では「光輸送結像」として表示されます。
--------------------------------------------------------------------------------
■ 動作要件
@@ -27,27 +31,59 @@ YukkuriMovieMaker4上で動作する、現在のフレームの明るさを光
Direct3D 11デバイスとの共有テクスチャおよび共有フェンスを作成できない
場合は、エフェクトを適用せず入力映像を表示します。
- 処理対象: 現在のフレームだけを処理します。履歴フレーム、外部画像、
深度情報、学習済みモデルは使用しません。
- 処理対象: 計算には現在のフレームの色と不透明度だけを使用します。
履歴フレーム、外部画像、深度情報、学習済みモデルは使用しません。
処理する範囲は、このエフェクトに入る映像を囲む矩形です。輸送格子は、
処理する範囲を縦横に区切ったセルの並びです。光は処理する範囲の外へは
広がらず、範囲の端へ向かう光は端の画素に集まります。光の分布を集めた後の
処理は、3つの段階に分かれます。輸送の計算は、光の分布を光源形状へ移す
輸送写像を求める段階です。描画は、輸送写像に沿って各画素の色と不透明度を
動かし、光の像を作る段階です。合成は、光の像と入力映像を強さの割合で
混ぜる段階です。
- 対応する大きさ: 処理する範囲の辺が8192画素以下、かつ総画素数が
11184810以下の入力に対応します。3840×2160と4096×2160はこの範囲に
含まれます。範囲を超える入力には、エフェクトを適用せず入力映像を
表示します。
- 素材の上限: 処理する範囲の辺が8192画素以下、かつ総画素数が11184810以下の
入力に対応します。3840×2160と4096×2160はこの条件を満たし、6000×4000は
総画素数が上限を超えます。判定には、プロジェクトの解像度ではなく、
処理する範囲の大きさを使います。条件を満たさない入力には、エフェクトを
適用せず入力映像を表示します。
- 処理負荷: 入力映像の画素数に応じて処理量とGPUメモリ使用量が増えます。
最高品質は格子解像度と反復回数が最も多いため、高品質と標準より
処理負荷が高くなります。
格子解像度は、輸送格子の長辺のセル数の上限です。最高品質は格子解像度と
反復回数が最も多いため、高品質と標準より処理負荷が高くなります。
- 集光度100%: 集光度が100%のときは輸送を行わず、入力映像をそのまま
出力します。強さが0%のときも入力を変更しません。
- キャッシュ: 入力映像とその大きさ、品質、光源形状、光源サイズが変わらない
フレームでは、輸送の計算を再利用します。光源形状が面のときは、光源サイズを
変えても輸送の計算を再利用します。光の分布と、変化の判定に使う2個の整数は、
毎フレームGPUで求めます。2個の整数は、全画素の色と不透明度から作ります。
この整数と入力映像の大きさが、輸送を計算したときと同じなら、輸送の計算を
再利用します。動画のように、直近に読み戻した2フレーム分の整数が違う
あいだは、入力映像が変わり続けているとみなします。このときは、
今のフレームの整数の読み戻しを待たず、毎フレーム輸送の計算をやり直し、
整数は次のフレームで読み戻します。
変化が最後に起きたフレームの次のフレームでも、直近に読み戻した2フレーム分の
整数はまだ違います。そのため、このフレームでも輸送の計算をやり直し、
その次のフレームから再利用します。光源形状が円かスリットのときに
光源サイズをアニメーションで変えると、輸送の計算を毎フレームやり直します。
入力映像が変わり続けるときと、光源サイズを動かすときは、処理が重くなります。
- 描き直し: 集光度、分散、面粗さ、シードが変わらず、輸送の計算も再利用する
フレームでは、描画も再利用します。面粗さが0%のときは、シードを変えても
描き直しません。集光度、分散、面粗さ、シードのどれかだけを変えた
フレームでは、輸送の計算は再利用し、描画だけをやり直します。強さだけを
変えたフレームでは、描き直さず、合成の量だけを変えます。
- 集光度100%と強さ0%: 集光度が100%のときは輸送の計算も描画も行わず、
入力映像をそのまま出力します。強さが0%のときも入力を変更しません。
- シードと再現性: 散乱は、シードとセル位置から決定論的に算出します。
時間値は散乱の生成に使用しません。面粗さが0%のとき、シードは結果へ
影響しません。
- 透明部分: 入力のアルファ値を出力へ維持します。完全に透明な画素は
輸送の対象から除外されます。
- 透明部分: 光の像は、色と不透明度をまとめて移動先へ動かして作ります。
完全に透明な画素は動かしませんが、その位置へほかの画素から移ってきた
色と不透明度は描かれます。内容が移って空いた位置は、ほかから何も
移ってこなければ透明に近づきます。出力の不透明度は、色と同じく、
入力映像と光の像を強さの割合で混ぜた値です。
- 更新通知: エフェクトを最初に生成したときに、YMM4の実行中に一度だけ
新しい正式版を確認します。更新情報を取得できない場合は通知せず、
@@ -55,6 +91,51 @@ YukkuriMovieMaker4上で動作する、現在のフレームの明るさを光
- 本プラグインを使用する前に、YMM4のプロジェクトファイルのバックアップを
作成することを推奨します。
--------------------------------------------------------------------------------
■ 不具合の報告
--------------------------------------------------------------------------------
本プラグインは、想定していない例外が起きたときに、その内容を開発者へ自動で
送信します。同意は求めず、常に送信します。
送信する情報は次のとおりです。
例外 : 型の完全名、メッセージ、スタックトレース
発生位置 : モジュール名、関数名、ファイル名、行番号
プラグイン : アセンブリ名、バージョン
実行環境 : OSの名前とバージョン、.NETのバージョン、
CPUのアーキテクチャ、論理プロセッサ数
識別子 : YMM4の起動ごとに決まるセッション識別子、報告ごとの識別子
映像の中身とプロジェクトの内容は送信しません。継続して個人を追跡する
識別子も持ちません。セッション識別子はYMM4を起動し直すと別の値に
なります。メッセージとファイル名に含まれる利用者名などの文字列は、送信の
前に置き換えます。送信元のIPアドレスは受信側へ渡す手前で取り除いています。
送信するのは想定していない例外だけです。YMM4が本プラグインのエフェクトを
作るとき、フレームごとに更新するとき、入力をつなぎ直すとき、破棄するときと、
Direct2Dがシェーダーの定数を書き込むときに起きた例外を報告し、その後は
YMM4へそのまま渡します。更新の確認では、更新情報の取得と比較で起きた例外は
報告しません。通知の文を組み立てて表示するときに起きた例外は報告し、
YMM4へは渡しません。画面の操作やバックグラウンドの処理で未処理になった
例外も報告しますが、本プラグインのコードが関わる例外に限ります。
本プラグインの外で起きた例外は送信しません。
次の失敗は送信しません。
効果をかけないだけで済ませるもの : Direct3D 12デバイスを取得できない、
YMM4のDirect3D 11デバイスとの共有
テクスチャや共有フェンスを作成できない、
処理する範囲の辺が8192画素を超えるか、
総画素数が11184810を超えるときに、
エフェクトを適用せず入力映像を
表示したとき
更新の確認の通信の失敗 : manjubox.netとGitHubのどちらへも
接続できない
送信できなかった報告はYMM4のユーザーフォルダーへ退避します。
次にYMM4を起動したあと、本プラグインのエフェクトを生成するか、
同じくYMM4-Telemetryで報告する別のプラグインが動き始めると、
退避した報告を1回の起動で10件まで送り直します。
送信も再送も非同期に行うため、通信を待って起動と描画が遅くなることは
ありません。
--------------------------------------------------------------------------------
■ 免責事項
--------------------------------------------------------------------------------
@@ -68,9 +149,9 @@ YukkuriMovieMaker4上で動作する、現在のフレームの明るさを光
--------------------------------------------------------------------------------
■ サードパーティライセンス
--------------------------------------------------------------------------------
本プラグインはComputeSharp(MIT License)を同梱しています。
ライセンスの全文は同梱のLICENSEフォルダー(ComputeSharp.txt)に収録しています。
ComputeSharp : Copyright (c) 2024 Sergio Pedri
本プラグインはComputeWeave(MIT License)を同梱しています。
ライセンスの全文は同梱のLICENSEフォルダー(ComputeWeave.txt)に収録しています。
ComputeWeave : Copyright (c) 2024 Sergio Pedri
--------------------------------------------------------------------------------
■ ライセンス
--------------------------------------------------------------------------------
+87
ファイルの表示
@@ -0,0 +1,87 @@
<!--
当てはまらない節は消してください。「関連する Issue」と「動きの変更」の節は残し、該当しないときは「なし」と書いてください。
-->
## 概要
<!--
何をどう変えたか。なぜその変更が必要か。
-->
## 関連する Issue
<!--
新しい機能、設定の項目や既定値の変更、大きめの不具合の修正、意図して出力を変える変更、互換性を損なう変更、コードの構成を大きく変える変更は、先に Issue で合意してください。
Issue が無い変更では、下の行を「なし」に書き換えてください。
-->
Closes #
## 変更の種類
<!-- 当てはまるものを残してください。 -->
- 不具合の修正
- 機能の追加
- 動きの変更
- 性能の改善
- テストの追加
- 依存関係の更新
- 文書
- ビルド、リリース
## 動きの変更
<!--
利用者から見て何が変わるか。設定の項目、既定値、出力の結果、エラーの出方の変化も含みます。
保存済みのプロジェクトの結果が変わるなら、必ず書いてください。
-->
## 検証
<!--
手元で実際に確かめた結果を書いてください。
- ビルドの結果と、テストのプロジェクトがあればテストの結果
- YukkuriMovieMaker4 で実際に動かして確かめたこと
- 実行できなかったテストと、その理由
実際に動かして観察したこと、コードを読んで判断したこと、推測したことを分けて書いてください。
-->
使った YukkuriMovieMaker4 のバージョン:
GPU に関わる変更では、使った GPU とドライバー:
## 確認
<!-- テストのプロジェクトが無いリポジトリでは、実装とテストを分ける項目を消してください。 -->
- [ ] 1 つの目的の変更だけを含み、関係の無い整理や整形を含めていない。
- [ ] どのコミットも、それ単独でビルドが通る。
- [ ] 実装の変更と、それを確かめるテストを、別のコミットに分けた。
- [ ] コミットの件名は日本語で書き、50 文字以内に収め、「〜する」の形で終えた。日本語で書けない場合は、その旨を「レビューで見てほしい点」に書いた。
- [ ] コミットの本文は、リリースノートでの変更の分類を指定する行を求められたときだけ書いた。
- [ ] 変更する箇所で既に使われている実装のパターンに従った。
- [ ] 新しく書いたコードにコメントを入れず、コメントアウトしたコードも残していない。既存のコメントとドキュメントコメントは残した。
- [ ] 自分の変更で増えたビルドの警告を直した。
- [ ] 出力を変えるつもりの無い変更では、変更前と変更後で出力が一致することを確かめた。
- [ ] この変更と関係の無い依存関係の更新を含めていない。
- [ ] 動きを変えた場合、README を直した。`.github/Plugin_Readme.txt` があるリポジトリでは、それも直した。
- [ ] バージョンを上げる変更を含めていない。
## 性能の改善を主張する場合
<!-- それ以外の場合は、この節ごと消してください。 -->
- [ ] 同じ機材、ドライバー、設定、電源の条件で、変更前と変更後のビルドを交互に繰り返し測った。
- [ ] 測定の間を空け、ほかのプロセスが GPU を使っていない状態で測った。
- [ ] 正しさの確認と性能の測定を、別々に実行した。
<!--
測定の条件と、測定値。
-->
## レビューで見てほしい点
<!--
判断に迷った点、意見を聞きたい点、意図して外した部分とその理由。
-->
+306 -47
ファイルの表示
@@ -14,31 +14,20 @@ jobs:
steps:
- name: ソースコードのチェックアウト
uses: actions/checkout@v4
uses: actions/checkout@v7
with:
submodules: recursive
fetch-depth: 0
- name: .NET SDKのセットアップ
uses: actions/setup-dotnet@v4
- name: .NET SDK のセットアップ
uses: actions/setup-dotnet@v6
with:
dotnet-version: '10.0.x'
- name: fxc.exeの検索
id: fxc
shell: pwsh
run: |
$fxc = Get-ChildItem "C:\Program Files (x86)\Windows Kits\10\bin" -Recurse -Filter "fxc.exe" |
Where-Object { $_.FullName -like "*x64*" } |
Sort-Object FullName -Descending |
Select-Object -First 1
if (-not $fxc) {
Write-Error "fxc.exeが見つかりませんでした。"
exit 1
}
Write-Host "fxc.exeの場所: $($fxc.FullName)"
echo "FXC_PATH=$($fxc.FullName)" >> $env:GITHUB_OUTPUT
- name: MSBuild のセットアップ
uses: microsoft/setup-msbuild@v3
- name: YMM4最新リリースの取得と解凍
- name: YMM4 最新リリースの取得と解凍
id: ymm4
shell: pwsh
run: |
@@ -48,20 +37,12 @@ jobs:
if (-not $asset) {
$asset = $release.assets | Where-Object { $_.name -like "*.zip" } | Select-Object -First 1
}
if (-not $asset) {
Write-Error "YMM4のリリースにZIPファイルが見つかりませんでした。"
exit 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
if (-not $ymm4Dir) {
Write-Error "YukkuriMovieMaker.dllが見つかりませんでした。"
exit 1
}
Write-Host "YMM4 DLLディレクトリ: $ymm4Dir"
Write-Host "YMM4 DLL ディレクトリ: $ymm4Dir"
echo "YMM4_DIR=$ymm4Dir\" >> $env:GITHUB_OUTPUT
- name: タグ名からバージョンを取得
@@ -70,17 +51,47 @@ jobs:
run: |
$tag = "${{ github.ref_name }}"
echo "TAG=$tag" >> $env:GITHUB_OUTPUT
echo "VERSION=$($tag.TrimStart('v'))" >> $env:GITHUB_OUTPUT
- name: resxファイルの生成
- name: バージョン記載の照合
shell: pwsh
run: |
$proj = "CausticTransport/CausticTransport.csproj"
dotnet build "$proj" `
-c Release `
-p:YMM4DirPath="${{ steps.ymm4.outputs.YMM4_DIR }}" `
-p:FxcPath="${{ steps.fxc.outputs.FXC_PATH }}" `
-p:Platform=x64 `
-p:SkipPluginDeploy=true
$tag = "${{ steps.version.outputs.TAG }}"
$version = "${{ steps.version.outputs.VERSION }}"
$problems = @()
$csprojPath = "CausticTransport/CausticTransport.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 CausticTransport.Shader/CausticTransport.Shader.vcxproj `
/p:Configuration=Release `
/p:Platform=Win32 `
/nologo
- name: プロジェクトのビルド
shell: pwsh
@@ -89,7 +100,6 @@ jobs:
dotnet build "$proj" `
-c Release `
-p:YMM4DirPath="${{ steps.ymm4.outputs.YMM4_DIR }}" `
-p:FxcPath="${{ steps.fxc.outputs.FXC_PATH }}" `
-p:Platform=x64 `
-p:SkipPluginDeploy=true
@@ -99,7 +109,6 @@ jobs:
dotnet build CausticTransport.Tests/CausticTransport.Tests.csproj `
-c Release `
-p:YMM4DirPath="${{ steps.ymm4.outputs.YMM4_DIR }}" `
-p:FxcPath="${{ steps.fxc.outputs.FXC_PATH }}" `
-p:Platform=x64 `
-p:SkipPluginDeploy=true `
-maxcpucount:1
@@ -118,17 +127,20 @@ jobs:
id: package
shell: pwsh
run: |
$version = "${{ steps.version.outputs.TAG }}"
$outDir = "CausticTransport/bin/x64/Release/net10.0-windows10.0.19041.0"
$version = "${{ steps.version.outputs.TAG }}"
$outDir = "CausticTransport/bin/x64/Release/net10.0-windows10.0.19041.0"
$stageRoot = "stage/CausticTransport"
$pkgName = "CausticTransport_$version.ymme"
$pkgName = "CausticTransport_$version.ymme"
New-Item -ItemType Directory -Path $stageRoot -Force | Out-Null
New-Item -ItemType Directory -Path "$stageRoot/LICENSE" -Force | Out-Null
Copy-Item "$outDir/CausticTransport.dll" "$stageRoot/"
Copy-Item "$outDir/CausticTransport.ComputeSharp.dll" "$stageRoot/"
Copy-Item "$outDir/CausticTransport.ComputeSharp.Core.dll" "$stageRoot/"
$dll = "$outDir/plugin/CausticTransport.dll"
if (-not (Test-Path $dll)) {
Write-Error "ビルド結果に CausticTransport.dll が見つかりませんでした: $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"
@@ -138,17 +150,264 @@ jobs:
}
}
Copy-Item ".github/LICENSE/*.txt" "$stageRoot/LICENSE/"
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: GitHubリリースの作成
uses: softprops/action-gh-release@v2
- 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: .github/CHANGELOG.md
body_path: release-body.md
files: ${{ steps.package.outputs.PKG_NAME }}
draft: false
prerelease: false
+3 -1
ファイルの表示
@@ -362,4 +362,6 @@ MigrationBackup/
.ionide/
# Fody - auto-generated XML schema
FodyWeavers.xsd
FodyWeavers.xsd
# Stryker.NET
StrykerOutput/
+3 -3
ファイルの表示
@@ -4,6 +4,6 @@
[submodule "YMM4-GitHubUpdateNotifier"]
path = YMM4-GitHubUpdateNotifier
url = https://github.com/routersys/YMM4-GitHubUpdateNotifier.git
[submodule "ComputeSharp"]
path = ComputeSharp
url = https://github.com/routersys/ComputeSharp.git
[submodule "YMM4-Telemetry"]
path = YMM4-Telemetry
url = https://github.com/routersys/YMM4-Telemetry.git
+81
ファイルの表示
@@ -0,0 +1,81 @@
# Contributor Covenant 行動規範
## 私たちの約束
メンバー、貢献者、リーダーである私たちは、年齢、体格、目に見える障害と目に見えない障害、民族、性的特徴、性自認と性表現、経験の程度、教育、社会経済的地位、国籍、外見、人種、宗教、性的アイデンティティと性的指向を問わず、コミュニティへの参加を誰にとっても嫌がらせの無いものにすることを誓います。
私たちは、開かれていて誰もが歓迎される、多様で包摂的な、健全なコミュニティを作るように行動し、交流することを誓います。
## 私たちの基準
コミュニティのよい環境を作る行動の例は、次のとおりです。
- ほかの人に共感と思いやりを示す
- 異なる意見、視点、経験を尊重する
- 建設的な意見を伝え、また快く受け入れる
- 自分たちの誤りに責任を持ち、影響を受けた人に謝り、その経験から学ぶ
- 自分個人にとってだけでなく、コミュニティ全体にとって最善のことを考える
受け入れられない行動の例は、次のとおりです。
- 性的な言葉や画像を使うこと、どのような形であれ、相手に性的な関心を向けることや言い寄ること
- 荒らし、侮辱的または軽蔑的な発言、個人攻撃や政治的な攻撃
- 公の場か私的な場かを問わない嫌がらせ
- 住所やメールアドレスなど、ほかの人の個人情報を明示の許可なく公開すること
- 仕事の場で不適切と合理的に考えられるその他の行為
## 執行の責任
コミュニティリーダーは、受け入れられる行動の基準を明確にし、それを守らせる責任を負います。不適切、脅迫的、攻撃的、または有害と判断した行動には、適切で公正な是正措置をとります。
コミュニティリーダーは、この行動規範に沿わないコメント、コミット、コード、Wiki の編集、Issue、その他の貢献を削除、編集、または却下する権利と責任を持ちます。モデレーションの判断については、適切な場合に理由を伝えます。
## 適用範囲
この行動規範は、コミュニティのあらゆる場で適用されます。個人が公の場でコミュニティを公式に代表しているときにも適用されます。コミュニティを代表しているときとは、たとえば、公式のメールアドレスを使うとき、公式のソーシャルメディアのアカウントから投稿するとき、オンラインやオフラインのイベントで任命された代表として行動するときです。
## 執行
虐待的な言動、嫌がらせ、その他の受け入れられない行動は、執行を担当するコミュニティリーダーへ github.routersys@gmail.com で報告できます。コミュニティリーダーは、すべての苦情を速やかかつ公正に確認し、調査します。
すべてのコミュニティリーダーは、事案を報告した人のプライバシーと安全を尊重する義務を負います。
## 執行のガイドライン
コミュニティリーダーは、この行動規範に違反すると判断した行動への処置を決めるとき、次に示すコミュニティへの影響に応じたガイドラインに従います。
### 1. 是正
コミュニティへの影響: 不適切な言葉づかいや、コミュニティの中で、仕事の場にふさわしくない、または歓迎されないと判断されるその他の行動。
処置: コミュニティリーダーが、非公開の書面による警告を送ります。違反の内容を明らかにし、その行動がなぜ不適切だったかを説明します。公の場での謝罪を求めることがあります。
### 2. 警告
コミュニティへの影響: 1 回の出来事、または一連の行動による違反。
処置: 行動が続いた場合の処置を示した警告を送ります。警告を受けた人は、定められた期間、関係する人々とやり取りしてはいけません。行動規範を執行する人々へ、求められていないのに接触することも、これに含まれます。コミュニティの場だけでなく、ソーシャルメディアなど外部の場でのやり取りも避けなければなりません。これらの条件に違反すると、一時的または永久的な参加禁止につながることがあります。
### 3. 一時的な参加禁止
コミュニティへの影響: 不適切な行動を続けることを含む、コミュニティの基準への重大な違反。
処置: 定められた期間、コミュニティとのあらゆるやり取りと、コミュニティに向けた公の発信を禁止します。この期間中は、公の場か私的な場かを問わず、関係する人々とのやり取りを認めません。行動規範を執行する人々へ、求められていないのに接触することも、これに含まれます。これらの条件に違反すると、永久的な参加禁止につながることがあります。
### 4. 永久的な参加禁止
コミュニティへの影響: コミュニティの基準に繰り返し違反すること。不適切な行動を続けること、個人への嫌がらせ、特定の属性を持つ人々への攻撃や中傷も、これに当たります。
処置: コミュニティの中でのあらゆる公のやり取りを、永久に禁止します。
## 出典
この行動規範は、[Contributor Covenant][homepage] のバージョン 2.0 を基にしています。原文は https://www.contributor-covenant.org/version/2/0/code_of_conduct.html にあります。日本語の文は、公式の日本語訳 https://www.contributor-covenant.org/ja/version/2/0/code_of_conduct/ を基に、原文と照らし合わせて改めたものです。
Contributor Covenant は、[クリエイティブ・コモンズ 表示 4.0 国際 ライセンス](https://creativecommons.org/licenses/by/4.0/deed.ja)のもとで提供されています。
コミュニティへの影響に応じたガイドラインは、[Mozilla の行動規範の執行の段階](https://github.com/mozilla/diversity)に着想を得ています。
[homepage]: https://www.contributor-covenant.org
この行動規範についてのよくある質問と回答は、https://www.contributor-covenant.org/faq にあります。ほかの言語の訳は、https://www.contributor-covenant.org/translations にあります。
+168
ファイルの表示
@@ -0,0 +1,168 @@
# 貢献の手引き
本プラグインへの貢献に関心を持っていただき、ありがとうございます。この手引きは、Issue の立て方、プルリクエストの作り方、変更の確かめ方、コードとコミットの書き方を定めます。
本プラグインでできることとできないことは、[README](README.md) に書いてあります。まず README を読んでください。
---
## 目次
1. [貢献の進め方](#貢献の進め方)
2. [開発環境](#開発環境)
3. [Issue](#issue)
4. [プルリクエスト](#プルリクエスト)
5. [検証](#検証)
6. [コードの規約](#コードの規約)
7. [コミットの規約](#コミットの規約)
8. [行動規範](#行動規範)
---
## 貢献の進め方
誤字の修正、文書の修正、軽微な不具合の修正は、そのままプルリクエストを送ってください。
新しい機能、設定の項目や既定値の変更、大きめの不具合の修正、意図して出力を変える変更、互換性を損なう変更、コードの構成を大きく変える変更は、先に Issue を立ててください。実装を始める前に、意図する動きと変更の範囲について合意するためです。どちらに当たるか迷ったときも、Issue を立ててください。
脆弱性は Issue に書かず、[セキュリティポリシー](SECURITY.md)に従って非公開で報告してください。
Issue とプルリクエストは、日本語か英語で書いてください。
---
## 開発環境
| 項目 | 要件 |
|---|---|
| OS | Windows 10 バージョン 2004 以降の 64bit 版 |
| SDK | .NET 10 |
| YukkuriMovieMaker4 | ビルドがインストール先の DLL を参照するため、手元に入れておく |
| シェーダーのビルド | HLSL をビルドのときにコンパイルするリポジトリでは Windows SDK が要る。シェーダーを `.vcxproj` でビルドするリポジトリでは、Visual Studio 2026 の「C++ によるデスクトップ開発」も要る |
### 取得
リポジトリをフォークし、自分のフォークをクローンしてください。リポジトリはサブモジュールを含むことがあるので、`--recursive` を付けます。
```console
git clone --recursive https://github.com/<自分のアカウント>/<リポジトリ名>.git
```
`--recursive` を付けずにクローンしたときは、後から次のコマンドでサブモジュールを取得できます。
```console
git submodule update --init --recursive
```
作業は `main` から切ったブランチで行ってください。
### YukkuriMovieMaker4 の場所
YukkuriMovieMaker4 のインストール先は、MSBuild のプロパティ `YMM4DirPath` で渡します。値の末尾には `\` を付けてください。
- コマンドラインでは、`-p:YMM4DirPath="<インストール先>\"` を付けてビルドします。PowerShell 7 以降で実行してください。Windows PowerShell 5.1 と cmd では、末尾の `\"` が正しく渡らないため、末尾を `\\"` と書いてください。
- Visual Studio でビルドするときは、プラグインのプロジェクトのフォルダーか、その上のフォルダーに `Directory.Build.props` があれば、その `YMM4DirPath` を手元で書き換えます。無ければ、環境変数 `YMM4DirPath` を設定します。書き換えた `Directory.Build.props` はコミットに含めないでください。サブモジュールの中にある `Directory.Build.props` は書き換えないでください。
### ビルド
ソリューションを開き、Release でビルドしてください。
シェーダーを `.vcxproj` でビルドするリポジトリでは、コマンドラインのビルドに Visual Studio の MSBuild を使ってください。.NET SDK の `dotnet` コマンドは `.vcxproj` を扱えません。テストは、`dotnet test <名前>.Tests\<名前>.Tests.csproj` のようにテストのプロジェクトのファイルを指定して実行してください。ビルドの手順は、`.github/workflows/release.yml` があればそこに書いてあります。
多くのリポジトリでは、ビルドの後にプラグインが YukkuriMovieMaker4 の `user\plugin` フォルダーへ自動でコピーされます。
- YukkuriMovieMaker4 を起動したままだと、コピーの段階で失敗します。ビルドの前に終了してください。
- 配布版のプラグインを入れているときは、同じ名前のファイルが上書きされます。
- コマンドラインでソリューションをビルドしたときはコピーしないリポジトリがあります。その場合は、プラグインのプロジェクトを指定してビルドしてください。
- `.csproj` に `SkipPluginDeploy` の条件があるリポジトリでは、`-p:SkipPluginDeploy=true` を付けるとコピーせずにビルドできます。
---
## Issue
Issue はテンプレートから立ててください。不具合の報告、文書の不備、機能の提案、使い方の質問の 4 つがあります。
不具合の報告には、次の内容を書いてください。
- 期待した動きと、実際の動き
- 再現の手順。できれば、問題が起きる最小のプロジェクトファイルや素材
- プラグインのバージョン、YukkuriMovieMaker4 のバージョン、Windows のバージョン
- 描画や GPU に関わる不具合では、GPU の名前とドライバーのバージョン
- エラー画面に出た内容。省略せずに貼ってください
ときどきしか起きない不具合も、確実な再現の手順が無いまま報告して構いません。何回試して何回起きたかと、どの操作の後に起きたかを書いてください。
コードを読んで見つけた不具合を報告するときは、実際に再現を確かめたかどうかも書いてください。
Issue に添付したファイルは、誰でも見られます。プロジェクトファイルには、素材を置いたフォルダーのパスが記録されています。パスにユーザー名が含まれることがあるので、公開できない情報が無いかを確かめてから添付してください。
不具合の情報を自動で送信するプラグインでも、Issue での報告には意味があります。自動で送られるのは、例外の内容と実行環境の一部です。そこに至った操作、YukkuriMovieMaker4 のバージョン、GPU、例外を伴わない描画の乱れは届きません。
---
## プルリクエスト
1 つのプルリクエストには、1 つの目的の変更だけを含めてください。関係の無い整理、整形、依存関係の更新を含めないでください。依存関係を更新するのは、必要な機能を使うため、不具合やセキュリティの問題を直すため、互換性を保つためなど、具体的な理由があるときだけにしてください。
特に注意が要るのは、次の箇所です。
- 設定の項目と、その既定値と範囲。保存済みのプロジェクトの結果が変わるおそれがある
- 出力の結果。変えるつもりの無い変更で、映像や音が変わっていないか
- GPU のリソース、ファイル、ハンドルの寿命
- 破棄の処理と、失敗したときの処理
- YukkuriMovieMaker4 の内部に手を入れるプラグインでは、YukkuriMovieMaker4 のバージョンによる違い
動きを変えたときは、同じプルリクエストで README を直してください。`.github/Plugin_Readme.txt` があるリポジトリでは、それも直してください。`Plugin_Readme.txt` は配布パッケージに `Readme.txt` として入り、利用者の手元に残ります。
バージョンを上げる変更は、プルリクエストに含めないでください。バージョンの更新とリリースは、開発者が行います。
レビューを受けて直すときは、コミットを目的ごとのまとまりに保つため、ブランチの履歴を組み直して強制プッシュして構いません。
プルリクエストを送った時点で、その貢献をリポジトリと同じライセンスで提供することに同意したものとみなします。リポジトリのライセンスは、リポジトリの直下にあるライセンスのファイルに書いてあります。
---
## 検証
プルリクエストには、手元で実際に確かめた結果を書いてください。
- ビルドの結果と、テストのプロジェクトがあればテストの結果
- YukkuriMovieMaker4 で実際に動かして確かめたこと。使った YukkuriMovieMaker4 のバージョンを添え、GPU に関わる変更では GPU の名前とドライバーのバージョンも添えてください
- 実行できなかったテストと、その理由
実際に動かして観察したこと、コードを読んで判断したこと、推測したことを分けて書いてください。
出力を変えるつもりの無い変更では、変更前と変更後で出力が一致することを確かめてください。`--golden` と `--verify` を持つハーネスのプロジェクトがあるリポジトリでは、それで描画を比べられます。基準値は、手元の環境で変更前のコミットから作り直し、作り直した基準値はコミットに含めないでください。そのようなハーネスが無いリポジトリでは、変更前と変更後の出力を比べてください。サブモジュールの中にあるハーネスは、この確認には使いません。
性能の改善を主張するときは、1 回の測定で判断しないでください。
- 同じ機材、ドライバー、設定、電源の条件で、変更前と変更後のビルドを交互に繰り返し測ってください。
- GPU と CPU の温度で値が変わるため、測定の間を空けてください。
- ほかのプロセスが GPU を使っていない状態で測ってください。
- 正しさの確認と性能の測定は、別々に実行してください。確認のための処理が、測定値を変えるためです。
---
## コードの規約
変更する箇所で既に使われている実装のパターンと書き方に従ってください。既存の実装どうしが食い違っているときは、どちらかを機械的にまねず、README とテストに照らして意図された動きを確かめ、それに合うほうへ揃えてください。
自分の変更で増えたビルドの警告は、放置せず原因を直してください。
新しく書くコードには、コメントを入れず、コメントアウトしたコードも残さないでください。既存のコードにあるコメントとドキュメントコメントは残してください。
---
## コミットの規約
- 1 つのコミットは、目的ごとのまとまりを保てる範囲で、できるだけ小さくしてください。どのコミットも、それ単独でビルドが通るようにしてください。
- 実装の変更と、それを確かめるテストは、別のコミットに分けてください。
- 件名は日本語で書き、50 文字以内に収め、「〜する」の形で終えてください。「〜を追加する」「〜を直す」はよい例です。「〜の追加」「〜を修正」のように名詞で終える形は使いません。
- 件名を日本語で書けないときは、プルリクエストにその旨を書いてください。
- 本文は書かないでください。例外は、リリースノートでの変更の分類を指定する行だけです。この行が要るときは、書き方をレビューで伝えます。
---
## 行動規範
貢献するすべての人に、[行動規範](CODE_OF_CONDUCT.md)に従うことを求めます。
+35 -4
ファイルの表示
@@ -3,12 +3,14 @@
<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>CausticTransport.Harness</AssemblyName>
<RootNamespace>CausticTransport.Harness</RootNamespace>
<PlatformTarget>x64</PlatformTarget>
<TieredCompilation>false</TieredCompilation>
</PropertyGroup>
<ItemGroup>
@@ -18,14 +20,43 @@
</ItemGroup>
<ItemGroup>
<Reference Include="YukkuriMovieMaker.Plugin">
<HintPath>$(YMM4DirPath)YukkuriMovieMaker.Plugin.dll</HintPath>
<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>
<Import Project="..\CausticTransport\ComputeSharp.Reference.props" />
</Project>
+55
ファイルの表示
@@ -0,0 +1,55 @@
using System.IO;
using System.Reflection;
using System.Text.Encodings.Web;
using System.Text.Json;
namespace CausticTransport.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} がありません。");
}
+63
ファイルの表示
@@ -0,0 +1,63 @@
using System.Diagnostics;
using Vortice.Direct3D11;
namespace CausticTransport.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();
}
}
+88
ファイルの表示
@@ -0,0 +1,88 @@
namespace CausticTransport.Harness;
internal sealed class HarnessException(string message) : Exception(message);
internal enum HarnessMode
{
Render,
Golden,
Verify,
Transition,
Compare,
Benchmark,
}
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 <画像>] 描画を計測します
""";
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 "--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 つだけ指定してください。");
}
+84
ファイルの表示
@@ -0,0 +1,84 @@
using System.Globalization;
using YukkuriMovieMaker.Commons;
using YukkuriMovieMaker.Json;
namespace CausticTransport.Harness;
internal static class HarnessCases
{
public static IEnumerable<(string Name, CausticTransportEffect Effect, IReadOnlyList<int> Frames)> All()
{
yield return ("default", Create(), [0]);
yield return ("focus-animated-frames", Create(effect => effect.Focus.CopyFrom(Linear(20d, 80d))), [0, 100, 200, 299]);
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 ("focus-0", Create(effect => effect.Focus.Values[0].Value = 0), [0]);
yield return ("focus-90", Create(effect => effect.Focus.Values[0].Value = 90), [0]);
yield return ("quality-balanced", Create(effect => effect.Quality = CausticTransportQuality.Balanced), [0]);
yield return ("quality-ultra", Create(effect => effect.Quality = CausticTransportQuality.Ultra), [0]);
yield return ("shape-circle", Create(effect => effect.LightShape = CausticLightShape.Circle), [0]);
yield return ("shape-horizontal-slit", Create(effect => effect.LightShape = CausticLightShape.HorizontalSlit), [0]);
yield return ("shape-vertical-slit", Create(effect => effect.LightShape = CausticLightShape.VerticalSlit), [0]);
yield return ("circle-aperture-5", Create(effect =>
{
effect.LightShape = CausticLightShape.Circle;
effect.ApertureSize.Values[0].Value = 5;
}), [0]);
yield return ("circle-aperture-100", Create(effect =>
{
effect.LightShape = CausticLightShape.Circle;
effect.ApertureSize.Values[0].Value = 100;
}), [0]);
yield return ("dispersion-0", Create(effect => effect.Dispersion.Values[0].Value = 0), [0]);
yield return ("dispersion-100", Create(effect => effect.Dispersion.Values[0].Value = 100), [0]);
yield return ("roughness-0", Create(effect => effect.Roughness.Values[0].Value = 0), [0]);
yield return ("roughness-100", Create(effect => effect.Roughness.Values[0].Value = 100), [0]);
yield return ("seed-42", Create(effect => effect.Seed = 42), [0]);
}
public static IEnumerable<(string Name, Func<CausticTransportEffect> Create, Action<CausticTransportEffect> Change, int Frame)> Transitions()
{
yield return ("amount-100-to-0", () => Create(), effect => effect.Amount.Values[0].Value = 0, 0);
yield return ("amount-0-to-100", () => Create(effect => effect.Amount.Values[0].Value = 0), effect => effect.Amount.Values[0].Value = 100, 0);
yield return ("amount-100-to-50", () => Create(), effect => effect.Amount.Values[0].Value = 50, 0);
yield return ("focus-50-to-100", () => Create(), effect => effect.Focus.Values[0].Value = 100, 0);
yield return ("focus-100-to-50", () => Create(effect => effect.Focus.Values[0].Value = 100), effect => effect.Focus.Values[0].Value = 50, 0);
yield return ("focus-50-to-0", () => Create(), effect => effect.Focus.Values[0].Value = 0, 0);
yield return ("quality-high-to-ultra", () => Create(), effect => effect.Quality = CausticTransportQuality.Ultra, 0);
yield return ("quality-high-to-balanced", () => Create(), effect => effect.Quality = CausticTransportQuality.Balanced, 0);
yield return ("shape-plane-to-circle", () => Create(), effect => effect.LightShape = CausticLightShape.Circle, 0);
yield return ("shape-circle-to-slit", () => Create(effect => effect.LightShape = CausticLightShape.Circle), effect => effect.LightShape = CausticLightShape.HorizontalSlit, 0);
yield return ("aperture-50-to-100", () => Create(effect => effect.LightShape = CausticLightShape.Circle), effect => effect.ApertureSize.Values[0].Value = 100, 0);
yield return ("dispersion-30-to-0", () => Create(), effect => effect.Dispersion.Values[0].Value = 0, 0);
yield return ("dispersion-0-to-100", () => Create(effect => effect.Dispersion.Values[0].Value = 0), effect => effect.Dispersion.Values[0].Value = 100, 0);
yield return ("roughness-20-to-100", () => Create(), effect => effect.Roughness.Values[0].Value = 100, 0);
yield return ("roughness-20-to-0", () => Create(), effect => effect.Roughness.Values[0].Value = 0, 0);
yield return ("seed-0-to-42", () => Create(), effect => effect.Seed = 42, 0);
}
public static IEnumerable<(string Name, CausticTransportEffect Effect)> Benchmarks()
{
yield return ("quality-balanced", Create(effect => effect.Quality = CausticTransportQuality.Balanced));
yield return ("default", Create());
yield return ("quality-ultra", Create(effect => effect.Quality = CausticTransportQuality.Ultra));
yield return ("shape-circle", Create(effect => effect.LightShape = CausticLightShape.Circle));
yield return ("dispersion-0", Create(effect => effect.Dispersion.Values[0].Value = 0));
yield return ("focus-animated", Create(effect => effect.Focus.CopyFrom(Linear(20d, 80d))));
yield return ("aperture-animated", Create(effect =>
{
effect.LightShape = CausticLightShape.Circle;
effect.ApertureSize.CopyFrom(Linear(30d, 80d));
}));
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 CausticTransportEffect Create(Action<CausticTransportEffect>? configure = null)
{
var effect = new CausticTransportEffect();
configure?.Invoke(effect);
return effect;
}
}
+59
ファイルの表示
@@ -0,0 +1,59 @@
using System.IO;
using System.Security.Cryptography;
using System.Windows.Media;
using System.Windows.Media.Imaging;
namespace CausticTransport.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);
}
}
+262
ファイルの表示
@@ -0,0 +1,262 @@
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 CausticTransport.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);
}
+37
ファイルの表示
@@ -0,0 +1,37 @@
using System.IO;
using System.Reflection;
using System.Runtime.CompilerServices;
namespace CausticTransport.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;
}
+46
ファイルの表示
@@ -0,0 +1,46 @@
namespace CausticTransport.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);
}
}
+301 -176
ファイルの表示
@@ -1,202 +1,327 @@
using System.Diagnostics;
using CausticTransport;
using ComputeSharp;
using System.IO;
using System.IO.Packaging;
using System.Security.Cryptography;
using CausticTransport.Harness;
using SharpGen.Runtime;
var width = 1280;
var height = 720;
var outputDirectory = args.Length > 0 ? args[0] : Path.Combine(AppContext.BaseDirectory, "harness-output");
Directory.CreateDirectory(outputDirectory);
const int CanvasWidth = 1280;
const int CanvasHeight = 720;
const int ImageWidth = 642;
const int ImageHeight = 478;
(int Width, int Height)[] BenchmarkSizes = [(1024, 1000), (1920, 1080), (3840, 2160)];
using var pipeline = CausticTransportPipeline.TryCreate();
if (pipeline is null)
_ = PackUriHelper.UriSchemePack;
HarnessArguments arguments;
try
{
Console.WriteLine("Direct3D 12 is unavailable.");
return 1;
arguments = HarnessArguments.Parse(args);
}
catch (HarnessException exception)
{
Console.Error.WriteLine(exception.Message);
Console.Error.WriteLine(HarnessArguments.Usage);
return 2;
}
var source = CreateTestImage(width, height);
var destination = new int[source.Length];
var reconstruction = new CausticTransportPipeline.Parameters(0, CausticTransportQuality.High, 1f, 0.5f, 0.5f, 0.5f, 7);
pipeline.Process(source, destination, width, height, in reconstruction);
var maxError = 0;
for (var index = 0; index < source.Length; index++)
try
{
for (var shift = 0; shift < 32; shift += 8)
maxError = Math.Max(maxError, Math.Abs(((source[index] >> shift) & 255) - ((destination[index] >> shift) & 255)));
}
Console.WriteLine($"reconstruction max channel error at focus=1: {maxError}");
if (arguments.Mode == HarnessMode.Compare)
return Compare(arguments.Before!, arguments.After!);
foreach (var quality in new[] { CausticTransportQuality.Balanced, CausticTransportQuality.High, CausticTransportQuality.Ultra })
{
var parameters = new CausticTransportPipeline.Parameters(1, quality, 0.5f, 0.5f, 0.3f, 0.2f, 7);
pipeline.Process(source, destination, width, height, in parameters);
pipeline.Process(source, destination, width, height, in parameters);
var stopwatch = Stopwatch.StartNew();
const int frames = 10;
for (var frame = 0; frame < frames; frame++)
pipeline.Process(source, destination, width, height, in parameters);
stopwatch.Stop();
Console.WriteLine($"{quality}: {stopwatch.Elapsed.TotalMilliseconds / frames:F2} ms/frame ({width}x{height})");
}
{
var device = ComputeSharp.GraphicsDevice.GetDefault();
foreach (var (benchWidth, benchHeight) in new[] { (1024, 1000), (1920, 1080), (3840, 2160) })
var outputDirectory = arguments.OutputDirectory ?? Path.Combine(AppContext.BaseDirectory, "harness-output");
if (arguments.Mode == HarnessMode.Benchmark)
{
using var sourceTexture = ComputeSharp.Interop.InteropServices.AllocateSharedReadWriteTexture2D<ComputeSharp.Bgra32, ComputeSharp.Float4>(device, benchWidth, benchHeight);
using var outputTexture = ComputeSharp.Interop.InteropServices.AllocateSharedReadWriteTexture2D<ComputeSharp.Bgra32, ComputeSharp.Float4>(device, benchWidth, benchHeight);
var benchSource = CreateTestImage(benchWidth, benchHeight);
var pixels = new ComputeSharp.Bgra32[benchSource.Length];
for (var index = 0; index < benchSource.Length; index++)
pixels[index].PackedValue = unchecked((uint)benchSource[index]);
sourceTexture.CopyFrom(pixels);
foreach (var shape in new[] { 0, 1 })
if (arguments.Input is { } benchmarkInput)
{
var parameters = new CausticTransportPipeline.Parameters(shape, CausticTransportQuality.High, 0.5f, 0.5f, 0.3f, 0.2f, 7);
var median = MeasureMedian(pipeline, sourceTexture, outputTexture, benchWidth, benchHeight, in parameters);
Console.WriteLine($"shared shape={shape}: {median:F2} ms/frame ({benchWidth}x{benchHeight})");
Benchmark(HarnessImage.Load(benchmarkInput));
}
}
}
foreach (var shape in new[] { 0, 1, 2, 3 })
{
foreach (var focus in new[] { 0f, 0.25f, 0.5f, 0.75f, 1f })
{
var parameters = new CausticTransportPipeline.Parameters(shape, CausticTransportQuality.High, focus, 0.4f, 0.4f, 0.25f, 7);
pipeline.Process(source, destination, width, height, in parameters);
var stats = ComputeStats(source, destination);
Console.WriteLine($"shape={shape} focus={focus:F2} massRatio={stats.MassRatio:F4} spreadStdDev={stats.SpreadStdDev:F4}");
WriteBmp(Path.Combine(outputDirectory, $"shape{shape}_focus{(int)(focus * 100):D3}.bmp"), destination, width, height);
}
}
WriteBmp(Path.Combine(outputDirectory, "source.bmp"), source, width, height);
Console.WriteLine($"images written to {outputDirectory}");
return 0;
static double MeasureMedian(
CausticTransportPipeline pipeline,
ReadWriteTexture2D<Bgra32, Float4> source,
ReadWriteTexture2D<Bgra32, Float4> destination,
int width,
int height,
in CausticTransportPipeline.Parameters parameters)
{
for (var warmup = 0; warmup < 5; warmup++)
pipeline.Process(source, destination, width, height, in parameters);
pipeline.WaitForCompletion();
var samples = new double[12];
for (var sample = 0; sample < samples.Length; sample++)
{
const int frames = 20;
var stopwatch = Stopwatch.StartNew();
for (var frame = 0; frame < frames; frame++)
pipeline.Process(source, destination, width, height, in parameters);
pipeline.WaitForCompletion();
stopwatch.Stop();
samples[sample] = stopwatch.Elapsed.TotalMilliseconds / frames;
}
Array.Sort(samples);
return (samples[5] + samples[6]) * 0.5;
}
static int[] CreateTestImage(int width, int height)
{
var pixels = new int[width * height];
for (var y = 0; y < height; y++)
{
for (var x = 0; x < width; x++)
else
{
var nx = x / (double)width;
var ny = y / (double)height;
var red = (int)(255 * nx);
var green = (int)(255 * ny);
var blue = (int)(255 * (0.5 + 0.5 * Math.Sin(nx * 12) * Math.Cos(ny * 9)));
var inCircle = Math.Pow(nx - 0.3, 2) + Math.Pow(ny - 0.35, 2) < 0.02;
var inBar = Math.Abs(nx - 0.7) < 0.04 && ny > 0.15 && ny < 0.85;
if (inCircle)
foreach (var (benchmarkWidth, benchmarkHeight) in BenchmarkSizes)
Benchmark(HarnessImage.Synthetic(benchmarkWidth, benchmarkHeight));
}
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)
{
red = 255;
green = 240;
blue = 210;
Console.Error.WriteLine($"{files[index]}: 出力が完全に透明です。");
failures++;
}
else if (inBar)
{
red = 40;
green = 220;
blue = 255;
}
var alpha = 255;
if (nx < 0.05 || ny < 0.05 || nx > 0.95 || ny > 0.95)
alpha = 0;
red = red * alpha / 255;
green = green * alpha / 255;
blue = blue * alpha / 255;
pixels[y * width + x] = alpha << 24 | red << 16 | green << 8 | blue;
}
}
return pixels;
});
Console.WriteLine($"-> {outputDirectory}");
return failures + CountDuplicates(cases) == 0 ? 0 : 1;
}
static (double MassRatio, double SpreadStdDev) ComputeStats(int[] source, int[] destination)
static int WriteGolden(HarnessRenderer renderer, HarnessImage image)
{
double sourceMass = 0;
double destinationMass = 0;
foreach (var pixel in source)
sourceMass += Luminance(pixel);
foreach (var pixel in destination)
destinationMass += Luminance(pixel);
var cases = Evaluate(renderer, null);
if (CountDuplicates(cases) != 0)
return 1;
if (cases.Count == 0)
Console.Error.WriteLine("ケースがありません。HarnessCases に書き足してください。");
var mean = destinationMass / destination.Length;
double variance = 0;
foreach (var pixel in destination)
{
var difference = Luminance(pixel) - mean;
variance += difference * difference;
}
return (sourceMass > 0 ? destinationMass / sourceMass : 0, Math.Sqrt(variance / destination.Length));
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 double Luminance(int pixel)
=> (0.2126 * ((pixel >> 16) & 255) + 0.7152 * ((pixel >> 8) & 255) + 0.0722 * (pixel & 255)) / 255.0;
static void WriteBmp(string path, int[] pixels, int width, int height)
static int Verify(HarnessRenderer renderer, HarnessImage image)
{
var stride = width * 3;
var padding = (4 - stride % 4) % 4;
var dataSize = (stride + padding) * height;
using var stream = new FileStream(path, FileMode.Create, FileAccess.Write);
using var writer = new BinaryWriter(stream);
writer.Write((byte)'B');
writer.Write((byte)'M');
writer.Write(54 + dataSize);
writer.Write(0);
writer.Write(54);
writer.Write(40);
writer.Write(width);
writer.Write(height);
writer.Write((short)1);
writer.Write((short)24);
writer.Write(0);
writer.Write(dataSize);
writer.Write(2835);
writer.Write(2835);
writer.Write(0);
writer.Write(0);
var pad = new byte[padding];
for (var y = height - 1; y >= 0; y--)
var golden = Golden.Load(Golden.PathFor(image));
var canvas = $"{renderer.CanvasWidth}x{renderer.CanvasHeight}";
if (golden.Input != image.Identity || golden.Canvas != canvas)
{
for (var x = 0; x < width; x++)
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))
{
var pixel = pixels[y * width + x];
writer.Write((byte)(pixel & 255));
writer.Write((byte)((pixel >> 8) & 255));
writer.Write((byte)((pixel >> 16) & 255));
Console.Error.WriteLine($"{name}: ケースがありません。基準値を書き直してください。");
failures++;
}
writer.Write(pad);
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 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;
}
+46
ファイルの表示
@@ -0,0 +1,46 @@
namespace CausticTransport.Harness;
internal static class SyntheticImage
{
public static byte[] Create(int width, int height)
{
var pixels = new byte[width * height * HarnessImage.BytesPerPixel];
for (var y = 0; y < height; y++)
{
for (var x = 0; x < width; x++)
{
var nx = x / (double)width;
var ny = y / (double)height;
var red = (int)(255 * nx);
var green = (int)(255 * ny);
var blue = (int)(255 * (0.5 + 0.5 * Math.Sin(nx * 12) * Math.Cos(ny * 9)));
var inCircle = Math.Pow(nx - 0.3, 2) + Math.Pow(ny - 0.35, 2) < 0.02;
var inBar = Math.Abs(nx - 0.7) < 0.04 && ny > 0.15 && ny < 0.85;
if (inCircle)
{
red = 255;
green = 240;
blue = 210;
}
else if (inBar)
{
red = 40;
green = 220;
blue = 255;
}
var alpha = 255;
if (nx < 0.05 || ny < 0.05 || nx > 0.95 || ny > 0.95)
alpha = 0;
var offset = (y * width + x) * HarnessImage.BytesPerPixel;
pixels[offset] = (byte)(blue * alpha / 255);
pixels[offset + 1] = (byte)(green * alpha / 255);
pixels[offset + 2] = (byte)(red * alpha / 255);
pixels[offset + 3] = (byte)alpha;
}
}
return pixels;
}
}
+137
ファイルの表示
@@ -0,0 +1,137 @@
{
"adapter": "Intel(R) Iris(R) Xe Graphics",
"driver": "32.0.101.7085",
"input": "synthetic 642x478 25181FB39D9D659D",
"canvas": "1280x720",
"cases": [
{
"name": "default",
"frames": [
0
],
"hash": "E81E93219057257D61B62218C6D47B9920F1134765AEAA34CBF8AC39B8034F47"
},
{
"name": "focus-animated-frames",
"frames": [
0,
100,
200,
299
],
"hash": "8B344039E5129EAFB8F3DD45736B2615A9C5ECBA95BA88723264BFF117A95057"
},
{
"name": "amount-0",
"frames": [
0
],
"hash": "425E90F4AC3BF34164FF2B03349F46AF593D36DD8CE15C3FA5FE7A83D4021BC7"
},
{
"name": "amount-50",
"frames": [
0
],
"hash": "3A3E62BE94A39D1E15A90AAC3BEB43BFA0973BB6AEEF63C503BE9A84FB98572A"
},
{
"name": "focus-0",
"frames": [
0
],
"hash": "43D47C7DE981F4DFAE1740E08CE1056787A131A62DFE1318594905177232E62D"
},
{
"name": "focus-90",
"frames": [
0
],
"hash": "D3E399F3C2C12161738C14A72E8730BC37718958CB9C8ADA1D75402ED4CEC480"
},
{
"name": "quality-balanced",
"frames": [
0
],
"hash": "36C373E654CCB7FC163E8BA633A508ABCAAFCFB7B4C596F047374ABD0862B1C4"
},
{
"name": "quality-ultra",
"frames": [
0
],
"hash": "D65D17DCEE980BA7D167F936E716E0321F0275249688B7DEB69B1E3A0EE43B1F"
},
{
"name": "shape-circle",
"frames": [
0
],
"hash": "FFF92596C884B43124564D91321D18E8AA820BE2E94E8BA5937078799643867C"
},
{
"name": "shape-horizontal-slit",
"frames": [
0
],
"hash": "7830013D2CF140419CFA4A9296CAFDDBA73ACACABC13918D72F835E72A1E7E6D"
},
{
"name": "shape-vertical-slit",
"frames": [
0
],
"hash": "A5DC6CDAB4B06690E3E485AC30D6C9A724841D171C33A5118C821F7BF95CB307"
},
{
"name": "circle-aperture-5",
"frames": [
0
],
"hash": "98491426BECCE352A98B0BD18F580D1CAA59277C38D0C3B1516FAB2B345AB9A4"
},
{
"name": "circle-aperture-100",
"frames": [
0
],
"hash": "BE65BF4D342C999F14BA44E4209A896FEEF300CC6FD8F3C0F51310C1E3A5793A"
},
{
"name": "dispersion-0",
"frames": [
0
],
"hash": "10273F557A0E68BBFE7C50EB961F26EC1E37D5B6DF8CC1393CE63C7385B6FA2E"
},
{
"name": "dispersion-100",
"frames": [
0
],
"hash": "0359ED1BE3B98CD5E6568717BE11A9DB2CFFCAC47D36AC256180725F8D6BA8D6"
},
{
"name": "roughness-0",
"frames": [
0
],
"hash": "80317D697DDD89604358BA3E67BE0B835C7BD5F7ADF9AF9A211E7A4E4922BE8C"
},
{
"name": "roughness-100",
"frames": [
0
],
"hash": "10C0F949EEEC886CE1FD157384A845C50BB58498598D9048D0DA656745712E76"
},
{
"name": "seed-42",
"frames": [
0
],
"hash": "2D4B334E5798BA74120B1669D34251400E2BB8D3A6E64F944324B714B61DD95A"
}
]
}
+157
ファイルの表示
@@ -0,0 +1,157 @@
<?xml version="1.0" encoding="utf-8"?>
<Project DefaultTargets="Build" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
<ItemGroup Label="ProjectConfigurations">
<ProjectConfiguration Include="Debug|Win32">
<Configuration>Debug</Configuration>
<Platform>Win32</Platform>
</ProjectConfiguration>
<ProjectConfiguration Include="Release|Win32">
<Configuration>Release</Configuration>
<Platform>Win32</Platform>
</ProjectConfiguration>
<ProjectConfiguration Include="Debug|x64">
<Configuration>Debug</Configuration>
<Platform>x64</Platform>
</ProjectConfiguration>
<ProjectConfiguration Include="Release|x64">
<Configuration>Release</Configuration>
<Platform>x64</Platform>
</ProjectConfiguration>
</ItemGroup>
<PropertyGroup Label="Globals">
<VCProjectVersion>17.0</VCProjectVersion>
<Keyword>Win32Proj</Keyword>
<ProjectGuid>{2A40D928-1A27-414E-BC6F-96D685B9A899}</ProjectGuid>
<RootNamespace>CausticTransportShader</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="CausticTransport.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>
+22
ファイルの表示
@@ -0,0 +1,22 @@
<?xml version="1.0" encoding="utf-8"?>
<Project ToolsVersion="4.0" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
<ItemGroup>
<Filter Include="ソース ファイル">
<UniqueIdentifier>{4FC737F1-C7A5-4376-A066-2A32D752A2FF}</UniqueIdentifier>
<Extensions>cpp;c;cc;cxx;c++;cppm;ixx;def;odl;idl;hpj;bat;asm;asmx</Extensions>
</Filter>
<Filter Include="ヘッダー ファイル">
<UniqueIdentifier>{93995380-89BD-4b04-88EB-625FBE52EBFB}</UniqueIdentifier>
<Extensions>h;hh;hpp;hxx;h++;hm;inl;inc;ipp;xsd</Extensions>
</Filter>
<Filter Include="リソース ファイル">
<UniqueIdentifier>{67DA6AB6-F800-4c08-8B7A-83BB121AAD01}</UniqueIdentifier>
<Extensions>rc;ico;cur;bmp;dlg;rc2;rct;bin;rgs;gif;jpg;jpeg;jpe;resx;tiff;tif;png;wav;mfcribbon-ms</Extensions>
</Filter>
</ItemGroup>
<ItemGroup>
<FxCompile Include="CausticTransport.hlsl">
<Filter>ソース ファイル</Filter>
</FxCompile>
</ItemGroup>
</Project>
差分なしでファイル名を変更。
+12
ファイルの表示
@@ -0,0 +1,12 @@
namespace CausticTransport.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);
}
+29 -13
ファイルの表示
@@ -1,7 +1,8 @@
<Project Sdk="Microsoft.NET.Sdk">
<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>
@@ -12,50 +13,67 @@
<ItemGroup>
<PackageReference Include="coverlet.collector" Version="10.0.1">
<PrivateAssets>all</PrivateAssets>
<IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets>
</PackageReference>
<PackageReference Include="Microsoft.NET.Test.Sdk" Version="18.6.0" />
<PackageReference Include="xunit.runner.visualstudio" Version="3.1.5">
<PrivateAssets>all</PrivateAssets>
<IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets>
</PackageReference>
<PackageReference Include="xunit.v3" Version="3.2.2" />
<PackageReference Include="Microsoft.NET.Test.Sdk" Version="18.10.0" />
<PackageReference Include="xunit.runner.visualstudio" Version="4.0.0">
<IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets>
<PrivateAssets>all</PrivateAssets>
</PackageReference>
<PackageReference Include="xunit.v3" Version="4.0.1" />
</ItemGroup>
<ItemGroup>
<ProjectReference Include="..\CausticTransport\CausticTransport.csproj" SetConfiguration="Configuration=$(Configuration)" SetPlatform="Platform=x64">
<ProjectReference Include="..\CausticTransport\CausticTransport.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>
</Reference>
<Reference Include="YukkuriMovieMaker.Plugin">
<HintPath>$(YMM4DirPath)YukkuriMovieMaker.Plugin.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>
@@ -63,6 +81,4 @@
<Using Include="Xunit" />
</ItemGroup>
<Import Project="..\CausticTransport\ComputeSharp.Reference.props" />
</Project>
+218
ファイルの表示
@@ -0,0 +1,218 @@
using System.Numerics;
using System.Reflection;
using Vortice;
using Vortice.Direct2D1;
using Vortice.Direct2D1.Effects;
using Vortice.Mathematics;
using YukkuriMovieMaker.Commons;
namespace CausticTransport.Tests;
[Collection("Direct2D")]
public sealed class CausticTransportCustomEffectTests
{
const int AmountIndex = 0;
const int Width = 40;
const int Height = 24;
static readonly Bgra Blue = Bgra.Opaque(255, 0, 0);
static readonly Bgra HalfLight = new(224, 192, 160, 128);
static Rendering Render(IGraphicsDevicesAndContext devices, ID2D1Image source, ID2D1Image caustic, float amount)
{
using var effect = new CausticTransportCustomEffect(devices);
effect.SetInput(0, source, true);
effect.SetInput(1, caustic, 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 Premultiplied(IGraphicsDevicesAndContext devices, int width, int height, Bgra color)
{
var stride = width * SourceImage.BytesPerPixel;
var pixels = new byte[stride * height];
for (var offset = 0; offset < pixels.Length; offset += SourceImage.BytesPerPixel)
{
pixels[offset] = color.Blue;
pixels[offset + 1] = color.Green;
pixels[offset + 2] = color.Red;
pixels[offset + 3] = color.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 source, Bgra caustic, float amount)
{
byte Channel(byte sourceValue, byte causticValue) => (byte)Math.Round(sourceValue + (causticValue - sourceValue) * (double)amount, MidpointRounding.AwayFromZero);
return new Bgra(Channel(source.Blue, caustic.Blue), Channel(source.Green, caustic.Green), Channel(source.Red, caustic.Red), Channel(source.Alpha, caustic.Alpha));
}
[Fact]
public void TheEffectIsEnabledOnceCreated()
{
using var devices = new GraphicsDevices();
using var context = devices.CreateContext();
using var effect = new CausticTransportCustomEffect(context);
Assert.True(effect.IsEnabled);
}
[Fact]
public void TheAmountStartsFromZero()
{
using var devices = new GraphicsDevices();
using var context = devices.CreateContext();
using var effect = new CausticTransportCustomEffect(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 CausticTransportCustomEffect(context);
effect.Amount = value;
Assert.Equal(expected, effect.GetFloatValue(AmountIndex));
}
[Fact]
public void TheOutputBoundsFollowTheSourceAlone()
{
using var devices = new GraphicsDevices();
using var context = devices.CreateContext();
using var source = SourceImage.Solid(context, Width, Height, Blue);
using var caustic = SourceImage.Solid(context, 8, 8, HalfLight);
using var moved = Translate(context, caustic.Bitmap, 50f, -6f);
using var movedOutput = moved.Output;
using var effect = new CausticTransportCustomEffect(context);
effect.SetInput(0, source.Bitmap, true);
effect.SetInput(1, movedOutput, true);
using var output = effect.Output;
var bounds = context.DeviceContext.GetImageLocalBounds(output);
Assert.Equal(0f, bounds.Left);
Assert.Equal(0f, bounds.Top);
Assert.Equal((float)Width, bounds.Right);
Assert.Equal((float)Height, 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 caustic = SourceImage.Solid(context, Width, Height, HalfLight);
var rendering = Render(context, source.Bitmap, caustic.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 TheSourceFadesIntoTheCausticByTheAmount(float amount)
{
using var devices = new GraphicsDevices();
using var context = devices.CreateContext();
using var source = SourceImage.Solid(context, Width, Height, Blue);
using var caustic = SourceImage.Solid(context, Width, Height, HalfLight);
var expected = Mix(Blue.Premultiplied(), HalfLight.Premultiplied(), amount);
var rendering = Render(context, source.Bitmap, caustic.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 AnAmountChangedAfterADrawReachesTheNextDraw()
{
using var devices = new GraphicsDevices();
using var context = devices.CreateContext();
using var source = SourceImage.Solid(context, Width, Height, Blue);
using var caustic = SourceImage.Solid(context, Width, Height, HalfLight);
using var effect = new CausticTransportCustomEffect(context);
effect.SetInput(0, source.Bitmap, true);
effect.SetInput(1, caustic.Bitmap, true);
using var output = effect.Output;
effect.Amount = 0.25f;
var first = Rendering.Capture(context, output);
effect.Amount = 0.75f;
var second = Rendering.Capture(context, output);
var expectedFirst = Mix(Blue.Premultiplied(), HalfLight.Premultiplied(), 0.25f);
var expectedSecond = Mix(Blue.Premultiplied(), HalfLight.Premultiplied(), 0.75f);
Assert.All(first.Coordinates(), point => Assert.True(WithinRounding(expectedFirst, first[point.X, point.Y])));
Assert.All(second.Coordinates(), point => Assert.True(WithinRounding(expectedSecond, second[point.X, point.Y])));
}
[Fact]
public void WithoutAnyInputTheOutputRectIsEmptyAndWithInputsItIsTheFirstOne()
{
var type = typeof(CausticTransportCustomEffect).GetNestedType("EffectImpl", BindingFlags.NonPublic)!;
var implementation = Activator.CreateInstance(type)!;
var method = type.GetMethod("MapInputRectsToOutputRect")!;
var first = new RawRect(3, 4, 50, 60);
var second = new RawRect(1, 1, 99, 99);
var none = new object?[] { Array.Empty<RawRect>(), Array.Empty<RawRect>(), default(RawRect), default(RawRect) };
method.Invoke(implementation, none);
var some = new object?[] { new[] { first, second }, new RawRect[2], default(RawRect), default(RawRect) };
method.Invoke(implementation, some);
Assert.Equal(default(RawRect), (RawRect)none[2]!);
Assert.Equal(first, (RawRect)some[2]!);
Assert.Equal(default(RawRect), (RawRect)some[3]!);
}
[Fact]
public void ColorsBrighterThanTheirAlphaAreHeldToTheAlpha()
{
using var devices = new GraphicsDevices();
using var context = devices.CreateContext();
using var source = SourceImage.Solid(context, Width, Height, Bgra.Transparent);
using var caustic = Premultiplied(context, Width, Height, new Bgra(240, 200, 255, 128));
var rendering = Render(context, source.Bitmap, caustic, 1f);
Assert.All(rendering.Coordinates(), point => Assert.True(WithinRounding(new Bgra(128, 128, 128, 128), rendering[point.X, point.Y]), $"({point.X}, {point.Y}) {rendering[point.X, point.Y]}"));
caustic.Dispose();
}
}
+542
ファイルの表示
@@ -0,0 +1,542 @@
using System.Globalization;
using System.Numerics;
using ComputeWeave;
using Vortice.Direct2D1;
using Vortice.Direct2D1.Effects;
using YukkuriMovieMaker.Commons;
using YukkuriMovieMaker.Json;
using YukkuriMovieMaker.Player.Video;
namespace CausticTransport.Tests;
[Collection("Direct2D")]
public sealed class CausticTransportEffectProcessorTests
{
const int Size = 64;
const int Length = 30;
static readonly Bgra Gray = Bgra.Opaque(192, 192, 192);
static readonly Bgra Amber = Bgra.Opaque(80, 200, 255);
static readonly Bgra Azure = Bgra.Opaque(255, 120, 60);
static Bgra Scene(int x, int y)
{
var dx = x - 22;
var dy = y - 30;
if (dx * dx + dy * dy <= 144)
return Amber;
return x is >= 44 and < 52 && y is >= 40 and < 48 ? Azure : Bgra.Transparent;
}
static Func<int, int, Bgra> Filled(Bgra color) => (x, y) => x is >= 16 and < 48 && y is >= 16 and < 48 ? color : Bgra.Transparent;
static void RequireInterop(IGraphicsDevicesAndContext devices)
{
using var scheduler = ComputeExternalQueueScheduler.Create();
using var provider = CausticTransportInteropProvider.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 Rendering RenderFresh(IGraphicsDevicesAndContext devices, CausticTransportEffect effect, SourceImage source, int frame = 0)
{
using var processor = effect.CreateVideoEffect(devices);
processor.SetInput(source.Bitmap);
return RenderFrame(devices, processor, frame);
}
static void AssertSameAsSource(IGraphicsDevicesAndContext devices, Rendering rendering, SourceImage source, string? setting = null)
{
var expected = Rendering.Capture(devices, source.Bitmap);
Assert.Equal((0, 0, source.Width, source.Height), (rendering.Left, rendering.Top, rendering.Width, rendering.Height));
Assert.True(rendering.SamePixelsAs(expected), setting);
}
static int[] Pixels(SourceImage source)
{
var pixels = new int[source.Width * source.Height];
for (var y = 0; y < source.Height; y++)
{
for (var x = 0; x < source.Width; x++)
{
var pixel = source[x, y];
pixels[y * source.Width + x] = pixel.Alpha << 24 | pixel.Red << 16 | pixel.Green << 8 | pixel.Blue;
}
}
return pixels;
}
static int[] ThroughThePipeline(SourceImage source, CausticTransportPipeline.Parameters parameters)
{
using var pipeline = CausticTransportPipeline.TryCreate();
Assert.NotNull(pipeline);
var destination = new int[source.Width * source.Height];
pipeline.Process(Pixels(source), destination, source.Width, source.Height, in parameters);
return destination;
}
static bool Close(Bgra pixel, int expected)
=> Math.Abs(pixel.Alpha - ((expected >> 24) & 255)) <= 1
&& Math.Abs(pixel.Red - ((expected >> 16) & 255)) <= 1
&& Math.Abs(pixel.Green - ((expected >> 8) & 255)) <= 1
&& Math.Abs(pixel.Blue - (expected & 255)) <= 1;
static bool Differs(Rendering rendering, SourceImage source)
=> rendering.Coordinates().Any(point => rendering[point.X, point.Y] != source[point.X, point.Y]);
[Fact]
public void TheProcessorHandsTheDrawDescriptionBackUnchanged()
{
using var devices = new GraphicsDevices();
using var context = devices.CreateContext();
using var source = new SourceImage(context, Size, Size, Scene);
using var processor = new CausticTransportEffect().CreateVideoEffect(context);
processor.SetInput(source.Bitmap);
var description = EffectDescriptions.At(0, Length);
var draw = processor.Update(description);
Assert.Same(description.DrawDescription, draw);
}
public static readonly TheoryData<string, Action<CausticTransportEffect>, CausticLightShape, CausticTransportQuality, float, float, float, float, int> Settings = new()
{
{ "Default", _ => { }, CausticLightShape.Plane, CausticTransportQuality.High, 0.5f, 0.5f, 0.3f, 0.2f, 0 },
{ nameof(CausticTransportEffect.Focus), effect => effect.Focus.Values[0].Value = 20d, CausticLightShape.Plane, CausticTransportQuality.High, 0.2f, 0.5f, 0.3f, 0.2f, 0 },
{ nameof(CausticTransportEffect.LightShape), effect => effect.LightShape = CausticLightShape.Circle, CausticLightShape.Circle, CausticTransportQuality.High, 0.5f, 0.5f, 0.3f, 0.2f, 0 },
{ nameof(CausticTransportEffect.Quality), effect => effect.Quality = CausticTransportQuality.Balanced, CausticLightShape.Plane, CausticTransportQuality.Balanced, 0.5f, 0.5f, 0.3f, 0.2f, 0 },
{ nameof(CausticTransportEffect.ApertureSize), effect => { effect.LightShape = CausticLightShape.Circle; effect.ApertureSize.Values[0].Value = 100d; }, CausticLightShape.Circle, CausticTransportQuality.High, 0.5f, 1f, 0.3f, 0.2f, 0 },
{ nameof(CausticTransportEffect.Dispersion), effect => effect.Dispersion.Values[0].Value = 100d, CausticLightShape.Plane, CausticTransportQuality.High, 0.5f, 0.5f, 1f, 0.2f, 0 },
{ nameof(CausticTransportEffect.Roughness), effect => effect.Roughness.Values[0].Value = 100d, CausticLightShape.Plane, CausticTransportQuality.High, 0.5f, 0.5f, 0.3f, 1f, 0 },
{ nameof(CausticTransportEffect.Seed), effect => effect.Seed = 9, CausticLightShape.Plane, CausticTransportQuality.High, 0.5f, 0.5f, 0.3f, 0.2f, 9 },
};
[Theory]
[MemberData(nameof(Settings))]
public void EverySettingReachesThePipeline(string setting, Action<CausticTransportEffect> configure, CausticLightShape shape, CausticTransportQuality quality, float focus, float aperture, float dispersion, float roughness, int seed)
{
using var devices = new GraphicsDevices();
using var context = devices.CreateContext();
RequireInterop(context);
using var source = new SourceImage(context, Size, Size, Scene);
var effect = new CausticTransportEffect();
configure(effect);
var expected = ThroughThePipeline(source, new CausticTransportPipeline.Parameters((int)shape, quality, focus, aperture, dispersion, roughness, seed));
var rendering = RenderFresh(context, effect, source);
Assert.Equal((0, 0, Size, Size), (rendering.Left, rendering.Top, rendering.Width, rendering.Height));
Assert.All(rendering.Coordinates(), point => Assert.True(Close(rendering[point.X, point.Y], expected[point.Y * Size + point.X]), $"{setting} ({point.X}, {point.Y})"));
Assert.True(Differs(rendering, source), setting);
}
[Fact]
public void TheLightSpreadsPastTheShapeOfTheSourceAndStaysPremultiplied()
{
using var devices = new GraphicsDevices();
using var context = devices.CreateContext();
RequireInterop(context);
using var source = new SourceImage(context, Size, Size, Scene);
var rendering = RenderFresh(context, new CausticTransportEffect(), source);
Assert.All(rendering.Coordinates().Where(point => rendering[point.X, point.Y].Alpha > 0), 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);
});
Assert.Contains(rendering.Coordinates(), point => rendering[point.X, point.Y].Alpha > 0 && source[point.X, point.Y].Alpha == 0);
}
public static readonly TheoryData<string, Action<CausticTransportEffect>> PassThroughSettings = new()
{
{ nameof(CausticTransportEffect.Amount), effect => effect.Amount.Values[0].Value = 0d },
{ nameof(CausticTransportEffect.Focus), effect => effect.Focus.Values[0].Value = 100d },
};
[Theory]
[MemberData(nameof(PassThroughSettings))]
public void AZeroAmountOrAFullFocusPassesTheImageThrough(string setting, Action<CausticTransportEffect> configure)
{
using var devices = new GraphicsDevices();
using var context = devices.CreateContext();
using var source = new SourceImage(context, Size, Size, Scene);
var effect = new CausticTransportEffect();
configure(effect);
var rendering = RenderFresh(context, effect, source);
AssertSameAsSource(context, rendering, source, setting);
}
[Theory]
[InlineData(8193, 2)]
[InlineData(2, 8193)]
[InlineData(4096, 2731)]
public void AnImageBeyondTheSupportedSizePassesThroughUntouched(int width, int height)
{
using var devices = new GraphicsDevices();
using var context = devices.CreateContext();
RequireInterop(context);
using var source = new SourceImage(context, width, height, (x, y) => x < width / 2 ? Gray : Bgra.Transparent);
var rendering = RenderFresh(context, new CausticTransportEffect(), source);
AssertSameAsSource(context, rendering, source);
}
[Theory]
[InlineData(8192, 8)]
[InlineData(8, 8192)]
public void AnImageAtTheLongestSupportedSideIsStillTransported(int width, int height)
{
using var devices = new GraphicsDevices();
using var context = devices.CreateContext();
RequireInterop(context);
using var source = new SourceImage(context, width, height, (x, y) => x * y == 0 && x + y < 300 ? Gray : Bgra.Transparent);
var rendering = RenderFresh(context, new CausticTransportEffect(), source);
Assert.Equal((0, 0, width, height), (rendering.Left, rendering.Top, rendering.Width, rendering.Height));
Assert.False(rendering.SamePixelsAs(Rendering.Capture(context, source.Bitmap)));
}
[Theory]
[InlineData(100, 50)]
[InlineData(-37, 21)]
public void TheLightTravelsWithTheImage(int dx, int dy)
{
using var devices = new GraphicsDevices();
using var context = devices.CreateContext();
RequireInterop(context);
using var source = new SourceImage(context, Size, Size, Scene);
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 CausticTransportEffect().CreateVideoEffect(context);
inPlaceProcessor.SetInput(source.Bitmap);
var inPlace = RenderFrame(context, inPlaceProcessor, 0);
using var travelledProcessor = new CausticTransportEffect().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})"));
Assert.True(Differs(inPlace, source));
}
[Fact]
public void ReturningToAFrameReproducesItExactly()
{
using var devices = new GraphicsDevices();
using var context = devices.CreateContext();
RequireInterop(context);
using var source = new SourceImage(context, Size, Size, Scene);
var effect = new CausticTransportEffect();
effect.Focus.CopyFrom(Linear(10d, 90d));
using var processor = effect.CreateVideoEffect(context);
processor.SetInput(source.Bitmap);
var first = RenderFrame(context, processor, 4);
var other = RenderFrame(context, processor, 20);
var again = RenderFrame(context, processor, 4);
Assert.False(first.SamePixelsAs(other));
Assert.True(first.SamePixelsAs(again));
}
[Fact]
public void TheNextFrameOfAnUnchangedSettingIsDrawnTheSame()
{
using var devices = new GraphicsDevices();
using var context = devices.CreateContext();
RequireInterop(context);
using var source = new SourceImage(context, Size, Size, Scene);
using var processor = new CausticTransportEffect().CreateVideoEffect(context);
processor.SetInput(source.Bitmap);
var first = RenderFrame(context, processor, 0);
var next = RenderFrame(context, processor, 1);
Assert.True(Differs(first, source));
Assert.True(first.SamePixelsAs(next));
}
[Fact]
public void ANewProcessorDrawsTheSameLight()
{
using var devices = new GraphicsDevices();
using var context = devices.CreateContext();
RequireInterop(context);
using var source = new SourceImage(context, Size, Size, Scene);
var effect = new CausticTransportEffect { Seed = 9 };
var first = RenderFresh(context, effect, source);
var second = RenderFresh(context, effect, source);
Assert.True(first.SamePixelsAs(second));
}
[Fact]
public void AnimatedFocusIsReadAtEachFrame()
{
using var devices = new GraphicsDevices();
using var context = devices.CreateContext();
RequireInterop(context);
using var source = new SourceImage(context, Size, Size, Scene);
var effect = new CausticTransportEffect();
effect.Focus.CopyFrom(Linear(100d, 0d));
using var processor = effect.CreateVideoEffect(context);
processor.SetInput(source.Bitmap);
var start = RenderFrame(context, processor, 0);
var end = RenderFrame(context, processor, Length - 1);
var back = RenderFrame(context, processor, 0);
AssertSameAsSource(context, start, source);
Assert.True(Differs(end, source));
AssertSameAsSource(context, back, source);
}
[Theory]
[InlineData(100d, 30d)]
[InlineData(30d, 100d)]
[InlineData(30d, 60d)]
public void AProcessorThatDrewAnotherFocusDrawsLikeAFreshOne(double firstFocus, double secondFocus)
{
using var devices = new GraphicsDevices();
using var context = devices.CreateContext();
RequireInterop(context);
using var source = new SourceImage(context, Size, Size, Scene);
var effect = new CausticTransportEffect();
effect.Focus.Values[0].Value = firstFocus;
using var processor = effect.CreateVideoEffect(context);
processor.SetInput(source.Bitmap);
RenderFrame(context, processor, 0);
effect.Focus.Values[0].Value = secondFocus;
var expected = RenderFresh(context, effect, source);
var reused = RenderFrame(context, processor, 0);
Assert.True(reused.SamePixelsAs(expected));
}
public static readonly TheoryData<string, Action<CausticTransportEffect>> LaterChanges = new()
{
{ nameof(CausticTransportEffect.Amount), effect => effect.Amount.Values[0].Value = 50d },
{ nameof(CausticTransportEffect.Focus), effect => effect.Focus.Values[0].Value = 20d },
{ nameof(CausticTransportEffect.Quality), effect => effect.Quality = CausticTransportQuality.Balanced },
{ nameof(CausticTransportEffect.LightShape), effect => effect.LightShape = CausticLightShape.Circle },
{ nameof(CausticTransportEffect.ApertureSize), effect => { effect.LightShape = CausticLightShape.Circle; effect.ApertureSize.Values[0].Value = 100d; } },
{ nameof(CausticTransportEffect.Dispersion), effect => effect.Dispersion.Values[0].Value = 100d },
{ nameof(CausticTransportEffect.Roughness), effect => effect.Roughness.Values[0].Value = 100d },
{ nameof(CausticTransportEffect.Seed), effect => effect.Seed = 9 },
};
[Theory]
[MemberData(nameof(LaterChanges))]
public void EverySettingChangedAfterTheFirstFrameReachesTheEffect(string setting, Action<CausticTransportEffect> change)
{
using var devices = new GraphicsDevices();
using var context = devices.CreateContext();
RequireInterop(context);
using var source = new SourceImage(context, Size, Size, Scene);
var effect = new CausticTransportEffect();
using var processor = effect.CreateVideoEffect(context);
processor.SetInput(source.Bitmap);
var before = RenderFrame(context, processor, 0);
change(effect);
var after = RenderFrame(context, processor, 0);
var expected = RenderFresh(context, effect, source);
Assert.False(before.SamePixelsAs(after), setting);
Assert.True(after.SamePixelsAs(expected), setting);
}
[Theory]
[InlineData(32, 128)]
[InlineData(128, 32)]
[InlineData(64, 48)]
public void AResizedSourceIsDrawnLikeAFreshOne(int firstSize, int secondSize)
{
using var devices = new GraphicsDevices();
using var context = devices.CreateContext();
RequireInterop(context);
using var first = new SourceImage(context, firstSize, firstSize, (x, y) => (x - 8) * (x - 8) + (y - 8) * (y - 8) <= 36 ? Amber : Bgra.Transparent);
using var second = new SourceImage(context, secondSize, secondSize, (x, y) => (x - 20) * (x - 20) + (y - 12) * (y - 12) <= 64 ? Azure : Bgra.Transparent);
var effect = new CausticTransportEffect();
using var processor = effect.CreateVideoEffect(context);
processor.SetInput(first.Bitmap);
RenderFrame(context, processor, 0);
var expected = RenderFresh(context, effect, second);
processor.SetInput(second.Bitmap);
var after = RenderFrame(context, processor, 0);
Assert.Equal((0, 0, secondSize, secondSize), (after.Left, after.Top, after.Width, after.Height));
Assert.True(Differs(after, second));
Assert.True(after.SamePixelsAs(expected));
}
[Theory]
[InlineData(false)]
[InlineData(true)]
public void LightAppearsOnceATransparentSourceTakesShape(bool lightWasDrawnBefore)
{
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, Scene);
var effect = new CausticTransportEffect();
var expected = RenderFresh(context, effect, source);
using var processor = effect.CreateVideoEffect(context);
if (lightWasDrawnBefore)
{
processor.SetInput(source.Bitmap);
RenderFrame(context, processor, 0);
}
processor.SetInput(empty.Bitmap);
var before = RenderFrame(context, processor, 0);
processor.SetInput(source.Bitmap);
var after = RenderFrame(context, processor, 0);
Assert.All(before.Coordinates(), point => Assert.Equal(0, before[point.X, point.Y].Alpha));
Assert.True(Differs(after, source));
Assert.True(after.SamePixelsAs(expected));
}
[Fact]
public void ARecoloredImageIsDrawnLikeAFreshOne()
{
using var devices = new GraphicsDevices();
using var context = devices.CreateContext();
RequireInterop(context);
using var amber = new SourceImage(context, Size, Size, Filled(Amber));
using var azure = new SourceImage(context, Size, Size, Filled(Azure));
var effect = new CausticTransportEffect();
using var processor = effect.CreateVideoEffect(context);
processor.SetInput(amber.Bitmap);
RenderFrame(context, processor, 0);
var expected = RenderFresh(context, effect, azure);
processor.SetInput(azure.Bitmap);
var recolored = RenderFrame(context, processor, 0);
Assert.True(recolored.SamePixelsAs(expected));
}
[Fact]
public void EveryFrameOfAnInputChangingInPlaceIsDrawnLikeAFreshProcessor()
{
using var devices = new GraphicsDevices();
using var context = devices.CreateContext();
RequireInterop(context);
using var amber = new SourceImage(context, Size, Size, Scene);
using var azure = new SourceImage(context, Size, Size, Filled(Azure));
using var passThrough = new AffineTransform2D(context.DeviceContext);
using var image = passThrough.Output;
var effect = new CausticTransportEffect();
using var processor = effect.CreateVideoEffect(context);
processor.SetInput(image);
var frames = new (SourceImage Source, Action<CausticTransportEffect> Change)[]
{
(amber, _ => { }),
(amber, _ => { }),
(azure, _ => { }),
(azure, effect => effect.Focus.Values[0].Value = 30d),
(amber, _ => { }),
(amber, effect => effect.Amount.Values[0].Value = 50d),
(amber, effect => effect.Roughness.Values[0].Value = 0d),
(amber, effect => effect.Seed = 9),
(amber, effect => effect.Roughness.Values[0].Value = 20d),
(amber, effect => effect.Seed = 3),
(amber, effect => effect.Dispersion.Values[0].Value = 70d),
};
for (var index = 0; index < frames.Length; index++)
{
var (source, change) = frames[index];
change(effect);
passThrough.SetInput(0, source.Bitmap, true);
var drawn = RenderFrame(context, processor, 0);
using var fresh = effect.CreateVideoEffect(context);
fresh.SetInput(image);
var expected = RenderFrame(context, fresh, 0);
Assert.True(drawn.SamePixelsAs(expected), $"frame {index}");
}
}
[Fact]
public void AProcessorWithoutAnInputHandsTheDrawDescriptionBack()
{
using var devices = new GraphicsDevices();
using var context = devices.CreateContext();
using var processor = new CausticTransportEffect().CreateVideoEffect(context);
var description = EffectDescriptions.At(0, Length);
var draw = processor.Update(description);
Assert.Same(description.DrawDescription, draw);
}
[Fact]
public void LightReturnsOnceAnUnsupportedFrameIsFollowedByASupportedOne()
{
using var devices = new GraphicsDevices();
using var context = devices.CreateContext();
RequireInterop(context);
using var source = new SourceImage(context, 8193, Size, Scene);
using var crop = new Crop(context.DeviceContext) { Rectangle = new Vector4(0f, 0f, Size, Size) };
crop.SetInput(0, source.Bitmap, true);
using var cropOutput = crop.Output;
using var processor = new CausticTransportEffect().CreateVideoEffect(context);
processor.SetInput(cropOutput);
var first = RenderFrame(context, processor, 0);
crop.Rectangle = new Vector4(0f, 0f, 8193f, Size);
var unsupported = RenderFrame(context, processor, 1);
crop.Rectangle = new Vector4(0f, 0f, Size, Size);
var again = RenderFrame(context, processor, 2);
Assert.Equal((0, 0, 8193, Size), (unsupported.Left, unsupported.Top, unsupported.Width, unsupported.Height));
Assert.True(unsupported.SamePixelsAs(Rendering.Capture(context, source.Bitmap)));
Assert.False(first.SamePixelsAs(Rendering.Capture(context, cropOutput)));
Assert.True(first.SamePixelsAs(again));
}
[Fact]
public void AFailureWhileUpdatingIsNotSwallowed()
{
using var devices = new GraphicsDevices();
using var context = devices.CreateContext();
using var processor = new CausticTransportEffect().CreateVideoEffect(context);
Assert.ThrowsAny<Exception>(() => processor.Update(null!));
}
}
+192 -515
ファイルの表示
@@ -1,29 +1,47 @@
using System.Runtime.InteropServices;
using ComputeSharp;
using ComputeSharp.Interop;
using Vortice;
using Vortice.Direct2D1;
using Vortice.DXGI;
using Vortice.Mathematics;
using System.ComponentModel;
using System.ComponentModel.DataAnnotations;
using System.Reflection;
using YukkuriMovieMaker.Commons;
using PixelFormat = Vortice.DCommon.PixelFormat;
using YukkuriMovieMaker.Controls;
using YukkuriMovieMaker.Exo;
using YukkuriMovieMaker.Json;
using YukkuriMovieMaker.Plugin.Effects;
using YukkuriMovieMaker.Project;
namespace CausticTransport.Tests;
public sealed class CausticTransportEffectTests
{
private static double ValueAt(YukkuriMovieMaker.Commons.Animation animation) => animation.GetValue(0, 1, 30);
static PropertyInfo Property(string name) => typeof(CausticTransportEffect).GetProperty(name)!;
static T Attribute<T>(string property) where T : Attribute => Property(property).GetCustomAttribute<T>()!;
static Animation[] Animations(CausticTransportEffect effect)
=> [effect.Amount, effect.Focus, effect.ApertureSize, effect.Dispersion, effect.Roughness];
[Theory]
[InlineData(nameof(CausticTransportEffect.Amount), 100d, 0d, 100d)]
[InlineData(nameof(CausticTransportEffect.Focus), 50d, 0d, 100d)]
[InlineData(nameof(CausticTransportEffect.ApertureSize), 50d, 5d, 100d)]
[InlineData(nameof(CausticTransportEffect.Dispersion), 30d, 0d, 100d)]
[InlineData(nameof(CausticTransportEffect.Roughness), 20d, 0d, 100d)]
public void AnimatedParametersStartFromTheirDefaultsWithinTheirRange(string name, double defaultValue, double minimum, double maximum)
{
var effect = new CausticTransportEffect();
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 DefaultParameterValuesMatchSpecification()
public void ShapeQualityAndSeedStartFromTheirDefaults()
{
var effect = new CausticTransportEffect();
Assert.Equal(100d, ValueAt(effect.Amount), 6);
Assert.Equal(50d, ValueAt(effect.Focus), 6);
Assert.Equal(50d, ValueAt(effect.ApertureSize), 6);
Assert.Equal(30d, ValueAt(effect.Dispersion), 6);
Assert.Equal(20d, ValueAt(effect.Roughness), 6);
Assert.Equal(CausticLightShape.Plane, effect.LightShape);
Assert.Equal(CausticTransportQuality.High, effect.Quality);
Assert.Equal(0, effect.Seed);
@@ -34,555 +52,214 @@ public sealed class CausticTransportEffectTests
[InlineData(-1, 0)]
[InlineData(0, 0)]
[InlineData(1234, 1234)]
public void SeedClampsNegativeInputToZero(int input, int expected)
[InlineData(10000, 10000)]
[InlineData(int.MaxValue, int.MaxValue)]
public void SeedNeverDropsBelowZero(int value, int expected)
{
var effect = new CausticTransportEffect { Seed = input };
var effect = new CausticTransportEffect { Seed = 5 };
effect.Seed = value;
Assert.Equal(expected, effect.Seed);
Assert.False(effect.HasErrors);
}
[Fact]
public void CreateExoVideoFiltersReturnsEmpty()
public void ChangingShapeQualityOrSeedNotifiesTheEditor()
{
var effect = new CausticTransportEffect();
var changed = new List<string?>();
effect.PropertyChanged += (_, e) => changed.Add(e.PropertyName);
effect.LightShape = CausticLightShape.Circle;
effect.Quality = CausticTransportQuality.Ultra;
effect.Seed = 7;
Assert.Equal([nameof(CausticTransportEffect.LightShape), nameof(CausticTransportEffect.Quality), nameof(CausticTransportEffect.Seed)], changed);
}
[Fact]
public void AssigningAnUnchangedOrClampedValueDoesNotNotify()
{
var effect = new CausticTransportEffect();
var changed = new List<string?>();
effect.PropertyChanged += (_, e) => changed.Add(e.PropertyName);
effect.LightShape = CausticLightShape.Plane;
effect.Quality = CausticTransportQuality.High;
effect.Seed = 0;
effect.Seed = -1;
Assert.Empty(changed);
}
[Fact]
public void TheAnimatedParametersAreListedOnceAndReused()
{
var effect = new CausticTransportEffect();
var method = typeof(CausticTransportEffect).GetMethod("GetAnimatables", BindingFlags.NonPublic | BindingFlags.Instance)!;
var first = (IEnumerable<IAnimatable>)method.Invoke(effect, null)!;
var second = (IEnumerable<IAnimatable>)method.Invoke(effect, null)!;
Assert.Same(first, second);
Assert.Equal(Animations(effect), first);
}
[Fact]
public void TheLabelIsTheLocalizedEffectName()
{
var effect = new CausticTransportEffect();
Assert.Empty(effect.CreateExoVideoFilters(0, null!));
Assert.Equal(Texts.CausticTransport, effect.Label);
}
[Fact]
public void TheFiveNumericParametersReceiveTheAnimationParameters()
{
var effect = new CausticTransportEffect();
effect.SetAnimationParameters(120, EffectDescriptions.Fps);
Assert.All(Animations(effect), animation => Assert.Equal(120, animation.Length));
}
[Theory]
[InlineData(CausticTransportQuality.Balanced, 128, 4, 12)]
[InlineData(CausticTransportQuality.High, 192, 6, 16)]
[InlineData(CausticTransportQuality.Ultra, 256, 8, 20)]
public void QualitySettingsMatchSpecification(CausticTransportQuality quality, int resolution, int transport, int jacobi)
[InlineData(0)]
[InlineData(1)]
[InlineData(int.MaxValue)]
public void NoExoFilterIsWrittenForAviUtl(int keyFrameIndex)
{
var settings = CausticTransportSettings.GetQuality(quality);
var effect = new CausticTransportEffect();
Assert.Equal(resolution, settings.GridResolution);
Assert.Equal(transport, settings.TransportIterations);
Assert.Equal(jacobi, settings.JacobiIterations);
var description = new ExoOutputDescription(new VideoInfo(), string.Empty, new AviUtlDirectories(string.Empty, string.Empty));
Assert.Empty(effect.CreateExoVideoFilters(keyFrameIndex, description));
}
[Fact]
public void TheEffectIsRegisteredForFilteringAndDecorationWithoutAviUtlSupport()
{
var attribute = typeof(CausticTransportEffect).GetCustomAttribute<VideoEffectAttribute>()!;
Assert.Equal(nameof(Texts.CausticTransport), attribute.Name);
Assert.Equal([VideoEffectCategories.Filtering, VideoEffectCategories.Decoration], attribute.Categories);
Assert.Equal([nameof(Texts.TagCaustic), nameof(Texts.TagLight), nameof(Texts.TagTransition)], attribute.Keywords);
Assert.False(attribute.IsAviUtlSupported);
Assert.True(attribute.IsEffectItemSupported);
Assert.Equal(typeof(Texts), attribute.ResourceType);
Assert.Equal(Texts.CausticTransport, attribute.GetName());
}
[Theory]
[InlineData(1920, 1080, 192, 192, 108)]
[InlineData(1080, 1920, 192, 108, 192)]
[InlineData(8, 8, 192, 8, 8)]
[InlineData(4096, 16, 128, 128, 4)]
[InlineData(100, 100, 256, 100, 100)]
public void GridSizeKeepsAspectAndBounds(int width, int height, int resolution, int expectedWidth, int expectedHeight)
[InlineData(nameof(CausticTransportEffect.Amount), nameof(Texts.BasicGroup), nameof(Texts.Amount), nameof(Texts.AmountDescription), 0)]
[InlineData(nameof(CausticTransportEffect.Focus), nameof(Texts.BasicGroup), nameof(Texts.Focus), nameof(Texts.FocusDescription), 1)]
[InlineData(nameof(CausticTransportEffect.Quality), nameof(Texts.BasicGroup), nameof(Texts.Quality), nameof(Texts.QualityDescription), 2)]
[InlineData(nameof(CausticTransportEffect.LightShape), nameof(Texts.LightGroup), nameof(Texts.LightShape), nameof(Texts.LightShapeDescription), 10)]
[InlineData(nameof(CausticTransportEffect.ApertureSize), nameof(Texts.LightGroup), nameof(Texts.ApertureSize), nameof(Texts.ApertureSizeDescription), 11)]
[InlineData(nameof(CausticTransportEffect.Dispersion), nameof(Texts.OpticsGroup), nameof(Texts.Dispersion), nameof(Texts.DispersionDescription), 20)]
[InlineData(nameof(CausticTransportEffect.Roughness), nameof(Texts.OpticsGroup), nameof(Texts.Roughness), nameof(Texts.RoughnessDescription), 21)]
[InlineData(nameof(CausticTransportEffect.Seed), nameof(Texts.OpticsGroup), nameof(Texts.Seed), nameof(Texts.SeedDescription), 22)]
public void EveryParameterIsDisplayedInItsGroupInOrder(string property, string group, string name, string description, int order)
{
var (gridWidth, gridHeight) = CausticTransportSettings.GetGridSize(width, height, resolution);
var display = Attribute<DisplayAttribute>(property);
Assert.Equal(expectedWidth, gridWidth);
Assert.Equal(expectedHeight, gridHeight);
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(8, 8, 1)]
[InlineData(16, 16, 1)]
[InlineData(17, 17, 2)]
[InlineData(192, 108, 5)]
[InlineData(256, 256, 5)]
public void LevelCountCoversGridDownToCoarsestSize(int gridWidth, int gridHeight, int expected)
[InlineData(nameof(CausticTransportEffect.Amount), 0d, 100d)]
[InlineData(nameof(CausticTransportEffect.Focus), 0d, 100d)]
[InlineData(nameof(CausticTransportEffect.ApertureSize), 5d, 100d)]
[InlineData(nameof(CausticTransportEffect.Dispersion), 0d, 100d)]
[InlineData(nameof(CausticTransportEffect.Roughness), 0d, 100d)]
public void AnimatedParametersAreEditedAsPercentagesWithAnimationSliders(string property, double minimum, double maximum)
{
Assert.Equal(expected, CausticTransportSettings.GetLevelCount(gridWidth, gridHeight));
}
var slider = Attribute<AnimationSliderAttribute>(property);
[Fact]
public void ColorFixedScaleStaysWithinSafeBounds()
{
Assert.Equal(65536, CausticTransportSettings.GetColorFixedScale(64));
Assert.Equal(345, CausticTransportSettings.GetColorFixedScale(3840 * 2160));
Assert.True((double)CausticTransportSettings.GetColorFixedScale(3840 * 2160) * 3840 * 2160 <= uint.MaxValue);
Assert.Equal("F1", slider.StringFormat);
Assert.Equal("%", slider.UnitText);
Assert.Equal(minimum, slider.DefaultMin);
Assert.Equal(maximum, slider.DefaultMax);
}
[Theory]
[InlineData(1, 8)]
[InlineData(8, 8)]
[InlineData(9, 16)]
[InlineData(1080, 1080)]
[InlineData(2730, 2736)]
public void SplatDispatchSizeCoversFrameInWholeThreadGroups(int size, int expected)
[InlineData(nameof(CausticTransportEffect.Quality))]
[InlineData(nameof(CausticTransportEffect.LightShape))]
public void TheChoicesAreMadeFromACombo(string property)
{
var dispatch = CausticTransportSettings.GetSplatDispatchSize(size);
Assert.NotNull(Attribute<EnumComboBoxAttribute>(property));
}
Assert.Equal(expected, dispatch);
Assert.Equal(0, dispatch % CausticTransportSettings.SplatGroupSize);
Assert.InRange(dispatch - size, 0, CausticTransportSettings.SplatGroupSize - 1);
[Fact]
public void TheQualitiesAndShapesAreListedInOrder()
{
Assert.Equal([CausticTransportQuality.Balanced, CausticTransportQuality.High, CausticTransportQuality.Ultra], Enum.GetValues<CausticTransportQuality>());
Assert.Equal([CausticLightShape.Plane, CausticLightShape.Circle, CausticLightShape.HorizontalSlit, CausticLightShape.VerticalSlit], Enum.GetValues<CausticLightShape>());
Assert.Equal([0, 1, 2], Enum.GetValues<CausticTransportQuality>().Select(quality => (int)quality));
Assert.Equal([0, 1, 2, 3], Enum.GetValues<CausticLightShape>().Select(shape => (int)shape));
}
[Theory]
[InlineData(5, 3)]
[InlineData(9, 1)]
[InlineData(1, 9)]
[InlineData(17, 15)]
public void FramesNotAlignedToThreadGroupsAreProcessed(int width, int height)
[InlineData(CausticTransportQuality.Balanced, nameof(Texts.QualityBalanced), nameof(Texts.QualityBalancedDescription))]
[InlineData(CausticTransportQuality.High, nameof(Texts.QualityHigh), nameof(Texts.QualityHighDescription))]
[InlineData(CausticTransportQuality.Ultra, nameof(Texts.QualityUltra), nameof(Texts.QualityUltraDescription))]
public void EveryQualityIsDisplayedWithItsLocalizedName(CausticTransportQuality quality, string name, string description)
{
using var pipeline = CausticTransportPipeline.TryCreate();
if (pipeline is null)
{
Assert.Skip("Direct3D 12 is unavailable.");
return;
}
var display = typeof(CausticTransportQuality).GetField(quality.ToString())!.GetCustomAttribute<DisplayAttribute>()!;
var source = CreateSourcePixels(width, height);
var destination = new int[source.Length];
var parameters = new CausticTransportPipeline.Parameters(1, CausticTransportQuality.Balanced, 1f, 0.5f, 0.3f, 0.2f, 5);
pipeline.Process(source, destination, width, height, in parameters);
for (var index = 0; index < source.Length; index++)
{
for (var shift = 0; shift < 32; shift += 8)
{
var expected = (source[index] >> shift) & 255;
var actual = (destination[index] >> shift) & 255;
Assert.InRange(actual, Math.Max(expected - 1, 0), Math.Min(expected + 1, 255));
}
}
}
[Fact]
public void MaximumPixelCountKeepsColorAccumulationWithinUnsignedRange()
{
var scale = CausticTransportSettings.GetColorFixedScale(CausticTransportSettings.MaximumPixelCount);
Assert.Equal(CausticTransportSettings.MinimumColorFixedScale, scale);
Assert.True((double)CausticTransportSettings.MaximumPixelCount * scale <= uint.MaxValue);
Assert.True(CausticTransportSettings.MaximumPixelCount >= 4096 * 2160);
Assert.Equal(name, display.Name);
Assert.Equal(description, display.Description);
Assert.Equal(typeof(Texts), display.ResourceType);
}
[Theory]
[InlineData(1920d, 1080d, true)]
[InlineData(3840d, 2160d, true)]
[InlineData(4096d, 2160d, true)]
[InlineData(8192d, 1365d, true)]
[InlineData(8193d, 1365d, false)]
[InlineData(4096d, 2731d, false)]
[InlineData(0d, 1080d, false)]
[InlineData(double.NaN, 1080d, false)]
[InlineData(double.PositiveInfinity, 1080d, false)]
public void SupportedSizeCoversUpTo4KAndRejectsLarger(double width, double height, bool expected)
[InlineData(CausticLightShape.Plane, nameof(Texts.ShapePlane), nameof(Texts.ShapePlaneDescription))]
[InlineData(CausticLightShape.Circle, nameof(Texts.ShapeCircle), nameof(Texts.ShapeCircleDescription))]
[InlineData(CausticLightShape.HorizontalSlit, nameof(Texts.ShapeHorizontalSlit), nameof(Texts.ShapeHorizontalSlitDescription))]
[InlineData(CausticLightShape.VerticalSlit, nameof(Texts.ShapeVerticalSlit), nameof(Texts.ShapeVerticalSlitDescription))]
public void EveryShapeIsDisplayedWithItsLocalizedName(CausticLightShape shape, string name, string description)
{
Assert.Equal(expected, CausticTransportSettings.IsSupportedSize(width, height));
}
var display = typeof(CausticLightShape).GetField(shape.ToString())!.GetCustomAttribute<DisplayAttribute>()!;
[Theory]
[InlineData(0f, 0f, 0)]
[InlineData(0.5f, 0.3f, 7)]
[InlineData(0.5f, 0f, 0)]
public void FullConvergenceReconstructsSourceWithinQuantization(float roughness, float dispersion, int seed)
{
using var pipeline = CausticTransportPipeline.TryCreate();
if (pipeline is null)
{
Assert.Skip("Direct3D 12 is unavailable.");
return;
}
const int width = 16;
const int height = 12;
var source = CreateSourcePixels(width, height);
var destination = new int[source.Length];
var parameters = new CausticTransportPipeline.Parameters(0, CausticTransportQuality.Balanced, 1f, 0.5f, dispersion, roughness, seed);
pipeline.Process(source, destination, width, height, in parameters);
for (var index = 0; index < source.Length; index++)
{
for (var shift = 0; shift < 32; shift += 8)
{
var expected = (source[index] >> shift) & 255;
var actual = (destination[index] >> shift) & 255;
Assert.InRange(actual, Math.Max(expected - 1, 0), Math.Min(expected + 1, 255));
}
}
Assert.Equal(name, display.Name);
Assert.Equal(description, display.Description);
Assert.Equal(typeof(Texts), display.ResourceType);
}
[Fact]
public void GpuPipelineIsDeterministic()
public void TheSeedIsEditedWithoutAUnitFromZero()
{
using var pipeline = CausticTransportPipeline.TryCreate();
if (pipeline is null)
{
Assert.Skip("Direct3D 12 is unavailable.");
return;
}
var slider = Attribute<TextBoxSliderAttribute>(nameof(CausticTransportEffect.Seed));
var range = Attribute<RangeAttribute>(nameof(CausticTransportEffect.Seed));
const int width = 24;
const int height = 16;
var source = CreateSourcePixels(width, height);
var first = new int[source.Length];
var second = new int[source.Length];
var parameters = new CausticTransportPipeline.Parameters(1, CausticTransportQuality.Balanced, 0.4f, 0.4f, 0.6f, 0.5f, 42);
pipeline.Process(source, first, width, height, in parameters);
pipeline.Process(source, second, width, height, in parameters);
Assert.Equal(first, second);
}
[Theory]
[InlineData(1920, 1080)]
[InlineData(3840, 2160)]
[InlineData(4096, 2160)]
[InlineData(4096, 2730)]
public void LargeFramesAreProcessedWithoutDispatchGroupOverflow(int width, int height)
{
Assert.True(CausticTransportSettings.IsSupportedSize(width, height));
using var pipeline = CausticTransportPipeline.TryCreate();
if (pipeline is null)
{
Assert.Skip("Direct3D 12 is unavailable.");
return;
}
var source = CreateSourcePixels(width, height);
var destination = new int[source.Length];
var parameters = new CausticTransportPipeline.Parameters(0, CausticTransportQuality.Balanced, 0.5f, 0.5f, 0.3f, 0.2f, 5);
pipeline.Process(source, destination, width, height, in parameters);
Assert.Contains(destination, pixel => pixel != 0);
}
[Theory]
[InlineData(3840, 2160)]
[InlineData(4096, 2730)]
public void LargeFrameConservesMassDuringTransport(int width, int height)
{
using var pipeline = CausticTransportPipeline.TryCreate();
if (pipeline is null)
{
Assert.Skip("Direct3D 12 is unavailable.");
return;
}
var source = new int[width * height];
for (var index = 0; index < source.Length; index++)
{
var value = 16 + (index * 7) % 48;
source[index] = 64 << 24 | value << 16 | value << 8 | value;
}
var destination = new int[source.Length];
var parameters = new CausticTransportPipeline.Parameters(0, CausticTransportQuality.Balanced, 0.5f, 0.5f, 0f, 0f, 0);
pipeline.Process(source, destination, width, height, in parameters);
double sourceSum = 0;
double destinationSum = 0;
foreach (var pixel in source)
sourceSum += (pixel >> 24) & 255;
foreach (var pixel in destination)
destinationSum += (pixel >> 24) & 255;
Assert.InRange(destinationSum, sourceSum * 0.98, sourceSum * 1.02);
Assert.Equal("F0", slider.StringFormat);
Assert.Equal(string.Empty, slider.UnitText);
Assert.Equal(0d, slider.DefaultMin);
Assert.Equal(10000d, slider.DefaultMax);
Assert.Equal(0, range.Minimum);
Assert.Equal(int.MaxValue, range.Maximum);
Assert.Equal(0, Attribute<DefaultValueAttribute>(nameof(CausticTransportEffect.Seed)).Value);
}
[Fact]
public void OutputAlphaStaysPremultipliedAndBounded()
public void EverySettingSurvivesAProjectRoundTrip()
{
using var pipeline = CausticTransportPipeline.TryCreate();
if (pipeline is null)
{
Assert.Skip("Direct3D 12 is unavailable.");
return;
}
var effect = new CausticTransportEffect { LightShape = CausticLightShape.VerticalSlit, Quality = CausticTransportQuality.Ultra, Seed = 42 };
var values = new[] { 55d, 45d, 70d, 20d, 65d };
foreach (var (animation, value) in Animations(effect).Zip(values))
animation.Values[0].Value = value;
const int width = 24;
const int height = 16;
var source = CreateSourcePixels(width, height);
var destination = new int[source.Length];
var parameters = new CausticTransportPipeline.Parameters(1, CausticTransportQuality.Balanced, 0.3f, 0.3f, 0.5f, 0.4f, 3);
var clone = Json.GetClone(effect)!;
pipeline.Process(source, destination, width, height, in parameters);
foreach (var pixel in destination)
{
var alpha = (pixel >> 24) & 255;
Assert.InRange((pixel >> 16) & 255, 0, alpha);
Assert.InRange((pixel >> 8) & 255, 0, alpha);
Assert.InRange(pixel & 255, 0, alpha);
}
}
[Fact]
public void MassIsConservedDuringTransport()
{
using var pipeline = CausticTransportPipeline.TryCreate();
if (pipeline is null)
{
Assert.Skip("Direct3D 12 is unavailable.");
return;
}
const int width = 64;
const int height = 48;
var source = new int[width * height];
for (var index = 0; index < source.Length; index++)
{
var value = 16 + (index * 7) % 48;
source[index] = 64 << 24 | value << 16 | value << 8 | value;
}
var destination = new int[source.Length];
var parameters = new CausticTransportPipeline.Parameters(0, CausticTransportQuality.Balanced, 0.5f, 0.5f, 0f, 0f, 0);
pipeline.Process(source, destination, width, height, in parameters);
double sourceSum = 0;
double destinationSum = 0;
foreach (var pixel in source)
sourceSum += (pixel >> 24) & 255;
foreach (var pixel in destination)
destinationSum += (pixel >> 24) & 255;
Assert.InRange(destinationSum, sourceSum * 0.98, sourceSum * 1.02);
}
[Fact]
public void TransparentInputYieldsTransparentOutput()
{
using var pipeline = CausticTransportPipeline.TryCreate();
if (pipeline is null)
{
Assert.Skip("Direct3D 12 is unavailable.");
return;
}
const int width = 16;
const int height = 16;
var source = new int[width * height];
var destination = new int[source.Length];
Array.Fill(destination, -1);
var parameters = new CausticTransportPipeline.Parameters(1, CausticTransportQuality.Balanced, 0.5f, 0.5f, 0.5f, 0.5f, 0);
pipeline.Process(source, destination, width, height, in parameters);
Assert.All(destination, pixel => Assert.Equal(0, pixel));
}
[Fact]
public void UniformImageWithPlaneLightIsFixedPointOfTransport()
{
using var pipeline = CausticTransportPipeline.TryCreate();
if (pipeline is null)
{
Assert.Skip("Direct3D 12 is unavailable.");
return;
}
const int width = 32;
const int height = 32;
const int expected = unchecked((int)0xFF808080);
var source = new int[width * height];
Array.Fill(source, expected);
var destination = new int[source.Length];
var parameters = new CausticTransportPipeline.Parameters(0, CausticTransportQuality.Balanced, 0f, 1f, 0f, 0f, 0);
pipeline.Process(source, destination, width, height, in parameters);
foreach (var pixel in destination)
{
for (var shift = 0; shift < 32; shift += 8)
{
var expectedChannel = (expected >> shift) & 255;
var actual = (pixel >> shift) & 255;
Assert.InRange(actual, expectedChannel - 1, expectedChannel + 1);
}
}
}
[Fact]
public void GpuPipelineDoesNotAllocateManagedMemoryAfterWarmup()
{
using var pipeline = CausticTransportPipeline.TryCreate();
if (pipeline is null)
{
Assert.Skip("Direct3D 12 is unavailable.");
return;
}
const int width = 16;
const int height = 16;
var source = CreateSourcePixels(width, height);
var destination = new int[source.Length];
var parameters = new CausticTransportPipeline.Parameters(1, CausticTransportQuality.Balanced, 0.5f, 0.5f, 0.5f, 0.5f, 1);
pipeline.Process(source, destination, width, height, in parameters);
pipeline.Process(source, destination, width, height, in parameters);
GC.Collect();
GC.WaitForPendingFinalizers();
GC.Collect();
var before = GC.GetAllocatedBytesForCurrentThread();
pipeline.Process(source, destination, width, height, in parameters);
var allocated = GC.GetAllocatedBytesForCurrentThread() - before;
Assert.Equal(0, allocated);
}
[Fact]
public void SharedTexturePipelineMatchesPackedBufferPipeline()
{
using var pipeline = CausticTransportPipeline.TryCreate();
if (pipeline is null)
{
Assert.Skip("Direct3D 12 is unavailable.");
return;
}
const int width = 24;
const int height = 18;
var source = CreateSourcePixels(width, height);
var expected = new int[source.Length];
var parameters = new CausticTransportPipeline.Parameters(1, CausticTransportQuality.Balanced, 0.35f, 0.4f, 0.5f, 0.3f, 11);
pipeline.Process(source, expected, width, height, in parameters);
var device = GraphicsDevice.GetDefault();
using var sourceTexture = InteropServices.AllocateSharedReadWriteTexture2D<Bgra32, Float4>(device, width, height);
using var outputTexture = InteropServices.AllocateSharedReadWriteTexture2D<Bgra32, Float4>(device, width, height);
var sourcePixels = new Bgra32[source.Length];
for (var index = 0; index < source.Length; index++)
sourcePixels[index].PackedValue = unchecked((uint)source[index]);
sourceTexture.CopyFrom(sourcePixels);
pipeline.ProcessSharedAndWait(sourceTexture, outputTexture, width, height, in parameters);
var result = new Bgra32[source.Length];
outputTexture.CopyTo(result);
for (var index = 0; index < expected.Length; index++)
Assert.Equal(unchecked((uint)expected[index]), result[index].PackedValue);
}
[Fact]
public void SubmittedSharedTexturePipelineDoesNotAllocateManagedMemoryAfterWarmup()
{
using var pipeline = CausticTransportPipeline.TryCreate();
if (pipeline is null)
{
Assert.Skip("Direct3D 12 is unavailable.");
return;
}
const int width = 16;
const int height = 16;
var device = GraphicsDevice.GetDefault();
using var source = InteropServices.AllocateSharedReadWriteTexture2D<Bgra32, Float4>(device, width, height);
using var destination = InteropServices.AllocateSharedReadWriteTexture2D<Bgra32, Float4>(device, width, height);
var parameters = new CausticTransportPipeline.Parameters(0, CausticTransportQuality.Balanced, 0.5f, 0.5f, 0.3f, 0.2f, 0);
for (var iteration = 0; iteration < 4; iteration++)
pipeline.Process(source, destination, width, height, in parameters);
pipeline.WaitForCompletion();
GC.Collect();
GC.WaitForPendingFinalizers();
GC.Collect();
var before = GC.GetAllocatedBytesForCurrentThread();
pipeline.Process(source, destination, width, height, in parameters);
var allocated = GC.GetAllocatedBytesForCurrentThread() - before;
pipeline.WaitForCompletion();
Assert.Equal(0, allocated);
}
[Fact]
public void Direct2DInteropRoundTripReconstructsPixelsAtFullConvergence()
{
using var devices = new GraphicsDevices();
using var graphicsContext = devices.CreateContext();
using var interop = CausticTransportGpuInterop.TryCreate(graphicsContext);
if (interop is null)
{
Assert.Skip("Direct3D 11 and Direct3D 12 sharing is unavailable.");
return;
}
using var pipeline = CausticTransportPipeline.TryCreate(interop.Device);
Assert.NotNull(pipeline);
const int width = 16;
const int height = 12;
const int expected = unchecked((int)0xC0302010);
var pixels = Enumerable.Repeat(expected, width * height).ToArray();
var handle = GCHandle.Alloc(pixels, GCHandleType.Pinned);
using var inputBitmap = graphicsContext.DeviceContext.CreateBitmap(
new SizeI(width, height),
new BitmapProperties1(
new PixelFormat(Format.B8G8R8A8_UNorm, Vortice.DCommon.AlphaMode.Premultiplied),
96f,
96f,
BitmapOptions.None));
try
{
inputBitmap.CopyFromMemory(handle.AddrOfPinnedObject(), width * sizeof(int));
}
finally
{
handle.Free();
}
Assert.True(interop.EnsureResources(width, height));
var bounds = new RawRectF(0f, 0f, width, height);
var parameters = new CausticTransportPipeline.Parameters(0, CausticTransportQuality.Balanced, 1f, 0.5f, 0f, 0f, 0);
for (var iteration = 0; iteration < 2; iteration++)
{
interop.RenderInput(inputBitmap, bounds);
interop.BeginCompute();
try
{
pipeline!.Process(interop.SourceTexture, interop.OutputTexture, width, height, in parameters);
}
finally
{
interop.EndCompute();
}
}
interop.WaitForIdle();
using var staging = graphicsContext.DeviceContext.CreateBitmap(
new SizeI(width, height),
new BitmapProperties1(
new PixelFormat(Format.B8G8R8A8_UNorm, Vortice.DCommon.AlphaMode.Premultiplied),
96f,
96f,
BitmapOptions.CpuRead | BitmapOptions.CannotDraw));
staging.CopyFromBitmap(interop.OutputBitmap);
var mapped = staging.Map(MapOptions.Read);
try
{
for (var y = 0; y < height; y++)
{
for (var x = 0; x < width; x++)
{
var actual = Marshal.ReadInt32(mapped.Bits + (nint)(y * mapped.Pitch + x * sizeof(int)));
for (var shift = 0; shift < 32; shift += 8)
{
var expectedChannel = (expected >> shift) & 255;
var actualChannel = (actual >> shift) & 255;
Assert.InRange(actualChannel, expectedChannel - 1, expectedChannel + 1);
}
}
}
}
finally
{
staging.Unmap();
}
}
private static int[] CreateSourcePixels(int width, int height)
{
var source = new int[width * height];
for (var y = 0; y < height; y++)
{
for (var x = 0; x < width; x++)
{
var alpha = x == 0 && y == 0 ? 0 : 96 + (x + y) * 4;
alpha = Math.Min(alpha, 255);
var red = (x * 35 % 256) * alpha / 255;
var green = (y * 35 % 256) * alpha / 255;
var blue = ((x + y) * 17 % 256) * alpha / 255;
source[y * width + x] = alpha << 24 | red << 16 | green << 8 | blue;
}
}
return source;
Assert.NotSame(effect, clone);
Assert.Equal(CausticLightShape.VerticalSlit, clone.LightShape);
Assert.Equal(CausticTransportQuality.Ultra, clone.Quality);
Assert.Equal(42, clone.Seed);
Assert.Equal(values, Animations(clone).Select(animation => animation.GetValue(0, 1, EffectDescriptions.Fps)));
}
}
+389
ファイルの表示
@@ -0,0 +1,389 @@
using System.Numerics;
using ComputeWeave;
using Vortice.Direct2D1;
using YukkuriMovieMaker.Commons;
namespace CausticTransport.Tests;
[Collection("Direct2D")]
public sealed class CausticTransportInteropTests
{
static readonly Bgra Gray = Bgra.Opaque(192, 192, 192);
static CausticTransportPipeline.Parameters Parameters(float focus = 1f)
=> new((int)CausticLightShape.Circle, CausticTransportQuality.Balanced, focus, 0.5f, 0.3f, 0.2f, 5);
static Bgra Gradient(int x, int y)
=> new((byte)(32 + x * 3 % 200), (byte)(96 + y * 5 % 150), (byte)(160 + (x + y) % 90), (byte)(96 + (x + y) * 2 % 159));
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 CausticTransportInteropProvider provider;
readonly ComputeInteropDomain domain;
public CausticTransportResourceSet Resources { get; }
public CausticTransportPipeline Pipeline { get; }
public GraphicsDevice Device { get; }
Interop(ComputeExternalQueueScheduler scheduler, CausticTransportInteropProvider provider, GraphicsDevice device)
{
this.scheduler = scheduler;
this.provider = provider;
Device = device;
domain = device.RegisterExternalDomain(provider);
Resources = CausticTransportResourceSet.Create(device, domain);
Pipeline = CausticTransportPipeline.TryCreate(device)!;
}
public static Interop Create(IGraphicsDevicesAndContext devices)
{
var scheduler = ComputeExternalQueueScheduler.Create();
var provider = CausticTransportInteropProvider.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 void Process(int width, int height, CausticTransportPipeline.Parameters parameters)
=> Pipeline.Process(Resources.GetSourceComputeBinding(), Resources.GetOutputComputeBinding(), width, height, in parameters);
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();
}
}
[Fact]
public void AProviderCannotBeMadeWithoutAScheduler()
{
using var devices = new GraphicsDevices();
using var context = devices.CreateContext();
Assert.Throws<ArgumentNullException>(() => CausticTransportInteropProvider.TryCreate(context, null!, out _));
}
[Fact]
public void TheSourceIsReproducedAtFullFocus()
{
using var devices = new GraphicsDevices();
using var context = devices.CreateContext();
using var interop = Interop.Create(context);
using var source = new SourceImage(context, 24, 18, Gradient);
Assert.True(interop.Resources.TryEnsureSource(24, 18, out _));
Assert.True(interop.Resources.TryEnsureOutput(24, 18, out _));
interop.Draw(source.Bitmap);
interop.Process(24, 18, Parameters(focus: 1f));
var output = interop.CaptureOutput(context, out _, out _);
AssertShows(output, Pixels(source), 24, 18, tolerance: 1);
}
[Fact]
public void ThePictureMatchesWhatThePipelineMakesFromThePackedPixels()
{
using var devices = new GraphicsDevices();
using var context = devices.CreateContext();
using var interop = Interop.Create(context);
using var source = new SourceImage(context, 48, 32, Gradient);
var parameters = Parameters(focus: 0.3f);
var expected = new int[48 * 32];
interop.Pipeline.Process(Pixels(source), expected, 48, 32, in parameters);
Assert.True(interop.Resources.TryEnsureSource(48, 32, out _));
Assert.True(interop.Resources.TryEnsureOutput(48, 32, out _));
interop.Draw(source.Bitmap);
interop.Process(48, 32, parameters);
var output = interop.CaptureOutput(context, out _, out _);
AssertShows(output, expected, 48, 32, tolerance: 0);
Assert.NotEqual(Pixels(source), expected);
}
[Fact]
public void ASourceDrawnAgainReplacesTheLightOfTheOneBefore()
{
using var devices = new GraphicsDevices();
using var context = devices.CreateContext();
using var interop = Interop.Create(context);
using var first = new SourceImage(context, 48, 48, CenteredSquare(48, 16));
using var second = new SourceImage(context, 48, 48, (x, y) => x < 16 && y < 16 ? Gray : Bgra.Transparent);
var parameters = Parameters(focus: 0.3f);
var expected = new int[48 * 48];
interop.Pipeline.Process(Pixels(second), expected, 48, 48, in parameters);
Assert.True(interop.Resources.TryEnsureSource(48, 48, out _));
Assert.True(interop.Resources.TryEnsureOutput(48, 48, out _));
interop.Draw(first.Bitmap);
interop.Process(48, 48, parameters);
interop.Draw(second.Bitmap);
interop.Process(48, 48, parameters);
var output = interop.CaptureOutput(context, out _, out _);
AssertShows(output, expected, 48, 48, tolerance: 0);
}
[Fact]
public void ThePictureIsDrawnAfterTheOutputGrowsToFullHd()
{
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(focus: 0.3f);
var expected = new int[96 * 96];
interop.Pipeline.Process(Pixels(source), expected, 96, 96, in parameters);
Assert.True(interop.Resources.TryEnsureSource(96, 96, out _));
Assert.True(interop.Resources.TryEnsureOutput(96, 96, out _));
interop.Draw(source.Bitmap);
interop.Process(96, 96, parameters);
interop.CaptureOutput(context, out var firstWidth, out var firstHeight);
Assert.True(interop.Resources.TryEnsureOutput(1920, 1080, out var outputChanged));
interop.Draw(source.Bitmap);
interop.Process(96, 96, parameters);
var output = interop.CaptureOutput(context, out var secondWidth, out var secondHeight);
Assert.Equal((96, 96), (firstWidth, firstHeight));
Assert.True(outputChanged);
Assert.Equal((1920, 1080), (secondWidth, secondHeight));
AssertShows(output, expected, 96, 96, tolerance: 0);
}
[Fact]
public void ThePictureIsDrawnAfterTheSourceIsReplacedByALargerOne()
{
using var devices = new GraphicsDevices();
using var context = devices.CreateContext();
using var interop = Interop.Create(context);
var parameters = Parameters(focus: 0.3f);
foreach (var (size, square) in new[] { (64, 24), (128, 48) })
{
using var source = new SourceImage(context, size, size, CenteredSquare(size, square));
var expected = new int[size * size];
interop.Pipeline.Process(Pixels(source), expected, size, size, in parameters);
Assert.True(interop.Resources.TryEnsureSource(size, size, out var sourceChanged));
Assert.True(interop.Resources.TryEnsureOutput(size, size, out _));
interop.Draw(source.Bitmap);
interop.Process(size, size, parameters);
var output = interop.CaptureOutput(context, out var width, out var height);
Assert.True(sourceChanged);
Assert.Equal((size, size), (width, height));
AssertShows(output, expected, size, size, tolerance: 0);
}
}
[Fact]
public void EveryFrameOfASequenceMatchesWhatAnotherPipelineMakesFromThePackedPixels()
{
using var devices = new GraphicsDevices();
using var context = devices.CreateContext();
using var interop = Interop.Create(context);
using var reference = CausticTransportPipeline.TryCreate(interop.Device)!;
using var first = new SourceImage(context, 48, 32, Gradient);
using var second = new SourceImage(context, 48, 32, (x, y) => x < 20 && y >= 8 ? Gray : Bgra.Transparent);
var circle = Parameters(focus: 0.3f);
var plane = circle with { Shape = (int)CausticLightShape.Plane, Aperture = 0.8f };
var frames = new (SourceImage Source, CausticTransportPipeline.Parameters Parameters)[]
{
(first, circle),
(first, circle),
(first, circle with { Focus = 0.6f }),
(first, circle with { Dispersion = 0f }),
(first, circle with { Roughness = 0f }),
(first, circle with { Roughness = 0f, Seed = 9 }),
(first, circle with { Aperture = 0.8f }),
(second, circle with { Aperture = 0.8f }),
(second, circle with { Aperture = 0.8f }),
(second, circle with { Aperture = 0.8f }),
(second, circle with { Shape = (int)CausticLightShape.HorizontalSlit, Aperture = 0.8f }),
(second, plane),
(second, plane with { Aperture = 0.3f }),
(second, plane with { Quality = CausticTransportQuality.High }),
(first, plane with { Quality = CausticTransportQuality.High }),
(first, circle),
};
Assert.True(interop.Resources.TryEnsureSource(48, 32, out _));
Assert.True(interop.Resources.TryEnsureOutput(48, 32, out _));
for (var index = 0; index < frames.Length; index++)
{
var (source, parameters) = frames[index];
var expected = new int[48 * 32];
reference.Process(Pixels(source), expected, 48, 32, in parameters);
interop.Draw(source.Bitmap);
interop.Process(48, 32, parameters);
var output = interop.CaptureOutput(context, out _, out _);
AssertShows(output, expected, 48, 32, tolerance: 0);
}
}
[Theory]
[InlineData(false)]
[InlineData(true)]
public void TheTransportIsReusedOnceTheSourceAndTheLightSettle(bool sourceChanges)
{
using var devices = new GraphicsDevices();
using var context = devices.CreateContext();
using var interop = Interop.Create(context);
using var reference = CausticTransportPipeline.TryCreate(interop.Device)!;
using var first = new SourceImage(context, 48, 32, Gradient);
using var second = new SourceImage(context, 48, 32, (x, y) => x < 20 && y >= 8 ? Gray : Bgra.Transparent);
var before = Parameters(focus: 0.3f);
var after = sourceChanges ? before : before with { Aperture = 0.8f };
var settled = sourceChanges ? second : first;
Assert.True(interop.Resources.TryEnsureSource(48, 32, out _));
Assert.True(interop.Resources.TryEnsureOutput(48, 32, out _));
interop.Draw(first.Bitmap);
interop.Process(48, 32, before);
var recomputed = new List<bool>();
for (var frame = 0; frame < 3; frame++)
{
interop.Draw(settled.Bitmap);
recomputed.Add(interop.Pipeline.Simulate(interop.Resources.GetSourceComputeBinding(), 48, 32, in after));
interop.Pipeline.Render(interop.Resources.GetSourceComputeBinding(), interop.Resources.GetOutputComputeBinding(), 48, 32, in after);
}
var expected = new int[48 * 32];
reference.Process(Pixels(settled), expected, 48, 32, in after);
var output = interop.CaptureOutput(context, out _, out _);
Assert.True(recomputed[0]);
Assert.False(recomputed[2]);
AssertShows(output, expected, 48, 32, tolerance: 0);
}
[Fact(Timeout = 60000)]
public async Task AReclaimedGridIsTransportedAgain()
{
await Task.Run(() =>
{
using var devices = new GraphicsDevices();
using var context = devices.CreateContext();
using var interop = Interop.Create(context);
using var source = new SourceImage(context, 48, 32, Gradient);
var parameters = Parameters(focus: 0.3f);
Assert.True(interop.Resources.TryEnsureSource(48, 32, out _));
bool Simulate()
{
interop.Draw(source.Bitmap);
return interop.Pipeline.Simulate(interop.Resources.GetSourceComputeBinding(), 48, 32, in parameters);
}
var first = Simulate();
var repeated = Simulate();
interop.Device.TrimMemory();
var reclaimed = Simulate();
Assert.True(first);
Assert.False(repeated);
Assert.True(reclaimed);
}, TestContext.Current.CancellationToken);
}
[Fact(Timeout = 60000)]
public async Task ASharedPipelineWhoseGridWasReclaimedDrawsLikeAnotherPipeline()
{
await Task.Run(() =>
{
using var devices = new GraphicsDevices();
using var context = devices.CreateContext();
using var interop = Interop.Create(context);
using var reference = CausticTransportPipeline.TryCreate(interop.Device)!;
using var source = new SourceImage(context, 48, 32, Gradient);
var parameters = Parameters(focus: 0.3f);
var expected = new int[48 * 32];
reference.Process(Pixels(source), expected, 48, 32, in parameters);
Assert.True(interop.Resources.TryEnsureSource(48, 32, out _));
Assert.True(interop.Resources.TryEnsureOutput(48, 32, out _));
interop.Draw(source.Bitmap);
interop.Process(48, 32, parameters);
interop.Device.TrimMemory();
interop.Draw(source.Bitmap);
interop.Process(48, 32, parameters);
var output = interop.CaptureOutput(context, out _, out _);
AssertShows(output, expected, 48, 32, tolerance: 0);
}, TestContext.Current.CancellationToken);
}
static int[] Pixels(SourceImage source)
{
var pixels = new int[source.Width * source.Height];
for (var y = 0; y < source.Height; y++)
{
for (var x = 0; x < source.Width; x++)
{
var pixel = source[x, y];
pixels[y * source.Width + x] = pixel.Alpha << 24 | pixel.Red << 16 | pixel.Green << 8 | pixel.Blue;
}
}
return pixels;
}
static void AssertShows(Rendering rendering, int[] expected, int width, int height, int tolerance)
{
Assert.All(Enumerable.Range(0, height), y =>
{
for (var x = 0; x < width; x++)
{
var pixel = rendering[x, y];
var value = pixel.Alpha << 24 | pixel.Red << 16 | pixel.Green << 8 | pixel.Blue;
var other = expected[y * width + x];
var close = Math.Abs(pixel.Alpha - ((other >> 24) & 255)) <= tolerance
&& Math.Abs(pixel.Red - ((other >> 16) & 255)) <= tolerance
&& Math.Abs(pixel.Green - ((other >> 8) & 255)) <= tolerance
&& Math.Abs(pixel.Blue - (other & 255)) <= tolerance;
Assert.True(close, $"({x}, {y}) {value:X8} {other:X8}");
}
});
}
}
+703
ファイルの表示
@@ -0,0 +1,703 @@
using ComputeWeave;
using ComputeWeave.Interop;
namespace CausticTransport.Tests;
[Collection("Direct3D12")]
public sealed class CausticTransportPipelineTests
{
const int Opaque = unchecked((int)0xFFC0C0C0);
const int Plane = (int)CausticLightShape.Plane;
const int Circle = (int)CausticLightShape.Circle;
const int HorizontalSlit = (int)CausticLightShape.HorizontalSlit;
const int VerticalSlit = (int)CausticLightShape.VerticalSlit;
static readonly bool Direct3D12IsAvailable = GraphicsDevice.EnumerateDevices().Any();
public static readonly TheoryData<int> Shapes = [Plane, Circle, HorizontalSlit, VerticalSlit];
static CausticTransportPipeline CreatePipeline()
{
if (!Direct3D12IsAvailable)
Assert.Skip("Direct3D 12 is unavailable.");
var pipeline = CausticTransportPipeline.TryCreate();
Assert.NotNull(pipeline);
return pipeline;
}
static CausticTransportPipeline.Parameters Parameters(
int shape = Plane,
CausticTransportQuality quality = CausticTransportQuality.Balanced,
float focus = 0.5f,
float aperture = 0.5f,
float dispersion = 0f,
float roughness = 0f,
int seed = 0)
=> new(shape, quality, focus, aperture, dispersion, roughness, seed);
static int Alpha(int pixel) => (pixel >> 24) & 255;
static int Red(int pixel) => (pixel >> 16) & 255;
static int Green(int pixel) => (pixel >> 8) & 255;
static int Blue(int pixel) => pixel & 255;
static int[] Uniform(int width, int height, int pixel) => Enumerable.Repeat(pixel, width * height).ToArray();
static int[] Disc(int width, int height, double centerX, double centerY, double radius, int pixel)
{
var pixels = new int[width * height];
for (var y = 0; y < height; y++)
{
for (var x = 0; x < width; x++)
{
var dx = x + 0.5 - centerX;
var dy = y + 0.5 - centerY;
if (dx * dx + dy * dy <= radius * radius)
pixels[y * width + x] = pixel;
}
}
return pixels;
}
static int[] Mixed(int width, int height)
{
var source = new int[width * height];
for (var y = 0; y < height; y++)
{
for (var x = 0; x < width; x++)
{
var alpha = x == 0 && y == 0 ? 0 : Math.Min(96 + (x + y) * 4, 255);
var red = (x * 35 % 256) * alpha / 255;
var green = (y * 35 % 256) * alpha / 255;
var blue = ((x + y) * 17 % 256) * alpha / 255;
source[y * width + x] = alpha << 24 | red << 16 | green << 8 | blue;
}
}
return source;
}
static int[] Speckled(int width, int height)
{
var source = new int[width * height];
for (var index = 0; index < source.Length; index++)
{
var value = 16 + (index * 7) % 48;
source[index] = 64 << 24 | value << 16 | value << 8 | value;
}
return source;
}
static int[] Render(CausticTransportPipeline pipeline, int[] source, int width, int height, CausticTransportPipeline.Parameters parameters)
{
var destination = new int[source.Length];
pipeline.Process(source, destination, width, height, in parameters);
return destination;
}
static long Light(int[] pixels) => pixels.Sum(pixel => (long)Alpha(pixel));
static int LitPixels(int[] pixels) => pixels.Count(pixel => Alpha(pixel) > 0);
static double DistanceFromCenter(int index, int width, int height)
{
var dx = index % width + 0.5 - width / 2.0;
var dy = index / width + 0.5 - height / 2.0;
return Math.Sqrt(dx * dx + dy * dy);
}
static double FarthestLit(int[] pixels, int width, int height)
=> Enumerable.Range(0, pixels.Length).Where(index => Alpha(pixels[index]) > 0).Max(index => DistanceFromCenter(index, width, height));
static double CentroidX(int[] pixels, int width, Func<int, int> channel)
{
double weighted = 0;
double total = 0;
for (var index = 0; index < pixels.Length; index++)
{
var value = channel(pixels[index]);
weighted += value * (index % width + 0.5);
total += value;
}
return weighted / total;
}
static void AssertWithinOne(int[] expected, int[] actual)
{
Assert.Equal(expected.Length, actual.Length);
for (var index = 0; index < expected.Length; index++)
{
for (var shift = 0; shift < 32; shift += 8)
{
var expectedChannel = (expected[index] >> shift) & 255;
var actualChannel = (actual[index] >> shift) & 255;
Assert.True(Math.Abs(expectedChannel - actualChannel) <= 1, $"{index} {shift} {expectedChannel} {actualChannel}");
}
}
}
static void Upload(ReadWriteTexture2D<Bgra32, Float4> texture, int[] pixels)
=> texture.CopyFrom(pixels.Select(pixel => new Bgra32 { PackedValue = unchecked((uint)pixel) }).ToArray());
[Theory]
[MemberData(nameof(Shapes))]
public void ATransparentSourceProducesNoLight(int shape)
{
using var pipeline = CreatePipeline();
var destination = Enumerable.Repeat(-1, 32 * 32).ToArray();
var parameters = Parameters(shape);
pipeline.Process(new int[32 * 32], destination, 32, 32, in parameters);
Assert.All(destination, pixel => Assert.Equal(0, pixel));
}
[Fact]
public void ATransparentSourceAfterABrightOneLeavesNoLightBehind()
{
using var pipeline = CreatePipeline();
var parameters = Parameters(Circle, focus: 0.2f);
Assert.True(LitPixels(Render(pipeline, Uniform(32, 32, Opaque), 32, 32, parameters)) > 0);
var rendering = Render(pipeline, new int[32 * 32], 32, 32, parameters);
Assert.All(rendering, pixel => Assert.Equal(0, pixel));
}
[Theory]
[MemberData(nameof(Shapes))]
public void TheOutputStaysPremultipliedAndBounded(int shape)
{
using var pipeline = CreatePipeline();
var parameters = Parameters(shape, focus: 0.3f, dispersion: 0.5f, roughness: 0.4f, seed: 3);
var rendering = Render(pipeline, Mixed(24, 16), 24, 16, parameters);
Assert.All(rendering, pixel =>
{
Assert.InRange(Red(pixel), 0, Alpha(pixel));
Assert.InRange(Green(pixel), 0, Alpha(pixel));
Assert.InRange(Blue(pixel), 0, Alpha(pixel));
});
}
[Theory]
[InlineData(0f)]
[InlineData(1f)]
public void AColorWithoutLightStaysDark(float dispersion)
{
using var pipeline = CreatePipeline();
var red = Disc(64, 48, 24, 24, 8, unchecked((int)0xFFFF0000));
var parameters = Parameters(Circle, focus: 0.4f, dispersion: dispersion, roughness: 0.3f, seed: 3);
var rendering = Render(pipeline, red, 64, 48, parameters);
Assert.True(LitPixels(rendering) > 0);
Assert.All(rendering, pixel =>
{
Assert.Equal(0, Green(pixel));
Assert.Equal(0, Blue(pixel));
});
}
[Theory]
[InlineData(Plane, 0f, 0f, 0)]
[InlineData(Plane, 0.5f, 0.3f, 7)]
[InlineData(Circle, 0f, 0f, 0)]
[InlineData(Circle, 1f, 0.6f, 5)]
[InlineData(HorizontalSlit, 0.5f, 0.3f, 7)]
[InlineData(VerticalSlit, 0.5f, 0.3f, 7)]
public void AFullFocusReproducesTheSourceWithinQuantization(int shape, float roughness, float dispersion, int seed)
{
using var pipeline = CreatePipeline();
var source = Mixed(16, 12);
var parameters = Parameters(shape, focus: 1f, dispersion: dispersion, roughness: roughness, seed: seed);
var rendering = Render(pipeline, source, 16, 12, parameters);
AssertWithinOne(source, rendering);
}
[Theory]
[InlineData(0f)]
[InlineData(0.5f)]
[InlineData(1f)]
public void AUniformImageIsAFixedPointOfThePlaneLight(float focus)
{
using var pipeline = CreatePipeline();
var source = Uniform(32, 32, unchecked((int)0xFF808080));
var parameters = Parameters(Plane, focus: focus, aperture: 1f);
var rendering = Render(pipeline, source, 32, 32, parameters);
AssertWithinOne(source, rendering);
}
[Fact]
public void ThePlaneLightIgnoresTheAperture()
{
using var pipeline = CreatePipeline();
var source = Mixed(32, 24);
var small = Render(pipeline, source, 32, 24, Parameters(Plane, focus: 0.3f, aperture: 0.1f));
var large = Render(pipeline, source, 32, 24, Parameters(Plane, focus: 0.3f, aperture: 1f));
Assert.Equal(small, large);
}
[Fact]
public void TheCircleGathersTheLightOntoItsDisc()
{
using var pipeline = CreatePipeline();
var rendering = Render(pipeline, Uniform(96, 96, Opaque), 96, 96, Parameters(Circle, focus: 0f, aperture: 0.5f));
Assert.Equal(255, Alpha(rendering[48 * 96 + 48]));
Assert.All(new[] { 0, 95, 95 * 96, 96 * 96 - 1 }, corner => Assert.Equal(0, Alpha(rendering[corner])));
Assert.True(FarthestLit(rendering, 96, 96) <= 32d);
}
[Fact]
public void AHorizontalSlitGathersTheLightOntoItsBand()
{
using var pipeline = CreatePipeline();
var rendering = Render(pipeline, Uniform(96, 96, Opaque), 96, 96, Parameters(HorizontalSlit, focus: 0f, aperture: 0.5f));
Assert.Equal(255, Alpha(rendering[48 * 96]));
Assert.Equal(255, Alpha(rendering[48 * 96 + 95]));
Assert.All(Enumerable.Range(0, 96), x =>
{
Assert.Equal(0, Alpha(rendering[x]));
Assert.Equal(0, Alpha(rendering[95 * 96 + x]));
Assert.Equal(0, Alpha(rendering[10 * 96 + x]));
Assert.Equal(0, Alpha(rendering[85 * 96 + x]));
});
}
[Fact]
public void AVerticalSlitGathersTheLightOntoItsBand()
{
using var pipeline = CreatePipeline();
var rendering = Render(pipeline, Uniform(96, 96, Opaque), 96, 96, Parameters(VerticalSlit, focus: 0f, aperture: 0.5f));
Assert.Equal(255, Alpha(rendering[48]));
Assert.Equal(255, Alpha(rendering[95 * 96 + 48]));
Assert.All(Enumerable.Range(0, 96), y =>
{
Assert.Equal(0, Alpha(rendering[y * 96]));
Assert.Equal(0, Alpha(rendering[y * 96 + 95]));
Assert.Equal(0, Alpha(rendering[y * 96 + 10]));
Assert.Equal(0, Alpha(rendering[y * 96 + 85]));
});
}
[Fact]
public void ALargerApertureSpreadsTheLightWider()
{
using var pipeline = CreatePipeline();
var source = Uniform(96, 96, Opaque);
var narrow = Render(pipeline, source, 96, 96, Parameters(Circle, focus: 0f, aperture: 0.5f));
var wide = Render(pipeline, source, 96, 96, Parameters(Circle, focus: 0f, aperture: 1f));
Assert.True(FarthestLit(wide, 96, 96) > FarthestLit(narrow, 96, 96) + 10d);
Assert.True(FarthestLit(wide, 96, 96) > 44d);
Assert.True(LitPixels(wide) > LitPixels(narrow) * 2);
}
[Fact]
public void LessFocusGathersTheLightMore()
{
using var pipeline = CreatePipeline();
var source = Uniform(64, 48, Opaque);
var focused = LitPixels(Render(pipeline, source, 64, 48, Parameters(Circle, focus: 1f)));
var halfway = LitPixels(Render(pipeline, source, 64, 48, Parameters(Circle, focus: 0.5f)));
var gathered = LitPixels(Render(pipeline, source, 64, 48, Parameters(Circle, focus: 0f)));
Assert.True(focused > halfway && halfway > gathered);
Assert.Equal(64 * 48, focused);
}
[Fact]
public void ThePlaneLightConservesTheLightItTransports()
{
using var pipeline = CreatePipeline();
var source = Speckled(64, 48);
var rendering = Render(pipeline, source, 64, 48, Parameters(Plane, focus: 0.5f));
Assert.InRange(Light(rendering), Light(source) * 0.98, Light(source) * 1.02);
}
[Theory]
[InlineData(3840, 2160)]
[InlineData(4096, 2730)]
public void ALargeFrameConservesTheLightItTransports(int width, int height)
{
using var pipeline = CreatePipeline();
var source = Speckled(width, height);
var rendering = Render(pipeline, source, width, height, Parameters(Plane, focus: 0.5f));
Assert.InRange(Light(rendering), Light(source) * 0.98, Light(source) * 1.02);
}
[Fact]
public void LightSpreadFarBeyondItsSourceIsConservedAndStaysBalanced()
{
using var pipeline = CreatePipeline();
var source = Disc(96, 64, 48, 32, 16, Opaque);
var rendering = Render(pipeline, source, 96, 64, Parameters(Plane, focus: 0f));
var left = rendering.Where((_, index) => index % 96 < 48).Sum(pixel => (long)Alpha(pixel));
var right = rendering.Where((_, index) => index % 96 >= 48).Sum(pixel => (long)Alpha(pixel));
Assert.InRange(Light(rendering), Light(source) * 0.98, Light(source) * 1.02);
Assert.InRange(left, right * 0.98, right * 1.02);
Assert.True(LitPixels(rendering) > LitPixels(source) * 2);
}
[Fact]
public void WithoutDispersionEveryColorTravelsTogether()
{
using var pipeline = CreatePipeline();
var source = Disc(64, 48, 16, 24, 8, Opaque);
var rendering = Render(pipeline, source, 64, 48, Parameters(Circle, focus: 0.4f, dispersion: 0f));
Assert.True(LitPixels(rendering) > 0);
Assert.All(rendering, pixel =>
{
Assert.Equal(Red(pixel), Green(pixel));
Assert.Equal(Green(pixel), Blue(pixel));
});
}
[Theory]
[InlineData(0.5f)]
[InlineData(1f)]
public void DispersionKeepsTheLightItTransports(float dispersion)
{
using var pipeline = CreatePipeline();
var source = Speckled(64, 48);
var rendering = Render(pipeline, source, 64, 48, Parameters(Plane, focus: 0.5f, dispersion: dispersion));
Assert.InRange(Light(rendering), Light(source) * 0.98, Light(source) * 1.02);
}
[Fact]
public void DispersionCarriesRedFartherThanBlue()
{
using var pipeline = CreatePipeline();
var source = Disc(64, 48, 16, 24, 8, Opaque);
double Split(float dispersion)
{
var rendering = Render(pipeline, source, 64, 48, Parameters(Circle, focus: 0.4f, dispersion: dispersion));
return CentroidX(rendering, 64, Red) - CentroidX(rendering, 64, Blue);
}
var none = Split(0f);
var some = Split(0.5f);
var most = Split(1f);
Assert.InRange(none, -0.01d, 0.01d);
Assert.True(some > 1d);
Assert.True(most > some + 1d);
}
[Fact]
public void TheSameSettingsAlwaysProduceTheSamePicture()
{
using var pipeline = CreatePipeline();
var source = Mixed(24, 16);
var parameters = Parameters(Circle, focus: 0.4f, aperture: 0.4f, dispersion: 0.6f, roughness: 0.5f, seed: 42);
var first = Render(pipeline, source, 24, 16, parameters);
var second = Render(pipeline, source, 24, 16, parameters);
Assert.Equal(first, second);
}
[Theory]
[InlineData(Plane)]
[InlineData(Circle)]
public void WithoutRoughnessTheSeedChangesNothing(int shape)
{
using var pipeline = CreatePipeline();
var source = Disc(64, 48, 16, 24, 8, Opaque);
var first = Render(pipeline, source, 64, 48, Parameters(shape, focus: 0.4f, roughness: 0f, seed: 0));
var second = Render(pipeline, source, 64, 48, Parameters(shape, focus: 0.4f, roughness: 0f, seed: 1));
Assert.Equal(first, second);
}
[Theory]
[InlineData(Plane)]
[InlineData(Circle)]
public void ADifferentSeedScattersTheLightDifferently(int shape)
{
using var pipeline = CreatePipeline();
var source = Disc(64, 48, 16, 24, 8, Opaque);
var first = Render(pipeline, source, 64, 48, Parameters(shape, focus: 0.4f, roughness: 0.5f, seed: 0));
var second = Render(pipeline, source, 64, 48, Parameters(shape, focus: 0.4f, roughness: 0.5f, seed: 1));
Assert.NotEqual(first, second);
}
[Fact]
public void RoughnessScattersTheLight()
{
using var pipeline = CreatePipeline();
var source = Disc(64, 48, 16, 24, 8, Opaque);
var smooth = Render(pipeline, source, 64, 48, Parameters(Circle, focus: 0.4f, roughness: 0f));
var rough = Render(pipeline, source, 64, 48, Parameters(Circle, focus: 0.4f, roughness: 1f));
Assert.NotEqual(smooth, rough);
Assert.InRange(Light(rough), Light(smooth) * 0.95, Light(smooth) * 1.05);
}
[Theory]
[InlineData(5, 3)]
[InlineData(9, 1)]
[InlineData(1, 9)]
[InlineData(7, 7)]
[InlineData(8, 9)]
[InlineData(15, 16)]
[InlineData(16, 17)]
[InlineData(17, 15)]
[InlineData(65, 63)]
public void FramesThatDoNotFillWholeThreadGroupsAreReproduced(int width, int height)
{
using var pipeline = CreatePipeline();
var source = Mixed(width, height);
var parameters = Parameters(Circle, focus: 1f, dispersion: 0.3f, roughness: 0.2f, seed: 5);
var rendering = Render(pipeline, source, width, height, parameters);
AssertWithinOne(source, rendering);
}
[Theory]
[InlineData(1920, 1080)]
[InlineData(3840, 2160)]
[InlineData(4096, 2160)]
[InlineData(4096, 2730)]
public void ALargeFrameIsProcessedWithoutDispatchOverflow(int width, int height)
{
Assert.True(CausticTransportSettings.IsSupportedSize(width, height));
using var pipeline = CreatePipeline();
var rendering = Render(pipeline, Speckled(width, height), width, height, Parameters(Plane, focus: 0.5f, dispersion: 0.3f, roughness: 0.2f, seed: 5));
Assert.Contains(rendering, pixel => pixel != 0);
}
[Theory]
[InlineData(96, 64, 64, 48)]
[InlineData(64, 48, 96, 64)]
[InlineData(64, 48, 64, 64)]
[InlineData(64, 64, 64, 48)]
[InlineData(64, 64, 48, 64)]
[InlineData(48, 64, 64, 64)]
public void APipelineUsedAtAnotherSizeDrawsLikeAFreshOne(int firstWidth, int firstHeight, int width, int height)
{
using var pipeline = CreatePipeline();
using var fresh = CreatePipeline();
var parameters = Parameters(Circle, focus: 0.3f, dispersion: 0.4f, roughness: 0.3f, seed: 7);
Render(pipeline, Mixed(firstWidth, firstHeight), firstWidth, firstHeight, parameters);
var source = Mixed(width, height);
var reused = Render(pipeline, source, width, height, parameters);
var expected = Render(fresh, source, width, height, parameters);
Assert.Equal(expected, reused);
}
[Fact]
public void APipelineWhoseFrameGrowsOnTheSameGridDrawsLikeAFreshOne()
{
using var pipeline = CreatePipeline();
using var fresh = CreatePipeline();
var parameters = Parameters(Plane, focus: 0.3f);
Render(pipeline, Mixed(1000, 500), 1000, 500, parameters);
var source = Mixed(1001, 500);
var reused = Render(pipeline, source, 1001, 500, parameters);
var expected = Render(fresh, source, 1001, 500, parameters);
Assert.Equal(expected, reused);
}
[Fact]
public void SharedTexturesAreProcessedByAPipelineThatHasNotDrawnYet()
{
using var packed = CreatePipeline();
using var pipeline = CreatePipeline();
var source = Mixed(24, 18);
var parameters = Parameters(Circle, focus: 0.35f, dispersion: 0.5f);
var expected = Render(packed, source, 24, 18, parameters);
var device = GraphicsDevice.GetDefault();
using var sourceTexture = InteropServices.AllocateSharedReadWriteTexture2D<Bgra32, Float4>(device, 24, 18);
using var outputTexture = InteropServices.AllocateSharedReadWriteTexture2D<Bgra32, Float4>(device, 24, 18);
Upload(sourceTexture, source);
pipeline.ProcessSharedAndWait(sourceTexture, outputTexture, 24, 18, 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 AFrameWhosePixelCountOverflowsIsRejectedBeforeAnythingIsAllocated()
{
using var pipeline = CreatePipeline();
var device = GraphicsDevice.GetDefault();
using var source = InteropServices.AllocateSharedReadWriteTexture2D<Bgra32, Float4>(device, 1, 1);
using var destination = InteropServices.AllocateSharedReadWriteTexture2D<Bgra32, Float4>(device, 1, 1);
var parameters = Parameters(Circle);
Assert.Throws<OverflowException>(() => pipeline.Process(Array.Empty<int>(), Array.Empty<int>(), 65536, 65536, in parameters));
Assert.Throws<OverflowException>(() => pipeline.ProcessSharedAndWait(source, destination, 65536, 65536, in parameters));
}
[Fact]
public void AFrameWhoseAccumulatorCannotBeIndexedIsRejectedBeforeAnythingIsAllocated()
{
using var pipeline = CreatePipeline();
var parameters = Parameters(Circle);
Assert.Throws<OverflowException>(() => pipeline.Process(Array.Empty<int>(), Array.Empty<int>(), 30000, 20000, in parameters));
}
[Fact]
public void ALargeFrameGatheredOntoASmallApertureDoesNotOverflowTheAccumulator()
{
using var pipeline = CreatePipeline();
var source = Uniform(3840, 2160, Opaque);
var rendering = Render(pipeline, source, 3840, 2160, Parameters(Circle, focus: 0f, aperture: 0.05f));
var center = rendering[1080 * 3840 + 1920];
Assert.Equal(255, Alpha(center));
Assert.InRange(Red(center), 191, 193);
Assert.InRange(Green(center), 191, 193);
Assert.InRange(Blue(center), 191, 193);
}
[Theory]
[InlineData(CausticTransportQuality.Balanced, CausticTransportQuality.Ultra)]
[InlineData(CausticTransportQuality.Ultra, CausticTransportQuality.Balanced)]
public void APipelineUsedAtAnotherQualityDrawsLikeAFreshOne(CausticTransportQuality first, CausticTransportQuality second)
{
using var pipeline = CreatePipeline();
using var fresh = CreatePipeline();
var source = Mixed(160, 100);
Render(pipeline, source, 160, 100, Parameters(Circle, first, focus: 0.3f));
var parameters = Parameters(Circle, second, focus: 0.3f);
var reused = Render(pipeline, source, 160, 100, parameters);
var expected = Render(fresh, source, 160, 100, parameters);
Assert.Equal(expected, reused);
}
[Fact]
public void SharedTexturesProduceTheSamePicturesAsPackedBuffers()
{
using var pipeline = CreatePipeline();
var source = Mixed(24, 18);
var parameters = Parameters(Circle, focus: 0.35f, aperture: 0.4f, dispersion: 0.5f, roughness: 0.3f, seed: 11);
var expected = Render(pipeline, source, 24, 18, parameters);
var device = GraphicsDevice.GetDefault();
using var sourceTexture = InteropServices.AllocateSharedReadWriteTexture2D<Bgra32, Float4>(device, 24, 18);
using var outputTexture = InteropServices.AllocateSharedReadWriteTexture2D<Bgra32, Float4>(device, 24, 18);
Upload(sourceTexture, source);
pipeline.ProcessSharedAndWait(sourceTexture, outputTexture, 24, 18, 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 APipelineWhoseGridWasReclaimedDrawsLikeAFreshOne()
{
using var pipeline = CreatePipeline();
using var fresh = CreatePipeline();
var source = Mixed(48, 32);
var parameters = Parameters(Circle, focus: 0.3f, dispersion: 0.5f);
Render(pipeline, source, 48, 32, parameters);
GraphicsDevice.GetDefault().TrimMemory();
var reused = Render(pipeline, source, 48, 32, parameters);
var expected = Render(fresh, source, 48, 32, parameters);
Assert.Equal(expected, reused);
}
[Fact]
public void AWarmPipelineAllocatesNoManagedMemory()
{
using var pipeline = CreatePipeline();
var source = Mixed(16, 16);
var destination = new int[source.Length];
var parameters = Parameters(Circle, dispersion: 0.5f, roughness: 0.5f, seed: 1);
for (var iteration = 0; iteration < 4; iteration++)
pipeline.Process(source, destination, 16, 16, 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, 16, 16, in parameters);
minimum = Math.Min(minimum, GC.GetAllocatedBytesForCurrentThread() - before);
}
Assert.Equal(0, minimum);
}
[Fact]
public void RepeatedSharedTextureSubmissionsAllocateNoManagedMemory()
{
using var pipeline = CreatePipeline();
var device = GraphicsDevice.GetDefault();
using var source = InteropServices.AllocateSharedReadWriteTexture2D<Bgra32, Float4>(device, 16, 16);
using var destination = InteropServices.AllocateSharedReadWriteTexture2D<Bgra32, Float4>(device, 16, 16);
var parameters = Parameters(Circle, aperture: 0.3f);
for (var iteration = 0; iteration < 4; iteration++)
pipeline.Process(source, destination, 16, 16, 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, 16, 16, in parameters);
minimum = Math.Min(minimum, GC.GetAllocatedBytesForCurrentThread() - before);
}
pipeline.WaitForCompletion();
Assert.Equal(0, minimum);
}
}
+333
ファイルの表示
@@ -0,0 +1,333 @@
using ComputeWeave;
namespace CausticTransport.Tests;
public sealed class CausticTransportSettingsTests
{
public static readonly TheoryData<CausticTransportQuality> Qualities = [CausticTransportQuality.Balanced, CausticTransportQuality.High, CausticTransportQuality.Ultra];
[Theory]
[InlineData(CausticTransportQuality.Balanced, 128, 4, 12)]
[InlineData(CausticTransportQuality.High, 192, 6, 16)]
[InlineData(CausticTransportQuality.Ultra, 256, 8, 20)]
public void EachQualityHasItsGridResolutionAndIterations(CausticTransportQuality quality, int resolution, int transport, int jacobi)
{
var settings = CausticTransportSettings.GetQuality(quality);
Assert.Equal(resolution, settings.GridResolution);
Assert.Equal(transport, settings.TransportIterations);
Assert.Equal(jacobi, settings.JacobiIterations);
}
[Fact]
public void AnUnknownQualityFallsBackToHigh()
{
var unknown = CausticTransportSettings.GetQuality((CausticTransportQuality)99);
Assert.Equal(CausticTransportSettings.GetQuality(CausticTransportQuality.High), unknown);
}
[Fact]
public void ABetterQualitySolvesOnAFinerGridWithMoreIterations()
{
var balanced = CausticTransportSettings.GetQuality(CausticTransportQuality.Balanced);
var high = CausticTransportSettings.GetQuality(CausticTransportQuality.High);
var ultra = CausticTransportSettings.GetQuality(CausticTransportQuality.Ultra);
Assert.True(balanced.GridResolution < high.GridResolution && high.GridResolution < ultra.GridResolution);
Assert.True(balanced.TransportIterations < high.TransportIterations && high.TransportIterations < ultra.TransportIterations);
Assert.True(balanced.JacobiIterations < high.JacobiIterations && high.JacobiIterations < ultra.JacobiIterations);
}
[Theory]
[InlineData(1920, 1080, 192, 192, 108)]
[InlineData(1080, 1920, 192, 108, 192)]
[InlineData(1000, 333, 192, 192, 64)]
[InlineData(333, 1000, 192, 64, 192)]
[InlineData(101, 100, 256, 101, 100)]
[InlineData(100, 100, 256, 100, 100)]
[InlineData(500, 500, 192, 192, 192)]
[InlineData(8, 8, 192, 8, 8)]
[InlineData(2, 2, 192, 4, 4)]
[InlineData(4096, 16, 128, 128, 4)]
[InlineData(16, 4096, 128, 4, 128)]
[InlineData(8192, 1, 256, 256, 4)]
public void TheGridKeepsTheAspectOfTheFrameWithinItsBounds(int width, int height, int resolution, int expectedWidth, int expectedHeight)
{
var (gridWidth, gridHeight) = CausticTransportSettings.GetGridSize(width, height, resolution);
Assert.Equal(expectedWidth, gridWidth);
Assert.Equal(expectedHeight, gridHeight);
}
[Theory]
[MemberData(nameof(Qualities))]
public void TheGridNeverExceedsTheResolutionOfTheQuality(CausticTransportQuality quality)
{
var resolution = CausticTransportSettings.GetQuality(quality).GridResolution;
foreach (var (width, height) in new[] { (8192, 8192), (8192, 1), (1, 8192), (3840, 2160), (7, 5), (5, 7) })
{
var (gridWidth, gridHeight) = CausticTransportSettings.GetGridSize(width, height, resolution);
Assert.InRange(gridWidth, CausticTransportSettings.MinimumGridSize, resolution);
Assert.InRange(gridHeight, CausticTransportSettings.MinimumGridSize, resolution);
}
}
[Theory]
[InlineData(4, 4, 1)]
[InlineData(8, 8, 1)]
[InlineData(16, 16, 1)]
[InlineData(17, 4, 2)]
[InlineData(4, 17, 2)]
[InlineData(17, 17, 2)]
[InlineData(32, 32, 2)]
[InlineData(33, 33, 3)]
[InlineData(192, 108, 5)]
[InlineData(256, 256, 5)]
[InlineData(4, 128, 4)]
[InlineData(128, 4, 4)]
public void TheLevelsHalveTheGridDownToTheCoarsestSize(int gridWidth, int gridHeight, int expected)
{
Assert.Equal(expected, CausticTransportSettings.GetLevelCount(gridWidth, gridHeight));
}
[Theory]
[InlineData(192, 108, 96, 54)]
[InlineData(7, 5, 4, 4)]
[InlineData(5, 128, 4, 64)]
[InlineData(4, 4, 4, 4)]
[InlineData(255, 255, 128, 128)]
public void ACoarserLevelHalvesRoundingUpWithoutPassingTheMinimum(int width, int height, int expectedWidth, int expectedHeight)
{
var (coarserWidth, coarserHeight) = CausticTransportSettings.GetCoarserLevelSize(width, height);
Assert.Equal(expectedWidth, coarserWidth);
Assert.Equal(expectedHeight, coarserHeight);
}
[Theory]
[InlineData(0, 192, 108)]
[InlineData(1, 96, 54)]
[InlineData(2, 48, 27)]
[InlineData(3, 24, 14)]
[InlineData(4, 12, 7)]
public void ALevelSizeIsTheGridHalvedOncePerLevel(int level, int expectedWidth, int expectedHeight)
{
var (width, height) = CausticTransportSettings.GetLevelSize(192, 108, level);
Assert.Equal(expectedWidth, width);
Assert.Equal(expectedHeight, height);
}
[Theory]
[MemberData(nameof(Qualities))]
public void EveryLevelOfEverySupportedFrameFitsTheLevelsTheResourcesHold(CausticTransportQuality quality)
{
var resolution = CausticTransportSettings.GetQuality(quality).GridResolution;
foreach (var (width, height) in new[] { (8192, 8192), (8192, 1), (1, 8192), (1920, 1080), (1080, 1920), (4096, 16), (16, 4096), (17, 17), (1, 1) })
{
var (gridWidth, gridHeight) = CausticTransportSettings.GetGridSize(width, height, resolution);
Assert.InRange(CausticTransportSettings.GetLevelCount(gridWidth, gridHeight), 1, CausticTransportSettings.MaximumLevelCount);
}
}
[Theory]
[InlineData(1, 8)]
[InlineData(7, 8)]
[InlineData(8, 8)]
[InlineData(9, 16)]
[InlineData(1080, 1080)]
[InlineData(2730, 2736)]
[InlineData(8191, 8192)]
[InlineData(8192, 8192)]
public void TheSplatDispatchCoversTheFrameInWholeThreadGroups(int size, int expected)
{
var horizontal = ThreadGroupAlignment.AlignX<SplatShader>(size);
var vertical = ThreadGroupAlignment.AlignY<SplatShader>(size);
Assert.Equal(expected, horizontal);
Assert.Equal(expected, vertical);
Assert.Equal(0, horizontal % CausticTransportSettings.SplatGroupSize);
Assert.InRange(horizontal - size, 0, CausticTransportSettings.SplatGroupSize - 1);
}
[Fact]
public void EverySupportedSizeIsRoundedUpToTheNextWholeThreadGroup()
{
for (var size = 1; size <= CausticTransportSettings.MaximumCanvasSize; size++)
{
var expected = (size + CausticTransportSettings.SplatGroupSize - 1) / CausticTransportSettings.SplatGroupSize * CausticTransportSettings.SplatGroupSize;
Assert.Equal(expected, ThreadGroupAlignment.AlignX<SplatShader>(size));
Assert.Equal(expected, ThreadGroupAlignment.AlignY<SplatShader>(size));
}
}
[Fact]
public void TheSplatTileHoldsFourChannelsPerCell()
{
Assert.Equal(CausticTransportSettings.SplatTileSize * CausticTransportSettings.SplatTileSize * 4, CausticTransportSettings.SplatTileLength);
Assert.True(CausticTransportSettings.SplatTileSize > CausticTransportSettings.SplatGroupSize);
}
[Fact]
public void TheSplatTileCoversTheGroupWithinItsMargin()
{
Assert.InRange(CausticTransportSettings.SplatTileMargin, 1, CausticTransportSettings.SplatTileSize - CausticTransportSettings.SplatGroupSize - 1);
}
[Theory]
[InlineData(128, 72, 1)]
[InlineData(192, 108, 2)]
[InlineData(256, 144, 2)]
[InlineData(64, 64, 1)]
[InlineData(48, 32, 0)]
[InlineData(16, 16, 0)]
public void TheCoarseSolveStartsAtTheFinestLevelThatFitsItsSharedMemory(int gridWidth, int gridHeight, int expected)
{
Assert.Equal(expected, CausticTransportSettings.GetCoarseSolveLevel(gridWidth, gridHeight));
}
[Theory]
[MemberData(nameof(Qualities))]
public void TheCoarseSolveOfEverySupportedFrameFitsItsSharedMemory(CausticTransportQuality quality)
{
var resolution = CausticTransportSettings.GetQuality(quality).GridResolution;
foreach (var (width, height) in new[] { (8192, 8192), (8192, 1), (1, 8192), (1920, 1080), (1080, 1920), (4096, 16), (16, 4096), (17, 17), (1, 1) })
{
var (gridWidth, gridHeight) = CausticTransportSettings.GetGridSize(width, height, resolution);
var levelCount = CausticTransportSettings.GetLevelCount(gridWidth, gridHeight);
var level = CausticTransportSettings.GetCoarseSolveLevel(gridWidth, gridHeight);
var (levelWidth, levelHeight) = CausticTransportSettings.GetLevelSize(gridWidth, gridHeight, level);
var required = 2 * levelWidth * levelHeight;
for (var coarser = level; coarser < levelCount; coarser++)
{
var (coarserWidth, coarserHeight) = CausticTransportSettings.GetLevelSize(gridWidth, gridHeight, coarser);
required += coarserWidth * coarserHeight;
}
Assert.InRange(level, 0, levelCount - 1);
Assert.True(required <= CausticTransportSettings.CoarseSolveCapacity, $"{width}x{height} {quality}");
}
}
[Theory]
[InlineData(12, 3)]
[InlineData(16, 4)]
[InlineData(20, 5)]
[InlineData(4, 1)]
[InlineData(0, 0)]
[InlineData(-4, 0)]
[InlineData(18, 0)]
[InlineData(24, 0)]
public void TheJacobiStepsSplitIntoBlocksOnlyWhenTheyDivideEvenlyWithinTheHalo(int iterations, int expected)
{
Assert.Equal(expected, CausticTransportSettings.GetJacobiBlockSteps(iterations));
}
[Theory]
[MemberData(nameof(Qualities))]
public void EveryQualityRelaxesItsFineLevelsInBlocks(CausticTransportQuality quality)
{
var iterations = CausticTransportSettings.GetQuality(quality).JacobiIterations;
Assert.Equal(iterations, CausticTransportSettings.GetJacobiBlockSteps(iterations) * CausticTransportSettings.JacobiBlockCount);
}
[Fact]
public void TheJacobiBlocksEndOnTheBufferTheNextStageReads()
{
Assert.Equal(0, CausticTransportSettings.JacobiBlockCount % 2);
Assert.Equal(CausticTransportSettings.JacobiTileSize + 2 * CausticTransportSettings.JacobiBlockMaximumSteps, CausticTransportSettings.JacobiBlockSpan);
Assert.Equal(CausticTransportSettings.JacobiBlockSpan * CausticTransportSettings.JacobiBlockSpan, CausticTransportSettings.JacobiBlockLength);
}
[Theory]
[InlineData(1, 65536)]
[InlineData(64, 65536)]
[InlineData(43690, 65536)]
[InlineData(43691, 65535)]
[InlineData(65536, 43690)]
[InlineData(1920 * 1080, 1380)]
[InlineData(3840 * 2160, 345)]
[InlineData(11184810, 256)]
[InlineData(int.MaxValue, 256)]
public void TheColorScaleShrinksWithThePixelCountWithinItsBounds(int pixelCount, int expected)
{
Assert.Equal(expected, CausticTransportSettings.GetColorFixedScale(pixelCount));
}
[Theory]
[InlineData(0)]
[InlineData(-5)]
public void AnEmptyFrameIsScaledLikeASinglePixel(int pixelCount)
{
Assert.Equal(CausticTransportSettings.GetColorFixedScale(1), CausticTransportSettings.GetColorFixedScale(pixelCount));
}
[Theory]
[InlineData(1)]
[InlineData(1000)]
[InlineData(43690)]
[InlineData(43691)]
[InlineData(1920 * 1080)]
[InlineData(3840 * 2160)]
[InlineData(4096 * 2160)]
[InlineData(11184810)]
public void TheColorOfEveryPixelAccumulatesWithinTheUnsignedRangeWithMargin(int pixelCount)
{
var scale = CausticTransportSettings.GetColorFixedScale(pixelCount);
Assert.True((double)scale * pixelCount * CausticTransportSettings.ColorFixedScaleMargin <= uint.MaxValue);
}
[Fact]
public void TheLargestSupportedFrameStillAccumulatesWithinTheUnsignedRange()
{
var scale = CausticTransportSettings.GetColorFixedScale(CausticTransportSettings.MaximumPixelCount);
Assert.Equal(CausticTransportSettings.MinimumColorFixedScale, scale);
Assert.True((double)CausticTransportSettings.MaximumPixelCount * scale * CausticTransportSettings.ColorFixedScaleMargin <= uint.MaxValue);
Assert.True((double)(CausticTransportSettings.MaximumPixelCount + 1) * scale * CausticTransportSettings.ColorFixedScaleMargin > uint.MaxValue);
}
[Fact]
public void FourKFramesAreSupported()
{
Assert.True(CausticTransportSettings.MaximumPixelCount >= 4096 * 2160);
Assert.True(CausticTransportSettings.MaximumCanvasSize >= 4096);
}
[Theory]
[InlineData(1d, 1d, true)]
[InlineData(1920d, 1080d, true)]
[InlineData(3840d, 2160d, true)]
[InlineData(4096d, 2160d, true)]
[InlineData(8192d, 1d, true)]
[InlineData(1d, 8192d, true)]
[InlineData(8192d, 1365d, true)]
[InlineData(8192d, 1366d, false)]
[InlineData(1446d, 7735d, true)]
[InlineData(1446d, 7736d, false)]
[InlineData(8193d, 1d, false)]
[InlineData(1d, 8193d, false)]
[InlineData(4096d, 2731d, false)]
[InlineData(0.5d, 100d, false)]
[InlineData(100d, 0.5d, false)]
[InlineData(0d, 1080d, false)]
[InlineData(1920d, 0d, false)]
[InlineData(-1d, 1080d, false)]
[InlineData(double.NaN, 1080d, false)]
[InlineData(1920d, double.NaN, false)]
[InlineData(double.PositiveInfinity, 1080d, false)]
[InlineData(1920d, double.PositiveInfinity, false)]
public void AFrameIsSupportedWhenItsSidesAndPixelCountStayWithinTheLimits(double width, double height, bool expected)
{
Assert.Equal(expected, CausticTransportSettings.IsSupportedSize(width, height));
}
}
+28
ファイルの表示
@@ -0,0 +1,28 @@
using System.Drawing;
using System.Numerics;
using Vortice.Direct2D1;
using YukkuriMovieMaker.Player.Video;
namespace CausticTransport.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);
}
}
+37
ファイルの表示
@@ -0,0 +1,37 @@
using System.IO;
using System.Reflection;
using System.Runtime.CompilerServices;
namespace CausticTransport.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;
}
+45
ファイルの表示
@@ -0,0 +1,45 @@
using System.Reflection;
using System.Windows;
using Telemetry;
namespace CausticTransport.Tests;
public sealed class HostIntegrationTests
{
static int UpdateChecksStarted()
=> (int)typeof(CausticTransportUpdateNotifier).GetField("_started", BindingFlags.NonPublic | BindingFlags.Static)!.GetValue(null)!;
[Fact]
public void OutsideAWpfApplicationNoTelemetryIsStartedOrSent()
{
Assert.Null(Application.Current);
CausticTransportTelemetry.EnsureStartedOnce();
CausticTransportTelemetry.Report(new InvalidOperationException());
Assert.Null(ProcessState.Read("DrainClaimed"));
Assert.Null(ProcessState.Read("SentCount"));
}
[Fact]
public void OutsideAWpfApplicationNoUpdateCheckIsStarted()
{
Assert.Null(Application.Current);
CausticTransportUpdateNotifier.EnsureCheckedOnce();
Assert.Equal(0, UpdateChecksStarted());
}
[Fact]
public void OutsideAWpfApplicationTheEffectCanStillBeCreated()
{
Assert.Null(Application.Current);
var effect = new CausticTransportEffect();
Assert.Equal(Texts.CausticTransport, effect.Label);
Assert.Equal(0, UpdateChecksStarted());
Assert.Null(ProcessState.Read("DrainClaimed"));
}
}
+10
ファイルの表示
@@ -0,0 +1,10 @@
using System.IO.Packaging;
using System.Runtime.CompilerServices;
namespace CausticTransport.Tests;
internal static class PackUriScheme
{
[ModuleInitializer]
internal static void Register() => _ = PackUriHelper.UriSchemePack;
}
+95
ファイルの表示
@@ -0,0 +1,95 @@
using System.Numerics;
using System.Runtime.InteropServices;
using Vortice.Direct2D1;
using Vortice.Mathematics;
using YukkuriMovieMaker.Commons;
namespace CausticTransport.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);
}
}
}
+59
ファイルの表示
@@ -0,0 +1,59 @@
using Vortice.DCommon;
using Vortice.Direct2D1;
using Vortice.DXGI;
using Vortice.Mathematics;
using YukkuriMovieMaker.Commons;
namespace CausticTransport.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();
}
+60
ファイルの表示
@@ -0,0 +1,60 @@
using System.Collections;
using System.Globalization;
using System.Reflection;
namespace CausticTransport.Tests;
public sealed class TextsTests
{
public static readonly TheoryData<string> Cultures = ["ja-JP", "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();
[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 = Texts.ResourceManager.GetResourceSet(CultureInfo.GetCultureInfo(culture), true, true)!;
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.CausticTransport), CultureInfo.InvariantCulture);
Assert.Equal("光輸送結像", neutral);
Assert.Equal(neutral, Texts.ResourceManager.GetString(nameof(Texts.CausticTransport), CultureInfo.GetCultureInfo("ja-JP")));
}
[Fact]
public void TheUpdateMessageEmbedsTheVersion()
{
var message = string.Format(CultureInfo.InvariantCulture, Texts.ResourceManager.GetString(nameof(Texts.UpdateAvailableMessage), CultureInfo.InvariantCulture)!, "v1.2.3");
Assert.Contains("v1.2.3", message);
}
}
+26
ファイルの表示
@@ -0,0 +1,26 @@
{
"stryker-config": {
"project": "CausticTransport.csproj",
"test-runner": "mtp",
"coverage-analysis": "off",
"concurrency": 4,
"additional-timeout": 30000,
"mutate": [
"**/*.cs",
"!**/YMM4-GitHubUpdateNotifier/**",
"!**/YMM4-Telemetry/**",
"!**/CausticTransportTelemetry.cs",
"!**/CausticTransportUpdateNotifier.cs"
],
"reporters": [
"progress",
"cleartext",
"html"
],
"thresholds": {
"high": 80,
"low": 60,
"break": 60
}
}
}
+14 -8
ファイルの表示
@@ -3,18 +3,24 @@
<Platform Name="Any CPU" />
<Platform Name="x64" />
</Configurations>
<Project Path="ComputeSharp/src/ComputeSharp.Core/ComputeSharp.Core.csproj">
<Platform Solution="*|x64" Project="Any CPU" />
</Project>
<Project Path="ComputeSharp/src/ComputeSharp.Core.SourceGenerators/ComputeSharp.Core.SourceGenerators.csproj" />
<Project Path="ComputeSharp/src/ComputeSharp/ComputeSharp.csproj">
<Platform Solution="*|x64" Project="Any CPU" />
</Project>
<Project Path="ComputeSharp/src/ComputeSharp.SourceGenerators/ComputeSharp.SourceGenerators.csproj" />
<Folder Name="/Solution Items/">
<File Path=".editorconfig" />
<File Path=".gitattributes" />
<File Path=".gitignore" />
<File Path=".gitmodules" />
<File Path="Directory.Build.props" />
<File Path="LICENSE.txt" />
<File Path="README.md" />
</Folder>
<Project Path="CausticTransport/CausticTransport.csproj">
<Platform Solution="*|x64" Project="x64" />
<BuildDependency Project="CausticTransport.Shader/CausticTransport.Shader.vcxproj" />
</Project>
<Project Path="CausticTransport.Tests/CausticTransport.Tests.csproj" />
<Project Path="CausticTransport.Harness/CausticTransport.Harness.csproj" />
<Project Path="CausticTransport.Shader/CausticTransport.Shader.vcxproj">
<BuildType Solution="*|*" Project="Release" />
<Platform Solution="*|*" Project="Win32" />
</Project>
<Project Path="YukkuriMovieMaker.Generator/YukkuriMovieMaker.Generator/YukkuriMovieMaker.Generator.csproj" />
</Solution>
+13 -26
ファイルの表示
@@ -5,32 +5,18 @@
<UseWPF>true</UseWPF>
<ImplicitUsings>enable</ImplicitUsings>
<Nullable>enable</Nullable>
<Version>1.0.1</Version>
<Version>1.1.1</Version>
<Platforms>AnyCPU;x64</Platforms>
<PlatformTarget>x64</PlatformTarget>
<AllowUnsafeBlocks>True</AllowUnsafeBlocks>
<CopyLocalLockFileAssemblies>true</CopyLocalLockFileAssemblies>
<ShaderDirPath>..\Release\</ShaderDirPath>
</PropertyGroup>
<ItemGroup>
<HlslShader Include="Shaders\**\*.hlsl" />
<Resource Include="@(HlslShader->'%(RelativeDir)%(Filename).cso')" />
<Resource Include="$(ShaderDirPath)CausticTransport.cso" Link="Resources\Shader\CausticTransport.cso" />
</ItemGroup>
<ItemDefinitionGroup>
<HlslShader>
<ShaderType>ps_5_0</ShaderType>
<EntryPoint>main</EntryPoint>
<ObjectFileOutput>%(RelativeDir)%(Filename).cso</ObjectFileOutput>
</HlslShader>
</ItemDefinitionGroup>
<Target Name="CompileHLSLShaders" BeforeTargets="BeforeBuild" Inputs="@(HlslShader)" Outputs="@(HlslShader->'%(ObjectFileOutput)')">
<Message Text="Compiling HLSL Shader: %(HlslShader.Identity) [Type: %(HlslShader.ShaderType), Entry: %(HlslShader.EntryPoint)]" Importance="high" />
<Error Text="fxc.exe not found at path: $(FxcPath)" Condition="!Exists('$(FxcPath)') AND '$(FxcPath)' != 'fxc.exe'" />
<Exec Command="&quot;$(FxcPath)&quot; /nologo /T %(HlslShader.ShaderType) /E %(HlslShader.EntryPoint) /Fo &quot;%(HlslShader.ObjectFileOutput)&quot; &quot;%(HlslShader.FullPath)&quot;" Condition="Exists('%(HlslShader.FullPath)')" />
</Target>
<ItemGroup>
<Reference Include="SharpGen.Runtime">
<HintPath>$(YMM4DirPath)SharpGen.Runtime.dll</HintPath>
@@ -82,7 +68,11 @@
<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>
@@ -96,20 +86,17 @@
</ItemGroup>
<ItemGroup>
<ProjectReference Include="..\ComputeSharp\src\ComputeSharp.Core.SourceGenerators\ComputeSharp.Core.SourceGenerators.csproj" SetConfiguration="Configuration=$(Configuration)" SetPlatform="Platform=AnyCPU" GlobalPropertiesToRemove="SkipPluginDeploy" OutputItemType="Analyzer" ReferenceOutputAssembly="false" />
<ProjectReference Include="..\ComputeSharp\src\ComputeSharp.SourceGenerators\ComputeSharp.SourceGenerators.csproj" SetConfiguration="Configuration=$(Configuration)" SetPlatform="Platform=AnyCPU" GlobalPropertiesToRemove="SkipPluginDeploy" OutputItemType="Analyzer" ReferenceOutputAssembly="false" />
<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>
<Import Project="ComputeSharp.Reference.props" />
<Target Name="MergePluginAssembly" AfterTargets="PostBuildEvent" Inputs="$(TargetPath);$(TargetDir)ComputeWeave.dll;$(TargetDir)ComputeWeave.Core.dll" Outputs="$(TargetDir)plugin\$(TargetFileName)">
<MakeDir Directories="$(TargetDir)plugin" />
<Exec Command="&quot;$(PkgILRepack)\tools\ILRepack.exe&quot; /out:&quot;$(TargetDir)plugin\$(TargetFileName)&quot; /lib:&quot;$([System.IO.Path]::GetDirectoryName('$(TargetPath)'))&quot; /lib:&quot;$([System.IO.Path]::GetDirectoryName('$(YMM4DirPath)'))&quot; /internalize &quot;$(TargetPath)&quot; &quot;$(TargetDir)ComputeWeave.dll&quot; &quot;$(TargetDir)ComputeWeave.Core.dll&quot;" />
</Target>
<ItemGroup>
<Folder Include="Shaders\" />
</ItemGroup>
<Target Name="PostBuild" AfterTargets="PostBuildEvent" Condition="'$(SkipPluginDeploy)' != 'true' AND '$(BuildingSolutionFile)' != 'true'">
<Exec Command="mkdir &quot;$(YMM4DirPath)user\plugin\$(ProjectName)&quot; &gt; NUL 2&gt;&amp;1&#xD;&#xA;copy &quot;$(TargetPath)&quot; &quot;$(YMM4DirPath)user\plugin\$(ProjectName)\&quot;&#xD;&#xA;copy &quot;$(TargetDir)CausticTransport.ComputeSharp.dll&quot; &quot;$(YMM4DirPath)user\plugin\$(ProjectName)\&quot;&#xD;&#xA;copy &quot;$(TargetDir)CausticTransport.ComputeSharp.Core.dll&quot; &quot;$(YMM4DirPath)user\plugin\$(ProjectName)\&quot;" />
<Target Name="PostBuild" AfterTargets="MergePluginAssembly" Condition="'$(SkipPluginDeploy)' != 'true' AND '$(BuildingSolutionFile)' != 'true'">
<Exec Command="mkdir &quot;$(YMM4DirPath)user\plugin\$(ProjectName)&quot; &gt; NUL 2&gt;&amp;1&#xD;&#xA;copy &quot;$(TargetDir)plugin\$(TargetFileName)&quot; &quot;$(YMM4DirPath)user\plugin\$(ProjectName)\&quot;&#xD;&#xA;del &quot;$(YMM4DirPath)user\plugin\$(ProjectName)\ComputeWeave.dll&quot; &gt; NUL 2&gt;&amp;1&#xD;&#xA;del &quot;$(YMM4DirPath)user\plugin\$(ProjectName)\ComputeWeave.Core.dll&quot; &gt; NUL 2&gt;&amp;1" />
</Target>
</Project>
+12 -1
ファイルの表示
@@ -33,7 +33,18 @@ internal sealed class CausticTransportCustomEffect(IGraphicsDevicesAndContext de
protected override void UpdateConstants()
{
drawInformation?.SetPixelShaderConstantBuffer(_cb);
if (drawInformation is null)
return;
try
{
drawInformation.SetPixelShaderConstantBuffer(_cb);
}
catch (Exception exception)
{
CausticTransportTelemetry.Report(exception);
throw;
}
}
public override void MapInputRectsToOutputRect(
+12 -1
ファイルの表示
@@ -15,6 +15,7 @@ public sealed class CausticTransportEffect : VideoEffectBase
public CausticTransportEffect()
{
CausticTransportTelemetry.EnsureStartedOnce();
CausticTransportUpdateNotifier.EnsureCheckedOnce();
}
@@ -64,7 +65,17 @@ public sealed class CausticTransportEffect : VideoEffectBase
public override IEnumerable<string> CreateExoVideoFilters(int keyFrameIndex, ExoOutputDescription exoOutputDescription) => [];
public override IVideoEffectProcessor CreateVideoEffect(IGraphicsDevicesAndContext devices)
=> new CausticTransportEffectProcessor(devices, this);
{
try
{
return new CausticTransportEffectProcessor(devices, this);
}
catch (Exception exception)
{
CausticTransportTelemetry.Report(exception);
throw;
}
}
protected override IEnumerable<IAnimatable> GetAnimatables()
=> _animatables ??= [Amount, Focus, ApertureSize, Dispersion, Roughness];
+212 -40
ファイルの表示
@@ -1,4 +1,6 @@
using System.ComponentModel;
using System.Numerics;
using ComputeWeave;
using Vortice.Direct2D1;
using Vortice.Direct2D1.Effects;
using YukkuriMovieMaker.Commons;
@@ -11,16 +13,26 @@ internal sealed class CausticTransportEffectProcessor : VideoEffectProcessorBase
{
private readonly IGraphicsDevicesAndContext _devices;
private readonly CausticTransportEffect _item;
private CausticTransportGpuInterop? _interop;
private ComputeExternalQueueScheduler? _scheduler;
private CausticTransportInteropProvider? _interopProvider;
private ComputeInteropDomain? _interopDomain;
private CausticTransportResourceSet? _resourceSet;
private ExternalTextureLease<ExternalDirect3D11TextureView>? _outputLease;
private CausticTransportPipeline? _pipeline;
private CausticTransportCustomEffect? _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 Parameters _parameters;
private RenderState _renderState;
public CausticTransportEffectProcessor(IGraphicsDevicesAndContext devices, CausticTransportEffect item)
: base(devices)
@@ -31,7 +43,20 @@ internal sealed class CausticTransportEffectProcessor : VideoEffectProcessorBase
public override DrawDescription Update(EffectDescription effectDescription)
{
if (IsPassThroughEffect || _effect is null || _outputTransform is null || _outputTransformOutput is null || _interop is null || _pipeline is null || input is null)
try
{
return UpdateCore(effectDescription);
}
catch (Exception exception)
{
CausticTransportTelemetry.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;
@@ -78,17 +103,14 @@ internal sealed class CausticTransportEffectProcessor : VideoEffectProcessorBase
var width = (int)widthValue;
var height = (int)heightValue;
if (!_interop.MatchesSize(width, height))
_outputTransform.SetInput(0, null, true);
var resourcesChanged = _interop.EnsureResources(width, height);
var outputOffset = new Vector2(bounds.Left, bounds.Top);
if (!_hasOutputOffset || _outputOffset != outputOffset)
if (!_resourceSet.TryEnsureSource(width, height, out _))
{
_outputTransform.TransformMatrix = Matrix3x2.CreateTranslation(outputOffset);
_outputOffset = outputOffset;
_hasOutputOffset = true;
_effect.Amount = 0f;
_isFirst = true;
return effectDescription.DrawDescription;
}
_interop.RenderInput(input, bounds);
RenderInput(new Vortice.RawRectF(bounds.Left, bounds.Top, bounds.Left + width, bounds.Top + height));
var pipelineParameters = new CausticTransportPipeline.Parameters(
(int)parameters.LightShape,
@@ -99,45 +121,163 @@ internal sealed class CausticTransportEffectProcessor : VideoEffectProcessorBase
Math.Clamp(parameters.Roughness, 0f, 1f),
Math.Max(parameters.Seed, 0));
_interop.BeginCompute();
try
var transportChanged = _pipeline.Simulate(
_resourceSet.GetSourceComputeBinding(),
width,
height,
in pipelineParameters);
if (!OutputCovers(width, height))
_outputCrop.SetInput(0, null, true);
if (!EnsureOutput(width, height, out var outputChanged))
{
_pipeline.Process(
_interop.SourceTexture,
_interop.OutputTexture,
_effect.Amount = 0f;
_isFirst = true;
_hasOutput = false;
_hasRenderState = false;
return effectDescription.DrawDescription;
}
var renderState = new RenderState(
new RenderSettings(
pipelineParameters.Focus,
pipelineParameters.Dispersion,
pipelineParameters.Roughness,
pipelineParameters.Roughness > 0f ? pipelineParameters.Seed : 0),
width,
height);
if (transportChanged || outputChanged || !_hasOutput || !_hasRenderState || _renderState != renderState)
{
_pipeline.Render(
_resourceSet.GetSourceComputeBinding(),
_resourceSet.GetOutputComputeBinding(),
width,
height,
in pipelineParameters);
}
finally
{
_interop.EndCompute();
_renderState = renderState;
_hasRenderState = true;
}
if (resourcesChanged || !_hasOutput)
_outputLease ??= _resourceSet.AcquireOutputExternalViewLease();
if (outputChanged || !_hasOutput)
{
_outputTransform.SetInput(0, _interop.OutputBitmap, true);
using var outputBitmap = new ID2D1Bitmap1(_outputLease.DangerousGetView().AddRefBitmap());
_outputCrop.SetInput(0, outputBitmap, true);
_effect.SetInput(1, _outputTransformOutput, true);
}
var cropRect = new Vector4(0f, 0f, width, height);
if (!_hasCropRect || _cropRect != cropRect)
{
_outputCrop.Rectangle = cropRect;
_cropRect = cropRect;
_hasCropRect = true;
}
var outputOffset = new Vector2(bounds.Left, bounds.Top);
if (!_hasOutputOffset || _outputOffset != outputOffset)
{
_outputTransform.TransformMatrix = Matrix3x2.CreateTranslation(outputOffset);
_outputOffset = outputOffset;
_hasOutputOffset = true;
}
_hasOutput = true;
_parameters = parameters;
_isFirst = false;
return effectDescription.DrawDescription;
}
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 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 interop = CausticTransportGpuInterop.TryCreate(devices);
if (interop is null)
return null;
var pipeline = CausticTransportPipeline.TryCreate(interop.Device);
if (pipeline is null)
var scheduler = ComputeExternalQueueScheduler.Create();
var interopProvider = CausticTransportInteropProvider.TryCreate(devices, scheduler, out var interopDevice);
if (interopProvider is null || interopDevice is null)
{
interop.Dispose();
scheduler.Dispose();
return null;
}
_scheduler = scheduler;
try
{
_interopProvider = interopProvider;
_interopDomain = interopDevice.RegisterExternalDomain(interopProvider);
_resourceSet = CausticTransportResourceSet.Create(interopDevice, _interopDomain);
_pipeline = CausticTransportPipeline.TryCreate(interopDevice);
}
catch (Win32Exception)
{
ReleaseInterop();
return null;
}
catch
{
ReleaseInterop();
throw;
}
if (_pipeline is null)
{
ReleaseInterop();
return null;
}
CausticTransportCustomEffect? effect = null;
Crop? outputCrop = null;
ID2D1Image? outputCropOutput = null;
AffineTransform2D? outputTransform = null;
ID2D1Image? outputTransformOutput = null;
ID2D1Image? output = null;
@@ -147,22 +287,26 @@ internal sealed class CausticTransportEffectProcessor : VideoEffectProcessorBase
if (!effect.IsEnabled)
{
effect.Dispose();
pipeline.Dispose();
interop.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;
_interop = interop;
_pipeline = pipeline;
_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);
@@ -173,14 +317,28 @@ internal sealed class CausticTransportEffectProcessor : VideoEffectProcessorBase
output?.Dispose();
outputTransformOutput?.Dispose();
outputTransform?.Dispose();
outputCropOutput?.Dispose();
outputCrop?.Dispose();
effect?.Dispose();
pipeline.Dispose();
interop.Dispose();
ReleaseInterop();
throw;
}
}
protected override void setInput(ID2D1Image? inputImage)
{
try
{
SetInputCore(inputImage);
}
catch (Exception exception)
{
CausticTransportTelemetry.Report(exception);
throw;
}
}
private void SetInputCore(ID2D1Image? inputImage)
{
_effect?.SetInput(0, inputImage, true);
if (!_hasOutput)
@@ -191,10 +349,12 @@ internal sealed class CausticTransportEffectProcessor : VideoEffectProcessorBase
{
_effect?.SetInput(0, null, true);
_effect?.SetInput(1, null, true);
_outputTransform?.SetInput(0, null, true);
_outputCrop?.SetInput(0, null, true);
_isFirst = true;
_hasOutput = false;
_hasOutputOffset = false;
_hasCropRect = false;
_hasRenderState = false;
}
protected override void Dispose(bool disposing)
@@ -204,13 +364,14 @@ internal sealed class CausticTransportEffectProcessor : VideoEffectProcessorBase
if (disposing)
{
ClearEffectChain();
_interop?.WaitForIdle();
_pipeline?.Dispose();
_pipeline = null;
_interop?.Dispose();
_interop = null;
ReleaseInterop();
}
}
catch (Exception exception)
{
CausticTransportTelemetry.Report(exception);
throw;
}
finally
{
base.Dispose(disposing);
@@ -226,4 +387,15 @@ internal sealed class CausticTransportEffectProcessor : VideoEffectProcessorBase
float Dispersion,
float Roughness,
int Seed);
private readonly record struct RenderSettings(
float Focus,
float Dispersion,
float Roughness,
int Seed);
private readonly record struct RenderState(
RenderSettings Settings,
int Width,
int Height);
}
+56 -243
ファイルの表示
@@ -1,276 +1,89 @@
using System.Runtime.InteropServices;
using ComputeSharp;
using ComputeSharp.Interop;
using Vortice;
using ComputeWeave;
using Vortice.Direct2D1;
using Vortice.Direct3D11;
using Vortice.DXGI;
using YukkuriMovieMaker.Commons;
using PixelFormat = Vortice.DCommon.PixelFormat;
namespace CausticTransport;
internal sealed class CausticTransportGpuInterop : IDisposable
internal sealed class CausticTransportInteropProvider : ComputeExternalDirect3D11Provider
{
private static readonly Guid D3D12FenceGuid = new("0a753dcf-c4d8-4b91-adf6-be5a60d95a76");
private readonly GraphicsDevice _device;
private readonly ID3D11Device1 _d3dDevice;
private readonly ID3D11DeviceContext4 _d3dContext;
private readonly ID3D11Fence _fence;
private readonly ID2D1DeviceContext6 _renderContext;
private nint _d3d12Fence;
private ReadWriteTexture2D<Bgra32, Float4>? _sourceTexture;
private ReadWriteTexture2D<Bgra32, Float4>? _outputTexture;
private ID3D11Texture2D? _sourceD3D11Texture;
private ID3D11Texture2D? _outputD3D11Texture;
private ID2D1Bitmap1? _sourceBitmap;
private ID2D1Bitmap1? _outputBitmap;
private int _width;
private int _height;
private ulong _fenceValue;
private bool _computeActive;
private bool _disposed;
private CausticTransportGpuInterop(
GraphicsDevice device,
ID3D11Device1 d3dDevice,
ID3D11DeviceContext4 d3dContext,
ID3D11Fence fence,
private CausticTransportInteropProvider(
ID3D11Device1 device,
ID3D11DeviceContext4 context,
ID2D1DeviceContext6 renderContext,
nint d3d12Fence)
ComputeExternalQueueScheduler scheduler)
: base(device.NativePointer, context.NativePointer, renderContext.NativePointer, scheduler)
{
_device = device;
_d3dDevice = d3dDevice;
_d3dContext = d3dContext;
_fence = fence;
_renderContext = renderContext;
_d3d12Fence = d3d12Fence;
}
public GraphicsDevice Device => _device;
public ID2D1DeviceContext6 RenderContext => _renderContext;
public ReadWriteTexture2D<Bgra32, Float4> SourceTexture => _sourceTexture!;
public ReadWriteTexture2D<Bgra32, Float4> OutputTexture => _outputTexture!;
public ID2D1Bitmap1 OutputBitmap => _outputBitmap!;
public bool MatchesSize(int width, int height)
=> _sourceTexture is not null && _width == width && _height == height;
public static unsafe CausticTransportGpuInterop? TryCreate(IGraphicsDevicesAndContext devices)
public static CausticTransportInteropProvider? TryCreate(
IGraphicsDevicesAndContext devices,
ComputeExternalQueueScheduler scheduler,
out GraphicsDevice? graphicsDevice)
{
ID3D11Device1? d3dDevice = null;
ID3D11DeviceContext4? d3dContext = null;
ID3D11Fence? fence = null;
ArgumentNullException.ThrowIfNull(scheduler);
graphicsDevice = null;
ID3D11Device1? device = null;
ID3D11DeviceContext4? context = null;
ID2D1DeviceContext6? renderContext = null;
nint d3d12Fence = 0;
nint fenceHandle = 0;
try
{
var device = GetMatchingDevice(devices);
d3dDevice = devices.D3D.Device.QueryInterface<ID3D11Device1>();
d3dContext = devices.D3D.DeviceContext.QueryInterface<ID3D11DeviceContext4>();
using var d3dDevice5 = devices.D3D.Device.QueryInterface<ID3D11Device5>();
var fenceGuid = D3D12FenceGuid;
InteropServices.CreateSharedFence(device, &fenceGuid, (void**)&d3d12Fence, &fenceHandle);
fence = d3dDevice5.OpenSharedFence(fenceHandle);
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);
return new CausticTransportGpuInterop(device, d3dDevice, d3dContext, fence, renderContext, d3d12Fence);
var provider = new CausticTransportInteropProvider(device, context, renderContext, scheduler);
renderContext = null;
return provider;
}
catch
{
renderContext?.Dispose();
fence?.Dispose();
d3dContext?.Dispose();
d3dDevice?.Dispose();
if (d3d12Fence != 0)
Marshal.Release(d3d12Fence);
graphicsDevice = null;
return null;
}
finally
{
if (fenceHandle != 0)
CloseHandle(fenceHandle);
renderContext?.Dispose();
context?.Dispose();
device?.Dispose();
}
}
public bool EnsureResources(int width, int height)
protected override void DisposeCore()
{
if (MatchesSize(width, height))
return false;
if (_sourceTexture is not null)
WaitForIdle();
ReleaseResources();
CreateResources(width, height);
return true;
_renderContext.Dispose();
}
public void RenderInput(ID2D1Image source, RawRectF bounds)
{
_renderContext.BeginDraw();
_renderContext.Clear(null);
_renderContext.DrawImage(
source,
new System.Numerics.Vector2(-bounds.Left, -bounds.Top),
null,
InterpolationMode.NearestNeighbor,
CompositeMode.SourceCopy);
_renderContext.EndDraw();
}
public unsafe void BeginCompute()
{
if (_computeActive)
throw new InvalidOperationException();
var value = ++_fenceValue;
_d3dContext.Signal(_fence, value);
_d3dContext.Flush();
InteropServices.WaitForSharedFence(_device, (void*)_d3d12Fence, value);
_computeActive = true;
}
public unsafe void EndCompute()
{
if (!_computeActive)
throw new InvalidOperationException();
try
{
var value = ++_fenceValue;
InteropServices.SignalSharedFence(_device, (void*)_d3d12Fence, value);
_d3dContext.Wait(_fence, value);
}
finally
{
_computeActive = false;
}
}
public void WaitForIdle()
{
if (_computeActive)
throw new InvalidOperationException();
var value = ++_fenceValue;
_d3dContext.Signal(_fence, value);
_d3dContext.Flush();
_fence.SetEventOnCompletion(value, 0);
}
private static GraphicsDevice GetMatchingDevice(IGraphicsDevicesAndContext devices)
{
var adapterLuid = devices.DXGI.Adapter.Description.Luid.ToString();
using var enumerator = GraphicsDevice.QueryDevices(
device => string.Equals(device.Luid.ToString(), adapterLuid, StringComparison.Ordinal)).GetEnumerator();
if (!enumerator.MoveNext())
throw new NotSupportedException();
return enumerator.Current;
}
private void CreateResources(int width, int height)
{
ReadWriteTexture2D<Bgra32, Float4>? sourceTexture = null;
ReadWriteTexture2D<Bgra32, Float4>? outputTexture = null;
ID3D11Texture2D? sourceD3D11Texture = null;
ID3D11Texture2D? outputD3D11Texture = null;
ID2D1Bitmap1? sourceBitmap = null;
ID2D1Bitmap1? outputBitmap = null;
nint sourceHandle = 0;
nint outputHandle = 0;
try
{
sourceTexture = InteropServices.AllocateSharedReadWriteTexture2D<Bgra32, Float4>(_device, width, height);
outputTexture = InteropServices.AllocateSharedReadWriteTexture2D<Bgra32, Float4>(_device, width, height);
sourceHandle = InteropServices.CreateSharedHandle(sourceTexture);
outputHandle = InteropServices.CreateSharedHandle(outputTexture);
sourceD3D11Texture = _d3dDevice.OpenSharedResource1<ID3D11Texture2D>(sourceHandle);
outputD3D11Texture = _d3dDevice.OpenSharedResource1<ID3D11Texture2D>(outputHandle);
using var sourceSurface = sourceD3D11Texture.QueryInterface<IDXGISurface>();
using var outputSurface = outputD3D11Texture.QueryInterface<IDXGISurface>();
var pixelFormat = new PixelFormat(Format.B8G8R8A8_UNorm, Vortice.DCommon.AlphaMode.Premultiplied);
sourceBitmap = _renderContext.CreateBitmapFromDxgiSurface(
sourceSurface,
new BitmapProperties1(pixelFormat, 96f, 96f, BitmapOptions.Target));
outputBitmap = _renderContext.CreateBitmapFromDxgiSurface(
outputSurface,
new BitmapProperties1(pixelFormat, 96f, 96f, BitmapOptions.None));
_renderContext.Target = sourceBitmap;
_sourceTexture = sourceTexture;
_outputTexture = outputTexture;
_sourceD3D11Texture = sourceD3D11Texture;
_outputD3D11Texture = outputD3D11Texture;
_sourceBitmap = sourceBitmap;
_outputBitmap = outputBitmap;
_width = width;
_height = height;
sourceTexture = null;
outputTexture = null;
sourceD3D11Texture = null;
outputD3D11Texture = null;
sourceBitmap = null;
outputBitmap = null;
}
finally
{
if (sourceHandle != 0)
CloseHandle(sourceHandle);
if (outputHandle != 0)
CloseHandle(outputHandle);
outputBitmap?.Dispose();
sourceBitmap?.Dispose();
outputD3D11Texture?.Dispose();
sourceD3D11Texture?.Dispose();
outputTexture?.Dispose();
sourceTexture?.Dispose();
}
}
private void ReleaseResources()
{
_renderContext.Target = null;
_outputBitmap?.Dispose();
_sourceBitmap?.Dispose();
_outputD3D11Texture?.Dispose();
_sourceD3D11Texture?.Dispose();
_outputTexture?.Dispose();
_sourceTexture?.Dispose();
_outputBitmap = null;
_sourceBitmap = null;
_outputD3D11Texture = null;
_sourceD3D11Texture = null;
_outputTexture = null;
_sourceTexture = null;
_width = 0;
_height = 0;
}
public void Dispose()
{
if (_disposed)
return;
try
{
WaitForIdle();
}
finally
{
_disposed = true;
ReleaseResources();
_renderContext.Dispose();
_fence.Dispose();
_d3dContext.Dispose();
_d3dDevice.Dispose();
if (_d3d12Fence != 0)
{
Marshal.Release(_d3d12Fence);
_d3d12Fence = 0;
}
}
}
[DllImport("kernel32.dll", SetLastError = true)]
[return: MarshalAs(UnmanagedType.Bool)]
private static extern bool CloseHandle(nint handle);
}
[ComputeInteropResourceSet]
internal sealed partial class CausticTransportResourceSet
{
[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;
}
+348 -76
ファイルの表示
@@ -1,4 +1,5 @@
using ComputeSharp;
// Stryker disable all
using ComputeWeave;
namespace CausticTransport;
@@ -70,6 +71,7 @@ internal readonly partial struct InitializeDisplacementShader(
internal readonly partial struct GridDepositShader(
ReadWriteTexture2D<Bgra32, Float4> source,
ReadWriteBuffer<float> density,
ReadWriteBuffer<int> sourceHash,
int width,
int height,
int gridWidth,
@@ -77,33 +79,57 @@ internal readonly partial struct GridDepositShader(
{
private readonly ReadWriteTexture2D<Bgra32, Float4> source = source;
private readonly ReadWriteBuffer<float> density = density;
private readonly ReadWriteBuffer<int> sourceHash = sourceHash;
private readonly int width = width;
private readonly int height = height;
private readonly int gridWidth = gridWidth;
private readonly int gridHeight = gridHeight;
[GroupShared(2)]
private static readonly int[] groupHash = null!;
public void Execute()
{
if (GroupIds.Index == 0)
{
groupHash[0] = 0;
groupHash[1] = 0;
}
Hlsl.GroupMemoryBarrierWithGroupSync();
var gx = ThreadIds.X;
var gy = ThreadIds.Y;
if (gx >= gridWidth || gy >= gridHeight)
return;
var x0 = gx * width / gridWidth;
var x1 = (gx + 1) * width / gridWidth;
var y0 = gy * height / gridHeight;
var y1 = (gy + 1) * height / gridHeight;
var sum = 0f;
for (var y = y0; y < y1; y++)
if (gx < gridWidth && gy < gridHeight)
{
for (var x = x0; x < x1; x++)
var x0 = gx * width / gridWidth;
var x1 = (gx + 1) * width / gridWidth;
var y0 = gy * height / gridHeight;
var y1 = (gy + 1) * height / gridHeight;
var sum = 0f;
var hashSum = 0u;
var hashMix = 0u;
for (var y = y0; y < y1; y++)
{
var pixel = source[new Int2(x, y)];
sum += 0.2126f * pixel.X + 0.7152f * pixel.Y + 0.0722f * pixel.Z + 0.01f * pixel.W;
for (var x = x0; x < x1; x++)
{
var pixel = source[new Int2(x, y)];
sum += 0.2126f * pixel.X + 0.7152f * pixel.Y + 0.0722f * pixel.Z + 0.01f * pixel.W;
var mixed = CausticTransportShaderMath.MixTexel((uint)(y * width + x), pixel);
hashSum += mixed;
hashMix ^= mixed * 0xC2B2AE35u;
}
}
density[gy * gridWidth + gx] = sum;
Hlsl.InterlockedAdd(ref groupHash[0], (int)hashSum);
Hlsl.InterlockedXor(ref groupHash[1], (int)hashMix);
}
density[gy * gridWidth + gx] = sum;
Hlsl.GroupMemoryBarrierWithGroupSync();
if (GroupIds.Index != 0)
return;
Hlsl.InterlockedAdd(ref sourceHash[0], groupHash[0]);
Hlsl.InterlockedXor(ref sourceHash[1], groupHash[1]);
}
}
@@ -365,6 +391,98 @@ internal readonly partial struct JacobiShader(
}
}
[ThreadGroupSize(CausticTransportSettings.JacobiTileSize, CausticTransportSettings.JacobiTileSize, 1)]
[GeneratedComputeShaderDescriptor]
internal readonly partial struct JacobiBlockShader(
ReadWriteBuffer<float> phiIn,
ReadWriteBuffer<float> residual,
ReadWriteBuffer<float> phiOut,
int gridWidth,
int gridHeight,
int steps) : IComputeShader
{
private readonly ReadWriteBuffer<float> phiIn = phiIn;
private readonly ReadWriteBuffer<float> residual = residual;
private readonly ReadWriteBuffer<float> phiOut = phiOut;
private readonly int gridWidth = gridWidth;
private readonly int gridHeight = gridHeight;
private readonly int steps = steps;
[GroupShared(CausticTransportSettings.JacobiBlockLength)]
private static readonly float[] phiA = null!;
[GroupShared(CausticTransportSettings.JacobiBlockLength)]
private static readonly float[] phiB = null!;
[GroupShared(CausticTransportSettings.JacobiBlockLength)]
private static readonly float[] residualTile = null!;
public void Execute()
{
var threadIndex = GroupIds.Index;
var threadCount = GroupSize.Count;
var span = CausticTransportSettings.JacobiTileSize + 2 * steps;
var regionX = ThreadIds.X - GroupIds.X - steps;
var regionY = ThreadIds.Y - GroupIds.Y - steps;
var regionLength = span * span;
for (var local = threadIndex; local < regionLength; local += threadCount)
{
var ly = local / span;
var lx = local - ly * span;
var gx = regionX + lx;
var gy = regionY + ly;
if (gx >= 0 && gx < gridWidth && gy >= 0 && gy < gridHeight)
{
phiA[local] = phiIn[gy * gridWidth + gx];
residualTile[local] = residual[gy * gridWidth + gx];
}
}
Hlsl.GroupMemoryBarrierWithGroupSync();
for (var step = 0; step < steps; step++)
{
for (var local = threadIndex; local < regionLength; local += threadCount)
{
var ly = local / span;
var lx = local - ly * span;
var gx = regionX + lx;
var gy = regionY + ly;
if (gx < 0 || gx >= gridWidth || gy < 0 || gy >= gridHeight)
continue;
if ((step & 1) == 0)
{
var center = phiA[local];
var left = gx > 0 && lx > 0 ? phiA[local - 1] : center;
var right = gx < gridWidth - 1 && lx < span - 1 ? phiA[local + 1] : center;
var up = gy > 0 && ly > 0 ? phiA[local - span] : center;
var down = gy < gridHeight - 1 && ly < span - 1 ? phiA[local + span] : center;
phiB[local] = (left + right + up + down - residualTile[local]) * 0.25f;
}
else
{
var center = phiB[local];
var left = gx > 0 && lx > 0 ? phiB[local - 1] : center;
var right = gx < gridWidth - 1 && lx < span - 1 ? phiB[local + 1] : center;
var up = gy > 0 && ly > 0 ? phiB[local - span] : center;
var down = gy < gridHeight - 1 && ly < span - 1 ? phiB[local + span] : center;
phiA[local] = (left + right + up + down - residualTile[local]) * 0.25f;
}
}
Hlsl.GroupMemoryBarrierWithGroupSync();
}
var x = ThreadIds.X;
var y = ThreadIds.Y;
if (x >= gridWidth || y >= gridHeight)
return;
var own = (GroupIds.Y + steps) * span + GroupIds.X + steps;
phiOut[y * gridWidth + x] = (steps & 1) == 0 ? phiA[own] : phiB[own];
}
}
[ThreadGroupSize(DefaultThreadGroupSizes.XY)]
[GeneratedComputeShaderDescriptor]
internal readonly partial struct ProlongShader(
@@ -404,6 +522,160 @@ internal readonly partial struct ProlongShader(
}
}
[ThreadGroupSize(CausticTransportSettings.CoarseSolveThreads, 1, 1)]
[GeneratedComputeShaderDescriptor]
internal readonly partial struct CoarseSolveShader(
ReadWriteBuffer<float> fineResidual,
ReadWriteBuffer<float> phi,
int fineWidth,
int fineHeight,
int levelWidth,
int levelHeight,
int levelCount,
int jacobiIterations,
int restrictFirst) : IComputeShader
{
private readonly ReadWriteBuffer<float> fineResidual = fineResidual;
private readonly ReadWriteBuffer<float> phi = phi;
private readonly int fineWidth = fineWidth;
private readonly int fineHeight = fineHeight;
private readonly int levelWidth = levelWidth;
private readonly int levelHeight = levelHeight;
private readonly int levelCount = levelCount;
private readonly int jacobiIterations = jacobiIterations;
private readonly int restrictFirst = restrictFirst;
[GroupShared(CausticTransportSettings.CoarseSolveCapacity)]
private static readonly float[] shared = null!;
public void Execute()
{
var thread = ThreadIds.X;
var levelLength = levelWidth * levelHeight;
for (var index = thread; index < levelLength; index += CausticTransportSettings.CoarseSolveThreads)
{
if (restrictFirst != 0)
{
var cy = index / levelWidth;
var cx = index - cy * levelWidth;
var fx0 = Hlsl.Min(cx * 2, fineWidth - 1);
var fx1 = Hlsl.Min(cx * 2 + 1, fineWidth - 1);
var fy0 = Hlsl.Min(cy * 2, fineHeight - 1);
var fy1 = Hlsl.Min(cy * 2 + 1, fineHeight - 1);
shared[index] =
fineResidual[fy0 * fineWidth + fx0] +
fineResidual[fy0 * fineWidth + fx1] +
fineResidual[fy1 * fineWidth + fx0] +
fineResidual[fy1 * fineWidth + fx1];
}
else
{
shared[index] = fineResidual[index];
}
}
Hlsl.GroupMemoryBarrierWithGroupSync();
var width = levelWidth;
var height = levelHeight;
var offset = 0;
for (var level = 1; level < levelCount; level++)
{
var coarseWidth = Hlsl.Max((width + 1) / 2, CausticTransportSettings.MinimumGridSize);
var coarseHeight = Hlsl.Max((height + 1) / 2, CausticTransportSettings.MinimumGridSize);
var coarseOffset = offset + width * height;
for (var index = thread; index < coarseWidth * coarseHeight; index += CausticTransportSettings.CoarseSolveThreads)
{
var cy = index / coarseWidth;
var cx = index - cy * coarseWidth;
var fx0 = Hlsl.Min(cx * 2, width - 1);
var fx1 = Hlsl.Min(cx * 2 + 1, width - 1);
var fy0 = Hlsl.Min(cy * 2, height - 1);
var fy1 = Hlsl.Min(cy * 2 + 1, height - 1);
shared[coarseOffset + index] =
shared[offset + fy0 * width + fx0] +
shared[offset + fy0 * width + fx1] +
shared[offset + fy1 * width + fx0] +
shared[offset + fy1 * width + fx1];
}
Hlsl.GroupMemoryBarrierWithGroupSync();
offset = coarseOffset;
width = coarseWidth;
height = coarseHeight;
}
var regionA = offset + width * height;
var regionB = regionA + levelLength;
for (var index = thread; index < width * height; index += CausticTransportSettings.CoarseSolveThreads)
shared[regionA + index] = 0f;
Hlsl.GroupMemoryBarrierWithGroupSync();
Relax(regionA, regionB, offset, width, height, thread);
for (var level = levelCount - 2; level >= 0; level--)
{
var fineLevelWidth = levelWidth;
var fineLevelHeight = levelHeight;
var fineOffset = 0;
for (var step = 0; step < level; step++)
{
fineOffset += fineLevelWidth * fineLevelHeight;
fineLevelWidth = Hlsl.Max((fineLevelWidth + 1) / 2, CausticTransportSettings.MinimumGridSize);
fineLevelHeight = Hlsl.Max((fineLevelHeight + 1) / 2, CausticTransportSettings.MinimumGridSize);
}
for (var index = thread; index < fineLevelWidth * fineLevelHeight; index += CausticTransportSettings.CoarseSolveThreads)
{
var fy = index / fineLevelWidth;
var fx = index - fy * fineLevelWidth;
var px = Hlsl.Clamp((fx + 0.5f) * width / fineLevelWidth - 0.5f, 0f, width - 1f);
var py = Hlsl.Clamp((fy + 0.5f) * height / fineLevelHeight - 0.5f, 0f, height - 1f);
var ix0 = (int)px;
var iy0 = (int)py;
var wx = px - ix0;
var wy = py - iy0;
var ix1 = Hlsl.Min(ix0 + 1, width - 1);
var iy1 = Hlsl.Min(iy0 + 1, height - 1);
var top = Hlsl.Lerp(shared[regionA + iy0 * width + ix0], shared[regionA + iy0 * width + ix1], wx);
var bottom = Hlsl.Lerp(shared[regionA + iy1 * width + ix0], shared[regionA + iy1 * width + ix1], wx);
shared[regionB + index] = Hlsl.Lerp(top, bottom, wy);
}
Hlsl.GroupMemoryBarrierWithGroupSync();
var swapped = regionA;
regionA = regionB;
regionB = swapped;
width = fineLevelWidth;
height = fineLevelHeight;
offset = fineOffset;
Relax(regionA, regionB, offset, width, height, thread);
}
for (var index = thread; index < levelLength; index += CausticTransportSettings.CoarseSolveThreads)
phi[index] = shared[regionA + index];
}
private void Relax(int regionA, int regionB, int residualOffset, int width, int height, int thread)
{
for (var step = 0; step < jacobiIterations; step++)
{
var reading = (step & 1) == 0 ? regionA : regionB;
var writing = (step & 1) == 0 ? regionB : regionA;
for (var index = thread; index < width * height; index += CausticTransportSettings.CoarseSolveThreads)
{
var gy = index / width;
var gx = index - gy * width;
var center = shared[reading + index];
var left = gx > 0 ? shared[reading + index - 1] : center;
var right = gx < width - 1 ? shared[reading + index + 1] : center;
var up = gy > 0 ? shared[reading + index - width] : center;
var down = gy < height - 1 ? shared[reading + index + width] : center;
shared[writing + index] = (left + right + up + down - shared[residualOffset + index]) * 0.25f;
}
Hlsl.GroupMemoryBarrierWithGroupSync();
}
}
}
[ThreadGroupSize(DefaultThreadGroupSizes.XY)]
[GeneratedComputeShaderDescriptor]
internal readonly partial struct UpdateDisplacementShader(
@@ -499,8 +771,8 @@ internal readonly partial struct SplatShader(
[GroupShared(CausticTransportSettings.SplatTileLength)]
private static readonly uint[] tile = null!;
[GroupShared(4)]
private static readonly int[] extent = null!;
[GroupShared(3)]
private static readonly int[] anchor = null!;
public void Execute()
{
@@ -512,6 +784,12 @@ internal readonly partial struct SplatShader(
var active = x < width && y < height &&
(pixel.X > 0f || pixel.Y > 0f || pixel.Z > 0f || pixel.W > 0f);
if (threadIndex == 0)
anchor[2] = 0;
Hlsl.GroupMemoryBarrierWithGroupSync();
if (active)
Hlsl.InterlockedOr(ref anchor[2], 1);
var transport = new Float2(0f, 0f);
if (active)
transport = SampleDisplacement(x, y);
@@ -554,51 +832,26 @@ internal readonly partial struct SplatShader(
if (threadIndex == 0)
{
extent[0] = width;
extent[1] = height;
extent[2] = -1;
extent[3] = -1;
}
Hlsl.GroupMemoryBarrierWithGroupSync();
if (active)
{
Hlsl.InterlockedMin(ref extent[0], ix0);
Hlsl.InterlockedMin(ref extent[1], iy0);
Hlsl.InterlockedMax(ref extent[2], ix1);
Hlsl.InterlockedMax(ref extent[3], iy1);
anchor[0] = ix0 - CausticTransportSettings.SplatTileMargin;
anchor[1] = iy0 - CausticTransportSettings.SplatTileMargin;
}
ClearTile(threadIndex, threadCount);
Hlsl.GroupMemoryBarrierWithGroupSync();
if (anchor[2] == 0)
return;
var originX = extent[0];
var originY = extent[1];
var spanX = extent[2] - originX + 1;
var spanY = extent[3] - originY + 1;
var useTile = spanX >= 1 &&
spanX <= CausticTransportSettings.SplatTileSize &&
spanY <= CausticTransportSettings.SplatTileSize;
if (useTile)
ClearTile(spanX, spanY, threadIndex, threadCount);
Hlsl.GroupMemoryBarrierWithGroupSync();
var originX = anchor[0];
var originY = anchor[1];
if (active)
{
if (useTile)
{
AddTileTap(TileOffset(ix0 - originX, iy0 - originY), contribution, (1f - wx) * (1f - wy));
AddTileTap(TileOffset(ix1 - originX, iy0 - originY), contribution, wx * (1f - wy));
AddTileTap(TileOffset(ix0 - originX, iy1 - originY), contribution, (1f - wx) * wy);
AddTileTap(TileOffset(ix1 - originX, iy1 - originY), contribution, wx * wy);
}
else
{
AddGlobalTap((iy0 * width + ix0) * 4, contribution, (1f - wx) * (1f - wy));
AddGlobalTap((iy0 * width + ix1) * 4, contribution, wx * (1f - wy));
AddGlobalTap((iy1 * width + ix0) * 4, contribution, (1f - wx) * wy);
AddGlobalTap((iy1 * width + ix1) * 4, contribution, wx * wy);
}
AddTap(ix0, iy0, originX, originY, contribution, (1f - wx) * (1f - wy));
AddTap(ix1, iy0, originX, originY, contribution, wx * (1f - wy));
AddTap(ix0, iy1, originX, originY, contribution, (1f - wx) * wy);
AddTap(ix1, iy1, originX, originY, contribution, wx * wy);
}
Hlsl.GroupMemoryBarrierWithGroupSync();
if (useTile)
FlushTile(originX, originY, spanX, spanY, threadIndex, threadCount);
FlushTile(originX, originY, threadIndex, threadCount);
Hlsl.GroupMemoryBarrierWithGroupSync();
}
}
@@ -635,33 +888,34 @@ internal readonly partial struct SplatShader(
private int TileOffset(int tileX, int tileY)
=> (tileY * CausticTransportSettings.SplatTileSize + tileX) * 4;
private void ClearTile(int spanX, int spanY, int threadIndex, int threadCount)
private void ClearTile(int threadIndex, int threadCount)
{
var cellCount = spanX * spanY * 4;
for (var index = threadIndex; index < cellCount; index += threadCount)
for (var index = threadIndex; index < CausticTransportSettings.SplatTileLength; index += threadCount)
tile[index] = 0;
}
private void FlushTile(int originX, int originY, int threadIndex, int threadCount)
{
for (var index = threadIndex; index < CausticTransportSettings.SplatTileLength; index += threadCount)
{
var cell = index / 4;
var channel = index - cell * 4;
var tileY = cell / spanX;
var tileX = cell - tileY * spanX;
tile[TileOffset(tileX, tileY) + channel] = 0;
var amount = tile[index];
if (amount == 0)
continue;
var cell = index >> 2;
var tileY = cell / CausticTransportSettings.SplatTileSize;
var tileX = cell - tileY * CausticTransportSettings.SplatTileSize;
Hlsl.InterlockedAdd(ref accumulator[((originY + tileY) * width + originX + tileX) * 4 + (index & 3)], amount);
}
}
private void FlushTile(int originX, int originY, int spanX, int spanY, int threadIndex, int threadCount)
private void AddTap(int cellX, int cellY, int originX, int originY, Float4 value, float weight)
{
var cellCount = spanX * spanY * 4;
for (var index = threadIndex; index < cellCount; index += threadCount)
{
var cell = index / 4;
var channel = index - cell * 4;
var tileY = cell / spanX;
var tileX = cell - tileY * spanX;
var amount = tile[TileOffset(tileX, tileY) + channel];
if (amount == 0)
continue;
Hlsl.InterlockedAdd(ref accumulator[((originY + tileY) * width + originX + tileX) * 4 + channel], amount);
}
var tileX = cellX - originX;
var tileY = cellY - originY;
if (tileX >= 0 && tileX < CausticTransportSettings.SplatTileSize && tileY >= 0 && tileY < CausticTransportSettings.SplatTileSize)
AddTileTap(TileOffset(tileX, tileY), value, weight);
else
AddGlobalTap((cellY * width + cellX) * 4, value, weight);
}
private void AddTileTap(int index4, Float4 value, float weight)
@@ -743,3 +997,21 @@ internal readonly partial struct ResolveShader(
output[ThreadIds.XY] = new Float4(red, green, blue, outAlpha);
}
}
internal static class CausticTransportShaderMath
{
public static uint MixTexel(uint index, Float4 texel)
{
var packed = (uint)(texel.X * 255f + 0.5f)
| ((uint)(texel.Y * 255f + 0.5f) << 8)
| ((uint)(texel.Z * 255f + 0.5f) << 16)
| ((uint)(texel.W * 255f + 0.5f) << 24);
var mixed = index * 0x9E3779B9u ^ packed;
mixed ^= mixed >> 16;
mixed *= 0x85EBCA6Bu;
mixed ^= mixed >> 13;
mixed *= 0xC2B2AE35u;
mixed ^= mixed >> 16;
return mixed;
}
}
+196 -202
ファイルの表示
@@ -1,35 +1,36 @@
using System.ComponentModel;
using System.Runtime.InteropServices;
using ComputeSharp;
using ComputeWeave;
namespace CausticTransport;
internal sealed class CausticTransportPipeline : IDisposable
{
private readonly GraphicsDevice _device;
private ReadWriteBuffer<float>? _density;
private ReadWriteBuffer<float>? _sigma;
private ReadWriteBuffer<int>? _warpedFixed;
private ReadWriteBuffer<Float2>? _displacement;
private ReadWriteBuffer<Float2>? _rowSums;
private ReadWriteBuffer<Float2>? _scales;
private ReadWriteBuffer<float>[] _residuals = [];
private ReadWriteBuffer<float>[] _phiA = [];
private ReadWriteBuffer<float>[] _phiB = [];
private (int Width, int Height)[] _levelSizes = [];
private readonly CausticTransportPipelineHost _host;
private readonly ReadWriteBuffer<int> _syncBuffer;
private readonly ReadWriteBuffer<int> _sourceHash;
private readonly ReadBackBuffer<int> _sourceHashReadBack;
private TransportKey? _transportKey;
private ComputeSubmission _pendingSourceHash;
private bool _hasPendingSourceHash;
private ContentHash? _lastSourceHash;
private bool _sourceChanging;
private int _gridWidth;
private int _gridHeight;
private ReadWriteBuffer<uint>? _accumulator;
private int _accumulatorCapacity;
private ReadWriteTexture2D<Bgra32, Float4>? _packedSource;
private ReadWriteTexture2D<Bgra32, Float4>? _packedOutput;
private int _packedWidth;
private int _packedHeight;
private readonly ReadWriteBuffer<int> _syncBuffer;
private CausticTransportPipeline(GraphicsDevice device)
private CausticTransportPipeline(GraphicsDevice device, CausticTransportPipelineHost host)
{
_device = device;
_host = host;
_syncBuffer = device.AllocateReadWriteBuffer<int>(1);
_sourceHash = device.AllocateReadWriteBuffer<int>(CausticTransportSettings.SourceHashLength);
_sourceHashReadBack = device.AllocateReadBackBuffer<int>(CausticTransportSettings.SourceHashLength);
}
internal void WaitForCompletion() => SynchronizeDevice();
@@ -44,7 +45,7 @@ internal sealed class CausticTransportPipeline : IDisposable
{
try
{
return new CausticTransportPipeline(GraphicsDevice.GetDefault());
return TryCreate(GraphicsDevice.GetDefault());
}
catch
{
@@ -54,14 +55,23 @@ internal sealed class CausticTransportPipeline : IDisposable
public static CausticTransportPipeline? TryCreate(GraphicsDevice device)
{
CausticTransportPipelineHost? host = null;
try
{
return new CausticTransportPipeline(device);
host = CausticTransportPipelineHost.Create(device, CausticTransportSettings.MaximumPendingSubmissions);
var pipeline = new CausticTransportPipeline(device, host);
host = null;
return pipeline;
}
catch
catch (Win32Exception)
{
return null;
}
finally
{
host?.Dispose();
host?.WaitForDisposal();
}
}
public void Process(ReadOnlySpan<int> source, Span<int> destination, int width, int height, in Parameters parameters)
@@ -72,8 +82,7 @@ internal sealed class CausticTransportPipeline : IDisposable
var sourceTexture = _packedSource!;
var outputTexture = _packedOutput!;
sourceTexture.CopyFrom(MemoryMarshal.Cast<int, Bgra32>(source[..pixelCount]));
using (ComputeContext context = _device.CreateComputeContext())
RecordPipeline(in context, sourceTexture, outputTexture, width, height, in parameters);
SubmitFullPipeline(sourceTexture, outputTexture, width, height, in parameters).Wait();
outputTexture.CopyTo(MemoryMarshal.Cast<int, Bgra32>(destination[..pixelCount]));
}
@@ -85,9 +94,7 @@ internal sealed class CausticTransportPipeline : IDisposable
in Parameters parameters)
{
EnsureResources(width, height, parameters.Quality);
using ComputeContext context = _device.CreateComputeContext();
RecordPipeline(in context, source, destination, width, height, in parameters);
context.Submit();
_ = SubmitFullPipeline(source, destination, width, height, in parameters);
}
internal void ProcessSharedAndWait(
@@ -98,170 +105,166 @@ internal sealed class CausticTransportPipeline : IDisposable
in Parameters parameters)
{
EnsureResources(width, height, parameters.Quality);
using ComputeContext context = _device.CreateComputeContext();
RecordPipeline(in context, source, destination, width, height, in parameters);
SubmitFullPipeline(source, destination, width, height, in parameters).Wait();
}
private void RecordPipeline(
in ComputeContext context,
public void Process(
ComputeResourceBinding<ReadWriteTexture2D<Bgra32, Float4>> source,
ComputeResourceBinding<ReadWriteTexture2D<Bgra32, Float4>> destination,
int width,
int height,
in Parameters parameters)
{
_ = Simulate(source, width, height, in parameters);
Render(source, destination, width, height, in parameters);
}
internal bool Simulate(
ComputeResourceBinding<ReadWriteTexture2D<Bgra32, Float4>> source,
int width,
int height,
in Parameters parameters)
{
EnsureResources(width, height, parameters.Quality);
var derived = Derive(width, height, in parameters);
ResolvePendingSourceHash();
var deposited = _host.RecordSharedDeposit(source, _sourceHash, width, height, in derived);
var transportParameters = new TransportParameters(
width,
height,
parameters.Quality,
parameters.Shape,
parameters.Shape == (int)CausticLightShape.Plane ? 0f : parameters.Aperture);
ContentHash? sourceHash = null;
if (!_sourceChanging && _transportKey is { Source: not null } current && current.Parameters == transportParameters)
{
deposited.Wait();
sourceHash = ReadSourceHash();
if (current.Source == sourceHash)
return false;
}
else
{
_pendingSourceHash = deposited;
_hasPendingSourceHash = true;
}
_ = _host.RecordTransport(in derived, in parameters);
_transportKey = new TransportKey(transportParameters, sourceHash);
return true;
}
private void ResolvePendingSourceHash()
{
if (!_hasPendingSourceHash)
return;
_hasPendingSourceHash = false;
_pendingSourceHash.Wait();
var sourceHash = ReadSourceHash();
if (_transportKey is { Source: null } key)
_transportKey = key with { Source = sourceHash };
}
private ContentHash ReadSourceHash()
{
_sourceHashReadBack.CopyFrom(_sourceHash);
var hashed = _sourceHashReadBack.Span;
var sourceHash = new ContentHash(hashed[CausticTransportSettings.SourceHashSum], hashed[CausticTransportSettings.SourceHashMix]);
_sourceChanging = _lastSourceHash is { } last && last != sourceHash;
_lastSourceHash = sourceHash;
return sourceHash;
}
internal void Render(
ComputeResourceBinding<ReadWriteTexture2D<Bgra32, Float4>> source,
ComputeResourceBinding<ReadWriteTexture2D<Bgra32, Float4>> output,
int width,
int height,
in Parameters parameters)
{
var derived = Derive(width, height, in parameters);
_ = _host.RecordSharedSplat(source, output, width, height, in derived, in parameters);
}
private ComputeSubmission SubmitFullPipeline(
ReadWriteTexture2D<Bgra32, Float4> source,
ReadWriteTexture2D<Bgra32, Float4> output,
int width,
int height,
in Parameters parameters)
{
_transportKey = null;
_hasPendingSourceHash = false;
_lastSourceHash = null;
_sourceChanging = false;
var derived = Derive(width, height, in parameters);
return _host.RecordFullPipeline(source, output, _sourceHash, width, height, in derived, in parameters);
}
private DerivedValues Derive(int width, int height, in Parameters parameters)
{
var settings = CausticTransportSettings.GetQuality(parameters.Quality);
var gridWidth = _gridWidth;
var gridHeight = _gridHeight;
var gridLength = gridWidth * gridHeight;
var pixelCount = width * height;
var colorScale = CausticTransportSettings.GetColorFixedScale(pixelCount);
var levelCount = _levelSizes.Length;
var density = _density!;
var sigma = _sigma!;
var warpedFixed = _warpedFixed!;
var displacement = _displacement!;
var rowSums = _rowSums!;
var scales = _scales!;
var accumulator = _accumulator!;
context.For(gridWidth, gridHeight, new GridDepositShader(source, density, width, height, gridWidth, gridHeight));
context.For(gridWidth, gridHeight, new LightShapeShader(sigma, gridWidth, gridHeight, parameters.Shape, parameters.Aperture));
context.Barrier(density);
context.Barrier(sigma);
context.For(gridHeight, new GridRowSumShader(density, sigma, rowSums, gridWidth, gridHeight));
context.Barrier(rowSums);
context.For(1, new NormalizeScaleShader(rowSums, scales, gridHeight, gridLength));
context.Barrier(scales);
context.For(gridWidth, gridHeight, new InitializeDisplacementShader(displacement, gridWidth, gridHeight, parameters.Shape, parameters.Aperture));
context.Clear(warpedFixed);
context.Barrier(displacement);
context.Barrier(warpedFixed);
var coarsest = levelCount - 1;
for (var iteration = 0; iteration < settings.TransportIterations; iteration++)
{
context.For(gridWidth, gridHeight, new PushforwardShader(density, scales, displacement, warpedFixed, gridWidth, gridHeight, CausticTransportSettings.GridFixedScale));
context.Barrier(warpedFixed);
context.For(gridWidth, gridHeight, new ResidualShader(warpedFixed, sigma, scales, _residuals[0], gridWidth, gridHeight, 1f / CausticTransportSettings.GridFixedScale));
context.Barrier(_residuals[0]);
context.Barrier(warpedFixed);
for (var level = 1; level < levelCount; level++)
{
var (fineWidth, fineHeight) = _levelSizes[level - 1];
var (coarseWidth, coarseHeight) = _levelSizes[level];
context.For(coarseWidth, coarseHeight, new RestrictShader(_residuals[level - 1], _residuals[level], fineWidth, fineHeight, coarseWidth, coarseHeight));
context.Barrier(_residuals[level]);
}
context.Clear(_phiA[coarsest]);
context.Barrier(_phiA[coarsest]);
for (var level = coarsest; level >= 0; level--)
{
var (levelWidth, levelHeight) = _levelSizes[level];
if (level != coarsest)
{
var (belowWidth, belowHeight) = _levelSizes[level + 1];
context.For(levelWidth, levelHeight, new ProlongShader(_phiA[level + 1], _phiA[level], belowWidth, belowHeight, levelWidth, levelHeight));
context.Barrier(_phiA[level]);
}
for (var step = 0; step < settings.JacobiIterations; step++)
{
var reading = (step & 1) == 0 ? _phiA[level] : _phiB[level];
var writing = (step & 1) == 0 ? _phiB[level] : _phiA[level];
context.For(levelWidth, levelHeight, new JacobiShader(reading, _residuals[level], writing, levelWidth, levelHeight));
context.Barrier(writing);
}
}
context.For(gridWidth, gridHeight, new UpdateDisplacementShader(_phiA[0], displacement, gridWidth, gridHeight, CausticTransportSettings.DisplacementRelaxation, CausticTransportSettings.DisplacementStepLimit));
context.Barrier(displacement);
}
context.Clear(accumulator);
context.Barrier(accumulator);
var movement = 1f - parameters.Focus;
var jitterAmplitude = parameters.Roughness * CausticTransportSettings.JitterCellAmplitude;
context.For(
CausticTransportSettings.GetSplatDispatchSize(width),
CausticTransportSettings.GetSplatDispatchSize(height),
new SplatShader(
source,
displacement,
accumulator,
width,
height,
gridWidth,
gridHeight,
movement,
parameters.Dispersion,
jitterAmplitude,
parameters.Seed,
colorScale));
context.Barrier(accumulator);
context.For(width, height, new ResolveShader(accumulator, output, width, height, 1f / colorScale));
return new DerivedValues(
_gridWidth,
_gridHeight,
CausticTransportSettings.GetLevelCount(_gridWidth, _gridHeight),
settings.TransportIterations,
settings.JacobiIterations,
CausticTransportSettings.GetColorFixedScale(checked(width * height)));
}
private void EnsureResources(int width, int height, CausticTransportQuality quality)
{
var settings = CausticTransportSettings.GetQuality(quality);
var (gridWidth, gridHeight) = CausticTransportSettings.GetGridSize(width, height, settings.GridResolution);
EnsureGrid(gridWidth, gridHeight);
EnsureAccumulator(checked(width * height));
}
private void EnsureGrid(int gridWidth, int gridHeight)
{
if (_gridWidth == gridWidth && _gridHeight == gridHeight)
return;
DisposeGridBuffers();
var pixelCount = checked(width * height);
var accumulatorCapacity = Math.Max(_accumulatorCapacity, pixelCount);
var gridLength = gridWidth * gridHeight;
var levelCount = CausticTransportSettings.GetLevelCount(gridWidth, gridHeight);
var levelSizes = new (int Width, int Height)[levelCount];
var residuals = new ReadWriteBuffer<float>[levelCount];
var phiA = new ReadWriteBuffer<float>[levelCount];
var phiB = new ReadWriteBuffer<float>[levelCount];
var (levelWidth, levelHeight) = (gridWidth, gridHeight);
if (levelCount > CausticTransportSettings.MaximumLevelCount)
throw new InvalidOperationException();
Span<int> levelLengths = stackalloc int[CausticTransportSettings.MaximumLevelCount];
levelLengths.Fill(1);
for (var level = 0; level < levelCount; level++)
{
levelSizes[level] = (levelWidth, levelHeight);
var levelLength = levelWidth * levelHeight;
residuals[level] = _device.AllocateReadWriteBuffer<float>(levelLength);
phiA[level] = _device.AllocateReadWriteBuffer<float>(levelLength);
phiB[level] = _device.AllocateReadWriteBuffer<float>(levelLength);
(levelWidth, levelHeight) = CausticTransportSettings.GetCoarserLevelSize(levelWidth, levelHeight);
var (levelWidth, levelHeight) = CausticTransportSettings.GetLevelSize(gridWidth, gridHeight, level);
levelLengths[level] = levelWidth * levelHeight;
}
_density = _device.AllocateReadWriteBuffer<float>(gridLength);
_sigma = _device.AllocateReadWriteBuffer<float>(gridLength);
_warpedFixed = _device.AllocateReadWriteBuffer<int>(gridLength);
_displacement = _device.AllocateReadWriteBuffer<Float2>(gridLength);
_rowSums = _device.AllocateReadWriteBuffer<Float2>(gridHeight);
_scales ??= _device.AllocateReadWriteBuffer<Float2>(1);
_residuals = residuals;
_phiA = phiA;
_phiB = phiB;
_levelSizes = levelSizes;
if (!_host.TryEnsureGrid(
new CausticTransportGridResources.Plan(
accumulatorLength: checked(accumulatorCapacity * 4),
densityLength: gridLength,
displacementLength: gridLength,
phiA0Length: levelLengths[0],
phiA1Length: levelLengths[1],
phiA2Length: levelLengths[2],
phiA3Length: levelLengths[3],
phiA4Length: levelLengths[4],
phiB0Length: levelLengths[0],
phiB1Length: levelLengths[1],
phiB2Length: levelLengths[2],
phiB3Length: levelLengths[3],
phiB4Length: levelLengths[4],
residual0Length: levelLengths[0],
residual1Length: levelLengths[1],
residual2Length: levelLengths[2],
residual3Length: levelLengths[3],
residual4Length: levelLengths[4],
rowSumsLength: gridHeight,
scalesLength: 1,
sigmaLength: gridLength,
warpedFixedLength: gridLength),
out var changed))
throw new InvalidOperationException();
if (changed)
_transportKey = null;
_gridWidth = gridWidth;
_gridHeight = gridHeight;
}
private void EnsureAccumulator(int pixelCount)
{
if (_accumulatorCapacity >= pixelCount)
return;
if (_accumulator is not null)
{
SynchronizeDevice();
_accumulator.Dispose();
}
_accumulator = _device.AllocateReadWriteBuffer<uint>(pixelCount * 4);
_accumulatorCapacity = pixelCount;
_accumulatorCapacity = accumulatorCapacity;
}
private void EnsurePackedTextures(int width, int height)
@@ -269,53 +272,21 @@ internal sealed class CausticTransportPipeline : IDisposable
if (_packedWidth == width && _packedHeight == height)
return;
if (_packedSource is not null)
{
SynchronizeDevice();
_packedSource.Dispose();
_packedOutput?.Dispose();
}
_packedSource?.Dispose();
_packedOutput?.Dispose();
_packedSource = _device.AllocateReadWriteTexture2D<Bgra32, Float4>(width, height);
_packedOutput = _device.AllocateReadWriteTexture2D<Bgra32, Float4>(width, height);
_packedWidth = width;
_packedHeight = height;
}
private void DisposeGridBuffers()
{
if (_gridWidth != 0)
SynchronizeDevice();
foreach (var buffer in _residuals)
buffer.Dispose();
foreach (var buffer in _phiA)
buffer.Dispose();
foreach (var buffer in _phiB)
buffer.Dispose();
_residuals = [];
_phiA = [];
_phiB = [];
_levelSizes = [];
_density?.Dispose();
_sigma?.Dispose();
_warpedFixed?.Dispose();
_displacement?.Dispose();
_rowSums?.Dispose();
_density = null;
_sigma = null;
_warpedFixed = null;
_displacement = null;
_rowSums = null;
_gridWidth = 0;
_gridHeight = 0;
}
public void Dispose()
{
DisposeGridBuffers();
_scales?.Dispose();
_scales = null;
_accumulator?.Dispose();
_accumulator = null;
_host.Dispose();
_host.WaitForDisposal();
_transportKey = null;
_gridWidth = 0;
_gridHeight = 0;
_accumulatorCapacity = 0;
_packedSource?.Dispose();
_packedOutput?.Dispose();
@@ -324,8 +295,31 @@ internal sealed class CausticTransportPipeline : IDisposable
_packedWidth = 0;
_packedHeight = 0;
_syncBuffer.Dispose();
_sourceHash.Dispose();
_sourceHashReadBack.Dispose();
}
internal readonly record struct ContentHash(int Sum, int Mix);
private readonly record struct TransportParameters(
int Width,
int Height,
CausticTransportQuality Quality,
int Shape,
float Aperture);
private readonly record struct TransportKey(
TransportParameters Parameters,
ContentHash? Source);
internal readonly record struct DerivedValues(
int GridWidth,
int GridHeight,
int LevelCount,
int TransportIterations,
int JacobiIterations,
int ColorScale);
internal readonly record struct Parameters(
int Shape,
CausticTransportQuality Quality,
+331
ファイルの表示
@@ -0,0 +1,331 @@
using ComputeWeave;
namespace CausticTransport;
[ComputeResourceGroup]
internal sealed partial class CausticTransportGridResources
{
[ComputePipelineResource(ComputeResourceAccess.ReadWrite)]
internal ReadWriteBuffer<float> Density { get; }
[ComputePipelineResource(ComputeResourceAccess.ReadWrite)]
internal ReadWriteBuffer<float> Sigma { get; }
[ComputePipelineResource(ComputeResourceAccess.ReadWrite)]
internal ReadWriteBuffer<int> WarpedFixed { get; }
[ComputePipelineResource(ComputeResourceAccess.ReadWrite)]
internal ReadWriteBuffer<Float2> Displacement { get; }
[ComputePipelineResource(ComputeResourceAccess.ReadWrite)]
internal ReadWriteBuffer<Float2> RowSums { get; }
[ComputePipelineResource(ComputeResourceAccess.ReadWrite)]
internal ReadWriteBuffer<Float2> Scales { get; }
[ComputePipelineResource(ComputeResourceAccess.ReadWrite)]
internal ReadWriteBuffer<uint> Accumulator { get; }
[ComputePipelineResource(ComputeResourceAccess.ReadWrite)]
internal ReadWriteBuffer<float> Residual0 { get; }
[ComputePipelineResource(ComputeResourceAccess.ReadWrite)]
internal ReadWriteBuffer<float> Residual1 { get; }
[ComputePipelineResource(ComputeResourceAccess.ReadWrite)]
internal ReadWriteBuffer<float> Residual2 { get; }
[ComputePipelineResource(ComputeResourceAccess.ReadWrite)]
internal ReadWriteBuffer<float> Residual3 { get; }
[ComputePipelineResource(ComputeResourceAccess.ReadWrite)]
internal ReadWriteBuffer<float> Residual4 { get; }
[ComputePipelineResource(ComputeResourceAccess.ReadWrite)]
internal ReadWriteBuffer<float> PhiA0 { get; }
[ComputePipelineResource(ComputeResourceAccess.ReadWrite)]
internal ReadWriteBuffer<float> PhiA1 { get; }
[ComputePipelineResource(ComputeResourceAccess.ReadWrite)]
internal ReadWriteBuffer<float> PhiA2 { get; }
[ComputePipelineResource(ComputeResourceAccess.ReadWrite)]
internal ReadWriteBuffer<float> PhiA3 { get; }
[ComputePipelineResource(ComputeResourceAccess.ReadWrite)]
internal ReadWriteBuffer<float> PhiA4 { get; }
[ComputePipelineResource(ComputeResourceAccess.ReadWrite)]
internal ReadWriteBuffer<float> PhiB0 { get; }
[ComputePipelineResource(ComputeResourceAccess.ReadWrite)]
internal ReadWriteBuffer<float> PhiB1 { get; }
[ComputePipelineResource(ComputeResourceAccess.ReadWrite)]
internal ReadWriteBuffer<float> PhiB2 { get; }
[ComputePipelineResource(ComputeResourceAccess.ReadWrite)]
internal ReadWriteBuffer<float> PhiB3 { get; }
[ComputePipelineResource(ComputeResourceAccess.ReadWrite)]
internal ReadWriteBuffer<float> PhiB4 { get; }
internal ReadWriteBuffer<float> GetResidual(int level) => level switch
{
0 => Residual0,
1 => Residual1,
2 => Residual2,
3 => Residual3,
4 => Residual4,
_ => throw new ArgumentOutOfRangeException(nameof(level)),
};
internal ReadWriteBuffer<float> GetPhiA(int level) => level switch
{
0 => PhiA0,
1 => PhiA1,
2 => PhiA2,
3 => PhiA3,
4 => PhiA4,
_ => throw new ArgumentOutOfRangeException(nameof(level)),
};
internal ReadWriteBuffer<float> GetPhiB(int level) => level switch
{
0 => PhiB0,
1 => PhiB1,
2 => PhiB2,
3 => PhiB3,
4 => PhiB4,
_ => throw new ArgumentOutOfRangeException(nameof(level)),
};
}
[ComputePipelineHost("_device", 1)]
internal sealed partial class CausticTransportPipelineHost
{
private readonly GraphicsDevice _device;
[ComputePipelineResource(ComputeResourceAccess.ReadWrite, ComputeResourceRecovery.Recompute)]
private readonly ComputeResourceGroupSlot<CausticTransportGridResources> _grid = new();
[ComputePipeline]
private void RecordFullPipeline(
in ComputeContext context,
[ComputeOwnedResource(nameof(_grid))] CausticTransportGridResources grid,
[ComputeResource(ComputeResourceAccess.ReadWrite)] ReadWriteTexture2D<Bgra32, Float4> source,
[ComputeResource(ComputeResourceAccess.ReadWrite)] ReadWriteTexture2D<Bgra32, Float4> output,
[ComputeResource(ComputeResourceAccess.ReadWrite)] ReadWriteBuffer<int> sourceHash,
int width,
int height,
in CausticTransportPipeline.DerivedValues derived,
in CausticTransportPipeline.Parameters parameters)
{
_ = _device;
RecordDepositStage(in context, grid, source, sourceHash, width, height, in derived);
RecordTransportStage(in context, grid, in derived, in parameters);
RecordSplatStage(in context, grid, source, output, width, height, in derived, in parameters);
}
[ComputePipeline]
[ComputeInterop]
private void RecordSharedDeposit(
in ComputeContext context,
[ComputeOwnedResource(nameof(_grid))] CausticTransportGridResources grid,
[ComputeResource(ComputeResourceAccess.ReadWrite, Sharing = ComputeResourceSharing.External)] ReadWriteTexture2D<Bgra32, Float4> source,
[ComputeResource(ComputeResourceAccess.ReadWrite)] ReadWriteBuffer<int> sourceHash,
int width,
int height,
in CausticTransportPipeline.DerivedValues derived)
{
_ = _device;
RecordDepositStage(in context, grid, source, sourceHash, width, height, in derived);
}
[ComputePipeline]
private void RecordTransport(
in ComputeContext context,
[ComputeOwnedResource(nameof(_grid))] CausticTransportGridResources grid,
in CausticTransportPipeline.DerivedValues derived,
in CausticTransportPipeline.Parameters parameters)
{
_ = _device;
RecordTransportStage(in context, grid, in derived, in parameters);
}
[ComputePipeline]
[ComputeInterop]
private void RecordSharedSplat(
in ComputeContext context,
[ComputeOwnedResource(nameof(_grid))] CausticTransportGridResources grid,
[ComputeResource(ComputeResourceAccess.ReadWrite, Sharing = ComputeResourceSharing.External)] ReadWriteTexture2D<Bgra32, Float4> source,
[ComputeResource(ComputeResourceAccess.ReadWrite, Sharing = ComputeResourceSharing.External)] ReadWriteTexture2D<Bgra32, Float4> output,
int width,
int height,
in CausticTransportPipeline.DerivedValues derived,
in CausticTransportPipeline.Parameters parameters)
{
_ = _device;
RecordSplatStage(in context, grid, source, output, width, height, in derived, in parameters);
}
private static void RecordDepositStage(
in ComputeContext context,
CausticTransportGridResources grid,
ReadWriteTexture2D<Bgra32, Float4> source,
ReadWriteBuffer<int> sourceHash,
int width,
int height,
in CausticTransportPipeline.DerivedValues derived)
{
var gridWidth = derived.GridWidth;
var gridHeight = derived.GridHeight;
context.Clear(sourceHash);
context.Barrier(sourceHash);
context.For(
ThreadGroupAlignment.AlignX<GridDepositShader>(gridWidth),
ThreadGroupAlignment.AlignY<GridDepositShader>(gridHeight),
new GridDepositShader(source, grid.Density, sourceHash, width, height, gridWidth, gridHeight));
context.Barrier(grid.Density);
}
private static void RecordTransportStage(
in ComputeContext context,
CausticTransportGridResources grid,
in CausticTransportPipeline.DerivedValues derived,
in CausticTransportPipeline.Parameters parameters)
{
var gridWidth = derived.GridWidth;
var gridHeight = derived.GridHeight;
var gridLength = gridWidth * gridHeight;
var levelCount = derived.LevelCount;
context.For(gridWidth, gridHeight, new LightShapeShader(grid.Sigma, gridWidth, gridHeight, parameters.Shape, parameters.Aperture));
context.Barrier(grid.Sigma);
context.For(gridHeight, new GridRowSumShader(grid.Density, grid.Sigma, grid.RowSums, gridWidth, gridHeight));
context.Barrier(grid.RowSums);
context.For(1, new NormalizeScaleShader(grid.RowSums, grid.Scales, gridHeight, gridLength));
context.Barrier(grid.Scales);
context.For(gridWidth, gridHeight, new InitializeDisplacementShader(grid.Displacement, gridWidth, gridHeight, parameters.Shape, parameters.Aperture));
context.Clear(grid.WarpedFixed);
context.Barrier(grid.Displacement);
context.Barrier(grid.WarpedFixed);
var coarseLevel = CausticTransportSettings.GetCoarseSolveLevel(gridWidth, gridHeight);
var (coarseLevelWidth, coarseLevelHeight) = CausticTransportSettings.GetLevelSize(gridWidth, gridHeight, coarseLevel);
var (coarseFineWidth, coarseFineHeight) = coarseLevel > 0
? CausticTransportSettings.GetLevelSize(gridWidth, gridHeight, coarseLevel - 1)
: (gridWidth, gridHeight);
for (var iteration = 0; iteration < derived.TransportIterations; iteration++)
{
context.For(gridWidth, gridHeight, new PushforwardShader(grid.Density, grid.Scales, grid.Displacement, grid.WarpedFixed, gridWidth, gridHeight, CausticTransportSettings.GridFixedScale));
context.Barrier(grid.WarpedFixed);
context.For(gridWidth, gridHeight, new ResidualShader(grid.WarpedFixed, grid.Sigma, grid.Scales, grid.Residual0, gridWidth, gridHeight, 1f / CausticTransportSettings.GridFixedScale));
context.Barrier(grid.Residual0);
context.Barrier(grid.WarpedFixed);
for (var level = 1; level < coarseLevel; level++)
{
var (fineWidth, fineHeight) = CausticTransportSettings.GetLevelSize(gridWidth, gridHeight, level - 1);
var (coarseWidth, coarseHeight) = CausticTransportSettings.GetLevelSize(gridWidth, gridHeight, level);
context.For(coarseWidth, coarseHeight, new RestrictShader(grid.GetResidual(level - 1), grid.GetResidual(level), fineWidth, fineHeight, coarseWidth, coarseHeight));
context.Barrier(grid.GetResidual(level));
}
context.For(
CausticTransportSettings.CoarseSolveThreads,
new CoarseSolveShader(
coarseLevel > 0 ? grid.GetResidual(coarseLevel - 1) : grid.Residual0,
grid.GetPhiA(coarseLevel),
coarseFineWidth,
coarseFineHeight,
coarseLevelWidth,
coarseLevelHeight,
levelCount - coarseLevel,
derived.JacobiIterations,
coarseLevel > 0 ? 1 : 0));
context.Barrier(grid.GetPhiA(coarseLevel));
for (var level = coarseLevel - 1; level >= 0; level--)
{
var (levelWidth, levelHeight) = CausticTransportSettings.GetLevelSize(gridWidth, gridHeight, level);
var (belowWidth, belowHeight) = CausticTransportSettings.GetLevelSize(gridWidth, gridHeight, level + 1);
context.For(levelWidth, levelHeight, new ProlongShader(grid.GetPhiA(level + 1), grid.GetPhiA(level), belowWidth, belowHeight, levelWidth, levelHeight));
context.Barrier(grid.GetPhiA(level));
RecordRelaxation(in context, grid, level, levelWidth, levelHeight, derived.JacobiIterations);
}
context.For(gridWidth, gridHeight, new UpdateDisplacementShader(grid.PhiA0, grid.Displacement, gridWidth, gridHeight, CausticTransportSettings.DisplacementRelaxation, CausticTransportSettings.DisplacementStepLimit));
context.Barrier(grid.Displacement);
}
}
private static void RecordRelaxation(
in ComputeContext context,
CausticTransportGridResources grid,
int level,
int levelWidth,
int levelHeight,
int jacobiIterations)
{
var blockSteps = CausticTransportSettings.GetJacobiBlockSteps(jacobiIterations);
var passes = blockSteps > 0 ? CausticTransportSettings.JacobiBlockCount : jacobiIterations;
for (var pass = 0; pass < passes; pass++)
{
var reading = (pass & 1) == 0 ? grid.GetPhiA(level) : grid.GetPhiB(level);
var writing = (pass & 1) == 0 ? grid.GetPhiB(level) : grid.GetPhiA(level);
if (blockSteps > 0)
{
context.For(
ThreadGroupAlignment.AlignX<JacobiBlockShader>(levelWidth),
ThreadGroupAlignment.AlignY<JacobiBlockShader>(levelHeight),
new JacobiBlockShader(reading, grid.GetResidual(level), writing, levelWidth, levelHeight, blockSteps));
}
else
{
context.For(levelWidth, levelHeight, new JacobiShader(reading, grid.GetResidual(level), writing, levelWidth, levelHeight));
}
context.Barrier(writing);
}
}
private static void RecordSplatStage(
in ComputeContext context,
CausticTransportGridResources grid,
ReadWriteTexture2D<Bgra32, Float4> source,
ReadWriteTexture2D<Bgra32, Float4> output,
int width,
int height,
in CausticTransportPipeline.DerivedValues derived,
in CausticTransportPipeline.Parameters parameters)
{
context.Clear(grid.Accumulator);
context.Barrier(grid.Accumulator);
var movement = 1f - parameters.Focus;
var jitterAmplitude = parameters.Roughness * CausticTransportSettings.JitterCellAmplitude;
context.For(
ThreadGroupAlignment.AlignX<SplatShader>(width),
ThreadGroupAlignment.AlignY<SplatShader>(height),
new SplatShader(
source,
grid.Displacement,
grid.Accumulator,
width,
height,
derived.GridWidth,
derived.GridHeight,
movement,
parameters.Dispersion,
jitterAmplitude,
parameters.Seed,
derived.ColorScale));
context.Barrier(grid.Accumulator);
context.For(width, height, new ResolveShader(grid.Accumulator, output, width, height, 1f / derived.ColorScale));
}
}
+47 -3
ファイルの表示
@@ -14,8 +14,21 @@ internal static class CausticTransportSettings
public const int MaximumCanvasSize = 8192;
public const int MaximumPixelCount = (int)(uint.MaxValue / (ColorFixedScaleMargin * MinimumColorFixedScale));
public const int SplatGroupSize = 8;
public const int SplatTileSize = 10;
public const int SplatTileSize = 12;
public const int SplatTileMargin = 2;
public const int SplatTileLength = SplatTileSize * SplatTileSize * 4;
public const int MaximumLevelCount = 5;
public const int CoarseSolveThreads = 1024;
public const int CoarseSolveCapacity = 8000;
public const int JacobiTileSize = 16;
public const int JacobiBlockCount = 4;
public const int JacobiBlockMaximumSteps = 5;
public const int JacobiBlockSpan = JacobiTileSize + 2 * JacobiBlockMaximumSteps;
public const int JacobiBlockLength = JacobiBlockSpan * JacobiBlockSpan;
public const int MaximumPendingSubmissions = 32;
public const int SourceHashLength = 2;
public const int SourceHashSum = 0;
public const int SourceHashMix = 1;
public static QualitySettings GetQuality(CausticTransportQuality quality)
=> quality switch
@@ -49,8 +62,39 @@ internal static class CausticTransportSettings
public static (int Width, int Height) GetCoarserLevelSize(int width, int height)
=> (Math.Max((width + 1) / 2, MinimumGridSize), Math.Max((height + 1) / 2, MinimumGridSize));
public static int GetSplatDispatchSize(int size)
=> (size + SplatGroupSize - 1) / SplatGroupSize * SplatGroupSize;
public static (int Width, int Height) GetLevelSize(int gridWidth, int gridHeight, int level)
{
var (width, height) = (gridWidth, gridHeight);
for (var index = 0; index < level; index++)
(width, height) = GetCoarserLevelSize(width, height);
return (width, height);
}
public static int GetCoarseSolveLevel(int gridWidth, int gridHeight)
{
var levelCount = GetLevelCount(gridWidth, gridHeight);
for (var level = 0; level < levelCount - 1; level++)
{
var (width, height) = GetLevelSize(gridWidth, gridHeight, level);
var required = 2 * width * height;
for (var coarser = level; coarser < levelCount; coarser++)
{
var (coarserWidth, coarserHeight) = GetLevelSize(gridWidth, gridHeight, coarser);
required += coarserWidth * coarserHeight;
}
if (required <= CoarseSolveCapacity)
return level;
}
return levelCount - 1;
}
public static int GetJacobiBlockSteps(int jacobiIterations)
{
if (jacobiIterations <= 0 || jacobiIterations % JacobiBlockCount != 0)
return 0;
var steps = jacobiIterations / JacobiBlockCount;
return steps <= JacobiBlockMaximumSteps ? steps : 0;
}
public static bool IsSupportedSize(double width, double height)
=> width >= 1d && height >= 1d &&
+102
ファイルの表示
@@ -0,0 +1,102 @@
using System.Diagnostics;
using System.Reflection;
using System.Windows;
using System.Windows.Threading;
using Telemetry;
namespace CausticTransport;
internal static class CausticTransportTelemetry
{
private const int MaxChainLength = 5;
private const int MaxFrames = 100;
private static readonly Assembly Own = typeof(CausticTransportTelemetry).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;
}
}
+4 -2
ファイルの表示
@@ -13,7 +13,7 @@ internal static class CausticTransportUpdateNotifier
public static void EnsureCheckedOnce()
{
if (Interlocked.Exchange(ref _started, 1) != 0)
if (Application.Current is null || Interlocked.Exchange(ref _started, 1) != 0)
return;
_ = RunAsync();
}
@@ -31,8 +31,10 @@ internal static class CausticTransportUpdateNotifier
};
await new Notifier(Owner, Repository, options).NotifyAsync().ConfigureAwait(false);
}
catch
catch (Exception exception)
{
if (exception is not UpdateCheckException)
CausticTransportTelemetry.Report(exception);
}
}
-8
ファイルの表示
@@ -1,8 +0,0 @@
<Project>
<PropertyGroup Condition="'$(MSBuildProjectName)' == 'ComputeSharp' or '$(MSBuildProjectName)' == 'ComputeSharp.Core'">
<IsPackagedProject>false</IsPackagedProject>
</PropertyGroup>
<ItemGroup Condition="'$(MSBuildProjectName)' == 'ComputeSharp.Core'">
<InternalsVisibleTo Include="CausticTransport.ComputeSharp, PublicKey=$(AssemblySignPublicKey)" />
</ItemGroup>
</Project>
-14
ファイルの表示
@@ -1,14 +0,0 @@
<Project>
<PropertyGroup Condition="'$(MSBuildProjectName)' == 'ComputeSharp' or '$(MSBuildProjectName)' == 'ComputeSharp.Core'">
<BaseOutputPath>$(MSBuildProjectDirectory)\bin\CausticTransport\</BaseOutputPath>
<BaseIntermediateOutputPath>$(MSBuildProjectDirectory)\obj\CausticTransport\</BaseIntermediateOutputPath>
<MSBuildProjectExtensionsPath>$(MSBuildProjectDirectory)\obj\</MSBuildProjectExtensionsPath>
<DefaultItemExcludes>$(DefaultItemExcludes);$(MSBuildProjectDirectory)\obj\**</DefaultItemExcludes>
</PropertyGroup>
<PropertyGroup Condition="'$(MSBuildProjectName)' == 'ComputeSharp'">
<AssemblyName>CausticTransport.ComputeSharp</AssemblyName>
</PropertyGroup>
<PropertyGroup Condition="'$(MSBuildProjectName)' == 'ComputeSharp.Core'">
<AssemblyName>CausticTransport.ComputeSharp.Core</AssemblyName>
</PropertyGroup>
</Project>
-9
ファイルの表示
@@ -1,9 +0,0 @@
<Project>
<PropertyGroup>
<PrivateComputeSharpBuildProperties Condition="'$(BuildingSolutionFile)' != 'true'">CustomBeforeDirectoryBuildProps=$(MSBuildThisFileDirectory)ComputeSharp.Build.props;CustomAfterDirectoryBuildProps=$(MSBuildThisFileDirectory)ComputeSharp.Build.after.props</PrivateComputeSharpBuildProperties>
</PropertyGroup>
<ItemGroup>
<ProjectReference Include="$(MSBuildThisFileDirectory)..\ComputeSharp\src\ComputeSharp.Core\ComputeSharp.Core.csproj" SetConfiguration="Configuration=$(Configuration)" SetPlatform="Platform=AnyCPU" AdditionalProperties="$(PrivateComputeSharpBuildProperties)" GlobalPropertiesToRemove="SkipPluginDeploy" />
<ProjectReference Include="$(MSBuildThisFileDirectory)..\ComputeSharp\src\ComputeSharp\ComputeSharp.csproj" SetConfiguration="Configuration=$(Configuration)" SetPlatform="Platform=AnyCPU" AdditionalProperties="$(PrivateComputeSharpBuildProperties)" GlobalPropertiesToRemove="SkipPluginDeploy" />
</ItemGroup>
</Project>
+1 -1
ファイルの表示
@@ -2,5 +2,5 @@ namespace CausticTransport;
internal static class ShaderResourceUri
{
public static Uri Get(string shaderName) => new($"pack://application:,,,/CausticTransport;component/Shaders/{shaderName}.cso", UriKind.Absolute);
public static Uri Get(string shaderName) => new($"pack://application:,,,/CausticTransport;component/Resources/Shader/{shaderName}.cso", UriKind.Absolute);
}
+4 -6
ファイルの表示
@@ -1,10 +1,8 @@
using YukkuriMovieMaker.Generator;
namespace CausticTransport
{
[AutoGenLocalizer]
partial class Texts
{
namespace CausticTransport;
}
[AutoGenLocalizer]
partial class Texts
{
}
+1 -1
ファイルの表示
@@ -20,7 +20,7 @@ RoughnessDescription,,磨りガラスのように光の筋を柔らかく散ら
Seed,,シード,Seed,种子,種子,시드,Semilla,البذرة,Seed
SeedDescription,,散乱の分布を決める固定値です,A fixed value that determines the scatter distribution,决定散射分布的固定值,決定散射分佈的固定值,산란 분포를 결정하는 고정값입니다,Valor fijo que determina la distribución de la dispersión,قيمة ثابتة تحدد توزيع التشتت,Nilai tetap yang menentukan distribusi hamburan
ShapePlane,,面,Plane,平面,平面,평면,Plano,مستو,Bidang
ShapePlaneDescription,,画面全体へ一様に広がります,Spreads uniformly across the whole frame,均匀扩散到整个画面,均勻擴散到整個畫面,화면 전체로 균일하게 퍼집니다,Se extiende uniformemente por todo el cuadro,ينتشر بانتظام عبر الإطار كله,Menyebar merata ke seluruh bingkai
ShapePlaneDescription,,元映像の全体へ一様に広がります,Spreads uniformly across the whole source image,均匀扩散到整个原图像,均勻擴散到整個原圖像,원본 영상 전체로 균일하게 퍼집니다,Se extiende uniformemente por toda la imagen original,ينتشر بانتظام عبر الصورة الأصلية كلها,Menyebar merata ke seluruh citra sumber
ShapeCircle,,円,Circle,圆形,圓形,원형,Círculo,دائرة,Lingkaran
ShapeCircleDescription,,中央の円形の絞りへ集まります,Gathers into a circular aperture at the center,聚集到中央的圆形光圈,聚集到中央的圓形光圈,중앙의 원형 조리개로 모입니다,Se concentra en una apertura circular en el centro,يتجمع في فتحة دائرية في المنتصف,Berkumpul ke bukaan melingkar di tengah
ShapeHorizontalSlit,,横スリット,Horizontal Slit,水平狭缝,水平狹縫,가로 슬릿,Rendija horizontal,شق أفقي,Celah Horizontal
1 Key Parameter ja-jp en-us zh-cn zh-tw ko-kr es-es ar-sa id-id
20 Seed シード Seed 种子 種子 시드 Semilla البذرة Seed
21 SeedDescription 散乱の分布を決める固定値です A fixed value that determines the scatter distribution 决定散射分布的固定值 決定散射分佈的固定值 산란 분포를 결정하는 고정값입니다 Valor fijo que determina la distribución de la dispersión قيمة ثابتة تحدد توزيع التشتت Nilai tetap yang menentukan distribusi hamburan
22 ShapePlane 面 Plane 平面 平面 평면 Plano مستو Bidang
23 ShapePlaneDescription 画面全体へ一様に広がります 元映像の全体へ一様に広がります Spreads uniformly across the whole frame Spreads uniformly across the whole source image 均匀扩散到整个画面 均匀扩散到整个原图像 均勻擴散到整個畫面 均勻擴散到整個原圖像 화면 전체로 균일하게 퍼집니다 원본 영상 전체로 균일하게 퍼집니다 Se extiende uniformemente por todo el cuadro Se extiende uniformemente por toda la imagen original ينتشر بانتظام عبر الإطار كله ينتشر بانتظام عبر الصورة الأصلية كلها Menyebar merata ke seluruh bingkai Menyebar merata ke seluruh citra sumber
24 ShapeCircle 円 Circle 圆形 圓形 원형 Círculo دائرة Lingkaran
25 ShapeCircleDescription 中央の円形の絞りへ集まります Gathers into a circular aperture at the center 聚集到中央的圆形光圈 聚集到中央的圓形光圈 중앙의 원형 조리개로 모입니다 Se concentra en una apertura circular en el centro يتجمع في فتحة دائرية في المنتصف Berkumpul ke bukaan melingkar di tengah
26 ShapeHorizontalSlit 横スリット Horizontal Slit 水平狭缝 水平狹縫 가로 슬릿 Rendija horizontal شق أفقي Celah Horizontal
サブモジュール ComputeSharp が 1dd1430858 から削除されました。
-10
ファイルの表示
@@ -1,15 +1,5 @@
<Project>
<PropertyGroup>
<YMM4DirPath>C:\Program Files\YukkuriMovieMaker_v4_Lite_Dev\</YMM4DirPath>
<WindowsKitRoot>C:\Program Files (x86)\Windows Kits\10\bin</WindowsKitRoot>
<FxcPath Condition="'$(FxcPath)' == '' AND Exists('$(WindowsKitRoot)\10.0.26100.0\x64\fxc.exe')">$(WindowsKitRoot)\10.0.26100.0\x64\fxc.exe</FxcPath>
<FxcPath Condition="'$(FxcPath)' == '' AND Exists('$(WindowsKitRoot)\10.0.22621.0\x64\fxc.exe')">$(WindowsKitRoot)\10.0.22621.0\x64\fxc.exe</FxcPath>
<FxcPath Condition="'$(FxcPath)' == '' AND Exists('$(WindowsKitRoot)\10.0.19041.0\x64\fxc.exe')">$(WindowsKitRoot)\10.0.19041.0\x64\fxc.exe</FxcPath>
<FxcPath Condition="'$(FxcPath)' == '' AND Exists('$(WindowsKitRoot)\10.0.18362.0\x64\fxc.exe')">$(WindowsKitRoot)\10.0.18362.0\x64\fxc.exe</FxcPath>
<FxcPath Condition="'$(FxcPath)' == '' AND Exists('$(WindowsKitRoot)\10.0.17763.0\x64\fxc.exe')">$(WindowsKitRoot)\10.0.17763.0\x64\fxc.exe</FxcPath>
<FxcPath Condition="'$(FxcPath)' == ''">fxc.exe</FxcPath>
</PropertyGroup>
</Project>
+81 -36
ファイルの表示
@@ -8,6 +8,7 @@
YukkuriMovieMaker4(YMM4)上で動作する、現在のフレームの明るさを光の分布として輸送格子へ集め、選択した光源形状へ広げた光を元映像へ結像させる映像エフェクトプラグインです。
履歴フレーム、参照画像、学習済みモデルを使わず、入力された一枚の映像だけを処理します。
結果は入力映像と設定から決定論的に決まり、同じ環境と設定では常に同じ結果になります。
面、円、横スリット、縦スリットの4種類から光源形状を選択できます。
強さ、集光度、光源サイズ、分散、面粗さの5項目はアニメーションに対応しています。
@@ -21,11 +22,11 @@ YukkuriMovieMaker4(YMM4)上で動作する、現在のフレームの明る
2. [動作要件](#動作要件)
3. [インストール方法](#インストール方法)
4. [主な機能](#主な機能)
- [1. 現在フレームの光分布の輸送](#1-現在フレームの光分布の輸送)
- [2. 集光度による広がりと結像](#2-集光度による広がりと結像)
- [1. 光の分布の輸送](#1-光の分布の輸送)
- [2. 集光度による描画と結像](#2-集光度による描画と結像)
- [3. 光源形状と光源サイズ](#3-光源形状と光源サイズ)
- [4. 分散による色分け](#4-分散による色分け)
- [5. 面粗さによる散乱](#5-面粗さによる散乱)
- [5. 面粗さによる散乱とシード](#5-面粗さによる散乱とシード)
- [6. 品質の選択](#6-品質の選択)
5. [パラメータ一覧](#パラメータ一覧)
- [基本グループ](#基本グループ)
@@ -33,21 +34,22 @@ YukkuriMovieMaker4(YMM4)上で動作する、現在のフレームの明る
- [光学グループ](#光学グループ)
6. [制限事項](#制限事項)
7. [注意事項](#注意事項)
8. [免責事項](#免責事項)
9. [サードパーティライセンス](#サードパーティライセンス)
10. [ライセンス](#ライセンス)
8. [不具合の報告](#不具合の報告)
9. [免責事項](#免責事項)
10. [サードパーティライセンス](#サードパーティライセンス)
11. [ライセンス](#ライセンス)
---
## 概要
本プラグインはYMM4の映像エフェクトとして動作し、エフェクトの種類一覧では「光輸送結像」として表示されます。カテゴリはフィルタリングと装飾です。
本プラグインはYMM4の映像エフェクトとして動作し、エフェクトの種類一覧では「光輸送結像」として表示されます。カテゴリは加工と装飾です。
入力された現在のフレームから各画素の明るさを求め、輸送格子の上に光の分布として集めます。この分布を、選択した光源形状が定める目標分布へ移す輸送写像を求めます。輸送写像は、現在の分布を写像に沿って押し出し、目標分布との差からポテンシャルのポアソン方程式をマルチグリッドのVサイクルで解き、ポテンシャルの勾配に沿って写像を更新する反復で計算します。
入力された現在のフレームから各画素の明るさを求め、輸送格子の上に光の分布として集めます。処理する範囲は、このエフェクトに入る映像を囲む矩形です。輸送格子は、この範囲を縦横に区切ったセルの並びです。輸送写像は、光の分布を、選択した光源形状が定める目標分布へ移す対応づけです。この対応づけは、ポアソン方程式を解く反復で求めます。
集光度は、この輸送をどれだけ進めるかを決めます。集光度が0%のときは光を光源形状へ広げ、100%のときは輸送を行わず元映像へ結像します。求めた輸送写像に沿って各画素の色を移動先へ加算し、固定小数点で集計してから出力します。分散は波長ごとに輸送量を変えて色を虹色に分け、面粗さは輸送量へ散乱を加えて光の筋を柔らかくします。
光の分布を集めた後の処理は、3つの段階に分かれます。輸送の計算は、輸送写像を求める段階です。描画は、輸送写像に沿って各画素の色と不透明度を動かし、光の像を作る段階です。合成は、光の像と入力映像を強さの割合で混ぜる段階です。集光度は、描画で画素をどれだけ動かすかを決めます。集光度が0%のときは光を光源形状へ広げ、100%のときは入力映像をそのまま出力します。分散は赤、緑、青の移動量に差を付けて色を分け、面粗さは輸送写像にずれを加えて光の筋を柔らかくします。
計算はComputeSharpの計算シェーダーがDirect3D 12で実行します。YMM4のDirect3D 11側とComputeSharpのDirect3D 12側は、共有テクスチャと共有フェンスで接続します。通常のフレーム処理ではCPUへの画素読み戻しを行いません。入力と出力のアルファ値は維持します。
計算はComputeWeaveの計算シェーダーがDirect3D 12で実行します。YMM4のDirect3D 11側とComputeWeaveのDirect3D 12側は、共有テクスチャと共有フェンスで接続します。通常のフレーム処理では、CPUへ画素を読み戻さず、入力映像の変化の判定に使う2個の整数だけを読み戻します。入力映像、品質、光源形状、光源サイズが変わらないフレームでは、輸送の計算を再利用します。集光度、分散、面粗さ、シードも変わらなければ、描き直しません。再利用の条件は「注意事項」にあります。
このエフェクトはAviUtl向けのEXO出力には対応していません。
@@ -75,45 +77,51 @@ YukkuriMovieMaker4(YMM4)上で動作する、現在のフレームの明る
## 主な機能
### 1. 現在フレームの光分布の輸送
### 1. 光の分布の輸送
現在のフレームの各画素からBT.709の輝度を求め、輸送格子の各セルへ合計して光の分布を作ります。この分布を、選択した光源形状が定める目標分布と同じ総量へそろえます。続いて、分布を輸送写像に沿って押し出し、目標分布との差をポテンシャルのポアソン方程式として解き、ポテンシャルの勾配に沿って写像を更新します。この反復で、元映像の光を光源形状へ移す写像を求めます。
現在のフレームの各画素について、不透明度を掛けた色のBT.709の輝度に、不透明度の1%を足します。この値を各画素の明るさとし、輸送格子のセルごとに合計して光の分布を作ります。この分布と、選択した光源形状が定める目標分布を、同じ総量へそろえます。外部マスクや手動の位置指定は必要としません。
外部マスクや手動の位置指定は必要としません。輸送写像は品質設定が定める反復回数だけ更新します。
最初の輸送写像は、面では各セルを動かさない写像、円では範囲を円形へ写す写像、スリットでは範囲を帯へ一様に縮める写像です。この写像から、次の3つの処理を品質が定める回数だけ繰り返します。まず、光の分布を輸送写像に沿って動かします。次に、動かした分布と目標分布の差を求めます。この差が右辺になるポアソン方程式を解き、その解をポテンシャルとします。最後に、ポテンシャルの勾配に沿って輸送写像を更新します。
### 2. 集光度による広がりと結像
ポアソン方程式は、マルチグリッド法のVサイクルで解きます。マルチグリッド法は、セルを2×2ずつまとめて粗くした格子を重ね、粗い格子の解を細かい格子へ引き継ぎながら解く方法です。Vサイクルは、まず右辺の差を粗い格子へ順にまとめます。次に、粗い格子で解を求めます。その解を細かい格子へ順に引き継ぎ、各格子でJacobi反復を行って解を整えます。Jacobi反復は、各セルの値を、上下左右の隣のセルの直前の反復での値と、そのセル自身の右辺から計算し直す操作です。この操作を、全セルで同時に行い、繰り返します。輸送写像の反復回数と、Vサイクル1回につき各格子で行うJacobi反復の回数は、「品質の選択」の表にあります。
集光度は、求めた輸送写像に沿って画素をどれだけ移動させるかを決めます。集光度が0%のとき、画素は写像の移動先へ完全に移り、光は光源形状の分布へ広がります。集光度が100%のとき、画素は移動せず、元映像がそのまま結像します。中間の値では、広がった光が元映像へ集まる途中の像になります。
### 2. 集光度による描画と結像
集光度を時間で変えると、光源形状から映像が立ち上がる遷移、または映像が光源形状へ崩れる遷移になります。集光度が100%のときは輸送を行わず、入力映像をそのまま出力します。
集光度は、求めた輸送写像に沿って画素をどれだけ動かすかを決めます。画素は、元の位置から輸送写像の移動先へ向かう道のりのうち、100%から集光度を引いた割合だけ動きます。たとえば集光度が25%なら、道のりの75%まで動きます。分散を上げたときの色ごとの違いは、「分散による色分け」にあります。集光度が0%のとき、画素は輸送写像の移動先まで動き、光は光源形状の分布へ広がります。集光度が100%に近づくほど画素は元の位置に近づき、光は入力映像の形へ戻ります。この戻った状態を結像と呼びます。
描画では、各画素の色と不透明度を、動かした先の位置を囲む4画素へ、位置に近い画素ほど多くなる割合で分けて足し込みます。足し込む順序によらず同じ結果になるよう、値を整数に直して集計します。足し込んだ先の画素で不透明度の合計が100%を超えるときは、色と不透明度を不透明度の合計で割ります。この画素の不透明度は100%になり、色は重なった色を不透明度で重み付けした平均になります。描いた光の像は、強さの割合で入力映像と混ぜて出力します。
集光度をアニメーションで変えると、光源形状へ広がった光から入力映像が立ち上がる遷移や、入力映像が光源形状へ崩れる遷移を作れます。
### 3. 光源形状と光源サイズ
光源形状は、集光度0%で光が広がる目標分布の形を決めます。面は画面全体へ一様に広げ、円は中央の円形の絞りへ集め、横スリットと縦スリットはそれぞれ水平と垂直の帯状の光へ集めます。
光源形状は、集光度0%で光が広がる目標分布の形を決めます。面は、処理する範囲の全体へ光を一様に広げます。円は円形に、横スリットは水平の帯に、縦スリットは垂直の帯に光を集めます。円とスリットの位置は処理する範囲の中央に決まっており、ずらすことも、斜めに傾けることもできません。
光源サイズは、円とスリットの大きさを決めます。面では光源サイズの影響を受けません。円とスリットの縁は柔らかくぼかします。
光源サイズは、円の直径とスリットの帯の幅を決めます。100%のとき、直径と帯の幅は処理する範囲の短辺と同じ長さです。面では光源サイズを使いません。円とスリットの縁はぼかします。
### 4. 分散による色分け
分散は、波長ごとに輸送量を変えます。赤は移動量を大きく、青は移動量を小さくずらし、緑は基準の移動量を保ちます。この差で、光が集まる途中に赤と青の縁が分かれ、色が虹色にずれます。分散を0%にすると、3色を同じ移動量で輸送します。
分散は、赤、緑、青の3色で移動量を変えます。緑は集光度が決める基準の移動量で動かします。赤は緑より遠くへ動かしますが、輸送写像の移動先を越えることはありません。青は緑より手前までしか動かしません。この移動量の差で、光が広がる途中では赤と青の縁が分かれ、色が虹色にずれます。赤の移動量は最大で緑の(1+0.35×分散)倍、青は(1-0.35×分散)倍です。分散が100%のとき、赤は最大で1.35倍、青は0.65倍です。分散を0%にすると、3色を同じ移動量で動かします。
### 5. 面粗さによる散乱
赤が輸送写像の移動先で止まるため、分散が100%で集光度が約26%を下回ると、赤の移動量は緑の1.35倍に届きません。分散が0%より大きければ、集光度が0%のとき赤と緑は同じ位置へ動き、青だけが手前に残ります。分散が0%より大きいとき、不透明度は3色に3分の1ずつ分け、それぞれの色と一緒に動かします。
面粗さは、輸送写像へセルごとの散乱を加えます。散乱の向きと大きさは、シードとセル位置から決まるハッシュで決定論的に決まります。面粗さを上げると、光の筋が磨りガラスのように柔らかく散らばります。面粗さを0%にすると、散乱を加えません。
### 5. 面粗さによる散乱とシード
シードは、散乱の分布を決める固定値です。同じシードと同じパラメータでは、常に同じ散乱になります。面粗さが0%のとき、シードは結果へ影響しません。
面粗さは、輸送写像にセルごとのずれを加えて、光を散乱させます。面粗さを上げると、光の筋が磨りガラスのように柔らかく散らばります。ずれの向きと大きさは、シードとセルの位置から作るハッシュで決まります。ずれの大きさは、面粗さが100%のとき、縦と横のそれぞれで最大0.5セルです。セルの大きさは「品質の選択」にあります。このずれにも、輸送写像と同じ割合を掛けます。この割合は、緑では100%から集光度を引いた値です。赤と青の割合は、緑の割合に「分散による色分け」の倍率を掛けた値で、赤は100%で止まります。面粗さを0%にすると、ずれを加えません。
シードは、散乱の分布を決める固定値です。同じシードと同じパラメータでは、常に同じ散乱になります。面粗さが0%のとき、シードは結果に影響しません。
### 6. 品質の選択
品質は、輸送格子の解像度、輸送写像の反復回数、ポアソン方程式のJacobi反復回数をまとめて切り替えます。
品質は、輸送格子の解像度、輸送写像の反復回数、ポアソン方程式を解くJacobi反復の回数をまとめて切り替えます。
| 品質 | 格子解像度 | 輸送反復 | Jacobi反復 |
| 品質 | 格子解像度 | 輸送写像の反復 | Jacobi反復 |
|---|---:|---:|---:|
| 標準 | 128 | 4回 | 12回 |
| 高品質 | 192 | 6回 | 16回 |
| 最高品質 | 256 | 8回 | 20回 |
格子解像度は長辺のセル数です。短辺のセル数は入力映像の縦横比に合わせて決めます。
格子解像度は、輸送格子の長辺のセル数の上限です。短辺のセル数は、処理する範囲の縦横比に合わせて決めます。処理する範囲の長辺が格子解像度以下のときは、長辺の画素数がそのままセル数になります。そのため、長辺が128画素以下なら、格子の大きさはどの品質でも同じです。違うのは反復の回数だけです。1セルの幅と高さは、処理する範囲の幅と高さを、それぞれ輸送格子の横と縦のセル数で割った長さです。
---
@@ -124,7 +132,7 @@ YukkuriMovieMaker4(YMM4)上で動作する、現在のフレームの明る
| パラメータ名 | 型 | デフォルト | スライダー表示範囲 | アニメーション | 説明 |
|---|---|---|---|---|---|
| 強さ | 数値 | 100% | 0〜100% | 対応 | 元映像と生成した光の像の合成量です。0%では入力を変更しません。 |
| 集光度 | 数値 | 50% | 0〜100% | 対応 | 0%で光源の形に広がり、100%で元映像に結像します。 |
| 集光度 | 数値 | 50% | 0〜100% | 対応 | 0%で光源形状に広がり、100%で元映像に結像します。 |
| 品質 | 列挙 | 高品質 | 標準 / 高品質 / 最高品質 | 非対応 | 輸送格子の解像度と反復回数を選択します。 |
### 光源グループ
@@ -132,15 +140,15 @@ YukkuriMovieMaker4(YMM4)上で動作する、現在のフレームの明る
| パラメータ名 | 型 | デフォルト | スライダー表示範囲 | アニメーション | 説明 |
|---|---|---|---|---|---|
| 光源形状 | 列挙 | 面 | 面 / 円 / 横スリット / 縦スリット | 非対応 | 集光度0%で光が広がる分布の形です。 |
| 光源サイズ | 数値 | 50% | 5〜100% | 対応 | 円とスリットの大きさです。 |
| 光源サイズ | 数値 | 50% | 5〜100% | 対応 | 円の直径とスリットの帯の幅です。面では使いません。 |
### 光学グループ
| パラメータ名 | 型 | デフォルト | スライダー表示範囲 | アニメーション | 説明 |
|---|---|---|---|---|---|
| 分散 | 数値 | 30% | 0〜100% | 対応 | 波長ごとに集まる速さを変えて色を虹色に分けます。 |
| 分散 | 数値 | 30% | 0〜100% | 対応 | 赤、緑、青の移動量に差を付けて色を虹色に分けます。 |
| 面粗さ | 数値 | 20% | 0〜100% | 対応 | 磨りガラスのように光の筋を柔らかく散らします。 |
| シード | 整数 | 0 | 0〜10000 | 非対応 | 散乱の分布を決める固定値です。直接入力では2147483647まで指定できます。 |
| シード | 整数 | 0 | 0〜10000 | 非対応 | 散乱の分布を決める固定値です。面粗さが0%のときは影響しません。直接入力では2147483647まで指定できます。 |
---
@@ -148,8 +156,9 @@ YukkuriMovieMaker4(YMM4)上で動作する、現在のフレームの明る
- AviUtl向けのEXO出力には対応していません。
- Direct3D 12デバイスを取得できない場合や、YMM4が使うDirect3D 11デバイスとの共有テクスチャおよび共有フェンスを作成できない場合は、エフェクトを適用せず入力映像を表示します。
- 解析対象は現在のフレームだけです。履歴フレーム、外部画像、深度情報、学習済みモデルは使用しません。
- 処理する範囲の辺が8192画素以下、かつ総画素数が11,184,810以下の入力に対応します。3840×2160と4096×2160はこの範囲に含まれます。範囲を超える入力には、エフェクトを適用せず入力映像を表示します。
- 光の像の計算には現在のフレームの色と不透明度だけを使用します。履歴フレーム、外部画像、学習済みモデルは使用しません。
- 処理する範囲の辺が8192画素以下、かつ総画素数が11184810以下の入力に対応します。3840×2160と4096×2160はこの条件を満たし、6000×4000は総画素数が上限を超えます。判定には、プロジェクトの解像度ではなく、処理する範囲の大きさを使います。条件を満たさない入力には、エフェクトを適用せず入力映像を表示します。
- 光は処理する範囲の外へは広がりません。範囲の端へ向かう光は、端の画素に集まります。
- 処理量とGPUメモリ使用量は入力映像の画素数に応じて増えます。
---
@@ -157,14 +166,50 @@ YukkuriMovieMaker4(YMM4)上で動作する、現在のフレームの明る
## 注意事項
- 処理負荷: 最高品質は格子解像度と反復回数が最も多いため、高品質と標準より処理負荷が高くなります。
- 集光度100%: 集光度が100%のときは輸送を行わず、入力映像をそのまま出力します。強さが0%のときも入力を変更しません。
- シードと再現性: 散乱は、シード、セル位置から決定論的に算出します。時間値は散乱の生成に使用しません。面粗さが0%のとき、シードは結果へ影響しません。
- 透明部分: 入力のアルファ値を出力へ維持します。完全に透明な画素は輸送の対象から除外されます。
- キャッシュ: 入力映像とその大きさ、品質、光源形状、光源サイズが変わらないフレームでは、輸送の計算を再利用します。光源形状が面のときは、光源サイズを変えても輸送の計算を再利用します。光の分布と、変化の判定に使う2個の整数は、毎フレームGPUで求めます。2個の整数は、全画素の色と不透明度から作ります。この整数と入力映像の大きさが、輸送を計算したときと同じなら、輸送の計算を再利用します。動画のように、直近に読み戻した2フレーム分の整数が違うあいだは、入力映像が変わり続けているとみなします。このときは、今のフレームの整数の読み戻しを待たず、毎フレーム輸送の計算をやり直し、整数は次のフレームで読み戻します。変化が最後に起きたフレームの次のフレームでも、直近に読み戻した2フレーム分の整数はまだ違います。そのため、このフレームでも輸送の計算をやり直し、その次のフレームから再利用します。光源形状が円かスリットのときに光源サイズをアニメーションで変えると、輸送の計算を毎フレームやり直します。入力映像が変わり続けるときと、光源サイズを動かすときは、処理が重くなります。
- 描き直し: 集光度、分散、面粗さ、シードが変わらず、輸送の計算も再利用するフレームでは、描画も再利用します。面粗さが0%のときは、シードを変えても描き直しません。集光度、分散、面粗さ、シードのどれかだけを変えたフレームでは、輸送の計算は再利用し、描画だけをやり直します。強さだけを変えたフレームでは、描き直さず、合成の量だけを変えます。
- 集光度100%と強さ0%: 集光度が100%のときは輸送の計算も描画も行わず、入力映像をそのまま出力します。強さが0%のときも入力を変更しません。
- シードと再現性: 散乱は、シードとセル位置から決定論的に算出します。時間値は散乱の生成に使用しません。面粗さが0%のとき、シードは結果へ影響しません。
- 透明部分: 光の像は、色と不透明度をまとめて移動先へ動かして作ります。完全に透明な画素は動かしませんが、その位置へほかの画素から移ってきた色と不透明度は描かれます。内容が移って空いた位置は、ほかから何も移ってこなければ透明に近づきます。出力の不透明度は、色と同じく、入力映像と光の像を強さの割合で混ぜた値です。
- 更新通知: エフェクトを最初に生成したときに、YMM4の実行中に一度だけ新しい正式版を確認します。更新情報を取得できない場合は通知せず、そのまま動作します。プレリリースは通知の対象に含めません。
- 不具合の自動送信: 想定していない例外が起きたときは、その内容を開発者へ自動で送信します。内容は「不具合の報告」に書いています。
- 本プラグインを使用する前に、YMM4のプロジェクトファイルのバックアップを作成することを推奨します。
---
## 不具合の報告
本プラグインは、想定していない例外が起きたときに、その内容を開発者へ自動で送信します。同意は求めず、常に送信します。
送信する情報は次のとおりです。
| 種類 | 内容 |
|---|---|
| 例外 | 型の完全名、メッセージ、スタックトレース |
| 発生位置 | モジュール名、関数名、ファイル名、行番号 |
| プラグイン | アセンブリ名、バージョン |
| 実行環境 | OSの名前とバージョン、.NETのバージョン、CPUのアーキテクチャ、論理プロセッサ数 |
| 識別子 | YMM4の起動ごとに決まるセッション識別子、報告ごとの識別子 |
メッセージとファイル名は、送信の前に置き換えを通します。置き換えるのは、Windowsのユーザー名、ユーザーフォルダー、AppDataのパス、マシン名、ドメイン名、メールアドレス、IPv4アドレスです。送信元のIPアドレスは受信側へ渡す手前で取り除いています。
映像の中身とプロジェクトの内容は送信しません。継続して個人を追跡する識別子も持ちません。セッション識別子はYMM4を起動し直すと別の値になります。
送信するのは想定していない例外だけです。YMM4が本プラグインのエフェクトを作るとき、フレームごとに更新するとき、入力をつなぎ直すとき、破棄するときと、Direct2Dがシェーダーの定数を書き込むときに起きた例外を報告し、その後はYMM4へそのまま渡します。更新の確認では、更新情報の取得と比較で起きた例外は報告しません。通知の文を組み立てて表示するときに起きた例外は報告し、YMM4へは渡しません。画面の操作やバックグラウンドの処理で未処理になった例外も報告しますが、本プラグインのコードが関わる例外に限ります。本プラグインの外で起きた例外は送信しません。
次の失敗は送信しません。
| 種類 | 例 |
|---|---|
| 効果をかけないだけで済ませるもの | Direct3D 12デバイスを取得できない、YMM4のDirect3D 11デバイスとの共有テクスチャや共有フェンスを作成できない、処理する範囲の辺が8192画素を超えるか、総画素数が11184810を超えるときに、エフェクトを適用せず入力映像を表示したとき |
| 更新の確認の通信の失敗 | manjubox.netとGitHubのどちらへも接続できない |
送信できなかった報告はYMM4のユーザーフォルダーへ退避します。次にYMM4を起動したあと、本プラグインのエフェクトを生成するか、同じくYMM4-Telemetryで報告する別のプラグインが動き始めると、退避した報告を1回の起動で10件まで送り直します。送信も再送も非同期に行うため、通信を待って起動と描画が遅くなることはありません。
実装は [YMM4-Telemetry](https://github.com/routersys/YMM4-Telemetry) をサブモジュールとして取り込んでいます。
---
## 免責事項
本プラグインはMITライセンスのもとで公開されています。
@@ -177,11 +222,11 @@ YukkuriMovieMaker4(YMM4)上で動作する、現在のフレームの明る
## サードパーティライセンス
本プラグインは以下のサードパーティソフトウェアを同梱・使用しています。ライセンスの全文は、リポジトリの [`.github/LICENSE/ComputeSharp.txt`](.github/LICENSE/ComputeSharp.txt) と、配布パッケージの `LICENSE` フォルダーに収録しています。
本プラグインは以下のサードパーティソフトウェアを同梱・使用しています。ライセンスの全文は、リポジトリの [`.github/LICENSE/ComputeWeave.txt`](.github/LICENSE/ComputeWeave.txt) と、配布パッケージの `LICENSE` フォルダーに収録しています。
| ソフトウェア | 用途 | ライセンス | 著作権表示 |
|---|---|---|---|
| [ComputeSharp](https://github.com/routersys/ComputeSharp) | Direct3D 12計算シェーダーとDirect3D 11・12共有処理 | MIT License | Copyright (c) 2024 Sergio Pedri |
| [ComputeWeave](https://github.com/routersys/ComputeWeave) | Direct3D 12計算シェーダーとDirect3D 11・12共有処理 | MIT License | Copyright (c) 2024 Sergio Pedri |
---
+46
ファイルの表示
@@ -0,0 +1,46 @@
# セキュリティポリシー
## サポートするバージョン
セキュリティの修正は、最新のリリースだけを対象にします。
| バージョン | サポート |
|---|---|
| 最新のリリース | 対象 |
| それより前のリリース | 対象外 |
修正は、最新のリリースの次のバージョンとして公開します。報告する前に、最新のリリースでも問題が起きるかを確かめてください。
## 対象とする問題
本プラグインのコードと配布パッケージに原因がある問題を対象にします。たとえば次のようなものです。
- 細工したプロジェクトファイルや素材を開くと、意図しない処理が実行される
- 更新の確認などで行う通信の内容を、第三者が書き換えられる
- 不具合の情報を自動で送信するプラグインで、個人を特定できる情報が伏せられないまま送信される
配布パッケージに同梱したライブラリの脆弱性は、本プラグインを通じて悪用できる場合に対象にします。
YukkuriMovieMaker4 本体や、ほかのプラグインに原因がある問題は対象外です。それぞれの開発者へ報告してください。
## 報告の方法
脆弱性は、公開の Issue に書かないでください。修正を公開する前に悪用されるおそれがあります。
1. リポジトリの URL の末尾に `/security` を付けたページを開き、「Report a vulnerability」から非公開で報告してください。報告の内容を見られるのは、開発者と報告した人、開発者が招いた人だけです。
2. この方法が使えないときは、github.routersys@gmail.com へメールで報告してください。
報告には、次の内容を書いてください。分からない項目は書かなくて構いません。
| 項目 | 内容 |
|---|---|
| バージョン | 問題を確かめたプラグインのバージョンと、YukkuriMovieMaker4 のバージョン |
| 再現の手順 | 問題を起こす操作と、使ったプロジェクトファイルや素材 |
| 影響 | 問題によって何ができてしまうか |
| 回避策 | 分かっていれば、修正までの間に被害を避ける方法 |
## 報告の後
開発者は、報告を受け取ったら内容を確かめ、修正の見込みを返信します。
報告した人は、修正を含むバージョンが出るまで、報告の内容を明かさないでください。問題の詳細は、修正版の公開後に開発者が公表します。
サブモジュール
+1
サブモジュール YMM4-Telemetry が 04010903ca で追加されました。
+5
ファイルの表示
@@ -0,0 +1,5 @@
{
"test": {
"runner": "Microsoft.Testing.Platform"
}
}