12 コミット
10個のファイルの変更、443行の追加、271行の削除

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

+65 -123
ファイルの表示
@@ -1,153 +1,95 @@
# v1.0.0 - 光輸送結像 for YMM4
# v1.0.1 - 光輸送結像 for YMM4
YukkuriMovieMaker4向けの光輸送結像エフェクトプラグインの初回リリースです。
現在のフレームの明るさを輸送格子の上に光の分布として集め、選択した光源形状が定める目標分布へ移す輸送写像を求めます。
集光度に応じて写像を進め、光源形状へ広げた光を元映像へ結像させます。
計算はComputeSharpの計算シェーダーがDirect3D 12で実行し、YMM4のDirect3D 11側とは共有テクスチャおよび共有フェンスで接続します。
8言語のリソース構成のUIを備えます。
光輸送結像エフェクトプラグインの修正と改善のリリースです。
画素数が1048560を超える映像で例外が発生し、アイテムの更新に失敗していた不具合を修正しました。合わせて対応する大きさの上限を定め、3840×2160と4096×2160を処理できるようにしました。
色の積算をグループ共有メモリでタイル化し、1フレームあたりの処理時間を短縮しました。1024×1000ではv1.0.0の13.71msから9.09msへ、v1.0.0では例外で処理できなかった3840×2160では、修正だけを適用した状態の74.50msから44.71msへ短縮しました。
積算の固定小数点の倍率が変わるため、出力の画素値はv1.0.0と完全には一致しません。タイル化の前後では全画素が一致します。根拠は「改善 3. 等価性の検証」に記載します。
---
## 新機能
## 修正
### 1. 光輸送の計算パイプライン
### 1. 積算バッファーのクリアがスレッドグループ数の上限を超える不具合
`CausticTransportPipeline`は、1フレーム分の計算シェーダーを1つの`ComputeContext`へ記録して実行します。輸送格子と積算バッファーは入力サイズと品質に応じて確保し、サイズが変わらないフレームでは再利用します。処理の流れは次のとおりです。
プレビューの再生中に`System.ArgumentOutOfRangeException`が発生し、アイテムの更新に失敗する不具合を修正しました。
1. `GridDepositShader`が、各格子セルに対応する画素のBT.709輝度(`0.2126 R + 0.7152 G + 0.0722 B + 0.01 A`)を合計し、光の分布を作ります。
2. `LightShapeShader`が、光源形状から目標分布を作ります。面は全体を1とし、円とスリットは光源サイズが定める半径の内側を1、外側を0へ`SmoothStep`で落とします。
3. `GridRowSumShader`と`NormalizeScaleShader`が、光の分布と目標分布の総量を求め、両者を同じ総量へそろえる倍率を計算します。
4. `InitializeDisplacementShader`が、輸送写像の初期値を置きます。面は移動なし、円は正方格子を円板へ写す写像、スリットは片方の軸を帯へ圧縮する写像を初期値とします。
5. 輸送反復では、`PushforwardShader`が分布を写像に沿って押し出し、`ResidualShader`が押し出した分布と目標分布の差を求めます。差を右辺として、`RestrictShader`・`JacobiShader`・`ProlongShader`によるマルチグリッドのVサイクルでポテンシャルのポアソン方程式を解き、`UpdateDisplacementShader`がポテンシャルの勾配に沿って写像を更新します。
6. `SplatShader`が、各画素の色を集光度に応じた移動先へ加算し、`ResolveShader`が積算値を正規化して出力します。
原因は、色の積算バッファーのゼロ初期化を、要素数をそのまま反復数とする1次元のディスパッチで実行していたことです。このシェーダーのスレッドグループは64スレッドであり、積算バッファーの要素数は画素数の4倍であるため、ディスパッチするスレッドグループ数は画素数の16分の1になります。ComputeSharpが検証するスレッドグループ数の上限は1次元あたり65535であるため、画素数が1048560を超えると超過します。1920×1080では129600になり、報告された例外の値202500は3240000画素に対応します。
押し出しと積算は、`Hlsl.InterlockedAdd`で加算するために固定小数点で行います。押し出しは倍率`16384`、積算は画素数から`256`〜`65536`の範囲で選ぶ倍率を使い、32ビット整数の範囲を超えないようにします。
ゼロ初期化を、ComputeSharpの`ComputeContext.Clear`へ変更しました。この操作は`ClearUnorderedAccessViewUint`を発行するため、ディスパッチを伴わず、スレッドグループ数の上限の制約を受けません。輸送格子とマルチグリッドの最粗階層のゼロ初期化も同じ操作へ統一し、そのための専用シェーダー2種類を削除しました。
| シェーダー | 役割 |
|---|---|
| `GridDepositShader` | 画素の輝度を格子セルへ合計する |
| `LightShapeShader` | 光源形状から目標分布を作る |
| `GridRowSumShader` / `NormalizeScaleShader` | 分布と目標分布の総量をそろえる倍率を求める |
| `InitializeDisplacementShader` | 光源形状から輸送写像の初期値を置く |
| `PushforwardShader` | 分布を写像に沿って押し出す |
| `ResidualShader` | 押し出した分布と目標分布の差を求める |
| `RestrictShader` / `ProlongShader` | マルチグリッドの粗化と補間を行う |
| `JacobiShader` | ポアソン方程式をJacobi法で解く |
| `UpdateDisplacementShader` | ポテンシャルの勾配で写像を更新する |
| `SplatShader` | 画素の色を移動先へ加算する |
| `ResolveShader` | 積算値を正規化して出力する |
### 2. 対応する大きさの上限と上限超過時の素通し
写像の更新は、緩和係数`0.7`で勾配を掛け、1回の移動量を格子`3`セル分に制限します。マルチグリッドは、長辺が`16`セル以下になる粗さまで階層を作ります。
色の積算は`Hlsl.InterlockedAdd`で加算するため固定小数点で行います。1つの積算先が受け取る値の上界は画素数と倍率の積であり、桁あふれしない条件は、この積が積算バッファーの型の最大値以下であることです。倍率の下限は256、余裕は1.5倍として算出しているため、符号付き32ビットでの上限は5592405画素でした。3840×2160の8294400画素はこの上限を超えており、桁あふれしない保証がありませんでした。
### 2. Direct3D 11・Direct3D 12相互運用
- 積算バッファーを符号付き32ビットから符号なし32ビットへ変更しました。積算へ加える値は、画素値と双線形の重みと分散時のアルファ配分のいずれも非負であるため、符号ビットは使用していませんでした。桁が2倍になり、上限は11184810画素へ広がります。4096×2160の8847360画素もこの範囲に含まれます。
- 倍率の算出の基準も符号なし32ビットの最大値へ改めました。3840×2160の倍率は256から345へ上がり、8ビット出力の量子化幅である255分の1より細かい刻みを保ちます。
- 桁あふれを隠していた`ResolveShader`の負値の切り上げを削除しました。符号なし32ビットの積算値は常に0以上です。
- 対応する大きさの判定を`CausticTransportSettings.IsSupportedSize`へ集約しました。辺が8192画素以下、かつ総画素数が11184810以下です。上限を超える入力にはカスタムシェーダーの`Amount`を0にし、入力映像をそのまま表示します。従来の判定は`int.MaxValue`を基準としており、テクスチャの確保がComputeSharpの検証で例外になる大きさを通していました。
- 辺の上限は、Direct3D 12のTexture2Dの上限である16384に対して余裕を取り、8192としました。本プラグインは共有テクスチャからDirect2Dのビットマップを作成するため、Direct2Dのビットマップの上限も効きます。この上限は機能レベルに依存します。
`CausticTransportGpuInterop`は、YMM4のDirect3D 11・Direct2D側と、ComputeSharpのDirect3D 12側を接続します。ComputeSharpの`GraphicsDevice`は、YMM4が使うDXGIアダプターのLUIDと一致するものを選びます。
| 項目 | v1.0.0 | v1.0.1 |
|---|---|---|
| 積算バッファーの型 | 符号付き32ビット | 符号なし32ビット |
| 桁あふれしない画素数の上限 | 5592405 | 11184810 |
| 3840×2160の倍率 | 256 | 345 |
| 対応する辺の上限 | `int.MaxValue` | 8192 |
| 上限超過時の動作 | テクスチャの確保で例外 | 入力映像をそのまま表示 |
入力と出力は、ComputeSharpで確保した共有テクスチャをDirect3D 11のテクスチャとして開き、Direct2Dのビットマップとして扱います。入力は、Direct2Dの描画コンテキストが共有テクスチャへ`SourceCopy`で描き込みます。両デバイスの同期は、Direct3D 12のフェンスを共有フェンスとしてDirect3D 11側で開いて行います。
---
`BeginCompute`は、Direct3D 11のコマンドを送出したうえでDirect3D 12側を待機させ、`EndCompute`は、Direct3D 12側の完了をDirect3D 11側で待ちます。通常のフレーム処理では、CPUへの画素読み戻しとCPUからの画素再転送を行いません。
## 改善
Direct3D 12デバイスの取得や共有リソースの作成に失敗した場合は、`TryCreate`が`null`を返し、エフェクトを適用せず入力映像を表示します。
### 1. スプラットのグループ共有メモリによるタイル化
### 3. カスタムシェーダーによる合成
スプラットは、各画素の色を輸送写像の移動先へ双線形の4点で加算する処理です。分散が0%のときは1画素につき4点×4成分で16回、分散が有効なときは色ごとに移動先が異なるため3色×4点×2成分で24回の大域アトミック加算を発行していました。分散が有効な3840×2160では1フレームあたり199065600回に達します。
`CausticTransportCustomEffect`は、`[CustomEffect(2)]`の2入力エフェクトです。入力0は元映像、入力1は輸送した光の像です。ピクセルシェーダー`CausticTransport.hlsl`の`main`は、`amount`が0以下のとき元映像をそのまま返し、そうでないときは光の像のRGBをアルファでクランプし、`lerp(source, caustic, amount)`で合成します。
段ごとに外して測ると、不透明な高周波の素材、3840×2160、標準品質、分散30%の1フレーム100.79msのうち、スプラットが88msを占めていました。輸送反復は1.4ms、解決とクリアは測定の変動に埋もれる水準です。スプラットの内訳は、変位のサンプリングを含む演算が8ms、残りが大域アトミック加算です。別の測定では、加算16回になる分散0%の経路が76.06ms、24回になる分散30%の経路が103.93msであり、処理時間は加算の回数にほぼ比例していました。
定数バッファーは`Amount`と3つの詰め物で16バイトです。`MapInputRectsToOutputRect`は入力0の矩形をそのまま出力矩形とし、出力範囲を拡張しません。輸送は入力の範囲内に収まるため、素材より大きな出力範囲を必要としません。
8×8画素のスレッドグループごとに、書き込み先の範囲を`InterlockedMin`と`InterlockedMax`で求め、範囲が10×10画素のタイルに収まる場合はグループ共有メモリへ加算してから、値が0でないセルだけを大域へ1回ずつ反映するようにしました。
シェーダーリソース: `pack://application:,,,/CausticTransport;component/Shaders/CausticTransport.cso`(ps_5_0、`ShaderResourceUri.Get`が生成)
- 隣り合う画素の移動先は重なるため、グループ内で合算した後の大域アトミック加算は、収まる場合に1画素あたり16回または24回から数回へ減ります。範囲がタイルに収まらない場合は従来どおり大域へ直接加算します。判定はグループ内で一様です。
- 分散が有効なときは色ごとに移動先が離れるため、色ごとの3段に分け、各段で範囲の算出とタイルの集約を行います。
- グループ共有メモリは10×10画素×4成分の400要素で1.6KBです。タイルのクリアと反映は、実際に使う範囲だけを走査します。
- グループ共有メモリを使うシェーダーは、グループ内のすべてのスレッドが同期に到達する必要があります。ComputeSharpが生成するシェーダーの入口は`For`へ渡した反復数を上限としてスレッドを間引くため、画像の寸法のままディスパッチすると端のグループの一部のスレッドが同期に到達しません。この状態ではGPUが停止し、デバイスが失われることを16×12の入力で確認しました。スプラットのディスパッチ範囲は`CausticTransportSettings.GetSplatDispatchSize`で8の倍数へ切り上げ、画像の範囲の判定をシェーダー内へ移しています。切り上げで増えたスレッドは範囲外として何も加算しません。
### 4. エフェクト定義とパラメータ
### 2. 性能
`CausticTransportEffect`は、YMM4の映像エフェクトとして宣言されます。
検証ハーネス、Releaseビルドによる実測値です。GPUはIntel Iris Xe Graphicsです。素材は検証ハーネスが生成するテスト画像で、外周5%が透明です。共有テクスチャの経路で20フレームの平均を1標本として12標本を取得し、その中央値を1回の実行の値とします。3つのリビジョンの実行ファイルを別々に用意し、交互に3回ずつ実行した最小値を記載します。この環境は連続測定で温度が上がると同じ実行ファイルでも33%遅くなるため、交互実行で熱状態の影響をそろえています。品質は高品質、集光度50%、光源サイズ50%、分散30%、面粗さ20%です。
`[VideoEffect]`属性は以下のパラメーターで宣言されます。
- 表示名: `Texts.CausticTransport`(ローカライズキー、日本語では「光輸送結像」)
- カテゴリー: `VideoEffectCategories.Filtering`・`VideoEffectCategories.Decoration`
- 検索タグ: `TagCaustic`・`TagLight`・`TagTransition`
- `IsAviUtlSupported = false`によりAviUtl向けEXO出力は非対応
- `ResourceType = typeof(Texts)`でローカライズリソースを指定
公開プロパティは以下のとおりです。基本項目は「基本」グループ、光源項目は「光源」グループ、光学項目は「光学」グループに属します。
| プロパティ | 型 | デフォルト | 内部範囲 | アニメーション |
|---|---|---|---|---|
| `Amount` | `Animation` | 100 | 0〜100 | あり |
| `Focus` | `Animation` | 50 | 0〜100 | あり |
| `Quality` | `CausticTransportQuality` | `High` | — | なし |
| `LightShape` | `CausticLightShape` | `Plane` | — | なし |
| `ApertureSize` | `Animation` | 50 | 5〜100 | あり |
| `Dispersion` | `Animation` | 30 | 0〜100 | あり |
| `Roughness` | `Animation` | 20 | 0〜100 | あり |
| `Seed` | `int` | 0 | 0〜int.MaxValue | なし |
`GetAnimatables`は`Amount`・`Focus`・`ApertureSize`・`Dispersion`・`Roughness`を返します。`Seed`は負値を代入すると0へ丸めます。
`CreateExoVideoFilters`は空のシーケンスを返します(EXO非対応)。`CreateVideoEffect`は映像処理用のインスタンスを生成します。エフェクトを最初に生成したときに、更新確認を一度だけ開始します。
### 5. フレームごとの更新
各フレームでYMM4の`EffectDescription`からフレーム位置、アイテム長、FPSを取得し、アニメーション値を評価します。値をパイプラインが前提とする範囲へ制限してから転送します。
| パラメータ | 変換 |
|---|---|
| `Amount` | `value / 100` をカスタムシェーダーの`Amount`へ |
| `Focus` | `value / 100` を0〜1へクランプ |
| `ApertureSize` | `value / 100` を0.05〜1へクランプ |
| `Dispersion` | `value / 100` を0〜1へクランプ |
| `Roughness` | `value / 100` を0〜1へクランプ |
| `LightShape` | 列挙値を整数の形状番号へ |
| `Quality` | 列挙値をそのまま |
| `Seed` | 0以上へクランプ |
強さが0以下のときは輸送を行わず、入力映像をそのまま出力します。集光度が1以上のときはカスタムシェーダーの`Amount`を0にし、入力映像をそのまま出力します。入力の範囲が有限でない場合や画素数が上限を超える場合も、入力映像を表示します。
パイプライン側では、集光度から移動量`1 − 集光度`を求め、面粗さから散乱量`面粗さ × 0.5`を求め、分散から色ごとの移動量の広がり`分散 × 0.35`を求めます。
### 6. 品質設定
品質は、輸送格子の解像度、輸送写像の反復回数、Jacobi反復回数をまとめて切り替えます。
| 品質 | 格子解像度 | 輸送反復 | Jacobi反復 |
| 項目 | v1.0.0 | 修正だけを適用 | v1.0.1 |
|---|---:|---:|---:|
| 標準 | 128 | 4回 | 12回 |
| 高品質 | 192 | 6回 | 16回 |
| 最高品質 | 256 | 8回 | 20回 |
| 1024×1000 面光源の1フレーム | 13.71ms | 13.94ms | 9.09ms |
| 1024×1000 円光源の1フレーム | 14.10ms | 13.77ms | 8.63ms |
| 1920×1080 面光源の1フレーム | 例外 | 20.54ms | 13.87ms |
| 1920×1080 円光源の1フレーム | 例外 | 20.64ms | 13.34ms |
| 3840×2160 面光源の1フレーム | 例外 | 74.50ms | 44.71ms |
| 3840×2160 円光源の1フレーム | 例外 | 76.86ms | 45.13ms |
格子解像度は長辺のセル数です。短辺のセル数は入力映像の縦横比に合わせ、最小4セルとします。
v1.0.0は画素数が1048560を超えると例外で停止するため、1920×1080と3840×2160を測定できません。検証ハーネスも1024×1000の測定を終えた直後に同じ例外で停止します。1024×1000でv1.0.0と修正だけを適用した状態が同水準であることから、この短縮はタイル化によるものです。倍率は1024×1000で1.53倍から1.60倍、1920×1080で1.48倍から1.55倍、3840×2160で1.67倍から1.70倍です。
### 7. ローカライズ
倍率は素材によって変わります。移動先の範囲がタイルに収まる割合が高いほど大域アトミック加算の削減が大きくなるためです。全画素が不透明な高周波の素材では、テストプロジェクトへ一時的に追加した同じ12標本の中央値の計測で、1920×1080が2.14倍から2.25倍、3840×2160が2.06倍から2.46倍でした。この計測は交互実行ではないため、熱状態の影響を含みます。
`Texts`クラスは`[AutoGenLocalizer]`属性を持つ`partial`クラスとして宣言されます。
`YukkuriMovieMaker.Generator`のソースジェネレーターが`Texts.csv`を処理し、各ロケールのリソースファイルを自動生成します。
### 3. 等価性の検証
対応リソース: 日本語(`ja-jp`)・英語(`en-us`)・中国語簡体字(`zh-cn`)・中国語繁体字(`zh-tw`)・韓国語(`ko-kr`)・スペイン語(`es-es`)・アラビア語(`ar-sa`)・インドネシア語(`id-id`)
- タイル化の前後の出力は全画素で一致します。6種類の寸法、光源形状4種類、集光度3水準、分散3水準、光源サイズ、面粗さ、品質3段階を組み合わせた3276条件について、出力全画素のFNV-1a 64のハッシュを比較し、すべて一致しました。
- 一致する理由は、加える値が従来と同じ丸めを経た整数であり、整数の加算が結合的かつ可換であることです。集約の順序によらず合計は同一になります。値が0の加算を省く箇所も合計を変えません。浮動小数点の加算は導入していません。
- 出力の画素値はv1.0.0とは完全には一致しません。積算バッファーの型を変えたことで固定小数点の倍率が変わるためです。倍率は1024×1000で1398から2796、3840×2160で256から345へ上がるため、量子化は細かくなる方向です。
- xUnitテスト57件がすべて成功し、クリーンビルドの警告は0です。スレッドグループの境界に合わない5×3、9×1、1×9、17×15の入力を処理する検証と、ディスパッチ範囲が8の倍数へ切り上がる検証を追加しました。
主なローカライズキーは以下のとおりです。
### 4. 採用しなかった構成
| キー | ja-jp |
同じ試みを繰り返さないように、測定して採用しなかった構成を記録します。いずれも3840×2160の1フレームの実測値で、素材は全画素が不透明な高周波の画像です。タイル寸法の比較は集光度50%と集光度90%の2条件で、20フレームの平均を3回取った最小値です。スレッドグループの比較はタイル化を行う前の実装での10フレームの平均です。
| 構成 | 測定結果 |
|---|---|
| `CausticTransport` | 光輸送結像 |
| `BasicGroup` | 基本 |
| `LightGroup` | 光源 |
| `OpticsGroup` | 光学 |
| `Amount` | 強さ |
| `Focus` | 集光度 |
| `Quality` | 品質 |
| `LightShape` | 光源形状 |
| `ApertureSize` | 光源サイズ |
| `Dispersion` | 分散 |
| `Roughness` | 面粗さ |
| `Seed` | シード |
| `ShapePlane` | 面 |
| `ShapeCircle` | 円 |
| `ShapeHorizontalSlit` | 横スリット |
| `ShapeVerticalSlit` | 縦スリット |
| `QualityBalanced` | 標準 |
| `QualityHigh` | 高品質 |
| `QualityUltra` | 最高品質 |
| `TagCaustic` | 集光 |
| `TagLight` | 光 |
| `TagTransition` | 遷移 |
| `UpdateAvailableMessage` | 新しいバージョン {0} が公開されています。 |
| スレッドグループを16×16へ拡大 | 91.41msから97.01msへ悪化 |
| タイルを8×8 | 集光度50%で42.36ms、集光度90%で87.16ms |
| タイルを9×9 | 集光度50%で37.70ms、集光度90%で41.92ms |
| タイルを12×12 | 集光度50%で38.95ms、集光度90%で41.62ms |
| タイルを16×16 | 集光度50%で45.23ms、集光度90%で49.81ms |
採用した10×10は集光度50%で36.31ms、集光度90%で39.75msです。8×8では、移動量が小さいときの書き込み先の範囲が8×8画素の移動と双線形の1画素で9×9画素になり、タイルに収まらないため集約されません。16×16ではグループ共有メモリが4KBになり、占有率が下がります。
### 5. 検証ハーネスの測定手法の変更
共有テクスチャの経路の測定を、1280×720で品質3段階を20フレームの平均1回で測る形から、1024×1000と1920×1080と3840×2160の3寸法について面光源と円光源を、20フレームの平均を1標本とする12標本の中央値で測る形へ変更しました。従来の1回の平均は、GPUのクロック状態と温度の影響を受け、同じ実行ファイルでも実行ごとに33%ばらつくことがあります。本リリースの性能表はこの手法で測定した値です。
+6 -1
ファイルの表示
@@ -1,5 +1,5 @@
========================================
光輸送結像 for YMM4 v1.0.0
光輸送結像 for YMM4 v1.0.1
========================================
YukkuriMovieMaker4上で動作する、現在のフレームの明るさを光の分布として
輸送格子へ集め、選択した光源形状へ広げた光を元映像へ結像させる映像
@@ -30,6 +30,11 @@ YukkuriMovieMaker4上で動作する、現在のフレームの明るさを光
- 処理対象: 現在のフレームだけを処理します。履歴フレーム、外部画像、
深度情報、学習済みモデルは使用しません。
- 対応する大きさ: 処理する範囲の辺が8192画素以下、かつ総画素数が
11184810以下の入力に対応します。3840×2160と4096×2160はこの範囲に
含まれます。範囲を超える入力には、エフェクトを適用せず入力映像を
表示します。
- 処理負荷: 入力映像の画素数に応じて処理量とGPUメモリ使用量が増えます。
最高品質は格子解像度と反復回数が最も多いため、高品質と標準より
処理負荷が高くなります。
+42 -18
ファイルの表示
@@ -42,25 +42,21 @@ foreach (var quality in new[] { CausticTransportQuality.Balanced, CausticTranspo
{
var device = ComputeSharp.GraphicsDevice.GetDefault();
using var sourceTexture = ComputeSharp.Interop.InteropServices.AllocateSharedReadWriteTexture2D<ComputeSharp.Bgra32, ComputeSharp.Float4>(device, width, height);
using var outputTexture = ComputeSharp.Interop.InteropServices.AllocateSharedReadWriteTexture2D<ComputeSharp.Bgra32, ComputeSharp.Float4>(device, width, height);
var pixels = new ComputeSharp.Bgra32[source.Length];
for (var index = 0; index < source.Length; index++)
pixels[index].PackedValue = unchecked((uint)source[index]);
sourceTexture.CopyFrom(pixels);
foreach (var quality in new[] { CausticTransportQuality.Balanced, CausticTransportQuality.High, CausticTransportQuality.Ultra })
foreach (var (benchWidth, benchHeight) in new[] { (1024, 1000), (1920, 1080), (3840, 2160) })
{
var parameters = new CausticTransportPipeline.Parameters(1, quality, 0.5f, 0.5f, 0.3f, 0.2f, 7);
pipeline.Process(sourceTexture, outputTexture, width, height, in parameters);
pipeline.WaitForCompletion();
var stopwatch = Stopwatch.StartNew();
const int frames = 20;
for (var frame = 0; frame < frames; frame++)
pipeline.Process(sourceTexture, outputTexture, width, height, in parameters);
pipeline.WaitForCompletion();
stopwatch.Stop();
outputTexture.CopyTo(pixels);
Console.WriteLine($"shared {quality}: {stopwatch.Elapsed.TotalMilliseconds / frames:F2} ms/frame ({width}x{height})");
using var sourceTexture = ComputeSharp.Interop.InteropServices.AllocateSharedReadWriteTexture2D<ComputeSharp.Bgra32, ComputeSharp.Float4>(device, benchWidth, benchHeight);
using var outputTexture = ComputeSharp.Interop.InteropServices.AllocateSharedReadWriteTexture2D<ComputeSharp.Bgra32, ComputeSharp.Float4>(device, benchWidth, benchHeight);
var benchSource = CreateTestImage(benchWidth, benchHeight);
var pixels = new ComputeSharp.Bgra32[benchSource.Length];
for (var index = 0; index < benchSource.Length; index++)
pixels[index].PackedValue = unchecked((uint)benchSource[index]);
sourceTexture.CopyFrom(pixels);
foreach (var shape in new[] { 0, 1 })
{
var parameters = new CausticTransportPipeline.Parameters(shape, CausticTransportQuality.High, 0.5f, 0.5f, 0.3f, 0.2f, 7);
var median = MeasureMedian(pipeline, sourceTexture, outputTexture, benchWidth, benchHeight, in parameters);
Console.WriteLine($"shared shape={shape}: {median:F2} ms/frame ({benchWidth}x{benchHeight})");
}
}
}
@@ -80,6 +76,34 @@ WriteBmp(Path.Combine(outputDirectory, "source.bmp"), source, width, height);
Console.WriteLine($"images written to {outputDirectory}");
return 0;
static double MeasureMedian(
CausticTransportPipeline pipeline,
ReadWriteTexture2D<Bgra32, Float4> source,
ReadWriteTexture2D<Bgra32, Float4> destination,
int width,
int height,
in CausticTransportPipeline.Parameters parameters)
{
for (var warmup = 0; warmup < 5; warmup++)
pipeline.Process(source, destination, width, height, in parameters);
pipeline.WaitForCompletion();
var samples = new double[12];
for (var sample = 0; sample < samples.Length; sample++)
{
const int frames = 20;
var stopwatch = Stopwatch.StartNew();
for (var frame = 0; frame < frames; frame++)
pipeline.Process(source, destination, width, height, in parameters);
pipeline.WaitForCompletion();
stopwatch.Stop();
samples[sample] = stopwatch.Elapsed.TotalMilliseconds / frames;
}
Array.Sort(samples);
return (samples[5] + samples[6]) * 0.5;
}
static int[] CreateTestImage(int width, int height)
{
var pixels = new int[width * height];
+131 -2
ファイルの表示
@@ -91,8 +91,79 @@ public sealed class CausticTransportEffectTests
public void ColorFixedScaleStaysWithinSafeBounds()
{
Assert.Equal(65536, CausticTransportSettings.GetColorFixedScale(64));
Assert.Equal(256, CausticTransportSettings.GetColorFixedScale(3840 * 2160));
Assert.True((long)CausticTransportSettings.GetColorFixedScale(1920 * 1080) * 1920 * 1080 < int.MaxValue * 1.01);
Assert.Equal(345, CausticTransportSettings.GetColorFixedScale(3840 * 2160));
Assert.True((double)CausticTransportSettings.GetColorFixedScale(3840 * 2160) * 3840 * 2160 <= uint.MaxValue);
}
[Theory]
[InlineData(1, 8)]
[InlineData(8, 8)]
[InlineData(9, 16)]
[InlineData(1080, 1080)]
[InlineData(2730, 2736)]
public void SplatDispatchSizeCoversFrameInWholeThreadGroups(int size, int expected)
{
var dispatch = CausticTransportSettings.GetSplatDispatchSize(size);
Assert.Equal(expected, dispatch);
Assert.Equal(0, dispatch % CausticTransportSettings.SplatGroupSize);
Assert.InRange(dispatch - size, 0, CausticTransportSettings.SplatGroupSize - 1);
}
[Theory]
[InlineData(5, 3)]
[InlineData(9, 1)]
[InlineData(1, 9)]
[InlineData(17, 15)]
public void FramesNotAlignedToThreadGroupsAreProcessed(int width, int height)
{
using var pipeline = CausticTransportPipeline.TryCreate();
if (pipeline is null)
{
Assert.Skip("Direct3D 12 is unavailable.");
return;
}
var source = CreateSourcePixels(width, height);
var destination = new int[source.Length];
var parameters = new CausticTransportPipeline.Parameters(1, CausticTransportQuality.Balanced, 1f, 0.5f, 0.3f, 0.2f, 5);
pipeline.Process(source, destination, width, height, in parameters);
for (var index = 0; index < source.Length; index++)
{
for (var shift = 0; shift < 32; shift += 8)
{
var expected = (source[index] >> shift) & 255;
var actual = (destination[index] >> shift) & 255;
Assert.InRange(actual, Math.Max(expected - 1, 0), Math.Min(expected + 1, 255));
}
}
}
[Fact]
public void MaximumPixelCountKeepsColorAccumulationWithinUnsignedRange()
{
var scale = CausticTransportSettings.GetColorFixedScale(CausticTransportSettings.MaximumPixelCount);
Assert.Equal(CausticTransportSettings.MinimumColorFixedScale, scale);
Assert.True((double)CausticTransportSettings.MaximumPixelCount * scale <= uint.MaxValue);
Assert.True(CausticTransportSettings.MaximumPixelCount >= 4096 * 2160);
}
[Theory]
[InlineData(1920d, 1080d, true)]
[InlineData(3840d, 2160d, true)]
[InlineData(4096d, 2160d, true)]
[InlineData(8192d, 1365d, true)]
[InlineData(8193d, 1365d, false)]
[InlineData(4096d, 2731d, false)]
[InlineData(0d, 1080d, false)]
[InlineData(double.NaN, 1080d, false)]
[InlineData(double.PositiveInfinity, 1080d, false)]
public void SupportedSizeCoversUpTo4KAndRejectsLarger(double width, double height, bool expected)
{
Assert.Equal(expected, CausticTransportSettings.IsSupportedSize(width, height));
}
[Theory]
@@ -150,6 +221,64 @@ public sealed class CausticTransportEffectTests
Assert.Equal(first, second);
}
[Theory]
[InlineData(1920, 1080)]
[InlineData(3840, 2160)]
[InlineData(4096, 2160)]
[InlineData(4096, 2730)]
public void LargeFramesAreProcessedWithoutDispatchGroupOverflow(int width, int height)
{
Assert.True(CausticTransportSettings.IsSupportedSize(width, height));
using var pipeline = CausticTransportPipeline.TryCreate();
if (pipeline is null)
{
Assert.Skip("Direct3D 12 is unavailable.");
return;
}
var source = CreateSourcePixels(width, height);
var destination = new int[source.Length];
var parameters = new CausticTransportPipeline.Parameters(0, CausticTransportQuality.Balanced, 0.5f, 0.5f, 0.3f, 0.2f, 5);
pipeline.Process(source, destination, width, height, in parameters);
Assert.Contains(destination, pixel => pixel != 0);
}
[Theory]
[InlineData(3840, 2160)]
[InlineData(4096, 2730)]
public void LargeFrameConservesMassDuringTransport(int width, int height)
{
using var pipeline = CausticTransportPipeline.TryCreate();
if (pipeline is null)
{
Assert.Skip("Direct3D 12 is unavailable.");
return;
}
var source = new int[width * height];
for (var index = 0; index < source.Length; index++)
{
var value = 16 + (index * 7) % 48;
source[index] = 64 << 24 | value << 16 | value << 8 | value;
}
var destination = new int[source.Length];
var parameters = new CausticTransportPipeline.Parameters(0, CausticTransportQuality.Balanced, 0.5f, 0.5f, 0f, 0f, 0);
pipeline.Process(source, destination, width, height, in parameters);
double sourceSum = 0;
double destinationSum = 0;
foreach (var pixel in source)
sourceSum += (pixel >> 24) & 255;
foreach (var pixel in destination)
destinationSum += (pixel >> 24) & 255;
Assert.InRange(destinationSum, sourceSum * 0.98, sourceSum * 1.02);
}
[Fact]
public void OutputAlphaStaysPremultipliedAndBounded()
{
+1 -1
ファイルの表示
@@ -5,7 +5,7 @@
<UseWPF>true</UseWPF>
<ImplicitUsings>enable</ImplicitUsings>
<Nullable>enable</Nullable>
<Version>1.0.0</Version>
<Version>1.0.1</Version>
<Platforms>AnyCPU;x64</Platforms>
<PlatformTarget>x64</PlatformTarget>
<AllowUnsafeBlocks>True</AllowUnsafeBlocks>
+2 -5
ファイルの表示
@@ -68,11 +68,8 @@ internal sealed class CausticTransportEffectProcessor : VideoEffectProcessorBase
var bounds = _devices.DeviceContext.GetImageLocalBounds(input);
var widthValue = Math.Ceiling((double)bounds.Right - bounds.Left);
var heightValue = Math.Ceiling((double)bounds.Bottom - bounds.Top);
if (!double.IsFinite(widthValue) || !double.IsFinite(heightValue) ||
!float.IsFinite(bounds.Left) || !float.IsFinite(bounds.Top) ||
widthValue <= 0d || heightValue <= 0d ||
widthValue > int.MaxValue || heightValue > int.MaxValue ||
widthValue * heightValue > int.MaxValue)
if (!float.IsFinite(bounds.Left) || !float.IsFinite(bounds.Top) ||
!CausticTransportSettings.IsSupportedSize(widthValue, heightValue))
{
_effect.Amount = 0f;
_isFirst = true;
+153 -99
ファイルの表示
@@ -2,42 +2,6 @@ using ComputeSharp;
namespace CausticTransport;
[ThreadGroupSize(DefaultThreadGroupSizes.X)]
[GeneratedComputeShaderDescriptor]
internal readonly partial struct ClearIntShader(
ReadWriteBuffer<int> values,
int length) : IComputeShader
{
private readonly ReadWriteBuffer<int> values = values;
private readonly int length = length;
public void Execute()
{
var index = ThreadIds.X;
if (index >= length)
return;
values[index] = 0;
}
}
[ThreadGroupSize(DefaultThreadGroupSizes.X)]
[GeneratedComputeShaderDescriptor]
internal readonly partial struct ClearFloatShader(
ReadWriteBuffer<float> values,
int length) : IComputeShader
{
private readonly ReadWriteBuffer<float> values = values;
private readonly int length = length;
public void Execute()
{
var index = ThreadIds.X;
if (index >= length)
return;
values[index] = 0f;
}
}
[ThreadGroupSize(DefaultThreadGroupSizes.XY)]
[GeneratedComputeShaderDescriptor]
internal readonly partial struct InitializeDisplacementShader(
@@ -503,12 +467,12 @@ internal readonly partial struct UpdateDisplacementShader(
}
}
[ThreadGroupSize(DefaultThreadGroupSizes.XY)]
[ThreadGroupSize(CausticTransportSettings.SplatGroupSize, CausticTransportSettings.SplatGroupSize, 1)]
[GeneratedComputeShaderDescriptor]
internal readonly partial struct SplatShader(
ReadWriteTexture2D<Bgra32, Float4> source,
ReadWriteBuffer<Float2> displacement,
ReadWriteBuffer<int> accumulator,
ReadWriteBuffer<uint> accumulator,
int width,
int height,
int gridWidth,
@@ -521,7 +485,7 @@ internal readonly partial struct SplatShader(
{
private readonly ReadWriteTexture2D<Bgra32, Float4> source = source;
private readonly ReadWriteBuffer<Float2> displacement = displacement;
private readonly ReadWriteBuffer<int> accumulator = accumulator;
private readonly ReadWriteBuffer<uint> accumulator = accumulator;
private readonly int width = width;
private readonly int height = height;
private readonly int gridWidth = gridWidth;
@@ -532,33 +496,109 @@ internal readonly partial struct SplatShader(
private readonly int seed = seed;
private readonly float colorScale = colorScale;
[GroupShared(CausticTransportSettings.SplatTileLength)]
private static readonly uint[] tile = null!;
[GroupShared(4)]
private static readonly int[] extent = null!;
public void Execute()
{
var threadIndex = GroupIds.Index;
var threadCount = GroupSize.Count;
var x = ThreadIds.X;
var y = ThreadIds.Y;
if (x >= width || y >= height)
return;
var pixel = source[new Int2(Hlsl.Min(x, width - 1), Hlsl.Min(y, height - 1))];
var active = x < width && y < height &&
(pixel.X > 0f || pixel.Y > 0f || pixel.Z > 0f || pixel.W > 0f);
var pixel = source[ThreadIds.XY];
if (pixel.X <= 0f && pixel.Y <= 0f && pixel.Z <= 0f && pixel.W <= 0f)
return;
var transport = new Float2(0f, 0f);
if (active)
transport = SampleDisplacement(x, y);
var transport = SampleDisplacement(x, y);
var baseX = x + 0.5f;
var baseY = y + 0.5f;
if (dispersion <= 0f)
var spread = dispersion * 0.35f;
var phaseCount = dispersion <= 0f ? 1 : 3;
for (var phase = 0; phase < phaseCount; phase++)
{
SplatAll(baseX + transport.X * movement, baseY + transport.Y * movement, pixel);
}
else
{
var spread = dispersion * 0.35f;
var movementRed = Hlsl.Saturate(movement * (1f + spread));
var movementBlue = Hlsl.Saturate(movement * (1f - spread));
var alphaShare = pixel.W * (1f / 3f);
SplatChannel(baseX + transport.X * movementRed, baseY + transport.Y * movementRed, 0, pixel.X, alphaShare);
SplatChannel(baseX + transport.X * movement, baseY + transport.Y * movement, 1, pixel.Y, alphaShare);
SplatChannel(baseX + transport.X * movementBlue, baseY + transport.Y * movementBlue, 2, pixel.Z, alphaShare);
var phaseMovement = movement;
var contribution = pixel;
if (dispersion > 0f)
{
var alphaShare = pixel.W * (1f / 3f);
if (phase == 0)
{
phaseMovement = Hlsl.Saturate(movement * (1f + spread));
contribution = new Float4(pixel.X, 0f, 0f, alphaShare);
}
else if (phase == 1)
{
contribution = new Float4(0f, pixel.Y, 0f, alphaShare);
}
else
{
phaseMovement = Hlsl.Saturate(movement * (1f - spread));
contribution = new Float4(0f, 0f, pixel.Z, alphaShare);
}
}
var px = Hlsl.Clamp(baseX + transport.X * phaseMovement, 0.5f, width - 0.5f) - 0.5f;
var py = Hlsl.Clamp(baseY + transport.Y * phaseMovement, 0.5f, height - 0.5f) - 0.5f;
var ix0 = (int)px;
var iy0 = (int)py;
var wx = px - ix0;
var wy = py - iy0;
var ix1 = Hlsl.Min(ix0 + 1, width - 1);
var iy1 = Hlsl.Min(iy0 + 1, height - 1);
if (threadIndex == 0)
{
extent[0] = width;
extent[1] = height;
extent[2] = -1;
extent[3] = -1;
}
Hlsl.GroupMemoryBarrierWithGroupSync();
if (active)
{
Hlsl.InterlockedMin(ref extent[0], ix0);
Hlsl.InterlockedMin(ref extent[1], iy0);
Hlsl.InterlockedMax(ref extent[2], ix1);
Hlsl.InterlockedMax(ref extent[3], iy1);
}
Hlsl.GroupMemoryBarrierWithGroupSync();
var originX = extent[0];
var originY = extent[1];
var spanX = extent[2] - originX + 1;
var spanY = extent[3] - originY + 1;
var useTile = spanX >= 1 &&
spanX <= CausticTransportSettings.SplatTileSize &&
spanY <= CausticTransportSettings.SplatTileSize;
if (useTile)
ClearTile(spanX, spanY, threadIndex, threadCount);
Hlsl.GroupMemoryBarrierWithGroupSync();
if (active)
{
if (useTile)
{
AddTileTap(TileOffset(ix0 - originX, iy0 - originY), contribution, (1f - wx) * (1f - wy));
AddTileTap(TileOffset(ix1 - originX, iy0 - originY), contribution, wx * (1f - wy));
AddTileTap(TileOffset(ix0 - originX, iy1 - originY), contribution, (1f - wx) * wy);
AddTileTap(TileOffset(ix1 - originX, iy1 - originY), contribution, wx * wy);
}
else
{
AddGlobalTap((iy0 * width + ix0) * 4, contribution, (1f - wx) * (1f - wy));
AddGlobalTap((iy0 * width + ix1) * 4, contribution, wx * (1f - wy));
AddGlobalTap((iy1 * width + ix0) * 4, contribution, (1f - wx) * wy);
AddGlobalTap((iy1 * width + ix1) * 4, contribution, wx * wy);
}
}
Hlsl.GroupMemoryBarrierWithGroupSync();
if (useTile)
FlushTile(originX, originY, spanX, spanY, threadIndex, threadCount);
}
}
@@ -592,54 +632,68 @@ internal readonly partial struct SplatShader(
return value;
}
private void SplatAll(float x, float y, Float4 value)
{
var px = Hlsl.Clamp(x, 0.5f, width - 0.5f) - 0.5f;
var py = Hlsl.Clamp(y, 0.5f, height - 0.5f) - 0.5f;
var ix0 = (int)px;
var iy0 = (int)py;
var wx = px - ix0;
var wy = py - iy0;
var ix1 = Hlsl.Min(ix0 + 1, width - 1);
var iy1 = Hlsl.Min(iy0 + 1, height - 1);
private int TileOffset(int tileX, int tileY)
=> (tileY * CausticTransportSettings.SplatTileSize + tileX) * 4;
SplatAllTap((iy0 * width + ix0) * 4, value, (1f - wx) * (1f - wy));
SplatAllTap((iy0 * width + ix1) * 4, value, wx * (1f - wy));
SplatAllTap((iy1 * width + ix0) * 4, value, (1f - wx) * wy);
SplatAllTap((iy1 * width + ix1) * 4, value, wx * wy);
private void ClearTile(int spanX, int spanY, int threadIndex, int threadCount)
{
var cellCount = spanX * spanY * 4;
for (var index = threadIndex; index < cellCount; index += threadCount)
{
var cell = index / 4;
var channel = index - cell * 4;
var tileY = cell / spanX;
var tileX = cell - tileY * spanX;
tile[TileOffset(tileX, tileY) + channel] = 0;
}
}
private void SplatAllTap(int index4, Float4 value, float weight)
private void FlushTile(int originX, int originY, int spanX, int spanY, int threadIndex, int threadCount)
{
var cellCount = spanX * spanY * 4;
for (var index = threadIndex; index < cellCount; index += threadCount)
{
var cell = index / 4;
var channel = index - cell * 4;
var tileY = cell / spanX;
var tileX = cell - tileY * spanX;
var amount = tile[TileOffset(tileX, tileY) + channel];
if (amount == 0)
continue;
Hlsl.InterlockedAdd(ref accumulator[((originY + tileY) * width + originX + tileX) * 4 + channel], amount);
}
}
private void AddTileTap(int index4, Float4 value, float weight)
{
var scaled = weight * colorScale;
Hlsl.InterlockedAdd(ref accumulator[index4], (int)Hlsl.Round(value.X * scaled));
Hlsl.InterlockedAdd(ref accumulator[index4 + 1], (int)Hlsl.Round(value.Y * scaled));
Hlsl.InterlockedAdd(ref accumulator[index4 + 2], (int)Hlsl.Round(value.Z * scaled));
Hlsl.InterlockedAdd(ref accumulator[index4 + 3], (int)Hlsl.Round(value.W * scaled));
AddTile(index4, value.X * scaled);
AddTile(index4 + 1, value.Y * scaled);
AddTile(index4 + 2, value.Z * scaled);
AddTile(index4 + 3, value.W * scaled);
}
private void SplatChannel(float x, float y, int channel, float value, float alphaShare)
private void AddTile(int index, float value)
{
var px = Hlsl.Clamp(x, 0.5f, width - 0.5f) - 0.5f;
var py = Hlsl.Clamp(y, 0.5f, height - 0.5f) - 0.5f;
var ix0 = (int)px;
var iy0 = (int)py;
var wx = px - ix0;
var wy = py - iy0;
var ix1 = Hlsl.Min(ix0 + 1, width - 1);
var iy1 = Hlsl.Min(iy0 + 1, height - 1);
SplatChannelTap((iy0 * width + ix0) * 4, channel, value, alphaShare, (1f - wx) * (1f - wy));
SplatChannelTap((iy0 * width + ix1) * 4, channel, value, alphaShare, wx * (1f - wy));
SplatChannelTap((iy1 * width + ix0) * 4, channel, value, alphaShare, (1f - wx) * wy);
SplatChannelTap((iy1 * width + ix1) * 4, channel, value, alphaShare, wx * wy);
var amount = (uint)Hlsl.Round(value);
if (amount != 0)
Hlsl.InterlockedAdd(ref tile[index], amount);
}
private void SplatChannelTap(int index4, int channel, float value, float alphaShare, float weight)
private void AddGlobalTap(int index4, Float4 value, float weight)
{
var scaled = weight * colorScale;
Hlsl.InterlockedAdd(ref accumulator[index4 + channel], (int)Hlsl.Round(value * scaled));
Hlsl.InterlockedAdd(ref accumulator[index4 + 3], (int)Hlsl.Round(alphaShare * scaled));
AddGlobal(index4, value.X * scaled);
AddGlobal(index4 + 1, value.Y * scaled);
AddGlobal(index4 + 2, value.Z * scaled);
AddGlobal(index4 + 3, value.W * scaled);
}
private void AddGlobal(int index, float value)
{
var amount = (uint)Hlsl.Round(value);
if (amount != 0)
Hlsl.InterlockedAdd(ref accumulator[index], amount);
}
private float Hash01(uint value)
@@ -656,13 +710,13 @@ internal readonly partial struct SplatShader(
[ThreadGroupSize(DefaultThreadGroupSizes.XY)]
[GeneratedComputeShaderDescriptor]
internal readonly partial struct ResolveShader(
ReadWriteBuffer<int> accumulator,
ReadWriteBuffer<uint> accumulator,
ReadWriteTexture2D<Bgra32, Float4> output,
int width,
int height,
float inverseColorScale) : IComputeShader
{
private readonly ReadWriteBuffer<int> accumulator = accumulator;
private readonly ReadWriteBuffer<uint> accumulator = accumulator;
private readonly ReadWriteTexture2D<Bgra32, Float4> output = output;
private readonly int width = width;
private readonly int height = height;
@@ -676,10 +730,10 @@ internal readonly partial struct ResolveShader(
return;
var index4 = (y * width + x) * 4;
var red = Hlsl.Max(accumulator[index4], 0) * inverseColorScale;
var green = Hlsl.Max(accumulator[index4 + 1], 0) * inverseColorScale;
var blue = Hlsl.Max(accumulator[index4 + 2], 0) * inverseColorScale;
var alpha = Hlsl.Max(accumulator[index4 + 3], 0) * inverseColorScale;
var red = accumulator[index4] * inverseColorScale;
var green = accumulator[index4 + 1] * inverseColorScale;
var blue = accumulator[index4 + 2] * inverseColorScale;
var alpha = accumulator[index4 + 3] * inverseColorScale;
var outAlpha = Hlsl.Min(alpha, 1f);
var scale = alpha > 1f ? outAlpha / alpha : 1f;
+22 -21
ファイルの表示
@@ -18,7 +18,7 @@ internal sealed class CausticTransportPipeline : IDisposable
private (int Width, int Height)[] _levelSizes = [];
private int _gridWidth;
private int _gridHeight;
private ReadWriteBuffer<int>? _accumulator;
private ReadWriteBuffer<uint>? _accumulator;
private int _accumulatorCapacity;
private ReadWriteTexture2D<Bgra32, Float4>? _packedSource;
private ReadWriteTexture2D<Bgra32, Float4>? _packedOutput;
@@ -37,7 +37,7 @@ internal sealed class CausticTransportPipeline : IDisposable
private void SynchronizeDevice()
{
using ComputeContext context = _device.CreateComputeContext();
context.For(1, new ClearIntShader(_syncBuffer, 1));
context.Clear(_syncBuffer);
}
public static CausticTransportPipeline? TryCreate()
@@ -135,7 +135,7 @@ internal sealed class CausticTransportPipeline : IDisposable
context.For(1, new NormalizeScaleShader(rowSums, scales, gridHeight, gridLength));
context.Barrier(scales);
context.For(gridWidth, gridHeight, new InitializeDisplacementShader(displacement, gridWidth, gridHeight, parameters.Shape, parameters.Aperture));
context.For(gridLength, new ClearIntShader(warpedFixed, gridLength));
context.Clear(warpedFixed);
context.Barrier(displacement);
context.Barrier(warpedFixed);
@@ -156,8 +156,7 @@ internal sealed class CausticTransportPipeline : IDisposable
context.Barrier(_residuals[level]);
}
var (coarsestWidth, coarsestHeight) = _levelSizes[coarsest];
context.For(coarsestWidth * coarsestHeight, new ClearFloatShader(_phiA[coarsest], coarsestWidth * coarsestHeight));
context.Clear(_phiA[coarsest]);
context.Barrier(_phiA[coarsest]);
for (var level = coarsest; level >= 0; level--)
@@ -182,24 +181,26 @@ internal sealed class CausticTransportPipeline : IDisposable
context.Barrier(displacement);
}
var accumulatorLength = pixelCount * 4;
context.For(accumulatorLength, new ClearIntShader(accumulator, accumulatorLength));
context.Clear(accumulator);
context.Barrier(accumulator);
var movement = 1f - parameters.Focus;
var jitterAmplitude = parameters.Roughness * CausticTransportSettings.JitterCellAmplitude;
context.For(width, height, new SplatShader(
source,
displacement,
accumulator,
width,
height,
gridWidth,
gridHeight,
movement,
parameters.Dispersion,
jitterAmplitude,
parameters.Seed,
colorScale));
context.For(
CausticTransportSettings.GetSplatDispatchSize(width),
CausticTransportSettings.GetSplatDispatchSize(height),
new SplatShader(
source,
displacement,
accumulator,
width,
height,
gridWidth,
gridHeight,
movement,
parameters.Dispersion,
jitterAmplitude,
parameters.Seed,
colorScale));
context.Barrier(accumulator);
context.For(width, height, new ResolveShader(accumulator, output, width, height, 1f / colorScale));
}
@@ -259,7 +260,7 @@ internal sealed class CausticTransportPipeline : IDisposable
SynchronizeDevice();
_accumulator.Dispose();
}
_accumulator = _device.AllocateReadWriteBuffer<int>(pixelCount * 4);
_accumulator = _device.AllocateReadWriteBuffer<uint>(pixelCount * 4);
_accumulatorCapacity = pixelCount;
}
+20 -1
ファイルの表示
@@ -8,6 +8,14 @@ internal static class CausticTransportSettings
public const float JitterCellAmplitude = 0.5f;
public const int CoarsestLevelSize = 16;
public const int MinimumGridSize = 4;
public const int MinimumColorFixedScale = 256;
public const int MaximumColorFixedScale = 65536;
public const double ColorFixedScaleMargin = 1.5;
public const int MaximumCanvasSize = 8192;
public const int MaximumPixelCount = (int)(uint.MaxValue / (ColorFixedScaleMargin * MinimumColorFixedScale));
public const int SplatGroupSize = 8;
public const int SplatTileSize = 10;
public const int SplatTileLength = SplatTileSize * SplatTileSize * 4;
public static QualitySettings GetQuality(CausticTransportQuality quality)
=> quality switch
@@ -41,8 +49,19 @@ internal static class CausticTransportSettings
public static (int Width, int Height) GetCoarserLevelSize(int width, int height)
=> (Math.Max((width + 1) / 2, MinimumGridSize), Math.Max((height + 1) / 2, MinimumGridSize));
public static int GetSplatDispatchSize(int size)
=> (size + SplatGroupSize - 1) / SplatGroupSize * SplatGroupSize;
public static bool IsSupportedSize(double width, double height)
=> width >= 1d && height >= 1d &&
width <= MaximumCanvasSize && height <= MaximumCanvasSize &&
width * height <= MaximumPixelCount;
public static int GetColorFixedScale(int pixelCount)
=> (int)Math.Clamp(int.MaxValue / (1.5 * Math.Max(pixelCount, 1)), 256d, 65536d);
=> (int)Math.Clamp(
uint.MaxValue / (ColorFixedScaleMargin * Math.Max(pixelCount, 1)),
MinimumColorFixedScale,
MaximumColorFixedScale);
internal readonly record struct QualitySettings(int GridResolution, int TransportIterations, int JacobiIterations);
}
+1
ファイルの表示
@@ -149,6 +149,7 @@ YukkuriMovieMaker4(YMM4)上で動作する、現在のフレームの明る
- AviUtl向けのEXO出力には対応していません。
- Direct3D 12デバイスを取得できない場合や、YMM4が使うDirect3D 11デバイスとの共有テクスチャおよび共有フェンスを作成できない場合は、エフェクトを適用せず入力映像を表示します。
- 解析対象は現在のフレームだけです。履歴フレーム、外部画像、深度情報、学習済みモデルは使用しません。
- 処理する範囲の辺が8192画素以下、かつ総画素数が11,184,810以下の入力に対応します。3840×2160と4096×2160はこの範囲に含まれます。範囲を超える入力には、エフェクトを適用せず入力映像を表示します。
- 処理量とGPUメモリ使用量は入力映像の画素数に応じて増えます。
---