コミットを比較
| 作成者 | SHA1 | 日付 | |
|---|---|---|---|
|
|
59dcb82b49
|
||
|
|
d37726cdf6
|
||
|
|
0c09cf4a51
|
||
|
|
0d4809924d
|
||
|
|
1e97e7d8fe
|
||
|
|
06cfefe1b4
|
||
|
|
37b1371f57
|
||
|
|
9db756c974
|
||
|
|
43f3161ebb
|
||
|
|
4b3b74edae
|
||
|
|
5129ece749
|
||
|
|
24ef4135cf
|
||
|
|
044fdbf1eb
|
||
|
|
9e1ad6c133
|
||
|
|
6d8def9f08
|
||
|
|
7a9f1ff6e8
|
||
|
|
82db144b86
|
||
|
|
d3fb73ed94
|
||
|
|
7dd777fbc6
|
||
|
|
aa17df08d8
|
||
|
|
e5c4485f16
|
||
|
|
9b901f91b6
|
||
|
|
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
|
検索条件に一致するファイルはありません
+44
-27
@@ -1,46 +1,63 @@
|
||||
# v1.9.1 - Lua スクリプト for YMM4
|
||||
# v1.13.2 - Lua スクリプト for YMM4
|
||||
|
||||
チェック(check0〜check3)とカラー(color)を、AviUtl 互換の `--check`/`--color`
|
||||
ヘッダ宣言だけでなく、スクリプト本体で参照するだけでエフェクトパネルへ自動表示できる
|
||||
ようにしたマイナーリリースです。トラックバー(track0〜track3)と同じ感覚で、必要な
|
||||
入力欄だけを `--` ヘッダ無しで出せます。既存のヘッダ宣言・トラック常時表示の挙動は
|
||||
変わりません。
|
||||
scene.set / scene.get の値の見え方を、フレーム位置に対して決定論的なモデルへ変更したリリースです。
|
||||
共有領域を「どのフレームで何を書き込んだか」を記録する履歴として再設計し、各フレームの読み取りは「そのフレームより前に確定した最新の値」を返すようにしました。これにより、タイムラインをどの順番でシークしても、同じフレームでは同じ値を読み取ります。あわせて、書き込みの確定に次のフレームの評価を必要としないようにし、同じフレームで複数のアイテムが同じ名前へ書き込んだ場合の優先規則を定め、動画出力とアイテムエフェクトの編集画面を編集中のプレビューから分離し、履歴が使うメモリへ上限を設けました。
|
||||
呼び出しの書き方と関数の引数に変更はありません。scene.set / scene.get を使わないスクリプトへの影響はありません。
|
||||
|
||||
---
|
||||
|
||||
## 新機能・機能改善
|
||||
## 動作の変更
|
||||
|
||||
### 1. check / color の参照による UI 自動表示
|
||||
### 1. 値の見え方をフレーム位置に対して決定論的なモデルへ変更
|
||||
|
||||
スクリプト本体で `obj.check0`〜`obj.check3` や `color` を参照すると、対応する
|
||||
チェックボックス・カラーピッカーがエフェクトパネルへ自動的に表示されます(参照を
|
||||
消すと非表示に戻ります)。AviUtl 互換時と同じ動的表示機構をそのまま用いており、
|
||||
`--` ヘッダを書かずに必要な入力欄だけを出せます。
|
||||
v1.13.1 までは、各アイテムの書き込みを保留領域へため、次のフレームの評価が行われた時点で共有領域の現在値へ反映していました。このため、読み取れる値が「どのフレームを評価してきたか」というシークの経路に左右され、前のフレームへ戻ったときに後のフレームで書き込まれた値が見えることがありました。
|
||||
今回から、書き込みをフレーム番号付きの履歴として記録し、scene.get は「自分のフレームより前に確定した最新の値」を返すようにしました。
|
||||
自分のスクリプトが書き込んだ値は、同じ実行の中で直後の scene.get からそのまま読み取れます。他のアイテムが書き込んだ値は、次のフレーム以降の評価から読み取れます。
|
||||
同じフレームの中では、アイテムがどの順番で評価されても scene.get が返す値は変わりません。
|
||||
|
||||
- トラックバー(track0〜track3)は従来どおり常に表示されます。
|
||||
- この一般利用では `--` 引数による範囲・既定値の宣言を伴わないため、値の範囲は
|
||||
スクリプト内で扱います(クランプは行いません)。
|
||||
- 参照表示したカラーピッカーの値は `color` としてスクリプトへ供給されます。
|
||||
- AviUtl 互換の `--track` / `--check` / `--color` ヘッダによる宣言表示は従来どおり
|
||||
利用できます。
|
||||
### 2. ランダムシークへの対応
|
||||
|
||||
### 2. 入力補完への登録
|
||||
タイムライン上をどの順番でシークしても、各フレームの読み取り結果は変わりません。
|
||||
前へ戻ったフレームでは、そのフレームより後に書き込まれた値は見えず、そのフレームより前に書き込まれた値だけが見えます。
|
||||
書き込んだフレームの直後のフレームを評価しなくても、それより後のどのフレームからでも読み取れます。
|
||||
同じフレームを何度再評価しても、読み取れる値と書き込みの結果は同一です。
|
||||
|
||||
スクリプトエディタの入力補完候補に `obj.check0`〜`obj.check3` と `color` を追加し、
|
||||
トラック(`obj.track0`〜`obj.track3`)と同様に補完できるようにしました。
|
||||
### 3. 同じフレームで複数のアイテムが同じ名前へ書き込んだ場合の規則
|
||||
|
||||
同じフレームで複数のアイテムが同じ名前へ書き込んだ場合、レイヤー番号の大きいアイテムの書き込みが優先されます。
|
||||
アイテムは並列に評価されますが、この規則により結果は評価のタイミングに依存しません。
|
||||
同じアイテムの中で複数の Lua スクリプトエフェクトが同じ名前へ書き込んだ場合は、エフェクトチェーンの後段の書き込みが優先されます。
|
||||
|
||||
### 4. 動画出力とアイテムエフェクトの編集画面を編集中のプレビューから分離
|
||||
|
||||
動画出力は編集中のプレビューとは独立した空の共有領域から始まります。編集画面での試行の途中経過が出力へ持ち込まれることがなくなり、同じプロジェクトを出力すれば毎回同じ結果になります。出力が終わると、その出力で使った共有領域は破棄されます。
|
||||
アイテムエフェクトの編集画面のプレビューも独立した共有領域を使うため、編集画面を開いても編集中のプレビューの共有値は変化しません。
|
||||
現在のフレームの画像出力は編集中のプレビューと同じ共有領域を参照するため、保存される画像はプレビューの表示と一致します。v1.13.1 までは画像出力が共有領域を全消去していましたが、この副作用はなくなりました。
|
||||
|
||||
### 5. 履歴のメモリへ上限を追加
|
||||
|
||||
各名前の最新の値を除いた履歴が使うメモリは 16MB までとし、超過した場合は全体で最も古い記録から順に間引きます。最新の値は間引きの対象になりません。
|
||||
1 つのシーンに保存できる名前が 4096 個までである仕様は、v1.13.1 から変わりません。
|
||||
|
||||
---
|
||||
|
||||
## 互換性・後方互換
|
||||
|
||||
- ヘッダ宣言時の表示やトラックバーの常時表示など、既存の挙動は変わりません。
|
||||
- 参照検出は、ヘッダ(`--`)を用いない一般利用時にのみ加算的に働きます。
|
||||
- 呼び出しの書き方と関数の引数に変更はありません。scene.set / scene.get を使わないスクリプトへの影響はありません。
|
||||
- スクリプトがエラーまたはタイムアウトで終了したフレームの書き込みを反映しない仕様は、v1.13.1 から変わりません。
|
||||
- 名前と文字列値を UTF-8 換算で 4095 バイトへ切り詰める仕様は、v1.13.0 から変わりません。
|
||||
- nil を渡した削除は、削除の記録として履歴へ残ります。削除より前のフレームでは削除前の値を、削除より後のフレームでは nil を読み取ります。
|
||||
- 共有値はメモリ上にのみ保持し、プロジェクトファイルには保存しません。YMM4 を終了すると失われます。
|
||||
|
||||
---
|
||||
|
||||
## 内部実装
|
||||
|
||||
- 参照検出は既存の Lua 字句解析器(`LuaLexer`)を再利用し、文字列・コメントを除外
|
||||
した正確な検出を行います(カスタム UI の新設なし)。
|
||||
- 全 8 言語(日本語・英語・簡体字中国語・繁体字中国語・韓国語・スペイン語・
|
||||
インドネシア語・アラビア語)のドキュメントへ、本挙動を追記しました。
|
||||
- SceneSharedValues を世代スナップショット方式からフレーム索引付きの履歴方式へ再設計しました。名前ごとに「フレーム番号・レイヤー番号・値」の組をフレーム昇順で保持し、読み取りは自分のフレームより前の最新の組を二分探索で求めます。nil の書き込みは削除の記録として履歴へ残し、直前の値と同じ書き込みは記録しません。保留領域と世代の追跡、出力開始の検出によるリセットは撤廃しました。
|
||||
- 共有領域を描画パイプラインごとに分離しました。YMM4 は動画出力・画像出力・アイテムエフェクトの編集画面のそれぞれで専用のグラフィックデバイスを生成するため、デバイスのインスタンスを鍵とした ConditionalWeakTable で領域を引き当てることで、出力は毎回空の領域から始まり、出力の終了後は領域が GC で解放されます。編集中のプレビューはアプリケーションの実行中を通して同じデバイスを使うため、領域が維持されます。
|
||||
- 同じフレームの同じ名前への書き込みが競合した場合、レイヤー番号の大きい書き込みを採用し、同じレイヤーでは後から確定した書き込みで置き換えます。並列評価でも結果が発行順序に依存しません。
|
||||
- SceneValueSession の開始時にスコープとレイヤー番号を受け取るようにし、正常終了時の発行でフレーム番号とレイヤー番号を付けて履歴へ即時確定します。書き込みバッファと読み取りメモ化、参照の記録は従来どおりです。
|
||||
- LuaScriptEffectProcessor のフレームキャッシュの検証を履歴照合へ変更しました。記録した読み取り結果を現在のフレームの履歴と照合し、食い違うフレームでは再実行します。書き込みは履歴として保持され再発行が不要になったため、共有値を書き込んだフレームのキャッシュ再利用の禁止を撤廃しました。
|
||||
- 各名前の最新の組を除いた履歴のメモリ使用量を追跡し、16MB を超えた場合は全体で最も古い組から決定論的に間引きます。
|
||||
- NativeProtocol と worker.lua に変更はありません。ワーカーの実行内キャッシュのセマンティクスは新しいモデルとそのまま一致します。
|
||||
- テストは 3086 件です。v1.13.1 の 3080 件から、履歴の可視性とランダムシークの決定論、後戻りシークでの挿入、レイヤーによる競合解決、nil の削除記録、再発行の冪等性、履歴メモリの上限、スコープの分離の検証を追加しました。
|
||||
@@ -1,5 +1,5 @@
|
||||
========================================
|
||||
Luaスクリプト for YMM4 v1.9.1
|
||||
Luaスクリプト for YMM4 v1.13.2
|
||||
========================================
|
||||
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,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);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -21,6 +21,8 @@ namespace LuaScript.Tests
|
||||
[InlineData("for y=0,obj.h-1 do for x=0,obj.w-1 do local r,g,b,a=obj.getpixel(x,y) 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 };
|
||||
@@ -38,6 +40,31 @@ namespace LuaScript.Tests
|
||||
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")]
|
||||
@@ -107,6 +134,8 @@ namespace LuaScript.Tests
|
||||
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;
|
||||
@@ -134,10 +163,60 @@ namespace LuaScript.Tests
|
||||
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)
|
||||
|
||||
@@ -31,6 +31,21 @@ namespace LuaScript.Tests
|
||||
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()
|
||||
{
|
||||
|
||||
@@ -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>
|
||||
|
||||
@@ -30,17 +31,35 @@
|
||||
<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\SceneValueSession.cs" Link="Linked\SceneValueSession.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" />
|
||||
@@ -52,6 +71,7 @@
|
||||
<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>
|
||||
|
||||
|
||||
@@ -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,188 @@
|
||||
namespace LuaScript.Tests
|
||||
{
|
||||
public class SceneSharedValuesTests
|
||||
{
|
||||
private static Dictionary<string, SceneValue> Writes(params (string Name, SceneValue Value)[] entries)
|
||||
{
|
||||
var writes = new Dictionary<string, SceneValue>(StringComparer.Ordinal);
|
||||
foreach (var (name, value) in entries)
|
||||
writes[name] = value;
|
||||
return writes;
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Publish_IsInvisibleAtOwnFrame_AndVisibleImmediatelyAfter()
|
||||
{
|
||||
var store = new SceneSharedValues();
|
||||
store.Publish(10, 0, Writes(("key", SceneValue.FromNumber(1d))));
|
||||
Assert.Equal(SceneValue.Nil, store.Read(10, "key"));
|
||||
Assert.Equal(SceneValue.FromNumber(1d), store.Read(11, "key"));
|
||||
Assert.Equal(SceneValue.FromNumber(1d), store.Read(1000, "key"));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Read_IsOrderIndependentWithinFrame()
|
||||
{
|
||||
var store = new SceneSharedValues();
|
||||
store.Publish(0, 0, Writes(("key", SceneValue.FromNumber(1d))));
|
||||
|
||||
Assert.Equal(SceneValue.FromNumber(1d), store.Read(1, "key"));
|
||||
store.Publish(1, 0, Writes(("key", SceneValue.FromNumber(2d))));
|
||||
Assert.Equal(SceneValue.FromNumber(1d), store.Read(1, "key"));
|
||||
store.Publish(1, 1, Writes(("other", SceneValue.FromNumber(3d))));
|
||||
Assert.Equal(SceneValue.FromNumber(1d), store.Read(1, "key"));
|
||||
|
||||
Assert.Equal(SceneValue.FromNumber(2d), store.Read(2, "key"));
|
||||
Assert.Equal(SceneValue.FromNumber(3d), store.Read(2, "other"));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void RandomSeek_ReadsAreDeterministicPerFrame()
|
||||
{
|
||||
var store = new SceneSharedValues();
|
||||
store.Publish(10, 0, Writes(("key", SceneValue.FromNumber(1d))));
|
||||
store.Publish(20, 0, Writes(("key", SceneValue.FromNumber(2d))));
|
||||
|
||||
Assert.Equal(SceneValue.Nil, store.Read(5, "key"));
|
||||
Assert.Equal(SceneValue.FromNumber(1d), store.Read(15, "key"));
|
||||
Assert.Equal(SceneValue.FromNumber(2d), store.Read(25, "key"));
|
||||
Assert.Equal(SceneValue.FromNumber(1d), store.Read(15, "key"));
|
||||
Assert.Equal(SceneValue.Nil, store.Read(5, "key"));
|
||||
|
||||
store.Publish(30, 0, Writes(("key", SceneValue.FromNumber(3d))));
|
||||
Assert.Equal(SceneValue.Nil, store.Read(5, "key"));
|
||||
Assert.Equal(SceneValue.FromNumber(1d), store.Read(15, "key"));
|
||||
Assert.Equal(SceneValue.FromNumber(2d), store.Read(25, "key"));
|
||||
Assert.Equal(SceneValue.FromNumber(3d), store.Read(35, "key"));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void BackwardSeekPublish_InsertsIntoHistoryInOrder()
|
||||
{
|
||||
var store = new SceneSharedValues();
|
||||
store.Publish(20, 0, Writes(("key", SceneValue.FromNumber(2d))));
|
||||
store.Publish(10, 0, Writes(("key", SceneValue.FromNumber(1d))));
|
||||
|
||||
Assert.Equal(SceneValue.Nil, store.Read(10, "key"));
|
||||
Assert.Equal(SceneValue.FromNumber(1d), store.Read(15, "key"));
|
||||
Assert.Equal(SceneValue.FromNumber(2d), store.Read(25, "key"));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void NilWrite_RecordsRemovalWithoutErasingHistory()
|
||||
{
|
||||
var store = new SceneSharedValues();
|
||||
store.Publish(10, 0, Writes(("key", SceneValue.FromNumber(1d))));
|
||||
store.Publish(20, 0, Writes(("key", SceneValue.Nil)));
|
||||
|
||||
Assert.Equal(SceneValue.FromNumber(1d), store.Read(15, "key"));
|
||||
Assert.Equal(SceneValue.Nil, store.Read(25, "key"));
|
||||
|
||||
store.Publish(30, 0, Writes(("key", SceneValue.FromNumber(3d))));
|
||||
Assert.Equal(SceneValue.Nil, store.Read(25, "key"));
|
||||
Assert.Equal(SceneValue.FromNumber(3d), store.Read(31, "key"));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void SameFrameConflict_HigherLayerWinsRegardlessOfPublishOrder()
|
||||
{
|
||||
var forward = new SceneSharedValues();
|
||||
forward.Publish(0, 3, Writes(("key", SceneValue.FromNumber(3d))));
|
||||
forward.Publish(0, 5, Writes(("key", SceneValue.FromNumber(5d))));
|
||||
|
||||
var reverse = new SceneSharedValues();
|
||||
reverse.Publish(0, 5, Writes(("key", SceneValue.FromNumber(5d))));
|
||||
reverse.Publish(0, 3, Writes(("key", SceneValue.FromNumber(3d))));
|
||||
|
||||
Assert.Equal(SceneValue.FromNumber(5d), forward.Read(1, "key"));
|
||||
Assert.Equal(SceneValue.FromNumber(5d), reverse.Read(1, "key"));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void SameFrameSameLayer_LaterPublishReplaces()
|
||||
{
|
||||
var store = new SceneSharedValues();
|
||||
store.Publish(0, 2, Writes(("key", SceneValue.FromNumber(1d))));
|
||||
store.Publish(0, 2, Writes(("key", SceneValue.FromNumber(2d))));
|
||||
|
||||
Assert.Equal(SceneValue.FromNumber(2d), store.Read(1, "key"));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Republish_IsIdempotent()
|
||||
{
|
||||
var store = new SceneSharedValues();
|
||||
for (int i = 0; i < 5; i++)
|
||||
store.Publish(7, 1, Writes(("key", SceneValue.FromNumber(9d))));
|
||||
|
||||
Assert.Equal(SceneValue.Nil, store.Read(7, "key"));
|
||||
Assert.Equal(SceneValue.FromNumber(9d), store.Read(8, "key"));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Capacity_LimitsDistinctNames_AndKeepsExistingUpdatable()
|
||||
{
|
||||
var store = new SceneSharedValues();
|
||||
var writes = new Dictionary<string, SceneValue>(StringComparer.Ordinal);
|
||||
for (int i = 0; i < SceneSharedValues.MaxEntries; i++)
|
||||
writes["k" + i] = SceneValue.FromNumber(i);
|
||||
store.Publish(0, 0, writes);
|
||||
|
||||
store.Publish(1, 0, Writes(
|
||||
("overflow", SceneValue.FromNumber(1d)),
|
||||
("k0", SceneValue.FromNumber(-1d))));
|
||||
|
||||
Assert.Equal(SceneValue.Nil, store.Read(2, "overflow"));
|
||||
Assert.Equal(SceneValue.FromNumber(-1d), store.Read(2, "k0"));
|
||||
|
||||
store.Publish(2, 0, Writes(("k1", SceneValue.Nil)));
|
||||
Assert.Equal(SceneValue.Nil, store.Read(3, "k1"));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void NilWritesToUnknownNames_DoNotConsumeCapacity()
|
||||
{
|
||||
var store = new SceneSharedValues();
|
||||
var removals = new Dictionary<string, SceneValue>(StringComparer.Ordinal);
|
||||
for (int i = 0; i < SceneSharedValues.MaxEntries; i++)
|
||||
removals["ghost" + i] = SceneValue.Nil;
|
||||
store.Publish(0, 0, removals);
|
||||
|
||||
store.Publish(1, 0, Writes(("real", SceneValue.FromNumber(1d))));
|
||||
Assert.Equal(SceneValue.FromNumber(1d), store.Read(2, "real"));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void HistoryBudget_EvictsOldestVersionsAndKeepsNewest()
|
||||
{
|
||||
var store = new SceneSharedValues();
|
||||
string payload = new('x', SceneSharedValues.MaxTextBytes - 5);
|
||||
int frames = (int)(SceneSharedValues.MaxHistoryCostBytes /
|
||||
(SceneSharedValues.MaxTextBytes * 2L)) + 200;
|
||||
|
||||
for (int i = 0; i < frames; i++)
|
||||
store.Publish(i, 0, Writes(("key", SceneValue.FromString(payload + i.ToString("D5")))));
|
||||
|
||||
Assert.Equal(SceneValue.Nil, store.Read(1, "key"));
|
||||
Assert.Equal(
|
||||
SceneValue.FromString(payload + (frames - 1).ToString("D5")),
|
||||
store.Read(frames, "key"));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void ForScene_IsolatesScopesAndScenes_AndSharesWithinBoth()
|
||||
{
|
||||
object scopeA = new();
|
||||
object scopeB = new();
|
||||
string sceneA = Guid.NewGuid().ToString();
|
||||
string sceneB = Guid.NewGuid().ToString();
|
||||
|
||||
SceneSharedValues.ForScene(scopeA, sceneA).Publish(0, 0, Writes(("key", SceneValue.FromNumber(1d))));
|
||||
|
||||
Assert.Equal(SceneValue.FromNumber(1d), SceneSharedValues.ForScene(scopeA, sceneA).Read(1, "key"));
|
||||
Assert.Equal(SceneValue.Nil, SceneSharedValues.ForScene(scopeA, sceneB).Read(1, "key"));
|
||||
Assert.Equal(SceneValue.Nil, SceneSharedValues.ForScene(scopeB, sceneA).Read(1, "key"));
|
||||
Assert.Same(SceneSharedValues.ForScene(scopeA, sceneA), SceneSharedValues.ForScene(scopeA, sceneA));
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,132 @@
|
||||
using MoonSharp.Interpreter;
|
||||
|
||||
namespace LuaScript.Tests
|
||||
{
|
||||
public class SceneTableRegistrarTests
|
||||
{
|
||||
private sealed class Harness
|
||||
{
|
||||
private readonly object _scope = new();
|
||||
private readonly string _sceneId = Guid.NewGuid().ToString();
|
||||
private long _generation;
|
||||
|
||||
public Script Script { get; }
|
||||
public SceneValueSession Session { get; } = new();
|
||||
|
||||
public Harness()
|
||||
{
|
||||
Script = new Script(CoreModules.Basic | CoreModules.Math | CoreModules.String | CoreModules.Table);
|
||||
var scene = new Table(Script);
|
||||
SceneTableRegistrar.RegisterFunctions(scene, Session.Get, Session.Set);
|
||||
Script.Globals["scene"] = scene;
|
||||
Session.Begin(_scope, _sceneId, _generation, 0);
|
||||
}
|
||||
|
||||
public DynValue Run(string code)
|
||||
{
|
||||
var result = Script.DoString(code);
|
||||
Session.Publish();
|
||||
return result;
|
||||
}
|
||||
|
||||
public void NextFrame()
|
||||
{
|
||||
_generation++;
|
||||
Session.Begin(_scope, _sceneId, _generation, 0);
|
||||
}
|
||||
|
||||
public SceneValue Stored(string name)
|
||||
{
|
||||
NextFrame();
|
||||
return Session.Get(name);
|
||||
}
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Set_StoresAllSupportedKinds()
|
||||
{
|
||||
var harness = new Harness();
|
||||
harness.Run(
|
||||
"scene.set('num', 4.25) " +
|
||||
"scene.set('text', 'こんにちは') " +
|
||||
"scene.set('flag', false)");
|
||||
|
||||
Assert.Equal(SceneValue.FromNumber(4.25), harness.Stored("num"));
|
||||
Assert.Equal(SceneValue.FromString("こんにちは"), harness.Stored("text"));
|
||||
Assert.Equal(SceneValue.FromBoolean(false), harness.Stored("flag"));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Set_NilOrMissingValue_Removes()
|
||||
{
|
||||
var harness = new Harness();
|
||||
harness.Run("scene.set('a', 1) scene.set('b', 2)");
|
||||
harness.NextFrame();
|
||||
harness.Run("scene.set('a', nil) scene.set('b')");
|
||||
|
||||
Assert.Equal(SceneValue.Nil, harness.Stored("a"));
|
||||
Assert.Equal(SceneValue.Nil, harness.Stored("b"));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Set_UnsupportedTypesAndNames_AreIgnored()
|
||||
{
|
||||
var harness = new Harness();
|
||||
harness.Run("scene.set('keep', 9)");
|
||||
harness.NextFrame();
|
||||
harness.Run(
|
||||
"scene.set('keep', {}) " +
|
||||
"scene.set('fn', function() end) " +
|
||||
"scene.set(12, 'x') " +
|
||||
"scene.set()");
|
||||
|
||||
Assert.Equal(SceneValue.FromNumber(9d), harness.Stored("keep"));
|
||||
Assert.Equal(SceneValue.Nil, harness.Stored("fn"));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Get_ReturnsStoredValuesWithLuaTypes()
|
||||
{
|
||||
var harness = new Harness();
|
||||
harness.Run(
|
||||
"scene.set('num', -8.5) " +
|
||||
"scene.set('text', 'v') " +
|
||||
"scene.set('flag', true)");
|
||||
harness.NextFrame();
|
||||
|
||||
var result = harness.Run(
|
||||
"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 harness = new Harness();
|
||||
var result = harness.Run(
|
||||
"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);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Counter_AccumulatesAcrossFrames()
|
||||
{
|
||||
var harness = new Harness();
|
||||
const string script = "scene.set('counter', (scene.get('counter') or 0) + 1) return scene.get('counter')";
|
||||
|
||||
Assert.Equal(1d, harness.Run(script).Number);
|
||||
harness.NextFrame();
|
||||
Assert.Equal(2d, harness.Run(script).Number);
|
||||
harness.NextFrame();
|
||||
Assert.Equal(3d, harness.Run(script).Number);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,225 @@
|
||||
using System.Text;
|
||||
|
||||
namespace LuaScript.Tests
|
||||
{
|
||||
public class SceneValueSessionTests
|
||||
{
|
||||
private static string NewSceneId() => Guid.NewGuid().ToString();
|
||||
|
||||
[Fact]
|
||||
public void Get_ReturnsOwnWriteWithinRun()
|
||||
{
|
||||
var session = new SceneValueSession();
|
||||
session.Begin(new object(), NewSceneId(), 0, 0);
|
||||
|
||||
Assert.Equal(SceneValue.Nil, session.Get("key"));
|
||||
session.Set("key", SceneValue.FromNumber(1d));
|
||||
Assert.Equal(SceneValue.FromNumber(1d), session.Get("key"));
|
||||
session.Set("key", SceneValue.Nil);
|
||||
Assert.Equal(SceneValue.Nil, session.Get("key"));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Writes_AreDiscardedWithoutPublish()
|
||||
{
|
||||
object scope = new();
|
||||
string sceneId = NewSceneId();
|
||||
var session = new SceneValueSession();
|
||||
session.Begin(scope, sceneId, 0, 0);
|
||||
session.Set("key", SceneValue.FromNumber(1d));
|
||||
|
||||
session.Begin(scope, sceneId, 1, 0);
|
||||
Assert.Equal(SceneValue.Nil, session.Get("key"));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void PublishedWrites_AreVisibleFromNextFrame_WithoutIntermediateFrames()
|
||||
{
|
||||
object scope = new();
|
||||
string sceneId = NewSceneId();
|
||||
var writer = new SceneValueSession();
|
||||
var reader = new SceneValueSession();
|
||||
|
||||
writer.Begin(scope, sceneId, 0, 0);
|
||||
writer.Set("key", SceneValue.FromNumber(1d));
|
||||
writer.Publish();
|
||||
|
||||
reader.Begin(scope, sceneId, 0, 1);
|
||||
Assert.Equal(SceneValue.Nil, reader.Get("key"));
|
||||
|
||||
reader.Begin(scope, sceneId, 1, 1);
|
||||
Assert.Equal(SceneValue.FromNumber(1d), reader.Get("key"));
|
||||
|
||||
reader.Begin(scope, sceneId, 1000, 1);
|
||||
Assert.Equal(SceneValue.FromNumber(1d), reader.Get("key"));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void ReadResults_AreStableWithinRun()
|
||||
{
|
||||
object scope = new();
|
||||
string sceneId = NewSceneId();
|
||||
var writer = new SceneValueSession();
|
||||
var reader = new SceneValueSession();
|
||||
|
||||
writer.Begin(scope, sceneId, 0, 0);
|
||||
writer.Set("key", SceneValue.FromNumber(1d));
|
||||
writer.Publish();
|
||||
|
||||
reader.Begin(scope, sceneId, 1, 1);
|
||||
Assert.Equal(SceneValue.FromNumber(1d), reader.Get("key"));
|
||||
|
||||
writer.Begin(scope, sceneId, 0, 0);
|
||||
writer.Set("key", SceneValue.FromNumber(2d));
|
||||
writer.Publish();
|
||||
|
||||
Assert.Equal(SceneValue.FromNumber(1d), reader.Get("key"));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void BackwardSeek_ReadsValuesCommittedBeforeThatFrameOnly()
|
||||
{
|
||||
object scope = new();
|
||||
string sceneId = NewSceneId();
|
||||
var writer = new SceneValueSession();
|
||||
var reader = new SceneValueSession();
|
||||
|
||||
writer.Begin(scope, sceneId, 10, 0);
|
||||
writer.Set("key", SceneValue.FromNumber(1d));
|
||||
writer.Publish();
|
||||
|
||||
writer.Begin(scope, sceneId, 20, 0);
|
||||
writer.Set("key", SceneValue.FromNumber(2d));
|
||||
writer.Publish();
|
||||
|
||||
reader.Begin(scope, sceneId, 25, 1);
|
||||
Assert.Equal(SceneValue.FromNumber(2d), reader.Get("key"));
|
||||
|
||||
reader.Begin(scope, sceneId, 15, 1);
|
||||
Assert.Equal(SceneValue.FromNumber(1d), reader.Get("key"));
|
||||
|
||||
reader.Begin(scope, sceneId, 5, 1);
|
||||
Assert.Equal(SceneValue.Nil, reader.Get("key"));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void SameFrame_HigherLayerWinsAcrossSessions()
|
||||
{
|
||||
object scope = new();
|
||||
string sceneId = NewSceneId();
|
||||
var lower = new SceneValueSession();
|
||||
var upper = new SceneValueSession();
|
||||
var reader = new SceneValueSession();
|
||||
|
||||
upper.Begin(scope, sceneId, 0, 5);
|
||||
upper.Set("key", SceneValue.FromNumber(5d));
|
||||
upper.Publish();
|
||||
|
||||
lower.Begin(scope, sceneId, 0, 3);
|
||||
lower.Set("key", SceneValue.FromNumber(3d));
|
||||
lower.Publish();
|
||||
|
||||
reader.Begin(scope, sceneId, 1, 0);
|
||||
Assert.Equal(SceneValue.FromNumber(5d), reader.Get("key"));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Scopes_IsolateSessionsSharingSceneId()
|
||||
{
|
||||
string sceneId = NewSceneId();
|
||||
var writer = new SceneValueSession();
|
||||
var reader = new SceneValueSession();
|
||||
|
||||
writer.Begin(new object(), sceneId, 0, 0);
|
||||
writer.Set("key", SceneValue.FromNumber(1d));
|
||||
writer.Publish();
|
||||
|
||||
reader.Begin(new object(), sceneId, 1, 0);
|
||||
Assert.Equal(SceneValue.Nil, reader.Get("key"));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Queries_TrackDistinctStoreReadsOnly()
|
||||
{
|
||||
var session = new SceneValueSession();
|
||||
session.Begin(new object(), NewSceneId(), 0, 0);
|
||||
|
||||
session.Get("a");
|
||||
session.Get("a");
|
||||
session.Get("b");
|
||||
session.Set("c", SceneValue.FromNumber(1d));
|
||||
session.Get("c");
|
||||
|
||||
Assert.Equal(2, session.Queries.Count);
|
||||
Assert.Equal("a", session.Queries[0].Name);
|
||||
Assert.Equal("b", session.Queries[1].Name);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void HasWrites_ReflectsWritesIncludingRemovals()
|
||||
{
|
||||
object scope = new();
|
||||
var session = new SceneValueSession();
|
||||
session.Begin(scope, NewSceneId(), 0, 0);
|
||||
Assert.False(session.HasWrites);
|
||||
|
||||
session.Set("key", SceneValue.Nil);
|
||||
Assert.True(session.HasWrites);
|
||||
|
||||
session.Begin(scope, NewSceneId(), 0, 0);
|
||||
Assert.False(session.HasWrites);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Set_TruncatesLongTextAtUtf8Boundary()
|
||||
{
|
||||
var session = new SceneValueSession();
|
||||
session.Begin(new object(), NewSceneId(), 0, 0);
|
||||
|
||||
string text = new('あ', 2000);
|
||||
session.Set("key", SceneValue.FromString(text));
|
||||
|
||||
var stored = session.Get("key");
|
||||
Assert.Equal(SceneValueKind.String, stored.Kind);
|
||||
Assert.Equal(SceneSharedValues.MaxTextBytes / 3, stored.Text!.Length);
|
||||
Assert.True(Encoding.UTF8.GetByteCount(stored.Text) <= SceneSharedValues.MaxTextBytes);
|
||||
Assert.StartsWith(stored.Text, text, StringComparison.Ordinal);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void LongNames_AreTruncatedConsistentlyAcrossSetAndGet()
|
||||
{
|
||||
object scope = new();
|
||||
string sceneId = NewSceneId();
|
||||
var session = new SceneValueSession();
|
||||
string name = new('k', SceneSharedValues.MaxNameBytes + 100);
|
||||
|
||||
session.Begin(scope, sceneId, 0, 0);
|
||||
session.Set(name, SceneValue.FromNumber(7d));
|
||||
Assert.Equal(SceneValue.FromNumber(7d), session.Get(name));
|
||||
session.Publish();
|
||||
|
||||
session.Begin(scope, sceneId, 1, 0);
|
||||
Assert.Equal(SceneValue.FromNumber(7d), session.Get(name[..SceneSharedValues.MaxNameBytes]));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Sessions_FollowSceneIdChanges()
|
||||
{
|
||||
object scope = new();
|
||||
string sceneA = NewSceneId();
|
||||
string sceneB = NewSceneId();
|
||||
var session = new SceneValueSession();
|
||||
|
||||
session.Begin(scope, sceneA, 0, 0);
|
||||
session.Set("key", SceneValue.FromNumber(1d));
|
||||
session.Publish();
|
||||
|
||||
session.Begin(scope, sceneB, 1, 0);
|
||||
Assert.Equal(SceneValue.Nil, session.Get("key"));
|
||||
|
||||
session.Begin(scope, sceneA, 1, 0);
|
||||
Assert.Equal(SceneValue.FromNumber(1d), session.Get("key"));
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -31,18 +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)", "Native")]
|
||||
[InlineData("obj.draw()", "MoonSharp")]
|
||||
[InlineData("obj.draw()\nlocal r = obj.getpixel(0,0)", "Native")]
|
||||
[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,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,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,12 +71,32 @@ 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 readonly SceneValueSession _sceneValues = new();
|
||||
|
||||
public IReadOnlyList<SceneValueQuery> SceneValueQueries => _sceneValues.Queries;
|
||||
|
||||
internal object? SceneScope { get; set; }
|
||||
|
||||
internal void BeginSceneValues() => _sceneValues.Begin(SceneScope ?? this, SceneId, TimelineFrame, Layer);
|
||||
|
||||
internal void PublishSceneValues() => _sceneValues.Publish();
|
||||
|
||||
public SceneValue GetSceneValue(string name) => _sceneValues.Get(name);
|
||||
|
||||
public void SetSceneValue(string name, SceneValue value) => _sceneValues.Set(name, value);
|
||||
|
||||
private readonly List<AviUtlEffectRequest> _effectRequests = [];
|
||||
|
||||
public IReadOnlyList<AviUtlEffectRequest> EffectRequests => _effectRequests;
|
||||
@@ -66,6 +105,8 @@ namespace LuaScript
|
||||
|
||||
internal void ClearEffects() => _effectRequests.Clear();
|
||||
|
||||
internal IBufferCompositor Compositor { get; set; } = SoftwareCompositor.Instance;
|
||||
|
||||
private readonly List<DrawCommand> _drawCommands = [];
|
||||
|
||||
public IReadOnlyList<DrawCommand> DrawCommands => _drawCommands;
|
||||
@@ -74,6 +115,49 @@ namespace LuaScript
|
||||
|
||||
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)
|
||||
@@ -115,20 +199,29 @@ namespace LuaScript
|
||||
|
||||
private bool TryWriteBuffer(string id, byte[] data, int width, int height)
|
||||
{
|
||||
int n = width * height * 4;
|
||||
switch (BufferKind(id, out string key))
|
||||
{
|
||||
case 'o':
|
||||
ReplaceBuffer((byte[])data.Clone(), width, height);
|
||||
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':
|
||||
_buffers[key] = ((byte[])data.Clone(), width, height);
|
||||
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;
|
||||
|
||||
@@ -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);
|
||||
}
|
||||
}
|
||||
@@ -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');
|
||||
|
||||
@@ -48,15 +50,24 @@ namespace LuaScript.Compat
|
||||
AppendDeclarations(lines[i], prelude);
|
||||
|
||||
if (!hasSection && prelude.Count == 0)
|
||||
return source;
|
||||
return (source, []);
|
||||
|
||||
var builder = new StringBuilder(source.Length + 64);
|
||||
foreach (var declaration in prelude)
|
||||
builder.Append(declaration).Append('\n');
|
||||
for (int i = sectionStart; i < sectionEnd; i++)
|
||||
builder.Append(lines[i]).Append('\n');
|
||||
var lineMap = new int[prelude.Count + (sectionEnd - sectionStart)];
|
||||
int row = 0;
|
||||
|
||||
return builder.ToString();
|
||||
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(), lineMap);
|
||||
}
|
||||
|
||||
private static void AppendDeclarations(string line, List<string> prelude)
|
||||
|
||||
@@ -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;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -6,31 +6,29 @@ namespace LuaScript.Compat
|
||||
{
|
||||
internal readonly struct ScriptParameterUsage
|
||||
{
|
||||
public bool Check0 { get; }
|
||||
public bool Check1 { get; }
|
||||
public bool Check2 { get; }
|
||||
public bool Check3 { get; }
|
||||
public bool Color { get; }
|
||||
private readonly HashSet<string>? _members;
|
||||
private readonly bool _color;
|
||||
|
||||
private ScriptParameterUsage(bool check0, bool check1, bool check2, bool check3, bool color)
|
||||
private ScriptParameterUsage(HashSet<string>? members, bool color)
|
||||
{
|
||||
Check0 = check0;
|
||||
Check1 = check1;
|
||||
Check2 = check2;
|
||||
Check3 = check3;
|
||||
Color = color;
|
||||
_members = members;
|
||||
_color = color;
|
||||
}
|
||||
|
||||
public static readonly ScriptParameterUsage None = default;
|
||||
|
||||
public bool Check(int index) => index switch
|
||||
{
|
||||
0 => Check0,
|
||||
1 => Check1,
|
||||
2 => Check2,
|
||||
3 => Check3,
|
||||
_ => false,
|
||||
};
|
||||
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)
|
||||
{
|
||||
@@ -47,7 +45,7 @@ namespace LuaScript.Compat
|
||||
return None;
|
||||
}
|
||||
|
||||
var checks = new bool[4];
|
||||
HashSet<string>? members = null;
|
||||
bool color = false;
|
||||
|
||||
for (int i = 0; i < tokens.Count; i++)
|
||||
@@ -68,17 +66,11 @@ namespace LuaScript.Compat
|
||||
tokens[i + 1].IsSymbol(".") &&
|
||||
tokens[i + 2].Kind == LuaTokenKind.Name)
|
||||
{
|
||||
string member = tokens[i + 2].Text;
|
||||
if (member.Length == 6 && member.StartsWith("check", StringComparison.Ordinal))
|
||||
{
|
||||
char digit = member[5];
|
||||
if (digit is >= '0' and <= '3')
|
||||
checks[digit - '0'] = true;
|
||||
}
|
||||
(members ??= new HashSet<string>(StringComparer.Ordinal)).Add(tokens[i + 2].Text);
|
||||
}
|
||||
}
|
||||
|
||||
return new ScriptParameterUsage(checks[0], checks[1], checks[2], checks[3], color);
|
||||
return new ScriptParameterUsage(members, color);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -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;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -8,5 +8,6 @@ namespace LuaScript
|
||||
double Alpha,
|
||||
double Aspect,
|
||||
double[]? Poly = null,
|
||||
double Antialias = 1d);
|
||||
double Antialias = 1d,
|
||||
double Blend = 0d);
|
||||
}
|
||||
+49
-23
@@ -1,9 +1,12 @@
|
||||
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
|
||||
{
|
||||
@@ -15,6 +18,9 @@ namespace LuaScript
|
||||
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;
|
||||
@@ -65,7 +71,7 @@ namespace LuaScript
|
||||
|
||||
var dc = _ctx.DeviceContext;
|
||||
var rt = (ID2D1RenderTarget)dc;
|
||||
var savedTarget = dc.Target;
|
||||
using var savedTarget = dc.Target;
|
||||
|
||||
dc.Target = _target;
|
||||
dc.BeginDraw();
|
||||
@@ -74,40 +80,44 @@ namespace LuaScript
|
||||
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);
|
||||
|
||||
if (cmd.Poly is { } poly)
|
||||
{
|
||||
if (!DrawPolyMath.TrySolveAffine(poly, out var affine))
|
||||
continue;
|
||||
rt.Transform = affine * toTarget;
|
||||
rt.DrawBitmap(_source, (float)Math.Clamp(poly[20], 0d, 1d), interpolation);
|
||||
continue;
|
||||
}
|
||||
|
||||
double aspect = Math.Clamp(cmd.Aspect, -1d, 1d);
|
||||
float zx = (float)(cmd.Zoom * (1d + aspect));
|
||||
float zy = (float)(cmd.Zoom * (1d - aspect));
|
||||
float opacity = (float)Math.Clamp(cmd.Alpha, 0d, 1d);
|
||||
|
||||
var matrix =
|
||||
Matrix3x2.CreateTranslation(-width * 0.5f, -height * 0.5f) *
|
||||
Matrix3x2.CreateScale(zx, zy) *
|
||||
Matrix3x2.CreateTranslation((float)(cmd.Ox - originX), (float)(cmd.Oy - originY));
|
||||
|
||||
rt.Transform = matrix;
|
||||
rt.DrawBitmap(_source, opacity, interpolation);
|
||||
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 _placement.Output;
|
||||
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)
|
||||
@@ -117,6 +127,13 @@ namespace LuaScript
|
||||
_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)
|
||||
@@ -124,8 +141,10 @@ namespace LuaScript
|
||||
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);
|
||||
@@ -134,14 +153,21 @@ namespace LuaScript
|
||||
|
||||
_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,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;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,28 +1,95 @@
|
||||
using System.Diagnostics;
|
||||
using System.Runtime.Intrinsics;
|
||||
using System.Threading.Tasks;
|
||||
|
||||
namespace LuaScript.Engine.Kernel
|
||||
{
|
||||
internal sealed class CpuKernel(CpuKernel.RowDelegate row)
|
||||
internal sealed class CpuKernel(CpuKernel.RowDelegate row, CpuKernel.RowDelegate? block)
|
||||
{
|
||||
public delegate void RowDelegate(byte[] buffer, int width, int rowBase, double y, double[] uniforms);
|
||||
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++)
|
||||
row(buffer, width, y * stride, y, uniforms);
|
||||
RunRow(y);
|
||||
return;
|
||||
}
|
||||
|
||||
Parallel.For(0, height, y => row(buffer, width, y * stride, y, uniforms));
|
||||
Parallel.For(0, height, RunRow);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -31,11 +31,15 @@ namespace LuaScript.Engine.Kernel
|
||||
[KFunc.Max] = Binary(nameof(Math.Max)),
|
||||
};
|
||||
|
||||
public static CpuKernel Compile(KernelProgram program)
|
||||
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 width = Expression.Parameter(typeof(int), "width");
|
||||
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");
|
||||
|
||||
@@ -85,7 +89,7 @@ namespace LuaScript.Engine.Kernel
|
||||
var breakLabel = Expression.Label("break");
|
||||
var loop = Expression.Loop(
|
||||
Expression.IfThenElse(
|
||||
Expression.LessThan(x, width),
|
||||
Expression.LessThan(x, xEnd),
|
||||
Expression.Block(statements),
|
||||
Expression.Break(breakLabel)),
|
||||
breakLabel);
|
||||
@@ -94,10 +98,10 @@ namespace LuaScript.Engine.Kernel
|
||||
locals.AddRange(inputs);
|
||||
locals.AddRange(slots);
|
||||
|
||||
var body = Expression.Block(locals, Expression.Assign(x, Constant(0)), loop);
|
||||
var body = Expression.Block(locals, Expression.Assign(x, xStart), loop);
|
||||
|
||||
var lambda = Expression.Lambda<CpuKernel.RowDelegate>(body, buffer, width, rowBase, y, uniforms);
|
||||
return new CpuKernel(lambda.Compile());
|
||||
var lambda = Expression.Lambda<CpuKernel.RowDelegate>(body, buffer, rowBase, xStart, xEnd, y, uniforms);
|
||||
return lambda.Compile();
|
||||
}
|
||||
|
||||
private sealed record Context(
|
||||
@@ -151,6 +155,8 @@ namespace LuaScript.Engine.Kernel
|
||||
|
||||
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));
|
||||
|
||||
@@ -1,17 +1,30 @@
|
||||
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)
|
||||
=> _effect = new GpuKernelEffect(devices, HlslKernelEmitter.Emit(program));
|
||||
{
|
||||
_devices = devices;
|
||||
_effect = new GpuKernelEffect(devices, HlslKernelEmitter.Emit(program));
|
||||
}
|
||||
|
||||
public bool IsReady => _effect.IsReady;
|
||||
|
||||
@@ -21,9 +34,130 @@ namespace LuaScript.Engine.Kernel
|
||||
Buffer.BlockCopy(_packed, 0, _bytes, 0, _bytes.Length);
|
||||
_effect.SetConstants(_bytes);
|
||||
_effect.SetInput(0, input, true);
|
||||
return _effect.Output;
|
||||
return _output ??= _effect.Output;
|
||||
}
|
||||
|
||||
public void Dispose() => _effect.Dispose();
|
||||
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();
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -32,8 +32,8 @@ namespace LuaScript.Engine.Kernel
|
||||
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(";\n");
|
||||
builder.Append(" float py = uv.y * ").Append(Uniform(KernelUniform.Height)).Append(";\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++)
|
||||
{
|
||||
@@ -42,21 +42,21 @@ namespace LuaScript.Engine.Kernel
|
||||
builder.Append(";\n");
|
||||
}
|
||||
|
||||
builder.Append(" float outA = ");
|
||||
builder.Append(" float outA = clamp(");
|
||||
EmitExpression(builder, program.OutputA);
|
||||
builder.Append(";\n");
|
||||
builder.Append(" float alphaK = clamp(outA, 0.0, 255.0) / 255.0;\n");
|
||||
builder.Append(", 0.0, 255.0);\n");
|
||||
builder.Append(" float alphaK = outA / 255.0;\n");
|
||||
|
||||
builder.Append(" float oR = clamp((");
|
||||
builder.Append(" float oR = floor(clamp((");
|
||||
EmitExpression(builder, program.OutputR);
|
||||
builder.Append(") * alphaK, 0.0, 255.0) / 255.0;\n");
|
||||
builder.Append(" float oG = clamp((");
|
||||
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 = clamp((");
|
||||
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 = clamp(outA, 0.0, 255.0) / 255.0;\n");
|
||||
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();
|
||||
|
||||
@@ -35,6 +35,9 @@ namespace LuaScript.Engine.Kernel
|
||||
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)
|
||||
{
|
||||
@@ -55,6 +58,11 @@ namespace LuaScript.Engine.Kernel
|
||||
int index = 0;
|
||||
while (index < block.Count && block[index] is LocalStmt prelude)
|
||||
{
|
||||
if (TryBindPixelData(prelude))
|
||||
{
|
||||
index++;
|
||||
continue;
|
||||
}
|
||||
BindLocal(prelude);
|
||||
index++;
|
||||
}
|
||||
@@ -72,11 +80,140 @@ namespace LuaScript.Engine.Kernel
|
||||
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 BuildKernel(inner.Body);
|
||||
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)
|
||||
@@ -112,7 +249,7 @@ namespace LuaScript.Engine.Kernel
|
||||
}
|
||||
}
|
||||
|
||||
if (body[^1] is not CallStmt { Call: var call } || !IsObjectMethod(call, "setpixel"))
|
||||
if (body[^1] is not CallStmt { Call: CallExpr call } || !IsObjectMethod(call, "setpixel"))
|
||||
return null;
|
||||
if (call.Arguments.Count is < 5 or > 6)
|
||||
return null;
|
||||
@@ -167,6 +304,10 @@ namespace LuaScript.Engine.Kernel
|
||||
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)
|
||||
@@ -187,6 +328,8 @@ namespace LuaScript.Engine.Kernel
|
||||
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:
|
||||
@@ -323,20 +466,36 @@ namespace LuaScript.Engine.Kernel
|
||||
return false;
|
||||
if (loop.Stop is not BinaryExpr { Operator: "-", Right: NumberExpr { Value: 1d } } bound)
|
||||
return false;
|
||||
if (bound.Left is not MemberExpr { Target: NameExpr { Name: "obj" }, Name: var field })
|
||||
return false;
|
||||
if (!KernelUniforms.TryResolveMember("obj", field, out var uniform))
|
||||
return false;
|
||||
|
||||
if (uniform == KernelUniform.Width)
|
||||
if (bound.Left is MemberExpr { Target: NameExpr { Name: "obj" }, Name: var field } &&
|
||||
KernelUniforms.TryResolveMember("obj", field, out var uniform))
|
||||
{
|
||||
axis = KAxis.X;
|
||||
return true;
|
||||
if (uniform == KernelUniform.Width)
|
||||
{
|
||||
axis = KAxis.X;
|
||||
return true;
|
||||
}
|
||||
if (uniform == KernelUniform.Height)
|
||||
{
|
||||
axis = KAxis.Y;
|
||||
return true;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
if (uniform == KernelUniform.Height)
|
||||
|
||||
if (_pixelDataVariable is not null &&
|
||||
bound.Left is MemberExpr { Target: NameExpr { } handle, Name: var pixelField } &&
|
||||
string.Equals(handle.Name, _pixelDataVariable, StringComparison.Ordinal))
|
||||
{
|
||||
axis = KAxis.Y;
|
||||
return true;
|
||||
if (pixelField == "width")
|
||||
{
|
||||
axis = KAxis.X;
|
||||
return true;
|
||||
}
|
||||
if (pixelField == "height")
|
||||
{
|
||||
axis = KAxis.Y;
|
||||
return true;
|
||||
}
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
@@ -35,6 +35,10 @@ namespace LuaScript.Engine.Kernel
|
||||
Track1,
|
||||
Track2,
|
||||
Track3,
|
||||
Slider0,
|
||||
Slider1,
|
||||
Slider2,
|
||||
Slider3,
|
||||
Check0,
|
||||
Check1,
|
||||
Check2,
|
||||
@@ -105,6 +109,10 @@ namespace LuaScript.Engine.Kernel
|
||||
["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,
|
||||
|
||||
@@ -38,6 +38,10 @@ namespace LuaScript.Engine.Kernel
|
||||
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;
|
||||
|
||||
@@ -20,6 +20,8 @@ namespace LuaScript.Engine.Kernel
|
||||
|
||||
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;
|
||||
@@ -30,7 +32,7 @@ namespace LuaScript.Engine.Kernel
|
||||
|
||||
internal sealed record AssignStmt(IReadOnlyList<LuaExpr> Targets, IReadOnlyList<LuaExpr> Values) : LuaStmt;
|
||||
|
||||
internal sealed record CallStmt(CallExpr Call) : LuaStmt;
|
||||
internal sealed record CallStmt(LuaExpr Call) : LuaStmt;
|
||||
|
||||
internal sealed record IfClause(LuaExpr Condition, IReadOnlyList<LuaStmt> Body);
|
||||
|
||||
|
||||
@@ -149,8 +149,8 @@ namespace LuaScript.Engine.Kernel
|
||||
return new AssignStmt(targets, values);
|
||||
}
|
||||
|
||||
if (first is CallExpr call)
|
||||
return new CallStmt(call);
|
||||
if (first is CallExpr or MethodCallExpr)
|
||||
return new CallStmt(first);
|
||||
|
||||
throw new KernelUnsupportedException("Expression is not a valid statement.");
|
||||
}
|
||||
@@ -275,6 +275,12 @@ namespace LuaScript.Engine.Kernel
|
||||
{
|
||||
expression = new CallExpr(expression, ParseArguments());
|
||||
}
|
||||
else if (t.IsSymbol(":"))
|
||||
{
|
||||
Advance();
|
||||
string method = ExpectName();
|
||||
expression = new MethodCallExpr(expression, method, ParseArguments());
|
||||
}
|
||||
else
|
||||
{
|
||||
break;
|
||||
|
||||
@@ -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<>);
|
||||
}
|
||||
}
|
||||
+297
-63
@@ -19,15 +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 byte[]? _resultBuffer;
|
||||
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)
|
||||
{
|
||||
@@ -43,7 +51,8 @@ namespace LuaScript.Engine
|
||||
public bool Execute(
|
||||
string script,
|
||||
double[] fields,
|
||||
byte[] pixels,
|
||||
IReadOnlyDictionary<string, string> stringParameters,
|
||||
PixelRegionAccess loadPixels,
|
||||
int width,
|
||||
int height,
|
||||
int timeoutMs,
|
||||
@@ -54,36 +63,50 @@ namespace LuaScript.Engine
|
||||
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 byte[]? newPixels,
|
||||
out int resultWidth,
|
||||
out int resultHeight,
|
||||
out string? error)
|
||||
{
|
||||
pixelsDirty = false;
|
||||
bufferReplaced = false;
|
||||
newPixels = null;
|
||||
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);
|
||||
@@ -107,7 +130,27 @@ namespace LuaScript.Engine
|
||||
if (status != NativeProtocol.StatusCallback)
|
||||
break;
|
||||
|
||||
DispatchCallback(view, resolveObject, loadFigure, loadText, loadImage, loadMovie, addEffect, addDraw);
|
||||
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();
|
||||
}
|
||||
|
||||
@@ -120,33 +163,114 @@ 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)
|
||||
if (pixelsDirty && (long)resultWidth * resultHeight * 4 > _allocatedSize - _pixelOffset)
|
||||
{
|
||||
if (bufferReplaced)
|
||||
{
|
||||
int pixelSize = resultWidth * resultHeight * 4;
|
||||
if (_resultBuffer == null || _resultBuffer.Length < pixelSize)
|
||||
_resultBuffer = new byte[pixelSize];
|
||||
view.ReadArray(NativeProtocol.PixelOffset, _resultBuffer, 0, pixelSize);
|
||||
newPixels = _resultBuffer;
|
||||
}
|
||||
else
|
||||
{
|
||||
view.ReadArray(NativeProtocol.PixelOffset, pixels, 0, pixels.Length);
|
||||
}
|
||||
error = "native worker reported a pixel buffer beyond capacity";
|
||||
return false;
|
||||
}
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
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,
|
||||
@@ -155,7 +279,9 @@ namespace LuaScript.Engine
|
||||
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)
|
||||
{
|
||||
int kind = view.ReadInt32(NativeProtocol.OffCallbackKind);
|
||||
switch (kind)
|
||||
@@ -178,41 +304,145 @@ namespace LuaScript.Engine
|
||||
case NativeProtocol.CbKindEffect:
|
||||
ResolveEffectCallback(view, addEffect);
|
||||
break;
|
||||
case NativeProtocol.CbKindDraw:
|
||||
ResolveDrawCallback(view, addDraw);
|
||||
case NativeProtocol.CbKindSetAnchor:
|
||||
ResolveSetAnchorCallback(view, setAnchor);
|
||||
break;
|
||||
case NativeProtocol.CbKindDrawPoly:
|
||||
ResolveDrawPolyCallback(view, addDraw);
|
||||
case NativeProtocol.CbKindSceneGet:
|
||||
ResolveSceneGetCallback(view, sceneGetValue);
|
||||
break;
|
||||
case NativeProtocol.CbKindSceneSet:
|
||||
ResolveSceneSetCallback(view, sceneSetValue);
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
private static void ResolveDrawCallback(MemoryMappedViewAccessor view, Action<DrawCommand> addDraw)
|
||||
private void ResolveSceneGetCallback(MemoryMappedViewAccessor view, Func<string, SceneValue> getValue)
|
||||
{
|
||||
long rOff = NativeProtocol.CallbackResultOffset;
|
||||
double ox = view.ReadDouble(rOff + 0 * 8);
|
||||
double oy = view.ReadDouble(rOff + 1 * 8);
|
||||
double oz = view.ReadDouble(rOff + 2 * 8);
|
||||
double zoom = view.ReadDouble(rOff + 3 * 8);
|
||||
double alpha = view.ReadDouble(rOff + 4 * 8);
|
||||
double aspect = view.ReadDouble(rOff + 5 * 8);
|
||||
double antialias = view.ReadDouble(rOff + 6 * 8);
|
||||
int tagLen = Math.Clamp(view.ReadInt32(NativeProtocol.OffCallbackTagLen), 0, NativeProtocol.CallbackTagMax);
|
||||
view.ReadArray(NativeProtocol.CallbackTagOffset, _callbackTag, 0, tagLen);
|
||||
string name = ResolveTag(tagLen);
|
||||
|
||||
try { addDraw(new DrawCommand(ox, oy, oz, zoom, alpha, aspect, null, antialias)); }
|
||||
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 static void ResolveDrawPolyCallback(MemoryMappedViewAccessor view, Action<DrawCommand> addDraw)
|
||||
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(NativeProtocol.CallbackTagOffset + i * 8);
|
||||
double antialias = view.ReadDouble(NativeProtocol.CallbackTagOffset + DrawPolyMath.Length * 8);
|
||||
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)); }
|
||||
try { addDraw(new DrawCommand(0d, 0d, 0d, 1d, poly[20], 0d, poly, antialias, blend)); }
|
||||
catch { }
|
||||
view.Write(NativeProtocol.OffCallbackFound, 1);
|
||||
}
|
||||
|
||||
private void ResolveGetObjectCallback(MemoryMappedViewAccessor view, Func<string, int, SceneObjectInfo?> resolveObject)
|
||||
@@ -264,7 +494,7 @@ namespace LuaScript.Engine
|
||||
catch { result = (new byte[4], 1, 1); }
|
||||
|
||||
int pixelSize = result.w * result.h * 4;
|
||||
long capacity = view.Capacity - NativeProtocol.PixelOffset;
|
||||
long capacity = view.Capacity - _pixelOffset;
|
||||
if (pixelSize > capacity)
|
||||
{
|
||||
result = (new byte[4], 1, 1);
|
||||
@@ -273,7 +503,7 @@ namespace LuaScript.Engine
|
||||
|
||||
view.Write(NativeProtocol.OffLoadResultWidth, result.w);
|
||||
view.Write(NativeProtocol.OffLoadResultHeight, result.h);
|
||||
view.WriteArray(NativeProtocol.PixelOffset, result.buffer, 0, pixelSize);
|
||||
WritePixelRegion(result.buffer, pixelSize);
|
||||
view.Write(NativeProtocol.OffCallbackFound, 1);
|
||||
}
|
||||
|
||||
@@ -299,7 +529,7 @@ namespace LuaScript.Engine
|
||||
catch { result = (new byte[4], 1, 1); }
|
||||
|
||||
int pixelSize = result.w * result.h * 4;
|
||||
long capacity = view.Capacity - NativeProtocol.PixelOffset;
|
||||
long capacity = view.Capacity - _pixelOffset;
|
||||
if (pixelSize > capacity)
|
||||
{
|
||||
result = (new byte[4], 1, 1);
|
||||
@@ -308,7 +538,7 @@ namespace LuaScript.Engine
|
||||
|
||||
view.Write(NativeProtocol.OffLoadResultWidth, result.w);
|
||||
view.Write(NativeProtocol.OffLoadResultHeight, result.h);
|
||||
view.WriteArray(NativeProtocol.PixelOffset, result.buffer, 0, pixelSize);
|
||||
WritePixelRegion(result.buffer, pixelSize);
|
||||
view.Write(NativeProtocol.OffCallbackFound, 1);
|
||||
}
|
||||
|
||||
@@ -325,7 +555,7 @@ namespace LuaScript.Engine
|
||||
catch { result = (new byte[4], 1, 1); }
|
||||
|
||||
int pixelSize = result.w * result.h * 4;
|
||||
long capacity = view.Capacity - NativeProtocol.PixelOffset;
|
||||
long capacity = view.Capacity - _pixelOffset;
|
||||
if (pixelSize > capacity)
|
||||
{
|
||||
result = (new byte[4], 1, 1);
|
||||
@@ -334,7 +564,7 @@ namespace LuaScript.Engine
|
||||
|
||||
view.Write(NativeProtocol.OffLoadResultWidth, result.w);
|
||||
view.Write(NativeProtocol.OffLoadResultHeight, result.h);
|
||||
view.WriteArray(NativeProtocol.PixelOffset, result.buffer, 0, pixelSize);
|
||||
WritePixelRegion(result.buffer, pixelSize);
|
||||
view.Write(NativeProtocol.OffCallbackFound, 1);
|
||||
}
|
||||
|
||||
@@ -352,7 +582,7 @@ namespace LuaScript.Engine
|
||||
catch { result = (new byte[4], 1, 1); }
|
||||
|
||||
int pixelSize = result.w * result.h * 4;
|
||||
long capacity = view.Capacity - NativeProtocol.PixelOffset;
|
||||
long capacity = view.Capacity - _pixelOffset;
|
||||
if (pixelSize > capacity)
|
||||
{
|
||||
result = (new byte[4], 1, 1);
|
||||
@@ -361,7 +591,7 @@ namespace LuaScript.Engine
|
||||
|
||||
view.Write(NativeProtocol.OffLoadResultWidth, result.w);
|
||||
view.Write(NativeProtocol.OffLoadResultHeight, result.h);
|
||||
view.WriteArray(NativeProtocol.PixelOffset, result.buffer, 0, pixelSize);
|
||||
WritePixelRegion(result.buffer, pixelSize);
|
||||
view.Write(NativeProtocol.OffCallbackFound, 1);
|
||||
}
|
||||
|
||||
@@ -409,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;
|
||||
@@ -449,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;
|
||||
@@ -89,6 +91,13 @@ namespace LuaScript.Engine
|
||||
f[NativeProtocol.Rxr],
|
||||
f[NativeProtocol.Ryr],
|
||||
f[NativeProtocol.Rzr]);
|
||||
|
||||
ctx.DrawStateOverride = f[NativeProtocol.DrawState] switch
|
||||
{
|
||||
1d => true,
|
||||
2d => false,
|
||||
_ => null,
|
||||
};
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -26,6 +26,8 @@ namespace LuaScript.Engine
|
||||
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;
|
||||
|
||||
@@ -39,10 +41,13 @@ namespace LuaScript.Engine
|
||||
public const int ErrorMax = 4 * 1024;
|
||||
|
||||
public const int CallbackTagOffset = ErrorOffset + ErrorMax;
|
||||
public const int CallbackTagMax = 4096;
|
||||
public const int CallbackTagMax = 8192;
|
||||
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;
|
||||
@@ -51,6 +56,16 @@ namespace LuaScript.Engine
|
||||
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;
|
||||
@@ -61,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;
|
||||
@@ -121,13 +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 const int MaxPixelBufferSize = 3840 * 2160 * 4;
|
||||
|
||||
public static long BufferSize(int width, int height) =>
|
||||
PixelOffset + Math.Max((long)width * height * 4, MaxPixelBufferSize);
|
||||
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);
|
||||
}
|
||||
@@ -9,23 +9,14 @@ namespace LuaScript.Engine
|
||||
|
||||
public static ScriptEngineKind ResolveAuto(string? script)
|
||||
{
|
||||
if (TryGetDirective(script, out var kind))
|
||||
return kind;
|
||||
if (UsesDrawingApi(script))
|
||||
if (string.IsNullOrEmpty(script))
|
||||
return ScriptEngineKind.MoonSharp;
|
||||
return UsesPixelApi(script) ? ScriptEngineKind.Native : ScriptEngineKind.MoonSharp;
|
||||
return TryGetDirective(script, out var kind) ? kind : ScriptEngineKind.Native;
|
||||
}
|
||||
|
||||
public static bool TryResolveExplicit(string? script, out ScriptEngineKind kind) =>
|
||||
TryGetDirective(script, out kind);
|
||||
|
||||
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.setoption", StringComparison.Ordinal);
|
||||
|
||||
private static bool TryGetDirective(string? script, out ScriptEngineKind kind)
|
||||
{
|
||||
kind = ScriptEngineKind.MoonSharp;
|
||||
|
||||
@@ -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);
|
||||
}
|
||||
}
|
||||
@@ -21,6 +21,7 @@ namespace LuaScript
|
||||
"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,7 +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",
|
||||
@@ -72,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.9.1</Version>
|
||||
<Version>1.13.2</Version>
|
||||
<Platforms>AnyCPU;x64</Platforms>
|
||||
<Nullable>enable</Nullable>
|
||||
<AllowUnsafeBlocks>true</AllowUnsafeBlocks>
|
||||
@@ -94,6 +94,10 @@
|
||||
<AdditionalFiles Include="**/*.csv" />
|
||||
</ItemGroup>
|
||||
|
||||
<ItemGroup>
|
||||
<EmbeddedResource Include="Compat\AviUtlCompatMap.xml" />
|
||||
</ItemGroup>
|
||||
|
||||
<ItemGroup>
|
||||
<PackageReference Include="MoonSharp" Version="2.0.0" />
|
||||
</ItemGroup>
|
||||
|
||||
@@ -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()
|
||||
{
|
||||
@@ -120,6 +248,10 @@ namespace LuaScript
|
||||
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);
|
||||
@@ -129,6 +261,17 @@ namespace LuaScript
|
||||
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);
|
||||
}
|
||||
@@ -152,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)
|
||||
|
||||
@@ -1,7 +1,10 @@
|
||||
using System.Collections.Immutable;
|
||||
using System.IO;
|
||||
using System.Numerics;
|
||||
using System.Runtime.InteropServices;
|
||||
using LuaScript.Anchor;
|
||||
using LuaScript.Compat;
|
||||
using LuaScript.Diagnostics;
|
||||
using LuaScript.Engine;
|
||||
using LuaScript.Engine.Kernel;
|
||||
using Vortice;
|
||||
@@ -29,13 +32,18 @@ namespace LuaScript
|
||||
double Track1,
|
||||
double Track2,
|
||||
double Track3,
|
||||
double Slider0,
|
||||
double Slider1,
|
||||
double Slider2,
|
||||
double Slider3,
|
||||
bool Check0,
|
||||
bool Check1,
|
||||
bool Check2,
|
||||
bool Check3,
|
||||
bool HasColor,
|
||||
int Color,
|
||||
string Script,
|
||||
int ScriptVersion,
|
||||
int StringsVersion,
|
||||
TimelineSourceUsage Usage,
|
||||
Guid SceneId,
|
||||
int TimelineFrame,
|
||||
@@ -49,6 +57,7 @@ namespace LuaScript
|
||||
int GroupCount,
|
||||
int TimelineTotalFrame,
|
||||
double TimelineTotalTime,
|
||||
int AnchorVersion,
|
||||
DrawDescription InputDesc
|
||||
);
|
||||
|
||||
@@ -67,6 +76,9 @@ namespace LuaScript
|
||||
private bool _effectChainWarned;
|
||||
private bool _gpuWarned;
|
||||
|
||||
private string? _scriptKeyRef;
|
||||
private int _scriptKeyVersion;
|
||||
|
||||
private string _kernelSource = string.Empty;
|
||||
private bool _kernelResolved;
|
||||
private KernelProgram? _kernelProgram;
|
||||
@@ -83,35 +95,87 @@ namespace LuaScript
|
||||
private string _lastSceneId = string.Empty;
|
||||
private bool _sceneIdCached;
|
||||
|
||||
private IGraphicsDevicesAndContext? _hostDevices;
|
||||
|
||||
private GraphicsDevicesAndContext? _ownCtx;
|
||||
|
||||
private PixelBufferManager? _pixelManager;
|
||||
|
||||
private RawRectF _pixelBounds;
|
||||
private int _pixelWidth;
|
||||
private int _pixelHeight;
|
||||
private Func<byte[]>? _pixelLoader;
|
||||
|
||||
private string _directiveSource = string.Empty;
|
||||
private bool _directiveCached;
|
||||
private ScriptEngineKind _autoKind;
|
||||
private bool _hasExplicitDirective;
|
||||
private ScriptEngineKind _explicitDirectiveKind;
|
||||
|
||||
private PixelRegionAccess? _nativeUpload;
|
||||
private PixelRegionAccess? _nativeReadIntoResult;
|
||||
private PixelRegionAccess? _nativeWriteOutput;
|
||||
private byte[]? _nativeResultBuffer;
|
||||
private int _nativeReadLength;
|
||||
private int _nativeOutputWidth;
|
||||
private int _nativeOutputHeight;
|
||||
private bool _nativeUploaded;
|
||||
private Func<string, int, SceneObjectInfo?>? _nativeResolveObject;
|
||||
private Func<string, int, double, double, double, (byte[] buffer, int w, int h)>? _nativeLoadFigure;
|
||||
private Func<string, string, double, bool, bool, int, (byte[] buffer, int w, int h)>? _nativeLoadText;
|
||||
private Func<string, (byte[] buffer, int w, int h)>? _nativeLoadImage;
|
||||
private Func<string, double, (byte[] buffer, int w, int h)>? _nativeLoadMovie;
|
||||
private Action<string, IReadOnlyList<KeyValuePair<string, object>>>? _nativeAddEffect;
|
||||
private Action<DrawCommand>? _nativeAddDraw;
|
||||
private Action<string, int, bool, int, double[]>? _nativeSetAnchor;
|
||||
private Func<string, SceneValue>? _nativeSceneGet;
|
||||
private Action<string, SceneValue>? _nativeSceneSet;
|
||||
|
||||
private bool _isFirst = true;
|
||||
private string _sourceScript = string.Empty;
|
||||
private string _runnableScript = string.Empty;
|
||||
private int[] _runnableLineMap = [];
|
||||
private bool _runnableCached;
|
||||
private ID2D1Image? _cachedInput;
|
||||
private RenderKey _cachedKey;
|
||||
private SceneObjectQuery[] _cachedQueries = [];
|
||||
private SceneValueQuery[] _cachedSceneValueQueries = [];
|
||||
private DrawDescription? _cachedOutputDesc;
|
||||
private ID2D1Image? _cachedEffectOutput;
|
||||
|
||||
private VideoEffectChain? _effectChain;
|
||||
private DrawCompositor? _drawCompositor;
|
||||
private FallbackCompositor? _bufferCompositor;
|
||||
private TextRenderer? _nativeTextRenderer;
|
||||
private ImageDecoder? _nativeImageDecoder;
|
||||
private MovieDecoder? _nativeMovieDecoder;
|
||||
|
||||
protected override ID2D1Image? CreateEffect(IGraphicsDevicesAndContext devices)
|
||||
{
|
||||
_hostDevices = devices;
|
||||
_ownCtx = new GraphicsDevicesAndContext(devices);
|
||||
disposer.Collect(_ownCtx);
|
||||
_pixelManager = new PixelBufferManager(_ownCtx);
|
||||
_bufferCompositor = new FallbackCompositor(
|
||||
new SynchronizedCompositor(new HardwareCompositor(_ownCtx), _pixelLoaderSemaphore),
|
||||
SoftwareCompositor.Instance,
|
||||
WarnBufferCompositorDegraded);
|
||||
_context.ResolverProvider = GetFrameResolver;
|
||||
_context.Compositor = _bufferCompositor;
|
||||
return null;
|
||||
}
|
||||
|
||||
private static void WarnBufferCompositorDegraded(Exception ex) =>
|
||||
Log.Default.Write("LuaScript: hardware buffer compositing failed; falling back to the software compositor.", ex);
|
||||
|
||||
private AviUtlScriptContext CreateScriptContext()
|
||||
{
|
||||
var context = new AviUtlScriptContext { ResolverProvider = GetFrameResolver };
|
||||
if (_bufferCompositor is not null)
|
||||
context.Compositor = _bufferCompositor;
|
||||
return context;
|
||||
}
|
||||
|
||||
private SceneObjectResolver GetFrameResolver()
|
||||
{
|
||||
if (!_frameResolverBuilt)
|
||||
@@ -138,12 +202,39 @@ namespace LuaScript
|
||||
if (_runnableCached && string.Equals(source, _sourceScript, StringComparison.Ordinal))
|
||||
return _runnableScript;
|
||||
|
||||
_runnableScript = AviUtlScript.Transform(source);
|
||||
var (code, lineMap) = AviUtlScript.TransformWithMap(source);
|
||||
_runnableScript = code;
|
||||
_runnableLineMap = lineMap;
|
||||
_sourceScript = source;
|
||||
_runnableCached = true;
|
||||
return _runnableScript;
|
||||
}
|
||||
|
||||
private static LuaScriptDiagnosticKind ClassifyDiagnostic(LuaScriptException exception) => exception switch
|
||||
{
|
||||
LuaScriptCompilationException => LuaScriptDiagnosticKind.Compile,
|
||||
LuaScriptTimeoutException => LuaScriptDiagnosticKind.Timeout,
|
||||
_ => LuaScriptDiagnosticKind.Runtime,
|
||||
};
|
||||
|
||||
private LuaScriptDiagnostic CreateDiagnostic(LuaScriptDiagnosticKind kind, string message)
|
||||
{
|
||||
var diagnostic = LuaScriptDiagnosticParser.Parse(kind, message);
|
||||
return diagnostic.Line > 0
|
||||
? diagnostic with { Line = MapRunnableLine(diagnostic.Line) }
|
||||
: diagnostic;
|
||||
}
|
||||
|
||||
private int MapRunnableLine(int runnableLine)
|
||||
{
|
||||
int index = runnableLine - 1;
|
||||
if (index < 0 || index >= _runnableLineMap.Length)
|
||||
return runnableLine;
|
||||
|
||||
int sourceLine = _runnableLineMap[index];
|
||||
return sourceLine >= 0 ? sourceLine + 1 : 0;
|
||||
}
|
||||
|
||||
protected override void setInput(ID2D1Image? input)
|
||||
{
|
||||
if (!ReferenceEquals(_cachedInput, input))
|
||||
@@ -166,6 +257,11 @@ namespace LuaScript
|
||||
var fps = desc.FPS;
|
||||
var time = desc.ItemPosition.Time.TotalSeconds;
|
||||
var script = item.Script ?? string.Empty;
|
||||
if (!ReferenceEquals(script, _scriptKeyRef))
|
||||
{
|
||||
_scriptKeyRef = script;
|
||||
_scriptKeyVersion++;
|
||||
}
|
||||
|
||||
var layout = item.Layout;
|
||||
var t0 = ClampTrack(item.Track0.GetValue(frame, length, fps), layout, 0);
|
||||
@@ -174,6 +270,7 @@ namespace LuaScript
|
||||
var t3 = ClampTrack(item.Track3.GetValue(frame, length, fps), layout, 3);
|
||||
|
||||
bool c0 = item.Check0, c1 = item.Check1, c2 = item.Check2, c3 = item.Check3;
|
||||
double s0 = item.Slider0, s1 = item.Slider1, s2 = item.Slider2, s3 = item.Slider3;
|
||||
bool hasColor = item.IsColorVisible;
|
||||
int colorRgb = hasColor ? (item.Color.R << 16) | (item.Color.G << 8) | item.Color.B : 0;
|
||||
|
||||
@@ -182,8 +279,10 @@ namespace LuaScript
|
||||
var key = new RenderKey(
|
||||
frame, time, length, fps,
|
||||
t0, t1, t2, t3,
|
||||
s0, s1, s2, s3,
|
||||
c0, c1, c2, c3, hasColor, colorRgb,
|
||||
script, desc.Usage, desc.SceneId,
|
||||
_scriptKeyVersion, RefreshStringParameters(),
|
||||
desc.Usage, desc.SceneId,
|
||||
desc.TimelinePosition.Frame,
|
||||
desc.TimelinePosition.Time.TotalSeconds,
|
||||
desc.ScreenSize.Width, desc.ScreenSize.Height,
|
||||
@@ -191,6 +290,7 @@ namespace LuaScript
|
||||
desc.GroupIndex, desc.GroupCount,
|
||||
desc.TimelineDuration.Frame,
|
||||
desc.TimelineDuration.Time.TotalSeconds,
|
||||
item.AnchorVersion,
|
||||
inDesc);
|
||||
|
||||
_frameDesc = desc;
|
||||
@@ -198,7 +298,11 @@ namespace LuaScript
|
||||
_frameResolverBuilt = false;
|
||||
|
||||
if (!_isFirst && key == _cachedKey &&
|
||||
(_cachedQueries.Length == 0 || QueriesMatch(_cachedQueries, GetFrameResolver())))
|
||||
(_cachedQueries.Length == 0 || QueriesMatch(_cachedQueries, GetFrameResolver())) &&
|
||||
(_cachedSceneValueQueries.Length == 0 || SceneValuesMatch(
|
||||
_cachedSceneValueQueries,
|
||||
SceneSharedValues.ForScene(_hostDevices!, ResolveSceneId(key.SceneId)),
|
||||
key.TimelineFrame)))
|
||||
{
|
||||
effectOutput = _cachedEffectOutput;
|
||||
return _cachedOutputDesc ?? inDesc;
|
||||
@@ -210,22 +314,27 @@ namespace LuaScript
|
||||
|
||||
var ctx = _context;
|
||||
PopulateContext(ctx, in key, imgW, imgH);
|
||||
ctx.SetPixelLoader(() => LoadInputPixels(bounds, imgW, imgH));
|
||||
_pixelBounds = bounds;
|
||||
_pixelWidth = imgW;
|
||||
_pixelHeight = imgH;
|
||||
ctx.SetPixelLoader(_pixelLoader ??= LoadPendingInputPixels);
|
||||
|
||||
DrawDescription outDesc = inDesc;
|
||||
IReadOnlyList<LuaScriptDiagnostic> diagnostics = [];
|
||||
|
||||
try
|
||||
{
|
||||
string runnable = GetRunnableScript(script);
|
||||
EnsureKernel(runnable);
|
||||
EnsureDirective(runnable);
|
||||
|
||||
if (ExecuteKernelLane(runnable, ctx, bounds, imgW, imgH))
|
||||
if (ExecuteKernelLane(ctx, bounds, imgW, imgH))
|
||||
{
|
||||
outDesc = inDesc;
|
||||
}
|
||||
else
|
||||
{
|
||||
bool wantNative = ScriptDirective.ResolveAuto(runnable) == ScriptEngineKind.Native;
|
||||
bool wantNative = _autoKind == ScriptEngineKind.Native;
|
||||
bool nativeReady = wantNative && LuaJitWorker.IsAvailable(NativeDirectory);
|
||||
if (wantNative && !nativeReady)
|
||||
WarnNativeUnavailableOnce();
|
||||
@@ -254,6 +363,8 @@ namespace LuaScript
|
||||
}
|
||||
}
|
||||
|
||||
ctx.PublishSceneValues();
|
||||
|
||||
if (ctx.DrawCommands.Count > 0)
|
||||
{
|
||||
ctx.EnsurePixelBuffer();
|
||||
@@ -265,6 +376,8 @@ namespace LuaScript
|
||||
}
|
||||
}
|
||||
|
||||
ApplyDrawState(ctx, bounds);
|
||||
|
||||
outDesc = BuildOutputDesc(inDesc, ctx);
|
||||
|
||||
if (ctx.EffectRequests.Count > 0)
|
||||
@@ -280,21 +393,27 @@ namespace LuaScript
|
||||
WarnEffectChainFailureOnce(ex);
|
||||
}
|
||||
}
|
||||
|
||||
outDesc = AddAnchorControllers(outDesc, ctx);
|
||||
}
|
||||
}
|
||||
catch (LuaScriptTimeoutException ex)
|
||||
{
|
||||
effectOutput = null;
|
||||
_context = new AviUtlScriptContext { ResolverProvider = GetFrameResolver };
|
||||
_context = CreateScriptContext();
|
||||
_isFirst = true;
|
||||
DebugOutput.Write(ex.Message);
|
||||
Log.Default.Write(ex.Message, ex);
|
||||
LuaScriptDiagnostics.Instance.Report(script, [CreateDiagnostic(LuaScriptDiagnosticKind.Timeout, ex.Message)]);
|
||||
return inDesc;
|
||||
}
|
||||
catch (LuaScriptException ex)
|
||||
{
|
||||
effectOutput = null;
|
||||
outDesc = inDesc;
|
||||
DebugOutput.Write(ex.Message);
|
||||
Log.Default.Write(ex.Message, ex);
|
||||
diagnostics = [CreateDiagnostic(ClassifyDiagnostic(ex), ex.Message)];
|
||||
}
|
||||
finally
|
||||
{
|
||||
@@ -302,9 +421,12 @@ namespace LuaScript
|
||||
_pixelLoaderSemaphore.Release();
|
||||
}
|
||||
|
||||
LuaScriptDiagnostics.Instance.Report(script, diagnostics);
|
||||
|
||||
_isFirst = false;
|
||||
_cachedKey = key;
|
||||
_cachedQueries = ctx.ObjectQueries.Count == 0 ? [] : [.. ctx.ObjectQueries];
|
||||
_cachedSceneValueQueries = ctx.SceneValueQueries.Count == 0 ? [] : [.. ctx.SceneValueQueries];
|
||||
_cachedOutputDesc = outDesc;
|
||||
_cachedEffectOutput = effectOutput;
|
||||
|
||||
@@ -314,7 +436,8 @@ namespace LuaScript
|
||||
private ID2D1Image ApplyEffectChain(ID2D1Image source, IReadOnlyList<AviUtlEffectRequest> requests, EffectDescription desc, ref DrawDescription drawDescription)
|
||||
{
|
||||
_effectChain ??= new VideoEffectChain(_ownCtx!);
|
||||
return _effectChain.Apply(source, requests, desc, ref drawDescription);
|
||||
var target = AviUtlCompatMap.ResolveTarget(item.Script);
|
||||
return _effectChain.Apply(source, requests, desc, target, ref drawDescription);
|
||||
}
|
||||
|
||||
private static SceneObjectResolver BuildSceneObjectResolver(EffectDescription desc)
|
||||
@@ -352,6 +475,16 @@ namespace LuaScript
|
||||
return new SceneObjectResolver([.. entries], desc.FPS);
|
||||
}
|
||||
|
||||
private static bool SceneValuesMatch(SceneValueQuery[] queries, SceneSharedValues values, long generation)
|
||||
{
|
||||
for (int i = 0; i < queries.Length; i++)
|
||||
{
|
||||
if (values.Read(generation, queries[i].Name) != queries[i].Result)
|
||||
return false;
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
private static bool QueriesMatch(SceneObjectQuery[] queries, SceneObjectResolver resolver)
|
||||
{
|
||||
for (int i = 0; i < queries.Length; i++)
|
||||
@@ -364,6 +497,52 @@ namespace LuaScript
|
||||
return true;
|
||||
}
|
||||
|
||||
private static readonly string[] s_stringParameterNames =
|
||||
[
|
||||
"text", "font", "dir",
|
||||
"file_video", "file_audio", "file_image", "file_project",
|
||||
"file_mp4", "file_exo", "file_subtitle", "file_shader",
|
||||
];
|
||||
|
||||
private readonly string?[] _stringParameterValues = new string?[s_stringParameterNames.Length];
|
||||
private int _stringParametersVersion;
|
||||
|
||||
private int RefreshStringParameters()
|
||||
{
|
||||
var values = _stringParameterValues;
|
||||
bool changed = false;
|
||||
changed |= UpdateStringSlot(values, 0, item.Text);
|
||||
changed |= UpdateStringSlot(values, 1, item.Font);
|
||||
changed |= UpdateStringSlot(values, 2, item.Directory);
|
||||
changed |= UpdateStringSlot(values, 3, item.FileVideo);
|
||||
changed |= UpdateStringSlot(values, 4, item.FileAudio);
|
||||
changed |= UpdateStringSlot(values, 5, item.FileImage);
|
||||
changed |= UpdateStringSlot(values, 6, item.FileProject);
|
||||
changed |= UpdateStringSlot(values, 7, item.FileMp4);
|
||||
changed |= UpdateStringSlot(values, 8, item.FileExo);
|
||||
changed |= UpdateStringSlot(values, 9, item.FileSubtitle);
|
||||
changed |= UpdateStringSlot(values, 10, item.FileShader);
|
||||
if (changed)
|
||||
_stringParametersVersion++;
|
||||
return _stringParametersVersion;
|
||||
}
|
||||
|
||||
private static bool UpdateStringSlot(string?[] values, int index, string value)
|
||||
{
|
||||
if (ReferenceEquals(values[index], value))
|
||||
return false;
|
||||
values[index] = value;
|
||||
return true;
|
||||
}
|
||||
|
||||
private void PopulateStringParameters(AviUtlScriptContext ctx)
|
||||
{
|
||||
var names = s_stringParameterNames;
|
||||
var values = _stringParameterValues;
|
||||
for (int i = 0; i < names.Length; i++)
|
||||
ctx.SetStringParameter(names[i], values[i]);
|
||||
}
|
||||
|
||||
private void PopulateContext(AviUtlScriptContext ctx, in RenderKey key, int imgW, int imgH)
|
||||
{
|
||||
var zoom = key.InputDesc.Zoom;
|
||||
@@ -375,6 +554,10 @@ namespace LuaScript
|
||||
ctx.ClearQueries();
|
||||
ctx.ClearEffects();
|
||||
ctx.ClearDraws();
|
||||
ctx.ClearAnchorRequests();
|
||||
ctx.AnchorSource = item.Anchors;
|
||||
ctx.DrawStateOverride = null;
|
||||
ctx.ResetDrawTarget();
|
||||
|
||||
ctx.ImageWidth = imgW;
|
||||
ctx.ImageHeight = imgH;
|
||||
@@ -396,6 +579,10 @@ namespace LuaScript
|
||||
ctx.Track1 = key.Track1;
|
||||
ctx.Track2 = key.Track2;
|
||||
ctx.Track3 = key.Track3;
|
||||
ctx.Slider0 = key.Slider0;
|
||||
ctx.Slider1 = key.Slider1;
|
||||
ctx.Slider2 = key.Slider2;
|
||||
ctx.Slider3 = key.Slider3;
|
||||
ctx.Check0 = key.Check0;
|
||||
ctx.Check1 = key.Check1;
|
||||
ctx.Check2 = key.Check2;
|
||||
@@ -423,6 +610,9 @@ namespace LuaScript
|
||||
ctx.IsPaused = key.Usage == TimelineSourceUsage.Paused;
|
||||
ctx.SceneId = ResolveSceneId(key.SceneId);
|
||||
ctx.TimeRatio = key.Length > 0 ? key.Frame / (double)key.Length : 0d;
|
||||
PopulateStringParameters(ctx);
|
||||
ctx.SceneScope = _hostDevices;
|
||||
ctx.BeginSceneValues();
|
||||
}
|
||||
|
||||
private static double ClampTrack(double value, AviUtlParameterLayout layout, int index)
|
||||
@@ -430,6 +620,143 @@ namespace LuaScript
|
||||
return layout.GetTrack(index) is { } p ? Math.Clamp(value, p.Min, p.Max) : value;
|
||||
}
|
||||
|
||||
private ImmutableList<VideoEffectController> _anchorControllers = ImmutableList<VideoEffectController>.Empty;
|
||||
private AnchorRequestData[] _anchorSignature = [];
|
||||
private IReadOnlyList<LuaAnchorPoint>? _anchorSignatureSource;
|
||||
|
||||
private ImmutableList<VideoEffectController> ResolveAnchorControllers(AviUtlScriptContext ctx)
|
||||
{
|
||||
var requests = ctx.AnchorRequests;
|
||||
if (requests.Count == 0)
|
||||
{
|
||||
_anchorControllers = ImmutableList<VideoEffectController>.Empty;
|
||||
_anchorSignature = [];
|
||||
_anchorSignatureSource = null;
|
||||
return _anchorControllers;
|
||||
}
|
||||
|
||||
if (ReferenceEquals(_anchorSignatureSource, ctx.AnchorSource) && AnchorSignatureMatches(requests))
|
||||
return _anchorControllers;
|
||||
|
||||
_anchorControllers = BuildAnchorControllers(ctx.AnchorSource, requests);
|
||||
_anchorSignature = new AnchorRequestData[requests.Count];
|
||||
for (int i = 0; i < requests.Count; i++)
|
||||
_anchorSignature[i] = requests[i];
|
||||
_anchorSignatureSource = ctx.AnchorSource;
|
||||
return _anchorControllers;
|
||||
}
|
||||
|
||||
private bool AnchorSignatureMatches(IReadOnlyList<AnchorRequestData> requests)
|
||||
{
|
||||
if (_anchorSignature.Length != requests.Count)
|
||||
return false;
|
||||
for (int i = 0; i < requests.Count; i++)
|
||||
if (!_anchorSignature[i].Equals(requests[i]))
|
||||
return false;
|
||||
return true;
|
||||
}
|
||||
|
||||
private DrawDescription AddAnchorControllers(DrawDescription desc, AviUtlScriptContext ctx)
|
||||
{
|
||||
var controllers = ResolveAnchorControllers(ctx);
|
||||
return controllers.Count == 0 ? desc : desc with { Controllers = desc.Controllers.AddRange(controllers) };
|
||||
}
|
||||
|
||||
private ImmutableList<VideoEffectController> BuildAnchorControllers(
|
||||
IReadOnlyList<LuaAnchorPoint>? source, IReadOnlyList<AnchorRequestData> requests)
|
||||
{
|
||||
var builder = ImmutableList.CreateBuilder<VideoEffectController>();
|
||||
foreach (var request in requests)
|
||||
{
|
||||
if (request.Count <= 0)
|
||||
continue;
|
||||
|
||||
AddConnectionControllers(builder, source, request);
|
||||
|
||||
var group = request.Group;
|
||||
bool is3D = request.Is3D;
|
||||
for (int i = 0; i < request.Count; i++)
|
||||
{
|
||||
AnchorSupport.ResolvePosition(source, group, i, out double x, out double y, out double z);
|
||||
int index = i;
|
||||
var point = new ControllerPoint(
|
||||
new Vector3((float)x, (float)y, (float)(is3D ? z : 0d)),
|
||||
arg => item.ApplyAnchorDrag(group, index, arg.Delta.X, arg.Delta.Y, is3D ? arg.Delta.Z : 0d))
|
||||
{
|
||||
Shape = VideoControllerPointShape.Circle,
|
||||
};
|
||||
builder.Add(new VideoEffectController(item, [point]));
|
||||
}
|
||||
}
|
||||
return builder.ToImmutable();
|
||||
}
|
||||
|
||||
private void AddConnectionControllers(
|
||||
ImmutableList<VideoEffectController>.Builder builder, IReadOnlyList<LuaAnchorPoint>? source, in AnchorRequestData request)
|
||||
{
|
||||
switch (request.Connection)
|
||||
{
|
||||
case AnchorConnection.Line:
|
||||
for (int i = 0; i + 1 < request.Count; i++)
|
||||
AddEdge(builder, ConnectionPoint(source, request, i), ConnectionPoint(source, request, i + 1));
|
||||
break;
|
||||
case AnchorConnection.Loop:
|
||||
for (int i = 0; i + 1 < request.Count; i++)
|
||||
AddEdge(builder, ConnectionPoint(source, request, i), ConnectionPoint(source, request, i + 1));
|
||||
if (request.Count >= 2)
|
||||
AddEdge(builder, ConnectionPoint(source, request, request.Count - 1), ConnectionPoint(source, request, 0));
|
||||
break;
|
||||
case AnchorConnection.Star:
|
||||
for (int i = 0; i < request.Count; i++)
|
||||
AddEdge(builder, CenterPoint(), ConnectionPoint(source, request, i));
|
||||
break;
|
||||
case AnchorConnection.Arm:
|
||||
if (request.Count >= 1)
|
||||
AddEdge(builder, CenterPoint(), ConnectionPoint(source, request, 0));
|
||||
for (int i = 0; i + 1 < request.Count; i++)
|
||||
AddEdge(builder, ConnectionPoint(source, request, i), ConnectionPoint(source, request, i + 1));
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
private void AddEdge(ImmutableList<VideoEffectController>.Builder builder, ControllerPoint a, ControllerPoint b) =>
|
||||
builder.Add(new VideoEffectController(item, [a, b]) { Connection = VideoControllerPointConnection.Line });
|
||||
|
||||
private static ControllerPoint CenterPoint() =>
|
||||
new(Vector3.Zero) { Shape = VideoControllerPointShape.None };
|
||||
|
||||
private static ControllerPoint ConnectionPoint(IReadOnlyList<LuaAnchorPoint>? source, in AnchorRequestData request, int index)
|
||||
{
|
||||
AnchorSupport.ResolvePosition(source, request.Group, index, out double x, out double y, out double z);
|
||||
return new ControllerPoint(new Vector3((float)x, (float)y, (float)(request.Is3D ? z : 0d)))
|
||||
{
|
||||
Shape = VideoControllerPointShape.None,
|
||||
};
|
||||
}
|
||||
|
||||
private void ApplyDrawState(AviUtlScriptContext ctx, RawRectF bounds)
|
||||
{
|
||||
if (ctx.DrawStateOverride is not { } drawn)
|
||||
return;
|
||||
|
||||
if (!drawn)
|
||||
{
|
||||
effectOutput = null;
|
||||
return;
|
||||
}
|
||||
|
||||
if (effectOutput is not null)
|
||||
return;
|
||||
|
||||
ctx.EnsurePixelBuffer();
|
||||
var buffer = ctx.GetPixelBuffer();
|
||||
if (buffer is null)
|
||||
return;
|
||||
|
||||
_pixelManager!.WritePixelsToOutput(buffer, ctx.ImageWidth, ctx.ImageHeight);
|
||||
effectOutput = _pixelManager.GetTransformOutput(bounds.Left, bounds.Top);
|
||||
}
|
||||
|
||||
private static DrawDescription BuildOutputDesc(DrawDescription inDesc, AviUtlScriptContext ctx)
|
||||
{
|
||||
return inDesc with
|
||||
@@ -456,19 +783,31 @@ namespace LuaScript
|
||||
_gpuKernelChecked = false;
|
||||
}
|
||||
|
||||
private bool ExecuteKernelLane(string runnable, AviUtlScriptContext ctx, RawRectF bounds, int imgW, int imgH)
|
||||
private void EnsureDirective(string runnable)
|
||||
{
|
||||
if (_directiveCached && string.Equals(runnable, _directiveSource, StringComparison.Ordinal))
|
||||
return;
|
||||
|
||||
_directiveSource = runnable;
|
||||
_directiveCached = true;
|
||||
_hasExplicitDirective = ScriptDirective.TryResolveExplicit(runnable, out _explicitDirectiveKind);
|
||||
_autoKind = ScriptDirective.ResolveAuto(runnable);
|
||||
}
|
||||
|
||||
private bool ExecuteKernelLane(AviUtlScriptContext ctx, RawRectF bounds, int imgW, int imgH)
|
||||
{
|
||||
if (_kernelProgram is null || _cpuKernel is null)
|
||||
return false;
|
||||
|
||||
bool explicitDirective = ScriptDirective.TryResolveExplicit(runnable, out var kind);
|
||||
bool explicitDirective = _hasExplicitDirective;
|
||||
var kind = _explicitDirectiveKind;
|
||||
if (explicitDirective && kind is not (ScriptEngineKind.Gpu or ScriptEngineKind.Cpu))
|
||||
return false;
|
||||
|
||||
_kernelUniforms ??= KernelUniformBinding.Create();
|
||||
KernelUniformBinding.Fill(ctx, _kernelUniforms);
|
||||
|
||||
if (explicitDirective && kind == ScriptEngineKind.Gpu)
|
||||
if (!explicitDirective || kind == ScriptEngineKind.Gpu)
|
||||
{
|
||||
var gpu = GetGpuKernel();
|
||||
if (gpu is not null)
|
||||
@@ -476,7 +815,8 @@ namespace LuaScript
|
||||
effectOutput = gpu.Apply(input!, _kernelUniforms);
|
||||
return true;
|
||||
}
|
||||
WarnGpuUnavailableOnce();
|
||||
if (explicitDirective)
|
||||
WarnGpuUnavailableOnce();
|
||||
}
|
||||
|
||||
byte[] buffer = LoadInputPixels(bounds, imgW, imgH);
|
||||
@@ -492,16 +832,22 @@ namespace LuaScript
|
||||
return _gpuKernel;
|
||||
|
||||
_gpuKernelChecked = true;
|
||||
if (_kernelProgram is null)
|
||||
if (_kernelProgram is null || _cpuKernel is null)
|
||||
return null;
|
||||
|
||||
try
|
||||
{
|
||||
var kernel = new GpuKernel(_ownCtx!, _kernelProgram);
|
||||
if (kernel.IsReady)
|
||||
if (kernel.IsReady && kernel.Verify(_cpuKernel))
|
||||
{
|
||||
_gpuKernel = kernel;
|
||||
}
|
||||
else
|
||||
{
|
||||
if (kernel.IsReady)
|
||||
Log.Default.Write("LuaScript: GPU kernel output diverges from the CPU kernel beyond tolerance; using the CPU kernel.");
|
||||
kernel.Dispose();
|
||||
}
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
@@ -535,20 +881,34 @@ namespace LuaScript
|
||||
{
|
||||
_nativeWorker ??= new LuaJitWorker(NativeDirectory);
|
||||
_nativeFields ??= new double[NativeProtocol.FieldCount];
|
||||
_nativeUpload ??= UploadNativeInputPixels;
|
||||
_nativeResolveObject ??= (tag, frame) => _context.ResolveObject(tag, frame, out var info) ? info : null;
|
||||
_nativeLoadFigure ??= NativeLoadFigure;
|
||||
_nativeLoadText ??= NativeLoadText;
|
||||
_nativeLoadImage ??= NativeLoadImage;
|
||||
_nativeLoadMovie ??= NativeLoadMovie;
|
||||
_nativeAddEffect ??= (name, args) => _context.AddEffect(new AviUtlEffectRequest(name, args));
|
||||
_nativeAddDraw ??= command => _context.AddDraw(command);
|
||||
_nativeSetAnchor ??= ResolveNativeAnchor;
|
||||
_nativeSceneGet ??= name => _context.GetSceneValue(name);
|
||||
_nativeSceneSet ??= (name, value) => _context.SetSceneValue(name, value);
|
||||
|
||||
NativeFieldMap.ToFields(ctx, _nativeFields);
|
||||
byte[] buffer = LoadInputPixels(bounds, imgW, imgH);
|
||||
_nativeUploaded = false;
|
||||
|
||||
bool ok = _nativeWorker.Execute(
|
||||
script, _nativeFields, buffer, imgW, imgH, NativeTimeoutMilliseconds,
|
||||
(tag, frame) => ctx.ResolveObject(tag, frame, out var info) ? info : null,
|
||||
NativeLoadFigure,
|
||||
NativeLoadText,
|
||||
NativeLoadImage,
|
||||
NativeLoadMovie,
|
||||
(name, args) => ctx.AddEffect(new AviUtlEffectRequest(name, args)),
|
||||
ctx.AddDraw,
|
||||
out bool dirty, out bool bufferReplaced, out byte[]? newPixels,
|
||||
script, _nativeFields, ctx.StringParameters, _nativeUpload, imgW, imgH, NativeTimeoutMilliseconds,
|
||||
_nativeResolveObject,
|
||||
_nativeLoadFigure,
|
||||
_nativeLoadText,
|
||||
_nativeLoadImage,
|
||||
_nativeLoadMovie,
|
||||
_nativeAddEffect,
|
||||
_nativeAddDraw,
|
||||
_nativeSetAnchor,
|
||||
_nativeSceneGet,
|
||||
_nativeSceneSet,
|
||||
out bool dirty, out bool bufferReplaced,
|
||||
out int resultW, out int resultH, out string? error);
|
||||
|
||||
if (!ok)
|
||||
@@ -566,31 +926,31 @@ namespace LuaScript
|
||||
{
|
||||
int outW = bufferReplaced ? resultW : imgW;
|
||||
int outH = bufferReplaced ? resultH : imgH;
|
||||
byte[] outPixels = buffer;
|
||||
|
||||
if (bufferReplaced && newPixels != null)
|
||||
{
|
||||
outPixels = newPixels;
|
||||
ctx.ReplaceBuffer(outPixels, outW, outH);
|
||||
}
|
||||
|
||||
if (hasDraws)
|
||||
{
|
||||
ctx.SetResolvedBuffer(outPixels, outW, outH);
|
||||
var result = ReadNativeResultPixels(outW, outH);
|
||||
if (bufferReplaced)
|
||||
ctx.ReplaceBuffer(result, outW, outH);
|
||||
else
|
||||
ctx.SetResolvedBuffer(result, outW, outH);
|
||||
return true;
|
||||
}
|
||||
|
||||
_pixelManager!.WritePixelsToOutput(outPixels, outW, outH);
|
||||
_nativeOutputWidth = outW;
|
||||
_nativeOutputHeight = outH;
|
||||
_nativeWorker.ReadPixels(_nativeWriteOutput ??= WriteNativeOutputPixels);
|
||||
if (bufferReplaced)
|
||||
effectOutput = _pixelManager.GetTransformOutput(-outW / 2f, -outH / 2f);
|
||||
effectOutput = _pixelManager!.GetTransformOutput(-outW / 2f, -outH / 2f);
|
||||
else
|
||||
effectOutput = _pixelManager.GetTransformOutput(bounds.Left, bounds.Top);
|
||||
effectOutput = _pixelManager!.GetTransformOutput(bounds.Left, bounds.Top);
|
||||
return true;
|
||||
}
|
||||
|
||||
if (hasDraws)
|
||||
{
|
||||
ctx.SetResolvedBuffer(buffer, imgW, imgH);
|
||||
if (_nativeUploaded)
|
||||
ctx.SetResolvedBuffer(ReadNativeResultPixels(imgW, imgH), imgW, imgH);
|
||||
return false;
|
||||
}
|
||||
|
||||
@@ -598,6 +958,57 @@ namespace LuaScript
|
||||
return false;
|
||||
}
|
||||
|
||||
private void UploadNativeInputPixels(nint address, long capacity)
|
||||
{
|
||||
_nativeUploaded = true;
|
||||
_pixelLoaderSemaphore.Wait();
|
||||
try
|
||||
{
|
||||
_pixelManager!.LoadInputPixelsInto(input!, _pixelBounds, _pixelWidth, _pixelHeight, address, capacity);
|
||||
}
|
||||
finally
|
||||
{
|
||||
_pixelLoaderSemaphore.Release();
|
||||
}
|
||||
}
|
||||
|
||||
private byte[] ReadNativeResultPixels(int width, int height)
|
||||
{
|
||||
int length = width * height * 4;
|
||||
if (_nativeResultBuffer is null || _nativeResultBuffer.Length < length)
|
||||
_nativeResultBuffer = new byte[length];
|
||||
_nativeReadLength = length;
|
||||
_nativeWorker!.ReadPixels(_nativeReadIntoResult ??= ReadNativePixelsIntoResult);
|
||||
return _nativeResultBuffer;
|
||||
}
|
||||
|
||||
private unsafe void ReadNativePixelsIntoResult(nint address, long capacity)
|
||||
{
|
||||
fixed (byte* destination = _nativeResultBuffer)
|
||||
Buffer.MemoryCopy((void*)address, destination, _nativeResultBuffer!.Length, Math.Min(_nativeReadLength, capacity));
|
||||
}
|
||||
|
||||
private void WriteNativeOutputPixels(nint address, long capacity)
|
||||
{
|
||||
_pixelManager!.WritePixelsToOutput(address, _nativeOutputWidth, _nativeOutputHeight);
|
||||
}
|
||||
|
||||
private void ResolveNativeAnchor(string group, int count, bool is3D, int connection, double[] positions)
|
||||
{
|
||||
_context.AddAnchorRequest(new AnchorRequestData(group, count, (AnchorConnection)connection, is3D));
|
||||
|
||||
int stride = is3D ? 3 : 2;
|
||||
var source = _context.AnchorSource;
|
||||
for (int i = 0; i < count; i++)
|
||||
{
|
||||
AnchorSupport.ResolvePosition(source, group, i, out double x, out double y, out double z);
|
||||
positions[i * stride + 0] = x;
|
||||
positions[i * stride + 1] = y;
|
||||
if (is3D)
|
||||
positions[i * stride + 2] = z;
|
||||
}
|
||||
}
|
||||
|
||||
private (byte[] buffer, int w, int h) NativeLoadText(string family, string text, double size, bool bold, bool italic, int color)
|
||||
{
|
||||
_nativeTextRenderer ??= new TextRenderer();
|
||||
@@ -631,6 +1042,8 @@ namespace LuaScript
|
||||
return (buffer, fw, fh);
|
||||
}
|
||||
|
||||
private byte[] LoadPendingInputPixels() => LoadInputPixels(_pixelBounds, _pixelWidth, _pixelHeight);
|
||||
|
||||
private byte[] LoadInputPixels(RawRectF bounds, int width, int height)
|
||||
{
|
||||
_pixelLoaderSemaphore.Wait();
|
||||
@@ -653,6 +1066,7 @@ namespace LuaScript
|
||||
_nativeWorker?.Dispose();
|
||||
_effectChain?.Dispose();
|
||||
_drawCompositor?.Dispose();
|
||||
_bufferCompositor?.Dispose();
|
||||
_nativeTextRenderer?.Dispose();
|
||||
_nativeImageDecoder?.Dispose();
|
||||
_pixelLoaderSemaphore.Dispose();
|
||||
|
||||
@@ -1,3 +1,4 @@
|
||||
using LuaScript.Anchor;
|
||||
using LuaScript.Compat;
|
||||
using MoonSharp.Interpreter;
|
||||
using MoonSharp.Interpreter.Debugging;
|
||||
@@ -170,6 +171,7 @@ namespace LuaScript
|
||||
CoreModules.ErrorHandling);
|
||||
script.Options.ScriptLoader = new DisabledFileScriptLoader();
|
||||
script.AttachDebugger(_debugger);
|
||||
AviUtlGlobalRegistrar.RegisterFunctions(script.Globals, CurrentTimeRatio);
|
||||
_script = script;
|
||||
}
|
||||
|
||||
@@ -226,6 +228,7 @@ namespace LuaScript
|
||||
if (isFirstSetup)
|
||||
{
|
||||
var sceneTable = new Table(script);
|
||||
RegisterSceneCallbacks(sceneTable);
|
||||
script.Globals["scene"] = sceneTable;
|
||||
|
||||
var objTable = new Table(script);
|
||||
@@ -251,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;
|
||||
@@ -333,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;
|
||||
@@ -418,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) =>
|
||||
@@ -581,7 +609,7 @@ namespace LuaScript
|
||||
double alpha = args.Count > 4 ? args[4].CastToNumber() ?? 1d : 1d;
|
||||
double aspect = args.Count > 5 ? args[5].CastToNumber() ?? 0d : 0d;
|
||||
|
||||
_activeContext.AddDraw(new DrawCommand(ox, oy, oz, zoom, alpha, aspect, null, CurrentAntialias()));
|
||||
_activeContext.SubmitDraw(new DrawCommand(ox, oy, oz, zoom, alpha, aspect, null, CurrentAntialias(), CurrentBlend()));
|
||||
return DynValue.Void;
|
||||
});
|
||||
|
||||
@@ -617,7 +645,7 @@ namespace LuaScript
|
||||
_ => 1d,
|
||||
};
|
||||
|
||||
_activeContext.AddDraw(new DrawCommand(0d, 0d, 0d, 1d, poly[20], 0d, poly, CurrentAntialias()));
|
||||
_activeContext.SubmitDraw(new DrawCommand(0d, 0d, 0d, 1d, poly[20], 0d, poly, CurrentAntialias(), CurrentBlend()));
|
||||
return DynValue.Void;
|
||||
});
|
||||
|
||||
@@ -642,12 +670,68 @@ namespace LuaScript
|
||||
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;
|
||||
_options[args[0].String] = args.Count > 1 ? args[1] : DynValue.True;
|
||||
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;
|
||||
});
|
||||
|
||||
@@ -674,6 +758,11 @@ namespace LuaScript
|
||||
? 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));
|
||||
|
||||
@@ -1,7 +1,6 @@
|
||||
using System;
|
||||
using Vortice;
|
||||
using System.Numerics;
|
||||
using System.Runtime.InteropServices;
|
||||
using Vortice.DCommon;
|
||||
using Vortice.Direct2D1;
|
||||
using Vortice.Direct2D1.Effects;
|
||||
@@ -18,6 +17,7 @@ namespace LuaScript
|
||||
private ID2D1Bitmap1? _stagingBitmap;
|
||||
private ID2D1Bitmap1? _outputBitmap;
|
||||
private AffineTransform2D? _transformEffect;
|
||||
private ID2D1Image? _transformOutput;
|
||||
private byte[]? _pixelBuffer;
|
||||
private int _bitmapWidth;
|
||||
private int _bitmapHeight;
|
||||
@@ -28,38 +28,16 @@ namespace LuaScript
|
||||
_ctx = ctx;
|
||||
}
|
||||
|
||||
public byte[] LoadInputPixels(ID2D1Image input, RawRectF bounds, int width, int height)
|
||||
public unsafe byte[] LoadInputPixels(ID2D1Image input, RawRectF bounds, int width, int height)
|
||||
{
|
||||
EnsureBitmaps(width, height);
|
||||
RenderToStaging(input, bounds);
|
||||
|
||||
var dc = _ctx.DeviceContext;
|
||||
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!);
|
||||
|
||||
var mapped = _stagingBitmap.Map(MapOptions.Read);
|
||||
var mapped = _stagingBitmap!.Map(MapOptions.Read);
|
||||
try
|
||||
{
|
||||
if (mapped.Pitch == width * 4)
|
||||
{
|
||||
Marshal.Copy(mapped.Bits, _pixelBuffer!, 0, width * height * 4);
|
||||
}
|
||||
else
|
||||
{
|
||||
for (int row = 0; row < height; row++)
|
||||
Marshal.Copy(
|
||||
mapped.Bits + mapped.Pitch * row,
|
||||
_pixelBuffer!,
|
||||
row * width * 4,
|
||||
width * 4);
|
||||
}
|
||||
fixed (byte* destination = _pixelBuffer)
|
||||
CopyStagingRows(mapped.Bits, mapped.Pitch, destination, _pixelBuffer!.Length, width, height);
|
||||
}
|
||||
finally
|
||||
{
|
||||
@@ -69,6 +47,22 @@ namespace LuaScript
|
||||
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);
|
||||
@@ -76,12 +70,56 @@ namespace LuaScript
|
||||
_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;
|
||||
}
|
||||
|
||||
@@ -91,7 +129,7 @@ namespace LuaScript
|
||||
_cachedBounds = new RawRectF(left, top, left, top);
|
||||
}
|
||||
|
||||
return _transformEffect.Output;
|
||||
return _transformOutput!;
|
||||
}
|
||||
|
||||
private void EnsureBitmaps(int width, int height)
|
||||
@@ -101,10 +139,12 @@ namespace LuaScript
|
||||
_renderTarget?.Dispose();
|
||||
_stagingBitmap?.Dispose();
|
||||
_outputBitmap?.Dispose();
|
||||
_transformOutput?.Dispose();
|
||||
_transformEffect?.Dispose();
|
||||
_renderTarget = null;
|
||||
_stagingBitmap = null;
|
||||
_outputBitmap = null;
|
||||
_transformOutput = null;
|
||||
_transformEffect = null;
|
||||
_bitmapWidth = 0;
|
||||
_bitmapHeight = 0;
|
||||
@@ -135,10 +175,12 @@ namespace LuaScript
|
||||
_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()
|
||||
};
|
||||
}
|
||||
|
||||
@@ -0,0 +1,197 @@
|
||||
using System.Collections.Concurrent;
|
||||
using System.Runtime.CompilerServices;
|
||||
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 = 4095;
|
||||
public const int MaxTextBytes = 4095;
|
||||
public const int MaxEntries = 4096;
|
||||
public const long MaxHistoryCostBytes = 16 * 1024 * 1024;
|
||||
|
||||
private const long VersionBaseCost = 64;
|
||||
|
||||
private readonly record struct SceneVersion(long Frame, int Layer, SceneValue Value);
|
||||
|
||||
private static readonly ConditionalWeakTable<object, ConcurrentDictionary<string, SceneSharedValues>> s_scopes = new();
|
||||
|
||||
private readonly Dictionary<string, List<SceneVersion>> _names = new(StringComparer.Ordinal);
|
||||
private readonly object _gate = new();
|
||||
private long _historyCost;
|
||||
|
||||
public static SceneSharedValues ForScene(object scope, string sceneId) =>
|
||||
s_scopes.GetOrCreateValue(scope).GetOrAdd(sceneId, static _ => new SceneSharedValues());
|
||||
|
||||
public SceneValue Read(long generation, string name)
|
||||
{
|
||||
lock (_gate)
|
||||
{
|
||||
if (!_names.TryGetValue(name, out var versions))
|
||||
return SceneValue.Nil;
|
||||
int index = LatestBefore(versions, generation);
|
||||
return index >= 0 ? versions[index].Value : SceneValue.Nil;
|
||||
}
|
||||
}
|
||||
|
||||
public void Publish(long generation, int layer, Dictionary<string, SceneValue> writes)
|
||||
{
|
||||
lock (_gate)
|
||||
{
|
||||
foreach (var pair in writes)
|
||||
Upsert(generation, layer, pair.Key, pair.Value);
|
||||
EnforceHistoryBudget();
|
||||
}
|
||||
}
|
||||
|
||||
private void Upsert(long generation, int layer, string name, SceneValue value)
|
||||
{
|
||||
if (!_names.TryGetValue(name, out var versions))
|
||||
{
|
||||
if (_names.Count >= MaxEntries)
|
||||
return;
|
||||
if (value == SceneValue.Nil)
|
||||
return;
|
||||
_names[name] = [new SceneVersion(generation, layer, value)];
|
||||
return;
|
||||
}
|
||||
|
||||
int index = LatestBefore(versions, generation + 1);
|
||||
if (index >= 0 && versions[index].Frame == generation)
|
||||
{
|
||||
if (layer < versions[index].Layer)
|
||||
return;
|
||||
if (index < versions.Count - 1)
|
||||
_historyCost += CostOf(value) - CostOf(versions[index].Value);
|
||||
versions[index] = new SceneVersion(generation, layer, value);
|
||||
return;
|
||||
}
|
||||
|
||||
var previous = index >= 0 ? versions[index].Value : SceneValue.Nil;
|
||||
if (value == previous)
|
||||
return;
|
||||
|
||||
versions.Insert(index + 1, new SceneVersion(generation, layer, value));
|
||||
if (index + 1 < versions.Count - 1)
|
||||
_historyCost += CostOf(value);
|
||||
else if (versions.Count > 1)
|
||||
_historyCost += CostOf(versions[^2].Value);
|
||||
}
|
||||
|
||||
private void EnforceHistoryBudget()
|
||||
{
|
||||
while (_historyCost > MaxHistoryCostBytes)
|
||||
{
|
||||
List<SceneVersion>? oldest = null;
|
||||
string oldestName = string.Empty;
|
||||
foreach (var pair in _names)
|
||||
{
|
||||
var versions = pair.Value;
|
||||
if (versions.Count < 2)
|
||||
continue;
|
||||
if (oldest is null ||
|
||||
versions[0].Frame < oldest[0].Frame ||
|
||||
(versions[0].Frame == oldest[0].Frame && string.CompareOrdinal(pair.Key, oldestName) < 0))
|
||||
{
|
||||
oldest = versions;
|
||||
oldestName = pair.Key;
|
||||
}
|
||||
}
|
||||
if (oldest is null)
|
||||
return;
|
||||
_historyCost -= CostOf(oldest[0].Value);
|
||||
oldest.RemoveAt(0);
|
||||
}
|
||||
}
|
||||
|
||||
private static long CostOf(SceneValue value) =>
|
||||
VersionBaseCost + (value.Text is null ? 0 : value.Text.Length * 2L);
|
||||
|
||||
private static int LatestBefore(List<SceneVersion> versions, long generation)
|
||||
{
|
||||
int low = 0;
|
||||
int high = versions.Count - 1;
|
||||
int result = -1;
|
||||
while (low <= high)
|
||||
{
|
||||
int mid = (low + high) >> 1;
|
||||
if (versions[mid].Frame < generation)
|
||||
{
|
||||
result = mid;
|
||||
low = mid + 1;
|
||||
}
|
||||
else
|
||||
{
|
||||
high = mid - 1;
|
||||
}
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
public static string NormalizeName(string name) => TruncateUtf8(name, MaxNameBytes);
|
||||
|
||||
public static SceneValue NormalizeValue(SceneValue value) =>
|
||||
value.Kind == SceneValueKind.String
|
||||
? SceneValue.FromString(TruncateUtf8(value.Text ?? string.Empty, MaxTextBytes))
|
||||
: value;
|
||||
|
||||
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,69 @@
|
||||
namespace LuaScript
|
||||
{
|
||||
internal sealed class SceneValueSession
|
||||
{
|
||||
private readonly Dictionary<string, SceneValue> _writes = new(StringComparer.Ordinal);
|
||||
private readonly Dictionary<string, SceneValue> _reads = new(StringComparer.Ordinal);
|
||||
private readonly List<SceneValueQuery> _queries = [];
|
||||
|
||||
private SceneSharedValues? _store;
|
||||
private object _scope = new();
|
||||
private string _sceneId = string.Empty;
|
||||
private long _generation;
|
||||
private int _layer;
|
||||
|
||||
public bool HasWrites => _writes.Count > 0;
|
||||
|
||||
public IReadOnlyList<SceneValueQuery> Queries => _queries;
|
||||
|
||||
public void Begin(object scope, string sceneId, long generation, int layer)
|
||||
{
|
||||
if (!ReferenceEquals(_scope, scope) || !string.Equals(_sceneId, sceneId, StringComparison.Ordinal))
|
||||
{
|
||||
_store = null;
|
||||
_scope = scope;
|
||||
_sceneId = sceneId;
|
||||
}
|
||||
_generation = generation;
|
||||
_layer = layer;
|
||||
_writes.Clear();
|
||||
_reads.Clear();
|
||||
_queries.Clear();
|
||||
}
|
||||
|
||||
public SceneValue Get(string name)
|
||||
{
|
||||
name = SceneSharedValues.NormalizeName(name);
|
||||
if (_writes.TryGetValue(name, out var written))
|
||||
return written;
|
||||
if (_reads.TryGetValue(name, out var cached))
|
||||
return cached;
|
||||
var value = Store.Read(_generation, name);
|
||||
_reads[name] = value;
|
||||
_queries.Add(new SceneValueQuery(name, value));
|
||||
return value;
|
||||
}
|
||||
|
||||
public void Set(string name, SceneValue value)
|
||||
{
|
||||
name = SceneSharedValues.NormalizeName(name);
|
||||
value = SceneSharedValues.NormalizeValue(value);
|
||||
if (value.Kind != SceneValueKind.Nil &&
|
||||
!_writes.ContainsKey(name) &&
|
||||
_writes.Count >= SceneSharedValues.MaxEntries)
|
||||
{
|
||||
return;
|
||||
}
|
||||
_writes[name] = value;
|
||||
}
|
||||
|
||||
public void Publish()
|
||||
{
|
||||
if (_writes.Count == 0)
|
||||
return;
|
||||
Store.Publish(_generation, _layer, _writes);
|
||||
}
|
||||
|
||||
private SceneSharedValues Store => _store ??= SceneSharedValues.ForScene(_scope, _sceneId);
|
||||
}
|
||||
}
|
||||
@@ -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();
|
||||
}
|
||||
}
|
||||
@@ -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>
|
||||
+71
-29
@@ -9,6 +9,7 @@ using YukkuriMovieMaker.Commons;
|
||||
using YukkuriMovieMaker.Player.Video;
|
||||
using YukkuriMovieMaker.Plugin;
|
||||
using YukkuriMovieMaker.Plugin.Effects;
|
||||
using LuaScript.Compat;
|
||||
|
||||
namespace LuaScript
|
||||
{
|
||||
@@ -16,29 +17,33 @@ namespace LuaScript
|
||||
{
|
||||
private sealed class Node
|
||||
{
|
||||
public required Type Type;
|
||||
public required IVideoEffect Model;
|
||||
public required IVideoEffectProcessor Processor;
|
||||
public required AviUtlEffectMapping? Mapping;
|
||||
public required int RequestIndex;
|
||||
}
|
||||
|
||||
private static Dictionary<string, Type>? _registry;
|
||||
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, ref DrawDescription drawDescription)
|
||||
public ID2D1Image Apply(ID2D1Image source, IReadOnlyList<AviUtlEffectRequest> requests, EffectDescription baseDesc, AviUtlEngine target, ref DrawDescription drawDescription)
|
||||
{
|
||||
try
|
||||
{
|
||||
SyncNodes(requests);
|
||||
SyncNodes(requests, target);
|
||||
}
|
||||
catch
|
||||
{
|
||||
@@ -52,7 +57,7 @@ namespace LuaScript
|
||||
{
|
||||
try
|
||||
{
|
||||
ApplyParameters(node.Model, requests[node.RequestIndex].Arguments);
|
||||
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);
|
||||
@@ -67,19 +72,32 @@ namespace LuaScript
|
||||
return current;
|
||||
}
|
||||
|
||||
private void SyncNodes(IReadOnlyList<AviUtlEffectRequest> requests)
|
||||
private void SyncNodes(IReadOnlyList<AviUtlEffectRequest> requests, AviUtlEngine target)
|
||||
{
|
||||
if (SignatureMatches(requests))
|
||||
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++)
|
||||
{
|
||||
var type = Resolve(requests[i].Name);
|
||||
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;
|
||||
|
||||
@@ -104,13 +122,13 @@ namespace LuaScript
|
||||
continue;
|
||||
}
|
||||
|
||||
_nodes.Add(new Node { Type = type, Model = model, Processor = processor, RequestIndex = i });
|
||||
_nodes.Add(new Node { Model = model, Processor = processor, Mapping = mapping, RequestIndex = i });
|
||||
}
|
||||
}
|
||||
|
||||
private bool SignatureMatches(IReadOnlyList<AviUtlEffectRequest> requests)
|
||||
private bool SignatureMatches(IReadOnlyList<AviUtlEffectRequest> requests, AviUtlEngine target)
|
||||
{
|
||||
if (_signature.Length != requests.Count)
|
||||
if (_signatureTarget != target || _signature.Length != requests.Count)
|
||||
return false;
|
||||
for (int i = 0; i < requests.Count; i++)
|
||||
{
|
||||
@@ -120,38 +138,49 @@ namespace LuaScript
|
||||
return true;
|
||||
}
|
||||
|
||||
private static Type? Resolve(string name)
|
||||
private static Type? ResolveType(string targetType)
|
||||
{
|
||||
var registry = GetRegistry();
|
||||
return registry.TryGetValue(Normalize(name), out var type) ? type : null;
|
||||
EnsureRegistries();
|
||||
return _typeRegistry!.TryGetValue(Normalize(targetType), out var type) ? type : null;
|
||||
}
|
||||
|
||||
private static Dictionary<string, Type> GetRegistry()
|
||||
private static Type? ResolveName(string name)
|
||||
{
|
||||
if (_registry is not null)
|
||||
return _registry;
|
||||
EnsureRegistries();
|
||||
return _nameRegistry!.TryGetValue(Normalize(name), out var type) ? type : null;
|
||||
}
|
||||
|
||||
var map = new Dictionary<string, Type>(StringComparer.Ordinal);
|
||||
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
|
||||
{
|
||||
Register(map, factory.Name, factory.EffectType);
|
||||
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(map, keyword, factory.EffectType);
|
||||
Register(byName, keyword, type);
|
||||
}
|
||||
catch
|
||||
{
|
||||
}
|
||||
}
|
||||
_registry = map;
|
||||
}
|
||||
catch
|
||||
{
|
||||
}
|
||||
return map;
|
||||
_typeRegistry = byType;
|
||||
_nameRegistry = byName;
|
||||
}
|
||||
|
||||
private static void Register(Dictionary<string, Type> map, string? key, Type type)
|
||||
@@ -163,7 +192,7 @@ namespace LuaScript
|
||||
|
||||
private static string Normalize(string value) => value.Trim().ToLowerInvariant();
|
||||
|
||||
private static void ApplyParameters(IVideoEffect model, IReadOnlyList<KeyValuePair<string, object>> arguments)
|
||||
private static void ApplyParameters(IVideoEffect model, AviUtlEffectMapping? mapping, IReadOnlyList<KeyValuePair<string, object>> arguments)
|
||||
{
|
||||
if (arguments.Count == 0)
|
||||
return;
|
||||
@@ -171,11 +200,24 @@ namespace LuaScript
|
||||
var properties = GetProperties(model.GetType());
|
||||
foreach (var (key, value) in arguments)
|
||||
{
|
||||
if (!properties.TryGetValue(Normalize(key), out var property))
|
||||
continue;
|
||||
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);
|
||||
SetValue(model, property, value, parameter);
|
||||
}
|
||||
catch
|
||||
{
|
||||
@@ -213,14 +255,14 @@ namespace LuaScript
|
||||
return map;
|
||||
}
|
||||
|
||||
private static void SetValue(IVideoEffect model, PropertyInfo property, object value)
|
||||
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(ToDouble(value)));
|
||||
animation.CopyFrom(new Animation(parameter.Transform(ToDouble(value))));
|
||||
return;
|
||||
}
|
||||
if (type == typeof(bool))
|
||||
@@ -240,7 +282,7 @@ namespace LuaScript
|
||||
}
|
||||
if (type == typeof(double) || type == typeof(float) || type == typeof(int) || type == typeof(long) || type == typeof(short))
|
||||
{
|
||||
property.SetValue(model, Convert.ChangeType(ToDouble(value), type, CultureInfo.InvariantCulture));
|
||||
property.SetValue(model, Convert.ChangeType(parameter.Transform(ToDouble(value)), type, CultureInfo.InvariantCulture));
|
||||
return;
|
||||
}
|
||||
if (type == typeof(string))
|
||||
|
||||
@@ -2,7 +2,8 @@
|
||||
|
||||
يستخدم تأثير الفيديو "نص Lua" في YukkuriMovieMaker4
|
||||
لغة Lua لكتابة النصوص البرمجية.
|
||||
يعتمد محرك النصوص على MoonSharp (متوافق مع Lua 5.2).
|
||||
تُنفَّذ النصوص على بيئة التشغيل السريعة المرفقة (LuaJIT)،
|
||||
وتعمل على MoonSharp (متوافق مع Lua 5.2) عندما لا تتوفر تلك البيئة.
|
||||
|
||||
* هذا التأثير تطبيق مستقل ويختلف عن مواصفات نصوص AviUtl2.
|
||||
* يختلف في مواصفاته عن ملفات نصوص AviUtl2 (*.anm2 وما شابه).
|
||||
@@ -11,7 +12,7 @@
|
||||
|
||||
- ملاحظات -
|
||||
|
||||
○ محرك تنفيذ النصوص هو MoonSharp (متوافق مع Lua 5.2).
|
||||
○ محركا تنفيذ النصوص هما LuaJIT (الافتراضي) وMoonSharp (متوافق مع Lua 5.2).
|
||||
○ المكتبات القياسية المتاحة محدودة بما يلي:
|
||||
table, string, math, bit32
|
||||
* io, os, debug, ffi, require وغيرها غير متاحة.
|
||||
@@ -26,16 +27,16 @@
|
||||
|
||||
- محركات التنفيذ والتسريع التلقائي -
|
||||
|
||||
النصوص التي تحتوي على معالجة بكسل (حلقة getpixel/setpixel متداخلة)
|
||||
يُحلَّل تركيبها وتُوجَّه تلقائياً إلى محرك أسرع.
|
||||
أما النصوص العادية (الإحداثيات، الدوران، الشفافية، إلخ) فتظل تعمل على
|
||||
MoonSharp كما في السابق دون أي تغيير في السلوك.
|
||||
يُحلَّل تركيب النصوص وتُوجَّه تلقائياً إلى المحرك الأنسب.
|
||||
النصوص التي لا تحمل توجيهاً تُنفَّذ على بيئة التشغيل السريعة المرفقة
|
||||
(LuaJIT)، أما تخطيطات البكسل المكتفية بنفسها فتُترجَم إضافةً إلى ذلك
|
||||
إلى نواة CPU الأسرع. وفي كلتا الحالتين تطابق النتائج MoonSharp.
|
||||
|
||||
○ التوجيه التلقائي (عند عدم وجود توجيه)
|
||||
· تخطيط بكسل مكتفٍ بنفسه (انظر الشروط أدناه)
|
||||
→ نواة CPU (سريعة ودقيقة)
|
||||
· عمليات البكسل الأخرى → Native (LuaJIT، فقط عند نشره)
|
||||
· بلا عمليات بكسل → MoonSharp
|
||||
· كل ما عدا ذلك → Native (LuaJIT، فقط عند نشره)
|
||||
· عند عدم نشر native أو كون النص فارغاً → MoonSharp
|
||||
|
||||
○ توجيهات المحرك (تعليق في السطر الأول من النص)
|
||||
--!cpu : نواة CPU. تُترجَم وقت التشغيل إلى شجرة تعابير
|
||||
@@ -93,6 +94,32 @@
|
||||
العام لا يصاحبه إعلان نطاق/قيمة افتراضية، لذا تعامل مع نطاقات القيم داخل النص.
|
||||
وتبقى رؤوس AviUtl --track / --check / --color تعمل كما كانت.
|
||||
|
||||
توجد 4 منزلقات رقمية، ويُشار إليها عبر obj.slider0 إلى obj.slider3.
|
||||
القيم أعداد صحيحة ولا تحمل كسوراً عشرية.
|
||||
|
||||
Slider0 : منزلق صحيح (النطاق: 1 ~ 10)
|
||||
Slider1 : منزلق صحيح (النطاق: 0 ~ 100)
|
||||
Slider2 : منزلق صحيح (النطاق: 0 ~ 1000)
|
||||
Slider3 : منزلق صحيح (النطاق: -1000 ~ 1000)
|
||||
|
||||
تتوفر أيضاً معاملات نصية، ويُشار إلى كل قيمة بالأسماء التالية.
|
||||
|
||||
obj.text : نص حقل إدخال النص
|
||||
obj.font : اسم الخط من محدد الخطوط
|
||||
obj.dir : مسار محدد المجلدات
|
||||
obj.file_video : مسار ملف فيديو
|
||||
obj.file_audio : مسار ملف صوتي
|
||||
obj.file_image : مسار ملف صورة
|
||||
obj.file_project : مسار ملف مشروع
|
||||
obj.file_mp4 : مسار ملف MP4
|
||||
obj.file_exo : مسار ملف EXO
|
||||
obj.file_subtitle : مسار ملف ترجمة
|
||||
obj.file_shader : مسار ملف تظليل
|
||||
|
||||
※تظهر المنزلقات والمعاملات النصية في لوح التأثيرات تلقائياً عندما يشير إليها النص البرمجي.
|
||||
※يمكن تمرير مسار الملف إلى obj.load لتحميل صورة أو فيديو.
|
||||
※تتوفر هذه المعاملات في محركَي MoonSharp والمحرك الأصلي معاً.
|
||||
|
||||
|
||||
- المتغيرات العامة -
|
||||
|
||||
@@ -123,6 +150,32 @@
|
||||
scene.width : الدقة الأفقية (بكسل) للمشهد (المشروع) [للقراءة فقط]
|
||||
scene.height : الدقة الرأسية (بكسل) للمشهد (المشروع) [للقراءة فقط]
|
||||
|
||||
scene.set(name, value)
|
||||
يخزّن قيمة في منطقة مشتركة على مستوى المشهد.
|
||||
يمكن قراءة القيمة عبر scene.get(name) من جميع تأثيرات نصوص Lua
|
||||
في المشهد نفسه، عبر العناصر والإطارات.
|
||||
name : اسم القيمة (نص)
|
||||
value : القيمة المراد تخزينها (رقم أو نص أو قيمة منطقية). تمرير nil
|
||||
يحذفها.
|
||||
* القيم غير الأرقام والنصوص والقيم المنطقية (الجداول والدوال وغيرها)
|
||||
لا يتم تخزينها.
|
||||
* تُقتطع الأسماء وقيم النصوص بعد 4095 بايت بترميز UTF-8.
|
||||
مثال: scene.set("shared_x", obj.x)
|
||||
scene.get(name)
|
||||
يسترجع قيمة مخزّنة عبر scene.set(). يعيد nil للأسماء غير المعيّنة.
|
||||
مثال: local x = scene.get("shared_x") or 0
|
||||
* القيم التي كتبها النص البرمجي نفسه يمكن قراءتها فورًا عبر scene.get ضمن
|
||||
التنفيذ نفسه. أما القيم التي كتبتها عناصر أخرى فتظهر اعتبارًا من الإطار
|
||||
التالي، لذا لا تعتمد النتيجة على ترتيب تقييم العناصر داخل الإطار الواحد.
|
||||
* عندما ينتهي النص البرمجي بخطأ أو بانتهاء المهلة، لا تُطبَّق أي من كتاباته
|
||||
على المنطقة المشتركة.
|
||||
* عند بدء تصدير الفيديو تبدأ المنطقة المشتركة فارغة، لذا يعطي تصدير المشروع
|
||||
نفسه النتيجة نفسها في كل مرة.
|
||||
* يمكن تخزين ما يصل إلى 4096 اسمًا لكل مشهد. تُتجاهل الكتابات إلى أسماء
|
||||
جديدة تتجاوز الحد.
|
||||
* القيم مستقلة لكل مشهد وتبقى في الذاكرة حتى إغلاق YMM4.
|
||||
لا تُحفظ في ملف المشروع.
|
||||
|
||||
|
||||
- جدول obj - المتغيرات -
|
||||
|
||||
@@ -213,6 +266,18 @@
|
||||
obj.track2 : القيمة الحالية لـ Track2 في لوح التأثيرات [للقراءة فقط]
|
||||
obj.track3 : القيمة الحالية لـ Track3 في لوح التأثيرات [للقراءة فقط]
|
||||
|
||||
○ المنزلقات
|
||||
obj.slider0 : القيمة الحالية لـ Slider0 في لوح التأثيرات (عدد صحيح) [للقراءة فقط]
|
||||
obj.slider1 : القيمة الحالية لـ Slider1 في لوح التأثيرات (عدد صحيح) [للقراءة فقط]
|
||||
obj.slider2 : القيمة الحالية لـ Slider2 في لوح التأثيرات (عدد صحيح) [للقراءة فقط]
|
||||
obj.slider3 : القيمة الحالية لـ Slider3 في لوح التأثيرات (عدد صحيح) [للقراءة فقط]
|
||||
|
||||
○ المعاملات النصية
|
||||
obj.text : نص حقل إدخال النص [للقراءة فقط]
|
||||
obj.font : اسم الخط من محدد الخطوط [للقراءة فقط]
|
||||
obj.dir : مسار محدد المجلدات [للقراءة فقط]
|
||||
obj.file_video ~ obj.file_shader : مسار كل محدد ملفات [للقراءة فقط]
|
||||
|
||||
○ الطبقة
|
||||
obj.layer : رقم الطبقة التي يوجد فيها الكائن [للقراءة فقط]
|
||||
* نفس قيمة المتغير العام layer.
|
||||
@@ -451,10 +516,57 @@
|
||||
الخيارات التي تؤثر على الرسم حالياً:
|
||||
"antialias" : 0 = أقرب جار، وإلا استيفاء خطّي
|
||||
(obj.draw / obj.drawpoly).
|
||||
"blend" : رقم وضع الدمج (obj.draw / obj.drawpoly). بنفس ترتيب
|
||||
القائمة المنسدلة "وضع الدمج" في لوحة الخصائص في YMM4 (يبدأ من 0):
|
||||
0=عادي,1=اكتمل الذوبان,2=أغمق,3=ضرب,4=حرق اللون,
|
||||
5=احتراق خطي,6=معالجة (أخفّ),7=شاشة,8=تراكب اللون,
|
||||
9=المزج الخطي (إضافة),10=إضافة,11=تراكب,12=ضوء ناعم,
|
||||
13=ضوء قوي,14=ضوء حيوي,15=الضوء الخطي,16=ضوء دبوس,
|
||||
17=مزج قوي,18=الفرق,19=استبعاد,20=طرح,21=القسمة,22=تدرج,
|
||||
23=التشبع,24=لون,25=السطوع,26=لون أفتح,27=خلفية,
|
||||
28=لون أغمق,29=مسح,30=القص حسب الخلفية,
|
||||
31=فقط الأجزاء غير المتراكبة,32=قناع عكس الألوان.
|
||||
القيم خارج النطاق أو غير الصالحة تُعامَل كـ 0 (عادي).
|
||||
"draw_state" : قيمة منطقية تحدد ما إذا كان هذا التأثير يُخرج صورة
|
||||
العمل. true تُخرج صورة العمل، وfalse تمرر الدخل كما هو. تُستخدم
|
||||
لإخراج صورة العمل دون obj.draw أو setpixel، أو لإيقاف الإخراج.
|
||||
تعمل في المحركين معاً.
|
||||
"drawtarget" : يبدّل وجهة رسم obj.draw / obj.drawpoly.
|
||||
"framebuffer" (الافتراضي) يركّب في مخزن الإطار. "tempbuffer"
|
||||
يركّب في مخزن العمل tmp مباشرة. في
|
||||
obj.setoption("drawtarget", "tempbuffer", w, h) تُحدد w, h حجم
|
||||
تهيئة مخزن tmp، وحذفهما يُبقيه كما هو. أعِد نتيجة tmp إلى صورة
|
||||
العمل عبر obj.copybuffer("obj", "tmp"). التركيب في tempbuffer
|
||||
عادي (source-over)، وblend يُطبَّق على الرسم في framebuffer.
|
||||
تعمل في المحركين معاً. في MoonSharp يُنفَّذ التركيب في tempbuffer
|
||||
على GPU، ويتحوّل تلقائياً إلى التركيب على CPU عندما تكون GPU
|
||||
غير متاحة. وبسبب اختلاف التقريب قد تختلف نتيجة التركيب
|
||||
اختلافاً طفيفاً جداً بين المحركين.
|
||||
|
||||
○ obj.pixeloption(name, value)
|
||||
يحفظ خياراً لعمليات البكسل كحالة.
|
||||
|
||||
○ obj.setanchor(name, count [, option, ..])
|
||||
يعرض نقاط الإرساء على المعاينة لضبط إحداثياتها بالسحب بالفأرة.
|
||||
تُحفَظ الإحداثيات المعدّلة مع المشروع.
|
||||
name : اسم متغير Lua الذي يستقبل الإحداثيات، كسلسلة نصية. يكون
|
||||
المتغير بالترتيب pos={x0,y0,x1,y1,…}، أو {x0,y0,z0,x1,y1,z1,…}
|
||||
مع "xyz". الإحداثيات بالنسبة إلى مركز الكائن.
|
||||
count : عدد نقاط الإرساء. حتى 32.
|
||||
option : تُذكَر كسلاسل نصية.
|
||||
"line" : يصل نقاط الإرساء بخطوط.
|
||||
"loop" : يصل نقاط الإرساء ويغلق الحلقة.
|
||||
"star" : يصل كل نقطة إرساء بمركز الكائن.
|
||||
"arm" : يصل مركز الكائن بكل نقطة إرساء بالترتيب.
|
||||
"xyz" : يعامل النقاط كإحداثيات ثلاثية الأبعاد. الافتراضي ثنائي.
|
||||
يعيد عدد نقاط الإرساء. يعمل في المحركين معاً.
|
||||
وضع شريط "track" غير مدعوم حالياً ويعيد 0.
|
||||
مثال:
|
||||
num = obj.track0
|
||||
obj.setanchor("pos", num, "loop")
|
||||
for i = 0, num - 1 do
|
||||
obj.draw(pos[i * 2 + 1], pos[i * 2 + 2])
|
||||
end
|
||||
|
||||
|
||||
- ymm4 Table -
|
||||
@@ -516,6 +628,49 @@
|
||||
anim.bezier(t, p0, p1, p2, p3): Evaluates cubic bezier curve at `t` (0.0~1.0)
|
||||
|
||||
|
||||
- الدوال العامة المتوافقة مع AviUtl -
|
||||
|
||||
يمكن استدعاء الدوال التالية مباشرة في النطاق العام.
|
||||
تعيد نتائج متطابقة على جميع محركات التنفيذ (MoonSharp / الأصلي).
|
||||
|
||||
RGB(r, g, b)
|
||||
RGB(col)
|
||||
RGB(r1, g1, b1, r2, g2, b2)
|
||||
تحوّل بين قيمة اللون (0x000000-0xffffff) ومكوّناتها الأحمر والأخضر
|
||||
والأزرق (0-255 لكل منها). بثلاث وسائط تركّب قيمة لون واحدة، وبوسيطة
|
||||
واحدة تفكّكها إلى r وg وb. بست وسائط تعيد لونًا يتغيّر خطيًا من اللون
|
||||
الأول إلى الثاني وفق الزمن المنقضي للكائن
|
||||
(obj.time / obj.totaltime).
|
||||
مثال: col = RGB(64, 192, 255) -- 0x40C0FF
|
||||
مثال: r, g, b = RGB(0x0080FF) -- 0, 128, 255
|
||||
مثال: col = RGB(64,192,255, 128,64,0) -- اللون الأول ← الثاني
|
||||
|
||||
HSV(h, s, v)
|
||||
HSV(col)
|
||||
HSV(h1, s1, v1, h2, s2, v2)
|
||||
تحوّل بين قيمة اللون (0x000000-0xffffff) وتدرّج اللون (0-360)
|
||||
والتشبع (0-100) والقيمة (0-100). تعمل الوسائط مثل RGB().
|
||||
مثال: col = HSV(60, 100, 100) -- 0xFFFF00
|
||||
مثال: h, s, v = HSV(0x0080FF) -- 210, 100, 100
|
||||
|
||||
OR(a, b) / AND(a, b) / XOR(a, b)
|
||||
تنفّذ عمليات على مستوى البتات (أو / و / أو حصرية) على أعداد صحيحة
|
||||
بطول 32 بت. تُقتطع الكسور حتى 0.5 بالضبط عند التحويل إلى عدد صحيح
|
||||
(2.50 ← 2، 2.51 ← 3).
|
||||
مثال: result = OR(8, 3) -- 11
|
||||
|
||||
SHIFT(a, shift)
|
||||
تنفّذ إزاحة حسابية. القيمة الموجبة تزيح لليسار والسالبة تزيح لليمين.
|
||||
مثال: result = SHIFT(5, 3) -- 40
|
||||
مثال: result = SHIFT(91, -2) -- 22
|
||||
|
||||
debug_print(text)
|
||||
ترسل النص المحدد إلى OutputDebugString(). للتصحيح.
|
||||
يمكن عرض الرسائل بأداة مراقبة تصحيح مثل DebugView. عند حدوث خطأ في
|
||||
تنفيذ النص البرمجي تُرسل رسالة الخطأ تلقائيًا أيضًا.
|
||||
مثال: debug_print(string.format("x = %d", obj.x))
|
||||
|
||||
|
||||
- المكتبات القياسية المتاحة -
|
||||
|
||||
مكتبة math:
|
||||
@@ -632,19 +787,52 @@
|
||||
و obj.getvalue، و obj.setoption / obj.getoption / obj.pixeloption.
|
||||
انظر "جدول obj - الدوال" للتفاصيل.
|
||||
|
||||
○ خريطة توافق AviUtl / AviUtl2 لـ obj.effect
|
||||
يَرجع obj.effect("اسم التأثير"، "اسم المعامل"، القيمة، ...) إلى خريطة
|
||||
التوافق أولًا. التأثيرات المُعلَنة بأسماء AviUtl / AviUtl2 تمر عبر تحويل
|
||||
المقياس/الإزاحة المُعلَن قبل الوصول إلى خصائص YMM4. الأسماء غير المُعلَنة في
|
||||
الخريطة تُحَلّ مباشرةً عبر اسم تأثير YMM4 أو كلمته المفتاحية، لذا تظل
|
||||
الاستدعاءات الحالية تعمل.
|
||||
بُنيت الخريطة كمعكوس لتصدير AviUtl الخاص بـ YMM4 نفسه (مخرجات .exo)، لذا
|
||||
تتطابق ذهابًا وإيابًا. يُختار المحرك الهدف عبر --!aviutl (الافتراضي) /
|
||||
--!aviutl2.
|
||||
أسماء التأثيرات المُعلَنة في الخريطة ومعاملاتها الرئيسية كما يلي:
|
||||
ぼかし: 範囲, サイズ固定
|
||||
境界ぼかし: 範囲
|
||||
方向ブラー: 範囲, 角度, サイズ固定
|
||||
放射ブラー: 範囲, X, Y, サイズを固定
|
||||
閃光: 範囲, X, Y, サイズを固定
|
||||
クロマキー: 色相範囲, 境界補正
|
||||
クリッピング: 上, 下, 左, 右, 中心の位置を変更
|
||||
斜めクリッピング: 中心X, 中心Y, 角度, ぼかし, 幅
|
||||
領域拡張: 上, 下, 左, 右
|
||||
座標: X, Y, Z
|
||||
回転: X, Y, Z
|
||||
リサイズ: 拡大率, X, Y, 補間なし
|
||||
画像ループ: 横回数, 縦回数
|
||||
極座標変換: 中心幅, 渦巻
|
||||
グラデーション: 強さ, 中心X, 中心Y, 角度, 幅
|
||||
単色化: 強さ, 輝度を保持する
|
||||
縁取り: サイズ, ぼかし
|
||||
反転: -
|
||||
モザイク: サイズ
|
||||
ディスプレイスメントマップ: ぼかし
|
||||
動画ファイル合成: X, Y, 拡大率
|
||||
色調補正: 明るさ, コントラスト, 色相, 輝度, 彩度
|
||||
色ずれ: ずれ幅, 角度, 強さ
|
||||
يتوافق 色調補正 و 色ずれ مع تأثيرات إضافة المجتمع.
|
||||
|
||||
الميزات التالية خارج نطاق هذه الطبقة.
|
||||
النصوص التي تستدعيها لن تعمل كما هو متوقع.
|
||||
× تحميل الوحدات عبر require، والوصول العشوائي إلى الملفات مثل
|
||||
io / dofile (تحميل الصور / الفيديو عبر obj.load مدعوم مع التحقق
|
||||
من الترويسة).
|
||||
× obj.setanchor، scene.set / scene.get وما شابه.
|
||||
× obj.setanchor وما شابه.
|
||||
|
||||
|
||||
- الميزات غير المدعومة / القيود -
|
||||
|
||||
× obj.rand1()، obj.mes()، obj.setanchor() وما شابه من AviUtl2 غير مدعومة.
|
||||
× الدوال مثل scene.set() و scene.get() في جدول scene الخاص بـ AviUtl2 غير مدعومة.
|
||||
(يمكن قراءة scene.width و scene.height فقط)
|
||||
× الوصول العشوائي إلى الملفات من النصوص (require, dofile, io وما شابه) غير مدعوم.
|
||||
فقط obj.load("image"/"movie") يحمّل الملفات المؤكَّد أنها وسائط أصلية عبر
|
||||
التحقق من الترويسة الأولى.
|
||||
|
||||
@@ -2,7 +2,8 @@
|
||||
|
||||
The "Lua Script" video effect in YukkuriMovieMaker4 uses
|
||||
the Lua language for scripting.
|
||||
The scripting engine is MoonSharp (Lua 5.2 compatible).
|
||||
Scripts run on the bundled fast runtime (LuaJIT), and fall back to
|
||||
MoonSharp (Lua 5.2 compatible) when the runtime is unavailable.
|
||||
|
||||
* This effect is a custom implementation and differs from the AviUtl2 script specification.
|
||||
* This is a separate specification from AviUtl2 script files (*.anm2, etc.).
|
||||
@@ -11,7 +12,7 @@
|
||||
|
||||
- Notes -
|
||||
|
||||
o The script execution engine is MoonSharp (Lua 5.2 compatible).
|
||||
o The script execution engines are LuaJIT (default) and MoonSharp (Lua 5.2 compatible).
|
||||
o Available standard libraries are limited to the following:
|
||||
table, string, math, bit32
|
||||
* io, os, debug, ffi, require, etc. are not available.
|
||||
@@ -26,16 +27,16 @@
|
||||
|
||||
- Execution Engines and Automatic Acceleration -
|
||||
|
||||
Scripts that contain pixel processing (a nested getpixel/setpixel loop)
|
||||
are analyzed and automatically routed to a faster engine.
|
||||
Ordinary scripts (coordinate, rotation, opacity changes, etc.) keep
|
||||
running on MoonSharp as before, with no change in behavior.
|
||||
Scripts are analyzed and automatically routed to the best engine.
|
||||
Scripts without a directive run on the bundled fast runtime (LuaJIT),
|
||||
and self-contained per-pixel maps are further compiled to the even
|
||||
faster CPU kernel. Either way the results match MoonSharp.
|
||||
|
||||
o Automatic routing (when no directive is present)
|
||||
- A self-contained per-pixel map (see conditions below)
|
||||
-> CPU kernel (fast, exact)
|
||||
- Other pixel operations -> Native (LuaJIT, only when deployed)
|
||||
- No pixel operations -> MoonSharp
|
||||
- Everything else -> Native (LuaJIT, only when deployed)
|
||||
- Native not deployed, or an empty script -> MoonSharp
|
||||
|
||||
o Engine directives (a comment on the first line of the script)
|
||||
--!cpu : CPU kernel. Compiled at runtime to an expression
|
||||
@@ -97,6 +98,33 @@
|
||||
value ranges within the script. The AviUtl --track / --check / --color headers
|
||||
still work as before.
|
||||
|
||||
There are 4 numeric sliders, referenced as obj.slider0 through obj.slider3.
|
||||
The values are integers and do not hold decimals.
|
||||
|
||||
Slider0 : Integer slider (Range: 1 ~ 10)
|
||||
Slider1 : Integer slider (Range: 0 ~ 100)
|
||||
Slider2 : Integer slider (Range: 0 ~ 1000)
|
||||
Slider3 : Integer slider (Range: -1000 ~ 1000)
|
||||
|
||||
String parameters are also available, referenced by the following names.
|
||||
|
||||
obj.text : String from the text input field
|
||||
obj.font : Font name from the font selector
|
||||
obj.dir : Path from the folder selector
|
||||
obj.file_video : Path of a video file
|
||||
obj.file_audio : Path of an audio file
|
||||
obj.file_image : Path of an image file
|
||||
obj.file_project : Path of a project file
|
||||
obj.file_mp4 : Path of an MP4 file
|
||||
obj.file_exo : Path of an EXO file
|
||||
obj.file_subtitle : Path of a subtitle file
|
||||
obj.file_shader : Path of a shader file
|
||||
|
||||
* The sliders and string parameters appear in the effect panel automatically
|
||||
when the script references them.
|
||||
* A file path can be passed to obj.load to load an image or movie.
|
||||
* These parameters are available in both the MoonSharp and native engines.
|
||||
|
||||
|
||||
- Global Variables -
|
||||
|
||||
@@ -129,6 +157,32 @@
|
||||
scene.cx : Half of the scene's horizontal resolution (= scene.width / 2) [ReadOnly]
|
||||
scene.cy : Half of the scene's vertical resolution (= scene.height / 2) [ReadOnly]
|
||||
|
||||
scene.set(name, value)
|
||||
Stores a value in a shared area scoped to the scene.
|
||||
The value can be read back with scene.get(name) from every Lua script
|
||||
effect in the same scene, across items and frames.
|
||||
name : Name of the value (string)
|
||||
value : Value to store (number, string, or boolean). Passing nil removes it.
|
||||
* Values other than numbers, strings, and booleans (tables, functions,
|
||||
etc.) are not stored.
|
||||
* Names and string values are truncated beyond 4095 bytes in UTF-8.
|
||||
Example: scene.set("shared_x", obj.x)
|
||||
scene.get(name)
|
||||
Retrieves a value stored with scene.set(). Returns nil for unset names.
|
||||
Example: local x = scene.get("shared_x") or 0
|
||||
* Values written by your own script can be read back immediately with
|
||||
scene.get within the same run. Values written by other items become
|
||||
visible from the next frame, so the result does not depend on the order
|
||||
in which items are evaluated within a frame.
|
||||
* When a script ends with an error or a timeout, none of its writes are
|
||||
applied to the shared area.
|
||||
* When video export starts, the shared area starts empty, so exporting the
|
||||
same project always produces the same result.
|
||||
* Up to 4096 names can be stored per scene. Writes to new names beyond the
|
||||
limit are ignored.
|
||||
* Values are independent per scene and kept in memory until YMM4 exits.
|
||||
They are not saved into the project file.
|
||||
|
||||
|
||||
- obj Table - Variables -
|
||||
|
||||
@@ -220,6 +274,18 @@
|
||||
obj.track2 : Current value of Track2 in the effect panel [ReadOnly]
|
||||
obj.track3 : Current value of Track3 in the effect panel [ReadOnly]
|
||||
|
||||
o Sliders
|
||||
obj.slider0 : Current value of Slider0 in the effect panel (integer) [ReadOnly]
|
||||
obj.slider1 : Current value of Slider1 in the effect panel (integer) [ReadOnly]
|
||||
obj.slider2 : Current value of Slider2 in the effect panel (integer) [ReadOnly]
|
||||
obj.slider3 : Current value of Slider3 in the effect panel (integer) [ReadOnly]
|
||||
|
||||
o String parameters
|
||||
obj.text : String from the text input field [ReadOnly]
|
||||
obj.font : Font name from the font selector [ReadOnly]
|
||||
obj.dir : Path from the folder selector [ReadOnly]
|
||||
obj.file_video ~ obj.file_shader : Path from each file selector [ReadOnly]
|
||||
|
||||
o Layer
|
||||
obj.layer : Layer number where the object is placed [ReadOnly]
|
||||
* Same value as global variable layer.
|
||||
@@ -467,10 +533,61 @@
|
||||
Options that currently affect drawing:
|
||||
"antialias" : 0 = nearest neighbor, otherwise linear interpolation
|
||||
(obj.draw / obj.drawpoly).
|
||||
"blend" : blend mode number (obj.draw / obj.drawpoly). Same order
|
||||
(0-based) as YMM4's own "Blend mode" dropdown in the property
|
||||
panel: 0=Normal,1=Dissolve,2=Darker,3=Multiply,4=Color burn,
|
||||
5=Linear burn,6=Lighter,7=Screen,8=Color dodge,
|
||||
9=Linear dodge (Add),10=Add,11=Overlay,12=Soft light,
|
||||
13=Hard light,14=Vivid light,15=Linear light,16=Pin light,
|
||||
17=Hard mix,18=Difference,19=Exclution,20=Subtract,
|
||||
21=Division,22=Hue,23=Saturation,24=Color,25=Luminance,
|
||||
26=Lighter color,27=Behind,28=Darker color,29=Clear,
|
||||
30=Clipping by background,31=XOR,32=Color inversion mask.
|
||||
Out-of-range or invalid values are treated as 0 (Normal).
|
||||
"draw_state" : a boolean that decides whether this effect emits
|
||||
its working image. true outputs the working image; false passes
|
||||
the input through unchanged. Use it to emit the working image
|
||||
without obj.draw or setpixel, or to suppress the output. It works
|
||||
in both engines.
|
||||
"drawtarget" : switches the destination of obj.draw / obj.drawpoly.
|
||||
"framebuffer" (default) composites into the frame buffer.
|
||||
"tempbuffer" composites into the working tmp buffer in place. In
|
||||
obj.setoption("drawtarget", "tempbuffer", w, h) the w, h give the
|
||||
size to initialize the tmp buffer; omit them to keep it. Bring the
|
||||
tmp result back to the working image with
|
||||
obj.copybuffer("obj", "tmp"). Compositing into tempbuffer is
|
||||
normal (source-over); blend applies to framebuffer drawing. It
|
||||
works in both engines. In MoonSharp the compositing into
|
||||
tempbuffer runs on the GPU and switches to the CPU compositing
|
||||
automatically when the GPU is unavailable. Due to rounding, the
|
||||
composited result may differ very slightly between the engines.
|
||||
|
||||
o obj.pixeloption(name, value)
|
||||
Stores an option for pixel operations as state.
|
||||
|
||||
o obj.setanchor(name, count [, option, ..])
|
||||
Shows anchor points on the preview so their coordinates can be
|
||||
adjusted by mouse dragging. The adjusted coordinates are saved with
|
||||
the project.
|
||||
name : the name of the Lua variable that receives the coordinates,
|
||||
given as a string. The variable is laid out as
|
||||
pos={x0,y0,x1,y1,…}, or {x0,y0,z0,x1,y1,z1,…} with "xyz".
|
||||
Coordinates are relative to the object center.
|
||||
count : the number of anchor points. Up to 32.
|
||||
option : enumerated as strings.
|
||||
"line" : connect the anchor points with lines.
|
||||
"loop" : connect the anchor points and close the loop.
|
||||
"star" : connect each anchor point to the object center.
|
||||
"arm" : connect the object center to each anchor point in order.
|
||||
"xyz" : treat the anchor points as 3D coordinates. 2D by default.
|
||||
Returns the number of anchor points. It works in both engines.
|
||||
The "track" trackbar mode is not supported yet and returns 0.
|
||||
Example:
|
||||
num = obj.track0
|
||||
obj.setanchor("pos", num, "loop")
|
||||
for i = 0, num - 1 do
|
||||
obj.draw(pos[i * 2 + 1], pos[i * 2 + 2])
|
||||
end
|
||||
|
||||
|
||||
- ymm4 Table -
|
||||
@@ -532,6 +649,52 @@
|
||||
anim.bezier(t, p0, p1, p2, p3): Evaluates cubic bezier curve at `t` (0.0~1.0)
|
||||
|
||||
|
||||
- AviUtl-Compatible Global Functions -
|
||||
|
||||
The following functions can be called directly in the global scope.
|
||||
They return identical results on every execution engine (MoonSharp / native).
|
||||
|
||||
RGB(r, g, b)
|
||||
RGB(col)
|
||||
RGB(r1, g1, b1, r2, g2, b2)
|
||||
Converts between a color value (0x000000-0xffffff) and its red, green,
|
||||
and blue components (0-255 each). With 3 arguments it composes a single
|
||||
color value, and with 1 argument it decomposes into r, g, b. With 6
|
||||
arguments it returns a color that changes linearly from the first color
|
||||
to the second according to the object's elapsed time
|
||||
(obj.time / obj.totaltime).
|
||||
Example: col = RGB(64, 192, 255) -- 0x40C0FF
|
||||
Example: r, g, b = RGB(0x0080FF) -- 0, 128, 255
|
||||
Example: col = RGB(64,192,255, 128,64,0) -- start color -> end color
|
||||
|
||||
HSV(h, s, v)
|
||||
HSV(col)
|
||||
HSV(h1, s1, v1, h2, s2, v2)
|
||||
Converts between a color value (0x000000-0xffffff) and hue (0-360),
|
||||
saturation (0-100), and value (0-100). The arguments work like RGB().
|
||||
Example: col = HSV(60, 100, 100) -- 0xFFFF00
|
||||
Example: h, s, v = HSV(0x0080FF) -- 210, 100, 100
|
||||
|
||||
OR(a, b) / AND(a, b) / XOR(a, b)
|
||||
Performs bitwise operations (or / and / exclusive or) on 32-bit
|
||||
integers. Fractions up to exactly 0.5 are truncated when converting to
|
||||
integers (2.50 -> 2, 2.51 -> 3).
|
||||
Example: result = OR(8, 3) -- 11
|
||||
|
||||
SHIFT(a, shift)
|
||||
Performs an arithmetic shift. A positive shift shifts left and a
|
||||
negative shift shifts right.
|
||||
Example: result = SHIFT(5, 3) -- 40
|
||||
Example: result = SHIFT(91, -2) -- 22
|
||||
|
||||
debug_print(text)
|
||||
Sends the given string to OutputDebugString(). For debugging.
|
||||
Messages can be viewed with a debug monitor tool such as DebugView.
|
||||
When a script execution error occurs, the error message is also sent
|
||||
automatically.
|
||||
Example: debug_print(string.format("x = %d", obj.x))
|
||||
|
||||
|
||||
- Available Standard Libraries -
|
||||
|
||||
math library:
|
||||
@@ -652,19 +815,53 @@
|
||||
obj.getvalue, and obj.setoption / obj.getoption / obj.pixeloption are
|
||||
supported. See "obj Table - Functions" for details.
|
||||
|
||||
o AviUtl / AviUtl2 compatibility map for obj.effect
|
||||
obj.effect("effect name", "parameter name", value, ...) first consults
|
||||
the compatibility map. Effects declared as AviUtl / AviUtl2 names pass
|
||||
through the declared scale/offset conversion before reaching the YMM4
|
||||
properties. Names not declared in the map are resolved directly by the
|
||||
YMM4 effect name or keyword, so existing calls keep working. The map is
|
||||
built as the inverse of YMM4's own AviUtl export (.exo output), so it
|
||||
round-trips exactly. The target engine is selected with --!aviutl
|
||||
(default) / --!aviutl2.
|
||||
The effect names declared in the map and their main parameters are as
|
||||
follows.
|
||||
ぼかし: 範囲, サイズ固定
|
||||
境界ぼかし: 範囲
|
||||
方向ブラー: 範囲, 角度, サイズ固定
|
||||
放射ブラー: 範囲, X, Y, サイズを固定
|
||||
閃光: 範囲, X, Y, サイズを固定
|
||||
クロマキー: 色相範囲, 境界補正
|
||||
クリッピング: 上, 下, 左, 右, 中心の位置を変更
|
||||
斜めクリッピング: 中心X, 中心Y, 角度, ぼかし, 幅
|
||||
領域拡張: 上, 下, 左, 右
|
||||
座標: X, Y, Z
|
||||
回転: X, Y, Z
|
||||
リサイズ: 拡大率, X, Y, 補間なし
|
||||
画像ループ: 横回数, 縦回数
|
||||
極座標変換: 中心幅, 渦巻
|
||||
グラデーション: 強さ, 中心X, 中心Y, 角度, 幅
|
||||
単色化: 強さ, 輝度を保持する
|
||||
縁取り: サイズ, ぼかし
|
||||
反転: -
|
||||
モザイク: サイズ
|
||||
ディスプレイスメントマップ: ぼかし
|
||||
動画ファイル合成: X, Y, 拡大率
|
||||
色調補正: 明るさ, コントラスト, 色相, 輝度, 彩度
|
||||
色ずれ: ずれ幅, 角度, 強さ
|
||||
色調補正 and 色ずれ correspond to community plugin effects.
|
||||
|
||||
The following are out of scope for this layer. Scripts that call them will not
|
||||
behave as intended.
|
||||
x Module loading via require, and arbitrary file access such as io /
|
||||
dofile (image / video loading via obj.load is supported with header
|
||||
validation).
|
||||
x obj.setanchor, scene.set / scene.get, etc.
|
||||
x obj.setanchor, etc.
|
||||
|
||||
|
||||
- Unsupported Features / Limitations -
|
||||
|
||||
x obj.rand1(), obj.mes(), obj.setanchor(), etc. from AviUtl2 are not supported.
|
||||
x Functions such as scene.set() and scene.get() in the AviUtl2 scene table are not supported.
|
||||
(Only scene.width and scene.height can be read)
|
||||
x Arbitrary file access from scripts (require, dofile, io, etc.) is not supported.
|
||||
Only obj.load("image"/"movie") loads files confirmed to be genuine media by
|
||||
leading-header validation.
|
||||
|
||||
@@ -2,7 +2,8 @@
|
||||
|
||||
El efecto de video «Script Lua» de YukkuriMovieMaker4 utiliza
|
||||
el lenguaje Lua para los scripts.
|
||||
El motor de scripts empleado es MoonSharp (compatible con Lua 5.2).
|
||||
Los scripts se ejecutan en el runtime rápido incluido (LuaJIT) y,
|
||||
cuando este no está disponible, en MoonSharp (compatible con Lua 5.2).
|
||||
|
||||
* Este efecto es una implementación propia y difiere de la especificación de scripts de AviUtl2.
|
||||
* Tiene una especificación distinta a los archivos de script de AviUtl2 (*.anm2, etc.).
|
||||
@@ -11,7 +12,7 @@
|
||||
|
||||
- Notas -
|
||||
|
||||
o El motor de ejecución de scripts es MoonSharp (compatible con Lua 5.2).
|
||||
o Los motores de ejecución son LuaJIT (predeterminado) y MoonSharp (compatible con Lua 5.2).
|
||||
o Las bibliotecas estándar disponibles se limitan a las siguientes:
|
||||
table, string, math, bit32
|
||||
* io, os, debug, ffi, require, etc. no están disponibles.
|
||||
@@ -26,17 +27,17 @@
|
||||
|
||||
- Motores de ejecución y aceleración automática -
|
||||
|
||||
Los scripts que contienen procesamiento de píxeles (un bucle anidado
|
||||
getpixel/setpixel) se analizan y se enrutan automáticamente a un motor
|
||||
más rápido. Los scripts normales (coordenadas, rotación, opacidad, etc.)
|
||||
siguen ejecutándose en MoonSharp como antes, sin cambios de comportamiento.
|
||||
Los scripts se analizan y se enrutan automáticamente al mejor motor.
|
||||
Los scripts sin directiva se ejecutan en el runtime rápido incluido
|
||||
(LuaJIT), y los mapeos por píxel autocontenidos se compilan además al
|
||||
núcleo CPU, aún más rápido. En ambos casos los resultados coinciden
|
||||
con MoonSharp.
|
||||
|
||||
o Enrutamiento automático (cuando no hay directiva)
|
||||
- Un mapeo por píxel autocontenido (ver condiciones abajo)
|
||||
-> núcleo CPU (rápido, exacto)
|
||||
- Otras operaciones de píxeles -> Nativo (LuaJIT, solo si está
|
||||
desplegado)
|
||||
- Sin operaciones de píxeles -> MoonSharp
|
||||
- Todo lo demás -> Nativo (LuaJIT, solo si está desplegado)
|
||||
- Nativo no desplegado, o script vacío -> MoonSharp
|
||||
|
||||
o Directivas de motor (un comentario en la primera línea del script)
|
||||
--!cpu : Núcleo CPU. Compilado en tiempo de ejecución a un
|
||||
@@ -97,6 +98,33 @@
|
||||
así que gestione los rangos dentro del script. Las cabeceras --track / --check /
|
||||
--color de AviUtl siguen funcionando como antes.
|
||||
|
||||
Hay 4 deslizadores numéricos, referenciados como obj.slider0 ~ obj.slider3.
|
||||
Los valores son enteros y no contienen decimales.
|
||||
|
||||
Slider0 : Deslizador entero (Rango: 1 ~ 10)
|
||||
Slider1 : Deslizador entero (Rango: 0 ~ 100)
|
||||
Slider2 : Deslizador entero (Rango: 0 ~ 1000)
|
||||
Slider3 : Deslizador entero (Rango: -1000 ~ 1000)
|
||||
|
||||
También hay parámetros de cadena, referenciados por los siguientes nombres.
|
||||
|
||||
obj.text : Cadena del campo de entrada de texto
|
||||
obj.font : Nombre de fuente del selector de fuentes
|
||||
obj.dir : Ruta del selector de carpetas
|
||||
obj.file_video : Ruta de un archivo de video
|
||||
obj.file_audio : Ruta de un archivo de audio
|
||||
obj.file_image : Ruta de un archivo de imagen
|
||||
obj.file_project : Ruta de un archivo de proyecto
|
||||
obj.file_mp4 : Ruta de un archivo MP4
|
||||
obj.file_exo : Ruta de un archivo EXO
|
||||
obj.file_subtitle : Ruta de un archivo de subtítulos
|
||||
obj.file_shader : Ruta de un archivo de sombreador
|
||||
|
||||
* Los deslizadores y los parámetros de cadena aparecen en el panel de efectos
|
||||
automáticamente cuando el script los referencia.
|
||||
* Una ruta de archivo puede pasarse a obj.load para cargar una imagen o un video.
|
||||
* Estos parámetros están disponibles en los motores MoonSharp y nativo.
|
||||
|
||||
|
||||
- Variables globales -
|
||||
|
||||
@@ -127,6 +155,34 @@
|
||||
scene.width : Resolución horizontal (píxeles) de la escena (proyecto) [Solo lectura]
|
||||
scene.height : Resolución vertical (píxeles) de la escena (proyecto) [Solo lectura]
|
||||
|
||||
scene.set(name, value)
|
||||
Guarda un valor en un área compartida a nivel de escena.
|
||||
El valor puede leerse con scene.get(name) desde todos los efectos de
|
||||
script Lua de la misma escena, a través de elementos y fotogramas.
|
||||
name : Nombre del valor (cadena)
|
||||
value : Valor a guardar (número, cadena o booleano). Pasar nil lo elimina.
|
||||
* Los valores que no sean números, cadenas o booleanos (tablas,
|
||||
funciones, etc.) no se guardan.
|
||||
* Los nombres y los valores de cadena se truncan más allá de 4095
|
||||
bytes en UTF-8.
|
||||
Ejemplo: scene.set("shared_x", obj.x)
|
||||
scene.get(name)
|
||||
Obtiene un valor guardado con scene.set(). Devuelve nil para nombres
|
||||
no establecidos.
|
||||
Ejemplo: local x = scene.get("shared_x") or 0
|
||||
* Los valores escritos por su propio script pueden leerse inmediatamente con
|
||||
scene.get dentro de la misma ejecución. Los valores escritos por otros
|
||||
elementos son visibles a partir del fotograma siguiente, por lo que el
|
||||
resultado no depende del orden de evaluación dentro de un fotograma.
|
||||
* Cuando un script termina con un error o por tiempo de espera, ninguna de
|
||||
sus escrituras se aplica al área compartida.
|
||||
* Al iniciar la exportación de video, el área compartida comienza vacía, por
|
||||
lo que exportar el mismo proyecto siempre produce el mismo resultado.
|
||||
* Se pueden guardar hasta 4096 nombres por escena. Las escrituras a nombres
|
||||
nuevos por encima del límite se ignoran.
|
||||
* Los valores son independientes por escena y se mantienen en memoria hasta
|
||||
que YMM4 se cierra. No se guardan en el archivo del proyecto.
|
||||
|
||||
|
||||
- Tabla obj - Variables -
|
||||
|
||||
@@ -217,6 +273,18 @@
|
||||
obj.track2 : Valor actual de Track2 en el panel de efectos [Solo lectura]
|
||||
obj.track3 : Valor actual de Track3 en el panel de efectos [Solo lectura]
|
||||
|
||||
o Deslizadores
|
||||
obj.slider0 : Valor actual de Slider0 en el panel de efectos (entero) [Solo lectura]
|
||||
obj.slider1 : Valor actual de Slider1 en el panel de efectos (entero) [Solo lectura]
|
||||
obj.slider2 : Valor actual de Slider2 en el panel de efectos (entero) [Solo lectura]
|
||||
obj.slider3 : Valor actual de Slider3 en el panel de efectos (entero) [Solo lectura]
|
||||
|
||||
o Parámetros de cadena
|
||||
obj.text : Cadena del campo de entrada de texto [Solo lectura]
|
||||
obj.font : Nombre de fuente del selector de fuentes [Solo lectura]
|
||||
obj.dir : Ruta del selector de carpetas [Solo lectura]
|
||||
obj.file_video ~ obj.file_shader : Ruta de cada selector de archivos [Solo lectura]
|
||||
|
||||
o Capa
|
||||
obj.layer : Número de capa donde se encuentra el objeto [Solo lectura]
|
||||
* Mismo valor que la variable global layer.
|
||||
@@ -466,10 +534,66 @@
|
||||
Opciones que afectan al dibujo actualmente:
|
||||
"antialias" : 0 = vecino más cercano, en otro caso interpolación
|
||||
lineal (obj.draw / obj.drawpoly).
|
||||
"blend" : número de modo de fusión (obj.draw / obj.drawpoly). El
|
||||
mismo orden (empezando en 0) que la lista desplegable "Modo de
|
||||
fusión" del panel de propiedades de YMM4:
|
||||
0=Normal,1=Síntesis de interpolación,2=Comparación (oscura),
|
||||
3=Multiplicar,4=Color de relleno,5=Burn-in (lineal),
|
||||
6=Comparación (clara),7=Pantalla,8=Color sin máscara,
|
||||
9=Sin máscara (lineal) - Aditivo,10=Adición,11=Superponer,
|
||||
12=Luz suave,13=Luz dura,14=Luz viva,15=Luz lineal,
|
||||
16=Pin Light,17=Mezcla dura,18=diferencia,19=Excluido,
|
||||
20=Sustracción,21=División,22=Tono,23=Saturación,24=Color,
|
||||
25=Luminosidad,26=Comparación de colores (claro),27=Fondo,
|
||||
28=Comparación de colores (oscuro),29=Supresión,
|
||||
30=Recorte en el fondo,31=Sólo partes no superpuestas,
|
||||
32=Máscara de inversión de color. Los valores fuera de rango
|
||||
o no válidos se tratan como 0 (Normal).
|
||||
"draw_state" : un booleano que decide si este efecto emite su
|
||||
imagen de trabajo. true emite la imagen de trabajo; false deja
|
||||
pasar la entrada sin cambios. Sirve para emitir la imagen de
|
||||
trabajo sin obj.draw ni setpixel, o para suprimir la salida.
|
||||
Funciona en ambos motores.
|
||||
"drawtarget" : cambia el destino de obj.draw / obj.drawpoly.
|
||||
"framebuffer" (por defecto) compone en el búfer de fotograma.
|
||||
"tempbuffer" compone en el búfer de trabajo tmp en el momento. En
|
||||
obj.setoption("drawtarget", "tempbuffer", w, h) los valores w, h
|
||||
dan el tamaño con que se inicializa el búfer tmp; omítelos para
|
||||
conservarlo. Recupera el resultado de tmp a la imagen de trabajo
|
||||
con obj.copybuffer("obj", "tmp"). La composición en tempbuffer es
|
||||
normal (source-over); blend se aplica al dibujo en framebuffer.
|
||||
Funciona en ambos motores. En MoonSharp la composición en
|
||||
tempbuffer se ejecuta en la GPU y cambia automáticamente a la
|
||||
composición por CPU cuando la GPU no está disponible. Por el
|
||||
redondeo, el resultado puede diferir muy ligeramente entre los
|
||||
motores.
|
||||
|
||||
o obj.pixeloption(nombre, valor)
|
||||
Guarda como estado una opción para las operaciones de píxeles.
|
||||
|
||||
o obj.setanchor(nombre, cantidad [, opción, ..])
|
||||
Muestra puntos de anclaje en la vista previa para ajustar sus
|
||||
coordenadas arrastrando con el ratón. Las coordenadas ajustadas se
|
||||
guardan con el proyecto.
|
||||
nombre : el nombre de la variable Lua que recibe las coordenadas,
|
||||
como cadena. La variable se dispone como pos={x0,y0,x1,y1,…}, o
|
||||
{x0,y0,z0,x1,y1,z1,…} con "xyz". Las coordenadas son relativas
|
||||
al centro del objeto.
|
||||
cantidad : el número de puntos de anclaje. Hasta 32.
|
||||
opción : se enumeran como cadenas.
|
||||
"line" : une los puntos de anclaje con líneas.
|
||||
"loop" : une los puntos de anclaje y cierra el bucle.
|
||||
"star" : une cada punto de anclaje con el centro del objeto.
|
||||
"arm" : une el centro del objeto con cada punto en orden.
|
||||
"xyz" : trata los puntos como coordenadas 3D. 2D por defecto.
|
||||
Devuelve el número de puntos de anclaje. Funciona en ambos motores.
|
||||
El modo de barra "track" aún no se admite y devuelve 0.
|
||||
Ejemplo:
|
||||
num = obj.track0
|
||||
obj.setanchor("pos", num, "loop")
|
||||
for i = 0, num - 1 do
|
||||
obj.draw(pos[i * 2 + 1], pos[i * 2 + 2])
|
||||
end
|
||||
|
||||
|
||||
- ymm4 Table -
|
||||
@@ -531,6 +655,54 @@
|
||||
anim.bezier(t, p0, p1, p2, p3): Evaluates cubic bezier curve at `t` (0.0~1.0)
|
||||
|
||||
|
||||
- Funciones globales compatibles con AviUtl -
|
||||
|
||||
Las siguientes funciones pueden llamarse directamente en el ámbito global.
|
||||
Devuelven resultados idénticos en todos los motores de ejecución
|
||||
(MoonSharp / nativo).
|
||||
|
||||
RGB(r, g, b)
|
||||
RGB(col)
|
||||
RGB(r1, g1, b1, r2, g2, b2)
|
||||
Convierte entre un valor de color (0x000000-0xffffff) y sus
|
||||
componentes rojo, verde y azul (0-255 cada uno). Con 3 argumentos
|
||||
compone un único valor de color y con 1 argumento lo descompone en
|
||||
r, g, b. Con 6 argumentos devuelve un color que cambia linealmente
|
||||
del primer color al segundo según el tiempo transcurrido del objeto
|
||||
(obj.time / obj.totaltime).
|
||||
Ejemplo: col = RGB(64, 192, 255) -- 0x40C0FF
|
||||
Ejemplo: r, g, b = RGB(0x0080FF) -- 0, 128, 255
|
||||
Ejemplo: col = RGB(64,192,255, 128,64,0) -- color inicial -> final
|
||||
|
||||
HSV(h, s, v)
|
||||
HSV(col)
|
||||
HSV(h1, s1, v1, h2, s2, v2)
|
||||
Convierte entre un valor de color (0x000000-0xffffff) y tono (0-360),
|
||||
saturación (0-100) y valor (0-100). Los argumentos funcionan como
|
||||
en RGB().
|
||||
Ejemplo: col = HSV(60, 100, 100) -- 0xFFFF00
|
||||
Ejemplo: h, s, v = HSV(0x0080FF) -- 210, 100, 100
|
||||
|
||||
OR(a, b) / AND(a, b) / XOR(a, b)
|
||||
Realiza operaciones bit a bit (or / and / or exclusivo) sobre enteros
|
||||
de 32 bits. Las fracciones hasta exactamente 0.5 se truncan al
|
||||
convertir a entero (2.50 -> 2, 2.51 -> 3).
|
||||
Ejemplo: result = OR(8, 3) -- 11
|
||||
|
||||
SHIFT(a, shift)
|
||||
Realiza un desplazamiento aritmético. Un shift positivo desplaza a la
|
||||
izquierda y uno negativo a la derecha.
|
||||
Ejemplo: result = SHIFT(5, 3) -- 40
|
||||
Ejemplo: result = SHIFT(91, -2) -- 22
|
||||
|
||||
debug_print(text)
|
||||
Envía la cadena indicada a OutputDebugString(). Para depuración.
|
||||
Los mensajes pueden verse con una herramienta de monitorización como
|
||||
DebugView. Cuando ocurre un error de ejecución del script, el mensaje
|
||||
de error también se envía automáticamente.
|
||||
Ejemplo: debug_print(string.format("x = %d", obj.x))
|
||||
|
||||
|
||||
- Bibliotecas estándar disponibles -
|
||||
|
||||
Biblioteca math:
|
||||
@@ -653,19 +825,55 @@
|
||||
obj.getvalue y obj.setoption / obj.getoption / obj.pixeloption.
|
||||
Consulte "Tabla obj - Funciones" para más detalles.
|
||||
|
||||
o Mapa de compatibilidad AviUtl / AviUtl2 para obj.effect
|
||||
obj.effect("nombre de efecto", "nombre de parámetro", valor, ...)
|
||||
consulta primero el mapa de compatibilidad. Los efectos declarados como
|
||||
nombres de AviUtl / AviUtl2 pasan por la conversión de
|
||||
escala/desplazamiento declarada antes de llegar a las propiedades de
|
||||
YMM4. Los nombres no declarados en el mapa se resuelven directamente por
|
||||
el nombre de efecto o la palabra clave de YMM4, por lo que las llamadas
|
||||
existentes siguen funcionando. El mapa se construye como la inversa de
|
||||
la propia exportación de AviUtl de YMM4 (salida .exo), por lo que es
|
||||
reversible de forma exacta. El motor de destino se selecciona con
|
||||
--!aviutl (predeterminado) / --!aviutl2.
|
||||
Los nombres de efecto declarados en el mapa y sus parámetros principales
|
||||
son los siguientes.
|
||||
ぼかし: 範囲, サイズ固定
|
||||
境界ぼかし: 範囲
|
||||
方向ブラー: 範囲, 角度, サイズ固定
|
||||
放射ブラー: 範囲, X, Y, サイズを固定
|
||||
閃光: 範囲, X, Y, サイズを固定
|
||||
クロマキー: 色相範囲, 境界補正
|
||||
クリッピング: 上, 下, 左, 右, 中心の位置を変更
|
||||
斜めクリッピング: 中心X, 中心Y, 角度, ぼかし, 幅
|
||||
領域拡張: 上, 下, 左, 右
|
||||
座標: X, Y, Z
|
||||
回転: X, Y, Z
|
||||
リサイズ: 拡大率, X, Y, 補間なし
|
||||
画像ループ: 横回数, 縦回数
|
||||
極座標変換: 中心幅, 渦巻
|
||||
グラデーション: 強さ, 中心X, 中心Y, 角度, 幅
|
||||
単色化: 強さ, 輝度を保持する
|
||||
縁取り: サイズ, ぼかし
|
||||
反転: -
|
||||
モザイク: サイズ
|
||||
ディスプレイスメントマップ: ぼかし
|
||||
動画ファイル合成: X, Y, 拡大率
|
||||
色調補正: 明るさ, コントラスト, 色相, 輝度, 彩度
|
||||
色ずれ: ずれ幅, 角度, 強さ
|
||||
色調補正 y 色ずれ corresponden a efectos del complemento de la comunidad.
|
||||
|
||||
Lo siguiente queda fuera del alcance de esta capa. Los scripts que lo llamen no
|
||||
se comportarán como se espera.
|
||||
x Carga de módulos mediante require y acceso arbitrario a archivos como
|
||||
io / dofile (la carga de imagen / vídeo con obj.load sí se admite con
|
||||
validación de cabecera).
|
||||
x obj.setanchor, scene.set / scene.get, etc.
|
||||
x obj.setanchor, etc.
|
||||
|
||||
|
||||
- Funciones no admitidas / Limitaciones -
|
||||
|
||||
x obj.rand1(), obj.mes(), obj.setanchor(), etc. de AviUtl2 no son compatibles.
|
||||
x Las funciones como scene.set() y scene.get() de la tabla scene de AviUtl2 no son compatibles.
|
||||
(Solo se pueden leer scene.width y scene.height)
|
||||
x El acceso arbitrario a archivos desde scripts (require, dofile, io, etc.) no es compatible.
|
||||
Solo obj.load("image"/"movie") carga archivos confirmados como medios genuinos
|
||||
mediante validación de la cabecera inicial.
|
||||
|
||||
@@ -2,7 +2,9 @@
|
||||
|
||||
Efek video "Script Lua" di YukkuriMovieMaker4 menggunakan
|
||||
bahasa Lua untuk penulisan skrip.
|
||||
Mesin skrip yang digunakan adalah MoonSharp (kompatibel dengan Lua 5.2).
|
||||
Skrip dijalankan pada runtime cepat yang disertakan (LuaJIT), dan
|
||||
berjalan pada MoonSharp (kompatibel dengan Lua 5.2) jika runtime
|
||||
tersebut tidak tersedia.
|
||||
|
||||
* Efek ini adalah implementasi mandiri dan berbeda dari spesifikasi skrip AviUtl2.
|
||||
* Memiliki spesifikasi yang berbeda dari file skrip AviUtl2 (*.anm2, dll.).
|
||||
@@ -11,7 +13,7 @@
|
||||
|
||||
- Catatan -
|
||||
|
||||
o Mesin eksekusi skrip adalah MoonSharp (kompatibel dengan Lua 5.2).
|
||||
o Mesin eksekusi skrip adalah LuaJIT (bawaan) dan MoonSharp (kompatibel dengan Lua 5.2).
|
||||
o Pustaka standar yang tersedia terbatas pada berikut ini:
|
||||
table, string, math, bit32
|
||||
* io, os, debug, ffi, require, dll. tidak tersedia.
|
||||
@@ -26,16 +28,17 @@
|
||||
|
||||
- Mesin Eksekusi dan Akselerasi Otomatis -
|
||||
|
||||
Skrip yang berisi pemrosesan piksel (loop bersarang getpixel/setpixel)
|
||||
dianalisis sintaksnya dan secara otomatis dialihkan ke mesin yang lebih
|
||||
cepat. Skrip biasa (koordinat, rotasi, opasitas, dll.) tetap berjalan di
|
||||
MoonSharp seperti sebelumnya, tanpa perubahan perilaku.
|
||||
Skrip dianalisis sintaksnya dan secara otomatis dialihkan ke mesin
|
||||
yang paling sesuai. Skrip tanpa direktif dijalankan pada runtime cepat
|
||||
yang disertakan (LuaJIT), dan pemetaan per-piksel mandiri dikompilasi
|
||||
lebih lanjut ke kernel CPU yang lebih cepat lagi. Hasil keduanya sama
|
||||
dengan MoonSharp.
|
||||
|
||||
o Pengalihan otomatis (saat tidak ada direktif)
|
||||
- Pemetaan per-piksel mandiri (lihat syarat di bawah)
|
||||
-> kernel CPU (cepat, tepat)
|
||||
- Operasi piksel lainnya -> Native (LuaJIT, hanya jika di-deploy)
|
||||
- Tanpa operasi piksel -> MoonSharp
|
||||
- Selain itu -> Native (LuaJIT, hanya jika di-deploy)
|
||||
- Native tidak di-deploy, atau skrip kosong -> MoonSharp
|
||||
|
||||
o Direktif mesin (komentar pada baris pertama skrip)
|
||||
--!cpu : Kernel CPU. Dikompilasi saat runtime menjadi pohon
|
||||
@@ -96,6 +99,33 @@
|
||||
rentang nilai di dalam skrip. Header --track / --check / --color AviUtl tetap
|
||||
berfungsi seperti sebelumnya.
|
||||
|
||||
Ada 4 slider numerik, direferensikan sebagai obj.slider0 hingga obj.slider3.
|
||||
Nilainya berupa bilangan bulat dan tidak memuat desimal.
|
||||
|
||||
Slider0 : Slider bilangan bulat (Rentang: 1 ~ 10)
|
||||
Slider1 : Slider bilangan bulat (Rentang: 0 ~ 100)
|
||||
Slider2 : Slider bilangan bulat (Rentang: 0 ~ 1000)
|
||||
Slider3 : Slider bilangan bulat (Rentang: -1000 ~ 1000)
|
||||
|
||||
Parameter string juga tersedia, direferensikan dengan nama berikut.
|
||||
|
||||
obj.text : String dari kolom input teks
|
||||
obj.font : Nama font dari pemilih font
|
||||
obj.dir : Path dari pemilih folder
|
||||
obj.file_video : Path file video
|
||||
obj.file_audio : Path file audio
|
||||
obj.file_image : Path file gambar
|
||||
obj.file_project : Path file proyek
|
||||
obj.file_mp4 : Path file MP4
|
||||
obj.file_exo : Path file EXO
|
||||
obj.file_subtitle : Path file subtitle
|
||||
obj.file_shader : Path file shader
|
||||
|
||||
* Slider dan parameter string muncul di panel efek secara otomatis saat skrip
|
||||
mereferensikannya.
|
||||
* Path file dapat diteruskan ke obj.load untuk memuat gambar atau video.
|
||||
* Parameter ini tersedia pada mesin MoonSharp maupun native.
|
||||
|
||||
|
||||
- Variabel Global -
|
||||
|
||||
@@ -126,6 +156,34 @@
|
||||
scene.width : Resolusi horizontal (piksel) adegan (proyek) [Hanya Baca]
|
||||
scene.height : Resolusi vertikal (piksel) adegan (proyek) [Hanya Baca]
|
||||
|
||||
scene.set(name, value)
|
||||
Menyimpan nilai ke area bersama yang dibatasi per adegan.
|
||||
Nilai dapat dibaca kembali dengan scene.get(name) dari semua efek
|
||||
skrip Lua dalam adegan yang sama, lintas item dan frame.
|
||||
name : Nama nilai (string)
|
||||
value : Nilai yang disimpan (angka, string, atau boolean). Mengirim
|
||||
nil akan menghapusnya.
|
||||
* Nilai selain angka, string, dan boolean (tabel, fungsi, dll.)
|
||||
tidak disimpan.
|
||||
* Nama dan nilai string dipotong setelah 4095 byte dalam UTF-8.
|
||||
Contoh: scene.set("shared_x", obj.x)
|
||||
scene.get(name)
|
||||
Mengambil nilai yang disimpan dengan scene.set(). Mengembalikan nil
|
||||
untuk nama yang belum diatur.
|
||||
Contoh: local x = scene.get("shared_x") or 0
|
||||
* Nilai yang ditulis oleh skrip Anda sendiri dapat langsung dibaca kembali
|
||||
dengan scene.get dalam eksekusi yang sama. Nilai yang ditulis oleh item
|
||||
lain terlihat mulai frame berikutnya, sehingga hasilnya tidak bergantung
|
||||
pada urutan evaluasi item dalam satu frame.
|
||||
* Saat skrip berakhir dengan kesalahan atau batas waktu, tidak ada
|
||||
penulisannya yang diterapkan ke area bersama.
|
||||
* Saat ekspor video dimulai, area bersama dimulai dari keadaan kosong,
|
||||
sehingga mengekspor proyek yang sama selalu menghasilkan hasil yang sama.
|
||||
* Hingga 4096 nama dapat disimpan per adegan. Penulisan ke nama baru di
|
||||
atas batas akan diabaikan.
|
||||
* Nilai bersifat independen per adegan dan disimpan di memori sampai YMM4
|
||||
ditutup. Tidak disimpan ke berkas proyek.
|
||||
|
||||
|
||||
- Tabel obj - Variabel -
|
||||
|
||||
@@ -216,6 +274,18 @@
|
||||
obj.track2 : Nilai saat ini Track2 di panel efek [Hanya Baca]
|
||||
obj.track3 : Nilai saat ini Track3 di panel efek [Hanya Baca]
|
||||
|
||||
o Slider
|
||||
obj.slider0 : Nilai saat ini Slider0 di panel efek (bilangan bulat) [Hanya Baca]
|
||||
obj.slider1 : Nilai saat ini Slider1 di panel efek (bilangan bulat) [Hanya Baca]
|
||||
obj.slider2 : Nilai saat ini Slider2 di panel efek (bilangan bulat) [Hanya Baca]
|
||||
obj.slider3 : Nilai saat ini Slider3 di panel efek (bilangan bulat) [Hanya Baca]
|
||||
|
||||
o Parameter string
|
||||
obj.text : String dari kolom input teks [Hanya Baca]
|
||||
obj.font : Nama font dari pemilih font [Hanya Baca]
|
||||
obj.dir : Path dari pemilih folder [Hanya Baca]
|
||||
obj.file_video ~ obj.file_shader : Path dari setiap pemilih file [Hanya Baca]
|
||||
|
||||
o Layer
|
||||
obj.layer : Nomor layer tempat objek ditempatkan [Hanya Baca]
|
||||
* Nilai yang sama dengan variabel global layer.
|
||||
@@ -462,10 +532,64 @@
|
||||
Opsi yang saat ini memengaruhi penggambaran:
|
||||
"antialias" : 0 = tetangga terdekat, selain itu interpolasi linear
|
||||
(obj.draw / obj.drawpoly).
|
||||
"blend" : nomor mode blend (obj.draw / obj.drawpoly). Urutan yang
|
||||
sama (mulai dari 0) dengan dropdown "Mode blend" pada panel
|
||||
properti YMM4:
|
||||
0=Normal,1=Larut,2=Gelap,3=Multiply,4=Bakar warna,
|
||||
5=Bakar linier,6=Terang,7=Layar,8=Peleburan warna,
|
||||
9=Peleburan linier (tambah),10=Tambah,11=Overlay,
|
||||
12=Cahaya lembut,13=Cahaya keras,14=Cahaya hidup,
|
||||
15=Cahaya linier,16=Cahaya pin,17=Campuran keras,
|
||||
18=Perbedaan,19=Ekslklusi,20=Pengurangan,21=Divisi,22=Hue,
|
||||
23=Saturasi,24=Warna,25=Pencahayaan,26=Warna terang,
|
||||
27=Belakang,28=Warna gelap,29=Bersih,
|
||||
30=Potong dengan latar belakang,
|
||||
31=Hanya bagian yang tidak tumpang tindih,32=Mask inversi warna.
|
||||
Nilai di luar jangkauan atau tidak valid dianggap 0 (Normal).
|
||||
"draw_state" : boolean yang menentukan apakah efek ini
|
||||
mengeluarkan citra kerjanya. true mengeluarkan citra kerja;
|
||||
false meneruskan input apa adanya. Berguna untuk mengeluarkan
|
||||
citra kerja tanpa obj.draw atau setpixel, atau untuk menekan
|
||||
keluaran. Bekerja pada kedua mesin.
|
||||
"drawtarget" : mengganti tujuan gambar obj.draw / obj.drawpoly.
|
||||
"framebuffer" (bawaan) mengomposit ke frame buffer. "tempbuffer"
|
||||
mengomposit ke buffer kerja tmp secara langsung. Pada
|
||||
obj.setoption("drawtarget", "tempbuffer", w, h), w, h adalah
|
||||
ukuran untuk menginisialisasi buffer tmp; hilangkan untuk
|
||||
mempertahankannya. Kembalikan hasil tmp ke citra kerja dengan
|
||||
obj.copybuffer("obj", "tmp"). Komposit ke tempbuffer bersifat
|
||||
normal (source-over); blend berlaku untuk gambar ke framebuffer.
|
||||
Bekerja pada kedua mesin. Pada MoonSharp, komposit ke tempbuffer
|
||||
dijalankan di GPU dan beralih secara otomatis ke komposit CPU
|
||||
saat GPU tidak tersedia. Karena pembulatan, hasil komposit dapat
|
||||
sedikit berbeda antara kedua mesin.
|
||||
|
||||
o obj.pixeloption(name, value)
|
||||
Menyimpan opsi untuk operasi piksel sebagai status.
|
||||
|
||||
o obj.setanchor(name, count [, option, ..])
|
||||
Menampilkan titik jangkar pada pratinjau agar koordinatnya dapat
|
||||
disesuaikan dengan menyeret mouse. Koordinat yang disesuaikan
|
||||
disimpan bersama proyek.
|
||||
name : nama variabel Lua yang menerima koordinat, sebagai string.
|
||||
Variabel disusun sebagai pos={x0,y0,x1,y1,…}, atau
|
||||
{x0,y0,z0,x1,y1,z1,…} dengan "xyz". Koordinat relatif terhadap
|
||||
pusat objek.
|
||||
count : jumlah titik jangkar. Hingga 32.
|
||||
option : dicantumkan sebagai string.
|
||||
"line" : menghubungkan titik jangkar dengan garis.
|
||||
"loop" : menghubungkan titik jangkar dan menutup lingkaran.
|
||||
"star" : menghubungkan tiap titik jangkar ke pusat objek.
|
||||
"arm" : menghubungkan pusat objek ke tiap titik secara berurutan.
|
||||
"xyz" : memperlakukan titik sebagai koordinat 3D. Bawaan 2D.
|
||||
Mengembalikan jumlah titik jangkar. Bekerja pada kedua mesin.
|
||||
Mode bilah "track" belum didukung dan mengembalikan 0.
|
||||
Contoh:
|
||||
num = obj.track0
|
||||
obj.setanchor("pos", num, "loop")
|
||||
for i = 0, num - 1 do
|
||||
obj.draw(pos[i * 2 + 1], pos[i * 2 + 2])
|
||||
end
|
||||
|
||||
|
||||
- ymm4 Table -
|
||||
@@ -527,6 +651,53 @@
|
||||
anim.bezier(t, p0, p1, p2, p3): Evaluates cubic bezier curve at `t` (0.0~1.0)
|
||||
|
||||
|
||||
- Fungsi Global yang Kompatibel dengan AviUtl -
|
||||
|
||||
Fungsi-fungsi berikut dapat dipanggil langsung di lingkup global.
|
||||
Semuanya mengembalikan hasil identik di setiap mesin eksekusi
|
||||
(MoonSharp / native).
|
||||
|
||||
RGB(r, g, b)
|
||||
RGB(col)
|
||||
RGB(r1, g1, b1, r2, g2, b2)
|
||||
Mengonversi antara nilai warna (0x000000-0xffffff) dan komponen
|
||||
merah, hijau, biru (masing-masing 0-255). Dengan 3 argumen menyusun
|
||||
satu nilai warna, dan dengan 1 argumen menguraikannya menjadi
|
||||
r, g, b. Dengan 6 argumen mengembalikan warna yang berubah linear
|
||||
dari warna pertama ke warna kedua sesuai waktu objek
|
||||
(obj.time / obj.totaltime).
|
||||
Contoh: col = RGB(64, 192, 255) -- 0x40C0FF
|
||||
Contoh: r, g, b = RGB(0x0080FF) -- 0, 128, 255
|
||||
Contoh: col = RGB(64,192,255, 128,64,0) -- warna awal -> akhir
|
||||
|
||||
HSV(h, s, v)
|
||||
HSV(col)
|
||||
HSV(h1, s1, v1, h2, s2, v2)
|
||||
Mengonversi antara nilai warna (0x000000-0xffffff) dan hue (0-360),
|
||||
saturasi (0-100), serta value (0-100). Argumen bekerja seperti RGB().
|
||||
Contoh: col = HSV(60, 100, 100) -- 0xFFFF00
|
||||
Contoh: h, s, v = HSV(0x0080FF) -- 210, 100, 100
|
||||
|
||||
OR(a, b) / AND(a, b) / XOR(a, b)
|
||||
Melakukan operasi bitwise (or / and / exclusive or) pada bilangan
|
||||
bulat 32-bit. Pecahan hingga tepat 0.5 dibulatkan ke bawah saat
|
||||
dikonversi ke bilangan bulat (2.50 -> 2, 2.51 -> 3).
|
||||
Contoh: result = OR(8, 3) -- 11
|
||||
|
||||
SHIFT(a, shift)
|
||||
Melakukan pergeseran aritmetika. Shift positif menggeser ke kiri dan
|
||||
shift negatif menggeser ke kanan.
|
||||
Contoh: result = SHIFT(5, 3) -- 40
|
||||
Contoh: result = SHIFT(91, -2) -- 22
|
||||
|
||||
debug_print(text)
|
||||
Mengirim string yang ditentukan ke OutputDebugString(). Untuk
|
||||
debugging. Pesan dapat dilihat dengan alat pemantau debug seperti
|
||||
DebugView. Saat terjadi kesalahan eksekusi skrip, pesan kesalahan
|
||||
juga dikirim secara otomatis.
|
||||
Contoh: debug_print(string.format("x = %d", obj.x))
|
||||
|
||||
|
||||
- Pustaka Standar yang Tersedia -
|
||||
|
||||
Pustaka math:
|
||||
@@ -648,19 +819,53 @@
|
||||
obj.getvalue, serta obj.setoption / obj.getoption / obj.pixeloption
|
||||
didukung. Lihat "Tabel obj - Fungsi" untuk detailnya.
|
||||
|
||||
o Peta kompatibilitas AviUtl / AviUtl2 untuk obj.effect
|
||||
obj.effect("nama efek", "nama parameter", nilai, ...) pertama-tama
|
||||
merujuk peta kompatibilitas. Efek yang dideklarasikan sebagai nama
|
||||
AviUtl / AviUtl2 melewati konversi skala/offset yang dideklarasikan
|
||||
sebelum mencapai properti YMM4. Nama yang tidak dideklarasikan dalam peta
|
||||
diselesaikan langsung melalui nama efek atau kata kunci YMM4, sehingga
|
||||
pemanggilan yang sudah ada tetap berfungsi. Peta ini dibuat sebagai kebalikan dari ekspor AviUtl milik YMM4
|
||||
sendiri (keluaran .exo), sehingga konsisten secara bolak-balik. Mesin
|
||||
target dipilih dengan --!aviutl (bawaan) / --!aviutl2.
|
||||
Nama efek yang dideklarasikan dalam peta beserta parameter utamanya
|
||||
adalah sebagai berikut.
|
||||
ぼかし: 範囲, サイズ固定
|
||||
境界ぼかし: 範囲
|
||||
方向ブラー: 範囲, 角度, サイズ固定
|
||||
放射ブラー: 範囲, X, Y, サイズを固定
|
||||
閃光: 範囲, X, Y, サイズを固定
|
||||
クロマキー: 色相範囲, 境界補正
|
||||
クリッピング: 上, 下, 左, 右, 中心の位置を変更
|
||||
斜めクリッピング: 中心X, 中心Y, 角度, ぼかし, 幅
|
||||
領域拡張: 上, 下, 左, 右
|
||||
座標: X, Y, Z
|
||||
回転: X, Y, Z
|
||||
リサイズ: 拡大率, X, Y, 補間なし
|
||||
画像ループ: 横回数, 縦回数
|
||||
極座標変換: 中心幅, 渦巻
|
||||
グラデーション: 強さ, 中心X, 中心Y, 角度, 幅
|
||||
単色化: 強さ, 輝度を保持する
|
||||
縁取り: サイズ, ぼかし
|
||||
反転: -
|
||||
モザイク: サイズ
|
||||
ディスプレイスメントマップ: ぼかし
|
||||
動画ファイル合成: X, Y, 拡大率
|
||||
色調補正: 明るさ, コントラスト, 色相, 輝度, 彩度
|
||||
色ずれ: ずれ幅, 角度, 強さ
|
||||
色調補正 dan 色ずれ sesuai dengan efek plugin komunitas.
|
||||
|
||||
Berikut ini berada di luar cakupan lapisan ini. Skrip yang memanggilnya tidak
|
||||
akan berperilaku seperti yang diharapkan.
|
||||
x Pemuatan modul melalui require, dan akses berkas sembarang seperti
|
||||
io / dofile (pemuatan gambar / video via obj.load didukung dengan
|
||||
validasi header).
|
||||
x obj.setanchor, scene.set / scene.get, dll.
|
||||
x obj.setanchor, dll.
|
||||
|
||||
|
||||
- Fitur yang Tidak Didukung / Batasan -
|
||||
|
||||
x obj.rand1(), obj.mes(), obj.setanchor(), dll. dari AviUtl2 tidak didukung.
|
||||
x Fungsi seperti scene.set() dan scene.get() dalam tabel scene AviUtl2 tidak didukung.
|
||||
(Hanya scene.width dan scene.height yang dapat dibaca)
|
||||
x Akses berkas sembarang dari skrip (require, dofile, io, dll.) tidak didukung.
|
||||
Hanya obj.load("image"/"movie") yang memuat berkas yang dipastikan sebagai
|
||||
media asli melalui validasi header awal.
|
||||
|
||||
@@ -2,7 +2,8 @@
|
||||
|
||||
YukkuriMovieMaker4 の「Luaスクリプト」映像エフェクトで
|
||||
利用可能なスクリプトには Lua 言語を使用します。
|
||||
スクリプトエンジンには MoonSharp (Lua 5.2 互換) が採用されています。
|
||||
スクリプトは同梱の高速ランタイム(LuaJIT)で実行され、
|
||||
利用できない環境では MoonSharp (Lua 5.2 互換) で実行されます。
|
||||
|
||||
※このエフェクトは AviUtl2 のスクリプト仕様とは異なる独自実装です。
|
||||
※AviUtl2 のスクリプトファイル(*.anm2 等)とは別仕様です。
|
||||
@@ -11,7 +12,7 @@
|
||||
|
||||
- 注意点 -
|
||||
|
||||
○スクリプトの実行エンジンは MoonSharp (Lua 5.2 互換) です。
|
||||
○スクリプトの実行エンジンは LuaJIT(標準)と MoonSharp (Lua 5.2 互換) です。
|
||||
○利用可能な標準ライブラリは以下に限定されます。
|
||||
table, string, math, bit32
|
||||
※io, os, debug, ffi, require 等は使用できません。
|
||||
@@ -26,15 +27,15 @@
|
||||
|
||||
- 実行エンジンと自動高速化 -
|
||||
|
||||
ピクセル処理(getpixel/setpixel の二重ループ)を含むスクリプトは、
|
||||
構文を解析して自動的に高速なエンジンへ振り分けられます。
|
||||
座標・回転・不透明度などの通常スクリプトは従来どおり MoonSharp で
|
||||
実行され、挙動は一切変わりません。
|
||||
スクリプトは構文を解析して自動的に最適なエンジンへ振り分けられます。
|
||||
ディレクティブ無しのスクリプトは同梱の高速ランタイム(LuaJIT)で
|
||||
実行され、自ピクセル完結のピクセル写像はさらに高速な CPU カーネルへ
|
||||
変換されます。いずれの結果も MoonSharp と一致します。
|
||||
|
||||
○自動振り分け(ディレクティブ無しのとき)
|
||||
・自ピクセル完結のピクセル写像(下記条件) → CPU カーネル(高速・厳密)
|
||||
・上記以外のピクセル操作 → ネイティブ(LuaJIT, 配備時のみ)
|
||||
・ピクセル操作なし → MoonSharp
|
||||
・上記以外 → ネイティブ(LuaJIT, 配備時のみ)
|
||||
・native 未配備または空のスクリプト → MoonSharp
|
||||
|
||||
○エンジン指定ディレクティブ(スクリプト先頭行のコメント)
|
||||
--!cpu : CPU カーネル。式ツリーへ実行時コンパイルして
|
||||
@@ -91,6 +92,33 @@
|
||||
この一般利用では範囲・既定値の宣言を伴わないため、値はスクリプト内で扱います。
|
||||
--track / --check / --color ヘッダによる宣言表示も従来どおり利用できます。
|
||||
|
||||
数値スライダーが 4 つあり、各値は obj.slider0 ~ obj.slider3 として参照できます。
|
||||
値は整数で、小数は扱いません。
|
||||
|
||||
Slider0 : 整数スライダー (範囲: 1 ~ 10)
|
||||
Slider1 : 整数スライダー (範囲: 0 ~ 100)
|
||||
Slider2 : 整数スライダー (範囲: 0 ~ 1000)
|
||||
Slider3 : 整数スライダー (範囲: -1000 ~ 1000)
|
||||
|
||||
文字列パラメータも利用でき、各値は以下の名前で参照できます。
|
||||
|
||||
obj.text : テキスト入力欄の文字列
|
||||
obj.font : フォント選択欄のフォント名
|
||||
obj.dir : フォルダ選択欄のパス
|
||||
obj.file_video : 動画ファイルのパス
|
||||
obj.file_audio : 音声ファイルのパス
|
||||
obj.file_image : 画像ファイルのパス
|
||||
obj.file_project : プロジェクトファイルのパス
|
||||
obj.file_mp4 : MP4 ファイルのパス
|
||||
obj.file_exo : EXO ファイルのパス
|
||||
obj.file_subtitle : 字幕ファイルのパス
|
||||
obj.file_shader : シェーダーファイルのパス
|
||||
|
||||
※スライダーと文字列パラメータは、スクリプト本体でそれらを参照すると
|
||||
自動的にエフェクトパネルへ表示されます。
|
||||
※ファイル選択のパスは obj.load へ渡して画像・動画の読み込みに使えます。
|
||||
※これらのパラメータは MoonSharp とネイティブのどちらのエンジンでも参照できます。
|
||||
|
||||
|
||||
- グローバル変数 -
|
||||
|
||||
@@ -123,6 +151,31 @@
|
||||
scene.cx : シーンの横解像度の半分 (= scene.width / 2) [ReadOnly]
|
||||
scene.cy : シーンの縦解像度の半分 (= scene.height / 2) [ReadOnly]
|
||||
|
||||
scene.set(name, value)
|
||||
シーン単位の共有領域へ値を保存します。
|
||||
同じシーン内のすべての Lua スクリプトエフェクトから、アイテムや
|
||||
フレームをまたいで scene.get(name) で参照できます。
|
||||
name : 値の名前(文字列)
|
||||
value : 保存する値(数値・文字列・真偽値)。nil を渡すと削除します。
|
||||
※ 数値・文字列・真偽値以外(テーブル・関数など)は保存されません。
|
||||
※ 名前と文字列値は UTF-8 換算で 4095 バイトを超える部分を切り捨てます。
|
||||
例:scene.set("shared_x", obj.x)
|
||||
scene.get(name)
|
||||
scene.set() で保存した値を取得します。未設定の名前は nil を返します。
|
||||
例:local x = scene.get("shared_x") or 0
|
||||
※ 自分のスクリプトが書き込んだ値は、同じ実行の中で直後の scene.get から
|
||||
そのまま読み取れます。他のアイテムが書き込んだ値は、次のフレームの
|
||||
評価から読み取れます。同じフレームの中では、アイテムがどの順番で
|
||||
評価されても読み取れる値は変わりません。
|
||||
※ スクリプトがエラーまたはタイムアウトで終了した場合には、その実行の
|
||||
書き込みは共有領域へ反映されません。
|
||||
※ 動画出力を開始すると共有領域は空の状態から始まるため、同じ
|
||||
プロジェクトを出力すれば毎回同じ結果になります。
|
||||
※ 1 つのシーンに保存できる名前は 4096 個までです。上限を超えた新しい
|
||||
名前への書き込みは無視されます。
|
||||
※ 値はシーンごとに独立しており、YMM4 を終了するまでメモリ上に保持
|
||||
されます。プロジェクトファイルには保存されません。
|
||||
|
||||
|
||||
- obj テーブル - 変数 -
|
||||
|
||||
@@ -214,6 +267,18 @@
|
||||
obj.track2 : エフェクトパネルの Track2 の現在値 [ReadOnly]
|
||||
obj.track3 : エフェクトパネルの Track3 の現在値 [ReadOnly]
|
||||
|
||||
○スライダー
|
||||
obj.slider0 : エフェクトパネルの Slider0 の現在値(整数) [ReadOnly]
|
||||
obj.slider1 : エフェクトパネルの Slider1 の現在値(整数) [ReadOnly]
|
||||
obj.slider2 : エフェクトパネルの Slider2 の現在値(整数) [ReadOnly]
|
||||
obj.slider3 : エフェクトパネルの Slider3 の現在値(整数) [ReadOnly]
|
||||
|
||||
○文字列パラメータ
|
||||
obj.text : テキスト入力欄の文字列 [ReadOnly]
|
||||
obj.font : フォント選択欄のフォント名 [ReadOnly]
|
||||
obj.dir : フォルダ選択欄のパス [ReadOnly]
|
||||
obj.file_video 〜 obj.file_shader : 各ファイル選択欄のパス [ReadOnly]
|
||||
|
||||
○レイヤー
|
||||
obj.layer : オブジェクトが配置されているレイヤー番号 [ReadOnly]
|
||||
※ グローバル変数 layer と同じ値です。
|
||||
@@ -451,10 +516,61 @@
|
||||
停止させません(getoption は設定値を返し、未設定は 0)。
|
||||
現在描画へ反映される項目:
|
||||
"antialias" : 0 で最近傍、それ以外で線形補間(obj.draw/drawpoly)。
|
||||
"blend" : obj.draw / obj.drawpoly の合成モードを番号で指定します。
|
||||
YMM4 のプロパティパネルにある「合成モード」のドロップダウンと
|
||||
並び順が同じで、番号は 0 から始まります。
|
||||
0=通常,1=ディザ合成,2=比較(暗),3=乗算,4=焼き込みカラー,
|
||||
5=焼き込み(リニア),6=比較(明),7=スクリーン,8=覆い焼きカラー,
|
||||
9=覆い焼き(リニア) - 加算,10=加算,11=オーバーレイ,
|
||||
12=ソフトライト,13=ハードライト,14=ビビッドライト,15=リニアライト,
|
||||
16=ピンライト,17=ハードミックス,18=差分,19=除外,20=減算,21=除算,
|
||||
22=色相,23=彩度,24=カラー,25=輝度,26=カラー比較(明),27=背景,
|
||||
28=カラー比較(暗),29=削除,30=背景でクリッピング,
|
||||
31=重ならない部分のみ,32=色反転マスク。
|
||||
範囲外の値や数値以外を指定した場合は通常モードになります。
|
||||
"draw_state" : このエフェクトが作業画像を出力するかどうかを
|
||||
真偽値で決めます。true で作業画像を出力し、false で入力を
|
||||
そのまま通します。obj.draw や setpixel を使わずに作業画像を
|
||||
そのまま出力させたいときや、逆に出力を止めたいときに使います。
|
||||
両エンジンで動きます。
|
||||
"drawtarget" : obj.draw / obj.drawpoly の描画先を切り替えます。
|
||||
"framebuffer"(既定)ではフレームバッファへ合成します。
|
||||
"tempbuffer" では作業用の tmp バッファへその場で合成します。
|
||||
obj.setoption("drawtarget", "tempbuffer", w, h) の w, h は
|
||||
tmp バッファを初期化するサイズで、省略すると初期化しません。
|
||||
tmp へ描いた結果は obj.copybuffer("obj", "tmp") で作業画像へ
|
||||
戻せます。tempbuffer への合成は通常(ソースオーバー)で、blend は
|
||||
framebuffer への描画に適用されます。両エンジンで動きます。
|
||||
MoonSharp では tempbuffer への合成を GPU で実行し、GPU を
|
||||
利用できない環境では CPU の合成へ自動的に切り替わります。
|
||||
丸めの違いにより、合成の結果はエンジン間でごく僅かに
|
||||
異なることがあります。
|
||||
|
||||
○obj.pixeloption(名前, 値)
|
||||
ピクセル操作のオプションを状態として保持します。
|
||||
|
||||
○obj.setanchor(名前, 個数 [, オプション, ..])
|
||||
アンカーポイントをプレビュー上に表示し、マウスドラッグで座標を
|
||||
調整できるようにします。調整した座標はプロジェクトへ保存されます。
|
||||
名前 : 座標を格納する Lua 変数の名前を文字列で指定します。
|
||||
変数は pos={x0,y0,x1,y1,…} の並びで、xyz 指定時は
|
||||
{x0,y0,z0,x1,y1,z1,…} になります。座標はオブジェクトの
|
||||
中心が原点です。
|
||||
個数 : アンカーポイントの数を指定します。最大 32 個です。
|
||||
オプション : 文字列で列挙できます。
|
||||
"line" : アンカーポイントを線で結びます。
|
||||
"loop" : アンカーポイントを線で結び一周させます。
|
||||
"star" : 各アンカーポイントとオブジェクトの中心を線で結びます。
|
||||
"arm" : オブジェクトの中心から各アンカーポイントへ順に線で結びます。
|
||||
"xyz" : アンカーポイントを 3D 座標で扱います。既定は 2D です。
|
||||
戻り値は設置したアンカーポイントの数です。両エンジンで動きます。
|
||||
名前に "track" を指定するトラックバー連携は現在未対応で、0 を返します。
|
||||
例:
|
||||
num = obj.track0
|
||||
obj.setanchor("pos", num, "loop")
|
||||
for i = 0, num - 1 do
|
||||
obj.draw(pos[i * 2 + 1], pos[i * 2 + 2])
|
||||
end
|
||||
|
||||
|
||||
- ymm4 テーブル -
|
||||
@@ -516,6 +632,50 @@
|
||||
anim.bezier(t, p0, p1, p2, p3): t (0.0~1.0) における3次ベジェ曲線の値を計算
|
||||
|
||||
|
||||
- AviUtl 互換のグローバル関数 -
|
||||
|
||||
以下の関数はグローバルスコープで直接呼び出せます。
|
||||
すべての実行エンジン(MoonSharp / ネイティブ)で同一の結果を返します。
|
||||
|
||||
RGB(r, g, b)
|
||||
RGB(col)
|
||||
RGB(r1, g1, b1, r2, g2, b2)
|
||||
色情報(0x000000~0xffffff)と赤・緑・青(各0~255)を相互変換します。
|
||||
引数 3 つで 1 つの色情報へ合成し、引数 1 つで r, g, b の 3 値へ
|
||||
分解します。引数 6 つでは、オブジェクトの時間経過
|
||||
(obj.time / obj.totaltime)に応じて一色目から二色目へ直線的に
|
||||
変化する色情報を返します。
|
||||
例:col = RGB(64, 192, 255) -- 0x40C0FF
|
||||
例:r, g, b = RGB(0x0080FF) -- 0, 128, 255
|
||||
例:col = RGB(64,192,255, 128,64,0) -- 開始色→終了色
|
||||
|
||||
HSV(h, s, v)
|
||||
HSV(col)
|
||||
HSV(h1, s1, v1, h2, s2, v2)
|
||||
色情報(0x000000~0xffffff)と色相(0~360)・彩度(0~100)・
|
||||
明度(0~100)を相互変換します。引数の意味は RGB() と同様です。
|
||||
例:col = HSV(60, 100, 100) -- 0xFFFF00
|
||||
例:h, s, v = HSV(0x0080FF) -- 210, 100, 100
|
||||
|
||||
OR(a, b) / AND(a, b) / XOR(a, b)
|
||||
32bit 整数としてビット演算(論理和・論理積・排他的論理和)をします。
|
||||
小数は 0.5 ちょうどまでを切り捨てて整数化します(2.50→2、2.51→3)。
|
||||
例:result = OR(8, 3) -- 11
|
||||
|
||||
SHIFT(a, shift)
|
||||
算術シフトをします。shift が正の数だと左シフト、負の数だと
|
||||
右シフトになります。
|
||||
例:result = SHIFT(5, 3) -- 40
|
||||
例:result = SHIFT(91, -2) -- 22
|
||||
|
||||
debug_print(text)
|
||||
指定の文字列を OutputDebugString() へ送ります。デバッグ用です。
|
||||
メッセージは DebugView などのデバッグモニタツールで確認できます。
|
||||
また、スクリプトの実行エラーが発生したときにはエラーメッセージが
|
||||
自動で送られます。
|
||||
例:debug_print(string.format("x = %d", obj.x))
|
||||
|
||||
|
||||
- 利用可能な標準ライブラリ -
|
||||
|
||||
math ライブラリ:
|
||||
@@ -634,18 +794,51 @@
|
||||
obj.getoption / obj.pixeloption に対応します。詳細は「obj テーブル -
|
||||
関数」を参照してください。
|
||||
|
||||
○obj.effect の AviUtl/AviUtl2 互換マップ
|
||||
obj.effect("エフェクト名", "パラメータ名", 値, …) はまず互換マップを
|
||||
参照します。AviUtl/AviUtl2 の名前として宣言したエフェクトは、値がマップに
|
||||
定義した倍率とオフセットの変換を経て YMM4 のプロパティへ反映します。互換
|
||||
マップに宣言が無い名前は、YMM4 のエフェクト名やキーワードでそのまま解決
|
||||
するため、既存の呼び出しはそのまま動きます。この互換マップは、YMM4 自身が AviUtl の
|
||||
.exo へ書き出す変換を逆向きにたどって作っているため、往復しても結果が
|
||||
一致します。対象のエンジンは指定子 --!aviutl または --!aviutl2 で
|
||||
切り替えます。指定子を書かないときは --!aviutl として扱います。
|
||||
マップに宣言したエフェクト名と主なパラメータは次のとおりです。
|
||||
ぼかし: 範囲, サイズ固定
|
||||
境界ぼかし: 範囲
|
||||
方向ブラー: 範囲, 角度, サイズ固定
|
||||
放射ブラー: 範囲, X, Y, サイズを固定
|
||||
閃光: 範囲, X, Y, サイズを固定
|
||||
クロマキー: 色相範囲, 境界補正
|
||||
クリッピング: 上, 下, 左, 右, 中心の位置を変更
|
||||
斜めクリッピング: 中心X, 中心Y, 角度, ぼかし, 幅
|
||||
領域拡張: 上, 下, 左, 右
|
||||
座標: X, Y, Z
|
||||
回転: X, Y, Z
|
||||
リサイズ: 拡大率, X, Y, 補間なし
|
||||
画像ループ: 横回数, 縦回数
|
||||
極座標変換: 中心幅, 渦巻
|
||||
グラデーション: 強さ, 中心X, 中心Y, 角度, 幅
|
||||
単色化: 強さ, 輝度を保持する
|
||||
縁取り: サイズ, ぼかし
|
||||
反転: パラメータなし
|
||||
モザイク: サイズ
|
||||
ディスプレイスメントマップ: ぼかし
|
||||
動画ファイル合成: X, Y, 拡大率
|
||||
色調補正: 明るさ, コントラスト, 色相, 輝度, 彩度
|
||||
色ずれ: ずれ幅, 角度, 強さ
|
||||
色調補正 と 色ずれ はコミュニティプラグインのエフェクトに対応します。
|
||||
|
||||
次の機能はこの互換層では対象外です。
|
||||
これらを呼び出すスクリプトは意図どおりには動作しません。
|
||||
×require によるモジュール読み込み、io / dofile などの任意ファイル
|
||||
アクセス(obj.load の画像 / 動画はヘッダー検証付きで対応)。
|
||||
×obj.setanchor、scene.set / scene.get 等。
|
||||
×obj.setanchor 等。
|
||||
|
||||
|
||||
- 非対応・制限事項 -
|
||||
|
||||
×AviUtl2 の obj.rand1(), obj.mes(), obj.setanchor() 等には対応していません。
|
||||
×AviUtl2 の scene テーブルの scene.set(), scene.get() 等の関数には対応していません。
|
||||
(scene.width と scene.height の読み取りのみ対応)
|
||||
×スクリプトからの任意ファイルアクセス(require, dofile, io 等)には対応して
|
||||
いません。obj.load("image"/"movie") のみ、先頭ヘッダー検証で真正なメディアと
|
||||
確認できたファイルを読み込みます。
|
||||
|
||||
@@ -2,7 +2,8 @@
|
||||
|
||||
YukkuriMovieMaker4의 「Lua 스크립트」 영상 이펙트에서
|
||||
사용 가능한 스크립트에는 Lua 언어를 사용합니다.
|
||||
스크립트 엔진으로는 MoonSharp (Lua 5.2 호환)이 채용되어 있습니다.
|
||||
스크립트는 동봉된 고속 런타임(LuaJIT)으로 실행되며,
|
||||
사용할 수 없는 환경에서는 MoonSharp (Lua 5.2 호환)으로 실행됩니다.
|
||||
|
||||
※ 이 이펙트는 AviUtl2의 스크립트 사양과는 다른 독자적인 구현입니다.
|
||||
※ AviUtl2의 스크립트 파일(*.anm2 등)과는 별도의 사양입니다.
|
||||
@@ -11,7 +12,7 @@
|
||||
|
||||
- 주의 사항 -
|
||||
|
||||
○ 스크립트 실행 엔진은 MoonSharp (Lua 5.2 호환)입니다.
|
||||
○ 스크립트 실행 엔진은 LuaJIT(표준)과 MoonSharp (Lua 5.2 호환)입니다.
|
||||
○ 사용 가능한 표준 라이브러리는 다음으로 제한됩니다.
|
||||
table, string, math, bit32
|
||||
※ io, os, debug, ffi, require 등은 사용할 수 없습니다.
|
||||
@@ -26,15 +27,15 @@
|
||||
|
||||
- 실행 엔진과 자동 가속 -
|
||||
|
||||
픽셀 처리(getpixel/setpixel 이중 루프)를 포함하는 스크립트는
|
||||
구문을 분석하여 자동으로 더 빠른 엔진으로 분배됩니다.
|
||||
좌표・회전・불투명도 등 일반 스크립트는 기존과 동일하게 MoonSharp으로
|
||||
실행되며 동작은 전혀 바뀌지 않습니다.
|
||||
스크립트는 구문을 분석하여 자동으로 가장 적합한 엔진으로 분배됩니다.
|
||||
디렉티브가 없는 스크립트는 동봉된 고속 런타임(LuaJIT)으로 실행되며,
|
||||
자기 픽셀로 완결되는 픽셀 매핑은 더욱 빠른 CPU 커널로 변환됩니다.
|
||||
어느 쪽이든 결과는 MoonSharp과 일치합니다.
|
||||
|
||||
○ 자동 분배(디렉티브가 없을 때)
|
||||
· 자기 픽셀로 완결되는 픽셀 매핑(아래 조건) → CPU 커널(고속・엄밀)
|
||||
· 위 이외의 픽셀 조작 → 네이티브(LuaJIT, 배치된 경우에만)
|
||||
· 픽셀 조작 없음 → MoonSharp
|
||||
· 위 이외 → 네이티브(LuaJIT, 배치된 경우에만)
|
||||
· native 미배치 또는 빈 스크립트 → MoonSharp
|
||||
|
||||
○ 엔진 지정 디렉티브(스크립트 첫 줄의 주석)
|
||||
--!cpu : CPU 커널. 식 트리로 런타임 컴파일하여
|
||||
@@ -91,6 +92,32 @@
|
||||
선언을 동반하지 않으므로 값의 범위는 스크립트 내에서 처리하세요. AviUtl의
|
||||
--track / --check / --color 헤더 선언 표시도 기존과 동일하게 사용할 수 있습니다.
|
||||
|
||||
숫자 슬라이더가 4개 있으며, 각 값은 obj.slider0 ~ obj.slider3으로 참조할 수 있습니다.
|
||||
값은 정수이며 소수는 다루지 않습니다.
|
||||
|
||||
Slider0 : 정수 슬라이더 (범위: 1 ~ 10)
|
||||
Slider1 : 정수 슬라이더 (범위: 0 ~ 100)
|
||||
Slider2 : 정수 슬라이더 (범위: 0 ~ 1000)
|
||||
Slider3 : 정수 슬라이더 (범위: -1000 ~ 1000)
|
||||
|
||||
문자열 파라미터도 사용할 수 있으며, 각 값은 다음 이름으로 참조합니다.
|
||||
|
||||
obj.text : 텍스트 입력란의 문자열
|
||||
obj.font : 글꼴 선택란의 글꼴 이름
|
||||
obj.dir : 폴더 선택란의 경로
|
||||
obj.file_video : 동영상 파일의 경로
|
||||
obj.file_audio : 음성 파일의 경로
|
||||
obj.file_image : 이미지 파일의 경로
|
||||
obj.file_project : 프로젝트 파일의 경로
|
||||
obj.file_mp4 : MP4 파일의 경로
|
||||
obj.file_exo : EXO 파일의 경로
|
||||
obj.file_subtitle : 자막 파일의 경로
|
||||
obj.file_shader : 셰이더 파일의 경로
|
||||
|
||||
※슬라이더와 문자열 파라미터는 스크립트 본문에서 참조하면 이펙트 패널에 자동으로 표시됩니다.
|
||||
※파일 선택 경로는 obj.load에 전달해 이미지・동영상을 불러오는 데 사용할 수 있습니다.
|
||||
※이 파라미터들은 MoonSharp과 네이티브 두 엔진에서 모두 참조할 수 있습니다.
|
||||
|
||||
|
||||
- 전역 변수 -
|
||||
|
||||
@@ -121,6 +148,32 @@
|
||||
scene.width : 씬(프로젝트)의 가로 해상도(픽셀) [읽기 전용]
|
||||
scene.height : 씬(프로젝트)의 세로 해상도(픽셀) [읽기 전용]
|
||||
|
||||
scene.set(name, value)
|
||||
씬 단위의 공유 영역에 값을 저장합니다.
|
||||
같은 씬 안의 모든 Lua 스크립트 이펙트에서 아이템과 프레임을 넘어
|
||||
scene.get(name)으로 참조할 수 있습니다.
|
||||
name : 값의 이름(문자열)
|
||||
value : 저장할 값(숫자·문자열·불리언). nil을 전달하면 삭제됩니다.
|
||||
※ 숫자·문자열·불리언 이외(테이블·함수 등)는 저장되지 않습니다.
|
||||
※ 이름과 문자열 값은 UTF-8 기준 4095바이트를 넘는 부분이 잘립니다.
|
||||
예: scene.set("shared_x", obj.x)
|
||||
scene.get(name)
|
||||
scene.set()으로 저장한 값을 가져옵니다. 설정되지 않은 이름은 nil을
|
||||
반환합니다.
|
||||
예: local x = scene.get("shared_x") or 0
|
||||
※ 자신의 스크립트가 기록한 값은 같은 실행 안에서 바로 다음의 scene.get으로
|
||||
그대로 읽을 수 있습니다. 다른 아이템이 기록한 값은 다음 프레임의
|
||||
평가부터 읽을 수 있으므로, 같은 프레임 안에서는 아이템의 평가 순서와
|
||||
관계없이 결과가 같습니다.
|
||||
※ 스크립트가 오류 또는 시간 초과로 종료된 경우, 그 실행의 기록은 공유
|
||||
영역에 반영되지 않습니다.
|
||||
※ 동영상 출력을 시작하면 공유 영역은 빈 상태에서 시작하므로, 같은
|
||||
프로젝트를 출력하면 항상 같은 결과가 나옵니다.
|
||||
※ 하나의 씬에 저장할 수 있는 이름은 4096개까지입니다. 상한을 넘는 새
|
||||
이름에 대한 기록은 무시됩니다.
|
||||
※ 값은 씬마다 독립적이며 YMM4를 종료할 때까지 메모리에 유지됩니다.
|
||||
프로젝트 파일에는 저장되지 않습니다.
|
||||
|
||||
|
||||
- obj 테이블 - 변수 -
|
||||
|
||||
@@ -211,6 +264,18 @@
|
||||
obj.track2 : 이펙트 패널의 Track2 현재값 [읽기 전용]
|
||||
obj.track3 : 이펙트 패널의 Track3 현재값 [읽기 전용]
|
||||
|
||||
○ 슬라이더
|
||||
obj.slider0 : 이펙트 패널의 Slider0 현재값(정수) [읽기 전용]
|
||||
obj.slider1 : 이펙트 패널의 Slider1 현재값(정수) [읽기 전용]
|
||||
obj.slider2 : 이펙트 패널의 Slider2 현재값(정수) [읽기 전용]
|
||||
obj.slider3 : 이펙트 패널의 Slider3 현재값(정수) [읽기 전용]
|
||||
|
||||
○ 문자열 파라미터
|
||||
obj.text : 텍스트 입력란의 문자열 [읽기 전용]
|
||||
obj.font : 글꼴 선택란의 글꼴 이름 [읽기 전용]
|
||||
obj.dir : 폴더 선택란의 경로 [읽기 전용]
|
||||
obj.file_video ~ obj.file_shader : 각 파일 선택란의 경로 [읽기 전용]
|
||||
|
||||
○ 레이어
|
||||
obj.layer : 오브젝트가 배치된 레이어 번호 [읽기 전용]
|
||||
※ 전역 변수 layer와 동일한 값입니다.
|
||||
@@ -446,10 +511,59 @@
|
||||
스크립트를 중단시키지 않습니다(getoption은 설정값을 반환, 미설정은 0).
|
||||
현재 그리기에 반영되는 항목:
|
||||
"antialias" : 0이면 최근접, 그 외는 선형 보간(obj.draw / obj.drawpoly).
|
||||
"blend" : 합성 모드 번호(obj.draw / obj.drawpoly). YMM4 속성
|
||||
패널의 "합성 모드" 드롭다운과 동일한 순서(0부터 시작):
|
||||
0=보통,1=디졸브,2=비교(어두움),3=곱하기,4=색상번,
|
||||
5=구워내기(선형),6=비교(밝음),7=화면,8=색상 닷지,
|
||||
9=선형 닷지 ‐ 가산,10=가산,11=오버레이,12=소프트 라이트,
|
||||
13=하드 라이트,14=선명한 라이트,15=리니어 라이트,16=핀 라이트,
|
||||
17=하드 믹스,18=차분,19=제외,20=감산,21=디비전,22=색조,
|
||||
23=채도,24=컬러,25=밝기,26=색상 비교(밝음),27=배경,
|
||||
28=색상 비교(어두운),29=삭제,30=배경에서 클리핑,
|
||||
31=겹치지 않는 부분만,32=색상 반전 마스크.
|
||||
범위를 벗어나거나 잘못된 값은 0(보통)으로 처리합니다.
|
||||
"draw_state" : 이 이펙트가 작업 이미지를 출력할지를 불리언으로
|
||||
정합니다. true는 작업 이미지를 출력하고, false는 입력을 그대로
|
||||
통과시킵니다. obj.draw나 setpixel을 쓰지 않고 작업 이미지를
|
||||
출력하거나, 반대로 출력을 막을 때 사용합니다. 두 엔진 모두에서
|
||||
동작합니다.
|
||||
"drawtarget" : obj.draw / obj.drawpoly의 그리기 대상을 바꿉니다.
|
||||
"framebuffer"(기본)는 프레임 버퍼에 합성합니다. "tempbuffer"는
|
||||
작업용 tmp 버퍼에 즉시 합성합니다.
|
||||
obj.setoption("drawtarget", "tempbuffer", w, h)의 w, h는 tmp
|
||||
버퍼를 초기화하는 크기이며, 생략하면 초기화하지 않습니다. tmp에
|
||||
그린 결과는 obj.copybuffer("obj", "tmp")로 작업 이미지에 되돌릴
|
||||
수 있습니다. tempbuffer로의 합성은 보통(소스 오버)이며, blend는
|
||||
framebuffer 그리기에 적용됩니다. 두 엔진 모두에서 동작합니다.
|
||||
MoonSharp에서는 tempbuffer로의 합성을 GPU에서 실행하며, GPU를
|
||||
사용할 수 없는 환경에서는 CPU 합성으로 자동 전환됩니다. 반올림
|
||||
차이로 인해 합성 결과가 엔진 간에 아주 조금 다를 수 있습니다.
|
||||
|
||||
○ obj.pixeloption(이름, 값)
|
||||
픽셀 조작 옵션을 상태로 보존합니다.
|
||||
|
||||
○ obj.setanchor(이름, 개수 [, 옵션, ..])
|
||||
프리뷰에 앵커 포인트를 표시하고 마우스 드래그로 좌표를 조정할 수
|
||||
있게 합니다. 조정한 좌표는 프로젝트에 저장됩니다.
|
||||
이름 : 좌표를 받을 Lua 변수 이름을 문자열로 지정합니다. 변수는
|
||||
pos={x0,y0,x1,y1,…} 배열이며, "xyz" 지정 시
|
||||
{x0,y0,z0,x1,y1,z1,…}가 됩니다. 좌표는 오브젝트 중심이
|
||||
원점입니다.
|
||||
개수 : 앵커 포인트 수를 지정합니다. 최대 32개입니다.
|
||||
옵션 : 문자열로 열거할 수 있습니다.
|
||||
"line" : 앵커 포인트를 선으로 잇습니다.
|
||||
"loop" : 앵커 포인트를 선으로 잇고 한 바퀴 닫습니다.
|
||||
"star" : 각 앵커 포인트를 오브젝트 중심과 선으로 잇습니다.
|
||||
"arm" : 오브젝트 중심에서 각 앵커 포인트로 차례로 잇습니다.
|
||||
"xyz" : 앵커 포인트를 3D 좌표로 다룹니다. 기본은 2D입니다.
|
||||
설치한 앵커 포인트 수를 반환합니다. 두 엔진 모두에서 동작합니다.
|
||||
이름에 "track"을 지정하는 트랙바 연동은 현재 미지원이며 0을 반환합니다.
|
||||
예:
|
||||
num = obj.track0
|
||||
obj.setanchor("pos", num, "loop")
|
||||
for i = 0, num - 1 do
|
||||
obj.draw(pos[i * 2 + 1], pos[i * 2 + 2])
|
||||
end
|
||||
|
||||
|
||||
- ymm4 테이블 -
|
||||
@@ -511,6 +625,50 @@
|
||||
anim.bezier(t, p0, p1, p2, p3): t(0.0~1.0)에서의 3차 베지어 곡선 값을 계산
|
||||
|
||||
|
||||
- AviUtl 호환 전역 함수 -
|
||||
|
||||
다음 함수는 전역 스코프에서 직접 호출할 수 있습니다.
|
||||
모든 실행 엔진(MoonSharp / 네이티브)에서 동일한 결과를 반환합니다.
|
||||
|
||||
RGB(r, g, b)
|
||||
RGB(col)
|
||||
RGB(r1, g1, b1, r2, g2, b2)
|
||||
색 정보(0x000000~0xffffff)와 빨강·초록·파랑(각 0~255)을 상호
|
||||
변환합니다. 인수 3개는 하나의 색 정보로 합성하고, 인수 1개는
|
||||
r, g, b 세 값으로 분해합니다. 인수 6개는 오브젝트의 시간 경과
|
||||
(obj.time / obj.totaltime)에 따라 첫 번째 색에서 두 번째 색으로
|
||||
선형 변화하는 색 정보를 반환합니다.
|
||||
예: col = RGB(64, 192, 255) -- 0x40C0FF
|
||||
예: r, g, b = RGB(0x0080FF) -- 0, 128, 255
|
||||
예: col = RGB(64,192,255, 128,64,0) -- 시작 색 → 종료 색
|
||||
|
||||
HSV(h, s, v)
|
||||
HSV(col)
|
||||
HSV(h1, s1, v1, h2, s2, v2)
|
||||
색 정보(0x000000~0xffffff)와 색상(0~360)·채도(0~100)·
|
||||
명도(0~100)를 상호 변환합니다. 인수의 의미는 RGB()와 같습니다.
|
||||
예: col = HSV(60, 100, 100) -- 0xFFFF00
|
||||
예: h, s, v = HSV(0x0080FF) -- 210, 100, 100
|
||||
|
||||
OR(a, b) / AND(a, b) / XOR(a, b)
|
||||
32bit 정수로 비트 연산(논리합·논리곱·배타적 논리합)을 합니다.
|
||||
소수는 정확히 0.5까지 내림하여 정수화합니다(2.50→2, 2.51→3).
|
||||
예: result = OR(8, 3) -- 11
|
||||
|
||||
SHIFT(a, shift)
|
||||
산술 시프트를 합니다. shift가 양수면 왼쪽, 음수면 오른쪽으로
|
||||
시프트합니다.
|
||||
예: result = SHIFT(5, 3) -- 40
|
||||
예: result = SHIFT(91, -2) -- 22
|
||||
|
||||
debug_print(text)
|
||||
지정한 문자열을 OutputDebugString()으로 보냅니다. 디버그용입니다.
|
||||
메시지는 DebugView 등의 디버그 모니터 도구로 확인할 수 있습니다.
|
||||
또한 스크립트 실행 오류가 발생하면 오류 메시지가 자동으로
|
||||
전송됩니다.
|
||||
예: debug_print(string.format("x = %d", obj.x))
|
||||
|
||||
|
||||
- 사용 가능한 표준 라이브러리 -
|
||||
|
||||
math 라이브러리:
|
||||
@@ -629,18 +787,51 @@
|
||||
obj.getoption / obj.pixeloption을 지원합니다. 자세한 내용은
|
||||
"obj 테이블 - 함수"를 참조하세요.
|
||||
|
||||
○ obj.effect의 AviUtl / AviUtl2 호환 맵
|
||||
obj.effect("이펙트 이름", "파라미터 이름", 값, ...)은 먼저 호환 맵을
|
||||
참조합니다. AviUtl / AviUtl2의 이름으로 선언된 이펙트는 값이 선언된
|
||||
배율·오프셋 변환을 거쳐 YMM4의 속성에 반영됩니다. 맵에 선언되지 않은
|
||||
이름은 YMM4의 이펙트 이름이나 키워드로 그대로 해석되므로 기존 호출도
|
||||
그대로 동작합니다.
|
||||
이 맵은 YMM4 자체의 AviUtl 내보내기(.exo 출력)의 역으로 만들어졌기 때문에
|
||||
왕복해도 일치합니다. 대상 엔진은 --!aviutl(기본) / --!aviutl2로
|
||||
전환합니다.
|
||||
맵에 선언된 이펙트 이름과 주요 파라미터는 다음과 같습니다.
|
||||
ぼかし: 範囲, サイズ固定
|
||||
境界ぼかし: 範囲
|
||||
方向ブラー: 範囲, 角度, サイズ固定
|
||||
放射ブラー: 範囲, X, Y, サイズを固定
|
||||
閃光: 範囲, X, Y, サイズを固定
|
||||
クロマキー: 色相範囲, 境界補正
|
||||
クリッピング: 上, 下, 左, 右, 中心の位置を変更
|
||||
斜めクリッピング: 中心X, 中心Y, 角度, ぼかし, 幅
|
||||
領域拡張: 上, 下, 左, 右
|
||||
座標: X, Y, Z
|
||||
回転: X, Y, Z
|
||||
リサイズ: 拡大率, X, Y, 補間なし
|
||||
画像ループ: 横回数, 縦回数
|
||||
極座標変換: 中心幅, 渦巻
|
||||
グラデーション: 強さ, 中心X, 中心Y, 角度, 幅
|
||||
単色化: 強さ, 輝度を保持する
|
||||
縁取り: サイズ, ぼかし
|
||||
反転: -
|
||||
モザイク: サイズ
|
||||
ディスプレイスメントマップ: ぼかし
|
||||
動画ファイル合成: X, Y, 拡大率
|
||||
色調補正: 明るさ, コントラスト, 色相, 輝度, 彩度
|
||||
色ずれ: ずれ幅, 角度, 強さ
|
||||
色調補正 와 色ずれ 는 커뮤니티 플러그인의 이펙트에 대응합니다.
|
||||
|
||||
다음 기능은 이 호환 계층의 범위 밖입니다.
|
||||
이를 호출하는 스크립트는 의도대로 동작하지 않습니다.
|
||||
× require에 의한 모듈 로드 및 io / dofile 등의 임의 파일 접근
|
||||
(obj.load의 이미지 / 동영상 로드는 헤더 검증과 함께 지원).
|
||||
× obj.setanchor, scene.set / scene.get 등.
|
||||
× obj.setanchor 등.
|
||||
|
||||
|
||||
- 미지원·제한 사항 -
|
||||
|
||||
× AviUtl2의 obj.rand1(), obj.mes(), obj.setanchor() 등은 지원하지 않습니다.
|
||||
× AviUtl2의 scene 테이블의 scene.set(), scene.get() 등의 함수는 지원하지 않습니다.
|
||||
(scene.width와 scene.height의 읽기만 지원)
|
||||
× 스크립트에서의 임의 파일 접근(require, dofile, io 등)은 지원하지 않습니다.
|
||||
obj.load("image"/"movie")만 선두 헤더 검증으로 진짜 미디어로 확인된 파일을
|
||||
읽습니다.
|
||||
|
||||
@@ -2,7 +2,8 @@
|
||||
|
||||
YukkuriMovieMaker4 的"Lua 脚本"视频特效使用
|
||||
Lua 语言编写脚本。
|
||||
脚本引擎采用 MoonSharp(兼容 Lua 5.2)。
|
||||
脚本由随附的高速运行时(LuaJIT)执行,
|
||||
在其不可用的环境下改由 MoonSharp(兼容 Lua 5.2)执行。
|
||||
|
||||
* 本特效为独立实现,与 AviUtl2 的脚本规范不同。
|
||||
* 与 AviUtl2 的脚本文件(*.anm2 等)为不同规范。
|
||||
@@ -11,7 +12,7 @@
|
||||
|
||||
- 注意事项 -
|
||||
|
||||
○ 脚本执行引擎为 MoonSharp(兼容 Lua 5.2)。
|
||||
○ 脚本执行引擎为 LuaJIT(默认)与 MoonSharp(兼容 Lua 5.2)。
|
||||
○ 可用的标准库仅限以下内容:
|
||||
table, string, math, bit32
|
||||
* io、os、debug、ffi、require 等不可使用。
|
||||
@@ -26,14 +27,15 @@
|
||||
|
||||
- 执行引擎与自动加速 -
|
||||
|
||||
包含像素处理(getpixel/setpixel 双重循环)的脚本会被解析语法,
|
||||
并自动分配到更快的引擎。
|
||||
坐标、旋转、不透明度等普通脚本仍照旧由 MoonSharp 执行,行为不变。
|
||||
脚本会被解析语法,并自动分配到最合适的引擎。
|
||||
未指定指令的脚本由随附的高速运行时(LuaJIT)执行,
|
||||
自像素完结的像素映射会进一步转换为更快的 CPU 内核。
|
||||
两者的结果均与 MoonSharp 一致。
|
||||
|
||||
○ 自动分配(未指定指令时)
|
||||
· 自像素完结的像素映射(见下方条件)→ CPU 内核(高速、精确)
|
||||
· 上述以外的像素操作 → 原生(LuaJIT,仅在已部署时)
|
||||
· 无像素操作 → MoonSharp
|
||||
· 上述以外 → 原生(LuaJIT,仅在已部署时)
|
||||
· 未部署 native 或脚本为空 → MoonSharp
|
||||
|
||||
○ 引擎指定指令(脚本首行的注释)
|
||||
--!cpu :CPU 内核。运行时编译为表达式树,
|
||||
@@ -89,6 +91,32 @@
|
||||
自动显示在特效面板中(轨道条始终显示)。该通用用法不带范围・默认值声明,
|
||||
因此请在脚本内处理取值范围。AviUtl 的 --track / --check / --color 头声明显示仍可照常使用。
|
||||
|
||||
共有 4 个数值滑块,各值可通过 obj.slider0 ~ obj.slider3 引用。
|
||||
取值为整数,不处理小数。
|
||||
|
||||
Slider0 : 整数滑块 (范围: 1 ~ 10)
|
||||
Slider1 : 整数滑块 (范围: 0 ~ 100)
|
||||
Slider2 : 整数滑块 (范围: 0 ~ 1000)
|
||||
Slider3 : 整数滑块 (范围: -1000 ~ 1000)
|
||||
|
||||
还可使用字符串参数,各值通过以下名称引用。
|
||||
|
||||
obj.text : 文本输入框的字符串
|
||||
obj.font : 字体选择框的字体名
|
||||
obj.dir : 文件夹选择框的路径
|
||||
obj.file_video : 视频文件的路径
|
||||
obj.file_audio : 音频文件的路径
|
||||
obj.file_image : 图像文件的路径
|
||||
obj.file_project : 项目文件的路径
|
||||
obj.file_mp4 : MP4 文件的路径
|
||||
obj.file_exo : EXO 文件的路径
|
||||
obj.file_subtitle : 字幕文件的路径
|
||||
obj.file_shader : 着色器文件的路径
|
||||
|
||||
※滑块与字符串参数在脚本本体引用它们时会自动显示在特效面板中。
|
||||
※文件选择的路径可传给 obj.load 用于加载图像・视频。
|
||||
※这些参数在 MoonSharp 与原生两种引擎中均可引用。
|
||||
|
||||
|
||||
- 全局变量 -
|
||||
|
||||
@@ -119,6 +147,28 @@
|
||||
scene.width : 场景(项目)的水平分辨率(像素)[只读]
|
||||
scene.height : 场景(项目)的垂直分辨率(像素)[只读]
|
||||
|
||||
scene.set(name, value)
|
||||
将值保存到以场景为单位的共享区域。
|
||||
同一场景内的所有 Lua 脚本效果都可以跨项目、跨帧通过
|
||||
scene.get(name) 读取该值。
|
||||
name : 值的名称(字符串)
|
||||
value : 要保存的值(数值、字符串、布尔值)。传入 nil 时删除。
|
||||
* 数值、字符串、布尔值以外的类型(表、函数等)不会被保存。
|
||||
* 名称和字符串值按 UTF-8 计算超过 4095 字节的部分将被截断。
|
||||
例:scene.set("shared_x", obj.x)
|
||||
scene.get(name)
|
||||
获取通过 scene.set() 保存的值。未设置的名称返回 nil。
|
||||
例:local x = scene.get("shared_x") or 0
|
||||
* 自己的脚本写入的值,在同一次执行中可以立即通过 scene.get 读取。
|
||||
其他项目写入的值从下一帧的求值开始可见,因此同一帧内的结果不依赖
|
||||
项目的求值顺序。
|
||||
* 脚本因错误或超时而结束时,该次执行的写入不会反映到共享区域。
|
||||
* 开始视频输出时,共享区域从空状态开始,因此输出同一项目时每次都会
|
||||
得到相同的结果。
|
||||
* 每个场景最多可保存 4096 个名称。超过上限的新名称写入将被忽略。
|
||||
* 值按场景相互独立,在 YMM4 退出前一直保留在内存中。
|
||||
不会保存到项目文件。
|
||||
|
||||
|
||||
- obj 表 - 变量 -
|
||||
|
||||
@@ -209,6 +259,18 @@
|
||||
obj.track2 : 特效面板 Track2 的当前值 [只读]
|
||||
obj.track3 : 特效面板 Track3 的当前值 [只读]
|
||||
|
||||
○ 滑块
|
||||
obj.slider0 : 特效面板 Slider0 的当前值(整数) [只读]
|
||||
obj.slider1 : 特效面板 Slider1 的当前值(整数) [只读]
|
||||
obj.slider2 : 特效面板 Slider2 的当前值(整数) [只读]
|
||||
obj.slider3 : 特效面板 Slider3 的当前值(整数) [只读]
|
||||
|
||||
○ 字符串参数
|
||||
obj.text : 文本输入框的字符串 [只读]
|
||||
obj.font : 字体选择框的字体名 [只读]
|
||||
obj.dir : 文件夹选择框的路径 [只读]
|
||||
obj.file_video ~ obj.file_shader : 各文件选择框的路径 [只读]
|
||||
|
||||
○ 图层
|
||||
obj.layer : 对象所在的图层编号 [只读]
|
||||
* 与全局变量 layer 的值相同。
|
||||
@@ -439,10 +501,51 @@
|
||||
(getoption 返回设置值,未设置为 0)。
|
||||
当前会反映到绘制的项目:
|
||||
"antialias" : 0 为最近邻,其它为线性插值(obj.draw / obj.drawpoly)。
|
||||
"blend" : 合成模式编号(obj.draw / obj.drawpoly)。与 YMM4 属性
|
||||
面板中「合成模式」下拉列表相同的顺序(从 0 开始):
|
||||
0=普通,1=溶解,2=对比(暗),3=相乘,4=颜色加深,5=线性加深,
|
||||
6=对比(明),7=画面,8=颜色减淡,9=线性减淡 (相加),10=相加,
|
||||
11=覆盖,12=柔光,13=强光,14=亮光,15=明暗,16=点光,17=实色混合,
|
||||
18=反差,19=排除,20=相减,21=相除,22=色相,23=饱和度,24=颜色,
|
||||
25=亮度,26=颜色对比(明),27=背景,28=颜色对比(暗),29=清除,
|
||||
30=按背景裁剪,31=异或,32=颜色反转遮罩。超出范围或无效的值
|
||||
将按 0(普通)处理。
|
||||
"draw_state" : 用布尔值决定该效果是否输出工作图像。true 输出
|
||||
工作图像,false 则原样传递输入。可用于不使用 obj.draw 或
|
||||
setpixel 也输出工作图像,或反过来抑制输出。两个引擎都可用。
|
||||
"drawtarget" : 切换 obj.draw / obj.drawpoly 的绘制目标。
|
||||
"framebuffer"(默认)合成到帧缓冲。"tempbuffer" 则就地合成到
|
||||
工作用 tmp 缓冲。obj.setoption("drawtarget", "tempbuffer", w, h)
|
||||
中的 w, h 是初始化 tmp 缓冲的尺寸,省略则不初始化。画到 tmp 的
|
||||
结果可用 obj.copybuffer("obj", "tmp") 取回工作图像。合成到
|
||||
tempbuffer 使用普通(源覆盖),blend 应用于 framebuffer 的绘制。
|
||||
两个引擎都可用。在 MoonSharp 中,合成到 tempbuffer 在 GPU 上
|
||||
执行,GPU 不可用时会自动切换到 CPU 合成。由于舍入方式不同,
|
||||
合成结果在引擎之间可能存在极小差异。
|
||||
|
||||
○ obj.pixeloption(名称, 值)
|
||||
将像素操作的选项作为状态保存。
|
||||
|
||||
○ obj.setanchor(名称, 个数 [, 选项, ..])
|
||||
在预览上显示锚点,可用鼠标拖动调整坐标。调整后的坐标会随工程保存。
|
||||
名称 : 以字符串指定接收坐标的 Lua 变量名。变量排列为
|
||||
pos={x0,y0,x1,y1,…},指定 "xyz" 时为 {x0,y0,z0,x1,y1,z1,…}。
|
||||
坐标以对象中心为原点。
|
||||
个数 : 指定锚点数量。最多 32 个。
|
||||
选项 : 可用字符串列举。
|
||||
"line" : 用线连接锚点。
|
||||
"loop" : 用线连接锚点并闭合一圈。
|
||||
"star" : 将每个锚点与对象中心用线连接。
|
||||
"arm" : 从对象中心依次连接到各锚点。
|
||||
"xyz" : 以 3D 坐标处理锚点。默认是 2D。
|
||||
返回设置的锚点数量。两个引擎都可用。
|
||||
名称指定 "track" 的轨道条联动暂不支持,返回 0。
|
||||
示例:
|
||||
num = obj.track0
|
||||
obj.setanchor("pos", num, "loop")
|
||||
for i = 0, num - 1 do
|
||||
obj.draw(pos[i * 2 + 1], pos[i * 2 + 2])
|
||||
end
|
||||
|
||||
|
||||
- ymm4 表 -
|
||||
@@ -504,6 +607,47 @@
|
||||
anim.bezier(t, p0, p1, p2, p3): 计算 t(0.0~1.0) 时的三次贝塞尔曲线值
|
||||
|
||||
|
||||
- AviUtl 兼容的全局函数 -
|
||||
|
||||
以下函数可在全局作用域中直接调用。
|
||||
在所有执行引擎(MoonSharp / 原生)上返回完全相同的结果。
|
||||
|
||||
RGB(r, g, b)
|
||||
RGB(col)
|
||||
RGB(r1, g1, b1, r2, g2, b2)
|
||||
在颜色信息(0x000000~0xffffff)与红、绿、蓝(各 0~255)之间相互
|
||||
转换。3 个参数时合成为一个颜色信息,1 个参数时分解为 r, g, b 三个值。
|
||||
6 个参数时,返回随对象时间经过(obj.time / obj.totaltime)从第一种
|
||||
颜色向第二种颜色线性变化的颜色信息。
|
||||
例:col = RGB(64, 192, 255) -- 0x40C0FF
|
||||
例:r, g, b = RGB(0x0080FF) -- 0, 128, 255
|
||||
例:col = RGB(64,192,255, 128,64,0) -- 起始色→结束色
|
||||
|
||||
HSV(h, s, v)
|
||||
HSV(col)
|
||||
HSV(h1, s1, v1, h2, s2, v2)
|
||||
在颜色信息(0x000000~0xffffff)与色相(0~360)、饱和度(0~100)、
|
||||
明度(0~100)之间相互转换。参数含义与 RGB() 相同。
|
||||
例:col = HSV(60, 100, 100) -- 0xFFFF00
|
||||
例:h, s, v = HSV(0x0080FF) -- 210, 100, 100
|
||||
|
||||
OR(a, b) / AND(a, b) / XOR(a, b)
|
||||
以 32bit 整数进行位运算(或、与、异或)。
|
||||
小数转换为整数时,恰好 0.5 及以下会被舍去(2.50→2、2.51→3)。
|
||||
例:result = OR(8, 3) -- 11
|
||||
|
||||
SHIFT(a, shift)
|
||||
进行算术移位。shift 为正数时左移,为负数时右移。
|
||||
例:result = SHIFT(5, 3) -- 40
|
||||
例:result = SHIFT(91, -2) -- 22
|
||||
|
||||
debug_print(text)
|
||||
将指定字符串发送到 OutputDebugString()。用于调试。
|
||||
可通过 DebugView 等调试监视工具查看消息。
|
||||
此外,脚本发生执行错误时会自动发送错误消息。
|
||||
例:debug_print(string.format("x = %d", obj.x))
|
||||
|
||||
|
||||
- 可用标准库 -
|
||||
|
||||
math 库:
|
||||
@@ -616,18 +760,49 @@
|
||||
obj.effect、obj.getvalue 以及 obj.setoption / obj.getoption /
|
||||
obj.pixeloption。详情请参阅“obj 表 - 函数”。
|
||||
|
||||
○ obj.effect 的 AviUtl / AviUtl2 兼容映射
|
||||
obj.effect("效果名", "参数名", 值, ...) 会先查阅兼容映射。
|
||||
以 AviUtl / AviUtl2 名称声明的效果,数值会经过声明的倍率/偏移转换后再写入
|
||||
YMM4 的属性。映射中未声明的名称则按 YMM4 的效果名或关键字直接解析,
|
||||
因此既有调用仍可正常使用。该映射是按 YMM4 自身的 AviUtl 导出
|
||||
(.exo 输出) 的逆向构建的,因此往返一致。目标引擎通过 --!aviutl(默认) /
|
||||
--!aviutl2 切换。
|
||||
映射中声明的效果名及其主要参数如下。
|
||||
ぼかし: 範囲, サイズ固定
|
||||
境界ぼかし: 範囲
|
||||
方向ブラー: 範囲, 角度, サイズ固定
|
||||
放射ブラー: 範囲, X, Y, サイズを固定
|
||||
閃光: 範囲, X, Y, サイズを固定
|
||||
クロマキー: 色相範囲, 境界補正
|
||||
クリッピング: 上, 下, 左, 右, 中心の位置を変更
|
||||
斜めクリッピング: 中心X, 中心Y, 角度, ぼかし, 幅
|
||||
領域拡張: 上, 下, 左, 右
|
||||
座標: X, Y, Z
|
||||
回転: X, Y, Z
|
||||
リサイズ: 拡大率, X, Y, 補間なし
|
||||
画像ループ: 横回数, 縦回数
|
||||
極座標変換: 中心幅, 渦巻
|
||||
グラデーション: 強さ, 中心X, 中心Y, 角度, 幅
|
||||
単色化: 強さ, 輝度を保持する
|
||||
縁取り: サイズ, ぼかし
|
||||
反転: -
|
||||
モザイク: サイズ
|
||||
ディスプレイスメントマップ: ぼかし
|
||||
動画ファイル合成: X, Y, 拡大率
|
||||
色調補正: 明るさ, コントラスト, 色相, 輝度, 彩度
|
||||
色ずれ: ずれ幅, 角度, 強さ
|
||||
色調補正 与 色ずれ 对应社区插件的效果。
|
||||
|
||||
以下功能不在此兼容层的范围内。
|
||||
调用它们的脚本不会按预期运行。
|
||||
× 通过 require 加载模块,以及 io / dofile 等任意文件访问
|
||||
(obj.load 的图像 / 视频加载已带文件头校验支持)。
|
||||
× obj.setanchor、scene.set / scene.get 等。
|
||||
× obj.setanchor 等。
|
||||
|
||||
|
||||
- 不支持项目·限制事项 -
|
||||
|
||||
× 不支持 AviUtl2 的 obj.rand1()、obj.mes()、obj.setanchor() 等。
|
||||
× 不支持 AviUtl2 scene 表中的 scene.set()、scene.get() 等函数。
|
||||
(仅支持读取 scene.width 和 scene.height)
|
||||
× 不支持脚本进行任意文件访问(require、dofile、io 等)。
|
||||
仅 obj.load("image"/"movie") 会加载经文件头校验确认为真正媒体的文件。
|
||||
× 修改 obj.z 会反映到绘制中(包含在 ReadBack 中),
|
||||
|
||||
@@ -2,7 +2,8 @@
|
||||
|
||||
YukkuriMovieMaker4 的「Lua 腳本」視訊特效使用
|
||||
Lua 語言編寫腳本。
|
||||
腳本引擎採用 MoonSharp(相容 Lua 5.2)。
|
||||
腳本由隨附的高速執行環境(LuaJIT)執行,
|
||||
在其不可用的環境下改由 MoonSharp(相容 Lua 5.2)執行。
|
||||
|
||||
* 本特效為獨立實作,與 AviUtl2 的腳本規範不同。
|
||||
* 與 AviUtl2 的腳本檔案(*.anm2 等)為不同規範。
|
||||
@@ -11,7 +12,7 @@
|
||||
|
||||
- 注意事項 -
|
||||
|
||||
○ 腳本執行引擎為 MoonSharp(相容 Lua 5.2)。
|
||||
○ 腳本執行引擎為 LuaJIT(預設)與 MoonSharp(相容 Lua 5.2)。
|
||||
○ 可用的標準函式庫僅限以下內容:
|
||||
table, string, math, bit32
|
||||
* io、os、debug、ffi、require 等不可使用。
|
||||
@@ -26,14 +27,15 @@
|
||||
|
||||
- 執行引擎與自動加速 -
|
||||
|
||||
包含像素處理(getpixel/setpixel 雙重迴圈)的腳本會被解析語法,
|
||||
並自動分配到更快的引擎。
|
||||
座標、旋轉、不透明度等一般腳本仍照舊由 MoonSharp 執行,行為不變。
|
||||
腳本會被解析語法,並自動分配到最合適的引擎。
|
||||
未指定指令的腳本由隨附的高速執行環境(LuaJIT)執行,
|
||||
自像素完結的像素映射會進一步轉換為更快的 CPU 核心。
|
||||
兩者的結果均與 MoonSharp 一致。
|
||||
|
||||
○ 自動分配(未指定指令時)
|
||||
· 自像素完結的像素映射(見下方條件)→ CPU 核心(高速、精確)
|
||||
· 上述以外的像素操作 → 原生(LuaJIT,僅在已部署時)
|
||||
· 無像素操作 → MoonSharp
|
||||
· 上述以外 → 原生(LuaJIT,僅在已部署時)
|
||||
· 未部署 native 或腳本為空 → MoonSharp
|
||||
|
||||
○ 引擎指定指令(腳本首行的註解)
|
||||
--!cpu :CPU 核心。執行時編譯為運算式樹,
|
||||
@@ -89,6 +91,32 @@
|
||||
自動顯示於特效面板中(軌道條始終顯示)。此通用用法不帶範圍・預設值宣告,
|
||||
因此請在腳本內處理取值範圍。AviUtl 的 --track / --check / --color 標頭宣告顯示仍可照常使用。
|
||||
|
||||
共有 4 個數值滑桿,各值可透過 obj.slider0 ~ obj.slider3 參照。
|
||||
取值為整數,不處理小數。
|
||||
|
||||
Slider0 : 整數滑桿 (範圍: 1 ~ 10)
|
||||
Slider1 : 整數滑桿 (範圍: 0 ~ 100)
|
||||
Slider2 : 整數滑桿 (範圍: 0 ~ 1000)
|
||||
Slider3 : 整數滑桿 (範圍: -1000 ~ 1000)
|
||||
|
||||
亦可使用字串參數,各值透過以下名稱參照。
|
||||
|
||||
obj.text : 文字輸入框的字串
|
||||
obj.font : 字型選擇框的字型名
|
||||
obj.dir : 資料夾選擇框的路徑
|
||||
obj.file_video : 影片檔案的路徑
|
||||
obj.file_audio : 音訊檔案的路徑
|
||||
obj.file_image : 圖片檔案的路徑
|
||||
obj.file_project : 專案檔案的路徑
|
||||
obj.file_mp4 : MP4 檔案的路徑
|
||||
obj.file_exo : EXO 檔案的路徑
|
||||
obj.file_subtitle : 字幕檔案的路徑
|
||||
obj.file_shader : 著色器檔案的路徑
|
||||
|
||||
※滑桿與字串參數在腳本本體參照它們時會自動顯示於特效面板中。
|
||||
※檔案選擇的路徑可傳給 obj.load 用於載入圖片・影片。
|
||||
※這些參數在 MoonSharp 與原生兩種引擎中皆可參照。
|
||||
|
||||
|
||||
- 全域變數 -
|
||||
|
||||
@@ -119,6 +147,28 @@
|
||||
scene.width : 場景(專案)的水平解析度(像素)[唯讀]
|
||||
scene.height : 場景(專案)的垂直解析度(像素)[唯讀]
|
||||
|
||||
scene.set(name, value)
|
||||
將值儲存到以場景為單位的共享區域。
|
||||
同一場景內的所有 Lua 腳本效果都可以跨項目、跨影格透過
|
||||
scene.get(name) 讀取該值。
|
||||
name : 值的名稱(字串)
|
||||
value : 要儲存的值(數值、字串、布林值)。傳入 nil 時刪除。
|
||||
* 數值、字串、布林值以外的型別(表、函式等)不會被儲存。
|
||||
* 名稱和字串值按 UTF-8 計算超過 4095 位元組的部分將被截斷。
|
||||
例:scene.set("shared_x", obj.x)
|
||||
scene.get(name)
|
||||
取得透過 scene.set() 儲存的值。未設定的名稱回傳 nil。
|
||||
例:local x = scene.get("shared_x") or 0
|
||||
* 自己的腳本寫入的值,在同一次執行中可以立即透過 scene.get 讀取。
|
||||
其他項目寫入的值從下一影格的求值開始可見,因此同一影格內的結果不
|
||||
依賴項目的求值順序。
|
||||
* 腳本因錯誤或逾時而結束時,該次執行的寫入不會反映到共享區域。
|
||||
* 開始影片輸出時,共享區域從空狀態開始,因此輸出同一專案時每次都會
|
||||
得到相同的結果。
|
||||
* 每個場景最多可儲存 4096 個名稱。超過上限的新名稱寫入將被忽略。
|
||||
* 值按場景相互獨立,在 YMM4 結束前一直保留在記憶體中。
|
||||
不會儲存到專案檔。
|
||||
|
||||
|
||||
- obj 表 - 變數 -
|
||||
|
||||
@@ -209,6 +259,18 @@
|
||||
obj.track2 : 特效面板 Track2 的當前值 [唯讀]
|
||||
obj.track3 : 特效面板 Track3 的當前值 [唯讀]
|
||||
|
||||
○ 滑桿
|
||||
obj.slider0 : 特效面板 Slider0 的當前值(整數) [唯讀]
|
||||
obj.slider1 : 特效面板 Slider1 的當前值(整數) [唯讀]
|
||||
obj.slider2 : 特效面板 Slider2 的當前值(整數) [唯讀]
|
||||
obj.slider3 : 特效面板 Slider3 的當前值(整數) [唯讀]
|
||||
|
||||
○ 字串參數
|
||||
obj.text : 文字輸入框的字串 [唯讀]
|
||||
obj.font : 字型選擇框的字型名 [唯讀]
|
||||
obj.dir : 資料夾選擇框的路徑 [唯讀]
|
||||
obj.file_video ~ obj.file_shader : 各檔案選擇框的路徑 [唯讀]
|
||||
|
||||
○ 圖層
|
||||
obj.layer : 物件所在的圖層編號 [唯讀]
|
||||
* 與全域變數 layer 的值相同。
|
||||
@@ -439,10 +501,52 @@
|
||||
(getoption 回傳設定值,未設定為 0)。
|
||||
目前會反映到繪製的項目:
|
||||
"antialias" : 0 為最近鄰,其它為線性內插(obj.draw / obj.drawpoly)。
|
||||
"blend" : 合成模式編號(obj.draw / obj.drawpoly)。與 YMM4 屬性
|
||||
面板中「合成模式」下拉選單相同的順序(從 0 開始):
|
||||
0=一般,1=Dissolve,2=比較(暗),3=相乘,4=Color burn,5=陰影,
|
||||
6=比較(亮),7=畫面,8=Color dodge,9=Linear dodge (Add),
|
||||
10=相加,11=覆蓋,12=Soft light,13=Hard light,14=Vivid light,
|
||||
15=明暗,16=Pin light,17=Hard mix,18=差異,19=Exclution,
|
||||
20=相減,21=Division,22=Hue,23=Saturation,24=色,25=亮度,
|
||||
26=Lighter color,27=Behind,28=Darker color,29=Clear,
|
||||
30=Clipping by background,31=XOR,32=Color inversion mask。
|
||||
超出範圍或無效的值將視為 0(一般)。
|
||||
"draw_state" : 以布林值決定此效果是否輸出工作影像。true 輸出
|
||||
工作影像,false 則原樣傳遞輸入。可用於不使用 obj.draw 或
|
||||
setpixel 也輸出工作影像,或反過來抑制輸出。兩個引擎都可用。
|
||||
"drawtarget" : 切換 obj.draw / obj.drawpoly 的繪製目標。
|
||||
"framebuffer"(預設)合成到影格緩衝。"tempbuffer" 則就地合成到
|
||||
工作用 tmp 緩衝。obj.setoption("drawtarget", "tempbuffer", w, h)
|
||||
中的 w, h 是初始化 tmp 緩衝的尺寸,省略則不初始化。畫到 tmp 的
|
||||
結果可用 obj.copybuffer("obj", "tmp") 取回工作影像。合成到
|
||||
tempbuffer 使用一般(來源覆蓋),blend 套用於 framebuffer 的繪製。
|
||||
兩個引擎都可用。在 MoonSharp 中,合成到 tempbuffer 在 GPU 上
|
||||
執行,GPU 無法使用時會自動切換到 CPU 合成。由於捨入方式不同,
|
||||
合成結果在引擎之間可能存在極小差異。
|
||||
|
||||
○ obj.pixeloption(名稱, 值)
|
||||
將像素操作的選項作為狀態保存。
|
||||
|
||||
○ obj.setanchor(名稱, 個數 [, 選項, ..])
|
||||
在預覽上顯示錨點,可用滑鼠拖曳調整座標。調整後的座標會隨專案保存。
|
||||
名稱 : 以字串指定接收座標的 Lua 變數名。變數排列為
|
||||
pos={x0,y0,x1,y1,…},指定 "xyz" 時為 {x0,y0,z0,x1,y1,z1,…}。
|
||||
座標以物件中心為原點。
|
||||
個數 : 指定錨點數量。最多 32 個。
|
||||
選項 : 可用字串列舉。
|
||||
"line" : 用線連接錨點。
|
||||
"loop" : 用線連接錨點並閉合一圈。
|
||||
"star" : 將每個錨點與物件中心用線連接。
|
||||
"arm" : 從物件中心依序連接到各錨點。
|
||||
"xyz" : 以 3D 座標處理錨點。預設是 2D。
|
||||
回傳設置的錨點數量。兩個引擎都可用。
|
||||
名稱指定 "track" 的軌道條連動暫不支援,回傳 0。
|
||||
範例:
|
||||
num = obj.track0
|
||||
obj.setanchor("pos", num, "loop")
|
||||
for i = 0, num - 1 do
|
||||
obj.draw(pos[i * 2 + 1], pos[i * 2 + 2])
|
||||
end
|
||||
|
||||
|
||||
- ymm4 表 -
|
||||
@@ -504,6 +608,47 @@
|
||||
anim.bezier(t, p0, p1, p2, p3): 計算 t(0.0~1.0) 時的三次貝茲曲線值
|
||||
|
||||
|
||||
- AviUtl 相容的全域函式 -
|
||||
|
||||
以下函式可在全域範圍中直接呼叫。
|
||||
在所有執行引擎(MoonSharp / 原生)上回傳完全相同的結果。
|
||||
|
||||
RGB(r, g, b)
|
||||
RGB(col)
|
||||
RGB(r1, g1, b1, r2, g2, b2)
|
||||
在顏色資訊(0x000000~0xffffff)與紅、綠、藍(各 0~255)之間相互
|
||||
轉換。3 個引數時合成為一個顏色資訊,1 個引數時分解為 r, g, b 三個值。
|
||||
6 個引數時,回傳隨物件時間經過(obj.time / obj.totaltime)從第一種
|
||||
顏色向第二種顏色線性變化的顏色資訊。
|
||||
例:col = RGB(64, 192, 255) -- 0x40C0FF
|
||||
例:r, g, b = RGB(0x0080FF) -- 0, 128, 255
|
||||
例:col = RGB(64,192,255, 128,64,0) -- 起始色→結束色
|
||||
|
||||
HSV(h, s, v)
|
||||
HSV(col)
|
||||
HSV(h1, s1, v1, h2, s2, v2)
|
||||
在顏色資訊(0x000000~0xffffff)與色相(0~360)、飽和度(0~100)、
|
||||
明度(0~100)之間相互轉換。引數含義與 RGB() 相同。
|
||||
例:col = HSV(60, 100, 100) -- 0xFFFF00
|
||||
例:h, s, v = HSV(0x0080FF) -- 210, 100, 100
|
||||
|
||||
OR(a, b) / AND(a, b) / XOR(a, b)
|
||||
以 32bit 整數進行位元運算(或、與、互斥或)。
|
||||
小數轉換為整數時,恰好 0.5 及以下會被捨去(2.50→2、2.51→3)。
|
||||
例:result = OR(8, 3) -- 11
|
||||
|
||||
SHIFT(a, shift)
|
||||
進行算術移位。shift 為正數時左移,為負數時右移。
|
||||
例:result = SHIFT(5, 3) -- 40
|
||||
例:result = SHIFT(91, -2) -- 22
|
||||
|
||||
debug_print(text)
|
||||
將指定字串傳送到 OutputDebugString()。用於除錯。
|
||||
可透過 DebugView 等除錯監視工具查看訊息。
|
||||
此外,腳本發生執行錯誤時會自動傳送錯誤訊息。
|
||||
例:debug_print(string.format("x = %d", obj.x))
|
||||
|
||||
|
||||
- 可用標準函式庫 -
|
||||
|
||||
math 函式庫:
|
||||
@@ -616,18 +761,49 @@
|
||||
obj.effect、obj.getvalue 以及 obj.setoption / obj.getoption /
|
||||
obj.pixeloption。詳情請參閱「obj 表 - 函式」。
|
||||
|
||||
○ obj.effect 的 AviUtl / AviUtl2 相容對應表
|
||||
obj.effect("效果名", "參數名", 值, ...) 會先查閱相容對應表。
|
||||
以 AviUtl / AviUtl2 名稱宣告的效果,數值會經過宣告的倍率/位移轉換後再寫入
|
||||
YMM4 的屬性。對應表中未宣告的名稱則依 YMM4 的效果名或關鍵字直接解析,
|
||||
因此既有呼叫仍可正常使用。此對應表是依 YMM4 自身的 AviUtl 匯出
|
||||
(.exo 輸出) 的逆向建構的,因此往返一致。目標引擎透過 --!aviutl(預設) /
|
||||
--!aviutl2 切換。
|
||||
對應表中宣告的效果名及其主要參數如下。
|
||||
ぼかし: 範囲, サイズ固定
|
||||
境界ぼかし: 範囲
|
||||
方向ブラー: 範囲, 角度, サイズ固定
|
||||
放射ブラー: 範囲, X, Y, サイズを固定
|
||||
閃光: 範囲, X, Y, サイズを固定
|
||||
クロマキー: 色相範囲, 境界補正
|
||||
クリッピング: 上, 下, 左, 右, 中心の位置を変更
|
||||
斜めクリッピング: 中心X, 中心Y, 角度, ぼかし, 幅
|
||||
領域拡張: 上, 下, 左, 右
|
||||
座標: X, Y, Z
|
||||
回転: X, Y, Z
|
||||
リサイズ: 拡大率, X, Y, 補間なし
|
||||
画像ループ: 横回数, 縦回数
|
||||
極座標変換: 中心幅, 渦巻
|
||||
グラデーション: 強さ, 中心X, 中心Y, 角度, 幅
|
||||
単色化: 強さ, 輝度を保持する
|
||||
縁取り: サイズ, ぼかし
|
||||
反転: -
|
||||
モザイク: サイズ
|
||||
ディスプレイスメントマップ: ぼかし
|
||||
動画ファイル合成: X, Y, 拡大率
|
||||
色調補正: 明るさ, コントラスト, 色相, 輝度, 彩度
|
||||
色ずれ: ずれ幅, 角度, 強さ
|
||||
色調補正 與 色ずれ 對應社群外掛的效果。
|
||||
|
||||
以下功能不在此相容層的範圍內。
|
||||
呼叫它們的腳本不會如預期運作。
|
||||
× 透過 require 載入模組,以及 io / dofile 等任意檔案存取
|
||||
(obj.load 的影像 / 影片載入已附檔頭驗證支援)。
|
||||
× obj.setanchor、scene.set / scene.get 等。
|
||||
× obj.setanchor 等。
|
||||
|
||||
|
||||
- 不支援項目·限制事項 -
|
||||
|
||||
× 不支援 AviUtl2 的 obj.rand1()、obj.mes()、obj.setanchor() 等。
|
||||
× 不支援 AviUtl2 scene 表中的 scene.set()、scene.get() 等函式。
|
||||
(僅支援讀取 scene.width 和 scene.height)
|
||||
× 不支援腳本進行任意檔案存取(require、dofile、io 等)。
|
||||
僅 obj.load("image"/"movie") 會載入經檔頭驗證確認為真正媒體的檔案。
|
||||
× 修改 obj.z 會反映至繪製中(包含在 ReadBack 中),
|
||||
|
||||
@@ -7,7 +7,7 @@
|
||||
---
|
||||
|
||||
YukkuriMovieMaker4(YMM4)上で動作する、**Luaスクリプトでオブジェクトの座標・拡縮・回転・不透明度・ピクセルを直接制御できる映像エフェクトプラグイン**です。
|
||||
スクリプトエンジンには MoonSharp(Lua 5.2 互換)が採用されており、`obj.x` や `obj.alpha` といった変数をスクリプトから書き換えることで、AviUtl のスクリプト制御に近い感覚でアニメーションを組み立てられます。
|
||||
スクリプトは同梱の高速ランタイム(LuaJIT)で実行され、`obj.x` や `obj.alpha` といった変数をスクリプトから書き換えることで、AviUtl のスクリプト制御に近い感覚でアニメーションを組み立てられます。高速ランタイムを利用できない環境では MoonSharp(Lua 5.2 互換)で実行されます。
|
||||
|
||||
座標・拡縮・回転・不透明度の制御に加えて、`obj.getpixel` / `obj.setpixel` / `obj.getpixeldata` によるピクセル単位の画像加工、アニメーション制作向けの数学ユーティリティ群(`anim` テーブル)、4 系統のトラックバー(Track0〜Track3)によるスクリプトへのパラメータ受け渡しに対応しています。
|
||||
|
||||
@@ -46,7 +46,7 @@ YukkuriMovieMaker4(YMM4)上で動作する、**Luaスクリプトでオブ
|
||||
|
||||
本プラグインは YMM4 の「映像エフェクト」として動作し、エフェクトの種類一覧では「Luaスクリプト」として表示されます。
|
||||
|
||||
内部的には MoonSharp(Lua 5.2 互換のスクリプトエンジン)を組み込んでおり、ユーザーが記述した Lua スクリプトをフレームごとに実行します。スクリプト内で `obj.x` や `obj.alpha` といったグローバル変数を書き換えると、その値がオブジェクトの座標・拡縮・回転・不透明度として描画に反映されます。
|
||||
内部的には高速ランタイム(LuaJIT)と MoonSharp(Lua 5.2 互換のスクリプトエンジン)を組み込んでおり、ユーザーが記述した Lua スクリプトをフレームごとに実行します。スクリプト内で `obj.x` や `obj.alpha` といったグローバル変数を書き換えると、その値がオブジェクトの座標・拡縮・回転・不透明度として描画に反映されます。
|
||||
|
||||
このエフェクトは独自のスクリプト実行系を基盤としつつ、AviUtl のアニメーション効果スクリプト(`.anm` 系)の一部に対する互換層を備えています(詳細は[AviUtl スクリプトの部分互換](#9-aviutl-スクリプトの部分互換)を参照)。AviUtl 向けの EXO 出力(`.exo`)には対応していません。
|
||||
|
||||
@@ -60,7 +60,7 @@ YukkuriMovieMaker4(YMM4)上で動作する、**Luaスクリプトでオブ
|
||||
| YukkuriMovieMaker4 | 最新版を推奨 |
|
||||
| ランタイム | .NET 10.0 |
|
||||
|
||||
※ スクリプトエンジン(MoonSharp)はプラグインに同梱されており、別途インストールする必要はありません。
|
||||
※ スクリプトエンジン(LuaJIT・MoonSharp)はプラグインに同梱されており、別途インストールする必要はありません。
|
||||
|
||||
---
|
||||
|
||||
@@ -76,7 +76,7 @@ YukkuriMovieMaker4(YMM4)上で動作する、**Luaスクリプトでオブ
|
||||
|
||||
### 1. スクリプトエンジン
|
||||
|
||||
スクリプトの実行エンジンには MoonSharp(Lua 5.2 互換)を使用しています。加えて、自ピクセル完結のピクセル写像(`obj.getpixel` で読み取り `obj.setpixel` で書き戻す二重ループ)は構文解析で検出して **CPU カーネル(式ツリー)** または **GPU カーネル(Direct2D ピクセルシェーダ)** へ実行時コンパイルして高速化し、それ以外のピクセル操作を含むスクリプトは同梱の高速ランタイム(**LuaJIT**)で自動実行されます(詳細は[実行エンジンの自動振り分け](#実行エンジンの自動振り分け)を参照)。いずれのエンジンでも利用可能な標準ライブラリは以下に限定されています。
|
||||
スクリプトの実行エンジンには、同梱の高速ランタイム(**LuaJIT**)と MoonSharp(Lua 5.2 互換)を使用しています。ディレクティブを書いていないスクリプトは LuaJIT で実行され、自ピクセル完結のピクセル写像(`obj.getpixel` で読み取り `obj.setpixel` で書き戻す二重ループ)は構文解析で検出して **CPU カーネル(式ツリー)** へ実行時コンパイルしてさらに高速化されます。`native` フォルダが配備されていない環境と空のスクリプトは MoonSharp で実行されます(詳細は[実行エンジンの自動振り分け](#実行エンジンの自動振り分け)を参照)。いずれのエンジンでも利用可能な標準ライブラリは以下に限定されています。
|
||||
|
||||
- `table`、`string`、`math`、`bit32`
|
||||
- 基本関数: `type`、`tostring`、`tonumber`、`select`、`error`、`assert`、`print`、`ipairs`、`pairs`、`next`、`unpack`、`setmetatable`、`getmetatable`、`rawget`、`rawset`、`rawequal`、`rawlen`、`pcall`、`xpcall`
|
||||
@@ -98,6 +98,9 @@ YukkuriMovieMaker4(YMM4)上で動作する、**Luaスクリプトでオブ
|
||||
| `obj.rxr`, `obj.ryr`, `obj.rzr` | 変更可 | 回転角(ラジアン)。同名の度数版より優先して反映される |
|
||||
| `obj.w`, `obj.h`, `obj.hw`, `obj.hh`, `obj.cx`, `obj.cy`, `obj.cz`, `obj.diagonal` | 読み取り専用 | 入力画像のサイズ・中心座標・対角線長 |
|
||||
| `obj.track0`〜`obj.track3` | 読み取り専用 | トラックバーの現在値(後述) |
|
||||
| `obj.slider0`〜`obj.slider3` | 読み取り専用 | 整数スライダーの現在値(後述) |
|
||||
| `obj.text`, `obj.font`, `obj.dir` | 読み取り専用 | テキスト入力欄の文字列、フォント名、フォルダパス(後述) |
|
||||
| `obj.file_video`〜`obj.file_shader` | 読み取り専用 | 各ファイル選択欄のパス(後述) |
|
||||
| `obj.time`, `obj.frame`, `obj.totalframe`, `obj.totaltime`, `obj.t`, `obj.framerate`, `obj.layer`, `obj.index`, `obj.num` | 読み取り専用 | 時間・フレーム・レイヤー等の情報 |
|
||||
|
||||
### 3. ピクセル操作機能
|
||||
@@ -110,16 +113,20 @@ YukkuriMovieMaker4(YMM4)上で動作する、**Luaスクリプトでオブ
|
||||
- **`obj.putpixeldata()`**: 互換性のために定義された空実装関数です。`setpixel` / `PixelDataProxy:set` による変更は自動的に反映されるため、呼び出す必要はありません。
|
||||
`getpixel` / `setpixel` / `getpixeldata` のいずれかを最初に呼び出した時点で、GPU 上の画像データを CPU 側へ転送する処理が一度だけ発生します。ピクセル操作を行わないスクリプトではこの転送は発生しません。
|
||||
|
||||
これらのピクセル操作を含むスクリプトは自動的に高速化されます。自ピクセル完結のピクセル写像は CPU カーネル(式ツリー)または GPU カーネル(Direct2D ピクセルシェーダ)へ、それ以外は高速ランタイム(LuaJIT)へ自動で振り分けられ、いずれも従来エンジンに比べて大幅(内部計測で数十倍)に高速化されます。CPU カーネルと LuaJIT の出力結果は従来エンジンと一致します(GPU カーネルのみ float32 精度のためごく僅かに異なり得ます)。詳細・制約は[実行エンジンの自動振り分け](#実行エンジンの自動振り分け)を参照してください。
|
||||
これらのピクセル操作を含むスクリプトは自動的に高速化されます。自ピクセル完結のピクセル写像は CPU カーネル(式ツリー)へ、それ以外は高速ランタイム(LuaJIT)へ自動で振り分けられ、いずれも MoonSharp に比べて大幅(内部計測で数十倍)に高速化されます。CPU カーネルと LuaJIT の出力結果は MoonSharp と一致します(明示指定のみで使われる GPU カーネルは float32 精度のためごく僅かに異なり得ます)。詳細・制約は[実行エンジンの自動振り分け](#実行エンジンの自動振り分け)を参照してください。
|
||||
|
||||
### 4. scene テーブルと ymm4 テーブル
|
||||
|
||||
`scene` テーブルにはシーン(プロジェクト)の解像度情報が格納されています。いずれも読み取り専用です。
|
||||
`scene` テーブルにはシーン(プロジェクト)の解像度情報と、シーン単位で値を共有する関数が格納されています。
|
||||
|
||||
| 変数 | 説明 |
|
||||
| 変数 / 関数 | 説明 |
|
||||
|---|---|
|
||||
| `scene.width`, `scene.height` | シーンの横・縦解像度(ピクセル) |
|
||||
| `scene.cx`, `scene.cy` | シーン解像度の半分(width/2, height/2) |
|
||||
| `scene.width`, `scene.height` | シーンの横・縦解像度(ピクセル)。読み取り専用です |
|
||||
| `scene.cx`, `scene.cy` | シーン解像度の半分(width/2, height/2)。読み取り専用です |
|
||||
| `scene.set(name, value)` | シーン単位の共有領域へ値を保存します。同じシーン内のすべての Lua スクリプトエフェクトから、アイテムやフレームをまたいで参照できます。値は数値・文字列・真偽値のみで、`nil` を渡すと削除されます |
|
||||
| `scene.get(name)` | `scene.set()` で保存した値を取得します。未設定の名前は `nil` を返します |
|
||||
|
||||
自分のスクリプトが書き込んだ値は、同じ実行の中で直後の `scene.get` からそのまま読み取れます。他のアイテムが書き込んだ値は、次のフレームの評価から読み取れます。同じフレームの中では、アイテムがどの順番で評価されても読み取れる値は変わりません。スクリプトがエラーまたはタイムアウトで終了した場合には、その実行の書き込みは反映されません。動画出力を開始すると共有領域は空の状態から始まるため、同じプロジェクトを出力すれば毎回同じ結果になります。名前と文字列の値は UTF-8 換算で 4095 バイトを超える部分が切り捨てられ、1 つのシーンに保存できる名前は 4096 個までです。値はシーンごとに独立しており、YMM4 を終了するまでメモリ上に保持されます。プロジェクトファイルには保存されません。MoonSharp と LuaJIT のどちらのエンジンでも同じ動作をします。
|
||||
|
||||
`ymm4` テーブルには YMM4 固有のメタ情報が格納されています。いずれも読み取り専用です。
|
||||
|
||||
@@ -177,6 +184,10 @@ YukkuriMovieMaker4(YMM4)上で動作する、**Luaスクリプトでオブ
|
||||
エフェクトパネルには 4 本のトラックバー(アニメーション対応)があり、各値はスクリプト内で `obj.track0`〜`obj.track3` として参照できます。スライダー表示範囲はいずれも -100〜100、デフォルト値は 0、表示形式は小数点以下2桁です。トラックバーは常に表示されます。
|
||||
|
||||
チェックボックス(`obj.check0`〜`obj.check3`)とカラーピッカー(`color`)は、スクリプト本体でそれらを参照すると自動的にエフェクトパネルへ表示されます(参照を消すと非表示に戻ります)。これにより、`--` ヘッダを書かなくても必要な入力欄だけを出せます。なお、この一般利用ではスライダーのようなラベル・範囲・既定値の宣言は伴わないため、値の範囲はスクリプト内で扱ってください。AviUtl 互換の `--track`/`--check`/`--color` ヘッダによる宣言表示は従来どおり利用できます([AviUtl スクリプトの部分互換](#9-aviutl-スクリプトの部分互換)を参照)。
|
||||
|
||||
数値スライダーが 4 本あり、各値はスクリプト内で `obj.slider0`〜`obj.slider3` として参照できます。値は整数で、表示範囲は `obj.slider0` が 1〜10、`obj.slider1` が 0〜100、`obj.slider2` が 0〜1000、`obj.slider3` が -1000〜1000 です。状態の切り替えなど、補間を伴わない整数値の受け渡しに使えます。
|
||||
|
||||
文字列パラメータも利用できます。テキスト入力欄は `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.load` へ渡して画像・動画の読み込みに使えます。スライダーと文字列パラメータは、スクリプト本体でそれらを参照すると自動的にエフェクトパネルへ表示されます。いずれのパラメータも MoonSharp とネイティブの両エンジンから参照できます。
|
||||
|
||||
### 7. スクリプトエディタの支援機能
|
||||
|
||||
@@ -206,11 +217,15 @@ AviUtl のアニメーション効果スクリプト(`.anm` 系)のうち、
|
||||
- **`@` による複数セクション**: 1 つのスクリプトに `@名前` で複数の効果が定義されている場合、先頭のセクションのみを実行します。
|
||||
- **`obj.rand(st, ed [, seed [, frame]])`**: 指定範囲(`st`〜`ed`)の整数を返す決定論的な乱数です。`seed` と `frame` が同じであれば常に同じ値を返し、`frame` を省略すると現在のフレームを用います。従来エンジン(MoonSharp)と高速ランタイム(LuaJIT)で同じ値を返します。
|
||||
- **`obj.load("figure", 名前, 色, サイズ [, ライン [, アスペクト]])`**: 円・四角形・三角形・五角形・六角形・星形を生成し、オブジェクトのバッファを置き換えて描画します(出力は図形サイズに合わせて生成され、中心に配置されます)。`ライン` を省略するか `0` で塗りつぶし、サイズ以上の値でも塗りつぶしになります。`アスペクト`(-1.0〜1.0)で幅・高さを歪曲できます。
|
||||
- **描画・メディア・バッファ・オプション API**: `obj.draw` / `obj.drawpoly` による描画合成、`obj.load` の `"text"` / `"image"` / `"movie"`、`obj.setfont`、`obj.copybuffer`、`obj.effect`、`obj.getvalue`、`obj.setoption` / `obj.getoption` / `obj.pixeloption` に対応しています。これらは従来エンジン(MoonSharp)と高速ランタイム(LuaJIT)の双方で動作します。
|
||||
- **描画・メディア・バッファ・オプション API**: `obj.draw` / `obj.drawpoly` による描画合成、`obj.load` の `"text"` / `"image"` / `"movie"`、`obj.setfont`、`obj.copybuffer`、`obj.effect`、`obj.getvalue`、`obj.setoption` / `obj.getoption` / `obj.pixeloption` に対応しています。これらは従来エンジン(MoonSharp)と高速ランタイム(LuaJIT)の双方で動作します。`obj.setoption` では `antialias` に加えて、`obj.draw` / `obj.drawpoly` の合成モードを YMM4 の並びで指定する `blend`、描画先を `"framebuffer"` / `"tempbuffer"` で切り替える `drawtarget`、作業画像の出力可否を切り替える `draw_state` に対応します。MoonSharp では `tempbuffer` への合成を GPU で実行し、GPU を利用できない環境では CPU の合成へ自動的に切り替わります。丸めの違いにより、合成の結果はエンジン間でごく僅かに異なることがあります。
|
||||
- **`obj.setanchor(name, count [, option, ...])`**: プレビュー上にドラッグ可能なアンカーポイントを表示し、その座標を `name` の Lua 変数(`pos={x0,y0,x1,y1,…}`、`"xyz"` 指定時は `{x0,y0,z0,…}`)へ格納します。座標はオブジェクトの中心が原点で、ドラッグで調整した値はプロジェクトへ保存されます。最大 32 個で、`"line"` / `"loop"` / `"star"` / `"arm"` の線結びと `"xyz"` の 3D 指定に対応します。設置数を返し、従来エンジン(MoonSharp)と高速ランタイム(LuaJIT)の双方で動作します。`name` に `"track"` を指定するトラックバー連携は未対応です。
|
||||
- **`obj.effect` の AviUtl/AviUtl2 互換マップ**: `obj.effect("エフェクト名", "パラメータ名", 値, …)` はまず互換マップを参照し、AviUtl/AviUtl2 の名前として宣言したエフェクトを、対応する YMM4 の映像エフェクトとプロパティへ変換して適用します。値の倍率とオフセットの変換まで宣言できます。互換マップに宣言が無い名前は、従来どおり YMM4 のエフェクト名・キーワードでそのまま解決するため、既存の呼び出しはそのまま動きます。この互換マップは YMM4 自身が AviUtl の `.exo` へ書き出す変換を逆向きにたどって構築しているため、往復しても結果が一致します。対象のエンジンは指定子 `--!aviutl` または `--!aviutl2` で切り替え、指定子を書かないときは `--!aviutl` として扱います。互換マップが対応するエフェクト名の一覧はドキュメントの「obj の関数」を参照してください。
|
||||
|
||||
- **AviUtl 互換のグローバル関数**: `RGB` / `HSV`(色情報と各要素の相互変換。6 引数指定で時間変化)、`OR` / `AND` / `XOR`(32bit 整数のビット演算)、`SHIFT`(算術シフト)、`debug_print`(`OutputDebugString()` への文字列送信。スクリプトの実行エラーも自動で送信されます)をグローバルスコープで呼び出せます。すべての実行エンジンで同一の結果を返します。
|
||||
|
||||
次のような機能は、この互換層では対象外です(呼び出しを含むスクリプトは意図どおりには動作しません)。
|
||||
|
||||
- `obj.setanchor`、`scene.set` / `scene.get` などの未実装関数
|
||||
- `obj.mes` / `obj.rand1` などの未実装関数
|
||||
- `require` によるモジュール読み込み、`io` / `dofile` などの任意ファイルアクセス(`obj.load("image"/"movie")` のみ、先頭ヘッダー検証付きで対応)
|
||||
|
||||
---
|
||||
@@ -222,8 +237,8 @@ AviUtl のアニメーション効果スクリプト(`.anm` 系)のうち、
|
||||
スクリプトは内容に応じて 4 つのエンジンへ自動的に振り分けられます。
|
||||
|
||||
- **自ピクセル完結のピクセル写像**(`for y … for x … obj.getpixel … obj.setpixel … end end` の形)→ **CPU カーネル(式ツリー)** へ実行時コンパイルして実行。
|
||||
- **上記以外のピクセル操作を含むスクリプト**(`obj.getpixeldata` や近傍参照・別座標書き込みなど)→ 同梱の高速ランタイム **LuaJIT** で実行(ネイティブ実行)。
|
||||
- **変形のみのスクリプト** → 従来の **MoonSharp** で実行。
|
||||
- **上記以外のスクリプト** → 同梱の高速ランタイム **LuaJIT** で実行(ネイティブ実行)。
|
||||
- **`native` フォルダが配備されていない環境と空のスクリプト** → **MoonSharp** で実行。
|
||||
|
||||
スクリプトの先頭行に次のディレクティブを書くと、エンジンを明示指定できます。
|
||||
|
||||
@@ -236,7 +251,7 @@ AviUtl のアニメーション効果スクリプト(`.anm` 系)のうち、
|
||||
|
||||
CPU / GPU カーネルが成立するのは、四則演算・`math.*`・比較・しきい値の「条件 and 値1 or 値2」・`local` 変数のみを使い、処理中の自ピクセル(`obj.getpixel(x, y)`)と `obj` / `scene` / `time` 等の値だけを参照する純粋な写像(色変換・グレースケール・ガンマ・しきい値・チャンネル混合など)の場合です。近傍参照(ぼかし等)・別座標への書き込み・`getpixeldata`・`getobject`・テーブル/文字列操作・`if` 文などを含む場合はカーネル化されず、自動的に LuaJIT または MoonSharp で実行されます。コンパイル済みのカーネルはスクリプト本文をキーにキャッシュされ、初回フレームのみコンパイルコストを払います。
|
||||
|
||||
ネイティブ実行は**専用の別プロセス**で行われ、ピクセルバッファは共有メモリ経由で受け渡されます。スクリプトが無限ループに陥った場合でも **5 秒のタイムアウトでプロセスを強制終了**するため本体は固まらず、終了後は自動的に復帰します。出力結果は従来エンジンと一致します。
|
||||
ネイティブ実行は**専用の別プロセス**で行われ、ピクセルバッファは共有メモリ経由で受け渡されます。ピクセルの転送はスクリプトがピクセルへ初めてアクセスした時点でのみ行われるため、変形や描画だけのスクリプトでは転送が発生しません。ワーカープロセスは入力画像のサイズが変わっても再起動せず、フレームをまたいで再利用されます。スクリプトが無限ループに陥った場合でも **5 秒のタイムアウトでプロセスを強制終了**するため本体は固まらず、終了後は自動的に復帰します。出力結果は MoonSharp と一致します。
|
||||
|
||||
`obj.getobject` はネイティブ実行でも利用できます。呼び出し時に本体プロセスへ同期的に問い合わせてシーンオブジェクトを解決するため、従来エンジンと同じ結果を返します。同じタグ・同じフレームへの連続した問い合わせはフレーム内でキャッシュされ、2 回目以降は往復を行いません。
|
||||
|
||||
@@ -263,7 +278,7 @@ CPU / GPU カーネルが成立するのは、四則演算・`math.*`・比較
|
||||
|
||||
### グローバル変数のリセットと整合性チェック
|
||||
|
||||
内部の Lua 実行環境(Script / Table インスタンス)は性能のためフレームをまたいで再利用されますが、スクリプトが定義したユーザー定義のグローバル変数や、`obj` / `scene` / `anim` / `ymm4` テーブルへスクリプトが追加したキーは、各フレームの実行開始時に初期状態のスナップショットと比較して取り除かれます。これにより、あるフレームでスクリプトが作成した状態が次のフレームへ意図せず持ち越されることを防いでいます。
|
||||
内部の Lua 実行環境は性能のためフレームをまたいで再利用されますが、スクリプトが定義したユーザー定義のグローバル変数や、`obj` / `scene` / `anim` / `ymm4` テーブルへスクリプトが追加したキーは、各フレームの実行開始時に初期状態のスナップショットと比較して取り除かれます。これにより、あるフレームでスクリプトが作成した状態が次のフレームへ意図せず持ち越されることを防いでいます。このリセットは LuaJIT と MoonSharp のどちらのエンジンでも同じように行われます。
|
||||
|
||||
また、実行のたびに組み込みの `math` グローバルがテーブル型のまま残っているかを確認し、スクリプトの誤操作などで破壊されていた場合は Lua 実行環境ごと再構築します。
|
||||
|
||||
@@ -279,6 +294,14 @@ CPU / GPU カーネルが成立するのは、四則演算・`math.*`・比較
|
||||
| **Track1** | 数値 | 0.00 | -100 〜 100 | ✔ | `obj.track1` として参照できる汎用パラメータ |
|
||||
| **Track2** | 数値 | 0.00 | -100 〜 100 | ✔ | `obj.track2` として参照できる汎用パラメータ |
|
||||
| **Track3** | 数値 | 0.00 | -100 〜 100 | ✔ | `obj.track3` として参照できる汎用パラメータ |
|
||||
| **Slider0** | 整数 | 1 | 1 〜 10 | - | `obj.slider0` として参照できる整数パラメータ |
|
||||
| **Slider1** | 整数 | 0 | 0 〜 100 | - | `obj.slider1` として参照できる整数パラメータ |
|
||||
| **Slider2** | 整数 | 0 | 0 〜 1000 | - | `obj.slider2` として参照できる整数パラメータ |
|
||||
| **Slider3** | 整数 | 0 | -1000 〜 1000 | - | `obj.slider3` として参照できる整数パラメータ |
|
||||
| **Text** | 文字列 | 空 | - | - | `obj.text` として参照できるテキスト入力 |
|
||||
| **Font** | 文字列 | メイリオ | - | - | `obj.font` として参照できるフォント名 |
|
||||
| **Directory** | 文字列 | 空 | - | - | `obj.dir` として参照できるフォルダパス |
|
||||
| **FileVideo**〜**FileShader** | 文字列 | 空 | - | - | `obj.file_video`〜`obj.file_shader` として参照できるファイルパス |
|
||||
|
||||
---
|
||||
|
||||
@@ -357,7 +380,7 @@ obj.alpha = anim.ease_out(t) * 255
|
||||
- **AviUtl 互換は部分的**: AviUtl のアニメーション効果スクリプトのうち、変形・不透明度・乱数の範囲のみ実行できます([AviUtl スクリプトの部分互換](#9-aviutl-スクリプトの部分互換)を参照)。描画・フィルタ・ファイルアクセス系の関数、および AviUtl 向けの EXO 出力(`.exo`)には対応していません。
|
||||
- **実行タイムアウト**: スクリプトの実行は 5000ms(5秒)でタイムアウトし、超過した場合は強制終了されエラーとして扱われます。無限ループが発生しないよう注意してください。
|
||||
- **利用可能な標準ライブラリの制限**: `table`、`string`、`math`、`bit32` および基本関数のみ利用できます。`io`、`os`、`debug`、`ffi`、`require` は利用できません。
|
||||
- **ピクセル操作の負荷**: `obj.getpixel` / `obj.setpixel` / `obj.getpixeldata` は実際の入力画像にアクセスするため、各フレームで最初に呼び出した際に GPU→CPU へのデータ転送が発生します(GPU カーネルはこの転送を行いません)。不要な場合は呼び出しを省略することで処理を高速化できます。これらを含むスクリプトは内容に応じて CPU カーネル・GPU カーネル・高速ランタイム(LuaJIT)のいずれかで自動実行され大幅に高速化されます。詳細は[実行エンジンの自動振り分け](#実行エンジンの自動振り分け)を参照。
|
||||
- **ピクセル操作の負荷**: `obj.getpixel` / `obj.setpixel` / `obj.getpixeldata` は実際の入力画像にアクセスするため、各フレームで最初に呼び出した際に GPU→CPU へのデータ転送が発生します(GPU カーネルはこの転送を行いません)。不要な場合は呼び出しを省略することで処理を高速化できます。これらを含むスクリプトは内容に応じて CPU カーネルまたは高速ランタイム(LuaJIT)で自動実行され大幅に高速化されます。詳細は[実行エンジンの自動振り分け](#実行エンジンの自動振り分け)を参照。
|
||||
- **`math.random` はフレームごとの決定論的な乱数**: 毎フレーム `frame` の値でシードし直されるため、同一フレームでは常に同じ値になります。フレームをまたいで変化する乱数的な値が必要な場合は `anim.rand` の利用を検討してください。
|
||||
- **`obj.oz` は出力に反映されません**: スクリプト実行後にコンテキストへ読み戻されますが、現在の実装では中心点オフセットの出力計算に使用されていません。
|
||||
- **エクスポートは先頭の1件のみ**: 複数アイテムを選択した状態でも、エクスポートされるスクリプトは先頭のアイテムのもののみです(インポート・クリアは選択中のすべてのアイテムに適用されます)。
|
||||
@@ -382,8 +405,8 @@ obj.alpha = anim.ease_out(t) * 255
|
||||
|
||||
| ソフトウェア | 用途 | ライセンス |
|
||||
|---|---|---|
|
||||
| [MoonSharp](https://github.com/moonsharp-devs/moonsharp) | 標準のLua実行エンジン(Lua 5.2 互換) | 3-Clause BSD License |
|
||||
| [LuaJIT](https://github.com/LuaJIT/LuaJIT) | ピクセル操作向け高速ランタイム(`native/luajit.exe`・`lua51.dll`) | MIT License |
|
||||
| [MoonSharp](https://github.com/moonsharp-devs/moonsharp) | フォールバック用のLua実行エンジン(Lua 5.2 互換) | 3-Clause BSD License |
|
||||
| [LuaJIT](https://github.com/LuaJIT/LuaJIT) | 標準の高速ランタイム(`native/luajit.exe`・`lua51.dll`) | MIT License |
|
||||
|
||||
### MoonSharp(3-Clause BSD License)
|
||||
|
||||
|
||||
+160
@@ -0,0 +1,160 @@
|
||||
<!DOCTYPE html>
|
||||
<html lang="ja">
|
||||
<head>
|
||||
<meta charset="utf-8">
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1">
|
||||
<title>anim ライブラリ | Lua スクリプト for YMM4</title>
|
||||
<link rel="stylesheet" href="assets/style.css">
|
||||
</head>
|
||||
<body>
|
||||
<button id="navtoggle" aria-label="メニュー">☰</button>
|
||||
<nav id="sidebar"></nav>
|
||||
<main>
|
||||
|
||||
<h1>anim ライブラリ</h1>
|
||||
|
||||
<p>
|
||||
<code>anim</code> は、アニメーションでよく使う計算をまとめた補助ライブラリです。
|
||||
補間・イージング・波・範囲変換・ベクトル・ノイズ・色変換と、便利な定数を提供します。
|
||||
これらは標準 Lua にはない、このエフェクト独自の関数です。
|
||||
</p>
|
||||
|
||||
<h2>定数</h2>
|
||||
|
||||
<table>
|
||||
<tr><th>定数</th><th>値</th><th>説明</th></tr>
|
||||
<tr><td><code>anim.tau</code></td><td><code>math.pi * 2</code></td><td>円一周分のラジアン。周期運動に使う</td></tr>
|
||||
<tr><td><code>anim.e</code></td><td>ネイピア数</td><td>自然対数の底</td></tr>
|
||||
<tr><td><code>anim.phi</code></td><td><code>(1 + sqrt(5)) / 2</code></td><td>黄金比</td></tr>
|
||||
<tr><td><code>anim.sqrt2</code></td><td><code>sqrt(2)</code></td><td>2 の平方根</td></tr>
|
||||
</table>
|
||||
|
||||
<pre><code>obj.x = obj.x + math.sin(time * anim.tau) * 100</code></pre>
|
||||
|
||||
<h2>補間・イージング</h2>
|
||||
|
||||
<p>
|
||||
イージング関数はおおむね 0.0 ~ 1.0 の進行度 <code>t</code> を受け取り、変化のカーブを返します。
|
||||
<code>obj.t</code> をそのまま渡すのが定番です。
|
||||
</p>
|
||||
|
||||
<table>
|
||||
<tr><th>関数</th><th>説明</th></tr>
|
||||
<tr><td><code>anim.lerp(a, b, t)</code></td><td><code>a</code> と <code>b</code> を <code>t</code> で線形補間</td></tr>
|
||||
<tr><td><code>anim.smoothstep(e0, e1, x)</code></td><td><code>e0</code> ~ <code>e1</code> をエルミート補間で滑らかに遷移</td></tr>
|
||||
<tr><td><code>anim.smootherstep(e0, e1, x)</code></td><td>2 次導関数まで連続な、より滑らかな遷移</td></tr>
|
||||
<tr><td><code>anim.ease_in(t)</code></td><td>2 次イーズイン(加速)</td></tr>
|
||||
<tr><td><code>anim.ease_out(t)</code></td><td>2 次イーズアウト(減速)</td></tr>
|
||||
<tr><td><code>anim.ease_in_out(t)</code></td><td>2 次イーズイン・アウト(加速後減速)</td></tr>
|
||||
<tr><td><code>anim.elastic(t)</code></td><td>弾むようなスプリングイージング(t は 0 ~ 1 にクランプ)</td></tr>
|
||||
<tr><td><code>anim.back(t)</code></td><td>行き過ぎてから戻るイージング</td></tr>
|
||||
<tr><td><code>anim.bounce(t)</code></td><td>バウンドするイージング(t は 0 ~ 1 にクランプ)</td></tr>
|
||||
<tr><td><code>anim.step(edge, x)</code></td><td><code>x</code> が <code>edge</code> 以上なら 1.0、未満なら 0.0</td></tr>
|
||||
<tr><td><code>anim.bezier(t, p0, p1, p2, p3)</code></td><td><code>t</code> における 3 次ベジェ曲線の値(t は 0 ~ 1 にクランプ)</td></tr>
|
||||
</table>
|
||||
|
||||
<h3>2 点間をイージングで移動</h3>
|
||||
<pre><code>local tx, ty = 200, -100
|
||||
local p = anim.ease_in_out(obj.t)
|
||||
obj.x = anim.lerp(obj.x, tx, p)
|
||||
obj.y = anim.lerp(obj.y, ty, p)</code></pre>
|
||||
|
||||
<h3>弾むように登場</h3>
|
||||
<pre><code>local p = anim.duration(time, 0.3)
|
||||
obj.zoom = obj.zoom * anim.elastic(p)</code></pre>
|
||||
|
||||
<h2>範囲・周期</h2>
|
||||
|
||||
<table>
|
||||
<tr><th>関数</th><th>説明</th></tr>
|
||||
<tr><td><code>anim.clamp(v, lo, hi)</code></td><td><code>v</code> を <code>lo</code> ~ <code>hi</code> に収める</td></tr>
|
||||
<tr><td><code>anim.map(v, a1, b1, a2, b2)</code></td><td>範囲 <code>a1</code>~<code>b1</code> の <code>v</code> を <code>a2</code>~<code>b2</code> に変換</td></tr>
|
||||
<tr><td><code>anim.norm(v, lo, hi)</code></td><td><code>v</code> が <code>lo</code>~<code>hi</code> のどの割合(0.0~1.0)かを返す</td></tr>
|
||||
<tr><td><code>anim.wrap(v, lo, hi)</code></td><td><code>v</code> を <code>lo</code> ~ <code>hi</code> でループさせる</td></tr>
|
||||
<tr><td><code>anim.pingpong(t, len)</code></td><td>0 ~ <code>len</code> を往復する値</td></tr>
|
||||
<tr><td><code>anim.sign(v)</code></td><td>符号(正=1, 負=-1, ゼロ=0)</td></tr>
|
||||
<tr><td><code>anim.fract(v)</code></td><td>小数部分のみ</td></tr>
|
||||
<tr><td><code>anim.oscillate(t, lo, hi, freq)</code></td><td>周波数 <code>freq</code> で <code>lo</code>~<code>hi</code> を正弦波で往復</td></tr>
|
||||
<tr><td><code>anim.triangle(t, freq)</code></td><td>周波数 <code>freq</code> で 0.0~1.0 を往復する三角波</td></tr>
|
||||
<tr><td><code>anim.square(t, freq)</code></td><td>周波数 <code>freq</code> で 1.0 と 0.0 を切り替える矩形波</td></tr>
|
||||
<tr><td><code>anim.duration(t, dur)</code></td><td>時間 <code>dur</code> に対する割合(0.0~1.0、クランプあり)</td></tr>
|
||||
<tr><td><code>anim.delay(t, d)</code></td><td>時間 <code>d</code> を引いた値(0 未満は 0)</td></tr>
|
||||
</table>
|
||||
|
||||
<h3>値の範囲変換</h3>
|
||||
<pre><code>obj.rz = anim.map(obj.track0, 0, 100, -180, 180)</code></pre>
|
||||
|
||||
<h3>滑らかな明滅</h3>
|
||||
<pre><code>obj.alpha = anim.oscillate(time, 64, 255, 1)</code></pre>
|
||||
|
||||
<h2>ベクトル・幾何</h2>
|
||||
|
||||
<table>
|
||||
<tr><th>関数</th><th>戻り値</th><th>説明</th></tr>
|
||||
<tr><td><code>anim.len(x, y)</code></td><td>数値</td><td>ベクトル (x, y) の長さ</td></tr>
|
||||
<tr><td><code>anim.dist(x1, y1, x2, y2)</code></td><td>数値</td><td>2 点間の距離</td></tr>
|
||||
<tr><td><code>anim.dot(x1, y1, x2, y2)</code></td><td>数値</td><td>2 ベクトルの内積</td></tr>
|
||||
<tr><td><code>anim.normalize(x, y)</code></td><td>x, y</td><td>正規化した方向ベクトル(2 値で返す)</td></tr>
|
||||
<tr><td><code>anim.polar(r, a)</code></td><td>x, y</td><td>半径 <code>r</code>・角度 <code>a</code>(度)から移動量</td></tr>
|
||||
<tr><td><code>anim.rotate(x, y, a)</code></td><td>x, y</td><td>(x, y) を <code>a</code>(度)回転させた座標</td></tr>
|
||||
</table>
|
||||
|
||||
<h3>円運動</h3>
|
||||
<pre><code>local r = obj.track0
|
||||
local dx, dy = anim.polar(r, time * 90)
|
||||
obj.x = obj.x + dx
|
||||
obj.y = obj.y + dy</code></pre>
|
||||
|
||||
<h2>ノイズ・乱数</h2>
|
||||
|
||||
<table>
|
||||
<tr><th>関数</th><th>説明</th></tr>
|
||||
<tr><td><code>anim.noise(x [, y [, z]])</code></td><td>1 ~ 3 次元の滑らかなノイズ(0.0 ~ 1.0)。同じ座標では常に同じ値</td></tr>
|
||||
<tr><td><code>anim.rand(s)</code></td><td>シード <code>s</code> に基づく 0.0 ~ 1.0 の安定した乱数</td></tr>
|
||||
<tr><td><code>anim.rand(max, s)</code></td><td>0.0 ~ <code>max</code> の安定した乱数</td></tr>
|
||||
<tr><td><code>anim.rand(min, max, s)</code></td><td><code>min</code> ~ <code>max</code> の安定した乱数</td></tr>
|
||||
</table>
|
||||
|
||||
<div class="note">
|
||||
<code>anim.rand</code> はシードのみで決まる小数の乱数です(フレームは関与しません)。
|
||||
整数で、フレームによっても変えたい場合は <a href="obj-functions.html"><code>obj.rand</code></a> を使ってください。
|
||||
</div>
|
||||
|
||||
<h3>安定した乱数で個体差をつける</h3>
|
||||
<pre><code>local offset = anim.rand(-50, 50, obj.layer)
|
||||
obj.x = obj.x + offset</code></pre>
|
||||
|
||||
<h3>ノイズで揺らぐ手ぶれ風</h3>
|
||||
<pre><code>obj.x = obj.x + (anim.noise(time * 2, 0, 0) - 0.5) * 20
|
||||
obj.y = obj.y + (anim.noise(0, time * 2, 0) - 0.5) * 20
|
||||
obj.rz = (anim.noise(0, 0, time * 2) - 0.5) * 10</code></pre>
|
||||
|
||||
<h2>色変換</h2>
|
||||
|
||||
<table>
|
||||
<tr><th>関数</th><th>戻り値</th><th>説明</th></tr>
|
||||
<tr><td><code>anim.hsv_to_rgb(h, s, v)</code></td><td>r, g, b</td><td>HSV(色相 0~360, 彩度 0~1, 明度 0~1)を RGB(0~255)へ変換</td></tr>
|
||||
<tr><td><code>anim.rgb_to_hsv(r, g, b)</code></td><td>h, s, v</td><td>RGB(0~255)を HSV へ変換</td></tr>
|
||||
</table>
|
||||
|
||||
<h3>時間で色相を回す</h3>
|
||||
<pre><code>local hue = anim.wrap(time * 60, 0, 360)
|
||||
local cr, cg, cb = anim.hsv_to_rgb(hue, 1, 1)
|
||||
local pd = obj.getpixeldata()
|
||||
local n = pd.width * pd.height
|
||||
for i = 0, n - 1 do
|
||||
local base = i * 4
|
||||
pd:set(base + 1, pd:get(base + 1) * cr / 255)
|
||||
pd:set(base + 2, pd:get(base + 2) * cg / 255)
|
||||
pd:set(base + 3, pd:get(base + 3) * cb / 255)
|
||||
end</code></pre>
|
||||
|
||||
<div class="pager">
|
||||
<a href="obj-functions.html">← obj の関数</a>
|
||||
<a href="scene-ymm4.html">scene と ymm4 →</a>
|
||||
</div>
|
||||
|
||||
</main>
|
||||
<script src="assets/nav.js"></script>
|
||||
</body>
|
||||
</html>
|
||||
@@ -0,0 +1,241 @@
|
||||
(function () {
|
||||
var NAV = [
|
||||
{
|
||||
group: "はじめに",
|
||||
items: [
|
||||
{ title: "概要", href: "index.html" },
|
||||
{ title: "導入と使い方", href: "getting-started.html" }
|
||||
]
|
||||
},
|
||||
{
|
||||
group: "Lua 言語",
|
||||
items: [
|
||||
{ title: "Lua の基礎", href: "lua-basics.html" },
|
||||
{ title: "標準ライブラリ", href: "stdlib.html" }
|
||||
]
|
||||
},
|
||||
{
|
||||
group: "API リファレンス",
|
||||
items: [
|
||||
{ title: "グローバル変数", href: "globals.html" },
|
||||
{ title: "obj オブジェクト", href: "obj.html" },
|
||||
{ title: "obj の関数", href: "obj-functions.html" },
|
||||
{ title: "anim ライブラリ", href: "anim.html" },
|
||||
{ title: "scene と ymm4", href: "scene-ymm4.html" },
|
||||
{ title: "ピクセル操作", href: "pixels.html" }
|
||||
]
|
||||
},
|
||||
{
|
||||
group: "高度な機能",
|
||||
items: [
|
||||
{ title: "エンジンと高速化", href: "engines.html" },
|
||||
{ title: "パラメータ指定子", href: "directives.html" }
|
||||
]
|
||||
},
|
||||
{
|
||||
group: "実用",
|
||||
items: [
|
||||
{ title: "サンプル集", href: "samples.html" },
|
||||
{ title: "クイックリファレンス", href: "reference.html" },
|
||||
{ title: "制限事項とトラブル", href: "limits.html" }
|
||||
]
|
||||
}
|
||||
];
|
||||
|
||||
var titleOf = {};
|
||||
for (var gi = 0; gi < NAV.length; gi++) {
|
||||
for (var ii = 0; ii < NAV[gi].items.length; ii++) {
|
||||
titleOf[NAV[gi].items[ii].href] = NAV[gi].items[ii].title;
|
||||
}
|
||||
}
|
||||
|
||||
var indexPromise = null;
|
||||
var searchTimer = null;
|
||||
|
||||
function currentFile() {
|
||||
var path = window.location.pathname;
|
||||
var file = path.substring(path.lastIndexOf("/") + 1);
|
||||
return file === "" ? "index.html" : file;
|
||||
}
|
||||
|
||||
function escapeHtml(text) {
|
||||
return text
|
||||
.replace(/&/g, "&")
|
||||
.replace(/</g, "<")
|
||||
.replace(/>/g, ">");
|
||||
}
|
||||
|
||||
function build() {
|
||||
var here = currentFile();
|
||||
var sidebar = document.getElementById("sidebar");
|
||||
if (!sidebar) return;
|
||||
|
||||
var html = '<a class="brand" href="index.html">Lua スクリプト for YMM4</a>';
|
||||
html += '<input id="navfilter" type="search" placeholder="全ページを検索" aria-label="全ページを検索" autocomplete="off">';
|
||||
html += '<div id="navresults"></div>';
|
||||
html += '<div id="navtree">';
|
||||
for (var i = 0; i < NAV.length; i++) {
|
||||
html += '<div class="group">' + NAV[i].group + "</div><ul>";
|
||||
for (var j = 0; j < NAV[i].items.length; j++) {
|
||||
var it = NAV[i].items[j];
|
||||
var cls = it.href === here ? ' class="active"' : "";
|
||||
html += "<li><a" + cls + ' href="' + it.href + '">' + it.title + "</a></li>";
|
||||
}
|
||||
html += "</ul>";
|
||||
}
|
||||
html += "</div>";
|
||||
sidebar.innerHTML = html;
|
||||
|
||||
var filter = document.getElementById("navfilter");
|
||||
filter.addEventListener("input", function () {
|
||||
var q = filter.value.trim();
|
||||
if (searchTimer) clearTimeout(searchTimer);
|
||||
searchTimer = setTimeout(function () { runSearch(q); }, 150);
|
||||
});
|
||||
}
|
||||
|
||||
function runSearch(query) {
|
||||
var tree = document.getElementById("navtree");
|
||||
var results = document.getElementById("navresults");
|
||||
if (!tree || !results) return;
|
||||
|
||||
if (query.length < 2) {
|
||||
results.innerHTML = "";
|
||||
tree.style.display = "";
|
||||
return;
|
||||
}
|
||||
|
||||
tree.style.display = "none";
|
||||
results.innerHTML = '<div class="navmsg">検索中…</div>';
|
||||
|
||||
buildIndex().then(function (sections) {
|
||||
if (document.getElementById("navfilter").value.trim() !== query) return;
|
||||
render(results, sections, query);
|
||||
});
|
||||
}
|
||||
|
||||
function buildIndex() {
|
||||
if (indexPromise) return indexPromise;
|
||||
|
||||
var hrefs = [];
|
||||
for (var key in titleOf) {
|
||||
if (Object.prototype.hasOwnProperty.call(titleOf, key)) hrefs.push(key);
|
||||
}
|
||||
|
||||
indexPromise = Promise.all(hrefs.map(fetchSections)).then(function (lists) {
|
||||
var all = [];
|
||||
for (var i = 0; i < lists.length; i++) {
|
||||
for (var j = 0; j < lists[i].length; j++) all.push(lists[i][j]);
|
||||
}
|
||||
return all;
|
||||
});
|
||||
return indexPromise;
|
||||
}
|
||||
|
||||
function fetchSections(href) {
|
||||
return fetch(href)
|
||||
.then(function (res) { return res.text(); })
|
||||
.then(function (text) {
|
||||
var doc = new DOMParser().parseFromString(text, "text/html");
|
||||
var main = doc.querySelector("main");
|
||||
if (!main) return [];
|
||||
|
||||
var sections = [];
|
||||
var heading = "";
|
||||
var buffer = "";
|
||||
var children = main.children;
|
||||
|
||||
function flush() {
|
||||
var body = buffer.replace(/\s+/g, " ").trim();
|
||||
if (body.length > 0) {
|
||||
sections.push({
|
||||
href: href,
|
||||
page: titleOf[href] || href,
|
||||
heading: heading,
|
||||
text: body,
|
||||
lower: body.toLowerCase()
|
||||
});
|
||||
}
|
||||
buffer = "";
|
||||
}
|
||||
|
||||
for (var i = 0; i < children.length; i++) {
|
||||
var el = children[i];
|
||||
var tag = el.tagName;
|
||||
if (tag === "H2" || tag === "H3") {
|
||||
flush();
|
||||
heading = el.textContent.replace(/\s+/g, " ").trim();
|
||||
} else if (el.className === "pager") {
|
||||
continue;
|
||||
} else {
|
||||
buffer += " " + el.textContent;
|
||||
}
|
||||
}
|
||||
flush();
|
||||
return sections;
|
||||
})
|
||||
.catch(function () { return []; });
|
||||
}
|
||||
|
||||
function render(container, sections, query) {
|
||||
var q = query.toLowerCase();
|
||||
var hits = [];
|
||||
for (var i = 0; i < sections.length; i++) {
|
||||
var s = sections[i];
|
||||
var inHeading = s.heading.toLowerCase().indexOf(q) !== -1;
|
||||
var inPage = s.page.toLowerCase().indexOf(q) !== -1;
|
||||
var pos = s.lower.indexOf(q);
|
||||
if (inHeading || inPage || pos !== -1) {
|
||||
hits.push({ section: s, pos: pos, rank: inHeading || inPage ? 0 : 1 });
|
||||
}
|
||||
}
|
||||
|
||||
hits.sort(function (a, b) { return a.rank - b.rank; });
|
||||
|
||||
if (hits.length === 0) {
|
||||
container.innerHTML = '<div class="navmsg">「' + escapeHtml(query) + "」に一致する内容はありません。</div>";
|
||||
return;
|
||||
}
|
||||
|
||||
var max = Math.min(hits.length, 40);
|
||||
var html = '<div class="navmsg">' + hits.length + " 件</div>";
|
||||
for (var k = 0; k < max; k++) {
|
||||
var s2 = hits[k].section;
|
||||
var label = s2.heading ? s2.page + " — " + s2.heading : s2.page;
|
||||
var anchor = s2.heading ? "#:~:text=" + encodeURIComponent(s2.heading) : "";
|
||||
html +=
|
||||
'<a class="navhit" href="' + s2.href + anchor + '">' +
|
||||
'<span class="h">' + escapeHtml(label) + "</span>" +
|
||||
'<span class="s">' + snippet(s2.text, hits[k].pos, query) + "</span>" +
|
||||
"</a>";
|
||||
}
|
||||
container.innerHTML = html;
|
||||
}
|
||||
|
||||
function snippet(text, pos, query) {
|
||||
if (pos < 0) {
|
||||
return escapeHtml(text.substring(0, 70)) + (text.length > 70 ? "…" : "");
|
||||
}
|
||||
var start = Math.max(0, pos - 30);
|
||||
var end = Math.min(text.length, pos + query.length + 40);
|
||||
var before = (start > 0 ? "…" : "") + text.substring(start, pos);
|
||||
var hit = text.substring(pos, pos + query.length);
|
||||
var after = text.substring(pos + query.length, end) + (end < text.length ? "…" : "");
|
||||
return escapeHtml(before) + "<mark>" + escapeHtml(hit) + "</mark>" + escapeHtml(after);
|
||||
}
|
||||
|
||||
function toggle() {
|
||||
var btn = document.getElementById("navtoggle");
|
||||
if (!btn) return;
|
||||
btn.addEventListener("click", function () {
|
||||
document.body.classList.toggle("nav-open");
|
||||
});
|
||||
}
|
||||
|
||||
if (document.readyState === "loading") {
|
||||
document.addEventListener("DOMContentLoaded", function () { build(); toggle(); });
|
||||
} else {
|
||||
build();
|
||||
toggle();
|
||||
}
|
||||
})();
|
||||
@@ -0,0 +1,28 @@
|
||||
* { box-sizing: border-box; }
|
||||
body { margin: 0; font-family: sans-serif; line-height: 1.7; }
|
||||
#sidebar { position: fixed; top: 0; left: 0; width: 240px; height: 100vh; overflow: auto; border-right: 1px solid #ccc; padding: 1em; }
|
||||
#sidebar .brand { display: block; margin-bottom: .6em; font-weight: bold; text-decoration: none; color: #000; }
|
||||
#sidebar input { width: 100%; margin-bottom: .6em; }
|
||||
#sidebar .group { font-size: .8em; color: #666; margin-top: 1em; }
|
||||
#sidebar ul { list-style: none; margin: 0; padding: 0; }
|
||||
#sidebar li a { display: block; padding: .2em .4em; text-decoration: none; color: #000; }
|
||||
#sidebar li a.active { background: #0969da; color: #fff; }
|
||||
main { margin-left: 240px; max-width: 860px; padding: 1em 2em 4em; }
|
||||
pre { background: #f0f0f0; border: 1px solid #ccc; padding: .8em; overflow-x: auto; }
|
||||
code { background: #f0f0f0; padding: 0 .2em; }
|
||||
pre code { background: none; padding: 0; }
|
||||
table { border-collapse: collapse; margin: 1em 0; }
|
||||
th, td { border: 1px solid #ccc; padding: .3em .6em; text-align: left; vertical-align: top; }
|
||||
#navresults .navmsg { font-size: .8em; color: #666; margin: .4em 0; }
|
||||
#navresults .navhit { display: block; padding: .3em .4em; text-decoration: none; color: #000; border-top: 1px solid #eee; }
|
||||
#navresults .navhit .h { display: block; font-size: .82em; color: #0969da; }
|
||||
#navresults .navhit .s { display: block; font-size: .82em; color: #444; }
|
||||
.note, .warn { border-left: 3px solid #888; padding-left: .8em; margin: 1em 0; }
|
||||
.pager { display: flex; justify-content: space-between; margin-top: 2em; }
|
||||
#navtoggle { display: none; }
|
||||
@media (max-width: 820px) {
|
||||
#sidebar { transform: translateX(-100%); transition: transform .2s; z-index: 9; background: #fff; }
|
||||
body.nav-open #sidebar { transform: none; }
|
||||
main { margin-left: 0; padding: 3em 1em; }
|
||||
#navtoggle { display: block; position: fixed; top: .5em; left: .5em; z-index: 10; }
|
||||
}
|
||||
@@ -0,0 +1,140 @@
|
||||
<!DOCTYPE html>
|
||||
<html lang="ja">
|
||||
<head>
|
||||
<meta charset="utf-8">
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1">
|
||||
<title>パラメータ指定子 | Lua スクリプト for YMM4</title>
|
||||
<link rel="stylesheet" href="assets/style.css">
|
||||
</head>
|
||||
<body>
|
||||
<button id="navtoggle" aria-label="メニュー">☰</button>
|
||||
<nav id="sidebar"></nav>
|
||||
<main>
|
||||
|
||||
<h1>パラメータ指定子</h1>
|
||||
|
||||
<p>
|
||||
スクリプトの先頭などにコメント形式の指定子を書くと、パラメータパネルのトラックバーや
|
||||
チェックボックス、色の名前・範囲・既定値を定義できます。指定子は <code>--</code> で始まる
|
||||
コメント行なので、Lua の実行には影響しません。
|
||||
</p>
|
||||
|
||||
<div class="note">
|
||||
指定子は必須ではありません。<code>--</code> の行を書かなくても、
|
||||
トラックバーの値は <code>obj.track0</code> ~ <code>obj.track3</code> で読めます。
|
||||
チェックボックスの <code>obj.check0</code> ~ <code>obj.check3</code> と <code>color</code> も、
|
||||
スクリプト中で参照すればパネルに現れて使えます。指定子は、名前や範囲・既定値を整えたいときに使います。
|
||||
</div>
|
||||
|
||||
<div class="note">
|
||||
エンジンを選ぶ <code>--!native</code> などの指定子は別物です。先頭が <code>--!</code> で始まります。
|
||||
エンジンの指定は<a href="engines.html">エンジンと高速化</a>を参照してください。
|
||||
</div>
|
||||
|
||||
<h2>トラックバー</h2>
|
||||
|
||||
<p>
|
||||
<code>--track0:</code> ~ <code>--track3:</code> で、各トラックバーの名前・範囲・既定値・増分を指定します。
|
||||
書式はカンマ区切りです。
|
||||
</p>
|
||||
|
||||
<pre><code>--track0:振幅,0,200,50
|
||||
--track1:周波数,0,10,1,0.1</code></pre>
|
||||
|
||||
<table>
|
||||
<tr><th>項目</th><th>位置</th><th>省略時</th></tr>
|
||||
<tr><td>名前</td><td>1 番目</td><td>空</td></tr>
|
||||
<tr><td>最小値</td><td>2 番目</td><td>0</td></tr>
|
||||
<tr><td>最大値</td><td>3 番目</td><td>100</td></tr>
|
||||
<tr><td>既定値</td><td>4 番目</td><td>最小値</td></tr>
|
||||
<tr><td>増分</td><td>5 番目</td><td>0</td></tr>
|
||||
</table>
|
||||
|
||||
<p>
|
||||
最大値が最小値より小さい場合は自動で入れ替わり、既定値は範囲内にクランプされます。
|
||||
値はスクリプトから <code>obj.track0</code> ~ <code>obj.track3</code> で読めます。
|
||||
</p>
|
||||
|
||||
<h2>チェックボックス</h2>
|
||||
|
||||
<p>
|
||||
<code>--check0:</code> ~ <code>--check3:</code> で、名前と既定値(0 で off、0 以外で on)を指定します。
|
||||
値は <code>obj.check0</code> ~ <code>obj.check3</code> で読めます。
|
||||
</p>
|
||||
|
||||
<pre><code>--check0:反転を有効にする,0</code></pre>
|
||||
|
||||
<table>
|
||||
<tr><th>項目</th><th>位置</th><th>省略時</th></tr>
|
||||
<tr><td>名前</td><td>1 番目</td><td>空</td></tr>
|
||||
<tr><td>既定値</td><td>2 番目</td><td>0(off)</td></tr>
|
||||
</table>
|
||||
|
||||
<h2>色</h2>
|
||||
|
||||
<p>
|
||||
<code>--color:</code> で Color パラメータの既定色を指定します。
|
||||
<code>0xRRGGBB</code> 形式または 10 進整数で書けます。値はグローバルの <code>color</code> で読めます。
|
||||
</p>
|
||||
|
||||
<pre><code>--color:0xFF8800</code></pre>
|
||||
|
||||
<h2>表示条件</h2>
|
||||
|
||||
<p>パラメータの表示・非表示は次のルールで決まります。</p>
|
||||
|
||||
<ul>
|
||||
<li>トラックバー: 指定子がまったく無い場合は 4 本すべて表示。
|
||||
いずれかの <code>--track@:</code> を書いた場合は、宣言したトラックのみ表示。</li>
|
||||
<li>チェックボックス: <code>--check@:</code> を書いた場合、または指定子がまったく無く
|
||||
スクリプト中で <code>obj.check@</code> を使っている場合に表示。</li>
|
||||
<li>色: <code>--color:</code> を書いた場合、または指定子がまったく無く
|
||||
スクリプト中で <code>color</code> を使っている場合に表示。</li>
|
||||
</ul>
|
||||
|
||||
<h2>セクション(@)</h2>
|
||||
|
||||
<p>
|
||||
行頭が <code>@</code> の行はセクションの区切りです。セクションを使う場合、
|
||||
指定子と本文は最初のセクションから読み取られます。通常のスクリプトでは <code>@</code> を使わず、
|
||||
指定子をスクリプト先頭にコメントとして並べれば十分です。
|
||||
</p>
|
||||
|
||||
<h2>AviUtl 互換の宣言(dialog / param)</h2>
|
||||
|
||||
<p>
|
||||
<code>--dialog:</code> と <code>--param:</code> は、AviUtl のダイアログ変数に近い書き方で、
|
||||
本文の先頭に Lua の宣言を差し込みます。差し込まれた行は本体より前に実行されます。
|
||||
</p>
|
||||
|
||||
<table>
|
||||
<tr><th>指定子</th><th>説明</th></tr>
|
||||
<tr><td><code>--param:宣言</code></td><td>指定した宣言を本文の先頭に追加する</td></tr>
|
||||
<tr><td><code>--dialog:ラベル,宣言; ...</code></td><td><code>;</code> 区切りの各項目について、最初の <code>,</code> の後ろを宣言として先頭に追加する</td></tr>
|
||||
</table>
|
||||
|
||||
<pre><code>--param:local speed = 90
|
||||
obj.rz = time * speed</code></pre>
|
||||
|
||||
<h2>AviUtl 互換マップの対象エンジン</h2>
|
||||
|
||||
<p>
|
||||
<code>obj.effect</code> が参照する互換マップの対象エンジンを切り替えます。
|
||||
指定子 <code>--!aviutl</code> または <code>--!aviutl2</code> を書くと、
|
||||
そのエンジンに対応するエフェクトだけを解決します。
|
||||
指定子を書かないときは <code>--!aviutl</code> として扱います。詳細は
|
||||
<a href="obj-functions.html">obj の関数</a>を参照してください。
|
||||
</p>
|
||||
|
||||
<pre><code>--!aviutl2
|
||||
obj.effect("ぼかし", "範囲", 20)</code></pre>
|
||||
|
||||
<div class="pager">
|
||||
<a href="engines.html">← エンジンと高速化</a>
|
||||
<a href="samples.html">サンプル集 →</a>
|
||||
</div>
|
||||
|
||||
</main>
|
||||
<script src="assets/nav.js"></script>
|
||||
</body>
|
||||
</html>
|
||||
+143
@@ -0,0 +1,143 @@
|
||||
<!DOCTYPE html>
|
||||
<html lang="ja">
|
||||
<head>
|
||||
<meta charset="utf-8">
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1">
|
||||
<title>エンジンと高速化 | Lua スクリプト for YMM4</title>
|
||||
<link rel="stylesheet" href="assets/style.css">
|
||||
</head>
|
||||
<body>
|
||||
<button id="navtoggle" aria-label="メニュー">☰</button>
|
||||
<nav id="sidebar"></nav>
|
||||
<main>
|
||||
|
||||
<h1>エンジンと高速化</h1>
|
||||
|
||||
<p>
|
||||
このプラグインには複数の実行エンジンがあります。標準は同梱の LuaJIT ネイティブレーンで、
|
||||
決まった形の重いピクセル処理はさらに CPU カーネルへ変換されます。Lua 5.2 互換の MoonSharp は
|
||||
フォールバック用の従来エンジンです。指定子を書かなくても、内容に応じて自動で最適なレーンが選ばれます。
|
||||
</p>
|
||||
|
||||
<h2>エンジンの種類</h2>
|
||||
|
||||
<table>
|
||||
<tr><th>エンジン</th><th>指定子</th><th>特徴</th></tr>
|
||||
<tr><td>ネイティブ(LuaJIT)</td><td><code>--!native</code>(既定)</td><td>別プロセスの LuaJIT で実行。ピクセル処理が大幅に高速</td></tr>
|
||||
<tr><td>MoonSharp</td><td><code>--!moonsharp</code></td><td>Lua 5.2 互換。フォールバック用の従来エンジン</td></tr>
|
||||
<tr><td>CPU カーネル</td><td><code>--!cpu</code></td><td>決まった形のピクセルループを並列実行へ変換。SIMD を実測で使い分け、MoonSharp と一致する結果</td></tr>
|
||||
<tr><td>GPU カーネル</td><td><code>--!gpu</code></td><td>ピクセルループを GPU シェーダーに変換。最速だが float32 精度(明示指定のみ)</td></tr>
|
||||
</table>
|
||||
|
||||
<div class="note">
|
||||
スライダー <code>obj.slider0</code> ~ <code>obj.slider3</code> と文字列パラメータ
|
||||
<code>obj.text</code> / <code>obj.font</code> / <code>obj.dir</code> / <code>obj.file_*</code> は、
|
||||
MoonSharp とネイティブのどちらのエンジンでも同じ名前で参照できます。
|
||||
CPU カーネルと GPU カーネルは数値計算に特化するため、文字列を扱いません。
|
||||
</div>
|
||||
|
||||
<h2>指定子の書き方</h2>
|
||||
|
||||
<p>
|
||||
エンジンの指定子は <code>--!</code> で始まる 1 行です。トークンの前後の空白以外に文字があってはいけません。
|
||||
スクリプトのどの行に書いても構いません。
|
||||
</p>
|
||||
|
||||
<pre><code>--!native
|
||||
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</code></pre>
|
||||
|
||||
<h2>自動振り分け</h2>
|
||||
|
||||
<p>指定子が無いときは、スクリプトの内容から自動でエンジンが選ばれます。</p>
|
||||
|
||||
<ul>
|
||||
<li>後述のカーネル条件に当てはまるピクセルループは、まず GPU カーネルを試します。初回に実機の GPU で
|
||||
処理し、CPU カーネルと出力が許容差に収まるか検証します。収まれば以後は GPU カーネル、収まらなければ
|
||||
CPU カーネルで実行します。CPU カーネルの結果は MoonSharp と一致します。</li>
|
||||
<li>それ以外のスクリプトは、同梱の LuaJIT ネイティブで実行します。結果は MoonSharp と一致します。</li>
|
||||
<li><code>native</code> フォルダが配備されていない環境と空のスクリプトは、MoonSharp で実行します。</li>
|
||||
</ul>
|
||||
|
||||
<div class="note">
|
||||
明示した指定子は自動振り分けより優先されます。GPU カーネルは浮動小数点の 32 ビットで計算するため、
|
||||
自動で選ぶときは初回の検証に通ったプログラムだけを対象とし、CPU カーネルと食い違うことはありません。
|
||||
<code>--!gpu</code> を明示したときは検証に通れば GPU、通らなければ CPU カーネルで実行します。
|
||||
</div>
|
||||
|
||||
<h2>カーネルに変換できる形</h2>
|
||||
|
||||
<p>
|
||||
CPU / GPU カーネルは、次の決まった形のスクリプトだけを変換します。条件に合わないスクリプトは
|
||||
カーネルにならず、自動でほかのエンジンへフォールバックします(結果は変わりません)。
|
||||
</p>
|
||||
|
||||
<ul>
|
||||
<li>先頭に <code>local</code> 宣言を置いてもよい。</li>
|
||||
<li>本体は二重の数値 for ループ 1 組だけ。外側と内側で <code>obj.h</code> と <code>obj.w</code> をそれぞれ
|
||||
<code>0</code> から <code>-1</code> まで回す。</li>
|
||||
<li>内側ループの最初が <code>local r, g, b[, a] = obj.getpixel(x, y)</code>、最後が
|
||||
<code>obj.setpixel(x, y, ...)</code>。</li>
|
||||
<li>その間は <code>local</code> 宣言と代入のみ。</li>
|
||||
</ul>
|
||||
|
||||
<p>カーネル内で使える要素は限られます。</p>
|
||||
|
||||
<table>
|
||||
<tr><th>分類</th><th>使えるもの</th></tr>
|
||||
<tr><td>演算子</td><td><code>+</code> <code>-</code> <code>*</code> <code>/</code> <code>%</code> <code>^</code>、単項マイナス、条件式 <code>cond and a or b</code></td></tr>
|
||||
<tr><td>math 関数</td><td><code>abs, floor, ceil, sqrt, sin, cos, tan, asin, acos, atan, atan2, exp, log, pow, fmod, min, max</code></td></tr>
|
||||
<tr><td>math 定数</td><td><code>math.pi</code>, <code>math.huge</code></td></tr>
|
||||
<tr><td>条件</td><td>比較(<code>< > <= >= == ~=</code>)、<code>and</code> / <code>or</code> / <code>not</code>、<code>obj.check0</code> ~ <code>obj.check3</code></td></tr>
|
||||
<tr><td>参照できる値</td><td>座標 <code>x</code> / <code>y</code>、<code>obj</code> の各フィールド、<code>scene.width/height/cx/cy</code>、
|
||||
<code>time, frame, totalframe, framerate, timelineframe, timelinetime, layer, color</code></td></tr>
|
||||
</table>
|
||||
|
||||
<div class="note">
|
||||
CPU カーネルは、4 画素をまとめて計算する SIMD 経路を持ちます。SIMD が有利かどうかは
|
||||
カーネルの内容と実行環境で変わるため、最初の数フレームでスカラ経路と SIMD 経路の両方を
|
||||
実行して時間を計り、速かった経路をそのプログラムで使い続けます。どちらの経路でも出力は
|
||||
同一です。
|
||||
</div>
|
||||
|
||||
<h3>カーネルになるグレースケールの例</h3>
|
||||
<pre><code>for y = 0, obj.h - 1 do
|
||||
for x = 0, obj.w - 1 do
|
||||
local r, g, b, a = obj.getpixel(x, y)
|
||||
local gray = r * 0.299 + g * 0.587 + b * 0.114
|
||||
obj.setpixel(x, y, gray, gray, gray, a)
|
||||
end
|
||||
end</code></pre>
|
||||
|
||||
<h2>フォールバックの動き</h2>
|
||||
|
||||
<ul>
|
||||
<li><code>--!native</code> を指定しても、プラグインの隣に <code>native</code> フォルダが配置されていない場合は
|
||||
MoonSharp で実行されます(ログに一度だけ警告が出ます)。期待した高速化が得られないときは、
|
||||
ビルド・配置に <code>native</code> フォルダが含まれているか確認してください。</li>
|
||||
<li><code>--!gpu</code> を指定しても、GPU カーネルを初期化できない場合は CPU カーネル、さらに MoonSharp の順で
|
||||
フォールバックします。</li>
|
||||
<li><code>--!cpu</code> を指定してもカーネル条件に合わないスクリプトは、ほかのエンジンで実行されます。</li>
|
||||
<li>MoonSharp では <code>tempbuffer</code> への描画合成を GPU で実行し、GPU を利用できない環境では
|
||||
CPU の合成へ自動的に切り替わります。丸めの違いにより、合成の結果はエンジン間で
|
||||
ごく僅かに異なることがあります。</li>
|
||||
</ul>
|
||||
|
||||
<div class="warn">
|
||||
GPU カーネルは float32 精度で計算するため、MoonSharp / CPU カーネルとわずかに結果が異なることがあります。
|
||||
厳密に一致させたい場合は CPU カーネルかネイティブを使ってください。
|
||||
</div>
|
||||
|
||||
<div class="pager">
|
||||
<a href="pixels.html">← ピクセル操作</a>
|
||||
<a href="directives.html">パラメータ指定子 →</a>
|
||||
</div>
|
||||
|
||||
</main>
|
||||
<script src="assets/nav.js"></script>
|
||||
</body>
|
||||
</html>
|
||||
@@ -0,0 +1,104 @@
|
||||
<!DOCTYPE html>
|
||||
<html lang="ja">
|
||||
<head>
|
||||
<meta charset="utf-8">
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1">
|
||||
<title>導入と使い方 | Lua スクリプト for YMM4</title>
|
||||
<link rel="stylesheet" href="assets/style.css">
|
||||
</head>
|
||||
<body>
|
||||
<button id="navtoggle" aria-label="メニュー">☰</button>
|
||||
<nav id="sidebar"></nav>
|
||||
<main>
|
||||
|
||||
<h1>導入と使い方</h1>
|
||||
|
||||
<p>
|
||||
「Lua スクリプト」は映像エフェクトの一種です。アイテム(テキスト・画像・図形など)に対して、
|
||||
他のエフェクトと同じように追加して使います。
|
||||
</p>
|
||||
|
||||
<h2>エフェクトを追加する</h2>
|
||||
|
||||
<ol>
|
||||
<li>タイムライン上のアイテムを選択します。</li>
|
||||
<li>プロパティエリアのエフェクト欄で、フィルタ効果の追加から「Lua スクリプト」を選びます。
|
||||
検索欄では <code>lua</code> / <code>script</code> / <code>スクリプト</code> / <code>アニメーション効果</code> などのキーワードでも見つかります。</li>
|
||||
<li>追加すると、スクリプト入力欄と、トラックバーやチェックボックスなどのパラメータが表示されます。</li>
|
||||
</ol>
|
||||
|
||||
<h2>スクリプトエディタ</h2>
|
||||
|
||||
<p>スクリプト欄はコードエディタになっており、次の機能があります。</p>
|
||||
|
||||
<ul>
|
||||
<li>シンタックスハイライト: Lua の構文に色が付きます。</li>
|
||||
<li>入力補完: 識別子を入力すると候補が表示されます。<code>obj.</code> や <code>anim.</code> のように
|
||||
ドットを入力すると、そのテーブルのメンバーだけが候補に出ます。スクリプト内で定義した関数も補完されます。</li>
|
||||
<li>折りたたみ: <code>function ... end</code> などのブロックを折りたためます。</li>
|
||||
<li>エラー表示: 構文エラー・実行時エラー・タイムアウトが起きると、該当行に赤い波線で警告が表示されます。</li>
|
||||
</ul>
|
||||
|
||||
<h2>実行のしくみ</h2>
|
||||
|
||||
<p>
|
||||
スクリプトは表示中の各フレームで 1 回ずつ実行されます。
|
||||
プラグインは実行前に <code>obj</code>・<code>scene</code>・<code>ymm4</code> などへ現在の値を流し込み、
|
||||
スクリプトの実行後に <code>obj</code> の値を読み戻して描画へ反映します。
|
||||
</p>
|
||||
|
||||
<div class="note">
|
||||
グローバル変数(自分で <code>x = 1</code> のように作った変数)の状態はフレームをまたいで保持されません。
|
||||
毎フレーム、組み込み以外のグローバルはリセットされます。前のフレームの値を覚えておくことはできません。
|
||||
時間に応じた変化は <code>time</code> や <code>obj.t</code> から計算してください。
|
||||
</div>
|
||||
|
||||
<h2>はじめてのスクリプト</h2>
|
||||
|
||||
<p>既定のフェードインを、少しずつ拡張してみます。</p>
|
||||
|
||||
<h3>1. 不透明度を変える</h3>
|
||||
<pre><code>obj.alpha = math.min(time * 255, 255)</code></pre>
|
||||
|
||||
<h3>2. 横に動かす</h3>
|
||||
<pre><code>obj.alpha = math.min(time * 255, 255)
|
||||
obj.x = obj.x + math.sin(time * anim.tau) * 100</code></pre>
|
||||
|
||||
<h3>3. トラックバーで振幅を変える</h3>
|
||||
<p>
|
||||
パラメータパネルの <code>Track0</code> スライダーの値が <code>obj.track0</code> として読めます。
|
||||
スライダーを動かすと、揺れの大きさが変わります。
|
||||
</p>
|
||||
<pre><code>obj.alpha = math.min(time * 255, 255)
|
||||
obj.x = obj.x + math.sin(time * anim.tau) * obj.track0</code></pre>
|
||||
|
||||
<h2>パラメータパネル</h2>
|
||||
|
||||
<p>
|
||||
既定では <code>Track0</code> ~ <code>Track3</code> の 4 本のトラックバーが表示されます。
|
||||
チェックボックス(<code>Check0</code> ~ <code>Check3</code>)と色(<code>Color</code>)は、
|
||||
スクリプトでそれらを使うか、指定子で宣言したときに表示されます。
|
||||
表示条件と既定値・名前・範囲の指定方法は <a href="directives.html">パラメータ指定子</a> を参照してください。
|
||||
</p>
|
||||
|
||||
<table>
|
||||
<tr><th>UI</th><th>スクリプトでの読み取り</th><th>型</th></tr>
|
||||
<tr><td>Track0 ~ Track3</td><td><code>obj.track0</code> ~ <code>obj.track3</code></td><td>数値</td></tr>
|
||||
<tr><td>Check0 ~ Check3</td><td><code>obj.check0</code> ~ <code>obj.check3</code></td><td>真偽値</td></tr>
|
||||
<tr><td>Color</td><td><code>color</code></td><td>数値 (0xRRGGBB)</td></tr>
|
||||
</table>
|
||||
|
||||
<div class="warn">
|
||||
スクリプトの実行には 5 秒のタイムアウトがあります。無限ループや非常に重い処理は中断されます。
|
||||
詳しくは <a href="limits.html">制限事項とトラブル</a> を参照してください。
|
||||
</div>
|
||||
|
||||
<div class="pager">
|
||||
<a href="index.html">← 概要</a>
|
||||
<a href="lua-basics.html">Lua の基礎 →</a>
|
||||
</div>
|
||||
|
||||
</main>
|
||||
<script src="assets/nav.js"></script>
|
||||
</body>
|
||||
</html>
|
||||
+116
@@ -0,0 +1,116 @@
|
||||
<!DOCTYPE html>
|
||||
<html lang="ja">
|
||||
<head>
|
||||
<meta charset="utf-8">
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1">
|
||||
<title>グローバル変数 | Lua スクリプト for YMM4</title>
|
||||
<link rel="stylesheet" href="assets/style.css">
|
||||
</head>
|
||||
<body>
|
||||
<button id="navtoggle" aria-label="メニュー">☰</button>
|
||||
<nav id="sidebar"></nav>
|
||||
<main>
|
||||
|
||||
<h1>グローバル変数</h1>
|
||||
|
||||
<p>
|
||||
スクリプトのグローバルスコープから直接参照できる変数です。
|
||||
これらは毎フレーム、実行前にプラグインが設定します。値は読み取り専用です
|
||||
(書き換えても描画には反映されません。描画を変えるには <a href="obj.html"><code>obj</code></a> を使います)。
|
||||
</p>
|
||||
|
||||
<h2>時間とフレーム</h2>
|
||||
|
||||
<table>
|
||||
<tr><th>変数</th><th>型</th><th>説明</th></tr>
|
||||
<tr><td><code>time</code></td><td>数値</td><td>アイテム先頭からの経過時間(秒)。<code>obj.time</code> と同じ</td></tr>
|
||||
<tr><td><code>frame</code></td><td>整数</td><td>アイテム先頭からの現在フレーム番号。<code>obj.frame</code> と同じ</td></tr>
|
||||
<tr><td><code>totalframe</code></td><td>整数</td><td>アイテムの総フレーム数。<code>obj.totalframe</code> と同じ</td></tr>
|
||||
<tr><td><code>framerate</code></td><td>整数</td><td>フレームレート(fps)。<code>obj.framerate</code> と同じ</td></tr>
|
||||
<tr><td><code>timelineframe</code></td><td>整数</td><td>タイムライン先頭からの絶対フレーム番号</td></tr>
|
||||
<tr><td><code>timelinetime</code></td><td>数値</td><td>タイムライン基準の現在時間(秒)</td></tr>
|
||||
<tr><td><code>layer</code></td><td>整数</td><td>配置されているレイヤー番号。<code>obj.layer</code> と同じ</td></tr>
|
||||
</table>
|
||||
|
||||
<p>
|
||||
<code>time</code> はアニメーションの基準としてもっともよく使います。
|
||||
アイテム内の進行割合(0.0 ~ 1.0)が欲しいときは <a href="obj.html"><code>obj.t</code></a> を使います。
|
||||
</p>
|
||||
|
||||
<pre><code>obj.rz = time * 90
|
||||
obj.alpha = obj.t * 255</code></pre>
|
||||
|
||||
<h2>色</h2>
|
||||
|
||||
<table>
|
||||
<tr><th>変数</th><th>型</th><th>説明</th></tr>
|
||||
<tr><td><code>color</code></td><td>数値</td><td>Color パラメータの色を <code>0xRRGGBB</code> の整数で表す</td></tr>
|
||||
</table>
|
||||
|
||||
<p>
|
||||
<code>color</code> は、Color パラメータが表示されているとき(スクリプトで <code>color</code> を使うか、
|
||||
<a href="directives.html"><code>--color@</code></a> 指定子で宣言したとき)にのみ設定されます。
|
||||
各成分は次のように取り出せます。
|
||||
</p>
|
||||
|
||||
<pre><code>local r = bit32.rshift(bit32.band(color, 0xFF0000), 16)
|
||||
local g = bit32.rshift(bit32.band(color, 0x00FF00), 8)
|
||||
local b = bit32.band(color, 0x0000FF)</code></pre>
|
||||
|
||||
<h2>テーブル</h2>
|
||||
|
||||
<p>主要な機能は、グローバルに置かれた次のテーブルにまとまっています。</p>
|
||||
|
||||
<table>
|
||||
<tr><th>テーブル</th><th>役割</th><th>参照</th></tr>
|
||||
<tr><td><code>obj</code></td><td>描画対象の座標・回転・拡大率・不透明度と各種関数</td><td><a href="obj.html">obj</a> / <a href="obj-functions.html">obj の関数</a></td></tr>
|
||||
<tr><td><code>anim</code></td><td>補間・波・ノイズ・色変換などのアニメーション関数</td><td><a href="anim.html">anim</a></td></tr>
|
||||
<tr><td><code>scene</code></td><td>シーンの解像度と、シーン全体で共有する値</td><td><a href="scene-ymm4.html">scene</a></td></tr>
|
||||
<tr><td><code>ymm4</code></td><td>グループ・タイムライン・再生状態などの環境情報</td><td><a href="scene-ymm4.html">ymm4</a></td></tr>
|
||||
</table>
|
||||
|
||||
<h2>グローバル関数(AviUtl 互換)</h2>
|
||||
|
||||
<p>
|
||||
以下の関数はグローバルスコープから直接呼び出せます。
|
||||
MoonSharp とネイティブのどちらのエンジンでも同一の結果を返します。
|
||||
</p>
|
||||
|
||||
<table>
|
||||
<tr><th>関数</th><th>説明</th></tr>
|
||||
<tr><td><code>RGB(r, g, b)</code></td><td>RGB 各要素(0 ~ 255)を 1 つの色情報(<code>0xRRGGBB</code>)へ合成</td></tr>
|
||||
<tr><td><code>RGB(col)</code></td><td>色情報を <code>r, g, b</code> の 3 値へ分解</td></tr>
|
||||
<tr><td><code>RGB(r1, g1, b1, r2, g2, b2)</code></td><td>オブジェクトの時間経過(<code>obj.time / obj.totaltime</code>)で一色目から二色目へ直線的に変化する色情報を返す</td></tr>
|
||||
<tr><td><code>HSV(h, s, v)</code> / <code>HSV(col)</code> / <code>HSV(h1, s1, v1, h2, s2, v2)</code></td><td>色相(0 ~ 360)・彩度(0 ~ 100)・明度(0 ~ 100)と色情報の相互変換。引数の意味は <code>RGB()</code> と同様</td></tr>
|
||||
<tr><td><code>OR(a, b)</code> / <code>AND(a, b)</code> / <code>XOR(a, b)</code></td><td>32bit 整数のビット演算。小数は 0.5 ちょうどまでを切り捨てて整数化(2.50 → 2、2.51 → 3)</td></tr>
|
||||
<tr><td><code>SHIFT(a, shift)</code></td><td>算術シフト。<code>shift</code> が正で左シフト、負で右シフト</td></tr>
|
||||
<tr><td><code>debug_print(text)</code></td><td>文字列を <code>OutputDebugString()</code> へ送信。DebugView などで確認できる。スクリプトの実行エラーも自動で送信される</td></tr>
|
||||
</table>
|
||||
|
||||
<pre><code>col = RGB(64, 192, 255) -- 0x40C0FF
|
||||
r, g, b = RGB(0x0080FF) -- 0, 128, 255
|
||||
col = HSV(60, 100, 100) -- 0xFFFF00
|
||||
result = SHIFT(5, 3) -- 40
|
||||
debug_print(string.format("x = %d", obj.x))</code></pre>
|
||||
|
||||
<p>標準ライブラリのテーブルもグローバルに置かれています。</p>
|
||||
|
||||
<table>
|
||||
<tr><th>テーブル</th><th>役割</th></tr>
|
||||
<tr><td><code>math</code></td><td>数学関数</td></tr>
|
||||
<tr><td><code>string</code></td><td>文字列操作</td></tr>
|
||||
<tr><td><code>table</code></td><td>テーブル操作</td></tr>
|
||||
<tr><td><code>bit32</code></td><td>ビット演算</td></tr>
|
||||
</table>
|
||||
|
||||
<p>これらの中身は <a href="stdlib.html">標準ライブラリ</a> にまとめています。</p>
|
||||
|
||||
<div class="pager">
|
||||
<a href="stdlib.html">← 標準ライブラリ</a>
|
||||
<a href="obj.html">obj オブジェクト →</a>
|
||||
</div>
|
||||
|
||||
</main>
|
||||
<script src="assets/nav.js"></script>
|
||||
</body>
|
||||
</html>
|
||||
+49
-598
@@ -3,628 +3,79 @@
|
||||
<head>
|
||||
<meta charset="utf-8">
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1">
|
||||
<title>Luaスクリプト for YMM4 サンプル集</title>
|
||||
<title>概要 | Lua スクリプト for YMM4</title>
|
||||
<link rel="stylesheet" href="assets/style.css">
|
||||
</head>
|
||||
<body>
|
||||
<button id="navtoggle" aria-label="メニュー">☰</button>
|
||||
<nav id="sidebar"></nav>
|
||||
<main>
|
||||
|
||||
<img src="LuaScript.png" alt="Luaスクリプト for YMM4" width="640">
|
||||
|
||||
<h1>Luaスクリプト for YMM4 サンプル集</h1>
|
||||
<h1>Lua スクリプト for YMM4</h1>
|
||||
|
||||
<p>
|
||||
YukkuriMovieMaker4 の「Luaスクリプト」映像エフェクトで使えるサンプルと、
|
||||
利用可能な変数・関数・定数の一覧をまとめたページです。
|
||||
各サンプルはエフェクトのスクリプト欄にそのまま貼り付けて利用できます。
|
||||
スクリプトエンジンは MoonSharp (Lua 5.2 互換) です。
|
||||
YukkuriMovieMaker4 の映像エフェクト「Lua スクリプト」の公式ドキュメントです。
|
||||
このエフェクトでは、Lua のコードで映像を毎フレーム加工できます。座標・回転・拡大率・不透明度の制御から、
|
||||
ピクセル単位の画像処理、図形やテキストの生成、ほかのエフェクトの呼び出しまでを、1 つのスクリプト欄で行えます。
|
||||
</p>
|
||||
|
||||
<p>
|
||||
変数・関数の詳細な仕様は、スクリプトエディタのヘルプ、または
|
||||
<code>docs/LuaScript.ja-jp.txt</code> を参照してください。
|
||||
標準のスクリプトエンジンは LuaJIT で実行するネイティブレーンで、
|
||||
決まった形のピクセル処理は CPU カーネルや GPU カーネルへ変換されます。
|
||||
GPU カーネルは初回に CPU カーネルとの一致を検証したうえで自動選択します。
|
||||
Lua 5.2 互換の MoonSharp はフォールバックとして使われます。
|
||||
詳しくは<a href="engines.html">エンジンと高速化</a>を参照してください。
|
||||
</p>
|
||||
|
||||
<hr>
|
||||
<div class="note">
|
||||
このドキュメントは、プラグインの実装そのものに基づいて記述しています。
|
||||
変数・関数・定数の名前と挙動は、スクリプトエディタの入力補完に表示されるものと一致します。
|
||||
</div>
|
||||
|
||||
<h2>このドキュメントの構成</h2>
|
||||
|
||||
<h2>目次</h2>
|
||||
<nav>
|
||||
<ul>
|
||||
<li><a href="#about">サンプルの読み方</a></li>
|
||||
<li><a href="#basic">1. 基本</a></li>
|
||||
<li><a href="#motion">2. 座標と動き</a></li>
|
||||
<li><a href="#rotation">3. 回転</a></li>
|
||||
<li><a href="#scale">4. 拡大・変形</a></li>
|
||||
<li><a href="#alpha">5. 不透明度・フェード</a></li>
|
||||
<li><a href="#ease">6. anim 補間・イージング</a></li>
|
||||
<li><a href="#range">7. anim 範囲・周期</a></li>
|
||||
<li><a href="#vector">8. anim ベクトル・幾何</a></li>
|
||||
<li><a href="#noise">9. anim ノイズ・乱数</a></li>
|
||||
<li><a href="#animcolor">10. anim 色</a></li>
|
||||
<li><a href="#const">11. anim 定数</a></li>
|
||||
<li><a href="#getobject">12. 他オブジェクトの参照 (obj.getobject)</a></li>
|
||||
<li><a href="#pixel">13. ピクセル操作</a></li>
|
||||
<li><a href="#scene">14. シーン情報 (scene)</a></li>
|
||||
<li><a href="#ymm4">15. 環境・メタ情報 (ymm4)</a></li>
|
||||
<li><a href="#globals">16. グローバル変数</a></li>
|
||||
<li><a href="#stdlib">17. 標準ライブラリ</a></li>
|
||||
<li><a href="#reference">クイックリファレンス</a></li>
|
||||
<li><a href="getting-started.html">導入と使い方</a> … エフェクトの追加方法と、エディタ・パラメータパネルの使い方を説明します。</li>
|
||||
<li><a href="lua-basics.html">Lua の基礎</a> … 変数・型・制御構文・関数・テーブルなど、Lua 言語そのものを学べます。</li>
|
||||
<li><a href="obj.html">obj オブジェクト</a> … 座標・回転・拡大率・不透明度など、描画を制御する中心のテーブルです。</li>
|
||||
<li><a href="anim.html">anim ライブラリ</a> … イージング・波・ノイズ・色変換など、アニメーション用の関数をまとめています。</li>
|
||||
<li><a href="pixels.html">ピクセル操作</a> … 画像を 1 ピクセルずつ読み書きする方法と注意点を説明します。</li>
|
||||
<li><a href="samples.html">サンプル集</a> … そのまま貼り付けて使えるスクリプトを集めています。</li>
|
||||
</ul>
|
||||
</nav>
|
||||
|
||||
<hr>
|
||||
<h2>最小の例</h2>
|
||||
|
||||
<h2 id="about">サンプルの読み方</h2>
|
||||
<p>
|
||||
スクリプト内では、変更可能な <code>obj</code> の値(座標・拡大率・回転・不透明度など)を
|
||||
書き換えると描画に反映されます。読み戻されるのは
|
||||
<code>x, y, z, ox, oy, zoom, aspect, alpha, rx, ry, rz</code>
|
||||
(およびラジアン版 <code>rxr, ryr, rzr</code>、独立スケール <code>sx, sy</code>)です。
|
||||
</p>
|
||||
<p>
|
||||
<code>time</code> はアイテム基準の経過秒数、<code>obj.t</code> はアイテム内の進行割合
|
||||
(0.0 ~ 1.0) です。グローバル変数の状態はフレーム間で保持されません。
|
||||
<code>math.random</code> は毎フレーム同じシードで初期化されるため、同一フレームでは
|
||||
同じ値を返します。安定した乱数が必要な場合は <code>anim.rand</code> を使います。
|
||||
</p>
|
||||
<p>エフェクトを追加した直後に入っている既定のスクリプトは、フェードインです。</p>
|
||||
|
||||
<hr>
|
||||
|
||||
<h2 id="basic">1. 基本</h2>
|
||||
|
||||
<h3>1-1. フェードイン (デフォルトスクリプト)</h3>
|
||||
<pre><code>obj.alpha = math.min(time * 255, 255)</code></pre>
|
||||
|
||||
<h3>1-2. フェードアウト</h3>
|
||||
<pre><code>obj.alpha = math.max((obj.totalframe - obj.frame) / obj.framerate * 255, 0)</code></pre>
|
||||
|
||||
<h3>1-3. Track0 で不透明度を制御</h3>
|
||||
<pre><code>obj.alpha = obj.track0</code></pre>
|
||||
|
||||
<h3>1-4. 時間に応じて回転</h3>
|
||||
<pre><code>obj.rz = time * 90</code></pre>
|
||||
|
||||
<h3>1-5. Track0 でズームを制御</h3>
|
||||
<pre><code>obj.zoom = obj.zoom * (1 + obj.track0 / 100)</code></pre>
|
||||
|
||||
<hr>
|
||||
|
||||
<h2 id="motion">2. 座標と動き</h2>
|
||||
|
||||
<h3>2-1. 左右の揺れ</h3>
|
||||
<p>Track0 を振幅(px)、Track1 を周波数(回/秒)として使います。</p>
|
||||
<pre><code>local amp = obj.track0
|
||||
local freq = obj.track1
|
||||
obj.x = obj.x + math.sin(time * anim.tau * freq) * amp</code></pre>
|
||||
|
||||
<h3>2-2. 円運動</h3>
|
||||
<pre><code>local r = obj.track0
|
||||
local dx, dy = anim.polar(r, time * 90)
|
||||
obj.x = obj.x + dx
|
||||
obj.y = obj.y + dy</code></pre>
|
||||
|
||||
<h3>2-3. バウンド (跳ねる)</h3>
|
||||
<pre><code>local h = obj.track0
|
||||
obj.y = obj.y - anim.bounce(anim.pingpong(time, 1)) * h</code></pre>
|
||||
|
||||
<h3>2-4. ゆらぎ (ノイズによる手ぶれ風)</h3>
|
||||
<pre><code>obj.x = obj.x + (anim.noise(time * 2, 0, 0) - 0.5) * 20
|
||||
obj.y = obj.y + (anim.noise(0, time * 2, 0) - 0.5) * 20
|
||||
obj.rz = (anim.noise(0, 0, time * 2) - 0.5) * 10</code></pre>
|
||||
|
||||
<h3>2-5. 中心オフセットを基準に振り子運動</h3>
|
||||
<p>回転中心 <code>ox, oy</code> をずらして振り子のように揺らします。</p>
|
||||
<pre><code>obj.oy = -obj.hh
|
||||
obj.rz = math.sin(time * anim.tau) * 30</code></pre>
|
||||
|
||||
<hr>
|
||||
|
||||
<h2 id="rotation">3. 回転</h2>
|
||||
|
||||
<h3>3-1. 度とラジアン</h3>
|
||||
<p>
|
||||
<code>rx, ry, rz</code> は度、<code>rxr, ryr, rzr</code> はラジアンです。
|
||||
ラジアン版を変更するとそちらが優先して反映されます。
|
||||
</p>
|
||||
<pre><code>obj.rzr = time * anim.tau</code></pre>
|
||||
|
||||
<h3>3-2. Y軸回転で立体的に回す</h3>
|
||||
<pre><code>obj.ry = time * 180</code></pre>
|
||||
|
||||
<h3>3-3. 加速しながら回転 (イージング)</h3>
|
||||
<pre><code>obj.rz = anim.ease_in(obj.t) * 360</code></pre>
|
||||
|
||||
<hr>
|
||||
|
||||
<h2 id="scale">4. 拡大・変形</h2>
|
||||
|
||||
<h3>4-1. 弾むように登場 (スケールイン)</h3>
|
||||
<pre><code>local p = anim.duration(time, 0.3)
|
||||
obj.zoom = obj.zoom * anim.elastic(p)</code></pre>
|
||||
|
||||
<h3>4-2. アスペクト比で横伸び・縦伸び</h3>
|
||||
<p>
|
||||
<code>aspect</code> は正で横方向に縮小、負で縦方向に縮小します。
|
||||
</p>
|
||||
<pre><code>obj.aspect = math.sin(time * anim.tau) * 0.5</code></pre>
|
||||
|
||||
<h3>4-3. X・Y を独立して拡大 (sx, sy)</h3>
|
||||
<p>ぷにぷにと潰れる動きを <code>sx, sy</code> で表現します。</p>
|
||||
<pre><code>local s = math.sin(time * anim.tau * 2) * 0.2
|
||||
obj.sx = 1 + s
|
||||
obj.sy = 1 - s</code></pre>
|
||||
|
||||
<hr>
|
||||
|
||||
<h2 id="alpha">5. 不透明度・フェード</h2>
|
||||
|
||||
<h3>5-1. 遅延フェードイン</h3>
|
||||
<pre><code>local p = anim.duration(anim.delay(time, 0.5), 1)
|
||||
obj.alpha = p * 255</code></pre>
|
||||
|
||||
<h3>5-2. 点滅 (矩形波)</h3>
|
||||
<pre><code>obj.alpha = anim.square(time, 4) * 255</code></pre>
|
||||
|
||||
<h3>5-3. 滑らかな明滅 (正弦波)</h3>
|
||||
<pre><code>obj.alpha = anim.oscillate(time, 64, 255, 1)</code></pre>
|
||||
|
||||
<hr>
|
||||
|
||||
<h2 id="ease">6. anim 補間・イージング</h2>
|
||||
|
||||
<h3>6-1. 2点間をイージングで移動</h3>
|
||||
<pre><code>local tx, ty = 200, -100
|
||||
local p = anim.ease_in_out(obj.t)
|
||||
obj.x = anim.lerp(obj.x, tx, p)
|
||||
obj.y = anim.lerp(obj.y, ty, p)</code></pre>
|
||||
|
||||
<h3>6-2. 行き過ぎてから戻る (back)</h3>
|
||||
<pre><code>obj.x = obj.x + anim.back(obj.t) * 200</code></pre>
|
||||
|
||||
<h3>6-3. しきい値で切り替え (step / smoothstep)</h3>
|
||||
<pre><code>obj.alpha = anim.smoothstep(0, 0.5, obj.t) * 255</code></pre>
|
||||
|
||||
<p>補間・イージング系関数の一覧です。</p>
|
||||
<table border="1">
|
||||
<tr><th>関数</th><th>説明</th></tr>
|
||||
<tr><td>anim.lerp(a, b, t)</td><td>a と b を t (0.0~1.0) で線形補間</td></tr>
|
||||
<tr><td>anim.smoothstep(e0, e1, x)</td><td>e0~e1 をエルミート補間で滑らかに遷移</td></tr>
|
||||
<tr><td>anim.smootherstep(e0, e1, x)</td><td>2次導関数まで連続な、より滑らかな遷移</td></tr>
|
||||
<tr><td>anim.ease_in(t)</td><td>2次イーズイン (加速)</td></tr>
|
||||
<tr><td>anim.ease_out(t)</td><td>2次イーズアウト (減速)</td></tr>
|
||||
<tr><td>anim.ease_in_out(t)</td><td>2次イーズイン・アウト (加速後減速)</td></tr>
|
||||
<tr><td>anim.elastic(t)</td><td>弾むようなスプリングイージング</td></tr>
|
||||
<tr><td>anim.back(t)</td><td>行き過ぎてから戻るイージング</td></tr>
|
||||
<tr><td>anim.bounce(t)</td><td>バウンドするイージング</td></tr>
|
||||
<tr><td>anim.step(edge, x)</td><td>x が edge 以上なら 1.0、未満なら 0.0</td></tr>
|
||||
<tr><td>anim.bezier(t, p0, p1, p2, p3)</td><td>t における3次ベジェ曲線の値</td></tr>
|
||||
</table>
|
||||
|
||||
<hr>
|
||||
|
||||
<h2 id="range">7. anim 範囲・周期</h2>
|
||||
|
||||
<h3>7-1. 値の範囲変換 (map)</h3>
|
||||
<pre><code>obj.rz = anim.map(obj.track0, 0, 100, -180, 180)</code></pre>
|
||||
|
||||
<h3>7-2. 三角波で往復</h3>
|
||||
<pre><code>obj.x = obj.x + (anim.triangle(time, 1) - 0.5) * 200</code></pre>
|
||||
|
||||
<p>範囲・周期系関数の一覧です。</p>
|
||||
<table border="1">
|
||||
<tr><th>関数</th><th>説明</th></tr>
|
||||
<tr><td>anim.clamp(v, lo, hi)</td><td>v を lo ~ hi の範囲に収める</td></tr>
|
||||
<tr><td>anim.map(v, a1, b1, a2, b2)</td><td>範囲 a1~b1 の v を a2~b2 に変換</td></tr>
|
||||
<tr><td>anim.norm(v, lo, hi)</td><td>v が lo~hi のどの割合 (0.0~1.0) かを取得</td></tr>
|
||||
<tr><td>anim.wrap(v, lo, hi)</td><td>v を lo ~ hi でループさせる</td></tr>
|
||||
<tr><td>anim.pingpong(t, len)</td><td>0 ~ len を往復する値</td></tr>
|
||||
<tr><td>anim.sign(v)</td><td>符号 (正=1, 負=-1, ゼロ=0)</td></tr>
|
||||
<tr><td>anim.fract(v)</td><td>小数部分のみを取得</td></tr>
|
||||
<tr><td>anim.oscillate(t, lo, hi, freq)</td><td>freq の周波数で lo~hi を正弦波で往復</td></tr>
|
||||
<tr><td>anim.triangle(t, freq)</td><td>freq の周波数で 0.0~1.0 を往復する三角波</td></tr>
|
||||
<tr><td>anim.square(t, freq)</td><td>freq の周波数で 1.0 と 0.0 を切り替える矩形波</td></tr>
|
||||
<tr><td>anim.duration(t, dur)</td><td>時間 dur に対する割合 (0.0~1.0, clamp あり)</td></tr>
|
||||
<tr><td>anim.delay(t, d)</td><td>時間 d 経過後から開始する時間 (0以下は0)</td></tr>
|
||||
</table>
|
||||
|
||||
<hr>
|
||||
|
||||
<h2 id="vector">8. anim ベクトル・幾何</h2>
|
||||
|
||||
<h3>8-1. 座標を回転させる</h3>
|
||||
<pre><code>local rx, ry = anim.rotate(obj.track0, 0, time * 90)
|
||||
obj.x = obj.x + rx
|
||||
obj.y = obj.y + ry</code></pre>
|
||||
|
||||
<h3>8-2. 2点間の距離で挙動を変える</h3>
|
||||
<pre><code>local d = anim.dist(obj.x, obj.y, 0, 0)
|
||||
obj.alpha = anim.clamp(255 - d, 0, 255)</code></pre>
|
||||
|
||||
<p>ベクトル・幾何系関数の一覧です。</p>
|
||||
<table border="1">
|
||||
<tr><th>関数</th><th>説明</th></tr>
|
||||
<tr><td>anim.len(x, y)</td><td>ベクトル (x, y) の長さ</td></tr>
|
||||
<tr><td>anim.dist(x1, y1, x2, y2)</td><td>2点間の距離</td></tr>
|
||||
<tr><td>anim.dot(x1, y1, x2, y2)</td><td>2ベクトルの内積</td></tr>
|
||||
<tr><td>anim.normalize(x, y)</td><td>正規化した方向ベクトル (Tuple で返却)</td></tr>
|
||||
<tr><td>anim.polar(r, a)</td><td>半径 r・角度 a(度) から移動量 (x, y)</td></tr>
|
||||
<tr><td>anim.rotate(x, y, a)</td><td>(x, y) を a(度) 回転させた座標</td></tr>
|
||||
</table>
|
||||
|
||||
<hr>
|
||||
|
||||
<h2 id="noise">9. anim ノイズ・乱数</h2>
|
||||
|
||||
<h3>9-1. 安定した乱数で個体差をつける</h3>
|
||||
<p>
|
||||
<code>anim.rand</code> はシード引数に基づく決定的な乱数です。レイヤー番号をシードにすると
|
||||
オブジェクトごとに異なる固定値が得られます。
|
||||
</p>
|
||||
<pre><code>local offset = anim.rand(-50, 50, obj.layer)
|
||||
obj.x = obj.x + offset</code></pre>
|
||||
|
||||
<h3>9-2. ノイズで揺らぐ不透明度</h3>
|
||||
<pre><code>obj.alpha = anim.noise(time, obj.layer, 0) * 255</code></pre>
|
||||
|
||||
<table border="1">
|
||||
<tr><th>関数</th><th>説明</th></tr>
|
||||
<tr><td>anim.noise(x, y, z)</td><td>1~3次元の滑らかなノイズ (0.0~1.0)</td></tr>
|
||||
<tr><td>anim.rand(min, max, s)</td><td>シード s に基づく安定した乱数</td></tr>
|
||||
</table>
|
||||
|
||||
<hr>
|
||||
|
||||
<h2 id="animcolor">10. anim 色</h2>
|
||||
|
||||
<h3>10-1. 時間で色相を回す (虹色)</h3>
|
||||
<pre><code>local hue = anim.wrap(time * 60, 0, 360)
|
||||
local cr, cg, cb = anim.hsv_to_rgb(hue, 1, 1)
|
||||
local pd = obj.getpixeldata()
|
||||
local n = pd.width * pd.height
|
||||
for i = 0, n - 1 do
|
||||
local base = i * 4
|
||||
pd:set(base + 1, pd:get(base + 1) * cr / 255)
|
||||
pd:set(base + 2, pd:get(base + 2) * cg / 255)
|
||||
pd:set(base + 3, pd:get(base + 3) * cb / 255)
|
||||
end</code></pre>
|
||||
|
||||
<table border="1">
|
||||
<tr><th>関数</th><th>説明</th></tr>
|
||||
<tr><td>anim.hsv_to_rgb(h, s, v)</td><td>HSV (色相0~360, 彩度0~1, 明度0~1) を RGB に変換</td></tr>
|
||||
<tr><td>anim.rgb_to_hsv(r, g, b)</td><td>RGB (0~255) を HSV に変換</td></tr>
|
||||
</table>
|
||||
|
||||
<hr>
|
||||
|
||||
<h2 id="const">11. anim 定数</h2>
|
||||
<table border="1">
|
||||
<tr><th>定数</th><th>説明</th></tr>
|
||||
<tr><td>anim.tau</td><td>円周率の2倍 (math.pi * 2)</td></tr>
|
||||
<tr><td>anim.e</td><td>ネイピア数 (math.exp(1))</td></tr>
|
||||
<tr><td>anim.phi</td><td>黄金比 ((1 + math.sqrt(5)) / 2)</td></tr>
|
||||
<tr><td>anim.sqrt2</td><td>2の平方根 (math.sqrt(2))</td></tr>
|
||||
</table>
|
||||
|
||||
<hr>
|
||||
|
||||
<h2 id="getobject">12. 他オブジェクトの参照 (obj.getobject)</h2>
|
||||
|
||||
<p>
|
||||
<code>obj.getobject(tag [, frame])</code> は、対象アイテムの「備考」欄に入力した文字列を
|
||||
タグとして、そのアイテムの描画情報を取得します。備考欄はプロパティエリアの上側にあります。
|
||||
第2引数 <code>frame</code> を指定すると、そのタイムラインフレーム時点の値を取得します
|
||||
(省略時は現在フレーム)。返り値は対象アイテム自身の座標・回転・拡大率であり、
|
||||
グループ制御・カメラ制御による変形は含みません。一致するアイテムが無い場合は
|
||||
<code>nil</code> を返します。同じタグのアイテムが複数あるときは、対象フレームで
|
||||
表示中のものを優先します。
|
||||
<code>obj.alpha</code> に値を代入すると不透明度が変わります。<code>time</code> はアイテム先頭からの経過秒数です。
|
||||
スクリプトはフレームごとに実行され、<code>obj</code> の値を書き換えると描画へ反映されます。
|
||||
</p>
|
||||
|
||||
<h3>12-1. 発射元の座標に合わせる</h3>
|
||||
<pre><code>local src = obj.getobject("routersys")
|
||||
if src then
|
||||
obj.x = src.x
|
||||
obj.y = src.y
|
||||
end</code></pre>
|
||||
<h2>できることの全体像</h2>
|
||||
|
||||
<h3>12-2. 発射元へ向かって移動する</h3>
|
||||
<pre><code>local target = obj.getobject("routersys")
|
||||
if target then
|
||||
local p = anim.ease_in_out(obj.t)
|
||||
obj.x = anim.lerp(obj.x, target.x, p)
|
||||
obj.y = anim.lerp(obj.y, target.y, p)
|
||||
end</code></pre>
|
||||
|
||||
<h3>12-3. 発射元へ向きながら移動する (ファンネル風)</h3>
|
||||
<pre><code>local target = obj.getobject("routersys")
|
||||
if target then
|
||||
local p = anim.ease_in_out(obj.t)
|
||||
local nx = anim.lerp(obj.x, target.x, p)
|
||||
local ny = anim.lerp(obj.y, target.y, p)
|
||||
obj.rz = math.deg(math.atan2(target.y - obj.y, target.x - obj.x))
|
||||
obj.x = nx
|
||||
obj.y = ny
|
||||
end</code></pre>
|
||||
|
||||
<h3>12-4. 一定速度で接近し、到達したら停止</h3>
|
||||
<pre><code>local target = obj.getobject("routersys")
|
||||
if target then
|
||||
local dx = target.x - obj.x
|
||||
local dy = target.y - obj.y
|
||||
local dist = anim.len(dx, dy)
|
||||
if dist > 0 then
|
||||
local step = math.min(dist, obj.track0 * obj.time)
|
||||
obj.x = obj.x + dx / dist * step
|
||||
obj.y = obj.y + dy / dist * step
|
||||
end
|
||||
end</code></pre>
|
||||
|
||||
<h3>12-5. 表示中のときだけ追従する</h3>
|
||||
<pre><code>local target = obj.getobject("routersys")
|
||||
if target and target.exist then
|
||||
obj.x = target.x
|
||||
obj.y = target.y
|
||||
end</code></pre>
|
||||
|
||||
<h3>12-6. 発射元の拡大率・回転・不透明度も引き継ぐ</h3>
|
||||
<pre><code>local src = obj.getobject("routersys")
|
||||
if src then
|
||||
obj.x = src.x
|
||||
obj.y = src.y
|
||||
obj.zoom = src.zoom
|
||||
obj.rz = src.rz
|
||||
obj.alpha = src.alpha
|
||||
end</code></pre>
|
||||
|
||||
<h3>12-7. 発射時の座標に固定する</h3>
|
||||
<p>
|
||||
弾の発射フレーム (弾アイテムの開始フレーム) は <code>timelineframe - frame</code> で
|
||||
求まります。そのフレーム時点の発射元座標を取得すれば、発射元が動いても弾の原点は
|
||||
発射位置に固定されます。
|
||||
</p>
|
||||
<pre><code>local fire = timelineframe - frame
|
||||
local src = obj.getobject("routersys", fire)
|
||||
if src then
|
||||
obj.x = src.x
|
||||
obj.y = src.y
|
||||
end</code></pre>
|
||||
|
||||
<p>返り値テーブルのメンバーは以下のとおりです。</p>
|
||||
<table border="1">
|
||||
<tr><th>メンバー</th><th>説明</th></tr>
|
||||
<tr><td>exist</td><td>対象フレームが表示期間内か (boolean)</td></tr>
|
||||
<tr><td>x / y / z</td><td>描画位置 (ピクセル)</td></tr>
|
||||
<tr><td>zoom / sx / sy</td><td>拡大率 (1.0 で等倍)</td></tr>
|
||||
<tr><td>rx / ry / rz</td><td>X / Y / Z 軸回転角 (度)</td></tr>
|
||||
<tr><td>rxr / ryr / rzr</td><td>X / Y / Z 軸回転角 (ラジアン)</td></tr>
|
||||
<tr><td>alpha</td><td>不透明度 (0.0 ~ 255.0)</td></tr>
|
||||
<tr><td>layer</td><td>レイヤー番号</td></tr>
|
||||
<table>
|
||||
<tr><th>分野</th><th>主な API</th><th>参照</th></tr>
|
||||
<tr><td>座標・回転・拡大率・不透明度の制御</td><td><code>obj.x</code>, <code>obj.rz</code>, <code>obj.zoom</code>, <code>obj.alpha</code> ほか</td><td><a href="obj.html">obj</a></td></tr>
|
||||
<tr><td>時間・フレーム情報</td><td><code>time</code>, <code>frame</code>, <code>obj.t</code>, <code>timelineframe</code></td><td><a href="globals.html">グローバル変数</a></td></tr>
|
||||
<tr><td>アニメーション補間・波・ノイズ・色</td><td><code>anim.lerp</code>, <code>anim.ease_in_out</code>, <code>anim.noise</code>, <code>anim.hsv_to_rgb</code></td><td><a href="anim.html">anim</a></td></tr>
|
||||
<tr><td>他アイテムの参照</td><td><code>obj.getobject</code></td><td><a href="obj-functions.html">obj の関数</a></td></tr>
|
||||
<tr><td>ピクセル操作</td><td><code>obj.getpixel</code>, <code>obj.setpixel</code>, <code>obj.getpixeldata</code></td><td><a href="pixels.html">ピクセル操作</a></td></tr>
|
||||
<tr><td>図形・テキスト・画像・動画の読み込み</td><td><code>obj.load</code>, <code>obj.setfont</code></td><td><a href="obj-functions.html">obj の関数</a></td></tr>
|
||||
<tr><td>他エフェクトの適用・描画</td><td><code>obj.effect</code>, <code>obj.draw</code>, <code>obj.drawpoly</code></td><td><a href="obj-functions.html">obj の関数</a></td></tr>
|
||||
<tr><td>シーン・環境情報</td><td><code>scene.width</code>, <code>ymm4.is_saving</code></td><td><a href="scene-ymm4.html">scene / ymm4</a></td></tr>
|
||||
<tr><td>パラメータ UI の定義</td><td><code>--track@</code>, <code>--check@</code>, <code>--color@</code>, <code>--dialog:</code></td><td><a href="directives.html">パラメータ指定子</a></td></tr>
|
||||
<tr><td>高速化エンジンの選択</td><td><code>--!native</code>, <code>--!cpu</code>, <code>--!gpu</code></td><td><a href="engines.html">エンジンと高速化</a></td></tr>
|
||||
</table>
|
||||
|
||||
<hr>
|
||||
|
||||
<h2 id="pixel">13. ピクセル操作</h2>
|
||||
|
||||
<p>
|
||||
ピクセル操作は実際の入力画像へアクセスするため、初回アクセス時に画像データの
|
||||
転送が発生します。座標は画像の左上を (0, 0) とし、右・下方向が正です。
|
||||
取得値はストレートアルファ相当です。
|
||||
</p>
|
||||
|
||||
<h3>13-1. getpixel / setpixel で赤成分を反転</h3>
|
||||
<pre><code>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, g, b, a)
|
||||
end
|
||||
end</code></pre>
|
||||
|
||||
<h3>13-2. getpixeldata でグレースケール (高速)</h3>
|
||||
<p>
|
||||
<code>obj.getpixeldata()</code> はピクセルへ直接アクセスできるプロキシを返します。
|
||||
インデックスは 1 始まりで、チャンネルは R, G, B, A の繰り返しです。
|
||||
<code>pixel(x, y)</code> の R チャンネルのインデックスは <code>(y * obj.w + x) * 4 + 1</code> です。
|
||||
</p>
|
||||
<pre><code>local pd = obj.getpixeldata()
|
||||
local w = pd.width
|
||||
local h = pd.height
|
||||
for y = 0, h - 1 do
|
||||
for x = 0, w - 1 do
|
||||
local base = (y * w + x) * 4
|
||||
local r = pd:get(base + 1)
|
||||
local g = pd:get(base + 2)
|
||||
local b = pd:get(base + 3)
|
||||
local gray = r * 0.299 + g * 0.587 + b * 0.114
|
||||
pd:set(base + 1, gray)
|
||||
pd:set(base + 2, gray)
|
||||
pd:set(base + 3, gray)
|
||||
end
|
||||
end</code></pre>
|
||||
|
||||
<h3>13-3. 中心からの距離でフェード (円形ビネット)</h3>
|
||||
<pre><code>local pd = obj.getpixeldata()
|
||||
local w = pd.width
|
||||
local h = pd.height
|
||||
local cx = w / 2
|
||||
local cy = h / 2
|
||||
local maxd = anim.len(cx, cy)
|
||||
for y = 0, h - 1 do
|
||||
for x = 0, w - 1 do
|
||||
local base = (y * w + x) * 4
|
||||
local d = anim.len(x - cx, y - cy)
|
||||
local k = anim.clamp(1 - d / maxd, 0, 1)
|
||||
pd:set(base + 4, pd:get(base + 4) * k)
|
||||
end
|
||||
end</code></pre>
|
||||
|
||||
<p>
|
||||
<code>obj.putpixeldata()</code> は AviUtl との互換性のために存在しますが、
|
||||
このプラグインでは変更が自動的に反映されるため呼び出す必要はありません (no-op)。
|
||||
</p>
|
||||
|
||||
<table border="1">
|
||||
<tr><th>関数</th><th>戻り値</th><th>説明</th></tr>
|
||||
<tr><td>obj.getpixel(x, y)</td><td>r, g, b, a</td><td>指定座標のピクセルを取得 (各成分 0~255)</td></tr>
|
||||
<tr><td>obj.setpixel(x, y, r, g, b [, a])</td><td>なし</td><td>指定座標へ書き込み (a 既定 255)</td></tr>
|
||||
<tr><td>obj.getpixeldata()</td><td>PixelDataProxy</td><td>全ピクセルへの直接アクセスプロキシ</td></tr>
|
||||
<tr><td>obj.putpixeldata()</td><td>なし</td><td>互換用の空実装</td></tr>
|
||||
</table>
|
||||
|
||||
<hr>
|
||||
|
||||
<h2 id="scene">14. シーン情報 (scene)</h2>
|
||||
|
||||
<h3>14-1. シーンサイズに対する相対配置</h3>
|
||||
<pre><code>obj.x = scene.cx * obj.track0 / 100</code></pre>
|
||||
|
||||
<table border="1">
|
||||
<tr><th>メンバー</th><th>説明</th></tr>
|
||||
<tr><td>scene.width</td><td>シーンの横解像度 (ピクセル)</td></tr>
|
||||
<tr><td>scene.height</td><td>シーンの縦解像度 (ピクセル)</td></tr>
|
||||
<tr><td>scene.cx</td><td>横解像度の半分 (= scene.width / 2)</td></tr>
|
||||
<tr><td>scene.cy</td><td>縦解像度の半分 (= scene.height / 2)</td></tr>
|
||||
</table>
|
||||
|
||||
<hr>
|
||||
|
||||
<h2 id="ymm4">15. 環境・メタ情報 (ymm4)</h2>
|
||||
|
||||
<h3>15-1. グループ内のインデックスで時間差をつける</h3>
|
||||
<pre><code>local d = ymm4.group_index * 0.1
|
||||
local p = anim.duration(anim.delay(time, d), 0.5)
|
||||
obj.alpha = p * 255</code></pre>
|
||||
|
||||
<h3>15-2. グループ内の進行割合で配置をずらす</h3>
|
||||
<pre><code>obj.x = obj.x + ymm4.group_ratio * 400</code></pre>
|
||||
|
||||
<h3>15-3. 出力時のみ挙動を変える</h3>
|
||||
<pre><code>if ymm4.is_saving then
|
||||
obj.alpha = 255
|
||||
else
|
||||
obj.alpha = 128
|
||||
end</code></pre>
|
||||
|
||||
<table border="1">
|
||||
<tr><th>メンバー</th><th>説明</th></tr>
|
||||
<tr><td>ymm4.group_index</td><td>グループ制御内の現在のインデックス (0始まり)</td></tr>
|
||||
<tr><td>ymm4.group_count</td><td>グループ制御内の総アイテム数</td></tr>
|
||||
<tr><td>ymm4.group_ratio</td><td>グループ内の進行割合 (group_index / group_count)</td></tr>
|
||||
<tr><td>ymm4.timeline_totalframe</td><td>タイムライン全体の総フレーム数</td></tr>
|
||||
<tr><td>ymm4.timeline_totaltime</td><td>タイムライン全体の総時間 (秒)</td></tr>
|
||||
<tr><td>ymm4.time_ratio</td><td>現在の再生位置の割合 (0.0 ~ 1.0)</td></tr>
|
||||
<tr><td>ymm4.is_saving</td><td>動画出力中のみ true</td></tr>
|
||||
<tr><td>ymm4.is_playing</td><td>再生中のみ true</td></tr>
|
||||
<tr><td>ymm4.is_paused</td><td>一時停止中のみ true</td></tr>
|
||||
<tr><td>ymm4.scene_id</td><td>現在のシーンを識別する文字列 (Guid)</td></tr>
|
||||
</table>
|
||||
|
||||
<hr>
|
||||
|
||||
<h2 id="globals">16. グローバル変数</h2>
|
||||
<p>以下の変数はスクリプトのグローバルスコープで直接参照できます (すべて読み取り専用)。</p>
|
||||
<table border="1">
|
||||
<tr><th>変数</th><th>説明</th></tr>
|
||||
<tr><td>time</td><td>オブジェクト基準の現在時間 (秒)。obj.time と同じ</td></tr>
|
||||
<tr><td>frame</td><td>オブジェクト基準の現在フレーム番号。obj.frame と同じ</td></tr>
|
||||
<tr><td>totalframe</td><td>オブジェクトの総フレーム数。obj.totalframe と同じ</td></tr>
|
||||
<tr><td>framerate</td><td>フレームレート (fps)。obj.framerate と同じ</td></tr>
|
||||
<tr><td>timelineframe</td><td>タイムライン先頭からの絶対フレーム番号</td></tr>
|
||||
<tr><td>timelinetime</td><td>タイムライン基準の現在時間 (秒)</td></tr>
|
||||
<tr><td>layer</td><td>配置されているレイヤー番号。obj.layer と同じ</td></tr>
|
||||
<tr><td>obj / scene / ymm4 / anim</td><td>各テーブル (本ページ参照)</td></tr>
|
||||
</table>
|
||||
|
||||
<hr>
|
||||
|
||||
<h2 id="stdlib">17. 標準ライブラリ</h2>
|
||||
<p>利用できる標準ライブラリは以下に限定されます。io, os, debug, ffi, require 等は使用できません。</p>
|
||||
|
||||
<h3>math</h3>
|
||||
<p>
|
||||
abs, ceil, cos, exp, floor, fmod, huge, log, max, min, modf, pi, random, randomseed,
|
||||
sin, sqrt, tan, atan, atan2, deg, rad, ldexp, frexp, sinh, cosh, tanh, type,
|
||||
tointeger, maxinteger, mininteger
|
||||
</p>
|
||||
|
||||
<h3>string</h3>
|
||||
<p>
|
||||
format, len, sub, upper, lower, rep, reverse, find, match, gmatch, gsub, byte, char,
|
||||
dump, pack, unpack, packsize
|
||||
</p>
|
||||
|
||||
<h3>table</h3>
|
||||
<p>insert, remove, sort, concat, unpack, move</p>
|
||||
|
||||
<h3>bit32</h3>
|
||||
<p>
|
||||
band, bor, bxor, bnot, lshift, rshift, arshift, extract, replace, btest, countlz, countrz
|
||||
</p>
|
||||
|
||||
<h3>基本関数</h3>
|
||||
<p>
|
||||
type, tostring, tonumber, select, error, assert, print, ipairs, pairs, next, unpack,
|
||||
setmetatable, getmetatable, rawget, rawset, rawequal, rawlen, pcall, xpcall
|
||||
</p>
|
||||
|
||||
<hr>
|
||||
|
||||
<h2 id="reference">クイックリファレンス</h2>
|
||||
|
||||
<h3>obj (変更可能メンバー)</h3>
|
||||
<table border="1">
|
||||
<tr><th>メンバー</th><th>説明</th></tr>
|
||||
<tr><td>obj.x / obj.y / obj.z</td><td>描画位置 (ピクセル)</td></tr>
|
||||
<tr><td>obj.ox / obj.oy / obj.oz</td><td>回転中心のオフセット (ピクセル)</td></tr>
|
||||
<tr><td>obj.zoom</td><td>拡大率 (sx と sy の平均、1.0 で等倍)</td></tr>
|
||||
<tr><td>obj.aspect</td><td>アスペクト比 (-1.0 ~ 1.0)</td></tr>
|
||||
<tr><td>obj.sx / obj.sy</td><td>X / Y 方向の独立拡大率</td></tr>
|
||||
<tr><td>obj.alpha</td><td>不透明度 (0.0 ~ 255.0)</td></tr>
|
||||
<tr><td>obj.rx / obj.ry / obj.rz</td><td>X / Y / Z 軸回転角 (度)</td></tr>
|
||||
<tr><td>obj.rxr / obj.ryr / obj.rzr</td><td>X / Y / Z 軸回転角 (ラジアン)</td></tr>
|
||||
</table>
|
||||
|
||||
<h3>obj (読み取り専用メンバー)</h3>
|
||||
<table border="1">
|
||||
<tr><th>メンバー</th><th>説明</th></tr>
|
||||
<tr><td>obj.w / obj.h</td><td>入力画像の幅 / 高さ (ピクセル)</td></tr>
|
||||
<tr><td>obj.hw / obj.hh</td><td>幅 / 高さの半分</td></tr>
|
||||
<tr><td>obj.cx / obj.cy</td><td>画像中心 (= hw / hh)</td></tr>
|
||||
<tr><td>obj.cz / obj.sz</td><td>常に 0 / 常に 1</td></tr>
|
||||
<tr><td>obj.diagonal</td><td>対角線長 (sqrt(w^2 + h^2))</td></tr>
|
||||
<tr><td>obj.time / obj.frame</td><td>アイテム基準の経過時間 (秒) / フレーム</td></tr>
|
||||
<tr><td>obj.totalframe / obj.totaltime</td><td>アイテムの総フレーム数 / 総時間 (秒)</td></tr>
|
||||
<tr><td>obj.t</td><td>アイテム内の進行割合 (0.0 ~ 1.0)</td></tr>
|
||||
<tr><td>obj.framerate</td><td>フレームレート (fps)</td></tr>
|
||||
<tr><td>obj.layer</td><td>レイヤー番号</td></tr>
|
||||
<tr><td>obj.index / obj.num</td><td>グループ内のインデックス / 総数</td></tr>
|
||||
<tr><td>obj.track0 ~ obj.track3</td><td>エフェクトパネルの各トラックバーの値</td></tr>
|
||||
</table>
|
||||
|
||||
<h3>obj 関数</h3>
|
||||
<table border="1">
|
||||
<tr><th>関数</th><th>説明</th></tr>
|
||||
<tr><td>obj.getobject(tag [, frame])</td><td>他アイテムの描画情報を取得 (本ページ 12 章)</td></tr>
|
||||
<tr><td>obj.getpixel(x, y)</td><td>ピクセル取得</td></tr>
|
||||
<tr><td>obj.setpixel(x, y, r, g, b [, a])</td><td>ピクセル書き込み</td></tr>
|
||||
<tr><td>obj.getpixeldata()</td><td>ピクセル直接アクセスプロキシ</td></tr>
|
||||
<tr><td>obj.putpixeldata()</td><td>互換用の空実装</td></tr>
|
||||
</table>
|
||||
|
||||
<hr>
|
||||
|
||||
<h2>非対応・制限事項</h2>
|
||||
<ul>
|
||||
<li>AviUtl2 の obj.effect(), obj.draw(), obj.drawpoly(), obj.load() 等は非対応です。</li>
|
||||
<li>obj.setoption(), obj.getoption(), obj.getvalue(), obj.setanchor() 等は非対応です。</li>
|
||||
<li>scene.set(), scene.get() 等は非対応です (scene.width / scene.height の読み取りのみ)。</li>
|
||||
<li>ファイルアクセス (require, dofile, io 等) は非対応です。</li>
|
||||
<li>スクリプトのタイムアウトは 5 秒です。無限ループに注意してください。</li>
|
||||
<li>--track@, --check@ 等のヘッダーディレクティブは非対応です (Track0 ~ Track3 のみ)。</li>
|
||||
</ul>
|
||||
|
||||
<hr>
|
||||
|
||||
<p>
|
||||
Luaスクリプト for YMM4 / MIT License /
|
||||
<a href="https://github.com/routersys/YMM4-LuaScript">https://github.com/routersys/YMM4-LuaScript</a>
|
||||
</p>
|
||||
<div class="pager">
|
||||
<span></span>
|
||||
<a href="getting-started.html">導入と使い方 →</a>
|
||||
</div>
|
||||
|
||||
</main>
|
||||
<script src="assets/nav.js"></script>
|
||||
</body>
|
||||
</html>
|
||||
@@ -0,0 +1,86 @@
|
||||
<!DOCTYPE html>
|
||||
<html lang="ja">
|
||||
<head>
|
||||
<meta charset="utf-8">
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1">
|
||||
<title>制限事項とトラブル | Lua スクリプト for YMM4</title>
|
||||
<link rel="stylesheet" href="assets/style.css">
|
||||
</head>
|
||||
<body>
|
||||
<button id="navtoggle" aria-label="メニュー">☰</button>
|
||||
<nav id="sidebar"></nav>
|
||||
<main>
|
||||
|
||||
<h1>制限事項とトラブル</h1>
|
||||
|
||||
<h2>実行に関する制限</h2>
|
||||
|
||||
<ul>
|
||||
<li>タイムアウト 5 秒: 1 フレームのスクリプト実行が 5 秒を超えると中断され、そのフレームは
|
||||
元の映像のままになります。無限ループや極端に重い処理に注意してください。</li>
|
||||
<li>フレーム間で状態は保持されない: 組み込み以外のグローバル変数は毎フレームリセットされます。
|
||||
時間変化は <code>time</code> や <code>obj.t</code> から計算します。フレームやアイテムをまたいで値を
|
||||
共有したい場合は <a href="scene-ymm4.html"><code>scene.set()</code> / <code>scene.get()</code></a> を使ってください。</li>
|
||||
<li>ファイルアクセス不可: <code>require</code>・<code>dofile</code>・<code>io</code> などは使えません。</li>
|
||||
<li>使えない標準ライブラリ: <code>io</code>・<code>os</code>・<code>debug</code>・<code>coroutine</code>・
|
||||
<code>package</code>・<code>ffi</code> は無効です(<a href="stdlib.html">標準ライブラリ</a>)。</li>
|
||||
</ul>
|
||||
|
||||
<h2>乱数について</h2>
|
||||
|
||||
<p>
|
||||
<code>math.random</code> の結果はフレームごとに決まります。シードの仕組みは
|
||||
<a href="stdlib.html">標準ライブラリ</a>の <code>math</code> で説明しています。
|
||||
オブジェクトやフレームに対して安定した乱数が欲しいときは、
|
||||
<a href="anim.html"><code>anim.rand</code></a> や <code>anim.noise</code>、
|
||||
<a href="obj-functions.html"><code>obj.rand</code></a> を使ってください。
|
||||
</p>
|
||||
|
||||
<h2>非対応の機能</h2>
|
||||
|
||||
<ul>
|
||||
<li><code>obj.setanchor()</code> など、本ドキュメントに記載のない AviUtl 関数は対応していません。</li>
|
||||
<li><code>obj.effect</code> は、AviUtl/AviUtl2 互換マップに宣言したエフェクト名と、YMM4 に読み込まれている映像エフェクトの名前・キーワードを解決します。
|
||||
名前が見つからない・適用に失敗した場合は、そのフレームでは元の映像がそのまま使われます。
|
||||
互換マップが対応するエフェクト名の一覧は<a href="obj-functions.html">obj の関数</a>を参照してください。</li>
|
||||
</ul>
|
||||
|
||||
<h2>エラー表示</h2>
|
||||
|
||||
<p>
|
||||
構文エラー・実行時エラー・タイムアウトが起きると、スクリプトエディタの該当行に赤い波線で
|
||||
警告が表示されます。まずはエラーメッセージと行番号を確認してください。
|
||||
</p>
|
||||
|
||||
<h2>困ったときは</h2>
|
||||
|
||||
<table>
|
||||
<tr><th>症状</th><th>確認すること</th></tr>
|
||||
<tr><td>スクリプトを書いても見た目が変わらない</td><td>値を <code>obj</code> に代入しているか(グローバル変数に入れても反映されません)。
|
||||
例: <code>obj.x = ...</code>。読み取り専用メンバーに代入していないか。</td></tr>
|
||||
<tr><td>トラックバーや色が表示されない</td><td>指定子や使用状況によって表示が決まります。<a href="directives.html">パラメータ指定子</a> の表示条件を確認してください。</td></tr>
|
||||
<tr><td>前のフレームの値が消える</td><td>仕様です。グローバル変数はフレーム間で保持されません。
|
||||
持ち越したい値は <code>scene.set()</code> / <code>scene.get()</code> で共有してください。</td></tr>
|
||||
<tr><td>処理が中断される / フレームが描画されない</td><td>5 秒のタイムアウトに達している可能性があります。ループ回数を減らすか、
|
||||
ピクセル処理を <a href="engines.html">カーネルやネイティブ</a>に任せられる形にしてください。</td></tr>
|
||||
<tr><td><code>--!native</code> を指定しても速くならない</td><td>プラグインの隣に <code>native</code> フォルダが配置されていないと MoonSharp で実行されます。
|
||||
配置を確認してください(ログに一度だけ警告が出ます)。</td></tr>
|
||||
<tr><td>GPU でわずかに結果が違う</td><td>GPU カーネルは float32 精度です。厳密一致が必要なら CPU カーネルかネイティブを使ってください。</td></tr>
|
||||
</table>
|
||||
|
||||
<hr>
|
||||
|
||||
<p>
|
||||
Lua スクリプト for YMM4 / MIT License /
|
||||
<a href="https://github.com/routersys/YMM4-LuaScript">https://github.com/routersys/YMM4-LuaScript</a>
|
||||
</p>
|
||||
|
||||
<div class="pager">
|
||||
<a href="reference.html">← クイックリファレンス</a>
|
||||
<a href="index.html">概要 →</a>
|
||||
</div>
|
||||
|
||||
</main>
|
||||
<script src="assets/nav.js"></script>
|
||||
</body>
|
||||
</html>
|
||||
@@ -0,0 +1,251 @@
|
||||
<!DOCTYPE html>
|
||||
<html lang="ja">
|
||||
<head>
|
||||
<meta charset="utf-8">
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1">
|
||||
<title>Lua の基礎 | Lua スクリプト for YMM4</title>
|
||||
<link rel="stylesheet" href="assets/style.css">
|
||||
</head>
|
||||
<body>
|
||||
<button id="navtoggle" aria-label="メニュー">☰</button>
|
||||
<nav id="sidebar"></nav>
|
||||
<main>
|
||||
|
||||
<h1>Lua の基礎</h1>
|
||||
|
||||
<p>
|
||||
このページは、Lua をはじめて触る人向けの入門です。Lua スクリプトエフェクトで使える範囲に絞って、
|
||||
言語そのものの書き方を学びます。エンジンは Lua 5.2 互換の MoonSharp です。
|
||||
ファイル入出力やコルーチンなど一部の機能は使えません。詳しくは<a href="stdlib.html">標準ライブラリ</a>を参照してください。
|
||||
</p>
|
||||
|
||||
<h2>コメント</h2>
|
||||
|
||||
<p>
|
||||
Lua のコメントは <code>--</code> から行末までです。複数行コメントは <code>--[[</code> から <code>]]</code> までです。
|
||||
コメントは実行に影響しません。なお、行頭の <code>--track:</code> や <code>--!native</code> のような特定の書式は
|
||||
プラグインが解釈する<a href="directives.html">指定子</a>として扱われます。
|
||||
</p>
|
||||
|
||||
<table>
|
||||
<tr><th>書き方</th><th>意味</th></tr>
|
||||
<tr><td><code>-- text</code></td><td>1 行コメント</td></tr>
|
||||
<tr><td><code>--[[ text ]]</code></td><td>複数行コメント</td></tr>
|
||||
</table>
|
||||
|
||||
<h2>値と型</h2>
|
||||
|
||||
<p>Lua の値には次の型があります。スクリプトでよく使うのは数値・文字列・真偽値・テーブルです。</p>
|
||||
|
||||
<table>
|
||||
<tr><th>型</th><th>例</th><th>説明</th></tr>
|
||||
<tr><td>nil</td><td><code>nil</code></td><td>値が無いことを表す。未定義の変数も nil</td></tr>
|
||||
<tr><td>boolean</td><td><code>true</code>, <code>false</code></td><td>真偽値。条件分岐で使う</td></tr>
|
||||
<tr><td>number</td><td><code>10</code>, <code>3.14</code>, <code>-0.5</code></td><td>数値。内部は倍精度浮動小数点</td></tr>
|
||||
<tr><td>string</td><td><code>"hello"</code>, <code>'abc'</code></td><td>文字列</td></tr>
|
||||
<tr><td>table</td><td><code>{1, 2, 3}</code></td><td>配列や連想配列に使う唯一の構造体</td></tr>
|
||||
<tr><td>function</td><td><code>function(x) return x end</code></td><td>関数も値として扱える</td></tr>
|
||||
</table>
|
||||
|
||||
<div class="note">
|
||||
条件式で「偽」とみなされるのは <code>false</code> と <code>nil</code> だけです。
|
||||
<code>0</code> も <code>""</code>(空文字列)も「真」です。これは C や JavaScript と違うので注意してください。
|
||||
</div>
|
||||
|
||||
<h2>変数</h2>
|
||||
|
||||
<p>
|
||||
変数は <code>local</code> を付けて宣言します。<code>local</code> を付けるとそのブロック内だけで有効な
|
||||
ローカル変数になります。付けないとグローバル変数になります。スクリプトでは原則 <code>local</code> を使ってください。
|
||||
</p>
|
||||
|
||||
<pre><code>local a = 10
|
||||
local b = 20
|
||||
local sum = a + b
|
||||
obj.x = sum</code></pre>
|
||||
|
||||
<p>複数の変数を一度に宣言・代入できます。</p>
|
||||
|
||||
<pre><code>local x, y = 100, 200
|
||||
x, y = y, x</code></pre>
|
||||
|
||||
<div class="warn">
|
||||
このエフェクトでは、グローバル変数の状態はフレーム間で保持されません。
|
||||
毎フレーム独立に実行されるため、「前のフレームの値」を変数に貯めることはできません。
|
||||
</div>
|
||||
|
||||
<h2>演算子</h2>
|
||||
|
||||
<table>
|
||||
<tr><th>分類</th><th>演算子</th></tr>
|
||||
<tr><td>算術</td><td><code>+</code> <code>-</code> <code>*</code> <code>/</code> <code>%</code>(剰余) <code>^</code>(べき乗)</td></tr>
|
||||
<tr><td>比較</td><td><code>==</code> <code>~=</code>(等しくない) <code><</code> <code>></code> <code><=</code> <code>>=</code></td></tr>
|
||||
<tr><td>論理</td><td><code>and</code> <code>or</code> <code>not</code></td></tr>
|
||||
<tr><td>連結</td><td><code>..</code>(文字列の連結)</td></tr>
|
||||
<tr><td>長さ</td><td><code>#</code>(文字列やテーブルの長さ)</td></tr>
|
||||
</table>
|
||||
|
||||
<p>
|
||||
<code>and</code> と <code>or</code> は値を返します。<code>a and b</code> は <code>a</code> が偽なら <code>a</code>、
|
||||
真なら <code>b</code> を返します。<code>a or b</code> は <code>a</code> が真なら <code>a</code>、偽なら <code>b</code> を返します。
|
||||
これを使うと既定値を簡潔に書けます。
|
||||
</p>
|
||||
|
||||
<pre><code>local amp = obj.track0
|
||||
local v = amp ~= 0 and amp or 50
|
||||
obj.x = obj.x + v</code></pre>
|
||||
|
||||
<h2>条件分岐</h2>
|
||||
|
||||
<pre><code>if obj.t < 0.5 then
|
||||
obj.alpha = 255
|
||||
elseif obj.t < 0.8 then
|
||||
obj.alpha = 128
|
||||
else
|
||||
obj.alpha = 0
|
||||
end</code></pre>
|
||||
|
||||
<p>三項演算子の代わりに <code>and</code> / <code>or</code> を使うのが定番です。</p>
|
||||
|
||||
<pre><code>obj.alpha = obj.check0 and 255 or 0</code></pre>
|
||||
|
||||
<h2>繰り返し</h2>
|
||||
|
||||
<h3>数値 for</h3>
|
||||
<p><code>for 変数 = 開始, 終了 [, 増分] do ... end</code> です。終了値も含みます。</p>
|
||||
|
||||
<pre><code>local total = 0
|
||||
for i = 1, 10 do
|
||||
total = total + i
|
||||
end</code></pre>
|
||||
|
||||
<p>ピクセル処理では 0 始まりで幅・高さ分ループするのが基本形です。</p>
|
||||
|
||||
<pre><code>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, g, b, a)
|
||||
end
|
||||
end</code></pre>
|
||||
|
||||
<h3>汎用 for(ipairs / pairs)</h3>
|
||||
<p>配列を順に走査するなら <code>ipairs</code> を、すべてのキーを走査するなら <code>pairs</code> を使います。</p>
|
||||
|
||||
<pre><code>local points = {10, 20, 30}
|
||||
local sum = 0
|
||||
for index, value in ipairs(points) do
|
||||
sum = sum + value
|
||||
end</code></pre>
|
||||
|
||||
<h3>while と repeat</h3>
|
||||
<pre><code>local i = 0
|
||||
while i < 5 do
|
||||
i = i + 1
|
||||
end
|
||||
|
||||
local j = 0
|
||||
repeat
|
||||
j = j + 1
|
||||
until j >= 5</code></pre>
|
||||
|
||||
<div class="warn">
|
||||
ループの終了条件は必ず満たされるようにしてください。
|
||||
無限ループになると 5 秒で実行が打ち切られ、そのフレームは描画されません。
|
||||
</div>
|
||||
|
||||
<h2>関数</h2>
|
||||
|
||||
<p>関数は <code>function</code> で定義します。スクリプト内で定義した関数は入力補完にも出ます。</p>
|
||||
|
||||
<pre><code>local function ease(t)
|
||||
return t * t * (3 - 2 * t)
|
||||
end
|
||||
|
||||
obj.alpha = ease(obj.t) * 255</code></pre>
|
||||
|
||||
<h3>複数の戻り値</h3>
|
||||
<p>Lua の関数は複数の値を返せます。<code>anim.polar</code> など多くの組み込み関数がこれを使います。</p>
|
||||
|
||||
<pre><code>local function offset()
|
||||
return 10, -20
|
||||
end
|
||||
|
||||
local dx, dy = offset()
|
||||
obj.x = obj.x + dx
|
||||
obj.y = obj.y + dy</code></pre>
|
||||
|
||||
<h3>可変長引数</h3>
|
||||
<pre><code>local function sum(...)
|
||||
local total = 0
|
||||
for _, v in ipairs({...}) do
|
||||
total = total + v
|
||||
end
|
||||
return total
|
||||
end</code></pre>
|
||||
|
||||
<h2>テーブル</h2>
|
||||
|
||||
<p>テーブルは Lua で唯一の複合データ構造で、配列にも連想配列にも使えます。</p>
|
||||
|
||||
<h3>配列として</h3>
|
||||
<pre><code>local list = {5, 10, 15}
|
||||
local first = list[1]
|
||||
local count = #list</code></pre>
|
||||
|
||||
<div class="note">
|
||||
配列のインデックスは 1 始まりです。多くの言語と違って 0 ではありません。
|
||||
ただし <code>obj.getpixel(x, y)</code> の座標や、数値 for を 0 から回す処理は別物です。
|
||||
ピクセルデータプロキシのインデックスは 1 始まりです(<a href="pixels.html">ピクセル操作</a>)。
|
||||
</div>
|
||||
|
||||
<h3>連想配列として</h3>
|
||||
<pre><code>local config = { speed = 90, radius = 100 }
|
||||
obj.rz = time * config.speed</code></pre>
|
||||
|
||||
<h3>テーブル操作</h3>
|
||||
<p><code>table</code> ライブラリで挿入・削除・連結・並べ替えができます。</p>
|
||||
|
||||
<pre><code>local t = {}
|
||||
table.insert(t, 1)
|
||||
table.insert(t, 2)
|
||||
table.sort(t)
|
||||
local joined = table.concat(t, ",")</code></pre>
|
||||
|
||||
<h2>文字列</h2>
|
||||
|
||||
<p>文字列は <code>string</code> ライブラリで整形・検索できます。連結は <code>..</code> です。</p>
|
||||
|
||||
<pre><code>local label = string.format("%.1f", obj.t)
|
||||
local upper = string.upper("abc")
|
||||
local n = string.len(label)</code></pre>
|
||||
|
||||
<h2>標準で使える数学関数</h2>
|
||||
|
||||
<p><code>math</code> ライブラリに基本的な数学関数があります。よく使うものだけ挙げます。</p>
|
||||
|
||||
<pre><code>local r = math.sqrt(obj.x * obj.x + obj.y * obj.y)
|
||||
local angle = math.atan2(obj.y, obj.x)
|
||||
obj.rz = math.deg(angle)
|
||||
obj.zoom = math.max(0.1, 1 + math.sin(time))</code></pre>
|
||||
|
||||
<p>
|
||||
全関数の一覧は <a href="stdlib.html">標準ライブラリ</a> を参照してください。
|
||||
アニメーション向けの高度な補間や波・ノイズは <a href="anim.html">anim ライブラリ</a> にまとまっています。
|
||||
</p>
|
||||
|
||||
<h2>このエフェクト特有の注意点</h2>
|
||||
|
||||
<p>
|
||||
標準 Lua との違いとして、使える標準ライブラリの範囲、乱数の扱い、5 秒の実行時間制限などの制約があります。
|
||||
これらは<a href="limits.html">制限事項とトラブル</a>にまとめています。
|
||||
</p>
|
||||
|
||||
<div class="pager">
|
||||
<a href="getting-started.html">← 導入と使い方</a>
|
||||
<a href="stdlib.html">標準ライブラリ →</a>
|
||||
</div>
|
||||
|
||||
</main>
|
||||
<script src="assets/nav.js"></script>
|
||||
</body>
|
||||
</html>
|
||||
@@ -0,0 +1,350 @@
|
||||
<!DOCTYPE html>
|
||||
<html lang="ja">
|
||||
<head>
|
||||
<meta charset="utf-8">
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1">
|
||||
<title>obj の関数 | Lua スクリプト for YMM4</title>
|
||||
<link rel="stylesheet" href="assets/style.css">
|
||||
</head>
|
||||
<body>
|
||||
<button id="navtoggle" aria-label="メニュー">☰</button>
|
||||
<nav id="sidebar"></nav>
|
||||
<main>
|
||||
|
||||
<h1>obj の関数</h1>
|
||||
|
||||
<p>
|
||||
<code>obj</code> には値だけでなく関数も用意されています。他アイテムの参照、ピクセル操作、
|
||||
図形やテキストの生成、他エフェクトの適用などができます。座標などの値メンバーは
|
||||
<a href="obj.html">obj オブジェクト</a> を参照してください。
|
||||
</p>
|
||||
|
||||
<h2>obj.getobject — 他アイテムの参照</h2>
|
||||
|
||||
<p>
|
||||
<code>obj.getobject(tag [, frame])</code> は、対象アイテムの「備考」欄に入力した文字列を <code>tag</code> として、
|
||||
そのアイテムの描画情報を取得します。備考欄はプロパティエリアの上側にあります。
|
||||
第 2 引数 <code>frame</code> を指定すると、そのタイムラインフレーム時点の値を取得します(省略時は現在フレーム)。
|
||||
一致するアイテムが無い場合は <code>nil</code> を返します。
|
||||
</p>
|
||||
|
||||
<p>
|
||||
返り値は対象アイテム自身の座標・回転・拡大率であり、グループ制御・カメラ制御による変形は含みません。
|
||||
同じタグのアイテムが複数あるときは、対象フレームで表示中のものが優先されます。
|
||||
</p>
|
||||
|
||||
<table>
|
||||
<tr><th>メンバー</th><th>説明</th></tr>
|
||||
<tr><td><code>exist</code></td><td>対象フレームが表示期間内か(boolean)</td></tr>
|
||||
<tr><td><code>x</code> / <code>y</code> / <code>z</code></td><td>描画位置(ピクセル)</td></tr>
|
||||
<tr><td><code>zoom</code> / <code>sx</code> / <code>sy</code></td><td>拡大率(1.0 で等倍)。<code>sx</code>・<code>sy</code> は <code>zoom</code> と同じ値</td></tr>
|
||||
<tr><td><code>rz</code> / <code>rzr</code></td><td>Z 軸回転角(度 / ラジアン)</td></tr>
|
||||
<tr><td><code>rx</code> / <code>ry</code> / <code>rxr</code> / <code>ryr</code></td><td>常に 0(X・Y 軸回転は取得しません)</td></tr>
|
||||
<tr><td><code>alpha</code></td><td>不透明度(0.0 ~ 255.0)</td></tr>
|
||||
<tr><td><code>layer</code></td><td>レイヤー番号</td></tr>
|
||||
</table>
|
||||
|
||||
<h3>発射元の座標に合わせる</h3>
|
||||
<pre><code>local src = obj.getobject("routersys")
|
||||
if src then
|
||||
obj.x = src.x
|
||||
obj.y = src.y
|
||||
end</code></pre>
|
||||
|
||||
<h3>発射元へ向かって移動する</h3>
|
||||
<pre><code>local target = obj.getobject("routersys")
|
||||
if target then
|
||||
local p = anim.ease_in_out(obj.t)
|
||||
obj.x = anim.lerp(obj.x, target.x, p)
|
||||
obj.y = anim.lerp(obj.y, target.y, p)
|
||||
end</code></pre>
|
||||
|
||||
<h3>表示中のときだけ追従する</h3>
|
||||
<pre><code>local target = obj.getobject("routersys")
|
||||
if target and target.exist then
|
||||
obj.x = target.x
|
||||
obj.y = target.y
|
||||
end</code></pre>
|
||||
|
||||
<h3>発射時の座標に固定する</h3>
|
||||
<p>
|
||||
弾の発射フレーム(弾アイテムの開始フレーム)は <code>timelineframe - frame</code> で求まります。
|
||||
そのフレーム時点の発射元座標を取得すれば、発射元が動いても原点は発射位置に固定されます。
|
||||
</p>
|
||||
<pre><code>local fire = timelineframe - frame
|
||||
local src = obj.getobject("routersys", fire)
|
||||
if src then
|
||||
obj.x = src.x
|
||||
obj.y = src.y
|
||||
end</code></pre>
|
||||
|
||||
<h2>ピクセル操作</h2>
|
||||
|
||||
<p>
|
||||
<code>obj.getpixel</code> / <code>obj.setpixel</code> / <code>obj.getpixeldata</code> は画像を直接読み書きします。
|
||||
座標・チャンネル・アルファの扱いといった詳細は <a href="pixels.html">ピクセル操作</a> を参照してください。
|
||||
ここでは関数の概要だけ示します。
|
||||
</p>
|
||||
|
||||
<table>
|
||||
<tr><th>関数</th><th>戻り値</th><th>説明</th></tr>
|
||||
<tr><td><code>obj.getpixel(x, y)</code></td><td>r, g, b, a</td><td>指定座標のピクセルを取得(各成分 0 ~ 255)</td></tr>
|
||||
<tr><td><code>obj.setpixel(x, y, r, g, b [, a])</code></td><td>なし</td><td>指定座標へ書き込み(a 既定 255)</td></tr>
|
||||
<tr><td><code>obj.getpixeldata()</code></td><td>プロキシ</td><td>全ピクセルへ直接アクセスするプロキシを返す</td></tr>
|
||||
<tr><td><code>obj.putpixeldata()</code></td><td>なし</td><td>AviUtl 互換用の空実装(呼ぶ必要はない)</td></tr>
|
||||
</table>
|
||||
|
||||
<h2>obj.rand — 整数の安定した乱数</h2>
|
||||
|
||||
<p>
|
||||
<code>obj.rand(a, b [, seed [, frame]])</code> は <code>a</code> ~ <code>b</code> の範囲の整数を返します
|
||||
(端点を含みます)。同じ <code>seed</code> と <code>frame</code> の組では常に同じ値になります。
|
||||
<code>seed</code> の既定値は 0、<code>frame</code> の既定値は現在フレームです。
|
||||
</p>
|
||||
|
||||
<table>
|
||||
<tr><th>関数</th><th>戻り値</th><th>用途</th></tr>
|
||||
<tr><td><code>obj.rand(a, b)</code></td><td>整数</td><td>毎フレーム変わる乱数</td></tr>
|
||||
<tr><td><code>obj.rand(a, b, seed)</code></td><td>整数</td><td>シードで固定。レイヤー番号などを渡す</td></tr>
|
||||
<tr><td><code>obj.rand(a, b, seed, frame)</code></td><td>整数</td><td>フレームも固定して完全に決定的にする</td></tr>
|
||||
</table>
|
||||
|
||||
<div class="note">
|
||||
小数を含む乱数や、ベクトル・色のゆらぎが欲しいときは <a href="anim.html"><code>anim.rand</code></a> や
|
||||
<code>anim.noise</code> が便利です。<code>obj.rand</code> は整数を返す AviUtl 互換の乱数です。
|
||||
</div>
|
||||
|
||||
<h2>obj.load — 図形・テキスト・画像・動画の読み込み</h2>
|
||||
|
||||
<p>
|
||||
<code>obj.load(種類, ...)</code> は、対象の画像バッファを生成した内容で置き換えます。
|
||||
読み込み後は <code>obj.w</code> / <code>obj.h</code> などの寸法も更新されます。
|
||||
</p>
|
||||
|
||||
<table>
|
||||
<tr><th>呼び出し</th><th>説明</th></tr>
|
||||
<tr><td><code>obj.load("figure", name, color, size [, line [, aspect]])</code></td><td>図形を生成。<code>color</code> は <code>0xRRGGBB</code>、<code>size</code> は大きさ(px)、<code>line</code> は 0 以下で塗りつぶし・正で輪郭の太さ、<code>aspect</code> は -1.0 ~ 1.0</td></tr>
|
||||
<tr><td><code>obj.load("text", str)</code></td><td>文字列を描画。フォントは <code>obj.setfont</code> の設定を使う</td></tr>
|
||||
<tr><td><code>obj.load("image", path)</code></td><td>画像ファイルを読み込む</td></tr>
|
||||
<tr><td><code>obj.load("movie", path [, time])</code></td><td>動画の指定時刻のフレームを読み込む(既定は現在時刻)</td></tr>
|
||||
</table>
|
||||
|
||||
<p><code>obj.load("figure", ...)</code> で指定できる図形名は次のとおりです。</p>
|
||||
|
||||
<table>
|
||||
<tr><th>図形</th><th>名前</th></tr>
|
||||
<tr><td>円・楕円</td><td><code>円</code> / <code>楕円</code> / <code>circle</code> / <code>ellipse</code></td></tr>
|
||||
<tr><td>三角形</td><td><code>三角形</code> / <code>triangle</code></td></tr>
|
||||
<tr><td>五角形</td><td><code>五角形</code> / <code>pentagon</code></td></tr>
|
||||
<tr><td>六角形</td><td><code>六角形</code> / <code>hexagon</code></td></tr>
|
||||
<tr><td>星形</td><td><code>星形</code> / <code>star</code></td></tr>
|
||||
<tr><td>四角形</td><td>上記以外の名前(既定)</td></tr>
|
||||
</table>
|
||||
|
||||
<pre><code>obj.load("figure", "star", 0xFFCC00, 200, 0, 0)</code></pre>
|
||||
|
||||
<h2>obj.setfont — フォント設定</h2>
|
||||
|
||||
<p>
|
||||
<code>obj.setfont(name [, size [, type [, color]]])</code> は、続く <code>obj.load("text", ...)</code> で使う
|
||||
フォントを設定します。<code>type</code> はビットフラグで、ビット 0 が太字、ビット 1 が斜体です
|
||||
(太字+斜体は 3)。既定の大きさは 34、既定色は <code>0xFFFFFF</code> です。
|
||||
</p>
|
||||
|
||||
<pre><code>obj.setfont("Yu Gothic UI", 48, 1, 0xFFFFFF)
|
||||
obj.load("text", "サンプル")</code></pre>
|
||||
|
||||
<h2>AviUtl 互換の描画・効果関数(上級)</h2>
|
||||
|
||||
<p>
|
||||
次の関数は AviUtl のスクリプト制御に近い使い勝手で用意されています。
|
||||
<code>obj.effect</code> は AviUtl/AviUtl2 のエフェクト名とパラメータ名で、対応する YMM4 の映像エフェクトを適用します。
|
||||
</p>
|
||||
|
||||
<table>
|
||||
<tr><th>関数</th><th>説明</th></tr>
|
||||
<tr><td><code>obj.effect(name, key1, val1, ...)</code></td><td>AviUtl/AviUtl2 のエフェクト名で YMM4 の映像エフェクトを適用する。<code>key, val</code> の組は AviUtl のパラメータ名で指定し、互換マップを通じて YMM4 のプロパティへ変換される</td></tr>
|
||||
<tr><td><code>obj.draw([ox, oy, oz, zoom, alpha, aspect])</code></td><td>現在のバッファをオフセット・拡大率・不透明度を指定して描画する</td></tr>
|
||||
<tr><td><code>obj.drawpoly(x0,y0,z0, x1,y1,z1, x2,y2,z2, x3,y3,z3 [, u0,v0, ... ,u3,v3] [, alpha])</code></td><td>4 頂点のテクスチャ付きポリゴンを描画する。UV を省略すると画像全体を使う</td></tr>
|
||||
<tr><td><code>obj.copybuffer(dst, src)</code></td><td>バッファ間でコピーする。ID は <code>obj</code>(作業画像)・<code>tmp</code>・<code>cache:名前</code>。書き込み先が <code>obj</code> のときのみ作業画像を置き換える</td></tr>
|
||||
<tr><td><code>obj.setoption(name [, value])</code></td><td>オプションを設定する。<code>antialias</code> は <code>obj.draw</code> で参照される。<code>blend</code> は <code>obj.draw</code>/<code>obj.drawpoly</code> の合成モードを番号で指定する。番号は下記の「合成モード」を参照。<code>draw_state</code> は真偽値で、<code>true</code> なら作業画像を出力し、<code>false</code> なら入力をそのまま通す。<code>drawtarget</code> は <code>obj.draw</code>/<code>obj.drawpoly</code> の描画先を <code>"framebuffer"</code> と <code>"tempbuffer"</code> で切り替える。詳細は下記の「描画先」を参照</td></tr>
|
||||
<tr><td><code>obj.getoption(name)</code></td><td>設定したオプションを取得する</td></tr>
|
||||
<tr><td><code>obj.getvalue(name)</code></td><td><code>obj</code> の数値メンバーを名前で取得する</td></tr>
|
||||
<tr><td><code>obj.pixeloption(name [, value])</code></td><td>ピクセル処理向けのオプションを設定する</td></tr>
|
||||
<tr><td><code>obj.setanchor(name, count [, option, ...])</code></td><td>プレビュー上にドラッグ可能なアンカーポイントを表示し、その座標を <code>name</code> の Lua 変数へ格納する。設置数を返す。詳細は下記の「アンカーポイント」を参照</td></tr>
|
||||
</table>
|
||||
|
||||
<h3>合成モード</h3>
|
||||
|
||||
<p>
|
||||
<code>obj.setoption("blend", 番号)</code> は <code>obj.draw</code>/<code>obj.drawpoly</code> の描画に合成モードを設定します。
|
||||
番号は YMM4 のプロパティパネルにある「合成モード」のドロップダウンと並び順が同じで、0 から始まります。
|
||||
範囲外の値や数値以外を指定したときは通常モードになります。
|
||||
</p>
|
||||
|
||||
<pre><code>obj.setoption("blend", 3)
|
||||
obj.draw()</code></pre>
|
||||
|
||||
<table>
|
||||
<tr><th>番号</th><th>合成モード</th></tr>
|
||||
<tr><td><code>0</code></td><td>通常</td></tr>
|
||||
<tr><td><code>1</code></td><td>ディザ合成</td></tr>
|
||||
<tr><td><code>2</code></td><td>比較(暗)</td></tr>
|
||||
<tr><td><code>3</code></td><td>乗算</td></tr>
|
||||
<tr><td><code>4</code></td><td>焼き込みカラー</td></tr>
|
||||
<tr><td><code>5</code></td><td>焼き込み(リニア)</td></tr>
|
||||
<tr><td><code>6</code></td><td>比較(明)</td></tr>
|
||||
<tr><td><code>7</code></td><td>スクリーン</td></tr>
|
||||
<tr><td><code>8</code></td><td>覆い焼きカラー</td></tr>
|
||||
<tr><td><code>9</code></td><td>覆い焼き(リニア) - 加算</td></tr>
|
||||
<tr><td><code>10</code></td><td>加算</td></tr>
|
||||
<tr><td><code>11</code></td><td>オーバーレイ</td></tr>
|
||||
<tr><td><code>12</code></td><td>ソフトライト</td></tr>
|
||||
<tr><td><code>13</code></td><td>ハードライト</td></tr>
|
||||
<tr><td><code>14</code></td><td>ビビッドライト</td></tr>
|
||||
<tr><td><code>15</code></td><td>リニアライト</td></tr>
|
||||
<tr><td><code>16</code></td><td>ピンライト</td></tr>
|
||||
<tr><td><code>17</code></td><td>ハードミックス</td></tr>
|
||||
<tr><td><code>18</code></td><td>差分</td></tr>
|
||||
<tr><td><code>19</code></td><td>除外</td></tr>
|
||||
<tr><td><code>20</code></td><td>減算</td></tr>
|
||||
<tr><td><code>21</code></td><td>除算</td></tr>
|
||||
<tr><td><code>22</code></td><td>色相</td></tr>
|
||||
<tr><td><code>23</code></td><td>彩度</td></tr>
|
||||
<tr><td><code>24</code></td><td>カラー</td></tr>
|
||||
<tr><td><code>25</code></td><td>輝度</td></tr>
|
||||
<tr><td><code>26</code></td><td>カラー比較(明)</td></tr>
|
||||
<tr><td><code>27</code></td><td>背景</td></tr>
|
||||
<tr><td><code>28</code></td><td>カラー比較(暗)</td></tr>
|
||||
<tr><td><code>29</code></td><td>削除</td></tr>
|
||||
<tr><td><code>30</code></td><td>背景でクリッピング</td></tr>
|
||||
<tr><td><code>31</code></td><td>重ならない部分のみ</td></tr>
|
||||
<tr><td><code>32</code></td><td>色反転マスク</td></tr>
|
||||
</table>
|
||||
|
||||
<h3>描画先</h3>
|
||||
|
||||
<p>
|
||||
<code>obj.setoption("drawtarget", 先)</code> は <code>obj.draw</code>/<code>obj.drawpoly</code> の描画先を切り替えます。
|
||||
<code>"framebuffer"</code>(既定)ではフレームバッファへ合成します。
|
||||
<code>"tempbuffer"</code> では作業用の <code>tmp</code> バッファへその場で合成します。
|
||||
<code>obj.setoption("drawtarget", "tempbuffer", w, h)</code> の <code>w, h</code> は <code>tmp</code> バッファを初期化するサイズで、省略すると初期化しません。
|
||||
<code>tmp</code> へ描いた結果は <code>obj.copybuffer("obj", "tmp")</code> で作業画像へ戻せます。
|
||||
</p>
|
||||
|
||||
<p>
|
||||
<code>tempbuffer</code> への合成は通常(ソースオーバー)で、<code>blend</code> は <code>framebuffer</code> への描画に適用されます。
|
||||
描画先の切り替えは両エンジンで動きます。
|
||||
MoonSharp では <code>tempbuffer</code> への合成を GPU で実行し、GPU を利用できない環境では CPU の合成へ自動的に切り替わります。
|
||||
丸めの違いにより、合成の結果はエンジン間でごく僅かに異なることがあります。
|
||||
</p>
|
||||
|
||||
<pre><code>obj.setoption("drawtarget", "tempbuffer", obj.w, obj.h)
|
||||
obj.draw()
|
||||
obj.setoption("drawtarget", "framebuffer")
|
||||
obj.copybuffer("obj", "tmp")</code></pre>
|
||||
|
||||
<h3>アンカーポイント</h3>
|
||||
|
||||
<p>
|
||||
<code>obj.setanchor(name, count [, option, ...])</code> は、プレビュー上にドラッグ可能なアンカーポイントを表示します。
|
||||
ドラッグで調整した座標はプロジェクトへ保存され、<code>name</code> で指定した Lua 変数へ格納されます。
|
||||
変数は <code>pos={x0,y0,x1,y1,…}</code> の並びで、<code>"xyz"</code> を指定すると <code>{x0,y0,z0,x1,y1,z1,…}</code> になります。
|
||||
座標はオブジェクトの中心が原点です。個数は最大 32 個です。
|
||||
</p>
|
||||
|
||||
<table>
|
||||
<tr><th>オプション</th><th>意味</th></tr>
|
||||
<tr><td><code>"line"</code></td><td>アンカーポイントを線で結ぶ</td></tr>
|
||||
<tr><td><code>"loop"</code></td><td>アンカーポイントを線で結び一周させる</td></tr>
|
||||
<tr><td><code>"star"</code></td><td>各アンカーポイントとオブジェクトの中心を線で結ぶ</td></tr>
|
||||
<tr><td><code>"arm"</code></td><td>オブジェクトの中心から各アンカーポイントへ順に線で結ぶ</td></tr>
|
||||
<tr><td><code>"xyz"</code></td><td>アンカーポイントを 3D 座標で扱う。既定は 2D</td></tr>
|
||||
</table>
|
||||
|
||||
<p>
|
||||
戻り値は設置したアンカーポイントの数です。両エンジンで動きます。
|
||||
<code>name</code> に <code>"track"</code> を指定するトラックバー連携は現在未対応で、<code>0</code> を返します。
|
||||
</p>
|
||||
|
||||
<pre><code>num = obj.track0
|
||||
obj.setanchor("pos", num, "loop")
|
||||
for i = 0, num - 1 do
|
||||
obj.draw(pos[i * 2 + 1], pos[i * 2 + 2])
|
||||
end</code></pre>
|
||||
|
||||
<h3>互換マップ</h3>
|
||||
|
||||
<p>
|
||||
<code>obj.effect</code> は二段階で解決します。
|
||||
まず互換マップを参照し、AviUtl/AviUtl2 の名前として宣言したエフェクトは、
|
||||
パラメータ名の対応と値の変換を経て YMM4 のプロパティへ反映します。
|
||||
互換マップに宣言が無い名前は、YMM4 のエフェクト名やキーワードでそのまま解決します。
|
||||
たとえば <code>ウェーブクリッピング</code> のように、YMM4 やコミュニティのエフェクトを
|
||||
名前で呼ぶ使い方もそのまま動きます。
|
||||
</p>
|
||||
|
||||
<p>
|
||||
互換マップでは、パラメータの値を AviUtl と同じ尺度で渡すと、
|
||||
マップに定義した倍率とオフセットの変換を経て、YMM4 のプロパティへ反映します。
|
||||
たとえば <code>ぼかし</code> の <code>範囲</code> は YMM4 の <code>Blur</code> へ 0.5 倍で対応し、
|
||||
AviUtl と同じ見た目になります。
|
||||
この互換マップは、YMM4 自身が AviUtl の <code>.exo</code> へ書き出す変換を逆向きにたどって作っているため、
|
||||
往復しても結果が一致します。
|
||||
</p>
|
||||
|
||||
<p>
|
||||
対象のエンジンは指定子 <code>--!aviutl</code> または <code>--!aviutl2</code> で切り替えます。
|
||||
指定子を書かないときは <code>--!aviutl</code> として扱います。
|
||||
各エントリは対応するエンジンを AviUtl・AviUtl2・両方のいずれかとして保持し、
|
||||
対象に一致するエントリだけを解決します。
|
||||
</p>
|
||||
|
||||
<pre><code>--!aviutl
|
||||
obj.effect("ぼかし", "範囲", 20)
|
||||
obj.effect("方向ブラー", "範囲", 16, "角度", 45)</code></pre>
|
||||
|
||||
<p>現在マップが宣言している AviUtl のエフェクト名は次のとおりです。</p>
|
||||
|
||||
<table>
|
||||
<tr><th>エフェクト名</th><th>主なパラメータ</th></tr>
|
||||
<tr><td><code>ぼかし</code></td><td>範囲, サイズ固定</td></tr>
|
||||
<tr><td><code>境界ぼかし</code></td><td>範囲</td></tr>
|
||||
<tr><td><code>方向ブラー</code></td><td>範囲, 角度, サイズ固定</td></tr>
|
||||
<tr><td><code>放射ブラー</code></td><td>範囲, X, Y, サイズを固定</td></tr>
|
||||
<tr><td><code>閃光</code></td><td>範囲, X, Y, サイズを固定</td></tr>
|
||||
<tr><td><code>クロマキー</code></td><td>色相範囲, 境界補正</td></tr>
|
||||
<tr><td><code>クリッピング</code></td><td>上, 下, 左, 右, 中心の位置を変更</td></tr>
|
||||
<tr><td><code>斜めクリッピング</code></td><td>中心X, 中心Y, 角度, ぼかし, 幅</td></tr>
|
||||
<tr><td><code>領域拡張</code></td><td>上, 下, 左, 右</td></tr>
|
||||
<tr><td><code>座標</code></td><td>X, Y, Z</td></tr>
|
||||
<tr><td><code>回転</code></td><td>X, Y, Z</td></tr>
|
||||
<tr><td><code>リサイズ</code></td><td>拡大率, X, Y, 補間なし</td></tr>
|
||||
<tr><td><code>画像ループ</code></td><td>横回数, 縦回数</td></tr>
|
||||
<tr><td><code>極座標変換</code></td><td>中心幅, 渦巻</td></tr>
|
||||
<tr><td><code>グラデーション</code></td><td>強さ, 中心X, 中心Y, 角度, 幅</td></tr>
|
||||
<tr><td><code>単色化</code></td><td>強さ, 輝度を保持する</td></tr>
|
||||
<tr><td><code>縁取り</code></td><td>サイズ, ぼかし</td></tr>
|
||||
<tr><td><code>反転</code></td><td>—</td></tr>
|
||||
<tr><td><code>モザイク</code></td><td>サイズ</td></tr>
|
||||
<tr><td><code>ディスプレイスメントマップ</code></td><td>ぼかし</td></tr>
|
||||
<tr><td><code>動画ファイル合成</code></td><td>X, Y, 拡大率</td></tr>
|
||||
<tr><td><code>色調補正</code></td><td>明るさ, コントラスト, 色相, 輝度, 彩度</td></tr>
|
||||
<tr><td><code>色ずれ</code></td><td>ずれ幅, 角度, 強さ</td></tr>
|
||||
</table>
|
||||
|
||||
<div class="note">
|
||||
対象のエフェクトが YMM4 やコミュニティプラグインに読み込まれていないとき、または適用に失敗したときは、
|
||||
そのフレームでは元の映像をそのまま使います。このときログへ警告を一度だけ出します。
|
||||
<code>色調補正</code> と <code>色ずれ</code> はコミュニティプラグインのエフェクトに対応します。
|
||||
</div>
|
||||
|
||||
<div class="pager">
|
||||
<a href="obj.html">← obj オブジェクト</a>
|
||||
<a href="anim.html">anim ライブラリ →</a>
|
||||
</div>
|
||||
|
||||
</main>
|
||||
<script src="assets/nav.js"></script>
|
||||
</body>
|
||||
</html>
|
||||
109ファイル中100ファイルを読み込みました。 変更されたファイルが多すぎるため、それ以降のファイルは表示していません。
さらに表示
新しいイシューから参照
ユーザーをブロックする