87 コミット
作成者 SHA1 メッセージ 日付
routersys 25b9e42bb5 バージョンをv1.1.0へ更新する
リリース / build-and-release (workflow_dispatch) Actions がタグ v1.1.0 のコミットから作成しました
2026-09-27 14:10:44 +09:00
routersys 2001d10b14 キャッシュの記述を実装に合わせる 2026-09-27 14:09:29 +09:00
routersys a0f0608e3b 計算領域の最大の長辺を余白の取り方に合わせる 2026-09-27 14:08:12 +09:00
routersys e3b4578703 到達距離が1セルに満たないときも1セル分の余白を取る
・大きな素材を標準品質で処理すると霜の外縁が計算領域の端で切れる不具合を修正-F
2026-09-27 14:07:16 +09:00
routersys 90cd78b3ad パラメータの説明文を実際の働きに合わせる
・到達距離や屈折などの説明文が実際の働きと食い違っていた点を修正-F
2026-09-27 13:58:04 +09:00
routersys 0099e4eee6 形が変わる描画を保存の処理から別のシェーダーに分ける
・凍結度を動かすフレームの描画を高速化-M
2026-09-27 13:44:11 +09:00
routersys e9797735b5 白濁を動かすベンチマークのケースを加える 2026-09-27 12:34:46 +09:00
routersys 50fc802636 形が同じまま描き直すときは氷のかかる画素の途中結果から描く
・白濁や屈折、光沢、色、素材の色だけが変わるフレームの描画を高速化-M
2026-09-27 12:34:29 +09:00
routersys bad74cdea3 氷のかからない区画では周りのセルを集めずに描く
・描き直すフレームの描画を高速化-M
2026-09-27 12:23:49 +09:00
routersys 797f754bc4 凍結度を動かすベンチマークのケースを加える 2026-09-27 12:09:39 +09:00
routersys b7099b7639 描き直しが決まっているフレームでは素材の色のハッシュを省く
・凍結度や白濁などを動かしているフレームの処理を高速化-M
2026-09-27 11:07:03 +09:00
routersys ddc65f3495 描画の前にセルごとの厚みを求めておく
・凍結度のアニメーションなどで描き直すフレームの描画を高速化-M
2026-09-27 11:03:40 +09:00
routersys 3d96bc9a57 ゆらぎが0%のときはシードの変更で成長を計算し直さない
・ゆらぎが0%のときにシードを変えても結晶の成長を再計算しないよう高速化-M
2026-09-27 11:01:07 +09:00
routersys da76bc698d サムネイル画像を更新する 2026-09-27 10:42:00 +09:00
routersys 0a6042f5d9 仕組みと各項目の説明を実装に合わせて書き直す 2026-09-27 05:19:49 +09:00
routersys 3dc06db8cf 制限事項と注意事項を実装に合わせる 2026-09-27 05:19:39 +09:00
routersys 0f39de5887 不具合の報告を実装に合わせる 2026-09-27 05:19:27 +09:00
routersys 094c82bc1f 論文の出典を掲載誌の書誌に合わせて示す 2026-09-27 05:19:08 +09:00
routersys 452782ca44 成長の記録を分割して提出しGPUの実行と重ねる
・結晶の成長の再計算でCPUとGPUの処理を重ねて待ち時間を短縮-M
2026-09-26 19:46:10 +09:00
routersys a637bcbe44 拡散と成長の更新を横長のスレッドグループで実行する
・結晶の成長の再計算を高速化-M
2026-09-26 18:22:13 +09:00
routersys be216ea119 色だけが変わった画像の氷越しの背景を描き直す
・素材の色だけが変わったときに氷越しの背景が前の色のまま残る不具合を修正-F
2026-09-26 16:28:44 +09:00
routersys d501cf9ecf マージ 2026-09-26 15:17:41 +09:00
routersys be82ad738a 余白が収まらない長い画像の試験を追加する 2026-09-26 11:33:26 +09:00
routersys 3f9a04f6b0 透明な画像に形が現れたときの試験を追加する 2026-09-26 11:32:28 +09:00
routersys aa17d6fa55 凍結度を変えた処理器が新しいものと同じ絵を描く試験を追加する 2026-09-26 11:30:16 +09:00
routersys 73484a3f13 到達距離が長辺を基準にする試験を追加する 2026-09-26 11:29:05 +09:00
routersys df0748be31 氷晶が画像と一緒に動く試験を追加する 2026-09-26 11:27:14 +09:00
routersys 0be22a63d7 氷晶の色の試験を追加する 2026-09-26 11:26:06 +09:00
routersys 7f1fe615d5 大きさを変えて使い回したパイプラインの試験を追加する 2026-09-26 11:24:26 +09:00
routersys 899f21a964 氷晶が無いときの可視範囲の試験を追加する 2026-09-26 11:23:26 +09:00
routersys 0ab2f241a6 凍結度に応じて可視範囲が狭まる試験を追加する 2026-09-26 11:21:57 +09:00
routersys 87b500dbcd 可視範囲が氷晶に沿う試験を追加する 2026-09-26 11:21:05 +09:00
routersys b1d5de072c 六方格子の近傍の試験を追加する 2026-09-26 11:18:33 +09:00
routersys dc076243c5 格子の長辺の分割数の試験を追加する 2026-09-26 11:17:39 +09:00
routersys 5257f9697d Plugin_Readmeへ不具合の報告を追記する 2026-09-26 11:15:44 +09:00
routersys 20e0dad919 READMEへ不具合の報告を追記する 2026-09-26 11:15:20 +09:00
routersys a499e63a01 テレメトリーを変異試験の対象から外す 2026-09-26 11:14:22 +09:00
routersys af468e5dcf WPFアプリケーションの外でテレメトリーを送らない試験を追加する 2026-09-26 11:14:15 +09:00
routersys 9619a81709 更新確認で例外を握り潰さず報告する 2026-09-26 11:13:17 +09:00
routersys dc6bb2e089 資源確保の失敗だけを素通しにしそれ以外の例外は伝える 2026-09-26 11:12:47 +09:00
routersys 297ed193cc ホストとDirect2Dからの呼び出し口で例外を報告する
・想定していない例外を開発者へ自動で報告する機能を追加-A
2026-09-26 11:11:44 +09:00
routersys 55cc472254 CrystallineGrowthTelemetryを追加する 2026-09-26 11:10:46 +09:00
routersys d9104a09c2 Telemetryをコンパイルに含める 2026-09-26 11:10:15 +09:00
routersys edf73f3609 YMM4-Telemetryサブモジュールを追加する 2026-09-26 11:09:39 +09:00
routersys 73c3c03f17 使われないジャンプフラッドの段数の計算を取り除く 2026-09-26 11:02:57 +09:00
routersys 62ab7c349e スクラッチの添字を名前付きの定数で読む 2026-09-26 11:02:03 +09:00
routersys d1a426c610 更新確認をWPF起動中に限り行う 2026-09-26 11:01:08 +09:00
routersys 3033a6f797 シェーダーを変異試験の対象から外す 2026-09-26 10:12:02 +09:00
routersys 149d16858b サードパーティの表記をComputeWeaveにする 2026-09-26 10:11:32 +09:00
routersys f1c4cb428d パイプラインを作れないときは試験を飛ばさずに失敗させる 2026-09-26 10:09:40 +09:00
routersys 1dc37a2b7d 変異試験の並列数と制限時間をGPUに合わせる 2026-09-26 10:08:27 +09:00
routersys df873c76c1 本体の参照でプラットフォームを固定しない 2026-09-26 10:08:26 +09:00
routersys 224b726065 WPFアプリケーションの外での挙動の試験を追加する 2026-09-26 10:06:51 +09:00
routersys c7565227ac 処理器の試験を追加する 2026-09-26 10:05:56 +09:00
routersys 66719c3abe カスタムエフェクトの試験を追加する 2026-09-26 10:04:13 +09:00
routersys 4936c3a9ae 文言の試験を追加する 2026-09-26 10:02:11 +09:00
routersys ba337dc4a7 パラメータの試験を既存群の形で書き直す 2026-09-26 09:58:54 +09:00
routersys 5e2ae23015 入力寸法の変更後の描画を検証する 2026-09-26 09:56:52 +09:00
routersys 04e364b0a8 相互運用の試験を土台の上に書き直す 2026-09-26 09:55:15 +09:00
routersys 213b81e243 成長計算の試験を分ける 2026-09-26 09:54:12 +09:00
routersys 46c263807b 設定値の試験を分ける 2026-09-26 09:52:37 +09:00
routersys 042bed3b8a 試験の土台を追加する 2026-09-26 09:51:02 +09:00
routersys 5cec9a1ba7 テストプロジェクトの設定を既存群に揃える 2026-09-26 09:50:30 +09:00
routersys a91147e559 Stryker.NETで変異試験を行う 2026-09-26 09:49:48 +09:00
routersys 009d3c4e83 テストの依存関係を最新にする 2026-09-26 09:49:25 +09:00
routersys 19bc7aabb7 ルートファイルをSolution Itemsへ加える 2026-09-26 09:47:15 +09:00
routersys 211a0f1edf リリースノートへ分類の内訳節を加える 2026-09-26 09:46:47 +09:00
routersys 9a2892372a リリースワークフローを既存群と同一の構成にする 2026-09-26 09:46:21 +09:00
routersys 0787b9cd41 使われなくなったFxcPathの設定を取り除く 2026-09-26 09:45:21 +09:00
routersys 5a6e102f40 シェーダーの生成をCrystallineGrowth.Shaderへ切り出す 2026-09-26 09:44:42 +09:00
routersys 00da193819 Full HD出力置換直後の描画を検証する 2026-09-26 09:42:20 +09:00
routersys ff89a2e1a5 相互運用を外部提供者と共有テクスチャ集合へ移す 2026-09-26 09:41:28 +09:00
routersys 10fe9195d1 格子の資源を生成ホストの所有スロットへ移す 2026-09-26 09:36:35 +09:00
routersys 9e0e6c365b 管理メモリの試験を暖機の揺れに左右されない形にする 2026-09-26 09:35:08 +09:00
routersys f59bb17c67 ComputeWeaveを配布DLLへ統合し衝突を防ぐ
・配布物をCrystallineGrowth.dllの1つに統合-M
2026-09-26 09:26:52 +09:00
routersys 0162c41f4b ComputeSharpサブモジュールの登録を外す 2026-09-26 09:24:38 +09:00
routersys f466888eda ComputeWeaveをNuGet参照へ移行する 2026-09-26 09:23:56 +09:00
routersys 83a138f048 ハーネスへ構造再計算の内訳計測を統合する 2026-09-26 09:20:52 +09:00
routersys bee08d8f76 ハーネスを実機描画によるゴールデン検証基盤にする 2026-09-26 09:19:32 +09:00
routersys f9c1750ba1 Textsの名前空間をファイル形式にする 2026-09-26 00:29:50 +09:00
routersys 1410c50ff1 エディターのコード規則を追加する 2026-09-26 00:29:49 +09:00
routersys aa61c85985 プルリクエストのテンプレートを追加する 2026-09-23 13:57:59 +09:00
routersys 8ca76d1edc Issueのテンプレートを追加する 2026-09-23 13:57:58 +09:00
routersys 31d34b8191 スポンサーの設定を追加する 2026-09-23 13:57:58 +09:00
routersys f3f3b34443 貢献の手引きを追加する 2026-09-23 13:57:58 +09:00
routersys 3f8161d1f9 セキュリティポリシーを追加する 2026-09-23 13:57:57 +09:00
routersys c1977e4b41 行動規範を追加する 2026-09-23 13:57:57 +09:00
74個のファイルの変更、6468行の追加、1552行の削除

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

+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
-36
ファイルの表示
@@ -1,36 +0,0 @@
# v1.0.1 - 氷晶成長 for YMM4
氷晶成長エフェクトプラグインの改善リリースです。
成長計算のメモリアクセスを削減し、結晶の形と描画結果を一切変えずに、構造の再計算とフレームの描画を高速化しました。
出力は前バージョンと全画素で一致します。
---
## 改善
### 1. 付着フラグの拡散質量への埋め込み
成長格子の付着フラグを、独立した状態バッファーではなく拡散質量バッファーの符号として保持するようにしました。非付着セルの拡散質量は、凍結・付着・融解・ゆらぎのすべての演算で0以上に保たれるため、付着セルを負の値で表せます。
- 拡散シェーダーの近傍読み取りが、状態と質量の2バッファー×7セルから1バッファー×7セルへ半減しました。
- 状態バッファー2枚の確保、書き込み、同期バリアが不要になり、GPUメモリ使用量も減りました。
- 加算の値と順序は変えていないため、浮動小数点の丸めも含めて前バージョンと同一の結果になります。
### 2. 境界セル以外の質量アクセスの省略
成長更新シェーダーで、境界質量と結晶質量の読み書きを、結晶に隣接するセルだけに限定しました。付着は不可逆であるため、隣接する結晶セルを持たないセルの両質量は常に0であることが厳密に成り立ち、読み飛ばしても結果は変わりません。大多数のセルで1ステップあたり2回の読み取りと2回の書き込みが不要になります。
### 3. 性能
1280×720の素材、到達距離160画素での構造再計算の実測値です。結晶の形と描画画素数はすべての条件で前バージョンと一致します。
| 項目 | v1.0.0 | v1.0.1 |
|---|---:|---:|
| 標準の構造再計算 | 69ms | 36ms |
| 高品質の構造再計算 | 208ms | 115ms |
| 最高品質の構造再計算 | 496ms | 261ms |
| キャッシュ後のフレーム | 12.8ms | 7.1ms |
### 4. ゴールデンハッシュ検証モード
検証ハーネスへ`--golden`引数を追加しました。品質、シード、ゆらぎ0、部分凍結、板状、シダ状、短距離の8条件で出力全画素のSHA-256を出力し、変更の前後で結果が一致することを機械的に確認できます。本リリースの等価性はこのモードで検証しました。
+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
ファイルの表示
差分なしでファイル名を変更。
+90 -21
ファイルの表示
@@ -1,13 +1,17 @@
========================================
氷晶成長 for YMM4 v1.0.1
氷晶成長 for YMM4 v1.1.0
========================================
YukkuriMovieMaker4上で動作する、素材の輪郭を核形成点とみなし、
YukkuriMovieMaker4上で動作する、素材の縁を結晶の核とみなし、
Gravner–Griffeathの雪結晶成長モデルで氷晶を成長させて霜として描画する
映像エフェクトプラグインです。
氷晶の成長の計算に使う格子モデルは、Gravner and Griffeathの論文「Modeling
snow crystal growth II: A mesoscopic lattice map with plausible dynamics」
(Physica D、2008年)に基づきます。
履歴フレーム、参照画像、深度情報、学習済みモデルは使用しません。
氷晶の形はシードから決定論的に決まり、同じ設定では常に同じ形になります。
氷晶の形は素材とシードから決定論的に決まり、同じ設定では常に同じ形になります。
強さ、凍結度、樹枝化、ファセット、到達距離、ゆらぎ、白濁、屈折、光沢の
9項目はアニメーションに対応しています。
凍結度をアニメーションで変えると、素材が縁から凍りついていきます。
エフェクトの種類一覧では「氷晶成長」として表示されます。
--------------------------------------------------------------------------------
■ 動作要件
@@ -27,30 +31,53 @@ Gravner–Griffeathの雪結晶成長モデルで氷晶を成長させて霜と
Direct3D 11デバイスとの共有テクスチャおよび共有フェンスを作成できない
場合は、エフェクトを適用せず入力映像を表示します。
- 処理対象: 核形成点の判定には現在のフレームのアルファ値だけを使用します。
輝度と色は判定に影響しません。履歴フレーム、外部画像、深度情報、
学習済みモデルは使用しません。
- 処理対象: 核の判定には現在のフレームの不透明度だけを使用します。
輝度と色は判定に影響しません。セルは、成長を計算する格子の1つ1つの区画です。
不透明度が5%を超える画素が1つでもあるセルを素材の内側とし、
内側のセルのうち外側のセルと接するセルを核にします。
透明な部分の無い素材では、素材の四辺が縁になります。履歴フレーム、
外部画像、深度情報、学習済みモデルは使用しません。
- 計算領域: 素材の範囲に到達距離と描画の余白を加えた大きさを計算領域とし、
長辺は8192画素が上限です。素材が大きく余白を確保できない場合は、
エフェクトを適用せず入力映像を表示します。
- 計算領域: 透明な部分も含む素材全体の上下左右に、到達距離と80画素の
余白を加えた大きさを計算領域とします。到達距離と余白をそのまま加えると
計算領域の長辺が8192画素を超えるときは、縁から霜が広がる距離の上限を
設定より短くして計算します。ただし計算領域を決めるときは、
この上限を1セルの幅より短くせず、80画素の余白も必ず取ります。そのため、
計算領域の長辺は8192画素を超えることがあり、最大で8408画素になります。
素材の長辺が8160画素を超える場合は、エフェクトを適用せず入力映像を表示します。
- 処理負荷: 計算領域の大きさと品質に応じて処理量とGPUメモリ使用量が
増えます。最高品質は格子解像度と成長ステップ数が最も多いため、
高品質と標準より処理負荷が高くなります。描画は氷晶が存在する矩形の
範囲だけを計算します。
増えます。格子解像度は、成長を計算する格子の1セルの幅を決める数で、
大きいほど1セルが小さくなります。
最高品質は格子解像度と成長ステップ数の上限が最も大きいため、
高品質と標準より処理負荷が高くなります。描画は、凍結度で表示している
氷晶を囲む矩形の範囲だけで行います。
- キャッシュ: 素材の輪郭と結晶の形を決めるパラメータが変わらないフレームでは、
成長の計算を再利用します。
- キャッシュ: 素材の形と大きさ、品質、シード、樹枝化、ファセット、
到達距離、ゆらぎが変わらないフレームでは、成長の計算を再利用します。
ゆらぎが0%のときは、シードを変えても成長の計算を再利用します。
素材の形が変わったかどうかは、素材の内側とみなしたセルの並びで判定します。
不透明な動画のように形を保ったまま色だけが変わる素材では、
成長の計算を再利用し、氷の描画だけをやり直します。
成長の計算を再利用し、凍結度も変わらないまま氷の描き直しが続くときは、
描画の途中結果を氷のかかる画素だけGPUメモリに保存します。次からは、
保存した途中結果から描き直します。成長を計算し直すか凍結度が変わると、
保存した途中結果は破棄します。
強さ、凍結度、白濁、屈折、光沢、色だけを変えたフレームでは、成長を
計算し直しません。素材の形が変わるフレームと、樹枝化、ファセット、
到達距離、ゆらぎをアニメーションで変えたフレームでは、成長を毎回
計算し直すため、処理が重くなります。
- 凍結度0%と強さ0%: 凍結度が0%のときは何も描画しません。強さが0%のときは
入力を変更しません。
- シードと再現性: 氷晶の形は、シード、セル位置、成長ステップから
決定論的に算出します。時間値は結晶の生成に使用しません。
- シードと再現性: 氷晶の形は、素材の形と大きさ、パラメータ、シード、
セル位置、成長ステップから決定論的に算出します。
時間値は結晶の生成に使用しません。
- 透明部分: 霜は素材の外側にも描画されるため、出力範囲は素材より
広がります。氷は元映像の上へアルファ合成します。
- 透明部分: 氷は素材の外側にも描画されるため、出力範囲は素材より
広がります。素材の外側の氷は白濁が強いほど濃く見え、白濁が0%のときは
ほとんど見えません。氷は元映像の上へアルファ合成します。
- 更新通知: エフェクトを最初に生成したときに、YMM4の実行中に一度だけ
新しい正式版を確認します。更新情報を取得できない場合は通知せず、
@@ -58,6 +85,48 @@ Gravner–Griffeathの雪結晶成長モデルで氷晶を成長させて霜と
- 本プラグインを使用する前に、YMM4のプロジェクトファイルのバックアップを
作成することを推奨します。
--------------------------------------------------------------------------------
■ 不具合の報告
--------------------------------------------------------------------------------
本プラグインは、想定していない例外が起きたときに、その内容を開発者へ自動で
送信します。同意は求めず、常に送信します。
送信する情報は次のとおりです。
例外 : 型の完全名、メッセージ、スタックトレース
発生位置 : モジュール名、関数名、ファイル名、行番号
プラグイン : アセンブリ名、バージョン
実行環境 : OSの名前とバージョン、.NETのバージョン、
CPUのアーキテクチャ、論理プロセッサ数
識別子 : YMM4の起動ごとに決まるセッション識別子、報告ごとの識別子
映像の中身とプロジェクトの内容は送信しません。継続して個人を追跡する
識別子も持ちません。セッション識別子はYMM4を起動し直すと別の値に
なります。メッセージとファイル名に含まれる利用者名などの文字列は、送信の
前に置き換えます。送信元のIPアドレスは受信側へ渡す手前で取り除いています。
送信するのは想定していない例外だけです。YMM4が本プラグインのエフェクトを
作るとき、フレームごとに更新するとき、入力をつなぎ直すとき、破棄するときと、
Direct2Dがシェーダーの定数を書き込むときに起きた例外を報告し、その後は
YMM4へそのまま渡します。更新の確認で起きた例外は、更新情報の取得の失敗を
除いて報告し、YMM4へは渡しません。画面の操作やバックグラウンドの処理で
未処理になった例外も報告しますが、本プラグインのコードが関わる例外に
限ります。本プラグインの外で起きた例外は送信しません。
次の失敗は送信しません。
効果をかけないだけで済ませるもの : Direct3D 12デバイスを取得できない、
YMM4のDirect3D 11デバイスとの共有
テクスチャや共有フェンスを作成できない、
素材の長辺が8160画素を超えるときに、
エフェクトを適用せず入力映像を
表示したとき
更新の確認の通信の失敗 : GitHubへ接続できない
送信できなかった報告はYMM4のユーザーフォルダーへ退避します。
次にYMM4を起動したあと、本プラグインのエフェクトを生成するか、
同じくYMM4-Telemetryで報告する別のプラグインが動き始めると、
退避した報告を1回の起動で10件まで送り直します。
送信も再送も非同期に行うため、通信を待って起動と描画が遅くなることは
ありません。
--------------------------------------------------------------------------------
■ 免責事項
--------------------------------------------------------------------------------
@@ -71,9 +140,9 @@ Gravner–Griffeathの雪結晶成長モデルで氷晶を成長させて霜と
--------------------------------------------------------------------------------
■ サードパーティライセンス
--------------------------------------------------------------------------------
本プラグインは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 = "CrystallineGrowth/CrystallineGrowth.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 = "CrystallineGrowth/CrystallineGrowth.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 CrystallineGrowth.Shader/CrystallineGrowth.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 CrystallineGrowth.Tests/CrystallineGrowth.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 = "CrystallineGrowth/bin/x64/Release/net10.0-windows10.0.19041.0"
$version = "${{ steps.version.outputs.TAG }}"
$outDir = "CrystallineGrowth/bin/x64/Release/net10.0-windows10.0.19041.0"
$stageRoot = "stage/CrystallineGrowth"
$pkgName = "CrystallineGrowth_$version.ymme"
$pkgName = "CrystallineGrowth_$version.ymme"
New-Item -ItemType Directory -Path $stageRoot -Force | Out-Null
New-Item -ItemType Directory -Path "$stageRoot/LICENSE" -Force | Out-Null
Copy-Item "$outDir/CrystallineGrowth.dll" "$stageRoot/"
Copy-Item "$outDir/CrystallineGrowth.ComputeSharp.dll" "$stageRoot/"
Copy-Item "$outDir/CrystallineGrowth.ComputeSharp.Core.dll" "$stageRoot/"
$dll = "$outDir/plugin/CrystallineGrowth.dll"
if (-not (Test-Path $dll)) {
Write-Error "ビルド結果に CrystallineGrowth.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)に従うことを求めます。
サブモジュール ComputeSharp が 7c4145d5f2 から削除されました。
+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>CrystallineGrowth.Harness</AssemblyName>
<RootNamespace>CrystallineGrowth.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="..\CrystallineGrowth\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 CrystallineGrowth.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 CrystallineGrowth.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();
}
}
+93
ファイルの表示
@@ -0,0 +1,93 @@
namespace CrystallineGrowth.Harness;
internal sealed class HarnessException(string message) : Exception(message);
internal enum HarnessMode
{
Render,
Golden,
Verify,
Transition,
Compare,
Benchmark,
Structure,
}
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 <画像>] 描画を計測します
--structure 構造の再計算がパラメータごとに掛かる時間を内訳で計測します
""";
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 "--structure":
mode = Select(mode, HarnessMode.Structure);
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 つだけ指定してください。");
}
+72
ファイルの表示
@@ -0,0 +1,72 @@
using System.Globalization;
using System.Windows.Media;
using YukkuriMovieMaker.Commons;
using YukkuriMovieMaker.Json;
namespace CrystallineGrowth.Harness;
internal static class HarnessCases
{
public static IEnumerable<(string Name, CrystallineGrowthEffect Effect, IReadOnlyList<int> Frames)> All()
{
yield return ("default", Create(), [0]);
yield return ("default-frames-0-8", Create(), Enumerable.Range(0, 9).ToArray());
yield return ("amount-0", Create(effect => effect.Amount.Values[0].Value = 0), [0]);
yield return ("freeze-35", Create(effect => effect.Freeze.Values[0].Value = 35), [0]);
yield return ("quality-balanced", Create(effect => effect.Quality = CrystallineGrowthQuality.Balanced), [0]);
yield return ("quality-ultra", Create(effect => effect.Quality = CrystallineGrowthQuality.Ultra), [0]);
yield return ("branching-0", Create(effect => effect.Branching.Values[0].Value = 0), [0]);
yield return ("branching-100", Create(effect => effect.Branching.Values[0].Value = 100), [0]);
yield return ("facet-0", Create(effect => effect.Facet.Values[0].Value = 0), [0]);
yield return ("facet-100", Create(effect => effect.Facet.Values[0].Value = 100), [0]);
yield return ("reach-5", Create(effect => effect.Reach.Values[0].Value = 5), [0]);
yield return ("reach-100", Create(effect => effect.Reach.Values[0].Value = 100), [0]);
yield return ("noise-0", Create(effect => effect.Noise.Values[0].Value = 0), [0]);
yield return ("noise-100", Create(effect => effect.Noise.Values[0].Value = 100), [0]);
yield return ("frost-0", Create(effect => effect.Frost.Values[0].Value = 0), [0]);
yield return ("frost-100", Create(effect => effect.Frost.Values[0].Value = 100), [0]);
yield return ("refraction-0", Create(effect => effect.Refraction.Values[0].Value = 0), [0]);
yield return ("refraction-100", Create(effect => effect.Refraction.Values[0].Value = 100), [0]);
yield return ("specular-0", Create(effect => effect.Specular.Values[0].Value = 0), [0]);
yield return ("specular-100", Create(effect => effect.Specular.Values[0].Value = 100), [0]);
yield return ("seed-42", Create(effect => effect.Seed = 42), [0]);
yield return ("ice-color", Create(effect => effect.IceColor = Color.FromArgb(255, 200, 20, 20)), [0]);
}
public static IEnumerable<(string Name, Func<CrystallineGrowthEffect> Create, Action<CrystallineGrowthEffect> Change, int Frame)> Transitions()
{
yield return ("freeze-100-to-35", () => Create(), effect => effect.Freeze.Values[0].Value = 35, 0);
yield return ("quality-high-to-ultra", () => Create(), effect => effect.Quality = CrystallineGrowthQuality.Ultra, 0);
yield return ("branching-60-to-100", () => Create(), effect => effect.Branching.Values[0].Value = 100, 0);
yield return ("facet-40-to-100", () => Create(), effect => effect.Facet.Values[0].Value = 100, 0);
yield return ("reach-25-to-100", () => Create(), effect => effect.Reach.Values[0].Value = 100, 0);
yield return ("noise-25-to-100", () => Create(), effect => effect.Noise.Values[0].Value = 100, 0);
yield return ("frost-70-to-100", () => Create(), effect => effect.Frost.Values[0].Value = 100, 0);
yield return ("refraction-40-to-100", () => Create(), effect => effect.Refraction.Values[0].Value = 100, 0);
yield return ("specular-50-to-100", () => Create(), effect => effect.Specular.Values[0].Value = 100, 0);
yield return ("seed-0-to-42", () => Create(), effect => effect.Seed = 42, 0);
yield return ("ice-color-change", () => Create(), effect => effect.IceColor = Color.FromArgb(255, 200, 20, 20), 0);
yield return ("amount-100-to-0", () => Create(), effect => effect.Amount.Values[0].Value = 0, 0);
}
public static IEnumerable<(string Name, CrystallineGrowthEffect Effect)> Benchmarks()
{
yield return ("quality-balanced", Create(effect => effect.Quality = CrystallineGrowthQuality.Balanced));
yield return ("default", Create());
yield return ("quality-ultra", Create(effect => effect.Quality = CrystallineGrowthQuality.Ultra));
yield return ("reach-100", Create(effect => effect.Reach.Values[0].Value = 100));
yield return ("freeze-animated", Create(effect => effect.Freeze.CopyFrom(Linear(50d, 100d))));
yield return ("frost-animated", Create(effect => effect.Frost.CopyFrom(Linear(0d, 100d))));
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 CrystallineGrowthEffect Create(Action<CrystallineGrowthEffect>? configure = null)
{
var effect = new CrystallineGrowthEffect();
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 CrystallineGrowth.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 CrystallineGrowth.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 CrystallineGrowth.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 CrystallineGrowth.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);
}
}
+396 -154
ファイルの表示
@@ -1,202 +1,444 @@
using System.Diagnostics;
using ComputeSharp;
using System.IO;
using System.IO.Packaging;
using System.Security.Cryptography;
using ComputeWeave;
using CrystallineGrowth;
using CrystallineGrowth.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 = 640;
const int ImageHeight = 480;
const int FullHdWidth = 1920;
const int FullHdHeight = 1080;
using var pipeline = CrystallineGrowthPipeline.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];
if (args.Contains("--golden"))
try
{
var goldenCases = new (string Name, CrystallineGrowthPipeline.Parameters Parameters)[]
if (arguments.Mode == HarnessMode.Compare)
return Compare(arguments.Before!, arguments.After!);
if (arguments.Mode == HarnessMode.Structure)
{
("balanced-default", new(CrystallineGrowthQuality.Balanced, 1f, 0.6f, 0.4f, 120f, 0.25f, 0.7f, 0.4f, 0.5f, 0.8f, 0.89f, 1f, 7)),
("high-default", new(CrystallineGrowthQuality.High, 1f, 0.6f, 0.4f, 120f, 0.25f, 0.7f, 0.4f, 0.5f, 0.8f, 0.89f, 1f, 7)),
("noise-zero", new(CrystallineGrowthQuality.Balanced, 1f, 0.6f, 0.4f, 120f, 0f, 0.7f, 0.4f, 0.5f, 0.8f, 0.89f, 1f, 3)),
("seed-42", new(CrystallineGrowthQuality.Balanced, 1f, 0.6f, 0.4f, 120f, 0.5f, 0.7f, 0.4f, 0.5f, 0.8f, 0.89f, 1f, 42)),
("partial-freeze", new(CrystallineGrowthQuality.Balanced, 0.35f, 0.6f, 0.4f, 120f, 0.25f, 0.7f, 0.4f, 0.5f, 0.8f, 0.89f, 1f, 7)),
("plate", new(CrystallineGrowthQuality.Balanced, 1f, 0.1f, 0.9f, 120f, 0.25f, 0.7f, 0.4f, 0.5f, 0.8f, 0.89f, 1f, 7)),
("fern", new(CrystallineGrowthQuality.Balanced, 1f, 1f, 0.1f, 120f, 0.25f, 1f, 1f, 1f, 0.8f, 0.89f, 1f, 7)),
("short-reach", new(CrystallineGrowthQuality.Balanced, 1f, 0.6f, 0.4f, 24f, 0.25f, 0.7f, 0.4f, 0.5f, 0.8f, 0.89f, 1f, 7)),
};
foreach (var (name, goldenParameters) in goldenCases)
{
var parameters = goldenParameters;
pipeline.Process(source, destination, width, height, in parameters);
var bytes = new byte[destination.Length * sizeof(int)];
Buffer.BlockCopy(destination, 0, bytes, 0, bytes.Length);
Console.WriteLine($"{name}: {Convert.ToHexString(System.Security.Cryptography.SHA256.HashData(bytes))}");
var structureImage = arguments.Input is { } structureInput ? HarnessImage.Load(structureInput) : HarnessImage.Synthetic(CanvasWidth, CanvasHeight);
return Structure(structureImage);
}
var outputDirectory = arguments.OutputDirectory ?? Path.Combine(AppContext.BaseDirectory, "harness-output");
if (arguments.Mode == HarnessMode.Benchmark)
{
if (arguments.Input is { } benchmarkInput)
{
Benchmark(HarnessImage.Load(benchmarkInput));
}
else
{
Benchmark(HarnessImage.Synthetic(CanvasWidth, CanvasHeight));
Benchmark(HarnessImage.Synthetic(FullHdWidth, FullHdHeight));
}
return 0;
}
var image = arguments.Input is { } input ? HarnessImage.Load(input) : HarnessImage.Synthetic(ImageWidth, ImageHeight);
using var renderer = new HarnessRenderer(CanvasWidth, CanvasHeight, image);
return arguments.Mode switch
{
HarnessMode.Golden => WriteGolden(renderer, image),
HarnessMode.Verify => Verify(renderer, image),
HarnessMode.Transition => Transition(renderer, outputDirectory),
_ => Render(renderer, outputDirectory),
};
}
catch (Exception exception) when (exception is HarnessException or SharpGenException)
{
Console.Error.WriteLine(exception.Message);
return 2;
}
static int Render(HarnessRenderer renderer, string outputDirectory)
{
Directory.CreateDirectory(outputDirectory);
var failures = 0;
var cases = Evaluate(renderer, (golden, files, frames) =>
{
Console.WriteLine($"{golden.Name}: {golden.Hash}");
for (var index = 0; index < files.Length; index++)
{
HarnessImage.Save(Path.Combine(outputDirectory, files[index]), frames[index], renderer.CanvasWidth, renderer.CanvasHeight);
var opaque = CountOpaque(frames[index]);
Console.WriteLine($" {files[index]} opaque={opaque}");
if (opaque == 0)
{
Console.Error.WriteLine($"{files[index]}: 出力が完全に透明です。");
failures++;
}
}
});
Console.WriteLine($"-> {outputDirectory}");
return failures + CountDuplicates(cases) == 0 ? 0 : 1;
}
static int WriteGolden(HarnessRenderer renderer, HarnessImage image)
{
var cases = Evaluate(renderer, null);
if (CountDuplicates(cases) != 0)
return 1;
if (cases.Count == 0)
Console.Error.WriteLine("ケースがありません。HarnessCases に書き足してください。");
var golden = new Golden(renderer.Adapter, renderer.Driver, image.Identity, $"{renderer.CanvasWidth}x{renderer.CanvasHeight}", cases);
var path = Golden.PathFor(image);
golden.Save(path);
Console.WriteLine($"adapter: {golden.Adapter} (driver {golden.Driver})");
Console.WriteLine($"input: {golden.Input}");
foreach (var (name, _, hash) in cases)
Console.WriteLine($"{name}: {hash}");
Console.WriteLine($"-> {path}");
return 0;
}
foreach (var quality in new[] { CrystallineGrowthQuality.Balanced, CrystallineGrowthQuality.High, CrystallineGrowthQuality.Ultra })
static int Verify(HarnessRenderer renderer, HarnessImage image)
{
var parameters = new CrystallineGrowthPipeline.Parameters(quality, 1f, 0.6f, 0.4f, 160f, 0.25f, 0.7f, 0.4f, 0.5f, 0.8f, 0.89f, 1f, 7);
pipeline.Process(source, destination, width, height, in parameters);
pipeline.Process(source, destination, width, height, in parameters);
var stopwatch = Stopwatch.StartNew();
const int frames = 5;
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}) litPixels={CountLit(destination)}");
var golden = Golden.Load(Golden.PathFor(image));
var canvas = $"{renderer.CanvasWidth}x{renderer.CanvasHeight}";
if (golden.Input != image.Identity || golden.Canvas != canvas)
{
Console.Error.WriteLine($"基準値は入力 {golden.Input} とキャンバス {golden.Canvas} で書かれています。今回は入力 {image.Identity} とキャンバス {canvas} です。");
return 1;
}
if (golden.Adapter != renderer.Adapter || golden.Driver != renderer.Driver)
Console.Error.WriteLine($"基準値は {golden.Adapter} (driver {golden.Driver}) で書かれています。今回は {renderer.Adapter} (driver {renderer.Driver}) です。画素の差はこの違いから来ることがあります。");
var failures = 0;
var current = Evaluate(renderer, null).ToDictionary(item => item.Name, StringComparer.Ordinal);
if (golden.Cases.Count == 0 && current.Count == 0)
Console.Error.WriteLine("ケースがありません。HarnessCases に書き足してください。");
foreach (var (name, frames, hash) in golden.Cases)
{
if (!current.Remove(name, out var actual))
{
Console.Error.WriteLine($"{name}: ケースがありません。基準値を書き直してください。");
failures++;
}
else if (!actual.Frames.SequenceEqual(frames))
{
Console.Error.WriteLine($"{name}: フレームが違います。基準値 [{string.Join(", ", frames)}]、今回 [{string.Join(", ", actual.Frames)}]。基準値を書き直してください。");
failures++;
}
else if (actual.Hash != hash)
{
Console.Error.WriteLine($"{name}: 一致しません。基準値 {hash}、今回 {actual.Hash}");
failures++;
}
else
{
Console.WriteLine($"{name}: 一致");
}
}
foreach (var name in current.Keys)
{
Console.Error.WriteLine($"{name}: 基準値にありません。基準値を書き直してください。");
failures++;
}
return failures == 0 ? 0 : 1;
}
static int Transition(HarnessRenderer renderer, string outputDirectory)
{
var failures = 0;
foreach (var (name, create, change, frame) in HarnessCases.Transitions())
{
var (direct, transitioned) = renderer.RenderTransition(create, change, frame);
var difference = ImageComparison.Of(direct, transitioned, renderer.CanvasWidth, renderer.CanvasHeight);
if (difference.IsEmpty)
{
Console.WriteLine($"{name}: 一致");
continue;
}
failures++;
Directory.CreateDirectory(outputDirectory);
HarnessImage.Save(Path.Combine(outputDirectory, name + "-direct.png"), direct, renderer.CanvasWidth, renderer.CanvasHeight);
HarnessImage.Save(Path.Combine(outputDirectory, name + "-transitioned.png"), transitioned, renderer.CanvasWidth, renderer.CanvasHeight);
Console.Error.WriteLine($"{name}: {difference}。設定を変えた後の描画が作り直した場合と違います。-> {outputDirectory}");
}
if (!HarnessCases.Transitions().Any() && !HarnessCases.All().Any(item => item.Frames.Count > 1))
Console.Error.WriteLine("ケースがありません。HarnessCases に書き足してください。");
foreach (var (name, effect, frames) in HarnessCases.All())
{
if (frames.Count < 2)
continue;
var sequential = renderer.Render(effect, frames);
for (var index = 0; index < frames.Count; index++)
{
var fresh = renderer.Render(effect, [frames[index]])[0];
var difference = ImageComparison.Of(fresh, sequential[index], renderer.CanvasWidth, renderer.CanvasHeight);
var label = $"{name}-f{frames[index]:D3}";
if (difference.IsEmpty)
{
Console.WriteLine($"{label}: 一致");
continue;
}
failures++;
Directory.CreateDirectory(outputDirectory);
HarnessImage.Save(Path.Combine(outputDirectory, label + "-direct.png"), fresh, renderer.CanvasWidth, renderer.CanvasHeight);
HarnessImage.Save(Path.Combine(outputDirectory, label + "-transitioned.png"), sequential[index], renderer.CanvasWidth, renderer.CanvasHeight);
Console.Error.WriteLine($"{label}: {difference}。前のフレームから進めた描画が作り直した場合と違います。-> {outputDirectory}");
}
}
return failures == 0 ? 0 : 1;
}
static int Structure(HarnessImage image)
{
const int Rounds = 12;
const int Seed = 17;
const int RectFrames = 20;
using var pipeline = CrystallineGrowthPipeline.TryCreate();
if (pipeline is null)
throw new HarnessException("Direct3D 12を利用できません。");
var device = GraphicsDevice.GetDefault();
using var sourceTexture = device.AllocateReadWriteTexture2D<Bgra32, Float4>(width, height);
var pixels = new Bgra32[source.Length];
for (var index = 0; index < source.Length; index++)
pixels[index].PackedValue = unchecked((uint)source[index]);
using var sourceTexture = device.AllocateReadWriteTexture2D<Bgra32, Float4>(image.Width, image.Height);
var pixels = new Bgra32[image.Width * image.Height];
for (var index = 0; index < pixels.Length; index++)
{
var offset = index * HarnessImage.BytesPerPixel;
pixels[index] = new Bgra32(image.Pixels[offset + 2], image.Pixels[offset + 1], image.Pixels[offset], image.Pixels[offset + 3]);
}
sourceTexture.CopyFrom(pixels);
var parameters = new CrystallineGrowthPipeline.Parameters(CrystallineGrowthQuality.High, 1f, 0.6f, 0.4f, 160f, 0.25f, 0.7f, 0.4f, 0.5f, 0.8f, 0.89f, 1f, 7);
pipeline.Simulate(sourceTexture, image.Width, image.Height, 0, 0, image.Width, image.Height, in parameters, hashSource: true);
pipeline.WaitForCompletion();
var stopwatch = new Stopwatch();
pipeline.Simulate(sourceTexture, width, height, 0, 0, width, height, in parameters);
var stopwatch = Stopwatch.StartNew();
pipeline.Simulate(sourceTexture, width, height, 0, 0, width, height, parameters with { Seed = 8 });
stopwatch.Stop();
Console.WriteLine($"structure recompute: {stopwatch.Elapsed.TotalMilliseconds:F2} ms");
var variants = new (string Name, Func<bool, CrystallineGrowthPipeline.Parameters> Make)[]
{
("cached", _ => parameters),
("branching", flip => parameters with { Branching = flip ? 0.70f : 0.60f }),
("facet", flip => parameters with { Facet = flip ? 0.50f : 0.40f }),
("reach", flip => parameters with { ReachPixels = flip ? 176f : 160f }),
("noise", flip => parameters with { Noise = flip ? 0.35f : 0.25f }),
("seed", flip => parameters with { Seed = flip ? 8 : 7 }),
("all", flip => parameters with
{
Branching = flip ? 0.70f : 0.60f,
Facet = flip ? 0.50f : 0.40f,
ReachPixels = flip ? 176f : 160f,
Noise = flip ? 0.35f : 0.25f,
Seed = flip ? 8 : 7,
}),
};
if (pipeline.TryGetVisibleBounds(width, height, in parameters, out var rect))
var samples = new List<double>[variants.Length];
for (var index = 0; index < samples.Length; index++)
samples[index] = new List<double>(Rounds);
foreach (var (_, make) in variants)
{
var warmup = make(true);
pipeline.Simulate(sourceTexture, image.Width, image.Height, 0, 0, image.Width, image.Height, in warmup, hashSource: true);
pipeline.WaitForCompletion();
}
var order = Enumerable.Range(0, variants.Length).ToArray();
var random = new Random(Seed);
for (var round = 0; round < Rounds; round++)
{
for (var index = order.Length - 1; index > 0; index--)
{
var swap = random.Next(index + 1);
(order[index], order[swap]) = (order[swap], order[index]);
}
foreach (var index in order)
{
var settled = variants[index].Make(false);
pipeline.Simulate(sourceTexture, image.Width, image.Height, 0, 0, image.Width, image.Height, in settled, hashSource: true);
pipeline.WaitForCompletion();
var measured = variants[index].Make(true);
stopwatch.Restart();
pipeline.Simulate(sourceTexture, image.Width, image.Height, 0, 0, image.Width, image.Height, in measured, hashSource: true);
pipeline.WaitForCompletion();
stopwatch.Stop();
samples[index].Add(stopwatch.Elapsed.TotalMilliseconds);
}
}
Console.WriteLine($"structure recompute over {Rounds} interleaved rounds (ms)");
for (var index = 0; index < variants.Length; index++)
{
var sorted = samples[index].OrderBy(static value => value).ToArray();
var median = sorted[sorted.Length / 2];
Console.WriteLine($" {variants[index].Name,-11} min={sorted[0],7:F2} median={median,7:F2} max={sorted[^1],7:F2}");
}
if (pipeline.TryGetVisibleBounds(image.Width, image.Height, in parameters, out var rect))
{
using var rectOutput = device.AllocateReadWriteTexture2D<Bgra32, Float4>(rect.Width, rect.Height);
pipeline.RenderVisible(sourceTexture, rectOutput, width, height, 0, 0, width, height, rect, in parameters);
pipeline.RenderVisible(sourceTexture, rectOutput, image.Width, image.Height, 0, 0, image.Width, image.Height, rect, in parameters);
pipeline.WaitForCompletion();
stopwatch.Restart();
const int rectFrames = 20;
for (var frame = 0; frame < rectFrames; frame++)
for (var frame = 0; frame < RectFrames; frame++)
{
pipeline.Simulate(sourceTexture, width, height, 0, 0, width, height, in parameters);
pipeline.TryGetVisibleBounds(width, height, in parameters, out rect);
pipeline.RenderVisible(sourceTexture, rectOutput, width, height, 0, 0, width, height, rect, in parameters);
pipeline.Simulate(sourceTexture, image.Width, image.Height, 0, 0, image.Width, image.Height, in parameters, hashSource: true);
pipeline.TryGetVisibleBounds(image.Width, image.Height, in parameters, out rect);
pipeline.RenderVisible(sourceTexture, rectOutput, image.Width, image.Height, 0, 0, image.Width, image.Height, rect, in parameters);
}
pipeline.WaitForCompletion();
stopwatch.Stop();
Console.WriteLine($"cached frame with rect {rect.Width}x{rect.Height} at ({rect.X},{rect.Y}): {stopwatch.Elapsed.TotalMilliseconds / rectFrames:F2} ms/frame");
Console.WriteLine($"cached frame with rect {rect.Width}x{rect.Height} at ({rect.X},{rect.Y}): {stopwatch.Elapsed.TotalMilliseconds / RectFrames:F2} ms/frame");
}
return 0;
}
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));
}
}
foreach (var freeze in new[] { 0.25f, 0.5f, 0.75f, 1f })
{
var parameters = new CrystallineGrowthPipeline.Parameters(CrystallineGrowthQuality.High, freeze, 0.6f, 0.4f, 160f, 0.25f, 0.7f, 0.4f, 0.5f, 0.8f, 0.89f, 1f, 7);
pipeline.Process(source, destination, width, height, in parameters);
Console.WriteLine($"freeze={freeze:F2} litPixels={CountLit(destination)}");
WriteBmp(Path.Combine(outputDirectory, $"freeze{(int)(freeze * 100):D3}.bmp"), Composite(source, destination), width, height);
}
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}");
foreach (var branching in new[] { 0f, 0.5f, 1f })
static List<GoldenCase> Evaluate(HarnessRenderer renderer, Action<GoldenCase, string[], byte[][]>? report)
{
var parameters = new CrystallineGrowthPipeline.Parameters(CrystallineGrowthQuality.High, 1f, branching, 0.4f, 160f, 0.25f, 0.7f, 0.4f, 0.5f, 0.8f, 0.89f, 1f, 7);
pipeline.Process(source, destination, width, height, in parameters);
Console.WriteLine($"branching={branching:F2} litPixels={CountLit(destination)}");
WriteBmp(Path.Combine(outputDirectory, $"branching{(int)(branching * 100):D3}.bmp"), Composite(source, destination), width, height);
}
foreach (var facet in new[] { 0f, 0.5f, 1f })
{
var parameters = new CrystallineGrowthPipeline.Parameters(CrystallineGrowthQuality.High, 1f, 0.6f, facet, 160f, 0.25f, 0.7f, 0.4f, 0.5f, 0.8f, 0.89f, 1f, 7);
pipeline.Process(source, destination, width, height, in parameters);
Console.WriteLine($"facet={facet:F2} litPixels={CountLit(destination)}");
WriteBmp(Path.Combine(outputDirectory, $"facet{(int)(facet * 100):D3}.bmp"), Composite(source, destination), width, height);
}
WriteBmp(Path.Combine(outputDirectory, "source.bmp"), source, width, height);
Console.WriteLine($"images written to {outputDirectory}");
return 0;
static int[] CreateTestImage(int width, int height)
{
var pixels = new int[width * height];
var left = width / 2 - 100;
var top = height / 2 - 40;
for (var y = top; y < top + 80; y++)
var cases = new List<GoldenCase>();
var names = new HashSet<string>(StringComparer.Ordinal);
foreach (var (name, effect, frames) in HarnessCases.All())
{
for (var x = left; x < left + 200; x++)
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++)
{
if (x < 0 || x >= width || y < 0 || y >= height)
continue;
pixels[y * width + x] = unchecked((int)0xFFB0B0B8);
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 pixels;
return duplicates;
}
static int CountLit(int[] pixels)
static int CountOpaque(byte[] pixels)
{
var count = 0;
foreach (var pixel in pixels)
for (var offset = HarnessImage.BytesPerPixel - 1; offset < pixels.Length; offset += HarnessImage.BytesPerPixel)
{
if (((pixel >> 24) & 255) > 8)
if (pixels[offset] != 0)
count++;
}
return count;
}
static int[] Composite(int[] source, int[] ice)
{
var result = new int[source.Length];
for (var index = 0; index < source.Length; index++)
{
var s = source[index];
var i = ice[index];
var sa = (s >> 24) & 255;
var ia = (i >> 24) & 255;
var a = Math.Min(ia + sa * (255 - ia) / 255, 255);
var r = Over((s >> 16) & 255, (i >> 16) & 255, ia);
var g = Over((s >> 8) & 255, (i >> 8) & 255, ia);
var b = Over(s & 255, i & 255, ia);
result[index] = a << 24 | r << 16 | g << 8 | b;
}
return result;
static int Over(int s, int i, int ia) => Math.Min(i + s * (255 - ia) / 255, 255);
}
static void WriteBmp(string path, int[] pixels, int width, int height)
{
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--)
{
for (var x = 0; x < width; x++)
{
var pixel = pixels[y * width + x];
writer.Write((byte)(pixel & 255));
writer.Write((byte)((pixel >> 8) & 255));
writer.Write((byte)((pixel >> 16) & 255));
}
writer.Write(pad);
}
}
+51
ファイルの表示
@@ -0,0 +1,51 @@
namespace CrystallineGrowth.Harness;
internal static class SyntheticImage
{
const int GridPitch = 32;
public static byte[] Create(int width, int height)
{
var pixels = new byte[width * height * HarnessImage.BytesPerPixel];
var plateLeft = width * 0.10f;
var plateRight = width * 0.56f;
var plateTop = height * 0.14f;
var plateBottom = height * 0.86f;
var discCenterX = width * 0.70f;
var discCenterY = height * 0.50f;
var discRadius = MathF.Min(width, height) * 0.28f;
for (var y = 0; y < height; y++)
{
for (var x = 0; x < width; x++)
{
var positionX = x + 0.5f;
var positionY = y + 0.5f;
var plateInset = MathF.Min(MathF.Min(positionX - plateLeft, plateRight - positionX), MathF.Min(positionY - plateTop, plateBottom - positionY));
var plateCoverage = Math.Clamp(plateInset + 0.5f, 0f, 1f);
var distance = MathF.Sqrt((positionX - discCenterX) * (positionX - discCenterX) + (positionY - discCenterY) * (positionY - discCenterY));
var discCoverage = Math.Clamp(discRadius - distance + 0.5f, 0f, 1f);
if (plateCoverage == 0f && discCoverage == 0f)
continue;
var onGrid = x % GridPitch == 0 || y % GridPitch == 0;
var plateWeight = plateCoverage * (1f - discCoverage);
var shade = 1f - distance / discRadius * 0.5f;
var red = (onGrid ? 0.25f : 0.82f) * plateWeight + 0.90f * shade * discCoverage;
var green = (onGrid ? 0.30f : 0.86f) * plateWeight + 0.45f * shade * discCoverage;
var blue = (onGrid ? 0.40f : 0.90f) * plateWeight + 0.30f * shade * discCoverage;
var alpha = plateWeight + discCoverage;
var offset = (y * width + x) * HarnessImage.BytesPerPixel;
pixels[offset] = ToByte(blue);
pixels[offset + 1] = ToByte(green);
pixels[offset + 2] = ToByte(red);
pixels[offset + 3] = ToByte(alpha);
}
}
return pixels;
}
static byte ToByte(float premultiplied) => (byte)MathF.Round(Math.Clamp(premultiplied, 0f, 1f) * byte.MaxValue);
}
+170
ファイルの表示
@@ -0,0 +1,170 @@
{
"adapter": "Intel(R) Iris(R) Xe Graphics",
"driver": "32.0.101.7085",
"input": "synthetic 640x480 89838D8976198E40",
"canvas": "1280x720",
"cases": [
{
"name": "default",
"frames": [
0
],
"hash": "210C12219713DE34867BC8CF9F78A58767396AEBC87FCFE0A1B04EFB22C6C7F4"
},
{
"name": "default-frames-0-8",
"frames": [
0,
1,
2,
3,
4,
5,
6,
7,
8
],
"hash": "8AF8E9DB2C66DCFE5B8E0A1E0B17D13A02EB0DECBA383767E8DBD04D6F53143A"
},
{
"name": "amount-0",
"frames": [
0
],
"hash": "0A700F76CEDDBAD7C4B6A2C19D46939C1A93940E86C6EFEF1E5A53DB48D2A020"
},
{
"name": "freeze-35",
"frames": [
0
],
"hash": "28E31C3C654681F9DEC715B77EA9DAE94B12A747E45137123E2544D1544AA624"
},
{
"name": "quality-balanced",
"frames": [
0
],
"hash": "F52B24AC4C97AA4BECAB5244748B74614902316E410DE339B3CABBCCE375705F"
},
{
"name": "quality-ultra",
"frames": [
0
],
"hash": "4F764786416A7256A0F2416969A9F38E1A229AB3CEEB8600D41E148047AB18BF"
},
{
"name": "branching-0",
"frames": [
0
],
"hash": "B9B41301B660EEED1AD52416782F641CD9E8078D804F12AF91056DC27AB50070"
},
{
"name": "branching-100",
"frames": [
0
],
"hash": "DCB5160636A3683133909F6715688342926F2AF70045E060F8DA7732B3EFC160"
},
{
"name": "facet-0",
"frames": [
0
],
"hash": "82A8C571BE22FC35CC8DD949B81D0F2C5D147EC5C114232C1A47FF21C3646D29"
},
{
"name": "facet-100",
"frames": [
0
],
"hash": "FCDF06EF5FC74ABD3E917E2EB8EFFBA2743883891FCE0EE0122E9E1909E3CEBD"
},
{
"name": "reach-5",
"frames": [
0
],
"hash": "21D53360473EE6D20C3A33DE3E3CEA187C76B35F5CF0E19EE867C0DD924C51AA"
},
{
"name": "reach-100",
"frames": [
0
],
"hash": "8E10427FDDC041C96C24455C983F99689B9453379A22CF17AE8A74FC65871D7B"
},
{
"name": "noise-0",
"frames": [
0
],
"hash": "8646E1A2A020990AA90DFF180E4C157ED7CA957E2DEE2E0DD935BCEEA54D15BD"
},
{
"name": "noise-100",
"frames": [
0
],
"hash": "AA8B002F93AE3B6BFB1790337B8BC6538C90DA574853CA1150C8B15059E4F338"
},
{
"name": "frost-0",
"frames": [
0
],
"hash": "D2C2C8A028A5DABD41986967B015F942932783F477C590ED450EC0DAD6348D79"
},
{
"name": "frost-100",
"frames": [
0
],
"hash": "A154469F100620089380470266B9C081A1D07C3AE4953803E8948FF077959B9E"
},
{
"name": "refraction-0",
"frames": [
0
],
"hash": "C42D5AFFD77E1F6B98A0CEAD762C899156332E8EEE0E3DDDF1F5A8F8998B9E40"
},
{
"name": "refraction-100",
"frames": [
0
],
"hash": "BDDA610B1C963CC4DCBCFDB7DE327CCEFCC89A49E2EF3C68D28E42F67D19DB41"
},
{
"name": "specular-0",
"frames": [
0
],
"hash": "D63F025CFAB9F511DD343EF857B4E4A882F35BF7BC30DBFFCEF70FAA64982870"
},
{
"name": "specular-100",
"frames": [
0
],
"hash": "0C8512F652702C2D62BF91EC352A24DAE7545156C7C343C4294D8572271EC177"
},
{
"name": "seed-42",
"frames": [
0
],
"hash": "C490055DA37F8A539EE6035EAF93B092B9D3A08593C44954E1D2EBCB13819107"
},
{
"name": "ice-color",
"frames": [
0
],
"hash": "A369732D04849CDA78173E2D4FB39F6AAC35FC1CD62E0944B8B1C3DE79A82B78"
}
]
}
+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>{14BDAE0A-C2B1-473E-A90C-2AC115506780}</ProjectGuid>
<RootNamespace>CrystallineGrowthShader</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="CrystallineGrowth.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="CrystallineGrowth.hlsl">
<Filter>ソース ファイル</Filter>
</FxCompile>
</ItemGroup>
</Project>
差分なしでファイル名を変更。
+12
ファイルの表示
@@ -0,0 +1,12 @@
namespace CrystallineGrowth.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);
}
+28 -12
ファイルの表示
@@ -2,6 +2,7 @@
<PropertyGroup>
<TargetFramework>net10.0-windows10.0.19041.0</TargetFramework>
<UseWPF>true</UseWPF>
<ImplicitUsings>enable</ImplicitUsings>
<Nullable>enable</Nullable>
<IsPackable>false</IsPackable>
@@ -12,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="..\CrystallineGrowth\CrystallineGrowth.csproj" SetConfiguration="Configuration=$(Configuration)" SetPlatform="Platform=x64">
<ProjectReference Include="..\CrystallineGrowth\CrystallineGrowth.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="..\CrystallineGrowth\ComputeSharp.Reference.props" />
</Project>
+160
ファイルの表示
@@ -0,0 +1,160 @@
using System.Numerics;
using Vortice.Direct2D1;
using Vortice.Direct2D1.Effects;
using YukkuriMovieMaker.Commons;
namespace CrystallineGrowth.Tests;
[Collection("Direct2D")]
public sealed class CrystallineGrowthCustomEffectTests
{
const int AmountIndex = 0;
const int Width = 40;
const int Height = 24;
static readonly Bgra Blue = Bgra.Opaque(255, 0, 0);
static readonly Bgra HalfIce = new(224, 192, 160, 128);
static Rendering Render(IGraphicsDevicesAndContext devices, ID2D1Image source, ID2D1Image ice, float amount)
{
using var effect = new CrystallineGrowthCustomEffect(devices);
effect.SetInput(0, source, true);
effect.SetInput(1, ice, 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 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 Over(Bgra ice, Bgra source, float amount)
{
var iceAlpha = ice.Alpha * amount;
var keep = 1d - iceAlpha / byte.MaxValue;
byte Channel(byte iceValue, byte sourceValue) => (byte)Math.Round(iceValue * amount + sourceValue * keep, MidpointRounding.AwayFromZero);
return new Bgra(Channel(ice.Blue, source.Blue), Channel(ice.Green, source.Green), Channel(ice.Red, source.Red), Channel(ice.Alpha, source.Alpha));
}
[Fact]
public void TheEffectIsEnabledOnceCreated()
{
using var devices = new GraphicsDevices();
using var context = devices.CreateContext();
using var effect = new CrystallineGrowthCustomEffect(context);
Assert.True(effect.IsEnabled);
}
[Fact]
public void TheAmountStartsFromZero()
{
using var devices = new GraphicsDevices();
using var context = devices.CreateContext();
using var effect = new CrystallineGrowthCustomEffect(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 CrystallineGrowthCustomEffect(context);
effect.Amount = value;
Assert.Equal(expected, effect.GetFloatValue(AmountIndex));
}
[Fact]
public void TheOutputBoundsCoverTheSourceAndTheIce()
{
using var devices = new GraphicsDevices();
using var context = devices.CreateContext();
using var source = SourceImage.Solid(context, Width, Height, Blue);
using var ice = SourceImage.Solid(context, 8, 8, HalfIce);
using var moved = Translate(context, ice.Bitmap, 50f, -6f);
using var movedOutput = moved.Output;
using var effect = new CrystallineGrowthCustomEffect(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(-6f, bounds.Top);
Assert.Equal(58f, 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 ice = SourceImage.Solid(context, Width, Height, HalfIce);
var rendering = Render(context, source.Bitmap, ice.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 TheIceIsLaidOverTheSourceScaledByTheAmount(float amount)
{
using var devices = new GraphicsDevices();
using var context = devices.CreateContext();
using var source = SourceImage.Solid(context, Width, Height, Blue);
using var ice = SourceImage.Solid(context, Width, Height, HalfIce);
var expected = Over(HalfIce.Premultiplied(), Blue.Premultiplied(), amount);
var rendering = Render(context, source.Bitmap, ice.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 IceOutsideTheSourceIsDrawnOnItsOwn()
{
using var devices = new GraphicsDevices();
using var context = devices.CreateContext();
using var source = SourceImage.Solid(context, Width, Height, Blue);
using var ice = SourceImage.Solid(context, 8, 8, HalfIce);
using var moved = Translate(context, ice.Bitmap, 50f, 4f);
using var movedOutput = moved.Output;
var expected = Over(HalfIce.Premultiplied(), Bgra.Transparent, 1f);
var rendering = Render(context, source.Bitmap, movedOutput, 1f);
Assert.True(WithinRounding(expected, rendering[53, 7]), $"{rendering[53, 7]}");
Assert.Equal(Blue.Premultiplied(), rendering[10, 10]);
Assert.Equal(Bgra.Transparent, rendering[45, 10]);
}
}
+502
ファイルの表示
@@ -0,0 +1,502 @@
using System.Globalization;
using System.Numerics;
using System.Windows.Media;
using ComputeWeave;
using Vortice.Direct2D1;
using Vortice.Direct2D1.Effects;
using YukkuriMovieMaker.Commons;
using YukkuriMovieMaker.Json;
using YukkuriMovieMaker.Player.Video;
namespace CrystallineGrowth.Tests;
[Collection("Direct2D")]
public sealed class CrystallineGrowthEffectProcessorTests
{
const int Size = 64;
const int Length = 30;
static readonly Bgra Gray = Bgra.Opaque(192, 192, 192);
static readonly Bgra Red = Bgra.Opaque(0, 0, 255);
static readonly Bgra Green = Bgra.Opaque(0, 160, 0);
static Bgra CenteredSquare(int x, int y) => x is >= 16 and < 48 && y is >= 16 and < 48 ? Gray : 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 = CrystallineGrowthInteropProvider.TryCreate(devices, scheduler, out var device);
if (provider is null || device is null)
Assert.Skip("Direct3D 11 and Direct3D 12 sharing is unavailable.");
}
static Animation Linear(double from, double to)
=> Json.LoadFromText<Animation>(string.Create(CultureInfo.InvariantCulture, $$"""{"AnimationType":"直線移動","Values":[{"Value":{{from}}},{"Value":{{to}}}]}"""))!;
static Rendering RenderFrame(IGraphicsDevicesAndContext devices, IVideoEffectProcessor processor, int frame)
{
processor.Update(EffectDescriptions.At(frame, Length));
return Rendering.Capture(devices, processor.Output);
}
static void AssertSameAsSource(Rendering rendering, SourceImage source)
{
Assert.Equal((0, 0, source.Width, source.Height), (rendering.Left, rendering.Top, rendering.Width, rendering.Height));
Assert.All(rendering.Coordinates(), point => Assert.Equal(source[point.X, point.Y], rendering[point.X, point.Y]));
}
static bool HasFrostOutside(Rendering rendering, SourceImage source)
=> rendering.Coordinates().Any(point => (!source.Contains(point.X, point.Y) || source[point.X, point.Y].Alpha == 0) && rendering[point.X, point.Y].Alpha > 0);
static bool Tinted(byte channel, byte alpha, byte color) => Math.Abs(channel - color * alpha / 255d) <= 2d;
static double DistanceFrom(SourceImage source, int x, int y)
{
var dx = Math.Max(Math.Max(-x, x - (source.Width - 1)), 0);
var dy = Math.Max(Math.Max(-y, y - (source.Height - 1)), 0);
return Math.Sqrt(dx * dx + dy * dy);
}
[Fact]
public void TheProcessorHandsTheDrawDescriptionBackUnchanged()
{
using var devices = new GraphicsDevices();
using var context = devices.CreateContext();
using var source = new SourceImage(context, Size, Size, CenteredSquare);
using var processor = new CrystallineGrowthEffect().CreateVideoEffect(context);
processor.SetInput(source.Bitmap);
var description = EffectDescriptions.At(0, Length);
var draw = processor.Update(description);
Assert.Same(description.DrawDescription, draw);
}
[Fact]
public void TheFrostGrowsOutOfTheSource()
{
using var devices = new GraphicsDevices();
using var context = devices.CreateContext();
RequireInterop(context);
using var source = new SourceImage(context, Size, Size, CenteredSquare);
using var processor = new CrystallineGrowthEffect().CreateVideoEffect(context);
processor.SetInput(source.Bitmap);
var rendering = RenderFrame(context, processor, 0);
Assert.True(HasFrostOutside(rendering, source));
Assert.All(rendering.Coordinates(), point =>
{
var pixel = rendering[point.X, point.Y];
Assert.InRange(pixel.Blue, 0, pixel.Alpha);
Assert.InRange(pixel.Green, 0, pixel.Alpha);
Assert.InRange(pixel.Red, 0, pixel.Alpha);
});
}
[Fact]
public void TheFrostTakesTheChosenColor()
{
using var devices = new GraphicsDevices();
using var context = devices.CreateContext();
RequireInterop(context);
using var source = new SourceImage(context, Size, Size, CenteredSquare);
var effect = new CrystallineGrowthEffect { IceColor = Color.FromRgb(32, 96, 160) };
effect.Refraction.Values[0].Value = 0d;
effect.Specular.Values[0].Value = 0d;
using var processor = effect.CreateVideoEffect(context);
processor.SetInput(source.Bitmap);
var rendering = RenderFrame(context, processor, 0);
Assert.True(HasFrostOutside(rendering, source));
Assert.All(rendering.Coordinates().Where(point => !source.Contains(point.X, point.Y) || source[point.X, point.Y].Alpha == 0), point =>
{
var pixel = rendering[point.X, point.Y];
Assert.True(Tinted(pixel.Red, pixel.Alpha, 32) && Tinted(pixel.Green, pixel.Alpha, 96) && Tinted(pixel.Blue, pixel.Alpha, 160), $"({point.X}, {point.Y}) {pixel}");
});
}
[Theory]
[InlineData(100, 50)]
[InlineData(-37, 21)]
public void TheFrostTravelsWithTheImage(int dx, int dy)
{
using var devices = new GraphicsDevices();
using var context = devices.CreateContext();
RequireInterop(context);
using var source = new SourceImage(context, Size, Size, CenteredSquare);
using var moved = new AffineTransform2D(context.DeviceContext)
{
InterPolationMode = AffineTransform2DInterpolationMode.NearestNeighbor,
BorderMode = BorderMode.Hard,
TransformMatrix = Matrix3x2.CreateTranslation(dx, dy),
};
moved.SetInput(0, source.Bitmap, true);
using var movedOutput = moved.Output;
using var inPlaceProcessor = new CrystallineGrowthEffect().CreateVideoEffect(context);
inPlaceProcessor.SetInput(source.Bitmap);
var inPlace = RenderFrame(context, inPlaceProcessor, 0);
using var travelledProcessor = new CrystallineGrowthEffect().CreateVideoEffect(context);
travelledProcessor.SetInput(movedOutput);
var travelled = RenderFrame(context, travelledProcessor, 0);
Assert.Equal((inPlace.Left + dx, inPlace.Top + dy, inPlace.Width, inPlace.Height), (travelled.Left, travelled.Top, travelled.Width, travelled.Height));
Assert.All(inPlace.Coordinates(), point => Assert.True(inPlace[point.X, point.Y] == travelled[point.X + dx, point.Y + dy], $"({point.X}, {point.Y})"));
}
[Fact]
public void TheReachIsMeasuredAgainstTheLongSideOfTheImage()
{
using var devices = new GraphicsDevices();
using var context = devices.CreateContext();
RequireInterop(context);
using var source = SourceImage.Solid(context, 96, 24, Gray);
var effect = new CrystallineGrowthEffect();
effect.Reach.Values[0].Value = 25d;
using var processor = effect.CreateVideoEffect(context);
processor.SetInput(source.Bitmap);
var rendering = RenderFrame(context, processor, 0);
var distances = rendering.Coordinates()
.Where(point => !source.Contains(point.X, point.Y) && rendering[point.X, point.Y].Alpha > 0)
.Select(point => DistanceFrom(source, point.X, point.Y))
.ToArray();
Assert.Contains(distances, distance => distance > 12d);
Assert.All(distances, distance => Assert.True(distance <= 30d, $"{distance}"));
}
public static readonly TheoryData<string, Action<CrystallineGrowthEffect>> PassThroughSettings = new()
{
{ nameof(CrystallineGrowthEffect.Amount), effect => effect.Amount.Values[0].Value = 0d },
{ nameof(CrystallineGrowthEffect.Freeze), effect => effect.Freeze.Values[0].Value = 0d },
};
[Theory]
[MemberData(nameof(PassThroughSettings))]
public void AZeroAmountOrFreezePassesTheImageThrough(string setting, Action<CrystallineGrowthEffect> configure)
{
using var devices = new GraphicsDevices();
using var context = devices.CreateContext();
using var source = new SourceImage(context, Size, Size, CenteredSquare);
var effect = new CrystallineGrowthEffect();
configure(effect);
using var processor = effect.CreateVideoEffect(context);
processor.SetInput(source.Bitmap);
var rendering = RenderFrame(context, processor, 0);
Assert.Equal((0, 0, Size, Size), (rendering.Left, rendering.Top, rendering.Width, rendering.Height));
Assert.All(rendering.Coordinates(), point => Assert.True(source[point.X, point.Y] == rendering[point.X, point.Y], $"{setting} ({point.X}, {point.Y})"));
}
[Fact]
public void AnImageThatLeavesNoRoomForTheFrostPassesThroughUntouched()
{
using var devices = new GraphicsDevices();
using var context = devices.CreateContext();
using var source = SourceImage.Solid(context, CrystallineGrowthSettings.MaximumCanvasSize - 16, 8, Gray);
using var processor = new CrystallineGrowthEffect().CreateVideoEffect(context);
processor.SetInput(source.Bitmap);
var rendering = RenderFrame(context, processor, 0);
AssertSameAsSource(rendering, source);
}
[Theory]
[InlineData(CrystallineGrowthQuality.Balanced, 8000)]
[InlineData(CrystallineGrowthQuality.Balanced, 8160)]
[InlineData(CrystallineGrowthQuality.High, 8160)]
[InlineData(CrystallineGrowthQuality.Ultra, 8160)]
public void TheFrostOfAVeryLongImageFadesOutBeforeTheEdgeOfTheCanvas(CrystallineGrowthQuality quality, int width)
{
using var devices = new GraphicsDevices();
using var context = devices.CreateContext();
RequireInterop(context);
using var source = SourceImage.Solid(context, width, 24, Gray);
using var processor = new CrystallineGrowthEffect { Quality = quality }.CreateVideoEffect(context);
processor.SetInput(source.Bitmap);
var rendering = RenderFrame(context, processor, 0);
var litAtTheEdge = rendering.Coordinates()
.Where(point => point.X == rendering.Left || point.X == rendering.Right - 1 || point.Y == rendering.Top || point.Y == rendering.Bottom - 1)
.Where(point => rendering[point.X, point.Y].Alpha > 0)
.ToArray();
Assert.True(HasFrostOutside(rendering, source));
Assert.Empty(litAtTheEdge);
}
[Fact]
public void ReturningToAFrameReproducesItExactly()
{
using var devices = new GraphicsDevices();
using var context = devices.CreateContext();
RequireInterop(context);
using var source = new SourceImage(context, Size, Size, CenteredSquare);
using var processor = new CrystallineGrowthEffect().CreateVideoEffect(context);
processor.SetInput(source.Bitmap);
var first = RenderFrame(context, processor, 4);
RenderFrame(context, processor, 9);
var again = RenderFrame(context, processor, 4);
Assert.True(first.SamePixelsAs(again));
}
[Fact]
public void ANewProcessorDrawsTheSameFrost()
{
using var devices = new GraphicsDevices();
using var context = devices.CreateContext();
RequireInterop(context);
using var source = new SourceImage(context, Size, Size, CenteredSquare);
var effect = new CrystallineGrowthEffect { Seed = 9 };
using var firstProcessor = effect.CreateVideoEffect(context);
firstProcessor.SetInput(source.Bitmap);
var first = RenderFrame(context, firstProcessor, 0);
using var secondProcessor = effect.CreateVideoEffect(context);
secondProcessor.SetInput(source.Bitmap);
var second = RenderFrame(context, secondProcessor, 0);
Assert.True(first.SamePixelsAs(second));
}
[Fact]
public void AnimatedFreezeIsReadAtEachFrame()
{
using var devices = new GraphicsDevices();
using var context = devices.CreateContext();
RequireInterop(context);
using var source = new SourceImage(context, Size, Size, CenteredSquare);
var effect = new CrystallineGrowthEffect();
effect.Freeze.CopyFrom(Linear(0d, 100d));
using var processor = effect.CreateVideoEffect(context);
processor.SetInput(source.Bitmap);
var start = RenderFrame(context, processor, 0);
var end = RenderFrame(context, processor, Length - 1);
AssertSameAsSource(start, source);
Assert.True(HasFrostOutside(end, source));
}
[Theory]
[InlineData(100d, 30d)]
[InlineData(30d, 100d)]
public void AProcessorThatDrewAnotherFreezeDrawsLikeAFreshOne(double firstFreeze, double secondFreeze)
{
using var devices = new GraphicsDevices();
using var context = devices.CreateContext();
RequireInterop(context);
using var source = new SourceImage(context, Size, Size, CenteredSquare);
var effect = new CrystallineGrowthEffect();
effect.Freeze.Values[0].Value = firstFreeze;
using var processor = effect.CreateVideoEffect(context);
processor.SetInput(source.Bitmap);
RenderFrame(context, processor, 0);
effect.Freeze.Values[0].Value = secondFreeze;
using var fresh = effect.CreateVideoEffect(context);
fresh.SetInput(source.Bitmap);
var expected = RenderFrame(context, fresh, 0);
var reused = RenderFrame(context, processor, 0);
Assert.True(reused.SamePixelsAs(expected));
}
public static readonly TheoryData<string, Action<CrystallineGrowthEffect>> LaterChanges = new()
{
{ nameof(CrystallineGrowthEffect.Amount), effect => effect.Amount.Values[0].Value = 50d },
{ nameof(CrystallineGrowthEffect.Freeze), effect => effect.Freeze.Values[0].Value = 30d },
{ nameof(CrystallineGrowthEffect.Quality), effect => effect.Quality = CrystallineGrowthQuality.Balanced },
{ nameof(CrystallineGrowthEffect.Branching), effect => effect.Branching.Values[0].Value = 100d },
{ nameof(CrystallineGrowthEffect.Facet), effect => effect.Facet.Values[0].Value = 100d },
{ nameof(CrystallineGrowthEffect.Reach), effect => effect.Reach.Values[0].Value = 10d },
{ nameof(CrystallineGrowthEffect.Noise), effect => effect.Noise.Values[0].Value = 100d },
{ nameof(CrystallineGrowthEffect.Seed), effect => effect.Seed = 1 },
{ nameof(CrystallineGrowthEffect.Frost), effect => effect.Frost.Values[0].Value = 100d },
{ nameof(CrystallineGrowthEffect.Refraction), effect => effect.Refraction.Values[0].Value = 100d },
{ nameof(CrystallineGrowthEffect.Specular), effect => effect.Specular.Values[0].Value = 100d },
{ nameof(CrystallineGrowthEffect.IceColor), effect => effect.IceColor = Colors.Crimson },
};
[Theory]
[MemberData(nameof(LaterChanges))]
public void EverySettingChangedAfterTheFirstFrameReachesTheEffect(string setting, Action<CrystallineGrowthEffect> change)
{
using var devices = new GraphicsDevices();
using var context = devices.CreateContext();
RequireInterop(context);
using var source = new SourceImage(context, Size, Size, CenteredSquare);
var effect = new CrystallineGrowthEffect();
using var processor = effect.CreateVideoEffect(context);
processor.SetInput(source.Bitmap);
var before = RenderFrame(context, processor, 0);
change(effect);
var after = RenderFrame(context, processor, 0);
Assert.False(before.SamePixelsAs(after), setting);
}
[Theory]
[InlineData(32, 128)]
[InlineData(128, 32)]
public void AResizedSourceKeepsProducingFrost(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) => Gray);
using var second = new SourceImage(context, secondSize, secondSize, (x, y) => Gray);
using var processor = new CrystallineGrowthEffect().CreateVideoEffect(context);
processor.SetInput(first.Bitmap);
var before = RenderFrame(context, processor, 0);
processor.SetInput(second.Bitmap);
var after = RenderFrame(context, processor, 0);
Assert.True(HasFrostOutside(before, first));
Assert.True(HasFrostOutside(after, second));
Assert.Equal(secondSize > firstSize, after.Width > before.Width);
}
[Theory]
[InlineData(false)]
[InlineData(true)]
public void FrostAppearsOnceATransparentSourceTakesShape(bool frostWasDrawnBefore)
{
using var devices = new GraphicsDevices();
using var context = devices.CreateContext();
RequireInterop(context);
using var empty = SourceImage.Solid(context, Size, Size, Bgra.Transparent);
using var source = new SourceImage(context, Size, Size, CenteredSquare);
using var processor = new CrystallineGrowthEffect().CreateVideoEffect(context);
if (frostWasDrawnBefore)
{
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.False(HasFrostOutside(before, empty));
Assert.True(HasFrostOutside(after, source));
}
[Fact]
public void ARecoloredImageIsDrawnLikeAFreshOne()
{
using var devices = new GraphicsDevices();
using var context = devices.CreateContext();
RequireInterop(context);
using var red = new SourceImage(context, Size, Size, Filled(Red));
using var green = new SourceImage(context, Size, Size, Filled(Green));
var effect = new CrystallineGrowthEffect();
using var processor = effect.CreateVideoEffect(context);
processor.SetInput(red.Bitmap);
RenderFrame(context, processor, 0);
using var fresh = effect.CreateVideoEffect(context);
fresh.SetInput(green.Bitmap);
var expected = RenderFrame(context, fresh, 0);
processor.SetInput(green.Bitmap);
var recolored = RenderFrame(context, processor, 0);
Assert.True(recolored.SamePixelsAs(expected));
}
[Fact]
public void AnImageRestoredAfterASettingChangeIsDrawnLikeAFreshOne()
{
using var devices = new GraphicsDevices();
using var context = devices.CreateContext();
RequireInterop(context);
using var red = new SourceImage(context, Size, Size, Filled(Red));
using var green = new SourceImage(context, Size, Size, Filled(Green));
var effect = new CrystallineGrowthEffect();
using var processor = effect.CreateVideoEffect(context);
processor.SetInput(red.Bitmap);
RenderFrame(context, processor, 0);
RenderFrame(context, processor, 0);
effect.Frost.Values[0].Value = 100d;
processor.SetInput(green.Bitmap);
RenderFrame(context, processor, 0);
using var fresh = effect.CreateVideoEffect(context);
fresh.SetInput(red.Bitmap);
var expected = RenderFrame(context, fresh, 0);
processor.SetInput(red.Bitmap);
var restored = RenderFrame(context, processor, 0);
Assert.True(restored.SamePixelsAs(expected));
}
[Fact]
public void FrostChangedFrameAfterFrameIsDrawnLikeAFreshOne()
{
using var devices = new GraphicsDevices();
using var context = devices.CreateContext();
RequireInterop(context);
using var source = new SourceImage(context, Size, Size, CenteredSquare);
var effect = new CrystallineGrowthEffect();
using var processor = effect.CreateVideoEffect(context);
processor.SetInput(source.Bitmap);
foreach (var frost in new[] { 70d, 80d, 90d, 100d, 40d })
{
effect.Frost.Values[0].Value = frost;
var reused = RenderFrame(context, processor, 0);
using var fresh = effect.CreateVideoEffect(context);
fresh.SetInput(source.Bitmap);
var expected = RenderFrame(context, fresh, 0);
Assert.True(reused.SamePixelsAs(expected), $"{frost}");
}
}
[Fact]
public void AnImageRecoloredFrameAfterFrameIsDrawnLikeAFreshOne()
{
using var devices = new GraphicsDevices();
using var context = devices.CreateContext();
RequireInterop(context);
using var red = new SourceImage(context, Size, Size, Filled(Red));
using var green = new SourceImage(context, Size, Size, Filled(Green));
using var gray = new SourceImage(context, Size, Size, Filled(Gray));
var effect = new CrystallineGrowthEffect();
using var processor = effect.CreateVideoEffect(context);
foreach (var (name, source) in new[] { ("red", red), ("green", green), ("gray", gray), ("red", red), ("green", green) })
{
processor.SetInput(source.Bitmap);
var reused = RenderFrame(context, processor, 0);
using var fresh = effect.CreateVideoEffect(context);
fresh.SetInput(source.Bitmap);
var expected = RenderFrame(context, fresh, 0);
Assert.True(reused.SamePixelsAs(expected), name);
}
}
[Fact]
public void AFailureWhileUpdatingIsNotSwallowed()
{
using var devices = new GraphicsDevices();
using var context = devices.CreateContext();
using var processor = new CrystallineGrowthEffect().CreateVideoEffect(context);
Assert.ThrowsAny<Exception>(() => processor.Update(null!));
}
}
+180 -575
ファイルの表示
@@ -1,49 +1,57 @@
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 System.Windows.Media;
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 CrystallineGrowth.Tests;
public sealed class CrystallineGrowthEffectTests
{
private static double ValueAt(YukkuriMovieMaker.Commons.Animation animation) => animation.GetValue(0, 1, 30);
static readonly Color DefaultIceColor = Color.FromArgb(255, 205, 228, 255);
private static CrystallineGrowthPipeline.Parameters CreateParameters(
CrystallineGrowthQuality quality = CrystallineGrowthQuality.Balanced,
float freeze = 1f,
float branching = 0.6f,
float facet = 0.4f,
float reachPixels = 40f,
float noise = 0.25f,
float frost = 0.7f,
float refraction = 0.4f,
float specular = 0.5f,
int seed = 0)
=> new(quality, freeze, branching, facet, reachPixels, noise, frost, refraction, specular, 0.8f, 0.89f, 1f, seed);
static PropertyInfo Property(string name) => typeof(CrystallineGrowthEffect).GetProperty(name)!;
static T Attribute<T>(string property) where T : Attribute => Property(property).GetCustomAttribute<T>()!;
static Animation[] Animations(CrystallineGrowthEffect effect)
=> [effect.Amount, effect.Freeze, effect.Branching, effect.Facet, effect.Reach, effect.Noise, effect.Frost, effect.Refraction, effect.Specular];
[Theory]
[InlineData(nameof(CrystallineGrowthEffect.Amount), 100d, 0d, 100d)]
[InlineData(nameof(CrystallineGrowthEffect.Freeze), 100d, 0d, 100d)]
[InlineData(nameof(CrystallineGrowthEffect.Branching), 60d, 0d, 100d)]
[InlineData(nameof(CrystallineGrowthEffect.Facet), 40d, 0d, 100d)]
[InlineData(nameof(CrystallineGrowthEffect.Reach), 25d, 1d, 400d)]
[InlineData(nameof(CrystallineGrowthEffect.Noise), 25d, 0d, 100d)]
[InlineData(nameof(CrystallineGrowthEffect.Frost), 70d, 0d, 100d)]
[InlineData(nameof(CrystallineGrowthEffect.Refraction), 40d, 0d, 100d)]
[InlineData(nameof(CrystallineGrowthEffect.Specular), 50d, 0d, 100d)]
public void AnimatedParametersStartFromTheirDefaultsWithinTheirRange(string name, double defaultValue, double minimum, double maximum)
{
var effect = new CrystallineGrowthEffect();
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 QualitySeedAndIceColorStartFromTheirDefaults()
{
var effect = new CrystallineGrowthEffect();
Assert.Equal(100d, ValueAt(effect.Amount), 6);
Assert.Equal(100d, ValueAt(effect.Freeze), 6);
Assert.Equal(60d, ValueAt(effect.Branching), 6);
Assert.Equal(40d, ValueAt(effect.Facet), 6);
Assert.Equal(25d, ValueAt(effect.Reach), 6);
Assert.Equal(25d, ValueAt(effect.Noise), 6);
Assert.Equal(70d, ValueAt(effect.Frost), 6);
Assert.Equal(40d, ValueAt(effect.Refraction), 6);
Assert.Equal(50d, ValueAt(effect.Specular), 6);
Assert.Equal(CrystallineGrowthQuality.High, effect.Quality);
Assert.Equal(0, effect.Seed);
Assert.Equal(System.Windows.Media.Color.FromArgb(255, 205, 228, 255), effect.IceColor);
Assert.Equal(DefaultIceColor, effect.IceColor);
}
[Theory]
@@ -51,594 +59,191 @@ public sealed class CrystallineGrowthEffectTests
[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 CrystallineGrowthEffect { Seed = input };
var effect = new CrystallineGrowthEffect { Seed = 5 };
effect.Seed = value;
Assert.Equal(expected, effect.Seed);
Assert.False(effect.HasErrors);
}
[Fact]
public void CreateExoVideoFiltersReturnsEmpty()
public void ChangingQualitySeedOrIceColorNotifiesTheEditor()
{
var effect = new CrystallineGrowthEffect();
var changed = new List<string?>();
effect.PropertyChanged += (_, e) => changed.Add(e.PropertyName);
effect.Quality = CrystallineGrowthQuality.Ultra;
effect.Seed = 7;
effect.IceColor = Colors.Crimson;
Assert.Equal([nameof(CrystallineGrowthEffect.Quality), nameof(CrystallineGrowthEffect.Seed), nameof(CrystallineGrowthEffect.IceColor)], changed);
}
[Fact]
public void AssigningAnUnchangedOrClampedValueDoesNotNotify()
{
var effect = new CrystallineGrowthEffect();
var changed = new List<string?>();
effect.PropertyChanged += (_, e) => changed.Add(e.PropertyName);
effect.Quality = CrystallineGrowthQuality.High;
effect.Seed = 0;
effect.Seed = -1;
effect.IceColor = DefaultIceColor;
Assert.Empty(changed);
}
[Fact]
public void TheLabelIsTheLocalizedEffectName()
{
var effect = new CrystallineGrowthEffect();
Assert.Empty(effect.CreateExoVideoFilters(0, null!));
Assert.Equal(Texts.CrystallineGrowth, effect.Label);
}
[Fact]
public void TheNineNumericParametersReceiveTheAnimationParameters()
{
var effect = new CrystallineGrowthEffect();
effect.SetAnimationParameters(120, EffectDescriptions.Fps);
Assert.All(Animations(effect), animation => Assert.Equal(120, animation.Length));
}
[Theory]
[InlineData(CrystallineGrowthQuality.Balanced, 192, 1200)]
[InlineData(CrystallineGrowthQuality.High, 288, 2048)]
[InlineData(CrystallineGrowthQuality.Ultra, 384, 3072)]
public void QualitySettingsMatchSpecification(CrystallineGrowthQuality quality, int resolution, int maxSteps)
[InlineData(0)]
[InlineData(1)]
[InlineData(int.MaxValue)]
public void NoExoFilterIsWrittenForAviUtl(int keyFrameIndex)
{
var settings = CrystallineGrowthSettings.GetQuality(quality);
var effect = new CrystallineGrowthEffect();
Assert.Equal(resolution, settings.GridResolution);
Assert.Equal(maxSteps, settings.MaxSteps);
var description = new ExoOutputDescription(new VideoInfo(), string.Empty, new AviUtlDirectories(string.Empty, string.Empty));
Assert.Empty(effect.CreateExoVideoFilters(keyFrameIndex, description));
}
[Fact]
public void TheEffectIsRegisteredForDecorationAndAnimationWithoutAviUtlSupport()
{
var attribute = typeof(CrystallineGrowthEffect).GetCustomAttribute<VideoEffectAttribute>()!;
Assert.Equal(nameof(Texts.CrystallineGrowth), attribute.Name);
Assert.Equal([VideoEffectCategories.Decoration, VideoEffectCategories.Animation], attribute.Categories);
Assert.Equal([nameof(Texts.TagIce), nameof(Texts.TagFrost), nameof(Texts.TagFreeze)], attribute.Keywords);
Assert.False(attribute.IsAviUtlSupported);
Assert.True(attribute.IsEffectItemSupported);
Assert.Equal(typeof(Texts), attribute.ResourceType);
Assert.Equal(Texts.CrystallineGrowth, attribute.GetName());
}
[Theory]
[InlineData(1920, 1080, 288)]
[InlineData(1080, 1920, 288)]
[InlineData(8, 8, 288)]
[InlineData(4096, 16, 192)]
[InlineData(100, 100, 384)]
public void GridSizeCoversCanvas(int width, int height, int resolution)
[InlineData(nameof(CrystallineGrowthEffect.Amount), nameof(Texts.BasicGroup), nameof(Texts.Amount), nameof(Texts.AmountDescription), 0)]
[InlineData(nameof(CrystallineGrowthEffect.Freeze), nameof(Texts.BasicGroup), nameof(Texts.Freeze), nameof(Texts.FreezeDescription), 1)]
[InlineData(nameof(CrystallineGrowthEffect.Quality), nameof(Texts.BasicGroup), nameof(Texts.Quality), nameof(Texts.QualityDescription), 2)]
[InlineData(nameof(CrystallineGrowthEffect.Branching), nameof(Texts.GrowthGroup), nameof(Texts.Branching), nameof(Texts.BranchingDescription), 10)]
[InlineData(nameof(CrystallineGrowthEffect.Facet), nameof(Texts.GrowthGroup), nameof(Texts.Facet), nameof(Texts.FacetDescription), 11)]
[InlineData(nameof(CrystallineGrowthEffect.Reach), nameof(Texts.GrowthGroup), nameof(Texts.Reach), nameof(Texts.ReachDescription), 12)]
[InlineData(nameof(CrystallineGrowthEffect.Noise), nameof(Texts.GrowthGroup), nameof(Texts.Noise), nameof(Texts.NoiseDescription), 13)]
[InlineData(nameof(CrystallineGrowthEffect.Seed), nameof(Texts.GrowthGroup), nameof(Texts.Seed), nameof(Texts.SeedDescription), 14)]
[InlineData(nameof(CrystallineGrowthEffect.Frost), nameof(Texts.AppearanceGroup), nameof(Texts.Frost), nameof(Texts.FrostDescription), 20)]
[InlineData(nameof(CrystallineGrowthEffect.Refraction), nameof(Texts.AppearanceGroup), nameof(Texts.Refraction), nameof(Texts.RefractionDescription), 21)]
[InlineData(nameof(CrystallineGrowthEffect.Specular), nameof(Texts.AppearanceGroup), nameof(Texts.Specular), nameof(Texts.SpecularDescription), 22)]
[InlineData(nameof(CrystallineGrowthEffect.IceColor), nameof(Texts.AppearanceGroup), nameof(Texts.IceColor), nameof(Texts.IceColorDescription), 23)]
public void EveryParameterIsDisplayedInItsGroupInOrder(string property, string group, string name, string description, int order)
{
var (gridWidth, gridHeight, cellSize) = CrystallineGrowthSettings.GetGridSize(width, height, resolution);
var display = Attribute<DisplayAttribute>(property);
Assert.True(gridWidth >= CrystallineGrowthSettings.MinimumGridSize);
Assert.True(gridHeight >= CrystallineGrowthSettings.MinimumGridSize);
Assert.True(cellSize > 0f);
Assert.True(gridWidth * cellSize >= width);
Assert.True(gridHeight * cellSize * CrystallineGrowthSettings.RowStep >= height);
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(0f, 1200, 192)]
[InlineData(10f, 1200, 368)]
[InlineData(60f, 2048, 1568)]
[InlineData(500f, 2048, 2048)]
[InlineData(500f, 1200, 1200)]
public void StepCountScalesWithReachAndRespectsCap(float reachCells, int maxSteps, int expected)
[InlineData(nameof(CrystallineGrowthEffect.Amount), 0d, 100d)]
[InlineData(nameof(CrystallineGrowthEffect.Freeze), 0d, 100d)]
[InlineData(nameof(CrystallineGrowthEffect.Branching), 0d, 100d)]
[InlineData(nameof(CrystallineGrowthEffect.Facet), 0d, 100d)]
[InlineData(nameof(CrystallineGrowthEffect.Reach), 5d, 100d)]
[InlineData(nameof(CrystallineGrowthEffect.Noise), 0d, 100d)]
[InlineData(nameof(CrystallineGrowthEffect.Frost), 0d, 100d)]
[InlineData(nameof(CrystallineGrowthEffect.Refraction), 0d, 100d)]
[InlineData(nameof(CrystallineGrowthEffect.Specular), 0d, 100d)]
public void AnimatedParametersAreEditedAsPercentagesWithAnimationSliders(string property, double minimum, double maximum)
{
Assert.Equal(expected, CrystallineGrowthSettings.GetStepCount(reachCells, maxSteps));
var slider = Attribute<AnimationSliderAttribute>(property);
Assert.Equal("F1", slider.StringFormat);
Assert.Equal("%", slider.UnitText);
Assert.Equal(minimum, slider.DefaultMin);
Assert.Equal(maximum, slider.DefaultMax);
}
[Fact]
public void ParameterMappingsAreMonotonicAndBounded()
public void TheQualityIsChosenFromACombo()
{
Assert.Equal(CrystallineGrowthSettings.MinimumVaporDensity, CrystallineGrowthSettings.GetVaporDensity(0f), 5);
Assert.Equal(CrystallineGrowthSettings.MaximumVaporDensity, CrystallineGrowthSettings.GetVaporDensity(1f), 5);
Assert.Equal(CrystallineGrowthSettings.MinimumVaporDensity, CrystallineGrowthSettings.GetVaporDensity(-5f), 5);
Assert.Equal(CrystallineGrowthSettings.MaximumVaporDensity, CrystallineGrowthSettings.GetVaporDensity(5f), 5);
Assert.True(CrystallineGrowthSettings.GetVaporDensity(0.75f) > CrystallineGrowthSettings.GetVaporDensity(0.25f));
Assert.Equal(CrystallineGrowthSettings.MinimumBeta, CrystallineGrowthSettings.GetAttachmentThreshold(0f), 5);
Assert.Equal(CrystallineGrowthSettings.MaximumBeta, CrystallineGrowthSettings.GetAttachmentThreshold(1f), 5);
Assert.True(CrystallineGrowthSettings.GetAttachmentThreshold(0.75f) > CrystallineGrowthSettings.GetAttachmentThreshold(0.25f));
Assert.Equal(0f, CrystallineGrowthSettings.GetNoiseSigma(0f), 7);
Assert.Equal(CrystallineGrowthSettings.MaximumSigma, CrystallineGrowthSettings.GetNoiseSigma(1f), 7);
Assert.Equal(0f, CrystallineGrowthSettings.GetNoiseSigma(-1f), 7);
Assert.Equal(CrystallineGrowthSettings.MaximumSigma, CrystallineGrowthSettings.GetNoiseSigma(2f), 7);
Assert.NotNull(Attribute<EnumComboBoxAttribute>(nameof(CrystallineGrowthEffect.Quality)));
Assert.Equal([CrystallineGrowthQuality.Balanced, CrystallineGrowthQuality.High, CrystallineGrowthQuality.Ultra], Enum.GetValues<CrystallineGrowthQuality>());
}
[Theory]
[InlineData(1, 1, 1)]
[InlineData(2, 2, 1)]
[InlineData(3, 3, 2)]
[InlineData(256, 128, 8)]
[InlineData(257, 16, 9)]
public void JumpFloodPassCountCoversLongSide(int width, int height, int expected)
[InlineData(CrystallineGrowthQuality.Balanced, nameof(Texts.QualityBalanced), nameof(Texts.QualityBalancedDescription))]
[InlineData(CrystallineGrowthQuality.High, nameof(Texts.QualityHigh), nameof(Texts.QualityHighDescription))]
[InlineData(CrystallineGrowthQuality.Ultra, nameof(Texts.QualityUltra), nameof(Texts.QualityUltraDescription))]
public void EveryQualityIsDisplayedWithItsLocalizedName(CrystallineGrowthQuality quality, string name, string description)
{
Assert.Equal(expected, CrystallineGrowthSettings.GetJumpFloodPassCount(width, height));
var display = typeof(CrystallineGrowthQuality).GetField(quality.ToString())!.GetCustomAttribute<DisplayAttribute>()!;
Assert.Equal(name, display.Name);
Assert.Equal(description, display.Description);
Assert.Equal(typeof(Texts), display.ResourceType);
}
[Fact]
public void TransparentInputYieldsTransparentOutput()
public void TheSeedIsEditedWithoutAUnitFromZero()
{
using var pipeline = CrystallineGrowthPipeline.TryCreate();
if (pipeline is null)
{
Assert.Skip("Direct3D 12 is unavailable.");
return;
}
var slider = Attribute<TextBoxSliderAttribute>(nameof(CrystallineGrowthEffect.Seed));
var range = Attribute<RangeAttribute>(nameof(CrystallineGrowthEffect.Seed));
const int width = 64;
const int height = 64;
var source = new int[width * height];
var destination = new int[source.Length];
Array.Fill(destination, -1);
var parameters = CreateParameters();
pipeline.Process(source, destination, width, height, in parameters);
Assert.All(destination, pixel => Assert.Equal(0, pixel));
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(CrystallineGrowthEffect.Seed)).Value);
}
[Fact]
public void FreezeZeroYieldsTransparentOutput()
public void TheIceColorIsPickedWithAColorPicker()
{
using var pipeline = CrystallineGrowthPipeline.TryCreate();
if (pipeline is null)
{
Assert.Skip("Direct3D 12 is unavailable.");
return;
}
const int width = 96;
const int height = 96;
var source = CreateSquareSource(width, height, 32, 32, 32, 32);
var destination = new int[source.Length];
Array.Fill(destination, -1);
var parameters = CreateParameters(freeze: 0f);
pipeline.Process(source, destination, width, height, in parameters);
Assert.All(destination, pixel => Assert.Equal(0, pixel));
Assert.NotNull(Attribute<ColorPickerAttribute>(nameof(CrystallineGrowthEffect.IceColor)));
}
[Fact]
public void FullFreezeProducesFrost()
public void EverySettingSurvivesAProjectRoundTrip()
{
using var pipeline = CrystallineGrowthPipeline.TryCreate();
if (pipeline is null)
{
Assert.Skip("Direct3D 12 is unavailable.");
return;
}
var effect = new CrystallineGrowthEffect { Quality = CrystallineGrowthQuality.Ultra, Seed = 42, IceColor = Colors.Crimson };
var values = new[] { 55d, 45d, 70d, 20d, 120d, 65d, 15d, 85d, 35d };
foreach (var (animation, value) in Animations(effect).Zip(values))
animation.Values[0].Value = value;
const int width = 128;
const int height = 128;
var source = CreateSquareSource(width, height, 48, 48, 32, 32);
var destination = new int[source.Length];
var parameters = CreateParameters();
var clone = Json.GetClone(effect)!;
pipeline.Process(source, destination, width, height, in parameters);
Assert.True(CountLitPixels(destination) > 0);
}
[Fact]
public void GpuPipelineIsDeterministic()
{
using var pipeline = CrystallineGrowthPipeline.TryCreate();
if (pipeline is null)
{
Assert.Skip("Direct3D 12 is unavailable.");
return;
}
const int width = 128;
const int height = 128;
var source = CreateSquareSource(width, height, 48, 48, 32, 32);
var first = new int[source.Length];
var second = new int[source.Length];
var parameters = CreateParameters(branching: 0.8f, noise: 0.5f, seed: 42);
pipeline.Process(source, first, width, height, in parameters);
pipeline.Process(source, second, width, height, in parameters);
Assert.Equal(first, second);
}
[Fact]
public void DifferentSeedsProduceDifferentCrystals()
{
using var pipeline = CrystallineGrowthPipeline.TryCreate();
if (pipeline is null)
{
Assert.Skip("Direct3D 12 is unavailable.");
return;
}
const int width = 128;
const int height = 128;
var source = CreateSquareSource(width, height, 48, 48, 32, 32);
var first = new int[source.Length];
var second = new int[source.Length];
var parametersA = CreateParameters(noise: 0.5f, seed: 1);
var parametersB = CreateParameters(noise: 0.5f, seed: 2);
pipeline.Process(source, first, width, height, in parametersA);
pipeline.Process(source, second, width, height, in parametersB);
Assert.NotEqual(first, second);
}
[Fact]
public void OutputAlphaStaysPremultipliedAndBounded()
{
using var pipeline = CrystallineGrowthPipeline.TryCreate();
if (pipeline is null)
{
Assert.Skip("Direct3D 12 is unavailable.");
return;
}
const int width = 128;
const int height = 128;
var source = CreateSquareSource(width, height, 48, 48, 32, 32);
var destination = new int[source.Length];
var parameters = CreateParameters(frost: 1f, refraction: 1f, specular: 1f);
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 FreezeIncreasesLitArea()
{
using var pipeline = CrystallineGrowthPipeline.TryCreate();
if (pipeline is null)
{
Assert.Skip("Direct3D 12 is unavailable.");
return;
}
const int width = 128;
const int height = 128;
var source = CreateSquareSource(width, height, 48, 48, 32, 32);
var partial = new int[source.Length];
var full = new int[source.Length];
var partialParameters = CreateParameters(freeze: 0.2f);
var fullParameters = CreateParameters(freeze: 1f);
pipeline.Process(source, partial, width, height, in partialParameters);
pipeline.Process(source, full, width, height, in fullParameters);
Assert.True(CountLitPixels(full) > CountLitPixels(partial));
}
[Fact]
public void ReachLimitsFrostExtent()
{
using var pipeline = CrystallineGrowthPipeline.TryCreate();
if (pipeline is null)
{
Assert.Skip("Direct3D 12 is unavailable.");
return;
}
const int width = 192;
const int height = 192;
var source = CreateSquareSource(width, height, 80, 80, 32, 32);
var shortReach = new int[source.Length];
var longReach = new int[source.Length];
var shortParameters = CreateParameters(reachPixels: 12f);
var longParameters = CreateParameters(reachPixels: 48f);
pipeline.Process(source, shortReach, width, height, in shortParameters);
pipeline.Process(source, longReach, width, height, in longParameters);
var shortMaxY = MaxLitY(shortReach, width, height);
var longMaxY = MaxLitY(longReach, width, height);
Assert.True(shortMaxY > 0);
Assert.True(longMaxY > shortMaxY);
Assert.True(shortMaxY <= 80 + 32 + 12 + 8);
}
[Fact]
public void GpuPipelineDoesNotAllocateManagedMemoryAfterWarmup()
{
using var pipeline = CrystallineGrowthPipeline.TryCreate();
if (pipeline is null)
{
Assert.Skip("Direct3D 12 is unavailable.");
return;
}
const int width = 64;
const int height = 64;
var source = CreateSquareSource(width, height, 24, 24, 16, 16);
var destination = new int[source.Length];
var parameters = CreateParameters();
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 = CrystallineGrowthPipeline.TryCreate();
if (pipeline is null)
{
Assert.Skip("Direct3D 12 is unavailable.");
return;
}
const int width = 96;
const int height = 96;
var source = CreateSquareSource(width, height, 32, 32, 32, 32);
var expected = new int[source.Length];
var parameters = CreateParameters(branching: 0.7f, seed: 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 SubmittedSharedTexturePipelineAllocationsAmortizeToZero()
{
using var pipeline = CrystallineGrowthPipeline.TryCreate();
if (pipeline is null)
{
Assert.Skip("Direct3D 12 is unavailable.");
return;
}
const int width = 64;
const int height = 64;
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 = CreateParameters();
for (var iteration = 0; iteration < 4; iteration++)
pipeline.Process(source, destination, width, height, 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, width, height, in parameters);
minimum = Math.Min(minimum, GC.GetAllocatedBytesForCurrentThread() - before);
}
pipeline.WaitForCompletion();
Assert.Equal(0, minimum);
}
[Theory]
[InlineData(0.3f)]
[InlineData(1f)]
public void VisibleBoundsCoverAllLitPixelsAndMatchFullRender(float freeze)
{
using var pipeline = CrystallineGrowthPipeline.TryCreate();
if (pipeline is null)
{
Assert.Skip("Direct3D 12 is unavailable.");
return;
}
const int width = 192;
const int height = 192;
var source = CreateSquareSource(width, height, 80, 80, 32, 24);
var full = new int[source.Length];
var parameters = CreateParameters(freeze: freeze, reachPixels: 32f, seed: 5);
pipeline.Process(source, full, width, height, in parameters);
var device = GraphicsDevice.GetDefault();
using var sourceTexture = device.AllocateReadWriteTexture2D<Bgra32, Float4>(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.Simulate(sourceTexture, width, height, 0, 0, width, height, in parameters);
Assert.True(pipeline.TryGetVisibleBounds(width, height, in parameters, out var rect));
Assert.True(rect.Width > 0 && rect.Height > 0);
Assert.True(rect.X >= 0 && rect.Y >= 0);
Assert.True(rect.X + rect.Width <= width && rect.Y + rect.Height <= height);
for (var y = 0; y < height; y++)
{
for (var x = 0; x < width; x++)
{
if (full[y * width + x] == 0)
continue;
Assert.InRange(x, rect.X, rect.X + rect.Width - 1);
Assert.InRange(y, rect.Y, rect.Y + rect.Height - 1);
}
}
using var outputTexture = device.AllocateReadWriteTexture2D<Bgra32, Float4>(rect.Width, rect.Height);
pipeline.RenderVisible(sourceTexture, outputTexture, width, height, 0, 0, width, height, rect, in parameters);
var result = new Bgra32[rect.Width * rect.Height];
outputTexture.CopyTo(result);
for (var y = 0; y < rect.Height; y++)
{
for (var x = 0; x < rect.Width; x++)
{
var expected = unchecked((uint)full[(rect.Y + y) * width + rect.X + x]);
Assert.Equal(expected, result[y * rect.Width + x].PackedValue);
}
}
}
[Fact]
public void SimulateCachesStructureUntilInputsChange()
{
using var pipeline = CrystallineGrowthPipeline.TryCreate();
if (pipeline is null)
{
Assert.Skip("Direct3D 12 is unavailable.");
return;
}
const int width = 128;
const int height = 128;
var source = CreateSquareSource(width, height, 48, 48, 32, 32);
var device = GraphicsDevice.GetDefault();
using var sourceTexture = device.AllocateReadWriteTexture2D<Bgra32, Float4>(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);
var parameters = CreateParameters(seed: 3);
Assert.True(pipeline.Simulate(sourceTexture, width, height, 0, 0, width, height, in parameters));
Assert.False(pipeline.Simulate(sourceTexture, width, height, 0, 0, width, height, in parameters));
var freezeChanged = parameters with { Freeze = 0.5f };
Assert.False(pipeline.Simulate(sourceTexture, width, height, 0, 0, width, height, in freezeChanged));
var seedChanged = parameters with { Seed = 4 };
Assert.True(pipeline.Simulate(sourceTexture, width, height, 0, 0, width, height, in seedChanged));
var movedSource = CreateSquareSource(width, height, 32, 32, 32, 32);
for (var index = 0; index < movedSource.Length; index++)
sourcePixels[index].PackedValue = unchecked((uint)movedSource[index]);
sourceTexture.CopyFrom(sourcePixels);
Assert.True(pipeline.Simulate(sourceTexture, width, height, 0, 0, width, height, in seedChanged));
}
[Fact]
public void Direct2DInteropProducesFrostFromOpaqueCore()
{
using var devices = new GraphicsDevices();
using var graphicsContext = devices.CreateContext();
using var interop = CrystallineGrowthGpuInterop.TryCreate(graphicsContext);
if (interop is null)
{
Assert.Skip("Direct3D 11 and Direct3D 12 sharing is unavailable.");
return;
}
using var pipeline = CrystallineGrowthPipeline.TryCreate(interop.Device);
Assert.NotNull(pipeline);
const int width = 96;
const int height = 96;
var pixels = CreateSquareSource(width, height, 32, 32, 32, 32);
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 = CreateParameters();
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
{
var lit = 0;
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)));
var alpha = (actual >> 24) & 255;
Assert.InRange((actual >> 16) & 255, 0, alpha);
Assert.InRange((actual >> 8) & 255, 0, alpha);
Assert.InRange(actual & 255, 0, alpha);
if (alpha > 0)
lit++;
}
}
Assert.True(lit > 0);
}
finally
{
staging.Unmap();
}
}
private static int[] CreateSquareSource(int width, int height, int left, int top, int squareWidth, int squareHeight)
{
var source = new int[width * height];
for (var y = top; y < top + squareHeight; y++)
{
for (var x = left; x < left + squareWidth; x++)
{
if (x < 0 || x >= width || y < 0 || y >= height)
continue;
source[y * width + x] = unchecked((int)0xFFC0C0C0);
}
}
return source;
}
private static int CountLitPixels(int[] pixels)
{
var count = 0;
foreach (var pixel in pixels)
{
if (((pixel >> 24) & 255) > 8)
count++;
}
return count;
}
private static int MaxLitY(int[] pixels, int width, int height)
{
for (var y = height - 1; y >= 0; y--)
{
for (var x = 0; x < width; x++)
{
if (((pixels[y * width + x] >> 24) & 255) >= 32)
return y;
}
}
return 0;
Assert.NotSame(effect, clone);
Assert.Equal(CrystallineGrowthQuality.Ultra, clone.Quality);
Assert.Equal(42, clone.Seed);
Assert.Equal(Colors.Crimson, clone.IceColor);
Assert.Equal(values, Animations(clone).Select(animation => animation.GetValue(0, 1, EffectDescriptions.Fps)));
}
}
+165
ファイルの表示
@@ -0,0 +1,165 @@
using System.Numerics;
using ComputeWeave;
using Vortice.Direct2D1;
using YukkuriMovieMaker.Commons;
namespace CrystallineGrowth.Tests;
[Collection("Direct2D")]
public sealed class CrystallineGrowthInteropTests
{
static readonly Bgra Gray = Bgra.Opaque(192, 192, 192);
static CrystallineGrowthPipeline.Parameters Parameters()
=> new(CrystallineGrowthQuality.Balanced, 1f, 0.6f, 0.4f, 40f, 0.25f, 0.7f, 0.4f, 0.5f, 0.8f, 0.89f, 1f, 0);
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 CrystallineGrowthInteropProvider provider;
readonly ComputeInteropDomain domain;
public CrystallineGrowthResourceSet Resources { get; }
public CrystallineGrowthPipeline Pipeline { get; }
Interop(ComputeExternalQueueScheduler scheduler, CrystallineGrowthInteropProvider provider, GraphicsDevice device)
{
this.scheduler = scheduler;
this.provider = provider;
domain = device.RegisterExternalDomain(provider);
Resources = CrystallineGrowthResourceSet.Create(device, domain);
Pipeline = CrystallineGrowthPipeline.TryCreate(device)!;
}
public static Interop Create(IGraphicsDevicesAndContext devices)
{
var scheduler = ComputeExternalQueueScheduler.Create();
var provider = CrystallineGrowthInteropProvider.TryCreate(devices, scheduler, out var device);
if (provider is null || device is null)
{
scheduler.Dispose();
Assert.Skip("Direct3D 11 and Direct3D 12 sharing is unavailable.");
}
return new Interop(scheduler, provider, device);
}
public void Draw(ID2D1Image image)
{
var context = provider.RenderContext;
using var borrow = Resources.BeginSourceExternalOperation();
var previousTarget = context.Target;
using var target = new ID2D1Bitmap1(borrow.DangerousGetView().AddRefBitmap());
context.Target = target;
context.BeginDraw();
context.Clear(null);
context.DrawImage(image, Vector2.Zero, null, InterpolationMode.NearestNeighbor, CompositeMode.SourceCopy);
context.EndDraw();
context.Target = previousTarget;
}
public Rendering CaptureOutput(IGraphicsDevicesAndContext devices, out int width, out int height)
{
using var lease = Resources.AcquireOutputExternalViewLease();
width = lease.Width;
height = lease.Height;
using var bitmap = new ID2D1Bitmap1(lease.DangerousGetView().AddRefBitmap());
return Rendering.Capture(devices, bitmap);
}
public void Dispose()
{
Pipeline.Dispose();
Resources.Dispose();
Resources.WaitForDisposal();
domain.Dispose();
domain.WaitForDisposal();
provider.Dispose();
scheduler.Dispose();
}
}
static int LitPixels(Rendering rendering, CrystallineGrowthPipeline.PixelRect visible)
{
var lit = 0;
for (var y = 0; y < visible.Height; y++)
{
for (var x = 0; x < visible.Width; x++)
{
var pixel = rendering[x, y];
Assert.InRange(pixel.Blue, 0, pixel.Alpha);
Assert.InRange(pixel.Green, 0, pixel.Alpha);
Assert.InRange(pixel.Red, 0, pixel.Alpha);
if (pixel.Alpha > 0)
lit++;
}
}
return lit;
}
[Fact]
public void FrostIsDrawnAfterTheOutputGrowsToFullHd()
{
using var devices = new GraphicsDevices();
using var context = devices.CreateContext();
using var interop = Interop.Create(context);
using var source = new SourceImage(context, 96, 96, CenteredSquare(96, 32));
var parameters = Parameters();
Assert.True(interop.Resources.TryEnsureSource(96, 96, out _));
CrystallineGrowthPipeline.PixelRect RenderInto(Func<CrystallineGrowthPipeline.PixelRect, (int Width, int Height)> outputSize)
{
interop.Draw(source.Bitmap);
interop.Pipeline.Simulate(interop.Resources.GetSourceComputeBinding(), 96, 96, 0, 0, 96, 96, in parameters, hashSource: true);
Assert.True(interop.Pipeline.TryGetVisibleBounds(96, 96, in parameters, out var visible));
var (width, height) = outputSize(visible);
Assert.True(interop.Resources.TryEnsureOutput(width, height, out _));
interop.Pipeline.RenderVisible(interop.Resources.GetSourceComputeBinding(), interop.Resources.GetOutputComputeBinding(), 96, 96, 0, 0, 96, 96, visible, in parameters);
return visible;
}
var first = RenderInto(visible => (visible.Width, visible.Height));
interop.CaptureOutput(context, out var firstWidth, out var firstHeight);
var second = RenderInto(_ => (1920, 1080));
var output = interop.CaptureOutput(context, out var secondWidth, out var secondHeight);
Assert.Equal((first.Width, first.Height), (firstWidth, firstHeight));
Assert.Equal((1920, 1080), (secondWidth, secondHeight));
Assert.True(LitPixels(output, second) > 0);
}
[Fact]
public void FrostIsDrawnAfterTheSourceIsReplacedByALargerOne()
{
using var devices = new GraphicsDevices();
using var context = devices.CreateContext();
using var interop = Interop.Create(context);
var parameters = Parameters();
var previous = default(CrystallineGrowthPipeline.PixelRect);
foreach (var (size, square) in new[] { (96, 32), (128, 64) })
{
using var source = new SourceImage(context, size, size, CenteredSquare(size, square));
Assert.True(interop.Resources.TryEnsureSource(size, size, out var sourceChanged));
interop.Draw(source.Bitmap);
Assert.True(interop.Pipeline.Simulate(interop.Resources.GetSourceComputeBinding(), size, size, 0, 0, size, size, in parameters, hashSource: true));
Assert.True(interop.Pipeline.TryGetVisibleBounds(size, size, in parameters, out var visible));
Assert.True(interop.Resources.TryEnsureOutput(visible.Width, visible.Height, out _));
interop.Pipeline.RenderVisible(interop.Resources.GetSourceComputeBinding(), interop.Resources.GetOutputComputeBinding(), size, size, 0, 0, size, size, visible, in parameters);
var output = interop.CaptureOutput(context, out var width, out var height);
Assert.True(sourceChanged);
Assert.True(visible.Width > previous.Width && visible.Height > previous.Height);
Assert.Equal((visible.Width, visible.Height), (width, height));
Assert.True(LitPixels(output, visible) > square * square);
previous = visible;
}
}
}
+501
ファイルの表示
@@ -0,0 +1,501 @@
using ComputeWeave;
using ComputeWeave.Interop;
namespace CrystallineGrowth.Tests;
[Collection("Direct3D12")]
public sealed class CrystallineGrowthPipelineTests
{
const int Opaque = unchecked((int)0xFFC0C0C0);
static readonly bool Direct3D12IsAvailable = GraphicsDevice.EnumerateDevices().Any();
static CrystallineGrowthPipeline CreatePipeline()
{
if (!Direct3D12IsAvailable)
Assert.Skip("Direct3D 12 is unavailable.");
var pipeline = CrystallineGrowthPipeline.TryCreate();
Assert.NotNull(pipeline);
return pipeline;
}
static CrystallineGrowthPipeline.Parameters Parameters(
CrystallineGrowthQuality quality = CrystallineGrowthQuality.Balanced,
float freeze = 1f,
float branching = 0.6f,
float facet = 0.4f,
float reachPixels = 40f,
float noise = 0.25f,
float frost = 0.7f,
float refraction = 0.4f,
float specular = 0.5f,
int seed = 0)
=> new(quality, freeze, branching, facet, reachPixels, noise, frost, refraction, specular, 0.8f, 0.89f, 1f, seed);
static int[] Square(int width, int height, int left, int top, int squareWidth, int squareHeight)
{
var pixels = new int[width * height];
for (var y = Math.Max(top, 0); y < Math.Min(top + squareHeight, height); y++)
{
for (var x = Math.Max(left, 0); x < Math.Min(left + squareWidth, width); x++)
pixels[y * width + x] = Opaque;
}
return pixels;
}
static int Alpha(int pixel) => (pixel >> 24) & 255;
static int LitPixels(int[] pixels) => pixels.Count(pixel => Alpha(pixel) > 8);
static (int Left, int Top, int Right, int Bottom) FrostBounds(int[] pixels, int width)
{
var (left, top, right, bottom) = (int.MaxValue, int.MaxValue, int.MinValue, int.MinValue);
for (var index = 0; index < pixels.Length; index++)
{
if (Alpha(pixels[index]) == 0)
continue;
left = Math.Min(left, index % width);
top = Math.Min(top, index / width);
right = Math.Max(right, index % width + 1);
bottom = Math.Max(bottom, index / width + 1);
}
return (left, top, right, bottom);
}
static int LowestLitRow(int[] pixels, int width)
{
for (var index = pixels.Length - 1; index >= 0; index--)
{
if (Alpha(pixels[index]) >= 32)
return index / width;
}
return 0;
}
static void Upload(ReadWriteTexture2D<Bgra32, Float4> texture, int[] pixels)
=> texture.CopyFrom(pixels.Select(pixel => new Bgra32 { PackedValue = unchecked((uint)pixel) }).ToArray());
static int[] Render(CrystallineGrowthPipeline pipeline, int[] source, int width, int height, CrystallineGrowthPipeline.Parameters parameters)
{
var destination = new int[source.Length];
pipeline.Process(source, destination, width, height, in parameters);
return destination;
}
[Fact]
public void ATransparentSourceProducesNoFrost()
{
using var pipeline = CreatePipeline();
var destination = Enumerable.Repeat(-1, 64 * 64).ToArray();
var parameters = Parameters();
pipeline.Process(new int[64 * 64], destination, 64, 64, in parameters);
Assert.All(destination, pixel => Assert.Equal(0, pixel));
}
[Fact]
public void AZeroFreezeProducesNoFrost()
{
using var pipeline = CreatePipeline();
var source = Square(96, 96, 32, 32, 32, 32);
var destination = Enumerable.Repeat(-1, source.Length).ToArray();
var parameters = Parameters(freeze: 0f);
pipeline.Process(source, destination, 96, 96, in parameters);
Assert.All(destination, pixel => Assert.Equal(0, pixel));
}
[Fact]
public void AFullFreezeProducesFrost()
{
using var pipeline = CreatePipeline();
var rendering = Render(pipeline, Square(128, 128, 48, 48, 32, 32), 128, 128, Parameters());
Assert.True(LitPixels(rendering) > 0);
}
[Fact]
public void TheSameSettingsAlwaysProduceTheSameFrost()
{
using var pipeline = CreatePipeline();
var source = Square(128, 128, 48, 48, 32, 32);
var first = Render(pipeline, source, 128, 128, Parameters(branching: 0.8f, noise: 0.5f, seed: 42));
var second = Render(pipeline, source, 128, 128, Parameters(branching: 0.8f, noise: 0.5f, seed: 42));
Assert.Equal(first, second);
}
[Fact]
public void ADifferentSeedGrowsTheCrystalsDifferently()
{
using var pipeline = CreatePipeline();
var source = Square(128, 128, 48, 48, 32, 32);
var first = Render(pipeline, source, 128, 128, Parameters(noise: 0.5f, seed: 1));
var second = Render(pipeline, source, 128, 128, Parameters(noise: 0.5f, seed: 2));
Assert.NotEqual(first, second);
}
[Fact]
public void TheFrostStaysPremultiplied()
{
using var pipeline = CreatePipeline();
var rendering = Render(pipeline, Square(128, 128, 48, 48, 32, 32), 128, 128, Parameters(frost: 1f, refraction: 1f, specular: 1f));
Assert.All(rendering, pixel =>
{
Assert.InRange((pixel >> 16) & 255, 0, Alpha(pixel));
Assert.InRange((pixel >> 8) & 255, 0, Alpha(pixel));
Assert.InRange(pixel & 255, 0, Alpha(pixel));
});
}
[Fact]
public void AFurtherFreezeCoversMorePixels()
{
using var pipeline = CreatePipeline();
var source = Square(128, 128, 48, 48, 32, 32);
var partial = Render(pipeline, source, 128, 128, Parameters(freeze: 0.2f));
var full = Render(pipeline, source, 128, 128, Parameters(freeze: 1f));
Assert.True(LitPixels(full) > LitPixels(partial));
}
[Fact]
public void TheReachLimitsHowFarTheFrostGrows()
{
using var pipeline = CreatePipeline();
var source = Square(192, 192, 80, 80, 32, 32);
var shortReach = LowestLitRow(Render(pipeline, source, 192, 192, Parameters(reachPixels: 12f)), 192);
var longReach = LowestLitRow(Render(pipeline, source, 192, 192, Parameters(reachPixels: 48f)), 192);
Assert.True(shortReach > 0);
Assert.True(longReach > shortReach);
Assert.True(shortReach <= 80 + 32 + 12 + 8);
}
[Fact]
public void AWarmPipelineAllocatesNoManagedMemory()
{
using var pipeline = CreatePipeline();
var source = Square(64, 64, 24, 24, 16, 16);
var destination = new int[source.Length];
var parameters = Parameters();
for (var iteration = 0; iteration < 4; iteration++)
pipeline.Process(source, destination, 64, 64, in parameters);
GC.Collect();
GC.WaitForPendingFinalizers();
GC.Collect();
var minimum = long.MaxValue;
for (var iteration = 0; iteration < 16; iteration++)
{
var before = GC.GetAllocatedBytesForCurrentThread();
pipeline.Process(source, destination, 64, 64, in parameters);
minimum = Math.Min(minimum, GC.GetAllocatedBytesForCurrentThread() - before);
}
Assert.Equal(0, minimum);
}
[Fact]
public void SharedTexturesProduceTheSameFrostAsPackedBuffers()
{
using var pipeline = CreatePipeline();
var source = Square(96, 96, 32, 32, 32, 32);
var parameters = Parameters(branching: 0.7f, seed: 11);
var expected = Render(pipeline, source, 96, 96, parameters);
var device = GraphicsDevice.GetDefault();
using var sourceTexture = InteropServices.AllocateSharedReadWriteTexture2D<Bgra32, Float4>(device, 96, 96);
using var outputTexture = InteropServices.AllocateSharedReadWriteTexture2D<Bgra32, Float4>(device, 96, 96);
Upload(sourceTexture, source);
pipeline.ProcessSharedAndWait(sourceTexture, outputTexture, 96, 96, in parameters);
var result = new Bgra32[source.Length];
outputTexture.CopyTo(result);
Assert.Equal(expected.Select(pixel => unchecked((uint)pixel)), result.Select(pixel => pixel.PackedValue));
}
[Fact]
public void RepeatedSharedTextureSubmissionsAllocateNoManagedMemory()
{
using var pipeline = CreatePipeline();
var device = GraphicsDevice.GetDefault();
using var source = InteropServices.AllocateSharedReadWriteTexture2D<Bgra32, Float4>(device, 64, 64);
using var destination = InteropServices.AllocateSharedReadWriteTexture2D<Bgra32, Float4>(device, 64, 64);
var parameters = Parameters();
for (var iteration = 0; iteration < 4; iteration++)
pipeline.Process(source, destination, 64, 64, in parameters);
pipeline.WaitForCompletion();
GC.Collect();
GC.WaitForPendingFinalizers();
GC.Collect();
var minimum = long.MaxValue;
for (var iteration = 0; iteration < 16; iteration++)
{
var before = GC.GetAllocatedBytesForCurrentThread();
pipeline.Process(source, destination, 64, 64, in parameters);
minimum = Math.Min(minimum, GC.GetAllocatedBytesForCurrentThread() - before);
}
pipeline.WaitForCompletion();
Assert.Equal(0, minimum);
}
[Theory]
[InlineData(0.3f)]
[InlineData(1f)]
public void TheVisibleBoundsHoldEveryFrostedPixelAndRenderTheSameFrost(float freeze)
{
using var pipeline = CreatePipeline();
var source = Square(192, 192, 80, 80, 32, 24);
var parameters = Parameters(freeze: freeze, reachPixels: 32f, seed: 5);
var full = Render(pipeline, source, 192, 192, parameters);
var device = GraphicsDevice.GetDefault();
using var sourceTexture = device.AllocateReadWriteTexture2D<Bgra32, Float4>(192, 192);
Upload(sourceTexture, source);
pipeline.Simulate(sourceTexture, 192, 192, 0, 0, 192, 192, in parameters, hashSource: true);
Assert.True(pipeline.TryGetVisibleBounds(192, 192, in parameters, out var rect));
using var outputTexture = device.AllocateReadWriteTexture2D<Bgra32, Float4>(rect.Width, rect.Height);
pipeline.RenderVisible(sourceTexture, outputTexture, 192, 192, 0, 0, 192, 192, rect, in parameters);
var visible = new Bgra32[rect.Width * rect.Height];
outputTexture.CopyTo(visible);
Assert.True(rect is { Width: > 0, Height: > 0, X: >= 0, Y: >= 0 });
Assert.True(rect.X + rect.Width <= 192 && rect.Y + rect.Height <= 192);
for (var y = 0; y < 192; y++)
{
for (var x = 0; x < 192; x++)
{
var inside = x >= rect.X && x < rect.X + rect.Width && y >= rect.Y && y < rect.Y + rect.Height;
if (!inside)
Assert.Equal(0, full[y * 192 + x]);
else
Assert.Equal(unchecked((uint)full[y * 192 + x]), visible[(y - rect.Y) * rect.Width + x - rect.X].PackedValue);
}
}
}
static uint[] DrawVisible(
CrystallineGrowthPipeline pipeline,
ReadWriteTexture2D<Bgra32, Float4> sourceTexture,
CrystallineGrowthPipeline.PixelRect rect,
CrystallineGrowthPipeline.Parameters parameters)
{
using var outputTexture = GraphicsDevice.GetDefault().AllocateReadWriteTexture2D<Bgra32, Float4>(rect.Width, rect.Height);
pipeline.RenderVisible(sourceTexture, outputTexture, 128, 128, 0, 0, 128, 128, rect, in parameters);
var pixels = new Bgra32[rect.Width * rect.Height];
outputTexture.CopyTo(pixels);
return pixels.Select(static pixel => pixel.PackedValue).ToArray();
}
[Fact]
public void SettingsRedrawnFrameAfterFrameMatchAFreshRender()
{
using var pipeline = CreatePipeline();
using var sourceTexture = GraphicsDevice.GetDefault().AllocateReadWriteTexture2D<Bgra32, Float4>(128, 128);
Upload(sourceTexture, Square(128, 128, 48, 48, 32, 32));
var first = Parameters(seed: 3);
var frames = new[]
{
first,
first with { Frost = 0.9f },
first with { Refraction = 1f },
first with { Specular = 1f },
first with { ColorR = 0.2f },
first with { Freeze = 0.6f },
first with { Freeze = 0.6f, Frost = 0.2f },
first with { Freeze = 0.6f, Refraction = 0f },
first with { Freeze = 0.6f, Specular = 0f },
};
foreach (var parameters in frames)
{
pipeline.Simulate(sourceTexture, 128, 128, 0, 0, 128, 128, in parameters, hashSource: false);
Assert.True(pipeline.TryGetVisibleBounds(128, 128, in parameters, out var rect));
using var fresh = CreatePipeline();
fresh.Simulate(sourceTexture, 128, 128, 0, 0, 128, 128, in parameters, hashSource: false);
Assert.Equal(DrawVisible(fresh, sourceTexture, rect, parameters), DrawVisible(pipeline, sourceTexture, rect, parameters));
}
}
[Fact]
public void TheVisibleBoundsHugTheFrostOnAFourPixelGrid()
{
using var pipeline = CreatePipeline();
var source = Square(480, 480, 192, 192, 96, 96);
var parameters = Parameters(reachPixels: 48f, seed: 5);
var frost = FrostBounds(Render(pipeline, source, 480, 480, parameters), 480);
var device = GraphicsDevice.GetDefault();
using var sourceTexture = device.AllocateReadWriteTexture2D<Bgra32, Float4>(480, 480);
Upload(sourceTexture, source);
pipeline.Simulate(sourceTexture, 480, 480, 0, 0, 480, 480, in parameters, hashSource: true);
Assert.True(pipeline.TryGetVisibleBounds(480, 480, in parameters, out var rect));
Assert.Equal((0, 0), (rect.X % 4, rect.Y % 4));
Assert.InRange(frost.Left - rect.X, 0, 24);
Assert.InRange(frost.Top - rect.Y, 0, 24);
Assert.InRange(rect.X + rect.Width - frost.Right, 0, 24);
Assert.InRange(rect.Y + rect.Height - frost.Bottom, 0, 24);
}
[Fact]
public void ALesserFreezeNarrowsTheVisibleBounds()
{
using var pipeline = CreatePipeline();
var device = GraphicsDevice.GetDefault();
using var sourceTexture = device.AllocateReadWriteTexture2D<Bgra32, Float4>(192, 192);
Upload(sourceTexture, Square(192, 192, 80, 80, 32, 32));
var full = Parameters(reachPixels: 48f, seed: 5);
var partial = full with { Freeze = 0.3f };
pipeline.Simulate(sourceTexture, 192, 192, 0, 0, 192, 192, in full, hashSource: true);
Assert.True(pipeline.TryGetVisibleBounds(192, 192, in full, out var wide));
Assert.True(pipeline.TryGetVisibleBounds(192, 192, in partial, out var narrow));
Assert.True(narrow.X >= wide.X && narrow.Y >= wide.Y);
Assert.True(narrow.X + narrow.Width <= wide.X + wide.Width && narrow.Y + narrow.Height <= wide.Y + wide.Height);
Assert.True(narrow.Width * narrow.Height < wide.Width * wide.Height);
}
[Theory]
[InlineData(false, 1f)]
[InlineData(true, 0f)]
public void NothingIsVisibleWithoutFrostOrFreeze(bool shaped, float freeze)
{
using var pipeline = CreatePipeline();
var device = GraphicsDevice.GetDefault();
using var sourceTexture = device.AllocateReadWriteTexture2D<Bgra32, Float4>(128, 128);
Upload(sourceTexture, shaped ? Square(128, 128, 48, 48, 32, 32) : new int[128 * 128]);
var parameters = Parameters(freeze: freeze);
pipeline.Simulate(sourceTexture, 128, 128, 0, 0, 128, 128, in parameters, hashSource: true);
Assert.False(pipeline.TryGetVisibleBounds(128, 128, in parameters, out _));
}
[Fact]
public void APipelineUsedAtAnotherSizeDrawsLikeAFreshOne()
{
using var pipeline = CreatePipeline();
using var fresh = CreatePipeline();
var parameters = Parameters(seed: 7);
Render(pipeline, Square(128, 64, 48, 16, 32, 32), 128, 64, parameters);
var source = Square(64, 64, 16, 16, 32, 32);
var reused = Render(pipeline, source, 64, 64, parameters);
var expected = Render(fresh, source, 64, 64, parameters);
Assert.Equal(expected, reused);
}
[Fact]
public void RecoloringTheSourceChangesItsHashWithoutGrowingTheCrystalsAgain()
{
using var pipeline = CreatePipeline();
var device = GraphicsDevice.GetDefault();
using var sourceTexture = device.AllocateReadWriteTexture2D<Bgra32, Float4>(128, 128);
var gray = Square(128, 128, 48, 48, 32, 32);
var red = gray.Select(pixel => pixel == 0 ? 0 : unchecked((int)0xFFFF0000)).ToArray();
var parameters = Parameters(seed: 3);
Upload(sourceTexture, gray);
pipeline.Simulate(sourceTexture, 128, 128, 0, 0, 128, 128, in parameters, hashSource: true);
var grayHash = Assert.NotNull(pipeline.SourceHash);
Upload(sourceTexture, red);
var grewAgain = pipeline.Simulate(sourceTexture, 128, 128, 0, 0, 128, 128, in parameters, hashSource: true);
var redHash = Assert.NotNull(pipeline.SourceHash);
Upload(sourceTexture, gray);
pipeline.Simulate(sourceTexture, 128, 128, 0, 0, 128, 128, in parameters, hashSource: true);
Assert.False(grewAgain);
Assert.NotEqual(grayHash.Sum, redHash.Sum);
Assert.NotEqual(grayHash.Mix, redHash.Mix);
Assert.Equal(grayHash, pipeline.SourceHash);
}
[Fact]
public void TheSourceHashIsLeftUnknownWhenItIsNotAskedFor()
{
using var pipeline = CreatePipeline();
var device = GraphicsDevice.GetDefault();
using var sourceTexture = device.AllocateReadWriteTexture2D<Bgra32, Float4>(128, 128);
Upload(sourceTexture, Square(128, 128, 48, 48, 32, 32));
var parameters = Parameters(seed: 3);
Assert.True(pipeline.Simulate(sourceTexture, 128, 128, 0, 0, 128, 128, in parameters, hashSource: false));
Assert.Null(pipeline.SourceHash);
Assert.False(pipeline.Simulate(sourceTexture, 128, 128, 0, 0, 128, 128, in parameters, hashSource: true));
Assert.NotNull(pipeline.SourceHash);
Upload(sourceTexture, Square(128, 128, 32, 32, 32, 32));
Assert.True(pipeline.Simulate(sourceTexture, 128, 128, 0, 0, 128, 128, in parameters, hashSource: false));
Assert.Null(pipeline.SourceHash);
}
[Fact]
public void TheGrowthIsSimulatedAgainOnlyWhenTheShapeOrTheGrowthSettingsChange()
{
using var pipeline = CreatePipeline();
var device = GraphicsDevice.GetDefault();
using var sourceTexture = device.AllocateReadWriteTexture2D<Bgra32, Float4>(128, 128);
Upload(sourceTexture, Square(128, 128, 48, 48, 32, 32));
var parameters = Parameters(seed: 3);
Assert.True(pipeline.Simulate(sourceTexture, 128, 128, 0, 0, 128, 128, in parameters, hashSource: true));
Assert.False(pipeline.Simulate(sourceTexture, 128, 128, 0, 0, 128, 128, in parameters, hashSource: true));
var freezeChanged = parameters with { Freeze = 0.5f };
Assert.False(pipeline.Simulate(sourceTexture, 128, 128, 0, 0, 128, 128, in freezeChanged, hashSource: true));
var seedChanged = parameters with { Seed = 4 };
Assert.True(pipeline.Simulate(sourceTexture, 128, 128, 0, 0, 128, 128, in seedChanged, hashSource: true));
Upload(sourceTexture, Square(128, 128, 32, 32, 32, 32));
Assert.True(pipeline.Simulate(sourceTexture, 128, 128, 0, 0, 128, 128, in seedChanged, hashSource: true));
}
[Fact]
public void WithoutNoiseTheSeedDoesNotGrowTheCrystalsAgain()
{
using var pipeline = CreatePipeline();
var device = GraphicsDevice.GetDefault();
using var sourceTexture = device.AllocateReadWriteTexture2D<Bgra32, Float4>(128, 128);
Upload(sourceTexture, Square(128, 128, 48, 48, 32, 32));
var parameters = Parameters(noise: 0f, seed: 3);
var seedChanged = parameters with { Seed = 4 };
var noiseAdded = seedChanged with { Noise = 0.25f };
Assert.True(pipeline.Simulate(sourceTexture, 128, 128, 0, 0, 128, 128, in parameters, hashSource: true));
Assert.False(pipeline.Simulate(sourceTexture, 128, 128, 0, 0, 128, 128, in seedChanged, hashSource: true));
Assert.True(pipeline.Simulate(sourceTexture, 128, 128, 0, 0, 128, 128, in noiseAdded, hashSource: true));
}
[Fact]
public void WithoutNoiseEverySeedDrawsTheSameFrost()
{
using var pipeline = CreatePipeline();
var source = Square(128, 128, 48, 48, 32, 32);
var first = Render(pipeline, source, 128, 128, Parameters(noise: 0f, seed: 1));
var second = Render(pipeline, source, 128, 128, Parameters(noise: 0f, seed: 2));
Assert.Equal(first, second);
}
}
+135
ファイルの表示
@@ -0,0 +1,135 @@
namespace CrystallineGrowth.Tests;
public sealed class CrystallineGrowthSettingsTests
{
[Theory]
[InlineData(CrystallineGrowthQuality.Balanced, 192, 1200)]
[InlineData(CrystallineGrowthQuality.High, 288, 2048)]
[InlineData(CrystallineGrowthQuality.Ultra, 384, 3072)]
public void EveryQualityChoosesItsGridResolutionAndStepLimit(CrystallineGrowthQuality quality, int resolution, int maxSteps)
{
var settings = CrystallineGrowthSettings.GetQuality(quality);
Assert.Equal(resolution, settings.GridResolution);
Assert.Equal(maxSteps, settings.MaxSteps);
}
[Theory]
[InlineData(640, 480, 120d, 288, 200)]
[InlineData(1920, 1080, 480d, 192, 560)]
[InlineData(96, 24, 1d, 288, 81)]
public void TheMarginIsTheReachPlusThePaddingWhenTheReachSpansACell(int width, int height, double reachPixels, int resolution, int expected)
{
Assert.Equal(expected, CrystallineGrowthSettings.GetMargin(width, height, reachPixels, resolution));
}
[Theory]
[InlineData(8000, 24, 16d, 192)]
[InlineData(8100, 24, 1d, 192)]
[InlineData(8160, 8160, 1d, 192)]
[InlineData(8100, 24, 1d, 288)]
[InlineData(8160, 24, 1d, 384)]
[InlineData(96, 24, 1d, 192)]
public void AReachShorterThanACellTakesTheMarginOfOneCell(int width, int height, double reachPixels, int resolution)
{
var margin = CrystallineGrowthSettings.GetMargin(width, height, reachPixels, resolution);
var (_, _, cellSize) = CrystallineGrowthSettings.GetGridSize(width + margin * 2, height + margin * 2, resolution);
Assert.True(reachPixels < cellSize);
Assert.Equal((int)Math.Ceiling(cellSize + CrystallineGrowthSettings.MarginPadding), margin);
}
[Theory]
[InlineData(CrystallineGrowthQuality.Balanced, 8408)]
[InlineData(CrystallineGrowthQuality.High, 8380)]
[InlineData(CrystallineGrowthQuality.Ultra, 8364)]
public void TheLongestImageThatIsProcessedGetsTheLargestCanvas(CrystallineGrowthQuality quality, int expected)
{
var longSide = CrystallineGrowthSettings.MaximumCanvasSize - 32;
var resolution = CrystallineGrowthSettings.GetQuality(quality).GridResolution;
var margin = CrystallineGrowthSettings.GetMargin(longSide, longSide, 1d, resolution);
Assert.Equal(expected, longSide + margin * 2);
}
[Theory]
[InlineData(1, 8)]
[InlineData(8, 8)]
[InlineData(9, 16)]
[InlineData(1228, 1232)]
public void TheRenderRangeIsRoundedUpToWholeTiles(int length, int expected)
{
Assert.Equal(expected, CrystallineGrowthSettings.RoundUpToRenderTile(length));
}
[Theory]
[InlineData(1920, 1080, 288)]
[InlineData(1080, 1920, 288)]
[InlineData(8, 8, 288)]
[InlineData(4096, 16, 192)]
[InlineData(100, 100, 384)]
public void TheGridCoversTheWholeCanvas(int width, int height, int resolution)
{
var (gridWidth, gridHeight, cellSize) = CrystallineGrowthSettings.GetGridSize(width, height, resolution);
Assert.True(gridWidth >= CrystallineGrowthSettings.MinimumGridSize);
Assert.True(gridHeight >= CrystallineGrowthSettings.MinimumGridSize);
Assert.True(cellSize > 0f);
Assert.True(gridWidth * cellSize >= width);
Assert.True(gridHeight * cellSize * CrystallineGrowthSettings.RowStep >= height);
}
[Theory]
[InlineData(1920, 1080, 288, 1920f / 288)]
[InlineData(1080, 1920, 288, 1920f / 288)]
[InlineData(8, 8, 288, 1f)]
[InlineData(4096, 16, 192, 4096f / 192)]
[InlineData(100, 100, 384, 1f)]
[InlineData(2, 2, 288, 0.5f)]
public void TheLongSideIsSplitIntoTheResolutionButNeverIntoFewerThanTheMinimumCells(int width, int height, int resolution, float cellSize)
{
var (_, _, actual) = CrystallineGrowthSettings.GetGridSize(width, height, resolution);
Assert.Equal(cellSize, actual, 4);
}
[Theory]
[InlineData(0f, 1200, 192)]
[InlineData(10f, 1200, 368)]
[InlineData(60f, 2048, 1568)]
[InlineData(500f, 2048, 2048)]
[InlineData(500f, 1200, 1200)]
public void TheStepCountGrowsWithTheReachWithinItsLimits(float reachCells, int maxSteps, int expected)
=> Assert.Equal(expected, CrystallineGrowthSettings.GetStepCount(reachCells, maxSteps));
[Theory]
[InlineData(-5f, CrystallineGrowthSettings.MinimumVaporDensity)]
[InlineData(0f, CrystallineGrowthSettings.MinimumVaporDensity)]
[InlineData(1f, CrystallineGrowthSettings.MaximumVaporDensity)]
[InlineData(5f, CrystallineGrowthSettings.MaximumVaporDensity)]
public void TheVaporDensityStaysWithinItsRange(float branching, float expected)
=> Assert.Equal(expected, CrystallineGrowthSettings.GetVaporDensity(branching), 5);
[Fact]
public void MoreBranchingFillsTheAirWithMoreVapor()
=> Assert.True(CrystallineGrowthSettings.GetVaporDensity(0.75f) > CrystallineGrowthSettings.GetVaporDensity(0.25f));
[Theory]
[InlineData(0f, CrystallineGrowthSettings.MinimumBeta)]
[InlineData(1f, CrystallineGrowthSettings.MaximumBeta)]
public void TheAttachmentThresholdSpansItsRangeOverTheFacet(float facet, float expected)
=> Assert.Equal(expected, CrystallineGrowthSettings.GetAttachmentThreshold(facet), 5);
[Fact]
public void AStrongerFacetRaisesTheAttachmentThreshold()
=> Assert.True(CrystallineGrowthSettings.GetAttachmentThreshold(0.75f) > CrystallineGrowthSettings.GetAttachmentThreshold(0.25f));
[Theory]
[InlineData(-1f, 0f)]
[InlineData(0f, 0f)]
[InlineData(1f, CrystallineGrowthSettings.MaximumSigma)]
[InlineData(2f, CrystallineGrowthSettings.MaximumSigma)]
public void TheNoiseStaysWithinItsRange(float noise, float expected)
=> Assert.Equal(expected, CrystallineGrowthSettings.GetNoiseSigma(noise), 7);
}
+82
ファイルの表示
@@ -0,0 +1,82 @@
using ComputeWeave;
namespace CrystallineGrowth.Tests;
public sealed class CrystallineGrowthShaderMathTests
{
const float CellSize = 3f;
const int Column = 7;
static Float4 Texel(int[] bytes) => new(bytes[0] / 255f, bytes[1] / 255f, bytes[2] / 255f, bytes[3] / 255f);
public static readonly TheoryData<int, int> Neighbors = new()
{
{ 4, 0 }, { 4, 1 }, { 4, 2 }, { 4, 3 }, { 4, 4 }, { 4, 5 },
{ 5, 0 }, { 5, 1 }, { 5, 2 }, { 5, 3 }, { 5, 4 }, { 5, 5 },
};
[Theory]
[MemberData(nameof(Neighbors))]
public void EveryNeighborLiesOneCellAway(int row, int neighbor)
{
var center = CrystallineGrowthShaderMath.CellCenter(Column, row, CellSize);
var other = CrystallineGrowthShaderMath.CellCenter(
Column + CrystallineGrowthShaderMath.NeighborDx(neighbor, row & 1),
row + CrystallineGrowthShaderMath.NeighborDy(neighbor),
CellSize);
Assert.Equal(CellSize, MathF.Sqrt((other.X - center.X) * (other.X - center.X) + (other.Y - center.Y) * (other.Y - center.Y)), 4);
}
[Theory]
[InlineData(4, 0, 1)]
[InlineData(4, 1, 0)]
[InlineData(4, 2, 5)]
[InlineData(4, 5, 2)]
[InlineData(4, 3, 4)]
[InlineData(4, 4, 3)]
[InlineData(5, 0, 1)]
[InlineData(5, 1, 0)]
[InlineData(5, 2, 5)]
[InlineData(5, 5, 2)]
[InlineData(5, 3, 4)]
[InlineData(5, 4, 3)]
public void OppositeNeighborsPointBackToEachOther(int row, int neighbor, int opposite)
{
var x = Column + CrystallineGrowthShaderMath.NeighborDx(neighbor, row & 1);
var y = row + CrystallineGrowthShaderMath.NeighborDy(neighbor);
var back = (x + CrystallineGrowthShaderMath.NeighborDx(opposite, y & 1), y + CrystallineGrowthShaderMath.NeighborDy(opposite));
Assert.Equal((Column, row), back);
}
[Theory]
[InlineData(0)]
[InlineData(1)]
[InlineData(2)]
[InlineData(3)]
public void ChangingAnyChannelOfATexelChangesItsMix(int channel)
{
int[] original = [32, 96, 160, 255];
var changed = original.ToArray();
changed[channel] += channel == 3 ? -1 : 1;
var before = CrystallineGrowthShaderMath.MixTexel(1234, Texel(original));
var after = CrystallineGrowthShaderMath.MixTexel(1234, Texel(changed));
Assert.NotEqual(before, after);
}
[Fact]
public void TheSameTexelMixesDifferentlyAtAnotherPosition()
{
var texel = Texel([32, 96, 160, 255]);
var here = CrystallineGrowthShaderMath.MixTexel(1234, texel);
var there = CrystallineGrowthShaderMath.MixTexel(1235, texel);
Assert.NotEqual(here, there);
}
}
+28
ファイルの表示
@@ -0,0 +1,28 @@
using System.Drawing;
using System.Numerics;
using Vortice.Direct2D1;
using YukkuriMovieMaker.Player.Video;
namespace CrystallineGrowth.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 CrystallineGrowth.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;
}
+30
ファイルの表示
@@ -0,0 +1,30 @@
using System.Windows;
using Telemetry;
namespace CrystallineGrowth.Tests;
public sealed class HostIntegrationTests
{
[Fact]
public void OutsideAWpfApplicationNoTelemetryIsStartedOrSent()
{
Assert.Null(Application.Current);
CrystallineGrowthTelemetry.EnsureStartedOnce();
CrystallineGrowthTelemetry.Report(new InvalidOperationException());
Assert.Null(ProcessState.Read("DrainClaimed"));
Assert.Null(ProcessState.Read("SentCount"));
}
[Fact]
public void OutsideAWpfApplicationTheEffectCanStillBeCreated()
{
Assert.Null(Application.Current);
var effect = new CrystallineGrowthEffect();
Assert.Equal(Texts.CrystallineGrowth, effect.Label);
Assert.Null(ProcessState.Read("DrainClaimed"));
}
}
+10
ファイルの表示
@@ -0,0 +1,10 @@
using System.IO.Packaging;
using System.Runtime.CompilerServices;
namespace CrystallineGrowth.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 CrystallineGrowth.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 CrystallineGrowth.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 CrystallineGrowth.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.CrystallineGrowth), CultureInfo.InvariantCulture);
Assert.Equal("氷晶成長", neutral);
Assert.Equal(neutral, Texts.ResourceManager.GetString(nameof(Texts.CrystallineGrowth), 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": "CrystallineGrowth.csproj",
"test-runner": "mtp",
"coverage-analysis": "off",
"concurrency": 4,
"additional-timeout": 30000,
"mutate": [
"**/*.cs",
"!**/YMM4-GitHubUpdateNotifier/**",
"!**/YMM4-Telemetry/**",
"!**/CrystallineGrowthTelemetry.cs",
"!**/CrystallineGrowthUpdateNotifier.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="CrystallineGrowth/CrystallineGrowth.csproj">
<Platform Solution="*|x64" Project="x64" />
<BuildDependency Project="CrystallineGrowth.Shader/CrystallineGrowth.Shader.vcxproj" />
</Project>
<Project Path="CrystallineGrowth.Tests/CrystallineGrowth.Tests.csproj" />
<Project Path="CrystallineGrowth.Harness/CrystallineGrowth.Harness.csproj" />
<Project Path="CrystallineGrowth.Shader/CrystallineGrowth.Shader.vcxproj" Id="14bdae0a-c2b1-473e-a90c-2ac115506780">
<BuildType Project="Release" />
<Platform Project="Win32" />
</Project>
<Project Path="YukkuriMovieMaker.Generator/YukkuriMovieMaker.Generator/YukkuriMovieMaker.Generator.csproj" />
</Solution>
-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="CrystallineGrowth.ComputeSharp, PublicKey=$(AssemblySignPublicKey)" />
</ItemGroup>
</Project>
-14
ファイルの表示
@@ -1,14 +0,0 @@
<Project>
<PropertyGroup Condition="'$(MSBuildProjectName)' == 'ComputeSharp' or '$(MSBuildProjectName)' == 'ComputeSharp.Core'">
<BaseOutputPath>$(MSBuildProjectDirectory)\bin\CrystallineGrowth\</BaseOutputPath>
<BaseIntermediateOutputPath>$(MSBuildProjectDirectory)\obj\CrystallineGrowth\</BaseIntermediateOutputPath>
<MSBuildProjectExtensionsPath>$(MSBuildProjectDirectory)\obj\</MSBuildProjectExtensionsPath>
<DefaultItemExcludes>$(DefaultItemExcludes);$(MSBuildProjectDirectory)\obj\**</DefaultItemExcludes>
</PropertyGroup>
<PropertyGroup Condition="'$(MSBuildProjectName)' == 'ComputeSharp'">
<AssemblyName>CrystallineGrowth.ComputeSharp</AssemblyName>
</PropertyGroup>
<PropertyGroup Condition="'$(MSBuildProjectName)' == 'ComputeSharp.Core'">
<AssemblyName>CrystallineGrowth.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>
+13 -26
ファイルの表示
@@ -5,32 +5,18 @@
<UseWPF>true</UseWPF>
<ImplicitUsings>enable</ImplicitUsings>
<Nullable>enable</Nullable>
<Version>1.0.1</Version>
<Version>1.1.0</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)CrystallineGrowth.cso" Link="Resources\Shader\CrystallineGrowth.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)CrystallineGrowth.ComputeSharp.dll&quot; &quot;$(YMM4DirPath)user\plugin\$(ProjectName)\&quot;&#xD;&#xA;copy &quot;$(TargetDir)CrystallineGrowth.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;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&#xD;&#xA;copy &quot;$(TargetDir)plugin\$(TargetFileName)&quot; &quot;$(YMM4DirPath)user\plugin\$(ProjectName)\&quot;" />
</Target>
</Project>
+12 -1
ファイルの表示
@@ -33,7 +33,18 @@ internal sealed class CrystallineGrowthCustomEffect(IGraphicsDevicesAndContext d
protected override void UpdateConstants()
{
drawInformation?.SetPixelShaderConstantBuffer(_cb);
if (drawInformation is null)
return;
try
{
drawInformation.SetPixelShaderConstantBuffer(_cb);
}
catch (Exception exception)
{
CrystallineGrowthTelemetry.Report(exception);
throw;
}
}
public override void MapInputRectsToOutputRect(
+12 -1
ファイルの表示
@@ -16,6 +16,7 @@ public sealed class CrystallineGrowthEffect : VideoEffectBase
public CrystallineGrowthEffect()
{
CrystallineGrowthTelemetry.EnsureStartedOnce();
CrystallineGrowthUpdateNotifier.EnsureCheckedOnce();
}
@@ -85,7 +86,17 @@ public sealed class CrystallineGrowthEffect : VideoEffectBase
public override IEnumerable<string> CreateExoVideoFilters(int keyFrameIndex, ExoOutputDescription exoOutputDescription) => [];
public override IVideoEffectProcessor CreateVideoEffect(IGraphicsDevicesAndContext devices)
=> new CrystallineGrowthEffectProcessor(devices, this);
{
try
{
return new CrystallineGrowthEffectProcessor(devices, this);
}
catch (Exception exception)
{
CrystallineGrowthTelemetry.Report(exception);
throw;
}
}
protected override IEnumerable<IAnimatable> GetAnimatables()
=> _animatables ??= [Amount, Freeze, Branching, Facet, Reach, Noise, Frost, Refraction, Specular];
+191 -76
ファイルの表示
@@ -1,4 +1,6 @@
using System.ComponentModel;
using System.Numerics;
using ComputeWeave;
using Vortice.Direct2D1;
using Vortice.Direct2D1.Effects;
using YukkuriMovieMaker.Commons;
@@ -11,7 +13,11 @@ internal sealed class CrystallineGrowthEffectProcessor : VideoEffectProcessorBas
{
private readonly IGraphicsDevicesAndContext _devices;
private readonly CrystallineGrowthEffect _item;
private CrystallineGrowthGpuInterop? _interop;
private ComputeExternalQueueScheduler? _scheduler;
private CrystallineGrowthInteropProvider? _interopProvider;
private ComputeInteropDomain? _interopDomain;
private CrystallineGrowthResourceSet? _resourceSet;
private ExternalTextureLease<ExternalDirect3D11TextureView>? _outputLease;
private CrystallineGrowthPipeline? _pipeline;
private CrystallineGrowthCustomEffect? _effect;
private Crop? _outputCrop;
@@ -37,7 +43,20 @@ internal sealed class CrystallineGrowthEffectProcessor : VideoEffectProcessorBas
public override DrawDescription Update(EffectDescription effectDescription)
{
if (IsPassThroughEffect || _effect is null || _outputCrop is null || _outputTransform is null || _outputTransformOutput is null || _interop is null || _pipeline is null || input is null)
try
{
return UpdateCore(effectDescription);
}
catch (Exception exception)
{
CrystallineGrowthTelemetry.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;
@@ -89,9 +108,9 @@ internal sealed class CrystallineGrowthEffectProcessor : VideoEffectProcessorBas
_isFirst = true;
return effectDescription.DrawDescription;
}
var padding = (double)CrystallineGrowthSettings.MarginPadding;
var reachPixels = Math.Min(reach * longSide, Math.Max(marginLimit - padding, 1d));
var margin = (int)Math.Ceiling(reachPixels + padding);
var reachPixels = Math.Min(reach * longSide, Math.Max(marginLimit - CrystallineGrowthSettings.MarginPadding, 1d));
var margin = CrystallineGrowthSettings.GetMargin(
(int)widthValue, (int)heightValue, reachPixels, CrystallineGrowthSettings.GetQuality(parameters.Quality).GridResolution);
var canvasWidthValue = widthValue + margin * 2d;
var canvasHeightValue = heightValue + margin * 2d;
if (canvasWidthValue * canvasHeightValue > int.MaxValue)
@@ -105,8 +124,14 @@ internal sealed class CrystallineGrowthEffectProcessor : VideoEffectProcessorBas
var itemWidth = (int)widthValue;
var itemHeight = (int)heightValue;
_interop.EnsureSource(itemWidth, itemHeight);
_interop.RenderInput(input, new Vortice.RawRectF(bounds.Left, bounds.Top, bounds.Left + itemWidth, bounds.Top + itemHeight));
if (!EnsureSource(itemWidth, itemHeight))
{
_effect.Amount = 0f;
_isFirst = true;
return effectDescription.DrawDescription;
}
RenderInput(new Vortice.RawRectF(bounds.Left, bounds.Top, bounds.Left + itemWidth, bounds.Top + itemHeight));
var pipelineParameters = new CrystallineGrowthPipeline.Parameters(
parameters.Quality,
@@ -123,24 +148,24 @@ internal sealed class CrystallineGrowthEffectProcessor : VideoEffectProcessorBas
parameters.Color.B / 255f,
Math.Max(parameters.Seed, 0));
bool structureChanged;
_interop.BeginCompute();
try
{
structureChanged = _pipeline.Simulate(
_interop.SourceTexture,
canvasWidth,
canvasHeight,
margin,
margin,
itemWidth,
itemHeight,
in pipelineParameters);
}
finally
{
_interop.EndCompute();
}
var renderSettings = new RenderSettings(
pipelineParameters.Freeze,
pipelineParameters.Frost,
pipelineParameters.Refraction,
pipelineParameters.Specular,
pipelineParameters.ColorR,
pipelineParameters.ColorG,
pipelineParameters.ColorB);
var structureChanged = _pipeline.Simulate(
_resourceSet.GetSourceComputeBinding(),
canvasWidth,
canvasHeight,
margin,
margin,
itemWidth,
itemHeight,
in pipelineParameters,
_hasOutput && _hasRenderState && _renderState.Settings == renderSettings);
if (!_pipeline.TryGetVisibleBounds(canvasWidth, canvasHeight, in pipelineParameters, out var rect))
{
@@ -151,46 +176,40 @@ internal sealed class CrystallineGrowthEffectProcessor : VideoEffectProcessorBas
return effectDescription.DrawDescription;
}
if (!_interop.OutputCovers(rect.Width, rect.Height))
if (!OutputCovers(rect.Width, rect.Height))
_outputCrop.SetInput(0, null, true);
var outputChanged = _interop.EnsureOutput(rect.Width, rect.Height);
var renderState = new RenderState(
pipelineParameters.Freeze,
pipelineParameters.Frost,
pipelineParameters.Refraction,
pipelineParameters.Specular,
pipelineParameters.ColorR,
pipelineParameters.ColorG,
pipelineParameters.ColorB,
rect);
if (!EnsureOutput(rect.Width, rect.Height, out var outputChanged))
{
_effect.Amount = 0f;
_parameters = parameters;
_isFirst = true;
_hasRenderState = false;
return effectDescription.DrawDescription;
}
var renderState = new RenderState(renderSettings, rect, _pipeline.SourceHash);
if (structureChanged || outputChanged || !_hasOutput || !_hasRenderState || _renderState != renderState)
{
_interop.BeginCompute();
try
{
_pipeline.RenderVisible(
_interop.SourceTexture,
_interop.OutputTexture,
canvasWidth,
canvasHeight,
margin,
margin,
itemWidth,
itemHeight,
rect,
in pipelineParameters);
}
finally
{
_interop.EndCompute();
}
_pipeline.RenderVisible(
_resourceSet.GetSourceComputeBinding(),
_resourceSet.GetOutputComputeBinding(),
canvasWidth,
canvasHeight,
margin,
margin,
itemWidth,
itemHeight,
rect,
in pipelineParameters);
_renderState = renderState;
_hasRenderState = true;
}
_outputLease ??= _resourceSet.AcquireOutputExternalViewLease();
if (outputChanged || !_hasOutput)
{
_outputCrop.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, rect.Width, rect.Height);
@@ -213,15 +232,97 @@ internal sealed class CrystallineGrowthEffectProcessor : VideoEffectProcessorBas
return effectDescription.DrawDescription;
}
private bool EnsureSource(int width, int height)
{
return _resourceSet!.TryEnsureSource(width, height, out _);
}
private bool OutputCovers(int width, int height)
=> _outputLease is { IsDisposed: false } lease &&
lease.Width >= width &&
lease.Height >= height;
private bool EnsureOutput(int width, int height, out bool changed)
{
changed = false;
if (OutputCovers(width, height))
return true;
_outputLease?.Dispose();
_outputLease = null;
return _resourceSet!.TryEnsureOutput(width, height, out changed);
}
private void RenderInput(Vortice.RawRectF bounds)
{
var renderContext = _interopProvider!.RenderContext;
using var borrow = _resourceSet!.BeginSourceExternalOperation();
var previousTarget = renderContext.Target;
using var sourceBitmap = new ID2D1Bitmap1(borrow.DangerousGetView().AddRefBitmap());
renderContext.Target = sourceBitmap;
renderContext.BeginDraw();
renderContext.Clear(null);
renderContext.DrawImage(
input,
new Vector2(-bounds.Left, -bounds.Top),
null,
InterpolationMode.NearestNeighbor,
CompositeMode.SourceCopy);
renderContext.EndDraw();
renderContext.Target = previousTarget;
}
private 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 = CrystallineGrowthGpuInterop.TryCreate(devices);
if (interop is null)
return null;
var pipeline = CrystallineGrowthPipeline.TryCreate(interop.Device);
if (pipeline is null)
var scheduler = ComputeExternalQueueScheduler.Create();
var interopProvider = CrystallineGrowthInteropProvider.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 = CrystallineGrowthResourceSet.Create(interopDevice, _interopDomain);
_pipeline = CrystallineGrowthPipeline.TryCreate(interopDevice);
}
catch (Win32Exception)
{
ReleaseInterop();
return null;
}
catch
{
ReleaseInterop();
throw;
}
if (_pipeline is null)
{
ReleaseInterop();
return null;
}
@@ -237,8 +338,7 @@ internal sealed class CrystallineGrowthEffectProcessor : VideoEffectProcessorBas
if (!effect.IsEnabled)
{
effect.Dispose();
pipeline.Dispose();
interop.Dispose();
ReleaseInterop();
return null;
}
outputCrop = new Crop(devices.DeviceContext);
@@ -250,8 +350,6 @@ internal sealed class CrystallineGrowthEffectProcessor : VideoEffectProcessorBas
outputTransform.SetInput(0, outputCropOutput, true);
outputTransformOutput = outputTransform.Output;
output = effect.Output;
_interop = interop;
_pipeline = pipeline;
_effect = effect;
_outputCrop = outputCrop;
_outputCropOutput = outputCropOutput;
@@ -273,13 +371,25 @@ internal sealed class CrystallineGrowthEffectProcessor : VideoEffectProcessorBas
outputCropOutput?.Dispose();
outputCrop?.Dispose();
effect?.Dispose();
pipeline.Dispose();
interop.Dispose();
ReleaseInterop();
throw;
}
}
protected override void setInput(ID2D1Image? inputImage)
{
try
{
SetInputCore(inputImage);
}
catch (Exception exception)
{
CrystallineGrowthTelemetry.Report(exception);
throw;
}
}
private void SetInputCore(ID2D1Image? inputImage)
{
_effect?.SetInput(0, inputImage, true);
if (!_hasOutput)
@@ -305,28 +415,33 @@ internal sealed class CrystallineGrowthEffectProcessor : VideoEffectProcessorBas
if (disposing)
{
ClearEffectChain();
_interop?.WaitForIdle();
_pipeline?.Dispose();
_pipeline = null;
_interop?.Dispose();
_interop = null;
ReleaseInterop();
}
}
catch (Exception exception)
{
CrystallineGrowthTelemetry.Report(exception);
throw;
}
finally
{
base.Dispose(disposing);
}
}
private readonly record struct RenderState(
private readonly record struct RenderSettings(
float Freeze,
float Frost,
float Refraction,
float Specular,
float ColorR,
float ColorG,
float ColorB,
CrystallineGrowthPipeline.PixelRect Rect);
float ColorB);
private readonly record struct RenderState(
RenderSettings Settings,
CrystallineGrowthPipeline.PixelRect Rect,
CrystallineGrowthPipeline.ContentHash? Source);
private readonly record struct Parameters(
float Amount,
+56 -290
ファイルの表示
@@ -1,323 +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 CrystallineGrowth;
internal sealed class CrystallineGrowthGpuInterop : IDisposable
internal sealed class CrystallineGrowthInteropProvider : 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 _sourceWidth;
private int _sourceHeight;
private int _outputWidth;
private int _outputHeight;
private ulong _fenceValue;
private bool _computeActive;
private bool _disposed;
private CrystallineGrowthGpuInterop(
GraphicsDevice device,
ID3D11Device1 d3dDevice,
ID3D11DeviceContext4 d3dContext,
ID3D11Fence fence,
private CrystallineGrowthInteropProvider(
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 SourceMatches(int width, int height)
=> _sourceTexture is not null && _sourceWidth == width && _sourceHeight == height;
public bool OutputCovers(int width, int height)
=> _outputTexture is not null && _outputWidth >= width && _outputHeight >= height;
public static unsafe CrystallineGrowthGpuInterop? TryCreate(IGraphicsDevicesAndContext devices)
public static CrystallineGrowthInteropProvider? 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 CrystallineGrowthGpuInterop(device, d3dDevice, d3dContext, fence, renderContext, d3d12Fence);
var provider = new CrystallineGrowthInteropProvider(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()
{
var sourceChanged = EnsureSource(width, height);
var outputChanged = EnsureOutput(width, height);
return sourceChanged || outputChanged;
_renderContext.Dispose();
}
public bool EnsureSource(int width, int height)
{
if (SourceMatches(width, height))
return false;
if (_sourceTexture is not null)
WaitForIdle();
ReleaseSourceResources();
CreateSourceResources(width, height);
return true;
}
public bool EnsureOutput(int width, int height)
{
if (OutputCovers(width, height))
return false;
var capacityWidth = Math.Max(width, _outputWidth);
var capacityHeight = Math.Max(height, _outputHeight);
if (_outputTexture is not null)
WaitForIdle();
ReleaseOutputResources();
CreateOutputResources(capacityWidth, capacityHeight);
return true;
}
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 CreateSourceResources(int width, int height)
{
ReadWriteTexture2D<Bgra32, Float4>? sourceTexture = null;
ID3D11Texture2D? sourceD3D11Texture = null;
ID2D1Bitmap1? sourceBitmap = null;
nint sourceHandle = 0;
try
{
sourceTexture = InteropServices.AllocateSharedReadWriteTexture2D<Bgra32, Float4>(_device, width, height);
sourceHandle = InteropServices.CreateSharedHandle(sourceTexture);
sourceD3D11Texture = _d3dDevice.OpenSharedResource1<ID3D11Texture2D>(sourceHandle);
using var sourceSurface = sourceD3D11Texture.QueryInterface<IDXGISurface>();
var pixelFormat = new PixelFormat(Format.B8G8R8A8_UNorm, Vortice.DCommon.AlphaMode.Premultiplied);
sourceBitmap = _renderContext.CreateBitmapFromDxgiSurface(
sourceSurface,
new BitmapProperties1(pixelFormat, 96f, 96f, BitmapOptions.Target));
_renderContext.Target = sourceBitmap;
_sourceTexture = sourceTexture;
_sourceD3D11Texture = sourceD3D11Texture;
_sourceBitmap = sourceBitmap;
_sourceWidth = width;
_sourceHeight = height;
sourceTexture = null;
sourceD3D11Texture = null;
sourceBitmap = null;
}
finally
{
if (sourceHandle != 0)
CloseHandle(sourceHandle);
sourceBitmap?.Dispose();
sourceD3D11Texture?.Dispose();
sourceTexture?.Dispose();
}
}
private void CreateOutputResources(int width, int height)
{
ReadWriteTexture2D<Bgra32, Float4>? outputTexture = null;
ID3D11Texture2D? outputD3D11Texture = null;
ID2D1Bitmap1? outputBitmap = null;
nint outputHandle = 0;
try
{
outputTexture = InteropServices.AllocateSharedReadWriteTexture2D<Bgra32, Float4>(_device, width, height);
outputHandle = InteropServices.CreateSharedHandle(outputTexture);
outputD3D11Texture = _d3dDevice.OpenSharedResource1<ID3D11Texture2D>(outputHandle);
using var outputSurface = outputD3D11Texture.QueryInterface<IDXGISurface>();
var pixelFormat = new PixelFormat(Format.B8G8R8A8_UNorm, Vortice.DCommon.AlphaMode.Premultiplied);
outputBitmap = _renderContext.CreateBitmapFromDxgiSurface(
outputSurface,
new BitmapProperties1(pixelFormat, 96f, 96f, BitmapOptions.None));
_outputTexture = outputTexture;
_outputD3D11Texture = outputD3D11Texture;
_outputBitmap = outputBitmap;
_outputWidth = width;
_outputHeight = height;
outputTexture = null;
outputD3D11Texture = null;
outputBitmap = null;
}
finally
{
if (outputHandle != 0)
CloseHandle(outputHandle);
outputBitmap?.Dispose();
outputD3D11Texture?.Dispose();
outputTexture?.Dispose();
}
}
private void ReleaseSourceResources()
{
_renderContext.Target = null;
_sourceBitmap?.Dispose();
_sourceD3D11Texture?.Dispose();
_sourceTexture?.Dispose();
_sourceBitmap = null;
_sourceD3D11Texture = null;
_sourceTexture = null;
_sourceWidth = 0;
_sourceHeight = 0;
}
private void ReleaseOutputResources()
{
_outputBitmap?.Dispose();
_outputD3D11Texture?.Dispose();
_outputTexture?.Dispose();
_outputBitmap = null;
_outputD3D11Texture = null;
_outputTexture = null;
_outputWidth = 0;
_outputHeight = 0;
}
public void Dispose()
{
if (_disposed)
return;
try
{
WaitForIdle();
}
finally
{
_disposed = true;
ReleaseOutputResources();
ReleaseSourceResources();
_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 CrystallineGrowthResourceSet
{
[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;
}
+522 -24
ファイルの表示
@@ -1,4 +1,5 @@
using ComputeSharp;
// Stryker disable all
using ComputeWeave;
namespace CrystallineGrowth;
@@ -145,6 +146,77 @@ internal readonly partial struct MaskHashShader(
}
}
[ThreadGroupSize(DefaultThreadGroupSizes.X)]
[GeneratedComputeShaderDescriptor]
internal readonly partial struct ShadedCountResetShader(
ReadWriteBuffer<int> scratch) : IComputeShader
{
private readonly ReadWriteBuffer<int> scratch = scratch;
public void Execute()
{
scratch[CrystallineGrowthSettings.ScratchShadedCount] = 0;
}
}
[ThreadGroupSize(DefaultThreadGroupSizes.X)]
[GeneratedComputeShaderDescriptor]
internal readonly partial struct SourceHashResetShader(
ReadWriteBuffer<int> scratch) : IComputeShader
{
private readonly ReadWriteBuffer<int> scratch = scratch;
public void Execute()
{
if (ThreadIds.X != 0)
return;
scratch[8] = 0;
scratch[9] = 0;
}
}
[ThreadGroupSize(DefaultThreadGroupSizes.XY)]
[GeneratedComputeShaderDescriptor]
internal readonly partial struct SourceHashShader(
ReadWriteTexture2D<Bgra32, Float4> source,
ReadWriteBuffer<int> scratch,
int sourceWidth,
int sourceHeight) : IComputeShader
{
private readonly ReadWriteTexture2D<Bgra32, Float4> source = source;
private readonly ReadWriteBuffer<int> scratch = scratch;
private readonly int sourceWidth = sourceWidth;
private readonly int sourceHeight = sourceHeight;
[GroupShared(2)]
private static readonly int[] groupScratch = null!;
public void Execute()
{
if (GroupIds.Index == 0)
{
groupScratch[0] = 0;
groupScratch[1] = 0;
}
Hlsl.GroupMemoryBarrierWithGroupSync();
var x = ThreadIds.X;
var y = ThreadIds.Y;
if (x < sourceWidth && y < sourceHeight)
{
var mixed = CrystallineGrowthShaderMath.MixTexel((uint)(y * sourceWidth + x), source[new Int2(x, y)]);
Hlsl.InterlockedAdd(ref groupScratch[0], (int)mixed);
Hlsl.InterlockedXor(ref groupScratch[1], (int)(mixed * 0xC2B2AE35u));
}
Hlsl.GroupMemoryBarrierWithGroupSync();
if (GroupIds.Index != 0)
return;
Hlsl.InterlockedAdd(ref scratch[8], groupScratch[0]);
Hlsl.InterlockedXor(ref scratch[9], groupScratch[1]);
}
}
[ThreadGroupSize(DefaultThreadGroupSizes.XY)]
[GeneratedComputeShaderDescriptor]
internal readonly partial struct SeedInitShader(
@@ -323,7 +395,7 @@ internal readonly partial struct ReachMaskShader(
}
}
[ThreadGroupSize(DefaultThreadGroupSizes.XY)]
[ThreadGroupSize(CrystallineGrowthSettings.GrowthGroupWidth, CrystallineGrowthSettings.GrowthGroupHeight, 1)]
[GeneratedComputeShaderDescriptor]
internal readonly partial struct DiffusionShader(
ReadWriteBuffer<float> diffusiveIn,
@@ -369,7 +441,7 @@ internal readonly partial struct DiffusionShader(
}
}
[ThreadGroupSize(DefaultThreadGroupSizes.XY)]
[ThreadGroupSize(CrystallineGrowthSettings.GrowthGroupWidth, CrystallineGrowthSettings.GrowthGroupHeight, 1)]
[GeneratedComputeShaderDescriptor]
internal readonly partial struct GrowthUpdateShader(
ReadWriteBuffer<float> diffusiveMid,
@@ -483,12 +555,44 @@ internal readonly partial struct GrowthUpdateShader(
}
}
[ThreadGroupSize(DefaultThreadGroupSizes.XY)]
[ThreadGroupSize(DefaultThreadGroupSizes.X)]
[GeneratedComputeShaderDescriptor]
internal readonly partial struct RenderShader(
internal readonly partial struct RenderMassShader(
ReadWriteBuffer<int> birth,
ReadWriteBuffer<float> crystalMass,
ReadWriteBuffer<int> scratch,
ReadWriteBuffer<float> renderMass,
int gridLength,
float freeze) : IComputeShader
{
private readonly ReadWriteBuffer<int> birth = birth;
private readonly ReadWriteBuffer<float> crystalMass = crystalMass;
private readonly ReadWriteBuffer<int> scratch = scratch;
private readonly ReadWriteBuffer<float> renderMass = renderMass;
private readonly int gridLength = gridLength;
private readonly float freeze = freeze;
public void Execute()
{
var index = ThreadIds.X;
if (index >= gridLength)
return;
var visible = freeze * (scratch[1] + 1);
var cellBirth = birth[index];
var mass = 0f;
if (cellBirth < CrystallineGrowthSettings.BirthSentinel)
{
var fade = Hlsl.Saturate(visible - cellBirth);
mass = fade * (0.55f + 0.45f * Hlsl.Saturate(crystalMass[index] * CrystallineGrowthSettings.MassScale));
}
renderMass[index] = mass;
}
}
[ThreadGroupSize(CrystallineGrowthSettings.RenderTileSize, CrystallineGrowthSettings.RenderTileSize, 1)]
[GeneratedComputeShaderDescriptor]
internal readonly partial struct RenderShader(
ReadWriteBuffer<float> renderMass,
ReadWriteTexture2D<Bgra32, Float4> source,
ReadWriteTexture2D<Bgra32, Float4> output,
int rectOffsetX,
@@ -502,7 +606,6 @@ internal readonly partial struct RenderShader(
int sourceWidth,
int sourceHeight,
float cellSize,
float freeze,
float frost,
float refractionPixels,
float specular,
@@ -510,9 +613,7 @@ internal readonly partial struct RenderShader(
float colorG,
float colorB) : IComputeShader
{
private readonly ReadWriteBuffer<int> birth = birth;
private readonly ReadWriteBuffer<float> crystalMass = crystalMass;
private readonly ReadWriteBuffer<int> scratch = scratch;
private readonly ReadWriteBuffer<float> renderMass = renderMass;
private readonly ReadWriteTexture2D<Bgra32, Float4> source = source;
private readonly ReadWriteTexture2D<Bgra32, Float4> output = output;
private readonly int rectOffsetX = rectOffsetX;
@@ -526,7 +627,6 @@ internal readonly partial struct RenderShader(
private readonly int sourceWidth = sourceWidth;
private readonly int sourceHeight = sourceHeight;
private readonly float cellSize = cellSize;
private readonly float freeze = freeze;
private readonly float frost = frost;
private readonly float refractionPixels = refractionPixels;
private readonly float specular = specular;
@@ -534,17 +634,43 @@ internal readonly partial struct RenderShader(
private readonly float colorG = colorG;
private readonly float colorB = colorB;
[GroupShared(1)]
private static readonly int[] tileLit = null!;
public void Execute()
{
if (ThreadIds.X >= rectWidth || ThreadIds.Y >= rectHeight)
return;
var px = ThreadIds.X + rectOffsetX + 0.5f;
var py = ThreadIds.Y + rectOffsetY + 0.5f;
var visible = freeze * (scratch[1] + 1);
var kernelRadius = CrystallineGrowthSettings.KernelRadiusFactor * cellSize;
var inverseRadiusSquared = 1f / (kernelRadius * kernelRadius);
var rowStep = cellSize * CrystallineGrowthSettings.RowStep;
if (GroupIds.Index == 0)
tileLit[0] = 0;
Hlsl.GroupMemoryBarrierWithGroupSync();
var tileLeft = ThreadIds.X - GroupIds.X + rectOffsetX + 0.5f;
var tileTop = ThreadIds.Y - GroupIds.Y + rectOffsetY + 0.5f;
var tileSpan = CrystallineGrowthSettings.RenderTileSize - 1;
var tileJ0 = Hlsl.Max((int)Hlsl.Floor((tileTop - kernelRadius) / rowStep - 0.5f) - 1, 0);
var tileJ1 = Hlsl.Min((int)Hlsl.Ceil((tileTop + tileSpan + kernelRadius) / rowStep - 0.5f) + 1, gridHeight - 1);
var tileI0 = Hlsl.Max((int)Hlsl.Floor((tileLeft - kernelRadius) / cellSize - 1f) - 1, 0);
var tileI1 = Hlsl.Min((int)Hlsl.Ceil((tileLeft + tileSpan + kernelRadius) / cellSize - 0.5f) + 1, gridWidth - 1);
var tileWidth = Hlsl.Max(tileI1 - tileI0 + 1, 0);
var tileCells = tileWidth * Hlsl.Max(tileJ1 - tileJ0 + 1, 0);
for (var slot = GroupIds.Index; slot < tileCells; slot += CrystallineGrowthSettings.RenderTileSize * CrystallineGrowthSettings.RenderTileSize)
{
if (renderMass[(tileJ0 + slot / tileWidth) * gridWidth + tileI0 + slot % tileWidth] > 0f)
Hlsl.InterlockedOr(ref tileLit[0], 1);
}
Hlsl.GroupMemoryBarrierWithGroupSync();
if (ThreadIds.X >= rectWidth || ThreadIds.Y >= rectHeight)
return;
if (tileLit[0] == 0)
{
output[ThreadIds.XY] = new Float4(0f, 0f, 0f, 0f);
return;
}
var px = ThreadIds.X + rectOffsetX + 0.5f;
var py = ThreadIds.Y + rectOffsetY + 0.5f;
var j0 = Hlsl.Max((int)Hlsl.Floor((py - kernelRadius) / rowStep - 0.5f), 0);
var j1 = Hlsl.Min((int)Hlsl.Ceil((py + kernelRadius) / rowStep - 0.5f), gridHeight - 1);
@@ -572,14 +698,7 @@ internal readonly partial struct RenderShader(
var oneMinusU = 1f - u;
var weight = oneMinusU * oneMinusU;
var weightGradientScale = -4f * oneMinusU * inverseRadiusSquared;
var index = j * gridWidth + i;
var cellBirth = birth[index];
var mass = 0f;
if (cellBirth < CrystallineGrowthSettings.BirthSentinel)
{
var fade = Hlsl.Saturate(visible - cellBirth);
mass = fade * (0.55f + 0.45f * Hlsl.Saturate(crystalMass[index] * CrystallineGrowthSettings.MassScale));
}
var mass = renderMass[j * gridWidth + i];
num += weight * mass;
den += weight;
numX += weightGradientScale * dx * mass;
@@ -653,6 +772,362 @@ internal readonly partial struct RenderShader(
}
}
[ThreadGroupSize(CrystallineGrowthSettings.RenderTileSize, CrystallineGrowthSettings.RenderTileSize, 1)]
[GeneratedComputeShaderDescriptor]
internal readonly partial struct RenderStoreShader(
ReadWriteBuffer<float> renderMass,
ReadWriteBuffer<int> scratch,
ReadWriteBuffer<int> tileBase,
ReadWriteBuffer<int> tileMask,
ReadWriteBuffer<float> geometry,
ReadWriteTexture2D<Bgra32, Float4> source,
ReadWriteTexture2D<Bgra32, Float4> output,
int rectOffsetX,
int rectOffsetY,
int rectWidth,
int rectHeight,
int gridWidth,
int gridHeight,
int sourceOffsetX,
int sourceOffsetY,
int sourceWidth,
int sourceHeight,
float cellSize,
float frost,
float refractionPixels,
float specular,
float colorR,
float colorG,
float colorB,
int mode,
int geometryCapacity) : IComputeShader
{
private readonly ReadWriteBuffer<float> renderMass = renderMass;
private readonly ReadWriteBuffer<int> scratch = scratch;
private readonly ReadWriteBuffer<int> tileBase = tileBase;
private readonly ReadWriteBuffer<int> tileMask = tileMask;
private readonly ReadWriteBuffer<float> geometry = geometry;
private readonly ReadWriteTexture2D<Bgra32, Float4> source = source;
private readonly ReadWriteTexture2D<Bgra32, Float4> output = output;
private readonly int rectOffsetX = rectOffsetX;
private readonly int rectOffsetY = rectOffsetY;
private readonly int rectWidth = rectWidth;
private readonly int rectHeight = rectHeight;
private readonly int gridWidth = gridWidth;
private readonly int gridHeight = gridHeight;
private readonly int sourceOffsetX = sourceOffsetX;
private readonly int sourceOffsetY = sourceOffsetY;
private readonly int sourceWidth = sourceWidth;
private readonly int sourceHeight = sourceHeight;
private readonly float cellSize = cellSize;
private readonly float frost = frost;
private readonly float refractionPixels = refractionPixels;
private readonly float specular = specular;
private readonly float colorR = colorR;
private readonly float colorG = colorG;
private readonly float colorB = colorB;
private readonly int mode = mode;
private readonly int geometryCapacity = geometryCapacity;
[GroupShared(4)]
private static readonly int[] tileShared = null!;
public void Execute()
{
var kernelRadius = CrystallineGrowthSettings.KernelRadiusFactor * cellSize;
var inverseRadiusSquared = 1f / (kernelRadius * kernelRadius);
var rowStep = cellSize * CrystallineGrowthSettings.RowStep;
var tile = ThreadIds.Y / CrystallineGrowthSettings.RenderTileSize * ((rectWidth + CrystallineGrowthSettings.RenderTileSize - 1) / CrystallineGrowthSettings.RenderTileSize)
+ ThreadIds.X / CrystallineGrowthSettings.RenderTileSize;
var bit = GroupIds.Index;
var inside = ThreadIds.X < rectWidth && ThreadIds.Y < rectHeight;
var px = ThreadIds.X + rectOffsetX + 0.5f;
var py = ThreadIds.Y + rectOffsetY + 0.5f;
if (GroupIds.Index == 0)
{
tileShared[0] = 0;
tileShared[1] = 0;
tileShared[2] = 0;
}
Hlsl.GroupMemoryBarrierWithGroupSync();
var tileLeft = ThreadIds.X - GroupIds.X + rectOffsetX + 0.5f;
var tileTop = ThreadIds.Y - GroupIds.Y + rectOffsetY + 0.5f;
var tileSpan = CrystallineGrowthSettings.RenderTileSize - 1;
var tileJ0 = Hlsl.Max((int)Hlsl.Floor((tileTop - kernelRadius) / rowStep - 0.5f) - 1, 0);
var tileJ1 = Hlsl.Min((int)Hlsl.Ceil((tileTop + tileSpan + kernelRadius) / rowStep - 0.5f) + 1, gridHeight - 1);
var tileI0 = Hlsl.Max((int)Hlsl.Floor((tileLeft - kernelRadius) / cellSize - 1f) - 1, 0);
var tileI1 = Hlsl.Min((int)Hlsl.Ceil((tileLeft + tileSpan + kernelRadius) / cellSize - 0.5f) + 1, gridWidth - 1);
var tileWidth = Hlsl.Max(tileI1 - tileI0 + 1, 0);
var tileCells = tileWidth * Hlsl.Max(tileJ1 - tileJ0 + 1, 0);
for (var slot = GroupIds.Index; slot < tileCells; slot += CrystallineGrowthSettings.RenderTileSize * CrystallineGrowthSettings.RenderTileSize)
{
if (renderMass[(tileJ0 + slot / tileWidth) * gridWidth + tileI0 + slot % tileWidth] > 0f)
Hlsl.InterlockedOr(ref tileShared[0], 1);
}
Hlsl.GroupMemoryBarrierWithGroupSync();
var lit = tileShared[0];
var shaded = false;
var field = 0f;
var slopeX = 0f;
var slopeY = 0f;
var color = new Float4(0f, 0f, 0f, 0f);
if (inside && lit != 0)
{
var j0 = Hlsl.Max((int)Hlsl.Floor((py - kernelRadius) / rowStep - 0.5f), 0);
var j1 = Hlsl.Min((int)Hlsl.Ceil((py + kernelRadius) / rowStep - 0.5f), gridHeight - 1);
var num = 0f;
var den = 0f;
var numX = 0f;
var denX = 0f;
var numY = 0f;
var denY = 0f;
for (var j = j0; j <= j1; j++)
{
var shift = 0.5f * (j & 1) + 0.5f;
var i0 = Hlsl.Max((int)Hlsl.Floor((px - kernelRadius) / cellSize - shift), 0);
var i1 = Hlsl.Min((int)Hlsl.Ceil((px + kernelRadius) / cellSize - shift), gridWidth - 1);
var cy = (j + 0.5f) * rowStep;
var dy = py - cy;
for (var i = i0; i <= i1; i++)
{
var cx = (i + shift) * cellSize;
var dx = px - cx;
var distanceSquared = dx * dx + dy * dy;
var u = distanceSquared * inverseRadiusSquared;
if (u >= 1f)
continue;
var oneMinusU = 1f - u;
var weight = oneMinusU * oneMinusU;
var weightGradientScale = -4f * oneMinusU * inverseRadiusSquared;
var mass = renderMass[j * gridWidth + i];
num += weight * mass;
den += weight;
numX += weightGradientScale * dx * mass;
denX += weightGradientScale * dx;
numY += weightGradientScale * dy * mass;
denY += weightGradientScale * dy;
}
}
if (num > 0f)
{
var safeDen = Hlsl.Max(den, 1e-4f);
field = num / safeDen;
var coverage = Hlsl.SmoothStep(CrystallineGrowthSettings.CoverageLow, CrystallineGrowthSettings.CoverageHigh, field);
if (coverage > 0f)
{
var inverseDenSquared = 1f / (safeDen * safeDen);
var amplitude = CrystallineGrowthSettings.NormalAmplitudeFactor * cellSize;
slopeX = (numX * safeDen - num * denX) * inverseDenSquared * amplitude;
slopeY = (numY * safeDen - num * denY) * inverseDenSquared * amplitude;
shaded = true;
color = Shade(px, py, field, coverage, slopeX, slopeY);
}
}
}
if (inside)
output[ThreadIds.XY] = color;
if (mode == CrystallineGrowthSettings.RenderModeCount || mode == CrystallineGrowthSettings.RenderModeStore)
{
if (shaded)
Hlsl.InterlockedOr(ref tileShared[1 + bit / 32], (int)(1u << (bit % 32)));
Hlsl.GroupMemoryBarrierWithGroupSync();
if (GroupIds.Index == 0)
{
var lowMask = (uint)tileShared[1];
var highMask = (uint)tileShared[2];
var count = (int)(Hlsl.CountBits(lowMask) + Hlsl.CountBits(highMask));
var stored = -1;
if (count > 0)
{
Hlsl.InterlockedAdd(ref scratch[CrystallineGrowthSettings.ScratchShadedCount], count, out var first);
if (mode == CrystallineGrowthSettings.RenderModeStore && first + count <= geometryCapacity)
stored = first;
}
if (mode == CrystallineGrowthSettings.RenderModeStore)
{
tileBase[tile] = stored;
tileMask[tile * 2] = (int)lowMask;
tileMask[tile * 2 + 1] = (int)highMask;
}
tileShared[3] = stored;
}
Hlsl.GroupMemoryBarrierWithGroupSync();
if (mode == CrystallineGrowthSettings.RenderModeStore && shaded && tileShared[3] >= 0)
{
var slotIndex = (tileShared[3] + CrystallineGrowthShaderMath.TileRank((uint)tileShared[1], (uint)tileShared[2], (uint)bit)) * 3;
geometry[slotIndex] = field;
geometry[slotIndex + 1] = slopeX;
geometry[slotIndex + 2] = slopeY;
}
}
}
private Float4 Shade(float px, float py, float field, float coverage, float slopeX, float slopeY)
{
var normal = Hlsl.Normalize(new Float3(-slopeX, -slopeY, 1f));
var offsetScale = refractionPixels / Hlsl.Max(normal.Z, 0.5f);
var refracted = SampleSource(
px - normal.X * offsetScale - sourceOffsetX,
py - normal.Y * offsetScale - sourceOffsetY);
var frostAmount = frost * Hlsl.Saturate(field * 1.25f);
var baseAlpha = frostAmount + refracted.W * (1f - frostAmount);
var baseR = colorR * frostAmount + refracted.X * (1f - frostAmount);
var baseG = colorG * frostAmount + refracted.Y * (1f - frostAmount);
var baseB = colorB * frostAmount + refracted.Z * (1f - frostAmount);
var highlight = specular * Hlsl.Pow(Hlsl.Saturate(normal.X * -0.2490f + normal.Y * -0.3598f + normal.Z * 0.8992f), CrystallineGrowthSettings.SpecularPower);
var alpha = Hlsl.Saturate(coverage * baseAlpha);
var r = Hlsl.Min(coverage * baseR + highlight * alpha, alpha);
var g = Hlsl.Min(coverage * baseG + highlight * alpha, alpha);
var b = Hlsl.Min(coverage * baseB + highlight * alpha, alpha);
return new Float4(r, g, b, alpha);
}
private Float4 SampleSource(float x, float y)
{
var fx = x - 0.5f;
var fy = y - 0.5f;
var ix0 = (int)Hlsl.Floor(fx);
var iy0 = (int)Hlsl.Floor(fy);
var wx = fx - ix0;
var wy = fy - iy0;
var c00 = SampleTexel(ix0, iy0);
var c10 = SampleTexel(ix0 + 1, iy0);
var c01 = SampleTexel(ix0, iy0 + 1);
var c11 = SampleTexel(ix0 + 1, iy0 + 1);
return Hlsl.Lerp(Hlsl.Lerp(c00, c10, wx), Hlsl.Lerp(c01, c11, wx), wy);
}
private Float4 SampleTexel(int x, int y)
{
if (x < 0 || x >= sourceWidth || y < 0 || y >= sourceHeight)
return new Float4(0f, 0f, 0f, 0f);
return source[new Int2(x, y)];
}
}
[ThreadGroupSize(CrystallineGrowthSettings.RenderTileSize, CrystallineGrowthSettings.RenderTileSize, 1)]
[GeneratedComputeShaderDescriptor]
internal readonly partial struct CachedRenderShader(
ReadWriteBuffer<int> tileBase,
ReadWriteBuffer<int> tileMask,
ReadWriteBuffer<float> geometry,
ReadWriteTexture2D<Bgra32, Float4> source,
ReadWriteTexture2D<Bgra32, Float4> output,
int rectOffsetX,
int rectOffsetY,
int rectWidth,
int rectHeight,
int sourceOffsetX,
int sourceOffsetY,
int sourceWidth,
int sourceHeight,
float frost,
float refractionPixels,
float specular,
float colorR,
float colorG,
float colorB) : IComputeShader
{
private readonly ReadWriteBuffer<int> tileBase = tileBase;
private readonly ReadWriteBuffer<int> tileMask = tileMask;
private readonly ReadWriteBuffer<float> geometry = geometry;
private readonly ReadWriteTexture2D<Bgra32, Float4> source = source;
private readonly ReadWriteTexture2D<Bgra32, Float4> output = output;
private readonly int rectOffsetX = rectOffsetX;
private readonly int rectOffsetY = rectOffsetY;
private readonly int rectWidth = rectWidth;
private readonly int rectHeight = rectHeight;
private readonly int sourceOffsetX = sourceOffsetX;
private readonly int sourceOffsetY = sourceOffsetY;
private readonly int sourceWidth = sourceWidth;
private readonly int sourceHeight = sourceHeight;
private readonly float frost = frost;
private readonly float refractionPixels = refractionPixels;
private readonly float specular = specular;
private readonly float colorR = colorR;
private readonly float colorG = colorG;
private readonly float colorB = colorB;
public void Execute()
{
if (ThreadIds.X >= rectWidth || ThreadIds.Y >= rectHeight)
return;
var tile = ThreadIds.Y / CrystallineGrowthSettings.RenderTileSize * ((rectWidth + CrystallineGrowthSettings.RenderTileSize - 1) / CrystallineGrowthSettings.RenderTileSize)
+ ThreadIds.X / CrystallineGrowthSettings.RenderTileSize;
var color = new Float4(0f, 0f, 0f, 0f);
var cachedBase = tileBase[tile];
if (cachedBase >= 0)
{
var rank = CrystallineGrowthShaderMath.TileRank((uint)tileMask[tile * 2], (uint)tileMask[tile * 2 + 1], (uint)GroupIds.Index);
if (rank >= 0)
{
var slotIndex = (cachedBase + rank) * 3;
var field = geometry[slotIndex];
var coverage = Hlsl.SmoothStep(CrystallineGrowthSettings.CoverageLow, CrystallineGrowthSettings.CoverageHigh, field);
color = Shade(ThreadIds.X + rectOffsetX + 0.5f, ThreadIds.Y + rectOffsetY + 0.5f, field, coverage, geometry[slotIndex + 1], geometry[slotIndex + 2]);
}
}
output[ThreadIds.XY] = color;
}
private Float4 Shade(float px, float py, float field, float coverage, float slopeX, float slopeY)
{
var normal = Hlsl.Normalize(new Float3(-slopeX, -slopeY, 1f));
var offsetScale = refractionPixels / Hlsl.Max(normal.Z, 0.5f);
var refracted = SampleSource(
px - normal.X * offsetScale - sourceOffsetX,
py - normal.Y * offsetScale - sourceOffsetY);
var frostAmount = frost * Hlsl.Saturate(field * 1.25f);
var baseAlpha = frostAmount + refracted.W * (1f - frostAmount);
var baseR = colorR * frostAmount + refracted.X * (1f - frostAmount);
var baseG = colorG * frostAmount + refracted.Y * (1f - frostAmount);
var baseB = colorB * frostAmount + refracted.Z * (1f - frostAmount);
var highlight = specular * Hlsl.Pow(Hlsl.Saturate(normal.X * -0.2490f + normal.Y * -0.3598f + normal.Z * 0.8992f), CrystallineGrowthSettings.SpecularPower);
var alpha = Hlsl.Saturate(coverage * baseAlpha);
var r = Hlsl.Min(coverage * baseR + highlight * alpha, alpha);
var g = Hlsl.Min(coverage * baseG + highlight * alpha, alpha);
var b = Hlsl.Min(coverage * baseB + highlight * alpha, alpha);
return new Float4(r, g, b, alpha);
}
private Float4 SampleSource(float x, float y)
{
var fx = x - 0.5f;
var fy = y - 0.5f;
var ix0 = (int)Hlsl.Floor(fx);
var iy0 = (int)Hlsl.Floor(fy);
var wx = fx - ix0;
var wy = fy - iy0;
var c00 = SampleTexel(ix0, iy0);
var c10 = SampleTexel(ix0 + 1, iy0);
var c01 = SampleTexel(ix0, iy0 + 1);
var c11 = SampleTexel(ix0 + 1, iy0 + 1);
return Hlsl.Lerp(Hlsl.Lerp(c00, c10, wx), Hlsl.Lerp(c01, c11, wx), wy);
}
private Float4 SampleTexel(int x, int y)
{
if (x < 0 || x >= sourceWidth || y < 0 || y >= sourceHeight)
return new Float4(0f, 0f, 0f, 0f);
return source[new Int2(x, y)];
}
}
internal static class CrystallineGrowthShaderMath
{
public static Float2 CellCenter(int i, int j, float cellSize)
@@ -683,4 +1158,27 @@ internal static class CrystallineGrowthShaderMath
value ^= value >> 16;
return value * 2.3283064e-10f;
}
public static int TileRank(uint lowMask, uint highMask, uint bit)
{
if (bit < 32u)
return (lowMask & (1u << (int)bit)) != 0u ? (int)Hlsl.CountBits(lowMask & ((1u << (int)bit) - 1u)) : -1;
var highBit = bit - 32u;
return (highMask & (1u << (int)highBit)) != 0u ? (int)(Hlsl.CountBits(lowMask) + Hlsl.CountBits(highMask & ((1u << (int)highBit) - 1u))) : -1;
}
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;
}
}
+219 -158
ファイルの表示
@@ -1,31 +1,36 @@
using System.ComponentModel;
using System.Runtime.InteropServices;
using ComputeSharp;
using ComputeWeave;
namespace CrystallineGrowth;
internal sealed class CrystallineGrowthPipeline : IDisposable
{
private readonly GraphicsDevice _device;
private readonly CrystallineGrowthPipelineHost _host;
private readonly ReadWriteBuffer<int> _scratch;
private readonly ReadBackBuffer<int> _scratchReadBack;
private readonly ReadWriteBuffer<int> _unusedTileBase;
private readonly ReadWriteBuffer<int> _unusedTileMask;
private readonly ReadWriteBuffer<float> _unusedGeometry;
private readonly int[] _boundsMinX;
private readonly int[] _boundsMinY;
private readonly int[] _boundsMaxX;
private readonly int[] _boundsMaxY;
private ReadWriteBuffer<int>? _mask;
private ReadWriteBuffer<int>? _birth;
private ReadWriteBuffer<int>? _reachMask;
private ReadWriteBuffer<int>? _jumpFloodA;
private ReadWriteBuffer<int>? _jumpFloodB;
private ReadWriteBuffer<float>? _boundaryMass;
private ReadWriteBuffer<float>? _crystalMass;
private ReadWriteBuffer<float>? _diffusiveA;
private ReadWriteBuffer<float>? _diffusiveB;
private ReadBackBuffer<int>? _birthReadBack;
private int[]? _cachedBirth;
private int _cachedMaxBirth;
private int _cachedAttached;
private StructureKey? _structureKey;
private int _structureGeneration;
private GeometryKey? _geometryKey;
private GeometryStage _geometryStage;
private int _shadedCount;
private int _geometryCapacity;
private ReadWriteBuffer<int>? _tileBase;
private ReadWriteBuffer<int>? _tileMask;
private ReadWriteBuffer<float>? _geometry;
private int _gridWidth;
private int _gridHeight;
private ReadWriteTexture2D<Bgra32, Float4>? _packedSource;
@@ -33,22 +38,28 @@ internal sealed class CrystallineGrowthPipeline : IDisposable
private int _packedWidth;
private int _packedHeight;
private CrystallineGrowthPipeline(GraphicsDevice device)
private CrystallineGrowthPipeline(GraphicsDevice device, CrystallineGrowthPipelineHost host)
{
_device = device;
_host = host;
_scratch = device.AllocateReadWriteBuffer<int>(CrystallineGrowthSettings.ScratchLength);
_scratchReadBack = device.AllocateReadBackBuffer<int>(CrystallineGrowthSettings.ScratchLength);
_unusedTileBase = device.AllocateReadWriteBuffer<int>(1);
_unusedTileMask = device.AllocateReadWriteBuffer<int>(1);
_unusedGeometry = device.AllocateReadWriteBuffer<float>(1);
_boundsMinX = new int[CrystallineGrowthSettings.MaximumStepCount + 1];
_boundsMinY = new int[CrystallineGrowthSettings.MaximumStepCount + 1];
_boundsMaxX = new int[CrystallineGrowthSettings.MaximumStepCount + 1];
_boundsMaxY = new int[CrystallineGrowthSettings.MaximumStepCount + 1];
}
internal ContentHash? SourceHash { get; private set; }
public static CrystallineGrowthPipeline? TryCreate()
{
try
{
return new CrystallineGrowthPipeline(GraphicsDevice.GetDefault());
return TryCreate(GraphicsDevice.GetDefault());
}
catch
{
@@ -58,14 +69,23 @@ internal sealed class CrystallineGrowthPipeline : IDisposable
public static CrystallineGrowthPipeline? TryCreate(GraphicsDevice device)
{
CrystallineGrowthPipelineHost? host = null;
try
{
return new CrystallineGrowthPipeline(device);
host = CrystallineGrowthPipelineHost.Create(device, CrystallineGrowthSettings.MaximumPendingSubmissions);
var pipeline = new CrystallineGrowthPipeline(device, host);
host = null;
return pipeline;
}
catch
catch (Win32Exception)
{
return null;
}
finally
{
host?.Dispose();
host?.WaitForDisposal();
}
}
internal void WaitForCompletion()
@@ -81,8 +101,7 @@ internal sealed class CrystallineGrowthPipeline : IDisposable
var sourceTexture = _packedSource!;
var outputTexture = _packedOutput!;
sourceTexture.CopyFrom(MemoryMarshal.Cast<int, Bgra32>(source[..pixelCount]));
using (ComputeContext context = _device.CreateComputeContext())
RecordFullPipeline(in context, sourceTexture, outputTexture, width, height, in parameters);
SubmitFullPipeline(sourceTexture, outputTexture, width, height, in parameters).Wait();
outputTexture.CopyTo(MemoryMarshal.Cast<int, Bgra32>(destination[..pixelCount]));
}
@@ -94,9 +113,7 @@ internal sealed class CrystallineGrowthPipeline : IDisposable
in Parameters parameters)
{
EnsureGridFor(width, height, parameters.Quality);
using ComputeContext context = _device.CreateComputeContext();
RecordFullPipeline(in context, source, destination, width, height, in parameters);
context.Submit();
_ = SubmitFullPipeline(source, destination, width, height, in parameters);
}
internal void ProcessSharedAndWait(
@@ -107,8 +124,7 @@ internal sealed class CrystallineGrowthPipeline : IDisposable
in Parameters parameters)
{
EnsureGridFor(width, height, parameters.Quality);
using ComputeContext context = _device.CreateComputeContext();
RecordFullPipeline(in context, source, destination, width, height, in parameters);
SubmitFullPipeline(source, destination, width, height, in parameters).Wait();
}
internal bool Simulate(
@@ -119,24 +135,61 @@ internal sealed class CrystallineGrowthPipeline : IDisposable
int sourceOffsetY,
int sourceWidth,
int sourceHeight,
in Parameters parameters)
in Parameters parameters,
bool hashSource)
{
var derived = BeginSimulate(canvasWidth, canvasHeight, in parameters);
var hashed = hashSource
? _host.RecordSilhouetteAndHashes(
source, _scratch, sourceOffsetX, sourceOffsetY, sourceWidth, sourceHeight, _gridWidth, _gridHeight, in derived)
: _host.RecordSilhouetteAndMaskHash(
source, _scratch, sourceOffsetX, sourceOffsetY, sourceWidth, sourceHeight, _gridWidth, _gridHeight, in derived);
hashed.Wait();
return CompleteSimulate(canvasWidth, canvasHeight, in parameters, in derived, hashSource);
}
internal bool Simulate(
ComputeResourceBinding<ReadWriteTexture2D<Bgra32, Float4>> source,
int canvasWidth,
int canvasHeight,
int sourceOffsetX,
int sourceOffsetY,
int sourceWidth,
int sourceHeight,
in Parameters parameters,
bool hashSource)
{
var derived = BeginSimulate(canvasWidth, canvasHeight, in parameters);
var hashed = hashSource
? _host.RecordSharedSilhouetteAndHashes(
source, _scratch, sourceOffsetX, sourceOffsetY, sourceWidth, sourceHeight, _gridWidth, _gridHeight, in derived)
: _host.RecordSharedSilhouetteAndMaskHash(
source, _scratch, sourceOffsetX, sourceOffsetY, sourceWidth, sourceHeight, _gridWidth, _gridHeight, in derived);
hashed.Wait();
return CompleteSimulate(canvasWidth, canvasHeight, in parameters, in derived, hashSource);
}
private DerivedValues BeginSimulate(int canvasWidth, int canvasHeight, in Parameters parameters)
{
EnsureGridFor(canvasWidth, canvasHeight, parameters.Quality);
var derived = Derive(canvasWidth, canvasHeight, in parameters);
using (ComputeContext context = _device.CreateComputeContext())
{
RecordSilhouetteStage(in context, source, sourceOffsetX, sourceOffsetY, sourceWidth, sourceHeight, in derived);
RecordMaskHashStage(in context);
}
return Derive(canvasWidth, canvasHeight, in parameters);
}
private bool CompleteSimulate(int canvasWidth, int canvasHeight, in Parameters parameters, in DerivedValues derived, bool hashSource)
{
_scratchReadBack.CopyFrom(_scratch);
var hashed = _scratchReadBack.Span;
ResolveGeometry(hashed[CrystallineGrowthSettings.ScratchShadedCount]);
SourceHash = hashSource
? new ContentHash(hashed[CrystallineGrowthSettings.ScratchSourceHashSum], hashed[CrystallineGrowthSettings.ScratchSourceHashMix])
: null;
var key = new StructureKey(
hashed[6],
hashed[7],
hashed[CrystallineGrowthSettings.ScratchMaskHashSum],
hashed[CrystallineGrowthSettings.ScratchMaskHashMix],
canvasWidth,
canvasHeight,
parameters.Quality,
parameters.Seed,
derived.Sigma > 0f ? parameters.Seed : 0,
parameters.ReachPixels,
parameters.Branching,
parameters.Facet,
@@ -144,17 +197,24 @@ internal sealed class CrystallineGrowthPipeline : IDisposable
if (_structureKey == key)
return false;
using (ComputeContext context = _device.CreateComputeContext())
RecordGrowthStage(in context, in derived, in parameters);
_ = _host.RecordGrowthSetup(_scratch, _birth!, _gridWidth, _gridHeight, in derived);
var grown = default(ComputeSubmission);
for (var firstStep = 0; firstStep < derived.Steps; firstStep += CrystallineGrowthSettings.GrowthStepsPerSubmission)
{
var stepCount = Math.Min(CrystallineGrowthSettings.GrowthStepsPerSubmission, derived.Steps - firstStep);
grown = _host.RecordGrowthSteps(_scratch, _birth!, _gridWidth, _gridHeight, in derived, in parameters, firstStep, stepCount);
}
grown.Wait();
_scratchReadBack.CopyFrom(_scratch);
var birthReadBack = _birthReadBack!;
birthReadBack.CopyFrom(_birth!);
var scratch = _scratchReadBack.Span;
_cachedAttached = scratch[0];
_cachedMaxBirth = scratch[1];
_cachedAttached = scratch[CrystallineGrowthSettings.ScratchAttachedCount];
_cachedMaxBirth = scratch[CrystallineGrowthSettings.ScratchMaxBirth];
birthReadBack.Span.CopyTo(_cachedBirth!);
BuildBoundsPrefix();
_structureKey = key;
_structureGeneration++;
return true;
}
@@ -201,12 +261,32 @@ internal sealed class CrystallineGrowthPipeline : IDisposable
in Parameters parameters)
{
var derived = Derive(canvasWidth, canvasHeight, in parameters);
using ComputeContext context = _device.CreateComputeContext();
RecordRenderStage(in context, source, output, rect, sourceOffsetX, sourceOffsetY, sourceWidth, sourceHeight, in derived, in parameters);
var mode = PrepareGeometry(in rect, Math.Clamp(parameters.Freeze, 0f, 1f));
_host.RecordRender(
source, output, _scratch, _birth!, _tileBase ?? _unusedTileBase, _tileMask ?? _unusedTileMask, _geometry ?? _unusedGeometry,
in rect, sourceOffsetX, sourceOffsetY, sourceWidth, sourceHeight, _gridWidth, _gridHeight, in derived, in parameters, mode, _geometryCapacity).Wait();
}
private void RecordFullPipeline(
in ComputeContext context,
internal void RenderVisible(
ComputeResourceBinding<ReadWriteTexture2D<Bgra32, Float4>> source,
ComputeResourceBinding<ReadWriteTexture2D<Bgra32, Float4>> output,
int canvasWidth,
int canvasHeight,
int sourceOffsetX,
int sourceOffsetY,
int sourceWidth,
int sourceHeight,
PixelRect rect,
in Parameters parameters)
{
var derived = Derive(canvasWidth, canvasHeight, in parameters);
var mode = PrepareGeometry(in rect, Math.Clamp(parameters.Freeze, 0f, 1f));
_host.RecordSharedRender(
source, output, _scratch, _birth!, _tileBase ?? _unusedTileBase, _tileMask ?? _unusedTileMask, _geometry ?? _unusedGeometry,
in rect, sourceOffsetX, sourceOffsetY, sourceWidth, sourceHeight, _gridWidth, _gridHeight, in derived, in parameters, mode, _geometryCapacity).Wait();
}
private ComputeSubmission SubmitFullPipeline(
ReadWriteTexture2D<Bgra32, Float4> source,
ReadWriteTexture2D<Bgra32, Float4> output,
int width,
@@ -214,113 +294,82 @@ internal sealed class CrystallineGrowthPipeline : IDisposable
in Parameters parameters)
{
_structureKey = null;
_structureGeneration++;
ReleaseGeometry();
var derived = Derive(width, height, in parameters);
RecordSilhouetteStage(in context, source, 0, 0, width, height, in derived);
RecordGrowthStage(in context, in derived, in parameters);
RecordRenderStage(in context, source, output, new PixelRect(0, 0, width, height), 0, 0, width, height, in derived, in parameters);
return _host.RecordFullPipeline(
source, output, _scratch, _birth!, _unusedTileBase, _unusedTileMask, _unusedGeometry,
width, height, _gridWidth, _gridHeight, in derived, in parameters, CrystallineGrowthSettings.RenderModeDraw, 0);
}
private void RecordSilhouetteStage(
in ComputeContext context,
ReadWriteTexture2D<Bgra32, Float4> source,
int sourceOffsetX,
int sourceOffsetY,
int sourceWidth,
int sourceHeight,
in DerivedValues derived)
private int PrepareGeometry(in PixelRect rect, float freeze)
{
context.For(_gridWidth, _gridHeight, new SilhouetteShader(
source, _mask!, sourceOffsetX, sourceOffsetY, sourceWidth, sourceHeight, _gridWidth, _gridHeight, derived.CellSize, 0.05f));
context.Barrier(_mask!);
}
private void RecordMaskHashStage(in ComputeContext context)
{
context.For(1, new MaskHashResetShader(_scratch));
context.Barrier(_scratch);
context.For(_gridWidth, _gridHeight, new MaskHashShader(_mask!, _scratch, _gridWidth, _gridHeight));
context.Barrier(_scratch);
}
private void RecordGrowthStage(
in ComputeContext context,
in DerivedValues derived,
in Parameters parameters)
{
var gridWidth = _gridWidth;
var gridHeight = _gridHeight;
var mask = _mask!;
var birth = _birth!;
var boundaryMass = _boundaryMass!;
var crystalMass = _crystalMass!;
var reachMask = _reachMask!;
context.For(1, new InitScratchShader(_scratch));
context.Barrier(_scratch);
context.For(gridWidth, gridHeight, new SeedInitShader(
mask, birth, boundaryMass, crystalMass, _diffusiveA!, _scratch, gridWidth, gridHeight, derived.VaporDensity));
context.Barrier(birth);
context.Barrier(boundaryMass);
context.Barrier(crystalMass);
context.Barrier(_diffusiveA!);
context.Barrier(_scratch);
context.For(gridWidth, gridHeight, new JumpFloodSeedShader(birth, _jumpFloodA!, gridWidth, gridHeight));
context.Barrier(_jumpFloodA!);
var reading = _jumpFloodA!;
var writing = _jumpFloodB!;
var stepSize = 1;
var maxSide = Math.Max(gridWidth, gridHeight);
while (stepSize < maxSide)
stepSize <<= 1;
stepSize >>= 1;
while (stepSize >= 1)
var key = new GeometryKey(_structureGeneration, freeze, rect);
if (_geometryKey != key)
{
context.For(gridWidth, gridHeight, new JumpFloodPassShader(reading, writing, gridWidth, gridHeight, stepSize, derived.CellSize));
context.Barrier(writing);
(reading, writing) = (writing, reading);
stepSize >>= 1;
ReleaseGeometry();
_geometryKey = key;
_geometryStage = GeometryStage.Drawn;
return CrystallineGrowthSettings.RenderModeDraw;
}
context.For(gridWidth, gridHeight, new ReachMaskShader(reading, reachMask, gridWidth, gridHeight, derived.CellSize, derived.ReachPixels));
context.Barrier(reachMask);
for (var step = 0; step < derived.Steps; step++)
switch (_geometryStage)
{
context.For(gridWidth, gridHeight, new DiffusionShader(_diffusiveA!, _diffusiveB!, gridWidth, gridHeight));
context.Barrier(_diffusiveB!);
context.For(gridWidth, gridHeight, new GrowthUpdateShader(
_diffusiveB!, _diffusiveA!, boundaryMass, crystalMass, birth, reachMask, _scratch,
gridWidth, gridHeight, step, parameters.Seed,
CrystallineGrowthSettings.Kappa, derived.Beta, CrystallineGrowthSettings.Alpha, CrystallineGrowthSettings.Theta,
CrystallineGrowthSettings.Mu, CrystallineGrowthSettings.Gamma, derived.Sigma));
context.Barrier(_diffusiveA!);
context.Barrier(boundaryMass);
context.Barrier(crystalMass);
case GeometryStage.Drawn:
_geometryStage = GeometryStage.Counting;
return CrystallineGrowthSettings.RenderModeCount;
case GeometryStage.Counted:
AllocateGeometry(in rect, _shadedCount);
_geometryStage = GeometryStage.Storing;
return CrystallineGrowthSettings.RenderModeStore;
case GeometryStage.Stored:
return CrystallineGrowthSettings.RenderModeCached;
default:
return CrystallineGrowthSettings.RenderModeDraw;
}
context.Barrier(birth);
context.Barrier(_scratch);
}
private void RecordRenderStage(
in ComputeContext context,
ReadWriteTexture2D<Bgra32, Float4> source,
ReadWriteTexture2D<Bgra32, Float4> output,
PixelRect rect,
int sourceOffsetX,
int sourceOffsetY,
int sourceWidth,
int sourceHeight,
in DerivedValues derived,
in Parameters parameters)
private void ResolveGeometry(int shadedCount)
{
context.For(rect.Width, rect.Height, new RenderShader(
_birth!, _crystalMass!, _scratch, source, output,
rect.X, rect.Y, rect.Width, rect.Height, _gridWidth, _gridHeight,
sourceOffsetX, sourceOffsetY, sourceWidth, sourceHeight,
derived.CellSize, Math.Clamp(parameters.Freeze, 0f, 1f),
Math.Clamp(parameters.Frost, 0f, 1f), derived.RefractionPixels,
Math.Clamp(parameters.Specular, 0f, 1f),
parameters.ColorR, parameters.ColorG, parameters.ColorB));
if (_geometryStage == GeometryStage.Counting)
{
_shadedCount = shadedCount;
_geometryStage = GeometryStage.Counted;
}
else if (_geometryStage == GeometryStage.Storing)
{
if (shadedCount <= _geometryCapacity)
{
_geometryStage = GeometryStage.Stored;
}
else
{
_shadedCount = shadedCount;
_geometryStage = GeometryStage.Counted;
}
}
}
private void AllocateGeometry(in PixelRect rect, int shadedCount)
{
ReleaseGeometry();
var tiles = CrystallineGrowthSettings.RoundUpToRenderTile(rect.Width) / CrystallineGrowthSettings.RenderTileSize
* (CrystallineGrowthSettings.RoundUpToRenderTile(rect.Height) / CrystallineGrowthSettings.RenderTileSize);
_tileBase = _device.AllocateReadWriteBuffer<int>(tiles);
_tileMask = _device.AllocateReadWriteBuffer<int>(tiles * 2);
_geometry = _device.AllocateReadWriteBuffer<float>(Math.Max(shadedCount, 1) * 3);
_geometryCapacity = shadedCount;
}
private void ReleaseGeometry()
{
_tileBase?.Dispose();
_tileMask?.Dispose();
_geometry?.Dispose();
_tileBase = null;
_tileMask = null;
_geometry = null;
_geometryCapacity = 0;
}
private void BuildBoundsPrefix()
@@ -396,15 +445,20 @@ internal sealed class CrystallineGrowthPipeline : IDisposable
DisposeGridBuffers();
var gridLength = gridWidth * gridHeight;
_mask = _device.AllocateReadWriteBuffer<int>(gridLength);
if (!_host.TryEnsureGrid(
new CrystallineGrowthGridResources.Plan(
boundaryMassLength: gridLength,
crystalMassLength: gridLength,
diffusiveALength: gridLength,
diffusiveBLength: gridLength,
jumpFloodALength: gridLength,
jumpFloodBLength: gridLength,
maskLength: gridLength,
reachMaskLength: gridLength,
renderMassLength: gridLength),
out _))
throw new InvalidOperationException();
_birth = _device.AllocateReadWriteBuffer<int>(gridLength);
_reachMask = _device.AllocateReadWriteBuffer<int>(gridLength);
_jumpFloodA = _device.AllocateReadWriteBuffer<int>(gridLength);
_jumpFloodB = _device.AllocateReadWriteBuffer<int>(gridLength);
_boundaryMass = _device.AllocateReadWriteBuffer<float>(gridLength);
_crystalMass = _device.AllocateReadWriteBuffer<float>(gridLength);
_diffusiveA = _device.AllocateReadWriteBuffer<float>(gridLength);
_diffusiveB = _device.AllocateReadWriteBuffer<float>(gridLength);
_birthReadBack = _device.AllocateReadBackBuffer<int>(gridLength);
_cachedBirth = new int[gridLength];
_cachedMaxBirth = -1;
@@ -428,36 +482,24 @@ internal sealed class CrystallineGrowthPipeline : IDisposable
private void DisposeGridBuffers()
{
_mask?.Dispose();
_birth?.Dispose();
_reachMask?.Dispose();
_jumpFloodA?.Dispose();
_jumpFloodB?.Dispose();
_boundaryMass?.Dispose();
_crystalMass?.Dispose();
_diffusiveA?.Dispose();
_diffusiveB?.Dispose();
_birthReadBack?.Dispose();
_mask = null;
_birth = null;
_reachMask = null;
_jumpFloodA = null;
_jumpFloodB = null;
_boundaryMass = null;
_crystalMass = null;
_diffusiveA = null;
_diffusiveB = null;
_birthReadBack = null;
_cachedBirth = null;
_cachedMaxBirth = -1;
_cachedAttached = 0;
_structureKey = null;
_geometryKey = null;
ReleaseGeometry();
_gridWidth = 0;
_gridHeight = 0;
}
public void Dispose()
{
_host.Dispose();
_host.WaitForDisposal();
DisposeGridBuffers();
_packedSource?.Dispose();
_packedOutput?.Dispose();
@@ -467,10 +509,15 @@ internal sealed class CrystallineGrowthPipeline : IDisposable
_packedHeight = 0;
_scratchReadBack.Dispose();
_scratch.Dispose();
_unusedTileBase.Dispose();
_unusedTileMask.Dispose();
_unusedGeometry.Dispose();
}
internal readonly record struct PixelRect(int X, int Y, int Width, int Height);
internal readonly record struct ContentHash(int Sum, int Mix);
private readonly record struct StructureKey(
int MaskHashSum,
int MaskHashMix,
@@ -483,7 +530,21 @@ internal sealed class CrystallineGrowthPipeline : IDisposable
float Facet,
float Noise);
private readonly record struct DerivedValues(
private readonly record struct GeometryKey(
int StructureGeneration,
float Freeze,
PixelRect Rect);
private enum GeometryStage
{
Drawn,
Counting,
Counted,
Storing,
Stored,
}
internal readonly record struct DerivedValues(
float CellSize,
int Steps,
float VaporDensity,
+420
ファイルの表示
@@ -0,0 +1,420 @@
using ComputeWeave;
namespace CrystallineGrowth;
[ComputeResourceGroup]
internal sealed partial class CrystallineGrowthGridResources
{
[ComputePipelineResource(ComputeResourceAccess.ReadWrite)]
internal ReadWriteBuffer<int> Mask { get; }
[ComputePipelineResource(ComputeResourceAccess.ReadWrite)]
internal ReadWriteBuffer<int> ReachMask { get; }
[ComputePipelineResource(ComputeResourceAccess.ReadWrite)]
internal ReadWriteBuffer<int> JumpFloodA { get; }
[ComputePipelineResource(ComputeResourceAccess.ReadWrite)]
internal ReadWriteBuffer<int> JumpFloodB { get; }
[ComputePipelineResource(ComputeResourceAccess.ReadWrite)]
internal ReadWriteBuffer<float> BoundaryMass { get; }
[ComputePipelineResource(ComputeResourceAccess.ReadWrite)]
internal ReadWriteBuffer<float> CrystalMass { get; }
[ComputePipelineResource(ComputeResourceAccess.ReadWrite)]
internal ReadWriteBuffer<float> DiffusiveA { get; }
[ComputePipelineResource(ComputeResourceAccess.ReadWrite)]
internal ReadWriteBuffer<float> DiffusiveB { get; }
[ComputePipelineResource(ComputeResourceAccess.ReadWrite)]
internal ReadWriteBuffer<float> RenderMass { get; }
}
[ComputePipelineHost("_device", 1)]
internal sealed partial class CrystallineGrowthPipelineHost
{
private readonly GraphicsDevice _device;
[ComputePipelineResource(ComputeResourceAccess.ReadWrite, ComputeResourceRecovery.Recompute)]
private readonly ComputeResourceGroupSlot<CrystallineGrowthGridResources> _grid = new();
[ComputePipeline]
private void RecordFullPipeline(
in ComputeContext context,
[ComputeOwnedResource(nameof(_grid))] CrystallineGrowthGridResources grid,
[ComputeResource(ComputeResourceAccess.ReadWrite)] ReadWriteTexture2D<Bgra32, Float4> source,
[ComputeResource(ComputeResourceAccess.ReadWrite)] ReadWriteTexture2D<Bgra32, Float4> output,
[ComputeResource(ComputeResourceAccess.ReadWrite)] ReadWriteBuffer<int> scratch,
[ComputeResource(ComputeResourceAccess.ReadWrite)] ReadWriteBuffer<int> birth,
[ComputeResource(ComputeResourceAccess.ReadWrite)] ReadWriteBuffer<int> tileBase,
[ComputeResource(ComputeResourceAccess.ReadWrite)] ReadWriteBuffer<int> tileMask,
[ComputeResource(ComputeResourceAccess.ReadWrite)] ReadWriteBuffer<float> geometry,
int width,
int height,
int gridWidth,
int gridHeight,
in CrystallineGrowthPipeline.DerivedValues derived,
in CrystallineGrowthPipeline.Parameters parameters,
int mode,
int geometryCapacity)
{
_ = _device;
RecordSilhouetteStage(in context, grid, source, 0, 0, width, height, gridWidth, gridHeight, in derived);
RecordGrowthSetupStage(in context, grid, scratch, birth, gridWidth, gridHeight, in derived);
RecordGrowthStepsStage(in context, grid, scratch, birth, gridWidth, gridHeight, in derived, in parameters, 0, derived.Steps);
RecordRenderStage(in context, grid, source, output, scratch, birth, tileBase, tileMask, geometry, new CrystallineGrowthPipeline.PixelRect(0, 0, width, height), 0, 0, width, height, gridWidth, gridHeight, in derived, in parameters, mode, geometryCapacity);
}
[ComputePipeline]
private void RecordSilhouetteAndHashes(
in ComputeContext context,
[ComputeOwnedResource(nameof(_grid))] CrystallineGrowthGridResources grid,
[ComputeResource(ComputeResourceAccess.ReadWrite)] ReadWriteTexture2D<Bgra32, Float4> source,
[ComputeResource(ComputeResourceAccess.ReadWrite)] ReadWriteBuffer<int> scratch,
int sourceOffsetX,
int sourceOffsetY,
int sourceWidth,
int sourceHeight,
int gridWidth,
int gridHeight,
in CrystallineGrowthPipeline.DerivedValues derived)
{
_ = _device;
RecordSilhouetteStage(in context, grid, source, sourceOffsetX, sourceOffsetY, sourceWidth, sourceHeight, gridWidth, gridHeight, in derived);
RecordMaskHashStage(in context, grid, scratch, gridWidth, gridHeight);
RecordSourceHashStage(in context, source, scratch, sourceWidth, sourceHeight);
}
[ComputePipeline]
[ComputeInterop]
private void RecordSharedSilhouetteAndHashes(
in ComputeContext context,
[ComputeOwnedResource(nameof(_grid))] CrystallineGrowthGridResources grid,
[ComputeResource(ComputeResourceAccess.ReadWrite, Sharing = ComputeResourceSharing.External)] ReadWriteTexture2D<Bgra32, Float4> source,
[ComputeResource(ComputeResourceAccess.ReadWrite)] ReadWriteBuffer<int> scratch,
int sourceOffsetX,
int sourceOffsetY,
int sourceWidth,
int sourceHeight,
int gridWidth,
int gridHeight,
in CrystallineGrowthPipeline.DerivedValues derived)
{
_ = _device;
RecordSilhouetteStage(in context, grid, source, sourceOffsetX, sourceOffsetY, sourceWidth, sourceHeight, gridWidth, gridHeight, in derived);
RecordMaskHashStage(in context, grid, scratch, gridWidth, gridHeight);
RecordSourceHashStage(in context, source, scratch, sourceWidth, sourceHeight);
}
[ComputePipeline]
private void RecordSilhouetteAndMaskHash(
in ComputeContext context,
[ComputeOwnedResource(nameof(_grid))] CrystallineGrowthGridResources grid,
[ComputeResource(ComputeResourceAccess.ReadWrite)] ReadWriteTexture2D<Bgra32, Float4> source,
[ComputeResource(ComputeResourceAccess.ReadWrite)] ReadWriteBuffer<int> scratch,
int sourceOffsetX,
int sourceOffsetY,
int sourceWidth,
int sourceHeight,
int gridWidth,
int gridHeight,
in CrystallineGrowthPipeline.DerivedValues derived)
{
_ = _device;
RecordSilhouetteStage(in context, grid, source, sourceOffsetX, sourceOffsetY, sourceWidth, sourceHeight, gridWidth, gridHeight, in derived);
RecordMaskHashStage(in context, grid, scratch, gridWidth, gridHeight);
}
[ComputePipeline]
[ComputeInterop]
private void RecordSharedSilhouetteAndMaskHash(
in ComputeContext context,
[ComputeOwnedResource(nameof(_grid))] CrystallineGrowthGridResources grid,
[ComputeResource(ComputeResourceAccess.ReadWrite, Sharing = ComputeResourceSharing.External)] ReadWriteTexture2D<Bgra32, Float4> source,
[ComputeResource(ComputeResourceAccess.ReadWrite)] ReadWriteBuffer<int> scratch,
int sourceOffsetX,
int sourceOffsetY,
int sourceWidth,
int sourceHeight,
int gridWidth,
int gridHeight,
in CrystallineGrowthPipeline.DerivedValues derived)
{
_ = _device;
RecordSilhouetteStage(in context, grid, source, sourceOffsetX, sourceOffsetY, sourceWidth, sourceHeight, gridWidth, gridHeight, in derived);
RecordMaskHashStage(in context, grid, scratch, gridWidth, gridHeight);
}
[ComputePipeline]
[ComputeInterop]
private void RecordSharedRender(
in ComputeContext context,
[ComputeOwnedResource(nameof(_grid))] CrystallineGrowthGridResources grid,
[ComputeResource(ComputeResourceAccess.ReadWrite, Sharing = ComputeResourceSharing.External)] ReadWriteTexture2D<Bgra32, Float4> source,
[ComputeResource(ComputeResourceAccess.ReadWrite, Sharing = ComputeResourceSharing.External)] ReadWriteTexture2D<Bgra32, Float4> output,
[ComputeResource(ComputeResourceAccess.ReadWrite)] ReadWriteBuffer<int> scratch,
[ComputeResource(ComputeResourceAccess.ReadWrite)] ReadWriteBuffer<int> birth,
[ComputeResource(ComputeResourceAccess.ReadWrite)] ReadWriteBuffer<int> tileBase,
[ComputeResource(ComputeResourceAccess.ReadWrite)] ReadWriteBuffer<int> tileMask,
[ComputeResource(ComputeResourceAccess.ReadWrite)] ReadWriteBuffer<float> geometry,
in CrystallineGrowthPipeline.PixelRect rect,
int sourceOffsetX,
int sourceOffsetY,
int sourceWidth,
int sourceHeight,
int gridWidth,
int gridHeight,
in CrystallineGrowthPipeline.DerivedValues derived,
in CrystallineGrowthPipeline.Parameters parameters,
int mode,
int geometryCapacity)
{
_ = _device;
RecordRenderStage(in context, grid, source, output, scratch, birth, tileBase, tileMask, geometry, rect, sourceOffsetX, sourceOffsetY, sourceWidth, sourceHeight, gridWidth, gridHeight, in derived, in parameters, mode, geometryCapacity);
}
[ComputePipeline]
private void RecordGrowthSetup(
in ComputeContext context,
[ComputeOwnedResource(nameof(_grid))] CrystallineGrowthGridResources grid,
[ComputeResource(ComputeResourceAccess.ReadWrite)] ReadWriteBuffer<int> scratch,
[ComputeResource(ComputeResourceAccess.ReadWrite)] ReadWriteBuffer<int> birth,
int gridWidth,
int gridHeight,
in CrystallineGrowthPipeline.DerivedValues derived)
{
_ = _device;
RecordGrowthSetupStage(in context, grid, scratch, birth, gridWidth, gridHeight, in derived);
}
[ComputePipeline]
private void RecordGrowthSteps(
in ComputeContext context,
[ComputeOwnedResource(nameof(_grid))] CrystallineGrowthGridResources grid,
[ComputeResource(ComputeResourceAccess.ReadWrite)] ReadWriteBuffer<int> scratch,
[ComputeResource(ComputeResourceAccess.ReadWrite)] ReadWriteBuffer<int> birth,
int gridWidth,
int gridHeight,
in CrystallineGrowthPipeline.DerivedValues derived,
in CrystallineGrowthPipeline.Parameters parameters,
int firstStep,
int stepCount)
{
_ = _device;
RecordGrowthStepsStage(in context, grid, scratch, birth, gridWidth, gridHeight, in derived, in parameters, firstStep, stepCount);
}
[ComputePipeline]
private void RecordRender(
in ComputeContext context,
[ComputeOwnedResource(nameof(_grid))] CrystallineGrowthGridResources grid,
[ComputeResource(ComputeResourceAccess.ReadWrite)] ReadWriteTexture2D<Bgra32, Float4> source,
[ComputeResource(ComputeResourceAccess.ReadWrite)] ReadWriteTexture2D<Bgra32, Float4> output,
[ComputeResource(ComputeResourceAccess.ReadWrite)] ReadWriteBuffer<int> scratch,
[ComputeResource(ComputeResourceAccess.ReadWrite)] ReadWriteBuffer<int> birth,
[ComputeResource(ComputeResourceAccess.ReadWrite)] ReadWriteBuffer<int> tileBase,
[ComputeResource(ComputeResourceAccess.ReadWrite)] ReadWriteBuffer<int> tileMask,
[ComputeResource(ComputeResourceAccess.ReadWrite)] ReadWriteBuffer<float> geometry,
in CrystallineGrowthPipeline.PixelRect rect,
int sourceOffsetX,
int sourceOffsetY,
int sourceWidth,
int sourceHeight,
int gridWidth,
int gridHeight,
in CrystallineGrowthPipeline.DerivedValues derived,
in CrystallineGrowthPipeline.Parameters parameters,
int mode,
int geometryCapacity)
{
_ = _device;
RecordRenderStage(in context, grid, source, output, scratch, birth, tileBase, tileMask, geometry, rect, sourceOffsetX, sourceOffsetY, sourceWidth, sourceHeight, gridWidth, gridHeight, in derived, in parameters, mode, geometryCapacity);
}
private static void RecordSilhouetteStage(
in ComputeContext context,
CrystallineGrowthGridResources grid,
ReadWriteTexture2D<Bgra32, Float4> source,
int sourceOffsetX,
int sourceOffsetY,
int sourceWidth,
int sourceHeight,
int gridWidth,
int gridHeight,
in CrystallineGrowthPipeline.DerivedValues derived)
{
context.For(gridWidth, gridHeight, new SilhouetteShader(
source, grid.Mask, sourceOffsetX, sourceOffsetY, sourceWidth, sourceHeight, gridWidth, gridHeight, derived.CellSize, 0.05f));
context.Barrier(grid.Mask);
}
private static void RecordMaskHashStage(
in ComputeContext context,
CrystallineGrowthGridResources grid,
ReadWriteBuffer<int> scratch,
int gridWidth,
int gridHeight)
{
context.For(1, new MaskHashResetShader(scratch));
context.Barrier(scratch);
context.For(gridWidth, gridHeight, new MaskHashShader(grid.Mask, scratch, gridWidth, gridHeight));
context.Barrier(scratch);
}
private static void RecordSourceHashStage(
in ComputeContext context,
ReadWriteTexture2D<Bgra32, Float4> source,
ReadWriteBuffer<int> scratch,
int sourceWidth,
int sourceHeight)
{
context.For(1, new SourceHashResetShader(scratch));
context.Barrier(scratch);
context.For(sourceWidth, sourceHeight, new SourceHashShader(source, scratch, sourceWidth, sourceHeight));
context.Barrier(scratch);
}
private static void RecordGrowthSetupStage(
in ComputeContext context,
CrystallineGrowthGridResources grid,
ReadWriteBuffer<int> scratch,
ReadWriteBuffer<int> birth,
int gridWidth,
int gridHeight,
in CrystallineGrowthPipeline.DerivedValues derived)
{
context.For(1, new InitScratchShader(scratch));
context.Barrier(scratch);
context.For(gridWidth, gridHeight, new SeedInitShader(
grid.Mask, birth, grid.BoundaryMass, grid.CrystalMass, grid.DiffusiveA, scratch, gridWidth, gridHeight, derived.VaporDensity));
context.Barrier(birth);
context.Barrier(grid.BoundaryMass);
context.Barrier(grid.CrystalMass);
context.Barrier(grid.DiffusiveA);
context.Barrier(scratch);
context.For(gridWidth, gridHeight, new JumpFloodSeedShader(birth, grid.JumpFloodA, gridWidth, gridHeight));
context.Barrier(grid.JumpFloodA);
var reading = grid.JumpFloodA;
var writing = grid.JumpFloodB;
var stepSize = 1;
var maxSide = Math.Max(gridWidth, gridHeight);
while (stepSize < maxSide)
stepSize <<= 1;
stepSize >>= 1;
while (stepSize >= 1)
{
context.For(gridWidth, gridHeight, new JumpFloodPassShader(reading, writing, gridWidth, gridHeight, stepSize, derived.CellSize));
context.Barrier(writing);
(reading, writing) = (writing, reading);
stepSize >>= 1;
}
context.For(gridWidth, gridHeight, new ReachMaskShader(reading, grid.ReachMask, gridWidth, gridHeight, derived.CellSize, derived.ReachPixels));
context.Barrier(grid.ReachMask);
}
private static void RecordGrowthStepsStage(
in ComputeContext context,
CrystallineGrowthGridResources grid,
ReadWriteBuffer<int> scratch,
ReadWriteBuffer<int> birth,
int gridWidth,
int gridHeight,
in CrystallineGrowthPipeline.DerivedValues derived,
in CrystallineGrowthPipeline.Parameters parameters,
int firstStep,
int stepCount)
{
for (var step = firstStep; step < firstStep + stepCount; step++)
{
context.For(gridWidth, gridHeight, new DiffusionShader(grid.DiffusiveA, grid.DiffusiveB, gridWidth, gridHeight));
context.Barrier(grid.DiffusiveB);
context.For(gridWidth, gridHeight, new GrowthUpdateShader(
grid.DiffusiveB, grid.DiffusiveA, grid.BoundaryMass, grid.CrystalMass, birth, grid.ReachMask, scratch,
gridWidth, gridHeight, step, parameters.Seed,
CrystallineGrowthSettings.Kappa, derived.Beta, CrystallineGrowthSettings.Alpha, CrystallineGrowthSettings.Theta,
CrystallineGrowthSettings.Mu, CrystallineGrowthSettings.Gamma, derived.Sigma));
context.Barrier(grid.DiffusiveA);
context.Barrier(grid.BoundaryMass);
context.Barrier(grid.CrystalMass);
}
context.Barrier(birth);
context.Barrier(scratch);
}
private static void RecordRenderStage(
in ComputeContext context,
CrystallineGrowthGridResources grid,
ReadWriteTexture2D<Bgra32, Float4> source,
ReadWriteTexture2D<Bgra32, Float4> output,
ReadWriteBuffer<int> scratch,
ReadWriteBuffer<int> birth,
ReadWriteBuffer<int> tileBase,
ReadWriteBuffer<int> tileMask,
ReadWriteBuffer<float> geometry,
in CrystallineGrowthPipeline.PixelRect rect,
int sourceOffsetX,
int sourceOffsetY,
int sourceWidth,
int sourceHeight,
int gridWidth,
int gridHeight,
in CrystallineGrowthPipeline.DerivedValues derived,
in CrystallineGrowthPipeline.Parameters parameters,
int mode,
int geometryCapacity)
{
if (mode == CrystallineGrowthSettings.RenderModeCached)
{
context.For(rect.Width, rect.Height, new CachedRenderShader(
tileBase, tileMask, geometry, source, output,
rect.X, rect.Y, rect.Width, rect.Height,
sourceOffsetX, sourceOffsetY, sourceWidth, sourceHeight,
Math.Clamp(parameters.Frost, 0f, 1f), derived.RefractionPixels,
Math.Clamp(parameters.Specular, 0f, 1f),
parameters.ColorR, parameters.ColorG, parameters.ColorB));
return;
}
var gridLength = gridWidth * gridHeight;
context.For(gridLength, new RenderMassShader(
birth, grid.CrystalMass, scratch, grid.RenderMass, gridLength, Math.Clamp(parameters.Freeze, 0f, 1f)));
context.Barrier(grid.RenderMass);
if (mode == CrystallineGrowthSettings.RenderModeDraw)
{
context.For(CrystallineGrowthSettings.RoundUpToRenderTile(rect.Width), CrystallineGrowthSettings.RoundUpToRenderTile(rect.Height), new RenderShader(
grid.RenderMass, source, output,
rect.X, rect.Y, rect.Width, rect.Height, gridWidth, gridHeight,
sourceOffsetX, sourceOffsetY, sourceWidth, sourceHeight,
derived.CellSize,
Math.Clamp(parameters.Frost, 0f, 1f), derived.RefractionPixels,
Math.Clamp(parameters.Specular, 0f, 1f),
parameters.ColorR, parameters.ColorG, parameters.ColorB));
return;
}
context.For(1, new ShadedCountResetShader(scratch));
context.Barrier(scratch);
context.For(CrystallineGrowthSettings.RoundUpToRenderTile(rect.Width), CrystallineGrowthSettings.RoundUpToRenderTile(rect.Height), new RenderStoreShader(
grid.RenderMass, scratch, tileBase, tileMask, geometry, source, output,
rect.X, rect.Y, rect.Width, rect.Height, gridWidth, gridHeight,
sourceOffsetX, sourceOffsetY, sourceWidth, sourceHeight,
derived.CellSize,
Math.Clamp(parameters.Frost, 0f, 1f), derived.RefractionPixels,
Math.Clamp(parameters.Specular, 0f, 1f),
parameters.ColorR, parameters.ColorG, parameters.ColorB,
mode, geometryCapacity));
}
}
+29 -14
ファイルの表示
@@ -26,11 +26,23 @@ internal static class CrystallineGrowthSettings
public const int MaximumCanvasSize = 8192;
public const int MaximumStepCount = 3072;
public const int MarginPadding = 80;
public const int ScratchLength = 8;
public const int ScratchLength = 10;
public const int ScratchAttachedCount = 0;
public const int ScratchMaxBirth = 1;
public const int ScratchShadedCount = 2;
public const int ScratchMaskHashSum = 6;
public const int ScratchMaskHashMix = 7;
public const int ScratchSourceHashSum = 8;
public const int ScratchSourceHashMix = 9;
public const int MaximumPendingSubmissions = 32;
public const int GrowthStepsPerSubmission = 128;
public const int GrowthGroupWidth = 32;
public const int GrowthGroupHeight = 2;
public const int RenderTileSize = 8;
public const int RenderModeDraw = 0;
public const int RenderModeCount = 1;
public const int RenderModeStore = 2;
public const int RenderModeCached = 3;
public static QualitySettings GetQuality(CrystallineGrowthQuality quality)
=> quality switch
@@ -49,6 +61,22 @@ internal static class CrystallineGrowthSettings
return (gridWidth, gridHeight, cellSize);
}
public static int GetMargin(int itemWidth, int itemHeight, double reachPixels, int gridResolution)
{
var margin = (int)Math.Ceiling(reachPixels + MarginPadding);
while (true)
{
var (_, _, cellSize) = GetGridSize(itemWidth + margin * 2, itemHeight + margin * 2, gridResolution);
var required = (int)Math.Ceiling(Math.Max(reachPixels, cellSize) + MarginPadding);
if (required <= margin)
return margin;
margin = required;
}
}
public static int RoundUpToRenderTile(int length)
=> (length + RenderTileSize - 1) / RenderTileSize * RenderTileSize;
public static int GetStepCount(float reachCells, int maxSteps)
=> Math.Clamp((int)(reachCells * StepsPerCell) + 128, 192, maxSteps);
@@ -61,18 +89,5 @@ internal static class CrystallineGrowthSettings
public static float GetNoiseSigma(float noise)
=> Math.Clamp(noise, 0f, 1f) * MaximumSigma;
public static int GetJumpFloodPassCount(int width, int height)
{
var maxSide = Math.Max(Math.Max(width, height), 1);
var count = 0;
var step = 1;
while (step < maxSide)
{
step <<= 1;
count++;
}
return Math.Max(count, 1);
}
internal readonly record struct QualitySettings(int GridResolution, int MaxSteps);
}
+102
ファイルの表示
@@ -0,0 +1,102 @@
using System.Diagnostics;
using System.Reflection;
using System.Windows;
using System.Windows.Threading;
using Telemetry;
namespace CrystallineGrowth;
internal static class CrystallineGrowthTelemetry
{
private const int MaxChainLength = 5;
private const int MaxFrames = 100;
private static readonly Assembly Own = typeof(CrystallineGrowthTelemetry).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 CrystallineGrowthUpdateNotifier
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 CrystallineGrowthUpdateNotifier
};
await new Notifier(Owner, Repository, options).NotifyAsync().ConfigureAwait(false);
}
catch
catch (Exception exception)
{
if (exception is not UpdateCheckException)
CrystallineGrowthTelemetry.Report(exception);
}
}
+1 -1
ファイルの表示
@@ -2,5 +2,5 @@ namespace CrystallineGrowth;
internal static class ShaderResourceUri
{
public static Uri Get(string shaderName) => new($"pack://application:,,,/CrystallineGrowth;component/Shaders/{shaderName}.cso", UriKind.Absolute);
public static Uri Get(string shaderName) => new($"pack://application:,,,/CrystallineGrowth;component/Resources/Shader/{shaderName}.cso", UriKind.Absolute);
}
+4 -6
ファイルの表示
@@ -1,10 +1,8 @@
using YukkuriMovieMaker.Generator;
namespace CrystallineGrowth
{
[AutoGenLocalizer]
partial class Texts
{
namespace CrystallineGrowth;
}
[AutoGenLocalizer]
partial class Texts
{
}
+8 -8
ファイルの表示
@@ -8,31 +8,31 @@ AmountDescription,,氷の合成量です,Blend amount of the ice over the source
Freeze,,凍結度,Freeze,冻结度,凍結度,동결도,Congelación,درجة التجمد,Pembekuan
FreezeDescription,,霜の広がり具合です。素材の縁から凍りついていきます,Progress of the frost. It freezes over from the edges of the source,霜的扩展程度。从素材边缘开始冻结,霜的擴展程度。從素材邊緣開始凍結,서리가 퍼지는 정도입니다. 소재 가장자리부터 얼어붙습니다,Progreso de la escarcha. Se congela desde los bordes de la imagen,مدى انتشار الصقيع. يتجمد من حواف الصورة,Kemajuan embun beku. Membeku dari tepi sumber
Quality,,品質,Quality,品质,品質,품질,Calidad,الجودة,Kualitas
QualityDescription,,成長格子の解像度と成長ステップ数を選びます,Selects the growth grid resolution and step counts,选择生长网格分辨率与步数,選擇生長網格解析度與步數,성장 격자 해상도와 스텝 수를 선택합니다,Selecciona la resolución de la cuadrícula de crecimiento y el número de pasos,يحدد دقة شبكة النمو وعدد الخطوات,Memilih resolusi kisi pertumbuhan dan jumlah langkah
QualityDescription,,成長格子の解像度と成長ステップ数の上限を選びます,Selects the growth grid resolution and the step limit,选择生长网格分辨率与步数上限,選擇生長網格解析度與步數上限,성장 격자 해상도와 스텝 수 상한을 선택합니다,Selecciona la resolución de la cuadrícula de crecimiento y el límite de pasos,يحدد دقة شبكة النمو والحد الأقصى لعدد الخطوات,Memilih resolusi kisi pertumbuhan dan batas jumlah langkah
Branching,,樹枝化,Branching,树枝化,樹枝化,수지화,Ramificación,التفرع,Percabangan
BranchingDescription,,水蒸気の密度です。高いほど樹枝状に枝分かれします,Density of the vapor. Higher values branch into dendritic shapes,水蒸气密度。数值越高越呈树枝状分支,水蒸氣密度。數值越高越呈樹枝狀分支,수증기의 밀도입니다. 높을수록 수지상으로 가지를 칩니다,Densidad del vapor. Valores altos se ramifican en formas dendríticas,كثافة بخار الماء. القيم الأعلى تتفرع بأشكال شجيرية,Kepadatan uap air. Nilai tinggi bercabang berbentuk dendritik
Facet,,ファセット,Facet,晶面,晶面,패싯,Facetado,التسطح البلوري,Faset
FacetDescription,,付着の異方性です。高いほど結晶面が平らに揃います,Anisotropy of attachment. Higher values form flat crystal facets,附着的各向异性。数值越高晶面越平整,附著的異向性。數值越高晶面越平整,부착의 이방성입니다. 높을수록 결정면이 평평하게 정렬됩니다,Anisotropía de adhesión. Valores altos forman facetas cristalinas planas,تباين الالتصاق. القيم الأعلى تشكل أوجهًا بلورية مستوية,Anisotropi perlekatan. Nilai tinggi membentuk faset kristal yang datar
Reach,,到達距離,Reach,到达距离,到達距離,도달 거리,Alcance,المدى,Jangkauan
ReachDescription,,縁から霜が広がる距離です。素材の長辺に対する割合で指定します,Distance the frost spreads from the edge as a ratio of the longer side of the source,霜从边缘扩展的距离。以素材长边的比例指定,霜從邊緣擴展的距離。以素材長邊的比例指定,가장자리에서 서리가 퍼지는 거리입니다. 소재 긴 변에 대한 비율로 지정합니다,Distancia que se extiende la escarcha desde el borde como proporción del lado más largo de la fuente,المسافة التي ينتشر بها الصقيع من الحافة كنسبة من الضلع الأطول للمصدر,Jarak penyebaran embun beku dari tepi sebagai rasio sisi terpanjang sumber
ReachDescription,,縁から霜が広がる距離の上限です。素材の長辺に対する割合で指定します,Upper limit of the distance the frost spreads from the edge as a ratio of the longer side of the source,霜从边缘扩展的距离上限。以素材长边的比例指定,霜從邊緣擴展的距離上限。以素材長邊的比例指定,가장자리에서 서리가 퍼지는 거리의 상한입니다. 소재 긴 변에 대한 비율로 지정합니다,Límite de la distancia que se extiende la escarcha desde el borde como proporción del lado más largo de la fuente,الحد الأقصى للمسافة التي ينتشر بها الصقيع من الحافة كنسبة من الضلع الأطول للمصدر,Batas jarak penyebaran embun beku dari tepi sebagai rasio sisi terpanjang sumber
Noise,,ゆらぎ,Noise,扰动,擾動,요동,Fluctuación,التذبذب,Fluktuasi
NoiseDescription,,水蒸気のゆらぎです。シード値ごとに結晶の形が変わります,Fluctuation of the vapor. The crystal shape varies with the seed value,水蒸气的扰动。晶体形状随种子值变化,水蒸氣的擾動。晶體形狀隨種子值變化,수증기의 요동입니다. 시드 값에 따라 결정의 형태가 달라집니다,Fluctuación del vapor. La forma del cristal varía con el valor de la semilla,تذبذب بخار الماء. يتغير شكل البلورة حسب قيمة البذرة,Fluktuasi uap air. Bentuk kristal berubah sesuai nilai seed
NoiseDescription,,水蒸気のゆらぎです。シードごとに結晶の形が変わります,Fluctuation of the vapor. The crystal shape varies with the seed,水蒸气的扰动。晶体形状随种子变化,水蒸氣的擾動。晶體形狀隨種子變化,수증기의 요동입니다. 시드에 따라 결정의 형태가 달라집니다,Fluctuación del vapor. La forma del cristal varía con la semilla,تذبذب بخار الماء. يتغير شكل البلورة حسب البذرة,Fluktuasi uap air. Bentuk kristal berubah sesuai seed
Seed,,シード,Seed,种子,種子,시드,Semilla,البذرة,Seed
SeedDescription,,結晶の形を決める固定値です,A fixed value that determines the crystal shape,决定晶体形状的固定值,決定晶體形狀的固定值,결정의 형태를 결정하는 고정값입니다,Valor fijo que determina la forma del cristal,قيمة ثابتة تحدد شكل البلورة,Nilai tetap yang menentukan bentuk kristal
Frost,,白濁,Frost,白浊,白濁,백탁,Escarcha,التعكر الأبيض,Kabut Putih
FrostDescription,,氷の白濁の強さです,Strength of the white frosting of the ice,冰的白浊强度,冰的白濁強度,얼음이 하얗게 흐려지는 정도입니다,Intensidad del velo blanco del hielo,شدة التعكر الأبيض للجليد,Kekuatan kabut putih pada es
FrostDescription,,氷が素材を覆い隠す度合いです,How much the ice hides the source,冰遮盖素材的程度,冰遮蓋素材的程度,얼음이 소재를 가리는 정도입니다,Grado en que el hielo oculta la fuente,مدى إخفاء الجليد للمصدر,Seberapa jauh es menutupi sumber
Refraction,,屈折,Refraction,折射,折射,굴절,Refracción,الانكسار,Refraksi
RefractionDescription,,氷を通した背景の歪みの強さです,Strength of the background distortion through the ice,透过冰的背景扭曲强度,透過冰的背景扭曲強度,얼음을 통한 배경 왜곡의 강도입니다,Intensidad de la distorsión del fondo a través del hielo,شدة تشوه الخلفية عبر الجليد,Kekuatan distorsi latar melalui es
RefractionDescription,,氷越しに見える素材の歪みの強さです,Strength of the distortion of the source seen through the ice,透过冰看到的素材的扭曲强度,透過冰看到的素材的扭曲強度,얼음 너머로 보이는 소재의 왜곡 강도입니다,Intensidad de la distorsión de la fuente vista a través del hielo,شدة تشوه المصدر المرئي عبر الجليد,Kekuatan distorsi sumber yang terlihat melalui es
Specular,,光沢,Specular,光泽,光澤,광택,Brillo,اللمعان,Kilau
SpecularDescription,,氷の表面に映る光の強さです,Strength of the light reflected on the ice surface,冰面反射光的强度,冰面反射光的強度,얼음 표면에 비치는 빛의 강도입니다,Intensidad de la luz reflejada en la superficie del hielo,شدة الضوء المنعكس على سطح الجليد,Kekuatan cahaya yang terpantul pada permukaan es
IceColor,,色,Color,颜色,顏色,색,Color,اللون,Warna
IceColorDescription,,氷の色です,Color of the ice,冰的颜色,冰的顏色,얼음의 색입니다,Color del hielo,لون الجليد,Warna es
IceColorDescription,,白濁で覆った部分の色です,Color of the part covered by the frost,白浊覆盖部分的颜色,白濁覆蓋部分的顏色,백탁으로 덮인 부분의 색입니다,Color de la parte cubierta por la escarcha,لون الجزء المغطى بالتعكر الأبيض,Warna bagian yang tertutup kabut putih
QualityBalanced,,標準,Balanced,标准,標準,표준,Estándar,قياسي,Standar
QualityBalancedDescription,,格子解像度とステップ数を抑えた設定です,Uses reduced grid resolution and step counts,降低网格分辨率与步数的设置,降低網格解析度與步數的設定,격자 해상도와 스텝 수를 줄인 설정입니다,Configuración con resolución de cuadrícula y pasos reducidos,إعداد بدقة شبكة وعدد خطوات مخفضين,Pengaturan dengan resolusi kisi dan langkah yang dikurangi
QualityBalancedDescription,,格子解像度とステップ数の上限を抑えた設定です,Uses a reduced grid resolution and step limit,降低网格分辨率与步数上限的设置,降低網格解析度與步數上限的設定,격자 해상도와 스텝 수 상한을 줄인 설정입니다,Configuración con resolución de cuadrícula y límite de pasos reducidos,إعداد بدقة شبكة وحد أقصى للخطوات مخفضين,Pengaturan dengan resolusi kisi dan batas langkah yang dikurangi
QualityHigh,,高品質,High,高品质,高品質,고품질,Alta,عالية,Tinggi
QualityHighDescription,,品質と処理量の基準設定です,The reference balance of quality and cost,品质与处理量的基准设置,品質與處理量的基準設定,품질과 처리량의 기준 설정입니다,Configuración de referencia entre calidad y coste,الإعداد المرجعي للتوازن بين الجودة والتكلفة,Pengaturan acuan antara kualitas dan beban proses
QualityUltra,,最高品質,Ultra,最高品质,最高品質,최고 품질,Máxima,قصوى,Ultra
QualityUltraDescription,,最大の格子解像度とステップ数を使用します,Uses the largest grid resolution and step counts,使用最大的网格分辨率与步数,使用最大的網格解析度與步數,최대 격자 해상도와 스텝 수를 사용합니다,Usa la mayor resolución de cuadrícula y el mayor número de pasos,يستخدم أكبر دقة شبكة وأكبر عدد من الخطوات,Menggunakan resolusi kisi dan jumlah langkah terbesar
QualityUltraDescription,,最大の格子解像度とステップ数の上限を使用します,Uses the largest grid resolution and step limit,使用最大的网格分辨率与步数上限,使用最大的網格解析度與步數上限,최대 격자 해상도와 스텝 수 상한을 사용합니다,Usa la mayor resolución de cuadrícula y el mayor límite de pasos,يستخدم أكبر دقة شبكة وأعلى حد لعدد الخطوات,Menggunakan resolusi kisi dan batas langkah terbesar
TagIce,,氷,Ice,冰,冰,얼음,Hielo,جليد,Es
TagFrost,,霜,Frost,霜,霜,서리,Escarcha,صقيع,Embun beku
TagFreeze,,凍結,Freeze,冻结,凍結,동결,Congelación,تجمد,Pembekuan
1 Key Parameter ja-jp en-us zh-cn zh-tw ko-kr es-es ar-sa id-id
8 Freeze 凍結度 Freeze 冻结度 凍結度 동결도 Congelación درجة التجمد Pembekuan
9 FreezeDescription 霜の広がり具合です。素材の縁から凍りついていきます Progress of the frost. It freezes over from the edges of the source 霜的扩展程度。从素材边缘开始冻结 霜的擴展程度。從素材邊緣開始凍結 서리가 퍼지는 정도입니다. 소재 가장자리부터 얼어붙습니다 Progreso de la escarcha. Se congela desde los bordes de la imagen مدى انتشار الصقيع. يتجمد من حواف الصورة Kemajuan embun beku. Membeku dari tepi sumber
10 Quality 品質 Quality 品质 品質 품질 Calidad الجودة Kualitas
11 QualityDescription 成長格子の解像度と成長ステップ数を選びます 成長格子の解像度と成長ステップ数の上限を選びます Selects the growth grid resolution and step counts Selects the growth grid resolution and the step limit 选择生长网格分辨率与步数 选择生长网格分辨率与步数上限 選擇生長網格解析度與步數 選擇生長網格解析度與步數上限 성장 격자 해상도와 스텝 수를 선택합니다 성장 격자 해상도와 스텝 수 상한을 선택합니다 Selecciona la resolución de la cuadrícula de crecimiento y el número de pasos Selecciona la resolución de la cuadrícula de crecimiento y el límite de pasos يحدد دقة شبكة النمو وعدد الخطوات يحدد دقة شبكة النمو والحد الأقصى لعدد الخطوات Memilih resolusi kisi pertumbuhan dan jumlah langkah Memilih resolusi kisi pertumbuhan dan batas jumlah langkah
12 Branching 樹枝化 Branching 树枝化 樹枝化 수지화 Ramificación التفرع Percabangan
13 BranchingDescription 水蒸気の密度です。高いほど樹枝状に枝分かれします Density of the vapor. Higher values branch into dendritic shapes 水蒸气密度。数值越高越呈树枝状分支 水蒸氣密度。數值越高越呈樹枝狀分支 수증기의 밀도입니다. 높을수록 수지상으로 가지를 칩니다 Densidad del vapor. Valores altos se ramifican en formas dendríticas كثافة بخار الماء. القيم الأعلى تتفرع بأشكال شجيرية Kepadatan uap air. Nilai tinggi bercabang berbentuk dendritik
14 Facet ファセット Facet 晶面 晶面 패싯 Facetado التسطح البلوري Faset
15 FacetDescription 付着の異方性です。高いほど結晶面が平らに揃います Anisotropy of attachment. Higher values form flat crystal facets 附着的各向异性。数值越高晶面越平整 附著的異向性。數值越高晶面越平整 부착의 이방성입니다. 높을수록 결정면이 평평하게 정렬됩니다 Anisotropía de adhesión. Valores altos forman facetas cristalinas planas تباين الالتصاق. القيم الأعلى تشكل أوجهًا بلورية مستوية Anisotropi perlekatan. Nilai tinggi membentuk faset kristal yang datar
16 Reach 到達距離 Reach 到达距离 到達距離 도달 거리 Alcance المدى Jangkauan
17 ReachDescription 縁から霜が広がる距離です。素材の長辺に対する割合で指定します 縁から霜が広がる距離の上限です。素材の長辺に対する割合で指定します Distance the frost spreads from the edge as a ratio of the longer side of the source Upper limit of the distance the frost spreads from the edge as a ratio of the longer side of the source 霜从边缘扩展的距离。以素材长边的比例指定 霜从边缘扩展的距离上限。以素材长边的比例指定 霜從邊緣擴展的距離。以素材長邊的比例指定 霜從邊緣擴展的距離上限。以素材長邊的比例指定 가장자리에서 서리가 퍼지는 거리입니다. 소재 긴 변에 대한 비율로 지정합니다 가장자리에서 서리가 퍼지는 거리의 상한입니다. 소재 긴 변에 대한 비율로 지정합니다 Distancia que se extiende la escarcha desde el borde como proporción del lado más largo de la fuente Límite de la distancia que se extiende la escarcha desde el borde como proporción del lado más largo de la fuente المسافة التي ينتشر بها الصقيع من الحافة كنسبة من الضلع الأطول للمصدر الحد الأقصى للمسافة التي ينتشر بها الصقيع من الحافة كنسبة من الضلع الأطول للمصدر Jarak penyebaran embun beku dari tepi sebagai rasio sisi terpanjang sumber Batas jarak penyebaran embun beku dari tepi sebagai rasio sisi terpanjang sumber
18 Noise ゆらぎ Noise 扰动 擾動 요동 Fluctuación التذبذب Fluktuasi
19 NoiseDescription 水蒸気のゆらぎです。シード値ごとに結晶の形が変わります 水蒸気のゆらぎです。シードごとに結晶の形が変わります Fluctuation of the vapor. The crystal shape varies with the seed value Fluctuation of the vapor. The crystal shape varies with the seed 水蒸气的扰动。晶体形状随种子值变化 水蒸气的扰动。晶体形状随种子变化 水蒸氣的擾動。晶體形狀隨種子值變化 水蒸氣的擾動。晶體形狀隨種子變化 수증기의 요동입니다. 시드 값에 따라 결정의 형태가 달라집니다 수증기의 요동입니다. 시드에 따라 결정의 형태가 달라집니다 Fluctuación del vapor. La forma del cristal varía con el valor de la semilla Fluctuación del vapor. La forma del cristal varía con la semilla تذبذب بخار الماء. يتغير شكل البلورة حسب قيمة البذرة تذبذب بخار الماء. يتغير شكل البلورة حسب البذرة Fluktuasi uap air. Bentuk kristal berubah sesuai nilai seed Fluktuasi uap air. Bentuk kristal berubah sesuai seed
20 Seed シード Seed 种子 種子 시드 Semilla البذرة Seed
21 SeedDescription 結晶の形を決める固定値です A fixed value that determines the crystal shape 决定晶体形状的固定值 決定晶體形狀的固定值 결정의 형태를 결정하는 고정값입니다 Valor fijo que determina la forma del cristal قيمة ثابتة تحدد شكل البلورة Nilai tetap yang menentukan bentuk kristal
22 Frost 白濁 Frost 白浊 白濁 백탁 Escarcha التعكر الأبيض Kabut Putih
23 FrostDescription 氷の白濁の強さです 氷が素材を覆い隠す度合いです Strength of the white frosting of the ice How much the ice hides the source 冰的白浊强度 冰遮盖素材的程度 冰的白濁強度 冰遮蓋素材的程度 얼음이 하얗게 흐려지는 정도입니다 얼음이 소재를 가리는 정도입니다 Intensidad del velo blanco del hielo Grado en que el hielo oculta la fuente شدة التعكر الأبيض للجليد مدى إخفاء الجليد للمصدر Kekuatan kabut putih pada es Seberapa jauh es menutupi sumber
24 Refraction 屈折 Refraction 折射 折射 굴절 Refracción الانكسار Refraksi
25 RefractionDescription 氷を通した背景の歪みの強さです 氷越しに見える素材の歪みの強さです Strength of the background distortion through the ice Strength of the distortion of the source seen through the ice 透过冰的背景扭曲强度 透过冰看到的素材的扭曲强度 透過冰的背景扭曲強度 透過冰看到的素材的扭曲強度 얼음을 통한 배경 왜곡의 강도입니다 얼음 너머로 보이는 소재의 왜곡 강도입니다 Intensidad de la distorsión del fondo a través del hielo Intensidad de la distorsión de la fuente vista a través del hielo شدة تشوه الخلفية عبر الجليد شدة تشوه المصدر المرئي عبر الجليد Kekuatan distorsi latar melalui es Kekuatan distorsi sumber yang terlihat melalui es
26 Specular 光沢 Specular 光泽 光澤 광택 Brillo اللمعان Kilau
27 SpecularDescription 氷の表面に映る光の強さです Strength of the light reflected on the ice surface 冰面反射光的强度 冰面反射光的強度 얼음 표면에 비치는 빛의 강도입니다 Intensidad de la luz reflejada en la superficie del hielo شدة الضوء المنعكس على سطح الجليد Kekuatan cahaya yang terpantul pada permukaan es
28 IceColor 色 Color 颜色 顏色 색 Color اللون Warna
29 IceColorDescription 氷の色です 白濁で覆った部分の色です Color of the ice Color of the part covered by the frost 冰的颜色 白浊覆盖部分的颜色 冰的顏色 白濁覆蓋部分的顏色 얼음의 색입니다 백탁으로 덮인 부분의 색입니다 Color del hielo Color de la parte cubierta por la escarcha لون الجليد لون الجزء المغطى بالتعكر الأبيض Warna es Warna bagian yang tertutup kabut putih
30 QualityBalanced 標準 Balanced 标准 標準 표준 Estándar قياسي Standar
31 QualityBalancedDescription 格子解像度とステップ数を抑えた設定です 格子解像度とステップ数の上限を抑えた設定です Uses reduced grid resolution and step counts Uses a reduced grid resolution and step limit 降低网格分辨率与步数的设置 降低网格分辨率与步数上限的设置 降低網格解析度與步數的設定 降低網格解析度與步數上限的設定 격자 해상도와 스텝 수를 줄인 설정입니다 격자 해상도와 스텝 수 상한을 줄인 설정입니다 Configuración con resolución de cuadrícula y pasos reducidos Configuración con resolución de cuadrícula y límite de pasos reducidos إعداد بدقة شبكة وعدد خطوات مخفضين إعداد بدقة شبكة وحد أقصى للخطوات مخفضين Pengaturan dengan resolusi kisi dan langkah yang dikurangi Pengaturan dengan resolusi kisi dan batas langkah yang dikurangi
32 QualityHigh 高品質 High 高品质 高品質 고품질 Alta عالية Tinggi
33 QualityHighDescription 品質と処理量の基準設定です The reference balance of quality and cost 品质与处理量的基准设置 品質與處理量的基準設定 품질과 처리량의 기준 설정입니다 Configuración de referencia entre calidad y coste الإعداد المرجعي للتوازن بين الجودة والتكلفة Pengaturan acuan antara kualitas dan beban proses
34 QualityUltra 最高品質 Ultra 最高品质 最高品質 최고 품질 Máxima قصوى Ultra
35 QualityUltraDescription 最大の格子解像度とステップ数を使用します 最大の格子解像度とステップ数の上限を使用します Uses the largest grid resolution and step counts Uses the largest grid resolution and step limit 使用最大的网格分辨率与步数 使用最大的网格分辨率与步数上限 使用最大的網格解析度與步數 使用最大的網格解析度與步數上限 최대 격자 해상도와 스텝 수를 사용합니다 최대 격자 해상도와 스텝 수 상한을 사용합니다 Usa la mayor resolución de cuadrícula y el mayor número de pasos Usa la mayor resolución de cuadrícula y el mayor límite de pasos يستخدم أكبر دقة شبكة وأكبر عدد من الخطوات يستخدم أكبر دقة شبكة وأعلى حد لعدد الخطوات Menggunakan resolusi kisi dan jumlah langkah terbesar Menggunakan resolusi kisi dan batas langkah terbesar
36 TagIce 氷 Ice 冰 冰 얼음 Hielo جليد Es
37 TagFrost 霜 Frost 霜 霜 서리 Escarcha صقيع Embun beku
38 TagFreeze 凍結 Freeze 冻结 凍結 동결 Congelación تجمد Pembekuan
-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>
+91 -42
ファイルの表示
@@ -6,9 +6,9 @@
---
YukkuriMovieMaker4(YMM4)上で動作する、素材の輪郭を核形成点とみなし、Gravner–Griffeathの雪結晶成長モデルで氷晶を成長させて霜として描画する映像エフェクトプラグインです。
YukkuriMovieMaker4(YMM4)上で動作する、素材の縁を結晶の核とみなし、Gravner–Griffeathの雪結晶成長モデルで氷晶を成長させて霜として描画する映像エフェクトプラグインです。
履歴フレーム、参照画像、学習済みモデルを使わず、入力された一枚の映像だけを処理します。
氷晶の形はシードから決定論的に決まり、同じ設定では常に同じ形になります。
氷晶の形は素材とシードから決定論的に決まり、同じ設定では常に同じ形になります。
強さ、凍結度、樹枝化、ファセット、到達距離、ゆらぎ、白濁、屈折、光沢の9項目はアニメーションに対応しています。
![Image](https://github.com/routersys/YMM4-CrystallineGrowth/blob/main/docs/CrystallineGrowth.png)
@@ -22,7 +22,7 @@ YukkuriMovieMaker4(YMM4)上で動作する、素材の輪郭を核形成点
3. [インストール方法](#インストール方法)
4. [主な機能](#主な機能)
- [1. 氷晶の成長](#1-氷晶の成長)
- [2. 凍結度による凍結の遷移](#2-凍結度による凍結の遷移)
- [2. 凍結度と凍りつく様子](#2-凍結度と凍りつく様子)
- [3. 樹枝化とファセット](#3-樹枝化とファセット)
- [4. 到達距離とゆらぎ・シード](#4-到達距離とゆらぎシード)
- [5. 白濁・屈折・光沢・色](#5-白濁屈折光沢色)
@@ -33,9 +33,10 @@ YukkuriMovieMaker4(YMM4)上で動作する、素材の輪郭を核形成点
- [描画グループ](#描画グループ)
6. [制限事項](#制限事項)
7. [注意事項](#注意事項)
8. [免責事項](#免責事項)
9. [サードパーティライセンス](#サードパーティライセンス)
10. [ライセンス](#ライセンス)
8. [不具合の報告](#不具合の報告)
9. [免責事項](#免責事項)
10. [サードパーティライセンス](#サードパーティライセンス)
11. [ライセンス](#ライセンス)
---
@@ -43,11 +44,11 @@ YukkuriMovieMaker4(YMM4)上で動作する、素材の輪郭を核形成点
本プラグインはYMM4の映像エフェクトとして動作し、エフェクトの種類一覧では「氷晶成長」として表示されます。カテゴリは装飾とアニメーションです。
入力された現在のフレームのアルファ値から素材の輪郭を求め、輪郭のセルを核形成点として六方格子の上に置きます。成長の計算はGravner and Griffeathの論文「Modeling Snow Crystal Growth II: A mesoscopic lattice map with plausible dynamics」(2007年)のセルオートマトンに基づきます。各セルは付着フラグ、境界質量、結晶質量、拡散質量の4つの状態を持ち、水蒸気の拡散、凍結、異方性の付着、融解、ゆらぎの5つのステップを繰り返して氷晶を成長させます。成長は決定論的で、同じシードと同じパラメータでは常に同じ形になります。
入力された現在のフレームの不透明度から素材の形を求め、六角形のセルを敷き詰めた格子の上で、素材の縁にあたるセルを結晶の核にします。氷晶の成長の計算に使う格子モデルは、Gravner and Griffeathの論文「Modeling snow crystal growth II: A mesoscopic lattice map with plausible dynamics」(Physica D、2008年)に基づきます。水蒸気の拡散、凍結、付着、融解、ゆらぎの5つの処理を1ステップとし、このステップを繰り返して氷晶を成長させます。同じ素材、同じシード、同じパラメータからは、常に同じ形の氷晶ができます。
凍結度のパラメータは、成長の記録をどこまで表示するかを決めます。各セルには付着したステップが記録されるため、凍結度を時間で変えると、素材が縁から凍りついていく遷移になります。求めた氷晶は、白濁、背景の屈折、表面の光沢を持つ氷として描画し、元映像の上へ合成します。
求めた氷晶は、氷として描画して素材の上へ重ねます。氷は白く濁り、氷越しの素材を屈折させ、表面に光沢を持ちます。各セルが結晶に加わったステップの記録を、成長の記録と呼びます。描画するのは、成長の記録のうち、凍結度で決めた途中までです。凍結度をアニメーションで変えると、素材が縁から凍りついていく様子になります。
計算はComputeSharpの計算シェーダーがDirect3D 12で実行します。YMM4のDirect3D 11側とComputeSharpのDirect3D 12側は、共有テクスチャと共有フェンスで接続します。通常のフレーム処理では、CPUへの画素の読み戻しを行わず、付着ステップの記録だけを読み戻します。氷晶が存在する矩形の範囲だけを描画し、素材の形状とパラメータが変わらないフレームでは成長の計算を再利用します。
計算はComputeWeaveの計算シェーダーがDirect3D 12で実行します。YMM4のDirect3D 11側とComputeWeaveのDirect3D 12側は、共有テクスチャと共有フェンスで接続します。通常のフレーム処理では、CPUへの画素の読み戻しを行わず、10個の整数の読み戻しだけで素材の変化を判定します。素材の形と大きさ、成長に関わるパラメータが変わらないフレームでは、成長の計算を再利用します。成長を計算し直したときだけ、成長の記録を読み戻します。この記録から、凍結度で表示している氷晶を囲む矩形をフレームごとに求め、描画はこの矩形の範囲だけで行います。
このエフェクトはAviUtl向けのEXO出力には対応していません。
@@ -77,45 +78,57 @@ YukkuriMovieMaker4(YMM4)上で動作する、素材の輪郭を核形成点
### 1. 氷晶の成長
現在のフレームのアルファ値から素材の輪郭を求め、輪郭のセルを核形成点として六方格子の上に置きます。格子は各セルが6つの隣接セルを持つ三角格子で、実際の氷の結晶構造と同じ六方対称の成長になります。
成長は、平面を六角形のセルで隙間なく敷き詰めた格子の上で計算します。各セルは6つのセルと隣り合い、結晶はこの6つの方向に沿って伸びます。枝や平らな面の向きは、実際の雪結晶と同じく60度ごとに揃います。
各セルは付着フラグ、境界質量、結晶質量、拡散質量の4つの状態を持ちます。1ステップの更新は、水蒸気の拡散、結晶境界での凍結、境界質量のしきい値による付着、融解、ゆらぎの順で行います。付着のしきい値は隣接する結晶セルの数で変わり、先端では高く、くぼみでは低くなります。この異方性が、実際の雪結晶に見られるファセットと樹枝の分岐を作ります。
不透明度が5%を超える画素が1つでもあるセルを素材の内側とし、内側のセルのうち外側のセルと接するセルを結晶の核にします。透明な部分の無い素材では、素材の四辺が縁になります。
外部マスクや手動の位置指定は必要としません。成長は品質設定が定めるステップ数を上限として、到達距離に応じた回数だけ進みます。
各セルは、結晶に加わったかどうかと、水蒸気の量、擬似液体層の量、氷の量の4つの状態を持ちます。擬似液体層は、氷点下の氷の表面を覆う、液体に近い薄い水の層です。
### 2. 凍結度による凍結の遷移
1ステップでは、水蒸気の拡散、結晶の縁での凍結、付着、融解、ゆらぎの順に処理します。凍結では、結晶に接するセルの水蒸気の一部が氷に、残りが擬似液体層に変わります。付着では、擬似液体層の量がしきい値に達したセルが結晶に加わります。しきい値は、隣のセルのうち結晶に加わっているセルの数で変わり、結晶の先端では高く、くぼみでは低くなります。融解では、結晶に接していながら結晶に加わらなかったセルで、擬似液体層と氷のごく一部が水蒸気に戻ります。
凍結度は、成長の記録をどこまで表示するかを決めます。0%では何も描画せず、値を上げると氷晶が素材の縁から外側と内側の両方へ伸びていきます。各セルには付着したステップが記録されるため、表示は成長の順序どおりに進みます。
結晶への加わりやすさが先端かくぼみかで変わるため、結晶は向きによって伸び方が違ってきます。この性質を付着の異方性と呼びます。付着の異方性によって、実際の雪結晶に見られる平らな結晶面と樹枝の分岐が生まれます。この平らな結晶面をファセットと呼びます。
凍結度を時間で変えると、テキストや立ち絵が端から凍りついていく演出になります。
成長を進めるステップ数は到達距離から決まり、品質ごとの上限を超えません。決め方は「品質の選択」にあります。
### 2. 凍結度と凍りつく様子
凍結度は、成長の記録をどこまで表示するかを決めます。成長の記録には、各セルが結晶に加わったステップが残り、表示はこのステップの順に進みます。凍結度が決めるのは表示だけで、成長の計算には影響しません。0%では何も描画せず、値を上げると氷晶が素材の縁から外側と内側の両方へ伸びていきます。セルが最後に結晶に加わったステップを100%とし、凍結度が50%なら、そのステップ数の半分までに結晶に加わったセルを表示します。
凍結度のデフォルトは100%なので、エフェクトを追加すると、計算したステップをすべて終えた形が表示されます。凍結度を0%から100%へアニメーションで変えると、テキストや立ち絵が縁から凍りついていく演出になります。
### 3. 樹枝化とファセット
樹枝化は、格子を満たす水蒸気の密度を決めます。低いほど板状にまとまり、高いほど樹枝状に枝分かれします。
ファセットは、付着の異方性の強さを決めます。高いほど結晶面が平らに揃い、板状の輪郭になります。低いほど枝が細かく分かれます。2つのパラメータの組み合わせで、板状、扇状、樹枝状、シダ状の形を連続的に変えられます。
パラメータの「ファセット」は、付着の異方性の強さを決めます。「ファセット」を上げると、結晶の先端や平らな縁にあるセルは、擬似液体層の量がより多くなるまで結晶に加わりません。そのため先端が伸びにくくなり、結晶面が平らに揃って板状の輪郭になります。「ファセット」が低いほど、枝が細かく分かれます。
Gravner and Griffeathの論文によると、氷晶の形は水蒸気の密度と先端や平らな縁のしきい値によって、板状、扇状、樹枝状、シダ状へ連続的に移り変わります。樹枝化は水蒸気の密度を、「ファセット」は先端や平らな縁のしきい値を決めます。
### 4. 到達距離とゆらぎ・シード
到達距離は、縁から霜が広がる距離を素材の長辺に対する割合で決めます。距離はジャンプフラッドで求めた縁からの距離で判定し、縁の外側と内側の両方に適用します。到達距離を大きくするほど計算領域が広がり、処理量が増えます。
到達距離は、縁から霜が広がる距離の上限を、素材の長辺に対する割合で決めます。素材の長辺は、透明な部分も含む素材全体の長辺です。どの核のセルからも上限より遠いセルは、結晶に加わりません。上限は縁の外側と内側の両方に適用します。上限が1セルの幅より短いときは、1セルの幅を上限にします。
ゆらぎは、水蒸気の拡散質量へ加える微小な変動の大きさを決めます。ゆらぎが0%のとき、氷晶の形は素材の輪郭とパラメータだけで決まり、シードは形に影響しません。
計算領域は、透明な部分も含む素材全体の上下左右に、到達距離と80画素の余白を加えた大きさです。到達距離を大きくするほど計算領域が広がり、ステップ数も増えるので、処理が重くなります。1セルの幅は計算領域の長辺と格子解像度から決まるため、計算領域が広がると1セルが大きくなることがあり、そのときは氷晶の細部が粗くなります。1セルの幅の決め方は「品質の選択」にあります。
シードは、ゆらぎの内容を決める固定値です。ゆらぎとシードとセル位置から決定論的に変動を作るため、同じシードと同じパラメータでは常に同じ形になります。
ゆらぎは、各ステップでセルごとの水蒸気の量がわずかに増減する割合を決めます。増減の割合は、ゆらぎが100%のときに0.2%です。ゆらぎが0%のとき、氷晶の形は素材の形とパラメータだけで決まり、シードは形に影響しません。
シードは、どのセルで水蒸気を増やし、どのセルで減らすかを決める固定値です。増やすか減らすかは、シードとセル位置とステップだけで決まります。
### 5. 白濁・屈折・光沢・色
白濁は、氷の白さを決めます。結晶質量が多い部分ほど強く白くなります。
白濁は、氷が素材を覆い隠す度合いを決めます。氷の厚い部分ほど強くかかります。素材の内側も凍るので、白濁が強いと素材は見えにくくなります。
屈折は、氷を通した背景の歪みの強さを決めます。氷の厚みの勾配から法線を求め、法線の向きに応じて元映像の参照位置をずらします。
素材の外側には、氷越しに見える映像がありません。そこへ伸びた氷は白濁の色に光沢が乗って見え、白濁が強いほど濃くなります。白濁を0%にすると、素材の外側の氷は光沢も含めて見えなくなります。ただし縁のすぐ近くでは、屈折でずれた素材が氷に映り込むため、見えることがあります。
光沢は、氷の表面に映る光の強さを決めます。固定した光源の向きと法線から反射光を計算します。
屈折は、氷越しに見える素材の歪みの強さを決めます。氷の厚みの勾配から法線を求め、法線の向きに応じて素材を参照する位置をずらします。歪むのは素材だけで、下にある別のアイテムは歪みません。
色は、氷の色を決めます。白濁した部分が指定した色に染まります。
光沢は、氷の表面に映る光の強さを決めます。照り返しは、左上の手前に固定した光と法線から計算します。
色は、白濁で覆った部分の色を決めます。色の不透明度は使いません。
### 6. 品質の選択
品質は、成長格子の解像度と成長ステップ数の上限をまとめて切り替えます。
品質は、成長格子の解像度と成長ステップ数の上限をまとめて切り替えます。品質を変えると格子解像度が変わるため、氷晶の形も変わります。
| 品質 | 格子解像度 | 成長ステップ上限 |
|---|---:|---:|
@@ -123,7 +136,9 @@ YukkuriMovieMaker4(YMM4)上で動作する、素材の輪郭を核形成点
| 高品質 | 288 | 2048回 |
| 最高品質 | 384 | 3072回 |
格子解像度は計算領域の長辺のセル数です。短辺のセル数は計算領域の縦横比に合わせて決めます。実際のステップ数は到達距離に応じて決まり、上限で打ち切ります。
格子解像度は、1セルの幅を決める数です。1セルの幅は、計算領域の長辺の画素数を格子解像度で割った長さで、1画素より小さくはなりません。格子解像度が大きいほど1セルが小さくなり、氷晶の細部まで表せます。
ステップ数は、到達距離がセル何個分にあたるかを求め、その24倍の整数部分に128を足した回数です。ただし192回を下回らず、品質の上限を超えません。
---
@@ -133,9 +148,9 @@ YukkuriMovieMaker4(YMM4)上で動作する、素材の輪郭を核形成点
| パラメータ名 | 型 | デフォルト | スライダー表示範囲 | アニメーション | 説明 |
|---|---|---|---|---|---|
| 強さ | 数値 | 100% | 0〜100% | 対応 | 氷の合成量です。0%では入力を変更しません。 |
| 凍結度 | 数値 | 100% | 0〜100% | 対応 | 霜の広がり具合です。素材の縁から凍りついていきます。 |
| 品質 | 列挙 | 高品質 | 標準 / 高品質 / 最高品質 | 非対応 | 成長格子の解像度と成長ステップ数を選択します。 |
| 強さ | 数値 | 100% | 0〜100% | 対応 | 氷の合成量です。下げると白濁、屈折、光沢がまとめて弱まります。0%では入力を変更しません。 |
| 凍結度 | 数値 | 100% | 0〜100% | 対応 | 成長の記録をどこまで表示するかです。0%では何も描画せず、100%では計算したステップをすべて終えた形を表示します。 |
| 品質 | 列挙 | 高品質 | 標準 / 高品質 / 最高品質 | 非対応 | 成長格子の解像度と成長ステップ数の上限を選択します。 |
### 成長グループ
@@ -143,18 +158,18 @@ YukkuriMovieMaker4(YMM4)上で動作する、素材の輪郭を核形成点
|---|---|---|---|---|---|
| 樹枝化 | 数値 | 60% | 0〜100% | 対応 | 水蒸気の密度です。高いほど樹枝状に枝分かれします。 |
| ファセット | 数値 | 40% | 0〜100% | 対応 | 付着の異方性です。高いほど結晶面が平らに揃います。 |
| 到達距離 | 数値 | 25% | 5〜100% | 対応 | 縁から霜が広がる距離です。素材の長辺に対する割合で指定します。直接入力では1〜400%まで指定できます。 |
| ゆらぎ | 数値 | 25% | 0〜100% | 対応 | 水蒸気のゆらぎです。シード値ごとに結晶の形が変わります。 |
| シード | 整数 | 0 | 0〜10000 | 非対応 | 結晶の形を決める固定値です。直接入力では2147483647まで指定できます。 |
| 到達距離 | 数値 | 25% | 5〜100% | 対応 | 縁から霜が広がる距離の上限です。素材の長辺に対する割合で指定します。直接入力では1〜400%まで指定できます。 |
| ゆらぎ | 数値 | 25% | 0〜100% | 対応 | 水蒸気のゆらぎです。シードごとに結晶の形が変わります。 |
| シード | 整数 | 0 | 0〜10000 | 非対応 | 結晶の形を決める固定値です。ゆらぎが0%のときは形に影響しません。直接入力では2147483647まで指定できます。 |
### 描画グループ
| パラメータ名 | 型 | デフォルト | スライダー表示範囲 | アニメーション | 説明 |
|---|---|---|---|---|---|
| 白濁 | 数値 | 70% | 0〜100% | 対応 | 氷の白濁の強さです。 |
| 屈折 | 数値 | 40% | 0〜100% | 対応 | 氷を通した背景の歪みの強さです。 |
| 白濁 | 数値 | 70% | 0〜100% | 対応 | 氷が素材を覆い隠す度合いです。 |
| 屈折 | 数値 | 40% | 0〜100% | 対応 | 氷越しに見える素材の歪みの強さです。 |
| 光沢 | 数値 | 50% | 0〜100% | 対応 | 氷の表面に映る光の強さです。 |
| 色 | 色 | #CDE4FF | — | 非対応 | 氷の色です。 |
| 色 | 色 | #CDE4FF | — | 非対応 | 白濁で覆った部分の色です。不透明度は使いません。 |
---
@@ -162,24 +177,58 @@ YukkuriMovieMaker4(YMM4)上で動作する、素材の輪郭を核形成点
- AviUtl向けのEXO出力には対応していません。
- Direct3D 12デバイスを取得できない場合や、YMM4が使うDirect3D 11デバイスとの共有テクスチャおよび共有フェンスを作成できない場合は、エフェクトを適用せず入力映像を表示します。
- 核形成点の判定には現在のフレームのアルファ値だけを使用します。輝度と色は判定に影響しません。履歴フレーム、外部画像、学習済みモデルは使用しません。
- 計算領域は素材の範囲に到達距離と描画の余白を加えた大きさで、長辺は8192画素が上限です。素材が大きく余白を確保できない場合は、エフェクトを適用せず入力映像を表示します。
- 核の判定には現在のフレームの不透明度だけを使用します。輝度と色は判定に影響しません。不透明度が5%を超える画素が1つでもあるセルを素材の内側とみなします。履歴フレーム、外部画像、学習済みモデルは使用しません。
- 計算領域は、透明な部分も含む素材全体の上下左右に、到達距離と80画素の余白を加えた大きさです。到達距離と余白をそのまま加えると計算領域の長辺が8192画素を超えるときは、縁から霜が広がる距離の上限を設定より短くして計算します。ただし計算領域を決めるときは、この上限を1セルの幅より短くせず、80画素の余白も必ず取ります。そのため、計算領域の長辺は8192画素を超えることがあり、最大で8408画素になります。素材の長辺が8160画素を超える場合は、エフェクトを適用せず入力映像を表示します。
- 処理量とGPUメモリ使用量は、計算領域の大きさと品質に応じて増えます。
---
## 注意事項
- 処理負荷: 最高品質は格子解像度と成長ステップ数が最も多いため、高品質と標準より処理負荷が高くなります。到達距離を大きくするほど計算領域が広がります。描画は氷晶が存在する矩形の範囲だけを計算します。
- キャッシュ: 素材の輪郭と結晶の形を決めるパラメータが変わらないフレームでは、成長の計算を再利用します。凍結度、白濁、屈折、光沢、色だけを変えたフレームでは、結晶を再計算しません。
- 処理負荷: 最高品質は格子解像度と成長ステップ数の上限が最も大きいため、高品質と標準より処理負荷が高くなります。到達距離を大きくするほど計算領域が広がり、ステップ数も増えます。描画は、凍結度で表示している氷晶を囲む矩形の範囲だけで行います。
- キャッシュ: 素材の形と大きさ、品質、シード、樹枝化、ファセット、到達距離、ゆらぎが変わらないフレームでは、成長の計算を再利用します。ゆらぎが0%のときは、シードを変えても成長の計算を再利用します。素材の形が変わったかどうかは、素材の内側とみなしたセルの並びで判定し、成長の計算を再利用するフレームでも毎回確かめます。不透明な動画のように形を保ったまま色だけが変わる素材では、成長の計算を再利用し、氷の描画だけをやり直します。素材の色が変わったかどうかは、凍結度、白濁、屈折、光沢、色が前に氷を描いたときと同じフレームで確かめます。これらのどれかが変わったフレームでは、色を確かめずに氷を描き直します。成長の計算を再利用し、凍結度も変わらないまま氷の描き直しが続くときは、描画の途中結果を氷のかかる画素だけGPUメモリに保存します。次からは、保存した途中結果から描き直します。成長を計算し直すか凍結度が変わると、保存した途中結果は破棄します。強さ、凍結度、白濁、屈折、光沢、色だけを変えたフレームでは、成長を計算し直しません。素材の形が変わるフレームと、樹枝化、ファセット、到達距離、ゆらぎをアニメーションで変えたフレームでは、成長を毎回計算し直すため、処理が重くなります。
- 凍結度0%と強さ0%: 凍結度が0%のときは何も描画しません。強さが0%のときは入力を変更しません。
- シードと再現性: 氷晶の形は、シード、セル位置、成長ステップから決定論的に算出します。時間値は結晶の生成に使用しません。
- 透明部分: 霜は素材の外側にも描画されるため、出力範囲は素材より広がります。氷は元映像の上へアルファ合成します。
- シードと再現性: 氷晶の形は、素材の形と大きさ、パラメータ、シード、セル位置、成長ステップから決定論的に算出します。時間値は結晶の生成に使用しません。
- 透明部分: 氷は素材の外側にも描画されるため、出力範囲は素材より広がります。素材の外側の氷は白濁が強いほど濃く見え、白濁が0%のときはほとんど見えません。氷は元映像の上へアルファ合成します。
- 更新通知: エフェクトを最初に生成したときに、YMM4の実行中に一度だけ新しい正式版を確認します。更新情報を取得できない場合は通知せず、そのまま動作します。プレリリースは通知の対象に含めません。
- 不具合の自動送信: 想定していない例外が起きたときは、その内容を開発者へ自動で送信します。内容は「不具合の報告」に書いています。
- 本プラグインを使用する前に、YMM4のプロジェクトファイルのバックアップを作成することを推奨します。
---
## 不具合の報告
本プラグインは、想定していない例外が起きたときに、その内容を開発者へ自動で送信します。同意は求めず、常に送信します。
送信する情報は次のとおりです。
| 種類 | 内容 |
|---|---|
| 例外 | 型の完全名、メッセージ、スタックトレース |
| 発生位置 | モジュール名、関数名、ファイル名、行番号 |
| プラグイン | アセンブリ名、バージョン |
| 実行環境 | OSの名前とバージョン、.NETのバージョン、CPUのアーキテクチャ、論理プロセッサ数 |
| 識別子 | YMM4の起動ごとに決まるセッション識別子、報告ごとの識別子 |
メッセージとファイル名は、送信の前に置き換えを通します。置き換えるのは、Windowsのユーザー名、ユーザーフォルダー、AppDataのパス、マシン名、ドメイン名、メールアドレス、IPv4アドレスです。送信元のIPアドレスは受信側へ渡す手前で取り除いています。
映像の中身とプロジェクトの内容は送信しません。継続して個人を追跡する識別子も持ちません。セッション識別子はYMM4を起動し直すと別の値になります。
送信するのは想定していない例外だけです。YMM4が本プラグインのエフェクトを作るとき、フレームごとに更新するとき、入力をつなぎ直すとき、破棄するときと、Direct2Dがシェーダーの定数を書き込むときに起きた例外を報告し、その後はYMM4へそのまま渡します。更新の確認で起きた例外は、更新情報の取得の失敗を除いて報告し、YMM4へは渡しません。画面の操作やバックグラウンドの処理で未処理になった例外も報告しますが、本プラグインのコードが関わる例外に限ります。本プラグインの外で起きた例外は送信しません。
次の失敗は送信しません。
| 種類 | 例 |
|---|---|
| 効果をかけないだけで済ませるもの | Direct3D 12デバイスを取得できない、YMM4のDirect3D 11デバイスとの共有テクスチャや共有フェンスを作成できない、素材の長辺が8160画素を超えるときに、エフェクトを適用せず入力映像を表示したとき |
| 更新の確認の通信の失敗 | GitHubへ接続できない |
送信できなかった報告はYMM4のユーザーフォルダーへ退避します。次にYMM4を起動したあと、本プラグインのエフェクトを生成するか、同じくYMM4-Telemetryで報告する別のプラグインが動き始めると、退避した報告を1回の起動で10件まで送り直します。送信も再送も非同期に行うため、通信を待って起動と描画が遅くなることはありません。
実装は [YMM4-Telemetry](https://github.com/routersys/YMM4-Telemetry) をサブモジュールとして取り込んでいます。
---
## 免責事項
本プラグインはMITライセンスのもとで公開されています。
@@ -192,11 +241,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 で追加されました。
バイナリ
ファイルの表示
バイナリファイルは表示されません。

変更前

幅:  |  高さ:  |  サイズ: 751 KiB

変更後

幅:  |  高さ:  |  サイズ: 1.0 MiB

+5
ファイルの表示
@@ -0,0 +1,5 @@
{
"test": {
"runner": "Microsoft.Testing.Platform"
}
}