コミットを比較

..
42 コミット
作成者 SHA1 メッセージ 日付
routersys 573234d727 nativeをリリースに同梱
リリース / build-and-release (workflow_dispatch) Actions がタグ v1.3.0 のコミットから作成しました
2026-06-27 12:59:28 +09:00
routersys 69a5f26260 テスト専用luaを配布から除外し必要な4ファイルのみ同梱 2026-06-27 12:40:33 +09:00
routersys ed4601a03a 実行エンジンの自動振り分け・高速化・制約をREADMEに追記 2026-06-27 12:34:49 +09:00
routersys 960569177c v1.3.0のリリースノートを記載 2026-06-27 12:34:48 +09:00
routersys 2831ea25ee バージョンを1.3.0へ更新 2026-06-27 12:34:48 +09:00
routersys a2caa2e910 ネイティブ実行でmath.randomseed(frame)を毎フレーム適用し決定論を維持 2026-06-27 12:34:47 +09:00
routersys 26bc21681f オートルーティングのテストを追加 2026-06-27 12:23:09 +09:00
routersys 7edbe189a2 getpixeldata往復テストを追加 2026-06-27 12:23:08 +09:00
routersys e8ae7d1189 自動振り分けを採用しネイティブ未配備時は一度だけ警告(サイレントフォールバック解消) 2026-06-27 12:23:08 +09:00
routersys ce7007c42e ピクセルAPI使用スクリプトをネイティブへ自動振り分け(ResolveAuto) 2026-06-27 12:23:07 +09:00
routersys f10f31ef2b ワーカーにgetpixeldata(PixelDataProxy相当)を実装 2026-06-27 12:23:07 +09:00
routersys 4a5043eb3a テストプロジェクトの参照を追加 2026-06-27 10:07:47 +09:00
routersys 640c9f5347 ネイティブワーカー往復テスト(変形/ピクセル/タイムアウト/エラー)を追加 2026-06-27 09:57:19 +09:00
routersys b339d60bd7 vendored nativeをリポジトリ直下へ集約し両プロジェクトから参照 2026-06-27 09:57:18 +09:00
routersys f94e0ea849 nativeランタイムをプラグイン出力へ同梱・配備(csproj) 2026-06-27 09:56:57 +09:00
routersys 729ba355d9 --!nativeをLuaJITワーカーへ振り分けるよう配線 2026-06-27 09:56:56 +09:00
routersys 67697930b7 常駐ワーカースクリプト(obj/scene/ymm4/pixel,サンドボックス)を追加 2026-06-27 09:56:56 +09:00
routersys f929c1a83a コンテキスト⇄ネイティブフィールド配列の写像を追加 2026-06-27 09:56:56 +09:00
routersys 6ee2784d6a 常駐LuaJITワーカー管理(別プロセス/共有メモリ/ハードキル)を追加 2026-06-27 09:56:55 +09:00
routersys 03db2d4faf ネイティブ実行の共有メモリプロトコルを定義 2026-06-27 09:56:55 +09:00
routersys fda89f726b 共有メモリでのBGRA授受の検証を追加 2026-06-27 09:33:34 +09:00
routersys d22035111a 共有メモリBGRA処理ワーカー(PoC)を追加 2026-06-27 09:33:34 +09:00
routersys 28bc23cd49 JIT無限ループのハードキル・タイムアウト検証を追加 2026-06-27 09:33:33 +09:00
routersys 796051015c animのMoonSharp×LuaJIT実機等価テストを追加 2026-06-27 09:33:33 +09:00
routersys 7184a89330 bit32のC#×LuaJIT実機等価テストを追加 2026-06-27 09:33:33 +09:00
routersys add78d673a クロスエンジン評価ランナーを追加 2026-06-27 09:33:33 +09:00
routersys f8522ad816 LuaJIT用 bit32/rawlen/anim シムを追加 2026-06-27 09:33:32 +09:00
routersys 45bee472e4 LuaJIT 2.1 x64バイナリを同梱(テストfixture) 2026-06-27 09:33:32 +09:00
routersys be411b596d animユーティリティの契約テストを追加 2026-06-27 09:33:14 +09:00
routersys 21741fc620 rawlen等の基本関数の挙動固定テストを追加 2026-06-27 09:33:14 +09:00
routersys 05ffdcc9d3 Bit32の正しさと安全域でのMoonSharp一致テストを追加 2026-06-27 09:33:13 +09:00
routersys 1f32ec59ce MoonSharpBit32のMoonSharp等価テストを追加 2026-06-27 09:33:13 +09:00
routersys 6af9153f50 ルータのテストを追加 2026-06-27 09:33:13 +09:00
routersys 4528748493 テスト用LuaJITレーン(別プロセス駆動)ヘルパを追加 2026-06-27 09:33:13 +09:00
routersys 3c0e13c85d テスト用MoonSharpレーンヘルパを追加 2026-06-27 09:33:13 +09:00
routersys 66786bfc98 テストプロジェクトLuaScript.Testsを追加 2026-06-27 09:33:12 +09:00
routersys 10dbb022bc 正しいLua5.2準拠のbit32実装を追加 2026-06-27 09:32:53 +09:00
routersys b0e47b82f5 MoonSharp挙動を完全再現するbit32実装(互換層)を追加 2026-06-27 09:32:53 +09:00
routersys 9e3381f0d0 エンジン振り分けディレクティブ(--!native等)を解析するルータを追加 2026-06-27 09:32:53 +09:00
routersys 6e29bf08b0 毎フレーム処理のアロケーションを削減し動画出力を高速化 2026-06-26 20:25:58 +09:00
routersys 21615a5461 マージ 2026-06-25 15:17:11 +09:00
routersys bc3bd511df Create CNAME 2026-06-25 07:46:55 +09:00
35個のファイルの変更、2953行の追加、189行の削除

検索条件に一致するファイルはありません

+55 -36
ファイルの表示
@@ -1,54 +1,73 @@
# v1.2.0 - Lua スクリプト for YMM4
# v1.3.0 - Lua スクリプト for YMM4
他オブジェクトの情報を任意のフレーム時点で取得できるようにしたリリースです。
発射元が動いても弾の発射位置を固定するなど、フレームを指定した参照が可能になりました。
ピクセル操作スクリプトを**大幅に高速化**したリリースです。
`obj.getpixel` / `obj.setpixel` / `obj.getpixeldata` を使うスクリプトは、同梱した高速
ランタイム(LuaJIT)で自動的に実行されるようになり、内部計測では**最大で数十倍**
(例:1920×1080 のフルフレーム加工で約 41 倍、小さめの画像では 70 倍前後)の
高速化を確認しています。
---
## 新機能
## 新機能・改善
### 1. obj.getobject へのフレーム指定引数の追加
### 1. ピクセル操作スクリプトの自動高速化
`obj.getobject(tag, frame)` の第2引数 `frame` を追加しました。指定したタイムライン
フレーム時点での対象オブジェクトの座標・回転・拡大率・不透明度を取得できます。
`frame` を省略した場合は従来どおり現在フレームの値を返します。
ピクセル操作 API(`obj.getpixel` / `obj.setpixel` / `obj.getpixeldata`)を含むスクリプトは、
**特別な記述なしで自動的に高速ランタイム(ネイティブ実行)へ振り分け**られます。
変形のみ(座標・回転・拡縮・不透明度)のスクリプトは従来どおりの実行系で動作します
(変形のみの処理は元々十分高速なため、速度差はありません)。
弾の発射フレーム(弾アイテムの開始フレーム)は `timelineframe - frame` で求まるため、
そのフレームの発射元座標を取得すれば、発射元が動いても弾の原点を発射位置に固定できます。
ネイティブ実行は**専用の別プロセス**で行われ、ピクセルバッファは共有メモリ経由で
受け渡されます。スクリプトが無限ループに陥っても、**5 秒のタイムアウトで強制終了**
され、本体が固まることはありません(終了後は自動的に復帰します)。
```lua
local fire = timelineframe - frame
local src = obj.getobject("routersys", fire)
if src then
obj.x = src.x
obj.y = src.y
end
```
### 2. 実行エンジンを指定するディレクティブ
取得値は対象アイテム自身の座標・回転・拡大率であり、グループ制御・カメラ制御による
変形は含みません。同じタグのアイテムが複数ある場合は、対象フレームで表示中のものを
優先して返します。
スクリプトの先頭行に次のディレクティブを書くことで、実行エンジンを明示指定できます。
- `--!native` … 高速ランタイム(LuaJIT)で実行
- `--!moonsharp` … 従来エンジン(MoonSharp)で実行
- 記述なし … ピクセル操作を含む場合は自動的にネイティブ、それ以外は従来エンジン
### 3. bit32 の Lua 5.2 準拠化(ネイティブ実行時)
ネイティブ実行時の `bit32` ライブラリは、正しい Lua 5.2 の挙動になりました。
実用域(0〜2^31 未満の値、0〜31 のシフト量)では従来と完全に一致するため、
通常のスクリプトの見た目は変わりません。`bit32.lshift(1, 32)` のような範囲外の
特殊なケースのみ結果が変わります(ネイティブ=正しい 0、従来=1)。
### 4. 変形処理のアロケーション削減
毎フレームの実行で発生していた一時オブジェクトの確保を削減し、シーンオブジェクトの
解決を遅延化しました。長時間の出力における GC 負荷を軽減します。
---
## 注意事項(ネイティブ実行時の制約)
- **`obj.getobject` はネイティブ実行では使用できません**(常に `nil` を返します)。
他オブジェクトの参照を行うスクリプトには `--!native` を付けないでください
(ピクセル操作と併用する場合は `--!moonsharp` を明示してください)。
- `math.random` は両エンジンとも「フレーム番号でシードし直す決定論的乱数」ですが、
乱数列の実装が異なるため、エンジンをまたぐと同じシードでも値が変わります。
エンジンに依存しない乱数が必要な場合は `anim.rand(min, max, seed)` を使用してください。
- ネイティブ実行は最初のピクセルアクセス前から GPU→CPU の画像転送を行います。
---
## 内部実装
### 2. 参照方式の統一(依存クエリの再評価)
他オブジェクトの値を「現在フレームで事前に算出したスナップショット」を比較する方式から、
「参照したオブジェクトを保持し、要求されたフレームで評価する」方式へ統一しました。
- 取得対象のアイテムを保持し、任意のフレームで評価する `SceneObjectResolver` を追加
- スクリプト実行中に行われた参照 `(タグ, フレーム)` を記録し、出力キャッシュの
再利用判定では記録した参照を再評価して一致を確認
これにより、任意フレームの参照に対しても決定論的かつキャッシュ整合性を保った
取得が可能になります。評価はすべて描画スレッド側で行い、スクリプト実行スレッドへは
数値のみを渡します。
- 同梱した LuaJIT を別プロセスで常駐させ、名前付き共有メモリとイベントで往復します。
タイムアウト時はプロセスを強制終了し、自動的に再起動します。
- ネイティブ側に `bit32`(正しい 5.2)・`rawlen`・`anim.*`(`rand` / `noise` を含む)・
`obj.getpixel` / `setpixel` / `getpixeldata` を実装し、従来エンジンとの**出力一致を
自動テストで検証**しています(2800 件超のクロスエンジン等価テストを追加)。
- ユーザースクリプトはサンドボックス環境で実行され、`io` / `os` / `ffi` / `require`
などは従来どおり利用できません。
---
## ドキュメント
## 同梱物
対応する 8 言語のスクリプト説明文に `frame` 引数の説明と発射位置を固定する例を
追記し、サンプル集ページにも同様の例を追加しました。
- 本プラグインには高速ランタイム(`luajit.exe` / `lua51.dll`)と実行スクリプトを同梱して
おり、プラグイン本体と同じ `native` フォルダーに配置されます(手動インストールは不要)。
+5
ファイルの表示
@@ -69,9 +69,14 @@ jobs:
$pkgName = "LuaScript_$version.ymme"
New-Item -ItemType Directory -Path "$stageRoot/docs" -Force | Out-Null
New-Item -ItemType Directory -Path "$stageRoot/native" -Force | Out-Null
Copy-Item "$outDir/LuaScript.dll" "$stageRoot/"
Copy-Item "$outDir/MoonSharp.Interpreter.dll" "$stageRoot/"
Copy-Item "$outDir/native/luajit.exe" "$stageRoot/native/"
Copy-Item "$outDir/native/lua51.dll" "$stageRoot/native/"
Copy-Item "$outDir/native/worker.lua" "$stageRoot/native/"
Copy-Item "$outDir/native/shim.lua" "$stageRoot/native/"
foreach ($lang in @("ar-sa", "en-us", "es-es", "id-id", "ko-kr", "zh-cn", "zh-tw")) {
$src = "$outDir/$lang"
+146
ファイルの表示
@@ -0,0 +1,146 @@
namespace LuaScript.Tests
{
public class AnimContractTests
{
private const int Precision = 9;
private readonly MoonSharpLane _lane = new();
private void Eq(double expected, string expression) =>
Assert.Equal(expected, _lane.Number(expression), Precision);
[Fact]
public void Constants()
{
Eq(Math.PI * 2d, "anim.tau");
Eq(Math.E, "anim.e");
Eq((1d + Math.Sqrt(5d)) / 2d, "anim.phi");
Eq(Math.Sqrt(2d), "anim.sqrt2");
}
[Fact]
public void LerpMapNormClamp()
{
Eq(5d, "anim.lerp(0,10,0.5)");
Eq(12.5d, "anim.lerp(10,20,0.25)");
Eq(50d, "anim.map(5,0,10,0,100)");
Eq(0.5d, "anim.norm(5,0,10)");
Eq(1d, "anim.clamp(5,0,1)");
Eq(0d, "anim.clamp(-1,0,1)");
Eq(0.5d, "anim.clamp(0.5,0,1)");
}
[Fact]
public void SmoothSteps()
{
Eq(0.5d, "anim.smoothstep(0,1,0.5)");
Eq(0d, "anim.smoothstep(0,1,0)");
Eq(1d, "anim.smoothstep(0,1,1)");
Eq(0.5d, "anim.smootherstep(0,1,0.5)");
}
[Fact]
public void WrapPingpong()
{
Eq(2d, "anim.wrap(7,0,5)");
Eq(4d, "anim.wrap(-1,0,5)");
Eq(3d, "anim.pingpong(7,5)");
Eq(3d, "anim.pingpong(3,5)");
}
[Fact]
public void Waves()
{
Eq(0.5d, "anim.oscillate(0,0,1,1)");
Eq(0d, "anim.triangle(0,1)");
Eq(0.5d, "anim.triangle(0.25,1)");
Eq(1d, "anim.triangle(0.5,1)");
Eq(0d, "anim.square(0.25,1)");
Eq(1d, "anim.square(0.5,1)");
}
[Fact]
public void Easings()
{
Eq(0.25d, "anim.ease_in(0.5)");
Eq(0.75d, "anim.ease_out(0.5)");
Eq(0.125d, "anim.ease_in_out(0.25)");
Eq(0.875d, "anim.ease_in_out(0.75)");
Eq(0d, "anim.back(0)");
Eq(1d, "anim.back(1)");
Eq(0d, "anim.elastic(0)");
Eq(1d, "anim.elastic(1)");
Eq(0d, "anim.bounce(0)");
}
[Fact]
public void Misc()
{
Eq(-1d, "anim.sign(-5)");
Eq(0d, "anim.sign(0)");
Eq(1d, "anim.sign(3)");
Eq(0.5d, "anim.duration(0.5,1)");
Eq(1d, "anim.duration(2,1)");
Eq(1d, "anim.delay(2,1)");
Eq(0d, "anim.delay(0.5,1)");
Eq(1d, "anim.step(0.5,0.6)");
Eq(0d, "anim.step(0.5,0.4)");
Eq(0.25d, "anim.fract(3.25)");
Eq(0.75d, "anim.fract(-0.25)");
}
[Fact]
public void Vectors()
{
Eq(5d, "anim.len(3,4)");
Eq(5d, "anim.dist(0,0,3,4)");
Eq(11d, "anim.dot(1,2,3,4)");
Eq(0d, "anim.bezier(0,0,1,2,3)");
Eq(3d, "anim.bezier(1,0,1,2,3)");
}
[Fact]
public void TupleFunctions()
{
var rgb = _lane.Tuple("anim.hsv_to_rgb(0,1,1)", 3);
Assert.Equal(255d, rgb[0], Precision);
Assert.Equal(0d, rgb[1], Precision);
Assert.Equal(0d, rgb[2], Precision);
var hsv = _lane.Tuple("anim.rgb_to_hsv(255,0,0)", 3);
Assert.Equal(0d, hsv[0], Precision);
Assert.Equal(1d, hsv[1], Precision);
Assert.Equal(1d, hsv[2], Precision);
var n = _lane.Tuple("anim.normalize(3,4)", 2);
Assert.Equal(0.6d, n[0], Precision);
Assert.Equal(0.8d, n[1], Precision);
var rot = _lane.Tuple("anim.rotate(1,0,90)", 2);
Assert.Equal(0d, rot[0], Precision);
Assert.Equal(1d, rot[1], Precision);
}
[Fact]
public void RandIsDeterministicAndBounded()
{
Assert.Equal(_lane.Number("anim.rand(5)"), _lane.Number("anim.rand(5)"));
Assert.NotEqual(_lane.Number("anim.rand(5)"), _lane.Number("anim.rand(6)"));
for (int seed = 0; seed < 50; seed++)
{
double r = _lane.Number($"anim.rand(10,20,{seed})");
Assert.InRange(r, 10d, 20d);
}
}
[Fact]
public void NoiseIsDeterministicAndBounded()
{
Assert.Equal(_lane.Number("anim.noise(1.5,2.5,0.5)"), _lane.Number("anim.noise(1.5,2.5,0.5)"));
for (double x = 0d; x < 5d; x += 0.37d)
{
double v = _lane.Number($"anim.noise({x.ToString(System.Globalization.CultureInfo.InvariantCulture)})");
Assert.InRange(v, 0d, 1d);
}
}
}
}
+113
ファイルの表示
@@ -0,0 +1,113 @@
using System.Collections.Generic;
using LuaScript.Compat;
namespace LuaScript.Tests
{
public class Bit32CleanTests
{
[Fact]
public void Correct_Lua52_Semantics()
{
Assert.Equal(0xFFFFFFFFu, Bit32.Band(4294967295d, 4294967295d));
Assert.Equal(0xFFFFFFFFu, Bit32.Bnot(0d));
Assert.Equal(2147483648u, Bit32.Lshift(1d, 31d));
Assert.Equal(0u, Bit32.Lshift(1d, 32d));
Assert.Equal(0u, Bit32.Lshift(1d, -1d));
Assert.Equal(1u, Bit32.Rshift(2147483648d, 31d));
Assert.Equal(3221225472u, Bit32.Arshift(2147483648d, 1d));
Assert.Equal(0xFFFFFFFFu, Bit32.Arshift(4294967295d, 40d));
Assert.Equal(2147483648u, Bit32.Lrotate(1d, -1d));
Assert.Equal(1u, Bit32.Lrotate(2147483648d, 1d));
}
[Fact]
public void Correct_Extract_Replace_AllowsFullRange()
{
Assert.Equal(1u, Bit32.Extract(4294967295d, 31, 1));
Assert.Equal(0xFFFFFFFFu, Bit32.Extract(4294967295d, 0, 32));
Assert.Equal(255u, Bit32.Extract(255d, 0, 8));
Assert.Equal(2147483648u, Bit32.Replace(0d, 1d, 31, 1));
}
[Theory]
[InlineData(32, 1)]
[InlineData(0, 33)]
[InlineData(-1, 1)]
[InlineData(0, 0)]
public void Extract_OutOfRange_Throws(int field, int width) =>
Assert.Throws<System.ArgumentException>(() => Bit32.Extract(1d, field, width));
public static readonly double[] SafeValues =
[
0d, 1d, 2d, 255d, 256d, 65535d, 65536d, 16777215d,
1073741824d, 2147483647d,
];
public static readonly int[] SafeShifts = [0, 1, 4, 8, 15, 16, 24, 31];
public static IEnumerable<object[]> SafeBinary()
{
foreach (var a in SafeValues)
foreach (var b in SafeValues)
yield return [a, b];
}
public static IEnumerable<object[]> SafeValueAndShift()
{
foreach (var a in SafeValues)
foreach (var n in SafeShifts)
yield return [a, n];
}
[Theory]
[MemberData(nameof(SafeBinary))]
public void Bitwise_MatchesMoonSharp_OnSafeDomain(double a, double b)
{
Assert.Equal(MoonSharpBit32.Band(a, b), Bit32.Band(a, b));
Assert.Equal(MoonSharpBit32.Bor(a, b), Bit32.Bor(a, b));
Assert.Equal(MoonSharpBit32.Bxor(a, b), Bit32.Bxor(a, b));
Assert.Equal(MoonSharpBit32.Btest(a, b), Bit32.Btest(a, b));
}
[Theory]
[MemberData(nameof(SafeValueAndShift))]
public void Shifts_MatchMoonSharp_OnSafeDomain(double a, int n)
{
Assert.Equal(MoonSharpBit32.Lshift(a, n), Bit32.Lshift(a, n));
Assert.Equal(MoonSharpBit32.Rshift(a, n), Bit32.Rshift(a, n));
Assert.Equal((double)MoonSharpBit32.Arshift(a, n), (double)Bit32.Arshift(a, n));
Assert.Equal(MoonSharpBit32.Lrotate(a, n), Bit32.Lrotate(a, n));
Assert.Equal(MoonSharpBit32.Rrotate(a, n), Bit32.Rrotate(a, n));
}
[Theory]
[InlineData(0, 1)]
[InlineData(0, 8)]
[InlineData(4, 4)]
[InlineData(8, 8)]
[InlineData(0, 16)]
[InlineData(15, 16)]
[InlineData(30, 1)]
public void Extract_MatchesMoonSharp_OnSafeDomain(int field, int width)
{
foreach (var a in SafeValues)
Assert.Equal(MoonSharpBit32.Extract(a, field, width), Bit32.Extract(a, field, width));
}
[Fact]
public void Replace_IsCorrectLua52_ShiftsReplacementIntoField()
{
Assert.Equal(0xF0u, Bit32.Replace(0d, 15d, 4, 4));
Assert.Equal(0x80000000u, Bit32.Replace(0d, 1d, 31, 1));
Assert.Equal(0xABCD0000u, Bit32.Replace(0d, 43981d, 16, 16));
}
[Fact]
public void Replace_DivergesFromMoonSharpBug_ForNonZeroField()
{
Assert.NotEqual((double)MoonSharpBit32.Replace(0d, 15d, 4, 4), (double)Bit32.Replace(0d, 15d, 4, 4));
Assert.Equal(0u, MoonSharpBit32.Replace(0d, 15d, 4, 4));
Assert.Equal(0xF0u, Bit32.Replace(0d, 15d, 4, 4));
}
}
}
+161
ファイルの表示
@@ -0,0 +1,161 @@
using System.Collections.Generic;
using System.Globalization;
using LuaScript.Compat;
using MoonSharp.Interpreter;
namespace LuaScript.Tests
{
public class Bit32EquivalenceTests
{
private static readonly Script Oracle = new(CoreModules.Basic | CoreModules.Math | CoreModules.Bit32);
private static double Eval(string expression) => Oracle.DoString("return " + expression).Number;
private static bool EvalBool(string expression) => Oracle.DoString("return " + expression).Boolean;
private static string Lit(double value) => value.ToString("R", CultureInfo.InvariantCulture);
public static readonly double[] RawInputs =
[
0d, 1d, 2d, 255d, 256d, 65535d, 65536d,
2147483647d, 2147483648d, 4294967295d,
4294967296d, 4294967301d,
-1d, -2d, -256d, -2147483648d,
];
public static readonly int[] Shifts =
[
0, 1, 4, 7, 8, 15, 16, 24, 31, 32, 33, 64,
-1, -4, -8, -16, -31, -32, -33,
];
public static IEnumerable<object[]> Unary()
{
foreach (var a in RawInputs)
yield return [a];
}
public static IEnumerable<object[]> Binary()
{
foreach (var a in RawInputs)
foreach (var b in RawInputs)
yield return [a, b];
}
public static IEnumerable<object[]> ValueAndShift()
{
foreach (var a in RawInputs)
foreach (var n in Shifts)
yield return [a, n];
}
[Theory]
[MemberData(nameof(Binary))]
public void Band(double a, double b) =>
Assert.Equal((double)MoonSharpBit32.Band(a, b), Eval($"bit32.band({Lit(a)},{Lit(b)})"));
[Theory]
[MemberData(nameof(Binary))]
public void Bor(double a, double b) =>
Assert.Equal((double)MoonSharpBit32.Bor(a, b), Eval($"bit32.bor({Lit(a)},{Lit(b)})"));
[Theory]
[MemberData(nameof(Binary))]
public void Bxor(double a, double b) =>
Assert.Equal((double)MoonSharpBit32.Bxor(a, b), Eval($"bit32.bxor({Lit(a)},{Lit(b)})"));
[Theory]
[MemberData(nameof(Binary))]
public void Btest(double a, double b) =>
Assert.Equal(MoonSharpBit32.Btest(a, b), EvalBool($"bit32.btest({Lit(a)},{Lit(b)})"));
[Theory]
[MemberData(nameof(Unary))]
public void Bnot(double a) =>
Assert.Equal((double)MoonSharpBit32.Bnot(a), Eval($"bit32.bnot({Lit(a)})"));
[Theory]
[MemberData(nameof(ValueAndShift))]
public void Lshift(double a, int n) =>
Assert.Equal((double)MoonSharpBit32.Lshift(a, n), Eval($"bit32.lshift({Lit(a)},{n})"));
[Theory]
[MemberData(nameof(ValueAndShift))]
public void Rshift(double a, int n) =>
Assert.Equal((double)MoonSharpBit32.Rshift(a, n), Eval($"bit32.rshift({Lit(a)},{n})"));
[Theory]
[MemberData(nameof(ValueAndShift))]
public void Arshift(double a, int n) =>
Assert.Equal((double)MoonSharpBit32.Arshift(a, n), Eval($"bit32.arshift({Lit(a)},{n})"));
[Theory]
[MemberData(nameof(ValueAndShift))]
public void Lrotate(double a, int n) =>
Assert.Equal((double)MoonSharpBit32.Lrotate(a, n), Eval($"bit32.lrotate({Lit(a)},{n})"));
[Theory]
[MemberData(nameof(ValueAndShift))]
public void Rrotate(double a, int n) =>
Assert.Equal((double)MoonSharpBit32.Rrotate(a, n), Eval($"bit32.rrotate({Lit(a)},{n})"));
[Theory]
[InlineData(0, 1)]
[InlineData(0, 8)]
[InlineData(4, 4)]
[InlineData(8, 8)]
[InlineData(0, 16)]
[InlineData(8, 16)]
[InlineData(0, 31)]
[InlineData(30, 1)]
[InlineData(15, 16)]
public void Extract(int field, int width)
{
foreach (var a in RawInputs)
Assert.Equal(
(double)MoonSharpBit32.Extract(a, field, width),
Eval($"bit32.extract({Lit(a)},{field},{width})"));
}
[Theory]
[InlineData(0, 1)]
[InlineData(0, 8)]
[InlineData(4, 4)]
[InlineData(8, 8)]
[InlineData(0, 16)]
[InlineData(8, 16)]
[InlineData(0, 31)]
[InlineData(30, 1)]
[InlineData(15, 16)]
public void Replace(int field, int width)
{
foreach (var a in RawInputs)
foreach (var v in RawInputs)
Assert.Equal(
(double)MoonSharpBit32.Replace(a, v, field, width),
Eval($"bit32.replace({Lit(a)},{Lit(v)},{field},{width})"));
}
[Theory]
[InlineData(31, 1)]
[InlineData(16, 16)]
[InlineData(0, 32)]
[InlineData(32, 0)]
public void Extract_OutOfRange_BothReject(int field, int width)
{
Assert.ThrowsAny<Exception>(() => MoonSharpBit32.Extract(1d, field, width));
Assert.ThrowsAny<ScriptRuntimeException>(() => Eval($"bit32.extract(1,{field},{width})"));
}
[Theory]
[InlineData(31, 1)]
[InlineData(16, 16)]
[InlineData(0, 32)]
[InlineData(32, 0)]
public void Replace_OutOfRange_BothReject(int field, int width)
{
Assert.ThrowsAny<Exception>(() => MoonSharpBit32.Replace(1d, 1d, field, width));
Assert.ThrowsAny<ScriptRuntimeException>(() => Eval($"bit32.replace(1,1,{field},{width})"));
}
}
}
+48
ファイルの表示
@@ -0,0 +1,48 @@
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
namespace LuaScript.Tests
{
internal sealed class LuaJitLane
{
private readonly string _nativeDir = Path.Combine(AppContext.BaseDirectory, "native");
public bool Available => File.Exists(Path.Combine(_nativeDir, "luajit.exe"));
public string[] Eval(IReadOnlyList<string> expressions)
{
string vectors = Path.GetTempFileName();
File.WriteAllLines(vectors, expressions);
try
{
var psi = new ProcessStartInfo
{
FileName = Path.Combine(_nativeDir, "luajit.exe"),
WorkingDirectory = _nativeDir,
RedirectStandardOutput = true,
RedirectStandardError = true,
UseShellExecute = false,
};
psi.ArgumentList.Add("runner.lua");
psi.ArgumentList.Add(Path.Combine(_nativeDir, "shim.lua"));
psi.ArgumentList.Add(vectors);
using var process = Process.Start(psi)
?? throw new InvalidOperationException("Failed to start luajit.exe");
string stdout = process.StandardOutput.ReadToEnd();
string stderr = process.StandardError.ReadToEnd();
process.WaitForExit();
if (process.ExitCode != 0)
throw new InvalidOperationException("luajit exited " + process.ExitCode + ": " + stderr);
return stdout.Replace("\r\n", "\n").Split('\n');
}
finally
{
File.Delete(vectors);
}
}
}
}
+35
ファイルの表示
@@ -0,0 +1,35 @@
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<TargetFramework>net10.0</TargetFramework>
<ImplicitUsings>enable</ImplicitUsings>
<Nullable>enable</Nullable>
<IsPackable>false</IsPackable>
</PropertyGroup>
<ItemGroup>
<PackageReference Include="coverlet.collector" Version="6.0.4" />
<PackageReference Include="Microsoft.NET.Test.Sdk" Version="17.14.1" />
<PackageReference Include="MoonSharp" Version="2.0.0" />
<PackageReference Include="xunit" Version="2.9.3" />
<PackageReference Include="xunit.runner.visualstudio" Version="3.1.4" />
</ItemGroup>
<ItemGroup>
<Using Include="Xunit" />
</ItemGroup>
<ItemGroup>
<None Include="..\native\**" CopyToOutputDirectory="PreserveNewest" LinkBase="native" />
</ItemGroup>
<ItemGroup>
<Compile Include="..\LuaScript\Compat\MoonSharpBit32.cs" Link="Linked\MoonSharpBit32.cs" />
<Compile Include="..\LuaScript\Compat\Bit32.cs" Link="Linked\Bit32.cs" />
<Compile Include="..\LuaScript\Engine\ScriptEngineKind.cs" Link="Linked\ScriptEngineKind.cs" />
<Compile Include="..\LuaScript\Engine\NativeProtocol.cs" Link="Linked\NativeProtocol.cs" />
<Compile Include="..\LuaScript\Engine\LuaJitWorker.cs" Link="Linked\LuaJitWorker.cs" />
<Compile Include="..\LuaScript\AnimTableRegistrar.cs" Link="Linked\AnimTableRegistrar.cs" />
</ItemGroup>
</Project>
+46
ファイルの表示
@@ -0,0 +1,46 @@
using LuaScript;
using MoonSharp.Interpreter;
namespace LuaScript.Tests
{
internal sealed class MoonSharpLane
{
private readonly Script _script;
public MoonSharpLane()
{
_script = new Script(
CoreModules.Basic |
CoreModules.Math |
CoreModules.String |
CoreModules.Table |
CoreModules.Bit32 |
CoreModules.TableIterators |
CoreModules.Metatables |
CoreModules.ErrorHandling);
var anim = new Table(_script);
AnimTableRegistrar.RegisterFunctions(anim);
_script.Globals["anim"] = anim;
}
public DynValue Run(string code) => _script.DoString(code);
public double Number(string expression) => Run("return " + expression).Number;
public bool Boolean(string expression) => Run("return " + expression).Boolean;
public string? Text(string expression) => Run("return " + expression).CastToString();
public DataType Type(string expression) => Run("return " + expression).Type;
public double[] Tuple(string expression, int count)
{
var table = Run("return {" + expression + "}").Table;
var result = new double[count];
for (int i = 0; i < count; i++)
result[i] = table.Get(i + 1).Number;
return result;
}
}
}
+133
ファイルの表示
@@ -0,0 +1,133 @@
using System;
using System.Collections.Generic;
using System.Globalization;
namespace LuaScript.Tests
{
public class NativeAnimEquivalenceTests
{
private readonly MoonSharpLane _oracle = new();
[Fact]
public void Anim_MatchesBetweenMoonSharpAndLuaJit()
{
var lane = new LuaJitLane();
Assert.True(lane.Available, "native/luajit.exe must be present");
var exprs = new List<string>();
void Add(string e) => exprs.Add(e);
void Tuple(string call, int n)
{
for (int k = 1; k <= n; k++)
exprs.Add($"({{{call}}})[{k}]");
}
Add("anim.tau"); Add("anim.e"); Add("anim.phi"); Add("anim.sqrt2");
foreach (var (a, b, t) in new[] { (0d, 10d, 0.5d), (10d, 20d, 0.25d), (-5d, 5d, 0.75d), (100d, -100d, 0.1d) })
Add($"anim.lerp({L(a)},{L(b)},{L(t)})");
foreach (var (e0, e1, x) in new[] { (0d, 1d, 0.5d), (0d, 1d, 0.3d), (2d, 4d, 3d), (0d, 1d, -1d), (0d, 1d, 2d) })
{
Add($"anim.smoothstep({L(e0)},{L(e1)},{L(x)})");
Add($"anim.smootherstep({L(e0)},{L(e1)},{L(x)})");
}
foreach (var (v, lo, hi) in new[] { (5d, 0d, 1d), (-1d, 0d, 1d), (0.5d, 0d, 1d), (7d, 2d, 9d) })
{
Add($"anim.clamp({L(v)},{L(lo)},{L(hi)})");
Add($"anim.norm({L(v)},{L(lo)},{L(hi)})");
}
Add("anim.map(5,0,10,0,100)"); Add("anim.map(0.5,0,1,-1,1)");
foreach (var (v, lo, hi) in new[] { (7d, 0d, 5d), (-1d, 0d, 5d), (12d, 2d, 8d), (-7d, -3d, 3d) })
Add($"anim.wrap({L(v)},{L(lo)},{L(hi)})");
foreach (var (t, len) in new[] { (7d, 5d), (3d, 5d), (0d, 5d), (13d, 5d), (-2d, 5d) })
Add($"anim.pingpong({L(t)},{L(len)})");
foreach (var v in new[] { -5d, 0d, 3d, 0.1d, -0.1d })
Add($"anim.sign({L(v)})");
Add("anim.oscillate(0,0,1,1)"); Add("anim.oscillate(0.25,0,1,1)"); Add("anim.oscillate(1,0,10,2)");
foreach (var (t, f) in new[] { (0d, 1d), (0.25d, 1d), (0.5d, 1d), (0.75d, 1d), (1.3d, 2d) })
{
Add($"anim.triangle({L(t)},{L(f)})");
Add($"anim.square({L(t)},{L(f)})");
}
foreach (var (t, d) in new[] { (0.5d, 1d), (2d, 1d), (0d, 1d), (0.3d, 2d) })
Add($"anim.duration({L(t)},{L(d)})");
foreach (var (t, d) in new[] { (2d, 1d), (0.5d, 1d), (3d, 0.5d) })
Add($"anim.delay({L(t)},{L(d)})");
foreach (var t in new[] { 0d, 0.25d, 0.5d, 0.75d, 1d, 0.1d })
{
Add($"anim.ease_in({L(t)})");
Add($"anim.ease_out({L(t)})");
Add($"anim.ease_in_out({L(t)})");
Add($"anim.elastic({L(t)})");
Add($"anim.back({L(t)})");
Add($"anim.bounce({L(t)})");
Add($"anim.fract({L(t + 3d)})");
}
Add("anim.step(0.5,0.6)"); Add("anim.step(0.5,0.4)"); Add("anim.step(0.5,0.5)");
Add("anim.bezier(0,0,1,2,3)"); Add("anim.bezier(1,0,1,2,3)"); Add("anim.bezier(0.5,0,0.3,0.7,1)");
Add("anim.len(3,4)"); Add("anim.len(1,1)");
Add("anim.dist(0,0,3,4)"); Add("anim.dist(1,1,4,5)");
Add("anim.dot(1,2,3,4)"); Add("anim.dot(0,0,1,1)");
foreach (var (h, s, v) in new[] { (0d, 1d, 1d), (120d, 1d, 1d), (240d, 0.5d, 0.8d), (60d, 1d, 1d), (300d, 0.7d, 0.9d) })
Tuple($"anim.hsv_to_rgb({L(h)},{L(s)},{L(v)})", 3);
foreach (var (r, g, b) in new[] { (255d, 0d, 0d), (0d, 255d, 0d), (0d, 0d, 255d), (128d, 128d, 128d), (200d, 100d, 50d) })
Tuple($"anim.rgb_to_hsv({L(r)},{L(g)},{L(b)})", 3);
foreach (var (x, y) in new[] { (3d, 4d), (-1d, 1d), (5d, 0d) })
Tuple($"anim.normalize({L(x)},{L(y)})", 2);
foreach (var (r, a) in new[] { (1d, 0d), (1d, 90d), (2d, 45d) })
Tuple($"anim.polar({L(r)},{L(a)})", 2);
foreach (var (x, y, a) in new[] { (1d, 0d, 90d), (1d, 0d, 45d), (0d, 1d, 180d) })
Tuple($"anim.rotate({L(x)},{L(y)},{L(a)})", 2);
for (int seed = 0; seed < 12; seed++)
{
Add($"anim.rand({seed})");
Add($"anim.rand(10,20,{seed})");
Add($"anim.rand(-3,3,{seed * 7 + 1})");
}
foreach (var x in new[] { 0.3d, 1.5d, 2.7d, 5.1d, -1.2d })
{
Add($"anim.noise({L(x)})");
Add($"anim.noise({L(x)},{L(x + 0.5d)})");
Add($"anim.noise({L(x)},{L(x + 0.5d)},{L(x - 0.3d)})");
}
var expected = new double[exprs.Count];
for (int i = 0; i < exprs.Count; i++)
expected[i] = _oracle.Number(exprs[i]);
string[] lines = lane.Eval(exprs);
Assert.Equal(exprs.Count, lines.Length);
var failures = new List<string>();
for (int i = 0; i < exprs.Count; i++)
{
if (!double.TryParse(lines[i], NumberStyles.Float, CultureInfo.InvariantCulture, out var got))
{
failures.Add($"{exprs[i]} => luajit '{lines[i]}' (not a number), expected {expected[i]}");
continue;
}
double tol = 1e-9 * Math.Max(1d, Math.Abs(expected[i]));
if (Math.Abs(got - expected[i]) > tol)
failures.Add($"{exprs[i]} => luajit {got}, moonsharp {expected[i]}");
}
Assert.True(failures.Count == 0,
$"{failures.Count}/{exprs.Count} mismatches:\n" + string.Join("\n", failures.GetRange(0, Math.Min(25, failures.Count))));
}
private static string L(double value) => value.ToString("R", CultureInfo.InvariantCulture);
}
}
+108
ファイルの表示
@@ -0,0 +1,108 @@
using System;
using System.Collections.Generic;
using System.Globalization;
using LuaScript.Compat;
namespace LuaScript.Tests
{
public class NativeBit32EquivalenceTests
{
private static readonly double[] Values =
[
0d, 1d, 2d, 255d, 256d, 65535d, 65536d,
2147483647d, 2147483648d, 4294967295d,
4294967296d, 4294967301d,
-1d, -2d, -256d, -2147483648d,
];
private static readonly int[] Shifts =
[
0, 1, 4, 7, 8, 15, 16, 24, 31, 32, 33, 64,
-1, -4, -8, -16, -31, -32, -33,
];
private static readonly (int Field, int Width)[] ValidFields =
[
(0, 1), (0, 8), (4, 4), (8, 8), (0, 16), (15, 16), (30, 1), (0, 31), (0, 32),
];
private static readonly (int Field, int Width)[] InvalidFields =
[
(32, 1), (0, 33), (-1, 1), (0, 0),
];
private static string Lit(double value) => value.ToString("R", CultureInfo.InvariantCulture);
[Fact]
public void CorrectBit32_MatchesAcrossMoonSharpAndLuaJit()
{
var lane = new LuaJitLane();
Assert.True(lane.Available, "native/luajit.exe must be present");
var exprs = new List<string>();
var expects = new List<object>();
void Num(string e, double v) { exprs.Add(e); expects.Add(v); }
void Bool(string e, bool v) { exprs.Add(e); expects.Add(v); }
void Err(string e) { exprs.Add(e); expects.Add("ERROR"); }
foreach (var a in Values)
{
Num($"bit32.bnot({Lit(a)})", Bit32.Bnot(a));
foreach (var b in Values)
{
Num($"bit32.band({Lit(a)},{Lit(b)})", Bit32.Band(a, b));
Num($"bit32.bor({Lit(a)},{Lit(b)})", Bit32.Bor(a, b));
Num($"bit32.bxor({Lit(a)},{Lit(b)})", Bit32.Bxor(a, b));
Bool($"bit32.btest({Lit(a)},{Lit(b)})", Bit32.Btest(a, b));
}
foreach (var n in Shifts)
{
Num($"bit32.lshift({Lit(a)},{n})", Bit32.Lshift(a, n));
Num($"bit32.rshift({Lit(a)},{n})", Bit32.Rshift(a, n));
Num($"bit32.arshift({Lit(a)},{n})", Bit32.Arshift(a, n));
Num($"bit32.lrotate({Lit(a)},{n})", Bit32.Lrotate(a, n));
Num($"bit32.rrotate({Lit(a)},{n})", Bit32.Rrotate(a, n));
}
foreach (var (field, width) in ValidFields)
{
Num($"bit32.extract({Lit(a)},{field},{width})", Bit32.Extract(a, field, width));
foreach (var v in Values)
Num($"bit32.replace({Lit(a)},{Lit(v)},{field},{width})", Bit32.Replace(a, v, field, width));
}
foreach (var (field, width) in InvalidFields)
{
Err($"bit32.extract({Lit(a)},{field},{width})");
Err($"bit32.replace({Lit(a)},1,{field},{width})");
}
}
string[] lines = lane.Eval(exprs);
Assert.Equal(exprs.Count, lines.Length);
var failures = new List<string>();
for (int i = 0; i < exprs.Count; i++)
{
string actual = lines[i];
switch (expects[i])
{
case double d:
if (!double.TryParse(actual, NumberStyles.Float, CultureInfo.InvariantCulture, out var got) || got != d)
failures.Add($"{exprs[i]} => luajit '{actual}', expected {d}");
break;
case bool b:
if (actual != (b ? "true" : "false"))
failures.Add($"{exprs[i]} => luajit '{actual}', expected {b}");
break;
case string s:
if (actual != s)
failures.Add($"{exprs[i]} => luajit '{actual}', expected {s}");
break;
}
}
Assert.True(failures.Count == 0,
$"{failures.Count}/{exprs.Count} mismatches:\n" + string.Join("\n", failures.GetRange(0, Math.Min(20, failures.Count))));
}
}
}
+78
ファイルの表示
@@ -0,0 +1,78 @@
using System;
using System.Diagnostics;
using System.IO;
using System.IO.MemoryMappedFiles;
namespace LuaScript.Tests
{
public class NativeSharedMemoryTests
{
private static string NativeDir => Path.Combine(AppContext.BaseDirectory, "native");
[Fact]
public void Worker_ProcessesSharedBgraBuffer_ViaFfi()
{
string luajit = Path.Combine(NativeDir, "luajit.exe");
Assert.True(File.Exists(luajit), "native/luajit.exe must be present");
const int width = 8;
const int height = 8;
const int pixels = width * height;
long size = pixels * 4L;
string mapName = "LuaScriptShmPoC_" + Guid.NewGuid().ToString("N");
using var mmf = MemoryMappedFile.CreateNew(mapName, size);
var expectedGray = new byte[pixels];
using (var acc = mmf.CreateViewAccessor())
{
for (int i = 0; i < pixels; i++)
{
byte b = (byte)(i * 3 % 256);
byte g = (byte)(i * 5 % 256);
byte r = (byte)(i * 7 % 256);
acc.Write(i * 4 + 0, b);
acc.Write(i * 4 + 1, g);
acc.Write(i * 4 + 2, r);
acc.Write(i * 4 + 3, (byte)255);
expectedGray[i] = (byte)Math.Min(255, (int)Math.Floor(r * 0.299 + g * 0.587 + b * 0.114 + 0.5));
}
}
var psi = new ProcessStartInfo
{
FileName = luajit,
WorkingDirectory = NativeDir,
RedirectStandardOutput = true,
RedirectStandardError = true,
UseShellExecute = false,
};
psi.ArgumentList.Add("worker_grayscale.lua");
psi.ArgumentList.Add(mapName);
psi.ArgumentList.Add(size.ToString());
using var process = Process.Start(psi)!;
string stdout = process.StandardOutput.ReadToEnd();
string stderr = process.StandardError.ReadToEnd();
Assert.True(process.WaitForExit(5000), "worker should finish quickly");
Assert.Equal(0, process.ExitCode);
Assert.Equal("done", stdout);
Assert.Equal("", stderr);
using (var acc = mmf.CreateViewAccessor())
{
for (int i = 0; i < pixels; i++)
{
byte b = acc.ReadByte(i * 4 + 0);
byte g = acc.ReadByte(i * 4 + 1);
byte r = acc.ReadByte(i * 4 + 2);
byte a = acc.ReadByte(i * 4 + 3);
Assert.Equal(expectedGray[i], b);
Assert.Equal(expectedGray[i], g);
Assert.Equal(expectedGray[i], r);
Assert.Equal(255, a);
}
}
}
}
}
+184
ファイルの表示
@@ -0,0 +1,184 @@
using System;
using System.IO;
using LuaScript.Engine;
namespace LuaScript.Tests
{
public class NativeWorkerRoundTripTests : IDisposable
{
private static string NativeDir => Path.Combine(AppContext.BaseDirectory, "native");
private readonly LuaJitWorker _worker = new(NativeDir);
public void Dispose() => _worker.Dispose();
private static double[] Fields(int w, int h, double time)
{
var f = new double[NativeProtocol.FieldCount];
f[NativeProtocol.W] = w;
f[NativeProtocol.H] = h;
f[NativeProtocol.Time] = time;
f[NativeProtocol.Alpha] = 255d;
return f;
}
[Fact]
public void TransformScript_WritesBackObjFields()
{
Assert.True(LuaJitWorker.IsAvailable(NativeDir), "native/luajit.exe must be present");
var fields = Fields(4, 4, 2d);
var pixels = new byte[4 * 4 * 4];
bool ok = _worker.Execute(
"obj.rz = obj.time * 90\nobj.alpha = 128",
fields, pixels, 4, 4, 5000, out bool dirty, out string? error);
Assert.True(ok, error);
Assert.False(dirty);
Assert.Equal(180d, fields[NativeProtocol.Rz]);
Assert.Equal(128d, fields[NativeProtocol.Alpha]);
}
[Fact]
public void PixelScript_MatchesExpectedGrayscale()
{
Assert.True(LuaJitWorker.IsAvailable(NativeDir), "native/luajit.exe must be present");
const int w = 2, h = 2;
var pixels = new byte[w * h * 4];
void SetBgra(int i, byte b, byte g, byte r, byte a)
{
pixels[i * 4 + 0] = b; pixels[i * 4 + 1] = g; pixels[i * 4 + 2] = r; pixels[i * 4 + 3] = a;
}
SetBgra(0, 10, 20, 30, 255);
SetBgra(1, 0, 0, 0, 0);
SetBgra(2, 50, 100, 200, 128);
SetBgra(3, 255, 255, 255, 255);
var expected = (byte[])pixels.Clone();
for (int i = 0; i < w * h; i++)
Grayscale(expected, i);
var fields = Fields(w, h, 0d);
const string script =
"for y=0,obj.h-1 do for x=0,obj.w-1 do " +
"local r,g,b,a = obj.getpixel(x,y) " +
"local gray = r*0.299 + g*0.587 + b*0.114 " +
"obj.setpixel(x,y,gray,gray,gray,a) end end";
bool ok = _worker.Execute(script, fields, pixels, w, h, 5000, out bool dirty, out string? error);
Assert.True(ok, error);
Assert.True(dirty);
Assert.Equal(expected, pixels);
}
[Fact]
public void PixelDataProxy_MatchesExpectedGrayscale()
{
Assert.True(LuaJitWorker.IsAvailable(NativeDir), "native/luajit.exe must be present");
const int w = 2, h = 2;
var pixels = new byte[w * h * 4];
void SetBgra(int i, byte b, byte g, byte r, byte a)
{
pixels[i * 4 + 0] = b; pixels[i * 4 + 1] = g; pixels[i * 4 + 2] = r; pixels[i * 4 + 3] = a;
}
SetBgra(0, 10, 20, 30, 255);
SetBgra(1, 0, 0, 0, 0);
SetBgra(2, 50, 100, 200, 128);
SetBgra(3, 255, 255, 255, 255);
var expected = (byte[])pixels.Clone();
for (int i = 0; i < w * h; i++)
Grayscale(expected, i);
var fields = Fields(w, h, 0d);
const string script =
"local pd = obj.getpixeldata() local w,h = pd.width, 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";
bool ok = _worker.Execute(script, fields, pixels, w, h, 5000, out bool dirty, out string? error);
Assert.True(ok, error);
Assert.True(dirty);
Assert.Equal(expected, pixels);
}
private static void Grayscale(byte[] px, int i)
{
double b = px[i * 4 + 0], g = px[i * 4 + 1], r = px[i * 4 + 2], a = px[i * 4 + 3];
double sr, sg, sb;
if (a <= 0d) { sr = sg = sb = 0d; }
else
{
double s = 255d / a;
sr = Math.Clamp(r * s, 0d, 255d);
sg = Math.Clamp(g * s, 0d, 255d);
sb = Math.Clamp(b * s, 0d, 255d);
}
double gray = sr * 0.299 + sg * 0.587 + sb * 0.114;
double aK = Math.Clamp(a, 0d, 255d) / 255d;
px[i * 4 + 0] = (byte)Math.Floor(Math.Clamp(gray * aK, 0d, 255d));
px[i * 4 + 1] = (byte)Math.Floor(Math.Clamp(gray * aK, 0d, 255d));
px[i * 4 + 2] = (byte)Math.Floor(Math.Clamp(gray * aK, 0d, 255d));
px[i * 4 + 3] = (byte)Math.Floor(Math.Clamp(a, 0d, 255d));
}
[Fact]
public void PersistentWorker_HandlesMultipleCalls()
{
Assert.True(LuaJitWorker.IsAvailable(NativeDir), "native/luajit.exe must be present");
var pixels = new byte[16];
for (int k = 1; k <= 5; k++)
{
var fields = Fields(2, 2, k);
bool ok = _worker.Execute("obj.x = obj.time * 10", fields, pixels, 2, 2, 5000, out _, out string? error);
Assert.True(ok, error);
Assert.Equal(k * 10d, fields[NativeProtocol.X]);
}
}
[Fact]
public void Timeout_KillsWorker_AndRecovers()
{
Assert.True(LuaJitWorker.IsAvailable(NativeDir), "native/luajit.exe must be present");
var pixels = new byte[16];
var fields = Fields(2, 2, 0d);
bool timedOut = _worker.Execute(
"local x=0 while true do x=x+1 end", fields, pixels, 2, 2, 1500, out _, out string? error);
Assert.False(timedOut);
Assert.Contains("timed out", error);
var fields2 = Fields(2, 2, 3d);
bool ok = _worker.Execute("obj.x = obj.time", fields2, pixels, 2, 2, 5000, out _, out error);
Assert.True(ok, error);
Assert.Equal(3d, fields2[NativeProtocol.X]);
}
[Fact]
public void RuntimeError_IsReported_AndWorkerSurvives()
{
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.x = missing.value", fields, pixels, 2, 2, 5000, out _, out string? error);
Assert.False(ok);
Assert.False(string.IsNullOrEmpty(error));
var fields2 = Fields(2, 2, 7d);
bool ok2 = _worker.Execute("obj.x = obj.time", fields2, pixels, 2, 2, 5000, out _, out error);
Assert.True(ok2, error);
Assert.Equal(7d, fields2[NativeProtocol.X]);
}
}
}
+52
ファイルの表示
@@ -0,0 +1,52 @@
using System;
using System.Diagnostics;
using System.IO;
namespace LuaScript.Tests
{
public class NativeWorkerTimeoutTests
{
private static string LuaJit => Path.Combine(AppContext.BaseDirectory, "native", "luajit.exe");
private static Process Launch(string inlineScript)
{
var psi = new ProcessStartInfo
{
FileName = LuaJit,
WorkingDirectory = Path.GetDirectoryName(LuaJit)!,
RedirectStandardOutput = true,
RedirectStandardError = true,
UseShellExecute = false,
};
psi.ArgumentList.Add("-e");
psi.ArgumentList.Add(inlineScript);
return Process.Start(psi) ?? throw new InvalidOperationException("failed to start luajit");
}
[Fact]
public void JitCompiledInfiniteLoop_IsHardKilledWithinTimeout_AndHostRecovers()
{
Assert.True(File.Exists(LuaJit), "native/luajit.exe must be present");
const int timeoutMs = 1500;
using (var hung = Launch("local x=0 for i=1,1e9 do for j=1,1e9 do x=x+1 end end"))
{
bool exitedOnItsOwn = hung.WaitForExit(timeoutMs);
Assert.False(exitedOnItsOwn, "the hot loop should still be running at the timeout");
var sw = Stopwatch.StartNew();
hung.Kill(entireProcessTree: true);
Assert.True(hung.WaitForExit(2000), "the process must terminate promptly after Kill");
sw.Stop();
Assert.True(sw.ElapsedMilliseconds < 2000, "kill should take effect quickly");
}
using var ok = Launch("io.write('recovered')");
string output = ok.StandardOutput.ReadToEnd();
Assert.True(ok.WaitForExit(5000), "a fresh worker must run after the previous was killed");
Assert.Equal(0, ok.ExitCode);
Assert.Equal("recovered", output);
}
}
}
+85
ファイルの表示
@@ -0,0 +1,85 @@
using MoonSharp.Interpreter;
namespace LuaScript.Tests
{
public class RawAndBasicTests
{
private readonly MoonSharpLane _lane = new();
[Fact]
public void RawLen_Table() => Assert.Equal(3d, _lane.Number("rawlen({10,20,30})"));
[Fact]
public void RawLen_String() => Assert.Equal(5d, _lane.Number("rawlen('hello')"));
[Fact]
public void RawEqual_SameReference()
{
Assert.True(_lane.Boolean("(function() local t={} return rawequal(t,t) end)()"));
Assert.False(_lane.Boolean("rawequal({},{})"));
}
[Fact]
public void RawGetSet_BypassMetatable()
{
Assert.Equal(7d, _lane.Number(
"(function() local t=setmetatable({},{__index=function() return 99 end}) rawset(t,'k',7) return rawget(t,'k') end)()"));
Assert.Equal(99d, _lane.Number(
"(function() local t=setmetatable({},{__index=function() return 99 end}) return t.missing end)()"));
}
[Fact]
public void Select_Count() => Assert.Equal(3d, _lane.Number("select('#', 'a', 'b', 'c')"));
[Fact]
public void Select_Index() => Assert.Equal(20d, _lane.Number("(select(2, 10, 20, 30))"));
[Theory]
[InlineData("type(1)", "number")]
[InlineData("type('x')", "string")]
[InlineData("type({})", "table")]
[InlineData("type(nil)", "nil")]
[InlineData("type(true)", "boolean")]
[InlineData("type(print)", "function")]
public void Type_Names(string expression, string expected) =>
Assert.Equal(expected, _lane.Text(expression));
[Theory]
[InlineData("tonumber('42')", 42d)]
[InlineData("tonumber('10', 2)", 2d)]
[InlineData("tonumber('ff', 16)", 255d)]
public void ToNumber_Parsing(string expression, double expected) =>
Assert.Equal(expected, _lane.Number(expression));
[Fact]
public void ToNumber_InvalidIsNil() =>
Assert.Equal(DataType.Nil, _lane.Type("tonumber('not a number')"));
[Fact]
public void ToNumber_HexStringPrefix_IsNil_MoonSharpDivergence() =>
Assert.Equal(DataType.Nil, _lane.Type("tonumber('0x1F')"));
[Fact]
public void Unpack_Global() =>
Assert.Equal(6d, _lane.Number("(function() local a,b,c = unpack({1,2,3}) return a+b+c end)()"));
[Fact]
public void Pcall_CapturesError() =>
Assert.False(_lane.Boolean("(function() local ok = pcall(function() error('boom') end) return ok end)()"));
[Fact]
public void Pcall_SuccessReturnsTrue() =>
Assert.True(_lane.Boolean("(function() local ok = pcall(function() return 1 end) return ok end)()"));
[Fact]
public void StringFormat_Basic() =>
Assert.Equal("a=5 b=2.50", _lane.Text("string.format('a=%d b=%.2f', 5, 2.5)"));
[Fact]
public void MathFloorCeil()
{
Assert.Equal(3d, _lane.Number("math.floor(3.7)"));
Assert.Equal(4d, _lane.Number("math.ceil(3.2)"));
}
}
}
+45
ファイルの表示
@@ -0,0 +1,45 @@
using LuaScript.Engine;
namespace LuaScript.Tests
{
public class ScriptDirectiveTests
{
[Theory]
[InlineData(null, "MoonSharp")]
[InlineData("", "MoonSharp")]
[InlineData("obj.rz = time * 90", "MoonSharp")]
[InlineData("--!native", "Native")]
[InlineData("--!gpu", "Gpu")]
[InlineData("--!cpu", "Cpu")]
[InlineData("--!moonsharp", "MoonSharp")]
[InlineData("--! native ", "Native")]
[InlineData("--!NATIVE", "Native")]
[InlineData("\r\n --!gpu\r\nfunction pixel() end", "Gpu")]
[InlineData("-- normal comment\n--!native\nobj.x = 0", "Native")]
[InlineData("--!unknown", "MoonSharp")]
[InlineData("--!native extra", "MoonSharp")]
[InlineData("obj.x=0 --!native", "MoonSharp")]
public void Resolve_ReturnsExpectedEngine(string? script, string expected)
{
Assert.Equal(expected, ScriptDirective.Resolve(script).ToString());
}
[Fact]
public void Resolve_FirstDirectiveWins()
{
Assert.Equal("Native", ScriptDirective.Resolve("--!native\n--!gpu").ToString());
}
[Theory]
[InlineData("obj.rz = time * 90", "MoonSharp")]
[InlineData("local r,g,b,a = obj.getpixel(0,0)", "Native")]
[InlineData("obj.setpixel(0,0,255,0,0)", "Native")]
[InlineData("local pd = obj.getpixeldata()", "Native")]
[InlineData("--!moonsharp\nobj.setpixel(0,0,1,1,1)", "MoonSharp")]
[InlineData("--!native\nobj.rz = 1", "Native")]
public void ResolveAuto_RoutesPixelScriptsToNative(string script, string expected)
{
Assert.Equal(expected, ScriptDirective.ResolveAuto(script).ToString());
}
}
}
+1
ファイルの表示
@@ -3,6 +3,7 @@
<Platform Name="Any CPU" />
<Platform Name="x64" />
</Configurations>
<Project Path="LuaScript.Tests/LuaScript.Tests.csproj" />
<Project Path="LuaScript/LuaScript.csproj">
<Platform Solution="*|x64" Project="x64" />
</Project>
+32 -29
ファイルの表示
@@ -2,12 +2,12 @@ namespace LuaScript
{
internal sealed class AviUtlScriptContext
{
public bool IsPlaying { get; init; }
public bool IsPaused { get; init; }
public string SceneId { get; init; } = string.Empty;
public bool IsPlaying { get; set; }
public bool IsPaused { get; set; }
public string SceneId { get; set; } = string.Empty;
public int ImageWidth { get; init; }
public int ImageHeight { get; init; }
public int ImageWidth { get; set; }
public int ImageHeight { get; set; }
public double X { get; set; }
public double Y { get; set; }
@@ -24,25 +24,25 @@ namespace LuaScript
public double Ry { get; set; }
public double Rz { get; set; }
public double Track0 { get; init; }
public double Track1 { get; init; }
public double Track2 { get; init; }
public double Track3 { get; init; }
public double Track0 { get; set; }
public double Track1 { get; set; }
public double Track2 { get; set; }
public double Track3 { get; set; }
public double Time { get; init; }
public int Frame { get; init; }
public int TotalFrame { get; init; }
public double TotalTime { get; init; }
public int Framerate { get; init; }
public int TimelineFrame { get; init; }
public double TimelineTime { get; init; }
public int SceneWidth { get; init; }
public int SceneHeight { get; init; }
public int Layer { get; init; }
public int Index { get; init; }
public int Num { get; init; }
public double Time { get; set; }
public int Frame { get; set; }
public int TotalFrame { get; set; }
public double TotalTime { get; set; }
public int Framerate { get; set; }
public int TimelineFrame { get; set; }
public double TimelineTime { get; set; }
public int SceneWidth { get; set; }
public int SceneHeight { get; set; }
public int Layer { get; set; }
public int Index { get; set; }
public int Num { get; set; }
public SceneObjectResolver? Resolver { get; init; }
public Func<SceneObjectResolver>? ResolverProvider { get; set; }
private readonly List<SceneObjectQuery> _objectQueries = [];
@@ -52,12 +52,12 @@ namespace LuaScript
public double RyRad => Ry * Math.PI / 180d;
public double RzRad => Rz * Math.PI / 180d;
public int GroupIndex { get; init; }
public int GroupCount { get; init; }
public int TimelineTotalFrame { get; init; }
public double TimelineTotalTime { get; init; }
public bool IsSaving { get; init; }
public double TimeRatio { get; init; }
public int GroupIndex { get; set; }
public int GroupCount { get; set; }
public int TimelineTotalFrame { get; set; }
public double TimelineTotalTime { get; set; }
public bool IsSaving { get; set; }
public double TimeRatio { get; set; }
private Func<byte[]>? _pixelLoader;
private byte[]? _pixelBuffer;
@@ -68,6 +68,8 @@ namespace LuaScript
internal int TotalChannels => ImageWidth * ImageHeight * 4;
internal void ClearQueries() => _objectQueries.Clear();
internal void SetPixelLoader(Func<byte[]> loader)
{
_pixelLoader = loader;
@@ -89,7 +91,8 @@ namespace LuaScript
public bool ResolveObject(string tag, int frame, out SceneObjectInfo info)
{
if (Resolver is not null && Resolver.TryResolve(tag, frame, out var resolved))
var resolver = ResolverProvider?.Invoke();
if (resolver is not null && resolver.TryResolve(tag, frame, out var resolved))
{
_objectQueries.Add(new SceneObjectQuery(tag, frame, resolved));
info = resolved;
+109
ファイルの表示
@@ -0,0 +1,109 @@
using System;
namespace LuaScript.Compat
{
internal static class Bit32
{
public static uint ToUInt32(double value) => unchecked((uint)(long)value);
public static uint Band(params double[] values)
{
uint accum = 0xFFFFFFFFu;
foreach (var value in values)
accum &= ToUInt32(value);
return accum;
}
public static uint Bor(params double[] values)
{
uint accum = 0u;
foreach (var value in values)
accum |= ToUInt32(value);
return accum;
}
public static uint Bxor(params double[] values)
{
uint accum = 0u;
foreach (var value in values)
accum ^= ToUInt32(value);
return accum;
}
public static bool Btest(params double[] values) => Band(values) != 0u;
public static uint Bnot(double value) => ~ToUInt32(value);
public static uint Lshift(double value, double shift)
{
uint v = ToUInt32(value);
int a = (int)shift;
if (a <= -32 || a >= 32)
return 0u;
return a >= 0 ? v << a : v >> -a;
}
public static uint Rshift(double value, double shift) => Lshift(value, -shift);
public static uint Arshift(double value, double shift)
{
uint v = ToUInt32(value);
int a = (int)shift;
if (a < 0)
return Lshift(value, -shift);
bool negative = (v & 0x80000000u) != 0u;
if (a >= 32)
return negative ? 0xFFFFFFFFu : 0u;
if (a == 0)
return v;
uint result = v >> a;
if (negative)
result |= ~0u << (32 - a);
return result;
}
public static uint Lrotate(double value, double shift)
{
uint v = ToUInt32(value);
int a = ((int)shift % 32 + 32) % 32;
return a == 0 ? v : (v << a) | (v >> (32 - a));
}
public static uint Rrotate(double value, double shift) => Lrotate(value, -shift);
public static uint Extract(double value, double pos, double? width)
{
uint v = ToUInt32(value);
int p = (int)pos;
int w = width is null ? 1 : (int)width.Value;
ValidatePosWidth(p, w);
return (v >> p) & NBitMask(w);
}
public static uint Replace(double value, double replacement, double pos, double? width)
{
uint v = ToUInt32(value);
uint u = ToUInt32(replacement);
int p = (int)pos;
int w = width is null ? 1 : (int)width.Value;
ValidatePosWidth(p, w);
uint mask = NBitMask(w) << p;
return (v & ~mask) | ((u & NBitMask(w)) << p);
}
private static void ValidatePosWidth(int pos, int width)
{
if (pos < 0 || width < 1 || pos + width > 32)
throw new ArgumentException("trying to access non-existent bits");
}
private static uint NBitMask(int bits)
{
if (bits <= 0)
return 0u;
if (bits >= 32)
return 0xFFFFFFFFu;
return (1u << bits) - 1u;
}
}
}
+111
ファイルの表示
@@ -0,0 +1,111 @@
using System;
namespace LuaScript.Compat
{
internal static class MoonSharpBit32
{
private const double Modulo = 4294967296.0;
public static uint ToUInt32(double value) => unchecked((uint)Math.IEEERemainder(value, Modulo));
public static int ToInt32(double value) => unchecked((int)Math.IEEERemainder(value, Modulo));
public static uint Band(params double[] values)
{
uint accum = ToUInt32(values[0]);
for (int i = 1; i < values.Length; i++)
accum &= ToUInt32(values[i]);
return accum;
}
public static uint Bor(params double[] values)
{
uint accum = ToUInt32(values[0]);
for (int i = 1; i < values.Length; i++)
accum |= ToUInt32(values[i]);
return accum;
}
public static uint Bxor(params double[] values)
{
uint accum = ToUInt32(values[0]);
for (int i = 1; i < values.Length; i++)
accum ^= ToUInt32(values[i]);
return accum;
}
public static bool Btest(params double[] values) => Band(values) != 0u;
public static uint Bnot(double value) => ~ToUInt32(value);
public static uint Lshift(double value, double shift)
{
uint v = ToUInt32(value);
int a = (int)shift;
return a < 0 ? v >> -a : v << a;
}
public static uint Rshift(double value, double shift)
{
uint v = ToUInt32(value);
int a = (int)shift;
return a < 0 ? v << -a : v >> a;
}
public static int Arshift(double value, double shift)
{
int v = ToInt32(value);
int a = (int)shift;
return a < 0 ? v << -a : v >> a;
}
public static uint Lrotate(double value, double shift)
{
uint v = ToUInt32(value);
int a = ((int)shift) % 32;
return a < 0 ? (v >> -a) | (v << (32 + a)) : (v << a) | (v >> (32 - a));
}
public static uint Rrotate(double value, double shift)
{
uint v = ToUInt32(value);
int a = ((int)shift) % 32;
return a < 0 ? (v << -a) | (v >> (32 + a)) : (v >> a) | (v << (32 - a));
}
public static uint Extract(double value, double pos, double? width)
{
uint v = ToUInt32(value);
int p = (int)pos;
int w = width is null ? 1 : (int)width.Value;
ValidatePosWidth(p, w);
return (v >> p) & NBitMask(w);
}
public static uint Replace(double value, double replacement, double pos, double? width)
{
uint v = ToUInt32(value);
uint u = ToUInt32(replacement);
int p = (int)pos;
int w = width is null ? 1 : (int)width.Value;
ValidatePosWidth(p, w);
uint mask = NBitMask(w) << p;
return (v & ~mask) | (u & mask);
}
private static void ValidatePosWidth(int pos, int width)
{
if (pos > 31 || pos + width > 31)
throw new ArgumentException("trying to access non-existent bits");
}
private static uint NBitMask(int bits)
{
if (bits <= 0)
return 0u;
if (bits >= 32)
return 0xFFFFFFFFu;
return (1u << bits) - 1u;
}
}
}
+180
ファイルの表示
@@ -0,0 +1,180 @@
using System;
using System.Diagnostics;
using System.IO;
using System.IO.MemoryMappedFiles;
using System.Text;
using System.Threading;
namespace LuaScript.Engine
{
internal sealed class LuaJitWorker : IDisposable
{
private readonly string _luajitPath;
private readonly string _workerScript;
private readonly string _shimScript;
private readonly string _nativeDir;
private MemoryMappedFile? _mmf;
private MemoryMappedViewAccessor? _view;
private EventWaitHandle? _workEvent;
private EventWaitHandle? _doneEvent;
private Process? _process;
private int _width;
private int _height;
private bool _alive;
public LuaJitWorker(string nativeDir)
{
_nativeDir = nativeDir;
_luajitPath = Path.Combine(nativeDir, "luajit.exe");
_workerScript = Path.Combine(nativeDir, "worker.lua");
_shimScript = Path.Combine(nativeDir, "shim.lua");
}
public static bool IsAvailable(string nativeDir) =>
File.Exists(Path.Combine(nativeDir, "luajit.exe"));
public bool Execute(
string script,
double[] fields,
byte[] pixels,
int width,
int height,
int timeoutMs,
out bool pixelsDirty,
out string? error)
{
pixelsDirty = false;
error = null;
byte[] scriptBytes = Encoding.UTF8.GetBytes(script);
if (scriptBytes.Length > NativeProtocol.ScriptMax)
{
error = "script too large for native lane";
return false;
}
EnsureWorker(width, height);
var view = _view!;
view.WriteArray(NativeProtocol.FieldsOffset, fields, 0, NativeProtocol.FieldCount);
view.Write(NativeProtocol.OffWidth, width);
view.Write(NativeProtocol.OffHeight, height);
view.Write(NativeProtocol.OffScriptLen, scriptBytes.Length);
view.WriteArray(NativeProtocol.ScriptOffset, scriptBytes, 0, scriptBytes.Length);
view.WriteArray(NativeProtocol.PixelOffset, pixels, 0, pixels.Length);
view.Write(NativeProtocol.OffPixelsDirty, 0);
view.Write(NativeProtocol.OffErrorLen, 0);
view.Write(NativeProtocol.OffStatus, NativeProtocol.StatusIdle);
view.Write(NativeProtocol.OffCommand, NativeProtocol.CmdRun);
_workEvent!.Set();
if (!_doneEvent!.WaitOne(timeoutMs))
{
KillWorker();
error = "native script execution timed out";
return false;
}
int status = view.ReadInt32(NativeProtocol.OffStatus);
if (status == NativeProtocol.StatusError)
{
int len = view.ReadInt32(NativeProtocol.OffErrorLen);
var buffer = new byte[Math.Clamp(len, 0, NativeProtocol.ErrorMax)];
view.ReadArray(NativeProtocol.ErrorOffset, buffer, 0, buffer.Length);
error = Encoding.UTF8.GetString(buffer);
return false;
}
for (int i = NativeProtocol.FirstWritableField; i <= NativeProtocol.LastWritableField; i++)
fields[i] = view.ReadDouble(NativeProtocol.FieldsOffset + i * 8);
pixelsDirty = view.ReadInt32(NativeProtocol.OffPixelsDirty) != 0;
if (pixelsDirty)
view.ReadArray(NativeProtocol.PixelOffset, pixels, 0, pixels.Length);
return true;
}
private void EnsureWorker(int width, int height)
{
if (_alive && _process is { HasExited: false } && _width == width && _height == height)
return;
KillWorker();
StartWorker(width, height);
}
private void StartWorker(int width, int height)
{
_width = width;
_height = height;
long size = NativeProtocol.BufferSize(width, height);
string suffix = Guid.NewGuid().ToString("N");
string mapName = "LuaScriptMap_" + suffix;
string workName = "LuaScriptWork_" + suffix;
string doneName = "LuaScriptDone_" + suffix;
_mmf = MemoryMappedFile.CreateNew(mapName, size);
_view = _mmf.CreateViewAccessor();
_view.Write(NativeProtocol.OffMagic, NativeProtocol.Magic);
_workEvent = new EventWaitHandle(false, EventResetMode.AutoReset, workName);
_doneEvent = new EventWaitHandle(false, EventResetMode.AutoReset, doneName);
var psi = new ProcessStartInfo
{
FileName = _luajitPath,
WorkingDirectory = _nativeDir,
UseShellExecute = false,
CreateNoWindow = true,
RedirectStandardError = true,
};
psi.ArgumentList.Add(_workerScript);
psi.ArgumentList.Add(mapName);
psi.ArgumentList.Add(size.ToString());
psi.ArgumentList.Add(workName);
psi.ArgumentList.Add(doneName);
psi.ArgumentList.Add(_shimScript);
_process = Process.Start(psi);
_alive = _process is not null;
}
private void KillWorker()
{
if (_process is { HasExited: false })
{
try { _process.Kill(entireProcessTree: true); }
catch { }
}
_process?.Dispose();
_process = null;
_view?.Dispose();
_view = null;
_mmf?.Dispose();
_mmf = null;
_workEvent?.Dispose();
_workEvent = null;
_doneEvent?.Dispose();
_doneEvent = null;
_alive = false;
}
public void Dispose()
{
if (_alive && _process is { HasExited: false } && _view is not null && _workEvent is not null)
{
try
{
_view.Write(NativeProtocol.OffCommand, NativeProtocol.CmdShutdown);
_workEvent.Set();
_process.WaitForExit(500);
}
catch { }
}
KillWorker();
}
}
}
+114
ファイルの表示
@@ -0,0 +1,114 @@
using System;
namespace LuaScript.Engine
{
internal static class NativeFieldMap
{
private const double Epsilon = 1e-10;
public static void ToFields(AviUtlScriptContext ctx, double[] f)
{
f[NativeProtocol.W] = ctx.ImageWidth;
f[NativeProtocol.H] = ctx.ImageHeight;
f[NativeProtocol.Hw] = ctx.ImageWidth / 2d;
f[NativeProtocol.Hh] = ctx.ImageHeight / 2d;
f[NativeProtocol.Cx] = ctx.ImageWidth / 2d;
f[NativeProtocol.Cy] = ctx.ImageHeight / 2d;
f[NativeProtocol.Cz] = 0d;
f[NativeProtocol.Diagonal] = Math.Sqrt((double)ctx.ImageWidth * ctx.ImageWidth + (double)ctx.ImageHeight * ctx.ImageHeight);
f[NativeProtocol.X] = ctx.X;
f[NativeProtocol.Y] = ctx.Y;
f[NativeProtocol.Z] = ctx.Z;
f[NativeProtocol.Ox] = ctx.Ox;
f[NativeProtocol.Oy] = ctx.Oy;
f[NativeProtocol.Oz] = ctx.Oz;
f[NativeProtocol.Sx] = ctx.Sx;
f[NativeProtocol.Sy] = ctx.Sy;
f[NativeProtocol.Sz] = 1d;
f[NativeProtocol.Zoom] = ctx.Zoom;
f[NativeProtocol.Aspect] = ctx.Aspect;
f[NativeProtocol.Alpha] = ctx.Alpha;
f[NativeProtocol.Rx] = ctx.Rx;
f[NativeProtocol.Ry] = ctx.Ry;
f[NativeProtocol.Rz] = ctx.Rz;
f[NativeProtocol.Rxr] = ctx.RxRad;
f[NativeProtocol.Ryr] = ctx.RyRad;
f[NativeProtocol.Rzr] = ctx.RzRad;
f[NativeProtocol.Track0] = ctx.Track0;
f[NativeProtocol.Track1] = ctx.Track1;
f[NativeProtocol.Track2] = ctx.Track2;
f[NativeProtocol.Track3] = ctx.Track3;
f[NativeProtocol.Time] = ctx.Time;
f[NativeProtocol.Frame] = ctx.Frame;
f[NativeProtocol.TotalFrame] = ctx.TotalFrame;
f[NativeProtocol.TotalTime] = ctx.TotalTime;
f[NativeProtocol.T] = ctx.TotalFrame > 0 ? ctx.Frame / (double)ctx.TotalFrame : 0d;
f[NativeProtocol.Framerate] = ctx.Framerate;
f[NativeProtocol.Layer] = ctx.Layer;
f[NativeProtocol.Index] = ctx.Index;
f[NativeProtocol.Num] = ctx.Num;
f[NativeProtocol.SceneWidth] = ctx.SceneWidth;
f[NativeProtocol.SceneHeight] = ctx.SceneHeight;
f[NativeProtocol.SceneCx] = ctx.SceneWidth / 2d;
f[NativeProtocol.SceneCy] = ctx.SceneHeight / 2d;
f[NativeProtocol.GroupIndex] = ctx.GroupIndex;
f[NativeProtocol.GroupCount] = ctx.GroupCount;
f[NativeProtocol.TimelineTotalFrame] = ctx.TimelineTotalFrame;
f[NativeProtocol.TimelineTotalTime] = ctx.TimelineTotalTime;
f[NativeProtocol.TimeRatio] = ctx.TimeRatio;
f[NativeProtocol.IsSaving] = ctx.IsSaving ? 1d : 0d;
f[NativeProtocol.IsPlaying] = ctx.IsPlaying ? 1d : 0d;
f[NativeProtocol.IsPaused] = ctx.IsPaused ? 1d : 0d;
f[NativeProtocol.TimelineFrame] = ctx.TimelineFrame;
f[NativeProtocol.TimelineTime] = ctx.TimelineTime;
}
public static void FromFields(double[] f, AviUtlScriptContext ctx)
{
ctx.X = f[NativeProtocol.X];
ctx.Y = f[NativeProtocol.Y];
ctx.Z = f[NativeProtocol.Z];
ctx.Ox = f[NativeProtocol.Ox];
ctx.Oy = f[NativeProtocol.Oy];
ctx.Oz = f[NativeProtocol.Oz];
ctx.Alpha = f[NativeProtocol.Alpha];
double initialSx = ctx.Sx;
double initialSy = ctx.Sy;
double initialZoom = ctx.Zoom;
double initialAspect = ctx.Aspect;
ctx.Sx = f[NativeProtocol.Sx];
ctx.Sy = f[NativeProtocol.Sy];
ctx.Zoom = f[NativeProtocol.Zoom];
ctx.Aspect = f[NativeProtocol.Aspect];
bool sxsyChanged = Math.Abs(ctx.Sx - initialSx) > Epsilon || Math.Abs(ctx.Sy - initialSy) > Epsilon;
bool zoomAspectChanged = Math.Abs(ctx.Zoom - initialZoom) > Epsilon || Math.Abs(ctx.Aspect - initialAspect) > Epsilon;
if (zoomAspectChanged && !sxsyChanged)
{
ctx.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];
}
}
}
+96
ファイルの表示
@@ -0,0 +1,96 @@
namespace LuaScript.Engine
{
internal static class NativeProtocol
{
public const int Magic = 0x4C4A4954;
public const int CmdRun = 0;
public const int CmdShutdown = 1;
public const int StatusIdle = 0;
public const int StatusOk = 1;
public const int StatusError = 2;
public const int OffMagic = 0;
public const int OffCommand = 4;
public const int OffStatus = 8;
public const int OffWidth = 12;
public const int OffHeight = 16;
public const int OffScriptLen = 20;
public const int OffPixelsDirty = 24;
public const int OffErrorLen = 28;
public const int HeaderSize = 64;
public const int FieldCount = 64;
public const int FieldsOffset = HeaderSize;
public const int ScriptOffset = FieldsOffset + FieldCount * 8;
public const int ScriptMax = 128 * 1024;
public const int ErrorOffset = ScriptOffset + ScriptMax;
public const int ErrorMax = 4 * 1024;
public const int PixelOffset = ErrorOffset + ErrorMax;
public const int W = 0;
public const int H = 1;
public const int Hw = 2;
public const int Hh = 3;
public const int Cx = 4;
public const int Cy = 5;
public const int Cz = 6;
public const int Diagonal = 7;
public const int X = 8;
public const int Y = 9;
public const int Z = 10;
public const int Ox = 11;
public const int Oy = 12;
public const int Oz = 13;
public const int Sx = 14;
public const int Sy = 15;
public const int Sz = 16;
public const int Zoom = 17;
public const int Aspect = 18;
public const int Alpha = 19;
public const int Rx = 20;
public const int Ry = 21;
public const int Rz = 22;
public const int Rxr = 23;
public const int Ryr = 24;
public const int Rzr = 25;
public const int Track0 = 26;
public const int Track1 = 27;
public const int Track2 = 28;
public const int Track3 = 29;
public const int Time = 30;
public const int Frame = 31;
public const int TotalFrame = 32;
public const int TotalTime = 33;
public const int T = 34;
public const int Framerate = 35;
public const int Layer = 36;
public const int Index = 37;
public const int Num = 38;
public const int SceneWidth = 39;
public const int SceneHeight = 40;
public const int SceneCx = 41;
public const int SceneCy = 42;
public const int GroupIndex = 43;
public const int GroupCount = 44;
public const int TimelineTotalFrame = 45;
public const int TimelineTotalTime = 46;
public const int TimeRatio = 47;
public const int IsSaving = 48;
public const int IsPlaying = 49;
public const int IsPaused = 50;
public const int TimelineFrame = 51;
public const int TimelineTime = 52;
public const int FirstWritableField = X;
public const int LastWritableField = Rzr;
public static long BufferSize(int width, int height) =>
PixelOffset + (long)width * height * 4;
}
}
+106
ファイルの表示
@@ -0,0 +1,106 @@
using System;
namespace LuaScript.Engine
{
internal enum ScriptEngineKind
{
MoonSharp,
Native,
Gpu,
Cpu,
}
internal static class ScriptDirective
{
public static ScriptEngineKind Resolve(string? script) =>
TryGetDirective(script, out var kind) ? kind : ScriptEngineKind.MoonSharp;
public static ScriptEngineKind ResolveAuto(string? script)
{
if (TryGetDirective(script, out var kind))
return kind;
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));
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');
}
}
+6 -2
ファイルの表示
@@ -4,7 +4,7 @@
<TargetFramework>net10.0-windows10.0.19041.0</TargetFramework>
<UseWPF>true</UseWPF>
<ImplicitUsings>enable</ImplicitUsings>
<Version>1.2.0</Version>
<Version>1.3.0</Version>
<Platforms>AnyCPU;x64</Platforms>
<Nullable>enable</Nullable>
<AllowUnsafeBlocks>true</AllowUnsafeBlocks>
@@ -102,10 +102,14 @@
<Resource Include="Resources\SyntaxDefinitions\Lua-Light.xshd" />
<Resource Include="Resources\SyntaxDefinitions\Lua-Black.xshd" />
<Resource Include="Resources\SyntaxDefinitions\Lua-Windows.xshd" />
<None Include="..\native\luajit.exe" Link="native\luajit.exe" CopyToOutputDirectory="PreserveNewest" />
<None Include="..\native\lua51.dll" Link="native\lua51.dll" CopyToOutputDirectory="PreserveNewest" />
<None Include="..\native\worker.lua" Link="native\worker.lua" CopyToOutputDirectory="PreserveNewest" />
<None Include="..\native\shim.lua" Link="native\shim.lua" CopyToOutputDirectory="PreserveNewest" />
</ItemGroup>
<Target Name="PostBuild" AfterTargets="PostBuildEvent" Condition="'$(CI)' != 'true'">
<Exec Command="mkdir &quot;$(YMM4DirPath)user\plugin\$(ProjectName)&quot; &gt; NUL 2&gt;&amp;1&#xD;&#xA;copy &quot;$(TargetPath)&quot; &quot;$(YMM4DirPath)user\plugin\$(ProjectName)\&quot;" />
<Exec Command="mkdir &quot;$(YMM4DirPath)user\plugin\$(ProjectName)&quot; &gt; NUL 2&gt;&amp;1&#xD;&#xA;copy &quot;$(TargetPath)&quot; &quot;$(YMM4DirPath)user\plugin\$(ProjectName)\&quot;&#xD;&#xA;xcopy /E /I /Y &quot;$(TargetDir)native&quot; &quot;$(YMM4DirPath)user\plugin\$(ProjectName)\native&quot;" />
</Target>
</Project>
+162 -58
ファイルの表示
@@ -1,5 +1,7 @@
using System.IO;
using System.Numerics;
using System.Runtime.InteropServices;
using LuaScript.Engine;
using Vortice;
using Vortice.DCommon;
using Vortice.Direct2D1;
@@ -42,8 +44,26 @@ namespace LuaScript
DrawDescription InputDesc
);
private const int NativeTimeoutMilliseconds = 5000;
private static string NativeDirectory =>
Path.Combine(Path.GetDirectoryName(typeof(LuaScriptEffectProcessor).Assembly.Location) ?? AppContext.BaseDirectory, "native");
private readonly LuaScriptEngine _engine = new();
private readonly SemaphoreSlim _pixelLoaderSemaphore = new(1, 1);
private AviUtlScriptContext _context = new();
private LuaJitWorker? _nativeWorker;
private double[]? _nativeFields;
private bool _nativeWarned;
private EffectDescription? _frameDesc;
private SceneObjectResolver? _frameResolver;
private bool _frameResolverBuilt;
private Guid _lastSceneGuid;
private string _lastSceneId = string.Empty;
private bool _sceneIdCached;
private GraphicsDevicesAndContext? _ownCtx;
@@ -67,9 +87,31 @@ namespace LuaScript
{
_ownCtx = new GraphicsDevicesAndContext(devices);
disposer.Collect(_ownCtx);
_context.ResolverProvider = GetFrameResolver;
return null;
}
private SceneObjectResolver GetFrameResolver()
{
if (!_frameResolverBuilt)
{
_frameResolver = BuildSceneObjectResolver(_frameDesc!);
_frameResolverBuilt = true;
}
return _frameResolver!;
}
private string ResolveSceneId(Guid sceneId)
{
if (!_sceneIdCached || sceneId != _lastSceneGuid)
{
_lastSceneId = sceneId.ToString();
_lastSceneGuid = sceneId;
_sceneIdCached = true;
}
return _lastSceneId;
}
protected override void setInput(ID2D1Image? input)
{
if (!ReferenceEquals(_cachedInput, input))
@@ -113,10 +155,12 @@ namespace LuaScript
desc.TimelineDuration.Time.TotalSeconds,
inDesc);
var resolver = BuildSceneObjectResolver(desc);
_frameDesc = desc;
_frameResolver = null;
_frameResolverBuilt = false;
if (!_isFirst && key == _cachedKey &&
QueriesMatch(_cachedQueries, resolver))
(_cachedQueries.Length == 0 || QueriesMatch(_cachedQueries, GetFrameResolver())))
{
effectOutput = _cachedPixelsModified ? _transformEffect?.Output : null;
return _cachedOutputDesc ?? inDesc;
@@ -126,7 +170,8 @@ namespace LuaScript
int imgW = Math.Max(1, (int)Math.Ceiling(bounds.Right - bounds.Left));
int imgH = Math.Max(1, (int)Math.Ceiling(bounds.Bottom - bounds.Top));
var ctx = BuildContext(in key, imgW, imgH, resolver);
var ctx = _context;
PopulateContext(ctx, in key, imgW, imgH);
ctx.SetPixelLoader(() => LoadInputPixels(bounds, imgW, imgH));
DrawDescription outDesc = inDesc;
@@ -134,23 +179,43 @@ namespace LuaScript
try
{
_engine.Execute(script, ctx);
bool wantNative = ScriptDirective.ResolveAuto(script) == ScriptEngineKind.Native;
bool nativeReady = wantNative && LuaJitWorker.IsAvailable(NativeDirectory);
if (wantNative && !nativeReady)
WarnNativeUnavailableOnce();
if (ctx.IsPixelsDirty)
if (nativeReady)
{
EnsureBitmaps(imgW, imgH);
WritePixelsToOutput(ctx.GetPixelBuffer()!, imgW);
UpdateTransformEffect(bounds);
effectOutput = _transformEffect!.Output;
pixelsModified = true;
pixelsModified = ExecuteNative(script, ctx, bounds, imgW, imgH);
}
else
{
effectOutput = null;
_engine.Execute(script, ctx);
if (ctx.IsPixelsDirty)
{
EnsureBitmaps(imgW, imgH);
WritePixelsToOutput(ctx.GetPixelBuffer()!, imgW);
UpdateTransformEffect(bounds);
effectOutput = _transformEffect!.Output;
pixelsModified = true;
}
else
{
effectOutput = null;
}
}
outDesc = BuildOutputDesc(inDesc, ctx);
}
catch (LuaScriptTimeoutException ex)
{
effectOutput = null;
_context = new AviUtlScriptContext { ResolverProvider = GetFrameResolver };
_isFirst = true;
Log.Default.Write(ex.Message, ex);
return inDesc;
}
catch (LuaScriptException ex)
{
effectOutput = null;
@@ -165,7 +230,7 @@ namespace LuaScript
_isFirst = false;
_cachedKey = key;
_cachedQueries = [.. ctx.ObjectQueries];
_cachedQueries = ctx.ObjectQueries.Count == 0 ? [] : [.. ctx.ObjectQueries];
_cachedOutputDesc = outDesc;
_cachedPixelsModified = pixelsModified;
@@ -219,7 +284,7 @@ namespace LuaScript
return true;
}
private static AviUtlScriptContext BuildContext(in RenderKey key, int imgW, int imgH, SceneObjectResolver resolver)
private void PopulateContext(AviUtlScriptContext ctx, in RenderKey key, int imgW, int imgH)
{
var zoom = key.InputDesc.Zoom;
double zoomAvg = (zoom.X + zoom.Y) / 2d;
@@ -227,51 +292,49 @@ namespace LuaScript
? (zoom.X - zoom.Y) / (zoom.X + zoom.Y)
: 0d;
return new AviUtlScriptContext
{
ImageWidth = imgW,
ImageHeight = imgH,
X = key.InputDesc.Draw.X,
Y = key.InputDesc.Draw.Y,
Z = key.InputDesc.Draw.Z,
Ox = key.InputDesc.CenterPoint.X,
Oy = key.InputDesc.CenterPoint.Y,
Oz = 0d,
Sx = zoom.X,
Sy = zoom.Y,
Zoom = zoomAvg,
Aspect = aspect,
Alpha = key.InputDesc.Opacity * 255d,
Rx = key.InputDesc.Rotation.X,
Ry = key.InputDesc.Rotation.Y,
Rz = key.InputDesc.Rotation.Z,
Track0 = key.Track0,
Track1 = key.Track1,
Track2 = key.Track2,
Track3 = key.Track3,
Time = key.Time,
Frame = key.Frame,
TotalFrame = key.Length,
TotalTime = key.Fps > 0 ? key.Length / (double)key.Fps : 0d,
Framerate = key.Fps,
TimelineFrame = key.TimelineFrame,
TimelineTime = key.TimelineTime,
SceneWidth = key.SceneWidth,
SceneHeight = key.SceneHeight,
Layer = key.Layer,
Index = key.InputIndex,
Num = key.InputCount,
GroupIndex = key.GroupIndex,
GroupCount = key.GroupCount,
TimelineTotalFrame = key.TimelineTotalFrame,
TimelineTotalTime = key.TimelineTotalTime,
IsSaving = key.Usage == TimelineSourceUsage.Exporting,
IsPlaying = key.Usage == TimelineSourceUsage.Playing,
IsPaused = key.Usage == TimelineSourceUsage.Paused,
SceneId = key.SceneId.ToString(),
TimeRatio = key.Length > 0 ? key.Frame / (double)key.Length : 0d,
Resolver = resolver,
};
ctx.ClearQueries();
ctx.ImageWidth = imgW;
ctx.ImageHeight = imgH;
ctx.X = key.InputDesc.Draw.X;
ctx.Y = key.InputDesc.Draw.Y;
ctx.Z = key.InputDesc.Draw.Z;
ctx.Ox = key.InputDesc.CenterPoint.X;
ctx.Oy = key.InputDesc.CenterPoint.Y;
ctx.Oz = 0d;
ctx.Sx = zoom.X;
ctx.Sy = zoom.Y;
ctx.Zoom = zoomAvg;
ctx.Aspect = aspect;
ctx.Alpha = key.InputDesc.Opacity * 255d;
ctx.Rx = key.InputDesc.Rotation.X;
ctx.Ry = key.InputDesc.Rotation.Y;
ctx.Rz = key.InputDesc.Rotation.Z;
ctx.Track0 = key.Track0;
ctx.Track1 = key.Track1;
ctx.Track2 = key.Track2;
ctx.Track3 = key.Track3;
ctx.Time = key.Time;
ctx.Frame = key.Frame;
ctx.TotalFrame = key.Length;
ctx.TotalTime = key.Fps > 0 ? key.Length / (double)key.Fps : 0d;
ctx.Framerate = key.Fps;
ctx.TimelineFrame = key.TimelineFrame;
ctx.TimelineTime = key.TimelineTime;
ctx.SceneWidth = key.SceneWidth;
ctx.SceneHeight = key.SceneHeight;
ctx.Layer = key.Layer;
ctx.Index = key.InputIndex;
ctx.Num = key.InputCount;
ctx.GroupIndex = key.GroupIndex;
ctx.GroupCount = key.GroupCount;
ctx.TimelineTotalFrame = key.TimelineTotalFrame;
ctx.TimelineTotalTime = key.TimelineTotalTime;
ctx.IsSaving = key.Usage == TimelineSourceUsage.Exporting;
ctx.IsPlaying = key.Usage == TimelineSourceUsage.Playing;
ctx.IsPaused = key.Usage == TimelineSourceUsage.Paused;
ctx.SceneId = ResolveSceneId(key.SceneId);
ctx.TimeRatio = key.Length > 0 ? key.Frame / (double)key.Length : 0d;
}
private static DrawDescription BuildOutputDesc(DrawDescription inDesc, AviUtlScriptContext ctx)
@@ -286,6 +349,46 @@ namespace LuaScript
};
}
private void WarnNativeUnavailableOnce()
{
if (_nativeWarned) return;
_nativeWarned = true;
Log.Default.Write($"LuaScript: native runtime not found at '{NativeDirectory}'. Falling back to MoonSharp (slow). Deploy the 'native' folder next to the plugin.");
}
private bool ExecuteNative(string script, AviUtlScriptContext ctx, RawRectF bounds, int imgW, int imgH)
{
_nativeWorker ??= new LuaJitWorker(NativeDirectory);
_nativeFields ??= new double[NativeProtocol.FieldCount];
NativeFieldMap.ToFields(ctx, _nativeFields);
byte[] buffer = LoadInputPixels(bounds, imgW, imgH);
bool ok = _nativeWorker.Execute(
script, _nativeFields, buffer, imgW, imgH, NativeTimeoutMilliseconds, out bool dirty, out string? error);
if (!ok)
{
if (error is not null && error.Contains("timed out", StringComparison.Ordinal))
throw new LuaScriptTimeoutException(error);
throw new LuaScriptRuntimeException(error ?? "Native script execution failed.");
}
NativeFieldMap.FromFields(_nativeFields, ctx);
if (dirty)
{
EnsureBitmaps(imgW, imgH);
WritePixelsToOutput(buffer, imgW);
UpdateTransformEffect(bounds);
effectOutput = _transformEffect!.Output;
return true;
}
effectOutput = null;
return false;
}
private byte[] LoadInputPixels(RawRectF bounds, int width, int height)
{
_pixelLoaderSemaphore.Wait();
@@ -398,6 +501,7 @@ namespace LuaScript
if (disposing)
{
_engine.Dispose();
_nativeWorker?.Dispose();
_pixelLoaderSemaphore.Dispose();
_renderTarget?.Dispose();
_stagingBitmap?.Dispose();
+63 -62
ファイルの表示
@@ -1,4 +1,3 @@
using System.Collections.Concurrent;
using MoonSharp.Interpreter;
using MoonSharp.Interpreter.Debugging;
using MoonSharp.Interpreter.Loaders;
@@ -11,12 +10,6 @@ namespace LuaScript
LuaScriptException? Exception,
bool TimedOut);
private sealed record ExecutionJob(
string Code,
AviUtlScriptContext Context,
CancellationToken Cancellation,
TaskCompletionSource<ExecutionResult> Completion);
private sealed class ExecutionThread : IDisposable
{
private sealed class CancellationDebugger : IDebugger
@@ -46,10 +39,19 @@ namespace LuaScript
}
}
private readonly BlockingCollection<ExecutionJob> _queue = new(boundedCapacity: 1);
private readonly SemaphoreSlim _workSignal = new(0);
private readonly ManualResetEventSlim _doneSignal = new(false);
private readonly CancellationTokenSource _cts = new();
private readonly Thread _thread;
private readonly CancellationDebugger _debugger = new();
private string _jobCode = string.Empty;
private AviUtlScriptContext? _jobContext;
private LuaScriptException? _jobException;
private volatile bool _disposeRequested;
private readonly List<string> _removalBuffer = [];
private Script? _script;
private DynValue? _compiledChunk;
private string _lastCompiledCode = string.Empty;
@@ -67,6 +69,8 @@ namespace LuaScript
internal ExecutionThread()
{
_activeCancellation = _cts.Token;
_debugger.UpdateToken(_cts.Token);
_thread = new Thread(WorkerLoop)
{
IsBackground = true,
@@ -77,77 +81,65 @@ namespace LuaScript
internal ExecutionResult TryExecute(string code, AviUtlScriptContext ctx, int timeoutMs)
{
using var cts = new CancellationTokenSource();
var tcs = new TaskCompletionSource<ExecutionResult>(
TaskCreationOptions.RunContinuationsAsynchronously);
_jobCode = code;
_jobContext = ctx;
_jobException = null;
_doneSignal.Reset();
_workSignal.Release();
if (!_queue.TryAdd(new ExecutionJob(code, ctx, cts.Token, tcs)))
return new ExecutionResult(
new LuaScriptRuntimeException("Script execution queue is full."), false);
if (_doneSignal.Wait(timeoutMs))
return new ExecutionResult(_jobException, false);
if (tcs.Task.Wait(timeoutMs))
return tcs.Task.Result;
cts.Cancel();
_cts.Cancel();
return new ExecutionResult(null, TimedOut: true);
}
private void WorkerLoop()
{
try
while (true)
{
foreach (var job in _queue.GetConsumingEnumerable())
ProcessJob(job);
_workSignal.Wait();
if (_disposeRequested)
return;
ProcessJob();
_doneSignal.Set();
}
catch (OperationCanceledException) { }
catch (InvalidOperationException) { }
}
private void ProcessJob(ExecutionJob job)
private void ProcessJob()
{
if (job.Cancellation.IsCancellationRequested)
{
job.Completion.TrySetResult(new ExecutionResult(null, TimedOut: true));
return;
}
_activeCancellation = job.Cancellation;
_activeContext = job.Context;
_debugger.UpdateToken(job.Cancellation);
var context = _jobContext!;
_activeContext = context;
try
{
EnsureScript();
EnsureScriptIntegrity();
EnsureCompiled(job.Code);
SetupGlobals(job.Context);
EnsureCompiled(_jobCode);
SetupGlobals(context);
_script!.Call(_compiledChunk!);
ReadBackGlobals(job.Context);
job.Completion.TrySetResult(new ExecutionResult(null, false));
ReadBackGlobals(context);
_jobException = null;
}
catch (OperationCanceledException) when (job.Cancellation.IsCancellationRequested)
catch (OperationCanceledException) when (_cts.IsCancellationRequested)
{
job.Completion.TrySetResult(new ExecutionResult(null, TimedOut: true));
_jobException = null;
}
catch (LuaScriptException ex)
{
job.Completion.TrySetResult(new ExecutionResult(ex, false));
_jobException = ex;
}
catch (ScriptRuntimeException ex)
{
job.Completion.TrySetResult(new ExecutionResult(
new LuaScriptRuntimeException(ex.DecoratedMessage ?? ex.Message, ex), false));
_jobException = new LuaScriptRuntimeException(ex.DecoratedMessage ?? ex.Message, ex);
}
catch (Exception ex)
{
job.Completion.TrySetResult(new ExecutionResult(
new LuaScriptRuntimeException(ex.Message, ex), false));
_jobException = new LuaScriptRuntimeException(ex.Message, ex);
}
finally
{
_debugger.UpdateToken(default);
_activeContext = null;
_activeCancellation = default;
}
}
@@ -269,10 +261,10 @@ namespace LuaScript
_ymm4TableSnapshot = null;
}
ResetUserTableKeys(_objTable!, ref _objTableSnapshot);
ResetUserTableKeys(_sceneTable!, ref _sceneTableSnapshot);
ResetUserTableKeys(_animTable!, ref _animTableSnapshot);
ResetUserTableKeys(_ymm4Table!, ref _ymm4TableSnapshot);
ResetUserTableKeys(_objTable!, _objTableSnapshot);
ResetUserTableKeys(_sceneTable!, _sceneTableSnapshot);
ResetUserTableKeys(_animTable!, _animTableSnapshot);
ResetUserTableKeys(_ymm4Table!, _ymm4TableSnapshot);
}
script.Globals["time"] = ctx.Time;
@@ -366,34 +358,36 @@ namespace LuaScript
return keys;
}
private static void ResetUserTableKeys(Table table, ref HashSet<string>? snapshot)
private void ResetUserTableKeys(Table table, HashSet<string>? snapshot)
{
if (snapshot is null) return;
var keysToRemove = new List<string>();
var buffer = _removalBuffer;
buffer.Clear();
foreach (var key in table.Keys)
{
if (key.Type == DataType.String &&
!snapshot.Contains(key.String))
{
keysToRemove.Add(key.String);
buffer.Add(key.String);
}
}
foreach (var key in keysToRemove)
foreach (var key in buffer)
table[key] = DynValue.Nil;
}
private void ResetUserGlobals(Script script)
{
var keysToRemove = new List<string>();
var buffer = _removalBuffer;
buffer.Clear();
foreach (var key in script.Globals.Keys)
{
if (key.Type == DataType.String &&
!_builtinGlobalSnapshot!.Contains(key.String))
{
keysToRemove.Add(key.String);
buffer.Add(key.String);
}
}
foreach (var key in keysToRemove)
foreach (var key in buffer)
script.Globals[key] = DynValue.Nil;
}
@@ -531,18 +525,25 @@ namespace LuaScript
public void Dispose()
{
_queue.CompleteAdding();
_disposeRequested = true;
_workSignal.Release();
_thread.Join();
_queue.Dispose();
_cts.Cancel();
_cts.Dispose();
_workSignal.Dispose();
_doneSignal.Dispose();
}
internal void AbandonAsync()
{
_queue.CompleteAdding();
_disposeRequested = true;
_workSignal.Release();
ThreadPool.QueueUserWorkItem(_ =>
{
_thread.Join();
_queue.Dispose();
_cts.Dispose();
_workSignal.Dispose();
_doneSignal.Dispose();
});
}
@@ -577,7 +578,7 @@ namespace LuaScript
var stale = _executionThread;
_executionThread = new ExecutionThread();
stale.AbandonAsync();
throw new LuaScriptRuntimeException(
throw new LuaScriptTimeoutException(
$"Script execution timed out after {ExecutionTimeoutMilliseconds} ms.");
}
+2
ファイルの表示
@@ -5,4 +5,6 @@ namespace LuaScript
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);
}
+27 -2
ファイルの表示
@@ -30,6 +30,7 @@ YukkuriMovieMaker4(YMM4)上で動作する、**Luaスクリプトでオブ
- [7. スクリプトエディタの支援機能](#7-スクリプトエディタの支援機能)
- [8. インポート・エクスポート・クリア](#8-インポートエクスポートクリア)
5. [実行モデル](#実行モデル)
- [実行エンジンの自動振り分け](#実行エンジンの自動振り分け)
- [実行スレッドとタイムアウト](#実行スレッドとタイムアウト)
- [実行結果のキャッシュ](#実行結果のキャッシュ)
- [グローバル変数のリセットと整合性チェック](#グローバル変数のリセットと整合性チェック)
@@ -74,7 +75,7 @@ YukkuriMovieMaker4(YMM4)上で動作する、**Luaスクリプトでオブ
### 1. スクリプトエンジン
スクリプトの実行エンジンには MoonSharp(Lua 5.2 互換)を使用しています。利用可能な標準ライブラリは以下に限定されています。
スクリプトの実行エンジンには MoonSharp(Lua 5.2 互換)を使用しています。加えて、ピクセル操作(`obj.getpixel` / `obj.setpixel` / `obj.getpixeldata`)を含むスクリプトは、同梱した高速ランタイム(LuaJIT)で自動的に実行され、大幅に高速化されます(詳細は[実行エンジンの自動振り分け](#実行エンジンの自動振り分け)を参照)。どちらのエンジンでも利用可能な標準ライブラリは以下に限定されています。
- `table`、`string`、`math`、`bit32`
- 基本関数: `type`、`tostring`、`tonumber`、`select`、`error`、`assert`、`print`、`ipairs`、`pairs`、`next`、`unpack`、`setmetatable`、`getmetatable`、`rawget`、`rawset`、`rawequal`、`rawlen`、`pcall`、`xpcall`
@@ -108,6 +109,8 @@ YukkuriMovieMaker4(YMM4)上で動作する、**Luaスクリプトでオブ
- **`obj.putpixeldata()`**: 互換性のために定義された空実装関数です。`setpixel` / `PixelDataProxy:set` による変更は自動的に反映されるため、呼び出す必要はありません。
`getpixel` / `setpixel` / `getpixeldata` のいずれかを最初に呼び出した時点で、GPU 上の画像データを CPU 側へ転送する処理が一度だけ発生します。ピクセル操作を行わないスクリプトではこの転送は発生しません。
これらのピクセル操作を含むスクリプトは、同梱の高速ランタイム(LuaJIT)で自動的に実行され、従来エンジンに比べて大幅(内部計測で数十倍)に高速化されます。出力結果は従来エンジンと一致します。詳細・制約は[実行エンジンの自動振り分け](#実行エンジンの自動振り分け)を参照してください。
### 4. scene テーブルと ymm4 テーブル
`scene` テーブルにはシーン(プロジェクト)の解像度情報が格納されています。いずれも読み取り専用です。
@@ -188,6 +191,28 @@ YukkuriMovieMaker4(YMM4)上で動作する、**Luaスクリプトでオブ
## 実行モデル
### 実行エンジンの自動振り分け
スクリプトは内容に応じて 2 つのエンジンへ自動的に振り分けられます。
- **ピクセル操作を含むスクリプト**(`obj.getpixel` / `obj.setpixel` / `obj.getpixeldata` を含む)→ 同梱の高速ランタイム **LuaJIT** で実行(ネイティブ実行)。
- **変形のみのスクリプト** → 従来の **MoonSharp** で実行。
スクリプトの先頭行に次のディレクティブを書くと、エンジンを明示指定できます。
- `--!native` … 高速ランタイム(LuaJIT)で実行
- `--!moonsharp` … 従来エンジン(MoonSharp)で実行
ネイティブ実行は**専用の別プロセス**で行われ、ピクセルバッファは共有メモリ経由で受け渡されます。スクリプトが無限ループに陥った場合でも **5 秒のタイムアウトでプロセスを強制終了**するため本体は固まらず、終了後は自動的に復帰します。出力結果は従来エンジンと一致します。
ネイティブ実行には次の制約があります。
- **`obj.getobject` は使用できません**(常に `nil` を返します)。他オブジェクトを参照するスクリプトはピクセル操作と併用しないか、`--!moonsharp` を明示してください。
- `bit32` は正しい Lua 5.2 の挙動になります。実用域(0〜2³¹未満の値・0〜31 のシフト量)では従来と一致しますが、`bit32.lshift(1, 32)` のような範囲外の特殊ケースのみ結果が変わります(ネイティブ=0、従来=1)。
- `math.random` は両エンジンとも毎フレーム `frame` でシードし直す決定論的乱数ですが、乱数列の実装が異なるためエンジンをまたぐと同じシードでも値が変わります。エンジン非依存の乱数が必要な場合は `anim.rand(min, max, seed)` を使用してください。
> 高速ランタイム(`luajit.exe` / `lua51.dll` 等)はプラグインに同梱され、本体と同じ場所の `native` フォルダーへ自動配置されます。手動インストールは不要です。
### 実行スレッドとタイムアウト
スクリプトはエフェクトインスタンスごとに確保された専用のバックグラウンドスレッド上で実行されます。実行要求は容量 1 のキューを介してこのスレッドへ渡され、メイン側は実行完了またはタイムアウトまで待機します。
@@ -298,7 +323,7 @@ obj.alpha = anim.ease_out(t) * 255
- **AviUtl 非対応**: 本プラグインは独自のスクリプト実行系であり、AviUtl 向けの EXO 出力(`.exo`)には対応していません。
- **実行タイムアウト**: スクリプトの実行は 5000ms(5秒)でタイムアウトし、超過した場合は強制終了されエラーとして扱われます。無限ループが発生しないよう注意してください。
- **利用可能な標準ライブラリの制限**: `table`、`string`、`math`、`bit32` および基本関数のみ利用できます。`io`、`os`、`debug`、`ffi`、`require` は利用できません。
- **ピクセル操作の負荷**: `obj.getpixel` / `obj.setpixel` / `obj.getpixeldata` は実際の入力画像にアクセスするため、各フレームで最初に呼び出した際に GPU→CPU へのデータ転送が発生します。不要な場合は呼び出しを省略することで処理を高速化できます。
- **ピクセル操作の負荷**: `obj.getpixel` / `obj.setpixel` / `obj.getpixeldata` は実際の入力画像にアクセスするため、各フレームで最初に呼び出した際に GPU→CPU へのデータ転送が発生します。不要な場合は呼び出しを省略することで処理を高速化できます。これらを含むスクリプトは高速ランタイム(LuaJIT)で自動実行され大幅に高速化されますが、**ネイティブ実行では `obj.getobject` が使用できません**(`nil` を返します)。他オブジェクトの参照と併用する場合は `--!moonsharp` を明示してください。詳細は[実行エンジンの自動振り分け](#実行エンジンの自動振り分け)を参照。
- **`math.random` はフレームごとの決定論的な乱数**: 毎フレーム `frame` の値でシードし直されるため、同一フレームでは常に同じ値になります。フレームをまたいで変化する乱数的な値が必要な場合は `anim.rand` の利用を検討してください。
- **`obj.oz` は出力に反映されません**: スクリプト実行後にコンテキストへ読み戻されますが、現在の実装では中心点オフセットの出力計算に使用されていません。
- **エクスポートは先頭の1件のみ**: 複数アイテムを選択した状態でも、エクスポートされるスクリプトは先頭のアイテムのもののみです(インポート・クリアは選択中のすべてのアイテムに適用されます)。
+1
ファイルの表示
@@ -0,0 +1 @@
luascript.routersys.com
バイナリ
ファイルの表示
バイナリファイルは表示されません。
バイナリ
ファイルの表示
バイナリファイルは表示されません。
+25
ファイルの表示
@@ -0,0 +1,25 @@
local shimPath = arg[1]
local vectorsPath = arg[2]
assert(loadfile(shimPath))()
local f = assert(io.open(vectorsPath, "r"))
local out = {}
for line in f:lines() do
local chunk = loadstring("return " .. line)
if not chunk then
out[#out + 1] = "ERROR"
else
local ok, res = pcall(chunk)
if not ok then
out[#out + 1] = "ERROR"
elseif type(res) == "boolean" then
out[#out + 1] = res and "true" or "false"
else
out[#out + 1] = string.format("%.17g", res)
end
end
end
f:close()
io.write(table.concat(out, "\n"))
+347
ファイルの表示
@@ -0,0 +1,347 @@
local ffi = require("ffi")
local bit = require("bit")
local i64 = ffi.typeof("int64_t")
local u32 = ffi.typeof("uint32_t")
local u64 = ffi.typeof("uint64_t")
local function tou(d)
return tonumber(u32(i64(d)))
end
local function umul32(a, b)
return tonumber(u32(u64(a) * u64(b)))
end
local function mask(width)
if width <= 0 then return 0 end
if width >= 32 then return tou(0xFFFFFFFF) end
return bit.lshift(1, width) - 1
end
local function validate(pos, width)
if pos < 0 or width < 1 or pos + width > 32 then
error("trying to access non-existent bits")
end
end
bit32 = {}
function bit32.band(...) return tou(bit.band(...)) end
function bit32.bor(...) return tou(bit.bor(...)) end
function bit32.bxor(...) return tou(bit.bxor(...)) end
function bit32.btest(...) return tou(bit.band(...)) ~= 0 end
function bit32.bnot(x) return tou(bit.bnot(x)) end
function bit32.lshift(x, n)
if n <= -32 or n >= 32 then return 0 end
if n >= 0 then return tou(bit.lshift(x, n)) end
return tou(bit.rshift(x, -n))
end
function bit32.rshift(x, n) return bit32.lshift(x, -n) end
function bit32.arshift(x, n)
if n < 0 then return bit32.lshift(x, -n) end
if n > 31 then n = 31 end
return tou(bit.arshift(x, n))
end
function bit32.lrotate(x, n) return tou(bit.rol(x, n)) end
function bit32.rrotate(x, n) return tou(bit.ror(x, n)) end
function bit32.extract(v, pos, width)
width = width or 1
validate(pos, width)
return tou(bit.band(bit.rshift(v, pos), mask(width)))
end
function bit32.replace(v, u, pos, width)
width = width or 1
validate(pos, width)
local m = bit.lshift(mask(width), pos)
return tou(bit.bor(bit.band(v, bit.bnot(m)), bit.band(bit.lshift(u, pos), m)))
end
if rawlen == nil then
rawlen = function(x)
local t = type(x)
if t == "table" then return #x end
if t == "string" then return string.len(x) end
error("table or string expected")
end
end
local floor = math.floor
local abs = math.abs
local sqrt = math.sqrt
local sin = math.sin
local cos = math.cos
local fmod = math.fmod
local pi = math.pi
local tau = pi * 2
local function clamp(v, lo, hi)
if v < lo then return lo end
if v > hi then return hi end
return v
end
anim = {}
anim.tau = tau
anim.e = math.exp(1)
anim.phi = (1 + sqrt(5)) / 2
anim.sqrt2 = sqrt(2)
function anim.lerp(a, b, t) return a + (b - a) * t end
function anim.smoothstep(e0, e1, x)
local span = e1 - e0
local t = span == 0 and 0 or clamp((x - e0) / span, 0, 1)
return t * t * (3 - 2 * t)
end
function anim.smootherstep(e0, e1, x)
local span = e1 - e0
local t = span == 0 and 0 or clamp((x - e0) / span, 0, 1)
return t * t * t * (t * (6 * t - 15) + 10)
end
function anim.clamp(v, lo, hi) return clamp(v, lo, hi) end
function anim.map(v, a1, b1, a2, b2)
local range = b1 - a1
if range == 0 then return a2 end
return a2 + (b2 - a2) * (v - a1) / range
end
function anim.norm(v, lo, hi)
local span = hi - lo
if span == 0 then return 0 end
return (v - lo) / span
end
function anim.wrap(v, lo, hi)
local range = hi - lo
if range <= 0 then return lo end
local result = fmod(v - lo, range)
if result < 0 then result = result + range end
return lo + result
end
function anim.pingpong(t, length)
if length <= 0 then return 0 end
local v = fmod(t, 2 * length)
if v < 0 then v = v + 2 * length end
if v > length then return 2 * length - v end
return v
end
function anim.sign(v)
if v > 0 then return 1 end
if v < 0 then return -1 end
return 0
end
function anim.oscillate(t, lo, hi, freq)
local wave = (sin(t * freq * tau) + 1) / 2
return lo + (hi - lo) * wave
end
function anim.triangle(t, freq)
local f = t * freq
f = f - floor(f)
return 1 - 2 * abs(f - 0.5)
end
function anim.square(t, freq)
local f = t * freq
f = f - floor(f)
return f >= 0.5 and 1 or 0
end
function anim.duration(t, dur)
if dur <= 0 then return 1 end
return clamp(t / dur, 0, 1)
end
function anim.delay(t, d) return math.max(0, t - d) end
function anim.ease_in(t) return t * t end
function anim.ease_out(t)
local inv = 1 - t
return 1 - inv * inv
end
function anim.ease_in_out(t)
if t < 0.5 then return 2 * t * t end
local inv = -2 * t + 2
return 1 - inv * inv / 2
end
function anim.elastic(t)
t = clamp(t, 0, 1)
if t == 0 then return 0 end
if t == 1 then return 1 end
return 2 ^ (-10 * t) * sin((t * 10 - 0.75) * (tau / 3)) + 1
end
function anim.back(t)
local c1 = 1.70158
local c3 = c1 + 1
local inv = t - 1
return 1 + c3 * inv * inv * inv + c1 * inv * inv
end
function anim.step(edge, x) return x >= edge and 1 or 0 end
function anim.fract(v) return v - floor(v) end
function anim.bounce(t)
local n1 = 7.5625
local d1 = 2.75
t = clamp(t, 0, 1)
if t < 1 / d1 then return n1 * t * t end
if t < 2 / d1 then
t = t - 1.5 / d1
return n1 * t * t + 0.75
end
if t < 2.5 / d1 then
t = t - 2.25 / d1
return n1 * t * t + 0.9375
end
t = t - 2.625 / d1
return n1 * t * t + 0.984375
end
function anim.hsv_to_rgb(h, s, v)
local c = v * s
local x = c * (1 - abs(fmod(h / 60, 2) - 1))
local m = v - c
local sector = floor(h / 60) % 6
local r, g, b
if sector == 0 then r, g, b = c, x, 0
elseif sector == 1 then r, g, b = x, c, 0
elseif sector == 2 then r, g, b = 0, c, x
elseif sector == 3 then r, g, b = 0, x, c
elseif sector == 4 then r, g, b = x, 0, c
else r, g, b = c, 0, x end
return (r + m) * 255, (g + m) * 255, (b + m) * 255
end
function anim.rgb_to_hsv(r, g, b)
r = r / 255; g = g / 255; b = b / 255
local max = math.max(r, g, b)
local min = math.min(r, g, b)
local delta = max - min
local h = 0
if delta > 0 then
if max == r then
h = 60 * fmod(fmod((g - b) / delta, 6) + 6, 6)
elseif max == g then
h = 60 * ((b - r) / delta + 2)
else
h = 60 * ((r - g) / delta + 4)
end
end
return h, max > 0 and delta / max or 0, max
end
function anim.len(x, y) return sqrt(x * x + y * y) end
function anim.dist(x1, y1, x2, y2)
local dx = x2 - x1
local dy = y2 - y1
return sqrt(dx * dx + dy * dy)
end
function anim.dot(x1, y1, x2, y2) return x1 * x2 + y1 * y2 end
function anim.normalize(x, y)
local m = sqrt(x * x + y * y)
if m == 0 then return 0, 0 end
return x / m, y / m
end
function anim.polar(r, a)
local rad = a * pi / 180
return r * cos(rad), r * sin(rad)
end
function anim.rotate(x, y, a)
local rad = a * pi / 180
local c = cos(rad)
local s = sin(rad)
return x * c - y * s, x * s + y * c
end
function anim.bezier(t, p0, p1, p2, p3)
t = clamp(t, 0, 1)
local inv = 1 - t
local b0 = inv * inv * inv
local b1 = 3 * inv * inv * t
local b2 = 3 * inv * t * t
local b3 = t * t * t
return b0 * p0 + b1 * p1 + b2 * p2 + b3 * p3
end
function anim.rand(...)
local a = { ... }
local n = select("#", ...)
if n == 0 then return 0 end
local min, max, seed = 0, 1, 0
if n == 1 then
seed = a[1]
elseif n == 2 then
max, seed = a[1], a[2]
else
min, max, seed = a[1], a[2], a[3]
end
local p = ffi.new("double[1]", seed)
local w = ffi.cast("uint32_t*", p)
local lo, hi = tonumber(w[0]), tonumber(w[1])
local h = umul32(tou(bit.bxor(lo, hi)), 374761393)
h = umul32(tou(bit.bxor(h, bit.rshift(h, 13))), 1274126177)
local r = tou(bit.bxor(h, bit.rshift(h, 16))) / 4294967295.0
return min + r * (max - min)
end
local function noise_hash(x, y, z)
local n = tou(umul32(tou(x), 374761393) + umul32(tou(y), 668265263) + umul32(tou(z), 1013904223))
n = umul32(tou(bit.bxor(n, bit.rshift(n, 13))), 1274126177)
return tou(bit.bxor(n, bit.rshift(n, 16))) / 4294967295.0
end
function anim.noise(x, y, z)
y = y or 0
z = z or 0
local xi = floor(x)
local yi = floor(y)
local zi = floor(z)
local xf = x - xi
local yf = y - yi
local zf = z - zi
local u = xf * xf * (3 - 2 * xf)
local v = yf * yf * (3 - 2 * yf)
local w = zf * zf * (3 - 2 * zf)
local c000 = noise_hash(xi, yi, zi)
local c100 = noise_hash(xi + 1, yi, zi)
local c010 = noise_hash(xi, yi + 1, zi)
local c110 = noise_hash(xi + 1, yi + 1, zi)
local c001 = noise_hash(xi, yi, zi + 1)
local c101 = noise_hash(xi + 1, yi, zi + 1)
local c011 = noise_hash(xi, yi + 1, zi + 1)
local c111 = noise_hash(xi + 1, yi + 1, zi + 1)
local x00 = c000 + u * (c100 - c000)
local x10 = c010 + u * (c110 - c010)
local x01 = c001 + u * (c101 - c001)
local x11 = c011 + u * (c111 - c011)
local y0 = x00 + v * (x10 - x00)
local y1 = x01 + v * (x11 - x01)
return y0 + w * (y1 - y0)
end
+235
ファイルの表示
@@ -0,0 +1,235 @@
local ffi = require("ffi")
ffi.cdef [[
typedef void* HANDLE;
HANDLE OpenFileMappingA(unsigned long, int, const char*);
void* MapViewOfFile(HANDLE, unsigned long, unsigned long, unsigned long, size_t);
int UnmapViewOfFile(const void*);
int CloseHandle(HANDLE);
HANDLE OpenEventA(unsigned long, int, const char*);
unsigned long WaitForSingleObject(HANDLE, unsigned long);
int SetEvent(HANDLE);
unsigned long GetLastError();
]]
local k32 = ffi.load("kernel32")
local FILE_MAP_ALL_ACCESS = 0x000F001F
local EVENT_ALL_ACCESS = 0x1F0003
local INFINITE = 0xFFFFFFFF
local mapName = arg[1]
local mapSize = tonumber(arg[2])
local workEventName = arg[3]
local doneEventName = arg[4]
local shimPath = arg[5]
local hMap = k32.OpenFileMappingA(FILE_MAP_ALL_ACCESS, 0, mapName)
assert(hMap ~= nil, "OpenFileMapping failed")
local view = k32.MapViewOfFile(hMap, FILE_MAP_ALL_ACCESS, 0, 0, mapSize)
assert(view ~= nil, "MapViewOfFile failed")
local workEvent = k32.OpenEventA(EVENT_ALL_ACCESS, 0, workEventName)
local doneEvent = k32.OpenEventA(EVENT_ALL_ACCESS, 0, doneEventName)
assert(workEvent ~= nil and doneEvent ~= nil, "OpenEvent failed")
local base = ffi.cast("uint8_t*", view)
local i32 = ffi.cast("int32_t*", base)
local f64 = ffi.cast("double*", base + 64)
local OFF_COMMAND = 1
local OFF_STATUS = 2
local OFF_WIDTH = 3
local OFF_HEIGHT = 4
local OFF_SCRIPTLEN = 5
local OFF_PIXELSDIRTY = 6
local OFF_ERRORLEN = 7
local SCRIPT_OFFSET = 64 + 64 * 8
local ERROR_OFFSET = SCRIPT_OFFSET + 128 * 1024
local PIXEL_OFFSET = ERROR_OFFSET + 4 * 1024
local FIRST_WRITABLE = 8
local LAST_WRITABLE = 25
assert(loadfile(shimPath))()
local clamp = function(v, lo, hi)
if v < lo then return lo end
if v > hi then return hi end
return v
end
local width, height = 0, 0
local pixels = ffi.cast("uint8_t*", base + PIXEL_OFFSET)
local dirty = false
local obj = {}
local scene = {}
local ymm4 = {}
function obj.getpixel(x, y)
x = math.floor(x); y = math.floor(y)
if x < 0 or y < 0 or x >= width or y >= height then return 0, 0, 0, 0 end
local p = pixels + (y * width + x) * 4
local a = p[3]
if a <= 0 then return 0, 0, 0, 0 end
local s = 255 / a
return clamp(p[2] * s, 0, 255), clamp(p[1] * s, 0, 255), clamp(p[0] * s, 0, 255), a
end
function obj.setpixel(x, y, r, g, b, a)
x = math.floor(x); y = math.floor(y)
if x < 0 or y < 0 or x >= width or y >= height then return end
a = a or 255
dirty = true
local aK = clamp(a, 0, 255) / 255
local p = pixels + (y * width + x) * 4
p[0] = math.floor(clamp(b * aK, 0, 255))
p[1] = math.floor(clamp(g * aK, 0, 255))
p[2] = math.floor(clamp(r * aK, 0, 255))
p[3] = math.floor(clamp(a, 0, 255))
end
function obj.getpixeldata()
local total = width * height * 4
local buf = pixels
local pd = { width = width, height = height }
function pd:get(index)
local zb = index - 1
if zb < 0 or zb >= total then return 0 end
local pi = math.floor(zb / 4)
local ch = zb - pi * 4
local p = buf + pi * 4
local a = p[3]
if ch == 3 then return a end
if a <= 0 then return 0 end
local sc = 255 / a
if ch == 0 then return clamp(p[2] * sc, 0, 255) end
if ch == 1 then return clamp(p[1] * sc, 0, 255) end
return clamp(p[0] * sc, 0, 255)
end
function pd:set(index, value)
local zb = index - 1
if zb < 0 or zb >= total then return end
dirty = true
local pi = math.floor(zb / 4)
local ch = zb - pi * 4
local p = buf + pi * 4
local clamped = clamp(value, 0, 255)
if ch == 3 then
local oldA = p[3]
local newA = clamped
if oldA > 0 and newA > 0 then
local f = newA / oldA
p[0] = math.floor(clamp(p[0] * f, 0, 255))
p[1] = math.floor(clamp(p[1] * f, 0, 255))
p[2] = math.floor(clamp(p[2] * f, 0, 255))
elseif newA <= 0 then
p[0] = 0; p[1] = 0; p[2] = 0
end
p[3] = math.floor(newA)
else
local a = p[3]
local pm = clamped * (a / 255)
local bo = (ch == 0) and 2 or ((ch == 1) and 1 or 0)
p[bo] = math.floor(clamp(pm, 0, 255))
end
end
return pd
end
function obj.putpixeldata() end
function obj.getobject() return nil end
local sandbox = {
obj = obj, scene = scene, ymm4 = ymm4,
anim = anim, bit32 = bit32, rawlen = rawlen,
math = math, string = string, table = table,
type = type, tostring = tostring, tonumber = tonumber, select = select,
error = error, assert = assert, ipairs = ipairs, pairs = pairs, next = next,
unpack = unpack, setmetatable = setmetatable, getmetatable = getmetatable,
rawget = rawget, rawset = rawset, rawequal = rawequal, rawlen = rawlen,
pcall = pcall, xpcall = xpcall, print = function() end,
}
sandbox._G = sandbox
local compiledCode, compiledChunk
local function loadFields()
width = i32[OFF_WIDTH]
height = i32[OFF_HEIGHT]
obj.w = f64[0]; obj.h = f64[1]; obj.hw = f64[2]; obj.hh = f64[3]
obj.cx = f64[4]; obj.cy = f64[5]; obj.cz = f64[6]; obj.diagonal = f64[7]
obj.x = f64[8]; obj.y = f64[9]; obj.z = f64[10]
obj.ox = f64[11]; obj.oy = f64[12]; obj.oz = f64[13]
obj.sx = f64[14]; obj.sy = f64[15]; obj.sz = f64[16]
obj.zoom = f64[17]; obj.aspect = f64[18]; obj.alpha = f64[19]
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.track0 = f64[26]; obj.track1 = f64[27]; obj.track2 = f64[28]; obj.track3 = f64[29]
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]
scene.width = f64[39]; scene.height = f64[40]; scene.cx = f64[41]; scene.cy = f64[42]
ymm4.group_index = f64[43]; ymm4.group_count = f64[44]
ymm4.timeline_totalframe = f64[45]; ymm4.timeline_totaltime = f64[46]
ymm4.time_ratio = f64[47]
ymm4.is_saving = f64[48] ~= 0; ymm4.is_playing = f64[49] ~= 0; ymm4.is_paused = f64[50] ~= 0
ymm4.group_ratio = (f64[44] ~= 0) and (f64[43] / f64[44]) or 0
obj.timelineframe = f64[51]; obj.timelinetime = f64[52]
end
local function storeFields()
for i = FIRST_WRITABLE, LAST_WRITABLE do
local key
if i == 8 then key = obj.x elseif i == 9 then key = obj.y elseif i == 10 then key = obj.z
elseif i == 11 then key = obj.ox elseif i == 12 then key = obj.oy elseif i == 13 then key = obj.oz
elseif i == 14 then key = obj.sx elseif i == 15 then key = obj.sy elseif i == 16 then key = obj.sz
elseif i == 17 then key = obj.zoom elseif i == 18 then key = obj.aspect elseif i == 19 then key = obj.alpha
elseif i == 20 then key = obj.rx elseif i == 21 then key = obj.ry elseif i == 22 then key = obj.rz
elseif i == 23 then key = obj.rxr elseif i == 24 then key = obj.ryr elseif i == 25 then key = obj.rzr end
f64[i] = tonumber(key) or f64[i]
end
end
while true do
k32.WaitForSingleObject(workEvent, INFINITE)
if i32[OFF_COMMAND] == 1 then break end
dirty = false
local scriptLen = i32[OFF_SCRIPTLEN]
local code = ffi.string(base + SCRIPT_OFFSET, scriptLen)
if code ~= compiledCode then
local chunk, err = loadstring(code, "LuaScript")
if chunk then
compiledChunk = chunk
compiledCode = code
else
compiledChunk = nil
local msg = err or "compile error"
ffi.copy(base + ERROR_OFFSET, msg, math.min(#msg, 4096))
i32[OFF_ERRORLEN] = math.min(#msg, 4096)
i32[OFF_STATUS] = 2
k32.SetEvent(doneEvent)
end
end
if compiledChunk and code == compiledCode then
loadFields()
math.randomseed(f64[31])
setfenv(compiledChunk, sandbox)
local ok, err = pcall(compiledChunk)
if ok then
storeFields()
i32[OFF_PIXELSDIRTY] = dirty and 1 or 0
i32[OFF_STATUS] = 1
else
local msg = tostring(err)
ffi.copy(base + ERROR_OFFSET, msg, math.min(#msg, 4096))
i32[OFF_ERRORLEN] = math.min(#msg, 4096)
i32[OFF_STATUS] = 2
end
k32.SetEvent(doneEvent)
end
end
k32.UnmapViewOfFile(view)
k32.CloseHandle(hMap)
+42
ファイルの表示
@@ -0,0 +1,42 @@
local ffi = require("ffi")
ffi.cdef [[
typedef void* HANDLE;
HANDLE OpenFileMappingA(unsigned long dwDesiredAccess, int bInheritHandle, const char* lpName);
void* MapViewOfFile(HANDLE hFileMappingObject, unsigned long dwDesiredAccess, unsigned long dwFileOffsetHigh, unsigned long dwFileOffsetLow, size_t dwNumberOfBytesToMap);
int UnmapViewOfFile(const void* lpBaseAddress);
int CloseHandle(HANDLE hObject);
unsigned long GetLastError();
]]
local k32 = ffi.load("kernel32")
local FILE_MAP_ALL_ACCESS = 0x000F001F
local name = arg[1]
local size = tonumber(arg[2])
local h = k32.OpenFileMappingA(FILE_MAP_ALL_ACCESS, 0, name)
if h == nil then error("OpenFileMapping failed: " .. tonumber(k32.GetLastError())) end
local p = k32.MapViewOfFile(h, FILE_MAP_ALL_ACCESS, 0, 0, size)
if p == nil then
k32.CloseHandle(h)
error("MapViewOfFile failed: " .. tonumber(k32.GetLastError()))
end
local buf = ffi.cast("uint8_t*", p)
local pixels = size / 4
for i = 0, pixels - 1 do
local b = buf[i * 4]
local g = buf[i * 4 + 1]
local r = buf[i * 4 + 2]
local gray = math.floor(r * 0.299 + g * 0.587 + b * 0.114 + 0.5)
if gray > 255 then gray = 255 end
buf[i * 4] = gray
buf[i * 4 + 1] = gray
buf[i * 4 + 2] = gray
end
k32.UnmapViewOfFile(p)
k32.CloseHandle(h)
io.write("done")