コミットを比較
| 作成者 | SHA1 | 日付 | |
|---|---|---|---|
|
|
2b24a407e6
|
||
|
|
150b4818d4
|
||
|
|
34b7d60ca6
|
||
|
|
7dc6083fd7
|
||
|
|
245fb9c323
|
||
|
|
42c3bc4f4b
|
||
|
|
d273f99593
|
||
|
|
e1763e0c81
|
||
|
|
7221ce3aca
|
||
|
|
5f3ad96ea2
|
||
|
|
4e0bf831c5
|
||
|
|
0fedfd5804
|
||
|
|
f11225e2a1
|
||
|
|
92e8c43160
|
||
|
|
5fb9eae7a0
|
||
|
|
f109232cae
|
||
|
|
1596a048cd
|
||
|
|
0b0c795d7a
|
||
|
|
2be3c3d28b
|
||
|
|
3f9e4ebca4
|
||
|
|
03042b17e7
|
||
|
|
5e6d74dfee
|
||
|
|
40d68416c2
|
||
|
|
de6472c34b
|
||
|
|
55c8bffb70
|
||
|
|
8ca66bceb8
|
||
|
|
865f5117ea
|
||
|
|
b30f7a818b
|
||
|
|
95786a1f0a
|
||
|
|
cc07e2a83d
|
||
|
|
08e5e432b7
|
||
|
|
1e9b039cef
|
||
|
|
bad39fe0db
|
||
|
|
a5567a804d
|
||
|
|
a9cb4a9cda
|
||
|
|
9e9b5277af
|
||
|
|
1d8705c7ee
|
||
|
|
14683c7909
|
||
|
|
42b123ebc3
|
||
|
|
b0114abdb7
|
||
|
|
c21de5b3eb
|
||
|
|
bd891d9a1e
|
||
|
|
d2bef10085
|
||
|
|
3eafcdc70e
|
||
|
|
6f26fc95fa
|
||
|
|
88ce786d05
|
||
|
|
d69ae5f06e
|
||
|
|
d42d8a6764
|
||
|
|
8f9ace2dc8
|
||
|
|
c416e955a4
|
||
|
|
7362e70ab8
|
||
|
|
c9741836a5
|
||
|
|
afd57d758d
|
||
|
|
c56432dbd6
|
||
|
|
9493aef779
|
||
|
|
5d55f2c083
|
||
|
|
09918c2858
|
||
|
|
a687bba0ff
|
||
|
|
bb591b6fef
|
||
|
|
27d7294290
|
||
|
|
8d1cf91499
|
||
|
|
b2a1900616
|
||
|
|
f786250866
|
||
|
|
20dfba6e7e
|
||
|
|
5e40f45910
|
||
|
|
ea4f096bc4
|
||
|
|
d7812f39dc
|
||
|
|
77fdf60ec9
|
||
|
|
bcb9925953
|
||
|
|
ec7d8a1da4
|
||
|
|
098d6e498b
|
||
|
|
ccf37dd1d3
|
||
|
|
2ce3068d54
|
||
|
|
c2a1990501
|
||
|
|
4ac25584b9
|
||
|
|
5e40f30124
|
||
|
|
9d541e06b9
|
||
|
|
bca7b5707e
|
||
|
|
a17289a2da
|
||
|
|
71e6b71056
|
||
|
|
13a0602adb
|
||
|
|
6a0c993755
|
||
|
|
484a26ec45
|
||
|
|
a121a598b6
|
||
|
|
6dd70413a9
|
||
|
|
ac482b6041
|
||
|
|
c2761c0796
|
||
|
|
3bbd411d86
|
||
|
|
324faabb96
|
||
|
|
32b706cb8b
|
||
|
|
aa97c52b38
|
||
|
|
a2f0231739
|
||
|
|
2905192d3a
|
||
|
|
ee6f6bd9c1
|
||
|
|
8853f5e403
|
||
|
|
867de7aa73
|
||
|
|
e384d7e490
|
||
|
|
87e060d71d
|
||
|
|
9c6167d224
|
||
|
|
a8a91103e1
|
||
|
|
4a2f4b2dbb
|
||
|
|
33fc45639b
|
||
|
|
7af803e46e
|
||
|
|
48e8287704
|
||
|
|
7eff4591f0
|
||
|
|
5b1bb4ad6e
|
||
|
|
7f3e6b0019
|
||
|
|
7519a11851
|
||
|
|
4193c40f41
|
||
|
|
cd68bf86b0
|
||
|
|
9948204265
|
||
|
|
25670bde90
|
||
|
|
ae230c0e10
|
||
|
|
7ee8f1ccf0
|
||
|
|
da88898a67
|
||
|
|
3c63ba0729
|
||
|
|
e7382ac289
|
||
|
|
ee7e4f43bc
|
||
|
|
7dc6e9fb40
|
||
|
|
803534d804
|
||
|
|
a25803fa30
|
||
|
|
e42401670f
|
||
|
|
a139326c39
|
||
|
|
496c237f50
|
||
|
|
dfbcbded98
|
||
|
|
2ebbe3ced0
|
||
|
|
9671cba5a1
|
||
|
|
947532f064
|
||
|
|
6e3594eb01
|
||
|
|
abc7b2cde2
|
||
|
|
68d862ded0
|
||
|
|
d3060fd202
|
||
|
|
1d92d80a86
|
||
|
|
86ad19105f
|
||
|
|
2cd5ab273a
|
||
|
|
d75aeee3c2
|
||
|
|
981fb2ceeb
|
||
|
|
01a0dcb9ae
|
||
|
|
460b5e6252
|
||
|
|
fb02580836
|
||
|
|
58a5f59b19
|
||
|
|
95598b1a88
|
||
|
|
7f436ebe17
|
||
|
|
d620f7ea3b
|
||
|
|
ad377a0923
|
||
|
|
f374038000
|
||
|
|
ddba8d63c2
|
||
|
|
ab2e195139
|
||
|
|
85c585db89
|
||
|
|
93eb681b0e
|
||
|
|
30ca75f65e
|
||
|
|
a07916de6b
|
||
|
|
467a4b0dd8
|
||
|
|
03aad4cc6e
|
||
|
|
b638c7b9c2
|
||
|
|
ede56971cd
|
||
|
|
94c11dffcb
|
||
|
|
28c1f70fa1
|
||
|
|
2ecde28980
|
||
|
|
1c2c3915e9
|
||
|
|
9f2cab9961
|
||
|
|
e1778c7c73
|
||
|
|
98426f4ca8
|
||
|
|
7358e2b0a1
|
||
|
|
1af7b8fc8b
|
||
|
|
26d7b0c470
|
||
|
|
96400605ba
|
||
|
|
695cb2f04d
|
||
|
|
6b39a4cceb
|
||
|
|
4b4252855b
|
||
|
|
0d6c3285e1
|
||
|
|
3bcf206a95
|
||
|
|
c65bb5b08f
|
||
|
|
e5b9b98a27
|
||
|
|
7906d4c735
|
||
|
|
d879f3c6fa
|
||
|
|
e7ae3bf290
|
||
|
|
735fd86bed
|
||
|
|
813b3d6686
|
||
|
|
ca43e3706b
|
||
|
|
ef4d7e8024
|
||
|
|
299da15bb8
|
||
|
|
ffba68aeb0
|
||
|
|
1085294aa0
|
||
|
|
cb7e4622e8
|
||
|
|
06e2afa7ed
|
||
|
|
3e60c6d77f
|
||
|
|
594517b436
|
||
|
|
1d3b924492
|
||
|
|
b6cd4bb43e
|
||
|
|
5c0745e039
|
||
|
|
c5fd507ab5
|
||
|
|
dfc39e9e19
|
||
|
|
48d7969a84
|
||
|
|
9eb5a44f2d
|
||
|
|
fc2fc6ab77
|
||
|
|
bc7fa914a4
|
||
|
|
c436f24ee0
|
||
|
|
5a192f5a6f
|
||
|
|
a032f0728f
|
||
|
|
548432f3a9
|
||
|
|
3bd1e5384e
|
||
|
|
738da05e59
|
||
|
|
d457b65f44
|
||
|
|
270cf025ff
|
||
|
|
c657892b7b
|
||
|
|
87cdd4ed90
|
||
|
|
5c1c1272db
|
||
|
|
bcac943775
|
||
|
|
3d0ff687e2
|
||
|
|
ce0da92ac8
|
||
|
|
7dbe063ac8
|
||
|
|
1acaef291c
|
||
|
|
26c96b302f
|
||
|
|
c4011d8eef
|
||
|
|
451b017f6f
|
||
|
|
d6b6e440bf
|
||
|
|
7601b77902
|
||
|
|
0799785cad
|
||
|
|
d607e4ec49
|
||
|
|
c7e5b91509
|
||
|
|
cf23d184fe
|
||
|
|
d2b518f611
|
||
|
|
c186a6b27d
|
||
|
|
5f411e89ec
|
||
|
|
16ed6336c3
|
||
|
|
6d2a5cbe24
|
||
|
|
94f7ad4f50
|
||
|
|
3ba77aab18
|
||
|
|
90fe288f66
|
||
|
|
6b2b5d879f | ||
|
|
d01d5d6df5 | ||
|
|
a093c458a2
|
||
|
|
0e65bf1883
|
||
|
|
d8f728b3f9
|
||
|
|
244e75a238
|
||
|
|
75cc4bd62e
|
||
|
|
6385dbeb6d
|
||
|
|
bc395a0181
|
||
|
|
a0dec019fe
|
||
|
|
c8350161db
|
||
|
|
679cab03b5
|
||
|
|
6783146231
|
||
|
|
df303ee154
|
||
|
|
f49bd740a0
|
||
|
|
80d1b75227
|
検索条件に一致するファイルはありません
+39
-39
@@ -1,56 +1,56 @@
|
||||
# v1.6.0 - Lua スクリプト for YMM4
|
||||
# v1.13.0 - Lua スクリプト for YMM4
|
||||
|
||||
AviUtl のアニメーション効果スクリプト互換層に**動的パラメータの UI 反映**を
|
||||
追加したリリースです。スクリプトのヘッダに記述した `--track` / `--check` /
|
||||
`--color` の宣言が、エディタのパラメータUIへ自動的に反映されるようになりました。
|
||||
シーン単位で値を共有する scene.set / scene.get と、AviUtl 互換のグローバル関数を追加したリリースです。
|
||||
アイテムやフレームをまたいだ値の受け渡しと、RGB / HSV による色計算、ビット演算、デバッグ出力を、MoonSharp とネイティブの両エンジンで同一に扱えるようにしました。
|
||||
いずれも既存のスクリプトと API に影響しない追加で、従来の呼び出しはそのまま動作します。
|
||||
|
||||
---
|
||||
|
||||
## 新機能
|
||||
|
||||
### 1. AviUtl ヘッダ宣言に応じた動的パラメータUI
|
||||
### 1. シーン単位で値を共有する scene.set / scene.get を追加
|
||||
|
||||
スクリプト先頭の `--track0`〜`--track3` / `--check0`〜`--check3` / `--color` を
|
||||
解析し、宣言された項目だけをエディタUIへ表示します。AviUtl の仕様に準じ、
|
||||
トラックバーは最大4個、チェックボックスは最大4個、カラーは1個です。
|
||||
scene.set(name, value) はシーン単位の共有領域へ値を保存し、同じシーン内のすべての Lua スクリプトエフェクトから scene.get(name) で参照できます。
|
||||
アイテムやフレームをまたいで値を受け渡せるため、グローバル変数がフレーム間で保持されない制約を、共有領域を介して回避できます。
|
||||
保存できる値は数値・文字列・真偽値で、nil を渡すと削除します。テーブルや関数などそれ以外の値は保存しません。
|
||||
scene.get は未設定の名前に対して nil を返します。
|
||||
名前と文字列値は UTF-8 換算で 4095 バイトを超える部分を切り捨てます。
|
||||
共有値はシーンごとに独立しており、シーン識別子を鍵として YMM4 を終了するまでメモリ上に保持します。プロジェクトファイルには保存しません。
|
||||
アイテム間の評価順序は保証しないため、同一フレーム内での書き込みと読み取りの順序に依存する作りは避けてください。
|
||||
MoonSharp とネイティブのどちらのエンジンでも同一に動作します。
|
||||
|
||||
- `--track番号:名前,最小,最大,初期値,移動量`: 宣言されたトラックのスライダーを
|
||||
表示します。トラック値は評価時にヘッダの最小〜最大へクランプされ、`obj.track0`〜
|
||||
`obj.track3` から参照できます。
|
||||
- `--check番号:名前,初期値`: トグルスライダーを表示します。値は `obj.check0`〜
|
||||
`obj.check3` から真偽値(false / true)として参照できます。
|
||||
- `--color:色`: カラーピッカーを表示します。選択した色はグローバル変数 `color`
|
||||
(0xRRGGBB)として参照できます。
|
||||
- 宣言が一つも無い場合は、従来どおり Track0〜Track3 の4スライダー表示へ戻ります。
|
||||
- 各項目のラベルは多言語化された固定スロット(Track0〜3 / Check0〜3 / Color)で
|
||||
表示されます。設定した値はプロジェクトファイルに保存され、再現できます。
|
||||
### 2. AviUtl 互換のグローバル関数を追加
|
||||
|
||||
グローバルスコープから RGB / HSV / OR / AND / XOR / SHIFT / debug_print を直接呼び出せるようにしました。
|
||||
RGB(r, g, b) は RGB 各要素を 0xRRGGBB の色情報へ合成し、RGB(col) は色情報を r, g, b の 3 値へ分解します。RGB(r1, g1, b1, r2, g2, b2) は obj.time / obj.totaltime の進行に合わせて一色目から二色目へ直線的に変化する色情報を返します。
|
||||
HSV も同様に色相・彩度・明度と色情報を相互に変換し、6 引数指定で時間変化します。色相は 0 から 360、彩度と明度は 0 から 100 の範囲で扱います。
|
||||
OR / AND / XOR は 32bit 整数のビット演算で、小数は 0.5 ちょうどまでを切り捨てて整数化します(2.50 は 2、2.51 は 3)。
|
||||
SHIFT(a, shift) は算術シフトで、shift が正で左シフト、負で右シフトします。
|
||||
debug_print(text) は文字列を OutputDebugString() へ送信し、DebugView などで確認できます。スクリプトの実行エラーも自動で送信します。
|
||||
これらの関数は MoonSharp とネイティブのどちらのエンジンでも同一の結果を返します。
|
||||
|
||||
### 3. エディタの入力補完へ追加
|
||||
|
||||
上記のグローバル関数と scene.set / scene.get を、スクリプトエディタの入力補完の候補へ追加しました。
|
||||
|
||||
---
|
||||
|
||||
## 注意事項
|
||||
## 互換性・後方互換
|
||||
|
||||
- ラベルは固定スロット番号で表示され、スクリプト内に記述したパラメータ名
|
||||
(例: `--track0:X速度,...` の「X速度」)は UI ラベルへは反映されません。
|
||||
- トラックのスライダー操作範囲は従来どおり -100〜100 で、ヘッダの範囲・既定値は
|
||||
スライダーの表示そのものには反映されません。トラック値は評価時にヘッダの
|
||||
最小〜最大へクランプされます。新規に宣言されたチェック・色にはヘッダの既定値が
|
||||
適用されますが、トラックには適用されず初期値は 0 のままです。
|
||||
- `--dialog`(`/chk`・`/col`・`/fig`)、`--file`、`--font` には対応していません。
|
||||
- 本変更に伴い、`--check` / `--color` の擬似展開(従来 `obj.checkN` や `color` を
|
||||
スクリプト先頭へ自動挿入していた挙動)は廃止され、値は UI から供給されます。
|
||||
`--dialog` / `--param` の展開は従来どおりです。
|
||||
- 既存のスクリプトの書き方と API に変更はありません。追加した関数と scene.set / scene.get はいずれも新規で、従来の呼び出しに影響しません。
|
||||
- これまで未対応だった scene.set / scene.get に対応しました。AviUtl の同名関数を使うスクリプトが、シーン内での値共有として動作します。
|
||||
- RGB / HSV / OR / AND / XOR / SHIFT / debug_print はグローバル名として追加されます。スクリプト側で同名のグローバルを定義した場合は、スクリプト側の定義が優先されます。
|
||||
- 共有値はメモリ上にのみ保持し、プロジェクトファイルには保存しません。YMM4 を終了すると失われます。
|
||||
|
||||
---
|
||||
|
||||
## 内部実装
|
||||
|
||||
- AviUtl ヘッダ(`--track` / `--check` / `--color`)を解析するレイアウト解析を
|
||||
追加しました。走査範囲は既存の互換変換と同じく最初の `@` セクションより前です。
|
||||
- 解析結果に基づき、`[ShowPropertyEditorWhen]` による項目ごとの動的表示と、
|
||||
評価時のトラック値クランプを実装しました。
|
||||
- `obj.check0`〜`obj.check3`(真偽値)とグローバル `color` を、MoonSharp および
|
||||
ネイティブ(LuaJIT)双方の実行経路へ配線しました。
|
||||
- 互換変換から `--check` / `--color` の擬似展開を廃止し、UI を値の唯一のソースに
|
||||
しました。
|
||||
- チェック・色のラベルを多言語リソースへ追加しました。
|
||||
- ヘッダ解析および互換変換の挙動変更に関するユニットテストを追加・更新しました。
|
||||
- SceneSharedValues がシーン識別子ごとに共有辞書を保持し、名前と文字列値を UTF-8 で 4095 バイトへ切り詰めます。
|
||||
- AviUtlScriptContext がシーン共有値の取得と書き込みを仲介し、読み取った名前と結果、書き込みの有無を記録します。
|
||||
- LuaScriptEffectProcessor は記録した読み取り結果と書き込みの有無をフレームキャッシュへ持ち込み、共有値を書き込んだフレーム、または読み取った値が現在値と食い違うフレームではキャッシュを使わず再実行します。
|
||||
- MoonSharp では AviUtlGlobalRegistrar がグローバル関数を、SceneTableRegistrar が scene.set / scene.get を登録します。時間変化の割合は obj.time / obj.totaltime から求めます。
|
||||
- ネイティブでは NativeProtocol へ scene 取得と設定のコールバック種別を追加し、LuaJitWorker が名前と値を共有メモリ経由でやり取りします。文字列は名前と値を区切って 1 つのタグ領域へ格納します。
|
||||
- worker.lua が scene.get / scene.set のブリッジと時間変化の割合の設定を行い、shim.lua が RGB / HSV / OR / AND / XOR / SHIFT / debug_print を実装します。
|
||||
- スクリプトのタイムアウトと実行時例外のメッセージも、debug_print と同じ OutputDebugString の経路へ送信します。
|
||||
- テストは 3063 件です。v1.12.0 の 3041 件から、シーン共有値の保存と削除と切り詰め、scene テーブルへの登録、グローバル関数のエンジン間の一致、ネイティブワーカーでの往復などの検証を追加しました。
|
||||
@@ -1,5 +1,5 @@
|
||||
========================================
|
||||
Luaスクリプト for YMM4 v1.6.0
|
||||
Luaスクリプト for YMM4 v1.13.0
|
||||
========================================
|
||||
YukkuriMovieMaker4(YMM4)上で動作する、Luaスクリプトで映像エフェクトのパラメータや
|
||||
ピクセルを直接制御できるプラグインです。
|
||||
@@ -26,7 +26,9 @@ obj.x/y/zoom/alpha等の値はキーフレームアニメーションと連動
|
||||
|
||||
- スクリプトエラー時の挙動: コンパイルエラーまたは実行時エラーが発生した場合、
|
||||
そのフレームでの座標・透明度・回転・ピクセルの変更は適用されず、入力された
|
||||
元の状態がそのまま出力されます。エラー内容はログへ出力されます。
|
||||
元の状態がそのまま出力されます。エラー内容はログへ出力されるほか、スクリプト
|
||||
エディタの該当箇所へ赤い波線が表示され、ポイントするとエラー内容をツールチップ
|
||||
で確認できます。
|
||||
|
||||
- ファイルアクセスの制限: スクリプトからのファイル読み込みは許可されておらず、
|
||||
io・os等のモジュールも有効化されていません。
|
||||
|
||||
@@ -0,0 +1,103 @@
|
||||
using System.Collections.Immutable;
|
||||
using LuaScript.Anchor;
|
||||
|
||||
namespace LuaScript.Tests
|
||||
{
|
||||
public class AnchorSupportTests
|
||||
{
|
||||
[Fact]
|
||||
public void ClampCount_LimitsToRange()
|
||||
{
|
||||
Assert.Equal(0, AnchorSupport.ClampCount(-5));
|
||||
Assert.Equal(10, AnchorSupport.ClampCount(10));
|
||||
Assert.Equal(AnchorSupport.MaxAnchors, AnchorSupport.ClampCount(100));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void ApplyOption_SetsConnectionAndDimension()
|
||||
{
|
||||
var connection = AnchorConnection.None;
|
||||
bool is3D = false;
|
||||
|
||||
AnchorSupport.ApplyOption("loop", ref connection, ref is3D);
|
||||
AnchorSupport.ApplyOption("xyz", ref connection, ref is3D);
|
||||
|
||||
Assert.Equal(AnchorConnection.Loop, connection);
|
||||
Assert.True(is3D);
|
||||
|
||||
AnchorSupport.ApplyOption("star", ref connection, ref is3D);
|
||||
Assert.Equal(AnchorConnection.Star, connection);
|
||||
|
||||
AnchorSupport.ApplyOption("unknown", ref connection, ref is3D);
|
||||
Assert.Equal(AnchorConnection.Star, connection);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void DefaultPosition_IsDeterministicGrid()
|
||||
{
|
||||
Assert.Equal(AnchorSupport.DefaultPosition(0), AnchorSupport.DefaultPosition(0));
|
||||
Assert.NotEqual(AnchorSupport.DefaultPosition(0), AnchorSupport.DefaultPosition(1));
|
||||
|
||||
var (x8, y8) = AnchorSupport.DefaultPosition(8);
|
||||
var (x0, y0) = AnchorSupport.DefaultPosition(0);
|
||||
Assert.Equal(x0, x8);
|
||||
Assert.True(y8 > y0);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void ResolvePosition_PrefersStoredThenDefault()
|
||||
{
|
||||
var source = ImmutableList.Create(new LuaAnchorPoint { Group = "pos", Index = 1, X = 12, Y = 34, Z = 56 });
|
||||
|
||||
AnchorSupport.ResolvePosition(source, "pos", 1, out double x, out double y, out double z);
|
||||
Assert.Equal(12, x);
|
||||
Assert.Equal(34, y);
|
||||
Assert.Equal(56, z);
|
||||
|
||||
AnchorSupport.ResolvePosition(source, "pos", 0, out double dx, out double dy, out double dz);
|
||||
var (ex, ey) = AnchorSupport.DefaultPosition(0);
|
||||
Assert.Equal(ex, dx);
|
||||
Assert.Equal(ey, dy);
|
||||
Assert.Equal(0, dz);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void ResolvePosition_IsGroupScoped()
|
||||
{
|
||||
var source = ImmutableList.Create(new LuaAnchorPoint { Group = "a", Index = 0, X = 5, Y = 5, Z = 0 });
|
||||
|
||||
AnchorSupport.ResolvePosition(source, "b", 0, out double x, out double y, out _);
|
||||
var (ex, ey) = AnchorSupport.DefaultPosition(0);
|
||||
Assert.Equal(ex, x);
|
||||
Assert.Equal(ey, y);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void ApplyDrag_UpdatesExistingPoint()
|
||||
{
|
||||
var source = ImmutableList.Create(new LuaAnchorPoint { Group = "pos", Index = 2, X = 10, Y = 20, Z = 30 });
|
||||
|
||||
var result = AnchorSupport.ApplyDrag(source, "pos", 2, 3, -4, 5);
|
||||
|
||||
Assert.Single(result);
|
||||
Assert.Equal(13, result[0].X);
|
||||
Assert.Equal(16, result[0].Y);
|
||||
Assert.Equal(35, result[0].Z);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void ApplyDrag_AddsNewPointFromDefault()
|
||||
{
|
||||
var source = ImmutableList<LuaAnchorPoint>.Empty;
|
||||
|
||||
var result = AnchorSupport.ApplyDrag(source, "pos", 3, 7, 8, 0);
|
||||
|
||||
Assert.Single(result);
|
||||
var (bx, by) = AnchorSupport.DefaultPosition(3);
|
||||
Assert.Equal("pos", result[0].Group);
|
||||
Assert.Equal(3, result[0].Index);
|
||||
Assert.Equal(bx + 7, result[0].X);
|
||||
Assert.Equal(by + 8, result[0].Y);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,64 @@
|
||||
using LuaScript.Compat;
|
||||
|
||||
namespace LuaScript.Tests
|
||||
{
|
||||
public class AviUtlCompatMapTests
|
||||
{
|
||||
[Fact]
|
||||
public void Resolve_KnownEffect_ReturnsTargetType()
|
||||
{
|
||||
Assert.True(AviUtlCompatMap.Default.TryResolve("ぼかし", AviUtlEngine.AviUtl, out var mapping));
|
||||
Assert.Equal("GaussianBlurEffect", mapping.TargetType);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Resolve_ParameterTransform_IsInverseOfExoExport()
|
||||
{
|
||||
AviUtlCompatMap.Default.TryResolve("ぼかし", AviUtlEngine.AviUtl, out var mapping);
|
||||
Assert.True(mapping.TryGetParameter("範囲", out var parameter));
|
||||
Assert.Equal("Blur", parameter.Property);
|
||||
Assert.Equal(5d, parameter.Transform(10d));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Resolve_AngleParameter_IsIdentity()
|
||||
{
|
||||
AviUtlCompatMap.Default.TryResolve("方向ブラー", AviUtlEngine.AviUtl, out var mapping);
|
||||
Assert.True(mapping.TryGetParameter("角度", out var parameter));
|
||||
Assert.Equal(45d, parameter.Transform(45d));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Resolve_BothEngine_MatchesAviUtl2()
|
||||
{
|
||||
Assert.True(AviUtlCompatMap.Default.TryResolve("クロマキー", AviUtlEngine.AviUtl2, out var mapping));
|
||||
Assert.Equal("ChromaKeyEffect", mapping.TargetType);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Resolve_UndeclaredEffect_DoesNotResolve()
|
||||
{
|
||||
Assert.False(AviUtlCompatMap.Default.TryResolve("存在しないエフェクト", AviUtlEngine.AviUtl, out _));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void ResolveTarget_DefaultsToAviUtl()
|
||||
{
|
||||
Assert.Equal(AviUtlEngine.AviUtl, AviUtlCompatMap.ResolveTarget("obj.effect(\"ぼかし\", \"範囲\", 10)"));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void ResolveTarget_DirectiveSelectsAviUtl2()
|
||||
{
|
||||
Assert.Equal(AviUtlEngine.AviUtl2, AviUtlCompatMap.ResolveTarget("--!aviutl2\nobj.effect(\"ぼかし\", \"範囲\", 10)"));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Engine_BothIncludesEveryTarget()
|
||||
{
|
||||
Assert.True(AviUtlEngine.Both.Includes(AviUtlEngine.AviUtl));
|
||||
Assert.True(AviUtlEngine.Both.Includes(AviUtlEngine.AviUtl2));
|
||||
Assert.False(AviUtlEngine.AviUtl.Includes(AviUtlEngine.AviUtl2));
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,196 @@
|
||||
using System.Globalization;
|
||||
using LuaScript.Compat;
|
||||
|
||||
namespace LuaScript.Tests
|
||||
{
|
||||
public class AviUtlGlobalEquivalenceTests
|
||||
{
|
||||
private static readonly double[] s_bitValues =
|
||||
[
|
||||
0d, 1d, 5d, 8d, 3d, 12d, 6d, 25d, 11d, 91d,
|
||||
-1d, -5d, -91d, 255d, 256d, 65535d,
|
||||
0.4d, 0.5d, 0.6d, 2.5d, 2.51d, -2.5d, -2.51d,
|
||||
2147483647d, -2147483648d, 2147483648d, -2147483649d, 1e18d, -1e18d,
|
||||
];
|
||||
|
||||
private static readonly double[] s_shiftValues =
|
||||
[
|
||||
0d, 1d, 2d, 3d, 5d, 31d, 32d, 33d, 63d,
|
||||
-1d, -2d, -5d, -31d, -32d, -33d, -63d,
|
||||
0.5d, 1.5d, -0.5d,
|
||||
];
|
||||
|
||||
[Fact]
|
||||
public void BitFunctions_MatchDocumentedExamples()
|
||||
{
|
||||
var lane = new MoonSharpLane();
|
||||
Assert.Equal(11d, lane.Number("OR(8,3)"));
|
||||
Assert.Equal(4d, lane.Number("AND(12,6)"));
|
||||
Assert.Equal(18d, lane.Number("XOR(25,11)"));
|
||||
Assert.Equal(40d, lane.Number("SHIFT(5,3)"));
|
||||
Assert.Equal(22d, lane.Number("SHIFT(91,-2)"));
|
||||
Assert.Equal(-2147483648d, lane.Number("SHIFT(1,31)"));
|
||||
Assert.Equal(2d, lane.Number("OR(2.50,0)"));
|
||||
Assert.Equal(3d, lane.Number("OR(2.51,0)"));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void ColorFunctions_MatchDocumentedExamples()
|
||||
{
|
||||
var lane = new MoonSharpLane();
|
||||
Assert.Equal(0x40C0FF, lane.Number("RGB(64,192,255)"));
|
||||
Assert.Equal([0d, 128d, 255d], lane.Tuple("RGB(0x0080FF)", 3));
|
||||
Assert.Equal(0xFFFF00, lane.Number("HSV(60,100,100)"));
|
||||
Assert.Equal([210d, 100d, 100d], lane.Tuple("HSV(0x0080FF)", 3));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Interpolation_UsesTimeRatio()
|
||||
{
|
||||
var lane = new MoonSharpLane { TimeRatio = 0.25 };
|
||||
Assert.Equal(
|
||||
AviUtlGlobalFunctions.RgbInterpolate(64, 192, 255, 128, 64, 0, 0.25),
|
||||
lane.Number("RGB(64,192,255,128,64,0)"));
|
||||
Assert.Equal(
|
||||
AviUtlGlobalFunctions.HsvInterpolate(30, 50, 100, 120, 100, 50, 0.25),
|
||||
lane.Number("HSV(30,50,100,120,100,50)"));
|
||||
|
||||
lane.TimeRatio = 0d;
|
||||
Assert.Equal(lane.Number("RGB(64,192,255)"), lane.Number("RGB(64,192,255,128,64,0)"));
|
||||
lane.TimeRatio = 1d;
|
||||
Assert.Equal(lane.Number("RGB(128,64,0)"), lane.Number("RGB(64,192,255,128,64,0)"));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void MoonSharp_MatchesOracle_OverBitMatrix()
|
||||
{
|
||||
var lane = new MoonSharpLane();
|
||||
foreach (var a in s_bitValues)
|
||||
{
|
||||
foreach (var b in s_bitValues)
|
||||
{
|
||||
string sa = Format(a);
|
||||
string sb = Format(b);
|
||||
Assert.Equal(AviUtlGlobalFunctions.BitOr(a, b), lane.Number($"OR({sa},{sb})"));
|
||||
Assert.Equal(AviUtlGlobalFunctions.BitAnd(a, b), lane.Number($"AND({sa},{sb})"));
|
||||
Assert.Equal(AviUtlGlobalFunctions.BitXor(a, b), lane.Number($"XOR({sa},{sb})"));
|
||||
}
|
||||
foreach (var shift in s_shiftValues)
|
||||
{
|
||||
Assert.Equal(
|
||||
AviUtlGlobalFunctions.BitShift(a, shift),
|
||||
lane.Number($"SHIFT({Format(a)},{Format(shift)})"));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void MoonSharp_MatchesOracle_OverColorMatrix()
|
||||
{
|
||||
var lane = new MoonSharpLane();
|
||||
double[] channels = [0d, 1d, 63.5d, 64d, 128d, 254.9d, 255d, 256d, -1d, 1000d];
|
||||
foreach (var r in channels)
|
||||
{
|
||||
foreach (var g in channels)
|
||||
{
|
||||
Assert.Equal(
|
||||
AviUtlGlobalFunctions.RgbCompose(r, g, 200d),
|
||||
lane.Number($"RGB({Format(r)},{Format(g)},200)"));
|
||||
}
|
||||
}
|
||||
|
||||
double[] hues = [0d, 30d, 59.9d, 60d, 60.1d, 120d, 180d, 209.88d, 240d, 300d, 359.9d, 360d, 361d, -30d, 720.5d];
|
||||
double[] ratios = [0d, 25d, 50d, 99.5d, 100d, 101d, -5d];
|
||||
foreach (var h in hues)
|
||||
{
|
||||
foreach (var s in ratios)
|
||||
{
|
||||
Assert.Equal(
|
||||
AviUtlGlobalFunctions.HsvCompose(h, s, 80d),
|
||||
lane.Number($"HSV({Format(h)},{Format(s)},80)"));
|
||||
}
|
||||
}
|
||||
|
||||
int[] colors = [0x000000, 0xFFFFFF, 0x0080FF, 0x40C0FF, 0xFF0000, 0x00FF00, 0x0000FF, 0x123456, 0x808080, 0xFFFF00];
|
||||
foreach (var color in colors)
|
||||
{
|
||||
AviUtlGlobalFunctions.RgbComponents(color, out int r, out int g, out int b);
|
||||
Assert.Equal([r, g, b], lane.Tuple($"RGB({color})", 3));
|
||||
AviUtlGlobalFunctions.HsvComponents(color, out int h, out int s, out int v);
|
||||
Assert.Equal([h, s, v], lane.Tuple($"HSV({color})", 3));
|
||||
}
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void LuaJitShim_MatchesOracle()
|
||||
{
|
||||
var jit = new LuaJitLane();
|
||||
Assert.True(jit.Available, "native/luajit.exe must be present");
|
||||
|
||||
var expressions = new List<string>();
|
||||
var expected = new List<double>();
|
||||
|
||||
foreach (var a in s_bitValues)
|
||||
{
|
||||
foreach (var b in s_bitValues)
|
||||
{
|
||||
expressions.Add($"OR({Format(a)},{Format(b)})");
|
||||
expected.Add(AviUtlGlobalFunctions.BitOr(a, b));
|
||||
expressions.Add($"AND({Format(a)},{Format(b)})");
|
||||
expected.Add(AviUtlGlobalFunctions.BitAnd(a, b));
|
||||
expressions.Add($"XOR({Format(a)},{Format(b)})");
|
||||
expected.Add(AviUtlGlobalFunctions.BitXor(a, b));
|
||||
}
|
||||
foreach (var shift in s_shiftValues)
|
||||
{
|
||||
expressions.Add($"SHIFT({Format(a)},{Format(shift)})");
|
||||
expected.Add(AviUtlGlobalFunctions.BitShift(a, shift));
|
||||
}
|
||||
}
|
||||
|
||||
double[] channels = [0d, 1d, 63.5d, 64d, 128d, 254.9d, 255d, 256d, -1d, 1000d];
|
||||
foreach (var r in channels)
|
||||
{
|
||||
expressions.Add($"RGB({Format(r)},192,255)");
|
||||
expected.Add(AviUtlGlobalFunctions.RgbCompose(r, 192d, 255d));
|
||||
}
|
||||
|
||||
double[] hues = [0d, 30d, 59.9d, 60d, 60.1d, 120d, 180d, 209.88d, 240d, 300d, 359.9d, 360d, 361d, -30d, 720.5d];
|
||||
foreach (var h in hues)
|
||||
{
|
||||
expressions.Add($"HSV({Format(h)},100,100)");
|
||||
expected.Add(AviUtlGlobalFunctions.HsvCompose(h, 100d, 100d));
|
||||
}
|
||||
|
||||
int[] colors = [0x000000, 0xFFFFFF, 0x0080FF, 0x40C0FF, 0xFF0000, 0x00FF00, 0x0000FF, 0x123456, 0x808080, 0xFFFF00];
|
||||
foreach (var color in colors)
|
||||
{
|
||||
for (int component = 1; component <= 3; component++)
|
||||
{
|
||||
expressions.Add($"select({component}, RGB({color}))");
|
||||
AviUtlGlobalFunctions.RgbComponents(color, out int r, out int g, out int b);
|
||||
expected.Add(component == 1 ? r : component == 2 ? g : b);
|
||||
expressions.Add($"select({component}, HSV({color}))");
|
||||
AviUtlGlobalFunctions.HsvComponents(color, out int h, out int s, out int v);
|
||||
expected.Add(component == 1 ? h : component == 2 ? s : v);
|
||||
}
|
||||
}
|
||||
|
||||
expressions.Add("(function() aviutl_set_time_ratio(0.25) return RGB(64,192,255,128,64,0) end)()");
|
||||
expected.Add(AviUtlGlobalFunctions.RgbInterpolate(64, 192, 255, 128, 64, 0, 0.25));
|
||||
expressions.Add("(function() aviutl_set_time_ratio(0.75) return HSV(30,50,100,120,100,50) end)()");
|
||||
expected.Add(AviUtlGlobalFunctions.HsvInterpolate(30, 50, 100, 120, 100, 50, 0.75));
|
||||
|
||||
var results = jit.Eval(expressions);
|
||||
Assert.True(results.Length >= expressions.Count, "luajit runner returned fewer results than expressions");
|
||||
for (int i = 0; i < expressions.Count; i++)
|
||||
{
|
||||
double actual = double.Parse(results[i], CultureInfo.InvariantCulture);
|
||||
Assert.True(expected[i] == actual, $"{expressions[i]}: expected {expected[i]}, got {actual}");
|
||||
}
|
||||
}
|
||||
|
||||
private static string Format(double value) =>
|
||||
value.ToString("R", CultureInfo.InvariantCulture);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,63 @@
|
||||
using System.Numerics;
|
||||
using LuaScript;
|
||||
|
||||
namespace LuaScript.Tests
|
||||
{
|
||||
public class DrawPolyMathTests
|
||||
{
|
||||
private static double[] Quad(
|
||||
double x0, double y0, double x1, double y1,
|
||||
double x2, double y2, double x3, double y3,
|
||||
double u0, double v0, double u1, double v1,
|
||||
double u2, double v2, double u3, double v3,
|
||||
double alpha)
|
||||
=> [x0, y0, 0, x1, y1, 0, x2, y2, 0, x3, y3, 0, u0, v0, u1, v1, u2, v2, u3, v3, alpha];
|
||||
|
||||
[Fact]
|
||||
public void TrySolveAffine_MapsUvCornersToQuad()
|
||||
{
|
||||
var poly = Quad(
|
||||
10, 20, 18, 20, 18, 32, 10, 32,
|
||||
0, 0, 4, 0, 4, 4, 0, 4, 1);
|
||||
|
||||
Assert.True(DrawPolyMath.TrySolveAffine(poly, out var m));
|
||||
|
||||
AssertMaps(m, 0, 0, 10, 20);
|
||||
AssertMaps(m, 4, 0, 18, 20);
|
||||
AssertMaps(m, 4, 4, 18, 32);
|
||||
AssertMaps(m, 0, 4, 10, 32);
|
||||
AssertMaps(m, 2, 2, 14, 26);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void TrySolveAffine_HandlesRotatedQuad()
|
||||
{
|
||||
var poly = Quad(
|
||||
0, 0, 0, 10, -10, 10, -10, 0,
|
||||
0, 0, 10, 0, 10, 10, 0, 10, 1);
|
||||
|
||||
Assert.True(DrawPolyMath.TrySolveAffine(poly, out var m));
|
||||
|
||||
AssertMaps(m, 0, 0, 0, 0);
|
||||
AssertMaps(m, 10, 0, 0, 10);
|
||||
AssertMaps(m, 0, 10, -10, 0);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void TrySolveAffine_ReturnsFalse_OnDegenerateUv()
|
||||
{
|
||||
var poly = Quad(
|
||||
0, 0, 10, 0, 10, 10, 0, 10,
|
||||
0, 0, 0, 0, 0, 0, 0, 0, 1);
|
||||
|
||||
Assert.False(DrawPolyMath.TrySolveAffine(poly, out _));
|
||||
}
|
||||
|
||||
private static void AssertMaps(Matrix3x2 m, float u, float v, float x, float y)
|
||||
{
|
||||
var p = Vector2.Transform(new Vector2(u, v), m);
|
||||
Assert.Equal(x, p.X, 3);
|
||||
Assert.Equal(y, p.Y, 3);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,82 @@
|
||||
using System.Numerics;
|
||||
|
||||
namespace LuaScript.Tests
|
||||
{
|
||||
public class DrawTransformTests
|
||||
{
|
||||
[Fact]
|
||||
public void TryResolve_Affine_MapsSourceCenterToOffset()
|
||||
{
|
||||
var command = new DrawCommand(10d, 20d, 0d, 1d, 1d, 0d);
|
||||
|
||||
Assert.True(DrawTransform.TryResolve(command, 4, 6, out var matrix));
|
||||
|
||||
var mapped = Vector2.Transform(new Vector2(2f, 3f), matrix);
|
||||
Assert.Equal(10d, mapped.X, 3);
|
||||
Assert.Equal(20d, mapped.Y, 3);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void TryResolve_Affine_AppliesZoomAndAspect()
|
||||
{
|
||||
var command = new DrawCommand(0d, 0d, 0d, 2d, 1d, 0.5d);
|
||||
|
||||
Assert.True(DrawTransform.TryResolve(command, 2, 2, out var matrix));
|
||||
|
||||
var mapped = Vector2.Transform(new Vector2(2f, 2f), matrix);
|
||||
Assert.Equal(3d, mapped.X, 3);
|
||||
Assert.Equal(1d, mapped.Y, 3);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void TryResolve_Affine_ClampsAspect()
|
||||
{
|
||||
var command = new DrawCommand(0d, 0d, 0d, 2d, 1d, -3d);
|
||||
|
||||
Assert.False(DrawTransform.TryResolve(command, 2, 2, out _));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void TryResolve_ZeroZoom_Fails()
|
||||
{
|
||||
var command = new DrawCommand(0d, 0d, 0d, 0d, 1d, 0d);
|
||||
|
||||
Assert.False(DrawTransform.TryResolve(command, 2, 2, out _));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void TryResolve_NegativeZoom_Mirrors()
|
||||
{
|
||||
var command = new DrawCommand(0d, 0d, 0d, -1d, 1d, 0d);
|
||||
|
||||
Assert.True(DrawTransform.TryResolve(command, 2, 2, out var matrix));
|
||||
|
||||
var mapped = Vector2.Transform(new Vector2(2f, 2f), matrix);
|
||||
Assert.Equal(-1d, mapped.X, 3);
|
||||
Assert.Equal(-1d, mapped.Y, 3);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void TryResolve_IdentityPoly_YieldsIdentity()
|
||||
{
|
||||
double[] poly =
|
||||
[
|
||||
0, 0, 0, 2, 0, 0, 2, 2, 0, 0, 2, 0,
|
||||
0, 0, 2, 0, 2, 2, 0, 2,
|
||||
1,
|
||||
];
|
||||
var command = new DrawCommand(0d, 0d, 0d, 1d, 1d, 0d, poly);
|
||||
|
||||
Assert.True(DrawTransform.TryResolve(command, 2, 2, out var matrix));
|
||||
Assert.Equal(Matrix3x2.Identity, matrix);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void TryResolve_DegeneratePoly_Fails()
|
||||
{
|
||||
var command = new DrawCommand(0d, 0d, 0d, 1d, 1d, 0d, new double[DrawPolyMath.Length]);
|
||||
|
||||
Assert.False(DrawTransform.TryResolve(command, 2, 2, out _));
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,137 @@
|
||||
using System;
|
||||
|
||||
namespace LuaScript.Tests
|
||||
{
|
||||
public class FallbackCompositorTests
|
||||
{
|
||||
private sealed class RecordingCompositor : IBufferCompositor
|
||||
{
|
||||
public int Calls;
|
||||
public byte[]? LastDst;
|
||||
public byte[]? LastSrc;
|
||||
public DrawCommand LastCommand;
|
||||
|
||||
public bool TryCompose(byte[] dst, int dstW, int dstH, byte[] src, int srcW, int srcH, in DrawCommand command)
|
||||
{
|
||||
Calls++;
|
||||
LastDst = dst;
|
||||
LastSrc = src;
|
||||
LastCommand = command;
|
||||
return true;
|
||||
}
|
||||
}
|
||||
|
||||
private sealed class RejectingCompositor : IBufferCompositor
|
||||
{
|
||||
public int Calls;
|
||||
|
||||
public bool TryCompose(byte[] dst, int dstW, int dstH, byte[] src, int srcW, int srcH, in DrawCommand command)
|
||||
{
|
||||
Calls++;
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
private sealed class ThrowingCompositor : IBufferCompositor
|
||||
{
|
||||
public int Calls;
|
||||
|
||||
public bool TryCompose(byte[] dst, int dstW, int dstH, byte[] src, int srcW, int srcH, in DrawCommand command)
|
||||
{
|
||||
Calls++;
|
||||
throw new InvalidOperationException("device lost");
|
||||
}
|
||||
}
|
||||
|
||||
private sealed class DisposableCompositor : IBufferCompositor, IDisposable
|
||||
{
|
||||
public bool Disposed;
|
||||
|
||||
public bool TryCompose(byte[] dst, int dstW, int dstH, byte[] src, int srcW, int srcH, in DrawCommand command) => true;
|
||||
|
||||
public void Dispose() => Disposed = true;
|
||||
}
|
||||
|
||||
private static readonly DrawCommand Command = new(1d, 2d, 0d, 1d, 1d, 0d);
|
||||
|
||||
[Fact]
|
||||
public void TryCompose_PrimarySucceeds_FallbackIsNotUsed()
|
||||
{
|
||||
var primary = new RecordingCompositor();
|
||||
var fallback = new RecordingCompositor();
|
||||
var compositor = new FallbackCompositor(primary, fallback);
|
||||
|
||||
Assert.True(compositor.TryCompose(new byte[4], 1, 1, new byte[4], 1, 1, Command));
|
||||
|
||||
Assert.Equal(1, primary.Calls);
|
||||
Assert.Equal(0, fallback.Calls);
|
||||
Assert.False(compositor.IsDegraded);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void TryCompose_PrimaryThrows_FallbackReceivesSameArguments()
|
||||
{
|
||||
var primary = new ThrowingCompositor();
|
||||
var fallback = new RecordingCompositor();
|
||||
Exception? reported = null;
|
||||
var compositor = new FallbackCompositor(primary, fallback, ex => reported = ex);
|
||||
var dst = new byte[4];
|
||||
var src = new byte[4];
|
||||
|
||||
Assert.True(compositor.TryCompose(dst, 1, 1, src, 1, 1, Command));
|
||||
|
||||
Assert.Equal(1, fallback.Calls);
|
||||
Assert.Same(dst, fallback.LastDst);
|
||||
Assert.Same(src, fallback.LastSrc);
|
||||
Assert.Equal(Command, fallback.LastCommand);
|
||||
Assert.IsType<InvalidOperationException>(reported);
|
||||
Assert.True(compositor.IsDegraded);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void TryCompose_AfterFailure_PrimaryIsSkippedAndDegradationReportedOnce()
|
||||
{
|
||||
var primary = new ThrowingCompositor();
|
||||
var fallback = new RecordingCompositor();
|
||||
int reports = 0;
|
||||
var compositor = new FallbackCompositor(primary, fallback, _ => reports++);
|
||||
|
||||
compositor.TryCompose(new byte[4], 1, 1, new byte[4], 1, 1, Command);
|
||||
compositor.TryCompose(new byte[4], 1, 1, new byte[4], 1, 1, Command);
|
||||
|
||||
Assert.Equal(1, primary.Calls);
|
||||
Assert.Equal(2, fallback.Calls);
|
||||
Assert.Equal(1, reports);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void TryCompose_PrimaryRejects_FallbackIsUsedWithoutDegradation()
|
||||
{
|
||||
var primary = new RejectingCompositor();
|
||||
var fallback = new RecordingCompositor();
|
||||
int reports = 0;
|
||||
var compositor = new FallbackCompositor(primary, fallback, _ => reports++);
|
||||
|
||||
Assert.True(compositor.TryCompose(new byte[4], 1, 1, new byte[4], 1, 1, Command));
|
||||
Assert.True(compositor.TryCompose(new byte[4], 1, 1, new byte[4], 1, 1, Command));
|
||||
|
||||
Assert.Equal(2, primary.Calls);
|
||||
Assert.Equal(2, fallback.Calls);
|
||||
Assert.Equal(0, reports);
|
||||
Assert.False(compositor.IsDegraded);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Dispose_DisposesDisposableLanes()
|
||||
{
|
||||
var primary = new DisposableCompositor();
|
||||
var fallback = new DisposableCompositor();
|
||||
var compositor = new FallbackCompositor(primary, fallback);
|
||||
|
||||
compositor.Dispose();
|
||||
|
||||
Assert.True(primary.Disposed);
|
||||
Assert.True(fallback.Disposed);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,251 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using LuaScript.Engine;
|
||||
using LuaScript.Engine.Kernel;
|
||||
using MoonSharp.Interpreter;
|
||||
|
||||
namespace LuaScript.Tests
|
||||
{
|
||||
public sealed class KernelCpuEquivalenceTests
|
||||
{
|
||||
private const int Width = 23;
|
||||
private const int Height = 17;
|
||||
|
||||
[Theory]
|
||||
[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")]
|
||||
[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 l=0.298912*r+0.586611*g+0.114478*b obj.setpixel(x,y,l,l,l,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,b,g,r,a) end end")]
|
||||
[InlineData("for x=0,obj.w-1 do for y=0,obj.h-1 do local r,g,b,a=obj.getpixel(x,y) obj.setpixel(x,y,255-r,255-g,255-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*r/255,g*g/255,b*b/255,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,255*math.pow(r/255,0.45),255*math.pow(g/255,0.45),255*math.pow(b/255,0.45),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 obj.setpixel(x,y,v>128 and 255 or 0,v>128 and 255 or 0,v>128 and 255 or 0,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.min(255,r+50),math.max(0,g-50),math.floor(b/16)*16,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%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")]
|
||||
public void CpuKernelMatchesMoonSharp(string script)
|
||||
{
|
||||
var fields = new Dictionary<string, double> { ["w"] = Width, ["h"] = Height };
|
||||
AssertEquivalent(script, fields, new Dictionary<string, double>());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void CpuKernelMatchesMoonSharpWithUniforms()
|
||||
{
|
||||
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) " +
|
||||
"obj.setpixel(x,y,r*obj.track0/100,g*math.sin(time)*0.5+g*0.5,b+x/obj.w*obj.track1,a) end end";
|
||||
var fields = new Dictionary<string, double> { ["w"] = Width, ["h"] = Height, ["track0"] = 73d, ["track1"] = 40d };
|
||||
var globals = new Dictionary<string, double> { ["time"] = 1.2345d };
|
||||
AssertEquivalent(script, fields, globals);
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[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")]
|
||||
[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 g=pd:get(i+2) local b=pd:get(i+3) local l=0.298912*r+0.586611*g+0.114478*b pd:set(i+1,l) pd:set(i+2,l) pd:set(i+3,l) 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,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")]
|
||||
public void GetPixelDataKernelMatchesMoonSharp(string script)
|
||||
{
|
||||
var fields = new Dictionary<string, double> { ["w"] = Width, ["h"] = Height, ["track0"] = 73d };
|
||||
AssertEquivalent(script, fields, new Dictionary<string, double>());
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[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+4,128) 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,pd:get(i+5)) 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+1)*pd.width+x)*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 pd:set(i+1,pd:get(i+3)) pd:set(i+2,pd:get(i+2)) pd:set(i+3,pd:get(i+1)) 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 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")]
|
||||
public void GetPixelDataNonKernelScriptsAreRejected(string script)
|
||||
{
|
||||
Assert.Null(KernelExtractor.TryExtract(script));
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[InlineData("--!cpu\nfor 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,255-r,255-g,255-b,a) end end")]
|
||||
[InlineData("--!gpu\nfor y=0,obj.h-1 do for x=0,obj.w-1 do local r,g,b,a=obj.getpixel(x,y) local l=0.298912*r+0.586611*g+0.114478*b obj.setpixel(x,y,l,l,l,a) end end")]
|
||||
[InlineData("--!cpu\r\nfor 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,y/obj.h*255,b,a) end end")]
|
||||
public void DirectivePrefixedKernelsMatchMoonSharp(string script)
|
||||
{
|
||||
var fields = new Dictionary<string, double> { ["w"] = Width, ["h"] = Height };
|
||||
AssertEquivalent(script, fields, new Dictionary<string, double>());
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[InlineData("--!cpu", "Cpu")]
|
||||
[InlineData("--!gpu", "Gpu")]
|
||||
public void DirectivePrefixedKernelsRouteToAcceleratedLane(string directive, string expected)
|
||||
{
|
||||
string script = directive + "\nfor 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";
|
||||
|
||||
Assert.True(ScriptDirective.TryResolveExplicit(script, out var kind));
|
||||
Assert.Equal(expected, kind.ToString());
|
||||
Assert.NotNull(KernelExtractor.TryExtract(script));
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[InlineData("obj.setpixel(0,0,0,0,0,0)")]
|
||||
[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")]
|
||||
public void NonKernelScriptsAreRejected(string script)
|
||||
{
|
||||
Assert.Null(KernelExtractor.TryExtract(script));
|
||||
}
|
||||
|
||||
private static void AssertEquivalent(string script, Dictionary<string, double> fields, Dictionary<string, double> globals)
|
||||
{
|
||||
var program = KernelExtractor.TryExtract(script);
|
||||
Assert.NotNull(program);
|
||||
|
||||
byte[] source = CreateBuffer(20260629);
|
||||
byte[] oracle = (byte[])source.Clone();
|
||||
byte[] candidate = (byte[])source.Clone();
|
||||
|
||||
RunMoonSharp(script, oracle, fields, globals);
|
||||
|
||||
double[] uniforms = new double[KernelUniforms.Count];
|
||||
foreach (var (name, value) in fields)
|
||||
if (KernelUniforms.TryResolveMember("obj", name, out var uniform))
|
||||
uniforms[(int)uniform] = value;
|
||||
foreach (var (name, value) in globals)
|
||||
if (KernelUniforms.TryResolveGlobal(name, out var uniform))
|
||||
uniforms[(int)uniform] = value;
|
||||
|
||||
CpuKernelCompiler.Compile(program!).Execute(candidate, Width, Height, uniforms);
|
||||
|
||||
Assert.Equal(oracle, candidate);
|
||||
}
|
||||
|
||||
private static byte[] CreateBuffer(int seed)
|
||||
{
|
||||
var random = new Random(seed);
|
||||
var buffer = new byte[Width * Height * 4];
|
||||
random.NextBytes(buffer);
|
||||
return buffer;
|
||||
}
|
||||
|
||||
private static void RunMoonSharp(string script, byte[] buffer, Dictionary<string, double> fields, Dictionary<string, double> globals)
|
||||
{
|
||||
var engine = new Script(CoreModules.Basic | CoreModules.Math | CoreModules.Bit32);
|
||||
engine.Globals.Get("math").Table["fmod"] = DynValue.NewCallback((_, a) =>
|
||||
DynValue.NewNumber(a[0].Number % a[1].Number));
|
||||
var obj = new Table(engine);
|
||||
foreach (var (name, value) in fields)
|
||||
obj[name] = value;
|
||||
foreach (var (name, value) in globals)
|
||||
engine.Globals[name] = value;
|
||||
|
||||
obj["getpixel"] = DynValue.NewCallback((_, args) =>
|
||||
{
|
||||
int x = (int)(args[0].CastToNumber() ?? 0d);
|
||||
int y = (int)(args[1].CastToNumber() ?? 0d);
|
||||
var (r, g, b, a) = GetPixel(buffer, x, y);
|
||||
return DynValue.NewTuple(
|
||||
DynValue.NewNumber(r), DynValue.NewNumber(g), DynValue.NewNumber(b), DynValue.NewNumber(a));
|
||||
});
|
||||
|
||||
obj["setpixel"] = DynValue.NewCallback((_, args) =>
|
||||
{
|
||||
int x = (int)(args[0].CastToNumber() ?? 0d);
|
||||
int y = (int)(args[1].CastToNumber() ?? 0d);
|
||||
double r = args[2].CastToNumber() ?? 0d;
|
||||
double g = args[3].CastToNumber() ?? 0d;
|
||||
double b = args[4].CastToNumber() ?? 0d;
|
||||
double a = args.Count > 5 ? args[5].CastToNumber() ?? 255d : 255d;
|
||||
SetPixel(buffer, x, y, r, g, b, a);
|
||||
return DynValue.Void;
|
||||
});
|
||||
|
||||
obj["getpixeldata"] = DynValue.NewCallback((_, _) =>
|
||||
{
|
||||
var pd = new Table(engine);
|
||||
pd["width"] = Width;
|
||||
pd["height"] = Height;
|
||||
pd["get"] = DynValue.NewCallback((_, a) =>
|
||||
DynValue.NewNumber(PixelDataGet(buffer, (int)(a[1].CastToNumber() ?? 0d))));
|
||||
pd["set"] = DynValue.NewCallback((_, a) =>
|
||||
{
|
||||
PixelDataSet(buffer, (int)(a[1].CastToNumber() ?? 0d), a[2].CastToNumber() ?? 0d);
|
||||
return DynValue.Void;
|
||||
});
|
||||
return DynValue.NewTable(pd);
|
||||
});
|
||||
|
||||
engine.Globals["obj"] = obj;
|
||||
engine.DoString(script);
|
||||
}
|
||||
|
||||
private static double PixelDataGet(byte[] buffer, int index)
|
||||
{
|
||||
int zeroBased = index - 1;
|
||||
if ((uint)zeroBased >= (uint)buffer.Length)
|
||||
return 0d;
|
||||
int pixel = Math.DivRem(zeroBased, 4, out int channel);
|
||||
int p = pixel * 4;
|
||||
double a = buffer[p + 3];
|
||||
if (channel == 3)
|
||||
return a;
|
||||
if (a <= 0d)
|
||||
return 0d;
|
||||
double scale = 255d / a;
|
||||
return channel switch
|
||||
{
|
||||
0 => Math.Clamp(buffer[p + 2] * scale, 0d, 255d),
|
||||
1 => Math.Clamp(buffer[p + 1] * scale, 0d, 255d),
|
||||
_ => Math.Clamp(buffer[p] * scale, 0d, 255d),
|
||||
};
|
||||
}
|
||||
|
||||
private static void PixelDataSet(byte[] buffer, int index, double value)
|
||||
{
|
||||
int zeroBased = index - 1;
|
||||
if ((uint)zeroBased >= (uint)buffer.Length)
|
||||
return;
|
||||
int pixel = Math.DivRem(zeroBased, 4, out int channel);
|
||||
int p = pixel * 4;
|
||||
double clamped = Math.Clamp(value, 0d, 255d);
|
||||
double a = buffer[p + 3];
|
||||
double premultiplied = clamped * (a / 255d);
|
||||
int byteOffset = channel switch { 0 => 2, 1 => 1, _ => 0 };
|
||||
buffer[p + byteOffset] = (byte)Math.Clamp(premultiplied, 0d, 255d);
|
||||
}
|
||||
|
||||
private static (double r, double g, double b, double a) GetPixel(byte[] buffer, int x, int y)
|
||||
{
|
||||
if ((uint)x >= Width || (uint)y >= Height)
|
||||
return (0d, 0d, 0d, 0d);
|
||||
|
||||
int p = (y * Width + x) * 4;
|
||||
double alpha = buffer[p + 3];
|
||||
if (alpha <= 0d)
|
||||
return (0d, 0d, 0d, 0d);
|
||||
|
||||
double scale = 255d / alpha;
|
||||
return (
|
||||
Math.Clamp(buffer[p + 2] * scale, 0d, 255d),
|
||||
Math.Clamp(buffer[p + 1] * scale, 0d, 255d),
|
||||
Math.Clamp(buffer[p] * scale, 0d, 255d),
|
||||
alpha);
|
||||
}
|
||||
|
||||
private static void SetPixel(byte[] buffer, int x, int y, double r, double g, double b, double a)
|
||||
{
|
||||
if ((uint)x >= Width || (uint)y >= Height)
|
||||
return;
|
||||
|
||||
int p = (y * Width + x) * 4;
|
||||
double k = Math.Clamp(a, 0d, 255d) / 255d;
|
||||
buffer[p] = (byte)Math.Clamp(b * k, 0d, 255d);
|
||||
buffer[p + 1] = (byte)Math.Clamp(g * k, 0d, 255d);
|
||||
buffer[p + 2] = (byte)Math.Clamp(r * k, 0d, 255d);
|
||||
buffer[p + 3] = (byte)Math.Clamp(a, 0d, 255d);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,79 @@
|
||||
using LuaScript.Engine.Kernel;
|
||||
|
||||
namespace LuaScript.Tests
|
||||
{
|
||||
public sealed class KernelHlslEmitterTests
|
||||
{
|
||||
private const string Grayscale =
|
||||
"for y=0,obj.h-1 do for x=0,obj.w-1 do local r,g,b,a=obj.getpixel(x,y) " +
|
||||
"local l=0.298912*r+0.586611*g+0.114478*b obj.setpixel(x,y,l,l,l,a) end end";
|
||||
|
||||
private const string Threshold =
|
||||
"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 255 or 0,g,b,a) end end";
|
||||
|
||||
private const string WithTrack =
|
||||
"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*obj.track0/100,g,b,a) end end";
|
||||
|
||||
[Fact]
|
||||
public void EmitsValidShaderSkeleton()
|
||||
{
|
||||
string hlsl = HlslKernelEmitter.Emit(Extract(Grayscale));
|
||||
|
||||
Assert.Contains("Texture2D InputTexture : register(t0);", hlsl);
|
||||
Assert.Contains("cbuffer constants : register(b0)", hlsl);
|
||||
Assert.Contains("float4 main(float4 pos : SV_POSITION", hlsl);
|
||||
Assert.Contains("InputTexture.Sample(InputSampler, uv.xy)", hlsl);
|
||||
Assert.Contains("return float4(oR, oG, oB, oA);", hlsl);
|
||||
Assert.Contains("inR", hlsl);
|
||||
Assert.Contains("inG", hlsl);
|
||||
Assert.Contains("inB", hlsl);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void CoordinatesUsePixelCenterOrigin()
|
||||
{
|
||||
string hlsl = HlslKernelEmitter.Emit(Extract(Grayscale));
|
||||
Assert.Contains(" - 0.5;", hlsl);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void OutputTruncatesToMatchCpuKernel()
|
||||
{
|
||||
string hlsl = HlslKernelEmitter.Emit(Extract(Grayscale));
|
||||
Assert.Contains("float oR = floor(clamp((", hlsl);
|
||||
Assert.Contains("float oA = floor(outA) / 255.0;", hlsl);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void ThresholdEmitsTernary()
|
||||
{
|
||||
string hlsl = HlslKernelEmitter.Emit(Extract(Threshold));
|
||||
Assert.Contains(" ? (", hlsl);
|
||||
Assert.Contains(" > ", hlsl);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void UniformReferencesUsePackedConstantBuffer()
|
||||
{
|
||||
string hlsl = HlslKernelEmitter.Emit(Extract(WithTrack));
|
||||
int index = (int)KernelUniform.Track0;
|
||||
Assert.Contains($"uniforms[{index / 4}].{"xyzw"[index % 4]}", hlsl);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void EmissionIsDeterministic()
|
||||
{
|
||||
var program = Extract(Grayscale);
|
||||
Assert.Equal(HlslKernelEmitter.Emit(program), HlslKernelEmitter.Emit(program));
|
||||
}
|
||||
|
||||
private static KernelProgram Extract(string script)
|
||||
{
|
||||
var program = KernelExtractor.TryExtract(script);
|
||||
Assert.NotNull(program);
|
||||
return program!;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,122 @@
|
||||
using System;
|
||||
using System.Runtime.Intrinsics;
|
||||
using System.Threading;
|
||||
using LuaScript.Engine.Kernel;
|
||||
|
||||
namespace LuaScript.Tests
|
||||
{
|
||||
public class KernelSimdAdoptionTests
|
||||
{
|
||||
private const int CalibrationExecutes = 8;
|
||||
|
||||
private static CpuKernel.RowDelegate Path(Action onCall, int delayMs) =>
|
||||
(buffer, rowBase, xStart, xEnd, y, uniforms) =>
|
||||
{
|
||||
onCall();
|
||||
if (delayMs > 0)
|
||||
Thread.Sleep(delayMs);
|
||||
};
|
||||
|
||||
[Fact]
|
||||
public void SlowerBlock_SettlesOnScalar()
|
||||
{
|
||||
if (!Vector256.IsHardwareAccelerated)
|
||||
return;
|
||||
|
||||
int rowCalls = 0, blockCalls = 0;
|
||||
var kernel = new CpuKernel(Path(() => rowCalls++, 0), Path(() => blockCalls++, 5));
|
||||
var buffer = new byte[8 * 4];
|
||||
var uniforms = new double[1];
|
||||
|
||||
for (int i = 0; i < CalibrationExecutes - 1; i++)
|
||||
kernel.Execute(buffer, 8, 1, uniforms);
|
||||
Assert.Null(kernel.BlockAdopted);
|
||||
|
||||
kernel.Execute(buffer, 8, 1, uniforms);
|
||||
Assert.True(kernel.BlockAdopted.HasValue);
|
||||
Assert.False(kernel.BlockAdopted.Value);
|
||||
|
||||
int blockCallsAtDecision = blockCalls;
|
||||
int rowCallsAtDecision = rowCalls;
|
||||
for (int i = 0; i < 5; i++)
|
||||
kernel.Execute(buffer, 8, 1, uniforms);
|
||||
|
||||
Assert.Equal(blockCallsAtDecision, blockCalls);
|
||||
Assert.Equal(rowCallsAtDecision + 5, rowCalls);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void FasterBlock_SettlesOnBlock()
|
||||
{
|
||||
if (!Vector256.IsHardwareAccelerated)
|
||||
return;
|
||||
|
||||
int rowCalls = 0, blockCalls = 0;
|
||||
var kernel = new CpuKernel(Path(() => rowCalls++, 5), Path(() => blockCalls++, 0));
|
||||
var buffer = new byte[8 * 4];
|
||||
var uniforms = new double[1];
|
||||
|
||||
for (int i = 0; i < CalibrationExecutes; i++)
|
||||
kernel.Execute(buffer, 8, 1, uniforms);
|
||||
Assert.True(kernel.BlockAdopted.HasValue);
|
||||
Assert.True(kernel.BlockAdopted.Value);
|
||||
|
||||
int rowCallsAtDecision = rowCalls;
|
||||
int blockCallsAtDecision = blockCalls;
|
||||
for (int i = 0; i < 5; i++)
|
||||
kernel.Execute(buffer, 8, 1, uniforms);
|
||||
|
||||
Assert.Equal(rowCallsAtDecision, rowCalls);
|
||||
Assert.Equal(blockCallsAtDecision + 5, blockCalls);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void CalibrationAlternatesBothPaths()
|
||||
{
|
||||
if (!Vector256.IsHardwareAccelerated)
|
||||
return;
|
||||
|
||||
int rowCalls = 0, blockCalls = 0;
|
||||
var kernel = new CpuKernel(Path(() => rowCalls++, 0), Path(() => blockCalls++, 0));
|
||||
var buffer = new byte[8 * 4];
|
||||
var uniforms = new double[1];
|
||||
|
||||
for (int i = 0; i < CalibrationExecutes; i++)
|
||||
kernel.Execute(buffer, 8, 1, uniforms);
|
||||
|
||||
Assert.Equal(CalibrationExecutes / 2, rowCalls);
|
||||
Assert.Equal(CalibrationExecutes / 2, blockCalls);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void WithoutBlock_RunsScalarWithoutDecision()
|
||||
{
|
||||
int rowCalls = 0;
|
||||
var kernel = new CpuKernel(Path(() => rowCalls++, 0), null);
|
||||
var buffer = new byte[8 * 4];
|
||||
var uniforms = new double[1];
|
||||
|
||||
for (int i = 0; i < CalibrationExecutes + 2; i++)
|
||||
kernel.Execute(buffer, 8, 1, uniforms);
|
||||
|
||||
Assert.Null(kernel.BlockAdopted);
|
||||
Assert.Equal(CalibrationExecutes + 2, rowCalls);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void BlockPath_UsesScalarRowForRemainder()
|
||||
{
|
||||
if (!Vector256.IsHardwareAccelerated)
|
||||
return;
|
||||
|
||||
int rowCalls = 0, blockCalls = 0;
|
||||
var kernel = new CpuKernel(Path(() => rowCalls++, 0), Path(() => blockCalls++, 0));
|
||||
var buffer = new byte[10 * 4];
|
||||
var uniforms = new double[1];
|
||||
|
||||
kernel.Execute(buffer, 10, 1, uniforms);
|
||||
Assert.Equal(1, blockCalls);
|
||||
Assert.Equal(1, rowCalls);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,96 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using LuaScript.Engine.Kernel;
|
||||
|
||||
namespace LuaScript.Tests
|
||||
{
|
||||
public sealed class KernelSimdEquivalenceTests
|
||||
{
|
||||
private const int Width = 24;
|
||||
private const int Height = 17;
|
||||
|
||||
[Theory]
|
||||
[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")]
|
||||
[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,255-r,255-g,255-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,b,g,r,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 l=0.298912*r+0.586611*g+0.114478*b obj.setpixel(x,y,l,l,l,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*r/255,g*g/255,b*b/255,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,x/obj.w*255,y/obj.h*255,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 obj.setpixel(x,y,v>128 and 255 or 0,v>128 and 255 or 0,v>128 and 255 or 0,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%64,math.abs(g-128),math.sqrt(b*255),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.floor(r/16)*16,math.ceil(g/16)*16,-b+255,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*obj.track0/100,g+x/obj.w*obj.track1,b,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,255-r) pd:set(i+2,g*g/255) pd:set(i+3,b) 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>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")]
|
||||
public void SimdBlockMatchesScalarRow(string script)
|
||||
{
|
||||
var program = KernelExtractor.TryExtract(script);
|
||||
Assert.NotNull(program);
|
||||
|
||||
var block = SimdKernelCompiler.TryCompile(program!);
|
||||
Assert.NotNull(block);
|
||||
|
||||
var scalarRow = CpuKernelCompiler.CompileRow(program!);
|
||||
double[] uniforms = BuildUniforms();
|
||||
|
||||
byte[] source = CreateBuffer();
|
||||
byte[] scalar = (byte[])source.Clone();
|
||||
byte[] simd = (byte[])source.Clone();
|
||||
|
||||
int stride = Width * 4;
|
||||
for (int y = 0; y < Height; y++)
|
||||
{
|
||||
scalarRow(scalar, y * stride, 0, Width, y, uniforms);
|
||||
block!(simd, y * stride, 0, Width, y, uniforms);
|
||||
}
|
||||
|
||||
Assert.Equal(scalar, simd);
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[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.min(255,r+50),math.max(0,g-50),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,255*math.pow(r/255,0.45),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^2/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) obj.setpixel(x,y,255*math.sin(r/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) obj.setpixel(x,y,math.atan2(r,g),b,a,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),g,b,a) end end")]
|
||||
public void SimdRejectsNonVectorizableKernels(string script)
|
||||
{
|
||||
var program = KernelExtractor.TryExtract(script);
|
||||
Assert.NotNull(program);
|
||||
Assert.Null(SimdKernelCompiler.TryCompile(program!));
|
||||
}
|
||||
|
||||
private static double[] BuildUniforms()
|
||||
{
|
||||
double[] uniforms = new double[KernelUniforms.Count];
|
||||
var fields = new Dictionary<string, double> { ["w"] = Width, ["h"] = Height, ["track0"] = 73d, ["track1"] = 40d };
|
||||
foreach (var (name, value) in fields)
|
||||
if (KernelUniforms.TryResolveMember("obj", name, out var uniform))
|
||||
uniforms[(int)uniform] = value;
|
||||
return uniforms;
|
||||
}
|
||||
|
||||
private static byte[] CreateBuffer()
|
||||
{
|
||||
var random = new Random(20260702);
|
||||
var buffer = new byte[Width * Height * 4];
|
||||
random.NextBytes(buffer);
|
||||
|
||||
void SetPixel(int i, byte b, byte g, byte r, byte a)
|
||||
{
|
||||
buffer[i * 4 + 0] = b; buffer[i * 4 + 1] = g; buffer[i * 4 + 2] = r; buffer[i * 4 + 3] = a;
|
||||
}
|
||||
|
||||
SetPixel(0, 0, 0, 0, 0);
|
||||
SetPixel(1, 255, 255, 255, 255);
|
||||
SetPixel(2, 1, 0, 0, 1);
|
||||
SetPixel(3, 200, 128, 64, 254);
|
||||
SetPixel(4, 0, 0, 0, 128);
|
||||
SetPixel(5, 255, 255, 255, 2);
|
||||
return buffer;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -4,6 +4,7 @@
|
||||
<TargetFramework>net10.0</TargetFramework>
|
||||
<ImplicitUsings>enable</ImplicitUsings>
|
||||
<Nullable>enable</Nullable>
|
||||
<AllowUnsafeBlocks>true</AllowUnsafeBlocks>
|
||||
<IsPackable>false</IsPackable>
|
||||
</PropertyGroup>
|
||||
|
||||
@@ -27,15 +28,50 @@
|
||||
<Compile Include="..\LuaScript\Compat\MoonSharpBit32.cs" Link="Linked\MoonSharpBit32.cs" />
|
||||
<Compile Include="..\LuaScript\Compat\Bit32.cs" Link="Linked\Bit32.cs" />
|
||||
<Compile Include="..\LuaScript\Engine\ScriptEngineKind.cs" Link="Linked\ScriptEngineKind.cs" />
|
||||
<Compile Include="..\LuaScript\Engine\ScriptDirective.cs" Link="Linked\ScriptDirective.cs" />
|
||||
<Compile Include="..\LuaScript\Engine\NativeProtocol.cs" Link="Linked\NativeProtocol.cs" />
|
||||
<Compile Include="..\LuaScript\Engine\ProcessJobObject.cs" Link="Linked\ProcessJobObject.cs" />
|
||||
<Compile Include="..\LuaScript\Engine\PixelRegionAccess.cs" Link="Linked\PixelRegionAccess.cs" />
|
||||
<Compile Include="..\LuaScript\Engine\LuaJitWorker.cs" Link="Linked\LuaJitWorker.cs" />
|
||||
<Compile Include="..\LuaScript\DrawCommand.cs" Link="Linked\DrawCommand.cs" />
|
||||
<Compile Include="..\LuaScript\DrawPolyMath.cs" Link="Linked\DrawPolyMath.cs" />
|
||||
<Compile Include="..\LuaScript\DrawTransform.cs" Link="Linked\DrawTransform.cs" />
|
||||
<Compile Include="..\LuaScript\IBufferCompositor.cs" Link="Linked\IBufferCompositor.cs" />
|
||||
<Compile Include="..\LuaScript\SoftwareCompositor.cs" Link="Linked\SoftwareCompositor.cs" />
|
||||
<Compile Include="..\LuaScript\FallbackCompositor.cs" Link="Linked\FallbackCompositor.cs" />
|
||||
<Compile Include="..\LuaScript\SynchronizedCompositor.cs" Link="Linked\SynchronizedCompositor.cs" />
|
||||
<Compile Include="..\LuaScript\Anchor\LuaAnchorPoint.cs" Link="Linked\LuaAnchorPoint.cs" />
|
||||
<Compile Include="..\LuaScript\Anchor\AnchorSupport.cs" Link="Linked\AnchorSupport.cs" />
|
||||
<Compile Include="..\LuaScript\SceneObjectInfo.cs" Link="Linked\SceneObjectInfo.cs" />
|
||||
<Compile Include="..\LuaScript\SceneObjectQuery.cs" Link="Linked\SceneObjectQuery.cs" />
|
||||
<Compile Include="..\LuaScript\SceneSharedValues.cs" Link="Linked\SceneSharedValues.cs" />
|
||||
<Compile Include="..\LuaScript\SceneTableRegistrar.cs" Link="Linked\SceneTableRegistrar.cs" />
|
||||
<Compile Include="..\LuaScript\AnimTableRegistrar.cs" Link="Linked\AnimTableRegistrar.cs" />
|
||||
<Compile Include="..\LuaScript\AviUtlGlobalRegistrar.cs" Link="Linked\AviUtlGlobalRegistrar.cs" />
|
||||
<Compile Include="..\LuaScript\Compat\AviUtlGlobalFunctions.cs" Link="Linked\AviUtlGlobalFunctions.cs" />
|
||||
<Compile Include="..\LuaScript\Diagnostics\DebugOutput.cs" Link="Linked\DebugOutput.cs" />
|
||||
<Compile Include="..\LuaScript\Compat\AviUtlScript.cs" Link="Linked\AviUtlScript.cs" />
|
||||
<Compile Include="..\LuaScript\Compat\ScriptParserHelper.cs" Link="Linked\ScriptParserHelper.cs" />
|
||||
<Compile Include="..\LuaScript\Compat\AviUtlParameterLayout.cs" Link="Linked\AviUtlParameterLayout.cs" />
|
||||
<Compile Include="..\LuaScript\Compat\ScriptParameterUsage.cs" Link="Linked\ScriptParameterUsage.cs" />
|
||||
<Compile Include="..\LuaScript\Compat\AviUtlRandom.cs" Link="Linked\AviUtlRandom.cs" />
|
||||
<Compile Include="..\LuaScript\Compat\AviUtlEngine.cs" Link="Linked\AviUtlEngine.cs" />
|
||||
<Compile Include="..\LuaScript\Compat\AviUtlEffectMapping.cs" Link="Linked\AviUtlEffectMapping.cs" />
|
||||
<Compile Include="..\LuaScript\Compat\AviUtlCompatMap.cs" Link="Linked\AviUtlCompatMap.cs" />
|
||||
<EmbeddedResource Include="..\LuaScript\Compat\AviUtlCompatMap.xml" Link="Linked\AviUtlCompatMap.xml" />
|
||||
<Compile Include="..\LuaScript\Compat\FigureRenderer.cs" Link="Linked\FigureRenderer.cs" />
|
||||
<Compile Include="..\LuaScript\Engine\Kernel\KernelUnsupportedException.cs" Link="Linked\Kernel\KernelUnsupportedException.cs" />
|
||||
<Compile Include="..\LuaScript\Engine\Kernel\LuaToken.cs" Link="Linked\Kernel\LuaToken.cs" />
|
||||
<Compile Include="..\LuaScript\Engine\Kernel\LuaLexer.cs" Link="Linked\Kernel\LuaLexer.cs" />
|
||||
<Compile Include="..\LuaScript\Engine\Kernel\LuaAst.cs" Link="Linked\Kernel\LuaAst.cs" />
|
||||
<Compile Include="..\LuaScript\Engine\Kernel\LuaParser.cs" Link="Linked\Kernel\LuaParser.cs" />
|
||||
<Compile Include="..\LuaScript\Engine\Kernel\KernelUniform.cs" Link="Linked\Kernel\KernelUniform.cs" />
|
||||
<Compile Include="..\LuaScript\Engine\Kernel\KernelModel.cs" Link="Linked\Kernel\KernelModel.cs" />
|
||||
<Compile Include="..\LuaScript\Engine\Kernel\KernelExtractor.cs" Link="Linked\Kernel\KernelExtractor.cs" />
|
||||
<Compile Include="..\LuaScript\Engine\Kernel\CpuKernel.cs" Link="Linked\Kernel\CpuKernel.cs" />
|
||||
<Compile Include="..\LuaScript\Engine\Kernel\CpuKernelCompiler.cs" Link="Linked\Kernel\CpuKernelCompiler.cs" />
|
||||
<Compile Include="..\LuaScript\Engine\Kernel\SimdKernelCompiler.cs" Link="Linked\Kernel\SimdKernelCompiler.cs" />
|
||||
<Compile Include="..\LuaScript\Engine\Kernel\HlslKernelEmitter.cs" Link="Linked\Kernel\HlslKernelEmitter.cs" />
|
||||
</ItemGroup>
|
||||
|
||||
</Project>
|
||||
@@ -7,6 +7,8 @@ namespace LuaScript.Tests
|
||||
{
|
||||
private readonly Script _script;
|
||||
|
||||
public double TimeRatio { get; set; }
|
||||
|
||||
public MoonSharpLane()
|
||||
{
|
||||
_script = new Script(
|
||||
@@ -22,6 +24,8 @@ namespace LuaScript.Tests
|
||||
var anim = new Table(_script);
|
||||
AnimTableRegistrar.RegisterFunctions(anim);
|
||||
_script.Globals["anim"] = anim;
|
||||
|
||||
AviUtlGlobalRegistrar.RegisterFunctions(_script.Globals, () => TimeRatio);
|
||||
}
|
||||
|
||||
public DynValue Run(string code) => _script.DoString(code);
|
||||
|
||||
ファイル差分が大きすぎるため表示されません。
差分を読み込み
@@ -0,0 +1,78 @@
|
||||
using System.Text;
|
||||
|
||||
namespace LuaScript.Tests
|
||||
{
|
||||
public class SceneSharedValuesTests
|
||||
{
|
||||
[Fact]
|
||||
public void Set_Get_RoundTripsAllKinds()
|
||||
{
|
||||
var store = new SceneSharedValues();
|
||||
store.Set("num", SceneValue.FromNumber(1.5));
|
||||
store.Set("text", SceneValue.FromString("あいう"));
|
||||
store.Set("flagTrue", SceneValue.FromBoolean(true));
|
||||
store.Set("flagFalse", SceneValue.FromBoolean(false));
|
||||
|
||||
Assert.Equal(SceneValue.FromNumber(1.5), store.Get("num"));
|
||||
Assert.Equal(SceneValue.FromString("あいう"), store.Get("text"));
|
||||
Assert.Equal(SceneValue.FromBoolean(true), store.Get("flagTrue"));
|
||||
Assert.Equal(SceneValue.FromBoolean(false), store.Get("flagFalse"));
|
||||
Assert.Equal(SceneValue.Nil, store.Get("missing"));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Set_Nil_RemovesValue()
|
||||
{
|
||||
var store = new SceneSharedValues();
|
||||
store.Set("key", SceneValue.FromNumber(1d));
|
||||
store.Set("key", SceneValue.Nil);
|
||||
Assert.Equal(SceneValue.Nil, store.Get("key"));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Set_OverwritesValueAndKind()
|
||||
{
|
||||
var store = new SceneSharedValues();
|
||||
store.Set("key", SceneValue.FromNumber(1d));
|
||||
store.Set("key", SceneValue.FromString("s"));
|
||||
Assert.Equal(SceneValue.FromString("s"), store.Get("key"));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void ForScene_IsolatesScenes_AndSharesWithinScene()
|
||||
{
|
||||
string sceneA = Guid.NewGuid().ToString();
|
||||
string sceneB = Guid.NewGuid().ToString();
|
||||
|
||||
SceneSharedValues.ForScene(sceneA).Set("key", SceneValue.FromNumber(1d));
|
||||
|
||||
Assert.Equal(SceneValue.FromNumber(1d), SceneSharedValues.ForScene(sceneA).Get("key"));
|
||||
Assert.Equal(SceneValue.Nil, SceneSharedValues.ForScene(sceneB).Get("key"));
|
||||
Assert.Same(SceneSharedValues.ForScene(sceneA), SceneSharedValues.ForScene(sceneA));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void LongText_IsTruncatedAtUtf8Boundary()
|
||||
{
|
||||
var store = new SceneSharedValues();
|
||||
string text = new string('あ', 2000);
|
||||
store.Set("key", SceneValue.FromString(text));
|
||||
|
||||
var stored = store.Get("key");
|
||||
Assert.Equal(SceneValueKind.String, stored.Kind);
|
||||
Assert.True(Encoding.UTF8.GetByteCount(stored.Text!) <= SceneSharedValues.MaxTextBytes);
|
||||
Assert.Equal(SceneSharedValues.MaxTextBytes / 3, stored.Text!.Length);
|
||||
Assert.StartsWith(stored.Text, text, StringComparison.Ordinal);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void LongName_IsTruncatedConsistentlyOnSetAndGet()
|
||||
{
|
||||
var store = new SceneSharedValues();
|
||||
string name = new string('k', SceneSharedValues.MaxNameBytes + 100);
|
||||
store.Set(name, SceneValue.FromNumber(7d));
|
||||
Assert.Equal(SceneValue.FromNumber(7d), store.Get(name));
|
||||
Assert.Equal(SceneValue.FromNumber(7d), store.Get(name[..SceneSharedValues.MaxNameBytes]));
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,87 @@
|
||||
using MoonSharp.Interpreter;
|
||||
|
||||
namespace LuaScript.Tests
|
||||
{
|
||||
public class SceneTableRegistrarTests
|
||||
{
|
||||
private static (Script script, SceneSharedValues store) CreateScript()
|
||||
{
|
||||
var script = new Script(CoreModules.Basic | CoreModules.Math | CoreModules.String | CoreModules.Table);
|
||||
var store = new SceneSharedValues();
|
||||
var scene = new Table(script);
|
||||
SceneTableRegistrar.RegisterFunctions(scene, store.Get, store.Set);
|
||||
script.Globals["scene"] = scene;
|
||||
return (script, store);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Set_StoresAllSupportedKinds()
|
||||
{
|
||||
var (script, store) = CreateScript();
|
||||
script.DoString(
|
||||
"scene.set('num', 4.25) " +
|
||||
"scene.set('text', 'こんにちは') " +
|
||||
"scene.set('flag', false)");
|
||||
|
||||
Assert.Equal(SceneValue.FromNumber(4.25), store.Get("num"));
|
||||
Assert.Equal(SceneValue.FromString("こんにちは"), store.Get("text"));
|
||||
Assert.Equal(SceneValue.FromBoolean(false), store.Get("flag"));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Set_NilOrMissingValue_Removes()
|
||||
{
|
||||
var (script, store) = CreateScript();
|
||||
store.Set("a", SceneValue.FromNumber(1d));
|
||||
store.Set("b", SceneValue.FromNumber(2d));
|
||||
script.DoString("scene.set('a', nil) scene.set('b')");
|
||||
Assert.Equal(SceneValue.Nil, store.Get("a"));
|
||||
Assert.Equal(SceneValue.Nil, store.Get("b"));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Set_UnsupportedTypesAndNames_AreIgnored()
|
||||
{
|
||||
var (script, store) = CreateScript();
|
||||
store.Set("keep", SceneValue.FromNumber(9d));
|
||||
script.DoString(
|
||||
"scene.set('keep', {}) " +
|
||||
"scene.set('fn', function() end) " +
|
||||
"scene.set(12, 'x') " +
|
||||
"scene.set()");
|
||||
|
||||
Assert.Equal(SceneValue.FromNumber(9d), store.Get("keep"));
|
||||
Assert.Equal(SceneValue.Nil, store.Get("fn"));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Get_ReturnsStoredValuesWithLuaTypes()
|
||||
{
|
||||
var (script, store) = CreateScript();
|
||||
store.Set("num", SceneValue.FromNumber(-8.5));
|
||||
store.Set("text", SceneValue.FromString("v"));
|
||||
store.Set("flag", SceneValue.FromBoolean(true));
|
||||
|
||||
var result = script.DoString(
|
||||
"return scene.get('num'), scene.get('text'), scene.get('flag'), scene.get('missing'), scene.get(1)");
|
||||
|
||||
Assert.Equal(DataType.Tuple, result.Type);
|
||||
Assert.Equal(-8.5d, result.Tuple[0].Number);
|
||||
Assert.Equal("v", result.Tuple[1].String);
|
||||
Assert.True(result.Tuple[2].Boolean);
|
||||
Assert.Equal(DataType.Nil, result.Tuple[3].Type);
|
||||
Assert.Equal(DataType.Nil, result.Tuple[4].Type);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void SetAndGet_RoundTripWithinScript()
|
||||
{
|
||||
var (script, _) = CreateScript();
|
||||
var result = script.DoString(
|
||||
"scene.set('counter', (scene.get('counter') or 0) + 1) " +
|
||||
"scene.set('counter', (scene.get('counter') or 0) + 1) " +
|
||||
"return scene.get('counter')");
|
||||
Assert.Equal(2d, result.Number);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -31,16 +31,21 @@ namespace LuaScript.Tests
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[InlineData("obj.rz = time * 90", "MoonSharp")]
|
||||
[InlineData(null, "MoonSharp")]
|
||||
[InlineData("", "MoonSharp")]
|
||||
[InlineData("obj.rz = time * 90", "Native")]
|
||||
[InlineData("local r,g,b,a = obj.getpixel(0,0)", "Native")]
|
||||
[InlineData("obj.setpixel(0,0,255,0,0)", "Native")]
|
||||
[InlineData("local pd = obj.getpixeldata()", "Native")]
|
||||
[InlineData("--!moonsharp\nobj.setpixel(0,0,1,1,1)", "MoonSharp")]
|
||||
[InlineData("--!native\nobj.rz = 1", "Native")]
|
||||
[InlineData("obj.load(\"figure\", \"円\", 0xff0000, 100)", "MoonSharp")]
|
||||
[InlineData("obj.load(\"figure\", \"円\", 0xff0000, 100)\nlocal r = obj.getpixel(0,0)", "MoonSharp")]
|
||||
[InlineData("--!native\nobj.load(\"figure\", \"円\", 0xff0000, 100)", "Native")]
|
||||
public void ResolveAuto_RoutesPixelScriptsToNative(string script, string expected)
|
||||
[InlineData("--!gpu\nfunction pixel() end", "Gpu")]
|
||||
[InlineData("--!cpu\nfunction pixel() end", "Cpu")]
|
||||
[InlineData("obj.load(\"figure\", \"円\", 0xff0000, 100)", "Native")]
|
||||
[InlineData("obj.draw()", "Native")]
|
||||
[InlineData("obj.setoption('blend', 1)", "Native")]
|
||||
[InlineData("obj.setanchor('pos', 2)", "Native")]
|
||||
public void ResolveAuto_DefaultsToNative(string? script, string expected)
|
||||
{
|
||||
Assert.Equal(expected, ScriptDirective.ResolveAuto(script).ToString());
|
||||
}
|
||||
|
||||
@@ -0,0 +1,68 @@
|
||||
using LuaScript.Compat;
|
||||
|
||||
namespace LuaScript.Tests
|
||||
{
|
||||
public sealed class ScriptParameterUsageTests
|
||||
{
|
||||
[Theory]
|
||||
[InlineData("if obj.check0 then obj.alpha = 0 end", 0)]
|
||||
[InlineData("local v = obj.check3 and 255 or 0", 3)]
|
||||
[InlineData("obj . check1 = true", 1)]
|
||||
public void DetectsReferencedCheck(string script, int index)
|
||||
{
|
||||
var usage = ScriptParameterUsage.Detect(script);
|
||||
for (int i = 0; i < 4; i++)
|
||||
Assert.Equal(i == index, usage.Check(i));
|
||||
Assert.False(usage.Color);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void DetectsReferencedColor()
|
||||
{
|
||||
var usage = ScriptParameterUsage.Detect("obj.rz = color / 1000");
|
||||
Assert.True(usage.Color);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void DetectsMultipleChecks()
|
||||
{
|
||||
var usage = ScriptParameterUsage.Detect("local a = obj.check0\nlocal b = obj.check2");
|
||||
Assert.True(usage.Check0);
|
||||
Assert.False(usage.Check1);
|
||||
Assert.True(usage.Check2);
|
||||
Assert.False(usage.Check3);
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[InlineData("obj.setoption(\"color\", 1)")]
|
||||
[InlineData("-- color and obj.check0 in a comment")]
|
||||
[InlineData("local colorful = 1")]
|
||||
[InlineData("scene.color = 0")]
|
||||
public void IgnoresStringsCommentsAndUnrelatedNames(string script)
|
||||
{
|
||||
var usage = ScriptParameterUsage.Detect(script);
|
||||
Assert.False(usage.Color);
|
||||
for (int i = 0; i < 4; i++)
|
||||
Assert.False(usage.Check(i));
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[InlineData(null)]
|
||||
[InlineData("")]
|
||||
[InlineData("local s = \"unterminated")]
|
||||
public void ReturnsNoneForEmptyOrInvalid(string? script)
|
||||
{
|
||||
var usage = ScriptParameterUsage.Detect(script);
|
||||
Assert.False(usage.Color);
|
||||
Assert.False(usage.Check0);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void DoesNotDetectOutOfRangeCheck()
|
||||
{
|
||||
var usage = ScriptParameterUsage.Detect("local a = obj.check4");
|
||||
for (int i = 0; i < 4; i++)
|
||||
Assert.False(usage.Check(i));
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,142 @@
|
||||
using LuaScript;
|
||||
|
||||
namespace LuaScript.Tests
|
||||
{
|
||||
public class SoftwareCompositorTests
|
||||
{
|
||||
private static byte[] Solid(int w, int h, byte b, byte g, byte r, byte a)
|
||||
{
|
||||
var buffer = new byte[w * h * 4];
|
||||
for (int i = 0; i < w * h; i++)
|
||||
{
|
||||
buffer[i * 4] = b;
|
||||
buffer[i * 4 + 1] = g;
|
||||
buffer[i * 4 + 2] = r;
|
||||
buffer[i * 4 + 3] = a;
|
||||
}
|
||||
return buffer;
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void DrawInto_NearestOpaque_BlitsSinglePixel()
|
||||
{
|
||||
var dst = new byte[3 * 3 * 4];
|
||||
var src = Solid(1, 1, 255, 255, 255, 255);
|
||||
|
||||
SoftwareCompositor.DrawInto(dst, 3, 3, src, 1, 1, 1.5, 1.5, 1d, 0d, 1d, linear: false);
|
||||
|
||||
int center = (1 * 3 + 1) * 4;
|
||||
Assert.Equal(255, dst[center]);
|
||||
Assert.Equal(255, dst[center + 1]);
|
||||
Assert.Equal(255, dst[center + 2]);
|
||||
Assert.Equal(255, dst[center + 3]);
|
||||
|
||||
Assert.Equal(0, dst[0]);
|
||||
Assert.Equal(0, dst[(0 * 3 + 0) * 4 + 3]);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void DrawInto_HalfAlphaOverOpaque_BlendsPremultiplied()
|
||||
{
|
||||
var dst = Solid(1, 1, 0, 0, 0, 255);
|
||||
var src = Solid(1, 1, 255, 255, 255, 255);
|
||||
|
||||
SoftwareCompositor.DrawInto(dst, 1, 1, src, 1, 1, 0.5, 0.5, 1d, 0d, 0.5, linear: false);
|
||||
|
||||
Assert.Equal(127, dst[0]);
|
||||
Assert.Equal(127, dst[1]);
|
||||
Assert.Equal(127, dst[2]);
|
||||
Assert.Equal(255, dst[3]);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void DrawInto_OutOfBounds_LeavesDestinationUnchanged()
|
||||
{
|
||||
var dst = new byte[2 * 2 * 4];
|
||||
var src = Solid(1, 1, 255, 255, 255, 255);
|
||||
|
||||
SoftwareCompositor.DrawInto(dst, 2, 2, src, 1, 1, 100d, 100d, 1d, 0d, 1d, linear: false);
|
||||
|
||||
foreach (var value in dst)
|
||||
Assert.Equal(0, value);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void TryCompose_AffineCommand_MatchesDrawInto()
|
||||
{
|
||||
var src = Solid(1, 1, 10, 20, 30, 255);
|
||||
var actual = new byte[3 * 3 * 4];
|
||||
var expected = new byte[3 * 3 * 4];
|
||||
var command = new DrawCommand(1.5, 1.5, 0d, 1d, 1d, 0d, Antialias: 0d);
|
||||
|
||||
Assert.True(SoftwareCompositor.Instance.TryCompose(actual, 3, 3, src, 1, 1, command));
|
||||
SoftwareCompositor.DrawInto(expected, 3, 3, src, 1, 1, 1.5, 1.5, 1d, 0d, 1d, linear: false);
|
||||
|
||||
Assert.Equal(expected, actual);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void TryCompose_PolyCommand_MatchesDrawPolyInto()
|
||||
{
|
||||
var src = Solid(2, 2, 40, 50, 60, 255);
|
||||
var actual = new byte[2 * 2 * 4];
|
||||
var expected = new byte[2 * 2 * 4];
|
||||
double[] poly =
|
||||
[
|
||||
0, 0, 0, 2, 0, 0, 2, 2, 0, 0, 2, 0,
|
||||
0, 0, 2, 0, 2, 2, 0, 2,
|
||||
1,
|
||||
];
|
||||
var command = new DrawCommand(0d, 0d, 0d, 1d, 1d, 0d, poly, Antialias: 0d);
|
||||
|
||||
Assert.True(SoftwareCompositor.Instance.TryCompose(actual, 2, 2, src, 2, 2, command));
|
||||
SoftwareCompositor.DrawPolyInto(expected, 2, 2, src, 2, 2, poly, 1d, linear: false);
|
||||
|
||||
Assert.Equal(expected, actual);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void TryCompose_AntialiasCommand_UsesLinearSampling()
|
||||
{
|
||||
var src = new byte[2 * 1 * 4];
|
||||
src[3] = 255;
|
||||
src[4] = 255;
|
||||
src[5] = 255;
|
||||
src[6] = 255;
|
||||
src[7] = 255;
|
||||
var actual = new byte[4 * 1 * 4];
|
||||
var expected = new byte[4 * 1 * 4];
|
||||
var command = new DrawCommand(2d, 0.5, 0d, 2d, 1d, 0d, Antialias: 1d);
|
||||
|
||||
Assert.True(SoftwareCompositor.Instance.TryCompose(actual, 4, 1, src, 2, 1, command));
|
||||
SoftwareCompositor.DrawInto(expected, 4, 1, src, 2, 1, 2d, 0.5, 2d, 0d, 1d, linear: true);
|
||||
|
||||
Assert.Equal(expected, actual);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void DrawPolyInto_IdentityAffine_CopiesSource()
|
||||
{
|
||||
var src = new byte[2 * 2 * 4];
|
||||
for (int i = 0; i < 4; i++)
|
||||
{
|
||||
src[i * 4] = (byte)(i + 1);
|
||||
src[i * 4 + 1] = (byte)(i + 10);
|
||||
src[i * 4 + 2] = (byte)(i + 20);
|
||||
src[i * 4 + 3] = 255;
|
||||
}
|
||||
var dst = new byte[2 * 2 * 4];
|
||||
|
||||
double[] poly =
|
||||
[
|
||||
0, 0, 0, 2, 0, 0, 2, 2, 0, 0, 2, 0,
|
||||
0, 0, 2, 0, 2, 2, 0, 2,
|
||||
1,
|
||||
];
|
||||
|
||||
SoftwareCompositor.DrawPolyInto(dst, 2, 2, src, 2, 2, poly, 1d, linear: false);
|
||||
|
||||
Assert.Equal(src, dst);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,88 @@
|
||||
using System;
|
||||
using System.Threading;
|
||||
|
||||
namespace LuaScript.Tests
|
||||
{
|
||||
public class SynchronizedCompositorTests
|
||||
{
|
||||
private sealed class GateObservingCompositor(SemaphoreSlim gate, bool result) : IBufferCompositor
|
||||
{
|
||||
public int Calls;
|
||||
public int GateCountDuringCompose = -1;
|
||||
|
||||
public bool TryCompose(byte[] dst, int dstW, int dstH, byte[] src, int srcW, int srcH, in DrawCommand command)
|
||||
{
|
||||
Calls++;
|
||||
GateCountDuringCompose = gate.CurrentCount;
|
||||
return result;
|
||||
}
|
||||
}
|
||||
|
||||
private sealed class ThrowingCompositor : IBufferCompositor
|
||||
{
|
||||
public bool TryCompose(byte[] dst, int dstW, int dstH, byte[] src, int srcW, int srcH, in DrawCommand command) =>
|
||||
throw new InvalidOperationException("device lost");
|
||||
}
|
||||
|
||||
private sealed class DisposableCompositor : IBufferCompositor, IDisposable
|
||||
{
|
||||
public bool Disposed;
|
||||
|
||||
public bool TryCompose(byte[] dst, int dstW, int dstH, byte[] src, int srcW, int srcH, in DrawCommand command) => true;
|
||||
|
||||
public void Dispose() => Disposed = true;
|
||||
}
|
||||
|
||||
private static readonly DrawCommand Command = new(0d, 0d, 0d, 1d, 1d, 0d);
|
||||
|
||||
[Fact]
|
||||
public void TryCompose_HoldsGateDuringComposeAndReleasesAfter()
|
||||
{
|
||||
using var gate = new SemaphoreSlim(1, 1);
|
||||
var inner = new GateObservingCompositor(gate, result: true);
|
||||
var compositor = new SynchronizedCompositor(inner, gate);
|
||||
|
||||
Assert.True(compositor.TryCompose(new byte[4], 1, 1, new byte[4], 1, 1, Command));
|
||||
|
||||
Assert.Equal(1, inner.Calls);
|
||||
Assert.Equal(0, inner.GateCountDuringCompose);
|
||||
Assert.Equal(1, gate.CurrentCount);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void TryCompose_PassesRejectionThrough()
|
||||
{
|
||||
using var gate = new SemaphoreSlim(1, 1);
|
||||
var inner = new GateObservingCompositor(gate, result: false);
|
||||
var compositor = new SynchronizedCompositor(inner, gate);
|
||||
|
||||
Assert.False(compositor.TryCompose(new byte[4], 1, 1, new byte[4], 1, 1, Command));
|
||||
Assert.Equal(1, gate.CurrentCount);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void TryCompose_ReleasesGateWhenInnerThrows()
|
||||
{
|
||||
using var gate = new SemaphoreSlim(1, 1);
|
||||
var compositor = new SynchronizedCompositor(new ThrowingCompositor(), gate);
|
||||
|
||||
Assert.Throws<InvalidOperationException>(() =>
|
||||
compositor.TryCompose(new byte[4], 1, 1, new byte[4], 1, 1, Command));
|
||||
Assert.Equal(1, gate.CurrentCount);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Dispose_DisposesInnerButNotGate()
|
||||
{
|
||||
using var gate = new SemaphoreSlim(1, 1);
|
||||
var inner = new DisposableCompositor();
|
||||
var compositor = new SynchronizedCompositor(inner, gate);
|
||||
|
||||
compositor.Dispose();
|
||||
|
||||
Assert.True(inner.Disposed);
|
||||
gate.Wait();
|
||||
gate.Release();
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,100 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Collections.Immutable;
|
||||
|
||||
namespace LuaScript.Anchor
|
||||
{
|
||||
internal enum AnchorConnection
|
||||
{
|
||||
None,
|
||||
Line,
|
||||
Loop,
|
||||
Star,
|
||||
Arm,
|
||||
}
|
||||
|
||||
internal readonly record struct AnchorOptions(AnchorConnection Connection, bool Is3D);
|
||||
|
||||
internal readonly record struct AnchorRequestData(string Group, int Count, AnchorConnection Connection, bool Is3D);
|
||||
|
||||
internal static class AnchorSupport
|
||||
{
|
||||
public const int MaxAnchors = 32;
|
||||
public const string TrackGroup = "track";
|
||||
|
||||
public static int ClampCount(int count) => Math.Clamp(count, 0, MaxAnchors);
|
||||
|
||||
public static void ApplyOption(string option, ref AnchorConnection connection, ref bool is3D)
|
||||
{
|
||||
switch (option)
|
||||
{
|
||||
case "line": connection = AnchorConnection.Line; break;
|
||||
case "loop": connection = AnchorConnection.Loop; break;
|
||||
case "star": connection = AnchorConnection.Star; break;
|
||||
case "arm": connection = AnchorConnection.Arm; break;
|
||||
case "xyz": is3D = true; break;
|
||||
}
|
||||
}
|
||||
|
||||
public static (double X, double Y) DefaultPosition(int index)
|
||||
{
|
||||
int col = index % 8;
|
||||
int row = index / 8;
|
||||
return ((col - 3.5) * 60d, (row - 1.5) * 60d);
|
||||
}
|
||||
|
||||
public static void ResolvePosition(IReadOnlyList<LuaAnchorPoint>? source, string group, int index,
|
||||
out double x, out double y, out double z)
|
||||
{
|
||||
if (source is not null)
|
||||
{
|
||||
for (int i = 0; i < source.Count; i++)
|
||||
{
|
||||
var a = source[i];
|
||||
if (a.Index == index && string.Equals(a.Group, group, StringComparison.Ordinal))
|
||||
{
|
||||
x = a.X;
|
||||
y = a.Y;
|
||||
z = a.Z;
|
||||
return;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
var (dx, dy) = DefaultPosition(index);
|
||||
x = dx;
|
||||
y = dy;
|
||||
z = 0d;
|
||||
}
|
||||
|
||||
public static ImmutableList<LuaAnchorPoint> ApplyDrag(
|
||||
ImmutableList<LuaAnchorPoint> source, string group, int index, double dx, double dy, double dz)
|
||||
{
|
||||
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 = a.X + dx,
|
||||
Y = a.Y + dy,
|
||||
Z = a.Z + dz,
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
var (bx, by) = DefaultPosition(index);
|
||||
return source.Add(new LuaAnchorPoint
|
||||
{
|
||||
Group = group,
|
||||
Index = index,
|
||||
X = bx + dx,
|
||||
Y = by + dy,
|
||||
Z = dz,
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,11 @@
|
||||
namespace LuaScript.Anchor
|
||||
{
|
||||
public sealed class LuaAnchorPoint
|
||||
{
|
||||
public string Group { get; set; } = string.Empty;
|
||||
public int Index { get; set; }
|
||||
public double X { get; set; }
|
||||
public double Y { get; set; }
|
||||
public double Z { get; set; }
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,17 @@
|
||||
using System.Collections.Generic;
|
||||
|
||||
namespace LuaScript
|
||||
{
|
||||
internal sealed class AviUtlEffectRequest
|
||||
{
|
||||
public string Name { get; }
|
||||
|
||||
public IReadOnlyList<KeyValuePair<string, object>> Arguments { get; }
|
||||
|
||||
public AviUtlEffectRequest(string name, IReadOnlyList<KeyValuePair<string, object>> arguments)
|
||||
{
|
||||
Name = name;
|
||||
Arguments = arguments;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,81 @@
|
||||
using LuaScript.Compat;
|
||||
using LuaScript.Diagnostics;
|
||||
using MoonSharp.Interpreter;
|
||||
|
||||
namespace LuaScript
|
||||
{
|
||||
internal static class AviUtlGlobalRegistrar
|
||||
{
|
||||
internal static void RegisterFunctions(Table globals, Func<double> timeRatio)
|
||||
{
|
||||
globals["debug_print"] = DynValue.NewCallback((_, args) =>
|
||||
{
|
||||
if (args.Count > 0)
|
||||
{
|
||||
var value = args[0];
|
||||
DebugOutput.Write(value.Type == DataType.String ? value.String : value.ToPrintString());
|
||||
}
|
||||
return DynValue.Void;
|
||||
});
|
||||
|
||||
globals["RGB"] = DynValue.NewCallback((_, args) =>
|
||||
{
|
||||
int count = args.Count;
|
||||
if (count >= 6)
|
||||
return DynValue.NewNumber(AviUtlGlobalFunctions.RgbInterpolate(
|
||||
Number(args, 0), Number(args, 1), Number(args, 2),
|
||||
Number(args, 3), Number(args, 4), Number(args, 5),
|
||||
timeRatio()));
|
||||
if (count >= 3)
|
||||
return DynValue.NewNumber(AviUtlGlobalFunctions.RgbCompose(
|
||||
Number(args, 0), Number(args, 1), Number(args, 2)));
|
||||
if (count >= 1)
|
||||
{
|
||||
AviUtlGlobalFunctions.RgbComponents(Number(args, 0), out int r, out int g, out int b);
|
||||
return DynValue.NewTuple(
|
||||
DynValue.NewNumber(r),
|
||||
DynValue.NewNumber(g),
|
||||
DynValue.NewNumber(b));
|
||||
}
|
||||
return DynValue.Nil;
|
||||
});
|
||||
|
||||
globals["HSV"] = DynValue.NewCallback((_, args) =>
|
||||
{
|
||||
int count = args.Count;
|
||||
if (count >= 6)
|
||||
return DynValue.NewNumber(AviUtlGlobalFunctions.HsvInterpolate(
|
||||
Number(args, 0), Number(args, 1), Number(args, 2),
|
||||
Number(args, 3), Number(args, 4), Number(args, 5),
|
||||
timeRatio()));
|
||||
if (count >= 3)
|
||||
return DynValue.NewNumber(AviUtlGlobalFunctions.HsvCompose(
|
||||
Number(args, 0), Number(args, 1), Number(args, 2)));
|
||||
if (count >= 1)
|
||||
{
|
||||
AviUtlGlobalFunctions.HsvComponents(Number(args, 0), out int h, out int s, out int v);
|
||||
return DynValue.NewTuple(
|
||||
DynValue.NewNumber(h),
|
||||
DynValue.NewNumber(s),
|
||||
DynValue.NewNumber(v));
|
||||
}
|
||||
return DynValue.Nil;
|
||||
});
|
||||
|
||||
globals["OR"] = DynValue.NewCallback((_, args) =>
|
||||
DynValue.NewNumber(AviUtlGlobalFunctions.BitOr(Number(args, 0), Number(args, 1))));
|
||||
|
||||
globals["AND"] = DynValue.NewCallback((_, args) =>
|
||||
DynValue.NewNumber(AviUtlGlobalFunctions.BitAnd(Number(args, 0), Number(args, 1))));
|
||||
|
||||
globals["XOR"] = DynValue.NewCallback((_, args) =>
|
||||
DynValue.NewNumber(AviUtlGlobalFunctions.BitXor(Number(args, 0), Number(args, 1))));
|
||||
|
||||
globals["SHIFT"] = DynValue.NewCallback((_, args) =>
|
||||
DynValue.NewNumber(AviUtlGlobalFunctions.BitShift(Number(args, 0), Number(args, 1))));
|
||||
}
|
||||
|
||||
private static double Number(CallbackArguments args, int index) =>
|
||||
args.Count > index ? args[index].CastToNumber() ?? 0d : 0d;
|
||||
}
|
||||
}
|
||||
@@ -1,7 +1,19 @@
|
||||
using LuaScript.Anchor;
|
||||
|
||||
namespace LuaScript
|
||||
{
|
||||
internal sealed class AviUtlScriptContext
|
||||
{
|
||||
public IReadOnlyList<LuaAnchorPoint>? AnchorSource { get; set; }
|
||||
|
||||
private readonly List<AnchorRequestData> _anchorRequests = [];
|
||||
|
||||
public IReadOnlyList<AnchorRequestData> AnchorRequests => _anchorRequests;
|
||||
|
||||
internal void AddAnchorRequest(in AnchorRequestData request) => _anchorRequests.Add(request);
|
||||
|
||||
internal void ClearAnchorRequests() => _anchorRequests.Clear();
|
||||
|
||||
public bool IsPlaying { get; set; }
|
||||
public bool IsPaused { get; set; }
|
||||
public string SceneId { get; set; } = string.Empty;
|
||||
@@ -29,6 +41,11 @@ namespace LuaScript
|
||||
public double Track2 { get; set; }
|
||||
public double Track3 { get; set; }
|
||||
|
||||
public double Slider0 { get; set; }
|
||||
public double Slider1 { get; set; }
|
||||
public double Slider2 { get; set; }
|
||||
public double Slider3 { get; set; }
|
||||
|
||||
public bool Check0 { get; set; }
|
||||
public bool Check1 { get; set; }
|
||||
public bool Check2 { get; set; }
|
||||
@@ -37,6 +54,8 @@ namespace LuaScript
|
||||
public bool HasColor { get; set; }
|
||||
public double ColorValue { get; set; }
|
||||
|
||||
public bool? DrawStateOverride { get; set; }
|
||||
|
||||
public double Time { get; set; }
|
||||
public int Frame { get; set; }
|
||||
public int TotalFrame { get; set; }
|
||||
@@ -52,10 +71,202 @@ namespace LuaScript
|
||||
|
||||
public Func<SceneObjectResolver>? ResolverProvider { get; set; }
|
||||
|
||||
private readonly Dictionary<string, string> _stringParameters = new(StringComparer.Ordinal);
|
||||
|
||||
public IReadOnlyDictionary<string, string> StringParameters => _stringParameters;
|
||||
|
||||
internal void SetStringParameter(string name, string? value) => _stringParameters[name] = value ?? string.Empty;
|
||||
|
||||
private const double Epsilon = 1e-10;
|
||||
|
||||
private readonly List<SceneObjectQuery> _objectQueries = [];
|
||||
|
||||
public IReadOnlyList<SceneObjectQuery> ObjectQueries => _objectQueries;
|
||||
|
||||
private SceneSharedValues? _sceneValues;
|
||||
private string _sceneValuesKey = string.Empty;
|
||||
private readonly List<SceneValueQuery> _sceneValueQueries = [];
|
||||
|
||||
public IReadOnlyList<SceneValueQuery> SceneValueQueries => _sceneValueQueries;
|
||||
|
||||
public bool SceneValuesWritten { get; private set; }
|
||||
|
||||
private SceneSharedValues SceneValues
|
||||
{
|
||||
get
|
||||
{
|
||||
if (_sceneValues is null || !string.Equals(_sceneValuesKey, SceneId, StringComparison.Ordinal))
|
||||
{
|
||||
_sceneValues = SceneSharedValues.ForScene(SceneId);
|
||||
_sceneValuesKey = SceneId;
|
||||
}
|
||||
return _sceneValues;
|
||||
}
|
||||
}
|
||||
|
||||
internal void ClearSceneValueTracking()
|
||||
{
|
||||
_sceneValueQueries.Clear();
|
||||
SceneValuesWritten = false;
|
||||
}
|
||||
|
||||
public SceneValue GetSceneValue(string name)
|
||||
{
|
||||
var value = SceneValues.Get(name);
|
||||
_sceneValueQueries.Add(new SceneValueQuery(name, value));
|
||||
return value;
|
||||
}
|
||||
|
||||
public void SetSceneValue(string name, SceneValue value)
|
||||
{
|
||||
SceneValuesWritten = true;
|
||||
SceneValues.Set(name, value);
|
||||
}
|
||||
|
||||
private readonly List<AviUtlEffectRequest> _effectRequests = [];
|
||||
|
||||
public IReadOnlyList<AviUtlEffectRequest> EffectRequests => _effectRequests;
|
||||
|
||||
internal void AddEffect(AviUtlEffectRequest request) => _effectRequests.Add(request);
|
||||
|
||||
internal void ClearEffects() => _effectRequests.Clear();
|
||||
|
||||
internal IBufferCompositor Compositor { get; set; } = SoftwareCompositor.Instance;
|
||||
|
||||
private readonly List<DrawCommand> _drawCommands = [];
|
||||
|
||||
public IReadOnlyList<DrawCommand> DrawCommands => _drawCommands;
|
||||
|
||||
internal void AddDraw(DrawCommand command) => _drawCommands.Add(command);
|
||||
|
||||
internal void ClearDraws() => _drawCommands.Clear();
|
||||
|
||||
private bool _drawTargetTemp;
|
||||
|
||||
internal void ResetDrawTarget() => _drawTargetTemp = false;
|
||||
|
||||
internal void SetDrawTarget(bool temp, int width, int height, bool hasSize)
|
||||
{
|
||||
_drawTargetTemp = temp;
|
||||
if (temp && hasSize)
|
||||
{
|
||||
int w = Math.Max(1, width);
|
||||
int h = Math.Max(1, height);
|
||||
_buffers["t"] = (new byte[w * h * 4], w, h);
|
||||
}
|
||||
}
|
||||
|
||||
internal void SubmitDraw(DrawCommand command)
|
||||
{
|
||||
if (!_drawTargetTemp)
|
||||
{
|
||||
_drawCommands.Add(command);
|
||||
return;
|
||||
}
|
||||
CompositeToTemp(command);
|
||||
}
|
||||
|
||||
private void CompositeToTemp(DrawCommand command)
|
||||
{
|
||||
EnsurePixelBuffer();
|
||||
var src = _pixelBuffer;
|
||||
if (src is null)
|
||||
return;
|
||||
|
||||
if (!_buffers.TryGetValue("t", out var temp))
|
||||
{
|
||||
int w = Math.Max(1, ImageWidth);
|
||||
int h = Math.Max(1, ImageHeight);
|
||||
temp = (new byte[w * h * 4], w, h);
|
||||
_buffers["t"] = temp;
|
||||
}
|
||||
|
||||
Compositor.TryCompose(temp.Data, temp.Width, temp.Height, src, ImageWidth, ImageHeight, command);
|
||||
}
|
||||
|
||||
private readonly Dictionary<string, (byte[] Data, int Width, int Height)> _buffers = new(StringComparer.Ordinal);
|
||||
|
||||
internal bool CopyBuffer(string dst, string src)
|
||||
{
|
||||
if (!TryReadBuffer(src, out var data, out int w, out int h))
|
||||
return false;
|
||||
return TryWriteBuffer(dst, data, w, h);
|
||||
}
|
||||
|
||||
private bool TryReadBuffer(string id, out byte[] data, out int width, out int height)
|
||||
{
|
||||
data = [];
|
||||
width = 0;
|
||||
height = 0;
|
||||
switch (BufferKind(id, out string key))
|
||||
{
|
||||
case 'o':
|
||||
EnsurePixelBuffer();
|
||||
if (_pixelBuffer is null)
|
||||
return false;
|
||||
data = _pixelBuffer;
|
||||
width = ImageWidth;
|
||||
height = ImageHeight;
|
||||
return true;
|
||||
case 't':
|
||||
case 'c':
|
||||
if (_buffers.TryGetValue(key, out var stored))
|
||||
{
|
||||
data = stored.Data;
|
||||
width = stored.Width;
|
||||
height = stored.Height;
|
||||
return true;
|
||||
}
|
||||
return false;
|
||||
default:
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
private bool TryWriteBuffer(string id, byte[] data, int width, int height)
|
||||
{
|
||||
int n = width * height * 4;
|
||||
switch (BufferKind(id, out string key))
|
||||
{
|
||||
case 'o':
|
||||
if (_copyOutputBuffer is null || _copyOutputBuffer.Length != n)
|
||||
_copyOutputBuffer = new byte[n];
|
||||
Buffer.BlockCopy(data, 0, _copyOutputBuffer, 0, n);
|
||||
ReplaceBuffer(_copyOutputBuffer, width, height);
|
||||
return true;
|
||||
case 't':
|
||||
case 'c':
|
||||
if (!_buffers.TryGetValue(key, out var existing) || existing.Data.Length != n)
|
||||
existing.Data = new byte[n];
|
||||
Buffer.BlockCopy(data, 0, existing.Data, 0, n);
|
||||
_buffers[key] = (existing.Data, width, height);
|
||||
return false;
|
||||
default:
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
private byte[]? _copyOutputBuffer;
|
||||
|
||||
private static char BufferKind(string id, out string key)
|
||||
{
|
||||
key = string.Empty;
|
||||
int i = 0;
|
||||
while (i < id.Length && (id[i] == ' ' || id[i] == '\t'))
|
||||
i++;
|
||||
if (i >= id.Length)
|
||||
return '\0';
|
||||
char kind = char.ToLowerInvariant(id[i]);
|
||||
if (kind == 't')
|
||||
key = "t";
|
||||
else if (kind == 'c')
|
||||
{
|
||||
int colon = id.IndexOf(':', i);
|
||||
key = colon >= 0 ? "c:" + id[(colon + 1)..].Trim() : "c";
|
||||
}
|
||||
return kind;
|
||||
}
|
||||
|
||||
public double RxRad => Rx * Math.PI / 180d;
|
||||
public double RyRad => Ry * Math.PI / 180d;
|
||||
public double RzRad => Rz * Math.PI / 180d;
|
||||
@@ -106,6 +317,14 @@ namespace LuaScript
|
||||
_pixelBufferLoaded = true;
|
||||
}
|
||||
|
||||
internal void SetResolvedBuffer(byte[] buffer, int width, int height)
|
||||
{
|
||||
_pixelBuffer = buffer;
|
||||
_pixelBufferLoaded = true;
|
||||
ImageWidth = width;
|
||||
ImageHeight = height;
|
||||
}
|
||||
|
||||
internal byte[]? GetPixelBuffer() => _pixelBuffer;
|
||||
|
||||
internal void MarkPixelsDirty() => _isPixelsDirty = true;
|
||||
@@ -125,6 +344,46 @@ namespace LuaScript
|
||||
return false;
|
||||
}
|
||||
|
||||
public void ApplyWriteBack(
|
||||
double newSx, double newSy, double newZoom, double newAspect,
|
||||
double newRx, double newRy, double newRz,
|
||||
double newRxr, double newRyr, double newRzr)
|
||||
{
|
||||
double initialSx = Sx;
|
||||
double initialSy = Sy;
|
||||
double initialZoom = Zoom;
|
||||
double initialAspect = Aspect;
|
||||
|
||||
Sx = newSx;
|
||||
Sy = newSy;
|
||||
Zoom = newZoom;
|
||||
Aspect = newAspect;
|
||||
|
||||
bool sxsyChanged = Math.Abs(Sx - initialSx) > Epsilon || Math.Abs(Sy - initialSy) > Epsilon;
|
||||
bool zoomAspectChanged = Math.Abs(Zoom - initialZoom) > Epsilon || Math.Abs(Aspect - initialAspect) > Epsilon;
|
||||
|
||||
if (zoomAspectChanged && !sxsyChanged)
|
||||
{
|
||||
Sx = Zoom * (1.0 + Aspect);
|
||||
Sy = Zoom * (1.0 - Aspect);
|
||||
}
|
||||
|
||||
double initialRxr = RxRad;
|
||||
Rx = Math.Abs(newRxr - initialRxr) > Epsilon
|
||||
? newRxr * (180d / Math.PI)
|
||||
: newRx;
|
||||
|
||||
double initialRyr = RyRad;
|
||||
Ry = Math.Abs(newRyr - initialRyr) > Epsilon
|
||||
? newRyr * (180d / Math.PI)
|
||||
: newRy;
|
||||
|
||||
double initialRzr = RzRad;
|
||||
Rz = Math.Abs(newRzr - initialRzr) > Epsilon
|
||||
? newRzr * (180d / Math.PI)
|
||||
: newRz;
|
||||
}
|
||||
|
||||
public unsafe (double r, double g, double b, double a) GetPixel(int x, int y)
|
||||
{
|
||||
EnsurePixelBuffer();
|
||||
|
||||
@@ -0,0 +1,138 @@
|
||||
using System.Collections.Generic;
|
||||
using System.Globalization;
|
||||
using System.IO;
|
||||
using System.Linq;
|
||||
using System.Reflection;
|
||||
using System.Xml.Linq;
|
||||
|
||||
namespace LuaScript.Compat
|
||||
{
|
||||
internal sealed class AviUtlCompatMap
|
||||
{
|
||||
private const string ResourceSuffix = "AviUtlCompatMap.xml";
|
||||
|
||||
private readonly Dictionary<string, List<AviUtlEffectMapping>> _effects;
|
||||
|
||||
public static AviUtlCompatMap Default { get; } = Load();
|
||||
|
||||
private AviUtlCompatMap(Dictionary<string, List<AviUtlEffectMapping>> effects)
|
||||
{
|
||||
_effects = effects;
|
||||
}
|
||||
|
||||
public bool TryResolve(string name, AviUtlEngine target, out AviUtlEffectMapping mapping)
|
||||
{
|
||||
mapping = null!;
|
||||
if (string.IsNullOrEmpty(name) || !_effects.TryGetValue(Normalize(name), out var candidates))
|
||||
return false;
|
||||
|
||||
foreach (var candidate in candidates)
|
||||
{
|
||||
if (candidate.Engine.Includes(target))
|
||||
{
|
||||
mapping = candidate;
|
||||
return true;
|
||||
}
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
public static AviUtlEngine ResolveTarget(string? script)
|
||||
{
|
||||
if (string.IsNullOrEmpty(script))
|
||||
return AviUtlEngine.AviUtl;
|
||||
|
||||
foreach (var raw in script.Replace("\r\n", "\n").Replace("\r", "\n").Split('\n'))
|
||||
{
|
||||
var line = raw.Trim();
|
||||
if (!line.StartsWith("--!", System.StringComparison.Ordinal))
|
||||
continue;
|
||||
var token = line[3..].Trim().ToLowerInvariant();
|
||||
if (token == "aviutl2")
|
||||
return AviUtlEngine.AviUtl2;
|
||||
if (token == "aviutl")
|
||||
return AviUtlEngine.AviUtl;
|
||||
}
|
||||
return AviUtlEngine.AviUtl;
|
||||
}
|
||||
|
||||
private static AviUtlCompatMap Load()
|
||||
{
|
||||
var effects = new Dictionary<string, List<AviUtlEffectMapping>>(StringComparer.OrdinalIgnoreCase);
|
||||
try
|
||||
{
|
||||
using var stream = OpenResource();
|
||||
if (stream is not null)
|
||||
Populate(effects, stream);
|
||||
}
|
||||
catch
|
||||
{
|
||||
}
|
||||
return new AviUtlCompatMap(effects);
|
||||
}
|
||||
|
||||
private static void Populate(Dictionary<string, List<AviUtlEffectMapping>> effects, Stream stream)
|
||||
{
|
||||
var root = XDocument.Load(stream).Root;
|
||||
if (root is null)
|
||||
return;
|
||||
|
||||
foreach (var element in root.Elements("effect"))
|
||||
{
|
||||
var target = (string?)element.Attribute("target");
|
||||
if (string.IsNullOrWhiteSpace(target))
|
||||
continue;
|
||||
|
||||
if (!AviUtlEngineExtensions.TryParse(((string?)element.Attribute("engine"))?.Trim().ToLowerInvariant(), out var engine))
|
||||
engine = AviUtlEngine.Both;
|
||||
|
||||
var parameters = element.Elements("param").Select(ParseParameter).ToArray();
|
||||
var mapping = new AviUtlEffectMapping(engine, target.Trim(), parameters);
|
||||
|
||||
foreach (var name in SplitNames((string?)element.Attribute("names")))
|
||||
{
|
||||
if (!effects.TryGetValue(name, out var list))
|
||||
{
|
||||
list = [];
|
||||
effects[name] = list;
|
||||
}
|
||||
list.Add(mapping);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private static AviUtlParameterMapping ParseParameter(XElement element)
|
||||
{
|
||||
var source = ((string?)element.Attribute("name") ?? string.Empty).Trim();
|
||||
var property = ((string?)element.Attribute("property") ?? string.Empty).Trim();
|
||||
double scale = ParseDouble((string?)element.Attribute("scale"), 1d);
|
||||
double offset = ParseDouble((string?)element.Attribute("offset"), 0d);
|
||||
return new AviUtlParameterMapping(source, property, scale, offset);
|
||||
}
|
||||
|
||||
private static IEnumerable<string> SplitNames(string? names)
|
||||
{
|
||||
if (string.IsNullOrWhiteSpace(names))
|
||||
yield break;
|
||||
foreach (var part in names.Split(','))
|
||||
{
|
||||
var trimmed = part.Trim();
|
||||
if (trimmed.Length != 0)
|
||||
yield return Normalize(trimmed);
|
||||
}
|
||||
}
|
||||
|
||||
private static double ParseDouble(string? value, double fallback) =>
|
||||
double.TryParse(value, NumberStyles.Float, CultureInfo.InvariantCulture, out double result) ? result : fallback;
|
||||
|
||||
private static string Normalize(string value) => value.Trim().ToLowerInvariant();
|
||||
|
||||
private static Stream? OpenResource()
|
||||
{
|
||||
var assembly = typeof(AviUtlCompatMap).Assembly;
|
||||
var name = assembly.GetManifestResourceNames()
|
||||
.FirstOrDefault(n => n.EndsWith(ResourceSuffix, System.StringComparison.Ordinal));
|
||||
return name is null ? null : assembly.GetManifestResourceStream(name);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,114 @@
|
||||
<?xml version="1.0" encoding="utf-8"?>
|
||||
<aviUtlCompat>
|
||||
<effect engine="both" names="ぼかし" target="GaussianBlurEffect">
|
||||
<param name="範囲" property="Blur" scale="0.5" />
|
||||
<param name="サイズ固定" property="IsHardBorderMode" />
|
||||
</effect>
|
||||
<effect engine="both" names="境界ぼかし" target="BorderBlurEffect">
|
||||
<param name="範囲" property="Blur" />
|
||||
</effect>
|
||||
<effect engine="both" names="方向ブラー" target="DirectionalBlurEffect">
|
||||
<param name="範囲" property="StandardDeviation" scale="0.5" />
|
||||
<param name="角度" property="Angle" />
|
||||
<param name="サイズ固定" property="IsHardBorderMode" />
|
||||
</effect>
|
||||
<effect engine="both" names="放射ブラー" target="RadialBlurEffect">
|
||||
<param name="範囲" property="Blur" />
|
||||
<param name="X" property="X" />
|
||||
<param name="Y" property="Y" />
|
||||
<param name="サイズを固定" property="IsHardBorderMode" />
|
||||
</effect>
|
||||
<effect engine="both" names="閃光" target="RadialLightEffect">
|
||||
<param name="範囲" property="Value" />
|
||||
<param name="X" property="X" />
|
||||
<param name="Y" property="Y" />
|
||||
<param name="サイズを固定" property="IsHardBorderMode" />
|
||||
</effect>
|
||||
<effect engine="both" names="クロマキー" target="ChromaKeyEffect">
|
||||
<param name="色相範囲" property="Tolerance" scale="0.390625" />
|
||||
<param name="境界補正" property="Feather" />
|
||||
</effect>
|
||||
<effect engine="both" names="クリッピング" target="CropEffect">
|
||||
<param name="上" property="Top" />
|
||||
<param name="下" property="Bottom" />
|
||||
<param name="左" property="Left" />
|
||||
<param name="右" property="Right" />
|
||||
<param name="中心の位置を変更" property="IsCentering" />
|
||||
</effect>
|
||||
<effect engine="both" names="斜めクリッピング" target="CropByAngleEffect">
|
||||
<param name="中心X" property="X" />
|
||||
<param name="中心Y" property="Y" />
|
||||
<param name="角度" property="Angle" />
|
||||
<param name="ぼかし" property="Blur" scale="0.5" />
|
||||
<param name="幅" property="Width" />
|
||||
</effect>
|
||||
<effect engine="both" names="領域拡張" target="MarginEffect">
|
||||
<param name="上" property="Top" />
|
||||
<param name="下" property="Bottom" />
|
||||
<param name="左" property="Left" />
|
||||
<param name="右" property="Right" />
|
||||
</effect>
|
||||
<effect engine="both" names="座標" target="DrawPositionEffect">
|
||||
<param name="X" property="X" />
|
||||
<param name="Y" property="Y" />
|
||||
<param name="Z" property="Z" />
|
||||
</effect>
|
||||
<effect engine="both" names="回転" target="RotateEffect">
|
||||
<param name="X" property="X" />
|
||||
<param name="Y" property="Y" />
|
||||
<param name="Z" property="Z" />
|
||||
</effect>
|
||||
<effect engine="both" names="リサイズ" target="ZoomEffect">
|
||||
<param name="拡大率" property="Zoom" />
|
||||
<param name="X" property="ZoomX" />
|
||||
<param name="Y" property="ZoomY" />
|
||||
<param name="補間なし" property="IsNearestNeighbor" />
|
||||
</effect>
|
||||
<effect engine="both" names="画像ループ" target="TilingEffect">
|
||||
<param name="横回数" property="X" />
|
||||
<param name="縦回数" property="Y" />
|
||||
</effect>
|
||||
<effect engine="both" names="極座標変換" target="PolarTransformEffect">
|
||||
<param name="中心幅" property="CoreWidth" />
|
||||
<param name="渦巻" property="TwistAngle" scale="360" />
|
||||
</effect>
|
||||
<effect engine="both" names="グラデーション" target="GradientEffect">
|
||||
<param name="強さ" property="Opacity" />
|
||||
<param name="中心X" property="X" />
|
||||
<param name="中心Y" property="Y" />
|
||||
<param name="角度" property="Rotation" />
|
||||
<param name="幅" property="Size" />
|
||||
</effect>
|
||||
<effect engine="both" names="単色化" target="MonocolorizationEffect">
|
||||
<param name="強さ" property="Strength" />
|
||||
<param name="輝度を保持する" property="KeepBrightness" />
|
||||
</effect>
|
||||
<effect engine="both" names="縁取り" target="OutlineEffect">
|
||||
<param name="サイズ" property="StrokeThickness" />
|
||||
<param name="ぼかし" property="Blur" />
|
||||
</effect>
|
||||
<effect engine="both" names="反転" target="InvertEffect" />
|
||||
<effect engine="both" names="モザイク" target="MosaicEffect">
|
||||
<param name="サイズ" property="Size" />
|
||||
</effect>
|
||||
<effect engine="both" names="ディスプレイスメントマップ" target="DisplacementMapEffect">
|
||||
<param name="ぼかし" property="Blur" scale="0.5" />
|
||||
</effect>
|
||||
<effect engine="both" names="動画ファイル合成" target="TextureEffect">
|
||||
<param name="X" property="X" />
|
||||
<param name="Y" property="Y" />
|
||||
<param name="拡大率" property="Zoom" />
|
||||
</effect>
|
||||
<effect engine="both" names="色調補正" target="ColorCorrectionEffect">
|
||||
<param name="明るさ" property="Lightness" />
|
||||
<param name="コントラスト" property="Contrast" />
|
||||
<param name="色相" property="HueRotation" />
|
||||
<param name="輝度" property="Brightness" />
|
||||
<param name="彩度" property="Saturation" />
|
||||
</effect>
|
||||
<effect engine="both" names="色ずれ" target="ColorShiftEffect">
|
||||
<param name="ずれ幅" property="Shift" />
|
||||
<param name="角度" property="Angle" />
|
||||
<param name="強さ" property="Strength" />
|
||||
</effect>
|
||||
</aviUtlCompat>
|
||||
@@ -0,0 +1,30 @@
|
||||
using System.Collections.Generic;
|
||||
|
||||
namespace LuaScript.Compat
|
||||
{
|
||||
internal readonly record struct AviUtlParameterMapping(string Source, string Property, double Scale, double Offset)
|
||||
{
|
||||
public double Transform(double value) => value * Scale + Offset;
|
||||
}
|
||||
|
||||
internal sealed class AviUtlEffectMapping
|
||||
{
|
||||
private readonly Dictionary<string, AviUtlParameterMapping> _parameters;
|
||||
|
||||
public AviUtlEngine Engine { get; }
|
||||
|
||||
public string TargetType { get; }
|
||||
|
||||
public AviUtlEffectMapping(AviUtlEngine engine, string targetType, IEnumerable<AviUtlParameterMapping> parameters)
|
||||
{
|
||||
Engine = engine;
|
||||
TargetType = targetType;
|
||||
_parameters = new Dictionary<string, AviUtlParameterMapping>(StringComparer.OrdinalIgnoreCase);
|
||||
foreach (var parameter in parameters)
|
||||
_parameters[parameter.Source] = parameter;
|
||||
}
|
||||
|
||||
public bool TryGetParameter(string source, out AviUtlParameterMapping mapping) =>
|
||||
_parameters.TryGetValue(source, out mapping);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,34 @@
|
||||
namespace LuaScript.Compat
|
||||
{
|
||||
internal enum AviUtlEngine
|
||||
{
|
||||
AviUtl,
|
||||
AviUtl2,
|
||||
Both,
|
||||
}
|
||||
|
||||
internal static class AviUtlEngineExtensions
|
||||
{
|
||||
public static bool Includes(this AviUtlEngine scope, AviUtlEngine target) =>
|
||||
scope == AviUtlEngine.Both || scope == target;
|
||||
|
||||
public static bool TryParse(string? value, out AviUtlEngine engine)
|
||||
{
|
||||
switch (value)
|
||||
{
|
||||
case "aviutl":
|
||||
engine = AviUtlEngine.AviUtl;
|
||||
return true;
|
||||
case "aviutl2":
|
||||
engine = AviUtlEngine.AviUtl2;
|
||||
return true;
|
||||
case "both":
|
||||
engine = AviUtlEngine.Both;
|
||||
return true;
|
||||
default:
|
||||
engine = AviUtlEngine.AviUtl;
|
||||
return false;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,137 @@
|
||||
namespace LuaScript.Compat
|
||||
{
|
||||
internal static class AviUtlGlobalFunctions
|
||||
{
|
||||
public static int BitOr(double a, double b) => ToBitOperand(a) | ToBitOperand(b);
|
||||
|
||||
public static int BitAnd(double a, double b) => ToBitOperand(a) & ToBitOperand(b);
|
||||
|
||||
public static int BitXor(double a, double b) => ToBitOperand(a) ^ ToBitOperand(b);
|
||||
|
||||
public static int BitShift(double value, double shift)
|
||||
{
|
||||
int v = ToBitOperand(value);
|
||||
int n = ToBitOperand(shift);
|
||||
return n >= 0 ? v << n : v >> -n;
|
||||
}
|
||||
|
||||
public static int ToBitOperand(double value)
|
||||
{
|
||||
if (double.IsNaN(value))
|
||||
return 0;
|
||||
if (value <= int.MinValue)
|
||||
return int.MinValue;
|
||||
if (value >= int.MaxValue)
|
||||
return int.MaxValue;
|
||||
return (int)Math.Ceiling(value - 0.5);
|
||||
}
|
||||
|
||||
public static int RgbCompose(double r, double g, double b) =>
|
||||
(ToColorChannel(r) << 16) | (ToColorChannel(g) << 8) | ToColorChannel(b);
|
||||
|
||||
public static void RgbComponents(double color, out int r, out int g, out int b)
|
||||
{
|
||||
int c = ToColor(color);
|
||||
r = (c >> 16) & 0xFF;
|
||||
g = (c >> 8) & 0xFF;
|
||||
b = c & 0xFF;
|
||||
}
|
||||
|
||||
public static int RgbInterpolate(double r1, double g1, double b1, double r2, double g2, double b2, double t) =>
|
||||
RgbCompose(r1 + (r2 - r1) * t, g1 + (g2 - g1) * t, b1 + (b2 - b1) * t);
|
||||
|
||||
public static int HsvCompose(double h, double s, double v)
|
||||
{
|
||||
h = WrapHue(h);
|
||||
s = ClampRatio(s);
|
||||
v = ClampRatio(v);
|
||||
|
||||
double c = v * s;
|
||||
double x = c * (1d - Math.Abs(h / 60d % 2d - 1d));
|
||||
double m = v - c;
|
||||
int sector = (int)Math.Floor(h / 60d);
|
||||
|
||||
double r, g, b;
|
||||
if (sector == 0) { r = c; g = x; b = 0d; }
|
||||
else if (sector == 1) { r = x; g = c; b = 0d; }
|
||||
else if (sector == 2) { r = 0d; g = c; b = x; }
|
||||
else if (sector == 3) { r = 0d; g = x; b = c; }
|
||||
else if (sector == 4) { r = x; g = 0d; b = c; }
|
||||
else { r = c; g = 0d; b = x; }
|
||||
|
||||
return (ToColorChannel(RoundHalfUp((r + m) * 255d)) << 16) |
|
||||
(ToColorChannel(RoundHalfUp((g + m) * 255d)) << 8) |
|
||||
ToColorChannel(RoundHalfUp((b + m) * 255d));
|
||||
}
|
||||
|
||||
public static void HsvComponents(double color, out int h, out int s, out int v)
|
||||
{
|
||||
RgbComponents(color, out int r, out int g, out int b);
|
||||
double rf = r / 255d;
|
||||
double gf = g / 255d;
|
||||
double bf = b / 255d;
|
||||
|
||||
double max = Math.Max(rf, Math.Max(gf, bf));
|
||||
double min = Math.Min(rf, Math.Min(gf, bf));
|
||||
double delta = max - min;
|
||||
|
||||
double hue = 0d;
|
||||
if (delta > 0d)
|
||||
{
|
||||
if (max == rf)
|
||||
hue = 60d * (((gf - bf) / delta % 6d + 6d) % 6d);
|
||||
else if (max == gf)
|
||||
hue = 60d * ((bf - rf) / delta + 2d);
|
||||
else
|
||||
hue = 60d * ((rf - gf) / delta + 4d);
|
||||
}
|
||||
|
||||
h = (int)RoundHalfUp(hue);
|
||||
s = (int)RoundHalfUp(max > 0d ? delta / max * 100d : 0d);
|
||||
v = (int)RoundHalfUp(max * 100d);
|
||||
}
|
||||
|
||||
public static int HsvInterpolate(double h1, double s1, double v1, double h2, double s2, double v2, double t) =>
|
||||
HsvCompose(h1 + (h2 - h1) * t, s1 + (s2 - s1) * t, v1 + (v2 - v1) * t);
|
||||
|
||||
private static int ToColorChannel(double value)
|
||||
{
|
||||
if (double.IsNaN(value) || value <= 0d)
|
||||
return 0;
|
||||
if (value >= 255d)
|
||||
return 255;
|
||||
return (int)Math.Floor(value);
|
||||
}
|
||||
|
||||
private static int ToColor(double value)
|
||||
{
|
||||
if (double.IsNaN(value))
|
||||
return 0;
|
||||
if (value <= int.MinValue)
|
||||
value = int.MinValue;
|
||||
else if (value >= int.MaxValue)
|
||||
value = int.MaxValue;
|
||||
long floored = (long)Math.Floor(value);
|
||||
return (int)(floored & 0xFFFFFF);
|
||||
}
|
||||
|
||||
private static double WrapHue(double h)
|
||||
{
|
||||
if (double.IsNaN(h) || double.IsInfinity(h))
|
||||
return 0d;
|
||||
double wrapped = h - Math.Floor(h / 360d) * 360d;
|
||||
return wrapped >= 360d ? 0d : wrapped;
|
||||
}
|
||||
|
||||
private static double ClampRatio(double value)
|
||||
{
|
||||
if (double.IsNaN(value) || value <= 0d)
|
||||
return 0d;
|
||||
if (value >= 100d)
|
||||
return 1d;
|
||||
return value / 100d;
|
||||
}
|
||||
|
||||
private static double RoundHalfUp(double value) => Math.Floor(value + 0.5);
|
||||
}
|
||||
}
|
||||
@@ -49,13 +49,13 @@ namespace LuaScript.Compat
|
||||
int sectionEnd = lines.Length;
|
||||
for (int i = 0; i < lines.Length; i++)
|
||||
{
|
||||
if (!IsSectionHeader(lines[i]))
|
||||
if (!ScriptParserHelper.IsSectionHeader(lines[i]))
|
||||
continue;
|
||||
sectionStart = i + 1;
|
||||
sectionEnd = lines.Length;
|
||||
for (int j = sectionStart; j < lines.Length; j++)
|
||||
{
|
||||
if (IsSectionHeader(lines[j]))
|
||||
if (ScriptParserHelper.IsSectionHeader(lines[j]))
|
||||
{
|
||||
sectionEnd = j;
|
||||
break;
|
||||
@@ -72,7 +72,7 @@ namespace LuaScript.Compat
|
||||
|
||||
private void ParseLine(string line)
|
||||
{
|
||||
int i = SkipSpaces(line, 0);
|
||||
int i = ScriptParserHelper.SkipSpaces(line, 0);
|
||||
if (i + 1 >= line.Length || line[i] != '-' || line[i + 1] != '-')
|
||||
return;
|
||||
i += 2;
|
||||
@@ -80,7 +80,7 @@ namespace LuaScript.Compat
|
||||
return;
|
||||
|
||||
int nameStart = i;
|
||||
while (i < line.Length && IsNameChar(line[i]))
|
||||
while (i < line.Length && ScriptParserHelper.IsNameChar(line[i]))
|
||||
i++;
|
||||
if (i >= line.Length || line[i] != ':')
|
||||
return;
|
||||
@@ -174,27 +174,11 @@ namespace LuaScript.Compat
|
||||
|
||||
private static string FirstToken(string content)
|
||||
{
|
||||
int start = SkipSpaces(content, 0);
|
||||
int start = ScriptParserHelper.SkipSpaces(content, 0);
|
||||
int i = start;
|
||||
while (i < content.Length && content[i] != ',' && content[i] != ' ' && content[i] != '\t')
|
||||
i++;
|
||||
return content.Substring(start, i - start);
|
||||
}
|
||||
|
||||
private static bool IsSectionHeader(string line)
|
||||
{
|
||||
int i = SkipSpaces(line, 0);
|
||||
return i < line.Length && line[i] == '@';
|
||||
}
|
||||
|
||||
private static int SkipSpaces(string text, int index)
|
||||
{
|
||||
while (index < text.Length && (text[index] == ' ' || text[index] == '\t'))
|
||||
index++;
|
||||
return index;
|
||||
}
|
||||
|
||||
private static bool IsNameChar(char c) =>
|
||||
(c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z') || (c >= '0' && c <= '9');
|
||||
}
|
||||
}
|
||||
@@ -13,10 +13,12 @@ namespace LuaScript.Compat
|
||||
Param,
|
||||
}
|
||||
|
||||
public static string Transform(string source)
|
||||
public static string Transform(string source) => TransformWithMap(source).Code;
|
||||
|
||||
public static (string Code, int[] LineMap) TransformWithMap(string source)
|
||||
{
|
||||
if (string.IsNullOrEmpty(source))
|
||||
return source;
|
||||
return (source, []);
|
||||
|
||||
var lines = source.Replace("\r\n", "\n").Replace("\r", "\n").Split('\n');
|
||||
|
||||
@@ -26,7 +28,7 @@ namespace LuaScript.Compat
|
||||
|
||||
for (int i = 0; i < lines.Length; i++)
|
||||
{
|
||||
if (!IsSectionHeader(lines[i]))
|
||||
if (!ScriptParserHelper.IsSectionHeader(lines[i]))
|
||||
continue;
|
||||
|
||||
hasSection = true;
|
||||
@@ -34,7 +36,7 @@ namespace LuaScript.Compat
|
||||
sectionEnd = lines.Length;
|
||||
for (int j = sectionStart; j < lines.Length; j++)
|
||||
{
|
||||
if (IsSectionHeader(lines[j]))
|
||||
if (ScriptParserHelper.IsSectionHeader(lines[j]))
|
||||
{
|
||||
sectionEnd = j;
|
||||
break;
|
||||
@@ -48,26 +50,29 @@ namespace LuaScript.Compat
|
||||
AppendDeclarations(lines[i], prelude);
|
||||
|
||||
if (!hasSection && prelude.Count == 0)
|
||||
return source;
|
||||
return (source, []);
|
||||
|
||||
var builder = new StringBuilder(source.Length + 64);
|
||||
var lineMap = new int[prelude.Count + (sectionEnd - sectionStart)];
|
||||
int row = 0;
|
||||
|
||||
foreach (var declaration in prelude)
|
||||
{
|
||||
builder.Append(declaration).Append('\n');
|
||||
lineMap[row++] = -1;
|
||||
}
|
||||
for (int i = sectionStart; i < sectionEnd; i++)
|
||||
{
|
||||
builder.Append(lines[i]).Append('\n');
|
||||
lineMap[row++] = i;
|
||||
}
|
||||
|
||||
return builder.ToString();
|
||||
}
|
||||
|
||||
private static bool IsSectionHeader(string line)
|
||||
{
|
||||
int i = SkipSpaces(line, 0);
|
||||
return i < line.Length && line[i] == '@';
|
||||
return (builder.ToString(), lineMap);
|
||||
}
|
||||
|
||||
private static void AppendDeclarations(string line, List<string> prelude)
|
||||
{
|
||||
int i = SkipSpaces(line, 0);
|
||||
int i = ScriptParserHelper.SkipSpaces(line, 0);
|
||||
if (i + 1 >= line.Length || line[i] != '-' || line[i + 1] != '-')
|
||||
return;
|
||||
i += 2;
|
||||
@@ -75,7 +80,7 @@ namespace LuaScript.Compat
|
||||
return;
|
||||
|
||||
int nameStart = i;
|
||||
while (i < line.Length && IsNameChar(line[i]))
|
||||
while (i < line.Length && ScriptParserHelper.IsNameChar(line[i]))
|
||||
i++;
|
||||
if (i >= line.Length || line[i] != ':')
|
||||
return;
|
||||
@@ -125,15 +130,5 @@ namespace LuaScript.Compat
|
||||
if (trimmed.Length != 0)
|
||||
prelude.Add(trimmed);
|
||||
}
|
||||
|
||||
private static int SkipSpaces(string text, int index)
|
||||
{
|
||||
while (index < text.Length && (text[index] == ' ' || text[index] == '\t'))
|
||||
index++;
|
||||
return index;
|
||||
}
|
||||
|
||||
private static bool IsNameChar(char c) =>
|
||||
(c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z') || (c >= '0' && c <= '9');
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,53 @@
|
||||
using YukkuriMovieMaker.Project;
|
||||
|
||||
namespace LuaScript.Compat
|
||||
{
|
||||
internal static class BlendModeMap
|
||||
{
|
||||
private static readonly Blend[] Order =
|
||||
[
|
||||
Blend.Normal,
|
||||
Blend.Dissolve,
|
||||
Blend.Darker,
|
||||
Blend.Multiply,
|
||||
Blend.ColorBurn,
|
||||
Blend.LinearBurn,
|
||||
Blend.Lighter,
|
||||
Blend.Screen,
|
||||
Blend.ColorDodge,
|
||||
Blend.LinearDodge,
|
||||
Blend.Add,
|
||||
Blend.Overlay,
|
||||
Blend.SoftLight,
|
||||
Blend.HardLight,
|
||||
Blend.VividLight,
|
||||
Blend.LinearLight,
|
||||
Blend.PinLight,
|
||||
Blend.HardMix,
|
||||
Blend.Difference,
|
||||
Blend.Exclusion,
|
||||
Blend.Subtract,
|
||||
Blend.Division,
|
||||
Blend.Hue,
|
||||
Blend.Saturation,
|
||||
Blend.Color,
|
||||
Blend.Luminosity,
|
||||
Blend.LighterColor,
|
||||
Blend.DestinationOver,
|
||||
Blend.DarkerColor,
|
||||
Blend.DestinationOut,
|
||||
Blend.SourceAtop,
|
||||
Blend.XOR,
|
||||
Blend.MaskInvert,
|
||||
];
|
||||
|
||||
public static Blend Resolve(double value)
|
||||
{
|
||||
if (double.IsNaN(value))
|
||||
return Blend.Normal;
|
||||
|
||||
int index = (int)value;
|
||||
return (uint)index < (uint)Order.Length ? Order[index] : Blend.Normal;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,76 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using LuaScript.Engine.Kernel;
|
||||
|
||||
namespace LuaScript.Compat
|
||||
{
|
||||
internal readonly struct ScriptParameterUsage
|
||||
{
|
||||
private readonly HashSet<string>? _members;
|
||||
private readonly bool _color;
|
||||
|
||||
private ScriptParameterUsage(HashSet<string>? members, bool color)
|
||||
{
|
||||
_members = members;
|
||||
_color = color;
|
||||
}
|
||||
|
||||
public static readonly ScriptParameterUsage None = default;
|
||||
|
||||
public bool Color => _color;
|
||||
|
||||
public bool Uses(string member) => _members is not null && _members.Contains(member);
|
||||
|
||||
public bool Check0 => Uses("check0");
|
||||
public bool Check1 => Uses("check1");
|
||||
public bool Check2 => Uses("check2");
|
||||
public bool Check3 => Uses("check3");
|
||||
|
||||
public bool Check(int index) => (uint)index < 4 && Uses("check" + (char)('0' + index));
|
||||
|
||||
public bool Slider(int index) => (uint)index < 4 && Uses("slider" + (char)('0' + index));
|
||||
|
||||
public static ScriptParameterUsage Detect(string? script)
|
||||
{
|
||||
if (string.IsNullOrEmpty(script))
|
||||
return None;
|
||||
|
||||
List<LuaToken> tokens;
|
||||
try
|
||||
{
|
||||
tokens = LuaLexer.Tokenize(script);
|
||||
}
|
||||
catch (KernelUnsupportedException)
|
||||
{
|
||||
return None;
|
||||
}
|
||||
|
||||
HashSet<string>? members = null;
|
||||
bool color = false;
|
||||
|
||||
for (int i = 0; i < tokens.Count; i++)
|
||||
{
|
||||
var token = tokens[i];
|
||||
if (token.Kind != LuaTokenKind.Name)
|
||||
continue;
|
||||
|
||||
if (token.Text == "color")
|
||||
{
|
||||
if (i == 0 || !tokens[i - 1].IsSymbol("."))
|
||||
color = true;
|
||||
continue;
|
||||
}
|
||||
|
||||
if (token.Text == "obj" &&
|
||||
i + 2 < tokens.Count &&
|
||||
tokens[i + 1].IsSymbol(".") &&
|
||||
tokens[i + 2].Kind == LuaTokenKind.Name)
|
||||
{
|
||||
(members ??= new HashSet<string>(StringComparer.Ordinal)).Add(tokens[i + 2].Text);
|
||||
}
|
||||
}
|
||||
|
||||
return new ScriptParameterUsage(members, color);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,21 @@
|
||||
namespace LuaScript.Compat
|
||||
{
|
||||
internal static class ScriptParserHelper
|
||||
{
|
||||
public static bool IsSectionHeader(string line)
|
||||
{
|
||||
int i = SkipSpaces(line, 0);
|
||||
return i < line.Length && line[i] == '@';
|
||||
}
|
||||
|
||||
public static int SkipSpaces(string text, int index)
|
||||
{
|
||||
while (index < text.Length && (text[index] == ' ' || text[index] == '\t'))
|
||||
index++;
|
||||
return index;
|
||||
}
|
||||
|
||||
public static bool IsNameChar(char c) =>
|
||||
(c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z') || (c >= '0' && c <= '9');
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,12 @@
|
||||
using System.Runtime.InteropServices;
|
||||
|
||||
namespace LuaScript.Diagnostics
|
||||
{
|
||||
internal static partial class DebugOutput
|
||||
{
|
||||
[LibraryImport("kernel32.dll", EntryPoint = "OutputDebugStringW", StringMarshalling = StringMarshalling.Utf16)]
|
||||
private static partial void OutputDebugStringW(string message);
|
||||
|
||||
internal static void Write(string message) => OutputDebugStringW(message);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,42 @@
|
||||
using System;
|
||||
using System.Text.RegularExpressions;
|
||||
|
||||
namespace LuaScript.Diagnostics
|
||||
{
|
||||
internal enum LuaScriptDiagnosticKind
|
||||
{
|
||||
Compile,
|
||||
Runtime,
|
||||
Timeout,
|
||||
}
|
||||
|
||||
internal readonly record struct LuaScriptDiagnostic(
|
||||
LuaScriptDiagnosticKind Kind,
|
||||
int Line,
|
||||
int Column,
|
||||
int Length,
|
||||
string Message);
|
||||
|
||||
internal static partial class LuaScriptDiagnosticParser
|
||||
{
|
||||
[GeneratedRegex(@"^LuaScript:\((\d+),(\d+)(?:-(\d+)(?:,(\d+))?)?\):\s*", RegexOptions.None)]
|
||||
private static partial Regex LocationPattern();
|
||||
|
||||
public static LuaScriptDiagnostic Parse(LuaScriptDiagnosticKind kind, string? message)
|
||||
{
|
||||
var text = message ?? string.Empty;
|
||||
var match = LocationPattern().Match(text);
|
||||
if (!match.Success)
|
||||
return new LuaScriptDiagnostic(kind, 0, 0, 0, text.Trim());
|
||||
|
||||
int line = int.Parse(match.Groups[1].Value);
|
||||
int columnStart = int.Parse(match.Groups[2].Value);
|
||||
|
||||
int length = 0;
|
||||
if (match.Groups[3].Success && !match.Groups[4].Success)
|
||||
length = Math.Max(0, int.Parse(match.Groups[3].Value) - columnStart);
|
||||
|
||||
return new LuaScriptDiagnostic(kind, line, columnStart + 1, length, text[match.Length..].Trim());
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,263 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Reflection;
|
||||
using System.Windows;
|
||||
using System.Windows.Controls;
|
||||
using System.Windows.Controls.Primitives;
|
||||
using System.Windows.Input;
|
||||
using System.Windows.Media;
|
||||
using ICSharpCode.AvalonEdit.Document;
|
||||
using ICSharpCode.AvalonEdit.Folding;
|
||||
using ICSharpCode.AvalonEdit.Rendering;
|
||||
|
||||
namespace LuaScript.Diagnostics
|
||||
{
|
||||
internal sealed class LuaScriptDiagnosticOverlay : IBackgroundRenderer, ILuaScriptDiagnosticsListener
|
||||
{
|
||||
private static readonly FieldInfo? s_textViewsField = ResolveTextViewsField();
|
||||
|
||||
private static readonly Pen s_squigglePen = CreateSquigglePen();
|
||||
|
||||
private sealed class Marker : ISegment
|
||||
{
|
||||
public required int Offset { get; init; }
|
||||
public required int Length { get; init; }
|
||||
public int EndOffset => Offset + Length;
|
||||
public required LuaScriptDiagnostic Diagnostic { get; init; }
|
||||
}
|
||||
|
||||
private readonly TextView _textView;
|
||||
private readonly ToolTip _toolTip = new() { Placement = PlacementMode.Mouse };
|
||||
private readonly List<Marker> _markers = [];
|
||||
private object? _renderedText;
|
||||
private bool _isDirty = true;
|
||||
|
||||
public static void Attach(FoldingManager manager)
|
||||
{
|
||||
var textView = ResolveTextView(manager);
|
||||
if (textView is null)
|
||||
return;
|
||||
|
||||
foreach (var renderer in textView.BackgroundRenderers)
|
||||
{
|
||||
if (renderer is LuaScriptDiagnosticOverlay)
|
||||
return;
|
||||
}
|
||||
|
||||
_ = new LuaScriptDiagnosticOverlay(textView);
|
||||
}
|
||||
|
||||
private LuaScriptDiagnosticOverlay(TextView textView)
|
||||
{
|
||||
_textView = textView;
|
||||
textView.BackgroundRenderers.Add(this);
|
||||
textView.MouseHover += OnMouseHover;
|
||||
textView.MouseHoverStopped += OnMouseHoverStopped;
|
||||
LuaScriptDiagnostics.Instance.Subscribe(this);
|
||||
}
|
||||
|
||||
public KnownLayer Layer => KnownLayer.Selection;
|
||||
|
||||
public void OnDiagnosticsChanged()
|
||||
{
|
||||
_textView.Dispatcher.BeginInvoke(() =>
|
||||
{
|
||||
_isDirty = true;
|
||||
_textView.InvalidateLayer(KnownLayer.Selection);
|
||||
});
|
||||
}
|
||||
|
||||
public void Draw(TextView textView, DrawingContext drawingContext)
|
||||
{
|
||||
var document = textView.Document;
|
||||
if (document is null)
|
||||
return;
|
||||
|
||||
if (_isDirty || !ReferenceEquals(document.Text, _renderedText))
|
||||
Rebuild(document);
|
||||
|
||||
if (_markers.Count == 0 || !textView.VisualLinesValid)
|
||||
return;
|
||||
|
||||
foreach (var marker in _markers)
|
||||
{
|
||||
foreach (var rect in BackgroundGeometryBuilder.GetRectsForSegment(textView, marker, false))
|
||||
DrawSquiggle(drawingContext, rect);
|
||||
}
|
||||
}
|
||||
|
||||
private void Rebuild(TextDocument document)
|
||||
{
|
||||
_isDirty = false;
|
||||
_renderedText = document.Text;
|
||||
_markers.Clear();
|
||||
|
||||
foreach (var diagnostic in LuaScriptDiagnostics.Instance.Get(document.Text))
|
||||
{
|
||||
if (TryCreateMarker(document, diagnostic, out var marker))
|
||||
_markers.Add(marker);
|
||||
}
|
||||
}
|
||||
|
||||
private static bool TryCreateMarker(TextDocument document, LuaScriptDiagnostic diagnostic, out Marker marker)
|
||||
{
|
||||
marker = null!;
|
||||
|
||||
int lineNumber = diagnostic.Line > 0 ? diagnostic.Line : 1;
|
||||
if (lineNumber > document.LineCount)
|
||||
return false;
|
||||
|
||||
var line = document.GetLineByNumber(lineNumber);
|
||||
|
||||
int offset;
|
||||
int length;
|
||||
if (diagnostic.Line > 0 && diagnostic.Column > 0 && diagnostic.Length > 0)
|
||||
{
|
||||
offset = Math.Min(line.Offset + diagnostic.Column - 1, line.EndOffset);
|
||||
length = Math.Min(diagnostic.Length, line.EndOffset - offset);
|
||||
}
|
||||
else
|
||||
{
|
||||
offset = SkipLeadingWhitespace(document, line);
|
||||
length = line.EndOffset - offset;
|
||||
}
|
||||
|
||||
if (length <= 0)
|
||||
{
|
||||
if (line.Length == 0)
|
||||
return false;
|
||||
offset = line.Offset;
|
||||
length = line.Length;
|
||||
}
|
||||
|
||||
marker = new Marker { Offset = offset, Length = length, Diagnostic = diagnostic };
|
||||
return true;
|
||||
}
|
||||
|
||||
private static int SkipLeadingWhitespace(TextDocument document, DocumentLine line)
|
||||
{
|
||||
int offset = line.Offset;
|
||||
while (offset < line.EndOffset)
|
||||
{
|
||||
char c = document.GetCharAt(offset);
|
||||
if (c != ' ' && c != '\t')
|
||||
break;
|
||||
offset++;
|
||||
}
|
||||
return offset;
|
||||
}
|
||||
|
||||
private void OnMouseHover(object? sender, MouseEventArgs e)
|
||||
{
|
||||
var document = _textView.Document;
|
||||
if (document is null)
|
||||
return;
|
||||
|
||||
var position = _textView.GetPositionFloor(e.GetPosition(_textView) + _textView.ScrollOffset);
|
||||
if (position is null)
|
||||
return;
|
||||
|
||||
int offset = document.GetOffset(position.Value.Location);
|
||||
foreach (var marker in _markers)
|
||||
{
|
||||
if (offset < marker.Offset || offset > marker.EndOffset)
|
||||
continue;
|
||||
|
||||
_toolTip.Content = BuildToolTipContent(marker.Diagnostic);
|
||||
_toolTip.IsOpen = true;
|
||||
e.Handled = true;
|
||||
return;
|
||||
}
|
||||
}
|
||||
|
||||
private void OnMouseHoverStopped(object? sender, MouseEventArgs e)
|
||||
{
|
||||
_toolTip.IsOpen = false;
|
||||
}
|
||||
|
||||
private static object BuildToolTipContent(LuaScriptDiagnostic diagnostic)
|
||||
{
|
||||
var panel = new StackPanel { MaxWidth = 480 };
|
||||
panel.Children.Add(new TextBlock { Text = KindLabel(diagnostic.Kind), FontWeight = FontWeights.Bold });
|
||||
if (!string.IsNullOrEmpty(diagnostic.Message))
|
||||
panel.Children.Add(new TextBlock { Text = diagnostic.Message, TextWrapping = TextWrapping.Wrap });
|
||||
return panel;
|
||||
}
|
||||
|
||||
private static string KindLabel(LuaScriptDiagnosticKind kind) => kind switch
|
||||
{
|
||||
LuaScriptDiagnosticKind.Compile => Texts.DiagnosticCompile,
|
||||
LuaScriptDiagnosticKind.Timeout => Texts.DiagnosticTimeout,
|
||||
_ => Texts.DiagnosticRuntime,
|
||||
};
|
||||
|
||||
private static void DrawSquiggle(DrawingContext drawingContext, Rect rect)
|
||||
{
|
||||
if (rect.Width <= 0)
|
||||
return;
|
||||
|
||||
const double step = 3.0;
|
||||
double baseline = rect.Bottom - 0.5;
|
||||
|
||||
var geometry = new StreamGeometry();
|
||||
using (var context = geometry.Open())
|
||||
{
|
||||
context.BeginFigure(new Point(rect.Left, baseline), false, false);
|
||||
|
||||
var points = new List<Point>();
|
||||
int index = 0;
|
||||
for (double x = rect.Left; x <= rect.Right; x += step)
|
||||
{
|
||||
points.Add(new Point(x, baseline - (index % 2 == 0 ? 0.0 : step)));
|
||||
index++;
|
||||
}
|
||||
context.PolyLineTo(points, true, false);
|
||||
}
|
||||
geometry.Freeze();
|
||||
|
||||
drawingContext.DrawGeometry(null, s_squigglePen, geometry);
|
||||
}
|
||||
|
||||
private static Pen CreateSquigglePen()
|
||||
{
|
||||
var pen = new Pen(new SolidColorBrush(Color.FromRgb(0xE5, 0x1A, 0x1A)), 1.0);
|
||||
pen.Brush.Freeze();
|
||||
pen.Freeze();
|
||||
return pen;
|
||||
}
|
||||
|
||||
private static FieldInfo? ResolveTextViewsField()
|
||||
{
|
||||
foreach (var field in typeof(FoldingManager).GetFields(BindingFlags.Instance | BindingFlags.NonPublic))
|
||||
{
|
||||
if (typeof(IEnumerable<TextView>).IsAssignableFrom(field.FieldType))
|
||||
return field;
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
private static TextView? ResolveTextView(FoldingManager? manager)
|
||||
{
|
||||
if (manager is null || s_textViewsField is null)
|
||||
return null;
|
||||
|
||||
try
|
||||
{
|
||||
if (s_textViewsField.GetValue(manager) is IEnumerable<TextView> views)
|
||||
{
|
||||
foreach (var view in views)
|
||||
{
|
||||
if (view is not null)
|
||||
return view;
|
||||
}
|
||||
}
|
||||
}
|
||||
catch
|
||||
{
|
||||
return null;
|
||||
}
|
||||
|
||||
return null;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,110 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
|
||||
namespace LuaScript.Diagnostics
|
||||
{
|
||||
internal interface ILuaScriptDiagnosticsListener
|
||||
{
|
||||
void OnDiagnosticsChanged();
|
||||
}
|
||||
|
||||
internal sealed class LuaScriptDiagnostics
|
||||
{
|
||||
public static LuaScriptDiagnostics Instance { get; } = new();
|
||||
|
||||
private const int MaxTrackedScripts = 64;
|
||||
|
||||
private readonly object _gate = new();
|
||||
private readonly Dictionary<string, IReadOnlyList<LuaScriptDiagnostic>> _entries = new(StringComparer.Ordinal);
|
||||
private readonly Queue<string> _insertionOrder = new();
|
||||
private readonly List<WeakReference<ILuaScriptDiagnosticsListener>> _listeners = [];
|
||||
|
||||
private LuaScriptDiagnostics()
|
||||
{
|
||||
}
|
||||
|
||||
public void Subscribe(ILuaScriptDiagnosticsListener listener)
|
||||
{
|
||||
lock (_gate)
|
||||
{
|
||||
PruneDeadListeners();
|
||||
_listeners.Add(new WeakReference<ILuaScriptDiagnosticsListener>(listener));
|
||||
}
|
||||
}
|
||||
|
||||
public IReadOnlyList<LuaScriptDiagnostic> Get(string? script)
|
||||
{
|
||||
if (script is null)
|
||||
return [];
|
||||
|
||||
lock (_gate)
|
||||
return _entries.TryGetValue(script, out var diagnostics) ? diagnostics : [];
|
||||
}
|
||||
|
||||
public void Report(string? script, IReadOnlyList<LuaScriptDiagnostic> diagnostics)
|
||||
{
|
||||
if (script is null)
|
||||
return;
|
||||
|
||||
diagnostics ??= [];
|
||||
|
||||
ILuaScriptDiagnosticsListener[] targets;
|
||||
lock (_gate)
|
||||
{
|
||||
if (_entries.TryGetValue(script, out var existing) && AreEqual(existing, diagnostics))
|
||||
return;
|
||||
|
||||
if (!_entries.ContainsKey(script))
|
||||
_insertionOrder.Enqueue(script);
|
||||
|
||||
_entries[script] = diagnostics;
|
||||
|
||||
while (_entries.Count > MaxTrackedScripts && _insertionOrder.Count > 0)
|
||||
{
|
||||
var oldest = _insertionOrder.Dequeue();
|
||||
if (!string.Equals(oldest, script, StringComparison.Ordinal))
|
||||
_entries.Remove(oldest);
|
||||
}
|
||||
|
||||
targets = CollectLiveListeners();
|
||||
}
|
||||
|
||||
foreach (var target in targets)
|
||||
target.OnDiagnosticsChanged();
|
||||
}
|
||||
|
||||
private ILuaScriptDiagnosticsListener[] CollectLiveListeners()
|
||||
{
|
||||
var live = new List<ILuaScriptDiagnosticsListener>(_listeners.Count);
|
||||
for (int i = _listeners.Count - 1; i >= 0; i--)
|
||||
{
|
||||
if (_listeners[i].TryGetTarget(out var listener))
|
||||
live.Add(listener);
|
||||
else
|
||||
_listeners.RemoveAt(i);
|
||||
}
|
||||
return [.. live];
|
||||
}
|
||||
|
||||
private void PruneDeadListeners()
|
||||
{
|
||||
for (int i = _listeners.Count - 1; i >= 0; i--)
|
||||
{
|
||||
if (!_listeners[i].TryGetTarget(out _))
|
||||
_listeners.RemoveAt(i);
|
||||
}
|
||||
}
|
||||
|
||||
private static bool AreEqual(IReadOnlyList<LuaScriptDiagnostic> a, IReadOnlyList<LuaScriptDiagnostic> b)
|
||||
{
|
||||
if (a.Count != b.Count)
|
||||
return false;
|
||||
for (int i = 0; i < a.Count; i++)
|
||||
{
|
||||
if (!a[i].Equals(b[i]))
|
||||
return false;
|
||||
}
|
||||
return true;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,13 @@
|
||||
namespace LuaScript
|
||||
{
|
||||
internal readonly record struct DrawCommand(
|
||||
double Ox,
|
||||
double Oy,
|
||||
double Oz,
|
||||
double Zoom,
|
||||
double Alpha,
|
||||
double Aspect,
|
||||
double[]? Poly = null,
|
||||
double Antialias = 1d,
|
||||
double Blend = 0d);
|
||||
}
|
||||
@@ -0,0 +1,175 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Numerics;
|
||||
using LuaScript.Compat;
|
||||
using Vortice.Direct2D1;
|
||||
using Vortice.Direct2D1.Effects;
|
||||
using YukkuriMovieMaker.Commons;
|
||||
using YukkuriMovieMaker.Player;
|
||||
using Blend = YukkuriMovieMaker.Project.Blend;
|
||||
|
||||
namespace LuaScript
|
||||
{
|
||||
internal sealed class DrawCompositor : IDisposable
|
||||
{
|
||||
private const int MaxDimension = 8192;
|
||||
|
||||
private readonly GraphicsDevicesAndContext _ctx;
|
||||
private ID2D1Bitmap1? _source;
|
||||
private ID2D1Bitmap1? _target;
|
||||
private AffineTransform2D? _placement;
|
||||
private ID2D1Image? _placementOutput;
|
||||
private Opacity? _opacityEffect;
|
||||
private ID2D1Image? _opacityOutput;
|
||||
private int _sourceWidth;
|
||||
private int _sourceHeight;
|
||||
private int _targetWidth;
|
||||
private int _targetHeight;
|
||||
|
||||
public DrawCompositor(GraphicsDevicesAndContext ctx)
|
||||
{
|
||||
_ctx = ctx;
|
||||
}
|
||||
|
||||
public unsafe ID2D1Image Compose(byte[] pixels, int width, int height, IReadOnlyList<DrawCommand> commands)
|
||||
{
|
||||
EnsureSource(width, height);
|
||||
fixed (byte* ptr = pixels)
|
||||
_source!.CopyFromMemory(new nint(ptr), width * 4);
|
||||
|
||||
double minX = double.MaxValue, minY = double.MaxValue;
|
||||
double maxX = double.MinValue, maxY = double.MinValue;
|
||||
for (int i = 0; i < commands.Count; i++)
|
||||
{
|
||||
var cmd = commands[i];
|
||||
if (cmd.Poly is { } poly)
|
||||
{
|
||||
DrawPolyMath.Bounds(poly, out double pMinX, out double pMinY, out double pMaxX, out double pMaxY);
|
||||
minX = Math.Min(minX, pMinX);
|
||||
maxX = Math.Max(maxX, pMaxX);
|
||||
minY = Math.Min(minY, pMinY);
|
||||
maxY = Math.Max(maxY, pMaxY);
|
||||
continue;
|
||||
}
|
||||
double aspect = Math.Clamp(cmd.Aspect, -1d, 1d);
|
||||
double zx = cmd.Zoom * (1d + aspect);
|
||||
double zy = cmd.Zoom * (1d - aspect);
|
||||
double halfW = width * 0.5 * zx;
|
||||
double halfH = height * 0.5 * zy;
|
||||
minX = Math.Min(minX, cmd.Ox - halfW);
|
||||
maxX = Math.Max(maxX, cmd.Ox + halfW);
|
||||
minY = Math.Min(minY, cmd.Oy - halfH);
|
||||
maxY = Math.Max(maxY, cmd.Oy + halfH);
|
||||
}
|
||||
|
||||
int originX = (int)Math.Floor(minX);
|
||||
int originY = (int)Math.Floor(minY);
|
||||
int targetW = Math.Clamp((int)Math.Ceiling(maxX) - originX, 1, MaxDimension);
|
||||
int targetH = Math.Clamp((int)Math.Ceiling(maxY) - originY, 1, MaxDimension);
|
||||
|
||||
EnsureTarget(targetW, targetH);
|
||||
|
||||
var dc = _ctx.DeviceContext;
|
||||
var rt = (ID2D1RenderTarget)dc;
|
||||
using var savedTarget = dc.Target;
|
||||
|
||||
dc.Target = _target;
|
||||
dc.BeginDraw();
|
||||
dc.Clear(null);
|
||||
var toTarget = Matrix3x2.CreateTranslation(-originX, -originY);
|
||||
for (int i = 0; i < commands.Count; i++)
|
||||
{
|
||||
var cmd = commands[i];
|
||||
if (!DrawTransform.TryResolve(cmd, width, height, out var transform))
|
||||
continue;
|
||||
|
||||
var interpolation = cmd.Antialias != 0d
|
||||
? BitmapInterpolationMode.Linear
|
||||
: BitmapInterpolationMode.NearestNeighbor;
|
||||
var blend = BlendModeMap.Resolve(cmd.Blend);
|
||||
|
||||
rt.Transform = transform * toTarget;
|
||||
DrawSource(rt, (float)Math.Clamp(cmd.Alpha, 0d, 1d), interpolation, blend);
|
||||
}
|
||||
rt.Transform = Matrix3x2.Identity;
|
||||
dc.EndDraw();
|
||||
dc.Target = savedTarget;
|
||||
|
||||
_placement!.TransformMatrix = Matrix3x2.CreateTranslation(originX, originY);
|
||||
return _placementOutput!;
|
||||
}
|
||||
|
||||
private void DrawSource(ID2D1RenderTarget rt, float opacity, BitmapInterpolationMode interpolation, Blend blend)
|
||||
{
|
||||
if (blend == Blend.Normal)
|
||||
{
|
||||
rt.DrawBitmap(_source!, opacity, interpolation);
|
||||
return;
|
||||
}
|
||||
|
||||
var interp = ToImageInterpolation(interpolation);
|
||||
_opacityEffect!.Value = opacity;
|
||||
if (blend.IsCompositionEffect())
|
||||
_ctx.DeviceContext.DrawImage(_opacityOutput!, interpolationMode: interp, compositeMode: blend.ToD2DCompositionMode());
|
||||
else
|
||||
_ctx.DeviceContext.BlendImage(_opacityOutput!, blend.ToD2DBlendMode(), null, null, interp);
|
||||
}
|
||||
|
||||
private static InterpolationMode ToImageInterpolation(BitmapInterpolationMode mode) =>
|
||||
mode == BitmapInterpolationMode.Linear ? InterpolationMode.Linear : InterpolationMode.NearestNeighbor;
|
||||
|
||||
private void EnsureSource(int width, int height)
|
||||
{
|
||||
if (_source is not null && _sourceWidth == width && _sourceHeight == height)
|
||||
return;
|
||||
|
||||
_source?.Dispose();
|
||||
_source = _ctx.DeviceContext.CreateEmptyBitmap(width, height, BitmapOptions.Target);
|
||||
_sourceWidth = width;
|
||||
_sourceHeight = height;
|
||||
|
||||
if (_opacityEffect is null)
|
||||
{
|
||||
_opacityEffect = new Opacity(_ctx.DeviceContext);
|
||||
_opacityOutput = _opacityEffect.Output;
|
||||
}
|
||||
_opacityEffect.SetInput(0, _source, true);
|
||||
}
|
||||
|
||||
private void EnsureTarget(int width, int height)
|
||||
{
|
||||
if (_target is not null && _targetWidth == width && _targetHeight == height)
|
||||
return;
|
||||
|
||||
_placementOutput?.Dispose();
|
||||
_placement?.Dispose();
|
||||
_target?.Dispose();
|
||||
_placementOutput = null;
|
||||
_placement = null;
|
||||
|
||||
_target = _ctx.DeviceContext.CreateEmptyBitmap(width, height, BitmapOptions.Target);
|
||||
_targetWidth = width;
|
||||
_targetHeight = height;
|
||||
|
||||
_placement = new AffineTransform2D(_ctx.DeviceContext);
|
||||
_placement.SetInput(0, _target, true);
|
||||
_placementOutput = _placement.Output;
|
||||
}
|
||||
|
||||
public void Dispose()
|
||||
{
|
||||
_placementOutput?.Dispose();
|
||||
_placement?.Dispose();
|
||||
_opacityOutput?.Dispose();
|
||||
_opacityEffect?.Dispose();
|
||||
_source?.Dispose();
|
||||
_target?.Dispose();
|
||||
_placementOutput = null;
|
||||
_placement = null;
|
||||
_opacityOutput = null;
|
||||
_opacityEffect = null;
|
||||
_source = null;
|
||||
_target = null;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,53 @@
|
||||
using System;
|
||||
using System.Numerics;
|
||||
|
||||
namespace LuaScript
|
||||
{
|
||||
internal static class DrawPolyMath
|
||||
{
|
||||
public const int Length = 21;
|
||||
|
||||
public static bool TrySolveAffine(double[] poly, out Matrix3x2 matrix)
|
||||
{
|
||||
double x0 = poly[0], y0 = poly[1];
|
||||
double x1 = poly[3], y1 = poly[4];
|
||||
double x3 = poly[9], y3 = poly[10];
|
||||
double u0 = poly[12], v0 = poly[13];
|
||||
double u1 = poly[14], v1 = poly[15];
|
||||
double u3 = poly[18], v3 = poly[19];
|
||||
|
||||
double det = u0 * (v1 - v3) - v0 * (u1 - u3) + (u1 * v3 - v1 * u3);
|
||||
if (Math.Abs(det) < 1e-9)
|
||||
{
|
||||
matrix = Matrix3x2.Identity;
|
||||
return false;
|
||||
}
|
||||
|
||||
double inv = 1d / det;
|
||||
double a = (x0 * (v1 - v3) - v0 * (x1 - x3) + (x1 * v3 - v1 * x3)) * inv;
|
||||
double b = (u0 * (x1 - x3) - x0 * (u1 - u3) + (u1 * x3 - x1 * u3)) * inv;
|
||||
double c = (u0 * (v1 * x3 - x1 * v3) - v0 * (u1 * x3 - x1 * u3) + x0 * (u1 * v3 - v1 * u3)) * inv;
|
||||
double d = (y0 * (v1 - v3) - v0 * (y1 - y3) + (y1 * v3 - v1 * y3)) * inv;
|
||||
double e = (u0 * (y1 - y3) - y0 * (u1 - u3) + (u1 * y3 - y1 * u3)) * inv;
|
||||
double f = (u0 * (v1 * y3 - y1 * v3) - v0 * (u1 * y3 - y1 * u3) + y0 * (u1 * v3 - v1 * u3)) * inv;
|
||||
|
||||
matrix = new Matrix3x2((float)a, (float)d, (float)b, (float)e, (float)c, (float)f);
|
||||
return true;
|
||||
}
|
||||
|
||||
public static void Bounds(double[] poly, out double minX, out double minY, out double maxX, out double maxY)
|
||||
{
|
||||
minX = minY = double.MaxValue;
|
||||
maxX = maxY = double.MinValue;
|
||||
for (int i = 0; i < 4; i++)
|
||||
{
|
||||
double x = poly[i * 3];
|
||||
double y = poly[i * 3 + 1];
|
||||
if (x < minX) minX = x;
|
||||
if (x > maxX) maxX = x;
|
||||
if (y < minY) minY = y;
|
||||
if (y > maxY) maxY = y;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,29 @@
|
||||
using System;
|
||||
using System.Numerics;
|
||||
|
||||
namespace LuaScript
|
||||
{
|
||||
internal static class DrawTransform
|
||||
{
|
||||
public static bool TryResolve(in DrawCommand command, int srcW, int srcH, out Matrix3x2 matrix)
|
||||
{
|
||||
if (command.Poly is { } poly)
|
||||
return DrawPolyMath.TrySolveAffine(poly, out matrix);
|
||||
|
||||
double aspect = Math.Clamp(command.Aspect, -1d, 1d);
|
||||
double zx = command.Zoom * (1d + aspect);
|
||||
double zy = command.Zoom * (1d - aspect);
|
||||
if (zx == 0d || zy == 0d)
|
||||
{
|
||||
matrix = Matrix3x2.Identity;
|
||||
return false;
|
||||
}
|
||||
|
||||
matrix =
|
||||
Matrix3x2.CreateTranslation(-srcW * 0.5f, -srcH * 0.5f) *
|
||||
Matrix3x2.CreateScale((float)zx, (float)zy) *
|
||||
Matrix3x2.CreateTranslation((float)command.Ox, (float)command.Oy);
|
||||
return true;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,95 @@
|
||||
using System.Diagnostics;
|
||||
using System.Runtime.Intrinsics;
|
||||
using System.Threading.Tasks;
|
||||
|
||||
namespace LuaScript.Engine.Kernel
|
||||
{
|
||||
internal sealed class CpuKernel(CpuKernel.RowDelegate row, CpuKernel.RowDelegate? block)
|
||||
{
|
||||
public delegate void RowDelegate(byte[] buffer, int rowBase, int xStart, int xEnd, double y, double[] uniforms);
|
||||
|
||||
private const int ParallelThreshold = 64;
|
||||
private const int WarmupRunsPerPath = 1;
|
||||
private const int TimedRunsPerPath = 3;
|
||||
|
||||
private readonly RowDelegate _row = row;
|
||||
private readonly RowDelegate? _block = block;
|
||||
private long _rowTicks;
|
||||
private long _blockTicks;
|
||||
private int _rowRuns;
|
||||
private int _blockRuns;
|
||||
private bool _nextIsBlock = true;
|
||||
private bool _decided;
|
||||
private bool _useBlock;
|
||||
|
||||
public bool? BlockAdopted => _decided ? _useBlock : null;
|
||||
|
||||
public void Execute(byte[] buffer, int width, int height, double[] uniforms)
|
||||
{
|
||||
if (_block is null || !Vector256.IsHardwareAccelerated)
|
||||
{
|
||||
Run(buffer, width, height, uniforms, false);
|
||||
return;
|
||||
}
|
||||
|
||||
if (_decided)
|
||||
{
|
||||
Run(buffer, width, height, uniforms, _useBlock);
|
||||
return;
|
||||
}
|
||||
|
||||
bool useBlock = _nextIsBlock;
|
||||
_nextIsBlock = !_nextIsBlock;
|
||||
|
||||
long start = Stopwatch.GetTimestamp();
|
||||
Run(buffer, width, height, uniforms, useBlock);
|
||||
long elapsed = Stopwatch.GetTimestamp() - start;
|
||||
|
||||
if (useBlock)
|
||||
{
|
||||
if (_blockRuns >= WarmupRunsPerPath)
|
||||
_blockTicks += elapsed;
|
||||
_blockRuns++;
|
||||
}
|
||||
else
|
||||
{
|
||||
if (_rowRuns >= WarmupRunsPerPath)
|
||||
_rowTicks += elapsed;
|
||||
_rowRuns++;
|
||||
}
|
||||
|
||||
if (_rowRuns >= WarmupRunsPerPath + TimedRunsPerPath &&
|
||||
_blockRuns >= WarmupRunsPerPath + TimedRunsPerPath)
|
||||
{
|
||||
_useBlock = _blockTicks < _rowTicks;
|
||||
_decided = true;
|
||||
}
|
||||
}
|
||||
|
||||
private void Run(byte[] buffer, int width, int height, double[] uniforms, bool useBlock)
|
||||
{
|
||||
var row = _row;
|
||||
var block = useBlock ? _block : null;
|
||||
int stride = width * 4;
|
||||
int blockWidth = block is null ? 0 : width & ~3;
|
||||
|
||||
void RunRow(int y)
|
||||
{
|
||||
int rowBase = y * stride;
|
||||
if (blockWidth > 0)
|
||||
block!(buffer, rowBase, 0, blockWidth, y, uniforms);
|
||||
if (blockWidth < width)
|
||||
row(buffer, rowBase, blockWidth, width, y, uniforms);
|
||||
}
|
||||
|
||||
if (height < ParallelThreshold)
|
||||
{
|
||||
for (int y = 0; y < height; y++)
|
||||
RunRow(y);
|
||||
return;
|
||||
}
|
||||
|
||||
Parallel.For(0, height, RunRow);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,222 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq.Expressions;
|
||||
using System.Reflection;
|
||||
|
||||
namespace LuaScript.Engine.Kernel
|
||||
{
|
||||
internal static class CpuKernelCompiler
|
||||
{
|
||||
private static readonly MethodInfo Clamp = typeof(Math).GetMethod(nameof(Math.Clamp), [typeof(double), typeof(double), typeof(double)])!;
|
||||
private static readonly MethodInfo Floor = Unary(nameof(Math.Floor));
|
||||
private static readonly MethodInfo Pow = Binary(nameof(Math.Pow));
|
||||
|
||||
private static readonly Dictionary<KFunc, MethodInfo> Functions = new()
|
||||
{
|
||||
[KFunc.Abs] = Unary(nameof(Math.Abs)),
|
||||
[KFunc.Floor] = Floor,
|
||||
[KFunc.Ceil] = Unary(nameof(Math.Ceiling)),
|
||||
[KFunc.Sqrt] = Unary(nameof(Math.Sqrt)),
|
||||
[KFunc.Sin] = Unary(nameof(Math.Sin)),
|
||||
[KFunc.Cos] = Unary(nameof(Math.Cos)),
|
||||
[KFunc.Tan] = Unary(nameof(Math.Tan)),
|
||||
[KFunc.Asin] = Unary(nameof(Math.Asin)),
|
||||
[KFunc.Acos] = Unary(nameof(Math.Acos)),
|
||||
[KFunc.Atan] = Unary(nameof(Math.Atan)),
|
||||
[KFunc.Atan2] = Binary(nameof(Math.Atan2)),
|
||||
[KFunc.Exp] = Unary(nameof(Math.Exp)),
|
||||
[KFunc.Log] = Unary(nameof(Math.Log)),
|
||||
[KFunc.Pow] = Pow,
|
||||
[KFunc.Min] = Binary(nameof(Math.Min)),
|
||||
[KFunc.Max] = Binary(nameof(Math.Max)),
|
||||
};
|
||||
|
||||
public static CpuKernel Compile(KernelProgram program) =>
|
||||
new(CompileRow(program), SimdKernelCompiler.TryCompile(program));
|
||||
|
||||
public static CpuKernel.RowDelegate CompileRow(KernelProgram program)
|
||||
{
|
||||
var buffer = Expression.Parameter(typeof(byte[]), "buffer");
|
||||
var rowBase = Expression.Parameter(typeof(int), "rowBase");
|
||||
var xStart = Expression.Parameter(typeof(int), "xStart");
|
||||
var xEnd = Expression.Parameter(typeof(int), "xEnd");
|
||||
var y = Expression.Parameter(typeof(double), "y");
|
||||
var uniforms = Expression.Parameter(typeof(double[]), "uniforms");
|
||||
|
||||
var x = Expression.Variable(typeof(int), "x");
|
||||
var index = Expression.Variable(typeof(int), "index");
|
||||
var alphaRaw = Expression.Variable(typeof(double), "alphaRaw");
|
||||
var transparent = Expression.Variable(typeof(bool), "transparent");
|
||||
var scale = Expression.Variable(typeof(double), "scale");
|
||||
var inputs = new[]
|
||||
{
|
||||
Expression.Variable(typeof(double), "inR"),
|
||||
Expression.Variable(typeof(double), "inG"),
|
||||
Expression.Variable(typeof(double), "inB"),
|
||||
Expression.Variable(typeof(double), "inA"),
|
||||
};
|
||||
var slots = new ParameterExpression[program.Bindings.Count];
|
||||
for (int i = 0; i < slots.Length; i++)
|
||||
slots[i] = Expression.Variable(typeof(double), "slot" + i);
|
||||
|
||||
var context = new Context(x, y, uniforms, inputs, slots);
|
||||
|
||||
var statements = new List<Expression>
|
||||
{
|
||||
Expression.Assign(index, Expression.Add(rowBase, Expression.Multiply(x, Constant(4)))),
|
||||
Expression.Assign(alphaRaw, ToDouble(ReadByte(buffer, index, 3))),
|
||||
Expression.Assign(transparent, Expression.LessThanOrEqual(alphaRaw, Constant(0d))),
|
||||
Expression.Assign(scale, Select(transparent, Constant(0d), Expression.Divide(Constant(255d), alphaRaw))),
|
||||
Expression.Assign(inputs[3], Select(transparent, Constant(0d), alphaRaw)),
|
||||
Expression.Assign(inputs[0], Select(transparent, Constant(0d), ClampByte(Expression.Multiply(ToDouble(ReadByte(buffer, index, 2)), scale)))),
|
||||
Expression.Assign(inputs[1], Select(transparent, Constant(0d), ClampByte(Expression.Multiply(ToDouble(ReadByte(buffer, index, 1)), scale)))),
|
||||
Expression.Assign(inputs[2], Select(transparent, Constant(0d), ClampByte(Expression.Multiply(ToDouble(ReadByte(buffer, index, 0)), scale)))),
|
||||
};
|
||||
|
||||
for (int i = 0; i < slots.Length; i++)
|
||||
statements.Add(Expression.Assign(slots[i], Build(program.Bindings[i], context)));
|
||||
|
||||
var outA = Expression.Variable(typeof(double), "outA");
|
||||
var alphaScale = Expression.Variable(typeof(double), "alphaScale");
|
||||
statements.Add(Expression.Assign(outA, Build(program.OutputA, context)));
|
||||
statements.Add(Expression.Assign(alphaScale, Expression.Divide(ClampByte(outA), Constant(255d))));
|
||||
statements.Add(WriteByte(buffer, index, 0, ClampByte(Expression.Multiply(Build(program.OutputB, context), alphaScale))));
|
||||
statements.Add(WriteByte(buffer, index, 1, ClampByte(Expression.Multiply(Build(program.OutputG, context), alphaScale))));
|
||||
statements.Add(WriteByte(buffer, index, 2, ClampByte(Expression.Multiply(Build(program.OutputR, context), alphaScale))));
|
||||
statements.Add(WriteByte(buffer, index, 3, ClampByte(outA)));
|
||||
statements.Add(Expression.PostIncrementAssign(x));
|
||||
|
||||
var breakLabel = Expression.Label("break");
|
||||
var loop = Expression.Loop(
|
||||
Expression.IfThenElse(
|
||||
Expression.LessThan(x, xEnd),
|
||||
Expression.Block(statements),
|
||||
Expression.Break(breakLabel)),
|
||||
breakLabel);
|
||||
|
||||
var locals = new List<ParameterExpression> { x, index, alphaRaw, transparent, scale, outA, alphaScale };
|
||||
locals.AddRange(inputs);
|
||||
locals.AddRange(slots);
|
||||
|
||||
var body = Expression.Block(locals, Expression.Assign(x, xStart), loop);
|
||||
|
||||
var lambda = Expression.Lambda<CpuKernel.RowDelegate>(body, buffer, rowBase, xStart, xEnd, y, uniforms);
|
||||
return lambda.Compile();
|
||||
}
|
||||
|
||||
private sealed record Context(
|
||||
ParameterExpression X,
|
||||
ParameterExpression Y,
|
||||
ParameterExpression Uniforms,
|
||||
ParameterExpression[] Inputs,
|
||||
ParameterExpression[] Slots);
|
||||
|
||||
private static Expression Build(KExpr expression, Context context)
|
||||
{
|
||||
switch (expression)
|
||||
{
|
||||
case KConst value:
|
||||
return Constant(value.Value);
|
||||
case KInput input:
|
||||
return context.Inputs[(int)input.Channel];
|
||||
case KCoord coord:
|
||||
return coord.Axis == KAxis.X ? ToDouble(context.X) : context.Y;
|
||||
case KUniformRef uniform:
|
||||
return Expression.ArrayIndex(context.Uniforms, Constant((int)uniform.Uniform));
|
||||
case KLocalRef local:
|
||||
return context.Slots[local.Slot];
|
||||
case KNegate negate:
|
||||
return Expression.Negate(Build(negate.Operand, context));
|
||||
case KArith arithmetic:
|
||||
return BuildArithmetic(arithmetic, context);
|
||||
case KCall call:
|
||||
return BuildCall(call, context);
|
||||
case KSelect select:
|
||||
return Select(BuildBool(select.Condition, context), Build(select.WhenTrue, context), Build(select.WhenFalse, context));
|
||||
}
|
||||
throw new KernelUnsupportedException("Unsupported CPU expression.");
|
||||
}
|
||||
|
||||
private static Expression BuildArithmetic(KArith arithmetic, Context context)
|
||||
{
|
||||
var left = Build(arithmetic.Left, context);
|
||||
var right = Build(arithmetic.Right, context);
|
||||
return arithmetic.Op switch
|
||||
{
|
||||
KArithOp.Add => Expression.Add(left, right),
|
||||
KArithOp.Subtract => Expression.Subtract(left, right),
|
||||
KArithOp.Multiply => Expression.Multiply(left, right),
|
||||
KArithOp.Divide => Expression.Divide(left, right),
|
||||
KArithOp.Modulo => FlooredModulo(left, right),
|
||||
KArithOp.Power => Expression.Call(Pow, left, right),
|
||||
_ => throw new KernelUnsupportedException("Unsupported arithmetic operator."),
|
||||
};
|
||||
}
|
||||
|
||||
private static Expression BuildCall(KCall call, Context context)
|
||||
{
|
||||
if (call.Func == KFunc.Fmod)
|
||||
return Expression.Modulo(Build(call.Arguments[0], context), Build(call.Arguments[1], context));
|
||||
var method = Functions[call.Func];
|
||||
if (call.Arguments.Count == 1)
|
||||
return Expression.Call(method, Build(call.Arguments[0], context));
|
||||
return Expression.Call(method, Build(call.Arguments[0], context), Build(call.Arguments[1], context));
|
||||
}
|
||||
|
||||
private static Expression BuildBool(KBool condition, Context context)
|
||||
{
|
||||
switch (condition)
|
||||
{
|
||||
case KBoolConst value:
|
||||
return Expression.Constant(value.Value);
|
||||
case KNot not:
|
||||
return Expression.Not(BuildBool(not.Operand, context));
|
||||
case KLogical logical:
|
||||
return logical.IsAnd
|
||||
? Expression.AndAlso(BuildBool(logical.Left, context), BuildBool(logical.Right, context))
|
||||
: Expression.OrElse(BuildBool(logical.Left, context), BuildBool(logical.Right, context));
|
||||
case KCompare compare:
|
||||
var left = Build(compare.Left, context);
|
||||
var right = Build(compare.Right, context);
|
||||
return compare.Op switch
|
||||
{
|
||||
KCompareOp.Less => Expression.LessThan(left, right),
|
||||
KCompareOp.Greater => Expression.GreaterThan(left, right),
|
||||
KCompareOp.LessEqual => Expression.LessThanOrEqual(left, right),
|
||||
KCompareOp.GreaterEqual => Expression.GreaterThanOrEqual(left, right),
|
||||
KCompareOp.Equal => Expression.Equal(left, right),
|
||||
KCompareOp.NotEqual => Expression.NotEqual(left, right),
|
||||
_ => throw new KernelUnsupportedException("Unsupported comparison."),
|
||||
};
|
||||
}
|
||||
throw new KernelUnsupportedException("Unsupported CPU condition.");
|
||||
}
|
||||
|
||||
private static Expression FlooredModulo(Expression left, Expression right) =>
|
||||
Expression.Subtract(left, Expression.Multiply(Expression.Call(Floor, Expression.Divide(left, right)), right));
|
||||
|
||||
private static Expression Select(Expression condition, Expression whenTrue, Expression whenFalse) =>
|
||||
Expression.Condition(condition, whenTrue, whenFalse);
|
||||
|
||||
private static Expression ClampByte(Expression value) =>
|
||||
Expression.Call(Clamp, value, Constant(0d), Constant(255d));
|
||||
|
||||
private static Expression ReadByte(ParameterExpression buffer, ParameterExpression index, int offset) =>
|
||||
Expression.ArrayIndex(buffer, offset == 0 ? index : Expression.Add(index, Constant(offset)));
|
||||
|
||||
private static Expression WriteByte(ParameterExpression buffer, ParameterExpression index, int offset, Expression value) =>
|
||||
Expression.Assign(
|
||||
Expression.ArrayAccess(buffer, offset == 0 ? index : Expression.Add(index, Constant(offset))),
|
||||
Expression.Convert(value, typeof(byte)));
|
||||
|
||||
private static Expression ToDouble(Expression value) => Expression.Convert(value, typeof(double));
|
||||
|
||||
private static ConstantExpression Constant(double value) => Expression.Constant(value, typeof(double));
|
||||
|
||||
private static ConstantExpression Constant(int value) => Expression.Constant(value, typeof(int));
|
||||
|
||||
private static MethodInfo Unary(string name) => typeof(Math).GetMethod(name, [typeof(double)])!;
|
||||
|
||||
private static MethodInfo Binary(string name) => typeof(Math).GetMethod(name, [typeof(double), typeof(double)])!;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,163 @@
|
||||
using System;
|
||||
using System.Numerics;
|
||||
using System.Runtime.InteropServices;
|
||||
using Vortice.DCommon;
|
||||
using Vortice.Direct2D1;
|
||||
using Vortice.DXGI;
|
||||
using Vortice.Mathematics;
|
||||
using YukkuriMovieMaker.Commons;
|
||||
|
||||
namespace LuaScript.Engine.Kernel
|
||||
{
|
||||
internal sealed class GpuKernel : IDisposable
|
||||
{
|
||||
private const int VerifySize = 64;
|
||||
private const int VerifyTolerance = 2;
|
||||
|
||||
private readonly IGraphicsDevicesAndContext _devices;
|
||||
private readonly GpuKernelEffect _effect;
|
||||
private readonly float[] _packed = new float[HlslKernelEmitter.ConstantFloatCount];
|
||||
private readonly byte[] _bytes = new byte[HlslKernelEmitter.ConstantFloatCount * sizeof(float)];
|
||||
private ID2D1Image? _output;
|
||||
|
||||
public GpuKernel(IGraphicsDevicesAndContext devices, KernelProgram program)
|
||||
{
|
||||
_devices = devices;
|
||||
_effect = new GpuKernelEffect(devices, HlslKernelEmitter.Emit(program));
|
||||
}
|
||||
|
||||
public bool IsReady => _effect.IsReady;
|
||||
|
||||
public ID2D1Image Apply(ID2D1Image input, double[] uniforms)
|
||||
{
|
||||
KernelUniformBinding.Pack(uniforms, _packed);
|
||||
Buffer.BlockCopy(_packed, 0, _bytes, 0, _bytes.Length);
|
||||
_effect.SetConstants(_bytes);
|
||||
_effect.SetInput(0, input, true);
|
||||
return _output ??= _effect.Output;
|
||||
}
|
||||
|
||||
public unsafe bool Verify(CpuKernel reference)
|
||||
{
|
||||
if (!IsReady)
|
||||
return false;
|
||||
|
||||
var uniforms = KernelUniformBinding.Create();
|
||||
for (int i = 0; i < uniforms.Length; i++)
|
||||
uniforms[i] = (i % 7) + 1;
|
||||
uniforms[(int)KernelUniform.Width] = VerifySize;
|
||||
uniforms[(int)KernelUniform.Height] = VerifySize;
|
||||
|
||||
byte[] probe = BuildProbe(VerifySize);
|
||||
byte[] expected = (byte[])probe.Clone();
|
||||
reference.Execute(expected, VerifySize, VerifySize, uniforms);
|
||||
|
||||
var dc = (ID2D1DeviceContext)_devices.DeviceContext;
|
||||
ID2D1Bitmap1? source = null;
|
||||
ID2D1Bitmap1? target = null;
|
||||
ID2D1Bitmap1? staging = null;
|
||||
try
|
||||
{
|
||||
source = dc.CreateEmptyBitmap(VerifySize, VerifySize, BitmapOptions.Target);
|
||||
fixed (byte* ptr = probe)
|
||||
source.CopyFromMemory(new nint(ptr), VerifySize * 4);
|
||||
|
||||
target = dc.CreateEmptyBitmap(VerifySize, VerifySize, BitmapOptions.Target);
|
||||
|
||||
var stagingProps = new BitmapProperties1(
|
||||
new PixelFormat(Format.B8G8R8A8_UNorm, Vortice.DCommon.AlphaMode.Premultiplied),
|
||||
96f, 96f,
|
||||
BitmapOptions.CpuRead | BitmapOptions.CannotDraw);
|
||||
staging = dc.CreateBitmap(new SizeI(VerifySize, VerifySize), nint.Zero, VerifySize * 4, stagingProps);
|
||||
|
||||
var output = Apply(source, uniforms);
|
||||
|
||||
using var savedTarget = dc.Target;
|
||||
dc.Target = target;
|
||||
try
|
||||
{
|
||||
dc.BeginDraw();
|
||||
dc.Clear(null);
|
||||
dc.DrawImage(output, new Vector2(0f, 0f));
|
||||
dc.EndDraw();
|
||||
}
|
||||
finally
|
||||
{
|
||||
dc.Target = savedTarget;
|
||||
}
|
||||
|
||||
staging.CopyFromBitmap(target);
|
||||
byte[] actual = new byte[VerifySize * VerifySize * 4];
|
||||
var mapped = staging.Map(MapOptions.Read);
|
||||
try
|
||||
{
|
||||
if (mapped.Pitch == VerifySize * 4)
|
||||
{
|
||||
Marshal.Copy(mapped.Bits, actual, 0, actual.Length);
|
||||
}
|
||||
else
|
||||
{
|
||||
for (int row = 0; row < VerifySize; row++)
|
||||
Marshal.Copy(mapped.Bits + mapped.Pitch * row, actual, row * VerifySize * 4, VerifySize * 4);
|
||||
}
|
||||
}
|
||||
finally
|
||||
{
|
||||
staging.Unmap();
|
||||
}
|
||||
|
||||
return WithinTolerance(expected, actual, VerifyTolerance);
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
Log.Default.Write("LuaScript: GPU kernel verification could not run; using the CPU kernel.", ex);
|
||||
return false;
|
||||
}
|
||||
finally
|
||||
{
|
||||
source?.Dispose();
|
||||
target?.Dispose();
|
||||
staging?.Dispose();
|
||||
}
|
||||
}
|
||||
|
||||
private static byte[] BuildProbe(int size)
|
||||
{
|
||||
var buffer = new byte[size * size * 4];
|
||||
ReadOnlySpan<int> alphas = [0, 64, 128, 200, 255];
|
||||
for (int y = 0; y < size; y++)
|
||||
{
|
||||
for (int x = 0; x < size; x++)
|
||||
{
|
||||
int alpha = alphas[(x + y) % alphas.Length];
|
||||
int r = x * 255 / (size - 1);
|
||||
int g = y * 255 / (size - 1);
|
||||
int b = (x + y) * 255 / (2 * (size - 1));
|
||||
int p = (y * size + x) * 4;
|
||||
buffer[p] = (byte)(b * alpha / 255);
|
||||
buffer[p + 1] = (byte)(g * alpha / 255);
|
||||
buffer[p + 2] = (byte)(r * alpha / 255);
|
||||
buffer[p + 3] = (byte)alpha;
|
||||
}
|
||||
}
|
||||
return buffer;
|
||||
}
|
||||
|
||||
private static bool WithinTolerance(byte[] expected, byte[] actual, int tolerance)
|
||||
{
|
||||
if (expected.Length != actual.Length)
|
||||
return false;
|
||||
for (int i = 0; i < expected.Length; i++)
|
||||
if (Math.Abs(expected[i] - actual[i]) > tolerance)
|
||||
return false;
|
||||
return true;
|
||||
}
|
||||
|
||||
public void Dispose()
|
||||
{
|
||||
_output?.Dispose();
|
||||
_output = null;
|
||||
_effect.Dispose();
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,193 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Runtime.InteropServices;
|
||||
using System.Text;
|
||||
using System.Threading;
|
||||
using Vortice;
|
||||
using Vortice.D3DCompiler;
|
||||
using Vortice.Direct2D1;
|
||||
using Vortice.Direct3D;
|
||||
using Vortice.Mathematics;
|
||||
using YukkuriMovieMaker.Commons;
|
||||
|
||||
namespace LuaScript.Engine.Kernel
|
||||
{
|
||||
internal sealed class GpuKernelEffect : ID2D1Effect
|
||||
{
|
||||
private const int ConstantsIndex = 0;
|
||||
private const int InitializedIndex = 1;
|
||||
|
||||
[StructLayout(LayoutKind.Sequential)]
|
||||
private unsafe struct ConstantBuffer
|
||||
{
|
||||
public fixed float Values[HlslKernelEmitter.ConstantFloatCount];
|
||||
}
|
||||
|
||||
[CustomEffect(1, null, null, null, null)]
|
||||
private sealed class Impl(Guid guid, string hlsl) : CustomEffectBase, ID2D1DrawTransform
|
||||
{
|
||||
private ConstantBuffer _constants;
|
||||
private ID2D1DrawInfo? _drawInfo;
|
||||
|
||||
[CustomEffectProperty(PropertyType.Blob, ConstantsIndex)]
|
||||
public byte[] Constants
|
||||
{
|
||||
get => ToBytes(_constants);
|
||||
set
|
||||
{
|
||||
FromBytes(value, ref _constants);
|
||||
_drawInfo?.SetPixelShaderConstantBuffer(in _constants);
|
||||
}
|
||||
}
|
||||
|
||||
[CustomEffectProperty(PropertyType.Bool, InitializedIndex)]
|
||||
public bool Initialized { get; private set; }
|
||||
|
||||
public override void Initialize(ID2D1EffectContext effectContext, ID2D1TransformGraph transformGraph)
|
||||
{
|
||||
byte[] source = Encoding.ASCII.GetBytes(hlsl);
|
||||
var result = Compiler.Compile(source, "main", string.Empty, "ps_4_1", out var bytecode, out var errors);
|
||||
if (result.Failure || bytecode is null)
|
||||
{
|
||||
Initialized = false;
|
||||
Log.Default.Write("LuaScript: GPU kernel shader compilation failed.\n" + (errors?.AsString() ?? string.Empty));
|
||||
errors?.Dispose();
|
||||
bytecode?.Dispose();
|
||||
return;
|
||||
}
|
||||
|
||||
try
|
||||
{
|
||||
byte[] shader = bytecode.AsBytes();
|
||||
effectContext.LoadPixelShader(guid, shader, shader.Length);
|
||||
transformGraph.SetSingleTransformNode(this);
|
||||
Initialized = true;
|
||||
}
|
||||
finally
|
||||
{
|
||||
errors?.Dispose();
|
||||
bytecode.Dispose();
|
||||
}
|
||||
}
|
||||
|
||||
public void SetDrawInfo(ID2D1DrawInfo drawInfo)
|
||||
{
|
||||
_drawInfo = drawInfo;
|
||||
drawInfo.SetPixelShader(guid, PixelOptions.None);
|
||||
drawInfo.SetInputDescription(0, new InputDescription { Filter = (Filter)21, LevelOfDetailCount = 1 });
|
||||
drawInfo.SetPixelShaderConstantBuffer(in _constants);
|
||||
}
|
||||
|
||||
public int GetInputCount() => 1;
|
||||
|
||||
public void MapOutputRectToInputRects(RawRect outputRect, RawRect[] inputRects) =>
|
||||
inputRects[0] = outputRect;
|
||||
|
||||
public void MapInputRectsToOutputRect(RawRect[] inputRects, RawRect[] inputOpaqueSubRects, out RawRect outputRect, out RawRect outputOpaqueSubRect)
|
||||
{
|
||||
outputRect = inputRects[0];
|
||||
outputOpaqueSubRect = default;
|
||||
}
|
||||
|
||||
public RawRect MapInvalidRect(int inputIndex, RawRect invalidInputRect) => invalidInputRect;
|
||||
|
||||
private static unsafe byte[] ToBytes(ConstantBuffer constants)
|
||||
{
|
||||
byte[] bytes = new byte[sizeof(ConstantBuffer)];
|
||||
fixed (byte* destination = bytes)
|
||||
*(ConstantBuffer*)destination = constants;
|
||||
return bytes;
|
||||
}
|
||||
|
||||
private static unsafe void FromBytes(byte[] bytes, ref ConstantBuffer constants)
|
||||
{
|
||||
int length = Math.Min(bytes.Length, sizeof(ConstantBuffer));
|
||||
fixed (byte* source = bytes)
|
||||
fixed (ConstantBuffer* destination = &constants)
|
||||
Buffer.MemoryCopy(source, destination, sizeof(ConstantBuffer), length);
|
||||
}
|
||||
}
|
||||
|
||||
private sealed class Manager
|
||||
{
|
||||
private readonly Lock _locker = new();
|
||||
private readonly Dictionary<int, Dictionary<string, (Guid Guid, int Count)>> _registered = [];
|
||||
|
||||
public Guid Acquire(IGraphicsDevicesAndContext devices, string hlsl)
|
||||
{
|
||||
lock (_locker)
|
||||
{
|
||||
int device = devices.GetHashCode();
|
||||
if (!_registered.TryGetValue(device, out var byHlsl))
|
||||
{
|
||||
byHlsl = [];
|
||||
_registered[device] = byHlsl;
|
||||
}
|
||||
if (byHlsl.TryGetValue(hlsl, out var entry))
|
||||
{
|
||||
byHlsl[hlsl] = (entry.Guid, entry.Count + 1);
|
||||
return entry.Guid;
|
||||
}
|
||||
|
||||
var guid = Guid.NewGuid();
|
||||
byHlsl[hlsl] = (guid, 1);
|
||||
((ID2D1Factory1)devices.D2D.Factory).RegisterEffect<Impl>(() => new Impl(guid, hlsl), guid);
|
||||
return guid;
|
||||
}
|
||||
}
|
||||
|
||||
public void Release(IGraphicsDevicesAndContext devices, string hlsl)
|
||||
{
|
||||
lock (_locker)
|
||||
{
|
||||
int device = devices.GetHashCode();
|
||||
if (!_registered.TryGetValue(device, out var byHlsl) || !byHlsl.TryGetValue(hlsl, out var entry))
|
||||
return;
|
||||
if (entry.Count > 1)
|
||||
{
|
||||
byHlsl[hlsl] = (entry.Guid, entry.Count - 1);
|
||||
return;
|
||||
}
|
||||
byHlsl.Remove(hlsl);
|
||||
((ID2D1Factory1)devices.D2D.Factory).UnregisterEffect(entry.Guid);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private static readonly Manager Effects = new();
|
||||
|
||||
private readonly IGraphicsDevicesAndContext _devices;
|
||||
private readonly string _hlsl;
|
||||
|
||||
public GpuKernelEffect(IGraphicsDevicesAndContext devices, string hlsl)
|
||||
: base(Create(devices, hlsl))
|
||||
{
|
||||
_devices = devices;
|
||||
_hlsl = hlsl;
|
||||
}
|
||||
|
||||
public bool IsReady => NativePointer != nint.Zero && ((ID2D1Properties)this).GetBoolValue(InitializedIndex);
|
||||
|
||||
public void SetConstants(byte[] bytes) => ((ID2D1Properties)this).SetValue(ConstantsIndex, bytes);
|
||||
|
||||
private static nint Create(IGraphicsDevicesAndContext devices, string hlsl)
|
||||
{
|
||||
try
|
||||
{
|
||||
var guid = Effects.Acquire(devices, hlsl);
|
||||
return ((ID2D1DeviceContext)devices.DeviceContext).CreateEffect(guid);
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
Log.Default.Write("LuaScript: failed to create GPU kernel effect.", ex);
|
||||
return nint.Zero;
|
||||
}
|
||||
}
|
||||
|
||||
protected override void DisposeCore(nint nativePointer, bool disposing)
|
||||
{
|
||||
base.DisposeCore(nativePointer, disposing);
|
||||
Effects.Release(_devices, _hlsl);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,225 @@
|
||||
using System.Globalization;
|
||||
using System.Text;
|
||||
|
||||
namespace LuaScript.Engine.Kernel
|
||||
{
|
||||
internal static class HlslKernelEmitter
|
||||
{
|
||||
public const int ConstantVectorCount = 16;
|
||||
|
||||
public const int ConstantFloatCount = ConstantVectorCount * 4;
|
||||
|
||||
private static readonly string[] Intrinsics =
|
||||
[
|
||||
"abs", "floor", "ceil", "sqrt", "sin", "cos", "tan", "asin", "acos",
|
||||
"atan", "atan2", "exp", "log", "pow", "min", "max", "fmod",
|
||||
];
|
||||
|
||||
public static string Emit(KernelProgram program)
|
||||
{
|
||||
var builder = new StringBuilder(1024);
|
||||
|
||||
builder.Append("Texture2D InputTexture : register(t0);\n");
|
||||
builder.Append("SamplerState InputSampler : register(s0);\n");
|
||||
builder.Append("cbuffer constants : register(b0)\n{\n");
|
||||
builder.Append(" float4 uniforms[").Append(ConstantVectorCount).Append("];\n");
|
||||
builder.Append("};\n\n");
|
||||
builder.Append("float4 main(float4 pos : SV_POSITION, float4 posScene : SCENE_POSITION, float4 uv : TEXCOORD0) : SV_Target\n{\n");
|
||||
builder.Append(" float4 src = InputTexture.Sample(InputSampler, uv.xy);\n");
|
||||
builder.Append(" float srcA = src.a;\n");
|
||||
builder.Append(" float invA = srcA <= 0.0 ? 0.0 : 1.0 / srcA;\n");
|
||||
builder.Append(" float inR = clamp(src.r * invA * 255.0, 0.0, 255.0);\n");
|
||||
builder.Append(" float inG = clamp(src.g * invA * 255.0, 0.0, 255.0);\n");
|
||||
builder.Append(" float inB = clamp(src.b * invA * 255.0, 0.0, 255.0);\n");
|
||||
builder.Append(" float inA = srcA * 255.0;\n");
|
||||
builder.Append(" float px = uv.x * ").Append(Uniform(KernelUniform.Width)).Append(" - 0.5;\n");
|
||||
builder.Append(" float py = uv.y * ").Append(Uniform(KernelUniform.Height)).Append(" - 0.5;\n");
|
||||
|
||||
for (int i = 0; i < program.Bindings.Count; i++)
|
||||
{
|
||||
builder.Append(" float slot").Append(i).Append(" = ");
|
||||
EmitExpression(builder, program.Bindings[i]);
|
||||
builder.Append(";\n");
|
||||
}
|
||||
|
||||
builder.Append(" float outA = clamp(");
|
||||
EmitExpression(builder, program.OutputA);
|
||||
builder.Append(", 0.0, 255.0);\n");
|
||||
builder.Append(" float alphaK = outA / 255.0;\n");
|
||||
|
||||
builder.Append(" float oR = floor(clamp((");
|
||||
EmitExpression(builder, program.OutputR);
|
||||
builder.Append(") * alphaK, 0.0, 255.0)) / 255.0;\n");
|
||||
builder.Append(" float oG = floor(clamp((");
|
||||
EmitExpression(builder, program.OutputG);
|
||||
builder.Append(") * alphaK, 0.0, 255.0)) / 255.0;\n");
|
||||
builder.Append(" float oB = floor(clamp((");
|
||||
EmitExpression(builder, program.OutputB);
|
||||
builder.Append(") * alphaK, 0.0, 255.0)) / 255.0;\n");
|
||||
builder.Append(" float oA = floor(outA) / 255.0;\n");
|
||||
builder.Append(" return float4(oR, oG, oB, oA);\n}\n");
|
||||
|
||||
return builder.ToString();
|
||||
}
|
||||
|
||||
private static void EmitExpression(StringBuilder builder, KExpr expression)
|
||||
{
|
||||
switch (expression)
|
||||
{
|
||||
case KConst value:
|
||||
builder.Append(Number(value.Value));
|
||||
return;
|
||||
case KInput input:
|
||||
builder.Append(input.Channel switch
|
||||
{
|
||||
KChannel.R => "inR",
|
||||
KChannel.G => "inG",
|
||||
KChannel.B => "inB",
|
||||
_ => "inA",
|
||||
});
|
||||
return;
|
||||
case KCoord coord:
|
||||
builder.Append(coord.Axis == KAxis.X ? "px" : "py");
|
||||
return;
|
||||
case KUniformRef uniform:
|
||||
builder.Append(Uniform(uniform.Uniform));
|
||||
return;
|
||||
case KLocalRef local:
|
||||
builder.Append("slot").Append(local.Slot);
|
||||
return;
|
||||
case KNegate negate:
|
||||
builder.Append("(-(");
|
||||
EmitExpression(builder, negate.Operand);
|
||||
builder.Append("))");
|
||||
return;
|
||||
case KArith arithmetic:
|
||||
EmitArithmetic(builder, arithmetic);
|
||||
return;
|
||||
case KCall call:
|
||||
EmitCall(builder, call);
|
||||
return;
|
||||
case KSelect select:
|
||||
builder.Append('(');
|
||||
EmitCondition(builder, select.Condition);
|
||||
builder.Append(" ? (");
|
||||
EmitExpression(builder, select.WhenTrue);
|
||||
builder.Append(") : (");
|
||||
EmitExpression(builder, select.WhenFalse);
|
||||
builder.Append("))");
|
||||
return;
|
||||
}
|
||||
throw new KernelUnsupportedException("Unsupported HLSL expression.");
|
||||
}
|
||||
|
||||
private static void EmitArithmetic(StringBuilder builder, KArith arithmetic)
|
||||
{
|
||||
if (arithmetic.Op == KArithOp.Power)
|
||||
{
|
||||
builder.Append("pow(");
|
||||
EmitExpression(builder, arithmetic.Left);
|
||||
builder.Append(", ");
|
||||
EmitExpression(builder, arithmetic.Right);
|
||||
builder.Append(')');
|
||||
return;
|
||||
}
|
||||
|
||||
if (arithmetic.Op == KArithOp.Modulo)
|
||||
{
|
||||
builder.Append('(');
|
||||
EmitExpression(builder, arithmetic.Left);
|
||||
builder.Append(" - floor((");
|
||||
EmitExpression(builder, arithmetic.Left);
|
||||
builder.Append(") / (");
|
||||
EmitExpression(builder, arithmetic.Right);
|
||||
builder.Append(")) * (");
|
||||
EmitExpression(builder, arithmetic.Right);
|
||||
builder.Append("))");
|
||||
return;
|
||||
}
|
||||
|
||||
builder.Append('(');
|
||||
EmitExpression(builder, arithmetic.Left);
|
||||
builder.Append(arithmetic.Op switch
|
||||
{
|
||||
KArithOp.Add => " + ",
|
||||
KArithOp.Subtract => " - ",
|
||||
KArithOp.Multiply => " * ",
|
||||
KArithOp.Divide => " / ",
|
||||
_ => throw new KernelUnsupportedException("Unsupported arithmetic operator."),
|
||||
});
|
||||
EmitExpression(builder, arithmetic.Right);
|
||||
builder.Append(')');
|
||||
}
|
||||
|
||||
private static void EmitCall(StringBuilder builder, KCall call)
|
||||
{
|
||||
builder.Append(Intrinsics[(int)call.Func]).Append('(');
|
||||
for (int i = 0; i < call.Arguments.Count; i++)
|
||||
{
|
||||
if (i > 0)
|
||||
builder.Append(", ");
|
||||
EmitExpression(builder, call.Arguments[i]);
|
||||
}
|
||||
builder.Append(')');
|
||||
}
|
||||
|
||||
private static void EmitCondition(StringBuilder builder, KBool condition)
|
||||
{
|
||||
switch (condition)
|
||||
{
|
||||
case KBoolConst value:
|
||||
builder.Append(value.Value ? "true" : "false");
|
||||
return;
|
||||
case KNot not:
|
||||
builder.Append("(!(");
|
||||
EmitCondition(builder, not.Operand);
|
||||
builder.Append("))");
|
||||
return;
|
||||
case KLogical logical:
|
||||
builder.Append('(');
|
||||
EmitCondition(builder, logical.Left);
|
||||
builder.Append(logical.IsAnd ? " && " : " || ");
|
||||
EmitCondition(builder, logical.Right);
|
||||
builder.Append(')');
|
||||
return;
|
||||
case KCompare compare:
|
||||
builder.Append('(');
|
||||
EmitExpression(builder, compare.Left);
|
||||
builder.Append(compare.Op switch
|
||||
{
|
||||
KCompareOp.Less => " < ",
|
||||
KCompareOp.Greater => " > ",
|
||||
KCompareOp.LessEqual => " <= ",
|
||||
KCompareOp.GreaterEqual => " >= ",
|
||||
KCompareOp.Equal => " == ",
|
||||
_ => " != ",
|
||||
});
|
||||
EmitExpression(builder, compare.Right);
|
||||
builder.Append(')');
|
||||
return;
|
||||
}
|
||||
throw new KernelUnsupportedException("Unsupported HLSL condition.");
|
||||
}
|
||||
|
||||
private static string Uniform(KernelUniform uniform)
|
||||
{
|
||||
int index = (int)uniform;
|
||||
return $"uniforms[{index / 4}].{"xyzw"[index % 4]}";
|
||||
}
|
||||
|
||||
private static string Number(double value)
|
||||
{
|
||||
if (double.IsPositiveInfinity(value))
|
||||
return "3.4028235e38";
|
||||
if (double.IsNegativeInfinity(value))
|
||||
return "-3.4028235e38";
|
||||
if (double.IsNaN(value))
|
||||
return "(0.0 / 0.0)";
|
||||
|
||||
string text = value.ToString("R", CultureInfo.InvariantCulture);
|
||||
if (!text.Contains('.') && !text.Contains('e') && !text.Contains('E'))
|
||||
text += ".0";
|
||||
return text;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,516 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
|
||||
namespace LuaScript.Engine.Kernel
|
||||
{
|
||||
internal sealed class KernelExtractor
|
||||
{
|
||||
private readonly record struct FuncSpec(KFunc Func, int MinArgs, int MaxArgs);
|
||||
|
||||
private static readonly Dictionary<string, FuncSpec> MathFunctions = new(StringComparer.Ordinal)
|
||||
{
|
||||
["abs"] = new(KFunc.Abs, 1, 1),
|
||||
["floor"] = new(KFunc.Floor, 1, 1),
|
||||
["ceil"] = new(KFunc.Ceil, 1, 1),
|
||||
["sqrt"] = new(KFunc.Sqrt, 1, 1),
|
||||
["sin"] = new(KFunc.Sin, 1, 1),
|
||||
["cos"] = new(KFunc.Cos, 1, 1),
|
||||
["tan"] = new(KFunc.Tan, 1, 1),
|
||||
["asin"] = new(KFunc.Asin, 1, 1),
|
||||
["acos"] = new(KFunc.Acos, 1, 1),
|
||||
["atan"] = new(KFunc.Atan, 1, 1),
|
||||
["atan2"] = new(KFunc.Atan2, 2, 2),
|
||||
["exp"] = new(KFunc.Exp, 1, 1),
|
||||
["log"] = new(KFunc.Log, 1, 1),
|
||||
["pow"] = new(KFunc.Pow, 2, 2),
|
||||
["fmod"] = new(KFunc.Fmod, 2, 2),
|
||||
["min"] = new(KFunc.Min, 2, int.MaxValue),
|
||||
["max"] = new(KFunc.Max, 2, int.MaxValue),
|
||||
};
|
||||
|
||||
private readonly List<KExpr> _bindings = [];
|
||||
private readonly Dictionary<string, int> _scope = new(StringComparer.Ordinal);
|
||||
private readonly SortedSet<KernelUniform> _uniforms = [];
|
||||
|
||||
private string _widthVariable = string.Empty;
|
||||
private string _heightVariable = string.Empty;
|
||||
private bool _coordsEnabled;
|
||||
private string? _pixelDataVariable;
|
||||
private string _baseIndexVariable = string.Empty;
|
||||
private readonly bool[] _writtenChannels = new bool[4];
|
||||
|
||||
public static KernelProgram? TryExtract(string runnableScript)
|
||||
{
|
||||
try
|
||||
{
|
||||
return new KernelExtractor().Extract(runnableScript);
|
||||
}
|
||||
catch (KernelUnsupportedException)
|
||||
{
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
private KernelProgram? Extract(string runnableScript)
|
||||
{
|
||||
var block = LuaParser.Parse(runnableScript);
|
||||
|
||||
int index = 0;
|
||||
while (index < block.Count && block[index] is LocalStmt prelude)
|
||||
{
|
||||
if (TryBindPixelData(prelude))
|
||||
{
|
||||
index++;
|
||||
continue;
|
||||
}
|
||||
BindLocal(prelude);
|
||||
index++;
|
||||
}
|
||||
|
||||
if (index >= block.Count || block[index] is not NumericForStmt outer)
|
||||
return null;
|
||||
if (index + 1 != block.Count)
|
||||
return null;
|
||||
|
||||
if (!TryAxis(outer, out string outerVar, out KAxis outerAxis))
|
||||
return null;
|
||||
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;
|
||||
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;
|
||||
|
||||
return _pixelDataVariable is null ? BuildKernel(inner.Body) : BuildPixelDataKernel(inner.Body);
|
||||
}
|
||||
|
||||
private bool TryBindPixelData(LocalStmt local)
|
||||
{
|
||||
if (local.Names.Count != 1 || local.Values.Count != 1 ||
|
||||
local.Values[0] is not CallExpr { Target: MemberExpr { Target: NameExpr { Name: "obj" }, Name: "getpixeldata" }, Arguments.Count: 0 })
|
||||
return false;
|
||||
if (_pixelDataVariable is not null)
|
||||
throw new KernelUnsupportedException("Multiple pixel-data handles are not supported.");
|
||||
_pixelDataVariable = local.Names[0];
|
||||
return true;
|
||||
}
|
||||
|
||||
private KernelProgram? BuildPixelDataKernel(IReadOnlyList<LuaStmt> body)
|
||||
{
|
||||
if (body.Count < 5)
|
||||
return null;
|
||||
if (body[0] is not LocalStmt { Names.Count: 1, Values.Count: 1 } baseStmt || !IsBaseIndex(baseStmt.Values[0]))
|
||||
return null;
|
||||
|
||||
EnsureNotCoordinateName(baseStmt.Names[0]);
|
||||
_baseIndexVariable = baseStmt.Names[0];
|
||||
_coordsEnabled = true;
|
||||
|
||||
KExpr? outR = null, outG = null, outB = null;
|
||||
for (int i = 1; i < body.Count; i++)
|
||||
{
|
||||
switch (body[i])
|
||||
{
|
||||
case LocalStmt local:
|
||||
BindLocal(local);
|
||||
break;
|
||||
case AssignStmt assign:
|
||||
BindAssign(assign);
|
||||
break;
|
||||
case CallStmt { Call: MethodCallExpr set } when IsPixelDataSet(set, out int writeChannel):
|
||||
var value = ClampChannel(Lower(set.Arguments[1]));
|
||||
if (writeChannel == 0) outR = value;
|
||||
else if (writeChannel == 1) outG = value;
|
||||
else outB = value;
|
||||
_writtenChannels[writeChannel] = true;
|
||||
break;
|
||||
default:
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
if (outR is null || outG is null || outB is null)
|
||||
return null;
|
||||
|
||||
return new KernelProgram(_bindings, outR, outG, outB, new KInput(KChannel.A), [.. _uniforms]);
|
||||
}
|
||||
|
||||
private bool IsBaseIndex(LuaExpr expression)
|
||||
{
|
||||
if (expression is not BinaryExpr { Operator: "*", Right: NumberExpr { Value: 4d } } scaled ||
|
||||
scaled.Left is not BinaryExpr { Operator: "+" } sum)
|
||||
return false;
|
||||
if (!IsCoordinate(sum.Right, KAxis.X))
|
||||
return false;
|
||||
if (sum.Left is not BinaryExpr { Operator: "*" } stride)
|
||||
return false;
|
||||
return IsCoordinate(stride.Left, KAxis.Y) && IsWidth(stride.Right);
|
||||
}
|
||||
|
||||
private bool IsWidth(LuaExpr expression)
|
||||
{
|
||||
if (expression is MemberExpr { Target: NameExpr { Name: "obj" }, Name: var field } &&
|
||||
KernelUniforms.TryResolveMember("obj", field, out var uniform))
|
||||
return uniform == KernelUniform.Width;
|
||||
return _pixelDataVariable is not null &&
|
||||
expression is MemberExpr { Target: NameExpr { } target, Name: "width" } &&
|
||||
string.Equals(target.Name, _pixelDataVariable, StringComparison.Ordinal);
|
||||
}
|
||||
|
||||
private bool TryPixelDataChannel(LuaExpr expression, out int channel)
|
||||
{
|
||||
channel = 0;
|
||||
if (expression is not MethodCallExpr { Method: "get", Arguments.Count: 1 } call ||
|
||||
call.Target is not NameExpr { } handle ||
|
||||
!string.Equals(handle.Name, _pixelDataVariable, StringComparison.Ordinal))
|
||||
return false;
|
||||
if (!TryChannelOffset(call.Arguments[0], 1, 4, out channel))
|
||||
return false;
|
||||
channel--;
|
||||
return !_writtenChannels[channel];
|
||||
}
|
||||
|
||||
private bool IsPixelDataSet(MethodCallExpr call, out int channel)
|
||||
{
|
||||
channel = 0;
|
||||
if (call.Method != "set" || call.Arguments.Count != 2 ||
|
||||
call.Target is not NameExpr { } handle ||
|
||||
!string.Equals(handle.Name, _pixelDataVariable, StringComparison.Ordinal))
|
||||
return false;
|
||||
if (!TryChannelOffset(call.Arguments[0], 1, 3, out channel))
|
||||
return false;
|
||||
channel--;
|
||||
return true;
|
||||
}
|
||||
|
||||
private KExpr ClampChannel(KExpr value)
|
||||
{
|
||||
var bound = new KLocalRef(AddBinding(value));
|
||||
return new KSelect(
|
||||
new KCompare(KCompareOp.Less, bound, new KConst(0d)),
|
||||
new KConst(0d),
|
||||
new KSelect(
|
||||
new KCompare(KCompareOp.Greater, bound, new KConst(255d)),
|
||||
new KConst(255d),
|
||||
bound));
|
||||
}
|
||||
|
||||
private bool TryChannelOffset(LuaExpr expression, int min, int max, out int offset)
|
||||
{
|
||||
offset = 0;
|
||||
if (expression is not BinaryExpr { Operator: "+", Left: NameExpr baseName, Right: NumberExpr number } ||
|
||||
!string.Equals(baseName.Name, _baseIndexVariable, StringComparison.Ordinal))
|
||||
return false;
|
||||
offset = (int)number.Value;
|
||||
return offset == number.Value && offset >= min && offset <= max;
|
||||
}
|
||||
|
||||
private KernelProgram? BuildKernel(IReadOnlyList<LuaStmt> body)
|
||||
{
|
||||
if (body.Count < 2)
|
||||
return null;
|
||||
|
||||
if (body[0] is not LocalStmt sample || sample.Values.Count != 1 ||
|
||||
!IsGetPixel(sample.Values[0]))
|
||||
return null;
|
||||
if (sample.Names.Count is < 1 or > 4)
|
||||
return null;
|
||||
|
||||
_coordsEnabled = true;
|
||||
for (int i = 0; i < sample.Names.Count; i++)
|
||||
{
|
||||
EnsureNotCoordinateName(sample.Names[i]);
|
||||
_scope[sample.Names[i]] = AddBinding(new KInput((KChannel)i));
|
||||
}
|
||||
|
||||
for (int i = 1; i < body.Count - 1; i++)
|
||||
{
|
||||
switch (body[i])
|
||||
{
|
||||
case LocalStmt local:
|
||||
BindLocal(local);
|
||||
break;
|
||||
case AssignStmt assign:
|
||||
BindAssign(assign);
|
||||
break;
|
||||
default:
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
if (body[^1] is not CallStmt { Call: CallExpr call } || !IsObjectMethod(call, "setpixel"))
|
||||
return null;
|
||||
if (call.Arguments.Count is < 5 or > 6)
|
||||
return null;
|
||||
if (!IsCoordinate(call.Arguments[0], KAxis.X) || !IsCoordinate(call.Arguments[1], KAxis.Y))
|
||||
return null;
|
||||
|
||||
var outR = Lower(call.Arguments[2]);
|
||||
var outG = Lower(call.Arguments[3]);
|
||||
var outB = Lower(call.Arguments[4]);
|
||||
var outA = call.Arguments.Count == 6 ? Lower(call.Arguments[5]) : new KConst(255d);
|
||||
|
||||
return new KernelProgram(_bindings, outR, outG, outB, outA, [.. _uniforms]);
|
||||
}
|
||||
|
||||
private void BindLocal(LocalStmt local)
|
||||
{
|
||||
if (local.Values.Count == 1 && IsGetPixel(local.Values[0]))
|
||||
throw new KernelUnsupportedException("Unexpected pixel sample.");
|
||||
if (local.Names.Count != local.Values.Count)
|
||||
throw new KernelUnsupportedException("Multiple-value assignment is not supported.");
|
||||
|
||||
var lowered = new KExpr[local.Values.Count];
|
||||
for (int i = 0; i < local.Values.Count; i++)
|
||||
lowered[i] = Lower(local.Values[i]);
|
||||
for (int i = 0; i < local.Names.Count; i++)
|
||||
{
|
||||
EnsureNotCoordinateName(local.Names[i]);
|
||||
_scope[local.Names[i]] = AddBinding(lowered[i]);
|
||||
}
|
||||
}
|
||||
|
||||
private void BindAssign(AssignStmt assign)
|
||||
{
|
||||
if (assign.Targets.Count != assign.Values.Count)
|
||||
throw new KernelUnsupportedException("Unbalanced assignment is not supported.");
|
||||
|
||||
foreach (var target in assign.Targets)
|
||||
{
|
||||
if (target is not NameExpr name || !_scope.ContainsKey(name.Name))
|
||||
throw new KernelUnsupportedException("Assignment target must be a local variable.");
|
||||
}
|
||||
|
||||
var lowered = new KExpr[assign.Values.Count];
|
||||
for (int i = 0; i < assign.Values.Count; i++)
|
||||
lowered[i] = Lower(assign.Values[i]);
|
||||
for (int i = 0; i < assign.Targets.Count; i++)
|
||||
_scope[((NameExpr)assign.Targets[i]).Name] = AddBinding(lowered[i]);
|
||||
}
|
||||
|
||||
private void EnsureNotCoordinateName(string name)
|
||||
{
|
||||
if (string.Equals(name, _widthVariable, StringComparison.Ordinal) ||
|
||||
string.Equals(name, _heightVariable, StringComparison.Ordinal))
|
||||
throw new KernelUnsupportedException("Local variable shadows a loop coordinate.");
|
||||
if (_pixelDataVariable is not null && string.Equals(name, _pixelDataVariable, StringComparison.Ordinal))
|
||||
throw new KernelUnsupportedException("Local variable shadows the pixel-data handle.");
|
||||
if (_baseIndexVariable.Length > 0 && string.Equals(name, _baseIndexVariable, StringComparison.Ordinal))
|
||||
throw new KernelUnsupportedException("Local variable shadows the base index.");
|
||||
}
|
||||
|
||||
private int AddBinding(KExpr expression)
|
||||
{
|
||||
_bindings.Add(expression);
|
||||
return _bindings.Count - 1;
|
||||
}
|
||||
|
||||
private KExpr Lower(LuaExpr expression)
|
||||
{
|
||||
switch (expression)
|
||||
{
|
||||
case NumberExpr number:
|
||||
return new KConst(number.Value);
|
||||
case NameExpr name:
|
||||
return LowerName(name.Name);
|
||||
case MemberExpr member:
|
||||
return LowerMember(member);
|
||||
case CallExpr call:
|
||||
return LowerCall(call);
|
||||
case MethodCallExpr method when TryPixelDataChannel(method, out int channel):
|
||||
return new KInput((KChannel)channel);
|
||||
case UnaryExpr { Operator: "-" } unary:
|
||||
return new KNegate(Lower(unary.Operand));
|
||||
case BinaryExpr binary:
|
||||
return LowerBinary(binary);
|
||||
}
|
||||
throw new KernelUnsupportedException("Unsupported expression in pixel kernel.");
|
||||
}
|
||||
|
||||
private KExpr LowerName(string name)
|
||||
{
|
||||
if (_scope.TryGetValue(name, out int slot))
|
||||
return new KLocalRef(slot);
|
||||
if (_coordsEnabled && string.Equals(name, _widthVariable, StringComparison.Ordinal))
|
||||
return new KCoord(KAxis.X);
|
||||
if (_coordsEnabled && string.Equals(name, _heightVariable, StringComparison.Ordinal))
|
||||
return new KCoord(KAxis.Y);
|
||||
if (KernelUniforms.TryResolveGlobal(name, out var uniform))
|
||||
return UseUniform(uniform);
|
||||
throw new KernelUnsupportedException($"Unknown identifier '{name}'.");
|
||||
}
|
||||
|
||||
private KExpr LowerMember(MemberExpr member)
|
||||
{
|
||||
if (member.Target is NameExpr { Name: "math" })
|
||||
{
|
||||
return member.Name switch
|
||||
{
|
||||
"pi" => new KConst(Math.PI),
|
||||
"huge" => new KConst(double.PositiveInfinity),
|
||||
_ => throw new KernelUnsupportedException($"Unsupported math field '{member.Name}'."),
|
||||
};
|
||||
}
|
||||
|
||||
if (member.Target is NameExpr target && KernelUniforms.TryResolveMember(target.Name, member.Name, out var uniform))
|
||||
return UseUniform(uniform);
|
||||
|
||||
throw new KernelUnsupportedException("Unsupported member access in pixel kernel.");
|
||||
}
|
||||
|
||||
private KExpr LowerCall(CallExpr call)
|
||||
{
|
||||
if (call.Target is not MemberExpr { Target: NameExpr { Name: "math" }, Name: var function } ||
|
||||
!MathFunctions.TryGetValue(function, out var spec))
|
||||
throw new KernelUnsupportedException("Unsupported function call in pixel kernel.");
|
||||
|
||||
int count = call.Arguments.Count;
|
||||
if (count < spec.MinArgs || count > spec.MaxArgs)
|
||||
throw new KernelUnsupportedException($"Wrong argument count for 'math.{function}'.");
|
||||
|
||||
var arguments = new KExpr[count];
|
||||
for (int i = 0; i < count; i++)
|
||||
arguments[i] = Lower(call.Arguments[i]);
|
||||
|
||||
if (spec.Func is KFunc.Min or KFunc.Max)
|
||||
{
|
||||
var folded = arguments[0];
|
||||
for (int i = 1; i < count; i++)
|
||||
folded = new KCall(spec.Func, [folded, arguments[i]]);
|
||||
return folded;
|
||||
}
|
||||
|
||||
return new KCall(spec.Func, arguments);
|
||||
}
|
||||
|
||||
private KExpr LowerBinary(BinaryExpr binary)
|
||||
{
|
||||
switch (binary.Operator)
|
||||
{
|
||||
case "+": return new KArith(KArithOp.Add, Lower(binary.Left), Lower(binary.Right));
|
||||
case "-": return new KArith(KArithOp.Subtract, Lower(binary.Left), Lower(binary.Right));
|
||||
case "*": return new KArith(KArithOp.Multiply, Lower(binary.Left), Lower(binary.Right));
|
||||
case "/": return new KArith(KArithOp.Divide, Lower(binary.Left), Lower(binary.Right));
|
||||
case "%": return new KArith(KArithOp.Modulo, Lower(binary.Left), Lower(binary.Right));
|
||||
case "^": return new KArith(KArithOp.Power, Lower(binary.Left), Lower(binary.Right));
|
||||
case "or" when binary.Left is BinaryExpr { Operator: "and" } conditional:
|
||||
return new KSelect(LowerBool(conditional.Left), Lower(conditional.Right), Lower(binary.Right));
|
||||
}
|
||||
throw new KernelUnsupportedException($"Unsupported operator '{binary.Operator}' in value position.");
|
||||
}
|
||||
|
||||
private KBool LowerBool(LuaExpr expression)
|
||||
{
|
||||
switch (expression)
|
||||
{
|
||||
case BoolExpr boolean:
|
||||
return new KBoolConst(boolean.Value);
|
||||
case UnaryExpr { Operator: "not" } unary:
|
||||
return new KNot(LowerBool(unary.Operand));
|
||||
case BinaryExpr { Operator: "and" } conjunction:
|
||||
return new KLogical(true, LowerBool(conjunction.Left), LowerBool(conjunction.Right));
|
||||
case BinaryExpr { Operator: "or" } disjunction:
|
||||
return new KLogical(false, LowerBool(disjunction.Left), LowerBool(disjunction.Right));
|
||||
case BinaryExpr binary when TryCompareOp(binary.Operator, out var op):
|
||||
return new KCompare(op, Lower(binary.Left), Lower(binary.Right));
|
||||
case NameExpr name when IsCheck(LowerName(name.Name)):
|
||||
return new KCompare(KCompareOp.NotEqual, LowerName(name.Name), new KConst(0d));
|
||||
case MemberExpr member when IsCheck(LowerMember(member)):
|
||||
return new KCompare(KCompareOp.NotEqual, LowerMember(member), new KConst(0d));
|
||||
}
|
||||
throw new KernelUnsupportedException("Unsupported condition in pixel kernel.");
|
||||
}
|
||||
|
||||
private static bool IsCheck(KExpr expression) =>
|
||||
expression is KUniformRef { Uniform: KernelUniform.Check0 or KernelUniform.Check1 or KernelUniform.Check2 or KernelUniform.Check3 };
|
||||
|
||||
private static bool TryCompareOp(string symbol, out KCompareOp op)
|
||||
{
|
||||
switch (symbol)
|
||||
{
|
||||
case "<": op = KCompareOp.Less; return true;
|
||||
case ">": op = KCompareOp.Greater; return true;
|
||||
case "<=": op = KCompareOp.LessEqual; return true;
|
||||
case ">=": op = KCompareOp.GreaterEqual; return true;
|
||||
case "==": op = KCompareOp.Equal; return true;
|
||||
case "~=": op = KCompareOp.NotEqual; return true;
|
||||
default: op = default; return false;
|
||||
}
|
||||
}
|
||||
|
||||
private KExpr UseUniform(KernelUniform uniform)
|
||||
{
|
||||
_uniforms.Add(uniform);
|
||||
return new KUniformRef(uniform);
|
||||
}
|
||||
|
||||
private bool TryAxis(NumericForStmt loop, out string variable, out KAxis axis)
|
||||
{
|
||||
variable = loop.Variable;
|
||||
axis = default;
|
||||
|
||||
if (loop.Start is not NumberExpr { Value: 0d })
|
||||
return false;
|
||||
if (loop.Step is not null && loop.Step is not NumberExpr { Value: 1d })
|
||||
return false;
|
||||
if (loop.Stop is not BinaryExpr { Operator: "-", Right: NumberExpr { Value: 1d } } bound)
|
||||
return false;
|
||||
if (bound.Left is MemberExpr { Target: NameExpr { Name: "obj" }, Name: var field } &&
|
||||
KernelUniforms.TryResolveMember("obj", field, out var uniform))
|
||||
{
|
||||
if (uniform == KernelUniform.Width)
|
||||
{
|
||||
axis = KAxis.X;
|
||||
return true;
|
||||
}
|
||||
if (uniform == KernelUniform.Height)
|
||||
{
|
||||
axis = KAxis.Y;
|
||||
return true;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
if (_pixelDataVariable is not null &&
|
||||
bound.Left is MemberExpr { Target: NameExpr { } handle, Name: var pixelField } &&
|
||||
string.Equals(handle.Name, _pixelDataVariable, StringComparison.Ordinal))
|
||||
{
|
||||
if (pixelField == "width")
|
||||
{
|
||||
axis = KAxis.X;
|
||||
return true;
|
||||
}
|
||||
if (pixelField == "height")
|
||||
{
|
||||
axis = KAxis.Y;
|
||||
return true;
|
||||
}
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
private bool IsGetPixel(LuaExpr expression) =>
|
||||
expression is CallExpr call && IsObjectMethod(call, "getpixel") &&
|
||||
call.Arguments.Count == 2 &&
|
||||
IsCoordinate(call.Arguments[0], KAxis.X) && IsCoordinate(call.Arguments[1], KAxis.Y);
|
||||
|
||||
private bool IsCoordinate(LuaExpr expression, KAxis axis) =>
|
||||
expression is NameExpr name &&
|
||||
string.Equals(name.Name, axis == KAxis.X ? _widthVariable : _heightVariable, StringComparison.Ordinal);
|
||||
|
||||
private static bool IsObjectMethod(CallExpr call, string method) =>
|
||||
call.Target is MemberExpr { Target: NameExpr { Name: "obj" }, Name: var name } &&
|
||||
string.Equals(name, method, StringComparison.Ordinal);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,97 @@
|
||||
using System.Collections.Generic;
|
||||
|
||||
namespace LuaScript.Engine.Kernel
|
||||
{
|
||||
internal enum KChannel
|
||||
{
|
||||
R,
|
||||
G,
|
||||
B,
|
||||
A,
|
||||
}
|
||||
|
||||
internal enum KAxis
|
||||
{
|
||||
X,
|
||||
Y,
|
||||
}
|
||||
|
||||
internal enum KArithOp
|
||||
{
|
||||
Add,
|
||||
Subtract,
|
||||
Multiply,
|
||||
Divide,
|
||||
Modulo,
|
||||
Power,
|
||||
}
|
||||
|
||||
internal enum KCompareOp
|
||||
{
|
||||
Less,
|
||||
Greater,
|
||||
LessEqual,
|
||||
GreaterEqual,
|
||||
Equal,
|
||||
NotEqual,
|
||||
}
|
||||
|
||||
internal enum KFunc
|
||||
{
|
||||
Abs,
|
||||
Floor,
|
||||
Ceil,
|
||||
Sqrt,
|
||||
Sin,
|
||||
Cos,
|
||||
Tan,
|
||||
Asin,
|
||||
Acos,
|
||||
Atan,
|
||||
Atan2,
|
||||
Exp,
|
||||
Log,
|
||||
Pow,
|
||||
Min,
|
||||
Max,
|
||||
Fmod,
|
||||
}
|
||||
|
||||
internal abstract record KExpr;
|
||||
|
||||
internal sealed record KConst(double Value) : KExpr;
|
||||
|
||||
internal sealed record KInput(KChannel Channel) : KExpr;
|
||||
|
||||
internal sealed record KCoord(KAxis Axis) : KExpr;
|
||||
|
||||
internal sealed record KUniformRef(KernelUniform Uniform) : KExpr;
|
||||
|
||||
internal sealed record KLocalRef(int Slot) : KExpr;
|
||||
|
||||
internal sealed record KArith(KArithOp Op, KExpr Left, KExpr Right) : KExpr;
|
||||
|
||||
internal sealed record KNegate(KExpr Operand) : KExpr;
|
||||
|
||||
internal sealed record KCall(KFunc Func, IReadOnlyList<KExpr> Arguments) : KExpr;
|
||||
|
||||
internal sealed record KSelect(KBool Condition, KExpr WhenTrue, KExpr WhenFalse) : KExpr;
|
||||
|
||||
internal abstract record KBool;
|
||||
|
||||
internal sealed record KCompare(KCompareOp Op, KExpr Left, KExpr Right) : KBool;
|
||||
|
||||
internal sealed record KLogical(bool IsAnd, KBool Left, KBool Right) : KBool;
|
||||
|
||||
internal sealed record KNot(KBool Operand) : KBool;
|
||||
|
||||
internal sealed record KBoolConst(bool Value) : KBool;
|
||||
|
||||
internal sealed record KernelProgram(
|
||||
IReadOnlyList<KExpr> Bindings,
|
||||
KExpr OutputR,
|
||||
KExpr OutputG,
|
||||
KExpr OutputB,
|
||||
KExpr OutputA,
|
||||
IReadOnlyList<KernelUniform> Uniforms);
|
||||
}
|
||||
@@ -0,0 +1,155 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
|
||||
namespace LuaScript.Engine.Kernel
|
||||
{
|
||||
internal enum KernelUniform
|
||||
{
|
||||
Width,
|
||||
Height,
|
||||
HalfWidth,
|
||||
HalfHeight,
|
||||
CenterX,
|
||||
CenterY,
|
||||
CenterZ,
|
||||
Diagonal,
|
||||
X,
|
||||
Y,
|
||||
Z,
|
||||
Ox,
|
||||
Oy,
|
||||
Oz,
|
||||
Sx,
|
||||
Sy,
|
||||
Sz,
|
||||
Zoom,
|
||||
Aspect,
|
||||
Alpha,
|
||||
Rx,
|
||||
Ry,
|
||||
Rz,
|
||||
Rxr,
|
||||
Ryr,
|
||||
Rzr,
|
||||
Track0,
|
||||
Track1,
|
||||
Track2,
|
||||
Track3,
|
||||
Slider0,
|
||||
Slider1,
|
||||
Slider2,
|
||||
Slider3,
|
||||
Check0,
|
||||
Check1,
|
||||
Check2,
|
||||
Check3,
|
||||
Color,
|
||||
Time,
|
||||
Frame,
|
||||
TotalFrame,
|
||||
TotalTime,
|
||||
T,
|
||||
Framerate,
|
||||
Layer,
|
||||
Index,
|
||||
Num,
|
||||
SceneWidth,
|
||||
SceneHeight,
|
||||
SceneCenterX,
|
||||
SceneCenterY,
|
||||
TimelineFrame,
|
||||
TimelineTime,
|
||||
}
|
||||
|
||||
internal static class KernelUniforms
|
||||
{
|
||||
public static int Count { get; } = Enum.GetValues<KernelUniform>().Length;
|
||||
|
||||
private static readonly Dictionary<string, KernelUniform> Globals = new(StringComparer.Ordinal)
|
||||
{
|
||||
["time"] = KernelUniform.Time,
|
||||
["frame"] = KernelUniform.Frame,
|
||||
["totalframe"] = KernelUniform.TotalFrame,
|
||||
["framerate"] = KernelUniform.Framerate,
|
||||
["timelineframe"] = KernelUniform.TimelineFrame,
|
||||
["timelinetime"] = KernelUniform.TimelineTime,
|
||||
["layer"] = KernelUniform.Layer,
|
||||
["color"] = KernelUniform.Color,
|
||||
};
|
||||
|
||||
private static readonly Dictionary<string, KernelUniform> ObjectFields = new(StringComparer.Ordinal)
|
||||
{
|
||||
["w"] = KernelUniform.Width,
|
||||
["h"] = KernelUniform.Height,
|
||||
["hw"] = KernelUniform.HalfWidth,
|
||||
["hh"] = KernelUniform.HalfHeight,
|
||||
["cx"] = KernelUniform.CenterX,
|
||||
["cy"] = KernelUniform.CenterY,
|
||||
["cz"] = KernelUniform.CenterZ,
|
||||
["diagonal"] = KernelUniform.Diagonal,
|
||||
["x"] = KernelUniform.X,
|
||||
["y"] = KernelUniform.Y,
|
||||
["z"] = KernelUniform.Z,
|
||||
["ox"] = KernelUniform.Ox,
|
||||
["oy"] = KernelUniform.Oy,
|
||||
["oz"] = KernelUniform.Oz,
|
||||
["sx"] = KernelUniform.Sx,
|
||||
["sy"] = KernelUniform.Sy,
|
||||
["sz"] = KernelUniform.Sz,
|
||||
["zoom"] = KernelUniform.Zoom,
|
||||
["aspect"] = KernelUniform.Aspect,
|
||||
["alpha"] = KernelUniform.Alpha,
|
||||
["rx"] = KernelUniform.Rx,
|
||||
["ry"] = KernelUniform.Ry,
|
||||
["rz"] = KernelUniform.Rz,
|
||||
["rxr"] = KernelUniform.Rxr,
|
||||
["ryr"] = KernelUniform.Ryr,
|
||||
["rzr"] = KernelUniform.Rzr,
|
||||
["track0"] = KernelUniform.Track0,
|
||||
["track1"] = KernelUniform.Track1,
|
||||
["track2"] = KernelUniform.Track2,
|
||||
["track3"] = KernelUniform.Track3,
|
||||
["slider0"] = KernelUniform.Slider0,
|
||||
["slider1"] = KernelUniform.Slider1,
|
||||
["slider2"] = KernelUniform.Slider2,
|
||||
["slider3"] = KernelUniform.Slider3,
|
||||
["check0"] = KernelUniform.Check0,
|
||||
["check1"] = KernelUniform.Check1,
|
||||
["check2"] = KernelUniform.Check2,
|
||||
["check3"] = KernelUniform.Check3,
|
||||
["time"] = KernelUniform.Time,
|
||||
["frame"] = KernelUniform.Frame,
|
||||
["totalframe"] = KernelUniform.TotalFrame,
|
||||
["totaltime"] = KernelUniform.TotalTime,
|
||||
["t"] = KernelUniform.T,
|
||||
["framerate"] = KernelUniform.Framerate,
|
||||
["layer"] = KernelUniform.Layer,
|
||||
["index"] = KernelUniform.Index,
|
||||
["num"] = KernelUniform.Num,
|
||||
};
|
||||
|
||||
private static readonly Dictionary<string, KernelUniform> SceneFields = new(StringComparer.Ordinal)
|
||||
{
|
||||
["width"] = KernelUniform.SceneWidth,
|
||||
["height"] = KernelUniform.SceneHeight,
|
||||
["cx"] = KernelUniform.SceneCenterX,
|
||||
["cy"] = KernelUniform.SceneCenterY,
|
||||
};
|
||||
|
||||
public static bool TryResolveGlobal(string name, out KernelUniform uniform) =>
|
||||
Globals.TryGetValue(name, out uniform);
|
||||
|
||||
public static bool TryResolveMember(string target, string field, out KernelUniform uniform)
|
||||
{
|
||||
uniform = default;
|
||||
return target switch
|
||||
{
|
||||
"obj" => ObjectFields.TryGetValue(field, out uniform),
|
||||
"scene" => SceneFields.TryGetValue(field, out uniform),
|
||||
_ => false,
|
||||
};
|
||||
}
|
||||
|
||||
public static string Field(KernelUniform uniform) => "u_" + uniform;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,76 @@
|
||||
using System;
|
||||
|
||||
namespace LuaScript.Engine.Kernel
|
||||
{
|
||||
internal static class KernelUniformBinding
|
||||
{
|
||||
public static double[] Create() => new double[KernelUniforms.Count];
|
||||
|
||||
public static void Fill(AviUtlScriptContext ctx, double[] values)
|
||||
{
|
||||
values[(int)KernelUniform.Width] = ctx.ImageWidth;
|
||||
values[(int)KernelUniform.Height] = ctx.ImageHeight;
|
||||
values[(int)KernelUniform.HalfWidth] = ctx.ImageWidth / 2d;
|
||||
values[(int)KernelUniform.HalfHeight] = ctx.ImageHeight / 2d;
|
||||
values[(int)KernelUniform.CenterX] = ctx.ImageWidth / 2d;
|
||||
values[(int)KernelUniform.CenterY] = ctx.ImageHeight / 2d;
|
||||
values[(int)KernelUniform.CenterZ] = 0d;
|
||||
values[(int)KernelUniform.Diagonal] = Math.Sqrt((double)ctx.ImageWidth * ctx.ImageWidth + (double)ctx.ImageHeight * ctx.ImageHeight);
|
||||
values[(int)KernelUniform.X] = ctx.X;
|
||||
values[(int)KernelUniform.Y] = ctx.Y;
|
||||
values[(int)KernelUniform.Z] = ctx.Z;
|
||||
values[(int)KernelUniform.Ox] = ctx.Ox;
|
||||
values[(int)KernelUniform.Oy] = ctx.Oy;
|
||||
values[(int)KernelUniform.Oz] = ctx.Oz;
|
||||
values[(int)KernelUniform.Sx] = ctx.Sx;
|
||||
values[(int)KernelUniform.Sy] = ctx.Sy;
|
||||
values[(int)KernelUniform.Sz] = 1d;
|
||||
values[(int)KernelUniform.Zoom] = ctx.Zoom;
|
||||
values[(int)KernelUniform.Aspect] = ctx.Aspect;
|
||||
values[(int)KernelUniform.Alpha] = ctx.Alpha;
|
||||
values[(int)KernelUniform.Rx] = ctx.Rx;
|
||||
values[(int)KernelUniform.Ry] = ctx.Ry;
|
||||
values[(int)KernelUniform.Rz] = ctx.Rz;
|
||||
values[(int)KernelUniform.Rxr] = ctx.RxRad;
|
||||
values[(int)KernelUniform.Ryr] = ctx.RyRad;
|
||||
values[(int)KernelUniform.Rzr] = ctx.RzRad;
|
||||
values[(int)KernelUniform.Track0] = ctx.Track0;
|
||||
values[(int)KernelUniform.Track1] = ctx.Track1;
|
||||
values[(int)KernelUniform.Track2] = ctx.Track2;
|
||||
values[(int)KernelUniform.Track3] = ctx.Track3;
|
||||
values[(int)KernelUniform.Slider0] = ctx.Slider0;
|
||||
values[(int)KernelUniform.Slider1] = ctx.Slider1;
|
||||
values[(int)KernelUniform.Slider2] = ctx.Slider2;
|
||||
values[(int)KernelUniform.Slider3] = ctx.Slider3;
|
||||
values[(int)KernelUniform.Check0] = ctx.Check0 ? 1d : 0d;
|
||||
values[(int)KernelUniform.Check1] = ctx.Check1 ? 1d : 0d;
|
||||
values[(int)KernelUniform.Check2] = ctx.Check2 ? 1d : 0d;
|
||||
values[(int)KernelUniform.Check3] = ctx.Check3 ? 1d : 0d;
|
||||
values[(int)KernelUniform.Color] = ctx.HasColor ? ctx.ColorValue : -1d;
|
||||
values[(int)KernelUniform.Time] = ctx.Time;
|
||||
values[(int)KernelUniform.Frame] = ctx.Frame;
|
||||
values[(int)KernelUniform.TotalFrame] = ctx.TotalFrame;
|
||||
values[(int)KernelUniform.TotalTime] = ctx.TotalTime;
|
||||
values[(int)KernelUniform.T] = ctx.TotalFrame > 0 ? ctx.Frame / (double)ctx.TotalFrame : 0d;
|
||||
values[(int)KernelUniform.Framerate] = ctx.Framerate;
|
||||
values[(int)KernelUniform.Layer] = ctx.Layer;
|
||||
values[(int)KernelUniform.Index] = ctx.Index;
|
||||
values[(int)KernelUniform.Num] = ctx.Num;
|
||||
values[(int)KernelUniform.SceneWidth] = ctx.SceneWidth;
|
||||
values[(int)KernelUniform.SceneHeight] = ctx.SceneHeight;
|
||||
values[(int)KernelUniform.SceneCenterX] = ctx.SceneWidth / 2d;
|
||||
values[(int)KernelUniform.SceneCenterY] = ctx.SceneHeight / 2d;
|
||||
values[(int)KernelUniform.TimelineFrame] = ctx.TimelineFrame;
|
||||
values[(int)KernelUniform.TimelineTime] = ctx.TimelineTime;
|
||||
}
|
||||
|
||||
public static void Pack(double[] values, float[] packed)
|
||||
{
|
||||
int count = Math.Min(values.Length, packed.Length);
|
||||
for (int i = 0; i < count; i++)
|
||||
packed[i] = (float)values[i];
|
||||
for (int i = count; i < packed.Length; i++)
|
||||
packed[i] = 0f;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,4 @@
|
||||
namespace LuaScript.Engine.Kernel
|
||||
{
|
||||
internal sealed class KernelUnsupportedException(string reason) : Exception(reason);
|
||||
}
|
||||
@@ -0,0 +1,47 @@
|
||||
using System.Collections.Generic;
|
||||
|
||||
namespace LuaScript.Engine.Kernel
|
||||
{
|
||||
internal abstract record LuaExpr;
|
||||
|
||||
internal sealed record NumberExpr(double Value) : LuaExpr;
|
||||
|
||||
internal sealed record BoolExpr(bool Value) : LuaExpr;
|
||||
|
||||
internal sealed record NilExpr : LuaExpr;
|
||||
|
||||
internal sealed record StringExpr(string Value) : LuaExpr;
|
||||
|
||||
internal sealed record NameExpr(string Name) : LuaExpr;
|
||||
|
||||
internal sealed record MemberExpr(LuaExpr Target, string Name) : LuaExpr;
|
||||
|
||||
internal sealed record IndexExpr(LuaExpr Target, LuaExpr Key) : LuaExpr;
|
||||
|
||||
internal sealed record CallExpr(LuaExpr Target, IReadOnlyList<LuaExpr> Arguments) : LuaExpr;
|
||||
|
||||
internal sealed record MethodCallExpr(LuaExpr Target, string Method, IReadOnlyList<LuaExpr> Arguments) : LuaExpr;
|
||||
|
||||
internal sealed record UnaryExpr(string Operator, LuaExpr Operand) : LuaExpr;
|
||||
|
||||
internal sealed record BinaryExpr(string Operator, LuaExpr Left, LuaExpr Right) : LuaExpr;
|
||||
|
||||
internal abstract record LuaStmt;
|
||||
|
||||
internal sealed record LocalStmt(IReadOnlyList<string> Names, IReadOnlyList<LuaExpr> Values) : LuaStmt;
|
||||
|
||||
internal sealed record AssignStmt(IReadOnlyList<LuaExpr> Targets, IReadOnlyList<LuaExpr> Values) : LuaStmt;
|
||||
|
||||
internal sealed record CallStmt(LuaExpr Call) : LuaStmt;
|
||||
|
||||
internal sealed record IfClause(LuaExpr Condition, IReadOnlyList<LuaStmt> Body);
|
||||
|
||||
internal sealed record IfStmt(IReadOnlyList<IfClause> Clauses, IReadOnlyList<LuaStmt>? ElseBody) : LuaStmt;
|
||||
|
||||
internal sealed record NumericForStmt(
|
||||
string Variable,
|
||||
LuaExpr Start,
|
||||
LuaExpr Stop,
|
||||
LuaExpr? Step,
|
||||
IReadOnlyList<LuaStmt> Body) : LuaStmt;
|
||||
}
|
||||
@@ -0,0 +1,310 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Globalization;
|
||||
|
||||
namespace LuaScript.Engine.Kernel
|
||||
{
|
||||
internal static class LuaLexer
|
||||
{
|
||||
private static readonly HashSet<string> Keywords = new(StringComparer.Ordinal)
|
||||
{
|
||||
"and", "break", "do", "else", "elseif", "end", "false", "for", "function",
|
||||
"if", "in", "local", "nil", "not", "or", "repeat", "return", "then",
|
||||
"true", "until", "while",
|
||||
};
|
||||
|
||||
public static List<LuaToken> Tokenize(string source)
|
||||
{
|
||||
var tokens = new List<LuaToken>();
|
||||
int i = 0;
|
||||
int length = source.Length;
|
||||
|
||||
while (i < length)
|
||||
{
|
||||
char c = source[i];
|
||||
|
||||
if (c is ' ' or '\t' or '\r' or '\n' or '\f' or '\v')
|
||||
{
|
||||
i++;
|
||||
continue;
|
||||
}
|
||||
|
||||
if (c == '-' && i + 1 < length && source[i + 1] == '-')
|
||||
{
|
||||
i = SkipComment(source, i + 2);
|
||||
continue;
|
||||
}
|
||||
|
||||
if (c == '"' || c == '\'')
|
||||
{
|
||||
i = ReadShortString(source, i, tokens);
|
||||
continue;
|
||||
}
|
||||
|
||||
if (c == '[' && i + 1 < length && (source[i + 1] == '[' || source[i + 1] == '='))
|
||||
{
|
||||
int level = LongBracketLevel(source, i);
|
||||
if (level >= 0)
|
||||
{
|
||||
i = ReadLongString(source, i, level, tokens);
|
||||
continue;
|
||||
}
|
||||
}
|
||||
|
||||
if (char.IsDigit(c) || (c == '.' && i + 1 < length && char.IsDigit(source[i + 1])))
|
||||
{
|
||||
i = ReadNumber(source, i, tokens);
|
||||
continue;
|
||||
}
|
||||
|
||||
if (IsNameStart(c))
|
||||
{
|
||||
i = ReadName(source, i, tokens);
|
||||
continue;
|
||||
}
|
||||
|
||||
i = ReadSymbol(source, i, tokens);
|
||||
}
|
||||
|
||||
tokens.Add(new LuaToken(LuaTokenKind.Eof, string.Empty, 0d));
|
||||
return tokens;
|
||||
}
|
||||
|
||||
private static int SkipComment(string source, int i)
|
||||
{
|
||||
int level = LongBracketLevel(source, i);
|
||||
if (level >= 0)
|
||||
return SkipLongBracket(source, i, level);
|
||||
|
||||
int length = source.Length;
|
||||
while (i < length && source[i] != '\n')
|
||||
i++;
|
||||
return i;
|
||||
}
|
||||
|
||||
private static int LongBracketLevel(string source, int i)
|
||||
{
|
||||
if (i >= source.Length || source[i] != '[')
|
||||
return -1;
|
||||
int j = i + 1;
|
||||
int level = 0;
|
||||
while (j < source.Length && source[j] == '=')
|
||||
{
|
||||
level++;
|
||||
j++;
|
||||
}
|
||||
return j < source.Length && source[j] == '[' ? level : -1;
|
||||
}
|
||||
|
||||
private static int SkipLongBracket(string source, int i, int level)
|
||||
{
|
||||
int length = source.Length;
|
||||
i += level + 2;
|
||||
while (i < length)
|
||||
{
|
||||
if (source[i] == ']')
|
||||
{
|
||||
int j = i + 1;
|
||||
int count = 0;
|
||||
while (j < length && source[j] == '=')
|
||||
{
|
||||
count++;
|
||||
j++;
|
||||
}
|
||||
if (count == level && j < length && source[j] == ']')
|
||||
return j + 1;
|
||||
}
|
||||
i++;
|
||||
}
|
||||
throw new KernelUnsupportedException("Unterminated long bracket.");
|
||||
}
|
||||
|
||||
private static int ReadLongString(string source, int start, int level, List<LuaToken> tokens)
|
||||
{
|
||||
int end = SkipLongBracket(source, start, level);
|
||||
int contentStart = start + level + 2;
|
||||
int contentEnd = end - level - 2;
|
||||
string text = source.Substring(contentStart, Math.Max(0, contentEnd - contentStart));
|
||||
tokens.Add(new LuaToken(LuaTokenKind.String, text, 0d));
|
||||
return end;
|
||||
}
|
||||
|
||||
private static int ReadShortString(string source, int start, List<LuaToken> tokens)
|
||||
{
|
||||
char quote = source[start];
|
||||
int i = start + 1;
|
||||
int length = source.Length;
|
||||
var value = new System.Text.StringBuilder();
|
||||
|
||||
while (i < length)
|
||||
{
|
||||
char c = source[i];
|
||||
if (c == quote)
|
||||
{
|
||||
tokens.Add(new LuaToken(LuaTokenKind.String, value.ToString(), 0d));
|
||||
return i + 1;
|
||||
}
|
||||
if (c == '\n')
|
||||
throw new KernelUnsupportedException("Unterminated string.");
|
||||
if (c == '\\')
|
||||
{
|
||||
i = ReadEscape(source, i + 1, value);
|
||||
continue;
|
||||
}
|
||||
value.Append(c);
|
||||
i++;
|
||||
}
|
||||
throw new KernelUnsupportedException("Unterminated string.");
|
||||
}
|
||||
|
||||
private static int ReadEscape(string source, int i, System.Text.StringBuilder value)
|
||||
{
|
||||
if (i >= source.Length)
|
||||
throw new KernelUnsupportedException("Unterminated string escape.");
|
||||
|
||||
char c = source[i];
|
||||
switch (c)
|
||||
{
|
||||
case 'n': value.Append('\n'); return i + 1;
|
||||
case 't': value.Append('\t'); return i + 1;
|
||||
case 'r': value.Append('\r'); return i + 1;
|
||||
case 'a': value.Append('\a'); return i + 1;
|
||||
case 'b': value.Append('\b'); return i + 1;
|
||||
case 'f': value.Append('\f'); return i + 1;
|
||||
case 'v': value.Append('\v'); return i + 1;
|
||||
case '\\': value.Append('\\'); return i + 1;
|
||||
case '"': value.Append('"'); return i + 1;
|
||||
case '\'': value.Append('\''); return i + 1;
|
||||
case '\n': value.Append('\n'); return i + 1;
|
||||
default:
|
||||
if (char.IsDigit(c))
|
||||
{
|
||||
int n = 0;
|
||||
int count = 0;
|
||||
while (i < source.Length && count < 3 && char.IsDigit(source[i]))
|
||||
{
|
||||
n = n * 10 + (source[i] - '0');
|
||||
i++;
|
||||
count++;
|
||||
}
|
||||
value.Append((char)n);
|
||||
return i;
|
||||
}
|
||||
value.Append(c);
|
||||
return i + 1;
|
||||
}
|
||||
}
|
||||
|
||||
private static int ReadNumber(string source, int start, List<LuaToken> tokens)
|
||||
{
|
||||
int length = source.Length;
|
||||
int i = start;
|
||||
|
||||
if (source[i] == '0' && i + 1 < length && (source[i + 1] == 'x' || source[i + 1] == 'X'))
|
||||
{
|
||||
i += 2;
|
||||
int digitsStart = i;
|
||||
while (i < length && Uri.IsHexDigit(source[i]))
|
||||
i++;
|
||||
if (i == digitsStart)
|
||||
throw new KernelUnsupportedException("Malformed hexadecimal literal.");
|
||||
string hex = source.Substring(digitsStart, i - digitsStart);
|
||||
double hexValue = (double)ulong.Parse(hex, NumberStyles.HexNumber, CultureInfo.InvariantCulture);
|
||||
tokens.Add(new LuaToken(LuaTokenKind.Number, source.Substring(start, i - start), hexValue));
|
||||
return i;
|
||||
}
|
||||
|
||||
while (i < length && char.IsDigit(source[i]))
|
||||
i++;
|
||||
if (i < length && source[i] == '.')
|
||||
{
|
||||
i++;
|
||||
while (i < length && char.IsDigit(source[i]))
|
||||
i++;
|
||||
}
|
||||
if (i < length && (source[i] == 'e' || source[i] == 'E'))
|
||||
{
|
||||
i++;
|
||||
if (i < length && (source[i] == '+' || source[i] == '-'))
|
||||
i++;
|
||||
while (i < length && char.IsDigit(source[i]))
|
||||
i++;
|
||||
}
|
||||
|
||||
string text = source.Substring(start, i - start);
|
||||
double value = double.Parse(text, NumberStyles.Float, CultureInfo.InvariantCulture);
|
||||
tokens.Add(new LuaToken(LuaTokenKind.Number, text, value));
|
||||
return i;
|
||||
}
|
||||
|
||||
private static int ReadName(string source, int start, List<LuaToken> tokens)
|
||||
{
|
||||
int i = start;
|
||||
int length = source.Length;
|
||||
while (i < length && IsNamePart(source[i]))
|
||||
i++;
|
||||
string text = source.Substring(start, i - start);
|
||||
tokens.Add(new LuaToken(Keywords.Contains(text) ? LuaTokenKind.Keyword : LuaTokenKind.Name, text, 0d));
|
||||
return i;
|
||||
}
|
||||
|
||||
private static int ReadSymbol(string source, int start, List<LuaToken> tokens)
|
||||
{
|
||||
int length = source.Length;
|
||||
char c = source[start];
|
||||
|
||||
if (c == '.' && start + 2 < length && source[start + 1] == '.' && source[start + 2] == '.')
|
||||
{
|
||||
tokens.Add(new LuaToken(LuaTokenKind.Symbol, "...", 0d));
|
||||
return start + 3;
|
||||
}
|
||||
|
||||
if (start + 1 < length)
|
||||
{
|
||||
string two = source.Substring(start, 2);
|
||||
switch (two)
|
||||
{
|
||||
case "==":
|
||||
case "~=":
|
||||
case "<=":
|
||||
case ">=":
|
||||
case "..":
|
||||
tokens.Add(new LuaToken(LuaTokenKind.Symbol, two, 0d));
|
||||
return start + 2;
|
||||
}
|
||||
}
|
||||
|
||||
switch (c)
|
||||
{
|
||||
case '+':
|
||||
case '-':
|
||||
case '*':
|
||||
case '/':
|
||||
case '%':
|
||||
case '^':
|
||||
case '#':
|
||||
case '<':
|
||||
case '>':
|
||||
case '=':
|
||||
case '(':
|
||||
case ')':
|
||||
case '{':
|
||||
case '}':
|
||||
case '[':
|
||||
case ']':
|
||||
case ';':
|
||||
case ':':
|
||||
case ',':
|
||||
case '.':
|
||||
tokens.Add(new LuaToken(LuaTokenKind.Symbol, c.ToString(), 0d));
|
||||
return start + 1;
|
||||
default:
|
||||
throw new KernelUnsupportedException($"Unexpected character '{c}'.");
|
||||
}
|
||||
}
|
||||
|
||||
private static bool IsNameStart(char c) => c == '_' || char.IsLetter(c);
|
||||
|
||||
private static bool IsNamePart(char c) => c == '_' || char.IsLetterOrDigit(c);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,355 @@
|
||||
using System.Collections.Generic;
|
||||
|
||||
namespace LuaScript.Engine.Kernel
|
||||
{
|
||||
internal sealed class LuaParser
|
||||
{
|
||||
private readonly List<LuaToken> _tokens;
|
||||
private int _pos;
|
||||
|
||||
private LuaParser(List<LuaToken> tokens) => _tokens = tokens;
|
||||
|
||||
public static IReadOnlyList<LuaStmt> Parse(string source)
|
||||
{
|
||||
var parser = new LuaParser(LuaLexer.Tokenize(source));
|
||||
var block = parser.ParseBlock();
|
||||
parser.Expect(LuaTokenKind.Eof);
|
||||
return block;
|
||||
}
|
||||
|
||||
private LuaToken Current => _tokens[_pos];
|
||||
|
||||
private LuaToken Advance() => _tokens[_pos++];
|
||||
|
||||
private bool IsBlockEnd()
|
||||
{
|
||||
var t = Current;
|
||||
return t.Kind == LuaTokenKind.Eof ||
|
||||
t.IsKeyword("end") || t.IsKeyword("else") || t.IsKeyword("elseif") || t.IsKeyword("until");
|
||||
}
|
||||
|
||||
private IReadOnlyList<LuaStmt> ParseBlock()
|
||||
{
|
||||
var statements = new List<LuaStmt>();
|
||||
while (!IsBlockEnd())
|
||||
{
|
||||
if (Current.IsSymbol(";"))
|
||||
{
|
||||
Advance();
|
||||
continue;
|
||||
}
|
||||
statements.Add(ParseStatement());
|
||||
}
|
||||
return statements;
|
||||
}
|
||||
|
||||
private LuaStmt ParseStatement()
|
||||
{
|
||||
var t = Current;
|
||||
if (t.IsKeyword("local"))
|
||||
return ParseLocal();
|
||||
if (t.IsKeyword("if"))
|
||||
return ParseIf();
|
||||
if (t.IsKeyword("for"))
|
||||
return ParseFor();
|
||||
if (t.Kind == LuaTokenKind.Keyword)
|
||||
throw new KernelUnsupportedException($"Unsupported statement '{t.Text}'.");
|
||||
return ParseExpressionStatement();
|
||||
}
|
||||
|
||||
private LuaStmt ParseLocal()
|
||||
{
|
||||
Advance();
|
||||
if (Current.IsKeyword("function"))
|
||||
throw new KernelUnsupportedException("Local functions are not supported.");
|
||||
|
||||
var names = new List<string> { ExpectName() };
|
||||
while (Current.IsSymbol(","))
|
||||
{
|
||||
Advance();
|
||||
names.Add(ExpectName());
|
||||
}
|
||||
|
||||
IReadOnlyList<LuaExpr> values = [];
|
||||
if (Current.IsSymbol("="))
|
||||
{
|
||||
Advance();
|
||||
values = ParseExpressionList();
|
||||
}
|
||||
return new LocalStmt(names, values);
|
||||
}
|
||||
|
||||
private LuaStmt ParseIf()
|
||||
{
|
||||
Advance();
|
||||
var clauses = new List<IfClause>();
|
||||
|
||||
var condition = ParseExpression();
|
||||
ExpectKeyword("then");
|
||||
clauses.Add(new IfClause(condition, ParseBlock()));
|
||||
|
||||
while (Current.IsKeyword("elseif"))
|
||||
{
|
||||
Advance();
|
||||
var elseifCondition = ParseExpression();
|
||||
ExpectKeyword("then");
|
||||
clauses.Add(new IfClause(elseifCondition, ParseBlock()));
|
||||
}
|
||||
|
||||
IReadOnlyList<LuaStmt>? elseBody = null;
|
||||
if (Current.IsKeyword("else"))
|
||||
{
|
||||
Advance();
|
||||
elseBody = ParseBlock();
|
||||
}
|
||||
|
||||
ExpectKeyword("end");
|
||||
return new IfStmt(clauses, elseBody);
|
||||
}
|
||||
|
||||
private LuaStmt ParseFor()
|
||||
{
|
||||
Advance();
|
||||
string variable = ExpectName();
|
||||
if (!Current.IsSymbol("="))
|
||||
throw new KernelUnsupportedException("Generic for loops are not supported.");
|
||||
|
||||
Advance();
|
||||
var start = ParseExpression();
|
||||
ExpectSymbol(",");
|
||||
var stop = ParseExpression();
|
||||
|
||||
LuaExpr? step = null;
|
||||
if (Current.IsSymbol(","))
|
||||
{
|
||||
Advance();
|
||||
step = ParseExpression();
|
||||
}
|
||||
|
||||
ExpectKeyword("do");
|
||||
var body = ParseBlock();
|
||||
ExpectKeyword("end");
|
||||
return new NumericForStmt(variable, start, stop, step, body);
|
||||
}
|
||||
|
||||
private LuaStmt ParseExpressionStatement()
|
||||
{
|
||||
var first = ParseSuffixedExpression();
|
||||
|
||||
if (Current.IsSymbol("=") || Current.IsSymbol(","))
|
||||
{
|
||||
var targets = new List<LuaExpr> { first };
|
||||
while (Current.IsSymbol(","))
|
||||
{
|
||||
Advance();
|
||||
targets.Add(ParseSuffixedExpression());
|
||||
}
|
||||
ExpectSymbol("=");
|
||||
var values = ParseExpressionList();
|
||||
return new AssignStmt(targets, values);
|
||||
}
|
||||
|
||||
if (first is CallExpr or MethodCallExpr)
|
||||
return new CallStmt(first);
|
||||
|
||||
throw new KernelUnsupportedException("Expression is not a valid statement.");
|
||||
}
|
||||
|
||||
private List<LuaExpr> ParseExpressionList()
|
||||
{
|
||||
var values = new List<LuaExpr> { ParseExpression() };
|
||||
while (Current.IsSymbol(","))
|
||||
{
|
||||
Advance();
|
||||
values.Add(ParseExpression());
|
||||
}
|
||||
return values;
|
||||
}
|
||||
|
||||
private LuaExpr ParseExpression(int minPrecedence = 0)
|
||||
{
|
||||
var left = ParseUnary();
|
||||
while (true)
|
||||
{
|
||||
var (op, precedence, rightAssociative) = PeekBinaryOperator();
|
||||
if (op is null || precedence < minPrecedence)
|
||||
break;
|
||||
Advance();
|
||||
int nextMinimum = rightAssociative ? precedence : precedence + 1;
|
||||
var right = ParseExpression(nextMinimum);
|
||||
left = new BinaryExpr(op, left, right);
|
||||
}
|
||||
return left;
|
||||
}
|
||||
|
||||
private LuaExpr ParseUnary()
|
||||
{
|
||||
var t = Current;
|
||||
if (t.IsKeyword("not") || t.IsSymbol("-") || t.IsSymbol("#"))
|
||||
{
|
||||
Advance();
|
||||
return new UnaryExpr(t.Text, ParseExpression(7));
|
||||
}
|
||||
return ParseValue();
|
||||
}
|
||||
|
||||
private (string? Operator, int Precedence, bool RightAssociative) PeekBinaryOperator()
|
||||
{
|
||||
var t = Current;
|
||||
if (t.IsKeyword("or")) return ("or", 1, false);
|
||||
if (t.IsKeyword("and")) return ("and", 2, false);
|
||||
if (t.Kind == LuaTokenKind.Symbol)
|
||||
{
|
||||
switch (t.Text)
|
||||
{
|
||||
case "<":
|
||||
case ">":
|
||||
case "<=":
|
||||
case ">=":
|
||||
case "~=":
|
||||
case "==":
|
||||
return (t.Text, 3, false);
|
||||
case "..":
|
||||
return ("..", 4, true);
|
||||
case "+":
|
||||
case "-":
|
||||
return (t.Text, 5, false);
|
||||
case "*":
|
||||
case "/":
|
||||
case "%":
|
||||
return (t.Text, 6, false);
|
||||
case "^":
|
||||
return ("^", 8, true);
|
||||
}
|
||||
}
|
||||
return (null, 0, false);
|
||||
}
|
||||
|
||||
private LuaExpr ParseValue()
|
||||
{
|
||||
var t = Current;
|
||||
switch (t.Kind)
|
||||
{
|
||||
case LuaTokenKind.Number:
|
||||
Advance();
|
||||
return new NumberExpr(t.Number);
|
||||
case LuaTokenKind.String:
|
||||
Advance();
|
||||
return new StringExpr(t.Text);
|
||||
case LuaTokenKind.Keyword when t.Text == "true":
|
||||
Advance();
|
||||
return new BoolExpr(true);
|
||||
case LuaTokenKind.Keyword when t.Text == "false":
|
||||
Advance();
|
||||
return new BoolExpr(false);
|
||||
case LuaTokenKind.Keyword when t.Text == "nil":
|
||||
Advance();
|
||||
return new NilExpr();
|
||||
}
|
||||
|
||||
if (t.IsKeyword("function") || t.IsSymbol("{") || t.IsSymbol("..."))
|
||||
throw new KernelUnsupportedException($"Unsupported expression near '{t.Text}'.");
|
||||
|
||||
return ParseSuffixedExpression();
|
||||
}
|
||||
|
||||
private LuaExpr ParseSuffixedExpression()
|
||||
{
|
||||
var expression = ParsePrimaryExpression();
|
||||
while (true)
|
||||
{
|
||||
var t = Current;
|
||||
if (t.IsSymbol("."))
|
||||
{
|
||||
Advance();
|
||||
expression = new MemberExpr(expression, ExpectName());
|
||||
}
|
||||
else if (t.IsSymbol("["))
|
||||
{
|
||||
Advance();
|
||||
var key = ParseExpression();
|
||||
ExpectSymbol("]");
|
||||
expression = new IndexExpr(expression, key);
|
||||
}
|
||||
else if (t.IsSymbol("("))
|
||||
{
|
||||
expression = new CallExpr(expression, ParseArguments());
|
||||
}
|
||||
else if (t.IsSymbol(":"))
|
||||
{
|
||||
Advance();
|
||||
string method = ExpectName();
|
||||
expression = new MethodCallExpr(expression, method, ParseArguments());
|
||||
}
|
||||
else
|
||||
{
|
||||
break;
|
||||
}
|
||||
}
|
||||
return expression;
|
||||
}
|
||||
|
||||
private LuaExpr ParsePrimaryExpression()
|
||||
{
|
||||
var t = Current;
|
||||
if (t.IsSymbol("("))
|
||||
{
|
||||
Advance();
|
||||
var inner = ParseExpression();
|
||||
ExpectSymbol(")");
|
||||
return inner;
|
||||
}
|
||||
if (t.Kind == LuaTokenKind.Name)
|
||||
{
|
||||
Advance();
|
||||
return new NameExpr(t.Text);
|
||||
}
|
||||
throw new KernelUnsupportedException($"Unexpected token '{t.Text}'.");
|
||||
}
|
||||
|
||||
private List<LuaExpr> ParseArguments()
|
||||
{
|
||||
ExpectSymbol("(");
|
||||
var arguments = new List<LuaExpr>();
|
||||
if (!Current.IsSymbol(")"))
|
||||
{
|
||||
arguments.Add(ParseExpression());
|
||||
while (Current.IsSymbol(","))
|
||||
{
|
||||
Advance();
|
||||
arguments.Add(ParseExpression());
|
||||
}
|
||||
}
|
||||
ExpectSymbol(")");
|
||||
return arguments;
|
||||
}
|
||||
|
||||
private string ExpectName()
|
||||
{
|
||||
if (Current.Kind != LuaTokenKind.Name)
|
||||
throw new KernelUnsupportedException($"Expected a name but found '{Current.Text}'.");
|
||||
return Advance().Text;
|
||||
}
|
||||
|
||||
private void Expect(LuaTokenKind kind)
|
||||
{
|
||||
if (Current.Kind != kind)
|
||||
throw new KernelUnsupportedException($"Expected {kind} but found '{Current.Text}'.");
|
||||
Advance();
|
||||
}
|
||||
|
||||
private void ExpectSymbol(string symbol)
|
||||
{
|
||||
if (!Current.IsSymbol(symbol))
|
||||
throw new KernelUnsupportedException($"Expected '{symbol}' but found '{Current.Text}'.");
|
||||
Advance();
|
||||
}
|
||||
|
||||
private void ExpectKeyword(string keyword)
|
||||
{
|
||||
if (!Current.IsKeyword(keyword))
|
||||
throw new KernelUnsupportedException($"Expected '{keyword}' but found '{Current.Text}'.");
|
||||
Advance();
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,28 @@
|
||||
using System;
|
||||
|
||||
namespace LuaScript.Engine.Kernel
|
||||
{
|
||||
internal enum LuaTokenKind
|
||||
{
|
||||
Name,
|
||||
Number,
|
||||
String,
|
||||
Keyword,
|
||||
Symbol,
|
||||
Eof,
|
||||
}
|
||||
|
||||
internal readonly struct LuaToken(LuaTokenKind kind, string text, double number)
|
||||
{
|
||||
public LuaTokenKind Kind { get; } = kind;
|
||||
public string Text { get; } = text;
|
||||
public double Number { get; } = number;
|
||||
|
||||
public bool Is(LuaTokenKind kind, string text) =>
|
||||
Kind == kind && string.Equals(Text, text, StringComparison.Ordinal);
|
||||
|
||||
public bool IsSymbol(string text) => Is(LuaTokenKind.Symbol, text);
|
||||
|
||||
public bool IsKeyword(string text) => Is(LuaTokenKind.Keyword, text);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,270 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using System.Linq.Expressions;
|
||||
using System.Reflection;
|
||||
using System.Runtime.Intrinsics;
|
||||
|
||||
namespace LuaScript.Engine.Kernel
|
||||
{
|
||||
internal static class SimdKernelCompiler
|
||||
{
|
||||
private static readonly Type Vec = typeof(Vector256<double>);
|
||||
|
||||
private static readonly MethodInfo Broadcast = typeof(Vector256).GetMethod(nameof(Vector256.Create), [typeof(double)])!;
|
||||
private static readonly MethodInfo Create4 = typeof(Vector256).GetMethod(nameof(Vector256.Create), [typeof(double), typeof(double), typeof(double), typeof(double)])!;
|
||||
private static readonly MethodInfo GetElement = VecOp(nameof(Vector256.GetElement), 1, 1);
|
||||
private static readonly MethodInfo Add = VecOp(nameof(Vector256.Add), 2);
|
||||
private static readonly MethodInfo Subtract = VecOp(nameof(Vector256.Subtract), 2);
|
||||
private static readonly MethodInfo Multiply = VecOp(nameof(Vector256.Multiply), 2);
|
||||
private static readonly MethodInfo Divide = VecOp(nameof(Vector256.Divide), 2);
|
||||
private static readonly MethodInfo Negate = VecOp(nameof(Vector256.Negate), 1);
|
||||
private static readonly MethodInfo Abs = VecOp(nameof(Vector256.Abs), 1);
|
||||
private static readonly MethodInfo Sqrt = VecOp(nameof(Vector256.Sqrt), 1);
|
||||
private static readonly MethodInfo FloorFn = typeof(Vector256).GetMethod(nameof(Vector256.Floor), [Vec])!;
|
||||
private static readonly MethodInfo CeilingFn = typeof(Vector256).GetMethod(nameof(Vector256.Ceiling), [Vec])!;
|
||||
private static readonly MethodInfo ConditionalSelect = VecOp(nameof(Vector256.ConditionalSelect), 3);
|
||||
private static readonly MethodInfo LessThan = VecOp(nameof(Vector256.LessThan), 2);
|
||||
private static readonly MethodInfo GreaterThan = VecOp(nameof(Vector256.GreaterThan), 2);
|
||||
private static readonly MethodInfo LessThanOrEqual = VecOp(nameof(Vector256.LessThanOrEqual), 2);
|
||||
private static readonly MethodInfo GreaterThanOrEqual = VecOp(nameof(Vector256.GreaterThanOrEqual), 2);
|
||||
private static readonly MethodInfo EqualsFn = VecOp(nameof(Vector256.Equals), 2);
|
||||
private static readonly MethodInfo BitwiseAnd = VecOp(nameof(Vector256.BitwiseAnd), 2);
|
||||
private static readonly MethodInfo BitwiseOr = VecOp(nameof(Vector256.BitwiseOr), 2);
|
||||
private static readonly MethodInfo OnesComplement = VecOp(nameof(Vector256.OnesComplement), 1);
|
||||
|
||||
private static readonly Expression Zero = Expression.Constant(Vector256<double>.Zero, Vec);
|
||||
private static readonly Expression AllBits = Expression.Constant(Vector256<double>.AllBitsSet, Vec);
|
||||
private static readonly Expression V255 = Expression.Constant(Vector256.Create(255d), Vec);
|
||||
|
||||
public static CpuKernel.RowDelegate? TryCompile(KernelProgram program)
|
||||
{
|
||||
try
|
||||
{
|
||||
return Compile(program);
|
||||
}
|
||||
catch (KernelUnsupportedException)
|
||||
{
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
private static CpuKernel.RowDelegate Compile(KernelProgram program)
|
||||
{
|
||||
var buffer = Expression.Parameter(typeof(byte[]), "buffer");
|
||||
var rowBase = Expression.Parameter(typeof(int), "rowBase");
|
||||
var xStart = Expression.Parameter(typeof(int), "xStart");
|
||||
var xEnd = Expression.Parameter(typeof(int), "xEnd");
|
||||
var yScalar = Expression.Parameter(typeof(double), "y");
|
||||
var uniforms = Expression.Parameter(typeof(double[]), "uniforms");
|
||||
|
||||
var x = Expression.Variable(typeof(int), "x");
|
||||
var index = Expression.Variable(typeof(int), "index");
|
||||
var yVec = Expression.Variable(Vec, "yVec");
|
||||
var xVec = Expression.Variable(Vec, "xVec");
|
||||
var alphaRaw = Expression.Variable(Vec, "alphaRaw");
|
||||
var transparent = Expression.Variable(Vec, "transparent");
|
||||
var scale = Expression.Variable(Vec, "scale");
|
||||
var inputs = new[]
|
||||
{
|
||||
Expression.Variable(Vec, "inR"),
|
||||
Expression.Variable(Vec, "inG"),
|
||||
Expression.Variable(Vec, "inB"),
|
||||
Expression.Variable(Vec, "inA"),
|
||||
};
|
||||
var slots = new ParameterExpression[program.Bindings.Count];
|
||||
for (int i = 0; i < slots.Length; i++)
|
||||
slots[i] = Expression.Variable(Vec, "slot" + i);
|
||||
|
||||
var context = new Context(xVec, yVec, uniforms, inputs, slots);
|
||||
|
||||
var statements = new List<Expression>
|
||||
{
|
||||
Expression.Assign(index, Expression.Add(rowBase, Expression.Multiply(x, Constant(4)))),
|
||||
Expression.Assign(xVec, Expression.Call(Create4,
|
||||
ToDouble(x),
|
||||
ToDouble(Expression.Add(x, Constant(1))),
|
||||
ToDouble(Expression.Add(x, Constant(2))),
|
||||
ToDouble(Expression.Add(x, Constant(3))))),
|
||||
Expression.Assign(alphaRaw, LoadChannel(buffer, index, 3)),
|
||||
Expression.Assign(transparent, Call(LessThanOrEqual, alphaRaw, Zero)),
|
||||
Expression.Assign(scale, Select(transparent, Zero, Call(Divide, V255, alphaRaw))),
|
||||
Expression.Assign(inputs[3], Select(transparent, Zero, alphaRaw)),
|
||||
Expression.Assign(inputs[0], Select(transparent, Zero, ClampByte(Call(Multiply, LoadChannel(buffer, index, 2), scale)))),
|
||||
Expression.Assign(inputs[1], Select(transparent, Zero, ClampByte(Call(Multiply, LoadChannel(buffer, index, 1), scale)))),
|
||||
Expression.Assign(inputs[2], Select(transparent, Zero, ClampByte(Call(Multiply, LoadChannel(buffer, index, 0), scale)))),
|
||||
};
|
||||
|
||||
for (int i = 0; i < slots.Length; i++)
|
||||
statements.Add(Expression.Assign(slots[i], Build(program.Bindings[i], context)));
|
||||
|
||||
var outA = Expression.Variable(Vec, "outA");
|
||||
var alphaScale = Expression.Variable(Vec, "alphaScale");
|
||||
statements.Add(Expression.Assign(outA, Build(program.OutputA, context)));
|
||||
statements.Add(Expression.Assign(alphaScale, Call(Divide, ClampByte(outA), V255)));
|
||||
statements.Add(StoreChannel(buffer, index, 0, ClampByte(Call(Multiply, Build(program.OutputB, context), alphaScale))));
|
||||
statements.Add(StoreChannel(buffer, index, 1, ClampByte(Call(Multiply, Build(program.OutputG, context), alphaScale))));
|
||||
statements.Add(StoreChannel(buffer, index, 2, ClampByte(Call(Multiply, Build(program.OutputR, context), alphaScale))));
|
||||
statements.Add(StoreChannel(buffer, index, 3, ClampByte(outA)));
|
||||
statements.Add(Expression.AddAssign(x, Constant(4)));
|
||||
|
||||
var breakLabel = Expression.Label("break");
|
||||
var loop = Expression.Loop(
|
||||
Expression.IfThenElse(
|
||||
Expression.LessThan(x, xEnd),
|
||||
Expression.Block(statements),
|
||||
Expression.Break(breakLabel)),
|
||||
breakLabel);
|
||||
|
||||
var locals = new List<ParameterExpression> { x, index, yVec, xVec, alphaRaw, transparent, scale, outA, alphaScale };
|
||||
locals.AddRange(inputs);
|
||||
locals.AddRange(slots);
|
||||
|
||||
var body = Expression.Block(
|
||||
locals,
|
||||
Expression.Assign(yVec, Expression.Call(Broadcast, yScalar)),
|
||||
Expression.Assign(x, xStart),
|
||||
loop);
|
||||
|
||||
var lambda = Expression.Lambda<CpuKernel.RowDelegate>(body, buffer, rowBase, xStart, xEnd, yScalar, uniforms);
|
||||
return lambda.Compile();
|
||||
}
|
||||
|
||||
private sealed record Context(
|
||||
Expression X,
|
||||
Expression Y,
|
||||
ParameterExpression Uniforms,
|
||||
Expression[] Inputs,
|
||||
ParameterExpression[] Slots);
|
||||
|
||||
private static Expression Build(KExpr expression, Context context)
|
||||
{
|
||||
switch (expression)
|
||||
{
|
||||
case KConst value:
|
||||
return Expression.Constant(Vector256.Create(value.Value), Vec);
|
||||
case KInput input:
|
||||
return context.Inputs[(int)input.Channel];
|
||||
case KCoord coord:
|
||||
return coord.Axis == KAxis.X ? context.X : context.Y;
|
||||
case KUniformRef uniform:
|
||||
return Expression.Call(Broadcast, Expression.ArrayIndex(context.Uniforms, Constant((int)uniform.Uniform)));
|
||||
case KLocalRef local:
|
||||
return context.Slots[local.Slot];
|
||||
case KNegate negate:
|
||||
return Call(Negate, Build(negate.Operand, context));
|
||||
case KArith arithmetic:
|
||||
return BuildArithmetic(arithmetic, context);
|
||||
case KCall call:
|
||||
return BuildCall(call, context);
|
||||
case KSelect select:
|
||||
return Select(BuildBool(select.Condition, context), Build(select.WhenTrue, context), Build(select.WhenFalse, context));
|
||||
}
|
||||
throw new KernelUnsupportedException("Unsupported SIMD expression.");
|
||||
}
|
||||
|
||||
private static Expression BuildArithmetic(KArith arithmetic, Context context)
|
||||
{
|
||||
var left = Build(arithmetic.Left, context);
|
||||
var right = Build(arithmetic.Right, context);
|
||||
return arithmetic.Op switch
|
||||
{
|
||||
KArithOp.Add => Call(Add, left, right),
|
||||
KArithOp.Subtract => Call(Subtract, left, right),
|
||||
KArithOp.Multiply => Call(Multiply, left, right),
|
||||
KArithOp.Divide => Call(Divide, left, right),
|
||||
KArithOp.Modulo => Call(Subtract, left, Call(Multiply, Call(FloorFn, Call(Divide, left, right)), right)),
|
||||
_ => throw new KernelUnsupportedException("Unsupported SIMD arithmetic operator."),
|
||||
};
|
||||
}
|
||||
|
||||
private static Expression BuildCall(KCall call, Context context)
|
||||
{
|
||||
var argument = Build(call.Arguments[0], context);
|
||||
return call.Func switch
|
||||
{
|
||||
KFunc.Abs => Call(Abs, argument),
|
||||
KFunc.Floor => Call(FloorFn, argument),
|
||||
KFunc.Ceil => Call(CeilingFn, argument),
|
||||
KFunc.Sqrt => Call(Sqrt, argument),
|
||||
_ => throw new KernelUnsupportedException("Unsupported SIMD function."),
|
||||
};
|
||||
}
|
||||
|
||||
private static Expression BuildBool(KBool condition, Context context)
|
||||
{
|
||||
switch (condition)
|
||||
{
|
||||
case KBoolConst value:
|
||||
return value.Value ? AllBits : Zero;
|
||||
case KNot not:
|
||||
return Call(OnesComplement, BuildBool(not.Operand, context));
|
||||
case KLogical logical:
|
||||
return logical.IsAnd
|
||||
? Call(BitwiseAnd, BuildBool(logical.Left, context), BuildBool(logical.Right, context))
|
||||
: Call(BitwiseOr, BuildBool(logical.Left, context), BuildBool(logical.Right, context));
|
||||
case KCompare compare:
|
||||
var left = Build(compare.Left, context);
|
||||
var right = Build(compare.Right, context);
|
||||
return compare.Op switch
|
||||
{
|
||||
KCompareOp.Less => Call(LessThan, left, right),
|
||||
KCompareOp.Greater => Call(GreaterThan, left, right),
|
||||
KCompareOp.LessEqual => Call(LessThanOrEqual, left, right),
|
||||
KCompareOp.GreaterEqual => Call(GreaterThanOrEqual, left, right),
|
||||
KCompareOp.Equal => Call(EqualsFn, left, right),
|
||||
KCompareOp.NotEqual => Call(OnesComplement, Call(EqualsFn, left, right)),
|
||||
_ => throw new KernelUnsupportedException("Unsupported SIMD comparison."),
|
||||
};
|
||||
}
|
||||
throw new KernelUnsupportedException("Unsupported SIMD condition.");
|
||||
}
|
||||
|
||||
private static Expression ClampByte(Expression value)
|
||||
{
|
||||
var low = Select(Call(LessThan, value, Zero), Zero, value);
|
||||
return Select(Call(GreaterThan, low, V255), V255, low);
|
||||
}
|
||||
|
||||
private static Expression Select(Expression condition, Expression whenTrue, Expression whenFalse) =>
|
||||
Expression.Call(ConditionalSelect, condition, whenTrue, whenFalse);
|
||||
|
||||
private static Expression LoadChannel(ParameterExpression buffer, ParameterExpression index, int offset) =>
|
||||
Expression.Call(Create4,
|
||||
ToDouble(ReadByte(buffer, index, offset)),
|
||||
ToDouble(ReadByte(buffer, index, offset + 4)),
|
||||
ToDouble(ReadByte(buffer, index, offset + 8)),
|
||||
ToDouble(ReadByte(buffer, index, offset + 12)));
|
||||
|
||||
private static Expression StoreChannel(ParameterExpression buffer, ParameterExpression index, int offset, Expression value)
|
||||
{
|
||||
var writes = new Expression[4];
|
||||
for (int lane = 0; lane < 4; lane++)
|
||||
writes[lane] = Expression.Assign(
|
||||
Expression.ArrayAccess(buffer, Expression.Add(index, Constant(lane * 4 + offset))),
|
||||
Expression.Convert(Expression.Call(GetElement, value, Constant(lane)), typeof(byte)));
|
||||
return Expression.Block(writes);
|
||||
}
|
||||
|
||||
private static Expression ReadByte(ParameterExpression buffer, ParameterExpression index, int offset) =>
|
||||
Expression.ArrayIndex(buffer, offset == 0 ? index : Expression.Add(index, Constant(offset)));
|
||||
|
||||
private static Expression Call(MethodInfo method, params Expression[] arguments) =>
|
||||
Expression.Call(method, arguments);
|
||||
|
||||
private static Expression ToDouble(Expression value) => Expression.Convert(value, typeof(double));
|
||||
|
||||
private static ConstantExpression Constant(int value) => Expression.Constant(value, typeof(int));
|
||||
|
||||
private static MethodInfo VecOp(string name, int vectorArgs, int intArgs = 0) =>
|
||||
typeof(Vector256).GetMethods()
|
||||
.Single(m => m.Name == name && m.IsGenericMethodDefinition &&
|
||||
m.GetParameters().Length == vectorArgs + intArgs &&
|
||||
m.GetParameters().Take(vectorArgs).All(p => IsVector(p.ParameterType)) &&
|
||||
m.GetParameters().Skip(vectorArgs).All(p => p.ParameterType == typeof(int)))
|
||||
.MakeGenericMethod(typeof(double));
|
||||
|
||||
private static bool IsVector(Type type) =>
|
||||
type.IsGenericType && type.GetGenericTypeDefinition() == typeof(Vector256<>);
|
||||
}
|
||||
}
|
||||
+508
-22
@@ -19,14 +19,23 @@ namespace LuaScript.Engine
|
||||
private EventWaitHandle? _workEvent;
|
||||
private EventWaitHandle? _doneEvent;
|
||||
private Process? _process;
|
||||
private int _width;
|
||||
private int _height;
|
||||
private int _stringParamsCapacity = NativeProtocol.MinStringParamsCapacity;
|
||||
private long _pixelOffset = NativeProtocol.PixelOffset(NativeProtocol.MinStringParamsCapacity);
|
||||
private long _allocatedSize;
|
||||
private bool _alive;
|
||||
|
||||
private readonly byte[] _callbackTag = new byte[NativeProtocol.CallbackTagMax];
|
||||
private readonly byte[] _lastCallbackTag = new byte[NativeProtocol.CallbackTagMax];
|
||||
private readonly double[] _anchorBuffer = new double[Anchor.AnchorSupport.MaxAnchors * 3];
|
||||
private int _lastCallbackTagLength = -1;
|
||||
private string _lastCallbackTagText = string.Empty;
|
||||
private int _scriptVersion;
|
||||
private string? _lastScript;
|
||||
private byte[] _lastScriptBytes = Array.Empty<byte>();
|
||||
private bool _scriptWritten;
|
||||
private readonly Dictionary<string, byte[]> _stringNameBytes = new(StringComparer.Ordinal);
|
||||
private byte[] _stringValueBytes = new byte[256];
|
||||
private byte[] _sceneValueBytes = new byte[256];
|
||||
|
||||
public LuaJitWorker(string nativeDir)
|
||||
{
|
||||
@@ -42,33 +51,62 @@ namespace LuaScript.Engine
|
||||
public bool Execute(
|
||||
string script,
|
||||
double[] fields,
|
||||
byte[] pixels,
|
||||
IReadOnlyDictionary<string, string> stringParameters,
|
||||
PixelRegionAccess loadPixels,
|
||||
int width,
|
||||
int height,
|
||||
int timeoutMs,
|
||||
Func<string, int, SceneObjectInfo?> resolveObject,
|
||||
Func<string, int, double, double, double, (byte[] buffer, int w, int h)> loadFigure,
|
||||
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,
|
||||
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,
|
||||
out bool pixelsDirty,
|
||||
out bool bufferReplaced,
|
||||
out int resultWidth,
|
||||
out int resultHeight,
|
||||
out string? error)
|
||||
{
|
||||
pixelsDirty = false;
|
||||
bufferReplaced = false;
|
||||
resultWidth = width;
|
||||
resultHeight = height;
|
||||
error = null;
|
||||
|
||||
byte[] scriptBytes = Encoding.UTF8.GetBytes(script);
|
||||
if (scriptBytes.Length > NativeProtocol.ScriptMax)
|
||||
bool scriptChanged = !ReferenceEquals(script, _lastScript);
|
||||
if (scriptChanged)
|
||||
{
|
||||
error = "script too large for native lane";
|
||||
return false;
|
||||
byte[] scriptBytes = Encoding.UTF8.GetBytes(script);
|
||||
if (scriptBytes.Length > NativeProtocol.ScriptMax)
|
||||
{
|
||||
error = "script too large for native lane";
|
||||
return false;
|
||||
}
|
||||
_lastScript = script;
|
||||
_lastScriptBytes = scriptBytes;
|
||||
_scriptVersion++;
|
||||
}
|
||||
|
||||
EnsureWorker(width, height);
|
||||
int stringCapacity = ResolveStringCapacity(_stringParamsCapacity, MeasureStringParameters(stringParameters));
|
||||
EnsureWorker(width, height, stringCapacity);
|
||||
var view = _view!;
|
||||
|
||||
view.WriteArray(NativeProtocol.FieldsOffset, fields, 0, NativeProtocol.FieldCount);
|
||||
WriteStringParameters(view, stringParameters);
|
||||
view.Write(NativeProtocol.OffWidth, width);
|
||||
view.Write(NativeProtocol.OffHeight, height);
|
||||
view.Write(NativeProtocol.OffScriptLen, scriptBytes.Length);
|
||||
view.WriteArray(NativeProtocol.ScriptOffset, scriptBytes, 0, scriptBytes.Length);
|
||||
view.WriteArray(NativeProtocol.PixelOffset, pixels, 0, pixels.Length);
|
||||
if (scriptChanged || !_scriptWritten)
|
||||
{
|
||||
view.Write(NativeProtocol.OffScriptLen, _lastScriptBytes.Length);
|
||||
view.WriteArray(NativeProtocol.ScriptOffset, _lastScriptBytes, 0, _lastScriptBytes.Length);
|
||||
_scriptWritten = true;
|
||||
}
|
||||
view.Write(NativeProtocol.OffScriptVersion, _scriptVersion);
|
||||
view.Write(NativeProtocol.OffPixelsDirty, 0);
|
||||
view.Write(NativeProtocol.OffErrorLen, 0);
|
||||
view.Write(NativeProtocol.OffStatus, NativeProtocol.StatusIdle);
|
||||
@@ -92,7 +130,27 @@ namespace LuaScript.Engine
|
||||
if (status != NativeProtocol.StatusCallback)
|
||||
break;
|
||||
|
||||
ResolveCallback(view, resolveObject);
|
||||
int callbackKind = view.ReadInt32(NativeProtocol.OffCallbackKind);
|
||||
if (callbackKind == NativeProtocol.CbKindRequestPixels)
|
||||
{
|
||||
try
|
||||
{
|
||||
AccessPixelRegion(loadPixels);
|
||||
}
|
||||
catch
|
||||
{
|
||||
KillWorker();
|
||||
throw;
|
||||
}
|
||||
}
|
||||
else if (callbackKind == NativeProtocol.CbKindFlushDraws)
|
||||
{
|
||||
DrainDrawRing(view, addDraw);
|
||||
}
|
||||
else
|
||||
{
|
||||
DispatchCallback(view, resolveObject, loadFigure, loadText, loadImage, loadMovie, addEffect, setAnchor, sceneGetValue, sceneSetValue);
|
||||
}
|
||||
_workEvent.Set();
|
||||
}
|
||||
|
||||
@@ -105,17 +163,289 @@ namespace LuaScript.Engine
|
||||
return false;
|
||||
}
|
||||
|
||||
DrainDrawRing(view, addDraw);
|
||||
|
||||
for (int i = NativeProtocol.FirstWritableField; i <= NativeProtocol.LastWritableField; i++)
|
||||
fields[i] = view.ReadDouble(NativeProtocol.FieldsOffset + i * 8);
|
||||
|
||||
fields[NativeProtocol.DrawState] = view.ReadDouble(NativeProtocol.FieldsOffset + NativeProtocol.DrawState * 8);
|
||||
|
||||
resultWidth = view.ReadInt32(NativeProtocol.OffWidth);
|
||||
resultHeight = view.ReadInt32(NativeProtocol.OffHeight);
|
||||
bufferReplaced = resultWidth != width || resultHeight != height;
|
||||
|
||||
pixelsDirty = view.ReadInt32(NativeProtocol.OffPixelsDirty) != 0;
|
||||
if (pixelsDirty)
|
||||
view.ReadArray(NativeProtocol.PixelOffset, pixels, 0, pixels.Length);
|
||||
if (pixelsDirty && (long)resultWidth * resultHeight * 4 > _allocatedSize - _pixelOffset)
|
||||
{
|
||||
error = "native worker reported a pixel buffer beyond capacity";
|
||||
return false;
|
||||
}
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
private void ResolveCallback(MemoryMappedViewAccessor view, Func<string, int, SceneObjectInfo?> resolveObject)
|
||||
public void ReadPixels(PixelRegionAccess reader) => AccessPixelRegion(reader);
|
||||
|
||||
private unsafe void AccessPixelRegion(PixelRegionAccess access)
|
||||
{
|
||||
var handle = _view!.SafeMemoryMappedViewHandle;
|
||||
byte* ptr = null;
|
||||
handle.AcquirePointer(ref ptr);
|
||||
try
|
||||
{
|
||||
long offset = _view.PointerOffset + _pixelOffset;
|
||||
access((nint)(ptr + offset), (long)handle.ByteLength - offset);
|
||||
}
|
||||
finally
|
||||
{
|
||||
handle.ReleasePointer();
|
||||
}
|
||||
}
|
||||
|
||||
private unsafe void WritePixelRegion(byte[] source, int length)
|
||||
{
|
||||
var handle = _view!.SafeMemoryMappedViewHandle;
|
||||
byte* ptr = null;
|
||||
handle.AcquirePointer(ref ptr);
|
||||
try
|
||||
{
|
||||
fixed (byte* src = source)
|
||||
Buffer.MemoryCopy(src, ptr + _view.PointerOffset + _pixelOffset, handle.ByteLength - (ulong)(_view.PointerOffset + _pixelOffset), (ulong)length);
|
||||
}
|
||||
finally
|
||||
{
|
||||
handle.ReleasePointer();
|
||||
}
|
||||
}
|
||||
|
||||
private static int MeasureStringParameters(IReadOnlyDictionary<string, string> stringParameters)
|
||||
{
|
||||
int total = 4;
|
||||
foreach (var pair in stringParameters)
|
||||
total += 8 + Encoding.UTF8.GetByteCount(pair.Key) + Encoding.UTF8.GetByteCount(pair.Value ?? string.Empty);
|
||||
return total;
|
||||
}
|
||||
|
||||
private static int ResolveStringCapacity(int current, int required)
|
||||
{
|
||||
int capacity = current;
|
||||
while (capacity < required)
|
||||
{
|
||||
if (capacity > int.MaxValue / 2)
|
||||
{
|
||||
capacity = required;
|
||||
break;
|
||||
}
|
||||
capacity *= 2;
|
||||
}
|
||||
return capacity;
|
||||
}
|
||||
|
||||
private void WriteStringParameters(MemoryMappedViewAccessor view, IReadOnlyDictionary<string, string> stringParameters)
|
||||
{
|
||||
long basePos = NativeProtocol.StringParamsOffset;
|
||||
long limit = basePos + _stringParamsCapacity;
|
||||
long pos = basePos + 4;
|
||||
int count = 0;
|
||||
foreach (var pair in stringParameters)
|
||||
{
|
||||
if (!_stringNameBytes.TryGetValue(pair.Key, out var name))
|
||||
{
|
||||
name = Encoding.UTF8.GetBytes(pair.Key);
|
||||
_stringNameBytes[pair.Key] = name;
|
||||
}
|
||||
string value = pair.Value ?? string.Empty;
|
||||
int maxValueBytes = Encoding.UTF8.GetMaxByteCount(value.Length);
|
||||
if (_stringValueBytes.Length < maxValueBytes)
|
||||
_stringValueBytes = new byte[Math.Max(maxValueBytes, _stringValueBytes.Length * 2)];
|
||||
int valueLen = Encoding.UTF8.GetBytes(value, 0, value.Length, _stringValueBytes, 0);
|
||||
if (pos + 8 + name.Length + valueLen > limit)
|
||||
break;
|
||||
view.Write(pos, name.Length); pos += 4;
|
||||
view.WriteArray(pos, name, 0, name.Length); pos += name.Length;
|
||||
view.Write(pos, valueLen); pos += 4;
|
||||
view.WriteArray(pos, _stringValueBytes, 0, valueLen); pos += valueLen;
|
||||
count++;
|
||||
}
|
||||
view.Write(basePos, count);
|
||||
view.Write(NativeProtocol.OffStringParamsLen, (int)(pos - basePos));
|
||||
}
|
||||
|
||||
private void DispatchCallback(
|
||||
MemoryMappedViewAccessor view,
|
||||
Func<string, int, SceneObjectInfo?> resolveObject,
|
||||
Func<string, int, double, double, double, (byte[] buffer, int w, int h)> loadFigure,
|
||||
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,
|
||||
Action<string, IReadOnlyList<KeyValuePair<string, object>>> addEffect,
|
||||
Action<string, int, bool, int, double[]> setAnchor,
|
||||
Func<string, SceneValue> sceneGetValue,
|
||||
Action<string, SceneValue> sceneSetValue)
|
||||
{
|
||||
int kind = view.ReadInt32(NativeProtocol.OffCallbackKind);
|
||||
switch (kind)
|
||||
{
|
||||
case NativeProtocol.CbKindGetObject:
|
||||
ResolveGetObjectCallback(view, resolveObject);
|
||||
break;
|
||||
case NativeProtocol.CbKindLoadFigure:
|
||||
ResolveLoadFigureCallback(view, loadFigure);
|
||||
break;
|
||||
case NativeProtocol.CbKindLoadText:
|
||||
ResolveLoadTextCallback(view, loadText);
|
||||
break;
|
||||
case NativeProtocol.CbKindLoadImage:
|
||||
ResolveLoadImageCallback(view, loadImage);
|
||||
break;
|
||||
case NativeProtocol.CbKindLoadMovie:
|
||||
ResolveLoadMovieCallback(view, loadMovie);
|
||||
break;
|
||||
case NativeProtocol.CbKindEffect:
|
||||
ResolveEffectCallback(view, addEffect);
|
||||
break;
|
||||
case NativeProtocol.CbKindSetAnchor:
|
||||
ResolveSetAnchorCallback(view, setAnchor);
|
||||
break;
|
||||
case NativeProtocol.CbKindSceneGet:
|
||||
ResolveSceneGetCallback(view, sceneGetValue);
|
||||
break;
|
||||
case NativeProtocol.CbKindSceneSet:
|
||||
ResolveSceneSetCallback(view, sceneSetValue);
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
private void ResolveSceneGetCallback(MemoryMappedViewAccessor view, Func<string, SceneValue> getValue)
|
||||
{
|
||||
int tagLen = Math.Clamp(view.ReadInt32(NativeProtocol.OffCallbackTagLen), 0, NativeProtocol.CallbackTagMax);
|
||||
view.ReadArray(NativeProtocol.CallbackTagOffset, _callbackTag, 0, tagLen);
|
||||
string name = ResolveTag(tagLen);
|
||||
|
||||
SceneValue value;
|
||||
try { value = getValue(name); }
|
||||
catch { value = SceneValue.Nil; }
|
||||
|
||||
long rOff = NativeProtocol.CallbackResultOffset;
|
||||
view.Write(rOff + 0 * 8, (double)value.Kind);
|
||||
view.Write(rOff + 1 * 8, value.Number);
|
||||
if (value.Kind == SceneValueKind.String)
|
||||
{
|
||||
string text = value.Text ?? string.Empty;
|
||||
int maxBytes = Encoding.UTF8.GetMaxByteCount(text.Length);
|
||||
if (_sceneValueBytes.Length < maxBytes)
|
||||
_sceneValueBytes = new byte[Math.Max(maxBytes, _sceneValueBytes.Length * 2)];
|
||||
int length = Encoding.UTF8.GetBytes(text, 0, text.Length, _sceneValueBytes, 0);
|
||||
if (length > NativeProtocol.CallbackTagMax)
|
||||
length = NativeProtocol.CallbackTagMax;
|
||||
view.WriteArray(NativeProtocol.CallbackTagOffset, _sceneValueBytes, 0, length);
|
||||
view.Write(NativeProtocol.OffCallbackTagLen, length);
|
||||
}
|
||||
view.Write(NativeProtocol.OffCallbackFound, 1);
|
||||
}
|
||||
|
||||
private void ResolveSceneSetCallback(MemoryMappedViewAccessor view, Action<string, SceneValue> setValue)
|
||||
{
|
||||
int tagLen = Math.Clamp(view.ReadInt32(NativeProtocol.OffCallbackTagLen), 0, NativeProtocol.CallbackTagMax);
|
||||
view.ReadArray(NativeProtocol.CallbackTagOffset, _callbackTag, 0, tagLen);
|
||||
|
||||
long rOff = NativeProtocol.CallbackResultOffset;
|
||||
var kind = (SceneValueKind)(int)view.ReadDouble(rOff + 0 * 8);
|
||||
double number = view.ReadDouble(rOff + 1 * 8);
|
||||
|
||||
string name;
|
||||
SceneValue value;
|
||||
if (kind == SceneValueKind.String)
|
||||
{
|
||||
int separator = Array.IndexOf(_callbackTag, (byte)0, 0, tagLen);
|
||||
int nameLength = separator >= 0 ? separator : tagLen;
|
||||
name = Encoding.UTF8.GetString(_callbackTag, 0, nameLength);
|
||||
value = SceneValue.FromString(separator >= 0
|
||||
? Encoding.UTF8.GetString(_callbackTag, separator + 1, tagLen - separator - 1)
|
||||
: string.Empty);
|
||||
}
|
||||
else
|
||||
{
|
||||
name = ResolveTag(tagLen);
|
||||
value = kind switch
|
||||
{
|
||||
SceneValueKind.Number => SceneValue.FromNumber(number),
|
||||
SceneValueKind.Boolean => SceneValue.FromBoolean(number != 0d),
|
||||
_ => SceneValue.Nil,
|
||||
};
|
||||
}
|
||||
|
||||
try { setValue(name, value); }
|
||||
catch { }
|
||||
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);
|
||||
view.ReadArray(NativeProtocol.CallbackTagOffset, _callbackTag, 0, tagLen);
|
||||
string group = Encoding.UTF8.GetString(_callbackTag, 0, tagLen);
|
||||
|
||||
long rOff = NativeProtocol.CallbackResultOffset;
|
||||
int count = Math.Clamp((int)view.ReadDouble(rOff + 0 * 8), 0, Anchor.AnchorSupport.MaxAnchors);
|
||||
bool is3D = view.ReadDouble(rOff + 1 * 8) != 0d;
|
||||
int connection = (int)view.ReadDouble(rOff + 2 * 8);
|
||||
|
||||
Array.Clear(_anchorBuffer, 0, _anchorBuffer.Length);
|
||||
try { setAnchor(group, count, is3D, connection, _anchorBuffer); }
|
||||
catch { }
|
||||
|
||||
int stride = is3D ? 3 : 2;
|
||||
for (int i = 0; i < count * stride; i++)
|
||||
view.Write(NativeProtocol.CallbackTagOffset + i * 8, _anchorBuffer[i]);
|
||||
view.Write(NativeProtocol.OffCallbackFound, 1);
|
||||
}
|
||||
|
||||
private void DrainDrawRing(MemoryMappedViewAccessor view, Action<DrawCommand> addDraw)
|
||||
{
|
||||
long ringBase = NativeProtocol.DrawRingOffset(_stringParamsCapacity);
|
||||
int count = Math.Clamp((int)view.ReadDouble(ringBase), 0, NativeProtocol.DrawRingCapacity);
|
||||
for (int k = 0; k < count; k++)
|
||||
{
|
||||
long entry = ringBase + (1 + (long)k * NativeProtocol.DrawEntryDoubles) * 8;
|
||||
int kind = (int)view.ReadDouble(entry);
|
||||
long payload = entry + 8;
|
||||
if (kind == NativeProtocol.CbKindDrawPoly)
|
||||
DispatchRingDrawPoly(view, payload, addDraw);
|
||||
else
|
||||
DispatchRingDraw(view, payload, addDraw);
|
||||
}
|
||||
view.Write(ringBase, 0d);
|
||||
}
|
||||
|
||||
private static void DispatchRingDraw(MemoryMappedViewAccessor view, long payload, Action<DrawCommand> addDraw)
|
||||
{
|
||||
double ox = view.ReadDouble(payload + 0 * 8);
|
||||
double oy = view.ReadDouble(payload + 1 * 8);
|
||||
double oz = view.ReadDouble(payload + 2 * 8);
|
||||
double zoom = view.ReadDouble(payload + 3 * 8);
|
||||
double alpha = view.ReadDouble(payload + 4 * 8);
|
||||
double aspect = view.ReadDouble(payload + 5 * 8);
|
||||
double antialias = view.ReadDouble(payload + 6 * 8);
|
||||
double blend = view.ReadDouble(payload + 7 * 8);
|
||||
|
||||
try { addDraw(new DrawCommand(ox, oy, oz, zoom, alpha, aspect, null, antialias, blend)); }
|
||||
catch { }
|
||||
}
|
||||
|
||||
private static void DispatchRingDrawPoly(MemoryMappedViewAccessor view, long payload, Action<DrawCommand> addDraw)
|
||||
{
|
||||
var poly = new double[DrawPolyMath.Length];
|
||||
for (int i = 0; i < DrawPolyMath.Length; i++)
|
||||
poly[i] = view.ReadDouble(payload + i * 8);
|
||||
double antialias = view.ReadDouble(payload + DrawPolyMath.Length * 8);
|
||||
double blend = view.ReadDouble(payload + (DrawPolyMath.Length + 1) * 8);
|
||||
|
||||
try { addDraw(new DrawCommand(0d, 0d, 0d, 1d, poly[20], 0d, poly, antialias, blend)); }
|
||||
catch { }
|
||||
}
|
||||
|
||||
private void ResolveGetObjectCallback(MemoryMappedViewAccessor view, Func<string, int, SceneObjectInfo?> resolveObject)
|
||||
{
|
||||
int frame = view.ReadInt32(NativeProtocol.OffCallbackFrame);
|
||||
int tagLen = Math.Clamp(view.ReadInt32(NativeProtocol.OffCallbackTagLen), 0, NativeProtocol.CallbackTagMax);
|
||||
@@ -145,6 +475,158 @@ namespace LuaScript.Engine
|
||||
}
|
||||
}
|
||||
|
||||
private void ResolveLoadFigureCallback(
|
||||
MemoryMappedViewAccessor view,
|
||||
Func<string, int, double, double, double, (byte[] buffer, int w, int h)> loadFigure)
|
||||
{
|
||||
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);
|
||||
|
||||
long rOff = NativeProtocol.CallbackResultOffset;
|
||||
int color = (int)view.ReadDouble(rOff + 0 * 8);
|
||||
double size = view.ReadDouble(rOff + 1 * 8);
|
||||
double lineWidth = view.ReadDouble(rOff + 2 * 8);
|
||||
double aspect = view.ReadDouble(rOff + 3 * 8);
|
||||
|
||||
(byte[] buffer, int w, int h) result;
|
||||
try { result = loadFigure(name, color, size, lineWidth, aspect); }
|
||||
catch { result = (new byte[4], 1, 1); }
|
||||
|
||||
int pixelSize = result.w * result.h * 4;
|
||||
long capacity = view.Capacity - _pixelOffset;
|
||||
if (pixelSize > capacity)
|
||||
{
|
||||
result = (new byte[4], 1, 1);
|
||||
pixelSize = 4;
|
||||
}
|
||||
|
||||
view.Write(NativeProtocol.OffLoadResultWidth, result.w);
|
||||
view.Write(NativeProtocol.OffLoadResultHeight, result.h);
|
||||
WritePixelRegion(result.buffer, pixelSize);
|
||||
view.Write(NativeProtocol.OffCallbackFound, 1);
|
||||
}
|
||||
|
||||
private void ResolveLoadTextCallback(
|
||||
MemoryMappedViewAccessor view,
|
||||
Func<string, string, double, bool, bool, int, (byte[] buffer, int w, int h)> loadText)
|
||||
{
|
||||
int tagLen = Math.Clamp(view.ReadInt32(NativeProtocol.OffCallbackTagLen), 0, NativeProtocol.CallbackTagMax);
|
||||
view.ReadArray(NativeProtocol.CallbackTagOffset, _callbackTag, 0, tagLen);
|
||||
string payload = Encoding.UTF8.GetString(_callbackTag, 0, tagLen);
|
||||
int separator = payload.IndexOf('\0');
|
||||
string family = separator >= 0 ? payload[..separator] : string.Empty;
|
||||
string text = separator >= 0 ? payload[(separator + 1)..] : payload;
|
||||
|
||||
long rOff = NativeProtocol.CallbackResultOffset;
|
||||
double size = view.ReadDouble(rOff + 0 * 8);
|
||||
bool bold = view.ReadDouble(rOff + 1 * 8) != 0;
|
||||
bool italic = view.ReadDouble(rOff + 2 * 8) != 0;
|
||||
int color = (int)view.ReadDouble(rOff + 3 * 8);
|
||||
|
||||
(byte[] buffer, int w, int h) result;
|
||||
try { result = loadText(family, text, size, bold, italic, color); }
|
||||
catch { result = (new byte[4], 1, 1); }
|
||||
|
||||
int pixelSize = result.w * result.h * 4;
|
||||
long capacity = view.Capacity - _pixelOffset;
|
||||
if (pixelSize > capacity)
|
||||
{
|
||||
result = (new byte[4], 1, 1);
|
||||
pixelSize = 4;
|
||||
}
|
||||
|
||||
view.Write(NativeProtocol.OffLoadResultWidth, result.w);
|
||||
view.Write(NativeProtocol.OffLoadResultHeight, result.h);
|
||||
WritePixelRegion(result.buffer, pixelSize);
|
||||
view.Write(NativeProtocol.OffCallbackFound, 1);
|
||||
}
|
||||
|
||||
private void ResolveLoadImageCallback(
|
||||
MemoryMappedViewAccessor view,
|
||||
Func<string, (byte[] buffer, int w, int h)> loadImage)
|
||||
{
|
||||
int tagLen = Math.Clamp(view.ReadInt32(NativeProtocol.OffCallbackTagLen), 0, NativeProtocol.CallbackTagMax);
|
||||
view.ReadArray(NativeProtocol.CallbackTagOffset, _callbackTag, 0, tagLen);
|
||||
string path = Encoding.UTF8.GetString(_callbackTag, 0, tagLen);
|
||||
|
||||
(byte[] buffer, int w, int h) result;
|
||||
try { result = loadImage(path); }
|
||||
catch { result = (new byte[4], 1, 1); }
|
||||
|
||||
int pixelSize = result.w * result.h * 4;
|
||||
long capacity = view.Capacity - _pixelOffset;
|
||||
if (pixelSize > capacity)
|
||||
{
|
||||
result = (new byte[4], 1, 1);
|
||||
pixelSize = 4;
|
||||
}
|
||||
|
||||
view.Write(NativeProtocol.OffLoadResultWidth, result.w);
|
||||
view.Write(NativeProtocol.OffLoadResultHeight, result.h);
|
||||
WritePixelRegion(result.buffer, pixelSize);
|
||||
view.Write(NativeProtocol.OffCallbackFound, 1);
|
||||
}
|
||||
|
||||
private void ResolveLoadMovieCallback(
|
||||
MemoryMappedViewAccessor view,
|
||||
Func<string, double, (byte[] buffer, int w, int h)> loadMovie)
|
||||
{
|
||||
int tagLen = Math.Clamp(view.ReadInt32(NativeProtocol.OffCallbackTagLen), 0, NativeProtocol.CallbackTagMax);
|
||||
view.ReadArray(NativeProtocol.CallbackTagOffset, _callbackTag, 0, tagLen);
|
||||
string path = Encoding.UTF8.GetString(_callbackTag, 0, tagLen);
|
||||
double time = view.ReadDouble(NativeProtocol.CallbackResultOffset);
|
||||
|
||||
(byte[] buffer, int w, int h) result;
|
||||
try { result = loadMovie(path, time); }
|
||||
catch { result = (new byte[4], 1, 1); }
|
||||
|
||||
int pixelSize = result.w * result.h * 4;
|
||||
long capacity = view.Capacity - _pixelOffset;
|
||||
if (pixelSize > capacity)
|
||||
{
|
||||
result = (new byte[4], 1, 1);
|
||||
pixelSize = 4;
|
||||
}
|
||||
|
||||
view.Write(NativeProtocol.OffLoadResultWidth, result.w);
|
||||
view.Write(NativeProtocol.OffLoadResultHeight, result.h);
|
||||
WritePixelRegion(result.buffer, pixelSize);
|
||||
view.Write(NativeProtocol.OffCallbackFound, 1);
|
||||
}
|
||||
|
||||
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;
|
||||
|
||||
string effectName = segments[0];
|
||||
var arguments = new List<KeyValuePair<string, object>>();
|
||||
for (int i = 1; i + 1 < segments.Length; i += 2)
|
||||
{
|
||||
string key = segments[i];
|
||||
string raw = segments[i + 1];
|
||||
object value;
|
||||
if (raw.Length > 0 && raw[0] == 'n')
|
||||
value = double.TryParse(raw.AsSpan(1), System.Globalization.NumberStyles.Float, System.Globalization.CultureInfo.InvariantCulture, out var d) ? d : 0d;
|
||||
else if (raw.Length > 0 && raw[0] == 'b')
|
||||
value = raw.Length > 1 && raw[1] == '1';
|
||||
else if (raw.Length > 0 && raw[0] == 's')
|
||||
value = raw.Substring(1);
|
||||
else
|
||||
value = raw;
|
||||
arguments.Add(new KeyValuePair<string, object>(key, value));
|
||||
}
|
||||
|
||||
try { addEffect(effectName, arguments); }
|
||||
catch { }
|
||||
view.Write(NativeProtocol.OffCallbackFound, 1);
|
||||
}
|
||||
|
||||
private string ResolveTag(int tagLen)
|
||||
{
|
||||
if (tagLen == _lastCallbackTagLength &&
|
||||
@@ -157,20 +639,23 @@ namespace LuaScript.Engine
|
||||
return _lastCallbackTagText;
|
||||
}
|
||||
|
||||
private void EnsureWorker(int width, int height)
|
||||
private void EnsureWorker(int width, int height, int stringCapacity)
|
||||
{
|
||||
if (_alive && _process is { HasExited: false } && _width == width && _height == height)
|
||||
long required = NativeProtocol.PixelOffset(stringCapacity) + (long)width * height * 4;
|
||||
if (_alive && _process is { HasExited: false } && _stringParamsCapacity == stringCapacity && required <= _allocatedSize)
|
||||
return;
|
||||
|
||||
KillWorker();
|
||||
StartWorker(width, height);
|
||||
StartWorker(width, height, stringCapacity);
|
||||
}
|
||||
|
||||
private void StartWorker(int width, int height)
|
||||
private void StartWorker(int width, int height, int stringCapacity)
|
||||
{
|
||||
_width = width;
|
||||
_height = height;
|
||||
long size = NativeProtocol.BufferSize(width, height);
|
||||
_stringParamsCapacity = stringCapacity;
|
||||
_scriptWritten = false;
|
||||
_pixelOffset = NativeProtocol.PixelOffset(stringCapacity);
|
||||
long size = Math.Max(NativeProtocol.BufferSize(width, height, stringCapacity), _allocatedSize);
|
||||
_allocatedSize = size;
|
||||
|
||||
string suffix = Guid.NewGuid().ToString("N");
|
||||
string mapName = "LuaScriptMap_" + suffix;
|
||||
@@ -197,6 +682,7 @@ namespace LuaScript.Engine
|
||||
psi.ArgumentList.Add(workName);
|
||||
psi.ArgumentList.Add(doneName);
|
||||
psi.ArgumentList.Add(_shimScript);
|
||||
psi.ArgumentList.Add(stringCapacity.ToString());
|
||||
|
||||
_process = Process.Start(psi);
|
||||
if (_process is not null)
|
||||
|
||||
@@ -4,8 +4,6 @@ namespace LuaScript.Engine
|
||||
{
|
||||
internal static class NativeFieldMap
|
||||
{
|
||||
private const double Epsilon = 1e-10;
|
||||
|
||||
public static void ToFields(AviUtlScriptContext ctx, double[] f)
|
||||
{
|
||||
f[NativeProtocol.W] = ctx.ImageWidth;
|
||||
@@ -38,6 +36,10 @@ namespace LuaScript.Engine
|
||||
f[NativeProtocol.Track1] = ctx.Track1;
|
||||
f[NativeProtocol.Track2] = ctx.Track2;
|
||||
f[NativeProtocol.Track3] = ctx.Track3;
|
||||
f[NativeProtocol.Slider0] = ctx.Slider0;
|
||||
f[NativeProtocol.Slider1] = ctx.Slider1;
|
||||
f[NativeProtocol.Slider2] = ctx.Slider2;
|
||||
f[NativeProtocol.Slider3] = ctx.Slider3;
|
||||
f[NativeProtocol.Check0] = ctx.Check0 ? 1d : 0d;
|
||||
f[NativeProtocol.Check1] = ctx.Check1 ? 1d : 0d;
|
||||
f[NativeProtocol.Check2] = ctx.Check2 ? 1d : 0d;
|
||||
@@ -78,42 +80,24 @@ namespace LuaScript.Engine
|
||||
ctx.Oz = f[NativeProtocol.Oz];
|
||||
ctx.Alpha = f[NativeProtocol.Alpha];
|
||||
|
||||
double initialSx = ctx.Sx;
|
||||
double initialSy = ctx.Sy;
|
||||
double initialZoom = ctx.Zoom;
|
||||
double initialAspect = ctx.Aspect;
|
||||
ctx.ApplyWriteBack(
|
||||
f[NativeProtocol.Sx],
|
||||
f[NativeProtocol.Sy],
|
||||
f[NativeProtocol.Zoom],
|
||||
f[NativeProtocol.Aspect],
|
||||
f[NativeProtocol.Rx],
|
||||
f[NativeProtocol.Ry],
|
||||
f[NativeProtocol.Rz],
|
||||
f[NativeProtocol.Rxr],
|
||||
f[NativeProtocol.Ryr],
|
||||
f[NativeProtocol.Rzr]);
|
||||
|
||||
ctx.Sx = f[NativeProtocol.Sx];
|
||||
ctx.Sy = f[NativeProtocol.Sy];
|
||||
ctx.Zoom = f[NativeProtocol.Zoom];
|
||||
ctx.Aspect = f[NativeProtocol.Aspect];
|
||||
|
||||
bool sxsyChanged = Math.Abs(ctx.Sx - initialSx) > Epsilon || Math.Abs(ctx.Sy - initialSy) > Epsilon;
|
||||
bool zoomAspectChanged = Math.Abs(ctx.Zoom - initialZoom) > Epsilon || Math.Abs(ctx.Aspect - initialAspect) > Epsilon;
|
||||
|
||||
if (zoomAspectChanged && !sxsyChanged)
|
||||
ctx.DrawStateOverride = f[NativeProtocol.DrawState] switch
|
||||
{
|
||||
ctx.Sx = ctx.Zoom * (1.0 + ctx.Aspect);
|
||||
ctx.Sy = ctx.Zoom * (1.0 - ctx.Aspect);
|
||||
}
|
||||
|
||||
double initialRxr = ctx.RxRad;
|
||||
double rxrNew = f[NativeProtocol.Rxr];
|
||||
ctx.Rx = Math.Abs(rxrNew - initialRxr) > Epsilon
|
||||
? rxrNew * (180d / Math.PI)
|
||||
: f[NativeProtocol.Rx];
|
||||
|
||||
double initialRyr = ctx.RyRad;
|
||||
double ryrNew = f[NativeProtocol.Ryr];
|
||||
ctx.Ry = Math.Abs(ryrNew - initialRyr) > Epsilon
|
||||
? ryrNew * (180d / Math.PI)
|
||||
: f[NativeProtocol.Ry];
|
||||
|
||||
double initialRzr = ctx.RzRad;
|
||||
double rzrNew = f[NativeProtocol.Rzr];
|
||||
ctx.Rz = Math.Abs(rzrNew - initialRzr) > Epsilon
|
||||
? rzrNew * (180d / Math.PI)
|
||||
: f[NativeProtocol.Rz];
|
||||
1d => true,
|
||||
2d => false,
|
||||
_ => null,
|
||||
};
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -23,6 +23,11 @@ namespace LuaScript.Engine
|
||||
public const int OffCallbackFrame = 32;
|
||||
public const int OffCallbackTagLen = 36;
|
||||
public const int OffCallbackFound = 40;
|
||||
public const int OffCallbackKind = 44;
|
||||
public const int OffLoadResultWidth = 48;
|
||||
public const int OffLoadResultHeight = 52;
|
||||
public const int OffStringParamsLen = 56;
|
||||
public const int OffScriptVersion = 60;
|
||||
|
||||
public const int HeaderSize = 64;
|
||||
|
||||
@@ -36,10 +41,32 @@ namespace LuaScript.Engine
|
||||
public const int ErrorMax = 4 * 1024;
|
||||
|
||||
public const int CallbackTagOffset = ErrorOffset + ErrorMax;
|
||||
public const int CallbackTagMax = 256;
|
||||
public const int CallbackTagMax = 4096;
|
||||
public const int CallbackResultOffset = CallbackTagOffset + CallbackTagMax;
|
||||
public const int CallbackResultCount = 8;
|
||||
|
||||
public const int StringParamsOffset = CallbackResultOffset + CallbackResultCount * 8;
|
||||
public const int MinStringParamsCapacity = 64 * 1024;
|
||||
|
||||
public const int CbKindGetObject = 0;
|
||||
public const int CbKindLoadFigure = 1;
|
||||
public const int CbKindEffect = 2;
|
||||
public const int CbKindDraw = 3;
|
||||
public const int CbKindDrawPoly = 4;
|
||||
public const int CbKindLoadText = 5;
|
||||
public const int CbKindLoadImage = 6;
|
||||
public const int CbKindLoadMovie = 7;
|
||||
public const int CbKindSetAnchor = 8;
|
||||
public const int CbKindRequestPixels = 9;
|
||||
public const int CbKindFlushDraws = 10;
|
||||
public const int CbKindSceneGet = 11;
|
||||
public const int CbKindSceneSet = 12;
|
||||
|
||||
public const int DrawRingCapacity = 4096;
|
||||
public const int DrawEntryDoubles = 24;
|
||||
public const int DrawRingDoubles = 1 + DrawRingCapacity * DrawEntryDoubles;
|
||||
public const long DrawRingBytes = (long)DrawRingDoubles * 8;
|
||||
|
||||
public const int CbExist = 0;
|
||||
public const int CbX = 1;
|
||||
public const int CbY = 2;
|
||||
@@ -49,7 +76,9 @@ namespace LuaScript.Engine
|
||||
public const int CbAlpha = 6;
|
||||
public const int CbLayer = 7;
|
||||
|
||||
public const int PixelOffset = CallbackResultOffset + CallbackResultCount * 8;
|
||||
public static long DrawRingOffset(int stringCapacity) => StringParamsOffset + stringCapacity;
|
||||
|
||||
public static long PixelOffset(int stringCapacity) => DrawRingOffset(stringCapacity) + DrawRingBytes;
|
||||
|
||||
public const int W = 0;
|
||||
public const int H = 1;
|
||||
@@ -109,11 +138,18 @@ namespace LuaScript.Engine
|
||||
public const int Check2 = 55;
|
||||
public const int Check3 = 56;
|
||||
public const int Color = 57;
|
||||
public const int Slider0 = 58;
|
||||
public const int Slider1 = 59;
|
||||
public const int Slider2 = 60;
|
||||
public const int Slider3 = 61;
|
||||
public const int DrawState = 62;
|
||||
|
||||
public const int FirstWritableField = X;
|
||||
public const int LastWritableField = Rzr;
|
||||
|
||||
public static long BufferSize(int width, int height) =>
|
||||
PixelOffset + (long)width * height * 4;
|
||||
public const int MaxPixelBufferSize = 3840 * 2160 * 4;
|
||||
|
||||
public static long BufferSize(int width, int height, int stringCapacity) =>
|
||||
PixelOffset(stringCapacity) + Math.Max((long)width * height * 4, MaxPixelBufferSize);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,4 @@
|
||||
namespace LuaScript.Engine
|
||||
{
|
||||
internal delegate void PixelRegionAccess(nint address, long capacity);
|
||||
}
|
||||
@@ -0,0 +1,98 @@
|
||||
using System;
|
||||
|
||||
namespace LuaScript.Engine
|
||||
{
|
||||
internal static class ScriptDirective
|
||||
{
|
||||
public static ScriptEngineKind Resolve(string? script) =>
|
||||
TryGetDirective(script, out var kind) ? kind : ScriptEngineKind.MoonSharp;
|
||||
|
||||
public static ScriptEngineKind ResolveAuto(string? script)
|
||||
{
|
||||
if (string.IsNullOrEmpty(script))
|
||||
return ScriptEngineKind.MoonSharp;
|
||||
return TryGetDirective(script, out var kind) ? kind : ScriptEngineKind.Native;
|
||||
}
|
||||
|
||||
public static bool TryResolveExplicit(string? script, out ScriptEngineKind kind) =>
|
||||
TryGetDirective(script, out kind);
|
||||
|
||||
private static bool TryGetDirective(string? script, out ScriptEngineKind kind)
|
||||
{
|
||||
kind = ScriptEngineKind.MoonSharp;
|
||||
if (string.IsNullOrEmpty(script))
|
||||
return false;
|
||||
|
||||
int index = 0;
|
||||
int length = script.Length;
|
||||
while (index < length)
|
||||
{
|
||||
int lineStart = index;
|
||||
while (index < length && script[index] != '\n')
|
||||
index++;
|
||||
int lineEnd = index;
|
||||
if (lineEnd > lineStart && script[lineEnd - 1] == '\r')
|
||||
lineEnd--;
|
||||
|
||||
if (TryParseDirectiveLine(script, lineStart, lineEnd, out kind))
|
||||
return true;
|
||||
|
||||
index++;
|
||||
}
|
||||
|
||||
return false;
|
||||
}
|
||||
|
||||
private static bool TryParseDirectiveLine(string script, int start, int end, out ScriptEngineKind kind)
|
||||
{
|
||||
kind = ScriptEngineKind.MoonSharp;
|
||||
|
||||
int i = start;
|
||||
while (i < end && (script[i] == ' ' || script[i] == '\t'))
|
||||
i++;
|
||||
|
||||
if (i + 3 > end || script[i] != '-' || script[i + 1] != '-' || script[i + 2] != '!')
|
||||
return false;
|
||||
i += 3;
|
||||
|
||||
while (i < end && (script[i] == ' ' || script[i] == '\t'))
|
||||
i++;
|
||||
|
||||
int tokenStart = i;
|
||||
while (i < end && IsTokenChar(script[i]))
|
||||
i++;
|
||||
int tokenEnd = i;
|
||||
|
||||
while (i < end && (script[i] == ' ' || script[i] == '\t'))
|
||||
i++;
|
||||
if (i != end)
|
||||
return false;
|
||||
|
||||
var token = script.AsSpan(tokenStart, tokenEnd - tokenStart);
|
||||
if (token.Equals("native", StringComparison.OrdinalIgnoreCase))
|
||||
{
|
||||
kind = ScriptEngineKind.Native;
|
||||
return true;
|
||||
}
|
||||
if (token.Equals("gpu", StringComparison.OrdinalIgnoreCase))
|
||||
{
|
||||
kind = ScriptEngineKind.Gpu;
|
||||
return true;
|
||||
}
|
||||
if (token.Equals("cpu", StringComparison.OrdinalIgnoreCase))
|
||||
{
|
||||
kind = ScriptEngineKind.Cpu;
|
||||
return true;
|
||||
}
|
||||
if (token.Equals("moonsharp", StringComparison.OrdinalIgnoreCase))
|
||||
{
|
||||
kind = ScriptEngineKind.MoonSharp;
|
||||
return true;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
private static bool IsTokenChar(char c) =>
|
||||
(c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z');
|
||||
}
|
||||
}
|
||||
@@ -9,108 +9,4 @@ namespace LuaScript.Engine
|
||||
Gpu,
|
||||
Cpu,
|
||||
}
|
||||
|
||||
internal static class ScriptDirective
|
||||
{
|
||||
public static ScriptEngineKind Resolve(string? script) =>
|
||||
TryGetDirective(script, out var kind) ? kind : ScriptEngineKind.MoonSharp;
|
||||
|
||||
public static ScriptEngineKind ResolveAuto(string? script)
|
||||
{
|
||||
if (TryGetDirective(script, out var kind))
|
||||
return kind;
|
||||
if (UsesDrawingApi(script))
|
||||
return ScriptEngineKind.MoonSharp;
|
||||
return UsesPixelApi(script) ? ScriptEngineKind.Native : ScriptEngineKind.MoonSharp;
|
||||
}
|
||||
|
||||
public static bool UsesPixelApi(string? script) =>
|
||||
script is not null && (script.Contains("getpixel", StringComparison.Ordinal) || script.Contains("setpixel", StringComparison.Ordinal));
|
||||
|
||||
public static bool UsesDrawingApi(string? script) =>
|
||||
script is not null && (
|
||||
script.Contains("obj.load", StringComparison.Ordinal) ||
|
||||
script.Contains("obj.draw", StringComparison.Ordinal) ||
|
||||
script.Contains("obj.effect", StringComparison.Ordinal) ||
|
||||
script.Contains("obj.setoption", StringComparison.Ordinal) ||
|
||||
script.Contains("obj.copybuffer", StringComparison.Ordinal));
|
||||
|
||||
private static bool TryGetDirective(string? script, out ScriptEngineKind kind)
|
||||
{
|
||||
kind = ScriptEngineKind.MoonSharp;
|
||||
if (string.IsNullOrEmpty(script))
|
||||
return false;
|
||||
|
||||
int index = 0;
|
||||
int length = script.Length;
|
||||
while (index < length)
|
||||
{
|
||||
int lineStart = index;
|
||||
while (index < length && script[index] != '\n')
|
||||
index++;
|
||||
int lineEnd = index;
|
||||
if (lineEnd > lineStart && script[lineEnd - 1] == '\r')
|
||||
lineEnd--;
|
||||
|
||||
if (TryParseDirectiveLine(script, lineStart, lineEnd, out kind))
|
||||
return true;
|
||||
|
||||
index++;
|
||||
}
|
||||
|
||||
return false;
|
||||
}
|
||||
|
||||
private static bool TryParseDirectiveLine(string script, int start, int end, out ScriptEngineKind kind)
|
||||
{
|
||||
kind = ScriptEngineKind.MoonSharp;
|
||||
|
||||
int i = start;
|
||||
while (i < end && (script[i] == ' ' || script[i] == '\t'))
|
||||
i++;
|
||||
|
||||
if (i + 3 > end || script[i] != '-' || script[i + 1] != '-' || script[i + 2] != '!')
|
||||
return false;
|
||||
i += 3;
|
||||
|
||||
while (i < end && (script[i] == ' ' || script[i] == '\t'))
|
||||
i++;
|
||||
|
||||
int tokenStart = i;
|
||||
while (i < end && IsTokenChar(script[i]))
|
||||
i++;
|
||||
int tokenEnd = i;
|
||||
|
||||
while (i < end && (script[i] == ' ' || script[i] == '\t'))
|
||||
i++;
|
||||
if (i != end)
|
||||
return false;
|
||||
|
||||
var token = script.AsSpan(tokenStart, tokenEnd - tokenStart);
|
||||
if (token.Equals("native", StringComparison.OrdinalIgnoreCase))
|
||||
{
|
||||
kind = ScriptEngineKind.Native;
|
||||
return true;
|
||||
}
|
||||
if (token.Equals("gpu", StringComparison.OrdinalIgnoreCase))
|
||||
{
|
||||
kind = ScriptEngineKind.Gpu;
|
||||
return true;
|
||||
}
|
||||
if (token.Equals("cpu", StringComparison.OrdinalIgnoreCase))
|
||||
{
|
||||
kind = ScriptEngineKind.Cpu;
|
||||
return true;
|
||||
}
|
||||
if (token.Equals("moonsharp", StringComparison.OrdinalIgnoreCase))
|
||||
{
|
||||
kind = ScriptEngineKind.MoonSharp;
|
||||
return true;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
private static bool IsTokenChar(char c) =>
|
||||
(c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z');
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,38 @@
|
||||
using System;
|
||||
|
||||
namespace LuaScript
|
||||
{
|
||||
internal sealed class FallbackCompositor(
|
||||
IBufferCompositor primary,
|
||||
IBufferCompositor fallback,
|
||||
Action<Exception>? onDegraded = null) : IBufferCompositor, IDisposable
|
||||
{
|
||||
private bool _degraded;
|
||||
|
||||
public bool IsDegraded => _degraded;
|
||||
|
||||
public bool TryCompose(byte[] dst, int dstW, int dstH, byte[] src, int srcW, int srcH, in DrawCommand command)
|
||||
{
|
||||
if (!_degraded)
|
||||
{
|
||||
try
|
||||
{
|
||||
if (primary.TryCompose(dst, dstW, dstH, src, srcW, srcH, command))
|
||||
return true;
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
_degraded = true;
|
||||
onDegraded?.Invoke(ex);
|
||||
}
|
||||
}
|
||||
return fallback.TryCompose(dst, dstW, dstH, src, srcW, srcH, command);
|
||||
}
|
||||
|
||||
public void Dispose()
|
||||
{
|
||||
(primary as IDisposable)?.Dispose();
|
||||
(fallback as IDisposable)?.Dispose();
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,139 @@
|
||||
using System;
|
||||
using System.Numerics;
|
||||
using System.Runtime.InteropServices;
|
||||
using Vortice.DCommon;
|
||||
using Vortice.Direct2D1;
|
||||
using Vortice.DXGI;
|
||||
using Vortice.Mathematics;
|
||||
using YukkuriMovieMaker.Commons;
|
||||
|
||||
namespace LuaScript
|
||||
{
|
||||
internal sealed class HardwareCompositor : IBufferCompositor, IDisposable
|
||||
{
|
||||
private const int MaxDimension = 8192;
|
||||
|
||||
private readonly GraphicsDevicesAndContext _ctx;
|
||||
private ID2D1Bitmap1? _source;
|
||||
private ID2D1Bitmap1? _target;
|
||||
private ID2D1Bitmap1? _staging;
|
||||
private int _sourceWidth;
|
||||
private int _sourceHeight;
|
||||
private int _targetWidth;
|
||||
private int _targetHeight;
|
||||
|
||||
public HardwareCompositor(GraphicsDevicesAndContext ctx)
|
||||
{
|
||||
_ctx = ctx;
|
||||
}
|
||||
|
||||
public unsafe bool TryCompose(byte[] dst, int dstW, int dstH, byte[] src, int srcW, int srcH, in DrawCommand command)
|
||||
{
|
||||
if (srcW <= 0 || srcH <= 0 || dstW <= 0 || dstH <= 0)
|
||||
return true;
|
||||
if (srcW > MaxDimension || srcH > MaxDimension || dstW > MaxDimension || dstH > MaxDimension)
|
||||
return false;
|
||||
if (src.Length < srcW * srcH * 4 || dst.Length < dstW * dstH * 4)
|
||||
return false;
|
||||
if (!DrawTransform.TryResolve(command, srcW, srcH, out var transform))
|
||||
return true;
|
||||
|
||||
float opacity = (float)Math.Clamp(command.Alpha, 0d, 1d);
|
||||
if (opacity <= 0f)
|
||||
return true;
|
||||
|
||||
EnsureSource(srcW, srcH);
|
||||
EnsureTarget(dstW, dstH);
|
||||
|
||||
fixed (byte* ptr = src)
|
||||
_source!.CopyFromMemory(new nint(ptr), srcW * 4);
|
||||
fixed (byte* ptr = dst)
|
||||
_target!.CopyFromMemory(new nint(ptr), dstW * 4);
|
||||
|
||||
var interpolation = command.Antialias != 0d
|
||||
? BitmapInterpolationMode.Linear
|
||||
: BitmapInterpolationMode.NearestNeighbor;
|
||||
|
||||
var dc = _ctx.DeviceContext;
|
||||
var rt = (ID2D1RenderTarget)dc;
|
||||
using var savedTarget = dc.Target;
|
||||
dc.Target = _target;
|
||||
try
|
||||
{
|
||||
dc.BeginDraw();
|
||||
rt.Transform = transform;
|
||||
rt.DrawBitmap(_source!, opacity, interpolation);
|
||||
rt.Transform = Matrix3x2.Identity;
|
||||
dc.EndDraw();
|
||||
}
|
||||
finally
|
||||
{
|
||||
dc.Target = savedTarget;
|
||||
}
|
||||
|
||||
_staging!.CopyFromBitmap(_target!);
|
||||
var mapped = _staging.Map(MapOptions.Read);
|
||||
try
|
||||
{
|
||||
if (mapped.Pitch == dstW * 4)
|
||||
{
|
||||
Marshal.Copy(mapped.Bits, dst, 0, dstW * dstH * 4);
|
||||
}
|
||||
else
|
||||
{
|
||||
for (int row = 0; row < dstH; row++)
|
||||
Marshal.Copy(mapped.Bits + mapped.Pitch * row, dst, row * dstW * 4, dstW * 4);
|
||||
}
|
||||
}
|
||||
finally
|
||||
{
|
||||
_staging.Unmap();
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
private void EnsureSource(int width, int height)
|
||||
{
|
||||
if (_source is not null && _sourceWidth == width && _sourceHeight == height)
|
||||
return;
|
||||
|
||||
_source?.Dispose();
|
||||
_source = _ctx.DeviceContext.CreateEmptyBitmap(width, height, BitmapOptions.Target);
|
||||
_sourceWidth = width;
|
||||
_sourceHeight = height;
|
||||
}
|
||||
|
||||
private void EnsureTarget(int width, int height)
|
||||
{
|
||||
if (_target is not null && _targetWidth == width && _targetHeight == height)
|
||||
return;
|
||||
|
||||
_target?.Dispose();
|
||||
_staging?.Dispose();
|
||||
_target = null;
|
||||
_staging = null;
|
||||
|
||||
var dc = _ctx.DeviceContext;
|
||||
_target = dc.CreateEmptyBitmap(width, height, BitmapOptions.Target);
|
||||
|
||||
var stagingProps = new BitmapProperties1(
|
||||
new PixelFormat(Format.B8G8R8A8_UNorm, Vortice.DCommon.AlphaMode.Premultiplied),
|
||||
96f, 96f,
|
||||
BitmapOptions.CpuRead | BitmapOptions.CannotDraw);
|
||||
_staging = dc.CreateBitmap(new SizeI(width, height), nint.Zero, width * 4, stagingProps);
|
||||
|
||||
_targetWidth = width;
|
||||
_targetHeight = height;
|
||||
}
|
||||
|
||||
public void Dispose()
|
||||
{
|
||||
_source?.Dispose();
|
||||
_target?.Dispose();
|
||||
_staging?.Dispose();
|
||||
_source = null;
|
||||
_target = null;
|
||||
_staging = null;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,7 @@
|
||||
namespace LuaScript
|
||||
{
|
||||
internal interface IBufferCompositor
|
||||
{
|
||||
bool TryCompose(byte[] dst, int dstW, int dstH, byte[] src, int srcW, int srcH, in DrawCommand command);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,97 @@
|
||||
using System;
|
||||
using System.IO;
|
||||
using Vortice.Mathematics;
|
||||
using Vortice.WIC;
|
||||
|
||||
namespace LuaScript
|
||||
{
|
||||
internal sealed class ImageDecoder : IDisposable
|
||||
{
|
||||
private const int MaxDimension = 8192;
|
||||
|
||||
private IWICImagingFactory? _factory;
|
||||
|
||||
public unsafe byte[] Decode(string path, out int width, out int height)
|
||||
{
|
||||
width = 1;
|
||||
height = 1;
|
||||
if (string.IsNullOrEmpty(path) || !IsSupportedImage(path))
|
||||
return new byte[4];
|
||||
|
||||
try
|
||||
{
|
||||
_factory ??= new IWICImagingFactory();
|
||||
using var stream = _factory.CreateStream(path, FileAccess.Read);
|
||||
using var decoder = _factory.CreateDecoderFromStream(stream, DecodeOptions.CacheOnDemand);
|
||||
using var frame = decoder.GetFrame(0);
|
||||
using var converter = _factory.CreateFormatConverter();
|
||||
converter.Initialize(
|
||||
frame,
|
||||
Vortice.WIC.PixelFormat.Format32bppPBGRA,
|
||||
BitmapDitherType.None,
|
||||
null,
|
||||
0d,
|
||||
BitmapPaletteType.Custom);
|
||||
|
||||
converter.GetSize(out int w, out int h);
|
||||
if (w <= 0 || h <= 0 || w > MaxDimension || h > MaxDimension)
|
||||
return new byte[4];
|
||||
|
||||
var buffer = new byte[w * h * 4];
|
||||
fixed (byte* p = buffer)
|
||||
converter.CopyPixels(new RectI(0, 0, w, h), w * 4, buffer.Length, (nint)p);
|
||||
|
||||
width = w;
|
||||
height = h;
|
||||
return buffer;
|
||||
}
|
||||
catch
|
||||
{
|
||||
width = 1;
|
||||
height = 1;
|
||||
return new byte[4];
|
||||
}
|
||||
}
|
||||
|
||||
private static bool IsSupportedImage(string path)
|
||||
{
|
||||
try
|
||||
{
|
||||
if (!File.Exists(path))
|
||||
return false;
|
||||
Span<byte> head = stackalloc byte[12];
|
||||
using var stream = File.OpenRead(path);
|
||||
int read = stream.Read(head);
|
||||
if (read < 4)
|
||||
return false;
|
||||
|
||||
if (head[0] == 0x89 && head[1] == 0x50 && head[2] == 0x4E && head[3] == 0x47)
|
||||
return true;
|
||||
if (head[0] == 0xFF && head[1] == 0xD8 && head[2] == 0xFF)
|
||||
return true;
|
||||
if (head[0] == 0x47 && head[1] == 0x49 && head[2] == 0x46 && head[3] == 0x38)
|
||||
return true;
|
||||
if (head[0] == 0x42 && head[1] == 0x4D)
|
||||
return true;
|
||||
if ((head[0] == 0x49 && head[1] == 0x49 && head[2] == 0x2A && head[3] == 0x00) ||
|
||||
(head[0] == 0x4D && head[1] == 0x4D && head[2] == 0x00 && head[3] == 0x2A))
|
||||
return true;
|
||||
if (read >= 12 &&
|
||||
head[0] == 0x52 && head[1] == 0x49 && head[2] == 0x46 && head[3] == 0x46 &&
|
||||
head[8] == 0x57 && head[9] == 0x45 && head[10] == 0x42 && head[11] == 0x50)
|
||||
return true;
|
||||
return false;
|
||||
}
|
||||
catch
|
||||
{
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
public void Dispose()
|
||||
{
|
||||
_factory?.Dispose();
|
||||
_factory = null;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -17,10 +17,11 @@ namespace LuaScript
|
||||
private static readonly string[] s_globals =
|
||||
[
|
||||
"time", "frame", "totalframe", "framerate",
|
||||
"timelineframe", "timelinetime", "layer",
|
||||
"timelineframe", "timelinetime", "layer", "color",
|
||||
"obj", "scene", "anim", "ymm4",
|
||||
"math", "string", "table", "bit32",
|
||||
"type", "tostring", "tonumber", "select", "error", "assert", "print",
|
||||
"debug_print", "RGB", "HSV", "OR", "AND", "XOR", "SHIFT",
|
||||
"ipairs", "pairs", "next",
|
||||
"unpack",
|
||||
"setmetatable", "getmetatable", "rawget", "rawset", "rawequal", "rawlen",
|
||||
@@ -39,6 +40,11 @@ namespace LuaScript
|
||||
"obj.rx", "obj.ry", "obj.rz",
|
||||
"obj.rxr", "obj.ryr", "obj.rzr",
|
||||
"obj.track0", "obj.track1", "obj.track2", "obj.track3",
|
||||
"obj.slider0", "obj.slider1", "obj.slider2", "obj.slider3",
|
||||
"obj.check0", "obj.check1", "obj.check2", "obj.check3",
|
||||
"obj.text", "obj.font", "obj.dir",
|
||||
"obj.file_video", "obj.file_audio", "obj.file_image", "obj.file_project",
|
||||
"obj.file_mp4", "obj.file_exo", "obj.file_subtitle", "obj.file_shader",
|
||||
"obj.time", "obj.totaltime", "obj.t", "obj.frame", "obj.totalframe",
|
||||
"obj.framerate", "obj.layer", "obj.index", "obj.num",
|
||||
"obj.getpixel", "obj.setpixel",
|
||||
@@ -71,7 +77,8 @@ namespace LuaScript
|
||||
"bit32.btest", "bit32.countlz", "bit32.countrz"
|
||||
]),
|
||||
("scene", [
|
||||
"scene.width", "scene.height", "scene.cx", "scene.cy"
|
||||
"scene.width", "scene.height", "scene.cx", "scene.cy",
|
||||
"scene.set", "scene.get"
|
||||
]),
|
||||
("anim", [
|
||||
"anim.tau", "anim.e", "anim.phi", "anim.sqrt2",
|
||||
|
||||
@@ -2,6 +2,7 @@ using System.Collections.Generic;
|
||||
using System.Text.RegularExpressions;
|
||||
using ICSharpCode.AvalonEdit.Document;
|
||||
using ICSharpCode.AvalonEdit.Folding;
|
||||
using LuaScript.Diagnostics;
|
||||
using YukkuriMovieMaker.Controls.AvalonEdit.FoldingStrategy;
|
||||
|
||||
namespace LuaScript
|
||||
@@ -25,6 +26,7 @@ namespace LuaScript
|
||||
public void UpdateFoldings(FoldingManager manager, TextDocument document)
|
||||
{
|
||||
manager.UpdateFoldings(CreateNewFoldings(document, out int firstErrorOffset), firstErrorOffset);
|
||||
LuaScriptDiagnosticOverlay.Attach(manager);
|
||||
}
|
||||
|
||||
private static IEnumerable<NewFolding> CreateNewFoldings(TextDocument document, out int firstErrorOffset)
|
||||
|
||||
@@ -4,7 +4,7 @@
|
||||
<TargetFramework>net10.0-windows10.0.19041.0</TargetFramework>
|
||||
<UseWPF>true</UseWPF>
|
||||
<ImplicitUsings>enable</ImplicitUsings>
|
||||
<Version>1.6.0</Version>
|
||||
<Version>1.13.0</Version>
|
||||
<Platforms>AnyCPU;x64</Platforms>
|
||||
<Nullable>enable</Nullable>
|
||||
<AllowUnsafeBlocks>true</AllowUnsafeBlocks>
|
||||
@@ -67,6 +67,10 @@
|
||||
<HintPath>$(YMM4DirPath)Vortice.Mathematics.dll</HintPath>
|
||||
<Private>false</Private>
|
||||
</Reference>
|
||||
<Reference Include="Vortice.MediaFoundation">
|
||||
<HintPath>$(YMM4DirPath)Vortice.MediaFoundation.dll</HintPath>
|
||||
<Private>false</Private>
|
||||
</Reference>
|
||||
<Reference Include="YukkuriMovieMaker">
|
||||
<HintPath>$(YMM4DirPath)YukkuriMovieMaker.dll</HintPath>
|
||||
<Private>false</Private>
|
||||
@@ -90,6 +94,10 @@
|
||||
<AdditionalFiles Include="**/*.csv" />
|
||||
</ItemGroup>
|
||||
|
||||
<ItemGroup>
|
||||
<EmbeddedResource Include="Compat\AviUtlCompatMap.xml" />
|
||||
</ItemGroup>
|
||||
|
||||
<ItemGroup>
|
||||
<PackageReference Include="MoonSharp" Version="2.0.0" />
|
||||
</ItemGroup>
|
||||
|
||||
@@ -0,0 +1,6 @@
|
||||
using System;
|
||||
|
||||
namespace LuaScript
|
||||
{
|
||||
internal sealed class LuaScriptCompilationException(string message, Exception? inner = null) : LuaScriptException(message, inner);
|
||||
}
|
||||
+162
-5
@@ -1,6 +1,9 @@
|
||||
using System.Collections.Generic;
|
||||
using System.Collections.Immutable;
|
||||
using System.ComponentModel;
|
||||
using System.ComponentModel.DataAnnotations;
|
||||
using System.Windows.Media;
|
||||
using LuaScript.Anchor;
|
||||
using LuaScript.Compat;
|
||||
using Newtonsoft.Json;
|
||||
using YukkuriMovieMaker.Commons;
|
||||
@@ -10,6 +13,7 @@ using YukkuriMovieMaker.ItemEditor.CustomVisibilityAttributes;
|
||||
using YukkuriMovieMaker.Player.Video;
|
||||
using YukkuriMovieMaker.Plugin;
|
||||
using YukkuriMovieMaker.Plugin.Effects;
|
||||
using YukkuriMovieMaker.Settings;
|
||||
|
||||
namespace LuaScript
|
||||
{
|
||||
@@ -62,6 +66,34 @@ namespace LuaScript
|
||||
[ShowPropertyEditorWhen(nameof(IsTrack3Visible), true)]
|
||||
public Animation Track3 { get; } = new Animation(0, YMM4Constants.VerySmallValue, YMM4Constants.VeryLargeValue);
|
||||
|
||||
[Display(GroupName = nameof(Texts.ParametersGroup), Name = nameof(Texts.Slider0), Description = nameof(Texts.SliderDesc), ResourceType = typeof(Texts))]
|
||||
[TextBoxSlider("F0", "", 1, 10)]
|
||||
[DefaultValue(1)]
|
||||
[ShowPropertyEditorWhen(nameof(IsSlider0Visible), true)]
|
||||
public int Slider0 { get => _slider0; set => Set(ref _slider0, value); }
|
||||
int _slider0 = 1;
|
||||
|
||||
[Display(GroupName = nameof(Texts.ParametersGroup), Name = nameof(Texts.Slider1), Description = nameof(Texts.SliderDesc), ResourceType = typeof(Texts))]
|
||||
[TextBoxSlider("F0", "", 0, 100)]
|
||||
[DefaultValue(0)]
|
||||
[ShowPropertyEditorWhen(nameof(IsSlider1Visible), true)]
|
||||
public int Slider1 { get => _slider1; set => Set(ref _slider1, value); }
|
||||
int _slider1;
|
||||
|
||||
[Display(GroupName = nameof(Texts.ParametersGroup), Name = nameof(Texts.Slider2), Description = nameof(Texts.SliderDesc), ResourceType = typeof(Texts))]
|
||||
[TextBoxSlider("F0", "", 0, 1000)]
|
||||
[DefaultValue(0)]
|
||||
[ShowPropertyEditorWhen(nameof(IsSlider2Visible), true)]
|
||||
public int Slider2 { get => _slider2; set => Set(ref _slider2, value); }
|
||||
int _slider2;
|
||||
|
||||
[Display(GroupName = nameof(Texts.ParametersGroup), Name = nameof(Texts.Slider3), Description = nameof(Texts.SliderDesc), ResourceType = typeof(Texts))]
|
||||
[TextBoxSlider("F0", "", -1000, 1000)]
|
||||
[DefaultValue(0)]
|
||||
[ShowPropertyEditorWhen(nameof(IsSlider3Visible), true)]
|
||||
public int Slider3 { get => _slider3; set => Set(ref _slider3, value); }
|
||||
int _slider3;
|
||||
|
||||
[Display(GroupName = nameof(Texts.ParametersGroup), Name = nameof(Texts.Check0), Description = nameof(Texts.CheckDesc), ResourceType = typeof(Texts))]
|
||||
[ToggleSlider]
|
||||
[ShowPropertyEditorWhen(nameof(IsCheck0Visible), true)]
|
||||
@@ -92,6 +124,76 @@ namespace LuaScript
|
||||
public Color Color { get => _color; set => Set(ref _color, value); }
|
||||
Color _color = Colors.White;
|
||||
|
||||
[Display(GroupName = nameof(Texts.ParametersGroup), Name = nameof(Texts.Text), Description = nameof(Texts.TextDesc), ResourceType = typeof(Texts))]
|
||||
[TextEditor(AcceptsReturn = true, PropertyEditorSize = PropertyEditorSize.FullWidth)]
|
||||
[ShowPropertyEditorWhen(nameof(IsTextVisible), true)]
|
||||
public string Text { get => _text; set => Set(ref _text, value); }
|
||||
string _text = string.Empty;
|
||||
|
||||
[Display(GroupName = nameof(Texts.ParametersGroup), Name = nameof(Texts.Font), Description = nameof(Texts.FontDesc), ResourceType = typeof(Texts))]
|
||||
[FontComboBox]
|
||||
[ShowPropertyEditorWhen(nameof(IsFontVisible), true)]
|
||||
public string Font { get => _font; set => Set(ref _font, value); }
|
||||
string _font = "メイリオ";
|
||||
|
||||
[Display(GroupName = nameof(Texts.ParametersGroup), Name = nameof(Texts.Directory), Description = nameof(Texts.DirectoryDesc), ResourceType = typeof(Texts))]
|
||||
[DirectorySelector(PropertyEditorSize = PropertyEditorSize.FullWidth)]
|
||||
[ShowPropertyEditorWhen(nameof(IsDirectoryVisible), true)]
|
||||
public string Directory { get => _directory; set => Set(ref _directory, value); }
|
||||
string _directory = string.Empty;
|
||||
|
||||
[Display(GroupName = nameof(Texts.ParametersGroup), Name = nameof(Texts.FileVideo), Description = nameof(Texts.FileDesc), ResourceType = typeof(Texts))]
|
||||
[FileSelector(FileGroupType.VideoItem)]
|
||||
[ShowPropertyEditorWhen(nameof(IsFileVideoVisible), true)]
|
||||
public string FileVideo { get => _fileVideo; set => Set(ref _fileVideo, value); }
|
||||
string _fileVideo = string.Empty;
|
||||
|
||||
[Display(GroupName = nameof(Texts.ParametersGroup), Name = nameof(Texts.FileAudio), Description = nameof(Texts.FileDesc), ResourceType = typeof(Texts))]
|
||||
[FileSelector(FileGroupType.AudioItem)]
|
||||
[ShowPropertyEditorWhen(nameof(IsFileAudioVisible), true)]
|
||||
public string FileAudio { get => _fileAudio; set => Set(ref _fileAudio, value); }
|
||||
string _fileAudio = string.Empty;
|
||||
|
||||
[Display(GroupName = nameof(Texts.ParametersGroup), Name = nameof(Texts.FileImage), Description = nameof(Texts.FileDesc), ResourceType = typeof(Texts))]
|
||||
[FileSelector(FileGroupType.ImageItem)]
|
||||
[ShowPropertyEditorWhen(nameof(IsFileImageVisible), true)]
|
||||
public string FileImage { get => _fileImage; set => Set(ref _fileImage, value); }
|
||||
string _fileImage = string.Empty;
|
||||
|
||||
[Display(GroupName = nameof(Texts.ParametersGroup), Name = nameof(Texts.FileProject), Description = nameof(Texts.FileDesc), ResourceType = typeof(Texts))]
|
||||
[FileSelector(FileGroupType.Project)]
|
||||
[ShowPropertyEditorWhen(nameof(IsFileProjectVisible), true)]
|
||||
public string FileProject { get => _fileProject; set => Set(ref _fileProject, value); }
|
||||
string _fileProject = string.Empty;
|
||||
|
||||
[Display(GroupName = nameof(Texts.ParametersGroup), Name = nameof(Texts.FileMp4), Description = nameof(Texts.FileDesc), ResourceType = typeof(Texts))]
|
||||
[FileSelector(FileGroupType.MP4)]
|
||||
[ShowPropertyEditorWhen(nameof(IsFileMp4Visible), true)]
|
||||
public string FileMp4 { get => _fileMp4; set => Set(ref _fileMp4, value); }
|
||||
string _fileMp4 = string.Empty;
|
||||
|
||||
[Display(GroupName = nameof(Texts.ParametersGroup), Name = nameof(Texts.FileExo), Description = nameof(Texts.FileDesc), ResourceType = typeof(Texts))]
|
||||
[FileSelector(FileGroupType.Exo)]
|
||||
[ShowPropertyEditorWhen(nameof(IsFileExoVisible), true)]
|
||||
public string FileExo { get => _fileExo; set => Set(ref _fileExo, value); }
|
||||
string _fileExo = string.Empty;
|
||||
|
||||
[Display(GroupName = nameof(Texts.ParametersGroup), Name = nameof(Texts.FileSubtitle), Description = nameof(Texts.FileDesc), ResourceType = typeof(Texts))]
|
||||
[FileSelector(FileGroupType.Subtitle)]
|
||||
[ShowPropertyEditorWhen(nameof(IsFileSubtitleVisible), true)]
|
||||
public string FileSubtitle { get => _fileSubtitle; set => Set(ref _fileSubtitle, value); }
|
||||
string _fileSubtitle = string.Empty;
|
||||
|
||||
[Display(GroupName = nameof(Texts.ParametersGroup), Name = nameof(Texts.FileShader), Description = nameof(Texts.FileDesc), ResourceType = typeof(Texts))]
|
||||
[FileSelector(FileGroupType.PixelShaderSource)]
|
||||
[ShowPropertyEditorWhen(nameof(IsFileShaderVisible), true)]
|
||||
public string FileShader { get => _fileShader; set => Set(ref _fileShader, value); }
|
||||
string _fileShader = string.Empty;
|
||||
|
||||
[JsonIgnore] public bool IsSlider0Visible { get => _isSlider0Visible; private set => Set(ref _isSlider0Visible, value); }
|
||||
[JsonIgnore] public bool IsSlider1Visible { get => _isSlider1Visible; private set => Set(ref _isSlider1Visible, value); }
|
||||
[JsonIgnore] public bool IsSlider2Visible { get => _isSlider2Visible; private set => Set(ref _isSlider2Visible, value); }
|
||||
[JsonIgnore] public bool IsSlider3Visible { get => _isSlider3Visible; private set => Set(ref _isSlider3Visible, value); }
|
||||
[JsonIgnore] public bool IsTrack0Visible { get => _isTrack0Visible; private set => Set(ref _isTrack0Visible, value); }
|
||||
[JsonIgnore] public bool IsTrack1Visible { get => _isTrack1Visible; private set => Set(ref _isTrack1Visible, value); }
|
||||
[JsonIgnore] public bool IsTrack2Visible { get => _isTrack2Visible; private set => Set(ref _isTrack2Visible, value); }
|
||||
@@ -101,7 +203,22 @@ namespace LuaScript
|
||||
[JsonIgnore] public bool IsCheck2Visible { get => _isCheck2Visible; private set => Set(ref _isCheck2Visible, value); }
|
||||
[JsonIgnore] public bool IsCheck3Visible { get => _isCheck3Visible; private set => Set(ref _isCheck3Visible, value); }
|
||||
[JsonIgnore] public bool IsColorVisible { get => _isColorVisible; private set => Set(ref _isColorVisible, value); }
|
||||
[JsonIgnore] public bool IsTextVisible { get => _isTextVisible; private set => Set(ref _isTextVisible, value); }
|
||||
[JsonIgnore] public bool IsFontVisible { get => _isFontVisible; private set => Set(ref _isFontVisible, value); }
|
||||
[JsonIgnore] public bool IsDirectoryVisible { get => _isDirectoryVisible; private set => Set(ref _isDirectoryVisible, value); }
|
||||
[JsonIgnore] public bool IsFileVideoVisible { get => _isFileVideoVisible; private set => Set(ref _isFileVideoVisible, value); }
|
||||
[JsonIgnore] public bool IsFileAudioVisible { get => _isFileAudioVisible; private set => Set(ref _isFileAudioVisible, value); }
|
||||
[JsonIgnore] public bool IsFileImageVisible { get => _isFileImageVisible; private set => Set(ref _isFileImageVisible, value); }
|
||||
[JsonIgnore] public bool IsFileProjectVisible { get => _isFileProjectVisible; private set => Set(ref _isFileProjectVisible, value); }
|
||||
[JsonIgnore] public bool IsFileMp4Visible { get => _isFileMp4Visible; private set => Set(ref _isFileMp4Visible, value); }
|
||||
[JsonIgnore] public bool IsFileExoVisible { get => _isFileExoVisible; private set => Set(ref _isFileExoVisible, value); }
|
||||
[JsonIgnore] public bool IsFileSubtitleVisible { get => _isFileSubtitleVisible; private set => Set(ref _isFileSubtitleVisible, value); }
|
||||
[JsonIgnore] public bool IsFileShaderVisible { get => _isFileShaderVisible; private set => Set(ref _isFileShaderVisible, value); }
|
||||
|
||||
bool _isSlider0Visible;
|
||||
bool _isSlider1Visible;
|
||||
bool _isSlider2Visible;
|
||||
bool _isSlider3Visible;
|
||||
bool _isTrack0Visible = true;
|
||||
bool _isTrack1Visible = true;
|
||||
bool _isTrack2Visible = true;
|
||||
@@ -111,6 +228,17 @@ namespace LuaScript
|
||||
bool _isCheck2Visible;
|
||||
bool _isCheck3Visible;
|
||||
bool _isColorVisible;
|
||||
bool _isTextVisible;
|
||||
bool _isFontVisible;
|
||||
bool _isDirectoryVisible;
|
||||
bool _isFileVideoVisible;
|
||||
bool _isFileAudioVisible;
|
||||
bool _isFileImageVisible;
|
||||
bool _isFileProjectVisible;
|
||||
bool _isFileMp4Visible;
|
||||
bool _isFileExoVisible;
|
||||
bool _isFileSubtitleVisible;
|
||||
bool _isFileShaderVisible;
|
||||
|
||||
private void UpdateLayout()
|
||||
{
|
||||
@@ -118,16 +246,32 @@ namespace LuaScript
|
||||
Layout = layout;
|
||||
|
||||
bool hasAny = layout.HasAny;
|
||||
var usage = ScriptParameterUsage.Detect(_script);
|
||||
|
||||
IsSlider0Visible = usage.Slider(0);
|
||||
IsSlider1Visible = usage.Slider(1);
|
||||
IsSlider2Visible = usage.Slider(2);
|
||||
IsSlider3Visible = usage.Slider(3);
|
||||
IsTrack0Visible = !hasAny || layout.HasTrack(0);
|
||||
IsTrack1Visible = !hasAny || layout.HasTrack(1);
|
||||
IsTrack2Visible = !hasAny || layout.HasTrack(2);
|
||||
IsTrack3Visible = !hasAny || layout.HasTrack(3);
|
||||
IsCheck0Visible = layout.HasCheck(0);
|
||||
IsCheck1Visible = layout.HasCheck(1);
|
||||
IsCheck2Visible = layout.HasCheck(2);
|
||||
IsCheck3Visible = layout.HasCheck(3);
|
||||
IsColorVisible = layout.HasColor;
|
||||
IsCheck0Visible = layout.HasCheck(0) || (!hasAny && usage.Check0);
|
||||
IsCheck1Visible = layout.HasCheck(1) || (!hasAny && usage.Check1);
|
||||
IsCheck2Visible = layout.HasCheck(2) || (!hasAny && usage.Check2);
|
||||
IsCheck3Visible = layout.HasCheck(3) || (!hasAny && usage.Check3);
|
||||
IsColorVisible = layout.HasColor || (!hasAny && usage.Color);
|
||||
IsTextVisible = usage.Uses("text");
|
||||
IsFontVisible = usage.Uses("font");
|
||||
IsDirectoryVisible = usage.Uses("dir");
|
||||
IsFileVideoVisible = usage.Uses("file_video");
|
||||
IsFileAudioVisible = usage.Uses("file_audio");
|
||||
IsFileImageVisible = usage.Uses("file_image");
|
||||
IsFileProjectVisible = usage.Uses("file_project");
|
||||
IsFileMp4Visible = usage.Uses("file_mp4");
|
||||
IsFileExoVisible = usage.Uses("file_exo");
|
||||
IsFileSubtitleVisible = usage.Uses("file_subtitle");
|
||||
IsFileShaderVisible = usage.Uses("file_shader");
|
||||
|
||||
SeedDefaults(layout);
|
||||
}
|
||||
@@ -151,6 +295,19 @@ namespace LuaScript
|
||||
return Color.FromRgb(r, g, b);
|
||||
}
|
||||
|
||||
public ImmutableList<LuaAnchorPoint> Anchors
|
||||
{
|
||||
get => _anchors;
|
||||
set { if (Set(ref _anchors, value ?? ImmutableList<LuaAnchorPoint>.Empty)) AnchorVersion++; }
|
||||
}
|
||||
ImmutableList<LuaAnchorPoint> _anchors = ImmutableList<LuaAnchorPoint>.Empty;
|
||||
|
||||
[JsonIgnore]
|
||||
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);
|
||||
|
||||
public override IEnumerable<string> CreateExoVideoFilters(int keyFrameIndex, ExoOutputDescription exoOutputDescription) => [];
|
||||
|
||||
public override IVideoEffectProcessor CreateVideoEffect(IGraphicsDevicesAndContext devices)
|
||||
|
||||
+644
-137
ファイル差分が大きすぎるため表示されません。
差分を読み込み
+333
-42
@@ -1,3 +1,4 @@
|
||||
using LuaScript.Anchor;
|
||||
using LuaScript.Compat;
|
||||
using MoonSharp.Interpreter;
|
||||
using MoonSharp.Interpreter.Debugging;
|
||||
@@ -53,6 +54,18 @@ namespace LuaScript
|
||||
|
||||
private readonly List<string> _removalBuffer = [];
|
||||
|
||||
private readonly Dictionary<string, DynValue> _options = new(StringComparer.Ordinal);
|
||||
private readonly Dictionary<string, DynValue> _pixelOptions = new(StringComparer.Ordinal);
|
||||
|
||||
private TextRenderer? _textRenderer;
|
||||
private ImageDecoder? _imageDecoder;
|
||||
private MovieDecoder? _movieDecoder;
|
||||
private string _fontFamily = string.Empty;
|
||||
private double _fontSize = 34d;
|
||||
private bool _fontBold;
|
||||
private bool _fontItalic;
|
||||
private int _fontColor = 0xFFFFFF;
|
||||
|
||||
private Script? _script;
|
||||
private DynValue? _compiledChunk;
|
||||
private string _lastCompiledCode = string.Empty;
|
||||
@@ -158,6 +171,7 @@ namespace LuaScript
|
||||
CoreModules.ErrorHandling);
|
||||
script.Options.ScriptLoader = new DisabledFileScriptLoader();
|
||||
script.AttachDebugger(_debugger);
|
||||
AviUtlGlobalRegistrar.RegisterFunctions(script.Globals, CurrentTimeRatio);
|
||||
_script = script;
|
||||
}
|
||||
|
||||
@@ -203,9 +217,18 @@ namespace LuaScript
|
||||
var script = _script!;
|
||||
bool isFirstSetup = _objTable is null;
|
||||
|
||||
_options.Clear();
|
||||
_pixelOptions.Clear();
|
||||
_fontFamily = string.Empty;
|
||||
_fontSize = 34d;
|
||||
_fontBold = false;
|
||||
_fontItalic = false;
|
||||
_fontColor = 0xFFFFFF;
|
||||
|
||||
if (isFirstSetup)
|
||||
{
|
||||
var sceneTable = new Table(script);
|
||||
RegisterSceneCallbacks(sceneTable);
|
||||
script.Globals["scene"] = sceneTable;
|
||||
|
||||
var objTable = new Table(script);
|
||||
@@ -231,6 +254,7 @@ namespace LuaScript
|
||||
if (!ReferenceEquals(script.Globals.Get("scene").Table, _sceneTable))
|
||||
{
|
||||
var sceneTable = new Table(script);
|
||||
RegisterSceneCallbacks(sceneTable);
|
||||
script.Globals["scene"] = sceneTable;
|
||||
_sceneTable = sceneTable;
|
||||
_sceneTableSnapshot = null;
|
||||
@@ -313,6 +337,12 @@ namespace LuaScript
|
||||
_objTable!["track1"] = ctx.Track1;
|
||||
_objTable!["track2"] = ctx.Track2;
|
||||
_objTable!["track3"] = ctx.Track3;
|
||||
_objTable!["slider0"] = ctx.Slider0;
|
||||
_objTable!["slider1"] = ctx.Slider1;
|
||||
_objTable!["slider2"] = ctx.Slider2;
|
||||
_objTable!["slider3"] = ctx.Slider3;
|
||||
foreach (var parameter in ctx.StringParameters)
|
||||
_objTable![parameter.Key] = parameter.Value;
|
||||
_objTable!["check0"] = ctx.Check0;
|
||||
_objTable!["check1"] = ctx.Check1;
|
||||
_objTable!["check2"] = ctx.Check2;
|
||||
@@ -398,6 +428,24 @@ namespace LuaScript
|
||||
script.Globals[key] = DynValue.Nil;
|
||||
}
|
||||
|
||||
private double CurrentTimeRatio() =>
|
||||
_activeContext is { TotalTime: > 0d } context ? context.Time / context.TotalTime : 0d;
|
||||
|
||||
private void RegisterSceneCallbacks(Table scene) =>
|
||||
SceneTableRegistrar.RegisterFunctions(scene, GetSceneValue, SetSceneValue);
|
||||
|
||||
private SceneValue GetSceneValue(string name)
|
||||
{
|
||||
_activeCancellation.ThrowIfCancellationRequested();
|
||||
return _activeContext?.GetSceneValue(name) ?? SceneValue.Nil;
|
||||
}
|
||||
|
||||
private void SetSceneValue(string name, SceneValue value)
|
||||
{
|
||||
_activeCancellation.ThrowIfCancellationRequested();
|
||||
_activeContext?.SetSceneValue(name, value);
|
||||
}
|
||||
|
||||
private void RegisterObjectCallbacks(Table obj)
|
||||
{
|
||||
obj["getobject"] = DynValue.NewCallback((execCtx, args) =>
|
||||
@@ -473,22 +521,248 @@ namespace LuaScript
|
||||
obj["load"] = DynValue.NewCallback((_, args) =>
|
||||
{
|
||||
_activeCancellation.ThrowIfCancellationRequested();
|
||||
if (_activeContext is null || args.Count < 4)
|
||||
return DynValue.Void;
|
||||
if (args[0].Type != DataType.String || args[0].String != "figure")
|
||||
if (_activeContext is null || args.Count == 0 || args[0].Type != DataType.String)
|
||||
return DynValue.Void;
|
||||
|
||||
string name = args[1].Type == DataType.String ? args[1].String : string.Empty;
|
||||
int color = (int)(args[2].CastToNumber() ?? 0d);
|
||||
double size = args[3].CastToNumber() ?? 0d;
|
||||
double line = args.Count > 4 ? args[4].CastToNumber() ?? 0d : 0d;
|
||||
double aspect = args.Count > 5 ? Math.Clamp(args[5].CastToNumber() ?? 0d, -1d, 1d) : 0d;
|
||||
switch (args[0].String)
|
||||
{
|
||||
case "figure" when args.Count >= 4:
|
||||
LoadFigure(
|
||||
args[1].Type == DataType.String ? args[1].String : string.Empty,
|
||||
(int)(args[2].CastToNumber() ?? 0d),
|
||||
args[3].CastToNumber() ?? 0d,
|
||||
args.Count > 4 ? args[4].CastToNumber() ?? 0d : 0d,
|
||||
args.Count > 5 ? Math.Clamp(args[5].CastToNumber() ?? 0d, -1d, 1d) : 0d);
|
||||
break;
|
||||
case "text":
|
||||
LoadText(args.Count > 1 && args[1].Type == DataType.String ? args[1].String : string.Empty);
|
||||
break;
|
||||
case "image" when args.Count > 1 && args[1].Type == DataType.String:
|
||||
LoadImage(args[1].String);
|
||||
break;
|
||||
case "movie" when args.Count > 1 && args[1].Type == DataType.String:
|
||||
LoadMovie(
|
||||
args[1].String,
|
||||
args.Count > 2 ? args[2].CastToNumber() ?? _activeContext.Time : _activeContext.Time);
|
||||
break;
|
||||
}
|
||||
return DynValue.Void;
|
||||
});
|
||||
|
||||
LoadFigure(name, color, size, line, aspect);
|
||||
obj["setfont"] = DynValue.NewCallback((_, args) =>
|
||||
{
|
||||
_activeCancellation.ThrowIfCancellationRequested();
|
||||
if (args.Count == 0)
|
||||
return DynValue.Void;
|
||||
if (args[0].Type == DataType.String)
|
||||
_fontFamily = args[0].String;
|
||||
if (args.Count > 1)
|
||||
_fontSize = args[1].CastToNumber() ?? _fontSize;
|
||||
if (args.Count > 2)
|
||||
{
|
||||
int type = (int)(args[2].CastToNumber() ?? 0d);
|
||||
_fontBold = (type & 1) != 0;
|
||||
_fontItalic = (type & 2) != 0;
|
||||
}
|
||||
if (args.Count > 3)
|
||||
_fontColor = (int)(args[3].CastToNumber() ?? _fontColor);
|
||||
return DynValue.Void;
|
||||
});
|
||||
|
||||
obj["effect"] = DynValue.NewCallback((_, args) =>
|
||||
{
|
||||
_activeCancellation.ThrowIfCancellationRequested();
|
||||
if (_activeContext is null || args.Count == 0 || args[0].Type != DataType.String)
|
||||
return DynValue.Void;
|
||||
|
||||
string name = args[0].String;
|
||||
var arguments = new List<KeyValuePair<string, object>>();
|
||||
for (int i = 1; i + 1 < args.Count; i += 2)
|
||||
{
|
||||
if (args[i].Type != DataType.String)
|
||||
continue;
|
||||
var value = args[i + 1];
|
||||
object boxed = value.Type switch
|
||||
{
|
||||
DataType.Number => value.Number,
|
||||
DataType.Boolean => value.Boolean,
|
||||
DataType.String => value.String,
|
||||
_ => value.CastToNumber() ?? 0d,
|
||||
};
|
||||
arguments.Add(new KeyValuePair<string, object>(args[i].String, boxed));
|
||||
}
|
||||
|
||||
_activeContext.AddEffect(new AviUtlEffectRequest(name, arguments));
|
||||
return DynValue.Void;
|
||||
});
|
||||
|
||||
obj["draw"] = DynValue.NewCallback((_, args) =>
|
||||
{
|
||||
_activeCancellation.ThrowIfCancellationRequested();
|
||||
if (_activeContext is null)
|
||||
return DynValue.Void;
|
||||
|
||||
double ox = args.Count > 0 ? args[0].CastToNumber() ?? 0d : 0d;
|
||||
double oy = args.Count > 1 ? args[1].CastToNumber() ?? 0d : 0d;
|
||||
double oz = args.Count > 2 ? args[2].CastToNumber() ?? 0d : 0d;
|
||||
double zoom = args.Count > 3 ? args[3].CastToNumber() ?? 1d : 1d;
|
||||
double alpha = args.Count > 4 ? args[4].CastToNumber() ?? 1d : 1d;
|
||||
double aspect = args.Count > 5 ? args[5].CastToNumber() ?? 0d : 0d;
|
||||
|
||||
_activeContext.SubmitDraw(new DrawCommand(ox, oy, oz, zoom, alpha, aspect, null, CurrentAntialias(), CurrentBlend()));
|
||||
return DynValue.Void;
|
||||
});
|
||||
|
||||
obj["drawpoly"] = DynValue.NewCallback((_, args) =>
|
||||
{
|
||||
_activeCancellation.ThrowIfCancellationRequested();
|
||||
if (_activeContext is null || args.Count < 12)
|
||||
return DynValue.Void;
|
||||
|
||||
var poly = new double[DrawPolyMath.Length];
|
||||
for (int i = 0; i < 12; i++)
|
||||
poly[i] = args[i].CastToNumber() ?? 0d;
|
||||
|
||||
if (args.Count >= 20)
|
||||
{
|
||||
for (int i = 0; i < 8; i++)
|
||||
poly[12 + i] = args[12 + i].CastToNumber() ?? 0d;
|
||||
}
|
||||
else
|
||||
{
|
||||
double w = _activeContext.ImageWidth;
|
||||
double h = _activeContext.ImageHeight;
|
||||
poly[12] = 0d; poly[13] = 0d;
|
||||
poly[14] = w; poly[15] = 0d;
|
||||
poly[16] = w; poly[17] = h;
|
||||
poly[18] = 0d; poly[19] = h;
|
||||
}
|
||||
|
||||
poly[20] = args.Count switch
|
||||
{
|
||||
13 => args[12].CastToNumber() ?? 1d,
|
||||
>= 21 => args[20].CastToNumber() ?? 1d,
|
||||
_ => 1d,
|
||||
};
|
||||
|
||||
_activeContext.SubmitDraw(new DrawCommand(0d, 0d, 0d, 1d, poly[20], 0d, poly, CurrentAntialias(), CurrentBlend()));
|
||||
return DynValue.Void;
|
||||
});
|
||||
|
||||
obj["copybuffer"] = DynValue.NewCallback((_, args) =>
|
||||
{
|
||||
_activeCancellation.ThrowIfCancellationRequested();
|
||||
if (_activeContext is null || args.Count < 2 ||
|
||||
args[0].Type != DataType.String || args[1].Type != DataType.String)
|
||||
return DynValue.Void;
|
||||
|
||||
if (_activeContext.CopyBuffer(args[0].String, args[1].String))
|
||||
RefreshObjDimensions();
|
||||
return DynValue.Void;
|
||||
});
|
||||
|
||||
obj["getvalue"] = DynValue.NewCallback((_, args) =>
|
||||
{
|
||||
_activeCancellation.ThrowIfCancellationRequested();
|
||||
if (args.Count == 0 || args[0].Type != DataType.String)
|
||||
return DynValue.NewNumber(0d);
|
||||
var value = _objTable!.Get(args[0].String);
|
||||
return value.Type == DataType.Number ? value : DynValue.NewNumber(0d);
|
||||
});
|
||||
|
||||
obj["setanchor"] = DynValue.NewCallback((_, args) =>
|
||||
{
|
||||
_activeCancellation.ThrowIfCancellationRequested();
|
||||
if (_activeContext is null || _script is null || args.Count < 2 || args[0].Type != DataType.String)
|
||||
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);
|
||||
|
||||
var connection = AnchorConnection.None;
|
||||
bool is3D = false;
|
||||
for (int i = 2; i < args.Count; i++)
|
||||
{
|
||||
if (args[i].Type == DataType.String)
|
||||
AnchorSupport.ApplyOption(args[i].String, ref connection, ref is3D);
|
||||
}
|
||||
|
||||
int stride = is3D ? 3 : 2;
|
||||
var table = new Table(_script);
|
||||
var source = _activeContext.AnchorSource;
|
||||
for (int i = 0; i < count; i++)
|
||||
{
|
||||
AnchorSupport.ResolvePosition(source, anchorName, i, out double x, out double y, out double z);
|
||||
table.Set(i * stride + 1, DynValue.NewNumber(x));
|
||||
table.Set(i * stride + 2, DynValue.NewNumber(y));
|
||||
if (is3D)
|
||||
table.Set(i * stride + 3, DynValue.NewNumber(z));
|
||||
}
|
||||
_script.Globals.Set(anchorName, DynValue.NewTable(table));
|
||||
|
||||
_activeContext.AddAnchorRequest(new AnchorRequestData(anchorName, count, connection, is3D));
|
||||
return DynValue.NewNumber(count);
|
||||
});
|
||||
|
||||
obj["setoption"] = DynValue.NewCallback((_, args) =>
|
||||
{
|
||||
_activeCancellation.ThrowIfCancellationRequested();
|
||||
if (args.Count == 0 || args[0].Type != DataType.String)
|
||||
return DynValue.Void;
|
||||
var name = args[0].String;
|
||||
var value = args.Count > 1 ? args[1] : DynValue.True;
|
||||
_options[name] = value;
|
||||
if (name == "draw_state" && _activeContext is not null)
|
||||
_activeContext.DrawStateOverride = value.Type == DataType.Boolean
|
||||
? value.Boolean
|
||||
: (value.CastToNumber() ?? 0d) != 0d;
|
||||
if (name == "drawtarget" && _activeContext is not null)
|
||||
{
|
||||
if (value.Type == DataType.String && value.String == "tempbuffer")
|
||||
{
|
||||
bool hasSize = args.Count > 3;
|
||||
int w = hasSize ? (int)(args[2].CastToNumber() ?? 0d) : 0;
|
||||
int h = hasSize ? (int)(args[3].CastToNumber() ?? 0d) : 0;
|
||||
_activeContext.SetDrawTarget(true, w, h, hasSize);
|
||||
}
|
||||
else
|
||||
{
|
||||
_activeContext.SetDrawTarget(false, 0, 0, false);
|
||||
}
|
||||
}
|
||||
return DynValue.Void;
|
||||
});
|
||||
|
||||
obj["getoption"] = DynValue.NewCallback((_, args) =>
|
||||
{
|
||||
_activeCancellation.ThrowIfCancellationRequested();
|
||||
if (args.Count == 0 || args[0].Type != DataType.String)
|
||||
return DynValue.NewNumber(0d);
|
||||
return _options.TryGetValue(args[0].String, out var value) ? value : DynValue.NewNumber(0d);
|
||||
});
|
||||
|
||||
obj["pixeloption"] = DynValue.NewCallback((_, args) =>
|
||||
{
|
||||
_activeCancellation.ThrowIfCancellationRequested();
|
||||
if (args.Count == 0 || args[0].Type != DataType.String)
|
||||
return DynValue.Void;
|
||||
_pixelOptions[args[0].String] = args.Count > 1 ? args[1] : DynValue.True;
|
||||
return DynValue.Void;
|
||||
});
|
||||
}
|
||||
|
||||
private double CurrentAntialias() =>
|
||||
_options.TryGetValue("antialias", out var value) && value.Type == DataType.Number
|
||||
? value.Number
|
||||
: 1d;
|
||||
|
||||
private double CurrentBlend() =>
|
||||
_options.TryGetValue("blend", out var value) && value.Type == DataType.Number
|
||||
? value.Number
|
||||
: 0d;
|
||||
|
||||
private void LoadFigure(string name, int color, double size, double line, double aspect)
|
||||
{
|
||||
int boundingSize = Math.Max(1, (int)Math.Round(size));
|
||||
@@ -500,6 +774,39 @@ namespace LuaScript
|
||||
var buffer = FigureRenderer.Render(name, w, h, color, line);
|
||||
_activeContext!.ReplaceBuffer(buffer, w, h);
|
||||
|
||||
RefreshObjDimensions();
|
||||
}
|
||||
|
||||
private void LoadText(string text)
|
||||
{
|
||||
_textRenderer ??= new TextRenderer();
|
||||
var buffer = _textRenderer.Render(
|
||||
text, _fontFamily, _fontSize, _fontBold, _fontItalic, _fontColor,
|
||||
out int w, out int h);
|
||||
_activeContext!.ReplaceBuffer(buffer, w, h);
|
||||
RefreshObjDimensions();
|
||||
}
|
||||
|
||||
private void LoadImage(string path)
|
||||
{
|
||||
_imageDecoder ??= new ImageDecoder();
|
||||
var buffer = _imageDecoder.Decode(path, out int w, out int h);
|
||||
_activeContext!.ReplaceBuffer(buffer, w, h);
|
||||
RefreshObjDimensions();
|
||||
}
|
||||
|
||||
private void LoadMovie(string path, double time)
|
||||
{
|
||||
_movieDecoder ??= new MovieDecoder();
|
||||
var buffer = _movieDecoder.Decode(path, time, out int w, out int h);
|
||||
_activeContext!.ReplaceBuffer(buffer, w, h);
|
||||
RefreshObjDimensions();
|
||||
}
|
||||
|
||||
private void RefreshObjDimensions()
|
||||
{
|
||||
int w = _activeContext!.ImageWidth;
|
||||
int h = _activeContext.ImageHeight;
|
||||
var obj = _objTable!;
|
||||
obj["w"] = w;
|
||||
obj["h"] = h;
|
||||
@@ -546,39 +853,17 @@ namespace LuaScript
|
||||
ctx.Oz = _objTable.Get("oz").CastToNumber() ?? ctx.Oz;
|
||||
ctx.Alpha = _objTable.Get("alpha").CastToNumber() ?? ctx.Alpha;
|
||||
|
||||
double initialSx = ctx.Sx;
|
||||
double initialSy = ctx.Sy;
|
||||
double initialZoom = ctx.Zoom;
|
||||
double initialAspect = ctx.Aspect;
|
||||
|
||||
ctx.Sx = _objTable.Get("sx").CastToNumber() ?? ctx.Sx;
|
||||
ctx.Sy = _objTable.Get("sy").CastToNumber() ?? ctx.Sy;
|
||||
ctx.Zoom = _objTable.Get("zoom").CastToNumber() ?? ctx.Zoom;
|
||||
ctx.Aspect = _objTable.Get("aspect").CastToNumber() ?? ctx.Aspect;
|
||||
|
||||
bool sxsyChanged = Math.Abs(ctx.Sx - initialSx) > 1e-10 || Math.Abs(ctx.Sy - initialSy) > 1e-10;
|
||||
bool zoomAspectChanged = Math.Abs(ctx.Zoom - initialZoom) > 1e-10 || Math.Abs(ctx.Aspect - initialAspect) > 1e-10;
|
||||
|
||||
if (zoomAspectChanged && !sxsyChanged)
|
||||
{
|
||||
ctx.Sx = ctx.Zoom * (1.0 + ctx.Aspect);
|
||||
ctx.Sy = ctx.Zoom * (1.0 - ctx.Aspect);
|
||||
}
|
||||
|
||||
double rxrNew = _objTable.Get("rxr").CastToNumber() ?? ctx.RxRad;
|
||||
ctx.Rx = Math.Abs(rxrNew - ctx.RxRad) > 1e-10
|
||||
? rxrNew * (180d / Math.PI)
|
||||
: _objTable.Get("rx").CastToNumber() ?? ctx.Rx;
|
||||
|
||||
double ryrNew = _objTable.Get("ryr").CastToNumber() ?? ctx.RyRad;
|
||||
ctx.Ry = Math.Abs(ryrNew - ctx.RyRad) > 1e-10
|
||||
? ryrNew * (180d / Math.PI)
|
||||
: _objTable.Get("ry").CastToNumber() ?? ctx.Ry;
|
||||
|
||||
double rzrNew = _objTable.Get("rzr").CastToNumber() ?? ctx.RzRad;
|
||||
ctx.Rz = Math.Abs(rzrNew - ctx.RzRad) > 1e-10
|
||||
? rzrNew * (180d / Math.PI)
|
||||
: _objTable.Get("rz").CastToNumber() ?? ctx.Rz;
|
||||
ctx.ApplyWriteBack(
|
||||
_objTable.Get("sx").CastToNumber() ?? ctx.Sx,
|
||||
_objTable.Get("sy").CastToNumber() ?? ctx.Sy,
|
||||
_objTable.Get("zoom").CastToNumber() ?? ctx.Zoom,
|
||||
_objTable.Get("aspect").CastToNumber() ?? ctx.Aspect,
|
||||
_objTable.Get("rx").CastToNumber() ?? ctx.Rx,
|
||||
_objTable.Get("ry").CastToNumber() ?? ctx.Ry,
|
||||
_objTable.Get("rz").CastToNumber() ?? ctx.Rz,
|
||||
_objTable.Get("rxr").CastToNumber() ?? ctx.RxRad,
|
||||
_objTable.Get("ryr").CastToNumber() ?? ctx.RyRad,
|
||||
_objTable.Get("rzr").CastToNumber() ?? ctx.RzRad);
|
||||
}
|
||||
|
||||
public void Dispose()
|
||||
@@ -586,6 +871,9 @@ namespace LuaScript
|
||||
_disposeRequested = true;
|
||||
_workSignal.Release();
|
||||
_thread.Join();
|
||||
_textRenderer?.Dispose();
|
||||
_imageDecoder?.Dispose();
|
||||
_movieDecoder?.Dispose();
|
||||
_cts.Cancel();
|
||||
_cts.Dispose();
|
||||
_workSignal.Dispose();
|
||||
@@ -599,6 +887,9 @@ namespace LuaScript
|
||||
ThreadPool.QueueUserWorkItem(_ =>
|
||||
{
|
||||
_thread.Join();
|
||||
_textRenderer?.Dispose();
|
||||
_imageDecoder?.Dispose();
|
||||
_movieDecoder?.Dispose();
|
||||
_cts.Dispose();
|
||||
_workSignal.Dispose();
|
||||
_doneSignal.Dispose();
|
||||
|
||||
@@ -0,0 +1,6 @@
|
||||
using System;
|
||||
|
||||
namespace LuaScript
|
||||
{
|
||||
internal abstract class LuaScriptException(string message, Exception? inner = null) : Exception(message, inner);
|
||||
}
|
||||
@@ -1,10 +0,0 @@
|
||||
namespace LuaScript
|
||||
{
|
||||
internal abstract class LuaScriptException(string message, Exception? inner = null) : Exception(message, inner);
|
||||
|
||||
internal sealed class LuaScriptCompilationException(string message, Exception? inner = null) : LuaScriptException(message, inner);
|
||||
|
||||
internal sealed class LuaScriptRuntimeException(string message, Exception? inner = null) : LuaScriptException(message, inner);
|
||||
|
||||
internal sealed class LuaScriptTimeoutException(string message, Exception? inner = null) : LuaScriptException(message, inner);
|
||||
}
|
||||
@@ -0,0 +1,6 @@
|
||||
using System;
|
||||
|
||||
namespace LuaScript
|
||||
{
|
||||
internal sealed class LuaScriptRuntimeException(string message, Exception? inner = null) : LuaScriptException(message, inner);
|
||||
}
|
||||
@@ -0,0 +1,6 @@
|
||||
using System;
|
||||
|
||||
namespace LuaScript
|
||||
{
|
||||
internal sealed class LuaScriptTimeoutException(string message, Exception? inner = null) : LuaScriptException(message, inner);
|
||||
}
|
||||
@@ -0,0 +1,213 @@
|
||||
using System;
|
||||
using System.IO;
|
||||
using SharpGen.Runtime.Win32;
|
||||
using Vortice.MediaFoundation;
|
||||
|
||||
namespace LuaScript
|
||||
{
|
||||
internal sealed class MovieDecoder : IDisposable
|
||||
{
|
||||
private const int MaxDimension = 8192;
|
||||
private const int FirstVideoStream = -4;
|
||||
private const int AllStreams = -2;
|
||||
private const int EndOfStreamFlag = 0x2;
|
||||
|
||||
private bool _mfStarted;
|
||||
private string? _path;
|
||||
private IMFSourceReader? _reader;
|
||||
private int _width;
|
||||
private int _height;
|
||||
private int _stride;
|
||||
|
||||
public unsafe byte[] Decode(string path, double timeSeconds, out int width, out int height)
|
||||
{
|
||||
width = 1;
|
||||
height = 1;
|
||||
if (string.IsNullOrEmpty(path) || !IsSupportedVideo(path))
|
||||
return new byte[4];
|
||||
|
||||
try
|
||||
{
|
||||
EnsureReader(path);
|
||||
if (_reader is null || _width <= 0 || _height <= 0)
|
||||
return new byte[4];
|
||||
|
||||
SetPosition(_reader, (long)(Math.Max(0d, timeSeconds) * 10_000_000d));
|
||||
|
||||
using var sample = ReadVideoSample(_reader);
|
||||
if (sample is null)
|
||||
return new byte[4];
|
||||
|
||||
using var buffer = sample.ConvertToContiguousBuffer();
|
||||
buffer.Lock(out nint data, out _, out _);
|
||||
try
|
||||
{
|
||||
int w = _width;
|
||||
int h = _height;
|
||||
int absStride = Math.Abs(_stride);
|
||||
bool bottomUp = _stride < 0;
|
||||
var result = new byte[w * h * 4];
|
||||
byte* src = (byte*)data;
|
||||
fixed (byte* dst = result)
|
||||
{
|
||||
for (int y = 0; y < h; y++)
|
||||
{
|
||||
int sourceRow = bottomUp ? h - 1 - y : y;
|
||||
byte* s = src + sourceRow * absStride;
|
||||
byte* d = dst + y * w * 4;
|
||||
for (int x = 0; x < w; x++)
|
||||
{
|
||||
d[0] = s[0];
|
||||
d[1] = s[1];
|
||||
d[2] = s[2];
|
||||
d[3] = 255;
|
||||
s += 4;
|
||||
d += 4;
|
||||
}
|
||||
}
|
||||
}
|
||||
width = w;
|
||||
height = h;
|
||||
return result;
|
||||
}
|
||||
finally
|
||||
{
|
||||
buffer.Unlock();
|
||||
}
|
||||
}
|
||||
catch
|
||||
{
|
||||
width = 1;
|
||||
height = 1;
|
||||
return new byte[4];
|
||||
}
|
||||
}
|
||||
|
||||
private void EnsureReader(string path)
|
||||
{
|
||||
if (_reader is not null && string.Equals(_path, path, StringComparison.Ordinal))
|
||||
return;
|
||||
|
||||
DisposeReader();
|
||||
|
||||
if (!_mfStarted)
|
||||
{
|
||||
MediaFactory.MFStartup(false);
|
||||
_mfStarted = true;
|
||||
}
|
||||
|
||||
using var attributes = MediaFactory.MFCreateAttributes(1);
|
||||
attributes.Set(SourceReaderAttributeKeys.EnableAdvancedVideoProcessing, 1);
|
||||
var reader = MediaFactory.MFCreateSourceReaderFromURL(path, attributes);
|
||||
|
||||
reader.SetStreamSelection(AllStreams, false);
|
||||
reader.SetStreamSelection(FirstVideoStream, true);
|
||||
|
||||
using (var mediaType = MediaFactory.MFCreateMediaType())
|
||||
{
|
||||
mediaType.Set(MediaTypeAttributeKeys.MajorType, MediaTypeGuids.Video);
|
||||
mediaType.Set(MediaTypeAttributeKeys.Subtype, VideoFormatGuids.Rgb32);
|
||||
reader.SetCurrentMediaType(FirstVideoStream, mediaType);
|
||||
}
|
||||
|
||||
using var current = reader.GetCurrentMediaType(FirstVideoStream);
|
||||
var mediaAttributes = (IMFAttributes)current;
|
||||
ulong frameSize = Convert.ToUInt64(mediaAttributes.Get(MediaTypeAttributeKeys.FrameSize));
|
||||
int w = (int)(frameSize >> 32);
|
||||
int h = (int)(frameSize & 0xFFFFFFFF);
|
||||
|
||||
int stride;
|
||||
try { stride = Convert.ToInt32(mediaAttributes.Get(MediaTypeAttributeKeys.DefaultStride)); }
|
||||
catch { stride = w * 4; }
|
||||
if (stride == 0)
|
||||
stride = w * 4;
|
||||
|
||||
if (w <= 0 || h <= 0 || w > MaxDimension || h > MaxDimension)
|
||||
{
|
||||
reader.Dispose();
|
||||
return;
|
||||
}
|
||||
|
||||
_reader = reader;
|
||||
_path = path;
|
||||
_width = w;
|
||||
_height = h;
|
||||
_stride = stride;
|
||||
}
|
||||
|
||||
private static void SetPosition(IMFSourceReader reader, long ticks)
|
||||
{
|
||||
var variant = new Variant
|
||||
{
|
||||
Value = ticks,
|
||||
ElementType = (VariantElementType)20,
|
||||
};
|
||||
reader.SetCurrentPosition(Guid.Empty, variant);
|
||||
}
|
||||
|
||||
private static IMFSample? ReadVideoSample(IMFSourceReader reader)
|
||||
{
|
||||
for (int guard = 0; guard < 256; guard++)
|
||||
{
|
||||
reader.ReadSample(FirstVideoStream, 0, out _, out int flags, out _, out IMFSample? sample);
|
||||
if (sample is not null)
|
||||
return sample;
|
||||
if ((flags & EndOfStreamFlag) != 0)
|
||||
return null;
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
private static bool IsSupportedVideo(string path)
|
||||
{
|
||||
try
|
||||
{
|
||||
if (!File.Exists(path))
|
||||
return false;
|
||||
Span<byte> head = stackalloc byte[16];
|
||||
using var stream = File.OpenRead(path);
|
||||
int read = stream.Read(head);
|
||||
if (read < 12)
|
||||
return false;
|
||||
|
||||
if (head[4] == 0x66 && head[5] == 0x74 && head[6] == 0x79 && head[7] == 0x70)
|
||||
return true;
|
||||
if (head[0] == 0x1A && head[1] == 0x45 && head[2] == 0xDF && head[3] == 0xA3)
|
||||
return true;
|
||||
if (head[0] == 0x52 && head[1] == 0x49 && head[2] == 0x46 && head[3] == 0x46 &&
|
||||
head[8] == 0x41 && head[9] == 0x56 && head[10] == 0x49 && head[11] == 0x20)
|
||||
return true;
|
||||
if (head[0] == 0x46 && head[1] == 0x4C && head[2] == 0x56)
|
||||
return true;
|
||||
if (head[0] == 0x30 && head[1] == 0x26 && head[2] == 0xB2 && head[3] == 0x75)
|
||||
return true;
|
||||
return false;
|
||||
}
|
||||
catch
|
||||
{
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
private void DisposeReader()
|
||||
{
|
||||
_reader?.Dispose();
|
||||
_reader = null;
|
||||
_path = null;
|
||||
_width = 0;
|
||||
_height = 0;
|
||||
_stride = 0;
|
||||
}
|
||||
|
||||
public void Dispose()
|
||||
{
|
||||
DisposeReader();
|
||||
if (_mfStarted)
|
||||
{
|
||||
try { MediaFactory.MFShutdown(); }
|
||||
catch { }
|
||||
_mfStarted = false;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,187 @@
|
||||
using System;
|
||||
using Vortice;
|
||||
using System.Numerics;
|
||||
using Vortice.DCommon;
|
||||
using Vortice.Direct2D1;
|
||||
using Vortice.Direct2D1.Effects;
|
||||
using Vortice.DXGI;
|
||||
using Vortice.Mathematics;
|
||||
using YukkuriMovieMaker.Commons;
|
||||
|
||||
namespace LuaScript
|
||||
{
|
||||
internal sealed class PixelBufferManager : IDisposable
|
||||
{
|
||||
private readonly GraphicsDevicesAndContext _ctx;
|
||||
private ID2D1Bitmap1? _renderTarget;
|
||||
private ID2D1Bitmap1? _stagingBitmap;
|
||||
private ID2D1Bitmap1? _outputBitmap;
|
||||
private AffineTransform2D? _transformEffect;
|
||||
private ID2D1Image? _transformOutput;
|
||||
private byte[]? _pixelBuffer;
|
||||
private int _bitmapWidth;
|
||||
private int _bitmapHeight;
|
||||
private RawRectF _cachedBounds;
|
||||
|
||||
public PixelBufferManager(GraphicsDevicesAndContext ctx)
|
||||
{
|
||||
_ctx = ctx;
|
||||
}
|
||||
|
||||
public unsafe byte[] LoadInputPixels(ID2D1Image input, RawRectF bounds, int width, int height)
|
||||
{
|
||||
EnsureBitmaps(width, height);
|
||||
RenderToStaging(input, bounds);
|
||||
|
||||
var mapped = _stagingBitmap!.Map(MapOptions.Read);
|
||||
try
|
||||
{
|
||||
fixed (byte* destination = _pixelBuffer)
|
||||
CopyStagingRows(mapped.Bits, mapped.Pitch, destination, _pixelBuffer!.Length, width, height);
|
||||
}
|
||||
finally
|
||||
{
|
||||
_stagingBitmap.Unmap();
|
||||
}
|
||||
|
||||
return _pixelBuffer!;
|
||||
}
|
||||
|
||||
public unsafe void LoadInputPixelsInto(ID2D1Image input, RawRectF bounds, int width, int height, nint destination, long capacity)
|
||||
{
|
||||
EnsureBitmaps(width, height);
|
||||
RenderToStaging(input, bounds);
|
||||
|
||||
var mapped = _stagingBitmap!.Map(MapOptions.Read);
|
||||
try
|
||||
{
|
||||
CopyStagingRows(mapped.Bits, mapped.Pitch, (byte*)destination, capacity, width, height);
|
||||
}
|
||||
finally
|
||||
{
|
||||
_stagingBitmap.Unmap();
|
||||
}
|
||||
}
|
||||
|
||||
public unsafe void WritePixelsToOutput(byte[] pixels, int width, int height)
|
||||
{
|
||||
EnsureBitmaps(width, height);
|
||||
fixed (byte* ptr = pixels)
|
||||
_outputBitmap!.CopyFromMemory(new nint(ptr), width * 4);
|
||||
}
|
||||
|
||||
public void WritePixelsToOutput(nint source, int width, int height)
|
||||
{
|
||||
EnsureBitmaps(width, height);
|
||||
_outputBitmap!.CopyFromMemory(source, width * 4);
|
||||
}
|
||||
|
||||
private void RenderToStaging(ID2D1Image input, RawRectF bounds)
|
||||
{
|
||||
var dc = _ctx.DeviceContext;
|
||||
using var savedTarget = dc.Target;
|
||||
|
||||
dc.Target = _renderTarget;
|
||||
dc.BeginDraw();
|
||||
dc.Clear(null);
|
||||
dc.DrawImage(input, new Vector2(-bounds.Left, -bounds.Top));
|
||||
dc.EndDraw();
|
||||
dc.Target = savedTarget;
|
||||
|
||||
_stagingBitmap!.CopyFromBitmap(_renderTarget!);
|
||||
}
|
||||
|
||||
private static unsafe void CopyStagingRows(nint bits, int pitch, byte* destination, long capacity, int width, int height)
|
||||
{
|
||||
long required = (long)width * height * 4;
|
||||
if (required > capacity)
|
||||
throw new InvalidOperationException("Pixel destination is smaller than the mapped region.");
|
||||
|
||||
byte* source = (byte*)bits;
|
||||
if (pitch == width * 4)
|
||||
{
|
||||
Buffer.MemoryCopy(source, destination, capacity, required);
|
||||
return;
|
||||
}
|
||||
|
||||
long rowBytes = (long)width * 4;
|
||||
for (int row = 0; row < height; row++)
|
||||
Buffer.MemoryCopy(
|
||||
source + (long)pitch * row,
|
||||
destination + rowBytes * row,
|
||||
capacity - rowBytes * row,
|
||||
rowBytes);
|
||||
}
|
||||
|
||||
public ID2D1Image GetTransformOutput(float left, float top)
|
||||
{
|
||||
if (_transformEffect is null)
|
||||
{
|
||||
_transformEffect = new AffineTransform2D(_ctx.DeviceContext);
|
||||
_transformEffect.SetInput(0, _outputBitmap, true);
|
||||
_transformOutput = _transformEffect.Output;
|
||||
_cachedBounds = default;
|
||||
}
|
||||
|
||||
if (_cachedBounds.Left != left || _cachedBounds.Top != top)
|
||||
{
|
||||
_transformEffect.TransformMatrix = Matrix3x2.CreateTranslation(left, top);
|
||||
_cachedBounds = new RawRectF(left, top, left, top);
|
||||
}
|
||||
|
||||
return _transformOutput!;
|
||||
}
|
||||
|
||||
private void EnsureBitmaps(int width, int height)
|
||||
{
|
||||
if (_bitmapWidth == width && _bitmapHeight == height) return;
|
||||
|
||||
_renderTarget?.Dispose();
|
||||
_stagingBitmap?.Dispose();
|
||||
_outputBitmap?.Dispose();
|
||||
_transformOutput?.Dispose();
|
||||
_transformEffect?.Dispose();
|
||||
_renderTarget = null;
|
||||
_stagingBitmap = null;
|
||||
_outputBitmap = null;
|
||||
_transformOutput = null;
|
||||
_transformEffect = null;
|
||||
_bitmapWidth = 0;
|
||||
_bitmapHeight = 0;
|
||||
|
||||
var dc = _ctx.DeviceContext;
|
||||
|
||||
_renderTarget = dc.CreateEmptyBitmap(width, height, BitmapOptions.Target);
|
||||
|
||||
var stagingProps = new BitmapProperties1(
|
||||
new PixelFormat(Format.B8G8R8A8_UNorm, Vortice.DCommon.AlphaMode.Premultiplied),
|
||||
96f, 96f,
|
||||
BitmapOptions.CpuRead | BitmapOptions.CannotDraw);
|
||||
_stagingBitmap = dc.CreateBitmap(
|
||||
new SizeI(width, height),
|
||||
nint.Zero,
|
||||
width * 4,
|
||||
stagingProps);
|
||||
|
||||
_outputBitmap = dc.CreateEmptyBitmap(width, height, BitmapOptions.Target);
|
||||
_pixelBuffer = new byte[width * height * 4];
|
||||
|
||||
_bitmapWidth = width;
|
||||
_bitmapHeight = height;
|
||||
}
|
||||
|
||||
public void Dispose()
|
||||
{
|
||||
_renderTarget?.Dispose();
|
||||
_stagingBitmap?.Dispose();
|
||||
_outputBitmap?.Dispose();
|
||||
_transformOutput?.Dispose();
|
||||
_transformEffect?.Dispose();
|
||||
_renderTarget = null;
|
||||
_stagingBitmap = null;
|
||||
_outputBitmap = null;
|
||||
_transformOutput = null;
|
||||
_transformEffect = null;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -24,13 +24,17 @@ namespace LuaScript
|
||||
{
|
||||
byte* pixel = p + pixelIndex * 4;
|
||||
double a = pixel[3];
|
||||
if (channel == 3)
|
||||
return a;
|
||||
if (a <= 0d)
|
||||
return 0d;
|
||||
|
||||
double scale = 255d / a;
|
||||
return channel switch
|
||||
{
|
||||
0 => a > 0d ? Math.Clamp(pixel[2] * 255d / a, 0d, 255d) : 0d,
|
||||
1 => a > 0d ? Math.Clamp(pixel[1] * 255d / a, 0d, 255d) : 0d,
|
||||
2 => a > 0d ? Math.Clamp(pixel[0] * 255d / a, 0d, 255d) : 0d,
|
||||
3 => a,
|
||||
0 => Math.Clamp(pixel[2] * scale, 0d, 255d),
|
||||
1 => Math.Clamp(pixel[1] * scale, 0d, 255d),
|
||||
2 => Math.Clamp(pixel[0] * scale, 0d, 255d),
|
||||
_ => throw new UnreachableException()
|
||||
};
|
||||
}
|
||||
|
||||
@@ -10,9 +10,4 @@ namespace LuaScript
|
||||
double Rz,
|
||||
double Alpha,
|
||||
int Layer);
|
||||
|
||||
internal readonly record struct SceneObjectQuery(
|
||||
string Tag,
|
||||
int Frame,
|
||||
SceneObjectInfo? Result);
|
||||
}
|
||||
@@ -0,0 +1,7 @@
|
||||
namespace LuaScript
|
||||
{
|
||||
internal readonly record struct SceneObjectQuery(
|
||||
string Tag,
|
||||
int Frame,
|
||||
SceneObjectInfo? Result);
|
||||
}
|
||||
@@ -0,0 +1,101 @@
|
||||
using System.Collections.Concurrent;
|
||||
using System.Text;
|
||||
|
||||
namespace LuaScript
|
||||
{
|
||||
internal enum SceneValueKind
|
||||
{
|
||||
Nil = 0,
|
||||
Number = 1,
|
||||
String = 2,
|
||||
Boolean = 3,
|
||||
}
|
||||
|
||||
internal readonly record struct SceneValue(SceneValueKind Kind, double Number, string? Text)
|
||||
{
|
||||
public static readonly SceneValue Nil = new(SceneValueKind.Nil, 0d, null);
|
||||
|
||||
public static SceneValue FromNumber(double value) => new(SceneValueKind.Number, value, null);
|
||||
|
||||
public static SceneValue FromBoolean(bool value) => new(SceneValueKind.Boolean, value ? 1d : 0d, null);
|
||||
|
||||
public static SceneValue FromString(string value) => new(SceneValueKind.String, 0d, value);
|
||||
}
|
||||
|
||||
internal readonly record struct SceneValueQuery(string Name, SceneValue Result);
|
||||
|
||||
internal sealed class SceneSharedValues
|
||||
{
|
||||
public const int MaxNameBytes = NativeTagCapacity - 1;
|
||||
public const int MaxTextBytes = NativeTagCapacity - 1;
|
||||
|
||||
private const int NativeTagCapacity = 4096;
|
||||
|
||||
private static readonly ConcurrentDictionary<string, SceneSharedValues> s_scenes = new(StringComparer.Ordinal);
|
||||
|
||||
private readonly Dictionary<string, SceneValue> _values = new(StringComparer.Ordinal);
|
||||
private readonly object _gate = new();
|
||||
|
||||
public static SceneSharedValues ForScene(string sceneId) =>
|
||||
s_scenes.GetOrAdd(sceneId, static _ => new SceneSharedValues());
|
||||
|
||||
public void Set(string name, SceneValue value)
|
||||
{
|
||||
name = TruncateUtf8(name, MaxNameBytes);
|
||||
if (value.Kind == SceneValueKind.String)
|
||||
value = SceneValue.FromString(TruncateUtf8(value.Text ?? string.Empty, MaxTextBytes));
|
||||
|
||||
lock (_gate)
|
||||
{
|
||||
if (value.Kind == SceneValueKind.Nil)
|
||||
_values.Remove(name);
|
||||
else
|
||||
_values[name] = value;
|
||||
}
|
||||
}
|
||||
|
||||
public SceneValue Get(string name)
|
||||
{
|
||||
name = TruncateUtf8(name, MaxNameBytes);
|
||||
lock (_gate)
|
||||
return _values.TryGetValue(name, out var value) ? value : SceneValue.Nil;
|
||||
}
|
||||
|
||||
private static string TruncateUtf8(string text, int maxBytes)
|
||||
{
|
||||
if (text.Length <= maxBytes / 3 || Encoding.UTF8.GetByteCount(text) <= maxBytes)
|
||||
return text;
|
||||
|
||||
int bytes = 0;
|
||||
int length = 0;
|
||||
while (length < text.Length)
|
||||
{
|
||||
char c = text[length];
|
||||
int size;
|
||||
int step = 1;
|
||||
if (char.IsHighSurrogate(c) && length + 1 < text.Length && char.IsLowSurrogate(text[length + 1]))
|
||||
{
|
||||
size = 4;
|
||||
step = 2;
|
||||
}
|
||||
else if (c < 0x80)
|
||||
{
|
||||
size = 1;
|
||||
}
|
||||
else if (c < 0x800)
|
||||
{
|
||||
size = 2;
|
||||
}
|
||||
else
|
||||
{
|
||||
size = 3;
|
||||
}
|
||||
if (bytes + size > maxBytes)
|
||||
break;
|
||||
bytes += size;
|
||||
length += step;
|
||||
}
|
||||
return text[..length];
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,54 @@
|
||||
using MoonSharp.Interpreter;
|
||||
|
||||
namespace LuaScript
|
||||
{
|
||||
internal static class SceneTableRegistrar
|
||||
{
|
||||
internal static void RegisterFunctions(Table scene, Func<string, SceneValue> getValue, Action<string, SceneValue> setValue)
|
||||
{
|
||||
scene["set"] = DynValue.NewCallback((_, args) =>
|
||||
{
|
||||
if (args.Count == 0 || args[0].Type != DataType.String)
|
||||
return DynValue.Void;
|
||||
|
||||
var value = args.Count > 1 ? args[1] : DynValue.Nil;
|
||||
SceneValue stored;
|
||||
switch (value.Type)
|
||||
{
|
||||
case DataType.Number:
|
||||
stored = SceneValue.FromNumber(value.Number);
|
||||
break;
|
||||
case DataType.String:
|
||||
stored = SceneValue.FromString(value.String);
|
||||
break;
|
||||
case DataType.Boolean:
|
||||
stored = SceneValue.FromBoolean(value.Boolean);
|
||||
break;
|
||||
case DataType.Nil:
|
||||
case DataType.Void:
|
||||
stored = SceneValue.Nil;
|
||||
break;
|
||||
default:
|
||||
return DynValue.Void;
|
||||
}
|
||||
setValue(args[0].String, stored);
|
||||
return DynValue.Void;
|
||||
});
|
||||
|
||||
scene["get"] = DynValue.NewCallback((_, args) =>
|
||||
{
|
||||
if (args.Count == 0 || args[0].Type != DataType.String)
|
||||
return DynValue.Nil;
|
||||
|
||||
var value = getValue(args[0].String);
|
||||
return value.Kind switch
|
||||
{
|
||||
SceneValueKind.Number => DynValue.NewNumber(value.Number),
|
||||
SceneValueKind.String => DynValue.NewString(value.Text ?? string.Empty),
|
||||
SceneValueKind.Boolean => value.Number != 0d ? DynValue.True : DynValue.False,
|
||||
_ => DynValue.Nil,
|
||||
};
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,154 @@
|
||||
using System;
|
||||
using System.Numerics;
|
||||
|
||||
namespace LuaScript
|
||||
{
|
||||
internal sealed class SoftwareCompositor : IBufferCompositor
|
||||
{
|
||||
public static readonly SoftwareCompositor Instance = new();
|
||||
|
||||
private SoftwareCompositor()
|
||||
{
|
||||
}
|
||||
|
||||
public bool TryCompose(byte[] dst, int dstW, int dstH, byte[] src, int srcW, int srcH, in DrawCommand command)
|
||||
{
|
||||
bool linear = command.Antialias != 0d;
|
||||
if (command.Poly is { } poly)
|
||||
DrawPolyInto(dst, dstW, dstH, src, srcW, srcH, poly, command.Alpha, linear);
|
||||
else
|
||||
DrawInto(dst, dstW, dstH, src, srcW, srcH, command.Ox, command.Oy, command.Zoom, command.Aspect, command.Alpha, linear);
|
||||
return true;
|
||||
}
|
||||
|
||||
public static void DrawInto(
|
||||
byte[] dst, int dstW, int dstH,
|
||||
byte[] src, int srcW, int srcH,
|
||||
double ox, double oy, double zoom, double aspect, double alpha, bool linear)
|
||||
{
|
||||
if (srcW <= 0 || srcH <= 0 || dstW <= 0 || dstH <= 0)
|
||||
return;
|
||||
|
||||
double clampedAspect = Math.Clamp(aspect, -1d, 1d);
|
||||
double zx = zoom * (1d + clampedAspect);
|
||||
double zy = zoom * (1d - clampedAspect);
|
||||
if (zx == 0d || zy == 0d)
|
||||
return;
|
||||
|
||||
double ka = Math.Clamp(alpha, 0d, 1d);
|
||||
if (ka <= 0d)
|
||||
return;
|
||||
|
||||
double halfW = srcW * 0.5;
|
||||
double halfH = srcH * 0.5;
|
||||
double spanX = Math.Abs(halfW * zx);
|
||||
double spanY = Math.Abs(halfH * zy);
|
||||
|
||||
int x0 = Math.Max(0, (int)Math.Floor(ox - spanX));
|
||||
int x1 = Math.Min(dstW - 1, (int)Math.Ceiling(ox + spanX));
|
||||
int y0 = Math.Max(0, (int)Math.Floor(oy - spanY));
|
||||
int y1 = Math.Min(dstH - 1, (int)Math.Ceiling(oy + spanY));
|
||||
|
||||
for (int py = y0; py <= y1; py++)
|
||||
{
|
||||
for (int px = x0; px <= x1; px++)
|
||||
{
|
||||
double u = (px + 0.5 - ox) / zx + halfW;
|
||||
double v = (py + 0.5 - oy) / zy + halfH;
|
||||
if (u < 0d || u >= srcW || v < 0d || v >= srcH)
|
||||
continue;
|
||||
|
||||
Sample(src, srcW, srcH, u, v, linear, out double sb, out double sg, out double sr, out double sa);
|
||||
CompositeOver(dst, (py * dstW + px) * 4, sb * ka, sg * ka, sr * ka, sa * ka);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
public static void DrawPolyInto(
|
||||
byte[] dst, int dstW, int dstH,
|
||||
byte[] src, int srcW, int srcH,
|
||||
double[] poly, double alpha, bool linear)
|
||||
{
|
||||
if (srcW <= 0 || srcH <= 0 || dstW <= 0 || dstH <= 0)
|
||||
return;
|
||||
if (!DrawPolyMath.TrySolveAffine(poly, out var forward))
|
||||
return;
|
||||
if (!Matrix3x2.Invert(forward, out var inverse))
|
||||
return;
|
||||
|
||||
double ka = Math.Clamp(alpha, 0d, 1d);
|
||||
if (ka <= 0d)
|
||||
return;
|
||||
|
||||
DrawPolyMath.Bounds(poly, out double minX, out double minY, out double maxX, out double maxY);
|
||||
int x0 = Math.Max(0, (int)Math.Floor(minX));
|
||||
int x1 = Math.Min(dstW - 1, (int)Math.Ceiling(maxX));
|
||||
int y0 = Math.Max(0, (int)Math.Floor(minY));
|
||||
int y1 = Math.Min(dstH - 1, (int)Math.Ceiling(maxY));
|
||||
|
||||
for (int py = y0; py <= y1; py++)
|
||||
{
|
||||
for (int px = x0; px <= x1; px++)
|
||||
{
|
||||
var uv = Vector2.Transform(new Vector2(px + 0.5f, py + 0.5f), inverse);
|
||||
double u = uv.X;
|
||||
double v = uv.Y;
|
||||
if (u < 0d || u >= srcW || v < 0d || v >= srcH)
|
||||
continue;
|
||||
|
||||
Sample(src, srcW, srcH, u, v, linear, out double sb, out double sg, out double sr, out double sa);
|
||||
CompositeOver(dst, (py * dstW + px) * 4, sb * ka, sg * ka, sr * ka, sa * ka);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private static void Sample(byte[] src, int srcW, int srcH, double u, double v, bool linear,
|
||||
out double b, out double g, out double r, out double a)
|
||||
{
|
||||
if (!linear)
|
||||
{
|
||||
int su = Math.Clamp((int)Math.Floor(u), 0, srcW - 1);
|
||||
int sv = Math.Clamp((int)Math.Floor(v), 0, srcH - 1);
|
||||
int si = (sv * srcW + su) * 4;
|
||||
b = src[si];
|
||||
g = src[si + 1];
|
||||
r = src[si + 2];
|
||||
a = src[si + 3];
|
||||
return;
|
||||
}
|
||||
|
||||
double fx = u - 0.5;
|
||||
double fy = v - 0.5;
|
||||
int x0 = (int)Math.Floor(fx);
|
||||
int y0 = (int)Math.Floor(fy);
|
||||
double tx = fx - x0;
|
||||
double ty = fy - y0;
|
||||
|
||||
b = g = r = a = 0d;
|
||||
for (int j = 0; j < 2; j++)
|
||||
{
|
||||
int sy = Math.Clamp(y0 + j, 0, srcH - 1);
|
||||
double wy = j == 0 ? 1d - ty : ty;
|
||||
for (int i = 0; i < 2; i++)
|
||||
{
|
||||
int sx = Math.Clamp(x0 + i, 0, srcW - 1);
|
||||
double w = wy * (i == 0 ? 1d - tx : tx);
|
||||
int si = (sy * srcW + sx) * 4;
|
||||
b += src[si] * w;
|
||||
g += src[si + 1] * w;
|
||||
r += src[si + 2] * w;
|
||||
a += src[si + 3] * w;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private static void CompositeOver(byte[] dst, int di, double sb, double sg, double sr, double sa)
|
||||
{
|
||||
double inv = 1d - sa / 255d;
|
||||
dst[di] = (byte)Math.Clamp(sb + dst[di] * inv, 0d, 255d);
|
||||
dst[di + 1] = (byte)Math.Clamp(sg + dst[di + 1] * inv, 0d, 255d);
|
||||
dst[di + 2] = (byte)Math.Clamp(sr + dst[di + 2] * inv, 0d, 255d);
|
||||
dst[di + 3] = (byte)Math.Clamp(sa + dst[di + 3] * inv, 0d, 255d);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,23 @@
|
||||
using System;
|
||||
using System.Threading;
|
||||
|
||||
namespace LuaScript
|
||||
{
|
||||
internal sealed class SynchronizedCompositor(IBufferCompositor inner, SemaphoreSlim gate) : IBufferCompositor, IDisposable
|
||||
{
|
||||
public bool TryCompose(byte[] dst, int dstW, int dstH, byte[] src, int srcW, int srcH, in DrawCommand command)
|
||||
{
|
||||
gate.Wait();
|
||||
try
|
||||
{
|
||||
return inner.TryCompose(dst, dstW, dstH, src, srcW, srcH, command);
|
||||
}
|
||||
finally
|
||||
{
|
||||
gate.Release();
|
||||
}
|
||||
}
|
||||
|
||||
public void Dispose() => (inner as IDisposable)?.Dispose();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,97 @@
|
||||
using System;
|
||||
using System.Numerics;
|
||||
using Vortice.Direct2D1;
|
||||
using Vortice.DirectWrite;
|
||||
using Vortice.Mathematics;
|
||||
using Vortice.WIC;
|
||||
|
||||
namespace LuaScript
|
||||
{
|
||||
internal sealed class TextRenderer : IDisposable
|
||||
{
|
||||
private const int MaxDimension = 8192;
|
||||
private const string FallbackFamily = "Yu Gothic UI";
|
||||
|
||||
private ID2D1Factory? _d2dFactory;
|
||||
private IWICImagingFactory? _wicFactory;
|
||||
private IDWriteFactory? _dwriteFactory;
|
||||
|
||||
private void EnsureFactories()
|
||||
{
|
||||
_d2dFactory ??= D2D1.D2D1CreateFactory<ID2D1Factory>(
|
||||
Vortice.Direct2D1.FactoryType.MultiThreaded, DebugLevel.None);
|
||||
_wicFactory ??= new IWICImagingFactory();
|
||||
_dwriteFactory ??= DWrite.DWriteCreateFactory<IDWriteFactory>(
|
||||
Vortice.DirectWrite.FactoryType.Shared);
|
||||
}
|
||||
|
||||
public unsafe byte[] Render(
|
||||
string text, string fontFamily, double fontSize,
|
||||
bool bold, bool italic, int colorRgb,
|
||||
out int width, out int height)
|
||||
{
|
||||
width = 1;
|
||||
height = 1;
|
||||
if (string.IsNullOrEmpty(text))
|
||||
return new byte[4];
|
||||
|
||||
EnsureFactories();
|
||||
|
||||
float size = (float)Math.Clamp(fontSize, 1d, 4096d);
|
||||
using var format = _dwriteFactory!.CreateTextFormat(
|
||||
string.IsNullOrWhiteSpace(fontFamily) ? FallbackFamily : fontFamily,
|
||||
null,
|
||||
bold ? FontWeight.Bold : FontWeight.Normal,
|
||||
italic ? FontStyle.Italic : FontStyle.Normal,
|
||||
FontStretch.Normal,
|
||||
size,
|
||||
string.Empty);
|
||||
|
||||
using var layout = _dwriteFactory.CreateTextLayout(text, format, MaxDimension, MaxDimension);
|
||||
var metrics = layout.Metrics;
|
||||
int w = Math.Clamp((int)Math.Ceiling(metrics.WidthIncludingTrailingWhitespace), 1, MaxDimension);
|
||||
int h = Math.Clamp((int)Math.Ceiling(metrics.Height), 1, MaxDimension);
|
||||
|
||||
using var wic = _wicFactory!.CreateBitmap(
|
||||
w, h, Vortice.WIC.PixelFormat.Format32bppPBGRA, BitmapCreateCacheOption.CacheOnLoad);
|
||||
|
||||
var properties = new RenderTargetProperties(
|
||||
RenderTargetType.Default,
|
||||
new Vortice.DCommon.PixelFormat(Vortice.DXGI.Format.B8G8R8A8_UNorm, Vortice.DCommon.AlphaMode.Premultiplied),
|
||||
96f, 96f,
|
||||
RenderTargetUsage.None,
|
||||
FeatureLevel.Default);
|
||||
|
||||
float r = ((colorRgb >> 16) & 0xFF) / 255f;
|
||||
float g = ((colorRgb >> 8) & 0xFF) / 255f;
|
||||
float b = (colorRgb & 0xFF) / 255f;
|
||||
|
||||
using (var target = _d2dFactory!.CreateWicBitmapRenderTarget(wic, properties))
|
||||
{
|
||||
target.BeginDraw();
|
||||
target.Clear(new Color4(0f, 0f, 0f, 0f));
|
||||
using (var brush = target.CreateSolidColorBrush(new Color4(r, g, b, 1f)))
|
||||
target.DrawTextLayout(new Vector2(-metrics.Left, -metrics.Top), layout, brush);
|
||||
target.EndDraw();
|
||||
}
|
||||
|
||||
var buffer = new byte[w * h * 4];
|
||||
fixed (byte* p = buffer)
|
||||
wic.CopyPixels(new RectI(0, 0, w, h), w * 4, buffer.Length, (nint)p);
|
||||
|
||||
width = w;
|
||||
height = h;
|
||||
return buffer;
|
||||
}
|
||||
|
||||
public void Dispose()
|
||||
{
|
||||
_dwriteFactory?.Dispose();
|
||||
_wicFactory?.Dispose();
|
||||
_d2dFactory?.Dispose();
|
||||
_dwriteFactory = null;
|
||||
_wicFactory = null;
|
||||
_d2dFactory = null;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -69,6 +69,11 @@
|
||||
<data name="Track2" xml:space="preserve"><value>مسار 2</value></data>
|
||||
<data name="Track3" xml:space="preserve"><value>مسار 3</value></data>
|
||||
<data name="TrackDesc" xml:space="preserve"><value>قيمة المنزلق (متوافق مع AviUtl: track0-3)</value></data>
|
||||
<data name="Slider0" xml:space="preserve"><value>منزلق 0</value></data>
|
||||
<data name="Slider1" xml:space="preserve"><value>منزلق 1</value></data>
|
||||
<data name="Slider2" xml:space="preserve"><value>منزلق 2</value></data>
|
||||
<data name="Slider3" xml:space="preserve"><value>منزلق 3</value></data>
|
||||
<data name="SliderDesc" xml:space="preserve"><value>منزلق رقمي (obj.slider0-3)</value></data>
|
||||
<data name="Check0" xml:space="preserve"><value>خانة 0</value></data>
|
||||
<data name="Check1" xml:space="preserve"><value>خانة 1</value></data>
|
||||
<data name="Check2" xml:space="preserve"><value>خانة 2</value></data>
|
||||
@@ -76,6 +81,21 @@
|
||||
<data name="CheckDesc" xml:space="preserve"><value>قيمة خانة الاختيار (متوافق مع AviUtl: check0-3)</value></data>
|
||||
<data name="Color" xml:space="preserve"><value>اللون</value></data>
|
||||
<data name="ColorDesc" xml:space="preserve"><value>اللون (متوافق مع AviUtl: --color)</value></data>
|
||||
<data name="Text" xml:space="preserve"><value>نص</value></data>
|
||||
<data name="TextDesc" xml:space="preserve"><value>إدخال نص (obj.text)</value></data>
|
||||
<data name="Font" xml:space="preserve"><value>خط</value></data>
|
||||
<data name="FontDesc" xml:space="preserve"><value>اختيار الخط (obj.font)</value></data>
|
||||
<data name="Directory" xml:space="preserve"><value>مجلد</value></data>
|
||||
<data name="DirectoryDesc" xml:space="preserve"><value>اختيار المجلد (obj.dir)</value></data>
|
||||
<data name="FileDesc" xml:space="preserve"><value>اختيار الملف (obj.file_*)</value></data>
|
||||
<data name="FileVideo" xml:space="preserve"><value>ملف فيديو</value></data>
|
||||
<data name="FileAudio" xml:space="preserve"><value>ملف صوتي</value></data>
|
||||
<data name="FileImage" xml:space="preserve"><value>ملف صورة</value></data>
|
||||
<data name="FileProject" xml:space="preserve"><value>ملف المشروع</value></data>
|
||||
<data name="FileMp4" xml:space="preserve"><value>ملف MP4</value></data>
|
||||
<data name="FileExo" xml:space="preserve"><value>ملف EXO</value></data>
|
||||
<data name="FileSubtitle" xml:space="preserve"><value>ملف الترجمة</value></data>
|
||||
<data name="FileShader" xml:space="preserve"><value>ملف التظليل</value></data>
|
||||
<data name="ToolBarImport" xml:space="preserve"><value>استيراد</value></data>
|
||||
<data name="ToolBarExport" xml:space="preserve"><value>تصدير</value></data>
|
||||
<data name="ToolBarClear" xml:space="preserve"><value>مسح</value></data>
|
||||
@@ -84,4 +104,7 @@
|
||||
<data name="ToolBarImportErrorTitle" xml:space="preserve"><value>خطأ في الاستيراد</value></data>
|
||||
<data name="ToolBarExportErrorTitle" xml:space="preserve"><value>خطأ في التصدير</value></data>
|
||||
<data name="LuaFileFilter" xml:space="preserve"><value>نص Lua (*.lua)|*.lua|جميع الملفات (*.*)|*.*</value></data>
|
||||
<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>
|
||||
</root>
|
||||
@@ -9,6 +9,11 @@ Track1,,トラック1,Track 1,轨道1,軌道1,트랙1,Pista 1,مسار 1,Jalur 1
|
||||
Track2,,トラック2,Track 2,轨道2,軌道2,트랙2,Pista 2,مسار 2,Jalur 2
|
||||
Track3,,トラック3,Track 3,轨道3,軌道3,트랙3,Pista 3,مسار 3,Jalur 3
|
||||
TrackDesc,,スライダー値 (AviUtl準拠 track0〜3 に対応),Slider value (AviUtl compatible: track0–3),滑块值(AviUtl兼容: track0~3),滑塊值(AviUtl兼容: track0~3),슬라이더 값 (AviUtl 호환: track0~3),Valor del deslizador (compatible AviUtl: track0-3),قيمة المنزلق (متوافق مع AviUtl: track0-3),Nilai slider (kompatibel AviUtl: track0-3)
|
||||
Slider0,,スライダー0,Slider 0,滑块0,滑塊0,슬라이더0,Deslizador 0,منزلق 0,Slider 0
|
||||
Slider1,,スライダー1,Slider 1,滑块1,滑塊1,슬라이더1,Deslizador 1,منزلق 1,Slider 1
|
||||
Slider2,,スライダー2,Slider 2,滑块2,滑塊2,슬라이더2,Deslizador 2,منزلق 2,Slider 2
|
||||
Slider3,,スライダー3,Slider 3,滑块3,滑塊3,슬라이더3,Deslizador 3,منزلق 3,Slider 3
|
||||
SliderDesc,,数値スライダー (obj.slider0〜3 で参照),Numeric slider (obj.slider0–3),数值滑块 (obj.slider0~3),數值滑塊 (obj.slider0~3),숫자 슬라이더 (obj.slider0~3),Deslizador numérico (obj.slider0-3),منزلق رقمي (obj.slider0-3),Slider numerik (obj.slider0-3)
|
||||
Check0,,チェック0,Check 0,复选框0,核取方塊0,체크0,Casilla 0,خانة 0,Centang 0
|
||||
Check1,,チェック1,Check 1,复选框1,核取方塊1,체크1,Casilla 1,خانة 1,Centang 1
|
||||
Check2,,チェック2,Check 2,复选框2,核取方塊2,체크2,Casilla 2,خانة 2,Centang 2
|
||||
@@ -16,6 +21,21 @@ Check3,,チェック3,Check 3,复选框3,核取方塊3,체크3,Casilla 3,خان
|
||||
CheckDesc,,チェックボックス値 (AviUtl準拠 check0〜3 に対応),Checkbox value (AviUtl compatible: check0–3),复选框值(AviUtl兼容: check0~3),核取方塊值(AviUtl兼容: check0~3),체크박스 값 (AviUtl 호환: check0~3),Valor de casilla (compatible AviUtl: check0-3),قيمة خانة الاختيار (متوافق مع AviUtl: check0-3),Nilai kotak centang (kompatibel AviUtl: check0-3)
|
||||
Color,,色,Color,颜色,顏色,색,Color,اللون,Warna
|
||||
ColorDesc,,色 (AviUtl準拠 --color に対応),Color (AviUtl compatible: --color),颜色(AviUtl兼容: --color),顏色(AviUtl兼容: --color),색 (AviUtl 호환: --color),Color (compatible AviUtl: --color),اللون (متوافق مع AviUtl: --color),Warna (kompatibel AviUtl: --color)
|
||||
Text,,テキスト,Text,文本,文字,텍스트,Texto,نص,Teks
|
||||
TextDesc,,テキスト入力 (obj.text で参照),Text input (obj.text),文本输入 (obj.text),文字輸入 (obj.text),텍스트 입력 (obj.text),Entrada de texto (obj.text),إدخال نص (obj.text),Masukan teks (obj.text)
|
||||
Font,,フォント,Font,字体,字型,글꼴,Fuente,خط,Font
|
||||
FontDesc,,フォント選択 (obj.font で参照),Font selection (obj.font),字体选择 (obj.font),字型選擇 (obj.font),글꼴 선택 (obj.font),Selección de fuente (obj.font),اختيار الخط (obj.font),Pilihan font (obj.font)
|
||||
Directory,,フォルダ,Folder,文件夹,資料夾,폴더,Carpeta,مجلد,Folder
|
||||
DirectoryDesc,,フォルダ選択 (obj.dir で参照),Folder selection (obj.dir),文件夹选择 (obj.dir),資料夾選擇 (obj.dir),폴더 선택 (obj.dir),Selección de carpeta (obj.dir),اختيار المجلد (obj.dir),Pilihan folder (obj.dir)
|
||||
FileDesc,,ファイル選択 (obj.file_* で参照),File selection (obj.file_*),文件选择 (obj.file_*),檔案選擇 (obj.file_*),파일 선택 (obj.file_*),Selección de archivo (obj.file_*),اختيار الملف (obj.file_*),Pilihan file (obj.file_*)
|
||||
FileVideo,,動画ファイル,Video File,视频文件,影片檔案,동영상 파일,Archivo de video,ملف فيديو,File Video
|
||||
FileAudio,,音声ファイル,Audio File,音频文件,音訊檔案,음성 파일,Archivo de audio,ملف صوتي,File Audio
|
||||
FileImage,,画像ファイル,Image File,图像文件,圖片檔案,이미지 파일,Archivo de imagen,ملف صورة,File Gambar
|
||||
FileProject,,プロジェクトファイル,Project File,项目文件,專案檔案,프로젝트 파일,Archivo de proyecto,ملف المشروع,File Proyek
|
||||
FileMp4,,MP4ファイル,MP4 File,MP4文件,MP4檔案,MP4 파일,Archivo MP4,ملف MP4,File MP4
|
||||
FileExo,,EXOファイル,EXO File,EXO文件,EXO檔案,EXO 파일,Archivo EXO,ملف EXO,File EXO
|
||||
FileSubtitle,,字幕ファイル,Subtitle File,字幕文件,字幕檔案,자막 파일,Archivo de subtítulos,ملف الترجمة,File Subtitle
|
||||
FileShader,,シェーダーファイル,Shader File,着色器文件,著色器檔案,셰이더 파일,Archivo de sombreador,ملف التظليل,File Shader
|
||||
ToolBarImport,,インポート,Import,导入,導入,가져오기,Importar,استيراد,Impor
|
||||
ToolBarExport,,エクスポート,Export,导出,導出,내보내기,Exportar,تصدير,Ekspor
|
||||
ToolBarClear,,クリア,Clear,清除,清除,지우기,Limpiar,مسح,Hapus
|
||||
@@ -24,3 +44,6 @@ ToolBarClearTitle,,確認,Confirm,确认,確認,확인,Confirmar,تأكيد,Konf
|
||||
ToolBarImportErrorTitle,,インポートエラー,Import Error,导入错误,導入錯誤,가져오기 오류,Error de importación,خطأ في الاستيراد,Kesalahan impor
|
||||
ToolBarExportErrorTitle,,エクスポートエラー,Export Error,导出错误,導出錯誤,내보내기 오류,Error de exportación,خطأ في التصدير,Kesalahan ekspor
|
||||
LuaFileFilter,,Luaスクリプト (*.lua)|*.lua|すべてのファイル (*.*)|*.*,Lua Script (*.lua)|*.lua|All Files (*.*)|*.*,Lua脚本 (*.lua)|*.lua|所有文件 (*.*)|*.*,Lua腳本 (*.lua)|*.lua|所有檔案 (*.*)|*.*,Lua 스크립트 (*.lua)|*.lua|모든 파일 (*.*)|*.*,Script Lua (*.lua)|*.lua|Todos los archivos (*.*)|*.*,نص Lua (*.lua)|*.lua|جميع الملفات (*.*)|*.*,Skrip Lua (*.lua)|*.lua|Semua File (*.*)|*.*
|
||||
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
|
||||
|
@@ -69,6 +69,11 @@
|
||||
<data name="Track2" xml:space="preserve"><value>Track 2</value></data>
|
||||
<data name="Track3" xml:space="preserve"><value>Track 3</value></data>
|
||||
<data name="TrackDesc" xml:space="preserve"><value>Slider value (AviUtl compatible: track0–3)</value></data>
|
||||
<data name="Slider0" xml:space="preserve"><value>Slider 0</value></data>
|
||||
<data name="Slider1" xml:space="preserve"><value>Slider 1</value></data>
|
||||
<data name="Slider2" xml:space="preserve"><value>Slider 2</value></data>
|
||||
<data name="Slider3" xml:space="preserve"><value>Slider 3</value></data>
|
||||
<data name="SliderDesc" xml:space="preserve"><value>Numeric slider (obj.slider0–3)</value></data>
|
||||
<data name="Check0" xml:space="preserve"><value>Check 0</value></data>
|
||||
<data name="Check1" xml:space="preserve"><value>Check 1</value></data>
|
||||
<data name="Check2" xml:space="preserve"><value>Check 2</value></data>
|
||||
@@ -76,6 +81,21 @@
|
||||
<data name="CheckDesc" xml:space="preserve"><value>Checkbox value (AviUtl compatible: check0–3)</value></data>
|
||||
<data name="Color" xml:space="preserve"><value>Color</value></data>
|
||||
<data name="ColorDesc" xml:space="preserve"><value>Color (AviUtl compatible: --color)</value></data>
|
||||
<data name="Text" xml:space="preserve"><value>Text</value></data>
|
||||
<data name="TextDesc" xml:space="preserve"><value>Text input (obj.text)</value></data>
|
||||
<data name="Font" xml:space="preserve"><value>Font</value></data>
|
||||
<data name="FontDesc" xml:space="preserve"><value>Font selection (obj.font)</value></data>
|
||||
<data name="Directory" xml:space="preserve"><value>Folder</value></data>
|
||||
<data name="DirectoryDesc" xml:space="preserve"><value>Folder selection (obj.dir)</value></data>
|
||||
<data name="FileDesc" xml:space="preserve"><value>File selection (obj.file_*)</value></data>
|
||||
<data name="FileVideo" xml:space="preserve"><value>Video File</value></data>
|
||||
<data name="FileAudio" xml:space="preserve"><value>Audio File</value></data>
|
||||
<data name="FileImage" xml:space="preserve"><value>Image File</value></data>
|
||||
<data name="FileProject" xml:space="preserve"><value>Project File</value></data>
|
||||
<data name="FileMp4" xml:space="preserve"><value>MP4 File</value></data>
|
||||
<data name="FileExo" xml:space="preserve"><value>EXO File</value></data>
|
||||
<data name="FileSubtitle" xml:space="preserve"><value>Subtitle File</value></data>
|
||||
<data name="FileShader" xml:space="preserve"><value>Shader File</value></data>
|
||||
<data name="ToolBarImport" xml:space="preserve"><value>Import</value></data>
|
||||
<data name="ToolBarExport" xml:space="preserve"><value>Export</value></data>
|
||||
<data name="ToolBarClear" xml:space="preserve"><value>Clear</value></data>
|
||||
@@ -84,4 +104,7 @@
|
||||
<data name="ToolBarImportErrorTitle" xml:space="preserve"><value>Import Error</value></data>
|
||||
<data name="ToolBarExportErrorTitle" xml:space="preserve"><value>Export Error</value></data>
|
||||
<data name="LuaFileFilter" xml:space="preserve"><value>Lua Script (*.lua)|*.lua|All Files (*.*)|*.*</value></data>
|
||||
<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>
|
||||
</root>
|
||||
@@ -69,6 +69,11 @@
|
||||
<data name="Track2" xml:space="preserve"><value>Pista 2</value></data>
|
||||
<data name="Track3" xml:space="preserve"><value>Pista 3</value></data>
|
||||
<data name="TrackDesc" xml:space="preserve"><value>Valor del deslizador (compatible AviUtl: track0-3)</value></data>
|
||||
<data name="Slider0" xml:space="preserve"><value>Deslizador 0</value></data>
|
||||
<data name="Slider1" xml:space="preserve"><value>Deslizador 1</value></data>
|
||||
<data name="Slider2" xml:space="preserve"><value>Deslizador 2</value></data>
|
||||
<data name="Slider3" xml:space="preserve"><value>Deslizador 3</value></data>
|
||||
<data name="SliderDesc" xml:space="preserve"><value>Deslizador numérico (obj.slider0-3)</value></data>
|
||||
<data name="Check0" xml:space="preserve"><value>Casilla 0</value></data>
|
||||
<data name="Check1" xml:space="preserve"><value>Casilla 1</value></data>
|
||||
<data name="Check2" xml:space="preserve"><value>Casilla 2</value></data>
|
||||
@@ -76,6 +81,21 @@
|
||||
<data name="CheckDesc" xml:space="preserve"><value>Valor de casilla (compatible AviUtl: check0-3)</value></data>
|
||||
<data name="Color" xml:space="preserve"><value>Color</value></data>
|
||||
<data name="ColorDesc" xml:space="preserve"><value>Color (compatible AviUtl: --color)</value></data>
|
||||
<data name="Text" xml:space="preserve"><value>Texto</value></data>
|
||||
<data name="TextDesc" xml:space="preserve"><value>Entrada de texto (obj.text)</value></data>
|
||||
<data name="Font" xml:space="preserve"><value>Fuente</value></data>
|
||||
<data name="FontDesc" xml:space="preserve"><value>Selección de fuente (obj.font)</value></data>
|
||||
<data name="Directory" xml:space="preserve"><value>Carpeta</value></data>
|
||||
<data name="DirectoryDesc" xml:space="preserve"><value>Selección de carpeta (obj.dir)</value></data>
|
||||
<data name="FileDesc" xml:space="preserve"><value>Selección de archivo (obj.file_*)</value></data>
|
||||
<data name="FileVideo" xml:space="preserve"><value>Archivo de video</value></data>
|
||||
<data name="FileAudio" xml:space="preserve"><value>Archivo de audio</value></data>
|
||||
<data name="FileImage" xml:space="preserve"><value>Archivo de imagen</value></data>
|
||||
<data name="FileProject" xml:space="preserve"><value>Archivo de proyecto</value></data>
|
||||
<data name="FileMp4" xml:space="preserve"><value>Archivo MP4</value></data>
|
||||
<data name="FileExo" xml:space="preserve"><value>Archivo EXO</value></data>
|
||||
<data name="FileSubtitle" xml:space="preserve"><value>Archivo de subtítulos</value></data>
|
||||
<data name="FileShader" xml:space="preserve"><value>Archivo de sombreador</value></data>
|
||||
<data name="ToolBarImport" xml:space="preserve"><value>Importar</value></data>
|
||||
<data name="ToolBarExport" xml:space="preserve"><value>Exportar</value></data>
|
||||
<data name="ToolBarClear" xml:space="preserve"><value>Limpiar</value></data>
|
||||
@@ -84,4 +104,7 @@
|
||||
<data name="ToolBarImportErrorTitle" xml:space="preserve"><value>Error de importación</value></data>
|
||||
<data name="ToolBarExportErrorTitle" xml:space="preserve"><value>Error de exportación</value></data>
|
||||
<data name="LuaFileFilter" xml:space="preserve"><value>Script Lua (*.lua)|*.lua|Todos los archivos (*.*)|*.*</value></data>
|
||||
<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>
|
||||
</root>
|
||||
@@ -69,6 +69,11 @@
|
||||
<data name="Track2" xml:space="preserve"><value>Jalur 2</value></data>
|
||||
<data name="Track3" xml:space="preserve"><value>Jalur 3</value></data>
|
||||
<data name="TrackDesc" xml:space="preserve"><value>Nilai slider (kompatibel AviUtl: track0-3)</value></data>
|
||||
<data name="Slider0" xml:space="preserve"><value>Slider 0</value></data>
|
||||
<data name="Slider1" xml:space="preserve"><value>Slider 1</value></data>
|
||||
<data name="Slider2" xml:space="preserve"><value>Slider 2</value></data>
|
||||
<data name="Slider3" xml:space="preserve"><value>Slider 3</value></data>
|
||||
<data name="SliderDesc" xml:space="preserve"><value>Slider numerik (obj.slider0-3)</value></data>
|
||||
<data name="Check0" xml:space="preserve"><value>Centang 0</value></data>
|
||||
<data name="Check1" xml:space="preserve"><value>Centang 1</value></data>
|
||||
<data name="Check2" xml:space="preserve"><value>Centang 2</value></data>
|
||||
@@ -76,6 +81,21 @@
|
||||
<data name="CheckDesc" xml:space="preserve"><value>Nilai kotak centang (kompatibel AviUtl: check0-3)</value></data>
|
||||
<data name="Color" xml:space="preserve"><value>Warna</value></data>
|
||||
<data name="ColorDesc" xml:space="preserve"><value>Warna (kompatibel AviUtl: --color)</value></data>
|
||||
<data name="Text" xml:space="preserve"><value>Teks</value></data>
|
||||
<data name="TextDesc" xml:space="preserve"><value>Masukan teks (obj.text)</value></data>
|
||||
<data name="Font" xml:space="preserve"><value>Font</value></data>
|
||||
<data name="FontDesc" xml:space="preserve"><value>Pilihan font (obj.font)</value></data>
|
||||
<data name="Directory" xml:space="preserve"><value>Folder</value></data>
|
||||
<data name="DirectoryDesc" xml:space="preserve"><value>Pilihan folder (obj.dir)</value></data>
|
||||
<data name="FileDesc" xml:space="preserve"><value>Pilihan file (obj.file_*)</value></data>
|
||||
<data name="FileVideo" xml:space="preserve"><value>File Video</value></data>
|
||||
<data name="FileAudio" xml:space="preserve"><value>File Audio</value></data>
|
||||
<data name="FileImage" xml:space="preserve"><value>File Gambar</value></data>
|
||||
<data name="FileProject" xml:space="preserve"><value>File Proyek</value></data>
|
||||
<data name="FileMp4" xml:space="preserve"><value>File MP4</value></data>
|
||||
<data name="FileExo" xml:space="preserve"><value>File EXO</value></data>
|
||||
<data name="FileSubtitle" xml:space="preserve"><value>File Subtitle</value></data>
|
||||
<data name="FileShader" xml:space="preserve"><value>File Shader</value></data>
|
||||
<data name="ToolBarImport" xml:space="preserve"><value>Impor</value></data>
|
||||
<data name="ToolBarExport" xml:space="preserve"><value>Ekspor</value></data>
|
||||
<data name="ToolBarClear" xml:space="preserve"><value>Hapus</value></data>
|
||||
@@ -84,4 +104,7 @@
|
||||
<data name="ToolBarImportErrorTitle" xml:space="preserve"><value>Kesalahan impor</value></data>
|
||||
<data name="ToolBarExportErrorTitle" xml:space="preserve"><value>Kesalahan ekspor</value></data>
|
||||
<data name="LuaFileFilter" xml:space="preserve"><value>Skrip Lua (*.lua)|*.lua|Semua File (*.*)|*.*</value></data>
|
||||
<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>
|
||||
</root>
|
||||
@@ -69,6 +69,11 @@
|
||||
<data name="Track2" xml:space="preserve"><value>트랙2</value></data>
|
||||
<data name="Track3" xml:space="preserve"><value>트랙3</value></data>
|
||||
<data name="TrackDesc" xml:space="preserve"><value>슬라이더 값 (AviUtl 호환: track0~3)</value></data>
|
||||
<data name="Slider0" xml:space="preserve"><value>슬라이더0</value></data>
|
||||
<data name="Slider1" xml:space="preserve"><value>슬라이더1</value></data>
|
||||
<data name="Slider2" xml:space="preserve"><value>슬라이더2</value></data>
|
||||
<data name="Slider3" xml:space="preserve"><value>슬라이더3</value></data>
|
||||
<data name="SliderDesc" xml:space="preserve"><value>숫자 슬라이더 (obj.slider0~3)</value></data>
|
||||
<data name="Check0" xml:space="preserve"><value>체크0</value></data>
|
||||
<data name="Check1" xml:space="preserve"><value>체크1</value></data>
|
||||
<data name="Check2" xml:space="preserve"><value>체크2</value></data>
|
||||
@@ -76,6 +81,21 @@
|
||||
<data name="CheckDesc" xml:space="preserve"><value>체크박스 값 (AviUtl 호환: check0~3)</value></data>
|
||||
<data name="Color" xml:space="preserve"><value>색</value></data>
|
||||
<data name="ColorDesc" xml:space="preserve"><value>색 (AviUtl 호환: --color)</value></data>
|
||||
<data name="Text" xml:space="preserve"><value>텍스트</value></data>
|
||||
<data name="TextDesc" xml:space="preserve"><value>텍스트 입력 (obj.text)</value></data>
|
||||
<data name="Font" xml:space="preserve"><value>글꼴</value></data>
|
||||
<data name="FontDesc" xml:space="preserve"><value>글꼴 선택 (obj.font)</value></data>
|
||||
<data name="Directory" xml:space="preserve"><value>폴더</value></data>
|
||||
<data name="DirectoryDesc" xml:space="preserve"><value>폴더 선택 (obj.dir)</value></data>
|
||||
<data name="FileDesc" xml:space="preserve"><value>파일 선택 (obj.file_*)</value></data>
|
||||
<data name="FileVideo" xml:space="preserve"><value>동영상 파일</value></data>
|
||||
<data name="FileAudio" xml:space="preserve"><value>음성 파일</value></data>
|
||||
<data name="FileImage" xml:space="preserve"><value>이미지 파일</value></data>
|
||||
<data name="FileProject" xml:space="preserve"><value>프로젝트 파일</value></data>
|
||||
<data name="FileMp4" xml:space="preserve"><value>MP4 파일</value></data>
|
||||
<data name="FileExo" xml:space="preserve"><value>EXO 파일</value></data>
|
||||
<data name="FileSubtitle" xml:space="preserve"><value>자막 파일</value></data>
|
||||
<data name="FileShader" xml:space="preserve"><value>셰이더 파일</value></data>
|
||||
<data name="ToolBarImport" xml:space="preserve"><value>가져오기</value></data>
|
||||
<data name="ToolBarExport" xml:space="preserve"><value>내보내기</value></data>
|
||||
<data name="ToolBarClear" xml:space="preserve"><value>지우기</value></data>
|
||||
@@ -84,4 +104,7 @@
|
||||
<data name="ToolBarImportErrorTitle" xml:space="preserve"><value>가져오기 오류</value></data>
|
||||
<data name="ToolBarExportErrorTitle" xml:space="preserve"><value>내보내기 오류</value></data>
|
||||
<data name="LuaFileFilter" xml:space="preserve"><value>Lua 스크립트 (*.lua)|*.lua|모든 파일 (*.*)|*.*</value></data>
|
||||
<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>
|
||||
</root>
|
||||
@@ -69,6 +69,11 @@
|
||||
<data name="Track2" xml:space="preserve"><value>トラック2</value></data>
|
||||
<data name="Track3" xml:space="preserve"><value>トラック3</value></data>
|
||||
<data name="TrackDesc" xml:space="preserve"><value>スライダー値 (AviUtl準拠 track0〜3 に対応)</value></data>
|
||||
<data name="Slider0" xml:space="preserve"><value>スライダー0</value></data>
|
||||
<data name="Slider1" xml:space="preserve"><value>スライダー1</value></data>
|
||||
<data name="Slider2" xml:space="preserve"><value>スライダー2</value></data>
|
||||
<data name="Slider3" xml:space="preserve"><value>スライダー3</value></data>
|
||||
<data name="SliderDesc" xml:space="preserve"><value>数値スライダー (obj.slider0〜3 で参照)</value></data>
|
||||
<data name="Check0" xml:space="preserve"><value>チェック0</value></data>
|
||||
<data name="Check1" xml:space="preserve"><value>チェック1</value></data>
|
||||
<data name="Check2" xml:space="preserve"><value>チェック2</value></data>
|
||||
@@ -76,6 +81,21 @@
|
||||
<data name="CheckDesc" xml:space="preserve"><value>チェックボックス値 (AviUtl準拠 check0〜3 に対応)</value></data>
|
||||
<data name="Color" xml:space="preserve"><value>色</value></data>
|
||||
<data name="ColorDesc" xml:space="preserve"><value>色 (AviUtl準拠 --color に対応)</value></data>
|
||||
<data name="Text" xml:space="preserve"><value>テキスト</value></data>
|
||||
<data name="TextDesc" xml:space="preserve"><value>テキスト入力 (obj.text で参照)</value></data>
|
||||
<data name="Font" xml:space="preserve"><value>フォント</value></data>
|
||||
<data name="FontDesc" xml:space="preserve"><value>フォント選択 (obj.font で参照)</value></data>
|
||||
<data name="Directory" xml:space="preserve"><value>フォルダ</value></data>
|
||||
<data name="DirectoryDesc" xml:space="preserve"><value>フォルダ選択 (obj.dir で参照)</value></data>
|
||||
<data name="FileDesc" xml:space="preserve"><value>ファイル選択 (obj.file_* で参照)</value></data>
|
||||
<data name="FileVideo" xml:space="preserve"><value>動画ファイル</value></data>
|
||||
<data name="FileAudio" xml:space="preserve"><value>音声ファイル</value></data>
|
||||
<data name="FileImage" xml:space="preserve"><value>画像ファイル</value></data>
|
||||
<data name="FileProject" xml:space="preserve"><value>プロジェクトファイル</value></data>
|
||||
<data name="FileMp4" xml:space="preserve"><value>MP4ファイル</value></data>
|
||||
<data name="FileExo" xml:space="preserve"><value>EXOファイル</value></data>
|
||||
<data name="FileSubtitle" xml:space="preserve"><value>字幕ファイル</value></data>
|
||||
<data name="FileShader" xml:space="preserve"><value>シェーダーファイル</value></data>
|
||||
<data name="ToolBarImport" xml:space="preserve"><value>インポート</value></data>
|
||||
<data name="ToolBarExport" xml:space="preserve"><value>エクスポート</value></data>
|
||||
<data name="ToolBarClear" xml:space="preserve"><value>クリア</value></data>
|
||||
@@ -84,4 +104,7 @@
|
||||
<data name="ToolBarImportErrorTitle" xml:space="preserve"><value>インポートエラー</value></data>
|
||||
<data name="ToolBarExportErrorTitle" xml:space="preserve"><value>エクスポートエラー</value></data>
|
||||
<data name="LuaFileFilter" xml:space="preserve"><value>Luaスクリプト (*.lua)|*.lua|すべてのファイル (*.*)|*.*</value></data>
|
||||
<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>
|
||||
</root>
|
||||
@@ -69,6 +69,11 @@
|
||||
<data name="Track2" xml:space="preserve"><value>轨道2</value></data>
|
||||
<data name="Track3" xml:space="preserve"><value>轨道3</value></data>
|
||||
<data name="TrackDesc" xml:space="preserve"><value>滑块值(AviUtl兼容: track0~3)</value></data>
|
||||
<data name="Slider0" xml:space="preserve"><value>滑块0</value></data>
|
||||
<data name="Slider1" xml:space="preserve"><value>滑块1</value></data>
|
||||
<data name="Slider2" xml:space="preserve"><value>滑块2</value></data>
|
||||
<data name="Slider3" xml:space="preserve"><value>滑块3</value></data>
|
||||
<data name="SliderDesc" xml:space="preserve"><value>数值滑块 (obj.slider0~3)</value></data>
|
||||
<data name="Check0" xml:space="preserve"><value>复选框0</value></data>
|
||||
<data name="Check1" xml:space="preserve"><value>复选框1</value></data>
|
||||
<data name="Check2" xml:space="preserve"><value>复选框2</value></data>
|
||||
@@ -76,6 +81,21 @@
|
||||
<data name="CheckDesc" xml:space="preserve"><value>复选框值(AviUtl兼容: check0~3)</value></data>
|
||||
<data name="Color" xml:space="preserve"><value>颜色</value></data>
|
||||
<data name="ColorDesc" xml:space="preserve"><value>颜色(AviUtl兼容: --color)</value></data>
|
||||
<data name="Text" xml:space="preserve"><value>文本</value></data>
|
||||
<data name="TextDesc" xml:space="preserve"><value>文本输入 (obj.text)</value></data>
|
||||
<data name="Font" xml:space="preserve"><value>字体</value></data>
|
||||
<data name="FontDesc" xml:space="preserve"><value>字体选择 (obj.font)</value></data>
|
||||
<data name="Directory" xml:space="preserve"><value>文件夹</value></data>
|
||||
<data name="DirectoryDesc" xml:space="preserve"><value>文件夹选择 (obj.dir)</value></data>
|
||||
<data name="FileDesc" xml:space="preserve"><value>文件选择 (obj.file_*)</value></data>
|
||||
<data name="FileVideo" xml:space="preserve"><value>视频文件</value></data>
|
||||
<data name="FileAudio" xml:space="preserve"><value>音频文件</value></data>
|
||||
<data name="FileImage" xml:space="preserve"><value>图像文件</value></data>
|
||||
<data name="FileProject" xml:space="preserve"><value>项目文件</value></data>
|
||||
<data name="FileMp4" xml:space="preserve"><value>MP4文件</value></data>
|
||||
<data name="FileExo" xml:space="preserve"><value>EXO文件</value></data>
|
||||
<data name="FileSubtitle" xml:space="preserve"><value>字幕文件</value></data>
|
||||
<data name="FileShader" xml:space="preserve"><value>着色器文件</value></data>
|
||||
<data name="ToolBarImport" xml:space="preserve"><value>导入</value></data>
|
||||
<data name="ToolBarExport" xml:space="preserve"><value>导出</value></data>
|
||||
<data name="ToolBarClear" xml:space="preserve"><value>清除</value></data>
|
||||
@@ -84,4 +104,7 @@
|
||||
<data name="ToolBarImportErrorTitle" xml:space="preserve"><value>导入错误</value></data>
|
||||
<data name="ToolBarExportErrorTitle" xml:space="preserve"><value>导出错误</value></data>
|
||||
<data name="LuaFileFilter" xml:space="preserve"><value>Lua脚本 (*.lua)|*.lua|所有文件 (*.*)|*.*</value></data>
|
||||
<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>
|
||||
</root>
|
||||
@@ -69,6 +69,11 @@
|
||||
<data name="Track2" xml:space="preserve"><value>軌道2</value></data>
|
||||
<data name="Track3" xml:space="preserve"><value>軌道3</value></data>
|
||||
<data name="TrackDesc" xml:space="preserve"><value>滑塊值(AviUtl兼容: track0~3)</value></data>
|
||||
<data name="Slider0" xml:space="preserve"><value>滑塊0</value></data>
|
||||
<data name="Slider1" xml:space="preserve"><value>滑塊1</value></data>
|
||||
<data name="Slider2" xml:space="preserve"><value>滑塊2</value></data>
|
||||
<data name="Slider3" xml:space="preserve"><value>滑塊3</value></data>
|
||||
<data name="SliderDesc" xml:space="preserve"><value>數值滑塊 (obj.slider0~3)</value></data>
|
||||
<data name="Check0" xml:space="preserve"><value>核取方塊0</value></data>
|
||||
<data name="Check1" xml:space="preserve"><value>核取方塊1</value></data>
|
||||
<data name="Check2" xml:space="preserve"><value>核取方塊2</value></data>
|
||||
@@ -76,6 +81,21 @@
|
||||
<data name="CheckDesc" xml:space="preserve"><value>核取方塊值(AviUtl兼容: check0~3)</value></data>
|
||||
<data name="Color" xml:space="preserve"><value>顏色</value></data>
|
||||
<data name="ColorDesc" xml:space="preserve"><value>顏色(AviUtl兼容: --color)</value></data>
|
||||
<data name="Text" xml:space="preserve"><value>文字</value></data>
|
||||
<data name="TextDesc" xml:space="preserve"><value>文字輸入 (obj.text)</value></data>
|
||||
<data name="Font" xml:space="preserve"><value>字型</value></data>
|
||||
<data name="FontDesc" xml:space="preserve"><value>字型選擇 (obj.font)</value></data>
|
||||
<data name="Directory" xml:space="preserve"><value>資料夾</value></data>
|
||||
<data name="DirectoryDesc" xml:space="preserve"><value>資料夾選擇 (obj.dir)</value></data>
|
||||
<data name="FileDesc" xml:space="preserve"><value>檔案選擇 (obj.file_*)</value></data>
|
||||
<data name="FileVideo" xml:space="preserve"><value>影片檔案</value></data>
|
||||
<data name="FileAudio" xml:space="preserve"><value>音訊檔案</value></data>
|
||||
<data name="FileImage" xml:space="preserve"><value>圖片檔案</value></data>
|
||||
<data name="FileProject" xml:space="preserve"><value>專案檔案</value></data>
|
||||
<data name="FileMp4" xml:space="preserve"><value>MP4檔案</value></data>
|
||||
<data name="FileExo" xml:space="preserve"><value>EXO檔案</value></data>
|
||||
<data name="FileSubtitle" xml:space="preserve"><value>字幕檔案</value></data>
|
||||
<data name="FileShader" xml:space="preserve"><value>著色器檔案</value></data>
|
||||
<data name="ToolBarImport" xml:space="preserve"><value>導入</value></data>
|
||||
<data name="ToolBarExport" xml:space="preserve"><value>導出</value></data>
|
||||
<data name="ToolBarClear" xml:space="preserve"><value>清除</value></data>
|
||||
@@ -84,4 +104,7 @@
|
||||
<data name="ToolBarImportErrorTitle" xml:space="preserve"><value>導入錯誤</value></data>
|
||||
<data name="ToolBarExportErrorTitle" xml:space="preserve"><value>導出錯誤</value></data>
|
||||
<data name="LuaFileFilter" xml:space="preserve"><value>Lua腳本 (*.lua)|*.lua|所有檔案 (*.*)|*.*</value></data>
|
||||
<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>
|
||||
</root>
|
||||
@@ -0,0 +1,339 @@
|
||||
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;
|
||||
using YukkuriMovieMaker.Plugin;
|
||||
using YukkuriMovieMaker.Plugin.Effects;
|
||||
using LuaScript.Compat;
|
||||
|
||||
namespace LuaScript
|
||||
{
|
||||
internal sealed class VideoEffectChain : IDisposable
|
||||
{
|
||||
private sealed class Node
|
||||
{
|
||||
public required IVideoEffect Model;
|
||||
public required IVideoEffectProcessor Processor;
|
||||
public required AviUtlEffectMapping? Mapping;
|
||||
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 = [];
|
||||
private string[] _signature = [];
|
||||
private AviUtlEngine _signatureTarget = AviUtlEngine.Both;
|
||||
|
||||
public VideoEffectChain(IGraphicsDevicesAndContext devices)
|
||||
{
|
||||
_devices = devices;
|
||||
}
|
||||
|
||||
public ID2D1Image Apply(ID2D1Image source, IReadOnlyList<AviUtlEffectRequest> requests, EffectDescription baseDesc, AviUtlEngine target, ref DrawDescription drawDescription)
|
||||
{
|
||||
try
|
||||
{
|
||||
SyncNodes(requests, target);
|
||||
}
|
||||
catch
|
||||
{
|
||||
return source;
|
||||
}
|
||||
|
||||
var current = source;
|
||||
var desc = drawDescription;
|
||||
|
||||
foreach (var node in _nodes)
|
||||
{
|
||||
try
|
||||
{
|
||||
ApplyParameters(node.Model, node.Mapping, requests[node.RequestIndex].Arguments);
|
||||
node.Processor.SetInput(current);
|
||||
var effectDescription = new EffectDescription(baseDesc, desc, baseDesc.InputIndex, baseDesc.InputCount, baseDesc.GroupIndex, baseDesc.GroupCount);
|
||||
desc = node.Processor.Update(effectDescription);
|
||||
current = node.Processor.Output;
|
||||
}
|
||||
catch
|
||||
{
|
||||
}
|
||||
}
|
||||
|
||||
drawDescription = desc;
|
||||
return current;
|
||||
}
|
||||
|
||||
private void SyncNodes(IReadOnlyList<AviUtlEffectRequest> requests, AviUtlEngine target)
|
||||
{
|
||||
if (SignatureMatches(requests, target))
|
||||
return;
|
||||
|
||||
DisposeNodes();
|
||||
_signatureTarget = target;
|
||||
_signature = new string[requests.Count];
|
||||
for (int i = 0; i < requests.Count; i++)
|
||||
_signature[i] = requests[i].Name;
|
||||
|
||||
for (int i = 0; i < requests.Count; i++)
|
||||
{
|
||||
Type? type;
|
||||
AviUtlEffectMapping? mapping;
|
||||
if (AviUtlCompatMap.Default.TryResolve(requests[i].Name, target, out var resolved) &&
|
||||
ResolveType(resolved.TargetType) is { } mappedType)
|
||||
{
|
||||
mapping = resolved;
|
||||
type = mappedType;
|
||||
}
|
||||
else
|
||||
{
|
||||
mapping = null;
|
||||
type = ResolveName(requests[i].Name);
|
||||
}
|
||||
if (type is null)
|
||||
continue;
|
||||
|
||||
IVideoEffect? model = null;
|
||||
try
|
||||
{
|
||||
model = Activator.CreateInstance(type) as IVideoEffect;
|
||||
}
|
||||
catch
|
||||
{
|
||||
}
|
||||
if (model is null)
|
||||
continue;
|
||||
|
||||
IVideoEffectProcessor processor;
|
||||
try
|
||||
{
|
||||
processor = model.CreateVideoEffect(_devices);
|
||||
}
|
||||
catch
|
||||
{
|
||||
continue;
|
||||
}
|
||||
|
||||
_nodes.Add(new Node { Model = model, Processor = processor, Mapping = mapping, RequestIndex = i });
|
||||
}
|
||||
}
|
||||
|
||||
private bool SignatureMatches(IReadOnlyList<AviUtlEffectRequest> requests, AviUtlEngine target)
|
||||
{
|
||||
if (_signatureTarget != target || _signature.Length != requests.Count)
|
||||
return false;
|
||||
for (int i = 0; i < requests.Count; i++)
|
||||
{
|
||||
if (!string.Equals(_signature[i], requests[i].Name, StringComparison.Ordinal))
|
||||
return false;
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
private static Type? ResolveType(string targetType)
|
||||
{
|
||||
EnsureRegistries();
|
||||
return _typeRegistry!.TryGetValue(Normalize(targetType), out var type) ? type : null;
|
||||
}
|
||||
|
||||
private static Type? ResolveName(string name)
|
||||
{
|
||||
EnsureRegistries();
|
||||
return _nameRegistry!.TryGetValue(Normalize(name), out var type) ? type : null;
|
||||
}
|
||||
|
||||
private static void EnsureRegistries()
|
||||
{
|
||||
if (_typeRegistry is not null && _nameRegistry is not null)
|
||||
return;
|
||||
|
||||
var byType = new Dictionary<string, Type>(StringComparer.Ordinal);
|
||||
var byName = new Dictionary<string, Type>(StringComparer.Ordinal);
|
||||
try
|
||||
{
|
||||
foreach (var factory in EffectFactories.VideoEffectFactories)
|
||||
{
|
||||
try
|
||||
{
|
||||
var type = factory.EffectType;
|
||||
if (type is null)
|
||||
continue;
|
||||
byType.TryAdd(Normalize(type.Name), type);
|
||||
Register(byName, factory.Name, type);
|
||||
foreach (var keyword in factory.Keywords)
|
||||
Register(byName, keyword, type);
|
||||
}
|
||||
catch
|
||||
{
|
||||
}
|
||||
}
|
||||
}
|
||||
catch
|
||||
{
|
||||
}
|
||||
_typeRegistry = byType;
|
||||
_nameRegistry = byName;
|
||||
}
|
||||
|
||||
private static void Register(Dictionary<string, Type> map, string? key, Type type)
|
||||
{
|
||||
if (string.IsNullOrWhiteSpace(key))
|
||||
return;
|
||||
map.TryAdd(Normalize(key), type);
|
||||
}
|
||||
|
||||
private static string Normalize(string value) => value.Trim().ToLowerInvariant();
|
||||
|
||||
private static void ApplyParameters(IVideoEffect model, AviUtlEffectMapping? mapping, IReadOnlyList<KeyValuePair<string, object>> arguments)
|
||||
{
|
||||
if (arguments.Count == 0)
|
||||
return;
|
||||
|
||||
var properties = 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;
|
||||
}
|
||||
|
||||
try
|
||||
{
|
||||
SetValue(model, property, value, parameter);
|
||||
}
|
||||
catch
|
||||
{
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
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)
|
||||
{
|
||||
try
|
||||
{
|
||||
node.Processor.ClearInput();
|
||||
}
|
||||
catch
|
||||
{
|
||||
}
|
||||
node.Processor.Dispose();
|
||||
}
|
||||
_nodes.Clear();
|
||||
}
|
||||
|
||||
public void Dispose() => DisposeNodes();
|
||||
}
|
||||
}
|
||||
129ファイル中100ファイルを読み込みました。 変更されたファイルが多すぎるため、それ以降のファイルは表示していません。
さらに表示
新しいイシューから参照
ユーザーをブロックする