コミットを比較
| 作成者 | SHA1 | 日付 | |
|---|---|---|---|
|
|
1f421dd158
|
||
|
|
e56a2d85d7
|
||
|
|
969cf52299
|
||
|
|
01785267fc
|
||
|
|
206001888c
|
||
|
|
7c8776dd05
|
||
|
|
d6756ad3c8
|
||
|
|
57c3b346d8
|
||
|
|
55dde273ae
|
||
|
|
a6a9963c85
|
||
|
|
fb7614d6fb
|
||
|
|
a7a8c6b117
|
||
|
|
8b59897992
|
||
|
|
0d8f1e5102
|
||
|
|
e6165ca5a3
|
||
|
|
2bd54674c1
|
||
|
|
9a733807e8
|
||
|
|
f14c689353
|
||
|
|
d4443a1eef
|
||
|
|
b618a3093b
|
||
|
|
a03ba45f2a
|
||
|
|
56c38b2891
|
||
|
|
68b730e6d2
|
||
|
|
ce7b15121c
|
||
|
|
50b20e3060
|
||
|
|
c1f4fa2dc5
|
||
|
|
af9c5af173
|
||
|
|
406a4c1a1b
|
||
|
|
b732dd1b90
|
||
|
|
1e93df21ef
|
||
|
|
3bd6133bef
|
||
|
|
0c05fe2198
|
||
|
|
775791d1e1
|
||
|
|
a291d66567
|
||
|
|
31d26c0a70
|
||
|
|
88b95cc09a
|
||
|
|
9ff328d03a
|
||
|
|
481bce261e
|
||
|
|
421acf1a6a
|
||
|
|
1d01e9d275
|
||
|
|
1a3394b8f5
|
||
|
|
52bbff8284
|
||
|
|
b150970f83
|
||
|
|
6ce23d486a
|
||
|
|
024723a029
|
||
|
|
4746f01134
|
||
|
|
f2ea36ba49
|
||
|
|
adf47608d2
|
||
|
|
f916c810dc
|
||
|
|
9b86a3cb10
|
||
|
|
0fd1194596
|
||
|
|
72aa5d7351
|
||
|
|
a68c0fedd6
|
||
|
|
c5ed30bc72
|
||
|
|
6f44e30fa1
|
||
|
|
3db40f07cb
|
||
|
|
ff8791d086
|
||
|
|
f7f445bd3d
|
||
|
|
68af14bbf8
|
||
|
|
7a23318be3
|
||
|
|
4072d9b117
|
||
|
|
bc366a0af2
|
||
|
|
0c896d44ee
|
||
|
|
9a9acc4b85
|
||
|
|
a7e2285691
|
||
|
|
093e16feec
|
||
|
|
70b1b79fc2
|
||
|
|
995e1bc1aa
|
||
|
|
1120373e67
|
||
|
|
43b3ed7077
|
||
|
|
04ab6b111b
|
||
|
|
5d6787e7d6
|
||
|
|
6960406965
|
||
|
|
9454310988
|
||
|
|
d3118d20af
|
||
|
|
78337c06dd
|
||
|
|
85fc0f8e9f
|
||
|
|
c19ae507cf
|
||
|
|
004041b342
|
||
|
|
08f69cf76d
|
||
|
|
e10bfbe406
|
||
|
|
1a46a76b59
|
||
|
|
e2f32a6722
|
||
|
|
5a23f4329e
|
||
|
|
f5fd6cebdb
|
||
|
|
48f6711f1a
|
||
|
|
859046f5aa
|
||
|
|
7c7a60807f
|
||
|
|
1b23b2937e
|
||
|
|
4135f52499
|
||
|
|
8fda0bfec5
|
||
|
|
7e353053c7
|
||
|
|
d744d218fb
|
||
|
|
772fa6b678
|
||
|
|
154bc6a5c0
|
||
|
|
593939c2d4
|
||
|
|
6730c8ce70
|
||
|
|
b6a1e6e43c
|
||
|
|
fd06fdafe7
|
||
|
|
20a119c6c8
|
||
|
|
cfa8141424
|
||
|
|
7a2a7e5593
|
||
|
|
1a61091ec2
|
||
|
|
bbb1bd3562
|
||
|
|
db8017a8ce
|
||
|
|
bc69ec5681
|
||
|
|
8f6c3105ef
|
||
|
|
de6c1b8b44
|
||
|
|
ffd57fabd0
|
||
|
|
a80d5dec88
|
||
|
|
8bccf5ed01
|
||
|
|
7c831441fc
|
||
|
|
7cd54ff3e8
|
||
|
|
3c3f5aed69
|
||
|
|
913e1a8643
|
||
|
|
f6c7dac970
|
||
|
|
95db23f253
|
||
|
|
62044a3351
|
||
|
|
694b50d375
|
||
|
|
122d85068d
|
||
|
|
620670915f
|
||
|
|
10974242aa
|
||
|
|
36b2ada16a
|
検索条件に一致するファイルはありません
+24
-55
@@ -1,75 +1,44 @@
|
||||
# v1.16.0 - Lua スクリプト for YMM4
|
||||
# v1.20.1 - Lua スクリプト for YMM4
|
||||
|
||||
標準の Lua には無い簡易な記法を構文拡張へ 6 種類追加したリリースです。三項演算子、nil 条件演算子、ラムダ式、パイプ、補間文字列、範囲判定を書けるようになりました。いずれもスクリプトの実行前に等価な標準 Lua へ変換するため、LuaJIT、MoonSharp、CPU カーネルのどの実行エンジンでも同じ結果になります。変換は字句単位で行い、文字列とコメントの内側は変換しません。入口とする記号は通常の Lua には現れないため、既存のスクリプトの書き方と実行結果に変更はありません。
|
||||
画像加工の GPU 委譲を自動判定へ変更したリリースです。v1.20.0 では obj.fill / obj.convolve / obj.resize は [fast] マーカーを付けたときだけ GPU へ委譲していましたが、本バージョンからは標準の呼び出しでも、処理量がしきい値以上で GPU の結果が CPU と一致すると確認できたとき、自動で GPU へ委譲します。マーカーを知らなくても大きな処理は速くなり、成立しない場合は従来どおり CPU で実行するため結果は変わりません。[fast] は構文・診断ともそのまま残り、委譲の意図を明示する補助マーカーになりました。置いても動作は変わりません。
|
||||
|
||||
---
|
||||
|
||||
## 新機能
|
||||
## 変更
|
||||
|
||||
### 三項演算子
|
||||
### 画像加工の GPU 委譲を自動判定へ
|
||||
|
||||
条件 ? A : B を追加しました。条件が真のとき A を、偽のとき B を返します。条件と両辺は同じ行に式として書きます。
|
||||
obj.fill / obj.convolve / obj.resize は書き方を変えることなく、条件が成立したとき自動で GPU へ委譲します。委譲が成立する条件は v1.20.0 の [fast] と同じで、いずれかを満たさない場合は自動で CPU 実行になり、処理は失敗しません。
|
||||
|
||||
- (function() if 条件 then return (A) else return (B) end end)() へ展開します。条件は 1 度だけ評価し、選ばれた側の式だけを評価します。
|
||||
- a and b or c と違い、真の側の値が false や nil であっても、その値をそのまま返します。
|
||||
- : のあとにもう一度 ? : を書けば、else 側で分岐を続けられます。
|
||||
- 関数呼び出しの引数の位置にも書けます。? を値の位置に書いたときだけ変換するため、テーブルリテラルやメソッド呼び出し、ラベルなど、通常のコードには影響しません。
|
||||
- Direct3D 11 のハードウェアデバイスが利用できること。ソフトウェアラスタライザ(WARP)へは委譲しません。CPU 実装より遅くなるためです。
|
||||
- 処理量がしきい値以上であること。fill は画像全体で 1,048,576 画素以上、矩形指定では同じ画素数に加えて塗り面積が画像の 3/4 以上、resize は出力が 262,144 画素以上、convolve は画素数×係数の個数が 262,144 以上です。小さな処理は委譲の往復コストが上回るため CPU で実行します。
|
||||
- convolve のカーネルは 31×31 までです。それを超えるサイズは CPU で実行します。
|
||||
- 初回に小さな検証画像で GPU の結果を CPU 基準とバイト単位で比較し、一致した組み合わせだけを GPU へ委譲すること。不一致の環境やカーネルでは CPU 実行へ戻ります。
|
||||
|
||||
### nil 条件演算子
|
||||
### [fast] マーカーは補助的な明示へ
|
||||
|
||||
t?.x と t?[k] を追加しました。t が nil のときは nil を返し、そうでなければ t.x や t[k] を返します。nil の値へ添字アクセスして実行時エラーになるのを防ぎます。
|
||||
判定が自動になったため、[fast] は委譲の意図を明示する補助マーカーになりました。
|
||||
|
||||
- 対象を一時変数へ受けて 1 度だけ評価する無名関数へ展開します。(function() local tmp = (t) if tmp == nil then return nil end return tmp.x end)() の形になります。
|
||||
- a?.b?.c のように連ねれば、途中の値が nil でも安全にたどれます。
|
||||
- nil 合体演算子と組み合わせて、t?.x ?? 既定値 のように書けます。左辺が nil のときだけ既定値を返します。
|
||||
|
||||
### ラムダ式
|
||||
|
||||
(a, b) => 式 を追加しました。その式を返す無名関数へ展開し、(function(a, b) return 式 end) になります。
|
||||
|
||||
- 引数が 1 つのときは括弧を省いて x => 式、引数が無いときは () => 式 と書けます。最後の引数として ... を受け取れます。本体には 1 つの式を書きます。
|
||||
- table.sort の比較関数のように、関数を引数へ直接渡す場面で使えます。
|
||||
- 入口は => だけのため、比較演算子の >= や <= には影響しません。
|
||||
|
||||
### パイプ
|
||||
|
||||
x |> f を追加しました。f((x)) へ展開し、左辺を関数の第 1 引数として渡します。
|
||||
|
||||
- x |> f(a, b) のように引数を書いたときは、左辺が第 1 引数に入り、残りの引数は後ろへ続いて f((x), a, b) になります。
|
||||
- |> は左から右へ連ねられます。a |> f |> g は g(f(a)) と同じ順序で評価します。
|
||||
- math.floor のようなメンバー関数も呼べます。
|
||||
|
||||
### 補間文字列
|
||||
|
||||
バッククォートで囲む文字列を追加しました。中に {式} を書くと、その値を tostring で文字列にして差し込みます。
|
||||
|
||||
- `x={a}` は ("x=" .. tostring(a)) へ展開します。式を含まない `hello` は "hello" に、空の `` は "" になります。
|
||||
- { } の中では拡張構文もそのまま使えます。バックスラッシュによるエスケープは保持します。
|
||||
- 入口はバッククォートのため、通常の文字列やコメントの中のバッククォートは変換しません。
|
||||
|
||||
### 範囲判定
|
||||
|
||||
x in <1..5> を追加しました。x がその範囲に入っているかどうかを判定します。.. は終端を含み、..< は終端を含みません。
|
||||
|
||||
- 左辺を一時変数へ受けて 1 度だけ評価する無名関数へ展開し、1 <= x and x <= 5 に相当する判定を返します。<1..<5> は上限を含まず、1 <= x and x < 5 になります。
|
||||
- 範囲 for の for i in <0..10> とは書く位置が異なるため、for のヘッダーや、ipairs、pairs を使う汎用 for には影響しません。
|
||||
- 増分を伴う <開始..終了, 増分> の書き方は、範囲判定では扱いません。
|
||||
- 構文・置ける位置(単独の行または同じ行)・内部プリミティブへの書き換えは v1.20.0 から変わりません。
|
||||
- 3 関数以外へ付けたときのエラー表示もそのまま機能します。
|
||||
- [fast] を付けた呼び出しと付けない呼び出しは同じ判定を通るため、動作の差はありません。既存の [fast] 付きスクリプトはそのまま動きます。
|
||||
|
||||
---
|
||||
|
||||
## 互換性・後方互換
|
||||
|
||||
- 追加した記法はいずれも、標準の Lua には現れない記号、つまり ? と => と |> とバッククォートと in < の並びを入口にしています。既存のスクリプトはそのまま動作し、実行結果も変わりません。
|
||||
- 変換はすべての実行エンジンに適用され、LuaJIT、MoonSharp、CPU カーネルのいずれでも同じ結果になります。文字列とコメントの内側は変換しません。
|
||||
- 分岐の各辺、ラムダの本体、パイプの対象、補間文字列の {式}、範囲判定の両端など、入れ子になった式にも構文拡張の変換を再帰的に適用します。
|
||||
- v1.15.0 までの仕様に変更はありません。obj.pixelshader をはじめとする既存の API と、実行エンジンの自動振り分けに変更はありません。
|
||||
- しきい値未満の小さな処理、GPU が使えない環境、検証に通らないカーネルでは、実行結果は v1.20.0 と同一です。
|
||||
- GPU 委譲は事前の検証で CPU 基準とバイト単位まで一致した組み合わせに限って行い、成立しない場合は常に CPU 実装が結果を保証します。
|
||||
- 関数の引数・戻り値・エラーの扱いに変更はありません。スクリプトの書き換えは不要です。
|
||||
- エンジンの自動振り分け、エンジン指定ディレクティブの仕様と優先順位、カーネル化の対象、v1.20.0 までの構文拡張と既存の API に変更はありません。
|
||||
|
||||
---
|
||||
|
||||
## 内部実装
|
||||
|
||||
- 字句解析器に補間文字列のトークン種別を追加し、バッククォートで囲む文字列を 1 つのトークンとして読み取ります。あわせて演算子として => と |> を追加しました。
|
||||
- 範囲の解析を共通のヘルパーへ切り出しました。開始・終了・増分と、終端を含むかどうかを 1 か所で判定し、範囲 for と範囲判定の両方がこのヘルパーを使います。
|
||||
- 各記法は、属性で優先順位を与えた変換規則として実装しました。nil 条件演算子の規則は三項演算子より先に走り、?. と ?[ を単独の ? より先に処理します。既存の変換基盤はそのまま流用し、変換文脈に変更はありません。
|
||||
- ドキュメントは付属の 8 言語、サイトの構文拡張のページ、README を更新しました。
|
||||
- テストは 3297 件です。v1.15.0 の 3259 件から、三項演算子、nil 条件演算子、ラムダ式、パイプ、補間文字列、範囲判定の各変換と評価、入れ子になった式の変換、比較演算子や for のヘッダーを変換しないこと、対象や左辺を 1 度だけ評価することの検証を追加しました。
|
||||
- 3 実行系(MoonSharp・LuaJIT ワーカー・コンテキスト契約)から委譲の明示フラグ accelerate を削除しました。[fast] の書き換え先である __fast_fill / __fast_convolve / __fast_resize は標準の関数と同じ実装の別名になり、マーカーの有無で経路が分かれることは構造的にありません。
|
||||
- 従来エンジンは AviUtlScriptContext の fill / convolve / resize が常にプロセッサへ照会し、不成立なら CPU 実装へ落ちます。しきい値の判定は GPU 演算側(GpuFillOperation / GpuConvolveOperation / GpuResizeOperation)が持ちます。
|
||||
- 高速ランタイムは worker.lua がしきい値の成立時のみホストへ往復し、しきい値未満は往復せず Lua 内で完結します。成立し得ない委譲のプロセス間往復コストは発生しません。
|
||||
- GPU 基盤(専用プロジェクト・事前 DXBC コンパイル・検証キャッシュ・再生成予算)は v1.20.0 のまま変更していません。
|
||||
- ドキュメントは付属の 8 言語の [fast] の節、サイトの構文拡張と obj の関数のページ、README を自動判定の仕様へ更新しました。
|
||||
- テストは 3400 件です。v1.20.0 の 3396 件から、標準呼び出しがホストプロセッサへ委譲されることの検証へ両レーンの既定経路テストを反転し、しきい値未満では委譲しないことの検証 3 件と、従来エンジンの委譲と CPU フォールバックの検証 1 件を追加しました。ソリューションは x64 で 0 個の警告、0 個のエラーです。
|
||||
@@ -1,11 +1,11 @@
|
||||
========================================
|
||||
Luaスクリプト for YMM4 v1.16.0
|
||||
Luaスクリプト for YMM4 v1.20.1
|
||||
========================================
|
||||
YukkuriMovieMaker4(YMM4)上で動作する、Luaスクリプトで映像エフェクトのパラメータや
|
||||
ピクセルを直接制御できるプラグインです。
|
||||
スクリプトの実行にはMoonSharpによるLuaインタプリタを使用しており、座標・拡大率・
|
||||
透明度・回転といった描画パラメータの変更に加えて、ピクセル単位での読み書きにも
|
||||
対応しています。
|
||||
透明度・回転といった描画パラメータの変更に加えて、ピクセル単位での読み書きや、
|
||||
塗りつぶし・領域の一括読み書き・畳み込み・拡大縮小による画像加工にも対応しています。
|
||||
obj.x/y/zoom/alpha等の値はキーフレームアニメーションと連動するTrack0~3パラメータ
|
||||
からも参照でき、anim.*関数群によるイージングやノイズ等の演出も組み合わせられます。
|
||||
--------------------------------------------------------------------------------
|
||||
|
||||
@@ -77,6 +77,7 @@ jobs:
|
||||
Copy-Item "$outDir/LuaScript.Compat.dll" "$stageRoot/"
|
||||
Copy-Item "$outDir/LuaScript.Media.dll" "$stageRoot/"
|
||||
Copy-Item "$outDir/LuaScript.Runtime.dll" "$stageRoot/"
|
||||
Copy-Item "$outDir/LuaScript.Gpu.dll" "$stageRoot/"
|
||||
Copy-Item "$outDir/MoonSharp.Interpreter.dll" "$stageRoot/"
|
||||
Copy-Item "$outDir/native/luajit.exe" "$stageRoot/native/"
|
||||
Copy-Item "$outDir/native/lua51.dll" "$stageRoot/native/"
|
||||
|
||||
@@ -0,0 +1,195 @@
|
||||
using System;
|
||||
|
||||
namespace LuaScript.Compat
|
||||
{
|
||||
internal sealed class AviUtlAudioConverter
|
||||
{
|
||||
public const int MaxSamples = 1024;
|
||||
public const int SpectrumWindow = 1024;
|
||||
public const int FourierWindow = 2048;
|
||||
public const int SpectrumBins = SpectrumWindow / 2;
|
||||
|
||||
private const double PcmScale = 32768d;
|
||||
|
||||
private readonly double[] _mono = new double[FourierWindow];
|
||||
private readonly double[] _real = new double[FourierWindow];
|
||||
private readonly double[] _imag = new double[FourierWindow];
|
||||
|
||||
private enum DataKind
|
||||
{
|
||||
Unknown,
|
||||
Pcm,
|
||||
Spectrum,
|
||||
Fourier,
|
||||
}
|
||||
|
||||
public static int RequiredFrames(string type, int size)
|
||||
{
|
||||
var (kind, _) = Parse(type);
|
||||
return kind switch
|
||||
{
|
||||
DataKind.Pcm => ResolveCount(kind, size),
|
||||
DataKind.Spectrum => SpectrumWindow,
|
||||
DataKind.Fourier => FourierWindow,
|
||||
_ => 0,
|
||||
};
|
||||
}
|
||||
|
||||
public int Convert(string type, ReadOnlySpan<float> interleaved, int frames, int size, Span<double> destination)
|
||||
{
|
||||
var (kind, channel) = Parse(type);
|
||||
if (kind == DataKind.Unknown || frames <= 0)
|
||||
return 0;
|
||||
|
||||
int window = kind switch
|
||||
{
|
||||
DataKind.Pcm => Math.Min(frames, ResolveCount(kind, size)),
|
||||
DataKind.Spectrum => SpectrumWindow,
|
||||
_ => FourierWindow,
|
||||
};
|
||||
FillMono(interleaved, frames, channel, window);
|
||||
|
||||
switch (kind)
|
||||
{
|
||||
case DataKind.Pcm:
|
||||
{
|
||||
int count = Math.Min(ResolveCount(kind, size), frames);
|
||||
for (int i = 0; i < count; i++)
|
||||
destination[i] = Math.Clamp(_mono[i] * PcmScale, -32768d, 32767d);
|
||||
return count;
|
||||
}
|
||||
case DataKind.Spectrum:
|
||||
{
|
||||
int bands = ResolveCount(kind, size);
|
||||
Fft(SpectrumWindow);
|
||||
double scale = 2d / SpectrumWindow * PcmScale;
|
||||
for (int b = 0; b < bands; b++)
|
||||
{
|
||||
int start = b * SpectrumBins / bands;
|
||||
int end = (b + 1) * SpectrumBins / bands;
|
||||
if (end <= start)
|
||||
end = start + 1;
|
||||
double sum = 0d;
|
||||
for (int bin = start; bin < end; bin++)
|
||||
sum += Magnitude(bin);
|
||||
destination[b] = sum / (end - start) * scale;
|
||||
}
|
||||
return bands;
|
||||
}
|
||||
case DataKind.Fourier:
|
||||
{
|
||||
int count = ResolveCount(kind, size);
|
||||
Fft(FourierWindow);
|
||||
double scale = 2d / FourierWindow;
|
||||
for (int i = 0; i < count; i++)
|
||||
destination[i] = Magnitude(i + 1) * scale;
|
||||
return count;
|
||||
}
|
||||
default:
|
||||
return 0;
|
||||
}
|
||||
}
|
||||
|
||||
private static int ResolveCount(DataKind kind, int size)
|
||||
{
|
||||
int fallback = kind == DataKind.Spectrum ? 32 : MaxSamples;
|
||||
int max = kind == DataKind.Spectrum ? SpectrumBins : MaxSamples;
|
||||
return size <= 0 ? Math.Min(fallback, max) : Math.Clamp(size, 1, max);
|
||||
}
|
||||
|
||||
private static (DataKind Kind, int Channel) Parse(string type)
|
||||
{
|
||||
int channel = 0;
|
||||
int length = type.Length;
|
||||
if (length >= 2 && type[length - 2] == '.')
|
||||
{
|
||||
char suffix = type[length - 1];
|
||||
if (suffix == 'l')
|
||||
channel = 1;
|
||||
else if (suffix == 'r')
|
||||
channel = 2;
|
||||
if (channel != 0)
|
||||
length -= 2;
|
||||
}
|
||||
|
||||
var name = type.AsSpan(0, length);
|
||||
DataKind kind = DataKind.Unknown;
|
||||
if (name.SequenceEqual("pcm"))
|
||||
kind = DataKind.Pcm;
|
||||
else if (name.SequenceEqual("spectrum"))
|
||||
kind = DataKind.Spectrum;
|
||||
else if (name.SequenceEqual("fourier"))
|
||||
kind = DataKind.Fourier;
|
||||
return (kind, channel);
|
||||
}
|
||||
|
||||
private void FillMono(ReadOnlySpan<float> interleaved, int frames, int channel, int window)
|
||||
{
|
||||
int available = Math.Min(frames, window);
|
||||
for (int i = 0; i < available; i++)
|
||||
{
|
||||
float left = interleaved[i * 2];
|
||||
float right = interleaved[i * 2 + 1];
|
||||
_mono[i] = channel switch
|
||||
{
|
||||
1 => left,
|
||||
2 => right,
|
||||
_ => (left + right) * 0.5d,
|
||||
};
|
||||
}
|
||||
for (int i = available; i < window; i++)
|
||||
_mono[i] = 0d;
|
||||
}
|
||||
|
||||
private double Magnitude(int bin) =>
|
||||
Math.Sqrt(_real[bin] * _real[bin] + _imag[bin] * _imag[bin]);
|
||||
|
||||
private void Fft(int n)
|
||||
{
|
||||
for (int i = 0; i < n; i++)
|
||||
{
|
||||
_real[i] = _mono[i];
|
||||
_imag[i] = 0d;
|
||||
}
|
||||
|
||||
for (int i = 1, j = 0; i < n; i++)
|
||||
{
|
||||
int bit = n >> 1;
|
||||
for (; (j & bit) != 0; bit >>= 1)
|
||||
j ^= bit;
|
||||
j |= bit;
|
||||
if (i < j)
|
||||
{
|
||||
(_real[i], _real[j]) = (_real[j], _real[i]);
|
||||
(_imag[i], _imag[j]) = (_imag[j], _imag[i]);
|
||||
}
|
||||
}
|
||||
|
||||
for (int len = 2; len <= n; len <<= 1)
|
||||
{
|
||||
double angle = -2d * Math.PI / len;
|
||||
double wRe = Math.Cos(angle);
|
||||
double wIm = Math.Sin(angle);
|
||||
for (int i = 0; i < n; i += len)
|
||||
{
|
||||
double curRe = 1d;
|
||||
double curIm = 0d;
|
||||
for (int k = 0; k < len / 2; k++)
|
||||
{
|
||||
int a = i + k;
|
||||
int b = i + k + len / 2;
|
||||
double tRe = _real[b] * curRe - _imag[b] * curIm;
|
||||
double tIm = _real[b] * curIm + _imag[b] * curRe;
|
||||
_real[b] = _real[a] - tRe;
|
||||
_imag[b] = _imag[a] - tIm;
|
||||
_real[a] += tRe;
|
||||
_imag[a] += tIm;
|
||||
double nextRe = curRe * wRe - curIm * wIm;
|
||||
curIm = curRe * wIm + curIm * wRe;
|
||||
curRe = nextRe;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -3,7 +3,7 @@
|
||||
<PropertyGroup>
|
||||
<TargetFramework>net10.0-windows10.0.19041.0</TargetFramework>
|
||||
<ImplicitUsings>enable</ImplicitUsings>
|
||||
<Version>1.16.0</Version>
|
||||
<Version>1.20.1</Version>
|
||||
<Platforms>AnyCPU;x64</Platforms>
|
||||
<Nullable>enable</Nullable>
|
||||
</PropertyGroup>
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Text;
|
||||
using LuaScript.Compat.Syntax;
|
||||
|
||||
namespace LuaScript.Compat
|
||||
{
|
||||
@@ -15,10 +16,10 @@ namespace LuaScript.Compat
|
||||
|
||||
public static string Transform(string source) => TransformWithMap(source).Code;
|
||||
|
||||
public static (string Code, int[] LineMap, int[] ChangedLines) TransformWithMap(string source)
|
||||
public static (string Code, int[] LineMap, int[] ChangedLines, LuaRewriteDiagnostic[] Diagnostics) TransformWithMap(string source)
|
||||
{
|
||||
if (string.IsNullOrEmpty(source))
|
||||
return (source, [], []);
|
||||
return (source, [], [], []);
|
||||
|
||||
var lines = ScriptParserHelper.SplitLines(source);
|
||||
bool hasSection = ScriptParserHelper.TryFindSection(lines, out int sectionStart, out int sectionEnd);
|
||||
@@ -29,8 +30,8 @@ namespace LuaScript.Compat
|
||||
|
||||
if (!hasSection && prelude.Count == 0)
|
||||
{
|
||||
var (code, changed) = LuaSyntaxExtensions.RewriteWithMap(source);
|
||||
return (code, [], changed);
|
||||
var (code, changed, preludeless) = LuaSyntaxExtensions.RewriteWithMap(source);
|
||||
return (code, [], changed, preludeless);
|
||||
}
|
||||
|
||||
var builder = new StringBuilder(source.Length + 64);
|
||||
@@ -48,8 +49,8 @@ namespace LuaScript.Compat
|
||||
lineMap[row++] = i;
|
||||
}
|
||||
|
||||
var (rewritten, changedLines) = LuaSyntaxExtensions.RewriteWithMap(builder.ToString());
|
||||
return (rewritten, lineMap, changedLines);
|
||||
var (rewritten, changedLines, diagnostics) = LuaSyntaxExtensions.RewriteWithMap(builder.ToString());
|
||||
return (rewritten, lineMap, changedLines, diagnostics);
|
||||
}
|
||||
|
||||
private static void AppendDeclarations(string line, List<string> prelude)
|
||||
|
||||
@@ -6,10 +6,10 @@ namespace LuaScript.Compat
|
||||
{
|
||||
public static string Rewrite(string source) => RewriteWithMap(source).Code;
|
||||
|
||||
public static (string Code, int[] ChangedLines) RewriteWithMap(string source)
|
||||
public static (string Code, int[] ChangedLines, LuaRewriteDiagnostic[] Diagnostics) RewriteWithMap(string source)
|
||||
{
|
||||
if (string.IsNullOrEmpty(source))
|
||||
return (source, []);
|
||||
return (source, [], []);
|
||||
|
||||
var tokens = LuaSyntaxLexer.Tokenize(source);
|
||||
var context = new LuaRewriteContext(tokens);
|
||||
@@ -42,7 +42,8 @@ namespace LuaScript.Compat
|
||||
}
|
||||
}
|
||||
|
||||
return context.Changed ? (context.Serialize(), context.ChangedLines) : (source, []);
|
||||
var diagnostics = context.Diagnostics;
|
||||
return context.Changed ? (context.Serialize(), context.ChangedLines, diagnostics) : (source, [], diagnostics);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -8,6 +8,7 @@ namespace LuaScript.Compat.Syntax
|
||||
private readonly List<LuaSyntaxToken> _input;
|
||||
private readonly List<LuaSyntaxToken> _output;
|
||||
private List<int>? _changedLines;
|
||||
private List<LuaRewriteDiagnostic>? _diagnostics;
|
||||
private int _line = 1;
|
||||
private int _lastChangedLine;
|
||||
private int _temporaries;
|
||||
@@ -28,6 +29,14 @@ namespace LuaScript.Compat.Syntax
|
||||
|
||||
public int[] ChangedLines => _changedLines is null ? [] : _changedLines.ToArray();
|
||||
|
||||
public LuaRewriteDiagnostic[] Diagnostics => _diagnostics is null ? [] : _diagnostics.ToArray();
|
||||
|
||||
public void AddDiagnostic(string message)
|
||||
{
|
||||
(_diagnostics ??= new List<LuaRewriteDiagnostic>()).Add(new LuaRewriteDiagnostic(_line, message));
|
||||
MarkChanged();
|
||||
}
|
||||
|
||||
public bool AtEnd => Index >= _input.Count;
|
||||
|
||||
public LuaSyntaxToken Current => _input[Index];
|
||||
|
||||
@@ -0,0 +1,4 @@
|
||||
namespace LuaScript.Compat.Syntax
|
||||
{
|
||||
internal readonly record struct LuaRewriteDiagnostic(int Line, string Message);
|
||||
}
|
||||
@@ -6,5 +6,9 @@ namespace LuaScript.Compat.Syntax
|
||||
internal sealed class LuaSyntaxRuleAttribute(int order) : Attribute
|
||||
{
|
||||
public int Order { get; } = order;
|
||||
|
||||
public bool IsCatalog { get; set; }
|
||||
|
||||
public string Keyword { get; set; } = "";
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,76 @@
|
||||
namespace LuaScript.Compat.Syntax.Rules
|
||||
{
|
||||
[LuaSyntaxRule(2, IsCatalog = true, Keyword = MarkerKeyword)]
|
||||
internal sealed class LuaFastRule : ILuaSyntaxRule
|
||||
{
|
||||
private const string MarkerKeyword = "fast";
|
||||
private const string Message = "[fast]: only obj.fill, obj.convolve and obj.resize can be accelerated.";
|
||||
|
||||
public bool TryApply(LuaRewriteContext context)
|
||||
{
|
||||
if (!context.Current.IsOperator("["))
|
||||
return false;
|
||||
|
||||
if (context.TryPreviousOutputSignificantSameLine(out var previous) && LuaSyntaxFacts.IsValueEnd(previous))
|
||||
return false;
|
||||
|
||||
int nameIndex = context.NextSignificant(context.Index + 1);
|
||||
if (nameIndex < 0 || !context.Input[nameIndex].IsName(MarkerKeyword))
|
||||
return false;
|
||||
|
||||
int closeIndex = context.NextSignificant(nameIndex + 1);
|
||||
if (closeIndex < 0 || !context.Input[closeIndex].IsOperator("]"))
|
||||
return false;
|
||||
|
||||
int targetIndex = context.NextSignificant(closeIndex + 1);
|
||||
if (targetIndex < 0 || context.Input[targetIndex].Kind != LuaSyntaxTokenKind.Name)
|
||||
return false;
|
||||
|
||||
if (TryResolveTarget(context, targetIndex, out int funcIndex, out string function))
|
||||
{
|
||||
EmitBetween(context, closeIndex + 1, targetIndex);
|
||||
context.Index = funcIndex + 1;
|
||||
context.EmitRaw("__fast_" + function);
|
||||
return true;
|
||||
}
|
||||
|
||||
context.AddDiagnostic(Message);
|
||||
EmitBetween(context, closeIndex + 1, targetIndex);
|
||||
context.Index = targetIndex;
|
||||
return true;
|
||||
}
|
||||
|
||||
private static bool TryResolveTarget(LuaRewriteContext context, int objIndex, out int funcIndex, out string function)
|
||||
{
|
||||
funcIndex = -1;
|
||||
function = string.Empty;
|
||||
if (!context.Input[objIndex].IsName("obj"))
|
||||
return false;
|
||||
|
||||
int dot = context.NextSignificant(objIndex + 1);
|
||||
if (dot < 0 || !context.Input[dot].IsOperator("."))
|
||||
return false;
|
||||
|
||||
int name = context.NextSignificant(dot + 1);
|
||||
if (name < 0)
|
||||
return false;
|
||||
string text = context.Input[name].Text;
|
||||
if (text is not ("fill" or "convolve" or "resize"))
|
||||
return false;
|
||||
|
||||
int paren = context.NextSignificant(name + 1);
|
||||
if (paren < 0 || !context.Input[paren].IsOperator("("))
|
||||
return false;
|
||||
|
||||
funcIndex = name;
|
||||
function = text;
|
||||
return true;
|
||||
}
|
||||
|
||||
private static void EmitBetween(LuaRewriteContext context, int from, int to)
|
||||
{
|
||||
for (int i = from; i < to; i++)
|
||||
context.Emit(context.Input[i]);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,8 @@
|
||||
namespace LuaScript.Generator
|
||||
{
|
||||
internal sealed record GpuShaderClass(
|
||||
string Namespace,
|
||||
EquatableArray<GpuShaderTypePart> TypeChain,
|
||||
EquatableArray<GpuShaderMethod> Methods,
|
||||
EquatableArray<string> Errors);
|
||||
}
|
||||
@@ -0,0 +1,4 @@
|
||||
namespace LuaScript.Generator
|
||||
{
|
||||
internal sealed record GpuShaderFile(string Path, string Source);
|
||||
}
|
||||
@@ -0,0 +1,4 @@
|
||||
namespace LuaScript.Generator
|
||||
{
|
||||
internal sealed record GpuShaderInvocation(string Resources, string Constants, string Target, string Width, string Height);
|
||||
}
|
||||
@@ -0,0 +1,12 @@
|
||||
namespace LuaScript.Generator
|
||||
{
|
||||
internal sealed record GpuShaderMethod(
|
||||
string Accessibility,
|
||||
bool IsStatic,
|
||||
string ReturnType,
|
||||
string MethodName,
|
||||
EquatableArray<GpuShaderParameter> Parameters,
|
||||
string FileName,
|
||||
string EntryPoint,
|
||||
GpuShaderInvocation Invocation);
|
||||
}
|
||||
@@ -0,0 +1,4 @@
|
||||
namespace LuaScript.Generator
|
||||
{
|
||||
internal sealed record GpuShaderMethodSource(GpuShaderMethod Method, string Bytecode);
|
||||
}
|
||||
@@ -0,0 +1,4 @@
|
||||
namespace LuaScript.Generator
|
||||
{
|
||||
internal sealed record GpuShaderParameter(string Prefix, string Type, string Name);
|
||||
}
|
||||
@@ -0,0 +1,6 @@
|
||||
using System.Collections.Immutable;
|
||||
|
||||
namespace LuaScript.Generator
|
||||
{
|
||||
internal sealed record GpuShaderResolution(ImmutableArray<GpuShaderMethodSource> Methods, ImmutableArray<string> Errors);
|
||||
}
|
||||
@@ -0,0 +1,436 @@
|
||||
using System.Collections.Immutable;
|
||||
using System.Globalization;
|
||||
using System.IO;
|
||||
using System.Text;
|
||||
using Microsoft.CodeAnalysis;
|
||||
using Microsoft.CodeAnalysis.CSharp.Syntax;
|
||||
using Microsoft.CodeAnalysis.Text;
|
||||
|
||||
namespace LuaScript.Generator
|
||||
{
|
||||
[Generator]
|
||||
public sealed class GpuShaderSourceGenerator : IIncrementalGenerator
|
||||
{
|
||||
private const string AttributeName = "LuaScript.Engine.Processing.GpuPixelOperationShaderAttribute";
|
||||
|
||||
public void Initialize(IncrementalGeneratorInitializationContext context)
|
||||
{
|
||||
var classes = context.SyntaxProvider
|
||||
.CreateSyntaxProvider(
|
||||
static (node, _) => node is ClassDeclarationSyntax { AttributeLists.Count: > 0 },
|
||||
static (ctx, _) => CreateClass(ctx))
|
||||
.Where(static model => model is not null)
|
||||
.Select(static (model, _) => model!);
|
||||
|
||||
var files = context.AdditionalTextsProvider
|
||||
.Where(static file => file.Path.EndsWith(".hlsl", StringComparison.OrdinalIgnoreCase))
|
||||
.Select(static (file, token) => new GpuShaderFile(Normalize(file.Path), file.GetText(token)?.ToString() ?? string.Empty))
|
||||
.Collect()
|
||||
.Select(static (items, _) => new EquatableArray<GpuShaderFile>([.. items]));
|
||||
|
||||
context.RegisterSourceOutput(classes.Combine(files), static (context, source) =>
|
||||
{
|
||||
var (model, files) = source;
|
||||
var resolved = Resolve(model, files);
|
||||
if (resolved.Errors.Length > 0)
|
||||
{
|
||||
context.AddSource(ErrorHintName(model), SourceText.From(EmitErrors(resolved.Errors), Encoding.UTF8));
|
||||
return;
|
||||
}
|
||||
|
||||
context.AddSource(HintName(model), SourceText.From(Emit(model, resolved.Methods), Encoding.UTF8));
|
||||
});
|
||||
}
|
||||
|
||||
private static GpuShaderClass? CreateClass(GeneratorSyntaxContext context)
|
||||
{
|
||||
if (context.Node is not ClassDeclarationSyntax declaration)
|
||||
return null;
|
||||
if (context.SemanticModel.GetDeclaredSymbol(declaration) is not INamedTypeSymbol type)
|
||||
return null;
|
||||
|
||||
var attributes = type.GetAttributes()
|
||||
.Where(static attribute => attribute.AttributeClass?.ToDisplayString() == AttributeName)
|
||||
.ToArray();
|
||||
if (attributes.Length == 0)
|
||||
return null;
|
||||
|
||||
var chain = new List<GpuShaderTypePart>();
|
||||
for (var current = type; current is not null; current = current.ContainingType)
|
||||
chain.Insert(0, new GpuShaderTypePart(current.Name, current.IsStatic));
|
||||
|
||||
var methods = ImmutableArray.CreateBuilder<GpuShaderMethod>();
|
||||
var errors = ImmutableArray.CreateBuilder<string>();
|
||||
|
||||
foreach (var attribute in attributes)
|
||||
{
|
||||
if (attribute.ConstructorArguments.Length < 3 ||
|
||||
attribute.ConstructorArguments[0].Value is not string methodName ||
|
||||
attribute.ConstructorArguments[1].Value is not string fileName ||
|
||||
attribute.ConstructorArguments[2].Value is not string entryPoint)
|
||||
{
|
||||
errors.Add("GPU shader attribute arguments are invalid");
|
||||
continue;
|
||||
}
|
||||
|
||||
var candidates = type.GetMembers(methodName).OfType<IMethodSymbol>().ToArray();
|
||||
if (candidates.Length == 0)
|
||||
{
|
||||
errors.Add($"GPU shader method '{methodName}' was not found");
|
||||
continue;
|
||||
}
|
||||
if (candidates.Length > 1)
|
||||
{
|
||||
errors.Add($"GPU shader method '{methodName}' is ambiguous");
|
||||
continue;
|
||||
}
|
||||
|
||||
var method = candidates[0];
|
||||
string? error = Validate(method, fileName, entryPoint, out var invocation);
|
||||
if (error is not null)
|
||||
{
|
||||
errors.Add($"GPU shader method '{methodName}': {error}");
|
||||
continue;
|
||||
}
|
||||
|
||||
var parameters = ImmutableArray.CreateBuilder<GpuShaderParameter>();
|
||||
foreach (var parameter in method.Parameters)
|
||||
parameters.Add(new GpuShaderParameter(ParameterPrefix(parameter), parameter.Type.ToDisplayString(SymbolDisplayFormat.FullyQualifiedFormat), parameter.Name));
|
||||
|
||||
methods.Add(new GpuShaderMethod(
|
||||
AccessibilityName(method.DeclaredAccessibility),
|
||||
method.IsStatic,
|
||||
method.ReturnType.ToDisplayString(SymbolDisplayFormat.FullyQualifiedFormat),
|
||||
method.Name,
|
||||
new EquatableArray<GpuShaderParameter>([.. parameters]),
|
||||
Normalize(fileName),
|
||||
entryPoint,
|
||||
invocation));
|
||||
}
|
||||
|
||||
return new GpuShaderClass(
|
||||
type.ContainingNamespace.IsGlobalNamespace ? string.Empty : type.ContainingNamespace.ToDisplayString(),
|
||||
new EquatableArray<GpuShaderTypePart>([.. chain]),
|
||||
new EquatableArray<GpuShaderMethod>([.. methods]),
|
||||
new EquatableArray<string>([.. errors]));
|
||||
}
|
||||
|
||||
private static string? Validate(IMethodSymbol method, string fileName, string entryPoint, out GpuShaderInvocation invocation)
|
||||
{
|
||||
invocation = new GpuShaderInvocation(string.Empty, string.Empty, string.Empty, string.Empty, string.Empty);
|
||||
if (string.IsNullOrWhiteSpace(fileName))
|
||||
return "file name is empty";
|
||||
if (string.IsNullOrWhiteSpace(entryPoint))
|
||||
return "entry point is empty";
|
||||
if (method.ReturnType.SpecialType != SpecialType.System_Boolean)
|
||||
return "return type must be bool";
|
||||
|
||||
var parameters = method.Parameters;
|
||||
if (parameters.Length == 4 &&
|
||||
IsReadOnlySpanSingle(parameters[0].Type) &&
|
||||
IsByteArray(parameters[1].Type) &&
|
||||
IsInt32(parameters[2].Type) &&
|
||||
IsInt32(parameters[3].Type))
|
||||
{
|
||||
invocation = new GpuShaderInvocation("[]", parameters[0].Name, parameters[1].Name, parameters[2].Name, parameters[3].Name);
|
||||
return null;
|
||||
}
|
||||
|
||||
if (parameters.Length == 5 &&
|
||||
IsReadOnlySpanPixelShaderInput(parameters[0].Type) &&
|
||||
IsReadOnlySpanSingle(parameters[1].Type) &&
|
||||
IsByteArray(parameters[2].Type) &&
|
||||
IsInt32(parameters[3].Type) &&
|
||||
IsInt32(parameters[4].Type))
|
||||
{
|
||||
invocation = new GpuShaderInvocation(parameters[0].Name, parameters[1].Name, parameters[2].Name, parameters[3].Name, parameters[4].Name);
|
||||
return null;
|
||||
}
|
||||
|
||||
return "signature is invalid";
|
||||
}
|
||||
|
||||
private static GpuShaderResolution Resolve(GpuShaderClass model, EquatableArray<GpuShaderFile> files)
|
||||
{
|
||||
var methods = ImmutableArray.CreateBuilder<GpuShaderMethodSource>();
|
||||
var errors = ImmutableArray.CreateBuilder<string>();
|
||||
errors.AddRange(model.Errors);
|
||||
|
||||
foreach (var method in model.Methods)
|
||||
{
|
||||
var matched = files.Where(file => Matches(file.Path, method.FileName)).ToArray();
|
||||
if (matched.Length == 0)
|
||||
{
|
||||
errors.Add($"GPU shader file '{method.FileName}' for method '{method.MethodName}' was not found");
|
||||
continue;
|
||||
}
|
||||
if (matched.Length > 1)
|
||||
{
|
||||
errors.Add($"GPU shader file '{method.FileName}' for method '{method.MethodName}' matched multiple additional files");
|
||||
continue;
|
||||
}
|
||||
|
||||
string? failure = ShaderCompiler.Compile(matched[0].Source, method.EntryPoint, out string bytecode);
|
||||
if (failure is not null)
|
||||
{
|
||||
errors.Add($"GPU shader method '{method.MethodName}' failed to compile: {failure}");
|
||||
continue;
|
||||
}
|
||||
|
||||
methods.Add(new GpuShaderMethodSource(method, bytecode));
|
||||
}
|
||||
|
||||
return new GpuShaderResolution([.. methods], [.. errors]);
|
||||
}
|
||||
|
||||
private static bool Matches(string filePath, string registrationPath)
|
||||
{
|
||||
if (string.Equals(filePath, registrationPath, StringComparison.OrdinalIgnoreCase))
|
||||
return true;
|
||||
return filePath.EndsWith("/" + registrationPath, StringComparison.OrdinalIgnoreCase);
|
||||
}
|
||||
|
||||
private static bool IsReadOnlySpanSingle(ITypeSymbol type)
|
||||
{
|
||||
return type is INamedTypeSymbol named &&
|
||||
named.OriginalDefinition.ToDisplayString() == "System.ReadOnlySpan<T>" &&
|
||||
named.TypeArguments.Length == 1 &&
|
||||
named.TypeArguments[0].SpecialType == SpecialType.System_Single;
|
||||
}
|
||||
|
||||
private static bool IsReadOnlySpanPixelShaderInput(ITypeSymbol type)
|
||||
{
|
||||
string display = type.ToDisplayString(SymbolDisplayFormat.FullyQualifiedFormat);
|
||||
return display.Contains("ReadOnlySpan", StringComparison.Ordinal) &&
|
||||
display.Contains("PixelShaderInput", StringComparison.Ordinal);
|
||||
}
|
||||
|
||||
private static bool IsByteArray(ITypeSymbol type)
|
||||
{
|
||||
return type is IArrayTypeSymbol array &&
|
||||
array.Rank == 1 &&
|
||||
array.ElementType.SpecialType == SpecialType.System_Byte;
|
||||
}
|
||||
|
||||
private static bool IsInt32(ITypeSymbol type) => type.SpecialType == SpecialType.System_Int32;
|
||||
|
||||
private static string Normalize(string path) => path.Replace(Path.DirectorySeparatorChar, '/').Replace(Path.AltDirectorySeparatorChar, '/');
|
||||
|
||||
private static string AccessibilityName(Accessibility accessibility)
|
||||
{
|
||||
return accessibility switch
|
||||
{
|
||||
Accessibility.Public => "public",
|
||||
Accessibility.Internal => "internal",
|
||||
Accessibility.Protected => "protected",
|
||||
Accessibility.ProtectedAndInternal => "private protected",
|
||||
Accessibility.ProtectedOrInternal => "protected internal",
|
||||
_ => "private",
|
||||
};
|
||||
}
|
||||
|
||||
private static string ParameterPrefix(IParameterSymbol parameter)
|
||||
{
|
||||
return parameter.RefKind switch
|
||||
{
|
||||
RefKind.In => "in ",
|
||||
RefKind.Ref => "ref ",
|
||||
RefKind.Out => "out ",
|
||||
_ => string.Empty,
|
||||
};
|
||||
}
|
||||
|
||||
private static string Emit(GpuShaderClass model, ImmutableArray<GpuShaderMethodSource> sources)
|
||||
{
|
||||
var builder = new StringBuilder();
|
||||
builder.AppendLine("#nullable enable");
|
||||
if (model.Namespace.Length > 0)
|
||||
{
|
||||
builder.AppendLine("namespace " + model.Namespace);
|
||||
builder.AppendLine("{");
|
||||
}
|
||||
|
||||
int indent = model.Namespace.Length > 0 ? 1 : 0;
|
||||
foreach (var type in model.TypeChain)
|
||||
{
|
||||
AppendIndent(builder, indent);
|
||||
builder.Append(type.IsStatic ? "static partial class " : "partial class ");
|
||||
builder.AppendLine(type.Name);
|
||||
AppendIndent(builder, indent);
|
||||
builder.AppendLine("{");
|
||||
indent++;
|
||||
}
|
||||
|
||||
for (int i = 0; i < sources.Length; i++)
|
||||
{
|
||||
if (i > 0)
|
||||
builder.AppendLine();
|
||||
EmitMethod(builder, indent, sources[i]);
|
||||
}
|
||||
|
||||
for (int i = model.TypeChain.Count - 1; i >= 0; i--)
|
||||
{
|
||||
indent--;
|
||||
AppendIndent(builder, indent);
|
||||
builder.AppendLine("}");
|
||||
}
|
||||
|
||||
if (model.Namespace.Length > 0)
|
||||
builder.AppendLine("}");
|
||||
return builder.ToString();
|
||||
}
|
||||
|
||||
private static void EmitMethod(StringBuilder builder, int indent, GpuShaderMethodSource source)
|
||||
{
|
||||
var method = source.Method;
|
||||
string field = "s_shader_" + method.MethodName;
|
||||
|
||||
AppendIndent(builder, indent);
|
||||
builder.Append("private static readonly byte[] ");
|
||||
builder.Append(field);
|
||||
builder.Append(" = global::System.Convert.FromBase64String(");
|
||||
builder.Append(Literal(source.Bytecode));
|
||||
builder.AppendLine(");");
|
||||
builder.AppendLine();
|
||||
|
||||
AppendIndent(builder, indent);
|
||||
builder.Append(method.Accessibility);
|
||||
builder.Append(' ');
|
||||
if (method.IsStatic)
|
||||
builder.Append("static ");
|
||||
builder.Append("partial ");
|
||||
builder.Append(method.ReturnType);
|
||||
builder.Append(' ');
|
||||
builder.Append(method.MethodName);
|
||||
builder.Append('(');
|
||||
for (int i = 0; i < method.Parameters.Count; i++)
|
||||
{
|
||||
if (i > 0)
|
||||
builder.Append(", ");
|
||||
var parameter = method.Parameters[i];
|
||||
builder.Append(parameter.Prefix);
|
||||
builder.Append(parameter.Type);
|
||||
builder.Append(' ');
|
||||
builder.Append(parameter.Name);
|
||||
}
|
||||
builder.AppendLine(")");
|
||||
AppendIndent(builder, indent);
|
||||
builder.AppendLine("{");
|
||||
AppendIndent(builder, indent + 1);
|
||||
builder.Append("return Run(");
|
||||
builder.Append(field);
|
||||
builder.Append(", ");
|
||||
builder.Append(method.Invocation.Resources);
|
||||
builder.Append(", ");
|
||||
builder.Append(method.Invocation.Constants);
|
||||
builder.Append(", ");
|
||||
builder.Append(method.Invocation.Target);
|
||||
builder.Append(", ");
|
||||
builder.Append(method.Invocation.Width);
|
||||
builder.Append(", ");
|
||||
builder.Append(method.Invocation.Height);
|
||||
builder.AppendLine(");");
|
||||
AppendIndent(builder, indent);
|
||||
builder.AppendLine("}");
|
||||
}
|
||||
|
||||
private static void AppendIndent(StringBuilder builder, int indent)
|
||||
{
|
||||
for (int i = 0; i < indent; i++)
|
||||
builder.Append(" ");
|
||||
}
|
||||
|
||||
private static string EmitErrors(ImmutableArray<string> errors)
|
||||
{
|
||||
var builder = new StringBuilder();
|
||||
foreach (var error in errors)
|
||||
builder.AppendLine("#error " + error);
|
||||
return builder.ToString();
|
||||
}
|
||||
|
||||
private static string HintName(GpuShaderClass model)
|
||||
{
|
||||
var builder = new StringBuilder("GpuPixelOperationShader");
|
||||
if (model.Namespace.Length > 0)
|
||||
{
|
||||
builder.Append('.');
|
||||
builder.Append(HintPart(model.Namespace));
|
||||
}
|
||||
foreach (var type in model.TypeChain)
|
||||
{
|
||||
builder.Append('.');
|
||||
builder.Append(HintPart(type.Name));
|
||||
}
|
||||
builder.Append(".g.cs");
|
||||
return builder.ToString();
|
||||
}
|
||||
|
||||
private static string ErrorHintName(GpuShaderClass model)
|
||||
{
|
||||
return Path.ChangeExtension(HintName(model), ".Errors.g.cs");
|
||||
}
|
||||
|
||||
private static string HintPart(string value)
|
||||
{
|
||||
var builder = new StringBuilder(value.Length);
|
||||
foreach (char c in value)
|
||||
builder.Append(char.IsLetterOrDigit(c) ? c : '_');
|
||||
return builder.ToString();
|
||||
}
|
||||
|
||||
private static string Literal(string value)
|
||||
{
|
||||
var builder = new StringBuilder(value.Length + 2);
|
||||
builder.Append('"');
|
||||
foreach (char c in value)
|
||||
{
|
||||
switch (c)
|
||||
{
|
||||
case '\\':
|
||||
builder.Append(@"\\");
|
||||
break;
|
||||
case '"':
|
||||
builder.Append("\\\"");
|
||||
break;
|
||||
case '\0':
|
||||
builder.Append(@"\0");
|
||||
break;
|
||||
case '\a':
|
||||
builder.Append(@"\a");
|
||||
break;
|
||||
case '\b':
|
||||
builder.Append(@"\b");
|
||||
break;
|
||||
case '\f':
|
||||
builder.Append(@"\f");
|
||||
break;
|
||||
case '\n':
|
||||
builder.Append(@"\n");
|
||||
break;
|
||||
case '\r':
|
||||
builder.Append(@"\r");
|
||||
break;
|
||||
case '\t':
|
||||
builder.Append(@"\t");
|
||||
break;
|
||||
case '\v':
|
||||
builder.Append(@"\v");
|
||||
break;
|
||||
default:
|
||||
if (char.IsControl(c))
|
||||
{
|
||||
builder.Append(@"\u");
|
||||
builder.Append(((int)c).ToString("x4", CultureInfo.InvariantCulture));
|
||||
}
|
||||
else
|
||||
{
|
||||
builder.Append(c);
|
||||
}
|
||||
break;
|
||||
}
|
||||
}
|
||||
builder.Append('"');
|
||||
return builder.ToString();
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,4 @@
|
||||
namespace LuaScript.Generator
|
||||
{
|
||||
internal sealed record GpuShaderTypePart(string Name, bool IsStatic);
|
||||
}
|
||||
@@ -0,0 +1,96 @@
|
||||
using System.Globalization;
|
||||
using System.Runtime.InteropServices;
|
||||
using System.Text;
|
||||
|
||||
namespace LuaScript.Generator
|
||||
{
|
||||
internal static class ShaderCompiler
|
||||
{
|
||||
private const string Profile = "ps_5_0";
|
||||
|
||||
public static string? Compile(string source, string entryPoint, out string bytecode)
|
||||
{
|
||||
bytecode = string.Empty;
|
||||
byte[] data = Encoding.UTF8.GetBytes(source);
|
||||
IntPtr code = IntPtr.Zero;
|
||||
IntPtr errors = IntPtr.Zero;
|
||||
try
|
||||
{
|
||||
int hr = D3DCompile(data, (IntPtr)data.Length, null, IntPtr.Zero, IntPtr.Zero, entryPoint, Profile, 0u, 0u, out code, out errors);
|
||||
if (hr < 0 || code == IntPtr.Zero)
|
||||
return ReadError(errors, hr);
|
||||
bytecode = Convert.ToBase64String(ReadBlob(code));
|
||||
return null;
|
||||
}
|
||||
catch (DllNotFoundException)
|
||||
{
|
||||
return "the Direct3D shader compiler is unavailable on this build host";
|
||||
}
|
||||
catch (EntryPointNotFoundException)
|
||||
{
|
||||
return "the Direct3D shader compiler is unavailable on this build host";
|
||||
}
|
||||
finally
|
||||
{
|
||||
Release(errors);
|
||||
Release(code);
|
||||
}
|
||||
}
|
||||
|
||||
private static byte[] ReadBlob(IntPtr blob)
|
||||
{
|
||||
IntPtr pointer = Invoke<GetBufferPointerDelegate>(blob, 3)(blob);
|
||||
int size = checked((int)(long)Invoke<GetBufferSizeDelegate>(blob, 4)(blob));
|
||||
var buffer = new byte[size];
|
||||
Marshal.Copy(pointer, buffer, 0, size);
|
||||
return buffer;
|
||||
}
|
||||
|
||||
private static string ReadError(IntPtr blob, int hr)
|
||||
{
|
||||
string fallback = "HRESULT 0x" + hr.ToString("X8", CultureInfo.InvariantCulture);
|
||||
if (blob == IntPtr.Zero)
|
||||
return fallback;
|
||||
IntPtr pointer = Invoke<GetBufferPointerDelegate>(blob, 3)(blob);
|
||||
int size = checked((int)(long)Invoke<GetBufferSizeDelegate>(blob, 4)(blob));
|
||||
string message = (Marshal.PtrToStringAnsi(pointer, size) ?? string.Empty).Trim();
|
||||
return message.Length > 0 ? message : fallback;
|
||||
}
|
||||
|
||||
private static void Release(IntPtr unknown)
|
||||
{
|
||||
if (unknown != IntPtr.Zero)
|
||||
Invoke<ReleaseDelegate>(unknown, 2)(unknown);
|
||||
}
|
||||
|
||||
private static T Invoke<T>(IntPtr instance, int slot) where T : Delegate
|
||||
{
|
||||
IntPtr table = Marshal.ReadIntPtr(instance);
|
||||
IntPtr function = Marshal.ReadIntPtr(table, slot * IntPtr.Size);
|
||||
return (T)Marshal.GetDelegateForFunctionPointer(function, typeof(T));
|
||||
}
|
||||
|
||||
[UnmanagedFunctionPointer(CallingConvention.StdCall)]
|
||||
private delegate IntPtr GetBufferPointerDelegate(IntPtr self);
|
||||
|
||||
[UnmanagedFunctionPointer(CallingConvention.StdCall)]
|
||||
private delegate IntPtr GetBufferSizeDelegate(IntPtr self);
|
||||
|
||||
[UnmanagedFunctionPointer(CallingConvention.StdCall)]
|
||||
private delegate uint ReleaseDelegate(IntPtr self);
|
||||
|
||||
[DllImport("d3dcompiler_47.dll", CallingConvention = CallingConvention.StdCall)]
|
||||
private static extern int D3DCompile(
|
||||
byte[] srcData,
|
||||
IntPtr srcDataSize,
|
||||
[MarshalAs(UnmanagedType.LPStr)] string? sourceName,
|
||||
IntPtr defines,
|
||||
IntPtr include,
|
||||
[MarshalAs(UnmanagedType.LPStr)] string entryPoint,
|
||||
[MarshalAs(UnmanagedType.LPStr)] string target,
|
||||
uint flags1,
|
||||
uint flags2,
|
||||
out IntPtr code,
|
||||
out IntPtr errorMsgs);
|
||||
}
|
||||
}
|
||||
@@ -5,60 +5,6 @@ using Microsoft.CodeAnalysis.Text;
|
||||
|
||||
namespace LuaScript.Generator
|
||||
{
|
||||
internal enum LuaParameterKind
|
||||
{
|
||||
ExecutionContext,
|
||||
Arguments,
|
||||
DynValue,
|
||||
Double,
|
||||
Int,
|
||||
Bool,
|
||||
}
|
||||
|
||||
internal enum LuaReturnKind
|
||||
{
|
||||
DynValue,
|
||||
Double,
|
||||
Void,
|
||||
}
|
||||
|
||||
internal sealed record LuaParameterModel(string Name, LuaParameterKind Kind, string DefaultLiteral);
|
||||
|
||||
internal sealed record LuaFunctionModel(
|
||||
string LuaName,
|
||||
string MethodName,
|
||||
LuaReturnKind ReturnKind,
|
||||
EquatableArray<LuaParameterModel> Parameters);
|
||||
|
||||
internal sealed record LuaConstantModel(string LuaName, string MemberName);
|
||||
|
||||
internal enum LuaUpdateKind
|
||||
{
|
||||
Direct,
|
||||
OptionalValue,
|
||||
OptionalReference,
|
||||
}
|
||||
|
||||
internal sealed record LuaUpdateModel(string LuaName, string MethodName, LuaUpdateKind Kind);
|
||||
|
||||
internal sealed record LuaCatalogEntry(
|
||||
string Table,
|
||||
string Name,
|
||||
bool IsFunction,
|
||||
EquatableArray<string> Parameters);
|
||||
|
||||
internal sealed record LuaTypePart(string Name, bool IsStatic);
|
||||
|
||||
internal sealed record LuaTableModel(
|
||||
string Namespace,
|
||||
EquatableArray<LuaTypePart> TypeChain,
|
||||
string TableName,
|
||||
string ContextType,
|
||||
EquatableArray<LuaFunctionModel> Functions,
|
||||
EquatableArray<LuaConstantModel> Constants,
|
||||
EquatableArray<LuaUpdateModel> Updates,
|
||||
EquatableArray<LuaCatalogEntry> Entries);
|
||||
|
||||
[Generator]
|
||||
public sealed class LuaApiGenerator : IIncrementalGenerator
|
||||
{
|
||||
@@ -309,12 +255,30 @@ namespace LuaScript.Generator
|
||||
|
||||
var returnType = method.ReturnType;
|
||||
LuaUpdateKind kind;
|
||||
ITypeSymbol valueType;
|
||||
if (returnType.OriginalDefinition.SpecialType == SpecialType.System_Nullable_T)
|
||||
{
|
||||
kind = LuaUpdateKind.OptionalValue;
|
||||
valueType = ((INamedTypeSymbol)returnType).TypeArguments[0];
|
||||
}
|
||||
else if (returnType.IsReferenceType)
|
||||
{
|
||||
kind = LuaUpdateKind.OptionalReference;
|
||||
valueType = returnType;
|
||||
}
|
||||
else
|
||||
{
|
||||
kind = LuaUpdateKind.Direct;
|
||||
valueType = returnType;
|
||||
}
|
||||
|
||||
var valueKind = valueType.SpecialType switch
|
||||
{
|
||||
SpecialType.System_Double or SpecialType.System_Int32 => LuaValueKind.Number,
|
||||
SpecialType.System_Boolean => LuaValueKind.Boolean,
|
||||
SpecialType.System_String => LuaValueKind.String,
|
||||
_ => LuaValueKind.Other,
|
||||
};
|
||||
|
||||
bool inCatalog = true;
|
||||
foreach (var argument in attribute.NamedArguments)
|
||||
@@ -325,7 +289,7 @@ namespace LuaScript.Generator
|
||||
|
||||
if (inCatalog)
|
||||
entry = new LuaCatalogEntry(tableName, luaName, false, EquatableArray<string>.Empty);
|
||||
return new LuaUpdateModel(luaName, method.Name, kind);
|
||||
return new LuaUpdateModel(luaName, method.Name, kind, valueKind);
|
||||
}
|
||||
|
||||
private static string FormatDouble(double value) =>
|
||||
@@ -387,13 +351,19 @@ namespace LuaScript.Generator
|
||||
switch (update.Kind)
|
||||
{
|
||||
case LuaUpdateKind.OptionalValue:
|
||||
builder.AppendLine($"{body}{{ var value = {update.MethodName}(context); if (value.HasValue) table[\"{update.LuaName}\"] = value.Value; }}");
|
||||
builder.AppendLine(update.ValueKind == LuaValueKind.Other
|
||||
? $"{body}{{ var value = {update.MethodName}(context); if (value.HasValue) table[\"{update.LuaName}\"] = value.Value; }}"
|
||||
: $"{body}{{ var value = {update.MethodName}(context); if (value.HasValue) table.Set(\"{update.LuaName}\", {WrapValue(update.ValueKind, "value.Value")}); }}");
|
||||
break;
|
||||
case LuaUpdateKind.OptionalReference:
|
||||
builder.AppendLine($"{body}{{ var value = {update.MethodName}(context); if (value is not null) table[\"{update.LuaName}\"] = value; }}");
|
||||
builder.AppendLine(update.ValueKind == LuaValueKind.Other
|
||||
? $"{body}{{ var value = {update.MethodName}(context); if (value is not null) table[\"{update.LuaName}\"] = value; }}"
|
||||
: $"{body}{{ var value = {update.MethodName}(context); if (value is not null) table.Set(\"{update.LuaName}\", {WrapValue(update.ValueKind, "value")}); }}");
|
||||
break;
|
||||
default:
|
||||
builder.AppendLine($"{body}table[\"{update.LuaName}\"] = {update.MethodName}(context);");
|
||||
builder.AppendLine(update.ValueKind == LuaValueKind.Other
|
||||
? $"{body}table[\"{update.LuaName}\"] = {update.MethodName}(context);"
|
||||
: $"{body}table.Set(\"{update.LuaName}\", {WrapValue(update.ValueKind, $"{update.MethodName}(context)")});");
|
||||
break;
|
||||
}
|
||||
}
|
||||
@@ -409,6 +379,13 @@ namespace LuaScript.Generator
|
||||
return builder.ToString();
|
||||
}
|
||||
|
||||
private static string WrapValue(LuaValueKind kind, string expression) => kind switch
|
||||
{
|
||||
LuaValueKind.Number => $"global::MoonSharp.Interpreter.DynValue.NewNumber({expression})",
|
||||
LuaValueKind.Boolean => $"global::MoonSharp.Interpreter.DynValue.NewBoolean({expression})",
|
||||
_ => $"global::MoonSharp.Interpreter.DynValue.NewString({expression})",
|
||||
};
|
||||
|
||||
private static string EmitArguments(EquatableArray<LuaParameterModel> parameters)
|
||||
{
|
||||
var rendered = new List<string>();
|
||||
@@ -0,0 +1,8 @@
|
||||
namespace LuaScript.Generator
|
||||
{
|
||||
internal sealed record LuaCatalogEntry(
|
||||
string Table,
|
||||
string Name,
|
||||
bool IsFunction,
|
||||
EquatableArray<string> Parameters);
|
||||
}
|
||||
@@ -0,0 +1,4 @@
|
||||
namespace LuaScript.Generator
|
||||
{
|
||||
internal sealed record LuaConstantModel(string LuaName, string MemberName);
|
||||
}
|
||||
@@ -0,0 +1,8 @@
|
||||
namespace LuaScript.Generator
|
||||
{
|
||||
internal sealed record LuaFunctionModel(
|
||||
string LuaName,
|
||||
string MethodName,
|
||||
LuaReturnKind ReturnKind,
|
||||
EquatableArray<LuaParameterModel> Parameters);
|
||||
}
|
||||
@@ -0,0 +1,12 @@
|
||||
namespace LuaScript.Generator
|
||||
{
|
||||
internal enum LuaParameterKind
|
||||
{
|
||||
ExecutionContext,
|
||||
Arguments,
|
||||
DynValue,
|
||||
Double,
|
||||
Int,
|
||||
Bool,
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,4 @@
|
||||
namespace LuaScript.Generator
|
||||
{
|
||||
internal sealed record LuaParameterModel(string Name, LuaParameterKind Kind, string DefaultLiteral);
|
||||
}
|
||||
@@ -0,0 +1,9 @@
|
||||
namespace LuaScript.Generator
|
||||
{
|
||||
internal enum LuaReturnKind
|
||||
{
|
||||
DynValue,
|
||||
Double,
|
||||
Void,
|
||||
}
|
||||
}
|
||||
+29
-3
@@ -8,8 +8,6 @@ using Microsoft.CodeAnalysis.Text;
|
||||
|
||||
namespace LuaScript.Generator
|
||||
{
|
||||
internal sealed record LuaSyntaxRuleModel(string TypeName, int Order);
|
||||
|
||||
[Generator]
|
||||
public sealed class LuaSyntaxRuleGenerator : IIncrementalGenerator
|
||||
{
|
||||
@@ -47,7 +45,17 @@ namespace LuaScript.Generator
|
||||
if (arguments.Length > 0 && arguments[0].Value is int value)
|
||||
order = value;
|
||||
|
||||
return new LuaSyntaxRuleModel(symbol.ToDisplayString(), order);
|
||||
bool isCatalog = false;
|
||||
string keyword = string.Empty;
|
||||
foreach (var argument in context.Attributes[0].NamedArguments)
|
||||
{
|
||||
if (argument.Key == "IsCatalog" && argument.Value.Value is bool catalogValue)
|
||||
isCatalog = catalogValue;
|
||||
else if (argument.Key == "Keyword" && argument.Value.Value is string keywordValue)
|
||||
keyword = keywordValue;
|
||||
}
|
||||
|
||||
return new LuaSyntaxRuleModel(symbol.ToDisplayString(), order, isCatalog ? keyword : string.Empty);
|
||||
}
|
||||
|
||||
private static string Emit(ImmutableArray<LuaSyntaxRuleModel> models)
|
||||
@@ -68,6 +76,24 @@ namespace LuaScript.Generator
|
||||
foreach (var model in ordered)
|
||||
builder.AppendLine($" new global::{model.TypeName}(),");
|
||||
builder.AppendLine(" };");
|
||||
|
||||
var keywords = ordered
|
||||
.Where(static m => m.CatalogKeyword.Length > 0)
|
||||
.Select(static m => m.CatalogKeyword)
|
||||
.Distinct()
|
||||
.ToArray();
|
||||
if (keywords.Length == 0)
|
||||
{
|
||||
builder.AppendLine(" internal static readonly string[] CatalogKeywords = global::System.Array.Empty<string>();");
|
||||
}
|
||||
else
|
||||
{
|
||||
builder.AppendLine(" internal static readonly string[] CatalogKeywords = new string[]");
|
||||
builder.AppendLine(" {");
|
||||
foreach (var keyword in keywords)
|
||||
builder.AppendLine($" \"{keyword}\",");
|
||||
builder.AppendLine(" };");
|
||||
}
|
||||
builder.AppendLine(" }");
|
||||
builder.AppendLine("}");
|
||||
return builder.ToString();
|
||||
@@ -0,0 +1,4 @@
|
||||
namespace LuaScript.Generator
|
||||
{
|
||||
internal sealed record LuaSyntaxRuleModel(string TypeName, int Order, string CatalogKeyword);
|
||||
}
|
||||
@@ -0,0 +1,12 @@
|
||||
namespace LuaScript.Generator
|
||||
{
|
||||
internal sealed record LuaTableModel(
|
||||
string Namespace,
|
||||
EquatableArray<LuaTypePart> TypeChain,
|
||||
string TableName,
|
||||
string ContextType,
|
||||
EquatableArray<LuaFunctionModel> Functions,
|
||||
EquatableArray<LuaConstantModel> Constants,
|
||||
EquatableArray<LuaUpdateModel> Updates,
|
||||
EquatableArray<LuaCatalogEntry> Entries);
|
||||
}
|
||||
@@ -0,0 +1,4 @@
|
||||
namespace LuaScript.Generator
|
||||
{
|
||||
internal sealed record LuaTypePart(string Name, bool IsStatic);
|
||||
}
|
||||
@@ -0,0 +1,9 @@
|
||||
namespace LuaScript.Generator
|
||||
{
|
||||
internal enum LuaUpdateKind
|
||||
{
|
||||
Direct,
|
||||
OptionalValue,
|
||||
OptionalReference,
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,4 @@
|
||||
namespace LuaScript.Generator
|
||||
{
|
||||
internal sealed record LuaUpdateModel(string LuaName, string MethodName, LuaUpdateKind Kind, LuaValueKind ValueKind);
|
||||
}
|
||||
@@ -0,0 +1,10 @@
|
||||
namespace LuaScript.Generator
|
||||
{
|
||||
internal enum LuaValueKind
|
||||
{
|
||||
Number,
|
||||
Boolean,
|
||||
String,
|
||||
Other,
|
||||
}
|
||||
}
|
||||
@@ -5,7 +5,7 @@
|
||||
<LangVersion>latest</LangVersion>
|
||||
<Nullable>enable</Nullable>
|
||||
<ImplicitUsings>enable</ImplicitUsings>
|
||||
<Version>1.16.0</Version>
|
||||
<Version>1.20.1</Version>
|
||||
<IsRoslynComponent>true</IsRoslynComponent>
|
||||
<EnforceExtendedAnalyzerRules>true</EnforceExtendedAnalyzerRules>
|
||||
</PropertyGroup>
|
||||
|
||||
@@ -0,0 +1,134 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using LuaScript.Engine.Shader;
|
||||
|
||||
namespace LuaScript.Engine.Processing
|
||||
{
|
||||
[GpuPixelOperationShader(nameof(RunConvolve), "Shaders/convolve.hlsl", "convolve")]
|
||||
internal sealed partial class GpuConvolveOperation(PixelShaderRunner runner) : GpuPixelOperation(runner)
|
||||
{
|
||||
private const int ConvolveWorkThreshold = 262144;
|
||||
private const int MaxConvolveSize = 31;
|
||||
private const int MaxConvolveValidationCount = 64;
|
||||
|
||||
private readonly PixelShaderInput[] _resources = new PixelShaderInput[1];
|
||||
private readonly float[] _constants = new float[1024];
|
||||
private readonly List<ConvolveValidation> _validations = [];
|
||||
|
||||
public bool TryConvolve(byte[] target, int width, int height, double[] kernel, int size, double divisor, double offset)
|
||||
{
|
||||
if (!IsTextureSupported(target, width, height) || !IsSupported(kernel, size, divisor, offset))
|
||||
return false;
|
||||
|
||||
long work = (long)width * height * size * size;
|
||||
if (work < ConvolveWorkThreshold || !EnsureValidated(target, width, height, kernel, size, divisor, offset))
|
||||
return false;
|
||||
|
||||
SetConstants(width, height, kernel, size, divisor, offset);
|
||||
_resources[0] = new PixelShaderInput(target, width, height);
|
||||
return RunConvolve(_resources.AsSpan(0, 1), _constants.AsSpan(0, size * size + 8), target, width, height);
|
||||
}
|
||||
|
||||
private bool EnsureValidated(byte[] target, int width, int height, double[] kernel, int size, double divisor, double offset)
|
||||
{
|
||||
for (int i = 0; i < _validations.Count; i++)
|
||||
{
|
||||
if (_validations[i].Matches(kernel, size, divisor, offset))
|
||||
return _validations[i].Valid;
|
||||
}
|
||||
|
||||
if (_validations.Count >= MaxConvolveValidationCount)
|
||||
_validations.Clear();
|
||||
|
||||
bool valid = Validate(target, width, height, kernel, size, divisor, offset);
|
||||
_validations.Add(new ConvolveValidation(kernel, size, divisor, offset, valid));
|
||||
return valid;
|
||||
}
|
||||
|
||||
private bool Validate(byte[] target, int width, int height, double[] kernel, int size, double divisor, double offset)
|
||||
{
|
||||
int probeWidth = Math.Min(width, 8);
|
||||
int probeHeight = Math.Min(height, 7);
|
||||
var probe = CopyProbe(target, width, height, probeWidth, probeHeight);
|
||||
var cpu = (byte[])probe.Clone();
|
||||
var gpu = (byte[])probe.Clone();
|
||||
double[]? scratch = null;
|
||||
PixelBufferSoftwareProcessor.Convolve(cpu, probeWidth, probeHeight, kernel, size, divisor, offset, ref scratch);
|
||||
SetConstants(probeWidth, probeHeight, kernel, size, divisor, offset);
|
||||
_resources[0] = new PixelShaderInput(gpu, probeWidth, probeHeight);
|
||||
return RunConvolve(_resources.AsSpan(0, 1), _constants.AsSpan(0, size * size + 8), gpu, probeWidth, probeHeight) && Equal(cpu, gpu);
|
||||
}
|
||||
|
||||
private void SetConstants(int width, int height, double[] kernel, int size, double divisor, double offset)
|
||||
{
|
||||
_constants[0] = width;
|
||||
_constants[1] = height;
|
||||
_constants[2] = (float)divisor;
|
||||
_constants[3] = (float)offset;
|
||||
_constants[4] = size;
|
||||
_constants[5] = size / 2;
|
||||
_constants[6] = 0f;
|
||||
_constants[7] = 0f;
|
||||
int taps = size * size;
|
||||
for (int i = 0; i < taps; i++)
|
||||
_constants[i + 8] = (float)kernel[i];
|
||||
}
|
||||
|
||||
private static bool IsSupported(double[] kernel, int size, double divisor, double offset)
|
||||
{
|
||||
if (size < 1 || (size & 1) == 0 || size > MaxConvolveSize || divisor == 0d || !IsFloatCompatible(divisor) || !IsFloatCompatible(offset))
|
||||
return false;
|
||||
int taps = size * size;
|
||||
if (kernel.Length < taps || taps + 8 > 1024)
|
||||
return false;
|
||||
for (int i = 0; i < taps; i++)
|
||||
{
|
||||
if (!IsFloatCompatible(kernel[i]))
|
||||
return false;
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
private static bool IsFloatCompatible(double value)
|
||||
{
|
||||
return double.IsFinite(value) && float.IsFinite((float)value);
|
||||
}
|
||||
|
||||
private partial bool RunConvolve(ReadOnlySpan<PixelShaderInput> resources, ReadOnlySpan<float> constants, byte[] target, int width, int height);
|
||||
|
||||
private sealed class ConvolveValidation
|
||||
{
|
||||
private readonly double[] _kernel;
|
||||
private readonly int _size;
|
||||
private readonly double _divisor;
|
||||
private readonly double _offset;
|
||||
|
||||
public ConvolveValidation(double[] kernel, int size, double divisor, double offset, bool valid)
|
||||
{
|
||||
int taps = size * size;
|
||||
_kernel = new double[taps];
|
||||
Array.Copy(kernel, _kernel, taps);
|
||||
_size = size;
|
||||
_divisor = divisor;
|
||||
_offset = offset;
|
||||
Valid = valid;
|
||||
}
|
||||
|
||||
public bool Valid { get; }
|
||||
|
||||
public bool Matches(double[] kernel, int size, double divisor, double offset)
|
||||
{
|
||||
if (_size != size || BitConverter.DoubleToInt64Bits(_divisor) != BitConverter.DoubleToInt64Bits(divisor) ||
|
||||
BitConverter.DoubleToInt64Bits(_offset) != BitConverter.DoubleToInt64Bits(offset))
|
||||
return false;
|
||||
int taps = size * size;
|
||||
for (int i = 0; i < taps; i++)
|
||||
{
|
||||
if (BitConverter.DoubleToInt64Bits(_kernel[i]) != BitConverter.DoubleToInt64Bits(kernel[i]))
|
||||
return false;
|
||||
}
|
||||
return true;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,124 @@
|
||||
using System;
|
||||
using LuaScript.Engine.Shader;
|
||||
|
||||
namespace LuaScript.Engine.Processing
|
||||
{
|
||||
[GpuPixelOperationShader(nameof(RunFillFull), "Shaders/fill.hlsl", "fill_full")]
|
||||
[GpuPixelOperationShader(nameof(RunFillPartial), "Shaders/fill.hlsl", "fill_partial")]
|
||||
internal sealed partial class GpuFillOperation(PixelShaderRunner runner) : GpuPixelOperation(runner)
|
||||
{
|
||||
private const int FillFullThreshold = 1048576;
|
||||
private const int FillPartialThreshold = 1048576;
|
||||
|
||||
private readonly PixelShaderInput[] _resources = new PixelShaderInput[1];
|
||||
private readonly float[] _constants = new float[8];
|
||||
|
||||
private bool? _fullValidated;
|
||||
private bool? _partialValidated;
|
||||
|
||||
public bool TryFill(byte[] target, int width, int height, double r, double g, double b, double a, int x, int y, int fillWidth, int fillHeight)
|
||||
{
|
||||
if (!IsTextureSupported(target, width, height) || !AreFinite(r, g, b, a))
|
||||
return false;
|
||||
|
||||
long pixels = (long)width * height;
|
||||
bool full = x == 0 && y == 0 && fillWidth == width && fillHeight == height;
|
||||
if (full)
|
||||
{
|
||||
if (pixels < FillFullThreshold || !EnsureFullValidated())
|
||||
return false;
|
||||
SetConstants(r, g, b, a);
|
||||
return RunFillFull(_constants.AsSpan(0, 4), target, width, height);
|
||||
}
|
||||
|
||||
long area = (long)fillWidth * fillHeight;
|
||||
if (pixels < FillPartialThreshold || area * 4L < pixels * 3L || !EnsurePartialValidated())
|
||||
return false;
|
||||
|
||||
SetConstants(r, g, b, a);
|
||||
_constants[4] = x;
|
||||
_constants[5] = y;
|
||||
_constants[6] = x + fillWidth;
|
||||
_constants[7] = y + fillHeight;
|
||||
_resources[0] = new PixelShaderInput(target, width, height);
|
||||
return RunFillPartial(_resources.AsSpan(0, 1), _constants.AsSpan(0, 8), target, width, height);
|
||||
}
|
||||
|
||||
private bool EnsureFullValidated()
|
||||
{
|
||||
if (_fullValidated.HasValue)
|
||||
return _fullValidated.Value;
|
||||
|
||||
const int width = 7;
|
||||
const int height = 5;
|
||||
var source = CreateProbe(width, height);
|
||||
var cpu = (byte[])source.Clone();
|
||||
var gpu = (byte[])source.Clone();
|
||||
PixelBufferSoftwareProcessor.Fill(cpu, width, height, 23d, 197d, 89d, 173d, 0, 0, width, height);
|
||||
SetConstants(23d, 197d, 89d, 173d);
|
||||
_fullValidated = RunFillFull(_constants.AsSpan(0, 4), gpu, width, height) && Equal(cpu, gpu);
|
||||
return _fullValidated.Value;
|
||||
}
|
||||
|
||||
private bool EnsurePartialValidated()
|
||||
{
|
||||
if (_partialValidated.HasValue)
|
||||
return _partialValidated.Value;
|
||||
|
||||
const int width = 7;
|
||||
const int height = 5;
|
||||
var source = CreateProbe(width, height);
|
||||
var cpu = (byte[])source.Clone();
|
||||
var gpu = (byte[])source.Clone();
|
||||
PixelBufferSoftwareProcessor.Fill(cpu, width, height, 23d, 197d, 89d, 173d, 1, 2, 4, 2);
|
||||
SetConstants(23d, 197d, 89d, 173d);
|
||||
_constants[4] = 1f;
|
||||
_constants[5] = 2f;
|
||||
_constants[6] = 5f;
|
||||
_constants[7] = 4f;
|
||||
_resources[0] = new PixelShaderInput(gpu, width, height);
|
||||
_partialValidated = RunFillPartial(_resources.AsSpan(0, 1), _constants.AsSpan(0, 8), gpu, width, height) && Equal(cpu, gpu);
|
||||
return _partialValidated.Value;
|
||||
}
|
||||
|
||||
private void SetConstants(double r, double g, double b, double a)
|
||||
{
|
||||
double aK = Math.Clamp(a, 0d, 255d) / 255d;
|
||||
byte pb = (byte)Math.Clamp(b * aK, 0d, 255d);
|
||||
byte pg = (byte)Math.Clamp(g * aK, 0d, 255d);
|
||||
byte pr = (byte)Math.Clamp(r * aK, 0d, 255d);
|
||||
byte pa = (byte)Math.Clamp(a, 0d, 255d);
|
||||
_constants[0] = pr / 255f;
|
||||
_constants[1] = pg / 255f;
|
||||
_constants[2] = pb / 255f;
|
||||
_constants[3] = pa / 255f;
|
||||
}
|
||||
|
||||
private static bool AreFinite(double r, double g, double b, double a)
|
||||
{
|
||||
return double.IsFinite(r) && double.IsFinite(g) && double.IsFinite(b) && double.IsFinite(a);
|
||||
}
|
||||
|
||||
private static byte[] CreateProbe(int width, int height)
|
||||
{
|
||||
var data = new byte[width * height * 4];
|
||||
for (int y = 0; y < height; y++)
|
||||
{
|
||||
for (int x = 0; x < width; x++)
|
||||
{
|
||||
int index = (y * width + x) * 4;
|
||||
byte a = (byte)((x * 31 + y * 47) & 255);
|
||||
data[index] = a == 0 ? (byte)0 : (byte)((x * 17 + y * 29) % (a + 1));
|
||||
data[index + 1] = a == 0 ? (byte)0 : (byte)((x * 43 + y * 11) % (a + 1));
|
||||
data[index + 2] = a == 0 ? (byte)0 : (byte)((x * 7 + y * 53) % (a + 1));
|
||||
data[index + 3] = a;
|
||||
}
|
||||
}
|
||||
return data;
|
||||
}
|
||||
|
||||
private partial bool RunFillFull(ReadOnlySpan<float> constants, byte[] target, int width, int height);
|
||||
|
||||
private partial bool RunFillPartial(ReadOnlySpan<PixelShaderInput> resources, ReadOnlySpan<float> constants, byte[] target, int width, int height);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,30 @@
|
||||
using LuaScript.Engine.Shader;
|
||||
|
||||
namespace LuaScript.Engine.Processing
|
||||
{
|
||||
internal sealed class GpuPixelBufferProcessor(PixelShaderRunner runner) : IPixelBufferProcessor
|
||||
{
|
||||
private readonly object _gate = new();
|
||||
private readonly GpuFillOperation _fill = new(runner);
|
||||
private readonly GpuConvolveOperation _convolve = new(runner);
|
||||
private readonly GpuResizeOperation _resize = new(runner);
|
||||
|
||||
public bool TryFill(byte[] target, int width, int height, double r, double g, double b, double a, int x, int y, int fillWidth, int fillHeight)
|
||||
{
|
||||
lock (_gate)
|
||||
return _fill.TryFill(target, width, height, r, g, b, a, x, y, fillWidth, fillHeight);
|
||||
}
|
||||
|
||||
public bool TryConvolve(byte[] target, int width, int height, double[] kernel, int size, double divisor, double offset)
|
||||
{
|
||||
lock (_gate)
|
||||
return _convolve.TryConvolve(target, width, height, kernel, size, divisor, offset);
|
||||
}
|
||||
|
||||
public bool TryResize(byte[] source, int sourceWidth, int sourceHeight, int targetWidth, int targetHeight, bool linear, out byte[]? target)
|
||||
{
|
||||
lock (_gate)
|
||||
return _resize.TryResize(source, sourceWidth, sourceHeight, targetWidth, targetHeight, linear, out target);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,47 @@
|
||||
using System;
|
||||
using LuaScript.Engine.Shader;
|
||||
|
||||
namespace LuaScript.Engine.Processing
|
||||
{
|
||||
internal abstract class GpuPixelOperation(PixelShaderRunner runner)
|
||||
{
|
||||
protected const int MaxTextureSize = 16384;
|
||||
|
||||
protected bool Run(byte[] bytecode, ReadOnlySpan<PixelShaderInput> resources, ReadOnlySpan<float> constants, byte[] target, int width, int height)
|
||||
{
|
||||
return runner.TryRunHardware(
|
||||
bytecode,
|
||||
resources,
|
||||
constants,
|
||||
PixelShaderBlend.Copy,
|
||||
PixelShaderSampler.None,
|
||||
target,
|
||||
width,
|
||||
height,
|
||||
out _) == PixelShaderRunStatus.Success;
|
||||
}
|
||||
|
||||
protected static bool IsTextureSupported(byte[] buffer, int width, int height)
|
||||
{
|
||||
return IsTextureSizeSupported(width, height) && (long)buffer.Length >= (long)width * height * 4;
|
||||
}
|
||||
|
||||
protected static bool IsTextureSizeSupported(int width, int height)
|
||||
{
|
||||
return width > 0 && height > 0 && width <= MaxTextureSize && height <= MaxTextureSize;
|
||||
}
|
||||
|
||||
protected static bool Equal(byte[] expected, byte[] actual)
|
||||
{
|
||||
return expected.AsSpan().SequenceEqual(actual);
|
||||
}
|
||||
|
||||
protected static byte[] CopyProbe(byte[] source, int width, int height, int probeWidth, int probeHeight)
|
||||
{
|
||||
var data = new byte[probeWidth * probeHeight * 4];
|
||||
for (int y = 0; y < probeHeight; y++)
|
||||
Buffer.BlockCopy(source, y * width * 4, data, y * probeWidth * 4, probeWidth * 4);
|
||||
return data;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,14 @@
|
||||
using System;
|
||||
|
||||
namespace LuaScript.Engine.Processing
|
||||
{
|
||||
[AttributeUsage(AttributeTargets.Class, AllowMultiple = true)]
|
||||
internal sealed class GpuPixelOperationShaderAttribute(string methodName, string fileName, string entryPoint) : Attribute
|
||||
{
|
||||
public string MethodName { get; } = methodName;
|
||||
|
||||
public string FileName { get; } = fileName;
|
||||
|
||||
public string EntryPoint { get; } = entryPoint;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,82 @@
|
||||
using System;
|
||||
using LuaScript.Engine.Shader;
|
||||
|
||||
namespace LuaScript.Engine.Processing
|
||||
{
|
||||
[GpuPixelOperationShader(nameof(RunResizeNearest), "Shaders/resize.hlsl", "resize_nearest")]
|
||||
[GpuPixelOperationShader(nameof(RunResizeLinear), "Shaders/resize.hlsl", "resize_linear")]
|
||||
internal sealed partial class GpuResizeOperation(PixelShaderRunner runner) : GpuPixelOperation(runner)
|
||||
{
|
||||
private const int ResizeThreshold = 262144;
|
||||
|
||||
private readonly PixelShaderInput[] _resources = new PixelShaderInput[1];
|
||||
private readonly float[] _constants = new float[4];
|
||||
|
||||
private byte[] _target = [];
|
||||
private bool? _nearestValidated;
|
||||
private bool? _linearValidated;
|
||||
|
||||
public bool TryResize(byte[] source, int sourceWidth, int sourceHeight, int targetWidth, int targetHeight, bool linear, out byte[]? target)
|
||||
{
|
||||
target = null;
|
||||
if (!IsTextureSupported(source, sourceWidth, sourceHeight) || !IsTextureSizeSupported(targetWidth, targetHeight))
|
||||
return false;
|
||||
|
||||
long pixels = (long)targetWidth * targetHeight;
|
||||
if (pixels < ResizeThreshold || !(linear ? EnsureLinearValidated(source, sourceWidth, sourceHeight) : EnsureNearestValidated(source, sourceWidth, sourceHeight)))
|
||||
return false;
|
||||
|
||||
return RunShader(source, sourceWidth, sourceHeight, targetWidth, targetHeight, linear, out target);
|
||||
}
|
||||
|
||||
private bool EnsureNearestValidated(byte[] source, int sourceWidth, int sourceHeight)
|
||||
{
|
||||
if (_nearestValidated.HasValue)
|
||||
return _nearestValidated.Value;
|
||||
_nearestValidated = Validate(source, sourceWidth, sourceHeight, false);
|
||||
return _nearestValidated.Value;
|
||||
}
|
||||
|
||||
private bool EnsureLinearValidated(byte[] source, int sourceWidth, int sourceHeight)
|
||||
{
|
||||
if (_linearValidated.HasValue)
|
||||
return _linearValidated.Value;
|
||||
_linearValidated = Validate(source, sourceWidth, sourceHeight, true);
|
||||
return _linearValidated.Value;
|
||||
}
|
||||
|
||||
private bool Validate(byte[] source, int sourceWidth, int sourceHeight, bool linear)
|
||||
{
|
||||
int probeWidth = Math.Min(sourceWidth, 8);
|
||||
int probeHeight = Math.Min(sourceHeight, 7);
|
||||
int targetWidth = Math.Max(1, probeWidth * 2 - 3);
|
||||
int targetHeight = Math.Max(1, probeHeight * 2 - 5);
|
||||
var probe = CopyProbe(source, sourceWidth, sourceHeight, probeWidth, probeHeight);
|
||||
byte[]? sourceScratch = null;
|
||||
byte[]? targetScratch = null;
|
||||
var cpu = PixelBufferSoftwareProcessor.Resize(probe, probeWidth, probeHeight, targetWidth, targetHeight, linear, ref sourceScratch, ref targetScratch);
|
||||
return RunShader(probe, probeWidth, probeHeight, targetWidth, targetHeight, linear, out var gpu) && gpu is not null && Equal(cpu, gpu);
|
||||
}
|
||||
|
||||
private bool RunShader(byte[] source, int sourceWidth, int sourceHeight, int targetWidth, int targetHeight, bool linear, out byte[]? target)
|
||||
{
|
||||
int count = checked(targetWidth * targetHeight * 4);
|
||||
if (_target.Length != count)
|
||||
_target = new byte[count];
|
||||
|
||||
_constants[0] = sourceWidth;
|
||||
_constants[1] = sourceHeight;
|
||||
_constants[2] = targetWidth;
|
||||
_constants[3] = targetHeight;
|
||||
_resources[0] = new PixelShaderInput(source, sourceWidth, sourceHeight);
|
||||
target = _target;
|
||||
return linear
|
||||
? RunResizeLinear(_resources.AsSpan(0, 1), _constants.AsSpan(0, 4), _target, targetWidth, targetHeight)
|
||||
: RunResizeNearest(_resources.AsSpan(0, 1), _constants.AsSpan(0, 4), _target, targetWidth, targetHeight);
|
||||
}
|
||||
|
||||
private partial bool RunResizeNearest(ReadOnlySpan<PixelShaderInput> resources, ReadOnlySpan<float> constants, byte[] target, int width, int height);
|
||||
|
||||
private partial bool RunResizeLinear(ReadOnlySpan<PixelShaderInput> resources, ReadOnlySpan<float> constants, byte[] target, int width, int height);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,50 @@
|
||||
<Project Sdk="Microsoft.NET.Sdk">
|
||||
|
||||
<PropertyGroup>
|
||||
<TargetFramework>net10.0-windows10.0.19041.0</TargetFramework>
|
||||
<ImplicitUsings>enable</ImplicitUsings>
|
||||
<Version>1.20.1</Version>
|
||||
<Platforms>AnyCPU;x64</Platforms>
|
||||
<Nullable>enable</Nullable>
|
||||
<AllowUnsafeBlocks>true</AllowUnsafeBlocks>
|
||||
</PropertyGroup>
|
||||
|
||||
<ItemGroup>
|
||||
<InternalsVisibleTo Include="LuaScript" />
|
||||
<InternalsVisibleTo Include="LuaScript.Tests" />
|
||||
</ItemGroup>
|
||||
|
||||
<ItemGroup>
|
||||
<ProjectReference Include="..\LuaScript.Runtime\LuaScript.Runtime.csproj" />
|
||||
<ProjectReference Include="..\LuaScript.Generator\LuaScript.Generator.csproj" OutputItemType="Analyzer" ReferenceOutputAssembly="false" />
|
||||
<AdditionalFiles Include="Shaders\*.hlsl" />
|
||||
</ItemGroup>
|
||||
|
||||
<ItemGroup>
|
||||
<Reference Include="SharpGen.Runtime">
|
||||
<HintPath>$(YMM4DirPath)SharpGen.Runtime.dll</HintPath>
|
||||
<Private>false</Private>
|
||||
</Reference>
|
||||
<Reference Include="Vortice.Direct3D11">
|
||||
<HintPath>$(YMM4DirPath)Vortice.Direct3D11.dll</HintPath>
|
||||
<Private>false</Private>
|
||||
</Reference>
|
||||
<Reference Include="Vortice.DirectX">
|
||||
<HintPath>$(YMM4DirPath)Vortice.DirectX.dll</HintPath>
|
||||
<Private>false</Private>
|
||||
</Reference>
|
||||
<Reference Include="Vortice.D3DCompiler.dll">
|
||||
<HintPath>$(YMM4DirPath)Vortice.D3DCompiler.dll</HintPath>
|
||||
<Private>false</Private>
|
||||
</Reference>
|
||||
<Reference Include="Vortice.DXGI.dll">
|
||||
<HintPath>$(YMM4DirPath)Vortice.DXGI.dll</HintPath>
|
||||
<Private>false</Private>
|
||||
</Reference>
|
||||
<Reference Include="Vortice.Mathematics">
|
||||
<HintPath>$(YMM4DirPath)Vortice.Mathematics.dll</HintPath>
|
||||
<Private>false</Private>
|
||||
</Reference>
|
||||
</ItemGroup>
|
||||
|
||||
</Project>
|
||||
+106
-10
@@ -7,7 +7,6 @@ using Vortice.Direct3D;
|
||||
using Vortice.Direct3D11;
|
||||
using Vortice.DXGI;
|
||||
using Vortice.Mathematics;
|
||||
using YukkuriMovieMaker.Commons;
|
||||
|
||||
namespace LuaScript.Engine.Shader
|
||||
{
|
||||
@@ -43,6 +42,7 @@ namespace LuaScript.Engine.Shader
|
||||
|
||||
private readonly Lock _locker = new();
|
||||
private readonly Dictionary<(string Hlsl, string Entry), CompiledShader> _shaders = [];
|
||||
private readonly Dictionary<byte[], ID3D11PixelShader> _precompiled = new(ReferenceEqualityComparer.Instance);
|
||||
private readonly InputSlot[] _inputs = new InputSlot[MaxResources];
|
||||
private readonly ID3D11ShaderResourceView[] _boundViews = new ID3D11ShaderResourceView[MaxResources];
|
||||
private readonly ID3D11ShaderResourceView[] _nullViews = new ID3D11ShaderResourceView[MaxResources];
|
||||
@@ -51,8 +51,11 @@ namespace LuaScript.Engine.Shader
|
||||
|
||||
public IBufferCompositor Compositor { get; set; } = SoftwareCompositor.Instance;
|
||||
|
||||
public Action<string, Exception?>? Logger { get; set; }
|
||||
|
||||
private ID3D11Device? _device;
|
||||
private ID3D11DeviceContext? _context;
|
||||
private DriverType _driverType;
|
||||
private ID3D11VertexShader? _vertexShader;
|
||||
private ID3D11Buffer? _constantBuffer;
|
||||
private ID3D11RasterizerState? _rasterizer;
|
||||
@@ -70,6 +73,7 @@ namespace LuaScript.Engine.Shader
|
||||
|
||||
private bool _disposed;
|
||||
private bool _unavailable;
|
||||
private bool _hardwareUnavailable;
|
||||
private bool _failureLogged;
|
||||
private int _recreateBudget = 3;
|
||||
|
||||
@@ -88,9 +92,7 @@ namespace LuaScript.Engine.Shader
|
||||
error = null;
|
||||
lock (_locker)
|
||||
{
|
||||
if (_disposed || _unavailable)
|
||||
return PixelShaderRunStatus.Unavailable;
|
||||
if (targetWidth <= 0 || targetHeight <= 0 || (long)target.Length < (long)targetWidth * targetHeight * 4)
|
||||
if (!CanRun(target, targetWidth, targetHeight))
|
||||
return PixelShaderRunStatus.Unavailable;
|
||||
|
||||
try
|
||||
@@ -116,6 +118,46 @@ namespace LuaScript.Engine.Shader
|
||||
}
|
||||
}
|
||||
|
||||
public PixelShaderRunStatus TryRunHardware(
|
||||
byte[] bytecode,
|
||||
ReadOnlySpan<PixelShaderInput> resources,
|
||||
ReadOnlySpan<float> constants,
|
||||
PixelShaderBlend blend,
|
||||
PixelShaderSampler sampler,
|
||||
byte[] target,
|
||||
int targetWidth,
|
||||
int targetHeight,
|
||||
out string? error)
|
||||
{
|
||||
error = null;
|
||||
lock (_locker)
|
||||
{
|
||||
if (!CanRun(target, targetWidth, targetHeight))
|
||||
return PixelShaderRunStatus.Unavailable;
|
||||
|
||||
try
|
||||
{
|
||||
if (!EnsureHardwareDevice())
|
||||
return PixelShaderRunStatus.Unavailable;
|
||||
|
||||
Execute(GetOrCreate(bytecode), resources, constants, blend, sampler, target, targetWidth, targetHeight);
|
||||
return PixelShaderRunStatus.Success;
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
HandleFailure(ex);
|
||||
return PixelShaderRunStatus.Unavailable;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private bool CanRun(byte[] target, int targetWidth, int targetHeight)
|
||||
{
|
||||
return !_disposed && !_unavailable &&
|
||||
targetWidth > 0 && targetHeight > 0 &&
|
||||
(long)target.Length >= (long)targetWidth * targetHeight * 4;
|
||||
}
|
||||
|
||||
public void Invalidate()
|
||||
{
|
||||
lock (_locker)
|
||||
@@ -146,19 +188,55 @@ namespace LuaScript.Engine.Shader
|
||||
}
|
||||
_recreateBudget--;
|
||||
|
||||
if (!TryCreateDevice(DriverType.Hardware, out var device, out var context) &&
|
||||
!TryCreateDevice(DriverType.Warp, out device, out context))
|
||||
DriverType driverType;
|
||||
if (TryCreateDevice(DriverType.Hardware, out var device, out var context))
|
||||
{
|
||||
driverType = DriverType.Hardware;
|
||||
}
|
||||
else if (TryCreateDevice(DriverType.Warp, out device, out context))
|
||||
{
|
||||
driverType = DriverType.Warp;
|
||||
}
|
||||
else
|
||||
{
|
||||
MarkUnavailable(null);
|
||||
return false;
|
||||
}
|
||||
|
||||
return InitializeDevice(device, context, driverType, true);
|
||||
}
|
||||
|
||||
private bool EnsureHardwareDevice()
|
||||
{
|
||||
if (_device is not null)
|
||||
return _driverType == DriverType.Hardware;
|
||||
if (_hardwareUnavailable)
|
||||
return false;
|
||||
if (_recreateBudget <= 0)
|
||||
{
|
||||
_hardwareUnavailable = true;
|
||||
return false;
|
||||
}
|
||||
_recreateBudget--;
|
||||
if (!TryCreateDevice(DriverType.Hardware, out var device, out var context))
|
||||
{
|
||||
_hardwareUnavailable = true;
|
||||
return false;
|
||||
}
|
||||
|
||||
return InitializeDevice(device, context, DriverType.Hardware, false);
|
||||
}
|
||||
|
||||
private bool InitializeDevice(ID3D11Device? device, ID3D11DeviceContext? context, DriverType driverType, bool markUnavailable)
|
||||
{
|
||||
try
|
||||
{
|
||||
var vsBytecode = CompileOrThrow(VertexShaderSource, "vsmain", "vs_4_0");
|
||||
var vertexShader = device!.CreateVertexShader(vsBytecode);
|
||||
_device = device;
|
||||
_context = context;
|
||||
_driverType = driverType;
|
||||
_hardwareUnavailable = driverType != DriverType.Hardware && _hardwareUnavailable;
|
||||
_vertexShader = vertexShader;
|
||||
_constantBuffer = device.CreateBuffer(new BufferDescription(
|
||||
ConstantBufferSize, BindFlags.ConstantBuffer, ResourceUsage.Dynamic, CpuAccessFlags.Write));
|
||||
@@ -178,7 +256,10 @@ namespace LuaScript.Engine.Shader
|
||||
context?.Dispose();
|
||||
device?.Dispose();
|
||||
}
|
||||
MarkUnavailable(ex);
|
||||
if (markUnavailable)
|
||||
MarkUnavailable(ex);
|
||||
else
|
||||
_hardwareUnavailable = true;
|
||||
return false;
|
||||
}
|
||||
}
|
||||
@@ -267,6 +348,16 @@ namespace LuaScript.Engine.Shader
|
||||
return compiled;
|
||||
}
|
||||
|
||||
private ID3D11PixelShader GetOrCreate(byte[] bytecode)
|
||||
{
|
||||
if (_precompiled.TryGetValue(bytecode, out var cached))
|
||||
return cached;
|
||||
|
||||
var shader = _device!.CreatePixelShader(bytecode);
|
||||
_precompiled[bytecode] = shader;
|
||||
return shader;
|
||||
}
|
||||
|
||||
private static byte[] CompileOrThrow(string source, string entryPoint, string profile)
|
||||
{
|
||||
var result = Compiler.Compile(Encoding.UTF8.GetBytes(source), entryPoint, string.Empty, profile, out var bytecode, out var errors);
|
||||
@@ -503,7 +594,7 @@ namespace LuaScript.Engine.Shader
|
||||
if (!_failureLogged)
|
||||
{
|
||||
_failureLogged = true;
|
||||
Log.Default.Write("LuaScript: obj.pixelshader execution failed; the call is skipped.", ex);
|
||||
WriteLog("LuaScript: obj.pixelshader execution failed; the call is skipped.", ex);
|
||||
}
|
||||
ReleaseDeviceObjects();
|
||||
if (_recreateBudget <= 0)
|
||||
@@ -517,16 +608,21 @@ namespace LuaScript.Engine.Shader
|
||||
return;
|
||||
_failureLogged = true;
|
||||
if (ex is null)
|
||||
Log.Default.Write("LuaScript: Direct3D 11 is unavailable; obj.pixelshader is disabled.");
|
||||
WriteLog("LuaScript: Direct3D 11 is unavailable; obj.pixelshader is disabled.", null);
|
||||
else
|
||||
Log.Default.Write("LuaScript: Direct3D 11 initialization failed; obj.pixelshader is disabled.", ex);
|
||||
WriteLog("LuaScript: Direct3D 11 initialization failed; obj.pixelshader is disabled.", ex);
|
||||
}
|
||||
|
||||
private void WriteLog(string message, Exception? exception) => Logger?.Invoke(message, exception);
|
||||
|
||||
private void ReleaseShaders()
|
||||
{
|
||||
foreach (var compiled in _shaders.Values)
|
||||
compiled.Shader?.Dispose();
|
||||
_shaders.Clear();
|
||||
foreach (var shader in _precompiled.Values)
|
||||
shader.Dispose();
|
||||
_precompiled.Clear();
|
||||
}
|
||||
|
||||
private void ReleaseDeviceObjects()
|
||||
@@ -0,0 +1,58 @@
|
||||
Texture2D source : register(t0);
|
||||
|
||||
cbuffer Parameters : register(b0)
|
||||
{
|
||||
float4 values[256];
|
||||
};
|
||||
|
||||
float get_value(uint index)
|
||||
{
|
||||
uint row = index >> 2;
|
||||
uint column = index & 3u;
|
||||
float4 value = values[row];
|
||||
if (column == 0u)
|
||||
return value.x;
|
||||
if (column == 1u)
|
||||
return value.y;
|
||||
if (column == 2u)
|
||||
return value.z;
|
||||
return value.w;
|
||||
}
|
||||
|
||||
float convolve_channel(float value)
|
||||
{
|
||||
return floor(saturate(value) * 255.0) / 255.0;
|
||||
}
|
||||
|
||||
float4 convolve(float4 pos : SV_Position) : SV_Target
|
||||
{
|
||||
uint2 p = (uint2)floor(pos.xy);
|
||||
int width = (int)get_value(0u);
|
||||
int height = (int)get_value(1u);
|
||||
float divisor = get_value(2u);
|
||||
float offset = get_value(3u) / 255.0;
|
||||
int kernelSize = (int)get_value(4u);
|
||||
int radius = (int)get_value(5u);
|
||||
float4 sum = 0.0;
|
||||
|
||||
for (int ky = 0; ky < kernelSize; ky++)
|
||||
{
|
||||
int sy = clamp((int)p.y + ky - radius, 0, height - 1);
|
||||
for (int kx = 0; kx < kernelSize; kx++)
|
||||
{
|
||||
int sx = clamp((int)p.x + kx - radius, 0, width - 1);
|
||||
float kv = get_value((uint)(8 + ky * kernelSize + kx));
|
||||
float4 sourceValue = source[uint2((uint)sx, (uint)sy)];
|
||||
float3 rgb = sourceValue.a <= 0.0 ? 0.0 : saturate(sourceValue.rgb / sourceValue.a);
|
||||
sum += float4(rgb, sourceValue.a) * kv;
|
||||
}
|
||||
}
|
||||
|
||||
float3 rgbOut = saturate(sum.rgb / divisor + offset);
|
||||
float alpha = saturate(sum.a / divisor + offset);
|
||||
return float4(
|
||||
convolve_channel(rgbOut.r * alpha),
|
||||
convolve_channel(rgbOut.g * alpha),
|
||||
convolve_channel(rgbOut.b * alpha),
|
||||
convolve_channel(alpha));
|
||||
}
|
||||
@@ -0,0 +1,21 @@
|
||||
Texture2D source : register(t0);
|
||||
|
||||
cbuffer Parameters : register(b0)
|
||||
{
|
||||
float4 color;
|
||||
float4 rect;
|
||||
};
|
||||
|
||||
float4 fill_full(float4 pos : SV_Position) : SV_Target
|
||||
{
|
||||
return color;
|
||||
}
|
||||
|
||||
float4 fill_partial(float4 pos : SV_Position) : SV_Target
|
||||
{
|
||||
uint2 p = (uint2)floor(pos.xy);
|
||||
uint4 r = (uint4)rect;
|
||||
if (p.x >= r.x && p.y >= r.y && p.x < r.z && p.y < r.w)
|
||||
return color;
|
||||
return source[p];
|
||||
}
|
||||
@@ -0,0 +1,56 @@
|
||||
Texture2D source : register(t0);
|
||||
|
||||
cbuffer Parameters : register(b0)
|
||||
{
|
||||
float4 size;
|
||||
};
|
||||
|
||||
float channel(float value)
|
||||
{
|
||||
return floor(saturate(value) * 255.0) / 255.0;
|
||||
}
|
||||
|
||||
float4 resize_pack(float4 value)
|
||||
{
|
||||
return float4(channel(value.r), channel(value.g), channel(value.b), channel(value.a));
|
||||
}
|
||||
|
||||
float4 resize_nearest(float4 pos : SV_Position) : SV_Target
|
||||
{
|
||||
uint2 p = (uint2)floor(pos.xy);
|
||||
uint sourceWidth = (uint)size.x;
|
||||
uint sourceHeight = (uint)size.y;
|
||||
uint targetWidth = (uint)size.z;
|
||||
uint targetHeight = (uint)size.w;
|
||||
uint sx = min(((p.x * 2u + 1u) * sourceWidth) / (targetWidth * 2u), sourceWidth - 1u);
|
||||
uint sy = min(((p.y * 2u + 1u) * sourceHeight) / (targetHeight * 2u), sourceHeight - 1u);
|
||||
return source[uint2(sx, sy)];
|
||||
}
|
||||
|
||||
float4 resize_linear(float4 pos : SV_Position) : SV_Target
|
||||
{
|
||||
uint2 p = (uint2)floor(pos.xy);
|
||||
float sourceWidth = size.x;
|
||||
float sourceHeight = size.y;
|
||||
float targetWidth = size.z;
|
||||
float targetHeight = size.w;
|
||||
float u = (p.x + 0.5) * sourceWidth / targetWidth - 0.5;
|
||||
float v = (p.y + 0.5) * sourceHeight / targetHeight - 0.5;
|
||||
int x0 = (int)floor(u);
|
||||
int y0 = (int)floor(v);
|
||||
float tx = u - x0;
|
||||
float ty = v - y0;
|
||||
int maxX = (int)sourceWidth - 1;
|
||||
int maxY = (int)sourceHeight - 1;
|
||||
uint xA = (uint)clamp(x0, 0, maxX);
|
||||
uint yA = (uint)clamp(y0, 0, maxY);
|
||||
uint xB = (uint)clamp(x0 + 1, 0, maxX);
|
||||
uint yB = (uint)clamp(y0 + 1, 0, maxY);
|
||||
float4 c00 = source[uint2(xA, yA)];
|
||||
float4 c10 = source[uint2(xB, yA)];
|
||||
float4 c01 = source[uint2(xA, yB)];
|
||||
float4 c11 = source[uint2(xB, yB)];
|
||||
float4 top = c00 * (1.0 - tx) + c10 * tx;
|
||||
float4 bottom = c01 * (1.0 - tx) + c11 * tx;
|
||||
return resize_pack(top * (1.0 - ty) + bottom * ty);
|
||||
}
|
||||
@@ -6,7 +6,7 @@ namespace LuaScript.Engine.Kernel
|
||||
internal sealed class KernelExtractor
|
||||
{
|
||||
private readonly List<KExpr> _bindings = [];
|
||||
private readonly Dictionary<string, int> _scope = new(StringComparer.Ordinal);
|
||||
private Dictionary<string, int> _scope = new(StringComparer.Ordinal);
|
||||
private readonly SortedSet<KernelUniform> _uniforms = [];
|
||||
|
||||
private string _widthVariable = string.Empty;
|
||||
@@ -46,25 +46,26 @@ namespace LuaScript.Engine.Kernel
|
||||
|
||||
if (index >= block.Count || block[index] is not NumericForStmt outer)
|
||||
return null;
|
||||
if (index + 1 != block.Count)
|
||||
int tail = index + 1;
|
||||
if (tail < block.Count && IsPutPixelData(block[tail]))
|
||||
tail++;
|
||||
if (tail != block.Count)
|
||||
return null;
|
||||
|
||||
if (!TryAxis(outer, out string outerVar, out KAxis outerAxis))
|
||||
return null;
|
||||
_scope.Remove(outerVar);
|
||||
if (outer.Body.Count != 1 || outer.Body[0] is not NumericForStmt inner)
|
||||
return null;
|
||||
if (!TryAxis(inner, out string innerVar, out KAxis innerAxis))
|
||||
return null;
|
||||
_scope.Remove(innerVar);
|
||||
if (outerAxis == innerAxis)
|
||||
return null;
|
||||
if (_pixelDataVariable is not null &&
|
||||
(string.Equals(outerVar, _pixelDataVariable, StringComparison.Ordinal) ||
|
||||
string.Equals(innerVar, _pixelDataVariable, StringComparison.Ordinal)))
|
||||
return null;
|
||||
if (_scope.ContainsKey(outerVar))
|
||||
_scope.Remove(outerVar);
|
||||
if (_scope.ContainsKey(innerVar))
|
||||
_scope.Remove(innerVar);
|
||||
|
||||
_widthVariable = outerAxis == KAxis.X ? outerVar : innerVar;
|
||||
_heightVariable = outerAxis == KAxis.Y ? outerVar : innerVar;
|
||||
@@ -72,6 +73,13 @@ namespace LuaScript.Engine.Kernel
|
||||
return _pixelDataVariable is null ? BuildKernel(inner.Body) : BuildPixelDataKernel(inner.Body);
|
||||
}
|
||||
|
||||
private bool IsPutPixelData(LuaStmt statement) =>
|
||||
_pixelDataVariable is not null &&
|
||||
statement is CallStmt { Call: CallExpr { Arguments.Count: 1 } call } &&
|
||||
IsObjectMethod(call, "putpixeldata") &&
|
||||
call.Arguments[0] is NameExpr { } handle &&
|
||||
string.Equals(handle.Name, _pixelDataVariable, StringComparison.Ordinal);
|
||||
|
||||
private bool TryBindPixelData(LocalStmt local)
|
||||
{
|
||||
if (local.Names.Count != 1 || local.Values.Count != 1 ||
|
||||
@@ -105,6 +113,9 @@ namespace LuaScript.Engine.Kernel
|
||||
case AssignStmt assign:
|
||||
BindAssign(assign);
|
||||
break;
|
||||
case IfStmt conditional:
|
||||
LowerConditional(conditional);
|
||||
break;
|
||||
case CallStmt { Call: MethodCallExpr set } when IsPixelDataSet(set, out int writeChannel):
|
||||
var value = ClampChannel(Lower(set.Arguments[1]));
|
||||
if (writeChannel == 0) outR = value;
|
||||
@@ -140,11 +151,25 @@ namespace LuaScript.Engine.Kernel
|
||||
if (expression is MemberExpr { Target: NameExpr { Name: "obj" }, Name: var field } &&
|
||||
KernelUniforms.TryResolveMember("obj", field, out var uniform))
|
||||
return uniform == KernelUniform.Width;
|
||||
if (expression is NameExpr { } alias &&
|
||||
TryUniformAlias(alias.Name, out var aliased))
|
||||
return aliased == KernelUniform.Width;
|
||||
return _pixelDataVariable is not null &&
|
||||
expression is MemberExpr { Target: NameExpr { } target, Name: "width" } &&
|
||||
string.Equals(target.Name, _pixelDataVariable, StringComparison.Ordinal);
|
||||
}
|
||||
|
||||
private bool TryUniformAlias(string name, out KernelUniform uniform)
|
||||
{
|
||||
if (_scope.TryGetValue(name, out int slot) && _bindings[slot] is KUniformRef reference)
|
||||
{
|
||||
uniform = reference.Uniform;
|
||||
return true;
|
||||
}
|
||||
uniform = default;
|
||||
return false;
|
||||
}
|
||||
|
||||
private bool TryPixelDataChannel(LuaExpr expression, out int channel)
|
||||
{
|
||||
channel = 0;
|
||||
@@ -221,6 +246,9 @@ namespace LuaScript.Engine.Kernel
|
||||
case AssignStmt assign:
|
||||
BindAssign(assign);
|
||||
break;
|
||||
case IfStmt conditional:
|
||||
LowerConditional(conditional);
|
||||
break;
|
||||
default:
|
||||
return null;
|
||||
}
|
||||
@@ -276,6 +304,76 @@ namespace LuaScript.Engine.Kernel
|
||||
_scope[((NameExpr)assign.Targets[i]).Name] = AddBinding(lowered[i]);
|
||||
}
|
||||
|
||||
private void LowerConditional(IfStmt statement) =>
|
||||
LowerConditional(statement.Clauses, 0, statement.ElseBody);
|
||||
|
||||
private void LowerConditional(IReadOnlyList<IfClause> clauses, int index, IReadOnlyList<LuaStmt>? elseBody)
|
||||
{
|
||||
var clause = clauses[index];
|
||||
var condition = LowerBool(clause.Condition);
|
||||
var baseline = _scope;
|
||||
|
||||
_scope = new Dictionary<string, int>(baseline, StringComparer.Ordinal);
|
||||
LowerBranchBody(clause.Body);
|
||||
var taken = _scope;
|
||||
|
||||
_scope = new Dictionary<string, int>(baseline, StringComparer.Ordinal);
|
||||
if (index + 1 < clauses.Count)
|
||||
LowerConditional(clauses, index + 1, elseBody);
|
||||
else if (elseBody is not null)
|
||||
LowerBranchBody(elseBody);
|
||||
var skipped = _scope;
|
||||
|
||||
var merged = new Dictionary<string, int>(baseline.Count, StringComparer.Ordinal);
|
||||
foreach (var name in baseline.Keys)
|
||||
{
|
||||
int whenTrue = taken[name];
|
||||
int whenFalse = skipped[name];
|
||||
merged[name] = whenTrue == whenFalse
|
||||
? whenTrue
|
||||
: AddBinding(new KSelect(condition, new KLocalRef(whenTrue), new KLocalRef(whenFalse)));
|
||||
}
|
||||
_scope = merged;
|
||||
}
|
||||
|
||||
private void LowerBranchBody(IReadOnlyList<LuaStmt> body)
|
||||
{
|
||||
Dictionary<string, int>? shadowed = null;
|
||||
HashSet<string>? introduced = null;
|
||||
foreach (var statement in body)
|
||||
{
|
||||
switch (statement)
|
||||
{
|
||||
case LocalStmt local:
|
||||
foreach (var name in local.Names)
|
||||
{
|
||||
if (introduced?.Contains(name) == true || shadowed?.ContainsKey(name) == true)
|
||||
continue;
|
||||
if (_scope.TryGetValue(name, out int slot))
|
||||
(shadowed ??= new(StringComparer.Ordinal))[name] = slot;
|
||||
else
|
||||
(introduced ??= new(StringComparer.Ordinal)).Add(name);
|
||||
}
|
||||
BindLocal(local);
|
||||
break;
|
||||
case AssignStmt assign:
|
||||
BindAssign(assign);
|
||||
break;
|
||||
case IfStmt nested:
|
||||
LowerConditional(nested);
|
||||
break;
|
||||
default:
|
||||
throw new KernelUnsupportedException("Unsupported statement in a conditional branch.");
|
||||
}
|
||||
}
|
||||
if (shadowed is not null)
|
||||
foreach (var (name, slot) in shadowed)
|
||||
_scope[name] = slot;
|
||||
if (introduced is not null)
|
||||
foreach (var name in introduced)
|
||||
_scope.Remove(name);
|
||||
}
|
||||
|
||||
private void EnsureNotCoordinateName(string name)
|
||||
{
|
||||
if (string.Equals(name, _widthVariable, StringComparison.Ordinal) ||
|
||||
@@ -343,6 +441,16 @@ namespace LuaScript.Engine.Kernel
|
||||
if (member.Target is NameExpr target && KernelUniforms.TryResolveMember(target.Name, member.Name, out var uniform))
|
||||
return UseUniform(uniform);
|
||||
|
||||
if (_pixelDataVariable is not null &&
|
||||
member.Target is NameExpr { } handle &&
|
||||
string.Equals(handle.Name, _pixelDataVariable, StringComparison.Ordinal))
|
||||
{
|
||||
if (string.Equals(member.Name, "width", StringComparison.Ordinal))
|
||||
return UseUniform(KernelUniform.Width);
|
||||
if (string.Equals(member.Name, "height", StringComparison.Ordinal))
|
||||
return UseUniform(KernelUniform.Height);
|
||||
}
|
||||
|
||||
throw new KernelUnsupportedException("Unsupported member access in pixel kernel.");
|
||||
}
|
||||
|
||||
@@ -474,6 +582,20 @@ namespace LuaScript.Engine.Kernel
|
||||
return true;
|
||||
}
|
||||
}
|
||||
|
||||
if (bound.Left is NameExpr { } alias && TryUniformAlias(alias.Name, out var aliased))
|
||||
{
|
||||
if (aliased == KernelUniform.Width)
|
||||
{
|
||||
axis = KAxis.X;
|
||||
return true;
|
||||
}
|
||||
if (aliased == KernelUniform.Height)
|
||||
{
|
||||
axis = KAxis.Y;
|
||||
return true;
|
||||
}
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
|
||||
@@ -3,7 +3,7 @@
|
||||
<PropertyGroup>
|
||||
<TargetFramework>net10.0-windows10.0.19041.0</TargetFramework>
|
||||
<ImplicitUsings>enable</ImplicitUsings>
|
||||
<Version>1.16.0</Version>
|
||||
<Version>1.20.1</Version>
|
||||
<Platforms>AnyCPU;x64</Platforms>
|
||||
<Nullable>enable</Nullable>
|
||||
</PropertyGroup>
|
||||
|
||||
@@ -3,7 +3,7 @@
|
||||
<PropertyGroup>
|
||||
<TargetFramework>net10.0-windows10.0.19041.0</TargetFramework>
|
||||
<ImplicitUsings>enable</ImplicitUsings>
|
||||
<Version>1.16.0</Version>
|
||||
<Version>1.20.1</Version>
|
||||
<Platforms>AnyCPU;x64</Platforms>
|
||||
<Nullable>enable</Nullable>
|
||||
<AllowUnsafeBlocks>true</AllowUnsafeBlocks>
|
||||
|
||||
@@ -9,6 +9,13 @@ namespace LuaScript.Anchor
|
||||
|
||||
public static int ClampCount(int count) => Math.Clamp(count, 0, MaxAnchors);
|
||||
|
||||
public static int NormalizeCount(string group, int count)
|
||||
{
|
||||
if (count <= 0 && string.Equals(group, TrackGroup, StringComparison.Ordinal))
|
||||
return 1;
|
||||
return ClampCount(count);
|
||||
}
|
||||
|
||||
public static void ApplyOption(string option, ref AnchorConnection connection, ref bool is3D)
|
||||
{
|
||||
switch (option)
|
||||
@@ -52,6 +59,35 @@ namespace LuaScript.Anchor
|
||||
z = 0d;
|
||||
}
|
||||
|
||||
public static ImmutableList<LuaAnchorPoint> SetPosition(
|
||||
ImmutableList<LuaAnchorPoint> source, string group, int index, double x, double y, double z)
|
||||
{
|
||||
for (int i = 0; i < source.Count; i++)
|
||||
{
|
||||
var a = source[i];
|
||||
if (a.Index == index && string.Equals(a.Group, group, StringComparison.Ordinal))
|
||||
{
|
||||
return source.SetItem(i, new LuaAnchorPoint
|
||||
{
|
||||
Group = group,
|
||||
Index = index,
|
||||
X = x,
|
||||
Y = y,
|
||||
Z = z,
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
return source.Add(new LuaAnchorPoint
|
||||
{
|
||||
Group = group,
|
||||
Index = index,
|
||||
X = x,
|
||||
Y = y,
|
||||
Z = z,
|
||||
});
|
||||
}
|
||||
|
||||
public static ImmutableList<LuaAnchorPoint> ApplyDrag(
|
||||
ImmutableList<LuaAnchorPoint> source, string group, int index, double dx, double dy, double dz)
|
||||
{
|
||||
|
||||
@@ -60,6 +60,7 @@ namespace LuaScript.Api
|
||||
}
|
||||
|
||||
var candidates = Keywords
|
||||
.Concat(LuaScript.Compat.Syntax.LuaSyntaxRuleRegistry.CatalogKeywords)
|
||||
.Concat(globals)
|
||||
.Concat(tableMembers.Keys)
|
||||
.Concat(tableMembers.Values.SelectMany(x => x))
|
||||
|
||||
@@ -72,6 +72,12 @@ namespace LuaScript
|
||||
|
||||
public Func<ISceneObjectResolver>? ResolverProvider { get; set; }
|
||||
|
||||
public Func<string, double, (byte[] Buffer, int Width, int Height)>? SceneImageLoader { get; set; }
|
||||
|
||||
public Func<string, double, double, IReadOnlyList<KeyValuePair<string, object>>, (byte[] Buffer, int Width, int Height)>? BrushImageLoader { get; set; }
|
||||
|
||||
public Func<string, string, int, (int Count, int Rate, double[] Data)>? AudioLoader { get; set; }
|
||||
|
||||
private readonly Dictionary<string, string> _stringParameters = new(StringComparer.Ordinal);
|
||||
|
||||
public IReadOnlyDictionary<string, string> StringParameters => _stringParameters;
|
||||
@@ -163,6 +169,8 @@ namespace LuaScript
|
||||
|
||||
internal IPixelShaderRunner? ShaderRunner { get; set; }
|
||||
|
||||
internal IPixelBufferProcessor? PixelProcessor { get; set; }
|
||||
|
||||
internal AviUtlPixelShaderLibrary PixelShaders { get; set; } = AviUtlPixelShaderLibrary.Empty;
|
||||
|
||||
internal bool TryGetShaderResource(string id, out byte[] data, out int width, out int height) =>
|
||||
@@ -498,5 +506,158 @@ namespace LuaScript
|
||||
p[3] = (byte)Math.Clamp(a, 0d, 255d);
|
||||
}
|
||||
}
|
||||
|
||||
private double[]? _convolveSource;
|
||||
private byte[]? _resizeSource;
|
||||
private byte[]? _resizeBuffer;
|
||||
|
||||
public unsafe void FillBuffer(double r, double g, double b, double a, int x, int y, int w, int h)
|
||||
{
|
||||
EnsurePixelBuffer();
|
||||
if (_pixelBuffer is null)
|
||||
return;
|
||||
|
||||
int cw = ImageWidth;
|
||||
int ch = ImageHeight;
|
||||
int x0 = Math.Clamp(x, 0, cw);
|
||||
int y0 = Math.Clamp(y, 0, ch);
|
||||
int x1 = Math.Clamp(x + w, 0, cw);
|
||||
int y1 = Math.Clamp(y + h, 0, ch);
|
||||
if (x1 <= x0 || y1 <= y0)
|
||||
return;
|
||||
|
||||
if (PixelProcessor?.TryFill(_pixelBuffer, cw, ch, r, g, b, a, x0, y0, x1 - x0, y1 - y0) == true)
|
||||
{
|
||||
_isPixelsDirty = true;
|
||||
return;
|
||||
}
|
||||
|
||||
_isPixelsDirty = true;
|
||||
PixelBufferSoftwareProcessor.Fill(_pixelBuffer, cw, ch, r, g, b, a, x0, y0, x1 - x0, y1 - y0);
|
||||
}
|
||||
|
||||
public unsafe void ReadRegion(int x, int y, int w, int h, double[] destination)
|
||||
{
|
||||
EnsurePixelBuffer();
|
||||
int cw = ImageWidth;
|
||||
int ch = ImageHeight;
|
||||
if (_pixelBuffer is null)
|
||||
{
|
||||
Array.Clear(destination, 0, w * h * 4);
|
||||
return;
|
||||
}
|
||||
|
||||
fixed (byte* buf = _pixelBuffer)
|
||||
{
|
||||
for (int j = 0; j < h; j++)
|
||||
{
|
||||
int sy = y + j;
|
||||
for (int i = 0; i < w; i++)
|
||||
{
|
||||
int sx = x + i;
|
||||
int di = (j * w + i) * 4;
|
||||
if ((uint)sx >= (uint)cw || (uint)sy >= (uint)ch)
|
||||
{
|
||||
destination[di] = 0d;
|
||||
destination[di + 1] = 0d;
|
||||
destination[di + 2] = 0d;
|
||||
destination[di + 3] = 0d;
|
||||
continue;
|
||||
}
|
||||
byte* p = buf + (sy * cw + sx) * 4;
|
||||
double a = p[3];
|
||||
if (a <= 0d)
|
||||
{
|
||||
destination[di] = 0d;
|
||||
destination[di + 1] = 0d;
|
||||
destination[di + 2] = 0d;
|
||||
destination[di + 3] = 0d;
|
||||
}
|
||||
else
|
||||
{
|
||||
double s = 255d / a;
|
||||
destination[di] = Math.Clamp(p[2] * s, 0d, 255d);
|
||||
destination[di + 1] = Math.Clamp(p[1] * s, 0d, 255d);
|
||||
destination[di + 2] = Math.Clamp(p[0] * s, 0d, 255d);
|
||||
destination[di + 3] = a;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
public unsafe void WriteRegion(int x, int y, int w, int h, double[] source)
|
||||
{
|
||||
EnsurePixelBuffer();
|
||||
if (_pixelBuffer is null)
|
||||
return;
|
||||
|
||||
int cw = ImageWidth;
|
||||
int ch = ImageHeight;
|
||||
_isPixelsDirty = true;
|
||||
|
||||
fixed (byte* buf = _pixelBuffer)
|
||||
{
|
||||
for (int j = 0; j < h; j++)
|
||||
{
|
||||
int dy = y + j;
|
||||
if ((uint)dy >= (uint)ch)
|
||||
continue;
|
||||
for (int i = 0; i < w; i++)
|
||||
{
|
||||
int dx = x + i;
|
||||
if ((uint)dx >= (uint)cw)
|
||||
continue;
|
||||
int si = (j * w + i) * 4;
|
||||
double a = Math.Clamp(source[si + 3], 0d, 255d);
|
||||
double aK = a / 255d;
|
||||
byte* p = buf + (dy * cw + dx) * 4;
|
||||
p[0] = (byte)Math.Clamp(source[si + 2] * aK, 0d, 255d);
|
||||
p[1] = (byte)Math.Clamp(source[si + 1] * aK, 0d, 255d);
|
||||
p[2] = (byte)Math.Clamp(source[si] * aK, 0d, 255d);
|
||||
p[3] = (byte)a;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
public unsafe void Convolve(double[] kernel, int size, double divisor, double offset)
|
||||
{
|
||||
EnsurePixelBuffer();
|
||||
if (_pixelBuffer is null)
|
||||
return;
|
||||
|
||||
int cw = ImageWidth;
|
||||
int ch = ImageHeight;
|
||||
if (PixelProcessor?.TryConvolve(_pixelBuffer, cw, ch, kernel, size, divisor, offset) == true)
|
||||
{
|
||||
_isPixelsDirty = true;
|
||||
return;
|
||||
}
|
||||
|
||||
_isPixelsDirty = true;
|
||||
PixelBufferSoftwareProcessor.Convolve(_pixelBuffer, cw, ch, kernel, size, divisor, offset, ref _convolveSource);
|
||||
}
|
||||
|
||||
public unsafe void Resize(int newWidth, int newHeight, bool linear)
|
||||
{
|
||||
EnsurePixelBuffer();
|
||||
if (_pixelBuffer is null)
|
||||
return;
|
||||
|
||||
newWidth = Math.Max(1, newWidth);
|
||||
newHeight = Math.Max(1, newHeight);
|
||||
int cw = ImageWidth;
|
||||
int ch = ImageHeight;
|
||||
|
||||
if (PixelProcessor?.TryResize(_pixelBuffer, cw, ch, newWidth, newHeight, linear, out var processed) == true && processed is not null)
|
||||
{
|
||||
ReplaceBuffer(processed, newWidth, newHeight);
|
||||
return;
|
||||
}
|
||||
|
||||
var dst = PixelBufferSoftwareProcessor.Resize(_pixelBuffer, cw, ch, newWidth, newHeight, linear, ref _resizeSource, ref _resizeBuffer);
|
||||
ReplaceBuffer(dst, newWidth, newHeight);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,11 @@
|
||||
namespace LuaScript
|
||||
{
|
||||
internal interface IPixelBufferProcessor
|
||||
{
|
||||
bool TryFill(byte[] target, int width, int height, double r, double g, double b, double a, int x, int y, int fillWidth, int fillHeight);
|
||||
|
||||
bool TryConvolve(byte[] target, int width, int height, double[] kernel, int size, double divisor, double offset);
|
||||
|
||||
bool TryResize(byte[] source, int sourceWidth, int sourceHeight, int targetWidth, int targetHeight, bool linear, out byte[]? target);
|
||||
}
|
||||
}
|
||||
@@ -37,12 +37,15 @@ namespace LuaScript.Engine
|
||||
private readonly Dictionary<string, byte[]> _stringNameBytes = new(StringComparer.Ordinal);
|
||||
private byte[] _stringValueBytes = new byte[256];
|
||||
private byte[] _sceneValueBytes = new byte[256];
|
||||
private byte[] _objectMetaBytes = new byte[256];
|
||||
|
||||
private static readonly byte[] s_shaderTransparentPixel = new byte[4];
|
||||
private readonly PixelShaderInput[] _shaderInputs = new PixelShaderInput[NativeProtocol.ShaderResourcesMax];
|
||||
private readonly byte[]?[] _shaderResourceData = new byte[NativeProtocol.ShaderResourcesMax][];
|
||||
private readonly float[] _shaderConstants = new float[NativeProtocol.ShaderConstantsMax];
|
||||
private byte[] _shaderTarget = [];
|
||||
private byte[] _pixelProcessTarget = [];
|
||||
private double[] _pixelProcessKernel = [];
|
||||
|
||||
private long PixelRegionCapacity => _allocatedSize - _pixelOffset - NativeProtocol.ShaderRegionBytes;
|
||||
|
||||
@@ -71,12 +74,16 @@ namespace LuaScript.Engine
|
||||
Func<string, string, double, bool, bool, int, (byte[] buffer, int w, int h)> loadText,
|
||||
Func<string, (byte[] buffer, int w, int h)> loadImage,
|
||||
Func<string, double, (byte[] buffer, int w, int h)> loadMovie,
|
||||
Func<string, double, (byte[] buffer, int w, int h)> loadScene,
|
||||
Func<string, double, double, IReadOnlyList<KeyValuePair<string, object>>, (byte[] buffer, int w, int h)> loadBrush,
|
||||
Action<string, IReadOnlyList<KeyValuePair<string, object>>> addEffect,
|
||||
Action<DrawCommand> addDraw,
|
||||
Action<string, int, bool, int, double[]> setAnchor,
|
||||
Func<string, SceneValue> sceneGetValue,
|
||||
Action<string, SceneValue> sceneSetValue,
|
||||
Func<string, string, int, (int Count, int Rate, double[] Data)> loadAudio,
|
||||
PixelShaderInvoke? runPixelShader,
|
||||
IPixelBufferProcessor? pixelProcessor,
|
||||
out bool pixelsDirty,
|
||||
out bool bufferReplaced,
|
||||
out int resultWidth,
|
||||
@@ -120,16 +127,18 @@ namespace LuaScript.Engine
|
||||
view.Write(NativeProtocol.OffScriptVersion, _scriptVersion);
|
||||
view.Write(NativeProtocol.OffPixelsDirty, 0);
|
||||
view.Write(NativeProtocol.OffErrorLen, 0);
|
||||
view.Write(NativeProtocol.OffCallbackFound, pixelProcessor is null ? -1 : 1);
|
||||
view.Write(NativeProtocol.OffStatus, NativeProtocol.StatusIdle);
|
||||
view.Write(NativeProtocol.OffCommand, NativeProtocol.CmdRun);
|
||||
|
||||
_workEvent!.Set();
|
||||
|
||||
var stopwatch = Stopwatch.StartNew();
|
||||
long budget = timeoutMs;
|
||||
int status;
|
||||
while (true)
|
||||
{
|
||||
long remaining = timeoutMs - stopwatch.ElapsedMilliseconds;
|
||||
long remaining = budget - stopwatch.ElapsedMilliseconds;
|
||||
if (remaining <= 0 || !_doneEvent!.WaitOne((int)remaining))
|
||||
{
|
||||
KillWorker();
|
||||
@@ -141,6 +150,7 @@ namespace LuaScript.Engine
|
||||
if (status != NativeProtocol.StatusCallback)
|
||||
break;
|
||||
|
||||
long callbackStart = stopwatch.ElapsedMilliseconds;
|
||||
int callbackKind = view.ReadInt32(NativeProtocol.OffCallbackKind);
|
||||
if (callbackKind == NativeProtocol.CbKindRequestPixels)
|
||||
{
|
||||
@@ -160,8 +170,9 @@ namespace LuaScript.Engine
|
||||
}
|
||||
else
|
||||
{
|
||||
DispatchCallback(view, resolveObject, loadFigure, loadText, loadImage, loadMovie, addEffect, setAnchor, sceneGetValue, sceneSetValue, runPixelShader);
|
||||
DispatchCallback(view, resolveObject, loadFigure, loadText, loadImage, loadMovie, loadScene, loadBrush, addEffect, setAnchor, sceneGetValue, sceneSetValue, loadAudio, runPixelShader, pixelProcessor);
|
||||
}
|
||||
budget += stopwatch.ElapsedMilliseconds - callbackStart;
|
||||
_workEvent.Set();
|
||||
}
|
||||
|
||||
@@ -321,11 +332,15 @@ namespace LuaScript.Engine
|
||||
Func<string, string, double, bool, bool, int, (byte[] buffer, int w, int h)> loadText,
|
||||
Func<string, (byte[] buffer, int w, int h)> loadImage,
|
||||
Func<string, double, (byte[] buffer, int w, int h)> loadMovie,
|
||||
Func<string, double, (byte[] buffer, int w, int h)> loadScene,
|
||||
Func<string, double, double, IReadOnlyList<KeyValuePair<string, object>>, (byte[] buffer, int w, int h)> loadBrush,
|
||||
Action<string, IReadOnlyList<KeyValuePair<string, object>>> addEffect,
|
||||
Action<string, int, bool, int, double[]> setAnchor,
|
||||
Func<string, SceneValue> sceneGetValue,
|
||||
Action<string, SceneValue> sceneSetValue,
|
||||
PixelShaderInvoke? runPixelShader)
|
||||
Func<string, string, int, (int Count, int Rate, double[] Data)> loadAudio,
|
||||
PixelShaderInvoke? runPixelShader,
|
||||
IPixelBufferProcessor? pixelProcessor)
|
||||
{
|
||||
int kind = view.ReadInt32(NativeProtocol.OffCallbackKind);
|
||||
switch (kind)
|
||||
@@ -345,6 +360,15 @@ namespace LuaScript.Engine
|
||||
case NativeProtocol.CbKindLoadMovie:
|
||||
ResolveLoadMovieCallback(view, loadMovie);
|
||||
break;
|
||||
case NativeProtocol.CbKindLoadScene:
|
||||
ResolveLoadSceneCallback(view, loadScene);
|
||||
break;
|
||||
case NativeProtocol.CbKindLoadBrush:
|
||||
ResolveLoadBrushCallback(view, loadBrush);
|
||||
break;
|
||||
case NativeProtocol.CbKindBrush:
|
||||
ResolveBrushCallback(view, loadBrush);
|
||||
break;
|
||||
case NativeProtocol.CbKindEffect:
|
||||
ResolveEffectCallback(view, addEffect);
|
||||
break;
|
||||
@@ -357,15 +381,109 @@ namespace LuaScript.Engine
|
||||
case NativeProtocol.CbKindSceneSet:
|
||||
ResolveSceneSetCallback(view, sceneSetValue);
|
||||
break;
|
||||
case NativeProtocol.CbKindGetAudio:
|
||||
ResolveGetAudioCallback(view, loadAudio);
|
||||
break;
|
||||
case NativeProtocol.CbKindPixelShaderStage:
|
||||
ResolveShaderStageCallback(view);
|
||||
break;
|
||||
case NativeProtocol.CbKindPixelShaderRun:
|
||||
ResolveShaderRunCallback(view, runPixelShader);
|
||||
break;
|
||||
case NativeProtocol.CbKindPixelProcess:
|
||||
ResolvePixelProcessCallback(view, pixelProcessor);
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
private void ResolvePixelProcessCallback(MemoryMappedViewAccessor view, IPixelBufferProcessor? pixelProcessor)
|
||||
{
|
||||
bool processed = false;
|
||||
if (pixelProcessor is not null)
|
||||
{
|
||||
int width = view.ReadInt32(NativeProtocol.OffWidth);
|
||||
int height = view.ReadInt32(NativeProtocol.OffHeight);
|
||||
long length = (long)width * height * 4;
|
||||
if (width > 0 && height > 0 && length <= PixelRegionCapacity && length <= int.MaxValue)
|
||||
{
|
||||
int pixelLength = (int)length;
|
||||
if (_pixelProcessTarget.Length < pixelLength)
|
||||
_pixelProcessTarget = new byte[pixelLength];
|
||||
|
||||
int operation = (int)view.ReadDouble(NativeProtocol.CallbackResultOffset);
|
||||
processed = operation switch
|
||||
{
|
||||
NativeProtocol.PixelProcessFill => TryProcessFill(view, pixelProcessor, width, height, pixelLength),
|
||||
NativeProtocol.PixelProcessConvolve => TryProcessConvolve(view, pixelProcessor, width, height, pixelLength),
|
||||
NativeProtocol.PixelProcessResize => TryProcessResize(view, pixelProcessor, pixelLength),
|
||||
_ => false,
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
view.Write(NativeProtocol.OffCallbackFound, processed ? 1 : pixelProcessor is null ? -1 : 0);
|
||||
}
|
||||
|
||||
private bool TryProcessFill(MemoryMappedViewAccessor view, IPixelBufferProcessor pixelProcessor, int width, int height, int pixelLength)
|
||||
{
|
||||
long offset = NativeProtocol.CallbackResultOffset;
|
||||
double r = view.ReadDouble(offset + 1 * 8);
|
||||
double g = view.ReadDouble(offset + 2 * 8);
|
||||
double b = view.ReadDouble(offset + 3 * 8);
|
||||
double a = view.ReadDouble(offset + 4 * 8);
|
||||
int x = (int)view.ReadDouble(offset + 5 * 8);
|
||||
int y = (int)view.ReadDouble(offset + 6 * 8);
|
||||
int fillWidth = (int)view.ReadDouble(offset + 7 * 8);
|
||||
int fillHeight = (int)view.ReadDouble(offset + 8 * 8);
|
||||
if (x != 0 || y != 0 || fillWidth != width || fillHeight != height)
|
||||
ReadRegion(_pixelOffset, _pixelProcessTarget, pixelLength);
|
||||
if (!pixelProcessor.TryFill(_pixelProcessTarget, width, height, r, g, b, a, x, y, fillWidth, fillHeight))
|
||||
return false;
|
||||
WriteRegion(_pixelOffset, _pixelProcessTarget, pixelLength);
|
||||
return true;
|
||||
}
|
||||
|
||||
private bool TryProcessConvolve(MemoryMappedViewAccessor view, IPixelBufferProcessor pixelProcessor, int width, int height, int pixelLength)
|
||||
{
|
||||
long offset = NativeProtocol.CallbackResultOffset;
|
||||
int size = (int)view.ReadDouble(offset + 1 * 8);
|
||||
double divisor = view.ReadDouble(offset + 2 * 8);
|
||||
double kernelOffset = view.ReadDouble(offset + 3 * 8);
|
||||
if (size < 1 || (size & 1) == 0)
|
||||
return false;
|
||||
int taps = size * size;
|
||||
if (taps <= 0 || taps * 8 > Math.Clamp(view.ReadInt32(NativeProtocol.OffCallbackTagLen), 0, NativeProtocol.CallbackTagMax))
|
||||
return false;
|
||||
if (_pixelProcessKernel.Length < taps)
|
||||
_pixelProcessKernel = new double[taps];
|
||||
ReadRegion(_pixelOffset, _pixelProcessTarget, pixelLength);
|
||||
view.ReadArray(NativeProtocol.CallbackTagOffset, _pixelProcessKernel, 0, taps);
|
||||
if (!pixelProcessor.TryConvolve(_pixelProcessTarget, width, height, _pixelProcessKernel, size, divisor, kernelOffset))
|
||||
return false;
|
||||
WriteRegion(_pixelOffset, _pixelProcessTarget, pixelLength);
|
||||
return true;
|
||||
}
|
||||
|
||||
private bool TryProcessResize(MemoryMappedViewAccessor view, IPixelBufferProcessor pixelProcessor, int sourceLength)
|
||||
{
|
||||
long offset = NativeProtocol.CallbackResultOffset;
|
||||
int targetWidth = (int)view.ReadDouble(offset + 1 * 8);
|
||||
int targetHeight = (int)view.ReadDouble(offset + 2 * 8);
|
||||
bool linear = view.ReadDouble(offset + 3 * 8) != 0d;
|
||||
long length = (long)targetWidth * targetHeight * 4;
|
||||
int sourceWidth = view.ReadInt32(NativeProtocol.OffWidth);
|
||||
int sourceHeight = view.ReadInt32(NativeProtocol.OffHeight);
|
||||
if (targetWidth <= 0 || targetHeight <= 0 || length > PixelRegionCapacity || length > int.MaxValue)
|
||||
return false;
|
||||
ReadRegion(_pixelOffset, _pixelProcessTarget, sourceLength);
|
||||
if (!pixelProcessor.TryResize(_pixelProcessTarget, sourceWidth, sourceHeight, targetWidth, targetHeight, linear, out var target) || target is null)
|
||||
return false;
|
||||
WriteRegion(_pixelOffset, target, (int)length);
|
||||
view.Write(NativeProtocol.OffWidth, targetWidth);
|
||||
view.Write(NativeProtocol.OffHeight, targetHeight);
|
||||
return true;
|
||||
}
|
||||
|
||||
private void ResolveShaderStageCallback(MemoryMappedViewAccessor view)
|
||||
{
|
||||
long meta = NativeProtocol.ShaderMetaOffset(_allocatedSize);
|
||||
@@ -557,6 +675,40 @@ namespace LuaScript.Engine
|
||||
view.Write(NativeProtocol.OffCallbackFound, 1);
|
||||
}
|
||||
|
||||
private static readonly double[] s_noAudioData = [];
|
||||
|
||||
private void ResolveGetAudioCallback(
|
||||
MemoryMappedViewAccessor view,
|
||||
Func<string, string, int, (int Count, int Rate, double[] Data)> loadAudio)
|
||||
{
|
||||
int tagLen = Math.Clamp(view.ReadInt32(NativeProtocol.OffCallbackTagLen), 0, NativeProtocol.CallbackTagMax);
|
||||
view.ReadArray(NativeProtocol.CallbackTagOffset, _callbackTag, 0, tagLen);
|
||||
int separator = Array.IndexOf(_callbackTag, (byte)0, 0, tagLen);
|
||||
string file = Encoding.UTF8.GetString(_callbackTag, 0, separator >= 0 ? separator : tagLen);
|
||||
string type = separator >= 0
|
||||
? Encoding.UTF8.GetString(_callbackTag, separator + 1, tagLen - separator - 1)
|
||||
: "pcm";
|
||||
int size = (int)view.ReadDouble(NativeProtocol.CallbackResultOffset);
|
||||
|
||||
int count = 0;
|
||||
int rate = 0;
|
||||
double[] data = s_noAudioData;
|
||||
try { (count, rate, data) = loadAudio(file, type, size); }
|
||||
catch
|
||||
{
|
||||
count = 0;
|
||||
rate = 0;
|
||||
data = s_noAudioData;
|
||||
}
|
||||
|
||||
count = Math.Clamp(count, 0, Math.Min(data.Length, NativeProtocol.CallbackTagMax / 8));
|
||||
if (count > 0)
|
||||
view.WriteArray(NativeProtocol.CallbackTagOffset, data, 0, count);
|
||||
view.Write(NativeProtocol.CallbackResultOffset, (double)count);
|
||||
view.Write(NativeProtocol.CallbackResultOffset + 8, (double)rate);
|
||||
view.Write(NativeProtocol.OffCallbackFound, 1);
|
||||
}
|
||||
|
||||
private void ResolveSetAnchorCallback(MemoryMappedViewAccessor view, Action<string, int, bool, int, double[]> setAnchor)
|
||||
{
|
||||
int tagLen = Math.Clamp(view.ReadInt32(NativeProtocol.OffCallbackTagLen), 0, NativeProtocol.CallbackTagMax);
|
||||
@@ -644,6 +796,9 @@ namespace LuaScript.Engine
|
||||
view.Write(result + NativeProtocol.CbRz * 8, value.Rz);
|
||||
view.Write(result + NativeProtocol.CbAlpha * 8, value.Alpha);
|
||||
view.Write(result + NativeProtocol.CbLayer * 8, (double)value.Layer);
|
||||
view.Write(result + NativeProtocol.CbVolume * 8, value.Volume);
|
||||
view.Write(result + NativeProtocol.CbLength * 8, (double)value.Length);
|
||||
WriteObjectMeta(view, value.Character, value.Text, value.Kind);
|
||||
view.Write(NativeProtocol.OffCallbackFound, 1);
|
||||
}
|
||||
else
|
||||
@@ -652,6 +807,27 @@ namespace LuaScript.Engine
|
||||
}
|
||||
}
|
||||
|
||||
private void WriteObjectMeta(MemoryMappedViewAccessor view, string character, string text, string kind)
|
||||
{
|
||||
character ??= string.Empty;
|
||||
text ??= string.Empty;
|
||||
kind ??= string.Empty;
|
||||
int maxBytes = Encoding.UTF8.GetMaxByteCount(character.Length + text.Length + kind.Length) + 2;
|
||||
if (_objectMetaBytes.Length < maxBytes)
|
||||
_objectMetaBytes = new byte[Math.Max(maxBytes, _objectMetaBytes.Length * 2)];
|
||||
|
||||
int length = Encoding.UTF8.GetBytes(character, 0, character.Length, _objectMetaBytes, 0);
|
||||
_objectMetaBytes[length++] = 0;
|
||||
length += Encoding.UTF8.GetBytes(text, 0, text.Length, _objectMetaBytes, length);
|
||||
_objectMetaBytes[length++] = 0;
|
||||
length += Encoding.UTF8.GetBytes(kind, 0, kind.Length, _objectMetaBytes, length);
|
||||
if (length > NativeProtocol.CallbackTagMax)
|
||||
length = NativeProtocol.CallbackTagMax;
|
||||
|
||||
view.WriteArray(NativeProtocol.CallbackTagOffset, _objectMetaBytes, 0, length);
|
||||
view.Write(NativeProtocol.OffCallbackTagLen, length);
|
||||
}
|
||||
|
||||
private void ResolveLoadFigureCallback(
|
||||
MemoryMappedViewAccessor view,
|
||||
Func<string, int, double, double, double, (byte[] buffer, int w, int h)> loadFigure)
|
||||
@@ -772,16 +948,100 @@ namespace LuaScript.Engine
|
||||
view.Write(NativeProtocol.OffCallbackFound, 1);
|
||||
}
|
||||
|
||||
private void ResolveEffectCallback(MemoryMappedViewAccessor view, Action<string, IReadOnlyList<KeyValuePair<string, object>>> addEffect)
|
||||
private void ResolveLoadSceneCallback(
|
||||
MemoryMappedViewAccessor view,
|
||||
Func<string, double, (byte[] buffer, int w, int h)> loadScene)
|
||||
{
|
||||
int tagLen = Math.Clamp(view.ReadInt32(NativeProtocol.OffCallbackTagLen), 0, NativeProtocol.CallbackTagMax);
|
||||
view.ReadArray(NativeProtocol.CallbackTagOffset, _callbackTag, 0, tagLen);
|
||||
string name = Encoding.UTF8.GetString(_callbackTag, 0, tagLen);
|
||||
double time = view.ReadDouble(NativeProtocol.CallbackResultOffset);
|
||||
|
||||
(byte[] buffer, int w, int h) result;
|
||||
try { result = loadScene(name, time); }
|
||||
catch { result = ([], 0, 0); }
|
||||
|
||||
long pixelSize = (long)result.w * result.h * 4;
|
||||
if (result.w <= 0 || result.h <= 0 || pixelSize > PixelRegionCapacity)
|
||||
{
|
||||
view.Write(NativeProtocol.OffLoadResultWidth, 0);
|
||||
view.Write(NativeProtocol.OffLoadResultHeight, 0);
|
||||
view.Write(NativeProtocol.OffCallbackFound, 0);
|
||||
return;
|
||||
}
|
||||
|
||||
view.Write(NativeProtocol.OffLoadResultWidth, result.w);
|
||||
view.Write(NativeProtocol.OffLoadResultHeight, result.h);
|
||||
WritePixelRegion(result.buffer, (int)pixelSize);
|
||||
view.Write(NativeProtocol.OffCallbackFound, 1);
|
||||
}
|
||||
|
||||
private static readonly KeyValuePair<string, object>[] s_noBrushArguments = [];
|
||||
|
||||
private void ResolveLoadBrushCallback(
|
||||
MemoryMappedViewAccessor view,
|
||||
Func<string, double, double, IReadOnlyList<KeyValuePair<string, object>>, (byte[] buffer, int w, int h)> loadBrush)
|
||||
{
|
||||
int tagLen = Math.Clamp(view.ReadInt32(NativeProtocol.OffCallbackTagLen), 0, NativeProtocol.CallbackTagMax);
|
||||
view.ReadArray(NativeProtocol.CallbackTagOffset, _callbackTag, 0, tagLen);
|
||||
string name = Encoding.UTF8.GetString(_callbackTag, 0, tagLen);
|
||||
|
||||
WriteBrushResult(view, loadBrush, name, s_noBrushArguments);
|
||||
}
|
||||
|
||||
private void ResolveBrushCallback(
|
||||
MemoryMappedViewAccessor view,
|
||||
Func<string, double, double, IReadOnlyList<KeyValuePair<string, object>>, (byte[] buffer, int w, int h)> loadBrush)
|
||||
{
|
||||
int tagLen = Math.Clamp(view.ReadInt32(NativeProtocol.OffCallbackTagLen), 0, NativeProtocol.CallbackTagMax);
|
||||
view.ReadArray(NativeProtocol.CallbackTagOffset, _callbackTag, 0, tagLen);
|
||||
|
||||
var segments = Encoding.UTF8.GetString(_callbackTag, 0, tagLen).Split('\0');
|
||||
if (segments.Length == 0)
|
||||
{
|
||||
view.Write(NativeProtocol.OffLoadResultWidth, 0);
|
||||
view.Write(NativeProtocol.OffLoadResultHeight, 0);
|
||||
view.Write(NativeProtocol.OffCallbackFound, 0);
|
||||
return;
|
||||
}
|
||||
|
||||
WriteBrushResult(view, loadBrush, segments[0], ParseNamedArguments(segments));
|
||||
}
|
||||
|
||||
private void WriteBrushResult(
|
||||
MemoryMappedViewAccessor view,
|
||||
Func<string, double, double, IReadOnlyList<KeyValuePair<string, object>>, (byte[] buffer, int w, int h)> loadBrush,
|
||||
string name,
|
||||
IReadOnlyList<KeyValuePair<string, object>> arguments)
|
||||
{
|
||||
long rOff = NativeProtocol.CallbackResultOffset;
|
||||
double width = view.ReadDouble(rOff + 0 * 8);
|
||||
double height = view.ReadDouble(rOff + 1 * 8);
|
||||
|
||||
(byte[] buffer, int w, int h) result;
|
||||
try { result = loadBrush(name, width, height, arguments); }
|
||||
catch { result = ([], 0, 0); }
|
||||
|
||||
long pixelSize = (long)result.w * result.h * 4;
|
||||
if (result.w <= 0 || result.h <= 0 || pixelSize > PixelRegionCapacity)
|
||||
{
|
||||
view.Write(NativeProtocol.OffLoadResultWidth, 0);
|
||||
view.Write(NativeProtocol.OffLoadResultHeight, 0);
|
||||
view.Write(NativeProtocol.OffCallbackFound, 0);
|
||||
return;
|
||||
}
|
||||
|
||||
view.Write(NativeProtocol.OffLoadResultWidth, result.w);
|
||||
view.Write(NativeProtocol.OffLoadResultHeight, result.h);
|
||||
WritePixelRegion(result.buffer, (int)pixelSize);
|
||||
view.Write(NativeProtocol.OffCallbackFound, 1);
|
||||
}
|
||||
|
||||
private static IReadOnlyList<KeyValuePair<string, object>> ParseNamedArguments(string[] segments)
|
||||
{
|
||||
if (segments.Length < 3)
|
||||
return s_noBrushArguments;
|
||||
|
||||
string effectName = segments[0];
|
||||
var arguments = new List<KeyValuePair<string, object>>();
|
||||
for (int i = 1; i + 1 < segments.Length; i += 2)
|
||||
{
|
||||
@@ -798,8 +1058,19 @@ namespace LuaScript.Engine
|
||||
value = raw;
|
||||
arguments.Add(new KeyValuePair<string, object>(key, value));
|
||||
}
|
||||
return arguments;
|
||||
}
|
||||
|
||||
try { addEffect(effectName, arguments); }
|
||||
private void ResolveEffectCallback(MemoryMappedViewAccessor view, Action<string, IReadOnlyList<KeyValuePair<string, object>>> addEffect)
|
||||
{
|
||||
int tagLen = Math.Clamp(view.ReadInt32(NativeProtocol.OffCallbackTagLen), 0, NativeProtocol.CallbackTagMax);
|
||||
view.ReadArray(NativeProtocol.CallbackTagOffset, _callbackTag, 0, tagLen);
|
||||
|
||||
var segments = Encoding.UTF8.GetString(_callbackTag, 0, tagLen).Split('\0');
|
||||
if (segments.Length == 0)
|
||||
return;
|
||||
|
||||
try { addEffect(segments[0], ParseNamedArguments(segments)); }
|
||||
catch { }
|
||||
view.Write(NativeProtocol.OffCallbackFound, 1);
|
||||
}
|
||||
|
||||
@@ -181,9 +181,17 @@ namespace LuaScript
|
||||
script.AttachDebugger(_debugger);
|
||||
_globalRegistrar = new AviUtlGlobalRegistrar(CurrentTimeRatio);
|
||||
_globalRegistrar.RegisterLuaMembers(script.Globals);
|
||||
RegisterFastPrimitives(script);
|
||||
_script = script;
|
||||
}
|
||||
|
||||
private void RegisterFastPrimitives(Script script)
|
||||
{
|
||||
script.Globals.Set("__fast_fill", DynValue.NewCallback((_, args) => FillCore(args)));
|
||||
script.Globals.Set("__fast_convolve", DynValue.NewCallback((_, args) => ConvolveCore(args)));
|
||||
script.Globals.Set("__fast_resize", DynValue.NewCallback((_, args) => ResizeCore(args)));
|
||||
}
|
||||
|
||||
private void EnsureScriptIntegrity()
|
||||
{
|
||||
if (_script is null) return;
|
||||
@@ -548,6 +556,18 @@ namespace LuaScript
|
||||
args[1].String,
|
||||
args.Count > 2 ? args[2].CastToNumber() ?? _activeContext.Time : _activeContext.Time);
|
||||
break;
|
||||
case "scene" when args.Count > 1 && args[1].Type == DataType.String:
|
||||
LoadScene(
|
||||
args[1].String,
|
||||
args.Count > 2 ? args[2].CastToNumber() ?? _activeContext.Time : _activeContext.Time);
|
||||
break;
|
||||
case "brush" when args.Count > 1 && args[1].Type == DataType.String:
|
||||
LoadBrush(
|
||||
args[1].String,
|
||||
args.Count > 2 ? args[2].CastToNumber() ?? 0d : 0d,
|
||||
args.Count > 3 ? args[3].CastToNumber() ?? 0d : 0d,
|
||||
s_noNamedArguments);
|
||||
break;
|
||||
}
|
||||
return DynValue.Void;
|
||||
}
|
||||
@@ -771,6 +791,47 @@ namespace LuaScript
|
||||
return value.Type == DataType.Number ? value : DynValue.NewNumber(0d);
|
||||
}
|
||||
|
||||
private static readonly double[] s_noAudioData = [];
|
||||
|
||||
[LuaFunction("getaudio")]
|
||||
private DynValue GetAudio(CallbackArguments args)
|
||||
{
|
||||
_activeCancellation.ThrowIfCancellationRequested();
|
||||
if (_activeContext is null || _script is null || args.Count < 2 || args[1].Type != DataType.String)
|
||||
return DynValue.NewTuple(DynValue.NewNumber(0d), DynValue.NewNumber(0d));
|
||||
|
||||
string file = args[1].String;
|
||||
string type = args.Count > 2 && args[2].Type == DataType.String ? args[2].String : "pcm";
|
||||
int size = args.Count > 3 ? (int)(args[3].CastToNumber() ?? 0d) : 0;
|
||||
|
||||
int count = 0;
|
||||
int rate = 0;
|
||||
double[] data = s_noAudioData;
|
||||
var loader = _activeContext.AudioLoader;
|
||||
if (loader is not null)
|
||||
(count, rate, data) = loader(file, type, size);
|
||||
if (count > data.Length)
|
||||
count = data.Length;
|
||||
|
||||
var bufArg = args[0];
|
||||
Table? table = bufArg.Type == DataType.Table ? bufArg.Table : null;
|
||||
bool created = false;
|
||||
if (table is null && bufArg.IsNil())
|
||||
{
|
||||
table = new Table(_script);
|
||||
created = true;
|
||||
}
|
||||
if (table is not null)
|
||||
{
|
||||
for (int i = 0; i < count; i++)
|
||||
table.Set(i + 1, DynValue.NewNumber(data[i]));
|
||||
}
|
||||
|
||||
return created
|
||||
? DynValue.NewTuple(DynValue.NewNumber(count), DynValue.NewNumber(rate), DynValue.NewTable(table!))
|
||||
: DynValue.NewTuple(DynValue.NewNumber(count), DynValue.NewNumber(rate));
|
||||
}
|
||||
|
||||
[LuaFunction("setoption")]
|
||||
private DynValue SetOption(CallbackArguments args)
|
||||
{
|
||||
@@ -828,9 +889,7 @@ namespace LuaScript
|
||||
return DynValue.NewNumber(0d);
|
||||
|
||||
var anchorName = args[0].String;
|
||||
int count = AnchorSupport.ClampCount((int)(args[1].CastToNumber() ?? 0d));
|
||||
if (string.Equals(anchorName, AnchorSupport.TrackGroup, StringComparison.Ordinal))
|
||||
return DynValue.NewNumber(0d);
|
||||
int count = AnchorSupport.NormalizeCount(anchorName, (int)(args[1].CastToNumber() ?? 0d));
|
||||
|
||||
var connection = AnchorConnection.None;
|
||||
bool is3D = false;
|
||||
@@ -864,9 +923,19 @@ namespace LuaScript
|
||||
if (_activeContext is null || args.Count == 0 || args[0].Type != DataType.String)
|
||||
return DynValue.Void;
|
||||
|
||||
string name = args[0].String;
|
||||
_activeContext.AddEffect(new AviUtlEffectRequest(args[0].String, CollectNamedArguments(args, 1)));
|
||||
return DynValue.Void;
|
||||
}
|
||||
|
||||
private static readonly KeyValuePair<string, object>[] s_noNamedArguments = [];
|
||||
|
||||
private static IReadOnlyList<KeyValuePair<string, object>> CollectNamedArguments(CallbackArguments args, int start)
|
||||
{
|
||||
if (start + 1 >= args.Count)
|
||||
return s_noNamedArguments;
|
||||
|
||||
var arguments = new List<KeyValuePair<string, object>>();
|
||||
for (int i = 1; i + 1 < args.Count; i += 2)
|
||||
for (int i = start; i + 1 < args.Count; i += 2)
|
||||
{
|
||||
if (args[i].Type != DataType.String)
|
||||
continue;
|
||||
@@ -880,8 +949,27 @@ namespace LuaScript
|
||||
};
|
||||
arguments.Add(new KeyValuePair<string, object>(args[i].String, boxed));
|
||||
}
|
||||
return arguments;
|
||||
}
|
||||
|
||||
_activeContext.AddEffect(new AviUtlEffectRequest(name, arguments));
|
||||
[LuaFunction("brush")]
|
||||
private DynValue Brush(CallbackArguments args)
|
||||
{
|
||||
_activeCancellation.ThrowIfCancellationRequested();
|
||||
if (_activeContext is null || args.Count == 0 || args[0].Type != DataType.String)
|
||||
return DynValue.Void;
|
||||
|
||||
int start = 1;
|
||||
double width = 0d;
|
||||
double height = 0d;
|
||||
if (args.Count > 2 && args[1].Type == DataType.Number && args[2].Type == DataType.Number)
|
||||
{
|
||||
width = args[1].Number;
|
||||
height = args[2].Number;
|
||||
start = 3;
|
||||
}
|
||||
|
||||
LoadBrush(args[0].String, width, height, CollectNamedArguments(args, start));
|
||||
return DynValue.Void;
|
||||
}
|
||||
|
||||
@@ -907,6 +995,150 @@ namespace LuaScript
|
||||
};
|
||||
}
|
||||
|
||||
private double[] _regionScratch = [];
|
||||
private double[] _kernelScratch = [];
|
||||
|
||||
private static readonly DynValue[] s_byteNumbers = CreateByteNumbers();
|
||||
|
||||
private static DynValue[] CreateByteNumbers()
|
||||
{
|
||||
var values = new DynValue[256];
|
||||
for (int i = 0; i < values.Length; i++)
|
||||
values[i] = DynValue.NewNumber(i).AsReadOnly();
|
||||
return values;
|
||||
}
|
||||
|
||||
private static DynValue ChannelValue(double value)
|
||||
{
|
||||
int b = (int)value;
|
||||
return b == value && (uint)b < 256u ? s_byteNumbers[b] : DynValue.NewNumber(value);
|
||||
}
|
||||
|
||||
[LuaFunction("fill")]
|
||||
private DynValue Fill(CallbackArguments args) => FillCore(args);
|
||||
|
||||
private DynValue FillCore(CallbackArguments args)
|
||||
{
|
||||
_activeCancellation.ThrowIfCancellationRequested();
|
||||
if (_activeContext is null)
|
||||
return DynValue.Void;
|
||||
|
||||
var ctx = _activeContext;
|
||||
double r = args.Count > 0 ? args[0].CastToNumber() ?? 0d : 0d;
|
||||
double g = args.Count > 1 ? args[1].CastToNumber() ?? 0d : 0d;
|
||||
double b = args.Count > 2 ? args[2].CastToNumber() ?? 0d : 0d;
|
||||
double a = args.Count > 3 ? args[3].CastToNumber() ?? 255d : 255d;
|
||||
int x = args.Count > 4 ? (int)(args[4].CastToNumber() ?? 0d) : 0;
|
||||
int y = args.Count > 5 ? (int)(args[5].CastToNumber() ?? 0d) : 0;
|
||||
int w = args.Count > 6 ? (int)(args[6].CastToNumber() ?? 0d) : ctx.ImageWidth;
|
||||
int h = args.Count > 7 ? (int)(args[7].CastToNumber() ?? 0d) : ctx.ImageHeight;
|
||||
|
||||
ctx.FillBuffer(r, g, b, a, x, y, w, h);
|
||||
return DynValue.Void;
|
||||
}
|
||||
|
||||
[LuaFunction("getpixelregion")]
|
||||
private DynValue GetPixelRegion(CallbackArguments args)
|
||||
{
|
||||
_activeCancellation.ThrowIfCancellationRequested();
|
||||
if (_activeContext is null || _script is null || args.Count < 4)
|
||||
return DynValue.Nil;
|
||||
|
||||
int x = (int)(args[0].CastToNumber() ?? 0d);
|
||||
int y = (int)(args[1].CastToNumber() ?? 0d);
|
||||
int w = (int)(args[2].CastToNumber() ?? 0d);
|
||||
int h = (int)(args[3].CastToNumber() ?? 0d);
|
||||
var table = new Table(_script);
|
||||
if (w <= 0 || h <= 0)
|
||||
return DynValue.NewTable(table);
|
||||
|
||||
int count = w * h * 4;
|
||||
if (_regionScratch.Length < count)
|
||||
_regionScratch = new double[count];
|
||||
_activeContext.ReadRegion(x, y, w, h, _regionScratch);
|
||||
for (int i = 0; i < count; i++)
|
||||
table.Set(i + 1, ChannelValue(_regionScratch[i]));
|
||||
return DynValue.NewTable(table);
|
||||
}
|
||||
|
||||
[LuaFunction("putpixelregion")]
|
||||
private DynValue PutPixelRegion(CallbackArguments args)
|
||||
{
|
||||
_activeCancellation.ThrowIfCancellationRequested();
|
||||
if (_activeContext is null || args.Count < 5 || args[4].Type != DataType.Table)
|
||||
return DynValue.Void;
|
||||
|
||||
int x = (int)(args[0].CastToNumber() ?? 0d);
|
||||
int y = (int)(args[1].CastToNumber() ?? 0d);
|
||||
int w = (int)(args[2].CastToNumber() ?? 0d);
|
||||
int h = (int)(args[3].CastToNumber() ?? 0d);
|
||||
if (w <= 0 || h <= 0)
|
||||
return DynValue.Void;
|
||||
|
||||
int count = w * h * 4;
|
||||
if (_regionScratch.Length < count)
|
||||
_regionScratch = new double[count];
|
||||
var table = args[4].Table;
|
||||
for (int i = 0; i < count; i++)
|
||||
_regionScratch[i] = table.Get(i + 1).CastToNumber() ?? 0d;
|
||||
_activeContext.WriteRegion(x, y, w, h, _regionScratch);
|
||||
return DynValue.Void;
|
||||
}
|
||||
|
||||
[LuaFunction("convolve")]
|
||||
private DynValue Convolve(CallbackArguments args) => ConvolveCore(args);
|
||||
|
||||
private DynValue ConvolveCore(CallbackArguments args)
|
||||
{
|
||||
_activeCancellation.ThrowIfCancellationRequested();
|
||||
if (_activeContext is null || args.Count < 2 || args[0].Type != DataType.Table)
|
||||
return DynValue.Void;
|
||||
|
||||
int size = (int)(args[1].CastToNumber() ?? 0d);
|
||||
if (size < 1 || (size & 1) == 0)
|
||||
return DynValue.Void;
|
||||
|
||||
int taps = size * size;
|
||||
var kernel = args[0].Table;
|
||||
if (_kernelScratch.Length < taps)
|
||||
_kernelScratch = new double[taps];
|
||||
double sum = 0d;
|
||||
for (int i = 0; i < taps; i++)
|
||||
{
|
||||
double v = kernel.Get(i + 1).CastToNumber() ?? 0d;
|
||||
_kernelScratch[i] = v;
|
||||
sum += v;
|
||||
}
|
||||
|
||||
double divisor = args.Count > 2 ? args[2].CastToNumber() ?? sum : sum;
|
||||
if (divisor == 0d)
|
||||
divisor = 1d;
|
||||
double offset = args.Count > 3 ? args[3].CastToNumber() ?? 0d : 0d;
|
||||
|
||||
_activeContext.Convolve(_kernelScratch, size, divisor, offset);
|
||||
return DynValue.Void;
|
||||
}
|
||||
|
||||
[LuaFunction("resize")]
|
||||
private DynValue Resize(CallbackArguments args) => ResizeCore(args);
|
||||
|
||||
private DynValue ResizeCore(CallbackArguments args)
|
||||
{
|
||||
_activeCancellation.ThrowIfCancellationRequested();
|
||||
if (_activeContext is null || args.Count < 2)
|
||||
return DynValue.Void;
|
||||
|
||||
int w = (int)(args[0].CastToNumber() ?? 0d);
|
||||
int h = (int)(args[1].CastToNumber() ?? 0d);
|
||||
if (w <= 0 || h <= 0)
|
||||
return DynValue.Void;
|
||||
|
||||
bool linear = !(args.Count > 2 && args[2].Type == DataType.String && args[2].String == "nearest");
|
||||
_activeContext.Resize(w, h, linear);
|
||||
RefreshObjDimensions();
|
||||
return DynValue.Void;
|
||||
}
|
||||
|
||||
private double CurrentAntialias() =>
|
||||
_options.TryGetValue("antialias", out var value) && value.Type == DataType.Number
|
||||
? value.Number
|
||||
@@ -949,6 +1181,34 @@ namespace LuaScript
|
||||
RefreshObjDimensions();
|
||||
}
|
||||
|
||||
private void LoadScene(string name, double time)
|
||||
{
|
||||
var ctx = _activeContext!;
|
||||
var loader = ctx.SceneImageLoader;
|
||||
if (loader is null)
|
||||
return;
|
||||
var (buffer, w, h) = loader(name, time);
|
||||
if (w <= 0 || h <= 0)
|
||||
return;
|
||||
ctx.ReplaceBuffer(buffer, w, h);
|
||||
RefreshObjDimensions();
|
||||
}
|
||||
|
||||
private void LoadBrush(string name, double width, double height, IReadOnlyList<KeyValuePair<string, object>> arguments)
|
||||
{
|
||||
var ctx = _activeContext!;
|
||||
var loader = ctx.BrushImageLoader;
|
||||
if (loader is null)
|
||||
return;
|
||||
double w = width > 0d ? width : ctx.ImageWidth;
|
||||
double h = height > 0d ? height : ctx.ImageHeight;
|
||||
var (buffer, bw, bh) = loader(name, w, h, arguments);
|
||||
if (bw <= 0 || bh <= 0)
|
||||
return;
|
||||
ctx.ReplaceBuffer(buffer, bw, bh);
|
||||
RefreshObjDimensions();
|
||||
}
|
||||
|
||||
private void LoadMovie(string path, double time)
|
||||
{
|
||||
_mediaLoader ??= _mediaLoaderFactory();
|
||||
@@ -962,14 +1222,14 @@ namespace LuaScript
|
||||
int w = _activeContext!.ImageWidth;
|
||||
int h = _activeContext.ImageHeight;
|
||||
var obj = _objScope.Table;
|
||||
obj["w"] = w;
|
||||
obj["h"] = h;
|
||||
obj["hw"] = w / 2d;
|
||||
obj["hh"] = h / 2d;
|
||||
obj["cx"] = w / 2d;
|
||||
obj["cy"] = h / 2d;
|
||||
obj["cz"] = 0d;
|
||||
obj["diagonal"] = Math.Sqrt((double)w * w + (double)h * h);
|
||||
obj.Set("w", DynValue.NewNumber(w));
|
||||
obj.Set("h", DynValue.NewNumber(h));
|
||||
obj.Set("hw", DynValue.NewNumber(w / 2d));
|
||||
obj.Set("hh", DynValue.NewNumber(h / 2d));
|
||||
obj.Set("cx", DynValue.NewNumber(w / 2d));
|
||||
obj.Set("cy", DynValue.NewNumber(h / 2d));
|
||||
obj.Set("cz", DynValue.NewNumber(0d));
|
||||
obj.Set("diagonal", DynValue.NewNumber(Math.Sqrt((double)w * w + (double)h * h)));
|
||||
}
|
||||
|
||||
private static DynValue BuildObjectTable(Script script, SceneObjectInfo info)
|
||||
@@ -991,6 +1251,11 @@ namespace LuaScript
|
||||
["rzr"] = info.Rz * Math.PI / 180d,
|
||||
["alpha"] = info.Alpha,
|
||||
["layer"] = info.Layer,
|
||||
["volume"] = info.Volume,
|
||||
["length"] = info.Length,
|
||||
["character"] = info.Character ?? string.Empty,
|
||||
["text"] = info.Text ?? string.Empty,
|
||||
["kind"] = info.Kind ?? string.Empty,
|
||||
};
|
||||
return DynValue.NewTable(table);
|
||||
}
|
||||
|
||||
@@ -43,7 +43,7 @@ namespace LuaScript.Engine
|
||||
public const int CallbackTagOffset = ErrorOffset + ErrorMax;
|
||||
public const int CallbackTagMax = 8192;
|
||||
public const int CallbackResultOffset = CallbackTagOffset + CallbackTagMax;
|
||||
public const int CallbackResultCount = 8;
|
||||
public const int CallbackResultCount = 10;
|
||||
|
||||
public const int StringParamsOffset = CallbackResultOffset + CallbackResultCount * 8;
|
||||
public const int MinStringParamsCapacity = 64 * 1024;
|
||||
@@ -63,6 +63,15 @@ namespace LuaScript.Engine
|
||||
public const int CbKindSceneSet = 12;
|
||||
public const int CbKindPixelShaderStage = 13;
|
||||
public const int CbKindPixelShaderRun = 14;
|
||||
public const int CbKindLoadScene = 15;
|
||||
public const int CbKindLoadBrush = 16;
|
||||
public const int CbKindBrush = 17;
|
||||
public const int CbKindGetAudio = 18;
|
||||
public const int CbKindPixelProcess = 19;
|
||||
|
||||
public const int PixelProcessFill = 0;
|
||||
public const int PixelProcessConvolve = 1;
|
||||
public const int PixelProcessResize = 2;
|
||||
|
||||
public const int DrawRingCapacity = 4096;
|
||||
public const int DrawEntryDoubles = 24;
|
||||
@@ -77,6 +86,8 @@ namespace LuaScript.Engine
|
||||
public const int CbRz = 5;
|
||||
public const int CbAlpha = 6;
|
||||
public const int CbLayer = 7;
|
||||
public const int CbVolume = 8;
|
||||
public const int CbLength = 9;
|
||||
|
||||
public static long DrawRingOffset(int stringCapacity) => StringParamsOffset + stringCapacity;
|
||||
|
||||
|
||||
@@ -0,0 +1,166 @@
|
||||
using System;
|
||||
|
||||
namespace LuaScript
|
||||
{
|
||||
internal static unsafe class PixelBufferSoftwareProcessor
|
||||
{
|
||||
public static void Fill(byte[] target, int width, int height, double r, double g, double b, double a, int x, int y, int fillWidth, int fillHeight)
|
||||
{
|
||||
double aK = Math.Clamp(a, 0d, 255d) / 255d;
|
||||
byte pb = (byte)Math.Clamp(b * aK, 0d, 255d);
|
||||
byte pg = (byte)Math.Clamp(g * aK, 0d, 255d);
|
||||
byte pr = (byte)Math.Clamp(r * aK, 0d, 255d);
|
||||
byte pa = (byte)Math.Clamp(a, 0d, 255d);
|
||||
int x1 = x + fillWidth;
|
||||
int y1 = y + fillHeight;
|
||||
|
||||
fixed (byte* buf = target)
|
||||
{
|
||||
for (int py = y; py < y1; py++)
|
||||
{
|
||||
byte* p = buf + (py * width + x) * 4;
|
||||
for (int px = x; px < x1; px++)
|
||||
{
|
||||
p[0] = pb;
|
||||
p[1] = pg;
|
||||
p[2] = pr;
|
||||
p[3] = pa;
|
||||
p += 4;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
public static void Convolve(byte[] target, int width, int height, double[] kernel, int size, double divisor, double offset, ref double[]? sourceScratch)
|
||||
{
|
||||
int count = width * height * 4;
|
||||
if (sourceScratch is null || sourceScratch.Length < count)
|
||||
sourceScratch = new double[count];
|
||||
var src = sourceScratch;
|
||||
|
||||
fixed (byte* buf = target)
|
||||
{
|
||||
for (int pi = 0; pi < width * height; pi++)
|
||||
{
|
||||
byte* p = buf + pi * 4;
|
||||
int di = pi * 4;
|
||||
double a = p[3];
|
||||
src[di + 3] = a;
|
||||
if (a <= 0d)
|
||||
{
|
||||
src[di] = 0d;
|
||||
src[di + 1] = 0d;
|
||||
src[di + 2] = 0d;
|
||||
}
|
||||
else
|
||||
{
|
||||
double s = 255d / a;
|
||||
src[di] = Math.Clamp(p[2] * s, 0d, 255d);
|
||||
src[di + 1] = Math.Clamp(p[1] * s, 0d, 255d);
|
||||
src[di + 2] = Math.Clamp(p[0] * s, 0d, 255d);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
int half = size / 2;
|
||||
|
||||
fixed (byte* buf = target)
|
||||
{
|
||||
for (int y = 0; y < height; y++)
|
||||
{
|
||||
for (int x = 0; x < width; x++)
|
||||
{
|
||||
double sr = 0d, sg = 0d, sb = 0d, sa = 0d;
|
||||
for (int ky = 0; ky < size; ky++)
|
||||
{
|
||||
int sy = Math.Clamp(y + ky - half, 0, height - 1);
|
||||
for (int kx = 0; kx < size; kx++)
|
||||
{
|
||||
int sx = Math.Clamp(x + kx - half, 0, width - 1);
|
||||
double kv = kernel[ky * size + kx];
|
||||
int si = (sy * width + sx) * 4;
|
||||
sr += src[si] * kv;
|
||||
sg += src[si + 1] * kv;
|
||||
sb += src[si + 2] * kv;
|
||||
sa += src[si + 3] * kv;
|
||||
}
|
||||
}
|
||||
double rr = Math.Clamp(sr / divisor + offset, 0d, 255d);
|
||||
double gg = Math.Clamp(sg / divisor + offset, 0d, 255d);
|
||||
double bb = Math.Clamp(sb / divisor + offset, 0d, 255d);
|
||||
double aa = Math.Clamp(sa / divisor + offset, 0d, 255d);
|
||||
double aK = aa / 255d;
|
||||
byte* p = buf + (y * width + x) * 4;
|
||||
p[0] = (byte)Math.Clamp(bb * aK, 0d, 255d);
|
||||
p[1] = (byte)Math.Clamp(gg * aK, 0d, 255d);
|
||||
p[2] = (byte)Math.Clamp(rr * aK, 0d, 255d);
|
||||
p[3] = (byte)aa;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
public static byte[] Resize(byte[] source, int sourceWidth, int sourceHeight, int targetWidth, int targetHeight, bool linear, ref byte[]? sourceScratch, ref byte[]? targetScratch)
|
||||
{
|
||||
int srcCount = sourceWidth * sourceHeight * 4;
|
||||
if (sourceScratch is null || sourceScratch.Length < srcCount)
|
||||
sourceScratch = new byte[srcCount];
|
||||
Buffer.BlockCopy(source, 0, sourceScratch, 0, srcCount);
|
||||
|
||||
int dstCount = targetWidth * targetHeight * 4;
|
||||
if (targetScratch is null || targetScratch.Length != dstCount)
|
||||
targetScratch = new byte[dstCount];
|
||||
var src = sourceScratch;
|
||||
var dst = targetScratch;
|
||||
|
||||
fixed (byte* s = src)
|
||||
fixed (byte* d = dst)
|
||||
{
|
||||
for (int y = 0; y < targetHeight; y++)
|
||||
{
|
||||
for (int x = 0; x < targetWidth; x++)
|
||||
{
|
||||
byte* o = d + (y * targetWidth + x) * 4;
|
||||
if (!linear)
|
||||
{
|
||||
int sx = Math.Clamp((int)((x + 0.5) * sourceWidth / targetWidth), 0, sourceWidth - 1);
|
||||
int sy = Math.Clamp((int)((y + 0.5) * sourceHeight / targetHeight), 0, sourceHeight - 1);
|
||||
byte* p = s + (sy * sourceWidth + sx) * 4;
|
||||
o[0] = p[0];
|
||||
o[1] = p[1];
|
||||
o[2] = p[2];
|
||||
o[3] = p[3];
|
||||
}
|
||||
else
|
||||
{
|
||||
double u = (x + 0.5) * sourceWidth / targetWidth - 0.5;
|
||||
double v = (y + 0.5) * sourceHeight / targetHeight - 0.5;
|
||||
int x0 = (int)Math.Floor(u);
|
||||
int y0 = (int)Math.Floor(v);
|
||||
double tx = u - x0;
|
||||
double ty = v - y0;
|
||||
for (int c = 0; c < 4; c++)
|
||||
{
|
||||
double acc = 0d;
|
||||
for (int j = 0; j < 2; j++)
|
||||
{
|
||||
int sy = Math.Clamp(y0 + j, 0, sourceHeight - 1);
|
||||
double wy = j == 0 ? 1d - ty : ty;
|
||||
for (int i = 0; i < 2; i++)
|
||||
{
|
||||
int sx = Math.Clamp(x0 + i, 0, sourceWidth - 1);
|
||||
double wx = i == 0 ? 1d - tx : tx;
|
||||
acc += s[(sy * sourceWidth + sx) * 4 + c] * wy * wx;
|
||||
}
|
||||
}
|
||||
o[c] = (byte)Math.Clamp(acc, 0d, 255d);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return dst;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,15 +1,16 @@
|
||||
<Project Sdk="Microsoft.NET.Sdk">
|
||||
<Project Sdk="Microsoft.NET.Sdk">
|
||||
|
||||
<PropertyGroup>
|
||||
<TargetFramework>net10.0-windows10.0.19041.0</TargetFramework>
|
||||
<ImplicitUsings>enable</ImplicitUsings>
|
||||
<Version>1.16.0</Version>
|
||||
<Version>1.20.1</Version>
|
||||
<Platforms>AnyCPU;x64</Platforms>
|
||||
<Nullable>enable</Nullable>
|
||||
<AllowUnsafeBlocks>true</AllowUnsafeBlocks>
|
||||
</PropertyGroup>
|
||||
|
||||
<ItemGroup>
|
||||
<InternalsVisibleTo Include="LuaScript.Gpu" />
|
||||
<InternalsVisibleTo Include="LuaScript" />
|
||||
<InternalsVisibleTo Include="LuaScript.Tests" />
|
||||
</ItemGroup>
|
||||
|
||||
@@ -9,5 +9,10 @@ namespace LuaScript
|
||||
double Zoom,
|
||||
double Rz,
|
||||
double Alpha,
|
||||
int Layer);
|
||||
int Layer,
|
||||
int Length,
|
||||
double Volume,
|
||||
string Character,
|
||||
string Text,
|
||||
string Kind);
|
||||
}
|
||||
@@ -13,6 +13,35 @@ namespace LuaScript.Tests
|
||||
Assert.Equal(AnchorSupport.MaxAnchors, AnchorSupport.ClampCount(100));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void NormalizeCount_DefaultsTrackToSinglePoint()
|
||||
{
|
||||
Assert.Equal(1, AnchorSupport.NormalizeCount(AnchorSupport.TrackGroup, 0));
|
||||
Assert.Equal(1, AnchorSupport.NormalizeCount(AnchorSupport.TrackGroup, -3));
|
||||
Assert.Equal(4, AnchorSupport.NormalizeCount(AnchorSupport.TrackGroup, 4));
|
||||
Assert.Equal(0, AnchorSupport.NormalizeCount("pos", 0));
|
||||
Assert.Equal(AnchorSupport.MaxAnchors, AnchorSupport.NormalizeCount("pos", 100));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void SetPosition_ReplacesOrAppendsAbsolute()
|
||||
{
|
||||
var source = ImmutableList.Create(new LuaAnchorPoint { Group = "pos", Index = 2, X = 10, Y = 20, Z = 30 });
|
||||
|
||||
var replaced = AnchorSupport.SetPosition(source, "pos", 2, 1, 2, 3);
|
||||
Assert.Single(replaced);
|
||||
Assert.Equal(1, replaced[0].X);
|
||||
Assert.Equal(2, replaced[0].Y);
|
||||
Assert.Equal(3, replaced[0].Z);
|
||||
|
||||
var appended = AnchorSupport.SetPosition(source, "pos", 5, 7, 8, 9);
|
||||
Assert.Equal(2, appended.Count);
|
||||
Assert.Equal(5, appended[1].Index);
|
||||
Assert.Equal(7, appended[1].X);
|
||||
Assert.Equal(8, appended[1].Y);
|
||||
Assert.Equal(9, appended[1].Z);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void ApplyOption_SetsConnectionAndDimension()
|
||||
{
|
||||
|
||||
@@ -0,0 +1,132 @@
|
||||
using LuaScript.Compat;
|
||||
|
||||
namespace LuaScript.Tests
|
||||
{
|
||||
public sealed class AviUtlAudioConverterTests
|
||||
{
|
||||
private static float[] Interleave(double[] left, double[] right)
|
||||
{
|
||||
var data = new float[left.Length * 2];
|
||||
for (int i = 0; i < left.Length; i++)
|
||||
{
|
||||
data[i * 2] = (float)left[i];
|
||||
data[i * 2 + 1] = (float)right[i];
|
||||
}
|
||||
return data;
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void RequiredFrames_MatchesTypeWindows()
|
||||
{
|
||||
Assert.Equal(16, AviUtlAudioConverter.RequiredFrames("pcm", 16));
|
||||
Assert.Equal(AviUtlAudioConverter.MaxSamples, AviUtlAudioConverter.RequiredFrames("pcm", 0));
|
||||
Assert.Equal(AviUtlAudioConverter.MaxSamples, AviUtlAudioConverter.RequiredFrames("pcm", 99999));
|
||||
Assert.Equal(AviUtlAudioConverter.SpectrumWindow, AviUtlAudioConverter.RequiredFrames("spectrum", 32));
|
||||
Assert.Equal(AviUtlAudioConverter.FourierWindow, AviUtlAudioConverter.RequiredFrames("fourier", 0));
|
||||
Assert.Equal(AviUtlAudioConverter.FourierWindow, AviUtlAudioConverter.RequiredFrames("fourier.l", 0));
|
||||
Assert.Equal(0, AviUtlAudioConverter.RequiredFrames("unknown", 8));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Pcm_ScalesMonoMixTo16BitRange()
|
||||
{
|
||||
var converter = new AviUtlAudioConverter();
|
||||
var data = Interleave([0.5d, -1d, 0d], [0.5d, -1d, 1d]);
|
||||
var dest = new double[AviUtlAudioConverter.MaxSamples];
|
||||
|
||||
int count = converter.Convert("pcm", data, 3, 3, dest);
|
||||
|
||||
Assert.Equal(3, count);
|
||||
Assert.Equal(16384d, dest[0]);
|
||||
Assert.Equal(-32768d, dest[1]);
|
||||
Assert.Equal(16384d, dest[2]);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Pcm_SelectsChannelBySuffix()
|
||||
{
|
||||
var converter = new AviUtlAudioConverter();
|
||||
var data = Interleave([0.25d, 0.25d], [-0.5d, -0.5d]);
|
||||
var dest = new double[AviUtlAudioConverter.MaxSamples];
|
||||
|
||||
converter.Convert("pcm.l", data, 2, 2, dest);
|
||||
Assert.Equal(8192d, dest[0]);
|
||||
|
||||
converter.Convert("pcm.r", data, 2, 2, dest);
|
||||
Assert.Equal(-16384d, dest[0]);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Pcm_ReturnsFewerWhenSourceIsShort()
|
||||
{
|
||||
var converter = new AviUtlAudioConverter();
|
||||
var data = Interleave([0.1d, 0.2d], [0.1d, 0.2d]);
|
||||
var dest = new double[AviUtlAudioConverter.MaxSamples];
|
||||
|
||||
int count = converter.Convert("pcm", data, 2, 100, dest);
|
||||
|
||||
Assert.Equal(2, count);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Spectrum_PeaksInBandContainingSineFrequency()
|
||||
{
|
||||
var converter = new AviUtlAudioConverter();
|
||||
const int frames = AviUtlAudioConverter.SpectrumWindow;
|
||||
const int cycle = 64;
|
||||
var mono = new double[frames];
|
||||
for (int i = 0; i < frames; i++)
|
||||
mono[i] = Math.Sin(2d * Math.PI * i * cycle / frames);
|
||||
var data = Interleave(mono, mono);
|
||||
var dest = new double[AviUtlAudioConverter.MaxSamples];
|
||||
|
||||
int count = converter.Convert("spectrum", data, frames, 32, dest);
|
||||
|
||||
Assert.Equal(32, count);
|
||||
int expectedBand = cycle * 32 / AviUtlAudioConverter.SpectrumBins;
|
||||
int peakBand = 0;
|
||||
for (int i = 1; i < count; i++)
|
||||
{
|
||||
if (dest[i] > dest[peakBand])
|
||||
peakBand = i;
|
||||
}
|
||||
Assert.Equal(expectedBand, peakBand);
|
||||
Assert.True(dest[peakBand] > 1000d);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Fourier_ReturnsNormalizedMagnitudes()
|
||||
{
|
||||
var converter = new AviUtlAudioConverter();
|
||||
const int frames = AviUtlAudioConverter.FourierWindow;
|
||||
const int cycle = 8;
|
||||
var mono = new double[frames];
|
||||
for (int i = 0; i < frames; i++)
|
||||
mono[i] = Math.Sin(2d * Math.PI * i * cycle / frames);
|
||||
var data = Interleave(mono, mono);
|
||||
var dest = new double[AviUtlAudioConverter.MaxSamples];
|
||||
|
||||
int count = converter.Convert("fourier", data, frames, 0, dest);
|
||||
|
||||
Assert.Equal(AviUtlAudioConverter.MaxSamples, count);
|
||||
int peak = 0;
|
||||
for (int i = 1; i < count; i++)
|
||||
{
|
||||
if (dest[i] > dest[peak])
|
||||
peak = i;
|
||||
}
|
||||
Assert.Equal(cycle - 1, peak);
|
||||
Assert.Equal(1d, dest[peak], 3);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void UnknownTypeOrEmptySource_YieldsZero()
|
||||
{
|
||||
var converter = new AviUtlAudioConverter();
|
||||
var dest = new double[AviUtlAudioConverter.MaxSamples];
|
||||
|
||||
Assert.Equal(0, converter.Convert("waveform", new float[8], 4, 4, dest));
|
||||
Assert.Equal(0, converter.Convert("pcm", [], 0, 4, dest));
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -137,35 +137,35 @@ namespace LuaScript.Tests
|
||||
[Fact]
|
||||
public void ChangedLines_EmptyWhenNoRewrite()
|
||||
{
|
||||
var (_, _, changed) = AviUtlScript.TransformWithMap("obj.x = 1\nobj.y = 2");
|
||||
var (_, _, changed, _) = AviUtlScript.TransformWithMap("obj.x = 1\nobj.y = 2");
|
||||
Assert.Empty(changed);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void ChangedLines_ReportRewrittenLineInRunnableSpace()
|
||||
{
|
||||
var (_, _, changed) = AviUtlScript.TransformWithMap("obj.x = 1\nobj.y = obj.x != 0\nobj.z = 3");
|
||||
var (_, _, changed, _) = AviUtlScript.TransformWithMap("obj.x = 1\nobj.y = obj.x != 0\nobj.z = 3");
|
||||
Assert.Equal(new[] { 2 }, changed);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void ChangedLines_AreSortedAndCoverEveryRewrittenLine()
|
||||
{
|
||||
var (_, _, changed) = AviUtlScript.TransformWithMap("a = x != 0\nb = y\nc = z ?? 5\nw++");
|
||||
var (_, _, changed, _) = AviUtlScript.TransformWithMap("a = x != 0\nb = y\nc = z ?? 5\nw++");
|
||||
Assert.Equal(new[] { 1, 3, 4 }, changed);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void ChangedLines_DeduplicateMultipleRewritesOnOneLine()
|
||||
{
|
||||
var (_, _, changed) = AviUtlScript.TransformWithMap("a = x != 0 and y != 1 and z != 2");
|
||||
var (_, _, changed, _) = AviUtlScript.TransformWithMap("a = x != 0 and y != 1 and z != 2");
|
||||
Assert.Equal(new[] { 1 }, changed);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void ChangedLines_TrackRunnableLineAfterHoistedPrelude()
|
||||
{
|
||||
var (_, _, changed) = AviUtlScript.TransformWithMap("--dialog:V,local v=3;\nresult = v != 0");
|
||||
var (_, _, changed, _) = AviUtlScript.TransformWithMap("--dialog:V,local v=3;\nresult = v != 0");
|
||||
Assert.NotEmpty(changed);
|
||||
for (int i = 1; i < changed.Length; i++)
|
||||
Assert.True(changed[i] > changed[i - 1]);
|
||||
|
||||
@@ -23,6 +23,12 @@ namespace LuaScript.Tests
|
||||
[InlineData("for y=0,obj.h-1 do for x=0,obj.w-1 do local r,g,b,a=obj.getpixel(x,y) obj.setpixel(x,y,r%64,math.abs(g-128),math.sqrt(b*255),a) end end")]
|
||||
[InlineData("local x=99 local k=3 for y=0,obj.h-1 do for x=0,obj.w-1 do local r,g,b,a=obj.getpixel(x,y) obj.setpixel(x,y,x/obj.w*255+k,g,b,a) end end")]
|
||||
[InlineData("for y=0,obj.h-1 do for x=0,obj.w-1 do local r,g,b,a=obj.getpixel(x,y) obj.setpixel(x,y,math.fmod(r,64),math.fmod(g,7)*36,math.fmod(b-128,60)+128,a) end end")]
|
||||
[InlineData("for y=0,obj.h-1 do for x=0,obj.w-1 do local r,g,b,a=obj.getpixel(x,y) if r>128 then r=255 end obj.setpixel(x,y,r,g,b,a) end end")]
|
||||
[InlineData("for y=0,obj.h-1 do for x=0,obj.w-1 do local r,g,b,a=obj.getpixel(x,y) local v=(r+g+b)/3 local o=0 if v>128 then o=255 else o=32 end obj.setpixel(x,y,o,o,o,a) end end")]
|
||||
[InlineData("for y=0,obj.h-1 do for x=0,obj.w-1 do local r,g,b,a=obj.getpixel(x,y) local v=(r+g+b)/3 local o=0 if v>170 then o=255 elseif v>85 then o=128 elseif v>40 then o=64 end obj.setpixel(x,y,o,g,b,a) end end")]
|
||||
[InlineData("for y=0,obj.h-1 do for x=0,obj.w-1 do local r,g,b,a=obj.getpixel(x,y) if r>g then r=g end if b<64 and g>32 then b=g elseif b>192 then b=192 end obj.setpixel(x,y,r,g,b,a) end end")]
|
||||
[InlineData("for y=0,obj.h-1 do for x=0,obj.w-1 do local r,g,b,a=obj.getpixel(x,y) local v=0 if r>128 then local r=g*0.5 v=r+1 if v>100 then v=100 end else v=r end obj.setpixel(x,y,v,g,b,a) end end")]
|
||||
[InlineData("local w=obj.w local h=obj.h for y=0,h-1 do for x=0,w-1 do local r,g,b,a=obj.getpixel(x,y) obj.setpixel(x,y,x/w*255,y/h*255,b,a) end end")]
|
||||
public void CpuKernelMatchesMoonSharp(string script)
|
||||
{
|
||||
var fields = new Dictionary<string, double> { ["w"] = Width, ["h"] = Height };
|
||||
@@ -46,6 +52,9 @@ namespace LuaScript.Tests
|
||||
[InlineData("local pd=obj.getpixeldata() for y=0,pd.height-1 do for x=0,pd.width-1 do local i=(y*pd.width+x)*4 local r=pd:get(i+1) local g=pd:get(i+2) local b=pd:get(i+3) pd:set(i+1,b) pd:set(i+2,g) pd:set(i+3,r) end end")]
|
||||
[InlineData("local pd=obj.getpixeldata() for y=0,obj.h-1 do for x=0,obj.w-1 do local i=(y*obj.w+x)*4 local r=pd:get(i+1) local a=pd:get(i+4) pd:set(i+1,r*a/255) pd:set(i+2,pd:get(i+2)*obj.track0/100) pd:set(i+3,math.min(255,pd:get(i+3)+50)) end end")]
|
||||
[InlineData("local pd=obj.getpixeldata() for y=0,pd.height-1 do for x=0,pd.width-1 do local i=(y*pd.width+x)*4 local r=pd:get(i+1) local g=pd:get(i+2) local b=pd:get(i+3) pd:set(i+1,r*3) pd:set(i+2,g-300) pd:set(i+3,b*2-255) end end")]
|
||||
[InlineData("local pd=obj.getpixeldata() for y=0,pd.height-1 do for x=0,pd.width-1 do local i=(y*pd.width+x)*4 local r=pd:get(i+1) local g=pd:get(i+2) local b=pd:get(i+3) pd:set(i+1,255-r) pd:set(i+2,255-g) pd:set(i+3,255-b) end end obj.putpixeldata(pd)")]
|
||||
[InlineData("local data=obj.getpixeldata() local w=data.width local h=data.height for y=0,h-1 do for x=0,w-1 do local i=(y*w+x)*4 local r=data:get(i+1) local g=data:get(i+2) local b=data:get(i+3) data:set(i+1,g) data:set(i+2,b) data:set(i+3,r) end end obj.putpixeldata(data)")]
|
||||
[InlineData("local pd=obj.getpixeldata() for y=0,pd.height-1 do for x=0,pd.width-1 do local i=(y*pd.width+x)*4 local r=pd:get(i+1) local g=pd:get(i+2) local b=pd:get(i+3) local v=(r+g+b)/3 local o=0 if v>128 then o=255 end pd:set(i+1,o) pd:set(i+2,o) pd:set(i+3,o) end end")]
|
||||
public void GetPixelDataKernelMatchesMoonSharp(string script)
|
||||
{
|
||||
var fields = new Dictionary<string, double> { ["w"] = Width, ["h"] = Height, ["track0"] = 73d };
|
||||
@@ -60,6 +69,9 @@ namespace LuaScript.Tests
|
||||
[InlineData("local pd=obj.getpixeldata() for y=0,pd.height-1 do for x=0,pd.width-1 do local i=(y*pd.width+x)*4 local i=i+4 pd:set(i+1,0) pd:set(i+2,0) pd:set(i+3,0) end end")]
|
||||
[InlineData("local pd=obj.getpixeldata() for y=0,pd.height-1 do for pd=0,pd.width-1 do local i=(y*2+pd)*4 pd:set(i+1,0) pd:set(i+2,0) pd:set(i+3,0) end end")]
|
||||
[InlineData("local pd=obj.getpixeldata() for y=0,pd.height-1 do for x=0,pd.width-1 do local i=(y*pd.width+x)*4 local pd=0 pd:set(i+1,0) end end")]
|
||||
[InlineData("local pd=obj.getpixeldata() for y=0,pd.height-1 do for x=0,pd.width-1 do local i=(y*pd.width+x)*4 local r=pd:get(i+1) if r>128 then pd:set(i+1,255) end pd:set(i+2,0) pd:set(i+3,0) end end")]
|
||||
[InlineData("local pd=obj.getpixeldata() for y=0,pd.height-1 do for x=0,pd.width-1 do local i=(y*pd.width+x)*4 pd:set(i+1,0) pd:set(i+2,0) pd:set(i+3,0) end end obj.putpixeldata(other)")]
|
||||
[InlineData("local pd=obj.getpixeldata() for y=0,pd.height-1 do for x=0,pd.width-1 do local i=(y*pd.width+x)*4 pd:set(i+1,0) pd:set(i+2,0) pd:set(i+3,0) end end obj.putpixeldata(pd) obj.putpixeldata(pd)")]
|
||||
public void GetPixelDataNonKernelScriptsAreRejected(string script)
|
||||
{
|
||||
Assert.Null(KernelExtractor.TryExtract(script));
|
||||
@@ -92,8 +104,12 @@ namespace LuaScript.Tests
|
||||
[InlineData("for y=0,obj.h-1 do for x=0,obj.w-1 do local r,g,b,a=obj.getpixel(x,y) total=total+r obj.setpixel(x,y,r,g,b,a) end end")]
|
||||
[InlineData("for y=0,obj.h-1 do for x=0,obj.w-1 do local r,g,b,a=obj.getpixel(x+1,y) obj.setpixel(x,y,r,g,b,a) end end")]
|
||||
[InlineData("for i=0,10 do end")]
|
||||
[InlineData("for y=0,obj.h-1 do for x=0,obj.w-1 do local r,g,b,a=obj.getpixel(x,y) if r>128 then r=255 end obj.setpixel(x,y,r,g,b,a) end end")]
|
||||
[InlineData("for y=0,obj.h-1 do for x=0,obj.w-1 do local r,g,b,a=obj.getpixel(x,y) obj.setpixel(x,y,obj.rand(0,255),g,b,a) end end")]
|
||||
[InlineData("for y=0,obj.h-1 do for x=0,obj.w-1 do local r,g,b,a=obj.getpixel(x,y) if r>128 then obj.setpixel(x,y,255,g,b,a) end end end")]
|
||||
[InlineData("for y=0,obj.h-1 do for x=0,obj.w-1 do local r,g,b,a=obj.getpixel(x,y) if r then r=255 end obj.setpixel(x,y,r,g,b,a) end end")]
|
||||
[InlineData("for y=0,obj.h-1 do for x=0,obj.w-1 do local r,g,b,a=obj.getpixel(x,y) if r>128 then local y=0 r=y end obj.setpixel(x,y,r,g,b,a) end end")]
|
||||
[InlineData("for y=0,obj.h-1 do for x=0,obj.w-1 do local r,g,b,a=obj.getpixel(x,y) obj.setpixel(x,y,r,g,b,a) end end obj.putpixeldata(pd)")]
|
||||
[InlineData("local w=5 for y=0,obj.h-1 do for x=0,w-1 do local r,g,b,a=obj.getpixel(x,y) obj.setpixel(x,y,r,g,b,a) end end")]
|
||||
public void NonKernelScriptsAreRejected(string script)
|
||||
{
|
||||
Assert.Null(KernelExtractor.TryExtract(script));
|
||||
@@ -178,6 +194,8 @@ namespace LuaScript.Tests
|
||||
return DynValue.NewTable(pd);
|
||||
});
|
||||
|
||||
obj["putpixeldata"] = DynValue.NewCallback((_, _) => DynValue.Void);
|
||||
|
||||
engine.Globals["obj"] = obj;
|
||||
engine.DoString(script);
|
||||
}
|
||||
|
||||
@@ -62,6 +62,18 @@ namespace LuaScript.Tests
|
||||
Assert.Contains($"uniforms[{index / 4}].{"xyzw"[index % 4]}", hlsl);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void ConditionalStatementEmitsTernary()
|
||||
{
|
||||
const string script =
|
||||
"for y=0,obj.h-1 do for x=0,obj.w-1 do local r,g,b,a=obj.getpixel(x,y) " +
|
||||
"local v=(r+g+b)/3 local o=0 if v>170 then o=255 elseif v>85 then o=128 end " +
|
||||
"obj.setpixel(x,y,o,o,o,a) end end";
|
||||
string hlsl = HlslKernelEmitter.Emit(Extract(script));
|
||||
Assert.Contains(" ? (", hlsl);
|
||||
Assert.Contains(" > ", hlsl);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void EmissionIsDeterministic()
|
||||
{
|
||||
|
||||
@@ -24,6 +24,7 @@ namespace LuaScript.Tests
|
||||
[InlineData("for y=0,obj.h-1 do for x=0,obj.w-1 do local r,g,b,a=obj.getpixel(x,y) obj.setpixel(x,y,((r>128 and g<64) or (not (b>200))) and 255 or 0,g,b,a) end end")]
|
||||
[InlineData("for y=0,obj.h-1 do for x=0,obj.w-1 do local r,g,b,a=obj.getpixel(x,y) obj.setpixel(x,y,(r>=200) and 255 or 0,(g<=50) and 255 or 0,(b==0) and 255 or ((b~=0) and 100 or 0),a) end end")]
|
||||
[InlineData("local pd=obj.getpixeldata() for y=0,pd.height-1 do for x=0,pd.width-1 do local i=(y*pd.width+x)*4 local r=pd:get(i+1) local g=pd:get(i+2) local b=pd:get(i+3) pd:set(i+1,r*3) pd:set(i+2,g-300) pd:set(i+3,b*2-255) end end")]
|
||||
[InlineData("for y=0,obj.h-1 do for x=0,obj.w-1 do local r,g,b,a=obj.getpixel(x,y) local v=(r+g+b)/3 local o=0 if v>170 then o=255 elseif v>85 then o=128 else o=r end obj.setpixel(x,y,o,o,o,a) end end")]
|
||||
public void SimdBlockMatchesScalarRow(string script)
|
||||
{
|
||||
var program = KernelExtractor.TryExtract(script);
|
||||
|
||||
@@ -11,6 +11,8 @@ namespace LuaScript.Tests
|
||||
"repeat", "return", "then", "true", "until", "while"
|
||||
];
|
||||
|
||||
private static readonly string[] SyntaxKeywords = ["fast"];
|
||||
|
||||
private static readonly string[] Globals =
|
||||
[
|
||||
"time", "frame", "totalframe", "framerate",
|
||||
@@ -48,8 +50,9 @@ namespace LuaScript.Tests
|
||||
"obj.getpixeldata", "obj.putpixeldata", "obj.rand", "obj.load",
|
||||
"obj.setfont", "obj.draw", "obj.drawpoly", "obj.copybuffer",
|
||||
"obj.pixelshader",
|
||||
"obj.getvalue", "obj.setoption", "obj.getoption", "obj.pixeloption",
|
||||
"obj.setanchor", "obj.effect", "obj.getinfo"
|
||||
"obj.getvalue", "obj.getaudio", "obj.setoption", "obj.getoption", "obj.pixeloption",
|
||||
"obj.setanchor", "obj.effect", "obj.brush", "obj.getinfo",
|
||||
"obj.fill", "obj.getpixelregion", "obj.putpixelregion", "obj.convolve", "obj.resize"
|
||||
]),
|
||||
("math", [
|
||||
"math.abs", "math.ceil", "math.cos", "math.exp", "math.floor",
|
||||
@@ -103,6 +106,7 @@ namespace LuaScript.Tests
|
||||
|
||||
private static string[] ExpectedStaticCandidates() =>
|
||||
Keywords
|
||||
.Concat(SyntaxKeywords)
|
||||
.Concat(Globals)
|
||||
.Concat(Namespaces.SelectMany(n => n.Members))
|
||||
.Distinct()
|
||||
|
||||
@@ -0,0 +1,247 @@
|
||||
using LuaScript;
|
||||
|
||||
namespace LuaScript.Tests
|
||||
{
|
||||
public sealed class LuaScriptEngineBufferOpsTests
|
||||
{
|
||||
private sealed class StubMediaLoader : IMediaSourceLoader
|
||||
{
|
||||
public byte[] RenderText(string text, string fontFamily, double fontSize, bool bold, bool italic, int colorRgb, out int width, out int height)
|
||||
{
|
||||
width = 1;
|
||||
height = 1;
|
||||
return new byte[4];
|
||||
}
|
||||
|
||||
public byte[] DecodeImage(string path, out int width, out int height)
|
||||
{
|
||||
width = 1;
|
||||
height = 1;
|
||||
return new byte[4];
|
||||
}
|
||||
|
||||
public byte[] DecodeMovie(string path, double time, out int width, out int height)
|
||||
{
|
||||
width = 1;
|
||||
height = 1;
|
||||
return new byte[4];
|
||||
}
|
||||
|
||||
public void Dispose() { }
|
||||
}
|
||||
|
||||
private static LuaScriptEngine CreateEngine() => new(static () => new StubMediaLoader());
|
||||
|
||||
private static AviUtlScriptContext NewContext(byte[] buffer, int width, int height)
|
||||
{
|
||||
var ctx = new AviUtlScriptContext { Framerate = 30 };
|
||||
ctx.SetResolvedBuffer(buffer, width, height);
|
||||
return ctx;
|
||||
}
|
||||
|
||||
private static byte[] Bgra(params (byte B, byte G, byte R, byte A)[] pixels)
|
||||
{
|
||||
var buffer = new byte[pixels.Length * 4];
|
||||
for (int i = 0; i < pixels.Length; i++)
|
||||
{
|
||||
buffer[i * 4 + 0] = pixels[i].B;
|
||||
buffer[i * 4 + 1] = pixels[i].G;
|
||||
buffer[i * 4 + 2] = pixels[i].R;
|
||||
buffer[i * 4 + 3] = pixels[i].A;
|
||||
}
|
||||
return buffer;
|
||||
}
|
||||
|
||||
private sealed class RecordingProcessor : IPixelBufferProcessor
|
||||
{
|
||||
public int FillCalls;
|
||||
public int ConvolveCalls;
|
||||
public int ResizeCalls;
|
||||
|
||||
public bool TryFill(byte[] target, int width, int height, double r, double g, double b, double a, int x, int y, int fillWidth, int fillHeight)
|
||||
{
|
||||
FillCalls++;
|
||||
return false;
|
||||
}
|
||||
|
||||
public bool TryConvolve(byte[] target, int width, int height, double[] kernel, int size, double divisor, double offset)
|
||||
{
|
||||
ConvolveCalls++;
|
||||
return false;
|
||||
}
|
||||
|
||||
public bool TryResize(byte[] source, int sourceWidth, int sourceHeight, int targetWidth, int targetHeight, bool linear, out byte[]? target)
|
||||
{
|
||||
ResizeCalls++;
|
||||
target = null;
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void BufferOps_ConsultPixelProcessorAndFallBackToCpu()
|
||||
{
|
||||
using var engine = CreateEngine();
|
||||
var ctx = NewContext(new byte[2 * 2 * 4], 2, 2);
|
||||
var processor = new RecordingProcessor();
|
||||
ctx.PixelProcessor = processor;
|
||||
|
||||
engine.Execute("obj.fill(200, 100, 50, 255) obj.convolve({1,1,1,1,1,1,1,1,1}, 3) obj.resize(4, 4)", ctx);
|
||||
|
||||
Assert.Equal(1, processor.FillCalls);
|
||||
Assert.Equal(1, processor.ConvolveCalls);
|
||||
Assert.Equal(1, processor.ResizeCalls);
|
||||
Assert.Equal(4, ctx.ImageWidth);
|
||||
Assert.Equal(4, ctx.ImageHeight);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Fill_WholeBuffer_WritesPremultipliedColor()
|
||||
{
|
||||
using var engine = CreateEngine();
|
||||
var ctx = NewContext(new byte[2 * 2 * 4], 2, 2);
|
||||
|
||||
engine.Execute("obj.fill(200, 100, 50, 255)", ctx);
|
||||
|
||||
var buffer = ctx.GetPixelBuffer()!;
|
||||
for (int i = 0; i < 4; i++)
|
||||
{
|
||||
Assert.Equal(50, buffer[i * 4 + 0]);
|
||||
Assert.Equal(100, buffer[i * 4 + 1]);
|
||||
Assert.Equal(200, buffer[i * 4 + 2]);
|
||||
Assert.Equal(255, buffer[i * 4 + 3]);
|
||||
}
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Fill_Rectangle_TouchesOnlyRequestedPixels()
|
||||
{
|
||||
using var engine = CreateEngine();
|
||||
var ctx = NewContext(new byte[3 * 1 * 4], 3, 1);
|
||||
|
||||
engine.Execute("obj.fill(255, 255, 255, 255, 1, 0, 1, 1)", ctx);
|
||||
|
||||
var buffer = ctx.GetPixelBuffer()!;
|
||||
Assert.Equal(new byte[] { 0, 0, 0, 0 }, buffer.AsSpan(0, 4).ToArray());
|
||||
Assert.Equal(new byte[] { 255, 255, 255, 255 }, buffer.AsSpan(4, 4).ToArray());
|
||||
Assert.Equal(new byte[] { 0, 0, 0, 0 }, buffer.AsSpan(8, 4).ToArray());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void GetPixelRegion_ReturnsStraightRgba()
|
||||
{
|
||||
using var engine = CreateEngine();
|
||||
var ctx = NewContext(Bgra((50, 100, 200, 255)), 1, 1);
|
||||
|
||||
engine.Execute("local t = obj.getpixelregion(0, 0, 1, 1) obj.x = t[1] obj.y = t[2] obj.z = t[3] obj.alpha = t[4]", ctx);
|
||||
|
||||
Assert.Equal(200d, ctx.X);
|
||||
Assert.Equal(100d, ctx.Y);
|
||||
Assert.Equal(50d, ctx.Z);
|
||||
Assert.Equal(255d, ctx.Alpha);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void GetPixelRegion_OutOfBounds_YieldsTransparent()
|
||||
{
|
||||
using var engine = CreateEngine();
|
||||
var ctx = NewContext(Bgra((10, 20, 30, 255)), 1, 1);
|
||||
|
||||
engine.Execute("local t = obj.getpixelregion(1, 0, 1, 1) obj.x = t[1] + t[2] + t[3] + t[4]", ctx);
|
||||
|
||||
Assert.Equal(0d, ctx.X);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void PutPixelRegion_WritesPremultipliedColor()
|
||||
{
|
||||
using var engine = CreateEngine();
|
||||
var ctx = NewContext(new byte[2 * 1 * 4], 2, 1);
|
||||
|
||||
engine.Execute("obj.putpixelregion(0, 0, 2, 1, {200, 100, 50, 255, 10, 20, 30, 255})", ctx);
|
||||
|
||||
var buffer = ctx.GetPixelBuffer()!;
|
||||
Assert.Equal(new byte[] { 50, 100, 200, 255 }, buffer.AsSpan(0, 4).ToArray());
|
||||
Assert.Equal(new byte[] { 30, 20, 10, 255 }, buffer.AsSpan(4, 4).ToArray());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void RegionRoundTrip_PreservesOpaquePixels()
|
||||
{
|
||||
using var engine = CreateEngine();
|
||||
var original = Bgra((10, 20, 30, 255), (40, 50, 60, 255), (70, 80, 90, 255), (100, 110, 120, 255));
|
||||
var ctx = NewContext((byte[])original.Clone(), 2, 2);
|
||||
|
||||
engine.Execute(
|
||||
"local t = obj.getpixelregion(0, 0, obj.w, obj.h) obj.fill(0, 0, 0, 0) obj.putpixelregion(0, 0, obj.w, obj.h, t)",
|
||||
ctx);
|
||||
|
||||
Assert.Equal(original, ctx.GetPixelBuffer());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Convolve_Identity_LeavesOpaqueBufferUnchanged()
|
||||
{
|
||||
using var engine = CreateEngine();
|
||||
var original = Bgra((10, 20, 30, 255), (40, 50, 60, 255), (70, 80, 90, 255), (100, 110, 120, 255));
|
||||
var ctx = NewContext((byte[])original.Clone(), 2, 2);
|
||||
|
||||
engine.Execute("obj.convolve({0, 0, 0, 0, 1, 0, 0, 0, 0}, 3)", ctx);
|
||||
|
||||
Assert.Equal(original, ctx.GetPixelBuffer());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Convolve_BoxBlur_AveragesHorizontalStep()
|
||||
{
|
||||
using var engine = CreateEngine();
|
||||
var ctx = NewContext(Bgra((0, 0, 0, 255), (255, 255, 255, 255)), 2, 1);
|
||||
|
||||
engine.Execute("obj.convolve({1, 1, 1, 1, 1, 1, 1, 1, 1}, 3)", ctx);
|
||||
|
||||
var buffer = ctx.GetPixelBuffer()!;
|
||||
Assert.Equal(85, buffer[2]);
|
||||
Assert.Equal(85, buffer[1]);
|
||||
Assert.Equal(85, buffer[0]);
|
||||
Assert.Equal(170, buffer[6]);
|
||||
Assert.Equal(255, buffer[3]);
|
||||
Assert.Equal(255, buffer[7]);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Resize_Nearest_ReplicatesBlocks()
|
||||
{
|
||||
using var engine = CreateEngine();
|
||||
var ctx = NewContext(Bgra((11, 12, 13, 255), (21, 22, 23, 255), (31, 32, 33, 255), (41, 42, 43, 255)), 2, 2);
|
||||
|
||||
engine.Execute("obj.resize(4, 4, 'nearest')", ctx);
|
||||
|
||||
Assert.Equal(4, ctx.ImageWidth);
|
||||
Assert.Equal(4, ctx.ImageHeight);
|
||||
Assert.True(ctx.BufferReplaced);
|
||||
|
||||
var buffer = ctx.GetPixelBuffer()!;
|
||||
byte SampleR(int x, int y) => buffer[(y * 4 + x) * 4 + 2];
|
||||
Assert.Equal(13, SampleR(0, 0));
|
||||
Assert.Equal(13, SampleR(1, 1));
|
||||
Assert.Equal(23, SampleR(2, 0));
|
||||
Assert.Equal(33, SampleR(0, 2));
|
||||
Assert.Equal(43, SampleR(3, 3));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Resize_UpdatesObjDimensions()
|
||||
{
|
||||
using var engine = CreateEngine();
|
||||
var ctx = NewContext(new byte[4 * 4 * 4], 4, 4);
|
||||
|
||||
engine.Execute("obj.resize(8, 2) obj.x = obj.w obj.y = obj.h obj.z = obj.diagonal", ctx);
|
||||
|
||||
Assert.Equal(8, ctx.ImageWidth);
|
||||
Assert.Equal(2, ctx.ImageHeight);
|
||||
Assert.Equal(8d, ctx.X);
|
||||
Assert.Equal(2d, ctx.Y);
|
||||
Assert.Equal(Math.Sqrt(8d * 8d + 2d * 2d), ctx.Z);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,164 @@
|
||||
using LuaScript;
|
||||
|
||||
namespace LuaScript.Tests
|
||||
{
|
||||
public sealed class LuaScriptEngineGetAudioTests
|
||||
{
|
||||
private sealed class StubMediaLoader : IMediaSourceLoader
|
||||
{
|
||||
public byte[] RenderText(string text, string fontFamily, double fontSize, bool bold, bool italic, int colorRgb, out int width, out int height)
|
||||
{
|
||||
width = 1;
|
||||
height = 1;
|
||||
return new byte[4];
|
||||
}
|
||||
|
||||
public byte[] DecodeImage(string path, out int width, out int height)
|
||||
{
|
||||
width = 1;
|
||||
height = 1;
|
||||
return new byte[4];
|
||||
}
|
||||
|
||||
public byte[] DecodeMovie(string path, double time, out int width, out int height)
|
||||
{
|
||||
width = 1;
|
||||
height = 1;
|
||||
return new byte[4];
|
||||
}
|
||||
|
||||
public void Dispose() { }
|
||||
}
|
||||
|
||||
private static LuaScriptEngine CreateEngine() => new(static () => new StubMediaLoader());
|
||||
|
||||
private static AviUtlScriptContext NewContext()
|
||||
{
|
||||
return new AviUtlScriptContext
|
||||
{
|
||||
ImageWidth = 2,
|
||||
ImageHeight = 2,
|
||||
Framerate = 30,
|
||||
};
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void GetAudio_FillsBufferTableFromLoader()
|
||||
{
|
||||
using var engine = CreateEngine();
|
||||
var ctx = NewContext();
|
||||
|
||||
string? capturedFile = null;
|
||||
string? capturedType = null;
|
||||
int capturedSize = -1;
|
||||
ctx.AudioLoader = (file, type, size) =>
|
||||
{
|
||||
capturedFile = file;
|
||||
capturedType = type;
|
||||
capturedSize = size;
|
||||
return (3, 44100, [1.5d, -2.5d, 3d]);
|
||||
};
|
||||
|
||||
engine.Execute(
|
||||
"local buf = {}\n" +
|
||||
"local n, rate = obj.getaudio(buf, 'audiobuffer', 'pcm', 3)\n" +
|
||||
"obj.x = n\n" +
|
||||
"obj.y = rate\n" +
|
||||
"obj.z = buf[1]\n" +
|
||||
"obj.ox = buf[2]\n" +
|
||||
"obj.oy = buf[3]",
|
||||
ctx);
|
||||
|
||||
Assert.Equal("audiobuffer", capturedFile);
|
||||
Assert.Equal("pcm", capturedType);
|
||||
Assert.Equal(3, capturedSize);
|
||||
Assert.Equal(3d, ctx.X);
|
||||
Assert.Equal(44100d, ctx.Y);
|
||||
Assert.Equal(1.5d, ctx.Z);
|
||||
Assert.Equal(-2.5d, ctx.Ox);
|
||||
Assert.Equal(3d, ctx.Oy);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void GetAudio_NilBuffer_ReturnsTableAsThirdValue()
|
||||
{
|
||||
using var engine = CreateEngine();
|
||||
var ctx = NewContext();
|
||||
|
||||
ctx.AudioLoader = (_, type, _) => (2, 48000, [7d, 8d]);
|
||||
|
||||
engine.Execute(
|
||||
"local n, rate, buf = obj.getaudio(nil, 'C:/test.wav', 'spectrum.r', 2)\n" +
|
||||
"obj.x = n\n" +
|
||||
"obj.y = rate\n" +
|
||||
"obj.z = buf[1]\n" +
|
||||
"obj.ox = buf[2]",
|
||||
ctx);
|
||||
|
||||
Assert.Equal(2d, ctx.X);
|
||||
Assert.Equal(48000d, ctx.Y);
|
||||
Assert.Equal(7d, ctx.Z);
|
||||
Assert.Equal(8d, ctx.Ox);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void GetAudio_DefaultsTypeToPcm()
|
||||
{
|
||||
using var engine = CreateEngine();
|
||||
var ctx = NewContext();
|
||||
|
||||
string? capturedType = null;
|
||||
int capturedSize = -1;
|
||||
ctx.AudioLoader = (_, type, size) =>
|
||||
{
|
||||
capturedType = type;
|
||||
capturedSize = size;
|
||||
return (0, 48000, []);
|
||||
};
|
||||
|
||||
engine.Execute("obj.x = obj.getaudio({}, 'audiobuffer')", ctx);
|
||||
|
||||
Assert.Equal("pcm", capturedType);
|
||||
Assert.Equal(0, capturedSize);
|
||||
Assert.Equal(0d, ctx.X);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void GetAudio_WithoutLoader_ReturnsZero()
|
||||
{
|
||||
using var engine = CreateEngine();
|
||||
var ctx = NewContext();
|
||||
|
||||
engine.Execute(
|
||||
"local n, rate, buf = obj.getaudio(nil, 'audiobuffer', 'pcm', 8)\n" +
|
||||
"obj.x = n\n" +
|
||||
"obj.y = rate\n" +
|
||||
"obj.z = #buf\n" +
|
||||
"obj.ox = obj.getaudio({}, 7)",
|
||||
ctx);
|
||||
|
||||
Assert.Equal(0d, ctx.X);
|
||||
Assert.Equal(0d, ctx.Y);
|
||||
Assert.Equal(0d, ctx.Z);
|
||||
Assert.Equal(0d, ctx.Ox);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void GetAudio_ClampsCountToDataLength()
|
||||
{
|
||||
using var engine = CreateEngine();
|
||||
var ctx = NewContext();
|
||||
|
||||
ctx.AudioLoader = (_, _, _) => (10, 48000, [5d]);
|
||||
|
||||
engine.Execute(
|
||||
"local n, _, buf = obj.getaudio(nil, 'audiobuffer', 'pcm', 10)\n" +
|
||||
"obj.x = n\n" +
|
||||
"obj.y = #buf",
|
||||
ctx);
|
||||
|
||||
Assert.Equal(1d, ctx.X);
|
||||
Assert.Equal(1d, ctx.Y);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -130,6 +130,45 @@ namespace LuaScript.Tests
|
||||
Assert.Equal(1d, ctx.Oy);
|
||||
}
|
||||
|
||||
private sealed class StubResolver : ISceneObjectResolver
|
||||
{
|
||||
private readonly SceneObjectInfo _info;
|
||||
public StubResolver(SceneObjectInfo info) => _info = info;
|
||||
public bool TryResolve(string tag, int timelineFrame, out SceneObjectInfo info)
|
||||
{
|
||||
if (tag == _info.Tag)
|
||||
{
|
||||
info = _info;
|
||||
return true;
|
||||
}
|
||||
info = default;
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void GetObjectExposesItemMetadata()
|
||||
{
|
||||
using var engine = CreateEngine();
|
||||
var ctx = NewContext();
|
||||
var info = new SceneObjectInfo("a", true, 12d, 34d, 56d, 2d, 90d, 200d, 7, 120, 75d, "reimu", "hello", "VoiceItem");
|
||||
ctx.ResolverProvider = () => new StubResolver(info);
|
||||
|
||||
engine.Execute(
|
||||
"local o = obj.getobject('a')\n" +
|
||||
"obj.x = o.volume\n" +
|
||||
"obj.y = o.length\n" +
|
||||
"obj.z = (o.character == 'reimu') and 1 or 0\n" +
|
||||
"obj.ox = (o.text == 'hello') and 1 or 0\n" +
|
||||
"obj.oy = (o.kind == 'VoiceItem') and 1 or 0", ctx);
|
||||
|
||||
Assert.Equal(75d, ctx.X);
|
||||
Assert.Equal(120d, ctx.Y);
|
||||
Assert.Equal(1d, ctx.Z);
|
||||
Assert.Equal(1d, ctx.Ox);
|
||||
Assert.Equal(1d, ctx.Oy);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void ObjectWritesFlowBackToContext()
|
||||
{
|
||||
|
||||
@@ -0,0 +1,249 @@
|
||||
using LuaScript;
|
||||
|
||||
namespace LuaScript.Tests
|
||||
{
|
||||
public sealed class LuaScriptEngineSceneBrushLoadTests
|
||||
{
|
||||
private sealed class StubMediaLoader : IMediaSourceLoader
|
||||
{
|
||||
public byte[] RenderText(string text, string fontFamily, double fontSize, bool bold, bool italic, int colorRgb, out int width, out int height)
|
||||
{
|
||||
width = 1;
|
||||
height = 1;
|
||||
return new byte[4];
|
||||
}
|
||||
|
||||
public byte[] DecodeImage(string path, out int width, out int height)
|
||||
{
|
||||
width = 1;
|
||||
height = 1;
|
||||
return new byte[4];
|
||||
}
|
||||
|
||||
public byte[] DecodeMovie(string path, double time, out int width, out int height)
|
||||
{
|
||||
width = 1;
|
||||
height = 1;
|
||||
return new byte[4];
|
||||
}
|
||||
|
||||
public void Dispose() { }
|
||||
}
|
||||
|
||||
private static LuaScriptEngine CreateEngine() => new(static () => new StubMediaLoader());
|
||||
|
||||
private static AviUtlScriptContext NewContext()
|
||||
{
|
||||
return new AviUtlScriptContext
|
||||
{
|
||||
ImageWidth = 6,
|
||||
ImageHeight = 4,
|
||||
Time = 1.5,
|
||||
Framerate = 30,
|
||||
};
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void LoadScene_ReplacesBufferAndUpdatesObjDimensions()
|
||||
{
|
||||
using var engine = CreateEngine();
|
||||
var ctx = NewContext();
|
||||
|
||||
string? capturedName = null;
|
||||
double capturedTime = -1;
|
||||
var rendered = new byte[2 * 3 * 4];
|
||||
ctx.SceneImageLoader = (name, time) =>
|
||||
{
|
||||
capturedName = name;
|
||||
capturedTime = time;
|
||||
return (rendered, 2, 3);
|
||||
};
|
||||
|
||||
engine.Execute("obj.load('scene', 'サブ', 4.25); obj.x = obj.w; obj.y = obj.h", ctx);
|
||||
|
||||
Assert.Equal("サブ", capturedName);
|
||||
Assert.Equal(4.25d, capturedTime);
|
||||
Assert.True(ctx.BufferReplaced);
|
||||
Assert.Same(rendered, ctx.GetPixelBuffer());
|
||||
Assert.Equal(2, ctx.ImageWidth);
|
||||
Assert.Equal(3, ctx.ImageHeight);
|
||||
Assert.Equal(2d, ctx.X);
|
||||
Assert.Equal(3d, ctx.Y);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void LoadScene_DefaultsTimeToObjTime()
|
||||
{
|
||||
using var engine = CreateEngine();
|
||||
var ctx = NewContext();
|
||||
|
||||
double capturedTime = -1;
|
||||
ctx.SceneImageLoader = (_, time) =>
|
||||
{
|
||||
capturedTime = time;
|
||||
return ([], 0, 0);
|
||||
};
|
||||
|
||||
engine.Execute("obj.load('scene', 'サブ')", ctx);
|
||||
|
||||
Assert.Equal(1.5d, capturedTime);
|
||||
Assert.False(ctx.BufferReplaced);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void LoadScene_WithoutLoader_IsNoOp()
|
||||
{
|
||||
using var engine = CreateEngine();
|
||||
var ctx = NewContext();
|
||||
|
||||
engine.Execute("obj.load('scene', 'サブ'); obj.x = obj.w", ctx);
|
||||
|
||||
Assert.False(ctx.BufferReplaced);
|
||||
Assert.Equal(6d, ctx.X);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void LoadBrush_ReplacesBufferWithRequestedSize()
|
||||
{
|
||||
using var engine = CreateEngine();
|
||||
var ctx = NewContext();
|
||||
|
||||
string? capturedName = null;
|
||||
double capturedW = -1, capturedH = -1;
|
||||
var rendered = new byte[8 * 5 * 4];
|
||||
ctx.BrushImageLoader = (name, w, h, _) =>
|
||||
{
|
||||
capturedName = name;
|
||||
capturedW = w;
|
||||
capturedH = h;
|
||||
return (rendered, 8, 5);
|
||||
};
|
||||
|
||||
engine.Execute("obj.load('brush', '縞模様', 8, 5); obj.x = obj.w; obj.y = obj.h", ctx);
|
||||
|
||||
Assert.Equal("縞模様", capturedName);
|
||||
Assert.Equal(8d, capturedW);
|
||||
Assert.Equal(5d, capturedH);
|
||||
Assert.True(ctx.BufferReplaced);
|
||||
Assert.Same(rendered, ctx.GetPixelBuffer());
|
||||
Assert.Equal(8d, ctx.X);
|
||||
Assert.Equal(5d, ctx.Y);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void LoadBrush_DefaultsSizeToObjectDimensions()
|
||||
{
|
||||
using var engine = CreateEngine();
|
||||
var ctx = NewContext();
|
||||
|
||||
double capturedW = -1, capturedH = -1;
|
||||
ctx.BrushImageLoader = (_, w, h, _) =>
|
||||
{
|
||||
capturedW = w;
|
||||
capturedH = h;
|
||||
return ([], 0, 0);
|
||||
};
|
||||
|
||||
engine.Execute("obj.load('brush', '市松模様')", ctx);
|
||||
|
||||
Assert.Equal(6d, capturedW);
|
||||
Assert.Equal(4d, capturedH);
|
||||
Assert.False(ctx.BufferReplaced);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Brush_PassesParameterPairs()
|
||||
{
|
||||
using var engine = CreateEngine();
|
||||
var ctx = NewContext();
|
||||
|
||||
string? capturedName = null;
|
||||
double capturedW = -1, capturedH = -1;
|
||||
List<KeyValuePair<string, object>>? captured = null;
|
||||
var rendered = new byte[6 * 4 * 4];
|
||||
ctx.BrushImageLoader = (name, w, h, arguments) =>
|
||||
{
|
||||
capturedName = name;
|
||||
capturedW = w;
|
||||
capturedH = h;
|
||||
captured = [.. arguments];
|
||||
return (rendered, 6, 4);
|
||||
};
|
||||
|
||||
engine.Execute("obj.brush('縞模様', '色1', 0xff0000, 'ズーム', 250, '有効', true, 'ラベル', 'abc')", ctx);
|
||||
|
||||
Assert.Equal("縞模様", capturedName);
|
||||
Assert.Equal(6d, capturedW);
|
||||
Assert.Equal(4d, capturedH);
|
||||
Assert.NotNull(captured);
|
||||
Assert.Equal(4, captured!.Count);
|
||||
Assert.Equal(new KeyValuePair<string, object>("色1", (double)0xff0000), captured[0]);
|
||||
Assert.Equal(new KeyValuePair<string, object>("ズーム", 250d), captured[1]);
|
||||
Assert.Equal(new KeyValuePair<string, object>("有効", true), captured[2]);
|
||||
Assert.Equal(new KeyValuePair<string, object>("ラベル", "abc"), captured[3]);
|
||||
Assert.True(ctx.BufferReplaced);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Brush_AcceptsLeadingSizeBeforePairs()
|
||||
{
|
||||
using var engine = CreateEngine();
|
||||
var ctx = NewContext();
|
||||
|
||||
double capturedW = -1, capturedH = -1;
|
||||
List<KeyValuePair<string, object>>? captured = null;
|
||||
ctx.BrushImageLoader = (_, w, h, arguments) =>
|
||||
{
|
||||
capturedW = w;
|
||||
capturedH = h;
|
||||
captured = [.. arguments];
|
||||
return ([], 0, 0);
|
||||
};
|
||||
|
||||
engine.Execute("obj.brush('市松模様', 320, 240, 'ズーム', 50)", ctx);
|
||||
|
||||
Assert.Equal(320d, capturedW);
|
||||
Assert.Equal(240d, capturedH);
|
||||
Assert.NotNull(captured);
|
||||
Assert.Equal(new KeyValuePair<string, object>("ズーム", 50d), Assert.Single(captured!));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Brush_WithoutPairs_UsesObjectDimensions()
|
||||
{
|
||||
using var engine = CreateEngine();
|
||||
var ctx = NewContext();
|
||||
|
||||
double capturedW = -1, capturedH = -1;
|
||||
int capturedCount = -1;
|
||||
ctx.BrushImageLoader = (_, w, h, arguments) =>
|
||||
{
|
||||
capturedW = w;
|
||||
capturedH = h;
|
||||
capturedCount = arguments.Count;
|
||||
return ([], 0, 0);
|
||||
};
|
||||
|
||||
engine.Execute("obj.brush('市松模様')", ctx);
|
||||
|
||||
Assert.Equal(6d, capturedW);
|
||||
Assert.Equal(4d, capturedH);
|
||||
Assert.Equal(0, capturedCount);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void LoadBrush_FailureKeepsCurrentImage()
|
||||
{
|
||||
using var engine = CreateEngine();
|
||||
var ctx = NewContext();
|
||||
|
||||
ctx.BrushImageLoader = (_, _, _, _) => ([], 0, 0);
|
||||
|
||||
engine.Execute("obj.load('brush', '不明'); obj.x = obj.w; obj.y = obj.h", ctx);
|
||||
|
||||
Assert.False(ctx.BufferReplaced);
|
||||
Assert.Equal(6d, ctx.X);
|
||||
Assert.Equal(4d, ctx.Y);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -578,5 +578,95 @@ namespace LuaScript.Tests
|
||||
{
|
||||
Assert.Equal("for i = 0, 10 do end", Rewrite("for i in <0..10> do end"));
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[InlineData("[fast] obj.fill(0, 0, 0, 255)", " __fast_fill(0, 0, 0, 255)")]
|
||||
[InlineData("[fast] obj.convolve(k, 3)", " __fast_convolve(k, 3)")]
|
||||
[InlineData("[fast] obj.resize(100, 100)", " __fast_resize(100, 100)")]
|
||||
[InlineData("[ fast ] obj.resize(100, 100)", " __fast_resize(100, 100)")]
|
||||
[InlineData("[fast]obj.fill()", "__fast_fill()")]
|
||||
[InlineData(" [fast] obj.fill()", " __fast_fill()")]
|
||||
public void Fast_RewritesAcceleratedPrimitive(string source, string expected)
|
||||
{
|
||||
Assert.Equal(expected, Rewrite(source));
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[InlineData("[fast]\nobj.fill(0, 0, 0, 255)", "\n__fast_fill(0, 0, 0, 255)")]
|
||||
[InlineData("[fast]\nobj.convolve(k, 3)", "\n__fast_convolve(k, 3)")]
|
||||
[InlineData("[fast]\nobj.resize(64, 64)", "\n__fast_resize(64, 64)")]
|
||||
[InlineData("obj.x = 1\n[fast]\nobj.resize(64, 64)", "obj.x = 1\n\n__fast_resize(64, 64)")]
|
||||
public void Fast_MarkerOnOwnLine_RewritesNextStatement(string source, string expected)
|
||||
{
|
||||
Assert.Equal(expected, Rewrite(source));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Fast_MarkerOnOwnLine_ReportsDiagnosticOnMarkerLine()
|
||||
{
|
||||
var (code, _, diagnostics) = LuaSyntaxExtensions.RewriteWithMap("obj.x = 1\n[fast]\nobj.draw(0)");
|
||||
Assert.Equal("obj.x = 1\n\nobj.draw(0)", code);
|
||||
var diagnostic = Assert.Single(diagnostics);
|
||||
Assert.Equal(2, diagnostic.Line);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Fast_KeywordIsRegisteredInCatalog()
|
||||
{
|
||||
Assert.Contains("fast", LuaScript.Compat.Syntax.LuaSyntaxRuleRegistry.CatalogKeywords);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Fast_RewritesInsideBlock()
|
||||
{
|
||||
Assert.Equal(
|
||||
"for i = 1, 3 do __fast_fill(i, i, i, 255) end",
|
||||
Rewrite("for i in <1..3> do [fast] obj.fill(i, i, i, 255) end"));
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[InlineData("x = t[fast]")]
|
||||
[InlineData("x = obj.data[fast]")]
|
||||
[InlineData("x = f()[fast]")]
|
||||
[InlineData("t = { [fast] = 1 }")]
|
||||
[InlineData("x = \"[fast] obj.fill()\"")]
|
||||
[InlineData("-- [fast] obj.fill()")]
|
||||
public void Fast_DoesNotTouchNonMarkerBrackets(string source)
|
||||
{
|
||||
Assert.Equal(source, Rewrite(source));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Fast_OnUnsupportedTargetStripsMarkerAndReportsDiagnostic()
|
||||
{
|
||||
var (code, _, diagnostics) = LuaSyntaxExtensions.RewriteWithMap("[fast] obj.draw(0)");
|
||||
Assert.Equal(" obj.draw(0)", code);
|
||||
var diagnostic = Assert.Single(diagnostics);
|
||||
Assert.Equal(1, diagnostic.Line);
|
||||
Assert.Contains("fast", diagnostic.Message);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Fast_OnNonObjTargetReportsDiagnostic()
|
||||
{
|
||||
var (code, _, diagnostics) = LuaSyntaxExtensions.RewriteWithMap("[fast] local x = 1");
|
||||
Assert.Equal(" local x = 1", code);
|
||||
Assert.Single(diagnostics);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Fast_SupportedTargetEmitsNoDiagnostic()
|
||||
{
|
||||
var (_, _, diagnostics) = LuaSyntaxExtensions.RewriteWithMap("[fast] obj.fill(0, 0, 0, 255)");
|
||||
Assert.Empty(diagnostics);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Fast_ReportsDiagnosticLineWithinBlock()
|
||||
{
|
||||
var (_, _, diagnostics) = LuaSyntaxExtensions.RewriteWithMap("obj.x = 1\n[fast] obj.draw(0)");
|
||||
var diagnostic = Assert.Single(diagnostics);
|
||||
Assert.Equal(2, diagnostic.Line);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -22,9 +22,13 @@ namespace LuaScript.Tests
|
||||
|
||||
private readonly LuaJitWorker _worker = new(NativeDir, ScriptPath);
|
||||
|
||||
private Func<string, double, (byte[] buffer, int w, int h)> _loadScene = (_, _) => ([], 0, 0);
|
||||
private Func<string, double, double, System.Collections.Generic.IReadOnlyList<System.Collections.Generic.KeyValuePair<string, object>>, (byte[] buffer, int w, int h)> _loadBrush = (_, _, _, _) => ([], 0, 0);
|
||||
private Func<string, SceneValue> _sceneGet = _ => SceneValue.Nil;
|
||||
private Action<string, SceneValue> _sceneSet = (_, _) => { };
|
||||
private Func<string, string, int, (int Count, int Rate, double[] Data)> _loadAudio = (_, _, _) => (0, 0, []);
|
||||
private PixelShaderInvoke? _runPixelShader;
|
||||
private IPixelBufferProcessor? _pixelProcessor;
|
||||
|
||||
public void Dispose() => _worker.Dispose();
|
||||
|
||||
@@ -70,9 +74,11 @@ namespace LuaScript.Tests
|
||||
System.Runtime.InteropServices.Marshal.Copy(uploaded, 0, address, uploaded.Length);
|
||||
},
|
||||
width, height, timeoutMs,
|
||||
resolveObject, loadFigure, loadText, loadImage, loadMovie, addEffect, addDraw, setAnchor,
|
||||
resolveObject, loadFigure, loadText, loadImage, loadMovie, _loadScene, _loadBrush, addEffect, addDraw, setAnchor,
|
||||
_sceneGet, _sceneSet,
|
||||
_loadAudio,
|
||||
_runPixelShader,
|
||||
_pixelProcessor,
|
||||
out pixelsDirty, out bufferReplaced, out resultWidth, out resultHeight, out error);
|
||||
|
||||
resultPixels = null;
|
||||
@@ -106,9 +112,11 @@ namespace LuaScript.Tests
|
||||
observedCapacity = capacity;
|
||||
System.Runtime.InteropServices.Marshal.Copy(pixels, 0, address, pixels.Length);
|
||||
},
|
||||
w, h, 5000, NoResolver, NoLoadFigure, NoLoadText, NoLoadImage, NoLoadMovie, NoAddEffect, NoAddDraw, NoSetAnchor,
|
||||
w, h, 5000, NoResolver, NoLoadFigure, NoLoadText, NoLoadImage, NoLoadMovie, _loadScene, _loadBrush, NoAddEffect, NoAddDraw, NoSetAnchor,
|
||||
_sceneGet, _sceneSet,
|
||||
_loadAudio,
|
||||
_runPixelShader,
|
||||
null,
|
||||
out _, out _, out _, out _, out string? error);
|
||||
|
||||
Assert.True(ok, error);
|
||||
@@ -523,7 +531,7 @@ namespace LuaScript.Tests
|
||||
|
||||
var pixels = new byte[16];
|
||||
var fields = Fields(2, 2, 0d);
|
||||
var resolved = new SceneObjectInfo("a", true, 12d, 34d, 56d, 2d, 90d, 200d, 7);
|
||||
var resolved = new SceneObjectInfo("a", true, 12d, 34d, 56d, 2d, 90d, 200d, 7, 120, 75d, "reimu", "hello", "VoiceItem");
|
||||
Func<string, int, SceneObjectInfo?> resolver = (tag, frame) =>
|
||||
tag == "a" && frame == 5 ? resolved : null;
|
||||
|
||||
@@ -531,7 +539,11 @@ namespace LuaScript.Tests
|
||||
"local o = obj.getobject(\"a\", 5) " +
|
||||
"obj.x = o.x obj.y = o.y obj.z = o.z " +
|
||||
"obj.zoom = o.zoom obj.rz = o.rz obj.alpha = o.alpha " +
|
||||
"obj.sx = o.sy obj.rzr = o.rzr";
|
||||
"obj.sx = o.sy obj.rzr = o.rzr " +
|
||||
"obj.ox = o.volume obj.oy = o.length " +
|
||||
"obj.oz = (o.character == \"reimu\") and 1 or 0 " +
|
||||
"obj.rx = (o.text == \"hello\") and 1 or 0 " +
|
||||
"obj.ry = (o.kind == \"VoiceItem\") and 1 or 0";
|
||||
|
||||
bool ok = RunWorker(script, fields, NoStringParams, () => pixels, 2, 2, 5000, resolver, NoLoadFigure, NoLoadText, NoLoadImage, NoLoadMovie, NoAddEffect, NoAddDraw, NoSetAnchor, out _, out _, out _, out _, out _, out string? error);
|
||||
|
||||
@@ -544,6 +556,11 @@ namespace LuaScript.Tests
|
||||
Assert.Equal(200d, fields[NativeProtocol.Alpha]);
|
||||
Assert.Equal(2d, fields[NativeProtocol.Sx]);
|
||||
Assert.Equal(90d * Math.PI / 180d, fields[NativeProtocol.Rzr]);
|
||||
Assert.Equal(75d, fields[NativeProtocol.Ox]);
|
||||
Assert.Equal(120d, fields[NativeProtocol.Oy]);
|
||||
Assert.Equal(1d, fields[NativeProtocol.Oz]);
|
||||
Assert.Equal(1d, fields[NativeProtocol.Rx]);
|
||||
Assert.Equal(1d, fields[NativeProtocol.Ry]);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
@@ -557,7 +574,7 @@ namespace LuaScript.Tests
|
||||
Func<string, int, SceneObjectInfo?> resolver = (tag, frame) =>
|
||||
{
|
||||
calls++;
|
||||
return tag == "a" ? new SceneObjectInfo("a", true, x, 0, 0, 1, 0, 255, 0) : null;
|
||||
return tag == "a" ? new SceneObjectInfo("a", true, x, 0, 0, 1, 0, 255, 0, 0, 0d, "", "", "") : null;
|
||||
};
|
||||
|
||||
const string script =
|
||||
@@ -1027,6 +1044,215 @@ namespace LuaScript.Tests
|
||||
Assert.Equal(frame, newPixels!.AsSpan(0, frame.Length).ToArray());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void LoadScene_RoundTripsNameAndTime()
|
||||
{
|
||||
Assert.True(LuaJitWorker.IsAvailable(NativeDir), "native/luajit.exe must be present");
|
||||
|
||||
const int sw = 2, sh = 2;
|
||||
var rendered = new byte[sw * sh * 4];
|
||||
for (int i = 0; i < rendered.Length; i++)
|
||||
rendered[i] = (byte)((i * 13 + 1) & 0xFF);
|
||||
|
||||
string? capturedName = null;
|
||||
double capturedTime = -1;
|
||||
_loadScene = (name, time) =>
|
||||
{
|
||||
capturedName = name;
|
||||
capturedTime = time;
|
||||
return (rendered, sw, sh);
|
||||
};
|
||||
|
||||
var pixels = new byte[4 * 4 * 4];
|
||||
var fields = Fields(4, 4, 0d);
|
||||
|
||||
bool ok = RunWorker(
|
||||
"obj.load('scene', 'サブシーン', 2.5)",
|
||||
fields, NoStringParams, () => pixels, 4, 4, 5000, NoResolver, NoLoadFigure, NoLoadText, NoLoadImage, NoLoadMovie, NoAddEffect, NoAddDraw, NoSetAnchor,
|
||||
out bool dirty, out bool bufferReplaced, out byte[]? newPixels, out int rw, out int rh, out string? error);
|
||||
|
||||
Assert.True(ok, error);
|
||||
Assert.Equal("サブシーン", capturedName);
|
||||
Assert.Equal(2.5d, capturedTime);
|
||||
Assert.True(dirty);
|
||||
Assert.True(bufferReplaced);
|
||||
Assert.Equal(sw, rw);
|
||||
Assert.Equal(sh, rh);
|
||||
Assert.NotNull(newPixels);
|
||||
Assert.Equal(rendered, newPixels!.AsSpan(0, rendered.Length).ToArray());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void LoadScene_DefaultsTimeToObjTime_AndKeepsImageOnFailure()
|
||||
{
|
||||
Assert.True(LuaJitWorker.IsAvailable(NativeDir), "native/luajit.exe must be present");
|
||||
|
||||
double capturedTime = -1;
|
||||
_loadScene = (_, time) =>
|
||||
{
|
||||
capturedTime = time;
|
||||
return ([], 0, 0);
|
||||
};
|
||||
|
||||
var pixels = new byte[16];
|
||||
var fields = Fields(2, 2, 1.25d);
|
||||
|
||||
bool ok = RunWorker(
|
||||
"obj.load('scene', 'missing') obj.x = obj.w",
|
||||
fields, NoStringParams, () => pixels, 2, 2, 5000, NoResolver, NoLoadFigure, NoLoadText, NoLoadImage, NoLoadMovie, NoAddEffect, NoAddDraw, NoSetAnchor,
|
||||
out bool dirty, out bool bufferReplaced, out _, out _, out _, out string? error);
|
||||
|
||||
Assert.True(ok, error);
|
||||
Assert.Equal(1.25d, capturedTime);
|
||||
Assert.False(dirty);
|
||||
Assert.False(bufferReplaced);
|
||||
Assert.Equal(2d, fields[NativeProtocol.X]);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void LoadBrush_RoundTripsNameAndSize()
|
||||
{
|
||||
Assert.True(LuaJitWorker.IsAvailable(NativeDir), "native/luajit.exe must be present");
|
||||
|
||||
const int bw = 3, bh = 2;
|
||||
var rendered = new byte[bw * bh * 4];
|
||||
for (int i = 0; i < rendered.Length; i++)
|
||||
rendered[i] = (byte)((i * 11 + 2) & 0xFF);
|
||||
|
||||
string? capturedName = null;
|
||||
double capturedW = -1, capturedH = -1;
|
||||
_loadBrush = (name, w, h, _) =>
|
||||
{
|
||||
capturedName = name;
|
||||
capturedW = w;
|
||||
capturedH = h;
|
||||
return (rendered, bw, bh);
|
||||
};
|
||||
|
||||
var pixels = new byte[4 * 4 * 4];
|
||||
var fields = Fields(4, 4, 0d);
|
||||
|
||||
bool ok = RunWorker(
|
||||
"obj.load('brush', '縞模様', 3, 2)",
|
||||
fields, NoStringParams, () => pixels, 4, 4, 5000, NoResolver, NoLoadFigure, NoLoadText, NoLoadImage, NoLoadMovie, NoAddEffect, NoAddDraw, NoSetAnchor,
|
||||
out bool dirty, out bool bufferReplaced, out byte[]? newPixels, out int rw, out int rh, out string? error);
|
||||
|
||||
Assert.True(ok, error);
|
||||
Assert.Equal("縞模様", capturedName);
|
||||
Assert.Equal(3d, capturedW);
|
||||
Assert.Equal(2d, capturedH);
|
||||
Assert.True(dirty);
|
||||
Assert.True(bufferReplaced);
|
||||
Assert.Equal(bw, rw);
|
||||
Assert.Equal(bh, rh);
|
||||
Assert.NotNull(newPixels);
|
||||
Assert.Equal(rendered, newPixels!.AsSpan(0, rendered.Length).ToArray());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Brush_RoundTripsPairsAndDefaultSize()
|
||||
{
|
||||
Assert.True(LuaJitWorker.IsAvailable(NativeDir), "native/luajit.exe must be present");
|
||||
|
||||
const int bw = 2, bh = 2;
|
||||
var rendered = new byte[bw * bh * 4];
|
||||
for (int i = 0; i < rendered.Length; i++)
|
||||
rendered[i] = (byte)((i * 7 + 4) & 0xFF);
|
||||
|
||||
string? capturedName = null;
|
||||
double capturedW = -1, capturedH = -1;
|
||||
System.Collections.Generic.List<System.Collections.Generic.KeyValuePair<string, object>>? captured = null;
|
||||
_loadBrush = (name, w, h, arguments) =>
|
||||
{
|
||||
capturedName = name;
|
||||
capturedW = w;
|
||||
capturedH = h;
|
||||
captured = [.. arguments];
|
||||
return (rendered, bw, bh);
|
||||
};
|
||||
|
||||
var pixels = new byte[4 * 2 * 4];
|
||||
var fields = Fields(4, 2, 0d);
|
||||
|
||||
bool ok = RunWorker(
|
||||
"obj.brush('縞模様', '色1', 0xff0000, '有効', true, 'ラベル', 'abc')",
|
||||
fields, NoStringParams, () => pixels, 4, 2, 5000, NoResolver, NoLoadFigure, NoLoadText, NoLoadImage, NoLoadMovie, NoAddEffect, NoAddDraw, NoSetAnchor,
|
||||
out bool dirty, out bool bufferReplaced, out byte[]? newPixels, out int rw, out int rh, out string? error);
|
||||
|
||||
Assert.True(ok, error);
|
||||
Assert.Equal("縞模様", capturedName);
|
||||
Assert.Equal(4d, capturedW);
|
||||
Assert.Equal(2d, capturedH);
|
||||
Assert.NotNull(captured);
|
||||
Assert.Equal(3, captured!.Count);
|
||||
Assert.Equal(new System.Collections.Generic.KeyValuePair<string, object>("色1", (double)0xff0000), captured[0]);
|
||||
Assert.Equal(new System.Collections.Generic.KeyValuePair<string, object>("有効", true), captured[1]);
|
||||
Assert.Equal(new System.Collections.Generic.KeyValuePair<string, object>("ラベル", "abc"), captured[2]);
|
||||
Assert.True(dirty);
|
||||
Assert.True(bufferReplaced);
|
||||
Assert.Equal(bw, rw);
|
||||
Assert.Equal(bh, rh);
|
||||
Assert.NotNull(newPixels);
|
||||
Assert.Equal(rendered, newPixels!.AsSpan(0, rendered.Length).ToArray());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Brush_RoundTripsLeadingSize()
|
||||
{
|
||||
Assert.True(LuaJitWorker.IsAvailable(NativeDir), "native/luajit.exe must be present");
|
||||
|
||||
double capturedW = -1, capturedH = -1;
|
||||
int capturedCount = -1;
|
||||
_loadBrush = (_, w, h, arguments) =>
|
||||
{
|
||||
capturedW = w;
|
||||
capturedH = h;
|
||||
capturedCount = arguments.Count;
|
||||
return ([], 0, 0);
|
||||
};
|
||||
|
||||
var pixels = new byte[16];
|
||||
var fields = Fields(2, 2, 0d);
|
||||
|
||||
bool ok = RunWorker(
|
||||
"obj.brush('市松模様', 320, 240, 'ズーム', 50)",
|
||||
fields, NoStringParams, () => pixels, 2, 2, 5000, NoResolver, NoLoadFigure, NoLoadText, NoLoadImage, NoLoadMovie, NoAddEffect, NoAddDraw, NoSetAnchor,
|
||||
out bool dirty, out _, out _, out _, out _, out string? error);
|
||||
|
||||
Assert.True(ok, error);
|
||||
Assert.Equal(320d, capturedW);
|
||||
Assert.Equal(240d, capturedH);
|
||||
Assert.Equal(1, capturedCount);
|
||||
Assert.False(dirty);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void LoadBrush_DefaultsSizeToObjectDimensions()
|
||||
{
|
||||
Assert.True(LuaJitWorker.IsAvailable(NativeDir), "native/luajit.exe must be present");
|
||||
|
||||
double capturedW = -1, capturedH = -1;
|
||||
_loadBrush = (_, w, h, _) =>
|
||||
{
|
||||
capturedW = w;
|
||||
capturedH = h;
|
||||
return ([], 0, 0);
|
||||
};
|
||||
|
||||
var pixels = new byte[4 * 2 * 4];
|
||||
var fields = Fields(4, 2, 0d);
|
||||
|
||||
bool ok = RunWorker(
|
||||
"obj.load('brush', '市松模様')",
|
||||
fields, NoStringParams, () => pixels, 4, 2, 5000, NoResolver, NoLoadFigure, NoLoadText, NoLoadImage, NoLoadMovie, NoAddEffect, NoAddDraw, NoSetAnchor,
|
||||
out bool dirty, out _, out _, out _, out _, out string? error);
|
||||
|
||||
Assert.True(ok, error);
|
||||
Assert.Equal(4d, capturedW);
|
||||
Assert.Equal(2d, capturedH);
|
||||
Assert.False(dirty);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void GetValue_ReturnsObjFields()
|
||||
{
|
||||
@@ -1047,6 +1273,79 @@ namespace LuaScript.Tests
|
||||
Assert.Equal(0d, fields[NativeProtocol.Z]);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void GetAudio_RoundTripsThroughCallback()
|
||||
{
|
||||
Assert.True(LuaJitWorker.IsAvailable(NativeDir), "native/luajit.exe must be present");
|
||||
|
||||
string? capturedFile = null;
|
||||
string? capturedType = null;
|
||||
int capturedSize = -1;
|
||||
_loadAudio = (file, type, size) =>
|
||||
{
|
||||
capturedFile = file;
|
||||
capturedType = type;
|
||||
capturedSize = size;
|
||||
return (4, 48000, [10d, -20d, 30.5d, 40d]);
|
||||
};
|
||||
|
||||
var pixels = new byte[16];
|
||||
var fields = Fields(2, 2, 0d);
|
||||
const string script =
|
||||
"local buf = {}\n" +
|
||||
"local n, rate = obj.getaudio(buf, 'audiobuffer', 'pcm', 4)\n" +
|
||||
"obj.x = n\n" +
|
||||
"obj.y = rate\n" +
|
||||
"obj.z = buf[1]\n" +
|
||||
"obj.ox = buf[2]\n" +
|
||||
"obj.oy = buf[3]\n" +
|
||||
"obj.oz = buf[4]\n" +
|
||||
"local n2, rate2, buf2 = obj.getaudio(nil, 'C:/test.wav', 'spectrum.l', 2)\n" +
|
||||
"obj.sx = n2\n" +
|
||||
"obj.sy = buf2[1]";
|
||||
|
||||
bool ok = RunWorker(script, fields, NoStringParams, () => pixels, 2, 2, 5000, NoResolver, NoLoadFigure, NoLoadText, NoLoadImage, NoLoadMovie, NoAddEffect, NoAddDraw, NoSetAnchor, out _, out _, out _, out _, out _, out string? error);
|
||||
|
||||
Assert.True(ok, error);
|
||||
Assert.Equal("C:/test.wav", capturedFile);
|
||||
Assert.Equal("spectrum.l", capturedType);
|
||||
Assert.Equal(2, capturedSize);
|
||||
Assert.Equal(4d, fields[NativeProtocol.X]);
|
||||
Assert.Equal(48000d, fields[NativeProtocol.Y]);
|
||||
Assert.Equal(10d, fields[NativeProtocol.Z]);
|
||||
Assert.Equal(-20d, fields[NativeProtocol.Ox]);
|
||||
Assert.Equal(30.5d, fields[NativeProtocol.Oy]);
|
||||
Assert.Equal(40d, fields[NativeProtocol.Oz]);
|
||||
Assert.Equal(4d, fields[NativeProtocol.Sx]);
|
||||
Assert.Equal(10d, fields[NativeProtocol.Sy]);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void GetAudio_FailureYieldsZeroCount()
|
||||
{
|
||||
Assert.True(LuaJitWorker.IsAvailable(NativeDir), "native/luajit.exe must be present");
|
||||
|
||||
_loadAudio = (_, _, _) => throw new InvalidOperationException();
|
||||
|
||||
var pixels = new byte[16];
|
||||
var fields = Fields(2, 2, 0d);
|
||||
const string script =
|
||||
"local n, rate, buf = obj.getaudio(nil, 'audiobuffer', 'pcm', 8)\n" +
|
||||
"obj.x = n\n" +
|
||||
"obj.y = rate\n" +
|
||||
"obj.z = #buf\n" +
|
||||
"local n2 = obj.getaudio({}, 7)\n" +
|
||||
"obj.ox = n2";
|
||||
|
||||
bool ok = RunWorker(script, fields, NoStringParams, () => pixels, 2, 2, 5000, NoResolver, NoLoadFigure, NoLoadText, NoLoadImage, NoLoadMovie, NoAddEffect, NoAddDraw, NoSetAnchor, out _, out _, out _, out _, out _, out string? error);
|
||||
|
||||
Assert.True(ok, error);
|
||||
Assert.Equal(0d, fields[NativeProtocol.X]);
|
||||
Assert.Equal(0d, fields[NativeProtocol.Y]);
|
||||
Assert.Equal(0d, fields[NativeProtocol.Z]);
|
||||
Assert.Equal(0d, fields[NativeProtocol.Ox]);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void CopyBuffer_TmpSaveRestore_RoundTripsPixels()
|
||||
{
|
||||
@@ -1608,5 +1907,498 @@ namespace LuaScript.Tests
|
||||
Assert.True(ok2, error);
|
||||
Assert.Equal(7d, fields2[NativeProtocol.X]);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void PixelProcess_Fill_UsesHostProcessor()
|
||||
{
|
||||
Assert.True(LuaJitWorker.IsAvailable(NativeDir), "native/luajit.exe must be present");
|
||||
|
||||
const int w = 1024, h = 1024;
|
||||
var pixels = new byte[w * h * 4];
|
||||
var processor = new RecordingPixelProcessor { FillResult = true };
|
||||
_pixelProcessor = processor;
|
||||
|
||||
bool ok = RunWorker(
|
||||
"__fast_fill(10, 20, 30, 40, 0, 0, 1024, 1024)",
|
||||
Fields(w, h, 0d), NoStringParams, () => pixels, w, h, 5000, NoResolver, NoLoadFigure, NoLoadText, NoLoadImage, NoLoadMovie, NoAddEffect, NoAddDraw, NoSetAnchor,
|
||||
out bool dirty, out _, out _, out _, out _, out string? error);
|
||||
|
||||
Assert.True(ok, error);
|
||||
Assert.True(dirty);
|
||||
Assert.Equal(1, processor.FillCalls);
|
||||
Assert.Equal(0x41, pixels[0]);
|
||||
Assert.Equal(0x41, pixels[^1]);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void PixelProcess_Convolve_PassesKernelToHostProcessor()
|
||||
{
|
||||
Assert.True(LuaJitWorker.IsAvailable(NativeDir), "native/luajit.exe must be present");
|
||||
|
||||
const int w = 200, h = 200;
|
||||
var pixels = new byte[w * h * 4];
|
||||
var processor = new RecordingPixelProcessor { ConvolveResult = true };
|
||||
_pixelProcessor = processor;
|
||||
|
||||
bool ok = RunWorker(
|
||||
"__fast_convolve({1, 2, 3, 4, 5, 6, 7, 8, 9}, 3, 45, 6)",
|
||||
Fields(w, h, 0d), NoStringParams, () => pixels, w, h, 5000, NoResolver, NoLoadFigure, NoLoadText, NoLoadImage, NoLoadMovie, NoAddEffect, NoAddDraw, NoSetAnchor,
|
||||
out bool dirty, out _, out _, out _, out _, out string? error);
|
||||
|
||||
Assert.True(ok, error);
|
||||
Assert.True(dirty);
|
||||
Assert.Equal(1, processor.ConvolveCalls);
|
||||
Assert.Equal(3, processor.Size);
|
||||
Assert.Equal(45d, processor.Divisor);
|
||||
Assert.Equal(6d, processor.Offset);
|
||||
Assert.Equal(new double[] { 1, 2, 3, 4, 5, 6, 7, 8, 9 }, processor.Kernel);
|
||||
Assert.Equal(0x42, pixels[0]);
|
||||
Assert.Equal(0x42, pixels[^1]);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void PixelProcess_Resize_ReplacesBufferWithHostResult()
|
||||
{
|
||||
Assert.True(LuaJitWorker.IsAvailable(NativeDir), "native/luajit.exe must be present");
|
||||
|
||||
const int w = 2, h = 2;
|
||||
var pixels = new byte[w * h * 4];
|
||||
var processor = new RecordingPixelProcessor { ResizeResult = true };
|
||||
_pixelProcessor = processor;
|
||||
var fields = Fields(w, h, 0d);
|
||||
|
||||
bool ok = RunWorker(
|
||||
"__fast_resize(512, 512, 'nearest') obj.x = obj.w obj.y = obj.h",
|
||||
fields, NoStringParams, () => pixels, w, h, 5000, NoResolver, NoLoadFigure, NoLoadText, NoLoadImage, NoLoadMovie, NoAddEffect, NoAddDraw, NoSetAnchor,
|
||||
out bool dirty, out bool replaced, out byte[]? result, out int rw, out int rh, out string? error);
|
||||
|
||||
Assert.True(ok, error);
|
||||
Assert.True(dirty);
|
||||
Assert.True(replaced);
|
||||
Assert.Equal(512, rw);
|
||||
Assert.Equal(512, rh);
|
||||
Assert.Equal(512d, processor.TargetWidth);
|
||||
Assert.Equal(512d, processor.TargetHeight);
|
||||
Assert.False(processor.Linear);
|
||||
Assert.Equal(512d, fields[NativeProtocol.X]);
|
||||
Assert.Equal(512d, fields[NativeProtocol.Y]);
|
||||
Assert.NotNull(result);
|
||||
Assert.Equal(0x43, result![0]);
|
||||
Assert.Equal(0x43, result[^1]);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void PixelProcess_DefaultFill_UsesHostProcessor()
|
||||
{
|
||||
Assert.True(LuaJitWorker.IsAvailable(NativeDir), "native/luajit.exe must be present");
|
||||
|
||||
const int w = 1024, h = 1024;
|
||||
var pixels = new byte[w * h * 4];
|
||||
var processor = new RecordingPixelProcessor { FillResult = true };
|
||||
_pixelProcessor = processor;
|
||||
|
||||
bool ok = RunWorker(
|
||||
"obj.fill(10, 20, 30, 40, 0, 0, 1024, 1024)",
|
||||
Fields(w, h, 0d), NoStringParams, () => pixels, w, h, 5000, NoResolver, NoLoadFigure, NoLoadText, NoLoadImage, NoLoadMovie, NoAddEffect, NoAddDraw, NoSetAnchor,
|
||||
out bool dirty, out _, out _, out _, out _, out string? error);
|
||||
|
||||
Assert.True(ok, error);
|
||||
Assert.True(dirty);
|
||||
Assert.Equal(1, processor.FillCalls);
|
||||
Assert.Equal(0x41, pixels[0]);
|
||||
Assert.Equal(0x41, pixels[^1]);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void PixelProcess_DefaultConvolve_UsesHostProcessor()
|
||||
{
|
||||
Assert.True(LuaJitWorker.IsAvailable(NativeDir), "native/luajit.exe must be present");
|
||||
|
||||
const int w = 200, h = 200;
|
||||
var pixels = new byte[w * h * 4];
|
||||
var processor = new RecordingPixelProcessor { ConvolveResult = true };
|
||||
_pixelProcessor = processor;
|
||||
|
||||
bool ok = RunWorker(
|
||||
"obj.convolve({1, 2, 3, 4, 5, 6, 7, 8, 9}, 3, 45, 6)",
|
||||
Fields(w, h, 0d), NoStringParams, () => pixels, w, h, 5000, NoResolver, NoLoadFigure, NoLoadText, NoLoadImage, NoLoadMovie, NoAddEffect, NoAddDraw, NoSetAnchor,
|
||||
out bool dirty, out _, out _, out _, out _, out string? error);
|
||||
|
||||
Assert.True(ok, error);
|
||||
Assert.True(dirty);
|
||||
Assert.Equal(1, processor.ConvolveCalls);
|
||||
Assert.Equal(3, processor.Size);
|
||||
Assert.Equal(45d, processor.Divisor);
|
||||
Assert.Equal(6d, processor.Offset);
|
||||
Assert.Equal(new double[] { 1, 2, 3, 4, 5, 6, 7, 8, 9 }, processor.Kernel);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void PixelProcess_DefaultResize_UsesHostProcessor()
|
||||
{
|
||||
Assert.True(LuaJitWorker.IsAvailable(NativeDir), "native/luajit.exe must be present");
|
||||
|
||||
const int w = 2, h = 2;
|
||||
var pixels = new byte[w * h * 4];
|
||||
var processor = new RecordingPixelProcessor { ResizeResult = true };
|
||||
_pixelProcessor = processor;
|
||||
|
||||
bool ok = RunWorker(
|
||||
"obj.resize(512, 512, 'nearest')",
|
||||
Fields(w, h, 0d), NoStringParams, () => pixels, w, h, 5000, NoResolver, NoLoadFigure, NoLoadText, NoLoadImage, NoLoadMovie, NoAddEffect, NoAddDraw, NoSetAnchor,
|
||||
out _, out bool replaced, out _, out int rw, out int rh, out string? error);
|
||||
|
||||
Assert.True(ok, error);
|
||||
Assert.True(replaced);
|
||||
Assert.Equal(1, processor.ResizeCalls);
|
||||
Assert.Equal(512, rw);
|
||||
Assert.Equal(512, rh);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void PixelProcess_BelowThresholdFill_SkipsHostProcessor()
|
||||
{
|
||||
Assert.True(LuaJitWorker.IsAvailable(NativeDir), "native/luajit.exe must be present");
|
||||
|
||||
const int w = 64, h = 64;
|
||||
var pixels = new byte[w * h * 4];
|
||||
var processor = new RecordingPixelProcessor { FillResult = true };
|
||||
_pixelProcessor = processor;
|
||||
|
||||
bool ok = RunWorker(
|
||||
"obj.fill(10, 20, 30, 40)",
|
||||
Fields(w, h, 0d), NoStringParams, () => pixels, w, h, 5000, NoResolver, NoLoadFigure, NoLoadText, NoLoadImage, NoLoadMovie, NoAddEffect, NoAddDraw, NoSetAnchor,
|
||||
out _, out _, out _, out _, out _, out string? error);
|
||||
|
||||
Assert.True(ok, error);
|
||||
Assert.Equal(0, processor.FillCalls);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void PixelProcess_BelowThresholdConvolve_SkipsHostProcessor()
|
||||
{
|
||||
Assert.True(LuaJitWorker.IsAvailable(NativeDir), "native/luajit.exe must be present");
|
||||
|
||||
const int w = 8, h = 8;
|
||||
var pixels = new byte[w * h * 4];
|
||||
var processor = new RecordingPixelProcessor { ConvolveResult = true };
|
||||
_pixelProcessor = processor;
|
||||
|
||||
bool ok = RunWorker(
|
||||
"obj.convolve({1, 1, 1, 1, 1, 1, 1, 1, 1}, 3)",
|
||||
Fields(w, h, 0d), NoStringParams, () => pixels, w, h, 5000, NoResolver, NoLoadFigure, NoLoadText, NoLoadImage, NoLoadMovie, NoAddEffect, NoAddDraw, NoSetAnchor,
|
||||
out _, out _, out _, out _, out _, out string? error);
|
||||
|
||||
Assert.True(ok, error);
|
||||
Assert.Equal(0, processor.ConvolveCalls);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void PixelProcess_BelowThresholdResize_SkipsHostProcessor()
|
||||
{
|
||||
Assert.True(LuaJitWorker.IsAvailable(NativeDir), "native/luajit.exe must be present");
|
||||
|
||||
const int w = 2, h = 2;
|
||||
var pixels = new byte[w * h * 4];
|
||||
var processor = new RecordingPixelProcessor { ResizeResult = true };
|
||||
_pixelProcessor = processor;
|
||||
|
||||
bool ok = RunWorker(
|
||||
"obj.resize(4, 4, 'nearest')",
|
||||
Fields(w, h, 0d), NoStringParams, () => pixels, w, h, 5000, NoResolver, NoLoadFigure, NoLoadText, NoLoadImage, NoLoadMovie, NoAddEffect, NoAddDraw, NoSetAnchor,
|
||||
out _, out _, out _, out _, out _, out string? error);
|
||||
|
||||
Assert.True(ok, error);
|
||||
Assert.Equal(0, processor.ResizeCalls);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void HostCallbackTime_DoesNotConsumeScriptTimeout()
|
||||
{
|
||||
Assert.True(LuaJitWorker.IsAvailable(NativeDir), "native/luajit.exe must be present");
|
||||
|
||||
var decoded = new byte[4];
|
||||
Func<string, (byte[], int, int)> slowLoadImage = _ =>
|
||||
{
|
||||
System.Threading.Thread.Sleep(1500);
|
||||
return (decoded, 1, 1);
|
||||
};
|
||||
|
||||
var pixels = new byte[2 * 2 * 4];
|
||||
var fields = Fields(2, 2, 0d);
|
||||
|
||||
bool ok = RunWorker(
|
||||
"obj.load('image', 'C:/sample.png') obj.x = 5",
|
||||
fields, NoStringParams, () => pixels, 2, 2, 1000, NoResolver, NoLoadFigure, NoLoadText, slowLoadImage, NoLoadMovie, NoAddEffect, NoAddDraw, NoSetAnchor,
|
||||
out _, out _, out _, out _, out _, out string? error);
|
||||
|
||||
Assert.True(ok, error);
|
||||
Assert.Equal(5d, fields[NativeProtocol.X]);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Fill_WritesPremultipliedColor()
|
||||
{
|
||||
Assert.True(LuaJitWorker.IsAvailable(NativeDir), "native/luajit.exe must be present");
|
||||
|
||||
const int w = 2, h = 2;
|
||||
var pixels = new byte[w * h * 4];
|
||||
var fields = Fields(w, h, 0d);
|
||||
|
||||
bool ok = RunWorker(
|
||||
"obj.fill(200, 100, 50, 255)",
|
||||
fields, NoStringParams, () => pixels, w, h, 5000, NoResolver, NoLoadFigure, NoLoadText, NoLoadImage, NoLoadMovie, NoAddEffect, NoAddDraw, NoSetAnchor,
|
||||
out bool dirty, out _, out _, out _, out _, out string? error);
|
||||
|
||||
Assert.True(ok, error);
|
||||
Assert.True(dirty);
|
||||
for (int i = 0; i < w * h; i++)
|
||||
{
|
||||
Assert.Equal(50, pixels[i * 4 + 0]);
|
||||
Assert.Equal(100, pixels[i * 4 + 1]);
|
||||
Assert.Equal(200, pixels[i * 4 + 2]);
|
||||
Assert.Equal(255, pixels[i * 4 + 3]);
|
||||
}
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Fill_Rectangle_TouchesOnlyRequestedPixels()
|
||||
{
|
||||
Assert.True(LuaJitWorker.IsAvailable(NativeDir), "native/luajit.exe must be present");
|
||||
|
||||
const int w = 3, h = 1;
|
||||
var pixels = new byte[w * h * 4];
|
||||
var fields = Fields(w, h, 0d);
|
||||
|
||||
bool ok = RunWorker(
|
||||
"obj.fill(255, 255, 255, 255, 1, 0, 1, 1)",
|
||||
fields, NoStringParams, () => pixels, w, h, 5000, NoResolver, NoLoadFigure, NoLoadText, NoLoadImage, NoLoadMovie, NoAddEffect, NoAddDraw, NoSetAnchor,
|
||||
out bool dirty, out _, out _, out _, out _, out string? error);
|
||||
|
||||
Assert.True(ok, error);
|
||||
Assert.True(dirty);
|
||||
Assert.Equal(new byte[] { 0, 0, 0, 0 }, pixels.AsSpan(0, 4).ToArray());
|
||||
Assert.Equal(new byte[] { 255, 255, 255, 255 }, pixels.AsSpan(4, 4).ToArray());
|
||||
Assert.Equal(new byte[] { 0, 0, 0, 0 }, pixels.AsSpan(8, 4).ToArray());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void GetPixelRegion_ReturnsStraightRgba()
|
||||
{
|
||||
Assert.True(LuaJitWorker.IsAvailable(NativeDir), "native/luajit.exe must be present");
|
||||
|
||||
var pixels = new byte[] { 50, 100, 200, 255 };
|
||||
var fields = Fields(1, 1, 0d);
|
||||
|
||||
bool ok = RunWorker(
|
||||
"local t = obj.getpixelregion(0, 0, 1, 1) obj.x = t[1] obj.y = t[2] obj.z = t[3] obj.alpha = t[4]",
|
||||
fields, NoStringParams, () => pixels, 1, 1, 5000, NoResolver, NoLoadFigure, NoLoadText, NoLoadImage, NoLoadMovie, NoAddEffect, NoAddDraw, NoSetAnchor,
|
||||
out _, out _, out _, out _, out _, out string? error);
|
||||
|
||||
Assert.True(ok, error);
|
||||
Assert.Equal(200d, fields[NativeProtocol.X]);
|
||||
Assert.Equal(100d, fields[NativeProtocol.Y]);
|
||||
Assert.Equal(50d, fields[NativeProtocol.Z]);
|
||||
Assert.Equal(255d, fields[NativeProtocol.Alpha]);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void PutPixelRegion_WritesPremultipliedColor()
|
||||
{
|
||||
Assert.True(LuaJitWorker.IsAvailable(NativeDir), "native/luajit.exe must be present");
|
||||
|
||||
const int w = 2, h = 1;
|
||||
var pixels = new byte[w * h * 4];
|
||||
var fields = Fields(w, h, 0d);
|
||||
|
||||
bool ok = RunWorker(
|
||||
"obj.putpixelregion(0, 0, 2, 1, {200, 100, 50, 255, 10, 20, 30, 255})",
|
||||
fields, NoStringParams, () => pixels, w, h, 5000, NoResolver, NoLoadFigure, NoLoadText, NoLoadImage, NoLoadMovie, NoAddEffect, NoAddDraw, NoSetAnchor,
|
||||
out bool dirty, out _, out _, out _, out _, out string? error);
|
||||
|
||||
Assert.True(ok, error);
|
||||
Assert.True(dirty);
|
||||
Assert.Equal(new byte[] { 50, 100, 200, 255 }, pixels.AsSpan(0, 4).ToArray());
|
||||
Assert.Equal(new byte[] { 30, 20, 10, 255 }, pixels.AsSpan(4, 4).ToArray());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void RegionRoundTrip_PreservesOpaquePixels()
|
||||
{
|
||||
Assert.True(LuaJitWorker.IsAvailable(NativeDir), "native/luajit.exe must be present");
|
||||
|
||||
const int w = 2, h = 2;
|
||||
var pixels = new byte[]
|
||||
{
|
||||
10, 20, 30, 255, 40, 50, 60, 255,
|
||||
70, 80, 90, 255, 100, 110, 120, 255,
|
||||
};
|
||||
var original = (byte[])pixels.Clone();
|
||||
var fields = Fields(w, h, 0d);
|
||||
|
||||
bool ok = RunWorker(
|
||||
"local t = obj.getpixelregion(0, 0, obj.w, obj.h) obj.fill(0, 0, 0, 0) obj.putpixelregion(0, 0, obj.w, obj.h, t)",
|
||||
fields, NoStringParams, () => pixels, w, h, 5000, NoResolver, NoLoadFigure, NoLoadText, NoLoadImage, NoLoadMovie, NoAddEffect, NoAddDraw, NoSetAnchor,
|
||||
out bool dirty, out _, out _, out _, out _, out string? error);
|
||||
|
||||
Assert.True(ok, error);
|
||||
Assert.True(dirty);
|
||||
Assert.Equal(original, pixels);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Convolve_Identity_LeavesOpaqueBufferUnchanged()
|
||||
{
|
||||
Assert.True(LuaJitWorker.IsAvailable(NativeDir), "native/luajit.exe must be present");
|
||||
|
||||
const int w = 2, h = 2;
|
||||
var pixels = new byte[]
|
||||
{
|
||||
10, 20, 30, 255, 40, 50, 60, 255,
|
||||
70, 80, 90, 255, 100, 110, 120, 255,
|
||||
};
|
||||
var original = (byte[])pixels.Clone();
|
||||
var fields = Fields(w, h, 0d);
|
||||
|
||||
bool ok = RunWorker(
|
||||
"obj.convolve({0, 0, 0, 0, 1, 0, 0, 0, 0}, 3)",
|
||||
fields, NoStringParams, () => pixels, w, h, 5000, NoResolver, NoLoadFigure, NoLoadText, NoLoadImage, NoLoadMovie, NoAddEffect, NoAddDraw, NoSetAnchor,
|
||||
out bool dirty, out _, out _, out _, out _, out string? error);
|
||||
|
||||
Assert.True(ok, error);
|
||||
Assert.True(dirty);
|
||||
Assert.Equal(original, pixels);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Convolve_BoxBlur_AveragesHorizontalStep()
|
||||
{
|
||||
Assert.True(LuaJitWorker.IsAvailable(NativeDir), "native/luajit.exe must be present");
|
||||
|
||||
const int w = 2, h = 1;
|
||||
var pixels = new byte[] { 0, 0, 0, 255, 255, 255, 255, 255 };
|
||||
var fields = Fields(w, h, 0d);
|
||||
|
||||
bool ok = RunWorker(
|
||||
"obj.convolve({1, 1, 1, 1, 1, 1, 1, 1, 1}, 3)",
|
||||
fields, NoStringParams, () => pixels, w, h, 5000, NoResolver, NoLoadFigure, NoLoadText, NoLoadImage, NoLoadMovie, NoAddEffect, NoAddDraw, NoSetAnchor,
|
||||
out bool dirty, out _, out _, out _, out _, out string? error);
|
||||
|
||||
Assert.True(ok, error);
|
||||
Assert.True(dirty);
|
||||
Assert.Equal(85, pixels[0]);
|
||||
Assert.Equal(85, pixels[1]);
|
||||
Assert.Equal(85, pixels[2]);
|
||||
Assert.Equal(255, pixels[3]);
|
||||
Assert.Equal(170, pixels[6]);
|
||||
Assert.Equal(255, pixels[7]);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Resize_Nearest_ReplicatesBlocks()
|
||||
{
|
||||
Assert.True(LuaJitWorker.IsAvailable(NativeDir), "native/luajit.exe must be present");
|
||||
|
||||
const int w = 2, h = 2;
|
||||
var pixels = new byte[]
|
||||
{
|
||||
13, 12, 13, 255, 23, 22, 23, 255,
|
||||
33, 32, 33, 255, 43, 42, 43, 255,
|
||||
};
|
||||
var fields = Fields(w, h, 0d);
|
||||
|
||||
bool ok = RunWorker(
|
||||
"obj.resize(4, 4, 'nearest')",
|
||||
fields, NoStringParams, () => pixels, w, h, 5000, NoResolver, NoLoadFigure, NoLoadText, NoLoadImage, NoLoadMovie, NoAddEffect, NoAddDraw, NoSetAnchor,
|
||||
out bool dirty, out bool bufferReplaced, out byte[]? result, out int rw, out int rh, out string? error);
|
||||
|
||||
Assert.True(ok, error);
|
||||
Assert.True(dirty);
|
||||
Assert.True(bufferReplaced);
|
||||
Assert.Equal(4, rw);
|
||||
Assert.Equal(4, rh);
|
||||
Assert.NotNull(result);
|
||||
byte SampleR(int x, int y) => result![(y * 4 + x) * 4 + 2];
|
||||
Assert.Equal(13, SampleR(0, 0));
|
||||
Assert.Equal(13, SampleR(1, 1));
|
||||
Assert.Equal(23, SampleR(2, 0));
|
||||
Assert.Equal(33, SampleR(0, 2));
|
||||
Assert.Equal(43, SampleR(3, 3));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Resize_UpdatesObjDimensions()
|
||||
{
|
||||
Assert.True(LuaJitWorker.IsAvailable(NativeDir), "native/luajit.exe must be present");
|
||||
|
||||
var pixels = new byte[4 * 4 * 4];
|
||||
var fields = Fields(4, 4, 0d);
|
||||
|
||||
bool ok = RunWorker(
|
||||
"obj.resize(8, 2) obj.x = obj.w obj.y = obj.h obj.z = obj.diagonal",
|
||||
fields, NoStringParams, () => pixels, 4, 4, 5000, NoResolver, NoLoadFigure, NoLoadText, NoLoadImage, NoLoadMovie, NoAddEffect, NoAddDraw, NoSetAnchor,
|
||||
out _, out bool bufferReplaced, out _, out int rw, out int rh, out string? error);
|
||||
|
||||
Assert.True(ok, error);
|
||||
Assert.True(bufferReplaced);
|
||||
Assert.Equal(8, rw);
|
||||
Assert.Equal(2, rh);
|
||||
Assert.Equal(8d, fields[NativeProtocol.X]);
|
||||
Assert.Equal(2d, fields[NativeProtocol.Y]);
|
||||
Assert.Equal(Math.Sqrt(8d * 8d + 2d * 2d), fields[NativeProtocol.Z]);
|
||||
}
|
||||
|
||||
private sealed class RecordingPixelProcessor : IPixelBufferProcessor
|
||||
{
|
||||
public bool FillResult { get; init; }
|
||||
public bool ConvolveResult { get; init; }
|
||||
public bool ResizeResult { get; init; }
|
||||
public int FillCalls { get; private set; }
|
||||
public int ConvolveCalls { get; private set; }
|
||||
public int ResizeCalls { get; private set; }
|
||||
public int Size { get; private set; }
|
||||
public double Divisor { get; private set; }
|
||||
public double Offset { get; private set; }
|
||||
public double[] Kernel { get; private set; } = [];
|
||||
public int TargetWidth { get; private set; }
|
||||
public int TargetHeight { get; private set; }
|
||||
public bool Linear { get; private set; }
|
||||
|
||||
public bool TryFill(byte[] target, int width, int height, double r, double g, double b, double a, int x, int y, int fillWidth, int fillHeight)
|
||||
{
|
||||
FillCalls++;
|
||||
if (!FillResult)
|
||||
return false;
|
||||
Array.Fill(target, (byte)0x41, 0, width * height * 4);
|
||||
return true;
|
||||
}
|
||||
|
||||
public bool TryConvolve(byte[] target, int width, int height, double[] kernel, int size, double divisor, double offset)
|
||||
{
|
||||
ConvolveCalls++;
|
||||
Size = size;
|
||||
Divisor = divisor;
|
||||
Offset = offset;
|
||||
Kernel = kernel.AsSpan(0, size * size).ToArray();
|
||||
if (!ConvolveResult)
|
||||
return false;
|
||||
Array.Fill(target, (byte)0x42, 0, width * height * 4);
|
||||
return true;
|
||||
}
|
||||
|
||||
public bool TryResize(byte[] source, int sourceWidth, int sourceHeight, int targetWidth, int targetHeight, bool linear, out byte[]? target)
|
||||
{
|
||||
ResizeCalls++;
|
||||
TargetWidth = targetWidth;
|
||||
TargetHeight = targetHeight;
|
||||
Linear = linear;
|
||||
target = null;
|
||||
if (!ResizeResult)
|
||||
return false;
|
||||
target = new byte[targetWidth * targetHeight * 4];
|
||||
Array.Fill(target, (byte)0x43);
|
||||
return true;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -16,6 +16,9 @@
|
||||
<Project Path="LuaScript.Runtime/LuaScript.Runtime.csproj">
|
||||
<Platform Solution="*|x64" Project="Any CPU" />
|
||||
</Project>
|
||||
<Project Path="LuaScript.Gpu/LuaScript.Gpu.csproj">
|
||||
<Platform Solution="*|x64" Project="Any CPU" />
|
||||
</Project>
|
||||
<Project Path="LuaScript.Tests/LuaScript.Tests.csproj" />
|
||||
<Project Path="LuaScript/LuaScript.csproj">
|
||||
<Platform Solution="*|x64" Project="x64" />
|
||||
|
||||
@@ -0,0 +1,201 @@
|
||||
using System.Runtime.CompilerServices;
|
||||
using LuaScript.Compat;
|
||||
using YukkuriMovieMaker.ItemEditor;
|
||||
using YukkuriMovieMaker.Player.Audio.Effects;
|
||||
using YukkuriMovieMaker.Plugin;
|
||||
using YukkuriMovieMaker.Plugin.FileSource;
|
||||
using YukkuriMovieMaker.Project;
|
||||
using YukkuriMovieMaker.Project.Items;
|
||||
|
||||
namespace LuaScript
|
||||
{
|
||||
internal sealed class AudioSampleProvider : IDisposable
|
||||
{
|
||||
private readonly AviUtlAudioConverter _converter = new();
|
||||
private readonly double[] _data = new double[AviUtlAudioConverter.MaxSamples];
|
||||
private float[] _readBuffer = [];
|
||||
|
||||
private IAudioFileSource? _fileSource;
|
||||
private string _fileSourcePath = string.Empty;
|
||||
|
||||
private IAudioStream? _sceneSource;
|
||||
private Scene? _sceneSourceScene;
|
||||
|
||||
private IAudioStream? _itemSource;
|
||||
private IAudioItem? _itemSourceItem;
|
||||
private Scene? _itemSourceScene;
|
||||
private string? _itemSourceFile;
|
||||
|
||||
public double[] Data => _data;
|
||||
|
||||
public (int Count, int Rate) ReadFile(string path, double time, string type, int size)
|
||||
{
|
||||
try
|
||||
{
|
||||
if (_fileSource is null || !string.Equals(path, _fileSourcePath, StringComparison.Ordinal))
|
||||
{
|
||||
_fileSource?.Dispose();
|
||||
_fileSource = null;
|
||||
_fileSource = AudioFileSourceFactory.Create(path, 0);
|
||||
_fileSourcePath = path;
|
||||
}
|
||||
|
||||
var source = _fileSource;
|
||||
if (source is null || source.Hz <= 0)
|
||||
return (0, 0);
|
||||
|
||||
int floats = EnsureReadBuffer(type, size);
|
||||
if (floats <= 0)
|
||||
return (0, source.Hz);
|
||||
|
||||
source.Seek(TimeSpan.FromSeconds(Math.Max(0d, time)));
|
||||
int total = 0;
|
||||
while (total < floats)
|
||||
{
|
||||
int read = source.Read(_readBuffer, total, floats - total);
|
||||
if (read <= 0)
|
||||
break;
|
||||
total += read;
|
||||
}
|
||||
|
||||
return (_converter.Convert(type, _readBuffer, total / 2, size, _data), source.Hz);
|
||||
}
|
||||
catch
|
||||
{
|
||||
return (0, 0);
|
||||
}
|
||||
}
|
||||
|
||||
public (int Count, int Rate) ReadScene(Scene? scene, double time, string type, int size)
|
||||
{
|
||||
try
|
||||
{
|
||||
if (scene is null)
|
||||
return (0, 0);
|
||||
|
||||
if (_sceneSource is null || !ReferenceEquals(scene, _sceneSourceScene))
|
||||
{
|
||||
_sceneSource?.Dispose();
|
||||
_sceneSource = null;
|
||||
scene.TryCreateAudioSource(out _sceneSource);
|
||||
_sceneSourceScene = scene;
|
||||
}
|
||||
|
||||
return ReadStream(_sceneSource, time, type, size);
|
||||
}
|
||||
catch
|
||||
{
|
||||
return (0, 0);
|
||||
}
|
||||
}
|
||||
|
||||
public (int Count, int Rate) ReadItem(IAudioItem? item, Scene? scene, double time, string type, int size)
|
||||
{
|
||||
try
|
||||
{
|
||||
if (item is null || scene is null)
|
||||
return (0, 0);
|
||||
|
||||
string? file = item switch
|
||||
{
|
||||
AudioItem audio => audio.FilePath,
|
||||
VideoItem video => video.FilePath,
|
||||
_ => null,
|
||||
};
|
||||
if (_itemSource is null ||
|
||||
!ReferenceEquals(item, _itemSourceItem) ||
|
||||
!ReferenceEquals(scene, _itemSourceScene) ||
|
||||
!string.Equals(file, _itemSourceFile, StringComparison.Ordinal))
|
||||
{
|
||||
_itemSource?.Dispose();
|
||||
_itemSource = null;
|
||||
_itemSource = CreateItemSource(item, scene) ?? CreateRawItemSource(item, scene);
|
||||
_itemSourceItem = item;
|
||||
_itemSourceScene = scene;
|
||||
_itemSourceFile = file;
|
||||
}
|
||||
|
||||
return ReadStream(_itemSource, time, type, size);
|
||||
}
|
||||
catch
|
||||
{
|
||||
return (0, 0);
|
||||
}
|
||||
}
|
||||
|
||||
private (int Count, int Rate) ReadStream(IAudioStream? source, double time, string type, int size)
|
||||
{
|
||||
if (source is null || source.Hz <= 0)
|
||||
return (0, 0);
|
||||
|
||||
int floats = EnsureReadBuffer(type, size);
|
||||
if (floats <= 0)
|
||||
return (0, source.Hz);
|
||||
|
||||
source.Seek(TimeSpan.FromSeconds(Math.Max(0d, time)));
|
||||
int total = 0;
|
||||
while (total < floats)
|
||||
{
|
||||
int read = source.Read(_readBuffer, total, floats - total);
|
||||
if (read <= 0)
|
||||
break;
|
||||
total += read;
|
||||
}
|
||||
|
||||
return (_converter.Convert(type, _readBuffer, total / 2, size, _data), source.Hz);
|
||||
}
|
||||
|
||||
private int EnsureReadBuffer(string type, int size)
|
||||
{
|
||||
int frames = AviUtlAudioConverter.RequiredFrames(type, size);
|
||||
if (frames <= 0)
|
||||
return 0;
|
||||
int floats = frames * 2;
|
||||
if (_readBuffer.Length < floats)
|
||||
_readBuffer = new float[floats];
|
||||
return floats;
|
||||
}
|
||||
|
||||
private static IAudioStream? CreateItemSource(IAudioItem item, Scene scene)
|
||||
{
|
||||
try
|
||||
{
|
||||
return CreateEditorItemSource(item, scene);
|
||||
}
|
||||
catch
|
||||
{
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
[MethodImpl(MethodImplOptions.NoInlining)]
|
||||
private static IAudioStream CreateEditorItemSource(IAudioItem item, Scene scene) =>
|
||||
new EffectedItemSourceForEditorInfo(item, item.AudioEffects, scene);
|
||||
|
||||
private static IAudioStream? CreateRawItemSource(IAudioItem item, Scene scene)
|
||||
{
|
||||
try
|
||||
{
|
||||
return item.CreateAudioSource(scene);
|
||||
}
|
||||
catch
|
||||
{
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
public void Dispose()
|
||||
{
|
||||
_fileSource?.Dispose();
|
||||
_fileSource = null;
|
||||
_sceneSource?.Dispose();
|
||||
_sceneSource = null;
|
||||
_sceneSourceScene = null;
|
||||
_itemSource?.Dispose();
|
||||
_itemSource = null;
|
||||
_itemSourceItem = null;
|
||||
_itemSourceScene = null;
|
||||
_itemSourceFile = null;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,118 @@
|
||||
using YukkuriMovieMaker.Commons;
|
||||
using YukkuriMovieMaker.Player.Video;
|
||||
using YukkuriMovieMaker.Plugin.Brush;
|
||||
|
||||
namespace LuaScript
|
||||
{
|
||||
internal sealed class BrushImageRenderer(IGraphicsDevicesAndContext devices) : IDisposable
|
||||
{
|
||||
private const int MaxDimension = 8192;
|
||||
|
||||
private sealed class Entry(IBrushParameter parameter, IBrushSource source)
|
||||
{
|
||||
public IBrushParameter Parameter { get; } = parameter;
|
||||
public IBrushSource Source { get; } = source;
|
||||
public string[] AppliedKeys { get; set; } = [];
|
||||
}
|
||||
|
||||
private readonly Dictionary<string, Entry?> _sources = new(StringComparer.Ordinal);
|
||||
private GraphicsDevicesAndContext? _ctx;
|
||||
private PixelBufferManager? _pixels;
|
||||
|
||||
public bool TryRender(
|
||||
TimelineItemSourceDescription desc,
|
||||
string name,
|
||||
int width,
|
||||
int height,
|
||||
IReadOnlyList<KeyValuePair<string, object>> arguments,
|
||||
out byte[] pixels,
|
||||
out int outWidth,
|
||||
out int outHeight)
|
||||
{
|
||||
pixels = [];
|
||||
outWidth = 0;
|
||||
outHeight = 0;
|
||||
|
||||
if (width <= 0 || height <= 0 || width > MaxDimension || height > MaxDimension)
|
||||
return false;
|
||||
|
||||
if (!_sources.TryGetValue(name, out var entry))
|
||||
{
|
||||
entry = CreateEntry(name);
|
||||
_sources[name] = entry;
|
||||
}
|
||||
if (entry is null)
|
||||
return false;
|
||||
|
||||
if (!KeysMatch(entry.AppliedKeys, arguments))
|
||||
{
|
||||
entry.Source.Dispose();
|
||||
entry = CreateEntry(name);
|
||||
_sources[name] = entry;
|
||||
if (entry is null)
|
||||
return false;
|
||||
}
|
||||
|
||||
try
|
||||
{
|
||||
if (arguments.Count > 0)
|
||||
{
|
||||
ParameterBinder.ApplyArguments(entry.Parameter, arguments);
|
||||
if (entry.AppliedKeys.Length != arguments.Count)
|
||||
entry.AppliedKeys = new string[arguments.Count];
|
||||
for (int i = 0; i < arguments.Count; i++)
|
||||
entry.AppliedKeys[i] = arguments[i].Key;
|
||||
}
|
||||
|
||||
entry.Source.Update(desc);
|
||||
_pixels ??= new PixelBufferManager(_ctx!);
|
||||
pixels = _pixels.LoadBrushPixels(entry.Source.Brush, width, height);
|
||||
}
|
||||
catch
|
||||
{
|
||||
_sources.Remove(name);
|
||||
entry.Source.Dispose();
|
||||
pixels = [];
|
||||
return false;
|
||||
}
|
||||
|
||||
outWidth = width;
|
||||
outHeight = height;
|
||||
return true;
|
||||
}
|
||||
|
||||
private static bool KeysMatch(string[] appliedKeys, IReadOnlyList<KeyValuePair<string, object>> arguments)
|
||||
{
|
||||
if (appliedKeys.Length != arguments.Count)
|
||||
return false;
|
||||
for (int i = 0; i < appliedKeys.Length; i++)
|
||||
{
|
||||
if (!string.Equals(appliedKeys[i], arguments[i].Key, StringComparison.Ordinal))
|
||||
return false;
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
private Entry? CreateEntry(string name)
|
||||
{
|
||||
foreach (var plugin in BrushFactory.Plugins)
|
||||
{
|
||||
if (!string.Equals(plugin.Name, name, StringComparison.Ordinal))
|
||||
continue;
|
||||
_ctx ??= new GraphicsDevicesAndContext(devices);
|
||||
var parameter = plugin.CreateBrushParameter();
|
||||
return new Entry(parameter, parameter.CreateBrush(_ctx));
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
public void Dispose()
|
||||
{
|
||||
foreach (var entry in _sources.Values)
|
||||
entry?.Source.Dispose();
|
||||
_sources.Clear();
|
||||
_pixels?.Dispose();
|
||||
_ctx?.Dispose();
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,139 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.ComponentModel.DataAnnotations;
|
||||
using System.Globalization;
|
||||
using System.Reflection;
|
||||
using System.Windows.Media;
|
||||
using LuaScript.Compat;
|
||||
using YukkuriMovieMaker.Commons;
|
||||
|
||||
namespace LuaScript
|
||||
{
|
||||
internal static class ParameterBinder
|
||||
{
|
||||
public static readonly AviUtlParameterMapping Identity = new(string.Empty, string.Empty, 1d, 0d);
|
||||
|
||||
private static readonly Dictionary<Type, Dictionary<string, PropertyInfo>> s_propertyCache = [];
|
||||
|
||||
public static string Normalize(string value) => value.Trim().ToLowerInvariant();
|
||||
|
||||
public static Dictionary<string, PropertyInfo> GetProperties(Type type)
|
||||
{
|
||||
lock (s_propertyCache)
|
||||
{
|
||||
if (s_propertyCache.TryGetValue(type, out var cached))
|
||||
return cached;
|
||||
}
|
||||
|
||||
var map = new Dictionary<string, PropertyInfo>(StringComparer.Ordinal);
|
||||
foreach (var property in type.GetProperties(BindingFlags.Public | BindingFlags.Instance))
|
||||
{
|
||||
if (property.GetIndexParameters().Length != 0)
|
||||
continue;
|
||||
bool usable = property.PropertyType == typeof(Animation) || property.GetSetMethod() is not null;
|
||||
if (!usable)
|
||||
continue;
|
||||
|
||||
map.TryAdd(Normalize(property.Name), property);
|
||||
try
|
||||
{
|
||||
var display = property.GetCustomAttribute<DisplayAttribute>()?.GetName();
|
||||
if (!string.IsNullOrWhiteSpace(display))
|
||||
map.TryAdd(Normalize(display), property);
|
||||
}
|
||||
catch
|
||||
{
|
||||
}
|
||||
}
|
||||
|
||||
lock (s_propertyCache)
|
||||
{
|
||||
s_propertyCache[type] = map;
|
||||
}
|
||||
return map;
|
||||
}
|
||||
|
||||
public static void ApplyArguments(object model, IReadOnlyList<KeyValuePair<string, object>> arguments)
|
||||
{
|
||||
if (arguments.Count == 0)
|
||||
return;
|
||||
|
||||
var properties = GetProperties(model.GetType());
|
||||
foreach (var (key, value) in arguments)
|
||||
{
|
||||
if (!properties.TryGetValue(Normalize(key), out var property))
|
||||
continue;
|
||||
try
|
||||
{
|
||||
SetValue(model, property, value, Identity);
|
||||
}
|
||||
catch
|
||||
{
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
public static void SetValue(object model, PropertyInfo property, object value, AviUtlParameterMapping parameter)
|
||||
{
|
||||
var type = property.PropertyType;
|
||||
|
||||
if (type == typeof(Animation))
|
||||
{
|
||||
if (property.GetValue(model) is Animation animation)
|
||||
animation.CopyFrom(new Animation(parameter.Transform(ToDouble(value))));
|
||||
return;
|
||||
}
|
||||
if (type == typeof(bool))
|
||||
{
|
||||
property.SetValue(model, ToBool(value));
|
||||
return;
|
||||
}
|
||||
if (type.IsEnum)
|
||||
{
|
||||
property.SetValue(model, ToEnum(type, value));
|
||||
return;
|
||||
}
|
||||
if (type == typeof(Color))
|
||||
{
|
||||
property.SetValue(model, ToColor(value));
|
||||
return;
|
||||
}
|
||||
if (type == typeof(double) || type == typeof(float) || type == typeof(int) || type == typeof(long) || type == typeof(short))
|
||||
{
|
||||
property.SetValue(model, Convert.ChangeType(parameter.Transform(ToDouble(value)), type, CultureInfo.InvariantCulture));
|
||||
return;
|
||||
}
|
||||
if (type == typeof(string))
|
||||
property.SetValue(model, value?.ToString());
|
||||
}
|
||||
|
||||
private static double ToDouble(object value) => value switch
|
||||
{
|
||||
double d => d,
|
||||
bool b => b ? 1d : 0d,
|
||||
string s => double.TryParse(s, NumberStyles.Float, CultureInfo.InvariantCulture, out var r) ? r : 0d,
|
||||
_ => 0d,
|
||||
};
|
||||
|
||||
private static bool ToBool(object value) => value switch
|
||||
{
|
||||
bool b => b,
|
||||
double d => d != 0d,
|
||||
string s => s.Equals("true", StringComparison.OrdinalIgnoreCase) || s == "1",
|
||||
_ => false,
|
||||
};
|
||||
|
||||
private static object ToEnum(Type type, object value)
|
||||
{
|
||||
if (value is string s && Enum.TryParse(type, s, true, out var parsed))
|
||||
return parsed;
|
||||
return Enum.ToObject(type, (int)ToDouble(value));
|
||||
}
|
||||
|
||||
private static Color ToColor(object value)
|
||||
{
|
||||
int rgb = (int)ToDouble(value);
|
||||
return Color.FromRgb((byte)((rgb >> 16) & 0xFF), (byte)((rgb >> 8) & 0xFF), (byte)(rgb & 0xFF));
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -32,7 +32,32 @@ namespace LuaScript
|
||||
{
|
||||
EnsureBitmaps(width, height);
|
||||
RenderToStaging(input, bounds);
|
||||
return ReadStagingPixels(width, height);
|
||||
}
|
||||
|
||||
public byte[] LoadBrushPixels(ID2D1Brush brush, int width, int height)
|
||||
{
|
||||
EnsureBitmaps(width, height);
|
||||
|
||||
var dc = _ctx.DeviceContext;
|
||||
var rt = (ID2D1RenderTarget)dc;
|
||||
using var savedTarget = dc.Target;
|
||||
|
||||
dc.Target = _renderTarget;
|
||||
dc.BeginDraw();
|
||||
dc.Clear(null);
|
||||
rt.Transform = Matrix3x2.CreateTranslation(width / 2f, height / 2f);
|
||||
rt.FillRectangle(new RawRectF(-width / 2f, -height / 2f, width / 2f, height / 2f), brush);
|
||||
rt.Transform = Matrix3x2.Identity;
|
||||
dc.EndDraw();
|
||||
dc.Target = savedTarget;
|
||||
|
||||
_stagingBitmap!.CopyFromBitmap(_renderTarget!);
|
||||
return ReadStagingPixels(width, height);
|
||||
}
|
||||
|
||||
private unsafe byte[] ReadStagingPixels(int width, int height)
|
||||
{
|
||||
var mapped = _stagingBitmap!.Map(MapOptions.Read);
|
||||
try
|
||||
{
|
||||
|
||||
@@ -1,9 +1,5 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.ComponentModel.DataAnnotations;
|
||||
using System.Globalization;
|
||||
using System.Reflection;
|
||||
using System.Windows.Media;
|
||||
using Vortice.Direct2D1;
|
||||
using YukkuriMovieMaker.Commons;
|
||||
using YukkuriMovieMaker.Player.Video;
|
||||
@@ -23,11 +19,8 @@ namespace LuaScript
|
||||
public required int RequestIndex;
|
||||
}
|
||||
|
||||
private static readonly AviUtlParameterMapping Identity = new(string.Empty, string.Empty, 1d, 0d);
|
||||
|
||||
private static Dictionary<string, Type>? _typeRegistry;
|
||||
private static Dictionary<string, Type>? _nameRegistry;
|
||||
private static readonly Dictionary<Type, Dictionary<string, PropertyInfo>> _propertyCache = [];
|
||||
|
||||
private readonly IGraphicsDevicesAndContext _devices;
|
||||
private readonly List<Node> _nodes = [];
|
||||
@@ -190,34 +183,29 @@ namespace LuaScript
|
||||
map.TryAdd(Normalize(key), type);
|
||||
}
|
||||
|
||||
private static string Normalize(string value) => value.Trim().ToLowerInvariant();
|
||||
private static string Normalize(string value) => ParameterBinder.Normalize(value);
|
||||
|
||||
private static void ApplyParameters(IVideoEffect model, AviUtlEffectMapping? mapping, IReadOnlyList<KeyValuePair<string, object>> arguments)
|
||||
{
|
||||
if (arguments.Count == 0)
|
||||
return;
|
||||
|
||||
var properties = GetProperties(model.GetType());
|
||||
if (mapping is null)
|
||||
{
|
||||
ParameterBinder.ApplyArguments(model, arguments);
|
||||
return;
|
||||
}
|
||||
|
||||
var properties = ParameterBinder.GetProperties(model.GetType());
|
||||
foreach (var (key, value) in arguments)
|
||||
{
|
||||
PropertyInfo? property;
|
||||
AviUtlParameterMapping parameter;
|
||||
if (mapping is not null)
|
||||
{
|
||||
if (!mapping.TryGetParameter(key, out parameter) ||
|
||||
!properties.TryGetValue(Normalize(parameter.Property), out property))
|
||||
continue;
|
||||
}
|
||||
else
|
||||
{
|
||||
if (!properties.TryGetValue(Normalize(key), out property))
|
||||
continue;
|
||||
parameter = Identity;
|
||||
}
|
||||
if (!mapping.TryGetParameter(key, out var parameter) ||
|
||||
!properties.TryGetValue(Normalize(parameter.Property), out var property))
|
||||
continue;
|
||||
|
||||
try
|
||||
{
|
||||
SetValue(model, property, value, parameter);
|
||||
ParameterBinder.SetValue(model, property, value, parameter);
|
||||
}
|
||||
catch
|
||||
{
|
||||
@@ -225,99 +213,6 @@ namespace LuaScript
|
||||
}
|
||||
}
|
||||
|
||||
private static Dictionary<string, PropertyInfo> GetProperties(Type type)
|
||||
{
|
||||
if (_propertyCache.TryGetValue(type, out var cached))
|
||||
return cached;
|
||||
|
||||
var map = new Dictionary<string, PropertyInfo>(StringComparer.Ordinal);
|
||||
foreach (var property in type.GetProperties(BindingFlags.Public | BindingFlags.Instance))
|
||||
{
|
||||
if (property.GetIndexParameters().Length != 0)
|
||||
continue;
|
||||
bool usable = property.PropertyType == typeof(Animation) || property.GetSetMethod() is not null;
|
||||
if (!usable)
|
||||
continue;
|
||||
|
||||
map.TryAdd(Normalize(property.Name), property);
|
||||
try
|
||||
{
|
||||
var display = property.GetCustomAttribute<DisplayAttribute>()?.GetName();
|
||||
if (!string.IsNullOrWhiteSpace(display))
|
||||
map.TryAdd(Normalize(display), property);
|
||||
}
|
||||
catch
|
||||
{
|
||||
}
|
||||
}
|
||||
|
||||
_propertyCache[type] = map;
|
||||
return map;
|
||||
}
|
||||
|
||||
private static void SetValue(IVideoEffect model, PropertyInfo property, object value, AviUtlParameterMapping parameter)
|
||||
{
|
||||
var type = property.PropertyType;
|
||||
|
||||
if (type == typeof(Animation))
|
||||
{
|
||||
if (property.GetValue(model) is Animation animation)
|
||||
animation.CopyFrom(new Animation(parameter.Transform(ToDouble(value))));
|
||||
return;
|
||||
}
|
||||
if (type == typeof(bool))
|
||||
{
|
||||
property.SetValue(model, ToBool(value));
|
||||
return;
|
||||
}
|
||||
if (type.IsEnum)
|
||||
{
|
||||
property.SetValue(model, ToEnum(type, value));
|
||||
return;
|
||||
}
|
||||
if (type == typeof(Color))
|
||||
{
|
||||
property.SetValue(model, ToColor(value));
|
||||
return;
|
||||
}
|
||||
if (type == typeof(double) || type == typeof(float) || type == typeof(int) || type == typeof(long) || type == typeof(short))
|
||||
{
|
||||
property.SetValue(model, Convert.ChangeType(parameter.Transform(ToDouble(value)), type, CultureInfo.InvariantCulture));
|
||||
return;
|
||||
}
|
||||
if (type == typeof(string))
|
||||
property.SetValue(model, value?.ToString());
|
||||
}
|
||||
|
||||
private static double ToDouble(object value) => value switch
|
||||
{
|
||||
double d => d,
|
||||
bool b => b ? 1d : 0d,
|
||||
string s => double.TryParse(s, NumberStyles.Float, CultureInfo.InvariantCulture, out var r) ? r : 0d,
|
||||
_ => 0d,
|
||||
};
|
||||
|
||||
private static bool ToBool(object value) => value switch
|
||||
{
|
||||
bool b => b,
|
||||
double d => d != 0d,
|
||||
string s => s.Equals("true", StringComparison.OrdinalIgnoreCase) || s == "1",
|
||||
_ => false,
|
||||
};
|
||||
|
||||
private static object ToEnum(Type type, object value)
|
||||
{
|
||||
if (value is string s && Enum.TryParse(type, s, true, out var parsed))
|
||||
return parsed;
|
||||
return Enum.ToObject(type, (int)ToDouble(value));
|
||||
}
|
||||
|
||||
private static Color ToColor(object value)
|
||||
{
|
||||
int rgb = (int)ToDouble(value);
|
||||
return Color.FromRgb((byte)((rgb >> 16) & 0xFF), (byte)((rgb >> 8) & 0xFF), (byte)(rgb & 0xFF));
|
||||
}
|
||||
|
||||
private void DisposeNodes()
|
||||
{
|
||||
foreach (var node in _nodes)
|
||||
|
||||
@@ -295,6 +295,35 @@ namespace LuaScript
|
||||
return Color.FromRgb(r, g, b);
|
||||
}
|
||||
|
||||
[Display(GroupName = nameof(Texts.AnchorGroup), Name = nameof(Texts.AnchorX), Description = nameof(Texts.AnchorDesc), ResourceType = typeof(Texts))]
|
||||
[TextBoxSlider("F1", "", -9999, 9999)]
|
||||
[ShowPropertyEditorWhen(nameof(IsAnchorSelected), true)]
|
||||
[JsonIgnore]
|
||||
public double AnchorX { get => _anchorX; set { if (Set(ref _anchorX, value) && !_anchorSyncing) ApplyAnchorEdit(); } }
|
||||
double _anchorX;
|
||||
|
||||
[Display(GroupName = nameof(Texts.AnchorGroup), Name = nameof(Texts.AnchorY), Description = nameof(Texts.AnchorDesc), ResourceType = typeof(Texts))]
|
||||
[TextBoxSlider("F1", "", -9999, 9999)]
|
||||
[ShowPropertyEditorWhen(nameof(IsAnchorSelected), true)]
|
||||
[JsonIgnore]
|
||||
public double AnchorY { get => _anchorY; set { if (Set(ref _anchorY, value) && !_anchorSyncing) ApplyAnchorEdit(); } }
|
||||
double _anchorY;
|
||||
|
||||
[Display(GroupName = nameof(Texts.AnchorGroup), Name = nameof(Texts.AnchorZ), Description = nameof(Texts.AnchorDesc), ResourceType = typeof(Texts))]
|
||||
[TextBoxSlider("F1", "", -9999, 9999)]
|
||||
[ShowPropertyEditorWhen(nameof(IsAnchorZVisible), true)]
|
||||
[JsonIgnore]
|
||||
public double AnchorZ { get => _anchorZ; set { if (Set(ref _anchorZ, value) && !_anchorSyncing) ApplyAnchorEdit(); } }
|
||||
double _anchorZ;
|
||||
|
||||
[JsonIgnore] public bool IsAnchorSelected { get => _isAnchorSelected; private set => Set(ref _isAnchorSelected, value); }
|
||||
[JsonIgnore] public bool IsAnchorZVisible { get => _isAnchorZVisible; private set => Set(ref _isAnchorZVisible, value); }
|
||||
bool _isAnchorSelected;
|
||||
bool _isAnchorZVisible;
|
||||
string _selectedAnchorGroup = string.Empty;
|
||||
int _selectedAnchorIndex;
|
||||
bool _anchorSyncing;
|
||||
|
||||
public ImmutableList<LuaAnchorPoint> Anchors
|
||||
{
|
||||
get => _anchors;
|
||||
@@ -306,7 +335,37 @@ namespace LuaScript
|
||||
internal int AnchorVersion { get; private set; }
|
||||
|
||||
internal void ApplyAnchorDrag(string group, int index, double dx, double dy, double dz)
|
||||
=> Anchors = AnchorSupport.ApplyDrag(Anchors, group, index, dx, dy, dz);
|
||||
{
|
||||
Anchors = AnchorSupport.ApplyDrag(Anchors, group, index, dx, dy, dz);
|
||||
if (IsAnchorSelected && index == _selectedAnchorIndex && group == _selectedAnchorGroup)
|
||||
RefreshSelectedAnchor();
|
||||
}
|
||||
|
||||
internal void BeginAnchorEdit(string group, int index, bool is3D)
|
||||
{
|
||||
_selectedAnchorGroup = group;
|
||||
_selectedAnchorIndex = index;
|
||||
RefreshSelectedAnchor();
|
||||
IsAnchorSelected = true;
|
||||
IsAnchorZVisible = is3D;
|
||||
}
|
||||
|
||||
private void RefreshSelectedAnchor()
|
||||
{
|
||||
AnchorSupport.ResolvePosition(_anchors, _selectedAnchorGroup, _selectedAnchorIndex, out double x, out double y, out double z);
|
||||
_anchorSyncing = true;
|
||||
AnchorX = x;
|
||||
AnchorY = y;
|
||||
AnchorZ = z;
|
||||
_anchorSyncing = false;
|
||||
}
|
||||
|
||||
private void ApplyAnchorEdit()
|
||||
{
|
||||
if (!IsAnchorSelected)
|
||||
return;
|
||||
Anchors = AnchorSupport.SetPosition(_anchors, _selectedAnchorGroup, _selectedAnchorIndex, _anchorX, _anchorY, _anchorZ);
|
||||
}
|
||||
|
||||
public override IEnumerable<string> CreateExoVideoFilters(int keyFrameIndex, ExoOutputDescription exoOutputDescription) => [];
|
||||
|
||||
|
||||
@@ -7,6 +7,7 @@ using LuaScript.Compat;
|
||||
using LuaScript.Diagnostics;
|
||||
using LuaScript.Engine;
|
||||
using LuaScript.Engine.Kernel;
|
||||
using LuaScript.Engine.Processing;
|
||||
using LuaScript.Engine.Shader;
|
||||
using Vortice;
|
||||
using Vortice.DCommon;
|
||||
@@ -138,6 +139,14 @@ namespace LuaScript
|
||||
private Func<string, string, double, bool, bool, int, (byte[] buffer, int w, int h)>? _nativeLoadText;
|
||||
private Func<string, (byte[] buffer, int w, int h)>? _nativeLoadImage;
|
||||
private Func<string, double, (byte[] buffer, int w, int h)>? _nativeLoadMovie;
|
||||
private Func<string, double, (byte[] Buffer, int Width, int Height)>? _loadSceneImage;
|
||||
private Func<string, double, double, IReadOnlyList<KeyValuePair<string, object>>, (byte[] Buffer, int Width, int Height)>? _loadBrushImage;
|
||||
private SceneImageRenderer? _sceneImageRenderer;
|
||||
private BrushImageRenderer? _brushImageRenderer;
|
||||
private bool _sceneImageLoaded;
|
||||
private Func<string, string, int, (int Count, int Rate, double[] Data)>? _loadAudio;
|
||||
private AudioSampleProvider? _audioProvider;
|
||||
private bool _audioLoaded;
|
||||
private Action<string, IReadOnlyList<KeyValuePair<string, object>>>? _nativeAddEffect;
|
||||
private Action<DrawCommand>? _nativeAddDraw;
|
||||
private Action<string, int, bool, int, double[]>? _nativeSetAnchor;
|
||||
@@ -150,6 +159,7 @@ namespace LuaScript
|
||||
private string _runnableScript = string.Empty;
|
||||
private int[] _runnableLineMap = [];
|
||||
private int[] _runnableChangedLines = [];
|
||||
private LuaScriptDiagnostic[] _runnableRewriteDiagnostics = [];
|
||||
private bool _runnableCached;
|
||||
private ID2D1Image? _cachedInput;
|
||||
private RenderKey _cachedKey;
|
||||
@@ -159,6 +169,7 @@ namespace LuaScript
|
||||
private ID2D1Image? _cachedEffectOutput;
|
||||
|
||||
private PixelShaderRunner? _pixelShaderRunner;
|
||||
private GpuPixelBufferProcessor? _pixelProcessor;
|
||||
private AviUtlPixelShaderLibrary _pixelShaderLibrary = AviUtlPixelShaderLibrary.Empty;
|
||||
private string? _pixelShaderSourceRef;
|
||||
|
||||
@@ -179,20 +190,38 @@ namespace LuaScript
|
||||
new SynchronizedCompositor(new HardwareCompositor(_ownCtx), _pixelLoaderSemaphore),
|
||||
SoftwareCompositor.Instance,
|
||||
WarnBufferCompositorDegraded);
|
||||
_pixelShaderRunner = new PixelShaderRunner { Compositor = _bufferCompositor };
|
||||
_pixelShaderRunner = new PixelShaderRunner { Compositor = _bufferCompositor, Logger = WriteGpuLog };
|
||||
_pixelProcessor = new GpuPixelBufferProcessor(_pixelShaderRunner);
|
||||
_context.ResolverProvider = GetFrameResolver;
|
||||
_context.Compositor = _bufferCompositor;
|
||||
_context.PixelProcessor = _pixelProcessor;
|
||||
_context.SceneImageLoader = _loadSceneImage ??= LoadSceneImage;
|
||||
_context.BrushImageLoader = _loadBrushImage ??= LoadBrushImage;
|
||||
_context.AudioLoader = _loadAudio ??= LoadAudio;
|
||||
return null;
|
||||
}
|
||||
|
||||
private static void WarnBufferCompositorDegraded(Exception ex) =>
|
||||
Log.Default.Write("LuaScript: hardware buffer compositing failed; falling back to the software compositor.", ex);
|
||||
|
||||
private static void WriteGpuLog(string message, Exception? exception)
|
||||
{
|
||||
if (exception is null)
|
||||
Log.Default.Write(message);
|
||||
else
|
||||
Log.Default.Write(message, exception);
|
||||
}
|
||||
|
||||
private AviUtlScriptContext CreateScriptContext()
|
||||
{
|
||||
var context = new AviUtlScriptContext { ResolverProvider = GetFrameResolver };
|
||||
if (_bufferCompositor is not null)
|
||||
context.Compositor = _bufferCompositor;
|
||||
if (_pixelProcessor is not null)
|
||||
context.PixelProcessor = _pixelProcessor;
|
||||
context.SceneImageLoader = _loadSceneImage ??= LoadSceneImage;
|
||||
context.BrushImageLoader = _loadBrushImage ??= LoadBrushImage;
|
||||
context.AudioLoader = _loadAudio ??= LoadAudio;
|
||||
return context;
|
||||
}
|
||||
|
||||
@@ -219,18 +248,30 @@ namespace LuaScript
|
||||
|
||||
private string GetRunnableScript(string source)
|
||||
{
|
||||
if (_runnableCached && string.Equals(source, _sourceScript, StringComparison.Ordinal))
|
||||
if (_runnableCached && ReferenceEquals(source, _sourceScript))
|
||||
return _runnableScript;
|
||||
|
||||
var (code, lineMap, changedLines) = AviUtlScript.TransformWithMap(source);
|
||||
var (code, lineMap, changedLines, rewriteDiagnostics) = AviUtlScript.TransformWithMap(source);
|
||||
_runnableScript = code;
|
||||
_runnableLineMap = lineMap;
|
||||
_runnableChangedLines = changedLines;
|
||||
_sourceScript = source;
|
||||
_runnableCached = true;
|
||||
_runnableRewriteDiagnostics = BuildRewriteDiagnostics(rewriteDiagnostics);
|
||||
return _runnableScript;
|
||||
}
|
||||
|
||||
private LuaScriptDiagnostic[] BuildRewriteDiagnostics(LuaScript.Compat.Syntax.LuaRewriteDiagnostic[] source)
|
||||
{
|
||||
if (source.Length == 0)
|
||||
return [];
|
||||
|
||||
var diagnostics = new LuaScriptDiagnostic[source.Length];
|
||||
for (int i = 0; i < source.Length; i++)
|
||||
diagnostics[i] = new LuaScriptDiagnostic(LuaScriptDiagnosticKind.Compile, MapRunnableLine(source[i].Line), 0, 0, source[i].Message);
|
||||
return diagnostics;
|
||||
}
|
||||
|
||||
private AviUtlPixelShaderLibrary GetPixelShaderLibrary(string source)
|
||||
{
|
||||
if (!ReferenceEquals(_pixelShaderSourceRef, source))
|
||||
@@ -466,23 +507,47 @@ namespace LuaScript
|
||||
_pixelLoaderSemaphore.Release();
|
||||
}
|
||||
|
||||
LuaScriptDiagnostics.Instance.Report(script, diagnostics);
|
||||
LuaScriptDiagnostics.Instance.Report(script, _runnableRewriteDiagnostics.Length == 0
|
||||
? diagnostics
|
||||
: [.. _runnableRewriteDiagnostics, .. diagnostics]);
|
||||
|
||||
_isFirst = false;
|
||||
if (_sceneImageLoaded)
|
||||
{
|
||||
_sceneImageLoaded = false;
|
||||
_isFirst = true;
|
||||
}
|
||||
if (_audioLoaded)
|
||||
{
|
||||
_audioLoaded = false;
|
||||
_isFirst = true;
|
||||
}
|
||||
_cachedKey = key;
|
||||
_cachedQueries = ctx.ObjectQueries.Count == 0 ? [] : [.. ctx.ObjectQueries];
|
||||
_cachedSceneValueQueries = ctx.SceneValueQueries.Count == 0 ? [] : [.. ctx.SceneValueQueries];
|
||||
_cachedQueries = SnapshotQueries(ctx.ObjectQueries, _cachedQueries);
|
||||
_cachedSceneValueQueries = SnapshotQueries(ctx.SceneValueQueries, _cachedSceneValueQueries);
|
||||
_cachedOutputDesc = outDesc;
|
||||
_cachedEffectOutput = effectOutput;
|
||||
|
||||
return outDesc;
|
||||
}
|
||||
|
||||
private string? _effectTargetSource;
|
||||
private AviUtlEngine _effectTarget;
|
||||
|
||||
private AviUtlEngine ResolveEffectTarget(string? script)
|
||||
{
|
||||
if (!ReferenceEquals(_effectTargetSource, script) || _effectTargetSource is null)
|
||||
{
|
||||
_effectTarget = AviUtlCompatMap.ResolveTarget(script);
|
||||
_effectTargetSource = script;
|
||||
}
|
||||
return _effectTarget;
|
||||
}
|
||||
|
||||
private ID2D1Image ApplyEffectChain(ID2D1Image source, IReadOnlyList<AviUtlEffectRequest> requests, EffectDescription desc, ref DrawDescription drawDescription)
|
||||
{
|
||||
_effectChain ??= new VideoEffectChain(_ownCtx!);
|
||||
var target = AviUtlCompatMap.ResolveTarget(item.Script);
|
||||
return _effectChain.Apply(source, requests, desc, target, ref drawDescription);
|
||||
return _effectChain.Apply(source, requests, desc, ResolveEffectTarget(item.Script), ref drawDescription);
|
||||
}
|
||||
|
||||
private static (double Bpm, int Beat, double Offset) ResolveBpm(EffectDescription desc)
|
||||
@@ -527,18 +592,49 @@ namespace LuaScript
|
||||
|
||||
foreach (var item in items)
|
||||
{
|
||||
if (item is not VisualItem visual)
|
||||
if (item is not IVideoItem video)
|
||||
continue;
|
||||
var tag = item.Remark;
|
||||
if (string.IsNullOrEmpty(tag))
|
||||
continue;
|
||||
|
||||
entries.Add(new SceneObjectResolver.Entry(tag, item.Frame, item.Length, item.Layer, visual));
|
||||
var (character, text, kind, volume) = ExtractItemMetadata(item);
|
||||
entries.Add(new SceneObjectResolver.Entry(tag, item.Frame, item.Length, item.Layer, video, volume, character, text, kind));
|
||||
}
|
||||
|
||||
return new SceneObjectResolver([.. entries], desc.FPS);
|
||||
}
|
||||
|
||||
private static (string Character, string Text, string Kind, Animation? Volume) ExtractItemMetadata(IItem item)
|
||||
{
|
||||
string character = string.Empty;
|
||||
string text = string.Empty;
|
||||
string kind = string.Empty;
|
||||
Animation? volume = null;
|
||||
try
|
||||
{
|
||||
kind = item.GetType().Name;
|
||||
switch (item)
|
||||
{
|
||||
case VoiceItem voice:
|
||||
character = voice.CharacterName ?? string.Empty;
|
||||
text = voice.Serif ?? string.Empty;
|
||||
volume = voice.Volume;
|
||||
break;
|
||||
case TextItem textItem:
|
||||
text = textItem.Text ?? string.Empty;
|
||||
break;
|
||||
}
|
||||
}
|
||||
catch
|
||||
{
|
||||
character = string.Empty;
|
||||
text = string.Empty;
|
||||
volume = null;
|
||||
}
|
||||
return (character, text, kind, volume);
|
||||
}
|
||||
|
||||
private static bool SceneValuesMatch(SceneValueQuery[] queries, SceneSharedValues values, long generation)
|
||||
{
|
||||
for (int i = 0; i < queries.Length; i++)
|
||||
@@ -549,6 +645,17 @@ namespace LuaScript
|
||||
return true;
|
||||
}
|
||||
|
||||
private static T[] SnapshotQueries<T>(IReadOnlyList<T> source, T[] existing)
|
||||
{
|
||||
int count = source.Count;
|
||||
if (count == 0)
|
||||
return [];
|
||||
var target = existing.Length == count ? existing : new T[count];
|
||||
for (int i = 0; i < count; i++)
|
||||
target[i] = source[i];
|
||||
return target;
|
||||
}
|
||||
|
||||
private static bool QueriesMatch(SceneObjectQuery[] queries, SceneObjectResolver resolver)
|
||||
{
|
||||
for (int i = 0; i < queries.Length; i++)
|
||||
@@ -754,6 +861,7 @@ namespace LuaScript
|
||||
arg => item.ApplyAnchorDrag(group, index, arg.Delta.X, arg.Delta.Y, is3D ? arg.Delta.Z : 0d))
|
||||
{
|
||||
Shape = VideoControllerPointShape.Circle,
|
||||
OnDragStart = _ => item.BeginAnchorEdit(group, index, is3D),
|
||||
};
|
||||
builder.Add(new VideoEffectController(item, [point]));
|
||||
}
|
||||
@@ -841,7 +949,7 @@ namespace LuaScript
|
||||
|
||||
private void EnsureKernel(string runnable)
|
||||
{
|
||||
if (_kernelResolved && string.Equals(runnable, _kernelSource, StringComparison.Ordinal))
|
||||
if (_kernelResolved && ReferenceEquals(runnable, _kernelSource))
|
||||
return;
|
||||
|
||||
_kernelSource = runnable;
|
||||
@@ -855,7 +963,7 @@ namespace LuaScript
|
||||
|
||||
private void EnsureDirective(string runnable)
|
||||
{
|
||||
if (_directiveCached && string.Equals(runnable, _directiveSource, StringComparison.Ordinal))
|
||||
if (_directiveCached && ReferenceEquals(runnable, _directiveSource))
|
||||
return;
|
||||
|
||||
_directiveSource = runnable;
|
||||
@@ -957,6 +1065,9 @@ namespace LuaScript
|
||||
_nativeLoadText ??= NativeLoadText;
|
||||
_nativeLoadImage ??= NativeLoadImage;
|
||||
_nativeLoadMovie ??= NativeLoadMovie;
|
||||
_loadSceneImage ??= LoadSceneImage;
|
||||
_loadBrushImage ??= LoadBrushImage;
|
||||
_loadAudio ??= LoadAudio;
|
||||
_nativeAddEffect ??= (name, args) => _context.AddEffect(new AviUtlEffectRequest(name, args));
|
||||
_nativeAddDraw ??= command => _context.AddDraw(command);
|
||||
_nativeSetAnchor ??= ResolveNativeAnchor;
|
||||
@@ -974,12 +1085,16 @@ namespace LuaScript
|
||||
_nativeLoadText,
|
||||
_nativeLoadImage,
|
||||
_nativeLoadMovie,
|
||||
_loadSceneImage,
|
||||
_loadBrushImage,
|
||||
_nativeAddEffect,
|
||||
_nativeAddDraw,
|
||||
_nativeSetAnchor,
|
||||
_nativeSceneGet,
|
||||
_nativeSceneSet,
|
||||
_loadAudio,
|
||||
_nativeRunPixelShader,
|
||||
_pixelProcessor,
|
||||
out bool dirty, out bool bufferReplaced,
|
||||
out int resultW, out int resultH, out string? error);
|
||||
|
||||
@@ -1128,6 +1243,117 @@ namespace LuaScript
|
||||
return (buffer, w, h);
|
||||
}
|
||||
|
||||
private static readonly (byte[] Buffer, int Width, int Height) s_noLoadedImage = ([], 0, 0);
|
||||
|
||||
private (byte[] Buffer, int Width, int Height) LoadSceneImage(string name, double time)
|
||||
{
|
||||
var desc = _frameDesc;
|
||||
var devices = _hostDevices;
|
||||
if (desc is null || devices is null)
|
||||
return s_noLoadedImage;
|
||||
|
||||
_pixelLoaderSemaphore.Wait();
|
||||
try
|
||||
{
|
||||
_sceneImageRenderer ??= new SceneImageRenderer(devices);
|
||||
if (!_sceneImageRenderer.TryRender(desc, name, time, out var pixels, out int width, out int height))
|
||||
return s_noLoadedImage;
|
||||
_sceneImageLoaded = true;
|
||||
return (pixels, width, height);
|
||||
}
|
||||
finally
|
||||
{
|
||||
_pixelLoaderSemaphore.Release();
|
||||
}
|
||||
}
|
||||
|
||||
private (byte[] Buffer, int Width, int Height) LoadBrushImage(string name, double width, double height, IReadOnlyList<KeyValuePair<string, object>> arguments)
|
||||
{
|
||||
var desc = _frameDesc;
|
||||
var devices = _hostDevices;
|
||||
if (desc is null || devices is null)
|
||||
return s_noLoadedImage;
|
||||
|
||||
int w = (int)Math.Round(width);
|
||||
int h = (int)Math.Round(height);
|
||||
|
||||
_pixelLoaderSemaphore.Wait();
|
||||
try
|
||||
{
|
||||
_brushImageRenderer ??= new BrushImageRenderer(devices);
|
||||
if (!_brushImageRenderer.TryRender(desc, name, w, h, arguments, out var pixels, out int outWidth, out int outHeight))
|
||||
return s_noLoadedImage;
|
||||
return (pixels, outWidth, outHeight);
|
||||
}
|
||||
finally
|
||||
{
|
||||
_pixelLoaderSemaphore.Release();
|
||||
}
|
||||
}
|
||||
|
||||
private static readonly (int Count, int Rate, double[] Data) s_noAudio = (0, 0, []);
|
||||
|
||||
private (int Count, int Rate, double[] Data) LoadAudio(string file, string type, int size)
|
||||
{
|
||||
var desc = _frameDesc;
|
||||
if (desc is null)
|
||||
return s_noAudio;
|
||||
|
||||
_audioProvider ??= new AudioSampleProvider();
|
||||
(int Count, int Rate) result;
|
||||
if (string.Equals(file, "audiobuffer", StringComparison.Ordinal))
|
||||
{
|
||||
result = _audioProvider.ReadScene(FindOwnScene(desc), desc.TimelinePosition.Time.TotalSeconds, type, size);
|
||||
}
|
||||
else if (string.Equals(file, "itembuffer", StringComparison.Ordinal))
|
||||
{
|
||||
var (audioItem, scene) = ResolveOwnAudioItem(desc);
|
||||
result = _audioProvider.ReadItem(audioItem, scene, desc.ItemPosition.Time.TotalSeconds, type, size);
|
||||
}
|
||||
else
|
||||
{
|
||||
result = _audioProvider.ReadFile(file, desc.ItemPosition.Time.TotalSeconds, type, size);
|
||||
}
|
||||
|
||||
if (result.Count > 0)
|
||||
_audioLoaded = true;
|
||||
return (result.Count, result.Rate, _audioProvider.Data);
|
||||
}
|
||||
|
||||
private static Scene? FindOwnScene(EffectDescription desc)
|
||||
{
|
||||
var scenes = desc.Scenes;
|
||||
if (scenes is null)
|
||||
return null;
|
||||
foreach (var info in scenes)
|
||||
{
|
||||
if (info is Scene scene && scene.ID == desc.SceneId)
|
||||
return scene;
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
private (IAudioItem? Item, Scene? Scene) ResolveOwnAudioItem(EffectDescription desc)
|
||||
{
|
||||
var scene = FindOwnScene(desc);
|
||||
if (scene is null)
|
||||
return (null, null);
|
||||
|
||||
var items = scene.Timeline.Items;
|
||||
for (int i = 0; i < items.Count; i++)
|
||||
{
|
||||
if (items[i] is not IVideoItem video)
|
||||
continue;
|
||||
var effects = video.VideoEffects;
|
||||
for (int k = 0; k < effects.Count; k++)
|
||||
{
|
||||
if (ReferenceEquals(effects[k], item))
|
||||
return (items[i] as IAudioItem, scene);
|
||||
}
|
||||
}
|
||||
return (null, scene);
|
||||
}
|
||||
|
||||
private (byte[] buffer, int w, int h) NativeLoadMovie(string path, double time)
|
||||
{
|
||||
_nativeMovieDecoder ??= new MovieDecoder();
|
||||
@@ -1175,6 +1401,9 @@ namespace LuaScript
|
||||
_bufferCompositor?.Dispose();
|
||||
_nativeTextRenderer?.Dispose();
|
||||
_nativeImageDecoder?.Dispose();
|
||||
_sceneImageRenderer?.Dispose();
|
||||
_brushImageRenderer?.Dispose();
|
||||
_audioProvider?.Dispose();
|
||||
_pixelLoaderSemaphore.Dispose();
|
||||
_pixelManager?.Dispose();
|
||||
_pixelManager = null;
|
||||
|
||||
@@ -107,4 +107,9 @@
|
||||
<data name="DiagnosticCompile" xml:space="preserve"><value>خطأ في بناء الجملة</value></data>
|
||||
<data name="DiagnosticRuntime" xml:space="preserve"><value>خطأ وقت التشغيل</value></data>
|
||||
<data name="DiagnosticTimeout" xml:space="preserve"><value>انتهت المهلة</value></data>
|
||||
<data name="AnchorGroup" xml:space="preserve"><value>مرساة</value></data>
|
||||
<data name="AnchorX" xml:space="preserve"><value>X</value></data>
|
||||
<data name="AnchorY" xml:space="preserve"><value>Y</value></data>
|
||||
<data name="AnchorZ" xml:space="preserve"><value>Z</value></data>
|
||||
<data name="AnchorDesc" xml:space="preserve"><value>إحداثيات نقطة الإرساء المحددة</value></data>
|
||||
</root>
|
||||
@@ -47,3 +47,8 @@ LuaFileFilter,,Luaスクリプト (*.lua)|*.lua|すべてのファイル (*.*)|*
|
||||
DiagnosticCompile,,構文エラー,Syntax error,语法错误,語法錯誤,구문 오류,Error de sintaxis,خطأ في بناء الجملة,Kesalahan sintaksis
|
||||
DiagnosticRuntime,,実行時エラー,Runtime error,运行时错误,執行時錯誤,런타임 오류,Error de ejecución,خطأ وقت التشغيل,Kesalahan runtime
|
||||
DiagnosticTimeout,,タイムアウト,Timed out,执行超时,執行逾時,시간 초과,Tiempo de espera agotado,انتهت المهلة,Waktu habis
|
||||
AnchorGroup,,アンカー,Anchor,锚点,錨點,앵커,Anclaje,مرساة,Jangkar
|
||||
AnchorX,,X,X,X,X,X,X,X,X
|
||||
AnchorY,,Y,Y,Y,Y,Y,Y,Y,Y
|
||||
AnchorZ,,Z,Z,Z,Z,Z,Z,Z,Z
|
||||
AnchorDesc,,選択中のアンカーポイントの座標,Coordinate of the selected anchor point,所选锚点的坐标,所選錨點的座標,선택한 앵커 포인트의 좌표,Coordenada del punto de anclaje seleccionado,إحداثيات نقطة الإرساء المحددة,Koordinat titik jangkar yang dipilih
|
||||
|
@@ -107,4 +107,9 @@
|
||||
<data name="DiagnosticCompile" xml:space="preserve"><value>Syntax error</value></data>
|
||||
<data name="DiagnosticRuntime" xml:space="preserve"><value>Runtime error</value></data>
|
||||
<data name="DiagnosticTimeout" xml:space="preserve"><value>Timed out</value></data>
|
||||
<data name="AnchorGroup" xml:space="preserve"><value>Anchor</value></data>
|
||||
<data name="AnchorX" xml:space="preserve"><value>X</value></data>
|
||||
<data name="AnchorY" xml:space="preserve"><value>Y</value></data>
|
||||
<data name="AnchorZ" xml:space="preserve"><value>Z</value></data>
|
||||
<data name="AnchorDesc" xml:space="preserve"><value>Coordinate of the selected anchor point</value></data>
|
||||
</root>
|
||||
@@ -107,4 +107,9 @@
|
||||
<data name="DiagnosticCompile" xml:space="preserve"><value>Error de sintaxis</value></data>
|
||||
<data name="DiagnosticRuntime" xml:space="preserve"><value>Error de ejecución</value></data>
|
||||
<data name="DiagnosticTimeout" xml:space="preserve"><value>Tiempo de espera agotado</value></data>
|
||||
<data name="AnchorGroup" xml:space="preserve"><value>Anclaje</value></data>
|
||||
<data name="AnchorX" xml:space="preserve"><value>X</value></data>
|
||||
<data name="AnchorY" xml:space="preserve"><value>Y</value></data>
|
||||
<data name="AnchorZ" xml:space="preserve"><value>Z</value></data>
|
||||
<data name="AnchorDesc" xml:space="preserve"><value>Coordenada del punto de anclaje seleccionado</value></data>
|
||||
</root>
|
||||
@@ -107,4 +107,9 @@
|
||||
<data name="DiagnosticCompile" xml:space="preserve"><value>Kesalahan sintaksis</value></data>
|
||||
<data name="DiagnosticRuntime" xml:space="preserve"><value>Kesalahan runtime</value></data>
|
||||
<data name="DiagnosticTimeout" xml:space="preserve"><value>Waktu habis</value></data>
|
||||
<data name="AnchorGroup" xml:space="preserve"><value>Jangkar</value></data>
|
||||
<data name="AnchorX" xml:space="preserve"><value>X</value></data>
|
||||
<data name="AnchorY" xml:space="preserve"><value>Y</value></data>
|
||||
<data name="AnchorZ" xml:space="preserve"><value>Z</value></data>
|
||||
<data name="AnchorDesc" xml:space="preserve"><value>Koordinat titik jangkar yang dipilih</value></data>
|
||||
</root>
|
||||
@@ -107,4 +107,9 @@
|
||||
<data name="DiagnosticCompile" xml:space="preserve"><value>구문 오류</value></data>
|
||||
<data name="DiagnosticRuntime" xml:space="preserve"><value>런타임 오류</value></data>
|
||||
<data name="DiagnosticTimeout" xml:space="preserve"><value>시간 초과</value></data>
|
||||
<data name="AnchorGroup" xml:space="preserve"><value>앵커</value></data>
|
||||
<data name="AnchorX" xml:space="preserve"><value>X</value></data>
|
||||
<data name="AnchorY" xml:space="preserve"><value>Y</value></data>
|
||||
<data name="AnchorZ" xml:space="preserve"><value>Z</value></data>
|
||||
<data name="AnchorDesc" xml:space="preserve"><value>선택한 앵커 포인트의 좌표</value></data>
|
||||
</root>
|
||||
@@ -107,4 +107,9 @@
|
||||
<data name="DiagnosticCompile" xml:space="preserve"><value>構文エラー</value></data>
|
||||
<data name="DiagnosticRuntime" xml:space="preserve"><value>実行時エラー</value></data>
|
||||
<data name="DiagnosticTimeout" xml:space="preserve"><value>タイムアウト</value></data>
|
||||
<data name="AnchorGroup" xml:space="preserve"><value>アンカー</value></data>
|
||||
<data name="AnchorX" xml:space="preserve"><value>X</value></data>
|
||||
<data name="AnchorY" xml:space="preserve"><value>Y</value></data>
|
||||
<data name="AnchorZ" xml:space="preserve"><value>Z</value></data>
|
||||
<data name="AnchorDesc" xml:space="preserve"><value>選択中のアンカーポイントの座標</value></data>
|
||||
</root>
|
||||
@@ -107,4 +107,9 @@
|
||||
<data name="DiagnosticCompile" xml:space="preserve"><value>语法错误</value></data>
|
||||
<data name="DiagnosticRuntime" xml:space="preserve"><value>运行时错误</value></data>
|
||||
<data name="DiagnosticTimeout" xml:space="preserve"><value>执行超时</value></data>
|
||||
<data name="AnchorGroup" xml:space="preserve"><value>锚点</value></data>
|
||||
<data name="AnchorX" xml:space="preserve"><value>X</value></data>
|
||||
<data name="AnchorY" xml:space="preserve"><value>Y</value></data>
|
||||
<data name="AnchorZ" xml:space="preserve"><value>Z</value></data>
|
||||
<data name="AnchorDesc" xml:space="preserve"><value>所选锚点的坐标</value></data>
|
||||
</root>
|
||||
@@ -107,4 +107,9 @@
|
||||
<data name="DiagnosticCompile" xml:space="preserve"><value>語法錯誤</value></data>
|
||||
<data name="DiagnosticRuntime" xml:space="preserve"><value>執行時錯誤</value></data>
|
||||
<data name="DiagnosticTimeout" xml:space="preserve"><value>執行逾時</value></data>
|
||||
<data name="AnchorGroup" xml:space="preserve"><value>錨點</value></data>
|
||||
<data name="AnchorX" xml:space="preserve"><value>X</value></data>
|
||||
<data name="AnchorY" xml:space="preserve"><value>Y</value></data>
|
||||
<data name="AnchorZ" xml:space="preserve"><value>Z</value></data>
|
||||
<data name="AnchorDesc" xml:space="preserve"><value>所選錨點的座標</value></data>
|
||||
</root>
|
||||
@@ -1,10 +1,10 @@
|
||||
<Project Sdk="Microsoft.NET.Sdk">
|
||||
<Project Sdk="Microsoft.NET.Sdk">
|
||||
|
||||
<PropertyGroup>
|
||||
<TargetFramework>net10.0-windows10.0.19041.0</TargetFramework>
|
||||
<UseWPF>true</UseWPF>
|
||||
<ImplicitUsings>enable</ImplicitUsings>
|
||||
<Version>1.16.0</Version>
|
||||
<Version>1.20.1</Version>
|
||||
<Platforms>AnyCPU;x64</Platforms>
|
||||
<Nullable>enable</Nullable>
|
||||
<AllowUnsafeBlocks>true</AllowUnsafeBlocks>
|
||||
@@ -97,6 +97,7 @@
|
||||
<ItemGroup>
|
||||
<ProjectReference Include="..\LuaScript.Kernel\LuaScript.Kernel.csproj" />
|
||||
<ProjectReference Include="..\LuaScript.Compat\LuaScript.Compat.csproj" />
|
||||
<ProjectReference Include="..\LuaScript.Gpu\LuaScript.Gpu.csproj" />
|
||||
<ProjectReference Include="..\LuaScript.Media\LuaScript.Media.csproj" />
|
||||
<ProjectReference Include="..\LuaScript.Runtime\LuaScript.Runtime.csproj" />
|
||||
</ItemGroup>
|
||||
|
||||
@@ -0,0 +1,83 @@
|
||||
using Vortice;
|
||||
using YukkuriMovieMaker.Commons;
|
||||
using YukkuriMovieMaker.Player.Video;
|
||||
|
||||
namespace LuaScript
|
||||
{
|
||||
internal sealed class SceneImageRenderer(IGraphicsDevicesAndContext devices) : IDisposable
|
||||
{
|
||||
[ThreadStatic]
|
||||
private static bool t_rendering;
|
||||
|
||||
private readonly Dictionary<Guid, ITimelineSource> _sources = [];
|
||||
private GraphicsDevicesAndContext? _ctx;
|
||||
private PixelBufferManager? _pixels;
|
||||
|
||||
public bool TryRender(EffectDescription desc, string name, double time, out byte[] pixels, out int width, out int height)
|
||||
{
|
||||
pixels = [];
|
||||
width = 0;
|
||||
height = 0;
|
||||
|
||||
if (t_rendering)
|
||||
return false;
|
||||
|
||||
var info = FindScene(desc, name);
|
||||
if (info is null)
|
||||
return false;
|
||||
|
||||
_ctx ??= new GraphicsDevicesAndContext(devices);
|
||||
if (!_sources.TryGetValue(info.ID, out var source))
|
||||
{
|
||||
if (!info.TryCreateVideoSource(_ctx, out source))
|
||||
return false;
|
||||
_sources[info.ID] = source;
|
||||
}
|
||||
|
||||
int w = Math.Max(1, info.Width);
|
||||
int h = Math.Max(1, info.Height);
|
||||
|
||||
t_rendering = true;
|
||||
try
|
||||
{
|
||||
source.Update(TimeSpan.FromSeconds(time), desc.Usage);
|
||||
_pixels ??= new PixelBufferManager(_ctx);
|
||||
pixels = _pixels.LoadInputPixels(source.Output, new RawRectF(-w / 2f, -h / 2f, w / 2f, h / 2f), w, h);
|
||||
}
|
||||
catch
|
||||
{
|
||||
_sources.Remove(info.ID);
|
||||
source.Dispose();
|
||||
pixels = [];
|
||||
return false;
|
||||
}
|
||||
finally
|
||||
{
|
||||
t_rendering = false;
|
||||
}
|
||||
|
||||
width = w;
|
||||
height = h;
|
||||
return true;
|
||||
}
|
||||
|
||||
private static ISceneInfo? FindScene(EffectDescription desc, string name)
|
||||
{
|
||||
foreach (var info in desc.Scenes)
|
||||
{
|
||||
if (info.ID != desc.SceneId && string.Equals(info.Name, name, StringComparison.Ordinal))
|
||||
return info;
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
public void Dispose()
|
||||
{
|
||||
foreach (var source in _sources.Values)
|
||||
source.Dispose();
|
||||
_sources.Clear();
|
||||
_pixels?.Dispose();
|
||||
_ctx?.Dispose();
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,10 +1,20 @@
|
||||
using YukkuriMovieMaker.Commons;
|
||||
using YukkuriMovieMaker.Project.Items;
|
||||
|
||||
namespace LuaScript
|
||||
{
|
||||
internal sealed class SceneObjectResolver : ISceneObjectResolver
|
||||
{
|
||||
internal readonly record struct Entry(string Tag, int Frame, int Length, int Layer, VisualItem Item);
|
||||
internal readonly record struct Entry(
|
||||
string Tag,
|
||||
int Frame,
|
||||
int Length,
|
||||
int Layer,
|
||||
IVideoItem Item,
|
||||
Animation? Volume,
|
||||
string Character,
|
||||
string Text,
|
||||
string Kind);
|
||||
|
||||
private readonly Entry[] _entries;
|
||||
private readonly int _fps;
|
||||
@@ -46,24 +56,34 @@ namespace LuaScript
|
||||
|
||||
private SceneObjectInfo Evaluate(in Entry entry, int timelineFrame)
|
||||
{
|
||||
var visual = entry.Item;
|
||||
var video = entry.Item;
|
||||
int length = entry.Length;
|
||||
int local = Math.Clamp(timelineFrame - entry.Frame, 0, length);
|
||||
|
||||
double x = visual.X.GetValue(local, length, _fps);
|
||||
double y = visual.Y.GetValue(local, length, _fps);
|
||||
double z = visual.Z.GetValue(local, length, _fps);
|
||||
double zoom = visual.Zoom.GetValue(local, length, _fps) / 100d;
|
||||
double rz = visual.Rotation.GetValue(local, length, _fps);
|
||||
double x = video.X.GetValue(local, length, _fps);
|
||||
double y = video.Y.GetValue(local, length, _fps);
|
||||
double z = video.Z.GetValue(local, length, _fps);
|
||||
double zoom = video.Zoom.GetValue(local, length, _fps) / 100d;
|
||||
double rz = video.Rotation.GetValue(local, length, _fps);
|
||||
|
||||
double opacity = visual.Opacity.GetValue(local, length, _fps) / 100d;
|
||||
double opacity = video.Opacity.GetValue(local, length, _fps) / 100d;
|
||||
double timeSec = _fps > 0 ? local / (double)_fps : 0d;
|
||||
double durationSec = _fps > 0 ? length / (double)_fps : 0d;
|
||||
double fadeIn = visual.FadeIn <= 0d ? 1d : Math.Min(1d, timeSec / visual.FadeIn);
|
||||
double fadeOut = visual.FadeOut <= 0d ? 1d : Math.Min(1d, (durationSec - timeSec) / visual.FadeOut);
|
||||
double fadeIn = video.FadeIn <= 0d ? 1d : Math.Min(1d, timeSec / video.FadeIn);
|
||||
double fadeOut = video.FadeOut <= 0d ? 1d : Math.Min(1d, (durationSec - timeSec) / video.FadeOut);
|
||||
double alpha = opacity * Math.Min(fadeIn, fadeOut) * 255d;
|
||||
|
||||
return new SceneObjectInfo(entry.Tag, IsExist(entry, timelineFrame), x, y, z, zoom, rz, alpha, entry.Layer);
|
||||
double volume = 0d;
|
||||
if (entry.Volume is { } volumeAnimation)
|
||||
{
|
||||
try { volume = volumeAnimation.GetValue(local, length, _fps); }
|
||||
catch { volume = 0d; }
|
||||
}
|
||||
|
||||
return new SceneObjectInfo(
|
||||
entry.Tag, IsExist(entry, timelineFrame),
|
||||
x, y, z, zoom, rz, alpha, entry.Layer,
|
||||
length, volume, entry.Character, entry.Text, entry.Kind);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -58,14 +58,28 @@
|
||||
obj.setpixel(x, y, r2, g2, b2 [, a2])
|
||||
end
|
||||
end
|
||||
الشكل التالي الذي يستخدم getpixeldata يتحول إلى نواة أيضاً.
|
||||
local data = obj.getpixeldata()
|
||||
for y = 0, data.height - 1 do
|
||||
for x = 0, data.width - 1 do
|
||||
local i = (y * data.width + x) * 4
|
||||
local r = data:get(i + 1)
|
||||
data:set(i + 1, r2)
|
||||
data:set(i + 2, g2)
|
||||
data:set(i + 3, b2)
|
||||
end
|
||||
end
|
||||
obj.putpixeldata(data)
|
||||
· يجوز في الجسم استخدام العمليات الحسابية و math.* والمقارنات
|
||||
وصيغة العتبة "cond and value1 or value2" ومتغيرات local فقط.
|
||||
· يجوز الإشارة فقط إلى البكسل الجاري معالجته (getpixel(x, y))
|
||||
وقيم مثل obj/scene/time.
|
||||
وصيغة العتبة "cond and value1 or value2" والإسناد الشرطي إلى
|
||||
متغيرات local عبر if/elseif/else ومتغيرات local فقط.
|
||||
· يجوز أيضاً استخدام أسماء بديلة لحدود الحلقة مثل local w = obj.w.
|
||||
· يجوز الإشارة فقط إلى البكسل الجاري معالجته وقيم مثل
|
||||
obj/scene/time.
|
||||
· أي استخدام لأخذ عينات الجوار (التمويه، إلخ) أو الكتابة إلى
|
||||
إحداثيات أخرى أو getpixeldata أو getobject أو عمليات
|
||||
الجداول/السلاسل أو جُمَل if لا يتحول إلى نواة ويُنفَّذ تلقائياً
|
||||
على المحرك التقليدي.
|
||||
إحداثيات أخرى أو استدعاء setpixel أو set داخل جملة if أو
|
||||
getobject أو عمليات الجداول/السلاسل لا يتحول إلى نواة
|
||||
ويُنفَّذ تلقائياً على المحرك التقليدي.
|
||||
|
||||
مثال (يجعل شكلاً أبيض أحمر):
|
||||
--!gpu
|
||||
@@ -318,10 +332,15 @@
|
||||
※ عند وجود عدة عناصر تحمل الوسم نفسه، يُعاد العنصر الظاهر في
|
||||
الإطار الهدف بأولوية. وإن لم يكن أي منها ظاهرًا، يُعاد أول
|
||||
عنصر مطابق.
|
||||
※ عناصر الصوت (أصوات مُركَّبة وغيرها) مشمولة أيضًا. بالنسبة لعنصر
|
||||
صوتي، فإن الإحداثيات والمقياس والدوران والشفافية تخص عرض
|
||||
الترجمة (الجيماكو) الخاص به.
|
||||
※ القيم المُعادة هي إحداثيات العنصر ودورانه ومقياسه الخاصة به.
|
||||
ولا تتضمن التحويلات الناتجة عن التحكم بالمجموعة أو التحكم
|
||||
بالكاميرا أو التأثيرات الأعلى.
|
||||
※ تستخدم كل قيمة نظام الوحدات نفسه المستخدم في جدول obj.
|
||||
※ .character / .text / .volume / .kind / .length امتدادات خاصة
|
||||
بـ YMM4 لا توجد في AviUtl. وتعمل في كِلا المحركين.
|
||||
tag : النص المضبوط في ملاحظة العنصر الهدف
|
||||
frame : الإطار المطلق على المخطط الزمني المراد أخذه (اختياري)
|
||||
القيمة المُعادة : جدول معلومات الكائن. يُعيد nil عند عدم وجود
|
||||
@@ -341,6 +360,12 @@
|
||||
.rzr : زاوية الدوران حول المحور Z (بالراديان)
|
||||
.alpha : الشفافية (0.0 - 255.0، مع تطبيق التلاشي)
|
||||
.layer : رقم الطبقة التي وُضع فيها
|
||||
.length : طول العنصر (عدد الإطارات)
|
||||
.volume : القيمة الحالية لإعداد مستوى الصوت (لعناصر الصوت فقط؛ وإلا 0)
|
||||
.character : اسم الشخصية (لعناصر الصوت فقط؛ وإلا سلسلة فارغة)
|
||||
.text : الحوار أو النص المعروض (لعناصر الصوت والنص فقط؛
|
||||
وإلا سلسلة فارغة)
|
||||
.kind : اسم نوع العنصر (مثل VoiceItem، TextItem، ImageItem)
|
||||
مثال:
|
||||
local funnel = obj.getobject("funnel")
|
||||
if funnel then
|
||||
@@ -354,6 +379,11 @@
|
||||
obj.x = src.x
|
||||
obj.y = src.y
|
||||
end
|
||||
تغيير اللون حسب اسم الشخصية (ملاحظة الهدف هي "voice"):
|
||||
local v = obj.getobject("voice")
|
||||
if v and v.character == "ماريسا" then
|
||||
obj.effect("أحادي اللون", "القوة", 100, "color", 0xffee55)
|
||||
end
|
||||
|
||||
○ obj.getpixel(x, y)
|
||||
يسترد معلومات البكسل عند الإحداثيات المحددة.
|
||||
@@ -437,9 +467,11 @@
|
||||
|
||||
○ obj.load(الهدف، ...)
|
||||
يستبدل مخزن الكائن بمحتوى مُولَّد. تُدعم الأهداف "figure" و"text"
|
||||
و"image" (ملف صورة) و"movie" (ملف فيديو). بعد التحميل تُحدَّث
|
||||
و"image" (ملف صورة) و"movie" (ملف فيديو) و"scene" (مشهد المشروع)
|
||||
و"brush" (نمط YMM4). بعد التحميل تُحدَّث
|
||||
obj.w / obj.h وغيرها إلى الحجم المُولَّد، ويمكن قراءتها بـ getpixel
|
||||
مباشرة بعد التحميل. يعمل على محرك MoonSharp والمحرك السريع (LuaJIT).
|
||||
※ "scene" و"brush" امتدادان خاصان بـ YMM4 لا وجود لهما في AviUtl.
|
||||
|
||||
obj.load("figure", name, color, size [, line [, aspect]])
|
||||
يُولّد شكلاً ويستبدل المخزن (متوسَّطاً).
|
||||
@@ -471,6 +503,42 @@
|
||||
الفيديو الأصلية (MP4 / MOV / MKV / WebM / AVI / FLV / ASF).
|
||||
مثال: obj.load("movie", "C:\\mov\\clip.mp4", obj.time)
|
||||
|
||||
obj.load("scene", sceneName [, time])
|
||||
يرسم مشهداً آخر من المشروع ويستبدل المخزن.
|
||||
sceneName : الاسم الظاهر في قائمة المشاهد.
|
||||
time : بالثواني. الافتراضي obj.time عند الحذف.
|
||||
※ لا يمكن تحديد المشهد الذي يقع عليه الكائن الحالي، كما
|
||||
يُرفض تحميل مشهد من داخل رسم مشهد آخر.
|
||||
※ الإطارات التي تُحمِّل مشهداً تتجاوز ذاكرة التخزين المؤقت
|
||||
للرسم ويُعاد تنفيذها في كل مرة.
|
||||
مثال: obj.load("scene", "مشهد فرعي", obj.time)
|
||||
|
||||
obj.load("brush", patternName [, width [, height]])
|
||||
يُولّد صورة مملوءة بنمط (فرشاة) من YMM4 ويستبدل المخزن.
|
||||
يمكن أيضاً استخدام الأنماط المضافة عبر إضافات الفرش.
|
||||
patternName : الاسم الظاهر في قائمة الأنماط.
|
||||
width, height : حجم الإخراج بالبكسل. الافتراضي
|
||||
obj.w / obj.h الحاليان عند الحذف.
|
||||
※ يُرسم النمط بمعاملاته الافتراضية.
|
||||
مثال: obj.load("brush", "خطوط", 400, 300)
|
||||
|
||||
○ obj.brush(patternName [, width, height] [, paramName, value, ...])
|
||||
يرسم نمطاً (فرشاة) من YMM4 مع تحديد المعاملات ويستبدل المخزن.
|
||||
الرسم مطابق لـ obj.load("brush")، ويمكن إضافة إلى ذلك تغيير
|
||||
معاملات النمط بأزواج الاسم والقيمة نفسها المستخدمة في obj.effect.
|
||||
patternName : الاسم الظاهر في قائمة الأنماط.
|
||||
width, height : حجم الإخراج بالبكسل. الافتراضي obj.w / obj.h
|
||||
الحاليان. يُفسَّران كحجم فقط عندما يُعطى كلاهما
|
||||
كرقمين.
|
||||
paramName : الاسم الظاهر لإعداد النمط، أو اسم الخاصية
|
||||
الداخلي.
|
||||
value : رقم أو قيمة منطقية أو نص. الألوان أرقام بصيغة
|
||||
0xRRGGBB.
|
||||
※ المعاملات غير المحددة تُرسم بقيمها الافتراضية. الاستدعاء بلا
|
||||
أزواج يعادل obj.load("brush").
|
||||
※ هذا امتداد خاص بـ YMM4 لا وجود له في AviUtl.
|
||||
مثال: obj.brush("خطوط", "Angle", 45, "Color1", 0xff3366)
|
||||
|
||||
○ obj.setfont(font [, size [, style [, color]]])
|
||||
يحدد الخط المستخدم في obj.load("text").
|
||||
style : أعلام بِتّية. 1=عريض، 2=مائل، 3=عريض+مائل.
|
||||
@@ -544,12 +612,96 @@
|
||||
* يتخطى الاستدعاء في البيئات التي لا تتوفر فيها وحدة معالجة
|
||||
رسومات صالحة.
|
||||
|
||||
○ obj.fill(r, g, b [, a [, x, y, w, h]]) (امتداد خاص بـ YMM4)
|
||||
يملأ صورة الكائن بلون محدد. يعطى اللون بصيغة RGBA مباشرة من 0 إلى
|
||||
255 (نفس نموذج الألوان في obj.setpixel).
|
||||
r, g, b : مكونات اللون (0-255).
|
||||
a : الشفافية (0-255). القيمة الافتراضية 255.
|
||||
x, y, w, h: المستطيل المراد ملؤه. الافتراضي كامل الصورة، ويقص ما خرج
|
||||
عن النطاق.
|
||||
مثال: obj.fill(0, 0, 0, 0) -- مسح الكل إلى شفاف
|
||||
obj.fill(255, 0, 0, 255, 10, 10, 20, 20)
|
||||
يعمل على المحركين معا.
|
||||
|
||||
○ obj.getpixelregion(x, y, w, h) (امتداد خاص بـ YMM4)
|
||||
يقرأ منطقة مستطيلة من البكسلات إلى مصفوفة RGBA مباشرة. الترتيب هو
|
||||
r, g, b, a لكل بكسل ويبدأ من 1 (الفهرس (صف*w+عمود)*4+1..+4). البكسلات
|
||||
خارج الصورة تكون 0,0,0,0.
|
||||
القيمة المعادة: مصفوفة بطول w*h*4.
|
||||
مثال: local t = obj.getpixelregion(0, 0, obj.w, obj.h)
|
||||
|
||||
○ obj.putpixelregion(x, y, w, h, البيانات) (امتداد خاص بـ YMM4)
|
||||
يكتب مصفوفة بنفس ترتيب obj.getpixelregion إلى منطقة مستطيلة. البكسلات
|
||||
خارج حدود الصورة لا تكتب.
|
||||
البيانات : مصفوفة RGBA مباشرة بطول w*h*4 (تبدأ من 1).
|
||||
مثال: obj.putpixelregion(0, 0, obj.w, obj.h, t)
|
||||
|
||||
○ obj.convolve(النواة, الحجم [, المقسوم_عليه [, الإزاحة]]) (امتداد خاص بـ YMM4)
|
||||
يطبق التفاف بحجم الحجم×الحجم على صورة الكائن. مفيد للتمويه والتوضيح
|
||||
واكتشاف الحواف وغيرها.
|
||||
النواة : عدد الحجم*الحجم من المعاملات (حسب الصفوف، تبدأ من 1).
|
||||
الحجم : عدد فردي (3، 5، 7 …). الزوجي أو الأقل من 1 يتجاهل.
|
||||
المقسوم_عليه : يقسم مجموع كل بكسل على هذه القيمة. الافتراضي مجموع
|
||||
النواة (1 عندما يكون المجموع 0).
|
||||
الإزاحة : تضاف إلى كل مكون بعد القسمة. الافتراضي 0.
|
||||
تمدد بكسلات الحواف بأقرب بكسل. يطبق على r, g, b, a جميعا.
|
||||
مثال: obj.convolve({1,1,1, 1,1,1, 1,1,1}, 3) -- تمويه متوسط
|
||||
obj.convolve({0,-1,0, -1,5,-1, 0,-1,0}, 3) -- توضيح
|
||||
يعمل على المحركين معا.
|
||||
|
||||
○ obj.resize(العرض, الارتفاع [, الترشيح]) (امتداد خاص بـ YMM4)
|
||||
يغير حجم صورة الكائن إلى الحجم المحدد. تحدّث أيضا obj.w / obj.h وبقية
|
||||
الأبعاد.
|
||||
العرض, الارتفاع : أعداد صحيحة >= 1.
|
||||
الترشيح : "nearest" لأقرب جار، أو خطي عند الحذف.
|
||||
مثال: obj.resize(obj.w * 2, obj.h * 2)
|
||||
يعمل على المحركين معا. يترك التشغيل السريع الصورة دون تغيير عندما
|
||||
تتجاوز النتيجة أقصى حجم للصورة.
|
||||
|
||||
○ obj.getvalue(الهدف)
|
||||
يحصل على القيمة الحالية لـ obj (مثل obj.x و obj.track0).
|
||||
الهدف : "x","y","z","ox","oy","rx","ry","rz","zoom","aspect",
|
||||
"alpha","sx","sy","track0"~"track3","time","frame" إلخ.
|
||||
المُرجَع : رقم (0 لهدف غير معروف).
|
||||
|
||||
○ obj.getaudio(buf, file [, type [, size]])
|
||||
يحصل على بيانات الصوت.
|
||||
buf : جدول يستقبل البيانات. تُخزَّن القيم في buf[1]..buf[n]. مرِّر
|
||||
nil لاستلام الجدول كقيمة إرجاع ثالثة.
|
||||
file : مسار ملف صوتي. تُقبل أيضًا الأسماء الخاصة التالية.
|
||||
"audiobuffer" : يقرأ صوت المشهد الكامل قيد التحرير (جميع
|
||||
العناصر على الخط الزمني ممزوجة معًا).
|
||||
"itembuffer" : يقرأ صوت العنصر الذي أُضيف إليه هذا التأثير
|
||||
(بعد تطبيق مستوى الصوت والتوزيع والتلاشي
|
||||
وتأثيرات الصوت). هذا امتداد خاص بـ YMM4.
|
||||
type : نوع البيانات المطلوبة كسلسلة نصية. الافتراضي "pcm".
|
||||
"pcm" : PCM أحادي على مقياس 16 بت (من -32768 إلى 32767).
|
||||
"spectrum" : مستوى الصوت لكل نطاق تردد (تقريبًا من 0 إلى 32768).
|
||||
size هو عدد النطاقات (حتى 512، الافتراضي 32).
|
||||
"fourier" : مقادير تحويل فورييه المتقطع (تقريبًا من 0.0 إلى
|
||||
1.0). نطاق التردد من 1/2048 إلى 1/2، والعدد
|
||||
الافتراضي 1024.
|
||||
"xxxx.l" / "xxxx.r" : نسخة القناة اليسرى / اليمنى من الأنواع
|
||||
أعلاه. بدون لاحقة يُؤخذ متوسط القناتين.
|
||||
size : عدد القيم المطلوبة. قد يُرجَع عدد أقل. يمكن قراءة 1024
|
||||
قيمة كحد أقصى في كل استدعاء.
|
||||
المُرجَع : عدد القيم المقروءة، ومعدل أخذ العينات[, الجدول].
|
||||
موضع القراءة هو موضع الخط الزمني الحالي مع "audiobuffer"،
|
||||
وموضع التشغيل الحالي للكائن (obj.time) فيما عدا ذلك. يُرجِع
|
||||
"pcm" عينات متتالية من ذلك الموضع، بينما يحلل "spectrum" /
|
||||
"fourier" الفترة التي تبدأ هناك.
|
||||
مثال:
|
||||
local buf = {}
|
||||
local n = obj.getaudio(buf, "audiobuffer", "spectrum", 32)
|
||||
for i = 1, n do
|
||||
obj.draw((i - n / 2) * 8, -buf[i] / 200)
|
||||
end
|
||||
※ يعمل في كلا المحركين. عند تعذر قراءة الصوت يكون العدد 0 ولا
|
||||
يحدث أي خطأ.
|
||||
※ يُرجِع "itembuffer" العدد 0 للعناصر بلا صوت (الصور والأشكال
|
||||
وغيرها). عند تعذر استخدام المكونات الداخلية لـ YMM4 يُستخدم
|
||||
الصوت قبل تطبيق مستوى الصوت وبقية التأثيرات.
|
||||
|
||||
○ obj.getinfo(name)
|
||||
يحصل على معلومات بيئية متنوعة. الاسم غير المدعوم يُرجِع nil.
|
||||
"script_path" : يُرجِع مسار مجلد تثبيت الإضافة. ينتهي بفاصل مسار.
|
||||
@@ -619,7 +771,8 @@
|
||||
"arm" : يصل مركز الكائن بكل نقطة إرساء بالترتيب.
|
||||
"xyz" : يعامل النقاط كإحداثيات ثلاثية الأبعاد. الافتراضي ثنائي.
|
||||
يعيد عدد نقاط الإرساء. يعمل في المحركين معاً.
|
||||
وضع شريط "track" غير مدعوم حالياً ويعيد 0.
|
||||
يُدعم أيضاً الاسم "track"؛ وتضع القيمة 0 نقطة واحدة.
|
||||
يمكن ضبط نقطة الإرساء المحددة رقمياً عبر منزلقات X / Y / Z في مجموعة مرساة.
|
||||
مثال:
|
||||
num = obj.track0
|
||||
obj.setanchor("pos", num, "loop")
|
||||
@@ -821,6 +974,17 @@
|
||||
x in <1..5> يفحص 1 <= x and x <= 5.
|
||||
<1..<5> لا يشمل الحد الأعلى. يُقيَّم الطرف الأيسر مرة واحدة.
|
||||
|
||||
○ [fast] (علامة التسريع) * امتداد خاص بـ YMM4
|
||||
تُفوَّض obj.fill / obj.convolve / obj.resize إلى وحدة معالجة الرسوميات
|
||||
تلقائيًا عندما يتجاوز حجم المعالجة حدًا معينًا ويتم التحقق من تطابق نتيجة
|
||||
وحدة معالجة الرسوميات مع نتيجة المعالج. [fast] علامة مساعدة تصرّح
|
||||
بالنية صراحةً، وإضافتها لا تغيّر السلوك. يمكن وضع العلامة في سطر
|
||||
مستقل أو في السطر نفسه.
|
||||
مثال: [fast]
|
||||
obj.convolve(kernel, 5)
|
||||
* يظهر خطأ عندما يسبق [fast] أي شيء غير هذه الدوال الثلاث.
|
||||
* يعمل في محرك MoonSharp والمحرك الأصلي على حد سواء.
|
||||
|
||||
|
||||
- أمثلة على النصوص البرمجية -
|
||||
|
||||
@@ -900,7 +1064,7 @@
|
||||
يُدعم الرسم والتركيب عبر obj.draw / obj.drawpoly، وعمليات المخزن
|
||||
عبر obj.copybuffer، والتوليد والتحميل عبر
|
||||
obj.load("figure"/"text"/"image"/"movie")، و obj.setfont، و obj.effect،
|
||||
و obj.getvalue، و obj.getinfo، و obj.setoption / obj.getoption / obj.pixeloption.
|
||||
و obj.getvalue، و obj.getaudio، و obj.getinfo، و obj.setoption / obj.getoption / obj.pixeloption.
|
||||
انظر "جدول obj - الدوال" للتفاصيل.
|
||||
|
||||
○ خريطة توافق AviUtl / AviUtl2 لـ obj.effect
|
||||
@@ -943,12 +1107,11 @@
|
||||
× تحميل الوحدات عبر require، والوصول العشوائي إلى الملفات مثل
|
||||
io / dofile (تحميل الصور / الفيديو عبر obj.load مدعوم مع التحقق
|
||||
من الترويسة).
|
||||
× obj.setanchor وما شابه.
|
||||
|
||||
|
||||
- الميزات غير المدعومة / القيود -
|
||||
|
||||
× obj.rand1()، obj.mes()، obj.setanchor() وما شابه من AviUtl2 غير مدعومة.
|
||||
× obj.rand1()، obj.mes() وما شابه من AviUtl2 غير مدعومة.
|
||||
× الوصول العشوائي إلى الملفات من النصوص (require, dofile, io وما شابه) غير مدعوم.
|
||||
فقط obj.load("image"/"movie") يحمّل الملفات المؤكَّد أنها وسائط أصلية عبر
|
||||
التحقق من الترويسة الأولى.
|
||||
|
||||
@@ -60,15 +60,29 @@
|
||||
obj.setpixel(x, y, r2, g2, b2 [, a2])
|
||||
end
|
||||
end
|
||||
The following form using getpixeldata becomes a kernel as well.
|
||||
local data = obj.getpixeldata()
|
||||
for y = 0, data.height - 1 do
|
||||
for x = 0, data.width - 1 do
|
||||
local i = (y * data.width + x) * 4
|
||||
local r = data:get(i + 1)
|
||||
data:set(i + 1, r2)
|
||||
data:set(i + 2, g2)
|
||||
data:set(i + 3, b2)
|
||||
end
|
||||
end
|
||||
obj.putpixeldata(data)
|
||||
- The body may use only arithmetic, math.*, comparisons, the
|
||||
threshold idiom "cond and value1 or value2", and local
|
||||
threshold idiom "cond and value1 or value2", conditional
|
||||
assignment to local variables via if/elseif/else, and local
|
||||
variables.
|
||||
- It may reference only the current pixel being processed
|
||||
(getpixel(x, y)) and values such as obj/scene/time.
|
||||
- Loop bounds may also use aliases such as local w = obj.w.
|
||||
- It may reference only the current pixel being processed and
|
||||
values such as obj/scene/time.
|
||||
- Anything using neighbor sampling (blur, etc.), writes to other
|
||||
coordinates, getpixeldata, getobject, table/string operations,
|
||||
or if statements is not turned into a kernel and automatically
|
||||
runs on the classic engine.
|
||||
coordinates, setpixel or set calls inside an if statement,
|
||||
getobject, or table/string operations is not turned into a
|
||||
kernel and automatically runs on the classic engine.
|
||||
|
||||
Example (turns a white figure red):
|
||||
--!gpu
|
||||
@@ -329,10 +343,15 @@
|
||||
* If multiple items share the same tag, the item visible at the
|
||||
target frame is returned with priority. If none is visible,
|
||||
the first matching item is returned.
|
||||
* Voice items (synthesized voices, etc.) are also targeted. For a
|
||||
voice item, the coordinates, scale, rotation and opacity are
|
||||
those of its caption (subtitle) display.
|
||||
* The returned values are the item's own coordinates, rotation
|
||||
and scale. Transforms from group control, camera control or
|
||||
upper effects are NOT included.
|
||||
* Each value uses the same unit system as the obj table.
|
||||
* .character / .text / .volume / .kind / .length are YMM4-specific
|
||||
extensions that do not exist in AviUtl. They work on both engines.
|
||||
tag : The string set in the target item's remark
|
||||
frame : The absolute timeline frame to sample (optional)
|
||||
Return : An object information table. Returns nil when no
|
||||
@@ -352,6 +371,12 @@
|
||||
.rzr : Rotation angle around Z axis (radians)
|
||||
.alpha : Opacity (0.0 - 255.0, fade applied)
|
||||
.layer : Layer number where it is placed
|
||||
.length : Item length (number of frames)
|
||||
.volume : Current volume setting (voice items only; 0 otherwise)
|
||||
.character : Character name (voice items only; empty string otherwise)
|
||||
.text : Dialogue or displayed text (voice and text items only;
|
||||
empty string otherwise)
|
||||
.kind : Item type name (e.g. VoiceItem, TextItem, ImageItem)
|
||||
Example:
|
||||
local funnel = obj.getobject("funnel")
|
||||
if funnel then
|
||||
@@ -365,6 +390,11 @@
|
||||
obj.x = src.x
|
||||
obj.y = src.y
|
||||
end
|
||||
Recoloring by character name (target remark is "voice"):
|
||||
local v = obj.getobject("voice")
|
||||
if v and v.character == "Marisa" then
|
||||
obj.effect("Monochrome", "strength", 100, "color", 0xffee55)
|
||||
end
|
||||
|
||||
o obj.getpixel(x, y)
|
||||
Retrieves pixel information at the specified coordinates.
|
||||
@@ -449,10 +479,13 @@
|
||||
|
||||
o obj.load(target, ...)
|
||||
Replaces the object buffer with generated content. The targets
|
||||
"figure", "text", "image" (image file) and "movie" (video file)
|
||||
are supported. After loading, obj.w / obj.h, etc. are updated to the
|
||||
"figure", "text", "image" (image file), "movie" (video file),
|
||||
"scene" (project scene) and "brush" (YMM4 pattern) are supported.
|
||||
After loading, obj.w / obj.h, etc. are updated to the
|
||||
generated size and can be read by getpixel right after the load.
|
||||
Works on both the MoonSharp and the fast (LuaJIT) engine.
|
||||
* "scene" and "brush" are YMM4-only extensions that do not exist
|
||||
in AviUtl.
|
||||
|
||||
obj.load("figure", name, color, size [, line [, aspect]])
|
||||
Generates a shape and replaces the buffer (centered).
|
||||
@@ -484,6 +517,44 @@
|
||||
videos (MP4 / MOV / MKV / WebM / AVI / FLV / ASF) are loaded.
|
||||
Example: obj.load("movie", "C:\\mov\\clip.mp4", obj.time)
|
||||
|
||||
obj.load("scene", sceneName [, time])
|
||||
Renders another scene of the project and replaces the buffer.
|
||||
sceneName : The name shown in the scene list.
|
||||
time : Seconds. Defaults to obj.time when omitted.
|
||||
* The scene the current object belongs to cannot be specified.
|
||||
Loading a scene from inside a scene render is also rejected.
|
||||
* Frames that load a scene bypass the render cache and are
|
||||
re-executed every time.
|
||||
Example: obj.load("scene", "Sub Scene", obj.time)
|
||||
|
||||
obj.load("brush", patternName [, width [, height]])
|
||||
Generates an image filled with a YMM4 pattern (brush) and
|
||||
replaces the buffer. Patterns added by brush plugins can
|
||||
also be used.
|
||||
patternName : The name shown in the pattern list.
|
||||
width, height : Output size in pixels. Defaults to the
|
||||
current obj.w / obj.h when omitted.
|
||||
* The pattern is drawn with its default parameters.
|
||||
Example: obj.load("brush", "Stripe", 400, 300)
|
||||
|
||||
o obj.brush(patternName [, width, height] [, paramName, value, ...])
|
||||
Draws a YMM4 pattern (brush) with parameter overrides and replaces
|
||||
the buffer. The drawing is the same as obj.load("brush"), and in
|
||||
addition the pattern parameters can be changed with the same
|
||||
name-and-value pairs as obj.effect.
|
||||
patternName : The name shown in the pattern list.
|
||||
width, height : Output size in pixels. Defaults to the current
|
||||
obj.w / obj.h. Interpreted as the size only when
|
||||
both are given as numbers.
|
||||
paramName : The display name of a pattern setting, or its
|
||||
internal property name.
|
||||
value : A number, a boolean or a string. Colors are
|
||||
0xRRGGBB numbers.
|
||||
* Parameters that are not specified are drawn with their default
|
||||
values. A call without pairs equals obj.load("brush").
|
||||
* This is a YMM4-only extension that does not exist in AviUtl.
|
||||
Example: obj.brush("Stripe", "Angle", 45, "Color1", 0xff3366)
|
||||
|
||||
o obj.setfont(font [, size [, style [, color]]])
|
||||
Sets the font used by obj.load("text").
|
||||
style : Bit flags. 1=bold, 2=italic, 3=bold+italic.
|
||||
@@ -563,12 +634,103 @@
|
||||
onto a transparent scene-sized area.
|
||||
* The call is skipped in environments without a usable GPU.
|
||||
|
||||
o obj.fill(r, g, b [, a [, x, y, w, h]]) (YMM4 extension)
|
||||
Fills the object image with a color, given as straight RGBA in
|
||||
0-255 (same color model as obj.setpixel).
|
||||
r, g, b : Color components (0-255).
|
||||
a : Opacity (0-255). Default is 255.
|
||||
x, y, w, h: Rectangle to fill. Defaults to the whole image; out of
|
||||
range is clipped.
|
||||
Example: obj.fill(0, 0, 0, 0) -- clear to transparent
|
||||
obj.fill(255, 0, 0, 255, 10, 10, 20, 20)
|
||||
Runs on both engines.
|
||||
|
||||
o obj.getpixelregion(x, y, w, h) (YMM4 extension)
|
||||
Reads a rectangular region of pixels into a straight RGBA array.
|
||||
The layout is r, g, b, a per pixel and is 1-based (index
|
||||
(row*w+col)*4+1..+4). Pixels outside the image are 0,0,0,0.
|
||||
Returns: an array of length w*h*4.
|
||||
Example: local t = obj.getpixelregion(0, 0, obj.w, obj.h)
|
||||
|
||||
o obj.putpixelregion(x, y, w, h, data) (YMM4 extension)
|
||||
Writes an array in the same layout as obj.getpixelregion back into a
|
||||
rectangular region. Pixels outside the image are not written.
|
||||
data : straight RGBA array of length w*h*4 (1-based).
|
||||
Example: obj.putpixelregion(0, 0, obj.w, obj.h, t)
|
||||
|
||||
o obj.convolve(kernel, size [, divisor [, offset]]) (YMM4 extension)
|
||||
Applies a size x size convolution to the object image. Useful for
|
||||
blur, sharpen, edge detection and so on.
|
||||
kernel : size*size coefficients, row-major and 1-based.
|
||||
size : odd number (3, 5, 7 ...). Even or below 1 is ignored.
|
||||
divisor : divides each pixel sum. Defaults to the kernel sum (1 when
|
||||
the sum is 0).
|
||||
offset : added to each component after the division. Default is 0.
|
||||
Edge pixels are extended by the nearest pixel. Applies to r, g, b, a.
|
||||
Example: obj.convolve({1,1,1, 1,1,1, 1,1,1}, 3) -- box blur
|
||||
obj.convolve({0,-1,0, -1,5,-1, 0,-1,0}, 3) -- sharpen
|
||||
Runs on both engines.
|
||||
|
||||
o obj.resize(width, height [, filter]) (YMM4 extension)
|
||||
Scales the object image to the given size. obj.w / obj.h and the
|
||||
other dimensions are updated too.
|
||||
width, height : integers >= 1.
|
||||
filter : "nearest" for nearest-neighbor, or linear when
|
||||
omitted.
|
||||
Example: obj.resize(obj.w * 2, obj.h * 2)
|
||||
Runs on both engines. The fast runtime leaves the image unchanged
|
||||
when the result exceeds the maximum image size.
|
||||
|
||||
o obj.getvalue(target)
|
||||
Gets the current value of obj (same as obj.x, obj.track0, etc.).
|
||||
target : "x","y","z","ox","oy","rx","ry","rz","zoom","aspect",
|
||||
"alpha","sx","sy","track0"~"track3","time","frame", etc.
|
||||
Returns: a number (0 for an unknown target).
|
||||
|
||||
o obj.getaudio(buf, file [, type [, size]])
|
||||
Gets audio data.
|
||||
buf : A table that receives the data. Values are stored in
|
||||
buf[1]..buf[n]. Pass nil to receive the table as the third
|
||||
return value instead.
|
||||
file : Path of an audio file. The following special names are
|
||||
also accepted.
|
||||
"audiobuffer" : Reads the audio of the whole scene being edited
|
||||
(all items on the timeline mixed together).
|
||||
"itembuffer" : Reads the audio of the item this effect is
|
||||
attached to (after volume, pan, fade, and audio
|
||||
effects are applied). This is a YMM4-specific
|
||||
extension.
|
||||
type : Kind of data to get, as a string. Defaults to "pcm".
|
||||
"pcm" : Mono PCM on a 16-bit scale (-32768 to 32767).
|
||||
"spectrum" : Volume per frequency band (roughly 0 to 32768).
|
||||
size is the number of bands (up to 512, default 32).
|
||||
"fourier" : Magnitudes of the discrete Fourier transform
|
||||
(roughly 0.0 to 1.0). The frequency range is
|
||||
1/2048 to 1/2; the default count is 1024.
|
||||
"xxxx.l" / "xxxx.r" : Left / right channel variant of the kinds
|
||||
above. Without a suffix, both channels are averaged.
|
||||
size : Number of values to get. Fewer values may be returned.
|
||||
Up to 1024 values can be read per call.
|
||||
Returns: the number of values read, the sampling rate
|
||||
[, the table].
|
||||
The read position is the current timeline position for
|
||||
"audiobuffer", and the current playback position of the object
|
||||
(obj.time) otherwise. "pcm" returns consecutive samples from that
|
||||
position; "spectrum" / "fourier" analyze the interval starting
|
||||
there.
|
||||
Example:
|
||||
local buf = {}
|
||||
local n = obj.getaudio(buf, "audiobuffer", "spectrum", 32)
|
||||
for i = 1, n do
|
||||
obj.draw((i - n / 2) * 8, -buf[i] / 200)
|
||||
end
|
||||
* Works in both engines. When the audio cannot be read, the count
|
||||
is 0 and no error is raised.
|
||||
* "itembuffer" returns a count of 0 for items without audio
|
||||
(images, shapes, etc.). When the YMM4 internals are not
|
||||
available, it falls back to the audio before volume and other
|
||||
effects are applied.
|
||||
|
||||
o obj.getinfo(name)
|
||||
Gets various environment information. An unsupported name returns nil.
|
||||
"script_path" : Returns the path of the plugin install folder. It
|
||||
@@ -645,7 +807,8 @@
|
||||
"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.
|
||||
The "track" name is also supported; a count of 0 places 1 point.
|
||||
The selected anchor can be adjusted numerically via the X / Y / Z sliders in the Anchor group.
|
||||
Example:
|
||||
num = obj.track0
|
||||
obj.setanchor("pos", num, "loop")
|
||||
@@ -850,6 +1013,17 @@
|
||||
x in <1..5> tests 1 <= x and x <= 5.
|
||||
<1..<5> excludes the upper bound. The left side is evaluated once.
|
||||
|
||||
o [fast] (acceleration marker) * YMM4 extension
|
||||
obj.fill / obj.convolve / obj.resize are delegated to the GPU
|
||||
automatically when the workload exceeds a threshold and the GPU
|
||||
result is verified to match the CPU. [fast] is an auxiliary marker
|
||||
that states the intent explicitly; adding it does not change the
|
||||
behavior. The marker may be on its own line or on the same line.
|
||||
Example: [fast]
|
||||
obj.convolve(kernel, 5)
|
||||
* An error is shown when [fast] precedes anything other than those three functions.
|
||||
* Works in both the MoonSharp and native engines.
|
||||
|
||||
|
||||
- Script Examples -
|
||||
|
||||
@@ -933,7 +1107,7 @@
|
||||
Drawing and compositing with obj.draw / obj.drawpoly, buffer
|
||||
operations with obj.copybuffer, generation and loading with
|
||||
obj.load("figure"/"text"/"image"/"movie"), obj.setfont, obj.effect,
|
||||
obj.getvalue, obj.getinfo, and obj.setoption / obj.getoption / obj.pixeloption are
|
||||
obj.getvalue, obj.getaudio, obj.getinfo, and obj.setoption / obj.getoption / obj.pixeloption are
|
||||
supported. See "obj Table - Functions" for details.
|
||||
|
||||
o AviUtl / AviUtl2 compatibility map for obj.effect
|
||||
@@ -977,12 +1151,11 @@
|
||||
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, etc.
|
||||
|
||||
|
||||
- Unsupported Features / Limitations -
|
||||
|
||||
x obj.rand1(), obj.mes(), obj.setanchor(), etc. from AviUtl2 are not supported.
|
||||
x obj.rand1(), obj.mes(), etc. from AviUtl2 are not supported.
|
||||
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.
|
||||
|
||||
@@ -61,14 +61,31 @@
|
||||
obj.setpixel(x, y, r2, g2, b2 [, a2])
|
||||
end
|
||||
end
|
||||
La siguiente forma con getpixeldata también se convierte en núcleo.
|
||||
local data = obj.getpixeldata()
|
||||
for y = 0, data.height - 1 do
|
||||
for x = 0, data.width - 1 do
|
||||
local i = (y * data.width + x) * 4
|
||||
local r = data:get(i + 1)
|
||||
data:set(i + 1, r2)
|
||||
data:set(i + 2, g2)
|
||||
data:set(i + 3, b2)
|
||||
end
|
||||
end
|
||||
obj.putpixeldata(data)
|
||||
- El cuerpo solo puede usar aritmética, math.*, comparaciones, el
|
||||
modismo de umbral "cond and valor1 or valor2" y variables local.
|
||||
- Solo puede referenciar el píxel actual en proceso
|
||||
(getpixel(x, y)) y valores como obj/scene/time.
|
||||
modismo de umbral "cond and valor1 or valor2", la asignación
|
||||
condicional a variables local mediante if/elseif/else y
|
||||
variables local.
|
||||
- Los límites del bucle también pueden usar alias como
|
||||
local w = obj.w.
|
||||
- Solo puede referenciar el píxel actual en proceso y valores
|
||||
como obj/scene/time.
|
||||
- Todo lo que use muestreo de vecinos (desenfoque, etc.),
|
||||
escrituras en otras coordenadas, getpixeldata, getobject,
|
||||
operaciones de tabla/cadena o sentencias if no se convierte en
|
||||
núcleo y se ejecuta automáticamente en el motor clásico.
|
||||
escrituras en otras coordenadas, llamadas a setpixel o set
|
||||
dentro de una sentencia if, getobject u operaciones de
|
||||
tabla/cadena no se convierte en núcleo y se ejecuta
|
||||
automáticamente en el motor clásico.
|
||||
|
||||
Ejemplo (vuelve roja una figura blanca):
|
||||
--!gpu
|
||||
@@ -329,10 +346,15 @@
|
||||
con prioridad el elemento visible en el fotograma de destino.
|
||||
Si ninguno es visible, se devuelve el primer elemento que
|
||||
coincida.
|
||||
* Los elementos de voz (voces sintetizadas, etc.) también son objetivo.
|
||||
Para un elemento de voz, las coordenadas, escala, rotación y
|
||||
opacidad corresponden a la visualización de su subtítulo.
|
||||
* Los valores devueltos son las coordenadas, rotación y escala
|
||||
propias del elemento. NO se incluyen las transformaciones por
|
||||
control de grupo, control de cámara o efectos superiores.
|
||||
* Cada valor usa el mismo sistema de unidades que la tabla obj.
|
||||
* .character / .text / .volume / .kind / .length son extensiones
|
||||
propias de YMM4 que no existen en AviUtl. Funcionan en ambos motores.
|
||||
tag : El texto definido en la observación del elemento de destino
|
||||
frame : El fotograma absoluto de la línea de tiempo (opcional)
|
||||
Retorno : Una tabla de información del objeto. Devuelve nil cuando
|
||||
@@ -352,6 +374,12 @@
|
||||
.rzr : Ángulo de rotación en el eje Z (radianes)
|
||||
.alpha : Opacidad (0.0 - 255.0, fundido aplicado)
|
||||
.layer : Número de capa donde está colocado
|
||||
.length : Duración del elemento (número de fotogramas)
|
||||
.volume : Valor actual del volumen (solo elementos de voz; 0 en otro caso)
|
||||
.character : Nombre del personaje (solo elementos de voz; cadena vacía en otro caso)
|
||||
.text : Diálogo o texto mostrado (solo elementos de voz y texto;
|
||||
cadena vacía en otro caso)
|
||||
.kind : Nombre del tipo de elemento (p. ej. VoiceItem, TextItem, ImageItem)
|
||||
Ejemplo:
|
||||
local funnel = obj.getobject("funnel")
|
||||
if funnel then
|
||||
@@ -365,6 +393,11 @@
|
||||
obj.x = src.x
|
||||
obj.y = src.y
|
||||
end
|
||||
Recolorear según el nombre del personaje (la observación del destino es "voice"):
|
||||
local v = obj.getobject("voice")
|
||||
if v and v.character == "Marisa" then
|
||||
obj.effect("Monocromo", "intensidad", 100, "color", 0xffee55)
|
||||
end
|
||||
|
||||
o obj.getpixel(x, y)
|
||||
Obtiene información del píxel en las coordenadas especificadas.
|
||||
@@ -449,10 +482,13 @@
|
||||
|
||||
o obj.load(target, ...)
|
||||
Reemplaza el búfer del objeto con contenido generado. Se admiten los
|
||||
targets "figure", "text", "image" (archivo de imagen) y "movie"
|
||||
(archivo de vídeo). Tras la carga, obj.w / obj.h, etc. se actualizan al
|
||||
targets "figure", "text", "image" (archivo de imagen), "movie"
|
||||
(archivo de vídeo), "scene" (escena del proyecto) y "brush"
|
||||
(patrón de YMM4). Tras la carga, obj.w / obj.h, etc. se actualizan al
|
||||
tamaño generado y pueden leerse con getpixel justo después de la carga.
|
||||
Funciona en el motor MoonSharp y en el motor rápido (LuaJIT).
|
||||
* "scene" y "brush" son extensiones exclusivas de YMM4 que no
|
||||
existen en AviUtl.
|
||||
|
||||
obj.load("figure", name, color, size [, line [, aspect]])
|
||||
Genera una forma y reemplaza el búfer (centrada).
|
||||
@@ -484,6 +520,45 @@
|
||||
vídeos genuinos (MP4 / MOV / MKV / WebM / AVI / FLV / ASF).
|
||||
Ejemplo: obj.load("movie", "C:\\mov\\clip.mp4", obj.time)
|
||||
|
||||
obj.load("scene", nombreEscena [, tiempo])
|
||||
Dibuja otra escena del proyecto y reemplaza el búfer.
|
||||
nombreEscena : El nombre mostrado en la lista de escenas.
|
||||
tiempo : Segundos. Por defecto obj.time.
|
||||
* No se puede indicar la escena a la que pertenece el objeto
|
||||
actual, ni cargar una escena desde dentro del dibujado de
|
||||
otra escena.
|
||||
* Los fotogramas que cargan una escena omiten la caché de
|
||||
dibujado y se vuelven a ejecutar cada vez.
|
||||
Ejemplo: obj.load("scene", "Subescena", obj.time)
|
||||
|
||||
obj.load("brush", nombrePatron [, ancho [, alto]])
|
||||
Genera una imagen rellenada con un patrón (pincel) de YMM4 y
|
||||
reemplaza el búfer. También pueden usarse patrones añadidos
|
||||
por plugins de pincel.
|
||||
nombrePatron : El nombre mostrado en la lista de patrones.
|
||||
ancho, alto : Tamaño generado en píxeles. Por defecto los
|
||||
obj.w / obj.h actuales.
|
||||
* El patrón se dibuja con sus parámetros por defecto.
|
||||
Ejemplo: obj.load("brush", "Rayas", 400, 300)
|
||||
|
||||
o obj.brush(nombrePatron [, ancho, alto] [, nombreParam, valor, ...])
|
||||
Dibuja un patrón (pincel) de YMM4 con parámetros indicados y
|
||||
reemplaza el búfer. El dibujado es el mismo que obj.load("brush"),
|
||||
y además los parámetros del patrón pueden cambiarse con los mismos
|
||||
pares de nombre y valor que obj.effect.
|
||||
nombrePatron : El nombre mostrado en la lista de patrones.
|
||||
ancho, alto : Tamaño generado en píxeles. Por defecto los
|
||||
obj.w / obj.h actuales. Solo se interpreta como
|
||||
tamaño cuando ambos se dan como números.
|
||||
nombreParam : El nombre mostrado de un ajuste del patrón, o su
|
||||
nombre de propiedad interno.
|
||||
valor : Un número, un booleano o una cadena. Los colores
|
||||
son números 0xRRGGBB.
|
||||
* Los parámetros no indicados se dibujan con sus valores por
|
||||
defecto. Una llamada sin pares equivale a obj.load("brush").
|
||||
* Es una extensión exclusiva de YMM4 que no existe en AviUtl.
|
||||
Ejemplo: obj.brush("Rayas", "Angle", 45, "Color1", 0xff3366)
|
||||
|
||||
o obj.setfont(fuente [, tamaño [, estilo [, color]]])
|
||||
Establece la fuente usada por obj.load("text").
|
||||
estilo : Bits. 1=negrita, 2=cursiva, 3=negrita+cursiva.
|
||||
@@ -566,12 +641,107 @@
|
||||
sobre un area transparente del tamano de la escena.
|
||||
* La llamada se omite en entornos sin una GPU utilizable.
|
||||
|
||||
o obj.fill(r, g, b [, a [, x, y, w, h]]) (extension de YMM4)
|
||||
Rellena la imagen del objeto con un color, dado como RGBA directo en
|
||||
0-255 (mismo modelo de color que obj.setpixel).
|
||||
r, g, b : Componentes de color (0-255).
|
||||
a : Opacidad (0-255). Por defecto 255.
|
||||
x, y, w, h: Rectangulo a rellenar. Por defecto toda la imagen; lo que
|
||||
queda fuera de rango se recorta.
|
||||
Ejemplo: obj.fill(0, 0, 0, 0) -- borrar a transparente
|
||||
obj.fill(255, 0, 0, 255, 10, 10, 20, 20)
|
||||
Funciona en ambos motores.
|
||||
|
||||
o obj.getpixelregion(x, y, w, h) (extension de YMM4)
|
||||
Lee una region rectangular de pixeles en un arreglo RGBA directo. La
|
||||
disposicion es r, g, b, a por pixel y empieza en 1 (indice
|
||||
(fila*w+col)*4+1..+4). Los pixeles fuera de la imagen son 0,0,0,0.
|
||||
Devuelve: un arreglo de longitud w*h*4.
|
||||
Ejemplo: local t = obj.getpixelregion(0, 0, obj.w, obj.h)
|
||||
|
||||
o obj.putpixelregion(x, y, w, h, datos) (extension de YMM4)
|
||||
Escribe un arreglo con la misma disposicion que obj.getpixelregion en
|
||||
una region rectangular. Los pixeles fuera de la imagen no se escriben.
|
||||
datos : arreglo RGBA directo de longitud w*h*4 (empieza en 1).
|
||||
Ejemplo: obj.putpixelregion(0, 0, obj.w, obj.h, t)
|
||||
|
||||
o obj.convolve(kernel, tamano [, divisor [, desplazamiento]]) (extension de YMM4)
|
||||
Aplica una convolucion de tamano x tamano a la imagen del objeto.
|
||||
Util para desenfoque, enfoque, deteccion de bordes, etc.
|
||||
kernel : tamano*tamano coeficientes, por filas y empieza en 1.
|
||||
tamano : numero impar (3, 5, 7 ...). Par o menor que 1 se ignora.
|
||||
divisor : divide la suma de cada pixel. Por defecto la suma del
|
||||
kernel (1 cuando la suma es 0).
|
||||
desplazamiento: se suma a cada componente tras la division. Por
|
||||
defecto 0.
|
||||
Los pixeles de borde se extienden con el pixel mas cercano. Se aplica
|
||||
a r, g, b, a.
|
||||
Ejemplo: obj.convolve({1,1,1, 1,1,1, 1,1,1}, 3) -- desenfoque
|
||||
obj.convolve({0,-1,0, -1,5,-1, 0,-1,0}, 3) -- enfoque
|
||||
Funciona en ambos motores.
|
||||
|
||||
o obj.resize(ancho, alto [, filtro]) (extension de YMM4)
|
||||
Escala la imagen del objeto al tamano indicado. obj.w / obj.h y las
|
||||
demas dimensiones tambien se actualizan.
|
||||
ancho, alto : enteros >= 1.
|
||||
filtro : "nearest" para vecino mas cercano, o lineal si se omite.
|
||||
Ejemplo: obj.resize(obj.w * 2, obj.h * 2)
|
||||
Funciona en ambos motores. El runtime rapido deja la imagen sin
|
||||
cambios cuando el resultado supera el tamano maximo de imagen.
|
||||
|
||||
o obj.getvalue(target)
|
||||
Obtiene el valor actual de obj (igual que obj.x, obj.track0, etc.).
|
||||
target : "x","y","z","ox","oy","rx","ry","rz","zoom","aspect",
|
||||
"alpha","sx","sy","track0"~"track3","time","frame", etc.
|
||||
Devuelve: un número (0 para un target desconocido).
|
||||
|
||||
o obj.getaudio(buf, archivo [, tipo [, cantidad]])
|
||||
Obtiene datos de audio.
|
||||
buf : Tabla que recibe los datos. Los valores se guardan en
|
||||
buf[1]..buf[n]. Pase nil para recibir la tabla como el
|
||||
tercer valor de retorno.
|
||||
archivo : Ruta de un archivo de audio. También se aceptan los
|
||||
siguientes nombres especiales.
|
||||
"audiobuffer" : Lee el audio de toda la escena en edición
|
||||
(todos los elementos de la línea de tiempo
|
||||
mezclados).
|
||||
"itembuffer" : Lee el audio del elemento al que está aplicado
|
||||
este efecto (tras aplicar volumen, panorama,
|
||||
fundidos y efectos de audio). Es una extensión
|
||||
exclusiva de YMM4.
|
||||
tipo : Clase de datos a obtener, como cadena. Por defecto "pcm".
|
||||
"pcm" : PCM monoaural en escala de 16 bits (-32768 a 32767).
|
||||
"spectrum" : Volumen por banda de frecuencia (aprox. 0 a 32768).
|
||||
cantidad es el número de bandas (hasta 512, por
|
||||
defecto 32).
|
||||
"fourier" : Magnitudes de la transformada discreta de Fourier
|
||||
(aprox. 0.0 a 1.0). El rango de frecuencia es de
|
||||
1/2048 a 1/2; la cantidad por defecto es 1024.
|
||||
"xxxx.l" / "xxxx.r" : Variante del canal izquierdo / derecho de
|
||||
los tipos anteriores. Sin sufijo se promedian
|
||||
ambos canales.
|
||||
cantidad : Número de valores a obtener. Pueden devolverse menos.
|
||||
Se pueden leer hasta 1024 valores por llamada.
|
||||
Devuelve: el número de valores leídos, la frecuencia de muestreo
|
||||
[, la tabla].
|
||||
La posición de lectura es la posición actual de la línea de
|
||||
tiempo para "audiobuffer" y la posición de reproducción actual
|
||||
del objeto (obj.time) en los demás casos. "pcm" devuelve muestras
|
||||
consecutivas desde esa posición; "spectrum" / "fourier" analizan
|
||||
el intervalo que comienza allí.
|
||||
Ejemplo:
|
||||
local buf = {}
|
||||
local n = obj.getaudio(buf, "audiobuffer", "spectrum", 32)
|
||||
for i = 1, n do
|
||||
obj.draw((i - n / 2) * 8, -buf[i] / 200)
|
||||
end
|
||||
* Funciona en ambos motores. Si el audio no puede leerse, la
|
||||
cantidad es 0 y no se produce ningún error.
|
||||
* "itembuffer" devuelve una cantidad de 0 para los elementos sin
|
||||
audio (imágenes, figuras, etc.). Cuando los componentes
|
||||
internos de YMM4 no están disponibles, recurre al audio previo
|
||||
a la aplicación del volumen y demás efectos.
|
||||
|
||||
o obj.getinfo(nombre)
|
||||
Obtiene diversa información del entorno. Un nombre no admitido
|
||||
devuelve nil.
|
||||
@@ -656,7 +826,8 @@
|
||||
"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.
|
||||
El nombre "track" también se admite; una cantidad de 0 coloca 1 punto.
|
||||
El ancla seleccionada puede ajustarse numéricamente con los deslizadores X / Y / Z del grupo Anclaje.
|
||||
Ejemplo:
|
||||
num = obj.track0
|
||||
obj.setanchor("pos", num, "loop")
|
||||
@@ -863,6 +1034,17 @@
|
||||
x in <1..5> comprueba 1 <= x and x <= 5.
|
||||
<1..<5> excluye el límite superior. El lado izquierdo se evalúa una sola vez.
|
||||
|
||||
o [fast] (marcador de aceleración) * extensión de YMM4
|
||||
obj.fill / obj.convolve / obj.resize se delegan automáticamente a la
|
||||
GPU cuando la carga supera un umbral y el resultado de la GPU se
|
||||
verifica como idéntico al de la CPU. [fast] es un marcador auxiliar
|
||||
que declara la intención de forma explícita; añadirlo no cambia el
|
||||
comportamiento. El marcador puede ir en su propia línea o en la misma.
|
||||
Ejemplo: [fast]
|
||||
obj.convolve(kernel, 5)
|
||||
* Se muestra un error cuando [fast] precede a algo distinto de esas tres funciones.
|
||||
* Funciona tanto en el motor MoonSharp como en el nativo.
|
||||
|
||||
|
||||
- Ejemplos de script -
|
||||
|
||||
@@ -948,7 +1130,7 @@
|
||||
Se admiten el dibujo y composición con obj.draw / obj.drawpoly, las
|
||||
operaciones de búfer con obj.copybuffer, la generación y carga con
|
||||
obj.load("figure"/"text"/"image"/"movie"), obj.setfont, obj.effect,
|
||||
obj.getvalue, obj.getinfo y obj.setoption / obj.getoption / obj.pixeloption.
|
||||
obj.getvalue, obj.getaudio, obj.getinfo y obj.setoption / obj.getoption / obj.pixeloption.
|
||||
Consulte "Tabla obj - Funciones" para más detalles.
|
||||
|
||||
o Mapa de compatibilidad AviUtl / AviUtl2 para obj.effect
|
||||
@@ -994,12 +1176,11 @@
|
||||
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, etc.
|
||||
|
||||
|
||||
- Funciones no admitidas / Limitaciones -
|
||||
|
||||
x obj.rand1(), obj.mes(), obj.setanchor(), etc. de AviUtl2 no son compatibles.
|
||||
x obj.rand1(), obj.mes(), etc. de AviUtl2 no son compatibles.
|
||||
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.
|
||||
|
||||
@@ -62,14 +62,29 @@
|
||||
obj.setpixel(x, y, r2, g2, b2 [, a2])
|
||||
end
|
||||
end
|
||||
Bentuk berikut yang memakai getpixeldata juga menjadi kernel.
|
||||
local data = obj.getpixeldata()
|
||||
for y = 0, data.height - 1 do
|
||||
for x = 0, data.width - 1 do
|
||||
local i = (y * data.width + x) * 4
|
||||
local r = data:get(i + 1)
|
||||
data:set(i + 1, r2)
|
||||
data:set(i + 2, g2)
|
||||
data:set(i + 3, b2)
|
||||
end
|
||||
end
|
||||
obj.putpixeldata(data)
|
||||
- Badan hanya boleh memakai aritmetika, math.*, perbandingan,
|
||||
idiom ambang "cond and nilai1 or nilai2", dan variabel local.
|
||||
- Hanya boleh mereferensikan piksel yang sedang diproses
|
||||
(getpixel(x, y)) dan nilai seperti obj/scene/time.
|
||||
idiom ambang "cond and nilai1 or nilai2", penugasan bersyarat
|
||||
ke variabel local melalui if/elseif/else, dan variabel local.
|
||||
- Batas perulangan juga boleh memakai alias seperti
|
||||
local w = obj.w.
|
||||
- Hanya boleh mereferensikan piksel yang sedang diproses dan
|
||||
nilai seperti obj/scene/time.
|
||||
- Apa pun yang memakai sampling tetangga (blur, dll.), penulisan
|
||||
ke koordinat lain, getpixeldata, getobject, operasi
|
||||
tabel/string, atau pernyataan if tidak diubah menjadi kernel dan
|
||||
otomatis berjalan di mesin klasik.
|
||||
ke koordinat lain, pemanggilan setpixel atau set di dalam
|
||||
pernyataan if, getobject, atau operasi tabel/string tidak
|
||||
diubah menjadi kernel dan otomatis berjalan di mesin klasik.
|
||||
|
||||
Contoh (membuat figur putih menjadi merah):
|
||||
--!gpu
|
||||
@@ -328,10 +343,15 @@
|
||||
* Jika beberapa item berbagi tag yang sama, item yang tampil
|
||||
pada frame target dikembalikan dengan prioritas. Jika tidak
|
||||
ada yang tampil, item pertama yang cocok dikembalikan.
|
||||
* Item suara (suara sintesis, dll.) juga menjadi target. Untuk item
|
||||
suara, koordinat, skala, rotasi, dan opasitas adalah milik
|
||||
tampilan takarir (subtitle)-nya.
|
||||
* Nilai yang dikembalikan adalah koordinat, rotasi, dan skala
|
||||
milik item itu sendiri. Transformasi dari kontrol grup,
|
||||
kontrol kamera, atau efek di atasnya TIDAK disertakan.
|
||||
* Setiap nilai menggunakan sistem satuan yang sama dengan tabel obj.
|
||||
* .character / .text / .volume / .kind / .length adalah ekstensi
|
||||
khusus YMM4 yang tidak ada di AviUtl. Bekerja pada kedua mesin.
|
||||
tag : Teks yang diatur pada catatan item target
|
||||
frame : Frame absolut pada lini masa yang diambil (opsional)
|
||||
Kembali : Tabel informasi objek. Mengembalikan nil jika tidak ada
|
||||
@@ -351,6 +371,12 @@
|
||||
.rzr : Sudut rotasi sumbu Z (radian)
|
||||
.alpha : Opasitas (0.0 - 255.0, fade diterapkan)
|
||||
.layer : Nomor layer tempat ditempatkan
|
||||
.length : Panjang item (jumlah frame)
|
||||
.volume : Nilai pengaturan volume saat ini (hanya item suara; selain itu 0)
|
||||
.character : Nama karakter (hanya item suara; selain itu string kosong)
|
||||
.text : Dialog atau teks yang ditampilkan (hanya item suara dan teks;
|
||||
selain itu string kosong)
|
||||
.kind : Nama jenis item (mis. VoiceItem, TextItem, ImageItem)
|
||||
Contoh:
|
||||
local funnel = obj.getobject("funnel")
|
||||
if funnel then
|
||||
@@ -364,6 +390,11 @@
|
||||
obj.x = src.x
|
||||
obj.y = src.y
|
||||
end
|
||||
Mewarnai ulang berdasarkan nama karakter (catatan target adalah "voice"):
|
||||
local v = obj.getobject("voice")
|
||||
if v and v.character == "Marisa" then
|
||||
obj.effect("Monokrom", "kekuatan", 100, "color", 0xffee55)
|
||||
end
|
||||
|
||||
o obj.getpixel(x, y)
|
||||
Mengambil informasi piksel pada koordinat yang ditentukan.
|
||||
@@ -448,10 +479,13 @@
|
||||
|
||||
o obj.load(target, ...)
|
||||
Mengganti buffer objek dengan konten yang dihasilkan. Target "figure",
|
||||
"text", "image" (berkas gambar) dan "movie" (berkas video) didukung.
|
||||
"text", "image" (berkas gambar), "movie" (berkas video), "scene"
|
||||
(adegan proyek) dan "brush" (pola YMM4) didukung.
|
||||
Setelah dimuat, obj.w / obj.h, dll. diperbarui ke ukuran yang
|
||||
dihasilkan dan dapat dibaca oleh getpixel tepat setelah pemuatan.
|
||||
Berfungsi pada mesin MoonSharp maupun mesin cepat (LuaJIT).
|
||||
* "scene" dan "brush" adalah ekstensi khusus YMM4 yang tidak ada
|
||||
di AviUtl.
|
||||
|
||||
obj.load("figure", name, color, size [, line [, aspect]])
|
||||
Menghasilkan bentuk dan mengganti buffer (dipusatkan).
|
||||
@@ -483,6 +517,45 @@
|
||||
(MP4 / MOV / MKV / WebM / AVI / FLV / ASF) yang dimuat.
|
||||
Contoh: obj.load("movie", "C:\\mov\\clip.mp4", obj.time)
|
||||
|
||||
obj.load("scene", namaAdegan [, waktu])
|
||||
Menggambar adegan lain dalam proyek dan mengganti buffer.
|
||||
namaAdegan : Nama yang ditampilkan pada daftar adegan.
|
||||
waktu : Detik. Default obj.time bila dihilangkan.
|
||||
* Adegan tempat objek saat ini berada tidak dapat dipilih,
|
||||
dan memuat adegan dari dalam penggambaran adegan juga
|
||||
ditolak.
|
||||
* Frame yang memuat adegan melewati cache render dan
|
||||
dijalankan ulang setiap kali.
|
||||
Contoh: obj.load("scene", "Sub Adegan", obj.time)
|
||||
|
||||
obj.load("brush", namaPola [, lebar [, tinggi]])
|
||||
Menghasilkan gambar yang diisi pola (kuas) YMM4 dan
|
||||
mengganti buffer. Pola yang ditambahkan oleh plugin kuas
|
||||
juga dapat digunakan.
|
||||
namaPola : Nama yang ditampilkan pada daftar pola.
|
||||
lebar, tinggi : Ukuran keluaran dalam piksel. Default
|
||||
obj.w / obj.h saat ini bila dihilangkan.
|
||||
* Pola digambar dengan parameter default.
|
||||
Contoh: obj.load("brush", "Garis-garis", 400, 300)
|
||||
|
||||
o obj.brush(namaPola [, lebar, tinggi] [, namaParam, nilai, ...])
|
||||
Menggambar pola (kuas) YMM4 dengan parameter yang ditentukan dan
|
||||
mengganti buffer. Penggambarannya sama dengan obj.load("brush"),
|
||||
dan parameter pola dapat diubah dengan pasangan nama dan nilai
|
||||
yang sama seperti obj.effect.
|
||||
namaPola : Nama yang ditampilkan pada daftar pola.
|
||||
lebar, tinggi : Ukuran keluaran dalam piksel. Default
|
||||
obj.w / obj.h saat ini. Hanya ditafsirkan sebagai
|
||||
ukuran bila keduanya diberikan sebagai angka.
|
||||
namaParam : Nama tampilan pengaturan pola, atau nama properti
|
||||
internalnya.
|
||||
nilai : Angka, boolean atau string. Warna adalah angka
|
||||
0xRRGGBB.
|
||||
* Parameter yang tidak ditentukan digambar dengan nilai default.
|
||||
Panggilan tanpa pasangan sama dengan obj.load("brush").
|
||||
* Ini adalah ekstensi khusus YMM4 yang tidak ada di AviUtl.
|
||||
Contoh: obj.brush("Garis-garis", "Angle", 45, "Color1", 0xff3366)
|
||||
|
||||
o obj.setfont(font [, size [, style [, color]]])
|
||||
Mengatur font yang digunakan oleh obj.load("text").
|
||||
style : Flag bit. 1=tebal, 2=miring, 3=tebal+miring.
|
||||
@@ -564,12 +637,103 @@
|
||||
area transparan seukuran adegan.
|
||||
* Panggilan dilewati pada lingkungan tanpa GPU yang dapat digunakan.
|
||||
|
||||
o obj.fill(r, g, b [, a [, x, y, w, h]]) (ekstensi YMM4)
|
||||
Mengisi gambar objek dengan warna, diberikan sebagai RGBA lurus dalam
|
||||
0-255 (model warna sama dengan obj.setpixel).
|
||||
r, g, b : Komponen warna (0-255).
|
||||
a : Opasitas (0-255). Default 255.
|
||||
x, y, w, h: Persegi panjang yang diisi. Default seluruh gambar; di
|
||||
luar jangkauan dipangkas.
|
||||
Contoh: obj.fill(0, 0, 0, 0) -- bersihkan jadi transparan
|
||||
obj.fill(255, 0, 0, 255, 10, 10, 20, 20)
|
||||
Berjalan di kedua mesin.
|
||||
|
||||
o obj.getpixelregion(x, y, w, h) (ekstensi YMM4)
|
||||
Membaca wilayah piksel persegi panjang ke dalam larik RGBA lurus.
|
||||
Susunannya r, g, b, a per piksel dan berbasis 1 (indeks
|
||||
(baris*w+kolom)*4+1..+4). Piksel di luar gambar bernilai 0,0,0,0.
|
||||
Mengembalikan: larik sepanjang w*h*4.
|
||||
Contoh: local t = obj.getpixelregion(0, 0, obj.w, obj.h)
|
||||
|
||||
o obj.putpixelregion(x, y, w, h, data) (ekstensi YMM4)
|
||||
Menulis larik dengan susunan sama seperti obj.getpixelregion kembali
|
||||
ke wilayah persegi panjang. Piksel di luar gambar tidak ditulis.
|
||||
data : larik RGBA lurus sepanjang w*h*4 (berbasis 1).
|
||||
Contoh: obj.putpixelregion(0, 0, obj.w, obj.h, t)
|
||||
|
||||
o obj.convolve(kernel, ukuran [, pembagi [, offset]]) (ekstensi YMM4)
|
||||
Menerapkan konvolusi ukuran x ukuran ke gambar objek. Berguna untuk
|
||||
blur, penajaman, deteksi tepi, dan sebagainya.
|
||||
kernel : ukuran*ukuran koefisien, urut baris dan berbasis 1.
|
||||
ukuran : bilangan ganjil (3, 5, 7 ...). Genap atau di bawah 1 diabaikan.
|
||||
pembagi : membagi jumlah tiap piksel. Default jumlah kernel (1 bila
|
||||
jumlahnya 0).
|
||||
offset : ditambahkan ke tiap komponen setelah pembagian. Default 0.
|
||||
Piksel tepi diperluas dengan piksel terdekat. Berlaku untuk r, g, b, a.
|
||||
Contoh: obj.convolve({1,1,1, 1,1,1, 1,1,1}, 3) -- blur rata-rata
|
||||
obj.convolve({0,-1,0, -1,5,-1, 0,-1,0}, 3) -- penajaman
|
||||
Berjalan di kedua mesin.
|
||||
|
||||
o obj.resize(lebar, tinggi [, filter]) (ekstensi YMM4)
|
||||
Menskala gambar objek ke ukuran yang diberikan. obj.w / obj.h dan
|
||||
dimensi lainnya ikut diperbarui.
|
||||
lebar, tinggi : bilangan bulat >= 1.
|
||||
filter : "nearest" untuk tetangga terdekat, atau linear bila
|
||||
dihilangkan.
|
||||
Contoh: obj.resize(obj.w * 2, obj.h * 2)
|
||||
Berjalan di kedua mesin. Runtime cepat membiarkan gambar tanpa
|
||||
perubahan bila hasilnya melebihi ukuran gambar maksimum.
|
||||
|
||||
o obj.getvalue(target)
|
||||
Mengambil nilai saat ini dari obj (sama dengan obj.x, obj.track0, dll.).
|
||||
target : "x","y","z","ox","oy","rx","ry","rz","zoom","aspect",
|
||||
"alpha","sx","sy","track0"~"track3","time","frame", dll.
|
||||
Mengembalikan: sebuah angka (0 untuk target yang tidak dikenal).
|
||||
|
||||
o obj.getaudio(buf, file [, tipe [, jumlah]])
|
||||
Mengambil data audio.
|
||||
buf : Tabel yang menerima data. Nilai disimpan di buf[1]..buf[n].
|
||||
Berikan nil untuk menerima tabel sebagai nilai kembali
|
||||
ketiga.
|
||||
file : Jalur berkas audio. Nama khusus berikut juga diterima.
|
||||
"audiobuffer" : Membaca audio seluruh scene yang sedang
|
||||
disunting (semua item di lini masa dicampur
|
||||
menjadi satu).
|
||||
"itembuffer" : Membaca audio dari item tempat efek ini
|
||||
terpasang (setelah volume, pan, fade, dan efek
|
||||
audio diterapkan). Ini ekstensi khusus YMM4.
|
||||
tipe : Jenis data yang diambil, sebagai string. Bawaan "pcm".
|
||||
"pcm" : PCM mono pada skala 16-bit (-32768 sampai 32767).
|
||||
"spectrum" : Volume per pita frekuensi (sekitar 0 sampai 32768).
|
||||
jumlah adalah banyaknya pita (maksimal 512,
|
||||
bawaan 32).
|
||||
"fourier" : Magnitudo transformasi Fourier diskrit (sekitar
|
||||
0.0 sampai 1.0). Rentang frekuensinya 1/2048
|
||||
sampai 1/2; jumlah bawaannya 1024.
|
||||
"xxxx.l" / "xxxx.r" : Varian kanal kiri / kanan dari jenis di
|
||||
atas. Tanpa akhiran, kedua kanal dirata-ratakan.
|
||||
jumlah : Banyaknya nilai yang diambil. Hasilnya bisa lebih
|
||||
sedikit. Maksimal 1024 nilai per panggilan.
|
||||
Mengembalikan: banyaknya nilai yang terbaca, laju sampel
|
||||
[, tabel].
|
||||
Posisi baca adalah posisi lini masa saat ini untuk
|
||||
"audiobuffer", dan posisi pemutaran objek saat ini (obj.time)
|
||||
untuk lainnya. "pcm" mengembalikan sampel berurutan dari posisi
|
||||
itu; "spectrum" / "fourier" menganalisis interval yang dimulai
|
||||
dari sana.
|
||||
Contoh:
|
||||
local buf = {}
|
||||
local n = obj.getaudio(buf, "audiobuffer", "spectrum", 32)
|
||||
for i = 1, n do
|
||||
obj.draw((i - n / 2) * 8, -buf[i] / 200)
|
||||
end
|
||||
* Bekerja di kedua mesin. Jika audio tidak dapat dibaca,
|
||||
jumlahnya 0 dan tidak terjadi kesalahan.
|
||||
* "itembuffer" mengembalikan jumlah 0 untuk item tanpa audio
|
||||
(gambar, bentuk, dsb.). Jika komponen internal YMM4 tidak
|
||||
tersedia, digunakan audio sebelum volume dan efek lainnya
|
||||
diterapkan.
|
||||
|
||||
o obj.getinfo(name)
|
||||
Mengambil berbagai informasi lingkungan. Nama yang tidak didukung
|
||||
mengembalikan nil.
|
||||
@@ -653,7 +817,8 @@
|
||||
"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.
|
||||
Nama "track" juga didukung; jumlah 0 menempatkan 1 titik.
|
||||
Jangkar yang dipilih dapat disesuaikan secara numerik melalui slider X / Y / Z di grup Jangkar.
|
||||
Contoh:
|
||||
num = obj.track0
|
||||
obj.setanchor("pos", num, "loop")
|
||||
@@ -859,6 +1024,17 @@
|
||||
x in <1..5> menguji 1 <= x and x <= 5.
|
||||
<1..<5> tidak menyertakan batas atas. Sisi kiri dievaluasi sekali.
|
||||
|
||||
o [fast] (penanda akselerasi) * ekstensi YMM4
|
||||
obj.fill / obj.convolve / obj.resize didelegasikan ke GPU secara
|
||||
otomatis ketika beban kerja melebihi ambang batas dan hasil GPU
|
||||
terverifikasi sama dengan CPU. [fast] adalah penanda tambahan yang
|
||||
menyatakan niat secara eksplisit; menambahkannya tidak mengubah
|
||||
perilaku. Penanda boleh di baris tersendiri atau di baris yang sama.
|
||||
Contoh: [fast]
|
||||
obj.convolve(kernel, 5)
|
||||
* Kesalahan ditampilkan jika [fast] mendahului selain ketiga fungsi tersebut.
|
||||
* Berfungsi pada mesin MoonSharp maupun native.
|
||||
|
||||
|
||||
- Contoh Skrip -
|
||||
|
||||
@@ -943,7 +1119,7 @@
|
||||
Penggambaran dan komposisi dengan obj.draw / obj.drawpoly, operasi
|
||||
buffer dengan obj.copybuffer, pembuatan dan pemuatan dengan
|
||||
obj.load("figure"/"text"/"image"/"movie"), obj.setfont, obj.effect,
|
||||
obj.getvalue, obj.getinfo, serta obj.setoption / obj.getoption / obj.pixeloption
|
||||
obj.getvalue, obj.getaudio, obj.getinfo, serta obj.setoption / obj.getoption / obj.pixeloption
|
||||
didukung. Lihat "Tabel obj - Fungsi" untuk detailnya.
|
||||
|
||||
o Peta kompatibilitas AviUtl / AviUtl2 untuk obj.effect
|
||||
@@ -987,12 +1163,11 @@
|
||||
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, dll.
|
||||
|
||||
|
||||
- Fitur yang Tidak Didukung / Batasan -
|
||||
|
||||
x obj.rand1(), obj.mes(), obj.setanchor(), dll. dari AviUtl2 tidak didukung.
|
||||
x obj.rand1(), obj.mes(), dll. dari AviUtl2 tidak didukung.
|
||||
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.
|
||||
|
||||
@@ -57,13 +57,28 @@
|
||||
obj.setpixel(x, y, r2, g2, b2 [, a2])
|
||||
end
|
||||
end
|
||||
getpixeldata を使う次の形も同様にカーネル化されます。
|
||||
local data = obj.getpixeldata()
|
||||
for y = 0, data.height - 1 do
|
||||
for x = 0, data.width - 1 do
|
||||
local i = (y * data.width + x) * 4
|
||||
local r = data:get(i + 1)
|
||||
data:set(i + 1, r2)
|
||||
data:set(i + 2, g2)
|
||||
data:set(i + 3, b2)
|
||||
end
|
||||
end
|
||||
obj.putpixeldata(data)
|
||||
・本体で使えるのは四則演算・math.*・比較・しきい値の
|
||||
「条件 and 値1 or 値2」・local 変数のみです。
|
||||
・参照できるのは処理中の自ピクセル(getpixel(x, y))と
|
||||
obj/scene/time 等の値だけです。
|
||||
・近傍参照(ぼかし等)、別座標への書き込み、getpixeldata、
|
||||
getobject、テーブル/文字列操作、if 文などを含む場合は
|
||||
カーネル化されず、自動的に従来エンジンで実行されます。
|
||||
「条件 and 値1 or 値2」・if/elseif/else による local 変数への
|
||||
条件代入・local 変数のみです。
|
||||
・ループの上限には local w = obj.w のような別名も使えます。
|
||||
・参照できるのは処理中の自ピクセルと obj/scene/time 等の
|
||||
値だけです。
|
||||
・近傍参照(ぼかし等)、別座標への書き込み、if 文の中での
|
||||
setpixel や set の呼び出し、getobject、テーブル/文字列操作
|
||||
などを含む場合はカーネル化されず、自動的に従来エンジンで
|
||||
実行されます。
|
||||
|
||||
例(白い図形が赤くなる):
|
||||
--!gpu
|
||||
@@ -146,8 +161,8 @@
|
||||
|
||||
- scene テーブル -
|
||||
|
||||
scene.width : シーン(プロジェクト)の横解像度(ピクセル) [ReadOnly]
|
||||
scene.height : シーン(プロジェクト)の縦解像度(ピクセル) [ReadOnly]
|
||||
scene.width : シーンの横解像度(ピクセル) [ReadOnly]
|
||||
scene.height : シーンの縦解像度(ピクセル) [ReadOnly]
|
||||
scene.cx : シーンの横解像度の半分 (= scene.width / 2) [ReadOnly]
|
||||
scene.cy : シーンの縦解像度の半分 (= scene.height / 2) [ReadOnly]
|
||||
|
||||
@@ -319,9 +334,13 @@
|
||||
※ 同じタグを持つアイテムが複数ある場合、対象フレームで表示中の
|
||||
アイテムを優先して返します。表示中のものが無い場合は最初に
|
||||
一致したアイテムを返します。
|
||||
※ 音声アイテム(合成音声等)も対象になります。音声アイテムの
|
||||
座標・拡大率・回転・不透明度は字幕の表示情報を返します。
|
||||
※ 取得できる値はアイテム自身の座標・回転・拡大率です。
|
||||
グループ制御・カメラ制御・上位エフェクトによる変形は含まれません。
|
||||
※ 各値は obj テーブルと同一の単位系です。
|
||||
※ .character / .text / .volume / .kind / .length は AviUtl に存在しない
|
||||
YMM4 向けの独自拡張です。両エンジンで動作します。
|
||||
tag : 対象アイテムの備考に設定した文字列
|
||||
frame : 取得するタイムライン上の絶対フレーム (省略可)
|
||||
戻り値 : オブジェクト情報テーブル。一致するアイテムが存在しない場合は
|
||||
@@ -341,6 +360,12 @@
|
||||
.rzr : Z 軸回転角度 (ラジアン)
|
||||
.alpha : 不透明度 (0.0 ~ 255.0, フェード反映済み)
|
||||
.layer : 配置レイヤー番号
|
||||
.length : アイテムの長さ (フレーム数)
|
||||
.volume : 音量設定の現在値 (音声アイテムのみ。他は 0)
|
||||
.character : キャラクター名 (音声アイテムのみ。他は空文字列)
|
||||
.text : セリフまたは表示テキスト (音声・テキストアイテムのみ。
|
||||
他は空文字列)
|
||||
.kind : アイテムの種別名 (例:VoiceItem, TextItem, ImageItem)
|
||||
例:
|
||||
local funnel = obj.getobject("funnel")
|
||||
if funnel then
|
||||
@@ -354,6 +379,11 @@
|
||||
obj.x = src.x
|
||||
obj.y = src.y
|
||||
end
|
||||
キャラクター名で色を変える例 (対象の備考が "voice" の場合):
|
||||
local v = obj.getobject("voice")
|
||||
if v and v.character == "魔理沙" then
|
||||
obj.effect("単色化", "強さ", 100, "color", 0xffee55)
|
||||
end
|
||||
|
||||
○obj.getpixel(x, y)
|
||||
指定座標のピクセル情報を取得します。
|
||||
@@ -438,9 +468,12 @@
|
||||
○obj.load(対象, ...)
|
||||
オブジェクトのバッファを生成した内容に置き換えます。
|
||||
対象は "figure"(図形) / "text"(テキスト) / "image"(画像ファイル) /
|
||||
"movie"(動画ファイル) に対応します。生成後 obj.w / obj.h 等は生成
|
||||
サイズへ更新され、load 直後の getpixel でも参照できます。
|
||||
"movie"(動画ファイル) / "scene"(シーン) / "brush"(模様) に対応
|
||||
します。生成後 obj.w / obj.h 等は生成サイズへ更新され、load 直後
|
||||
の getpixel でも参照できます。
|
||||
従来エンジン・高速エンジンの両方で動作します。
|
||||
※ "scene" と "brush" は AviUtl に存在しない YMM4 向けの独自拡張
|
||||
です。
|
||||
|
||||
obj.load("figure", 名前, 色, サイズ [, ライン [, アスペクト]])
|
||||
図形を生成してバッファを置き換えます(中心に配置)。
|
||||
@@ -473,6 +506,43 @@
|
||||
読み込みます。
|
||||
例:obj.load("movie", "C:\\mov\\clip.mp4", obj.time)
|
||||
|
||||
obj.load("scene", シーン名 [, 時間])
|
||||
プロジェクト内の別シーンを描画してバッファを置き換えます。
|
||||
シーン名 : シーン一覧に表示される名前。
|
||||
時間 : 秒。省略時は obj.time。
|
||||
※ 現在のオブジェクトが乗っているシーン自身は指定でき
|
||||
ません。シーン描画の中からさらにシーンを読み込むこと
|
||||
もできません。
|
||||
※ シーンを読み込んだフレームは描画キャッシュを使わず
|
||||
毎回再実行されます。
|
||||
例:obj.load("scene", "サブシーン", obj.time)
|
||||
|
||||
obj.load("brush", 模様名 [, 幅 [, 高さ]])
|
||||
YMM4 の模様(ブラシ)で塗り潰した画像を生成してバッファを
|
||||
置き換えます。模様プラグインで追加した模様も使えます。
|
||||
模様名 : 模様一覧に表示される名前(例:縞模様、市松模様)。
|
||||
幅、高さ : 生成サイズ(ピクセル)。省略時は現在の
|
||||
obj.w / obj.h。
|
||||
※ 模様のパラメータは既定値で描画されます。
|
||||
例:obj.load("brush", "縞模様", 400, 300)
|
||||
|
||||
○obj.brush(模様名 [, 幅, 高さ] [, パラメータ名, 値, ...])
|
||||
YMM4 の模様(ブラシ)をパラメータ指定付きで描画してバッファを
|
||||
置き換えます。描画は obj.load("brush") と同じで、加えて
|
||||
obj.effect と同じ「名前と値の組」で模様のパラメータを変更
|
||||
できます。
|
||||
模様名 : 模様一覧に表示される名前。
|
||||
幅、高さ : 生成サイズ(ピクセル)。省略時は現在の
|
||||
obj.w / obj.h。両方を数値で並べたときだけ
|
||||
サイズとして解釈します。
|
||||
パラメータ名 : 模様の設定項目の表示名、または内部の
|
||||
プロパティ名。
|
||||
値 : 数値、真偽値、文字列。色は 0xRRGGBB の数値。
|
||||
※ 指定しなかったパラメータは既定値で描画されます。組を
|
||||
すべて省略した呼び出しは obj.load("brush") と同じです。
|
||||
※ AviUtl に存在しない YMM4 向けの独自拡張です。
|
||||
例:obj.brush("縞模様", "Angle", 45, "Color1", 0xff3366)
|
||||
|
||||
○obj.setfont(フォント名 [, サイズ [, スタイル [, 色]]])
|
||||
obj.load("text") で使用するフォントを設定します。
|
||||
スタイル : ビット和。1=太字, 2=斜体, 3=太字+斜体。
|
||||
@@ -546,12 +616,96 @@
|
||||
シーンサイズ領域へオブジェクトを合成した仮想の画像です。
|
||||
※ GPUが使用できない環境では呼び出しはスキップされます。
|
||||
|
||||
○obj.fill(r, g, b [, a [, x, y, w, h]]) ※YMM4独自拡張
|
||||
オブジェクト画像を指定色で塗りつぶします。色は 0~255 のストレート
|
||||
RGBA で指定します(obj.setpixel と同じ表色)。
|
||||
r, g, b : 色成分(0~255)。
|
||||
a : 不透明度(0~255)。省略時は 255。
|
||||
x, y, w, h : 塗りつぶす矩形。省略時は画像全体。範囲外は切り詰めます。
|
||||
例:obj.fill(0, 0, 0, 0) -- 全体を透明で消去
|
||||
obj.fill(255, 0, 0, 255, 10, 10, 20, 20)
|
||||
両エンジンで動きます。
|
||||
|
||||
○obj.getpixelregion(x, y, w, h) ※YMM4独自拡張
|
||||
矩形領域の画素をストレート RGBA の配列で取得します。並びは画素ごと
|
||||
に r, g, b, a の順で 1 始まりです(索引 (行*w+列)*4+1~+4)。範囲外の
|
||||
画素は 0,0,0,0 になります。
|
||||
戻り値 : 長さ w*h*4 の配列。
|
||||
例:local t = obj.getpixelregion(0, 0, obj.w, obj.h)
|
||||
|
||||
○obj.putpixelregion(x, y, w, h, データ) ※YMM4独自拡張
|
||||
obj.getpixelregion と同じ並びの配列を矩形領域へ書き戻します。画像の
|
||||
範囲外へはみ出した画素は書き込みません。
|
||||
データ : 長さ w*h*4 のストレート RGBA 配列(1 始まり)。
|
||||
例:obj.putpixelregion(0, 0, obj.w, obj.h, t)
|
||||
|
||||
○obj.convolve(カーネル, サイズ [, 除数 [, オフセット]]) ※YMM4独自拡張
|
||||
オブジェクト画像へ サイズ×サイズ の畳み込みを適用します。ぼかし、
|
||||
シャープ、輪郭抽出などに使えます。
|
||||
カーネル : サイズ*サイズ 個の係数配列(行優先, 1 始まり)。
|
||||
サイズ : 奇数(3, 5, 7 …)。偶数や 1 未満は無視します。
|
||||
除数 : 各画素の合計をこの値で割ります。省略時はカーネルの
|
||||
合計(合計が 0 のときは 1)。
|
||||
オフセット : 除算後に各成分へ加算します。省略時は 0。
|
||||
端の画素は最も近い画素で補います。r, g, b, a すべてに適用します。
|
||||
例:obj.convolve({1,1,1, 1,1,1, 1,1,1}, 3) -- 平均ぼかし
|
||||
obj.convolve({0,-1,0, -1,5,-1, 0,-1,0}, 3) -- シャープ
|
||||
両エンジンで動きます。
|
||||
|
||||
○obj.resize(幅, 高さ [, 補間]) ※YMM4独自拡張
|
||||
オブジェクト画像を指定サイズへ拡大縮小します。obj.w / obj.h などの
|
||||
寸法も更新されます。
|
||||
幅, 高さ : 1 以上の整数。
|
||||
補間 : "nearest"(最近傍)または省略で線形補間。
|
||||
例:obj.resize(obj.w * 2, obj.h * 2)
|
||||
両エンジンで動きます。高速ランタイムでは結果が最大画像サイズを
|
||||
超える場合は変更しません。
|
||||
|
||||
○obj.getvalue(対象)
|
||||
obj の現在値を取得します(obj.x や obj.track0 等と同値)。
|
||||
対象 : "x","y","z","ox","oy","rx","ry","rz","zoom","aspect",
|
||||
"alpha","sx","sy","track0"~"track3","time","frame" 等。
|
||||
戻り値 : 数値(未知の対象は 0)。
|
||||
|
||||
○obj.getaudio(バッファ, ファイル名 [, 種別 [, 個数]])
|
||||
音声データを取得します。
|
||||
バッファ : 取得データを格納するテーブルを指定します。データは
|
||||
バッファ[1]~バッファ[n] へ格納されます。nil を指定
|
||||
すると 3 番目の戻り値としてテーブルを返します。
|
||||
ファイル名 : 音声ファイルのパスを指定します。次の特別な名前も
|
||||
指定できます。
|
||||
"audiobuffer" : 編集中のシーン全体の音声(タイムライン上の
|
||||
全アイテムを合成した音声)を取得します。
|
||||
"itembuffer" : このエフェクトを付けたアイテム自身の音声
|
||||
(音量・パン・フェード・音声エフェクト適用後)
|
||||
を取得します。YMM4独自の拡張です。
|
||||
種別 : 取得するデータの種類を文字列で指定します。省略時は "pcm"。
|
||||
"pcm" : 16bit スケール基準(-32768~32767)のモノラル PCM。
|
||||
"spectrum" : 周波数帯ごとの音量データ(0~32768 目安)。個数は
|
||||
分割する帯域の数です(最大 512、省略時 32)。
|
||||
"fourier" : 離散フーリエ変換の振幅データ(0.0~1.0 目安)。
|
||||
周波数範囲は 1/2048~1/2 で、省略時は 1024 個です。
|
||||
"xxxx.l" / "xxxx.r" : 上記種別の左 / 右チャンネル版。無指定の
|
||||
ときは左右の平均です。
|
||||
個数 : 取得するデータ数を指定します。取得できた数が指定より
|
||||
少ないことがあります。1 回で取得できるのは最大 1024 個です。
|
||||
戻り値 : 取得したデータ数, サンプリングレート[, テーブル]。
|
||||
読み取り位置は、"audiobuffer" はタイムラインの現在の再生位置、
|
||||
それ以外はオブジェクトの現在の再生位置(obj.time)です。pcm は
|
||||
現在位置から連続したサンプルを返し、spectrum / fourier は現在位置
|
||||
からの区間を解析して返します。
|
||||
例:
|
||||
local buf = {}
|
||||
local n = obj.getaudio(buf, "audiobuffer", "spectrum", 32)
|
||||
for i = 1, n do
|
||||
obj.draw((i - n / 2) * 8, -buf[i] / 200)
|
||||
end
|
||||
※ 両エンジンで動きます。取得できない場合はデータ数 0 を返し、
|
||||
エラーにはなりません。
|
||||
※ "itembuffer" は音声を持たないアイテム(画像や図形等)では
|
||||
データ数 0 になります。YMM4の内部実装を利用できない場合は
|
||||
音量等を適用する前の音声になります。
|
||||
|
||||
○obj.getinfo(名前)
|
||||
各種の環境情報を取得します。未対応の名前は nil を返します。
|
||||
"script_path" : プラグインの設置フォルダのパスを返します。末尾に
|
||||
@@ -624,7 +778,8 @@
|
||||
"arm" : オブジェクトの中心から各アンカーポイントへ順に線で結びます。
|
||||
"xyz" : アンカーポイントを 3D 座標で扱います。既定は 2D です。
|
||||
戻り値は設置したアンカーポイントの数です。両エンジンで動きます。
|
||||
名前に "track" を指定するトラックバー連携は現在未対応で、0 を返します。
|
||||
名前に "track" を指定した場合も対応し、個数 0 は 1 個として設置します。
|
||||
選択中のアンカーは「アンカー」グループの X / Y / Z スライダーで数値調整できます。
|
||||
例:
|
||||
num = obj.track0
|
||||
obj.setanchor("pos", num, "loop")
|
||||
@@ -826,6 +981,17 @@
|
||||
x in <1..5> は 1 <= x and x <= 5 を判定します。
|
||||
<1..<5> は上限を含みません。左辺は 1 度だけ評価します。
|
||||
|
||||
○[fast](高速化マーカー) ※YMM4独自拡張
|
||||
obj.fill / obj.convolve / obj.resize は、処理量がしきい値以上で
|
||||
GPU の結果が CPU と一致すると確認できたとき、自動で GPU へ委譲
|
||||
します。[fast] は委譲の意図を明示する補助マーカーで、置いても
|
||||
動作は変わりません。マーカーは単独の行に置いても、同じ行に
|
||||
続けて書いても構いません。
|
||||
例:[fast]
|
||||
obj.convolve(kernel, 5)
|
||||
※ [fast] を付けた対象が上記 3 関数以外のときはエラーを表示します。
|
||||
※ 従来エンジンと高速ランタイムの両方で動作します。
|
||||
|
||||
|
||||
- スクリプト例 -
|
||||
|
||||
@@ -874,7 +1040,8 @@
|
||||
- AviUtl スクリプトの部分互換 -
|
||||
|
||||
AviUtl のアニメーション効果スクリプト(*.anm 系)のうち、座標・拡縮・回転・
|
||||
不透明度の変形と乱数を用いる範囲を、追加の記述変更なしで実行できる互換層です。
|
||||
不透明度の変形、乱数、図形描画、描画合成などを、追加の記述変更なしで
|
||||
実行できる互換層です。
|
||||
スクリプトに AviUtl 固有の記法が含まれない場合、この互換層は一切介入しません
|
||||
(従来のスクリプトの挙動は変わりません)。
|
||||
|
||||
@@ -905,8 +1072,10 @@
|
||||
|
||||
○描画・合成・読み込み
|
||||
obj.draw / obj.drawpoly による描画合成、obj.copybuffer による
|
||||
バッファ操作、obj.load("figure"/"text"/"image"/"movie") による生成・
|
||||
読み込み、obj.setfont、obj.effect、obj.getvalue、obj.getinfo、obj.setoption /
|
||||
バッファ操作、obj.fill / obj.getpixelregion / obj.putpixelregion /
|
||||
obj.convolve / obj.resize による画像加工、obj.load("figure"/"text"/
|
||||
"image"/"movie") による生成・読み込み、obj.setfont、obj.effect、
|
||||
obj.getvalue、obj.getaudio、obj.getinfo、obj.setoption /
|
||||
obj.getoption / obj.pixeloption に対応します。詳細は「obj テーブル -
|
||||
関数」を参照してください。
|
||||
|
||||
@@ -949,12 +1118,11 @@
|
||||
これらを呼び出すスクリプトは意図どおりには動作しません。
|
||||
×require によるモジュール読み込み、io / dofile などの任意ファイル
|
||||
アクセス(obj.load の画像 / 動画はヘッダー検証付きで対応)。
|
||||
×obj.setanchor 等。
|
||||
|
||||
|
||||
- 非対応・制限事項 -
|
||||
|
||||
×AviUtl2 の obj.rand1(), obj.mes(), obj.setanchor() 等には対応していません。
|
||||
×AviUtl2 の obj.rand1(), obj.mes() 等には対応していません。
|
||||
×スクリプトからの任意ファイルアクセス(require, dofile, io 等)には対応して
|
||||
いません。obj.load("image"/"movie") のみ、先頭ヘッダー検証で真正なメディアと
|
||||
確認できたファイルを読み込みます。
|
||||
|
||||
@@ -57,13 +57,28 @@
|
||||
obj.setpixel(x, y, r2, g2, b2 [, a2])
|
||||
end
|
||||
end
|
||||
getpixeldata를 사용하는 다음 형태도 마찬가지로 커널화됩니다.
|
||||
local data = obj.getpixeldata()
|
||||
for y = 0, data.height - 1 do
|
||||
for x = 0, data.width - 1 do
|
||||
local i = (y * data.width + x) * 4
|
||||
local r = data:get(i + 1)
|
||||
data:set(i + 1, r2)
|
||||
data:set(i + 2, g2)
|
||||
data:set(i + 3, b2)
|
||||
end
|
||||
end
|
||||
obj.putpixeldata(data)
|
||||
· 본문에서 사용할 수 있는 것은 사칙연산・math.*・비교・임계값
|
||||
「조건 and 값1 or 값2」・local 변수뿐입니다.
|
||||
· 참조할 수 있는 것은 처리 중인 자기 픽셀(getpixel(x, y))과
|
||||
obj/scene/time 등의 값뿐입니다.
|
||||
· 이웃 참조(블러 등), 다른 좌표로의 쓰기, getpixeldata,
|
||||
getobject, 테이블/문자열 조작, if 문 등을 포함하는 경우에는
|
||||
커널화되지 않고 자동으로 기존 엔진에서 실행됩니다.
|
||||
「조건 and 값1 or 값2」・if/elseif/else에 의한 local 변수에
|
||||
대한 조건 대입・local 변수뿐입니다.
|
||||
· 루프의 상한에는 local w = obj.w 같은 별칭도 사용할 수 있습니다.
|
||||
· 참조할 수 있는 것은 처리 중인 자기 픽셀과 obj/scene/time
|
||||
등의 값뿐입니다.
|
||||
· 이웃 참조(블러 등), 다른 좌표로의 쓰기, if 문 안에서의
|
||||
setpixel이나 set 호출, getobject, 테이블/문자열 조작 등을
|
||||
포함하는 경우에는 커널화되지 않고 자동으로 기존 엔진에서
|
||||
실행됩니다.
|
||||
|
||||
예(흰색 도형이 빨갛게 됨):
|
||||
--!gpu
|
||||
@@ -316,9 +331,13 @@
|
||||
※ 같은 태그를 가진 아이템이 여러 개인 경우, 대상 프레임에서
|
||||
표시 중인 아이템을 우선하여 반환합니다. 표시 중인 것이 없으면
|
||||
처음으로 일치한 아이템을 반환합니다.
|
||||
※ 음성 아이템(합성 음성 등)도 대상이 됩니다. 음성 아이템의
|
||||
좌표·확대율·회전·불투명도는 자막 표시 정보를 반환합니다.
|
||||
※ 취득되는 값은 아이템 자신의 좌표·회전·확대율입니다.
|
||||
그룹 제어·카메라 제어·상위 이펙트에 의한 변형은 포함되지 않습니다.
|
||||
※ 각 값은 obj 테이블과 동일한 단위 체계입니다.
|
||||
※ .character / .text / .volume / .kind / .length 은 AviUtl 에 없는
|
||||
YMM4 전용 확장입니다. 두 엔진 모두에서 동작합니다.
|
||||
tag : 대상 아이템의 비고에 설정한 문자열
|
||||
frame : 취득할 타임라인의 절대 프레임 (생략 가능)
|
||||
반환값 : 오브젝트 정보 테이블. 일치하는 아이템이 없으면 nil을 반환합니다.
|
||||
@@ -337,6 +356,11 @@
|
||||
.rzr : Z축 회전 각도 (라디안)
|
||||
.alpha : 불투명도 (0.0 ~ 255.0, 페이드 반영됨)
|
||||
.layer : 배치 레이어 번호
|
||||
.length : 아이템 길이 (프레임 수)
|
||||
.volume : 음량 설정의 현재 값 (음성 아이템만. 그 외는 0)
|
||||
.character : 캐릭터 이름 (음성 아이템만. 그 외는 빈 문자열)
|
||||
.text : 대사 또는 표시 텍스트 (음성·텍스트 아이템만. 그 외는 빈 문자열)
|
||||
.kind : 아이템 종류 이름 (예: VoiceItem, TextItem, ImageItem)
|
||||
예:
|
||||
local funnel = obj.getobject("funnel")
|
||||
if funnel then
|
||||
@@ -350,6 +374,11 @@
|
||||
obj.x = src.x
|
||||
obj.y = src.y
|
||||
end
|
||||
캐릭터 이름으로 색을 바꾸는 예 (대상의 비고가 "voice"인 경우):
|
||||
local v = obj.getobject("voice")
|
||||
if v and v.character == "마리사" then
|
||||
obj.effect("단색화", "강도", 100, "color", 0xffee55)
|
||||
end
|
||||
|
||||
○ obj.getpixel(x, y)
|
||||
지정 좌표의 픽셀 정보를 취득합니다.
|
||||
@@ -433,10 +462,13 @@
|
||||
|
||||
○ obj.load(대상, ...)
|
||||
오브젝트 버퍼를 생성한 내용으로 교체합니다. "figure"(도형) /
|
||||
"text"(텍스트) / "image"(이미지 파일) / "movie"(동영상 파일)를
|
||||
"text"(텍스트) / "image"(이미지 파일) / "movie"(동영상 파일) /
|
||||
"scene"(씬) / "brush"(무늬)를
|
||||
지원합니다. 로드 후 obj.w / obj.h 등은 생성 크기로 갱신되며, 로드
|
||||
직후의 getpixel로도 참조할 수 있습니다. 기존 엔진과 고속 엔진
|
||||
양쪽에서 동작합니다.
|
||||
※ "scene"과 "brush"는 AviUtl에 존재하지 않는 YMM4 전용
|
||||
확장입니다.
|
||||
|
||||
obj.load("figure", 이름, 색, 크기 [, 라인 [, 종횡비]])
|
||||
도형을 생성하여 버퍼를 교체합니다(중심 배치).
|
||||
@@ -468,6 +500,40 @@
|
||||
(MP4 / MOV / MKV / WebM / AVI / FLV / ASF)만 읽습니다.
|
||||
예: obj.load("movie", "C:\\mov\\clip.mp4", obj.time)
|
||||
|
||||
obj.load("scene", 씬이름 [, 시간])
|
||||
프로젝트 안의 다른 씬을 그려 버퍼를 교체합니다.
|
||||
씬이름 : 씬 목록에 표시되는 이름.
|
||||
시간 : 초. 생략 시 obj.time.
|
||||
※ 현재 오브젝트가 놓인 씬 자신은 지정할 수 없으며, 씬
|
||||
그리기 도중에 다시 씬을 로드할 수도 없습니다.
|
||||
※ 씬을 로드한 프레임은 렌더 캐시를 사용하지 않고 매번
|
||||
다시 실행됩니다.
|
||||
예: obj.load("scene", "서브 씬", obj.time)
|
||||
|
||||
obj.load("brush", 무늬이름 [, 너비 [, 높이]])
|
||||
YMM4의 무늬(브러시)로 채운 이미지를 생성하여 버퍼를
|
||||
교체합니다. 브러시 플러그인으로 추가한 무늬도 사용할 수
|
||||
있습니다.
|
||||
무늬이름 : 무늬 목록에 표시되는 이름.
|
||||
너비, 높이 : 생성 크기(픽셀). 생략 시 현재 obj.w / obj.h.
|
||||
※ 무늬는 기본 매개변수로 그려집니다.
|
||||
예: obj.load("brush", "줄무늬", 400, 300)
|
||||
|
||||
○ obj.brush(무늬이름 [, 너비, 높이] [, 매개변수명, 값, ...])
|
||||
YMM4의 무늬(브러시)를 매개변수 지정과 함께 그려 버퍼를
|
||||
교체합니다. 그리기는 obj.load("brush")와 같고, 추가로
|
||||
obj.effect와 같은 「이름과 값의 쌍」으로 무늬의 매개변수를
|
||||
변경할 수 있습니다.
|
||||
무늬이름 : 무늬 목록에 표시되는 이름.
|
||||
너비, 높이 : 생성 크기(픽셀). 생략 시 현재 obj.w / obj.h.
|
||||
둘 다 숫자로 주어졌을 때만 크기로 해석합니다.
|
||||
매개변수명 : 무늬 설정 항목의 표시 이름, 또는 내부 속성 이름.
|
||||
값 : 숫자, 불리언, 문자열. 색은 0xRRGGBB 숫자.
|
||||
※ 지정하지 않은 매개변수는 기본값으로 그려집니다. 쌍을 모두
|
||||
생략한 호출은 obj.load("brush")와 같습니다.
|
||||
※ AviUtl에 존재하지 않는 YMM4 전용 확장입니다.
|
||||
예: obj.brush("줄무늬", "Angle", 45, "Color1", 0xff3366)
|
||||
|
||||
○ obj.setfont(글꼴 [, 크기 [, 스타일 [, 색]]])
|
||||
obj.load("text")에서 사용할 글꼴을 설정합니다.
|
||||
스타일 : 비트 플래그. 1=굵게, 2=기울임, 3=굵게+기울임.
|
||||
@@ -539,12 +605,98 @@
|
||||
장면 크기의 투명한 영역에 오브젝트를 합성한 가상 이미지입니다.
|
||||
※ GPU를 사용할 수 없는 환경에서는 호출이 건너뛰어집니다.
|
||||
|
||||
○ obj.fill(r, g, b [, a [, x, y, w, h]]) (YMM4 전용 확장)
|
||||
오브젝트 이미지를 지정한 색으로 채웁니다. 색은 0~255 의 스트레이트
|
||||
RGBA 로 지정합니다(obj.setpixel 과 같은 표색).
|
||||
r, g, b : 색 성분(0~255).
|
||||
a : 불투명도(0~255). 생략 시 255.
|
||||
x, y, w, h: 채울 사각형. 생략 시 이미지 전체이며 범위를 벗어나면
|
||||
잘립니다.
|
||||
예: obj.fill(0, 0, 0, 0) -- 전체를 투명으로 지움
|
||||
obj.fill(255, 0, 0, 255, 10, 10, 20, 20)
|
||||
두 엔진 모두에서 동작합니다.
|
||||
|
||||
○ obj.getpixelregion(x, y, w, h) (YMM4 전용 확장)
|
||||
사각형 영역의 픽셀을 스트레이트 RGBA 배열로 가져옵니다. 배열은
|
||||
픽셀마다 r, g, b, a 순이며 1 부터 시작합니다(색인 (행*w+열)*4+1~+4).
|
||||
이미지 밖의 픽셀은 0,0,0,0 입니다.
|
||||
반환값 : 길이 w*h*4 의 배열.
|
||||
예: local t = obj.getpixelregion(0, 0, obj.w, obj.h)
|
||||
|
||||
○ obj.putpixelregion(x, y, w, h, 데이터) (YMM4 전용 확장)
|
||||
obj.getpixelregion 과 같은 배열을 사각형 영역에 다시 씁니다. 이미지
|
||||
범위를 벗어난 픽셀은 쓰지 않습니다.
|
||||
데이터 : 길이 w*h*4 의 스트레이트 RGBA 배열(1 부터 시작).
|
||||
예: obj.putpixelregion(0, 0, obj.w, obj.h, t)
|
||||
|
||||
○ obj.convolve(커널, 크기 [, 제수 [, 오프셋]]) (YMM4 전용 확장)
|
||||
오브젝트 이미지에 크기×크기 의 컨볼루션을 적용합니다. 흐림, 샤픈,
|
||||
윤곽 검출 등에 사용할 수 있습니다.
|
||||
커널 : 크기*크기 개의 계수 배열(행 우선, 1 부터 시작).
|
||||
크기 : 홀수(3, 5, 7 …). 짝수나 1 미만은 무시합니다.
|
||||
제수 : 각 픽셀의 합계를 이 값으로 나눕니다. 생략 시 커널의
|
||||
합계(합계가 0 이면 1).
|
||||
오프셋 : 나눗셈 후 각 성분에 더합니다. 생략 시 0.
|
||||
가장자리 픽셀은 가장 가까운 픽셀로 채웁니다. r, g, b, a 모두에
|
||||
적용됩니다.
|
||||
예: obj.convolve({1,1,1, 1,1,1, 1,1,1}, 3) -- 평균 흐림
|
||||
obj.convolve({0,-1,0, -1,5,-1, 0,-1,0}, 3) -- 샤픈
|
||||
두 엔진 모두에서 동작합니다.
|
||||
|
||||
○ obj.resize(너비, 높이 [, 보간]) (YMM4 전용 확장)
|
||||
오브젝트 이미지를 지정한 크기로 확대/축소합니다. obj.w / obj.h 등의
|
||||
치수도 갱신됩니다.
|
||||
너비, 높이 : 1 이상의 정수.
|
||||
보간 : "nearest"(최근접) 또는 생략 시 선형 보간.
|
||||
예: obj.resize(obj.w * 2, obj.h * 2)
|
||||
두 엔진 모두에서 동작합니다. 고속 런타임에서는 결과가 최대 이미지
|
||||
크기를 넘으면 변경하지 않습니다.
|
||||
|
||||
○ obj.getvalue(대상)
|
||||
obj의 현재 값을 가져옵니다(obj.x, obj.track0 등과 동일).
|
||||
대상 : "x","y","z","ox","oy","rx","ry","rz","zoom","aspect",
|
||||
"alpha","sx","sy","track0"~"track3","time","frame" 등.
|
||||
반환값 : 숫자(알 수 없는 대상은 0).
|
||||
|
||||
○ obj.getaudio(버퍼, 파일명 [, 종류 [, 개수]])
|
||||
오디오 데이터를 가져옵니다.
|
||||
버퍼 : 데이터를 저장할 테이블입니다. 데이터는 버퍼[1]~버퍼[n]에
|
||||
저장됩니다. nil을 지정하면 테이블이 세 번째 반환값으로
|
||||
반환됩니다.
|
||||
파일명 : 오디오 파일의 경로입니다. 다음의 특별한 이름도 지정할
|
||||
수 있습니다.
|
||||
"audiobuffer" : 편집 중인 씬 전체의 오디오(타임라인의 모든
|
||||
아이템을 합성한 오디오)를 가져옵니다.
|
||||
"itembuffer" : 이 이펙트가 붙은 아이템 자신의 오디오(음량·
|
||||
팬·페이드·오디오 이펙트 적용 후)를 가져
|
||||
옵니다. YMM4 전용 확장입니다.
|
||||
종류 : 가져올 데이터의 종류를 문자열로 지정합니다. 생략 시 "pcm".
|
||||
"pcm" : 16bit 스케일 기준(-32768~32767)의 모노 PCM.
|
||||
"spectrum" : 주파수 대역별 음량 데이터(약 0~32768). 개수는
|
||||
분할할 대역의 수입니다(최대 512, 생략 시 32).
|
||||
"fourier" : 이산 푸리에 변환의 진폭 데이터(약 0.0~1.0).
|
||||
주파수 범위는 1/2048~1/2이며 생략 시 1024개입니다.
|
||||
"xxxx.l" / "xxxx.r" : 위 종류의 왼쪽 / 오른쪽 채널 버전.
|
||||
지정하지 않으면 좌우의 평균입니다.
|
||||
개수 : 가져올 데이터 개수입니다. 실제 개수가 지정보다 적을 수
|
||||
있습니다. 한 번에 최대 1024개까지 가져올 수 있습니다.
|
||||
반환값 : 가져온 데이터 개수, 샘플링 레이트[, 테이블].
|
||||
읽기 위치는 "audiobuffer"의 경우 타임라인의 현재 위치, 그 외에는
|
||||
오브젝트의 현재 재생 위치(obj.time)입니다. "pcm"은 현재 위치부터
|
||||
연속된 샘플을 반환하고, "spectrum" / "fourier"는 현재 위치부터의
|
||||
구간을 분석해 반환합니다.
|
||||
예:
|
||||
local buf = {}
|
||||
local n = obj.getaudio(buf, "audiobuffer", "spectrum", 32)
|
||||
for i = 1, n do
|
||||
obj.draw((i - n / 2) * 8, -buf[i] / 200)
|
||||
end
|
||||
※ 두 엔진 모두에서 동작합니다. 읽을 수 없는 경우 데이터 개수 0을
|
||||
반환하며 오류가 되지 않습니다.
|
||||
※ "itembuffer"는 오디오가 없는 아이템(이미지, 도형 등)에서는
|
||||
데이터 개수 0이 됩니다. YMM4 내부 구현을 사용할 수 없는 경우
|
||||
음량 등을 적용하기 전의 오디오가 됩니다.
|
||||
|
||||
○ obj.getinfo(이름)
|
||||
각종 환경 정보를 가져옵니다. 지원하지 않는 이름은 nil을 반환합니다.
|
||||
"script_path" : 플러그인 설치 폴더의 경로를 반환합니다. 끝에 경로
|
||||
@@ -615,7 +767,8 @@
|
||||
"arm" : 오브젝트 중심에서 각 앵커 포인트로 차례로 잇습니다.
|
||||
"xyz" : 앵커 포인트를 3D 좌표로 다룹니다. 기본은 2D입니다.
|
||||
설치한 앵커 포인트 수를 반환합니다. 두 엔진 모두에서 동작합니다.
|
||||
이름에 "track"을 지정하는 트랙바 연동은 현재 미지원이며 0을 반환합니다.
|
||||
이름에 "track"을 지정하는 경우도 지원하며, 개수 0은 1개로 배치합니다.
|
||||
선택 중인 앵커는 앵커 그룹의 X / Y / Z 슬라이더로 수치 조정할 수 있습니다.
|
||||
예:
|
||||
num = obj.track0
|
||||
obj.setanchor("pos", num, "loop")
|
||||
@@ -817,6 +970,17 @@
|
||||
x in <1..5>는 1 <= x and x <= 5를 판정합니다.
|
||||
<1..<5>는 상한을 포함하지 않습니다. 왼쪽 값은 한 번만 평가합니다.
|
||||
|
||||
○ [fast] (가속 마커) ※YMM4 고유 확장
|
||||
obj.fill / obj.convolve / obj.resize는 처리량이 임계값 이상이고
|
||||
GPU 결과가 CPU와 일치함이 확인되면 자동으로 GPU에 위임합니다.
|
||||
[fast]는 위임 의도를 명시하는 보조 마커이며, 붙여도 동작은
|
||||
변하지 않습니다. 마커는 단독 행에 두어도, 같은 행에 이어 써도
|
||||
됩니다.
|
||||
예: [fast]
|
||||
obj.convolve(kernel, 5)
|
||||
※ [fast]를 붙인 대상이 위 3개 함수가 아니면 오류를 표시합니다.
|
||||
※ 기존 엔진과 고속 런타임 양쪽에서 동작합니다.
|
||||
|
||||
|
||||
- 스크립트 예 -
|
||||
|
||||
@@ -897,7 +1061,7 @@
|
||||
○ 그리기·합성·로드
|
||||
obj.draw / obj.drawpoly에 의한 그리기 합성, obj.copybuffer에 의한
|
||||
버퍼 조작, obj.load("figure"/"text"/"image"/"movie")에 의한 생성·로드,
|
||||
obj.setfont, obj.effect, obj.getvalue, obj.getinfo, 그리고 obj.setoption /
|
||||
obj.setfont, obj.effect, obj.getvalue, obj.getaudio, obj.getinfo, 그리고 obj.setoption /
|
||||
obj.getoption / obj.pixeloption을 지원합니다. 자세한 내용은
|
||||
"obj 테이블 - 함수"를 참조하세요.
|
||||
|
||||
@@ -940,12 +1104,11 @@
|
||||
이를 호출하는 스크립트는 의도대로 동작하지 않습니다.
|
||||
× require에 의한 모듈 로드 및 io / dofile 등의 임의 파일 접근
|
||||
(obj.load의 이미지 / 동영상 로드는 헤더 검증과 함께 지원).
|
||||
× obj.setanchor 등.
|
||||
|
||||
|
||||
- 미지원·제한 사항 -
|
||||
|
||||
× AviUtl2의 obj.rand1(), obj.mes(), obj.setanchor() 등은 지원하지 않습니다.
|
||||
× AviUtl2의 obj.rand1(), obj.mes() 등은 지원하지 않습니다.
|
||||
× 스크립트에서의 임의 파일 접근(require, dofile, io 등)은 지원하지 않습니다.
|
||||
obj.load("image"/"movie")만 선두 헤더 검증으로 진짜 미디어로 확인된 파일을
|
||||
읽습니다.
|
||||
|
||||
@@ -57,13 +57,26 @@
|
||||
obj.setpixel(x, y, r2, g2, b2 [, a2])
|
||||
end
|
||||
end
|
||||
使用 getpixeldata 的下列形式同样会被内核化。
|
||||
local data = obj.getpixeldata()
|
||||
for y = 0, data.height - 1 do
|
||||
for x = 0, data.width - 1 do
|
||||
local i = (y * data.width + x) * 4
|
||||
local r = data:get(i + 1)
|
||||
data:set(i + 1, r2)
|
||||
data:set(i + 2, g2)
|
||||
data:set(i + 3, b2)
|
||||
end
|
||||
end
|
||||
obj.putpixeldata(data)
|
||||
· 主体中仅可使用四则运算、math.*、比较、阈值写法
|
||||
“条件 and 值1 or 值2”以及 local 变量。
|
||||
· 仅可引用正在处理的自像素(getpixel(x, y))
|
||||
以及 obj/scene/time 等值。
|
||||
· 含有邻域参照(模糊等)、写入其他坐标、getpixeldata、
|
||||
getobject、表/字符串操作、if 语句等的脚本不会被内核化,
|
||||
会自动由传统引擎执行。
|
||||
“条件 and 值1 or 值2”、通过 if/elseif/else 对 local 变量的
|
||||
条件赋值以及 local 变量。
|
||||
· 循环上限也可以使用 local w = obj.w 这样的别名。
|
||||
· 仅可引用正在处理的自像素以及 obj/scene/time 等值。
|
||||
· 含有邻域参照(模糊等)、写入其他坐标、在 if 语句中调用
|
||||
setpixel 或 set、getobject、表/字符串操作等的脚本不会被
|
||||
内核化,会自动由传统引擎执行。
|
||||
|
||||
示例(让白色图形变红):
|
||||
--!gpu
|
||||
@@ -309,9 +322,13 @@
|
||||
※ 指定第二个参数 frame 时,获取该时间轴帧的数值。省略时获取当前帧。
|
||||
※ 当多个项目拥有相同标签时,优先返回在目标帧显示中的项目。
|
||||
若没有显示中的项目,则返回第一个匹配的项目。
|
||||
※ 语音项目 (合成语音等) 也是对象。语音项目的坐标、缩放、
|
||||
旋转和不透明度返回其字幕显示信息。
|
||||
※ 获取的值是项目自身的坐标、旋转和缩放。
|
||||
不包含组控制、摄像机控制以及上层特效造成的变换。
|
||||
※ 各数值使用与 obj 表相同的单位体系。
|
||||
※ .character / .text / .volume / .kind / .length 是 AviUtl 中不存在的
|
||||
YMM4 独有扩展。两种引擎均可运行。
|
||||
tag : 设置在目标项目备注中的字符串
|
||||
frame : 要获取的时间轴绝对帧 (可省略)
|
||||
返回值 : 对象信息表。当不存在匹配项目时返回 nil。
|
||||
@@ -330,6 +347,11 @@
|
||||
.rzr : Z 轴旋转角度 (弧度)
|
||||
.alpha : 不透明度 (0.0 ~ 255.0, 已应用淡入淡出)
|
||||
.layer : 所在图层编号
|
||||
.length : 项目长度 (帧数)
|
||||
.volume : 音量设置的当前值 (仅语音项目。其他为 0)
|
||||
.character : 角色名 (仅语音项目。其他为空字符串)
|
||||
.text : 台词或显示文本 (仅语音和文本项目。其他为空字符串)
|
||||
.kind : 项目类别名 (例:VoiceItem, TextItem, ImageItem)
|
||||
示例:
|
||||
local funnel = obj.getobject("funnel")
|
||||
if funnel then
|
||||
@@ -343,6 +365,11 @@
|
||||
obj.x = src.x
|
||||
obj.y = src.y
|
||||
end
|
||||
按角色名改变颜色的示例 (目标备注为 "voice"):
|
||||
local v = obj.getobject("voice")
|
||||
if v and v.character == "魔理沙" then
|
||||
obj.effect("单色化", "强度", 100, "color", 0xffee55)
|
||||
end
|
||||
|
||||
○ obj.getpixel(x, y)
|
||||
获取指定坐标的像素信息。
|
||||
@@ -426,8 +453,10 @@
|
||||
|
||||
○ obj.load(目标, ...)
|
||||
将对象缓冲区替换为生成的内容。支持 "figure"(图形) / "text"(文本) /
|
||||
"image"(图像文件) / "movie"(视频文件)。加载后 obj.w / obj.h 等会更新为
|
||||
"image"(图像文件) / "movie"(视频文件) / "scene"(场景) /
|
||||
"brush"(图案)。加载后 obj.w / obj.h 等会更新为
|
||||
生成尺寸,紧接着的 getpixel 也可读取。传统引擎与高速引擎均可运行。
|
||||
※ "scene" 与 "brush" 是 AviUtl 中不存在的 YMM4 专用扩展。
|
||||
|
||||
obj.load("figure", 名称, 颜色, 大小 [, 线宽 [, 纵横比]])
|
||||
生成图形并替换缓冲区(居中)。
|
||||
@@ -459,6 +488,37 @@
|
||||
(MP4 / MOV / MKV / WebM / AVI / FLV / ASF)。
|
||||
示例:obj.load("movie", "C:\\mov\\clip.mp4", obj.time)
|
||||
|
||||
obj.load("scene", 场景名 [, 时间])
|
||||
绘制项目内的另一个场景并替换缓冲区。
|
||||
场景名 : 场景列表中显示的名称。
|
||||
时间 : 秒。省略时为 obj.time。
|
||||
※ 不能指定当前对象所在的场景本身,也不能在场景绘制
|
||||
过程中再次加载场景。
|
||||
※ 加载了场景的帧不使用绘制缓存,每次都会重新执行。
|
||||
示例:obj.load("scene", "子场景", obj.time)
|
||||
|
||||
obj.load("brush", 图案名 [, 宽 [, 高]])
|
||||
以 YMM4 的图案(笔刷)填充生成图像并替换缓冲区。
|
||||
通过笔刷插件添加的图案也可以使用。
|
||||
图案名 : 图案列表中显示的名称(例:条纹、棋盘格)。
|
||||
宽、高 : 生成尺寸(像素)。省略时为当前 obj.w / obj.h。
|
||||
※ 图案以默认参数绘制。
|
||||
示例:obj.load("brush", "条纹", 400, 300)
|
||||
|
||||
○ obj.brush(图案名 [, 宽, 高] [, 参数名, 值, ...])
|
||||
以带参数指定的方式绘制 YMM4 的图案(笔刷)并替换缓冲区。
|
||||
绘制与 obj.load("brush") 相同,另外可以用与 obj.effect 相同的
|
||||
「名称与值的组」修改图案的参数。
|
||||
图案名 : 图案列表中显示的名称。
|
||||
宽、高 : 生成尺寸(像素)。省略时为当前 obj.w / obj.h。仅当两者
|
||||
都以数值给出时才解释为尺寸。
|
||||
参数名 : 图案设置项的显示名称,或其内部属性名。
|
||||
值 : 数值、布尔值、字符串。颜色为 0xRRGGBB 的数值。
|
||||
※ 未指定的参数以默认值绘制。省略所有组的调用与
|
||||
obj.load("brush") 相同。
|
||||
※ 这是 AviUtl 中不存在的 YMM4 专用扩展。
|
||||
示例:obj.brush("条纹", "Angle", 45, "Color1", 0xff3366)
|
||||
|
||||
○ obj.setfont(字体 [, 大小 [, 样式 [, 颜色]]])
|
||||
设置 obj.load("text") 使用的字体。
|
||||
样式 : 位标志。1=粗体, 2=斜体, 3=粗斜体。
|
||||
@@ -526,12 +586,89 @@
|
||||
场景大小透明区域后的虚拟图像。
|
||||
※ 在无法使用GPU的环境中会跳过该调用。
|
||||
|
||||
○ obj.fill(r, g, b [, a [, x, y, w, h]]) (YMM4 独有扩展)
|
||||
以指定颜色填充对象图像。颜色以 0~255 的直通 RGBA 指定(与
|
||||
obj.setpixel 相同的表色)。
|
||||
r, g, b : 颜色分量(0~255)。
|
||||
a : 不透明度(0~255)。省略时为 255。
|
||||
x, y, w, h: 要填充的矩形。省略时为整幅图像,超出范围会被裁剪。
|
||||
例: obj.fill(0, 0, 0, 0) -- 将整体清为透明
|
||||
obj.fill(255, 0, 0, 255, 10, 10, 20, 20)
|
||||
在两个引擎中均可使用。
|
||||
|
||||
○ obj.getpixelregion(x, y, w, h) (YMM4 独有扩展)
|
||||
将矩形区域的像素读入直通 RGBA 数组。排列为每个像素 r, g, b, a,
|
||||
从 1 开始(索引 (行*w+列)*4+1~+4)。图像外的像素为 0,0,0,0。
|
||||
返回值: 长度为 w*h*4 的数组。
|
||||
例: local t = obj.getpixelregion(0, 0, obj.w, obj.h)
|
||||
|
||||
○ obj.putpixelregion(x, y, w, h, 数据) (YMM4 独有扩展)
|
||||
将与 obj.getpixelregion 相同排列的数组写回矩形区域。超出图像范围的
|
||||
像素不会被写入。
|
||||
数据 : 长度为 w*h*4 的直通 RGBA 数组(从 1 开始)。
|
||||
例: obj.putpixelregion(0, 0, obj.w, obj.h, t)
|
||||
|
||||
○ obj.convolve(卷积核, 大小 [, 除数 [, 偏移]]) (YMM4 独有扩展)
|
||||
对对象图像应用 大小×大小 的卷积。可用于模糊、锐化、边缘检测等。
|
||||
卷积核 : 大小*大小 个系数数组(行优先,从 1 开始)。
|
||||
大小 : 奇数(3、5、7 …)。偶数或小于 1 会被忽略。
|
||||
除数 : 每个像素的合计除以该值。省略时为卷积核的合计(合计为 0
|
||||
时为 1)。
|
||||
偏移 : 除法后加到各分量上。省略时为 0。
|
||||
边缘像素以最近的像素补充。对 r, g, b, a 全部生效。
|
||||
例: obj.convolve({1,1,1, 1,1,1, 1,1,1}, 3) -- 均值模糊
|
||||
obj.convolve({0,-1,0, -1,5,-1, 0,-1,0}, 3) -- 锐化
|
||||
在两个引擎中均可使用。
|
||||
|
||||
○ obj.resize(宽, 高 [, 插值]) (YMM4 独有扩展)
|
||||
将对象图像缩放到指定尺寸。obj.w / obj.h 等尺寸也会更新。
|
||||
宽, 高 : 大于等于 1 的整数。
|
||||
插值 : "nearest"(最近邻)或省略以进行线性插值。
|
||||
例: obj.resize(obj.w * 2, obj.h * 2)
|
||||
在两个引擎中均可使用。在快速运行时中,若结果超过最大图像尺寸
|
||||
则不做更改。
|
||||
|
||||
○ obj.getvalue(目标)
|
||||
获取 obj 的当前值(与 obj.x、obj.track0 等相同)。
|
||||
目标 : "x","y","z","ox","oy","rx","ry","rz","zoom","aspect",
|
||||
"alpha","sx","sy","track0"~"track3","time","frame" 等。
|
||||
返回值 : 数值(未知目标返回 0)。
|
||||
|
||||
○ obj.getaudio(缓冲区, 文件名 [, 类型 [, 数量]])
|
||||
获取音频数据。
|
||||
缓冲区 : 用于存放数据的表。数据存入 缓冲区[1]~缓冲区[n]。
|
||||
指定 nil 时,表将作为第 3 个返回值返回。
|
||||
文件名 : 音频文件的路径。也可以指定以下特殊名称。
|
||||
"audiobuffer" : 获取正在编辑的整个场景的音频(时间轴上全部
|
||||
项目混合后的音频)。
|
||||
"itembuffer" : 获取附加了本效果的项目自身的音频(应用音量、
|
||||
声像、淡入淡出和音频效果之后)。这是 YMM4
|
||||
专有的扩展。
|
||||
类型 : 以字符串指定要获取的数据种类。省略时为 "pcm"。
|
||||
"pcm" : 以 16bit 为基准(-32768~32767)的单声道 PCM。
|
||||
"spectrum" : 各频段的音量数据(约 0~32768)。数量为频段的
|
||||
分割数(最多 512,省略时 32)。
|
||||
"fourier" : 离散傅里叶变换的振幅数据(约 0.0~1.0)。频率
|
||||
范围为 1/2048~1/2,省略时为 1024 个。
|
||||
"xxxx.l" / "xxxx.r" : 上述类型的左 / 右声道版本。未指定时
|
||||
取左右声道的平均值。
|
||||
数量 : 要获取的数据个数。实际获取的个数可能少于指定值。
|
||||
一次最多可获取 1024 个。
|
||||
返回值 : 获取的数据个数, 采样率[, 表]。
|
||||
"audiobuffer" 的读取位置为时间轴的当前位置,其余为对象当前的
|
||||
播放位置(obj.time)。"pcm" 返回从该位置起连续的采样,
|
||||
"spectrum" / "fourier" 则分析从该位置开始的区间。
|
||||
示例:
|
||||
local buf = {}
|
||||
local n = obj.getaudio(buf, "audiobuffer", "spectrum", 32)
|
||||
for i = 1, n do
|
||||
obj.draw((i - n / 2) * 8, -buf[i] / 200)
|
||||
end
|
||||
※ 在两个引擎中均可使用。无法读取时返回数据个数 0,不会报错。
|
||||
※ "itembuffer" 对没有音频的项目(图像、图形等)返回数据个数 0。
|
||||
无法使用 YMM4 内部实现时,将回退为应用音量等效果之前的
|
||||
音频。
|
||||
|
||||
○ obj.getinfo(名称)
|
||||
获取各种环境信息。不支持的名称返回 nil。
|
||||
"script_path" : 返回插件安装文件夹的路径,末尾带有路径分隔符。
|
||||
@@ -591,7 +728,8 @@
|
||||
"arm" : 从对象中心依次连接到各锚点。
|
||||
"xyz" : 以 3D 坐标处理锚点。默认是 2D。
|
||||
返回设置的锚点数量。两个引擎都可用。
|
||||
名称指定 "track" 的轨道条联动暂不支持,返回 0。
|
||||
名称指定 "track" 时也已支持,个数为 0 时放置 1 个。
|
||||
选中的锚点可通过锚点组的 X / Y / Z 滑块进行数值调整。
|
||||
示例:
|
||||
num = obj.track0
|
||||
obj.setanchor("pos", num, "loop")
|
||||
@@ -790,6 +928,16 @@
|
||||
x in <1..5> 判断 1 <= x and x <= 5。
|
||||
<1..<5> 不包含上限。左侧只求值一次。
|
||||
|
||||
○ [fast](加速标记) ※YMM4专有扩展
|
||||
当处理量达到阈值且 GPU 结果经验证与 CPU 一致时,obj.fill /
|
||||
obj.convolve / obj.resize 会自动委托给 GPU。[fast] 是显式表明
|
||||
委托意图的辅助标记,加上它不会改变行为。标记可以单独占一行,
|
||||
也可以写在同一行。
|
||||
例:[fast]
|
||||
obj.convolve(kernel, 5)
|
||||
※ 若 [fast] 修饰的目标不是上述 3 个函数,则显示错误。
|
||||
※ 在传统引擎和高速运行时上均可运行。
|
||||
|
||||
|
||||
- 脚本示例 -
|
||||
|
||||
@@ -865,7 +1013,7 @@
|
||||
○ 绘制·合成·加载
|
||||
支持 obj.draw / obj.drawpoly 的绘制合成、obj.copybuffer 的缓冲区操作、
|
||||
obj.load("figure"/"text"/"image"/"movie") 的生成与加载、obj.setfont、
|
||||
obj.effect、obj.getvalue、obj.getinfo 以及 obj.setoption / obj.getoption /
|
||||
obj.effect、obj.getvalue、obj.getaudio、obj.getinfo 以及 obj.setoption / obj.getoption /
|
||||
obj.pixeloption。详情请参阅“obj 表 - 函数”。
|
||||
|
||||
○ obj.effect 的 AviUtl / AviUtl2 兼容映射
|
||||
@@ -905,12 +1053,11 @@
|
||||
调用它们的脚本不会按预期运行。
|
||||
× 通过 require 加载模块,以及 io / dofile 等任意文件访问
|
||||
(obj.load 的图像 / 视频加载已带文件头校验支持)。
|
||||
× obj.setanchor 等。
|
||||
|
||||
|
||||
- 不支持项目·限制事项 -
|
||||
|
||||
× 不支持 AviUtl2 的 obj.rand1()、obj.mes()、obj.setanchor() 等。
|
||||
× 不支持 AviUtl2 的 obj.rand1()、obj.mes() 等。
|
||||
× 不支持脚本进行任意文件访问(require、dofile、io 等)。
|
||||
仅 obj.load("image"/"movie") 会加载经文件头校验确认为真正媒体的文件。
|
||||
× 修改 obj.z 会反映到绘制中(包含在 ReadBack 中),
|
||||
|
||||
110ファイル中100ファイルを読み込みました。 変更されたファイルが多すぎるため、それ以降のファイルは表示していません。
さらに表示
新しいイシューから参照
ユーザーをブロックする