コミットを比較
| 作成者 | SHA1 | 日付 | |
|---|---|---|---|
|
|
d1b0439611
|
||
|
|
30d6f62d15
|
||
|
|
ac3a1e350e
|
||
|
|
0a7a2c7d40
|
||
|
|
1a97536bc5
|
||
|
|
8f954c7a2e
|
||
|
|
20509b19c9
|
||
|
|
e4bdf0df19
|
||
|
|
1f421dd158
|
||
|
|
e56a2d85d7
|
||
|
|
969cf52299
|
||
|
|
01785267fc
|
||
|
|
206001888c
|
||
|
|
7c8776dd05
|
||
|
|
d6756ad3c8
|
||
|
|
57c3b346d8
|
||
|
|
55dde273ae
|
||
|
|
a6a9963c85
|
||
|
|
fb7614d6fb
|
||
|
|
a7a8c6b117
|
||
|
|
8b59897992
|
||
|
|
0d8f1e5102
|
||
|
|
e6165ca5a3
|
||
|
|
2bd54674c1
|
||
|
|
9a733807e8
|
||
|
|
f14c689353
|
||
|
|
d4443a1eef
|
||
|
|
b618a3093b
|
||
|
|
a03ba45f2a
|
||
|
|
56c38b2891
|
||
|
|
68b730e6d2
|
||
|
|
ce7b15121c
|
||
|
|
50b20e3060
|
||
|
|
c1f4fa2dc5
|
||
|
|
af9c5af173
|
||
|
|
406a4c1a1b
|
||
|
|
b732dd1b90
|
||
|
|
1e93df21ef
|
||
|
|
3bd6133bef
|
||
|
|
0c05fe2198
|
||
|
|
775791d1e1
|
||
|
|
a291d66567
|
||
|
|
31d26c0a70
|
||
|
|
88b95cc09a
|
||
|
|
9ff328d03a
|
||
|
|
481bce261e
|
||
|
|
421acf1a6a
|
||
|
|
1d01e9d275
|
||
|
|
1a3394b8f5
|
||
|
|
52bbff8284
|
||
|
|
b150970f83
|
||
|
|
6ce23d486a
|
||
|
|
024723a029
|
||
|
|
4746f01134
|
||
|
|
f2ea36ba49
|
||
|
|
adf47608d2
|
||
|
|
f916c810dc
|
||
|
|
9b86a3cb10
|
||
|
|
0fd1194596
|
||
|
|
72aa5d7351
|
||
|
|
a68c0fedd6
|
||
|
|
c5ed30bc72
|
||
|
|
6f44e30fa1
|
||
|
|
3db40f07cb
|
||
|
|
ff8791d086
|
||
|
|
f7f445bd3d
|
||
|
|
68af14bbf8
|
||
|
|
7a23318be3
|
||
|
|
4072d9b117
|
||
|
|
bc366a0af2
|
||
|
|
0c896d44ee
|
||
|
|
9a9acc4b85
|
||
|
|
a7e2285691
|
||
|
|
093e16feec
|
||
|
|
70b1b79fc2
|
||
|
|
995e1bc1aa
|
||
|
|
1120373e67
|
||
|
|
43b3ed7077
|
||
|
|
04ab6b111b
|
||
|
|
5d6787e7d6
|
||
|
|
6960406965
|
||
|
|
9454310988
|
||
|
|
d3118d20af
|
||
|
|
78337c06dd
|
||
|
|
85fc0f8e9f
|
||
|
|
c19ae507cf
|
||
|
|
004041b342
|
||
|
|
08f69cf76d
|
||
|
|
e10bfbe406
|
||
|
|
1a46a76b59
|
||
|
|
e2f32a6722
|
||
|
|
5a23f4329e
|
||
|
|
f5fd6cebdb
|
||
|
|
48f6711f1a
|
||
|
|
859046f5aa
|
||
|
|
7c7a60807f
|
||
|
|
1b23b2937e
|
||
|
|
4135f52499
|
||
|
|
8fda0bfec5
|
||
|
|
7e353053c7
|
||
|
|
d744d218fb
|
||
|
|
772fa6b678
|
||
|
|
154bc6a5c0
|
||
|
|
593939c2d4
|
||
|
|
6730c8ce70
|
||
|
|
b6a1e6e43c
|
||
|
|
fd06fdafe7
|
||
|
|
20a119c6c8
|
||
|
|
cfa8141424
|
||
|
|
7a2a7e5593
|
||
|
|
1a61091ec2
|
||
|
|
bbb1bd3562
|
||
|
|
db8017a8ce
|
||
|
|
bc69ec5681
|
||
|
|
8f6c3105ef
|
||
|
|
de6c1b8b44
|
||
|
|
ffd57fabd0
|
||
|
|
a80d5dec88
|
||
|
|
8bccf5ed01
|
||
|
|
7c831441fc
|
||
|
|
7cd54ff3e8
|
||
|
|
3c3f5aed69
|
||
|
|
913e1a8643
|
||
|
|
f6c7dac970
|
||
|
|
95db23f253
|
||
|
|
62044a3351
|
||
|
|
694b50d375
|
||
|
|
122d85068d
|
||
|
|
620670915f
|
||
|
|
10974242aa
|
||
|
|
36b2ada16a
|
||
|
|
8428057eb4
|
||
|
|
1133daf764
|
||
|
|
b09070e8df
|
||
|
|
cde0b8f498
|
||
|
|
916dd278b2
|
||
|
|
d6d0792207
|
||
|
|
a7bae506a7
|
||
|
|
d05906de7b
|
||
|
|
a8300041e3
|
||
|
|
8bd0d2bc0e
|
||
|
|
cf5f4acf72
|
||
|
|
0d6709d518
|
||
|
|
12bd10164b
|
||
|
|
6287e74fe5
|
||
|
|
8956b7c8d5
|
||
|
|
60c6a37f89
|
検索条件に一致するファイルはありません
+17
-42
@@ -1,59 +1,34 @@
|
||||
# v1.15.0 - Lua スクリプト for YMM4
|
||||
# v1.20.2 - Lua スクリプト for YMM4
|
||||
|
||||
AviUtl ExEdit2 互換のピクセルシェーダーを追加したリリースです。スクリプト内のコメントに HLSL で記述したピクセルシェーダーを obj.pixelshader で GPU 実行できます。記法と引数の並びは AviUtl ExEdit2 と同一で、MoonSharp とネイティブのどちらの実行エンジンでも動作します。互換にとどまらず YMM4 側の拡張も加えており、blend 引数へ obj.setoption("blend", 番号) と同じ番号を数値で渡すと、シェーダーの出力を YMM4 の全合成モードで出力先へ合成できます。また、YMM4 の構造上取得できないフレームバッファは、シーンサイズの仮想フレームバッファとして再解釈して対応しました。既存のスクリプトの書き方と実行結果に変更はありません。
|
||||
[fast] マーカーに実効性を戻すリリースです。v1.20.1 で obj.fill / obj.convolve / obj.resize の GPU 委譲を自動判定に統一した結果、[fast] は委譲の意図を明示するだけの補助マーカーとなり、付けても付けなくても同じ判定を通るため動作に差がありませんでした。本バージョンから [fast] は処理量のしきい値を無視して強制的に GPU へ委譲します。GPU が使えない環境や、GPU の結果が CPU と一致しないと判定された環境では、[fast] を付けても自動で CPU 実行に戻るため、結果が壊れることはありません。
|
||||
|
||||
---
|
||||
|
||||
## 新機能
|
||||
## 変更
|
||||
|
||||
### obj.pixelshader
|
||||
### [fast] はしきい値を無視して GPU 委譲を強制
|
||||
|
||||
スクリプト内に定義した HLSL のピクセルシェーダーを GPU で実行する obj.pixelshader(登録名, 出力先, リソース [, 定数 [, blend [, sampler]]]) を追加しました。
|
||||
obj.fill / obj.convolve / obj.resize は、v1.20.1 と同じく処理量がしきい値以上で GPU の結果が CPU と一致すると確認できたときに自動で GPU へ委譲します。呼び出しの直前に [fast] を置いたときだけ、この処理量のしきい値を無視します。
|
||||
|
||||
- シェーダーは AviUtl ExEdit2 と同じ記法の複数行コメントで定義します。--[[pixelshader@登録名: で始まるコメントに HLSL を記述し、登録名がエントリーポイントの関数名になります。1 つのスクリプトに複数のシェーダーを定義できます。
|
||||
- 出力先は "object"、"tempbuffer"、"cache:名前"、"framebuffer" に対応します。"tempbuffer" と "cache:名前" のバッファが存在しない場合は、オブジェクト画像と同じサイズで自動生成します。
|
||||
- リソースは参照するバッファ名の配列で、シェーダーリソース t0~t7 に設定されます。最大 8 個です。1 つの場合は文字列で直接指定できます。"random" を指定すると 0.0~1.0 の乱数値を持つ 256x256 の R32_FLOAT 領域になり、乱数の内容はフレームを跨いで変わりません。存在しないバッファ名を指定した場合は 1x1 の透明画像が設定されます。
|
||||
- 定数は数値の配列で、定数バッファ b0 へ float の配列として詰めて設定されます。最大 1024 個です。
|
||||
- blend は出力先への合成方法です。"copy" はそのまま、"mask" はα値のみ乗算、"draw" はアルファブレンド、"add" は加算で、省略時は "copy" です。
|
||||
- sampler は SamplerState s0 の種別で、"clip"、"clamp"、"loop"、"mirror"、"dot" に対応します。省略時は未設定です。
|
||||
- ピクセルシェーダーの入力シグネチャは float4 名前(float4 pos : SV_Position) : SV_Target と、float2 uv : TEXCOORD を加えた形式の 2 種類を使用できます。uv は描画範囲が 0.0~1.0 になるように設定されます。
|
||||
- 実行は Direct3D 11 の機能レベル 11_0 で行い、シェーダーモデルは ps_5_0 です。ハードウェアのデバイスを作成できない環境では WARP ラスタライザーへ、それも作成できない環境では呼び出しのスキップへ自動的に切り替わります。スキップした場合、画像は変化しません。
|
||||
- HLSL のコンパイルエラーはスクリプトの実行時エラーとして報告し、エディターの診断へ波線とエラー内容を表示します。未定義の登録名、綴りの誤った blend、綴りの誤った sampler も実行時エラーとして報告します。
|
||||
- MoonSharp とネイティブの両方の実行エンジンで動作します。ディレクティブを書かない自動選択のスクリプトでも動作します。シェーダーの実行自体は、どちらのエンジンでもホスト側の GPU で行われます。
|
||||
- 構文拡張の変換はシェーダー定義のコメントをそのまま保持するため、独自記法とシェーダー定義は同じスクリプトの中で併用できます。
|
||||
|
||||
### 合成モードの数値指定
|
||||
|
||||
blend 引数へ数値を渡す指定を追加しました。obj.setoption("blend", 番号) と同じ並びの番号で、シェーダーの出力を YMM4 の合成モードで出力先へ合成します。通常、乗算、スクリーン、オーバーレイなどの全種類を使用でき、合成の実装は obj.draw の合成モードと同じ経路を通るため、結果も一致します。範囲外の番号は通常になります。
|
||||
|
||||
### 仮想フレームバッファ
|
||||
|
||||
YMM4 のエフェクトは自分のオブジェクトの画像しか受け取れないため、AviUtl の "framebuffer" が指す背景込みの画面は取得できません。そこで、シーンサイズの仮想フレームバッファとして再解釈して対応しました。
|
||||
|
||||
- 内容は、シーンサイズの透明な領域へ、オブジェクトを現在の位置・拡大率・縦横比・不透明度で合成した画像です。回転は反映しません。背景は含まれません。内容はフレームごとに作り直します。
|
||||
- obj.pixelshader のリソースに "framebuffer" を指定すると、この画像がシェーダーリソースとして設定されます。
|
||||
- obj.pixelshader の出力先に "framebuffer" を指定すると、シェーダーはシーンサイズの領域へ描画し、その結果でオブジェクト画像を置き換えます。オブジェクトが既定の位置と拡大率であれば、置き換え後の画像はシーン全体を覆います。
|
||||
- obj.copybuffer のコピー元に "frm" を指定できるようになりました。コピー先には指定できません。
|
||||
- しきい値のみを無視し、Direct3D 11 のハードウェアデバイスが利用できることと、GPU の結果が CPU 基準とバイト単位で一致することの確認は、[fast] を付けても変わらず行います。どちらかが成立しない環境では CPU 実装へ戻ります。
|
||||
- convolve のカーネルサイズの上限(31×31)など、GPU 側の対応可否そのものに関わる制約は [fast] でも変わりません。
|
||||
- [fast] を付けない呼び出しは v1.20.1 までと同じく、しきい値未満の小さな処理では GPU へ委譲しません。
|
||||
|
||||
---
|
||||
|
||||
## 互換性・後方互換
|
||||
|
||||
- obj.pixelshader は新規の API です。既存のスクリプトはそのまま動作し、実行結果も変わりません。
|
||||
- obj.setoption("drawtarget", "tempbuffer") 使用時の obj.draw の合成は、従来どおり通常の合成です。blend の設定はフレームバッファへの描画にのみ適用されます。
|
||||
- ネイティブエンジンのワーカープロセスは、シェーダーの受け渡しに使う共有メモリ領域を常時確保するようになりました。確保量は約 32MB 増えますが、使用しない限り物理メモリは消費しません。
|
||||
- v1.14.0 までの仕様に変更はありません。
|
||||
- [fast] を付けない呼び出しの動作は v1.20.1 と同一です。
|
||||
- GPU が使えない環境や検証に通らないカーネルでは、[fast] を付けた呼び出しも CPU 実装が結果を保証するため、実行結果が変わることはありません。
|
||||
- 関数の引数・戻り値・エラーの扱い、構文・置ける位置(単独の行または同じ行)、3 関数以外へ付けたときのエラー表示に変更はありません。
|
||||
- エンジンの自動振り分け、エンジン指定ディレクティブの仕様と優先順位、カーネル化の対象、v1.20.1 までの構文拡張と既存の API に変更はありません。
|
||||
|
||||
---
|
||||
|
||||
## 内部実装
|
||||
|
||||
- シェーダー定義の解析器を互換層に新設しました。行頭の --[[pixelshader@ を走査し、同名の定義は初出を優先します。名前@スクリプト名 の形式はローカルの名前で解決します。
|
||||
- シェーダー実行の契約をランタイムに新設しました。合成指定は種別と合成番号を持つ構造体で、リソース・サンプラー・実行結果の型と合わせて、実行器の実装をエンジンから分離しています。
|
||||
- Direct3D 11 の実行器はプラグイン本体に置き、自前のデバイスを保持します。頂点シェーダーは SV_VertexID から生成するフルスクリーン三角形で、コンパイル結果はソースとエントリーポイントの組で、テクスチャはサイズの組でそれぞれ再利用します。デバイスロストの際は 3 回まで再生成し、それを超えると無効化して警告を 1 回だけ記録します。
|
||||
- 数値指定の合成は、シェーダーを copy で描画した結果を読み戻し、既存のバッファ合成器で出力先へ合成する 2 段構成です。ハードウェアのバッファ合成器が合成モードを Direct2D で適用するようになりました。ソフトウェアの合成へ切り替わった環境では通常の合成になり、切り替わりを警告として 1 回だけ記録します。
|
||||
- ネイティブエンジンでは、共有メモリの末尾へシェーダー交換領域を追加しました。領域はメタ情報、定数、画像域から成り、ワーカーがリソースを 1 枚ずつ交換域へ書いてホストへ引き渡し、ホストが実行して結果を書き戻します。オブジェクト画像が対象の場合は既存のピクセル領域を直接読み書きし、転送を省きます。領域は 8 バイト整列で確保し、ワーカーの容量判定も領域込みで行います。
|
||||
- 両エンジンとも、リソース・定数・転送先の受け渡しには再利用の配列を使い、フレームごとのメモリ確保を発生させません。
|
||||
- 仮想フレームバッファは、参照時に一度だけ構築してフレーム内で再利用します。ネイティブエンジンではワーカー側に同じ構築処理を持ち、スクリプト実行前の初期値から合成するため、両エンジンの内容が一致します。
|
||||
- ドキュメントは付属の 8 言語、サイトの obj の関数のページ、README を更新しました。
|
||||
- テストは 3259 件です。v1.14.0 の 3215 件から、シェーダー定義の解析、MoonSharp 束縛の引数と各エラー、数値指定の合成、仮想フレームバッファの参照と置き換え、ネイティブの往復でのリソース転送と書き戻し、コンパイルエラーの伝播、実行器が無い環境でのスキップ、構文拡張の変換がシェーダー定義を保持すること、および自動振り分けの検証を追加しました。
|
||||
- IPixelBufferProcessor.TryFill / TryConvolve / TryResize に force 引数を追加しました。GpuFillOperation / GpuConvolveOperation / GpuResizeOperation は force が真のときだけ内部のしきい値判定を飛ばし、ハードウェア対応の確認と CPU/GPU 一致検証はそのまま行います。
|
||||
- 従来エンジンは AviUtlScriptContext.FillBuffer / Convolve / Resize と LuaScriptEngine の FillCore / ConvolveCore / ResizeCore に force 引数を復元し、__fast_fill / __fast_convolve / __fast_resize が force: true を、obj.fill / obj.convolve / obj.resize が force: false を渡します。
|
||||
- 高速ランタイムは worker.lua の fillImpl / convolveImpl / resizeImpl に force 引数を復元しました。__fast_* 側は force: true、obj.* 側は force: false を渡し、force が真のときは worker.lua 側のしきい値判定も飛ばして常にホストへ照会します。ホストとの往復では cbResult の未使用スロット(10 番目)で force フラグを伝え、LuaJitWorker が読み取って IPixelBufferProcessor へ引き渡します。プロトコルの新しい定数は追加していません。
|
||||
- テストは 3404 件です。v1.20.1 の 3400 件から、__fast_* がしきい値未満でもホストプロセッサへ委譲されることの検証を両レーンに 3 件ずつ、標準呼び出しが force: false を渡すことの検証を追加しました。ソリューションは x64 で 0 個の警告、0 個のエラーです。
|
||||
- ドキュメントは付属の 8 言語の [fast] の節、サイトの構文拡張と obj の関数のページ、README を強制委譲の仕様へ更新しました。
|
||||
@@ -1,11 +1,11 @@
|
||||
========================================
|
||||
Luaスクリプト for YMM4 v1.15.0
|
||||
Luaスクリプト for YMM4 v1.20.2
|
||||
========================================
|
||||
YukkuriMovieMaker4(YMM4)上で動作する、Luaスクリプトで映像エフェクトのパラメータや
|
||||
ピクセルを直接制御できるプラグインです。
|
||||
スクリプトの実行にはMoonSharpによるLuaインタプリタを使用しており、座標・拡大率・
|
||||
透明度・回転といった描画パラメータの変更に加えて、ピクセル単位での読み書きにも
|
||||
対応しています。
|
||||
透明度・回転といった描画パラメータの変更に加えて、ピクセル単位での読み書きや、
|
||||
塗りつぶし・領域の一括読み書き・畳み込み・拡大縮小による画像加工にも対応しています。
|
||||
obj.x/y/zoom/alpha等の値はキーフレームアニメーションと連動するTrack0~3パラメータ
|
||||
からも参照でき、anim.*関数群によるイージングやノイズ等の演出も組み合わせられます。
|
||||
--------------------------------------------------------------------------------
|
||||
|
||||
@@ -77,6 +77,7 @@ jobs:
|
||||
Copy-Item "$outDir/LuaScript.Compat.dll" "$stageRoot/"
|
||||
Copy-Item "$outDir/LuaScript.Media.dll" "$stageRoot/"
|
||||
Copy-Item "$outDir/LuaScript.Runtime.dll" "$stageRoot/"
|
||||
Copy-Item "$outDir/LuaScript.Gpu.dll" "$stageRoot/"
|
||||
Copy-Item "$outDir/MoonSharp.Interpreter.dll" "$stageRoot/"
|
||||
Copy-Item "$outDir/native/luajit.exe" "$stageRoot/native/"
|
||||
Copy-Item "$outDir/native/lua51.dll" "$stageRoot/native/"
|
||||
|
||||
@@ -0,0 +1,195 @@
|
||||
using System;
|
||||
|
||||
namespace LuaScript.Compat
|
||||
{
|
||||
internal sealed class AviUtlAudioConverter
|
||||
{
|
||||
public const int MaxSamples = 1024;
|
||||
public const int SpectrumWindow = 1024;
|
||||
public const int FourierWindow = 2048;
|
||||
public const int SpectrumBins = SpectrumWindow / 2;
|
||||
|
||||
private const double PcmScale = 32768d;
|
||||
|
||||
private readonly double[] _mono = new double[FourierWindow];
|
||||
private readonly double[] _real = new double[FourierWindow];
|
||||
private readonly double[] _imag = new double[FourierWindow];
|
||||
|
||||
private enum DataKind
|
||||
{
|
||||
Unknown,
|
||||
Pcm,
|
||||
Spectrum,
|
||||
Fourier,
|
||||
}
|
||||
|
||||
public static int RequiredFrames(string type, int size)
|
||||
{
|
||||
var (kind, _) = Parse(type);
|
||||
return kind switch
|
||||
{
|
||||
DataKind.Pcm => ResolveCount(kind, size),
|
||||
DataKind.Spectrum => SpectrumWindow,
|
||||
DataKind.Fourier => FourierWindow,
|
||||
_ => 0,
|
||||
};
|
||||
}
|
||||
|
||||
public int Convert(string type, ReadOnlySpan<float> interleaved, int frames, int size, Span<double> destination)
|
||||
{
|
||||
var (kind, channel) = Parse(type);
|
||||
if (kind == DataKind.Unknown || frames <= 0)
|
||||
return 0;
|
||||
|
||||
int window = kind switch
|
||||
{
|
||||
DataKind.Pcm => Math.Min(frames, ResolveCount(kind, size)),
|
||||
DataKind.Spectrum => SpectrumWindow,
|
||||
_ => FourierWindow,
|
||||
};
|
||||
FillMono(interleaved, frames, channel, window);
|
||||
|
||||
switch (kind)
|
||||
{
|
||||
case DataKind.Pcm:
|
||||
{
|
||||
int count = Math.Min(ResolveCount(kind, size), frames);
|
||||
for (int i = 0; i < count; i++)
|
||||
destination[i] = Math.Clamp(_mono[i] * PcmScale, -32768d, 32767d);
|
||||
return count;
|
||||
}
|
||||
case DataKind.Spectrum:
|
||||
{
|
||||
int bands = ResolveCount(kind, size);
|
||||
Fft(SpectrumWindow);
|
||||
double scale = 2d / SpectrumWindow * PcmScale;
|
||||
for (int b = 0; b < bands; b++)
|
||||
{
|
||||
int start = b * SpectrumBins / bands;
|
||||
int end = (b + 1) * SpectrumBins / bands;
|
||||
if (end <= start)
|
||||
end = start + 1;
|
||||
double sum = 0d;
|
||||
for (int bin = start; bin < end; bin++)
|
||||
sum += Magnitude(bin);
|
||||
destination[b] = sum / (end - start) * scale;
|
||||
}
|
||||
return bands;
|
||||
}
|
||||
case DataKind.Fourier:
|
||||
{
|
||||
int count = ResolveCount(kind, size);
|
||||
Fft(FourierWindow);
|
||||
double scale = 2d / FourierWindow;
|
||||
for (int i = 0; i < count; i++)
|
||||
destination[i] = Magnitude(i + 1) * scale;
|
||||
return count;
|
||||
}
|
||||
default:
|
||||
return 0;
|
||||
}
|
||||
}
|
||||
|
||||
private static int ResolveCount(DataKind kind, int size)
|
||||
{
|
||||
int fallback = kind == DataKind.Spectrum ? 32 : MaxSamples;
|
||||
int max = kind == DataKind.Spectrum ? SpectrumBins : MaxSamples;
|
||||
return size <= 0 ? Math.Min(fallback, max) : Math.Clamp(size, 1, max);
|
||||
}
|
||||
|
||||
private static (DataKind Kind, int Channel) Parse(string type)
|
||||
{
|
||||
int channel = 0;
|
||||
int length = type.Length;
|
||||
if (length >= 2 && type[length - 2] == '.')
|
||||
{
|
||||
char suffix = type[length - 1];
|
||||
if (suffix == 'l')
|
||||
channel = 1;
|
||||
else if (suffix == 'r')
|
||||
channel = 2;
|
||||
if (channel != 0)
|
||||
length -= 2;
|
||||
}
|
||||
|
||||
var name = type.AsSpan(0, length);
|
||||
DataKind kind = DataKind.Unknown;
|
||||
if (name.SequenceEqual("pcm"))
|
||||
kind = DataKind.Pcm;
|
||||
else if (name.SequenceEqual("spectrum"))
|
||||
kind = DataKind.Spectrum;
|
||||
else if (name.SequenceEqual("fourier"))
|
||||
kind = DataKind.Fourier;
|
||||
return (kind, channel);
|
||||
}
|
||||
|
||||
private void FillMono(ReadOnlySpan<float> interleaved, int frames, int channel, int window)
|
||||
{
|
||||
int available = Math.Min(frames, window);
|
||||
for (int i = 0; i < available; i++)
|
||||
{
|
||||
float left = interleaved[i * 2];
|
||||
float right = interleaved[i * 2 + 1];
|
||||
_mono[i] = channel switch
|
||||
{
|
||||
1 => left,
|
||||
2 => right,
|
||||
_ => (left + right) * 0.5d,
|
||||
};
|
||||
}
|
||||
for (int i = available; i < window; i++)
|
||||
_mono[i] = 0d;
|
||||
}
|
||||
|
||||
private double Magnitude(int bin) =>
|
||||
Math.Sqrt(_real[bin] * _real[bin] + _imag[bin] * _imag[bin]);
|
||||
|
||||
private void Fft(int n)
|
||||
{
|
||||
for (int i = 0; i < n; i++)
|
||||
{
|
||||
_real[i] = _mono[i];
|
||||
_imag[i] = 0d;
|
||||
}
|
||||
|
||||
for (int i = 1, j = 0; i < n; i++)
|
||||
{
|
||||
int bit = n >> 1;
|
||||
for (; (j & bit) != 0; bit >>= 1)
|
||||
j ^= bit;
|
||||
j |= bit;
|
||||
if (i < j)
|
||||
{
|
||||
(_real[i], _real[j]) = (_real[j], _real[i]);
|
||||
(_imag[i], _imag[j]) = (_imag[j], _imag[i]);
|
||||
}
|
||||
}
|
||||
|
||||
for (int len = 2; len <= n; len <<= 1)
|
||||
{
|
||||
double angle = -2d * Math.PI / len;
|
||||
double wRe = Math.Cos(angle);
|
||||
double wIm = Math.Sin(angle);
|
||||
for (int i = 0; i < n; i += len)
|
||||
{
|
||||
double curRe = 1d;
|
||||
double curIm = 0d;
|
||||
for (int k = 0; k < len / 2; k++)
|
||||
{
|
||||
int a = i + k;
|
||||
int b = i + k + len / 2;
|
||||
double tRe = _real[b] * curRe - _imag[b] * curIm;
|
||||
double tIm = _real[b] * curIm + _imag[b] * curRe;
|
||||
_real[b] = _real[a] - tRe;
|
||||
_imag[b] = _imag[a] - tIm;
|
||||
_real[a] += tRe;
|
||||
_imag[a] += tIm;
|
||||
double nextRe = curRe * wRe - curIm * wIm;
|
||||
curIm = curRe * wIm + curIm * wRe;
|
||||
curRe = nextRe;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -3,7 +3,7 @@
|
||||
<PropertyGroup>
|
||||
<TargetFramework>net10.0-windows10.0.19041.0</TargetFramework>
|
||||
<ImplicitUsings>enable</ImplicitUsings>
|
||||
<Version>1.15.0</Version>
|
||||
<Version>1.20.2</Version>
|
||||
<Platforms>AnyCPU;x64</Platforms>
|
||||
<Nullable>enable</Nullable>
|
||||
</PropertyGroup>
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Text;
|
||||
using LuaScript.Compat.Syntax;
|
||||
|
||||
namespace LuaScript.Compat
|
||||
{
|
||||
@@ -15,10 +16,10 @@ namespace LuaScript.Compat
|
||||
|
||||
public static string Transform(string source) => TransformWithMap(source).Code;
|
||||
|
||||
public static (string Code, int[] LineMap, int[] ChangedLines) TransformWithMap(string source)
|
||||
public static (string Code, int[] LineMap, int[] ChangedLines, LuaRewriteDiagnostic[] Diagnostics) TransformWithMap(string source)
|
||||
{
|
||||
if (string.IsNullOrEmpty(source))
|
||||
return (source, [], []);
|
||||
return (source, [], [], []);
|
||||
|
||||
var lines = ScriptParserHelper.SplitLines(source);
|
||||
bool hasSection = ScriptParserHelper.TryFindSection(lines, out int sectionStart, out int sectionEnd);
|
||||
@@ -29,8 +30,8 @@ namespace LuaScript.Compat
|
||||
|
||||
if (!hasSection && prelude.Count == 0)
|
||||
{
|
||||
var (code, changed) = LuaSyntaxExtensions.RewriteWithMap(source);
|
||||
return (code, [], changed);
|
||||
var (code, changed, preludeless) = LuaSyntaxExtensions.RewriteWithMap(source);
|
||||
return (code, [], changed, preludeless);
|
||||
}
|
||||
|
||||
var builder = new StringBuilder(source.Length + 64);
|
||||
@@ -48,8 +49,8 @@ namespace LuaScript.Compat
|
||||
lineMap[row++] = i;
|
||||
}
|
||||
|
||||
var (rewritten, changedLines) = LuaSyntaxExtensions.RewriteWithMap(builder.ToString());
|
||||
return (rewritten, lineMap, changedLines);
|
||||
var (rewritten, changedLines, diagnostics) = LuaSyntaxExtensions.RewriteWithMap(builder.ToString());
|
||||
return (rewritten, lineMap, changedLines, diagnostics);
|
||||
}
|
||||
|
||||
private static void AppendDeclarations(string line, List<string> prelude)
|
||||
|
||||
@@ -6,10 +6,10 @@ namespace LuaScript.Compat
|
||||
{
|
||||
public static string Rewrite(string source) => RewriteWithMap(source).Code;
|
||||
|
||||
public static (string Code, int[] ChangedLines) RewriteWithMap(string source)
|
||||
public static (string Code, int[] ChangedLines, LuaRewriteDiagnostic[] Diagnostics) RewriteWithMap(string source)
|
||||
{
|
||||
if (string.IsNullOrEmpty(source))
|
||||
return (source, []);
|
||||
return (source, [], []);
|
||||
|
||||
var tokens = LuaSyntaxLexer.Tokenize(source);
|
||||
var context = new LuaRewriteContext(tokens);
|
||||
@@ -42,7 +42,8 @@ namespace LuaScript.Compat
|
||||
}
|
||||
}
|
||||
|
||||
return context.Changed ? (context.Serialize(), context.ChangedLines) : (source, []);
|
||||
var diagnostics = context.Diagnostics;
|
||||
return context.Changed ? (context.Serialize(), context.ChangedLines, diagnostics) : (source, [], diagnostics);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,130 @@
|
||||
using System.Collections.Generic;
|
||||
using System.Text;
|
||||
|
||||
namespace LuaScript.Compat.Syntax
|
||||
{
|
||||
internal readonly struct LuaRangeParts
|
||||
{
|
||||
public LuaRangeParts(string start, string stop, string? step, bool exclusive)
|
||||
{
|
||||
Start = start;
|
||||
Stop = stop;
|
||||
Step = step;
|
||||
Exclusive = exclusive;
|
||||
}
|
||||
|
||||
public string Start { get; }
|
||||
|
||||
public string Stop { get; }
|
||||
|
||||
public string? Step { get; }
|
||||
|
||||
public bool Exclusive { get; }
|
||||
}
|
||||
|
||||
internal static class LuaRangeSyntax
|
||||
{
|
||||
public static bool TryParse(IReadOnlyList<LuaSyntaxToken> input, int open, out LuaRangeParts parts, out int end)
|
||||
{
|
||||
parts = default;
|
||||
end = open;
|
||||
|
||||
if (open < 0 || open >= input.Count || !input[open].IsOperator("<"))
|
||||
return false;
|
||||
|
||||
int position = open + 1;
|
||||
if (!TryReadSegment(input, ref position, "..", ">", out string start, out string startTerminator) || startTerminator != "..")
|
||||
return false;
|
||||
|
||||
bool exclusive = false;
|
||||
int caret = NextSignificant(input, position);
|
||||
if (caret >= 0 && input[caret].IsOperator("<"))
|
||||
{
|
||||
exclusive = true;
|
||||
position = caret + 1;
|
||||
}
|
||||
|
||||
if (!TryReadSegment(input, ref position, ",", ">", out string stop, out string stopTerminator))
|
||||
return false;
|
||||
|
||||
string? step = null;
|
||||
if (stopTerminator == ",")
|
||||
{
|
||||
if (!TryReadSegment(input, ref position, ">", ">", out string stepText, out string stepTerminator) || stepTerminator != ">")
|
||||
return false;
|
||||
step = stepText;
|
||||
}
|
||||
else if (stopTerminator != ">")
|
||||
{
|
||||
return false;
|
||||
}
|
||||
|
||||
if (start.Length == 0 || stop.Length == 0 || (step is not null && step.Length == 0))
|
||||
return false;
|
||||
|
||||
parts = new LuaRangeParts(start, stop, step, exclusive);
|
||||
end = position;
|
||||
return true;
|
||||
}
|
||||
|
||||
private static bool TryReadSegment(IReadOnlyList<LuaSyntaxToken> input, ref int position, string primaryStop, string secondaryStop, out string text, out string terminator)
|
||||
{
|
||||
text = string.Empty;
|
||||
terminator = string.Empty;
|
||||
int start = position;
|
||||
int depth = 0;
|
||||
int count = input.Count;
|
||||
|
||||
while (position < count)
|
||||
{
|
||||
var token = input[position];
|
||||
if (token.Kind == LuaSyntaxTokenKind.Newline && depth == 0)
|
||||
return false;
|
||||
if (token.Kind == LuaSyntaxTokenKind.Operator)
|
||||
{
|
||||
if (token.Text is "(" or "[" or "{")
|
||||
{
|
||||
depth++;
|
||||
}
|
||||
else if (token.Text is ")" or "]" or "}")
|
||||
{
|
||||
if (depth == 0)
|
||||
return false;
|
||||
depth--;
|
||||
}
|
||||
else if (depth == 0 && (token.Text == primaryStop || token.Text == secondaryStop))
|
||||
{
|
||||
terminator = token.Text;
|
||||
text = Trim(input, start, position);
|
||||
position++;
|
||||
return true;
|
||||
}
|
||||
}
|
||||
position++;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
private static int NextSignificant(IReadOnlyList<LuaSyntaxToken> input, int from)
|
||||
{
|
||||
for (int i = from; i < input.Count; i++)
|
||||
{
|
||||
if (!input[i].IsTrivia)
|
||||
return i;
|
||||
}
|
||||
return -1;
|
||||
}
|
||||
|
||||
private static string Trim(IReadOnlyList<LuaSyntaxToken> input, int begin, int end)
|
||||
{
|
||||
while (begin < end && input[begin].IsTrivia)
|
||||
begin++;
|
||||
while (end > begin && input[end - 1].IsTrivia)
|
||||
end--;
|
||||
var builder = new StringBuilder();
|
||||
for (int i = begin; i < end; i++)
|
||||
builder.Append(input[i].Text);
|
||||
return builder.ToString();
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -8,6 +8,7 @@ namespace LuaScript.Compat.Syntax
|
||||
private readonly List<LuaSyntaxToken> _input;
|
||||
private readonly List<LuaSyntaxToken> _output;
|
||||
private List<int>? _changedLines;
|
||||
private List<LuaRewriteDiagnostic>? _diagnostics;
|
||||
private int _line = 1;
|
||||
private int _lastChangedLine;
|
||||
private int _temporaries;
|
||||
@@ -28,6 +29,14 @@ namespace LuaScript.Compat.Syntax
|
||||
|
||||
public int[] ChangedLines => _changedLines is null ? [] : _changedLines.ToArray();
|
||||
|
||||
public LuaRewriteDiagnostic[] Diagnostics => _diagnostics is null ? [] : _diagnostics.ToArray();
|
||||
|
||||
public void AddDiagnostic(string message)
|
||||
{
|
||||
(_diagnostics ??= new List<LuaRewriteDiagnostic>()).Add(new LuaRewriteDiagnostic(_line, message));
|
||||
MarkChanged();
|
||||
}
|
||||
|
||||
public bool AtEnd => Index >= _input.Count;
|
||||
|
||||
public LuaSyntaxToken Current => _input[Index];
|
||||
|
||||
@@ -0,0 +1,4 @@
|
||||
namespace LuaScript.Compat.Syntax
|
||||
{
|
||||
internal readonly record struct LuaRewriteDiagnostic(int Line, string Message);
|
||||
}
|
||||
@@ -8,6 +8,7 @@ namespace LuaScript.Compat.Syntax
|
||||
{
|
||||
"...", "..=", "??=", "||=", "&&=",
|
||||
"==", "~=", "<=", ">=", "..", "::", "??", "||", "&&", "!=", "++",
|
||||
"=>", "|>",
|
||||
"+=", "-=", "*=", "/=", "%=", "^=",
|
||||
"+", "-", "*", "/", "%", "^", "#", "<", ">", "=",
|
||||
"(", ")", "{", "}", "[", "]", ";", ":", ",", ".",
|
||||
@@ -72,6 +73,14 @@ namespace LuaScript.Compat.Syntax
|
||||
continue;
|
||||
}
|
||||
|
||||
if (c == '`')
|
||||
{
|
||||
int start = i;
|
||||
i = SkipShortString(source, i);
|
||||
tokens.Add(new LuaSyntaxToken(LuaSyntaxTokenKind.InterpolatedString, source.Substring(start, i - start)));
|
||||
continue;
|
||||
}
|
||||
|
||||
if (IsDigit(c) || (c == '.' && i + 1 < length && IsDigit(source[i + 1])))
|
||||
{
|
||||
int start = i;
|
||||
|
||||
@@ -6,5 +6,9 @@ namespace LuaScript.Compat.Syntax
|
||||
internal sealed class LuaSyntaxRuleAttribute(int order) : Attribute
|
||||
{
|
||||
public int Order { get; } = order;
|
||||
|
||||
public bool IsCatalog { get; set; }
|
||||
|
||||
public string Keyword { get; set; } = "";
|
||||
}
|
||||
}
|
||||
@@ -6,6 +6,7 @@ namespace LuaScript.Compat.Syntax
|
||||
Newline,
|
||||
Comment,
|
||||
String,
|
||||
InterpolatedString,
|
||||
Number,
|
||||
Name,
|
||||
Operator,
|
||||
|
||||
@@ -0,0 +1,76 @@
|
||||
namespace LuaScript.Compat.Syntax.Rules
|
||||
{
|
||||
[LuaSyntaxRule(2, IsCatalog = true, Keyword = MarkerKeyword)]
|
||||
internal sealed class LuaFastRule : ILuaSyntaxRule
|
||||
{
|
||||
private const string MarkerKeyword = "fast";
|
||||
private const string Message = "[fast]: only obj.fill, obj.convolve and obj.resize can be accelerated.";
|
||||
|
||||
public bool TryApply(LuaRewriteContext context)
|
||||
{
|
||||
if (!context.Current.IsOperator("["))
|
||||
return false;
|
||||
|
||||
if (context.TryPreviousOutputSignificantSameLine(out var previous) && LuaSyntaxFacts.IsValueEnd(previous))
|
||||
return false;
|
||||
|
||||
int nameIndex = context.NextSignificant(context.Index + 1);
|
||||
if (nameIndex < 0 || !context.Input[nameIndex].IsName(MarkerKeyword))
|
||||
return false;
|
||||
|
||||
int closeIndex = context.NextSignificant(nameIndex + 1);
|
||||
if (closeIndex < 0 || !context.Input[closeIndex].IsOperator("]"))
|
||||
return false;
|
||||
|
||||
int targetIndex = context.NextSignificant(closeIndex + 1);
|
||||
if (targetIndex < 0 || context.Input[targetIndex].Kind != LuaSyntaxTokenKind.Name)
|
||||
return false;
|
||||
|
||||
if (TryResolveTarget(context, targetIndex, out int funcIndex, out string function))
|
||||
{
|
||||
EmitBetween(context, closeIndex + 1, targetIndex);
|
||||
context.Index = funcIndex + 1;
|
||||
context.EmitRaw("__fast_" + function);
|
||||
return true;
|
||||
}
|
||||
|
||||
context.AddDiagnostic(Message);
|
||||
EmitBetween(context, closeIndex + 1, targetIndex);
|
||||
context.Index = targetIndex;
|
||||
return true;
|
||||
}
|
||||
|
||||
private static bool TryResolveTarget(LuaRewriteContext context, int objIndex, out int funcIndex, out string function)
|
||||
{
|
||||
funcIndex = -1;
|
||||
function = string.Empty;
|
||||
if (!context.Input[objIndex].IsName("obj"))
|
||||
return false;
|
||||
|
||||
int dot = context.NextSignificant(objIndex + 1);
|
||||
if (dot < 0 || !context.Input[dot].IsOperator("."))
|
||||
return false;
|
||||
|
||||
int name = context.NextSignificant(dot + 1);
|
||||
if (name < 0)
|
||||
return false;
|
||||
string text = context.Input[name].Text;
|
||||
if (text is not ("fill" or "convolve" or "resize"))
|
||||
return false;
|
||||
|
||||
int paren = context.NextSignificant(name + 1);
|
||||
if (paren < 0 || !context.Input[paren].IsOperator("("))
|
||||
return false;
|
||||
|
||||
funcIndex = name;
|
||||
function = text;
|
||||
return true;
|
||||
}
|
||||
|
||||
private static void EmitBetween(LuaRewriteContext context, int from, int to)
|
||||
{
|
||||
for (int i = from; i < to; i++)
|
||||
context.Emit(context.Input[i]);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,117 @@
|
||||
using System.Collections.Generic;
|
||||
using System.Text;
|
||||
|
||||
namespace LuaScript.Compat.Syntax.Rules
|
||||
{
|
||||
[LuaSyntaxRule(5)]
|
||||
internal sealed class LuaInterpolatedStringRule : ILuaSyntaxRule
|
||||
{
|
||||
public bool TryApply(LuaRewriteContext context)
|
||||
{
|
||||
if (context.Current.Kind != LuaSyntaxTokenKind.InterpolatedString)
|
||||
return false;
|
||||
|
||||
string text = context.Current.Text;
|
||||
int end = text.Length;
|
||||
if (end >= 2 && text[end - 1] == '`')
|
||||
end--;
|
||||
string content = text.Substring(1, end - 1);
|
||||
|
||||
var pieces = new List<string>();
|
||||
var literal = new StringBuilder();
|
||||
int i = 0;
|
||||
while (i < content.Length)
|
||||
{
|
||||
char c = content[i];
|
||||
if (c == '\\' && i + 1 < content.Length)
|
||||
{
|
||||
literal.Append(content[i]);
|
||||
literal.Append(content[i + 1]);
|
||||
i += 2;
|
||||
continue;
|
||||
}
|
||||
if (c == '{')
|
||||
{
|
||||
int close = FindClosingBrace(content, i + 1);
|
||||
if (close < 0)
|
||||
{
|
||||
literal.Append(c);
|
||||
i++;
|
||||
continue;
|
||||
}
|
||||
string expression = content.Substring(i + 1, close - i - 1).Trim();
|
||||
if (expression.Length > 0)
|
||||
{
|
||||
FlushLiteral(pieces, literal);
|
||||
pieces.Add($"tostring({LuaSyntaxExtensions.Rewrite(expression)})");
|
||||
}
|
||||
i = close + 1;
|
||||
continue;
|
||||
}
|
||||
literal.Append(c);
|
||||
i++;
|
||||
}
|
||||
FlushLiteral(pieces, literal);
|
||||
|
||||
context.Advance();
|
||||
if (pieces.Count == 0)
|
||||
{
|
||||
context.EmitRaw("\"\"");
|
||||
return true;
|
||||
}
|
||||
if (pieces.Count == 1)
|
||||
{
|
||||
context.EmitRaw(pieces[0]);
|
||||
return true;
|
||||
}
|
||||
context.EmitRaw($"({string.Join(" .. ", pieces)})");
|
||||
return true;
|
||||
}
|
||||
|
||||
private static void FlushLiteral(List<string> pieces, StringBuilder literal)
|
||||
{
|
||||
if (literal.Length == 0)
|
||||
return;
|
||||
pieces.Add($"\"{literal.ToString().Replace("\"", "\\\"")}\"");
|
||||
literal.Clear();
|
||||
}
|
||||
|
||||
private static int FindClosingBrace(string content, int from)
|
||||
{
|
||||
int depth = 0;
|
||||
char quote = '\0';
|
||||
for (int i = from; i < content.Length; i++)
|
||||
{
|
||||
char c = content[i];
|
||||
if (quote != '\0')
|
||||
{
|
||||
if (c == '\\')
|
||||
{
|
||||
i++;
|
||||
continue;
|
||||
}
|
||||
if (c == quote)
|
||||
quote = '\0';
|
||||
continue;
|
||||
}
|
||||
if (c == '"' || c == '\'')
|
||||
{
|
||||
quote = c;
|
||||
continue;
|
||||
}
|
||||
if (c == '{')
|
||||
{
|
||||
depth++;
|
||||
continue;
|
||||
}
|
||||
if (c == '}')
|
||||
{
|
||||
if (depth == 0)
|
||||
return i;
|
||||
depth--;
|
||||
}
|
||||
}
|
||||
return -1;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,74 @@
|
||||
namespace LuaScript.Compat.Syntax.Rules
|
||||
{
|
||||
[LuaSyntaxRule(35)]
|
||||
internal sealed class LuaLambdaRule : ILuaSyntaxRule
|
||||
{
|
||||
public bool TryApply(LuaRewriteContext context)
|
||||
{
|
||||
if (!context.Current.IsOperator("=>"))
|
||||
return false;
|
||||
if (!context.TryReadTrailingLvalue(out int start, out string target))
|
||||
return false;
|
||||
if (!TryNormalizeParameters(target, out string parameters))
|
||||
return false;
|
||||
|
||||
int body = context.NextSignificant(context.Index + 1);
|
||||
if (body < 0 || !LuaSyntaxFacts.IsValueStart(context.Input[body]))
|
||||
return false;
|
||||
|
||||
context.RemoveOutputFrom(start);
|
||||
context.Advance();
|
||||
string expression = context.ReadForwardOrOperand();
|
||||
if (expression.Length == 0)
|
||||
return false;
|
||||
|
||||
context.EmitRaw($"(function({parameters}) return {LuaSyntaxExtensions.Rewrite(expression)} end)");
|
||||
return true;
|
||||
}
|
||||
|
||||
private static bool TryNormalizeParameters(string text, out string parameters)
|
||||
{
|
||||
parameters = string.Empty;
|
||||
text = text.Trim();
|
||||
bool wrapped = text.StartsWith("(") && text.EndsWith(")");
|
||||
if (wrapped)
|
||||
text = text.Substring(1, text.Length - 2).Trim();
|
||||
|
||||
if (text.Length == 0)
|
||||
return wrapped;
|
||||
|
||||
var names = text.Split(',');
|
||||
for (int i = 0; i < names.Length; i++)
|
||||
{
|
||||
string name = names[i].Trim();
|
||||
if (name == "...")
|
||||
{
|
||||
if (i != names.Length - 1)
|
||||
return false;
|
||||
continue;
|
||||
}
|
||||
if (!IsName(name) || LuaKeywords.IsReserved(name))
|
||||
return false;
|
||||
if (!wrapped && names.Length > 1)
|
||||
return false;
|
||||
}
|
||||
|
||||
parameters = string.Join(", ", System.Array.ConvertAll(names, static n => n.Trim()));
|
||||
return true;
|
||||
}
|
||||
|
||||
private static bool IsName(string text)
|
||||
{
|
||||
if (text.Length == 0)
|
||||
return false;
|
||||
if (text[0] != '_' && !char.IsLetter(text[0]))
|
||||
return false;
|
||||
for (int i = 1; i < text.Length; i++)
|
||||
{
|
||||
if (text[i] != '_' && !char.IsLetterOrDigit(text[i]))
|
||||
return false;
|
||||
}
|
||||
return true;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,7 +1,3 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Text;
|
||||
|
||||
namespace LuaScript.Compat.Syntax.Rules
|
||||
{
|
||||
[LuaSyntaxRule(110)]
|
||||
@@ -15,113 +11,16 @@ namespace LuaScript.Compat.Syntax.Rules
|
||||
int open = context.NextSignificant(context.Index + 1);
|
||||
if (open < 0 || !context.Input[open].IsOperator("<"))
|
||||
return false;
|
||||
if (!TryParseRange(context.Input, open, out string replacement, out int end))
|
||||
if (!LuaRangeSyntax.TryParse(context.Input, open, out var parts, out int end))
|
||||
return false;
|
||||
|
||||
string stopExpression = parts.Exclusive ? $"({parts.Stop}) - 1" : parts.Stop;
|
||||
string replacement = parts.Step is null
|
||||
? $"= {parts.Start}, {stopExpression}"
|
||||
: $"= {parts.Start}, {stopExpression}, {parts.Step}";
|
||||
context.EmitRaw(replacement);
|
||||
context.Index = end;
|
||||
return true;
|
||||
}
|
||||
|
||||
private static bool TryParseRange(IReadOnlyList<LuaSyntaxToken> input, int open, out string replacement, out int end)
|
||||
{
|
||||
replacement = string.Empty;
|
||||
end = open;
|
||||
|
||||
int position = open + 1;
|
||||
if (!TryReadSegment(input, ref position, "..", ">", out string start, out string startTerminator) || startTerminator != "..")
|
||||
return false;
|
||||
|
||||
bool exclusive = false;
|
||||
int caret = NextSignificant(input, position);
|
||||
if (caret >= 0 && input[caret].IsOperator("<"))
|
||||
{
|
||||
exclusive = true;
|
||||
position = caret + 1;
|
||||
}
|
||||
|
||||
if (!TryReadSegment(input, ref position, ",", ">", out string stop, out string stopTerminator))
|
||||
return false;
|
||||
|
||||
string? step = null;
|
||||
if (stopTerminator == ",")
|
||||
{
|
||||
if (!TryReadSegment(input, ref position, ">", ">", out string stepText, out string stepTerminator) || stepTerminator != ">")
|
||||
return false;
|
||||
step = stepText;
|
||||
}
|
||||
else if (stopTerminator != ">")
|
||||
{
|
||||
return false;
|
||||
}
|
||||
|
||||
if (start.Length == 0 || stop.Length == 0 || (step is not null && step.Length == 0))
|
||||
return false;
|
||||
|
||||
string stopExpression = exclusive ? $"({stop}) - 1" : stop;
|
||||
replacement = step is null ? $"= {start}, {stopExpression}" : $"= {start}, {stopExpression}, {step}";
|
||||
end = position;
|
||||
return true;
|
||||
}
|
||||
|
||||
private static bool TryReadSegment(IReadOnlyList<LuaSyntaxToken> input, ref int position, string primaryStop, string secondaryStop, out string text, out string terminator)
|
||||
{
|
||||
text = string.Empty;
|
||||
terminator = string.Empty;
|
||||
int start = position;
|
||||
int depth = 0;
|
||||
int count = input.Count;
|
||||
|
||||
while (position < count)
|
||||
{
|
||||
var token = input[position];
|
||||
if (token.Kind == LuaSyntaxTokenKind.Newline && depth == 0)
|
||||
return false;
|
||||
if (token.Kind == LuaSyntaxTokenKind.Operator)
|
||||
{
|
||||
if (token.Text is "(" or "[" or "{")
|
||||
{
|
||||
depth++;
|
||||
}
|
||||
else if (token.Text is ")" or "]" or "}")
|
||||
{
|
||||
if (depth == 0)
|
||||
return false;
|
||||
depth--;
|
||||
}
|
||||
else if (depth == 0 && (token.Text == primaryStop || token.Text == secondaryStop))
|
||||
{
|
||||
terminator = token.Text;
|
||||
text = Trim(input, start, position);
|
||||
position++;
|
||||
return true;
|
||||
}
|
||||
}
|
||||
position++;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
private static int NextSignificant(IReadOnlyList<LuaSyntaxToken> input, int from)
|
||||
{
|
||||
for (int i = from; i < input.Count; i++)
|
||||
{
|
||||
if (!input[i].IsTrivia)
|
||||
return i;
|
||||
}
|
||||
return -1;
|
||||
}
|
||||
|
||||
private static string Trim(IReadOnlyList<LuaSyntaxToken> input, int begin, int end)
|
||||
{
|
||||
while (begin < end && input[begin].IsTrivia)
|
||||
begin++;
|
||||
while (end > begin && input[end - 1].IsTrivia)
|
||||
end--;
|
||||
var builder = new StringBuilder();
|
||||
for (int i = begin; i < end; i++)
|
||||
builder.Append(input[i].Text);
|
||||
return builder.ToString();
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,122 @@
|
||||
using System.Collections.Generic;
|
||||
using System.Text;
|
||||
|
||||
namespace LuaScript.Compat.Syntax.Rules
|
||||
{
|
||||
[LuaSyntaxRule(98)]
|
||||
internal sealed class LuaPipeRule : ILuaSyntaxRule
|
||||
{
|
||||
public bool TryApply(LuaRewriteContext context)
|
||||
{
|
||||
if (!context.Current.IsOperator("|>"))
|
||||
return false;
|
||||
|
||||
int targetStart = context.NextSignificant(context.Index + 1);
|
||||
if (targetStart < 0 || !LuaSyntaxFacts.IsValueStart(context.Input[targetStart]))
|
||||
return false;
|
||||
|
||||
if (!context.TryPopOrOperand(out string left))
|
||||
return false;
|
||||
|
||||
context.Advance();
|
||||
var segment = ReadSegment(context);
|
||||
string call = BuildCall(segment, left);
|
||||
context.EmitRaw(call);
|
||||
return true;
|
||||
}
|
||||
|
||||
private static List<LuaSyntaxToken> ReadSegment(LuaRewriteContext context)
|
||||
{
|
||||
var tokens = new List<LuaSyntaxToken>();
|
||||
int depth = 0;
|
||||
while (!context.AtEnd)
|
||||
{
|
||||
var token = context.Current;
|
||||
if (token.Kind == LuaSyntaxTokenKind.Newline && depth == 0)
|
||||
break;
|
||||
if (token.Kind == LuaSyntaxTokenKind.Name && depth == 0 && LuaKeywords.IsExpressionBoundary(token.Text))
|
||||
break;
|
||||
if (token.Kind == LuaSyntaxTokenKind.Operator)
|
||||
{
|
||||
if (token.Text is "(" or "[" or "{")
|
||||
{
|
||||
depth++;
|
||||
}
|
||||
else if (token.Text is ")" or "]" or "}")
|
||||
{
|
||||
if (depth == 0)
|
||||
break;
|
||||
depth--;
|
||||
}
|
||||
else if (depth == 0 && token.Text is "," or ";" or "|>")
|
||||
{
|
||||
break;
|
||||
}
|
||||
}
|
||||
tokens.Add(token);
|
||||
context.Advance();
|
||||
}
|
||||
while (tokens.Count > 0 && tokens[0].IsTrivia)
|
||||
tokens.RemoveAt(0);
|
||||
while (tokens.Count > 0 && tokens[tokens.Count - 1].IsTrivia)
|
||||
tokens.RemoveAt(tokens.Count - 1);
|
||||
return tokens;
|
||||
}
|
||||
|
||||
private static string BuildCall(List<LuaSyntaxToken> segment, string left)
|
||||
{
|
||||
string argument = $"({left})";
|
||||
if (segment.Count == 0)
|
||||
return argument;
|
||||
|
||||
if (segment[segment.Count - 1].IsOperator(")"))
|
||||
{
|
||||
int open = FindOpeningParen(segment);
|
||||
if (open > 0)
|
||||
{
|
||||
string callee = Concat(segment, 0, open);
|
||||
string arguments = Concat(segment, open + 1, segment.Count - 1);
|
||||
return arguments.Length == 0
|
||||
? $"{callee}({argument})"
|
||||
: $"{callee}({argument}, {arguments})";
|
||||
}
|
||||
}
|
||||
|
||||
return $"{Concat(segment, 0, segment.Count)}({argument})";
|
||||
}
|
||||
|
||||
private static int FindOpeningParen(List<LuaSyntaxToken> segment)
|
||||
{
|
||||
int depth = 0;
|
||||
for (int i = segment.Count - 1; i >= 0; i--)
|
||||
{
|
||||
var token = segment[i];
|
||||
if (token.Kind != LuaSyntaxTokenKind.Operator)
|
||||
continue;
|
||||
if (token.Text is ")" or "]" or "}")
|
||||
{
|
||||
depth++;
|
||||
}
|
||||
else if (token.Text is "(" or "[" or "{")
|
||||
{
|
||||
depth--;
|
||||
if (depth == 0)
|
||||
return token.Text == "(" ? i : -1;
|
||||
}
|
||||
}
|
||||
return -1;
|
||||
}
|
||||
|
||||
private static string Concat(List<LuaSyntaxToken> segment, int begin, int end)
|
||||
{
|
||||
while (begin < end && segment[begin].IsTrivia)
|
||||
begin++;
|
||||
while (end > begin && segment[end - 1].IsTrivia)
|
||||
end--;
|
||||
var builder = new StringBuilder();
|
||||
for (int i = begin; i < end; i++)
|
||||
builder.Append(segment[i].Text);
|
||||
return builder.ToString();
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,49 @@
|
||||
namespace LuaScript.Compat.Syntax.Rules
|
||||
{
|
||||
[LuaSyntaxRule(108)]
|
||||
internal sealed class LuaRangeMembershipRule : ILuaSyntaxRule
|
||||
{
|
||||
public bool TryApply(LuaRewriteContext context)
|
||||
{
|
||||
if (!context.Current.IsName("in"))
|
||||
return false;
|
||||
if (IsForHeader(context))
|
||||
return false;
|
||||
|
||||
int open = context.NextSignificant(context.Index + 1);
|
||||
if (open < 0 || !context.Input[open].IsOperator("<"))
|
||||
return false;
|
||||
if (!LuaRangeSyntax.TryParse(context.Input, open, out var parts, out int end))
|
||||
return false;
|
||||
if (parts.Step is not null)
|
||||
return false;
|
||||
|
||||
if (!context.TryPopOrOperand(out string left))
|
||||
return false;
|
||||
|
||||
string temporary = context.NextTemporary();
|
||||
string upper = parts.Exclusive ? "<" : "<=";
|
||||
context.EmitRaw($"(function() local {temporary} = ({left}) return {temporary} >= ({LuaSyntaxExtensions.Rewrite(parts.Start)}) and {temporary} {upper} ({LuaSyntaxExtensions.Rewrite(parts.Stop)}) end)()");
|
||||
context.Index = end;
|
||||
return true;
|
||||
}
|
||||
|
||||
private static bool IsForHeader(LuaRewriteContext context)
|
||||
{
|
||||
var output = context.Output;
|
||||
for (int i = output.Count - 1; i >= 0; i--)
|
||||
{
|
||||
var token = output[i];
|
||||
if (token.Kind == LuaSyntaxTokenKind.Newline)
|
||||
return false;
|
||||
if (token.Kind != LuaSyntaxTokenKind.Name)
|
||||
continue;
|
||||
if (token.Text is "do" or "then")
|
||||
return false;
|
||||
if (token.Text == "for")
|
||||
return true;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,105 @@
|
||||
using System.Text;
|
||||
|
||||
namespace LuaScript.Compat.Syntax.Rules
|
||||
{
|
||||
[LuaSyntaxRule(92)]
|
||||
internal sealed class LuaSafeNavigationRule : ILuaSyntaxRule
|
||||
{
|
||||
public bool TryApply(LuaRewriteContext context)
|
||||
{
|
||||
if (!context.Current.IsOperator("?"))
|
||||
return false;
|
||||
|
||||
int accessor = context.NextSignificantSameLine(context.Index + 1);
|
||||
if (accessor < 0)
|
||||
return false;
|
||||
|
||||
if (context.Input[accessor].IsOperator("."))
|
||||
return TryApplyMember(context, accessor);
|
||||
if (context.Input[accessor].IsOperator("["))
|
||||
return TryApplyIndex(context, accessor);
|
||||
return false;
|
||||
}
|
||||
|
||||
private static bool TryApplyMember(LuaRewriteContext context, int accessor)
|
||||
{
|
||||
int name = context.NextSignificantSameLine(accessor + 1);
|
||||
if (name < 0)
|
||||
return false;
|
||||
var token = context.Input[name];
|
||||
if (token.Kind != LuaSyntaxTokenKind.Name || LuaKeywords.IsReserved(token.Text))
|
||||
return false;
|
||||
|
||||
if (!context.TryReadTrailingLvalue(out int start, out string target))
|
||||
return false;
|
||||
|
||||
context.RemoveOutputFrom(start);
|
||||
context.Index = name + 1;
|
||||
string temporary = context.NextTemporary();
|
||||
context.EmitRaw($"(function() local {temporary} = ({target}) if {temporary} == nil then return nil end return {temporary}.{token.Text} end)()");
|
||||
return true;
|
||||
}
|
||||
|
||||
private static bool TryApplyIndex(LuaRewriteContext context, int accessor)
|
||||
{
|
||||
int close = FindClosingBracket(context, accessor + 1);
|
||||
if (close < 0)
|
||||
return false;
|
||||
|
||||
string key = Concat(context, accessor + 1, close);
|
||||
if (key.Length == 0)
|
||||
return false;
|
||||
|
||||
if (!context.TryReadTrailingLvalue(out int start, out string target))
|
||||
return false;
|
||||
|
||||
context.RemoveOutputFrom(start);
|
||||
context.Index = close + 1;
|
||||
string temporary = context.NextTemporary();
|
||||
context.EmitRaw($"(function() local {temporary} = ({target}) if {temporary} == nil then return nil end return {temporary}[{LuaSyntaxExtensions.Rewrite(key)}] end)()");
|
||||
return true;
|
||||
}
|
||||
|
||||
private static int FindClosingBracket(LuaRewriteContext context, int from)
|
||||
{
|
||||
int depth = 0;
|
||||
for (int i = from; i < context.Input.Count; i++)
|
||||
{
|
||||
var token = context.Input[i];
|
||||
if (token.Kind != LuaSyntaxTokenKind.Operator)
|
||||
continue;
|
||||
if (token.Text is "(" or "[" or "{")
|
||||
{
|
||||
depth++;
|
||||
continue;
|
||||
}
|
||||
if (token.Text is ")" or "}")
|
||||
{
|
||||
if (depth == 0)
|
||||
return -1;
|
||||
depth--;
|
||||
continue;
|
||||
}
|
||||
if (token.Text == "]")
|
||||
{
|
||||
if (depth == 0)
|
||||
return i;
|
||||
depth--;
|
||||
}
|
||||
}
|
||||
return -1;
|
||||
}
|
||||
|
||||
private static string Concat(LuaRewriteContext context, int begin, int end)
|
||||
{
|
||||
while (begin < end && context.Input[begin].IsTrivia)
|
||||
begin++;
|
||||
while (end > begin && context.Input[end - 1].IsTrivia)
|
||||
end--;
|
||||
var builder = new StringBuilder();
|
||||
for (int i = begin; i < end; i++)
|
||||
builder.Append(context.Input[i].Text);
|
||||
return builder.ToString();
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,85 @@
|
||||
namespace LuaScript.Compat.Syntax.Rules
|
||||
{
|
||||
[LuaSyntaxRule(96)]
|
||||
internal sealed class LuaTernaryRule : ILuaSyntaxRule
|
||||
{
|
||||
public bool TryApply(LuaRewriteContext context)
|
||||
{
|
||||
if (!context.Current.IsOperator("?"))
|
||||
return false;
|
||||
if (!context.TryPreviousOutputSignificantSameLine(out var previous) || !LuaSyntaxFacts.IsValueEnd(previous))
|
||||
return false;
|
||||
|
||||
int thenStart = context.NextSignificantSameLine(context.Index + 1);
|
||||
if (thenStart < 0 || !LuaSyntaxFacts.IsValueStart(context.Input[thenStart]))
|
||||
return false;
|
||||
|
||||
int colon = FindColon(context, context.Index + 1);
|
||||
if (colon < 0)
|
||||
return false;
|
||||
|
||||
int elseStart = context.NextSignificantSameLine(colon + 1);
|
||||
if (elseStart < 0 || !LuaSyntaxFacts.IsValueStart(context.Input[elseStart]))
|
||||
return false;
|
||||
|
||||
if (!context.TryPopOrOperand(out string condition))
|
||||
return false;
|
||||
|
||||
context.Index++;
|
||||
string thenExpression = ReadUntil(context, colon);
|
||||
context.Index = colon + 1;
|
||||
string elseExpression = context.ReadForwardOrOperand();
|
||||
|
||||
context.EmitRaw($"(function() if {condition} then return ({LuaSyntaxExtensions.Rewrite(thenExpression)}) else return ({LuaSyntaxExtensions.Rewrite(elseExpression)}) end end)()");
|
||||
return true;
|
||||
}
|
||||
|
||||
private static int FindColon(LuaRewriteContext context, int from)
|
||||
{
|
||||
int depth = 0;
|
||||
for (int i = from; i < context.Input.Count; i++)
|
||||
{
|
||||
var token = context.Input[i];
|
||||
if (token.Kind == LuaSyntaxTokenKind.Newline)
|
||||
return -1;
|
||||
if (token.Kind == LuaSyntaxTokenKind.Name && depth == 0 && LuaKeywords.IsExpressionBoundary(token.Text))
|
||||
return -1;
|
||||
if (token.Kind != LuaSyntaxTokenKind.Operator)
|
||||
continue;
|
||||
if (token.Text is "(" or "[" or "{")
|
||||
{
|
||||
depth++;
|
||||
continue;
|
||||
}
|
||||
if (token.Text is ")" or "]" or "}")
|
||||
{
|
||||
if (depth == 0)
|
||||
return -1;
|
||||
depth--;
|
||||
continue;
|
||||
}
|
||||
if (depth > 0)
|
||||
continue;
|
||||
if (token.Text is "," or ";" or "?")
|
||||
return -1;
|
||||
if (token.Text == ":")
|
||||
return i;
|
||||
}
|
||||
return -1;
|
||||
}
|
||||
|
||||
private static string ReadUntil(LuaRewriteContext context, int stop)
|
||||
{
|
||||
var builder = new System.Text.StringBuilder();
|
||||
int begin = context.Index;
|
||||
int end = stop;
|
||||
while (begin < end && context.Input[begin].IsTrivia)
|
||||
begin++;
|
||||
while (end > begin && context.Input[end - 1].IsTrivia)
|
||||
end--;
|
||||
for (int i = begin; i < end; i++)
|
||||
builder.Append(context.Input[i].Text);
|
||||
return builder.ToString();
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,8 @@
|
||||
namespace LuaScript.Generator
|
||||
{
|
||||
internal sealed record GpuShaderClass(
|
||||
string Namespace,
|
||||
EquatableArray<GpuShaderTypePart> TypeChain,
|
||||
EquatableArray<GpuShaderMethod> Methods,
|
||||
EquatableArray<string> Errors);
|
||||
}
|
||||
@@ -0,0 +1,4 @@
|
||||
namespace LuaScript.Generator
|
||||
{
|
||||
internal sealed record GpuShaderFile(string Path, string Source);
|
||||
}
|
||||
@@ -0,0 +1,4 @@
|
||||
namespace LuaScript.Generator
|
||||
{
|
||||
internal sealed record GpuShaderInvocation(string Resources, string Constants, string Target, string Width, string Height);
|
||||
}
|
||||
@@ -0,0 +1,12 @@
|
||||
namespace LuaScript.Generator
|
||||
{
|
||||
internal sealed record GpuShaderMethod(
|
||||
string Accessibility,
|
||||
bool IsStatic,
|
||||
string ReturnType,
|
||||
string MethodName,
|
||||
EquatableArray<GpuShaderParameter> Parameters,
|
||||
string FileName,
|
||||
string EntryPoint,
|
||||
GpuShaderInvocation Invocation);
|
||||
}
|
||||
@@ -0,0 +1,4 @@
|
||||
namespace LuaScript.Generator
|
||||
{
|
||||
internal sealed record GpuShaderMethodSource(GpuShaderMethod Method, string Bytecode);
|
||||
}
|
||||
@@ -0,0 +1,4 @@
|
||||
namespace LuaScript.Generator
|
||||
{
|
||||
internal sealed record GpuShaderParameter(string Prefix, string Type, string Name);
|
||||
}
|
||||
@@ -0,0 +1,6 @@
|
||||
using System.Collections.Immutable;
|
||||
|
||||
namespace LuaScript.Generator
|
||||
{
|
||||
internal sealed record GpuShaderResolution(ImmutableArray<GpuShaderMethodSource> Methods, ImmutableArray<string> Errors);
|
||||
}
|
||||
@@ -0,0 +1,436 @@
|
||||
using System.Collections.Immutable;
|
||||
using System.Globalization;
|
||||
using System.IO;
|
||||
using System.Text;
|
||||
using Microsoft.CodeAnalysis;
|
||||
using Microsoft.CodeAnalysis.CSharp.Syntax;
|
||||
using Microsoft.CodeAnalysis.Text;
|
||||
|
||||
namespace LuaScript.Generator
|
||||
{
|
||||
[Generator]
|
||||
public sealed class GpuShaderSourceGenerator : IIncrementalGenerator
|
||||
{
|
||||
private const string AttributeName = "LuaScript.Engine.Processing.GpuPixelOperationShaderAttribute";
|
||||
|
||||
public void Initialize(IncrementalGeneratorInitializationContext context)
|
||||
{
|
||||
var classes = context.SyntaxProvider
|
||||
.CreateSyntaxProvider(
|
||||
static (node, _) => node is ClassDeclarationSyntax { AttributeLists.Count: > 0 },
|
||||
static (ctx, _) => CreateClass(ctx))
|
||||
.Where(static model => model is not null)
|
||||
.Select(static (model, _) => model!);
|
||||
|
||||
var files = context.AdditionalTextsProvider
|
||||
.Where(static file => file.Path.EndsWith(".hlsl", StringComparison.OrdinalIgnoreCase))
|
||||
.Select(static (file, token) => new GpuShaderFile(Normalize(file.Path), file.GetText(token)?.ToString() ?? string.Empty))
|
||||
.Collect()
|
||||
.Select(static (items, _) => new EquatableArray<GpuShaderFile>([.. items]));
|
||||
|
||||
context.RegisterSourceOutput(classes.Combine(files), static (context, source) =>
|
||||
{
|
||||
var (model, files) = source;
|
||||
var resolved = Resolve(model, files);
|
||||
if (resolved.Errors.Length > 0)
|
||||
{
|
||||
context.AddSource(ErrorHintName(model), SourceText.From(EmitErrors(resolved.Errors), Encoding.UTF8));
|
||||
return;
|
||||
}
|
||||
|
||||
context.AddSource(HintName(model), SourceText.From(Emit(model, resolved.Methods), Encoding.UTF8));
|
||||
});
|
||||
}
|
||||
|
||||
private static GpuShaderClass? CreateClass(GeneratorSyntaxContext context)
|
||||
{
|
||||
if (context.Node is not ClassDeclarationSyntax declaration)
|
||||
return null;
|
||||
if (context.SemanticModel.GetDeclaredSymbol(declaration) is not INamedTypeSymbol type)
|
||||
return null;
|
||||
|
||||
var attributes = type.GetAttributes()
|
||||
.Where(static attribute => attribute.AttributeClass?.ToDisplayString() == AttributeName)
|
||||
.ToArray();
|
||||
if (attributes.Length == 0)
|
||||
return null;
|
||||
|
||||
var chain = new List<GpuShaderTypePart>();
|
||||
for (var current = type; current is not null; current = current.ContainingType)
|
||||
chain.Insert(0, new GpuShaderTypePart(current.Name, current.IsStatic));
|
||||
|
||||
var methods = ImmutableArray.CreateBuilder<GpuShaderMethod>();
|
||||
var errors = ImmutableArray.CreateBuilder<string>();
|
||||
|
||||
foreach (var attribute in attributes)
|
||||
{
|
||||
if (attribute.ConstructorArguments.Length < 3 ||
|
||||
attribute.ConstructorArguments[0].Value is not string methodName ||
|
||||
attribute.ConstructorArguments[1].Value is not string fileName ||
|
||||
attribute.ConstructorArguments[2].Value is not string entryPoint)
|
||||
{
|
||||
errors.Add("GPU shader attribute arguments are invalid");
|
||||
continue;
|
||||
}
|
||||
|
||||
var candidates = type.GetMembers(methodName).OfType<IMethodSymbol>().ToArray();
|
||||
if (candidates.Length == 0)
|
||||
{
|
||||
errors.Add($"GPU shader method '{methodName}' was not found");
|
||||
continue;
|
||||
}
|
||||
if (candidates.Length > 1)
|
||||
{
|
||||
errors.Add($"GPU shader method '{methodName}' is ambiguous");
|
||||
continue;
|
||||
}
|
||||
|
||||
var method = candidates[0];
|
||||
string? error = Validate(method, fileName, entryPoint, out var invocation);
|
||||
if (error is not null)
|
||||
{
|
||||
errors.Add($"GPU shader method '{methodName}': {error}");
|
||||
continue;
|
||||
}
|
||||
|
||||
var parameters = ImmutableArray.CreateBuilder<GpuShaderParameter>();
|
||||
foreach (var parameter in method.Parameters)
|
||||
parameters.Add(new GpuShaderParameter(ParameterPrefix(parameter), parameter.Type.ToDisplayString(SymbolDisplayFormat.FullyQualifiedFormat), parameter.Name));
|
||||
|
||||
methods.Add(new GpuShaderMethod(
|
||||
AccessibilityName(method.DeclaredAccessibility),
|
||||
method.IsStatic,
|
||||
method.ReturnType.ToDisplayString(SymbolDisplayFormat.FullyQualifiedFormat),
|
||||
method.Name,
|
||||
new EquatableArray<GpuShaderParameter>([.. parameters]),
|
||||
Normalize(fileName),
|
||||
entryPoint,
|
||||
invocation));
|
||||
}
|
||||
|
||||
return new GpuShaderClass(
|
||||
type.ContainingNamespace.IsGlobalNamespace ? string.Empty : type.ContainingNamespace.ToDisplayString(),
|
||||
new EquatableArray<GpuShaderTypePart>([.. chain]),
|
||||
new EquatableArray<GpuShaderMethod>([.. methods]),
|
||||
new EquatableArray<string>([.. errors]));
|
||||
}
|
||||
|
||||
private static string? Validate(IMethodSymbol method, string fileName, string entryPoint, out GpuShaderInvocation invocation)
|
||||
{
|
||||
invocation = new GpuShaderInvocation(string.Empty, string.Empty, string.Empty, string.Empty, string.Empty);
|
||||
if (string.IsNullOrWhiteSpace(fileName))
|
||||
return "file name is empty";
|
||||
if (string.IsNullOrWhiteSpace(entryPoint))
|
||||
return "entry point is empty";
|
||||
if (method.ReturnType.SpecialType != SpecialType.System_Boolean)
|
||||
return "return type must be bool";
|
||||
|
||||
var parameters = method.Parameters;
|
||||
if (parameters.Length == 4 &&
|
||||
IsReadOnlySpanSingle(parameters[0].Type) &&
|
||||
IsByteArray(parameters[1].Type) &&
|
||||
IsInt32(parameters[2].Type) &&
|
||||
IsInt32(parameters[3].Type))
|
||||
{
|
||||
invocation = new GpuShaderInvocation("[]", parameters[0].Name, parameters[1].Name, parameters[2].Name, parameters[3].Name);
|
||||
return null;
|
||||
}
|
||||
|
||||
if (parameters.Length == 5 &&
|
||||
IsReadOnlySpanPixelShaderInput(parameters[0].Type) &&
|
||||
IsReadOnlySpanSingle(parameters[1].Type) &&
|
||||
IsByteArray(parameters[2].Type) &&
|
||||
IsInt32(parameters[3].Type) &&
|
||||
IsInt32(parameters[4].Type))
|
||||
{
|
||||
invocation = new GpuShaderInvocation(parameters[0].Name, parameters[1].Name, parameters[2].Name, parameters[3].Name, parameters[4].Name);
|
||||
return null;
|
||||
}
|
||||
|
||||
return "signature is invalid";
|
||||
}
|
||||
|
||||
private static GpuShaderResolution Resolve(GpuShaderClass model, EquatableArray<GpuShaderFile> files)
|
||||
{
|
||||
var methods = ImmutableArray.CreateBuilder<GpuShaderMethodSource>();
|
||||
var errors = ImmutableArray.CreateBuilder<string>();
|
||||
errors.AddRange(model.Errors);
|
||||
|
||||
foreach (var method in model.Methods)
|
||||
{
|
||||
var matched = files.Where(file => Matches(file.Path, method.FileName)).ToArray();
|
||||
if (matched.Length == 0)
|
||||
{
|
||||
errors.Add($"GPU shader file '{method.FileName}' for method '{method.MethodName}' was not found");
|
||||
continue;
|
||||
}
|
||||
if (matched.Length > 1)
|
||||
{
|
||||
errors.Add($"GPU shader file '{method.FileName}' for method '{method.MethodName}' matched multiple additional files");
|
||||
continue;
|
||||
}
|
||||
|
||||
string? failure = ShaderCompiler.Compile(matched[0].Source, method.EntryPoint, out string bytecode);
|
||||
if (failure is not null)
|
||||
{
|
||||
errors.Add($"GPU shader method '{method.MethodName}' failed to compile: {failure}");
|
||||
continue;
|
||||
}
|
||||
|
||||
methods.Add(new GpuShaderMethodSource(method, bytecode));
|
||||
}
|
||||
|
||||
return new GpuShaderResolution([.. methods], [.. errors]);
|
||||
}
|
||||
|
||||
private static bool Matches(string filePath, string registrationPath)
|
||||
{
|
||||
if (string.Equals(filePath, registrationPath, StringComparison.OrdinalIgnoreCase))
|
||||
return true;
|
||||
return filePath.EndsWith("/" + registrationPath, StringComparison.OrdinalIgnoreCase);
|
||||
}
|
||||
|
||||
private static bool IsReadOnlySpanSingle(ITypeSymbol type)
|
||||
{
|
||||
return type is INamedTypeSymbol named &&
|
||||
named.OriginalDefinition.ToDisplayString() == "System.ReadOnlySpan<T>" &&
|
||||
named.TypeArguments.Length == 1 &&
|
||||
named.TypeArguments[0].SpecialType == SpecialType.System_Single;
|
||||
}
|
||||
|
||||
private static bool IsReadOnlySpanPixelShaderInput(ITypeSymbol type)
|
||||
{
|
||||
string display = type.ToDisplayString(SymbolDisplayFormat.FullyQualifiedFormat);
|
||||
return display.Contains("ReadOnlySpan", StringComparison.Ordinal) &&
|
||||
display.Contains("PixelShaderInput", StringComparison.Ordinal);
|
||||
}
|
||||
|
||||
private static bool IsByteArray(ITypeSymbol type)
|
||||
{
|
||||
return type is IArrayTypeSymbol array &&
|
||||
array.Rank == 1 &&
|
||||
array.ElementType.SpecialType == SpecialType.System_Byte;
|
||||
}
|
||||
|
||||
private static bool IsInt32(ITypeSymbol type) => type.SpecialType == SpecialType.System_Int32;
|
||||
|
||||
private static string Normalize(string path) => path.Replace(Path.DirectorySeparatorChar, '/').Replace(Path.AltDirectorySeparatorChar, '/');
|
||||
|
||||
private static string AccessibilityName(Accessibility accessibility)
|
||||
{
|
||||
return accessibility switch
|
||||
{
|
||||
Accessibility.Public => "public",
|
||||
Accessibility.Internal => "internal",
|
||||
Accessibility.Protected => "protected",
|
||||
Accessibility.ProtectedAndInternal => "private protected",
|
||||
Accessibility.ProtectedOrInternal => "protected internal",
|
||||
_ => "private",
|
||||
};
|
||||
}
|
||||
|
||||
private static string ParameterPrefix(IParameterSymbol parameter)
|
||||
{
|
||||
return parameter.RefKind switch
|
||||
{
|
||||
RefKind.In => "in ",
|
||||
RefKind.Ref => "ref ",
|
||||
RefKind.Out => "out ",
|
||||
_ => string.Empty,
|
||||
};
|
||||
}
|
||||
|
||||
private static string Emit(GpuShaderClass model, ImmutableArray<GpuShaderMethodSource> sources)
|
||||
{
|
||||
var builder = new StringBuilder();
|
||||
builder.AppendLine("#nullable enable");
|
||||
if (model.Namespace.Length > 0)
|
||||
{
|
||||
builder.AppendLine("namespace " + model.Namespace);
|
||||
builder.AppendLine("{");
|
||||
}
|
||||
|
||||
int indent = model.Namespace.Length > 0 ? 1 : 0;
|
||||
foreach (var type in model.TypeChain)
|
||||
{
|
||||
AppendIndent(builder, indent);
|
||||
builder.Append(type.IsStatic ? "static partial class " : "partial class ");
|
||||
builder.AppendLine(type.Name);
|
||||
AppendIndent(builder, indent);
|
||||
builder.AppendLine("{");
|
||||
indent++;
|
||||
}
|
||||
|
||||
for (int i = 0; i < sources.Length; i++)
|
||||
{
|
||||
if (i > 0)
|
||||
builder.AppendLine();
|
||||
EmitMethod(builder, indent, sources[i]);
|
||||
}
|
||||
|
||||
for (int i = model.TypeChain.Count - 1; i >= 0; i--)
|
||||
{
|
||||
indent--;
|
||||
AppendIndent(builder, indent);
|
||||
builder.AppendLine("}");
|
||||
}
|
||||
|
||||
if (model.Namespace.Length > 0)
|
||||
builder.AppendLine("}");
|
||||
return builder.ToString();
|
||||
}
|
||||
|
||||
private static void EmitMethod(StringBuilder builder, int indent, GpuShaderMethodSource source)
|
||||
{
|
||||
var method = source.Method;
|
||||
string field = "s_shader_" + method.MethodName;
|
||||
|
||||
AppendIndent(builder, indent);
|
||||
builder.Append("private static readonly byte[] ");
|
||||
builder.Append(field);
|
||||
builder.Append(" = global::System.Convert.FromBase64String(");
|
||||
builder.Append(Literal(source.Bytecode));
|
||||
builder.AppendLine(");");
|
||||
builder.AppendLine();
|
||||
|
||||
AppendIndent(builder, indent);
|
||||
builder.Append(method.Accessibility);
|
||||
builder.Append(' ');
|
||||
if (method.IsStatic)
|
||||
builder.Append("static ");
|
||||
builder.Append("partial ");
|
||||
builder.Append(method.ReturnType);
|
||||
builder.Append(' ');
|
||||
builder.Append(method.MethodName);
|
||||
builder.Append('(');
|
||||
for (int i = 0; i < method.Parameters.Count; i++)
|
||||
{
|
||||
if (i > 0)
|
||||
builder.Append(", ");
|
||||
var parameter = method.Parameters[i];
|
||||
builder.Append(parameter.Prefix);
|
||||
builder.Append(parameter.Type);
|
||||
builder.Append(' ');
|
||||
builder.Append(parameter.Name);
|
||||
}
|
||||
builder.AppendLine(")");
|
||||
AppendIndent(builder, indent);
|
||||
builder.AppendLine("{");
|
||||
AppendIndent(builder, indent + 1);
|
||||
builder.Append("return Run(");
|
||||
builder.Append(field);
|
||||
builder.Append(", ");
|
||||
builder.Append(method.Invocation.Resources);
|
||||
builder.Append(", ");
|
||||
builder.Append(method.Invocation.Constants);
|
||||
builder.Append(", ");
|
||||
builder.Append(method.Invocation.Target);
|
||||
builder.Append(", ");
|
||||
builder.Append(method.Invocation.Width);
|
||||
builder.Append(", ");
|
||||
builder.Append(method.Invocation.Height);
|
||||
builder.AppendLine(");");
|
||||
AppendIndent(builder, indent);
|
||||
builder.AppendLine("}");
|
||||
}
|
||||
|
||||
private static void AppendIndent(StringBuilder builder, int indent)
|
||||
{
|
||||
for (int i = 0; i < indent; i++)
|
||||
builder.Append(" ");
|
||||
}
|
||||
|
||||
private static string EmitErrors(ImmutableArray<string> errors)
|
||||
{
|
||||
var builder = new StringBuilder();
|
||||
foreach (var error in errors)
|
||||
builder.AppendLine("#error " + error);
|
||||
return builder.ToString();
|
||||
}
|
||||
|
||||
private static string HintName(GpuShaderClass model)
|
||||
{
|
||||
var builder = new StringBuilder("GpuPixelOperationShader");
|
||||
if (model.Namespace.Length > 0)
|
||||
{
|
||||
builder.Append('.');
|
||||
builder.Append(HintPart(model.Namespace));
|
||||
}
|
||||
foreach (var type in model.TypeChain)
|
||||
{
|
||||
builder.Append('.');
|
||||
builder.Append(HintPart(type.Name));
|
||||
}
|
||||
builder.Append(".g.cs");
|
||||
return builder.ToString();
|
||||
}
|
||||
|
||||
private static string ErrorHintName(GpuShaderClass model)
|
||||
{
|
||||
return Path.ChangeExtension(HintName(model), ".Errors.g.cs");
|
||||
}
|
||||
|
||||
private static string HintPart(string value)
|
||||
{
|
||||
var builder = new StringBuilder(value.Length);
|
||||
foreach (char c in value)
|
||||
builder.Append(char.IsLetterOrDigit(c) ? c : '_');
|
||||
return builder.ToString();
|
||||
}
|
||||
|
||||
private static string Literal(string value)
|
||||
{
|
||||
var builder = new StringBuilder(value.Length + 2);
|
||||
builder.Append('"');
|
||||
foreach (char c in value)
|
||||
{
|
||||
switch (c)
|
||||
{
|
||||
case '\\':
|
||||
builder.Append(@"\\");
|
||||
break;
|
||||
case '"':
|
||||
builder.Append("\\\"");
|
||||
break;
|
||||
case '\0':
|
||||
builder.Append(@"\0");
|
||||
break;
|
||||
case '\a':
|
||||
builder.Append(@"\a");
|
||||
break;
|
||||
case '\b':
|
||||
builder.Append(@"\b");
|
||||
break;
|
||||
case '\f':
|
||||
builder.Append(@"\f");
|
||||
break;
|
||||
case '\n':
|
||||
builder.Append(@"\n");
|
||||
break;
|
||||
case '\r':
|
||||
builder.Append(@"\r");
|
||||
break;
|
||||
case '\t':
|
||||
builder.Append(@"\t");
|
||||
break;
|
||||
case '\v':
|
||||
builder.Append(@"\v");
|
||||
break;
|
||||
default:
|
||||
if (char.IsControl(c))
|
||||
{
|
||||
builder.Append(@"\u");
|
||||
builder.Append(((int)c).ToString("x4", CultureInfo.InvariantCulture));
|
||||
}
|
||||
else
|
||||
{
|
||||
builder.Append(c);
|
||||
}
|
||||
break;
|
||||
}
|
||||
}
|
||||
builder.Append('"');
|
||||
return builder.ToString();
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,4 @@
|
||||
namespace LuaScript.Generator
|
||||
{
|
||||
internal sealed record GpuShaderTypePart(string Name, bool IsStatic);
|
||||
}
|
||||
@@ -0,0 +1,96 @@
|
||||
using System.Globalization;
|
||||
using System.Runtime.InteropServices;
|
||||
using System.Text;
|
||||
|
||||
namespace LuaScript.Generator
|
||||
{
|
||||
internal static class ShaderCompiler
|
||||
{
|
||||
private const string Profile = "ps_5_0";
|
||||
|
||||
public static string? Compile(string source, string entryPoint, out string bytecode)
|
||||
{
|
||||
bytecode = string.Empty;
|
||||
byte[] data = Encoding.UTF8.GetBytes(source);
|
||||
IntPtr code = IntPtr.Zero;
|
||||
IntPtr errors = IntPtr.Zero;
|
||||
try
|
||||
{
|
||||
int hr = D3DCompile(data, (IntPtr)data.Length, null, IntPtr.Zero, IntPtr.Zero, entryPoint, Profile, 0u, 0u, out code, out errors);
|
||||
if (hr < 0 || code == IntPtr.Zero)
|
||||
return ReadError(errors, hr);
|
||||
bytecode = Convert.ToBase64String(ReadBlob(code));
|
||||
return null;
|
||||
}
|
||||
catch (DllNotFoundException)
|
||||
{
|
||||
return "the Direct3D shader compiler is unavailable on this build host";
|
||||
}
|
||||
catch (EntryPointNotFoundException)
|
||||
{
|
||||
return "the Direct3D shader compiler is unavailable on this build host";
|
||||
}
|
||||
finally
|
||||
{
|
||||
Release(errors);
|
||||
Release(code);
|
||||
}
|
||||
}
|
||||
|
||||
private static byte[] ReadBlob(IntPtr blob)
|
||||
{
|
||||
IntPtr pointer = Invoke<GetBufferPointerDelegate>(blob, 3)(blob);
|
||||
int size = checked((int)(long)Invoke<GetBufferSizeDelegate>(blob, 4)(blob));
|
||||
var buffer = new byte[size];
|
||||
Marshal.Copy(pointer, buffer, 0, size);
|
||||
return buffer;
|
||||
}
|
||||
|
||||
private static string ReadError(IntPtr blob, int hr)
|
||||
{
|
||||
string fallback = "HRESULT 0x" + hr.ToString("X8", CultureInfo.InvariantCulture);
|
||||
if (blob == IntPtr.Zero)
|
||||
return fallback;
|
||||
IntPtr pointer = Invoke<GetBufferPointerDelegate>(blob, 3)(blob);
|
||||
int size = checked((int)(long)Invoke<GetBufferSizeDelegate>(blob, 4)(blob));
|
||||
string message = (Marshal.PtrToStringAnsi(pointer, size) ?? string.Empty).Trim();
|
||||
return message.Length > 0 ? message : fallback;
|
||||
}
|
||||
|
||||
private static void Release(IntPtr unknown)
|
||||
{
|
||||
if (unknown != IntPtr.Zero)
|
||||
Invoke<ReleaseDelegate>(unknown, 2)(unknown);
|
||||
}
|
||||
|
||||
private static T Invoke<T>(IntPtr instance, int slot) where T : Delegate
|
||||
{
|
||||
IntPtr table = Marshal.ReadIntPtr(instance);
|
||||
IntPtr function = Marshal.ReadIntPtr(table, slot * IntPtr.Size);
|
||||
return (T)Marshal.GetDelegateForFunctionPointer(function, typeof(T));
|
||||
}
|
||||
|
||||
[UnmanagedFunctionPointer(CallingConvention.StdCall)]
|
||||
private delegate IntPtr GetBufferPointerDelegate(IntPtr self);
|
||||
|
||||
[UnmanagedFunctionPointer(CallingConvention.StdCall)]
|
||||
private delegate IntPtr GetBufferSizeDelegate(IntPtr self);
|
||||
|
||||
[UnmanagedFunctionPointer(CallingConvention.StdCall)]
|
||||
private delegate uint ReleaseDelegate(IntPtr self);
|
||||
|
||||
[DllImport("d3dcompiler_47.dll", CallingConvention = CallingConvention.StdCall)]
|
||||
private static extern int D3DCompile(
|
||||
byte[] srcData,
|
||||
IntPtr srcDataSize,
|
||||
[MarshalAs(UnmanagedType.LPStr)] string? sourceName,
|
||||
IntPtr defines,
|
||||
IntPtr include,
|
||||
[MarshalAs(UnmanagedType.LPStr)] string entryPoint,
|
||||
[MarshalAs(UnmanagedType.LPStr)] string target,
|
||||
uint flags1,
|
||||
uint flags2,
|
||||
out IntPtr code,
|
||||
out IntPtr errorMsgs);
|
||||
}
|
||||
}
|
||||
@@ -5,60 +5,6 @@ using Microsoft.CodeAnalysis.Text;
|
||||
|
||||
namespace LuaScript.Generator
|
||||
{
|
||||
internal enum LuaParameterKind
|
||||
{
|
||||
ExecutionContext,
|
||||
Arguments,
|
||||
DynValue,
|
||||
Double,
|
||||
Int,
|
||||
Bool,
|
||||
}
|
||||
|
||||
internal enum LuaReturnKind
|
||||
{
|
||||
DynValue,
|
||||
Double,
|
||||
Void,
|
||||
}
|
||||
|
||||
internal sealed record LuaParameterModel(string Name, LuaParameterKind Kind, string DefaultLiteral);
|
||||
|
||||
internal sealed record LuaFunctionModel(
|
||||
string LuaName,
|
||||
string MethodName,
|
||||
LuaReturnKind ReturnKind,
|
||||
EquatableArray<LuaParameterModel> Parameters);
|
||||
|
||||
internal sealed record LuaConstantModel(string LuaName, string MemberName);
|
||||
|
||||
internal enum LuaUpdateKind
|
||||
{
|
||||
Direct,
|
||||
OptionalValue,
|
||||
OptionalReference,
|
||||
}
|
||||
|
||||
internal sealed record LuaUpdateModel(string LuaName, string MethodName, LuaUpdateKind Kind);
|
||||
|
||||
internal sealed record LuaCatalogEntry(
|
||||
string Table,
|
||||
string Name,
|
||||
bool IsFunction,
|
||||
EquatableArray<string> Parameters);
|
||||
|
||||
internal sealed record LuaTypePart(string Name, bool IsStatic);
|
||||
|
||||
internal sealed record LuaTableModel(
|
||||
string Namespace,
|
||||
EquatableArray<LuaTypePart> TypeChain,
|
||||
string TableName,
|
||||
string ContextType,
|
||||
EquatableArray<LuaFunctionModel> Functions,
|
||||
EquatableArray<LuaConstantModel> Constants,
|
||||
EquatableArray<LuaUpdateModel> Updates,
|
||||
EquatableArray<LuaCatalogEntry> Entries);
|
||||
|
||||
[Generator]
|
||||
public sealed class LuaApiGenerator : IIncrementalGenerator
|
||||
{
|
||||
@@ -309,12 +255,30 @@ namespace LuaScript.Generator
|
||||
|
||||
var returnType = method.ReturnType;
|
||||
LuaUpdateKind kind;
|
||||
ITypeSymbol valueType;
|
||||
if (returnType.OriginalDefinition.SpecialType == SpecialType.System_Nullable_T)
|
||||
{
|
||||
kind = LuaUpdateKind.OptionalValue;
|
||||
valueType = ((INamedTypeSymbol)returnType).TypeArguments[0];
|
||||
}
|
||||
else if (returnType.IsReferenceType)
|
||||
{
|
||||
kind = LuaUpdateKind.OptionalReference;
|
||||
valueType = returnType;
|
||||
}
|
||||
else
|
||||
{
|
||||
kind = LuaUpdateKind.Direct;
|
||||
valueType = returnType;
|
||||
}
|
||||
|
||||
var valueKind = valueType.SpecialType switch
|
||||
{
|
||||
SpecialType.System_Double or SpecialType.System_Int32 => LuaValueKind.Number,
|
||||
SpecialType.System_Boolean => LuaValueKind.Boolean,
|
||||
SpecialType.System_String => LuaValueKind.String,
|
||||
_ => LuaValueKind.Other,
|
||||
};
|
||||
|
||||
bool inCatalog = true;
|
||||
foreach (var argument in attribute.NamedArguments)
|
||||
@@ -325,7 +289,7 @@ namespace LuaScript.Generator
|
||||
|
||||
if (inCatalog)
|
||||
entry = new LuaCatalogEntry(tableName, luaName, false, EquatableArray<string>.Empty);
|
||||
return new LuaUpdateModel(luaName, method.Name, kind);
|
||||
return new LuaUpdateModel(luaName, method.Name, kind, valueKind);
|
||||
}
|
||||
|
||||
private static string FormatDouble(double value) =>
|
||||
@@ -387,13 +351,19 @@ namespace LuaScript.Generator
|
||||
switch (update.Kind)
|
||||
{
|
||||
case LuaUpdateKind.OptionalValue:
|
||||
builder.AppendLine($"{body}{{ var value = {update.MethodName}(context); if (value.HasValue) table[\"{update.LuaName}\"] = value.Value; }}");
|
||||
builder.AppendLine(update.ValueKind == LuaValueKind.Other
|
||||
? $"{body}{{ var value = {update.MethodName}(context); if (value.HasValue) table[\"{update.LuaName}\"] = value.Value; }}"
|
||||
: $"{body}{{ var value = {update.MethodName}(context); if (value.HasValue) table.Set(\"{update.LuaName}\", {WrapValue(update.ValueKind, "value.Value")}); }}");
|
||||
break;
|
||||
case LuaUpdateKind.OptionalReference:
|
||||
builder.AppendLine($"{body}{{ var value = {update.MethodName}(context); if (value is not null) table[\"{update.LuaName}\"] = value; }}");
|
||||
builder.AppendLine(update.ValueKind == LuaValueKind.Other
|
||||
? $"{body}{{ var value = {update.MethodName}(context); if (value is not null) table[\"{update.LuaName}\"] = value; }}"
|
||||
: $"{body}{{ var value = {update.MethodName}(context); if (value is not null) table.Set(\"{update.LuaName}\", {WrapValue(update.ValueKind, "value")}); }}");
|
||||
break;
|
||||
default:
|
||||
builder.AppendLine($"{body}table[\"{update.LuaName}\"] = {update.MethodName}(context);");
|
||||
builder.AppendLine(update.ValueKind == LuaValueKind.Other
|
||||
? $"{body}table[\"{update.LuaName}\"] = {update.MethodName}(context);"
|
||||
: $"{body}table.Set(\"{update.LuaName}\", {WrapValue(update.ValueKind, $"{update.MethodName}(context)")});");
|
||||
break;
|
||||
}
|
||||
}
|
||||
@@ -409,6 +379,13 @@ namespace LuaScript.Generator
|
||||
return builder.ToString();
|
||||
}
|
||||
|
||||
private static string WrapValue(LuaValueKind kind, string expression) => kind switch
|
||||
{
|
||||
LuaValueKind.Number => $"global::MoonSharp.Interpreter.DynValue.NewNumber({expression})",
|
||||
LuaValueKind.Boolean => $"global::MoonSharp.Interpreter.DynValue.NewBoolean({expression})",
|
||||
_ => $"global::MoonSharp.Interpreter.DynValue.NewString({expression})",
|
||||
};
|
||||
|
||||
private static string EmitArguments(EquatableArray<LuaParameterModel> parameters)
|
||||
{
|
||||
var rendered = new List<string>();
|
||||
@@ -0,0 +1,8 @@
|
||||
namespace LuaScript.Generator
|
||||
{
|
||||
internal sealed record LuaCatalogEntry(
|
||||
string Table,
|
||||
string Name,
|
||||
bool IsFunction,
|
||||
EquatableArray<string> Parameters);
|
||||
}
|
||||
@@ -0,0 +1,4 @@
|
||||
namespace LuaScript.Generator
|
||||
{
|
||||
internal sealed record LuaConstantModel(string LuaName, string MemberName);
|
||||
}
|
||||
@@ -0,0 +1,8 @@
|
||||
namespace LuaScript.Generator
|
||||
{
|
||||
internal sealed record LuaFunctionModel(
|
||||
string LuaName,
|
||||
string MethodName,
|
||||
LuaReturnKind ReturnKind,
|
||||
EquatableArray<LuaParameterModel> Parameters);
|
||||
}
|
||||
@@ -0,0 +1,12 @@
|
||||
namespace LuaScript.Generator
|
||||
{
|
||||
internal enum LuaParameterKind
|
||||
{
|
||||
ExecutionContext,
|
||||
Arguments,
|
||||
DynValue,
|
||||
Double,
|
||||
Int,
|
||||
Bool,
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,4 @@
|
||||
namespace LuaScript.Generator
|
||||
{
|
||||
internal sealed record LuaParameterModel(string Name, LuaParameterKind Kind, string DefaultLiteral);
|
||||
}
|
||||
@@ -0,0 +1,9 @@
|
||||
namespace LuaScript.Generator
|
||||
{
|
||||
internal enum LuaReturnKind
|
||||
{
|
||||
DynValue,
|
||||
Double,
|
||||
Void,
|
||||
}
|
||||
}
|
||||
+29
-3
@@ -8,8 +8,6 @@ using Microsoft.CodeAnalysis.Text;
|
||||
|
||||
namespace LuaScript.Generator
|
||||
{
|
||||
internal sealed record LuaSyntaxRuleModel(string TypeName, int Order);
|
||||
|
||||
[Generator]
|
||||
public sealed class LuaSyntaxRuleGenerator : IIncrementalGenerator
|
||||
{
|
||||
@@ -47,7 +45,17 @@ namespace LuaScript.Generator
|
||||
if (arguments.Length > 0 && arguments[0].Value is int value)
|
||||
order = value;
|
||||
|
||||
return new LuaSyntaxRuleModel(symbol.ToDisplayString(), order);
|
||||
bool isCatalog = false;
|
||||
string keyword = string.Empty;
|
||||
foreach (var argument in context.Attributes[0].NamedArguments)
|
||||
{
|
||||
if (argument.Key == "IsCatalog" && argument.Value.Value is bool catalogValue)
|
||||
isCatalog = catalogValue;
|
||||
else if (argument.Key == "Keyword" && argument.Value.Value is string keywordValue)
|
||||
keyword = keywordValue;
|
||||
}
|
||||
|
||||
return new LuaSyntaxRuleModel(symbol.ToDisplayString(), order, isCatalog ? keyword : string.Empty);
|
||||
}
|
||||
|
||||
private static string Emit(ImmutableArray<LuaSyntaxRuleModel> models)
|
||||
@@ -68,6 +76,24 @@ namespace LuaScript.Generator
|
||||
foreach (var model in ordered)
|
||||
builder.AppendLine($" new global::{model.TypeName}(),");
|
||||
builder.AppendLine(" };");
|
||||
|
||||
var keywords = ordered
|
||||
.Where(static m => m.CatalogKeyword.Length > 0)
|
||||
.Select(static m => m.CatalogKeyword)
|
||||
.Distinct()
|
||||
.ToArray();
|
||||
if (keywords.Length == 0)
|
||||
{
|
||||
builder.AppendLine(" internal static readonly string[] CatalogKeywords = global::System.Array.Empty<string>();");
|
||||
}
|
||||
else
|
||||
{
|
||||
builder.AppendLine(" internal static readonly string[] CatalogKeywords = new string[]");
|
||||
builder.AppendLine(" {");
|
||||
foreach (var keyword in keywords)
|
||||
builder.AppendLine($" \"{keyword}\",");
|
||||
builder.AppendLine(" };");
|
||||
}
|
||||
builder.AppendLine(" }");
|
||||
builder.AppendLine("}");
|
||||
return builder.ToString();
|
||||
@@ -0,0 +1,4 @@
|
||||
namespace LuaScript.Generator
|
||||
{
|
||||
internal sealed record LuaSyntaxRuleModel(string TypeName, int Order, string CatalogKeyword);
|
||||
}
|
||||
@@ -0,0 +1,12 @@
|
||||
namespace LuaScript.Generator
|
||||
{
|
||||
internal sealed record LuaTableModel(
|
||||
string Namespace,
|
||||
EquatableArray<LuaTypePart> TypeChain,
|
||||
string TableName,
|
||||
string ContextType,
|
||||
EquatableArray<LuaFunctionModel> Functions,
|
||||
EquatableArray<LuaConstantModel> Constants,
|
||||
EquatableArray<LuaUpdateModel> Updates,
|
||||
EquatableArray<LuaCatalogEntry> Entries);
|
||||
}
|
||||
@@ -0,0 +1,4 @@
|
||||
namespace LuaScript.Generator
|
||||
{
|
||||
internal sealed record LuaTypePart(string Name, bool IsStatic);
|
||||
}
|
||||
@@ -0,0 +1,9 @@
|
||||
namespace LuaScript.Generator
|
||||
{
|
||||
internal enum LuaUpdateKind
|
||||
{
|
||||
Direct,
|
||||
OptionalValue,
|
||||
OptionalReference,
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,4 @@
|
||||
namespace LuaScript.Generator
|
||||
{
|
||||
internal sealed record LuaUpdateModel(string LuaName, string MethodName, LuaUpdateKind Kind, LuaValueKind ValueKind);
|
||||
}
|
||||
@@ -0,0 +1,10 @@
|
||||
namespace LuaScript.Generator
|
||||
{
|
||||
internal enum LuaValueKind
|
||||
{
|
||||
Number,
|
||||
Boolean,
|
||||
String,
|
||||
Other,
|
||||
}
|
||||
}
|
||||
@@ -5,7 +5,7 @@
|
||||
<LangVersion>latest</LangVersion>
|
||||
<Nullable>enable</Nullable>
|
||||
<ImplicitUsings>enable</ImplicitUsings>
|
||||
<Version>1.15.0</Version>
|
||||
<Version>1.20.2</Version>
|
||||
<IsRoslynComponent>true</IsRoslynComponent>
|
||||
<EnforceExtendedAnalyzerRules>true</EnforceExtendedAnalyzerRules>
|
||||
</PropertyGroup>
|
||||
|
||||
@@ -0,0 +1,134 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using LuaScript.Engine.Shader;
|
||||
|
||||
namespace LuaScript.Engine.Processing
|
||||
{
|
||||
[GpuPixelOperationShader(nameof(RunConvolve), "Shaders/convolve.hlsl", "convolve")]
|
||||
internal sealed partial class GpuConvolveOperation(PixelShaderRunner runner) : GpuPixelOperation(runner)
|
||||
{
|
||||
private const int ConvolveWorkThreshold = 262144;
|
||||
private const int MaxConvolveSize = 31;
|
||||
private const int MaxConvolveValidationCount = 64;
|
||||
|
||||
private readonly PixelShaderInput[] _resources = new PixelShaderInput[1];
|
||||
private readonly float[] _constants = new float[1024];
|
||||
private readonly List<ConvolveValidation> _validations = [];
|
||||
|
||||
public bool TryConvolve(byte[] target, int width, int height, double[] kernel, int size, double divisor, double offset, bool force = false)
|
||||
{
|
||||
if (!IsTextureSupported(target, width, height) || !IsSupported(kernel, size, divisor, offset))
|
||||
return false;
|
||||
|
||||
long work = (long)width * height * size * size;
|
||||
if (!force && work < ConvolveWorkThreshold || !EnsureValidated(target, width, height, kernel, size, divisor, offset))
|
||||
return false;
|
||||
|
||||
SetConstants(width, height, kernel, size, divisor, offset);
|
||||
_resources[0] = new PixelShaderInput(target, width, height);
|
||||
return RunConvolve(_resources.AsSpan(0, 1), _constants.AsSpan(0, size * size + 8), target, width, height);
|
||||
}
|
||||
|
||||
private bool EnsureValidated(byte[] target, int width, int height, double[] kernel, int size, double divisor, double offset)
|
||||
{
|
||||
for (int i = 0; i < _validations.Count; i++)
|
||||
{
|
||||
if (_validations[i].Matches(kernel, size, divisor, offset))
|
||||
return _validations[i].Valid;
|
||||
}
|
||||
|
||||
if (_validations.Count >= MaxConvolveValidationCount)
|
||||
_validations.Clear();
|
||||
|
||||
bool valid = Validate(target, width, height, kernel, size, divisor, offset);
|
||||
_validations.Add(new ConvolveValidation(kernel, size, divisor, offset, valid));
|
||||
return valid;
|
||||
}
|
||||
|
||||
private bool Validate(byte[] target, int width, int height, double[] kernel, int size, double divisor, double offset)
|
||||
{
|
||||
int probeWidth = Math.Min(width, 8);
|
||||
int probeHeight = Math.Min(height, 7);
|
||||
var probe = CopyProbe(target, width, height, probeWidth, probeHeight);
|
||||
var cpu = (byte[])probe.Clone();
|
||||
var gpu = (byte[])probe.Clone();
|
||||
double[]? scratch = null;
|
||||
PixelBufferSoftwareProcessor.Convolve(cpu, probeWidth, probeHeight, kernel, size, divisor, offset, ref scratch);
|
||||
SetConstants(probeWidth, probeHeight, kernel, size, divisor, offset);
|
||||
_resources[0] = new PixelShaderInput(gpu, probeWidth, probeHeight);
|
||||
return RunConvolve(_resources.AsSpan(0, 1), _constants.AsSpan(0, size * size + 8), gpu, probeWidth, probeHeight) && Equal(cpu, gpu);
|
||||
}
|
||||
|
||||
private void SetConstants(int width, int height, double[] kernel, int size, double divisor, double offset)
|
||||
{
|
||||
_constants[0] = width;
|
||||
_constants[1] = height;
|
||||
_constants[2] = (float)divisor;
|
||||
_constants[3] = (float)offset;
|
||||
_constants[4] = size;
|
||||
_constants[5] = size / 2;
|
||||
_constants[6] = 0f;
|
||||
_constants[7] = 0f;
|
||||
int taps = size * size;
|
||||
for (int i = 0; i < taps; i++)
|
||||
_constants[i + 8] = (float)kernel[i];
|
||||
}
|
||||
|
||||
private static bool IsSupported(double[] kernel, int size, double divisor, double offset)
|
||||
{
|
||||
if (size < 1 || (size & 1) == 0 || size > MaxConvolveSize || divisor == 0d || !IsFloatCompatible(divisor) || !IsFloatCompatible(offset))
|
||||
return false;
|
||||
int taps = size * size;
|
||||
if (kernel.Length < taps || taps + 8 > 1024)
|
||||
return false;
|
||||
for (int i = 0; i < taps; i++)
|
||||
{
|
||||
if (!IsFloatCompatible(kernel[i]))
|
||||
return false;
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
private static bool IsFloatCompatible(double value)
|
||||
{
|
||||
return double.IsFinite(value) && float.IsFinite((float)value);
|
||||
}
|
||||
|
||||
private partial bool RunConvolve(ReadOnlySpan<PixelShaderInput> resources, ReadOnlySpan<float> constants, byte[] target, int width, int height);
|
||||
|
||||
private sealed class ConvolveValidation
|
||||
{
|
||||
private readonly double[] _kernel;
|
||||
private readonly int _size;
|
||||
private readonly double _divisor;
|
||||
private readonly double _offset;
|
||||
|
||||
public ConvolveValidation(double[] kernel, int size, double divisor, double offset, bool valid)
|
||||
{
|
||||
int taps = size * size;
|
||||
_kernel = new double[taps];
|
||||
Array.Copy(kernel, _kernel, taps);
|
||||
_size = size;
|
||||
_divisor = divisor;
|
||||
_offset = offset;
|
||||
Valid = valid;
|
||||
}
|
||||
|
||||
public bool Valid { get; }
|
||||
|
||||
public bool Matches(double[] kernel, int size, double divisor, double offset)
|
||||
{
|
||||
if (_size != size || BitConverter.DoubleToInt64Bits(_divisor) != BitConverter.DoubleToInt64Bits(divisor) ||
|
||||
BitConverter.DoubleToInt64Bits(_offset) != BitConverter.DoubleToInt64Bits(offset))
|
||||
return false;
|
||||
int taps = size * size;
|
||||
for (int i = 0; i < taps; i++)
|
||||
{
|
||||
if (BitConverter.DoubleToInt64Bits(_kernel[i]) != BitConverter.DoubleToInt64Bits(kernel[i]))
|
||||
return false;
|
||||
}
|
||||
return true;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,124 @@
|
||||
using System;
|
||||
using LuaScript.Engine.Shader;
|
||||
|
||||
namespace LuaScript.Engine.Processing
|
||||
{
|
||||
[GpuPixelOperationShader(nameof(RunFillFull), "Shaders/fill.hlsl", "fill_full")]
|
||||
[GpuPixelOperationShader(nameof(RunFillPartial), "Shaders/fill.hlsl", "fill_partial")]
|
||||
internal sealed partial class GpuFillOperation(PixelShaderRunner runner) : GpuPixelOperation(runner)
|
||||
{
|
||||
private const int FillFullThreshold = 1048576;
|
||||
private const int FillPartialThreshold = 1048576;
|
||||
|
||||
private readonly PixelShaderInput[] _resources = new PixelShaderInput[1];
|
||||
private readonly float[] _constants = new float[8];
|
||||
|
||||
private bool? _fullValidated;
|
||||
private bool? _partialValidated;
|
||||
|
||||
public bool TryFill(byte[] target, int width, int height, double r, double g, double b, double a, int x, int y, int fillWidth, int fillHeight, bool force = false)
|
||||
{
|
||||
if (!IsTextureSupported(target, width, height) || !AreFinite(r, g, b, a))
|
||||
return false;
|
||||
|
||||
long pixels = (long)width * height;
|
||||
bool full = x == 0 && y == 0 && fillWidth == width && fillHeight == height;
|
||||
if (full)
|
||||
{
|
||||
if (!force && pixels < FillFullThreshold || !EnsureFullValidated())
|
||||
return false;
|
||||
SetConstants(r, g, b, a);
|
||||
return RunFillFull(_constants.AsSpan(0, 4), target, width, height);
|
||||
}
|
||||
|
||||
long area = (long)fillWidth * fillHeight;
|
||||
if (!force && (pixels < FillPartialThreshold || area * 4L < pixels * 3L) || !EnsurePartialValidated())
|
||||
return false;
|
||||
|
||||
SetConstants(r, g, b, a);
|
||||
_constants[4] = x;
|
||||
_constants[5] = y;
|
||||
_constants[6] = x + fillWidth;
|
||||
_constants[7] = y + fillHeight;
|
||||
_resources[0] = new PixelShaderInput(target, width, height);
|
||||
return RunFillPartial(_resources.AsSpan(0, 1), _constants.AsSpan(0, 8), target, width, height);
|
||||
}
|
||||
|
||||
private bool EnsureFullValidated()
|
||||
{
|
||||
if (_fullValidated.HasValue)
|
||||
return _fullValidated.Value;
|
||||
|
||||
const int width = 7;
|
||||
const int height = 5;
|
||||
var source = CreateProbe(width, height);
|
||||
var cpu = (byte[])source.Clone();
|
||||
var gpu = (byte[])source.Clone();
|
||||
PixelBufferSoftwareProcessor.Fill(cpu, width, height, 23d, 197d, 89d, 173d, 0, 0, width, height);
|
||||
SetConstants(23d, 197d, 89d, 173d);
|
||||
_fullValidated = RunFillFull(_constants.AsSpan(0, 4), gpu, width, height) && Equal(cpu, gpu);
|
||||
return _fullValidated.Value;
|
||||
}
|
||||
|
||||
private bool EnsurePartialValidated()
|
||||
{
|
||||
if (_partialValidated.HasValue)
|
||||
return _partialValidated.Value;
|
||||
|
||||
const int width = 7;
|
||||
const int height = 5;
|
||||
var source = CreateProbe(width, height);
|
||||
var cpu = (byte[])source.Clone();
|
||||
var gpu = (byte[])source.Clone();
|
||||
PixelBufferSoftwareProcessor.Fill(cpu, width, height, 23d, 197d, 89d, 173d, 1, 2, 4, 2);
|
||||
SetConstants(23d, 197d, 89d, 173d);
|
||||
_constants[4] = 1f;
|
||||
_constants[5] = 2f;
|
||||
_constants[6] = 5f;
|
||||
_constants[7] = 4f;
|
||||
_resources[0] = new PixelShaderInput(gpu, width, height);
|
||||
_partialValidated = RunFillPartial(_resources.AsSpan(0, 1), _constants.AsSpan(0, 8), gpu, width, height) && Equal(cpu, gpu);
|
||||
return _partialValidated.Value;
|
||||
}
|
||||
|
||||
private void SetConstants(double r, double g, double b, double a)
|
||||
{
|
||||
double aK = Math.Clamp(a, 0d, 255d) / 255d;
|
||||
byte pb = (byte)Math.Clamp(b * aK, 0d, 255d);
|
||||
byte pg = (byte)Math.Clamp(g * aK, 0d, 255d);
|
||||
byte pr = (byte)Math.Clamp(r * aK, 0d, 255d);
|
||||
byte pa = (byte)Math.Clamp(a, 0d, 255d);
|
||||
_constants[0] = pr / 255f;
|
||||
_constants[1] = pg / 255f;
|
||||
_constants[2] = pb / 255f;
|
||||
_constants[3] = pa / 255f;
|
||||
}
|
||||
|
||||
private static bool AreFinite(double r, double g, double b, double a)
|
||||
{
|
||||
return double.IsFinite(r) && double.IsFinite(g) && double.IsFinite(b) && double.IsFinite(a);
|
||||
}
|
||||
|
||||
private static byte[] CreateProbe(int width, int height)
|
||||
{
|
||||
var data = new byte[width * height * 4];
|
||||
for (int y = 0; y < height; y++)
|
||||
{
|
||||
for (int x = 0; x < width; x++)
|
||||
{
|
||||
int index = (y * width + x) * 4;
|
||||
byte a = (byte)((x * 31 + y * 47) & 255);
|
||||
data[index] = a == 0 ? (byte)0 : (byte)((x * 17 + y * 29) % (a + 1));
|
||||
data[index + 1] = a == 0 ? (byte)0 : (byte)((x * 43 + y * 11) % (a + 1));
|
||||
data[index + 2] = a == 0 ? (byte)0 : (byte)((x * 7 + y * 53) % (a + 1));
|
||||
data[index + 3] = a;
|
||||
}
|
||||
}
|
||||
return data;
|
||||
}
|
||||
|
||||
private partial bool RunFillFull(ReadOnlySpan<float> constants, byte[] target, int width, int height);
|
||||
|
||||
private partial bool RunFillPartial(ReadOnlySpan<PixelShaderInput> resources, ReadOnlySpan<float> constants, byte[] target, int width, int height);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,30 @@
|
||||
using LuaScript.Engine.Shader;
|
||||
|
||||
namespace LuaScript.Engine.Processing
|
||||
{
|
||||
internal sealed class GpuPixelBufferProcessor(PixelShaderRunner runner) : IPixelBufferProcessor
|
||||
{
|
||||
private readonly object _gate = new();
|
||||
private readonly GpuFillOperation _fill = new(runner);
|
||||
private readonly GpuConvolveOperation _convolve = new(runner);
|
||||
private readonly GpuResizeOperation _resize = new(runner);
|
||||
|
||||
public bool TryFill(byte[] target, int width, int height, double r, double g, double b, double a, int x, int y, int fillWidth, int fillHeight, bool force = false)
|
||||
{
|
||||
lock (_gate)
|
||||
return _fill.TryFill(target, width, height, r, g, b, a, x, y, fillWidth, fillHeight, force);
|
||||
}
|
||||
|
||||
public bool TryConvolve(byte[] target, int width, int height, double[] kernel, int size, double divisor, double offset, bool force = false)
|
||||
{
|
||||
lock (_gate)
|
||||
return _convolve.TryConvolve(target, width, height, kernel, size, divisor, offset, force);
|
||||
}
|
||||
|
||||
public bool TryResize(byte[] source, int sourceWidth, int sourceHeight, int targetWidth, int targetHeight, bool linear, out byte[]? target, bool force = false)
|
||||
{
|
||||
lock (_gate)
|
||||
return _resize.TryResize(source, sourceWidth, sourceHeight, targetWidth, targetHeight, linear, out target, force);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,47 @@
|
||||
using System;
|
||||
using LuaScript.Engine.Shader;
|
||||
|
||||
namespace LuaScript.Engine.Processing
|
||||
{
|
||||
internal abstract class GpuPixelOperation(PixelShaderRunner runner)
|
||||
{
|
||||
protected const int MaxTextureSize = 16384;
|
||||
|
||||
protected bool Run(byte[] bytecode, ReadOnlySpan<PixelShaderInput> resources, ReadOnlySpan<float> constants, byte[] target, int width, int height)
|
||||
{
|
||||
return runner.TryRunHardware(
|
||||
bytecode,
|
||||
resources,
|
||||
constants,
|
||||
PixelShaderBlend.Copy,
|
||||
PixelShaderSampler.None,
|
||||
target,
|
||||
width,
|
||||
height,
|
||||
out _) == PixelShaderRunStatus.Success;
|
||||
}
|
||||
|
||||
protected static bool IsTextureSupported(byte[] buffer, int width, int height)
|
||||
{
|
||||
return IsTextureSizeSupported(width, height) && (long)buffer.Length >= (long)width * height * 4;
|
||||
}
|
||||
|
||||
protected static bool IsTextureSizeSupported(int width, int height)
|
||||
{
|
||||
return width > 0 && height > 0 && width <= MaxTextureSize && height <= MaxTextureSize;
|
||||
}
|
||||
|
||||
protected static bool Equal(byte[] expected, byte[] actual)
|
||||
{
|
||||
return expected.AsSpan().SequenceEqual(actual);
|
||||
}
|
||||
|
||||
protected static byte[] CopyProbe(byte[] source, int width, int height, int probeWidth, int probeHeight)
|
||||
{
|
||||
var data = new byte[probeWidth * probeHeight * 4];
|
||||
for (int y = 0; y < probeHeight; y++)
|
||||
Buffer.BlockCopy(source, y * width * 4, data, y * probeWidth * 4, probeWidth * 4);
|
||||
return data;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,14 @@
|
||||
using System;
|
||||
|
||||
namespace LuaScript.Engine.Processing
|
||||
{
|
||||
[AttributeUsage(AttributeTargets.Class, AllowMultiple = true)]
|
||||
internal sealed class GpuPixelOperationShaderAttribute(string methodName, string fileName, string entryPoint) : Attribute
|
||||
{
|
||||
public string MethodName { get; } = methodName;
|
||||
|
||||
public string FileName { get; } = fileName;
|
||||
|
||||
public string EntryPoint { get; } = entryPoint;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,82 @@
|
||||
using System;
|
||||
using LuaScript.Engine.Shader;
|
||||
|
||||
namespace LuaScript.Engine.Processing
|
||||
{
|
||||
[GpuPixelOperationShader(nameof(RunResizeNearest), "Shaders/resize.hlsl", "resize_nearest")]
|
||||
[GpuPixelOperationShader(nameof(RunResizeLinear), "Shaders/resize.hlsl", "resize_linear")]
|
||||
internal sealed partial class GpuResizeOperation(PixelShaderRunner runner) : GpuPixelOperation(runner)
|
||||
{
|
||||
private const int ResizeThreshold = 262144;
|
||||
|
||||
private readonly PixelShaderInput[] _resources = new PixelShaderInput[1];
|
||||
private readonly float[] _constants = new float[4];
|
||||
|
||||
private byte[] _target = [];
|
||||
private bool? _nearestValidated;
|
||||
private bool? _linearValidated;
|
||||
|
||||
public bool TryResize(byte[] source, int sourceWidth, int sourceHeight, int targetWidth, int targetHeight, bool linear, out byte[]? target, bool force = false)
|
||||
{
|
||||
target = null;
|
||||
if (!IsTextureSupported(source, sourceWidth, sourceHeight) || !IsTextureSizeSupported(targetWidth, targetHeight))
|
||||
return false;
|
||||
|
||||
long pixels = (long)targetWidth * targetHeight;
|
||||
if (!force && pixels < ResizeThreshold || !(linear ? EnsureLinearValidated(source, sourceWidth, sourceHeight) : EnsureNearestValidated(source, sourceWidth, sourceHeight)))
|
||||
return false;
|
||||
|
||||
return RunShader(source, sourceWidth, sourceHeight, targetWidth, targetHeight, linear, out target);
|
||||
}
|
||||
|
||||
private bool EnsureNearestValidated(byte[] source, int sourceWidth, int sourceHeight)
|
||||
{
|
||||
if (_nearestValidated.HasValue)
|
||||
return _nearestValidated.Value;
|
||||
_nearestValidated = Validate(source, sourceWidth, sourceHeight, false);
|
||||
return _nearestValidated.Value;
|
||||
}
|
||||
|
||||
private bool EnsureLinearValidated(byte[] source, int sourceWidth, int sourceHeight)
|
||||
{
|
||||
if (_linearValidated.HasValue)
|
||||
return _linearValidated.Value;
|
||||
_linearValidated = Validate(source, sourceWidth, sourceHeight, true);
|
||||
return _linearValidated.Value;
|
||||
}
|
||||
|
||||
private bool Validate(byte[] source, int sourceWidth, int sourceHeight, bool linear)
|
||||
{
|
||||
int probeWidth = Math.Min(sourceWidth, 8);
|
||||
int probeHeight = Math.Min(sourceHeight, 7);
|
||||
int targetWidth = Math.Max(1, probeWidth * 2 - 3);
|
||||
int targetHeight = Math.Max(1, probeHeight * 2 - 5);
|
||||
var probe = CopyProbe(source, sourceWidth, sourceHeight, probeWidth, probeHeight);
|
||||
byte[]? sourceScratch = null;
|
||||
byte[]? targetScratch = null;
|
||||
var cpu = PixelBufferSoftwareProcessor.Resize(probe, probeWidth, probeHeight, targetWidth, targetHeight, linear, ref sourceScratch, ref targetScratch);
|
||||
return RunShader(probe, probeWidth, probeHeight, targetWidth, targetHeight, linear, out var gpu) && gpu is not null && Equal(cpu, gpu);
|
||||
}
|
||||
|
||||
private bool RunShader(byte[] source, int sourceWidth, int sourceHeight, int targetWidth, int targetHeight, bool linear, out byte[]? target)
|
||||
{
|
||||
int count = checked(targetWidth * targetHeight * 4);
|
||||
if (_target.Length != count)
|
||||
_target = new byte[count];
|
||||
|
||||
_constants[0] = sourceWidth;
|
||||
_constants[1] = sourceHeight;
|
||||
_constants[2] = targetWidth;
|
||||
_constants[3] = targetHeight;
|
||||
_resources[0] = new PixelShaderInput(source, sourceWidth, sourceHeight);
|
||||
target = _target;
|
||||
return linear
|
||||
? RunResizeLinear(_resources.AsSpan(0, 1), _constants.AsSpan(0, 4), _target, targetWidth, targetHeight)
|
||||
: RunResizeNearest(_resources.AsSpan(0, 1), _constants.AsSpan(0, 4), _target, targetWidth, targetHeight);
|
||||
}
|
||||
|
||||
private partial bool RunResizeNearest(ReadOnlySpan<PixelShaderInput> resources, ReadOnlySpan<float> constants, byte[] target, int width, int height);
|
||||
|
||||
private partial bool RunResizeLinear(ReadOnlySpan<PixelShaderInput> resources, ReadOnlySpan<float> constants, byte[] target, int width, int height);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,50 @@
|
||||
<Project Sdk="Microsoft.NET.Sdk">
|
||||
|
||||
<PropertyGroup>
|
||||
<TargetFramework>net10.0-windows10.0.19041.0</TargetFramework>
|
||||
<ImplicitUsings>enable</ImplicitUsings>
|
||||
<Version>1.20.2</Version>
|
||||
<Platforms>AnyCPU;x64</Platforms>
|
||||
<Nullable>enable</Nullable>
|
||||
<AllowUnsafeBlocks>true</AllowUnsafeBlocks>
|
||||
</PropertyGroup>
|
||||
|
||||
<ItemGroup>
|
||||
<InternalsVisibleTo Include="LuaScript" />
|
||||
<InternalsVisibleTo Include="LuaScript.Tests" />
|
||||
</ItemGroup>
|
||||
|
||||
<ItemGroup>
|
||||
<ProjectReference Include="..\LuaScript.Runtime\LuaScript.Runtime.csproj" />
|
||||
<ProjectReference Include="..\LuaScript.Generator\LuaScript.Generator.csproj" OutputItemType="Analyzer" ReferenceOutputAssembly="false" />
|
||||
<AdditionalFiles Include="Shaders\*.hlsl" />
|
||||
</ItemGroup>
|
||||
|
||||
<ItemGroup>
|
||||
<Reference Include="SharpGen.Runtime">
|
||||
<HintPath>$(YMM4DirPath)SharpGen.Runtime.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.D3DCompiler.dll">
|
||||
<HintPath>$(YMM4DirPath)Vortice.D3DCompiler.dll</HintPath>
|
||||
<Private>false</Private>
|
||||
</Reference>
|
||||
<Reference Include="Vortice.DXGI.dll">
|
||||
<HintPath>$(YMM4DirPath)Vortice.DXGI.dll</HintPath>
|
||||
<Private>false</Private>
|
||||
</Reference>
|
||||
<Reference Include="Vortice.Mathematics">
|
||||
<HintPath>$(YMM4DirPath)Vortice.Mathematics.dll</HintPath>
|
||||
<Private>false</Private>
|
||||
</Reference>
|
||||
</ItemGroup>
|
||||
|
||||
</Project>
|
||||
+106
-10
@@ -7,7 +7,6 @@ using Vortice.Direct3D;
|
||||
using Vortice.Direct3D11;
|
||||
using Vortice.DXGI;
|
||||
using Vortice.Mathematics;
|
||||
using YukkuriMovieMaker.Commons;
|
||||
|
||||
namespace LuaScript.Engine.Shader
|
||||
{
|
||||
@@ -43,6 +42,7 @@ namespace LuaScript.Engine.Shader
|
||||
|
||||
private readonly Lock _locker = new();
|
||||
private readonly Dictionary<(string Hlsl, string Entry), CompiledShader> _shaders = [];
|
||||
private readonly Dictionary<byte[], ID3D11PixelShader> _precompiled = new(ReferenceEqualityComparer.Instance);
|
||||
private readonly InputSlot[] _inputs = new InputSlot[MaxResources];
|
||||
private readonly ID3D11ShaderResourceView[] _boundViews = new ID3D11ShaderResourceView[MaxResources];
|
||||
private readonly ID3D11ShaderResourceView[] _nullViews = new ID3D11ShaderResourceView[MaxResources];
|
||||
@@ -51,8 +51,11 @@ namespace LuaScript.Engine.Shader
|
||||
|
||||
public IBufferCompositor Compositor { get; set; } = SoftwareCompositor.Instance;
|
||||
|
||||
public Action<string, Exception?>? Logger { get; set; }
|
||||
|
||||
private ID3D11Device? _device;
|
||||
private ID3D11DeviceContext? _context;
|
||||
private DriverType _driverType;
|
||||
private ID3D11VertexShader? _vertexShader;
|
||||
private ID3D11Buffer? _constantBuffer;
|
||||
private ID3D11RasterizerState? _rasterizer;
|
||||
@@ -70,6 +73,7 @@ namespace LuaScript.Engine.Shader
|
||||
|
||||
private bool _disposed;
|
||||
private bool _unavailable;
|
||||
private bool _hardwareUnavailable;
|
||||
private bool _failureLogged;
|
||||
private int _recreateBudget = 3;
|
||||
|
||||
@@ -88,9 +92,7 @@ namespace LuaScript.Engine.Shader
|
||||
error = null;
|
||||
lock (_locker)
|
||||
{
|
||||
if (_disposed || _unavailable)
|
||||
return PixelShaderRunStatus.Unavailable;
|
||||
if (targetWidth <= 0 || targetHeight <= 0 || (long)target.Length < (long)targetWidth * targetHeight * 4)
|
||||
if (!CanRun(target, targetWidth, targetHeight))
|
||||
return PixelShaderRunStatus.Unavailable;
|
||||
|
||||
try
|
||||
@@ -116,6 +118,46 @@ namespace LuaScript.Engine.Shader
|
||||
}
|
||||
}
|
||||
|
||||
public PixelShaderRunStatus TryRunHardware(
|
||||
byte[] bytecode,
|
||||
ReadOnlySpan<PixelShaderInput> resources,
|
||||
ReadOnlySpan<float> constants,
|
||||
PixelShaderBlend blend,
|
||||
PixelShaderSampler sampler,
|
||||
byte[] target,
|
||||
int targetWidth,
|
||||
int targetHeight,
|
||||
out string? error)
|
||||
{
|
||||
error = null;
|
||||
lock (_locker)
|
||||
{
|
||||
if (!CanRun(target, targetWidth, targetHeight))
|
||||
return PixelShaderRunStatus.Unavailable;
|
||||
|
||||
try
|
||||
{
|
||||
if (!EnsureHardwareDevice())
|
||||
return PixelShaderRunStatus.Unavailable;
|
||||
|
||||
Execute(GetOrCreate(bytecode), resources, constants, blend, sampler, target, targetWidth, targetHeight);
|
||||
return PixelShaderRunStatus.Success;
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
HandleFailure(ex);
|
||||
return PixelShaderRunStatus.Unavailable;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private bool CanRun(byte[] target, int targetWidth, int targetHeight)
|
||||
{
|
||||
return !_disposed && !_unavailable &&
|
||||
targetWidth > 0 && targetHeight > 0 &&
|
||||
(long)target.Length >= (long)targetWidth * targetHeight * 4;
|
||||
}
|
||||
|
||||
public void Invalidate()
|
||||
{
|
||||
lock (_locker)
|
||||
@@ -146,19 +188,55 @@ namespace LuaScript.Engine.Shader
|
||||
}
|
||||
_recreateBudget--;
|
||||
|
||||
if (!TryCreateDevice(DriverType.Hardware, out var device, out var context) &&
|
||||
!TryCreateDevice(DriverType.Warp, out device, out context))
|
||||
DriverType driverType;
|
||||
if (TryCreateDevice(DriverType.Hardware, out var device, out var context))
|
||||
{
|
||||
driverType = DriverType.Hardware;
|
||||
}
|
||||
else if (TryCreateDevice(DriverType.Warp, out device, out context))
|
||||
{
|
||||
driverType = DriverType.Warp;
|
||||
}
|
||||
else
|
||||
{
|
||||
MarkUnavailable(null);
|
||||
return false;
|
||||
}
|
||||
|
||||
return InitializeDevice(device, context, driverType, true);
|
||||
}
|
||||
|
||||
private bool EnsureHardwareDevice()
|
||||
{
|
||||
if (_device is not null)
|
||||
return _driverType == DriverType.Hardware;
|
||||
if (_hardwareUnavailable)
|
||||
return false;
|
||||
if (_recreateBudget <= 0)
|
||||
{
|
||||
_hardwareUnavailable = true;
|
||||
return false;
|
||||
}
|
||||
_recreateBudget--;
|
||||
if (!TryCreateDevice(DriverType.Hardware, out var device, out var context))
|
||||
{
|
||||
_hardwareUnavailable = true;
|
||||
return false;
|
||||
}
|
||||
|
||||
return InitializeDevice(device, context, DriverType.Hardware, false);
|
||||
}
|
||||
|
||||
private bool InitializeDevice(ID3D11Device? device, ID3D11DeviceContext? context, DriverType driverType, bool markUnavailable)
|
||||
{
|
||||
try
|
||||
{
|
||||
var vsBytecode = CompileOrThrow(VertexShaderSource, "vsmain", "vs_4_0");
|
||||
var vertexShader = device!.CreateVertexShader(vsBytecode);
|
||||
_device = device;
|
||||
_context = context;
|
||||
_driverType = driverType;
|
||||
_hardwareUnavailable = driverType != DriverType.Hardware && _hardwareUnavailable;
|
||||
_vertexShader = vertexShader;
|
||||
_constantBuffer = device.CreateBuffer(new BufferDescription(
|
||||
ConstantBufferSize, BindFlags.ConstantBuffer, ResourceUsage.Dynamic, CpuAccessFlags.Write));
|
||||
@@ -178,7 +256,10 @@ namespace LuaScript.Engine.Shader
|
||||
context?.Dispose();
|
||||
device?.Dispose();
|
||||
}
|
||||
MarkUnavailable(ex);
|
||||
if (markUnavailable)
|
||||
MarkUnavailable(ex);
|
||||
else
|
||||
_hardwareUnavailable = true;
|
||||
return false;
|
||||
}
|
||||
}
|
||||
@@ -267,6 +348,16 @@ namespace LuaScript.Engine.Shader
|
||||
return compiled;
|
||||
}
|
||||
|
||||
private ID3D11PixelShader GetOrCreate(byte[] bytecode)
|
||||
{
|
||||
if (_precompiled.TryGetValue(bytecode, out var cached))
|
||||
return cached;
|
||||
|
||||
var shader = _device!.CreatePixelShader(bytecode);
|
||||
_precompiled[bytecode] = shader;
|
||||
return shader;
|
||||
}
|
||||
|
||||
private static byte[] CompileOrThrow(string source, string entryPoint, string profile)
|
||||
{
|
||||
var result = Compiler.Compile(Encoding.UTF8.GetBytes(source), entryPoint, string.Empty, profile, out var bytecode, out var errors);
|
||||
@@ -503,7 +594,7 @@ namespace LuaScript.Engine.Shader
|
||||
if (!_failureLogged)
|
||||
{
|
||||
_failureLogged = true;
|
||||
Log.Default.Write("LuaScript: obj.pixelshader execution failed; the call is skipped.", ex);
|
||||
WriteLog("LuaScript: obj.pixelshader execution failed; the call is skipped.", ex);
|
||||
}
|
||||
ReleaseDeviceObjects();
|
||||
if (_recreateBudget <= 0)
|
||||
@@ -517,16 +608,21 @@ namespace LuaScript.Engine.Shader
|
||||
return;
|
||||
_failureLogged = true;
|
||||
if (ex is null)
|
||||
Log.Default.Write("LuaScript: Direct3D 11 is unavailable; obj.pixelshader is disabled.");
|
||||
WriteLog("LuaScript: Direct3D 11 is unavailable; obj.pixelshader is disabled.", null);
|
||||
else
|
||||
Log.Default.Write("LuaScript: Direct3D 11 initialization failed; obj.pixelshader is disabled.", ex);
|
||||
WriteLog("LuaScript: Direct3D 11 initialization failed; obj.pixelshader is disabled.", ex);
|
||||
}
|
||||
|
||||
private void WriteLog(string message, Exception? exception) => Logger?.Invoke(message, exception);
|
||||
|
||||
private void ReleaseShaders()
|
||||
{
|
||||
foreach (var compiled in _shaders.Values)
|
||||
compiled.Shader?.Dispose();
|
||||
_shaders.Clear();
|
||||
foreach (var shader in _precompiled.Values)
|
||||
shader.Dispose();
|
||||
_precompiled.Clear();
|
||||
}
|
||||
|
||||
private void ReleaseDeviceObjects()
|
||||
@@ -0,0 +1,58 @@
|
||||
Texture2D source : register(t0);
|
||||
|
||||
cbuffer Parameters : register(b0)
|
||||
{
|
||||
float4 values[256];
|
||||
};
|
||||
|
||||
float get_value(uint index)
|
||||
{
|
||||
uint row = index >> 2;
|
||||
uint column = index & 3u;
|
||||
float4 value = values[row];
|
||||
if (column == 0u)
|
||||
return value.x;
|
||||
if (column == 1u)
|
||||
return value.y;
|
||||
if (column == 2u)
|
||||
return value.z;
|
||||
return value.w;
|
||||
}
|
||||
|
||||
float convolve_channel(float value)
|
||||
{
|
||||
return floor(saturate(value) * 255.0) / 255.0;
|
||||
}
|
||||
|
||||
float4 convolve(float4 pos : SV_Position) : SV_Target
|
||||
{
|
||||
uint2 p = (uint2)floor(pos.xy);
|
||||
int width = (int)get_value(0u);
|
||||
int height = (int)get_value(1u);
|
||||
float divisor = get_value(2u);
|
||||
float offset = get_value(3u) / 255.0;
|
||||
int kernelSize = (int)get_value(4u);
|
||||
int radius = (int)get_value(5u);
|
||||
float4 sum = 0.0;
|
||||
|
||||
for (int ky = 0; ky < kernelSize; ky++)
|
||||
{
|
||||
int sy = clamp((int)p.y + ky - radius, 0, height - 1);
|
||||
for (int kx = 0; kx < kernelSize; kx++)
|
||||
{
|
||||
int sx = clamp((int)p.x + kx - radius, 0, width - 1);
|
||||
float kv = get_value((uint)(8 + ky * kernelSize + kx));
|
||||
float4 sourceValue = source[uint2((uint)sx, (uint)sy)];
|
||||
float3 rgb = sourceValue.a <= 0.0 ? 0.0 : saturate(sourceValue.rgb / sourceValue.a);
|
||||
sum += float4(rgb, sourceValue.a) * kv;
|
||||
}
|
||||
}
|
||||
|
||||
float3 rgbOut = saturate(sum.rgb / divisor + offset);
|
||||
float alpha = saturate(sum.a / divisor + offset);
|
||||
return float4(
|
||||
convolve_channel(rgbOut.r * alpha),
|
||||
convolve_channel(rgbOut.g * alpha),
|
||||
convolve_channel(rgbOut.b * alpha),
|
||||
convolve_channel(alpha));
|
||||
}
|
||||
@@ -0,0 +1,21 @@
|
||||
Texture2D source : register(t0);
|
||||
|
||||
cbuffer Parameters : register(b0)
|
||||
{
|
||||
float4 color;
|
||||
float4 rect;
|
||||
};
|
||||
|
||||
float4 fill_full(float4 pos : SV_Position) : SV_Target
|
||||
{
|
||||
return color;
|
||||
}
|
||||
|
||||
float4 fill_partial(float4 pos : SV_Position) : SV_Target
|
||||
{
|
||||
uint2 p = (uint2)floor(pos.xy);
|
||||
uint4 r = (uint4)rect;
|
||||
if (p.x >= r.x && p.y >= r.y && p.x < r.z && p.y < r.w)
|
||||
return color;
|
||||
return source[p];
|
||||
}
|
||||
@@ -0,0 +1,56 @@
|
||||
Texture2D source : register(t0);
|
||||
|
||||
cbuffer Parameters : register(b0)
|
||||
{
|
||||
float4 size;
|
||||
};
|
||||
|
||||
float channel(float value)
|
||||
{
|
||||
return floor(saturate(value) * 255.0) / 255.0;
|
||||
}
|
||||
|
||||
float4 resize_pack(float4 value)
|
||||
{
|
||||
return float4(channel(value.r), channel(value.g), channel(value.b), channel(value.a));
|
||||
}
|
||||
|
||||
float4 resize_nearest(float4 pos : SV_Position) : SV_Target
|
||||
{
|
||||
uint2 p = (uint2)floor(pos.xy);
|
||||
uint sourceWidth = (uint)size.x;
|
||||
uint sourceHeight = (uint)size.y;
|
||||
uint targetWidth = (uint)size.z;
|
||||
uint targetHeight = (uint)size.w;
|
||||
uint sx = min(((p.x * 2u + 1u) * sourceWidth) / (targetWidth * 2u), sourceWidth - 1u);
|
||||
uint sy = min(((p.y * 2u + 1u) * sourceHeight) / (targetHeight * 2u), sourceHeight - 1u);
|
||||
return source[uint2(sx, sy)];
|
||||
}
|
||||
|
||||
float4 resize_linear(float4 pos : SV_Position) : SV_Target
|
||||
{
|
||||
uint2 p = (uint2)floor(pos.xy);
|
||||
float sourceWidth = size.x;
|
||||
float sourceHeight = size.y;
|
||||
float targetWidth = size.z;
|
||||
float targetHeight = size.w;
|
||||
float u = (p.x + 0.5) * sourceWidth / targetWidth - 0.5;
|
||||
float v = (p.y + 0.5) * sourceHeight / targetHeight - 0.5;
|
||||
int x0 = (int)floor(u);
|
||||
int y0 = (int)floor(v);
|
||||
float tx = u - x0;
|
||||
float ty = v - y0;
|
||||
int maxX = (int)sourceWidth - 1;
|
||||
int maxY = (int)sourceHeight - 1;
|
||||
uint xA = (uint)clamp(x0, 0, maxX);
|
||||
uint yA = (uint)clamp(y0, 0, maxY);
|
||||
uint xB = (uint)clamp(x0 + 1, 0, maxX);
|
||||
uint yB = (uint)clamp(y0 + 1, 0, maxY);
|
||||
float4 c00 = source[uint2(xA, yA)];
|
||||
float4 c10 = source[uint2(xB, yA)];
|
||||
float4 c01 = source[uint2(xA, yB)];
|
||||
float4 c11 = source[uint2(xB, yB)];
|
||||
float4 top = c00 * (1.0 - tx) + c10 * tx;
|
||||
float4 bottom = c01 * (1.0 - tx) + c11 * tx;
|
||||
return resize_pack(top * (1.0 - ty) + bottom * ty);
|
||||
}
|
||||
@@ -6,7 +6,7 @@ namespace LuaScript.Engine.Kernel
|
||||
internal sealed class KernelExtractor
|
||||
{
|
||||
private readonly List<KExpr> _bindings = [];
|
||||
private readonly Dictionary<string, int> _scope = new(StringComparer.Ordinal);
|
||||
private Dictionary<string, int> _scope = new(StringComparer.Ordinal);
|
||||
private readonly SortedSet<KernelUniform> _uniforms = [];
|
||||
|
||||
private string _widthVariable = string.Empty;
|
||||
@@ -46,25 +46,26 @@ namespace LuaScript.Engine.Kernel
|
||||
|
||||
if (index >= block.Count || block[index] is not NumericForStmt outer)
|
||||
return null;
|
||||
if (index + 1 != block.Count)
|
||||
int tail = index + 1;
|
||||
if (tail < block.Count && IsPutPixelData(block[tail]))
|
||||
tail++;
|
||||
if (tail != block.Count)
|
||||
return null;
|
||||
|
||||
if (!TryAxis(outer, out string outerVar, out KAxis outerAxis))
|
||||
return null;
|
||||
_scope.Remove(outerVar);
|
||||
if (outer.Body.Count != 1 || outer.Body[0] is not NumericForStmt inner)
|
||||
return null;
|
||||
if (!TryAxis(inner, out string innerVar, out KAxis innerAxis))
|
||||
return null;
|
||||
_scope.Remove(innerVar);
|
||||
if (outerAxis == innerAxis)
|
||||
return null;
|
||||
if (_pixelDataVariable is not null &&
|
||||
(string.Equals(outerVar, _pixelDataVariable, StringComparison.Ordinal) ||
|
||||
string.Equals(innerVar, _pixelDataVariable, StringComparison.Ordinal)))
|
||||
return null;
|
||||
if (_scope.ContainsKey(outerVar))
|
||||
_scope.Remove(outerVar);
|
||||
if (_scope.ContainsKey(innerVar))
|
||||
_scope.Remove(innerVar);
|
||||
|
||||
_widthVariable = outerAxis == KAxis.X ? outerVar : innerVar;
|
||||
_heightVariable = outerAxis == KAxis.Y ? outerVar : innerVar;
|
||||
@@ -72,6 +73,13 @@ namespace LuaScript.Engine.Kernel
|
||||
return _pixelDataVariable is null ? BuildKernel(inner.Body) : BuildPixelDataKernel(inner.Body);
|
||||
}
|
||||
|
||||
private bool IsPutPixelData(LuaStmt statement) =>
|
||||
_pixelDataVariable is not null &&
|
||||
statement is CallStmt { Call: CallExpr { Arguments.Count: 1 } call } &&
|
||||
IsObjectMethod(call, "putpixeldata") &&
|
||||
call.Arguments[0] is NameExpr { } handle &&
|
||||
string.Equals(handle.Name, _pixelDataVariable, StringComparison.Ordinal);
|
||||
|
||||
private bool TryBindPixelData(LocalStmt local)
|
||||
{
|
||||
if (local.Names.Count != 1 || local.Values.Count != 1 ||
|
||||
@@ -105,6 +113,9 @@ namespace LuaScript.Engine.Kernel
|
||||
case AssignStmt assign:
|
||||
BindAssign(assign);
|
||||
break;
|
||||
case IfStmt conditional:
|
||||
LowerConditional(conditional);
|
||||
break;
|
||||
case CallStmt { Call: MethodCallExpr set } when IsPixelDataSet(set, out int writeChannel):
|
||||
var value = ClampChannel(Lower(set.Arguments[1]));
|
||||
if (writeChannel == 0) outR = value;
|
||||
@@ -140,11 +151,25 @@ namespace LuaScript.Engine.Kernel
|
||||
if (expression is MemberExpr { Target: NameExpr { Name: "obj" }, Name: var field } &&
|
||||
KernelUniforms.TryResolveMember("obj", field, out var uniform))
|
||||
return uniform == KernelUniform.Width;
|
||||
if (expression is NameExpr { } alias &&
|
||||
TryUniformAlias(alias.Name, out var aliased))
|
||||
return aliased == KernelUniform.Width;
|
||||
return _pixelDataVariable is not null &&
|
||||
expression is MemberExpr { Target: NameExpr { } target, Name: "width" } &&
|
||||
string.Equals(target.Name, _pixelDataVariable, StringComparison.Ordinal);
|
||||
}
|
||||
|
||||
private bool TryUniformAlias(string name, out KernelUniform uniform)
|
||||
{
|
||||
if (_scope.TryGetValue(name, out int slot) && _bindings[slot] is KUniformRef reference)
|
||||
{
|
||||
uniform = reference.Uniform;
|
||||
return true;
|
||||
}
|
||||
uniform = default;
|
||||
return false;
|
||||
}
|
||||
|
||||
private bool TryPixelDataChannel(LuaExpr expression, out int channel)
|
||||
{
|
||||
channel = 0;
|
||||
@@ -221,6 +246,9 @@ namespace LuaScript.Engine.Kernel
|
||||
case AssignStmt assign:
|
||||
BindAssign(assign);
|
||||
break;
|
||||
case IfStmt conditional:
|
||||
LowerConditional(conditional);
|
||||
break;
|
||||
default:
|
||||
return null;
|
||||
}
|
||||
@@ -276,6 +304,76 @@ namespace LuaScript.Engine.Kernel
|
||||
_scope[((NameExpr)assign.Targets[i]).Name] = AddBinding(lowered[i]);
|
||||
}
|
||||
|
||||
private void LowerConditional(IfStmt statement) =>
|
||||
LowerConditional(statement.Clauses, 0, statement.ElseBody);
|
||||
|
||||
private void LowerConditional(IReadOnlyList<IfClause> clauses, int index, IReadOnlyList<LuaStmt>? elseBody)
|
||||
{
|
||||
var clause = clauses[index];
|
||||
var condition = LowerBool(clause.Condition);
|
||||
var baseline = _scope;
|
||||
|
||||
_scope = new Dictionary<string, int>(baseline, StringComparer.Ordinal);
|
||||
LowerBranchBody(clause.Body);
|
||||
var taken = _scope;
|
||||
|
||||
_scope = new Dictionary<string, int>(baseline, StringComparer.Ordinal);
|
||||
if (index + 1 < clauses.Count)
|
||||
LowerConditional(clauses, index + 1, elseBody);
|
||||
else if (elseBody is not null)
|
||||
LowerBranchBody(elseBody);
|
||||
var skipped = _scope;
|
||||
|
||||
var merged = new Dictionary<string, int>(baseline.Count, StringComparer.Ordinal);
|
||||
foreach (var name in baseline.Keys)
|
||||
{
|
||||
int whenTrue = taken[name];
|
||||
int whenFalse = skipped[name];
|
||||
merged[name] = whenTrue == whenFalse
|
||||
? whenTrue
|
||||
: AddBinding(new KSelect(condition, new KLocalRef(whenTrue), new KLocalRef(whenFalse)));
|
||||
}
|
||||
_scope = merged;
|
||||
}
|
||||
|
||||
private void LowerBranchBody(IReadOnlyList<LuaStmt> body)
|
||||
{
|
||||
Dictionary<string, int>? shadowed = null;
|
||||
HashSet<string>? introduced = null;
|
||||
foreach (var statement in body)
|
||||
{
|
||||
switch (statement)
|
||||
{
|
||||
case LocalStmt local:
|
||||
foreach (var name in local.Names)
|
||||
{
|
||||
if (introduced?.Contains(name) == true || shadowed?.ContainsKey(name) == true)
|
||||
continue;
|
||||
if (_scope.TryGetValue(name, out int slot))
|
||||
(shadowed ??= new(StringComparer.Ordinal))[name] = slot;
|
||||
else
|
||||
(introduced ??= new(StringComparer.Ordinal)).Add(name);
|
||||
}
|
||||
BindLocal(local);
|
||||
break;
|
||||
case AssignStmt assign:
|
||||
BindAssign(assign);
|
||||
break;
|
||||
case IfStmt nested:
|
||||
LowerConditional(nested);
|
||||
break;
|
||||
default:
|
||||
throw new KernelUnsupportedException("Unsupported statement in a conditional branch.");
|
||||
}
|
||||
}
|
||||
if (shadowed is not null)
|
||||
foreach (var (name, slot) in shadowed)
|
||||
_scope[name] = slot;
|
||||
if (introduced is not null)
|
||||
foreach (var name in introduced)
|
||||
_scope.Remove(name);
|
||||
}
|
||||
|
||||
private void EnsureNotCoordinateName(string name)
|
||||
{
|
||||
if (string.Equals(name, _widthVariable, StringComparison.Ordinal) ||
|
||||
@@ -343,6 +441,16 @@ namespace LuaScript.Engine.Kernel
|
||||
if (member.Target is NameExpr target && KernelUniforms.TryResolveMember(target.Name, member.Name, out var uniform))
|
||||
return UseUniform(uniform);
|
||||
|
||||
if (_pixelDataVariable is not null &&
|
||||
member.Target is NameExpr { } handle &&
|
||||
string.Equals(handle.Name, _pixelDataVariable, StringComparison.Ordinal))
|
||||
{
|
||||
if (string.Equals(member.Name, "width", StringComparison.Ordinal))
|
||||
return UseUniform(KernelUniform.Width);
|
||||
if (string.Equals(member.Name, "height", StringComparison.Ordinal))
|
||||
return UseUniform(KernelUniform.Height);
|
||||
}
|
||||
|
||||
throw new KernelUnsupportedException("Unsupported member access in pixel kernel.");
|
||||
}
|
||||
|
||||
@@ -474,6 +582,20 @@ namespace LuaScript.Engine.Kernel
|
||||
return true;
|
||||
}
|
||||
}
|
||||
|
||||
if (bound.Left is NameExpr { } alias && TryUniformAlias(alias.Name, out var aliased))
|
||||
{
|
||||
if (aliased == KernelUniform.Width)
|
||||
{
|
||||
axis = KAxis.X;
|
||||
return true;
|
||||
}
|
||||
if (aliased == KernelUniform.Height)
|
||||
{
|
||||
axis = KAxis.Y;
|
||||
return true;
|
||||
}
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
|
||||
@@ -3,7 +3,7 @@
|
||||
<PropertyGroup>
|
||||
<TargetFramework>net10.0-windows10.0.19041.0</TargetFramework>
|
||||
<ImplicitUsings>enable</ImplicitUsings>
|
||||
<Version>1.15.0</Version>
|
||||
<Version>1.20.2</Version>
|
||||
<Platforms>AnyCPU;x64</Platforms>
|
||||
<Nullable>enable</Nullable>
|
||||
</PropertyGroup>
|
||||
|
||||
@@ -3,7 +3,7 @@
|
||||
<PropertyGroup>
|
||||
<TargetFramework>net10.0-windows10.0.19041.0</TargetFramework>
|
||||
<ImplicitUsings>enable</ImplicitUsings>
|
||||
<Version>1.15.0</Version>
|
||||
<Version>1.20.2</Version>
|
||||
<Platforms>AnyCPU;x64</Platforms>
|
||||
<Nullable>enable</Nullable>
|
||||
<AllowUnsafeBlocks>true</AllowUnsafeBlocks>
|
||||
|
||||
@@ -9,6 +9,13 @@ namespace LuaScript.Anchor
|
||||
|
||||
public static int ClampCount(int count) => Math.Clamp(count, 0, MaxAnchors);
|
||||
|
||||
public static int NormalizeCount(string group, int count)
|
||||
{
|
||||
if (count <= 0 && string.Equals(group, TrackGroup, StringComparison.Ordinal))
|
||||
return 1;
|
||||
return ClampCount(count);
|
||||
}
|
||||
|
||||
public static void ApplyOption(string option, ref AnchorConnection connection, ref bool is3D)
|
||||
{
|
||||
switch (option)
|
||||
@@ -52,6 +59,35 @@ namespace LuaScript.Anchor
|
||||
z = 0d;
|
||||
}
|
||||
|
||||
public static ImmutableList<LuaAnchorPoint> SetPosition(
|
||||
ImmutableList<LuaAnchorPoint> source, string group, int index, double x, double y, double z)
|
||||
{
|
||||
for (int i = 0; i < source.Count; i++)
|
||||
{
|
||||
var a = source[i];
|
||||
if (a.Index == index && string.Equals(a.Group, group, StringComparison.Ordinal))
|
||||
{
|
||||
return source.SetItem(i, new LuaAnchorPoint
|
||||
{
|
||||
Group = group,
|
||||
Index = index,
|
||||
X = x,
|
||||
Y = y,
|
||||
Z = z,
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
return source.Add(new LuaAnchorPoint
|
||||
{
|
||||
Group = group,
|
||||
Index = index,
|
||||
X = x,
|
||||
Y = y,
|
||||
Z = z,
|
||||
});
|
||||
}
|
||||
|
||||
public static ImmutableList<LuaAnchorPoint> ApplyDrag(
|
||||
ImmutableList<LuaAnchorPoint> source, string group, int index, double dx, double dy, double dz)
|
||||
{
|
||||
|
||||
@@ -60,6 +60,7 @@ namespace LuaScript.Api
|
||||
}
|
||||
|
||||
var candidates = Keywords
|
||||
.Concat(LuaScript.Compat.Syntax.LuaSyntaxRuleRegistry.CatalogKeywords)
|
||||
.Concat(globals)
|
||||
.Concat(tableMembers.Keys)
|
||||
.Concat(tableMembers.Values.SelectMany(x => x))
|
||||
|
||||
@@ -72,6 +72,12 @@ namespace LuaScript
|
||||
|
||||
public Func<ISceneObjectResolver>? ResolverProvider { get; set; }
|
||||
|
||||
public Func<string, double, (byte[] Buffer, int Width, int Height)>? SceneImageLoader { get; set; }
|
||||
|
||||
public Func<string, double, double, IReadOnlyList<KeyValuePair<string, object>>, (byte[] Buffer, int Width, int Height)>? BrushImageLoader { get; set; }
|
||||
|
||||
public Func<string, string, int, (int Count, int Rate, double[] Data)>? AudioLoader { get; set; }
|
||||
|
||||
private readonly Dictionary<string, string> _stringParameters = new(StringComparer.Ordinal);
|
||||
|
||||
public IReadOnlyDictionary<string, string> StringParameters => _stringParameters;
|
||||
@@ -163,6 +169,8 @@ namespace LuaScript
|
||||
|
||||
internal IPixelShaderRunner? ShaderRunner { get; set; }
|
||||
|
||||
internal IPixelBufferProcessor? PixelProcessor { get; set; }
|
||||
|
||||
internal AviUtlPixelShaderLibrary PixelShaders { get; set; } = AviUtlPixelShaderLibrary.Empty;
|
||||
|
||||
internal bool TryGetShaderResource(string id, out byte[] data, out int width, out int height) =>
|
||||
@@ -498,5 +506,158 @@ namespace LuaScript
|
||||
p[3] = (byte)Math.Clamp(a, 0d, 255d);
|
||||
}
|
||||
}
|
||||
|
||||
private double[]? _convolveSource;
|
||||
private byte[]? _resizeSource;
|
||||
private byte[]? _resizeBuffer;
|
||||
|
||||
public unsafe void FillBuffer(double r, double g, double b, double a, int x, int y, int w, int h, bool force = false)
|
||||
{
|
||||
EnsurePixelBuffer();
|
||||
if (_pixelBuffer is null)
|
||||
return;
|
||||
|
||||
int cw = ImageWidth;
|
||||
int ch = ImageHeight;
|
||||
int x0 = Math.Clamp(x, 0, cw);
|
||||
int y0 = Math.Clamp(y, 0, ch);
|
||||
int x1 = Math.Clamp(x + w, 0, cw);
|
||||
int y1 = Math.Clamp(y + h, 0, ch);
|
||||
if (x1 <= x0 || y1 <= y0)
|
||||
return;
|
||||
|
||||
if (PixelProcessor?.TryFill(_pixelBuffer, cw, ch, r, g, b, a, x0, y0, x1 - x0, y1 - y0, force) == true)
|
||||
{
|
||||
_isPixelsDirty = true;
|
||||
return;
|
||||
}
|
||||
|
||||
_isPixelsDirty = true;
|
||||
PixelBufferSoftwareProcessor.Fill(_pixelBuffer, cw, ch, r, g, b, a, x0, y0, x1 - x0, y1 - y0);
|
||||
}
|
||||
|
||||
public unsafe void ReadRegion(int x, int y, int w, int h, double[] destination)
|
||||
{
|
||||
EnsurePixelBuffer();
|
||||
int cw = ImageWidth;
|
||||
int ch = ImageHeight;
|
||||
if (_pixelBuffer is null)
|
||||
{
|
||||
Array.Clear(destination, 0, w * h * 4);
|
||||
return;
|
||||
}
|
||||
|
||||
fixed (byte* buf = _pixelBuffer)
|
||||
{
|
||||
for (int j = 0; j < h; j++)
|
||||
{
|
||||
int sy = y + j;
|
||||
for (int i = 0; i < w; i++)
|
||||
{
|
||||
int sx = x + i;
|
||||
int di = (j * w + i) * 4;
|
||||
if ((uint)sx >= (uint)cw || (uint)sy >= (uint)ch)
|
||||
{
|
||||
destination[di] = 0d;
|
||||
destination[di + 1] = 0d;
|
||||
destination[di + 2] = 0d;
|
||||
destination[di + 3] = 0d;
|
||||
continue;
|
||||
}
|
||||
byte* p = buf + (sy * cw + sx) * 4;
|
||||
double a = p[3];
|
||||
if (a <= 0d)
|
||||
{
|
||||
destination[di] = 0d;
|
||||
destination[di + 1] = 0d;
|
||||
destination[di + 2] = 0d;
|
||||
destination[di + 3] = 0d;
|
||||
}
|
||||
else
|
||||
{
|
||||
double s = 255d / a;
|
||||
destination[di] = Math.Clamp(p[2] * s, 0d, 255d);
|
||||
destination[di + 1] = Math.Clamp(p[1] * s, 0d, 255d);
|
||||
destination[di + 2] = Math.Clamp(p[0] * s, 0d, 255d);
|
||||
destination[di + 3] = a;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
public unsafe void WriteRegion(int x, int y, int w, int h, double[] source)
|
||||
{
|
||||
EnsurePixelBuffer();
|
||||
if (_pixelBuffer is null)
|
||||
return;
|
||||
|
||||
int cw = ImageWidth;
|
||||
int ch = ImageHeight;
|
||||
_isPixelsDirty = true;
|
||||
|
||||
fixed (byte* buf = _pixelBuffer)
|
||||
{
|
||||
for (int j = 0; j < h; j++)
|
||||
{
|
||||
int dy = y + j;
|
||||
if ((uint)dy >= (uint)ch)
|
||||
continue;
|
||||
for (int i = 0; i < w; i++)
|
||||
{
|
||||
int dx = x + i;
|
||||
if ((uint)dx >= (uint)cw)
|
||||
continue;
|
||||
int si = (j * w + i) * 4;
|
||||
double a = Math.Clamp(source[si + 3], 0d, 255d);
|
||||
double aK = a / 255d;
|
||||
byte* p = buf + (dy * cw + dx) * 4;
|
||||
p[0] = (byte)Math.Clamp(source[si + 2] * aK, 0d, 255d);
|
||||
p[1] = (byte)Math.Clamp(source[si + 1] * aK, 0d, 255d);
|
||||
p[2] = (byte)Math.Clamp(source[si] * aK, 0d, 255d);
|
||||
p[3] = (byte)a;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
public unsafe void Convolve(double[] kernel, int size, double divisor, double offset, bool force = false)
|
||||
{
|
||||
EnsurePixelBuffer();
|
||||
if (_pixelBuffer is null)
|
||||
return;
|
||||
|
||||
int cw = ImageWidth;
|
||||
int ch = ImageHeight;
|
||||
if (PixelProcessor?.TryConvolve(_pixelBuffer, cw, ch, kernel, size, divisor, offset, force) == true)
|
||||
{
|
||||
_isPixelsDirty = true;
|
||||
return;
|
||||
}
|
||||
|
||||
_isPixelsDirty = true;
|
||||
PixelBufferSoftwareProcessor.Convolve(_pixelBuffer, cw, ch, kernel, size, divisor, offset, ref _convolveSource);
|
||||
}
|
||||
|
||||
public unsafe void Resize(int newWidth, int newHeight, bool linear, bool force = false)
|
||||
{
|
||||
EnsurePixelBuffer();
|
||||
if (_pixelBuffer is null)
|
||||
return;
|
||||
|
||||
newWidth = Math.Max(1, newWidth);
|
||||
newHeight = Math.Max(1, newHeight);
|
||||
int cw = ImageWidth;
|
||||
int ch = ImageHeight;
|
||||
|
||||
if (PixelProcessor?.TryResize(_pixelBuffer, cw, ch, newWidth, newHeight, linear, out var processed, force) == true && processed is not null)
|
||||
{
|
||||
ReplaceBuffer(processed, newWidth, newHeight);
|
||||
return;
|
||||
}
|
||||
|
||||
var dst = PixelBufferSoftwareProcessor.Resize(_pixelBuffer, cw, ch, newWidth, newHeight, linear, ref _resizeSource, ref _resizeBuffer);
|
||||
ReplaceBuffer(dst, newWidth, newHeight);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,11 @@
|
||||
namespace LuaScript
|
||||
{
|
||||
internal interface IPixelBufferProcessor
|
||||
{
|
||||
bool TryFill(byte[] target, int width, int height, double r, double g, double b, double a, int x, int y, int fillWidth, int fillHeight, bool force = false);
|
||||
|
||||
bool TryConvolve(byte[] target, int width, int height, double[] kernel, int size, double divisor, double offset, bool force = false);
|
||||
|
||||
bool TryResize(byte[] source, int sourceWidth, int sourceHeight, int targetWidth, int targetHeight, bool linear, out byte[]? target, bool force = false);
|
||||
}
|
||||
}
|
||||
@@ -37,12 +37,15 @@ namespace LuaScript.Engine
|
||||
private readonly Dictionary<string, byte[]> _stringNameBytes = new(StringComparer.Ordinal);
|
||||
private byte[] _stringValueBytes = new byte[256];
|
||||
private byte[] _sceneValueBytes = new byte[256];
|
||||
private byte[] _objectMetaBytes = new byte[256];
|
||||
|
||||
private static readonly byte[] s_shaderTransparentPixel = new byte[4];
|
||||
private readonly PixelShaderInput[] _shaderInputs = new PixelShaderInput[NativeProtocol.ShaderResourcesMax];
|
||||
private readonly byte[]?[] _shaderResourceData = new byte[NativeProtocol.ShaderResourcesMax][];
|
||||
private readonly float[] _shaderConstants = new float[NativeProtocol.ShaderConstantsMax];
|
||||
private byte[] _shaderTarget = [];
|
||||
private byte[] _pixelProcessTarget = [];
|
||||
private double[] _pixelProcessKernel = [];
|
||||
|
||||
private long PixelRegionCapacity => _allocatedSize - _pixelOffset - NativeProtocol.ShaderRegionBytes;
|
||||
|
||||
@@ -71,12 +74,16 @@ namespace LuaScript.Engine
|
||||
Func<string, string, double, bool, bool, int, (byte[] buffer, int w, int h)> loadText,
|
||||
Func<string, (byte[] buffer, int w, int h)> loadImage,
|
||||
Func<string, double, (byte[] buffer, int w, int h)> loadMovie,
|
||||
Func<string, double, (byte[] buffer, int w, int h)> loadScene,
|
||||
Func<string, double, double, IReadOnlyList<KeyValuePair<string, object>>, (byte[] buffer, int w, int h)> loadBrush,
|
||||
Action<string, IReadOnlyList<KeyValuePair<string, object>>> addEffect,
|
||||
Action<DrawCommand> addDraw,
|
||||
Action<string, int, bool, int, double[]> setAnchor,
|
||||
Func<string, SceneValue> sceneGetValue,
|
||||
Action<string, SceneValue> sceneSetValue,
|
||||
Func<string, string, int, (int Count, int Rate, double[] Data)> loadAudio,
|
||||
PixelShaderInvoke? runPixelShader,
|
||||
IPixelBufferProcessor? pixelProcessor,
|
||||
out bool pixelsDirty,
|
||||
out bool bufferReplaced,
|
||||
out int resultWidth,
|
||||
@@ -120,16 +127,18 @@ namespace LuaScript.Engine
|
||||
view.Write(NativeProtocol.OffScriptVersion, _scriptVersion);
|
||||
view.Write(NativeProtocol.OffPixelsDirty, 0);
|
||||
view.Write(NativeProtocol.OffErrorLen, 0);
|
||||
view.Write(NativeProtocol.OffCallbackFound, pixelProcessor is null ? -1 : 1);
|
||||
view.Write(NativeProtocol.OffStatus, NativeProtocol.StatusIdle);
|
||||
view.Write(NativeProtocol.OffCommand, NativeProtocol.CmdRun);
|
||||
|
||||
_workEvent!.Set();
|
||||
|
||||
var stopwatch = Stopwatch.StartNew();
|
||||
long budget = timeoutMs;
|
||||
int status;
|
||||
while (true)
|
||||
{
|
||||
long remaining = timeoutMs - stopwatch.ElapsedMilliseconds;
|
||||
long remaining = budget - stopwatch.ElapsedMilliseconds;
|
||||
if (remaining <= 0 || !_doneEvent!.WaitOne((int)remaining))
|
||||
{
|
||||
KillWorker();
|
||||
@@ -141,6 +150,7 @@ namespace LuaScript.Engine
|
||||
if (status != NativeProtocol.StatusCallback)
|
||||
break;
|
||||
|
||||
long callbackStart = stopwatch.ElapsedMilliseconds;
|
||||
int callbackKind = view.ReadInt32(NativeProtocol.OffCallbackKind);
|
||||
if (callbackKind == NativeProtocol.CbKindRequestPixels)
|
||||
{
|
||||
@@ -160,8 +170,9 @@ namespace LuaScript.Engine
|
||||
}
|
||||
else
|
||||
{
|
||||
DispatchCallback(view, resolveObject, loadFigure, loadText, loadImage, loadMovie, addEffect, setAnchor, sceneGetValue, sceneSetValue, runPixelShader);
|
||||
DispatchCallback(view, resolveObject, loadFigure, loadText, loadImage, loadMovie, loadScene, loadBrush, addEffect, setAnchor, sceneGetValue, sceneSetValue, loadAudio, runPixelShader, pixelProcessor);
|
||||
}
|
||||
budget += stopwatch.ElapsedMilliseconds - callbackStart;
|
||||
_workEvent.Set();
|
||||
}
|
||||
|
||||
@@ -321,11 +332,15 @@ namespace LuaScript.Engine
|
||||
Func<string, string, double, bool, bool, int, (byte[] buffer, int w, int h)> loadText,
|
||||
Func<string, (byte[] buffer, int w, int h)> loadImage,
|
||||
Func<string, double, (byte[] buffer, int w, int h)> loadMovie,
|
||||
Func<string, double, (byte[] buffer, int w, int h)> loadScene,
|
||||
Func<string, double, double, IReadOnlyList<KeyValuePair<string, object>>, (byte[] buffer, int w, int h)> loadBrush,
|
||||
Action<string, IReadOnlyList<KeyValuePair<string, object>>> addEffect,
|
||||
Action<string, int, bool, int, double[]> setAnchor,
|
||||
Func<string, SceneValue> sceneGetValue,
|
||||
Action<string, SceneValue> sceneSetValue,
|
||||
PixelShaderInvoke? runPixelShader)
|
||||
Func<string, string, int, (int Count, int Rate, double[] Data)> loadAudio,
|
||||
PixelShaderInvoke? runPixelShader,
|
||||
IPixelBufferProcessor? pixelProcessor)
|
||||
{
|
||||
int kind = view.ReadInt32(NativeProtocol.OffCallbackKind);
|
||||
switch (kind)
|
||||
@@ -345,6 +360,15 @@ namespace LuaScript.Engine
|
||||
case NativeProtocol.CbKindLoadMovie:
|
||||
ResolveLoadMovieCallback(view, loadMovie);
|
||||
break;
|
||||
case NativeProtocol.CbKindLoadScene:
|
||||
ResolveLoadSceneCallback(view, loadScene);
|
||||
break;
|
||||
case NativeProtocol.CbKindLoadBrush:
|
||||
ResolveLoadBrushCallback(view, loadBrush);
|
||||
break;
|
||||
case NativeProtocol.CbKindBrush:
|
||||
ResolveBrushCallback(view, loadBrush);
|
||||
break;
|
||||
case NativeProtocol.CbKindEffect:
|
||||
ResolveEffectCallback(view, addEffect);
|
||||
break;
|
||||
@@ -357,15 +381,110 @@ namespace LuaScript.Engine
|
||||
case NativeProtocol.CbKindSceneSet:
|
||||
ResolveSceneSetCallback(view, sceneSetValue);
|
||||
break;
|
||||
case NativeProtocol.CbKindGetAudio:
|
||||
ResolveGetAudioCallback(view, loadAudio);
|
||||
break;
|
||||
case NativeProtocol.CbKindPixelShaderStage:
|
||||
ResolveShaderStageCallback(view);
|
||||
break;
|
||||
case NativeProtocol.CbKindPixelShaderRun:
|
||||
ResolveShaderRunCallback(view, runPixelShader);
|
||||
break;
|
||||
case NativeProtocol.CbKindPixelProcess:
|
||||
ResolvePixelProcessCallback(view, pixelProcessor);
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
private void ResolvePixelProcessCallback(MemoryMappedViewAccessor view, IPixelBufferProcessor? pixelProcessor)
|
||||
{
|
||||
bool processed = false;
|
||||
if (pixelProcessor is not null)
|
||||
{
|
||||
int width = view.ReadInt32(NativeProtocol.OffWidth);
|
||||
int height = view.ReadInt32(NativeProtocol.OffHeight);
|
||||
long length = (long)width * height * 4;
|
||||
if (width > 0 && height > 0 && length <= PixelRegionCapacity && length <= int.MaxValue)
|
||||
{
|
||||
int pixelLength = (int)length;
|
||||
if (_pixelProcessTarget.Length < pixelLength)
|
||||
_pixelProcessTarget = new byte[pixelLength];
|
||||
|
||||
int operation = (int)view.ReadDouble(NativeProtocol.CallbackResultOffset);
|
||||
bool force = view.ReadDouble(NativeProtocol.CallbackResultOffset + 9 * 8) != 0d;
|
||||
processed = operation switch
|
||||
{
|
||||
NativeProtocol.PixelProcessFill => TryProcessFill(view, pixelProcessor, width, height, pixelLength, force),
|
||||
NativeProtocol.PixelProcessConvolve => TryProcessConvolve(view, pixelProcessor, width, height, pixelLength, force),
|
||||
NativeProtocol.PixelProcessResize => TryProcessResize(view, pixelProcessor, pixelLength, force),
|
||||
_ => false,
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
view.Write(NativeProtocol.OffCallbackFound, processed ? 1 : pixelProcessor is null ? -1 : 0);
|
||||
}
|
||||
|
||||
private bool TryProcessFill(MemoryMappedViewAccessor view, IPixelBufferProcessor pixelProcessor, int width, int height, int pixelLength, bool force)
|
||||
{
|
||||
long offset = NativeProtocol.CallbackResultOffset;
|
||||
double r = view.ReadDouble(offset + 1 * 8);
|
||||
double g = view.ReadDouble(offset + 2 * 8);
|
||||
double b = view.ReadDouble(offset + 3 * 8);
|
||||
double a = view.ReadDouble(offset + 4 * 8);
|
||||
int x = (int)view.ReadDouble(offset + 5 * 8);
|
||||
int y = (int)view.ReadDouble(offset + 6 * 8);
|
||||
int fillWidth = (int)view.ReadDouble(offset + 7 * 8);
|
||||
int fillHeight = (int)view.ReadDouble(offset + 8 * 8);
|
||||
if (x != 0 || y != 0 || fillWidth != width || fillHeight != height)
|
||||
ReadRegion(_pixelOffset, _pixelProcessTarget, pixelLength);
|
||||
if (!pixelProcessor.TryFill(_pixelProcessTarget, width, height, r, g, b, a, x, y, fillWidth, fillHeight, force))
|
||||
return false;
|
||||
WriteRegion(_pixelOffset, _pixelProcessTarget, pixelLength);
|
||||
return true;
|
||||
}
|
||||
|
||||
private bool TryProcessConvolve(MemoryMappedViewAccessor view, IPixelBufferProcessor pixelProcessor, int width, int height, int pixelLength, bool force)
|
||||
{
|
||||
long offset = NativeProtocol.CallbackResultOffset;
|
||||
int size = (int)view.ReadDouble(offset + 1 * 8);
|
||||
double divisor = view.ReadDouble(offset + 2 * 8);
|
||||
double kernelOffset = view.ReadDouble(offset + 3 * 8);
|
||||
if (size < 1 || (size & 1) == 0)
|
||||
return false;
|
||||
int taps = size * size;
|
||||
if (taps <= 0 || taps * 8 > Math.Clamp(view.ReadInt32(NativeProtocol.OffCallbackTagLen), 0, NativeProtocol.CallbackTagMax))
|
||||
return false;
|
||||
if (_pixelProcessKernel.Length < taps)
|
||||
_pixelProcessKernel = new double[taps];
|
||||
ReadRegion(_pixelOffset, _pixelProcessTarget, pixelLength);
|
||||
view.ReadArray(NativeProtocol.CallbackTagOffset, _pixelProcessKernel, 0, taps);
|
||||
if (!pixelProcessor.TryConvolve(_pixelProcessTarget, width, height, _pixelProcessKernel, size, divisor, kernelOffset, force))
|
||||
return false;
|
||||
WriteRegion(_pixelOffset, _pixelProcessTarget, pixelLength);
|
||||
return true;
|
||||
}
|
||||
|
||||
private bool TryProcessResize(MemoryMappedViewAccessor view, IPixelBufferProcessor pixelProcessor, int sourceLength, bool force)
|
||||
{
|
||||
long offset = NativeProtocol.CallbackResultOffset;
|
||||
int targetWidth = (int)view.ReadDouble(offset + 1 * 8);
|
||||
int targetHeight = (int)view.ReadDouble(offset + 2 * 8);
|
||||
bool linear = view.ReadDouble(offset + 3 * 8) != 0d;
|
||||
long length = (long)targetWidth * targetHeight * 4;
|
||||
int sourceWidth = view.ReadInt32(NativeProtocol.OffWidth);
|
||||
int sourceHeight = view.ReadInt32(NativeProtocol.OffHeight);
|
||||
if (targetWidth <= 0 || targetHeight <= 0 || length > PixelRegionCapacity || length > int.MaxValue)
|
||||
return false;
|
||||
ReadRegion(_pixelOffset, _pixelProcessTarget, sourceLength);
|
||||
if (!pixelProcessor.TryResize(_pixelProcessTarget, sourceWidth, sourceHeight, targetWidth, targetHeight, linear, out var target, force) || target is null)
|
||||
return false;
|
||||
WriteRegion(_pixelOffset, target, (int)length);
|
||||
view.Write(NativeProtocol.OffWidth, targetWidth);
|
||||
view.Write(NativeProtocol.OffHeight, targetHeight);
|
||||
return true;
|
||||
}
|
||||
|
||||
private void ResolveShaderStageCallback(MemoryMappedViewAccessor view)
|
||||
{
|
||||
long meta = NativeProtocol.ShaderMetaOffset(_allocatedSize);
|
||||
@@ -557,6 +676,40 @@ namespace LuaScript.Engine
|
||||
view.Write(NativeProtocol.OffCallbackFound, 1);
|
||||
}
|
||||
|
||||
private static readonly double[] s_noAudioData = [];
|
||||
|
||||
private void ResolveGetAudioCallback(
|
||||
MemoryMappedViewAccessor view,
|
||||
Func<string, string, int, (int Count, int Rate, double[] Data)> loadAudio)
|
||||
{
|
||||
int tagLen = Math.Clamp(view.ReadInt32(NativeProtocol.OffCallbackTagLen), 0, NativeProtocol.CallbackTagMax);
|
||||
view.ReadArray(NativeProtocol.CallbackTagOffset, _callbackTag, 0, tagLen);
|
||||
int separator = Array.IndexOf(_callbackTag, (byte)0, 0, tagLen);
|
||||
string file = Encoding.UTF8.GetString(_callbackTag, 0, separator >= 0 ? separator : tagLen);
|
||||
string type = separator >= 0
|
||||
? Encoding.UTF8.GetString(_callbackTag, separator + 1, tagLen - separator - 1)
|
||||
: "pcm";
|
||||
int size = (int)view.ReadDouble(NativeProtocol.CallbackResultOffset);
|
||||
|
||||
int count = 0;
|
||||
int rate = 0;
|
||||
double[] data = s_noAudioData;
|
||||
try { (count, rate, data) = loadAudio(file, type, size); }
|
||||
catch
|
||||
{
|
||||
count = 0;
|
||||
rate = 0;
|
||||
data = s_noAudioData;
|
||||
}
|
||||
|
||||
count = Math.Clamp(count, 0, Math.Min(data.Length, NativeProtocol.CallbackTagMax / 8));
|
||||
if (count > 0)
|
||||
view.WriteArray(NativeProtocol.CallbackTagOffset, data, 0, count);
|
||||
view.Write(NativeProtocol.CallbackResultOffset, (double)count);
|
||||
view.Write(NativeProtocol.CallbackResultOffset + 8, (double)rate);
|
||||
view.Write(NativeProtocol.OffCallbackFound, 1);
|
||||
}
|
||||
|
||||
private void ResolveSetAnchorCallback(MemoryMappedViewAccessor view, Action<string, int, bool, int, double[]> setAnchor)
|
||||
{
|
||||
int tagLen = Math.Clamp(view.ReadInt32(NativeProtocol.OffCallbackTagLen), 0, NativeProtocol.CallbackTagMax);
|
||||
@@ -644,6 +797,9 @@ namespace LuaScript.Engine
|
||||
view.Write(result + NativeProtocol.CbRz * 8, value.Rz);
|
||||
view.Write(result + NativeProtocol.CbAlpha * 8, value.Alpha);
|
||||
view.Write(result + NativeProtocol.CbLayer * 8, (double)value.Layer);
|
||||
view.Write(result + NativeProtocol.CbVolume * 8, value.Volume);
|
||||
view.Write(result + NativeProtocol.CbLength * 8, (double)value.Length);
|
||||
WriteObjectMeta(view, value.Character, value.Text, value.Kind);
|
||||
view.Write(NativeProtocol.OffCallbackFound, 1);
|
||||
}
|
||||
else
|
||||
@@ -652,6 +808,27 @@ namespace LuaScript.Engine
|
||||
}
|
||||
}
|
||||
|
||||
private void WriteObjectMeta(MemoryMappedViewAccessor view, string character, string text, string kind)
|
||||
{
|
||||
character ??= string.Empty;
|
||||
text ??= string.Empty;
|
||||
kind ??= string.Empty;
|
||||
int maxBytes = Encoding.UTF8.GetMaxByteCount(character.Length + text.Length + kind.Length) + 2;
|
||||
if (_objectMetaBytes.Length < maxBytes)
|
||||
_objectMetaBytes = new byte[Math.Max(maxBytes, _objectMetaBytes.Length * 2)];
|
||||
|
||||
int length = Encoding.UTF8.GetBytes(character, 0, character.Length, _objectMetaBytes, 0);
|
||||
_objectMetaBytes[length++] = 0;
|
||||
length += Encoding.UTF8.GetBytes(text, 0, text.Length, _objectMetaBytes, length);
|
||||
_objectMetaBytes[length++] = 0;
|
||||
length += Encoding.UTF8.GetBytes(kind, 0, kind.Length, _objectMetaBytes, length);
|
||||
if (length > NativeProtocol.CallbackTagMax)
|
||||
length = NativeProtocol.CallbackTagMax;
|
||||
|
||||
view.WriteArray(NativeProtocol.CallbackTagOffset, _objectMetaBytes, 0, length);
|
||||
view.Write(NativeProtocol.OffCallbackTagLen, length);
|
||||
}
|
||||
|
||||
private void ResolveLoadFigureCallback(
|
||||
MemoryMappedViewAccessor view,
|
||||
Func<string, int, double, double, double, (byte[] buffer, int w, int h)> loadFigure)
|
||||
@@ -772,16 +949,100 @@ namespace LuaScript.Engine
|
||||
view.Write(NativeProtocol.OffCallbackFound, 1);
|
||||
}
|
||||
|
||||
private void ResolveEffectCallback(MemoryMappedViewAccessor view, Action<string, IReadOnlyList<KeyValuePair<string, object>>> addEffect)
|
||||
private void ResolveLoadSceneCallback(
|
||||
MemoryMappedViewAccessor view,
|
||||
Func<string, double, (byte[] buffer, int w, int h)> loadScene)
|
||||
{
|
||||
int tagLen = Math.Clamp(view.ReadInt32(NativeProtocol.OffCallbackTagLen), 0, NativeProtocol.CallbackTagMax);
|
||||
view.ReadArray(NativeProtocol.CallbackTagOffset, _callbackTag, 0, tagLen);
|
||||
string name = Encoding.UTF8.GetString(_callbackTag, 0, tagLen);
|
||||
double time = view.ReadDouble(NativeProtocol.CallbackResultOffset);
|
||||
|
||||
(byte[] buffer, int w, int h) result;
|
||||
try { result = loadScene(name, time); }
|
||||
catch { result = ([], 0, 0); }
|
||||
|
||||
long pixelSize = (long)result.w * result.h * 4;
|
||||
if (result.w <= 0 || result.h <= 0 || pixelSize > PixelRegionCapacity)
|
||||
{
|
||||
view.Write(NativeProtocol.OffLoadResultWidth, 0);
|
||||
view.Write(NativeProtocol.OffLoadResultHeight, 0);
|
||||
view.Write(NativeProtocol.OffCallbackFound, 0);
|
||||
return;
|
||||
}
|
||||
|
||||
view.Write(NativeProtocol.OffLoadResultWidth, result.w);
|
||||
view.Write(NativeProtocol.OffLoadResultHeight, result.h);
|
||||
WritePixelRegion(result.buffer, (int)pixelSize);
|
||||
view.Write(NativeProtocol.OffCallbackFound, 1);
|
||||
}
|
||||
|
||||
private static readonly KeyValuePair<string, object>[] s_noBrushArguments = [];
|
||||
|
||||
private void ResolveLoadBrushCallback(
|
||||
MemoryMappedViewAccessor view,
|
||||
Func<string, double, double, IReadOnlyList<KeyValuePair<string, object>>, (byte[] buffer, int w, int h)> loadBrush)
|
||||
{
|
||||
int tagLen = Math.Clamp(view.ReadInt32(NativeProtocol.OffCallbackTagLen), 0, NativeProtocol.CallbackTagMax);
|
||||
view.ReadArray(NativeProtocol.CallbackTagOffset, _callbackTag, 0, tagLen);
|
||||
string name = Encoding.UTF8.GetString(_callbackTag, 0, tagLen);
|
||||
|
||||
WriteBrushResult(view, loadBrush, name, s_noBrushArguments);
|
||||
}
|
||||
|
||||
private void ResolveBrushCallback(
|
||||
MemoryMappedViewAccessor view,
|
||||
Func<string, double, double, IReadOnlyList<KeyValuePair<string, object>>, (byte[] buffer, int w, int h)> loadBrush)
|
||||
{
|
||||
int tagLen = Math.Clamp(view.ReadInt32(NativeProtocol.OffCallbackTagLen), 0, NativeProtocol.CallbackTagMax);
|
||||
view.ReadArray(NativeProtocol.CallbackTagOffset, _callbackTag, 0, tagLen);
|
||||
|
||||
var segments = Encoding.UTF8.GetString(_callbackTag, 0, tagLen).Split('\0');
|
||||
if (segments.Length == 0)
|
||||
{
|
||||
view.Write(NativeProtocol.OffLoadResultWidth, 0);
|
||||
view.Write(NativeProtocol.OffLoadResultHeight, 0);
|
||||
view.Write(NativeProtocol.OffCallbackFound, 0);
|
||||
return;
|
||||
}
|
||||
|
||||
WriteBrushResult(view, loadBrush, segments[0], ParseNamedArguments(segments));
|
||||
}
|
||||
|
||||
private void WriteBrushResult(
|
||||
MemoryMappedViewAccessor view,
|
||||
Func<string, double, double, IReadOnlyList<KeyValuePair<string, object>>, (byte[] buffer, int w, int h)> loadBrush,
|
||||
string name,
|
||||
IReadOnlyList<KeyValuePair<string, object>> arguments)
|
||||
{
|
||||
long rOff = NativeProtocol.CallbackResultOffset;
|
||||
double width = view.ReadDouble(rOff + 0 * 8);
|
||||
double height = view.ReadDouble(rOff + 1 * 8);
|
||||
|
||||
(byte[] buffer, int w, int h) result;
|
||||
try { result = loadBrush(name, width, height, arguments); }
|
||||
catch { result = ([], 0, 0); }
|
||||
|
||||
long pixelSize = (long)result.w * result.h * 4;
|
||||
if (result.w <= 0 || result.h <= 0 || pixelSize > PixelRegionCapacity)
|
||||
{
|
||||
view.Write(NativeProtocol.OffLoadResultWidth, 0);
|
||||
view.Write(NativeProtocol.OffLoadResultHeight, 0);
|
||||
view.Write(NativeProtocol.OffCallbackFound, 0);
|
||||
return;
|
||||
}
|
||||
|
||||
view.Write(NativeProtocol.OffLoadResultWidth, result.w);
|
||||
view.Write(NativeProtocol.OffLoadResultHeight, result.h);
|
||||
WritePixelRegion(result.buffer, (int)pixelSize);
|
||||
view.Write(NativeProtocol.OffCallbackFound, 1);
|
||||
}
|
||||
|
||||
private static IReadOnlyList<KeyValuePair<string, object>> ParseNamedArguments(string[] segments)
|
||||
{
|
||||
if (segments.Length < 3)
|
||||
return s_noBrushArguments;
|
||||
|
||||
string effectName = segments[0];
|
||||
var arguments = new List<KeyValuePair<string, object>>();
|
||||
for (int i = 1; i + 1 < segments.Length; i += 2)
|
||||
{
|
||||
@@ -798,8 +1059,19 @@ namespace LuaScript.Engine
|
||||
value = raw;
|
||||
arguments.Add(new KeyValuePair<string, object>(key, value));
|
||||
}
|
||||
return arguments;
|
||||
}
|
||||
|
||||
try { addEffect(effectName, arguments); }
|
||||
private void ResolveEffectCallback(MemoryMappedViewAccessor view, Action<string, IReadOnlyList<KeyValuePair<string, object>>> addEffect)
|
||||
{
|
||||
int tagLen = Math.Clamp(view.ReadInt32(NativeProtocol.OffCallbackTagLen), 0, NativeProtocol.CallbackTagMax);
|
||||
view.ReadArray(NativeProtocol.CallbackTagOffset, _callbackTag, 0, tagLen);
|
||||
|
||||
var segments = Encoding.UTF8.GetString(_callbackTag, 0, tagLen).Split('\0');
|
||||
if (segments.Length == 0)
|
||||
return;
|
||||
|
||||
try { addEffect(segments[0], ParseNamedArguments(segments)); }
|
||||
catch { }
|
||||
view.Write(NativeProtocol.OffCallbackFound, 1);
|
||||
}
|
||||
|
||||
@@ -181,9 +181,17 @@ namespace LuaScript
|
||||
script.AttachDebugger(_debugger);
|
||||
_globalRegistrar = new AviUtlGlobalRegistrar(CurrentTimeRatio);
|
||||
_globalRegistrar.RegisterLuaMembers(script.Globals);
|
||||
RegisterFastPrimitives(script);
|
||||
_script = script;
|
||||
}
|
||||
|
||||
private void RegisterFastPrimitives(Script script)
|
||||
{
|
||||
script.Globals.Set("__fast_fill", DynValue.NewCallback((_, args) => FillCore(args, true)));
|
||||
script.Globals.Set("__fast_convolve", DynValue.NewCallback((_, args) => ConvolveCore(args, true)));
|
||||
script.Globals.Set("__fast_resize", DynValue.NewCallback((_, args) => ResizeCore(args, true)));
|
||||
}
|
||||
|
||||
private void EnsureScriptIntegrity()
|
||||
{
|
||||
if (_script is null) return;
|
||||
@@ -548,6 +556,18 @@ namespace LuaScript
|
||||
args[1].String,
|
||||
args.Count > 2 ? args[2].CastToNumber() ?? _activeContext.Time : _activeContext.Time);
|
||||
break;
|
||||
case "scene" when args.Count > 1 && args[1].Type == DataType.String:
|
||||
LoadScene(
|
||||
args[1].String,
|
||||
args.Count > 2 ? args[2].CastToNumber() ?? _activeContext.Time : _activeContext.Time);
|
||||
break;
|
||||
case "brush" when args.Count > 1 && args[1].Type == DataType.String:
|
||||
LoadBrush(
|
||||
args[1].String,
|
||||
args.Count > 2 ? args[2].CastToNumber() ?? 0d : 0d,
|
||||
args.Count > 3 ? args[3].CastToNumber() ?? 0d : 0d,
|
||||
s_noNamedArguments);
|
||||
break;
|
||||
}
|
||||
return DynValue.Void;
|
||||
}
|
||||
@@ -771,6 +791,47 @@ namespace LuaScript
|
||||
return value.Type == DataType.Number ? value : DynValue.NewNumber(0d);
|
||||
}
|
||||
|
||||
private static readonly double[] s_noAudioData = [];
|
||||
|
||||
[LuaFunction("getaudio")]
|
||||
private DynValue GetAudio(CallbackArguments args)
|
||||
{
|
||||
_activeCancellation.ThrowIfCancellationRequested();
|
||||
if (_activeContext is null || _script is null || args.Count < 2 || args[1].Type != DataType.String)
|
||||
return DynValue.NewTuple(DynValue.NewNumber(0d), DynValue.NewNumber(0d));
|
||||
|
||||
string file = args[1].String;
|
||||
string type = args.Count > 2 && args[2].Type == DataType.String ? args[2].String : "pcm";
|
||||
int size = args.Count > 3 ? (int)(args[3].CastToNumber() ?? 0d) : 0;
|
||||
|
||||
int count = 0;
|
||||
int rate = 0;
|
||||
double[] data = s_noAudioData;
|
||||
var loader = _activeContext.AudioLoader;
|
||||
if (loader is not null)
|
||||
(count, rate, data) = loader(file, type, size);
|
||||
if (count > data.Length)
|
||||
count = data.Length;
|
||||
|
||||
var bufArg = args[0];
|
||||
Table? table = bufArg.Type == DataType.Table ? bufArg.Table : null;
|
||||
bool created = false;
|
||||
if (table is null && bufArg.IsNil())
|
||||
{
|
||||
table = new Table(_script);
|
||||
created = true;
|
||||
}
|
||||
if (table is not null)
|
||||
{
|
||||
for (int i = 0; i < count; i++)
|
||||
table.Set(i + 1, DynValue.NewNumber(data[i]));
|
||||
}
|
||||
|
||||
return created
|
||||
? DynValue.NewTuple(DynValue.NewNumber(count), DynValue.NewNumber(rate), DynValue.NewTable(table!))
|
||||
: DynValue.NewTuple(DynValue.NewNumber(count), DynValue.NewNumber(rate));
|
||||
}
|
||||
|
||||
[LuaFunction("setoption")]
|
||||
private DynValue SetOption(CallbackArguments args)
|
||||
{
|
||||
@@ -828,9 +889,7 @@ namespace LuaScript
|
||||
return DynValue.NewNumber(0d);
|
||||
|
||||
var anchorName = args[0].String;
|
||||
int count = AnchorSupport.ClampCount((int)(args[1].CastToNumber() ?? 0d));
|
||||
if (string.Equals(anchorName, AnchorSupport.TrackGroup, StringComparison.Ordinal))
|
||||
return DynValue.NewNumber(0d);
|
||||
int count = AnchorSupport.NormalizeCount(anchorName, (int)(args[1].CastToNumber() ?? 0d));
|
||||
|
||||
var connection = AnchorConnection.None;
|
||||
bool is3D = false;
|
||||
@@ -864,9 +923,19 @@ namespace LuaScript
|
||||
if (_activeContext is null || args.Count == 0 || args[0].Type != DataType.String)
|
||||
return DynValue.Void;
|
||||
|
||||
string name = args[0].String;
|
||||
_activeContext.AddEffect(new AviUtlEffectRequest(args[0].String, CollectNamedArguments(args, 1)));
|
||||
return DynValue.Void;
|
||||
}
|
||||
|
||||
private static readonly KeyValuePair<string, object>[] s_noNamedArguments = [];
|
||||
|
||||
private static IReadOnlyList<KeyValuePair<string, object>> CollectNamedArguments(CallbackArguments args, int start)
|
||||
{
|
||||
if (start + 1 >= args.Count)
|
||||
return s_noNamedArguments;
|
||||
|
||||
var arguments = new List<KeyValuePair<string, object>>();
|
||||
for (int i = 1; i + 1 < args.Count; i += 2)
|
||||
for (int i = start; i + 1 < args.Count; i += 2)
|
||||
{
|
||||
if (args[i].Type != DataType.String)
|
||||
continue;
|
||||
@@ -880,8 +949,27 @@ namespace LuaScript
|
||||
};
|
||||
arguments.Add(new KeyValuePair<string, object>(args[i].String, boxed));
|
||||
}
|
||||
return arguments;
|
||||
}
|
||||
|
||||
_activeContext.AddEffect(new AviUtlEffectRequest(name, arguments));
|
||||
[LuaFunction("brush")]
|
||||
private DynValue Brush(CallbackArguments args)
|
||||
{
|
||||
_activeCancellation.ThrowIfCancellationRequested();
|
||||
if (_activeContext is null || args.Count == 0 || args[0].Type != DataType.String)
|
||||
return DynValue.Void;
|
||||
|
||||
int start = 1;
|
||||
double width = 0d;
|
||||
double height = 0d;
|
||||
if (args.Count > 2 && args[1].Type == DataType.Number && args[2].Type == DataType.Number)
|
||||
{
|
||||
width = args[1].Number;
|
||||
height = args[2].Number;
|
||||
start = 3;
|
||||
}
|
||||
|
||||
LoadBrush(args[0].String, width, height, CollectNamedArguments(args, start));
|
||||
return DynValue.Void;
|
||||
}
|
||||
|
||||
@@ -907,6 +995,150 @@ namespace LuaScript
|
||||
};
|
||||
}
|
||||
|
||||
private double[] _regionScratch = [];
|
||||
private double[] _kernelScratch = [];
|
||||
|
||||
private static readonly DynValue[] s_byteNumbers = CreateByteNumbers();
|
||||
|
||||
private static DynValue[] CreateByteNumbers()
|
||||
{
|
||||
var values = new DynValue[256];
|
||||
for (int i = 0; i < values.Length; i++)
|
||||
values[i] = DynValue.NewNumber(i).AsReadOnly();
|
||||
return values;
|
||||
}
|
||||
|
||||
private static DynValue ChannelValue(double value)
|
||||
{
|
||||
int b = (int)value;
|
||||
return b == value && (uint)b < 256u ? s_byteNumbers[b] : DynValue.NewNumber(value);
|
||||
}
|
||||
|
||||
[LuaFunction("fill")]
|
||||
private DynValue Fill(CallbackArguments args) => FillCore(args, false);
|
||||
|
||||
private DynValue FillCore(CallbackArguments args, bool force)
|
||||
{
|
||||
_activeCancellation.ThrowIfCancellationRequested();
|
||||
if (_activeContext is null)
|
||||
return DynValue.Void;
|
||||
|
||||
var ctx = _activeContext;
|
||||
double r = args.Count > 0 ? args[0].CastToNumber() ?? 0d : 0d;
|
||||
double g = args.Count > 1 ? args[1].CastToNumber() ?? 0d : 0d;
|
||||
double b = args.Count > 2 ? args[2].CastToNumber() ?? 0d : 0d;
|
||||
double a = args.Count > 3 ? args[3].CastToNumber() ?? 255d : 255d;
|
||||
int x = args.Count > 4 ? (int)(args[4].CastToNumber() ?? 0d) : 0;
|
||||
int y = args.Count > 5 ? (int)(args[5].CastToNumber() ?? 0d) : 0;
|
||||
int w = args.Count > 6 ? (int)(args[6].CastToNumber() ?? 0d) : ctx.ImageWidth;
|
||||
int h = args.Count > 7 ? (int)(args[7].CastToNumber() ?? 0d) : ctx.ImageHeight;
|
||||
|
||||
ctx.FillBuffer(r, g, b, a, x, y, w, h, force);
|
||||
return DynValue.Void;
|
||||
}
|
||||
|
||||
[LuaFunction("getpixelregion")]
|
||||
private DynValue GetPixelRegion(CallbackArguments args)
|
||||
{
|
||||
_activeCancellation.ThrowIfCancellationRequested();
|
||||
if (_activeContext is null || _script is null || args.Count < 4)
|
||||
return DynValue.Nil;
|
||||
|
||||
int x = (int)(args[0].CastToNumber() ?? 0d);
|
||||
int y = (int)(args[1].CastToNumber() ?? 0d);
|
||||
int w = (int)(args[2].CastToNumber() ?? 0d);
|
||||
int h = (int)(args[3].CastToNumber() ?? 0d);
|
||||
var table = new Table(_script);
|
||||
if (w <= 0 || h <= 0)
|
||||
return DynValue.NewTable(table);
|
||||
|
||||
int count = w * h * 4;
|
||||
if (_regionScratch.Length < count)
|
||||
_regionScratch = new double[count];
|
||||
_activeContext.ReadRegion(x, y, w, h, _regionScratch);
|
||||
for (int i = 0; i < count; i++)
|
||||
table.Set(i + 1, ChannelValue(_regionScratch[i]));
|
||||
return DynValue.NewTable(table);
|
||||
}
|
||||
|
||||
[LuaFunction("putpixelregion")]
|
||||
private DynValue PutPixelRegion(CallbackArguments args)
|
||||
{
|
||||
_activeCancellation.ThrowIfCancellationRequested();
|
||||
if (_activeContext is null || args.Count < 5 || args[4].Type != DataType.Table)
|
||||
return DynValue.Void;
|
||||
|
||||
int x = (int)(args[0].CastToNumber() ?? 0d);
|
||||
int y = (int)(args[1].CastToNumber() ?? 0d);
|
||||
int w = (int)(args[2].CastToNumber() ?? 0d);
|
||||
int h = (int)(args[3].CastToNumber() ?? 0d);
|
||||
if (w <= 0 || h <= 0)
|
||||
return DynValue.Void;
|
||||
|
||||
int count = w * h * 4;
|
||||
if (_regionScratch.Length < count)
|
||||
_regionScratch = new double[count];
|
||||
var table = args[4].Table;
|
||||
for (int i = 0; i < count; i++)
|
||||
_regionScratch[i] = table.Get(i + 1).CastToNumber() ?? 0d;
|
||||
_activeContext.WriteRegion(x, y, w, h, _regionScratch);
|
||||
return DynValue.Void;
|
||||
}
|
||||
|
||||
[LuaFunction("convolve")]
|
||||
private DynValue Convolve(CallbackArguments args) => ConvolveCore(args, false);
|
||||
|
||||
private DynValue ConvolveCore(CallbackArguments args, bool force)
|
||||
{
|
||||
_activeCancellation.ThrowIfCancellationRequested();
|
||||
if (_activeContext is null || args.Count < 2 || args[0].Type != DataType.Table)
|
||||
return DynValue.Void;
|
||||
|
||||
int size = (int)(args[1].CastToNumber() ?? 0d);
|
||||
if (size < 1 || (size & 1) == 0)
|
||||
return DynValue.Void;
|
||||
|
||||
int taps = size * size;
|
||||
var kernel = args[0].Table;
|
||||
if (_kernelScratch.Length < taps)
|
||||
_kernelScratch = new double[taps];
|
||||
double sum = 0d;
|
||||
for (int i = 0; i < taps; i++)
|
||||
{
|
||||
double v = kernel.Get(i + 1).CastToNumber() ?? 0d;
|
||||
_kernelScratch[i] = v;
|
||||
sum += v;
|
||||
}
|
||||
|
||||
double divisor = args.Count > 2 ? args[2].CastToNumber() ?? sum : sum;
|
||||
if (divisor == 0d)
|
||||
divisor = 1d;
|
||||
double offset = args.Count > 3 ? args[3].CastToNumber() ?? 0d : 0d;
|
||||
|
||||
_activeContext.Convolve(_kernelScratch, size, divisor, offset, force);
|
||||
return DynValue.Void;
|
||||
}
|
||||
|
||||
[LuaFunction("resize")]
|
||||
private DynValue Resize(CallbackArguments args) => ResizeCore(args, false);
|
||||
|
||||
private DynValue ResizeCore(CallbackArguments args, bool force)
|
||||
{
|
||||
_activeCancellation.ThrowIfCancellationRequested();
|
||||
if (_activeContext is null || args.Count < 2)
|
||||
return DynValue.Void;
|
||||
|
||||
int w = (int)(args[0].CastToNumber() ?? 0d);
|
||||
int h = (int)(args[1].CastToNumber() ?? 0d);
|
||||
if (w <= 0 || h <= 0)
|
||||
return DynValue.Void;
|
||||
|
||||
bool linear = !(args.Count > 2 && args[2].Type == DataType.String && args[2].String == "nearest");
|
||||
_activeContext.Resize(w, h, linear, force);
|
||||
RefreshObjDimensions();
|
||||
return DynValue.Void;
|
||||
}
|
||||
|
||||
private double CurrentAntialias() =>
|
||||
_options.TryGetValue("antialias", out var value) && value.Type == DataType.Number
|
||||
? value.Number
|
||||
@@ -949,6 +1181,34 @@ namespace LuaScript
|
||||
RefreshObjDimensions();
|
||||
}
|
||||
|
||||
private void LoadScene(string name, double time)
|
||||
{
|
||||
var ctx = _activeContext!;
|
||||
var loader = ctx.SceneImageLoader;
|
||||
if (loader is null)
|
||||
return;
|
||||
var (buffer, w, h) = loader(name, time);
|
||||
if (w <= 0 || h <= 0)
|
||||
return;
|
||||
ctx.ReplaceBuffer(buffer, w, h);
|
||||
RefreshObjDimensions();
|
||||
}
|
||||
|
||||
private void LoadBrush(string name, double width, double height, IReadOnlyList<KeyValuePair<string, object>> arguments)
|
||||
{
|
||||
var ctx = _activeContext!;
|
||||
var loader = ctx.BrushImageLoader;
|
||||
if (loader is null)
|
||||
return;
|
||||
double w = width > 0d ? width : ctx.ImageWidth;
|
||||
double h = height > 0d ? height : ctx.ImageHeight;
|
||||
var (buffer, bw, bh) = loader(name, w, h, arguments);
|
||||
if (bw <= 0 || bh <= 0)
|
||||
return;
|
||||
ctx.ReplaceBuffer(buffer, bw, bh);
|
||||
RefreshObjDimensions();
|
||||
}
|
||||
|
||||
private void LoadMovie(string path, double time)
|
||||
{
|
||||
_mediaLoader ??= _mediaLoaderFactory();
|
||||
@@ -962,14 +1222,14 @@ namespace LuaScript
|
||||
int w = _activeContext!.ImageWidth;
|
||||
int h = _activeContext.ImageHeight;
|
||||
var obj = _objScope.Table;
|
||||
obj["w"] = w;
|
||||
obj["h"] = h;
|
||||
obj["hw"] = w / 2d;
|
||||
obj["hh"] = h / 2d;
|
||||
obj["cx"] = w / 2d;
|
||||
obj["cy"] = h / 2d;
|
||||
obj["cz"] = 0d;
|
||||
obj["diagonal"] = Math.Sqrt((double)w * w + (double)h * h);
|
||||
obj.Set("w", DynValue.NewNumber(w));
|
||||
obj.Set("h", DynValue.NewNumber(h));
|
||||
obj.Set("hw", DynValue.NewNumber(w / 2d));
|
||||
obj.Set("hh", DynValue.NewNumber(h / 2d));
|
||||
obj.Set("cx", DynValue.NewNumber(w / 2d));
|
||||
obj.Set("cy", DynValue.NewNumber(h / 2d));
|
||||
obj.Set("cz", DynValue.NewNumber(0d));
|
||||
obj.Set("diagonal", DynValue.NewNumber(Math.Sqrt((double)w * w + (double)h * h)));
|
||||
}
|
||||
|
||||
private static DynValue BuildObjectTable(Script script, SceneObjectInfo info)
|
||||
@@ -991,6 +1251,11 @@ namespace LuaScript
|
||||
["rzr"] = info.Rz * Math.PI / 180d,
|
||||
["alpha"] = info.Alpha,
|
||||
["layer"] = info.Layer,
|
||||
["volume"] = info.Volume,
|
||||
["length"] = info.Length,
|
||||
["character"] = info.Character ?? string.Empty,
|
||||
["text"] = info.Text ?? string.Empty,
|
||||
["kind"] = info.Kind ?? string.Empty,
|
||||
};
|
||||
return DynValue.NewTable(table);
|
||||
}
|
||||
|
||||
@@ -43,7 +43,7 @@ namespace LuaScript.Engine
|
||||
public const int CallbackTagOffset = ErrorOffset + ErrorMax;
|
||||
public const int CallbackTagMax = 8192;
|
||||
public const int CallbackResultOffset = CallbackTagOffset + CallbackTagMax;
|
||||
public const int CallbackResultCount = 8;
|
||||
public const int CallbackResultCount = 10;
|
||||
|
||||
public const int StringParamsOffset = CallbackResultOffset + CallbackResultCount * 8;
|
||||
public const int MinStringParamsCapacity = 64 * 1024;
|
||||
@@ -63,6 +63,15 @@ namespace LuaScript.Engine
|
||||
public const int CbKindSceneSet = 12;
|
||||
public const int CbKindPixelShaderStage = 13;
|
||||
public const int CbKindPixelShaderRun = 14;
|
||||
public const int CbKindLoadScene = 15;
|
||||
public const int CbKindLoadBrush = 16;
|
||||
public const int CbKindBrush = 17;
|
||||
public const int CbKindGetAudio = 18;
|
||||
public const int CbKindPixelProcess = 19;
|
||||
|
||||
public const int PixelProcessFill = 0;
|
||||
public const int PixelProcessConvolve = 1;
|
||||
public const int PixelProcessResize = 2;
|
||||
|
||||
public const int DrawRingCapacity = 4096;
|
||||
public const int DrawEntryDoubles = 24;
|
||||
@@ -77,6 +86,8 @@ namespace LuaScript.Engine
|
||||
public const int CbRz = 5;
|
||||
public const int CbAlpha = 6;
|
||||
public const int CbLayer = 7;
|
||||
public const int CbVolume = 8;
|
||||
public const int CbLength = 9;
|
||||
|
||||
public static long DrawRingOffset(int stringCapacity) => StringParamsOffset + stringCapacity;
|
||||
|
||||
|
||||
@@ -0,0 +1,166 @@
|
||||
using System;
|
||||
|
||||
namespace LuaScript
|
||||
{
|
||||
internal static unsafe class PixelBufferSoftwareProcessor
|
||||
{
|
||||
public static void Fill(byte[] target, int width, int height, double r, double g, double b, double a, int x, int y, int fillWidth, int fillHeight)
|
||||
{
|
||||
double aK = Math.Clamp(a, 0d, 255d) / 255d;
|
||||
byte pb = (byte)Math.Clamp(b * aK, 0d, 255d);
|
||||
byte pg = (byte)Math.Clamp(g * aK, 0d, 255d);
|
||||
byte pr = (byte)Math.Clamp(r * aK, 0d, 255d);
|
||||
byte pa = (byte)Math.Clamp(a, 0d, 255d);
|
||||
int x1 = x + fillWidth;
|
||||
int y1 = y + fillHeight;
|
||||
|
||||
fixed (byte* buf = target)
|
||||
{
|
||||
for (int py = y; py < y1; py++)
|
||||
{
|
||||
byte* p = buf + (py * width + x) * 4;
|
||||
for (int px = x; px < x1; px++)
|
||||
{
|
||||
p[0] = pb;
|
||||
p[1] = pg;
|
||||
p[2] = pr;
|
||||
p[3] = pa;
|
||||
p += 4;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
public static void Convolve(byte[] target, int width, int height, double[] kernel, int size, double divisor, double offset, ref double[]? sourceScratch)
|
||||
{
|
||||
int count = width * height * 4;
|
||||
if (sourceScratch is null || sourceScratch.Length < count)
|
||||
sourceScratch = new double[count];
|
||||
var src = sourceScratch;
|
||||
|
||||
fixed (byte* buf = target)
|
||||
{
|
||||
for (int pi = 0; pi < width * height; pi++)
|
||||
{
|
||||
byte* p = buf + pi * 4;
|
||||
int di = pi * 4;
|
||||
double a = p[3];
|
||||
src[di + 3] = a;
|
||||
if (a <= 0d)
|
||||
{
|
||||
src[di] = 0d;
|
||||
src[di + 1] = 0d;
|
||||
src[di + 2] = 0d;
|
||||
}
|
||||
else
|
||||
{
|
||||
double s = 255d / a;
|
||||
src[di] = Math.Clamp(p[2] * s, 0d, 255d);
|
||||
src[di + 1] = Math.Clamp(p[1] * s, 0d, 255d);
|
||||
src[di + 2] = Math.Clamp(p[0] * s, 0d, 255d);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
int half = size / 2;
|
||||
|
||||
fixed (byte* buf = target)
|
||||
{
|
||||
for (int y = 0; y < height; y++)
|
||||
{
|
||||
for (int x = 0; x < width; x++)
|
||||
{
|
||||
double sr = 0d, sg = 0d, sb = 0d, sa = 0d;
|
||||
for (int ky = 0; ky < size; ky++)
|
||||
{
|
||||
int sy = Math.Clamp(y + ky - half, 0, height - 1);
|
||||
for (int kx = 0; kx < size; kx++)
|
||||
{
|
||||
int sx = Math.Clamp(x + kx - half, 0, width - 1);
|
||||
double kv = kernel[ky * size + kx];
|
||||
int si = (sy * width + sx) * 4;
|
||||
sr += src[si] * kv;
|
||||
sg += src[si + 1] * kv;
|
||||
sb += src[si + 2] * kv;
|
||||
sa += src[si + 3] * kv;
|
||||
}
|
||||
}
|
||||
double rr = Math.Clamp(sr / divisor + offset, 0d, 255d);
|
||||
double gg = Math.Clamp(sg / divisor + offset, 0d, 255d);
|
||||
double bb = Math.Clamp(sb / divisor + offset, 0d, 255d);
|
||||
double aa = Math.Clamp(sa / divisor + offset, 0d, 255d);
|
||||
double aK = aa / 255d;
|
||||
byte* p = buf + (y * width + x) * 4;
|
||||
p[0] = (byte)Math.Clamp(bb * aK, 0d, 255d);
|
||||
p[1] = (byte)Math.Clamp(gg * aK, 0d, 255d);
|
||||
p[2] = (byte)Math.Clamp(rr * aK, 0d, 255d);
|
||||
p[3] = (byte)aa;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
public static byte[] Resize(byte[] source, int sourceWidth, int sourceHeight, int targetWidth, int targetHeight, bool linear, ref byte[]? sourceScratch, ref byte[]? targetScratch)
|
||||
{
|
||||
int srcCount = sourceWidth * sourceHeight * 4;
|
||||
if (sourceScratch is null || sourceScratch.Length < srcCount)
|
||||
sourceScratch = new byte[srcCount];
|
||||
Buffer.BlockCopy(source, 0, sourceScratch, 0, srcCount);
|
||||
|
||||
int dstCount = targetWidth * targetHeight * 4;
|
||||
if (targetScratch is null || targetScratch.Length != dstCount)
|
||||
targetScratch = new byte[dstCount];
|
||||
var src = sourceScratch;
|
||||
var dst = targetScratch;
|
||||
|
||||
fixed (byte* s = src)
|
||||
fixed (byte* d = dst)
|
||||
{
|
||||
for (int y = 0; y < targetHeight; y++)
|
||||
{
|
||||
for (int x = 0; x < targetWidth; x++)
|
||||
{
|
||||
byte* o = d + (y * targetWidth + x) * 4;
|
||||
if (!linear)
|
||||
{
|
||||
int sx = Math.Clamp((int)((x + 0.5) * sourceWidth / targetWidth), 0, sourceWidth - 1);
|
||||
int sy = Math.Clamp((int)((y + 0.5) * sourceHeight / targetHeight), 0, sourceHeight - 1);
|
||||
byte* p = s + (sy * sourceWidth + sx) * 4;
|
||||
o[0] = p[0];
|
||||
o[1] = p[1];
|
||||
o[2] = p[2];
|
||||
o[3] = p[3];
|
||||
}
|
||||
else
|
||||
{
|
||||
double u = (x + 0.5) * sourceWidth / targetWidth - 0.5;
|
||||
double v = (y + 0.5) * sourceHeight / targetHeight - 0.5;
|
||||
int x0 = (int)Math.Floor(u);
|
||||
int y0 = (int)Math.Floor(v);
|
||||
double tx = u - x0;
|
||||
double ty = v - y0;
|
||||
for (int c = 0; c < 4; c++)
|
||||
{
|
||||
double acc = 0d;
|
||||
for (int j = 0; j < 2; j++)
|
||||
{
|
||||
int sy = Math.Clamp(y0 + j, 0, sourceHeight - 1);
|
||||
double wy = j == 0 ? 1d - ty : ty;
|
||||
for (int i = 0; i < 2; i++)
|
||||
{
|
||||
int sx = Math.Clamp(x0 + i, 0, sourceWidth - 1);
|
||||
double wx = i == 0 ? 1d - tx : tx;
|
||||
acc += s[(sy * sourceWidth + sx) * 4 + c] * wy * wx;
|
||||
}
|
||||
}
|
||||
o[c] = (byte)Math.Clamp(acc, 0d, 255d);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return dst;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,15 +1,16 @@
|
||||
<Project Sdk="Microsoft.NET.Sdk">
|
||||
<Project Sdk="Microsoft.NET.Sdk">
|
||||
|
||||
<PropertyGroup>
|
||||
<TargetFramework>net10.0-windows10.0.19041.0</TargetFramework>
|
||||
<ImplicitUsings>enable</ImplicitUsings>
|
||||
<Version>1.15.0</Version>
|
||||
<Version>1.20.2</Version>
|
||||
<Platforms>AnyCPU;x64</Platforms>
|
||||
<Nullable>enable</Nullable>
|
||||
<AllowUnsafeBlocks>true</AllowUnsafeBlocks>
|
||||
</PropertyGroup>
|
||||
|
||||
<ItemGroup>
|
||||
<InternalsVisibleTo Include="LuaScript.Gpu" />
|
||||
<InternalsVisibleTo Include="LuaScript" />
|
||||
<InternalsVisibleTo Include="LuaScript.Tests" />
|
||||
</ItemGroup>
|
||||
|
||||
@@ -9,5 +9,10 @@ namespace LuaScript
|
||||
double Zoom,
|
||||
double Rz,
|
||||
double Alpha,
|
||||
int Layer);
|
||||
int Layer,
|
||||
int Length,
|
||||
double Volume,
|
||||
string Character,
|
||||
string Text,
|
||||
string Kind);
|
||||
}
|
||||
@@ -13,6 +13,35 @@ namespace LuaScript.Tests
|
||||
Assert.Equal(AnchorSupport.MaxAnchors, AnchorSupport.ClampCount(100));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void NormalizeCount_DefaultsTrackToSinglePoint()
|
||||
{
|
||||
Assert.Equal(1, AnchorSupport.NormalizeCount(AnchorSupport.TrackGroup, 0));
|
||||
Assert.Equal(1, AnchorSupport.NormalizeCount(AnchorSupport.TrackGroup, -3));
|
||||
Assert.Equal(4, AnchorSupport.NormalizeCount(AnchorSupport.TrackGroup, 4));
|
||||
Assert.Equal(0, AnchorSupport.NormalizeCount("pos", 0));
|
||||
Assert.Equal(AnchorSupport.MaxAnchors, AnchorSupport.NormalizeCount("pos", 100));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void SetPosition_ReplacesOrAppendsAbsolute()
|
||||
{
|
||||
var source = ImmutableList.Create(new LuaAnchorPoint { Group = "pos", Index = 2, X = 10, Y = 20, Z = 30 });
|
||||
|
||||
var replaced = AnchorSupport.SetPosition(source, "pos", 2, 1, 2, 3);
|
||||
Assert.Single(replaced);
|
||||
Assert.Equal(1, replaced[0].X);
|
||||
Assert.Equal(2, replaced[0].Y);
|
||||
Assert.Equal(3, replaced[0].Z);
|
||||
|
||||
var appended = AnchorSupport.SetPosition(source, "pos", 5, 7, 8, 9);
|
||||
Assert.Equal(2, appended.Count);
|
||||
Assert.Equal(5, appended[1].Index);
|
||||
Assert.Equal(7, appended[1].X);
|
||||
Assert.Equal(8, appended[1].Y);
|
||||
Assert.Equal(9, appended[1].Z);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void ApplyOption_SetsConnectionAndDimension()
|
||||
{
|
||||
|
||||
@@ -0,0 +1,132 @@
|
||||
using LuaScript.Compat;
|
||||
|
||||
namespace LuaScript.Tests
|
||||
{
|
||||
public sealed class AviUtlAudioConverterTests
|
||||
{
|
||||
private static float[] Interleave(double[] left, double[] right)
|
||||
{
|
||||
var data = new float[left.Length * 2];
|
||||
for (int i = 0; i < left.Length; i++)
|
||||
{
|
||||
data[i * 2] = (float)left[i];
|
||||
data[i * 2 + 1] = (float)right[i];
|
||||
}
|
||||
return data;
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void RequiredFrames_MatchesTypeWindows()
|
||||
{
|
||||
Assert.Equal(16, AviUtlAudioConverter.RequiredFrames("pcm", 16));
|
||||
Assert.Equal(AviUtlAudioConverter.MaxSamples, AviUtlAudioConverter.RequiredFrames("pcm", 0));
|
||||
Assert.Equal(AviUtlAudioConverter.MaxSamples, AviUtlAudioConverter.RequiredFrames("pcm", 99999));
|
||||
Assert.Equal(AviUtlAudioConverter.SpectrumWindow, AviUtlAudioConverter.RequiredFrames("spectrum", 32));
|
||||
Assert.Equal(AviUtlAudioConverter.FourierWindow, AviUtlAudioConverter.RequiredFrames("fourier", 0));
|
||||
Assert.Equal(AviUtlAudioConverter.FourierWindow, AviUtlAudioConverter.RequiredFrames("fourier.l", 0));
|
||||
Assert.Equal(0, AviUtlAudioConverter.RequiredFrames("unknown", 8));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Pcm_ScalesMonoMixTo16BitRange()
|
||||
{
|
||||
var converter = new AviUtlAudioConverter();
|
||||
var data = Interleave([0.5d, -1d, 0d], [0.5d, -1d, 1d]);
|
||||
var dest = new double[AviUtlAudioConverter.MaxSamples];
|
||||
|
||||
int count = converter.Convert("pcm", data, 3, 3, dest);
|
||||
|
||||
Assert.Equal(3, count);
|
||||
Assert.Equal(16384d, dest[0]);
|
||||
Assert.Equal(-32768d, dest[1]);
|
||||
Assert.Equal(16384d, dest[2]);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Pcm_SelectsChannelBySuffix()
|
||||
{
|
||||
var converter = new AviUtlAudioConverter();
|
||||
var data = Interleave([0.25d, 0.25d], [-0.5d, -0.5d]);
|
||||
var dest = new double[AviUtlAudioConverter.MaxSamples];
|
||||
|
||||
converter.Convert("pcm.l", data, 2, 2, dest);
|
||||
Assert.Equal(8192d, dest[0]);
|
||||
|
||||
converter.Convert("pcm.r", data, 2, 2, dest);
|
||||
Assert.Equal(-16384d, dest[0]);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Pcm_ReturnsFewerWhenSourceIsShort()
|
||||
{
|
||||
var converter = new AviUtlAudioConverter();
|
||||
var data = Interleave([0.1d, 0.2d], [0.1d, 0.2d]);
|
||||
var dest = new double[AviUtlAudioConverter.MaxSamples];
|
||||
|
||||
int count = converter.Convert("pcm", data, 2, 100, dest);
|
||||
|
||||
Assert.Equal(2, count);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Spectrum_PeaksInBandContainingSineFrequency()
|
||||
{
|
||||
var converter = new AviUtlAudioConverter();
|
||||
const int frames = AviUtlAudioConverter.SpectrumWindow;
|
||||
const int cycle = 64;
|
||||
var mono = new double[frames];
|
||||
for (int i = 0; i < frames; i++)
|
||||
mono[i] = Math.Sin(2d * Math.PI * i * cycle / frames);
|
||||
var data = Interleave(mono, mono);
|
||||
var dest = new double[AviUtlAudioConverter.MaxSamples];
|
||||
|
||||
int count = converter.Convert("spectrum", data, frames, 32, dest);
|
||||
|
||||
Assert.Equal(32, count);
|
||||
int expectedBand = cycle * 32 / AviUtlAudioConverter.SpectrumBins;
|
||||
int peakBand = 0;
|
||||
for (int i = 1; i < count; i++)
|
||||
{
|
||||
if (dest[i] > dest[peakBand])
|
||||
peakBand = i;
|
||||
}
|
||||
Assert.Equal(expectedBand, peakBand);
|
||||
Assert.True(dest[peakBand] > 1000d);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Fourier_ReturnsNormalizedMagnitudes()
|
||||
{
|
||||
var converter = new AviUtlAudioConverter();
|
||||
const int frames = AviUtlAudioConverter.FourierWindow;
|
||||
const int cycle = 8;
|
||||
var mono = new double[frames];
|
||||
for (int i = 0; i < frames; i++)
|
||||
mono[i] = Math.Sin(2d * Math.PI * i * cycle / frames);
|
||||
var data = Interleave(mono, mono);
|
||||
var dest = new double[AviUtlAudioConverter.MaxSamples];
|
||||
|
||||
int count = converter.Convert("fourier", data, frames, 0, dest);
|
||||
|
||||
Assert.Equal(AviUtlAudioConverter.MaxSamples, count);
|
||||
int peak = 0;
|
||||
for (int i = 1; i < count; i++)
|
||||
{
|
||||
if (dest[i] > dest[peak])
|
||||
peak = i;
|
||||
}
|
||||
Assert.Equal(cycle - 1, peak);
|
||||
Assert.Equal(1d, dest[peak], 3);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void UnknownTypeOrEmptySource_YieldsZero()
|
||||
{
|
||||
var converter = new AviUtlAudioConverter();
|
||||
var dest = new double[AviUtlAudioConverter.MaxSamples];
|
||||
|
||||
Assert.Equal(0, converter.Convert("waveform", new float[8], 4, 4, dest));
|
||||
Assert.Equal(0, converter.Convert("pcm", [], 0, 4, dest));
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -137,35 +137,35 @@ namespace LuaScript.Tests
|
||||
[Fact]
|
||||
public void ChangedLines_EmptyWhenNoRewrite()
|
||||
{
|
||||
var (_, _, changed) = AviUtlScript.TransformWithMap("obj.x = 1\nobj.y = 2");
|
||||
var (_, _, changed, _) = AviUtlScript.TransformWithMap("obj.x = 1\nobj.y = 2");
|
||||
Assert.Empty(changed);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void ChangedLines_ReportRewrittenLineInRunnableSpace()
|
||||
{
|
||||
var (_, _, changed) = AviUtlScript.TransformWithMap("obj.x = 1\nobj.y = obj.x != 0\nobj.z = 3");
|
||||
var (_, _, changed, _) = AviUtlScript.TransformWithMap("obj.x = 1\nobj.y = obj.x != 0\nobj.z = 3");
|
||||
Assert.Equal(new[] { 2 }, changed);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void ChangedLines_AreSortedAndCoverEveryRewrittenLine()
|
||||
{
|
||||
var (_, _, changed) = AviUtlScript.TransformWithMap("a = x != 0\nb = y\nc = z ?? 5\nw++");
|
||||
var (_, _, changed, _) = AviUtlScript.TransformWithMap("a = x != 0\nb = y\nc = z ?? 5\nw++");
|
||||
Assert.Equal(new[] { 1, 3, 4 }, changed);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void ChangedLines_DeduplicateMultipleRewritesOnOneLine()
|
||||
{
|
||||
var (_, _, changed) = AviUtlScript.TransformWithMap("a = x != 0 and y != 1 and z != 2");
|
||||
var (_, _, changed, _) = AviUtlScript.TransformWithMap("a = x != 0 and y != 1 and z != 2");
|
||||
Assert.Equal(new[] { 1 }, changed);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void ChangedLines_TrackRunnableLineAfterHoistedPrelude()
|
||||
{
|
||||
var (_, _, changed) = AviUtlScript.TransformWithMap("--dialog:V,local v=3;\nresult = v != 0");
|
||||
var (_, _, changed, _) = AviUtlScript.TransformWithMap("--dialog:V,local v=3;\nresult = v != 0");
|
||||
Assert.NotEmpty(changed);
|
||||
for (int i = 1; i < changed.Length; i++)
|
||||
Assert.True(changed[i] > changed[i - 1]);
|
||||
|
||||
@@ -23,6 +23,12 @@ namespace LuaScript.Tests
|
||||
[InlineData("for y=0,obj.h-1 do for x=0,obj.w-1 do local r,g,b,a=obj.getpixel(x,y) obj.setpixel(x,y,r%64,math.abs(g-128),math.sqrt(b*255),a) end end")]
|
||||
[InlineData("local x=99 local k=3 for y=0,obj.h-1 do for x=0,obj.w-1 do local r,g,b,a=obj.getpixel(x,y) obj.setpixel(x,y,x/obj.w*255+k,g,b,a) end end")]
|
||||
[InlineData("for y=0,obj.h-1 do for x=0,obj.w-1 do local r,g,b,a=obj.getpixel(x,y) obj.setpixel(x,y,math.fmod(r,64),math.fmod(g,7)*36,math.fmod(b-128,60)+128,a) end end")]
|
||||
[InlineData("for y=0,obj.h-1 do for x=0,obj.w-1 do local r,g,b,a=obj.getpixel(x,y) if r>128 then r=255 end obj.setpixel(x,y,r,g,b,a) end end")]
|
||||
[InlineData("for y=0,obj.h-1 do for x=0,obj.w-1 do local r,g,b,a=obj.getpixel(x,y) local v=(r+g+b)/3 local o=0 if v>128 then o=255 else o=32 end obj.setpixel(x,y,o,o,o,a) end end")]
|
||||
[InlineData("for y=0,obj.h-1 do for x=0,obj.w-1 do local r,g,b,a=obj.getpixel(x,y) local v=(r+g+b)/3 local o=0 if v>170 then o=255 elseif v>85 then o=128 elseif v>40 then o=64 end obj.setpixel(x,y,o,g,b,a) end end")]
|
||||
[InlineData("for y=0,obj.h-1 do for x=0,obj.w-1 do local r,g,b,a=obj.getpixel(x,y) if r>g then r=g end if b<64 and g>32 then b=g elseif b>192 then b=192 end obj.setpixel(x,y,r,g,b,a) end end")]
|
||||
[InlineData("for y=0,obj.h-1 do for x=0,obj.w-1 do local r,g,b,a=obj.getpixel(x,y) local v=0 if r>128 then local r=g*0.5 v=r+1 if v>100 then v=100 end else v=r end obj.setpixel(x,y,v,g,b,a) end end")]
|
||||
[InlineData("local w=obj.w local h=obj.h for y=0,h-1 do for x=0,w-1 do local r,g,b,a=obj.getpixel(x,y) obj.setpixel(x,y,x/w*255,y/h*255,b,a) end end")]
|
||||
public void CpuKernelMatchesMoonSharp(string script)
|
||||
{
|
||||
var fields = new Dictionary<string, double> { ["w"] = Width, ["h"] = Height };
|
||||
@@ -46,6 +52,9 @@ namespace LuaScript.Tests
|
||||
[InlineData("local pd=obj.getpixeldata() for y=0,pd.height-1 do for x=0,pd.width-1 do local i=(y*pd.width+x)*4 local r=pd:get(i+1) local g=pd:get(i+2) local b=pd:get(i+3) pd:set(i+1,b) pd:set(i+2,g) pd:set(i+3,r) end end")]
|
||||
[InlineData("local pd=obj.getpixeldata() for y=0,obj.h-1 do for x=0,obj.w-1 do local i=(y*obj.w+x)*4 local r=pd:get(i+1) local a=pd:get(i+4) pd:set(i+1,r*a/255) pd:set(i+2,pd:get(i+2)*obj.track0/100) pd:set(i+3,math.min(255,pd:get(i+3)+50)) end end")]
|
||||
[InlineData("local pd=obj.getpixeldata() for y=0,pd.height-1 do for x=0,pd.width-1 do local i=(y*pd.width+x)*4 local r=pd:get(i+1) local g=pd:get(i+2) local b=pd:get(i+3) pd:set(i+1,r*3) pd:set(i+2,g-300) pd:set(i+3,b*2-255) end end")]
|
||||
[InlineData("local pd=obj.getpixeldata() for y=0,pd.height-1 do for x=0,pd.width-1 do local i=(y*pd.width+x)*4 local r=pd:get(i+1) local g=pd:get(i+2) local b=pd:get(i+3) pd:set(i+1,255-r) pd:set(i+2,255-g) pd:set(i+3,255-b) end end obj.putpixeldata(pd)")]
|
||||
[InlineData("local data=obj.getpixeldata() local w=data.width local h=data.height for y=0,h-1 do for x=0,w-1 do local i=(y*w+x)*4 local r=data:get(i+1) local g=data:get(i+2) local b=data:get(i+3) data:set(i+1,g) data:set(i+2,b) data:set(i+3,r) end end obj.putpixeldata(data)")]
|
||||
[InlineData("local pd=obj.getpixeldata() for y=0,pd.height-1 do for x=0,pd.width-1 do local i=(y*pd.width+x)*4 local r=pd:get(i+1) local g=pd:get(i+2) local b=pd:get(i+3) local v=(r+g+b)/3 local o=0 if v>128 then o=255 end pd:set(i+1,o) pd:set(i+2,o) pd:set(i+3,o) end end")]
|
||||
public void GetPixelDataKernelMatchesMoonSharp(string script)
|
||||
{
|
||||
var fields = new Dictionary<string, double> { ["w"] = Width, ["h"] = Height, ["track0"] = 73d };
|
||||
@@ -60,6 +69,9 @@ namespace LuaScript.Tests
|
||||
[InlineData("local pd=obj.getpixeldata() for y=0,pd.height-1 do for x=0,pd.width-1 do local i=(y*pd.width+x)*4 local i=i+4 pd:set(i+1,0) pd:set(i+2,0) pd:set(i+3,0) end end")]
|
||||
[InlineData("local pd=obj.getpixeldata() for y=0,pd.height-1 do for pd=0,pd.width-1 do local i=(y*2+pd)*4 pd:set(i+1,0) pd:set(i+2,0) pd:set(i+3,0) end end")]
|
||||
[InlineData("local pd=obj.getpixeldata() for y=0,pd.height-1 do for x=0,pd.width-1 do local i=(y*pd.width+x)*4 local pd=0 pd:set(i+1,0) end end")]
|
||||
[InlineData("local pd=obj.getpixeldata() for y=0,pd.height-1 do for x=0,pd.width-1 do local i=(y*pd.width+x)*4 local r=pd:get(i+1) if r>128 then pd:set(i+1,255) end pd:set(i+2,0) pd:set(i+3,0) end end")]
|
||||
[InlineData("local pd=obj.getpixeldata() for y=0,pd.height-1 do for x=0,pd.width-1 do local i=(y*pd.width+x)*4 pd:set(i+1,0) pd:set(i+2,0) pd:set(i+3,0) end end obj.putpixeldata(other)")]
|
||||
[InlineData("local pd=obj.getpixeldata() for y=0,pd.height-1 do for x=0,pd.width-1 do local i=(y*pd.width+x)*4 pd:set(i+1,0) pd:set(i+2,0) pd:set(i+3,0) end end obj.putpixeldata(pd) obj.putpixeldata(pd)")]
|
||||
public void GetPixelDataNonKernelScriptsAreRejected(string script)
|
||||
{
|
||||
Assert.Null(KernelExtractor.TryExtract(script));
|
||||
@@ -92,8 +104,12 @@ namespace LuaScript.Tests
|
||||
[InlineData("for y=0,obj.h-1 do for x=0,obj.w-1 do local r,g,b,a=obj.getpixel(x,y) total=total+r obj.setpixel(x,y,r,g,b,a) end end")]
|
||||
[InlineData("for y=0,obj.h-1 do for x=0,obj.w-1 do local r,g,b,a=obj.getpixel(x+1,y) obj.setpixel(x,y,r,g,b,a) end end")]
|
||||
[InlineData("for i=0,10 do end")]
|
||||
[InlineData("for y=0,obj.h-1 do for x=0,obj.w-1 do local r,g,b,a=obj.getpixel(x,y) if r>128 then r=255 end obj.setpixel(x,y,r,g,b,a) end end")]
|
||||
[InlineData("for y=0,obj.h-1 do for x=0,obj.w-1 do local r,g,b,a=obj.getpixel(x,y) obj.setpixel(x,y,obj.rand(0,255),g,b,a) end end")]
|
||||
[InlineData("for y=0,obj.h-1 do for x=0,obj.w-1 do local r,g,b,a=obj.getpixel(x,y) if r>128 then obj.setpixel(x,y,255,g,b,a) end end end")]
|
||||
[InlineData("for y=0,obj.h-1 do for x=0,obj.w-1 do local r,g,b,a=obj.getpixel(x,y) if r then r=255 end obj.setpixel(x,y,r,g,b,a) end end")]
|
||||
[InlineData("for y=0,obj.h-1 do for x=0,obj.w-1 do local r,g,b,a=obj.getpixel(x,y) if r>128 then local y=0 r=y end obj.setpixel(x,y,r,g,b,a) end end")]
|
||||
[InlineData("for y=0,obj.h-1 do for x=0,obj.w-1 do local r,g,b,a=obj.getpixel(x,y) obj.setpixel(x,y,r,g,b,a) end end obj.putpixeldata(pd)")]
|
||||
[InlineData("local w=5 for y=0,obj.h-1 do for x=0,w-1 do local r,g,b,a=obj.getpixel(x,y) obj.setpixel(x,y,r,g,b,a) end end")]
|
||||
public void NonKernelScriptsAreRejected(string script)
|
||||
{
|
||||
Assert.Null(KernelExtractor.TryExtract(script));
|
||||
@@ -178,6 +194,8 @@ namespace LuaScript.Tests
|
||||
return DynValue.NewTable(pd);
|
||||
});
|
||||
|
||||
obj["putpixeldata"] = DynValue.NewCallback((_, _) => DynValue.Void);
|
||||
|
||||
engine.Globals["obj"] = obj;
|
||||
engine.DoString(script);
|
||||
}
|
||||
|
||||
@@ -62,6 +62,18 @@ namespace LuaScript.Tests
|
||||
Assert.Contains($"uniforms[{index / 4}].{"xyzw"[index % 4]}", hlsl);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void ConditionalStatementEmitsTernary()
|
||||
{
|
||||
const string script =
|
||||
"for y=0,obj.h-1 do for x=0,obj.w-1 do local r,g,b,a=obj.getpixel(x,y) " +
|
||||
"local v=(r+g+b)/3 local o=0 if v>170 then o=255 elseif v>85 then o=128 end " +
|
||||
"obj.setpixel(x,y,o,o,o,a) end end";
|
||||
string hlsl = HlslKernelEmitter.Emit(Extract(script));
|
||||
Assert.Contains(" ? (", hlsl);
|
||||
Assert.Contains(" > ", hlsl);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void EmissionIsDeterministic()
|
||||
{
|
||||
|
||||
@@ -24,6 +24,7 @@ namespace LuaScript.Tests
|
||||
[InlineData("for y=0,obj.h-1 do for x=0,obj.w-1 do local r,g,b,a=obj.getpixel(x,y) obj.setpixel(x,y,((r>128 and g<64) or (not (b>200))) and 255 or 0,g,b,a) end end")]
|
||||
[InlineData("for y=0,obj.h-1 do for x=0,obj.w-1 do local r,g,b,a=obj.getpixel(x,y) obj.setpixel(x,y,(r>=200) and 255 or 0,(g<=50) and 255 or 0,(b==0) and 255 or ((b~=0) and 100 or 0),a) end end")]
|
||||
[InlineData("local pd=obj.getpixeldata() for y=0,pd.height-1 do for x=0,pd.width-1 do local i=(y*pd.width+x)*4 local r=pd:get(i+1) local g=pd:get(i+2) local b=pd:get(i+3) pd:set(i+1,r*3) pd:set(i+2,g-300) pd:set(i+3,b*2-255) end end")]
|
||||
[InlineData("for y=0,obj.h-1 do for x=0,obj.w-1 do local r,g,b,a=obj.getpixel(x,y) local v=(r+g+b)/3 local o=0 if v>170 then o=255 elseif v>85 then o=128 else o=r end obj.setpixel(x,y,o,o,o,a) end end")]
|
||||
public void SimdBlockMatchesScalarRow(string script)
|
||||
{
|
||||
var program = KernelExtractor.TryExtract(script);
|
||||
|
||||
@@ -11,6 +11,8 @@ namespace LuaScript.Tests
|
||||
"repeat", "return", "then", "true", "until", "while"
|
||||
];
|
||||
|
||||
private static readonly string[] SyntaxKeywords = ["fast"];
|
||||
|
||||
private static readonly string[] Globals =
|
||||
[
|
||||
"time", "frame", "totalframe", "framerate",
|
||||
@@ -48,8 +50,9 @@ namespace LuaScript.Tests
|
||||
"obj.getpixeldata", "obj.putpixeldata", "obj.rand", "obj.load",
|
||||
"obj.setfont", "obj.draw", "obj.drawpoly", "obj.copybuffer",
|
||||
"obj.pixelshader",
|
||||
"obj.getvalue", "obj.setoption", "obj.getoption", "obj.pixeloption",
|
||||
"obj.setanchor", "obj.effect", "obj.getinfo"
|
||||
"obj.getvalue", "obj.getaudio", "obj.setoption", "obj.getoption", "obj.pixeloption",
|
||||
"obj.setanchor", "obj.effect", "obj.brush", "obj.getinfo",
|
||||
"obj.fill", "obj.getpixelregion", "obj.putpixelregion", "obj.convolve", "obj.resize"
|
||||
]),
|
||||
("math", [
|
||||
"math.abs", "math.ceil", "math.cos", "math.exp", "math.floor",
|
||||
@@ -103,6 +106,7 @@ namespace LuaScript.Tests
|
||||
|
||||
private static string[] ExpectedStaticCandidates() =>
|
||||
Keywords
|
||||
.Concat(SyntaxKeywords)
|
||||
.Concat(Globals)
|
||||
.Concat(Namespaces.SelectMany(n => n.Members))
|
||||
.Distinct()
|
||||
|
||||
@@ -0,0 +1,274 @@
|
||||
using LuaScript;
|
||||
|
||||
namespace LuaScript.Tests
|
||||
{
|
||||
public sealed class LuaScriptEngineBufferOpsTests
|
||||
{
|
||||
private sealed class StubMediaLoader : IMediaSourceLoader
|
||||
{
|
||||
public byte[] RenderText(string text, string fontFamily, double fontSize, bool bold, bool italic, int colorRgb, out int width, out int height)
|
||||
{
|
||||
width = 1;
|
||||
height = 1;
|
||||
return new byte[4];
|
||||
}
|
||||
|
||||
public byte[] DecodeImage(string path, out int width, out int height)
|
||||
{
|
||||
width = 1;
|
||||
height = 1;
|
||||
return new byte[4];
|
||||
}
|
||||
|
||||
public byte[] DecodeMovie(string path, double time, out int width, out int height)
|
||||
{
|
||||
width = 1;
|
||||
height = 1;
|
||||
return new byte[4];
|
||||
}
|
||||
|
||||
public void Dispose() { }
|
||||
}
|
||||
|
||||
private static LuaScriptEngine CreateEngine() => new(static () => new StubMediaLoader());
|
||||
|
||||
private static AviUtlScriptContext NewContext(byte[] buffer, int width, int height)
|
||||
{
|
||||
var ctx = new AviUtlScriptContext { Framerate = 30 };
|
||||
ctx.SetResolvedBuffer(buffer, width, height);
|
||||
return ctx;
|
||||
}
|
||||
|
||||
private static byte[] Bgra(params (byte B, byte G, byte R, byte A)[] pixels)
|
||||
{
|
||||
var buffer = new byte[pixels.Length * 4];
|
||||
for (int i = 0; i < pixels.Length; i++)
|
||||
{
|
||||
buffer[i * 4 + 0] = pixels[i].B;
|
||||
buffer[i * 4 + 1] = pixels[i].G;
|
||||
buffer[i * 4 + 2] = pixels[i].R;
|
||||
buffer[i * 4 + 3] = pixels[i].A;
|
||||
}
|
||||
return buffer;
|
||||
}
|
||||
|
||||
private sealed class RecordingProcessor : IPixelBufferProcessor
|
||||
{
|
||||
public int FillCalls;
|
||||
public int ConvolveCalls;
|
||||
public int ResizeCalls;
|
||||
public bool LastFillForce;
|
||||
public bool LastConvolveForce;
|
||||
public bool LastResizeForce;
|
||||
|
||||
public bool TryFill(byte[] target, int width, int height, double r, double g, double b, double a, int x, int y, int fillWidth, int fillHeight, bool force = false)
|
||||
{
|
||||
FillCalls++;
|
||||
LastFillForce = force;
|
||||
return false;
|
||||
}
|
||||
|
||||
public bool TryConvolve(byte[] target, int width, int height, double[] kernel, int size, double divisor, double offset, bool force = false)
|
||||
{
|
||||
ConvolveCalls++;
|
||||
LastConvolveForce = force;
|
||||
return false;
|
||||
}
|
||||
|
||||
public bool TryResize(byte[] source, int sourceWidth, int sourceHeight, int targetWidth, int targetHeight, bool linear, out byte[]? target, bool force = false)
|
||||
{
|
||||
ResizeCalls++;
|
||||
LastResizeForce = force;
|
||||
target = null;
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void BufferOps_ConsultPixelProcessorAndFallBackToCpu()
|
||||
{
|
||||
using var engine = CreateEngine();
|
||||
var ctx = NewContext(new byte[2 * 2 * 4], 2, 2);
|
||||
var processor = new RecordingProcessor();
|
||||
ctx.PixelProcessor = processor;
|
||||
|
||||
engine.Execute("obj.fill(200, 100, 50, 255) obj.convolve({1,1,1,1,1,1,1,1,1}, 3) obj.resize(4, 4)", ctx);
|
||||
|
||||
Assert.Equal(1, processor.FillCalls);
|
||||
Assert.Equal(1, processor.ConvolveCalls);
|
||||
Assert.Equal(1, processor.ResizeCalls);
|
||||
Assert.Equal(4, ctx.ImageWidth);
|
||||
Assert.Equal(4, ctx.ImageHeight);
|
||||
Assert.False(processor.LastFillForce);
|
||||
Assert.False(processor.LastConvolveForce);
|
||||
Assert.False(processor.LastResizeForce);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void FastMarker_ForcesPixelProcessorRegardlessOfSize()
|
||||
{
|
||||
using var engine = CreateEngine();
|
||||
var ctx = NewContext(new byte[2 * 2 * 4], 2, 2);
|
||||
var processor = new RecordingProcessor();
|
||||
ctx.PixelProcessor = processor;
|
||||
|
||||
engine.Execute("__fast_fill(200, 100, 50, 255) __fast_convolve({1,1,1,1,1,1,1,1,1}, 3) __fast_resize(4, 4)", ctx);
|
||||
|
||||
Assert.Equal(1, processor.FillCalls);
|
||||
Assert.Equal(1, processor.ConvolveCalls);
|
||||
Assert.Equal(1, processor.ResizeCalls);
|
||||
Assert.True(processor.LastFillForce);
|
||||
Assert.True(processor.LastConvolveForce);
|
||||
Assert.True(processor.LastResizeForce);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Fill_WholeBuffer_WritesPremultipliedColor()
|
||||
{
|
||||
using var engine = CreateEngine();
|
||||
var ctx = NewContext(new byte[2 * 2 * 4], 2, 2);
|
||||
|
||||
engine.Execute("obj.fill(200, 100, 50, 255)", ctx);
|
||||
|
||||
var buffer = ctx.GetPixelBuffer()!;
|
||||
for (int i = 0; i < 4; i++)
|
||||
{
|
||||
Assert.Equal(50, buffer[i * 4 + 0]);
|
||||
Assert.Equal(100, buffer[i * 4 + 1]);
|
||||
Assert.Equal(200, buffer[i * 4 + 2]);
|
||||
Assert.Equal(255, buffer[i * 4 + 3]);
|
||||
}
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Fill_Rectangle_TouchesOnlyRequestedPixels()
|
||||
{
|
||||
using var engine = CreateEngine();
|
||||
var ctx = NewContext(new byte[3 * 1 * 4], 3, 1);
|
||||
|
||||
engine.Execute("obj.fill(255, 255, 255, 255, 1, 0, 1, 1)", ctx);
|
||||
|
||||
var buffer = ctx.GetPixelBuffer()!;
|
||||
Assert.Equal(new byte[] { 0, 0, 0, 0 }, buffer.AsSpan(0, 4).ToArray());
|
||||
Assert.Equal(new byte[] { 255, 255, 255, 255 }, buffer.AsSpan(4, 4).ToArray());
|
||||
Assert.Equal(new byte[] { 0, 0, 0, 0 }, buffer.AsSpan(8, 4).ToArray());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void GetPixelRegion_ReturnsStraightRgba()
|
||||
{
|
||||
using var engine = CreateEngine();
|
||||
var ctx = NewContext(Bgra((50, 100, 200, 255)), 1, 1);
|
||||
|
||||
engine.Execute("local t = obj.getpixelregion(0, 0, 1, 1) obj.x = t[1] obj.y = t[2] obj.z = t[3] obj.alpha = t[4]", ctx);
|
||||
|
||||
Assert.Equal(200d, ctx.X);
|
||||
Assert.Equal(100d, ctx.Y);
|
||||
Assert.Equal(50d, ctx.Z);
|
||||
Assert.Equal(255d, ctx.Alpha);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void GetPixelRegion_OutOfBounds_YieldsTransparent()
|
||||
{
|
||||
using var engine = CreateEngine();
|
||||
var ctx = NewContext(Bgra((10, 20, 30, 255)), 1, 1);
|
||||
|
||||
engine.Execute("local t = obj.getpixelregion(1, 0, 1, 1) obj.x = t[1] + t[2] + t[3] + t[4]", ctx);
|
||||
|
||||
Assert.Equal(0d, ctx.X);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void PutPixelRegion_WritesPremultipliedColor()
|
||||
{
|
||||
using var engine = CreateEngine();
|
||||
var ctx = NewContext(new byte[2 * 1 * 4], 2, 1);
|
||||
|
||||
engine.Execute("obj.putpixelregion(0, 0, 2, 1, {200, 100, 50, 255, 10, 20, 30, 255})", ctx);
|
||||
|
||||
var buffer = ctx.GetPixelBuffer()!;
|
||||
Assert.Equal(new byte[] { 50, 100, 200, 255 }, buffer.AsSpan(0, 4).ToArray());
|
||||
Assert.Equal(new byte[] { 30, 20, 10, 255 }, buffer.AsSpan(4, 4).ToArray());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void RegionRoundTrip_PreservesOpaquePixels()
|
||||
{
|
||||
using var engine = CreateEngine();
|
||||
var original = Bgra((10, 20, 30, 255), (40, 50, 60, 255), (70, 80, 90, 255), (100, 110, 120, 255));
|
||||
var ctx = NewContext((byte[])original.Clone(), 2, 2);
|
||||
|
||||
engine.Execute(
|
||||
"local t = obj.getpixelregion(0, 0, obj.w, obj.h) obj.fill(0, 0, 0, 0) obj.putpixelregion(0, 0, obj.w, obj.h, t)",
|
||||
ctx);
|
||||
|
||||
Assert.Equal(original, ctx.GetPixelBuffer());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Convolve_Identity_LeavesOpaqueBufferUnchanged()
|
||||
{
|
||||
using var engine = CreateEngine();
|
||||
var original = Bgra((10, 20, 30, 255), (40, 50, 60, 255), (70, 80, 90, 255), (100, 110, 120, 255));
|
||||
var ctx = NewContext((byte[])original.Clone(), 2, 2);
|
||||
|
||||
engine.Execute("obj.convolve({0, 0, 0, 0, 1, 0, 0, 0, 0}, 3)", ctx);
|
||||
|
||||
Assert.Equal(original, ctx.GetPixelBuffer());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Convolve_BoxBlur_AveragesHorizontalStep()
|
||||
{
|
||||
using var engine = CreateEngine();
|
||||
var ctx = NewContext(Bgra((0, 0, 0, 255), (255, 255, 255, 255)), 2, 1);
|
||||
|
||||
engine.Execute("obj.convolve({1, 1, 1, 1, 1, 1, 1, 1, 1}, 3)", ctx);
|
||||
|
||||
var buffer = ctx.GetPixelBuffer()!;
|
||||
Assert.Equal(85, buffer[2]);
|
||||
Assert.Equal(85, buffer[1]);
|
||||
Assert.Equal(85, buffer[0]);
|
||||
Assert.Equal(170, buffer[6]);
|
||||
Assert.Equal(255, buffer[3]);
|
||||
Assert.Equal(255, buffer[7]);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Resize_Nearest_ReplicatesBlocks()
|
||||
{
|
||||
using var engine = CreateEngine();
|
||||
var ctx = NewContext(Bgra((11, 12, 13, 255), (21, 22, 23, 255), (31, 32, 33, 255), (41, 42, 43, 255)), 2, 2);
|
||||
|
||||
engine.Execute("obj.resize(4, 4, 'nearest')", ctx);
|
||||
|
||||
Assert.Equal(4, ctx.ImageWidth);
|
||||
Assert.Equal(4, ctx.ImageHeight);
|
||||
Assert.True(ctx.BufferReplaced);
|
||||
|
||||
var buffer = ctx.GetPixelBuffer()!;
|
||||
byte SampleR(int x, int y) => buffer[(y * 4 + x) * 4 + 2];
|
||||
Assert.Equal(13, SampleR(0, 0));
|
||||
Assert.Equal(13, SampleR(1, 1));
|
||||
Assert.Equal(23, SampleR(2, 0));
|
||||
Assert.Equal(33, SampleR(0, 2));
|
||||
Assert.Equal(43, SampleR(3, 3));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Resize_UpdatesObjDimensions()
|
||||
{
|
||||
using var engine = CreateEngine();
|
||||
var ctx = NewContext(new byte[4 * 4 * 4], 4, 4);
|
||||
|
||||
engine.Execute("obj.resize(8, 2) obj.x = obj.w obj.y = obj.h obj.z = obj.diagonal", ctx);
|
||||
|
||||
Assert.Equal(8, ctx.ImageWidth);
|
||||
Assert.Equal(2, ctx.ImageHeight);
|
||||
Assert.Equal(8d, ctx.X);
|
||||
Assert.Equal(2d, ctx.Y);
|
||||
Assert.Equal(Math.Sqrt(8d * 8d + 2d * 2d), ctx.Z);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,164 @@
|
||||
using LuaScript;
|
||||
|
||||
namespace LuaScript.Tests
|
||||
{
|
||||
public sealed class LuaScriptEngineGetAudioTests
|
||||
{
|
||||
private sealed class StubMediaLoader : IMediaSourceLoader
|
||||
{
|
||||
public byte[] RenderText(string text, string fontFamily, double fontSize, bool bold, bool italic, int colorRgb, out int width, out int height)
|
||||
{
|
||||
width = 1;
|
||||
height = 1;
|
||||
return new byte[4];
|
||||
}
|
||||
|
||||
public byte[] DecodeImage(string path, out int width, out int height)
|
||||
{
|
||||
width = 1;
|
||||
height = 1;
|
||||
return new byte[4];
|
||||
}
|
||||
|
||||
public byte[] DecodeMovie(string path, double time, out int width, out int height)
|
||||
{
|
||||
width = 1;
|
||||
height = 1;
|
||||
return new byte[4];
|
||||
}
|
||||
|
||||
public void Dispose() { }
|
||||
}
|
||||
|
||||
private static LuaScriptEngine CreateEngine() => new(static () => new StubMediaLoader());
|
||||
|
||||
private static AviUtlScriptContext NewContext()
|
||||
{
|
||||
return new AviUtlScriptContext
|
||||
{
|
||||
ImageWidth = 2,
|
||||
ImageHeight = 2,
|
||||
Framerate = 30,
|
||||
};
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void GetAudio_FillsBufferTableFromLoader()
|
||||
{
|
||||
using var engine = CreateEngine();
|
||||
var ctx = NewContext();
|
||||
|
||||
string? capturedFile = null;
|
||||
string? capturedType = null;
|
||||
int capturedSize = -1;
|
||||
ctx.AudioLoader = (file, type, size) =>
|
||||
{
|
||||
capturedFile = file;
|
||||
capturedType = type;
|
||||
capturedSize = size;
|
||||
return (3, 44100, [1.5d, -2.5d, 3d]);
|
||||
};
|
||||
|
||||
engine.Execute(
|
||||
"local buf = {}\n" +
|
||||
"local n, rate = obj.getaudio(buf, 'audiobuffer', 'pcm', 3)\n" +
|
||||
"obj.x = n\n" +
|
||||
"obj.y = rate\n" +
|
||||
"obj.z = buf[1]\n" +
|
||||
"obj.ox = buf[2]\n" +
|
||||
"obj.oy = buf[3]",
|
||||
ctx);
|
||||
|
||||
Assert.Equal("audiobuffer", capturedFile);
|
||||
Assert.Equal("pcm", capturedType);
|
||||
Assert.Equal(3, capturedSize);
|
||||
Assert.Equal(3d, ctx.X);
|
||||
Assert.Equal(44100d, ctx.Y);
|
||||
Assert.Equal(1.5d, ctx.Z);
|
||||
Assert.Equal(-2.5d, ctx.Ox);
|
||||
Assert.Equal(3d, ctx.Oy);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void GetAudio_NilBuffer_ReturnsTableAsThirdValue()
|
||||
{
|
||||
using var engine = CreateEngine();
|
||||
var ctx = NewContext();
|
||||
|
||||
ctx.AudioLoader = (_, type, _) => (2, 48000, [7d, 8d]);
|
||||
|
||||
engine.Execute(
|
||||
"local n, rate, buf = obj.getaudio(nil, 'C:/test.wav', 'spectrum.r', 2)\n" +
|
||||
"obj.x = n\n" +
|
||||
"obj.y = rate\n" +
|
||||
"obj.z = buf[1]\n" +
|
||||
"obj.ox = buf[2]",
|
||||
ctx);
|
||||
|
||||
Assert.Equal(2d, ctx.X);
|
||||
Assert.Equal(48000d, ctx.Y);
|
||||
Assert.Equal(7d, ctx.Z);
|
||||
Assert.Equal(8d, ctx.Ox);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void GetAudio_DefaultsTypeToPcm()
|
||||
{
|
||||
using var engine = CreateEngine();
|
||||
var ctx = NewContext();
|
||||
|
||||
string? capturedType = null;
|
||||
int capturedSize = -1;
|
||||
ctx.AudioLoader = (_, type, size) =>
|
||||
{
|
||||
capturedType = type;
|
||||
capturedSize = size;
|
||||
return (0, 48000, []);
|
||||
};
|
||||
|
||||
engine.Execute("obj.x = obj.getaudio({}, 'audiobuffer')", ctx);
|
||||
|
||||
Assert.Equal("pcm", capturedType);
|
||||
Assert.Equal(0, capturedSize);
|
||||
Assert.Equal(0d, ctx.X);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void GetAudio_WithoutLoader_ReturnsZero()
|
||||
{
|
||||
using var engine = CreateEngine();
|
||||
var ctx = NewContext();
|
||||
|
||||
engine.Execute(
|
||||
"local n, rate, buf = obj.getaudio(nil, 'audiobuffer', 'pcm', 8)\n" +
|
||||
"obj.x = n\n" +
|
||||
"obj.y = rate\n" +
|
||||
"obj.z = #buf\n" +
|
||||
"obj.ox = obj.getaudio({}, 7)",
|
||||
ctx);
|
||||
|
||||
Assert.Equal(0d, ctx.X);
|
||||
Assert.Equal(0d, ctx.Y);
|
||||
Assert.Equal(0d, ctx.Z);
|
||||
Assert.Equal(0d, ctx.Ox);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void GetAudio_ClampsCountToDataLength()
|
||||
{
|
||||
using var engine = CreateEngine();
|
||||
var ctx = NewContext();
|
||||
|
||||
ctx.AudioLoader = (_, _, _) => (10, 48000, [5d]);
|
||||
|
||||
engine.Execute(
|
||||
"local n, _, buf = obj.getaudio(nil, 'audiobuffer', 'pcm', 10)\n" +
|
||||
"obj.x = n\n" +
|
||||
"obj.y = #buf",
|
||||
ctx);
|
||||
|
||||
Assert.Equal(1d, ctx.X);
|
||||
Assert.Equal(1d, ctx.Y);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -130,6 +130,45 @@ namespace LuaScript.Tests
|
||||
Assert.Equal(1d, ctx.Oy);
|
||||
}
|
||||
|
||||
private sealed class StubResolver : ISceneObjectResolver
|
||||
{
|
||||
private readonly SceneObjectInfo _info;
|
||||
public StubResolver(SceneObjectInfo info) => _info = info;
|
||||
public bool TryResolve(string tag, int timelineFrame, out SceneObjectInfo info)
|
||||
{
|
||||
if (tag == _info.Tag)
|
||||
{
|
||||
info = _info;
|
||||
return true;
|
||||
}
|
||||
info = default;
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void GetObjectExposesItemMetadata()
|
||||
{
|
||||
using var engine = CreateEngine();
|
||||
var ctx = NewContext();
|
||||
var info = new SceneObjectInfo("a", true, 12d, 34d, 56d, 2d, 90d, 200d, 7, 120, 75d, "reimu", "hello", "VoiceItem");
|
||||
ctx.ResolverProvider = () => new StubResolver(info);
|
||||
|
||||
engine.Execute(
|
||||
"local o = obj.getobject('a')\n" +
|
||||
"obj.x = o.volume\n" +
|
||||
"obj.y = o.length\n" +
|
||||
"obj.z = (o.character == 'reimu') and 1 or 0\n" +
|
||||
"obj.ox = (o.text == 'hello') and 1 or 0\n" +
|
||||
"obj.oy = (o.kind == 'VoiceItem') and 1 or 0", ctx);
|
||||
|
||||
Assert.Equal(75d, ctx.X);
|
||||
Assert.Equal(120d, ctx.Y);
|
||||
Assert.Equal(1d, ctx.Z);
|
||||
Assert.Equal(1d, ctx.Ox);
|
||||
Assert.Equal(1d, ctx.Oy);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void ObjectWritesFlowBackToContext()
|
||||
{
|
||||
|
||||
@@ -0,0 +1,249 @@
|
||||
using LuaScript;
|
||||
|
||||
namespace LuaScript.Tests
|
||||
{
|
||||
public sealed class LuaScriptEngineSceneBrushLoadTests
|
||||
{
|
||||
private sealed class StubMediaLoader : IMediaSourceLoader
|
||||
{
|
||||
public byte[] RenderText(string text, string fontFamily, double fontSize, bool bold, bool italic, int colorRgb, out int width, out int height)
|
||||
{
|
||||
width = 1;
|
||||
height = 1;
|
||||
return new byte[4];
|
||||
}
|
||||
|
||||
public byte[] DecodeImage(string path, out int width, out int height)
|
||||
{
|
||||
width = 1;
|
||||
height = 1;
|
||||
return new byte[4];
|
||||
}
|
||||
|
||||
public byte[] DecodeMovie(string path, double time, out int width, out int height)
|
||||
{
|
||||
width = 1;
|
||||
height = 1;
|
||||
return new byte[4];
|
||||
}
|
||||
|
||||
public void Dispose() { }
|
||||
}
|
||||
|
||||
private static LuaScriptEngine CreateEngine() => new(static () => new StubMediaLoader());
|
||||
|
||||
private static AviUtlScriptContext NewContext()
|
||||
{
|
||||
return new AviUtlScriptContext
|
||||
{
|
||||
ImageWidth = 6,
|
||||
ImageHeight = 4,
|
||||
Time = 1.5,
|
||||
Framerate = 30,
|
||||
};
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void LoadScene_ReplacesBufferAndUpdatesObjDimensions()
|
||||
{
|
||||
using var engine = CreateEngine();
|
||||
var ctx = NewContext();
|
||||
|
||||
string? capturedName = null;
|
||||
double capturedTime = -1;
|
||||
var rendered = new byte[2 * 3 * 4];
|
||||
ctx.SceneImageLoader = (name, time) =>
|
||||
{
|
||||
capturedName = name;
|
||||
capturedTime = time;
|
||||
return (rendered, 2, 3);
|
||||
};
|
||||
|
||||
engine.Execute("obj.load('scene', 'サブ', 4.25); obj.x = obj.w; obj.y = obj.h", ctx);
|
||||
|
||||
Assert.Equal("サブ", capturedName);
|
||||
Assert.Equal(4.25d, capturedTime);
|
||||
Assert.True(ctx.BufferReplaced);
|
||||
Assert.Same(rendered, ctx.GetPixelBuffer());
|
||||
Assert.Equal(2, ctx.ImageWidth);
|
||||
Assert.Equal(3, ctx.ImageHeight);
|
||||
Assert.Equal(2d, ctx.X);
|
||||
Assert.Equal(3d, ctx.Y);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void LoadScene_DefaultsTimeToObjTime()
|
||||
{
|
||||
using var engine = CreateEngine();
|
||||
var ctx = NewContext();
|
||||
|
||||
double capturedTime = -1;
|
||||
ctx.SceneImageLoader = (_, time) =>
|
||||
{
|
||||
capturedTime = time;
|
||||
return ([], 0, 0);
|
||||
};
|
||||
|
||||
engine.Execute("obj.load('scene', 'サブ')", ctx);
|
||||
|
||||
Assert.Equal(1.5d, capturedTime);
|
||||
Assert.False(ctx.BufferReplaced);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void LoadScene_WithoutLoader_IsNoOp()
|
||||
{
|
||||
using var engine = CreateEngine();
|
||||
var ctx = NewContext();
|
||||
|
||||
engine.Execute("obj.load('scene', 'サブ'); obj.x = obj.w", ctx);
|
||||
|
||||
Assert.False(ctx.BufferReplaced);
|
||||
Assert.Equal(6d, ctx.X);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void LoadBrush_ReplacesBufferWithRequestedSize()
|
||||
{
|
||||
using var engine = CreateEngine();
|
||||
var ctx = NewContext();
|
||||
|
||||
string? capturedName = null;
|
||||
double capturedW = -1, capturedH = -1;
|
||||
var rendered = new byte[8 * 5 * 4];
|
||||
ctx.BrushImageLoader = (name, w, h, _) =>
|
||||
{
|
||||
capturedName = name;
|
||||
capturedW = w;
|
||||
capturedH = h;
|
||||
return (rendered, 8, 5);
|
||||
};
|
||||
|
||||
engine.Execute("obj.load('brush', '縞模様', 8, 5); obj.x = obj.w; obj.y = obj.h", ctx);
|
||||
|
||||
Assert.Equal("縞模様", capturedName);
|
||||
Assert.Equal(8d, capturedW);
|
||||
Assert.Equal(5d, capturedH);
|
||||
Assert.True(ctx.BufferReplaced);
|
||||
Assert.Same(rendered, ctx.GetPixelBuffer());
|
||||
Assert.Equal(8d, ctx.X);
|
||||
Assert.Equal(5d, ctx.Y);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void LoadBrush_DefaultsSizeToObjectDimensions()
|
||||
{
|
||||
using var engine = CreateEngine();
|
||||
var ctx = NewContext();
|
||||
|
||||
double capturedW = -1, capturedH = -1;
|
||||
ctx.BrushImageLoader = (_, w, h, _) =>
|
||||
{
|
||||
capturedW = w;
|
||||
capturedH = h;
|
||||
return ([], 0, 0);
|
||||
};
|
||||
|
||||
engine.Execute("obj.load('brush', '市松模様')", ctx);
|
||||
|
||||
Assert.Equal(6d, capturedW);
|
||||
Assert.Equal(4d, capturedH);
|
||||
Assert.False(ctx.BufferReplaced);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Brush_PassesParameterPairs()
|
||||
{
|
||||
using var engine = CreateEngine();
|
||||
var ctx = NewContext();
|
||||
|
||||
string? capturedName = null;
|
||||
double capturedW = -1, capturedH = -1;
|
||||
List<KeyValuePair<string, object>>? captured = null;
|
||||
var rendered = new byte[6 * 4 * 4];
|
||||
ctx.BrushImageLoader = (name, w, h, arguments) =>
|
||||
{
|
||||
capturedName = name;
|
||||
capturedW = w;
|
||||
capturedH = h;
|
||||
captured = [.. arguments];
|
||||
return (rendered, 6, 4);
|
||||
};
|
||||
|
||||
engine.Execute("obj.brush('縞模様', '色1', 0xff0000, 'ズーム', 250, '有効', true, 'ラベル', 'abc')", ctx);
|
||||
|
||||
Assert.Equal("縞模様", capturedName);
|
||||
Assert.Equal(6d, capturedW);
|
||||
Assert.Equal(4d, capturedH);
|
||||
Assert.NotNull(captured);
|
||||
Assert.Equal(4, captured!.Count);
|
||||
Assert.Equal(new KeyValuePair<string, object>("色1", (double)0xff0000), captured[0]);
|
||||
Assert.Equal(new KeyValuePair<string, object>("ズーム", 250d), captured[1]);
|
||||
Assert.Equal(new KeyValuePair<string, object>("有効", true), captured[2]);
|
||||
Assert.Equal(new KeyValuePair<string, object>("ラベル", "abc"), captured[3]);
|
||||
Assert.True(ctx.BufferReplaced);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Brush_AcceptsLeadingSizeBeforePairs()
|
||||
{
|
||||
using var engine = CreateEngine();
|
||||
var ctx = NewContext();
|
||||
|
||||
double capturedW = -1, capturedH = -1;
|
||||
List<KeyValuePair<string, object>>? captured = null;
|
||||
ctx.BrushImageLoader = (_, w, h, arguments) =>
|
||||
{
|
||||
capturedW = w;
|
||||
capturedH = h;
|
||||
captured = [.. arguments];
|
||||
return ([], 0, 0);
|
||||
};
|
||||
|
||||
engine.Execute("obj.brush('市松模様', 320, 240, 'ズーム', 50)", ctx);
|
||||
|
||||
Assert.Equal(320d, capturedW);
|
||||
Assert.Equal(240d, capturedH);
|
||||
Assert.NotNull(captured);
|
||||
Assert.Equal(new KeyValuePair<string, object>("ズーム", 50d), Assert.Single(captured!));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Brush_WithoutPairs_UsesObjectDimensions()
|
||||
{
|
||||
using var engine = CreateEngine();
|
||||
var ctx = NewContext();
|
||||
|
||||
double capturedW = -1, capturedH = -1;
|
||||
int capturedCount = -1;
|
||||
ctx.BrushImageLoader = (_, w, h, arguments) =>
|
||||
{
|
||||
capturedW = w;
|
||||
capturedH = h;
|
||||
capturedCount = arguments.Count;
|
||||
return ([], 0, 0);
|
||||
};
|
||||
|
||||
engine.Execute("obj.brush('市松模様')", ctx);
|
||||
|
||||
Assert.Equal(6d, capturedW);
|
||||
Assert.Equal(4d, capturedH);
|
||||
Assert.Equal(0, capturedCount);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void LoadBrush_FailureKeepsCurrentImage()
|
||||
{
|
||||
using var engine = CreateEngine();
|
||||
var ctx = NewContext();
|
||||
|
||||
ctx.BrushImageLoader = (_, _, _, _) => ([], 0, 0);
|
||||
|
||||
engine.Execute("obj.load('brush', '不明'); obj.x = obj.w; obj.y = obj.h", ctx);
|
||||
|
||||
Assert.False(ctx.BufferReplaced);
|
||||
Assert.Equal(6d, ctx.X);
|
||||
Assert.Equal(4d, ctx.Y);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -333,5 +333,340 @@ namespace LuaScript.Tests
|
||||
{
|
||||
Assert.Equal(30d, Eval("s = 0\nfor i in <0..10, 2> do s = s + i end\nresult = s").Number);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Ternary_Rewrites()
|
||||
{
|
||||
Assert.Equal(
|
||||
"x = (function() if c then return (1) else return (2) end end)()",
|
||||
Rewrite("x = c ? 1 : 2"));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Ternary_Evaluates()
|
||||
{
|
||||
Assert.Equal(1d, Eval("result = true ? 1 : 2").Number);
|
||||
Assert.Equal(2d, Eval("result = false ? 1 : 2").Number);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Ternary_ReturnsFalsyBranch()
|
||||
{
|
||||
var value = Eval("result = true ? false : 1");
|
||||
Assert.Equal(DataType.Boolean, value.Type);
|
||||
Assert.False(value.Boolean);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Ternary_InsideCallArgument()
|
||||
{
|
||||
Assert.Equal(3d, Eval("function f(v, w) return v + w end\nresult = f(true ? 1 : 2, 2)").Number);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Ternary_NestedInElse()
|
||||
{
|
||||
Assert.Equal(3d, Eval("a = 3\nresult = a == 1 ? 1 : a == 2 ? 2 : 3").Number);
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[InlineData("x = a and b or c")]
|
||||
[InlineData("t = { x = 1, y = 2 }")]
|
||||
[InlineData("obj:draw()")]
|
||||
[InlineData("::label::")]
|
||||
public void Ternary_DoesNotTouchOtherCode(string source)
|
||||
{
|
||||
Assert.Equal(source, Rewrite(source));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void SafeNavigation_ReturnsNilForNilTarget()
|
||||
{
|
||||
Assert.True(Eval("t = nil\nresult = t?.x == nil").Boolean);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void SafeNavigation_ReadsMember()
|
||||
{
|
||||
Assert.Equal(5d, Eval("t = { x = 5 }\nresult = t?.x").Number);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void SafeNavigation_Chains()
|
||||
{
|
||||
Assert.True(Eval("t = { a = nil }\nresult = t?.a?.b == nil").Boolean);
|
||||
Assert.Equal(7d, Eval("t = { a = { b = 7 } }\nresult = t?.a?.b").Number);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void SafeNavigation_Index()
|
||||
{
|
||||
Assert.True(Eval("t = nil\nresult = t?[1] == nil").Boolean);
|
||||
Assert.Equal(9d, Eval("t = { 9 }\nresult = t?[1]").Number);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void SafeNavigation_EvaluatesTargetOnce()
|
||||
{
|
||||
const string source = "calls = 0\nfunction f() calls = calls + 1 return { x = 3 } end\nresult = f()?.x";
|
||||
var script = new Script(CoreModules.Preset_SoftSandbox);
|
||||
script.DoString(AviUtlScript.Transform(source));
|
||||
Assert.Equal(3d, script.Globals.Get("result").Number);
|
||||
Assert.Equal(1d, script.Globals.Get("calls").Number);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void SafeNavigation_CombinesWithNilCoalesce()
|
||||
{
|
||||
Assert.Equal(4d, Eval("t = nil\nresult = t?.x ?? 4").Number);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Lambda_Rewrites()
|
||||
{
|
||||
Assert.Equal(
|
||||
"f = (function(a, b) return a + b end)",
|
||||
Rewrite("f = (a, b) => a + b"));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Lambda_SingleParameterWithoutParens()
|
||||
{
|
||||
Assert.Equal(9d, Eval("f = x => x * 3\nresult = f(3)").Number);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Lambda_NoParameters()
|
||||
{
|
||||
Assert.Equal(1d, Eval("f = () => 1\nresult = f()").Number);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Lambda_AsSortComparer()
|
||||
{
|
||||
const string source = "t = { 3, 1, 2 }\ntable.sort(t, (a, b) => a < b)\nresult = t[1]";
|
||||
Assert.Equal(1d, Eval(source).Number);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Lambda_DoesNotTouchComparisons()
|
||||
{
|
||||
Assert.Equal("x = a >= b", Rewrite("x = a >= b"));
|
||||
Assert.Equal("x = a <= b", Rewrite("x = a <= b"));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void InterpolatedString_Rewrites()
|
||||
{
|
||||
Assert.Equal(
|
||||
"s = (\"x=\" .. tostring(a))",
|
||||
Rewrite("s = `x={a}`"));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void InterpolatedString_Evaluates()
|
||||
{
|
||||
Assert.Equal("x=5 y=6", Eval("a = 5\nb = 6\nresult = `x={a} y={b}`").String);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void InterpolatedString_PlainLiteral()
|
||||
{
|
||||
Assert.Equal("hello", Eval("result = `hello`").String);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void InterpolatedString_ExpressionOnly()
|
||||
{
|
||||
Assert.Equal("7", Eval("result = `{3 + 4}`").String);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void InterpolatedString_NestedExtensionSyntax()
|
||||
{
|
||||
Assert.Equal("4", Eval("t = nil\nresult = `{t ?? 4}`").String);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void InterpolatedString_Empty()
|
||||
{
|
||||
Assert.Equal("", Eval("result = ``").String);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Backtick_InsideStringOrComment_IsPreserved()
|
||||
{
|
||||
const string source = "x = \"a ` b\"";
|
||||
Assert.Equal(source, Rewrite(source));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Pipe_Rewrites()
|
||||
{
|
||||
Assert.Equal("x = f((v))", Rewrite("x = v |> f"));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Pipe_Evaluates()
|
||||
{
|
||||
Assert.Equal(4d, Eval("function double(v) return v * 2 end\nresult = 2 |> double").Number);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Pipe_InsertsAsFirstArgument()
|
||||
{
|
||||
Assert.Equal(
|
||||
"x = clamp((v), 0, 255)",
|
||||
Rewrite("x = v |> clamp(0, 255)"));
|
||||
Assert.Equal(5d, Eval("function clamp(v, lo, hi) return math.min(math.max(v, lo), hi) end\nresult = 5 |> clamp(0, 255)").Number);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Pipe_Chains()
|
||||
{
|
||||
const string source = "function inc(v) return v + 1 end\nfunction double(v) return v * 2 end\nresult = 3 |> inc |> double";
|
||||
Assert.Equal(8d, Eval(source).Number);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Pipe_MemberFunction()
|
||||
{
|
||||
Assert.Equal(2d, Eval("result = 2.9 |> math.floor").Number);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void RangeMembership_Rewrites()
|
||||
{
|
||||
Assert.Equal(
|
||||
"x = (function() local __lc0 = (v) return __lc0 >= (1) and __lc0 <= (5) end)()",
|
||||
Rewrite("x = v in <1..5>"));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void RangeMembership_Evaluates()
|
||||
{
|
||||
Assert.True(Eval("result = 3 in <1..5>").Boolean);
|
||||
Assert.True(Eval("result = 5 in <1..5>").Boolean);
|
||||
Assert.False(Eval("result = 6 in <1..5>").Boolean);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void RangeMembership_ExclusiveEvaluates()
|
||||
{
|
||||
Assert.False(Eval("result = 5 in <1..<5>").Boolean);
|
||||
Assert.True(Eval("result = 4 in <1..<5>").Boolean);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void RangeMembership_InsideIf()
|
||||
{
|
||||
Assert.Equal(1d, Eval("v = 40\nresult = 0\nif v in <30..60> then result = 1 end").Number);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void RangeMembership_EvaluatesLeftOnce()
|
||||
{
|
||||
const string source = "calls = 0\nfunction f() calls = calls + 1 return 3 end\nresult = f() in <1..5>";
|
||||
var script = new Script(CoreModules.Preset_SoftSandbox);
|
||||
script.DoString(AviUtlScript.Transform(source));
|
||||
Assert.True(script.Globals.Get("result").Boolean);
|
||||
Assert.Equal(1d, script.Globals.Get("calls").Number);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void RangeMembership_DoesNotTouchForHeaders()
|
||||
{
|
||||
Assert.Equal("for i = 0, 10 do end", Rewrite("for i in <0..10> do end"));
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[InlineData("[fast] obj.fill(0, 0, 0, 255)", " __fast_fill(0, 0, 0, 255)")]
|
||||
[InlineData("[fast] obj.convolve(k, 3)", " __fast_convolve(k, 3)")]
|
||||
[InlineData("[fast] obj.resize(100, 100)", " __fast_resize(100, 100)")]
|
||||
[InlineData("[ fast ] obj.resize(100, 100)", " __fast_resize(100, 100)")]
|
||||
[InlineData("[fast]obj.fill()", "__fast_fill()")]
|
||||
[InlineData(" [fast] obj.fill()", " __fast_fill()")]
|
||||
public void Fast_RewritesAcceleratedPrimitive(string source, string expected)
|
||||
{
|
||||
Assert.Equal(expected, Rewrite(source));
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[InlineData("[fast]\nobj.fill(0, 0, 0, 255)", "\n__fast_fill(0, 0, 0, 255)")]
|
||||
[InlineData("[fast]\nobj.convolve(k, 3)", "\n__fast_convolve(k, 3)")]
|
||||
[InlineData("[fast]\nobj.resize(64, 64)", "\n__fast_resize(64, 64)")]
|
||||
[InlineData("obj.x = 1\n[fast]\nobj.resize(64, 64)", "obj.x = 1\n\n__fast_resize(64, 64)")]
|
||||
public void Fast_MarkerOnOwnLine_RewritesNextStatement(string source, string expected)
|
||||
{
|
||||
Assert.Equal(expected, Rewrite(source));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Fast_MarkerOnOwnLine_ReportsDiagnosticOnMarkerLine()
|
||||
{
|
||||
var (code, _, diagnostics) = LuaSyntaxExtensions.RewriteWithMap("obj.x = 1\n[fast]\nobj.draw(0)");
|
||||
Assert.Equal("obj.x = 1\n\nobj.draw(0)", code);
|
||||
var diagnostic = Assert.Single(diagnostics);
|
||||
Assert.Equal(2, diagnostic.Line);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Fast_KeywordIsRegisteredInCatalog()
|
||||
{
|
||||
Assert.Contains("fast", LuaScript.Compat.Syntax.LuaSyntaxRuleRegistry.CatalogKeywords);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Fast_RewritesInsideBlock()
|
||||
{
|
||||
Assert.Equal(
|
||||
"for i = 1, 3 do __fast_fill(i, i, i, 255) end",
|
||||
Rewrite("for i in <1..3> do [fast] obj.fill(i, i, i, 255) end"));
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[InlineData("x = t[fast]")]
|
||||
[InlineData("x = obj.data[fast]")]
|
||||
[InlineData("x = f()[fast]")]
|
||||
[InlineData("t = { [fast] = 1 }")]
|
||||
[InlineData("x = \"[fast] obj.fill()\"")]
|
||||
[InlineData("-- [fast] obj.fill()")]
|
||||
public void Fast_DoesNotTouchNonMarkerBrackets(string source)
|
||||
{
|
||||
Assert.Equal(source, Rewrite(source));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Fast_OnUnsupportedTargetStripsMarkerAndReportsDiagnostic()
|
||||
{
|
||||
var (code, _, diagnostics) = LuaSyntaxExtensions.RewriteWithMap("[fast] obj.draw(0)");
|
||||
Assert.Equal(" obj.draw(0)", code);
|
||||
var diagnostic = Assert.Single(diagnostics);
|
||||
Assert.Equal(1, diagnostic.Line);
|
||||
Assert.Contains("fast", diagnostic.Message);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Fast_OnNonObjTargetReportsDiagnostic()
|
||||
{
|
||||
var (code, _, diagnostics) = LuaSyntaxExtensions.RewriteWithMap("[fast] local x = 1");
|
||||
Assert.Equal(" local x = 1", code);
|
||||
Assert.Single(diagnostics);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Fast_SupportedTargetEmitsNoDiagnostic()
|
||||
{
|
||||
var (_, _, diagnostics) = LuaSyntaxExtensions.RewriteWithMap("[fast] obj.fill(0, 0, 0, 255)");
|
||||
Assert.Empty(diagnostics);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Fast_ReportsDiagnosticLineWithinBlock()
|
||||
{
|
||||
var (_, _, diagnostics) = LuaSyntaxExtensions.RewriteWithMap("obj.x = 1\n[fast] obj.draw(0)");
|
||||
var diagnostic = Assert.Single(diagnostics);
|
||||
Assert.Equal(2, diagnostic.Line);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -22,9 +22,13 @@ namespace LuaScript.Tests
|
||||
|
||||
private readonly LuaJitWorker _worker = new(NativeDir, ScriptPath);
|
||||
|
||||
private Func<string, double, (byte[] buffer, int w, int h)> _loadScene = (_, _) => ([], 0, 0);
|
||||
private Func<string, double, double, System.Collections.Generic.IReadOnlyList<System.Collections.Generic.KeyValuePair<string, object>>, (byte[] buffer, int w, int h)> _loadBrush = (_, _, _, _) => ([], 0, 0);
|
||||
private Func<string, SceneValue> _sceneGet = _ => SceneValue.Nil;
|
||||
private Action<string, SceneValue> _sceneSet = (_, _) => { };
|
||||
private Func<string, string, int, (int Count, int Rate, double[] Data)> _loadAudio = (_, _, _) => (0, 0, []);
|
||||
private PixelShaderInvoke? _runPixelShader;
|
||||
private IPixelBufferProcessor? _pixelProcessor;
|
||||
|
||||
public void Dispose() => _worker.Dispose();
|
||||
|
||||
@@ -70,9 +74,11 @@ namespace LuaScript.Tests
|
||||
System.Runtime.InteropServices.Marshal.Copy(uploaded, 0, address, uploaded.Length);
|
||||
},
|
||||
width, height, timeoutMs,
|
||||
resolveObject, loadFigure, loadText, loadImage, loadMovie, addEffect, addDraw, setAnchor,
|
||||
resolveObject, loadFigure, loadText, loadImage, loadMovie, _loadScene, _loadBrush, addEffect, addDraw, setAnchor,
|
||||
_sceneGet, _sceneSet,
|
||||
_loadAudio,
|
||||
_runPixelShader,
|
||||
_pixelProcessor,
|
||||
out pixelsDirty, out bufferReplaced, out resultWidth, out resultHeight, out error);
|
||||
|
||||
resultPixels = null;
|
||||
@@ -106,9 +112,11 @@ namespace LuaScript.Tests
|
||||
observedCapacity = capacity;
|
||||
System.Runtime.InteropServices.Marshal.Copy(pixels, 0, address, pixels.Length);
|
||||
},
|
||||
w, h, 5000, NoResolver, NoLoadFigure, NoLoadText, NoLoadImage, NoLoadMovie, NoAddEffect, NoAddDraw, NoSetAnchor,
|
||||
w, h, 5000, NoResolver, NoLoadFigure, NoLoadText, NoLoadImage, NoLoadMovie, _loadScene, _loadBrush, NoAddEffect, NoAddDraw, NoSetAnchor,
|
||||
_sceneGet, _sceneSet,
|
||||
_loadAudio,
|
||||
_runPixelShader,
|
||||
null,
|
||||
out _, out _, out _, out _, out string? error);
|
||||
|
||||
Assert.True(ok, error);
|
||||
@@ -523,7 +531,7 @@ namespace LuaScript.Tests
|
||||
|
||||
var pixels = new byte[16];
|
||||
var fields = Fields(2, 2, 0d);
|
||||
var resolved = new SceneObjectInfo("a", true, 12d, 34d, 56d, 2d, 90d, 200d, 7);
|
||||
var resolved = new SceneObjectInfo("a", true, 12d, 34d, 56d, 2d, 90d, 200d, 7, 120, 75d, "reimu", "hello", "VoiceItem");
|
||||
Func<string, int, SceneObjectInfo?> resolver = (tag, frame) =>
|
||||
tag == "a" && frame == 5 ? resolved : null;
|
||||
|
||||
@@ -531,7 +539,11 @@ namespace LuaScript.Tests
|
||||
"local o = obj.getobject(\"a\", 5) " +
|
||||
"obj.x = o.x obj.y = o.y obj.z = o.z " +
|
||||
"obj.zoom = o.zoom obj.rz = o.rz obj.alpha = o.alpha " +
|
||||
"obj.sx = o.sy obj.rzr = o.rzr";
|
||||
"obj.sx = o.sy obj.rzr = o.rzr " +
|
||||
"obj.ox = o.volume obj.oy = o.length " +
|
||||
"obj.oz = (o.character == \"reimu\") and 1 or 0 " +
|
||||
"obj.rx = (o.text == \"hello\") and 1 or 0 " +
|
||||
"obj.ry = (o.kind == \"VoiceItem\") and 1 or 0";
|
||||
|
||||
bool ok = RunWorker(script, fields, NoStringParams, () => pixels, 2, 2, 5000, resolver, NoLoadFigure, NoLoadText, NoLoadImage, NoLoadMovie, NoAddEffect, NoAddDraw, NoSetAnchor, out _, out _, out _, out _, out _, out string? error);
|
||||
|
||||
@@ -544,6 +556,11 @@ namespace LuaScript.Tests
|
||||
Assert.Equal(200d, fields[NativeProtocol.Alpha]);
|
||||
Assert.Equal(2d, fields[NativeProtocol.Sx]);
|
||||
Assert.Equal(90d * Math.PI / 180d, fields[NativeProtocol.Rzr]);
|
||||
Assert.Equal(75d, fields[NativeProtocol.Ox]);
|
||||
Assert.Equal(120d, fields[NativeProtocol.Oy]);
|
||||
Assert.Equal(1d, fields[NativeProtocol.Oz]);
|
||||
Assert.Equal(1d, fields[NativeProtocol.Rx]);
|
||||
Assert.Equal(1d, fields[NativeProtocol.Ry]);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
@@ -557,7 +574,7 @@ namespace LuaScript.Tests
|
||||
Func<string, int, SceneObjectInfo?> resolver = (tag, frame) =>
|
||||
{
|
||||
calls++;
|
||||
return tag == "a" ? new SceneObjectInfo("a", true, x, 0, 0, 1, 0, 255, 0) : null;
|
||||
return tag == "a" ? new SceneObjectInfo("a", true, x, 0, 0, 1, 0, 255, 0, 0, 0d, "", "", "") : null;
|
||||
};
|
||||
|
||||
const string script =
|
||||
@@ -1027,6 +1044,215 @@ namespace LuaScript.Tests
|
||||
Assert.Equal(frame, newPixels!.AsSpan(0, frame.Length).ToArray());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void LoadScene_RoundTripsNameAndTime()
|
||||
{
|
||||
Assert.True(LuaJitWorker.IsAvailable(NativeDir), "native/luajit.exe must be present");
|
||||
|
||||
const int sw = 2, sh = 2;
|
||||
var rendered = new byte[sw * sh * 4];
|
||||
for (int i = 0; i < rendered.Length; i++)
|
||||
rendered[i] = (byte)((i * 13 + 1) & 0xFF);
|
||||
|
||||
string? capturedName = null;
|
||||
double capturedTime = -1;
|
||||
_loadScene = (name, time) =>
|
||||
{
|
||||
capturedName = name;
|
||||
capturedTime = time;
|
||||
return (rendered, sw, sh);
|
||||
};
|
||||
|
||||
var pixels = new byte[4 * 4 * 4];
|
||||
var fields = Fields(4, 4, 0d);
|
||||
|
||||
bool ok = RunWorker(
|
||||
"obj.load('scene', 'サブシーン', 2.5)",
|
||||
fields, NoStringParams, () => pixels, 4, 4, 5000, NoResolver, NoLoadFigure, NoLoadText, NoLoadImage, NoLoadMovie, NoAddEffect, NoAddDraw, NoSetAnchor,
|
||||
out bool dirty, out bool bufferReplaced, out byte[]? newPixels, out int rw, out int rh, out string? error);
|
||||
|
||||
Assert.True(ok, error);
|
||||
Assert.Equal("サブシーン", capturedName);
|
||||
Assert.Equal(2.5d, capturedTime);
|
||||
Assert.True(dirty);
|
||||
Assert.True(bufferReplaced);
|
||||
Assert.Equal(sw, rw);
|
||||
Assert.Equal(sh, rh);
|
||||
Assert.NotNull(newPixels);
|
||||
Assert.Equal(rendered, newPixels!.AsSpan(0, rendered.Length).ToArray());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void LoadScene_DefaultsTimeToObjTime_AndKeepsImageOnFailure()
|
||||
{
|
||||
Assert.True(LuaJitWorker.IsAvailable(NativeDir), "native/luajit.exe must be present");
|
||||
|
||||
double capturedTime = -1;
|
||||
_loadScene = (_, time) =>
|
||||
{
|
||||
capturedTime = time;
|
||||
return ([], 0, 0);
|
||||
};
|
||||
|
||||
var pixels = new byte[16];
|
||||
var fields = Fields(2, 2, 1.25d);
|
||||
|
||||
bool ok = RunWorker(
|
||||
"obj.load('scene', 'missing') obj.x = obj.w",
|
||||
fields, NoStringParams, () => pixels, 2, 2, 5000, NoResolver, NoLoadFigure, NoLoadText, NoLoadImage, NoLoadMovie, NoAddEffect, NoAddDraw, NoSetAnchor,
|
||||
out bool dirty, out bool bufferReplaced, out _, out _, out _, out string? error);
|
||||
|
||||
Assert.True(ok, error);
|
||||
Assert.Equal(1.25d, capturedTime);
|
||||
Assert.False(dirty);
|
||||
Assert.False(bufferReplaced);
|
||||
Assert.Equal(2d, fields[NativeProtocol.X]);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void LoadBrush_RoundTripsNameAndSize()
|
||||
{
|
||||
Assert.True(LuaJitWorker.IsAvailable(NativeDir), "native/luajit.exe must be present");
|
||||
|
||||
const int bw = 3, bh = 2;
|
||||
var rendered = new byte[bw * bh * 4];
|
||||
for (int i = 0; i < rendered.Length; i++)
|
||||
rendered[i] = (byte)((i * 11 + 2) & 0xFF);
|
||||
|
||||
string? capturedName = null;
|
||||
double capturedW = -1, capturedH = -1;
|
||||
_loadBrush = (name, w, h, _) =>
|
||||
{
|
||||
capturedName = name;
|
||||
capturedW = w;
|
||||
capturedH = h;
|
||||
return (rendered, bw, bh);
|
||||
};
|
||||
|
||||
var pixels = new byte[4 * 4 * 4];
|
||||
var fields = Fields(4, 4, 0d);
|
||||
|
||||
bool ok = RunWorker(
|
||||
"obj.load('brush', '縞模様', 3, 2)",
|
||||
fields, NoStringParams, () => pixels, 4, 4, 5000, NoResolver, NoLoadFigure, NoLoadText, NoLoadImage, NoLoadMovie, NoAddEffect, NoAddDraw, NoSetAnchor,
|
||||
out bool dirty, out bool bufferReplaced, out byte[]? newPixels, out int rw, out int rh, out string? error);
|
||||
|
||||
Assert.True(ok, error);
|
||||
Assert.Equal("縞模様", capturedName);
|
||||
Assert.Equal(3d, capturedW);
|
||||
Assert.Equal(2d, capturedH);
|
||||
Assert.True(dirty);
|
||||
Assert.True(bufferReplaced);
|
||||
Assert.Equal(bw, rw);
|
||||
Assert.Equal(bh, rh);
|
||||
Assert.NotNull(newPixels);
|
||||
Assert.Equal(rendered, newPixels!.AsSpan(0, rendered.Length).ToArray());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Brush_RoundTripsPairsAndDefaultSize()
|
||||
{
|
||||
Assert.True(LuaJitWorker.IsAvailable(NativeDir), "native/luajit.exe must be present");
|
||||
|
||||
const int bw = 2, bh = 2;
|
||||
var rendered = new byte[bw * bh * 4];
|
||||
for (int i = 0; i < rendered.Length; i++)
|
||||
rendered[i] = (byte)((i * 7 + 4) & 0xFF);
|
||||
|
||||
string? capturedName = null;
|
||||
double capturedW = -1, capturedH = -1;
|
||||
System.Collections.Generic.List<System.Collections.Generic.KeyValuePair<string, object>>? captured = null;
|
||||
_loadBrush = (name, w, h, arguments) =>
|
||||
{
|
||||
capturedName = name;
|
||||
capturedW = w;
|
||||
capturedH = h;
|
||||
captured = [.. arguments];
|
||||
return (rendered, bw, bh);
|
||||
};
|
||||
|
||||
var pixels = new byte[4 * 2 * 4];
|
||||
var fields = Fields(4, 2, 0d);
|
||||
|
||||
bool ok = RunWorker(
|
||||
"obj.brush('縞模様', '色1', 0xff0000, '有効', true, 'ラベル', 'abc')",
|
||||
fields, NoStringParams, () => pixels, 4, 2, 5000, NoResolver, NoLoadFigure, NoLoadText, NoLoadImage, NoLoadMovie, NoAddEffect, NoAddDraw, NoSetAnchor,
|
||||
out bool dirty, out bool bufferReplaced, out byte[]? newPixels, out int rw, out int rh, out string? error);
|
||||
|
||||
Assert.True(ok, error);
|
||||
Assert.Equal("縞模様", capturedName);
|
||||
Assert.Equal(4d, capturedW);
|
||||
Assert.Equal(2d, capturedH);
|
||||
Assert.NotNull(captured);
|
||||
Assert.Equal(3, captured!.Count);
|
||||
Assert.Equal(new System.Collections.Generic.KeyValuePair<string, object>("色1", (double)0xff0000), captured[0]);
|
||||
Assert.Equal(new System.Collections.Generic.KeyValuePair<string, object>("有効", true), captured[1]);
|
||||
Assert.Equal(new System.Collections.Generic.KeyValuePair<string, object>("ラベル", "abc"), captured[2]);
|
||||
Assert.True(dirty);
|
||||
Assert.True(bufferReplaced);
|
||||
Assert.Equal(bw, rw);
|
||||
Assert.Equal(bh, rh);
|
||||
Assert.NotNull(newPixels);
|
||||
Assert.Equal(rendered, newPixels!.AsSpan(0, rendered.Length).ToArray());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Brush_RoundTripsLeadingSize()
|
||||
{
|
||||
Assert.True(LuaJitWorker.IsAvailable(NativeDir), "native/luajit.exe must be present");
|
||||
|
||||
double capturedW = -1, capturedH = -1;
|
||||
int capturedCount = -1;
|
||||
_loadBrush = (_, w, h, arguments) =>
|
||||
{
|
||||
capturedW = w;
|
||||
capturedH = h;
|
||||
capturedCount = arguments.Count;
|
||||
return ([], 0, 0);
|
||||
};
|
||||
|
||||
var pixels = new byte[16];
|
||||
var fields = Fields(2, 2, 0d);
|
||||
|
||||
bool ok = RunWorker(
|
||||
"obj.brush('市松模様', 320, 240, 'ズーム', 50)",
|
||||
fields, NoStringParams, () => pixels, 2, 2, 5000, NoResolver, NoLoadFigure, NoLoadText, NoLoadImage, NoLoadMovie, NoAddEffect, NoAddDraw, NoSetAnchor,
|
||||
out bool dirty, out _, out _, out _, out _, out string? error);
|
||||
|
||||
Assert.True(ok, error);
|
||||
Assert.Equal(320d, capturedW);
|
||||
Assert.Equal(240d, capturedH);
|
||||
Assert.Equal(1, capturedCount);
|
||||
Assert.False(dirty);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void LoadBrush_DefaultsSizeToObjectDimensions()
|
||||
{
|
||||
Assert.True(LuaJitWorker.IsAvailable(NativeDir), "native/luajit.exe must be present");
|
||||
|
||||
double capturedW = -1, capturedH = -1;
|
||||
_loadBrush = (_, w, h, _) =>
|
||||
{
|
||||
capturedW = w;
|
||||
capturedH = h;
|
||||
return ([], 0, 0);
|
||||
};
|
||||
|
||||
var pixels = new byte[4 * 2 * 4];
|
||||
var fields = Fields(4, 2, 0d);
|
||||
|
||||
bool ok = RunWorker(
|
||||
"obj.load('brush', '市松模様')",
|
||||
fields, NoStringParams, () => pixels, 4, 2, 5000, NoResolver, NoLoadFigure, NoLoadText, NoLoadImage, NoLoadMovie, NoAddEffect, NoAddDraw, NoSetAnchor,
|
||||
out bool dirty, out _, out _, out _, out _, out string? error);
|
||||
|
||||
Assert.True(ok, error);
|
||||
Assert.Equal(4d, capturedW);
|
||||
Assert.Equal(2d, capturedH);
|
||||
Assert.False(dirty);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void GetValue_ReturnsObjFields()
|
||||
{
|
||||
@@ -1047,6 +1273,79 @@ namespace LuaScript.Tests
|
||||
Assert.Equal(0d, fields[NativeProtocol.Z]);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void GetAudio_RoundTripsThroughCallback()
|
||||
{
|
||||
Assert.True(LuaJitWorker.IsAvailable(NativeDir), "native/luajit.exe must be present");
|
||||
|
||||
string? capturedFile = null;
|
||||
string? capturedType = null;
|
||||
int capturedSize = -1;
|
||||
_loadAudio = (file, type, size) =>
|
||||
{
|
||||
capturedFile = file;
|
||||
capturedType = type;
|
||||
capturedSize = size;
|
||||
return (4, 48000, [10d, -20d, 30.5d, 40d]);
|
||||
};
|
||||
|
||||
var pixels = new byte[16];
|
||||
var fields = Fields(2, 2, 0d);
|
||||
const string script =
|
||||
"local buf = {}\n" +
|
||||
"local n, rate = obj.getaudio(buf, 'audiobuffer', 'pcm', 4)\n" +
|
||||
"obj.x = n\n" +
|
||||
"obj.y = rate\n" +
|
||||
"obj.z = buf[1]\n" +
|
||||
"obj.ox = buf[2]\n" +
|
||||
"obj.oy = buf[3]\n" +
|
||||
"obj.oz = buf[4]\n" +
|
||||
"local n2, rate2, buf2 = obj.getaudio(nil, 'C:/test.wav', 'spectrum.l', 2)\n" +
|
||||
"obj.sx = n2\n" +
|
||||
"obj.sy = buf2[1]";
|
||||
|
||||
bool ok = RunWorker(script, fields, NoStringParams, () => pixels, 2, 2, 5000, NoResolver, NoLoadFigure, NoLoadText, NoLoadImage, NoLoadMovie, NoAddEffect, NoAddDraw, NoSetAnchor, out _, out _, out _, out _, out _, out string? error);
|
||||
|
||||
Assert.True(ok, error);
|
||||
Assert.Equal("C:/test.wav", capturedFile);
|
||||
Assert.Equal("spectrum.l", capturedType);
|
||||
Assert.Equal(2, capturedSize);
|
||||
Assert.Equal(4d, fields[NativeProtocol.X]);
|
||||
Assert.Equal(48000d, fields[NativeProtocol.Y]);
|
||||
Assert.Equal(10d, fields[NativeProtocol.Z]);
|
||||
Assert.Equal(-20d, fields[NativeProtocol.Ox]);
|
||||
Assert.Equal(30.5d, fields[NativeProtocol.Oy]);
|
||||
Assert.Equal(40d, fields[NativeProtocol.Oz]);
|
||||
Assert.Equal(4d, fields[NativeProtocol.Sx]);
|
||||
Assert.Equal(10d, fields[NativeProtocol.Sy]);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void GetAudio_FailureYieldsZeroCount()
|
||||
{
|
||||
Assert.True(LuaJitWorker.IsAvailable(NativeDir), "native/luajit.exe must be present");
|
||||
|
||||
_loadAudio = (_, _, _) => throw new InvalidOperationException();
|
||||
|
||||
var pixels = new byte[16];
|
||||
var fields = Fields(2, 2, 0d);
|
||||
const string script =
|
||||
"local n, rate, buf = obj.getaudio(nil, 'audiobuffer', 'pcm', 8)\n" +
|
||||
"obj.x = n\n" +
|
||||
"obj.y = rate\n" +
|
||||
"obj.z = #buf\n" +
|
||||
"local n2 = obj.getaudio({}, 7)\n" +
|
||||
"obj.ox = n2";
|
||||
|
||||
bool ok = RunWorker(script, fields, NoStringParams, () => pixels, 2, 2, 5000, NoResolver, NoLoadFigure, NoLoadText, NoLoadImage, NoLoadMovie, NoAddEffect, NoAddDraw, NoSetAnchor, out _, out _, out _, out _, out _, out string? error);
|
||||
|
||||
Assert.True(ok, error);
|
||||
Assert.Equal(0d, fields[NativeProtocol.X]);
|
||||
Assert.Equal(0d, fields[NativeProtocol.Y]);
|
||||
Assert.Equal(0d, fields[NativeProtocol.Z]);
|
||||
Assert.Equal(0d, fields[NativeProtocol.Ox]);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void CopyBuffer_TmpSaveRestore_RoundTripsPixels()
|
||||
{
|
||||
@@ -1608,5 +1907,570 @@ namespace LuaScript.Tests
|
||||
Assert.True(ok2, error);
|
||||
Assert.Equal(7d, fields2[NativeProtocol.X]);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void PixelProcess_Fill_UsesHostProcessor()
|
||||
{
|
||||
Assert.True(LuaJitWorker.IsAvailable(NativeDir), "native/luajit.exe must be present");
|
||||
|
||||
const int w = 1024, h = 1024;
|
||||
var pixels = new byte[w * h * 4];
|
||||
var processor = new RecordingPixelProcessor { FillResult = true };
|
||||
_pixelProcessor = processor;
|
||||
|
||||
bool ok = RunWorker(
|
||||
"__fast_fill(10, 20, 30, 40, 0, 0, 1024, 1024)",
|
||||
Fields(w, h, 0d), NoStringParams, () => pixels, w, h, 5000, NoResolver, NoLoadFigure, NoLoadText, NoLoadImage, NoLoadMovie, NoAddEffect, NoAddDraw, NoSetAnchor,
|
||||
out bool dirty, out _, out _, out _, out _, out string? error);
|
||||
|
||||
Assert.True(ok, error);
|
||||
Assert.True(dirty);
|
||||
Assert.Equal(1, processor.FillCalls);
|
||||
Assert.True(processor.LastFillForce);
|
||||
Assert.Equal(0x41, pixels[0]);
|
||||
Assert.Equal(0x41, pixels[^1]);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void PixelProcess_Convolve_PassesKernelToHostProcessor()
|
||||
{
|
||||
Assert.True(LuaJitWorker.IsAvailable(NativeDir), "native/luajit.exe must be present");
|
||||
|
||||
const int w = 200, h = 200;
|
||||
var pixels = new byte[w * h * 4];
|
||||
var processor = new RecordingPixelProcessor { ConvolveResult = true };
|
||||
_pixelProcessor = processor;
|
||||
|
||||
bool ok = RunWorker(
|
||||
"__fast_convolve({1, 2, 3, 4, 5, 6, 7, 8, 9}, 3, 45, 6)",
|
||||
Fields(w, h, 0d), NoStringParams, () => pixels, w, h, 5000, NoResolver, NoLoadFigure, NoLoadText, NoLoadImage, NoLoadMovie, NoAddEffect, NoAddDraw, NoSetAnchor,
|
||||
out bool dirty, out _, out _, out _, out _, out string? error);
|
||||
|
||||
Assert.True(ok, error);
|
||||
Assert.True(dirty);
|
||||
Assert.Equal(1, processor.ConvolveCalls);
|
||||
Assert.Equal(3, processor.Size);
|
||||
Assert.Equal(45d, processor.Divisor);
|
||||
Assert.Equal(6d, processor.Offset);
|
||||
Assert.Equal(new double[] { 1, 2, 3, 4, 5, 6, 7, 8, 9 }, processor.Kernel);
|
||||
Assert.True(processor.LastConvolveForce);
|
||||
Assert.Equal(0x42, pixels[0]);
|
||||
Assert.Equal(0x42, pixels[^1]);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void PixelProcess_Resize_ReplacesBufferWithHostResult()
|
||||
{
|
||||
Assert.True(LuaJitWorker.IsAvailable(NativeDir), "native/luajit.exe must be present");
|
||||
|
||||
const int w = 2, h = 2;
|
||||
var pixels = new byte[w * h * 4];
|
||||
var processor = new RecordingPixelProcessor { ResizeResult = true };
|
||||
_pixelProcessor = processor;
|
||||
var fields = Fields(w, h, 0d);
|
||||
|
||||
bool ok = RunWorker(
|
||||
"__fast_resize(512, 512, 'nearest') obj.x = obj.w obj.y = obj.h",
|
||||
fields, NoStringParams, () => pixels, w, h, 5000, NoResolver, NoLoadFigure, NoLoadText, NoLoadImage, NoLoadMovie, NoAddEffect, NoAddDraw, NoSetAnchor,
|
||||
out bool dirty, out bool replaced, out byte[]? result, out int rw, out int rh, out string? error);
|
||||
|
||||
Assert.True(ok, error);
|
||||
Assert.True(dirty);
|
||||
Assert.True(replaced);
|
||||
Assert.Equal(512, rw);
|
||||
Assert.Equal(512, rh);
|
||||
Assert.Equal(512d, processor.TargetWidth);
|
||||
Assert.Equal(512d, processor.TargetHeight);
|
||||
Assert.False(processor.Linear);
|
||||
Assert.Equal(512d, fields[NativeProtocol.X]);
|
||||
Assert.Equal(512d, fields[NativeProtocol.Y]);
|
||||
Assert.NotNull(result);
|
||||
Assert.Equal(0x43, result![0]);
|
||||
Assert.Equal(0x43, result[^1]);
|
||||
Assert.True(processor.LastResizeForce);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void PixelProcess_DefaultFill_UsesHostProcessor()
|
||||
{
|
||||
Assert.True(LuaJitWorker.IsAvailable(NativeDir), "native/luajit.exe must be present");
|
||||
|
||||
const int w = 1024, h = 1024;
|
||||
var pixels = new byte[w * h * 4];
|
||||
var processor = new RecordingPixelProcessor { FillResult = true };
|
||||
_pixelProcessor = processor;
|
||||
|
||||
bool ok = RunWorker(
|
||||
"obj.fill(10, 20, 30, 40, 0, 0, 1024, 1024)",
|
||||
Fields(w, h, 0d), NoStringParams, () => pixels, w, h, 5000, NoResolver, NoLoadFigure, NoLoadText, NoLoadImage, NoLoadMovie, NoAddEffect, NoAddDraw, NoSetAnchor,
|
||||
out bool dirty, out _, out _, out _, out _, out string? error);
|
||||
|
||||
Assert.True(ok, error);
|
||||
Assert.True(dirty);
|
||||
Assert.Equal(1, processor.FillCalls);
|
||||
Assert.False(processor.LastFillForce);
|
||||
Assert.Equal(0x41, pixels[0]);
|
||||
Assert.Equal(0x41, pixels[^1]);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void PixelProcess_DefaultConvolve_UsesHostProcessor()
|
||||
{
|
||||
Assert.True(LuaJitWorker.IsAvailable(NativeDir), "native/luajit.exe must be present");
|
||||
|
||||
const int w = 200, h = 200;
|
||||
var pixels = new byte[w * h * 4];
|
||||
var processor = new RecordingPixelProcessor { ConvolveResult = true };
|
||||
_pixelProcessor = processor;
|
||||
|
||||
bool ok = RunWorker(
|
||||
"obj.convolve({1, 2, 3, 4, 5, 6, 7, 8, 9}, 3, 45, 6)",
|
||||
Fields(w, h, 0d), NoStringParams, () => pixels, w, h, 5000, NoResolver, NoLoadFigure, NoLoadText, NoLoadImage, NoLoadMovie, NoAddEffect, NoAddDraw, NoSetAnchor,
|
||||
out bool dirty, out _, out _, out _, out _, out string? error);
|
||||
|
||||
Assert.True(ok, error);
|
||||
Assert.True(dirty);
|
||||
Assert.Equal(1, processor.ConvolveCalls);
|
||||
Assert.Equal(3, processor.Size);
|
||||
Assert.Equal(45d, processor.Divisor);
|
||||
Assert.Equal(6d, processor.Offset);
|
||||
Assert.Equal(new double[] { 1, 2, 3, 4, 5, 6, 7, 8, 9 }, processor.Kernel);
|
||||
Assert.False(processor.LastConvolveForce);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void PixelProcess_DefaultResize_UsesHostProcessor()
|
||||
{
|
||||
Assert.True(LuaJitWorker.IsAvailable(NativeDir), "native/luajit.exe must be present");
|
||||
|
||||
const int w = 2, h = 2;
|
||||
var pixels = new byte[w * h * 4];
|
||||
var processor = new RecordingPixelProcessor { ResizeResult = true };
|
||||
_pixelProcessor = processor;
|
||||
|
||||
bool ok = RunWorker(
|
||||
"obj.resize(512, 512, 'nearest')",
|
||||
Fields(w, h, 0d), NoStringParams, () => pixels, w, h, 5000, NoResolver, NoLoadFigure, NoLoadText, NoLoadImage, NoLoadMovie, NoAddEffect, NoAddDraw, NoSetAnchor,
|
||||
out _, out bool replaced, out _, out int rw, out int rh, out string? error);
|
||||
|
||||
Assert.True(ok, error);
|
||||
Assert.True(replaced);
|
||||
Assert.Equal(1, processor.ResizeCalls);
|
||||
Assert.Equal(512, rw);
|
||||
Assert.Equal(512, rh);
|
||||
Assert.False(processor.LastResizeForce);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void PixelProcess_BelowThresholdFill_SkipsHostProcessor()
|
||||
{
|
||||
Assert.True(LuaJitWorker.IsAvailable(NativeDir), "native/luajit.exe must be present");
|
||||
|
||||
const int w = 64, h = 64;
|
||||
var pixels = new byte[w * h * 4];
|
||||
var processor = new RecordingPixelProcessor { FillResult = true };
|
||||
_pixelProcessor = processor;
|
||||
|
||||
bool ok = RunWorker(
|
||||
"obj.fill(10, 20, 30, 40)",
|
||||
Fields(w, h, 0d), NoStringParams, () => pixels, w, h, 5000, NoResolver, NoLoadFigure, NoLoadText, NoLoadImage, NoLoadMovie, NoAddEffect, NoAddDraw, NoSetAnchor,
|
||||
out _, out _, out _, out _, out _, out string? error);
|
||||
|
||||
Assert.True(ok, error);
|
||||
Assert.Equal(0, processor.FillCalls);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void PixelProcess_BelowThresholdConvolve_SkipsHostProcessor()
|
||||
{
|
||||
Assert.True(LuaJitWorker.IsAvailable(NativeDir), "native/luajit.exe must be present");
|
||||
|
||||
const int w = 8, h = 8;
|
||||
var pixels = new byte[w * h * 4];
|
||||
var processor = new RecordingPixelProcessor { ConvolveResult = true };
|
||||
_pixelProcessor = processor;
|
||||
|
||||
bool ok = RunWorker(
|
||||
"obj.convolve({1, 1, 1, 1, 1, 1, 1, 1, 1}, 3)",
|
||||
Fields(w, h, 0d), NoStringParams, () => pixels, w, h, 5000, NoResolver, NoLoadFigure, NoLoadText, NoLoadImage, NoLoadMovie, NoAddEffect, NoAddDraw, NoSetAnchor,
|
||||
out _, out _, out _, out _, out _, out string? error);
|
||||
|
||||
Assert.True(ok, error);
|
||||
Assert.Equal(0, processor.ConvolveCalls);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void PixelProcess_BelowThresholdResize_SkipsHostProcessor()
|
||||
{
|
||||
Assert.True(LuaJitWorker.IsAvailable(NativeDir), "native/luajit.exe must be present");
|
||||
|
||||
const int w = 2, h = 2;
|
||||
var pixels = new byte[w * h * 4];
|
||||
var processor = new RecordingPixelProcessor { ResizeResult = true };
|
||||
_pixelProcessor = processor;
|
||||
|
||||
bool ok = RunWorker(
|
||||
"obj.resize(4, 4, 'nearest')",
|
||||
Fields(w, h, 0d), NoStringParams, () => pixels, w, h, 5000, NoResolver, NoLoadFigure, NoLoadText, NoLoadImage, NoLoadMovie, NoAddEffect, NoAddDraw, NoSetAnchor,
|
||||
out _, out _, out _, out _, out _, out string? error);
|
||||
|
||||
Assert.True(ok, error);
|
||||
Assert.Equal(0, processor.ResizeCalls);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void PixelProcess_ForcedFastFill_BelowThresholdUsesHostProcessor()
|
||||
{
|
||||
Assert.True(LuaJitWorker.IsAvailable(NativeDir), "native/luajit.exe must be present");
|
||||
|
||||
const int w = 64, h = 64;
|
||||
var pixels = new byte[w * h * 4];
|
||||
var processor = new RecordingPixelProcessor { FillResult = true };
|
||||
_pixelProcessor = processor;
|
||||
|
||||
bool ok = RunWorker(
|
||||
"__fast_fill(10, 20, 30, 40)",
|
||||
Fields(w, h, 0d), NoStringParams, () => pixels, w, h, 5000, NoResolver, NoLoadFigure, NoLoadText, NoLoadImage, NoLoadMovie, NoAddEffect, NoAddDraw, NoSetAnchor,
|
||||
out _, out _, out _, out _, out _, out string? error);
|
||||
|
||||
Assert.True(ok, error);
|
||||
Assert.Equal(1, processor.FillCalls);
|
||||
Assert.True(processor.LastFillForce);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void PixelProcess_ForcedFastConvolve_BelowThresholdUsesHostProcessor()
|
||||
{
|
||||
Assert.True(LuaJitWorker.IsAvailable(NativeDir), "native/luajit.exe must be present");
|
||||
|
||||
const int w = 8, h = 8;
|
||||
var pixels = new byte[w * h * 4];
|
||||
var processor = new RecordingPixelProcessor { ConvolveResult = true };
|
||||
_pixelProcessor = processor;
|
||||
|
||||
bool ok = RunWorker(
|
||||
"__fast_convolve({1, 1, 1, 1, 1, 1, 1, 1, 1}, 3)",
|
||||
Fields(w, h, 0d), NoStringParams, () => pixels, w, h, 5000, NoResolver, NoLoadFigure, NoLoadText, NoLoadImage, NoLoadMovie, NoAddEffect, NoAddDraw, NoSetAnchor,
|
||||
out _, out _, out _, out _, out _, out string? error);
|
||||
|
||||
Assert.True(ok, error);
|
||||
Assert.Equal(1, processor.ConvolveCalls);
|
||||
Assert.True(processor.LastConvolveForce);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void PixelProcess_ForcedFastResize_BelowThresholdUsesHostProcessor()
|
||||
{
|
||||
Assert.True(LuaJitWorker.IsAvailable(NativeDir), "native/luajit.exe must be present");
|
||||
|
||||
const int w = 2, h = 2;
|
||||
var pixels = new byte[w * h * 4];
|
||||
var processor = new RecordingPixelProcessor { ResizeResult = true };
|
||||
_pixelProcessor = processor;
|
||||
|
||||
bool ok = RunWorker(
|
||||
"__fast_resize(4, 4, 'nearest')",
|
||||
Fields(w, h, 0d), NoStringParams, () => pixels, w, h, 5000, NoResolver, NoLoadFigure, NoLoadText, NoLoadImage, NoLoadMovie, NoAddEffect, NoAddDraw, NoSetAnchor,
|
||||
out _, out _, out _, out _, out _, out string? error);
|
||||
|
||||
Assert.True(ok, error);
|
||||
Assert.Equal(1, processor.ResizeCalls);
|
||||
Assert.True(processor.LastResizeForce);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void HostCallbackTime_DoesNotConsumeScriptTimeout()
|
||||
{
|
||||
Assert.True(LuaJitWorker.IsAvailable(NativeDir), "native/luajit.exe must be present");
|
||||
|
||||
var decoded = new byte[4];
|
||||
Func<string, (byte[], int, int)> slowLoadImage = _ =>
|
||||
{
|
||||
System.Threading.Thread.Sleep(1500);
|
||||
return (decoded, 1, 1);
|
||||
};
|
||||
|
||||
var pixels = new byte[2 * 2 * 4];
|
||||
var fields = Fields(2, 2, 0d);
|
||||
|
||||
bool ok = RunWorker(
|
||||
"obj.load('image', 'C:/sample.png') obj.x = 5",
|
||||
fields, NoStringParams, () => pixels, 2, 2, 1000, NoResolver, NoLoadFigure, NoLoadText, slowLoadImage, NoLoadMovie, NoAddEffect, NoAddDraw, NoSetAnchor,
|
||||
out _, out _, out _, out _, out _, out string? error);
|
||||
|
||||
Assert.True(ok, error);
|
||||
Assert.Equal(5d, fields[NativeProtocol.X]);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Fill_WritesPremultipliedColor()
|
||||
{
|
||||
Assert.True(LuaJitWorker.IsAvailable(NativeDir), "native/luajit.exe must be present");
|
||||
|
||||
const int w = 2, h = 2;
|
||||
var pixels = new byte[w * h * 4];
|
||||
var fields = Fields(w, h, 0d);
|
||||
|
||||
bool ok = RunWorker(
|
||||
"obj.fill(200, 100, 50, 255)",
|
||||
fields, NoStringParams, () => pixels, w, h, 5000, NoResolver, NoLoadFigure, NoLoadText, NoLoadImage, NoLoadMovie, NoAddEffect, NoAddDraw, NoSetAnchor,
|
||||
out bool dirty, out _, out _, out _, out _, out string? error);
|
||||
|
||||
Assert.True(ok, error);
|
||||
Assert.True(dirty);
|
||||
for (int i = 0; i < w * h; i++)
|
||||
{
|
||||
Assert.Equal(50, pixels[i * 4 + 0]);
|
||||
Assert.Equal(100, pixels[i * 4 + 1]);
|
||||
Assert.Equal(200, pixels[i * 4 + 2]);
|
||||
Assert.Equal(255, pixels[i * 4 + 3]);
|
||||
}
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Fill_Rectangle_TouchesOnlyRequestedPixels()
|
||||
{
|
||||
Assert.True(LuaJitWorker.IsAvailable(NativeDir), "native/luajit.exe must be present");
|
||||
|
||||
const int w = 3, h = 1;
|
||||
var pixels = new byte[w * h * 4];
|
||||
var fields = Fields(w, h, 0d);
|
||||
|
||||
bool ok = RunWorker(
|
||||
"obj.fill(255, 255, 255, 255, 1, 0, 1, 1)",
|
||||
fields, NoStringParams, () => pixels, w, h, 5000, NoResolver, NoLoadFigure, NoLoadText, NoLoadImage, NoLoadMovie, NoAddEffect, NoAddDraw, NoSetAnchor,
|
||||
out bool dirty, out _, out _, out _, out _, out string? error);
|
||||
|
||||
Assert.True(ok, error);
|
||||
Assert.True(dirty);
|
||||
Assert.Equal(new byte[] { 0, 0, 0, 0 }, pixels.AsSpan(0, 4).ToArray());
|
||||
Assert.Equal(new byte[] { 255, 255, 255, 255 }, pixels.AsSpan(4, 4).ToArray());
|
||||
Assert.Equal(new byte[] { 0, 0, 0, 0 }, pixels.AsSpan(8, 4).ToArray());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void GetPixelRegion_ReturnsStraightRgba()
|
||||
{
|
||||
Assert.True(LuaJitWorker.IsAvailable(NativeDir), "native/luajit.exe must be present");
|
||||
|
||||
var pixels = new byte[] { 50, 100, 200, 255 };
|
||||
var fields = Fields(1, 1, 0d);
|
||||
|
||||
bool ok = RunWorker(
|
||||
"local t = obj.getpixelregion(0, 0, 1, 1) obj.x = t[1] obj.y = t[2] obj.z = t[3] obj.alpha = t[4]",
|
||||
fields, NoStringParams, () => pixels, 1, 1, 5000, NoResolver, NoLoadFigure, NoLoadText, NoLoadImage, NoLoadMovie, NoAddEffect, NoAddDraw, NoSetAnchor,
|
||||
out _, out _, out _, out _, out _, out string? error);
|
||||
|
||||
Assert.True(ok, error);
|
||||
Assert.Equal(200d, fields[NativeProtocol.X]);
|
||||
Assert.Equal(100d, fields[NativeProtocol.Y]);
|
||||
Assert.Equal(50d, fields[NativeProtocol.Z]);
|
||||
Assert.Equal(255d, fields[NativeProtocol.Alpha]);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void PutPixelRegion_WritesPremultipliedColor()
|
||||
{
|
||||
Assert.True(LuaJitWorker.IsAvailable(NativeDir), "native/luajit.exe must be present");
|
||||
|
||||
const int w = 2, h = 1;
|
||||
var pixels = new byte[w * h * 4];
|
||||
var fields = Fields(w, h, 0d);
|
||||
|
||||
bool ok = RunWorker(
|
||||
"obj.putpixelregion(0, 0, 2, 1, {200, 100, 50, 255, 10, 20, 30, 255})",
|
||||
fields, NoStringParams, () => pixels, w, h, 5000, NoResolver, NoLoadFigure, NoLoadText, NoLoadImage, NoLoadMovie, NoAddEffect, NoAddDraw, NoSetAnchor,
|
||||
out bool dirty, out _, out _, out _, out _, out string? error);
|
||||
|
||||
Assert.True(ok, error);
|
||||
Assert.True(dirty);
|
||||
Assert.Equal(new byte[] { 50, 100, 200, 255 }, pixels.AsSpan(0, 4).ToArray());
|
||||
Assert.Equal(new byte[] { 30, 20, 10, 255 }, pixels.AsSpan(4, 4).ToArray());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void RegionRoundTrip_PreservesOpaquePixels()
|
||||
{
|
||||
Assert.True(LuaJitWorker.IsAvailable(NativeDir), "native/luajit.exe must be present");
|
||||
|
||||
const int w = 2, h = 2;
|
||||
var pixels = new byte[]
|
||||
{
|
||||
10, 20, 30, 255, 40, 50, 60, 255,
|
||||
70, 80, 90, 255, 100, 110, 120, 255,
|
||||
};
|
||||
var original = (byte[])pixels.Clone();
|
||||
var fields = Fields(w, h, 0d);
|
||||
|
||||
bool ok = RunWorker(
|
||||
"local t = obj.getpixelregion(0, 0, obj.w, obj.h) obj.fill(0, 0, 0, 0) obj.putpixelregion(0, 0, obj.w, obj.h, t)",
|
||||
fields, NoStringParams, () => pixels, w, h, 5000, NoResolver, NoLoadFigure, NoLoadText, NoLoadImage, NoLoadMovie, NoAddEffect, NoAddDraw, NoSetAnchor,
|
||||
out bool dirty, out _, out _, out _, out _, out string? error);
|
||||
|
||||
Assert.True(ok, error);
|
||||
Assert.True(dirty);
|
||||
Assert.Equal(original, pixels);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Convolve_Identity_LeavesOpaqueBufferUnchanged()
|
||||
{
|
||||
Assert.True(LuaJitWorker.IsAvailable(NativeDir), "native/luajit.exe must be present");
|
||||
|
||||
const int w = 2, h = 2;
|
||||
var pixels = new byte[]
|
||||
{
|
||||
10, 20, 30, 255, 40, 50, 60, 255,
|
||||
70, 80, 90, 255, 100, 110, 120, 255,
|
||||
};
|
||||
var original = (byte[])pixels.Clone();
|
||||
var fields = Fields(w, h, 0d);
|
||||
|
||||
bool ok = RunWorker(
|
||||
"obj.convolve({0, 0, 0, 0, 1, 0, 0, 0, 0}, 3)",
|
||||
fields, NoStringParams, () => pixels, w, h, 5000, NoResolver, NoLoadFigure, NoLoadText, NoLoadImage, NoLoadMovie, NoAddEffect, NoAddDraw, NoSetAnchor,
|
||||
out bool dirty, out _, out _, out _, out _, out string? error);
|
||||
|
||||
Assert.True(ok, error);
|
||||
Assert.True(dirty);
|
||||
Assert.Equal(original, pixels);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Convolve_BoxBlur_AveragesHorizontalStep()
|
||||
{
|
||||
Assert.True(LuaJitWorker.IsAvailable(NativeDir), "native/luajit.exe must be present");
|
||||
|
||||
const int w = 2, h = 1;
|
||||
var pixels = new byte[] { 0, 0, 0, 255, 255, 255, 255, 255 };
|
||||
var fields = Fields(w, h, 0d);
|
||||
|
||||
bool ok = RunWorker(
|
||||
"obj.convolve({1, 1, 1, 1, 1, 1, 1, 1, 1}, 3)",
|
||||
fields, NoStringParams, () => pixels, w, h, 5000, NoResolver, NoLoadFigure, NoLoadText, NoLoadImage, NoLoadMovie, NoAddEffect, NoAddDraw, NoSetAnchor,
|
||||
out bool dirty, out _, out _, out _, out _, out string? error);
|
||||
|
||||
Assert.True(ok, error);
|
||||
Assert.True(dirty);
|
||||
Assert.Equal(85, pixels[0]);
|
||||
Assert.Equal(85, pixels[1]);
|
||||
Assert.Equal(85, pixels[2]);
|
||||
Assert.Equal(255, pixels[3]);
|
||||
Assert.Equal(170, pixels[6]);
|
||||
Assert.Equal(255, pixels[7]);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Resize_Nearest_ReplicatesBlocks()
|
||||
{
|
||||
Assert.True(LuaJitWorker.IsAvailable(NativeDir), "native/luajit.exe must be present");
|
||||
|
||||
const int w = 2, h = 2;
|
||||
var pixels = new byte[]
|
||||
{
|
||||
13, 12, 13, 255, 23, 22, 23, 255,
|
||||
33, 32, 33, 255, 43, 42, 43, 255,
|
||||
};
|
||||
var fields = Fields(w, h, 0d);
|
||||
|
||||
bool ok = RunWorker(
|
||||
"obj.resize(4, 4, 'nearest')",
|
||||
fields, NoStringParams, () => pixels, w, h, 5000, NoResolver, NoLoadFigure, NoLoadText, NoLoadImage, NoLoadMovie, NoAddEffect, NoAddDraw, NoSetAnchor,
|
||||
out bool dirty, out bool bufferReplaced, out byte[]? result, out int rw, out int rh, out string? error);
|
||||
|
||||
Assert.True(ok, error);
|
||||
Assert.True(dirty);
|
||||
Assert.True(bufferReplaced);
|
||||
Assert.Equal(4, rw);
|
||||
Assert.Equal(4, rh);
|
||||
Assert.NotNull(result);
|
||||
byte SampleR(int x, int y) => result![(y * 4 + x) * 4 + 2];
|
||||
Assert.Equal(13, SampleR(0, 0));
|
||||
Assert.Equal(13, SampleR(1, 1));
|
||||
Assert.Equal(23, SampleR(2, 0));
|
||||
Assert.Equal(33, SampleR(0, 2));
|
||||
Assert.Equal(43, SampleR(3, 3));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Resize_UpdatesObjDimensions()
|
||||
{
|
||||
Assert.True(LuaJitWorker.IsAvailable(NativeDir), "native/luajit.exe must be present");
|
||||
|
||||
var pixels = new byte[4 * 4 * 4];
|
||||
var fields = Fields(4, 4, 0d);
|
||||
|
||||
bool ok = RunWorker(
|
||||
"obj.resize(8, 2) obj.x = obj.w obj.y = obj.h obj.z = obj.diagonal",
|
||||
fields, NoStringParams, () => pixels, 4, 4, 5000, NoResolver, NoLoadFigure, NoLoadText, NoLoadImage, NoLoadMovie, NoAddEffect, NoAddDraw, NoSetAnchor,
|
||||
out _, out bool bufferReplaced, out _, out int rw, out int rh, out string? error);
|
||||
|
||||
Assert.True(ok, error);
|
||||
Assert.True(bufferReplaced);
|
||||
Assert.Equal(8, rw);
|
||||
Assert.Equal(2, rh);
|
||||
Assert.Equal(8d, fields[NativeProtocol.X]);
|
||||
Assert.Equal(2d, fields[NativeProtocol.Y]);
|
||||
Assert.Equal(Math.Sqrt(8d * 8d + 2d * 2d), fields[NativeProtocol.Z]);
|
||||
}
|
||||
|
||||
private sealed class RecordingPixelProcessor : IPixelBufferProcessor
|
||||
{
|
||||
public bool FillResult { get; init; }
|
||||
public bool ConvolveResult { get; init; }
|
||||
public bool ResizeResult { get; init; }
|
||||
public int FillCalls { get; private set; }
|
||||
public int ConvolveCalls { get; private set; }
|
||||
public int ResizeCalls { get; private set; }
|
||||
public int Size { get; private set; }
|
||||
public double Divisor { get; private set; }
|
||||
public double Offset { get; private set; }
|
||||
public double[] Kernel { get; private set; } = [];
|
||||
public int TargetWidth { get; private set; }
|
||||
public int TargetHeight { get; private set; }
|
||||
public bool Linear { get; private set; }
|
||||
public bool LastFillForce { get; private set; }
|
||||
public bool LastConvolveForce { get; private set; }
|
||||
public bool LastResizeForce { get; private set; }
|
||||
|
||||
public bool TryFill(byte[] target, int width, int height, double r, double g, double b, double a, int x, int y, int fillWidth, int fillHeight, bool force = false)
|
||||
{
|
||||
FillCalls++;
|
||||
LastFillForce = force;
|
||||
if (!FillResult)
|
||||
return false;
|
||||
Array.Fill(target, (byte)0x41, 0, width * height * 4);
|
||||
return true;
|
||||
}
|
||||
|
||||
public bool TryConvolve(byte[] target, int width, int height, double[] kernel, int size, double divisor, double offset, bool force = false)
|
||||
{
|
||||
ConvolveCalls++;
|
||||
Size = size;
|
||||
Divisor = divisor;
|
||||
Offset = offset;
|
||||
Kernel = kernel.AsSpan(0, size * size).ToArray();
|
||||
LastConvolveForce = force;
|
||||
if (!ConvolveResult)
|
||||
return false;
|
||||
Array.Fill(target, (byte)0x42, 0, width * height * 4);
|
||||
return true;
|
||||
}
|
||||
|
||||
public bool TryResize(byte[] source, int sourceWidth, int sourceHeight, int targetWidth, int targetHeight, bool linear, out byte[]? target, bool force = false)
|
||||
{
|
||||
ResizeCalls++;
|
||||
TargetWidth = targetWidth;
|
||||
TargetHeight = targetHeight;
|
||||
Linear = linear;
|
||||
LastResizeForce = force;
|
||||
target = null;
|
||||
if (!ResizeResult)
|
||||
return false;
|
||||
target = new byte[targetWidth * targetHeight * 4];
|
||||
Array.Fill(target, (byte)0x43);
|
||||
return true;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -16,6 +16,9 @@
|
||||
<Project Path="LuaScript.Runtime/LuaScript.Runtime.csproj">
|
||||
<Platform Solution="*|x64" Project="Any CPU" />
|
||||
</Project>
|
||||
<Project Path="LuaScript.Gpu/LuaScript.Gpu.csproj">
|
||||
<Platform Solution="*|x64" Project="Any CPU" />
|
||||
</Project>
|
||||
<Project Path="LuaScript.Tests/LuaScript.Tests.csproj" />
|
||||
<Project Path="LuaScript/LuaScript.csproj">
|
||||
<Platform Solution="*|x64" Project="x64" />
|
||||
|
||||
@@ -0,0 +1,201 @@
|
||||
using System.Runtime.CompilerServices;
|
||||
using LuaScript.Compat;
|
||||
using YukkuriMovieMaker.ItemEditor;
|
||||
using YukkuriMovieMaker.Player.Audio.Effects;
|
||||
using YukkuriMovieMaker.Plugin;
|
||||
using YukkuriMovieMaker.Plugin.FileSource;
|
||||
using YukkuriMovieMaker.Project;
|
||||
using YukkuriMovieMaker.Project.Items;
|
||||
|
||||
namespace LuaScript
|
||||
{
|
||||
internal sealed class AudioSampleProvider : IDisposable
|
||||
{
|
||||
private readonly AviUtlAudioConverter _converter = new();
|
||||
private readonly double[] _data = new double[AviUtlAudioConverter.MaxSamples];
|
||||
private float[] _readBuffer = [];
|
||||
|
||||
private IAudioFileSource? _fileSource;
|
||||
private string _fileSourcePath = string.Empty;
|
||||
|
||||
private IAudioStream? _sceneSource;
|
||||
private Scene? _sceneSourceScene;
|
||||
|
||||
private IAudioStream? _itemSource;
|
||||
private IAudioItem? _itemSourceItem;
|
||||
private Scene? _itemSourceScene;
|
||||
private string? _itemSourceFile;
|
||||
|
||||
public double[] Data => _data;
|
||||
|
||||
public (int Count, int Rate) ReadFile(string path, double time, string type, int size)
|
||||
{
|
||||
try
|
||||
{
|
||||
if (_fileSource is null || !string.Equals(path, _fileSourcePath, StringComparison.Ordinal))
|
||||
{
|
||||
_fileSource?.Dispose();
|
||||
_fileSource = null;
|
||||
_fileSource = AudioFileSourceFactory.Create(path, 0);
|
||||
_fileSourcePath = path;
|
||||
}
|
||||
|
||||
var source = _fileSource;
|
||||
if (source is null || source.Hz <= 0)
|
||||
return (0, 0);
|
||||
|
||||
int floats = EnsureReadBuffer(type, size);
|
||||
if (floats <= 0)
|
||||
return (0, source.Hz);
|
||||
|
||||
source.Seek(TimeSpan.FromSeconds(Math.Max(0d, time)));
|
||||
int total = 0;
|
||||
while (total < floats)
|
||||
{
|
||||
int read = source.Read(_readBuffer, total, floats - total);
|
||||
if (read <= 0)
|
||||
break;
|
||||
total += read;
|
||||
}
|
||||
|
||||
return (_converter.Convert(type, _readBuffer, total / 2, size, _data), source.Hz);
|
||||
}
|
||||
catch
|
||||
{
|
||||
return (0, 0);
|
||||
}
|
||||
}
|
||||
|
||||
public (int Count, int Rate) ReadScene(Scene? scene, double time, string type, int size)
|
||||
{
|
||||
try
|
||||
{
|
||||
if (scene is null)
|
||||
return (0, 0);
|
||||
|
||||
if (_sceneSource is null || !ReferenceEquals(scene, _sceneSourceScene))
|
||||
{
|
||||
_sceneSource?.Dispose();
|
||||
_sceneSource = null;
|
||||
scene.TryCreateAudioSource(out _sceneSource);
|
||||
_sceneSourceScene = scene;
|
||||
}
|
||||
|
||||
return ReadStream(_sceneSource, time, type, size);
|
||||
}
|
||||
catch
|
||||
{
|
||||
return (0, 0);
|
||||
}
|
||||
}
|
||||
|
||||
public (int Count, int Rate) ReadItem(IAudioItem? item, Scene? scene, double time, string type, int size)
|
||||
{
|
||||
try
|
||||
{
|
||||
if (item is null || scene is null)
|
||||
return (0, 0);
|
||||
|
||||
string? file = item switch
|
||||
{
|
||||
AudioItem audio => audio.FilePath,
|
||||
VideoItem video => video.FilePath,
|
||||
_ => null,
|
||||
};
|
||||
if (_itemSource is null ||
|
||||
!ReferenceEquals(item, _itemSourceItem) ||
|
||||
!ReferenceEquals(scene, _itemSourceScene) ||
|
||||
!string.Equals(file, _itemSourceFile, StringComparison.Ordinal))
|
||||
{
|
||||
_itemSource?.Dispose();
|
||||
_itemSource = null;
|
||||
_itemSource = CreateItemSource(item, scene) ?? CreateRawItemSource(item, scene);
|
||||
_itemSourceItem = item;
|
||||
_itemSourceScene = scene;
|
||||
_itemSourceFile = file;
|
||||
}
|
||||
|
||||
return ReadStream(_itemSource, time, type, size);
|
||||
}
|
||||
catch
|
||||
{
|
||||
return (0, 0);
|
||||
}
|
||||
}
|
||||
|
||||
private (int Count, int Rate) ReadStream(IAudioStream? source, double time, string type, int size)
|
||||
{
|
||||
if (source is null || source.Hz <= 0)
|
||||
return (0, 0);
|
||||
|
||||
int floats = EnsureReadBuffer(type, size);
|
||||
if (floats <= 0)
|
||||
return (0, source.Hz);
|
||||
|
||||
source.Seek(TimeSpan.FromSeconds(Math.Max(0d, time)));
|
||||
int total = 0;
|
||||
while (total < floats)
|
||||
{
|
||||
int read = source.Read(_readBuffer, total, floats - total);
|
||||
if (read <= 0)
|
||||
break;
|
||||
total += read;
|
||||
}
|
||||
|
||||
return (_converter.Convert(type, _readBuffer, total / 2, size, _data), source.Hz);
|
||||
}
|
||||
|
||||
private int EnsureReadBuffer(string type, int size)
|
||||
{
|
||||
int frames = AviUtlAudioConverter.RequiredFrames(type, size);
|
||||
if (frames <= 0)
|
||||
return 0;
|
||||
int floats = frames * 2;
|
||||
if (_readBuffer.Length < floats)
|
||||
_readBuffer = new float[floats];
|
||||
return floats;
|
||||
}
|
||||
|
||||
private static IAudioStream? CreateItemSource(IAudioItem item, Scene scene)
|
||||
{
|
||||
try
|
||||
{
|
||||
return CreateEditorItemSource(item, scene);
|
||||
}
|
||||
catch
|
||||
{
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
[MethodImpl(MethodImplOptions.NoInlining)]
|
||||
private static IAudioStream CreateEditorItemSource(IAudioItem item, Scene scene) =>
|
||||
new EffectedItemSourceForEditorInfo(item, item.AudioEffects, scene);
|
||||
|
||||
private static IAudioStream? CreateRawItemSource(IAudioItem item, Scene scene)
|
||||
{
|
||||
try
|
||||
{
|
||||
return item.CreateAudioSource(scene);
|
||||
}
|
||||
catch
|
||||
{
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
public void Dispose()
|
||||
{
|
||||
_fileSource?.Dispose();
|
||||
_fileSource = null;
|
||||
_sceneSource?.Dispose();
|
||||
_sceneSource = null;
|
||||
_sceneSourceScene = null;
|
||||
_itemSource?.Dispose();
|
||||
_itemSource = null;
|
||||
_itemSourceItem = null;
|
||||
_itemSourceScene = null;
|
||||
_itemSourceFile = null;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,118 @@
|
||||
using YukkuriMovieMaker.Commons;
|
||||
using YukkuriMovieMaker.Player.Video;
|
||||
using YukkuriMovieMaker.Plugin.Brush;
|
||||
|
||||
namespace LuaScript
|
||||
{
|
||||
internal sealed class BrushImageRenderer(IGraphicsDevicesAndContext devices) : IDisposable
|
||||
{
|
||||
private const int MaxDimension = 8192;
|
||||
|
||||
private sealed class Entry(IBrushParameter parameter, IBrushSource source)
|
||||
{
|
||||
public IBrushParameter Parameter { get; } = parameter;
|
||||
public IBrushSource Source { get; } = source;
|
||||
public string[] AppliedKeys { get; set; } = [];
|
||||
}
|
||||
|
||||
private readonly Dictionary<string, Entry?> _sources = new(StringComparer.Ordinal);
|
||||
private GraphicsDevicesAndContext? _ctx;
|
||||
private PixelBufferManager? _pixels;
|
||||
|
||||
public bool TryRender(
|
||||
TimelineItemSourceDescription desc,
|
||||
string name,
|
||||
int width,
|
||||
int height,
|
||||
IReadOnlyList<KeyValuePair<string, object>> arguments,
|
||||
out byte[] pixels,
|
||||
out int outWidth,
|
||||
out int outHeight)
|
||||
{
|
||||
pixels = [];
|
||||
outWidth = 0;
|
||||
outHeight = 0;
|
||||
|
||||
if (width <= 0 || height <= 0 || width > MaxDimension || height > MaxDimension)
|
||||
return false;
|
||||
|
||||
if (!_sources.TryGetValue(name, out var entry))
|
||||
{
|
||||
entry = CreateEntry(name);
|
||||
_sources[name] = entry;
|
||||
}
|
||||
if (entry is null)
|
||||
return false;
|
||||
|
||||
if (!KeysMatch(entry.AppliedKeys, arguments))
|
||||
{
|
||||
entry.Source.Dispose();
|
||||
entry = CreateEntry(name);
|
||||
_sources[name] = entry;
|
||||
if (entry is null)
|
||||
return false;
|
||||
}
|
||||
|
||||
try
|
||||
{
|
||||
if (arguments.Count > 0)
|
||||
{
|
||||
ParameterBinder.ApplyArguments(entry.Parameter, arguments);
|
||||
if (entry.AppliedKeys.Length != arguments.Count)
|
||||
entry.AppliedKeys = new string[arguments.Count];
|
||||
for (int i = 0; i < arguments.Count; i++)
|
||||
entry.AppliedKeys[i] = arguments[i].Key;
|
||||
}
|
||||
|
||||
entry.Source.Update(desc);
|
||||
_pixels ??= new PixelBufferManager(_ctx!);
|
||||
pixels = _pixels.LoadBrushPixels(entry.Source.Brush, width, height);
|
||||
}
|
||||
catch
|
||||
{
|
||||
_sources.Remove(name);
|
||||
entry.Source.Dispose();
|
||||
pixels = [];
|
||||
return false;
|
||||
}
|
||||
|
||||
outWidth = width;
|
||||
outHeight = height;
|
||||
return true;
|
||||
}
|
||||
|
||||
private static bool KeysMatch(string[] appliedKeys, IReadOnlyList<KeyValuePair<string, object>> arguments)
|
||||
{
|
||||
if (appliedKeys.Length != arguments.Count)
|
||||
return false;
|
||||
for (int i = 0; i < appliedKeys.Length; i++)
|
||||
{
|
||||
if (!string.Equals(appliedKeys[i], arguments[i].Key, StringComparison.Ordinal))
|
||||
return false;
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
private Entry? CreateEntry(string name)
|
||||
{
|
||||
foreach (var plugin in BrushFactory.Plugins)
|
||||
{
|
||||
if (!string.Equals(plugin.Name, name, StringComparison.Ordinal))
|
||||
continue;
|
||||
_ctx ??= new GraphicsDevicesAndContext(devices);
|
||||
var parameter = plugin.CreateBrushParameter();
|
||||
return new Entry(parameter, parameter.CreateBrush(_ctx));
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
public void Dispose()
|
||||
{
|
||||
foreach (var entry in _sources.Values)
|
||||
entry?.Source.Dispose();
|
||||
_sources.Clear();
|
||||
_pixels?.Dispose();
|
||||
_ctx?.Dispose();
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,139 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.ComponentModel.DataAnnotations;
|
||||
using System.Globalization;
|
||||
using System.Reflection;
|
||||
using System.Windows.Media;
|
||||
using LuaScript.Compat;
|
||||
using YukkuriMovieMaker.Commons;
|
||||
|
||||
namespace LuaScript
|
||||
{
|
||||
internal static class ParameterBinder
|
||||
{
|
||||
public static readonly AviUtlParameterMapping Identity = new(string.Empty, string.Empty, 1d, 0d);
|
||||
|
||||
private static readonly Dictionary<Type, Dictionary<string, PropertyInfo>> s_propertyCache = [];
|
||||
|
||||
public static string Normalize(string value) => value.Trim().ToLowerInvariant();
|
||||
|
||||
public static Dictionary<string, PropertyInfo> GetProperties(Type type)
|
||||
{
|
||||
lock (s_propertyCache)
|
||||
{
|
||||
if (s_propertyCache.TryGetValue(type, out var cached))
|
||||
return cached;
|
||||
}
|
||||
|
||||
var map = new Dictionary<string, PropertyInfo>(StringComparer.Ordinal);
|
||||
foreach (var property in type.GetProperties(BindingFlags.Public | BindingFlags.Instance))
|
||||
{
|
||||
if (property.GetIndexParameters().Length != 0)
|
||||
continue;
|
||||
bool usable = property.PropertyType == typeof(Animation) || property.GetSetMethod() is not null;
|
||||
if (!usable)
|
||||
continue;
|
||||
|
||||
map.TryAdd(Normalize(property.Name), property);
|
||||
try
|
||||
{
|
||||
var display = property.GetCustomAttribute<DisplayAttribute>()?.GetName();
|
||||
if (!string.IsNullOrWhiteSpace(display))
|
||||
map.TryAdd(Normalize(display), property);
|
||||
}
|
||||
catch
|
||||
{
|
||||
}
|
||||
}
|
||||
|
||||
lock (s_propertyCache)
|
||||
{
|
||||
s_propertyCache[type] = map;
|
||||
}
|
||||
return map;
|
||||
}
|
||||
|
||||
public static void ApplyArguments(object model, IReadOnlyList<KeyValuePair<string, object>> arguments)
|
||||
{
|
||||
if (arguments.Count == 0)
|
||||
return;
|
||||
|
||||
var properties = GetProperties(model.GetType());
|
||||
foreach (var (key, value) in arguments)
|
||||
{
|
||||
if (!properties.TryGetValue(Normalize(key), out var property))
|
||||
continue;
|
||||
try
|
||||
{
|
||||
SetValue(model, property, value, Identity);
|
||||
}
|
||||
catch
|
||||
{
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
public static void SetValue(object model, PropertyInfo property, object value, AviUtlParameterMapping parameter)
|
||||
{
|
||||
var type = property.PropertyType;
|
||||
|
||||
if (type == typeof(Animation))
|
||||
{
|
||||
if (property.GetValue(model) is Animation animation)
|
||||
animation.CopyFrom(new Animation(parameter.Transform(ToDouble(value))));
|
||||
return;
|
||||
}
|
||||
if (type == typeof(bool))
|
||||
{
|
||||
property.SetValue(model, ToBool(value));
|
||||
return;
|
||||
}
|
||||
if (type.IsEnum)
|
||||
{
|
||||
property.SetValue(model, ToEnum(type, value));
|
||||
return;
|
||||
}
|
||||
if (type == typeof(Color))
|
||||
{
|
||||
property.SetValue(model, ToColor(value));
|
||||
return;
|
||||
}
|
||||
if (type == typeof(double) || type == typeof(float) || type == typeof(int) || type == typeof(long) || type == typeof(short))
|
||||
{
|
||||
property.SetValue(model, Convert.ChangeType(parameter.Transform(ToDouble(value)), type, CultureInfo.InvariantCulture));
|
||||
return;
|
||||
}
|
||||
if (type == typeof(string))
|
||||
property.SetValue(model, value?.ToString());
|
||||
}
|
||||
|
||||
private static double ToDouble(object value) => value switch
|
||||
{
|
||||
double d => d,
|
||||
bool b => b ? 1d : 0d,
|
||||
string s => double.TryParse(s, NumberStyles.Float, CultureInfo.InvariantCulture, out var r) ? r : 0d,
|
||||
_ => 0d,
|
||||
};
|
||||
|
||||
private static bool ToBool(object value) => value switch
|
||||
{
|
||||
bool b => b,
|
||||
double d => d != 0d,
|
||||
string s => s.Equals("true", StringComparison.OrdinalIgnoreCase) || s == "1",
|
||||
_ => false,
|
||||
};
|
||||
|
||||
private static object ToEnum(Type type, object value)
|
||||
{
|
||||
if (value is string s && Enum.TryParse(type, s, true, out var parsed))
|
||||
return parsed;
|
||||
return Enum.ToObject(type, (int)ToDouble(value));
|
||||
}
|
||||
|
||||
private static Color ToColor(object value)
|
||||
{
|
||||
int rgb = (int)ToDouble(value);
|
||||
return Color.FromRgb((byte)((rgb >> 16) & 0xFF), (byte)((rgb >> 8) & 0xFF), (byte)(rgb & 0xFF));
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -32,7 +32,32 @@ namespace LuaScript
|
||||
{
|
||||
EnsureBitmaps(width, height);
|
||||
RenderToStaging(input, bounds);
|
||||
return ReadStagingPixels(width, height);
|
||||
}
|
||||
|
||||
public byte[] LoadBrushPixels(ID2D1Brush brush, int width, int height)
|
||||
{
|
||||
EnsureBitmaps(width, height);
|
||||
|
||||
var dc = _ctx.DeviceContext;
|
||||
var rt = (ID2D1RenderTarget)dc;
|
||||
using var savedTarget = dc.Target;
|
||||
|
||||
dc.Target = _renderTarget;
|
||||
dc.BeginDraw();
|
||||
dc.Clear(null);
|
||||
rt.Transform = Matrix3x2.CreateTranslation(width / 2f, height / 2f);
|
||||
rt.FillRectangle(new RawRectF(-width / 2f, -height / 2f, width / 2f, height / 2f), brush);
|
||||
rt.Transform = Matrix3x2.Identity;
|
||||
dc.EndDraw();
|
||||
dc.Target = savedTarget;
|
||||
|
||||
_stagingBitmap!.CopyFromBitmap(_renderTarget!);
|
||||
return ReadStagingPixels(width, height);
|
||||
}
|
||||
|
||||
private unsafe byte[] ReadStagingPixels(int width, int height)
|
||||
{
|
||||
var mapped = _stagingBitmap!.Map(MapOptions.Read);
|
||||
try
|
||||
{
|
||||
|
||||
@@ -1,9 +1,5 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.ComponentModel.DataAnnotations;
|
||||
using System.Globalization;
|
||||
using System.Reflection;
|
||||
using System.Windows.Media;
|
||||
using Vortice.Direct2D1;
|
||||
using YukkuriMovieMaker.Commons;
|
||||
using YukkuriMovieMaker.Player.Video;
|
||||
@@ -23,11 +19,8 @@ namespace LuaScript
|
||||
public required int RequestIndex;
|
||||
}
|
||||
|
||||
private static readonly AviUtlParameterMapping Identity = new(string.Empty, string.Empty, 1d, 0d);
|
||||
|
||||
private static Dictionary<string, Type>? _typeRegistry;
|
||||
private static Dictionary<string, Type>? _nameRegistry;
|
||||
private static readonly Dictionary<Type, Dictionary<string, PropertyInfo>> _propertyCache = [];
|
||||
|
||||
private readonly IGraphicsDevicesAndContext _devices;
|
||||
private readonly List<Node> _nodes = [];
|
||||
@@ -190,34 +183,29 @@ namespace LuaScript
|
||||
map.TryAdd(Normalize(key), type);
|
||||
}
|
||||
|
||||
private static string Normalize(string value) => value.Trim().ToLowerInvariant();
|
||||
private static string Normalize(string value) => ParameterBinder.Normalize(value);
|
||||
|
||||
private static void ApplyParameters(IVideoEffect model, AviUtlEffectMapping? mapping, IReadOnlyList<KeyValuePair<string, object>> arguments)
|
||||
{
|
||||
if (arguments.Count == 0)
|
||||
return;
|
||||
|
||||
var properties = GetProperties(model.GetType());
|
||||
if (mapping is null)
|
||||
{
|
||||
ParameterBinder.ApplyArguments(model, arguments);
|
||||
return;
|
||||
}
|
||||
|
||||
var properties = ParameterBinder.GetProperties(model.GetType());
|
||||
foreach (var (key, value) in arguments)
|
||||
{
|
||||
PropertyInfo? property;
|
||||
AviUtlParameterMapping parameter;
|
||||
if (mapping is not null)
|
||||
{
|
||||
if (!mapping.TryGetParameter(key, out parameter) ||
|
||||
!properties.TryGetValue(Normalize(parameter.Property), out property))
|
||||
continue;
|
||||
}
|
||||
else
|
||||
{
|
||||
if (!properties.TryGetValue(Normalize(key), out property))
|
||||
continue;
|
||||
parameter = Identity;
|
||||
}
|
||||
if (!mapping.TryGetParameter(key, out var parameter) ||
|
||||
!properties.TryGetValue(Normalize(parameter.Property), out var property))
|
||||
continue;
|
||||
|
||||
try
|
||||
{
|
||||
SetValue(model, property, value, parameter);
|
||||
ParameterBinder.SetValue(model, property, value, parameter);
|
||||
}
|
||||
catch
|
||||
{
|
||||
@@ -225,99 +213,6 @@ namespace LuaScript
|
||||
}
|
||||
}
|
||||
|
||||
private static Dictionary<string, PropertyInfo> GetProperties(Type type)
|
||||
{
|
||||
if (_propertyCache.TryGetValue(type, out var cached))
|
||||
return cached;
|
||||
|
||||
var map = new Dictionary<string, PropertyInfo>(StringComparer.Ordinal);
|
||||
foreach (var property in type.GetProperties(BindingFlags.Public | BindingFlags.Instance))
|
||||
{
|
||||
if (property.GetIndexParameters().Length != 0)
|
||||
continue;
|
||||
bool usable = property.PropertyType == typeof(Animation) || property.GetSetMethod() is not null;
|
||||
if (!usable)
|
||||
continue;
|
||||
|
||||
map.TryAdd(Normalize(property.Name), property);
|
||||
try
|
||||
{
|
||||
var display = property.GetCustomAttribute<DisplayAttribute>()?.GetName();
|
||||
if (!string.IsNullOrWhiteSpace(display))
|
||||
map.TryAdd(Normalize(display), property);
|
||||
}
|
||||
catch
|
||||
{
|
||||
}
|
||||
}
|
||||
|
||||
_propertyCache[type] = map;
|
||||
return map;
|
||||
}
|
||||
|
||||
private static void SetValue(IVideoEffect model, PropertyInfo property, object value, AviUtlParameterMapping parameter)
|
||||
{
|
||||
var type = property.PropertyType;
|
||||
|
||||
if (type == typeof(Animation))
|
||||
{
|
||||
if (property.GetValue(model) is Animation animation)
|
||||
animation.CopyFrom(new Animation(parameter.Transform(ToDouble(value))));
|
||||
return;
|
||||
}
|
||||
if (type == typeof(bool))
|
||||
{
|
||||
property.SetValue(model, ToBool(value));
|
||||
return;
|
||||
}
|
||||
if (type.IsEnum)
|
||||
{
|
||||
property.SetValue(model, ToEnum(type, value));
|
||||
return;
|
||||
}
|
||||
if (type == typeof(Color))
|
||||
{
|
||||
property.SetValue(model, ToColor(value));
|
||||
return;
|
||||
}
|
||||
if (type == typeof(double) || type == typeof(float) || type == typeof(int) || type == typeof(long) || type == typeof(short))
|
||||
{
|
||||
property.SetValue(model, Convert.ChangeType(parameter.Transform(ToDouble(value)), type, CultureInfo.InvariantCulture));
|
||||
return;
|
||||
}
|
||||
if (type == typeof(string))
|
||||
property.SetValue(model, value?.ToString());
|
||||
}
|
||||
|
||||
private static double ToDouble(object value) => value switch
|
||||
{
|
||||
double d => d,
|
||||
bool b => b ? 1d : 0d,
|
||||
string s => double.TryParse(s, NumberStyles.Float, CultureInfo.InvariantCulture, out var r) ? r : 0d,
|
||||
_ => 0d,
|
||||
};
|
||||
|
||||
private static bool ToBool(object value) => value switch
|
||||
{
|
||||
bool b => b,
|
||||
double d => d != 0d,
|
||||
string s => s.Equals("true", StringComparison.OrdinalIgnoreCase) || s == "1",
|
||||
_ => false,
|
||||
};
|
||||
|
||||
private static object ToEnum(Type type, object value)
|
||||
{
|
||||
if (value is string s && Enum.TryParse(type, s, true, out var parsed))
|
||||
return parsed;
|
||||
return Enum.ToObject(type, (int)ToDouble(value));
|
||||
}
|
||||
|
||||
private static Color ToColor(object value)
|
||||
{
|
||||
int rgb = (int)ToDouble(value);
|
||||
return Color.FromRgb((byte)((rgb >> 16) & 0xFF), (byte)((rgb >> 8) & 0xFF), (byte)(rgb & 0xFF));
|
||||
}
|
||||
|
||||
private void DisposeNodes()
|
||||
{
|
||||
foreach (var node in _nodes)
|
||||
|
||||
@@ -295,6 +295,35 @@ namespace LuaScript
|
||||
return Color.FromRgb(r, g, b);
|
||||
}
|
||||
|
||||
[Display(GroupName = nameof(Texts.AnchorGroup), Name = nameof(Texts.AnchorX), Description = nameof(Texts.AnchorDesc), ResourceType = typeof(Texts))]
|
||||
[TextBoxSlider("F1", "", -9999, 9999)]
|
||||
[ShowPropertyEditorWhen(nameof(IsAnchorSelected), true)]
|
||||
[JsonIgnore]
|
||||
public double AnchorX { get => _anchorX; set { if (Set(ref _anchorX, value) && !_anchorSyncing) ApplyAnchorEdit(); } }
|
||||
double _anchorX;
|
||||
|
||||
[Display(GroupName = nameof(Texts.AnchorGroup), Name = nameof(Texts.AnchorY), Description = nameof(Texts.AnchorDesc), ResourceType = typeof(Texts))]
|
||||
[TextBoxSlider("F1", "", -9999, 9999)]
|
||||
[ShowPropertyEditorWhen(nameof(IsAnchorSelected), true)]
|
||||
[JsonIgnore]
|
||||
public double AnchorY { get => _anchorY; set { if (Set(ref _anchorY, value) && !_anchorSyncing) ApplyAnchorEdit(); } }
|
||||
double _anchorY;
|
||||
|
||||
[Display(GroupName = nameof(Texts.AnchorGroup), Name = nameof(Texts.AnchorZ), Description = nameof(Texts.AnchorDesc), ResourceType = typeof(Texts))]
|
||||
[TextBoxSlider("F1", "", -9999, 9999)]
|
||||
[ShowPropertyEditorWhen(nameof(IsAnchorZVisible), true)]
|
||||
[JsonIgnore]
|
||||
public double AnchorZ { get => _anchorZ; set { if (Set(ref _anchorZ, value) && !_anchorSyncing) ApplyAnchorEdit(); } }
|
||||
double _anchorZ;
|
||||
|
||||
[JsonIgnore] public bool IsAnchorSelected { get => _isAnchorSelected; private set => Set(ref _isAnchorSelected, value); }
|
||||
[JsonIgnore] public bool IsAnchorZVisible { get => _isAnchorZVisible; private set => Set(ref _isAnchorZVisible, value); }
|
||||
bool _isAnchorSelected;
|
||||
bool _isAnchorZVisible;
|
||||
string _selectedAnchorGroup = string.Empty;
|
||||
int _selectedAnchorIndex;
|
||||
bool _anchorSyncing;
|
||||
|
||||
public ImmutableList<LuaAnchorPoint> Anchors
|
||||
{
|
||||
get => _anchors;
|
||||
@@ -306,7 +335,37 @@ namespace LuaScript
|
||||
internal int AnchorVersion { get; private set; }
|
||||
|
||||
internal void ApplyAnchorDrag(string group, int index, double dx, double dy, double dz)
|
||||
=> Anchors = AnchorSupport.ApplyDrag(Anchors, group, index, dx, dy, dz);
|
||||
{
|
||||
Anchors = AnchorSupport.ApplyDrag(Anchors, group, index, dx, dy, dz);
|
||||
if (IsAnchorSelected && index == _selectedAnchorIndex && group == _selectedAnchorGroup)
|
||||
RefreshSelectedAnchor();
|
||||
}
|
||||
|
||||
internal void BeginAnchorEdit(string group, int index, bool is3D)
|
||||
{
|
||||
_selectedAnchorGroup = group;
|
||||
_selectedAnchorIndex = index;
|
||||
RefreshSelectedAnchor();
|
||||
IsAnchorSelected = true;
|
||||
IsAnchorZVisible = is3D;
|
||||
}
|
||||
|
||||
private void RefreshSelectedAnchor()
|
||||
{
|
||||
AnchorSupport.ResolvePosition(_anchors, _selectedAnchorGroup, _selectedAnchorIndex, out double x, out double y, out double z);
|
||||
_anchorSyncing = true;
|
||||
AnchorX = x;
|
||||
AnchorY = y;
|
||||
AnchorZ = z;
|
||||
_anchorSyncing = false;
|
||||
}
|
||||
|
||||
private void ApplyAnchorEdit()
|
||||
{
|
||||
if (!IsAnchorSelected)
|
||||
return;
|
||||
Anchors = AnchorSupport.SetPosition(_anchors, _selectedAnchorGroup, _selectedAnchorIndex, _anchorX, _anchorY, _anchorZ);
|
||||
}
|
||||
|
||||
public override IEnumerable<string> CreateExoVideoFilters(int keyFrameIndex, ExoOutputDescription exoOutputDescription) => [];
|
||||
|
||||
|
||||
@@ -7,6 +7,7 @@ using LuaScript.Compat;
|
||||
using LuaScript.Diagnostics;
|
||||
using LuaScript.Engine;
|
||||
using LuaScript.Engine.Kernel;
|
||||
using LuaScript.Engine.Processing;
|
||||
using LuaScript.Engine.Shader;
|
||||
using Vortice;
|
||||
using Vortice.DCommon;
|
||||
@@ -138,6 +139,14 @@ namespace LuaScript
|
||||
private Func<string, string, double, bool, bool, int, (byte[] buffer, int w, int h)>? _nativeLoadText;
|
||||
private Func<string, (byte[] buffer, int w, int h)>? _nativeLoadImage;
|
||||
private Func<string, double, (byte[] buffer, int w, int h)>? _nativeLoadMovie;
|
||||
private Func<string, double, (byte[] Buffer, int Width, int Height)>? _loadSceneImage;
|
||||
private Func<string, double, double, IReadOnlyList<KeyValuePair<string, object>>, (byte[] Buffer, int Width, int Height)>? _loadBrushImage;
|
||||
private SceneImageRenderer? _sceneImageRenderer;
|
||||
private BrushImageRenderer? _brushImageRenderer;
|
||||
private bool _sceneImageLoaded;
|
||||
private Func<string, string, int, (int Count, int Rate, double[] Data)>? _loadAudio;
|
||||
private AudioSampleProvider? _audioProvider;
|
||||
private bool _audioLoaded;
|
||||
private Action<string, IReadOnlyList<KeyValuePair<string, object>>>? _nativeAddEffect;
|
||||
private Action<DrawCommand>? _nativeAddDraw;
|
||||
private Action<string, int, bool, int, double[]>? _nativeSetAnchor;
|
||||
@@ -150,6 +159,7 @@ namespace LuaScript
|
||||
private string _runnableScript = string.Empty;
|
||||
private int[] _runnableLineMap = [];
|
||||
private int[] _runnableChangedLines = [];
|
||||
private LuaScriptDiagnostic[] _runnableRewriteDiagnostics = [];
|
||||
private bool _runnableCached;
|
||||
private ID2D1Image? _cachedInput;
|
||||
private RenderKey _cachedKey;
|
||||
@@ -159,6 +169,7 @@ namespace LuaScript
|
||||
private ID2D1Image? _cachedEffectOutput;
|
||||
|
||||
private PixelShaderRunner? _pixelShaderRunner;
|
||||
private GpuPixelBufferProcessor? _pixelProcessor;
|
||||
private AviUtlPixelShaderLibrary _pixelShaderLibrary = AviUtlPixelShaderLibrary.Empty;
|
||||
private string? _pixelShaderSourceRef;
|
||||
|
||||
@@ -179,20 +190,38 @@ namespace LuaScript
|
||||
new SynchronizedCompositor(new HardwareCompositor(_ownCtx), _pixelLoaderSemaphore),
|
||||
SoftwareCompositor.Instance,
|
||||
WarnBufferCompositorDegraded);
|
||||
_pixelShaderRunner = new PixelShaderRunner { Compositor = _bufferCompositor };
|
||||
_pixelShaderRunner = new PixelShaderRunner { Compositor = _bufferCompositor, Logger = WriteGpuLog };
|
||||
_pixelProcessor = new GpuPixelBufferProcessor(_pixelShaderRunner);
|
||||
_context.ResolverProvider = GetFrameResolver;
|
||||
_context.Compositor = _bufferCompositor;
|
||||
_context.PixelProcessor = _pixelProcessor;
|
||||
_context.SceneImageLoader = _loadSceneImage ??= LoadSceneImage;
|
||||
_context.BrushImageLoader = _loadBrushImage ??= LoadBrushImage;
|
||||
_context.AudioLoader = _loadAudio ??= LoadAudio;
|
||||
return null;
|
||||
}
|
||||
|
||||
private static void WarnBufferCompositorDegraded(Exception ex) =>
|
||||
Log.Default.Write("LuaScript: hardware buffer compositing failed; falling back to the software compositor.", ex);
|
||||
|
||||
private static void WriteGpuLog(string message, Exception? exception)
|
||||
{
|
||||
if (exception is null)
|
||||
Log.Default.Write(message);
|
||||
else
|
||||
Log.Default.Write(message, exception);
|
||||
}
|
||||
|
||||
private AviUtlScriptContext CreateScriptContext()
|
||||
{
|
||||
var context = new AviUtlScriptContext { ResolverProvider = GetFrameResolver };
|
||||
if (_bufferCompositor is not null)
|
||||
context.Compositor = _bufferCompositor;
|
||||
if (_pixelProcessor is not null)
|
||||
context.PixelProcessor = _pixelProcessor;
|
||||
context.SceneImageLoader = _loadSceneImage ??= LoadSceneImage;
|
||||
context.BrushImageLoader = _loadBrushImage ??= LoadBrushImage;
|
||||
context.AudioLoader = _loadAudio ??= LoadAudio;
|
||||
return context;
|
||||
}
|
||||
|
||||
@@ -219,18 +248,30 @@ namespace LuaScript
|
||||
|
||||
private string GetRunnableScript(string source)
|
||||
{
|
||||
if (_runnableCached && string.Equals(source, _sourceScript, StringComparison.Ordinal))
|
||||
if (_runnableCached && ReferenceEquals(source, _sourceScript))
|
||||
return _runnableScript;
|
||||
|
||||
var (code, lineMap, changedLines) = AviUtlScript.TransformWithMap(source);
|
||||
var (code, lineMap, changedLines, rewriteDiagnostics) = AviUtlScript.TransformWithMap(source);
|
||||
_runnableScript = code;
|
||||
_runnableLineMap = lineMap;
|
||||
_runnableChangedLines = changedLines;
|
||||
_sourceScript = source;
|
||||
_runnableCached = true;
|
||||
_runnableRewriteDiagnostics = BuildRewriteDiagnostics(rewriteDiagnostics);
|
||||
return _runnableScript;
|
||||
}
|
||||
|
||||
private LuaScriptDiagnostic[] BuildRewriteDiagnostics(LuaScript.Compat.Syntax.LuaRewriteDiagnostic[] source)
|
||||
{
|
||||
if (source.Length == 0)
|
||||
return [];
|
||||
|
||||
var diagnostics = new LuaScriptDiagnostic[source.Length];
|
||||
for (int i = 0; i < source.Length; i++)
|
||||
diagnostics[i] = new LuaScriptDiagnostic(LuaScriptDiagnosticKind.Compile, MapRunnableLine(source[i].Line), 0, 0, source[i].Message);
|
||||
return diagnostics;
|
||||
}
|
||||
|
||||
private AviUtlPixelShaderLibrary GetPixelShaderLibrary(string source)
|
||||
{
|
||||
if (!ReferenceEquals(_pixelShaderSourceRef, source))
|
||||
@@ -466,23 +507,47 @@ namespace LuaScript
|
||||
_pixelLoaderSemaphore.Release();
|
||||
}
|
||||
|
||||
LuaScriptDiagnostics.Instance.Report(script, diagnostics);
|
||||
LuaScriptDiagnostics.Instance.Report(script, _runnableRewriteDiagnostics.Length == 0
|
||||
? diagnostics
|
||||
: [.. _runnableRewriteDiagnostics, .. diagnostics]);
|
||||
|
||||
_isFirst = false;
|
||||
if (_sceneImageLoaded)
|
||||
{
|
||||
_sceneImageLoaded = false;
|
||||
_isFirst = true;
|
||||
}
|
||||
if (_audioLoaded)
|
||||
{
|
||||
_audioLoaded = false;
|
||||
_isFirst = true;
|
||||
}
|
||||
_cachedKey = key;
|
||||
_cachedQueries = ctx.ObjectQueries.Count == 0 ? [] : [.. ctx.ObjectQueries];
|
||||
_cachedSceneValueQueries = ctx.SceneValueQueries.Count == 0 ? [] : [.. ctx.SceneValueQueries];
|
||||
_cachedQueries = SnapshotQueries(ctx.ObjectQueries, _cachedQueries);
|
||||
_cachedSceneValueQueries = SnapshotQueries(ctx.SceneValueQueries, _cachedSceneValueQueries);
|
||||
_cachedOutputDesc = outDesc;
|
||||
_cachedEffectOutput = effectOutput;
|
||||
|
||||
return outDesc;
|
||||
}
|
||||
|
||||
private string? _effectTargetSource;
|
||||
private AviUtlEngine _effectTarget;
|
||||
|
||||
private AviUtlEngine ResolveEffectTarget(string? script)
|
||||
{
|
||||
if (!ReferenceEquals(_effectTargetSource, script) || _effectTargetSource is null)
|
||||
{
|
||||
_effectTarget = AviUtlCompatMap.ResolveTarget(script);
|
||||
_effectTargetSource = script;
|
||||
}
|
||||
return _effectTarget;
|
||||
}
|
||||
|
||||
private ID2D1Image ApplyEffectChain(ID2D1Image source, IReadOnlyList<AviUtlEffectRequest> requests, EffectDescription desc, ref DrawDescription drawDescription)
|
||||
{
|
||||
_effectChain ??= new VideoEffectChain(_ownCtx!);
|
||||
var target = AviUtlCompatMap.ResolveTarget(item.Script);
|
||||
return _effectChain.Apply(source, requests, desc, target, ref drawDescription);
|
||||
return _effectChain.Apply(source, requests, desc, ResolveEffectTarget(item.Script), ref drawDescription);
|
||||
}
|
||||
|
||||
private static (double Bpm, int Beat, double Offset) ResolveBpm(EffectDescription desc)
|
||||
@@ -527,18 +592,49 @@ namespace LuaScript
|
||||
|
||||
foreach (var item in items)
|
||||
{
|
||||
if (item is not VisualItem visual)
|
||||
if (item is not IVideoItem video)
|
||||
continue;
|
||||
var tag = item.Remark;
|
||||
if (string.IsNullOrEmpty(tag))
|
||||
continue;
|
||||
|
||||
entries.Add(new SceneObjectResolver.Entry(tag, item.Frame, item.Length, item.Layer, visual));
|
||||
var (character, text, kind, volume) = ExtractItemMetadata(item);
|
||||
entries.Add(new SceneObjectResolver.Entry(tag, item.Frame, item.Length, item.Layer, video, volume, character, text, kind));
|
||||
}
|
||||
|
||||
return new SceneObjectResolver([.. entries], desc.FPS);
|
||||
}
|
||||
|
||||
private static (string Character, string Text, string Kind, Animation? Volume) ExtractItemMetadata(IItem item)
|
||||
{
|
||||
string character = string.Empty;
|
||||
string text = string.Empty;
|
||||
string kind = string.Empty;
|
||||
Animation? volume = null;
|
||||
try
|
||||
{
|
||||
kind = item.GetType().Name;
|
||||
switch (item)
|
||||
{
|
||||
case VoiceItem voice:
|
||||
character = voice.CharacterName ?? string.Empty;
|
||||
text = voice.Serif ?? string.Empty;
|
||||
volume = voice.Volume;
|
||||
break;
|
||||
case TextItem textItem:
|
||||
text = textItem.Text ?? string.Empty;
|
||||
break;
|
||||
}
|
||||
}
|
||||
catch
|
||||
{
|
||||
character = string.Empty;
|
||||
text = string.Empty;
|
||||
volume = null;
|
||||
}
|
||||
return (character, text, kind, volume);
|
||||
}
|
||||
|
||||
private static bool SceneValuesMatch(SceneValueQuery[] queries, SceneSharedValues values, long generation)
|
||||
{
|
||||
for (int i = 0; i < queries.Length; i++)
|
||||
@@ -549,6 +645,17 @@ namespace LuaScript
|
||||
return true;
|
||||
}
|
||||
|
||||
private static T[] SnapshotQueries<T>(IReadOnlyList<T> source, T[] existing)
|
||||
{
|
||||
int count = source.Count;
|
||||
if (count == 0)
|
||||
return [];
|
||||
var target = existing.Length == count ? existing : new T[count];
|
||||
for (int i = 0; i < count; i++)
|
||||
target[i] = source[i];
|
||||
return target;
|
||||
}
|
||||
|
||||
private static bool QueriesMatch(SceneObjectQuery[] queries, SceneObjectResolver resolver)
|
||||
{
|
||||
for (int i = 0; i < queries.Length; i++)
|
||||
@@ -754,6 +861,7 @@ namespace LuaScript
|
||||
arg => item.ApplyAnchorDrag(group, index, arg.Delta.X, arg.Delta.Y, is3D ? arg.Delta.Z : 0d))
|
||||
{
|
||||
Shape = VideoControllerPointShape.Circle,
|
||||
OnDragStart = _ => item.BeginAnchorEdit(group, index, is3D),
|
||||
};
|
||||
builder.Add(new VideoEffectController(item, [point]));
|
||||
}
|
||||
@@ -841,7 +949,7 @@ namespace LuaScript
|
||||
|
||||
private void EnsureKernel(string runnable)
|
||||
{
|
||||
if (_kernelResolved && string.Equals(runnable, _kernelSource, StringComparison.Ordinal))
|
||||
if (_kernelResolved && ReferenceEquals(runnable, _kernelSource))
|
||||
return;
|
||||
|
||||
_kernelSource = runnable;
|
||||
@@ -855,7 +963,7 @@ namespace LuaScript
|
||||
|
||||
private void EnsureDirective(string runnable)
|
||||
{
|
||||
if (_directiveCached && string.Equals(runnable, _directiveSource, StringComparison.Ordinal))
|
||||
if (_directiveCached && ReferenceEquals(runnable, _directiveSource))
|
||||
return;
|
||||
|
||||
_directiveSource = runnable;
|
||||
@@ -957,6 +1065,9 @@ namespace LuaScript
|
||||
_nativeLoadText ??= NativeLoadText;
|
||||
_nativeLoadImage ??= NativeLoadImage;
|
||||
_nativeLoadMovie ??= NativeLoadMovie;
|
||||
_loadSceneImage ??= LoadSceneImage;
|
||||
_loadBrushImage ??= LoadBrushImage;
|
||||
_loadAudio ??= LoadAudio;
|
||||
_nativeAddEffect ??= (name, args) => _context.AddEffect(new AviUtlEffectRequest(name, args));
|
||||
_nativeAddDraw ??= command => _context.AddDraw(command);
|
||||
_nativeSetAnchor ??= ResolveNativeAnchor;
|
||||
@@ -974,12 +1085,16 @@ namespace LuaScript
|
||||
_nativeLoadText,
|
||||
_nativeLoadImage,
|
||||
_nativeLoadMovie,
|
||||
_loadSceneImage,
|
||||
_loadBrushImage,
|
||||
_nativeAddEffect,
|
||||
_nativeAddDraw,
|
||||
_nativeSetAnchor,
|
||||
_nativeSceneGet,
|
||||
_nativeSceneSet,
|
||||
_loadAudio,
|
||||
_nativeRunPixelShader,
|
||||
_pixelProcessor,
|
||||
out bool dirty, out bool bufferReplaced,
|
||||
out int resultW, out int resultH, out string? error);
|
||||
|
||||
@@ -1128,6 +1243,117 @@ namespace LuaScript
|
||||
return (buffer, w, h);
|
||||
}
|
||||
|
||||
private static readonly (byte[] Buffer, int Width, int Height) s_noLoadedImage = ([], 0, 0);
|
||||
|
||||
private (byte[] Buffer, int Width, int Height) LoadSceneImage(string name, double time)
|
||||
{
|
||||
var desc = _frameDesc;
|
||||
var devices = _hostDevices;
|
||||
if (desc is null || devices is null)
|
||||
return s_noLoadedImage;
|
||||
|
||||
_pixelLoaderSemaphore.Wait();
|
||||
try
|
||||
{
|
||||
_sceneImageRenderer ??= new SceneImageRenderer(devices);
|
||||
if (!_sceneImageRenderer.TryRender(desc, name, time, out var pixels, out int width, out int height))
|
||||
return s_noLoadedImage;
|
||||
_sceneImageLoaded = true;
|
||||
return (pixels, width, height);
|
||||
}
|
||||
finally
|
||||
{
|
||||
_pixelLoaderSemaphore.Release();
|
||||
}
|
||||
}
|
||||
|
||||
private (byte[] Buffer, int Width, int Height) LoadBrushImage(string name, double width, double height, IReadOnlyList<KeyValuePair<string, object>> arguments)
|
||||
{
|
||||
var desc = _frameDesc;
|
||||
var devices = _hostDevices;
|
||||
if (desc is null || devices is null)
|
||||
return s_noLoadedImage;
|
||||
|
||||
int w = (int)Math.Round(width);
|
||||
int h = (int)Math.Round(height);
|
||||
|
||||
_pixelLoaderSemaphore.Wait();
|
||||
try
|
||||
{
|
||||
_brushImageRenderer ??= new BrushImageRenderer(devices);
|
||||
if (!_brushImageRenderer.TryRender(desc, name, w, h, arguments, out var pixels, out int outWidth, out int outHeight))
|
||||
return s_noLoadedImage;
|
||||
return (pixels, outWidth, outHeight);
|
||||
}
|
||||
finally
|
||||
{
|
||||
_pixelLoaderSemaphore.Release();
|
||||
}
|
||||
}
|
||||
|
||||
private static readonly (int Count, int Rate, double[] Data) s_noAudio = (0, 0, []);
|
||||
|
||||
private (int Count, int Rate, double[] Data) LoadAudio(string file, string type, int size)
|
||||
{
|
||||
var desc = _frameDesc;
|
||||
if (desc is null)
|
||||
return s_noAudio;
|
||||
|
||||
_audioProvider ??= new AudioSampleProvider();
|
||||
(int Count, int Rate) result;
|
||||
if (string.Equals(file, "audiobuffer", StringComparison.Ordinal))
|
||||
{
|
||||
result = _audioProvider.ReadScene(FindOwnScene(desc), desc.TimelinePosition.Time.TotalSeconds, type, size);
|
||||
}
|
||||
else if (string.Equals(file, "itembuffer", StringComparison.Ordinal))
|
||||
{
|
||||
var (audioItem, scene) = ResolveOwnAudioItem(desc);
|
||||
result = _audioProvider.ReadItem(audioItem, scene, desc.ItemPosition.Time.TotalSeconds, type, size);
|
||||
}
|
||||
else
|
||||
{
|
||||
result = _audioProvider.ReadFile(file, desc.ItemPosition.Time.TotalSeconds, type, size);
|
||||
}
|
||||
|
||||
if (result.Count > 0)
|
||||
_audioLoaded = true;
|
||||
return (result.Count, result.Rate, _audioProvider.Data);
|
||||
}
|
||||
|
||||
private static Scene? FindOwnScene(EffectDescription desc)
|
||||
{
|
||||
var scenes = desc.Scenes;
|
||||
if (scenes is null)
|
||||
return null;
|
||||
foreach (var info in scenes)
|
||||
{
|
||||
if (info is Scene scene && scene.ID == desc.SceneId)
|
||||
return scene;
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
private (IAudioItem? Item, Scene? Scene) ResolveOwnAudioItem(EffectDescription desc)
|
||||
{
|
||||
var scene = FindOwnScene(desc);
|
||||
if (scene is null)
|
||||
return (null, null);
|
||||
|
||||
var items = scene.Timeline.Items;
|
||||
for (int i = 0; i < items.Count; i++)
|
||||
{
|
||||
if (items[i] is not IVideoItem video)
|
||||
continue;
|
||||
var effects = video.VideoEffects;
|
||||
for (int k = 0; k < effects.Count; k++)
|
||||
{
|
||||
if (ReferenceEquals(effects[k], item))
|
||||
return (items[i] as IAudioItem, scene);
|
||||
}
|
||||
}
|
||||
return (null, scene);
|
||||
}
|
||||
|
||||
private (byte[] buffer, int w, int h) NativeLoadMovie(string path, double time)
|
||||
{
|
||||
_nativeMovieDecoder ??= new MovieDecoder();
|
||||
@@ -1175,6 +1401,9 @@ namespace LuaScript
|
||||
_bufferCompositor?.Dispose();
|
||||
_nativeTextRenderer?.Dispose();
|
||||
_nativeImageDecoder?.Dispose();
|
||||
_sceneImageRenderer?.Dispose();
|
||||
_brushImageRenderer?.Dispose();
|
||||
_audioProvider?.Dispose();
|
||||
_pixelLoaderSemaphore.Dispose();
|
||||
_pixelManager?.Dispose();
|
||||
_pixelManager = null;
|
||||
|
||||
@@ -107,4 +107,9 @@
|
||||
<data name="DiagnosticCompile" xml:space="preserve"><value>خطأ في بناء الجملة</value></data>
|
||||
<data name="DiagnosticRuntime" xml:space="preserve"><value>خطأ وقت التشغيل</value></data>
|
||||
<data name="DiagnosticTimeout" xml:space="preserve"><value>انتهت المهلة</value></data>
|
||||
<data name="AnchorGroup" xml:space="preserve"><value>مرساة</value></data>
|
||||
<data name="AnchorX" xml:space="preserve"><value>X</value></data>
|
||||
<data name="AnchorY" xml:space="preserve"><value>Y</value></data>
|
||||
<data name="AnchorZ" xml:space="preserve"><value>Z</value></data>
|
||||
<data name="AnchorDesc" xml:space="preserve"><value>إحداثيات نقطة الإرساء المحددة</value></data>
|
||||
</root>
|
||||
@@ -47,3 +47,8 @@ LuaFileFilter,,Luaスクリプト (*.lua)|*.lua|すべてのファイル (*.*)|*
|
||||
DiagnosticCompile,,構文エラー,Syntax error,语法错误,語法錯誤,구문 오류,Error de sintaxis,خطأ في بناء الجملة,Kesalahan sintaksis
|
||||
DiagnosticRuntime,,実行時エラー,Runtime error,运行时错误,執行時錯誤,런타임 오류,Error de ejecución,خطأ وقت التشغيل,Kesalahan runtime
|
||||
DiagnosticTimeout,,タイムアウト,Timed out,执行超时,執行逾時,시간 초과,Tiempo de espera agotado,انتهت المهلة,Waktu habis
|
||||
AnchorGroup,,アンカー,Anchor,锚点,錨點,앵커,Anclaje,مرساة,Jangkar
|
||||
AnchorX,,X,X,X,X,X,X,X,X
|
||||
AnchorY,,Y,Y,Y,Y,Y,Y,Y,Y
|
||||
AnchorZ,,Z,Z,Z,Z,Z,Z,Z,Z
|
||||
AnchorDesc,,選択中のアンカーポイントの座標,Coordinate of the selected anchor point,所选锚点的坐标,所選錨點的座標,선택한 앵커 포인트의 좌표,Coordenada del punto de anclaje seleccionado,إحداثيات نقطة الإرساء المحددة,Koordinat titik jangkar yang dipilih
|
||||
|
@@ -107,4 +107,9 @@
|
||||
<data name="DiagnosticCompile" xml:space="preserve"><value>Syntax error</value></data>
|
||||
<data name="DiagnosticRuntime" xml:space="preserve"><value>Runtime error</value></data>
|
||||
<data name="DiagnosticTimeout" xml:space="preserve"><value>Timed out</value></data>
|
||||
<data name="AnchorGroup" xml:space="preserve"><value>Anchor</value></data>
|
||||
<data name="AnchorX" xml:space="preserve"><value>X</value></data>
|
||||
<data name="AnchorY" xml:space="preserve"><value>Y</value></data>
|
||||
<data name="AnchorZ" xml:space="preserve"><value>Z</value></data>
|
||||
<data name="AnchorDesc" xml:space="preserve"><value>Coordinate of the selected anchor point</value></data>
|
||||
</root>
|
||||
@@ -107,4 +107,9 @@
|
||||
<data name="DiagnosticCompile" xml:space="preserve"><value>Error de sintaxis</value></data>
|
||||
<data name="DiagnosticRuntime" xml:space="preserve"><value>Error de ejecución</value></data>
|
||||
<data name="DiagnosticTimeout" xml:space="preserve"><value>Tiempo de espera agotado</value></data>
|
||||
<data name="AnchorGroup" xml:space="preserve"><value>Anclaje</value></data>
|
||||
<data name="AnchorX" xml:space="preserve"><value>X</value></data>
|
||||
<data name="AnchorY" xml:space="preserve"><value>Y</value></data>
|
||||
<data name="AnchorZ" xml:space="preserve"><value>Z</value></data>
|
||||
<data name="AnchorDesc" xml:space="preserve"><value>Coordenada del punto de anclaje seleccionado</value></data>
|
||||
</root>
|
||||
@@ -107,4 +107,9 @@
|
||||
<data name="DiagnosticCompile" xml:space="preserve"><value>Kesalahan sintaksis</value></data>
|
||||
<data name="DiagnosticRuntime" xml:space="preserve"><value>Kesalahan runtime</value></data>
|
||||
<data name="DiagnosticTimeout" xml:space="preserve"><value>Waktu habis</value></data>
|
||||
<data name="AnchorGroup" xml:space="preserve"><value>Jangkar</value></data>
|
||||
<data name="AnchorX" xml:space="preserve"><value>X</value></data>
|
||||
<data name="AnchorY" xml:space="preserve"><value>Y</value></data>
|
||||
<data name="AnchorZ" xml:space="preserve"><value>Z</value></data>
|
||||
<data name="AnchorDesc" xml:space="preserve"><value>Koordinat titik jangkar yang dipilih</value></data>
|
||||
</root>
|
||||
@@ -107,4 +107,9 @@
|
||||
<data name="DiagnosticCompile" xml:space="preserve"><value>구문 오류</value></data>
|
||||
<data name="DiagnosticRuntime" xml:space="preserve"><value>런타임 오류</value></data>
|
||||
<data name="DiagnosticTimeout" xml:space="preserve"><value>시간 초과</value></data>
|
||||
<data name="AnchorGroup" xml:space="preserve"><value>앵커</value></data>
|
||||
<data name="AnchorX" xml:space="preserve"><value>X</value></data>
|
||||
<data name="AnchorY" xml:space="preserve"><value>Y</value></data>
|
||||
<data name="AnchorZ" xml:space="preserve"><value>Z</value></data>
|
||||
<data name="AnchorDesc" xml:space="preserve"><value>선택한 앵커 포인트의 좌표</value></data>
|
||||
</root>
|
||||
@@ -107,4 +107,9 @@
|
||||
<data name="DiagnosticCompile" xml:space="preserve"><value>構文エラー</value></data>
|
||||
<data name="DiagnosticRuntime" xml:space="preserve"><value>実行時エラー</value></data>
|
||||
<data name="DiagnosticTimeout" xml:space="preserve"><value>タイムアウト</value></data>
|
||||
<data name="AnchorGroup" xml:space="preserve"><value>アンカー</value></data>
|
||||
<data name="AnchorX" xml:space="preserve"><value>X</value></data>
|
||||
<data name="AnchorY" xml:space="preserve"><value>Y</value></data>
|
||||
<data name="AnchorZ" xml:space="preserve"><value>Z</value></data>
|
||||
<data name="AnchorDesc" xml:space="preserve"><value>選択中のアンカーポイントの座標</value></data>
|
||||
</root>
|
||||
@@ -107,4 +107,9 @@
|
||||
<data name="DiagnosticCompile" xml:space="preserve"><value>语法错误</value></data>
|
||||
<data name="DiagnosticRuntime" xml:space="preserve"><value>运行时错误</value></data>
|
||||
<data name="DiagnosticTimeout" xml:space="preserve"><value>执行超时</value></data>
|
||||
<data name="AnchorGroup" xml:space="preserve"><value>锚点</value></data>
|
||||
<data name="AnchorX" xml:space="preserve"><value>X</value></data>
|
||||
<data name="AnchorY" xml:space="preserve"><value>Y</value></data>
|
||||
<data name="AnchorZ" xml:space="preserve"><value>Z</value></data>
|
||||
<data name="AnchorDesc" xml:space="preserve"><value>所选锚点的坐标</value></data>
|
||||
</root>
|
||||
@@ -107,4 +107,9 @@
|
||||
<data name="DiagnosticCompile" xml:space="preserve"><value>語法錯誤</value></data>
|
||||
<data name="DiagnosticRuntime" xml:space="preserve"><value>執行時錯誤</value></data>
|
||||
<data name="DiagnosticTimeout" xml:space="preserve"><value>執行逾時</value></data>
|
||||
<data name="AnchorGroup" xml:space="preserve"><value>錨點</value></data>
|
||||
<data name="AnchorX" xml:space="preserve"><value>X</value></data>
|
||||
<data name="AnchorY" xml:space="preserve"><value>Y</value></data>
|
||||
<data name="AnchorZ" xml:space="preserve"><value>Z</value></data>
|
||||
<data name="AnchorDesc" xml:space="preserve"><value>所選錨點的座標</value></data>
|
||||
</root>
|
||||
120ファイル中100ファイルを読み込みました。 変更されたファイルが多すぎるため、それ以降のファイルは表示していません。
さらに表示
新しいイシューから参照
ユーザーをブロックする