コミットを比較
| 作成者 | SHA1 | 日付 | |
|---|---|---|---|
|
|
381a717942
|
||
|
|
1d92d80a86
|
||
|
|
86ad19105f
|
||
|
|
2cd5ab273a
|
||
|
|
d75aeee3c2
|
||
|
|
981fb2ceeb
|
||
|
|
01a0dcb9ae
|
||
|
|
460b5e6252
|
||
|
|
fb02580836
|
||
|
|
58a5f59b19
|
||
|
|
95598b1a88
|
||
|
|
7f436ebe17
|
||
|
|
d620f7ea3b
|
||
|
|
ad377a0923
|
||
|
|
f374038000
|
||
|
|
ddba8d63c2
|
||
|
|
ab2e195139
|
||
|
|
85c585db89
|
||
|
|
93eb681b0e
|
||
|
|
30ca75f65e
|
||
|
|
a07916de6b
|
||
|
|
467a4b0dd8
|
||
|
|
03aad4cc6e
|
||
|
|
b638c7b9c2
|
||
|
|
ede56971cd
|
||
|
|
94c11dffcb
|
||
|
|
28c1f70fa1
|
||
|
|
2ecde28980
|
||
|
|
1c2c3915e9
|
||
|
|
9f2cab9961
|
||
|
|
e1778c7c73
|
||
|
|
98426f4ca8
|
||
|
|
7358e2b0a1
|
||
|
|
1af7b8fc8b
|
||
|
|
26d7b0c470
|
||
|
|
96400605ba
|
||
|
|
695cb2f04d
|
||
|
|
6b39a4cceb
|
||
|
|
4b4252855b
|
||
|
|
0d6c3285e1
|
||
|
|
3bcf206a95
|
||
|
|
c65bb5b08f
|
||
|
|
e5b9b98a27
|
||
|
|
7906d4c735
|
||
|
|
d879f3c6fa
|
||
|
|
e7ae3bf290
|
||
|
|
735fd86bed
|
||
|
|
813b3d6686
|
||
|
|
ca43e3706b
|
||
|
|
ef4d7e8024
|
||
|
|
299da15bb8
|
||
|
|
ffba68aeb0
|
||
|
|
1085294aa0
|
||
|
|
cb7e4622e8
|
||
|
|
06e2afa7ed
|
||
|
|
3e60c6d77f
|
||
|
|
594517b436
|
||
|
|
1d3b924492
|
||
|
|
b6cd4bb43e
|
||
|
|
5c0745e039
|
||
|
|
c5fd507ab5
|
||
|
|
dfc39e9e19
|
||
|
|
48d7969a84
|
||
|
|
9eb5a44f2d
|
||
|
|
fc2fc6ab77
|
||
|
|
bc7fa914a4
|
||
|
|
c436f24ee0
|
||
|
|
5a192f5a6f
|
||
|
|
a032f0728f
|
||
|
|
548432f3a9
|
||
|
|
3bd1e5384e
|
||
|
|
738da05e59
|
||
|
|
d457b65f44
|
||
|
|
270cf025ff
|
||
|
|
c657892b7b
|
||
|
|
87cdd4ed90
|
||
|
|
5c1c1272db
|
||
|
|
bcac943775
|
||
|
|
3d0ff687e2
|
||
|
|
ce0da92ac8
|
||
|
|
7dbe063ac8
|
||
|
|
1acaef291c
|
||
|
|
26c96b302f
|
||
|
|
c4011d8eef
|
||
|
|
451b017f6f
|
||
|
|
d6b6e440bf
|
||
|
|
7601b77902
|
||
|
|
0799785cad
|
||
|
|
d607e4ec49
|
||
|
|
c7e5b91509
|
||
|
|
cf23d184fe
|
||
|
|
d2b518f611
|
||
|
|
c186a6b27d
|
||
|
|
5f411e89ec
|
||
|
|
16ed6336c3
|
||
|
|
6d2a5cbe24
|
||
|
|
94f7ad4f50
|
||
|
|
3ba77aab18
|
||
|
|
90fe288f66
|
||
|
|
6b2b5d879f | ||
|
|
d01d5d6df5 | ||
|
|
a093c458a2
|
||
|
|
0e65bf1883
|
||
|
|
d8f728b3f9
|
||
|
|
244e75a238
|
||
|
|
75cc4bd62e
|
||
|
|
6385dbeb6d
|
||
|
|
bc395a0181
|
||
|
|
a0dec019fe
|
||
|
|
c8350161db
|
||
|
|
679cab03b5
|
||
|
|
6783146231
|
||
|
|
df303ee154
|
||
|
|
f49bd740a0
|
||
|
|
80d1b75227
|
検索条件に一致するファイルはありません
+45
-40
@@ -1,56 +1,61 @@
|
|||||||
# v1.6.0 - Lua スクリプト for YMM4
|
# v1.10.0 - Lua スクリプト for YMM4
|
||||||
|
|
||||||
AviUtl のアニメーション効果スクリプト互換層に**動的パラメータの UI 反映**を
|
エフェクトパネルへ新しいパラメータ入力欄を追加したリリースです。整数スライダー 4 本と、
|
||||||
追加したリリースです。スクリプトのヘッダに記述した `--track` / `--check` /
|
テキスト・フォント・フォルダ・ファイルの文字列入力をスクリプトから参照できるようにしました。
|
||||||
`--color` の宣言が、エディタのパラメータUIへ自動的に反映されるようになりました。
|
文字列パラメータは MoonSharp とネイティブの両エンジンで同じ名前から参照でき、ネイティブでは
|
||||||
|
共有メモリの文字列領域を必要量に応じて拡張・縮小します。あわせて毎フレームのアロケーションを
|
||||||
|
見直し、補完候補を拡充しました。
|
||||||
|
|
||||||
---
|
---
|
||||||
|
|
||||||
## 新機能
|
## 新機能・機能改善
|
||||||
|
|
||||||
### 1. AviUtl ヘッダ宣言に応じた動的パラメータUI
|
### 1. 整数スライダー obj.slider0〜3
|
||||||
|
|
||||||
スクリプト先頭の `--track0`〜`--track3` / `--check0`〜`--check3` / `--color` を
|
数値スライダーを 4 本追加しました。各値は `obj.slider0`〜`obj.slider3` として参照できます。
|
||||||
解析し、宣言された項目だけをエディタUIへ表示します。AviUtl の仕様に準じ、
|
|
||||||
トラックバーは最大4個、チェックボックスは最大4個、カラーは1個です。
|
|
||||||
|
|
||||||
- `--track番号:名前,最小,最大,初期値,移動量`: 宣言されたトラックのスライダーを
|
- 値は整数で、小数は扱いません。表示範囲は `obj.slider0` が 1〜10、`obj.slider1` が 0〜100、
|
||||||
表示します。トラック値は評価時にヘッダの最小〜最大へクランプされ、`obj.track0`〜
|
`obj.slider2` が 0〜1000、`obj.slider3` が -1000〜1000 です。
|
||||||
`obj.track3` から参照できます。
|
- 状態の切り替えなど、補間を伴わない整数値の受け渡しに使えます。
|
||||||
- `--check番号:名前,初期値`: トグルスライダーを表示します。値は `obj.check0`〜
|
- MoonSharp・ネイティブ・CPU/GPU カーネルのいずれのレーンからも参照できます。
|
||||||
`obj.check3` から真偽値(false / true)として参照できます。
|
|
||||||
- `--color:色`: カラーピッカーを表示します。選択した色はグローバル変数 `color`
|
### 2. 文字列パラメータ obj.text / obj.font / obj.dir / obj.file_*
|
||||||
(0xRRGGBB)として参照できます。
|
|
||||||
- 宣言が一つも無い場合は、従来どおり Track0〜Track3 の4スライダー表示へ戻ります。
|
テキスト・フォント・フォルダ・ファイルの入力欄を追加しました。
|
||||||
- 各項目のラベルは多言語化された固定スロット(Track0〜3 / Check0〜3 / Color)で
|
|
||||||
表示されます。設定した値はプロジェクトファイルに保存され、再現できます。
|
- `obj.text` はテキスト入力欄の文字列、`obj.font` はフォント名、`obj.dir` はフォルダのパスです。
|
||||||
|
- ファイル選択は種類ごとに `obj.file_video` / `obj.file_audio` / `obj.file_image` /
|
||||||
|
`obj.file_project` / `obj.file_mp4` / `obj.file_exo` / `obj.file_subtitle` /
|
||||||
|
`obj.file_shader` で参照し、選択したファイルのパスを取得します。
|
||||||
|
- 取得したパスは `obj.load` へ渡して画像・動画の読み込みに使えます。
|
||||||
|
- MoonSharp とネイティブの両エンジンで同じ名前から参照できます。
|
||||||
|
|
||||||
|
### 3. 補完候補の拡充
|
||||||
|
|
||||||
|
スクリプトエディタの補完候補へ `obj.slider0`〜`obj.slider3` と、追加した文字列パラメータの
|
||||||
|
各名前を加えました。
|
||||||
|
|
||||||
---
|
---
|
||||||
|
|
||||||
## 注意事項
|
## 互換性・後方互換
|
||||||
|
|
||||||
- ラベルは固定スロット番号で表示され、スクリプト内に記述したパラメータ名
|
- スライダーと文字列パラメータは、スクリプト本体でそれらを参照したときだけエフェクトパネルへ
|
||||||
(例: `--track0:X速度,...` の「X速度」)は UI ラベルへは反映されません。
|
表示されます。参照しない既存スクリプトの表示と挙動は変わりません。
|
||||||
- トラックのスライダー操作範囲は従来どおり -100〜100 で、ヘッダの範囲・既定値は
|
- CPU/GPU カーネルは数値計算に特化するため、文字列パラメータは扱いません。文字列を参照する
|
||||||
スライダーの表示そのものには反映されません。トラック値は評価時にヘッダの
|
スクリプトは MoonSharp かネイティブで実行してください。
|
||||||
最小〜最大へクランプされます。新規に宣言されたチェック・色にはヘッダの既定値が
|
- トラックバー・チェックボックス・カラー・AviUtl 互換ヘッダの既存挙動は変わりません。
|
||||||
適用されますが、トラックには適用されず初期値は 0 のままです。
|
|
||||||
- `--dialog`(`/chk`・`/col`・`/fig`)、`--file`、`--font` には対応していません。
|
|
||||||
- 本変更に伴い、`--check` / `--color` の擬似展開(従来 `obj.checkN` や `color` を
|
|
||||||
スクリプト先頭へ自動挿入していた挙動)は廃止され、値は UI から供給されます。
|
|
||||||
`--dialog` / `--param` の展開は従来どおりです。
|
|
||||||
|
|
||||||
---
|
---
|
||||||
|
|
||||||
## 内部実装
|
## 内部実装
|
||||||
|
|
||||||
- AviUtl ヘッダ(`--track` / `--check` / `--color`)を解析するレイアウト解析を
|
- ネイティブの共有メモリへ文字列パラメータ領域を追加し、容量をワーカーの起動引数にしました。
|
||||||
追加しました。走査範囲は既存の互換変換と同じく最初の `@` セクションより前です。
|
必要量が容量を超えると 2 倍へ拡張し、容量の半分以下に収まると縮小します。最小は 64KB で、
|
||||||
- 解析結果に基づき、`[ShowPropertyEditorWhen]` による項目ごとの動的表示と、
|
容量の変化はワーカーの再生成のみで完結します。
|
||||||
評価時のトラック値クランプを実装しました。
|
- 文字列パラメータの変更検出をバージョン方式へ変更し、フレームごとの署名文字列の生成を
|
||||||
- `obj.check0`〜`obj.check3`(真偽値)とグローバル `color` を、MoonSharp および
|
やめました。値の参照が変わったときだけ版数を進めます。
|
||||||
ネイティブ(LuaJIT)双方の実行経路へ配線しました。
|
- ネイティブの文字列書き込みで、名前のバイト列をキャッシュし、値のエンコード先バッファを
|
||||||
- 互換変換から `--check` / `--color` の擬似展開を廃止し、UI を値の唯一のソースに
|
再利用します。
|
||||||
しました。
|
- スライダーの値は MoonSharp の obj テーブル・ネイティブのフィールド・CPU/GPU カーネルの
|
||||||
- チェック・色のラベルを多言語リソースへ追加しました。
|
ユニフォームへ配線しました。スクリプトの使用検出は obj メンバを汎用的に走査する方式へ
|
||||||
- ヘッダ解析および互換変換の挙動変更に関するユニットテストを追加・更新しました。
|
再設計しました。
|
||||||
@@ -1,5 +1,5 @@
|
|||||||
========================================
|
========================================
|
||||||
Luaスクリプト for YMM4 v1.6.0
|
Luaスクリプト for YMM4 v1.10.0
|
||||||
========================================
|
========================================
|
||||||
YukkuriMovieMaker4(YMM4)上で動作する、Luaスクリプトで映像エフェクトのパラメータや
|
YukkuriMovieMaker4(YMM4)上で動作する、Luaスクリプトで映像エフェクトのパラメータや
|
||||||
ピクセルを直接制御できるプラグインです。
|
ピクセルを直接制御できるプラグインです。
|
||||||
@@ -26,7 +26,9 @@ obj.x/y/zoom/alpha等の値はキーフレームアニメーションと連動
|
|||||||
|
|
||||||
- スクリプトエラー時の挙動: コンパイルエラーまたは実行時エラーが発生した場合、
|
- スクリプトエラー時の挙動: コンパイルエラーまたは実行時エラーが発生した場合、
|
||||||
そのフレームでの座標・透明度・回転・ピクセルの変更は適用されず、入力された
|
そのフレームでの座標・透明度・回転・ピクセルの変更は適用されず、入力された
|
||||||
元の状態がそのまま出力されます。エラー内容はログへ出力されます。
|
元の状態がそのまま出力されます。エラー内容はログへ出力されるほか、スクリプト
|
||||||
|
エディタの該当箇所へ赤い波線が表示され、ポイントするとエラー内容をツールチップ
|
||||||
|
で確認できます。
|
||||||
|
|
||||||
- ファイルアクセスの制限: スクリプトからのファイル読み込みは許可されておらず、
|
- ファイルアクセスの制限: スクリプトからのファイル読み込みは許可されておらず、
|
||||||
io・os等のモジュールも有効化されていません。
|
io・os等のモジュールも有効化されていません。
|
||||||
|
|||||||
@@ -0,0 +1,64 @@
|
|||||||
|
using LuaScript.Compat;
|
||||||
|
|
||||||
|
namespace LuaScript.Tests
|
||||||
|
{
|
||||||
|
public class AviUtlCompatMapTests
|
||||||
|
{
|
||||||
|
[Fact]
|
||||||
|
public void Resolve_KnownEffect_ReturnsTargetType()
|
||||||
|
{
|
||||||
|
Assert.True(AviUtlCompatMap.Default.TryResolve("ぼかし", AviUtlEngine.AviUtl, out var mapping));
|
||||||
|
Assert.Equal("GaussianBlurEffect", mapping.TargetType);
|
||||||
|
}
|
||||||
|
|
||||||
|
[Fact]
|
||||||
|
public void Resolve_ParameterTransform_IsInverseOfExoExport()
|
||||||
|
{
|
||||||
|
AviUtlCompatMap.Default.TryResolve("ぼかし", AviUtlEngine.AviUtl, out var mapping);
|
||||||
|
Assert.True(mapping.TryGetParameter("範囲", out var parameter));
|
||||||
|
Assert.Equal("Blur", parameter.Property);
|
||||||
|
Assert.Equal(5d, parameter.Transform(10d));
|
||||||
|
}
|
||||||
|
|
||||||
|
[Fact]
|
||||||
|
public void Resolve_AngleParameter_IsIdentity()
|
||||||
|
{
|
||||||
|
AviUtlCompatMap.Default.TryResolve("方向ブラー", AviUtlEngine.AviUtl, out var mapping);
|
||||||
|
Assert.True(mapping.TryGetParameter("角度", out var parameter));
|
||||||
|
Assert.Equal(45d, parameter.Transform(45d));
|
||||||
|
}
|
||||||
|
|
||||||
|
[Fact]
|
||||||
|
public void Resolve_BothEngine_MatchesAviUtl2()
|
||||||
|
{
|
||||||
|
Assert.True(AviUtlCompatMap.Default.TryResolve("クロマキー", AviUtlEngine.AviUtl2, out var mapping));
|
||||||
|
Assert.Equal("ChromaKeyEffect", mapping.TargetType);
|
||||||
|
}
|
||||||
|
|
||||||
|
[Fact]
|
||||||
|
public void Resolve_UndeclaredEffect_DoesNotResolve()
|
||||||
|
{
|
||||||
|
Assert.False(AviUtlCompatMap.Default.TryResolve("存在しないエフェクト", AviUtlEngine.AviUtl, out _));
|
||||||
|
}
|
||||||
|
|
||||||
|
[Fact]
|
||||||
|
public void ResolveTarget_DefaultsToAviUtl()
|
||||||
|
{
|
||||||
|
Assert.Equal(AviUtlEngine.AviUtl, AviUtlCompatMap.ResolveTarget("obj.effect(\"ぼかし\", \"範囲\", 10)"));
|
||||||
|
}
|
||||||
|
|
||||||
|
[Fact]
|
||||||
|
public void ResolveTarget_DirectiveSelectsAviUtl2()
|
||||||
|
{
|
||||||
|
Assert.Equal(AviUtlEngine.AviUtl2, AviUtlCompatMap.ResolveTarget("--!aviutl2\nobj.effect(\"ぼかし\", \"範囲\", 10)"));
|
||||||
|
}
|
||||||
|
|
||||||
|
[Fact]
|
||||||
|
public void Engine_BothIncludesEveryTarget()
|
||||||
|
{
|
||||||
|
Assert.True(AviUtlEngine.Both.Includes(AviUtlEngine.AviUtl));
|
||||||
|
Assert.True(AviUtlEngine.Both.Includes(AviUtlEngine.AviUtl2));
|
||||||
|
Assert.False(AviUtlEngine.AviUtl.Includes(AviUtlEngine.AviUtl2));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,63 @@
|
|||||||
|
using System.Numerics;
|
||||||
|
using LuaScript;
|
||||||
|
|
||||||
|
namespace LuaScript.Tests
|
||||||
|
{
|
||||||
|
public class DrawPolyMathTests
|
||||||
|
{
|
||||||
|
private static double[] Quad(
|
||||||
|
double x0, double y0, double x1, double y1,
|
||||||
|
double x2, double y2, double x3, double y3,
|
||||||
|
double u0, double v0, double u1, double v1,
|
||||||
|
double u2, double v2, double u3, double v3,
|
||||||
|
double alpha)
|
||||||
|
=> [x0, y0, 0, x1, y1, 0, x2, y2, 0, x3, y3, 0, u0, v0, u1, v1, u2, v2, u3, v3, alpha];
|
||||||
|
|
||||||
|
[Fact]
|
||||||
|
public void TrySolveAffine_MapsUvCornersToQuad()
|
||||||
|
{
|
||||||
|
var poly = Quad(
|
||||||
|
10, 20, 18, 20, 18, 32, 10, 32,
|
||||||
|
0, 0, 4, 0, 4, 4, 0, 4, 1);
|
||||||
|
|
||||||
|
Assert.True(DrawPolyMath.TrySolveAffine(poly, out var m));
|
||||||
|
|
||||||
|
AssertMaps(m, 0, 0, 10, 20);
|
||||||
|
AssertMaps(m, 4, 0, 18, 20);
|
||||||
|
AssertMaps(m, 4, 4, 18, 32);
|
||||||
|
AssertMaps(m, 0, 4, 10, 32);
|
||||||
|
AssertMaps(m, 2, 2, 14, 26);
|
||||||
|
}
|
||||||
|
|
||||||
|
[Fact]
|
||||||
|
public void TrySolveAffine_HandlesRotatedQuad()
|
||||||
|
{
|
||||||
|
var poly = Quad(
|
||||||
|
0, 0, 0, 10, -10, 10, -10, 0,
|
||||||
|
0, 0, 10, 0, 10, 10, 0, 10, 1);
|
||||||
|
|
||||||
|
Assert.True(DrawPolyMath.TrySolveAffine(poly, out var m));
|
||||||
|
|
||||||
|
AssertMaps(m, 0, 0, 0, 0);
|
||||||
|
AssertMaps(m, 10, 0, 0, 10);
|
||||||
|
AssertMaps(m, 0, 10, -10, 0);
|
||||||
|
}
|
||||||
|
|
||||||
|
[Fact]
|
||||||
|
public void TrySolveAffine_ReturnsFalse_OnDegenerateUv()
|
||||||
|
{
|
||||||
|
var poly = Quad(
|
||||||
|
0, 0, 10, 0, 10, 10, 0, 10,
|
||||||
|
0, 0, 0, 0, 0, 0, 0, 0, 1);
|
||||||
|
|
||||||
|
Assert.False(DrawPolyMath.TrySolveAffine(poly, out _));
|
||||||
|
}
|
||||||
|
|
||||||
|
private static void AssertMaps(Matrix3x2 m, float u, float v, float x, float y)
|
||||||
|
{
|
||||||
|
var p = Vector2.Transform(new Vector2(u, v), m);
|
||||||
|
Assert.Equal(x, p.X, 3);
|
||||||
|
Assert.Equal(y, p.Y, 3);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,172 @@
|
|||||||
|
using System;
|
||||||
|
using System.Collections.Generic;
|
||||||
|
using LuaScript.Engine;
|
||||||
|
using LuaScript.Engine.Kernel;
|
||||||
|
using MoonSharp.Interpreter;
|
||||||
|
|
||||||
|
namespace LuaScript.Tests
|
||||||
|
{
|
||||||
|
public sealed class KernelCpuEquivalenceTests
|
||||||
|
{
|
||||||
|
private const int Width = 23;
|
||||||
|
private const int Height = 17;
|
||||||
|
|
||||||
|
[Theory]
|
||||||
|
[InlineData("for y=0,obj.h-1 do for x=0,obj.w-1 do local r,g,b,a=obj.getpixel(x,y) obj.setpixel(x,y,r,g,b,a) end end")]
|
||||||
|
[InlineData("for y=0,obj.h-1 do for x=0,obj.w-1 do local r,g,b,a=obj.getpixel(x,y) local l=0.298912*r+0.586611*g+0.114478*b obj.setpixel(x,y,l,l,l,a) end end")]
|
||||||
|
[InlineData("for y=0,obj.h-1 do for x=0,obj.w-1 do local r,g,b,a=obj.getpixel(x,y) obj.setpixel(x,y,b,g,r,a) end end")]
|
||||||
|
[InlineData("for x=0,obj.w-1 do for y=0,obj.h-1 do local r,g,b,a=obj.getpixel(x,y) obj.setpixel(x,y,255-r,255-g,255-b,a) end end")]
|
||||||
|
[InlineData("for y=0,obj.h-1 do for x=0,obj.w-1 do local r,g,b,a=obj.getpixel(x,y) obj.setpixel(x,y,r*r/255,g*g/255,b*b/255,a) end end")]
|
||||||
|
[InlineData("for y=0,obj.h-1 do for x=0,obj.w-1 do local r,g,b,a=obj.getpixel(x,y) obj.setpixel(x,y,255*math.pow(r/255,0.45),255*math.pow(g/255,0.45),255*math.pow(b/255,0.45),a) end end")]
|
||||||
|
[InlineData("for y=0,obj.h-1 do for x=0,obj.w-1 do local r,g,b,a=obj.getpixel(x,y) local v=(r+g+b)/3 obj.setpixel(x,y,v>128 and 255 or 0,v>128 and 255 or 0,v>128 and 255 or 0,a) end end")]
|
||||||
|
[InlineData("for y=0,obj.h-1 do for x=0,obj.w-1 do local r,g,b,a=obj.getpixel(x,y) obj.setpixel(x,y,math.min(255,r+50),math.max(0,g-50),math.floor(b/16)*16,a) end end")]
|
||||||
|
[InlineData("for y=0,obj.h-1 do for x=0,obj.w-1 do local r,g,b,a=obj.getpixel(x,y) obj.setpixel(x,y,r%64,math.abs(g-128),math.sqrt(b*255),a) end end")]
|
||||||
|
public void CpuKernelMatchesMoonSharp(string script)
|
||||||
|
{
|
||||||
|
var fields = new Dictionary<string, double> { ["w"] = Width, ["h"] = Height };
|
||||||
|
AssertEquivalent(script, fields, new Dictionary<string, double>());
|
||||||
|
}
|
||||||
|
|
||||||
|
[Fact]
|
||||||
|
public void CpuKernelMatchesMoonSharpWithUniforms()
|
||||||
|
{
|
||||||
|
const string script =
|
||||||
|
"for y=0,obj.h-1 do for x=0,obj.w-1 do local r,g,b,a=obj.getpixel(x,y) " +
|
||||||
|
"obj.setpixel(x,y,r*obj.track0/100,g*math.sin(time)*0.5+g*0.5,b+x/obj.w*obj.track1,a) end end";
|
||||||
|
var fields = new Dictionary<string, double> { ["w"] = Width, ["h"] = Height, ["track0"] = 73d, ["track1"] = 40d };
|
||||||
|
var globals = new Dictionary<string, double> { ["time"] = 1.2345d };
|
||||||
|
AssertEquivalent(script, fields, globals);
|
||||||
|
}
|
||||||
|
|
||||||
|
[Theory]
|
||||||
|
[InlineData("--!cpu\nfor y=0,obj.h-1 do for x=0,obj.w-1 do local r,g,b,a=obj.getpixel(x,y) obj.setpixel(x,y,255-r,255-g,255-b,a) end end")]
|
||||||
|
[InlineData("--!gpu\nfor y=0,obj.h-1 do for x=0,obj.w-1 do local r,g,b,a=obj.getpixel(x,y) local l=0.298912*r+0.586611*g+0.114478*b obj.setpixel(x,y,l,l,l,a) end end")]
|
||||||
|
[InlineData("--!cpu\r\nfor y=0,obj.h-1 do for x=0,obj.w-1 do local r,g,b,a=obj.getpixel(x,y) obj.setpixel(x,y,x/obj.w*255,y/obj.h*255,b,a) end end")]
|
||||||
|
public void DirectivePrefixedKernelsMatchMoonSharp(string script)
|
||||||
|
{
|
||||||
|
var fields = new Dictionary<string, double> { ["w"] = Width, ["h"] = Height };
|
||||||
|
AssertEquivalent(script, fields, new Dictionary<string, double>());
|
||||||
|
}
|
||||||
|
|
||||||
|
[Theory]
|
||||||
|
[InlineData("--!cpu", "Cpu")]
|
||||||
|
[InlineData("--!gpu", "Gpu")]
|
||||||
|
public void DirectivePrefixedKernelsRouteToAcceleratedLane(string directive, string expected)
|
||||||
|
{
|
||||||
|
string script = directive + "\nfor y=0,obj.h-1 do for x=0,obj.w-1 do local r,g,b,a=obj.getpixel(x,y) obj.setpixel(x,y,r,g,b,a) end end";
|
||||||
|
|
||||||
|
Assert.True(ScriptDirective.TryResolveExplicit(script, out var kind));
|
||||||
|
Assert.Equal(expected, kind.ToString());
|
||||||
|
Assert.NotNull(KernelExtractor.TryExtract(script));
|
||||||
|
}
|
||||||
|
|
||||||
|
[Theory]
|
||||||
|
[InlineData("obj.setpixel(0,0,0,0,0,0)")]
|
||||||
|
[InlineData("for y=0,obj.h-1 do for x=0,obj.w-1 do local r,g,b,a=obj.getpixel(x,y) total=total+r obj.setpixel(x,y,r,g,b,a) end end")]
|
||||||
|
[InlineData("for y=0,obj.h-1 do for x=0,obj.w-1 do local r,g,b,a=obj.getpixel(x+1,y) obj.setpixel(x,y,r,g,b,a) end end")]
|
||||||
|
[InlineData("for i=0,10 do end")]
|
||||||
|
[InlineData("for y=0,obj.h-1 do for x=0,obj.w-1 do local r,g,b,a=obj.getpixel(x,y) if r>128 then r=255 end obj.setpixel(x,y,r,g,b,a) end end")]
|
||||||
|
[InlineData("for y=0,obj.h-1 do for x=0,obj.w-1 do local r,g,b,a=obj.getpixel(x,y) obj.setpixel(x,y,obj.rand(0,255),g,b,a) end end")]
|
||||||
|
public void NonKernelScriptsAreRejected(string script)
|
||||||
|
{
|
||||||
|
Assert.Null(KernelExtractor.TryExtract(script));
|
||||||
|
}
|
||||||
|
|
||||||
|
private static void AssertEquivalent(string script, Dictionary<string, double> fields, Dictionary<string, double> globals)
|
||||||
|
{
|
||||||
|
var program = KernelExtractor.TryExtract(script);
|
||||||
|
Assert.NotNull(program);
|
||||||
|
|
||||||
|
byte[] source = CreateBuffer(20260629);
|
||||||
|
byte[] oracle = (byte[])source.Clone();
|
||||||
|
byte[] candidate = (byte[])source.Clone();
|
||||||
|
|
||||||
|
RunMoonSharp(script, oracle, fields, globals);
|
||||||
|
|
||||||
|
double[] uniforms = new double[KernelUniforms.Count];
|
||||||
|
foreach (var (name, value) in fields)
|
||||||
|
if (KernelUniforms.TryResolveMember("obj", name, out var uniform))
|
||||||
|
uniforms[(int)uniform] = value;
|
||||||
|
foreach (var (name, value) in globals)
|
||||||
|
if (KernelUniforms.TryResolveGlobal(name, out var uniform))
|
||||||
|
uniforms[(int)uniform] = value;
|
||||||
|
|
||||||
|
CpuKernelCompiler.Compile(program!).Execute(candidate, Width, Height, uniforms);
|
||||||
|
|
||||||
|
Assert.Equal(oracle, candidate);
|
||||||
|
}
|
||||||
|
|
||||||
|
private static byte[] CreateBuffer(int seed)
|
||||||
|
{
|
||||||
|
var random = new Random(seed);
|
||||||
|
var buffer = new byte[Width * Height * 4];
|
||||||
|
random.NextBytes(buffer);
|
||||||
|
return buffer;
|
||||||
|
}
|
||||||
|
|
||||||
|
private static void RunMoonSharp(string script, byte[] buffer, Dictionary<string, double> fields, Dictionary<string, double> globals)
|
||||||
|
{
|
||||||
|
var engine = new Script(CoreModules.Basic | CoreModules.Math | CoreModules.Bit32);
|
||||||
|
var obj = new Table(engine);
|
||||||
|
foreach (var (name, value) in fields)
|
||||||
|
obj[name] = value;
|
||||||
|
foreach (var (name, value) in globals)
|
||||||
|
engine.Globals[name] = value;
|
||||||
|
|
||||||
|
obj["getpixel"] = DynValue.NewCallback((_, args) =>
|
||||||
|
{
|
||||||
|
int x = (int)(args[0].CastToNumber() ?? 0d);
|
||||||
|
int y = (int)(args[1].CastToNumber() ?? 0d);
|
||||||
|
var (r, g, b, a) = GetPixel(buffer, x, y);
|
||||||
|
return DynValue.NewTuple(
|
||||||
|
DynValue.NewNumber(r), DynValue.NewNumber(g), DynValue.NewNumber(b), DynValue.NewNumber(a));
|
||||||
|
});
|
||||||
|
|
||||||
|
obj["setpixel"] = DynValue.NewCallback((_, args) =>
|
||||||
|
{
|
||||||
|
int x = (int)(args[0].CastToNumber() ?? 0d);
|
||||||
|
int y = (int)(args[1].CastToNumber() ?? 0d);
|
||||||
|
double r = args[2].CastToNumber() ?? 0d;
|
||||||
|
double g = args[3].CastToNumber() ?? 0d;
|
||||||
|
double b = args[4].CastToNumber() ?? 0d;
|
||||||
|
double a = args.Count > 5 ? args[5].CastToNumber() ?? 255d : 255d;
|
||||||
|
SetPixel(buffer, x, y, r, g, b, a);
|
||||||
|
return DynValue.Void;
|
||||||
|
});
|
||||||
|
|
||||||
|
engine.Globals["obj"] = obj;
|
||||||
|
engine.DoString(script);
|
||||||
|
}
|
||||||
|
|
||||||
|
private static (double r, double g, double b, double a) GetPixel(byte[] buffer, int x, int y)
|
||||||
|
{
|
||||||
|
if ((uint)x >= Width || (uint)y >= Height)
|
||||||
|
return (0d, 0d, 0d, 0d);
|
||||||
|
|
||||||
|
int p = (y * Width + x) * 4;
|
||||||
|
double alpha = buffer[p + 3];
|
||||||
|
if (alpha <= 0d)
|
||||||
|
return (0d, 0d, 0d, 0d);
|
||||||
|
|
||||||
|
double scale = 255d / alpha;
|
||||||
|
return (
|
||||||
|
Math.Clamp(buffer[p + 2] * scale, 0d, 255d),
|
||||||
|
Math.Clamp(buffer[p + 1] * scale, 0d, 255d),
|
||||||
|
Math.Clamp(buffer[p] * scale, 0d, 255d),
|
||||||
|
alpha);
|
||||||
|
}
|
||||||
|
|
||||||
|
private static void SetPixel(byte[] buffer, int x, int y, double r, double g, double b, double a)
|
||||||
|
{
|
||||||
|
if ((uint)x >= Width || (uint)y >= Height)
|
||||||
|
return;
|
||||||
|
|
||||||
|
int p = (y * Width + x) * 4;
|
||||||
|
double k = Math.Clamp(a, 0d, 255d) / 255d;
|
||||||
|
buffer[p] = (byte)Math.Clamp(b * k, 0d, 255d);
|
||||||
|
buffer[p + 1] = (byte)Math.Clamp(g * k, 0d, 255d);
|
||||||
|
buffer[p + 2] = (byte)Math.Clamp(r * k, 0d, 255d);
|
||||||
|
buffer[p + 3] = (byte)Math.Clamp(a, 0d, 255d);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,64 @@
|
|||||||
|
using LuaScript.Engine.Kernel;
|
||||||
|
|
||||||
|
namespace LuaScript.Tests
|
||||||
|
{
|
||||||
|
public sealed class KernelHlslEmitterTests
|
||||||
|
{
|
||||||
|
private const string Grayscale =
|
||||||
|
"for y=0,obj.h-1 do for x=0,obj.w-1 do local r,g,b,a=obj.getpixel(x,y) " +
|
||||||
|
"local l=0.298912*r+0.586611*g+0.114478*b obj.setpixel(x,y,l,l,l,a) end end";
|
||||||
|
|
||||||
|
private const string Threshold =
|
||||||
|
"for y=0,obj.h-1 do for x=0,obj.w-1 do local r,g,b,a=obj.getpixel(x,y) " +
|
||||||
|
"obj.setpixel(x,y,r>128 and 255 or 0,g,b,a) end end";
|
||||||
|
|
||||||
|
private const string WithTrack =
|
||||||
|
"for y=0,obj.h-1 do for x=0,obj.w-1 do local r,g,b,a=obj.getpixel(x,y) " +
|
||||||
|
"obj.setpixel(x,y,r*obj.track0/100,g,b,a) end end";
|
||||||
|
|
||||||
|
[Fact]
|
||||||
|
public void EmitsValidShaderSkeleton()
|
||||||
|
{
|
||||||
|
string hlsl = HlslKernelEmitter.Emit(Extract(Grayscale));
|
||||||
|
|
||||||
|
Assert.Contains("Texture2D InputTexture : register(t0);", hlsl);
|
||||||
|
Assert.Contains("cbuffer constants : register(b0)", hlsl);
|
||||||
|
Assert.Contains("float4 main(float4 pos : SV_POSITION", hlsl);
|
||||||
|
Assert.Contains("InputTexture.Sample(InputSampler, uv.xy)", hlsl);
|
||||||
|
Assert.Contains("return float4(oR, oG, oB, oA);", hlsl);
|
||||||
|
Assert.Contains("inR", hlsl);
|
||||||
|
Assert.Contains("inG", hlsl);
|
||||||
|
Assert.Contains("inB", hlsl);
|
||||||
|
}
|
||||||
|
|
||||||
|
[Fact]
|
||||||
|
public void ThresholdEmitsTernary()
|
||||||
|
{
|
||||||
|
string hlsl = HlslKernelEmitter.Emit(Extract(Threshold));
|
||||||
|
Assert.Contains(" ? (", hlsl);
|
||||||
|
Assert.Contains(" > ", hlsl);
|
||||||
|
}
|
||||||
|
|
||||||
|
[Fact]
|
||||||
|
public void UniformReferencesUsePackedConstantBuffer()
|
||||||
|
{
|
||||||
|
string hlsl = HlslKernelEmitter.Emit(Extract(WithTrack));
|
||||||
|
int index = (int)KernelUniform.Track0;
|
||||||
|
Assert.Contains($"uniforms[{index / 4}].{"xyzw"[index % 4]}", hlsl);
|
||||||
|
}
|
||||||
|
|
||||||
|
[Fact]
|
||||||
|
public void EmissionIsDeterministic()
|
||||||
|
{
|
||||||
|
var program = Extract(Grayscale);
|
||||||
|
Assert.Equal(HlslKernelEmitter.Emit(program), HlslKernelEmitter.Emit(program));
|
||||||
|
}
|
||||||
|
|
||||||
|
private static KernelProgram Extract(string script)
|
||||||
|
{
|
||||||
|
var program = KernelExtractor.TryExtract(script);
|
||||||
|
Assert.NotNull(program);
|
||||||
|
return program!;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -27,15 +27,36 @@
|
|||||||
<Compile Include="..\LuaScript\Compat\MoonSharpBit32.cs" Link="Linked\MoonSharpBit32.cs" />
|
<Compile Include="..\LuaScript\Compat\MoonSharpBit32.cs" Link="Linked\MoonSharpBit32.cs" />
|
||||||
<Compile Include="..\LuaScript\Compat\Bit32.cs" Link="Linked\Bit32.cs" />
|
<Compile Include="..\LuaScript\Compat\Bit32.cs" Link="Linked\Bit32.cs" />
|
||||||
<Compile Include="..\LuaScript\Engine\ScriptEngineKind.cs" Link="Linked\ScriptEngineKind.cs" />
|
<Compile Include="..\LuaScript\Engine\ScriptEngineKind.cs" Link="Linked\ScriptEngineKind.cs" />
|
||||||
|
<Compile Include="..\LuaScript\Engine\ScriptDirective.cs" Link="Linked\ScriptDirective.cs" />
|
||||||
<Compile Include="..\LuaScript\Engine\NativeProtocol.cs" Link="Linked\NativeProtocol.cs" />
|
<Compile Include="..\LuaScript\Engine\NativeProtocol.cs" Link="Linked\NativeProtocol.cs" />
|
||||||
<Compile Include="..\LuaScript\Engine\ProcessJobObject.cs" Link="Linked\ProcessJobObject.cs" />
|
<Compile Include="..\LuaScript\Engine\ProcessJobObject.cs" Link="Linked\ProcessJobObject.cs" />
|
||||||
<Compile Include="..\LuaScript\Engine\LuaJitWorker.cs" Link="Linked\LuaJitWorker.cs" />
|
<Compile Include="..\LuaScript\Engine\LuaJitWorker.cs" Link="Linked\LuaJitWorker.cs" />
|
||||||
|
<Compile Include="..\LuaScript\DrawCommand.cs" Link="Linked\DrawCommand.cs" />
|
||||||
|
<Compile Include="..\LuaScript\DrawPolyMath.cs" Link="Linked\DrawPolyMath.cs" />
|
||||||
<Compile Include="..\LuaScript\SceneObjectInfo.cs" Link="Linked\SceneObjectInfo.cs" />
|
<Compile Include="..\LuaScript\SceneObjectInfo.cs" Link="Linked\SceneObjectInfo.cs" />
|
||||||
|
<Compile Include="..\LuaScript\SceneObjectQuery.cs" Link="Linked\SceneObjectQuery.cs" />
|
||||||
<Compile Include="..\LuaScript\AnimTableRegistrar.cs" Link="Linked\AnimTableRegistrar.cs" />
|
<Compile Include="..\LuaScript\AnimTableRegistrar.cs" Link="Linked\AnimTableRegistrar.cs" />
|
||||||
<Compile Include="..\LuaScript\Compat\AviUtlScript.cs" Link="Linked\AviUtlScript.cs" />
|
<Compile Include="..\LuaScript\Compat\AviUtlScript.cs" Link="Linked\AviUtlScript.cs" />
|
||||||
|
<Compile Include="..\LuaScript\Compat\ScriptParserHelper.cs" Link="Linked\ScriptParserHelper.cs" />
|
||||||
<Compile Include="..\LuaScript\Compat\AviUtlParameterLayout.cs" Link="Linked\AviUtlParameterLayout.cs" />
|
<Compile Include="..\LuaScript\Compat\AviUtlParameterLayout.cs" Link="Linked\AviUtlParameterLayout.cs" />
|
||||||
|
<Compile Include="..\LuaScript\Compat\ScriptParameterUsage.cs" Link="Linked\ScriptParameterUsage.cs" />
|
||||||
<Compile Include="..\LuaScript\Compat\AviUtlRandom.cs" Link="Linked\AviUtlRandom.cs" />
|
<Compile Include="..\LuaScript\Compat\AviUtlRandom.cs" Link="Linked\AviUtlRandom.cs" />
|
||||||
|
<Compile Include="..\LuaScript\Compat\AviUtlEngine.cs" Link="Linked\AviUtlEngine.cs" />
|
||||||
|
<Compile Include="..\LuaScript\Compat\AviUtlEffectMapping.cs" Link="Linked\AviUtlEffectMapping.cs" />
|
||||||
|
<Compile Include="..\LuaScript\Compat\AviUtlCompatMap.cs" Link="Linked\AviUtlCompatMap.cs" />
|
||||||
|
<EmbeddedResource Include="..\LuaScript\Compat\AviUtlCompatMap.xml" Link="Linked\AviUtlCompatMap.xml" />
|
||||||
<Compile Include="..\LuaScript\Compat\FigureRenderer.cs" Link="Linked\FigureRenderer.cs" />
|
<Compile Include="..\LuaScript\Compat\FigureRenderer.cs" Link="Linked\FigureRenderer.cs" />
|
||||||
|
<Compile Include="..\LuaScript\Engine\Kernel\KernelUnsupportedException.cs" Link="Linked\Kernel\KernelUnsupportedException.cs" />
|
||||||
|
<Compile Include="..\LuaScript\Engine\Kernel\LuaToken.cs" Link="Linked\Kernel\LuaToken.cs" />
|
||||||
|
<Compile Include="..\LuaScript\Engine\Kernel\LuaLexer.cs" Link="Linked\Kernel\LuaLexer.cs" />
|
||||||
|
<Compile Include="..\LuaScript\Engine\Kernel\LuaAst.cs" Link="Linked\Kernel\LuaAst.cs" />
|
||||||
|
<Compile Include="..\LuaScript\Engine\Kernel\LuaParser.cs" Link="Linked\Kernel\LuaParser.cs" />
|
||||||
|
<Compile Include="..\LuaScript\Engine\Kernel\KernelUniform.cs" Link="Linked\Kernel\KernelUniform.cs" />
|
||||||
|
<Compile Include="..\LuaScript\Engine\Kernel\KernelModel.cs" Link="Linked\Kernel\KernelModel.cs" />
|
||||||
|
<Compile Include="..\LuaScript\Engine\Kernel\KernelExtractor.cs" Link="Linked\Kernel\KernelExtractor.cs" />
|
||||||
|
<Compile Include="..\LuaScript\Engine\Kernel\CpuKernel.cs" Link="Linked\Kernel\CpuKernel.cs" />
|
||||||
|
<Compile Include="..\LuaScript\Engine\Kernel\CpuKernelCompiler.cs" Link="Linked\Kernel\CpuKernelCompiler.cs" />
|
||||||
|
<Compile Include="..\LuaScript\Engine\Kernel\HlslKernelEmitter.cs" Link="Linked\Kernel\HlslKernelEmitter.cs" />
|
||||||
</ItemGroup>
|
</ItemGroup>
|
||||||
|
|
||||||
</Project>
|
</Project>
|
||||||
@@ -9,6 +9,13 @@ namespace LuaScript.Tests
|
|||||||
private static string NativeDir => Path.Combine(AppContext.BaseDirectory, "native");
|
private static string NativeDir => Path.Combine(AppContext.BaseDirectory, "native");
|
||||||
|
|
||||||
private static readonly Func<string, int, SceneObjectInfo?> NoResolver = (_, _) => null;
|
private static readonly Func<string, int, SceneObjectInfo?> NoResolver = (_, _) => null;
|
||||||
|
private static readonly Func<string, int, double, double, double, (byte[] buffer, int w, int h)> NoLoadFigure = (_, _, _, _, _) => ([], 1, 1);
|
||||||
|
private static readonly Func<string, string, double, bool, bool, int, (byte[] buffer, int w, int h)> NoLoadText = (_, _, _, _, _, _) => ([], 1, 1);
|
||||||
|
private static readonly Func<string, (byte[] buffer, int w, int h)> NoLoadImage = _ => ([], 1, 1);
|
||||||
|
private static readonly Func<string, double, (byte[] buffer, int w, int h)> NoLoadMovie = (_, _) => ([], 1, 1);
|
||||||
|
private static readonly Action<string, System.Collections.Generic.IReadOnlyList<System.Collections.Generic.KeyValuePair<string, object>>> NoAddEffect = (_, _) => { };
|
||||||
|
private static readonly Action<DrawCommand> NoAddDraw = _ => { };
|
||||||
|
private static readonly System.Collections.Generic.IReadOnlyDictionary<string, string> NoStringParams = new System.Collections.Generic.Dictionary<string, string>();
|
||||||
|
|
||||||
private readonly LuaJitWorker _worker = new(NativeDir);
|
private readonly LuaJitWorker _worker = new(NativeDir);
|
||||||
|
|
||||||
@@ -34,7 +41,7 @@ namespace LuaScript.Tests
|
|||||||
|
|
||||||
bool ok = _worker.Execute(
|
bool ok = _worker.Execute(
|
||||||
"obj.rz = obj.time * 90\nobj.alpha = 128",
|
"obj.rz = obj.time * 90\nobj.alpha = 128",
|
||||||
fields, pixels, 4, 4, 5000, NoResolver, out bool dirty, out string? error);
|
fields, NoStringParams, pixels, 4, 4, 5000, NoResolver, NoLoadFigure, NoLoadText, NoLoadImage, NoLoadMovie, NoAddEffect, NoAddDraw, out bool dirty, out _, out _, out _, out _, out string? error);
|
||||||
|
|
||||||
Assert.True(ok, error);
|
Assert.True(ok, error);
|
||||||
Assert.False(dirty);
|
Assert.False(dirty);
|
||||||
@@ -42,6 +49,53 @@ namespace LuaScript.Tests
|
|||||||
Assert.Equal(128d, fields[NativeProtocol.Alpha]);
|
Assert.Equal(128d, fields[NativeProtocol.Alpha]);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
[Fact]
|
||||||
|
public void StringParameters_AreExposedOnObj()
|
||||||
|
{
|
||||||
|
Assert.True(LuaJitWorker.IsAvailable(NativeDir), "native/luajit.exe must be present");
|
||||||
|
|
||||||
|
var fields = Fields(2, 2, 0d);
|
||||||
|
var pixels = new byte[16];
|
||||||
|
var stringParameters = new System.Collections.Generic.Dictionary<string, string>
|
||||||
|
{
|
||||||
|
["text"] = "hello",
|
||||||
|
["file_image"] = "C:/サンプル/画像.png",
|
||||||
|
};
|
||||||
|
|
||||||
|
bool ok = _worker.Execute(
|
||||||
|
"obj.x = string.len(obj.text) obj.alpha = string.len(obj.file_image)",
|
||||||
|
fields, stringParameters, pixels, 2, 2, 5000, NoResolver, NoLoadFigure, NoLoadText, NoLoadImage, NoLoadMovie, NoAddEffect, NoAddDraw, out _, out _, out _, out _, out _, out string? error);
|
||||||
|
|
||||||
|
Assert.True(ok, error);
|
||||||
|
Assert.Equal(5d, fields[NativeProtocol.X]);
|
||||||
|
Assert.Equal(System.Text.Encoding.UTF8.GetByteCount("C:/サンプル/画像.png"), fields[NativeProtocol.Alpha]);
|
||||||
|
}
|
||||||
|
|
||||||
|
[Fact]
|
||||||
|
public void StringParameters_GrowAndShrinkAroundCapacity()
|
||||||
|
{
|
||||||
|
Assert.True(LuaJitWorker.IsAvailable(NativeDir), "native/luajit.exe must be present");
|
||||||
|
|
||||||
|
var pixels = new byte[16];
|
||||||
|
string big = new string('x', 100 * 1024);
|
||||||
|
|
||||||
|
var large = new System.Collections.Generic.Dictionary<string, string> { ["text"] = big };
|
||||||
|
var fieldsLarge = Fields(2, 2, 0d);
|
||||||
|
bool ok = _worker.Execute(
|
||||||
|
"obj.x = string.len(obj.text)",
|
||||||
|
fieldsLarge, large, pixels, 2, 2, 5000, NoResolver, NoLoadFigure, NoLoadText, NoLoadImage, NoLoadMovie, NoAddEffect, NoAddDraw, out _, out _, out _, out _, out _, out string? error);
|
||||||
|
Assert.True(ok, error);
|
||||||
|
Assert.Equal(big.Length, fieldsLarge[NativeProtocol.X]);
|
||||||
|
|
||||||
|
var small = new System.Collections.Generic.Dictionary<string, string> { ["text"] = "ok" };
|
||||||
|
var fieldsSmall = Fields(2, 2, 0d);
|
||||||
|
ok = _worker.Execute(
|
||||||
|
"obj.x = string.len(obj.text)",
|
||||||
|
fieldsSmall, small, pixels, 2, 2, 5000, NoResolver, NoLoadFigure, NoLoadText, NoLoadImage, NoLoadMovie, NoAddEffect, NoAddDraw, out _, out _, out _, out _, out _, out error);
|
||||||
|
Assert.True(ok, error);
|
||||||
|
Assert.Equal(2d, fieldsSmall[NativeProtocol.X]);
|
||||||
|
}
|
||||||
|
|
||||||
[Fact]
|
[Fact]
|
||||||
public void PixelScript_MatchesExpectedGrayscale()
|
public void PixelScript_MatchesExpectedGrayscale()
|
||||||
{
|
{
|
||||||
@@ -69,7 +123,7 @@ namespace LuaScript.Tests
|
|||||||
"local gray = r*0.299 + g*0.587 + b*0.114 " +
|
"local gray = r*0.299 + g*0.587 + b*0.114 " +
|
||||||
"obj.setpixel(x,y,gray,gray,gray,a) end end";
|
"obj.setpixel(x,y,gray,gray,gray,a) end end";
|
||||||
|
|
||||||
bool ok = _worker.Execute(script, fields, pixels, w, h, 5000, NoResolver, out bool dirty, out string? error);
|
bool ok = _worker.Execute(script, fields, NoStringParams, pixels, w, h, 5000, NoResolver, NoLoadFigure, NoLoadText, NoLoadImage, NoLoadMovie, NoAddEffect, NoAddDraw, out bool dirty, out _, out _, out _, out _, out string? error);
|
||||||
|
|
||||||
Assert.True(ok, error);
|
Assert.True(ok, error);
|
||||||
Assert.True(dirty);
|
Assert.True(dirty);
|
||||||
@@ -104,7 +158,7 @@ namespace LuaScript.Tests
|
|||||||
"local gray=r*0.299+g*0.587+b*0.114 " +
|
"local gray=r*0.299+g*0.587+b*0.114 " +
|
||||||
"pd:set(base+1,gray) pd:set(base+2,gray) pd:set(base+3,gray) end end";
|
"pd:set(base+1,gray) pd:set(base+2,gray) pd:set(base+3,gray) end end";
|
||||||
|
|
||||||
bool ok = _worker.Execute(script, fields, pixels, w, h, 5000, NoResolver, out bool dirty, out string? error);
|
bool ok = _worker.Execute(script, fields, NoStringParams, pixels, w, h, 5000, NoResolver, NoLoadFigure, NoLoadText, NoLoadImage, NoLoadMovie, NoAddEffect, NoAddDraw, out bool dirty, out _, out _, out _, out _, out string? error);
|
||||||
|
|
||||||
Assert.True(ok, error);
|
Assert.True(ok, error);
|
||||||
Assert.True(dirty);
|
Assert.True(dirty);
|
||||||
@@ -140,7 +194,7 @@ namespace LuaScript.Tests
|
|||||||
for (int k = 1; k <= 5; k++)
|
for (int k = 1; k <= 5; k++)
|
||||||
{
|
{
|
||||||
var fields = Fields(2, 2, k);
|
var fields = Fields(2, 2, k);
|
||||||
bool ok = _worker.Execute("obj.x = obj.time * 10", fields, pixels, 2, 2, 5000, NoResolver, out _, out string? error);
|
bool ok = _worker.Execute("obj.x = obj.time * 10", fields, NoStringParams, pixels, 2, 2, 5000, NoResolver, NoLoadFigure, NoLoadText, NoLoadImage, NoLoadMovie, NoAddEffect, NoAddDraw, out _, out _, out _, out _, out _, out string? error);
|
||||||
Assert.True(ok, error);
|
Assert.True(ok, error);
|
||||||
Assert.Equal(k * 10d, fields[NativeProtocol.X]);
|
Assert.Equal(k * 10d, fields[NativeProtocol.X]);
|
||||||
}
|
}
|
||||||
@@ -155,12 +209,12 @@ namespace LuaScript.Tests
|
|||||||
var fields = Fields(2, 2, 0d);
|
var fields = Fields(2, 2, 0d);
|
||||||
|
|
||||||
bool timedOut = _worker.Execute(
|
bool timedOut = _worker.Execute(
|
||||||
"local x=0 while true do x=x+1 end", fields, pixels, 2, 2, 1500, NoResolver, out _, out string? error);
|
"local x=0 while true do x=x+1 end", fields, NoStringParams, pixels, 2, 2, 1500, NoResolver, NoLoadFigure, NoLoadText, NoLoadImage, NoLoadMovie, NoAddEffect, NoAddDraw, out _, out _, out _, out _, out _, out string? error);
|
||||||
Assert.False(timedOut);
|
Assert.False(timedOut);
|
||||||
Assert.Contains("timed out", error);
|
Assert.Contains("timed out", error);
|
||||||
|
|
||||||
var fields2 = Fields(2, 2, 3d);
|
var fields2 = Fields(2, 2, 3d);
|
||||||
bool ok = _worker.Execute("obj.x = obj.time", fields2, pixels, 2, 2, 5000, NoResolver, out _, out error);
|
bool ok = _worker.Execute("obj.x = obj.time", fields2, NoStringParams, pixels, 2, 2, 5000, NoResolver, NoLoadFigure, NoLoadText, NoLoadImage, NoLoadMovie, NoAddEffect, NoAddDraw, out _, out _, out _, out _, out _, out error);
|
||||||
Assert.True(ok, error);
|
Assert.True(ok, error);
|
||||||
Assert.Equal(3d, fields2[NativeProtocol.X]);
|
Assert.Equal(3d, fields2[NativeProtocol.X]);
|
||||||
}
|
}
|
||||||
@@ -182,7 +236,7 @@ namespace LuaScript.Tests
|
|||||||
"obj.zoom = o.zoom obj.rz = o.rz obj.alpha = o.alpha " +
|
"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";
|
||||||
|
|
||||||
bool ok = _worker.Execute(script, fields, pixels, 2, 2, 5000, resolver, out _, out string? error);
|
bool ok = _worker.Execute(script, fields, NoStringParams, pixels, 2, 2, 5000, resolver, NoLoadFigure, NoLoadText, NoLoadImage, NoLoadMovie, NoAddEffect, NoAddDraw, out _, out _, out _, out _, out _, out string? error);
|
||||||
|
|
||||||
Assert.True(ok, error);
|
Assert.True(ok, error);
|
||||||
Assert.Equal(12d, fields[NativeProtocol.X]);
|
Assert.Equal(12d, fields[NativeProtocol.X]);
|
||||||
@@ -214,13 +268,13 @@ namespace LuaScript.Tests
|
|||||||
"local b = obj.getobject(\"a\") " +
|
"local b = obj.getobject(\"a\") " +
|
||||||
"obj.x = a.x + b.x";
|
"obj.x = a.x + b.x";
|
||||||
|
|
||||||
bool ok = _worker.Execute(script, Fields(2, 2, 0d), pixels, 2, 2, 5000, resolver, out _, out string? error);
|
bool ok = _worker.Execute(script, Fields(2, 2, 0d), NoStringParams, pixels, 2, 2, 5000, resolver, NoLoadFigure, NoLoadText, NoLoadImage, NoLoadMovie, NoAddEffect, NoAddDraw, out _, out _, out _, out _, out _, out string? error);
|
||||||
Assert.True(ok, error);
|
Assert.True(ok, error);
|
||||||
Assert.Equal(1, calls);
|
Assert.Equal(1, calls);
|
||||||
var fields = Fields(2, 2, 0d);
|
var fields = Fields(2, 2, 0d);
|
||||||
|
|
||||||
x = 20d;
|
x = 20d;
|
||||||
ok = _worker.Execute(script, fields, pixels, 2, 2, 5000, resolver, out _, out error);
|
ok = _worker.Execute(script, fields, NoStringParams, pixels, 2, 2, 5000, resolver, NoLoadFigure, NoLoadText, NoLoadImage, NoLoadMovie, NoAddEffect, NoAddDraw, out _, out _, out _, out _, out _, out error);
|
||||||
Assert.True(ok, error);
|
Assert.True(ok, error);
|
||||||
Assert.Equal(2, calls);
|
Assert.Equal(2, calls);
|
||||||
Assert.Equal(40d, fields[NativeProtocol.X]);
|
Assert.Equal(40d, fields[NativeProtocol.X]);
|
||||||
@@ -237,12 +291,302 @@ namespace LuaScript.Tests
|
|||||||
const string script =
|
const string script =
|
||||||
"local o = obj.getobject(\"missing\") obj.x = o == nil and 1 or 0";
|
"local o = obj.getobject(\"missing\") obj.x = o == nil and 1 or 0";
|
||||||
|
|
||||||
bool ok = _worker.Execute(script, fields, pixels, 2, 2, 5000, NoResolver, out _, out string? error);
|
bool ok = _worker.Execute(script, fields, NoStringParams, pixels, 2, 2, 5000, NoResolver, NoLoadFigure, NoLoadText, NoLoadImage, NoLoadMovie, NoAddEffect, NoAddDraw, out _, out _, out _, out _, out _, out string? error);
|
||||||
|
|
||||||
Assert.True(ok, error);
|
Assert.True(ok, error);
|
||||||
Assert.Equal(1d, fields[NativeProtocol.X]);
|
Assert.Equal(1d, fields[NativeProtocol.X]);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
[Fact]
|
||||||
|
public void Draw_RecordsCommandsThroughCallback()
|
||||||
|
{
|
||||||
|
Assert.True(LuaJitWorker.IsAvailable(NativeDir), "native/luajit.exe must be present");
|
||||||
|
|
||||||
|
var pixels = new byte[16];
|
||||||
|
var fields = Fields(2, 2, 0d);
|
||||||
|
var commands = new System.Collections.Generic.List<DrawCommand>();
|
||||||
|
Action<DrawCommand> addDraw = commands.Add;
|
||||||
|
|
||||||
|
bool ok = _worker.Execute(
|
||||||
|
"obj.draw() obj.draw(10, 20, 30, 2, 0.5, 0.25)",
|
||||||
|
fields, NoStringParams, pixels, 2, 2, 5000, NoResolver, NoLoadFigure, NoLoadText, NoLoadImage, NoLoadMovie, NoAddEffect, addDraw,
|
||||||
|
out _, out _, out _, out _, out _, out string? error);
|
||||||
|
|
||||||
|
Assert.True(ok, error);
|
||||||
|
Assert.Equal(2, commands.Count);
|
||||||
|
Assert.Equal(new DrawCommand(0d, 0d, 0d, 1d, 1d, 0d), commands[0]);
|
||||||
|
Assert.Equal(new DrawCommand(10d, 20d, 30d, 2d, 0.5d, 0.25d), commands[1]);
|
||||||
|
}
|
||||||
|
|
||||||
|
[Fact]
|
||||||
|
public void DrawPoly_RecordsDefaultUvAndAlpha()
|
||||||
|
{
|
||||||
|
Assert.True(LuaJitWorker.IsAvailable(NativeDir), "native/luajit.exe must be present");
|
||||||
|
|
||||||
|
var pixels = new byte[4 * 4 * 4];
|
||||||
|
var fields = Fields(4, 4, 0d);
|
||||||
|
var commands = new System.Collections.Generic.List<DrawCommand>();
|
||||||
|
Action<DrawCommand> addDraw = commands.Add;
|
||||||
|
|
||||||
|
bool ok = _worker.Execute(
|
||||||
|
"obj.drawpoly(0,0,0, 10,0,0, 10,10,0, 0,10,0)",
|
||||||
|
fields, NoStringParams, pixels, 4, 4, 5000, NoResolver, NoLoadFigure, NoLoadText, NoLoadImage, NoLoadMovie, NoAddEffect, addDraw,
|
||||||
|
out _, out _, out _, out _, out _, out string? error);
|
||||||
|
|
||||||
|
Assert.True(ok, error);
|
||||||
|
Assert.Single(commands);
|
||||||
|
var poly = commands[0].Poly;
|
||||||
|
Assert.NotNull(poly);
|
||||||
|
Assert.Equal(new double[] { 0, 0, 0, 10, 0, 0, 10, 10, 0, 0, 10, 0, 0, 0, 4, 0, 4, 4, 0, 4, 1 }, poly);
|
||||||
|
}
|
||||||
|
|
||||||
|
[Fact]
|
||||||
|
public void DrawPoly_RecordsExplicitUvAndAlpha()
|
||||||
|
{
|
||||||
|
Assert.True(LuaJitWorker.IsAvailable(NativeDir), "native/luajit.exe must be present");
|
||||||
|
|
||||||
|
var pixels = new byte[4 * 4 * 4];
|
||||||
|
var fields = Fields(4, 4, 0d);
|
||||||
|
var commands = new System.Collections.Generic.List<DrawCommand>();
|
||||||
|
Action<DrawCommand> addDraw = commands.Add;
|
||||||
|
|
||||||
|
bool ok = _worker.Execute(
|
||||||
|
"obj.drawpoly(0,0,0, 8,0,0, 8,8,0, 0,8,0, 1,1, 3,1, 3,3, 1,3, 0.5)",
|
||||||
|
fields, NoStringParams, pixels, 4, 4, 5000, NoResolver, NoLoadFigure, NoLoadText, NoLoadImage, NoLoadMovie, NoAddEffect, addDraw,
|
||||||
|
out _, out _, out _, out _, out _, out string? error);
|
||||||
|
|
||||||
|
Assert.True(ok, error);
|
||||||
|
Assert.Single(commands);
|
||||||
|
var poly = commands[0].Poly;
|
||||||
|
Assert.NotNull(poly);
|
||||||
|
Assert.Equal(new double[] { 0, 0, 0, 8, 0, 0, 8, 8, 0, 0, 8, 0, 1, 1, 3, 1, 3, 3, 1, 3, 0.5 }, poly);
|
||||||
|
Assert.Equal(0.5d, commands[0].Alpha);
|
||||||
|
}
|
||||||
|
|
||||||
|
[Fact]
|
||||||
|
public void SetOption_GetOption_RoundTrips()
|
||||||
|
{
|
||||||
|
Assert.True(LuaJitWorker.IsAvailable(NativeDir), "native/luajit.exe must be present");
|
||||||
|
|
||||||
|
var pixels = new byte[16];
|
||||||
|
var fields = Fields(2, 2, 0d);
|
||||||
|
|
||||||
|
bool ok = _worker.Execute(
|
||||||
|
"obj.setoption('antialias', 0) obj.x = obj.getoption('antialias') obj.y = obj.getoption('unset')",
|
||||||
|
fields, NoStringParams, pixels, 2, 2, 5000, NoResolver, NoLoadFigure, NoLoadText, NoLoadImage, NoLoadMovie, NoAddEffect, NoAddDraw,
|
||||||
|
out _, out _, out _, out _, out _, out string? error);
|
||||||
|
|
||||||
|
Assert.True(ok, error);
|
||||||
|
Assert.Equal(0d, fields[NativeProtocol.X]);
|
||||||
|
Assert.Equal(0d, fields[NativeProtocol.Y]);
|
||||||
|
}
|
||||||
|
|
||||||
|
[Fact]
|
||||||
|
public void Draw_CarriesAntialiasFromOption()
|
||||||
|
{
|
||||||
|
Assert.True(LuaJitWorker.IsAvailable(NativeDir), "native/luajit.exe must be present");
|
||||||
|
|
||||||
|
var pixels = new byte[16];
|
||||||
|
var commands = new System.Collections.Generic.List<DrawCommand>();
|
||||||
|
Action<DrawCommand> addDraw = commands.Add;
|
||||||
|
|
||||||
|
bool ok = _worker.Execute(
|
||||||
|
"obj.draw() obj.setoption('antialias', 0) obj.draw()",
|
||||||
|
Fields(2, 2, 0d), NoStringParams, pixels, 2, 2, 5000, NoResolver, NoLoadFigure, NoLoadText, NoLoadImage, NoLoadMovie, NoAddEffect, addDraw,
|
||||||
|
out _, out _, out _, out _, out _, out string? error);
|
||||||
|
|
||||||
|
Assert.True(ok, error);
|
||||||
|
Assert.Equal(2, commands.Count);
|
||||||
|
Assert.Equal(1d, commands[0].Antialias);
|
||||||
|
Assert.Equal(0d, commands[1].Antialias);
|
||||||
|
}
|
||||||
|
|
||||||
|
[Fact]
|
||||||
|
public void LoadText_RoundTripsThroughCallback()
|
||||||
|
{
|
||||||
|
Assert.True(LuaJitWorker.IsAvailable(NativeDir), "native/luajit.exe must be present");
|
||||||
|
|
||||||
|
const int tw = 3, th = 2;
|
||||||
|
var rendered = new byte[tw * th * 4];
|
||||||
|
for (int i = 0; i < rendered.Length; i++)
|
||||||
|
rendered[i] = (byte)((i * 17 + 5) & 0xFF);
|
||||||
|
|
||||||
|
string? capturedFamily = null;
|
||||||
|
string? capturedText = null;
|
||||||
|
double capturedSize = 0;
|
||||||
|
bool capturedBold = false, capturedItalic = false;
|
||||||
|
int capturedColor = 0;
|
||||||
|
Func<string, string, double, bool, bool, int, (byte[], int, int)> loadText =
|
||||||
|
(family, text, size, bold, italic, color) =>
|
||||||
|
{
|
||||||
|
capturedFamily = family; capturedText = text; capturedSize = size;
|
||||||
|
capturedBold = bold; capturedItalic = italic; capturedColor = color;
|
||||||
|
return (rendered, tw, th);
|
||||||
|
};
|
||||||
|
|
||||||
|
var pixels = new byte[4 * 4 * 4];
|
||||||
|
var fields = Fields(4, 4, 0d);
|
||||||
|
|
||||||
|
bool ok = _worker.Execute(
|
||||||
|
"obj.setfont('Meiryo', 40, 3, 0x112233) obj.load('text', 'Hi')",
|
||||||
|
fields, NoStringParams, pixels, 4, 4, 5000, NoResolver, NoLoadFigure, loadText, NoLoadImage, NoLoadMovie, NoAddEffect, NoAddDraw,
|
||||||
|
out bool dirty, out bool bufferReplaced, out byte[]? newPixels, out int rw, out int rh, out string? error);
|
||||||
|
|
||||||
|
Assert.True(ok, error);
|
||||||
|
Assert.Equal("Meiryo", capturedFamily);
|
||||||
|
Assert.Equal("Hi", capturedText);
|
||||||
|
Assert.Equal(40d, capturedSize);
|
||||||
|
Assert.True(capturedBold);
|
||||||
|
Assert.True(capturedItalic);
|
||||||
|
Assert.Equal(0x112233, capturedColor);
|
||||||
|
Assert.True(dirty);
|
||||||
|
Assert.True(bufferReplaced);
|
||||||
|
Assert.Equal(tw, rw);
|
||||||
|
Assert.Equal(th, rh);
|
||||||
|
Assert.NotNull(newPixels);
|
||||||
|
Assert.Equal(rendered, newPixels!.AsSpan(0, rendered.Length).ToArray());
|
||||||
|
}
|
||||||
|
|
||||||
|
[Fact]
|
||||||
|
public void LoadImage_RoundTripsThroughCallback()
|
||||||
|
{
|
||||||
|
Assert.True(LuaJitWorker.IsAvailable(NativeDir), "native/luajit.exe must be present");
|
||||||
|
|
||||||
|
const int iw = 2, ih = 2;
|
||||||
|
var decoded = new byte[iw * ih * 4];
|
||||||
|
for (int i = 0; i < decoded.Length; i++)
|
||||||
|
decoded[i] = (byte)((i * 23 + 9) & 0xFF);
|
||||||
|
|
||||||
|
string? capturedPath = null;
|
||||||
|
Func<string, (byte[], int, int)> loadImage = path =>
|
||||||
|
{
|
||||||
|
capturedPath = path;
|
||||||
|
return (decoded, iw, ih);
|
||||||
|
};
|
||||||
|
|
||||||
|
var pixels = new byte[4 * 4 * 4];
|
||||||
|
var fields = Fields(4, 4, 0d);
|
||||||
|
|
||||||
|
bool ok = _worker.Execute(
|
||||||
|
"obj.load('image', 'C:/sample.png')",
|
||||||
|
fields, NoStringParams, pixels, 4, 4, 5000, NoResolver, NoLoadFigure, NoLoadText, loadImage, NoLoadMovie, NoAddEffect, NoAddDraw,
|
||||||
|
out bool dirty, out bool bufferReplaced, out byte[]? newPixels, out int rw, out int rh, out string? error);
|
||||||
|
|
||||||
|
Assert.True(ok, error);
|
||||||
|
Assert.Equal("C:/sample.png", capturedPath);
|
||||||
|
Assert.True(dirty);
|
||||||
|
Assert.True(bufferReplaced);
|
||||||
|
Assert.Equal(iw, rw);
|
||||||
|
Assert.Equal(ih, rh);
|
||||||
|
Assert.NotNull(newPixels);
|
||||||
|
Assert.Equal(decoded, newPixels!.AsSpan(0, decoded.Length).ToArray());
|
||||||
|
}
|
||||||
|
|
||||||
|
[Fact]
|
||||||
|
public void LoadMovie_RoundTripsPathAndTime()
|
||||||
|
{
|
||||||
|
Assert.True(LuaJitWorker.IsAvailable(NativeDir), "native/luajit.exe must be present");
|
||||||
|
|
||||||
|
const int mw = 2, mh = 2;
|
||||||
|
var frame = new byte[mw * mh * 4];
|
||||||
|
for (int i = 0; i < frame.Length; i++)
|
||||||
|
frame[i] = (byte)((i * 31 + 3) & 0xFF);
|
||||||
|
|
||||||
|
string? capturedPath = null;
|
||||||
|
double capturedTime = -1;
|
||||||
|
Func<string, double, (byte[], int, int)> loadMovie = (path, time) =>
|
||||||
|
{
|
||||||
|
capturedPath = path;
|
||||||
|
capturedTime = time;
|
||||||
|
return (frame, mw, mh);
|
||||||
|
};
|
||||||
|
|
||||||
|
var pixels = new byte[4 * 4 * 4];
|
||||||
|
var fields = Fields(4, 4, 0d);
|
||||||
|
|
||||||
|
bool ok = _worker.Execute(
|
||||||
|
"obj.load('movie', 'C:/clip.mp4', 1.5)",
|
||||||
|
fields, NoStringParams, pixels, 4, 4, 5000, NoResolver, NoLoadFigure, NoLoadText, NoLoadImage, loadMovie, NoAddEffect, NoAddDraw,
|
||||||
|
out bool dirty, out bool bufferReplaced, out byte[]? newPixels, out int rw, out int rh, out string? error);
|
||||||
|
|
||||||
|
Assert.True(ok, error);
|
||||||
|
Assert.Equal("C:/clip.mp4", capturedPath);
|
||||||
|
Assert.Equal(1.5d, capturedTime);
|
||||||
|
Assert.True(dirty);
|
||||||
|
Assert.True(bufferReplaced);
|
||||||
|
Assert.Equal(mw, rw);
|
||||||
|
Assert.Equal(mh, rh);
|
||||||
|
Assert.NotNull(newPixels);
|
||||||
|
Assert.Equal(frame, newPixels!.AsSpan(0, frame.Length).ToArray());
|
||||||
|
}
|
||||||
|
|
||||||
|
[Fact]
|
||||||
|
public void GetValue_ReturnsObjFields()
|
||||||
|
{
|
||||||
|
Assert.True(LuaJitWorker.IsAvailable(NativeDir), "native/luajit.exe must be present");
|
||||||
|
|
||||||
|
var pixels = new byte[16];
|
||||||
|
var fields = Fields(2, 2, 0d);
|
||||||
|
fields[NativeProtocol.Track0] = 42d;
|
||||||
|
|
||||||
|
bool ok = _worker.Execute(
|
||||||
|
"obj.x = obj.getvalue('track0') obj.y = obj.getvalue('alpha') obj.z = obj.getvalue('unknown')",
|
||||||
|
fields, NoStringParams, pixels, 2, 2, 5000, NoResolver, NoLoadFigure, NoLoadText, NoLoadImage, NoLoadMovie, NoAddEffect, NoAddDraw,
|
||||||
|
out _, out _, out _, out _, out _, out string? error);
|
||||||
|
|
||||||
|
Assert.True(ok, error);
|
||||||
|
Assert.Equal(42d, fields[NativeProtocol.X]);
|
||||||
|
Assert.Equal(255d, fields[NativeProtocol.Y]);
|
||||||
|
Assert.Equal(0d, fields[NativeProtocol.Z]);
|
||||||
|
}
|
||||||
|
|
||||||
|
[Fact]
|
||||||
|
public void CopyBuffer_TmpSaveRestore_RoundTripsPixels()
|
||||||
|
{
|
||||||
|
Assert.True(LuaJitWorker.IsAvailable(NativeDir), "native/luajit.exe must be present");
|
||||||
|
|
||||||
|
const int w = 2, h = 2;
|
||||||
|
var pixels = new byte[w * h * 4];
|
||||||
|
for (int i = 0; i < pixels.Length; i++)
|
||||||
|
pixels[i] = (byte)((i * 37 + 11) & 0xFF);
|
||||||
|
pixels[3] = 255; pixels[7] = 255; pixels[11] = 255; pixels[15] = 255;
|
||||||
|
var original = (byte[])pixels.Clone();
|
||||||
|
|
||||||
|
var fields = Fields(w, h, 0d);
|
||||||
|
const string script =
|
||||||
|
"obj.copybuffer('tmp','obj') " +
|
||||||
|
"for y=0,obj.h-1 do for x=0,obj.w-1 do obj.setpixel(x,y,0,0,0,0) end end " +
|
||||||
|
"obj.copybuffer('obj','tmp')";
|
||||||
|
|
||||||
|
bool ok = _worker.Execute(script, fields, NoStringParams, pixels, w, h, 5000, NoResolver, NoLoadFigure, NoLoadText, NoLoadImage, NoLoadMovie, NoAddEffect, NoAddDraw, out bool dirty, out _, out _, out _, out _, out string? error);
|
||||||
|
|
||||||
|
Assert.True(ok, error);
|
||||||
|
Assert.True(dirty);
|
||||||
|
Assert.Equal(original, pixels);
|
||||||
|
}
|
||||||
|
|
||||||
|
[Fact]
|
||||||
|
public void CopyBuffer_CachePersistsAcrossRuns()
|
||||||
|
{
|
||||||
|
Assert.True(LuaJitWorker.IsAvailable(NativeDir), "native/luajit.exe must be present");
|
||||||
|
|
||||||
|
const int w = 2, h = 2;
|
||||||
|
var stored = new byte[w * h * 4];
|
||||||
|
for (int i = 0; i < stored.Length; i++)
|
||||||
|
stored[i] = (byte)((i * 53 + 7) & 0xFF);
|
||||||
|
stored[3] = 255; stored[7] = 255; stored[11] = 255; stored[15] = 255;
|
||||||
|
|
||||||
|
var save = (byte[])stored.Clone();
|
||||||
|
bool ok = _worker.Execute("obj.copybuffer('cache:foo','obj')", Fields(w, h, 0d), NoStringParams, save, w, h, 5000, NoResolver, NoLoadFigure, NoLoadText, NoLoadImage, NoLoadMovie, NoAddEffect, NoAddDraw, out _, out _, out _, out _, out _, out string? error);
|
||||||
|
Assert.True(ok, error);
|
||||||
|
|
||||||
|
var blank = new byte[w * h * 4];
|
||||||
|
ok = _worker.Execute("obj.copybuffer('obj','cache:foo')", Fields(w, h, 0d), NoStringParams, blank, w, h, 5000, NoResolver, NoLoadFigure, NoLoadText, NoLoadImage, NoLoadMovie, NoAddEffect, NoAddDraw, out bool dirty, out _, out _, out _, out _, out error);
|
||||||
|
Assert.True(ok, error);
|
||||||
|
Assert.True(dirty);
|
||||||
|
Assert.Equal(stored, blank);
|
||||||
|
}
|
||||||
|
|
||||||
[Fact]
|
[Fact]
|
||||||
public void RuntimeError_IsReported_AndWorkerSurvives()
|
public void RuntimeError_IsReported_AndWorkerSurvives()
|
||||||
{
|
{
|
||||||
@@ -251,12 +595,12 @@ namespace LuaScript.Tests
|
|||||||
var pixels = new byte[16];
|
var pixels = new byte[16];
|
||||||
var fields = Fields(2, 2, 0d);
|
var fields = Fields(2, 2, 0d);
|
||||||
|
|
||||||
bool ok = _worker.Execute("obj.x = missing.value", fields, pixels, 2, 2, 5000, NoResolver, out _, out string? error);
|
bool ok = _worker.Execute("obj.x = missing.value", fields, NoStringParams, pixels, 2, 2, 5000, NoResolver, NoLoadFigure, NoLoadText, NoLoadImage, NoLoadMovie, NoAddEffect, NoAddDraw, out _, out _, out _, out _, out _, out string? error);
|
||||||
Assert.False(ok);
|
Assert.False(ok);
|
||||||
Assert.False(string.IsNullOrEmpty(error));
|
Assert.False(string.IsNullOrEmpty(error));
|
||||||
|
|
||||||
var fields2 = Fields(2, 2, 7d);
|
var fields2 = Fields(2, 2, 7d);
|
||||||
bool ok2 = _worker.Execute("obj.x = obj.time", fields2, pixels, 2, 2, 5000, NoResolver, out _, out error);
|
bool ok2 = _worker.Execute("obj.x = obj.time", fields2, NoStringParams, pixels, 2, 2, 5000, NoResolver, NoLoadFigure, NoLoadText, NoLoadImage, NoLoadMovie, NoAddEffect, NoAddDraw, out _, out _, out _, out _, out _, out error);
|
||||||
Assert.True(ok2, error);
|
Assert.True(ok2, error);
|
||||||
Assert.Equal(7d, fields2[NativeProtocol.X]);
|
Assert.Equal(7d, fields2[NativeProtocol.X]);
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -38,7 +38,9 @@ namespace LuaScript.Tests
|
|||||||
[InlineData("--!moonsharp\nobj.setpixel(0,0,1,1,1)", "MoonSharp")]
|
[InlineData("--!moonsharp\nobj.setpixel(0,0,1,1,1)", "MoonSharp")]
|
||||||
[InlineData("--!native\nobj.rz = 1", "Native")]
|
[InlineData("--!native\nobj.rz = 1", "Native")]
|
||||||
[InlineData("obj.load(\"figure\", \"円\", 0xff0000, 100)", "MoonSharp")]
|
[InlineData("obj.load(\"figure\", \"円\", 0xff0000, 100)", "MoonSharp")]
|
||||||
[InlineData("obj.load(\"figure\", \"円\", 0xff0000, 100)\nlocal r = obj.getpixel(0,0)", "MoonSharp")]
|
[InlineData("obj.load(\"figure\", \"円\", 0xff0000, 100)\nlocal r = obj.getpixel(0,0)", "Native")]
|
||||||
|
[InlineData("obj.draw()", "MoonSharp")]
|
||||||
|
[InlineData("obj.draw()\nlocal r = obj.getpixel(0,0)", "Native")]
|
||||||
[InlineData("--!native\nobj.load(\"figure\", \"円\", 0xff0000, 100)", "Native")]
|
[InlineData("--!native\nobj.load(\"figure\", \"円\", 0xff0000, 100)", "Native")]
|
||||||
public void ResolveAuto_RoutesPixelScriptsToNative(string script, string expected)
|
public void ResolveAuto_RoutesPixelScriptsToNative(string script, string expected)
|
||||||
{
|
{
|
||||||
|
|||||||
@@ -0,0 +1,68 @@
|
|||||||
|
using LuaScript.Compat;
|
||||||
|
|
||||||
|
namespace LuaScript.Tests
|
||||||
|
{
|
||||||
|
public sealed class ScriptParameterUsageTests
|
||||||
|
{
|
||||||
|
[Theory]
|
||||||
|
[InlineData("if obj.check0 then obj.alpha = 0 end", 0)]
|
||||||
|
[InlineData("local v = obj.check3 and 255 or 0", 3)]
|
||||||
|
[InlineData("obj . check1 = true", 1)]
|
||||||
|
public void DetectsReferencedCheck(string script, int index)
|
||||||
|
{
|
||||||
|
var usage = ScriptParameterUsage.Detect(script);
|
||||||
|
for (int i = 0; i < 4; i++)
|
||||||
|
Assert.Equal(i == index, usage.Check(i));
|
||||||
|
Assert.False(usage.Color);
|
||||||
|
}
|
||||||
|
|
||||||
|
[Fact]
|
||||||
|
public void DetectsReferencedColor()
|
||||||
|
{
|
||||||
|
var usage = ScriptParameterUsage.Detect("obj.rz = color / 1000");
|
||||||
|
Assert.True(usage.Color);
|
||||||
|
}
|
||||||
|
|
||||||
|
[Fact]
|
||||||
|
public void DetectsMultipleChecks()
|
||||||
|
{
|
||||||
|
var usage = ScriptParameterUsage.Detect("local a = obj.check0\nlocal b = obj.check2");
|
||||||
|
Assert.True(usage.Check0);
|
||||||
|
Assert.False(usage.Check1);
|
||||||
|
Assert.True(usage.Check2);
|
||||||
|
Assert.False(usage.Check3);
|
||||||
|
}
|
||||||
|
|
||||||
|
[Theory]
|
||||||
|
[InlineData("obj.setoption(\"color\", 1)")]
|
||||||
|
[InlineData("-- color and obj.check0 in a comment")]
|
||||||
|
[InlineData("local colorful = 1")]
|
||||||
|
[InlineData("scene.color = 0")]
|
||||||
|
public void IgnoresStringsCommentsAndUnrelatedNames(string script)
|
||||||
|
{
|
||||||
|
var usage = ScriptParameterUsage.Detect(script);
|
||||||
|
Assert.False(usage.Color);
|
||||||
|
for (int i = 0; i < 4; i++)
|
||||||
|
Assert.False(usage.Check(i));
|
||||||
|
}
|
||||||
|
|
||||||
|
[Theory]
|
||||||
|
[InlineData(null)]
|
||||||
|
[InlineData("")]
|
||||||
|
[InlineData("local s = \"unterminated")]
|
||||||
|
public void ReturnsNoneForEmptyOrInvalid(string? script)
|
||||||
|
{
|
||||||
|
var usage = ScriptParameterUsage.Detect(script);
|
||||||
|
Assert.False(usage.Color);
|
||||||
|
Assert.False(usage.Check0);
|
||||||
|
}
|
||||||
|
|
||||||
|
[Fact]
|
||||||
|
public void DoesNotDetectOutOfRangeCheck()
|
||||||
|
{
|
||||||
|
var usage = ScriptParameterUsage.Detect("local a = obj.check4");
|
||||||
|
for (int i = 0; i < 4; i++)
|
||||||
|
Assert.False(usage.Check(i));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,17 @@
|
|||||||
|
using System.Collections.Generic;
|
||||||
|
|
||||||
|
namespace LuaScript
|
||||||
|
{
|
||||||
|
internal sealed class AviUtlEffectRequest
|
||||||
|
{
|
||||||
|
public string Name { get; }
|
||||||
|
|
||||||
|
public IReadOnlyList<KeyValuePair<string, object>> Arguments { get; }
|
||||||
|
|
||||||
|
public AviUtlEffectRequest(string name, IReadOnlyList<KeyValuePair<string, object>> arguments)
|
||||||
|
{
|
||||||
|
Name = name;
|
||||||
|
Arguments = arguments;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -29,6 +29,11 @@ namespace LuaScript
|
|||||||
public double Track2 { get; set; }
|
public double Track2 { get; set; }
|
||||||
public double Track3 { get; set; }
|
public double Track3 { get; set; }
|
||||||
|
|
||||||
|
public double Slider0 { get; set; }
|
||||||
|
public double Slider1 { get; set; }
|
||||||
|
public double Slider2 { get; set; }
|
||||||
|
public double Slider3 { get; set; }
|
||||||
|
|
||||||
public bool Check0 { get; set; }
|
public bool Check0 { get; set; }
|
||||||
public bool Check1 { get; set; }
|
public bool Check1 { get; set; }
|
||||||
public bool Check2 { get; set; }
|
public bool Check2 { get; set; }
|
||||||
@@ -52,10 +57,108 @@ namespace LuaScript
|
|||||||
|
|
||||||
public Func<SceneObjectResolver>? ResolverProvider { get; set; }
|
public Func<SceneObjectResolver>? ResolverProvider { get; set; }
|
||||||
|
|
||||||
|
private readonly Dictionary<string, string> _stringParameters = new(StringComparer.Ordinal);
|
||||||
|
|
||||||
|
public IReadOnlyDictionary<string, string> StringParameters => _stringParameters;
|
||||||
|
|
||||||
|
internal void SetStringParameter(string name, string? value) => _stringParameters[name] = value ?? string.Empty;
|
||||||
|
|
||||||
|
private const double Epsilon = 1e-10;
|
||||||
|
|
||||||
private readonly List<SceneObjectQuery> _objectQueries = [];
|
private readonly List<SceneObjectQuery> _objectQueries = [];
|
||||||
|
|
||||||
public IReadOnlyList<SceneObjectQuery> ObjectQueries => _objectQueries;
|
public IReadOnlyList<SceneObjectQuery> ObjectQueries => _objectQueries;
|
||||||
|
|
||||||
|
private readonly List<AviUtlEffectRequest> _effectRequests = [];
|
||||||
|
|
||||||
|
public IReadOnlyList<AviUtlEffectRequest> EffectRequests => _effectRequests;
|
||||||
|
|
||||||
|
internal void AddEffect(AviUtlEffectRequest request) => _effectRequests.Add(request);
|
||||||
|
|
||||||
|
internal void ClearEffects() => _effectRequests.Clear();
|
||||||
|
|
||||||
|
private readonly List<DrawCommand> _drawCommands = [];
|
||||||
|
|
||||||
|
public IReadOnlyList<DrawCommand> DrawCommands => _drawCommands;
|
||||||
|
|
||||||
|
internal void AddDraw(DrawCommand command) => _drawCommands.Add(command);
|
||||||
|
|
||||||
|
internal void ClearDraws() => _drawCommands.Clear();
|
||||||
|
|
||||||
|
private readonly Dictionary<string, (byte[] Data, int Width, int Height)> _buffers = new(StringComparer.Ordinal);
|
||||||
|
|
||||||
|
internal bool CopyBuffer(string dst, string src)
|
||||||
|
{
|
||||||
|
if (!TryReadBuffer(src, out var data, out int w, out int h))
|
||||||
|
return false;
|
||||||
|
return TryWriteBuffer(dst, data, w, h);
|
||||||
|
}
|
||||||
|
|
||||||
|
private bool TryReadBuffer(string id, out byte[] data, out int width, out int height)
|
||||||
|
{
|
||||||
|
data = [];
|
||||||
|
width = 0;
|
||||||
|
height = 0;
|
||||||
|
switch (BufferKind(id, out string key))
|
||||||
|
{
|
||||||
|
case 'o':
|
||||||
|
EnsurePixelBuffer();
|
||||||
|
if (_pixelBuffer is null)
|
||||||
|
return false;
|
||||||
|
data = _pixelBuffer;
|
||||||
|
width = ImageWidth;
|
||||||
|
height = ImageHeight;
|
||||||
|
return true;
|
||||||
|
case 't':
|
||||||
|
case 'c':
|
||||||
|
if (_buffers.TryGetValue(key, out var stored))
|
||||||
|
{
|
||||||
|
data = stored.Data;
|
||||||
|
width = stored.Width;
|
||||||
|
height = stored.Height;
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
return false;
|
||||||
|
default:
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private bool TryWriteBuffer(string id, byte[] data, int width, int height)
|
||||||
|
{
|
||||||
|
switch (BufferKind(id, out string key))
|
||||||
|
{
|
||||||
|
case 'o':
|
||||||
|
ReplaceBuffer((byte[])data.Clone(), width, height);
|
||||||
|
return true;
|
||||||
|
case 't':
|
||||||
|
case 'c':
|
||||||
|
_buffers[key] = ((byte[])data.Clone(), width, height);
|
||||||
|
return false;
|
||||||
|
default:
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private static char BufferKind(string id, out string key)
|
||||||
|
{
|
||||||
|
key = string.Empty;
|
||||||
|
int i = 0;
|
||||||
|
while (i < id.Length && (id[i] == ' ' || id[i] == '\t'))
|
||||||
|
i++;
|
||||||
|
if (i >= id.Length)
|
||||||
|
return '\0';
|
||||||
|
char kind = char.ToLowerInvariant(id[i]);
|
||||||
|
if (kind == 't')
|
||||||
|
key = "t";
|
||||||
|
else if (kind == 'c')
|
||||||
|
{
|
||||||
|
int colon = id.IndexOf(':', i);
|
||||||
|
key = colon >= 0 ? "c:" + id[(colon + 1)..].Trim() : "c";
|
||||||
|
}
|
||||||
|
return kind;
|
||||||
|
}
|
||||||
|
|
||||||
public double RxRad => Rx * Math.PI / 180d;
|
public double RxRad => Rx * Math.PI / 180d;
|
||||||
public double RyRad => Ry * Math.PI / 180d;
|
public double RyRad => Ry * Math.PI / 180d;
|
||||||
public double RzRad => Rz * Math.PI / 180d;
|
public double RzRad => Rz * Math.PI / 180d;
|
||||||
@@ -106,6 +209,14 @@ namespace LuaScript
|
|||||||
_pixelBufferLoaded = true;
|
_pixelBufferLoaded = true;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
internal void SetResolvedBuffer(byte[] buffer, int width, int height)
|
||||||
|
{
|
||||||
|
_pixelBuffer = buffer;
|
||||||
|
_pixelBufferLoaded = true;
|
||||||
|
ImageWidth = width;
|
||||||
|
ImageHeight = height;
|
||||||
|
}
|
||||||
|
|
||||||
internal byte[]? GetPixelBuffer() => _pixelBuffer;
|
internal byte[]? GetPixelBuffer() => _pixelBuffer;
|
||||||
|
|
||||||
internal void MarkPixelsDirty() => _isPixelsDirty = true;
|
internal void MarkPixelsDirty() => _isPixelsDirty = true;
|
||||||
@@ -125,6 +236,46 @@ namespace LuaScript
|
|||||||
return false;
|
return false;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
public void ApplyWriteBack(
|
||||||
|
double newSx, double newSy, double newZoom, double newAspect,
|
||||||
|
double newRx, double newRy, double newRz,
|
||||||
|
double newRxr, double newRyr, double newRzr)
|
||||||
|
{
|
||||||
|
double initialSx = Sx;
|
||||||
|
double initialSy = Sy;
|
||||||
|
double initialZoom = Zoom;
|
||||||
|
double initialAspect = Aspect;
|
||||||
|
|
||||||
|
Sx = newSx;
|
||||||
|
Sy = newSy;
|
||||||
|
Zoom = newZoom;
|
||||||
|
Aspect = newAspect;
|
||||||
|
|
||||||
|
bool sxsyChanged = Math.Abs(Sx - initialSx) > Epsilon || Math.Abs(Sy - initialSy) > Epsilon;
|
||||||
|
bool zoomAspectChanged = Math.Abs(Zoom - initialZoom) > Epsilon || Math.Abs(Aspect - initialAspect) > Epsilon;
|
||||||
|
|
||||||
|
if (zoomAspectChanged && !sxsyChanged)
|
||||||
|
{
|
||||||
|
Sx = Zoom * (1.0 + Aspect);
|
||||||
|
Sy = Zoom * (1.0 - Aspect);
|
||||||
|
}
|
||||||
|
|
||||||
|
double initialRxr = RxRad;
|
||||||
|
Rx = Math.Abs(newRxr - initialRxr) > Epsilon
|
||||||
|
? newRxr * (180d / Math.PI)
|
||||||
|
: newRx;
|
||||||
|
|
||||||
|
double initialRyr = RyRad;
|
||||||
|
Ry = Math.Abs(newRyr - initialRyr) > Epsilon
|
||||||
|
? newRyr * (180d / Math.PI)
|
||||||
|
: newRy;
|
||||||
|
|
||||||
|
double initialRzr = RzRad;
|
||||||
|
Rz = Math.Abs(newRzr - initialRzr) > Epsilon
|
||||||
|
? newRzr * (180d / Math.PI)
|
||||||
|
: newRz;
|
||||||
|
}
|
||||||
|
|
||||||
public unsafe (double r, double g, double b, double a) GetPixel(int x, int y)
|
public unsafe (double r, double g, double b, double a) GetPixel(int x, int y)
|
||||||
{
|
{
|
||||||
EnsurePixelBuffer();
|
EnsurePixelBuffer();
|
||||||
|
|||||||
@@ -0,0 +1,138 @@
|
|||||||
|
using System.Collections.Generic;
|
||||||
|
using System.Globalization;
|
||||||
|
using System.IO;
|
||||||
|
using System.Linq;
|
||||||
|
using System.Reflection;
|
||||||
|
using System.Xml.Linq;
|
||||||
|
|
||||||
|
namespace LuaScript.Compat
|
||||||
|
{
|
||||||
|
internal sealed class AviUtlCompatMap
|
||||||
|
{
|
||||||
|
private const string ResourceSuffix = "AviUtlCompatMap.xml";
|
||||||
|
|
||||||
|
private readonly Dictionary<string, List<AviUtlEffectMapping>> _effects;
|
||||||
|
|
||||||
|
public static AviUtlCompatMap Default { get; } = Load();
|
||||||
|
|
||||||
|
private AviUtlCompatMap(Dictionary<string, List<AviUtlEffectMapping>> effects)
|
||||||
|
{
|
||||||
|
_effects = effects;
|
||||||
|
}
|
||||||
|
|
||||||
|
public bool TryResolve(string name, AviUtlEngine target, out AviUtlEffectMapping mapping)
|
||||||
|
{
|
||||||
|
mapping = null!;
|
||||||
|
if (string.IsNullOrEmpty(name) || !_effects.TryGetValue(Normalize(name), out var candidates))
|
||||||
|
return false;
|
||||||
|
|
||||||
|
foreach (var candidate in candidates)
|
||||||
|
{
|
||||||
|
if (candidate.Engine.Includes(target))
|
||||||
|
{
|
||||||
|
mapping = candidate;
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
|
public static AviUtlEngine ResolveTarget(string? script)
|
||||||
|
{
|
||||||
|
if (string.IsNullOrEmpty(script))
|
||||||
|
return AviUtlEngine.AviUtl;
|
||||||
|
|
||||||
|
foreach (var raw in script.Replace("\r\n", "\n").Replace("\r", "\n").Split('\n'))
|
||||||
|
{
|
||||||
|
var line = raw.Trim();
|
||||||
|
if (!line.StartsWith("--!", System.StringComparison.Ordinal))
|
||||||
|
continue;
|
||||||
|
var token = line[3..].Trim().ToLowerInvariant();
|
||||||
|
if (token == "aviutl2")
|
||||||
|
return AviUtlEngine.AviUtl2;
|
||||||
|
if (token == "aviutl")
|
||||||
|
return AviUtlEngine.AviUtl;
|
||||||
|
}
|
||||||
|
return AviUtlEngine.AviUtl;
|
||||||
|
}
|
||||||
|
|
||||||
|
private static AviUtlCompatMap Load()
|
||||||
|
{
|
||||||
|
var effects = new Dictionary<string, List<AviUtlEffectMapping>>(StringComparer.OrdinalIgnoreCase);
|
||||||
|
try
|
||||||
|
{
|
||||||
|
using var stream = OpenResource();
|
||||||
|
if (stream is not null)
|
||||||
|
Populate(effects, stream);
|
||||||
|
}
|
||||||
|
catch
|
||||||
|
{
|
||||||
|
}
|
||||||
|
return new AviUtlCompatMap(effects);
|
||||||
|
}
|
||||||
|
|
||||||
|
private static void Populate(Dictionary<string, List<AviUtlEffectMapping>> effects, Stream stream)
|
||||||
|
{
|
||||||
|
var root = XDocument.Load(stream).Root;
|
||||||
|
if (root is null)
|
||||||
|
return;
|
||||||
|
|
||||||
|
foreach (var element in root.Elements("effect"))
|
||||||
|
{
|
||||||
|
var target = (string?)element.Attribute("target");
|
||||||
|
if (string.IsNullOrWhiteSpace(target))
|
||||||
|
continue;
|
||||||
|
|
||||||
|
if (!AviUtlEngineExtensions.TryParse(((string?)element.Attribute("engine"))?.Trim().ToLowerInvariant(), out var engine))
|
||||||
|
engine = AviUtlEngine.Both;
|
||||||
|
|
||||||
|
var parameters = element.Elements("param").Select(ParseParameter).ToArray();
|
||||||
|
var mapping = new AviUtlEffectMapping(engine, target.Trim(), parameters);
|
||||||
|
|
||||||
|
foreach (var name in SplitNames((string?)element.Attribute("names")))
|
||||||
|
{
|
||||||
|
if (!effects.TryGetValue(name, out var list))
|
||||||
|
{
|
||||||
|
list = [];
|
||||||
|
effects[name] = list;
|
||||||
|
}
|
||||||
|
list.Add(mapping);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private static AviUtlParameterMapping ParseParameter(XElement element)
|
||||||
|
{
|
||||||
|
var source = ((string?)element.Attribute("name") ?? string.Empty).Trim();
|
||||||
|
var property = ((string?)element.Attribute("property") ?? string.Empty).Trim();
|
||||||
|
double scale = ParseDouble((string?)element.Attribute("scale"), 1d);
|
||||||
|
double offset = ParseDouble((string?)element.Attribute("offset"), 0d);
|
||||||
|
return new AviUtlParameterMapping(source, property, scale, offset);
|
||||||
|
}
|
||||||
|
|
||||||
|
private static IEnumerable<string> SplitNames(string? names)
|
||||||
|
{
|
||||||
|
if (string.IsNullOrWhiteSpace(names))
|
||||||
|
yield break;
|
||||||
|
foreach (var part in names.Split(','))
|
||||||
|
{
|
||||||
|
var trimmed = part.Trim();
|
||||||
|
if (trimmed.Length != 0)
|
||||||
|
yield return Normalize(trimmed);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private static double ParseDouble(string? value, double fallback) =>
|
||||||
|
double.TryParse(value, NumberStyles.Float, CultureInfo.InvariantCulture, out double result) ? result : fallback;
|
||||||
|
|
||||||
|
private static string Normalize(string value) => value.Trim().ToLowerInvariant();
|
||||||
|
|
||||||
|
private static Stream? OpenResource()
|
||||||
|
{
|
||||||
|
var assembly = typeof(AviUtlCompatMap).Assembly;
|
||||||
|
var name = assembly.GetManifestResourceNames()
|
||||||
|
.FirstOrDefault(n => n.EndsWith(ResourceSuffix, System.StringComparison.Ordinal));
|
||||||
|
return name is null ? null : assembly.GetManifestResourceStream(name);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,114 @@
|
|||||||
|
<?xml version="1.0" encoding="utf-8"?>
|
||||||
|
<aviUtlCompat>
|
||||||
|
<effect engine="both" names="ぼかし" target="GaussianBlurEffect">
|
||||||
|
<param name="範囲" property="Blur" scale="0.5" />
|
||||||
|
<param name="サイズ固定" property="IsHardBorderMode" />
|
||||||
|
</effect>
|
||||||
|
<effect engine="both" names="境界ぼかし" target="BorderBlurEffect">
|
||||||
|
<param name="範囲" property="Blur" />
|
||||||
|
</effect>
|
||||||
|
<effect engine="both" names="方向ブラー" target="DirectionalBlurEffect">
|
||||||
|
<param name="範囲" property="StandardDeviation" scale="0.5" />
|
||||||
|
<param name="角度" property="Angle" />
|
||||||
|
<param name="サイズ固定" property="IsHardBorderMode" />
|
||||||
|
</effect>
|
||||||
|
<effect engine="both" names="放射ブラー" target="RadialBlurEffect">
|
||||||
|
<param name="範囲" property="Blur" />
|
||||||
|
<param name="X" property="X" />
|
||||||
|
<param name="Y" property="Y" />
|
||||||
|
<param name="サイズを固定" property="IsHardBorderMode" />
|
||||||
|
</effect>
|
||||||
|
<effect engine="both" names="閃光" target="RadialLightEffect">
|
||||||
|
<param name="範囲" property="Value" />
|
||||||
|
<param name="X" property="X" />
|
||||||
|
<param name="Y" property="Y" />
|
||||||
|
<param name="サイズを固定" property="IsHardBorderMode" />
|
||||||
|
</effect>
|
||||||
|
<effect engine="both" names="クロマキー" target="ChromaKeyEffect">
|
||||||
|
<param name="色相範囲" property="Tolerance" scale="0.390625" />
|
||||||
|
<param name="境界補正" property="Feather" />
|
||||||
|
</effect>
|
||||||
|
<effect engine="both" names="クリッピング" target="CropEffect">
|
||||||
|
<param name="上" property="Top" />
|
||||||
|
<param name="下" property="Bottom" />
|
||||||
|
<param name="左" property="Left" />
|
||||||
|
<param name="右" property="Right" />
|
||||||
|
<param name="中心の位置を変更" property="IsCentering" />
|
||||||
|
</effect>
|
||||||
|
<effect engine="both" names="斜めクリッピング" target="CropByAngleEffect">
|
||||||
|
<param name="中心X" property="X" />
|
||||||
|
<param name="中心Y" property="Y" />
|
||||||
|
<param name="角度" property="Angle" />
|
||||||
|
<param name="ぼかし" property="Blur" scale="0.5" />
|
||||||
|
<param name="幅" property="Width" />
|
||||||
|
</effect>
|
||||||
|
<effect engine="both" names="領域拡張" target="MarginEffect">
|
||||||
|
<param name="上" property="Top" />
|
||||||
|
<param name="下" property="Bottom" />
|
||||||
|
<param name="左" property="Left" />
|
||||||
|
<param name="右" property="Right" />
|
||||||
|
</effect>
|
||||||
|
<effect engine="both" names="座標" target="DrawPositionEffect">
|
||||||
|
<param name="X" property="X" />
|
||||||
|
<param name="Y" property="Y" />
|
||||||
|
<param name="Z" property="Z" />
|
||||||
|
</effect>
|
||||||
|
<effect engine="both" names="回転" target="RotateEffect">
|
||||||
|
<param name="X" property="X" />
|
||||||
|
<param name="Y" property="Y" />
|
||||||
|
<param name="Z" property="Z" />
|
||||||
|
</effect>
|
||||||
|
<effect engine="both" names="リサイズ" target="ZoomEffect">
|
||||||
|
<param name="拡大率" property="Zoom" />
|
||||||
|
<param name="X" property="ZoomX" />
|
||||||
|
<param name="Y" property="ZoomY" />
|
||||||
|
<param name="補間なし" property="IsNearestNeighbor" />
|
||||||
|
</effect>
|
||||||
|
<effect engine="both" names="画像ループ" target="TilingEffect">
|
||||||
|
<param name="横回数" property="X" />
|
||||||
|
<param name="縦回数" property="Y" />
|
||||||
|
</effect>
|
||||||
|
<effect engine="both" names="極座標変換" target="PolarTransformEffect">
|
||||||
|
<param name="中心幅" property="CoreWidth" />
|
||||||
|
<param name="渦巻" property="TwistAngle" scale="360" />
|
||||||
|
</effect>
|
||||||
|
<effect engine="both" names="グラデーション" target="GradientEffect">
|
||||||
|
<param name="強さ" property="Opacity" />
|
||||||
|
<param name="中心X" property="X" />
|
||||||
|
<param name="中心Y" property="Y" />
|
||||||
|
<param name="角度" property="Rotation" />
|
||||||
|
<param name="幅" property="Size" />
|
||||||
|
</effect>
|
||||||
|
<effect engine="both" names="単色化" target="MonocolorizationEffect">
|
||||||
|
<param name="強さ" property="Strength" />
|
||||||
|
<param name="輝度を保持する" property="KeepBrightness" />
|
||||||
|
</effect>
|
||||||
|
<effect engine="both" names="縁取り" target="OutlineEffect">
|
||||||
|
<param name="サイズ" property="StrokeThickness" />
|
||||||
|
<param name="ぼかし" property="Blur" />
|
||||||
|
</effect>
|
||||||
|
<effect engine="both" names="反転" target="InvertEffect" />
|
||||||
|
<effect engine="both" names="モザイク" target="MosaicEffect">
|
||||||
|
<param name="サイズ" property="Size" />
|
||||||
|
</effect>
|
||||||
|
<effect engine="both" names="ディスプレイスメントマップ" target="DisplacementMapEffect">
|
||||||
|
<param name="ぼかし" property="Blur" scale="0.5" />
|
||||||
|
</effect>
|
||||||
|
<effect engine="both" names="動画ファイル合成" target="TextureEffect">
|
||||||
|
<param name="X" property="X" />
|
||||||
|
<param name="Y" property="Y" />
|
||||||
|
<param name="拡大率" property="Zoom" />
|
||||||
|
</effect>
|
||||||
|
<effect engine="both" names="色調補正" target="ColorCorrectionEffect">
|
||||||
|
<param name="明るさ" property="Lightness" />
|
||||||
|
<param name="コントラスト" property="Contrast" />
|
||||||
|
<param name="色相" property="HueRotation" />
|
||||||
|
<param name="輝度" property="Brightness" />
|
||||||
|
<param name="彩度" property="Saturation" />
|
||||||
|
</effect>
|
||||||
|
<effect engine="both" names="色ずれ" target="ColorShiftEffect">
|
||||||
|
<param name="ずれ幅" property="Shift" />
|
||||||
|
<param name="角度" property="Angle" />
|
||||||
|
<param name="強さ" property="Strength" />
|
||||||
|
</effect>
|
||||||
|
</aviUtlCompat>
|
||||||
@@ -0,0 +1,30 @@
|
|||||||
|
using System.Collections.Generic;
|
||||||
|
|
||||||
|
namespace LuaScript.Compat
|
||||||
|
{
|
||||||
|
internal readonly record struct AviUtlParameterMapping(string Source, string Property, double Scale, double Offset)
|
||||||
|
{
|
||||||
|
public double Transform(double value) => value * Scale + Offset;
|
||||||
|
}
|
||||||
|
|
||||||
|
internal sealed class AviUtlEffectMapping
|
||||||
|
{
|
||||||
|
private readonly Dictionary<string, AviUtlParameterMapping> _parameters;
|
||||||
|
|
||||||
|
public AviUtlEngine Engine { get; }
|
||||||
|
|
||||||
|
public string TargetType { get; }
|
||||||
|
|
||||||
|
public AviUtlEffectMapping(AviUtlEngine engine, string targetType, IEnumerable<AviUtlParameterMapping> parameters)
|
||||||
|
{
|
||||||
|
Engine = engine;
|
||||||
|
TargetType = targetType;
|
||||||
|
_parameters = new Dictionary<string, AviUtlParameterMapping>(StringComparer.OrdinalIgnoreCase);
|
||||||
|
foreach (var parameter in parameters)
|
||||||
|
_parameters[parameter.Source] = parameter;
|
||||||
|
}
|
||||||
|
|
||||||
|
public bool TryGetParameter(string source, out AviUtlParameterMapping mapping) =>
|
||||||
|
_parameters.TryGetValue(source, out mapping);
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,34 @@
|
|||||||
|
namespace LuaScript.Compat
|
||||||
|
{
|
||||||
|
internal enum AviUtlEngine
|
||||||
|
{
|
||||||
|
AviUtl,
|
||||||
|
AviUtl2,
|
||||||
|
Both,
|
||||||
|
}
|
||||||
|
|
||||||
|
internal static class AviUtlEngineExtensions
|
||||||
|
{
|
||||||
|
public static bool Includes(this AviUtlEngine scope, AviUtlEngine target) =>
|
||||||
|
scope == AviUtlEngine.Both || scope == target;
|
||||||
|
|
||||||
|
public static bool TryParse(string? value, out AviUtlEngine engine)
|
||||||
|
{
|
||||||
|
switch (value)
|
||||||
|
{
|
||||||
|
case "aviutl":
|
||||||
|
engine = AviUtlEngine.AviUtl;
|
||||||
|
return true;
|
||||||
|
case "aviutl2":
|
||||||
|
engine = AviUtlEngine.AviUtl2;
|
||||||
|
return true;
|
||||||
|
case "both":
|
||||||
|
engine = AviUtlEngine.Both;
|
||||||
|
return true;
|
||||||
|
default:
|
||||||
|
engine = AviUtlEngine.AviUtl;
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -49,13 +49,13 @@ namespace LuaScript.Compat
|
|||||||
int sectionEnd = lines.Length;
|
int sectionEnd = lines.Length;
|
||||||
for (int i = 0; i < lines.Length; i++)
|
for (int i = 0; i < lines.Length; i++)
|
||||||
{
|
{
|
||||||
if (!IsSectionHeader(lines[i]))
|
if (!ScriptParserHelper.IsSectionHeader(lines[i]))
|
||||||
continue;
|
continue;
|
||||||
sectionStart = i + 1;
|
sectionStart = i + 1;
|
||||||
sectionEnd = lines.Length;
|
sectionEnd = lines.Length;
|
||||||
for (int j = sectionStart; j < lines.Length; j++)
|
for (int j = sectionStart; j < lines.Length; j++)
|
||||||
{
|
{
|
||||||
if (IsSectionHeader(lines[j]))
|
if (ScriptParserHelper.IsSectionHeader(lines[j]))
|
||||||
{
|
{
|
||||||
sectionEnd = j;
|
sectionEnd = j;
|
||||||
break;
|
break;
|
||||||
@@ -72,7 +72,7 @@ namespace LuaScript.Compat
|
|||||||
|
|
||||||
private void ParseLine(string line)
|
private void ParseLine(string line)
|
||||||
{
|
{
|
||||||
int i = SkipSpaces(line, 0);
|
int i = ScriptParserHelper.SkipSpaces(line, 0);
|
||||||
if (i + 1 >= line.Length || line[i] != '-' || line[i + 1] != '-')
|
if (i + 1 >= line.Length || line[i] != '-' || line[i + 1] != '-')
|
||||||
return;
|
return;
|
||||||
i += 2;
|
i += 2;
|
||||||
@@ -80,7 +80,7 @@ namespace LuaScript.Compat
|
|||||||
return;
|
return;
|
||||||
|
|
||||||
int nameStart = i;
|
int nameStart = i;
|
||||||
while (i < line.Length && IsNameChar(line[i]))
|
while (i < line.Length && ScriptParserHelper.IsNameChar(line[i]))
|
||||||
i++;
|
i++;
|
||||||
if (i >= line.Length || line[i] != ':')
|
if (i >= line.Length || line[i] != ':')
|
||||||
return;
|
return;
|
||||||
@@ -174,27 +174,11 @@ namespace LuaScript.Compat
|
|||||||
|
|
||||||
private static string FirstToken(string content)
|
private static string FirstToken(string content)
|
||||||
{
|
{
|
||||||
int start = SkipSpaces(content, 0);
|
int start = ScriptParserHelper.SkipSpaces(content, 0);
|
||||||
int i = start;
|
int i = start;
|
||||||
while (i < content.Length && content[i] != ',' && content[i] != ' ' && content[i] != '\t')
|
while (i < content.Length && content[i] != ',' && content[i] != ' ' && content[i] != '\t')
|
||||||
i++;
|
i++;
|
||||||
return content.Substring(start, i - start);
|
return content.Substring(start, i - start);
|
||||||
}
|
}
|
||||||
|
|
||||||
private static bool IsSectionHeader(string line)
|
|
||||||
{
|
|
||||||
int i = SkipSpaces(line, 0);
|
|
||||||
return i < line.Length && line[i] == '@';
|
|
||||||
}
|
|
||||||
|
|
||||||
private static int SkipSpaces(string text, int index)
|
|
||||||
{
|
|
||||||
while (index < text.Length && (text[index] == ' ' || text[index] == '\t'))
|
|
||||||
index++;
|
|
||||||
return index;
|
|
||||||
}
|
|
||||||
|
|
||||||
private static bool IsNameChar(char c) =>
|
|
||||||
(c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z') || (c >= '0' && c <= '9');
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -13,10 +13,12 @@ namespace LuaScript.Compat
|
|||||||
Param,
|
Param,
|
||||||
}
|
}
|
||||||
|
|
||||||
public static string Transform(string source)
|
public static string Transform(string source) => TransformWithMap(source).Code;
|
||||||
|
|
||||||
|
public static (string Code, int[] LineMap) TransformWithMap(string source)
|
||||||
{
|
{
|
||||||
if (string.IsNullOrEmpty(source))
|
if (string.IsNullOrEmpty(source))
|
||||||
return source;
|
return (source, []);
|
||||||
|
|
||||||
var lines = source.Replace("\r\n", "\n").Replace("\r", "\n").Split('\n');
|
var lines = source.Replace("\r\n", "\n").Replace("\r", "\n").Split('\n');
|
||||||
|
|
||||||
@@ -26,7 +28,7 @@ namespace LuaScript.Compat
|
|||||||
|
|
||||||
for (int i = 0; i < lines.Length; i++)
|
for (int i = 0; i < lines.Length; i++)
|
||||||
{
|
{
|
||||||
if (!IsSectionHeader(lines[i]))
|
if (!ScriptParserHelper.IsSectionHeader(lines[i]))
|
||||||
continue;
|
continue;
|
||||||
|
|
||||||
hasSection = true;
|
hasSection = true;
|
||||||
@@ -34,7 +36,7 @@ namespace LuaScript.Compat
|
|||||||
sectionEnd = lines.Length;
|
sectionEnd = lines.Length;
|
||||||
for (int j = sectionStart; j < lines.Length; j++)
|
for (int j = sectionStart; j < lines.Length; j++)
|
||||||
{
|
{
|
||||||
if (IsSectionHeader(lines[j]))
|
if (ScriptParserHelper.IsSectionHeader(lines[j]))
|
||||||
{
|
{
|
||||||
sectionEnd = j;
|
sectionEnd = j;
|
||||||
break;
|
break;
|
||||||
@@ -48,26 +50,29 @@ namespace LuaScript.Compat
|
|||||||
AppendDeclarations(lines[i], prelude);
|
AppendDeclarations(lines[i], prelude);
|
||||||
|
|
||||||
if (!hasSection && prelude.Count == 0)
|
if (!hasSection && prelude.Count == 0)
|
||||||
return source;
|
return (source, []);
|
||||||
|
|
||||||
var builder = new StringBuilder(source.Length + 64);
|
var builder = new StringBuilder(source.Length + 64);
|
||||||
|
var lineMap = new int[prelude.Count + (sectionEnd - sectionStart)];
|
||||||
|
int row = 0;
|
||||||
|
|
||||||
foreach (var declaration in prelude)
|
foreach (var declaration in prelude)
|
||||||
|
{
|
||||||
builder.Append(declaration).Append('\n');
|
builder.Append(declaration).Append('\n');
|
||||||
|
lineMap[row++] = -1;
|
||||||
|
}
|
||||||
for (int i = sectionStart; i < sectionEnd; i++)
|
for (int i = sectionStart; i < sectionEnd; i++)
|
||||||
|
{
|
||||||
builder.Append(lines[i]).Append('\n');
|
builder.Append(lines[i]).Append('\n');
|
||||||
|
lineMap[row++] = i;
|
||||||
|
}
|
||||||
|
|
||||||
return builder.ToString();
|
return (builder.ToString(), lineMap);
|
||||||
}
|
|
||||||
|
|
||||||
private static bool IsSectionHeader(string line)
|
|
||||||
{
|
|
||||||
int i = SkipSpaces(line, 0);
|
|
||||||
return i < line.Length && line[i] == '@';
|
|
||||||
}
|
}
|
||||||
|
|
||||||
private static void AppendDeclarations(string line, List<string> prelude)
|
private static void AppendDeclarations(string line, List<string> prelude)
|
||||||
{
|
{
|
||||||
int i = SkipSpaces(line, 0);
|
int i = ScriptParserHelper.SkipSpaces(line, 0);
|
||||||
if (i + 1 >= line.Length || line[i] != '-' || line[i + 1] != '-')
|
if (i + 1 >= line.Length || line[i] != '-' || line[i + 1] != '-')
|
||||||
return;
|
return;
|
||||||
i += 2;
|
i += 2;
|
||||||
@@ -75,7 +80,7 @@ namespace LuaScript.Compat
|
|||||||
return;
|
return;
|
||||||
|
|
||||||
int nameStart = i;
|
int nameStart = i;
|
||||||
while (i < line.Length && IsNameChar(line[i]))
|
while (i < line.Length && ScriptParserHelper.IsNameChar(line[i]))
|
||||||
i++;
|
i++;
|
||||||
if (i >= line.Length || line[i] != ':')
|
if (i >= line.Length || line[i] != ':')
|
||||||
return;
|
return;
|
||||||
@@ -125,15 +130,5 @@ namespace LuaScript.Compat
|
|||||||
if (trimmed.Length != 0)
|
if (trimmed.Length != 0)
|
||||||
prelude.Add(trimmed);
|
prelude.Add(trimmed);
|
||||||
}
|
}
|
||||||
|
|
||||||
private static int SkipSpaces(string text, int index)
|
|
||||||
{
|
|
||||||
while (index < text.Length && (text[index] == ' ' || text[index] == '\t'))
|
|
||||||
index++;
|
|
||||||
return index;
|
|
||||||
}
|
|
||||||
|
|
||||||
private static bool IsNameChar(char c) =>
|
|
||||||
(c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z') || (c >= '0' && c <= '9');
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -0,0 +1,76 @@
|
|||||||
|
using System;
|
||||||
|
using System.Collections.Generic;
|
||||||
|
using LuaScript.Engine.Kernel;
|
||||||
|
|
||||||
|
namespace LuaScript.Compat
|
||||||
|
{
|
||||||
|
internal readonly struct ScriptParameterUsage
|
||||||
|
{
|
||||||
|
private readonly HashSet<string>? _members;
|
||||||
|
private readonly bool _color;
|
||||||
|
|
||||||
|
private ScriptParameterUsage(HashSet<string>? members, bool color)
|
||||||
|
{
|
||||||
|
_members = members;
|
||||||
|
_color = color;
|
||||||
|
}
|
||||||
|
|
||||||
|
public static readonly ScriptParameterUsage None = default;
|
||||||
|
|
||||||
|
public bool Color => _color;
|
||||||
|
|
||||||
|
public bool Uses(string member) => _members is not null && _members.Contains(member);
|
||||||
|
|
||||||
|
public bool Check0 => Uses("check0");
|
||||||
|
public bool Check1 => Uses("check1");
|
||||||
|
public bool Check2 => Uses("check2");
|
||||||
|
public bool Check3 => Uses("check3");
|
||||||
|
|
||||||
|
public bool Check(int index) => (uint)index < 4 && Uses("check" + (char)('0' + index));
|
||||||
|
|
||||||
|
public bool Slider(int index) => (uint)index < 4 && Uses("slider" + (char)('0' + index));
|
||||||
|
|
||||||
|
public static ScriptParameterUsage Detect(string? script)
|
||||||
|
{
|
||||||
|
if (string.IsNullOrEmpty(script))
|
||||||
|
return None;
|
||||||
|
|
||||||
|
List<LuaToken> tokens;
|
||||||
|
try
|
||||||
|
{
|
||||||
|
tokens = LuaLexer.Tokenize(script);
|
||||||
|
}
|
||||||
|
catch (KernelUnsupportedException)
|
||||||
|
{
|
||||||
|
return None;
|
||||||
|
}
|
||||||
|
|
||||||
|
HashSet<string>? members = null;
|
||||||
|
bool color = false;
|
||||||
|
|
||||||
|
for (int i = 0; i < tokens.Count; i++)
|
||||||
|
{
|
||||||
|
var token = tokens[i];
|
||||||
|
if (token.Kind != LuaTokenKind.Name)
|
||||||
|
continue;
|
||||||
|
|
||||||
|
if (token.Text == "color")
|
||||||
|
{
|
||||||
|
if (i == 0 || !tokens[i - 1].IsSymbol("."))
|
||||||
|
color = true;
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (token.Text == "obj" &&
|
||||||
|
i + 2 < tokens.Count &&
|
||||||
|
tokens[i + 1].IsSymbol(".") &&
|
||||||
|
tokens[i + 2].Kind == LuaTokenKind.Name)
|
||||||
|
{
|
||||||
|
(members ??= new HashSet<string>(StringComparer.Ordinal)).Add(tokens[i + 2].Text);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return new ScriptParameterUsage(members, color);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,21 @@
|
|||||||
|
namespace LuaScript.Compat
|
||||||
|
{
|
||||||
|
internal static class ScriptParserHelper
|
||||||
|
{
|
||||||
|
public static bool IsSectionHeader(string line)
|
||||||
|
{
|
||||||
|
int i = SkipSpaces(line, 0);
|
||||||
|
return i < line.Length && line[i] == '@';
|
||||||
|
}
|
||||||
|
|
||||||
|
public static int SkipSpaces(string text, int index)
|
||||||
|
{
|
||||||
|
while (index < text.Length && (text[index] == ' ' || text[index] == '\t'))
|
||||||
|
index++;
|
||||||
|
return index;
|
||||||
|
}
|
||||||
|
|
||||||
|
public static bool IsNameChar(char c) =>
|
||||||
|
(c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z') || (c >= '0' && c <= '9');
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,42 @@
|
|||||||
|
using System;
|
||||||
|
using System.Text.RegularExpressions;
|
||||||
|
|
||||||
|
namespace LuaScript.Diagnostics
|
||||||
|
{
|
||||||
|
internal enum LuaScriptDiagnosticKind
|
||||||
|
{
|
||||||
|
Compile,
|
||||||
|
Runtime,
|
||||||
|
Timeout,
|
||||||
|
}
|
||||||
|
|
||||||
|
internal readonly record struct LuaScriptDiagnostic(
|
||||||
|
LuaScriptDiagnosticKind Kind,
|
||||||
|
int Line,
|
||||||
|
int Column,
|
||||||
|
int Length,
|
||||||
|
string Message);
|
||||||
|
|
||||||
|
internal static partial class LuaScriptDiagnosticParser
|
||||||
|
{
|
||||||
|
[GeneratedRegex(@"^LuaScript:\((\d+),(\d+)(?:-(\d+)(?:,(\d+))?)?\):\s*", RegexOptions.None)]
|
||||||
|
private static partial Regex LocationPattern();
|
||||||
|
|
||||||
|
public static LuaScriptDiagnostic Parse(LuaScriptDiagnosticKind kind, string? message)
|
||||||
|
{
|
||||||
|
var text = message ?? string.Empty;
|
||||||
|
var match = LocationPattern().Match(text);
|
||||||
|
if (!match.Success)
|
||||||
|
return new LuaScriptDiagnostic(kind, 0, 0, 0, text.Trim());
|
||||||
|
|
||||||
|
int line = int.Parse(match.Groups[1].Value);
|
||||||
|
int columnStart = int.Parse(match.Groups[2].Value);
|
||||||
|
|
||||||
|
int length = 0;
|
||||||
|
if (match.Groups[3].Success && !match.Groups[4].Success)
|
||||||
|
length = Math.Max(0, int.Parse(match.Groups[3].Value) - columnStart);
|
||||||
|
|
||||||
|
return new LuaScriptDiagnostic(kind, line, columnStart + 1, length, text[match.Length..].Trim());
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,263 @@
|
|||||||
|
using System;
|
||||||
|
using System.Collections.Generic;
|
||||||
|
using System.Reflection;
|
||||||
|
using System.Windows;
|
||||||
|
using System.Windows.Controls;
|
||||||
|
using System.Windows.Controls.Primitives;
|
||||||
|
using System.Windows.Input;
|
||||||
|
using System.Windows.Media;
|
||||||
|
using ICSharpCode.AvalonEdit.Document;
|
||||||
|
using ICSharpCode.AvalonEdit.Folding;
|
||||||
|
using ICSharpCode.AvalonEdit.Rendering;
|
||||||
|
|
||||||
|
namespace LuaScript.Diagnostics
|
||||||
|
{
|
||||||
|
internal sealed class LuaScriptDiagnosticOverlay : IBackgroundRenderer, ILuaScriptDiagnosticsListener
|
||||||
|
{
|
||||||
|
private static readonly FieldInfo? s_textViewsField = ResolveTextViewsField();
|
||||||
|
|
||||||
|
private static readonly Pen s_squigglePen = CreateSquigglePen();
|
||||||
|
|
||||||
|
private sealed class Marker : ISegment
|
||||||
|
{
|
||||||
|
public required int Offset { get; init; }
|
||||||
|
public required int Length { get; init; }
|
||||||
|
public int EndOffset => Offset + Length;
|
||||||
|
public required LuaScriptDiagnostic Diagnostic { get; init; }
|
||||||
|
}
|
||||||
|
|
||||||
|
private readonly TextView _textView;
|
||||||
|
private readonly ToolTip _toolTip = new() { Placement = PlacementMode.Mouse };
|
||||||
|
private readonly List<Marker> _markers = [];
|
||||||
|
private object? _renderedText;
|
||||||
|
private bool _isDirty = true;
|
||||||
|
|
||||||
|
public static void Attach(FoldingManager manager)
|
||||||
|
{
|
||||||
|
var textView = ResolveTextView(manager);
|
||||||
|
if (textView is null)
|
||||||
|
return;
|
||||||
|
|
||||||
|
foreach (var renderer in textView.BackgroundRenderers)
|
||||||
|
{
|
||||||
|
if (renderer is LuaScriptDiagnosticOverlay)
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
_ = new LuaScriptDiagnosticOverlay(textView);
|
||||||
|
}
|
||||||
|
|
||||||
|
private LuaScriptDiagnosticOverlay(TextView textView)
|
||||||
|
{
|
||||||
|
_textView = textView;
|
||||||
|
textView.BackgroundRenderers.Add(this);
|
||||||
|
textView.MouseHover += OnMouseHover;
|
||||||
|
textView.MouseHoverStopped += OnMouseHoverStopped;
|
||||||
|
LuaScriptDiagnostics.Instance.Subscribe(this);
|
||||||
|
}
|
||||||
|
|
||||||
|
public KnownLayer Layer => KnownLayer.Selection;
|
||||||
|
|
||||||
|
public void OnDiagnosticsChanged()
|
||||||
|
{
|
||||||
|
_textView.Dispatcher.BeginInvoke(() =>
|
||||||
|
{
|
||||||
|
_isDirty = true;
|
||||||
|
_textView.InvalidateLayer(KnownLayer.Selection);
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
public void Draw(TextView textView, DrawingContext drawingContext)
|
||||||
|
{
|
||||||
|
var document = textView.Document;
|
||||||
|
if (document is null)
|
||||||
|
return;
|
||||||
|
|
||||||
|
if (_isDirty || !ReferenceEquals(document.Text, _renderedText))
|
||||||
|
Rebuild(document);
|
||||||
|
|
||||||
|
if (_markers.Count == 0 || !textView.VisualLinesValid)
|
||||||
|
return;
|
||||||
|
|
||||||
|
foreach (var marker in _markers)
|
||||||
|
{
|
||||||
|
foreach (var rect in BackgroundGeometryBuilder.GetRectsForSegment(textView, marker, false))
|
||||||
|
DrawSquiggle(drawingContext, rect);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private void Rebuild(TextDocument document)
|
||||||
|
{
|
||||||
|
_isDirty = false;
|
||||||
|
_renderedText = document.Text;
|
||||||
|
_markers.Clear();
|
||||||
|
|
||||||
|
foreach (var diagnostic in LuaScriptDiagnostics.Instance.Get(document.Text))
|
||||||
|
{
|
||||||
|
if (TryCreateMarker(document, diagnostic, out var marker))
|
||||||
|
_markers.Add(marker);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private static bool TryCreateMarker(TextDocument document, LuaScriptDiagnostic diagnostic, out Marker marker)
|
||||||
|
{
|
||||||
|
marker = null!;
|
||||||
|
|
||||||
|
int lineNumber = diagnostic.Line > 0 ? diagnostic.Line : 1;
|
||||||
|
if (lineNumber > document.LineCount)
|
||||||
|
return false;
|
||||||
|
|
||||||
|
var line = document.GetLineByNumber(lineNumber);
|
||||||
|
|
||||||
|
int offset;
|
||||||
|
int length;
|
||||||
|
if (diagnostic.Line > 0 && diagnostic.Column > 0 && diagnostic.Length > 0)
|
||||||
|
{
|
||||||
|
offset = Math.Min(line.Offset + diagnostic.Column - 1, line.EndOffset);
|
||||||
|
length = Math.Min(diagnostic.Length, line.EndOffset - offset);
|
||||||
|
}
|
||||||
|
else
|
||||||
|
{
|
||||||
|
offset = SkipLeadingWhitespace(document, line);
|
||||||
|
length = line.EndOffset - offset;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (length <= 0)
|
||||||
|
{
|
||||||
|
if (line.Length == 0)
|
||||||
|
return false;
|
||||||
|
offset = line.Offset;
|
||||||
|
length = line.Length;
|
||||||
|
}
|
||||||
|
|
||||||
|
marker = new Marker { Offset = offset, Length = length, Diagnostic = diagnostic };
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
|
||||||
|
private static int SkipLeadingWhitespace(TextDocument document, DocumentLine line)
|
||||||
|
{
|
||||||
|
int offset = line.Offset;
|
||||||
|
while (offset < line.EndOffset)
|
||||||
|
{
|
||||||
|
char c = document.GetCharAt(offset);
|
||||||
|
if (c != ' ' && c != '\t')
|
||||||
|
break;
|
||||||
|
offset++;
|
||||||
|
}
|
||||||
|
return offset;
|
||||||
|
}
|
||||||
|
|
||||||
|
private void OnMouseHover(object? sender, MouseEventArgs e)
|
||||||
|
{
|
||||||
|
var document = _textView.Document;
|
||||||
|
if (document is null)
|
||||||
|
return;
|
||||||
|
|
||||||
|
var position = _textView.GetPositionFloor(e.GetPosition(_textView) + _textView.ScrollOffset);
|
||||||
|
if (position is null)
|
||||||
|
return;
|
||||||
|
|
||||||
|
int offset = document.GetOffset(position.Value.Location);
|
||||||
|
foreach (var marker in _markers)
|
||||||
|
{
|
||||||
|
if (offset < marker.Offset || offset > marker.EndOffset)
|
||||||
|
continue;
|
||||||
|
|
||||||
|
_toolTip.Content = BuildToolTipContent(marker.Diagnostic);
|
||||||
|
_toolTip.IsOpen = true;
|
||||||
|
e.Handled = true;
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private void OnMouseHoverStopped(object? sender, MouseEventArgs e)
|
||||||
|
{
|
||||||
|
_toolTip.IsOpen = false;
|
||||||
|
}
|
||||||
|
|
||||||
|
private static object BuildToolTipContent(LuaScriptDiagnostic diagnostic)
|
||||||
|
{
|
||||||
|
var panel = new StackPanel { MaxWidth = 480 };
|
||||||
|
panel.Children.Add(new TextBlock { Text = KindLabel(diagnostic.Kind), FontWeight = FontWeights.Bold });
|
||||||
|
if (!string.IsNullOrEmpty(diagnostic.Message))
|
||||||
|
panel.Children.Add(new TextBlock { Text = diagnostic.Message, TextWrapping = TextWrapping.Wrap });
|
||||||
|
return panel;
|
||||||
|
}
|
||||||
|
|
||||||
|
private static string KindLabel(LuaScriptDiagnosticKind kind) => kind switch
|
||||||
|
{
|
||||||
|
LuaScriptDiagnosticKind.Compile => Texts.DiagnosticCompile,
|
||||||
|
LuaScriptDiagnosticKind.Timeout => Texts.DiagnosticTimeout,
|
||||||
|
_ => Texts.DiagnosticRuntime,
|
||||||
|
};
|
||||||
|
|
||||||
|
private static void DrawSquiggle(DrawingContext drawingContext, Rect rect)
|
||||||
|
{
|
||||||
|
if (rect.Width <= 0)
|
||||||
|
return;
|
||||||
|
|
||||||
|
const double step = 3.0;
|
||||||
|
double baseline = rect.Bottom - 0.5;
|
||||||
|
|
||||||
|
var geometry = new StreamGeometry();
|
||||||
|
using (var context = geometry.Open())
|
||||||
|
{
|
||||||
|
context.BeginFigure(new Point(rect.Left, baseline), false, false);
|
||||||
|
|
||||||
|
var points = new List<Point>();
|
||||||
|
int index = 0;
|
||||||
|
for (double x = rect.Left; x <= rect.Right; x += step)
|
||||||
|
{
|
||||||
|
points.Add(new Point(x, baseline - (index % 2 == 0 ? 0.0 : step)));
|
||||||
|
index++;
|
||||||
|
}
|
||||||
|
context.PolyLineTo(points, true, false);
|
||||||
|
}
|
||||||
|
geometry.Freeze();
|
||||||
|
|
||||||
|
drawingContext.DrawGeometry(null, s_squigglePen, geometry);
|
||||||
|
}
|
||||||
|
|
||||||
|
private static Pen CreateSquigglePen()
|
||||||
|
{
|
||||||
|
var pen = new Pen(new SolidColorBrush(Color.FromRgb(0xE5, 0x1A, 0x1A)), 1.0);
|
||||||
|
pen.Brush.Freeze();
|
||||||
|
pen.Freeze();
|
||||||
|
return pen;
|
||||||
|
}
|
||||||
|
|
||||||
|
private static FieldInfo? ResolveTextViewsField()
|
||||||
|
{
|
||||||
|
foreach (var field in typeof(FoldingManager).GetFields(BindingFlags.Instance | BindingFlags.NonPublic))
|
||||||
|
{
|
||||||
|
if (typeof(IEnumerable<TextView>).IsAssignableFrom(field.FieldType))
|
||||||
|
return field;
|
||||||
|
}
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
|
||||||
|
private static TextView? ResolveTextView(FoldingManager? manager)
|
||||||
|
{
|
||||||
|
if (manager is null || s_textViewsField is null)
|
||||||
|
return null;
|
||||||
|
|
||||||
|
try
|
||||||
|
{
|
||||||
|
if (s_textViewsField.GetValue(manager) is IEnumerable<TextView> views)
|
||||||
|
{
|
||||||
|
foreach (var view in views)
|
||||||
|
{
|
||||||
|
if (view is not null)
|
||||||
|
return view;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
catch
|
||||||
|
{
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,110 @@
|
|||||||
|
using System;
|
||||||
|
using System.Collections.Generic;
|
||||||
|
|
||||||
|
namespace LuaScript.Diagnostics
|
||||||
|
{
|
||||||
|
internal interface ILuaScriptDiagnosticsListener
|
||||||
|
{
|
||||||
|
void OnDiagnosticsChanged();
|
||||||
|
}
|
||||||
|
|
||||||
|
internal sealed class LuaScriptDiagnostics
|
||||||
|
{
|
||||||
|
public static LuaScriptDiagnostics Instance { get; } = new();
|
||||||
|
|
||||||
|
private const int MaxTrackedScripts = 64;
|
||||||
|
|
||||||
|
private readonly object _gate = new();
|
||||||
|
private readonly Dictionary<string, IReadOnlyList<LuaScriptDiagnostic>> _entries = new(StringComparer.Ordinal);
|
||||||
|
private readonly Queue<string> _insertionOrder = new();
|
||||||
|
private readonly List<WeakReference<ILuaScriptDiagnosticsListener>> _listeners = [];
|
||||||
|
|
||||||
|
private LuaScriptDiagnostics()
|
||||||
|
{
|
||||||
|
}
|
||||||
|
|
||||||
|
public void Subscribe(ILuaScriptDiagnosticsListener listener)
|
||||||
|
{
|
||||||
|
lock (_gate)
|
||||||
|
{
|
||||||
|
PruneDeadListeners();
|
||||||
|
_listeners.Add(new WeakReference<ILuaScriptDiagnosticsListener>(listener));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
public IReadOnlyList<LuaScriptDiagnostic> Get(string? script)
|
||||||
|
{
|
||||||
|
if (script is null)
|
||||||
|
return [];
|
||||||
|
|
||||||
|
lock (_gate)
|
||||||
|
return _entries.TryGetValue(script, out var diagnostics) ? diagnostics : [];
|
||||||
|
}
|
||||||
|
|
||||||
|
public void Report(string? script, IReadOnlyList<LuaScriptDiagnostic> diagnostics)
|
||||||
|
{
|
||||||
|
if (script is null)
|
||||||
|
return;
|
||||||
|
|
||||||
|
diagnostics ??= [];
|
||||||
|
|
||||||
|
ILuaScriptDiagnosticsListener[] targets;
|
||||||
|
lock (_gate)
|
||||||
|
{
|
||||||
|
if (_entries.TryGetValue(script, out var existing) && AreEqual(existing, diagnostics))
|
||||||
|
return;
|
||||||
|
|
||||||
|
if (!_entries.ContainsKey(script))
|
||||||
|
_insertionOrder.Enqueue(script);
|
||||||
|
|
||||||
|
_entries[script] = diagnostics;
|
||||||
|
|
||||||
|
while (_entries.Count > MaxTrackedScripts && _insertionOrder.Count > 0)
|
||||||
|
{
|
||||||
|
var oldest = _insertionOrder.Dequeue();
|
||||||
|
if (!string.Equals(oldest, script, StringComparison.Ordinal))
|
||||||
|
_entries.Remove(oldest);
|
||||||
|
}
|
||||||
|
|
||||||
|
targets = CollectLiveListeners();
|
||||||
|
}
|
||||||
|
|
||||||
|
foreach (var target in targets)
|
||||||
|
target.OnDiagnosticsChanged();
|
||||||
|
}
|
||||||
|
|
||||||
|
private ILuaScriptDiagnosticsListener[] CollectLiveListeners()
|
||||||
|
{
|
||||||
|
var live = new List<ILuaScriptDiagnosticsListener>(_listeners.Count);
|
||||||
|
for (int i = _listeners.Count - 1; i >= 0; i--)
|
||||||
|
{
|
||||||
|
if (_listeners[i].TryGetTarget(out var listener))
|
||||||
|
live.Add(listener);
|
||||||
|
else
|
||||||
|
_listeners.RemoveAt(i);
|
||||||
|
}
|
||||||
|
return [.. live];
|
||||||
|
}
|
||||||
|
|
||||||
|
private void PruneDeadListeners()
|
||||||
|
{
|
||||||
|
for (int i = _listeners.Count - 1; i >= 0; i--)
|
||||||
|
{
|
||||||
|
if (!_listeners[i].TryGetTarget(out _))
|
||||||
|
_listeners.RemoveAt(i);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private static bool AreEqual(IReadOnlyList<LuaScriptDiagnostic> a, IReadOnlyList<LuaScriptDiagnostic> b)
|
||||||
|
{
|
||||||
|
if (a.Count != b.Count)
|
||||||
|
return false;
|
||||||
|
for (int i = 0; i < a.Count; i++)
|
||||||
|
{
|
||||||
|
if (!a[i].Equals(b[i]))
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,12 @@
|
|||||||
|
namespace LuaScript
|
||||||
|
{
|
||||||
|
internal readonly record struct DrawCommand(
|
||||||
|
double Ox,
|
||||||
|
double Oy,
|
||||||
|
double Oz,
|
||||||
|
double Zoom,
|
||||||
|
double Alpha,
|
||||||
|
double Aspect,
|
||||||
|
double[]? Poly = null,
|
||||||
|
double Antialias = 1d);
|
||||||
|
}
|
||||||
@@ -0,0 +1,149 @@
|
|||||||
|
using System;
|
||||||
|
using System.Collections.Generic;
|
||||||
|
using System.Numerics;
|
||||||
|
using Vortice.Direct2D1;
|
||||||
|
using Vortice.Direct2D1.Effects;
|
||||||
|
using YukkuriMovieMaker.Commons;
|
||||||
|
|
||||||
|
namespace LuaScript
|
||||||
|
{
|
||||||
|
internal sealed class DrawCompositor : IDisposable
|
||||||
|
{
|
||||||
|
private const int MaxDimension = 8192;
|
||||||
|
|
||||||
|
private readonly GraphicsDevicesAndContext _ctx;
|
||||||
|
private ID2D1Bitmap1? _source;
|
||||||
|
private ID2D1Bitmap1? _target;
|
||||||
|
private AffineTransform2D? _placement;
|
||||||
|
private int _sourceWidth;
|
||||||
|
private int _sourceHeight;
|
||||||
|
private int _targetWidth;
|
||||||
|
private int _targetHeight;
|
||||||
|
|
||||||
|
public DrawCompositor(GraphicsDevicesAndContext ctx)
|
||||||
|
{
|
||||||
|
_ctx = ctx;
|
||||||
|
}
|
||||||
|
|
||||||
|
public unsafe ID2D1Image Compose(byte[] pixels, int width, int height, IReadOnlyList<DrawCommand> commands)
|
||||||
|
{
|
||||||
|
EnsureSource(width, height);
|
||||||
|
fixed (byte* ptr = pixels)
|
||||||
|
_source!.CopyFromMemory(new nint(ptr), width * 4);
|
||||||
|
|
||||||
|
double minX = double.MaxValue, minY = double.MaxValue;
|
||||||
|
double maxX = double.MinValue, maxY = double.MinValue;
|
||||||
|
for (int i = 0; i < commands.Count; i++)
|
||||||
|
{
|
||||||
|
var cmd = commands[i];
|
||||||
|
if (cmd.Poly is { } poly)
|
||||||
|
{
|
||||||
|
DrawPolyMath.Bounds(poly, out double pMinX, out double pMinY, out double pMaxX, out double pMaxY);
|
||||||
|
minX = Math.Min(minX, pMinX);
|
||||||
|
maxX = Math.Max(maxX, pMaxX);
|
||||||
|
minY = Math.Min(minY, pMinY);
|
||||||
|
maxY = Math.Max(maxY, pMaxY);
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
double aspect = Math.Clamp(cmd.Aspect, -1d, 1d);
|
||||||
|
double zx = cmd.Zoom * (1d + aspect);
|
||||||
|
double zy = cmd.Zoom * (1d - aspect);
|
||||||
|
double halfW = width * 0.5 * zx;
|
||||||
|
double halfH = height * 0.5 * zy;
|
||||||
|
minX = Math.Min(minX, cmd.Ox - halfW);
|
||||||
|
maxX = Math.Max(maxX, cmd.Ox + halfW);
|
||||||
|
minY = Math.Min(minY, cmd.Oy - halfH);
|
||||||
|
maxY = Math.Max(maxY, cmd.Oy + halfH);
|
||||||
|
}
|
||||||
|
|
||||||
|
int originX = (int)Math.Floor(minX);
|
||||||
|
int originY = (int)Math.Floor(minY);
|
||||||
|
int targetW = Math.Clamp((int)Math.Ceiling(maxX) - originX, 1, MaxDimension);
|
||||||
|
int targetH = Math.Clamp((int)Math.Ceiling(maxY) - originY, 1, MaxDimension);
|
||||||
|
|
||||||
|
EnsureTarget(targetW, targetH);
|
||||||
|
|
||||||
|
var dc = _ctx.DeviceContext;
|
||||||
|
var rt = (ID2D1RenderTarget)dc;
|
||||||
|
var savedTarget = dc.Target;
|
||||||
|
|
||||||
|
dc.Target = _target;
|
||||||
|
dc.BeginDraw();
|
||||||
|
dc.Clear(null);
|
||||||
|
var toTarget = Matrix3x2.CreateTranslation(-originX, -originY);
|
||||||
|
for (int i = 0; i < commands.Count; i++)
|
||||||
|
{
|
||||||
|
var cmd = commands[i];
|
||||||
|
var interpolation = cmd.Antialias != 0d
|
||||||
|
? BitmapInterpolationMode.Linear
|
||||||
|
: BitmapInterpolationMode.NearestNeighbor;
|
||||||
|
|
||||||
|
if (cmd.Poly is { } poly)
|
||||||
|
{
|
||||||
|
if (!DrawPolyMath.TrySolveAffine(poly, out var affine))
|
||||||
|
continue;
|
||||||
|
rt.Transform = affine * toTarget;
|
||||||
|
rt.DrawBitmap(_source, (float)Math.Clamp(poly[20], 0d, 1d), interpolation);
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
|
||||||
|
double aspect = Math.Clamp(cmd.Aspect, -1d, 1d);
|
||||||
|
float zx = (float)(cmd.Zoom * (1d + aspect));
|
||||||
|
float zy = (float)(cmd.Zoom * (1d - aspect));
|
||||||
|
float opacity = (float)Math.Clamp(cmd.Alpha, 0d, 1d);
|
||||||
|
|
||||||
|
var matrix =
|
||||||
|
Matrix3x2.CreateTranslation(-width * 0.5f, -height * 0.5f) *
|
||||||
|
Matrix3x2.CreateScale(zx, zy) *
|
||||||
|
Matrix3x2.CreateTranslation((float)(cmd.Ox - originX), (float)(cmd.Oy - originY));
|
||||||
|
|
||||||
|
rt.Transform = matrix;
|
||||||
|
rt.DrawBitmap(_source, opacity, interpolation);
|
||||||
|
}
|
||||||
|
rt.Transform = Matrix3x2.Identity;
|
||||||
|
dc.EndDraw();
|
||||||
|
dc.Target = savedTarget;
|
||||||
|
|
||||||
|
_placement!.TransformMatrix = Matrix3x2.CreateTranslation(originX, originY);
|
||||||
|
return _placement.Output;
|
||||||
|
}
|
||||||
|
|
||||||
|
private void EnsureSource(int width, int height)
|
||||||
|
{
|
||||||
|
if (_source is not null && _sourceWidth == width && _sourceHeight == height)
|
||||||
|
return;
|
||||||
|
|
||||||
|
_source?.Dispose();
|
||||||
|
_source = _ctx.DeviceContext.CreateEmptyBitmap(width, height, BitmapOptions.Target);
|
||||||
|
_sourceWidth = width;
|
||||||
|
_sourceHeight = height;
|
||||||
|
}
|
||||||
|
|
||||||
|
private void EnsureTarget(int width, int height)
|
||||||
|
{
|
||||||
|
if (_target is not null && _targetWidth == width && _targetHeight == height)
|
||||||
|
return;
|
||||||
|
|
||||||
|
_placement?.Dispose();
|
||||||
|
_target?.Dispose();
|
||||||
|
_placement = null;
|
||||||
|
|
||||||
|
_target = _ctx.DeviceContext.CreateEmptyBitmap(width, height, BitmapOptions.Target);
|
||||||
|
_targetWidth = width;
|
||||||
|
_targetHeight = height;
|
||||||
|
|
||||||
|
_placement = new AffineTransform2D(_ctx.DeviceContext);
|
||||||
|
_placement.SetInput(0, _target, true);
|
||||||
|
}
|
||||||
|
|
||||||
|
public void Dispose()
|
||||||
|
{
|
||||||
|
_placement?.Dispose();
|
||||||
|
_source?.Dispose();
|
||||||
|
_target?.Dispose();
|
||||||
|
_placement = null;
|
||||||
|
_source = null;
|
||||||
|
_target = null;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,53 @@
|
|||||||
|
using System;
|
||||||
|
using System.Numerics;
|
||||||
|
|
||||||
|
namespace LuaScript
|
||||||
|
{
|
||||||
|
internal static class DrawPolyMath
|
||||||
|
{
|
||||||
|
public const int Length = 21;
|
||||||
|
|
||||||
|
public static bool TrySolveAffine(double[] poly, out Matrix3x2 matrix)
|
||||||
|
{
|
||||||
|
double x0 = poly[0], y0 = poly[1];
|
||||||
|
double x1 = poly[3], y1 = poly[4];
|
||||||
|
double x3 = poly[9], y3 = poly[10];
|
||||||
|
double u0 = poly[12], v0 = poly[13];
|
||||||
|
double u1 = poly[14], v1 = poly[15];
|
||||||
|
double u3 = poly[18], v3 = poly[19];
|
||||||
|
|
||||||
|
double det = u0 * (v1 - v3) - v0 * (u1 - u3) + (u1 * v3 - v1 * u3);
|
||||||
|
if (Math.Abs(det) < 1e-9)
|
||||||
|
{
|
||||||
|
matrix = Matrix3x2.Identity;
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
|
double inv = 1d / det;
|
||||||
|
double a = (x0 * (v1 - v3) - v0 * (x1 - x3) + (x1 * v3 - v1 * x3)) * inv;
|
||||||
|
double b = (u0 * (x1 - x3) - x0 * (u1 - u3) + (u1 * x3 - x1 * u3)) * inv;
|
||||||
|
double c = (u0 * (v1 * x3 - x1 * v3) - v0 * (u1 * x3 - x1 * u3) + x0 * (u1 * v3 - v1 * u3)) * inv;
|
||||||
|
double d = (y0 * (v1 - v3) - v0 * (y1 - y3) + (y1 * v3 - v1 * y3)) * inv;
|
||||||
|
double e = (u0 * (y1 - y3) - y0 * (u1 - u3) + (u1 * y3 - y1 * u3)) * inv;
|
||||||
|
double f = (u0 * (v1 * y3 - y1 * v3) - v0 * (u1 * y3 - y1 * u3) + y0 * (u1 * v3 - v1 * u3)) * inv;
|
||||||
|
|
||||||
|
matrix = new Matrix3x2((float)a, (float)d, (float)b, (float)e, (float)c, (float)f);
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
|
||||||
|
public static void Bounds(double[] poly, out double minX, out double minY, out double maxX, out double maxY)
|
||||||
|
{
|
||||||
|
minX = minY = double.MaxValue;
|
||||||
|
maxX = maxY = double.MinValue;
|
||||||
|
for (int i = 0; i < 4; i++)
|
||||||
|
{
|
||||||
|
double x = poly[i * 3];
|
||||||
|
double y = poly[i * 3 + 1];
|
||||||
|
if (x < minX) minX = x;
|
||||||
|
if (x > maxX) maxX = x;
|
||||||
|
if (y < minY) minY = y;
|
||||||
|
if (y > maxY) maxY = y;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,28 @@
|
|||||||
|
using System.Threading.Tasks;
|
||||||
|
|
||||||
|
namespace LuaScript.Engine.Kernel
|
||||||
|
{
|
||||||
|
internal sealed class CpuKernel(CpuKernel.RowDelegate row)
|
||||||
|
{
|
||||||
|
public delegate void RowDelegate(byte[] buffer, int width, int rowBase, double y, double[] uniforms);
|
||||||
|
|
||||||
|
private const int ParallelThreshold = 64;
|
||||||
|
|
||||||
|
private readonly RowDelegate _row = row;
|
||||||
|
|
||||||
|
public void Execute(byte[] buffer, int width, int height, double[] uniforms)
|
||||||
|
{
|
||||||
|
var row = _row;
|
||||||
|
int stride = width * 4;
|
||||||
|
|
||||||
|
if (height < ParallelThreshold)
|
||||||
|
{
|
||||||
|
for (int y = 0; y < height; y++)
|
||||||
|
row(buffer, width, y * stride, y, uniforms);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
Parallel.For(0, height, y => row(buffer, width, y * stride, y, uniforms));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,216 @@
|
|||||||
|
using System;
|
||||||
|
using System.Collections.Generic;
|
||||||
|
using System.Linq.Expressions;
|
||||||
|
using System.Reflection;
|
||||||
|
|
||||||
|
namespace LuaScript.Engine.Kernel
|
||||||
|
{
|
||||||
|
internal static class CpuKernelCompiler
|
||||||
|
{
|
||||||
|
private static readonly MethodInfo Clamp = typeof(Math).GetMethod(nameof(Math.Clamp), [typeof(double), typeof(double), typeof(double)])!;
|
||||||
|
private static readonly MethodInfo Floor = Unary(nameof(Math.Floor));
|
||||||
|
private static readonly MethodInfo Pow = Binary(nameof(Math.Pow));
|
||||||
|
|
||||||
|
private static readonly Dictionary<KFunc, MethodInfo> Functions = new()
|
||||||
|
{
|
||||||
|
[KFunc.Abs] = Unary(nameof(Math.Abs)),
|
||||||
|
[KFunc.Floor] = Floor,
|
||||||
|
[KFunc.Ceil] = Unary(nameof(Math.Ceiling)),
|
||||||
|
[KFunc.Sqrt] = Unary(nameof(Math.Sqrt)),
|
||||||
|
[KFunc.Sin] = Unary(nameof(Math.Sin)),
|
||||||
|
[KFunc.Cos] = Unary(nameof(Math.Cos)),
|
||||||
|
[KFunc.Tan] = Unary(nameof(Math.Tan)),
|
||||||
|
[KFunc.Asin] = Unary(nameof(Math.Asin)),
|
||||||
|
[KFunc.Acos] = Unary(nameof(Math.Acos)),
|
||||||
|
[KFunc.Atan] = Unary(nameof(Math.Atan)),
|
||||||
|
[KFunc.Atan2] = Binary(nameof(Math.Atan2)),
|
||||||
|
[KFunc.Exp] = Unary(nameof(Math.Exp)),
|
||||||
|
[KFunc.Log] = Unary(nameof(Math.Log)),
|
||||||
|
[KFunc.Pow] = Pow,
|
||||||
|
[KFunc.Min] = Binary(nameof(Math.Min)),
|
||||||
|
[KFunc.Max] = Binary(nameof(Math.Max)),
|
||||||
|
};
|
||||||
|
|
||||||
|
public static CpuKernel Compile(KernelProgram program)
|
||||||
|
{
|
||||||
|
var buffer = Expression.Parameter(typeof(byte[]), "buffer");
|
||||||
|
var width = Expression.Parameter(typeof(int), "width");
|
||||||
|
var rowBase = Expression.Parameter(typeof(int), "rowBase");
|
||||||
|
var y = Expression.Parameter(typeof(double), "y");
|
||||||
|
var uniforms = Expression.Parameter(typeof(double[]), "uniforms");
|
||||||
|
|
||||||
|
var x = Expression.Variable(typeof(int), "x");
|
||||||
|
var index = Expression.Variable(typeof(int), "index");
|
||||||
|
var alphaRaw = Expression.Variable(typeof(double), "alphaRaw");
|
||||||
|
var transparent = Expression.Variable(typeof(bool), "transparent");
|
||||||
|
var scale = Expression.Variable(typeof(double), "scale");
|
||||||
|
var inputs = new[]
|
||||||
|
{
|
||||||
|
Expression.Variable(typeof(double), "inR"),
|
||||||
|
Expression.Variable(typeof(double), "inG"),
|
||||||
|
Expression.Variable(typeof(double), "inB"),
|
||||||
|
Expression.Variable(typeof(double), "inA"),
|
||||||
|
};
|
||||||
|
var slots = new ParameterExpression[program.Bindings.Count];
|
||||||
|
for (int i = 0; i < slots.Length; i++)
|
||||||
|
slots[i] = Expression.Variable(typeof(double), "slot" + i);
|
||||||
|
|
||||||
|
var context = new Context(x, y, uniforms, inputs, slots);
|
||||||
|
|
||||||
|
var statements = new List<Expression>
|
||||||
|
{
|
||||||
|
Expression.Assign(index, Expression.Add(rowBase, Expression.Multiply(x, Constant(4)))),
|
||||||
|
Expression.Assign(alphaRaw, ToDouble(ReadByte(buffer, index, 3))),
|
||||||
|
Expression.Assign(transparent, Expression.LessThanOrEqual(alphaRaw, Constant(0d))),
|
||||||
|
Expression.Assign(scale, Select(transparent, Constant(0d), Expression.Divide(Constant(255d), alphaRaw))),
|
||||||
|
Expression.Assign(inputs[3], Select(transparent, Constant(0d), alphaRaw)),
|
||||||
|
Expression.Assign(inputs[0], Select(transparent, Constant(0d), ClampByte(Expression.Multiply(ToDouble(ReadByte(buffer, index, 2)), scale)))),
|
||||||
|
Expression.Assign(inputs[1], Select(transparent, Constant(0d), ClampByte(Expression.Multiply(ToDouble(ReadByte(buffer, index, 1)), scale)))),
|
||||||
|
Expression.Assign(inputs[2], Select(transparent, Constant(0d), ClampByte(Expression.Multiply(ToDouble(ReadByte(buffer, index, 0)), scale)))),
|
||||||
|
};
|
||||||
|
|
||||||
|
for (int i = 0; i < slots.Length; i++)
|
||||||
|
statements.Add(Expression.Assign(slots[i], Build(program.Bindings[i], context)));
|
||||||
|
|
||||||
|
var outA = Expression.Variable(typeof(double), "outA");
|
||||||
|
var alphaScale = Expression.Variable(typeof(double), "alphaScale");
|
||||||
|
statements.Add(Expression.Assign(outA, Build(program.OutputA, context)));
|
||||||
|
statements.Add(Expression.Assign(alphaScale, Expression.Divide(ClampByte(outA), Constant(255d))));
|
||||||
|
statements.Add(WriteByte(buffer, index, 0, ClampByte(Expression.Multiply(Build(program.OutputB, context), alphaScale))));
|
||||||
|
statements.Add(WriteByte(buffer, index, 1, ClampByte(Expression.Multiply(Build(program.OutputG, context), alphaScale))));
|
||||||
|
statements.Add(WriteByte(buffer, index, 2, ClampByte(Expression.Multiply(Build(program.OutputR, context), alphaScale))));
|
||||||
|
statements.Add(WriteByte(buffer, index, 3, ClampByte(outA)));
|
||||||
|
statements.Add(Expression.PostIncrementAssign(x));
|
||||||
|
|
||||||
|
var breakLabel = Expression.Label("break");
|
||||||
|
var loop = Expression.Loop(
|
||||||
|
Expression.IfThenElse(
|
||||||
|
Expression.LessThan(x, width),
|
||||||
|
Expression.Block(statements),
|
||||||
|
Expression.Break(breakLabel)),
|
||||||
|
breakLabel);
|
||||||
|
|
||||||
|
var locals = new List<ParameterExpression> { x, index, alphaRaw, transparent, scale, outA, alphaScale };
|
||||||
|
locals.AddRange(inputs);
|
||||||
|
locals.AddRange(slots);
|
||||||
|
|
||||||
|
var body = Expression.Block(locals, Expression.Assign(x, Constant(0)), loop);
|
||||||
|
|
||||||
|
var lambda = Expression.Lambda<CpuKernel.RowDelegate>(body, buffer, width, rowBase, y, uniforms);
|
||||||
|
return new CpuKernel(lambda.Compile());
|
||||||
|
}
|
||||||
|
|
||||||
|
private sealed record Context(
|
||||||
|
ParameterExpression X,
|
||||||
|
ParameterExpression Y,
|
||||||
|
ParameterExpression Uniforms,
|
||||||
|
ParameterExpression[] Inputs,
|
||||||
|
ParameterExpression[] Slots);
|
||||||
|
|
||||||
|
private static Expression Build(KExpr expression, Context context)
|
||||||
|
{
|
||||||
|
switch (expression)
|
||||||
|
{
|
||||||
|
case KConst value:
|
||||||
|
return Constant(value.Value);
|
||||||
|
case KInput input:
|
||||||
|
return context.Inputs[(int)input.Channel];
|
||||||
|
case KCoord coord:
|
||||||
|
return coord.Axis == KAxis.X ? ToDouble(context.X) : context.Y;
|
||||||
|
case KUniformRef uniform:
|
||||||
|
return Expression.ArrayIndex(context.Uniforms, Constant((int)uniform.Uniform));
|
||||||
|
case KLocalRef local:
|
||||||
|
return context.Slots[local.Slot];
|
||||||
|
case KNegate negate:
|
||||||
|
return Expression.Negate(Build(negate.Operand, context));
|
||||||
|
case KArith arithmetic:
|
||||||
|
return BuildArithmetic(arithmetic, context);
|
||||||
|
case KCall call:
|
||||||
|
return BuildCall(call, context);
|
||||||
|
case KSelect select:
|
||||||
|
return Select(BuildBool(select.Condition, context), Build(select.WhenTrue, context), Build(select.WhenFalse, context));
|
||||||
|
}
|
||||||
|
throw new KernelUnsupportedException("Unsupported CPU expression.");
|
||||||
|
}
|
||||||
|
|
||||||
|
private static Expression BuildArithmetic(KArith arithmetic, Context context)
|
||||||
|
{
|
||||||
|
var left = Build(arithmetic.Left, context);
|
||||||
|
var right = Build(arithmetic.Right, context);
|
||||||
|
return arithmetic.Op switch
|
||||||
|
{
|
||||||
|
KArithOp.Add => Expression.Add(left, right),
|
||||||
|
KArithOp.Subtract => Expression.Subtract(left, right),
|
||||||
|
KArithOp.Multiply => Expression.Multiply(left, right),
|
||||||
|
KArithOp.Divide => Expression.Divide(left, right),
|
||||||
|
KArithOp.Modulo => FlooredModulo(left, right),
|
||||||
|
KArithOp.Power => Expression.Call(Pow, left, right),
|
||||||
|
_ => throw new KernelUnsupportedException("Unsupported arithmetic operator."),
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
private static Expression BuildCall(KCall call, Context context)
|
||||||
|
{
|
||||||
|
var method = Functions[call.Func];
|
||||||
|
if (call.Arguments.Count == 1)
|
||||||
|
return Expression.Call(method, Build(call.Arguments[0], context));
|
||||||
|
return Expression.Call(method, Build(call.Arguments[0], context), Build(call.Arguments[1], context));
|
||||||
|
}
|
||||||
|
|
||||||
|
private static Expression BuildBool(KBool condition, Context context)
|
||||||
|
{
|
||||||
|
switch (condition)
|
||||||
|
{
|
||||||
|
case KBoolConst value:
|
||||||
|
return Expression.Constant(value.Value);
|
||||||
|
case KNot not:
|
||||||
|
return Expression.Not(BuildBool(not.Operand, context));
|
||||||
|
case KLogical logical:
|
||||||
|
return logical.IsAnd
|
||||||
|
? Expression.AndAlso(BuildBool(logical.Left, context), BuildBool(logical.Right, context))
|
||||||
|
: Expression.OrElse(BuildBool(logical.Left, context), BuildBool(logical.Right, context));
|
||||||
|
case KCompare compare:
|
||||||
|
var left = Build(compare.Left, context);
|
||||||
|
var right = Build(compare.Right, context);
|
||||||
|
return compare.Op switch
|
||||||
|
{
|
||||||
|
KCompareOp.Less => Expression.LessThan(left, right),
|
||||||
|
KCompareOp.Greater => Expression.GreaterThan(left, right),
|
||||||
|
KCompareOp.LessEqual => Expression.LessThanOrEqual(left, right),
|
||||||
|
KCompareOp.GreaterEqual => Expression.GreaterThanOrEqual(left, right),
|
||||||
|
KCompareOp.Equal => Expression.Equal(left, right),
|
||||||
|
KCompareOp.NotEqual => Expression.NotEqual(left, right),
|
||||||
|
_ => throw new KernelUnsupportedException("Unsupported comparison."),
|
||||||
|
};
|
||||||
|
}
|
||||||
|
throw new KernelUnsupportedException("Unsupported CPU condition.");
|
||||||
|
}
|
||||||
|
|
||||||
|
private static Expression FlooredModulo(Expression left, Expression right) =>
|
||||||
|
Expression.Subtract(left, Expression.Multiply(Expression.Call(Floor, Expression.Divide(left, right)), right));
|
||||||
|
|
||||||
|
private static Expression Select(Expression condition, Expression whenTrue, Expression whenFalse) =>
|
||||||
|
Expression.Condition(condition, whenTrue, whenFalse);
|
||||||
|
|
||||||
|
private static Expression ClampByte(Expression value) =>
|
||||||
|
Expression.Call(Clamp, value, Constant(0d), Constant(255d));
|
||||||
|
|
||||||
|
private static Expression ReadByte(ParameterExpression buffer, ParameterExpression index, int offset) =>
|
||||||
|
Expression.ArrayIndex(buffer, offset == 0 ? index : Expression.Add(index, Constant(offset)));
|
||||||
|
|
||||||
|
private static Expression WriteByte(ParameterExpression buffer, ParameterExpression index, int offset, Expression value) =>
|
||||||
|
Expression.Assign(
|
||||||
|
Expression.ArrayAccess(buffer, offset == 0 ? index : Expression.Add(index, Constant(offset))),
|
||||||
|
Expression.Convert(value, typeof(byte)));
|
||||||
|
|
||||||
|
private static Expression ToDouble(Expression value) => Expression.Convert(value, typeof(double));
|
||||||
|
|
||||||
|
private static ConstantExpression Constant(double value) => Expression.Constant(value, typeof(double));
|
||||||
|
|
||||||
|
private static ConstantExpression Constant(int value) => Expression.Constant(value, typeof(int));
|
||||||
|
|
||||||
|
private static MethodInfo Unary(string name) => typeof(Math).GetMethod(name, [typeof(double)])!;
|
||||||
|
|
||||||
|
private static MethodInfo Binary(string name) => typeof(Math).GetMethod(name, [typeof(double), typeof(double)])!;
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,29 @@
|
|||||||
|
using System;
|
||||||
|
using Vortice.Direct2D1;
|
||||||
|
using YukkuriMovieMaker.Commons;
|
||||||
|
|
||||||
|
namespace LuaScript.Engine.Kernel
|
||||||
|
{
|
||||||
|
internal sealed class GpuKernel : IDisposable
|
||||||
|
{
|
||||||
|
private readonly GpuKernelEffect _effect;
|
||||||
|
private readonly float[] _packed = new float[HlslKernelEmitter.ConstantFloatCount];
|
||||||
|
private readonly byte[] _bytes = new byte[HlslKernelEmitter.ConstantFloatCount * sizeof(float)];
|
||||||
|
|
||||||
|
public GpuKernel(IGraphicsDevicesAndContext devices, KernelProgram program)
|
||||||
|
=> _effect = new GpuKernelEffect(devices, HlslKernelEmitter.Emit(program));
|
||||||
|
|
||||||
|
public bool IsReady => _effect.IsReady;
|
||||||
|
|
||||||
|
public ID2D1Image Apply(ID2D1Image input, double[] uniforms)
|
||||||
|
{
|
||||||
|
KernelUniformBinding.Pack(uniforms, _packed);
|
||||||
|
Buffer.BlockCopy(_packed, 0, _bytes, 0, _bytes.Length);
|
||||||
|
_effect.SetConstants(_bytes);
|
||||||
|
_effect.SetInput(0, input, true);
|
||||||
|
return _effect.Output;
|
||||||
|
}
|
||||||
|
|
||||||
|
public void Dispose() => _effect.Dispose();
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,193 @@
|
|||||||
|
using System;
|
||||||
|
using System.Collections.Generic;
|
||||||
|
using System.Runtime.InteropServices;
|
||||||
|
using System.Text;
|
||||||
|
using System.Threading;
|
||||||
|
using Vortice;
|
||||||
|
using Vortice.D3DCompiler;
|
||||||
|
using Vortice.Direct2D1;
|
||||||
|
using Vortice.Direct3D;
|
||||||
|
using Vortice.Mathematics;
|
||||||
|
using YukkuriMovieMaker.Commons;
|
||||||
|
|
||||||
|
namespace LuaScript.Engine.Kernel
|
||||||
|
{
|
||||||
|
internal sealed class GpuKernelEffect : ID2D1Effect
|
||||||
|
{
|
||||||
|
private const int ConstantsIndex = 0;
|
||||||
|
private const int InitializedIndex = 1;
|
||||||
|
|
||||||
|
[StructLayout(LayoutKind.Sequential)]
|
||||||
|
private unsafe struct ConstantBuffer
|
||||||
|
{
|
||||||
|
public fixed float Values[HlslKernelEmitter.ConstantFloatCount];
|
||||||
|
}
|
||||||
|
|
||||||
|
[CustomEffect(1, null, null, null, null)]
|
||||||
|
private sealed class Impl(Guid guid, string hlsl) : CustomEffectBase, ID2D1DrawTransform
|
||||||
|
{
|
||||||
|
private ConstantBuffer _constants;
|
||||||
|
private ID2D1DrawInfo? _drawInfo;
|
||||||
|
|
||||||
|
[CustomEffectProperty(PropertyType.Blob, ConstantsIndex)]
|
||||||
|
public byte[] Constants
|
||||||
|
{
|
||||||
|
get => ToBytes(_constants);
|
||||||
|
set
|
||||||
|
{
|
||||||
|
FromBytes(value, ref _constants);
|
||||||
|
_drawInfo?.SetPixelShaderConstantBuffer(in _constants);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
[CustomEffectProperty(PropertyType.Bool, InitializedIndex)]
|
||||||
|
public bool Initialized { get; private set; }
|
||||||
|
|
||||||
|
public override void Initialize(ID2D1EffectContext effectContext, ID2D1TransformGraph transformGraph)
|
||||||
|
{
|
||||||
|
byte[] source = Encoding.ASCII.GetBytes(hlsl);
|
||||||
|
var result = Compiler.Compile(source, "main", string.Empty, "ps_4_1", out var bytecode, out var errors);
|
||||||
|
if (result.Failure || bytecode is null)
|
||||||
|
{
|
||||||
|
Initialized = false;
|
||||||
|
Log.Default.Write("LuaScript: GPU kernel shader compilation failed.\n" + (errors?.AsString() ?? string.Empty));
|
||||||
|
errors?.Dispose();
|
||||||
|
bytecode?.Dispose();
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
try
|
||||||
|
{
|
||||||
|
byte[] shader = bytecode.AsBytes();
|
||||||
|
effectContext.LoadPixelShader(guid, shader, shader.Length);
|
||||||
|
transformGraph.SetSingleTransformNode(this);
|
||||||
|
Initialized = true;
|
||||||
|
}
|
||||||
|
finally
|
||||||
|
{
|
||||||
|
errors?.Dispose();
|
||||||
|
bytecode.Dispose();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
public void SetDrawInfo(ID2D1DrawInfo drawInfo)
|
||||||
|
{
|
||||||
|
_drawInfo = drawInfo;
|
||||||
|
drawInfo.SetPixelShader(guid, PixelOptions.None);
|
||||||
|
drawInfo.SetInputDescription(0, new InputDescription { Filter = (Filter)21, LevelOfDetailCount = 1 });
|
||||||
|
drawInfo.SetPixelShaderConstantBuffer(in _constants);
|
||||||
|
}
|
||||||
|
|
||||||
|
public int GetInputCount() => 1;
|
||||||
|
|
||||||
|
public void MapOutputRectToInputRects(RawRect outputRect, RawRect[] inputRects) =>
|
||||||
|
inputRects[0] = outputRect;
|
||||||
|
|
||||||
|
public void MapInputRectsToOutputRect(RawRect[] inputRects, RawRect[] inputOpaqueSubRects, out RawRect outputRect, out RawRect outputOpaqueSubRect)
|
||||||
|
{
|
||||||
|
outputRect = inputRects[0];
|
||||||
|
outputOpaqueSubRect = default;
|
||||||
|
}
|
||||||
|
|
||||||
|
public RawRect MapInvalidRect(int inputIndex, RawRect invalidInputRect) => invalidInputRect;
|
||||||
|
|
||||||
|
private static unsafe byte[] ToBytes(ConstantBuffer constants)
|
||||||
|
{
|
||||||
|
byte[] bytes = new byte[sizeof(ConstantBuffer)];
|
||||||
|
fixed (byte* destination = bytes)
|
||||||
|
*(ConstantBuffer*)destination = constants;
|
||||||
|
return bytes;
|
||||||
|
}
|
||||||
|
|
||||||
|
private static unsafe void FromBytes(byte[] bytes, ref ConstantBuffer constants)
|
||||||
|
{
|
||||||
|
int length = Math.Min(bytes.Length, sizeof(ConstantBuffer));
|
||||||
|
fixed (byte* source = bytes)
|
||||||
|
fixed (ConstantBuffer* destination = &constants)
|
||||||
|
Buffer.MemoryCopy(source, destination, sizeof(ConstantBuffer), length);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private sealed class Manager
|
||||||
|
{
|
||||||
|
private readonly Lock _locker = new();
|
||||||
|
private readonly Dictionary<int, Dictionary<string, (Guid Guid, int Count)>> _registered = [];
|
||||||
|
|
||||||
|
public Guid Acquire(IGraphicsDevicesAndContext devices, string hlsl)
|
||||||
|
{
|
||||||
|
lock (_locker)
|
||||||
|
{
|
||||||
|
int device = devices.GetHashCode();
|
||||||
|
if (!_registered.TryGetValue(device, out var byHlsl))
|
||||||
|
{
|
||||||
|
byHlsl = [];
|
||||||
|
_registered[device] = byHlsl;
|
||||||
|
}
|
||||||
|
if (byHlsl.TryGetValue(hlsl, out var entry))
|
||||||
|
{
|
||||||
|
byHlsl[hlsl] = (entry.Guid, entry.Count + 1);
|
||||||
|
return entry.Guid;
|
||||||
|
}
|
||||||
|
|
||||||
|
var guid = Guid.NewGuid();
|
||||||
|
byHlsl[hlsl] = (guid, 1);
|
||||||
|
((ID2D1Factory1)devices.D2D.Factory).RegisterEffect<Impl>(() => new Impl(guid, hlsl), guid);
|
||||||
|
return guid;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
public void Release(IGraphicsDevicesAndContext devices, string hlsl)
|
||||||
|
{
|
||||||
|
lock (_locker)
|
||||||
|
{
|
||||||
|
int device = devices.GetHashCode();
|
||||||
|
if (!_registered.TryGetValue(device, out var byHlsl) || !byHlsl.TryGetValue(hlsl, out var entry))
|
||||||
|
return;
|
||||||
|
if (entry.Count > 1)
|
||||||
|
{
|
||||||
|
byHlsl[hlsl] = (entry.Guid, entry.Count - 1);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
byHlsl.Remove(hlsl);
|
||||||
|
((ID2D1Factory1)devices.D2D.Factory).UnregisterEffect(entry.Guid);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private static readonly Manager Effects = new();
|
||||||
|
|
||||||
|
private readonly IGraphicsDevicesAndContext _devices;
|
||||||
|
private readonly string _hlsl;
|
||||||
|
|
||||||
|
public GpuKernelEffect(IGraphicsDevicesAndContext devices, string hlsl)
|
||||||
|
: base(Create(devices, hlsl))
|
||||||
|
{
|
||||||
|
_devices = devices;
|
||||||
|
_hlsl = hlsl;
|
||||||
|
}
|
||||||
|
|
||||||
|
public bool IsReady => NativePointer != nint.Zero && ((ID2D1Properties)this).GetBoolValue(InitializedIndex);
|
||||||
|
|
||||||
|
public void SetConstants(byte[] bytes) => ((ID2D1Properties)this).SetValue(ConstantsIndex, bytes);
|
||||||
|
|
||||||
|
private static nint Create(IGraphicsDevicesAndContext devices, string hlsl)
|
||||||
|
{
|
||||||
|
try
|
||||||
|
{
|
||||||
|
var guid = Effects.Acquire(devices, hlsl);
|
||||||
|
return ((ID2D1DeviceContext)devices.DeviceContext).CreateEffect(guid);
|
||||||
|
}
|
||||||
|
catch (Exception ex)
|
||||||
|
{
|
||||||
|
Log.Default.Write("LuaScript: failed to create GPU kernel effect.", ex);
|
||||||
|
return nint.Zero;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
protected override void DisposeCore(nint nativePointer, bool disposing)
|
||||||
|
{
|
||||||
|
base.DisposeCore(nativePointer, disposing);
|
||||||
|
Effects.Release(_devices, _hlsl);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,225 @@
|
|||||||
|
using System.Globalization;
|
||||||
|
using System.Text;
|
||||||
|
|
||||||
|
namespace LuaScript.Engine.Kernel
|
||||||
|
{
|
||||||
|
internal static class HlslKernelEmitter
|
||||||
|
{
|
||||||
|
public const int ConstantVectorCount = 16;
|
||||||
|
|
||||||
|
public const int ConstantFloatCount = ConstantVectorCount * 4;
|
||||||
|
|
||||||
|
private static readonly string[] Intrinsics =
|
||||||
|
[
|
||||||
|
"abs", "floor", "ceil", "sqrt", "sin", "cos", "tan", "asin", "acos",
|
||||||
|
"atan", "atan2", "exp", "log", "pow", "min", "max", "fmod",
|
||||||
|
];
|
||||||
|
|
||||||
|
public static string Emit(KernelProgram program)
|
||||||
|
{
|
||||||
|
var builder = new StringBuilder(1024);
|
||||||
|
|
||||||
|
builder.Append("Texture2D InputTexture : register(t0);\n");
|
||||||
|
builder.Append("SamplerState InputSampler : register(s0);\n");
|
||||||
|
builder.Append("cbuffer constants : register(b0)\n{\n");
|
||||||
|
builder.Append(" float4 uniforms[").Append(ConstantVectorCount).Append("];\n");
|
||||||
|
builder.Append("};\n\n");
|
||||||
|
builder.Append("float4 main(float4 pos : SV_POSITION, float4 posScene : SCENE_POSITION, float4 uv : TEXCOORD0) : SV_Target\n{\n");
|
||||||
|
builder.Append(" float4 src = InputTexture.Sample(InputSampler, uv.xy);\n");
|
||||||
|
builder.Append(" float srcA = src.a;\n");
|
||||||
|
builder.Append(" float invA = srcA <= 0.0 ? 0.0 : 1.0 / srcA;\n");
|
||||||
|
builder.Append(" float inR = clamp(src.r * invA * 255.0, 0.0, 255.0);\n");
|
||||||
|
builder.Append(" float inG = clamp(src.g * invA * 255.0, 0.0, 255.0);\n");
|
||||||
|
builder.Append(" float inB = clamp(src.b * invA * 255.0, 0.0, 255.0);\n");
|
||||||
|
builder.Append(" float inA = srcA * 255.0;\n");
|
||||||
|
builder.Append(" float px = uv.x * ").Append(Uniform(KernelUniform.Width)).Append(";\n");
|
||||||
|
builder.Append(" float py = uv.y * ").Append(Uniform(KernelUniform.Height)).Append(";\n");
|
||||||
|
|
||||||
|
for (int i = 0; i < program.Bindings.Count; i++)
|
||||||
|
{
|
||||||
|
builder.Append(" float slot").Append(i).Append(" = ");
|
||||||
|
EmitExpression(builder, program.Bindings[i]);
|
||||||
|
builder.Append(";\n");
|
||||||
|
}
|
||||||
|
|
||||||
|
builder.Append(" float outA = ");
|
||||||
|
EmitExpression(builder, program.OutputA);
|
||||||
|
builder.Append(";\n");
|
||||||
|
builder.Append(" float alphaK = clamp(outA, 0.0, 255.0) / 255.0;\n");
|
||||||
|
|
||||||
|
builder.Append(" float oR = clamp((");
|
||||||
|
EmitExpression(builder, program.OutputR);
|
||||||
|
builder.Append(") * alphaK, 0.0, 255.0) / 255.0;\n");
|
||||||
|
builder.Append(" float oG = clamp((");
|
||||||
|
EmitExpression(builder, program.OutputG);
|
||||||
|
builder.Append(") * alphaK, 0.0, 255.0) / 255.0;\n");
|
||||||
|
builder.Append(" float oB = clamp((");
|
||||||
|
EmitExpression(builder, program.OutputB);
|
||||||
|
builder.Append(") * alphaK, 0.0, 255.0) / 255.0;\n");
|
||||||
|
builder.Append(" float oA = clamp(outA, 0.0, 255.0) / 255.0;\n");
|
||||||
|
builder.Append(" return float4(oR, oG, oB, oA);\n}\n");
|
||||||
|
|
||||||
|
return builder.ToString();
|
||||||
|
}
|
||||||
|
|
||||||
|
private static void EmitExpression(StringBuilder builder, KExpr expression)
|
||||||
|
{
|
||||||
|
switch (expression)
|
||||||
|
{
|
||||||
|
case KConst value:
|
||||||
|
builder.Append(Number(value.Value));
|
||||||
|
return;
|
||||||
|
case KInput input:
|
||||||
|
builder.Append(input.Channel switch
|
||||||
|
{
|
||||||
|
KChannel.R => "inR",
|
||||||
|
KChannel.G => "inG",
|
||||||
|
KChannel.B => "inB",
|
||||||
|
_ => "inA",
|
||||||
|
});
|
||||||
|
return;
|
||||||
|
case KCoord coord:
|
||||||
|
builder.Append(coord.Axis == KAxis.X ? "px" : "py");
|
||||||
|
return;
|
||||||
|
case KUniformRef uniform:
|
||||||
|
builder.Append(Uniform(uniform.Uniform));
|
||||||
|
return;
|
||||||
|
case KLocalRef local:
|
||||||
|
builder.Append("slot").Append(local.Slot);
|
||||||
|
return;
|
||||||
|
case KNegate negate:
|
||||||
|
builder.Append("(-(");
|
||||||
|
EmitExpression(builder, negate.Operand);
|
||||||
|
builder.Append("))");
|
||||||
|
return;
|
||||||
|
case KArith arithmetic:
|
||||||
|
EmitArithmetic(builder, arithmetic);
|
||||||
|
return;
|
||||||
|
case KCall call:
|
||||||
|
EmitCall(builder, call);
|
||||||
|
return;
|
||||||
|
case KSelect select:
|
||||||
|
builder.Append('(');
|
||||||
|
EmitCondition(builder, select.Condition);
|
||||||
|
builder.Append(" ? (");
|
||||||
|
EmitExpression(builder, select.WhenTrue);
|
||||||
|
builder.Append(") : (");
|
||||||
|
EmitExpression(builder, select.WhenFalse);
|
||||||
|
builder.Append("))");
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
throw new KernelUnsupportedException("Unsupported HLSL expression.");
|
||||||
|
}
|
||||||
|
|
||||||
|
private static void EmitArithmetic(StringBuilder builder, KArith arithmetic)
|
||||||
|
{
|
||||||
|
if (arithmetic.Op == KArithOp.Power)
|
||||||
|
{
|
||||||
|
builder.Append("pow(");
|
||||||
|
EmitExpression(builder, arithmetic.Left);
|
||||||
|
builder.Append(", ");
|
||||||
|
EmitExpression(builder, arithmetic.Right);
|
||||||
|
builder.Append(')');
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (arithmetic.Op == KArithOp.Modulo)
|
||||||
|
{
|
||||||
|
builder.Append('(');
|
||||||
|
EmitExpression(builder, arithmetic.Left);
|
||||||
|
builder.Append(" - floor((");
|
||||||
|
EmitExpression(builder, arithmetic.Left);
|
||||||
|
builder.Append(") / (");
|
||||||
|
EmitExpression(builder, arithmetic.Right);
|
||||||
|
builder.Append(")) * (");
|
||||||
|
EmitExpression(builder, arithmetic.Right);
|
||||||
|
builder.Append("))");
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
builder.Append('(');
|
||||||
|
EmitExpression(builder, arithmetic.Left);
|
||||||
|
builder.Append(arithmetic.Op switch
|
||||||
|
{
|
||||||
|
KArithOp.Add => " + ",
|
||||||
|
KArithOp.Subtract => " - ",
|
||||||
|
KArithOp.Multiply => " * ",
|
||||||
|
KArithOp.Divide => " / ",
|
||||||
|
_ => throw new KernelUnsupportedException("Unsupported arithmetic operator."),
|
||||||
|
});
|
||||||
|
EmitExpression(builder, arithmetic.Right);
|
||||||
|
builder.Append(')');
|
||||||
|
}
|
||||||
|
|
||||||
|
private static void EmitCall(StringBuilder builder, KCall call)
|
||||||
|
{
|
||||||
|
builder.Append(Intrinsics[(int)call.Func]).Append('(');
|
||||||
|
for (int i = 0; i < call.Arguments.Count; i++)
|
||||||
|
{
|
||||||
|
if (i > 0)
|
||||||
|
builder.Append(", ");
|
||||||
|
EmitExpression(builder, call.Arguments[i]);
|
||||||
|
}
|
||||||
|
builder.Append(')');
|
||||||
|
}
|
||||||
|
|
||||||
|
private static void EmitCondition(StringBuilder builder, KBool condition)
|
||||||
|
{
|
||||||
|
switch (condition)
|
||||||
|
{
|
||||||
|
case KBoolConst value:
|
||||||
|
builder.Append(value.Value ? "true" : "false");
|
||||||
|
return;
|
||||||
|
case KNot not:
|
||||||
|
builder.Append("(!(");
|
||||||
|
EmitCondition(builder, not.Operand);
|
||||||
|
builder.Append("))");
|
||||||
|
return;
|
||||||
|
case KLogical logical:
|
||||||
|
builder.Append('(');
|
||||||
|
EmitCondition(builder, logical.Left);
|
||||||
|
builder.Append(logical.IsAnd ? " && " : " || ");
|
||||||
|
EmitCondition(builder, logical.Right);
|
||||||
|
builder.Append(')');
|
||||||
|
return;
|
||||||
|
case KCompare compare:
|
||||||
|
builder.Append('(');
|
||||||
|
EmitExpression(builder, compare.Left);
|
||||||
|
builder.Append(compare.Op switch
|
||||||
|
{
|
||||||
|
KCompareOp.Less => " < ",
|
||||||
|
KCompareOp.Greater => " > ",
|
||||||
|
KCompareOp.LessEqual => " <= ",
|
||||||
|
KCompareOp.GreaterEqual => " >= ",
|
||||||
|
KCompareOp.Equal => " == ",
|
||||||
|
_ => " != ",
|
||||||
|
});
|
||||||
|
EmitExpression(builder, compare.Right);
|
||||||
|
builder.Append(')');
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
throw new KernelUnsupportedException("Unsupported HLSL condition.");
|
||||||
|
}
|
||||||
|
|
||||||
|
private static string Uniform(KernelUniform uniform)
|
||||||
|
{
|
||||||
|
int index = (int)uniform;
|
||||||
|
return $"uniforms[{index / 4}].{"xyzw"[index % 4]}";
|
||||||
|
}
|
||||||
|
|
||||||
|
private static string Number(double value)
|
||||||
|
{
|
||||||
|
if (double.IsPositiveInfinity(value))
|
||||||
|
return "3.4028235e38";
|
||||||
|
if (double.IsNegativeInfinity(value))
|
||||||
|
return "-3.4028235e38";
|
||||||
|
if (double.IsNaN(value))
|
||||||
|
return "(0.0 / 0.0)";
|
||||||
|
|
||||||
|
string text = value.ToString("R", CultureInfo.InvariantCulture);
|
||||||
|
if (!text.Contains('.') && !text.Contains('e') && !text.Contains('E'))
|
||||||
|
text += ".0";
|
||||||
|
return text;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,357 @@
|
|||||||
|
using System;
|
||||||
|
using System.Collections.Generic;
|
||||||
|
|
||||||
|
namespace LuaScript.Engine.Kernel
|
||||||
|
{
|
||||||
|
internal sealed class KernelExtractor
|
||||||
|
{
|
||||||
|
private readonly record struct FuncSpec(KFunc Func, int MinArgs, int MaxArgs);
|
||||||
|
|
||||||
|
private static readonly Dictionary<string, FuncSpec> MathFunctions = new(StringComparer.Ordinal)
|
||||||
|
{
|
||||||
|
["abs"] = new(KFunc.Abs, 1, 1),
|
||||||
|
["floor"] = new(KFunc.Floor, 1, 1),
|
||||||
|
["ceil"] = new(KFunc.Ceil, 1, 1),
|
||||||
|
["sqrt"] = new(KFunc.Sqrt, 1, 1),
|
||||||
|
["sin"] = new(KFunc.Sin, 1, 1),
|
||||||
|
["cos"] = new(KFunc.Cos, 1, 1),
|
||||||
|
["tan"] = new(KFunc.Tan, 1, 1),
|
||||||
|
["asin"] = new(KFunc.Asin, 1, 1),
|
||||||
|
["acos"] = new(KFunc.Acos, 1, 1),
|
||||||
|
["atan"] = new(KFunc.Atan, 1, 1),
|
||||||
|
["atan2"] = new(KFunc.Atan2, 2, 2),
|
||||||
|
["exp"] = new(KFunc.Exp, 1, 1),
|
||||||
|
["log"] = new(KFunc.Log, 1, 1),
|
||||||
|
["pow"] = new(KFunc.Pow, 2, 2),
|
||||||
|
["fmod"] = new(KFunc.Fmod, 2, 2),
|
||||||
|
["min"] = new(KFunc.Min, 2, int.MaxValue),
|
||||||
|
["max"] = new(KFunc.Max, 2, int.MaxValue),
|
||||||
|
};
|
||||||
|
|
||||||
|
private readonly List<KExpr> _bindings = [];
|
||||||
|
private readonly Dictionary<string, int> _scope = new(StringComparer.Ordinal);
|
||||||
|
private readonly SortedSet<KernelUniform> _uniforms = [];
|
||||||
|
|
||||||
|
private string _widthVariable = string.Empty;
|
||||||
|
private string _heightVariable = string.Empty;
|
||||||
|
private bool _coordsEnabled;
|
||||||
|
|
||||||
|
public static KernelProgram? TryExtract(string runnableScript)
|
||||||
|
{
|
||||||
|
try
|
||||||
|
{
|
||||||
|
return new KernelExtractor().Extract(runnableScript);
|
||||||
|
}
|
||||||
|
catch (KernelUnsupportedException)
|
||||||
|
{
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private KernelProgram? Extract(string runnableScript)
|
||||||
|
{
|
||||||
|
var block = LuaParser.Parse(runnableScript);
|
||||||
|
|
||||||
|
int index = 0;
|
||||||
|
while (index < block.Count && block[index] is LocalStmt prelude)
|
||||||
|
{
|
||||||
|
BindLocal(prelude);
|
||||||
|
index++;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (index >= block.Count || block[index] is not NumericForStmt outer)
|
||||||
|
return null;
|
||||||
|
if (index + 1 != block.Count)
|
||||||
|
return null;
|
||||||
|
|
||||||
|
if (!TryAxis(outer, out string outerVar, out KAxis outerAxis))
|
||||||
|
return null;
|
||||||
|
if (outer.Body.Count != 1 || outer.Body[0] is not NumericForStmt inner)
|
||||||
|
return null;
|
||||||
|
if (!TryAxis(inner, out string innerVar, out KAxis innerAxis))
|
||||||
|
return null;
|
||||||
|
if (outerAxis == innerAxis)
|
||||||
|
return null;
|
||||||
|
|
||||||
|
_widthVariable = outerAxis == KAxis.X ? outerVar : innerVar;
|
||||||
|
_heightVariable = outerAxis == KAxis.Y ? outerVar : innerVar;
|
||||||
|
|
||||||
|
return BuildKernel(inner.Body);
|
||||||
|
}
|
||||||
|
|
||||||
|
private KernelProgram? BuildKernel(IReadOnlyList<LuaStmt> body)
|
||||||
|
{
|
||||||
|
if (body.Count < 2)
|
||||||
|
return null;
|
||||||
|
|
||||||
|
if (body[0] is not LocalStmt sample || sample.Values.Count != 1 ||
|
||||||
|
!IsGetPixel(sample.Values[0]))
|
||||||
|
return null;
|
||||||
|
if (sample.Names.Count is < 1 or > 4)
|
||||||
|
return null;
|
||||||
|
|
||||||
|
_coordsEnabled = true;
|
||||||
|
for (int i = 0; i < sample.Names.Count; i++)
|
||||||
|
{
|
||||||
|
EnsureNotCoordinateName(sample.Names[i]);
|
||||||
|
_scope[sample.Names[i]] = AddBinding(new KInput((KChannel)i));
|
||||||
|
}
|
||||||
|
|
||||||
|
for (int i = 1; i < body.Count - 1; i++)
|
||||||
|
{
|
||||||
|
switch (body[i])
|
||||||
|
{
|
||||||
|
case LocalStmt local:
|
||||||
|
BindLocal(local);
|
||||||
|
break;
|
||||||
|
case AssignStmt assign:
|
||||||
|
BindAssign(assign);
|
||||||
|
break;
|
||||||
|
default:
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
if (body[^1] is not CallStmt { Call: var call } || !IsObjectMethod(call, "setpixel"))
|
||||||
|
return null;
|
||||||
|
if (call.Arguments.Count is < 5 or > 6)
|
||||||
|
return null;
|
||||||
|
if (!IsCoordinate(call.Arguments[0], KAxis.X) || !IsCoordinate(call.Arguments[1], KAxis.Y))
|
||||||
|
return null;
|
||||||
|
|
||||||
|
var outR = Lower(call.Arguments[2]);
|
||||||
|
var outG = Lower(call.Arguments[3]);
|
||||||
|
var outB = Lower(call.Arguments[4]);
|
||||||
|
var outA = call.Arguments.Count == 6 ? Lower(call.Arguments[5]) : new KConst(255d);
|
||||||
|
|
||||||
|
return new KernelProgram(_bindings, outR, outG, outB, outA, [.. _uniforms]);
|
||||||
|
}
|
||||||
|
|
||||||
|
private void BindLocal(LocalStmt local)
|
||||||
|
{
|
||||||
|
if (local.Values.Count == 1 && IsGetPixel(local.Values[0]))
|
||||||
|
throw new KernelUnsupportedException("Unexpected pixel sample.");
|
||||||
|
if (local.Names.Count != local.Values.Count)
|
||||||
|
throw new KernelUnsupportedException("Multiple-value assignment is not supported.");
|
||||||
|
|
||||||
|
var lowered = new KExpr[local.Values.Count];
|
||||||
|
for (int i = 0; i < local.Values.Count; i++)
|
||||||
|
lowered[i] = Lower(local.Values[i]);
|
||||||
|
for (int i = 0; i < local.Names.Count; i++)
|
||||||
|
{
|
||||||
|
EnsureNotCoordinateName(local.Names[i]);
|
||||||
|
_scope[local.Names[i]] = AddBinding(lowered[i]);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private void BindAssign(AssignStmt assign)
|
||||||
|
{
|
||||||
|
if (assign.Targets.Count != assign.Values.Count)
|
||||||
|
throw new KernelUnsupportedException("Unbalanced assignment is not supported.");
|
||||||
|
|
||||||
|
foreach (var target in assign.Targets)
|
||||||
|
{
|
||||||
|
if (target is not NameExpr name || !_scope.ContainsKey(name.Name))
|
||||||
|
throw new KernelUnsupportedException("Assignment target must be a local variable.");
|
||||||
|
}
|
||||||
|
|
||||||
|
var lowered = new KExpr[assign.Values.Count];
|
||||||
|
for (int i = 0; i < assign.Values.Count; i++)
|
||||||
|
lowered[i] = Lower(assign.Values[i]);
|
||||||
|
for (int i = 0; i < assign.Targets.Count; i++)
|
||||||
|
_scope[((NameExpr)assign.Targets[i]).Name] = AddBinding(lowered[i]);
|
||||||
|
}
|
||||||
|
|
||||||
|
private void EnsureNotCoordinateName(string name)
|
||||||
|
{
|
||||||
|
if (string.Equals(name, _widthVariable, StringComparison.Ordinal) ||
|
||||||
|
string.Equals(name, _heightVariable, StringComparison.Ordinal))
|
||||||
|
throw new KernelUnsupportedException("Local variable shadows a loop coordinate.");
|
||||||
|
}
|
||||||
|
|
||||||
|
private int AddBinding(KExpr expression)
|
||||||
|
{
|
||||||
|
_bindings.Add(expression);
|
||||||
|
return _bindings.Count - 1;
|
||||||
|
}
|
||||||
|
|
||||||
|
private KExpr Lower(LuaExpr expression)
|
||||||
|
{
|
||||||
|
switch (expression)
|
||||||
|
{
|
||||||
|
case NumberExpr number:
|
||||||
|
return new KConst(number.Value);
|
||||||
|
case NameExpr name:
|
||||||
|
return LowerName(name.Name);
|
||||||
|
case MemberExpr member:
|
||||||
|
return LowerMember(member);
|
||||||
|
case CallExpr call:
|
||||||
|
return LowerCall(call);
|
||||||
|
case UnaryExpr { Operator: "-" } unary:
|
||||||
|
return new KNegate(Lower(unary.Operand));
|
||||||
|
case BinaryExpr binary:
|
||||||
|
return LowerBinary(binary);
|
||||||
|
}
|
||||||
|
throw new KernelUnsupportedException("Unsupported expression in pixel kernel.");
|
||||||
|
}
|
||||||
|
|
||||||
|
private KExpr LowerName(string name)
|
||||||
|
{
|
||||||
|
if (_scope.TryGetValue(name, out int slot))
|
||||||
|
return new KLocalRef(slot);
|
||||||
|
if (_coordsEnabled && string.Equals(name, _widthVariable, StringComparison.Ordinal))
|
||||||
|
return new KCoord(KAxis.X);
|
||||||
|
if (_coordsEnabled && string.Equals(name, _heightVariable, StringComparison.Ordinal))
|
||||||
|
return new KCoord(KAxis.Y);
|
||||||
|
if (KernelUniforms.TryResolveGlobal(name, out var uniform))
|
||||||
|
return UseUniform(uniform);
|
||||||
|
throw new KernelUnsupportedException($"Unknown identifier '{name}'.");
|
||||||
|
}
|
||||||
|
|
||||||
|
private KExpr LowerMember(MemberExpr member)
|
||||||
|
{
|
||||||
|
if (member.Target is NameExpr { Name: "math" })
|
||||||
|
{
|
||||||
|
return member.Name switch
|
||||||
|
{
|
||||||
|
"pi" => new KConst(Math.PI),
|
||||||
|
"huge" => new KConst(double.PositiveInfinity),
|
||||||
|
_ => throw new KernelUnsupportedException($"Unsupported math field '{member.Name}'."),
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
if (member.Target is NameExpr target && KernelUniforms.TryResolveMember(target.Name, member.Name, out var uniform))
|
||||||
|
return UseUniform(uniform);
|
||||||
|
|
||||||
|
throw new KernelUnsupportedException("Unsupported member access in pixel kernel.");
|
||||||
|
}
|
||||||
|
|
||||||
|
private KExpr LowerCall(CallExpr call)
|
||||||
|
{
|
||||||
|
if (call.Target is not MemberExpr { Target: NameExpr { Name: "math" }, Name: var function } ||
|
||||||
|
!MathFunctions.TryGetValue(function, out var spec))
|
||||||
|
throw new KernelUnsupportedException("Unsupported function call in pixel kernel.");
|
||||||
|
|
||||||
|
int count = call.Arguments.Count;
|
||||||
|
if (count < spec.MinArgs || count > spec.MaxArgs)
|
||||||
|
throw new KernelUnsupportedException($"Wrong argument count for 'math.{function}'.");
|
||||||
|
|
||||||
|
var arguments = new KExpr[count];
|
||||||
|
for (int i = 0; i < count; i++)
|
||||||
|
arguments[i] = Lower(call.Arguments[i]);
|
||||||
|
|
||||||
|
if (spec.Func is KFunc.Min or KFunc.Max)
|
||||||
|
{
|
||||||
|
var folded = arguments[0];
|
||||||
|
for (int i = 1; i < count; i++)
|
||||||
|
folded = new KCall(spec.Func, [folded, arguments[i]]);
|
||||||
|
return folded;
|
||||||
|
}
|
||||||
|
|
||||||
|
return new KCall(spec.Func, arguments);
|
||||||
|
}
|
||||||
|
|
||||||
|
private KExpr LowerBinary(BinaryExpr binary)
|
||||||
|
{
|
||||||
|
switch (binary.Operator)
|
||||||
|
{
|
||||||
|
case "+": return new KArith(KArithOp.Add, Lower(binary.Left), Lower(binary.Right));
|
||||||
|
case "-": return new KArith(KArithOp.Subtract, Lower(binary.Left), Lower(binary.Right));
|
||||||
|
case "*": return new KArith(KArithOp.Multiply, Lower(binary.Left), Lower(binary.Right));
|
||||||
|
case "/": return new KArith(KArithOp.Divide, Lower(binary.Left), Lower(binary.Right));
|
||||||
|
case "%": return new KArith(KArithOp.Modulo, Lower(binary.Left), Lower(binary.Right));
|
||||||
|
case "^": return new KArith(KArithOp.Power, Lower(binary.Left), Lower(binary.Right));
|
||||||
|
case "or" when binary.Left is BinaryExpr { Operator: "and" } conditional:
|
||||||
|
return new KSelect(LowerBool(conditional.Left), Lower(conditional.Right), Lower(binary.Right));
|
||||||
|
}
|
||||||
|
throw new KernelUnsupportedException($"Unsupported operator '{binary.Operator}' in value position.");
|
||||||
|
}
|
||||||
|
|
||||||
|
private KBool LowerBool(LuaExpr expression)
|
||||||
|
{
|
||||||
|
switch (expression)
|
||||||
|
{
|
||||||
|
case BoolExpr boolean:
|
||||||
|
return new KBoolConst(boolean.Value);
|
||||||
|
case UnaryExpr { Operator: "not" } unary:
|
||||||
|
return new KNot(LowerBool(unary.Operand));
|
||||||
|
case BinaryExpr { Operator: "and" } conjunction:
|
||||||
|
return new KLogical(true, LowerBool(conjunction.Left), LowerBool(conjunction.Right));
|
||||||
|
case BinaryExpr { Operator: "or" } disjunction:
|
||||||
|
return new KLogical(false, LowerBool(disjunction.Left), LowerBool(disjunction.Right));
|
||||||
|
case BinaryExpr binary when TryCompareOp(binary.Operator, out var op):
|
||||||
|
return new KCompare(op, Lower(binary.Left), Lower(binary.Right));
|
||||||
|
case NameExpr name when IsCheck(LowerName(name.Name)):
|
||||||
|
return new KCompare(KCompareOp.NotEqual, LowerName(name.Name), new KConst(0d));
|
||||||
|
case MemberExpr member when IsCheck(LowerMember(member)):
|
||||||
|
return new KCompare(KCompareOp.NotEqual, LowerMember(member), new KConst(0d));
|
||||||
|
}
|
||||||
|
throw new KernelUnsupportedException("Unsupported condition in pixel kernel.");
|
||||||
|
}
|
||||||
|
|
||||||
|
private static bool IsCheck(KExpr expression) =>
|
||||||
|
expression is KUniformRef { Uniform: KernelUniform.Check0 or KernelUniform.Check1 or KernelUniform.Check2 or KernelUniform.Check3 };
|
||||||
|
|
||||||
|
private static bool TryCompareOp(string symbol, out KCompareOp op)
|
||||||
|
{
|
||||||
|
switch (symbol)
|
||||||
|
{
|
||||||
|
case "<": op = KCompareOp.Less; return true;
|
||||||
|
case ">": op = KCompareOp.Greater; return true;
|
||||||
|
case "<=": op = KCompareOp.LessEqual; return true;
|
||||||
|
case ">=": op = KCompareOp.GreaterEqual; return true;
|
||||||
|
case "==": op = KCompareOp.Equal; return true;
|
||||||
|
case "~=": op = KCompareOp.NotEqual; return true;
|
||||||
|
default: op = default; return false;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private KExpr UseUniform(KernelUniform uniform)
|
||||||
|
{
|
||||||
|
_uniforms.Add(uniform);
|
||||||
|
return new KUniformRef(uniform);
|
||||||
|
}
|
||||||
|
|
||||||
|
private bool TryAxis(NumericForStmt loop, out string variable, out KAxis axis)
|
||||||
|
{
|
||||||
|
variable = loop.Variable;
|
||||||
|
axis = default;
|
||||||
|
|
||||||
|
if (loop.Start is not NumberExpr { Value: 0d })
|
||||||
|
return false;
|
||||||
|
if (loop.Step is not null && loop.Step is not NumberExpr { Value: 1d })
|
||||||
|
return false;
|
||||||
|
if (loop.Stop is not BinaryExpr { Operator: "-", Right: NumberExpr { Value: 1d } } bound)
|
||||||
|
return false;
|
||||||
|
if (bound.Left is not MemberExpr { Target: NameExpr { Name: "obj" }, Name: var field })
|
||||||
|
return false;
|
||||||
|
if (!KernelUniforms.TryResolveMember("obj", field, out var uniform))
|
||||||
|
return false;
|
||||||
|
|
||||||
|
if (uniform == KernelUniform.Width)
|
||||||
|
{
|
||||||
|
axis = KAxis.X;
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
if (uniform == KernelUniform.Height)
|
||||||
|
{
|
||||||
|
axis = KAxis.Y;
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
|
private bool IsGetPixel(LuaExpr expression) =>
|
||||||
|
expression is CallExpr call && IsObjectMethod(call, "getpixel") &&
|
||||||
|
call.Arguments.Count == 2 &&
|
||||||
|
IsCoordinate(call.Arguments[0], KAxis.X) && IsCoordinate(call.Arguments[1], KAxis.Y);
|
||||||
|
|
||||||
|
private bool IsCoordinate(LuaExpr expression, KAxis axis) =>
|
||||||
|
expression is NameExpr name &&
|
||||||
|
string.Equals(name.Name, axis == KAxis.X ? _widthVariable : _heightVariable, StringComparison.Ordinal);
|
||||||
|
|
||||||
|
private static bool IsObjectMethod(CallExpr call, string method) =>
|
||||||
|
call.Target is MemberExpr { Target: NameExpr { Name: "obj" }, Name: var name } &&
|
||||||
|
string.Equals(name, method, StringComparison.Ordinal);
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,97 @@
|
|||||||
|
using System.Collections.Generic;
|
||||||
|
|
||||||
|
namespace LuaScript.Engine.Kernel
|
||||||
|
{
|
||||||
|
internal enum KChannel
|
||||||
|
{
|
||||||
|
R,
|
||||||
|
G,
|
||||||
|
B,
|
||||||
|
A,
|
||||||
|
}
|
||||||
|
|
||||||
|
internal enum KAxis
|
||||||
|
{
|
||||||
|
X,
|
||||||
|
Y,
|
||||||
|
}
|
||||||
|
|
||||||
|
internal enum KArithOp
|
||||||
|
{
|
||||||
|
Add,
|
||||||
|
Subtract,
|
||||||
|
Multiply,
|
||||||
|
Divide,
|
||||||
|
Modulo,
|
||||||
|
Power,
|
||||||
|
}
|
||||||
|
|
||||||
|
internal enum KCompareOp
|
||||||
|
{
|
||||||
|
Less,
|
||||||
|
Greater,
|
||||||
|
LessEqual,
|
||||||
|
GreaterEqual,
|
||||||
|
Equal,
|
||||||
|
NotEqual,
|
||||||
|
}
|
||||||
|
|
||||||
|
internal enum KFunc
|
||||||
|
{
|
||||||
|
Abs,
|
||||||
|
Floor,
|
||||||
|
Ceil,
|
||||||
|
Sqrt,
|
||||||
|
Sin,
|
||||||
|
Cos,
|
||||||
|
Tan,
|
||||||
|
Asin,
|
||||||
|
Acos,
|
||||||
|
Atan,
|
||||||
|
Atan2,
|
||||||
|
Exp,
|
||||||
|
Log,
|
||||||
|
Pow,
|
||||||
|
Min,
|
||||||
|
Max,
|
||||||
|
Fmod,
|
||||||
|
}
|
||||||
|
|
||||||
|
internal abstract record KExpr;
|
||||||
|
|
||||||
|
internal sealed record KConst(double Value) : KExpr;
|
||||||
|
|
||||||
|
internal sealed record KInput(KChannel Channel) : KExpr;
|
||||||
|
|
||||||
|
internal sealed record KCoord(KAxis Axis) : KExpr;
|
||||||
|
|
||||||
|
internal sealed record KUniformRef(KernelUniform Uniform) : KExpr;
|
||||||
|
|
||||||
|
internal sealed record KLocalRef(int Slot) : KExpr;
|
||||||
|
|
||||||
|
internal sealed record KArith(KArithOp Op, KExpr Left, KExpr Right) : KExpr;
|
||||||
|
|
||||||
|
internal sealed record KNegate(KExpr Operand) : KExpr;
|
||||||
|
|
||||||
|
internal sealed record KCall(KFunc Func, IReadOnlyList<KExpr> Arguments) : KExpr;
|
||||||
|
|
||||||
|
internal sealed record KSelect(KBool Condition, KExpr WhenTrue, KExpr WhenFalse) : KExpr;
|
||||||
|
|
||||||
|
internal abstract record KBool;
|
||||||
|
|
||||||
|
internal sealed record KCompare(KCompareOp Op, KExpr Left, KExpr Right) : KBool;
|
||||||
|
|
||||||
|
internal sealed record KLogical(bool IsAnd, KBool Left, KBool Right) : KBool;
|
||||||
|
|
||||||
|
internal sealed record KNot(KBool Operand) : KBool;
|
||||||
|
|
||||||
|
internal sealed record KBoolConst(bool Value) : KBool;
|
||||||
|
|
||||||
|
internal sealed record KernelProgram(
|
||||||
|
IReadOnlyList<KExpr> Bindings,
|
||||||
|
KExpr OutputR,
|
||||||
|
KExpr OutputG,
|
||||||
|
KExpr OutputB,
|
||||||
|
KExpr OutputA,
|
||||||
|
IReadOnlyList<KernelUniform> Uniforms);
|
||||||
|
}
|
||||||
@@ -0,0 +1,155 @@
|
|||||||
|
using System;
|
||||||
|
using System.Collections.Generic;
|
||||||
|
|
||||||
|
namespace LuaScript.Engine.Kernel
|
||||||
|
{
|
||||||
|
internal enum KernelUniform
|
||||||
|
{
|
||||||
|
Width,
|
||||||
|
Height,
|
||||||
|
HalfWidth,
|
||||||
|
HalfHeight,
|
||||||
|
CenterX,
|
||||||
|
CenterY,
|
||||||
|
CenterZ,
|
||||||
|
Diagonal,
|
||||||
|
X,
|
||||||
|
Y,
|
||||||
|
Z,
|
||||||
|
Ox,
|
||||||
|
Oy,
|
||||||
|
Oz,
|
||||||
|
Sx,
|
||||||
|
Sy,
|
||||||
|
Sz,
|
||||||
|
Zoom,
|
||||||
|
Aspect,
|
||||||
|
Alpha,
|
||||||
|
Rx,
|
||||||
|
Ry,
|
||||||
|
Rz,
|
||||||
|
Rxr,
|
||||||
|
Ryr,
|
||||||
|
Rzr,
|
||||||
|
Track0,
|
||||||
|
Track1,
|
||||||
|
Track2,
|
||||||
|
Track3,
|
||||||
|
Slider0,
|
||||||
|
Slider1,
|
||||||
|
Slider2,
|
||||||
|
Slider3,
|
||||||
|
Check0,
|
||||||
|
Check1,
|
||||||
|
Check2,
|
||||||
|
Check3,
|
||||||
|
Color,
|
||||||
|
Time,
|
||||||
|
Frame,
|
||||||
|
TotalFrame,
|
||||||
|
TotalTime,
|
||||||
|
T,
|
||||||
|
Framerate,
|
||||||
|
Layer,
|
||||||
|
Index,
|
||||||
|
Num,
|
||||||
|
SceneWidth,
|
||||||
|
SceneHeight,
|
||||||
|
SceneCenterX,
|
||||||
|
SceneCenterY,
|
||||||
|
TimelineFrame,
|
||||||
|
TimelineTime,
|
||||||
|
}
|
||||||
|
|
||||||
|
internal static class KernelUniforms
|
||||||
|
{
|
||||||
|
public static int Count { get; } = Enum.GetValues<KernelUniform>().Length;
|
||||||
|
|
||||||
|
private static readonly Dictionary<string, KernelUniform> Globals = new(StringComparer.Ordinal)
|
||||||
|
{
|
||||||
|
["time"] = KernelUniform.Time,
|
||||||
|
["frame"] = KernelUniform.Frame,
|
||||||
|
["totalframe"] = KernelUniform.TotalFrame,
|
||||||
|
["framerate"] = KernelUniform.Framerate,
|
||||||
|
["timelineframe"] = KernelUniform.TimelineFrame,
|
||||||
|
["timelinetime"] = KernelUniform.TimelineTime,
|
||||||
|
["layer"] = KernelUniform.Layer,
|
||||||
|
["color"] = KernelUniform.Color,
|
||||||
|
};
|
||||||
|
|
||||||
|
private static readonly Dictionary<string, KernelUniform> ObjectFields = new(StringComparer.Ordinal)
|
||||||
|
{
|
||||||
|
["w"] = KernelUniform.Width,
|
||||||
|
["h"] = KernelUniform.Height,
|
||||||
|
["hw"] = KernelUniform.HalfWidth,
|
||||||
|
["hh"] = KernelUniform.HalfHeight,
|
||||||
|
["cx"] = KernelUniform.CenterX,
|
||||||
|
["cy"] = KernelUniform.CenterY,
|
||||||
|
["cz"] = KernelUniform.CenterZ,
|
||||||
|
["diagonal"] = KernelUniform.Diagonal,
|
||||||
|
["x"] = KernelUniform.X,
|
||||||
|
["y"] = KernelUniform.Y,
|
||||||
|
["z"] = KernelUniform.Z,
|
||||||
|
["ox"] = KernelUniform.Ox,
|
||||||
|
["oy"] = KernelUniform.Oy,
|
||||||
|
["oz"] = KernelUniform.Oz,
|
||||||
|
["sx"] = KernelUniform.Sx,
|
||||||
|
["sy"] = KernelUniform.Sy,
|
||||||
|
["sz"] = KernelUniform.Sz,
|
||||||
|
["zoom"] = KernelUniform.Zoom,
|
||||||
|
["aspect"] = KernelUniform.Aspect,
|
||||||
|
["alpha"] = KernelUniform.Alpha,
|
||||||
|
["rx"] = KernelUniform.Rx,
|
||||||
|
["ry"] = KernelUniform.Ry,
|
||||||
|
["rz"] = KernelUniform.Rz,
|
||||||
|
["rxr"] = KernelUniform.Rxr,
|
||||||
|
["ryr"] = KernelUniform.Ryr,
|
||||||
|
["rzr"] = KernelUniform.Rzr,
|
||||||
|
["track0"] = KernelUniform.Track0,
|
||||||
|
["track1"] = KernelUniform.Track1,
|
||||||
|
["track2"] = KernelUniform.Track2,
|
||||||
|
["track3"] = KernelUniform.Track3,
|
||||||
|
["slider0"] = KernelUniform.Slider0,
|
||||||
|
["slider1"] = KernelUniform.Slider1,
|
||||||
|
["slider2"] = KernelUniform.Slider2,
|
||||||
|
["slider3"] = KernelUniform.Slider3,
|
||||||
|
["check0"] = KernelUniform.Check0,
|
||||||
|
["check1"] = KernelUniform.Check1,
|
||||||
|
["check2"] = KernelUniform.Check2,
|
||||||
|
["check3"] = KernelUniform.Check3,
|
||||||
|
["time"] = KernelUniform.Time,
|
||||||
|
["frame"] = KernelUniform.Frame,
|
||||||
|
["totalframe"] = KernelUniform.TotalFrame,
|
||||||
|
["totaltime"] = KernelUniform.TotalTime,
|
||||||
|
["t"] = KernelUniform.T,
|
||||||
|
["framerate"] = KernelUniform.Framerate,
|
||||||
|
["layer"] = KernelUniform.Layer,
|
||||||
|
["index"] = KernelUniform.Index,
|
||||||
|
["num"] = KernelUniform.Num,
|
||||||
|
};
|
||||||
|
|
||||||
|
private static readonly Dictionary<string, KernelUniform> SceneFields = new(StringComparer.Ordinal)
|
||||||
|
{
|
||||||
|
["width"] = KernelUniform.SceneWidth,
|
||||||
|
["height"] = KernelUniform.SceneHeight,
|
||||||
|
["cx"] = KernelUniform.SceneCenterX,
|
||||||
|
["cy"] = KernelUniform.SceneCenterY,
|
||||||
|
};
|
||||||
|
|
||||||
|
public static bool TryResolveGlobal(string name, out KernelUniform uniform) =>
|
||||||
|
Globals.TryGetValue(name, out uniform);
|
||||||
|
|
||||||
|
public static bool TryResolveMember(string target, string field, out KernelUniform uniform)
|
||||||
|
{
|
||||||
|
uniform = default;
|
||||||
|
return target switch
|
||||||
|
{
|
||||||
|
"obj" => ObjectFields.TryGetValue(field, out uniform),
|
||||||
|
"scene" => SceneFields.TryGetValue(field, out uniform),
|
||||||
|
_ => false,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
public static string Field(KernelUniform uniform) => "u_" + uniform;
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,76 @@
|
|||||||
|
using System;
|
||||||
|
|
||||||
|
namespace LuaScript.Engine.Kernel
|
||||||
|
{
|
||||||
|
internal static class KernelUniformBinding
|
||||||
|
{
|
||||||
|
public static double[] Create() => new double[KernelUniforms.Count];
|
||||||
|
|
||||||
|
public static void Fill(AviUtlScriptContext ctx, double[] values)
|
||||||
|
{
|
||||||
|
values[(int)KernelUniform.Width] = ctx.ImageWidth;
|
||||||
|
values[(int)KernelUniform.Height] = ctx.ImageHeight;
|
||||||
|
values[(int)KernelUniform.HalfWidth] = ctx.ImageWidth / 2d;
|
||||||
|
values[(int)KernelUniform.HalfHeight] = ctx.ImageHeight / 2d;
|
||||||
|
values[(int)KernelUniform.CenterX] = ctx.ImageWidth / 2d;
|
||||||
|
values[(int)KernelUniform.CenterY] = ctx.ImageHeight / 2d;
|
||||||
|
values[(int)KernelUniform.CenterZ] = 0d;
|
||||||
|
values[(int)KernelUniform.Diagonal] = Math.Sqrt((double)ctx.ImageWidth * ctx.ImageWidth + (double)ctx.ImageHeight * ctx.ImageHeight);
|
||||||
|
values[(int)KernelUniform.X] = ctx.X;
|
||||||
|
values[(int)KernelUniform.Y] = ctx.Y;
|
||||||
|
values[(int)KernelUniform.Z] = ctx.Z;
|
||||||
|
values[(int)KernelUniform.Ox] = ctx.Ox;
|
||||||
|
values[(int)KernelUniform.Oy] = ctx.Oy;
|
||||||
|
values[(int)KernelUniform.Oz] = ctx.Oz;
|
||||||
|
values[(int)KernelUniform.Sx] = ctx.Sx;
|
||||||
|
values[(int)KernelUniform.Sy] = ctx.Sy;
|
||||||
|
values[(int)KernelUniform.Sz] = 1d;
|
||||||
|
values[(int)KernelUniform.Zoom] = ctx.Zoom;
|
||||||
|
values[(int)KernelUniform.Aspect] = ctx.Aspect;
|
||||||
|
values[(int)KernelUniform.Alpha] = ctx.Alpha;
|
||||||
|
values[(int)KernelUniform.Rx] = ctx.Rx;
|
||||||
|
values[(int)KernelUniform.Ry] = ctx.Ry;
|
||||||
|
values[(int)KernelUniform.Rz] = ctx.Rz;
|
||||||
|
values[(int)KernelUniform.Rxr] = ctx.RxRad;
|
||||||
|
values[(int)KernelUniform.Ryr] = ctx.RyRad;
|
||||||
|
values[(int)KernelUniform.Rzr] = ctx.RzRad;
|
||||||
|
values[(int)KernelUniform.Track0] = ctx.Track0;
|
||||||
|
values[(int)KernelUniform.Track1] = ctx.Track1;
|
||||||
|
values[(int)KernelUniform.Track2] = ctx.Track2;
|
||||||
|
values[(int)KernelUniform.Track3] = ctx.Track3;
|
||||||
|
values[(int)KernelUniform.Slider0] = ctx.Slider0;
|
||||||
|
values[(int)KernelUniform.Slider1] = ctx.Slider1;
|
||||||
|
values[(int)KernelUniform.Slider2] = ctx.Slider2;
|
||||||
|
values[(int)KernelUniform.Slider3] = ctx.Slider3;
|
||||||
|
values[(int)KernelUniform.Check0] = ctx.Check0 ? 1d : 0d;
|
||||||
|
values[(int)KernelUniform.Check1] = ctx.Check1 ? 1d : 0d;
|
||||||
|
values[(int)KernelUniform.Check2] = ctx.Check2 ? 1d : 0d;
|
||||||
|
values[(int)KernelUniform.Check3] = ctx.Check3 ? 1d : 0d;
|
||||||
|
values[(int)KernelUniform.Color] = ctx.HasColor ? ctx.ColorValue : -1d;
|
||||||
|
values[(int)KernelUniform.Time] = ctx.Time;
|
||||||
|
values[(int)KernelUniform.Frame] = ctx.Frame;
|
||||||
|
values[(int)KernelUniform.TotalFrame] = ctx.TotalFrame;
|
||||||
|
values[(int)KernelUniform.TotalTime] = ctx.TotalTime;
|
||||||
|
values[(int)KernelUniform.T] = ctx.TotalFrame > 0 ? ctx.Frame / (double)ctx.TotalFrame : 0d;
|
||||||
|
values[(int)KernelUniform.Framerate] = ctx.Framerate;
|
||||||
|
values[(int)KernelUniform.Layer] = ctx.Layer;
|
||||||
|
values[(int)KernelUniform.Index] = ctx.Index;
|
||||||
|
values[(int)KernelUniform.Num] = ctx.Num;
|
||||||
|
values[(int)KernelUniform.SceneWidth] = ctx.SceneWidth;
|
||||||
|
values[(int)KernelUniform.SceneHeight] = ctx.SceneHeight;
|
||||||
|
values[(int)KernelUniform.SceneCenterX] = ctx.SceneWidth / 2d;
|
||||||
|
values[(int)KernelUniform.SceneCenterY] = ctx.SceneHeight / 2d;
|
||||||
|
values[(int)KernelUniform.TimelineFrame] = ctx.TimelineFrame;
|
||||||
|
values[(int)KernelUniform.TimelineTime] = ctx.TimelineTime;
|
||||||
|
}
|
||||||
|
|
||||||
|
public static void Pack(double[] values, float[] packed)
|
||||||
|
{
|
||||||
|
int count = Math.Min(values.Length, packed.Length);
|
||||||
|
for (int i = 0; i < count; i++)
|
||||||
|
packed[i] = (float)values[i];
|
||||||
|
for (int i = count; i < packed.Length; i++)
|
||||||
|
packed[i] = 0f;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,4 @@
|
|||||||
|
namespace LuaScript.Engine.Kernel
|
||||||
|
{
|
||||||
|
internal sealed class KernelUnsupportedException(string reason) : Exception(reason);
|
||||||
|
}
|
||||||
@@ -0,0 +1,45 @@
|
|||||||
|
using System.Collections.Generic;
|
||||||
|
|
||||||
|
namespace LuaScript.Engine.Kernel
|
||||||
|
{
|
||||||
|
internal abstract record LuaExpr;
|
||||||
|
|
||||||
|
internal sealed record NumberExpr(double Value) : LuaExpr;
|
||||||
|
|
||||||
|
internal sealed record BoolExpr(bool Value) : LuaExpr;
|
||||||
|
|
||||||
|
internal sealed record NilExpr : LuaExpr;
|
||||||
|
|
||||||
|
internal sealed record StringExpr(string Value) : LuaExpr;
|
||||||
|
|
||||||
|
internal sealed record NameExpr(string Name) : LuaExpr;
|
||||||
|
|
||||||
|
internal sealed record MemberExpr(LuaExpr Target, string Name) : LuaExpr;
|
||||||
|
|
||||||
|
internal sealed record IndexExpr(LuaExpr Target, LuaExpr Key) : LuaExpr;
|
||||||
|
|
||||||
|
internal sealed record CallExpr(LuaExpr Target, IReadOnlyList<LuaExpr> Arguments) : LuaExpr;
|
||||||
|
|
||||||
|
internal sealed record UnaryExpr(string Operator, LuaExpr Operand) : LuaExpr;
|
||||||
|
|
||||||
|
internal sealed record BinaryExpr(string Operator, LuaExpr Left, LuaExpr Right) : LuaExpr;
|
||||||
|
|
||||||
|
internal abstract record LuaStmt;
|
||||||
|
|
||||||
|
internal sealed record LocalStmt(IReadOnlyList<string> Names, IReadOnlyList<LuaExpr> Values) : LuaStmt;
|
||||||
|
|
||||||
|
internal sealed record AssignStmt(IReadOnlyList<LuaExpr> Targets, IReadOnlyList<LuaExpr> Values) : LuaStmt;
|
||||||
|
|
||||||
|
internal sealed record CallStmt(CallExpr Call) : LuaStmt;
|
||||||
|
|
||||||
|
internal sealed record IfClause(LuaExpr Condition, IReadOnlyList<LuaStmt> Body);
|
||||||
|
|
||||||
|
internal sealed record IfStmt(IReadOnlyList<IfClause> Clauses, IReadOnlyList<LuaStmt>? ElseBody) : LuaStmt;
|
||||||
|
|
||||||
|
internal sealed record NumericForStmt(
|
||||||
|
string Variable,
|
||||||
|
LuaExpr Start,
|
||||||
|
LuaExpr Stop,
|
||||||
|
LuaExpr? Step,
|
||||||
|
IReadOnlyList<LuaStmt> Body) : LuaStmt;
|
||||||
|
}
|
||||||
@@ -0,0 +1,310 @@
|
|||||||
|
using System;
|
||||||
|
using System.Collections.Generic;
|
||||||
|
using System.Globalization;
|
||||||
|
|
||||||
|
namespace LuaScript.Engine.Kernel
|
||||||
|
{
|
||||||
|
internal static class LuaLexer
|
||||||
|
{
|
||||||
|
private static readonly HashSet<string> Keywords = new(StringComparer.Ordinal)
|
||||||
|
{
|
||||||
|
"and", "break", "do", "else", "elseif", "end", "false", "for", "function",
|
||||||
|
"if", "in", "local", "nil", "not", "or", "repeat", "return", "then",
|
||||||
|
"true", "until", "while",
|
||||||
|
};
|
||||||
|
|
||||||
|
public static List<LuaToken> Tokenize(string source)
|
||||||
|
{
|
||||||
|
var tokens = new List<LuaToken>();
|
||||||
|
int i = 0;
|
||||||
|
int length = source.Length;
|
||||||
|
|
||||||
|
while (i < length)
|
||||||
|
{
|
||||||
|
char c = source[i];
|
||||||
|
|
||||||
|
if (c is ' ' or '\t' or '\r' or '\n' or '\f' or '\v')
|
||||||
|
{
|
||||||
|
i++;
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (c == '-' && i + 1 < length && source[i + 1] == '-')
|
||||||
|
{
|
||||||
|
i = SkipComment(source, i + 2);
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (c == '"' || c == '\'')
|
||||||
|
{
|
||||||
|
i = ReadShortString(source, i, tokens);
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (c == '[' && i + 1 < length && (source[i + 1] == '[' || source[i + 1] == '='))
|
||||||
|
{
|
||||||
|
int level = LongBracketLevel(source, i);
|
||||||
|
if (level >= 0)
|
||||||
|
{
|
||||||
|
i = ReadLongString(source, i, level, tokens);
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
if (char.IsDigit(c) || (c == '.' && i + 1 < length && char.IsDigit(source[i + 1])))
|
||||||
|
{
|
||||||
|
i = ReadNumber(source, i, tokens);
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (IsNameStart(c))
|
||||||
|
{
|
||||||
|
i = ReadName(source, i, tokens);
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
|
||||||
|
i = ReadSymbol(source, i, tokens);
|
||||||
|
}
|
||||||
|
|
||||||
|
tokens.Add(new LuaToken(LuaTokenKind.Eof, string.Empty, 0d));
|
||||||
|
return tokens;
|
||||||
|
}
|
||||||
|
|
||||||
|
private static int SkipComment(string source, int i)
|
||||||
|
{
|
||||||
|
int level = LongBracketLevel(source, i);
|
||||||
|
if (level >= 0)
|
||||||
|
return SkipLongBracket(source, i, level);
|
||||||
|
|
||||||
|
int length = source.Length;
|
||||||
|
while (i < length && source[i] != '\n')
|
||||||
|
i++;
|
||||||
|
return i;
|
||||||
|
}
|
||||||
|
|
||||||
|
private static int LongBracketLevel(string source, int i)
|
||||||
|
{
|
||||||
|
if (i >= source.Length || source[i] != '[')
|
||||||
|
return -1;
|
||||||
|
int j = i + 1;
|
||||||
|
int level = 0;
|
||||||
|
while (j < source.Length && source[j] == '=')
|
||||||
|
{
|
||||||
|
level++;
|
||||||
|
j++;
|
||||||
|
}
|
||||||
|
return j < source.Length && source[j] == '[' ? level : -1;
|
||||||
|
}
|
||||||
|
|
||||||
|
private static int SkipLongBracket(string source, int i, int level)
|
||||||
|
{
|
||||||
|
int length = source.Length;
|
||||||
|
i += level + 2;
|
||||||
|
while (i < length)
|
||||||
|
{
|
||||||
|
if (source[i] == ']')
|
||||||
|
{
|
||||||
|
int j = i + 1;
|
||||||
|
int count = 0;
|
||||||
|
while (j < length && source[j] == '=')
|
||||||
|
{
|
||||||
|
count++;
|
||||||
|
j++;
|
||||||
|
}
|
||||||
|
if (count == level && j < length && source[j] == ']')
|
||||||
|
return j + 1;
|
||||||
|
}
|
||||||
|
i++;
|
||||||
|
}
|
||||||
|
throw new KernelUnsupportedException("Unterminated long bracket.");
|
||||||
|
}
|
||||||
|
|
||||||
|
private static int ReadLongString(string source, int start, int level, List<LuaToken> tokens)
|
||||||
|
{
|
||||||
|
int end = SkipLongBracket(source, start, level);
|
||||||
|
int contentStart = start + level + 2;
|
||||||
|
int contentEnd = end - level - 2;
|
||||||
|
string text = source.Substring(contentStart, Math.Max(0, contentEnd - contentStart));
|
||||||
|
tokens.Add(new LuaToken(LuaTokenKind.String, text, 0d));
|
||||||
|
return end;
|
||||||
|
}
|
||||||
|
|
||||||
|
private static int ReadShortString(string source, int start, List<LuaToken> tokens)
|
||||||
|
{
|
||||||
|
char quote = source[start];
|
||||||
|
int i = start + 1;
|
||||||
|
int length = source.Length;
|
||||||
|
var value = new System.Text.StringBuilder();
|
||||||
|
|
||||||
|
while (i < length)
|
||||||
|
{
|
||||||
|
char c = source[i];
|
||||||
|
if (c == quote)
|
||||||
|
{
|
||||||
|
tokens.Add(new LuaToken(LuaTokenKind.String, value.ToString(), 0d));
|
||||||
|
return i + 1;
|
||||||
|
}
|
||||||
|
if (c == '\n')
|
||||||
|
throw new KernelUnsupportedException("Unterminated string.");
|
||||||
|
if (c == '\\')
|
||||||
|
{
|
||||||
|
i = ReadEscape(source, i + 1, value);
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
value.Append(c);
|
||||||
|
i++;
|
||||||
|
}
|
||||||
|
throw new KernelUnsupportedException("Unterminated string.");
|
||||||
|
}
|
||||||
|
|
||||||
|
private static int ReadEscape(string source, int i, System.Text.StringBuilder value)
|
||||||
|
{
|
||||||
|
if (i >= source.Length)
|
||||||
|
throw new KernelUnsupportedException("Unterminated string escape.");
|
||||||
|
|
||||||
|
char c = source[i];
|
||||||
|
switch (c)
|
||||||
|
{
|
||||||
|
case 'n': value.Append('\n'); return i + 1;
|
||||||
|
case 't': value.Append('\t'); return i + 1;
|
||||||
|
case 'r': value.Append('\r'); return i + 1;
|
||||||
|
case 'a': value.Append('\a'); return i + 1;
|
||||||
|
case 'b': value.Append('\b'); return i + 1;
|
||||||
|
case 'f': value.Append('\f'); return i + 1;
|
||||||
|
case 'v': value.Append('\v'); return i + 1;
|
||||||
|
case '\\': value.Append('\\'); return i + 1;
|
||||||
|
case '"': value.Append('"'); return i + 1;
|
||||||
|
case '\'': value.Append('\''); return i + 1;
|
||||||
|
case '\n': value.Append('\n'); return i + 1;
|
||||||
|
default:
|
||||||
|
if (char.IsDigit(c))
|
||||||
|
{
|
||||||
|
int n = 0;
|
||||||
|
int count = 0;
|
||||||
|
while (i < source.Length && count < 3 && char.IsDigit(source[i]))
|
||||||
|
{
|
||||||
|
n = n * 10 + (source[i] - '0');
|
||||||
|
i++;
|
||||||
|
count++;
|
||||||
|
}
|
||||||
|
value.Append((char)n);
|
||||||
|
return i;
|
||||||
|
}
|
||||||
|
value.Append(c);
|
||||||
|
return i + 1;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private static int ReadNumber(string source, int start, List<LuaToken> tokens)
|
||||||
|
{
|
||||||
|
int length = source.Length;
|
||||||
|
int i = start;
|
||||||
|
|
||||||
|
if (source[i] == '0' && i + 1 < length && (source[i + 1] == 'x' || source[i + 1] == 'X'))
|
||||||
|
{
|
||||||
|
i += 2;
|
||||||
|
int digitsStart = i;
|
||||||
|
while (i < length && Uri.IsHexDigit(source[i]))
|
||||||
|
i++;
|
||||||
|
if (i == digitsStart)
|
||||||
|
throw new KernelUnsupportedException("Malformed hexadecimal literal.");
|
||||||
|
string hex = source.Substring(digitsStart, i - digitsStart);
|
||||||
|
double hexValue = (double)ulong.Parse(hex, NumberStyles.HexNumber, CultureInfo.InvariantCulture);
|
||||||
|
tokens.Add(new LuaToken(LuaTokenKind.Number, source.Substring(start, i - start), hexValue));
|
||||||
|
return i;
|
||||||
|
}
|
||||||
|
|
||||||
|
while (i < length && char.IsDigit(source[i]))
|
||||||
|
i++;
|
||||||
|
if (i < length && source[i] == '.')
|
||||||
|
{
|
||||||
|
i++;
|
||||||
|
while (i < length && char.IsDigit(source[i]))
|
||||||
|
i++;
|
||||||
|
}
|
||||||
|
if (i < length && (source[i] == 'e' || source[i] == 'E'))
|
||||||
|
{
|
||||||
|
i++;
|
||||||
|
if (i < length && (source[i] == '+' || source[i] == '-'))
|
||||||
|
i++;
|
||||||
|
while (i < length && char.IsDigit(source[i]))
|
||||||
|
i++;
|
||||||
|
}
|
||||||
|
|
||||||
|
string text = source.Substring(start, i - start);
|
||||||
|
double value = double.Parse(text, NumberStyles.Float, CultureInfo.InvariantCulture);
|
||||||
|
tokens.Add(new LuaToken(LuaTokenKind.Number, text, value));
|
||||||
|
return i;
|
||||||
|
}
|
||||||
|
|
||||||
|
private static int ReadName(string source, int start, List<LuaToken> tokens)
|
||||||
|
{
|
||||||
|
int i = start;
|
||||||
|
int length = source.Length;
|
||||||
|
while (i < length && IsNamePart(source[i]))
|
||||||
|
i++;
|
||||||
|
string text = source.Substring(start, i - start);
|
||||||
|
tokens.Add(new LuaToken(Keywords.Contains(text) ? LuaTokenKind.Keyword : LuaTokenKind.Name, text, 0d));
|
||||||
|
return i;
|
||||||
|
}
|
||||||
|
|
||||||
|
private static int ReadSymbol(string source, int start, List<LuaToken> tokens)
|
||||||
|
{
|
||||||
|
int length = source.Length;
|
||||||
|
char c = source[start];
|
||||||
|
|
||||||
|
if (c == '.' && start + 2 < length && source[start + 1] == '.' && source[start + 2] == '.')
|
||||||
|
{
|
||||||
|
tokens.Add(new LuaToken(LuaTokenKind.Symbol, "...", 0d));
|
||||||
|
return start + 3;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (start + 1 < length)
|
||||||
|
{
|
||||||
|
string two = source.Substring(start, 2);
|
||||||
|
switch (two)
|
||||||
|
{
|
||||||
|
case "==":
|
||||||
|
case "~=":
|
||||||
|
case "<=":
|
||||||
|
case ">=":
|
||||||
|
case "..":
|
||||||
|
tokens.Add(new LuaToken(LuaTokenKind.Symbol, two, 0d));
|
||||||
|
return start + 2;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
switch (c)
|
||||||
|
{
|
||||||
|
case '+':
|
||||||
|
case '-':
|
||||||
|
case '*':
|
||||||
|
case '/':
|
||||||
|
case '%':
|
||||||
|
case '^':
|
||||||
|
case '#':
|
||||||
|
case '<':
|
||||||
|
case '>':
|
||||||
|
case '=':
|
||||||
|
case '(':
|
||||||
|
case ')':
|
||||||
|
case '{':
|
||||||
|
case '}':
|
||||||
|
case '[':
|
||||||
|
case ']':
|
||||||
|
case ';':
|
||||||
|
case ':':
|
||||||
|
case ',':
|
||||||
|
case '.':
|
||||||
|
tokens.Add(new LuaToken(LuaTokenKind.Symbol, c.ToString(), 0d));
|
||||||
|
return start + 1;
|
||||||
|
default:
|
||||||
|
throw new KernelUnsupportedException($"Unexpected character '{c}'.");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private static bool IsNameStart(char c) => c == '_' || char.IsLetter(c);
|
||||||
|
|
||||||
|
private static bool IsNamePart(char c) => c == '_' || char.IsLetterOrDigit(c);
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,349 @@
|
|||||||
|
using System.Collections.Generic;
|
||||||
|
|
||||||
|
namespace LuaScript.Engine.Kernel
|
||||||
|
{
|
||||||
|
internal sealed class LuaParser
|
||||||
|
{
|
||||||
|
private readonly List<LuaToken> _tokens;
|
||||||
|
private int _pos;
|
||||||
|
|
||||||
|
private LuaParser(List<LuaToken> tokens) => _tokens = tokens;
|
||||||
|
|
||||||
|
public static IReadOnlyList<LuaStmt> Parse(string source)
|
||||||
|
{
|
||||||
|
var parser = new LuaParser(LuaLexer.Tokenize(source));
|
||||||
|
var block = parser.ParseBlock();
|
||||||
|
parser.Expect(LuaTokenKind.Eof);
|
||||||
|
return block;
|
||||||
|
}
|
||||||
|
|
||||||
|
private LuaToken Current => _tokens[_pos];
|
||||||
|
|
||||||
|
private LuaToken Advance() => _tokens[_pos++];
|
||||||
|
|
||||||
|
private bool IsBlockEnd()
|
||||||
|
{
|
||||||
|
var t = Current;
|
||||||
|
return t.Kind == LuaTokenKind.Eof ||
|
||||||
|
t.IsKeyword("end") || t.IsKeyword("else") || t.IsKeyword("elseif") || t.IsKeyword("until");
|
||||||
|
}
|
||||||
|
|
||||||
|
private IReadOnlyList<LuaStmt> ParseBlock()
|
||||||
|
{
|
||||||
|
var statements = new List<LuaStmt>();
|
||||||
|
while (!IsBlockEnd())
|
||||||
|
{
|
||||||
|
if (Current.IsSymbol(";"))
|
||||||
|
{
|
||||||
|
Advance();
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
statements.Add(ParseStatement());
|
||||||
|
}
|
||||||
|
return statements;
|
||||||
|
}
|
||||||
|
|
||||||
|
private LuaStmt ParseStatement()
|
||||||
|
{
|
||||||
|
var t = Current;
|
||||||
|
if (t.IsKeyword("local"))
|
||||||
|
return ParseLocal();
|
||||||
|
if (t.IsKeyword("if"))
|
||||||
|
return ParseIf();
|
||||||
|
if (t.IsKeyword("for"))
|
||||||
|
return ParseFor();
|
||||||
|
if (t.Kind == LuaTokenKind.Keyword)
|
||||||
|
throw new KernelUnsupportedException($"Unsupported statement '{t.Text}'.");
|
||||||
|
return ParseExpressionStatement();
|
||||||
|
}
|
||||||
|
|
||||||
|
private LuaStmt ParseLocal()
|
||||||
|
{
|
||||||
|
Advance();
|
||||||
|
if (Current.IsKeyword("function"))
|
||||||
|
throw new KernelUnsupportedException("Local functions are not supported.");
|
||||||
|
|
||||||
|
var names = new List<string> { ExpectName() };
|
||||||
|
while (Current.IsSymbol(","))
|
||||||
|
{
|
||||||
|
Advance();
|
||||||
|
names.Add(ExpectName());
|
||||||
|
}
|
||||||
|
|
||||||
|
IReadOnlyList<LuaExpr> values = [];
|
||||||
|
if (Current.IsSymbol("="))
|
||||||
|
{
|
||||||
|
Advance();
|
||||||
|
values = ParseExpressionList();
|
||||||
|
}
|
||||||
|
return new LocalStmt(names, values);
|
||||||
|
}
|
||||||
|
|
||||||
|
private LuaStmt ParseIf()
|
||||||
|
{
|
||||||
|
Advance();
|
||||||
|
var clauses = new List<IfClause>();
|
||||||
|
|
||||||
|
var condition = ParseExpression();
|
||||||
|
ExpectKeyword("then");
|
||||||
|
clauses.Add(new IfClause(condition, ParseBlock()));
|
||||||
|
|
||||||
|
while (Current.IsKeyword("elseif"))
|
||||||
|
{
|
||||||
|
Advance();
|
||||||
|
var elseifCondition = ParseExpression();
|
||||||
|
ExpectKeyword("then");
|
||||||
|
clauses.Add(new IfClause(elseifCondition, ParseBlock()));
|
||||||
|
}
|
||||||
|
|
||||||
|
IReadOnlyList<LuaStmt>? elseBody = null;
|
||||||
|
if (Current.IsKeyword("else"))
|
||||||
|
{
|
||||||
|
Advance();
|
||||||
|
elseBody = ParseBlock();
|
||||||
|
}
|
||||||
|
|
||||||
|
ExpectKeyword("end");
|
||||||
|
return new IfStmt(clauses, elseBody);
|
||||||
|
}
|
||||||
|
|
||||||
|
private LuaStmt ParseFor()
|
||||||
|
{
|
||||||
|
Advance();
|
||||||
|
string variable = ExpectName();
|
||||||
|
if (!Current.IsSymbol("="))
|
||||||
|
throw new KernelUnsupportedException("Generic for loops are not supported.");
|
||||||
|
|
||||||
|
Advance();
|
||||||
|
var start = ParseExpression();
|
||||||
|
ExpectSymbol(",");
|
||||||
|
var stop = ParseExpression();
|
||||||
|
|
||||||
|
LuaExpr? step = null;
|
||||||
|
if (Current.IsSymbol(","))
|
||||||
|
{
|
||||||
|
Advance();
|
||||||
|
step = ParseExpression();
|
||||||
|
}
|
||||||
|
|
||||||
|
ExpectKeyword("do");
|
||||||
|
var body = ParseBlock();
|
||||||
|
ExpectKeyword("end");
|
||||||
|
return new NumericForStmt(variable, start, stop, step, body);
|
||||||
|
}
|
||||||
|
|
||||||
|
private LuaStmt ParseExpressionStatement()
|
||||||
|
{
|
||||||
|
var first = ParseSuffixedExpression();
|
||||||
|
|
||||||
|
if (Current.IsSymbol("=") || Current.IsSymbol(","))
|
||||||
|
{
|
||||||
|
var targets = new List<LuaExpr> { first };
|
||||||
|
while (Current.IsSymbol(","))
|
||||||
|
{
|
||||||
|
Advance();
|
||||||
|
targets.Add(ParseSuffixedExpression());
|
||||||
|
}
|
||||||
|
ExpectSymbol("=");
|
||||||
|
var values = ParseExpressionList();
|
||||||
|
return new AssignStmt(targets, values);
|
||||||
|
}
|
||||||
|
|
||||||
|
if (first is CallExpr call)
|
||||||
|
return new CallStmt(call);
|
||||||
|
|
||||||
|
throw new KernelUnsupportedException("Expression is not a valid statement.");
|
||||||
|
}
|
||||||
|
|
||||||
|
private List<LuaExpr> ParseExpressionList()
|
||||||
|
{
|
||||||
|
var values = new List<LuaExpr> { ParseExpression() };
|
||||||
|
while (Current.IsSymbol(","))
|
||||||
|
{
|
||||||
|
Advance();
|
||||||
|
values.Add(ParseExpression());
|
||||||
|
}
|
||||||
|
return values;
|
||||||
|
}
|
||||||
|
|
||||||
|
private LuaExpr ParseExpression(int minPrecedence = 0)
|
||||||
|
{
|
||||||
|
var left = ParseUnary();
|
||||||
|
while (true)
|
||||||
|
{
|
||||||
|
var (op, precedence, rightAssociative) = PeekBinaryOperator();
|
||||||
|
if (op is null || precedence < minPrecedence)
|
||||||
|
break;
|
||||||
|
Advance();
|
||||||
|
int nextMinimum = rightAssociative ? precedence : precedence + 1;
|
||||||
|
var right = ParseExpression(nextMinimum);
|
||||||
|
left = new BinaryExpr(op, left, right);
|
||||||
|
}
|
||||||
|
return left;
|
||||||
|
}
|
||||||
|
|
||||||
|
private LuaExpr ParseUnary()
|
||||||
|
{
|
||||||
|
var t = Current;
|
||||||
|
if (t.IsKeyword("not") || t.IsSymbol("-") || t.IsSymbol("#"))
|
||||||
|
{
|
||||||
|
Advance();
|
||||||
|
return new UnaryExpr(t.Text, ParseExpression(7));
|
||||||
|
}
|
||||||
|
return ParseValue();
|
||||||
|
}
|
||||||
|
|
||||||
|
private (string? Operator, int Precedence, bool RightAssociative) PeekBinaryOperator()
|
||||||
|
{
|
||||||
|
var t = Current;
|
||||||
|
if (t.IsKeyword("or")) return ("or", 1, false);
|
||||||
|
if (t.IsKeyword("and")) return ("and", 2, false);
|
||||||
|
if (t.Kind == LuaTokenKind.Symbol)
|
||||||
|
{
|
||||||
|
switch (t.Text)
|
||||||
|
{
|
||||||
|
case "<":
|
||||||
|
case ">":
|
||||||
|
case "<=":
|
||||||
|
case ">=":
|
||||||
|
case "~=":
|
||||||
|
case "==":
|
||||||
|
return (t.Text, 3, false);
|
||||||
|
case "..":
|
||||||
|
return ("..", 4, true);
|
||||||
|
case "+":
|
||||||
|
case "-":
|
||||||
|
return (t.Text, 5, false);
|
||||||
|
case "*":
|
||||||
|
case "/":
|
||||||
|
case "%":
|
||||||
|
return (t.Text, 6, false);
|
||||||
|
case "^":
|
||||||
|
return ("^", 8, true);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return (null, 0, false);
|
||||||
|
}
|
||||||
|
|
||||||
|
private LuaExpr ParseValue()
|
||||||
|
{
|
||||||
|
var t = Current;
|
||||||
|
switch (t.Kind)
|
||||||
|
{
|
||||||
|
case LuaTokenKind.Number:
|
||||||
|
Advance();
|
||||||
|
return new NumberExpr(t.Number);
|
||||||
|
case LuaTokenKind.String:
|
||||||
|
Advance();
|
||||||
|
return new StringExpr(t.Text);
|
||||||
|
case LuaTokenKind.Keyword when t.Text == "true":
|
||||||
|
Advance();
|
||||||
|
return new BoolExpr(true);
|
||||||
|
case LuaTokenKind.Keyword when t.Text == "false":
|
||||||
|
Advance();
|
||||||
|
return new BoolExpr(false);
|
||||||
|
case LuaTokenKind.Keyword when t.Text == "nil":
|
||||||
|
Advance();
|
||||||
|
return new NilExpr();
|
||||||
|
}
|
||||||
|
|
||||||
|
if (t.IsKeyword("function") || t.IsSymbol("{") || t.IsSymbol("..."))
|
||||||
|
throw new KernelUnsupportedException($"Unsupported expression near '{t.Text}'.");
|
||||||
|
|
||||||
|
return ParseSuffixedExpression();
|
||||||
|
}
|
||||||
|
|
||||||
|
private LuaExpr ParseSuffixedExpression()
|
||||||
|
{
|
||||||
|
var expression = ParsePrimaryExpression();
|
||||||
|
while (true)
|
||||||
|
{
|
||||||
|
var t = Current;
|
||||||
|
if (t.IsSymbol("."))
|
||||||
|
{
|
||||||
|
Advance();
|
||||||
|
expression = new MemberExpr(expression, ExpectName());
|
||||||
|
}
|
||||||
|
else if (t.IsSymbol("["))
|
||||||
|
{
|
||||||
|
Advance();
|
||||||
|
var key = ParseExpression();
|
||||||
|
ExpectSymbol("]");
|
||||||
|
expression = new IndexExpr(expression, key);
|
||||||
|
}
|
||||||
|
else if (t.IsSymbol("("))
|
||||||
|
{
|
||||||
|
expression = new CallExpr(expression, ParseArguments());
|
||||||
|
}
|
||||||
|
else
|
||||||
|
{
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return expression;
|
||||||
|
}
|
||||||
|
|
||||||
|
private LuaExpr ParsePrimaryExpression()
|
||||||
|
{
|
||||||
|
var t = Current;
|
||||||
|
if (t.IsSymbol("("))
|
||||||
|
{
|
||||||
|
Advance();
|
||||||
|
var inner = ParseExpression();
|
||||||
|
ExpectSymbol(")");
|
||||||
|
return inner;
|
||||||
|
}
|
||||||
|
if (t.Kind == LuaTokenKind.Name)
|
||||||
|
{
|
||||||
|
Advance();
|
||||||
|
return new NameExpr(t.Text);
|
||||||
|
}
|
||||||
|
throw new KernelUnsupportedException($"Unexpected token '{t.Text}'.");
|
||||||
|
}
|
||||||
|
|
||||||
|
private List<LuaExpr> ParseArguments()
|
||||||
|
{
|
||||||
|
ExpectSymbol("(");
|
||||||
|
var arguments = new List<LuaExpr>();
|
||||||
|
if (!Current.IsSymbol(")"))
|
||||||
|
{
|
||||||
|
arguments.Add(ParseExpression());
|
||||||
|
while (Current.IsSymbol(","))
|
||||||
|
{
|
||||||
|
Advance();
|
||||||
|
arguments.Add(ParseExpression());
|
||||||
|
}
|
||||||
|
}
|
||||||
|
ExpectSymbol(")");
|
||||||
|
return arguments;
|
||||||
|
}
|
||||||
|
|
||||||
|
private string ExpectName()
|
||||||
|
{
|
||||||
|
if (Current.Kind != LuaTokenKind.Name)
|
||||||
|
throw new KernelUnsupportedException($"Expected a name but found '{Current.Text}'.");
|
||||||
|
return Advance().Text;
|
||||||
|
}
|
||||||
|
|
||||||
|
private void Expect(LuaTokenKind kind)
|
||||||
|
{
|
||||||
|
if (Current.Kind != kind)
|
||||||
|
throw new KernelUnsupportedException($"Expected {kind} but found '{Current.Text}'.");
|
||||||
|
Advance();
|
||||||
|
}
|
||||||
|
|
||||||
|
private void ExpectSymbol(string symbol)
|
||||||
|
{
|
||||||
|
if (!Current.IsSymbol(symbol))
|
||||||
|
throw new KernelUnsupportedException($"Expected '{symbol}' but found '{Current.Text}'.");
|
||||||
|
Advance();
|
||||||
|
}
|
||||||
|
|
||||||
|
private void ExpectKeyword(string keyword)
|
||||||
|
{
|
||||||
|
if (!Current.IsKeyword(keyword))
|
||||||
|
throw new KernelUnsupportedException($"Expected '{keyword}' but found '{Current.Text}'.");
|
||||||
|
Advance();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,28 @@
|
|||||||
|
using System;
|
||||||
|
|
||||||
|
namespace LuaScript.Engine.Kernel
|
||||||
|
{
|
||||||
|
internal enum LuaTokenKind
|
||||||
|
{
|
||||||
|
Name,
|
||||||
|
Number,
|
||||||
|
String,
|
||||||
|
Keyword,
|
||||||
|
Symbol,
|
||||||
|
Eof,
|
||||||
|
}
|
||||||
|
|
||||||
|
internal readonly struct LuaToken(LuaTokenKind kind, string text, double number)
|
||||||
|
{
|
||||||
|
public LuaTokenKind Kind { get; } = kind;
|
||||||
|
public string Text { get; } = text;
|
||||||
|
public double Number { get; } = number;
|
||||||
|
|
||||||
|
public bool Is(LuaTokenKind kind, string text) =>
|
||||||
|
Kind == kind && string.Equals(Text, text, StringComparison.Ordinal);
|
||||||
|
|
||||||
|
public bool IsSymbol(string text) => Is(LuaTokenKind.Symbol, text);
|
||||||
|
|
||||||
|
public bool IsKeyword(string text) => Is(LuaTokenKind.Keyword, text);
|
||||||
|
}
|
||||||
|
}
|
||||||
+327
-10
@@ -21,12 +21,17 @@ namespace LuaScript.Engine
|
|||||||
private Process? _process;
|
private Process? _process;
|
||||||
private int _width;
|
private int _width;
|
||||||
private int _height;
|
private int _height;
|
||||||
|
private int _stringParamsCapacity = NativeProtocol.MinStringParamsCapacity;
|
||||||
|
private long _pixelOffset = NativeProtocol.PixelOffset(NativeProtocol.MinStringParamsCapacity);
|
||||||
private bool _alive;
|
private bool _alive;
|
||||||
|
|
||||||
private readonly byte[] _callbackTag = new byte[NativeProtocol.CallbackTagMax];
|
private readonly byte[] _callbackTag = new byte[NativeProtocol.CallbackTagMax];
|
||||||
private readonly byte[] _lastCallbackTag = new byte[NativeProtocol.CallbackTagMax];
|
private readonly byte[] _lastCallbackTag = new byte[NativeProtocol.CallbackTagMax];
|
||||||
private int _lastCallbackTagLength = -1;
|
private int _lastCallbackTagLength = -1;
|
||||||
private string _lastCallbackTagText = string.Empty;
|
private string _lastCallbackTagText = string.Empty;
|
||||||
|
private byte[]? _resultBuffer;
|
||||||
|
private readonly Dictionary<string, byte[]> _stringNameBytes = new(StringComparer.Ordinal);
|
||||||
|
private byte[] _stringValueBytes = new byte[256];
|
||||||
|
|
||||||
public LuaJitWorker(string nativeDir)
|
public LuaJitWorker(string nativeDir)
|
||||||
{
|
{
|
||||||
@@ -42,15 +47,30 @@ namespace LuaScript.Engine
|
|||||||
public bool Execute(
|
public bool Execute(
|
||||||
string script,
|
string script,
|
||||||
double[] fields,
|
double[] fields,
|
||||||
|
IReadOnlyDictionary<string, string> stringParameters,
|
||||||
byte[] pixels,
|
byte[] pixels,
|
||||||
int width,
|
int width,
|
||||||
int height,
|
int height,
|
||||||
int timeoutMs,
|
int timeoutMs,
|
||||||
Func<string, int, SceneObjectInfo?> resolveObject,
|
Func<string, int, SceneObjectInfo?> resolveObject,
|
||||||
|
Func<string, int, double, double, double, (byte[] buffer, int w, int h)> loadFigure,
|
||||||
|
Func<string, string, double, bool, bool, int, (byte[] buffer, int w, int h)> loadText,
|
||||||
|
Func<string, (byte[] buffer, int w, int h)> loadImage,
|
||||||
|
Func<string, double, (byte[] buffer, int w, int h)> loadMovie,
|
||||||
|
Action<string, IReadOnlyList<KeyValuePair<string, object>>> addEffect,
|
||||||
|
Action<DrawCommand> addDraw,
|
||||||
out bool pixelsDirty,
|
out bool pixelsDirty,
|
||||||
|
out bool bufferReplaced,
|
||||||
|
out byte[]? newPixels,
|
||||||
|
out int resultWidth,
|
||||||
|
out int resultHeight,
|
||||||
out string? error)
|
out string? error)
|
||||||
{
|
{
|
||||||
pixelsDirty = false;
|
pixelsDirty = false;
|
||||||
|
bufferReplaced = false;
|
||||||
|
newPixels = null;
|
||||||
|
resultWidth = width;
|
||||||
|
resultHeight = height;
|
||||||
error = null;
|
error = null;
|
||||||
|
|
||||||
byte[] scriptBytes = Encoding.UTF8.GetBytes(script);
|
byte[] scriptBytes = Encoding.UTF8.GetBytes(script);
|
||||||
@@ -60,15 +80,17 @@ namespace LuaScript.Engine
|
|||||||
return false;
|
return false;
|
||||||
}
|
}
|
||||||
|
|
||||||
EnsureWorker(width, height);
|
int stringCapacity = ResolveStringCapacity(_stringParamsCapacity, MeasureStringParameters(stringParameters));
|
||||||
|
EnsureWorker(width, height, stringCapacity);
|
||||||
var view = _view!;
|
var view = _view!;
|
||||||
|
|
||||||
view.WriteArray(NativeProtocol.FieldsOffset, fields, 0, NativeProtocol.FieldCount);
|
view.WriteArray(NativeProtocol.FieldsOffset, fields, 0, NativeProtocol.FieldCount);
|
||||||
|
WriteStringParameters(view, stringParameters);
|
||||||
view.Write(NativeProtocol.OffWidth, width);
|
view.Write(NativeProtocol.OffWidth, width);
|
||||||
view.Write(NativeProtocol.OffHeight, height);
|
view.Write(NativeProtocol.OffHeight, height);
|
||||||
view.Write(NativeProtocol.OffScriptLen, scriptBytes.Length);
|
view.Write(NativeProtocol.OffScriptLen, scriptBytes.Length);
|
||||||
view.WriteArray(NativeProtocol.ScriptOffset, scriptBytes, 0, scriptBytes.Length);
|
view.WriteArray(NativeProtocol.ScriptOffset, scriptBytes, 0, scriptBytes.Length);
|
||||||
view.WriteArray(NativeProtocol.PixelOffset, pixels, 0, pixels.Length);
|
view.WriteArray(_pixelOffset, pixels, 0, pixels.Length);
|
||||||
view.Write(NativeProtocol.OffPixelsDirty, 0);
|
view.Write(NativeProtocol.OffPixelsDirty, 0);
|
||||||
view.Write(NativeProtocol.OffErrorLen, 0);
|
view.Write(NativeProtocol.OffErrorLen, 0);
|
||||||
view.Write(NativeProtocol.OffStatus, NativeProtocol.StatusIdle);
|
view.Write(NativeProtocol.OffStatus, NativeProtocol.StatusIdle);
|
||||||
@@ -92,7 +114,7 @@ namespace LuaScript.Engine
|
|||||||
if (status != NativeProtocol.StatusCallback)
|
if (status != NativeProtocol.StatusCallback)
|
||||||
break;
|
break;
|
||||||
|
|
||||||
ResolveCallback(view, resolveObject);
|
DispatchCallback(view, resolveObject, loadFigure, loadText, loadImage, loadMovie, addEffect, addDraw);
|
||||||
_workEvent.Set();
|
_workEvent.Set();
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -108,14 +130,154 @@ namespace LuaScript.Engine
|
|||||||
for (int i = NativeProtocol.FirstWritableField; i <= NativeProtocol.LastWritableField; i++)
|
for (int i = NativeProtocol.FirstWritableField; i <= NativeProtocol.LastWritableField; i++)
|
||||||
fields[i] = view.ReadDouble(NativeProtocol.FieldsOffset + i * 8);
|
fields[i] = view.ReadDouble(NativeProtocol.FieldsOffset + i * 8);
|
||||||
|
|
||||||
|
resultWidth = view.ReadInt32(NativeProtocol.OffWidth);
|
||||||
|
resultHeight = view.ReadInt32(NativeProtocol.OffHeight);
|
||||||
|
bufferReplaced = resultWidth != width || resultHeight != height;
|
||||||
|
|
||||||
pixelsDirty = view.ReadInt32(NativeProtocol.OffPixelsDirty) != 0;
|
pixelsDirty = view.ReadInt32(NativeProtocol.OffPixelsDirty) != 0;
|
||||||
if (pixelsDirty)
|
if (pixelsDirty)
|
||||||
view.ReadArray(NativeProtocol.PixelOffset, pixels, 0, pixels.Length);
|
{
|
||||||
|
if (bufferReplaced)
|
||||||
|
{
|
||||||
|
int pixelSize = resultWidth * resultHeight * 4;
|
||||||
|
if (_resultBuffer == null || _resultBuffer.Length < pixelSize)
|
||||||
|
_resultBuffer = new byte[pixelSize];
|
||||||
|
view.ReadArray(_pixelOffset, _resultBuffer, 0, pixelSize);
|
||||||
|
newPixels = _resultBuffer;
|
||||||
|
}
|
||||||
|
else
|
||||||
|
{
|
||||||
|
view.ReadArray(_pixelOffset, pixels, 0, pixels.Length);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
return true;
|
return true;
|
||||||
}
|
}
|
||||||
|
|
||||||
private void ResolveCallback(MemoryMappedViewAccessor view, Func<string, int, SceneObjectInfo?> resolveObject)
|
private static int MeasureStringParameters(IReadOnlyDictionary<string, string> stringParameters)
|
||||||
|
{
|
||||||
|
int total = 4;
|
||||||
|
foreach (var pair in stringParameters)
|
||||||
|
total += 8 + Encoding.UTF8.GetByteCount(pair.Key) + Encoding.UTF8.GetByteCount(pair.Value ?? string.Empty);
|
||||||
|
return total;
|
||||||
|
}
|
||||||
|
|
||||||
|
private static int ResolveStringCapacity(int current, int required)
|
||||||
|
{
|
||||||
|
int capacity = current;
|
||||||
|
while (capacity < required)
|
||||||
|
{
|
||||||
|
if (capacity > int.MaxValue / 2)
|
||||||
|
{
|
||||||
|
capacity = required;
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
capacity *= 2;
|
||||||
|
}
|
||||||
|
while (capacity > NativeProtocol.MinStringParamsCapacity && required <= capacity / 2)
|
||||||
|
capacity /= 2;
|
||||||
|
return capacity;
|
||||||
|
}
|
||||||
|
|
||||||
|
private void WriteStringParameters(MemoryMappedViewAccessor view, IReadOnlyDictionary<string, string> stringParameters)
|
||||||
|
{
|
||||||
|
long basePos = NativeProtocol.StringParamsOffset;
|
||||||
|
long limit = basePos + _stringParamsCapacity;
|
||||||
|
long pos = basePos + 4;
|
||||||
|
int count = 0;
|
||||||
|
foreach (var pair in stringParameters)
|
||||||
|
{
|
||||||
|
if (!_stringNameBytes.TryGetValue(pair.Key, out var name))
|
||||||
|
{
|
||||||
|
name = Encoding.UTF8.GetBytes(pair.Key);
|
||||||
|
_stringNameBytes[pair.Key] = name;
|
||||||
|
}
|
||||||
|
string value = pair.Value ?? string.Empty;
|
||||||
|
int maxValueBytes = Encoding.UTF8.GetMaxByteCount(value.Length);
|
||||||
|
if (_stringValueBytes.Length < maxValueBytes)
|
||||||
|
_stringValueBytes = new byte[Math.Max(maxValueBytes, _stringValueBytes.Length * 2)];
|
||||||
|
int valueLen = Encoding.UTF8.GetBytes(value, 0, value.Length, _stringValueBytes, 0);
|
||||||
|
if (pos + 8 + name.Length + valueLen > limit)
|
||||||
|
break;
|
||||||
|
view.Write(pos, name.Length); pos += 4;
|
||||||
|
view.WriteArray(pos, name, 0, name.Length); pos += name.Length;
|
||||||
|
view.Write(pos, valueLen); pos += 4;
|
||||||
|
view.WriteArray(pos, _stringValueBytes, 0, valueLen); pos += valueLen;
|
||||||
|
count++;
|
||||||
|
}
|
||||||
|
view.Write(basePos, count);
|
||||||
|
view.Write(NativeProtocol.OffStringParamsLen, (int)(pos - basePos));
|
||||||
|
}
|
||||||
|
|
||||||
|
private void DispatchCallback(
|
||||||
|
MemoryMappedViewAccessor view,
|
||||||
|
Func<string, int, SceneObjectInfo?> resolveObject,
|
||||||
|
Func<string, int, double, double, double, (byte[] buffer, int w, int h)> loadFigure,
|
||||||
|
Func<string, string, double, bool, bool, int, (byte[] buffer, int w, int h)> loadText,
|
||||||
|
Func<string, (byte[] buffer, int w, int h)> loadImage,
|
||||||
|
Func<string, double, (byte[] buffer, int w, int h)> loadMovie,
|
||||||
|
Action<string, IReadOnlyList<KeyValuePair<string, object>>> addEffect,
|
||||||
|
Action<DrawCommand> addDraw)
|
||||||
|
{
|
||||||
|
int kind = view.ReadInt32(NativeProtocol.OffCallbackKind);
|
||||||
|
switch (kind)
|
||||||
|
{
|
||||||
|
case NativeProtocol.CbKindGetObject:
|
||||||
|
ResolveGetObjectCallback(view, resolveObject);
|
||||||
|
break;
|
||||||
|
case NativeProtocol.CbKindLoadFigure:
|
||||||
|
ResolveLoadFigureCallback(view, loadFigure);
|
||||||
|
break;
|
||||||
|
case NativeProtocol.CbKindLoadText:
|
||||||
|
ResolveLoadTextCallback(view, loadText);
|
||||||
|
break;
|
||||||
|
case NativeProtocol.CbKindLoadImage:
|
||||||
|
ResolveLoadImageCallback(view, loadImage);
|
||||||
|
break;
|
||||||
|
case NativeProtocol.CbKindLoadMovie:
|
||||||
|
ResolveLoadMovieCallback(view, loadMovie);
|
||||||
|
break;
|
||||||
|
case NativeProtocol.CbKindEffect:
|
||||||
|
ResolveEffectCallback(view, addEffect);
|
||||||
|
break;
|
||||||
|
case NativeProtocol.CbKindDraw:
|
||||||
|
ResolveDrawCallback(view, addDraw);
|
||||||
|
break;
|
||||||
|
case NativeProtocol.CbKindDrawPoly:
|
||||||
|
ResolveDrawPolyCallback(view, addDraw);
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private static void ResolveDrawCallback(MemoryMappedViewAccessor view, Action<DrawCommand> addDraw)
|
||||||
|
{
|
||||||
|
long rOff = NativeProtocol.CallbackResultOffset;
|
||||||
|
double ox = view.ReadDouble(rOff + 0 * 8);
|
||||||
|
double oy = view.ReadDouble(rOff + 1 * 8);
|
||||||
|
double oz = view.ReadDouble(rOff + 2 * 8);
|
||||||
|
double zoom = view.ReadDouble(rOff + 3 * 8);
|
||||||
|
double alpha = view.ReadDouble(rOff + 4 * 8);
|
||||||
|
double aspect = view.ReadDouble(rOff + 5 * 8);
|
||||||
|
double antialias = view.ReadDouble(rOff + 6 * 8);
|
||||||
|
|
||||||
|
try { addDraw(new DrawCommand(ox, oy, oz, zoom, alpha, aspect, null, antialias)); }
|
||||||
|
catch { }
|
||||||
|
view.Write(NativeProtocol.OffCallbackFound, 1);
|
||||||
|
}
|
||||||
|
|
||||||
|
private static void ResolveDrawPolyCallback(MemoryMappedViewAccessor view, Action<DrawCommand> addDraw)
|
||||||
|
{
|
||||||
|
var poly = new double[DrawPolyMath.Length];
|
||||||
|
for (int i = 0; i < DrawPolyMath.Length; i++)
|
||||||
|
poly[i] = view.ReadDouble(NativeProtocol.CallbackTagOffset + i * 8);
|
||||||
|
double antialias = view.ReadDouble(NativeProtocol.CallbackTagOffset + DrawPolyMath.Length * 8);
|
||||||
|
|
||||||
|
try { addDraw(new DrawCommand(0d, 0d, 0d, 1d, poly[20], 0d, poly, antialias)); }
|
||||||
|
catch { }
|
||||||
|
view.Write(NativeProtocol.OffCallbackFound, 1);
|
||||||
|
}
|
||||||
|
|
||||||
|
private void ResolveGetObjectCallback(MemoryMappedViewAccessor view, Func<string, int, SceneObjectInfo?> resolveObject)
|
||||||
{
|
{
|
||||||
int frame = view.ReadInt32(NativeProtocol.OffCallbackFrame);
|
int frame = view.ReadInt32(NativeProtocol.OffCallbackFrame);
|
||||||
int tagLen = Math.Clamp(view.ReadInt32(NativeProtocol.OffCallbackTagLen), 0, NativeProtocol.CallbackTagMax);
|
int tagLen = Math.Clamp(view.ReadInt32(NativeProtocol.OffCallbackTagLen), 0, NativeProtocol.CallbackTagMax);
|
||||||
@@ -145,6 +307,158 @@ namespace LuaScript.Engine
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
private void ResolveLoadFigureCallback(
|
||||||
|
MemoryMappedViewAccessor view,
|
||||||
|
Func<string, int, double, double, double, (byte[] buffer, int w, int h)> loadFigure)
|
||||||
|
{
|
||||||
|
int tagLen = Math.Clamp(view.ReadInt32(NativeProtocol.OffCallbackTagLen), 0, NativeProtocol.CallbackTagMax);
|
||||||
|
view.ReadArray(NativeProtocol.CallbackTagOffset, _callbackTag, 0, tagLen);
|
||||||
|
string name = Encoding.UTF8.GetString(_callbackTag, 0, tagLen);
|
||||||
|
|
||||||
|
long rOff = NativeProtocol.CallbackResultOffset;
|
||||||
|
int color = (int)view.ReadDouble(rOff + 0 * 8);
|
||||||
|
double size = view.ReadDouble(rOff + 1 * 8);
|
||||||
|
double lineWidth = view.ReadDouble(rOff + 2 * 8);
|
||||||
|
double aspect = view.ReadDouble(rOff + 3 * 8);
|
||||||
|
|
||||||
|
(byte[] buffer, int w, int h) result;
|
||||||
|
try { result = loadFigure(name, color, size, lineWidth, aspect); }
|
||||||
|
catch { result = (new byte[4], 1, 1); }
|
||||||
|
|
||||||
|
int pixelSize = result.w * result.h * 4;
|
||||||
|
long capacity = view.Capacity - _pixelOffset;
|
||||||
|
if (pixelSize > capacity)
|
||||||
|
{
|
||||||
|
result = (new byte[4], 1, 1);
|
||||||
|
pixelSize = 4;
|
||||||
|
}
|
||||||
|
|
||||||
|
view.Write(NativeProtocol.OffLoadResultWidth, result.w);
|
||||||
|
view.Write(NativeProtocol.OffLoadResultHeight, result.h);
|
||||||
|
view.WriteArray(_pixelOffset, result.buffer, 0, pixelSize);
|
||||||
|
view.Write(NativeProtocol.OffCallbackFound, 1);
|
||||||
|
}
|
||||||
|
|
||||||
|
private void ResolveLoadTextCallback(
|
||||||
|
MemoryMappedViewAccessor view,
|
||||||
|
Func<string, string, double, bool, bool, int, (byte[] buffer, int w, int h)> loadText)
|
||||||
|
{
|
||||||
|
int tagLen = Math.Clamp(view.ReadInt32(NativeProtocol.OffCallbackTagLen), 0, NativeProtocol.CallbackTagMax);
|
||||||
|
view.ReadArray(NativeProtocol.CallbackTagOffset, _callbackTag, 0, tagLen);
|
||||||
|
string payload = Encoding.UTF8.GetString(_callbackTag, 0, tagLen);
|
||||||
|
int separator = payload.IndexOf('\0');
|
||||||
|
string family = separator >= 0 ? payload[..separator] : string.Empty;
|
||||||
|
string text = separator >= 0 ? payload[(separator + 1)..] : payload;
|
||||||
|
|
||||||
|
long rOff = NativeProtocol.CallbackResultOffset;
|
||||||
|
double size = view.ReadDouble(rOff + 0 * 8);
|
||||||
|
bool bold = view.ReadDouble(rOff + 1 * 8) != 0;
|
||||||
|
bool italic = view.ReadDouble(rOff + 2 * 8) != 0;
|
||||||
|
int color = (int)view.ReadDouble(rOff + 3 * 8);
|
||||||
|
|
||||||
|
(byte[] buffer, int w, int h) result;
|
||||||
|
try { result = loadText(family, text, size, bold, italic, color); }
|
||||||
|
catch { result = (new byte[4], 1, 1); }
|
||||||
|
|
||||||
|
int pixelSize = result.w * result.h * 4;
|
||||||
|
long capacity = view.Capacity - _pixelOffset;
|
||||||
|
if (pixelSize > capacity)
|
||||||
|
{
|
||||||
|
result = (new byte[4], 1, 1);
|
||||||
|
pixelSize = 4;
|
||||||
|
}
|
||||||
|
|
||||||
|
view.Write(NativeProtocol.OffLoadResultWidth, result.w);
|
||||||
|
view.Write(NativeProtocol.OffLoadResultHeight, result.h);
|
||||||
|
view.WriteArray(_pixelOffset, result.buffer, 0, pixelSize);
|
||||||
|
view.Write(NativeProtocol.OffCallbackFound, 1);
|
||||||
|
}
|
||||||
|
|
||||||
|
private void ResolveLoadImageCallback(
|
||||||
|
MemoryMappedViewAccessor view,
|
||||||
|
Func<string, (byte[] buffer, int w, int h)> loadImage)
|
||||||
|
{
|
||||||
|
int tagLen = Math.Clamp(view.ReadInt32(NativeProtocol.OffCallbackTagLen), 0, NativeProtocol.CallbackTagMax);
|
||||||
|
view.ReadArray(NativeProtocol.CallbackTagOffset, _callbackTag, 0, tagLen);
|
||||||
|
string path = Encoding.UTF8.GetString(_callbackTag, 0, tagLen);
|
||||||
|
|
||||||
|
(byte[] buffer, int w, int h) result;
|
||||||
|
try { result = loadImage(path); }
|
||||||
|
catch { result = (new byte[4], 1, 1); }
|
||||||
|
|
||||||
|
int pixelSize = result.w * result.h * 4;
|
||||||
|
long capacity = view.Capacity - _pixelOffset;
|
||||||
|
if (pixelSize > capacity)
|
||||||
|
{
|
||||||
|
result = (new byte[4], 1, 1);
|
||||||
|
pixelSize = 4;
|
||||||
|
}
|
||||||
|
|
||||||
|
view.Write(NativeProtocol.OffLoadResultWidth, result.w);
|
||||||
|
view.Write(NativeProtocol.OffLoadResultHeight, result.h);
|
||||||
|
view.WriteArray(_pixelOffset, result.buffer, 0, pixelSize);
|
||||||
|
view.Write(NativeProtocol.OffCallbackFound, 1);
|
||||||
|
}
|
||||||
|
|
||||||
|
private void ResolveLoadMovieCallback(
|
||||||
|
MemoryMappedViewAccessor view,
|
||||||
|
Func<string, double, (byte[] buffer, int w, int h)> loadMovie)
|
||||||
|
{
|
||||||
|
int tagLen = Math.Clamp(view.ReadInt32(NativeProtocol.OffCallbackTagLen), 0, NativeProtocol.CallbackTagMax);
|
||||||
|
view.ReadArray(NativeProtocol.CallbackTagOffset, _callbackTag, 0, tagLen);
|
||||||
|
string path = Encoding.UTF8.GetString(_callbackTag, 0, tagLen);
|
||||||
|
double time = view.ReadDouble(NativeProtocol.CallbackResultOffset);
|
||||||
|
|
||||||
|
(byte[] buffer, int w, int h) result;
|
||||||
|
try { result = loadMovie(path, time); }
|
||||||
|
catch { result = (new byte[4], 1, 1); }
|
||||||
|
|
||||||
|
int pixelSize = result.w * result.h * 4;
|
||||||
|
long capacity = view.Capacity - _pixelOffset;
|
||||||
|
if (pixelSize > capacity)
|
||||||
|
{
|
||||||
|
result = (new byte[4], 1, 1);
|
||||||
|
pixelSize = 4;
|
||||||
|
}
|
||||||
|
|
||||||
|
view.Write(NativeProtocol.OffLoadResultWidth, result.w);
|
||||||
|
view.Write(NativeProtocol.OffLoadResultHeight, result.h);
|
||||||
|
view.WriteArray(_pixelOffset, result.buffer, 0, pixelSize);
|
||||||
|
view.Write(NativeProtocol.OffCallbackFound, 1);
|
||||||
|
}
|
||||||
|
|
||||||
|
private void ResolveEffectCallback(MemoryMappedViewAccessor view, Action<string, IReadOnlyList<KeyValuePair<string, object>>> addEffect)
|
||||||
|
{
|
||||||
|
int tagLen = Math.Clamp(view.ReadInt32(NativeProtocol.OffCallbackTagLen), 0, NativeProtocol.CallbackTagMax);
|
||||||
|
view.ReadArray(NativeProtocol.CallbackTagOffset, _callbackTag, 0, tagLen);
|
||||||
|
|
||||||
|
var segments = Encoding.UTF8.GetString(_callbackTag, 0, tagLen).Split('\0');
|
||||||
|
if (segments.Length == 0)
|
||||||
|
return;
|
||||||
|
|
||||||
|
string effectName = segments[0];
|
||||||
|
var arguments = new List<KeyValuePair<string, object>>();
|
||||||
|
for (int i = 1; i + 1 < segments.Length; i += 2)
|
||||||
|
{
|
||||||
|
string key = segments[i];
|
||||||
|
string raw = segments[i + 1];
|
||||||
|
object value;
|
||||||
|
if (raw.Length > 0 && raw[0] == 'n')
|
||||||
|
value = double.TryParse(raw.AsSpan(1), System.Globalization.NumberStyles.Float, System.Globalization.CultureInfo.InvariantCulture, out var d) ? d : 0d;
|
||||||
|
else if (raw.Length > 0 && raw[0] == 'b')
|
||||||
|
value = raw.Length > 1 && raw[1] == '1';
|
||||||
|
else if (raw.Length > 0 && raw[0] == 's')
|
||||||
|
value = raw.Substring(1);
|
||||||
|
else
|
||||||
|
value = raw;
|
||||||
|
arguments.Add(new KeyValuePair<string, object>(key, value));
|
||||||
|
}
|
||||||
|
|
||||||
|
try { addEffect(effectName, arguments); }
|
||||||
|
catch { }
|
||||||
|
view.Write(NativeProtocol.OffCallbackFound, 1);
|
||||||
|
}
|
||||||
|
|
||||||
private string ResolveTag(int tagLen)
|
private string ResolveTag(int tagLen)
|
||||||
{
|
{
|
||||||
if (tagLen == _lastCallbackTagLength &&
|
if (tagLen == _lastCallbackTagLength &&
|
||||||
@@ -157,20 +471,22 @@ namespace LuaScript.Engine
|
|||||||
return _lastCallbackTagText;
|
return _lastCallbackTagText;
|
||||||
}
|
}
|
||||||
|
|
||||||
private void EnsureWorker(int width, int height)
|
private void EnsureWorker(int width, int height, int stringCapacity)
|
||||||
{
|
{
|
||||||
if (_alive && _process is { HasExited: false } && _width == width && _height == height)
|
if (_alive && _process is { HasExited: false } && _width == width && _height == height && _stringParamsCapacity == stringCapacity)
|
||||||
return;
|
return;
|
||||||
|
|
||||||
KillWorker();
|
KillWorker();
|
||||||
StartWorker(width, height);
|
StartWorker(width, height, stringCapacity);
|
||||||
}
|
}
|
||||||
|
|
||||||
private void StartWorker(int width, int height)
|
private void StartWorker(int width, int height, int stringCapacity)
|
||||||
{
|
{
|
||||||
_width = width;
|
_width = width;
|
||||||
_height = height;
|
_height = height;
|
||||||
long size = NativeProtocol.BufferSize(width, height);
|
_stringParamsCapacity = stringCapacity;
|
||||||
|
_pixelOffset = NativeProtocol.PixelOffset(stringCapacity);
|
||||||
|
long size = NativeProtocol.BufferSize(width, height, stringCapacity);
|
||||||
|
|
||||||
string suffix = Guid.NewGuid().ToString("N");
|
string suffix = Guid.NewGuid().ToString("N");
|
||||||
string mapName = "LuaScriptMap_" + suffix;
|
string mapName = "LuaScriptMap_" + suffix;
|
||||||
@@ -197,6 +513,7 @@ namespace LuaScript.Engine
|
|||||||
psi.ArgumentList.Add(workName);
|
psi.ArgumentList.Add(workName);
|
||||||
psi.ArgumentList.Add(doneName);
|
psi.ArgumentList.Add(doneName);
|
||||||
psi.ArgumentList.Add(_shimScript);
|
psi.ArgumentList.Add(_shimScript);
|
||||||
|
psi.ArgumentList.Add(stringCapacity.ToString());
|
||||||
|
|
||||||
_process = Process.Start(psi);
|
_process = Process.Start(psi);
|
||||||
if (_process is not null)
|
if (_process is not null)
|
||||||
|
|||||||
@@ -38,6 +38,10 @@ namespace LuaScript.Engine
|
|||||||
f[NativeProtocol.Track1] = ctx.Track1;
|
f[NativeProtocol.Track1] = ctx.Track1;
|
||||||
f[NativeProtocol.Track2] = ctx.Track2;
|
f[NativeProtocol.Track2] = ctx.Track2;
|
||||||
f[NativeProtocol.Track3] = ctx.Track3;
|
f[NativeProtocol.Track3] = ctx.Track3;
|
||||||
|
f[NativeProtocol.Slider0] = ctx.Slider0;
|
||||||
|
f[NativeProtocol.Slider1] = ctx.Slider1;
|
||||||
|
f[NativeProtocol.Slider2] = ctx.Slider2;
|
||||||
|
f[NativeProtocol.Slider3] = ctx.Slider3;
|
||||||
f[NativeProtocol.Check0] = ctx.Check0 ? 1d : 0d;
|
f[NativeProtocol.Check0] = ctx.Check0 ? 1d : 0d;
|
||||||
f[NativeProtocol.Check1] = ctx.Check1 ? 1d : 0d;
|
f[NativeProtocol.Check1] = ctx.Check1 ? 1d : 0d;
|
||||||
f[NativeProtocol.Check2] = ctx.Check2 ? 1d : 0d;
|
f[NativeProtocol.Check2] = ctx.Check2 ? 1d : 0d;
|
||||||
@@ -78,42 +82,17 @@ namespace LuaScript.Engine
|
|||||||
ctx.Oz = f[NativeProtocol.Oz];
|
ctx.Oz = f[NativeProtocol.Oz];
|
||||||
ctx.Alpha = f[NativeProtocol.Alpha];
|
ctx.Alpha = f[NativeProtocol.Alpha];
|
||||||
|
|
||||||
double initialSx = ctx.Sx;
|
ctx.ApplyWriteBack(
|
||||||
double initialSy = ctx.Sy;
|
f[NativeProtocol.Sx],
|
||||||
double initialZoom = ctx.Zoom;
|
f[NativeProtocol.Sy],
|
||||||
double initialAspect = ctx.Aspect;
|
f[NativeProtocol.Zoom],
|
||||||
|
f[NativeProtocol.Aspect],
|
||||||
ctx.Sx = f[NativeProtocol.Sx];
|
f[NativeProtocol.Rx],
|
||||||
ctx.Sy = f[NativeProtocol.Sy];
|
f[NativeProtocol.Ry],
|
||||||
ctx.Zoom = f[NativeProtocol.Zoom];
|
f[NativeProtocol.Rz],
|
||||||
ctx.Aspect = f[NativeProtocol.Aspect];
|
f[NativeProtocol.Rxr],
|
||||||
|
f[NativeProtocol.Ryr],
|
||||||
bool sxsyChanged = Math.Abs(ctx.Sx - initialSx) > Epsilon || Math.Abs(ctx.Sy - initialSy) > Epsilon;
|
f[NativeProtocol.Rzr]);
|
||||||
bool zoomAspectChanged = Math.Abs(ctx.Zoom - initialZoom) > Epsilon || Math.Abs(ctx.Aspect - initialAspect) > Epsilon;
|
|
||||||
|
|
||||||
if (zoomAspectChanged && !sxsyChanged)
|
|
||||||
{
|
|
||||||
ctx.Sx = ctx.Zoom * (1.0 + ctx.Aspect);
|
|
||||||
ctx.Sy = ctx.Zoom * (1.0 - ctx.Aspect);
|
|
||||||
}
|
|
||||||
|
|
||||||
double initialRxr = ctx.RxRad;
|
|
||||||
double rxrNew = f[NativeProtocol.Rxr];
|
|
||||||
ctx.Rx = Math.Abs(rxrNew - initialRxr) > Epsilon
|
|
||||||
? rxrNew * (180d / Math.PI)
|
|
||||||
: f[NativeProtocol.Rx];
|
|
||||||
|
|
||||||
double initialRyr = ctx.RyRad;
|
|
||||||
double ryrNew = f[NativeProtocol.Ryr];
|
|
||||||
ctx.Ry = Math.Abs(ryrNew - initialRyr) > Epsilon
|
|
||||||
? ryrNew * (180d / Math.PI)
|
|
||||||
: f[NativeProtocol.Ry];
|
|
||||||
|
|
||||||
double initialRzr = ctx.RzRad;
|
|
||||||
double rzrNew = f[NativeProtocol.Rzr];
|
|
||||||
ctx.Rz = Math.Abs(rzrNew - initialRzr) > Epsilon
|
|
||||||
? rzrNew * (180d / Math.PI)
|
|
||||||
: f[NativeProtocol.Rz];
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -23,6 +23,10 @@ namespace LuaScript.Engine
|
|||||||
public const int OffCallbackFrame = 32;
|
public const int OffCallbackFrame = 32;
|
||||||
public const int OffCallbackTagLen = 36;
|
public const int OffCallbackTagLen = 36;
|
||||||
public const int OffCallbackFound = 40;
|
public const int OffCallbackFound = 40;
|
||||||
|
public const int OffCallbackKind = 44;
|
||||||
|
public const int OffLoadResultWidth = 48;
|
||||||
|
public const int OffLoadResultHeight = 52;
|
||||||
|
public const int OffStringParamsLen = 56;
|
||||||
|
|
||||||
public const int HeaderSize = 64;
|
public const int HeaderSize = 64;
|
||||||
|
|
||||||
@@ -36,10 +40,22 @@ namespace LuaScript.Engine
|
|||||||
public const int ErrorMax = 4 * 1024;
|
public const int ErrorMax = 4 * 1024;
|
||||||
|
|
||||||
public const int CallbackTagOffset = ErrorOffset + ErrorMax;
|
public const int CallbackTagOffset = ErrorOffset + ErrorMax;
|
||||||
public const int CallbackTagMax = 256;
|
public const int CallbackTagMax = 4096;
|
||||||
public const int CallbackResultOffset = CallbackTagOffset + CallbackTagMax;
|
public const int CallbackResultOffset = CallbackTagOffset + CallbackTagMax;
|
||||||
public const int CallbackResultCount = 8;
|
public const int CallbackResultCount = 8;
|
||||||
|
|
||||||
|
public const int StringParamsOffset = CallbackResultOffset + CallbackResultCount * 8;
|
||||||
|
public const int MinStringParamsCapacity = 64 * 1024;
|
||||||
|
|
||||||
|
public const int CbKindGetObject = 0;
|
||||||
|
public const int CbKindLoadFigure = 1;
|
||||||
|
public const int CbKindEffect = 2;
|
||||||
|
public const int CbKindDraw = 3;
|
||||||
|
public const int CbKindDrawPoly = 4;
|
||||||
|
public const int CbKindLoadText = 5;
|
||||||
|
public const int CbKindLoadImage = 6;
|
||||||
|
public const int CbKindLoadMovie = 7;
|
||||||
|
|
||||||
public const int CbExist = 0;
|
public const int CbExist = 0;
|
||||||
public const int CbX = 1;
|
public const int CbX = 1;
|
||||||
public const int CbY = 2;
|
public const int CbY = 2;
|
||||||
@@ -49,7 +65,7 @@ namespace LuaScript.Engine
|
|||||||
public const int CbAlpha = 6;
|
public const int CbAlpha = 6;
|
||||||
public const int CbLayer = 7;
|
public const int CbLayer = 7;
|
||||||
|
|
||||||
public const int PixelOffset = CallbackResultOffset + CallbackResultCount * 8;
|
public static int PixelOffset(int stringCapacity) => StringParamsOffset + stringCapacity;
|
||||||
|
|
||||||
public const int W = 0;
|
public const int W = 0;
|
||||||
public const int H = 1;
|
public const int H = 1;
|
||||||
@@ -109,11 +125,17 @@ namespace LuaScript.Engine
|
|||||||
public const int Check2 = 55;
|
public const int Check2 = 55;
|
||||||
public const int Check3 = 56;
|
public const int Check3 = 56;
|
||||||
public const int Color = 57;
|
public const int Color = 57;
|
||||||
|
public const int Slider0 = 58;
|
||||||
|
public const int Slider1 = 59;
|
||||||
|
public const int Slider2 = 60;
|
||||||
|
public const int Slider3 = 61;
|
||||||
|
|
||||||
public const int FirstWritableField = X;
|
public const int FirstWritableField = X;
|
||||||
public const int LastWritableField = Rzr;
|
public const int LastWritableField = Rzr;
|
||||||
|
|
||||||
public static long BufferSize(int width, int height) =>
|
public const int MaxPixelBufferSize = 3840 * 2160 * 4;
|
||||||
PixelOffset + (long)width * height * 4;
|
|
||||||
|
public static long BufferSize(int width, int height, int stringCapacity) =>
|
||||||
|
PixelOffset(stringCapacity) + Math.Max((long)width * height * 4, MaxPixelBufferSize);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -0,0 +1,107 @@
|
|||||||
|
using System;
|
||||||
|
|
||||||
|
namespace LuaScript.Engine
|
||||||
|
{
|
||||||
|
internal static class ScriptDirective
|
||||||
|
{
|
||||||
|
public static ScriptEngineKind Resolve(string? script) =>
|
||||||
|
TryGetDirective(script, out var kind) ? kind : ScriptEngineKind.MoonSharp;
|
||||||
|
|
||||||
|
public static ScriptEngineKind ResolveAuto(string? script)
|
||||||
|
{
|
||||||
|
if (TryGetDirective(script, out var kind))
|
||||||
|
return kind;
|
||||||
|
if (UsesDrawingApi(script))
|
||||||
|
return ScriptEngineKind.MoonSharp;
|
||||||
|
return UsesPixelApi(script) ? ScriptEngineKind.Native : ScriptEngineKind.MoonSharp;
|
||||||
|
}
|
||||||
|
|
||||||
|
public static bool TryResolveExplicit(string? script, out ScriptEngineKind kind) =>
|
||||||
|
TryGetDirective(script, out kind);
|
||||||
|
|
||||||
|
public static bool UsesPixelApi(string? script) =>
|
||||||
|
script is not null && (script.Contains("getpixel", StringComparison.Ordinal) || script.Contains("setpixel", StringComparison.Ordinal));
|
||||||
|
|
||||||
|
public static bool UsesDrawingApi(string? script) =>
|
||||||
|
script is not null &&
|
||||||
|
script.Contains("obj.setoption", StringComparison.Ordinal);
|
||||||
|
|
||||||
|
private static bool TryGetDirective(string? script, out ScriptEngineKind kind)
|
||||||
|
{
|
||||||
|
kind = ScriptEngineKind.MoonSharp;
|
||||||
|
if (string.IsNullOrEmpty(script))
|
||||||
|
return false;
|
||||||
|
|
||||||
|
int index = 0;
|
||||||
|
int length = script.Length;
|
||||||
|
while (index < length)
|
||||||
|
{
|
||||||
|
int lineStart = index;
|
||||||
|
while (index < length && script[index] != '\n')
|
||||||
|
index++;
|
||||||
|
int lineEnd = index;
|
||||||
|
if (lineEnd > lineStart && script[lineEnd - 1] == '\r')
|
||||||
|
lineEnd--;
|
||||||
|
|
||||||
|
if (TryParseDirectiveLine(script, lineStart, lineEnd, out kind))
|
||||||
|
return true;
|
||||||
|
|
||||||
|
index++;
|
||||||
|
}
|
||||||
|
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
|
private static bool TryParseDirectiveLine(string script, int start, int end, out ScriptEngineKind kind)
|
||||||
|
{
|
||||||
|
kind = ScriptEngineKind.MoonSharp;
|
||||||
|
|
||||||
|
int i = start;
|
||||||
|
while (i < end && (script[i] == ' ' || script[i] == '\t'))
|
||||||
|
i++;
|
||||||
|
|
||||||
|
if (i + 3 > end || script[i] != '-' || script[i + 1] != '-' || script[i + 2] != '!')
|
||||||
|
return false;
|
||||||
|
i += 3;
|
||||||
|
|
||||||
|
while (i < end && (script[i] == ' ' || script[i] == '\t'))
|
||||||
|
i++;
|
||||||
|
|
||||||
|
int tokenStart = i;
|
||||||
|
while (i < end && IsTokenChar(script[i]))
|
||||||
|
i++;
|
||||||
|
int tokenEnd = i;
|
||||||
|
|
||||||
|
while (i < end && (script[i] == ' ' || script[i] == '\t'))
|
||||||
|
i++;
|
||||||
|
if (i != end)
|
||||||
|
return false;
|
||||||
|
|
||||||
|
var token = script.AsSpan(tokenStart, tokenEnd - tokenStart);
|
||||||
|
if (token.Equals("native", StringComparison.OrdinalIgnoreCase))
|
||||||
|
{
|
||||||
|
kind = ScriptEngineKind.Native;
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
if (token.Equals("gpu", StringComparison.OrdinalIgnoreCase))
|
||||||
|
{
|
||||||
|
kind = ScriptEngineKind.Gpu;
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
if (token.Equals("cpu", StringComparison.OrdinalIgnoreCase))
|
||||||
|
{
|
||||||
|
kind = ScriptEngineKind.Cpu;
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
if (token.Equals("moonsharp", StringComparison.OrdinalIgnoreCase))
|
||||||
|
{
|
||||||
|
kind = ScriptEngineKind.MoonSharp;
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
|
private static bool IsTokenChar(char c) =>
|
||||||
|
(c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z');
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -9,108 +9,4 @@ namespace LuaScript.Engine
|
|||||||
Gpu,
|
Gpu,
|
||||||
Cpu,
|
Cpu,
|
||||||
}
|
}
|
||||||
|
|
||||||
internal static class ScriptDirective
|
|
||||||
{
|
|
||||||
public static ScriptEngineKind Resolve(string? script) =>
|
|
||||||
TryGetDirective(script, out var kind) ? kind : ScriptEngineKind.MoonSharp;
|
|
||||||
|
|
||||||
public static ScriptEngineKind ResolveAuto(string? script)
|
|
||||||
{
|
|
||||||
if (TryGetDirective(script, out var kind))
|
|
||||||
return kind;
|
|
||||||
if (UsesDrawingApi(script))
|
|
||||||
return ScriptEngineKind.MoonSharp;
|
|
||||||
return UsesPixelApi(script) ? ScriptEngineKind.Native : ScriptEngineKind.MoonSharp;
|
|
||||||
}
|
|
||||||
|
|
||||||
public static bool UsesPixelApi(string? script) =>
|
|
||||||
script is not null && (script.Contains("getpixel", StringComparison.Ordinal) || script.Contains("setpixel", StringComparison.Ordinal));
|
|
||||||
|
|
||||||
public static bool UsesDrawingApi(string? script) =>
|
|
||||||
script is not null && (
|
|
||||||
script.Contains("obj.load", StringComparison.Ordinal) ||
|
|
||||||
script.Contains("obj.draw", StringComparison.Ordinal) ||
|
|
||||||
script.Contains("obj.effect", StringComparison.Ordinal) ||
|
|
||||||
script.Contains("obj.setoption", StringComparison.Ordinal) ||
|
|
||||||
script.Contains("obj.copybuffer", StringComparison.Ordinal));
|
|
||||||
|
|
||||||
private static bool TryGetDirective(string? script, out ScriptEngineKind kind)
|
|
||||||
{
|
|
||||||
kind = ScriptEngineKind.MoonSharp;
|
|
||||||
if (string.IsNullOrEmpty(script))
|
|
||||||
return false;
|
|
||||||
|
|
||||||
int index = 0;
|
|
||||||
int length = script.Length;
|
|
||||||
while (index < length)
|
|
||||||
{
|
|
||||||
int lineStart = index;
|
|
||||||
while (index < length && script[index] != '\n')
|
|
||||||
index++;
|
|
||||||
int lineEnd = index;
|
|
||||||
if (lineEnd > lineStart && script[lineEnd - 1] == '\r')
|
|
||||||
lineEnd--;
|
|
||||||
|
|
||||||
if (TryParseDirectiveLine(script, lineStart, lineEnd, out kind))
|
|
||||||
return true;
|
|
||||||
|
|
||||||
index++;
|
|
||||||
}
|
|
||||||
|
|
||||||
return false;
|
|
||||||
}
|
|
||||||
|
|
||||||
private static bool TryParseDirectiveLine(string script, int start, int end, out ScriptEngineKind kind)
|
|
||||||
{
|
|
||||||
kind = ScriptEngineKind.MoonSharp;
|
|
||||||
|
|
||||||
int i = start;
|
|
||||||
while (i < end && (script[i] == ' ' || script[i] == '\t'))
|
|
||||||
i++;
|
|
||||||
|
|
||||||
if (i + 3 > end || script[i] != '-' || script[i + 1] != '-' || script[i + 2] != '!')
|
|
||||||
return false;
|
|
||||||
i += 3;
|
|
||||||
|
|
||||||
while (i < end && (script[i] == ' ' || script[i] == '\t'))
|
|
||||||
i++;
|
|
||||||
|
|
||||||
int tokenStart = i;
|
|
||||||
while (i < end && IsTokenChar(script[i]))
|
|
||||||
i++;
|
|
||||||
int tokenEnd = i;
|
|
||||||
|
|
||||||
while (i < end && (script[i] == ' ' || script[i] == '\t'))
|
|
||||||
i++;
|
|
||||||
if (i != end)
|
|
||||||
return false;
|
|
||||||
|
|
||||||
var token = script.AsSpan(tokenStart, tokenEnd - tokenStart);
|
|
||||||
if (token.Equals("native", StringComparison.OrdinalIgnoreCase))
|
|
||||||
{
|
|
||||||
kind = ScriptEngineKind.Native;
|
|
||||||
return true;
|
|
||||||
}
|
|
||||||
if (token.Equals("gpu", StringComparison.OrdinalIgnoreCase))
|
|
||||||
{
|
|
||||||
kind = ScriptEngineKind.Gpu;
|
|
||||||
return true;
|
|
||||||
}
|
|
||||||
if (token.Equals("cpu", StringComparison.OrdinalIgnoreCase))
|
|
||||||
{
|
|
||||||
kind = ScriptEngineKind.Cpu;
|
|
||||||
return true;
|
|
||||||
}
|
|
||||||
if (token.Equals("moonsharp", StringComparison.OrdinalIgnoreCase))
|
|
||||||
{
|
|
||||||
kind = ScriptEngineKind.MoonSharp;
|
|
||||||
return true;
|
|
||||||
}
|
|
||||||
return false;
|
|
||||||
}
|
|
||||||
|
|
||||||
private static bool IsTokenChar(char c) =>
|
|
||||||
(c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z');
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
@@ -0,0 +1,97 @@
|
|||||||
|
using System;
|
||||||
|
using System.IO;
|
||||||
|
using Vortice.Mathematics;
|
||||||
|
using Vortice.WIC;
|
||||||
|
|
||||||
|
namespace LuaScript
|
||||||
|
{
|
||||||
|
internal sealed class ImageDecoder : IDisposable
|
||||||
|
{
|
||||||
|
private const int MaxDimension = 8192;
|
||||||
|
|
||||||
|
private IWICImagingFactory? _factory;
|
||||||
|
|
||||||
|
public unsafe byte[] Decode(string path, out int width, out int height)
|
||||||
|
{
|
||||||
|
width = 1;
|
||||||
|
height = 1;
|
||||||
|
if (string.IsNullOrEmpty(path) || !IsSupportedImage(path))
|
||||||
|
return new byte[4];
|
||||||
|
|
||||||
|
try
|
||||||
|
{
|
||||||
|
_factory ??= new IWICImagingFactory();
|
||||||
|
using var stream = _factory.CreateStream(path, FileAccess.Read);
|
||||||
|
using var decoder = _factory.CreateDecoderFromStream(stream, DecodeOptions.CacheOnDemand);
|
||||||
|
using var frame = decoder.GetFrame(0);
|
||||||
|
using var converter = _factory.CreateFormatConverter();
|
||||||
|
converter.Initialize(
|
||||||
|
frame,
|
||||||
|
Vortice.WIC.PixelFormat.Format32bppPBGRA,
|
||||||
|
BitmapDitherType.None,
|
||||||
|
null,
|
||||||
|
0d,
|
||||||
|
BitmapPaletteType.Custom);
|
||||||
|
|
||||||
|
converter.GetSize(out int w, out int h);
|
||||||
|
if (w <= 0 || h <= 0 || w > MaxDimension || h > MaxDimension)
|
||||||
|
return new byte[4];
|
||||||
|
|
||||||
|
var buffer = new byte[w * h * 4];
|
||||||
|
fixed (byte* p = buffer)
|
||||||
|
converter.CopyPixels(new RectI(0, 0, w, h), w * 4, buffer.Length, (nint)p);
|
||||||
|
|
||||||
|
width = w;
|
||||||
|
height = h;
|
||||||
|
return buffer;
|
||||||
|
}
|
||||||
|
catch
|
||||||
|
{
|
||||||
|
width = 1;
|
||||||
|
height = 1;
|
||||||
|
return new byte[4];
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private static bool IsSupportedImage(string path)
|
||||||
|
{
|
||||||
|
try
|
||||||
|
{
|
||||||
|
if (!File.Exists(path))
|
||||||
|
return false;
|
||||||
|
Span<byte> head = stackalloc byte[12];
|
||||||
|
using var stream = File.OpenRead(path);
|
||||||
|
int read = stream.Read(head);
|
||||||
|
if (read < 4)
|
||||||
|
return false;
|
||||||
|
|
||||||
|
if (head[0] == 0x89 && head[1] == 0x50 && head[2] == 0x4E && head[3] == 0x47)
|
||||||
|
return true;
|
||||||
|
if (head[0] == 0xFF && head[1] == 0xD8 && head[2] == 0xFF)
|
||||||
|
return true;
|
||||||
|
if (head[0] == 0x47 && head[1] == 0x49 && head[2] == 0x46 && head[3] == 0x38)
|
||||||
|
return true;
|
||||||
|
if (head[0] == 0x42 && head[1] == 0x4D)
|
||||||
|
return true;
|
||||||
|
if ((head[0] == 0x49 && head[1] == 0x49 && head[2] == 0x2A && head[3] == 0x00) ||
|
||||||
|
(head[0] == 0x4D && head[1] == 0x4D && head[2] == 0x00 && head[3] == 0x2A))
|
||||||
|
return true;
|
||||||
|
if (read >= 12 &&
|
||||||
|
head[0] == 0x52 && head[1] == 0x49 && head[2] == 0x46 && head[3] == 0x46 &&
|
||||||
|
head[8] == 0x57 && head[9] == 0x45 && head[10] == 0x42 && head[11] == 0x50)
|
||||||
|
return true;
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
catch
|
||||||
|
{
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
public void Dispose()
|
||||||
|
{
|
||||||
|
_factory?.Dispose();
|
||||||
|
_factory = null;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -17,7 +17,7 @@ namespace LuaScript
|
|||||||
private static readonly string[] s_globals =
|
private static readonly string[] s_globals =
|
||||||
[
|
[
|
||||||
"time", "frame", "totalframe", "framerate",
|
"time", "frame", "totalframe", "framerate",
|
||||||
"timelineframe", "timelinetime", "layer",
|
"timelineframe", "timelinetime", "layer", "color",
|
||||||
"obj", "scene", "anim", "ymm4",
|
"obj", "scene", "anim", "ymm4",
|
||||||
"math", "string", "table", "bit32",
|
"math", "string", "table", "bit32",
|
||||||
"type", "tostring", "tonumber", "select", "error", "assert", "print",
|
"type", "tostring", "tonumber", "select", "error", "assert", "print",
|
||||||
@@ -39,6 +39,11 @@ namespace LuaScript
|
|||||||
"obj.rx", "obj.ry", "obj.rz",
|
"obj.rx", "obj.ry", "obj.rz",
|
||||||
"obj.rxr", "obj.ryr", "obj.rzr",
|
"obj.rxr", "obj.ryr", "obj.rzr",
|
||||||
"obj.track0", "obj.track1", "obj.track2", "obj.track3",
|
"obj.track0", "obj.track1", "obj.track2", "obj.track3",
|
||||||
|
"obj.slider0", "obj.slider1", "obj.slider2", "obj.slider3",
|
||||||
|
"obj.check0", "obj.check1", "obj.check2", "obj.check3",
|
||||||
|
"obj.text", "obj.font", "obj.dir",
|
||||||
|
"obj.file_video", "obj.file_audio", "obj.file_image", "obj.file_project",
|
||||||
|
"obj.file_mp4", "obj.file_exo", "obj.file_subtitle", "obj.file_shader",
|
||||||
"obj.time", "obj.totaltime", "obj.t", "obj.frame", "obj.totalframe",
|
"obj.time", "obj.totaltime", "obj.t", "obj.frame", "obj.totalframe",
|
||||||
"obj.framerate", "obj.layer", "obj.index", "obj.num",
|
"obj.framerate", "obj.layer", "obj.index", "obj.num",
|
||||||
"obj.getpixel", "obj.setpixel",
|
"obj.getpixel", "obj.setpixel",
|
||||||
|
|||||||
@@ -2,6 +2,7 @@ using System.Collections.Generic;
|
|||||||
using System.Text.RegularExpressions;
|
using System.Text.RegularExpressions;
|
||||||
using ICSharpCode.AvalonEdit.Document;
|
using ICSharpCode.AvalonEdit.Document;
|
||||||
using ICSharpCode.AvalonEdit.Folding;
|
using ICSharpCode.AvalonEdit.Folding;
|
||||||
|
using LuaScript.Diagnostics;
|
||||||
using YukkuriMovieMaker.Controls.AvalonEdit.FoldingStrategy;
|
using YukkuriMovieMaker.Controls.AvalonEdit.FoldingStrategy;
|
||||||
|
|
||||||
namespace LuaScript
|
namespace LuaScript
|
||||||
@@ -25,6 +26,7 @@ namespace LuaScript
|
|||||||
public void UpdateFoldings(FoldingManager manager, TextDocument document)
|
public void UpdateFoldings(FoldingManager manager, TextDocument document)
|
||||||
{
|
{
|
||||||
manager.UpdateFoldings(CreateNewFoldings(document, out int firstErrorOffset), firstErrorOffset);
|
manager.UpdateFoldings(CreateNewFoldings(document, out int firstErrorOffset), firstErrorOffset);
|
||||||
|
LuaScriptDiagnosticOverlay.Attach(manager);
|
||||||
}
|
}
|
||||||
|
|
||||||
private static IEnumerable<NewFolding> CreateNewFoldings(TextDocument document, out int firstErrorOffset)
|
private static IEnumerable<NewFolding> CreateNewFoldings(TextDocument document, out int firstErrorOffset)
|
||||||
|
|||||||
@@ -4,7 +4,7 @@
|
|||||||
<TargetFramework>net10.0-windows10.0.19041.0</TargetFramework>
|
<TargetFramework>net10.0-windows10.0.19041.0</TargetFramework>
|
||||||
<UseWPF>true</UseWPF>
|
<UseWPF>true</UseWPF>
|
||||||
<ImplicitUsings>enable</ImplicitUsings>
|
<ImplicitUsings>enable</ImplicitUsings>
|
||||||
<Version>1.6.0</Version>
|
<Version>1.10.0</Version>
|
||||||
<Platforms>AnyCPU;x64</Platforms>
|
<Platforms>AnyCPU;x64</Platforms>
|
||||||
<Nullable>enable</Nullable>
|
<Nullable>enable</Nullable>
|
||||||
<AllowUnsafeBlocks>true</AllowUnsafeBlocks>
|
<AllowUnsafeBlocks>true</AllowUnsafeBlocks>
|
||||||
@@ -67,6 +67,10 @@
|
|||||||
<HintPath>$(YMM4DirPath)Vortice.Mathematics.dll</HintPath>
|
<HintPath>$(YMM4DirPath)Vortice.Mathematics.dll</HintPath>
|
||||||
<Private>false</Private>
|
<Private>false</Private>
|
||||||
</Reference>
|
</Reference>
|
||||||
|
<Reference Include="Vortice.MediaFoundation">
|
||||||
|
<HintPath>$(YMM4DirPath)Vortice.MediaFoundation.dll</HintPath>
|
||||||
|
<Private>false</Private>
|
||||||
|
</Reference>
|
||||||
<Reference Include="YukkuriMovieMaker">
|
<Reference Include="YukkuriMovieMaker">
|
||||||
<HintPath>$(YMM4DirPath)YukkuriMovieMaker.dll</HintPath>
|
<HintPath>$(YMM4DirPath)YukkuriMovieMaker.dll</HintPath>
|
||||||
<Private>false</Private>
|
<Private>false</Private>
|
||||||
@@ -90,6 +94,10 @@
|
|||||||
<AdditionalFiles Include="**/*.csv" />
|
<AdditionalFiles Include="**/*.csv" />
|
||||||
</ItemGroup>
|
</ItemGroup>
|
||||||
|
|
||||||
|
<ItemGroup>
|
||||||
|
<EmbeddedResource Include="Compat\AviUtlCompatMap.xml" />
|
||||||
|
</ItemGroup>
|
||||||
|
|
||||||
<ItemGroup>
|
<ItemGroup>
|
||||||
<PackageReference Include="MoonSharp" Version="2.0.0" />
|
<PackageReference Include="MoonSharp" Version="2.0.0" />
|
||||||
</ItemGroup>
|
</ItemGroup>
|
||||||
|
|||||||
@@ -0,0 +1,6 @@
|
|||||||
|
using System;
|
||||||
|
|
||||||
|
namespace LuaScript
|
||||||
|
{
|
||||||
|
internal sealed class LuaScriptCompilationException(string message, Exception? inner = null) : LuaScriptException(message, inner);
|
||||||
|
}
|
||||||
+147
-5
@@ -1,4 +1,5 @@
|
|||||||
using System.Collections.Generic;
|
using System.Collections.Generic;
|
||||||
|
using System.ComponentModel;
|
||||||
using System.ComponentModel.DataAnnotations;
|
using System.ComponentModel.DataAnnotations;
|
||||||
using System.Windows.Media;
|
using System.Windows.Media;
|
||||||
using LuaScript.Compat;
|
using LuaScript.Compat;
|
||||||
@@ -10,6 +11,7 @@ using YukkuriMovieMaker.ItemEditor.CustomVisibilityAttributes;
|
|||||||
using YukkuriMovieMaker.Player.Video;
|
using YukkuriMovieMaker.Player.Video;
|
||||||
using YukkuriMovieMaker.Plugin;
|
using YukkuriMovieMaker.Plugin;
|
||||||
using YukkuriMovieMaker.Plugin.Effects;
|
using YukkuriMovieMaker.Plugin.Effects;
|
||||||
|
using YukkuriMovieMaker.Settings;
|
||||||
|
|
||||||
namespace LuaScript
|
namespace LuaScript
|
||||||
{
|
{
|
||||||
@@ -62,6 +64,34 @@ namespace LuaScript
|
|||||||
[ShowPropertyEditorWhen(nameof(IsTrack3Visible), true)]
|
[ShowPropertyEditorWhen(nameof(IsTrack3Visible), true)]
|
||||||
public Animation Track3 { get; } = new Animation(0, YMM4Constants.VerySmallValue, YMM4Constants.VeryLargeValue);
|
public Animation Track3 { get; } = new Animation(0, YMM4Constants.VerySmallValue, YMM4Constants.VeryLargeValue);
|
||||||
|
|
||||||
|
[Display(GroupName = nameof(Texts.ParametersGroup), Name = nameof(Texts.Slider0), Description = nameof(Texts.SliderDesc), ResourceType = typeof(Texts))]
|
||||||
|
[TextBoxSlider("F0", "", 1, 10)]
|
||||||
|
[DefaultValue(1)]
|
||||||
|
[ShowPropertyEditorWhen(nameof(IsSlider0Visible), true)]
|
||||||
|
public int Slider0 { get => _slider0; set => Set(ref _slider0, value); }
|
||||||
|
int _slider0 = 1;
|
||||||
|
|
||||||
|
[Display(GroupName = nameof(Texts.ParametersGroup), Name = nameof(Texts.Slider1), Description = nameof(Texts.SliderDesc), ResourceType = typeof(Texts))]
|
||||||
|
[TextBoxSlider("F0", "", 0, 100)]
|
||||||
|
[DefaultValue(0)]
|
||||||
|
[ShowPropertyEditorWhen(nameof(IsSlider1Visible), true)]
|
||||||
|
public int Slider1 { get => _slider1; set => Set(ref _slider1, value); }
|
||||||
|
int _slider1;
|
||||||
|
|
||||||
|
[Display(GroupName = nameof(Texts.ParametersGroup), Name = nameof(Texts.Slider2), Description = nameof(Texts.SliderDesc), ResourceType = typeof(Texts))]
|
||||||
|
[TextBoxSlider("F0", "", 0, 1000)]
|
||||||
|
[DefaultValue(0)]
|
||||||
|
[ShowPropertyEditorWhen(nameof(IsSlider2Visible), true)]
|
||||||
|
public int Slider2 { get => _slider2; set => Set(ref _slider2, value); }
|
||||||
|
int _slider2;
|
||||||
|
|
||||||
|
[Display(GroupName = nameof(Texts.ParametersGroup), Name = nameof(Texts.Slider3), Description = nameof(Texts.SliderDesc), ResourceType = typeof(Texts))]
|
||||||
|
[TextBoxSlider("F0", "", -1000, 1000)]
|
||||||
|
[DefaultValue(0)]
|
||||||
|
[ShowPropertyEditorWhen(nameof(IsSlider3Visible), true)]
|
||||||
|
public int Slider3 { get => _slider3; set => Set(ref _slider3, value); }
|
||||||
|
int _slider3;
|
||||||
|
|
||||||
[Display(GroupName = nameof(Texts.ParametersGroup), Name = nameof(Texts.Check0), Description = nameof(Texts.CheckDesc), ResourceType = typeof(Texts))]
|
[Display(GroupName = nameof(Texts.ParametersGroup), Name = nameof(Texts.Check0), Description = nameof(Texts.CheckDesc), ResourceType = typeof(Texts))]
|
||||||
[ToggleSlider]
|
[ToggleSlider]
|
||||||
[ShowPropertyEditorWhen(nameof(IsCheck0Visible), true)]
|
[ShowPropertyEditorWhen(nameof(IsCheck0Visible), true)]
|
||||||
@@ -92,6 +122,76 @@ namespace LuaScript
|
|||||||
public Color Color { get => _color; set => Set(ref _color, value); }
|
public Color Color { get => _color; set => Set(ref _color, value); }
|
||||||
Color _color = Colors.White;
|
Color _color = Colors.White;
|
||||||
|
|
||||||
|
[Display(GroupName = nameof(Texts.ParametersGroup), Name = nameof(Texts.Text), Description = nameof(Texts.TextDesc), ResourceType = typeof(Texts))]
|
||||||
|
[TextEditor(AcceptsReturn = true, PropertyEditorSize = PropertyEditorSize.FullWidth)]
|
||||||
|
[ShowPropertyEditorWhen(nameof(IsTextVisible), true)]
|
||||||
|
public string Text { get => _text; set => Set(ref _text, value); }
|
||||||
|
string _text = string.Empty;
|
||||||
|
|
||||||
|
[Display(GroupName = nameof(Texts.ParametersGroup), Name = nameof(Texts.Font), Description = nameof(Texts.FontDesc), ResourceType = typeof(Texts))]
|
||||||
|
[FontComboBox]
|
||||||
|
[ShowPropertyEditorWhen(nameof(IsFontVisible), true)]
|
||||||
|
public string Font { get => _font; set => Set(ref _font, value); }
|
||||||
|
string _font = "メイリオ";
|
||||||
|
|
||||||
|
[Display(GroupName = nameof(Texts.ParametersGroup), Name = nameof(Texts.Directory), Description = nameof(Texts.DirectoryDesc), ResourceType = typeof(Texts))]
|
||||||
|
[DirectorySelector(PropertyEditorSize = PropertyEditorSize.FullWidth)]
|
||||||
|
[ShowPropertyEditorWhen(nameof(IsDirectoryVisible), true)]
|
||||||
|
public string Directory { get => _directory; set => Set(ref _directory, value); }
|
||||||
|
string _directory = string.Empty;
|
||||||
|
|
||||||
|
[Display(GroupName = nameof(Texts.ParametersGroup), Name = nameof(Texts.FileVideo), Description = nameof(Texts.FileDesc), ResourceType = typeof(Texts))]
|
||||||
|
[FileSelector(FileGroupType.VideoItem)]
|
||||||
|
[ShowPropertyEditorWhen(nameof(IsFileVideoVisible), true)]
|
||||||
|
public string FileVideo { get => _fileVideo; set => Set(ref _fileVideo, value); }
|
||||||
|
string _fileVideo = string.Empty;
|
||||||
|
|
||||||
|
[Display(GroupName = nameof(Texts.ParametersGroup), Name = nameof(Texts.FileAudio), Description = nameof(Texts.FileDesc), ResourceType = typeof(Texts))]
|
||||||
|
[FileSelector(FileGroupType.AudioItem)]
|
||||||
|
[ShowPropertyEditorWhen(nameof(IsFileAudioVisible), true)]
|
||||||
|
public string FileAudio { get => _fileAudio; set => Set(ref _fileAudio, value); }
|
||||||
|
string _fileAudio = string.Empty;
|
||||||
|
|
||||||
|
[Display(GroupName = nameof(Texts.ParametersGroup), Name = nameof(Texts.FileImage), Description = nameof(Texts.FileDesc), ResourceType = typeof(Texts))]
|
||||||
|
[FileSelector(FileGroupType.ImageItem)]
|
||||||
|
[ShowPropertyEditorWhen(nameof(IsFileImageVisible), true)]
|
||||||
|
public string FileImage { get => _fileImage; set => Set(ref _fileImage, value); }
|
||||||
|
string _fileImage = string.Empty;
|
||||||
|
|
||||||
|
[Display(GroupName = nameof(Texts.ParametersGroup), Name = nameof(Texts.FileProject), Description = nameof(Texts.FileDesc), ResourceType = typeof(Texts))]
|
||||||
|
[FileSelector(FileGroupType.Project)]
|
||||||
|
[ShowPropertyEditorWhen(nameof(IsFileProjectVisible), true)]
|
||||||
|
public string FileProject { get => _fileProject; set => Set(ref _fileProject, value); }
|
||||||
|
string _fileProject = string.Empty;
|
||||||
|
|
||||||
|
[Display(GroupName = nameof(Texts.ParametersGroup), Name = nameof(Texts.FileMp4), Description = nameof(Texts.FileDesc), ResourceType = typeof(Texts))]
|
||||||
|
[FileSelector(FileGroupType.MP4)]
|
||||||
|
[ShowPropertyEditorWhen(nameof(IsFileMp4Visible), true)]
|
||||||
|
public string FileMp4 { get => _fileMp4; set => Set(ref _fileMp4, value); }
|
||||||
|
string _fileMp4 = string.Empty;
|
||||||
|
|
||||||
|
[Display(GroupName = nameof(Texts.ParametersGroup), Name = nameof(Texts.FileExo), Description = nameof(Texts.FileDesc), ResourceType = typeof(Texts))]
|
||||||
|
[FileSelector(FileGroupType.Exo)]
|
||||||
|
[ShowPropertyEditorWhen(nameof(IsFileExoVisible), true)]
|
||||||
|
public string FileExo { get => _fileExo; set => Set(ref _fileExo, value); }
|
||||||
|
string _fileExo = string.Empty;
|
||||||
|
|
||||||
|
[Display(GroupName = nameof(Texts.ParametersGroup), Name = nameof(Texts.FileSubtitle), Description = nameof(Texts.FileDesc), ResourceType = typeof(Texts))]
|
||||||
|
[FileSelector(FileGroupType.Subtitle)]
|
||||||
|
[ShowPropertyEditorWhen(nameof(IsFileSubtitleVisible), true)]
|
||||||
|
public string FileSubtitle { get => _fileSubtitle; set => Set(ref _fileSubtitle, value); }
|
||||||
|
string _fileSubtitle = string.Empty;
|
||||||
|
|
||||||
|
[Display(GroupName = nameof(Texts.ParametersGroup), Name = nameof(Texts.FileShader), Description = nameof(Texts.FileDesc), ResourceType = typeof(Texts))]
|
||||||
|
[FileSelector(FileGroupType.PixelShaderSource)]
|
||||||
|
[ShowPropertyEditorWhen(nameof(IsFileShaderVisible), true)]
|
||||||
|
public string FileShader { get => _fileShader; set => Set(ref _fileShader, value); }
|
||||||
|
string _fileShader = string.Empty;
|
||||||
|
|
||||||
|
[JsonIgnore] public bool IsSlider0Visible { get => _isSlider0Visible; private set => Set(ref _isSlider0Visible, value); }
|
||||||
|
[JsonIgnore] public bool IsSlider1Visible { get => _isSlider1Visible; private set => Set(ref _isSlider1Visible, value); }
|
||||||
|
[JsonIgnore] public bool IsSlider2Visible { get => _isSlider2Visible; private set => Set(ref _isSlider2Visible, value); }
|
||||||
|
[JsonIgnore] public bool IsSlider3Visible { get => _isSlider3Visible; private set => Set(ref _isSlider3Visible, value); }
|
||||||
[JsonIgnore] public bool IsTrack0Visible { get => _isTrack0Visible; private set => Set(ref _isTrack0Visible, value); }
|
[JsonIgnore] public bool IsTrack0Visible { get => _isTrack0Visible; private set => Set(ref _isTrack0Visible, value); }
|
||||||
[JsonIgnore] public bool IsTrack1Visible { get => _isTrack1Visible; private set => Set(ref _isTrack1Visible, value); }
|
[JsonIgnore] public bool IsTrack1Visible { get => _isTrack1Visible; private set => Set(ref _isTrack1Visible, value); }
|
||||||
[JsonIgnore] public bool IsTrack2Visible { get => _isTrack2Visible; private set => Set(ref _isTrack2Visible, value); }
|
[JsonIgnore] public bool IsTrack2Visible { get => _isTrack2Visible; private set => Set(ref _isTrack2Visible, value); }
|
||||||
@@ -101,7 +201,22 @@ namespace LuaScript
|
|||||||
[JsonIgnore] public bool IsCheck2Visible { get => _isCheck2Visible; private set => Set(ref _isCheck2Visible, value); }
|
[JsonIgnore] public bool IsCheck2Visible { get => _isCheck2Visible; private set => Set(ref _isCheck2Visible, value); }
|
||||||
[JsonIgnore] public bool IsCheck3Visible { get => _isCheck3Visible; private set => Set(ref _isCheck3Visible, value); }
|
[JsonIgnore] public bool IsCheck3Visible { get => _isCheck3Visible; private set => Set(ref _isCheck3Visible, value); }
|
||||||
[JsonIgnore] public bool IsColorVisible { get => _isColorVisible; private set => Set(ref _isColorVisible, value); }
|
[JsonIgnore] public bool IsColorVisible { get => _isColorVisible; private set => Set(ref _isColorVisible, value); }
|
||||||
|
[JsonIgnore] public bool IsTextVisible { get => _isTextVisible; private set => Set(ref _isTextVisible, value); }
|
||||||
|
[JsonIgnore] public bool IsFontVisible { get => _isFontVisible; private set => Set(ref _isFontVisible, value); }
|
||||||
|
[JsonIgnore] public bool IsDirectoryVisible { get => _isDirectoryVisible; private set => Set(ref _isDirectoryVisible, value); }
|
||||||
|
[JsonIgnore] public bool IsFileVideoVisible { get => _isFileVideoVisible; private set => Set(ref _isFileVideoVisible, value); }
|
||||||
|
[JsonIgnore] public bool IsFileAudioVisible { get => _isFileAudioVisible; private set => Set(ref _isFileAudioVisible, value); }
|
||||||
|
[JsonIgnore] public bool IsFileImageVisible { get => _isFileImageVisible; private set => Set(ref _isFileImageVisible, value); }
|
||||||
|
[JsonIgnore] public bool IsFileProjectVisible { get => _isFileProjectVisible; private set => Set(ref _isFileProjectVisible, value); }
|
||||||
|
[JsonIgnore] public bool IsFileMp4Visible { get => _isFileMp4Visible; private set => Set(ref _isFileMp4Visible, value); }
|
||||||
|
[JsonIgnore] public bool IsFileExoVisible { get => _isFileExoVisible; private set => Set(ref _isFileExoVisible, value); }
|
||||||
|
[JsonIgnore] public bool IsFileSubtitleVisible { get => _isFileSubtitleVisible; private set => Set(ref _isFileSubtitleVisible, value); }
|
||||||
|
[JsonIgnore] public bool IsFileShaderVisible { get => _isFileShaderVisible; private set => Set(ref _isFileShaderVisible, value); }
|
||||||
|
|
||||||
|
bool _isSlider0Visible;
|
||||||
|
bool _isSlider1Visible;
|
||||||
|
bool _isSlider2Visible;
|
||||||
|
bool _isSlider3Visible;
|
||||||
bool _isTrack0Visible = true;
|
bool _isTrack0Visible = true;
|
||||||
bool _isTrack1Visible = true;
|
bool _isTrack1Visible = true;
|
||||||
bool _isTrack2Visible = true;
|
bool _isTrack2Visible = true;
|
||||||
@@ -111,6 +226,17 @@ namespace LuaScript
|
|||||||
bool _isCheck2Visible;
|
bool _isCheck2Visible;
|
||||||
bool _isCheck3Visible;
|
bool _isCheck3Visible;
|
||||||
bool _isColorVisible;
|
bool _isColorVisible;
|
||||||
|
bool _isTextVisible;
|
||||||
|
bool _isFontVisible;
|
||||||
|
bool _isDirectoryVisible;
|
||||||
|
bool _isFileVideoVisible;
|
||||||
|
bool _isFileAudioVisible;
|
||||||
|
bool _isFileImageVisible;
|
||||||
|
bool _isFileProjectVisible;
|
||||||
|
bool _isFileMp4Visible;
|
||||||
|
bool _isFileExoVisible;
|
||||||
|
bool _isFileSubtitleVisible;
|
||||||
|
bool _isFileShaderVisible;
|
||||||
|
|
||||||
private void UpdateLayout()
|
private void UpdateLayout()
|
||||||
{
|
{
|
||||||
@@ -118,16 +244,32 @@ namespace LuaScript
|
|||||||
Layout = layout;
|
Layout = layout;
|
||||||
|
|
||||||
bool hasAny = layout.HasAny;
|
bool hasAny = layout.HasAny;
|
||||||
|
var usage = ScriptParameterUsage.Detect(_script);
|
||||||
|
|
||||||
|
IsSlider0Visible = usage.Slider(0);
|
||||||
|
IsSlider1Visible = usage.Slider(1);
|
||||||
|
IsSlider2Visible = usage.Slider(2);
|
||||||
|
IsSlider3Visible = usage.Slider(3);
|
||||||
IsTrack0Visible = !hasAny || layout.HasTrack(0);
|
IsTrack0Visible = !hasAny || layout.HasTrack(0);
|
||||||
IsTrack1Visible = !hasAny || layout.HasTrack(1);
|
IsTrack1Visible = !hasAny || layout.HasTrack(1);
|
||||||
IsTrack2Visible = !hasAny || layout.HasTrack(2);
|
IsTrack2Visible = !hasAny || layout.HasTrack(2);
|
||||||
IsTrack3Visible = !hasAny || layout.HasTrack(3);
|
IsTrack3Visible = !hasAny || layout.HasTrack(3);
|
||||||
IsCheck0Visible = layout.HasCheck(0);
|
IsCheck0Visible = layout.HasCheck(0) || (!hasAny && usage.Check0);
|
||||||
IsCheck1Visible = layout.HasCheck(1);
|
IsCheck1Visible = layout.HasCheck(1) || (!hasAny && usage.Check1);
|
||||||
IsCheck2Visible = layout.HasCheck(2);
|
IsCheck2Visible = layout.HasCheck(2) || (!hasAny && usage.Check2);
|
||||||
IsCheck3Visible = layout.HasCheck(3);
|
IsCheck3Visible = layout.HasCheck(3) || (!hasAny && usage.Check3);
|
||||||
IsColorVisible = layout.HasColor;
|
IsColorVisible = layout.HasColor || (!hasAny && usage.Color);
|
||||||
|
IsTextVisible = usage.Uses("text");
|
||||||
|
IsFontVisible = usage.Uses("font");
|
||||||
|
IsDirectoryVisible = usage.Uses("dir");
|
||||||
|
IsFileVideoVisible = usage.Uses("file_video");
|
||||||
|
IsFileAudioVisible = usage.Uses("file_audio");
|
||||||
|
IsFileImageVisible = usage.Uses("file_image");
|
||||||
|
IsFileProjectVisible = usage.Uses("file_project");
|
||||||
|
IsFileMp4Visible = usage.Uses("file_mp4");
|
||||||
|
IsFileExoVisible = usage.Uses("file_exo");
|
||||||
|
IsFileSubtitleVisible = usage.Uses("file_subtitle");
|
||||||
|
IsFileShaderVisible = usage.Uses("file_shader");
|
||||||
|
|
||||||
SeedDefaults(layout);
|
SeedDefaults(layout);
|
||||||
}
|
}
|
||||||
|
|||||||
+340
-145
@@ -2,7 +2,9 @@ using System.IO;
|
|||||||
using System.Numerics;
|
using System.Numerics;
|
||||||
using System.Runtime.InteropServices;
|
using System.Runtime.InteropServices;
|
||||||
using LuaScript.Compat;
|
using LuaScript.Compat;
|
||||||
|
using LuaScript.Diagnostics;
|
||||||
using LuaScript.Engine;
|
using LuaScript.Engine;
|
||||||
|
using LuaScript.Engine.Kernel;
|
||||||
using Vortice;
|
using Vortice;
|
||||||
using Vortice.DCommon;
|
using Vortice.DCommon;
|
||||||
using Vortice.Direct2D1;
|
using Vortice.Direct2D1;
|
||||||
@@ -28,6 +30,10 @@ namespace LuaScript
|
|||||||
double Track1,
|
double Track1,
|
||||||
double Track2,
|
double Track2,
|
||||||
double Track3,
|
double Track3,
|
||||||
|
double Slider0,
|
||||||
|
double Slider1,
|
||||||
|
double Slider2,
|
||||||
|
double Slider3,
|
||||||
bool Check0,
|
bool Check0,
|
||||||
bool Check1,
|
bool Check1,
|
||||||
bool Check2,
|
bool Check2,
|
||||||
@@ -35,6 +41,7 @@ namespace LuaScript
|
|||||||
bool HasColor,
|
bool HasColor,
|
||||||
int Color,
|
int Color,
|
||||||
string Script,
|
string Script,
|
||||||
|
int StringsVersion,
|
||||||
TimelineSourceUsage Usage,
|
TimelineSourceUsage Usage,
|
||||||
Guid SceneId,
|
Guid SceneId,
|
||||||
int TimelineFrame,
|
int TimelineFrame,
|
||||||
@@ -63,6 +70,16 @@ namespace LuaScript
|
|||||||
private LuaJitWorker? _nativeWorker;
|
private LuaJitWorker? _nativeWorker;
|
||||||
private double[]? _nativeFields;
|
private double[]? _nativeFields;
|
||||||
private bool _nativeWarned;
|
private bool _nativeWarned;
|
||||||
|
private bool _effectChainWarned;
|
||||||
|
private bool _gpuWarned;
|
||||||
|
|
||||||
|
private string _kernelSource = string.Empty;
|
||||||
|
private bool _kernelResolved;
|
||||||
|
private KernelProgram? _kernelProgram;
|
||||||
|
private CpuKernel? _cpuKernel;
|
||||||
|
private GpuKernel? _gpuKernel;
|
||||||
|
private bool _gpuKernelChecked;
|
||||||
|
private double[]? _kernelUniforms;
|
||||||
|
|
||||||
private EffectDescription? _frameDesc;
|
private EffectDescription? _frameDesc;
|
||||||
private SceneObjectResolver? _frameResolver;
|
private SceneObjectResolver? _frameResolver;
|
||||||
@@ -74,29 +91,30 @@ namespace LuaScript
|
|||||||
|
|
||||||
private GraphicsDevicesAndContext? _ownCtx;
|
private GraphicsDevicesAndContext? _ownCtx;
|
||||||
|
|
||||||
private ID2D1Bitmap1? _renderTarget;
|
private PixelBufferManager? _pixelManager;
|
||||||
private ID2D1Bitmap1? _stagingBitmap;
|
|
||||||
private ID2D1Bitmap1? _outputBitmap;
|
|
||||||
private AffineTransform2D? _transformEffect;
|
|
||||||
private byte[]? _pixelBuffer;
|
|
||||||
private int _bitmapWidth;
|
|
||||||
private int _bitmapHeight;
|
|
||||||
private RawRectF _cachedBounds;
|
|
||||||
|
|
||||||
private bool _isFirst = true;
|
private bool _isFirst = true;
|
||||||
private string _sourceScript = string.Empty;
|
private string _sourceScript = string.Empty;
|
||||||
private string _runnableScript = string.Empty;
|
private string _runnableScript = string.Empty;
|
||||||
|
private int[] _runnableLineMap = [];
|
||||||
private bool _runnableCached;
|
private bool _runnableCached;
|
||||||
private ID2D1Image? _cachedInput;
|
private ID2D1Image? _cachedInput;
|
||||||
private RenderKey _cachedKey;
|
private RenderKey _cachedKey;
|
||||||
private SceneObjectQuery[] _cachedQueries = [];
|
private SceneObjectQuery[] _cachedQueries = [];
|
||||||
private DrawDescription? _cachedOutputDesc;
|
private DrawDescription? _cachedOutputDesc;
|
||||||
private bool _cachedPixelsModified;
|
private ID2D1Image? _cachedEffectOutput;
|
||||||
|
|
||||||
|
private VideoEffectChain? _effectChain;
|
||||||
|
private DrawCompositor? _drawCompositor;
|
||||||
|
private TextRenderer? _nativeTextRenderer;
|
||||||
|
private ImageDecoder? _nativeImageDecoder;
|
||||||
|
private MovieDecoder? _nativeMovieDecoder;
|
||||||
|
|
||||||
protected override ID2D1Image? CreateEffect(IGraphicsDevicesAndContext devices)
|
protected override ID2D1Image? CreateEffect(IGraphicsDevicesAndContext devices)
|
||||||
{
|
{
|
||||||
_ownCtx = new GraphicsDevicesAndContext(devices);
|
_ownCtx = new GraphicsDevicesAndContext(devices);
|
||||||
disposer.Collect(_ownCtx);
|
disposer.Collect(_ownCtx);
|
||||||
|
_pixelManager = new PixelBufferManager(_ownCtx);
|
||||||
_context.ResolverProvider = GetFrameResolver;
|
_context.ResolverProvider = GetFrameResolver;
|
||||||
return null;
|
return null;
|
||||||
}
|
}
|
||||||
@@ -127,12 +145,39 @@ namespace LuaScript
|
|||||||
if (_runnableCached && string.Equals(source, _sourceScript, StringComparison.Ordinal))
|
if (_runnableCached && string.Equals(source, _sourceScript, StringComparison.Ordinal))
|
||||||
return _runnableScript;
|
return _runnableScript;
|
||||||
|
|
||||||
_runnableScript = AviUtlScript.Transform(source);
|
var (code, lineMap) = AviUtlScript.TransformWithMap(source);
|
||||||
|
_runnableScript = code;
|
||||||
|
_runnableLineMap = lineMap;
|
||||||
_sourceScript = source;
|
_sourceScript = source;
|
||||||
_runnableCached = true;
|
_runnableCached = true;
|
||||||
return _runnableScript;
|
return _runnableScript;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
private static LuaScriptDiagnosticKind ClassifyDiagnostic(LuaScriptException exception) => exception switch
|
||||||
|
{
|
||||||
|
LuaScriptCompilationException => LuaScriptDiagnosticKind.Compile,
|
||||||
|
LuaScriptTimeoutException => LuaScriptDiagnosticKind.Timeout,
|
||||||
|
_ => LuaScriptDiagnosticKind.Runtime,
|
||||||
|
};
|
||||||
|
|
||||||
|
private LuaScriptDiagnostic CreateDiagnostic(LuaScriptDiagnosticKind kind, string message)
|
||||||
|
{
|
||||||
|
var diagnostic = LuaScriptDiagnosticParser.Parse(kind, message);
|
||||||
|
return diagnostic.Line > 0
|
||||||
|
? diagnostic with { Line = MapRunnableLine(diagnostic.Line) }
|
||||||
|
: diagnostic;
|
||||||
|
}
|
||||||
|
|
||||||
|
private int MapRunnableLine(int runnableLine)
|
||||||
|
{
|
||||||
|
int index = runnableLine - 1;
|
||||||
|
if (index < 0 || index >= _runnableLineMap.Length)
|
||||||
|
return runnableLine;
|
||||||
|
|
||||||
|
int sourceLine = _runnableLineMap[index];
|
||||||
|
return sourceLine >= 0 ? sourceLine + 1 : 0;
|
||||||
|
}
|
||||||
|
|
||||||
protected override void setInput(ID2D1Image? input)
|
protected override void setInput(ID2D1Image? input)
|
||||||
{
|
{
|
||||||
if (!ReferenceEquals(_cachedInput, input))
|
if (!ReferenceEquals(_cachedInput, input))
|
||||||
@@ -163,7 +208,8 @@ namespace LuaScript
|
|||||||
var t3 = ClampTrack(item.Track3.GetValue(frame, length, fps), layout, 3);
|
var t3 = ClampTrack(item.Track3.GetValue(frame, length, fps), layout, 3);
|
||||||
|
|
||||||
bool c0 = item.Check0, c1 = item.Check1, c2 = item.Check2, c3 = item.Check3;
|
bool c0 = item.Check0, c1 = item.Check1, c2 = item.Check2, c3 = item.Check3;
|
||||||
bool hasColor = layout.HasColor;
|
double s0 = item.Slider0, s1 = item.Slider1, s2 = item.Slider2, s3 = item.Slider3;
|
||||||
|
bool hasColor = item.IsColorVisible;
|
||||||
int colorRgb = hasColor ? (item.Color.R << 16) | (item.Color.G << 8) | item.Color.B : 0;
|
int colorRgb = hasColor ? (item.Color.R << 16) | (item.Color.G << 8) | item.Color.B : 0;
|
||||||
|
|
||||||
var inDesc = desc.DrawDescription;
|
var inDesc = desc.DrawDescription;
|
||||||
@@ -171,8 +217,10 @@ namespace LuaScript
|
|||||||
var key = new RenderKey(
|
var key = new RenderKey(
|
||||||
frame, time, length, fps,
|
frame, time, length, fps,
|
||||||
t0, t1, t2, t3,
|
t0, t1, t2, t3,
|
||||||
|
s0, s1, s2, s3,
|
||||||
c0, c1, c2, c3, hasColor, colorRgb,
|
c0, c1, c2, c3, hasColor, colorRgb,
|
||||||
script, desc.Usage, desc.SceneId,
|
script, RefreshStringParameters(),
|
||||||
|
desc.Usage, desc.SceneId,
|
||||||
desc.TimelinePosition.Frame,
|
desc.TimelinePosition.Frame,
|
||||||
desc.TimelinePosition.Time.TotalSeconds,
|
desc.TimelinePosition.Time.TotalSeconds,
|
||||||
desc.ScreenSize.Width, desc.ScreenSize.Height,
|
desc.ScreenSize.Width, desc.ScreenSize.Height,
|
||||||
@@ -189,7 +237,7 @@ namespace LuaScript
|
|||||||
if (!_isFirst && key == _cachedKey &&
|
if (!_isFirst && key == _cachedKey &&
|
||||||
(_cachedQueries.Length == 0 || QueriesMatch(_cachedQueries, GetFrameResolver())))
|
(_cachedQueries.Length == 0 || QueriesMatch(_cachedQueries, GetFrameResolver())))
|
||||||
{
|
{
|
||||||
effectOutput = _cachedPixelsModified ? _transformEffect?.Output : null;
|
effectOutput = _cachedEffectOutput;
|
||||||
return _cachedOutputDesc ?? inDesc;
|
return _cachedOutputDesc ?? inDesc;
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -202,44 +250,75 @@ namespace LuaScript
|
|||||||
ctx.SetPixelLoader(() => LoadInputPixels(bounds, imgW, imgH));
|
ctx.SetPixelLoader(() => LoadInputPixels(bounds, imgW, imgH));
|
||||||
|
|
||||||
DrawDescription outDesc = inDesc;
|
DrawDescription outDesc = inDesc;
|
||||||
bool pixelsModified = false;
|
IReadOnlyList<LuaScriptDiagnostic> diagnostics = [];
|
||||||
|
|
||||||
try
|
try
|
||||||
{
|
{
|
||||||
string runnable = GetRunnableScript(script);
|
string runnable = GetRunnableScript(script);
|
||||||
bool wantNative = ScriptDirective.ResolveAuto(runnable) == ScriptEngineKind.Native;
|
EnsureKernel(runnable);
|
||||||
bool nativeReady = wantNative && LuaJitWorker.IsAvailable(NativeDirectory);
|
|
||||||
if (wantNative && !nativeReady)
|
|
||||||
WarnNativeUnavailableOnce();
|
|
||||||
|
|
||||||
if (nativeReady)
|
if (ExecuteKernelLane(runnable, ctx, bounds, imgW, imgH))
|
||||||
{
|
{
|
||||||
pixelsModified = ExecuteNative(runnable, ctx, bounds, imgW, imgH);
|
outDesc = inDesc;
|
||||||
}
|
}
|
||||||
else
|
else
|
||||||
{
|
{
|
||||||
_engine.Execute(runnable, ctx);
|
bool wantNative = ScriptDirective.ResolveAuto(runnable) == ScriptEngineKind.Native;
|
||||||
|
bool nativeReady = wantNative && LuaJitWorker.IsAvailable(NativeDirectory);
|
||||||
|
if (wantNative && !nativeReady)
|
||||||
|
WarnNativeUnavailableOnce();
|
||||||
|
|
||||||
if (ctx.IsPixelsDirty)
|
if (nativeReady)
|
||||||
{
|
{
|
||||||
int bufW = ctx.ImageWidth;
|
ExecuteNative(runnable, ctx, bounds, imgW, imgH);
|
||||||
int bufH = ctx.ImageHeight;
|
|
||||||
EnsureBitmaps(bufW, bufH);
|
|
||||||
WritePixelsToOutput(ctx.GetPixelBuffer()!, bufW);
|
|
||||||
if (ctx.BufferReplaced)
|
|
||||||
UpdateTransformEffect(-bufW / 2f, -bufH / 2f);
|
|
||||||
else
|
|
||||||
UpdateTransformEffect(bounds.Left, bounds.Top);
|
|
||||||
effectOutput = _transformEffect!.Output;
|
|
||||||
pixelsModified = true;
|
|
||||||
}
|
}
|
||||||
else
|
else
|
||||||
{
|
{
|
||||||
effectOutput = null;
|
_engine.Execute(runnable, ctx);
|
||||||
|
|
||||||
|
if (ctx.IsPixelsDirty)
|
||||||
|
{
|
||||||
|
int bufW = ctx.ImageWidth;
|
||||||
|
int bufH = ctx.ImageHeight;
|
||||||
|
_pixelManager!.WritePixelsToOutput(ctx.GetPixelBuffer()!, bufW, bufH);
|
||||||
|
if (ctx.BufferReplaced)
|
||||||
|
effectOutput = _pixelManager.GetTransformOutput(-bufW / 2f, -bufH / 2f);
|
||||||
|
else
|
||||||
|
effectOutput = _pixelManager.GetTransformOutput(bounds.Left, bounds.Top);
|
||||||
|
}
|
||||||
|
else
|
||||||
|
{
|
||||||
|
effectOutput = null;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
if (ctx.DrawCommands.Count > 0)
|
||||||
|
{
|
||||||
|
ctx.EnsurePixelBuffer();
|
||||||
|
var drawBuffer = ctx.GetPixelBuffer();
|
||||||
|
if (drawBuffer is not null)
|
||||||
|
{
|
||||||
|
_drawCompositor ??= new DrawCompositor(_ownCtx);
|
||||||
|
effectOutput = _drawCompositor.Compose(drawBuffer, ctx.ImageWidth, ctx.ImageHeight, ctx.DrawCommands);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
outDesc = BuildOutputDesc(inDesc, ctx);
|
||||||
|
|
||||||
|
if (ctx.EffectRequests.Count > 0)
|
||||||
|
{
|
||||||
|
var source = effectOutput ?? input;
|
||||||
|
try
|
||||||
|
{
|
||||||
|
effectOutput = ApplyEffectChain(source, ctx.EffectRequests, desc, ref outDesc);
|
||||||
|
}
|
||||||
|
catch (Exception ex)
|
||||||
|
{
|
||||||
|
effectOutput = source;
|
||||||
|
WarnEffectChainFailureOnce(ex);
|
||||||
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
outDesc = BuildOutputDesc(inDesc, ctx);
|
|
||||||
}
|
}
|
||||||
catch (LuaScriptTimeoutException ex)
|
catch (LuaScriptTimeoutException ex)
|
||||||
{
|
{
|
||||||
@@ -247,6 +326,7 @@ namespace LuaScript
|
|||||||
_context = new AviUtlScriptContext { ResolverProvider = GetFrameResolver };
|
_context = new AviUtlScriptContext { ResolverProvider = GetFrameResolver };
|
||||||
_isFirst = true;
|
_isFirst = true;
|
||||||
Log.Default.Write(ex.Message, ex);
|
Log.Default.Write(ex.Message, ex);
|
||||||
|
LuaScriptDiagnostics.Instance.Report(script, [CreateDiagnostic(LuaScriptDiagnosticKind.Timeout, ex.Message)]);
|
||||||
return inDesc;
|
return inDesc;
|
||||||
}
|
}
|
||||||
catch (LuaScriptException ex)
|
catch (LuaScriptException ex)
|
||||||
@@ -254,6 +334,7 @@ namespace LuaScript
|
|||||||
effectOutput = null;
|
effectOutput = null;
|
||||||
outDesc = inDesc;
|
outDesc = inDesc;
|
||||||
Log.Default.Write(ex.Message, ex);
|
Log.Default.Write(ex.Message, ex);
|
||||||
|
diagnostics = [CreateDiagnostic(ClassifyDiagnostic(ex), ex.Message)];
|
||||||
}
|
}
|
||||||
finally
|
finally
|
||||||
{
|
{
|
||||||
@@ -261,15 +342,24 @@ namespace LuaScript
|
|||||||
_pixelLoaderSemaphore.Release();
|
_pixelLoaderSemaphore.Release();
|
||||||
}
|
}
|
||||||
|
|
||||||
|
LuaScriptDiagnostics.Instance.Report(script, diagnostics);
|
||||||
|
|
||||||
_isFirst = false;
|
_isFirst = false;
|
||||||
_cachedKey = key;
|
_cachedKey = key;
|
||||||
_cachedQueries = ctx.ObjectQueries.Count == 0 ? [] : [.. ctx.ObjectQueries];
|
_cachedQueries = ctx.ObjectQueries.Count == 0 ? [] : [.. ctx.ObjectQueries];
|
||||||
_cachedOutputDesc = outDesc;
|
_cachedOutputDesc = outDesc;
|
||||||
_cachedPixelsModified = pixelsModified;
|
_cachedEffectOutput = effectOutput;
|
||||||
|
|
||||||
return outDesc;
|
return outDesc;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
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);
|
||||||
|
}
|
||||||
|
|
||||||
private static SceneObjectResolver BuildSceneObjectResolver(EffectDescription desc)
|
private static SceneObjectResolver BuildSceneObjectResolver(EffectDescription desc)
|
||||||
{
|
{
|
||||||
var scenes = desc.Scenes;
|
var scenes = desc.Scenes;
|
||||||
@@ -317,6 +407,52 @@ namespace LuaScript
|
|||||||
return true;
|
return true;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
private static readonly string[] s_stringParameterNames =
|
||||||
|
[
|
||||||
|
"text", "font", "dir",
|
||||||
|
"file_video", "file_audio", "file_image", "file_project",
|
||||||
|
"file_mp4", "file_exo", "file_subtitle", "file_shader",
|
||||||
|
];
|
||||||
|
|
||||||
|
private readonly string?[] _stringParameterValues = new string?[s_stringParameterNames.Length];
|
||||||
|
private int _stringParametersVersion;
|
||||||
|
|
||||||
|
private int RefreshStringParameters()
|
||||||
|
{
|
||||||
|
var values = _stringParameterValues;
|
||||||
|
bool changed = false;
|
||||||
|
changed |= UpdateStringSlot(values, 0, item.Text);
|
||||||
|
changed |= UpdateStringSlot(values, 1, item.Font);
|
||||||
|
changed |= UpdateStringSlot(values, 2, item.Directory);
|
||||||
|
changed |= UpdateStringSlot(values, 3, item.FileVideo);
|
||||||
|
changed |= UpdateStringSlot(values, 4, item.FileAudio);
|
||||||
|
changed |= UpdateStringSlot(values, 5, item.FileImage);
|
||||||
|
changed |= UpdateStringSlot(values, 6, item.FileProject);
|
||||||
|
changed |= UpdateStringSlot(values, 7, item.FileMp4);
|
||||||
|
changed |= UpdateStringSlot(values, 8, item.FileExo);
|
||||||
|
changed |= UpdateStringSlot(values, 9, item.FileSubtitle);
|
||||||
|
changed |= UpdateStringSlot(values, 10, item.FileShader);
|
||||||
|
if (changed)
|
||||||
|
_stringParametersVersion++;
|
||||||
|
return _stringParametersVersion;
|
||||||
|
}
|
||||||
|
|
||||||
|
private static bool UpdateStringSlot(string?[] values, int index, string value)
|
||||||
|
{
|
||||||
|
if (ReferenceEquals(values[index], value))
|
||||||
|
return false;
|
||||||
|
values[index] = value;
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
|
||||||
|
private void PopulateStringParameters(AviUtlScriptContext ctx)
|
||||||
|
{
|
||||||
|
var names = s_stringParameterNames;
|
||||||
|
var values = _stringParameterValues;
|
||||||
|
for (int i = 0; i < names.Length; i++)
|
||||||
|
ctx.SetStringParameter(names[i], values[i]);
|
||||||
|
}
|
||||||
|
|
||||||
private void PopulateContext(AviUtlScriptContext ctx, in RenderKey key, int imgW, int imgH)
|
private void PopulateContext(AviUtlScriptContext ctx, in RenderKey key, int imgW, int imgH)
|
||||||
{
|
{
|
||||||
var zoom = key.InputDesc.Zoom;
|
var zoom = key.InputDesc.Zoom;
|
||||||
@@ -326,6 +462,8 @@ namespace LuaScript
|
|||||||
: 0d;
|
: 0d;
|
||||||
|
|
||||||
ctx.ClearQueries();
|
ctx.ClearQueries();
|
||||||
|
ctx.ClearEffects();
|
||||||
|
ctx.ClearDraws();
|
||||||
|
|
||||||
ctx.ImageWidth = imgW;
|
ctx.ImageWidth = imgW;
|
||||||
ctx.ImageHeight = imgH;
|
ctx.ImageHeight = imgH;
|
||||||
@@ -347,6 +485,10 @@ namespace LuaScript
|
|||||||
ctx.Track1 = key.Track1;
|
ctx.Track1 = key.Track1;
|
||||||
ctx.Track2 = key.Track2;
|
ctx.Track2 = key.Track2;
|
||||||
ctx.Track3 = key.Track3;
|
ctx.Track3 = key.Track3;
|
||||||
|
ctx.Slider0 = key.Slider0;
|
||||||
|
ctx.Slider1 = key.Slider1;
|
||||||
|
ctx.Slider2 = key.Slider2;
|
||||||
|
ctx.Slider3 = key.Slider3;
|
||||||
ctx.Check0 = key.Check0;
|
ctx.Check0 = key.Check0;
|
||||||
ctx.Check1 = key.Check1;
|
ctx.Check1 = key.Check1;
|
||||||
ctx.Check2 = key.Check2;
|
ctx.Check2 = key.Check2;
|
||||||
@@ -374,6 +516,7 @@ namespace LuaScript
|
|||||||
ctx.IsPaused = key.Usage == TimelineSourceUsage.Paused;
|
ctx.IsPaused = key.Usage == TimelineSourceUsage.Paused;
|
||||||
ctx.SceneId = ResolveSceneId(key.SceneId);
|
ctx.SceneId = ResolveSceneId(key.SceneId);
|
||||||
ctx.TimeRatio = key.Length > 0 ? key.Frame / (double)key.Length : 0d;
|
ctx.TimeRatio = key.Length > 0 ? key.Frame / (double)key.Length : 0d;
|
||||||
|
PopulateStringParameters(ctx);
|
||||||
}
|
}
|
||||||
|
|
||||||
private static double ClampTrack(double value, AviUtlParameterLayout layout, int index)
|
private static double ClampTrack(double value, AviUtlParameterLayout layout, int index)
|
||||||
@@ -393,6 +536,81 @@ namespace LuaScript
|
|||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
|
private void EnsureKernel(string runnable)
|
||||||
|
{
|
||||||
|
if (_kernelResolved && string.Equals(runnable, _kernelSource, StringComparison.Ordinal))
|
||||||
|
return;
|
||||||
|
|
||||||
|
_kernelSource = runnable;
|
||||||
|
_kernelResolved = true;
|
||||||
|
_kernelProgram = KernelExtractor.TryExtract(runnable);
|
||||||
|
_cpuKernel = _kernelProgram is null ? null : CpuKernelCompiler.Compile(_kernelProgram);
|
||||||
|
_gpuKernel?.Dispose();
|
||||||
|
_gpuKernel = null;
|
||||||
|
_gpuKernelChecked = false;
|
||||||
|
}
|
||||||
|
|
||||||
|
private bool ExecuteKernelLane(string runnable, AviUtlScriptContext ctx, RawRectF bounds, int imgW, int imgH)
|
||||||
|
{
|
||||||
|
if (_kernelProgram is null || _cpuKernel is null)
|
||||||
|
return false;
|
||||||
|
|
||||||
|
bool explicitDirective = ScriptDirective.TryResolveExplicit(runnable, out var kind);
|
||||||
|
if (explicitDirective && kind is not (ScriptEngineKind.Gpu or ScriptEngineKind.Cpu))
|
||||||
|
return false;
|
||||||
|
|
||||||
|
_kernelUniforms ??= KernelUniformBinding.Create();
|
||||||
|
KernelUniformBinding.Fill(ctx, _kernelUniforms);
|
||||||
|
|
||||||
|
if (explicitDirective && kind == ScriptEngineKind.Gpu)
|
||||||
|
{
|
||||||
|
var gpu = GetGpuKernel();
|
||||||
|
if (gpu is not null)
|
||||||
|
{
|
||||||
|
effectOutput = gpu.Apply(input!, _kernelUniforms);
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
WarnGpuUnavailableOnce();
|
||||||
|
}
|
||||||
|
|
||||||
|
byte[] buffer = LoadInputPixels(bounds, imgW, imgH);
|
||||||
|
_cpuKernel.Execute(buffer, imgW, imgH, _kernelUniforms);
|
||||||
|
_pixelManager!.WritePixelsToOutput(buffer, imgW, imgH);
|
||||||
|
effectOutput = _pixelManager.GetTransformOutput(bounds.Left, bounds.Top);
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
|
||||||
|
private GpuKernel? GetGpuKernel()
|
||||||
|
{
|
||||||
|
if (_gpuKernelChecked)
|
||||||
|
return _gpuKernel;
|
||||||
|
|
||||||
|
_gpuKernelChecked = true;
|
||||||
|
if (_kernelProgram is null)
|
||||||
|
return null;
|
||||||
|
|
||||||
|
try
|
||||||
|
{
|
||||||
|
var kernel = new GpuKernel(_ownCtx!, _kernelProgram);
|
||||||
|
if (kernel.IsReady)
|
||||||
|
_gpuKernel = kernel;
|
||||||
|
else
|
||||||
|
kernel.Dispose();
|
||||||
|
}
|
||||||
|
catch (Exception ex)
|
||||||
|
{
|
||||||
|
Log.Default.Write("LuaScript: GPU kernel initialization failed; falling back to CPU.", ex);
|
||||||
|
}
|
||||||
|
return _gpuKernel;
|
||||||
|
}
|
||||||
|
|
||||||
|
private void WarnGpuUnavailableOnce()
|
||||||
|
{
|
||||||
|
if (_gpuWarned) return;
|
||||||
|
_gpuWarned = true;
|
||||||
|
Log.Default.Write("LuaScript: GPU kernel unavailable; using the CPU kernel lane instead.");
|
||||||
|
}
|
||||||
|
|
||||||
private void WarnNativeUnavailableOnce()
|
private void WarnNativeUnavailableOnce()
|
||||||
{
|
{
|
||||||
if (_nativeWarned) return;
|
if (_nativeWarned) return;
|
||||||
@@ -400,6 +618,13 @@ namespace LuaScript
|
|||||||
Log.Default.Write($"LuaScript: native runtime not found at '{NativeDirectory}'. Falling back to MoonSharp (slow). Deploy the 'native' folder next to the plugin.");
|
Log.Default.Write($"LuaScript: native runtime not found at '{NativeDirectory}'. Falling back to MoonSharp (slow). Deploy the 'native' folder next to the plugin.");
|
||||||
}
|
}
|
||||||
|
|
||||||
|
private void WarnEffectChainFailureOnce(Exception ex)
|
||||||
|
{
|
||||||
|
if (_effectChainWarned) return;
|
||||||
|
_effectChainWarned = true;
|
||||||
|
Log.Default.Write("LuaScript: obj.effect chain failed and was skipped for this frame. The source image is passed through unchanged.", ex);
|
||||||
|
}
|
||||||
|
|
||||||
private bool ExecuteNative(string script, AviUtlScriptContext ctx, RawRectF bounds, int imgW, int imgH)
|
private bool ExecuteNative(string script, AviUtlScriptContext ctx, RawRectF bounds, int imgW, int imgH)
|
||||||
{
|
{
|
||||||
_nativeWorker ??= new LuaJitWorker(NativeDirectory);
|
_nativeWorker ??= new LuaJitWorker(NativeDirectory);
|
||||||
@@ -409,9 +634,16 @@ namespace LuaScript
|
|||||||
byte[] buffer = LoadInputPixels(bounds, imgW, imgH);
|
byte[] buffer = LoadInputPixels(bounds, imgW, imgH);
|
||||||
|
|
||||||
bool ok = _nativeWorker.Execute(
|
bool ok = _nativeWorker.Execute(
|
||||||
script, _nativeFields, buffer, imgW, imgH, NativeTimeoutMilliseconds,
|
script, _nativeFields, ctx.StringParameters, buffer, imgW, imgH, NativeTimeoutMilliseconds,
|
||||||
(tag, frame) => ctx.ResolveObject(tag, frame, out var info) ? info : null,
|
(tag, frame) => ctx.ResolveObject(tag, frame, out var info) ? info : null,
|
||||||
out bool dirty, out string? error);
|
NativeLoadFigure,
|
||||||
|
NativeLoadText,
|
||||||
|
NativeLoadImage,
|
||||||
|
NativeLoadMovie,
|
||||||
|
(name, args) => ctx.AddEffect(new AviUtlEffectRequest(name, args)),
|
||||||
|
ctx.AddDraw,
|
||||||
|
out bool dirty, out bool bufferReplaced, out byte[]? newPixels,
|
||||||
|
out int resultW, out int resultH, out string? error);
|
||||||
|
|
||||||
if (!ok)
|
if (!ok)
|
||||||
{
|
{
|
||||||
@@ -422,61 +654,83 @@ namespace LuaScript
|
|||||||
|
|
||||||
NativeFieldMap.FromFields(_nativeFields, ctx);
|
NativeFieldMap.FromFields(_nativeFields, ctx);
|
||||||
|
|
||||||
|
bool hasDraws = ctx.DrawCommands.Count > 0;
|
||||||
|
|
||||||
if (dirty)
|
if (dirty)
|
||||||
{
|
{
|
||||||
EnsureBitmaps(imgW, imgH);
|
int outW = bufferReplaced ? resultW : imgW;
|
||||||
WritePixelsToOutput(buffer, imgW);
|
int outH = bufferReplaced ? resultH : imgH;
|
||||||
UpdateTransformEffect(bounds.Left, bounds.Top);
|
byte[] outPixels = buffer;
|
||||||
effectOutput = _transformEffect!.Output;
|
|
||||||
|
if (bufferReplaced && newPixels != null)
|
||||||
|
{
|
||||||
|
outPixels = newPixels;
|
||||||
|
ctx.ReplaceBuffer(outPixels, outW, outH);
|
||||||
|
}
|
||||||
|
|
||||||
|
if (hasDraws)
|
||||||
|
{
|
||||||
|
ctx.SetResolvedBuffer(outPixels, outW, outH);
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
|
||||||
|
_pixelManager!.WritePixelsToOutput(outPixels, outW, outH);
|
||||||
|
if (bufferReplaced)
|
||||||
|
effectOutput = _pixelManager.GetTransformOutput(-outW / 2f, -outH / 2f);
|
||||||
|
else
|
||||||
|
effectOutput = _pixelManager.GetTransformOutput(bounds.Left, bounds.Top);
|
||||||
return true;
|
return true;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
if (hasDraws)
|
||||||
|
{
|
||||||
|
ctx.SetResolvedBuffer(buffer, imgW, imgH);
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
effectOutput = null;
|
effectOutput = null;
|
||||||
return false;
|
return false;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
private (byte[] buffer, int w, int h) NativeLoadText(string family, string text, double size, bool bold, bool italic, int color)
|
||||||
|
{
|
||||||
|
_nativeTextRenderer ??= new TextRenderer();
|
||||||
|
var buffer = _nativeTextRenderer.Render(text, family, size, bold, italic, color, out int w, out int h);
|
||||||
|
return (buffer, w, h);
|
||||||
|
}
|
||||||
|
|
||||||
|
private (byte[] buffer, int w, int h) NativeLoadImage(string path)
|
||||||
|
{
|
||||||
|
_nativeImageDecoder ??= new ImageDecoder();
|
||||||
|
var buffer = _nativeImageDecoder.Decode(path, out int w, out int h);
|
||||||
|
return (buffer, w, h);
|
||||||
|
}
|
||||||
|
|
||||||
|
private (byte[] buffer, int w, int h) NativeLoadMovie(string path, double time)
|
||||||
|
{
|
||||||
|
_nativeMovieDecoder ??= new MovieDecoder();
|
||||||
|
var buffer = _nativeMovieDecoder.Decode(path, time, out int w, out int h);
|
||||||
|
return (buffer, w, h);
|
||||||
|
}
|
||||||
|
|
||||||
|
private static (byte[] buffer, int w, int h) NativeLoadFigure(string name, int color, double size, double lineWidth, double aspect)
|
||||||
|
{
|
||||||
|
aspect = Math.Clamp(aspect, -1d, 1d);
|
||||||
|
int boundingSize = Math.Max(1, (int)Math.Round(size));
|
||||||
|
double w = aspect >= 0d ? boundingSize * (1d - aspect) : boundingSize;
|
||||||
|
double h = aspect <= 0d ? boundingSize * (1d + aspect) : boundingSize;
|
||||||
|
int fw = Math.Max(1, (int)Math.Round(w));
|
||||||
|
int fh = Math.Max(1, (int)Math.Round(h));
|
||||||
|
var buffer = FigureRenderer.Render(name, fw, fh, color, lineWidth);
|
||||||
|
return (buffer, fw, fh);
|
||||||
|
}
|
||||||
|
|
||||||
private byte[] LoadInputPixels(RawRectF bounds, int width, int height)
|
private byte[] LoadInputPixels(RawRectF bounds, int width, int height)
|
||||||
{
|
{
|
||||||
_pixelLoaderSemaphore.Wait();
|
_pixelLoaderSemaphore.Wait();
|
||||||
try
|
try
|
||||||
{
|
{
|
||||||
EnsureBitmaps(width, height);
|
return _pixelManager!.LoadInputPixels(input!, bounds, width, height);
|
||||||
|
|
||||||
var dc = _ownCtx!.DeviceContext;
|
|
||||||
var savedTarget = dc.Target;
|
|
||||||
|
|
||||||
dc.Target = _renderTarget;
|
|
||||||
dc.BeginDraw();
|
|
||||||
dc.Clear(null);
|
|
||||||
dc.DrawImage(input!, new Vector2(-bounds.Left, -bounds.Top));
|
|
||||||
dc.EndDraw();
|
|
||||||
dc.Target = savedTarget;
|
|
||||||
|
|
||||||
_stagingBitmap!.CopyFromBitmap(_renderTarget!);
|
|
||||||
|
|
||||||
var mapped = _stagingBitmap.Map(MapOptions.Read);
|
|
||||||
try
|
|
||||||
{
|
|
||||||
if (mapped.Pitch == width * 4)
|
|
||||||
{
|
|
||||||
Marshal.Copy(mapped.Bits, _pixelBuffer!, 0, width * height * 4);
|
|
||||||
}
|
|
||||||
else
|
|
||||||
{
|
|
||||||
for (int row = 0; row < height; row++)
|
|
||||||
Marshal.Copy(
|
|
||||||
mapped.Bits + mapped.Pitch * row,
|
|
||||||
_pixelBuffer!,
|
|
||||||
row * width * 4,
|
|
||||||
width * 4);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
finally
|
|
||||||
{
|
|
||||||
_stagingBitmap.Unmap();
|
|
||||||
}
|
|
||||||
|
|
||||||
return _pixelBuffer!;
|
|
||||||
}
|
}
|
||||||
finally
|
finally
|
||||||
{
|
{
|
||||||
@@ -484,79 +738,20 @@ namespace LuaScript
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
private unsafe void WritePixelsToOutput(byte[] pixels, int width)
|
|
||||||
{
|
|
||||||
fixed (byte* ptr = pixels)
|
|
||||||
_outputBitmap!.CopyFromMemory(new nint(ptr), width * 4);
|
|
||||||
}
|
|
||||||
|
|
||||||
private void UpdateTransformEffect(float left, float top)
|
|
||||||
{
|
|
||||||
if (_transformEffect is null)
|
|
||||||
{
|
|
||||||
_transformEffect = new AffineTransform2D(_ownCtx!.DeviceContext);
|
|
||||||
_transformEffect.SetInput(0, _outputBitmap, true);
|
|
||||||
_cachedBounds = default;
|
|
||||||
}
|
|
||||||
|
|
||||||
if (_cachedBounds.Left != left || _cachedBounds.Top != top)
|
|
||||||
{
|
|
||||||
_transformEffect.TransformMatrix = Matrix3x2.CreateTranslation(left, top);
|
|
||||||
_cachedBounds = new RawRectF(left, top, left, top);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
private void EnsureBitmaps(int width, int height)
|
|
||||||
{
|
|
||||||
if (_bitmapWidth == width && _bitmapHeight == height) return;
|
|
||||||
|
|
||||||
_renderTarget?.Dispose();
|
|
||||||
_stagingBitmap?.Dispose();
|
|
||||||
_outputBitmap?.Dispose();
|
|
||||||
_transformEffect?.Dispose();
|
|
||||||
_renderTarget = null;
|
|
||||||
_stagingBitmap = null;
|
|
||||||
_outputBitmap = null;
|
|
||||||
_transformEffect = null;
|
|
||||||
_bitmapWidth = 0;
|
|
||||||
_bitmapHeight = 0;
|
|
||||||
|
|
||||||
var dc = _ownCtx!.DeviceContext;
|
|
||||||
|
|
||||||
_renderTarget = dc.CreateEmptyBitmap(width, height, BitmapOptions.Target);
|
|
||||||
|
|
||||||
var stagingProps = new BitmapProperties1(
|
|
||||||
new PixelFormat(Format.B8G8R8A8_UNorm, Vortice.DCommon.AlphaMode.Premultiplied),
|
|
||||||
96f, 96f,
|
|
||||||
BitmapOptions.CpuRead | BitmapOptions.CannotDraw);
|
|
||||||
_stagingBitmap = dc.CreateBitmap(
|
|
||||||
new SizeI(width, height),
|
|
||||||
nint.Zero,
|
|
||||||
width * 4,
|
|
||||||
stagingProps);
|
|
||||||
|
|
||||||
_outputBitmap = dc.CreateEmptyBitmap(width, height, BitmapOptions.Target);
|
|
||||||
_pixelBuffer = new byte[width * height * 4];
|
|
||||||
|
|
||||||
_bitmapWidth = width;
|
|
||||||
_bitmapHeight = height;
|
|
||||||
}
|
|
||||||
|
|
||||||
protected override void Dispose(bool disposing)
|
protected override void Dispose(bool disposing)
|
||||||
{
|
{
|
||||||
if (disposing)
|
if (disposing)
|
||||||
{
|
{
|
||||||
_engine.Dispose();
|
_engine.Dispose();
|
||||||
|
_gpuKernel?.Dispose();
|
||||||
_nativeWorker?.Dispose();
|
_nativeWorker?.Dispose();
|
||||||
|
_effectChain?.Dispose();
|
||||||
|
_drawCompositor?.Dispose();
|
||||||
|
_nativeTextRenderer?.Dispose();
|
||||||
|
_nativeImageDecoder?.Dispose();
|
||||||
_pixelLoaderSemaphore.Dispose();
|
_pixelLoaderSemaphore.Dispose();
|
||||||
_renderTarget?.Dispose();
|
_pixelManager?.Dispose();
|
||||||
_stagingBitmap?.Dispose();
|
_pixelManager = null;
|
||||||
_outputBitmap?.Dispose();
|
|
||||||
_transformEffect?.Dispose();
|
|
||||||
_renderTarget = null;
|
|
||||||
_stagingBitmap = null;
|
|
||||||
_outputBitmap = null;
|
|
||||||
_transformEffect = null;
|
|
||||||
}
|
}
|
||||||
base.Dispose(disposing);
|
base.Dispose(disposing);
|
||||||
}
|
}
|
||||||
|
|||||||
+250
-42
@@ -53,6 +53,18 @@ namespace LuaScript
|
|||||||
|
|
||||||
private readonly List<string> _removalBuffer = [];
|
private readonly List<string> _removalBuffer = [];
|
||||||
|
|
||||||
|
private readonly Dictionary<string, DynValue> _options = new(StringComparer.Ordinal);
|
||||||
|
private readonly Dictionary<string, DynValue> _pixelOptions = new(StringComparer.Ordinal);
|
||||||
|
|
||||||
|
private TextRenderer? _textRenderer;
|
||||||
|
private ImageDecoder? _imageDecoder;
|
||||||
|
private MovieDecoder? _movieDecoder;
|
||||||
|
private string _fontFamily = string.Empty;
|
||||||
|
private double _fontSize = 34d;
|
||||||
|
private bool _fontBold;
|
||||||
|
private bool _fontItalic;
|
||||||
|
private int _fontColor = 0xFFFFFF;
|
||||||
|
|
||||||
private Script? _script;
|
private Script? _script;
|
||||||
private DynValue? _compiledChunk;
|
private DynValue? _compiledChunk;
|
||||||
private string _lastCompiledCode = string.Empty;
|
private string _lastCompiledCode = string.Empty;
|
||||||
@@ -203,6 +215,14 @@ namespace LuaScript
|
|||||||
var script = _script!;
|
var script = _script!;
|
||||||
bool isFirstSetup = _objTable is null;
|
bool isFirstSetup = _objTable is null;
|
||||||
|
|
||||||
|
_options.Clear();
|
||||||
|
_pixelOptions.Clear();
|
||||||
|
_fontFamily = string.Empty;
|
||||||
|
_fontSize = 34d;
|
||||||
|
_fontBold = false;
|
||||||
|
_fontItalic = false;
|
||||||
|
_fontColor = 0xFFFFFF;
|
||||||
|
|
||||||
if (isFirstSetup)
|
if (isFirstSetup)
|
||||||
{
|
{
|
||||||
var sceneTable = new Table(script);
|
var sceneTable = new Table(script);
|
||||||
@@ -313,6 +333,12 @@ namespace LuaScript
|
|||||||
_objTable!["track1"] = ctx.Track1;
|
_objTable!["track1"] = ctx.Track1;
|
||||||
_objTable!["track2"] = ctx.Track2;
|
_objTable!["track2"] = ctx.Track2;
|
||||||
_objTable!["track3"] = ctx.Track3;
|
_objTable!["track3"] = ctx.Track3;
|
||||||
|
_objTable!["slider0"] = ctx.Slider0;
|
||||||
|
_objTable!["slider1"] = ctx.Slider1;
|
||||||
|
_objTable!["slider2"] = ctx.Slider2;
|
||||||
|
_objTable!["slider3"] = ctx.Slider3;
|
||||||
|
foreach (var parameter in ctx.StringParameters)
|
||||||
|
_objTable![parameter.Key] = parameter.Value;
|
||||||
_objTable!["check0"] = ctx.Check0;
|
_objTable!["check0"] = ctx.Check0;
|
||||||
_objTable!["check1"] = ctx.Check1;
|
_objTable!["check1"] = ctx.Check1;
|
||||||
_objTable!["check2"] = ctx.Check2;
|
_objTable!["check2"] = ctx.Check2;
|
||||||
@@ -473,22 +499,187 @@ namespace LuaScript
|
|||||||
obj["load"] = DynValue.NewCallback((_, args) =>
|
obj["load"] = DynValue.NewCallback((_, args) =>
|
||||||
{
|
{
|
||||||
_activeCancellation.ThrowIfCancellationRequested();
|
_activeCancellation.ThrowIfCancellationRequested();
|
||||||
if (_activeContext is null || args.Count < 4)
|
if (_activeContext is null || args.Count == 0 || args[0].Type != DataType.String)
|
||||||
return DynValue.Void;
|
|
||||||
if (args[0].Type != DataType.String || args[0].String != "figure")
|
|
||||||
return DynValue.Void;
|
return DynValue.Void;
|
||||||
|
|
||||||
string name = args[1].Type == DataType.String ? args[1].String : string.Empty;
|
switch (args[0].String)
|
||||||
int color = (int)(args[2].CastToNumber() ?? 0d);
|
{
|
||||||
double size = args[3].CastToNumber() ?? 0d;
|
case "figure" when args.Count >= 4:
|
||||||
double line = args.Count > 4 ? args[4].CastToNumber() ?? 0d : 0d;
|
LoadFigure(
|
||||||
double aspect = args.Count > 5 ? Math.Clamp(args[5].CastToNumber() ?? 0d, -1d, 1d) : 0d;
|
args[1].Type == DataType.String ? args[1].String : string.Empty,
|
||||||
|
(int)(args[2].CastToNumber() ?? 0d),
|
||||||
|
args[3].CastToNumber() ?? 0d,
|
||||||
|
args.Count > 4 ? args[4].CastToNumber() ?? 0d : 0d,
|
||||||
|
args.Count > 5 ? Math.Clamp(args[5].CastToNumber() ?? 0d, -1d, 1d) : 0d);
|
||||||
|
break;
|
||||||
|
case "text":
|
||||||
|
LoadText(args.Count > 1 && args[1].Type == DataType.String ? args[1].String : string.Empty);
|
||||||
|
break;
|
||||||
|
case "image" when args.Count > 1 && args[1].Type == DataType.String:
|
||||||
|
LoadImage(args[1].String);
|
||||||
|
break;
|
||||||
|
case "movie" when args.Count > 1 && args[1].Type == DataType.String:
|
||||||
|
LoadMovie(
|
||||||
|
args[1].String,
|
||||||
|
args.Count > 2 ? args[2].CastToNumber() ?? _activeContext.Time : _activeContext.Time);
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
return DynValue.Void;
|
||||||
|
});
|
||||||
|
|
||||||
LoadFigure(name, color, size, line, aspect);
|
obj["setfont"] = DynValue.NewCallback((_, args) =>
|
||||||
|
{
|
||||||
|
_activeCancellation.ThrowIfCancellationRequested();
|
||||||
|
if (args.Count == 0)
|
||||||
|
return DynValue.Void;
|
||||||
|
if (args[0].Type == DataType.String)
|
||||||
|
_fontFamily = args[0].String;
|
||||||
|
if (args.Count > 1)
|
||||||
|
_fontSize = args[1].CastToNumber() ?? _fontSize;
|
||||||
|
if (args.Count > 2)
|
||||||
|
{
|
||||||
|
int type = (int)(args[2].CastToNumber() ?? 0d);
|
||||||
|
_fontBold = (type & 1) != 0;
|
||||||
|
_fontItalic = (type & 2) != 0;
|
||||||
|
}
|
||||||
|
if (args.Count > 3)
|
||||||
|
_fontColor = (int)(args[3].CastToNumber() ?? _fontColor);
|
||||||
|
return DynValue.Void;
|
||||||
|
});
|
||||||
|
|
||||||
|
obj["effect"] = DynValue.NewCallback((_, args) =>
|
||||||
|
{
|
||||||
|
_activeCancellation.ThrowIfCancellationRequested();
|
||||||
|
if (_activeContext is null || args.Count == 0 || args[0].Type != DataType.String)
|
||||||
|
return DynValue.Void;
|
||||||
|
|
||||||
|
string name = args[0].String;
|
||||||
|
var arguments = new List<KeyValuePair<string, object>>();
|
||||||
|
for (int i = 1; i + 1 < args.Count; i += 2)
|
||||||
|
{
|
||||||
|
if (args[i].Type != DataType.String)
|
||||||
|
continue;
|
||||||
|
var value = args[i + 1];
|
||||||
|
object boxed = value.Type switch
|
||||||
|
{
|
||||||
|
DataType.Number => value.Number,
|
||||||
|
DataType.Boolean => value.Boolean,
|
||||||
|
DataType.String => value.String,
|
||||||
|
_ => value.CastToNumber() ?? 0d,
|
||||||
|
};
|
||||||
|
arguments.Add(new KeyValuePair<string, object>(args[i].String, boxed));
|
||||||
|
}
|
||||||
|
|
||||||
|
_activeContext.AddEffect(new AviUtlEffectRequest(name, arguments));
|
||||||
|
return DynValue.Void;
|
||||||
|
});
|
||||||
|
|
||||||
|
obj["draw"] = DynValue.NewCallback((_, args) =>
|
||||||
|
{
|
||||||
|
_activeCancellation.ThrowIfCancellationRequested();
|
||||||
|
if (_activeContext is null)
|
||||||
|
return DynValue.Void;
|
||||||
|
|
||||||
|
double ox = args.Count > 0 ? args[0].CastToNumber() ?? 0d : 0d;
|
||||||
|
double oy = args.Count > 1 ? args[1].CastToNumber() ?? 0d : 0d;
|
||||||
|
double oz = args.Count > 2 ? args[2].CastToNumber() ?? 0d : 0d;
|
||||||
|
double zoom = args.Count > 3 ? args[3].CastToNumber() ?? 1d : 1d;
|
||||||
|
double alpha = args.Count > 4 ? args[4].CastToNumber() ?? 1d : 1d;
|
||||||
|
double aspect = args.Count > 5 ? args[5].CastToNumber() ?? 0d : 0d;
|
||||||
|
|
||||||
|
_activeContext.AddDraw(new DrawCommand(ox, oy, oz, zoom, alpha, aspect, null, CurrentAntialias()));
|
||||||
|
return DynValue.Void;
|
||||||
|
});
|
||||||
|
|
||||||
|
obj["drawpoly"] = DynValue.NewCallback((_, args) =>
|
||||||
|
{
|
||||||
|
_activeCancellation.ThrowIfCancellationRequested();
|
||||||
|
if (_activeContext is null || args.Count < 12)
|
||||||
|
return DynValue.Void;
|
||||||
|
|
||||||
|
var poly = new double[DrawPolyMath.Length];
|
||||||
|
for (int i = 0; i < 12; i++)
|
||||||
|
poly[i] = args[i].CastToNumber() ?? 0d;
|
||||||
|
|
||||||
|
if (args.Count >= 20)
|
||||||
|
{
|
||||||
|
for (int i = 0; i < 8; i++)
|
||||||
|
poly[12 + i] = args[12 + i].CastToNumber() ?? 0d;
|
||||||
|
}
|
||||||
|
else
|
||||||
|
{
|
||||||
|
double w = _activeContext.ImageWidth;
|
||||||
|
double h = _activeContext.ImageHeight;
|
||||||
|
poly[12] = 0d; poly[13] = 0d;
|
||||||
|
poly[14] = w; poly[15] = 0d;
|
||||||
|
poly[16] = w; poly[17] = h;
|
||||||
|
poly[18] = 0d; poly[19] = h;
|
||||||
|
}
|
||||||
|
|
||||||
|
poly[20] = args.Count switch
|
||||||
|
{
|
||||||
|
13 => args[12].CastToNumber() ?? 1d,
|
||||||
|
>= 21 => args[20].CastToNumber() ?? 1d,
|
||||||
|
_ => 1d,
|
||||||
|
};
|
||||||
|
|
||||||
|
_activeContext.AddDraw(new DrawCommand(0d, 0d, 0d, 1d, poly[20], 0d, poly, CurrentAntialias()));
|
||||||
|
return DynValue.Void;
|
||||||
|
});
|
||||||
|
|
||||||
|
obj["copybuffer"] = DynValue.NewCallback((_, args) =>
|
||||||
|
{
|
||||||
|
_activeCancellation.ThrowIfCancellationRequested();
|
||||||
|
if (_activeContext is null || args.Count < 2 ||
|
||||||
|
args[0].Type != DataType.String || args[1].Type != DataType.String)
|
||||||
|
return DynValue.Void;
|
||||||
|
|
||||||
|
if (_activeContext.CopyBuffer(args[0].String, args[1].String))
|
||||||
|
RefreshObjDimensions();
|
||||||
|
return DynValue.Void;
|
||||||
|
});
|
||||||
|
|
||||||
|
obj["getvalue"] = DynValue.NewCallback((_, args) =>
|
||||||
|
{
|
||||||
|
_activeCancellation.ThrowIfCancellationRequested();
|
||||||
|
if (args.Count == 0 || args[0].Type != DataType.String)
|
||||||
|
return DynValue.NewNumber(0d);
|
||||||
|
var value = _objTable!.Get(args[0].String);
|
||||||
|
return value.Type == DataType.Number ? value : DynValue.NewNumber(0d);
|
||||||
|
});
|
||||||
|
|
||||||
|
obj["setoption"] = DynValue.NewCallback((_, args) =>
|
||||||
|
{
|
||||||
|
_activeCancellation.ThrowIfCancellationRequested();
|
||||||
|
if (args.Count == 0 || args[0].Type != DataType.String)
|
||||||
|
return DynValue.Void;
|
||||||
|
_options[args[0].String] = args.Count > 1 ? args[1] : DynValue.True;
|
||||||
|
return DynValue.Void;
|
||||||
|
});
|
||||||
|
|
||||||
|
obj["getoption"] = DynValue.NewCallback((_, args) =>
|
||||||
|
{
|
||||||
|
_activeCancellation.ThrowIfCancellationRequested();
|
||||||
|
if (args.Count == 0 || args[0].Type != DataType.String)
|
||||||
|
return DynValue.NewNumber(0d);
|
||||||
|
return _options.TryGetValue(args[0].String, out var value) ? value : DynValue.NewNumber(0d);
|
||||||
|
});
|
||||||
|
|
||||||
|
obj["pixeloption"] = DynValue.NewCallback((_, args) =>
|
||||||
|
{
|
||||||
|
_activeCancellation.ThrowIfCancellationRequested();
|
||||||
|
if (args.Count == 0 || args[0].Type != DataType.String)
|
||||||
|
return DynValue.Void;
|
||||||
|
_pixelOptions[args[0].String] = args.Count > 1 ? args[1] : DynValue.True;
|
||||||
return DynValue.Void;
|
return DynValue.Void;
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
|
private double CurrentAntialias() =>
|
||||||
|
_options.TryGetValue("antialias", out var value) && value.Type == DataType.Number
|
||||||
|
? value.Number
|
||||||
|
: 1d;
|
||||||
|
|
||||||
private void LoadFigure(string name, int color, double size, double line, double aspect)
|
private void LoadFigure(string name, int color, double size, double line, double aspect)
|
||||||
{
|
{
|
||||||
int boundingSize = Math.Max(1, (int)Math.Round(size));
|
int boundingSize = Math.Max(1, (int)Math.Round(size));
|
||||||
@@ -500,6 +691,39 @@ namespace LuaScript
|
|||||||
var buffer = FigureRenderer.Render(name, w, h, color, line);
|
var buffer = FigureRenderer.Render(name, w, h, color, line);
|
||||||
_activeContext!.ReplaceBuffer(buffer, w, h);
|
_activeContext!.ReplaceBuffer(buffer, w, h);
|
||||||
|
|
||||||
|
RefreshObjDimensions();
|
||||||
|
}
|
||||||
|
|
||||||
|
private void LoadText(string text)
|
||||||
|
{
|
||||||
|
_textRenderer ??= new TextRenderer();
|
||||||
|
var buffer = _textRenderer.Render(
|
||||||
|
text, _fontFamily, _fontSize, _fontBold, _fontItalic, _fontColor,
|
||||||
|
out int w, out int h);
|
||||||
|
_activeContext!.ReplaceBuffer(buffer, w, h);
|
||||||
|
RefreshObjDimensions();
|
||||||
|
}
|
||||||
|
|
||||||
|
private void LoadImage(string path)
|
||||||
|
{
|
||||||
|
_imageDecoder ??= new ImageDecoder();
|
||||||
|
var buffer = _imageDecoder.Decode(path, out int w, out int h);
|
||||||
|
_activeContext!.ReplaceBuffer(buffer, w, h);
|
||||||
|
RefreshObjDimensions();
|
||||||
|
}
|
||||||
|
|
||||||
|
private void LoadMovie(string path, double time)
|
||||||
|
{
|
||||||
|
_movieDecoder ??= new MovieDecoder();
|
||||||
|
var buffer = _movieDecoder.Decode(path, time, out int w, out int h);
|
||||||
|
_activeContext!.ReplaceBuffer(buffer, w, h);
|
||||||
|
RefreshObjDimensions();
|
||||||
|
}
|
||||||
|
|
||||||
|
private void RefreshObjDimensions()
|
||||||
|
{
|
||||||
|
int w = _activeContext!.ImageWidth;
|
||||||
|
int h = _activeContext.ImageHeight;
|
||||||
var obj = _objTable!;
|
var obj = _objTable!;
|
||||||
obj["w"] = w;
|
obj["w"] = w;
|
||||||
obj["h"] = h;
|
obj["h"] = h;
|
||||||
@@ -546,39 +770,17 @@ namespace LuaScript
|
|||||||
ctx.Oz = _objTable.Get("oz").CastToNumber() ?? ctx.Oz;
|
ctx.Oz = _objTable.Get("oz").CastToNumber() ?? ctx.Oz;
|
||||||
ctx.Alpha = _objTable.Get("alpha").CastToNumber() ?? ctx.Alpha;
|
ctx.Alpha = _objTable.Get("alpha").CastToNumber() ?? ctx.Alpha;
|
||||||
|
|
||||||
double initialSx = ctx.Sx;
|
ctx.ApplyWriteBack(
|
||||||
double initialSy = ctx.Sy;
|
_objTable.Get("sx").CastToNumber() ?? ctx.Sx,
|
||||||
double initialZoom = ctx.Zoom;
|
_objTable.Get("sy").CastToNumber() ?? ctx.Sy,
|
||||||
double initialAspect = ctx.Aspect;
|
_objTable.Get("zoom").CastToNumber() ?? ctx.Zoom,
|
||||||
|
_objTable.Get("aspect").CastToNumber() ?? ctx.Aspect,
|
||||||
ctx.Sx = _objTable.Get("sx").CastToNumber() ?? ctx.Sx;
|
_objTable.Get("rx").CastToNumber() ?? ctx.Rx,
|
||||||
ctx.Sy = _objTable.Get("sy").CastToNumber() ?? ctx.Sy;
|
_objTable.Get("ry").CastToNumber() ?? ctx.Ry,
|
||||||
ctx.Zoom = _objTable.Get("zoom").CastToNumber() ?? ctx.Zoom;
|
_objTable.Get("rz").CastToNumber() ?? ctx.Rz,
|
||||||
ctx.Aspect = _objTable.Get("aspect").CastToNumber() ?? ctx.Aspect;
|
_objTable.Get("rxr").CastToNumber() ?? ctx.RxRad,
|
||||||
|
_objTable.Get("ryr").CastToNumber() ?? ctx.RyRad,
|
||||||
bool sxsyChanged = Math.Abs(ctx.Sx - initialSx) > 1e-10 || Math.Abs(ctx.Sy - initialSy) > 1e-10;
|
_objTable.Get("rzr").CastToNumber() ?? ctx.RzRad);
|
||||||
bool zoomAspectChanged = Math.Abs(ctx.Zoom - initialZoom) > 1e-10 || Math.Abs(ctx.Aspect - initialAspect) > 1e-10;
|
|
||||||
|
|
||||||
if (zoomAspectChanged && !sxsyChanged)
|
|
||||||
{
|
|
||||||
ctx.Sx = ctx.Zoom * (1.0 + ctx.Aspect);
|
|
||||||
ctx.Sy = ctx.Zoom * (1.0 - ctx.Aspect);
|
|
||||||
}
|
|
||||||
|
|
||||||
double rxrNew = _objTable.Get("rxr").CastToNumber() ?? ctx.RxRad;
|
|
||||||
ctx.Rx = Math.Abs(rxrNew - ctx.RxRad) > 1e-10
|
|
||||||
? rxrNew * (180d / Math.PI)
|
|
||||||
: _objTable.Get("rx").CastToNumber() ?? ctx.Rx;
|
|
||||||
|
|
||||||
double ryrNew = _objTable.Get("ryr").CastToNumber() ?? ctx.RyRad;
|
|
||||||
ctx.Ry = Math.Abs(ryrNew - ctx.RyRad) > 1e-10
|
|
||||||
? ryrNew * (180d / Math.PI)
|
|
||||||
: _objTable.Get("ry").CastToNumber() ?? ctx.Ry;
|
|
||||||
|
|
||||||
double rzrNew = _objTable.Get("rzr").CastToNumber() ?? ctx.RzRad;
|
|
||||||
ctx.Rz = Math.Abs(rzrNew - ctx.RzRad) > 1e-10
|
|
||||||
? rzrNew * (180d / Math.PI)
|
|
||||||
: _objTable.Get("rz").CastToNumber() ?? ctx.Rz;
|
|
||||||
}
|
}
|
||||||
|
|
||||||
public void Dispose()
|
public void Dispose()
|
||||||
@@ -586,6 +788,9 @@ namespace LuaScript
|
|||||||
_disposeRequested = true;
|
_disposeRequested = true;
|
||||||
_workSignal.Release();
|
_workSignal.Release();
|
||||||
_thread.Join();
|
_thread.Join();
|
||||||
|
_textRenderer?.Dispose();
|
||||||
|
_imageDecoder?.Dispose();
|
||||||
|
_movieDecoder?.Dispose();
|
||||||
_cts.Cancel();
|
_cts.Cancel();
|
||||||
_cts.Dispose();
|
_cts.Dispose();
|
||||||
_workSignal.Dispose();
|
_workSignal.Dispose();
|
||||||
@@ -599,6 +804,9 @@ namespace LuaScript
|
|||||||
ThreadPool.QueueUserWorkItem(_ =>
|
ThreadPool.QueueUserWorkItem(_ =>
|
||||||
{
|
{
|
||||||
_thread.Join();
|
_thread.Join();
|
||||||
|
_textRenderer?.Dispose();
|
||||||
|
_imageDecoder?.Dispose();
|
||||||
|
_movieDecoder?.Dispose();
|
||||||
_cts.Dispose();
|
_cts.Dispose();
|
||||||
_workSignal.Dispose();
|
_workSignal.Dispose();
|
||||||
_doneSignal.Dispose();
|
_doneSignal.Dispose();
|
||||||
|
|||||||
@@ -0,0 +1,6 @@
|
|||||||
|
using System;
|
||||||
|
|
||||||
|
namespace LuaScript
|
||||||
|
{
|
||||||
|
internal abstract class LuaScriptException(string message, Exception? inner = null) : Exception(message, inner);
|
||||||
|
}
|
||||||
@@ -1,10 +0,0 @@
|
|||||||
namespace LuaScript
|
|
||||||
{
|
|
||||||
internal abstract class LuaScriptException(string message, Exception? inner = null) : Exception(message, inner);
|
|
||||||
|
|
||||||
internal sealed class LuaScriptCompilationException(string message, Exception? inner = null) : LuaScriptException(message, inner);
|
|
||||||
|
|
||||||
internal sealed class LuaScriptRuntimeException(string message, Exception? inner = null) : LuaScriptException(message, inner);
|
|
||||||
|
|
||||||
internal sealed class LuaScriptTimeoutException(string message, Exception? inner = null) : LuaScriptException(message, inner);
|
|
||||||
}
|
|
||||||
@@ -0,0 +1,6 @@
|
|||||||
|
using System;
|
||||||
|
|
||||||
|
namespace LuaScript
|
||||||
|
{
|
||||||
|
internal sealed class LuaScriptRuntimeException(string message, Exception? inner = null) : LuaScriptException(message, inner);
|
||||||
|
}
|
||||||
@@ -0,0 +1,6 @@
|
|||||||
|
using System;
|
||||||
|
|
||||||
|
namespace LuaScript
|
||||||
|
{
|
||||||
|
internal sealed class LuaScriptTimeoutException(string message, Exception? inner = null) : LuaScriptException(message, inner);
|
||||||
|
}
|
||||||
@@ -0,0 +1,213 @@
|
|||||||
|
using System;
|
||||||
|
using System.IO;
|
||||||
|
using SharpGen.Runtime.Win32;
|
||||||
|
using Vortice.MediaFoundation;
|
||||||
|
|
||||||
|
namespace LuaScript
|
||||||
|
{
|
||||||
|
internal sealed class MovieDecoder : IDisposable
|
||||||
|
{
|
||||||
|
private const int MaxDimension = 8192;
|
||||||
|
private const int FirstVideoStream = -4;
|
||||||
|
private const int AllStreams = -2;
|
||||||
|
private const int EndOfStreamFlag = 0x2;
|
||||||
|
|
||||||
|
private bool _mfStarted;
|
||||||
|
private string? _path;
|
||||||
|
private IMFSourceReader? _reader;
|
||||||
|
private int _width;
|
||||||
|
private int _height;
|
||||||
|
private int _stride;
|
||||||
|
|
||||||
|
public unsafe byte[] Decode(string path, double timeSeconds, out int width, out int height)
|
||||||
|
{
|
||||||
|
width = 1;
|
||||||
|
height = 1;
|
||||||
|
if (string.IsNullOrEmpty(path) || !IsSupportedVideo(path))
|
||||||
|
return new byte[4];
|
||||||
|
|
||||||
|
try
|
||||||
|
{
|
||||||
|
EnsureReader(path);
|
||||||
|
if (_reader is null || _width <= 0 || _height <= 0)
|
||||||
|
return new byte[4];
|
||||||
|
|
||||||
|
SetPosition(_reader, (long)(Math.Max(0d, timeSeconds) * 10_000_000d));
|
||||||
|
|
||||||
|
using var sample = ReadVideoSample(_reader);
|
||||||
|
if (sample is null)
|
||||||
|
return new byte[4];
|
||||||
|
|
||||||
|
using var buffer = sample.ConvertToContiguousBuffer();
|
||||||
|
buffer.Lock(out nint data, out _, out _);
|
||||||
|
try
|
||||||
|
{
|
||||||
|
int w = _width;
|
||||||
|
int h = _height;
|
||||||
|
int absStride = Math.Abs(_stride);
|
||||||
|
bool bottomUp = _stride < 0;
|
||||||
|
var result = new byte[w * h * 4];
|
||||||
|
byte* src = (byte*)data;
|
||||||
|
fixed (byte* dst = result)
|
||||||
|
{
|
||||||
|
for (int y = 0; y < h; y++)
|
||||||
|
{
|
||||||
|
int sourceRow = bottomUp ? h - 1 - y : y;
|
||||||
|
byte* s = src + sourceRow * absStride;
|
||||||
|
byte* d = dst + y * w * 4;
|
||||||
|
for (int x = 0; x < w; x++)
|
||||||
|
{
|
||||||
|
d[0] = s[0];
|
||||||
|
d[1] = s[1];
|
||||||
|
d[2] = s[2];
|
||||||
|
d[3] = 255;
|
||||||
|
s += 4;
|
||||||
|
d += 4;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
width = w;
|
||||||
|
height = h;
|
||||||
|
return result;
|
||||||
|
}
|
||||||
|
finally
|
||||||
|
{
|
||||||
|
buffer.Unlock();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
catch
|
||||||
|
{
|
||||||
|
width = 1;
|
||||||
|
height = 1;
|
||||||
|
return new byte[4];
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private void EnsureReader(string path)
|
||||||
|
{
|
||||||
|
if (_reader is not null && string.Equals(_path, path, StringComparison.Ordinal))
|
||||||
|
return;
|
||||||
|
|
||||||
|
DisposeReader();
|
||||||
|
|
||||||
|
if (!_mfStarted)
|
||||||
|
{
|
||||||
|
MediaFactory.MFStartup(false);
|
||||||
|
_mfStarted = true;
|
||||||
|
}
|
||||||
|
|
||||||
|
using var attributes = MediaFactory.MFCreateAttributes(1);
|
||||||
|
attributes.Set(SourceReaderAttributeKeys.EnableAdvancedVideoProcessing, 1);
|
||||||
|
var reader = MediaFactory.MFCreateSourceReaderFromURL(path, attributes);
|
||||||
|
|
||||||
|
reader.SetStreamSelection(AllStreams, false);
|
||||||
|
reader.SetStreamSelection(FirstVideoStream, true);
|
||||||
|
|
||||||
|
using (var mediaType = MediaFactory.MFCreateMediaType())
|
||||||
|
{
|
||||||
|
mediaType.Set(MediaTypeAttributeKeys.MajorType, MediaTypeGuids.Video);
|
||||||
|
mediaType.Set(MediaTypeAttributeKeys.Subtype, VideoFormatGuids.Rgb32);
|
||||||
|
reader.SetCurrentMediaType(FirstVideoStream, mediaType);
|
||||||
|
}
|
||||||
|
|
||||||
|
using var current = reader.GetCurrentMediaType(FirstVideoStream);
|
||||||
|
var mediaAttributes = (IMFAttributes)current;
|
||||||
|
ulong frameSize = Convert.ToUInt64(mediaAttributes.Get(MediaTypeAttributeKeys.FrameSize));
|
||||||
|
int w = (int)(frameSize >> 32);
|
||||||
|
int h = (int)(frameSize & 0xFFFFFFFF);
|
||||||
|
|
||||||
|
int stride;
|
||||||
|
try { stride = Convert.ToInt32(mediaAttributes.Get(MediaTypeAttributeKeys.DefaultStride)); }
|
||||||
|
catch { stride = w * 4; }
|
||||||
|
if (stride == 0)
|
||||||
|
stride = w * 4;
|
||||||
|
|
||||||
|
if (w <= 0 || h <= 0 || w > MaxDimension || h > MaxDimension)
|
||||||
|
{
|
||||||
|
reader.Dispose();
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
_reader = reader;
|
||||||
|
_path = path;
|
||||||
|
_width = w;
|
||||||
|
_height = h;
|
||||||
|
_stride = stride;
|
||||||
|
}
|
||||||
|
|
||||||
|
private static void SetPosition(IMFSourceReader reader, long ticks)
|
||||||
|
{
|
||||||
|
var variant = new Variant
|
||||||
|
{
|
||||||
|
Value = ticks,
|
||||||
|
ElementType = (VariantElementType)20,
|
||||||
|
};
|
||||||
|
reader.SetCurrentPosition(Guid.Empty, variant);
|
||||||
|
}
|
||||||
|
|
||||||
|
private static IMFSample? ReadVideoSample(IMFSourceReader reader)
|
||||||
|
{
|
||||||
|
for (int guard = 0; guard < 256; guard++)
|
||||||
|
{
|
||||||
|
reader.ReadSample(FirstVideoStream, 0, out _, out int flags, out _, out IMFSample? sample);
|
||||||
|
if (sample is not null)
|
||||||
|
return sample;
|
||||||
|
if ((flags & EndOfStreamFlag) != 0)
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
|
||||||
|
private static bool IsSupportedVideo(string path)
|
||||||
|
{
|
||||||
|
try
|
||||||
|
{
|
||||||
|
if (!File.Exists(path))
|
||||||
|
return false;
|
||||||
|
Span<byte> head = stackalloc byte[16];
|
||||||
|
using var stream = File.OpenRead(path);
|
||||||
|
int read = stream.Read(head);
|
||||||
|
if (read < 12)
|
||||||
|
return false;
|
||||||
|
|
||||||
|
if (head[4] == 0x66 && head[5] == 0x74 && head[6] == 0x79 && head[7] == 0x70)
|
||||||
|
return true;
|
||||||
|
if (head[0] == 0x1A && head[1] == 0x45 && head[2] == 0xDF && head[3] == 0xA3)
|
||||||
|
return true;
|
||||||
|
if (head[0] == 0x52 && head[1] == 0x49 && head[2] == 0x46 && head[3] == 0x46 &&
|
||||||
|
head[8] == 0x41 && head[9] == 0x56 && head[10] == 0x49 && head[11] == 0x20)
|
||||||
|
return true;
|
||||||
|
if (head[0] == 0x46 && head[1] == 0x4C && head[2] == 0x56)
|
||||||
|
return true;
|
||||||
|
if (head[0] == 0x30 && head[1] == 0x26 && head[2] == 0xB2 && head[3] == 0x75)
|
||||||
|
return true;
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
catch
|
||||||
|
{
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private void DisposeReader()
|
||||||
|
{
|
||||||
|
_reader?.Dispose();
|
||||||
|
_reader = null;
|
||||||
|
_path = null;
|
||||||
|
_width = 0;
|
||||||
|
_height = 0;
|
||||||
|
_stride = 0;
|
||||||
|
}
|
||||||
|
|
||||||
|
public void Dispose()
|
||||||
|
{
|
||||||
|
DisposeReader();
|
||||||
|
if (_mfStarted)
|
||||||
|
{
|
||||||
|
try { MediaFactory.MFShutdown(); }
|
||||||
|
catch { }
|
||||||
|
_mfStarted = false;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,145 @@
|
|||||||
|
using System;
|
||||||
|
using Vortice;
|
||||||
|
using System.Numerics;
|
||||||
|
using System.Runtime.InteropServices;
|
||||||
|
using Vortice.DCommon;
|
||||||
|
using Vortice.Direct2D1;
|
||||||
|
using Vortice.Direct2D1.Effects;
|
||||||
|
using Vortice.DXGI;
|
||||||
|
using Vortice.Mathematics;
|
||||||
|
using YukkuriMovieMaker.Commons;
|
||||||
|
|
||||||
|
namespace LuaScript
|
||||||
|
{
|
||||||
|
internal sealed class PixelBufferManager : IDisposable
|
||||||
|
{
|
||||||
|
private readonly GraphicsDevicesAndContext _ctx;
|
||||||
|
private ID2D1Bitmap1? _renderTarget;
|
||||||
|
private ID2D1Bitmap1? _stagingBitmap;
|
||||||
|
private ID2D1Bitmap1? _outputBitmap;
|
||||||
|
private AffineTransform2D? _transformEffect;
|
||||||
|
private byte[]? _pixelBuffer;
|
||||||
|
private int _bitmapWidth;
|
||||||
|
private int _bitmapHeight;
|
||||||
|
private RawRectF _cachedBounds;
|
||||||
|
|
||||||
|
public PixelBufferManager(GraphicsDevicesAndContext ctx)
|
||||||
|
{
|
||||||
|
_ctx = ctx;
|
||||||
|
}
|
||||||
|
|
||||||
|
public byte[] LoadInputPixels(ID2D1Image input, RawRectF bounds, int width, int height)
|
||||||
|
{
|
||||||
|
EnsureBitmaps(width, height);
|
||||||
|
|
||||||
|
var dc = _ctx.DeviceContext;
|
||||||
|
var savedTarget = dc.Target;
|
||||||
|
|
||||||
|
dc.Target = _renderTarget;
|
||||||
|
dc.BeginDraw();
|
||||||
|
dc.Clear(null);
|
||||||
|
dc.DrawImage(input, new Vector2(-bounds.Left, -bounds.Top));
|
||||||
|
dc.EndDraw();
|
||||||
|
dc.Target = savedTarget;
|
||||||
|
|
||||||
|
_stagingBitmap!.CopyFromBitmap(_renderTarget!);
|
||||||
|
|
||||||
|
var mapped = _stagingBitmap.Map(MapOptions.Read);
|
||||||
|
try
|
||||||
|
{
|
||||||
|
if (mapped.Pitch == width * 4)
|
||||||
|
{
|
||||||
|
Marshal.Copy(mapped.Bits, _pixelBuffer!, 0, width * height * 4);
|
||||||
|
}
|
||||||
|
else
|
||||||
|
{
|
||||||
|
for (int row = 0; row < height; row++)
|
||||||
|
Marshal.Copy(
|
||||||
|
mapped.Bits + mapped.Pitch * row,
|
||||||
|
_pixelBuffer!,
|
||||||
|
row * width * 4,
|
||||||
|
width * 4);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
finally
|
||||||
|
{
|
||||||
|
_stagingBitmap.Unmap();
|
||||||
|
}
|
||||||
|
|
||||||
|
return _pixelBuffer!;
|
||||||
|
}
|
||||||
|
|
||||||
|
public unsafe void WritePixelsToOutput(byte[] pixels, int width, int height)
|
||||||
|
{
|
||||||
|
EnsureBitmaps(width, height);
|
||||||
|
fixed (byte* ptr = pixels)
|
||||||
|
_outputBitmap!.CopyFromMemory(new nint(ptr), width * 4);
|
||||||
|
}
|
||||||
|
|
||||||
|
public ID2D1Image GetTransformOutput(float left, float top)
|
||||||
|
{
|
||||||
|
if (_transformEffect is null)
|
||||||
|
{
|
||||||
|
_transformEffect = new AffineTransform2D(_ctx.DeviceContext);
|
||||||
|
_transformEffect.SetInput(0, _outputBitmap, true);
|
||||||
|
_cachedBounds = default;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (_cachedBounds.Left != left || _cachedBounds.Top != top)
|
||||||
|
{
|
||||||
|
_transformEffect.TransformMatrix = Matrix3x2.CreateTranslation(left, top);
|
||||||
|
_cachedBounds = new RawRectF(left, top, left, top);
|
||||||
|
}
|
||||||
|
|
||||||
|
return _transformEffect.Output;
|
||||||
|
}
|
||||||
|
|
||||||
|
private void EnsureBitmaps(int width, int height)
|
||||||
|
{
|
||||||
|
if (_bitmapWidth == width && _bitmapHeight == height) return;
|
||||||
|
|
||||||
|
_renderTarget?.Dispose();
|
||||||
|
_stagingBitmap?.Dispose();
|
||||||
|
_outputBitmap?.Dispose();
|
||||||
|
_transformEffect?.Dispose();
|
||||||
|
_renderTarget = null;
|
||||||
|
_stagingBitmap = null;
|
||||||
|
_outputBitmap = null;
|
||||||
|
_transformEffect = null;
|
||||||
|
_bitmapWidth = 0;
|
||||||
|
_bitmapHeight = 0;
|
||||||
|
|
||||||
|
var dc = _ctx.DeviceContext;
|
||||||
|
|
||||||
|
_renderTarget = dc.CreateEmptyBitmap(width, height, BitmapOptions.Target);
|
||||||
|
|
||||||
|
var stagingProps = new BitmapProperties1(
|
||||||
|
new PixelFormat(Format.B8G8R8A8_UNorm, Vortice.DCommon.AlphaMode.Premultiplied),
|
||||||
|
96f, 96f,
|
||||||
|
BitmapOptions.CpuRead | BitmapOptions.CannotDraw);
|
||||||
|
_stagingBitmap = dc.CreateBitmap(
|
||||||
|
new SizeI(width, height),
|
||||||
|
nint.Zero,
|
||||||
|
width * 4,
|
||||||
|
stagingProps);
|
||||||
|
|
||||||
|
_outputBitmap = dc.CreateEmptyBitmap(width, height, BitmapOptions.Target);
|
||||||
|
_pixelBuffer = new byte[width * height * 4];
|
||||||
|
|
||||||
|
_bitmapWidth = width;
|
||||||
|
_bitmapHeight = height;
|
||||||
|
}
|
||||||
|
|
||||||
|
public void Dispose()
|
||||||
|
{
|
||||||
|
_renderTarget?.Dispose();
|
||||||
|
_stagingBitmap?.Dispose();
|
||||||
|
_outputBitmap?.Dispose();
|
||||||
|
_transformEffect?.Dispose();
|
||||||
|
_renderTarget = null;
|
||||||
|
_stagingBitmap = null;
|
||||||
|
_outputBitmap = null;
|
||||||
|
_transformEffect = null;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -10,9 +10,4 @@ namespace LuaScript
|
|||||||
double Rz,
|
double Rz,
|
||||||
double Alpha,
|
double Alpha,
|
||||||
int Layer);
|
int Layer);
|
||||||
|
|
||||||
internal readonly record struct SceneObjectQuery(
|
|
||||||
string Tag,
|
|
||||||
int Frame,
|
|
||||||
SceneObjectInfo? Result);
|
|
||||||
}
|
}
|
||||||
@@ -0,0 +1,7 @@
|
|||||||
|
namespace LuaScript
|
||||||
|
{
|
||||||
|
internal readonly record struct SceneObjectQuery(
|
||||||
|
string Tag,
|
||||||
|
int Frame,
|
||||||
|
SceneObjectInfo? Result);
|
||||||
|
}
|
||||||
@@ -0,0 +1,97 @@
|
|||||||
|
using System;
|
||||||
|
using System.Numerics;
|
||||||
|
using Vortice.Direct2D1;
|
||||||
|
using Vortice.DirectWrite;
|
||||||
|
using Vortice.Mathematics;
|
||||||
|
using Vortice.WIC;
|
||||||
|
|
||||||
|
namespace LuaScript
|
||||||
|
{
|
||||||
|
internal sealed class TextRenderer : IDisposable
|
||||||
|
{
|
||||||
|
private const int MaxDimension = 8192;
|
||||||
|
private const string FallbackFamily = "Yu Gothic UI";
|
||||||
|
|
||||||
|
private ID2D1Factory? _d2dFactory;
|
||||||
|
private IWICImagingFactory? _wicFactory;
|
||||||
|
private IDWriteFactory? _dwriteFactory;
|
||||||
|
|
||||||
|
private void EnsureFactories()
|
||||||
|
{
|
||||||
|
_d2dFactory ??= D2D1.D2D1CreateFactory<ID2D1Factory>(
|
||||||
|
Vortice.Direct2D1.FactoryType.MultiThreaded, DebugLevel.None);
|
||||||
|
_wicFactory ??= new IWICImagingFactory();
|
||||||
|
_dwriteFactory ??= DWrite.DWriteCreateFactory<IDWriteFactory>(
|
||||||
|
Vortice.DirectWrite.FactoryType.Shared);
|
||||||
|
}
|
||||||
|
|
||||||
|
public unsafe byte[] Render(
|
||||||
|
string text, string fontFamily, double fontSize,
|
||||||
|
bool bold, bool italic, int colorRgb,
|
||||||
|
out int width, out int height)
|
||||||
|
{
|
||||||
|
width = 1;
|
||||||
|
height = 1;
|
||||||
|
if (string.IsNullOrEmpty(text))
|
||||||
|
return new byte[4];
|
||||||
|
|
||||||
|
EnsureFactories();
|
||||||
|
|
||||||
|
float size = (float)Math.Clamp(fontSize, 1d, 4096d);
|
||||||
|
using var format = _dwriteFactory!.CreateTextFormat(
|
||||||
|
string.IsNullOrWhiteSpace(fontFamily) ? FallbackFamily : fontFamily,
|
||||||
|
null,
|
||||||
|
bold ? FontWeight.Bold : FontWeight.Normal,
|
||||||
|
italic ? FontStyle.Italic : FontStyle.Normal,
|
||||||
|
FontStretch.Normal,
|
||||||
|
size,
|
||||||
|
string.Empty);
|
||||||
|
|
||||||
|
using var layout = _dwriteFactory.CreateTextLayout(text, format, MaxDimension, MaxDimension);
|
||||||
|
var metrics = layout.Metrics;
|
||||||
|
int w = Math.Clamp((int)Math.Ceiling(metrics.WidthIncludingTrailingWhitespace), 1, MaxDimension);
|
||||||
|
int h = Math.Clamp((int)Math.Ceiling(metrics.Height), 1, MaxDimension);
|
||||||
|
|
||||||
|
using var wic = _wicFactory!.CreateBitmap(
|
||||||
|
w, h, Vortice.WIC.PixelFormat.Format32bppPBGRA, BitmapCreateCacheOption.CacheOnLoad);
|
||||||
|
|
||||||
|
var properties = new RenderTargetProperties(
|
||||||
|
RenderTargetType.Default,
|
||||||
|
new Vortice.DCommon.PixelFormat(Vortice.DXGI.Format.B8G8R8A8_UNorm, Vortice.DCommon.AlphaMode.Premultiplied),
|
||||||
|
96f, 96f,
|
||||||
|
RenderTargetUsage.None,
|
||||||
|
FeatureLevel.Default);
|
||||||
|
|
||||||
|
float r = ((colorRgb >> 16) & 0xFF) / 255f;
|
||||||
|
float g = ((colorRgb >> 8) & 0xFF) / 255f;
|
||||||
|
float b = (colorRgb & 0xFF) / 255f;
|
||||||
|
|
||||||
|
using (var target = _d2dFactory!.CreateWicBitmapRenderTarget(wic, properties))
|
||||||
|
{
|
||||||
|
target.BeginDraw();
|
||||||
|
target.Clear(new Color4(0f, 0f, 0f, 0f));
|
||||||
|
using (var brush = target.CreateSolidColorBrush(new Color4(r, g, b, 1f)))
|
||||||
|
target.DrawTextLayout(new Vector2(-metrics.Left, -metrics.Top), layout, brush);
|
||||||
|
target.EndDraw();
|
||||||
|
}
|
||||||
|
|
||||||
|
var buffer = new byte[w * h * 4];
|
||||||
|
fixed (byte* p = buffer)
|
||||||
|
wic.CopyPixels(new RectI(0, 0, w, h), w * 4, buffer.Length, (nint)p);
|
||||||
|
|
||||||
|
width = w;
|
||||||
|
height = h;
|
||||||
|
return buffer;
|
||||||
|
}
|
||||||
|
|
||||||
|
public void Dispose()
|
||||||
|
{
|
||||||
|
_dwriteFactory?.Dispose();
|
||||||
|
_wicFactory?.Dispose();
|
||||||
|
_d2dFactory?.Dispose();
|
||||||
|
_dwriteFactory = null;
|
||||||
|
_wicFactory = null;
|
||||||
|
_d2dFactory = null;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -69,6 +69,11 @@
|
|||||||
<data name="Track2" xml:space="preserve"><value>مسار 2</value></data>
|
<data name="Track2" xml:space="preserve"><value>مسار 2</value></data>
|
||||||
<data name="Track3" xml:space="preserve"><value>مسار 3</value></data>
|
<data name="Track3" xml:space="preserve"><value>مسار 3</value></data>
|
||||||
<data name="TrackDesc" xml:space="preserve"><value>قيمة المنزلق (متوافق مع AviUtl: track0-3)</value></data>
|
<data name="TrackDesc" xml:space="preserve"><value>قيمة المنزلق (متوافق مع AviUtl: track0-3)</value></data>
|
||||||
|
<data name="Slider0" xml:space="preserve"><value>منزلق 0</value></data>
|
||||||
|
<data name="Slider1" xml:space="preserve"><value>منزلق 1</value></data>
|
||||||
|
<data name="Slider2" xml:space="preserve"><value>منزلق 2</value></data>
|
||||||
|
<data name="Slider3" xml:space="preserve"><value>منزلق 3</value></data>
|
||||||
|
<data name="SliderDesc" xml:space="preserve"><value>منزلق رقمي (obj.slider0-3)</value></data>
|
||||||
<data name="Check0" xml:space="preserve"><value>خانة 0</value></data>
|
<data name="Check0" xml:space="preserve"><value>خانة 0</value></data>
|
||||||
<data name="Check1" xml:space="preserve"><value>خانة 1</value></data>
|
<data name="Check1" xml:space="preserve"><value>خانة 1</value></data>
|
||||||
<data name="Check2" xml:space="preserve"><value>خانة 2</value></data>
|
<data name="Check2" xml:space="preserve"><value>خانة 2</value></data>
|
||||||
@@ -76,6 +81,21 @@
|
|||||||
<data name="CheckDesc" xml:space="preserve"><value>قيمة خانة الاختيار (متوافق مع AviUtl: check0-3)</value></data>
|
<data name="CheckDesc" xml:space="preserve"><value>قيمة خانة الاختيار (متوافق مع AviUtl: check0-3)</value></data>
|
||||||
<data name="Color" xml:space="preserve"><value>اللون</value></data>
|
<data name="Color" xml:space="preserve"><value>اللون</value></data>
|
||||||
<data name="ColorDesc" xml:space="preserve"><value>اللون (متوافق مع AviUtl: --color)</value></data>
|
<data name="ColorDesc" xml:space="preserve"><value>اللون (متوافق مع AviUtl: --color)</value></data>
|
||||||
|
<data name="Text" xml:space="preserve"><value>نص</value></data>
|
||||||
|
<data name="TextDesc" xml:space="preserve"><value>إدخال نص (obj.text)</value></data>
|
||||||
|
<data name="Font" xml:space="preserve"><value>خط</value></data>
|
||||||
|
<data name="FontDesc" xml:space="preserve"><value>اختيار الخط (obj.font)</value></data>
|
||||||
|
<data name="Directory" xml:space="preserve"><value>مجلد</value></data>
|
||||||
|
<data name="DirectoryDesc" xml:space="preserve"><value>اختيار المجلد (obj.dir)</value></data>
|
||||||
|
<data name="FileDesc" xml:space="preserve"><value>اختيار الملف (obj.file_*)</value></data>
|
||||||
|
<data name="FileVideo" xml:space="preserve"><value>ملف فيديو</value></data>
|
||||||
|
<data name="FileAudio" xml:space="preserve"><value>ملف صوتي</value></data>
|
||||||
|
<data name="FileImage" xml:space="preserve"><value>ملف صورة</value></data>
|
||||||
|
<data name="FileProject" xml:space="preserve"><value>ملف المشروع</value></data>
|
||||||
|
<data name="FileMp4" xml:space="preserve"><value>ملف MP4</value></data>
|
||||||
|
<data name="FileExo" xml:space="preserve"><value>ملف EXO</value></data>
|
||||||
|
<data name="FileSubtitle" xml:space="preserve"><value>ملف الترجمة</value></data>
|
||||||
|
<data name="FileShader" xml:space="preserve"><value>ملف التظليل</value></data>
|
||||||
<data name="ToolBarImport" xml:space="preserve"><value>استيراد</value></data>
|
<data name="ToolBarImport" xml:space="preserve"><value>استيراد</value></data>
|
||||||
<data name="ToolBarExport" xml:space="preserve"><value>تصدير</value></data>
|
<data name="ToolBarExport" xml:space="preserve"><value>تصدير</value></data>
|
||||||
<data name="ToolBarClear" xml:space="preserve"><value>مسح</value></data>
|
<data name="ToolBarClear" xml:space="preserve"><value>مسح</value></data>
|
||||||
@@ -84,4 +104,7 @@
|
|||||||
<data name="ToolBarImportErrorTitle" xml:space="preserve"><value>خطأ في الاستيراد</value></data>
|
<data name="ToolBarImportErrorTitle" xml:space="preserve"><value>خطأ في الاستيراد</value></data>
|
||||||
<data name="ToolBarExportErrorTitle" xml:space="preserve"><value>خطأ في التصدير</value></data>
|
<data name="ToolBarExportErrorTitle" xml:space="preserve"><value>خطأ في التصدير</value></data>
|
||||||
<data name="LuaFileFilter" xml:space="preserve"><value>نص Lua (*.lua)|*.lua|جميع الملفات (*.*)|*.*</value></data>
|
<data name="LuaFileFilter" xml:space="preserve"><value>نص Lua (*.lua)|*.lua|جميع الملفات (*.*)|*.*</value></data>
|
||||||
|
<data name="DiagnosticCompile" xml:space="preserve"><value>خطأ في بناء الجملة</value></data>
|
||||||
|
<data name="DiagnosticRuntime" xml:space="preserve"><value>خطأ وقت التشغيل</value></data>
|
||||||
|
<data name="DiagnosticTimeout" xml:space="preserve"><value>انتهت المهلة</value></data>
|
||||||
</root>
|
</root>
|
||||||
@@ -9,6 +9,11 @@ Track1,,トラック1,Track 1,轨道1,軌道1,트랙1,Pista 1,مسار 1,Jalur 1
|
|||||||
Track2,,トラック2,Track 2,轨道2,軌道2,트랙2,Pista 2,مسار 2,Jalur 2
|
Track2,,トラック2,Track 2,轨道2,軌道2,트랙2,Pista 2,مسار 2,Jalur 2
|
||||||
Track3,,トラック3,Track 3,轨道3,軌道3,트랙3,Pista 3,مسار 3,Jalur 3
|
Track3,,トラック3,Track 3,轨道3,軌道3,트랙3,Pista 3,مسار 3,Jalur 3
|
||||||
TrackDesc,,スライダー値 (AviUtl準拠 track0〜3 に対応),Slider value (AviUtl compatible: track0–3),滑块值(AviUtl兼容: track0~3),滑塊值(AviUtl兼容: track0~3),슬라이더 값 (AviUtl 호환: track0~3),Valor del deslizador (compatible AviUtl: track0-3),قيمة المنزلق (متوافق مع AviUtl: track0-3),Nilai slider (kompatibel AviUtl: track0-3)
|
TrackDesc,,スライダー値 (AviUtl準拠 track0〜3 に対応),Slider value (AviUtl compatible: track0–3),滑块值(AviUtl兼容: track0~3),滑塊值(AviUtl兼容: track0~3),슬라이더 값 (AviUtl 호환: track0~3),Valor del deslizador (compatible AviUtl: track0-3),قيمة المنزلق (متوافق مع AviUtl: track0-3),Nilai slider (kompatibel AviUtl: track0-3)
|
||||||
|
Slider0,,スライダー0,Slider 0,滑块0,滑塊0,슬라이더0,Deslizador 0,منزلق 0,Slider 0
|
||||||
|
Slider1,,スライダー1,Slider 1,滑块1,滑塊1,슬라이더1,Deslizador 1,منزلق 1,Slider 1
|
||||||
|
Slider2,,スライダー2,Slider 2,滑块2,滑塊2,슬라이더2,Deslizador 2,منزلق 2,Slider 2
|
||||||
|
Slider3,,スライダー3,Slider 3,滑块3,滑塊3,슬라이더3,Deslizador 3,منزلق 3,Slider 3
|
||||||
|
SliderDesc,,数値スライダー (obj.slider0〜3 で参照),Numeric slider (obj.slider0–3),数值滑块 (obj.slider0~3),數值滑塊 (obj.slider0~3),숫자 슬라이더 (obj.slider0~3),Deslizador numérico (obj.slider0-3),منزلق رقمي (obj.slider0-3),Slider numerik (obj.slider0-3)
|
||||||
Check0,,チェック0,Check 0,复选框0,核取方塊0,체크0,Casilla 0,خانة 0,Centang 0
|
Check0,,チェック0,Check 0,复选框0,核取方塊0,체크0,Casilla 0,خانة 0,Centang 0
|
||||||
Check1,,チェック1,Check 1,复选框1,核取方塊1,체크1,Casilla 1,خانة 1,Centang 1
|
Check1,,チェック1,Check 1,复选框1,核取方塊1,체크1,Casilla 1,خانة 1,Centang 1
|
||||||
Check2,,チェック2,Check 2,复选框2,核取方塊2,체크2,Casilla 2,خانة 2,Centang 2
|
Check2,,チェック2,Check 2,复选框2,核取方塊2,체크2,Casilla 2,خانة 2,Centang 2
|
||||||
@@ -16,6 +21,21 @@ Check3,,チェック3,Check 3,复选框3,核取方塊3,체크3,Casilla 3,خان
|
|||||||
CheckDesc,,チェックボックス値 (AviUtl準拠 check0〜3 に対応),Checkbox value (AviUtl compatible: check0–3),复选框值(AviUtl兼容: check0~3),核取方塊值(AviUtl兼容: check0~3),체크박스 값 (AviUtl 호환: check0~3),Valor de casilla (compatible AviUtl: check0-3),قيمة خانة الاختيار (متوافق مع AviUtl: check0-3),Nilai kotak centang (kompatibel AviUtl: check0-3)
|
CheckDesc,,チェックボックス値 (AviUtl準拠 check0〜3 に対応),Checkbox value (AviUtl compatible: check0–3),复选框值(AviUtl兼容: check0~3),核取方塊值(AviUtl兼容: check0~3),체크박스 값 (AviUtl 호환: check0~3),Valor de casilla (compatible AviUtl: check0-3),قيمة خانة الاختيار (متوافق مع AviUtl: check0-3),Nilai kotak centang (kompatibel AviUtl: check0-3)
|
||||||
Color,,色,Color,颜色,顏色,색,Color,اللون,Warna
|
Color,,色,Color,颜色,顏色,색,Color,اللون,Warna
|
||||||
ColorDesc,,色 (AviUtl準拠 --color に対応),Color (AviUtl compatible: --color),颜色(AviUtl兼容: --color),顏色(AviUtl兼容: --color),색 (AviUtl 호환: --color),Color (compatible AviUtl: --color),اللون (متوافق مع AviUtl: --color),Warna (kompatibel AviUtl: --color)
|
ColorDesc,,色 (AviUtl準拠 --color に対応),Color (AviUtl compatible: --color),颜色(AviUtl兼容: --color),顏色(AviUtl兼容: --color),색 (AviUtl 호환: --color),Color (compatible AviUtl: --color),اللون (متوافق مع AviUtl: --color),Warna (kompatibel AviUtl: --color)
|
||||||
|
Text,,テキスト,Text,文本,文字,텍스트,Texto,نص,Teks
|
||||||
|
TextDesc,,テキスト入力 (obj.text で参照),Text input (obj.text),文本输入 (obj.text),文字輸入 (obj.text),텍스트 입력 (obj.text),Entrada de texto (obj.text),إدخال نص (obj.text),Masukan teks (obj.text)
|
||||||
|
Font,,フォント,Font,字体,字型,글꼴,Fuente,خط,Font
|
||||||
|
FontDesc,,フォント選択 (obj.font で参照),Font selection (obj.font),字体选择 (obj.font),字型選擇 (obj.font),글꼴 선택 (obj.font),Selección de fuente (obj.font),اختيار الخط (obj.font),Pilihan font (obj.font)
|
||||||
|
Directory,,フォルダ,Folder,文件夹,資料夾,폴더,Carpeta,مجلد,Folder
|
||||||
|
DirectoryDesc,,フォルダ選択 (obj.dir で参照),Folder selection (obj.dir),文件夹选择 (obj.dir),資料夾選擇 (obj.dir),폴더 선택 (obj.dir),Selección de carpeta (obj.dir),اختيار المجلد (obj.dir),Pilihan folder (obj.dir)
|
||||||
|
FileDesc,,ファイル選択 (obj.file_* で参照),File selection (obj.file_*),文件选择 (obj.file_*),檔案選擇 (obj.file_*),파일 선택 (obj.file_*),Selección de archivo (obj.file_*),اختيار الملف (obj.file_*),Pilihan file (obj.file_*)
|
||||||
|
FileVideo,,動画ファイル,Video File,视频文件,影片檔案,동영상 파일,Archivo de video,ملف فيديو,File Video
|
||||||
|
FileAudio,,音声ファイル,Audio File,音频文件,音訊檔案,음성 파일,Archivo de audio,ملف صوتي,File Audio
|
||||||
|
FileImage,,画像ファイル,Image File,图像文件,圖片檔案,이미지 파일,Archivo de imagen,ملف صورة,File Gambar
|
||||||
|
FileProject,,プロジェクトファイル,Project File,项目文件,專案檔案,프로젝트 파일,Archivo de proyecto,ملف المشروع,File Proyek
|
||||||
|
FileMp4,,MP4ファイル,MP4 File,MP4文件,MP4檔案,MP4 파일,Archivo MP4,ملف MP4,File MP4
|
||||||
|
FileExo,,EXOファイル,EXO File,EXO文件,EXO檔案,EXO 파일,Archivo EXO,ملف EXO,File EXO
|
||||||
|
FileSubtitle,,字幕ファイル,Subtitle File,字幕文件,字幕檔案,자막 파일,Archivo de subtítulos,ملف الترجمة,File Subtitle
|
||||||
|
FileShader,,シェーダーファイル,Shader File,着色器文件,著色器檔案,셰이더 파일,Archivo de sombreador,ملف التظليل,File Shader
|
||||||
ToolBarImport,,インポート,Import,导入,導入,가져오기,Importar,استيراد,Impor
|
ToolBarImport,,インポート,Import,导入,導入,가져오기,Importar,استيراد,Impor
|
||||||
ToolBarExport,,エクスポート,Export,导出,導出,내보내기,Exportar,تصدير,Ekspor
|
ToolBarExport,,エクスポート,Export,导出,導出,내보내기,Exportar,تصدير,Ekspor
|
||||||
ToolBarClear,,クリア,Clear,清除,清除,지우기,Limpiar,مسح,Hapus
|
ToolBarClear,,クリア,Clear,清除,清除,지우기,Limpiar,مسح,Hapus
|
||||||
@@ -24,3 +44,6 @@ ToolBarClearTitle,,確認,Confirm,确认,確認,확인,Confirmar,تأكيد,Konf
|
|||||||
ToolBarImportErrorTitle,,インポートエラー,Import Error,导入错误,導入錯誤,가져오기 오류,Error de importación,خطأ في الاستيراد,Kesalahan impor
|
ToolBarImportErrorTitle,,インポートエラー,Import Error,导入错误,導入錯誤,가져오기 오류,Error de importación,خطأ في الاستيراد,Kesalahan impor
|
||||||
ToolBarExportErrorTitle,,エクスポートエラー,Export Error,导出错误,導出錯誤,내보내기 오류,Error de exportación,خطأ في التصدير,Kesalahan ekspor
|
ToolBarExportErrorTitle,,エクスポートエラー,Export Error,导出错误,導出錯誤,내보내기 오류,Error de exportación,خطأ في التصدير,Kesalahan ekspor
|
||||||
LuaFileFilter,,Luaスクリプト (*.lua)|*.lua|すべてのファイル (*.*)|*.*,Lua Script (*.lua)|*.lua|All Files (*.*)|*.*,Lua脚本 (*.lua)|*.lua|所有文件 (*.*)|*.*,Lua腳本 (*.lua)|*.lua|所有檔案 (*.*)|*.*,Lua 스크립트 (*.lua)|*.lua|모든 파일 (*.*)|*.*,Script Lua (*.lua)|*.lua|Todos los archivos (*.*)|*.*,نص Lua (*.lua)|*.lua|جميع الملفات (*.*)|*.*,Skrip Lua (*.lua)|*.lua|Semua File (*.*)|*.*
|
LuaFileFilter,,Luaスクリプト (*.lua)|*.lua|すべてのファイル (*.*)|*.*,Lua Script (*.lua)|*.lua|All Files (*.*)|*.*,Lua脚本 (*.lua)|*.lua|所有文件 (*.*)|*.*,Lua腳本 (*.lua)|*.lua|所有檔案 (*.*)|*.*,Lua 스크립트 (*.lua)|*.lua|모든 파일 (*.*)|*.*,Script Lua (*.lua)|*.lua|Todos los archivos (*.*)|*.*,نص Lua (*.lua)|*.lua|جميع الملفات (*.*)|*.*,Skrip Lua (*.lua)|*.lua|Semua File (*.*)|*.*
|
||||||
|
DiagnosticCompile,,構文エラー,Syntax error,语法错误,語法錯誤,구문 오류,Error de sintaxis,خطأ في بناء الجملة,Kesalahan sintaksis
|
||||||
|
DiagnosticRuntime,,実行時エラー,Runtime error,运行时错误,執行時錯誤,런타임 오류,Error de ejecución,خطأ وقت التشغيل,Kesalahan runtime
|
||||||
|
DiagnosticTimeout,,タイムアウト,Timed out,执行超时,執行逾時,시간 초과,Tiempo de espera agotado,انتهت المهلة,Waktu habis
|
||||||
|
@@ -69,6 +69,11 @@
|
|||||||
<data name="Track2" xml:space="preserve"><value>Track 2</value></data>
|
<data name="Track2" xml:space="preserve"><value>Track 2</value></data>
|
||||||
<data name="Track3" xml:space="preserve"><value>Track 3</value></data>
|
<data name="Track3" xml:space="preserve"><value>Track 3</value></data>
|
||||||
<data name="TrackDesc" xml:space="preserve"><value>Slider value (AviUtl compatible: track0–3)</value></data>
|
<data name="TrackDesc" xml:space="preserve"><value>Slider value (AviUtl compatible: track0–3)</value></data>
|
||||||
|
<data name="Slider0" xml:space="preserve"><value>Slider 0</value></data>
|
||||||
|
<data name="Slider1" xml:space="preserve"><value>Slider 1</value></data>
|
||||||
|
<data name="Slider2" xml:space="preserve"><value>Slider 2</value></data>
|
||||||
|
<data name="Slider3" xml:space="preserve"><value>Slider 3</value></data>
|
||||||
|
<data name="SliderDesc" xml:space="preserve"><value>Numeric slider (obj.slider0–3)</value></data>
|
||||||
<data name="Check0" xml:space="preserve"><value>Check 0</value></data>
|
<data name="Check0" xml:space="preserve"><value>Check 0</value></data>
|
||||||
<data name="Check1" xml:space="preserve"><value>Check 1</value></data>
|
<data name="Check1" xml:space="preserve"><value>Check 1</value></data>
|
||||||
<data name="Check2" xml:space="preserve"><value>Check 2</value></data>
|
<data name="Check2" xml:space="preserve"><value>Check 2</value></data>
|
||||||
@@ -76,6 +81,21 @@
|
|||||||
<data name="CheckDesc" xml:space="preserve"><value>Checkbox value (AviUtl compatible: check0–3)</value></data>
|
<data name="CheckDesc" xml:space="preserve"><value>Checkbox value (AviUtl compatible: check0–3)</value></data>
|
||||||
<data name="Color" xml:space="preserve"><value>Color</value></data>
|
<data name="Color" xml:space="preserve"><value>Color</value></data>
|
||||||
<data name="ColorDesc" xml:space="preserve"><value>Color (AviUtl compatible: --color)</value></data>
|
<data name="ColorDesc" xml:space="preserve"><value>Color (AviUtl compatible: --color)</value></data>
|
||||||
|
<data name="Text" xml:space="preserve"><value>Text</value></data>
|
||||||
|
<data name="TextDesc" xml:space="preserve"><value>Text input (obj.text)</value></data>
|
||||||
|
<data name="Font" xml:space="preserve"><value>Font</value></data>
|
||||||
|
<data name="FontDesc" xml:space="preserve"><value>Font selection (obj.font)</value></data>
|
||||||
|
<data name="Directory" xml:space="preserve"><value>Folder</value></data>
|
||||||
|
<data name="DirectoryDesc" xml:space="preserve"><value>Folder selection (obj.dir)</value></data>
|
||||||
|
<data name="FileDesc" xml:space="preserve"><value>File selection (obj.file_*)</value></data>
|
||||||
|
<data name="FileVideo" xml:space="preserve"><value>Video File</value></data>
|
||||||
|
<data name="FileAudio" xml:space="preserve"><value>Audio File</value></data>
|
||||||
|
<data name="FileImage" xml:space="preserve"><value>Image File</value></data>
|
||||||
|
<data name="FileProject" xml:space="preserve"><value>Project File</value></data>
|
||||||
|
<data name="FileMp4" xml:space="preserve"><value>MP4 File</value></data>
|
||||||
|
<data name="FileExo" xml:space="preserve"><value>EXO File</value></data>
|
||||||
|
<data name="FileSubtitle" xml:space="preserve"><value>Subtitle File</value></data>
|
||||||
|
<data name="FileShader" xml:space="preserve"><value>Shader File</value></data>
|
||||||
<data name="ToolBarImport" xml:space="preserve"><value>Import</value></data>
|
<data name="ToolBarImport" xml:space="preserve"><value>Import</value></data>
|
||||||
<data name="ToolBarExport" xml:space="preserve"><value>Export</value></data>
|
<data name="ToolBarExport" xml:space="preserve"><value>Export</value></data>
|
||||||
<data name="ToolBarClear" xml:space="preserve"><value>Clear</value></data>
|
<data name="ToolBarClear" xml:space="preserve"><value>Clear</value></data>
|
||||||
@@ -84,4 +104,7 @@
|
|||||||
<data name="ToolBarImportErrorTitle" xml:space="preserve"><value>Import Error</value></data>
|
<data name="ToolBarImportErrorTitle" xml:space="preserve"><value>Import Error</value></data>
|
||||||
<data name="ToolBarExportErrorTitle" xml:space="preserve"><value>Export Error</value></data>
|
<data name="ToolBarExportErrorTitle" xml:space="preserve"><value>Export Error</value></data>
|
||||||
<data name="LuaFileFilter" xml:space="preserve"><value>Lua Script (*.lua)|*.lua|All Files (*.*)|*.*</value></data>
|
<data name="LuaFileFilter" xml:space="preserve"><value>Lua Script (*.lua)|*.lua|All Files (*.*)|*.*</value></data>
|
||||||
|
<data name="DiagnosticCompile" xml:space="preserve"><value>Syntax error</value></data>
|
||||||
|
<data name="DiagnosticRuntime" xml:space="preserve"><value>Runtime error</value></data>
|
||||||
|
<data name="DiagnosticTimeout" xml:space="preserve"><value>Timed out</value></data>
|
||||||
</root>
|
</root>
|
||||||
@@ -69,6 +69,11 @@
|
|||||||
<data name="Track2" xml:space="preserve"><value>Pista 2</value></data>
|
<data name="Track2" xml:space="preserve"><value>Pista 2</value></data>
|
||||||
<data name="Track3" xml:space="preserve"><value>Pista 3</value></data>
|
<data name="Track3" xml:space="preserve"><value>Pista 3</value></data>
|
||||||
<data name="TrackDesc" xml:space="preserve"><value>Valor del deslizador (compatible AviUtl: track0-3)</value></data>
|
<data name="TrackDesc" xml:space="preserve"><value>Valor del deslizador (compatible AviUtl: track0-3)</value></data>
|
||||||
|
<data name="Slider0" xml:space="preserve"><value>Deslizador 0</value></data>
|
||||||
|
<data name="Slider1" xml:space="preserve"><value>Deslizador 1</value></data>
|
||||||
|
<data name="Slider2" xml:space="preserve"><value>Deslizador 2</value></data>
|
||||||
|
<data name="Slider3" xml:space="preserve"><value>Deslizador 3</value></data>
|
||||||
|
<data name="SliderDesc" xml:space="preserve"><value>Deslizador numérico (obj.slider0-3)</value></data>
|
||||||
<data name="Check0" xml:space="preserve"><value>Casilla 0</value></data>
|
<data name="Check0" xml:space="preserve"><value>Casilla 0</value></data>
|
||||||
<data name="Check1" xml:space="preserve"><value>Casilla 1</value></data>
|
<data name="Check1" xml:space="preserve"><value>Casilla 1</value></data>
|
||||||
<data name="Check2" xml:space="preserve"><value>Casilla 2</value></data>
|
<data name="Check2" xml:space="preserve"><value>Casilla 2</value></data>
|
||||||
@@ -76,6 +81,21 @@
|
|||||||
<data name="CheckDesc" xml:space="preserve"><value>Valor de casilla (compatible AviUtl: check0-3)</value></data>
|
<data name="CheckDesc" xml:space="preserve"><value>Valor de casilla (compatible AviUtl: check0-3)</value></data>
|
||||||
<data name="Color" xml:space="preserve"><value>Color</value></data>
|
<data name="Color" xml:space="preserve"><value>Color</value></data>
|
||||||
<data name="ColorDesc" xml:space="preserve"><value>Color (compatible AviUtl: --color)</value></data>
|
<data name="ColorDesc" xml:space="preserve"><value>Color (compatible AviUtl: --color)</value></data>
|
||||||
|
<data name="Text" xml:space="preserve"><value>Texto</value></data>
|
||||||
|
<data name="TextDesc" xml:space="preserve"><value>Entrada de texto (obj.text)</value></data>
|
||||||
|
<data name="Font" xml:space="preserve"><value>Fuente</value></data>
|
||||||
|
<data name="FontDesc" xml:space="preserve"><value>Selección de fuente (obj.font)</value></data>
|
||||||
|
<data name="Directory" xml:space="preserve"><value>Carpeta</value></data>
|
||||||
|
<data name="DirectoryDesc" xml:space="preserve"><value>Selección de carpeta (obj.dir)</value></data>
|
||||||
|
<data name="FileDesc" xml:space="preserve"><value>Selección de archivo (obj.file_*)</value></data>
|
||||||
|
<data name="FileVideo" xml:space="preserve"><value>Archivo de video</value></data>
|
||||||
|
<data name="FileAudio" xml:space="preserve"><value>Archivo de audio</value></data>
|
||||||
|
<data name="FileImage" xml:space="preserve"><value>Archivo de imagen</value></data>
|
||||||
|
<data name="FileProject" xml:space="preserve"><value>Archivo de proyecto</value></data>
|
||||||
|
<data name="FileMp4" xml:space="preserve"><value>Archivo MP4</value></data>
|
||||||
|
<data name="FileExo" xml:space="preserve"><value>Archivo EXO</value></data>
|
||||||
|
<data name="FileSubtitle" xml:space="preserve"><value>Archivo de subtítulos</value></data>
|
||||||
|
<data name="FileShader" xml:space="preserve"><value>Archivo de sombreador</value></data>
|
||||||
<data name="ToolBarImport" xml:space="preserve"><value>Importar</value></data>
|
<data name="ToolBarImport" xml:space="preserve"><value>Importar</value></data>
|
||||||
<data name="ToolBarExport" xml:space="preserve"><value>Exportar</value></data>
|
<data name="ToolBarExport" xml:space="preserve"><value>Exportar</value></data>
|
||||||
<data name="ToolBarClear" xml:space="preserve"><value>Limpiar</value></data>
|
<data name="ToolBarClear" xml:space="preserve"><value>Limpiar</value></data>
|
||||||
@@ -84,4 +104,7 @@
|
|||||||
<data name="ToolBarImportErrorTitle" xml:space="preserve"><value>Error de importación</value></data>
|
<data name="ToolBarImportErrorTitle" xml:space="preserve"><value>Error de importación</value></data>
|
||||||
<data name="ToolBarExportErrorTitle" xml:space="preserve"><value>Error de exportación</value></data>
|
<data name="ToolBarExportErrorTitle" xml:space="preserve"><value>Error de exportación</value></data>
|
||||||
<data name="LuaFileFilter" xml:space="preserve"><value>Script Lua (*.lua)|*.lua|Todos los archivos (*.*)|*.*</value></data>
|
<data name="LuaFileFilter" xml:space="preserve"><value>Script Lua (*.lua)|*.lua|Todos los archivos (*.*)|*.*</value></data>
|
||||||
|
<data name="DiagnosticCompile" xml:space="preserve"><value>Error de sintaxis</value></data>
|
||||||
|
<data name="DiagnosticRuntime" xml:space="preserve"><value>Error de ejecución</value></data>
|
||||||
|
<data name="DiagnosticTimeout" xml:space="preserve"><value>Tiempo de espera agotado</value></data>
|
||||||
</root>
|
</root>
|
||||||
@@ -69,6 +69,11 @@
|
|||||||
<data name="Track2" xml:space="preserve"><value>Jalur 2</value></data>
|
<data name="Track2" xml:space="preserve"><value>Jalur 2</value></data>
|
||||||
<data name="Track3" xml:space="preserve"><value>Jalur 3</value></data>
|
<data name="Track3" xml:space="preserve"><value>Jalur 3</value></data>
|
||||||
<data name="TrackDesc" xml:space="preserve"><value>Nilai slider (kompatibel AviUtl: track0-3)</value></data>
|
<data name="TrackDesc" xml:space="preserve"><value>Nilai slider (kompatibel AviUtl: track0-3)</value></data>
|
||||||
|
<data name="Slider0" xml:space="preserve"><value>Slider 0</value></data>
|
||||||
|
<data name="Slider1" xml:space="preserve"><value>Slider 1</value></data>
|
||||||
|
<data name="Slider2" xml:space="preserve"><value>Slider 2</value></data>
|
||||||
|
<data name="Slider3" xml:space="preserve"><value>Slider 3</value></data>
|
||||||
|
<data name="SliderDesc" xml:space="preserve"><value>Slider numerik (obj.slider0-3)</value></data>
|
||||||
<data name="Check0" xml:space="preserve"><value>Centang 0</value></data>
|
<data name="Check0" xml:space="preserve"><value>Centang 0</value></data>
|
||||||
<data name="Check1" xml:space="preserve"><value>Centang 1</value></data>
|
<data name="Check1" xml:space="preserve"><value>Centang 1</value></data>
|
||||||
<data name="Check2" xml:space="preserve"><value>Centang 2</value></data>
|
<data name="Check2" xml:space="preserve"><value>Centang 2</value></data>
|
||||||
@@ -76,6 +81,21 @@
|
|||||||
<data name="CheckDesc" xml:space="preserve"><value>Nilai kotak centang (kompatibel AviUtl: check0-3)</value></data>
|
<data name="CheckDesc" xml:space="preserve"><value>Nilai kotak centang (kompatibel AviUtl: check0-3)</value></data>
|
||||||
<data name="Color" xml:space="preserve"><value>Warna</value></data>
|
<data name="Color" xml:space="preserve"><value>Warna</value></data>
|
||||||
<data name="ColorDesc" xml:space="preserve"><value>Warna (kompatibel AviUtl: --color)</value></data>
|
<data name="ColorDesc" xml:space="preserve"><value>Warna (kompatibel AviUtl: --color)</value></data>
|
||||||
|
<data name="Text" xml:space="preserve"><value>Teks</value></data>
|
||||||
|
<data name="TextDesc" xml:space="preserve"><value>Masukan teks (obj.text)</value></data>
|
||||||
|
<data name="Font" xml:space="preserve"><value>Font</value></data>
|
||||||
|
<data name="FontDesc" xml:space="preserve"><value>Pilihan font (obj.font)</value></data>
|
||||||
|
<data name="Directory" xml:space="preserve"><value>Folder</value></data>
|
||||||
|
<data name="DirectoryDesc" xml:space="preserve"><value>Pilihan folder (obj.dir)</value></data>
|
||||||
|
<data name="FileDesc" xml:space="preserve"><value>Pilihan file (obj.file_*)</value></data>
|
||||||
|
<data name="FileVideo" xml:space="preserve"><value>File Video</value></data>
|
||||||
|
<data name="FileAudio" xml:space="preserve"><value>File Audio</value></data>
|
||||||
|
<data name="FileImage" xml:space="preserve"><value>File Gambar</value></data>
|
||||||
|
<data name="FileProject" xml:space="preserve"><value>File Proyek</value></data>
|
||||||
|
<data name="FileMp4" xml:space="preserve"><value>File MP4</value></data>
|
||||||
|
<data name="FileExo" xml:space="preserve"><value>File EXO</value></data>
|
||||||
|
<data name="FileSubtitle" xml:space="preserve"><value>File Subtitle</value></data>
|
||||||
|
<data name="FileShader" xml:space="preserve"><value>File Shader</value></data>
|
||||||
<data name="ToolBarImport" xml:space="preserve"><value>Impor</value></data>
|
<data name="ToolBarImport" xml:space="preserve"><value>Impor</value></data>
|
||||||
<data name="ToolBarExport" xml:space="preserve"><value>Ekspor</value></data>
|
<data name="ToolBarExport" xml:space="preserve"><value>Ekspor</value></data>
|
||||||
<data name="ToolBarClear" xml:space="preserve"><value>Hapus</value></data>
|
<data name="ToolBarClear" xml:space="preserve"><value>Hapus</value></data>
|
||||||
@@ -84,4 +104,7 @@
|
|||||||
<data name="ToolBarImportErrorTitle" xml:space="preserve"><value>Kesalahan impor</value></data>
|
<data name="ToolBarImportErrorTitle" xml:space="preserve"><value>Kesalahan impor</value></data>
|
||||||
<data name="ToolBarExportErrorTitle" xml:space="preserve"><value>Kesalahan ekspor</value></data>
|
<data name="ToolBarExportErrorTitle" xml:space="preserve"><value>Kesalahan ekspor</value></data>
|
||||||
<data name="LuaFileFilter" xml:space="preserve"><value>Skrip Lua (*.lua)|*.lua|Semua File (*.*)|*.*</value></data>
|
<data name="LuaFileFilter" xml:space="preserve"><value>Skrip Lua (*.lua)|*.lua|Semua File (*.*)|*.*</value></data>
|
||||||
|
<data name="DiagnosticCompile" xml:space="preserve"><value>Kesalahan sintaksis</value></data>
|
||||||
|
<data name="DiagnosticRuntime" xml:space="preserve"><value>Kesalahan runtime</value></data>
|
||||||
|
<data name="DiagnosticTimeout" xml:space="preserve"><value>Waktu habis</value></data>
|
||||||
</root>
|
</root>
|
||||||
@@ -69,6 +69,11 @@
|
|||||||
<data name="Track2" xml:space="preserve"><value>트랙2</value></data>
|
<data name="Track2" xml:space="preserve"><value>트랙2</value></data>
|
||||||
<data name="Track3" xml:space="preserve"><value>트랙3</value></data>
|
<data name="Track3" xml:space="preserve"><value>트랙3</value></data>
|
||||||
<data name="TrackDesc" xml:space="preserve"><value>슬라이더 값 (AviUtl 호환: track0~3)</value></data>
|
<data name="TrackDesc" xml:space="preserve"><value>슬라이더 값 (AviUtl 호환: track0~3)</value></data>
|
||||||
|
<data name="Slider0" xml:space="preserve"><value>슬라이더0</value></data>
|
||||||
|
<data name="Slider1" xml:space="preserve"><value>슬라이더1</value></data>
|
||||||
|
<data name="Slider2" xml:space="preserve"><value>슬라이더2</value></data>
|
||||||
|
<data name="Slider3" xml:space="preserve"><value>슬라이더3</value></data>
|
||||||
|
<data name="SliderDesc" xml:space="preserve"><value>숫자 슬라이더 (obj.slider0~3)</value></data>
|
||||||
<data name="Check0" xml:space="preserve"><value>체크0</value></data>
|
<data name="Check0" xml:space="preserve"><value>체크0</value></data>
|
||||||
<data name="Check1" xml:space="preserve"><value>체크1</value></data>
|
<data name="Check1" xml:space="preserve"><value>체크1</value></data>
|
||||||
<data name="Check2" xml:space="preserve"><value>체크2</value></data>
|
<data name="Check2" xml:space="preserve"><value>체크2</value></data>
|
||||||
@@ -76,6 +81,21 @@
|
|||||||
<data name="CheckDesc" xml:space="preserve"><value>체크박스 값 (AviUtl 호환: check0~3)</value></data>
|
<data name="CheckDesc" xml:space="preserve"><value>체크박스 값 (AviUtl 호환: check0~3)</value></data>
|
||||||
<data name="Color" xml:space="preserve"><value>색</value></data>
|
<data name="Color" xml:space="preserve"><value>색</value></data>
|
||||||
<data name="ColorDesc" xml:space="preserve"><value>색 (AviUtl 호환: --color)</value></data>
|
<data name="ColorDesc" xml:space="preserve"><value>색 (AviUtl 호환: --color)</value></data>
|
||||||
|
<data name="Text" xml:space="preserve"><value>텍스트</value></data>
|
||||||
|
<data name="TextDesc" xml:space="preserve"><value>텍스트 입력 (obj.text)</value></data>
|
||||||
|
<data name="Font" xml:space="preserve"><value>글꼴</value></data>
|
||||||
|
<data name="FontDesc" xml:space="preserve"><value>글꼴 선택 (obj.font)</value></data>
|
||||||
|
<data name="Directory" xml:space="preserve"><value>폴더</value></data>
|
||||||
|
<data name="DirectoryDesc" xml:space="preserve"><value>폴더 선택 (obj.dir)</value></data>
|
||||||
|
<data name="FileDesc" xml:space="preserve"><value>파일 선택 (obj.file_*)</value></data>
|
||||||
|
<data name="FileVideo" xml:space="preserve"><value>동영상 파일</value></data>
|
||||||
|
<data name="FileAudio" xml:space="preserve"><value>음성 파일</value></data>
|
||||||
|
<data name="FileImage" xml:space="preserve"><value>이미지 파일</value></data>
|
||||||
|
<data name="FileProject" xml:space="preserve"><value>프로젝트 파일</value></data>
|
||||||
|
<data name="FileMp4" xml:space="preserve"><value>MP4 파일</value></data>
|
||||||
|
<data name="FileExo" xml:space="preserve"><value>EXO 파일</value></data>
|
||||||
|
<data name="FileSubtitle" xml:space="preserve"><value>자막 파일</value></data>
|
||||||
|
<data name="FileShader" xml:space="preserve"><value>셰이더 파일</value></data>
|
||||||
<data name="ToolBarImport" xml:space="preserve"><value>가져오기</value></data>
|
<data name="ToolBarImport" xml:space="preserve"><value>가져오기</value></data>
|
||||||
<data name="ToolBarExport" xml:space="preserve"><value>내보내기</value></data>
|
<data name="ToolBarExport" xml:space="preserve"><value>내보내기</value></data>
|
||||||
<data name="ToolBarClear" xml:space="preserve"><value>지우기</value></data>
|
<data name="ToolBarClear" xml:space="preserve"><value>지우기</value></data>
|
||||||
@@ -84,4 +104,7 @@
|
|||||||
<data name="ToolBarImportErrorTitle" xml:space="preserve"><value>가져오기 오류</value></data>
|
<data name="ToolBarImportErrorTitle" xml:space="preserve"><value>가져오기 오류</value></data>
|
||||||
<data name="ToolBarExportErrorTitle" xml:space="preserve"><value>내보내기 오류</value></data>
|
<data name="ToolBarExportErrorTitle" xml:space="preserve"><value>내보내기 오류</value></data>
|
||||||
<data name="LuaFileFilter" xml:space="preserve"><value>Lua 스크립트 (*.lua)|*.lua|모든 파일 (*.*)|*.*</value></data>
|
<data name="LuaFileFilter" xml:space="preserve"><value>Lua 스크립트 (*.lua)|*.lua|모든 파일 (*.*)|*.*</value></data>
|
||||||
|
<data name="DiagnosticCompile" xml:space="preserve"><value>구문 오류</value></data>
|
||||||
|
<data name="DiagnosticRuntime" xml:space="preserve"><value>런타임 오류</value></data>
|
||||||
|
<data name="DiagnosticTimeout" xml:space="preserve"><value>시간 초과</value></data>
|
||||||
</root>
|
</root>
|
||||||
@@ -69,6 +69,11 @@
|
|||||||
<data name="Track2" xml:space="preserve"><value>トラック2</value></data>
|
<data name="Track2" xml:space="preserve"><value>トラック2</value></data>
|
||||||
<data name="Track3" xml:space="preserve"><value>トラック3</value></data>
|
<data name="Track3" xml:space="preserve"><value>トラック3</value></data>
|
||||||
<data name="TrackDesc" xml:space="preserve"><value>スライダー値 (AviUtl準拠 track0〜3 に対応)</value></data>
|
<data name="TrackDesc" xml:space="preserve"><value>スライダー値 (AviUtl準拠 track0〜3 に対応)</value></data>
|
||||||
|
<data name="Slider0" xml:space="preserve"><value>スライダー0</value></data>
|
||||||
|
<data name="Slider1" xml:space="preserve"><value>スライダー1</value></data>
|
||||||
|
<data name="Slider2" xml:space="preserve"><value>スライダー2</value></data>
|
||||||
|
<data name="Slider3" xml:space="preserve"><value>スライダー3</value></data>
|
||||||
|
<data name="SliderDesc" xml:space="preserve"><value>数値スライダー (obj.slider0〜3 で参照)</value></data>
|
||||||
<data name="Check0" xml:space="preserve"><value>チェック0</value></data>
|
<data name="Check0" xml:space="preserve"><value>チェック0</value></data>
|
||||||
<data name="Check1" xml:space="preserve"><value>チェック1</value></data>
|
<data name="Check1" xml:space="preserve"><value>チェック1</value></data>
|
||||||
<data name="Check2" xml:space="preserve"><value>チェック2</value></data>
|
<data name="Check2" xml:space="preserve"><value>チェック2</value></data>
|
||||||
@@ -76,6 +81,21 @@
|
|||||||
<data name="CheckDesc" xml:space="preserve"><value>チェックボックス値 (AviUtl準拠 check0〜3 に対応)</value></data>
|
<data name="CheckDesc" xml:space="preserve"><value>チェックボックス値 (AviUtl準拠 check0〜3 に対応)</value></data>
|
||||||
<data name="Color" xml:space="preserve"><value>色</value></data>
|
<data name="Color" xml:space="preserve"><value>色</value></data>
|
||||||
<data name="ColorDesc" xml:space="preserve"><value>色 (AviUtl準拠 --color に対応)</value></data>
|
<data name="ColorDesc" xml:space="preserve"><value>色 (AviUtl準拠 --color に対応)</value></data>
|
||||||
|
<data name="Text" xml:space="preserve"><value>テキスト</value></data>
|
||||||
|
<data name="TextDesc" xml:space="preserve"><value>テキスト入力 (obj.text で参照)</value></data>
|
||||||
|
<data name="Font" xml:space="preserve"><value>フォント</value></data>
|
||||||
|
<data name="FontDesc" xml:space="preserve"><value>フォント選択 (obj.font で参照)</value></data>
|
||||||
|
<data name="Directory" xml:space="preserve"><value>フォルダ</value></data>
|
||||||
|
<data name="DirectoryDesc" xml:space="preserve"><value>フォルダ選択 (obj.dir で参照)</value></data>
|
||||||
|
<data name="FileDesc" xml:space="preserve"><value>ファイル選択 (obj.file_* で参照)</value></data>
|
||||||
|
<data name="FileVideo" xml:space="preserve"><value>動画ファイル</value></data>
|
||||||
|
<data name="FileAudio" xml:space="preserve"><value>音声ファイル</value></data>
|
||||||
|
<data name="FileImage" xml:space="preserve"><value>画像ファイル</value></data>
|
||||||
|
<data name="FileProject" xml:space="preserve"><value>プロジェクトファイル</value></data>
|
||||||
|
<data name="FileMp4" xml:space="preserve"><value>MP4ファイル</value></data>
|
||||||
|
<data name="FileExo" xml:space="preserve"><value>EXOファイル</value></data>
|
||||||
|
<data name="FileSubtitle" xml:space="preserve"><value>字幕ファイル</value></data>
|
||||||
|
<data name="FileShader" xml:space="preserve"><value>シェーダーファイル</value></data>
|
||||||
<data name="ToolBarImport" xml:space="preserve"><value>インポート</value></data>
|
<data name="ToolBarImport" xml:space="preserve"><value>インポート</value></data>
|
||||||
<data name="ToolBarExport" xml:space="preserve"><value>エクスポート</value></data>
|
<data name="ToolBarExport" xml:space="preserve"><value>エクスポート</value></data>
|
||||||
<data name="ToolBarClear" xml:space="preserve"><value>クリア</value></data>
|
<data name="ToolBarClear" xml:space="preserve"><value>クリア</value></data>
|
||||||
@@ -84,4 +104,7 @@
|
|||||||
<data name="ToolBarImportErrorTitle" xml:space="preserve"><value>インポートエラー</value></data>
|
<data name="ToolBarImportErrorTitle" xml:space="preserve"><value>インポートエラー</value></data>
|
||||||
<data name="ToolBarExportErrorTitle" xml:space="preserve"><value>エクスポートエラー</value></data>
|
<data name="ToolBarExportErrorTitle" xml:space="preserve"><value>エクスポートエラー</value></data>
|
||||||
<data name="LuaFileFilter" xml:space="preserve"><value>Luaスクリプト (*.lua)|*.lua|すべてのファイル (*.*)|*.*</value></data>
|
<data name="LuaFileFilter" xml:space="preserve"><value>Luaスクリプト (*.lua)|*.lua|すべてのファイル (*.*)|*.*</value></data>
|
||||||
|
<data name="DiagnosticCompile" xml:space="preserve"><value>構文エラー</value></data>
|
||||||
|
<data name="DiagnosticRuntime" xml:space="preserve"><value>実行時エラー</value></data>
|
||||||
|
<data name="DiagnosticTimeout" xml:space="preserve"><value>タイムアウト</value></data>
|
||||||
</root>
|
</root>
|
||||||
@@ -69,6 +69,11 @@
|
|||||||
<data name="Track2" xml:space="preserve"><value>轨道2</value></data>
|
<data name="Track2" xml:space="preserve"><value>轨道2</value></data>
|
||||||
<data name="Track3" xml:space="preserve"><value>轨道3</value></data>
|
<data name="Track3" xml:space="preserve"><value>轨道3</value></data>
|
||||||
<data name="TrackDesc" xml:space="preserve"><value>滑块值(AviUtl兼容: track0~3)</value></data>
|
<data name="TrackDesc" xml:space="preserve"><value>滑块值(AviUtl兼容: track0~3)</value></data>
|
||||||
|
<data name="Slider0" xml:space="preserve"><value>滑块0</value></data>
|
||||||
|
<data name="Slider1" xml:space="preserve"><value>滑块1</value></data>
|
||||||
|
<data name="Slider2" xml:space="preserve"><value>滑块2</value></data>
|
||||||
|
<data name="Slider3" xml:space="preserve"><value>滑块3</value></data>
|
||||||
|
<data name="SliderDesc" xml:space="preserve"><value>数值滑块 (obj.slider0~3)</value></data>
|
||||||
<data name="Check0" xml:space="preserve"><value>复选框0</value></data>
|
<data name="Check0" xml:space="preserve"><value>复选框0</value></data>
|
||||||
<data name="Check1" xml:space="preserve"><value>复选框1</value></data>
|
<data name="Check1" xml:space="preserve"><value>复选框1</value></data>
|
||||||
<data name="Check2" xml:space="preserve"><value>复选框2</value></data>
|
<data name="Check2" xml:space="preserve"><value>复选框2</value></data>
|
||||||
@@ -76,6 +81,21 @@
|
|||||||
<data name="CheckDesc" xml:space="preserve"><value>复选框值(AviUtl兼容: check0~3)</value></data>
|
<data name="CheckDesc" xml:space="preserve"><value>复选框值(AviUtl兼容: check0~3)</value></data>
|
||||||
<data name="Color" xml:space="preserve"><value>颜色</value></data>
|
<data name="Color" xml:space="preserve"><value>颜色</value></data>
|
||||||
<data name="ColorDesc" xml:space="preserve"><value>颜色(AviUtl兼容: --color)</value></data>
|
<data name="ColorDesc" xml:space="preserve"><value>颜色(AviUtl兼容: --color)</value></data>
|
||||||
|
<data name="Text" xml:space="preserve"><value>文本</value></data>
|
||||||
|
<data name="TextDesc" xml:space="preserve"><value>文本输入 (obj.text)</value></data>
|
||||||
|
<data name="Font" xml:space="preserve"><value>字体</value></data>
|
||||||
|
<data name="FontDesc" xml:space="preserve"><value>字体选择 (obj.font)</value></data>
|
||||||
|
<data name="Directory" xml:space="preserve"><value>文件夹</value></data>
|
||||||
|
<data name="DirectoryDesc" xml:space="preserve"><value>文件夹选择 (obj.dir)</value></data>
|
||||||
|
<data name="FileDesc" xml:space="preserve"><value>文件选择 (obj.file_*)</value></data>
|
||||||
|
<data name="FileVideo" xml:space="preserve"><value>视频文件</value></data>
|
||||||
|
<data name="FileAudio" xml:space="preserve"><value>音频文件</value></data>
|
||||||
|
<data name="FileImage" xml:space="preserve"><value>图像文件</value></data>
|
||||||
|
<data name="FileProject" xml:space="preserve"><value>项目文件</value></data>
|
||||||
|
<data name="FileMp4" xml:space="preserve"><value>MP4文件</value></data>
|
||||||
|
<data name="FileExo" xml:space="preserve"><value>EXO文件</value></data>
|
||||||
|
<data name="FileSubtitle" xml:space="preserve"><value>字幕文件</value></data>
|
||||||
|
<data name="FileShader" xml:space="preserve"><value>着色器文件</value></data>
|
||||||
<data name="ToolBarImport" xml:space="preserve"><value>导入</value></data>
|
<data name="ToolBarImport" xml:space="preserve"><value>导入</value></data>
|
||||||
<data name="ToolBarExport" xml:space="preserve"><value>导出</value></data>
|
<data name="ToolBarExport" xml:space="preserve"><value>导出</value></data>
|
||||||
<data name="ToolBarClear" xml:space="preserve"><value>清除</value></data>
|
<data name="ToolBarClear" xml:space="preserve"><value>清除</value></data>
|
||||||
@@ -84,4 +104,7 @@
|
|||||||
<data name="ToolBarImportErrorTitle" xml:space="preserve"><value>导入错误</value></data>
|
<data name="ToolBarImportErrorTitle" xml:space="preserve"><value>导入错误</value></data>
|
||||||
<data name="ToolBarExportErrorTitle" xml:space="preserve"><value>导出错误</value></data>
|
<data name="ToolBarExportErrorTitle" xml:space="preserve"><value>导出错误</value></data>
|
||||||
<data name="LuaFileFilter" xml:space="preserve"><value>Lua脚本 (*.lua)|*.lua|所有文件 (*.*)|*.*</value></data>
|
<data name="LuaFileFilter" xml:space="preserve"><value>Lua脚本 (*.lua)|*.lua|所有文件 (*.*)|*.*</value></data>
|
||||||
|
<data name="DiagnosticCompile" xml:space="preserve"><value>语法错误</value></data>
|
||||||
|
<data name="DiagnosticRuntime" xml:space="preserve"><value>运行时错误</value></data>
|
||||||
|
<data name="DiagnosticTimeout" xml:space="preserve"><value>执行超时</value></data>
|
||||||
</root>
|
</root>
|
||||||
@@ -69,6 +69,11 @@
|
|||||||
<data name="Track2" xml:space="preserve"><value>軌道2</value></data>
|
<data name="Track2" xml:space="preserve"><value>軌道2</value></data>
|
||||||
<data name="Track3" xml:space="preserve"><value>軌道3</value></data>
|
<data name="Track3" xml:space="preserve"><value>軌道3</value></data>
|
||||||
<data name="TrackDesc" xml:space="preserve"><value>滑塊值(AviUtl兼容: track0~3)</value></data>
|
<data name="TrackDesc" xml:space="preserve"><value>滑塊值(AviUtl兼容: track0~3)</value></data>
|
||||||
|
<data name="Slider0" xml:space="preserve"><value>滑塊0</value></data>
|
||||||
|
<data name="Slider1" xml:space="preserve"><value>滑塊1</value></data>
|
||||||
|
<data name="Slider2" xml:space="preserve"><value>滑塊2</value></data>
|
||||||
|
<data name="Slider3" xml:space="preserve"><value>滑塊3</value></data>
|
||||||
|
<data name="SliderDesc" xml:space="preserve"><value>數值滑塊 (obj.slider0~3)</value></data>
|
||||||
<data name="Check0" xml:space="preserve"><value>核取方塊0</value></data>
|
<data name="Check0" xml:space="preserve"><value>核取方塊0</value></data>
|
||||||
<data name="Check1" xml:space="preserve"><value>核取方塊1</value></data>
|
<data name="Check1" xml:space="preserve"><value>核取方塊1</value></data>
|
||||||
<data name="Check2" xml:space="preserve"><value>核取方塊2</value></data>
|
<data name="Check2" xml:space="preserve"><value>核取方塊2</value></data>
|
||||||
@@ -76,6 +81,21 @@
|
|||||||
<data name="CheckDesc" xml:space="preserve"><value>核取方塊值(AviUtl兼容: check0~3)</value></data>
|
<data name="CheckDesc" xml:space="preserve"><value>核取方塊值(AviUtl兼容: check0~3)</value></data>
|
||||||
<data name="Color" xml:space="preserve"><value>顏色</value></data>
|
<data name="Color" xml:space="preserve"><value>顏色</value></data>
|
||||||
<data name="ColorDesc" xml:space="preserve"><value>顏色(AviUtl兼容: --color)</value></data>
|
<data name="ColorDesc" xml:space="preserve"><value>顏色(AviUtl兼容: --color)</value></data>
|
||||||
|
<data name="Text" xml:space="preserve"><value>文字</value></data>
|
||||||
|
<data name="TextDesc" xml:space="preserve"><value>文字輸入 (obj.text)</value></data>
|
||||||
|
<data name="Font" xml:space="preserve"><value>字型</value></data>
|
||||||
|
<data name="FontDesc" xml:space="preserve"><value>字型選擇 (obj.font)</value></data>
|
||||||
|
<data name="Directory" xml:space="preserve"><value>資料夾</value></data>
|
||||||
|
<data name="DirectoryDesc" xml:space="preserve"><value>資料夾選擇 (obj.dir)</value></data>
|
||||||
|
<data name="FileDesc" xml:space="preserve"><value>檔案選擇 (obj.file_*)</value></data>
|
||||||
|
<data name="FileVideo" xml:space="preserve"><value>影片檔案</value></data>
|
||||||
|
<data name="FileAudio" xml:space="preserve"><value>音訊檔案</value></data>
|
||||||
|
<data name="FileImage" xml:space="preserve"><value>圖片檔案</value></data>
|
||||||
|
<data name="FileProject" xml:space="preserve"><value>專案檔案</value></data>
|
||||||
|
<data name="FileMp4" xml:space="preserve"><value>MP4檔案</value></data>
|
||||||
|
<data name="FileExo" xml:space="preserve"><value>EXO檔案</value></data>
|
||||||
|
<data name="FileSubtitle" xml:space="preserve"><value>字幕檔案</value></data>
|
||||||
|
<data name="FileShader" xml:space="preserve"><value>著色器檔案</value></data>
|
||||||
<data name="ToolBarImport" xml:space="preserve"><value>導入</value></data>
|
<data name="ToolBarImport" xml:space="preserve"><value>導入</value></data>
|
||||||
<data name="ToolBarExport" xml:space="preserve"><value>導出</value></data>
|
<data name="ToolBarExport" xml:space="preserve"><value>導出</value></data>
|
||||||
<data name="ToolBarClear" xml:space="preserve"><value>清除</value></data>
|
<data name="ToolBarClear" xml:space="preserve"><value>清除</value></data>
|
||||||
@@ -84,4 +104,7 @@
|
|||||||
<data name="ToolBarImportErrorTitle" xml:space="preserve"><value>導入錯誤</value></data>
|
<data name="ToolBarImportErrorTitle" xml:space="preserve"><value>導入錯誤</value></data>
|
||||||
<data name="ToolBarExportErrorTitle" xml:space="preserve"><value>導出錯誤</value></data>
|
<data name="ToolBarExportErrorTitle" xml:space="preserve"><value>導出錯誤</value></data>
|
||||||
<data name="LuaFileFilter" xml:space="preserve"><value>Lua腳本 (*.lua)|*.lua|所有檔案 (*.*)|*.*</value></data>
|
<data name="LuaFileFilter" xml:space="preserve"><value>Lua腳本 (*.lua)|*.lua|所有檔案 (*.*)|*.*</value></data>
|
||||||
|
<data name="DiagnosticCompile" xml:space="preserve"><value>語法錯誤</value></data>
|
||||||
|
<data name="DiagnosticRuntime" xml:space="preserve"><value>執行時錯誤</value></data>
|
||||||
|
<data name="DiagnosticTimeout" xml:space="preserve"><value>執行逾時</value></data>
|
||||||
</root>
|
</root>
|
||||||
@@ -0,0 +1,339 @@
|
|||||||
|
using System;
|
||||||
|
using System.Collections.Generic;
|
||||||
|
using System.ComponentModel.DataAnnotations;
|
||||||
|
using System.Globalization;
|
||||||
|
using System.Reflection;
|
||||||
|
using System.Windows.Media;
|
||||||
|
using Vortice.Direct2D1;
|
||||||
|
using YukkuriMovieMaker.Commons;
|
||||||
|
using YukkuriMovieMaker.Player.Video;
|
||||||
|
using YukkuriMovieMaker.Plugin;
|
||||||
|
using YukkuriMovieMaker.Plugin.Effects;
|
||||||
|
using LuaScript.Compat;
|
||||||
|
|
||||||
|
namespace LuaScript
|
||||||
|
{
|
||||||
|
internal sealed class VideoEffectChain : IDisposable
|
||||||
|
{
|
||||||
|
private sealed class Node
|
||||||
|
{
|
||||||
|
public required IVideoEffect Model;
|
||||||
|
public required IVideoEffectProcessor Processor;
|
||||||
|
public required AviUtlEffectMapping? Mapping;
|
||||||
|
public required int RequestIndex;
|
||||||
|
}
|
||||||
|
|
||||||
|
private static readonly AviUtlParameterMapping Identity = new(string.Empty, string.Empty, 1d, 0d);
|
||||||
|
|
||||||
|
private static Dictionary<string, Type>? _typeRegistry;
|
||||||
|
private static Dictionary<string, Type>? _nameRegistry;
|
||||||
|
private static readonly Dictionary<Type, Dictionary<string, PropertyInfo>> _propertyCache = [];
|
||||||
|
|
||||||
|
private readonly IGraphicsDevicesAndContext _devices;
|
||||||
|
private readonly List<Node> _nodes = [];
|
||||||
|
private string[] _signature = [];
|
||||||
|
private AviUtlEngine _signatureTarget = AviUtlEngine.Both;
|
||||||
|
|
||||||
|
public VideoEffectChain(IGraphicsDevicesAndContext devices)
|
||||||
|
{
|
||||||
|
_devices = devices;
|
||||||
|
}
|
||||||
|
|
||||||
|
public ID2D1Image Apply(ID2D1Image source, IReadOnlyList<AviUtlEffectRequest> requests, EffectDescription baseDesc, AviUtlEngine target, ref DrawDescription drawDescription)
|
||||||
|
{
|
||||||
|
try
|
||||||
|
{
|
||||||
|
SyncNodes(requests, target);
|
||||||
|
}
|
||||||
|
catch
|
||||||
|
{
|
||||||
|
return source;
|
||||||
|
}
|
||||||
|
|
||||||
|
var current = source;
|
||||||
|
var desc = drawDescription;
|
||||||
|
|
||||||
|
foreach (var node in _nodes)
|
||||||
|
{
|
||||||
|
try
|
||||||
|
{
|
||||||
|
ApplyParameters(node.Model, node.Mapping, requests[node.RequestIndex].Arguments);
|
||||||
|
node.Processor.SetInput(current);
|
||||||
|
var effectDescription = new EffectDescription(baseDesc, desc, baseDesc.InputIndex, baseDesc.InputCount, baseDesc.GroupIndex, baseDesc.GroupCount);
|
||||||
|
desc = node.Processor.Update(effectDescription);
|
||||||
|
current = node.Processor.Output;
|
||||||
|
}
|
||||||
|
catch
|
||||||
|
{
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
drawDescription = desc;
|
||||||
|
return current;
|
||||||
|
}
|
||||||
|
|
||||||
|
private void SyncNodes(IReadOnlyList<AviUtlEffectRequest> requests, AviUtlEngine target)
|
||||||
|
{
|
||||||
|
if (SignatureMatches(requests, target))
|
||||||
|
return;
|
||||||
|
|
||||||
|
DisposeNodes();
|
||||||
|
_signatureTarget = target;
|
||||||
|
_signature = new string[requests.Count];
|
||||||
|
for (int i = 0; i < requests.Count; i++)
|
||||||
|
_signature[i] = requests[i].Name;
|
||||||
|
|
||||||
|
for (int i = 0; i < requests.Count; i++)
|
||||||
|
{
|
||||||
|
Type? type;
|
||||||
|
AviUtlEffectMapping? mapping;
|
||||||
|
if (AviUtlCompatMap.Default.TryResolve(requests[i].Name, target, out var resolved) &&
|
||||||
|
ResolveType(resolved.TargetType) is { } mappedType)
|
||||||
|
{
|
||||||
|
mapping = resolved;
|
||||||
|
type = mappedType;
|
||||||
|
}
|
||||||
|
else
|
||||||
|
{
|
||||||
|
mapping = null;
|
||||||
|
type = ResolveName(requests[i].Name);
|
||||||
|
}
|
||||||
|
if (type is null)
|
||||||
|
continue;
|
||||||
|
|
||||||
|
IVideoEffect? model = null;
|
||||||
|
try
|
||||||
|
{
|
||||||
|
model = Activator.CreateInstance(type) as IVideoEffect;
|
||||||
|
}
|
||||||
|
catch
|
||||||
|
{
|
||||||
|
}
|
||||||
|
if (model is null)
|
||||||
|
continue;
|
||||||
|
|
||||||
|
IVideoEffectProcessor processor;
|
||||||
|
try
|
||||||
|
{
|
||||||
|
processor = model.CreateVideoEffect(_devices);
|
||||||
|
}
|
||||||
|
catch
|
||||||
|
{
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
|
||||||
|
_nodes.Add(new Node { Model = model, Processor = processor, Mapping = mapping, RequestIndex = i });
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private bool SignatureMatches(IReadOnlyList<AviUtlEffectRequest> requests, AviUtlEngine target)
|
||||||
|
{
|
||||||
|
if (_signatureTarget != target || _signature.Length != requests.Count)
|
||||||
|
return false;
|
||||||
|
for (int i = 0; i < requests.Count; i++)
|
||||||
|
{
|
||||||
|
if (!string.Equals(_signature[i], requests[i].Name, StringComparison.Ordinal))
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
|
||||||
|
private static Type? ResolveType(string targetType)
|
||||||
|
{
|
||||||
|
EnsureRegistries();
|
||||||
|
return _typeRegistry!.TryGetValue(Normalize(targetType), out var type) ? type : null;
|
||||||
|
}
|
||||||
|
|
||||||
|
private static Type? ResolveName(string name)
|
||||||
|
{
|
||||||
|
EnsureRegistries();
|
||||||
|
return _nameRegistry!.TryGetValue(Normalize(name), out var type) ? type : null;
|
||||||
|
}
|
||||||
|
|
||||||
|
private static void EnsureRegistries()
|
||||||
|
{
|
||||||
|
if (_typeRegistry is not null && _nameRegistry is not null)
|
||||||
|
return;
|
||||||
|
|
||||||
|
var byType = new Dictionary<string, Type>(StringComparer.Ordinal);
|
||||||
|
var byName = new Dictionary<string, Type>(StringComparer.Ordinal);
|
||||||
|
try
|
||||||
|
{
|
||||||
|
foreach (var factory in EffectFactories.VideoEffectFactories)
|
||||||
|
{
|
||||||
|
try
|
||||||
|
{
|
||||||
|
var type = factory.EffectType;
|
||||||
|
if (type is null)
|
||||||
|
continue;
|
||||||
|
byType.TryAdd(Normalize(type.Name), type);
|
||||||
|
Register(byName, factory.Name, type);
|
||||||
|
foreach (var keyword in factory.Keywords)
|
||||||
|
Register(byName, keyword, type);
|
||||||
|
}
|
||||||
|
catch
|
||||||
|
{
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
catch
|
||||||
|
{
|
||||||
|
}
|
||||||
|
_typeRegistry = byType;
|
||||||
|
_nameRegistry = byName;
|
||||||
|
}
|
||||||
|
|
||||||
|
private static void Register(Dictionary<string, Type> map, string? key, Type type)
|
||||||
|
{
|
||||||
|
if (string.IsNullOrWhiteSpace(key))
|
||||||
|
return;
|
||||||
|
map.TryAdd(Normalize(key), type);
|
||||||
|
}
|
||||||
|
|
||||||
|
private static string Normalize(string value) => value.Trim().ToLowerInvariant();
|
||||||
|
|
||||||
|
private static void ApplyParameters(IVideoEffect model, AviUtlEffectMapping? mapping, IReadOnlyList<KeyValuePair<string, object>> arguments)
|
||||||
|
{
|
||||||
|
if (arguments.Count == 0)
|
||||||
|
return;
|
||||||
|
|
||||||
|
var properties = GetProperties(model.GetType());
|
||||||
|
foreach (var (key, value) in arguments)
|
||||||
|
{
|
||||||
|
PropertyInfo? property;
|
||||||
|
AviUtlParameterMapping parameter;
|
||||||
|
if (mapping is not null)
|
||||||
|
{
|
||||||
|
if (!mapping.TryGetParameter(key, out parameter) ||
|
||||||
|
!properties.TryGetValue(Normalize(parameter.Property), out property))
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
else
|
||||||
|
{
|
||||||
|
if (!properties.TryGetValue(Normalize(key), out property))
|
||||||
|
continue;
|
||||||
|
parameter = Identity;
|
||||||
|
}
|
||||||
|
|
||||||
|
try
|
||||||
|
{
|
||||||
|
SetValue(model, property, value, parameter);
|
||||||
|
}
|
||||||
|
catch
|
||||||
|
{
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private static Dictionary<string, PropertyInfo> GetProperties(Type type)
|
||||||
|
{
|
||||||
|
if (_propertyCache.TryGetValue(type, out var cached))
|
||||||
|
return cached;
|
||||||
|
|
||||||
|
var map = new Dictionary<string, PropertyInfo>(StringComparer.Ordinal);
|
||||||
|
foreach (var property in type.GetProperties(BindingFlags.Public | BindingFlags.Instance))
|
||||||
|
{
|
||||||
|
if (property.GetIndexParameters().Length != 0)
|
||||||
|
continue;
|
||||||
|
bool usable = property.PropertyType == typeof(Animation) || property.GetSetMethod() is not null;
|
||||||
|
if (!usable)
|
||||||
|
continue;
|
||||||
|
|
||||||
|
map.TryAdd(Normalize(property.Name), property);
|
||||||
|
try
|
||||||
|
{
|
||||||
|
var display = property.GetCustomAttribute<DisplayAttribute>()?.GetName();
|
||||||
|
if (!string.IsNullOrWhiteSpace(display))
|
||||||
|
map.TryAdd(Normalize(display), property);
|
||||||
|
}
|
||||||
|
catch
|
||||||
|
{
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
_propertyCache[type] = map;
|
||||||
|
return map;
|
||||||
|
}
|
||||||
|
|
||||||
|
private static void SetValue(IVideoEffect model, PropertyInfo property, object value, AviUtlParameterMapping parameter)
|
||||||
|
{
|
||||||
|
var type = property.PropertyType;
|
||||||
|
|
||||||
|
if (type == typeof(Animation))
|
||||||
|
{
|
||||||
|
if (property.GetValue(model) is Animation animation)
|
||||||
|
animation.CopyFrom(new Animation(parameter.Transform(ToDouble(value))));
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
if (type == typeof(bool))
|
||||||
|
{
|
||||||
|
property.SetValue(model, ToBool(value));
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
if (type.IsEnum)
|
||||||
|
{
|
||||||
|
property.SetValue(model, ToEnum(type, value));
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
if (type == typeof(Color))
|
||||||
|
{
|
||||||
|
property.SetValue(model, ToColor(value));
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
if (type == typeof(double) || type == typeof(float) || type == typeof(int) || type == typeof(long) || type == typeof(short))
|
||||||
|
{
|
||||||
|
property.SetValue(model, Convert.ChangeType(parameter.Transform(ToDouble(value)), type, CultureInfo.InvariantCulture));
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
if (type == typeof(string))
|
||||||
|
property.SetValue(model, value?.ToString());
|
||||||
|
}
|
||||||
|
|
||||||
|
private static double ToDouble(object value) => value switch
|
||||||
|
{
|
||||||
|
double d => d,
|
||||||
|
bool b => b ? 1d : 0d,
|
||||||
|
string s => double.TryParse(s, NumberStyles.Float, CultureInfo.InvariantCulture, out var r) ? r : 0d,
|
||||||
|
_ => 0d,
|
||||||
|
};
|
||||||
|
|
||||||
|
private static bool ToBool(object value) => value switch
|
||||||
|
{
|
||||||
|
bool b => b,
|
||||||
|
double d => d != 0d,
|
||||||
|
string s => s.Equals("true", StringComparison.OrdinalIgnoreCase) || s == "1",
|
||||||
|
_ => false,
|
||||||
|
};
|
||||||
|
|
||||||
|
private static object ToEnum(Type type, object value)
|
||||||
|
{
|
||||||
|
if (value is string s && Enum.TryParse(type, s, true, out var parsed))
|
||||||
|
return parsed;
|
||||||
|
return Enum.ToObject(type, (int)ToDouble(value));
|
||||||
|
}
|
||||||
|
|
||||||
|
private static Color ToColor(object value)
|
||||||
|
{
|
||||||
|
int rgb = (int)ToDouble(value);
|
||||||
|
return Color.FromRgb((byte)((rgb >> 16) & 0xFF), (byte)((rgb >> 8) & 0xFF), (byte)(rgb & 0xFF));
|
||||||
|
}
|
||||||
|
|
||||||
|
private void DisposeNodes()
|
||||||
|
{
|
||||||
|
foreach (var node in _nodes)
|
||||||
|
{
|
||||||
|
try
|
||||||
|
{
|
||||||
|
node.Processor.ClearInput();
|
||||||
|
}
|
||||||
|
catch
|
||||||
|
{
|
||||||
|
}
|
||||||
|
node.Processor.Dispose();
|
||||||
|
}
|
||||||
|
_nodes.Clear();
|
||||||
|
}
|
||||||
|
|
||||||
|
public void Dispose() => DisposeNodes();
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -24,6 +24,58 @@
|
|||||||
حذف هذه الاستدعاءات عند عدم الحاجة يسرّع المعالجة.
|
حذف هذه الاستدعاءات عند عدم الحاجة يسرّع المعالجة.
|
||||||
|
|
||||||
|
|
||||||
|
- محركات التنفيذ والتسريع التلقائي -
|
||||||
|
|
||||||
|
النصوص التي تحتوي على معالجة بكسل (حلقة getpixel/setpixel متداخلة)
|
||||||
|
يُحلَّل تركيبها وتُوجَّه تلقائياً إلى محرك أسرع.
|
||||||
|
أما النصوص العادية (الإحداثيات، الدوران، الشفافية، إلخ) فتظل تعمل على
|
||||||
|
MoonSharp كما في السابق دون أي تغيير في السلوك.
|
||||||
|
|
||||||
|
○ التوجيه التلقائي (عند عدم وجود توجيه)
|
||||||
|
· تخطيط بكسل مكتفٍ بنفسه (انظر الشروط أدناه)
|
||||||
|
→ نواة CPU (سريعة ودقيقة)
|
||||||
|
· عمليات البكسل الأخرى → Native (LuaJIT، فقط عند نشره)
|
||||||
|
· بلا عمليات بكسل → MoonSharp
|
||||||
|
|
||||||
|
○ توجيهات المحرك (تعليق في السطر الأول من النص)
|
||||||
|
--!cpu : نواة CPU. تُترجَم وقت التشغيل إلى شجرة تعابير
|
||||||
|
وتُنفَّذ بالتوازي على كل أنوية CPU (مطابقة تماماً لـ MoonSharp).
|
||||||
|
--!gpu : نواة GPU. تُنفَّذ كمظلِّل بكسل Direct2D،
|
||||||
|
وتلغي نقل GPU→CPU لأقصى سرعة.
|
||||||
|
قد تختلف النتائج اختلافاً طفيفاً بسبب دقة float32 (اختياري).
|
||||||
|
--!native : LuaJIT (عملية منفصلة). سريع ومطابق لـ MoonSharp.
|
||||||
|
يتطلب نشر مجلد native.
|
||||||
|
--!moonsharp : يفرض محرك MoonSharp التقليدي.
|
||||||
|
※ إذا كان التوجيه غير متاح/غير مدعوم، يرجع تلقائياً إلى محرك أدنى
|
||||||
|
(لا يتلف الإخراج أبداً).
|
||||||
|
|
||||||
|
○ التركيب المؤهَّل للنواة السريعة (تخطيط بكسل خالص)
|
||||||
|
فقط الحلقة المتداخلة بالشكل التالي تتحول إلى نواة.
|
||||||
|
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, r2, g2, b2 [, a2])
|
||||||
|
end
|
||||||
|
end
|
||||||
|
· يجوز في الجسم استخدام العمليات الحسابية و math.* والمقارنات
|
||||||
|
وصيغة العتبة "cond and value1 or value2" ومتغيرات local فقط.
|
||||||
|
· يجوز الإشارة فقط إلى البكسل الجاري معالجته (getpixel(x, y))
|
||||||
|
وقيم مثل obj/scene/time.
|
||||||
|
· أي استخدام لأخذ عينات الجوار (التمويه، إلخ) أو الكتابة إلى
|
||||||
|
إحداثيات أخرى أو getpixeldata أو getobject أو عمليات
|
||||||
|
الجداول/السلاسل أو جُمَل if لا يتحول إلى نواة ويُنفَّذ تلقائياً
|
||||||
|
على المحرك التقليدي.
|
||||||
|
|
||||||
|
مثال (يجعل شكلاً أبيض أحمر):
|
||||||
|
--!gpu
|
||||||
|
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 / 2, b / 2, a)
|
||||||
|
end
|
||||||
|
end
|
||||||
|
|
||||||
|
|
||||||
- المعاملات -
|
- المعاملات -
|
||||||
|
|
||||||
يحتوي لوح التأثيرات على 4 أشرطة تتبع (تدعم الرسوم المتحركة) على النحو التالي.
|
يحتوي لوح التأثيرات على 4 أشرطة تتبع (تدعم الرسوم المتحركة) على النحو التالي.
|
||||||
@@ -36,6 +88,36 @@
|
|||||||
|
|
||||||
* كل شريط تتبع يدعم شرائح الرسوم المتحركة (مع الاستيفاء).
|
* كل شريط تتبع يدعم شرائح الرسوم المتحركة (مع الاستيفاء).
|
||||||
* يمكن استيراد/تصدير ملفات .lua من شريط أدوات محرر النصوص.
|
* يمكن استيراد/تصدير ملفات .lua من شريط أدوات محرر النصوص.
|
||||||
|
* تظهر مربعات الاختيار (obj.check0 إلى obj.check3) واللون (color) في لوح التأثيرات
|
||||||
|
تلقائياً عندما يشير إليها النص البرمجي (تظهر أشرطة التتبع دائماً). هذا الاستخدام
|
||||||
|
العام لا يصاحبه إعلان نطاق/قيمة افتراضية، لذا تعامل مع نطاقات القيم داخل النص.
|
||||||
|
وتبقى رؤوس AviUtl --track / --check / --color تعمل كما كانت.
|
||||||
|
|
||||||
|
توجد 4 منزلقات رقمية، ويُشار إليها عبر obj.slider0 إلى obj.slider3.
|
||||||
|
القيم أعداد صحيحة ولا تحمل كسوراً عشرية.
|
||||||
|
|
||||||
|
Slider0 : منزلق صحيح (النطاق: 1 ~ 10)
|
||||||
|
Slider1 : منزلق صحيح (النطاق: 0 ~ 100)
|
||||||
|
Slider2 : منزلق صحيح (النطاق: 0 ~ 1000)
|
||||||
|
Slider3 : منزلق صحيح (النطاق: -1000 ~ 1000)
|
||||||
|
|
||||||
|
تتوفر أيضاً معاملات نصية، ويُشار إلى كل قيمة بالأسماء التالية.
|
||||||
|
|
||||||
|
obj.text : نص حقل إدخال النص
|
||||||
|
obj.font : اسم الخط من محدد الخطوط
|
||||||
|
obj.dir : مسار محدد المجلدات
|
||||||
|
obj.file_video : مسار ملف فيديو
|
||||||
|
obj.file_audio : مسار ملف صوتي
|
||||||
|
obj.file_image : مسار ملف صورة
|
||||||
|
obj.file_project : مسار ملف مشروع
|
||||||
|
obj.file_mp4 : مسار ملف MP4
|
||||||
|
obj.file_exo : مسار ملف EXO
|
||||||
|
obj.file_subtitle : مسار ملف ترجمة
|
||||||
|
obj.file_shader : مسار ملف تظليل
|
||||||
|
|
||||||
|
※تظهر المنزلقات والمعاملات النصية في لوح التأثيرات تلقائياً عندما يشير إليها النص البرمجي.
|
||||||
|
※يمكن تمرير مسار الملف إلى obj.load لتحميل صورة أو فيديو.
|
||||||
|
※تتوفر هذه المعاملات في محركَي MoonSharp والمحرك الأصلي معاً.
|
||||||
|
|
||||||
|
|
||||||
- المتغيرات العامة -
|
- المتغيرات العامة -
|
||||||
@@ -157,6 +239,18 @@
|
|||||||
obj.track2 : القيمة الحالية لـ Track2 في لوح التأثيرات [للقراءة فقط]
|
obj.track2 : القيمة الحالية لـ Track2 في لوح التأثيرات [للقراءة فقط]
|
||||||
obj.track3 : القيمة الحالية لـ Track3 في لوح التأثيرات [للقراءة فقط]
|
obj.track3 : القيمة الحالية لـ Track3 في لوح التأثيرات [للقراءة فقط]
|
||||||
|
|
||||||
|
○ المنزلقات
|
||||||
|
obj.slider0 : القيمة الحالية لـ Slider0 في لوح التأثيرات (عدد صحيح) [للقراءة فقط]
|
||||||
|
obj.slider1 : القيمة الحالية لـ Slider1 في لوح التأثيرات (عدد صحيح) [للقراءة فقط]
|
||||||
|
obj.slider2 : القيمة الحالية لـ Slider2 في لوح التأثيرات (عدد صحيح) [للقراءة فقط]
|
||||||
|
obj.slider3 : القيمة الحالية لـ Slider3 في لوح التأثيرات (عدد صحيح) [للقراءة فقط]
|
||||||
|
|
||||||
|
○ المعاملات النصية
|
||||||
|
obj.text : نص حقل إدخال النص [للقراءة فقط]
|
||||||
|
obj.font : اسم الخط من محدد الخطوط [للقراءة فقط]
|
||||||
|
obj.dir : مسار محدد المجلدات [للقراءة فقط]
|
||||||
|
obj.file_video ~ obj.file_shader : مسار كل محدد ملفات [للقراءة فقط]
|
||||||
|
|
||||||
○ الطبقة
|
○ الطبقة
|
||||||
obj.layer : رقم الطبقة التي يوجد فيها الكائن [للقراءة فقط]
|
obj.layer : رقم الطبقة التي يوجد فيها الكائن [للقراءة فقط]
|
||||||
* نفس قيمة المتغير العام layer.
|
* نفس قيمة المتغير العام layer.
|
||||||
@@ -315,23 +409,89 @@
|
|||||||
مثال: obj.ox = obj.ox + obj.rand(-10, 10, 1, obj.frame)
|
مثال: obj.ox = obj.ox + obj.rand(-10, 10, 1, obj.frame)
|
||||||
|
|
||||||
○ obj.load(الهدف، ...)
|
○ obj.load(الهدف، ...)
|
||||||
يستبدل مخزن الكائن بمحتوى مُولَّد. في هذا الإصدار يُدعم الهدف "figure" فقط.
|
يستبدل مخزن الكائن بمحتوى مُولَّد. تُدعم الأهداف "figure" و"text"
|
||||||
|
و"image" (ملف صورة) و"movie" (ملف فيديو). بعد التحميل تُحدَّث
|
||||||
|
obj.w / obj.h وغيرها إلى الحجم المُولَّد، ويمكن قراءتها بـ getpixel
|
||||||
|
مباشرة بعد التحميل. يعمل على محرك MoonSharp والمحرك السريع (LuaJIT).
|
||||||
|
|
||||||
obj.load("figure", name, color, size [, line [, aspect]])
|
obj.load("figure", name, color, size [, line [, aspect]])
|
||||||
يُولّد شكلاً ويستبدل مخزن الكائن به
|
يُولّد شكلاً ويستبدل المخزن (متوسَّطاً).
|
||||||
(يُعاد تحجيم الخرج ليطابق الشكل ويُتوسَّط).
|
name : 円 / 四角形 / 三角形 / 五角形 / 六角形 / 星形
|
||||||
name : اسم الشكل. أحد 円 / 四角形 / 三角形 / 五角形 /
|
(وتُقبل الأسماء الإنجليزية circle, rect, triangle,
|
||||||
六角形 / 星形 (وتُقبل الأسماء الإنجليزية circle, rect,
|
pentagon, hexagon, star).
|
||||||
triangle, pentagon, hexagon, star).
|
|
||||||
color : لون التعبئة 0xRRGGBB.
|
color : لون التعبئة 0xRRGGBB.
|
||||||
size : الحجم الأساسي بالبكسل.
|
size : الحجم الأساسي بالبكسل.
|
||||||
line : عرض الحد (اختياري). الحذف أو 0 يملأ الشكل،
|
line : عرض الحد (اختياري). 0 يملأ الشكل.
|
||||||
والقيمة المساوية للحجم أو الأكبر منه تملؤه أيضاً.
|
aspect : التشويه -1.0 ~ 1.0 (اختياري).
|
||||||
aspect : التشويه -1.0 ~ 1.0 (اختياري). الموجب يقلّص العرض،
|
مثال: obj.load("figure", "円", 0xff3366, 200)
|
||||||
والسالب يقلّص الارتفاع.
|
|
||||||
مثال: obj.load("figure", "円", 0xff3366, 200)
|
obj.load("text", string)
|
||||||
※ المُنفَّذ هو obj.load("figure", ...) فقط. الأهداف الأخرى
|
يرسم النص بالخط والحجم واللون المحددة بـ obj.setfont ويستبدل
|
||||||
(ملفات الصور و"text" و"tempbuffer" و"movie" وغيرها) لا تفعل شيئاً.
|
المخزن (يُرسم بـ DirectWrite).
|
||||||
※ تُنفَّذ نصوص الرسم على محرك MoonSharp.
|
مثال: obj.setfont("Yu Gothic UI", 48); obj.load("text", "字幕")
|
||||||
|
|
||||||
|
obj.load("image", path)
|
||||||
|
يحمّل ملف صورة ويستبدل المخزن.
|
||||||
|
※ للأمان يُتحقَّق من الترويسة الأولى، ولا تُحمَّل إلا الصور
|
||||||
|
الأصلية (PNG / JPEG / GIF / BMP / TIFF / WebP).
|
||||||
|
مثال: obj.load("image", "C:\\img\\logo.png")
|
||||||
|
|
||||||
|
obj.load("movie", path [, time])
|
||||||
|
يحمّل الإطار عند الزمن المحدد من ملف فيديو ويستبدل المخزن
|
||||||
|
(يُفكَّك بـ Media Foundation).
|
||||||
|
time : بالثواني. الافتراضي obj.time عند الحذف.
|
||||||
|
※ للأمان يُتحقَّق من الترويسة الأولى، ولا تُحمَّل إلا مقاطع
|
||||||
|
الفيديو الأصلية (MP4 / MOV / MKV / WebM / AVI / FLV / ASF).
|
||||||
|
مثال: obj.load("movie", "C:\\mov\\clip.mp4", obj.time)
|
||||||
|
|
||||||
|
○ obj.setfont(font [, size [, style [, color]]])
|
||||||
|
يحدد الخط المستخدم في obj.load("text").
|
||||||
|
style : أعلام بِتّية. 1=عريض، 2=مائل، 3=عريض+مائل.
|
||||||
|
color : 0xRRGGBB.
|
||||||
|
مثال: obj.setfont("Meiryo", 64, 1, 0xffffff)
|
||||||
|
|
||||||
|
○ obj.draw([ox, oy, oz [, zoom [, alpha [, aspect]]]])
|
||||||
|
يدمج صورة الكائن الحالية في مخزن التراكم ويرسمها.
|
||||||
|
استدعاؤها عدة مرات يرسم نسخاً متراكبة (صور لاحقة، جزيئات، إلخ).
|
||||||
|
ox, oy, oz : الإزاحة من المركز (افتراضي 0).
|
||||||
|
zoom : 1.0 هو الحجم الأصلي (افتراضي 1.0).
|
||||||
|
alpha : 0.0 ~ 1.0 (افتراضي 1.0).
|
||||||
|
aspect : -1.0 ~ 1.0 (افتراضي 0).
|
||||||
|
※ بعد الاستدعاء يُكبَت الرسم القياسي ويُخرَج الناتج المدموج.
|
||||||
|
|
||||||
|
○ obj.drawpoly(x0,y0,z0, x1,y1,z1, x2,y2,z2, x3,y3,z3
|
||||||
|
[, u0,v0, u1,v1, u2,v2, u3,v3 [, alpha]])
|
||||||
|
يطبّق صورة الكائن كنسيج على رباعي محدد بأربع رؤوس.
|
||||||
|
ترتيب الرؤوس: أعلى-يسار، أعلى-يمين، أسفل-يمين، أسفل-يسار.
|
||||||
|
عند حذف UV تُستخدم الصورة كاملة.
|
||||||
|
※ عند حذف UV وإعطاء المعامل الثالث عشر فقط، يُستخدم كقيمة ألفا
|
||||||
|
(12 إحداثياً + ألفا).
|
||||||
|
※ يُسقَط بتحويل أفيني (دقيق لمتوازي الأضلاع، تقريبي لغيره).
|
||||||
|
|
||||||
|
○ obj.copybuffer(الوجهة، المصدر)
|
||||||
|
ينسخ صورة بين المخازن، يُحدَّد بالحرف الأول.
|
||||||
|
"obj" : مخزن صورة الكائن
|
||||||
|
"tmp" : مخزن مؤقت
|
||||||
|
"cache:الاسم" : ذاكرة مخبّأة مُسمّاة (تُحفظ بين الإطارات)
|
||||||
|
مثال: obj.copybuffer("tmp", "obj") -- حفظ
|
||||||
|
obj.copybuffer("obj", "tmp") -- استعادة
|
||||||
|
※ "frm" (مخزن الإطار / الخلفية) لا يمكن الحصول عليه بسبب بنية YMM4.
|
||||||
|
|
||||||
|
○ 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.setoption(name, value) / obj.getoption(name)
|
||||||
|
يضبط / يحصل على خيار. الخيارات غير المدعومة تُقبَل كي لا توقف
|
||||||
|
النص (getoption يُرجع القيمة المحفوظة، و0 إن لم تُضبط).
|
||||||
|
الخيارات التي تؤثر على الرسم حالياً:
|
||||||
|
"antialias" : 0 = أقرب جار، وإلا استيفاء خطّي
|
||||||
|
(obj.draw / obj.drawpoly).
|
||||||
|
|
||||||
|
○ obj.pixeloption(name, value)
|
||||||
|
يحفظ خياراً لعمليات البكسل كحالة.
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
@@ -503,27 +663,64 @@
|
|||||||
دالة أرقام عشوائية صحيحة حتمية متوافقة مع AviUtl. انظر "جدول obj - الدوال"
|
دالة أرقام عشوائية صحيحة حتمية متوافقة مع AviUtl. انظر "جدول obj - الدوال"
|
||||||
للتفاصيل.
|
للتفاصيل.
|
||||||
|
|
||||||
○ رسم الأشكال
|
○ الرسم والتركيب والتحميل
|
||||||
obj.load("figure", ...) يُولّد دائرة أو مربعاً أو مثلثاً أو خماسياً أو
|
يُدعم الرسم والتركيب عبر obj.draw / obj.drawpoly، وعمليات المخزن
|
||||||
سداسياً أو نجمة، ويستبدل مخزن الكائن به. انظر "جدول obj - الدوال" للتفاصيل.
|
عبر obj.copybuffer، والتوليد والتحميل عبر
|
||||||
|
obj.load("figure"/"text"/"image"/"movie")، و obj.setfont، و obj.effect،
|
||||||
|
و obj.getvalue، و obj.setoption / obj.getoption / obj.pixeloption.
|
||||||
|
انظر "جدول obj - الدوال" للتفاصيل.
|
||||||
|
|
||||||
تتطلب الميزات التالية التكامل مع خط أنابيب الرسم، لذا فهي خارج نطاق هذه الطبقة.
|
○ خريطة توافق AviUtl / AviUtl2 لـ obj.effect
|
||||||
|
يَرجع obj.effect("اسم التأثير"، "اسم المعامل"، القيمة، ...) إلى خريطة
|
||||||
|
التوافق أولًا. التأثيرات المُعلَنة بأسماء AviUtl / AviUtl2 تمر عبر تحويل
|
||||||
|
المقياس/الإزاحة المُعلَن قبل الوصول إلى خصائص YMM4. الأسماء غير المُعلَنة في
|
||||||
|
الخريطة تُحَلّ مباشرةً عبر اسم تأثير YMM4 أو كلمته المفتاحية، لذا تظل
|
||||||
|
الاستدعاءات الحالية تعمل.
|
||||||
|
بُنيت الخريطة كمعكوس لتصدير AviUtl الخاص بـ YMM4 نفسه (مخرجات .exo)، لذا
|
||||||
|
تتطابق ذهابًا وإيابًا. يُختار المحرك الهدف عبر --!aviutl (الافتراضي) /
|
||||||
|
--!aviutl2.
|
||||||
|
أسماء التأثيرات المُعلَنة في الخريطة ومعاملاتها الرئيسية كما يلي:
|
||||||
|
ぼかし: 範囲, サイズ固定
|
||||||
|
境界ぼかし: 範囲
|
||||||
|
方向ブラー: 範囲, 角度, サイズ固定
|
||||||
|
放射ブラー: 範囲, X, Y, サイズを固定
|
||||||
|
閃光: 範囲, X, Y, サイズを固定
|
||||||
|
クロマキー: 色相範囲, 境界補正
|
||||||
|
クリッピング: 上, 下, 左, 右, 中心の位置を変更
|
||||||
|
斜めクリッピング: 中心X, 中心Y, 角度, ぼかし, 幅
|
||||||
|
領域拡張: 上, 下, 左, 右
|
||||||
|
座標: X, Y, Z
|
||||||
|
回転: X, Y, Z
|
||||||
|
リサイズ: 拡大率, X, Y, 補間なし
|
||||||
|
画像ループ: 横回数, 縦回数
|
||||||
|
極座標変換: 中心幅, 渦巻
|
||||||
|
グラデーション: 強さ, 中心X, 中心Y, 角度, 幅
|
||||||
|
単色化: 強さ, 輝度を保持する
|
||||||
|
縁取り: サイズ, ぼかし
|
||||||
|
反転: -
|
||||||
|
モザイク: サイズ
|
||||||
|
ディスプレイスメントマップ: ぼかし
|
||||||
|
動画ファイル合成: X, Y, 拡大率
|
||||||
|
色調補正: 明るさ, コントラスト, 色相, 輝度, 彩度
|
||||||
|
色ずれ: ずれ幅, 角度, 強さ
|
||||||
|
يتوافق 色調補正 و 色ずれ مع تأثيرات إضافة المجتمع.
|
||||||
|
|
||||||
|
الميزات التالية خارج نطاق هذه الطبقة.
|
||||||
النصوص التي تستدعيها لن تعمل كما هو متوقع.
|
النصوص التي تستدعيها لن تعمل كما هو متوقع.
|
||||||
× الرسم والتركيب (obj.draw / obj.drawpoly)، وأهداف obj.load غير "figure"
|
× تحميل الوحدات عبر require، والوصول العشوائي إلى الملفات مثل
|
||||||
(ملفات الصور و"text" و"movie" وغيرها)، وكذلك obj.setfont
|
io / dofile (تحميل الصور / الفيديو عبر obj.load مدعوم مع التحقق
|
||||||
× تأثيرات المرشّحات وعمليات المخزن المؤقت
|
من الترويسة).
|
||||||
(obj.effect / obj.copybuffer / obj.setoption وما شابه)
|
× obj.setanchor، scene.set / scene.get وما شابه.
|
||||||
× تحميل الوحدات عبر require، والوصول إلى الملفات مثل io
|
|
||||||
|
|
||||||
|
|
||||||
- الميزات غير المدعومة / القيود -
|
- الميزات غير المدعومة / القيود -
|
||||||
|
|
||||||
× obj.effect()، obj.draw()، obj.drawpoly() وما شابه من AviUtl2 غير مدعومة (يُدعم obj.load("figure", ...) فقط؛ انظر "التوافق الجزئي مع نصوص AviUtl").
|
× obj.rand1()، obj.mes()، obj.setanchor() وما شابه من AviUtl2 غير مدعومة.
|
||||||
× obj.rand1()، obj.setfont()، obj.mes() وما شابه من AviUtl2 غير مدعومة.
|
|
||||||
× obj.setoption()، obj.getoption()، obj.getvalue()، obj.setanchor() وما شابه من AviUtl2 غير مدعومة.
|
|
||||||
× الدوال مثل scene.set() و scene.get() في جدول scene الخاص بـ AviUtl2 غير مدعومة.
|
× الدوال مثل scene.set() و scene.get() في جدول scene الخاص بـ AviUtl2 غير مدعومة.
|
||||||
(يمكن قراءة scene.width و scene.height فقط)
|
(يمكن قراءة scene.width و scene.height فقط)
|
||||||
× الوصول إلى الملفات (require, dofile, io وما شابه) غير مدعوم.
|
× الوصول العشوائي إلى الملفات من النصوص (require, dofile, io وما شابه) غير مدعوم.
|
||||||
|
فقط obj.load("image"/"movie") يحمّل الملفات المؤكَّد أنها وسائط أصلية عبر
|
||||||
|
التحقق من الترويسة الأولى.
|
||||||
× تعديل obj.z ينعكس في الرسم (مضمَّن في ReadBack)،
|
× تعديل obj.z ينعكس في الرسم (مضمَّن في ReadBack)،
|
||||||
لكن دعم الرسم ثلاثي الأبعاد محدود.
|
لكن دعم الرسم ثلاثي الأبعاد محدود.
|
||||||
× إذا تجاوز النص البرمجي مهلة الانتهاء (5 ثوانٍ)، يُنهى التنفيذ قسراً.
|
× إذا تجاوز النص البرمجي مهلة الانتهاء (5 ثوانٍ)، يُنهى التنفيذ قسراً.
|
||||||
|
|||||||
@@ -24,6 +24,61 @@
|
|||||||
Omitting these calls when unnecessary will speed up processing.
|
Omitting these calls when unnecessary will speed up processing.
|
||||||
|
|
||||||
|
|
||||||
|
- Execution Engines and Automatic Acceleration -
|
||||||
|
|
||||||
|
Scripts that contain pixel processing (a nested getpixel/setpixel loop)
|
||||||
|
are analyzed and automatically routed to a faster engine.
|
||||||
|
Ordinary scripts (coordinate, rotation, opacity changes, etc.) keep
|
||||||
|
running on MoonSharp as before, with no change in behavior.
|
||||||
|
|
||||||
|
o Automatic routing (when no directive is present)
|
||||||
|
- A self-contained per-pixel map (see conditions below)
|
||||||
|
-> CPU kernel (fast, exact)
|
||||||
|
- Other pixel operations -> Native (LuaJIT, only when deployed)
|
||||||
|
- No pixel operations -> MoonSharp
|
||||||
|
|
||||||
|
o Engine directives (a comment on the first line of the script)
|
||||||
|
--!cpu : CPU kernel. Compiled at runtime to an expression
|
||||||
|
tree and run in parallel on all CPU cores
|
||||||
|
(bit-identical to MoonSharp).
|
||||||
|
--!gpu : GPU kernel. Run as a Direct2D pixel shader,
|
||||||
|
eliminating the GPU->CPU transfer for top speed.
|
||||||
|
Results may differ slightly due to float32
|
||||||
|
precision (opt-in).
|
||||||
|
--!native : LuaJIT (separate process). Fast and identical to
|
||||||
|
MoonSharp. Requires the native folder deployed.
|
||||||
|
--!moonsharp : Forces the classic MoonSharp engine.
|
||||||
|
* If a directive is unavailable or unsupported, it automatically
|
||||||
|
falls back to a lower engine (the output is never broken).
|
||||||
|
|
||||||
|
o Syntax eligible for the fast kernel (a pure per-pixel map)
|
||||||
|
Only a nested loop of the following form becomes a kernel.
|
||||||
|
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, r2, g2, b2 [, a2])
|
||||||
|
end
|
||||||
|
end
|
||||||
|
- The body may use only arithmetic, math.*, comparisons, the
|
||||||
|
threshold idiom "cond and value1 or value2", and local
|
||||||
|
variables.
|
||||||
|
- It may reference only the current pixel being processed
|
||||||
|
(getpixel(x, y)) 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.
|
||||||
|
|
||||||
|
Example (turns a white figure red):
|
||||||
|
--!gpu
|
||||||
|
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 / 2, b / 2, a)
|
||||||
|
end
|
||||||
|
end
|
||||||
|
|
||||||
|
|
||||||
- Parameters -
|
- Parameters -
|
||||||
|
|
||||||
The effect panel has 4 trackbars (animation-enabled) as follows.
|
The effect panel has 4 trackbars (animation-enabled) as follows.
|
||||||
@@ -36,6 +91,38 @@
|
|||||||
|
|
||||||
* Each trackbar supports animation sliders (with interpolation).
|
* Each trackbar supports animation sliders (with interpolation).
|
||||||
* .lua files can be imported/exported from the script editor toolbar.
|
* .lua files can be imported/exported from the script editor toolbar.
|
||||||
|
* The checkboxes (obj.check0 - obj.check3) and the color (color) appear in the
|
||||||
|
effect panel automatically when the script references them (the trackbars are
|
||||||
|
always shown). This general use carries no range/default declaration, so handle
|
||||||
|
value ranges within the script. The AviUtl --track / --check / --color headers
|
||||||
|
still work as before.
|
||||||
|
|
||||||
|
There are 4 numeric sliders, referenced as obj.slider0 through obj.slider3.
|
||||||
|
The values are integers and do not hold decimals.
|
||||||
|
|
||||||
|
Slider0 : Integer slider (Range: 1 ~ 10)
|
||||||
|
Slider1 : Integer slider (Range: 0 ~ 100)
|
||||||
|
Slider2 : Integer slider (Range: 0 ~ 1000)
|
||||||
|
Slider3 : Integer slider (Range: -1000 ~ 1000)
|
||||||
|
|
||||||
|
String parameters are also available, referenced by the following names.
|
||||||
|
|
||||||
|
obj.text : String from the text input field
|
||||||
|
obj.font : Font name from the font selector
|
||||||
|
obj.dir : Path from the folder selector
|
||||||
|
obj.file_video : Path of a video file
|
||||||
|
obj.file_audio : Path of an audio file
|
||||||
|
obj.file_image : Path of an image file
|
||||||
|
obj.file_project : Path of a project file
|
||||||
|
obj.file_mp4 : Path of an MP4 file
|
||||||
|
obj.file_exo : Path of an EXO file
|
||||||
|
obj.file_subtitle : Path of a subtitle file
|
||||||
|
obj.file_shader : Path of a shader file
|
||||||
|
|
||||||
|
* The sliders and string parameters appear in the effect panel automatically
|
||||||
|
when the script references them.
|
||||||
|
* A file path can be passed to obj.load to load an image or movie.
|
||||||
|
* These parameters are available in both the MoonSharp and native engines.
|
||||||
|
|
||||||
|
|
||||||
- Global Variables -
|
- Global Variables -
|
||||||
@@ -160,6 +247,18 @@
|
|||||||
obj.track2 : Current value of Track2 in the effect panel [ReadOnly]
|
obj.track2 : Current value of Track2 in the effect panel [ReadOnly]
|
||||||
obj.track3 : Current value of Track3 in the effect panel [ReadOnly]
|
obj.track3 : Current value of Track3 in the effect panel [ReadOnly]
|
||||||
|
|
||||||
|
o Sliders
|
||||||
|
obj.slider0 : Current value of Slider0 in the effect panel (integer) [ReadOnly]
|
||||||
|
obj.slider1 : Current value of Slider1 in the effect panel (integer) [ReadOnly]
|
||||||
|
obj.slider2 : Current value of Slider2 in the effect panel (integer) [ReadOnly]
|
||||||
|
obj.slider3 : Current value of Slider3 in the effect panel (integer) [ReadOnly]
|
||||||
|
|
||||||
|
o String parameters
|
||||||
|
obj.text : String from the text input field [ReadOnly]
|
||||||
|
obj.font : Font name from the font selector [ReadOnly]
|
||||||
|
obj.dir : Path from the folder selector [ReadOnly]
|
||||||
|
obj.file_video ~ obj.file_shader : Path from each file selector [ReadOnly]
|
||||||
|
|
||||||
o Layer
|
o Layer
|
||||||
obj.layer : Layer number where the object is placed [ReadOnly]
|
obj.layer : Layer number where the object is placed [ReadOnly]
|
||||||
* Same value as global variable layer.
|
* Same value as global variable layer.
|
||||||
@@ -322,24 +421,94 @@
|
|||||||
Example: obj.ox = obj.ox + obj.rand(-10, 10, 1, obj.frame)
|
Example: obj.ox = obj.ox + obj.rand(-10, 10, 1, obj.frame)
|
||||||
|
|
||||||
o obj.load(target, ...)
|
o obj.load(target, ...)
|
||||||
Replaces the object buffer with generated content.
|
Replaces the object buffer with generated content. The targets
|
||||||
Only the "figure" target is supported in this version.
|
"figure", "text", "image" (image file) and "movie" (video file)
|
||||||
|
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.
|
||||||
|
|
||||||
obj.load("figure", name, color, size [, line [, aspect]])
|
obj.load("figure", name, color, size [, line [, aspect]])
|
||||||
Generates a shape and replaces the object buffer with it
|
Generates a shape and replaces the buffer (centered).
|
||||||
(the output is resized to the shape and centered).
|
name : 円 / 四角形 / 三角形 / 五角形 / 六角形 / 星形
|
||||||
name : Shape name. One of 円 / 四角形 / 三角形 / 五角形 /
|
(English aliases circle, rect, triangle, pentagon,
|
||||||
六角形 / 星形 (English aliases circle, rect,
|
hexagon, star are also accepted).
|
||||||
triangle, pentagon, hexagon, star are also accepted).
|
|
||||||
color : Fill color 0xRRGGBB.
|
color : Fill color 0xRRGGBB.
|
||||||
size : Bounding size in pixels.
|
size : Bounding size in pixels.
|
||||||
line : Outline width (optional). Omitted or 0 fills the
|
line : Outline width (optional). 0 fills the shape.
|
||||||
shape; a value at or above the size also fills it.
|
aspect : Distortion -1.0 ~ 1.0 (optional).
|
||||||
aspect : Distortion -1.0 ~ 1.0 (optional). Positive shrinks
|
Example: obj.load("figure", "円", 0xff3366, 200)
|
||||||
the width, negative shrinks the height.
|
|
||||||
Example: obj.load("figure", "円", 0xff3366, 200)
|
obj.load("text", string)
|
||||||
* Only obj.load("figure", ...) is implemented. Other targets
|
Draws the string with the font, size and color set by
|
||||||
(image files, "text", "tempbuffer", "movie", etc.) do nothing.
|
obj.setfont and replaces the buffer (rendered with DirectWrite).
|
||||||
* Drawing scripts run on the MoonSharp engine.
|
Example: obj.setfont("Yu Gothic UI", 48); obj.load("text", "字幕")
|
||||||
|
|
||||||
|
obj.load("image", path)
|
||||||
|
Loads an image file and replaces the buffer.
|
||||||
|
* For safety the leading header is validated and only genuine
|
||||||
|
images (PNG / JPEG / GIF / BMP / TIFF / WebP) are loaded.
|
||||||
|
Example: obj.load("image", "C:\\img\\logo.png")
|
||||||
|
|
||||||
|
obj.load("movie", path [, time])
|
||||||
|
Loads the frame at the given time of a video file and replaces
|
||||||
|
the buffer (decoded with Media Foundation).
|
||||||
|
time : Seconds. Defaults to obj.time when omitted.
|
||||||
|
* For safety the leading header is validated and only genuine
|
||||||
|
videos (MP4 / MOV / MKV / WebM / AVI / FLV / ASF) are loaded.
|
||||||
|
Example: obj.load("movie", "C:\\mov\\clip.mp4", obj.time)
|
||||||
|
|
||||||
|
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.
|
||||||
|
color : 0xRRGGBB.
|
||||||
|
Example: obj.setfont("Meiryo", 64, 1, 0xffffff)
|
||||||
|
|
||||||
|
o obj.draw([ox, oy, oz [, zoom [, alpha [, aspect]]]])
|
||||||
|
Composites the current object image onto the accumulation buffer.
|
||||||
|
Calling it multiple times draws overlapping copies (afterimages,
|
||||||
|
particles, etc.).
|
||||||
|
ox, oy, oz : Offset from the center (default 0).
|
||||||
|
zoom : 1.0 is original size (default 1.0).
|
||||||
|
alpha : 0.0 ~ 1.0 (default 1.0).
|
||||||
|
aspect : -1.0 ~ 1.0 (default 0).
|
||||||
|
* Once called, the standard draw is suppressed and the composited
|
||||||
|
result is output.
|
||||||
|
|
||||||
|
o obj.drawpoly(x0,y0,z0, x1,y1,z1, x2,y2,z2, x3,y3,z3
|
||||||
|
[, u0,v0, u1,v1, u2,v2, u3,v3 [, alpha]])
|
||||||
|
Texture-maps the object image onto a quad given by 4 vertices.
|
||||||
|
Vertex order is top-left, top-right, bottom-right, bottom-left.
|
||||||
|
When UVs are omitted the whole image is used.
|
||||||
|
* If only a 13th argument is given (UVs omitted), it is used as the
|
||||||
|
alpha (12 coordinates + alpha).
|
||||||
|
* Mapped with an affine transform (exact for parallelograms,
|
||||||
|
approximate for non-parallelograms).
|
||||||
|
|
||||||
|
o obj.copybuffer(destination, source)
|
||||||
|
Copies an image between buffers, selected by the first character.
|
||||||
|
"obj" : Object image buffer
|
||||||
|
"tmp" : Temporary buffer
|
||||||
|
"cache:name" : Named cache (kept across frames)
|
||||||
|
Example: obj.copybuffer("tmp", "obj") -- save
|
||||||
|
obj.copybuffer("obj", "tmp") -- restore
|
||||||
|
* "frm" (frame buffer / background) cannot be obtained due to the
|
||||||
|
structure of YMM4.
|
||||||
|
|
||||||
|
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.setoption(name, value) / obj.getoption(name)
|
||||||
|
Sets / gets an option. Unsupported options are accepted so they do
|
||||||
|
not stop the script (getoption returns the stored value, 0 if unset).
|
||||||
|
Options that currently affect drawing:
|
||||||
|
"antialias" : 0 = nearest neighbor, otherwise linear interpolation
|
||||||
|
(obj.draw / obj.drawpoly).
|
||||||
|
|
||||||
|
o obj.pixeloption(name, value)
|
||||||
|
Stores an option for pixel operations as state.
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
@@ -515,28 +684,65 @@
|
|||||||
A deterministic integer random function compatible with AviUtl.
|
A deterministic integer random function compatible with AviUtl.
|
||||||
See "obj Table - Functions" for details.
|
See "obj Table - Functions" for details.
|
||||||
|
|
||||||
o Figure drawing
|
o Drawing, compositing and loading
|
||||||
obj.load("figure", ...) generates a basic shape (circle, rectangle,
|
Drawing and compositing with obj.draw / obj.drawpoly, buffer
|
||||||
triangle, pentagon, hexagon, star) and replaces the object buffer
|
operations with obj.copybuffer, generation and loading with
|
||||||
with it. See "obj Table - Functions" for details.
|
obj.load("figure"/"text"/"image"/"movie"), obj.setfont, obj.effect,
|
||||||
|
obj.getvalue, and obj.setoption / obj.getoption / obj.pixeloption are
|
||||||
|
supported. See "obj Table - Functions" for details.
|
||||||
|
|
||||||
The following require integration with the rendering pipeline and are out of
|
o AviUtl / AviUtl2 compatibility map for obj.effect
|
||||||
scope for this layer. Scripts that call them will not behave as intended.
|
obj.effect("effect name", "parameter name", value, ...) first consults
|
||||||
x Drawing and compositing (obj.draw / obj.drawpoly), obj.load targets
|
the compatibility map. Effects declared as AviUtl / AviUtl2 names pass
|
||||||
other than "figure" (image files, "text", "movie", etc.) and obj.setfont
|
through the declared scale/offset conversion before reaching the YMM4
|
||||||
x Filter effects and buffer operations
|
properties. Names not declared in the map are resolved directly by the
|
||||||
(obj.effect / obj.copybuffer / obj.setoption, etc.)
|
YMM4 effect name or keyword, so existing calls keep working. The map is
|
||||||
x Module loading via require, and file access such as io
|
built as the inverse of YMM4's own AviUtl export (.exo output), so it
|
||||||
|
round-trips exactly. The target engine is selected with --!aviutl
|
||||||
|
(default) / --!aviutl2.
|
||||||
|
The effect names declared in the map and their main parameters are as
|
||||||
|
follows.
|
||||||
|
ぼかし: 範囲, サイズ固定
|
||||||
|
境界ぼかし: 範囲
|
||||||
|
方向ブラー: 範囲, 角度, サイズ固定
|
||||||
|
放射ブラー: 範囲, X, Y, サイズを固定
|
||||||
|
閃光: 範囲, X, Y, サイズを固定
|
||||||
|
クロマキー: 色相範囲, 境界補正
|
||||||
|
クリッピング: 上, 下, 左, 右, 中心の位置を変更
|
||||||
|
斜めクリッピング: 中心X, 中心Y, 角度, ぼかし, 幅
|
||||||
|
領域拡張: 上, 下, 左, 右
|
||||||
|
座標: X, Y, Z
|
||||||
|
回転: X, Y, Z
|
||||||
|
リサイズ: 拡大率, X, Y, 補間なし
|
||||||
|
画像ループ: 横回数, 縦回数
|
||||||
|
極座標変換: 中心幅, 渦巻
|
||||||
|
グラデーション: 強さ, 中心X, 中心Y, 角度, 幅
|
||||||
|
単色化: 強さ, 輝度を保持する
|
||||||
|
縁取り: サイズ, ぼかし
|
||||||
|
反転: -
|
||||||
|
モザイク: サイズ
|
||||||
|
ディスプレイスメントマップ: ぼかし
|
||||||
|
動画ファイル合成: X, Y, 拡大率
|
||||||
|
色調補正: 明るさ, コントラスト, 色相, 輝度, 彩度
|
||||||
|
色ずれ: ずれ幅, 角度, 強さ
|
||||||
|
色調補正 and 色ずれ correspond to community plugin effects.
|
||||||
|
|
||||||
|
The following are out of scope for this layer. Scripts that call them will not
|
||||||
|
behave as intended.
|
||||||
|
x Module loading via require, and arbitrary file access such as io /
|
||||||
|
dofile (image / video loading via obj.load is supported with header
|
||||||
|
validation).
|
||||||
|
x obj.setanchor, scene.set / scene.get, etc.
|
||||||
|
|
||||||
|
|
||||||
- Unsupported Features / Limitations -
|
- Unsupported Features / Limitations -
|
||||||
|
|
||||||
x obj.effect(), obj.draw(), obj.drawpoly(), etc. from AviUtl2 are not supported (only obj.load("figure", ...) is supported; see "AviUtl Script Compatibility (Partial)").
|
x obj.rand1(), obj.mes(), obj.setanchor(), etc. from AviUtl2 are not supported.
|
||||||
x obj.rand1(), obj.setfont(), obj.mes(), etc. from AviUtl2 are not supported.
|
|
||||||
x obj.setoption(), obj.getoption(), obj.getvalue(), obj.setanchor(), etc. from AviUtl2 are not supported.
|
|
||||||
x Functions such as scene.set() and scene.get() in the AviUtl2 scene table are not supported.
|
x Functions such as scene.set() and scene.get() in the AviUtl2 scene table are not supported.
|
||||||
(Only scene.width and scene.height can be read)
|
(Only scene.width and scene.height can be read)
|
||||||
x File access (require, dofile, io, etc.) is 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.
|
||||||
x Modifying obj.z is reflected in rendering (included in ReadBack),
|
x Modifying obj.z is reflected in rendering (included in ReadBack),
|
||||||
but 3D rendering support is limited.
|
but 3D rendering support is limited.
|
||||||
x If the script timeout (5 seconds) is exceeded, execution is forcibly terminated.
|
x If the script timeout (5 seconds) is exceeded, execution is forcibly terminated.
|
||||||
|
|||||||
@@ -24,6 +24,61 @@
|
|||||||
primer acceso. Omitir estas llamadas cuando no sean necesarias acelera el procesamiento.
|
primer acceso. Omitir estas llamadas cuando no sean necesarias acelera el procesamiento.
|
||||||
|
|
||||||
|
|
||||||
|
- Motores de ejecución y aceleración automática -
|
||||||
|
|
||||||
|
Los scripts que contienen procesamiento de píxeles (un bucle anidado
|
||||||
|
getpixel/setpixel) se analizan y se enrutan automáticamente a un motor
|
||||||
|
más rápido. Los scripts normales (coordenadas, rotación, opacidad, etc.)
|
||||||
|
siguen ejecutándose en MoonSharp como antes, sin cambios de comportamiento.
|
||||||
|
|
||||||
|
o Enrutamiento automático (cuando no hay directiva)
|
||||||
|
- Un mapeo por píxel autocontenido (ver condiciones abajo)
|
||||||
|
-> núcleo CPU (rápido, exacto)
|
||||||
|
- Otras operaciones de píxeles -> Nativo (LuaJIT, solo si está
|
||||||
|
desplegado)
|
||||||
|
- Sin operaciones de píxeles -> MoonSharp
|
||||||
|
|
||||||
|
o Directivas de motor (un comentario en la primera línea del script)
|
||||||
|
--!cpu : Núcleo CPU. Compilado en tiempo de ejecución a un
|
||||||
|
árbol de expresiones y ejecutado en paralelo en
|
||||||
|
todos los núcleos de la CPU (idéntico a MoonSharp).
|
||||||
|
--!gpu : Núcleo GPU. Ejecutado como un sombreador de píxeles
|
||||||
|
de Direct2D, eliminando la transferencia GPU->CPU
|
||||||
|
para máxima velocidad. Los resultados pueden diferir
|
||||||
|
levemente por la precisión float32 (opcional).
|
||||||
|
--!native : LuaJIT (proceso aparte). Rápido e idéntico a
|
||||||
|
MoonSharp. Requiere la carpeta native desplegada.
|
||||||
|
--!moonsharp : Fuerza el motor clásico MoonSharp.
|
||||||
|
* Si una directiva no está disponible o no es compatible, recurre
|
||||||
|
automáticamente a un motor inferior (la salida nunca se rompe).
|
||||||
|
|
||||||
|
o Sintaxis apta para el núcleo rápido (un mapeo por píxel puro)
|
||||||
|
Solo un bucle anidado con la forma siguiente se convierte en núcleo.
|
||||||
|
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, r2, g2, b2 [, a2])
|
||||||
|
end
|
||||||
|
end
|
||||||
|
- 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.
|
||||||
|
- 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.
|
||||||
|
|
||||||
|
Ejemplo (vuelve roja una figura blanca):
|
||||||
|
--!gpu
|
||||||
|
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 / 2, b / 2, a)
|
||||||
|
end
|
||||||
|
end
|
||||||
|
|
||||||
|
|
||||||
- Parámetros -
|
- Parámetros -
|
||||||
|
|
||||||
El panel de efectos tiene los siguientes 4 controles deslizantes (con soporte de animación).
|
El panel de efectos tiene los siguientes 4 controles deslizantes (con soporte de animación).
|
||||||
@@ -36,6 +91,38 @@
|
|||||||
|
|
||||||
* Cada control deslizante es compatible con los deslizadores de animación (con interpolación).
|
* Cada control deslizante es compatible con los deslizadores de animación (con interpolación).
|
||||||
* Los archivos .lua pueden importarse/exportarse desde la barra de herramientas del editor de scripts.
|
* Los archivos .lua pueden importarse/exportarse desde la barra de herramientas del editor de scripts.
|
||||||
|
* Las casillas (obj.check0 - obj.check3) y el color (color) aparecen en el panel de
|
||||||
|
efectos automáticamente cuando el script los referencia (las barras siempre se
|
||||||
|
muestran). Este uso general no conlleva declaración de rango/valor predeterminado,
|
||||||
|
así que gestione los rangos dentro del script. Las cabeceras --track / --check /
|
||||||
|
--color de AviUtl siguen funcionando como antes.
|
||||||
|
|
||||||
|
Hay 4 deslizadores numéricos, referenciados como obj.slider0 ~ obj.slider3.
|
||||||
|
Los valores son enteros y no contienen decimales.
|
||||||
|
|
||||||
|
Slider0 : Deslizador entero (Rango: 1 ~ 10)
|
||||||
|
Slider1 : Deslizador entero (Rango: 0 ~ 100)
|
||||||
|
Slider2 : Deslizador entero (Rango: 0 ~ 1000)
|
||||||
|
Slider3 : Deslizador entero (Rango: -1000 ~ 1000)
|
||||||
|
|
||||||
|
También hay parámetros de cadena, referenciados por los siguientes nombres.
|
||||||
|
|
||||||
|
obj.text : Cadena del campo de entrada de texto
|
||||||
|
obj.font : Nombre de fuente del selector de fuentes
|
||||||
|
obj.dir : Ruta del selector de carpetas
|
||||||
|
obj.file_video : Ruta de un archivo de video
|
||||||
|
obj.file_audio : Ruta de un archivo de audio
|
||||||
|
obj.file_image : Ruta de un archivo de imagen
|
||||||
|
obj.file_project : Ruta de un archivo de proyecto
|
||||||
|
obj.file_mp4 : Ruta de un archivo MP4
|
||||||
|
obj.file_exo : Ruta de un archivo EXO
|
||||||
|
obj.file_subtitle : Ruta de un archivo de subtítulos
|
||||||
|
obj.file_shader : Ruta de un archivo de sombreador
|
||||||
|
|
||||||
|
* Los deslizadores y los parámetros de cadena aparecen en el panel de efectos
|
||||||
|
automáticamente cuando el script los referencia.
|
||||||
|
* Una ruta de archivo puede pasarse a obj.load para cargar una imagen o un video.
|
||||||
|
* Estos parámetros están disponibles en los motores MoonSharp y nativo.
|
||||||
|
|
||||||
|
|
||||||
- Variables globales -
|
- Variables globales -
|
||||||
@@ -157,6 +244,18 @@
|
|||||||
obj.track2 : Valor actual de Track2 en el panel de efectos [Solo lectura]
|
obj.track2 : Valor actual de Track2 en el panel de efectos [Solo lectura]
|
||||||
obj.track3 : Valor actual de Track3 en el panel de efectos [Solo lectura]
|
obj.track3 : Valor actual de Track3 en el panel de efectos [Solo lectura]
|
||||||
|
|
||||||
|
o Deslizadores
|
||||||
|
obj.slider0 : Valor actual de Slider0 en el panel de efectos (entero) [Solo lectura]
|
||||||
|
obj.slider1 : Valor actual de Slider1 en el panel de efectos (entero) [Solo lectura]
|
||||||
|
obj.slider2 : Valor actual de Slider2 en el panel de efectos (entero) [Solo lectura]
|
||||||
|
obj.slider3 : Valor actual de Slider3 en el panel de efectos (entero) [Solo lectura]
|
||||||
|
|
||||||
|
o Parámetros de cadena
|
||||||
|
obj.text : Cadena del campo de entrada de texto [Solo lectura]
|
||||||
|
obj.font : Nombre de fuente del selector de fuentes [Solo lectura]
|
||||||
|
obj.dir : Ruta del selector de carpetas [Solo lectura]
|
||||||
|
obj.file_video ~ obj.file_shader : Ruta de cada selector de archivos [Solo lectura]
|
||||||
|
|
||||||
o Capa
|
o Capa
|
||||||
obj.layer : Número de capa donde se encuentra el objeto [Solo lectura]
|
obj.layer : Número de capa donde se encuentra el objeto [Solo lectura]
|
||||||
* Mismo valor que la variable global layer.
|
* Mismo valor que la variable global layer.
|
||||||
@@ -320,24 +419,95 @@
|
|||||||
Ejemplo: obj.ox = obj.ox + obj.rand(-10, 10, 1, obj.frame)
|
Ejemplo: obj.ox = obj.ox + obj.rand(-10, 10, 1, obj.frame)
|
||||||
|
|
||||||
o obj.load(target, ...)
|
o obj.load(target, ...)
|
||||||
Reemplaza el búfer del objeto con contenido generado.
|
Reemplaza el búfer del objeto con contenido generado. Se admiten los
|
||||||
En esta versión solo se admite el target "figure".
|
targets "figure", "text", "image" (archivo de imagen) y "movie"
|
||||||
|
(archivo de vídeo). 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).
|
||||||
|
|
||||||
obj.load("figure", name, color, size [, line [, aspect]])
|
obj.load("figure", name, color, size [, line [, aspect]])
|
||||||
Genera una forma y reemplaza el búfer del objeto con ella
|
Genera una forma y reemplaza el búfer (centrada).
|
||||||
(la salida se redimensiona a la forma y se centra).
|
name : 円 / 四角形 / 三角形 / 五角形 / 六角形 / 星形
|
||||||
name : Nombre de la forma. Uno de 円 / 四角形 / 三角形 /
|
(también los alias en inglés circle, rect, triangle,
|
||||||
五角形 / 六角形 / 星形 (también se aceptan los alias
|
pentagon, hexagon, star).
|
||||||
en inglés circle, rect, triangle, pentagon, hexagon, star).
|
|
||||||
color : Color de relleno 0xRRGGBB.
|
color : Color de relleno 0xRRGGBB.
|
||||||
size : Tamaño base en píxeles.
|
size : Tamaño base en píxeles.
|
||||||
line : Grosor del contorno (opcional). Omitido o 0 rellena la
|
line : Grosor del contorno (opcional). 0 rellena la forma.
|
||||||
forma; un valor igual o mayor que el tamaño también la rellena.
|
aspect : Distorsión -1.0 ~ 1.0 (opcional).
|
||||||
aspect : Distorsión -1.0 ~ 1.0 (opcional). Positivo reduce el
|
Ejemplo: obj.load("figure", "円", 0xff3366, 200)
|
||||||
ancho, negativo reduce el alto.
|
|
||||||
Ejemplo: obj.load("figure", "円", 0xff3366, 200)
|
obj.load("text", cadena)
|
||||||
* Solo se implementa obj.load("figure", ...). Otros targets
|
Dibuja la cadena con la fuente, el tamaño y el color definidos
|
||||||
(archivos de imagen, "text", "tempbuffer", "movie", etc.) no hacen nada.
|
por obj.setfont y reemplaza el búfer (con DirectWrite).
|
||||||
* Los scripts de dibujo se ejecutan en el motor MoonSharp.
|
Ejemplo: obj.setfont("Yu Gothic UI", 48); obj.load("text", "字幕")
|
||||||
|
|
||||||
|
obj.load("image", ruta)
|
||||||
|
Carga un archivo de imagen y reemplaza el búfer.
|
||||||
|
* Por seguridad se valida la cabecera inicial y solo se cargan
|
||||||
|
imágenes genuinas (PNG / JPEG / GIF / BMP / TIFF / WebP).
|
||||||
|
Ejemplo: obj.load("image", "C:\\img\\logo.png")
|
||||||
|
|
||||||
|
obj.load("movie", ruta [, tiempo])
|
||||||
|
Carga el fotograma en el tiempo indicado de un archivo de vídeo
|
||||||
|
y reemplaza el búfer (decodificado con Media Foundation).
|
||||||
|
tiempo : Segundos. Por defecto obj.time si se omite.
|
||||||
|
* Por seguridad se valida la cabecera inicial y solo se cargan
|
||||||
|
vídeos genuinos (MP4 / MOV / MKV / WebM / AVI / FLV / ASF).
|
||||||
|
Ejemplo: obj.load("movie", "C:\\mov\\clip.mp4", obj.time)
|
||||||
|
|
||||||
|
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.
|
||||||
|
color : 0xRRGGBB.
|
||||||
|
Ejemplo: obj.setfont("Meiryo", 64, 1, 0xffffff)
|
||||||
|
|
||||||
|
o obj.draw([ox, oy, oz [, zoom [, alpha [, aspect]]]])
|
||||||
|
Compone la imagen actual del objeto en el búfer de acumulación.
|
||||||
|
Llamarla varias veces dibuja copias superpuestas (estelas,
|
||||||
|
partículas, etc.).
|
||||||
|
ox, oy, oz : Desplazamiento desde el centro (por defecto 0).
|
||||||
|
zoom : 1.0 es tamaño original (por defecto 1.0).
|
||||||
|
alpha : 0.0 ~ 1.0 (por defecto 1.0).
|
||||||
|
aspect : -1.0 ~ 1.0 (por defecto 0).
|
||||||
|
* Una vez llamada, se suprime el dibujo estándar y se emite el
|
||||||
|
resultado compuesto.
|
||||||
|
|
||||||
|
o obj.drawpoly(x0,y0,z0, x1,y1,z1, x2,y2,z2, x3,y3,z3
|
||||||
|
[, u0,v0, u1,v1, u2,v2, u3,v3 [, alpha]])
|
||||||
|
Aplica la imagen del objeto como textura sobre un cuadrilátero dado por
|
||||||
|
4 vértices. El orden es superior-izq, superior-der, inferior-der,
|
||||||
|
inferior-izq. Si se omiten las UV se usa toda la imagen.
|
||||||
|
* Si solo se da un 13.º argumento (UV omitidas), se usa como alpha
|
||||||
|
(12 coordenadas + alpha).
|
||||||
|
* Se mapea con una transformación afín (exacta para paralelogramos,
|
||||||
|
aproximada para no paralelogramos).
|
||||||
|
|
||||||
|
o obj.copybuffer(destino, origen)
|
||||||
|
Copia una imagen entre búferes, seleccionado por el primer carácter.
|
||||||
|
"obj" : Búfer de imagen del objeto
|
||||||
|
"tmp" : Búfer temporal
|
||||||
|
"cache:nombre" : Caché con nombre (se conserva entre fotogramas)
|
||||||
|
Ejemplo: obj.copybuffer("tmp", "obj") -- guardar
|
||||||
|
obj.copybuffer("obj", "tmp") -- restaurar
|
||||||
|
* "frm" (búfer de fotograma / fondo) no puede obtenerse por la
|
||||||
|
estructura de YMM4.
|
||||||
|
|
||||||
|
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.setoption(nombre, valor) / obj.getoption(nombre)
|
||||||
|
Establece / obtiene una opción. Las opciones no admitidas se aceptan
|
||||||
|
para no detener el script (getoption devuelve el valor guardado, 0 si
|
||||||
|
no está establecido).
|
||||||
|
Opciones que afectan al dibujo actualmente:
|
||||||
|
"antialias" : 0 = vecino más cercano, en otro caso interpolación
|
||||||
|
lineal (obj.draw / obj.drawpoly).
|
||||||
|
|
||||||
|
o obj.pixeloption(nombre, valor)
|
||||||
|
Guarda como estado una opción para las operaciones de píxeles.
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
@@ -515,29 +685,67 @@
|
|||||||
Función de número aleatorio entero determinista compatible con AviUtl.
|
Función de número aleatorio entero determinista compatible con AviUtl.
|
||||||
Consulte "Tabla obj - Funciones" para más detalles.
|
Consulte "Tabla obj - Funciones" para más detalles.
|
||||||
|
|
||||||
o Dibujo de figuras
|
o Dibujo, composición y carga
|
||||||
obj.load("figure", ...) genera una forma básica (círculo, rectángulo,
|
Se admiten el dibujo y composición con obj.draw / obj.drawpoly, las
|
||||||
triángulo, pentágono, hexágono, estrella) y reemplaza el búfer del
|
operaciones de búfer con obj.copybuffer, la generación y carga con
|
||||||
objeto con ella. Consulte "Tabla obj - Funciones" para más detalles.
|
obj.load("figure"/"text"/"image"/"movie"), obj.setfont, obj.effect,
|
||||||
|
obj.getvalue y obj.setoption / obj.getoption / obj.pixeloption.
|
||||||
|
Consulte "Tabla obj - Funciones" para más detalles.
|
||||||
|
|
||||||
Lo siguiente requiere integración con la canalización de renderizado y, por
|
o Mapa de compatibilidad AviUtl / AviUtl2 para obj.effect
|
||||||
tanto, queda fuera del alcance de esta capa. Los scripts que lo llamen no se
|
obj.effect("nombre de efecto", "nombre de parámetro", valor, ...)
|
||||||
comportarán como se espera.
|
consulta primero el mapa de compatibilidad. Los efectos declarados como
|
||||||
x Dibujo y composición (obj.draw / obj.drawpoly), targets de obj.load
|
nombres de AviUtl / AviUtl2 pasan por la conversión de
|
||||||
distintos de "figure" (archivos de imagen, "text", "movie", etc.) y obj.setfont
|
escala/desplazamiento declarada antes de llegar a las propiedades de
|
||||||
x Efectos de filtro y operaciones de búfer
|
YMM4. Los nombres no declarados en el mapa se resuelven directamente por
|
||||||
(obj.effect / obj.copybuffer / obj.setoption, etc.)
|
el nombre de efecto o la palabra clave de YMM4, por lo que las llamadas
|
||||||
x Carga de módulos mediante require y acceso a archivos como io
|
existentes siguen funcionando. El mapa se construye como la inversa de
|
||||||
|
la propia exportación de AviUtl de YMM4 (salida .exo), por lo que es
|
||||||
|
reversible de forma exacta. El motor de destino se selecciona con
|
||||||
|
--!aviutl (predeterminado) / --!aviutl2.
|
||||||
|
Los nombres de efecto declarados en el mapa y sus parámetros principales
|
||||||
|
son los siguientes.
|
||||||
|
ぼかし: 範囲, サイズ固定
|
||||||
|
境界ぼかし: 範囲
|
||||||
|
方向ブラー: 範囲, 角度, サイズ固定
|
||||||
|
放射ブラー: 範囲, X, Y, サイズを固定
|
||||||
|
閃光: 範囲, X, Y, サイズを固定
|
||||||
|
クロマキー: 色相範囲, 境界補正
|
||||||
|
クリッピング: 上, 下, 左, 右, 中心の位置を変更
|
||||||
|
斜めクリッピング: 中心X, 中心Y, 角度, ぼかし, 幅
|
||||||
|
領域拡張: 上, 下, 左, 右
|
||||||
|
座標: X, Y, Z
|
||||||
|
回転: X, Y, Z
|
||||||
|
リサイズ: 拡大率, X, Y, 補間なし
|
||||||
|
画像ループ: 横回数, 縦回数
|
||||||
|
極座標変換: 中心幅, 渦巻
|
||||||
|
グラデーション: 強さ, 中心X, 中心Y, 角度, 幅
|
||||||
|
単色化: 強さ, 輝度を保持する
|
||||||
|
縁取り: サイズ, ぼかし
|
||||||
|
反転: -
|
||||||
|
モザイク: サイズ
|
||||||
|
ディスプレイスメントマップ: ぼかし
|
||||||
|
動画ファイル合成: X, Y, 拡大率
|
||||||
|
色調補正: 明るさ, コントラスト, 色相, 輝度, 彩度
|
||||||
|
色ずれ: ずれ幅, 角度, 強さ
|
||||||
|
色調補正 y 色ずれ corresponden a efectos del complemento de la comunidad.
|
||||||
|
|
||||||
|
Lo siguiente queda fuera del alcance de esta capa. Los scripts que lo llamen no
|
||||||
|
se comportarán como se espera.
|
||||||
|
x Carga de módulos mediante require y acceso arbitrario a archivos como
|
||||||
|
io / dofile (la carga de imagen / vídeo con obj.load sí se admite con
|
||||||
|
validación de cabecera).
|
||||||
|
x obj.setanchor, scene.set / scene.get, etc.
|
||||||
|
|
||||||
|
|
||||||
- Funciones no admitidas / Limitaciones -
|
- Funciones no admitidas / Limitaciones -
|
||||||
|
|
||||||
x obj.effect(), obj.draw(), obj.drawpoly(), etc. de AviUtl2 no son compatibles (solo se admite obj.load("figure", ...); consulte "Compatibilidad parcial con scripts de AviUtl").
|
x obj.rand1(), obj.mes(), obj.setanchor(), etc. de AviUtl2 no son compatibles.
|
||||||
x obj.rand1(), obj.setfont(), obj.mes(), etc. de AviUtl2 no son compatibles.
|
|
||||||
x obj.setoption(), obj.getoption(), obj.getvalue(), obj.setanchor(), etc. de AviUtl2 no son compatibles.
|
|
||||||
x Las funciones como scene.set() y scene.get() de la tabla scene de AviUtl2 no son compatibles.
|
x Las funciones como scene.set() y scene.get() de la tabla scene de AviUtl2 no son compatibles.
|
||||||
(Solo se pueden leer scene.width y scene.height)
|
(Solo se pueden leer scene.width y scene.height)
|
||||||
x El acceso a archivos (require, dofile, io, etc.) no es compatible.
|
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.
|
||||||
x Modificar obj.z se refleja en el renderizado (incluido en ReadBack),
|
x Modificar obj.z se refleja en el renderizado (incluido en ReadBack),
|
||||||
pero el soporte de renderizado 3D es limitado.
|
pero el soporte de renderizado 3D es limitado.
|
||||||
x Si se supera el tiempo de espera del script (5 segundos), la ejecución se termina forzosamente.
|
x Si se supera el tiempo de espera del script (5 segundos), la ejecución se termina forzosamente.
|
||||||
|
|||||||
@@ -24,6 +24,60 @@
|
|||||||
Menghilangkan panggilan ini saat tidak diperlukan akan mempercepat pemrosesan.
|
Menghilangkan panggilan ini saat tidak diperlukan akan mempercepat pemrosesan.
|
||||||
|
|
||||||
|
|
||||||
|
- Mesin Eksekusi dan Akselerasi Otomatis -
|
||||||
|
|
||||||
|
Skrip yang berisi pemrosesan piksel (loop bersarang getpixel/setpixel)
|
||||||
|
dianalisis sintaksnya dan secara otomatis dialihkan ke mesin yang lebih
|
||||||
|
cepat. Skrip biasa (koordinat, rotasi, opasitas, dll.) tetap berjalan di
|
||||||
|
MoonSharp seperti sebelumnya, tanpa perubahan perilaku.
|
||||||
|
|
||||||
|
o Pengalihan otomatis (saat tidak ada direktif)
|
||||||
|
- Pemetaan per-piksel mandiri (lihat syarat di bawah)
|
||||||
|
-> kernel CPU (cepat, tepat)
|
||||||
|
- Operasi piksel lainnya -> Native (LuaJIT, hanya jika di-deploy)
|
||||||
|
- Tanpa operasi piksel -> MoonSharp
|
||||||
|
|
||||||
|
o Direktif mesin (komentar pada baris pertama skrip)
|
||||||
|
--!cpu : Kernel CPU. Dikompilasi saat runtime menjadi pohon
|
||||||
|
ekspresi dan dijalankan paralel di semua inti CPU
|
||||||
|
(identik dengan MoonSharp).
|
||||||
|
--!gpu : Kernel GPU. Dijalankan sebagai pixel shader Direct2D,
|
||||||
|
menghilangkan transfer GPU->CPU untuk kecepatan
|
||||||
|
tertinggi. Hasil dapat sedikit berbeda karena
|
||||||
|
presisi float32 (opsional/opt-in).
|
||||||
|
--!native : LuaJIT (proses terpisah). Cepat dan identik dengan
|
||||||
|
MoonSharp. Memerlukan folder native yang di-deploy.
|
||||||
|
--!moonsharp : Memaksa mesin MoonSharp klasik.
|
||||||
|
* Jika direktif tidak tersedia/tidak didukung, secara otomatis
|
||||||
|
jatuh ke mesin yang lebih rendah (output tidak pernah rusak).
|
||||||
|
|
||||||
|
o Sintaks yang memenuhi syarat kernel cepat (pemetaan per-piksel murni)
|
||||||
|
Hanya loop bersarang dengan bentuk berikut yang menjadi kernel.
|
||||||
|
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, r2, g2, b2 [, a2])
|
||||||
|
end
|
||||||
|
end
|
||||||
|
- 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.
|
||||||
|
- 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.
|
||||||
|
|
||||||
|
Contoh (membuat figur putih menjadi merah):
|
||||||
|
--!gpu
|
||||||
|
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 / 2, b / 2, a)
|
||||||
|
end
|
||||||
|
end
|
||||||
|
|
||||||
|
|
||||||
- Parameter -
|
- Parameter -
|
||||||
|
|
||||||
Panel efek memiliki 4 trackbar berikut (mendukung animasi).
|
Panel efek memiliki 4 trackbar berikut (mendukung animasi).
|
||||||
@@ -36,6 +90,38 @@
|
|||||||
|
|
||||||
* Setiap trackbar mendukung slider animasi (dengan interpolasi).
|
* Setiap trackbar mendukung slider animasi (dengan interpolasi).
|
||||||
* File .lua dapat diimpor/diekspor dari toolbar editor skrip.
|
* File .lua dapat diimpor/diekspor dari toolbar editor skrip.
|
||||||
|
* Kotak centang (obj.check0 - obj.check3) dan warna (color) muncul di panel efek
|
||||||
|
secara otomatis saat skrip mereferensikannya (trackbar selalu ditampilkan).
|
||||||
|
Penggunaan umum ini tidak disertai deklarasi rentang/nilai default, jadi tangani
|
||||||
|
rentang nilai di dalam skrip. Header --track / --check / --color AviUtl tetap
|
||||||
|
berfungsi seperti sebelumnya.
|
||||||
|
|
||||||
|
Ada 4 slider numerik, direferensikan sebagai obj.slider0 hingga obj.slider3.
|
||||||
|
Nilainya berupa bilangan bulat dan tidak memuat desimal.
|
||||||
|
|
||||||
|
Slider0 : Slider bilangan bulat (Rentang: 1 ~ 10)
|
||||||
|
Slider1 : Slider bilangan bulat (Rentang: 0 ~ 100)
|
||||||
|
Slider2 : Slider bilangan bulat (Rentang: 0 ~ 1000)
|
||||||
|
Slider3 : Slider bilangan bulat (Rentang: -1000 ~ 1000)
|
||||||
|
|
||||||
|
Parameter string juga tersedia, direferensikan dengan nama berikut.
|
||||||
|
|
||||||
|
obj.text : String dari kolom input teks
|
||||||
|
obj.font : Nama font dari pemilih font
|
||||||
|
obj.dir : Path dari pemilih folder
|
||||||
|
obj.file_video : Path file video
|
||||||
|
obj.file_audio : Path file audio
|
||||||
|
obj.file_image : Path file gambar
|
||||||
|
obj.file_project : Path file proyek
|
||||||
|
obj.file_mp4 : Path file MP4
|
||||||
|
obj.file_exo : Path file EXO
|
||||||
|
obj.file_subtitle : Path file subtitle
|
||||||
|
obj.file_shader : Path file shader
|
||||||
|
|
||||||
|
* Slider dan parameter string muncul di panel efek secara otomatis saat skrip
|
||||||
|
mereferensikannya.
|
||||||
|
* Path file dapat diteruskan ke obj.load untuk memuat gambar atau video.
|
||||||
|
* Parameter ini tersedia pada mesin MoonSharp maupun native.
|
||||||
|
|
||||||
|
|
||||||
- Variabel Global -
|
- Variabel Global -
|
||||||
@@ -157,6 +243,18 @@
|
|||||||
obj.track2 : Nilai saat ini Track2 di panel efek [Hanya Baca]
|
obj.track2 : Nilai saat ini Track2 di panel efek [Hanya Baca]
|
||||||
obj.track3 : Nilai saat ini Track3 di panel efek [Hanya Baca]
|
obj.track3 : Nilai saat ini Track3 di panel efek [Hanya Baca]
|
||||||
|
|
||||||
|
o Slider
|
||||||
|
obj.slider0 : Nilai saat ini Slider0 di panel efek (bilangan bulat) [Hanya Baca]
|
||||||
|
obj.slider1 : Nilai saat ini Slider1 di panel efek (bilangan bulat) [Hanya Baca]
|
||||||
|
obj.slider2 : Nilai saat ini Slider2 di panel efek (bilangan bulat) [Hanya Baca]
|
||||||
|
obj.slider3 : Nilai saat ini Slider3 di panel efek (bilangan bulat) [Hanya Baca]
|
||||||
|
|
||||||
|
o Parameter string
|
||||||
|
obj.text : String dari kolom input teks [Hanya Baca]
|
||||||
|
obj.font : Nama font dari pemilih font [Hanya Baca]
|
||||||
|
obj.dir : Path dari pemilih folder [Hanya Baca]
|
||||||
|
obj.file_video ~ obj.file_shader : Path dari setiap pemilih file [Hanya Baca]
|
||||||
|
|
||||||
o Layer
|
o Layer
|
||||||
obj.layer : Nomor layer tempat objek ditempatkan [Hanya Baca]
|
obj.layer : Nomor layer tempat objek ditempatkan [Hanya Baca]
|
||||||
* Nilai yang sama dengan variabel global layer.
|
* Nilai yang sama dengan variabel global layer.
|
||||||
@@ -318,24 +416,94 @@
|
|||||||
Contoh: obj.ox = obj.ox + obj.rand(-10, 10, 1, obj.frame)
|
Contoh: obj.ox = obj.ox + obj.rand(-10, 10, 1, obj.frame)
|
||||||
|
|
||||||
o obj.load(target, ...)
|
o obj.load(target, ...)
|
||||||
Mengganti buffer objek dengan konten yang dihasilkan.
|
Mengganti buffer objek dengan konten yang dihasilkan. Target "figure",
|
||||||
Pada versi ini hanya target "figure" yang didukung.
|
"text", "image" (berkas gambar) dan "movie" (berkas video) 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).
|
||||||
|
|
||||||
obj.load("figure", name, color, size [, line [, aspect]])
|
obj.load("figure", name, color, size [, line [, aspect]])
|
||||||
Menghasilkan sebuah bentuk dan mengganti buffer objek dengannya
|
Menghasilkan bentuk dan mengganti buffer (dipusatkan).
|
||||||
(output diubah ukurannya sesuai bentuk dan dipusatkan).
|
name : 円 / 四角形 / 三角形 / 五角形 / 六角形 / 星形
|
||||||
name : Nama bentuk. Salah satu dari 円 / 四角形 / 三角形 /
|
(alias Inggris circle, rect, triangle, pentagon,
|
||||||
五角形 / 六角形 / 星形 (alias Inggris circle, rect,
|
hexagon, star juga diterima).
|
||||||
triangle, pentagon, hexagon, star juga diterima).
|
|
||||||
color : Warna isi 0xRRGGBB.
|
color : Warna isi 0xRRGGBB.
|
||||||
size : Ukuran dasar dalam piksel.
|
size : Ukuran dasar dalam piksel.
|
||||||
line : Lebar garis tepi (opsional). Dihilangkan atau 0 mengisi
|
line : Lebar garis tepi (opsional). 0 mengisi bentuk.
|
||||||
bentuk; nilai sama atau lebih besar dari ukuran juga mengisinya.
|
aspect : Distorsi -1.0 ~ 1.0 (opsional).
|
||||||
aspect : Distorsi -1.0 ~ 1.0 (opsional). Positif mengecilkan
|
Contoh: obj.load("figure", "円", 0xff3366, 200)
|
||||||
lebar, negatif mengecilkan tinggi.
|
|
||||||
Contoh: obj.load("figure", "円", 0xff3366, 200)
|
obj.load("text", string)
|
||||||
* Hanya obj.load("figure", ...) yang diimplementasikan. Target lain
|
Menggambar string dengan font, ukuran, dan warna yang diatur
|
||||||
(berkas gambar, "text", "tempbuffer", "movie", dll.) tidak melakukan apa pun.
|
oleh obj.setfont dan mengganti buffer (digambar dengan DirectWrite).
|
||||||
* Skrip penggambaran dijalankan pada mesin MoonSharp.
|
Contoh: obj.setfont("Yu Gothic UI", 48); obj.load("text", "字幕")
|
||||||
|
|
||||||
|
obj.load("image", path)
|
||||||
|
Memuat berkas gambar dan mengganti buffer.
|
||||||
|
* Demi keamanan, header awal divalidasi dan hanya gambar asli
|
||||||
|
(PNG / JPEG / GIF / BMP / TIFF / WebP) yang dimuat.
|
||||||
|
Contoh: obj.load("image", "C:\\img\\logo.png")
|
||||||
|
|
||||||
|
obj.load("movie", path [, time])
|
||||||
|
Memuat frame pada waktu tertentu dari berkas video dan mengganti
|
||||||
|
buffer (didekode dengan Media Foundation).
|
||||||
|
time : Detik. Default obj.time jika dihilangkan.
|
||||||
|
* Demi keamanan, header awal divalidasi dan hanya video asli
|
||||||
|
(MP4 / MOV / MKV / WebM / AVI / FLV / ASF) yang dimuat.
|
||||||
|
Contoh: obj.load("movie", "C:\\mov\\clip.mp4", obj.time)
|
||||||
|
|
||||||
|
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.
|
||||||
|
color : 0xRRGGBB.
|
||||||
|
Contoh: obj.setfont("Meiryo", 64, 1, 0xffffff)
|
||||||
|
|
||||||
|
o obj.draw([ox, oy, oz [, zoom [, alpha [, aspect]]]])
|
||||||
|
Mengomposit gambar objek saat ini ke buffer akumulasi.
|
||||||
|
Memanggilnya beberapa kali menggambar salinan bertumpuk (afterimage,
|
||||||
|
partikel, dll.).
|
||||||
|
ox, oy, oz : Offset dari pusat (default 0).
|
||||||
|
zoom : 1.0 adalah ukuran asli (default 1.0).
|
||||||
|
alpha : 0.0 ~ 1.0 (default 1.0).
|
||||||
|
aspect : -1.0 ~ 1.0 (default 0).
|
||||||
|
* Setelah dipanggil, penggambaran standar ditekan dan hasil komposit
|
||||||
|
dikeluarkan.
|
||||||
|
|
||||||
|
o obj.drawpoly(x0,y0,z0, x1,y1,z1, x2,y2,z2, x3,y3,z3
|
||||||
|
[, u0,v0, u1,v1, u2,v2, u3,v3 [, alpha]])
|
||||||
|
Memetakan gambar objek sebagai tekstur ke quad dari 4 verteks.
|
||||||
|
Urutan verteks: kiri-atas, kanan-atas, kanan-bawah, kiri-bawah.
|
||||||
|
Jika UV dihilangkan, seluruh gambar digunakan.
|
||||||
|
* Jika hanya argumen ke-13 yang diberikan (UV dihilangkan), nilainya
|
||||||
|
dipakai sebagai alpha (12 koordinat + alpha).
|
||||||
|
* Dipetakan dengan transformasi afin (tepat untuk jajaran genjang,
|
||||||
|
perkiraan untuk non-jajaran genjang).
|
||||||
|
|
||||||
|
o obj.copybuffer(tujuan, sumber)
|
||||||
|
Menyalin gambar antar buffer, dipilih oleh karakter pertama.
|
||||||
|
"obj" : Buffer gambar objek
|
||||||
|
"tmp" : Buffer sementara
|
||||||
|
"cache:nama" : Cache bernama (dipertahankan antar frame)
|
||||||
|
Contoh: obj.copybuffer("tmp", "obj") -- simpan
|
||||||
|
obj.copybuffer("obj", "tmp") -- pulihkan
|
||||||
|
* "frm" (buffer frame / latar) tidak dapat diperoleh karena struktur YMM4.
|
||||||
|
|
||||||
|
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.setoption(name, value) / obj.getoption(name)
|
||||||
|
Mengatur / mengambil opsi. Opsi yang tidak didukung tetap diterima
|
||||||
|
sehingga tidak menghentikan skrip (getoption mengembalikan nilai
|
||||||
|
tersimpan, 0 jika belum diatur).
|
||||||
|
Opsi yang saat ini memengaruhi penggambaran:
|
||||||
|
"antialias" : 0 = tetangga terdekat, selain itu interpolasi linear
|
||||||
|
(obj.draw / obj.drawpoly).
|
||||||
|
|
||||||
|
o obj.pixeloption(name, value)
|
||||||
|
Menyimpan opsi untuk operasi piksel sebagai status.
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
@@ -512,29 +680,65 @@
|
|||||||
Fungsi bilangan acak bulat deterministik yang kompatibel dengan AviUtl.
|
Fungsi bilangan acak bulat deterministik yang kompatibel dengan AviUtl.
|
||||||
Lihat "Tabel obj - Fungsi" untuk detailnya.
|
Lihat "Tabel obj - Fungsi" untuk detailnya.
|
||||||
|
|
||||||
o Penggambaran figur
|
o Penggambaran, komposisi, dan pemuatan
|
||||||
obj.load("figure", ...) menghasilkan bentuk dasar (lingkaran, persegi,
|
Penggambaran dan komposisi dengan obj.draw / obj.drawpoly, operasi
|
||||||
segitiga, segilima, segienam, bintang) dan mengganti buffer objek
|
buffer dengan obj.copybuffer, pembuatan dan pemuatan dengan
|
||||||
dengannya. Lihat "Tabel obj - Fungsi" untuk detailnya.
|
obj.load("figure"/"text"/"image"/"movie"), obj.setfont, obj.effect,
|
||||||
|
obj.getvalue, serta obj.setoption / obj.getoption / obj.pixeloption
|
||||||
|
didukung. Lihat "Tabel obj - Fungsi" untuk detailnya.
|
||||||
|
|
||||||
Berikut ini memerlukan integrasi dengan pipeline render sehingga berada di
|
o Peta kompatibilitas AviUtl / AviUtl2 untuk obj.effect
|
||||||
luar cakupan lapisan ini. Skrip yang memanggilnya tidak akan berperilaku
|
obj.effect("nama efek", "nama parameter", nilai, ...) pertama-tama
|
||||||
seperti yang diharapkan.
|
merujuk peta kompatibilitas. Efek yang dideklarasikan sebagai nama
|
||||||
x Penggambaran dan komposisi (obj.draw / obj.drawpoly), target obj.load
|
AviUtl / AviUtl2 melewati konversi skala/offset yang dideklarasikan
|
||||||
selain "figure" (berkas gambar, "text", "movie", dll.) dan obj.setfont
|
sebelum mencapai properti YMM4. Nama yang tidak dideklarasikan dalam peta
|
||||||
x Efek filter dan operasi buffer
|
diselesaikan langsung melalui nama efek atau kata kunci YMM4, sehingga
|
||||||
(obj.effect / obj.copybuffer / obj.setoption, dll.)
|
pemanggilan yang sudah ada tetap berfungsi. Peta ini dibuat sebagai kebalikan dari ekspor AviUtl milik YMM4
|
||||||
x Pemuatan modul melalui require, dan akses file seperti io
|
sendiri (keluaran .exo), sehingga konsisten secara bolak-balik. Mesin
|
||||||
|
target dipilih dengan --!aviutl (bawaan) / --!aviutl2.
|
||||||
|
Nama efek yang dideklarasikan dalam peta beserta parameter utamanya
|
||||||
|
adalah sebagai berikut.
|
||||||
|
ぼかし: 範囲, サイズ固定
|
||||||
|
境界ぼかし: 範囲
|
||||||
|
方向ブラー: 範囲, 角度, サイズ固定
|
||||||
|
放射ブラー: 範囲, X, Y, サイズを固定
|
||||||
|
閃光: 範囲, X, Y, サイズを固定
|
||||||
|
クロマキー: 色相範囲, 境界補正
|
||||||
|
クリッピング: 上, 下, 左, 右, 中心の位置を変更
|
||||||
|
斜めクリッピング: 中心X, 中心Y, 角度, ぼかし, 幅
|
||||||
|
領域拡張: 上, 下, 左, 右
|
||||||
|
座標: X, Y, Z
|
||||||
|
回転: X, Y, Z
|
||||||
|
リサイズ: 拡大率, X, Y, 補間なし
|
||||||
|
画像ループ: 横回数, 縦回数
|
||||||
|
極座標変換: 中心幅, 渦巻
|
||||||
|
グラデーション: 強さ, 中心X, 中心Y, 角度, 幅
|
||||||
|
単色化: 強さ, 輝度を保持する
|
||||||
|
縁取り: サイズ, ぼかし
|
||||||
|
反転: -
|
||||||
|
モザイク: サイズ
|
||||||
|
ディスプレイスメントマップ: ぼかし
|
||||||
|
動画ファイル合成: X, Y, 拡大率
|
||||||
|
色調補正: 明るさ, コントラスト, 色相, 輝度, 彩度
|
||||||
|
色ずれ: ずれ幅, 角度, 強さ
|
||||||
|
色調補正 dan 色ずれ sesuai dengan efek plugin komunitas.
|
||||||
|
|
||||||
|
Berikut ini berada di luar cakupan lapisan ini. Skrip yang memanggilnya tidak
|
||||||
|
akan berperilaku seperti yang diharapkan.
|
||||||
|
x Pemuatan modul melalui require, dan akses berkas sembarang seperti
|
||||||
|
io / dofile (pemuatan gambar / video via obj.load didukung dengan
|
||||||
|
validasi header).
|
||||||
|
x obj.setanchor, scene.set / scene.get, dll.
|
||||||
|
|
||||||
|
|
||||||
- Fitur yang Tidak Didukung / Batasan -
|
- Fitur yang Tidak Didukung / Batasan -
|
||||||
|
|
||||||
x obj.effect(), obj.draw(), obj.drawpoly(), dll. dari AviUtl2 tidak didukung (hanya obj.load("figure", ...) yang didukung; lihat "Kompatibilitas Parsial Skrip AviUtl").
|
x obj.rand1(), obj.mes(), obj.setanchor(), dll. dari AviUtl2 tidak didukung.
|
||||||
x obj.rand1(), obj.setfont(), obj.mes(), dll. dari AviUtl2 tidak didukung.
|
|
||||||
x obj.setoption(), obj.getoption(), obj.getvalue(), obj.setanchor(), dll. dari AviUtl2 tidak didukung.
|
|
||||||
x Fungsi seperti scene.set() dan scene.get() dalam tabel scene AviUtl2 tidak didukung.
|
x Fungsi seperti scene.set() dan scene.get() dalam tabel scene AviUtl2 tidak didukung.
|
||||||
(Hanya scene.width dan scene.height yang dapat dibaca)
|
(Hanya scene.width dan scene.height yang dapat dibaca)
|
||||||
x Akses file (require, dofile, io, dll.) 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.
|
||||||
x Memodifikasi obj.z tercermin dalam render (termasuk dalam ReadBack),
|
x Memodifikasi obj.z tercermin dalam render (termasuk dalam ReadBack),
|
||||||
tetapi dukungan render 3D terbatas.
|
tetapi dukungan render 3D terbatas.
|
||||||
x Jika batas waktu skrip (5 detik) terlampaui, eksekusi dihentikan paksa.
|
x Jika batas waktu skrip (5 detik) terlampaui, eksekusi dihentikan paksa.
|
||||||
|
|||||||
@@ -24,6 +24,56 @@
|
|||||||
発生します。不要な場合は呼び出しを省略することで処理を高速化できます。
|
発生します。不要な場合は呼び出しを省略することで処理を高速化できます。
|
||||||
|
|
||||||
|
|
||||||
|
- 実行エンジンと自動高速化 -
|
||||||
|
|
||||||
|
ピクセル処理(getpixel/setpixel の二重ループ)を含むスクリプトは、
|
||||||
|
構文を解析して自動的に高速なエンジンへ振り分けられます。
|
||||||
|
座標・回転・不透明度などの通常スクリプトは従来どおり MoonSharp で
|
||||||
|
実行され、挙動は一切変わりません。
|
||||||
|
|
||||||
|
○自動振り分け(ディレクティブ無しのとき)
|
||||||
|
・自ピクセル完結のピクセル写像(下記条件) → CPU カーネル(高速・厳密)
|
||||||
|
・上記以外のピクセル操作 → ネイティブ(LuaJIT, 配備時のみ)
|
||||||
|
・ピクセル操作なし → MoonSharp
|
||||||
|
|
||||||
|
○エンジン指定ディレクティブ(スクリプト先頭行のコメント)
|
||||||
|
--!cpu : CPU カーネル。式ツリーへ実行時コンパイルして
|
||||||
|
全 CPU コアで並列実行します(MoonSharp と完全一致)。
|
||||||
|
--!gpu : GPU カーネル。Direct2D ピクセルシェーダとして実行し、
|
||||||
|
GPU→CPU 転送を排して最速です。float32 精度のため
|
||||||
|
結果はごく僅かに異なり得ます(オプトイン)。
|
||||||
|
--!native : LuaJIT(別プロセス)。高速かつ MoonSharp と一致。
|
||||||
|
native フォルダの配備が必要です。
|
||||||
|
--!moonsharp : 従来の MoonSharp を強制します。
|
||||||
|
※ 指定が利用不可/非対応の場合は、自動的に下位エンジンへ
|
||||||
|
フォールバックします(出力が壊れることはありません)。
|
||||||
|
|
||||||
|
○高速カーネルが成立する構文(純粋ピクセル写像)
|
||||||
|
次の形の二重ループのみがカーネル化されます。
|
||||||
|
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, r2, g2, b2 [, a2])
|
||||||
|
end
|
||||||
|
end
|
||||||
|
・本体で使えるのは四則演算・math.*・比較・しきい値の
|
||||||
|
「条件 and 値1 or 値2」・local 変数のみです。
|
||||||
|
・参照できるのは処理中の自ピクセル(getpixel(x, y))と
|
||||||
|
obj/scene/time 等の値だけです。
|
||||||
|
・近傍参照(ぼかし等)、別座標への書き込み、getpixeldata、
|
||||||
|
getobject、テーブル/文字列操作、if 文などを含む場合は
|
||||||
|
カーネル化されず、自動的に従来エンジンで実行されます。
|
||||||
|
|
||||||
|
例(白い図形が赤くなる):
|
||||||
|
--!gpu
|
||||||
|
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 / 2, b / 2, a)
|
||||||
|
end
|
||||||
|
end
|
||||||
|
|
||||||
|
|
||||||
- パラメータ -
|
- パラメータ -
|
||||||
|
|
||||||
エフェクトパネルには以下の 4 つのトラックバー(アニメーション対応)があります。
|
エフェクトパネルには以下の 4 つのトラックバー(アニメーション対応)があります。
|
||||||
@@ -36,6 +86,37 @@
|
|||||||
|
|
||||||
※各トラックバーはアニメーションスライダーに対応しています(補間あり)。
|
※各トラックバーはアニメーションスライダーに対応しています(補間あり)。
|
||||||
※スクリプトエディタのツールバーから .lua ファイルのインポート/エクスポートが可能です。
|
※スクリプトエディタのツールバーから .lua ファイルのインポート/エクスポートが可能です。
|
||||||
|
※チェック(obj.check0〜obj.check3)とカラー(color)は、スクリプト本体でそれらを
|
||||||
|
参照すると自動的にエフェクトパネルへ表示されます(トラックバーは常に表示)。
|
||||||
|
この一般利用では範囲・既定値の宣言を伴わないため、値はスクリプト内で扱います。
|
||||||
|
--track / --check / --color ヘッダによる宣言表示も従来どおり利用できます。
|
||||||
|
|
||||||
|
数値スライダーが 4 つあり、各値は obj.slider0 ~ obj.slider3 として参照できます。
|
||||||
|
値は整数で、小数は扱いません。
|
||||||
|
|
||||||
|
Slider0 : 整数スライダー (範囲: 1 ~ 10)
|
||||||
|
Slider1 : 整数スライダー (範囲: 0 ~ 100)
|
||||||
|
Slider2 : 整数スライダー (範囲: 0 ~ 1000)
|
||||||
|
Slider3 : 整数スライダー (範囲: -1000 ~ 1000)
|
||||||
|
|
||||||
|
文字列パラメータも利用でき、各値は以下の名前で参照できます。
|
||||||
|
|
||||||
|
obj.text : テキスト入力欄の文字列
|
||||||
|
obj.font : フォント選択欄のフォント名
|
||||||
|
obj.dir : フォルダ選択欄のパス
|
||||||
|
obj.file_video : 動画ファイルのパス
|
||||||
|
obj.file_audio : 音声ファイルのパス
|
||||||
|
obj.file_image : 画像ファイルのパス
|
||||||
|
obj.file_project : プロジェクトファイルのパス
|
||||||
|
obj.file_mp4 : MP4 ファイルのパス
|
||||||
|
obj.file_exo : EXO ファイルのパス
|
||||||
|
obj.file_subtitle : 字幕ファイルのパス
|
||||||
|
obj.file_shader : シェーダーファイルのパス
|
||||||
|
|
||||||
|
※スライダーと文字列パラメータは、スクリプト本体でそれらを参照すると
|
||||||
|
自動的にエフェクトパネルへ表示されます。
|
||||||
|
※ファイル選択のパスは obj.load へ渡して画像・動画の読み込みに使えます。
|
||||||
|
※これらのパラメータは MoonSharp とネイティブのどちらのエンジンでも参照できます。
|
||||||
|
|
||||||
|
|
||||||
- グローバル変数 -
|
- グローバル変数 -
|
||||||
@@ -160,6 +241,18 @@
|
|||||||
obj.track2 : エフェクトパネルの Track2 の現在値 [ReadOnly]
|
obj.track2 : エフェクトパネルの Track2 の現在値 [ReadOnly]
|
||||||
obj.track3 : エフェクトパネルの Track3 の現在値 [ReadOnly]
|
obj.track3 : エフェクトパネルの Track3 の現在値 [ReadOnly]
|
||||||
|
|
||||||
|
○スライダー
|
||||||
|
obj.slider0 : エフェクトパネルの Slider0 の現在値(整数) [ReadOnly]
|
||||||
|
obj.slider1 : エフェクトパネルの Slider1 の現在値(整数) [ReadOnly]
|
||||||
|
obj.slider2 : エフェクトパネルの Slider2 の現在値(整数) [ReadOnly]
|
||||||
|
obj.slider3 : エフェクトパネルの Slider3 の現在値(整数) [ReadOnly]
|
||||||
|
|
||||||
|
○文字列パラメータ
|
||||||
|
obj.text : テキスト入力欄の文字列 [ReadOnly]
|
||||||
|
obj.font : フォント選択欄のフォント名 [ReadOnly]
|
||||||
|
obj.dir : フォルダ選択欄のパス [ReadOnly]
|
||||||
|
obj.file_video 〜 obj.file_shader : 各ファイル選択欄のパス [ReadOnly]
|
||||||
|
|
||||||
○レイヤー
|
○レイヤー
|
||||||
obj.layer : オブジェクトが配置されているレイヤー番号 [ReadOnly]
|
obj.layer : オブジェクトが配置されているレイヤー番号 [ReadOnly]
|
||||||
※ グローバル変数 layer と同じ値です。
|
※ グローバル変数 layer と同じ値です。
|
||||||
@@ -318,22 +411,88 @@
|
|||||||
|
|
||||||
○obj.load(対象, ...)
|
○obj.load(対象, ...)
|
||||||
オブジェクトのバッファを生成した内容に置き換えます。
|
オブジェクトのバッファを生成した内容に置き換えます。
|
||||||
本バージョンでは "figure"(図形)のみ対応します。
|
対象は "figure"(図形) / "text"(テキスト) / "image"(画像ファイル) /
|
||||||
|
"movie"(動画ファイル) に対応します。生成後 obj.w / obj.h 等は生成
|
||||||
|
サイズへ更新され、load 直後の getpixel でも参照できます。
|
||||||
|
従来エンジン・高速エンジンの両方で動作します。
|
||||||
|
|
||||||
obj.load("figure", 名前, 色, サイズ [, ライン [, アスペクト]])
|
obj.load("figure", 名前, 色, サイズ [, ライン [, アスペクト]])
|
||||||
図形を生成してオブジェクトのバッファを置き換えます
|
図形を生成してバッファを置き換えます(中心に配置)。
|
||||||
(出力は図形サイズに合わせて生成され、中心に配置されます)。
|
名前 : 円 / 四角形 / 三角形 / 五角形 / 六角形 / 星形
|
||||||
名前 : 図形名。円 / 四角形 / 三角形 / 五角形 / 六角形 /
|
(英語名 circle, rect, triangle, pentagon,
|
||||||
星形 のいずれか(英語名 circle, rect, triangle,
|
hexagon, star も使用可)。
|
||||||
pentagon, hexagon, star も使用可)。
|
|
||||||
色 : 塗り色 0xRRGGBB。
|
色 : 塗り色 0xRRGGBB。
|
||||||
サイズ : 図形の基準サイズ(ピクセル)。
|
サイズ : 図形の基準サイズ(ピクセル)。
|
||||||
ライン : 輪郭の太さ(省略可)。省略または 0 で塗りつぶし。
|
ライン : 輪郭の太さ(省略可)。0 で塗りつぶし。
|
||||||
サイズ以上の値を指定した場合も塗りつぶしになります。
|
アスペクト: 歪曲 -1.0 ~ 1.0(省略可)。
|
||||||
アスペクト: 歪曲 -1.0 ~ 1.0(省略可)。正で横幅、負で縦幅が縮みます。
|
例:obj.load("figure", "円", 0xff3366, 200)
|
||||||
例:obj.load("figure", "円", 0xff3366, 200)
|
|
||||||
※ 実装されているのは obj.load("figure", ...) のみです。画像ファイルや
|
obj.load("text", 文字列)
|
||||||
"text"・"tempbuffer"・"movie" 等の対象は何も行いません。
|
obj.setfont で指定したフォント・サイズ・色で文字列を
|
||||||
※ 描画系スクリプトは従来エンジン(MoonSharp)で実行されます。
|
描画してバッファを置き換えます(DirectWrite で描画)。
|
||||||
|
例:obj.setfont("Yu Gothic UI", 48); obj.load("text", "字幕")
|
||||||
|
|
||||||
|
obj.load("image", パス)
|
||||||
|
画像ファイルを読み込んでバッファを置き換えます。
|
||||||
|
※ 安全のため先頭ヘッダーを検証し、真正な画像
|
||||||
|
(PNG / JPEG / GIF / BMP / TIFF / WebP)のみ読み込みます。
|
||||||
|
例:obj.load("image", "C:\\img\\logo.png")
|
||||||
|
|
||||||
|
obj.load("movie", パス [, 時間])
|
||||||
|
動画ファイルの指定時間のフレームを読み込んでバッファを
|
||||||
|
置き換えます(Media Foundation で復号)。
|
||||||
|
時間 : 秒。省略時は obj.time。
|
||||||
|
※ 安全のため先頭ヘッダーを検証し、真正な動画
|
||||||
|
(MP4 / MOV / MKV / WebM / AVI / FLV / ASF)のみ
|
||||||
|
読み込みます。
|
||||||
|
例:obj.load("movie", "C:\\mov\\clip.mp4", obj.time)
|
||||||
|
|
||||||
|
○obj.setfont(フォント名 [, サイズ [, スタイル [, 色]]])
|
||||||
|
obj.load("text") で使用するフォントを設定します。
|
||||||
|
スタイル : ビット和。1=太字, 2=斜体, 3=太字+斜体。
|
||||||
|
色 : 0xRRGGBB。
|
||||||
|
例:obj.setfont("Meiryo", 64, 1, 0xffffff)
|
||||||
|
|
||||||
|
○obj.draw([ox, oy, oz [, 拡大率 [, 不透明度 [, アスペクト]]]])
|
||||||
|
現在のオブジェクト画像を蓄積バッファへ合成して描画します。
|
||||||
|
複数回呼ぶと重ねて描画されます(残像・パーティクル等)。
|
||||||
|
ox, oy, oz : 中心からのオフセット(省略時 0)。
|
||||||
|
拡大率 : 1.0 で等倍(省略時 1.0)。
|
||||||
|
不透明度 : 0.0 ~ 1.0(省略時 1.0)。
|
||||||
|
アスペクト : -1.0 ~ 1.0(省略時 0)。
|
||||||
|
※ 呼び出すと標準描画は抑制され、合成結果が出力されます。
|
||||||
|
|
||||||
|
○obj.drawpoly(x0,y0,z0, x1,y1,z1, x2,y2,z2, x3,y3,z3
|
||||||
|
[, u0,v0, u1,v1, u2,v2, u3,v3 [, 不透明度]])
|
||||||
|
4 頂点で指定した四角形へオブジェクト画像をテクスチャ描画します。
|
||||||
|
頂点は左上→右上→右下→左下の順。UV 省略時は画像全体を使用します。
|
||||||
|
※ UV を省略し 13 番目の引数のみ与えた場合、その値を不透明度として
|
||||||
|
使用します(座標 12 個 + 不透明度)。
|
||||||
|
※ アフィン変換で写像します(平行四辺形は厳密、非平行四辺形は近似)。
|
||||||
|
|
||||||
|
○obj.copybuffer(コピー先, コピー元)
|
||||||
|
バッファ間で画像をコピーします。識別子の先頭文字で判定します。
|
||||||
|
"obj" : オブジェクト画像バッファ
|
||||||
|
"tmp" : 一時バッファ
|
||||||
|
"cache:名前" : 名前付きキャッシュ(フレーム間で保持)
|
||||||
|
例:obj.copybuffer("tmp", "obj") -- 退避
|
||||||
|
obj.copybuffer("obj", "tmp") -- 復元
|
||||||
|
※ "frm"(フレームバッファ/背景)はYMM4の構造上取得できません。
|
||||||
|
|
||||||
|
○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.setoption(名前, 値) / obj.getoption(名前)
|
||||||
|
オプションを設定 / 取得します。未対応の項目も受理してスクリプトを
|
||||||
|
停止させません(getoption は設定値を返し、未設定は 0)。
|
||||||
|
現在描画へ反映される項目:
|
||||||
|
"antialias" : 0 で最近傍、それ以外で線形補間(obj.draw/drawpoly)。
|
||||||
|
|
||||||
|
○obj.pixeloption(名前, 値)
|
||||||
|
ピクセル操作のオプションを状態として保持します。
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
@@ -507,28 +666,63 @@
|
|||||||
AviUtl 互換の決定論的な整数乱数です。詳細は「obj テーブル - 関数」を
|
AviUtl 互換の決定論的な整数乱数です。詳細は「obj テーブル - 関数」を
|
||||||
参照してください。
|
参照してください。
|
||||||
|
|
||||||
○図形描画
|
○描画・合成・読み込み
|
||||||
obj.load("figure", ...) で円・四角形・三角形・五角形・六角形・星形を
|
obj.draw / obj.drawpoly による描画合成、obj.copybuffer による
|
||||||
生成し、オブジェクトのバッファを置き換えます。詳細は「obj テーブル -
|
バッファ操作、obj.load("figure"/"text"/"image"/"movie") による生成・
|
||||||
|
読み込み、obj.setfont、obj.effect、obj.getvalue、obj.setoption /
|
||||||
|
obj.getoption / obj.pixeloption に対応します。詳細は「obj テーブル -
|
||||||
関数」を参照してください。
|
関数」を参照してください。
|
||||||
|
|
||||||
次の機能は本体の描画パイプラインへの統合を要するため、この互換層では対象外です。
|
○obj.effect の AviUtl/AviUtl2 互換マップ
|
||||||
|
obj.effect("エフェクト名", "パラメータ名", 値, …) はまず互換マップを
|
||||||
|
参照します。AviUtl/AviUtl2 の名前として宣言したエフェクトは、値がマップに
|
||||||
|
定義した倍率とオフセットの変換を経て YMM4 のプロパティへ反映します。互換
|
||||||
|
マップに宣言が無い名前は、YMM4 のエフェクト名やキーワードでそのまま解決
|
||||||
|
するため、既存の呼び出しはそのまま動きます。この互換マップは、YMM4 自身が AviUtl の
|
||||||
|
.exo へ書き出す変換を逆向きにたどって作っているため、往復しても結果が
|
||||||
|
一致します。対象のエンジンは指定子 --!aviutl または --!aviutl2 で
|
||||||
|
切り替えます。指定子を書かないときは --!aviutl として扱います。
|
||||||
|
マップに宣言したエフェクト名と主なパラメータは次のとおりです。
|
||||||
|
ぼかし: 範囲, サイズ固定
|
||||||
|
境界ぼかし: 範囲
|
||||||
|
方向ブラー: 範囲, 角度, サイズ固定
|
||||||
|
放射ブラー: 範囲, X, Y, サイズを固定
|
||||||
|
閃光: 範囲, X, Y, サイズを固定
|
||||||
|
クロマキー: 色相範囲, 境界補正
|
||||||
|
クリッピング: 上, 下, 左, 右, 中心の位置を変更
|
||||||
|
斜めクリッピング: 中心X, 中心Y, 角度, ぼかし, 幅
|
||||||
|
領域拡張: 上, 下, 左, 右
|
||||||
|
座標: X, Y, Z
|
||||||
|
回転: X, Y, Z
|
||||||
|
リサイズ: 拡大率, X, Y, 補間なし
|
||||||
|
画像ループ: 横回数, 縦回数
|
||||||
|
極座標変換: 中心幅, 渦巻
|
||||||
|
グラデーション: 強さ, 中心X, 中心Y, 角度, 幅
|
||||||
|
単色化: 強さ, 輝度を保持する
|
||||||
|
縁取り: サイズ, ぼかし
|
||||||
|
反転: パラメータなし
|
||||||
|
モザイク: サイズ
|
||||||
|
ディスプレイスメントマップ: ぼかし
|
||||||
|
動画ファイル合成: X, Y, 拡大率
|
||||||
|
色調補正: 明るさ, コントラスト, 色相, 輝度, 彩度
|
||||||
|
色ずれ: ずれ幅, 角度, 強さ
|
||||||
|
色調補正 と 色ずれ はコミュニティプラグインのエフェクトに対応します。
|
||||||
|
|
||||||
|
次の機能はこの互換層では対象外です。
|
||||||
これらを呼び出すスクリプトは意図どおりには動作しません。
|
これらを呼び出すスクリプトは意図どおりには動作しません。
|
||||||
×描画・合成(obj.draw / obj.drawpoly)、obj.load の "figure" 以外の対象
|
×require によるモジュール読み込み、io / dofile などの任意ファイル
|
||||||
(画像ファイル・"text"・"movie" 等)、および obj.setfont
|
アクセス(obj.load の画像 / 動画はヘッダー検証付きで対応)。
|
||||||
×フィルタ効果やバッファ操作
|
×obj.setanchor、scene.set / scene.get 等。
|
||||||
(obj.effect / obj.copybuffer / obj.setoption など)
|
|
||||||
×require によるモジュール読み込み、io などのファイルアクセス
|
|
||||||
|
|
||||||
|
|
||||||
- 非対応・制限事項 -
|
- 非対応・制限事項 -
|
||||||
|
|
||||||
×AviUtl2 の obj.effect(), obj.draw(), obj.drawpoly() 等には対応していません(obj.load は "figure" のみ対応。「AviUtl スクリプトの部分互換」を参照)。
|
×AviUtl2 の obj.rand1(), obj.mes(), obj.setanchor() 等には対応していません。
|
||||||
×AviUtl2 の obj.rand1(), obj.setfont(), obj.mes() 等には対応していません。
|
|
||||||
×AviUtl2 の obj.setoption(), obj.getoption(), obj.getvalue(), obj.setanchor() 等には対応していません。
|
|
||||||
×AviUtl2 の scene テーブルの scene.set(), scene.get() 等の関数には対応していません。
|
×AviUtl2 の scene テーブルの scene.set(), scene.get() 等の関数には対応していません。
|
||||||
(scene.width と scene.height の読み取りのみ対応)
|
(scene.width と scene.height の読み取りのみ対応)
|
||||||
×ファイルアクセス(require, dofile, io 等)には対応していません。
|
×スクリプトからの任意ファイルアクセス(require, dofile, io 等)には対応して
|
||||||
|
いません。obj.load("image"/"movie") のみ、先頭ヘッダー検証で真正なメディアと
|
||||||
|
確認できたファイルを読み込みます。
|
||||||
×obj.z を変更した場合、描画には反映されます(ReadBack に含まれる)が、
|
×obj.z を変更した場合、描画には反映されます(ReadBack に含まれる)が、
|
||||||
3D 描画のサポートは限定的です。
|
3D 描画のサポートは限定的です。
|
||||||
×スクリプトのタイムアウト(5秒)を超えた場合、実行は強制終了されます。
|
×スクリプトのタイムアウト(5秒)を超えた場合、実行は強制終了されます。
|
||||||
|
|||||||
@@ -24,6 +24,56 @@
|
|||||||
발생합니다. 필요 없는 경우 호출을 생략하면 처리를 빠르게 할 수 있습니다.
|
발생합니다. 필요 없는 경우 호출을 생략하면 처리를 빠르게 할 수 있습니다.
|
||||||
|
|
||||||
|
|
||||||
|
- 실행 엔진과 자동 가속 -
|
||||||
|
|
||||||
|
픽셀 처리(getpixel/setpixel 이중 루프)를 포함하는 스크립트는
|
||||||
|
구문을 분석하여 자동으로 더 빠른 엔진으로 분배됩니다.
|
||||||
|
좌표・회전・불투명도 등 일반 스크립트는 기존과 동일하게 MoonSharp으로
|
||||||
|
실행되며 동작은 전혀 바뀌지 않습니다.
|
||||||
|
|
||||||
|
○ 자동 분배(디렉티브가 없을 때)
|
||||||
|
· 자기 픽셀로 완결되는 픽셀 매핑(아래 조건) → CPU 커널(고속・엄밀)
|
||||||
|
· 위 이외의 픽셀 조작 → 네이티브(LuaJIT, 배치된 경우에만)
|
||||||
|
· 픽셀 조작 없음 → MoonSharp
|
||||||
|
|
||||||
|
○ 엔진 지정 디렉티브(스크립트 첫 줄의 주석)
|
||||||
|
--!cpu : CPU 커널. 식 트리로 런타임 컴파일하여
|
||||||
|
모든 CPU 코어에서 병렬 실행합니다(MoonSharp과 완전 일치).
|
||||||
|
--!gpu : GPU 커널. Direct2D 픽셀 셰이더로 실행하여
|
||||||
|
GPU→CPU 전송을 없애 가장 빠릅니다.
|
||||||
|
float32 정밀도이므로 결과가 아주 약간 다를 수 있습니다(옵트인).
|
||||||
|
--!native : LuaJIT(별도 프로세스). 고속이며 MoonSharp과 일치.
|
||||||
|
native 폴더의 배치가 필요합니다.
|
||||||
|
--!moonsharp : 기존의 MoonSharp을 강제합니다.
|
||||||
|
※ 지정이 사용 불가/미지원인 경우 자동으로 하위 엔진으로
|
||||||
|
폴백합니다(출력이 깨지지 않습니다).
|
||||||
|
|
||||||
|
○ 고속 커널이 성립하는 구문(순수 픽셀 매핑)
|
||||||
|
다음 형태의 이중 루프만 커널화됩니다.
|
||||||
|
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, r2, g2, b2 [, a2])
|
||||||
|
end
|
||||||
|
end
|
||||||
|
· 본문에서 사용할 수 있는 것은 사칙연산・math.*・비교・임계값
|
||||||
|
「조건 and 값1 or 값2」・local 변수뿐입니다.
|
||||||
|
· 참조할 수 있는 것은 처리 중인 자기 픽셀(getpixel(x, y))과
|
||||||
|
obj/scene/time 등의 값뿐입니다.
|
||||||
|
· 이웃 참조(블러 등), 다른 좌표로의 쓰기, getpixeldata,
|
||||||
|
getobject, 테이블/문자열 조작, if 문 등을 포함하는 경우에는
|
||||||
|
커널화되지 않고 자동으로 기존 엔진에서 실행됩니다.
|
||||||
|
|
||||||
|
예(흰색 도형이 빨갛게 됨):
|
||||||
|
--!gpu
|
||||||
|
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 / 2, b / 2, a)
|
||||||
|
end
|
||||||
|
end
|
||||||
|
|
||||||
|
|
||||||
- 파라미터 -
|
- 파라미터 -
|
||||||
|
|
||||||
이펙트 패널에는 다음 4개의 트랙바(애니메이션 지원)가 있습니다.
|
이펙트 패널에는 다음 4개의 트랙바(애니메이션 지원)가 있습니다.
|
||||||
@@ -36,6 +86,36 @@
|
|||||||
|
|
||||||
※ 각 트랙바는 애니메이션 슬라이더를 지원합니다(보간 있음).
|
※ 각 트랙바는 애니메이션 슬라이더를 지원합니다(보간 있음).
|
||||||
※ 스크립트 편집기의 툴바에서 .lua 파일을 가져오기/내보내기할 수 있습니다.
|
※ 스크립트 편집기의 툴바에서 .lua 파일을 가져오기/내보내기할 수 있습니다.
|
||||||
|
※ 체크박스(obj.check0〜obj.check3)와 색상(color)은 스크립트 본문에서 참조하면
|
||||||
|
이펙트 패널에 자동으로 표시됩니다(트랙바는 항상 표시). 이 일반 사용은 범위・기본값
|
||||||
|
선언을 동반하지 않으므로 값의 범위는 스크립트 내에서 처리하세요. AviUtl의
|
||||||
|
--track / --check / --color 헤더 선언 표시도 기존과 동일하게 사용할 수 있습니다.
|
||||||
|
|
||||||
|
숫자 슬라이더가 4개 있으며, 각 값은 obj.slider0 ~ obj.slider3으로 참조할 수 있습니다.
|
||||||
|
값은 정수이며 소수는 다루지 않습니다.
|
||||||
|
|
||||||
|
Slider0 : 정수 슬라이더 (범위: 1 ~ 10)
|
||||||
|
Slider1 : 정수 슬라이더 (범위: 0 ~ 100)
|
||||||
|
Slider2 : 정수 슬라이더 (범위: 0 ~ 1000)
|
||||||
|
Slider3 : 정수 슬라이더 (범위: -1000 ~ 1000)
|
||||||
|
|
||||||
|
문자열 파라미터도 사용할 수 있으며, 각 값은 다음 이름으로 참조합니다.
|
||||||
|
|
||||||
|
obj.text : 텍스트 입력란의 문자열
|
||||||
|
obj.font : 글꼴 선택란의 글꼴 이름
|
||||||
|
obj.dir : 폴더 선택란의 경로
|
||||||
|
obj.file_video : 동영상 파일의 경로
|
||||||
|
obj.file_audio : 음성 파일의 경로
|
||||||
|
obj.file_image : 이미지 파일의 경로
|
||||||
|
obj.file_project : 프로젝트 파일의 경로
|
||||||
|
obj.file_mp4 : MP4 파일의 경로
|
||||||
|
obj.file_exo : EXO 파일의 경로
|
||||||
|
obj.file_subtitle : 자막 파일의 경로
|
||||||
|
obj.file_shader : 셰이더 파일의 경로
|
||||||
|
|
||||||
|
※슬라이더와 문자열 파라미터는 스크립트 본문에서 참조하면 이펙트 패널에 자동으로 표시됩니다.
|
||||||
|
※파일 선택 경로는 obj.load에 전달해 이미지・동영상을 불러오는 데 사용할 수 있습니다.
|
||||||
|
※이 파라미터들은 MoonSharp과 네이티브 두 엔진에서 모두 참조할 수 있습니다.
|
||||||
|
|
||||||
|
|
||||||
- 전역 변수 -
|
- 전역 변수 -
|
||||||
@@ -157,6 +237,18 @@
|
|||||||
obj.track2 : 이펙트 패널의 Track2 현재값 [읽기 전용]
|
obj.track2 : 이펙트 패널의 Track2 현재값 [읽기 전용]
|
||||||
obj.track3 : 이펙트 패널의 Track3 현재값 [읽기 전용]
|
obj.track3 : 이펙트 패널의 Track3 현재값 [읽기 전용]
|
||||||
|
|
||||||
|
○ 슬라이더
|
||||||
|
obj.slider0 : 이펙트 패널의 Slider0 현재값(정수) [읽기 전용]
|
||||||
|
obj.slider1 : 이펙트 패널의 Slider1 현재값(정수) [읽기 전용]
|
||||||
|
obj.slider2 : 이펙트 패널의 Slider2 현재값(정수) [읽기 전용]
|
||||||
|
obj.slider3 : 이펙트 패널의 Slider3 현재값(정수) [읽기 전용]
|
||||||
|
|
||||||
|
○ 문자열 파라미터
|
||||||
|
obj.text : 텍스트 입력란의 문자열 [읽기 전용]
|
||||||
|
obj.font : 글꼴 선택란의 글꼴 이름 [읽기 전용]
|
||||||
|
obj.dir : 폴더 선택란의 경로 [읽기 전용]
|
||||||
|
obj.file_video ~ obj.file_shader : 각 파일 선택란의 경로 [읽기 전용]
|
||||||
|
|
||||||
○ 레이어
|
○ 레이어
|
||||||
obj.layer : 오브젝트가 배치된 레이어 번호 [읽기 전용]
|
obj.layer : 오브젝트가 배치된 레이어 번호 [읽기 전용]
|
||||||
※ 전역 변수 layer와 동일한 값입니다.
|
※ 전역 변수 layer와 동일한 값입니다.
|
||||||
@@ -313,23 +405,88 @@
|
|||||||
예: obj.ox = obj.ox + obj.rand(-10, 10, 1, obj.frame)
|
예: obj.ox = obj.ox + obj.rand(-10, 10, 1, obj.frame)
|
||||||
|
|
||||||
○ obj.load(대상, ...)
|
○ obj.load(대상, ...)
|
||||||
오브젝트 버퍼를 생성한 내용으로 교체합니다.
|
오브젝트 버퍼를 생성한 내용으로 교체합니다. "figure"(도형) /
|
||||||
이 버전에서는 "figure"(도형)만 지원합니다.
|
"text"(텍스트) / "image"(이미지 파일) / "movie"(동영상 파일)를
|
||||||
|
지원합니다. 로드 후 obj.w / obj.h 등은 생성 크기로 갱신되며, 로드
|
||||||
|
직후의 getpixel로도 참조할 수 있습니다. 기존 엔진과 고속 엔진
|
||||||
|
양쪽에서 동작합니다.
|
||||||
|
|
||||||
obj.load("figure", 이름, 색, 크기 [, 라인 [, 종횡비]])
|
obj.load("figure", 이름, 색, 크기 [, 라인 [, 종횡비]])
|
||||||
도형을 생성하여 오브젝트 버퍼를 교체합니다
|
도형을 생성하여 버퍼를 교체합니다(중심 배치).
|
||||||
(출력은 도형 크기에 맞춰 생성되고 중심에 배치됩니다).
|
이름 : 円 / 四角形 / 三角形 / 五角形 / 六角形 / 星形
|
||||||
이름 : 도형 이름. 円 / 四角形 / 三角形 / 五角形 / 六角形 /
|
(영어 circle, rect, triangle, pentagon, hexagon,
|
||||||
星形 중 하나(영어 circle, rect, triangle,
|
star 도 사용 가능).
|
||||||
pentagon, hexagon, star 도 사용 가능).
|
색 : 채움 색 0xRRGGBB.
|
||||||
색 : 채움 색 0xRRGGBB.
|
크기 : 기준 크기(픽셀).
|
||||||
크기 : 도형의 기준 크기(픽셀).
|
라인 : 외곽선 두께(생략 가능). 0이면 채움.
|
||||||
라인 : 외곽선 두께(생략 가능). 생략 또는 0이면 채움.
|
종횡비 : 왜곡 -1.0 ~ 1.0(생략 가능).
|
||||||
크기 이상의 값을 지정한 경우에도 채움이 됩니다.
|
예: obj.load("figure", "円", 0xff3366, 200)
|
||||||
종횡비 : 왜곡 -1.0 ~ 1.0(생략 가능). 양수는 너비, 음수는 높이를 줄입니다.
|
|
||||||
예: obj.load("figure", "円", 0xff3366, 200)
|
obj.load("text", 문자열)
|
||||||
※ 구현된 것은 obj.load("figure", ...) 뿐입니다. 이미지 파일,
|
obj.setfont로 지정한 글꼴・크기・색으로 문자열을 그려
|
||||||
"text"・"tempbuffer"・"movie" 등의 대상은 아무것도 하지 않습니다.
|
버퍼를 교체합니다(DirectWrite로 그림).
|
||||||
※ 그리기 계열 스크립트는 MoonSharp 엔진에서 실행됩니다.
|
예: obj.setfont("Yu Gothic UI", 48); obj.load("text", "자막")
|
||||||
|
|
||||||
|
obj.load("image", 경로)
|
||||||
|
이미지 파일을 읽어 버퍼를 교체합니다.
|
||||||
|
※ 안전을 위해 선두 헤더를 검증하여 진짜 이미지
|
||||||
|
(PNG / JPEG / GIF / BMP / TIFF / WebP)만 읽습니다.
|
||||||
|
예: obj.load("image", "C:\\img\\logo.png")
|
||||||
|
|
||||||
|
obj.load("movie", 경로 [, 시간])
|
||||||
|
동영상 파일의 지정 시간 프레임을 읽어 버퍼를 교체합니다
|
||||||
|
(Media Foundation으로 디코딩).
|
||||||
|
시간 : 초. 생략 시 obj.time.
|
||||||
|
※ 안전을 위해 선두 헤더를 검증하여 진짜 동영상
|
||||||
|
(MP4 / MOV / MKV / WebM / AVI / FLV / ASF)만 읽습니다.
|
||||||
|
예: obj.load("movie", "C:\\mov\\clip.mp4", obj.time)
|
||||||
|
|
||||||
|
○ obj.setfont(글꼴 [, 크기 [, 스타일 [, 색]]])
|
||||||
|
obj.load("text")에서 사용할 글꼴을 설정합니다.
|
||||||
|
스타일 : 비트 플래그. 1=굵게, 2=기울임, 3=굵게+기울임.
|
||||||
|
색 : 0xRRGGBB.
|
||||||
|
예: obj.setfont("Meiryo", 64, 1, 0xffffff)
|
||||||
|
|
||||||
|
○ obj.draw([ox, oy, oz [, 확대율 [, 불투명도 [, 종횡비]]]])
|
||||||
|
현재 오브젝트 이미지를 누적 버퍼에 합성하여 그립니다.
|
||||||
|
여러 번 호출하면 겹쳐서 그려집니다(잔상・파티클 등).
|
||||||
|
ox, oy, oz : 중심으로부터의 오프셋(기본 0).
|
||||||
|
확대율 : 1.0이 등배(기본 1.0).
|
||||||
|
불투명도 : 0.0 ~ 1.0(기본 1.0).
|
||||||
|
종횡비 : -1.0 ~ 1.0(기본 0).
|
||||||
|
※ 호출하면 표준 그리기가 억제되고 합성 결과가 출력됩니다.
|
||||||
|
|
||||||
|
○ obj.drawpoly(x0,y0,z0, x1,y1,z1, x2,y2,z2, x3,y3,z3
|
||||||
|
[, u0,v0, u1,v1, u2,v2, u3,v3 [, 불투명도]])
|
||||||
|
4개 정점으로 지정한 사각형에 오브젝트 이미지를 텍스처로 그립니다.
|
||||||
|
정점 순서는 좌상→우상→우하→좌하. UV 생략 시 전체 이미지를 사용합니다.
|
||||||
|
※ UV를 생략하고 13번째 인수만 준 경우, 그 값을 불투명도로 사용합니다
|
||||||
|
(좌표 12개 + 불투명도).
|
||||||
|
※ 아핀 변환으로 매핑합니다(평행사변형은 정확, 비평행사변형은 근사).
|
||||||
|
|
||||||
|
○ obj.copybuffer(대상, 원본)
|
||||||
|
버퍼 간에 이미지를 복사합니다. 식별자의 첫 글자로 판정합니다.
|
||||||
|
"obj" : 오브젝트 이미지 버퍼
|
||||||
|
"tmp" : 임시 버퍼
|
||||||
|
"cache:이름" : 명명 캐시(프레임 간 유지)
|
||||||
|
예: obj.copybuffer("tmp", "obj") -- 저장
|
||||||
|
obj.copybuffer("obj", "tmp") -- 복원
|
||||||
|
※ "frm"(프레임 버퍼 / 배경)은 YMM4의 구조상 가져올 수 없습니다.
|
||||||
|
|
||||||
|
○ 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.setoption(이름, 값) / obj.getoption(이름)
|
||||||
|
옵션을 설정 / 가져옵니다. 지원하지 않는 항목도 받아들여
|
||||||
|
스크립트를 중단시키지 않습니다(getoption은 설정값을 반환, 미설정은 0).
|
||||||
|
현재 그리기에 반영되는 항목:
|
||||||
|
"antialias" : 0이면 최근접, 그 외는 선형 보간(obj.draw / obj.drawpoly).
|
||||||
|
|
||||||
|
○ obj.pixeloption(이름, 값)
|
||||||
|
픽셀 조작 옵션을 상태로 보존합니다.
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
@@ -503,28 +660,63 @@
|
|||||||
AviUtl 호환의 결정론적 정수 난수입니다. 자세한 내용은
|
AviUtl 호환의 결정론적 정수 난수입니다. 자세한 내용은
|
||||||
"obj 테이블 - 함수"를 참조하세요.
|
"obj 테이블 - 함수"를 참조하세요.
|
||||||
|
|
||||||
○ 도형 그리기
|
○ 그리기·합성·로드
|
||||||
obj.load("figure", ...) 로 원·사각형·삼각형·오각형·육각형·별형을
|
obj.draw / obj.drawpoly에 의한 그리기 합성, obj.copybuffer에 의한
|
||||||
생성하여 오브젝트 버퍼를 교체합니다. 자세한 내용은
|
버퍼 조작, obj.load("figure"/"text"/"image"/"movie")에 의한 생성·로드,
|
||||||
|
obj.setfont, obj.effect, obj.getvalue, 그리고 obj.setoption /
|
||||||
|
obj.getoption / obj.pixeloption을 지원합니다. 자세한 내용은
|
||||||
"obj 테이블 - 함수"를 참조하세요.
|
"obj 테이블 - 함수"를 참조하세요.
|
||||||
|
|
||||||
다음 기능은 본체의 렌더링 파이프라인과의 통합이 필요하므로 이 호환
|
○ obj.effect의 AviUtl / AviUtl2 호환 맵
|
||||||
계층의 범위 밖입니다. 이를 호출하는 스크립트는 의도대로 동작하지 않습니다.
|
obj.effect("이펙트 이름", "파라미터 이름", 값, ...)은 먼저 호환 맵을
|
||||||
× 그리기·합성(obj.draw / obj.drawpoly), obj.load의 "figure" 이외 대상
|
참조합니다. AviUtl / AviUtl2의 이름으로 선언된 이펙트는 값이 선언된
|
||||||
(이미지 파일·"text"・"movie" 등), 그리고 obj.setfont
|
배율·오프셋 변환을 거쳐 YMM4의 속성에 반영됩니다. 맵에 선언되지 않은
|
||||||
× 필터 효과 및 버퍼 조작
|
이름은 YMM4의 이펙트 이름이나 키워드로 그대로 해석되므로 기존 호출도
|
||||||
(obj.effect / obj.copybuffer / obj.setoption 등)
|
그대로 동작합니다.
|
||||||
× require에 의한 모듈 로드 및 io 등의 파일 접근
|
이 맵은 YMM4 자체의 AviUtl 내보내기(.exo 출력)의 역으로 만들어졌기 때문에
|
||||||
|
왕복해도 일치합니다. 대상 엔진은 --!aviutl(기본) / --!aviutl2로
|
||||||
|
전환합니다.
|
||||||
|
맵에 선언된 이펙트 이름과 주요 파라미터는 다음과 같습니다.
|
||||||
|
ぼかし: 範囲, サイズ固定
|
||||||
|
境界ぼかし: 範囲
|
||||||
|
方向ブラー: 範囲, 角度, サイズ固定
|
||||||
|
放射ブラー: 範囲, X, Y, サイズを固定
|
||||||
|
閃光: 範囲, X, Y, サイズを固定
|
||||||
|
クロマキー: 色相範囲, 境界補正
|
||||||
|
クリッピング: 上, 下, 左, 右, 中心の位置を変更
|
||||||
|
斜めクリッピング: 中心X, 中心Y, 角度, ぼかし, 幅
|
||||||
|
領域拡張: 上, 下, 左, 右
|
||||||
|
座標: X, Y, Z
|
||||||
|
回転: X, Y, Z
|
||||||
|
リサイズ: 拡大率, X, Y, 補間なし
|
||||||
|
画像ループ: 横回数, 縦回数
|
||||||
|
極座標変換: 中心幅, 渦巻
|
||||||
|
グラデーション: 強さ, 中心X, 中心Y, 角度, 幅
|
||||||
|
単色化: 強さ, 輝度を保持する
|
||||||
|
縁取り: サイズ, ぼかし
|
||||||
|
反転: -
|
||||||
|
モザイク: サイズ
|
||||||
|
ディスプレイスメントマップ: ぼかし
|
||||||
|
動画ファイル合成: X, Y, 拡大率
|
||||||
|
色調補正: 明るさ, コントラスト, 色相, 輝度, 彩度
|
||||||
|
色ずれ: ずれ幅, 角度, 強さ
|
||||||
|
色調補正 와 色ずれ 는 커뮤니티 플러그인의 이펙트에 대응합니다.
|
||||||
|
|
||||||
|
다음 기능은 이 호환 계층의 범위 밖입니다.
|
||||||
|
이를 호출하는 스크립트는 의도대로 동작하지 않습니다.
|
||||||
|
× require에 의한 모듈 로드 및 io / dofile 등의 임의 파일 접근
|
||||||
|
(obj.load의 이미지 / 동영상 로드는 헤더 검증과 함께 지원).
|
||||||
|
× obj.setanchor, scene.set / scene.get 등.
|
||||||
|
|
||||||
|
|
||||||
- 미지원·제한 사항 -
|
- 미지원·제한 사항 -
|
||||||
|
|
||||||
× AviUtl2의 obj.effect(), obj.draw(), obj.drawpoly() 등은 지원하지 않습니다(obj.load은 "figure"만 지원. "AviUtl 스크립트 부분 호환" 참조).
|
× AviUtl2의 obj.rand1(), obj.mes(), obj.setanchor() 등은 지원하지 않습니다.
|
||||||
× AviUtl2의 obj.rand1(), obj.setfont(), obj.mes() 등은 지원하지 않습니다.
|
|
||||||
× AviUtl2의 obj.setoption(), obj.getoption(), obj.getvalue(), obj.setanchor() 등은 지원하지 않습니다.
|
|
||||||
× AviUtl2의 scene 테이블의 scene.set(), scene.get() 등의 함수는 지원하지 않습니다.
|
× AviUtl2의 scene 테이블의 scene.set(), scene.get() 등의 함수는 지원하지 않습니다.
|
||||||
(scene.width와 scene.height의 읽기만 지원)
|
(scene.width와 scene.height의 읽기만 지원)
|
||||||
× 파일 접근(require, dofile, io 등)은 지원하지 않습니다.
|
× 스크립트에서의 임의 파일 접근(require, dofile, io 등)은 지원하지 않습니다.
|
||||||
|
obj.load("image"/"movie")만 선두 헤더 검증으로 진짜 미디어로 확인된 파일을
|
||||||
|
읽습니다.
|
||||||
× obj.z를 변경하면 렌더링에 반영되지만(ReadBack에 포함),
|
× obj.z를 변경하면 렌더링에 반영되지만(ReadBack에 포함),
|
||||||
3D 렌더링 지원은 제한적입니다.
|
3D 렌더링 지원은 제한적입니다.
|
||||||
× 스크립트 타임아웃(5초)을 초과하면 실행이 강제 종료됩니다.
|
× 스크립트 타임아웃(5초)을 초과하면 실행이 강제 종료됩니다.
|
||||||
|
|||||||
@@ -24,6 +24,55 @@
|
|||||||
不需要时省略调用可加快处理速度。
|
不需要时省略调用可加快处理速度。
|
||||||
|
|
||||||
|
|
||||||
|
- 执行引擎与自动加速 -
|
||||||
|
|
||||||
|
包含像素处理(getpixel/setpixel 双重循环)的脚本会被解析语法,
|
||||||
|
并自动分配到更快的引擎。
|
||||||
|
坐标、旋转、不透明度等普通脚本仍照旧由 MoonSharp 执行,行为不变。
|
||||||
|
|
||||||
|
○ 自动分配(未指定指令时)
|
||||||
|
· 自像素完结的像素映射(见下方条件)→ CPU 内核(高速、精确)
|
||||||
|
· 上述以外的像素操作 → 原生(LuaJIT,仅在已部署时)
|
||||||
|
· 无像素操作 → MoonSharp
|
||||||
|
|
||||||
|
○ 引擎指定指令(脚本首行的注释)
|
||||||
|
--!cpu :CPU 内核。运行时编译为表达式树,
|
||||||
|
在所有 CPU 核心上并行执行(与 MoonSharp 完全一致)。
|
||||||
|
--!gpu :GPU 内核。作为 Direct2D 像素着色器执行,
|
||||||
|
消除 GPU→CPU 传输,速度最快。
|
||||||
|
因 float32 精度,结果可能有极小差异(需主动选用)。
|
||||||
|
--!native :LuaJIT(独立进程)。高速且与 MoonSharp 一致。
|
||||||
|
需要部署 native 文件夹。
|
||||||
|
--!moonsharp :强制使用传统的 MoonSharp。
|
||||||
|
※ 指令不可用/不支持时,会自动回退到较低的引擎
|
||||||
|
(输出不会损坏)。
|
||||||
|
|
||||||
|
○ 可成为高速内核的语法(纯像素映射)
|
||||||
|
只有以下形式的双重循环才会被内核化。
|
||||||
|
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, r2, g2, b2 [, a2])
|
||||||
|
end
|
||||||
|
end
|
||||||
|
· 主体中仅可使用四则运算、math.*、比较、阈值写法
|
||||||
|
“条件 and 值1 or 值2”以及 local 变量。
|
||||||
|
· 仅可引用正在处理的自像素(getpixel(x, y))
|
||||||
|
以及 obj/scene/time 等值。
|
||||||
|
· 含有邻域参照(模糊等)、写入其他坐标、getpixeldata、
|
||||||
|
getobject、表/字符串操作、if 语句等的脚本不会被内核化,
|
||||||
|
会自动由传统引擎执行。
|
||||||
|
|
||||||
|
示例(让白色图形变红):
|
||||||
|
--!gpu
|
||||||
|
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 / 2, b / 2, a)
|
||||||
|
end
|
||||||
|
end
|
||||||
|
|
||||||
|
|
||||||
- 参数 -
|
- 参数 -
|
||||||
|
|
||||||
特效面板包含以下 4 个轨道条(支持动画)。
|
特效面板包含以下 4 个轨道条(支持动画)。
|
||||||
@@ -36,6 +85,35 @@
|
|||||||
|
|
||||||
* 每个轨道条均支持动画滑块(含插值)。
|
* 每个轨道条均支持动画滑块(含插值)。
|
||||||
* 可通过脚本编辑器工具栏导入/导出 .lua 文件。
|
* 可通过脚本编辑器工具栏导入/导出 .lua 文件。
|
||||||
|
* 复选框(obj.check0~obj.check3)与颜色(color)会在脚本本体引用它们时
|
||||||
|
自动显示在特效面板中(轨道条始终显示)。该通用用法不带范围・默认值声明,
|
||||||
|
因此请在脚本内处理取值范围。AviUtl 的 --track / --check / --color 头声明显示仍可照常使用。
|
||||||
|
|
||||||
|
共有 4 个数值滑块,各值可通过 obj.slider0 ~ obj.slider3 引用。
|
||||||
|
取值为整数,不处理小数。
|
||||||
|
|
||||||
|
Slider0 : 整数滑块 (范围: 1 ~ 10)
|
||||||
|
Slider1 : 整数滑块 (范围: 0 ~ 100)
|
||||||
|
Slider2 : 整数滑块 (范围: 0 ~ 1000)
|
||||||
|
Slider3 : 整数滑块 (范围: -1000 ~ 1000)
|
||||||
|
|
||||||
|
还可使用字符串参数,各值通过以下名称引用。
|
||||||
|
|
||||||
|
obj.text : 文本输入框的字符串
|
||||||
|
obj.font : 字体选择框的字体名
|
||||||
|
obj.dir : 文件夹选择框的路径
|
||||||
|
obj.file_video : 视频文件的路径
|
||||||
|
obj.file_audio : 音频文件的路径
|
||||||
|
obj.file_image : 图像文件的路径
|
||||||
|
obj.file_project : 项目文件的路径
|
||||||
|
obj.file_mp4 : MP4 文件的路径
|
||||||
|
obj.file_exo : EXO 文件的路径
|
||||||
|
obj.file_subtitle : 字幕文件的路径
|
||||||
|
obj.file_shader : 着色器文件的路径
|
||||||
|
|
||||||
|
※滑块与字符串参数在脚本本体引用它们时会自动显示在特效面板中。
|
||||||
|
※文件选择的路径可传给 obj.load 用于加载图像・视频。
|
||||||
|
※这些参数在 MoonSharp 与原生两种引擎中均可引用。
|
||||||
|
|
||||||
|
|
||||||
- 全局变量 -
|
- 全局变量 -
|
||||||
@@ -157,6 +235,18 @@
|
|||||||
obj.track2 : 特效面板 Track2 的当前值 [只读]
|
obj.track2 : 特效面板 Track2 的当前值 [只读]
|
||||||
obj.track3 : 特效面板 Track3 的当前值 [只读]
|
obj.track3 : 特效面板 Track3 的当前值 [只读]
|
||||||
|
|
||||||
|
○ 滑块
|
||||||
|
obj.slider0 : 特效面板 Slider0 的当前值(整数) [只读]
|
||||||
|
obj.slider1 : 特效面板 Slider1 的当前值(整数) [只读]
|
||||||
|
obj.slider2 : 特效面板 Slider2 的当前值(整数) [只读]
|
||||||
|
obj.slider3 : 特效面板 Slider3 的当前值(整数) [只读]
|
||||||
|
|
||||||
|
○ 字符串参数
|
||||||
|
obj.text : 文本输入框的字符串 [只读]
|
||||||
|
obj.font : 字体选择框的字体名 [只读]
|
||||||
|
obj.dir : 文件夹选择框的路径 [只读]
|
||||||
|
obj.file_video ~ obj.file_shader : 各文件选择框的路径 [只读]
|
||||||
|
|
||||||
○ 图层
|
○ 图层
|
||||||
obj.layer : 对象所在的图层编号 [只读]
|
obj.layer : 对象所在的图层编号 [只读]
|
||||||
* 与全局变量 layer 的值相同。
|
* 与全局变量 layer 的值相同。
|
||||||
@@ -311,22 +401,85 @@
|
|||||||
示例:obj.ox = obj.ox + obj.rand(-10, 10, 1, obj.frame)
|
示例:obj.ox = obj.ox + obj.rand(-10, 10, 1, obj.frame)
|
||||||
|
|
||||||
○ obj.load(目标, ...)
|
○ obj.load(目标, ...)
|
||||||
将对象缓冲区替换为生成的内容。本版本仅支持 "figure"(图形)。
|
将对象缓冲区替换为生成的内容。支持 "figure"(图形) / "text"(文本) /
|
||||||
|
"image"(图像文件) / "movie"(视频文件)。加载后 obj.w / obj.h 等会更新为
|
||||||
|
生成尺寸,紧接着的 getpixel 也可读取。传统引擎与高速引擎均可运行。
|
||||||
|
|
||||||
obj.load("figure", 名称, 颜色, 大小 [, 线宽 [, 纵横比]])
|
obj.load("figure", 名称, 颜色, 大小 [, 线宽 [, 纵横比]])
|
||||||
生成图形并替换对象缓冲区
|
生成图形并替换缓冲区(居中)。
|
||||||
(输出按图形大小生成并居中)。
|
名称 : 円 / 四角形 / 三角形 / 五角形 / 六角形 / 星形
|
||||||
名称 : 图形名。円 / 四角形 / 三角形 / 五角形 / 六角形 /
|
(也可用英文 circle, rect, triangle, pentagon,
|
||||||
星形 之一(也可用英文 circle, rect, triangle,
|
hexagon, star)。
|
||||||
pentagon, hexagon, star)。
|
颜色 : 填充色 0xRRGGBB。
|
||||||
颜色 : 填充色 0xRRGGBB。
|
大小 : 基准大小(像素)。
|
||||||
大小 : 图形基准大小(像素)。
|
线宽 : 轮廓宽度(可省略)。0 为填充。
|
||||||
线宽 : 轮廓宽度(可省略)。省略或 0 为填充;
|
纵横比 : 变形 -1.0 ~ 1.0(可省略)。
|
||||||
指定大于等于大小的值时也为填充。
|
示例:obj.load("figure", "円", 0xff3366, 200)
|
||||||
纵横比 : 变形 -1.0 ~ 1.0(可省略)。正值缩小宽度,负值缩小高度。
|
|
||||||
示例:obj.load("figure", "円", 0xff3366, 200)
|
obj.load("text", 字符串)
|
||||||
* 仅实现了 obj.load("figure", ...)。图像文件、"text"、"tempbuffer"、
|
以 obj.setfont 指定的字体、大小、颜色绘制字符串并替换缓冲区
|
||||||
"movie" 等目标不执行任何操作。
|
(使用 DirectWrite 绘制)。
|
||||||
* 绘制类脚本在 MoonSharp 引擎上运行。
|
示例:obj.setfont("Yu Gothic UI", 48); obj.load("text", "字幕")
|
||||||
|
|
||||||
|
obj.load("image", 路径)
|
||||||
|
加载图像文件并替换缓冲区。
|
||||||
|
※ 为安全起见会校验文件头,仅加载真正的图像
|
||||||
|
(PNG / JPEG / GIF / BMP / TIFF / WebP)。
|
||||||
|
示例:obj.load("image", "C:\\img\\logo.png")
|
||||||
|
|
||||||
|
obj.load("movie", 路径 [, 时间])
|
||||||
|
加载视频文件指定时间的帧并替换缓冲区
|
||||||
|
(使用 Media Foundation 解码)。
|
||||||
|
时间 : 秒。省略时为 obj.time。
|
||||||
|
※ 为安全起见会校验文件头,仅加载真正的视频
|
||||||
|
(MP4 / MOV / MKV / WebM / AVI / FLV / ASF)。
|
||||||
|
示例:obj.load("movie", "C:\\mov\\clip.mp4", obj.time)
|
||||||
|
|
||||||
|
○ obj.setfont(字体 [, 大小 [, 样式 [, 颜色]]])
|
||||||
|
设置 obj.load("text") 使用的字体。
|
||||||
|
样式 : 位标志。1=粗体, 2=斜体, 3=粗斜体。
|
||||||
|
颜色 : 0xRRGGBB。
|
||||||
|
示例:obj.setfont("Meiryo", 64, 1, 0xffffff)
|
||||||
|
|
||||||
|
○ obj.draw([ox, oy, oz [, 缩放 [, 不透明度 [, 纵横比]]]])
|
||||||
|
将当前对象图像合成到累积缓冲区并绘制。
|
||||||
|
多次调用会叠加绘制(残像、粒子等)。
|
||||||
|
ox, oy, oz : 相对中心的偏移(默认 0)。
|
||||||
|
缩放 : 1.0 为原始大小(默认 1.0)。
|
||||||
|
不透明度 : 0.0 ~ 1.0(默认 1.0)。
|
||||||
|
纵横比 : -1.0 ~ 1.0(默认 0)。
|
||||||
|
※ 调用后将抑制标准绘制,输出合成结果。
|
||||||
|
|
||||||
|
○ obj.drawpoly(x0,y0,z0, x1,y1,z1, x2,y2,z2, x3,y3,z3
|
||||||
|
[, u0,v0, u1,v1, u2,v2, u3,v3 [, 不透明度]])
|
||||||
|
将对象图像以纹理方式绘制到 4 个顶点指定的四边形。
|
||||||
|
顶点顺序为左上→右上→右下→左下。省略 UV 时使用整幅图像。
|
||||||
|
※ 省略 UV 而仅提供第 13 个参数时,将其用作不透明度(12 个坐标 + 不透明度)。
|
||||||
|
※ 使用仿射变换映射(平行四边形精确,非平行四边形为近似)。
|
||||||
|
|
||||||
|
○ obj.copybuffer(目标, 源)
|
||||||
|
在缓冲区之间复制图像。按标识符首字符判定。
|
||||||
|
"obj" : 对象图像缓冲区
|
||||||
|
"tmp" : 临时缓冲区
|
||||||
|
"cache:名称" : 命名缓存(跨帧保留)
|
||||||
|
示例:obj.copybuffer("tmp", "obj") -- 保存
|
||||||
|
obj.copybuffer("obj", "tmp") -- 恢复
|
||||||
|
※ 由于 YMM4 的结构,无法获取 "frm"(帧缓冲区 / 背景)。
|
||||||
|
|
||||||
|
○ 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.setoption(名称, 值) / obj.getoption(名称)
|
||||||
|
设置 / 获取选项。未支持的项目也会被接受,不会中断脚本
|
||||||
|
(getoption 返回设置值,未设置为 0)。
|
||||||
|
当前会反映到绘制的项目:
|
||||||
|
"antialias" : 0 为最近邻,其它为线性插值(obj.draw / obj.drawpoly)。
|
||||||
|
|
||||||
|
○ obj.pixeloption(名称, 值)
|
||||||
|
将像素操作的选项作为状态保存。
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
@@ -495,27 +648,59 @@
|
|||||||
○ obj.rand(st, ed [, seed [, frame]])
|
○ obj.rand(st, ed [, seed [, frame]])
|
||||||
与 AviUtl 兼容的确定性整数随机数。详情请参阅“obj 表 - 函数”。
|
与 AviUtl 兼容的确定性整数随机数。详情请参阅“obj 表 - 函数”。
|
||||||
|
|
||||||
○ 图形绘制
|
○ 绘制·合成·加载
|
||||||
obj.load("figure", ...) 生成圆、四角形、三角形、五角形、六角形、星形,
|
支持 obj.draw / obj.drawpoly 的绘制合成、obj.copybuffer 的缓冲区操作、
|
||||||
并替换对象缓冲区。详情请参阅“obj 表 - 函数”。
|
obj.load("figure"/"text"/"image"/"movie") 的生成与加载、obj.setfont、
|
||||||
|
obj.effect、obj.getvalue 以及 obj.setoption / obj.getoption /
|
||||||
|
obj.pixeloption。详情请参阅“obj 表 - 函数”。
|
||||||
|
|
||||||
以下功能需要与本体的绘制管线集成,因此不在此兼容层的范围内。
|
○ obj.effect 的 AviUtl / AviUtl2 兼容映射
|
||||||
|
obj.effect("效果名", "参数名", 值, ...) 会先查阅兼容映射。
|
||||||
|
以 AviUtl / AviUtl2 名称声明的效果,数值会经过声明的倍率/偏移转换后再写入
|
||||||
|
YMM4 的属性。映射中未声明的名称则按 YMM4 的效果名或关键字直接解析,
|
||||||
|
因此既有调用仍可正常使用。该映射是按 YMM4 自身的 AviUtl 导出
|
||||||
|
(.exo 输出) 的逆向构建的,因此往返一致。目标引擎通过 --!aviutl(默认) /
|
||||||
|
--!aviutl2 切换。
|
||||||
|
映射中声明的效果名及其主要参数如下。
|
||||||
|
ぼかし: 範囲, サイズ固定
|
||||||
|
境界ぼかし: 範囲
|
||||||
|
方向ブラー: 範囲, 角度, サイズ固定
|
||||||
|
放射ブラー: 範囲, X, Y, サイズを固定
|
||||||
|
閃光: 範囲, X, Y, サイズを固定
|
||||||
|
クロマキー: 色相範囲, 境界補正
|
||||||
|
クリッピング: 上, 下, 左, 右, 中心の位置を変更
|
||||||
|
斜めクリッピング: 中心X, 中心Y, 角度, ぼかし, 幅
|
||||||
|
領域拡張: 上, 下, 左, 右
|
||||||
|
座標: X, Y, Z
|
||||||
|
回転: X, Y, Z
|
||||||
|
リサイズ: 拡大率, X, Y, 補間なし
|
||||||
|
画像ループ: 横回数, 縦回数
|
||||||
|
極座標変換: 中心幅, 渦巻
|
||||||
|
グラデーション: 強さ, 中心X, 中心Y, 角度, 幅
|
||||||
|
単色化: 強さ, 輝度を保持する
|
||||||
|
縁取り: サイズ, ぼかし
|
||||||
|
反転: -
|
||||||
|
モザイク: サイズ
|
||||||
|
ディスプレイスメントマップ: ぼかし
|
||||||
|
動画ファイル合成: X, Y, 拡大率
|
||||||
|
色調補正: 明るさ, コントラスト, 色相, 輝度, 彩度
|
||||||
|
色ずれ: ずれ幅, 角度, 強さ
|
||||||
|
色調補正 与 色ずれ 对应社区插件的效果。
|
||||||
|
|
||||||
|
以下功能不在此兼容层的范围内。
|
||||||
调用它们的脚本不会按预期运行。
|
调用它们的脚本不会按预期运行。
|
||||||
× 绘制与合成(obj.draw / obj.drawpoly)、obj.load 的 "figure" 以外目标
|
× 通过 require 加载模块,以及 io / dofile 等任意文件访问
|
||||||
(图像文件、"text"、"movie" 等),以及 obj.setfont
|
(obj.load 的图像 / 视频加载已带文件头校验支持)。
|
||||||
× 滤镜效果与缓冲区操作
|
× obj.setanchor、scene.set / scene.get 等。
|
||||||
(obj.effect / obj.copybuffer / obj.setoption 等)
|
|
||||||
× 通过 require 加载模块,以及 io 等文件访问
|
|
||||||
|
|
||||||
|
|
||||||
- 不支持项目·限制事项 -
|
- 不支持项目·限制事项 -
|
||||||
|
|
||||||
× 不支持 AviUtl2 的 obj.effect()、obj.draw()、obj.drawpoly() 等(obj.load 仅支持 "figure",参阅“AviUtl 脚本的部分兼容”)。
|
× 不支持 AviUtl2 的 obj.rand1()、obj.mes()、obj.setanchor() 等。
|
||||||
× 不支持 AviUtl2 的 obj.rand1()、obj.setfont()、obj.mes() 等。
|
|
||||||
× 不支持 AviUtl2 的 obj.setoption()、obj.getoption()、obj.getvalue()、obj.setanchor() 等。
|
|
||||||
× 不支持 AviUtl2 scene 表中的 scene.set()、scene.get() 等函数。
|
× 不支持 AviUtl2 scene 表中的 scene.set()、scene.get() 等函数。
|
||||||
(仅支持读取 scene.width 和 scene.height)
|
(仅支持读取 scene.width 和 scene.height)
|
||||||
× 不支持文件访问(require、dofile、io 等)。
|
× 不支持脚本进行任意文件访问(require、dofile、io 等)。
|
||||||
|
仅 obj.load("image"/"movie") 会加载经文件头校验确认为真正媒体的文件。
|
||||||
× 修改 obj.z 会反映到绘制中(包含在 ReadBack 中),
|
× 修改 obj.z 会反映到绘制中(包含在 ReadBack 中),
|
||||||
但 3D 绘制支持有限。
|
但 3D 绘制支持有限。
|
||||||
× 超过脚本超时时间(5 秒)时,执行将被强制终止。
|
× 超过脚本超时时间(5 秒)时,执行将被强制终止。
|
||||||
|
|||||||
@@ -24,6 +24,55 @@
|
|||||||
不需要時省略呼叫可加快處理速度。
|
不需要時省略呼叫可加快處理速度。
|
||||||
|
|
||||||
|
|
||||||
|
- 執行引擎與自動加速 -
|
||||||
|
|
||||||
|
包含像素處理(getpixel/setpixel 雙重迴圈)的腳本會被解析語法,
|
||||||
|
並自動分配到更快的引擎。
|
||||||
|
座標、旋轉、不透明度等一般腳本仍照舊由 MoonSharp 執行,行為不變。
|
||||||
|
|
||||||
|
○ 自動分配(未指定指令時)
|
||||||
|
· 自像素完結的像素映射(見下方條件)→ CPU 核心(高速、精確)
|
||||||
|
· 上述以外的像素操作 → 原生(LuaJIT,僅在已部署時)
|
||||||
|
· 無像素操作 → MoonSharp
|
||||||
|
|
||||||
|
○ 引擎指定指令(腳本首行的註解)
|
||||||
|
--!cpu :CPU 核心。執行時編譯為運算式樹,
|
||||||
|
在所有 CPU 核心上並行執行(與 MoonSharp 完全一致)。
|
||||||
|
--!gpu :GPU 核心。作為 Direct2D 像素著色器執行,
|
||||||
|
排除 GPU→CPU 傳輸,速度最快。
|
||||||
|
因 float32 精度,結果可能有極小差異(需主動選用)。
|
||||||
|
--!native :LuaJIT(獨立程序)。高速且與 MoonSharp 一致。
|
||||||
|
需要部署 native 資料夾。
|
||||||
|
--!moonsharp :強制使用傳統的 MoonSharp。
|
||||||
|
※ 指令不可用/不支援時,會自動回退到較低的引擎
|
||||||
|
(輸出不會損壞)。
|
||||||
|
|
||||||
|
○ 可成為高速核心的語法(純像素映射)
|
||||||
|
只有以下形式的雙重迴圈才會被核心化。
|
||||||
|
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, r2, g2, b2 [, a2])
|
||||||
|
end
|
||||||
|
end
|
||||||
|
· 主體中僅可使用四則運算、math.*、比較、閾值寫法
|
||||||
|
「條件 and 值1 or 值2」以及 local 變數。
|
||||||
|
· 僅可參照正在處理的自像素(getpixel(x, y))
|
||||||
|
以及 obj/scene/time 等值。
|
||||||
|
· 含有鄰域參照(模糊等)、寫入其他座標、getpixeldata、
|
||||||
|
getobject、表/字串操作、if 陳述式等的腳本不會被核心化,
|
||||||
|
會自動由傳統引擎執行。
|
||||||
|
|
||||||
|
範例(讓白色圖形變紅):
|
||||||
|
--!gpu
|
||||||
|
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 / 2, b / 2, a)
|
||||||
|
end
|
||||||
|
end
|
||||||
|
|
||||||
|
|
||||||
- 參數 -
|
- 參數 -
|
||||||
|
|
||||||
特效面板包含以下 4 個軌道條(支援動畫)。
|
特效面板包含以下 4 個軌道條(支援動畫)。
|
||||||
@@ -36,6 +85,35 @@
|
|||||||
|
|
||||||
* 每個軌道條均支援動畫滑桿(含插值)。
|
* 每個軌道條均支援動畫滑桿(含插值)。
|
||||||
* 可透過腳本編輯器工具列匯入/匯出 .lua 檔案。
|
* 可透過腳本編輯器工具列匯入/匯出 .lua 檔案。
|
||||||
|
* 核取方塊(obj.check0~obj.check3)與顏色(color)會在腳本本體參照它們時
|
||||||
|
自動顯示於特效面板中(軌道條始終顯示)。此通用用法不帶範圍・預設值宣告,
|
||||||
|
因此請在腳本內處理取值範圍。AviUtl 的 --track / --check / --color 標頭宣告顯示仍可照常使用。
|
||||||
|
|
||||||
|
共有 4 個數值滑桿,各值可透過 obj.slider0 ~ obj.slider3 參照。
|
||||||
|
取值為整數,不處理小數。
|
||||||
|
|
||||||
|
Slider0 : 整數滑桿 (範圍: 1 ~ 10)
|
||||||
|
Slider1 : 整數滑桿 (範圍: 0 ~ 100)
|
||||||
|
Slider2 : 整數滑桿 (範圍: 0 ~ 1000)
|
||||||
|
Slider3 : 整數滑桿 (範圍: -1000 ~ 1000)
|
||||||
|
|
||||||
|
亦可使用字串參數,各值透過以下名稱參照。
|
||||||
|
|
||||||
|
obj.text : 文字輸入框的字串
|
||||||
|
obj.font : 字型選擇框的字型名
|
||||||
|
obj.dir : 資料夾選擇框的路徑
|
||||||
|
obj.file_video : 影片檔案的路徑
|
||||||
|
obj.file_audio : 音訊檔案的路徑
|
||||||
|
obj.file_image : 圖片檔案的路徑
|
||||||
|
obj.file_project : 專案檔案的路徑
|
||||||
|
obj.file_mp4 : MP4 檔案的路徑
|
||||||
|
obj.file_exo : EXO 檔案的路徑
|
||||||
|
obj.file_subtitle : 字幕檔案的路徑
|
||||||
|
obj.file_shader : 著色器檔案的路徑
|
||||||
|
|
||||||
|
※滑桿與字串參數在腳本本體參照它們時會自動顯示於特效面板中。
|
||||||
|
※檔案選擇的路徑可傳給 obj.load 用於載入圖片・影片。
|
||||||
|
※這些參數在 MoonSharp 與原生兩種引擎中皆可參照。
|
||||||
|
|
||||||
|
|
||||||
- 全域變數 -
|
- 全域變數 -
|
||||||
@@ -157,6 +235,18 @@
|
|||||||
obj.track2 : 特效面板 Track2 的當前值 [唯讀]
|
obj.track2 : 特效面板 Track2 的當前值 [唯讀]
|
||||||
obj.track3 : 特效面板 Track3 的當前值 [唯讀]
|
obj.track3 : 特效面板 Track3 的當前值 [唯讀]
|
||||||
|
|
||||||
|
○ 滑桿
|
||||||
|
obj.slider0 : 特效面板 Slider0 的當前值(整數) [唯讀]
|
||||||
|
obj.slider1 : 特效面板 Slider1 的當前值(整數) [唯讀]
|
||||||
|
obj.slider2 : 特效面板 Slider2 的當前值(整數) [唯讀]
|
||||||
|
obj.slider3 : 特效面板 Slider3 的當前值(整數) [唯讀]
|
||||||
|
|
||||||
|
○ 字串參數
|
||||||
|
obj.text : 文字輸入框的字串 [唯讀]
|
||||||
|
obj.font : 字型選擇框的字型名 [唯讀]
|
||||||
|
obj.dir : 資料夾選擇框的路徑 [唯讀]
|
||||||
|
obj.file_video ~ obj.file_shader : 各檔案選擇框的路徑 [唯讀]
|
||||||
|
|
||||||
○ 圖層
|
○ 圖層
|
||||||
obj.layer : 物件所在的圖層編號 [唯讀]
|
obj.layer : 物件所在的圖層編號 [唯讀]
|
||||||
* 與全域變數 layer 的值相同。
|
* 與全域變數 layer 的值相同。
|
||||||
@@ -311,22 +401,85 @@
|
|||||||
範例:obj.ox = obj.ox + obj.rand(-10, 10, 1, obj.frame)
|
範例:obj.ox = obj.ox + obj.rand(-10, 10, 1, obj.frame)
|
||||||
|
|
||||||
○ obj.load(目標, ...)
|
○ obj.load(目標, ...)
|
||||||
將物件緩衝區替換為產生的內容。本版本僅支援 "figure"(圖形)。
|
將物件緩衝區替換為產生的內容。支援 "figure"(圖形) / "text"(文字) /
|
||||||
|
"image"(影像檔) / "movie"(影片檔)。載入後 obj.w / obj.h 等會更新為產生
|
||||||
|
尺寸,緊接著的 getpixel 亦可讀取。傳統引擎與高速引擎皆可執行。
|
||||||
|
|
||||||
obj.load("figure", 名稱, 顏色, 大小 [, 線寬 [, 長寬比]])
|
obj.load("figure", 名稱, 顏色, 大小 [, 線寬 [, 長寬比]])
|
||||||
產生圖形並替換物件緩衝區
|
產生圖形並替換緩衝區(置中)。
|
||||||
(輸出依圖形大小產生並置中)。
|
名稱 : 円 / 四角形 / 三角形 / 五角形 / 六角形 / 星形
|
||||||
名稱 : 圖形名。円 / 四角形 / 三角形 / 五角形 / 六角形 /
|
(亦可用英文 circle, rect, triangle, pentagon,
|
||||||
星形 之一(亦可用英文 circle, rect, triangle,
|
hexagon, star)。
|
||||||
pentagon, hexagon, star)。
|
顏色 : 填滿色 0xRRGGBB。
|
||||||
顏色 : 填滿色 0xRRGGBB。
|
大小 : 基準大小(像素)。
|
||||||
大小 : 圖形基準大小(像素)。
|
線寬 : 輪廓寬度(可省略)。0 為填滿。
|
||||||
線寬 : 輪廓寬度(可省略)。省略或 0 為填滿;
|
長寬比 : 變形 -1.0 ~ 1.0(可省略)。
|
||||||
指定大於等於大小的值時亦為填滿。
|
範例:obj.load("figure", "円", 0xff3366, 200)
|
||||||
長寬比 : 變形 -1.0 ~ 1.0(可省略)。正值縮小寬度,負值縮小高度。
|
|
||||||
範例:obj.load("figure", "円", 0xff3366, 200)
|
obj.load("text", 字串)
|
||||||
* 僅實作了 obj.load("figure", ...)。影像檔、"text"、"tempbuffer"、
|
以 obj.setfont 指定的字型、大小、顏色繪製字串並替換緩衝區
|
||||||
"movie" 等目標不執行任何動作。
|
(使用 DirectWrite 繪製)。
|
||||||
* 繪製類腳本在 MoonSharp 引擎上執行。
|
範例:obj.setfont("Yu Gothic UI", 48); obj.load("text", "字幕")
|
||||||
|
|
||||||
|
obj.load("image", 路徑)
|
||||||
|
載入影像檔並替換緩衝區。
|
||||||
|
※ 為安全起見會驗證檔頭,僅載入真正的影像
|
||||||
|
(PNG / JPEG / GIF / BMP / TIFF / WebP)。
|
||||||
|
範例:obj.load("image", "C:\\img\\logo.png")
|
||||||
|
|
||||||
|
obj.load("movie", 路徑 [, 時間])
|
||||||
|
載入影片檔指定時間的影格並替換緩衝區
|
||||||
|
(使用 Media Foundation 解碼)。
|
||||||
|
時間 : 秒。省略時為 obj.time。
|
||||||
|
※ 為安全起見會驗證檔頭,僅載入真正的影片
|
||||||
|
(MP4 / MOV / MKV / WebM / AVI / FLV / ASF)。
|
||||||
|
範例:obj.load("movie", "C:\\mov\\clip.mp4", obj.time)
|
||||||
|
|
||||||
|
○ obj.setfont(字型 [, 大小 [, 樣式 [, 顏色]]])
|
||||||
|
設定 obj.load("text") 使用的字型。
|
||||||
|
樣式 : 位元旗標。1=粗體, 2=斜體, 3=粗斜體。
|
||||||
|
顏色 : 0xRRGGBB。
|
||||||
|
範例:obj.setfont("Meiryo", 64, 1, 0xffffff)
|
||||||
|
|
||||||
|
○ obj.draw([ox, oy, oz [, 縮放 [, 不透明度 [, 長寬比]]]])
|
||||||
|
將目前物件影像合成到累積緩衝區並繪製。
|
||||||
|
多次呼叫會疊加繪製(殘影、粒子等)。
|
||||||
|
ox, oy, oz : 相對中心的偏移(預設 0)。
|
||||||
|
縮放 : 1.0 為原始大小(預設 1.0)。
|
||||||
|
不透明度 : 0.0 ~ 1.0(預設 1.0)。
|
||||||
|
長寬比 : -1.0 ~ 1.0(預設 0)。
|
||||||
|
※ 呼叫後會抑制標準繪製,輸出合成結果。
|
||||||
|
|
||||||
|
○ obj.drawpoly(x0,y0,z0, x1,y1,z1, x2,y2,z2, x3,y3,z3
|
||||||
|
[, u0,v0, u1,v1, u2,v2, u3,v3 [, 不透明度]])
|
||||||
|
將物件影像以材質方式繪製到 4 個頂點指定的四邊形。
|
||||||
|
頂點順序為左上→右上→右下→左下。省略 UV 時使用整幅影像。
|
||||||
|
※ 省略 UV 而僅提供第 13 個引數時,將其作為不透明度(12 個座標 + 不透明度)。
|
||||||
|
※ 使用仿射變換對應(平行四邊形精確,非平行四邊形為近似)。
|
||||||
|
|
||||||
|
○ obj.copybuffer(目標, 來源)
|
||||||
|
在緩衝區之間複製影像。依識別字首字元判定。
|
||||||
|
"obj" : 物件影像緩衝區
|
||||||
|
"tmp" : 暫存緩衝區
|
||||||
|
"cache:名稱" : 具名快取(跨影格保留)
|
||||||
|
範例:obj.copybuffer("tmp", "obj") -- 儲存
|
||||||
|
obj.copybuffer("obj", "tmp") -- 還原
|
||||||
|
※ 由於 YMM4 的結構,無法取得 "frm"(影格緩衝區 / 背景)。
|
||||||
|
|
||||||
|
○ 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.setoption(名稱, 值) / obj.getoption(名稱)
|
||||||
|
設定 / 取得選項。未支援的項目也會被接受,不會中斷腳本
|
||||||
|
(getoption 回傳設定值,未設定為 0)。
|
||||||
|
目前會反映到繪製的項目:
|
||||||
|
"antialias" : 0 為最近鄰,其它為線性內插(obj.draw / obj.drawpoly)。
|
||||||
|
|
||||||
|
○ obj.pixeloption(名稱, 值)
|
||||||
|
將像素操作的選項作為狀態保存。
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
@@ -495,27 +648,59 @@
|
|||||||
○ obj.rand(st, ed [, seed [, frame]])
|
○ obj.rand(st, ed [, seed [, frame]])
|
||||||
與 AviUtl 相容的確定性整數亂數。詳情請參閱「obj 表 - 函式」。
|
與 AviUtl 相容的確定性整數亂數。詳情請參閱「obj 表 - 函式」。
|
||||||
|
|
||||||
○ 圖形繪製
|
○ 繪製·合成·載入
|
||||||
obj.load("figure", ...) 產生圓、四角形、三角形、五角形、六角形、星形,
|
支援 obj.draw / obj.drawpoly 的繪製合成、obj.copybuffer 的緩衝區操作、
|
||||||
並替換物件緩衝區。詳情請參閱「obj 表 - 函式」。
|
obj.load("figure"/"text"/"image"/"movie") 的產生與載入、obj.setfont、
|
||||||
|
obj.effect、obj.getvalue 以及 obj.setoption / obj.getoption /
|
||||||
|
obj.pixeloption。詳情請參閱「obj 表 - 函式」。
|
||||||
|
|
||||||
以下功能需要與本體的繪製管線整合,因此不在此相容層的範圍內。
|
○ obj.effect 的 AviUtl / AviUtl2 相容對應表
|
||||||
|
obj.effect("效果名", "參數名", 值, ...) 會先查閱相容對應表。
|
||||||
|
以 AviUtl / AviUtl2 名稱宣告的效果,數值會經過宣告的倍率/位移轉換後再寫入
|
||||||
|
YMM4 的屬性。對應表中未宣告的名稱則依 YMM4 的效果名或關鍵字直接解析,
|
||||||
|
因此既有呼叫仍可正常使用。此對應表是依 YMM4 自身的 AviUtl 匯出
|
||||||
|
(.exo 輸出) 的逆向建構的,因此往返一致。目標引擎透過 --!aviutl(預設) /
|
||||||
|
--!aviutl2 切換。
|
||||||
|
對應表中宣告的效果名及其主要參數如下。
|
||||||
|
ぼかし: 範囲, サイズ固定
|
||||||
|
境界ぼかし: 範囲
|
||||||
|
方向ブラー: 範囲, 角度, サイズ固定
|
||||||
|
放射ブラー: 範囲, X, Y, サイズを固定
|
||||||
|
閃光: 範囲, X, Y, サイズを固定
|
||||||
|
クロマキー: 色相範囲, 境界補正
|
||||||
|
クリッピング: 上, 下, 左, 右, 中心の位置を変更
|
||||||
|
斜めクリッピング: 中心X, 中心Y, 角度, ぼかし, 幅
|
||||||
|
領域拡張: 上, 下, 左, 右
|
||||||
|
座標: X, Y, Z
|
||||||
|
回転: X, Y, Z
|
||||||
|
リサイズ: 拡大率, X, Y, 補間なし
|
||||||
|
画像ループ: 横回数, 縦回数
|
||||||
|
極座標変換: 中心幅, 渦巻
|
||||||
|
グラデーション: 強さ, 中心X, 中心Y, 角度, 幅
|
||||||
|
単色化: 強さ, 輝度を保持する
|
||||||
|
縁取り: サイズ, ぼかし
|
||||||
|
反転: -
|
||||||
|
モザイク: サイズ
|
||||||
|
ディスプレイスメントマップ: ぼかし
|
||||||
|
動画ファイル合成: X, Y, 拡大率
|
||||||
|
色調補正: 明るさ, コントラスト, 色相, 輝度, 彩度
|
||||||
|
色ずれ: ずれ幅, 角度, 強さ
|
||||||
|
色調補正 與 色ずれ 對應社群外掛的效果。
|
||||||
|
|
||||||
|
以下功能不在此相容層的範圍內。
|
||||||
呼叫它們的腳本不會如預期運作。
|
呼叫它們的腳本不會如預期運作。
|
||||||
× 繪製與合成(obj.draw / obj.drawpoly)、obj.load 的 "figure" 以外目標
|
× 透過 require 載入模組,以及 io / dofile 等任意檔案存取
|
||||||
(影像檔、"text"、"movie" 等),以及 obj.setfont
|
(obj.load 的影像 / 影片載入已附檔頭驗證支援)。
|
||||||
× 濾鏡效果與緩衝區操作
|
× obj.setanchor、scene.set / scene.get 等。
|
||||||
(obj.effect / obj.copybuffer / obj.setoption 等)
|
|
||||||
× 透過 require 載入模組,以及 io 等檔案存取
|
|
||||||
|
|
||||||
|
|
||||||
- 不支援項目·限制事項 -
|
- 不支援項目·限制事項 -
|
||||||
|
|
||||||
× 不支援 AviUtl2 的 obj.effect()、obj.draw()、obj.drawpoly() 等(obj.load 僅支援 "figure",參閱「AviUtl 腳本的部分相容」)。
|
× 不支援 AviUtl2 的 obj.rand1()、obj.mes()、obj.setanchor() 等。
|
||||||
× 不支援 AviUtl2 的 obj.rand1()、obj.setfont()、obj.mes() 等。
|
|
||||||
× 不支援 AviUtl2 的 obj.setoption()、obj.getoption()、obj.getvalue()、obj.setanchor() 等。
|
|
||||||
× 不支援 AviUtl2 scene 表中的 scene.set()、scene.get() 等函式。
|
× 不支援 AviUtl2 scene 表中的 scene.set()、scene.get() 等函式。
|
||||||
(僅支援讀取 scene.width 和 scene.height)
|
(僅支援讀取 scene.width 和 scene.height)
|
||||||
× 不支援檔案存取(require、dofile、io 等)。
|
× 不支援腳本進行任意檔案存取(require、dofile、io 等)。
|
||||||
|
僅 obj.load("image"/"movie") 會載入經檔頭驗證確認為真正媒體的檔案。
|
||||||
× 修改 obj.z 會反映至繪製中(包含在 ReadBack 中),
|
× 修改 obj.z 會反映至繪製中(包含在 ReadBack 中),
|
||||||
但 3D 繪製支援有限。
|
但 3D 繪製支援有限。
|
||||||
× 超過腳本逾時時間(5 秒)時,執行將被強制終止。
|
× 超過腳本逾時時間(5 秒)時,執行將被強制終止。
|
||||||
|
|||||||
@@ -11,7 +11,7 @@ YukkuriMovieMaker4(YMM4)上で動作する、**Luaスクリプトでオブ
|
|||||||
|
|
||||||
座標・拡縮・回転・不透明度の制御に加えて、`obj.getpixel` / `obj.setpixel` / `obj.getpixeldata` によるピクセル単位の画像加工、アニメーション制作向けの数学ユーティリティ群(`anim` テーブル)、4 系統のトラックバー(Track0〜Track3)によるスクリプトへのパラメータ受け渡しに対応しています。
|
座標・拡縮・回転・不透明度の制御に加えて、`obj.getpixel` / `obj.setpixel` / `obj.getpixeldata` によるピクセル単位の画像加工、アニメーション制作向けの数学ユーティリティ群(`anim` テーブル)、4 系統のトラックバー(Track0〜Track3)によるスクリプトへのパラメータ受け渡しに対応しています。
|
||||||
|
|
||||||

|

|
||||||
|
|
||||||
---
|
---
|
||||||
|
|
||||||
@@ -76,7 +76,7 @@ YukkuriMovieMaker4(YMM4)上で動作する、**Luaスクリプトでオブ
|
|||||||
|
|
||||||
### 1. スクリプトエンジン
|
### 1. スクリプトエンジン
|
||||||
|
|
||||||
スクリプトの実行エンジンには MoonSharp(Lua 5.2 互換)を使用しています。加えて、ピクセル操作(`obj.getpixel` / `obj.setpixel` / `obj.getpixeldata`)を含むスクリプトは、同梱した高速ランタイム(LuaJIT)で自動的に実行され、大幅に高速化されます(詳細は[実行エンジンの自動振り分け](#実行エンジンの自動振り分け)を参照)。どちらのエンジンでも利用可能な標準ライブラリは以下に限定されています。
|
スクリプトの実行エンジンには MoonSharp(Lua 5.2 互換)を使用しています。加えて、自ピクセル完結のピクセル写像(`obj.getpixel` で読み取り `obj.setpixel` で書き戻す二重ループ)は構文解析で検出して **CPU カーネル(式ツリー)** または **GPU カーネル(Direct2D ピクセルシェーダ)** へ実行時コンパイルして高速化し、それ以外のピクセル操作を含むスクリプトは同梱の高速ランタイム(**LuaJIT**)で自動実行されます(詳細は[実行エンジンの自動振り分け](#実行エンジンの自動振り分け)を参照)。いずれのエンジンでも利用可能な標準ライブラリは以下に限定されています。
|
||||||
|
|
||||||
- `table`、`string`、`math`、`bit32`
|
- `table`、`string`、`math`、`bit32`
|
||||||
- 基本関数: `type`、`tostring`、`tonumber`、`select`、`error`、`assert`、`print`、`ipairs`、`pairs`、`next`、`unpack`、`setmetatable`、`getmetatable`、`rawget`、`rawset`、`rawequal`、`rawlen`、`pcall`、`xpcall`
|
- 基本関数: `type`、`tostring`、`tonumber`、`select`、`error`、`assert`、`print`、`ipairs`、`pairs`、`next`、`unpack`、`setmetatable`、`getmetatable`、`rawget`、`rawset`、`rawequal`、`rawlen`、`pcall`、`xpcall`
|
||||||
@@ -98,6 +98,9 @@ YukkuriMovieMaker4(YMM4)上で動作する、**Luaスクリプトでオブ
|
|||||||
| `obj.rxr`, `obj.ryr`, `obj.rzr` | 変更可 | 回転角(ラジアン)。同名の度数版より優先して反映される |
|
| `obj.rxr`, `obj.ryr`, `obj.rzr` | 変更可 | 回転角(ラジアン)。同名の度数版より優先して反映される |
|
||||||
| `obj.w`, `obj.h`, `obj.hw`, `obj.hh`, `obj.cx`, `obj.cy`, `obj.cz`, `obj.diagonal` | 読み取り専用 | 入力画像のサイズ・中心座標・対角線長 |
|
| `obj.w`, `obj.h`, `obj.hw`, `obj.hh`, `obj.cx`, `obj.cy`, `obj.cz`, `obj.diagonal` | 読み取り専用 | 入力画像のサイズ・中心座標・対角線長 |
|
||||||
| `obj.track0`〜`obj.track3` | 読み取り専用 | トラックバーの現在値(後述) |
|
| `obj.track0`〜`obj.track3` | 読み取り専用 | トラックバーの現在値(後述) |
|
||||||
|
| `obj.slider0`〜`obj.slider3` | 読み取り専用 | 整数スライダーの現在値(後述) |
|
||||||
|
| `obj.text`, `obj.font`, `obj.dir` | 読み取り専用 | テキスト入力欄の文字列、フォント名、フォルダパス(後述) |
|
||||||
|
| `obj.file_video`〜`obj.file_shader` | 読み取り専用 | 各ファイル選択欄のパス(後述) |
|
||||||
| `obj.time`, `obj.frame`, `obj.totalframe`, `obj.totaltime`, `obj.t`, `obj.framerate`, `obj.layer`, `obj.index`, `obj.num` | 読み取り専用 | 時間・フレーム・レイヤー等の情報 |
|
| `obj.time`, `obj.frame`, `obj.totalframe`, `obj.totaltime`, `obj.t`, `obj.framerate`, `obj.layer`, `obj.index`, `obj.num` | 読み取り専用 | 時間・フレーム・レイヤー等の情報 |
|
||||||
|
|
||||||
### 3. ピクセル操作機能
|
### 3. ピクセル操作機能
|
||||||
@@ -110,7 +113,7 @@ YukkuriMovieMaker4(YMM4)上で動作する、**Luaスクリプトでオブ
|
|||||||
- **`obj.putpixeldata()`**: 互換性のために定義された空実装関数です。`setpixel` / `PixelDataProxy:set` による変更は自動的に反映されるため、呼び出す必要はありません。
|
- **`obj.putpixeldata()`**: 互換性のために定義された空実装関数です。`setpixel` / `PixelDataProxy:set` による変更は自動的に反映されるため、呼び出す必要はありません。
|
||||||
`getpixel` / `setpixel` / `getpixeldata` のいずれかを最初に呼び出した時点で、GPU 上の画像データを CPU 側へ転送する処理が一度だけ発生します。ピクセル操作を行わないスクリプトではこの転送は発生しません。
|
`getpixel` / `setpixel` / `getpixeldata` のいずれかを最初に呼び出した時点で、GPU 上の画像データを CPU 側へ転送する処理が一度だけ発生します。ピクセル操作を行わないスクリプトではこの転送は発生しません。
|
||||||
|
|
||||||
これらのピクセル操作を含むスクリプトは、同梱の高速ランタイム(LuaJIT)で自動的に実行され、従来エンジンに比べて大幅(内部計測で数十倍)に高速化されます。出力結果は従来エンジンと一致します。詳細・制約は[実行エンジンの自動振り分け](#実行エンジンの自動振り分け)を参照してください。
|
これらのピクセル操作を含むスクリプトは自動的に高速化されます。自ピクセル完結のピクセル写像は CPU カーネル(式ツリー)または GPU カーネル(Direct2D ピクセルシェーダ)へ、それ以外は高速ランタイム(LuaJIT)へ自動で振り分けられ、いずれも従来エンジンに比べて大幅(内部計測で数十倍)に高速化されます。CPU カーネルと LuaJIT の出力結果は従来エンジンと一致します(GPU カーネルのみ float32 精度のためごく僅かに異なり得ます)。詳細・制約は[実行エンジンの自動振り分け](#実行エンジンの自動振り分け)を参照してください。
|
||||||
|
|
||||||
### 4. scene テーブルと ymm4 テーブル
|
### 4. scene テーブルと ymm4 テーブル
|
||||||
|
|
||||||
@@ -174,7 +177,13 @@ YukkuriMovieMaker4(YMM4)上で動作する、**Luaスクリプトでオブ
|
|||||||
|
|
||||||
### 6. トラックバー(Track0〜Track3)
|
### 6. トラックバー(Track0〜Track3)
|
||||||
|
|
||||||
エフェクトパネルには 4 本のトラックバー(アニメーション対応)があり、各値はスクリプト内で `obj.track0`〜`obj.track3` として参照できます。スライダー表示範囲はいずれも -100〜100、デフォルト値は 0、表示形式は小数点以下2桁です。
|
エフェクトパネルには 4 本のトラックバー(アニメーション対応)があり、各値はスクリプト内で `obj.track0`〜`obj.track3` として参照できます。スライダー表示範囲はいずれも -100〜100、デフォルト値は 0、表示形式は小数点以下2桁です。トラックバーは常に表示されます。
|
||||||
|
|
||||||
|
チェックボックス(`obj.check0`〜`obj.check3`)とカラーピッカー(`color`)は、スクリプト本体でそれらを参照すると自動的にエフェクトパネルへ表示されます(参照を消すと非表示に戻ります)。これにより、`--` ヘッダを書かなくても必要な入力欄だけを出せます。なお、この一般利用ではスライダーのようなラベル・範囲・既定値の宣言は伴わないため、値の範囲はスクリプト内で扱ってください。AviUtl 互換の `--track`/`--check`/`--color` ヘッダによる宣言表示は従来どおり利用できます([AviUtl スクリプトの部分互換](#9-aviutl-スクリプトの部分互換)を参照)。
|
||||||
|
|
||||||
|
数値スライダーが 4 本あり、各値はスクリプト内で `obj.slider0`〜`obj.slider3` として参照できます。値は整数で、表示範囲は `obj.slider0` が 1〜10、`obj.slider1` が 0〜100、`obj.slider2` が 0〜1000、`obj.slider3` が -1000〜1000 です。状態の切り替えなど、補間を伴わない整数値の受け渡しに使えます。
|
||||||
|
|
||||||
|
文字列パラメータも利用できます。テキスト入力欄は `obj.text`、フォント選択欄は `obj.font`、フォルダ選択欄は `obj.dir` で参照します。ファイル選択欄は種類ごとに `obj.file_video` / `obj.file_audio` / `obj.file_image` / `obj.file_project` / `obj.file_mp4` / `obj.file_exo` / `obj.file_subtitle` / `obj.file_shader` で参照し、選択したファイルのパスを取得できます。取得したパスは `obj.load` へ渡して画像・動画の読み込みに使えます。スライダーと文字列パラメータは、スクリプト本体でそれらを参照すると自動的にエフェクトパネルへ表示されます。いずれのパラメータも MoonSharp とネイティブの両エンジンから参照できます。
|
||||||
|
|
||||||
### 7. スクリプトエディタの支援機能
|
### 7. スクリプトエディタの支援機能
|
||||||
|
|
||||||
@@ -203,13 +212,14 @@ AviUtl のアニメーション効果スクリプト(`.anm` 系)のうち、
|
|||||||
- `--track0:`〜`--track3:` … トラックバーの値は従来どおり `obj.track0`〜`obj.track3` から参照します(ラベル・範囲・既定値の UI 反映は行いません)。
|
- `--track0:`〜`--track3:` … トラックバーの値は従来どおり `obj.track0`〜`obj.track3` から参照します(ラベル・範囲・既定値の UI 反映は行いません)。
|
||||||
- **`@` による複数セクション**: 1 つのスクリプトに `@名前` で複数の効果が定義されている場合、先頭のセクションのみを実行します。
|
- **`@` による複数セクション**: 1 つのスクリプトに `@名前` で複数の効果が定義されている場合、先頭のセクションのみを実行します。
|
||||||
- **`obj.rand(st, ed [, seed [, frame]])`**: 指定範囲(`st`〜`ed`)の整数を返す決定論的な乱数です。`seed` と `frame` が同じであれば常に同じ値を返し、`frame` を省略すると現在のフレームを用います。従来エンジン(MoonSharp)と高速ランタイム(LuaJIT)で同じ値を返します。
|
- **`obj.rand(st, ed [, seed [, frame]])`**: 指定範囲(`st`〜`ed`)の整数を返す決定論的な乱数です。`seed` と `frame` が同じであれば常に同じ値を返し、`frame` を省略すると現在のフレームを用います。従来エンジン(MoonSharp)と高速ランタイム(LuaJIT)で同じ値を返します。
|
||||||
- **`obj.load("figure", 名前, 色, サイズ [, ライン [, アスペクト]])`**: 円・四角形・三角形・五角形・六角形・星形を生成し、オブジェクトのバッファを置き換えて描画します(出力は図形サイズに合わせて生成され、中心に配置されます)。`ライン` を省略するか `0` で塗りつぶし、サイズ以上の値でも塗りつぶしになります。`アスペクト`(-1.0〜1.0)で幅・高さを歪曲できます。`figure` 以外の対象は本バージョンでは対象外です。描画系 API を含むスクリプトは従来エンジン(MoonSharp)で実行されます。
|
- **`obj.load("figure", 名前, 色, サイズ [, ライン [, アスペクト]])`**: 円・四角形・三角形・五角形・六角形・星形を生成し、オブジェクトのバッファを置き換えて描画します(出力は図形サイズに合わせて生成され、中心に配置されます)。`ライン` を省略するか `0` で塗りつぶし、サイズ以上の値でも塗りつぶしになります。`アスペクト`(-1.0〜1.0)で幅・高さを歪曲できます。
|
||||||
|
- **描画・メディア・バッファ・オプション API**: `obj.draw` / `obj.drawpoly` による描画合成、`obj.load` の `"text"` / `"image"` / `"movie"`、`obj.setfont`、`obj.copybuffer`、`obj.effect`、`obj.getvalue`、`obj.setoption` / `obj.getoption` / `obj.pixeloption` に対応しています。これらは従来エンジン(MoonSharp)と高速ランタイム(LuaJIT)の双方で動作します。
|
||||||
|
- **`obj.effect` の AviUtl/AviUtl2 互換マップ**: `obj.effect("エフェクト名", "パラメータ名", 値, …)` はまず互換マップを参照し、AviUtl/AviUtl2 の名前として宣言したエフェクトを、対応する YMM4 の映像エフェクトとプロパティへ変換して適用します。値の倍率とオフセットの変換まで宣言できます。互換マップに宣言が無い名前は、従来どおり YMM4 のエフェクト名・キーワードでそのまま解決するため、既存の呼び出しはそのまま動きます。この互換マップは YMM4 自身が AviUtl の `.exo` へ書き出す変換を逆向きにたどって構築しているため、往復しても結果が一致します。対象のエンジンは指定子 `--!aviutl` または `--!aviutl2` で切り替え、指定子を書かないときは `--!aviutl` として扱います。互換マップが対応するエフェクト名の一覧はドキュメントの「obj の関数」を参照してください。
|
||||||
|
|
||||||
次のような機能は、本体の描画パイプラインへの統合を要するため、この互換層では対象外です(呼び出しを含むスクリプトは意図どおりには動作しません)。
|
次のような機能は、この互換層では対象外です(呼び出しを含むスクリプトは意図どおりには動作しません)。
|
||||||
|
|
||||||
- 描画・合成(`obj.draw` / `obj.drawpoly`)、`obj.load` の `"figure"` 以外の対象(画像ファイル・`"text"`・`"movie"` など)、および `obj.setfont`
|
- `obj.setanchor`、`scene.set` / `scene.get` などの未実装関数
|
||||||
- フィルタ効果やバッファ操作(`obj.effect` / `obj.copybuffer` / `obj.setoption` など)
|
- `require` によるモジュール読み込み、`io` / `dofile` などの任意ファイルアクセス(`obj.load("image"/"movie")` のみ、先頭ヘッダー検証付きで対応)
|
||||||
- `require` によるモジュール読み込み、`io` などのファイルアクセス
|
|
||||||
|
|
||||||
---
|
---
|
||||||
|
|
||||||
@@ -217,16 +227,23 @@ AviUtl のアニメーション効果スクリプト(`.anm` 系)のうち、
|
|||||||
|
|
||||||
### 実行エンジンの自動振り分け
|
### 実行エンジンの自動振り分け
|
||||||
|
|
||||||
スクリプトは内容に応じて 2 つのエンジンへ自動的に振り分けられます。
|
スクリプトは内容に応じて 4 つのエンジンへ自動的に振り分けられます。
|
||||||
|
|
||||||
- **ピクセル操作を含むスクリプト**(`obj.getpixel` / `obj.setpixel` / `obj.getpixeldata` を含む)→ 同梱の高速ランタイム **LuaJIT** で実行(ネイティブ実行)。
|
- **自ピクセル完結のピクセル写像**(`for y … for x … obj.getpixel … obj.setpixel … end end` の形)→ **CPU カーネル(式ツリー)** へ実行時コンパイルして実行。
|
||||||
|
- **上記以外のピクセル操作を含むスクリプト**(`obj.getpixeldata` や近傍参照・別座標書き込みなど)→ 同梱の高速ランタイム **LuaJIT** で実行(ネイティブ実行)。
|
||||||
- **変形のみのスクリプト** → 従来の **MoonSharp** で実行。
|
- **変形のみのスクリプト** → 従来の **MoonSharp** で実行。
|
||||||
|
|
||||||
スクリプトの先頭行に次のディレクティブを書くと、エンジンを明示指定できます。
|
スクリプトの先頭行に次のディレクティブを書くと、エンジンを明示指定できます。
|
||||||
|
|
||||||
|
- `--!cpu` … CPU カーネル(式ツリー)で実行。全 CPU コアで並列実行し、出力は MoonSharp とビット単位で一致します。
|
||||||
|
- `--!gpu` … GPU カーネル(Direct2D ピクセルシェーダ)で実行。GPU→CPU 転送を排して最速ですが、float32 精度のため結果はごく僅かに異なり得ます(オプトイン)。
|
||||||
- `--!native` … 高速ランタイム(LuaJIT)で実行
|
- `--!native` … 高速ランタイム(LuaJIT)で実行
|
||||||
- `--!moonsharp` … 従来エンジン(MoonSharp)で実行
|
- `--!moonsharp` … 従来エンジン(MoonSharp)で実行
|
||||||
|
|
||||||
|
いずれのディレクティブも、利用不可・非対応の場合は出力を壊さずに下位のエンジンへ自動的にフォールバックします(例:`--!gpu` の初期化に失敗した場合は CPU カーネル、さらに MoonSharp へ縮退します)。
|
||||||
|
|
||||||
|
CPU / GPU カーネルが成立するのは、四則演算・`math.*`・比較・しきい値の「条件 and 値1 or 値2」・`local` 変数のみを使い、処理中の自ピクセル(`obj.getpixel(x, y)`)と `obj` / `scene` / `time` 等の値だけを参照する純粋な写像(色変換・グレースケール・ガンマ・しきい値・チャンネル混合など)の場合です。近傍参照(ぼかし等)・別座標への書き込み・`getpixeldata`・`getobject`・テーブル/文字列操作・`if` 文などを含む場合はカーネル化されず、自動的に LuaJIT または MoonSharp で実行されます。コンパイル済みのカーネルはスクリプト本文をキーにキャッシュされ、初回フレームのみコンパイルコストを払います。
|
||||||
|
|
||||||
ネイティブ実行は**専用の別プロセス**で行われ、ピクセルバッファは共有メモリ経由で受け渡されます。スクリプトが無限ループに陥った場合でも **5 秒のタイムアウトでプロセスを強制終了**するため本体は固まらず、終了後は自動的に復帰します。出力結果は従来エンジンと一致します。
|
ネイティブ実行は**専用の別プロセス**で行われ、ピクセルバッファは共有メモリ経由で受け渡されます。スクリプトが無限ループに陥った場合でも **5 秒のタイムアウトでプロセスを強制終了**するため本体は固まらず、終了後は自動的に復帰します。出力結果は従来エンジンと一致します。
|
||||||
|
|
||||||
`obj.getobject` はネイティブ実行でも利用できます。呼び出し時に本体プロセスへ同期的に問い合わせてシーンオブジェクトを解決するため、従来エンジンと同じ結果を返します。同じタグ・同じフレームへの連続した問い合わせはフレーム内でキャッシュされ、2 回目以降は往復を行いません。
|
`obj.getobject` はネイティブ実行でも利用できます。呼び出し時に本体プロセスへ同期的に問い合わせてシーンオブジェクトを解決するため、従来エンジンと同じ結果を返します。同じタグ・同じフレームへの連続した問い合わせはフレーム内でキャッシュされ、2 回目以降は往復を行いません。
|
||||||
@@ -270,6 +287,14 @@ AviUtl のアニメーション効果スクリプト(`.anm` 系)のうち、
|
|||||||
| **Track1** | 数値 | 0.00 | -100 〜 100 | ✔ | `obj.track1` として参照できる汎用パラメータ |
|
| **Track1** | 数値 | 0.00 | -100 〜 100 | ✔ | `obj.track1` として参照できる汎用パラメータ |
|
||||||
| **Track2** | 数値 | 0.00 | -100 〜 100 | ✔ | `obj.track2` として参照できる汎用パラメータ |
|
| **Track2** | 数値 | 0.00 | -100 〜 100 | ✔ | `obj.track2` として参照できる汎用パラメータ |
|
||||||
| **Track3** | 数値 | 0.00 | -100 〜 100 | ✔ | `obj.track3` として参照できる汎用パラメータ |
|
| **Track3** | 数値 | 0.00 | -100 〜 100 | ✔ | `obj.track3` として参照できる汎用パラメータ |
|
||||||
|
| **Slider0** | 整数 | 1 | 1 〜 10 | - | `obj.slider0` として参照できる整数パラメータ |
|
||||||
|
| **Slider1** | 整数 | 0 | 0 〜 100 | - | `obj.slider1` として参照できる整数パラメータ |
|
||||||
|
| **Slider2** | 整数 | 0 | 0 〜 1000 | - | `obj.slider2` として参照できる整数パラメータ |
|
||||||
|
| **Slider3** | 整数 | 0 | -1000 〜 1000 | - | `obj.slider3` として参照できる整数パラメータ |
|
||||||
|
| **Text** | 文字列 | 空 | - | - | `obj.text` として参照できるテキスト入力 |
|
||||||
|
| **Font** | 文字列 | メイリオ | - | - | `obj.font` として参照できるフォント名 |
|
||||||
|
| **Directory** | 文字列 | 空 | - | - | `obj.dir` として参照できるフォルダパス |
|
||||||
|
| **FileVideo**〜**FileShader** | 文字列 | 空 | - | - | `obj.file_video`〜`obj.file_shader` として参照できるファイルパス |
|
||||||
|
|
||||||
---
|
---
|
||||||
|
|
||||||
@@ -348,7 +373,7 @@ obj.alpha = anim.ease_out(t) * 255
|
|||||||
- **AviUtl 互換は部分的**: AviUtl のアニメーション効果スクリプトのうち、変形・不透明度・乱数の範囲のみ実行できます([AviUtl スクリプトの部分互換](#9-aviutl-スクリプトの部分互換)を参照)。描画・フィルタ・ファイルアクセス系の関数、および AviUtl 向けの EXO 出力(`.exo`)には対応していません。
|
- **AviUtl 互換は部分的**: AviUtl のアニメーション効果スクリプトのうち、変形・不透明度・乱数の範囲のみ実行できます([AviUtl スクリプトの部分互換](#9-aviutl-スクリプトの部分互換)を参照)。描画・フィルタ・ファイルアクセス系の関数、および AviUtl 向けの EXO 出力(`.exo`)には対応していません。
|
||||||
- **実行タイムアウト**: スクリプトの実行は 5000ms(5秒)でタイムアウトし、超過した場合は強制終了されエラーとして扱われます。無限ループが発生しないよう注意してください。
|
- **実行タイムアウト**: スクリプトの実行は 5000ms(5秒)でタイムアウトし、超過した場合は強制終了されエラーとして扱われます。無限ループが発生しないよう注意してください。
|
||||||
- **利用可能な標準ライブラリの制限**: `table`、`string`、`math`、`bit32` および基本関数のみ利用できます。`io`、`os`、`debug`、`ffi`、`require` は利用できません。
|
- **利用可能な標準ライブラリの制限**: `table`、`string`、`math`、`bit32` および基本関数のみ利用できます。`io`、`os`、`debug`、`ffi`、`require` は利用できません。
|
||||||
- **ピクセル操作の負荷**: `obj.getpixel` / `obj.setpixel` / `obj.getpixeldata` は実際の入力画像にアクセスするため、各フレームで最初に呼び出した際に GPU→CPU へのデータ転送が発生します。不要な場合は呼び出しを省略することで処理を高速化できます。これらを含むスクリプトは高速ランタイム(LuaJIT)で自動実行され大幅に高速化されます。詳細は[実行エンジンの自動振り分け](#実行エンジンの自動振り分け)を参照。
|
- **ピクセル操作の負荷**: `obj.getpixel` / `obj.setpixel` / `obj.getpixeldata` は実際の入力画像にアクセスするため、各フレームで最初に呼び出した際に GPU→CPU へのデータ転送が発生します(GPU カーネルはこの転送を行いません)。不要な場合は呼び出しを省略することで処理を高速化できます。これらを含むスクリプトは内容に応じて CPU カーネル・GPU カーネル・高速ランタイム(LuaJIT)のいずれかで自動実行され大幅に高速化されます。詳細は[実行エンジンの自動振り分け](#実行エンジンの自動振り分け)を参照。
|
||||||
- **`math.random` はフレームごとの決定論的な乱数**: 毎フレーム `frame` の値でシードし直されるため、同一フレームでは常に同じ値になります。フレームをまたいで変化する乱数的な値が必要な場合は `anim.rand` の利用を検討してください。
|
- **`math.random` はフレームごとの決定論的な乱数**: 毎フレーム `frame` の値でシードし直されるため、同一フレームでは常に同じ値になります。フレームをまたいで変化する乱数的な値が必要な場合は `anim.rand` の利用を検討してください。
|
||||||
- **`obj.oz` は出力に反映されません**: スクリプト実行後にコンテキストへ読み戻されますが、現在の実装では中心点オフセットの出力計算に使用されていません。
|
- **`obj.oz` は出力に反映されません**: スクリプト実行後にコンテキストへ読み戻されますが、現在の実装では中心点オフセットの出力計算に使用されていません。
|
||||||
- **エクスポートは先頭の1件のみ**: 複数アイテムを選択した状態でも、エクスポートされるスクリプトは先頭のアイテムのもののみです(インポート・クリアは選択中のすべてのアイテムに適用されます)。
|
- **エクスポートは先頭の1件のみ**: 複数アイテムを選択した状態でも、エクスポートされるスクリプトは先頭のアイテムのもののみです(インポート・クリアは選択中のすべてのアイテムに適用されます)。
|
||||||
|
|||||||
+160
@@ -0,0 +1,160 @@
|
|||||||
|
<!DOCTYPE html>
|
||||||
|
<html lang="ja">
|
||||||
|
<head>
|
||||||
|
<meta charset="utf-8">
|
||||||
|
<meta name="viewport" content="width=device-width, initial-scale=1">
|
||||||
|
<title>anim ライブラリ | Lua スクリプト for YMM4</title>
|
||||||
|
<link rel="stylesheet" href="assets/style.css">
|
||||||
|
</head>
|
||||||
|
<body>
|
||||||
|
<button id="navtoggle" aria-label="メニュー">☰</button>
|
||||||
|
<nav id="sidebar"></nav>
|
||||||
|
<main>
|
||||||
|
|
||||||
|
<h1>anim ライブラリ</h1>
|
||||||
|
|
||||||
|
<p>
|
||||||
|
<code>anim</code> は、アニメーションでよく使う計算をまとめた補助ライブラリです。
|
||||||
|
補間・イージング・波・範囲変換・ベクトル・ノイズ・色変換と、便利な定数を提供します。
|
||||||
|
これらは標準 Lua にはない、このエフェクト独自の関数です。
|
||||||
|
</p>
|
||||||
|
|
||||||
|
<h2>定数</h2>
|
||||||
|
|
||||||
|
<table>
|
||||||
|
<tr><th>定数</th><th>値</th><th>説明</th></tr>
|
||||||
|
<tr><td><code>anim.tau</code></td><td><code>math.pi * 2</code></td><td>円一周分のラジアン。周期運動に使う</td></tr>
|
||||||
|
<tr><td><code>anim.e</code></td><td>ネイピア数</td><td>自然対数の底</td></tr>
|
||||||
|
<tr><td><code>anim.phi</code></td><td><code>(1 + sqrt(5)) / 2</code></td><td>黄金比</td></tr>
|
||||||
|
<tr><td><code>anim.sqrt2</code></td><td><code>sqrt(2)</code></td><td>2 の平方根</td></tr>
|
||||||
|
</table>
|
||||||
|
|
||||||
|
<pre><code>obj.x = obj.x + math.sin(time * anim.tau) * 100</code></pre>
|
||||||
|
|
||||||
|
<h2>補間・イージング</h2>
|
||||||
|
|
||||||
|
<p>
|
||||||
|
イージング関数はおおむね 0.0 ~ 1.0 の進行度 <code>t</code> を受け取り、変化のカーブを返します。
|
||||||
|
<code>obj.t</code> をそのまま渡すのが定番です。
|
||||||
|
</p>
|
||||||
|
|
||||||
|
<table>
|
||||||
|
<tr><th>関数</th><th>説明</th></tr>
|
||||||
|
<tr><td><code>anim.lerp(a, b, t)</code></td><td><code>a</code> と <code>b</code> を <code>t</code> で線形補間</td></tr>
|
||||||
|
<tr><td><code>anim.smoothstep(e0, e1, x)</code></td><td><code>e0</code> ~ <code>e1</code> をエルミート補間で滑らかに遷移</td></tr>
|
||||||
|
<tr><td><code>anim.smootherstep(e0, e1, x)</code></td><td>2 次導関数まで連続な、より滑らかな遷移</td></tr>
|
||||||
|
<tr><td><code>anim.ease_in(t)</code></td><td>2 次イーズイン(加速)</td></tr>
|
||||||
|
<tr><td><code>anim.ease_out(t)</code></td><td>2 次イーズアウト(減速)</td></tr>
|
||||||
|
<tr><td><code>anim.ease_in_out(t)</code></td><td>2 次イーズイン・アウト(加速後減速)</td></tr>
|
||||||
|
<tr><td><code>anim.elastic(t)</code></td><td>弾むようなスプリングイージング(t は 0 ~ 1 にクランプ)</td></tr>
|
||||||
|
<tr><td><code>anim.back(t)</code></td><td>行き過ぎてから戻るイージング</td></tr>
|
||||||
|
<tr><td><code>anim.bounce(t)</code></td><td>バウンドするイージング(t は 0 ~ 1 にクランプ)</td></tr>
|
||||||
|
<tr><td><code>anim.step(edge, x)</code></td><td><code>x</code> が <code>edge</code> 以上なら 1.0、未満なら 0.0</td></tr>
|
||||||
|
<tr><td><code>anim.bezier(t, p0, p1, p2, p3)</code></td><td><code>t</code> における 3 次ベジェ曲線の値(t は 0 ~ 1 にクランプ)</td></tr>
|
||||||
|
</table>
|
||||||
|
|
||||||
|
<h3>2 点間をイージングで移動</h3>
|
||||||
|
<pre><code>local tx, ty = 200, -100
|
||||||
|
local p = anim.ease_in_out(obj.t)
|
||||||
|
obj.x = anim.lerp(obj.x, tx, p)
|
||||||
|
obj.y = anim.lerp(obj.y, ty, p)</code></pre>
|
||||||
|
|
||||||
|
<h3>弾むように登場</h3>
|
||||||
|
<pre><code>local p = anim.duration(time, 0.3)
|
||||||
|
obj.zoom = obj.zoom * anim.elastic(p)</code></pre>
|
||||||
|
|
||||||
|
<h2>範囲・周期</h2>
|
||||||
|
|
||||||
|
<table>
|
||||||
|
<tr><th>関数</th><th>説明</th></tr>
|
||||||
|
<tr><td><code>anim.clamp(v, lo, hi)</code></td><td><code>v</code> を <code>lo</code> ~ <code>hi</code> に収める</td></tr>
|
||||||
|
<tr><td><code>anim.map(v, a1, b1, a2, b2)</code></td><td>範囲 <code>a1</code>~<code>b1</code> の <code>v</code> を <code>a2</code>~<code>b2</code> に変換</td></tr>
|
||||||
|
<tr><td><code>anim.norm(v, lo, hi)</code></td><td><code>v</code> が <code>lo</code>~<code>hi</code> のどの割合(0.0~1.0)かを返す</td></tr>
|
||||||
|
<tr><td><code>anim.wrap(v, lo, hi)</code></td><td><code>v</code> を <code>lo</code> ~ <code>hi</code> でループさせる</td></tr>
|
||||||
|
<tr><td><code>anim.pingpong(t, len)</code></td><td>0 ~ <code>len</code> を往復する値</td></tr>
|
||||||
|
<tr><td><code>anim.sign(v)</code></td><td>符号(正=1, 負=-1, ゼロ=0)</td></tr>
|
||||||
|
<tr><td><code>anim.fract(v)</code></td><td>小数部分のみ</td></tr>
|
||||||
|
<tr><td><code>anim.oscillate(t, lo, hi, freq)</code></td><td>周波数 <code>freq</code> で <code>lo</code>~<code>hi</code> を正弦波で往復</td></tr>
|
||||||
|
<tr><td><code>anim.triangle(t, freq)</code></td><td>周波数 <code>freq</code> で 0.0~1.0 を往復する三角波</td></tr>
|
||||||
|
<tr><td><code>anim.square(t, freq)</code></td><td>周波数 <code>freq</code> で 1.0 と 0.0 を切り替える矩形波</td></tr>
|
||||||
|
<tr><td><code>anim.duration(t, dur)</code></td><td>時間 <code>dur</code> に対する割合(0.0~1.0、クランプあり)</td></tr>
|
||||||
|
<tr><td><code>anim.delay(t, d)</code></td><td>時間 <code>d</code> を引いた値(0 未満は 0)</td></tr>
|
||||||
|
</table>
|
||||||
|
|
||||||
|
<h3>値の範囲変換</h3>
|
||||||
|
<pre><code>obj.rz = anim.map(obj.track0, 0, 100, -180, 180)</code></pre>
|
||||||
|
|
||||||
|
<h3>滑らかな明滅</h3>
|
||||||
|
<pre><code>obj.alpha = anim.oscillate(time, 64, 255, 1)</code></pre>
|
||||||
|
|
||||||
|
<h2>ベクトル・幾何</h2>
|
||||||
|
|
||||||
|
<table>
|
||||||
|
<tr><th>関数</th><th>戻り値</th><th>説明</th></tr>
|
||||||
|
<tr><td><code>anim.len(x, y)</code></td><td>数値</td><td>ベクトル (x, y) の長さ</td></tr>
|
||||||
|
<tr><td><code>anim.dist(x1, y1, x2, y2)</code></td><td>数値</td><td>2 点間の距離</td></tr>
|
||||||
|
<tr><td><code>anim.dot(x1, y1, x2, y2)</code></td><td>数値</td><td>2 ベクトルの内積</td></tr>
|
||||||
|
<tr><td><code>anim.normalize(x, y)</code></td><td>x, y</td><td>正規化した方向ベクトル(2 値で返す)</td></tr>
|
||||||
|
<tr><td><code>anim.polar(r, a)</code></td><td>x, y</td><td>半径 <code>r</code>・角度 <code>a</code>(度)から移動量</td></tr>
|
||||||
|
<tr><td><code>anim.rotate(x, y, a)</code></td><td>x, y</td><td>(x, y) を <code>a</code>(度)回転させた座標</td></tr>
|
||||||
|
</table>
|
||||||
|
|
||||||
|
<h3>円運動</h3>
|
||||||
|
<pre><code>local r = obj.track0
|
||||||
|
local dx, dy = anim.polar(r, time * 90)
|
||||||
|
obj.x = obj.x + dx
|
||||||
|
obj.y = obj.y + dy</code></pre>
|
||||||
|
|
||||||
|
<h2>ノイズ・乱数</h2>
|
||||||
|
|
||||||
|
<table>
|
||||||
|
<tr><th>関数</th><th>説明</th></tr>
|
||||||
|
<tr><td><code>anim.noise(x [, y [, z]])</code></td><td>1 ~ 3 次元の滑らかなノイズ(0.0 ~ 1.0)。同じ座標では常に同じ値</td></tr>
|
||||||
|
<tr><td><code>anim.rand(s)</code></td><td>シード <code>s</code> に基づく 0.0 ~ 1.0 の安定した乱数</td></tr>
|
||||||
|
<tr><td><code>anim.rand(max, s)</code></td><td>0.0 ~ <code>max</code> の安定した乱数</td></tr>
|
||||||
|
<tr><td><code>anim.rand(min, max, s)</code></td><td><code>min</code> ~ <code>max</code> の安定した乱数</td></tr>
|
||||||
|
</table>
|
||||||
|
|
||||||
|
<div class="note">
|
||||||
|
<code>anim.rand</code> はシードのみで決まる小数の乱数です(フレームは関与しません)。
|
||||||
|
整数で、フレームによっても変えたい場合は <a href="obj-functions.html"><code>obj.rand</code></a> を使ってください。
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<h3>安定した乱数で個体差をつける</h3>
|
||||||
|
<pre><code>local offset = anim.rand(-50, 50, obj.layer)
|
||||||
|
obj.x = obj.x + offset</code></pre>
|
||||||
|
|
||||||
|
<h3>ノイズで揺らぐ手ぶれ風</h3>
|
||||||
|
<pre><code>obj.x = obj.x + (anim.noise(time * 2, 0, 0) - 0.5) * 20
|
||||||
|
obj.y = obj.y + (anim.noise(0, time * 2, 0) - 0.5) * 20
|
||||||
|
obj.rz = (anim.noise(0, 0, time * 2) - 0.5) * 10</code></pre>
|
||||||
|
|
||||||
|
<h2>色変換</h2>
|
||||||
|
|
||||||
|
<table>
|
||||||
|
<tr><th>関数</th><th>戻り値</th><th>説明</th></tr>
|
||||||
|
<tr><td><code>anim.hsv_to_rgb(h, s, v)</code></td><td>r, g, b</td><td>HSV(色相 0~360, 彩度 0~1, 明度 0~1)を RGB(0~255)へ変換</td></tr>
|
||||||
|
<tr><td><code>anim.rgb_to_hsv(r, g, b)</code></td><td>h, s, v</td><td>RGB(0~255)を HSV へ変換</td></tr>
|
||||||
|
</table>
|
||||||
|
|
||||||
|
<h3>時間で色相を回す</h3>
|
||||||
|
<pre><code>local hue = anim.wrap(time * 60, 0, 360)
|
||||||
|
local cr, cg, cb = anim.hsv_to_rgb(hue, 1, 1)
|
||||||
|
local pd = obj.getpixeldata()
|
||||||
|
local n = pd.width * pd.height
|
||||||
|
for i = 0, n - 1 do
|
||||||
|
local base = i * 4
|
||||||
|
pd:set(base + 1, pd:get(base + 1) * cr / 255)
|
||||||
|
pd:set(base + 2, pd:get(base + 2) * cg / 255)
|
||||||
|
pd:set(base + 3, pd:get(base + 3) * cb / 255)
|
||||||
|
end</code></pre>
|
||||||
|
|
||||||
|
<div class="pager">
|
||||||
|
<a href="obj-functions.html">← obj の関数</a>
|
||||||
|
<a href="scene-ymm4.html">scene と ymm4 →</a>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
</main>
|
||||||
|
<script src="assets/nav.js"></script>
|
||||||
|
</body>
|
||||||
|
</html>
|
||||||
@@ -0,0 +1,241 @@
|
|||||||
|
(function () {
|
||||||
|
var NAV = [
|
||||||
|
{
|
||||||
|
group: "はじめに",
|
||||||
|
items: [
|
||||||
|
{ title: "概要", href: "index.html" },
|
||||||
|
{ title: "導入と使い方", href: "getting-started.html" }
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
group: "Lua 言語",
|
||||||
|
items: [
|
||||||
|
{ title: "Lua の基礎", href: "lua-basics.html" },
|
||||||
|
{ title: "標準ライブラリ", href: "stdlib.html" }
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
group: "API リファレンス",
|
||||||
|
items: [
|
||||||
|
{ title: "グローバル変数", href: "globals.html" },
|
||||||
|
{ title: "obj オブジェクト", href: "obj.html" },
|
||||||
|
{ title: "obj の関数", href: "obj-functions.html" },
|
||||||
|
{ title: "anim ライブラリ", href: "anim.html" },
|
||||||
|
{ title: "scene と ymm4", href: "scene-ymm4.html" },
|
||||||
|
{ title: "ピクセル操作", href: "pixels.html" }
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
group: "高度な機能",
|
||||||
|
items: [
|
||||||
|
{ title: "エンジンと高速化", href: "engines.html" },
|
||||||
|
{ title: "パラメータ指定子", href: "directives.html" }
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
group: "実用",
|
||||||
|
items: [
|
||||||
|
{ title: "サンプル集", href: "samples.html" },
|
||||||
|
{ title: "クイックリファレンス", href: "reference.html" },
|
||||||
|
{ title: "制限事項とトラブル", href: "limits.html" }
|
||||||
|
]
|
||||||
|
}
|
||||||
|
];
|
||||||
|
|
||||||
|
var titleOf = {};
|
||||||
|
for (var gi = 0; gi < NAV.length; gi++) {
|
||||||
|
for (var ii = 0; ii < NAV[gi].items.length; ii++) {
|
||||||
|
titleOf[NAV[gi].items[ii].href] = NAV[gi].items[ii].title;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
var indexPromise = null;
|
||||||
|
var searchTimer = null;
|
||||||
|
|
||||||
|
function currentFile() {
|
||||||
|
var path = window.location.pathname;
|
||||||
|
var file = path.substring(path.lastIndexOf("/") + 1);
|
||||||
|
return file === "" ? "index.html" : file;
|
||||||
|
}
|
||||||
|
|
||||||
|
function escapeHtml(text) {
|
||||||
|
return text
|
||||||
|
.replace(/&/g, "&")
|
||||||
|
.replace(/</g, "<")
|
||||||
|
.replace(/>/g, ">");
|
||||||
|
}
|
||||||
|
|
||||||
|
function build() {
|
||||||
|
var here = currentFile();
|
||||||
|
var sidebar = document.getElementById("sidebar");
|
||||||
|
if (!sidebar) return;
|
||||||
|
|
||||||
|
var html = '<a class="brand" href="index.html">Lua スクリプト for YMM4</a>';
|
||||||
|
html += '<input id="navfilter" type="search" placeholder="全ページを検索" aria-label="全ページを検索" autocomplete="off">';
|
||||||
|
html += '<div id="navresults"></div>';
|
||||||
|
html += '<div id="navtree">';
|
||||||
|
for (var i = 0; i < NAV.length; i++) {
|
||||||
|
html += '<div class="group">' + NAV[i].group + "</div><ul>";
|
||||||
|
for (var j = 0; j < NAV[i].items.length; j++) {
|
||||||
|
var it = NAV[i].items[j];
|
||||||
|
var cls = it.href === here ? ' class="active"' : "";
|
||||||
|
html += "<li><a" + cls + ' href="' + it.href + '">' + it.title + "</a></li>";
|
||||||
|
}
|
||||||
|
html += "</ul>";
|
||||||
|
}
|
||||||
|
html += "</div>";
|
||||||
|
sidebar.innerHTML = html;
|
||||||
|
|
||||||
|
var filter = document.getElementById("navfilter");
|
||||||
|
filter.addEventListener("input", function () {
|
||||||
|
var q = filter.value.trim();
|
||||||
|
if (searchTimer) clearTimeout(searchTimer);
|
||||||
|
searchTimer = setTimeout(function () { runSearch(q); }, 150);
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
function runSearch(query) {
|
||||||
|
var tree = document.getElementById("navtree");
|
||||||
|
var results = document.getElementById("navresults");
|
||||||
|
if (!tree || !results) return;
|
||||||
|
|
||||||
|
if (query.length < 2) {
|
||||||
|
results.innerHTML = "";
|
||||||
|
tree.style.display = "";
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
tree.style.display = "none";
|
||||||
|
results.innerHTML = '<div class="navmsg">検索中…</div>';
|
||||||
|
|
||||||
|
buildIndex().then(function (sections) {
|
||||||
|
if (document.getElementById("navfilter").value.trim() !== query) return;
|
||||||
|
render(results, sections, query);
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
function buildIndex() {
|
||||||
|
if (indexPromise) return indexPromise;
|
||||||
|
|
||||||
|
var hrefs = [];
|
||||||
|
for (var key in titleOf) {
|
||||||
|
if (Object.prototype.hasOwnProperty.call(titleOf, key)) hrefs.push(key);
|
||||||
|
}
|
||||||
|
|
||||||
|
indexPromise = Promise.all(hrefs.map(fetchSections)).then(function (lists) {
|
||||||
|
var all = [];
|
||||||
|
for (var i = 0; i < lists.length; i++) {
|
||||||
|
for (var j = 0; j < lists[i].length; j++) all.push(lists[i][j]);
|
||||||
|
}
|
||||||
|
return all;
|
||||||
|
});
|
||||||
|
return indexPromise;
|
||||||
|
}
|
||||||
|
|
||||||
|
function fetchSections(href) {
|
||||||
|
return fetch(href)
|
||||||
|
.then(function (res) { return res.text(); })
|
||||||
|
.then(function (text) {
|
||||||
|
var doc = new DOMParser().parseFromString(text, "text/html");
|
||||||
|
var main = doc.querySelector("main");
|
||||||
|
if (!main) return [];
|
||||||
|
|
||||||
|
var sections = [];
|
||||||
|
var heading = "";
|
||||||
|
var buffer = "";
|
||||||
|
var children = main.children;
|
||||||
|
|
||||||
|
function flush() {
|
||||||
|
var body = buffer.replace(/\s+/g, " ").trim();
|
||||||
|
if (body.length > 0) {
|
||||||
|
sections.push({
|
||||||
|
href: href,
|
||||||
|
page: titleOf[href] || href,
|
||||||
|
heading: heading,
|
||||||
|
text: body,
|
||||||
|
lower: body.toLowerCase()
|
||||||
|
});
|
||||||
|
}
|
||||||
|
buffer = "";
|
||||||
|
}
|
||||||
|
|
||||||
|
for (var i = 0; i < children.length; i++) {
|
||||||
|
var el = children[i];
|
||||||
|
var tag = el.tagName;
|
||||||
|
if (tag === "H2" || tag === "H3") {
|
||||||
|
flush();
|
||||||
|
heading = el.textContent.replace(/\s+/g, " ").trim();
|
||||||
|
} else if (el.className === "pager") {
|
||||||
|
continue;
|
||||||
|
} else {
|
||||||
|
buffer += " " + el.textContent;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
flush();
|
||||||
|
return sections;
|
||||||
|
})
|
||||||
|
.catch(function () { return []; });
|
||||||
|
}
|
||||||
|
|
||||||
|
function render(container, sections, query) {
|
||||||
|
var q = query.toLowerCase();
|
||||||
|
var hits = [];
|
||||||
|
for (var i = 0; i < sections.length; i++) {
|
||||||
|
var s = sections[i];
|
||||||
|
var inHeading = s.heading.toLowerCase().indexOf(q) !== -1;
|
||||||
|
var inPage = s.page.toLowerCase().indexOf(q) !== -1;
|
||||||
|
var pos = s.lower.indexOf(q);
|
||||||
|
if (inHeading || inPage || pos !== -1) {
|
||||||
|
hits.push({ section: s, pos: pos, rank: inHeading || inPage ? 0 : 1 });
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
hits.sort(function (a, b) { return a.rank - b.rank; });
|
||||||
|
|
||||||
|
if (hits.length === 0) {
|
||||||
|
container.innerHTML = '<div class="navmsg">「' + escapeHtml(query) + "」に一致する内容はありません。</div>";
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
var max = Math.min(hits.length, 40);
|
||||||
|
var html = '<div class="navmsg">' + hits.length + " 件</div>";
|
||||||
|
for (var k = 0; k < max; k++) {
|
||||||
|
var s2 = hits[k].section;
|
||||||
|
var label = s2.heading ? s2.page + " — " + s2.heading : s2.page;
|
||||||
|
var anchor = s2.heading ? "#:~:text=" + encodeURIComponent(s2.heading) : "";
|
||||||
|
html +=
|
||||||
|
'<a class="navhit" href="' + s2.href + anchor + '">' +
|
||||||
|
'<span class="h">' + escapeHtml(label) + "</span>" +
|
||||||
|
'<span class="s">' + snippet(s2.text, hits[k].pos, query) + "</span>" +
|
||||||
|
"</a>";
|
||||||
|
}
|
||||||
|
container.innerHTML = html;
|
||||||
|
}
|
||||||
|
|
||||||
|
function snippet(text, pos, query) {
|
||||||
|
if (pos < 0) {
|
||||||
|
return escapeHtml(text.substring(0, 70)) + (text.length > 70 ? "…" : "");
|
||||||
|
}
|
||||||
|
var start = Math.max(0, pos - 30);
|
||||||
|
var end = Math.min(text.length, pos + query.length + 40);
|
||||||
|
var before = (start > 0 ? "…" : "") + text.substring(start, pos);
|
||||||
|
var hit = text.substring(pos, pos + query.length);
|
||||||
|
var after = text.substring(pos + query.length, end) + (end < text.length ? "…" : "");
|
||||||
|
return escapeHtml(before) + "<mark>" + escapeHtml(hit) + "</mark>" + escapeHtml(after);
|
||||||
|
}
|
||||||
|
|
||||||
|
function toggle() {
|
||||||
|
var btn = document.getElementById("navtoggle");
|
||||||
|
if (!btn) return;
|
||||||
|
btn.addEventListener("click", function () {
|
||||||
|
document.body.classList.toggle("nav-open");
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
if (document.readyState === "loading") {
|
||||||
|
document.addEventListener("DOMContentLoaded", function () { build(); toggle(); });
|
||||||
|
} else {
|
||||||
|
build();
|
||||||
|
toggle();
|
||||||
|
}
|
||||||
|
})();
|
||||||
@@ -0,0 +1,28 @@
|
|||||||
|
* { box-sizing: border-box; }
|
||||||
|
body { margin: 0; font-family: sans-serif; line-height: 1.7; }
|
||||||
|
#sidebar { position: fixed; top: 0; left: 0; width: 240px; height: 100vh; overflow: auto; border-right: 1px solid #ccc; padding: 1em; }
|
||||||
|
#sidebar .brand { display: block; margin-bottom: .6em; font-weight: bold; text-decoration: none; color: #000; }
|
||||||
|
#sidebar input { width: 100%; margin-bottom: .6em; }
|
||||||
|
#sidebar .group { font-size: .8em; color: #666; margin-top: 1em; }
|
||||||
|
#sidebar ul { list-style: none; margin: 0; padding: 0; }
|
||||||
|
#sidebar li a { display: block; padding: .2em .4em; text-decoration: none; color: #000; }
|
||||||
|
#sidebar li a.active { background: #0969da; color: #fff; }
|
||||||
|
main { margin-left: 240px; max-width: 860px; padding: 1em 2em 4em; }
|
||||||
|
pre { background: #f0f0f0; border: 1px solid #ccc; padding: .8em; overflow-x: auto; }
|
||||||
|
code { background: #f0f0f0; padding: 0 .2em; }
|
||||||
|
pre code { background: none; padding: 0; }
|
||||||
|
table { border-collapse: collapse; margin: 1em 0; }
|
||||||
|
th, td { border: 1px solid #ccc; padding: .3em .6em; text-align: left; vertical-align: top; }
|
||||||
|
#navresults .navmsg { font-size: .8em; color: #666; margin: .4em 0; }
|
||||||
|
#navresults .navhit { display: block; padding: .3em .4em; text-decoration: none; color: #000; border-top: 1px solid #eee; }
|
||||||
|
#navresults .navhit .h { display: block; font-size: .82em; color: #0969da; }
|
||||||
|
#navresults .navhit .s { display: block; font-size: .82em; color: #444; }
|
||||||
|
.note, .warn { border-left: 3px solid #888; padding-left: .8em; margin: 1em 0; }
|
||||||
|
.pager { display: flex; justify-content: space-between; margin-top: 2em; }
|
||||||
|
#navtoggle { display: none; }
|
||||||
|
@media (max-width: 820px) {
|
||||||
|
#sidebar { transform: translateX(-100%); transition: transform .2s; z-index: 9; background: #fff; }
|
||||||
|
body.nav-open #sidebar { transform: none; }
|
||||||
|
main { margin-left: 0; padding: 3em 1em; }
|
||||||
|
#navtoggle { display: block; position: fixed; top: .5em; left: .5em; z-index: 10; }
|
||||||
|
}
|
||||||
@@ -0,0 +1,140 @@
|
|||||||
|
<!DOCTYPE html>
|
||||||
|
<html lang="ja">
|
||||||
|
<head>
|
||||||
|
<meta charset="utf-8">
|
||||||
|
<meta name="viewport" content="width=device-width, initial-scale=1">
|
||||||
|
<title>パラメータ指定子 | Lua スクリプト for YMM4</title>
|
||||||
|
<link rel="stylesheet" href="assets/style.css">
|
||||||
|
</head>
|
||||||
|
<body>
|
||||||
|
<button id="navtoggle" aria-label="メニュー">☰</button>
|
||||||
|
<nav id="sidebar"></nav>
|
||||||
|
<main>
|
||||||
|
|
||||||
|
<h1>パラメータ指定子</h1>
|
||||||
|
|
||||||
|
<p>
|
||||||
|
スクリプトの先頭などにコメント形式の指定子を書くと、パラメータパネルのトラックバーや
|
||||||
|
チェックボックス、色の名前・範囲・既定値を定義できます。指定子は <code>--</code> で始まる
|
||||||
|
コメント行なので、Lua の実行には影響しません。
|
||||||
|
</p>
|
||||||
|
|
||||||
|
<div class="note">
|
||||||
|
指定子は必須ではありません。<code>--</code> の行を書かなくても、
|
||||||
|
トラックバーの値は <code>obj.track0</code> ~ <code>obj.track3</code> で読めます。
|
||||||
|
チェックボックスの <code>obj.check0</code> ~ <code>obj.check3</code> と <code>color</code> も、
|
||||||
|
スクリプト中で参照すればパネルに現れて使えます。指定子は、名前や範囲・既定値を整えたいときに使います。
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div class="note">
|
||||||
|
エンジンを選ぶ <code>--!native</code> などの指定子は別物です。先頭が <code>--!</code> で始まります。
|
||||||
|
エンジンの指定は<a href="engines.html">エンジンと高速化</a>を参照してください。
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<h2>トラックバー</h2>
|
||||||
|
|
||||||
|
<p>
|
||||||
|
<code>--track0:</code> ~ <code>--track3:</code> で、各トラックバーの名前・範囲・既定値・増分を指定します。
|
||||||
|
書式はカンマ区切りです。
|
||||||
|
</p>
|
||||||
|
|
||||||
|
<pre><code>--track0:振幅,0,200,50
|
||||||
|
--track1:周波数,0,10,1,0.1</code></pre>
|
||||||
|
|
||||||
|
<table>
|
||||||
|
<tr><th>項目</th><th>位置</th><th>省略時</th></tr>
|
||||||
|
<tr><td>名前</td><td>1 番目</td><td>空</td></tr>
|
||||||
|
<tr><td>最小値</td><td>2 番目</td><td>0</td></tr>
|
||||||
|
<tr><td>最大値</td><td>3 番目</td><td>100</td></tr>
|
||||||
|
<tr><td>既定値</td><td>4 番目</td><td>最小値</td></tr>
|
||||||
|
<tr><td>増分</td><td>5 番目</td><td>0</td></tr>
|
||||||
|
</table>
|
||||||
|
|
||||||
|
<p>
|
||||||
|
最大値が最小値より小さい場合は自動で入れ替わり、既定値は範囲内にクランプされます。
|
||||||
|
値はスクリプトから <code>obj.track0</code> ~ <code>obj.track3</code> で読めます。
|
||||||
|
</p>
|
||||||
|
|
||||||
|
<h2>チェックボックス</h2>
|
||||||
|
|
||||||
|
<p>
|
||||||
|
<code>--check0:</code> ~ <code>--check3:</code> で、名前と既定値(0 で off、0 以外で on)を指定します。
|
||||||
|
値は <code>obj.check0</code> ~ <code>obj.check3</code> で読めます。
|
||||||
|
</p>
|
||||||
|
|
||||||
|
<pre><code>--check0:反転を有効にする,0</code></pre>
|
||||||
|
|
||||||
|
<table>
|
||||||
|
<tr><th>項目</th><th>位置</th><th>省略時</th></tr>
|
||||||
|
<tr><td>名前</td><td>1 番目</td><td>空</td></tr>
|
||||||
|
<tr><td>既定値</td><td>2 番目</td><td>0(off)</td></tr>
|
||||||
|
</table>
|
||||||
|
|
||||||
|
<h2>色</h2>
|
||||||
|
|
||||||
|
<p>
|
||||||
|
<code>--color:</code> で Color パラメータの既定色を指定します。
|
||||||
|
<code>0xRRGGBB</code> 形式または 10 進整数で書けます。値はグローバルの <code>color</code> で読めます。
|
||||||
|
</p>
|
||||||
|
|
||||||
|
<pre><code>--color:0xFF8800</code></pre>
|
||||||
|
|
||||||
|
<h2>表示条件</h2>
|
||||||
|
|
||||||
|
<p>パラメータの表示・非表示は次のルールで決まります。</p>
|
||||||
|
|
||||||
|
<ul>
|
||||||
|
<li>トラックバー: 指定子がまったく無い場合は 4 本すべて表示。
|
||||||
|
いずれかの <code>--track@:</code> を書いた場合は、宣言したトラックのみ表示。</li>
|
||||||
|
<li>チェックボックス: <code>--check@:</code> を書いた場合、または指定子がまったく無く
|
||||||
|
スクリプト中で <code>obj.check@</code> を使っている場合に表示。</li>
|
||||||
|
<li>色: <code>--color:</code> を書いた場合、または指定子がまったく無く
|
||||||
|
スクリプト中で <code>color</code> を使っている場合に表示。</li>
|
||||||
|
</ul>
|
||||||
|
|
||||||
|
<h2>セクション(@)</h2>
|
||||||
|
|
||||||
|
<p>
|
||||||
|
行頭が <code>@</code> の行はセクションの区切りです。セクションを使う場合、
|
||||||
|
指定子と本文は最初のセクションから読み取られます。通常のスクリプトでは <code>@</code> を使わず、
|
||||||
|
指定子をスクリプト先頭にコメントとして並べれば十分です。
|
||||||
|
</p>
|
||||||
|
|
||||||
|
<h2>AviUtl 互換の宣言(dialog / param)</h2>
|
||||||
|
|
||||||
|
<p>
|
||||||
|
<code>--dialog:</code> と <code>--param:</code> は、AviUtl のダイアログ変数に近い書き方で、
|
||||||
|
本文の先頭に Lua の宣言を差し込みます。差し込まれた行は本体より前に実行されます。
|
||||||
|
</p>
|
||||||
|
|
||||||
|
<table>
|
||||||
|
<tr><th>指定子</th><th>説明</th></tr>
|
||||||
|
<tr><td><code>--param:宣言</code></td><td>指定した宣言を本文の先頭に追加する</td></tr>
|
||||||
|
<tr><td><code>--dialog:ラベル,宣言; ...</code></td><td><code>;</code> 区切りの各項目について、最初の <code>,</code> の後ろを宣言として先頭に追加する</td></tr>
|
||||||
|
</table>
|
||||||
|
|
||||||
|
<pre><code>--param:local speed = 90
|
||||||
|
obj.rz = time * speed</code></pre>
|
||||||
|
|
||||||
|
<h2>AviUtl 互換マップの対象エンジン</h2>
|
||||||
|
|
||||||
|
<p>
|
||||||
|
<code>obj.effect</code> が参照する互換マップの対象エンジンを切り替えます。
|
||||||
|
指定子 <code>--!aviutl</code> または <code>--!aviutl2</code> を書くと、
|
||||||
|
そのエンジンに対応するエフェクトだけを解決します。
|
||||||
|
指定子を書かないときは <code>--!aviutl</code> として扱います。詳細は
|
||||||
|
<a href="obj-functions.html">obj の関数</a>を参照してください。
|
||||||
|
</p>
|
||||||
|
|
||||||
|
<pre><code>--!aviutl2
|
||||||
|
obj.effect("ぼかし", "範囲", 20)</code></pre>
|
||||||
|
|
||||||
|
<div class="pager">
|
||||||
|
<a href="engines.html">← エンジンと高速化</a>
|
||||||
|
<a href="samples.html">サンプル集 →</a>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
</main>
|
||||||
|
<script src="assets/nav.js"></script>
|
||||||
|
</body>
|
||||||
|
</html>
|
||||||
+131
@@ -0,0 +1,131 @@
|
|||||||
|
<!DOCTYPE html>
|
||||||
|
<html lang="ja">
|
||||||
|
<head>
|
||||||
|
<meta charset="utf-8">
|
||||||
|
<meta name="viewport" content="width=device-width, initial-scale=1">
|
||||||
|
<title>エンジンと高速化 | Lua スクリプト for YMM4</title>
|
||||||
|
<link rel="stylesheet" href="assets/style.css">
|
||||||
|
</head>
|
||||||
|
<body>
|
||||||
|
<button id="navtoggle" aria-label="メニュー">☰</button>
|
||||||
|
<nav id="sidebar"></nav>
|
||||||
|
<main>
|
||||||
|
|
||||||
|
<h1>エンジンと高速化</h1>
|
||||||
|
|
||||||
|
<p>
|
||||||
|
このプラグインには複数の実行エンジンがあります。標準は MoonSharp ですが、重いピクセル処理のために
|
||||||
|
LuaJIT ネイティブレーンや、CPU / GPU カーネルへ変換するレーンを選べます。
|
||||||
|
座標などを動かすだけのスクリプトでは MoonSharp で十分速く、エンジンを意識する必要はありません。
|
||||||
|
</p>
|
||||||
|
|
||||||
|
<h2>エンジンの種類</h2>
|
||||||
|
|
||||||
|
<table>
|
||||||
|
<tr><th>エンジン</th><th>指定子</th><th>特徴</th></tr>
|
||||||
|
<tr><td>MoonSharp</td><td><code>--!moonsharp</code>(既定)</td><td>Lua 5.2 互換。全機能が使える標準エンジン</td></tr>
|
||||||
|
<tr><td>ネイティブ(LuaJIT)</td><td><code>--!native</code></td><td>別プロセスの LuaJIT で実行。ピクセル処理が大幅に高速</td></tr>
|
||||||
|
<tr><td>CPU カーネル</td><td><code>--!cpu</code></td><td>決まった形のピクセルループを並列実行に変換。MoonSharp と一致する結果</td></tr>
|
||||||
|
<tr><td>GPU カーネル</td><td><code>--!gpu</code></td><td>ピクセルループを GPU シェーダーに変換。最速だが float32 精度(明示指定のみ)</td></tr>
|
||||||
|
</table>
|
||||||
|
|
||||||
|
<div class="note">
|
||||||
|
スライダー <code>obj.slider0</code> ~ <code>obj.slider3</code> と文字列パラメータ
|
||||||
|
<code>obj.text</code> / <code>obj.font</code> / <code>obj.dir</code> / <code>obj.file_*</code> は、
|
||||||
|
MoonSharp とネイティブのどちらのエンジンでも同じ名前で参照できます。
|
||||||
|
CPU カーネルと GPU カーネルは数値計算に特化するため、文字列を扱いません。
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<h2>指定子の書き方</h2>
|
||||||
|
|
||||||
|
<p>
|
||||||
|
エンジンの指定子は <code>--!</code> で始まる 1 行です。トークンの前後の空白以外に文字があってはいけません。
|
||||||
|
スクリプトのどの行に書いても構いません。
|
||||||
|
</p>
|
||||||
|
|
||||||
|
<pre><code>--!native
|
||||||
|
for y = 0, obj.h - 1 do
|
||||||
|
for x = 0, obj.w - 1 do
|
||||||
|
local r, g, b, a = obj.getpixel(x, y)
|
||||||
|
obj.setpixel(x, y, 255 - r, 255 - g, 255 - b, a)
|
||||||
|
end
|
||||||
|
end</code></pre>
|
||||||
|
|
||||||
|
<h2>自動振り分け</h2>
|
||||||
|
|
||||||
|
<p>指定子が無いときは、スクリプトの内容から自動でエンジンが選ばれます。</p>
|
||||||
|
|
||||||
|
<ul>
|
||||||
|
<li>後述のカーネル条件に当てはまるピクセルループは、CPU カーネルで実行します。結果は MoonSharp と一致します。</li>
|
||||||
|
<li><code>obj.setoption</code> を使う描画系のスクリプトは、MoonSharp で実行します。</li>
|
||||||
|
<li>カーネル条件には当てはまらないものの <code>getpixel</code> や <code>setpixel</code> を使うスクリプトは、ネイティブが使えればネイティブで実行します。</li>
|
||||||
|
<li>それ以外は MoonSharp で実行します。</li>
|
||||||
|
</ul>
|
||||||
|
|
||||||
|
<div class="note">
|
||||||
|
明示した指定子は自動振り分けより優先されます。
|
||||||
|
<code>--!gpu</code> は明示したときだけ使われ、自動では選ばれません(精度が float32 のため)。
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<h2>カーネルに変換できる形</h2>
|
||||||
|
|
||||||
|
<p>
|
||||||
|
CPU / GPU カーネルは、次の決まった形のスクリプトだけを変換します。条件に合わないスクリプトは
|
||||||
|
カーネルにならず、自動でほかのエンジンへフォールバックします(結果は変わりません)。
|
||||||
|
</p>
|
||||||
|
|
||||||
|
<ul>
|
||||||
|
<li>先頭に <code>local</code> 宣言を置いてもよい。</li>
|
||||||
|
<li>本体は二重の数値 for ループ 1 組だけ。外側と内側で <code>obj.h</code> と <code>obj.w</code> をそれぞれ
|
||||||
|
<code>0</code> から <code>-1</code> まで回す。</li>
|
||||||
|
<li>内側ループの最初が <code>local r, g, b[, a] = obj.getpixel(x, y)</code>、最後が
|
||||||
|
<code>obj.setpixel(x, y, ...)</code>。</li>
|
||||||
|
<li>その間は <code>local</code> 宣言と代入のみ。</li>
|
||||||
|
</ul>
|
||||||
|
|
||||||
|
<p>カーネル内で使える要素は限られます。</p>
|
||||||
|
|
||||||
|
<table>
|
||||||
|
<tr><th>分類</th><th>使えるもの</th></tr>
|
||||||
|
<tr><td>演算子</td><td><code>+</code> <code>-</code> <code>*</code> <code>/</code> <code>%</code> <code>^</code>、単項マイナス、条件式 <code>cond and a or b</code></td></tr>
|
||||||
|
<tr><td>math 関数</td><td><code>abs, floor, ceil, sqrt, sin, cos, tan, asin, acos, atan, atan2, exp, log, pow, fmod, min, max</code></td></tr>
|
||||||
|
<tr><td>math 定数</td><td><code>math.pi</code>, <code>math.huge</code></td></tr>
|
||||||
|
<tr><td>条件</td><td>比較(<code>< > <= >= == ~=</code>)、<code>and</code> / <code>or</code> / <code>not</code>、<code>obj.check0</code> ~ <code>obj.check3</code></td></tr>
|
||||||
|
<tr><td>参照できる値</td><td>座標 <code>x</code> / <code>y</code>、<code>obj</code> の各フィールド、<code>scene.width/height/cx/cy</code>、
|
||||||
|
<code>time, frame, totalframe, framerate, timelineframe, timelinetime, layer, color</code></td></tr>
|
||||||
|
</table>
|
||||||
|
|
||||||
|
<h3>カーネルになるグレースケールの例</h3>
|
||||||
|
<pre><code>for y = 0, obj.h - 1 do
|
||||||
|
for x = 0, obj.w - 1 do
|
||||||
|
local r, g, b, a = obj.getpixel(x, y)
|
||||||
|
local gray = r * 0.299 + g * 0.587 + b * 0.114
|
||||||
|
obj.setpixel(x, y, gray, gray, gray, a)
|
||||||
|
end
|
||||||
|
end</code></pre>
|
||||||
|
|
||||||
|
<h2>フォールバックの動き</h2>
|
||||||
|
|
||||||
|
<ul>
|
||||||
|
<li><code>--!native</code> を指定しても、プラグインの隣に <code>native</code> フォルダが配置されていない場合は
|
||||||
|
MoonSharp で実行されます(ログに一度だけ警告が出ます)。期待した高速化が得られないときは、
|
||||||
|
ビルド・配置に <code>native</code> フォルダが含まれているか確認してください。</li>
|
||||||
|
<li><code>--!gpu</code> を指定しても、GPU カーネルを初期化できない場合は CPU カーネル、さらに MoonSharp の順で
|
||||||
|
フォールバックします。</li>
|
||||||
|
<li><code>--!cpu</code> を指定してもカーネル条件に合わないスクリプトは、ほかのエンジンで実行されます。</li>
|
||||||
|
</ul>
|
||||||
|
|
||||||
|
<div class="warn">
|
||||||
|
GPU カーネルは float32 精度で計算するため、MoonSharp / CPU カーネルとわずかに結果が異なることがあります。
|
||||||
|
厳密に一致させたい場合は CPU カーネルかネイティブを使ってください。
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div class="pager">
|
||||||
|
<a href="pixels.html">← ピクセル操作</a>
|
||||||
|
<a href="directives.html">パラメータ指定子 →</a>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
</main>
|
||||||
|
<script src="assets/nav.js"></script>
|
||||||
|
</body>
|
||||||
|
</html>
|
||||||
@@ -0,0 +1,104 @@
|
|||||||
|
<!DOCTYPE html>
|
||||||
|
<html lang="ja">
|
||||||
|
<head>
|
||||||
|
<meta charset="utf-8">
|
||||||
|
<meta name="viewport" content="width=device-width, initial-scale=1">
|
||||||
|
<title>導入と使い方 | Lua スクリプト for YMM4</title>
|
||||||
|
<link rel="stylesheet" href="assets/style.css">
|
||||||
|
</head>
|
||||||
|
<body>
|
||||||
|
<button id="navtoggle" aria-label="メニュー">☰</button>
|
||||||
|
<nav id="sidebar"></nav>
|
||||||
|
<main>
|
||||||
|
|
||||||
|
<h1>導入と使い方</h1>
|
||||||
|
|
||||||
|
<p>
|
||||||
|
「Lua スクリプト」は映像エフェクトの一種です。アイテム(テキスト・画像・図形など)に対して、
|
||||||
|
他のエフェクトと同じように追加して使います。
|
||||||
|
</p>
|
||||||
|
|
||||||
|
<h2>エフェクトを追加する</h2>
|
||||||
|
|
||||||
|
<ol>
|
||||||
|
<li>タイムライン上のアイテムを選択します。</li>
|
||||||
|
<li>プロパティエリアのエフェクト欄で、フィルタ効果の追加から「Lua スクリプト」を選びます。
|
||||||
|
検索欄では <code>lua</code> / <code>script</code> / <code>スクリプト</code> / <code>アニメーション効果</code> などのキーワードでも見つかります。</li>
|
||||||
|
<li>追加すると、スクリプト入力欄と、トラックバーやチェックボックスなどのパラメータが表示されます。</li>
|
||||||
|
</ol>
|
||||||
|
|
||||||
|
<h2>スクリプトエディタ</h2>
|
||||||
|
|
||||||
|
<p>スクリプト欄はコードエディタになっており、次の機能があります。</p>
|
||||||
|
|
||||||
|
<ul>
|
||||||
|
<li>シンタックスハイライト: Lua の構文に色が付きます。</li>
|
||||||
|
<li>入力補完: 識別子を入力すると候補が表示されます。<code>obj.</code> や <code>anim.</code> のように
|
||||||
|
ドットを入力すると、そのテーブルのメンバーだけが候補に出ます。スクリプト内で定義した関数も補完されます。</li>
|
||||||
|
<li>折りたたみ: <code>function ... end</code> などのブロックを折りたためます。</li>
|
||||||
|
<li>エラー表示: 構文エラー・実行時エラー・タイムアウトが起きると、該当行に赤い波線で警告が表示されます。</li>
|
||||||
|
</ul>
|
||||||
|
|
||||||
|
<h2>実行のしくみ</h2>
|
||||||
|
|
||||||
|
<p>
|
||||||
|
スクリプトは表示中の各フレームで 1 回ずつ実行されます。
|
||||||
|
プラグインは実行前に <code>obj</code>・<code>scene</code>・<code>ymm4</code> などへ現在の値を流し込み、
|
||||||
|
スクリプトの実行後に <code>obj</code> の値を読み戻して描画へ反映します。
|
||||||
|
</p>
|
||||||
|
|
||||||
|
<div class="note">
|
||||||
|
グローバル変数(自分で <code>x = 1</code> のように作った変数)の状態はフレームをまたいで保持されません。
|
||||||
|
毎フレーム、組み込み以外のグローバルはリセットされます。前のフレームの値を覚えておくことはできません。
|
||||||
|
時間に応じた変化は <code>time</code> や <code>obj.t</code> から計算してください。
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<h2>はじめてのスクリプト</h2>
|
||||||
|
|
||||||
|
<p>既定のフェードインを、少しずつ拡張してみます。</p>
|
||||||
|
|
||||||
|
<h3>1. 不透明度を変える</h3>
|
||||||
|
<pre><code>obj.alpha = math.min(time * 255, 255)</code></pre>
|
||||||
|
|
||||||
|
<h3>2. 横に動かす</h3>
|
||||||
|
<pre><code>obj.alpha = math.min(time * 255, 255)
|
||||||
|
obj.x = obj.x + math.sin(time * anim.tau) * 100</code></pre>
|
||||||
|
|
||||||
|
<h3>3. トラックバーで振幅を変える</h3>
|
||||||
|
<p>
|
||||||
|
パラメータパネルの <code>Track0</code> スライダーの値が <code>obj.track0</code> として読めます。
|
||||||
|
スライダーを動かすと、揺れの大きさが変わります。
|
||||||
|
</p>
|
||||||
|
<pre><code>obj.alpha = math.min(time * 255, 255)
|
||||||
|
obj.x = obj.x + math.sin(time * anim.tau) * obj.track0</code></pre>
|
||||||
|
|
||||||
|
<h2>パラメータパネル</h2>
|
||||||
|
|
||||||
|
<p>
|
||||||
|
既定では <code>Track0</code> ~ <code>Track3</code> の 4 本のトラックバーが表示されます。
|
||||||
|
チェックボックス(<code>Check0</code> ~ <code>Check3</code>)と色(<code>Color</code>)は、
|
||||||
|
スクリプトでそれらを使うか、指定子で宣言したときに表示されます。
|
||||||
|
表示条件と既定値・名前・範囲の指定方法は <a href="directives.html">パラメータ指定子</a> を参照してください。
|
||||||
|
</p>
|
||||||
|
|
||||||
|
<table>
|
||||||
|
<tr><th>UI</th><th>スクリプトでの読み取り</th><th>型</th></tr>
|
||||||
|
<tr><td>Track0 ~ Track3</td><td><code>obj.track0</code> ~ <code>obj.track3</code></td><td>数値</td></tr>
|
||||||
|
<tr><td>Check0 ~ Check3</td><td><code>obj.check0</code> ~ <code>obj.check3</code></td><td>真偽値</td></tr>
|
||||||
|
<tr><td>Color</td><td><code>color</code></td><td>数値 (0xRRGGBB)</td></tr>
|
||||||
|
</table>
|
||||||
|
|
||||||
|
<div class="warn">
|
||||||
|
スクリプトの実行には 5 秒のタイムアウトがあります。無限ループや非常に重い処理は中断されます。
|
||||||
|
詳しくは <a href="limits.html">制限事項とトラブル</a> を参照してください。
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div class="pager">
|
||||||
|
<a href="index.html">← 概要</a>
|
||||||
|
<a href="lua-basics.html">Lua の基礎 →</a>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
</main>
|
||||||
|
<script src="assets/nav.js"></script>
|
||||||
|
</body>
|
||||||
|
</html>
|
||||||
@@ -0,0 +1,92 @@
|
|||||||
|
<!DOCTYPE html>
|
||||||
|
<html lang="ja">
|
||||||
|
<head>
|
||||||
|
<meta charset="utf-8">
|
||||||
|
<meta name="viewport" content="width=device-width, initial-scale=1">
|
||||||
|
<title>グローバル変数 | Lua スクリプト for YMM4</title>
|
||||||
|
<link rel="stylesheet" href="assets/style.css">
|
||||||
|
</head>
|
||||||
|
<body>
|
||||||
|
<button id="navtoggle" aria-label="メニュー">☰</button>
|
||||||
|
<nav id="sidebar"></nav>
|
||||||
|
<main>
|
||||||
|
|
||||||
|
<h1>グローバル変数</h1>
|
||||||
|
|
||||||
|
<p>
|
||||||
|
スクリプトのグローバルスコープから直接参照できる変数です。
|
||||||
|
これらは毎フレーム、実行前にプラグインが設定します。値は読み取り専用です
|
||||||
|
(書き換えても描画には反映されません。描画を変えるには <a href="obj.html"><code>obj</code></a> を使います)。
|
||||||
|
</p>
|
||||||
|
|
||||||
|
<h2>時間とフレーム</h2>
|
||||||
|
|
||||||
|
<table>
|
||||||
|
<tr><th>変数</th><th>型</th><th>説明</th></tr>
|
||||||
|
<tr><td><code>time</code></td><td>数値</td><td>アイテム先頭からの経過時間(秒)。<code>obj.time</code> と同じ</td></tr>
|
||||||
|
<tr><td><code>frame</code></td><td>整数</td><td>アイテム先頭からの現在フレーム番号。<code>obj.frame</code> と同じ</td></tr>
|
||||||
|
<tr><td><code>totalframe</code></td><td>整数</td><td>アイテムの総フレーム数。<code>obj.totalframe</code> と同じ</td></tr>
|
||||||
|
<tr><td><code>framerate</code></td><td>整数</td><td>フレームレート(fps)。<code>obj.framerate</code> と同じ</td></tr>
|
||||||
|
<tr><td><code>timelineframe</code></td><td>整数</td><td>タイムライン先頭からの絶対フレーム番号</td></tr>
|
||||||
|
<tr><td><code>timelinetime</code></td><td>数値</td><td>タイムライン基準の現在時間(秒)</td></tr>
|
||||||
|
<tr><td><code>layer</code></td><td>整数</td><td>配置されているレイヤー番号。<code>obj.layer</code> と同じ</td></tr>
|
||||||
|
</table>
|
||||||
|
|
||||||
|
<p>
|
||||||
|
<code>time</code> はアニメーションの基準としてもっともよく使います。
|
||||||
|
アイテム内の進行割合(0.0 ~ 1.0)が欲しいときは <a href="obj.html"><code>obj.t</code></a> を使います。
|
||||||
|
</p>
|
||||||
|
|
||||||
|
<pre><code>obj.rz = time * 90
|
||||||
|
obj.alpha = obj.t * 255</code></pre>
|
||||||
|
|
||||||
|
<h2>色</h2>
|
||||||
|
|
||||||
|
<table>
|
||||||
|
<tr><th>変数</th><th>型</th><th>説明</th></tr>
|
||||||
|
<tr><td><code>color</code></td><td>数値</td><td>Color パラメータの色を <code>0xRRGGBB</code> の整数で表す</td></tr>
|
||||||
|
</table>
|
||||||
|
|
||||||
|
<p>
|
||||||
|
<code>color</code> は、Color パラメータが表示されているとき(スクリプトで <code>color</code> を使うか、
|
||||||
|
<a href="directives.html"><code>--color@</code></a> 指定子で宣言したとき)にのみ設定されます。
|
||||||
|
各成分は次のように取り出せます。
|
||||||
|
</p>
|
||||||
|
|
||||||
|
<pre><code>local r = bit32.rshift(bit32.band(color, 0xFF0000), 16)
|
||||||
|
local g = bit32.rshift(bit32.band(color, 0x00FF00), 8)
|
||||||
|
local b = bit32.band(color, 0x0000FF)</code></pre>
|
||||||
|
|
||||||
|
<h2>テーブル</h2>
|
||||||
|
|
||||||
|
<p>主要な機能は、グローバルに置かれた次のテーブルにまとまっています。</p>
|
||||||
|
|
||||||
|
<table>
|
||||||
|
<tr><th>テーブル</th><th>役割</th><th>参照</th></tr>
|
||||||
|
<tr><td><code>obj</code></td><td>描画対象の座標・回転・拡大率・不透明度と各種関数</td><td><a href="obj.html">obj</a> / <a href="obj-functions.html">obj の関数</a></td></tr>
|
||||||
|
<tr><td><code>anim</code></td><td>補間・波・ノイズ・色変換などのアニメーション関数</td><td><a href="anim.html">anim</a></td></tr>
|
||||||
|
<tr><td><code>scene</code></td><td>シーンの解像度</td><td><a href="scene-ymm4.html">scene</a></td></tr>
|
||||||
|
<tr><td><code>ymm4</code></td><td>グループ・タイムライン・再生状態などの環境情報</td><td><a href="scene-ymm4.html">ymm4</a></td></tr>
|
||||||
|
</table>
|
||||||
|
|
||||||
|
<p>標準ライブラリのテーブルもグローバルに置かれています。</p>
|
||||||
|
|
||||||
|
<table>
|
||||||
|
<tr><th>テーブル</th><th>役割</th></tr>
|
||||||
|
<tr><td><code>math</code></td><td>数学関数</td></tr>
|
||||||
|
<tr><td><code>string</code></td><td>文字列操作</td></tr>
|
||||||
|
<tr><td><code>table</code></td><td>テーブル操作</td></tr>
|
||||||
|
<tr><td><code>bit32</code></td><td>ビット演算</td></tr>
|
||||||
|
</table>
|
||||||
|
|
||||||
|
<p>これらの中身は <a href="stdlib.html">標準ライブラリ</a> にまとめています。</p>
|
||||||
|
|
||||||
|
<div class="pager">
|
||||||
|
<a href="stdlib.html">← 標準ライブラリ</a>
|
||||||
|
<a href="obj.html">obj オブジェクト →</a>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
</main>
|
||||||
|
<script src="assets/nav.js"></script>
|
||||||
|
</body>
|
||||||
|
</html>
|
||||||
+48
-598
@@ -3,628 +3,78 @@
|
|||||||
<head>
|
<head>
|
||||||
<meta charset="utf-8">
|
<meta charset="utf-8">
|
||||||
<meta name="viewport" content="width=device-width, initial-scale=1">
|
<meta name="viewport" content="width=device-width, initial-scale=1">
|
||||||
<title>Luaスクリプト for YMM4 サンプル集</title>
|
<title>概要 | Lua スクリプト for YMM4</title>
|
||||||
|
<link rel="stylesheet" href="assets/style.css">
|
||||||
</head>
|
</head>
|
||||||
<body>
|
<body>
|
||||||
|
<button id="navtoggle" aria-label="メニュー">☰</button>
|
||||||
|
<nav id="sidebar"></nav>
|
||||||
|
<main>
|
||||||
|
|
||||||
<img src="LuaScript.png" alt="Luaスクリプト for YMM4" width="640">
|
<h1>Lua スクリプト for YMM4</h1>
|
||||||
|
|
||||||
<h1>Luaスクリプト for YMM4 サンプル集</h1>
|
|
||||||
|
|
||||||
<p>
|
<p>
|
||||||
YukkuriMovieMaker4 の「Luaスクリプト」映像エフェクトで使えるサンプルと、
|
YukkuriMovieMaker4 の映像エフェクト「Lua スクリプト」の公式ドキュメントです。
|
||||||
利用可能な変数・関数・定数の一覧をまとめたページです。
|
このエフェクトでは、Lua のコードで映像を毎フレーム加工できます。座標・回転・拡大率・不透明度の制御から、
|
||||||
各サンプルはエフェクトのスクリプト欄にそのまま貼り付けて利用できます。
|
ピクセル単位の画像処理、図形やテキストの生成、ほかのエフェクトの呼び出しまでを、1 つのスクリプト欄で行えます。
|
||||||
スクリプトエンジンは MoonSharp (Lua 5.2 互換) です。
|
|
||||||
</p>
|
</p>
|
||||||
|
|
||||||
<p>
|
<p>
|
||||||
変数・関数の詳細な仕様は、スクリプトエディタのヘルプ、または
|
標準のスクリプトエンジンは Lua 5.2 互換の MoonSharp です。
|
||||||
<code>docs/LuaScript.ja-jp.txt</code> を参照してください。
|
重いピクセル処理のためには、LuaJIT で実行する <code>--!native</code> レーンと、
|
||||||
|
CPU・GPU カーネルへ変換する <code>--!cpu</code>・<code>--!gpu</code> レーンも用意しています。
|
||||||
|
詳しくは<a href="engines.html">エンジンと高速化</a>を参照してください。
|
||||||
</p>
|
</p>
|
||||||
|
|
||||||
<hr>
|
<div class="note">
|
||||||
|
このドキュメントは、プラグインの実装そのものに基づいて記述しています。
|
||||||
|
変数・関数・定数の名前と挙動は、スクリプトエディタの入力補完に表示されるものと一致します。
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<h2>このドキュメントの構成</h2>
|
||||||
|
|
||||||
<h2>目次</h2>
|
|
||||||
<nav>
|
|
||||||
<ul>
|
<ul>
|
||||||
<li><a href="#about">サンプルの読み方</a></li>
|
<li><a href="getting-started.html">導入と使い方</a> … エフェクトの追加方法と、エディタ・パラメータパネルの使い方を説明します。</li>
|
||||||
<li><a href="#basic">1. 基本</a></li>
|
<li><a href="lua-basics.html">Lua の基礎</a> … 変数・型・制御構文・関数・テーブルなど、Lua 言語そのものを学べます。</li>
|
||||||
<li><a href="#motion">2. 座標と動き</a></li>
|
<li><a href="obj.html">obj オブジェクト</a> … 座標・回転・拡大率・不透明度など、描画を制御する中心のテーブルです。</li>
|
||||||
<li><a href="#rotation">3. 回転</a></li>
|
<li><a href="anim.html">anim ライブラリ</a> … イージング・波・ノイズ・色変換など、アニメーション用の関数をまとめています。</li>
|
||||||
<li><a href="#scale">4. 拡大・変形</a></li>
|
<li><a href="pixels.html">ピクセル操作</a> … 画像を 1 ピクセルずつ読み書きする方法と注意点を説明します。</li>
|
||||||
<li><a href="#alpha">5. 不透明度・フェード</a></li>
|
<li><a href="samples.html">サンプル集</a> … そのまま貼り付けて使えるスクリプトを集めています。</li>
|
||||||
<li><a href="#ease">6. anim 補間・イージング</a></li>
|
|
||||||
<li><a href="#range">7. anim 範囲・周期</a></li>
|
|
||||||
<li><a href="#vector">8. anim ベクトル・幾何</a></li>
|
|
||||||
<li><a href="#noise">9. anim ノイズ・乱数</a></li>
|
|
||||||
<li><a href="#animcolor">10. anim 色</a></li>
|
|
||||||
<li><a href="#const">11. anim 定数</a></li>
|
|
||||||
<li><a href="#getobject">12. 他オブジェクトの参照 (obj.getobject)</a></li>
|
|
||||||
<li><a href="#pixel">13. ピクセル操作</a></li>
|
|
||||||
<li><a href="#scene">14. シーン情報 (scene)</a></li>
|
|
||||||
<li><a href="#ymm4">15. 環境・メタ情報 (ymm4)</a></li>
|
|
||||||
<li><a href="#globals">16. グローバル変数</a></li>
|
|
||||||
<li><a href="#stdlib">17. 標準ライブラリ</a></li>
|
|
||||||
<li><a href="#reference">クイックリファレンス</a></li>
|
|
||||||
</ul>
|
</ul>
|
||||||
</nav>
|
|
||||||
|
|
||||||
<hr>
|
<h2>最小の例</h2>
|
||||||
|
|
||||||
<h2 id="about">サンプルの読み方</h2>
|
<p>エフェクトを追加した直後に入っている既定のスクリプトは、フェードインです。</p>
|
||||||
<p>
|
|
||||||
スクリプト内では、変更可能な <code>obj</code> の値(座標・拡大率・回転・不透明度など)を
|
|
||||||
書き換えると描画に反映されます。読み戻されるのは
|
|
||||||
<code>x, y, z, ox, oy, zoom, aspect, alpha, rx, ry, rz</code>
|
|
||||||
(およびラジアン版 <code>rxr, ryr, rzr</code>、独立スケール <code>sx, sy</code>)です。
|
|
||||||
</p>
|
|
||||||
<p>
|
|
||||||
<code>time</code> はアイテム基準の経過秒数、<code>obj.t</code> はアイテム内の進行割合
|
|
||||||
(0.0 ~ 1.0) です。グローバル変数の状態はフレーム間で保持されません。
|
|
||||||
<code>math.random</code> は毎フレーム同じシードで初期化されるため、同一フレームでは
|
|
||||||
同じ値を返します。安定した乱数が必要な場合は <code>anim.rand</code> を使います。
|
|
||||||
</p>
|
|
||||||
|
|
||||||
<hr>
|
|
||||||
|
|
||||||
<h2 id="basic">1. 基本</h2>
|
|
||||||
|
|
||||||
<h3>1-1. フェードイン (デフォルトスクリプト)</h3>
|
|
||||||
<pre><code>obj.alpha = math.min(time * 255, 255)</code></pre>
|
<pre><code>obj.alpha = math.min(time * 255, 255)</code></pre>
|
||||||
|
|
||||||
<h3>1-2. フェードアウト</h3>
|
|
||||||
<pre><code>obj.alpha = math.max((obj.totalframe - obj.frame) / obj.framerate * 255, 0)</code></pre>
|
|
||||||
|
|
||||||
<h3>1-3. Track0 で不透明度を制御</h3>
|
|
||||||
<pre><code>obj.alpha = obj.track0</code></pre>
|
|
||||||
|
|
||||||
<h3>1-4. 時間に応じて回転</h3>
|
|
||||||
<pre><code>obj.rz = time * 90</code></pre>
|
|
||||||
|
|
||||||
<h3>1-5. Track0 でズームを制御</h3>
|
|
||||||
<pre><code>obj.zoom = obj.zoom * (1 + obj.track0 / 100)</code></pre>
|
|
||||||
|
|
||||||
<hr>
|
|
||||||
|
|
||||||
<h2 id="motion">2. 座標と動き</h2>
|
|
||||||
|
|
||||||
<h3>2-1. 左右の揺れ</h3>
|
|
||||||
<p>Track0 を振幅(px)、Track1 を周波数(回/秒)として使います。</p>
|
|
||||||
<pre><code>local amp = obj.track0
|
|
||||||
local freq = obj.track1
|
|
||||||
obj.x = obj.x + math.sin(time * anim.tau * freq) * amp</code></pre>
|
|
||||||
|
|
||||||
<h3>2-2. 円運動</h3>
|
|
||||||
<pre><code>local r = obj.track0
|
|
||||||
local dx, dy = anim.polar(r, time * 90)
|
|
||||||
obj.x = obj.x + dx
|
|
||||||
obj.y = obj.y + dy</code></pre>
|
|
||||||
|
|
||||||
<h3>2-3. バウンド (跳ねる)</h3>
|
|
||||||
<pre><code>local h = obj.track0
|
|
||||||
obj.y = obj.y - anim.bounce(anim.pingpong(time, 1)) * h</code></pre>
|
|
||||||
|
|
||||||
<h3>2-4. ゆらぎ (ノイズによる手ぶれ風)</h3>
|
|
||||||
<pre><code>obj.x = obj.x + (anim.noise(time * 2, 0, 0) - 0.5) * 20
|
|
||||||
obj.y = obj.y + (anim.noise(0, time * 2, 0) - 0.5) * 20
|
|
||||||
obj.rz = (anim.noise(0, 0, time * 2) - 0.5) * 10</code></pre>
|
|
||||||
|
|
||||||
<h3>2-5. 中心オフセットを基準に振り子運動</h3>
|
|
||||||
<p>回転中心 <code>ox, oy</code> をずらして振り子のように揺らします。</p>
|
|
||||||
<pre><code>obj.oy = -obj.hh
|
|
||||||
obj.rz = math.sin(time * anim.tau) * 30</code></pre>
|
|
||||||
|
|
||||||
<hr>
|
|
||||||
|
|
||||||
<h2 id="rotation">3. 回転</h2>
|
|
||||||
|
|
||||||
<h3>3-1. 度とラジアン</h3>
|
|
||||||
<p>
|
<p>
|
||||||
<code>rx, ry, rz</code> は度、<code>rxr, ryr, rzr</code> はラジアンです。
|
<code>obj.alpha</code> に値を代入すると不透明度が変わります。<code>time</code> はアイテム先頭からの経過秒数です。
|
||||||
ラジアン版を変更するとそちらが優先して反映されます。
|
スクリプトはフレームごとに実行され、<code>obj</code> の値を書き換えると描画へ反映されます。
|
||||||
</p>
|
|
||||||
<pre><code>obj.rzr = time * anim.tau</code></pre>
|
|
||||||
|
|
||||||
<h3>3-2. Y軸回転で立体的に回す</h3>
|
|
||||||
<pre><code>obj.ry = time * 180</code></pre>
|
|
||||||
|
|
||||||
<h3>3-3. 加速しながら回転 (イージング)</h3>
|
|
||||||
<pre><code>obj.rz = anim.ease_in(obj.t) * 360</code></pre>
|
|
||||||
|
|
||||||
<hr>
|
|
||||||
|
|
||||||
<h2 id="scale">4. 拡大・変形</h2>
|
|
||||||
|
|
||||||
<h3>4-1. 弾むように登場 (スケールイン)</h3>
|
|
||||||
<pre><code>local p = anim.duration(time, 0.3)
|
|
||||||
obj.zoom = obj.zoom * anim.elastic(p)</code></pre>
|
|
||||||
|
|
||||||
<h3>4-2. アスペクト比で横伸び・縦伸び</h3>
|
|
||||||
<p>
|
|
||||||
<code>aspect</code> は正で横方向に縮小、負で縦方向に縮小します。
|
|
||||||
</p>
|
|
||||||
<pre><code>obj.aspect = math.sin(time * anim.tau) * 0.5</code></pre>
|
|
||||||
|
|
||||||
<h3>4-3. X・Y を独立して拡大 (sx, sy)</h3>
|
|
||||||
<p>ぷにぷにと潰れる動きを <code>sx, sy</code> で表現します。</p>
|
|
||||||
<pre><code>local s = math.sin(time * anim.tau * 2) * 0.2
|
|
||||||
obj.sx = 1 + s
|
|
||||||
obj.sy = 1 - s</code></pre>
|
|
||||||
|
|
||||||
<hr>
|
|
||||||
|
|
||||||
<h2 id="alpha">5. 不透明度・フェード</h2>
|
|
||||||
|
|
||||||
<h3>5-1. 遅延フェードイン</h3>
|
|
||||||
<pre><code>local p = anim.duration(anim.delay(time, 0.5), 1)
|
|
||||||
obj.alpha = p * 255</code></pre>
|
|
||||||
|
|
||||||
<h3>5-2. 点滅 (矩形波)</h3>
|
|
||||||
<pre><code>obj.alpha = anim.square(time, 4) * 255</code></pre>
|
|
||||||
|
|
||||||
<h3>5-3. 滑らかな明滅 (正弦波)</h3>
|
|
||||||
<pre><code>obj.alpha = anim.oscillate(time, 64, 255, 1)</code></pre>
|
|
||||||
|
|
||||||
<hr>
|
|
||||||
|
|
||||||
<h2 id="ease">6. anim 補間・イージング</h2>
|
|
||||||
|
|
||||||
<h3>6-1. 2点間をイージングで移動</h3>
|
|
||||||
<pre><code>local tx, ty = 200, -100
|
|
||||||
local p = anim.ease_in_out(obj.t)
|
|
||||||
obj.x = anim.lerp(obj.x, tx, p)
|
|
||||||
obj.y = anim.lerp(obj.y, ty, p)</code></pre>
|
|
||||||
|
|
||||||
<h3>6-2. 行き過ぎてから戻る (back)</h3>
|
|
||||||
<pre><code>obj.x = obj.x + anim.back(obj.t) * 200</code></pre>
|
|
||||||
|
|
||||||
<h3>6-3. しきい値で切り替え (step / smoothstep)</h3>
|
|
||||||
<pre><code>obj.alpha = anim.smoothstep(0, 0.5, obj.t) * 255</code></pre>
|
|
||||||
|
|
||||||
<p>補間・イージング系関数の一覧です。</p>
|
|
||||||
<table border="1">
|
|
||||||
<tr><th>関数</th><th>説明</th></tr>
|
|
||||||
<tr><td>anim.lerp(a, b, t)</td><td>a と b を t (0.0~1.0) で線形補間</td></tr>
|
|
||||||
<tr><td>anim.smoothstep(e0, e1, x)</td><td>e0~e1 をエルミート補間で滑らかに遷移</td></tr>
|
|
||||||
<tr><td>anim.smootherstep(e0, e1, x)</td><td>2次導関数まで連続な、より滑らかな遷移</td></tr>
|
|
||||||
<tr><td>anim.ease_in(t)</td><td>2次イーズイン (加速)</td></tr>
|
|
||||||
<tr><td>anim.ease_out(t)</td><td>2次イーズアウト (減速)</td></tr>
|
|
||||||
<tr><td>anim.ease_in_out(t)</td><td>2次イーズイン・アウト (加速後減速)</td></tr>
|
|
||||||
<tr><td>anim.elastic(t)</td><td>弾むようなスプリングイージング</td></tr>
|
|
||||||
<tr><td>anim.back(t)</td><td>行き過ぎてから戻るイージング</td></tr>
|
|
||||||
<tr><td>anim.bounce(t)</td><td>バウンドするイージング</td></tr>
|
|
||||||
<tr><td>anim.step(edge, x)</td><td>x が edge 以上なら 1.0、未満なら 0.0</td></tr>
|
|
||||||
<tr><td>anim.bezier(t, p0, p1, p2, p3)</td><td>t における3次ベジェ曲線の値</td></tr>
|
|
||||||
</table>
|
|
||||||
|
|
||||||
<hr>
|
|
||||||
|
|
||||||
<h2 id="range">7. anim 範囲・周期</h2>
|
|
||||||
|
|
||||||
<h3>7-1. 値の範囲変換 (map)</h3>
|
|
||||||
<pre><code>obj.rz = anim.map(obj.track0, 0, 100, -180, 180)</code></pre>
|
|
||||||
|
|
||||||
<h3>7-2. 三角波で往復</h3>
|
|
||||||
<pre><code>obj.x = obj.x + (anim.triangle(time, 1) - 0.5) * 200</code></pre>
|
|
||||||
|
|
||||||
<p>範囲・周期系関数の一覧です。</p>
|
|
||||||
<table border="1">
|
|
||||||
<tr><th>関数</th><th>説明</th></tr>
|
|
||||||
<tr><td>anim.clamp(v, lo, hi)</td><td>v を lo ~ hi の範囲に収める</td></tr>
|
|
||||||
<tr><td>anim.map(v, a1, b1, a2, b2)</td><td>範囲 a1~b1 の v を a2~b2 に変換</td></tr>
|
|
||||||
<tr><td>anim.norm(v, lo, hi)</td><td>v が lo~hi のどの割合 (0.0~1.0) かを取得</td></tr>
|
|
||||||
<tr><td>anim.wrap(v, lo, hi)</td><td>v を lo ~ hi でループさせる</td></tr>
|
|
||||||
<tr><td>anim.pingpong(t, len)</td><td>0 ~ len を往復する値</td></tr>
|
|
||||||
<tr><td>anim.sign(v)</td><td>符号 (正=1, 負=-1, ゼロ=0)</td></tr>
|
|
||||||
<tr><td>anim.fract(v)</td><td>小数部分のみを取得</td></tr>
|
|
||||||
<tr><td>anim.oscillate(t, lo, hi, freq)</td><td>freq の周波数で lo~hi を正弦波で往復</td></tr>
|
|
||||||
<tr><td>anim.triangle(t, freq)</td><td>freq の周波数で 0.0~1.0 を往復する三角波</td></tr>
|
|
||||||
<tr><td>anim.square(t, freq)</td><td>freq の周波数で 1.0 と 0.0 を切り替える矩形波</td></tr>
|
|
||||||
<tr><td>anim.duration(t, dur)</td><td>時間 dur に対する割合 (0.0~1.0, clamp あり)</td></tr>
|
|
||||||
<tr><td>anim.delay(t, d)</td><td>時間 d 経過後から開始する時間 (0以下は0)</td></tr>
|
|
||||||
</table>
|
|
||||||
|
|
||||||
<hr>
|
|
||||||
|
|
||||||
<h2 id="vector">8. anim ベクトル・幾何</h2>
|
|
||||||
|
|
||||||
<h3>8-1. 座標を回転させる</h3>
|
|
||||||
<pre><code>local rx, ry = anim.rotate(obj.track0, 0, time * 90)
|
|
||||||
obj.x = obj.x + rx
|
|
||||||
obj.y = obj.y + ry</code></pre>
|
|
||||||
|
|
||||||
<h3>8-2. 2点間の距離で挙動を変える</h3>
|
|
||||||
<pre><code>local d = anim.dist(obj.x, obj.y, 0, 0)
|
|
||||||
obj.alpha = anim.clamp(255 - d, 0, 255)</code></pre>
|
|
||||||
|
|
||||||
<p>ベクトル・幾何系関数の一覧です。</p>
|
|
||||||
<table border="1">
|
|
||||||
<tr><th>関数</th><th>説明</th></tr>
|
|
||||||
<tr><td>anim.len(x, y)</td><td>ベクトル (x, y) の長さ</td></tr>
|
|
||||||
<tr><td>anim.dist(x1, y1, x2, y2)</td><td>2点間の距離</td></tr>
|
|
||||||
<tr><td>anim.dot(x1, y1, x2, y2)</td><td>2ベクトルの内積</td></tr>
|
|
||||||
<tr><td>anim.normalize(x, y)</td><td>正規化した方向ベクトル (Tuple で返却)</td></tr>
|
|
||||||
<tr><td>anim.polar(r, a)</td><td>半径 r・角度 a(度) から移動量 (x, y)</td></tr>
|
|
||||||
<tr><td>anim.rotate(x, y, a)</td><td>(x, y) を a(度) 回転させた座標</td></tr>
|
|
||||||
</table>
|
|
||||||
|
|
||||||
<hr>
|
|
||||||
|
|
||||||
<h2 id="noise">9. anim ノイズ・乱数</h2>
|
|
||||||
|
|
||||||
<h3>9-1. 安定した乱数で個体差をつける</h3>
|
|
||||||
<p>
|
|
||||||
<code>anim.rand</code> はシード引数に基づく決定的な乱数です。レイヤー番号をシードにすると
|
|
||||||
オブジェクトごとに異なる固定値が得られます。
|
|
||||||
</p>
|
|
||||||
<pre><code>local offset = anim.rand(-50, 50, obj.layer)
|
|
||||||
obj.x = obj.x + offset</code></pre>
|
|
||||||
|
|
||||||
<h3>9-2. ノイズで揺らぐ不透明度</h3>
|
|
||||||
<pre><code>obj.alpha = anim.noise(time, obj.layer, 0) * 255</code></pre>
|
|
||||||
|
|
||||||
<table border="1">
|
|
||||||
<tr><th>関数</th><th>説明</th></tr>
|
|
||||||
<tr><td>anim.noise(x, y, z)</td><td>1~3次元の滑らかなノイズ (0.0~1.0)</td></tr>
|
|
||||||
<tr><td>anim.rand(min, max, s)</td><td>シード s に基づく安定した乱数</td></tr>
|
|
||||||
</table>
|
|
||||||
|
|
||||||
<hr>
|
|
||||||
|
|
||||||
<h2 id="animcolor">10. anim 色</h2>
|
|
||||||
|
|
||||||
<h3>10-1. 時間で色相を回す (虹色)</h3>
|
|
||||||
<pre><code>local hue = anim.wrap(time * 60, 0, 360)
|
|
||||||
local cr, cg, cb = anim.hsv_to_rgb(hue, 1, 1)
|
|
||||||
local pd = obj.getpixeldata()
|
|
||||||
local n = pd.width * pd.height
|
|
||||||
for i = 0, n - 1 do
|
|
||||||
local base = i * 4
|
|
||||||
pd:set(base + 1, pd:get(base + 1) * cr / 255)
|
|
||||||
pd:set(base + 2, pd:get(base + 2) * cg / 255)
|
|
||||||
pd:set(base + 3, pd:get(base + 3) * cb / 255)
|
|
||||||
end</code></pre>
|
|
||||||
|
|
||||||
<table border="1">
|
|
||||||
<tr><th>関数</th><th>説明</th></tr>
|
|
||||||
<tr><td>anim.hsv_to_rgb(h, s, v)</td><td>HSV (色相0~360, 彩度0~1, 明度0~1) を RGB に変換</td></tr>
|
|
||||||
<tr><td>anim.rgb_to_hsv(r, g, b)</td><td>RGB (0~255) を HSV に変換</td></tr>
|
|
||||||
</table>
|
|
||||||
|
|
||||||
<hr>
|
|
||||||
|
|
||||||
<h2 id="const">11. anim 定数</h2>
|
|
||||||
<table border="1">
|
|
||||||
<tr><th>定数</th><th>説明</th></tr>
|
|
||||||
<tr><td>anim.tau</td><td>円周率の2倍 (math.pi * 2)</td></tr>
|
|
||||||
<tr><td>anim.e</td><td>ネイピア数 (math.exp(1))</td></tr>
|
|
||||||
<tr><td>anim.phi</td><td>黄金比 ((1 + math.sqrt(5)) / 2)</td></tr>
|
|
||||||
<tr><td>anim.sqrt2</td><td>2の平方根 (math.sqrt(2))</td></tr>
|
|
||||||
</table>
|
|
||||||
|
|
||||||
<hr>
|
|
||||||
|
|
||||||
<h2 id="getobject">12. 他オブジェクトの参照 (obj.getobject)</h2>
|
|
||||||
|
|
||||||
<p>
|
|
||||||
<code>obj.getobject(tag [, frame])</code> は、対象アイテムの「備考」欄に入力した文字列を
|
|
||||||
タグとして、そのアイテムの描画情報を取得します。備考欄はプロパティエリアの上側にあります。
|
|
||||||
第2引数 <code>frame</code> を指定すると、そのタイムラインフレーム時点の値を取得します
|
|
||||||
(省略時は現在フレーム)。返り値は対象アイテム自身の座標・回転・拡大率であり、
|
|
||||||
グループ制御・カメラ制御による変形は含みません。一致するアイテムが無い場合は
|
|
||||||
<code>nil</code> を返します。同じタグのアイテムが複数あるときは、対象フレームで
|
|
||||||
表示中のものを優先します。
|
|
||||||
</p>
|
</p>
|
||||||
|
|
||||||
<h3>12-1. 発射元の座標に合わせる</h3>
|
<h2>できることの全体像</h2>
|
||||||
<pre><code>local src = obj.getobject("routersys")
|
|
||||||
if src then
|
|
||||||
obj.x = src.x
|
|
||||||
obj.y = src.y
|
|
||||||
end</code></pre>
|
|
||||||
|
|
||||||
<h3>12-2. 発射元へ向かって移動する</h3>
|
<table>
|
||||||
<pre><code>local target = obj.getobject("routersys")
|
<tr><th>分野</th><th>主な API</th><th>参照</th></tr>
|
||||||
if target then
|
<tr><td>座標・回転・拡大率・不透明度の制御</td><td><code>obj.x</code>, <code>obj.rz</code>, <code>obj.zoom</code>, <code>obj.alpha</code> ほか</td><td><a href="obj.html">obj</a></td></tr>
|
||||||
local p = anim.ease_in_out(obj.t)
|
<tr><td>時間・フレーム情報</td><td><code>time</code>, <code>frame</code>, <code>obj.t</code>, <code>timelineframe</code></td><td><a href="globals.html">グローバル変数</a></td></tr>
|
||||||
obj.x = anim.lerp(obj.x, target.x, p)
|
<tr><td>アニメーション補間・波・ノイズ・色</td><td><code>anim.lerp</code>, <code>anim.ease_in_out</code>, <code>anim.noise</code>, <code>anim.hsv_to_rgb</code></td><td><a href="anim.html">anim</a></td></tr>
|
||||||
obj.y = anim.lerp(obj.y, target.y, p)
|
<tr><td>他アイテムの参照</td><td><code>obj.getobject</code></td><td><a href="obj-functions.html">obj の関数</a></td></tr>
|
||||||
end</code></pre>
|
<tr><td>ピクセル操作</td><td><code>obj.getpixel</code>, <code>obj.setpixel</code>, <code>obj.getpixeldata</code></td><td><a href="pixels.html">ピクセル操作</a></td></tr>
|
||||||
|
<tr><td>図形・テキスト・画像・動画の読み込み</td><td><code>obj.load</code>, <code>obj.setfont</code></td><td><a href="obj-functions.html">obj の関数</a></td></tr>
|
||||||
<h3>12-3. 発射元へ向きながら移動する (ファンネル風)</h3>
|
<tr><td>他エフェクトの適用・描画</td><td><code>obj.effect</code>, <code>obj.draw</code>, <code>obj.drawpoly</code></td><td><a href="obj-functions.html">obj の関数</a></td></tr>
|
||||||
<pre><code>local target = obj.getobject("routersys")
|
<tr><td>シーン・環境情報</td><td><code>scene.width</code>, <code>ymm4.is_saving</code></td><td><a href="scene-ymm4.html">scene / ymm4</a></td></tr>
|
||||||
if target then
|
<tr><td>パラメータ UI の定義</td><td><code>--track@</code>, <code>--check@</code>, <code>--color@</code>, <code>--dialog:</code></td><td><a href="directives.html">パラメータ指定子</a></td></tr>
|
||||||
local p = anim.ease_in_out(obj.t)
|
<tr><td>高速化エンジンの選択</td><td><code>--!native</code>, <code>--!cpu</code>, <code>--!gpu</code></td><td><a href="engines.html">エンジンと高速化</a></td></tr>
|
||||||
local nx = anim.lerp(obj.x, target.x, p)
|
|
||||||
local ny = anim.lerp(obj.y, target.y, p)
|
|
||||||
obj.rz = math.deg(math.atan2(target.y - obj.y, target.x - obj.x))
|
|
||||||
obj.x = nx
|
|
||||||
obj.y = ny
|
|
||||||
end</code></pre>
|
|
||||||
|
|
||||||
<h3>12-4. 一定速度で接近し、到達したら停止</h3>
|
|
||||||
<pre><code>local target = obj.getobject("routersys")
|
|
||||||
if target then
|
|
||||||
local dx = target.x - obj.x
|
|
||||||
local dy = target.y - obj.y
|
|
||||||
local dist = anim.len(dx, dy)
|
|
||||||
if dist > 0 then
|
|
||||||
local step = math.min(dist, obj.track0 * obj.time)
|
|
||||||
obj.x = obj.x + dx / dist * step
|
|
||||||
obj.y = obj.y + dy / dist * step
|
|
||||||
end
|
|
||||||
end</code></pre>
|
|
||||||
|
|
||||||
<h3>12-5. 表示中のときだけ追従する</h3>
|
|
||||||
<pre><code>local target = obj.getobject("routersys")
|
|
||||||
if target and target.exist then
|
|
||||||
obj.x = target.x
|
|
||||||
obj.y = target.y
|
|
||||||
end</code></pre>
|
|
||||||
|
|
||||||
<h3>12-6. 発射元の拡大率・回転・不透明度も引き継ぐ</h3>
|
|
||||||
<pre><code>local src = obj.getobject("routersys")
|
|
||||||
if src then
|
|
||||||
obj.x = src.x
|
|
||||||
obj.y = src.y
|
|
||||||
obj.zoom = src.zoom
|
|
||||||
obj.rz = src.rz
|
|
||||||
obj.alpha = src.alpha
|
|
||||||
end</code></pre>
|
|
||||||
|
|
||||||
<h3>12-7. 発射時の座標に固定する</h3>
|
|
||||||
<p>
|
|
||||||
弾の発射フレーム (弾アイテムの開始フレーム) は <code>timelineframe - frame</code> で
|
|
||||||
求まります。そのフレーム時点の発射元座標を取得すれば、発射元が動いても弾の原点は
|
|
||||||
発射位置に固定されます。
|
|
||||||
</p>
|
|
||||||
<pre><code>local fire = timelineframe - frame
|
|
||||||
local src = obj.getobject("routersys", fire)
|
|
||||||
if src then
|
|
||||||
obj.x = src.x
|
|
||||||
obj.y = src.y
|
|
||||||
end</code></pre>
|
|
||||||
|
|
||||||
<p>返り値テーブルのメンバーは以下のとおりです。</p>
|
|
||||||
<table border="1">
|
|
||||||
<tr><th>メンバー</th><th>説明</th></tr>
|
|
||||||
<tr><td>exist</td><td>対象フレームが表示期間内か (boolean)</td></tr>
|
|
||||||
<tr><td>x / y / z</td><td>描画位置 (ピクセル)</td></tr>
|
|
||||||
<tr><td>zoom / sx / sy</td><td>拡大率 (1.0 で等倍)</td></tr>
|
|
||||||
<tr><td>rx / ry / rz</td><td>X / Y / Z 軸回転角 (度)</td></tr>
|
|
||||||
<tr><td>rxr / ryr / rzr</td><td>X / Y / Z 軸回転角 (ラジアン)</td></tr>
|
|
||||||
<tr><td>alpha</td><td>不透明度 (0.0 ~ 255.0)</td></tr>
|
|
||||||
<tr><td>layer</td><td>レイヤー番号</td></tr>
|
|
||||||
</table>
|
</table>
|
||||||
|
|
||||||
<hr>
|
<div class="pager">
|
||||||
|
<span></span>
|
||||||
<h2 id="pixel">13. ピクセル操作</h2>
|
<a href="getting-started.html">導入と使い方 →</a>
|
||||||
|
</div>
|
||||||
<p>
|
|
||||||
ピクセル操作は実際の入力画像へアクセスするため、初回アクセス時に画像データの
|
|
||||||
転送が発生します。座標は画像の左上を (0, 0) とし、右・下方向が正です。
|
|
||||||
取得値はストレートアルファ相当です。
|
|
||||||
</p>
|
|
||||||
|
|
||||||
<h3>13-1. getpixel / setpixel で赤成分を反転</h3>
|
|
||||||
<pre><code>for y = 0, obj.h - 1 do
|
|
||||||
for x = 0, obj.w - 1 do
|
|
||||||
local r, g, b, a = obj.getpixel(x, y)
|
|
||||||
obj.setpixel(x, y, 255 - r, g, b, a)
|
|
||||||
end
|
|
||||||
end</code></pre>
|
|
||||||
|
|
||||||
<h3>13-2. getpixeldata でグレースケール (高速)</h3>
|
|
||||||
<p>
|
|
||||||
<code>obj.getpixeldata()</code> はピクセルへ直接アクセスできるプロキシを返します。
|
|
||||||
インデックスは 1 始まりで、チャンネルは R, G, B, A の繰り返しです。
|
|
||||||
<code>pixel(x, y)</code> の R チャンネルのインデックスは <code>(y * obj.w + x) * 4 + 1</code> です。
|
|
||||||
</p>
|
|
||||||
<pre><code>local pd = obj.getpixeldata()
|
|
||||||
local w = pd.width
|
|
||||||
local h = pd.height
|
|
||||||
for y = 0, h - 1 do
|
|
||||||
for x = 0, w - 1 do
|
|
||||||
local base = (y * w + x) * 4
|
|
||||||
local r = pd:get(base + 1)
|
|
||||||
local g = pd:get(base + 2)
|
|
||||||
local b = pd:get(base + 3)
|
|
||||||
local gray = r * 0.299 + g * 0.587 + b * 0.114
|
|
||||||
pd:set(base + 1, gray)
|
|
||||||
pd:set(base + 2, gray)
|
|
||||||
pd:set(base + 3, gray)
|
|
||||||
end
|
|
||||||
end</code></pre>
|
|
||||||
|
|
||||||
<h3>13-3. 中心からの距離でフェード (円形ビネット)</h3>
|
|
||||||
<pre><code>local pd = obj.getpixeldata()
|
|
||||||
local w = pd.width
|
|
||||||
local h = pd.height
|
|
||||||
local cx = w / 2
|
|
||||||
local cy = h / 2
|
|
||||||
local maxd = anim.len(cx, cy)
|
|
||||||
for y = 0, h - 1 do
|
|
||||||
for x = 0, w - 1 do
|
|
||||||
local base = (y * w + x) * 4
|
|
||||||
local d = anim.len(x - cx, y - cy)
|
|
||||||
local k = anim.clamp(1 - d / maxd, 0, 1)
|
|
||||||
pd:set(base + 4, pd:get(base + 4) * k)
|
|
||||||
end
|
|
||||||
end</code></pre>
|
|
||||||
|
|
||||||
<p>
|
|
||||||
<code>obj.putpixeldata()</code> は AviUtl との互換性のために存在しますが、
|
|
||||||
このプラグインでは変更が自動的に反映されるため呼び出す必要はありません (no-op)。
|
|
||||||
</p>
|
|
||||||
|
|
||||||
<table border="1">
|
|
||||||
<tr><th>関数</th><th>戻り値</th><th>説明</th></tr>
|
|
||||||
<tr><td>obj.getpixel(x, y)</td><td>r, g, b, a</td><td>指定座標のピクセルを取得 (各成分 0~255)</td></tr>
|
|
||||||
<tr><td>obj.setpixel(x, y, r, g, b [, a])</td><td>なし</td><td>指定座標へ書き込み (a 既定 255)</td></tr>
|
|
||||||
<tr><td>obj.getpixeldata()</td><td>PixelDataProxy</td><td>全ピクセルへの直接アクセスプロキシ</td></tr>
|
|
||||||
<tr><td>obj.putpixeldata()</td><td>なし</td><td>互換用の空実装</td></tr>
|
|
||||||
</table>
|
|
||||||
|
|
||||||
<hr>
|
|
||||||
|
|
||||||
<h2 id="scene">14. シーン情報 (scene)</h2>
|
|
||||||
|
|
||||||
<h3>14-1. シーンサイズに対する相対配置</h3>
|
|
||||||
<pre><code>obj.x = scene.cx * obj.track0 / 100</code></pre>
|
|
||||||
|
|
||||||
<table border="1">
|
|
||||||
<tr><th>メンバー</th><th>説明</th></tr>
|
|
||||||
<tr><td>scene.width</td><td>シーンの横解像度 (ピクセル)</td></tr>
|
|
||||||
<tr><td>scene.height</td><td>シーンの縦解像度 (ピクセル)</td></tr>
|
|
||||||
<tr><td>scene.cx</td><td>横解像度の半分 (= scene.width / 2)</td></tr>
|
|
||||||
<tr><td>scene.cy</td><td>縦解像度の半分 (= scene.height / 2)</td></tr>
|
|
||||||
</table>
|
|
||||||
|
|
||||||
<hr>
|
|
||||||
|
|
||||||
<h2 id="ymm4">15. 環境・メタ情報 (ymm4)</h2>
|
|
||||||
|
|
||||||
<h3>15-1. グループ内のインデックスで時間差をつける</h3>
|
|
||||||
<pre><code>local d = ymm4.group_index * 0.1
|
|
||||||
local p = anim.duration(anim.delay(time, d), 0.5)
|
|
||||||
obj.alpha = p * 255</code></pre>
|
|
||||||
|
|
||||||
<h3>15-2. グループ内の進行割合で配置をずらす</h3>
|
|
||||||
<pre><code>obj.x = obj.x + ymm4.group_ratio * 400</code></pre>
|
|
||||||
|
|
||||||
<h3>15-3. 出力時のみ挙動を変える</h3>
|
|
||||||
<pre><code>if ymm4.is_saving then
|
|
||||||
obj.alpha = 255
|
|
||||||
else
|
|
||||||
obj.alpha = 128
|
|
||||||
end</code></pre>
|
|
||||||
|
|
||||||
<table border="1">
|
|
||||||
<tr><th>メンバー</th><th>説明</th></tr>
|
|
||||||
<tr><td>ymm4.group_index</td><td>グループ制御内の現在のインデックス (0始まり)</td></tr>
|
|
||||||
<tr><td>ymm4.group_count</td><td>グループ制御内の総アイテム数</td></tr>
|
|
||||||
<tr><td>ymm4.group_ratio</td><td>グループ内の進行割合 (group_index / group_count)</td></tr>
|
|
||||||
<tr><td>ymm4.timeline_totalframe</td><td>タイムライン全体の総フレーム数</td></tr>
|
|
||||||
<tr><td>ymm4.timeline_totaltime</td><td>タイムライン全体の総時間 (秒)</td></tr>
|
|
||||||
<tr><td>ymm4.time_ratio</td><td>現在の再生位置の割合 (0.0 ~ 1.0)</td></tr>
|
|
||||||
<tr><td>ymm4.is_saving</td><td>動画出力中のみ true</td></tr>
|
|
||||||
<tr><td>ymm4.is_playing</td><td>再生中のみ true</td></tr>
|
|
||||||
<tr><td>ymm4.is_paused</td><td>一時停止中のみ true</td></tr>
|
|
||||||
<tr><td>ymm4.scene_id</td><td>現在のシーンを識別する文字列 (Guid)</td></tr>
|
|
||||||
</table>
|
|
||||||
|
|
||||||
<hr>
|
|
||||||
|
|
||||||
<h2 id="globals">16. グローバル変数</h2>
|
|
||||||
<p>以下の変数はスクリプトのグローバルスコープで直接参照できます (すべて読み取り専用)。</p>
|
|
||||||
<table border="1">
|
|
||||||
<tr><th>変数</th><th>説明</th></tr>
|
|
||||||
<tr><td>time</td><td>オブジェクト基準の現在時間 (秒)。obj.time と同じ</td></tr>
|
|
||||||
<tr><td>frame</td><td>オブジェクト基準の現在フレーム番号。obj.frame と同じ</td></tr>
|
|
||||||
<tr><td>totalframe</td><td>オブジェクトの総フレーム数。obj.totalframe と同じ</td></tr>
|
|
||||||
<tr><td>framerate</td><td>フレームレート (fps)。obj.framerate と同じ</td></tr>
|
|
||||||
<tr><td>timelineframe</td><td>タイムライン先頭からの絶対フレーム番号</td></tr>
|
|
||||||
<tr><td>timelinetime</td><td>タイムライン基準の現在時間 (秒)</td></tr>
|
|
||||||
<tr><td>layer</td><td>配置されているレイヤー番号。obj.layer と同じ</td></tr>
|
|
||||||
<tr><td>obj / scene / ymm4 / anim</td><td>各テーブル (本ページ参照)</td></tr>
|
|
||||||
</table>
|
|
||||||
|
|
||||||
<hr>
|
|
||||||
|
|
||||||
<h2 id="stdlib">17. 標準ライブラリ</h2>
|
|
||||||
<p>利用できる標準ライブラリは以下に限定されます。io, os, debug, ffi, require 等は使用できません。</p>
|
|
||||||
|
|
||||||
<h3>math</h3>
|
|
||||||
<p>
|
|
||||||
abs, ceil, cos, exp, floor, fmod, huge, log, max, min, modf, pi, random, randomseed,
|
|
||||||
sin, sqrt, tan, atan, atan2, deg, rad, ldexp, frexp, sinh, cosh, tanh, type,
|
|
||||||
tointeger, maxinteger, mininteger
|
|
||||||
</p>
|
|
||||||
|
|
||||||
<h3>string</h3>
|
|
||||||
<p>
|
|
||||||
format, len, sub, upper, lower, rep, reverse, find, match, gmatch, gsub, byte, char,
|
|
||||||
dump, pack, unpack, packsize
|
|
||||||
</p>
|
|
||||||
|
|
||||||
<h3>table</h3>
|
|
||||||
<p>insert, remove, sort, concat, unpack, move</p>
|
|
||||||
|
|
||||||
<h3>bit32</h3>
|
|
||||||
<p>
|
|
||||||
band, bor, bxor, bnot, lshift, rshift, arshift, extract, replace, btest, countlz, countrz
|
|
||||||
</p>
|
|
||||||
|
|
||||||
<h3>基本関数</h3>
|
|
||||||
<p>
|
|
||||||
type, tostring, tonumber, select, error, assert, print, ipairs, pairs, next, unpack,
|
|
||||||
setmetatable, getmetatable, rawget, rawset, rawequal, rawlen, pcall, xpcall
|
|
||||||
</p>
|
|
||||||
|
|
||||||
<hr>
|
|
||||||
|
|
||||||
<h2 id="reference">クイックリファレンス</h2>
|
|
||||||
|
|
||||||
<h3>obj (変更可能メンバー)</h3>
|
|
||||||
<table border="1">
|
|
||||||
<tr><th>メンバー</th><th>説明</th></tr>
|
|
||||||
<tr><td>obj.x / obj.y / obj.z</td><td>描画位置 (ピクセル)</td></tr>
|
|
||||||
<tr><td>obj.ox / obj.oy / obj.oz</td><td>回転中心のオフセット (ピクセル)</td></tr>
|
|
||||||
<tr><td>obj.zoom</td><td>拡大率 (sx と sy の平均、1.0 で等倍)</td></tr>
|
|
||||||
<tr><td>obj.aspect</td><td>アスペクト比 (-1.0 ~ 1.0)</td></tr>
|
|
||||||
<tr><td>obj.sx / obj.sy</td><td>X / Y 方向の独立拡大率</td></tr>
|
|
||||||
<tr><td>obj.alpha</td><td>不透明度 (0.0 ~ 255.0)</td></tr>
|
|
||||||
<tr><td>obj.rx / obj.ry / obj.rz</td><td>X / Y / Z 軸回転角 (度)</td></tr>
|
|
||||||
<tr><td>obj.rxr / obj.ryr / obj.rzr</td><td>X / Y / Z 軸回転角 (ラジアン)</td></tr>
|
|
||||||
</table>
|
|
||||||
|
|
||||||
<h3>obj (読み取り専用メンバー)</h3>
|
|
||||||
<table border="1">
|
|
||||||
<tr><th>メンバー</th><th>説明</th></tr>
|
|
||||||
<tr><td>obj.w / obj.h</td><td>入力画像の幅 / 高さ (ピクセル)</td></tr>
|
|
||||||
<tr><td>obj.hw / obj.hh</td><td>幅 / 高さの半分</td></tr>
|
|
||||||
<tr><td>obj.cx / obj.cy</td><td>画像中心 (= hw / hh)</td></tr>
|
|
||||||
<tr><td>obj.cz / obj.sz</td><td>常に 0 / 常に 1</td></tr>
|
|
||||||
<tr><td>obj.diagonal</td><td>対角線長 (sqrt(w^2 + h^2))</td></tr>
|
|
||||||
<tr><td>obj.time / obj.frame</td><td>アイテム基準の経過時間 (秒) / フレーム</td></tr>
|
|
||||||
<tr><td>obj.totalframe / obj.totaltime</td><td>アイテムの総フレーム数 / 総時間 (秒)</td></tr>
|
|
||||||
<tr><td>obj.t</td><td>アイテム内の進行割合 (0.0 ~ 1.0)</td></tr>
|
|
||||||
<tr><td>obj.framerate</td><td>フレームレート (fps)</td></tr>
|
|
||||||
<tr><td>obj.layer</td><td>レイヤー番号</td></tr>
|
|
||||||
<tr><td>obj.index / obj.num</td><td>グループ内のインデックス / 総数</td></tr>
|
|
||||||
<tr><td>obj.track0 ~ obj.track3</td><td>エフェクトパネルの各トラックバーの値</td></tr>
|
|
||||||
</table>
|
|
||||||
|
|
||||||
<h3>obj 関数</h3>
|
|
||||||
<table border="1">
|
|
||||||
<tr><th>関数</th><th>説明</th></tr>
|
|
||||||
<tr><td>obj.getobject(tag [, frame])</td><td>他アイテムの描画情報を取得 (本ページ 12 章)</td></tr>
|
|
||||||
<tr><td>obj.getpixel(x, y)</td><td>ピクセル取得</td></tr>
|
|
||||||
<tr><td>obj.setpixel(x, y, r, g, b [, a])</td><td>ピクセル書き込み</td></tr>
|
|
||||||
<tr><td>obj.getpixeldata()</td><td>ピクセル直接アクセスプロキシ</td></tr>
|
|
||||||
<tr><td>obj.putpixeldata()</td><td>互換用の空実装</td></tr>
|
|
||||||
</table>
|
|
||||||
|
|
||||||
<hr>
|
|
||||||
|
|
||||||
<h2>非対応・制限事項</h2>
|
|
||||||
<ul>
|
|
||||||
<li>AviUtl2 の obj.effect(), obj.draw(), obj.drawpoly(), obj.load() 等は非対応です。</li>
|
|
||||||
<li>obj.setoption(), obj.getoption(), obj.getvalue(), obj.setanchor() 等は非対応です。</li>
|
|
||||||
<li>scene.set(), scene.get() 等は非対応です (scene.width / scene.height の読み取りのみ)。</li>
|
|
||||||
<li>ファイルアクセス (require, dofile, io 等) は非対応です。</li>
|
|
||||||
<li>スクリプトのタイムアウトは 5 秒です。無限ループに注意してください。</li>
|
|
||||||
<li>--track@, --check@ 等のヘッダーディレクティブは非対応です (Track0 ~ Track3 のみ)。</li>
|
|
||||||
</ul>
|
|
||||||
|
|
||||||
<hr>
|
|
||||||
|
|
||||||
<p>
|
|
||||||
Luaスクリプト for YMM4 / MIT License /
|
|
||||||
<a href="https://github.com/routersys/YMM4-LuaScript">https://github.com/routersys/YMM4-LuaScript</a>
|
|
||||||
</p>
|
|
||||||
|
|
||||||
|
</main>
|
||||||
|
<script src="assets/nav.js"></script>
|
||||||
</body>
|
</body>
|
||||||
</html>
|
</html>
|
||||||
@@ -0,0 +1,85 @@
|
|||||||
|
<!DOCTYPE html>
|
||||||
|
<html lang="ja">
|
||||||
|
<head>
|
||||||
|
<meta charset="utf-8">
|
||||||
|
<meta name="viewport" content="width=device-width, initial-scale=1">
|
||||||
|
<title>制限事項とトラブル | Lua スクリプト for YMM4</title>
|
||||||
|
<link rel="stylesheet" href="assets/style.css">
|
||||||
|
</head>
|
||||||
|
<body>
|
||||||
|
<button id="navtoggle" aria-label="メニュー">☰</button>
|
||||||
|
<nav id="sidebar"></nav>
|
||||||
|
<main>
|
||||||
|
|
||||||
|
<h1>制限事項とトラブル</h1>
|
||||||
|
|
||||||
|
<h2>実行に関する制限</h2>
|
||||||
|
|
||||||
|
<ul>
|
||||||
|
<li>タイムアウト 5 秒: 1 フレームのスクリプト実行が 5 秒を超えると中断され、そのフレームは
|
||||||
|
元の映像のままになります。無限ループや極端に重い処理に注意してください。</li>
|
||||||
|
<li>フレーム間で状態は保持されない: 組み込み以外のグローバル変数は毎フレームリセットされます。
|
||||||
|
前フレームの計算結果を変数に貯めることはできません。時間変化は <code>time</code> や <code>obj.t</code> から計算します。</li>
|
||||||
|
<li>ファイルアクセス不可: <code>require</code>・<code>dofile</code>・<code>io</code> などは使えません。</li>
|
||||||
|
<li>使えない標準ライブラリ: <code>io</code>・<code>os</code>・<code>debug</code>・<code>coroutine</code>・
|
||||||
|
<code>package</code>・<code>ffi</code> は無効です(<a href="stdlib.html">標準ライブラリ</a>)。</li>
|
||||||
|
</ul>
|
||||||
|
|
||||||
|
<h2>乱数について</h2>
|
||||||
|
|
||||||
|
<p>
|
||||||
|
<code>math.random</code> の結果はフレームごとに決まります。シードの仕組みは
|
||||||
|
<a href="stdlib.html">標準ライブラリ</a>の <code>math</code> で説明しています。
|
||||||
|
オブジェクトやフレームに対して安定した乱数が欲しいときは、
|
||||||
|
<a href="anim.html"><code>anim.rand</code></a> や <code>anim.noise</code>、
|
||||||
|
<a href="obj-functions.html"><code>obj.rand</code></a> を使ってください。
|
||||||
|
</p>
|
||||||
|
|
||||||
|
<h2>非対応の機能</h2>
|
||||||
|
|
||||||
|
<ul>
|
||||||
|
<li><code>scene.set()</code> や <code>scene.get()</code> はありません。<code>scene</code> は解像度の読み取りだけに対応します。</li>
|
||||||
|
<li><code>obj.setanchor()</code> など、本ドキュメントに記載のない AviUtl 関数は対応していません。</li>
|
||||||
|
<li><code>obj.effect</code> は、AviUtl/AviUtl2 互換マップに宣言したエフェクト名と、YMM4 に読み込まれている映像エフェクトの名前・キーワードを解決します。
|
||||||
|
名前が見つからない・適用に失敗した場合は、そのフレームでは元の映像がそのまま使われます。
|
||||||
|
互換マップが対応するエフェクト名の一覧は<a href="obj-functions.html">obj の関数</a>を参照してください。</li>
|
||||||
|
</ul>
|
||||||
|
|
||||||
|
<h2>エラー表示</h2>
|
||||||
|
|
||||||
|
<p>
|
||||||
|
構文エラー・実行時エラー・タイムアウトが起きると、スクリプトエディタの該当行に赤い波線で
|
||||||
|
警告が表示されます。まずはエラーメッセージと行番号を確認してください。
|
||||||
|
</p>
|
||||||
|
|
||||||
|
<h2>困ったときは</h2>
|
||||||
|
|
||||||
|
<table>
|
||||||
|
<tr><th>症状</th><th>確認すること</th></tr>
|
||||||
|
<tr><td>スクリプトを書いても見た目が変わらない</td><td>値を <code>obj</code> に代入しているか(グローバル変数に入れても反映されません)。
|
||||||
|
例: <code>obj.x = ...</code>。読み取り専用メンバーに代入していないか。</td></tr>
|
||||||
|
<tr><td>トラックバーや色が表示されない</td><td>指定子や使用状況によって表示が決まります。<a href="directives.html">パラメータ指定子</a> の表示条件を確認してください。</td></tr>
|
||||||
|
<tr><td>前のフレームの値が消える</td><td>仕様です。グローバル変数はフレーム間で保持されません。</td></tr>
|
||||||
|
<tr><td>処理が中断される / フレームが描画されない</td><td>5 秒のタイムアウトに達している可能性があります。ループ回数を減らすか、
|
||||||
|
ピクセル処理を <a href="engines.html">カーネルやネイティブ</a>に任せられる形にしてください。</td></tr>
|
||||||
|
<tr><td><code>--!native</code> を指定しても速くならない</td><td>プラグインの隣に <code>native</code> フォルダが配置されていないと MoonSharp で実行されます。
|
||||||
|
配置を確認してください(ログに一度だけ警告が出ます)。</td></tr>
|
||||||
|
<tr><td>GPU でわずかに結果が違う</td><td>GPU カーネルは float32 精度です。厳密一致が必要なら CPU カーネルかネイティブを使ってください。</td></tr>
|
||||||
|
</table>
|
||||||
|
|
||||||
|
<hr>
|
||||||
|
|
||||||
|
<p>
|
||||||
|
Lua スクリプト for YMM4 / MIT License /
|
||||||
|
<a href="https://github.com/routersys/YMM4-LuaScript">https://github.com/routersys/YMM4-LuaScript</a>
|
||||||
|
</p>
|
||||||
|
|
||||||
|
<div class="pager">
|
||||||
|
<a href="reference.html">← クイックリファレンス</a>
|
||||||
|
<a href="index.html">概要 →</a>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
</main>
|
||||||
|
<script src="assets/nav.js"></script>
|
||||||
|
</body>
|
||||||
|
</html>
|
||||||
@@ -0,0 +1,251 @@
|
|||||||
|
<!DOCTYPE html>
|
||||||
|
<html lang="ja">
|
||||||
|
<head>
|
||||||
|
<meta charset="utf-8">
|
||||||
|
<meta name="viewport" content="width=device-width, initial-scale=1">
|
||||||
|
<title>Lua の基礎 | Lua スクリプト for YMM4</title>
|
||||||
|
<link rel="stylesheet" href="assets/style.css">
|
||||||
|
</head>
|
||||||
|
<body>
|
||||||
|
<button id="navtoggle" aria-label="メニュー">☰</button>
|
||||||
|
<nav id="sidebar"></nav>
|
||||||
|
<main>
|
||||||
|
|
||||||
|
<h1>Lua の基礎</h1>
|
||||||
|
|
||||||
|
<p>
|
||||||
|
このページは、Lua をはじめて触る人向けの入門です。Lua スクリプトエフェクトで使える範囲に絞って、
|
||||||
|
言語そのものの書き方を学びます。エンジンは Lua 5.2 互換の MoonSharp です。
|
||||||
|
ファイル入出力やコルーチンなど一部の機能は使えません。詳しくは<a href="stdlib.html">標準ライブラリ</a>を参照してください。
|
||||||
|
</p>
|
||||||
|
|
||||||
|
<h2>コメント</h2>
|
||||||
|
|
||||||
|
<p>
|
||||||
|
Lua のコメントは <code>--</code> から行末までです。複数行コメントは <code>--[[</code> から <code>]]</code> までです。
|
||||||
|
コメントは実行に影響しません。なお、行頭の <code>--track:</code> や <code>--!native</code> のような特定の書式は
|
||||||
|
プラグインが解釈する<a href="directives.html">指定子</a>として扱われます。
|
||||||
|
</p>
|
||||||
|
|
||||||
|
<table>
|
||||||
|
<tr><th>書き方</th><th>意味</th></tr>
|
||||||
|
<tr><td><code>-- text</code></td><td>1 行コメント</td></tr>
|
||||||
|
<tr><td><code>--[[ text ]]</code></td><td>複数行コメント</td></tr>
|
||||||
|
</table>
|
||||||
|
|
||||||
|
<h2>値と型</h2>
|
||||||
|
|
||||||
|
<p>Lua の値には次の型があります。スクリプトでよく使うのは数値・文字列・真偽値・テーブルです。</p>
|
||||||
|
|
||||||
|
<table>
|
||||||
|
<tr><th>型</th><th>例</th><th>説明</th></tr>
|
||||||
|
<tr><td>nil</td><td><code>nil</code></td><td>値が無いことを表す。未定義の変数も nil</td></tr>
|
||||||
|
<tr><td>boolean</td><td><code>true</code>, <code>false</code></td><td>真偽値。条件分岐で使う</td></tr>
|
||||||
|
<tr><td>number</td><td><code>10</code>, <code>3.14</code>, <code>-0.5</code></td><td>数値。内部は倍精度浮動小数点</td></tr>
|
||||||
|
<tr><td>string</td><td><code>"hello"</code>, <code>'abc'</code></td><td>文字列</td></tr>
|
||||||
|
<tr><td>table</td><td><code>{1, 2, 3}</code></td><td>配列や連想配列に使う唯一の構造体</td></tr>
|
||||||
|
<tr><td>function</td><td><code>function(x) return x end</code></td><td>関数も値として扱える</td></tr>
|
||||||
|
</table>
|
||||||
|
|
||||||
|
<div class="note">
|
||||||
|
条件式で「偽」とみなされるのは <code>false</code> と <code>nil</code> だけです。
|
||||||
|
<code>0</code> も <code>""</code>(空文字列)も「真」です。これは C や JavaScript と違うので注意してください。
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<h2>変数</h2>
|
||||||
|
|
||||||
|
<p>
|
||||||
|
変数は <code>local</code> を付けて宣言します。<code>local</code> を付けるとそのブロック内だけで有効な
|
||||||
|
ローカル変数になります。付けないとグローバル変数になります。スクリプトでは原則 <code>local</code> を使ってください。
|
||||||
|
</p>
|
||||||
|
|
||||||
|
<pre><code>local a = 10
|
||||||
|
local b = 20
|
||||||
|
local sum = a + b
|
||||||
|
obj.x = sum</code></pre>
|
||||||
|
|
||||||
|
<p>複数の変数を一度に宣言・代入できます。</p>
|
||||||
|
|
||||||
|
<pre><code>local x, y = 100, 200
|
||||||
|
x, y = y, x</code></pre>
|
||||||
|
|
||||||
|
<div class="warn">
|
||||||
|
このエフェクトでは、グローバル変数の状態はフレーム間で保持されません。
|
||||||
|
毎フレーム独立に実行されるため、「前のフレームの値」を変数に貯めることはできません。
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<h2>演算子</h2>
|
||||||
|
|
||||||
|
<table>
|
||||||
|
<tr><th>分類</th><th>演算子</th></tr>
|
||||||
|
<tr><td>算術</td><td><code>+</code> <code>-</code> <code>*</code> <code>/</code> <code>%</code>(剰余) <code>^</code>(べき乗)</td></tr>
|
||||||
|
<tr><td>比較</td><td><code>==</code> <code>~=</code>(等しくない) <code><</code> <code>></code> <code><=</code> <code>>=</code></td></tr>
|
||||||
|
<tr><td>論理</td><td><code>and</code> <code>or</code> <code>not</code></td></tr>
|
||||||
|
<tr><td>連結</td><td><code>..</code>(文字列の連結)</td></tr>
|
||||||
|
<tr><td>長さ</td><td><code>#</code>(文字列やテーブルの長さ)</td></tr>
|
||||||
|
</table>
|
||||||
|
|
||||||
|
<p>
|
||||||
|
<code>and</code> と <code>or</code> は値を返します。<code>a and b</code> は <code>a</code> が偽なら <code>a</code>、
|
||||||
|
真なら <code>b</code> を返します。<code>a or b</code> は <code>a</code> が真なら <code>a</code>、偽なら <code>b</code> を返します。
|
||||||
|
これを使うと既定値を簡潔に書けます。
|
||||||
|
</p>
|
||||||
|
|
||||||
|
<pre><code>local amp = obj.track0
|
||||||
|
local v = amp ~= 0 and amp or 50
|
||||||
|
obj.x = obj.x + v</code></pre>
|
||||||
|
|
||||||
|
<h2>条件分岐</h2>
|
||||||
|
|
||||||
|
<pre><code>if obj.t < 0.5 then
|
||||||
|
obj.alpha = 255
|
||||||
|
elseif obj.t < 0.8 then
|
||||||
|
obj.alpha = 128
|
||||||
|
else
|
||||||
|
obj.alpha = 0
|
||||||
|
end</code></pre>
|
||||||
|
|
||||||
|
<p>三項演算子の代わりに <code>and</code> / <code>or</code> を使うのが定番です。</p>
|
||||||
|
|
||||||
|
<pre><code>obj.alpha = obj.check0 and 255 or 0</code></pre>
|
||||||
|
|
||||||
|
<h2>繰り返し</h2>
|
||||||
|
|
||||||
|
<h3>数値 for</h3>
|
||||||
|
<p><code>for 変数 = 開始, 終了 [, 増分] do ... end</code> です。終了値も含みます。</p>
|
||||||
|
|
||||||
|
<pre><code>local total = 0
|
||||||
|
for i = 1, 10 do
|
||||||
|
total = total + i
|
||||||
|
end</code></pre>
|
||||||
|
|
||||||
|
<p>ピクセル処理では 0 始まりで幅・高さ分ループするのが基本形です。</p>
|
||||||
|
|
||||||
|
<pre><code>for y = 0, obj.h - 1 do
|
||||||
|
for x = 0, obj.w - 1 do
|
||||||
|
local r, g, b, a = obj.getpixel(x, y)
|
||||||
|
obj.setpixel(x, y, 255 - r, g, b, a)
|
||||||
|
end
|
||||||
|
end</code></pre>
|
||||||
|
|
||||||
|
<h3>汎用 for(ipairs / pairs)</h3>
|
||||||
|
<p>配列を順に走査するなら <code>ipairs</code> を、すべてのキーを走査するなら <code>pairs</code> を使います。</p>
|
||||||
|
|
||||||
|
<pre><code>local points = {10, 20, 30}
|
||||||
|
local sum = 0
|
||||||
|
for index, value in ipairs(points) do
|
||||||
|
sum = sum + value
|
||||||
|
end</code></pre>
|
||||||
|
|
||||||
|
<h3>while と repeat</h3>
|
||||||
|
<pre><code>local i = 0
|
||||||
|
while i < 5 do
|
||||||
|
i = i + 1
|
||||||
|
end
|
||||||
|
|
||||||
|
local j = 0
|
||||||
|
repeat
|
||||||
|
j = j + 1
|
||||||
|
until j >= 5</code></pre>
|
||||||
|
|
||||||
|
<div class="warn">
|
||||||
|
ループの終了条件は必ず満たされるようにしてください。
|
||||||
|
無限ループになると 5 秒で実行が打ち切られ、そのフレームは描画されません。
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<h2>関数</h2>
|
||||||
|
|
||||||
|
<p>関数は <code>function</code> で定義します。スクリプト内で定義した関数は入力補完にも出ます。</p>
|
||||||
|
|
||||||
|
<pre><code>local function ease(t)
|
||||||
|
return t * t * (3 - 2 * t)
|
||||||
|
end
|
||||||
|
|
||||||
|
obj.alpha = ease(obj.t) * 255</code></pre>
|
||||||
|
|
||||||
|
<h3>複数の戻り値</h3>
|
||||||
|
<p>Lua の関数は複数の値を返せます。<code>anim.polar</code> など多くの組み込み関数がこれを使います。</p>
|
||||||
|
|
||||||
|
<pre><code>local function offset()
|
||||||
|
return 10, -20
|
||||||
|
end
|
||||||
|
|
||||||
|
local dx, dy = offset()
|
||||||
|
obj.x = obj.x + dx
|
||||||
|
obj.y = obj.y + dy</code></pre>
|
||||||
|
|
||||||
|
<h3>可変長引数</h3>
|
||||||
|
<pre><code>local function sum(...)
|
||||||
|
local total = 0
|
||||||
|
for _, v in ipairs({...}) do
|
||||||
|
total = total + v
|
||||||
|
end
|
||||||
|
return total
|
||||||
|
end</code></pre>
|
||||||
|
|
||||||
|
<h2>テーブル</h2>
|
||||||
|
|
||||||
|
<p>テーブルは Lua で唯一の複合データ構造で、配列にも連想配列にも使えます。</p>
|
||||||
|
|
||||||
|
<h3>配列として</h3>
|
||||||
|
<pre><code>local list = {5, 10, 15}
|
||||||
|
local first = list[1]
|
||||||
|
local count = #list</code></pre>
|
||||||
|
|
||||||
|
<div class="note">
|
||||||
|
配列のインデックスは 1 始まりです。多くの言語と違って 0 ではありません。
|
||||||
|
ただし <code>obj.getpixel(x, y)</code> の座標や、数値 for を 0 から回す処理は別物です。
|
||||||
|
ピクセルデータプロキシのインデックスは 1 始まりです(<a href="pixels.html">ピクセル操作</a>)。
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<h3>連想配列として</h3>
|
||||||
|
<pre><code>local config = { speed = 90, radius = 100 }
|
||||||
|
obj.rz = time * config.speed</code></pre>
|
||||||
|
|
||||||
|
<h3>テーブル操作</h3>
|
||||||
|
<p><code>table</code> ライブラリで挿入・削除・連結・並べ替えができます。</p>
|
||||||
|
|
||||||
|
<pre><code>local t = {}
|
||||||
|
table.insert(t, 1)
|
||||||
|
table.insert(t, 2)
|
||||||
|
table.sort(t)
|
||||||
|
local joined = table.concat(t, ",")</code></pre>
|
||||||
|
|
||||||
|
<h2>文字列</h2>
|
||||||
|
|
||||||
|
<p>文字列は <code>string</code> ライブラリで整形・検索できます。連結は <code>..</code> です。</p>
|
||||||
|
|
||||||
|
<pre><code>local label = string.format("%.1f", obj.t)
|
||||||
|
local upper = string.upper("abc")
|
||||||
|
local n = string.len(label)</code></pre>
|
||||||
|
|
||||||
|
<h2>標準で使える数学関数</h2>
|
||||||
|
|
||||||
|
<p><code>math</code> ライブラリに基本的な数学関数があります。よく使うものだけ挙げます。</p>
|
||||||
|
|
||||||
|
<pre><code>local r = math.sqrt(obj.x * obj.x + obj.y * obj.y)
|
||||||
|
local angle = math.atan2(obj.y, obj.x)
|
||||||
|
obj.rz = math.deg(angle)
|
||||||
|
obj.zoom = math.max(0.1, 1 + math.sin(time))</code></pre>
|
||||||
|
|
||||||
|
<p>
|
||||||
|
全関数の一覧は <a href="stdlib.html">標準ライブラリ</a> を参照してください。
|
||||||
|
アニメーション向けの高度な補間や波・ノイズは <a href="anim.html">anim ライブラリ</a> にまとまっています。
|
||||||
|
</p>
|
||||||
|
|
||||||
|
<h2>このエフェクト特有の注意点</h2>
|
||||||
|
|
||||||
|
<p>
|
||||||
|
標準 Lua との違いとして、使える標準ライブラリの範囲、乱数の扱い、5 秒の実行時間制限などの制約があります。
|
||||||
|
これらは<a href="limits.html">制限事項とトラブル</a>にまとめています。
|
||||||
|
</p>
|
||||||
|
|
||||||
|
<div class="pager">
|
||||||
|
<a href="getting-started.html">← 導入と使い方</a>
|
||||||
|
<a href="stdlib.html">標準ライブラリ →</a>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
</main>
|
||||||
|
<script src="assets/nav.js"></script>
|
||||||
|
</body>
|
||||||
|
</html>
|
||||||
@@ -0,0 +1,250 @@
|
|||||||
|
<!DOCTYPE html>
|
||||||
|
<html lang="ja">
|
||||||
|
<head>
|
||||||
|
<meta charset="utf-8">
|
||||||
|
<meta name="viewport" content="width=device-width, initial-scale=1">
|
||||||
|
<title>obj の関数 | Lua スクリプト for YMM4</title>
|
||||||
|
<link rel="stylesheet" href="assets/style.css">
|
||||||
|
</head>
|
||||||
|
<body>
|
||||||
|
<button id="navtoggle" aria-label="メニュー">☰</button>
|
||||||
|
<nav id="sidebar"></nav>
|
||||||
|
<main>
|
||||||
|
|
||||||
|
<h1>obj の関数</h1>
|
||||||
|
|
||||||
|
<p>
|
||||||
|
<code>obj</code> には値だけでなく関数も用意されています。他アイテムの参照、ピクセル操作、
|
||||||
|
図形やテキストの生成、他エフェクトの適用などができます。座標などの値メンバーは
|
||||||
|
<a href="obj.html">obj オブジェクト</a> を参照してください。
|
||||||
|
</p>
|
||||||
|
|
||||||
|
<h2>obj.getobject — 他アイテムの参照</h2>
|
||||||
|
|
||||||
|
<p>
|
||||||
|
<code>obj.getobject(tag [, frame])</code> は、対象アイテムの「備考」欄に入力した文字列を <code>tag</code> として、
|
||||||
|
そのアイテムの描画情報を取得します。備考欄はプロパティエリアの上側にあります。
|
||||||
|
第 2 引数 <code>frame</code> を指定すると、そのタイムラインフレーム時点の値を取得します(省略時は現在フレーム)。
|
||||||
|
一致するアイテムが無い場合は <code>nil</code> を返します。
|
||||||
|
</p>
|
||||||
|
|
||||||
|
<p>
|
||||||
|
返り値は対象アイテム自身の座標・回転・拡大率であり、グループ制御・カメラ制御による変形は含みません。
|
||||||
|
同じタグのアイテムが複数あるときは、対象フレームで表示中のものが優先されます。
|
||||||
|
</p>
|
||||||
|
|
||||||
|
<table>
|
||||||
|
<tr><th>メンバー</th><th>説明</th></tr>
|
||||||
|
<tr><td><code>exist</code></td><td>対象フレームが表示期間内か(boolean)</td></tr>
|
||||||
|
<tr><td><code>x</code> / <code>y</code> / <code>z</code></td><td>描画位置(ピクセル)</td></tr>
|
||||||
|
<tr><td><code>zoom</code> / <code>sx</code> / <code>sy</code></td><td>拡大率(1.0 で等倍)。<code>sx</code>・<code>sy</code> は <code>zoom</code> と同じ値</td></tr>
|
||||||
|
<tr><td><code>rz</code> / <code>rzr</code></td><td>Z 軸回転角(度 / ラジアン)</td></tr>
|
||||||
|
<tr><td><code>rx</code> / <code>ry</code> / <code>rxr</code> / <code>ryr</code></td><td>常に 0(X・Y 軸回転は取得しません)</td></tr>
|
||||||
|
<tr><td><code>alpha</code></td><td>不透明度(0.0 ~ 255.0)</td></tr>
|
||||||
|
<tr><td><code>layer</code></td><td>レイヤー番号</td></tr>
|
||||||
|
</table>
|
||||||
|
|
||||||
|
<h3>発射元の座標に合わせる</h3>
|
||||||
|
<pre><code>local src = obj.getobject("routersys")
|
||||||
|
if src then
|
||||||
|
obj.x = src.x
|
||||||
|
obj.y = src.y
|
||||||
|
end</code></pre>
|
||||||
|
|
||||||
|
<h3>発射元へ向かって移動する</h3>
|
||||||
|
<pre><code>local target = obj.getobject("routersys")
|
||||||
|
if target then
|
||||||
|
local p = anim.ease_in_out(obj.t)
|
||||||
|
obj.x = anim.lerp(obj.x, target.x, p)
|
||||||
|
obj.y = anim.lerp(obj.y, target.y, p)
|
||||||
|
end</code></pre>
|
||||||
|
|
||||||
|
<h3>表示中のときだけ追従する</h3>
|
||||||
|
<pre><code>local target = obj.getobject("routersys")
|
||||||
|
if target and target.exist then
|
||||||
|
obj.x = target.x
|
||||||
|
obj.y = target.y
|
||||||
|
end</code></pre>
|
||||||
|
|
||||||
|
<h3>発射時の座標に固定する</h3>
|
||||||
|
<p>
|
||||||
|
弾の発射フレーム(弾アイテムの開始フレーム)は <code>timelineframe - frame</code> で求まります。
|
||||||
|
そのフレーム時点の発射元座標を取得すれば、発射元が動いても原点は発射位置に固定されます。
|
||||||
|
</p>
|
||||||
|
<pre><code>local fire = timelineframe - frame
|
||||||
|
local src = obj.getobject("routersys", fire)
|
||||||
|
if src then
|
||||||
|
obj.x = src.x
|
||||||
|
obj.y = src.y
|
||||||
|
end</code></pre>
|
||||||
|
|
||||||
|
<h2>ピクセル操作</h2>
|
||||||
|
|
||||||
|
<p>
|
||||||
|
<code>obj.getpixel</code> / <code>obj.setpixel</code> / <code>obj.getpixeldata</code> は画像を直接読み書きします。
|
||||||
|
座標・チャンネル・アルファの扱いといった詳細は <a href="pixels.html">ピクセル操作</a> を参照してください。
|
||||||
|
ここでは関数の概要だけ示します。
|
||||||
|
</p>
|
||||||
|
|
||||||
|
<table>
|
||||||
|
<tr><th>関数</th><th>戻り値</th><th>説明</th></tr>
|
||||||
|
<tr><td><code>obj.getpixel(x, y)</code></td><td>r, g, b, a</td><td>指定座標のピクセルを取得(各成分 0 ~ 255)</td></tr>
|
||||||
|
<tr><td><code>obj.setpixel(x, y, r, g, b [, a])</code></td><td>なし</td><td>指定座標へ書き込み(a 既定 255)</td></tr>
|
||||||
|
<tr><td><code>obj.getpixeldata()</code></td><td>プロキシ</td><td>全ピクセルへ直接アクセスするプロキシを返す</td></tr>
|
||||||
|
<tr><td><code>obj.putpixeldata()</code></td><td>なし</td><td>AviUtl 互換用の空実装(呼ぶ必要はない)</td></tr>
|
||||||
|
</table>
|
||||||
|
|
||||||
|
<h2>obj.rand — 整数の安定した乱数</h2>
|
||||||
|
|
||||||
|
<p>
|
||||||
|
<code>obj.rand(a, b [, seed [, frame]])</code> は <code>a</code> ~ <code>b</code> の範囲の整数を返します
|
||||||
|
(端点を含みます)。同じ <code>seed</code> と <code>frame</code> の組では常に同じ値になります。
|
||||||
|
<code>seed</code> の既定値は 0、<code>frame</code> の既定値は現在フレームです。
|
||||||
|
</p>
|
||||||
|
|
||||||
|
<table>
|
||||||
|
<tr><th>関数</th><th>戻り値</th><th>用途</th></tr>
|
||||||
|
<tr><td><code>obj.rand(a, b)</code></td><td>整数</td><td>毎フレーム変わる乱数</td></tr>
|
||||||
|
<tr><td><code>obj.rand(a, b, seed)</code></td><td>整数</td><td>シードで固定。レイヤー番号などを渡す</td></tr>
|
||||||
|
<tr><td><code>obj.rand(a, b, seed, frame)</code></td><td>整数</td><td>フレームも固定して完全に決定的にする</td></tr>
|
||||||
|
</table>
|
||||||
|
|
||||||
|
<div class="note">
|
||||||
|
小数を含む乱数や、ベクトル・色のゆらぎが欲しいときは <a href="anim.html"><code>anim.rand</code></a> や
|
||||||
|
<code>anim.noise</code> が便利です。<code>obj.rand</code> は整数を返す AviUtl 互換の乱数です。
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<h2>obj.load — 図形・テキスト・画像・動画の読み込み</h2>
|
||||||
|
|
||||||
|
<p>
|
||||||
|
<code>obj.load(種類, ...)</code> は、対象の画像バッファを生成した内容で置き換えます。
|
||||||
|
読み込み後は <code>obj.w</code> / <code>obj.h</code> などの寸法も更新されます。
|
||||||
|
</p>
|
||||||
|
|
||||||
|
<table>
|
||||||
|
<tr><th>呼び出し</th><th>説明</th></tr>
|
||||||
|
<tr><td><code>obj.load("figure", name, color, size [, line [, aspect]])</code></td><td>図形を生成。<code>color</code> は <code>0xRRGGBB</code>、<code>size</code> は大きさ(px)、<code>line</code> は 0 以下で塗りつぶし・正で輪郭の太さ、<code>aspect</code> は -1.0 ~ 1.0</td></tr>
|
||||||
|
<tr><td><code>obj.load("text", str)</code></td><td>文字列を描画。フォントは <code>obj.setfont</code> の設定を使う</td></tr>
|
||||||
|
<tr><td><code>obj.load("image", path)</code></td><td>画像ファイルを読み込む</td></tr>
|
||||||
|
<tr><td><code>obj.load("movie", path [, time])</code></td><td>動画の指定時刻のフレームを読み込む(既定は現在時刻)</td></tr>
|
||||||
|
</table>
|
||||||
|
|
||||||
|
<p><code>obj.load("figure", ...)</code> で指定できる図形名は次のとおりです。</p>
|
||||||
|
|
||||||
|
<table>
|
||||||
|
<tr><th>図形</th><th>名前</th></tr>
|
||||||
|
<tr><td>円・楕円</td><td><code>円</code> / <code>楕円</code> / <code>circle</code> / <code>ellipse</code></td></tr>
|
||||||
|
<tr><td>三角形</td><td><code>三角形</code> / <code>triangle</code></td></tr>
|
||||||
|
<tr><td>五角形</td><td><code>五角形</code> / <code>pentagon</code></td></tr>
|
||||||
|
<tr><td>六角形</td><td><code>六角形</code> / <code>hexagon</code></td></tr>
|
||||||
|
<tr><td>星形</td><td><code>星形</code> / <code>star</code></td></tr>
|
||||||
|
<tr><td>四角形</td><td>上記以外の名前(既定)</td></tr>
|
||||||
|
</table>
|
||||||
|
|
||||||
|
<pre><code>obj.load("figure", "star", 0xFFCC00, 200, 0, 0)</code></pre>
|
||||||
|
|
||||||
|
<h2>obj.setfont — フォント設定</h2>
|
||||||
|
|
||||||
|
<p>
|
||||||
|
<code>obj.setfont(name [, size [, type [, color]]])</code> は、続く <code>obj.load("text", ...)</code> で使う
|
||||||
|
フォントを設定します。<code>type</code> はビットフラグで、ビット 0 が太字、ビット 1 が斜体です
|
||||||
|
(太字+斜体は 3)。既定の大きさは 34、既定色は <code>0xFFFFFF</code> です。
|
||||||
|
</p>
|
||||||
|
|
||||||
|
<pre><code>obj.setfont("Yu Gothic UI", 48, 1, 0xFFFFFF)
|
||||||
|
obj.load("text", "サンプル")</code></pre>
|
||||||
|
|
||||||
|
<h2>AviUtl 互換の描画・効果関数(上級)</h2>
|
||||||
|
|
||||||
|
<p>
|
||||||
|
次の関数は AviUtl のスクリプト制御に近い使い勝手で用意されています。
|
||||||
|
<code>obj.effect</code> は AviUtl/AviUtl2 のエフェクト名とパラメータ名で、対応する YMM4 の映像エフェクトを適用します。
|
||||||
|
</p>
|
||||||
|
|
||||||
|
<table>
|
||||||
|
<tr><th>関数</th><th>説明</th></tr>
|
||||||
|
<tr><td><code>obj.effect(name, key1, val1, ...)</code></td><td>AviUtl/AviUtl2 のエフェクト名で YMM4 の映像エフェクトを適用する。<code>key, val</code> の組は AviUtl のパラメータ名で指定し、互換マップを通じて YMM4 のプロパティへ変換される</td></tr>
|
||||||
|
<tr><td><code>obj.draw([ox, oy, oz, zoom, alpha, aspect])</code></td><td>現在のバッファをオフセット・拡大率・不透明度を指定して描画する</td></tr>
|
||||||
|
<tr><td><code>obj.drawpoly(x0,y0,z0, x1,y1,z1, x2,y2,z2, x3,y3,z3 [, u0,v0, ... ,u3,v3] [, alpha])</code></td><td>4 頂点のテクスチャ付きポリゴンを描画する。UV を省略すると画像全体を使う</td></tr>
|
||||||
|
<tr><td><code>obj.copybuffer(dst, src)</code></td><td>バッファ間でコピーする。ID は <code>obj</code>(作業画像)・<code>tmp</code>・<code>cache:名前</code>。書き込み先が <code>obj</code> のときのみ作業画像を置き換える</td></tr>
|
||||||
|
<tr><td><code>obj.setoption(name [, value])</code></td><td>オプションを設定する。<code>antialias</code> は <code>obj.draw</code> で参照される</td></tr>
|
||||||
|
<tr><td><code>obj.getoption(name)</code></td><td>設定したオプションを取得する</td></tr>
|
||||||
|
<tr><td><code>obj.getvalue(name)</code></td><td><code>obj</code> の数値メンバーを名前で取得する</td></tr>
|
||||||
|
<tr><td><code>obj.pixeloption(name [, value])</code></td><td>ピクセル処理向けのオプションを設定する</td></tr>
|
||||||
|
</table>
|
||||||
|
|
||||||
|
<h3>互換マップ</h3>
|
||||||
|
|
||||||
|
<p>
|
||||||
|
<code>obj.effect</code> は二段階で解決します。
|
||||||
|
まず互換マップを参照し、AviUtl/AviUtl2 の名前として宣言したエフェクトは、
|
||||||
|
パラメータ名の対応と値の変換を経て YMM4 のプロパティへ反映します。
|
||||||
|
互換マップに宣言が無い名前は、YMM4 のエフェクト名やキーワードでそのまま解決します。
|
||||||
|
たとえば <code>ウェーブクリッピング</code> のように、YMM4 やコミュニティのエフェクトを
|
||||||
|
名前で呼ぶ使い方もそのまま動きます。
|
||||||
|
</p>
|
||||||
|
|
||||||
|
<p>
|
||||||
|
互換マップでは、パラメータの値を AviUtl と同じ尺度で渡すと、
|
||||||
|
マップに定義した倍率とオフセットの変換を経て、YMM4 のプロパティへ反映します。
|
||||||
|
たとえば <code>ぼかし</code> の <code>範囲</code> は YMM4 の <code>Blur</code> へ 0.5 倍で対応し、
|
||||||
|
AviUtl と同じ見た目になります。
|
||||||
|
この互換マップは、YMM4 自身が AviUtl の <code>.exo</code> へ書き出す変換を逆向きにたどって作っているため、
|
||||||
|
往復しても結果が一致します。
|
||||||
|
</p>
|
||||||
|
|
||||||
|
<p>
|
||||||
|
対象のエンジンは指定子 <code>--!aviutl</code> または <code>--!aviutl2</code> で切り替えます。
|
||||||
|
指定子を書かないときは <code>--!aviutl</code> として扱います。
|
||||||
|
各エントリは対応するエンジンを AviUtl・AviUtl2・両方のいずれかとして保持し、
|
||||||
|
対象に一致するエントリだけを解決します。
|
||||||
|
</p>
|
||||||
|
|
||||||
|
<pre><code>--!aviutl
|
||||||
|
obj.effect("ぼかし", "範囲", 20)
|
||||||
|
obj.effect("方向ブラー", "範囲", 16, "角度", 45)</code></pre>
|
||||||
|
|
||||||
|
<p>現在マップが宣言している AviUtl のエフェクト名は次のとおりです。</p>
|
||||||
|
|
||||||
|
<table>
|
||||||
|
<tr><th>エフェクト名</th><th>主なパラメータ</th></tr>
|
||||||
|
<tr><td><code>ぼかし</code></td><td>範囲, サイズ固定</td></tr>
|
||||||
|
<tr><td><code>境界ぼかし</code></td><td>範囲</td></tr>
|
||||||
|
<tr><td><code>方向ブラー</code></td><td>範囲, 角度, サイズ固定</td></tr>
|
||||||
|
<tr><td><code>放射ブラー</code></td><td>範囲, X, Y, サイズを固定</td></tr>
|
||||||
|
<tr><td><code>閃光</code></td><td>範囲, X, Y, サイズを固定</td></tr>
|
||||||
|
<tr><td><code>クロマキー</code></td><td>色相範囲, 境界補正</td></tr>
|
||||||
|
<tr><td><code>クリッピング</code></td><td>上, 下, 左, 右, 中心の位置を変更</td></tr>
|
||||||
|
<tr><td><code>斜めクリッピング</code></td><td>中心X, 中心Y, 角度, ぼかし, 幅</td></tr>
|
||||||
|
<tr><td><code>領域拡張</code></td><td>上, 下, 左, 右</td></tr>
|
||||||
|
<tr><td><code>座標</code></td><td>X, Y, Z</td></tr>
|
||||||
|
<tr><td><code>回転</code></td><td>X, Y, Z</td></tr>
|
||||||
|
<tr><td><code>リサイズ</code></td><td>拡大率, X, Y, 補間なし</td></tr>
|
||||||
|
<tr><td><code>画像ループ</code></td><td>横回数, 縦回数</td></tr>
|
||||||
|
<tr><td><code>極座標変換</code></td><td>中心幅, 渦巻</td></tr>
|
||||||
|
<tr><td><code>グラデーション</code></td><td>強さ, 中心X, 中心Y, 角度, 幅</td></tr>
|
||||||
|
<tr><td><code>単色化</code></td><td>強さ, 輝度を保持する</td></tr>
|
||||||
|
<tr><td><code>縁取り</code></td><td>サイズ, ぼかし</td></tr>
|
||||||
|
<tr><td><code>反転</code></td><td>—</td></tr>
|
||||||
|
<tr><td><code>モザイク</code></td><td>サイズ</td></tr>
|
||||||
|
<tr><td><code>ディスプレイスメントマップ</code></td><td>ぼかし</td></tr>
|
||||||
|
<tr><td><code>動画ファイル合成</code></td><td>X, Y, 拡大率</td></tr>
|
||||||
|
<tr><td><code>色調補正</code></td><td>明るさ, コントラスト, 色相, 輝度, 彩度</td></tr>
|
||||||
|
<tr><td><code>色ずれ</code></td><td>ずれ幅, 角度, 強さ</td></tr>
|
||||||
|
</table>
|
||||||
|
|
||||||
|
<div class="note">
|
||||||
|
対象のエフェクトが YMM4 やコミュニティプラグインに読み込まれていないとき、または適用に失敗したときは、
|
||||||
|
そのフレームでは元の映像をそのまま使います。このときログへ警告を一度だけ出します。
|
||||||
|
<code>色調補正</code> と <code>色ずれ</code> はコミュニティプラグインのエフェクトに対応します。
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div class="pager">
|
||||||
|
<a href="obj.html">← obj オブジェクト</a>
|
||||||
|
<a href="anim.html">anim ライブラリ →</a>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
</main>
|
||||||
|
<script src="assets/nav.js"></script>
|
||||||
|
</body>
|
||||||
|
</html>
|
||||||
+163
@@ -0,0 +1,163 @@
|
|||||||
|
<!DOCTYPE html>
|
||||||
|
<html lang="ja">
|
||||||
|
<head>
|
||||||
|
<meta charset="utf-8">
|
||||||
|
<meta name="viewport" content="width=device-width, initial-scale=1">
|
||||||
|
<title>obj オブジェクト | Lua スクリプト for YMM4</title>
|
||||||
|
<link rel="stylesheet" href="assets/style.css">
|
||||||
|
</head>
|
||||||
|
<body>
|
||||||
|
<button id="navtoggle" aria-label="メニュー">☰</button>
|
||||||
|
<nav id="sidebar"></nav>
|
||||||
|
<main>
|
||||||
|
|
||||||
|
<h1>obj オブジェクト</h1>
|
||||||
|
|
||||||
|
<p>
|
||||||
|
<code>obj</code> は描画対象を表す中心的なテーブルです。座標・回転・拡大率・不透明度などの値を持ち、
|
||||||
|
これらを書き換えると描画に反映されます。実行前に現在の値が入り、実行後に書き換えた値が読み戻されます。
|
||||||
|
関数(ピクセル操作・読み込みなど)は <a href="obj-functions.html">obj の関数</a> にまとめています。
|
||||||
|
</p>
|
||||||
|
|
||||||
|
<h2>変更可能なメンバー</h2>
|
||||||
|
|
||||||
|
<p>これらに代入すると描画が変わります。実行後にプラグインが読み戻します。</p>
|
||||||
|
|
||||||
|
<table>
|
||||||
|
<tr><th>メンバー</th><th>説明</th></tr>
|
||||||
|
<tr><td><code>obj.x</code> / <code>obj.y</code> / <code>obj.z</code></td><td>描画位置(ピクセル)</td></tr>
|
||||||
|
<tr><td><code>obj.ox</code> / <code>obj.oy</code> / <code>obj.oz</code></td><td>中心点のオフセット(ピクセル)。回転・拡大の基準がずれる</td></tr>
|
||||||
|
<tr><td><code>obj.zoom</code></td><td>拡大率(sx と sy の平均、1.0 で等倍)</td></tr>
|
||||||
|
<tr><td><code>obj.aspect</code></td><td>縦横比(-1.0 ~ 1.0)。正で横を縮小、負で縦を縮小</td></tr>
|
||||||
|
<tr><td><code>obj.sx</code> / <code>obj.sy</code></td><td>X / Y 方向の独立した拡大率</td></tr>
|
||||||
|
<tr><td><code>obj.alpha</code></td><td>不透明度(0.0 ~ 255.0)</td></tr>
|
||||||
|
<tr><td><code>obj.rx</code> / <code>obj.ry</code> / <code>obj.rz</code></td><td>X / Y / Z 軸の回転角(度)</td></tr>
|
||||||
|
<tr><td><code>obj.rxr</code> / <code>obj.ryr</code> / <code>obj.rzr</code></td><td>X / Y / Z 軸の回転角(ラジアン)</td></tr>
|
||||||
|
</table>
|
||||||
|
|
||||||
|
<h3>拡大率(zoom / aspect と sx / sy)</h3>
|
||||||
|
|
||||||
|
<p>
|
||||||
|
拡大率には 2 通りの指定方法があり、片方を変えるともう片方は自動で計算されます。
|
||||||
|
入力時点では <code>zoom</code> は <code>sx</code> と <code>sy</code> の平均、
|
||||||
|
<code>aspect</code> は <code>(sx - sy) / (sx + sy)</code> です。
|
||||||
|
</p>
|
||||||
|
|
||||||
|
<ul>
|
||||||
|
<li><code>sx</code> / <code>sy</code> を変更した場合 … その値がそのまま使われます。</li>
|
||||||
|
<li><code>sx</code> / <code>sy</code> を変更せず <code>zoom</code> / <code>aspect</code> だけを変更した場合 …
|
||||||
|
<code>sx = zoom * (1 + aspect)</code>、<code>sy = zoom * (1 - aspect)</code> として反映されます。</li>
|
||||||
|
</ul>
|
||||||
|
|
||||||
|
<pre><code>obj.zoom = obj.zoom * 1.5
|
||||||
|
|
||||||
|
local s = math.sin(time * anim.tau * 2) * 0.2
|
||||||
|
obj.sx = 1 + s
|
||||||
|
obj.sy = 1 - s</code></pre>
|
||||||
|
|
||||||
|
<h3>回転(度とラジアン)</h3>
|
||||||
|
|
||||||
|
<p>
|
||||||
|
回転は度(<code>rx</code> / <code>ry</code> / <code>rz</code>)とラジアン(<code>rxr</code> / <code>ryr</code> / <code>rzr</code>)の
|
||||||
|
両方で指定できます。ラジアン版を変更した場合はラジアン版が優先され、
|
||||||
|
変更しなければ度の値が使われます。
|
||||||
|
</p>
|
||||||
|
|
||||||
|
<pre><code>obj.rz = time * 90
|
||||||
|
obj.rzr = time * anim.tau</code></pre>
|
||||||
|
|
||||||
|
<h2>読み取り専用メンバー</h2>
|
||||||
|
|
||||||
|
<p>入力画像の寸法や時間情報など、書き換えても反映されない値です。</p>
|
||||||
|
|
||||||
|
<table>
|
||||||
|
<tr><th>メンバー</th><th>説明</th></tr>
|
||||||
|
<tr><td><code>obj.w</code> / <code>obj.h</code></td><td>入力画像の幅 / 高さ(ピクセル)</td></tr>
|
||||||
|
<tr><td><code>obj.hw</code> / <code>obj.hh</code></td><td>幅 / 高さの半分</td></tr>
|
||||||
|
<tr><td><code>obj.cx</code> / <code>obj.cy</code></td><td>画像中心(幅 / 高さの半分に等しい)</td></tr>
|
||||||
|
<tr><td><code>obj.cz</code></td><td>常に 0</td></tr>
|
||||||
|
<tr><td><code>obj.sz</code></td><td>常に 1</td></tr>
|
||||||
|
<tr><td><code>obj.diagonal</code></td><td>対角線の長さ(<code>sqrt(w^2 + h^2)</code>)</td></tr>
|
||||||
|
<tr><td><code>obj.time</code></td><td>アイテム先頭からの経過時間(秒)</td></tr>
|
||||||
|
<tr><td><code>obj.frame</code></td><td>現在フレーム番号</td></tr>
|
||||||
|
<tr><td><code>obj.totalframe</code></td><td>総フレーム数</td></tr>
|
||||||
|
<tr><td><code>obj.totaltime</code></td><td>総時間(秒)</td></tr>
|
||||||
|
<tr><td><code>obj.t</code></td><td>アイテム内の進行割合(0.0 ~ 1.0、<code>frame / totalframe</code>)</td></tr>
|
||||||
|
<tr><td><code>obj.framerate</code></td><td>フレームレート(fps)</td></tr>
|
||||||
|
<tr><td><code>obj.layer</code></td><td>レイヤー番号</td></tr>
|
||||||
|
<tr><td><code>obj.index</code></td><td>入力のインデックス</td></tr>
|
||||||
|
<tr><td><code>obj.num</code></td><td>入力の総数</td></tr>
|
||||||
|
<tr><td><code>obj.track0</code> ~ <code>obj.track3</code></td><td>トラックバーの値(数値)</td></tr>
|
||||||
|
<tr><td><code>obj.check0</code> ~ <code>obj.check3</code></td><td>チェックボックスの値(真偽値)</td></tr>
|
||||||
|
<tr><td><code>obj.slider0</code> ~ <code>obj.slider3</code></td><td>整数スライダーの値</td></tr>
|
||||||
|
<tr><td><code>obj.text</code></td><td>テキスト入力欄の文字列</td></tr>
|
||||||
|
<tr><td><code>obj.font</code></td><td>フォント選択欄のフォント名</td></tr>
|
||||||
|
<tr><td><code>obj.dir</code></td><td>フォルダ選択欄のパス</td></tr>
|
||||||
|
<tr><td><code>obj.file_video</code> ~ <code>obj.file_shader</code></td><td>各ファイル選択欄のパス</td></tr>
|
||||||
|
</table>
|
||||||
|
|
||||||
|
<div class="note">
|
||||||
|
<code>obj.t</code> はアイテムの長さに対する進行割合なので、イージング関数の入力に最適です。
|
||||||
|
一方 <code>time</code> は実時間(秒)なので、速度や周波数の指定に向いています。
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<h2>パラメータ(track / check)</h2>
|
||||||
|
|
||||||
|
<p>
|
||||||
|
<code>obj.track0</code> ~ <code>obj.track3</code> はパラメータパネルのトラックバーの値です。
|
||||||
|
<code>obj.check0</code> ~ <code>obj.check3</code> はチェックボックスの値(true / false)です。
|
||||||
|
名前・範囲・既定値・表示条件は <a href="directives.html">パラメータ指定子</a> で定義できます。
|
||||||
|
</p>
|
||||||
|
|
||||||
|
<pre><code>local amp = obj.track0
|
||||||
|
local freq = obj.track1
|
||||||
|
obj.x = obj.x + math.sin(time * anim.tau * freq) * amp
|
||||||
|
|
||||||
|
if obj.check0 then
|
||||||
|
obj.alpha = 255
|
||||||
|
end</code></pre>
|
||||||
|
|
||||||
|
<h2>スライダーと文字列パラメータ</h2>
|
||||||
|
|
||||||
|
<p>
|
||||||
|
<code>obj.slider0</code> ~ <code>obj.slider3</code> は整数スライダーの値です。小数を含みません。
|
||||||
|
表示範囲は <code>obj.slider0</code> が 1 ~ 10、<code>obj.slider1</code> が 0 ~ 100、
|
||||||
|
<code>obj.slider2</code> が 0 ~ 1000、<code>obj.slider3</code> が -1000 ~ 1000 です。
|
||||||
|
状態の切り替えなど、整数値の受け渡しに使えます。
|
||||||
|
</p>
|
||||||
|
|
||||||
|
<p>
|
||||||
|
文字列パラメータも参照できます。<code>obj.text</code> はテキスト入力欄の文字列、
|
||||||
|
<code>obj.font</code> はフォント名、<code>obj.dir</code> はフォルダのパスです。
|
||||||
|
ファイル選択欄は種類ごとに <code>obj.file_video</code> / <code>obj.file_audio</code> /
|
||||||
|
<code>obj.file_image</code> / <code>obj.file_project</code> / <code>obj.file_mp4</code> /
|
||||||
|
<code>obj.file_exo</code> / <code>obj.file_subtitle</code> / <code>obj.file_shader</code> で参照し、
|
||||||
|
選択したファイルのパスを取得します。取得したパスは <code>obj.load</code> へ渡して画像や動画を読み込めます。
|
||||||
|
</p>
|
||||||
|
|
||||||
|
<p>
|
||||||
|
スライダーと文字列パラメータは、スクリプトがそれらを参照するとパラメータパネルへ表示されます。
|
||||||
|
いずれのパラメータも MoonSharp とネイティブの両エンジンから参照できます。
|
||||||
|
</p>
|
||||||
|
|
||||||
|
<pre><code>local mode = obj.slider0
|
||||||
|
obj.load("image", obj.file_image)</code></pre>
|
||||||
|
|
||||||
|
<h2>よく使う例</h2>
|
||||||
|
|
||||||
|
<h3>中心を基準に振り子のように揺らす</h3>
|
||||||
|
<pre><code>obj.oy = -obj.hh
|
||||||
|
obj.rz = math.sin(time * anim.tau) * 30</code></pre>
|
||||||
|
|
||||||
|
<h3>画面サイズに対する相対配置</h3>
|
||||||
|
<pre><code>obj.x = scene.cx * obj.track0 / 100</code></pre>
|
||||||
|
|
||||||
|
<div class="pager">
|
||||||
|
<a href="globals.html">← グローバル変数</a>
|
||||||
|
<a href="obj-functions.html">obj の関数 →</a>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
</main>
|
||||||
|
<script src="assets/nav.js"></script>
|
||||||
|
</body>
|
||||||
|
</html>
|
||||||
+140
@@ -0,0 +1,140 @@
|
|||||||
|
<!DOCTYPE html>
|
||||||
|
<html lang="ja">
|
||||||
|
<head>
|
||||||
|
<meta charset="utf-8">
|
||||||
|
<meta name="viewport" content="width=device-width, initial-scale=1">
|
||||||
|
<title>ピクセル操作 | Lua スクリプト for YMM4</title>
|
||||||
|
<link rel="stylesheet" href="assets/style.css">
|
||||||
|
</head>
|
||||||
|
<body>
|
||||||
|
<button id="navtoggle" aria-label="メニュー">☰</button>
|
||||||
|
<nav id="sidebar"></nav>
|
||||||
|
<main>
|
||||||
|
|
||||||
|
<h1>ピクセル操作</h1>
|
||||||
|
|
||||||
|
<p>
|
||||||
|
入力画像を 1 ピクセルずつ読み書きできます。色の反転・グレースケール・ビネットなど、
|
||||||
|
座標や色に基づく加工はピクセル操作で実現します。
|
||||||
|
</p>
|
||||||
|
|
||||||
|
<h2>座標と色の約束</h2>
|
||||||
|
|
||||||
|
<ul>
|
||||||
|
<li>座標は画像の左上を <code>(0, 0)</code> とし、右方向・下方向が正です。</li>
|
||||||
|
<li>有効範囲は <code>0 ≦ x < obj.w</code>、<code>0 ≦ y < obj.h</code> です。
|
||||||
|
範囲外を <code>getpixel</code> で読むと <code>(0, 0, 0, 0)</code> が返り、<code>setpixel</code> は無視されます。</li>
|
||||||
|
<li>取得・設定する色は、アルファを乗算していないストレートな RGB です。各成分は 0 ~ 255 で、内部表現との変換は自動で行われます。</li>
|
||||||
|
</ul>
|
||||||
|
|
||||||
|
<div class="note">
|
||||||
|
ピクセル操作は実際の入力画像へアクセスするため、初回アクセス時に画像データの転送が発生します。
|
||||||
|
転送は最初の 1 回だけです。
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<h2>getpixel / setpixel</h2>
|
||||||
|
|
||||||
|
<table>
|
||||||
|
<tr><th>関数</th><th>戻り値</th><th>説明</th></tr>
|
||||||
|
<tr><td><code>obj.getpixel(x, y)</code></td><td>r, g, b, a</td><td>指定座標の色を取得(各成分 0 ~ 255)</td></tr>
|
||||||
|
<tr><td><code>obj.setpixel(x, y, r, g, b [, a])</code></td><td>なし</td><td>指定座標へ書き込み(<code>a</code> 既定 255)</td></tr>
|
||||||
|
</table>
|
||||||
|
|
||||||
|
<h3>赤成分を反転する</h3>
|
||||||
|
<pre><code>for y = 0, obj.h - 1 do
|
||||||
|
for x = 0, obj.w - 1 do
|
||||||
|
local r, g, b, a = obj.getpixel(x, y)
|
||||||
|
obj.setpixel(x, y, 255 - r, g, b, a)
|
||||||
|
end
|
||||||
|
end</code></pre>
|
||||||
|
|
||||||
|
<h2>getpixeldata — 直接アクセス(高速)</h2>
|
||||||
|
|
||||||
|
<p>
|
||||||
|
<code>obj.getpixeldata()</code> は、全ピクセルへ直接アクセスできるプロキシを返します。
|
||||||
|
1 ピクセルずつ関数を呼ぶ <code>getpixel</code> / <code>setpixel</code> より高速です。
|
||||||
|
</p>
|
||||||
|
|
||||||
|
<table>
|
||||||
|
<tr><th>メンバー</th><th>説明</th></tr>
|
||||||
|
<tr><td><code>pd.width</code> / <code>pd.height</code></td><td>画像の幅 / 高さ</td></tr>
|
||||||
|
<tr><td><code>pd:get(index)</code></td><td>指定インデックスのチャンネル値を取得(0 ~ 255)</td></tr>
|
||||||
|
<tr><td><code>pd:set(index, value)</code></td><td>指定インデックスのチャンネル値を設定(0 ~ 255 にクランプ)</td></tr>
|
||||||
|
</table>
|
||||||
|
|
||||||
|
<p>
|
||||||
|
インデックスは 1 始まりで、各ピクセルにつき R, G, B, A の 4 チャンネルが順に並びます。
|
||||||
|
座標 <code>(x, y)</code> の R チャンネルのインデックスは <code>(y * pd.width + x) * 4 + 1</code> です。
|
||||||
|
続く +1, +2, +3 がそれぞれ G, B, A になります。
|
||||||
|
</p>
|
||||||
|
|
||||||
|
<div class="note">
|
||||||
|
プロキシのメンバーアクセスはコロン記法(<code>pd:get(i)</code> / <code>pd:set(i, v)</code>)で呼びます。
|
||||||
|
幅・高さはドット記法(<code>pd.width</code> / <code>pd.height</code>)で読みます。
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<h3>グレースケール化</h3>
|
||||||
|
<pre><code>local pd = obj.getpixeldata()
|
||||||
|
local w = pd.width
|
||||||
|
local h = pd.height
|
||||||
|
for y = 0, h - 1 do
|
||||||
|
for x = 0, w - 1 do
|
||||||
|
local base = (y * w + x) * 4
|
||||||
|
local r = pd:get(base + 1)
|
||||||
|
local g = pd:get(base + 2)
|
||||||
|
local b = pd:get(base + 3)
|
||||||
|
local gray = r * 0.299 + g * 0.587 + b * 0.114
|
||||||
|
pd:set(base + 1, gray)
|
||||||
|
pd:set(base + 2, gray)
|
||||||
|
pd:set(base + 3, gray)
|
||||||
|
end
|
||||||
|
end</code></pre>
|
||||||
|
|
||||||
|
<h3>中心からの距離でフェード(円形ビネット)</h3>
|
||||||
|
<pre><code>local pd = obj.getpixeldata()
|
||||||
|
local w = pd.width
|
||||||
|
local h = pd.height
|
||||||
|
local cx = w / 2
|
||||||
|
local cy = h / 2
|
||||||
|
local maxd = anim.len(cx, cy)
|
||||||
|
for y = 0, h - 1 do
|
||||||
|
for x = 0, w - 1 do
|
||||||
|
local base = (y * w + x) * 4
|
||||||
|
local d = anim.len(x - cx, y - cy)
|
||||||
|
local k = anim.clamp(1 - d / maxd, 0, 1)
|
||||||
|
pd:set(base + 4, pd:get(base + 4) * k)
|
||||||
|
end
|
||||||
|
end</code></pre>
|
||||||
|
|
||||||
|
<h2>アルファの扱い</h2>
|
||||||
|
|
||||||
|
<p>
|
||||||
|
A チャンネル(インデックス <code>base + 4</code>)を変更すると、不透明度が変わります。
|
||||||
|
このとき RGB はストレートな色味を保ったまま再計算されます。アルファを 0 にすると、そのピクセルは透明になります。
|
||||||
|
</p>
|
||||||
|
|
||||||
|
<h2>putpixeldata について</h2>
|
||||||
|
|
||||||
|
<p>
|
||||||
|
<code>obj.putpixeldata()</code> は AviUtl との互換のために存在しますが、このプラグインでは
|
||||||
|
変更が自動的に反映されるため、呼び出す必要はありません(何もしません)。
|
||||||
|
</p>
|
||||||
|
|
||||||
|
<h2>性能とエンジン</h2>
|
||||||
|
|
||||||
|
<p>
|
||||||
|
ピクセル処理は重くなりがちです。このプラグインは <code>getpixel</code> / <code>setpixel</code> を含むスクリプトを
|
||||||
|
自動的に高速なネイティブレーンへ振り分けます(利用できる場合)。さらに、二重ループで
|
||||||
|
<code>getpixel</code> → 計算 → <code>setpixel</code> という決まった形のスクリプトは、CPU / GPU カーネルへ
|
||||||
|
変換されてさらに高速に実行できます。詳しくは <a href="engines.html">エンジンと高速化</a> を参照してください。
|
||||||
|
</p>
|
||||||
|
|
||||||
|
<div class="pager">
|
||||||
|
<a href="scene-ymm4.html">← scene と ymm4</a>
|
||||||
|
<a href="engines.html">エンジンと高速化 →</a>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
</main>
|
||||||
|
<script src="assets/nav.js"></script>
|
||||||
|
</body>
|
||||||
|
</html>
|
||||||
@@ -0,0 +1,141 @@
|
|||||||
|
<!DOCTYPE html>
|
||||||
|
<html lang="ja">
|
||||||
|
<head>
|
||||||
|
<meta charset="utf-8">
|
||||||
|
<meta name="viewport" content="width=device-width, initial-scale=1">
|
||||||
|
<title>クイックリファレンス | Lua スクリプト for YMM4</title>
|
||||||
|
<link rel="stylesheet" href="assets/style.css">
|
||||||
|
</head>
|
||||||
|
<body>
|
||||||
|
<button id="navtoggle" aria-label="メニュー">☰</button>
|
||||||
|
<nav id="sidebar"></nav>
|
||||||
|
<main>
|
||||||
|
|
||||||
|
<h1>クイックリファレンス</h1>
|
||||||
|
|
||||||
|
<p>すべての変数・関数・指定子を一覧でまとめます。詳細は各ページを参照してください。</p>
|
||||||
|
|
||||||
|
<h2>グローバル変数</h2>
|
||||||
|
<table>
|
||||||
|
<tr><th>変数</th><th>説明</th></tr>
|
||||||
|
<tr><td><code>time</code></td><td>アイテム基準の経過時間(秒)</td></tr>
|
||||||
|
<tr><td><code>frame</code></td><td>アイテム基準の現在フレーム</td></tr>
|
||||||
|
<tr><td><code>totalframe</code></td><td>アイテムの総フレーム数</td></tr>
|
||||||
|
<tr><td><code>framerate</code></td><td>フレームレート(fps)</td></tr>
|
||||||
|
<tr><td><code>timelineframe</code></td><td>タイムライン先頭からの絶対フレーム</td></tr>
|
||||||
|
<tr><td><code>timelinetime</code></td><td>タイムライン基準の時間(秒)</td></tr>
|
||||||
|
<tr><td><code>layer</code></td><td>レイヤー番号</td></tr>
|
||||||
|
<tr><td><code>color</code></td><td>Color パラメータの色(0xRRGGBB)</td></tr>
|
||||||
|
<tr><td><code>obj</code> / <code>scene</code> / <code>anim</code> / <code>ymm4</code></td><td>各テーブル</td></tr>
|
||||||
|
<tr><td><code>math</code> / <code>string</code> / <code>table</code> / <code>bit32</code></td><td>標準ライブラリ</td></tr>
|
||||||
|
</table>
|
||||||
|
|
||||||
|
<h2>obj(変更可能)</h2>
|
||||||
|
<table>
|
||||||
|
<tr><th>メンバー</th><th>説明</th></tr>
|
||||||
|
<tr><td><code>obj.x</code> / <code>obj.y</code> / <code>obj.z</code></td><td>描画位置</td></tr>
|
||||||
|
<tr><td><code>obj.ox</code> / <code>obj.oy</code> / <code>obj.oz</code></td><td>中心点オフセット</td></tr>
|
||||||
|
<tr><td><code>obj.zoom</code></td><td>拡大率(sx と sy の平均)</td></tr>
|
||||||
|
<tr><td><code>obj.aspect</code></td><td>縦横比(-1.0 ~ 1.0)</td></tr>
|
||||||
|
<tr><td><code>obj.sx</code> / <code>obj.sy</code></td><td>独立した拡大率</td></tr>
|
||||||
|
<tr><td><code>obj.alpha</code></td><td>不透明度(0.0 ~ 255.0)</td></tr>
|
||||||
|
<tr><td><code>obj.rx</code> / <code>obj.ry</code> / <code>obj.rz</code></td><td>回転角(度)</td></tr>
|
||||||
|
<tr><td><code>obj.rxr</code> / <code>obj.ryr</code> / <code>obj.rzr</code></td><td>回転角(ラジアン、優先)</td></tr>
|
||||||
|
</table>
|
||||||
|
|
||||||
|
<h2>obj(読み取り専用)</h2>
|
||||||
|
<table>
|
||||||
|
<tr><th>メンバー</th><th>説明</th></tr>
|
||||||
|
<tr><td><code>obj.w</code> / <code>obj.h</code></td><td>入力画像の幅 / 高さ</td></tr>
|
||||||
|
<tr><td><code>obj.hw</code> / <code>obj.hh</code></td><td>幅 / 高さの半分</td></tr>
|
||||||
|
<tr><td><code>obj.cx</code> / <code>obj.cy</code></td><td>画像中心</td></tr>
|
||||||
|
<tr><td><code>obj.cz</code> / <code>obj.sz</code></td><td>常に 0 / 常に 1</td></tr>
|
||||||
|
<tr><td><code>obj.diagonal</code></td><td>対角線長</td></tr>
|
||||||
|
<tr><td><code>obj.time</code> / <code>obj.frame</code></td><td>経過時間 / フレーム</td></tr>
|
||||||
|
<tr><td><code>obj.totalframe</code> / <code>obj.totaltime</code></td><td>総フレーム数 / 総時間</td></tr>
|
||||||
|
<tr><td><code>obj.t</code></td><td>進行割合(0.0 ~ 1.0)</td></tr>
|
||||||
|
<tr><td><code>obj.framerate</code></td><td>フレームレート</td></tr>
|
||||||
|
<tr><td><code>obj.layer</code></td><td>レイヤー番号</td></tr>
|
||||||
|
<tr><td><code>obj.index</code> / <code>obj.num</code></td><td>入力のインデックス / 総数</td></tr>
|
||||||
|
<tr><td><code>obj.track0</code> ~ <code>obj.track3</code></td><td>トラックバーの値</td></tr>
|
||||||
|
<tr><td><code>obj.check0</code> ~ <code>obj.check3</code></td><td>チェックボックスの値</td></tr>
|
||||||
|
<tr><td><code>obj.slider0</code> ~ <code>obj.slider3</code></td><td>整数スライダーの値</td></tr>
|
||||||
|
<tr><td><code>obj.text</code> / <code>obj.font</code> / <code>obj.dir</code></td><td>テキスト、フォント名、フォルダパス</td></tr>
|
||||||
|
<tr><td><code>obj.file_video</code> ~ <code>obj.file_shader</code></td><td>各ファイル選択欄のパス</td></tr>
|
||||||
|
</table>
|
||||||
|
|
||||||
|
<h2>obj 関数</h2>
|
||||||
|
<table>
|
||||||
|
<tr><th>関数</th><th>説明</th></tr>
|
||||||
|
<tr><td><code>obj.getobject(tag [, frame])</code></td><td>他アイテムの描画情報を取得</td></tr>
|
||||||
|
<tr><td><code>obj.getpixel(x, y)</code></td><td>ピクセル取得</td></tr>
|
||||||
|
<tr><td><code>obj.setpixel(x, y, r, g, b [, a])</code></td><td>ピクセル書き込み</td></tr>
|
||||||
|
<tr><td><code>obj.getpixeldata()</code></td><td>ピクセル直接アクセスプロキシ</td></tr>
|
||||||
|
<tr><td><code>obj.putpixeldata()</code></td><td>互換用の空実装</td></tr>
|
||||||
|
<tr><td><code>obj.rand(a, b [, seed [, frame]])</code></td><td>整数の安定した乱数</td></tr>
|
||||||
|
<tr><td><code>obj.load(種類, ...)</code></td><td>図形 / テキスト / 画像 / 動画の読み込み</td></tr>
|
||||||
|
<tr><td><code>obj.setfont(name [, size [, type [, color]]])</code></td><td>フォント設定</td></tr>
|
||||||
|
<tr><td><code>obj.effect(name, key, val, ...)</code></td><td>AviUtl/AviUtl2 互換マップ経由でエフェクトを適用</td></tr>
|
||||||
|
<tr><td><code>obj.draw([ox, oy, oz, zoom, alpha, aspect])</code></td><td>バッファの描画</td></tr>
|
||||||
|
<tr><td><code>obj.drawpoly(...)</code></td><td>4 頂点ポリゴンの描画</td></tr>
|
||||||
|
<tr><td><code>obj.copybuffer(dst, src)</code></td><td>バッファのコピー</td></tr>
|
||||||
|
<tr><td><code>obj.setoption(name [, value])</code> / <code>obj.getoption(name)</code></td><td>オプションの設定 / 取得</td></tr>
|
||||||
|
<tr><td><code>obj.getvalue(name)</code></td><td>obj の数値メンバーを名前で取得</td></tr>
|
||||||
|
<tr><td><code>obj.pixeloption(name [, value])</code></td><td>ピクセル処理オプション</td></tr>
|
||||||
|
</table>
|
||||||
|
|
||||||
|
<h2>anim(定数)</h2>
|
||||||
|
<table>
|
||||||
|
<tr><th>定数</th><th>説明</th></tr>
|
||||||
|
<tr><td><code>anim.tau</code></td><td>math.pi * 2</td></tr>
|
||||||
|
<tr><td><code>anim.e</code></td><td>ネイピア数</td></tr>
|
||||||
|
<tr><td><code>anim.phi</code></td><td>黄金比</td></tr>
|
||||||
|
<tr><td><code>anim.sqrt2</code></td><td>2 の平方根</td></tr>
|
||||||
|
</table>
|
||||||
|
|
||||||
|
<h2>anim(関数)</h2>
|
||||||
|
<table>
|
||||||
|
<tr><th>分類</th><th>関数</th></tr>
|
||||||
|
<tr><td>補間・イージング</td><td><code>lerp, smoothstep, smootherstep, ease_in, ease_out, ease_in_out, elastic, back, bounce, step, bezier</code></td></tr>
|
||||||
|
<tr><td>範囲・周期</td><td><code>clamp, map, norm, wrap, pingpong, sign, fract, oscillate, triangle, square, duration, delay</code></td></tr>
|
||||||
|
<tr><td>ベクトル・幾何</td><td><code>len, dist, dot, normalize, polar, rotate</code></td></tr>
|
||||||
|
<tr><td>ノイズ・乱数</td><td><code>noise, rand</code></td></tr>
|
||||||
|
<tr><td>色変換</td><td><code>hsv_to_rgb, rgb_to_hsv</code></td></tr>
|
||||||
|
</table>
|
||||||
|
|
||||||
|
<h2>scene</h2>
|
||||||
|
<table>
|
||||||
|
<tr><th>メンバー</th><th>説明</th></tr>
|
||||||
|
<tr><td><code>scene.width</code> / <code>scene.height</code></td><td>シーンの解像度</td></tr>
|
||||||
|
<tr><td><code>scene.cx</code> / <code>scene.cy</code></td><td>解像度の半分</td></tr>
|
||||||
|
</table>
|
||||||
|
|
||||||
|
<h2>ymm4</h2>
|
||||||
|
<table>
|
||||||
|
<tr><th>メンバー</th><th>説明</th></tr>
|
||||||
|
<tr><td><code>ymm4.group_index</code> / <code>group_count</code> / <code>group_ratio</code></td><td>グループ制御の情報</td></tr>
|
||||||
|
<tr><td><code>ymm4.timeline_totalframe</code> / <code>timeline_totaltime</code></td><td>タイムライン全体の長さ</td></tr>
|
||||||
|
<tr><td><code>ymm4.time_ratio</code></td><td>再生位置の割合</td></tr>
|
||||||
|
<tr><td><code>ymm4.is_saving</code> / <code>is_playing</code> / <code>is_paused</code></td><td>再生・出力状態</td></tr>
|
||||||
|
<tr><td><code>ymm4.scene_id</code></td><td>シーン識別子(GUID)</td></tr>
|
||||||
|
</table>
|
||||||
|
|
||||||
|
<h2>指定子</h2>
|
||||||
|
<table>
|
||||||
|
<tr><th>指定子</th><th>説明</th></tr>
|
||||||
|
<tr><td><code>--track0:</code> ~ <code>--track3:</code></td><td>トラックバーの定義</td></tr>
|
||||||
|
<tr><td><code>--check0:</code> ~ <code>--check3:</code></td><td>チェックボックスの定義</td></tr>
|
||||||
|
<tr><td><code>--color:</code></td><td>色パラメータの既定色</td></tr>
|
||||||
|
<tr><td><code>--param:</code> / <code>--dialog:</code></td><td>本文先頭への宣言の追加</td></tr>
|
||||||
|
<tr><td><code>--!moonsharp</code> / <code>--!native</code> / <code>--!cpu</code> / <code>--!gpu</code></td><td>実行エンジンの指定</td></tr>
|
||||||
|
</table>
|
||||||
|
|
||||||
|
<div class="pager">
|
||||||
|
<a href="samples.html">← サンプル集</a>
|
||||||
|
<a href="limits.html">制限事項とトラブル →</a>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
</main>
|
||||||
|
<script src="assets/nav.js"></script>
|
||||||
|
</body>
|
||||||
|
</html>
|
||||||
+204
@@ -0,0 +1,204 @@
|
|||||||
|
<!DOCTYPE html>
|
||||||
|
<html lang="ja">
|
||||||
|
<head>
|
||||||
|
<meta charset="utf-8">
|
||||||
|
<meta name="viewport" content="width=device-width, initial-scale=1">
|
||||||
|
<title>サンプル集 | Lua スクリプト for YMM4</title>
|
||||||
|
<link rel="stylesheet" href="assets/style.css">
|
||||||
|
</head>
|
||||||
|
<body>
|
||||||
|
<button id="navtoggle" aria-label="メニュー">☰</button>
|
||||||
|
<nav id="sidebar"></nav>
|
||||||
|
<main>
|
||||||
|
|
||||||
|
<h1>サンプル集</h1>
|
||||||
|
|
||||||
|
<p>
|
||||||
|
各サンプルはエフェクトのスクリプト欄にそのまま貼り付けて使えます。
|
||||||
|
<code>Track0</code> ~ <code>Track3</code> はパラメータパネルのトラックバーで調整できます。
|
||||||
|
使われている変数・関数の意味は各リファレンスページを参照してください。
|
||||||
|
</p>
|
||||||
|
|
||||||
|
<h2>基本</h2>
|
||||||
|
|
||||||
|
<h3>フェードイン(既定スクリプト)</h3>
|
||||||
|
<pre><code>obj.alpha = math.min(time * 255, 255)</code></pre>
|
||||||
|
|
||||||
|
<h3>フェードアウト</h3>
|
||||||
|
<pre><code>obj.alpha = math.max((obj.totalframe - obj.frame) / obj.framerate * 255, 0)</code></pre>
|
||||||
|
|
||||||
|
<h3>Track0 で不透明度を制御</h3>
|
||||||
|
<pre><code>obj.alpha = obj.track0</code></pre>
|
||||||
|
|
||||||
|
<h3>時間に応じて回転</h3>
|
||||||
|
<pre><code>obj.rz = time * 90</code></pre>
|
||||||
|
|
||||||
|
<h3>Track0 でズームを制御</h3>
|
||||||
|
<pre><code>obj.zoom = obj.zoom * (1 + obj.track0 / 100)</code></pre>
|
||||||
|
|
||||||
|
<h2>座標と動き</h2>
|
||||||
|
|
||||||
|
<h3>左右の揺れ</h3>
|
||||||
|
<p>Track0 を振幅、Track1 を 1 秒あたりの周波数として使います。振幅の単位はピクセルです。</p>
|
||||||
|
<pre><code>local amp = obj.track0
|
||||||
|
local freq = obj.track1
|
||||||
|
obj.x = obj.x + math.sin(time * anim.tau * freq) * amp</code></pre>
|
||||||
|
|
||||||
|
<h3>円運動</h3>
|
||||||
|
<pre><code>local r = obj.track0
|
||||||
|
local dx, dy = anim.polar(r, time * 90)
|
||||||
|
obj.x = obj.x + dx
|
||||||
|
obj.y = obj.y + dy</code></pre>
|
||||||
|
|
||||||
|
<h3>バウンド(跳ねる)</h3>
|
||||||
|
<pre><code>local h = obj.track0
|
||||||
|
obj.y = obj.y - anim.bounce(anim.pingpong(time, 1)) * h</code></pre>
|
||||||
|
|
||||||
|
<h3>ゆらぎ(ノイズによる手ぶれ風)</h3>
|
||||||
|
<pre><code>obj.x = obj.x + (anim.noise(time * 2, 0, 0) - 0.5) * 20
|
||||||
|
obj.y = obj.y + (anim.noise(0, time * 2, 0) - 0.5) * 20
|
||||||
|
obj.rz = (anim.noise(0, 0, time * 2) - 0.5) * 10</code></pre>
|
||||||
|
|
||||||
|
<h2>回転</h2>
|
||||||
|
|
||||||
|
<h3>度とラジアン</h3>
|
||||||
|
<pre><code>obj.rzr = time * anim.tau</code></pre>
|
||||||
|
|
||||||
|
<h3>加速しながら回転</h3>
|
||||||
|
<pre><code>obj.rz = anim.ease_in(obj.t) * 360</code></pre>
|
||||||
|
|
||||||
|
<h2>拡大・変形</h2>
|
||||||
|
|
||||||
|
<h3>弾むように登場(スケールイン)</h3>
|
||||||
|
<pre><code>local p = anim.duration(time, 0.3)
|
||||||
|
obj.zoom = obj.zoom * anim.elastic(p)</code></pre>
|
||||||
|
|
||||||
|
<h3>ぷにぷに(独立スケール)</h3>
|
||||||
|
<pre><code>local s = math.sin(time * anim.tau * 2) * 0.2
|
||||||
|
obj.sx = 1 + s
|
||||||
|
obj.sy = 1 - s</code></pre>
|
||||||
|
|
||||||
|
<h2>不透明度・フェード</h2>
|
||||||
|
|
||||||
|
<h3>遅延フェードイン</h3>
|
||||||
|
<pre><code>local p = anim.duration(anim.delay(time, 0.5), 1)
|
||||||
|
obj.alpha = p * 255</code></pre>
|
||||||
|
|
||||||
|
<h3>点滅(矩形波)</h3>
|
||||||
|
<pre><code>obj.alpha = anim.square(time, 4) * 255</code></pre>
|
||||||
|
|
||||||
|
<h3>滑らかな明滅(正弦波)</h3>
|
||||||
|
<pre><code>obj.alpha = anim.oscillate(time, 64, 255, 1)</code></pre>
|
||||||
|
|
||||||
|
<h2>イージングと範囲</h2>
|
||||||
|
|
||||||
|
<h3>2 点間をイージングで移動</h3>
|
||||||
|
<pre><code>local tx, ty = 200, -100
|
||||||
|
local p = anim.ease_in_out(obj.t)
|
||||||
|
obj.x = anim.lerp(obj.x, tx, p)
|
||||||
|
obj.y = anim.lerp(obj.y, ty, p)</code></pre>
|
||||||
|
|
||||||
|
<h3>行き過ぎてから戻る</h3>
|
||||||
|
<pre><code>obj.x = obj.x + anim.back(obj.t) * 200</code></pre>
|
||||||
|
|
||||||
|
<h3>しきい値で切り替え</h3>
|
||||||
|
<pre><code>obj.alpha = anim.smoothstep(0, 0.5, obj.t) * 255</code></pre>
|
||||||
|
|
||||||
|
<h2>他オブジェクトの参照</h2>
|
||||||
|
|
||||||
|
<h3>発射元へ向きながら移動する(ファンネル風)</h3>
|
||||||
|
<pre><code>local target = obj.getobject("routersys")
|
||||||
|
if target then
|
||||||
|
local p = anim.ease_in_out(obj.t)
|
||||||
|
local nx = anim.lerp(obj.x, target.x, p)
|
||||||
|
local ny = anim.lerp(obj.y, target.y, p)
|
||||||
|
obj.rz = math.deg(math.atan2(target.y - obj.y, target.x - obj.x))
|
||||||
|
obj.x = nx
|
||||||
|
obj.y = ny
|
||||||
|
end</code></pre>
|
||||||
|
|
||||||
|
<h3>一定速度で接近し、到達したら停止</h3>
|
||||||
|
<pre><code>local target = obj.getobject("routersys")
|
||||||
|
if target then
|
||||||
|
local dx = target.x - obj.x
|
||||||
|
local dy = target.y - obj.y
|
||||||
|
local dist = anim.len(dx, dy)
|
||||||
|
if dist > 0 then
|
||||||
|
local step = math.min(dist, obj.track0 * obj.time)
|
||||||
|
obj.x = obj.x + dx / dist * step
|
||||||
|
obj.y = obj.y + dy / dist * step
|
||||||
|
end
|
||||||
|
end</code></pre>
|
||||||
|
|
||||||
|
<h2>ピクセル操作</h2>
|
||||||
|
|
||||||
|
<h3>色の反転</h3>
|
||||||
|
<pre><code>for y = 0, obj.h - 1 do
|
||||||
|
for x = 0, obj.w - 1 do
|
||||||
|
local r, g, b, a = obj.getpixel(x, y)
|
||||||
|
obj.setpixel(x, y, 255 - r, 255 - g, 255 - b, a)
|
||||||
|
end
|
||||||
|
end</code></pre>
|
||||||
|
|
||||||
|
<h3>グレースケール(高速)</h3>
|
||||||
|
<pre><code>local pd = obj.getpixeldata()
|
||||||
|
local w = pd.width
|
||||||
|
local h = pd.height
|
||||||
|
for y = 0, h - 1 do
|
||||||
|
for x = 0, w - 1 do
|
||||||
|
local base = (y * w + x) * 4
|
||||||
|
local r = pd:get(base + 1)
|
||||||
|
local g = pd:get(base + 2)
|
||||||
|
local b = pd:get(base + 3)
|
||||||
|
local gray = r * 0.299 + g * 0.587 + b * 0.114
|
||||||
|
pd:set(base + 1, gray)
|
||||||
|
pd:set(base + 2, gray)
|
||||||
|
pd:set(base + 3, gray)
|
||||||
|
end
|
||||||
|
end</code></pre>
|
||||||
|
|
||||||
|
<h3>時間で色相を回す(虹色)</h3>
|
||||||
|
<pre><code>local hue = anim.wrap(time * 60, 0, 360)
|
||||||
|
local cr, cg, cb = anim.hsv_to_rgb(hue, 1, 1)
|
||||||
|
local pd = obj.getpixeldata()
|
||||||
|
local n = pd.width * pd.height
|
||||||
|
for i = 0, n - 1 do
|
||||||
|
local base = i * 4
|
||||||
|
pd:set(base + 1, pd:get(base + 1) * cr / 255)
|
||||||
|
pd:set(base + 2, pd:get(base + 2) * cg / 255)
|
||||||
|
pd:set(base + 3, pd:get(base + 3) * cb / 255)
|
||||||
|
end</code></pre>
|
||||||
|
|
||||||
|
<h2>図形・テキスト</h2>
|
||||||
|
|
||||||
|
<h3>星形を生成して回す</h3>
|
||||||
|
<pre><code>obj.load("figure", "star", 0xFFCC00, 200, 0, 0)
|
||||||
|
obj.rz = time * 90</code></pre>
|
||||||
|
|
||||||
|
<h3>テキストを生成する</h3>
|
||||||
|
<pre><code>obj.setfont("Yu Gothic UI", 48, 1, 0xFFFFFF)
|
||||||
|
obj.load("text", "サンプル")</code></pre>
|
||||||
|
|
||||||
|
<h2>環境に応じた制御</h2>
|
||||||
|
|
||||||
|
<h3>グループ内のインデックスで時間差をつける</h3>
|
||||||
|
<pre><code>local d = ymm4.group_index * 0.1
|
||||||
|
local p = anim.duration(anim.delay(time, d), 0.5)
|
||||||
|
obj.alpha = p * 255</code></pre>
|
||||||
|
|
||||||
|
<h3>出力時のみ挙動を変える</h3>
|
||||||
|
<pre><code>if ymm4.is_saving then
|
||||||
|
obj.alpha = 255
|
||||||
|
else
|
||||||
|
obj.alpha = 128
|
||||||
|
end</code></pre>
|
||||||
|
|
||||||
|
<div class="pager">
|
||||||
|
<a href="directives.html">← パラメータ指定子</a>
|
||||||
|
<a href="reference.html">クイックリファレンス →</a>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
</main>
|
||||||
|
<script src="assets/nav.js"></script>
|
||||||
|
</body>
|
||||||
|
</html>
|
||||||
@@ -0,0 +1,78 @@
|
|||||||
|
<!DOCTYPE html>
|
||||||
|
<html lang="ja">
|
||||||
|
<head>
|
||||||
|
<meta charset="utf-8">
|
||||||
|
<meta name="viewport" content="width=device-width, initial-scale=1">
|
||||||
|
<title>scene と ymm4 | Lua スクリプト for YMM4</title>
|
||||||
|
<link rel="stylesheet" href="assets/style.css">
|
||||||
|
</head>
|
||||||
|
<body>
|
||||||
|
<button id="navtoggle" aria-label="メニュー">☰</button>
|
||||||
|
<nav id="sidebar"></nav>
|
||||||
|
<main>
|
||||||
|
|
||||||
|
<h1>scene と ymm4</h1>
|
||||||
|
|
||||||
|
<p>
|
||||||
|
<code>scene</code> はシーンの解像度を、<code>ymm4</code> はグループ・タイムライン・再生状態などの
|
||||||
|
環境情報を提供します。どちらも読み取り専用です。
|
||||||
|
</p>
|
||||||
|
|
||||||
|
<h2>scene — シーン情報</h2>
|
||||||
|
|
||||||
|
<table>
|
||||||
|
<tr><th>メンバー</th><th>説明</th></tr>
|
||||||
|
<tr><td><code>scene.width</code></td><td>シーンの横解像度(ピクセル)</td></tr>
|
||||||
|
<tr><td><code>scene.height</code></td><td>シーンの縦解像度(ピクセル)</td></tr>
|
||||||
|
<tr><td><code>scene.cx</code></td><td>横解像度の半分(<code>scene.width / 2</code>)</td></tr>
|
||||||
|
<tr><td><code>scene.cy</code></td><td>縦解像度の半分(<code>scene.height / 2</code>)</td></tr>
|
||||||
|
</table>
|
||||||
|
|
||||||
|
<div class="note">
|
||||||
|
このプラグインで使える <code>scene</code> は解像度の読み取りのみです。
|
||||||
|
AviUtl の <code>scene.set()</code> / <code>scene.get()</code> のような機能はありません。
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<h3>シーンサイズに対する相対配置</h3>
|
||||||
|
<pre><code>obj.x = scene.cx * obj.track0 / 100</code></pre>
|
||||||
|
|
||||||
|
<h2>ymm4 — 環境・メタ情報</h2>
|
||||||
|
|
||||||
|
<table>
|
||||||
|
<tr><th>メンバー</th><th>型</th><th>説明</th></tr>
|
||||||
|
<tr><td><code>ymm4.group_index</code></td><td>整数</td><td>グループ制御内の現在のインデックス(0 始まり)</td></tr>
|
||||||
|
<tr><td><code>ymm4.group_count</code></td><td>整数</td><td>グループ制御内の総アイテム数</td></tr>
|
||||||
|
<tr><td><code>ymm4.group_ratio</code></td><td>数値</td><td>グループ内の進行割合(<code>group_index / group_count</code>)</td></tr>
|
||||||
|
<tr><td><code>ymm4.timeline_totalframe</code></td><td>整数</td><td>タイムライン全体の総フレーム数</td></tr>
|
||||||
|
<tr><td><code>ymm4.timeline_totaltime</code></td><td>数値</td><td>タイムライン全体の総時間(秒)</td></tr>
|
||||||
|
<tr><td><code>ymm4.time_ratio</code></td><td>数値</td><td>現在の再生位置の割合(0.0 ~ 1.0)</td></tr>
|
||||||
|
<tr><td><code>ymm4.is_saving</code></td><td>真偽値</td><td>動画出力中のみ true</td></tr>
|
||||||
|
<tr><td><code>ymm4.is_playing</code></td><td>真偽値</td><td>再生中のみ true</td></tr>
|
||||||
|
<tr><td><code>ymm4.is_paused</code></td><td>真偽値</td><td>一時停止中のみ true</td></tr>
|
||||||
|
<tr><td><code>ymm4.scene_id</code></td><td>文字列</td><td>現在のシーンを識別する文字列(GUID)</td></tr>
|
||||||
|
</table>
|
||||||
|
|
||||||
|
<h3>グループ内のインデックスで時間差をつける</h3>
|
||||||
|
<pre><code>local d = ymm4.group_index * 0.1
|
||||||
|
local p = anim.duration(anim.delay(time, d), 0.5)
|
||||||
|
obj.alpha = p * 255</code></pre>
|
||||||
|
|
||||||
|
<h3>グループ内の進行割合で配置をずらす</h3>
|
||||||
|
<pre><code>obj.x = obj.x + ymm4.group_ratio * 400</code></pre>
|
||||||
|
|
||||||
|
<h3>出力時のみ挙動を変える</h3>
|
||||||
|
<pre><code>if ymm4.is_saving then
|
||||||
|
obj.alpha = 255
|
||||||
|
else
|
||||||
|
obj.alpha = 128
|
||||||
|
end</code></pre>
|
||||||
|
|
||||||
|
<div class="pager">
|
||||||
|
<a href="anim.html">← anim ライブラリ</a>
|
||||||
|
<a href="pixels.html">ピクセル操作 →</a>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
</main>
|
||||||
|
<script src="assets/nav.js"></script>
|
||||||
|
</body>
|
||||||
|
</html>
|
||||||
@@ -0,0 +1,86 @@
|
|||||||
|
<?xml version="1.0" encoding="UTF-8"?>
|
||||||
|
<urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
|
||||||
|
|
||||||
|
<!-- created with free sitemap generation system www.sitemapxml.jp -->
|
||||||
|
<url>
|
||||||
|
<loc>https://luascript.routersys.com/</loc>
|
||||||
|
<priority>1.0</priority>
|
||||||
|
<lastmod>2026-06-30T12:31:48+09:00</lastmod>
|
||||||
|
</url>
|
||||||
|
<url>
|
||||||
|
<loc>https://luascript.routersys.com/engines.html</loc>
|
||||||
|
<priority>0.8</priority>
|
||||||
|
<lastmod>2026-06-30T12:31:48+09:00</lastmod>
|
||||||
|
</url>
|
||||||
|
<url>
|
||||||
|
<loc>https://luascript.routersys.com/getting-started.html</loc>
|
||||||
|
<priority>0.8</priority>
|
||||||
|
<lastmod>2026-06-30T12:31:48+09:00</lastmod>
|
||||||
|
</url>
|
||||||
|
<url>
|
||||||
|
<loc>https://luascript.routersys.com/lua-basics.html</loc>
|
||||||
|
<priority>0.8</priority>
|
||||||
|
<lastmod>2026-06-30T12:31:48+09:00</lastmod>
|
||||||
|
</url>
|
||||||
|
<url>
|
||||||
|
<loc>https://luascript.routersys.com/obj.html</loc>
|
||||||
|
<priority>0.8</priority>
|
||||||
|
<lastmod>2026-06-30T12:31:48+09:00</lastmod>
|
||||||
|
</url>
|
||||||
|
<url>
|
||||||
|
<loc>https://luascript.routersys.com/anim.html</loc>
|
||||||
|
<priority>0.8</priority>
|
||||||
|
<lastmod>2026-06-30T12:31:48+09:00</lastmod>
|
||||||
|
</url>
|
||||||
|
<url>
|
||||||
|
<loc>https://luascript.routersys.com/pixels.html</loc>
|
||||||
|
<priority>0.8</priority>
|
||||||
|
<lastmod>2026-06-30T12:31:48+09:00</lastmod>
|
||||||
|
</url>
|
||||||
|
<url>
|
||||||
|
<loc>https://luascript.routersys.com/samples.html</loc>
|
||||||
|
<priority>0.8</priority>
|
||||||
|
<lastmod>2026-06-30T12:31:48+09:00</lastmod>
|
||||||
|
</url>
|
||||||
|
<url>
|
||||||
|
<loc>https://luascript.routersys.com/globals.html</loc>
|
||||||
|
<priority>0.8</priority>
|
||||||
|
<lastmod>2026-06-30T12:31:48+09:00</lastmod>
|
||||||
|
</url>
|
||||||
|
<url>
|
||||||
|
<loc>https://luascript.routersys.com/obj-functions.html</loc>
|
||||||
|
<priority>0.8</priority>
|
||||||
|
<lastmod>2026-06-30T12:31:48+09:00</lastmod>
|
||||||
|
</url>
|
||||||
|
<url>
|
||||||
|
<loc>https://luascript.routersys.com/scene-ymm4.html</loc>
|
||||||
|
<priority>0.8</priority>
|
||||||
|
<lastmod>2026-06-30T12:31:48+09:00</lastmod>
|
||||||
|
</url>
|
||||||
|
<url>
|
||||||
|
<loc>https://luascript.routersys.com/directives.html</loc>
|
||||||
|
<priority>0.8</priority>
|
||||||
|
<lastmod>2026-06-30T12:31:48+09:00</lastmod>
|
||||||
|
</url>
|
||||||
|
<url>
|
||||||
|
<loc>https://luascript.routersys.com/limits.html</loc>
|
||||||
|
<priority>0.7</priority>
|
||||||
|
<lastmod>2026-06-30T12:31:48+09:00</lastmod>
|
||||||
|
</url>
|
||||||
|
<url>
|
||||||
|
<loc>https://luascript.routersys.com/index.html</loc>
|
||||||
|
<priority>0.7</priority>
|
||||||
|
<lastmod>2026-06-30T12:31:48+09:00</lastmod>
|
||||||
|
</url>
|
||||||
|
<url>
|
||||||
|
<loc>https://luascript.routersys.com/stdlib.html</loc>
|
||||||
|
<priority>0.7</priority>
|
||||||
|
<lastmod>2026-06-30T12:31:48+09:00</lastmod>
|
||||||
|
</url>
|
||||||
|
<url>
|
||||||
|
<loc>https://luascript.routersys.com/reference.html</loc>
|
||||||
|
<priority>0.7</priority>
|
||||||
|
<lastmod>2026-06-30T12:31:48+09:00</lastmod>
|
||||||
|
</url>
|
||||||
|
|
||||||
|
</urlset>
|
||||||
+151
@@ -0,0 +1,151 @@
|
|||||||
|
<!DOCTYPE html>
|
||||||
|
<html lang="ja">
|
||||||
|
<head>
|
||||||
|
<meta charset="utf-8">
|
||||||
|
<meta name="viewport" content="width=device-width, initial-scale=1">
|
||||||
|
<title>標準ライブラリ | Lua スクリプト for YMM4</title>
|
||||||
|
<link rel="stylesheet" href="assets/style.css">
|
||||||
|
</head>
|
||||||
|
<body>
|
||||||
|
<button id="navtoggle" aria-label="メニュー">☰</button>
|
||||||
|
<nav id="sidebar"></nav>
|
||||||
|
<main>
|
||||||
|
|
||||||
|
<h1>標準ライブラリ</h1>
|
||||||
|
|
||||||
|
<p>
|
||||||
|
利用できる標準ライブラリは次のモジュールに限定されています:
|
||||||
|
基本関数・math・string・table・bit32、
|
||||||
|
そしてテーブル反復子(<code>pairs</code> / <code>ipairs</code> / <code>next</code>)・メタテーブル・エラー処理です。
|
||||||
|
</p>
|
||||||
|
|
||||||
|
<div class="warn">
|
||||||
|
<code>io</code>・<code>os</code>・<code>debug</code>・<code>coroutine</code>・<code>package</code>・<code>require</code>・
|
||||||
|
<code>dofile</code>・<code>ffi</code> などは使えません。ファイルアクセスは無効化されています。
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<h2>基本関数</h2>
|
||||||
|
|
||||||
|
<p>グローバルに直接呼べる関数です。</p>
|
||||||
|
|
||||||
|
<pre><code>type, tostring, tonumber, select, error, assert, print,
|
||||||
|
ipairs, pairs, next, unpack,
|
||||||
|
setmetatable, getmetatable, rawget, rawset, rawequal, rawlen,
|
||||||
|
pcall, xpcall</code></pre>
|
||||||
|
|
||||||
|
<table>
|
||||||
|
<tr><th>関数</th><th>説明</th></tr>
|
||||||
|
<tr><td><code>type(v)</code></td><td>値の型名を文字列で返す</td></tr>
|
||||||
|
<tr><td><code>tostring(v)</code></td><td>文字列へ変換</td></tr>
|
||||||
|
<tr><td><code>tonumber(v [, base])</code></td><td>数値へ変換。変換できなければ nil</td></tr>
|
||||||
|
<tr><td><code>select(n, ...)</code></td><td>可変長引数の n 番目以降、または <code>"#"</code> で個数</td></tr>
|
||||||
|
<tr><td><code>error(msg)</code></td><td>エラーを発生させる</td></tr>
|
||||||
|
<tr><td><code>assert(v [, msg])</code></td><td>v が偽ならエラー</td></tr>
|
||||||
|
<tr><td><code>pcall(f, ...)</code></td><td>f を保護モードで呼び、成否と結果を返す</td></tr>
|
||||||
|
<tr><td><code>xpcall(f, handler, ...)</code></td><td>エラーハンドラ付きの保護呼び出し</td></tr>
|
||||||
|
<tr><td><code>ipairs(t)</code> / <code>pairs(t)</code></td><td>テーブルの反復子</td></tr>
|
||||||
|
<tr><td><code>setmetatable</code> / <code>getmetatable</code></td><td>メタテーブルの設定・取得</td></tr>
|
||||||
|
<tr><td><code>rawget</code> / <code>rawset</code> / <code>rawequal</code> / <code>rawlen</code></td><td>メタメソッドを介さない素の操作</td></tr>
|
||||||
|
</table>
|
||||||
|
|
||||||
|
<h2>math</h2>
|
||||||
|
|
||||||
|
<pre><code>abs, ceil, cos, exp, floor, fmod, huge, log, max, min, modf, pi,
|
||||||
|
random, randomseed, sin, sqrt, tan, atan, atan2, deg, rad,
|
||||||
|
ldexp, frexp, sinh, cosh, tanh, type, tointeger, maxinteger, mininteger</code></pre>
|
||||||
|
|
||||||
|
<table>
|
||||||
|
<tr><th>関数 / 定数</th><th>説明</th></tr>
|
||||||
|
<tr><td><code>math.pi</code></td><td>円周率</td></tr>
|
||||||
|
<tr><td><code>math.huge</code></td><td>正の無限大</td></tr>
|
||||||
|
<tr><td><code>math.abs(x)</code></td><td>絶対値</td></tr>
|
||||||
|
<tr><td><code>math.floor(x)</code> / <code>math.ceil(x)</code></td><td>切り捨て / 切り上げ</td></tr>
|
||||||
|
<tr><td><code>math.min(...)</code> / <code>math.max(...)</code></td><td>最小 / 最大</td></tr>
|
||||||
|
<tr><td><code>math.sqrt(x)</code></td><td>平方根</td></tr>
|
||||||
|
<tr><td><code>math.sin/cos/tan(x)</code></td><td>三角関数(引数はラジアン)</td></tr>
|
||||||
|
<tr><td><code>math.atan(x)</code> / <code>math.atan2(y, x)</code></td><td>逆正接</td></tr>
|
||||||
|
<tr><td><code>math.deg(x)</code> / <code>math.rad(x)</code></td><td>ラジアン↔度</td></tr>
|
||||||
|
<tr><td><code>math.exp(x)</code> / <code>math.log(x)</code></td><td>指数 / 自然対数</td></tr>
|
||||||
|
<tr><td><code>math.fmod(x, y)</code></td><td>剰余</td></tr>
|
||||||
|
<tr><td><code>math.modf(x)</code></td><td>整数部と小数部を返す</td></tr>
|
||||||
|
<tr><td><code>math.ldexp(m, e)</code> / <code>math.frexp(x)</code></td><td>仮数・指数の操作</td></tr>
|
||||||
|
<tr><td><code>math.sinh/cosh/tanh(x)</code></td><td>双曲線関数</td></tr>
|
||||||
|
<tr><td><code>math.random([m [, n]])</code></td><td>乱数。後述の注意あり</td></tr>
|
||||||
|
<tr><td><code>math.randomseed(x)</code></td><td>乱数シードの設定</td></tr>
|
||||||
|
<tr><td><code>math.type(x)</code></td><td>数値の種別を返す</td></tr>
|
||||||
|
<tr><td><code>math.tointeger(x)</code></td><td>整数化できれば整数、できなければ nil</td></tr>
|
||||||
|
<tr><td><code>math.maxinteger</code> / <code>math.mininteger</code></td><td>整数の上限・下限</td></tr>
|
||||||
|
</table>
|
||||||
|
|
||||||
|
<div class="note">
|
||||||
|
<code>math.random</code> は実行のたびに現在のフレーム番号でシードが設定されます。
|
||||||
|
そのため同じフレームの再描画では同じ結果になりますが、1 回の実行の中で連続して呼ぶと値は進みます。
|
||||||
|
オブジェクトやフレームに対して安定した乱数が必要なときは
|
||||||
|
<a href="anim.html"><code>anim.rand</code></a>・<code>anim.noise</code>・<code>obj.rand</code> を使ってください。
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<h2>string</h2>
|
||||||
|
|
||||||
|
<pre><code>format, len, sub, upper, lower, rep, reverse, find, match,
|
||||||
|
gmatch, gsub, byte, char, dump, pack, unpack, packsize</code></pre>
|
||||||
|
|
||||||
|
<table>
|
||||||
|
<tr><th>関数</th><th>説明</th></tr>
|
||||||
|
<tr><td><code>string.format(fmt, ...)</code></td><td>書式付き文字列。例: <code>string.format("%.2f", x)</code></td></tr>
|
||||||
|
<tr><td><code>string.len(s)</code></td><td>長さ(<code>#s</code> と同じ)</td></tr>
|
||||||
|
<tr><td><code>string.sub(s, i [, j])</code></td><td>部分文字列</td></tr>
|
||||||
|
<tr><td><code>string.upper(s)</code> / <code>string.lower(s)</code></td><td>大文字 / 小文字</td></tr>
|
||||||
|
<tr><td><code>string.rep(s, n)</code></td><td>n 回繰り返した文字列</td></tr>
|
||||||
|
<tr><td><code>string.reverse(s)</code></td><td>反転</td></tr>
|
||||||
|
<tr><td><code>string.find(s, pat)</code></td><td>パターン検索</td></tr>
|
||||||
|
<tr><td><code>string.match(s, pat)</code></td><td>パターンに一致した部分を返す</td></tr>
|
||||||
|
<tr><td><code>string.gmatch(s, pat)</code></td><td>一致を順に返す反復子</td></tr>
|
||||||
|
<tr><td><code>string.gsub(s, pat, repl)</code></td><td>置換</td></tr>
|
||||||
|
<tr><td><code>string.byte(s [, i])</code> / <code>string.char(...)</code></td><td>文字コード↔文字</td></tr>
|
||||||
|
<tr><td><code>string.pack/unpack/packsize</code></td><td>バイナリのパック・アンパック</td></tr>
|
||||||
|
</table>
|
||||||
|
|
||||||
|
<h2>table</h2>
|
||||||
|
|
||||||
|
<pre><code>insert, remove, sort, concat, unpack, move</code></pre>
|
||||||
|
|
||||||
|
<table>
|
||||||
|
<tr><th>関数</th><th>説明</th></tr>
|
||||||
|
<tr><td><code>table.insert(t, [pos,] v)</code></td><td>要素を追加・挿入</td></tr>
|
||||||
|
<tr><td><code>table.remove(t [, pos])</code></td><td>要素を削除して返す</td></tr>
|
||||||
|
<tr><td><code>table.sort(t [, comp])</code></td><td>並べ替え</td></tr>
|
||||||
|
<tr><td><code>table.concat(t [, sep])</code></td><td>文字列に連結</td></tr>
|
||||||
|
<tr><td><code>table.unpack(t)</code></td><td>テーブルを複数の値に展開</td></tr>
|
||||||
|
<tr><td><code>table.move(a1, f, e, t [, a2])</code></td><td>要素の移動・コピー</td></tr>
|
||||||
|
</table>
|
||||||
|
|
||||||
|
<h2>bit32</h2>
|
||||||
|
|
||||||
|
<p>32 ビット整数のビット演算ライブラリです。</p>
|
||||||
|
|
||||||
|
<pre><code>band, bor, bxor, bnot, lshift, rshift, arshift,
|
||||||
|
extract, replace, btest, countlz, countrz</code></pre>
|
||||||
|
|
||||||
|
<table>
|
||||||
|
<tr><th>関数</th><th>説明</th></tr>
|
||||||
|
<tr><td><code>bit32.band(...)</code></td><td>ビット積</td></tr>
|
||||||
|
<tr><td><code>bit32.bor(...)</code></td><td>ビット和</td></tr>
|
||||||
|
<tr><td><code>bit32.bxor(...)</code></td><td>排他的論理和</td></tr>
|
||||||
|
<tr><td><code>bit32.bnot(x)</code></td><td>ビット反転</td></tr>
|
||||||
|
<tr><td><code>bit32.lshift(x, n)</code> / <code>bit32.rshift(x, n)</code></td><td>左 / 右シフト</td></tr>
|
||||||
|
<tr><td><code>bit32.arshift(x, n)</code></td><td>算術右シフト</td></tr>
|
||||||
|
<tr><td><code>bit32.extract(n, f [, w])</code></td><td>ビット列の取り出し</td></tr>
|
||||||
|
<tr><td><code>bit32.replace(n, v, f [, w])</code></td><td>ビット列の置き換え</td></tr>
|
||||||
|
<tr><td><code>bit32.btest(...)</code></td><td>ビット積が 0 でないか</td></tr>
|
||||||
|
<tr><td><code>bit32.countlz(x)</code> / <code>bit32.countrz(x)</code></td><td>先頭 / 末尾の 0 ビット数</td></tr>
|
||||||
|
</table>
|
||||||
|
|
||||||
|
<div class="pager">
|
||||||
|
<a href="lua-basics.html">← Lua の基礎</a>
|
||||||
|
<a href="globals.html">グローバル変数 →</a>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
</main>
|
||||||
|
<script src="assets/nav.js"></script>
|
||||||
|
</body>
|
||||||
|
</html>
|
||||||
+289
-2
@@ -22,6 +22,7 @@ local mapSize = tonumber(arg[2])
|
|||||||
local workEventName = arg[3]
|
local workEventName = arg[3]
|
||||||
local doneEventName = arg[4]
|
local doneEventName = arg[4]
|
||||||
local shimPath = arg[5]
|
local shimPath = arg[5]
|
||||||
|
local stringParamsCap = tonumber(arg[6])
|
||||||
|
|
||||||
local hMap = k32.OpenFileMappingA(FILE_MAP_ALL_ACCESS, 0, mapName)
|
local hMap = k32.OpenFileMappingA(FILE_MAP_ALL_ACCESS, 0, mapName)
|
||||||
assert(hMap ~= nil, "OpenFileMapping failed")
|
assert(hMap ~= nil, "OpenFileMapping failed")
|
||||||
@@ -46,15 +47,28 @@ local OFF_ERRORLEN = 7
|
|||||||
local OFF_CB_FRAME = 8
|
local OFF_CB_FRAME = 8
|
||||||
local OFF_CB_TAGLEN = 9
|
local OFF_CB_TAGLEN = 9
|
||||||
local OFF_CB_FOUND = 10
|
local OFF_CB_FOUND = 10
|
||||||
|
local OFF_CB_KIND = 11
|
||||||
|
local OFF_LOAD_RESULT_W = 12
|
||||||
|
local OFF_LOAD_RESULT_H = 13
|
||||||
|
local OFF_STRING_PARAMS_LEN = 14
|
||||||
local SCRIPT_OFFSET = 64 + 64 * 8
|
local SCRIPT_OFFSET = 64 + 64 * 8
|
||||||
local ERROR_OFFSET = SCRIPT_OFFSET + 128 * 1024
|
local ERROR_OFFSET = SCRIPT_OFFSET + 128 * 1024
|
||||||
local CB_TAG_OFFSET = ERROR_OFFSET + 4 * 1024
|
local CB_TAG_OFFSET = ERROR_OFFSET + 4 * 1024
|
||||||
local CB_TAG_MAX = 256
|
local CB_TAG_MAX = 4096
|
||||||
local CB_RESULT_OFFSET = CB_TAG_OFFSET + CB_TAG_MAX
|
local CB_RESULT_OFFSET = CB_TAG_OFFSET + CB_TAG_MAX
|
||||||
local PIXEL_OFFSET = CB_RESULT_OFFSET + 8 * 8
|
local STRING_PARAMS_OFFSET = CB_RESULT_OFFSET + 8 * 8
|
||||||
|
local PIXEL_OFFSET = STRING_PARAMS_OFFSET + stringParamsCap
|
||||||
local FIRST_WRITABLE = 8
|
local FIRST_WRITABLE = 8
|
||||||
local LAST_WRITABLE = 25
|
local LAST_WRITABLE = 25
|
||||||
local STATUS_CALLBACK = 3
|
local STATUS_CALLBACK = 3
|
||||||
|
local CB_KIND_GETOBJECT = 0
|
||||||
|
local CB_KIND_LOADFIGURE = 1
|
||||||
|
local CB_KIND_EFFECT = 2
|
||||||
|
local CB_KIND_DRAW = 3
|
||||||
|
local CB_KIND_DRAWPOLY = 4
|
||||||
|
local CB_KIND_LOADTEXT = 5
|
||||||
|
local CB_KIND_LOADIMAGE = 6
|
||||||
|
local CB_KIND_LOADMOVIE = 7
|
||||||
|
|
||||||
assert(loadfile(shimPath))()
|
assert(loadfile(shimPath))()
|
||||||
|
|
||||||
@@ -67,8 +81,24 @@ end
|
|||||||
local width, height = 0, 0
|
local width, height = 0, 0
|
||||||
local pixels = ffi.cast("uint8_t*", base + PIXEL_OFFSET)
|
local pixels = ffi.cast("uint8_t*", base + PIXEL_OFFSET)
|
||||||
local cbResult = ffi.cast("double*", base + CB_RESULT_OFFSET)
|
local cbResult = ffi.cast("double*", base + CB_RESULT_OFFSET)
|
||||||
|
local cbTagD = ffi.cast("double*", base + CB_TAG_OFFSET)
|
||||||
|
local pixelCapacity = mapSize - PIXEL_OFFSET
|
||||||
|
local buffers = {}
|
||||||
|
local options = {}
|
||||||
|
local pixeloptions = {}
|
||||||
local dirty = false
|
local dirty = false
|
||||||
|
|
||||||
|
local function bufferKind(id)
|
||||||
|
local c = id:match("^%s*(.)")
|
||||||
|
if not c then return nil end
|
||||||
|
c = c:lower()
|
||||||
|
if c == "c" then
|
||||||
|
local name = id:match(":%s*(.-)%s*$")
|
||||||
|
return "c", name and ("c:" .. name) or "c"
|
||||||
|
end
|
||||||
|
return c, c
|
||||||
|
end
|
||||||
|
|
||||||
local obj = {}
|
local obj = {}
|
||||||
local scene = {}
|
local scene = {}
|
||||||
local ymm4 = {}
|
local ymm4 = {}
|
||||||
@@ -150,6 +180,243 @@ function obj.rand(a, b, seed, frame)
|
|||||||
return aviutl_rand(a or 0, b or 0, seed or 0, frame or obj.frame or 0)
|
return aviutl_rand(a or 0, b or 0, seed or 0, frame or obj.frame or 0)
|
||||||
end
|
end
|
||||||
|
|
||||||
|
local font = { family = "", size = 34, bold = false, italic = false, color = 0xFFFFFF }
|
||||||
|
|
||||||
|
function obj.setfont(name, size, style, col1)
|
||||||
|
if name ~= nil then font.family = tostring(name) end
|
||||||
|
if size ~= nil then font.size = size end
|
||||||
|
if style ~= nil then
|
||||||
|
local s = math.floor(style)
|
||||||
|
font.bold = (s % 2) == 1
|
||||||
|
font.italic = (math.floor(s / 2) % 2) == 1
|
||||||
|
end
|
||||||
|
if col1 ~= nil then font.color = col1 end
|
||||||
|
end
|
||||||
|
|
||||||
|
local function applyLoadResult()
|
||||||
|
local newW = i32[OFF_LOAD_RESULT_W]
|
||||||
|
local newH = i32[OFF_LOAD_RESULT_H]
|
||||||
|
if newW > 0 and newH > 0 then
|
||||||
|
width = newW
|
||||||
|
height = newH
|
||||||
|
i32[OFF_WIDTH] = newW
|
||||||
|
i32[OFF_HEIGHT] = newH
|
||||||
|
dirty = true
|
||||||
|
obj.w = newW; obj.h = newH
|
||||||
|
obj.hw = newW / 2; obj.hh = newH / 2
|
||||||
|
obj.cx = newW / 2; obj.cy = newH / 2
|
||||||
|
obj.cz = 0
|
||||||
|
obj.diagonal = math.sqrt(newW * newW + newH * newH)
|
||||||
|
end
|
||||||
|
end
|
||||||
|
|
||||||
|
local function loadFigure(name, color, size, lineWidth, aspect)
|
||||||
|
local nameBytes = tostring(name or "")
|
||||||
|
local len = #nameBytes
|
||||||
|
if len > CB_TAG_MAX then len = CB_TAG_MAX end
|
||||||
|
ffi.copy(base + CB_TAG_OFFSET, nameBytes, len)
|
||||||
|
i32[OFF_CB_TAGLEN] = len
|
||||||
|
i32[OFF_CB_KIND] = CB_KIND_LOADFIGURE
|
||||||
|
cbResult[0] = color or 0
|
||||||
|
cbResult[1] = size or 100
|
||||||
|
cbResult[2] = lineWidth or 0
|
||||||
|
cbResult[3] = aspect or 0
|
||||||
|
i32[OFF_STATUS] = STATUS_CALLBACK
|
||||||
|
k32.SetEvent(doneEvent)
|
||||||
|
k32.WaitForSingleObject(workEvent, INFINITE)
|
||||||
|
applyLoadResult()
|
||||||
|
end
|
||||||
|
|
||||||
|
local function loadText(str)
|
||||||
|
local payload = font.family .. "\0" .. tostring(str or "")
|
||||||
|
local len = #payload
|
||||||
|
if len > CB_TAG_MAX then len = CB_TAG_MAX end
|
||||||
|
ffi.copy(base + CB_TAG_OFFSET, payload, len)
|
||||||
|
i32[OFF_CB_TAGLEN] = len
|
||||||
|
i32[OFF_CB_KIND] = CB_KIND_LOADTEXT
|
||||||
|
cbResult[0] = font.size
|
||||||
|
cbResult[1] = font.bold and 1 or 0
|
||||||
|
cbResult[2] = font.italic and 1 or 0
|
||||||
|
cbResult[3] = font.color
|
||||||
|
i32[OFF_STATUS] = STATUS_CALLBACK
|
||||||
|
k32.SetEvent(doneEvent)
|
||||||
|
k32.WaitForSingleObject(workEvent, INFINITE)
|
||||||
|
applyLoadResult()
|
||||||
|
end
|
||||||
|
|
||||||
|
local function loadImage(path)
|
||||||
|
local payload = tostring(path or "")
|
||||||
|
local len = #payload
|
||||||
|
if len > CB_TAG_MAX then len = CB_TAG_MAX end
|
||||||
|
ffi.copy(base + CB_TAG_OFFSET, payload, len)
|
||||||
|
i32[OFF_CB_TAGLEN] = len
|
||||||
|
i32[OFF_CB_KIND] = CB_KIND_LOADIMAGE
|
||||||
|
i32[OFF_STATUS] = STATUS_CALLBACK
|
||||||
|
k32.SetEvent(doneEvent)
|
||||||
|
k32.WaitForSingleObject(workEvent, INFINITE)
|
||||||
|
applyLoadResult()
|
||||||
|
end
|
||||||
|
|
||||||
|
local function loadMovie(path, time)
|
||||||
|
local payload = tostring(path or "")
|
||||||
|
local len = #payload
|
||||||
|
if len > CB_TAG_MAX then len = CB_TAG_MAX end
|
||||||
|
ffi.copy(base + CB_TAG_OFFSET, payload, len)
|
||||||
|
i32[OFF_CB_TAGLEN] = len
|
||||||
|
i32[OFF_CB_KIND] = CB_KIND_LOADMOVIE
|
||||||
|
cbResult[0] = time or obj.time or 0
|
||||||
|
i32[OFF_STATUS] = STATUS_CALLBACK
|
||||||
|
k32.SetEvent(doneEvent)
|
||||||
|
k32.WaitForSingleObject(workEvent, INFINITE)
|
||||||
|
applyLoadResult()
|
||||||
|
end
|
||||||
|
|
||||||
|
function obj.load(kind, ...)
|
||||||
|
if kind == "figure" then
|
||||||
|
loadFigure(...)
|
||||||
|
elseif kind == "text" then
|
||||||
|
loadText(...)
|
||||||
|
elseif kind == "image" then
|
||||||
|
loadImage(...)
|
||||||
|
elseif kind == "movie" then
|
||||||
|
loadMovie(...)
|
||||||
|
end
|
||||||
|
end
|
||||||
|
|
||||||
|
function obj.effect(name, ...)
|
||||||
|
if type(name) ~= "string" then return end
|
||||||
|
local args = { ... }
|
||||||
|
local n = select("#", ...)
|
||||||
|
local parts = { name }
|
||||||
|
local pos = #name + 1
|
||||||
|
for i = 1, n - 1, 2 do
|
||||||
|
local k = tostring(args[i])
|
||||||
|
local v = args[i + 1]
|
||||||
|
local encoded
|
||||||
|
local vt = type(v)
|
||||||
|
if vt == "number" then
|
||||||
|
encoded = "n" .. string.format("%.17g", v)
|
||||||
|
elseif vt == "boolean" then
|
||||||
|
encoded = v and "b1" or "b0"
|
||||||
|
else
|
||||||
|
encoded = "s" .. tostring(v)
|
||||||
|
end
|
||||||
|
local needed = 2 + #k + #encoded
|
||||||
|
if pos + needed > CB_TAG_MAX then break end
|
||||||
|
parts[#parts + 1] = k
|
||||||
|
parts[#parts + 1] = encoded
|
||||||
|
pos = pos + needed
|
||||||
|
end
|
||||||
|
local payload = table.concat(parts, "\0")
|
||||||
|
local len = #payload
|
||||||
|
if len > CB_TAG_MAX then len = CB_TAG_MAX end
|
||||||
|
ffi.copy(base + CB_TAG_OFFSET, payload, len)
|
||||||
|
i32[OFF_CB_TAGLEN] = len
|
||||||
|
i32[OFF_CB_KIND] = CB_KIND_EFFECT
|
||||||
|
i32[OFF_STATUS] = STATUS_CALLBACK
|
||||||
|
k32.SetEvent(doneEvent)
|
||||||
|
k32.WaitForSingleObject(workEvent, INFINITE)
|
||||||
|
end
|
||||||
|
|
||||||
|
function obj.draw(ox, oy, oz, zoom, alpha, aspect)
|
||||||
|
cbResult[0] = ox or 0
|
||||||
|
cbResult[1] = oy or 0
|
||||||
|
cbResult[2] = oz or 0
|
||||||
|
cbResult[3] = zoom or 1
|
||||||
|
cbResult[4] = alpha or 1
|
||||||
|
cbResult[5] = aspect or 0
|
||||||
|
cbResult[6] = options.antialias or 1
|
||||||
|
i32[OFF_CB_KIND] = CB_KIND_DRAW
|
||||||
|
i32[OFF_STATUS] = STATUS_CALLBACK
|
||||||
|
k32.SetEvent(doneEvent)
|
||||||
|
k32.WaitForSingleObject(workEvent, INFINITE)
|
||||||
|
end
|
||||||
|
|
||||||
|
function obj.drawpoly(...)
|
||||||
|
local n = select("#", ...)
|
||||||
|
if n < 12 then return end
|
||||||
|
local a = { ... }
|
||||||
|
for i = 0, 11 do cbTagD[i] = a[i + 1] or 0 end
|
||||||
|
if n >= 20 then
|
||||||
|
for i = 0, 7 do cbTagD[12 + i] = a[13 + i] or 0 end
|
||||||
|
else
|
||||||
|
cbTagD[12] = 0; cbTagD[13] = 0
|
||||||
|
cbTagD[14] = width; cbTagD[15] = 0
|
||||||
|
cbTagD[16] = width; cbTagD[17] = height
|
||||||
|
cbTagD[18] = 0; cbTagD[19] = height
|
||||||
|
end
|
||||||
|
local alpha = 1
|
||||||
|
if n == 13 then
|
||||||
|
alpha = a[13] or 1
|
||||||
|
elseif n >= 21 then
|
||||||
|
alpha = a[21] or 1
|
||||||
|
end
|
||||||
|
cbTagD[20] = alpha
|
||||||
|
cbTagD[21] = options.antialias or 1
|
||||||
|
i32[OFF_CB_KIND] = CB_KIND_DRAWPOLY
|
||||||
|
i32[OFF_STATUS] = STATUS_CALLBACK
|
||||||
|
k32.SetEvent(doneEvent)
|
||||||
|
k32.WaitForSingleObject(workEvent, INFINITE)
|
||||||
|
end
|
||||||
|
|
||||||
|
function obj.getvalue(target)
|
||||||
|
if type(target) ~= "string" then return 0 end
|
||||||
|
local v = obj[target]
|
||||||
|
if type(v) == "number" then return v end
|
||||||
|
return 0
|
||||||
|
end
|
||||||
|
|
||||||
|
function obj.setoption(name, value)
|
||||||
|
if type(name) ~= "string" then return end
|
||||||
|
if value == nil then value = true end
|
||||||
|
options[name] = value
|
||||||
|
end
|
||||||
|
|
||||||
|
function obj.getoption(name)
|
||||||
|
if type(name) ~= "string" then return 0 end
|
||||||
|
local v = options[name]
|
||||||
|
if v == nil then return 0 end
|
||||||
|
return v
|
||||||
|
end
|
||||||
|
|
||||||
|
function obj.pixeloption(name, value)
|
||||||
|
if type(name) ~= "string" then return end
|
||||||
|
if value == nil then value = true end
|
||||||
|
pixeloptions[name] = value
|
||||||
|
end
|
||||||
|
|
||||||
|
function obj.copybuffer(dst, src)
|
||||||
|
if type(dst) ~= "string" or type(src) ~= "string" then return end
|
||||||
|
local sk, skey = bufferKind(src)
|
||||||
|
local data, w, h
|
||||||
|
if sk == "o" then
|
||||||
|
data = ffi.string(pixels, width * height * 4)
|
||||||
|
w = width; h = height
|
||||||
|
elseif sk == "t" or sk == "c" then
|
||||||
|
local b = buffers[skey]
|
||||||
|
if not b then return end
|
||||||
|
data, w, h = b.data, b.w, b.h
|
||||||
|
else
|
||||||
|
return
|
||||||
|
end
|
||||||
|
local dk, dkey = bufferKind(dst)
|
||||||
|
if dk == "o" then
|
||||||
|
local need = w * h * 4
|
||||||
|
if need > pixelCapacity then return end
|
||||||
|
ffi.copy(pixels, data, need)
|
||||||
|
width = w; height = h
|
||||||
|
i32[OFF_WIDTH] = w; i32[OFF_HEIGHT] = h
|
||||||
|
dirty = true
|
||||||
|
obj.w = w; obj.h = h
|
||||||
|
obj.hw = w / 2; obj.hh = h / 2
|
||||||
|
obj.cx = w / 2; obj.cy = h / 2
|
||||||
|
obj.cz = 0
|
||||||
|
obj.diagonal = math.sqrt(w * w + h * h)
|
||||||
|
elseif dk == "t" or dk == "c" then
|
||||||
|
buffers[dkey] = { data = data, w = w, h = h }
|
||||||
|
end
|
||||||
|
end
|
||||||
|
|
||||||
local cacheTag, cacheFrame, cacheFound
|
local cacheTag, cacheFrame, cacheFound
|
||||||
local cacheExist, cacheX, cacheY, cacheZ, cacheZoom, cacheRz, cacheAlpha, cacheLayer
|
local cacheExist, cacheX, cacheY, cacheZ, cacheZoom, cacheRz, cacheAlpha, cacheLayer
|
||||||
|
|
||||||
@@ -176,6 +443,7 @@ function obj.getobject(tag, frame)
|
|||||||
ffi.copy(base + CB_TAG_OFFSET, tag, len)
|
ffi.copy(base + CB_TAG_OFFSET, tag, len)
|
||||||
i32[OFF_CB_TAGLEN] = len
|
i32[OFF_CB_TAGLEN] = len
|
||||||
i32[OFF_CB_FRAME] = frame
|
i32[OFF_CB_FRAME] = frame
|
||||||
|
i32[OFF_CB_KIND] = CB_KIND_GETOBJECT
|
||||||
i32[OFF_STATUS] = STATUS_CALLBACK
|
i32[OFF_STATUS] = STATUS_CALLBACK
|
||||||
k32.SetEvent(doneEvent)
|
k32.SetEvent(doneEvent)
|
||||||
k32.WaitForSingleObject(workEvent, INFINITE)
|
k32.WaitForSingleObject(workEvent, INFINITE)
|
||||||
@@ -218,6 +486,7 @@ local function loadFields()
|
|||||||
obj.rx = f64[20]; obj.ry = f64[21]; obj.rz = f64[22]
|
obj.rx = f64[20]; obj.ry = f64[21]; obj.rz = f64[22]
|
||||||
obj.rxr = f64[23]; obj.ryr = f64[24]; obj.rzr = f64[25]
|
obj.rxr = f64[23]; obj.ryr = f64[24]; obj.rzr = f64[25]
|
||||||
obj.track0 = f64[26]; obj.track1 = f64[27]; obj.track2 = f64[28]; obj.track3 = f64[29]
|
obj.track0 = f64[26]; obj.track1 = f64[27]; obj.track2 = f64[28]; obj.track3 = f64[29]
|
||||||
|
obj.slider0 = f64[58]; obj.slider1 = f64[59]; obj.slider2 = f64[60]; obj.slider3 = f64[61]
|
||||||
obj.time = f64[30]; obj.frame = f64[31]; obj.totalframe = f64[32]; obj.totaltime = f64[33]
|
obj.time = f64[30]; obj.frame = f64[31]; obj.totalframe = f64[32]; obj.totaltime = f64[33]
|
||||||
obj.t = f64[34]; obj.framerate = f64[35]; obj.layer = f64[36]; obj.index = f64[37]; obj.num = f64[38]
|
obj.t = f64[34]; obj.framerate = f64[35]; obj.layer = f64[36]; obj.index = f64[37]; obj.num = f64[38]
|
||||||
scene.width = f64[39]; scene.height = f64[40]; scene.cx = f64[41]; scene.cy = f64[42]
|
scene.width = f64[39]; scene.height = f64[40]; scene.cx = f64[41]; scene.cy = f64[42]
|
||||||
@@ -231,6 +500,20 @@ local function loadFields()
|
|||||||
sandbox.color = (f64[57] >= 0) and f64[57] or nil
|
sandbox.color = (f64[57] >= 0) and f64[57] or nil
|
||||||
end
|
end
|
||||||
|
|
||||||
|
local function loadStringParams()
|
||||||
|
if i32[OFF_STRING_PARAMS_LEN] <= 0 then return end
|
||||||
|
local p = base + STRING_PARAMS_OFFSET
|
||||||
|
local count = ffi.cast("int32_t*", p)[0]
|
||||||
|
local pos = 4
|
||||||
|
for _ = 1, count do
|
||||||
|
local nameLen = ffi.cast("int32_t*", p + pos)[0]; pos = pos + 4
|
||||||
|
local name = ffi.string(p + pos, nameLen); pos = pos + nameLen
|
||||||
|
local valLen = ffi.cast("int32_t*", p + pos)[0]; pos = pos + 4
|
||||||
|
local val = ffi.string(p + pos, valLen); pos = pos + valLen
|
||||||
|
obj[name] = val
|
||||||
|
end
|
||||||
|
end
|
||||||
|
|
||||||
local function storeFields()
|
local function storeFields()
|
||||||
for i = FIRST_WRITABLE, LAST_WRITABLE do
|
for i = FIRST_WRITABLE, LAST_WRITABLE do
|
||||||
local key
|
local key
|
||||||
@@ -269,7 +552,11 @@ while true do
|
|||||||
|
|
||||||
if compiledChunk and code == compiledCode then
|
if compiledChunk and code == compiledCode then
|
||||||
loadFields()
|
loadFields()
|
||||||
|
loadStringParams()
|
||||||
cacheTag = nil
|
cacheTag = nil
|
||||||
|
for k in pairs(options) do options[k] = nil end
|
||||||
|
for k in pairs(pixeloptions) do pixeloptions[k] = nil end
|
||||||
|
font.family = ""; font.size = 34; font.bold = false; font.italic = false; font.color = 0xFFFFFF
|
||||||
math.randomseed(f64[31])
|
math.randomseed(f64[31])
|
||||||
setfenv(compiledChunk, sandbox)
|
setfenv(compiledChunk, sandbox)
|
||||||
local ok, err = pcall(compiledChunk)
|
local ok, err = pcall(compiledChunk)
|
||||||
|
|||||||
新しいイシューから参照
ユーザーをブロックする