コミットを比較

...
65 コミット
作成者 SHA1 メッセージ 日付
routersys e685e7aa40 バージョンをv1.13.3へ更新
リリース / build-and-release (workflow_dispatch) Actions がタグ v1.13.3 のコミットから作成しました
2026-07-03 08:57:03 +09:00
routersys bf49fe9984 入力補完へ obj テーブルの関数 12 件を追加 2026-07-03 08:57:03 +09:00
routersys c05a1479f9 ワーカーの setfont 引数変換の等価性テストを追加 2026-07-03 08:57:02 +09:00
routersys 80ddb663b0 AviUtlFontState の変換規則と床剰余セマンティクスのテストを追加 2026-07-03 08:57:02 +09:00
routersys 2f1bbc3828 setfont へ型検査と数値変換を導入し ffi 変換エラーを排除 2026-07-03 08:57:02 +09:00
routersys e911f6e83f フォント状態を AviUtlFontState への委譲へ変更 2026-07-03 08:48:05 +09:00
routersys 6162ce5c19 setfont の引数解釈を AviUtlFontState へ抽出し床剰余でスタイルを判定 2026-07-03 08:47:57 +09:00
routersys 59dcb82b49 バージョンをv1.13.2へ更新
リリース / build-and-release (workflow_dispatch) Actions がタグ v1.13.2 のコミットから作成しました
2026-07-03 08:31:31 +09:00
routersys d37726cdf6 scene テーブルのテストをスコープ付きセッションへ追随 2026-07-03 08:31:16 +09:00
routersys 0c09cf4a51 セッションのテストへスコープ分離と後戻りシークとレイヤー優先の検証を追加 2026-07-03 08:30:56 +09:00
routersys 0d4809924d ストアのテストをランダムシークの決定論とレイヤー競合と履歴上限の検証へ書き換え 2026-07-03 08:30:49 +09:00
routersys 1e97e7d8fe 描画デバイスをスコープとして引き当てキャッシュ検証を履歴照合へ変更 2026-07-03 08:30:38 +09:00
routersys 06cfefe1b4 シーン共有値のスコープを保持し未使用の SceneValuesWritten を削除 2026-07-03 08:30:31 +09:00
routersys 37b1371f57 セッションへスコープとレイヤーを導入し発行を履歴への即時確定へ変更 2026-07-03 08:30:24 +09:00
routersys 9db756c974 シーン共有値ストアをフレーム索引付きの履歴方式へ再設計 2026-07-03 08:30:15 +09:00
routersys 43f3161ebb バージョンをv1.13.1へ更新
リリース / build-and-release (workflow_dispatch) Actions がタグ v1.13.1 のコミットから作成しました
2026-07-03 08:04:35 +09:00
routersys 4b3b74edae README の scene.set / scene.get の説明を新しいセマンティクスへ更新 2026-07-03 07:54:18 +09:00
routersys 5129ece749 全言語ドキュメントへ scene 共有値の可視性と出力時リセットを追記 2026-07-03 07:53:32 +09:00
routersys 24ef4135cf サイトへ scene.set / scene.get の可視性の規則と説明、制限を追記 2026-07-03 07:53:18 +09:00
routersys 044fdbf1eb ワーカーのシーン共有値テストへ IPC 回数と最大長往復の検証を追加 2026-07-03 07:52:50 +09:00
routersys 9e1ad6c133 scene テーブルのテストをセッション経由の検証へ書き換え 2026-07-03 07:52:40 +09:00
routersys 6d8def9f08 SceneValueSession の可視性とトランザクション性のテストを追加 2026-07-03 07:52:32 +09:00
routersys 7a9f1ff6e8 ストアのテストを世代・出力リセット・容量上限の検証へ書き換え 2026-07-03 07:52:18 +09:00
routersys 82db144b86 scene.set / scene.get へ実行内キャッシュと UTF-8 境界の切り詰めを追加 2026-07-03 07:52:08 +09:00
routersys d3fb73ed94 コールバックタグ領域を8192バイトへ拡張 2026-07-03 07:52:00 +09:00
routersys 7dd777fbc6 シーン共有値の発行を実行成功時のみに限定しキャッシュ検証を世代対応へ変更 2026-07-03 07:51:52 +09:00
routersys aa17df08d8 シーン共有値のアクセスを SceneValueSession への委譲へ変更 2026-07-03 07:51:42 +09:00
routersys e5c4485f16 アイテム単位の書き込みバッファと読み取りメモ化を担う SceneValueSession を追加 2026-07-03 07:51:33 +09:00
routersys 9b901f91b6 シーン共有値ストアを世代スナップショット方式へ再設計 2026-07-03 07:51:26 +09:00
routersys 2b24a407e6 バージョンをv1.13.0へ更新
リリース / build-and-release (workflow_dispatch) Actions がタグ v1.13.0 のコミットから作成しました
2026-07-02 23:33:31 +09:00
routersys 150b4818d4 README へ scene.set / scene.get と AviUtl 互換グローバル関数を追記 2026-07-02 23:20:29 +09:00
routersys 34b7d60ca6 サイトへ scene.set / scene.get とグローバル関数を追記 2026-07-02 23:18:24 +09:00
routersys 7dc6083fd7 全言語ドキュメントへ scene.set / scene.get とグローバル関数を追記 2026-07-02 23:17:26 +09:00
routersys 245fb9c323 テストレーンへグローバル関数登録と time_ratio を追加 2026-07-02 23:16:52 +09:00
routersys 42c3bc4f4b ネイティブワーカーの scene.set / scene.get 往復テストを追加 2026-07-02 23:16:20 +09:00
routersys d273f99593 グローバル関数のエンジン間等価性テストを追加 2026-07-02 23:15:48 +09:00
routersys e1763e0c81 scene.set / scene.get 登録のテストを追加 2026-07-02 23:14:35 +09:00
routersys 7221ce3aca シーン共有値のテストを追加 2026-07-02 23:14:08 +09:00
routersys 5f3ad96ea2 ネイティブワーカーへ scene.set / scene.get のブリッジとグローバル関数の公開を追加 2026-07-02 23:13:47 +09:00
routersys 4e0bf831c5 ネイティブ shim へ RGB / HSV などのグローバル関数と debug_print を追加 2026-07-02 23:13:27 +09:00
routersys 0fedfd5804 補完候補へ scene.set / scene.get とグローバル関数を追加 2026-07-02 23:13:08 +09:00
routersys f11225e2a1 LuaJIT ワーカーへ scene.set / scene.get のコールバック処理を追加 2026-07-02 23:12:36 +09:00
routersys 92e8c43160 ネイティブ経路へ scene 取得・設定のコールバック種別を追加 2026-07-02 23:12:23 +09:00
routersys 5fb9eae7a0 シーン共有値の変化を検知してフレームキャッシュを無効化 2026-07-02 23:12:00 +09:00
routersys f109232cae MoonSharp へ scene.set / scene.get と AviUtl 互換グローバル関数を登録 2026-07-02 23:11:44 +09:00
routersys 1596a048cd スクリプトコンテキストへシーン共有値の取得・書き込みと変化追跡を追加 2026-07-02 23:11:22 +09:00
routersys 0b0c795d7a debug_print 向けの OutputDebugString 出力を追加 2026-07-02 23:11:05 +09:00
routersys 2be3c3d28b AviUtl 互換グローバル関数と debug_print の登録処理を追加 2026-07-02 23:10:46 +09:00
routersys 3f9e4ebca4 AviUtl 互換の RGB / HSV / OR / AND / XOR / SHIFT を実装 2026-07-02 23:10:26 +09:00
routersys 03042b17e7 scene テーブルへ scene.set / scene.get の登録処理を追加 2026-07-02 23:10:10 +09:00
routersys 5e6d74dfee シーン単位で値を共有するストア SceneSharedValues を追加 2026-07-02 23:09:49 +09:00
routersys 40d68416c2 サイトへGPUカーネルの自動選択とSIMD判定記述を追加 2026-07-02 20:47:41 +09:00
routersys de6472c34b バージョンをv1.12.0へ更新
リリース / build-and-release (workflow_dispatch) Actions がタグ v1.12.0 のコミットから作成しました
2026-07-02 19:54:36 +09:00
routersys 55c8bffb70 SIMD経路の採用を初回フレームの実測で自動判定 2026-07-02 19:52:59 +09:00
routersys 8ca66bceb8 ネイティブ画素転送をD2DステージングとMMFの直結へ変更 2026-07-02 19:28:01 +09:00
routersys 865f5117ea カーネル抽出の検査漏れとfmodの剰余実装を修正 2026-07-02 19:04:05 +09:00
routersys b30f7a818b drawリングの読み出し件数を容量へクランプ 2026-07-02 19:03:41 +09:00
routersys 95786a1f0a getpixeldataの遅延書き込みをフレーム置換時に破棄 2026-07-02 19:03:23 +09:00
routersys cc07e2a83d CPUカーネルにVector256のSIMD経路を追加 2026-07-02 18:36:43 +09:00
routersys 08e5e432b7 getpixeldata添字ループをカーネル抽出へ対応 2026-07-02 17:48:59 +09:00
routersys 1e9b039cef draw/drawpolyをMMFリングバッファでバッチ化 2026-07-02 17:26:12 +09:00
routersys bad39fe0db getpixeldataをストレートFFI配列の遅延反映へ変更 2026-07-02 14:39:22 +09:00
routersys a5567a804d copybufferの複製をバッファ再利用へ変更 2026-07-02 14:20:01 +09:00
routersys a9cb4a9cda RenderKeyのスクリプト比較を参照バージョンへ変更 2026-07-02 14:17:57 +09:00
routersys 9e9b5277af スクリプト本文をバージョンスタンプで変更時のみ転送 2026-07-02 14:16:09 +09:00
54個のファイルの変更、4392行の追加、410行の削除

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

+27 -56
ファイルの表示
@@ -1,75 +1,46 @@
# v1.11.4 - Lua スクリプト for YMM4
# v1.13.3 - Lua スクリプト for YMM4
毎ピクセル処理のスクリプト(カーネル)の実行先を、GPU と CPU から自動で選べるように
したリリースです。これまで GPU カーネルは `--!gpu` を明示したときだけ使っていましたが、
指定が無いときも利用できるかを自動で判断し、利用できる場合は GPU で実行します。正確性を
最優先し、初回に実機の GPU で CPU カーネルとの出力一致を検証し、許容差に収まった
プログラムだけ GPU で実行します。あわせて、GPU カーネルと CPU カーネルで食い違って
いた HLSL の座標原点と出力の丸めを、CPU カーネルに合わせて修正しました。
obj.setfont の引数の解釈を MoonSharp とネイティブの両エンジンで統一したリリースです。
これまで両エンジンは通常の呼び出しでは同じ結果を返していましたが、引数へ想定外の型や値を渡した場合の挙動が食い違っており、ネイティブエンジンにはスクリプト全体をエラーにする経路が存在しました。今回から、どのような引数を渡しても両エンジンが同一の結果を返します。
あわせて、スクリプトエディタの入力補完へ、ドキュメントに記載済みで未登録だった obj テーブルの関数 12 件を追加しました。
呼び出しの書き方と関数の引数に変更はありません。通常の使い方への影響はありません。
---
## 改善
## 動作の変更
### 1. カーネルの GPU/CPU 自動選択
### 1. obj.setfont の引数の解釈を両エンジンで統一
これまで毎ピクセル処理のスクリプトは、`--!gpu` を明示したときだけ GPU カーネルで実行し、
指定が無いときは CPU カーネルで実行していました。本リリースでは、指定が無いときも
GPU カーネルを利用できるかを自動で判断し、利用できる場合は GPU で実行します。GPU
カーネルは CPU カーネルが必要とするピクセルの読み戻しとアップロードを伴わないため、
そのぶん高速です。実行先はプログラム単位で一度だけ決まり、フレームや画像サイズによって
切り替わらないため、途中で結果がちらつくことはありません。
obj.setfont(フォント名, サイズ, スタイル, 色) の各引数について、想定外の型や値を渡した場合の挙動を次のとおり統一しました。
### 2. 実行時のセルフ検証で正確性を担保
- フォント名へ数値を渡した場合、両エンジンとも文字列へ変換して採用します。これまで MoonSharp は無視し、ネイティブは真偽値やテーブルまで文字列化していました。文字列と数値以外の値は両エンジンとも無視し、直前の設定を保持します。
- サイズへ数値文字列を渡した場合、両エンジンとも数値へ変換して採用します。これまでネイティブは文字列のまま保持し、後続の obj.load("text") の呼び出しでスクリプト全体が実行時エラーになっていました。数値へ変換できない値は両エンジンとも無視し、直前の設定を保持します。
- スタイルへ数値へ変換できない値を渡した場合、両エンジンとも無視して直前の設定を保持します。これまで MoonSharp は 0 として太字と斜体を解除し、ネイティブは実行時エラーになっていました。
- スタイルの小数と負数は、両エンジンとも床関数で整数化してからビットを判定します。これまで MoonSharp はゼロ方向への切り捨てを行っており、負の小数で結果が食い違っていました。
- スタイルへ NaN・無限大・2^53 を超える数値を渡した場合も、両エンジンとも同一の結果(太字と斜体の解除)になります。これまで MoonSharp は変換の飽和により値ごとに異なるフラグが立つことがありました。
- 色へ数値へ変換できない値を渡した場合、両エンジンとも無視して直前の設定を保持します。
GPU カーネルを初めて構築したとき、固定の 64×64 の検証用画像を実機の GPU で処理し、
その結果を CPU カーネルの結果と比較します。全チャンネルの差が許容範囲に収まった
プログラムだけを GPU で実行し、収まらない場合や検証を実行できない場合は CPU カーネルで
実行します。GPU の出力が CPU カーネルと食い違うことはありません。検証の結果はログに
記録します。
### 2. スクリプトエディタの入力補完へ obj テーブルの関数 12 件を追加
---
## 不具合修正
### GPU カーネルの座標原点のずれを修正
GPU カーネルの HLSL は、ピクセル座標を「テクスチャ座標 × 寸法」で求めていました。
テクスチャ座標はピクセルの中心を指すため、求まる座標は CPU カーネルが用いる整数の
添字より 0.5 大きく、ループ変数 `x`・`y` を参照するスクリプトで結果がずれていました。
テクスチャ座標から 0.5 を引くように変更し、CPU カーネルの整数座標と一致させました。
### GPU カーネルの出力の丸めを修正
Direct2D は出力を四捨五入で 8 ビットへ量子化する一方、CPU カーネルは切り捨てていた
ため、両者に系統的な 1 階調のずれがありました。シェーダ側で各チャンネルを切り捨てて
から量子化するように変更し、丸め方を CPU カーネルへ統一しました。
ドキュメントに記載済みで入力補完に未登録だった次の関数を、候補へ追加しました。
obj.getobject、obj.putpixeldata、obj.setfont、obj.draw、obj.drawpoly、obj.copybuffer、obj.getvalue、obj.setoption、obj.getoption、obj.pixeloption、obj.setanchor、obj.effect の 12 件です。
並び順はドキュメントの「obj テーブル - 関数」の記載順に合わせています。
---
## 互換性・後方互換
- スクリプトの書き方と API に変更はありません。
- `--!cpu` は従来どおり CPU カーネルで実行します。`--!gpu` は GPU カーネルで実行しますが、
検証に通らない場合は CPU カーネルへ切り替え、一度だけ警告を記録します。
- 指定の無いカーネルは、検証に通れば GPU、通らなければ CPU で実行します。いずれも
出力は CPU カーネルと許容差の範囲で一致します。
- GPU カーネルは浮動小数点で計算するため、CPU カーネルと 1 階調程度異なることが
あります。この差が許容範囲に収まることを検証で確認したプログラムだけを GPU で
実行します。
- GPU を利用できない環境では、従来どおり CPU カーネルで実行します。
- 呼び出しの書き方と関数の引数に変更はありません。フォント名に文字列、サイズ・スタイル・色に数値を渡す通常の使い方の結果は変わりません。
- 引数を省略した場合と nil を渡した場合は、両エンジンとも直前の設定を保持します。
- フォントの既定値(フォント名なし・サイズ 34・標準スタイル・色 0xFFFFFF)と、実行ごとに既定値へ戻る仕様は変わりません。
- scene.set / scene.get を含む v1.13.2 の仕様に変更はありません。
---
## 内部実装
- `HlslKernelEmitter` の座標を「テクスチャ座標 × 寸法 - 0.5」へ、出力の各チャンネルを
`floor(clamp(...))` へ変更し、CPU カーネルの整数座標と切り捨てへ揃えました。
- `GpuKernel` へ `Verify` を追加しました。検証用画像を効果で描画して読み戻し、
`CpuKernel` の結果と比較します。差が許容範囲に収まらない場合は GPU カーネルを
採用しません。
- `LuaScriptEffectProcessor` の `GetGpuKernel` は検証に通った GPU カーネルだけを返し、
判定をプログラム単位でキャッシュします。`ExecuteKernelLane` は指定が無いときと
`--!gpu` のときに検証済みの GPU カーネルを優先し、無ければ CPU カーネルで実行します。
- テストへ HLSL の座標原点と出力の丸めを検証するケースを追加しました(全 2994 件)。
GPU カーネルの実行と検証は実機の GPU が必要なため、YMM4 上での確認が対象です。
- MoonSharp 側の setfont の引数解釈とフォント状態を AviUtlFontState として独立した型へ抽出しました。LuaScriptEngine はフォントの 5 つのフィールドを持たず、この型へ委譲します。テストレーンはソースリンク方式で LuaScriptEngine を参照できないため、SceneTableRegistrar と同じ「純粋な単位を切り出してリンクする」構成に従ったものです。
- スタイルのビット判定は Lua の剰余と同じ床剰余(値 - floor(値 / 除数) * 除数)で行います。C# の変換の飽和(NaN が 0、範囲外が最大値へ丸められる仕様)を経由しないため、非有限値と巨大な値でも LuaJIT の math.floor と剰余の結果に一致します。
- worker.lua の setfont へ型検査と tonumber による変換を導入しました。フォント名は文字列と数値のみ受理し、サイズ・スタイル・色は数値へ変換できた場合のみ採用します。変換できない値が共有メモリの数値領域へ渡って ffi の変換エラーになる経路を排除しました。
- 入力補完は LuaAutoCompletionStrategy の obj 名前空間の候補配列への追加のみで、補完の仕組みに変更はありません。
- テストは 3092 件です。v1.13.2 の 3086 件から、AviUtlFontState の既定値とリセット、引数の変換規則、負数スタイルの床セマンティクス、非有限値の扱いの検証と、ネイティブワーカーで同一の呼び出し列を実行して同じ期待値と照合する等価性の検証を追加しました。
+1 -1
ファイルの表示
@@ -1,5 +1,5 @@
========================================
Luaスクリプト for YMM4 v1.11.4
Luaスクリプト for YMM4 v1.13.3
========================================
YukkuriMovieMaker4(YMM4)上で動作する、Luaスクリプトで映像エフェクトのパラメータや
ピクセルを直接制御できるプラグインです。
+90
ファイルの表示
@@ -0,0 +1,90 @@
using MoonSharp.Interpreter;
namespace LuaScript.Tests
{
public class AviUtlFontStateTests
{
private static (string Family, double Size, bool Bold, bool Italic, int Color) Snapshot(AviUtlFontState state) =>
(state.Family, state.Size, state.Bold, state.Italic, state.Color);
private static DynValue NewTable() => DynValue.NewTable(new Script());
private static DynValue NewFunction() => DynValue.NewCallback((_, _) => DynValue.Void);
[Fact]
public void Defaults_MatchWorkerDefaults()
{
var state = new AviUtlFontState();
Assert.Equal((string.Empty, 34d, false, false, 0xFFFFFF), Snapshot(state));
}
[Fact]
public void Reset_RestoresDefaults()
{
var state = new AviUtlFontState();
state.Apply(DynValue.NewString("Meiryo"), DynValue.NewNumber(40), DynValue.NewNumber(3), DynValue.NewNumber(0x112233));
state.Reset();
Assert.Equal((string.Empty, 34d, false, false, 0xFFFFFF), Snapshot(state));
}
[Fact]
public void Apply_CoercesArgumentsLikeNativeWorker()
{
var state = new AviUtlFontState();
state.Apply(DynValue.NewString("Meiryo"), DynValue.NewNumber(40), DynValue.NewNumber(3), DynValue.NewNumber(0x112233));
Assert.Equal(("Meiryo", 40d, true, true, 0x112233), Snapshot(state));
state.Apply(DynValue.NewNumber(123), DynValue.NewString("48"), DynValue.Nil, DynValue.Nil);
Assert.Equal(("123", 48d, true, true, 0x112233), Snapshot(state));
state.Apply(DynValue.True, DynValue.False, NewTable(), NewFunction());
Assert.Equal(("123", 48d, true, true, 0x112233), Snapshot(state));
state.Apply(DynValue.Nil, DynValue.Nil, DynValue.NewNumber(-1.5), DynValue.Nil);
Assert.Equal(("123", 48d, false, true, 0x112233), Snapshot(state));
state.Apply(DynValue.NewString("X"), DynValue.NewNumber(20), DynValue.NewNumber(0), DynValue.NewNumber(0));
Assert.Equal(("X", 20d, false, false, 0), Snapshot(state));
}
[Fact]
public void Apply_NegativeStyles_UseFloorSemantics()
{
var state = new AviUtlFontState();
state.Apply(DynValue.Nil, DynValue.Nil, DynValue.NewNumber(-1d), DynValue.Nil);
Assert.True(state.Bold);
Assert.True(state.Italic);
state.Apply(DynValue.Nil, DynValue.Nil, DynValue.NewNumber(-2d), DynValue.Nil);
Assert.False(state.Bold);
Assert.True(state.Italic);
state.Apply(DynValue.Nil, DynValue.Nil, DynValue.NewNumber(-3d), DynValue.Nil);
Assert.True(state.Bold);
Assert.False(state.Italic);
}
[Fact]
public void Apply_NonFiniteAndHugeStyles_ClearFlagsWithoutError()
{
var state = new AviUtlFontState();
state.Apply(DynValue.Nil, DynValue.Nil, DynValue.NewNumber(3d), DynValue.Nil);
state.Apply(DynValue.Nil, DynValue.Nil, DynValue.NewNumber(double.NaN), DynValue.Nil);
Assert.False(state.Bold);
Assert.False(state.Italic);
state.Apply(DynValue.Nil, DynValue.Nil, DynValue.NewNumber(3d), DynValue.Nil);
state.Apply(DynValue.Nil, DynValue.Nil, DynValue.NewNumber(1e300), DynValue.Nil);
Assert.False(state.Bold);
Assert.False(state.Italic);
state.Apply(DynValue.Nil, DynValue.Nil, DynValue.NewNumber(3d), DynValue.Nil);
state.Apply(DynValue.Nil, DynValue.Nil, DynValue.NewNumber(double.PositiveInfinity), DynValue.Nil);
Assert.False(state.Bold);
Assert.False(state.Italic);
}
}
}
+196
ファイルの表示
@@ -0,0 +1,196 @@
using System.Globalization;
using LuaScript.Compat;
namespace LuaScript.Tests
{
public class AviUtlGlobalEquivalenceTests
{
private static readonly double[] s_bitValues =
[
0d, 1d, 5d, 8d, 3d, 12d, 6d, 25d, 11d, 91d,
-1d, -5d, -91d, 255d, 256d, 65535d,
0.4d, 0.5d, 0.6d, 2.5d, 2.51d, -2.5d, -2.51d,
2147483647d, -2147483648d, 2147483648d, -2147483649d, 1e18d, -1e18d,
];
private static readonly double[] s_shiftValues =
[
0d, 1d, 2d, 3d, 5d, 31d, 32d, 33d, 63d,
-1d, -2d, -5d, -31d, -32d, -33d, -63d,
0.5d, 1.5d, -0.5d,
];
[Fact]
public void BitFunctions_MatchDocumentedExamples()
{
var lane = new MoonSharpLane();
Assert.Equal(11d, lane.Number("OR(8,3)"));
Assert.Equal(4d, lane.Number("AND(12,6)"));
Assert.Equal(18d, lane.Number("XOR(25,11)"));
Assert.Equal(40d, lane.Number("SHIFT(5,3)"));
Assert.Equal(22d, lane.Number("SHIFT(91,-2)"));
Assert.Equal(-2147483648d, lane.Number("SHIFT(1,31)"));
Assert.Equal(2d, lane.Number("OR(2.50,0)"));
Assert.Equal(3d, lane.Number("OR(2.51,0)"));
}
[Fact]
public void ColorFunctions_MatchDocumentedExamples()
{
var lane = new MoonSharpLane();
Assert.Equal(0x40C0FF, lane.Number("RGB(64,192,255)"));
Assert.Equal([0d, 128d, 255d], lane.Tuple("RGB(0x0080FF)", 3));
Assert.Equal(0xFFFF00, lane.Number("HSV(60,100,100)"));
Assert.Equal([210d, 100d, 100d], lane.Tuple("HSV(0x0080FF)", 3));
}
[Fact]
public void Interpolation_UsesTimeRatio()
{
var lane = new MoonSharpLane { TimeRatio = 0.25 };
Assert.Equal(
AviUtlGlobalFunctions.RgbInterpolate(64, 192, 255, 128, 64, 0, 0.25),
lane.Number("RGB(64,192,255,128,64,0)"));
Assert.Equal(
AviUtlGlobalFunctions.HsvInterpolate(30, 50, 100, 120, 100, 50, 0.25),
lane.Number("HSV(30,50,100,120,100,50)"));
lane.TimeRatio = 0d;
Assert.Equal(lane.Number("RGB(64,192,255)"), lane.Number("RGB(64,192,255,128,64,0)"));
lane.TimeRatio = 1d;
Assert.Equal(lane.Number("RGB(128,64,0)"), lane.Number("RGB(64,192,255,128,64,0)"));
}
[Fact]
public void MoonSharp_MatchesOracle_OverBitMatrix()
{
var lane = new MoonSharpLane();
foreach (var a in s_bitValues)
{
foreach (var b in s_bitValues)
{
string sa = Format(a);
string sb = Format(b);
Assert.Equal(AviUtlGlobalFunctions.BitOr(a, b), lane.Number($"OR({sa},{sb})"));
Assert.Equal(AviUtlGlobalFunctions.BitAnd(a, b), lane.Number($"AND({sa},{sb})"));
Assert.Equal(AviUtlGlobalFunctions.BitXor(a, b), lane.Number($"XOR({sa},{sb})"));
}
foreach (var shift in s_shiftValues)
{
Assert.Equal(
AviUtlGlobalFunctions.BitShift(a, shift),
lane.Number($"SHIFT({Format(a)},{Format(shift)})"));
}
}
}
[Fact]
public void MoonSharp_MatchesOracle_OverColorMatrix()
{
var lane = new MoonSharpLane();
double[] channels = [0d, 1d, 63.5d, 64d, 128d, 254.9d, 255d, 256d, -1d, 1000d];
foreach (var r in channels)
{
foreach (var g in channels)
{
Assert.Equal(
AviUtlGlobalFunctions.RgbCompose(r, g, 200d),
lane.Number($"RGB({Format(r)},{Format(g)},200)"));
}
}
double[] hues = [0d, 30d, 59.9d, 60d, 60.1d, 120d, 180d, 209.88d, 240d, 300d, 359.9d, 360d, 361d, -30d, 720.5d];
double[] ratios = [0d, 25d, 50d, 99.5d, 100d, 101d, -5d];
foreach (var h in hues)
{
foreach (var s in ratios)
{
Assert.Equal(
AviUtlGlobalFunctions.HsvCompose(h, s, 80d),
lane.Number($"HSV({Format(h)},{Format(s)},80)"));
}
}
int[] colors = [0x000000, 0xFFFFFF, 0x0080FF, 0x40C0FF, 0xFF0000, 0x00FF00, 0x0000FF, 0x123456, 0x808080, 0xFFFF00];
foreach (var color in colors)
{
AviUtlGlobalFunctions.RgbComponents(color, out int r, out int g, out int b);
Assert.Equal([r, g, b], lane.Tuple($"RGB({color})", 3));
AviUtlGlobalFunctions.HsvComponents(color, out int h, out int s, out int v);
Assert.Equal([h, s, v], lane.Tuple($"HSV({color})", 3));
}
}
[Fact]
public void LuaJitShim_MatchesOracle()
{
var jit = new LuaJitLane();
Assert.True(jit.Available, "native/luajit.exe must be present");
var expressions = new List<string>();
var expected = new List<double>();
foreach (var a in s_bitValues)
{
foreach (var b in s_bitValues)
{
expressions.Add($"OR({Format(a)},{Format(b)})");
expected.Add(AviUtlGlobalFunctions.BitOr(a, b));
expressions.Add($"AND({Format(a)},{Format(b)})");
expected.Add(AviUtlGlobalFunctions.BitAnd(a, b));
expressions.Add($"XOR({Format(a)},{Format(b)})");
expected.Add(AviUtlGlobalFunctions.BitXor(a, b));
}
foreach (var shift in s_shiftValues)
{
expressions.Add($"SHIFT({Format(a)},{Format(shift)})");
expected.Add(AviUtlGlobalFunctions.BitShift(a, shift));
}
}
double[] channels = [0d, 1d, 63.5d, 64d, 128d, 254.9d, 255d, 256d, -1d, 1000d];
foreach (var r in channels)
{
expressions.Add($"RGB({Format(r)},192,255)");
expected.Add(AviUtlGlobalFunctions.RgbCompose(r, 192d, 255d));
}
double[] hues = [0d, 30d, 59.9d, 60d, 60.1d, 120d, 180d, 209.88d, 240d, 300d, 359.9d, 360d, 361d, -30d, 720.5d];
foreach (var h in hues)
{
expressions.Add($"HSV({Format(h)},100,100)");
expected.Add(AviUtlGlobalFunctions.HsvCompose(h, 100d, 100d));
}
int[] colors = [0x000000, 0xFFFFFF, 0x0080FF, 0x40C0FF, 0xFF0000, 0x00FF00, 0x0000FF, 0x123456, 0x808080, 0xFFFF00];
foreach (var color in colors)
{
for (int component = 1; component <= 3; component++)
{
expressions.Add($"select({component}, RGB({color}))");
AviUtlGlobalFunctions.RgbComponents(color, out int r, out int g, out int b);
expected.Add(component == 1 ? r : component == 2 ? g : b);
expressions.Add($"select({component}, HSV({color}))");
AviUtlGlobalFunctions.HsvComponents(color, out int h, out int s, out int v);
expected.Add(component == 1 ? h : component == 2 ? s : v);
}
}
expressions.Add("(function() aviutl_set_time_ratio(0.25) return RGB(64,192,255,128,64,0) end)()");
expected.Add(AviUtlGlobalFunctions.RgbInterpolate(64, 192, 255, 128, 64, 0, 0.25));
expressions.Add("(function() aviutl_set_time_ratio(0.75) return HSV(30,50,100,120,100,50) end)()");
expected.Add(AviUtlGlobalFunctions.HsvInterpolate(30, 50, 100, 120, 100, 50, 0.75));
var results = jit.Eval(expressions);
Assert.True(results.Length >= expressions.Count, "luajit runner returned fewer results than expressions");
for (int i = 0; i < expressions.Count; i++)
{
double actual = double.Parse(results[i], CultureInfo.InvariantCulture);
Assert.True(expected[i] == actual, $"{expressions[i]}: expected {expected[i]}, got {actual}");
}
}
private static string Format(double value) =>
value.ToString("R", CultureInfo.InvariantCulture);
}
}
+79
ファイルの表示
@@ -21,6 +21,8 @@ namespace LuaScript.Tests
[InlineData("for y=0,obj.h-1 do for x=0,obj.w-1 do local r,g,b,a=obj.getpixel(x,y) local v=(r+g+b)/3 obj.setpixel(x,y,v>128 and 255 or 0,v>128 and 255 or 0,v>128 and 255 or 0,a) end end")]
[InlineData("for y=0,obj.h-1 do for x=0,obj.w-1 do local r,g,b,a=obj.getpixel(x,y) obj.setpixel(x,y,math.min(255,r+50),math.max(0,g-50),math.floor(b/16)*16,a) end end")]
[InlineData("for y=0,obj.h-1 do for x=0,obj.w-1 do local r,g,b,a=obj.getpixel(x,y) obj.setpixel(x,y,r%64,math.abs(g-128),math.sqrt(b*255),a) end end")]
[InlineData("local x=99 local k=3 for y=0,obj.h-1 do for x=0,obj.w-1 do local r,g,b,a=obj.getpixel(x,y) obj.setpixel(x,y,x/obj.w*255+k,g,b,a) end end")]
[InlineData("for y=0,obj.h-1 do for x=0,obj.w-1 do local r,g,b,a=obj.getpixel(x,y) obj.setpixel(x,y,math.fmod(r,64),math.fmod(g,7)*36,math.fmod(b-128,60)+128,a) end end")]
public void CpuKernelMatchesMoonSharp(string script)
{
var fields = new Dictionary<string, double> { ["w"] = Width, ["h"] = Height };
@@ -38,6 +40,31 @@ namespace LuaScript.Tests
AssertEquivalent(script, fields, globals);
}
[Theory]
[InlineData("local pd=obj.getpixeldata() for y=0,pd.height-1 do for x=0,pd.width-1 do local i=(y*pd.width+x)*4 local r=pd:get(i+1) local g=pd:get(i+2) local b=pd:get(i+3) pd:set(i+1,255-r) pd:set(i+2,255-g) pd:set(i+3,255-b) end end")]
[InlineData("local pd=obj.getpixeldata() for y=0,obj.h-1 do for x=0,obj.w-1 do local i=(y*obj.w+x)*4 local r=pd:get(i+1) local g=pd:get(i+2) local b=pd:get(i+3) local l=0.298912*r+0.586611*g+0.114478*b pd:set(i+1,l) pd:set(i+2,l) pd:set(i+3,l) end end")]
[InlineData("local pd=obj.getpixeldata() for y=0,pd.height-1 do for x=0,pd.width-1 do local i=(y*pd.width+x)*4 local r=pd:get(i+1) local g=pd:get(i+2) local b=pd:get(i+3) pd:set(i+1,b) pd:set(i+2,g) pd:set(i+3,r) end end")]
[InlineData("local pd=obj.getpixeldata() for y=0,obj.h-1 do for x=0,obj.w-1 do local i=(y*obj.w+x)*4 local r=pd:get(i+1) local a=pd:get(i+4) pd:set(i+1,r*a/255) pd:set(i+2,pd:get(i+2)*obj.track0/100) pd:set(i+3,math.min(255,pd:get(i+3)+50)) end end")]
[InlineData("local pd=obj.getpixeldata() for y=0,pd.height-1 do for x=0,pd.width-1 do local i=(y*pd.width+x)*4 local r=pd:get(i+1) local g=pd:get(i+2) local b=pd:get(i+3) pd:set(i+1,r*3) pd:set(i+2,g-300) pd:set(i+3,b*2-255) end end")]
public void GetPixelDataKernelMatchesMoonSharp(string script)
{
var fields = new Dictionary<string, double> { ["w"] = Width, ["h"] = Height, ["track0"] = 73d };
AssertEquivalent(script, fields, new Dictionary<string, double>());
}
[Theory]
[InlineData("local pd=obj.getpixeldata() for y=0,pd.height-1 do for x=0,pd.width-1 do local i=(y*pd.width+x)*4 pd:set(i+4,128) end end")]
[InlineData("local pd=obj.getpixeldata() for y=0,pd.height-1 do for x=0,pd.width-1 do local i=(y*pd.width+x)*4 pd:set(i+1,pd:get(i+5)) pd:set(i+2,0) pd:set(i+3,0) end end")]
[InlineData("local pd=obj.getpixeldata() for y=0,pd.height-1 do for x=0,pd.width-1 do local i=((y+1)*pd.width+x)*4 pd:set(i+1,0) pd:set(i+2,0) pd:set(i+3,0) end end")]
[InlineData("local pd=obj.getpixeldata() for y=0,pd.height-1 do for x=0,pd.width-1 do local i=(y*pd.width+x)*4 pd:set(i+1,pd:get(i+3)) pd:set(i+2,pd:get(i+2)) pd:set(i+3,pd:get(i+1)) end end")]
[InlineData("local pd=obj.getpixeldata() for y=0,pd.height-1 do for x=0,pd.width-1 do local i=(y*pd.width+x)*4 local i=i+4 pd:set(i+1,0) pd:set(i+2,0) pd:set(i+3,0) end end")]
[InlineData("local pd=obj.getpixeldata() for y=0,pd.height-1 do for pd=0,pd.width-1 do local i=(y*2+pd)*4 pd:set(i+1,0) pd:set(i+2,0) pd:set(i+3,0) end end")]
[InlineData("local pd=obj.getpixeldata() for y=0,pd.height-1 do for x=0,pd.width-1 do local i=(y*pd.width+x)*4 local pd=0 pd:set(i+1,0) end end")]
public void GetPixelDataNonKernelScriptsAreRejected(string script)
{
Assert.Null(KernelExtractor.TryExtract(script));
}
[Theory]
[InlineData("--!cpu\nfor y=0,obj.h-1 do for x=0,obj.w-1 do local r,g,b,a=obj.getpixel(x,y) obj.setpixel(x,y,255-r,255-g,255-b,a) end end")]
[InlineData("--!gpu\nfor y=0,obj.h-1 do for x=0,obj.w-1 do local r,g,b,a=obj.getpixel(x,y) local l=0.298912*r+0.586611*g+0.114478*b obj.setpixel(x,y,l,l,l,a) end end")]
@@ -107,6 +134,8 @@ namespace LuaScript.Tests
private static void RunMoonSharp(string script, byte[] buffer, Dictionary<string, double> fields, Dictionary<string, double> globals)
{
var engine = new Script(CoreModules.Basic | CoreModules.Math | CoreModules.Bit32);
engine.Globals.Get("math").Table["fmod"] = DynValue.NewCallback((_, a) =>
DynValue.NewNumber(a[0].Number % a[1].Number));
var obj = new Table(engine);
foreach (var (name, value) in fields)
obj[name] = value;
@@ -134,10 +163,60 @@ namespace LuaScript.Tests
return DynValue.Void;
});
obj["getpixeldata"] = DynValue.NewCallback((_, _) =>
{
var pd = new Table(engine);
pd["width"] = Width;
pd["height"] = Height;
pd["get"] = DynValue.NewCallback((_, a) =>
DynValue.NewNumber(PixelDataGet(buffer, (int)(a[1].CastToNumber() ?? 0d))));
pd["set"] = DynValue.NewCallback((_, a) =>
{
PixelDataSet(buffer, (int)(a[1].CastToNumber() ?? 0d), a[2].CastToNumber() ?? 0d);
return DynValue.Void;
});
return DynValue.NewTable(pd);
});
engine.Globals["obj"] = obj;
engine.DoString(script);
}
private static double PixelDataGet(byte[] buffer, int index)
{
int zeroBased = index - 1;
if ((uint)zeroBased >= (uint)buffer.Length)
return 0d;
int pixel = Math.DivRem(zeroBased, 4, out int channel);
int p = pixel * 4;
double a = buffer[p + 3];
if (channel == 3)
return a;
if (a <= 0d)
return 0d;
double scale = 255d / a;
return channel switch
{
0 => Math.Clamp(buffer[p + 2] * scale, 0d, 255d),
1 => Math.Clamp(buffer[p + 1] * scale, 0d, 255d),
_ => Math.Clamp(buffer[p] * scale, 0d, 255d),
};
}
private static void PixelDataSet(byte[] buffer, int index, double value)
{
int zeroBased = index - 1;
if ((uint)zeroBased >= (uint)buffer.Length)
return;
int pixel = Math.DivRem(zeroBased, 4, out int channel);
int p = pixel * 4;
double clamped = Math.Clamp(value, 0d, 255d);
double a = buffer[p + 3];
double premultiplied = clamped * (a / 255d);
int byteOffset = channel switch { 0 => 2, 1 => 1, _ => 0 };
buffer[p + byteOffset] = (byte)Math.Clamp(premultiplied, 0d, 255d);
}
private static (double r, double g, double b, double a) GetPixel(byte[] buffer, int x, int y)
{
if ((uint)x >= Width || (uint)y >= Height)
+122
ファイルの表示
@@ -0,0 +1,122 @@
using System;
using System.Runtime.Intrinsics;
using System.Threading;
using LuaScript.Engine.Kernel;
namespace LuaScript.Tests
{
public class KernelSimdAdoptionTests
{
private const int CalibrationExecutes = 8;
private static CpuKernel.RowDelegate Path(Action onCall, int delayMs) =>
(buffer, rowBase, xStart, xEnd, y, uniforms) =>
{
onCall();
if (delayMs > 0)
Thread.Sleep(delayMs);
};
[Fact]
public void SlowerBlock_SettlesOnScalar()
{
if (!Vector256.IsHardwareAccelerated)
return;
int rowCalls = 0, blockCalls = 0;
var kernel = new CpuKernel(Path(() => rowCalls++, 0), Path(() => blockCalls++, 5));
var buffer = new byte[8 * 4];
var uniforms = new double[1];
for (int i = 0; i < CalibrationExecutes - 1; i++)
kernel.Execute(buffer, 8, 1, uniforms);
Assert.Null(kernel.BlockAdopted);
kernel.Execute(buffer, 8, 1, uniforms);
Assert.True(kernel.BlockAdopted.HasValue);
Assert.False(kernel.BlockAdopted.Value);
int blockCallsAtDecision = blockCalls;
int rowCallsAtDecision = rowCalls;
for (int i = 0; i < 5; i++)
kernel.Execute(buffer, 8, 1, uniforms);
Assert.Equal(blockCallsAtDecision, blockCalls);
Assert.Equal(rowCallsAtDecision + 5, rowCalls);
}
[Fact]
public void FasterBlock_SettlesOnBlock()
{
if (!Vector256.IsHardwareAccelerated)
return;
int rowCalls = 0, blockCalls = 0;
var kernel = new CpuKernel(Path(() => rowCalls++, 5), Path(() => blockCalls++, 0));
var buffer = new byte[8 * 4];
var uniforms = new double[1];
for (int i = 0; i < CalibrationExecutes; i++)
kernel.Execute(buffer, 8, 1, uniforms);
Assert.True(kernel.BlockAdopted.HasValue);
Assert.True(kernel.BlockAdopted.Value);
int rowCallsAtDecision = rowCalls;
int blockCallsAtDecision = blockCalls;
for (int i = 0; i < 5; i++)
kernel.Execute(buffer, 8, 1, uniforms);
Assert.Equal(rowCallsAtDecision, rowCalls);
Assert.Equal(blockCallsAtDecision + 5, blockCalls);
}
[Fact]
public void CalibrationAlternatesBothPaths()
{
if (!Vector256.IsHardwareAccelerated)
return;
int rowCalls = 0, blockCalls = 0;
var kernel = new CpuKernel(Path(() => rowCalls++, 0), Path(() => blockCalls++, 0));
var buffer = new byte[8 * 4];
var uniforms = new double[1];
for (int i = 0; i < CalibrationExecutes; i++)
kernel.Execute(buffer, 8, 1, uniforms);
Assert.Equal(CalibrationExecutes / 2, rowCalls);
Assert.Equal(CalibrationExecutes / 2, blockCalls);
}
[Fact]
public void WithoutBlock_RunsScalarWithoutDecision()
{
int rowCalls = 0;
var kernel = new CpuKernel(Path(() => rowCalls++, 0), null);
var buffer = new byte[8 * 4];
var uniforms = new double[1];
for (int i = 0; i < CalibrationExecutes + 2; i++)
kernel.Execute(buffer, 8, 1, uniforms);
Assert.Null(kernel.BlockAdopted);
Assert.Equal(CalibrationExecutes + 2, rowCalls);
}
[Fact]
public void BlockPath_UsesScalarRowForRemainder()
{
if (!Vector256.IsHardwareAccelerated)
return;
int rowCalls = 0, blockCalls = 0;
var kernel = new CpuKernel(Path(() => rowCalls++, 0), Path(() => blockCalls++, 0));
var buffer = new byte[10 * 4];
var uniforms = new double[1];
kernel.Execute(buffer, 10, 1, uniforms);
Assert.Equal(1, blockCalls);
Assert.Equal(1, rowCalls);
}
}
}
+96
ファイルの表示
@@ -0,0 +1,96 @@
using System;
using System.Collections.Generic;
using LuaScript.Engine.Kernel;
namespace LuaScript.Tests
{
public sealed class KernelSimdEquivalenceTests
{
private const int Width = 24;
private const int Height = 17;
[Theory]
[InlineData("for y=0,obj.h-1 do for x=0,obj.w-1 do local r,g,b,a=obj.getpixel(x,y) obj.setpixel(x,y,r,g,b,a) end end")]
[InlineData("for y=0,obj.h-1 do for x=0,obj.w-1 do local r,g,b,a=obj.getpixel(x,y) obj.setpixel(x,y,255-r,255-g,255-b,a) end end")]
[InlineData("for y=0,obj.h-1 do for x=0,obj.w-1 do local r,g,b,a=obj.getpixel(x,y) obj.setpixel(x,y,b,g,r,a) end end")]
[InlineData("for y=0,obj.h-1 do for x=0,obj.w-1 do local r,g,b,a=obj.getpixel(x,y) local l=0.298912*r+0.586611*g+0.114478*b obj.setpixel(x,y,l,l,l,a) end end")]
[InlineData("for y=0,obj.h-1 do for x=0,obj.w-1 do local r,g,b,a=obj.getpixel(x,y) obj.setpixel(x,y,r*r/255,g*g/255,b*b/255,a) end end")]
[InlineData("for y=0,obj.h-1 do for x=0,obj.w-1 do local r,g,b,a=obj.getpixel(x,y) obj.setpixel(x,y,x/obj.w*255,y/obj.h*255,b,a) end end")]
[InlineData("for y=0,obj.h-1 do for x=0,obj.w-1 do local r,g,b,a=obj.getpixel(x,y) local v=(r+g+b)/3 obj.setpixel(x,y,v>128 and 255 or 0,v>128 and 255 or 0,v>128 and 255 or 0,a) end end")]
[InlineData("for y=0,obj.h-1 do for x=0,obj.w-1 do local r,g,b,a=obj.getpixel(x,y) obj.setpixel(x,y,r%64,math.abs(g-128),math.sqrt(b*255),a) end end")]
[InlineData("for y=0,obj.h-1 do for x=0,obj.w-1 do local r,g,b,a=obj.getpixel(x,y) obj.setpixel(x,y,math.floor(r/16)*16,math.ceil(g/16)*16,-b+255,a) end end")]
[InlineData("for y=0,obj.h-1 do for x=0,obj.w-1 do local r,g,b,a=obj.getpixel(x,y) obj.setpixel(x,y,r*obj.track0/100,g+x/obj.w*obj.track1,b,a) end end")]
[InlineData("local pd=obj.getpixeldata() for y=0,pd.height-1 do for x=0,pd.width-1 do local i=(y*pd.width+x)*4 local r=pd:get(i+1) local g=pd:get(i+2) local b=pd:get(i+3) pd:set(i+1,255-r) pd:set(i+2,g*g/255) pd:set(i+3,b) end end")]
[InlineData("for y=0,obj.h-1 do for x=0,obj.w-1 do local r,g,b,a=obj.getpixel(x,y) obj.setpixel(x,y,((r>128 and g<64) or (not (b>200))) and 255 or 0,g,b,a) end end")]
[InlineData("for y=0,obj.h-1 do for x=0,obj.w-1 do local r,g,b,a=obj.getpixel(x,y) obj.setpixel(x,y,(r>=200) and 255 or 0,(g<=50) and 255 or 0,(b==0) and 255 or ((b~=0) and 100 or 0),a) end end")]
[InlineData("local pd=obj.getpixeldata() for y=0,pd.height-1 do for x=0,pd.width-1 do local i=(y*pd.width+x)*4 local r=pd:get(i+1) local g=pd:get(i+2) local b=pd:get(i+3) pd:set(i+1,r*3) pd:set(i+2,g-300) pd:set(i+3,b*2-255) end end")]
public void SimdBlockMatchesScalarRow(string script)
{
var program = KernelExtractor.TryExtract(script);
Assert.NotNull(program);
var block = SimdKernelCompiler.TryCompile(program!);
Assert.NotNull(block);
var scalarRow = CpuKernelCompiler.CompileRow(program!);
double[] uniforms = BuildUniforms();
byte[] source = CreateBuffer();
byte[] scalar = (byte[])source.Clone();
byte[] simd = (byte[])source.Clone();
int stride = Width * 4;
for (int y = 0; y < Height; y++)
{
scalarRow(scalar, y * stride, 0, Width, y, uniforms);
block!(simd, y * stride, 0, Width, y, uniforms);
}
Assert.Equal(scalar, simd);
}
[Theory]
[InlineData("for y=0,obj.h-1 do for x=0,obj.w-1 do local r,g,b,a=obj.getpixel(x,y) obj.setpixel(x,y,math.min(255,r+50),math.max(0,g-50),b,a) end end")]
[InlineData("for y=0,obj.h-1 do for x=0,obj.w-1 do local r,g,b,a=obj.getpixel(x,y) obj.setpixel(x,y,255*math.pow(r/255,0.45),g,b,a) end end")]
[InlineData("for y=0,obj.h-1 do for x=0,obj.w-1 do local r,g,b,a=obj.getpixel(x,y) obj.setpixel(x,y,r^2/255,g,b,a) end end")]
[InlineData("for y=0,obj.h-1 do for x=0,obj.w-1 do local r,g,b,a=obj.getpixel(x,y) obj.setpixel(x,y,255*math.sin(r/255),g,b,a) end end")]
[InlineData("for y=0,obj.h-1 do for x=0,obj.w-1 do local r,g,b,a=obj.getpixel(x,y) obj.setpixel(x,y,math.atan2(r,g),b,a,a) end end")]
[InlineData("for y=0,obj.h-1 do for x=0,obj.w-1 do local r,g,b,a=obj.getpixel(x,y) obj.setpixel(x,y,math.fmod(r,64),g,b,a) end end")]
public void SimdRejectsNonVectorizableKernels(string script)
{
var program = KernelExtractor.TryExtract(script);
Assert.NotNull(program);
Assert.Null(SimdKernelCompiler.TryCompile(program!));
}
private static double[] BuildUniforms()
{
double[] uniforms = new double[KernelUniforms.Count];
var fields = new Dictionary<string, double> { ["w"] = Width, ["h"] = Height, ["track0"] = 73d, ["track1"] = 40d };
foreach (var (name, value) in fields)
if (KernelUniforms.TryResolveMember("obj", name, out var uniform))
uniforms[(int)uniform] = value;
return uniforms;
}
private static byte[] CreateBuffer()
{
var random = new Random(20260702);
var buffer = new byte[Width * Height * 4];
random.NextBytes(buffer);
void SetPixel(int i, byte b, byte g, byte r, byte a)
{
buffer[i * 4 + 0] = b; buffer[i * 4 + 1] = g; buffer[i * 4 + 2] = r; buffer[i * 4 + 3] = a;
}
SetPixel(0, 0, 0, 0, 0);
SetPixel(1, 255, 255, 255, 255);
SetPixel(2, 1, 0, 0, 1);
SetPixel(3, 200, 128, 64, 254);
SetPixel(4, 0, 0, 0, 128);
SetPixel(5, 255, 255, 255, 2);
return buffer;
}
}
}
+9
ファイルの表示
@@ -31,6 +31,7 @@
<Compile Include="..\LuaScript\Engine\ScriptDirective.cs" Link="Linked\ScriptDirective.cs" />
<Compile Include="..\LuaScript\Engine\NativeProtocol.cs" Link="Linked\NativeProtocol.cs" />
<Compile Include="..\LuaScript\Engine\ProcessJobObject.cs" Link="Linked\ProcessJobObject.cs" />
<Compile Include="..\LuaScript\Engine\PixelRegionAccess.cs" Link="Linked\PixelRegionAccess.cs" />
<Compile Include="..\LuaScript\Engine\LuaJitWorker.cs" Link="Linked\LuaJitWorker.cs" />
<Compile Include="..\LuaScript\DrawCommand.cs" Link="Linked\DrawCommand.cs" />
<Compile Include="..\LuaScript\DrawPolyMath.cs" Link="Linked\DrawPolyMath.cs" />
@@ -43,7 +44,14 @@
<Compile Include="..\LuaScript\Anchor\AnchorSupport.cs" Link="Linked\AnchorSupport.cs" />
<Compile Include="..\LuaScript\SceneObjectInfo.cs" Link="Linked\SceneObjectInfo.cs" />
<Compile Include="..\LuaScript\SceneObjectQuery.cs" Link="Linked\SceneObjectQuery.cs" />
<Compile Include="..\LuaScript\SceneSharedValues.cs" Link="Linked\SceneSharedValues.cs" />
<Compile Include="..\LuaScript\SceneValueSession.cs" Link="Linked\SceneValueSession.cs" />
<Compile Include="..\LuaScript\SceneTableRegistrar.cs" Link="Linked\SceneTableRegistrar.cs" />
<Compile Include="..\LuaScript\AviUtlFontState.cs" Link="Linked\AviUtlFontState.cs" />
<Compile Include="..\LuaScript\AnimTableRegistrar.cs" Link="Linked\AnimTableRegistrar.cs" />
<Compile Include="..\LuaScript\AviUtlGlobalRegistrar.cs" Link="Linked\AviUtlGlobalRegistrar.cs" />
<Compile Include="..\LuaScript\Compat\AviUtlGlobalFunctions.cs" Link="Linked\AviUtlGlobalFunctions.cs" />
<Compile Include="..\LuaScript\Diagnostics\DebugOutput.cs" Link="Linked\DebugOutput.cs" />
<Compile Include="..\LuaScript\Compat\AviUtlScript.cs" Link="Linked\AviUtlScript.cs" />
<Compile Include="..\LuaScript\Compat\ScriptParserHelper.cs" Link="Linked\ScriptParserHelper.cs" />
<Compile Include="..\LuaScript\Compat\AviUtlParameterLayout.cs" Link="Linked\AviUtlParameterLayout.cs" />
@@ -64,6 +72,7 @@
<Compile Include="..\LuaScript\Engine\Kernel\KernelExtractor.cs" Link="Linked\Kernel\KernelExtractor.cs" />
<Compile Include="..\LuaScript\Engine\Kernel\CpuKernel.cs" Link="Linked\Kernel\CpuKernel.cs" />
<Compile Include="..\LuaScript\Engine\Kernel\CpuKernelCompiler.cs" Link="Linked\Kernel\CpuKernelCompiler.cs" />
<Compile Include="..\LuaScript\Engine\Kernel\SimdKernelCompiler.cs" Link="Linked\Kernel\SimdKernelCompiler.cs" />
<Compile Include="..\LuaScript\Engine\Kernel\HlslKernelEmitter.cs" Link="Linked\Kernel\HlslKernelEmitter.cs" />
</ItemGroup>
+4
ファイルの表示
@@ -7,6 +7,8 @@ namespace LuaScript.Tests
{
private readonly Script _script;
public double TimeRatio { get; set; }
public MoonSharpLane()
{
_script = new Script(
@@ -22,6 +24,8 @@ namespace LuaScript.Tests
var anim = new Table(_script);
AnimTableRegistrar.RegisterFunctions(anim);
_script.Globals["anim"] = anim;
AviUtlGlobalRegistrar.RegisterFunctions(_script.Globals, () => TimeRatio);
}
public DynValue Run(string code) => _script.DoString(code);
+552 -41
ファイルの表示
@@ -20,6 +20,9 @@ namespace LuaScript.Tests
private readonly LuaJitWorker _worker = new(NativeDir);
private Func<string, SceneValue> _sceneGet = _ => SceneValue.Nil;
private Action<string, SceneValue> _sceneSet = (_, _) => { };
public void Dispose() => _worker.Dispose();
private static double[] Fields(int w, int h, double time)
@@ -32,6 +35,81 @@ namespace LuaScript.Tests
return f;
}
private bool RunWorker(
string script,
double[] fields,
System.Collections.Generic.IReadOnlyDictionary<string, string> stringParameters,
Func<byte[]> loadPixels,
int width,
int height,
int timeoutMs,
Func<string, int, SceneObjectInfo?> resolveObject,
Func<string, int, double, double, double, (byte[] buffer, int w, int h)> loadFigure,
Func<string, string, double, bool, bool, int, (byte[] buffer, int w, int h)> loadText,
Func<string, (byte[] buffer, int w, int h)> loadImage,
Func<string, double, (byte[] buffer, int w, int h)> loadMovie,
Action<string, System.Collections.Generic.IReadOnlyList<System.Collections.Generic.KeyValuePair<string, object>>> addEffect,
Action<DrawCommand> addDraw,
Action<string, int, bool, int, double[]> setAnchor,
out bool pixelsDirty,
out bool bufferReplaced,
out byte[]? resultPixels,
out int resultWidth,
out int resultHeight,
out string? error)
{
byte[]? uploaded = null;
bool ok = _worker.Execute(
script, fields, stringParameters,
(address, capacity) =>
{
uploaded = loadPixels();
System.Runtime.InteropServices.Marshal.Copy(uploaded, 0, address, uploaded.Length);
},
width, height, timeoutMs,
resolveObject, loadFigure, loadText, loadImage, loadMovie, addEffect, addDraw, setAnchor,
_sceneGet, _sceneSet,
out pixelsDirty, out bufferReplaced, out resultWidth, out resultHeight, out error);
resultPixels = null;
if (ok && pixelsDirty)
{
int pixelSize = resultWidth * resultHeight * 4;
byte[] destination = !bufferReplaced && uploaded is not null && uploaded.Length >= pixelSize
? uploaded
: new byte[pixelSize];
_worker.ReadPixels((address, capacity) =>
System.Runtime.InteropServices.Marshal.Copy(address, destination, 0, pixelSize));
resultPixels = destination;
}
return ok;
}
[Fact]
public void PixelUpload_ProvidesRegionCoveringFrame()
{
Assert.True(LuaJitWorker.IsAvailable(NativeDir), "native/luajit.exe must be present");
const int w = 3, h = 2;
var pixels = new byte[w * h * 4];
long observedCapacity = -1;
bool ok = _worker.Execute(
"local r, g, b, a = obj.getpixel(0, 0) obj.x = a",
Fields(w, h, 0d), NoStringParams,
(address, capacity) =>
{
observedCapacity = capacity;
System.Runtime.InteropServices.Marshal.Copy(pixels, 0, address, pixels.Length);
},
w, h, 5000, NoResolver, NoLoadFigure, NoLoadText, NoLoadImage, NoLoadMovie, NoAddEffect, NoAddDraw, NoSetAnchor,
_sceneGet, _sceneSet,
out _, out _, out _, out _, out string? error);
Assert.True(ok, error);
Assert.True(observedCapacity >= (long)w * h * 4);
}
[Fact]
public void TransformScript_WritesBackObjFields()
{
@@ -40,7 +118,7 @@ namespace LuaScript.Tests
var fields = Fields(4, 4, 2d);
var pixels = new byte[4 * 4 * 4];
bool ok = _worker.Execute(
bool ok = RunWorker(
"obj.rz = obj.time * 90\nobj.alpha = 128",
fields, NoStringParams, () => pixels, 4, 4, 5000, NoResolver, NoLoadFigure, NoLoadText, NoLoadImage, NoLoadMovie, NoAddEffect, NoAddDraw, NoSetAnchor, out bool dirty, out _, out _, out _, out _, out string? error);
@@ -63,7 +141,7 @@ namespace LuaScript.Tests
["file_image"] = "C:/サンプル/画像.png",
};
bool ok = _worker.Execute(
bool ok = RunWorker(
"obj.x = string.len(obj.text) obj.alpha = string.len(obj.file_image)",
fields, stringParameters, () => pixels, 2, 2, 5000, NoResolver, NoLoadFigure, NoLoadText, NoLoadImage, NoLoadMovie, NoAddEffect, NoAddDraw, NoSetAnchor, out _, out _, out _, out _, out _, out string? error);
@@ -82,7 +160,7 @@ namespace LuaScript.Tests
var large = new System.Collections.Generic.Dictionary<string, string> { ["text"] = big };
var fieldsLarge = Fields(2, 2, 0d);
bool ok = _worker.Execute(
bool ok = RunWorker(
"obj.x = string.len(obj.text)",
fieldsLarge, large, () => pixels, 2, 2, 5000, NoResolver, NoLoadFigure, NoLoadText, NoLoadImage, NoLoadMovie, NoAddEffect, NoAddDraw, NoSetAnchor, out _, out _, out _, out _, out _, out string? error);
Assert.True(ok, error);
@@ -90,7 +168,7 @@ namespace LuaScript.Tests
var small = new System.Collections.Generic.Dictionary<string, string> { ["text"] = "ok" };
var fieldsSmall = Fields(2, 2, 0d);
ok = _worker.Execute(
ok = RunWorker(
"obj.x = string.len(obj.text)",
fieldsSmall, small, () => pixels, 2, 2, 5000, NoResolver, NoLoadFigure, NoLoadText, NoLoadImage, NoLoadMovie, NoAddEffect, NoAddDraw, NoSetAnchor, out _, out _, out _, out _, out _, out error);
Assert.True(ok, error);
@@ -124,7 +202,7 @@ namespace LuaScript.Tests
"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, NoStringParams, () => pixels, w, h, 5000, NoResolver, NoLoadFigure, NoLoadText, NoLoadImage, NoLoadMovie, NoAddEffect, NoAddDraw, NoSetAnchor, out bool dirty, out _, out _, out _, out _, out string? error);
bool ok = RunWorker(script, fields, NoStringParams, () => pixels, w, h, 5000, NoResolver, NoLoadFigure, NoLoadText, NoLoadImage, NoLoadMovie, NoAddEffect, NoAddDraw, NoSetAnchor, out bool dirty, out _, out _, out _, out _, out string? error);
Assert.True(ok, error);
Assert.True(dirty);
@@ -159,7 +237,7 @@ namespace LuaScript.Tests
"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, NoStringParams, () => pixels, w, h, 5000, NoResolver, NoLoadFigure, NoLoadText, NoLoadImage, NoLoadMovie, NoAddEffect, NoAddDraw, NoSetAnchor, out bool dirty, out _, out _, out _, out _, out string? error);
bool ok = RunWorker(script, fields, NoStringParams, () => pixels, w, h, 5000, NoResolver, NoLoadFigure, NoLoadText, NoLoadImage, NoLoadMovie, NoAddEffect, NoAddDraw, NoSetAnchor, out bool dirty, out _, out _, out _, out _, out string? error);
Assert.True(ok, error);
Assert.True(dirty);
@@ -186,6 +264,109 @@ namespace LuaScript.Tests
px[i * 4 + 3] = (byte)Math.Floor(Math.Clamp(a, 0d, 255d));
}
[Fact]
public void PixelData_RebuildsAfterSetPixel()
{
Assert.True(LuaJitWorker.IsAvailable(NativeDir), "native/luajit.exe must be present");
var pixels = new byte[16];
var fields = Fields(2, 2, 0d);
const string script =
"obj.setpixel(0,0,100,150,200,255) " +
"local pd = obj.getpixeldata() " +
"obj.x = pd:get(1) obj.y = pd:get(2) obj.z = pd:get(3) obj.alpha = pd:get(4)";
bool ok = RunWorker(script, fields, NoStringParams, () => pixels, 2, 2, 5000, NoResolver, NoLoadFigure, NoLoadText, NoLoadImage, NoLoadMovie, NoAddEffect, NoAddDraw, NoSetAnchor, out _, out _, out _, out _, out _, out string? error);
Assert.True(ok, error);
Assert.Equal(100d, fields[NativeProtocol.X]);
Assert.Equal(150d, fields[NativeProtocol.Y]);
Assert.Equal(200d, fields[NativeProtocol.Z]);
Assert.Equal(255d, fields[NativeProtocol.Alpha]);
}
[Fact]
public void PixelData_WritesAreVisibleToGetPixel()
{
Assert.True(LuaJitWorker.IsAvailable(NativeDir), "native/luajit.exe must be present");
var pixels = new byte[16];
pixels[3] = 255;
var fields = Fields(2, 2, 0d);
const string script =
"local pd = obj.getpixeldata() " +
"pd:set(1,120) pd:set(2,130) pd:set(3,140) " +
"local r,g,b,a = obj.getpixel(0,0) " +
"obj.x = r obj.y = g obj.z = b obj.alpha = a";
bool ok = RunWorker(script, fields, NoStringParams, () => pixels, 2, 2, 5000, NoResolver, NoLoadFigure, NoLoadText, NoLoadImage, NoLoadMovie, NoAddEffect, NoAddDraw, NoSetAnchor, out bool dirty, out _, out _, out _, out _, out string? error);
Assert.True(ok, error);
Assert.True(dirty);
Assert.Equal(120d, fields[NativeProtocol.X]);
Assert.Equal(130d, fields[NativeProtocol.Y]);
Assert.Equal(140d, fields[NativeProtocol.Z]);
Assert.Equal(255d, fields[NativeProtocol.Alpha]);
}
[Fact]
public void PixelData_StaleWritesDoNotResurrect_AfterLoad()
{
Assert.True(LuaJitWorker.IsAvailable(NativeDir), "native/luajit.exe must be present");
const int iw = 2, ih = 2;
var decoded = new byte[iw * ih * 4];
for (int i = 0; i < decoded.Length; i++)
decoded[i] = (byte)((i * 19 + 7) & 0xFF);
Func<string, (byte[], int, int)> loadImage = _ => (decoded, iw, ih);
var pixels = new byte[4 * 4 * 4];
for (int i = 3; i < pixels.Length; i += 4)
pixels[i] = 255;
const string script =
"local pd = obj.getpixeldata() " +
"pd:set(1, 11) pd:set(2, 22) pd:set(3, 33) " +
"obj.load('image', 'p')";
bool ok = RunWorker(script, Fields(4, 4, 0d), NoStringParams, () => pixels, 4, 4, 5000, NoResolver, NoLoadFigure, NoLoadText, loadImage, NoLoadMovie, NoAddEffect, NoAddDraw, NoSetAnchor,
out bool dirty, out bool bufferReplaced, out byte[]? result, out int rw, out int rh, out string? error);
Assert.True(ok, error);
Assert.True(dirty);
Assert.True(bufferReplaced);
Assert.Equal(iw, rw);
Assert.Equal(ih, rh);
Assert.NotNull(result);
Assert.Equal(decoded, result!.AsSpan(0, decoded.Length).ToArray());
}
[Fact]
public void PixelData_StaleWritesDoNotResurrect_AfterCopyBuffer()
{
Assert.True(LuaJitWorker.IsAvailable(NativeDir), "native/luajit.exe must be present");
const int w = 2, h = 2;
var pixels = new byte[w * h * 4];
for (int i = 0; i < pixels.Length; i++)
pixels[i] = (byte)((i * 29 + 3) & 0xFF);
pixels[3] = 255; pixels[7] = 255; pixels[11] = 255; pixels[15] = 255;
var original = (byte[])pixels.Clone();
const string script =
"obj.copybuffer('tmp','obj') " +
"local pd = obj.getpixeldata() " +
"pd:set(1, 99) pd:set(2, 98) pd:set(3, 97) " +
"obj.copybuffer('obj','tmp')";
bool ok = RunWorker(script, Fields(w, h, 0d), NoStringParams, () => pixels, w, h, 5000, NoResolver, NoLoadFigure, NoLoadText, NoLoadImage, NoLoadMovie, NoAddEffect, NoAddDraw, NoSetAnchor,
out bool dirty, out _, out _, out _, out _, out string? error);
Assert.True(ok, error);
Assert.True(dirty);
Assert.Equal(original, pixels);
}
[Fact]
public void PersistentWorker_HandlesMultipleCalls()
{
@@ -195,12 +376,57 @@ namespace LuaScript.Tests
for (int k = 1; k <= 5; k++)
{
var fields = Fields(2, 2, k);
bool ok = _worker.Execute("obj.x = obj.time * 10", fields, NoStringParams, () => pixels, 2, 2, 5000, NoResolver, NoLoadFigure, NoLoadText, NoLoadImage, NoLoadMovie, NoAddEffect, NoAddDraw, NoSetAnchor, out _, out _, out _, out _, out _, out string? error);
bool ok = RunWorker("obj.x = obj.time * 10", fields, NoStringParams, () => pixels, 2, 2, 5000, NoResolver, NoLoadFigure, NoLoadText, NoLoadImage, NoLoadMovie, NoAddEffect, NoAddDraw, NoSetAnchor, out _, out _, out _, out _, out _, out string? error);
Assert.True(ok, error);
Assert.Equal(k * 10d, fields[NativeProtocol.X]);
}
}
[Fact]
public void AlternatingScripts_RecompileWhenVersionChanges()
{
Assert.True(LuaJitWorker.IsAvailable(NativeDir), "native/luajit.exe must be present");
var pixels = new byte[16];
const string scriptA = "obj.x = obj.time * 2";
const string scriptB = "obj.x = obj.time * 3";
for (int k = 1; k <= 4; k++)
{
var fa = Fields(2, 2, k);
bool okA = RunWorker(scriptA, fa, NoStringParams, () => pixels, 2, 2, 5000, NoResolver, NoLoadFigure, NoLoadText, NoLoadImage, NoLoadMovie, NoAddEffect, NoAddDraw, NoSetAnchor, out _, out _, out _, out _, out _, out string? errorA);
Assert.True(okA, errorA);
Assert.Equal(k * 2d, fa[NativeProtocol.X]);
var fb = Fields(2, 2, k);
bool okB = RunWorker(scriptB, fb, NoStringParams, () => pixels, 2, 2, 5000, NoResolver, NoLoadFigure, NoLoadText, NoLoadImage, NoLoadMovie, NoAddEffect, NoAddDraw, NoSetAnchor, out _, out _, out _, out _, out _, out string? errorB);
Assert.True(okB, errorB);
Assert.Equal(k * 3d, fb[NativeProtocol.X]);
}
}
[Fact]
public void CompileError_IsReportedEveryFrame_AndRecovers()
{
Assert.True(LuaJitWorker.IsAvailable(NativeDir), "native/luajit.exe must be present");
var pixels = new byte[16];
const string broken = "obj.x = (";
for (int k = 0; k < 2; k++)
{
bool ok = RunWorker(broken, Fields(2, 2, 0d), NoStringParams, () => pixels, 2, 2, 5000, NoResolver, NoLoadFigure, NoLoadText, NoLoadImage, NoLoadMovie, NoAddEffect, NoAddDraw, NoSetAnchor, out _, out _, out _, out _, out _, out string? error);
Assert.False(ok);
Assert.False(string.IsNullOrEmpty(error));
Assert.DoesNotContain("timed out", error);
}
var fields = Fields(2, 2, 9d);
bool recovered = RunWorker("obj.x = obj.time", fields, NoStringParams, () => pixels, 2, 2, 5000, NoResolver, NoLoadFigure, NoLoadText, NoLoadImage, NoLoadMovie, NoAddEffect, NoAddDraw, NoSetAnchor, out _, out _, out _, out _, out _, out string? recoverError);
Assert.True(recovered, recoverError);
Assert.Equal(9d, fields[NativeProtocol.X]);
}
[Fact]
public void Timeout_KillsWorker_AndRecovers()
{
@@ -209,13 +435,13 @@ namespace LuaScript.Tests
var pixels = new byte[16];
var fields = Fields(2, 2, 0d);
bool timedOut = _worker.Execute(
bool timedOut = RunWorker(
"local x=0 while true do x=x+1 end", fields, NoStringParams, () => pixels, 2, 2, 1500, NoResolver, NoLoadFigure, NoLoadText, NoLoadImage, NoLoadMovie, NoAddEffect, NoAddDraw, NoSetAnchor, out _, out _, out _, out _, 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, NoStringParams, () => pixels, 2, 2, 5000, NoResolver, NoLoadFigure, NoLoadText, NoLoadImage, NoLoadMovie, NoAddEffect, NoAddDraw, NoSetAnchor, out _, out _, out _, out _, out _, out error);
bool ok = RunWorker("obj.x = obj.time", fields2, NoStringParams, () => pixels, 2, 2, 5000, NoResolver, NoLoadFigure, NoLoadText, NoLoadImage, NoLoadMovie, NoAddEffect, NoAddDraw, NoSetAnchor, out _, out _, out _, out _, out _, out error);
Assert.True(ok, error);
Assert.Equal(3d, fields2[NativeProtocol.X]);
}
@@ -237,7 +463,7 @@ namespace LuaScript.Tests
"obj.zoom = o.zoom obj.rz = o.rz obj.alpha = o.alpha " +
"obj.sx = o.sy obj.rzr = o.rzr";
bool ok = _worker.Execute(script, fields, NoStringParams, () => pixels, 2, 2, 5000, resolver, NoLoadFigure, NoLoadText, NoLoadImage, NoLoadMovie, NoAddEffect, NoAddDraw, NoSetAnchor, out _, out _, out _, out _, out _, out string? error);
bool ok = RunWorker(script, fields, NoStringParams, () => pixels, 2, 2, 5000, resolver, NoLoadFigure, NoLoadText, NoLoadImage, NoLoadMovie, NoAddEffect, NoAddDraw, NoSetAnchor, out _, out _, out _, out _, out _, out string? error);
Assert.True(ok, error);
Assert.Equal(12d, fields[NativeProtocol.X]);
@@ -269,13 +495,13 @@ namespace LuaScript.Tests
"local b = obj.getobject(\"a\") " +
"obj.x = a.x + b.x";
bool ok = _worker.Execute(script, Fields(2, 2, 0d), NoStringParams, () => pixels, 2, 2, 5000, resolver, NoLoadFigure, NoLoadText, NoLoadImage, NoLoadMovie, NoAddEffect, NoAddDraw, NoSetAnchor, out _, out _, out _, out _, out _, out string? error);
bool ok = RunWorker(script, Fields(2, 2, 0d), NoStringParams, () => pixels, 2, 2, 5000, resolver, NoLoadFigure, NoLoadText, NoLoadImage, NoLoadMovie, NoAddEffect, NoAddDraw, NoSetAnchor, out _, out _, out _, out _, out _, out string? error);
Assert.True(ok, error);
Assert.Equal(1, calls);
var fields = Fields(2, 2, 0d);
x = 20d;
ok = _worker.Execute(script, fields, NoStringParams, () => pixels, 2, 2, 5000, resolver, NoLoadFigure, NoLoadText, NoLoadImage, NoLoadMovie, NoAddEffect, NoAddDraw, NoSetAnchor, out _, out _, out _, out _, out _, out error);
ok = RunWorker(script, fields, NoStringParams, () => pixels, 2, 2, 5000, resolver, NoLoadFigure, NoLoadText, NoLoadImage, NoLoadMovie, NoAddEffect, NoAddDraw, NoSetAnchor, out _, out _, out _, out _, out _, out error);
Assert.True(ok, error);
Assert.Equal(2, calls);
Assert.Equal(40d, fields[NativeProtocol.X]);
@@ -292,7 +518,7 @@ namespace LuaScript.Tests
const string script =
"local o = obj.getobject(\"missing\") obj.x = o == nil and 1 or 0";
bool ok = _worker.Execute(script, fields, NoStringParams, () => pixels, 2, 2, 5000, NoResolver, NoLoadFigure, NoLoadText, NoLoadImage, NoLoadMovie, NoAddEffect, NoAddDraw, NoSetAnchor, out _, out _, out _, out _, out _, out string? error);
bool ok = RunWorker(script, fields, NoStringParams, () => pixels, 2, 2, 5000, NoResolver, NoLoadFigure, NoLoadText, NoLoadImage, NoLoadMovie, NoAddEffect, NoAddDraw, NoSetAnchor, out _, out _, out _, out _, out _, out string? error);
Assert.True(ok, error);
Assert.Equal(1d, fields[NativeProtocol.X]);
@@ -308,7 +534,7 @@ namespace LuaScript.Tests
var commands = new System.Collections.Generic.List<DrawCommand>();
Action<DrawCommand> addDraw = commands.Add;
bool ok = _worker.Execute(
bool ok = RunWorker(
"obj.draw() obj.draw(10, 20, 30, 2, 0.5, 0.25)",
fields, NoStringParams, () => pixels, 2, 2, 5000, NoResolver, NoLoadFigure, NoLoadText, NoLoadImage, NoLoadMovie, NoAddEffect, addDraw, NoSetAnchor,
out _, out _, out _, out _, out _, out string? error);
@@ -319,6 +545,28 @@ namespace LuaScript.Tests
Assert.Equal(new DrawCommand(10d, 20d, 30d, 2d, 0.5d, 0.25d), commands[1]);
}
[Fact]
public void Draw_BatchesInOrderAcrossRingOverflow()
{
Assert.True(LuaJitWorker.IsAvailable(NativeDir), "native/luajit.exe must be present");
var pixels = new byte[16];
var commands = new System.Collections.Generic.List<DrawCommand>();
Action<DrawCommand> addDraw = commands.Add;
int total = NativeProtocol.DrawRingCapacity + 100;
string script = "for i=1," + total + " do obj.draw(i,0,0,1,1,0) end";
bool ok = RunWorker(
script, Fields(2, 2, 0d), NoStringParams, () => pixels, 2, 2, 5000, NoResolver, NoLoadFigure, NoLoadText, NoLoadImage, NoLoadMovie, NoAddEffect, addDraw, NoSetAnchor,
out _, out _, out _, out _, out _, out string? error);
Assert.True(ok, error);
Assert.Equal(total, commands.Count);
for (int i = 0; i < total; i++)
Assert.Equal(i + 1, commands[i].Ox);
}
[Fact]
public void DrawPoly_RecordsDefaultUvAndAlpha()
{
@@ -329,7 +577,7 @@ namespace LuaScript.Tests
var commands = new System.Collections.Generic.List<DrawCommand>();
Action<DrawCommand> addDraw = commands.Add;
bool ok = _worker.Execute(
bool ok = RunWorker(
"obj.drawpoly(0,0,0, 10,0,0, 10,10,0, 0,10,0)",
fields, NoStringParams, () => pixels, 4, 4, 5000, NoResolver, NoLoadFigure, NoLoadText, NoLoadImage, NoLoadMovie, NoAddEffect, addDraw, NoSetAnchor,
out _, out _, out _, out _, out _, out string? error);
@@ -351,7 +599,7 @@ namespace LuaScript.Tests
var commands = new System.Collections.Generic.List<DrawCommand>();
Action<DrawCommand> addDraw = commands.Add;
bool ok = _worker.Execute(
bool ok = RunWorker(
"obj.drawpoly(0,0,0, 8,0,0, 8,8,0, 0,8,0, 1,1, 3,1, 3,3, 1,3, 0.5)",
fields, NoStringParams, () => pixels, 4, 4, 5000, NoResolver, NoLoadFigure, NoLoadText, NoLoadImage, NoLoadMovie, NoAddEffect, addDraw, NoSetAnchor,
out _, out _, out _, out _, out _, out string? error);
@@ -372,7 +620,7 @@ namespace LuaScript.Tests
var pixels = new byte[16];
var fields = Fields(2, 2, 0d);
bool ok = _worker.Execute(
bool ok = RunWorker(
"obj.setoption('antialias', 0) obj.x = obj.getoption('antialias') obj.y = obj.getoption('unset')",
fields, NoStringParams, () => pixels, 2, 2, 5000, NoResolver, NoLoadFigure, NoLoadText, NoLoadImage, NoLoadMovie, NoAddEffect, NoAddDraw, NoSetAnchor,
out _, out _, out _, out _, out _, out string? error);
@@ -391,7 +639,7 @@ namespace LuaScript.Tests
var commands = new System.Collections.Generic.List<DrawCommand>();
Action<DrawCommand> addDraw = commands.Add;
bool ok = _worker.Execute(
bool ok = RunWorker(
"obj.draw() obj.setoption('antialias', 0) obj.draw()",
Fields(2, 2, 0d), NoStringParams, () => pixels, 2, 2, 5000, NoResolver, NoLoadFigure, NoLoadText, NoLoadImage, NoLoadMovie, NoAddEffect, addDraw, NoSetAnchor,
out _, out _, out _, out _, out _, out string? error);
@@ -411,7 +659,7 @@ namespace LuaScript.Tests
var commands = new System.Collections.Generic.List<DrawCommand>();
Action<DrawCommand> addDraw = commands.Add;
bool ok = _worker.Execute(
bool ok = RunWorker(
"obj.draw() obj.setoption('blend', 3) obj.draw()",
Fields(2, 2, 0d), NoStringParams, () => pixels, 2, 2, 5000, NoResolver, NoLoadFigure, NoLoadText, NoLoadImage, NoLoadMovie, NoAddEffect, addDraw, NoSetAnchor,
out _, out _, out _, out _, out _, out string? error);
@@ -431,7 +679,7 @@ namespace LuaScript.Tests
var commands = new System.Collections.Generic.List<DrawCommand>();
Action<DrawCommand> addDraw = commands.Add;
bool ok = _worker.Execute(
bool ok = RunWorker(
"obj.setoption('blend', 11) obj.drawpoly(0,0,0, 10,0,0, 10,10,0, 0,10,0)",
Fields(4, 4, 0d), NoStringParams, () => pixels, 4, 4, 5000, NoResolver, NoLoadFigure, NoLoadText, NoLoadImage, NoLoadMovie, NoAddEffect, addDraw, NoSetAnchor,
out _, out _, out _, out _, out _, out string? error);
@@ -449,7 +697,7 @@ namespace LuaScript.Tests
var pixels = new byte[16];
var fTrue = Fields(2, 2, 0d);
bool okTrue = _worker.Execute(
bool okTrue = RunWorker(
"obj.setoption('draw_state', true)",
fTrue, NoStringParams, () => pixels, 2, 2, 5000, NoResolver, NoLoadFigure, NoLoadText, NoLoadImage, NoLoadMovie, NoAddEffect, NoAddDraw, NoSetAnchor,
out _, out _, out _, out _, out _, out string? errorTrue);
@@ -457,7 +705,7 @@ namespace LuaScript.Tests
Assert.Equal(1d, fTrue[NativeProtocol.DrawState]);
var fFalse = Fields(2, 2, 0d);
bool okFalse = _worker.Execute(
bool okFalse = RunWorker(
"obj.setoption('draw_state', false)",
fFalse, NoStringParams, () => pixels, 2, 2, 5000, NoResolver, NoLoadFigure, NoLoadText, NoLoadImage, NoLoadMovie, NoAddEffect, NoAddDraw, NoSetAnchor,
out _, out _, out _, out _, out _, out string? errorFalse);
@@ -465,7 +713,7 @@ namespace LuaScript.Tests
Assert.Equal(2d, fFalse[NativeProtocol.DrawState]);
var fUnset = Fields(2, 2, 0d);
bool okUnset = _worker.Execute(
bool okUnset = RunWorker(
"obj.x = 1",
fUnset, NoStringParams, () => pixels, 2, 2, 5000, NoResolver, NoLoadFigure, NoLoadText, NoLoadImage, NoLoadMovie, NoAddEffect, NoAddDraw, NoSetAnchor,
out _, out _, out _, out _, out _, out string? errorUnset);
@@ -503,7 +751,7 @@ namespace LuaScript.Tests
"obj.y = pos[1]\n" +
"obj.z = pos[3]";
bool ok = _worker.Execute(script, fields, NoStringParams, () => pixels, 2, 2, 5000,
bool ok = RunWorker(script, fields, NoStringParams, () => pixels, 2, 2, 5000,
NoResolver, NoLoadFigure, NoLoadText, NoLoadImage, NoLoadMovie, NoAddEffect, NoAddDraw, setAnchor,
out _, out _, out _, out _, out _, out string? error);
@@ -533,7 +781,7 @@ namespace LuaScript.Tests
"obj.setoption('drawtarget','framebuffer')\n" +
"obj.copybuffer('obj','tmp')";
bool ok = _worker.Execute(
bool ok = RunWorker(
script, fields, NoStringParams, () => pixels, 2, 2, 5000,
NoResolver, NoLoadFigure, NoLoadText, NoLoadImage, NoLoadMovie, NoAddEffect, NoAddDraw, NoSetAnchor,
out bool dirty, out _, out _, out _, out _, out string? error);
@@ -579,7 +827,7 @@ namespace LuaScript.Tests
var pixels = new byte[4 * 4 * 4];
var fields = Fields(4, 4, 0d);
bool ok = _worker.Execute(
bool ok = RunWorker(
"obj.setfont('Meiryo', 40, 3, 0x112233) obj.load('text', 'Hi')",
fields, NoStringParams, () => pixels, 4, 4, 5000, NoResolver, NoLoadFigure, loadText, NoLoadImage, NoLoadMovie, NoAddEffect, NoAddDraw, NoSetAnchor,
out bool dirty, out bool bufferReplaced, out byte[]? newPixels, out int rw, out int rh, out string? error);
@@ -599,6 +847,43 @@ namespace LuaScript.Tests
Assert.Equal(rendered, newPixels!.AsSpan(0, rendered.Length).ToArray());
}
[Fact]
public void SetFont_CoercesArgumentsLikeMoonSharp()
{
Assert.True(LuaJitWorker.IsAvailable(NativeDir), "native/luajit.exe must be present");
var rendered = new byte[4];
var captured = new List<(string Family, double Size, bool Bold, bool Italic, int Color)>();
Func<string, string, double, bool, bool, int, (byte[], int, int)> loadText =
(family, text, size, bold, italic, color) =>
{
captured.Add((family, size, bold, italic, color));
return (rendered, 1, 1);
};
var pixels = new byte[4 * 4 * 4];
var fields = Fields(4, 4, 0d);
bool ok = RunWorker(
"obj.setfont('Meiryo', 40, 3, 0x112233) obj.load('text', 'a') " +
"obj.setfont(123, '48') obj.load('text', 'a') " +
"obj.setfont(true, false, {}, function() end) obj.load('text', 'a') " +
"obj.setfont(nil, nil, -1.5) obj.load('text', 'a') " +
"obj.setfont('X', 20, 0, 0) obj.load('text', 'a')",
fields, NoStringParams, () => pixels, 4, 4, 5000, NoResolver, NoLoadFigure, loadText, NoLoadImage, NoLoadMovie, NoAddEffect, NoAddDraw, NoSetAnchor,
out _, out _, out _, out _, out _, out string? error);
Assert.True(ok, error);
Assert.Equal(
[
("Meiryo", 40d, true, true, 0x112233),
("123", 48d, true, true, 0x112233),
("123", 48d, true, true, 0x112233),
("123", 48d, false, true, 0x112233),
("X", 20d, false, false, 0),
], captured);
}
[Fact]
public void LoadImage_RoundTripsThroughCallback()
{
@@ -619,7 +904,7 @@ namespace LuaScript.Tests
var pixels = new byte[4 * 4 * 4];
var fields = Fields(4, 4, 0d);
bool ok = _worker.Execute(
bool ok = RunWorker(
"obj.load('image', 'C:/sample.png')",
fields, NoStringParams, () => pixels, 4, 4, 5000, NoResolver, NoLoadFigure, NoLoadText, loadImage, NoLoadMovie, NoAddEffect, NoAddDraw, NoSetAnchor,
out bool dirty, out bool bufferReplaced, out byte[]? newPixels, out int rw, out int rh, out string? error);
@@ -656,7 +941,7 @@ namespace LuaScript.Tests
var pixels = new byte[4 * 4 * 4];
var fields = Fields(4, 4, 0d);
bool ok = _worker.Execute(
bool ok = RunWorker(
"obj.load('movie', 'C:/clip.mp4', 1.5)",
fields, NoStringParams, () => pixels, 4, 4, 5000, NoResolver, NoLoadFigure, NoLoadText, NoLoadImage, loadMovie, NoAddEffect, NoAddDraw, NoSetAnchor,
out bool dirty, out bool bufferReplaced, out byte[]? newPixels, out int rw, out int rh, out string? error);
@@ -681,7 +966,7 @@ namespace LuaScript.Tests
var fields = Fields(2, 2, 0d);
fields[NativeProtocol.Track0] = 42d;
bool ok = _worker.Execute(
bool ok = RunWorker(
"obj.x = obj.getvalue('track0') obj.y = obj.getvalue('alpha') obj.z = obj.getvalue('unknown')",
fields, NoStringParams, () => pixels, 2, 2, 5000, NoResolver, NoLoadFigure, NoLoadText, NoLoadImage, NoLoadMovie, NoAddEffect, NoAddDraw, NoSetAnchor,
out _, out _, out _, out _, out _, out string? error);
@@ -710,7 +995,7 @@ namespace LuaScript.Tests
"for y=0,obj.h-1 do for x=0,obj.w-1 do obj.setpixel(x,y,0,0,0,0) end end " +
"obj.copybuffer('obj','tmp')";
bool ok = _worker.Execute(script, fields, NoStringParams, () => pixels, w, h, 5000, NoResolver, NoLoadFigure, NoLoadText, NoLoadImage, NoLoadMovie, NoAddEffect, NoAddDraw, NoSetAnchor, out bool dirty, out _, out _, out _, out _, out string? error);
bool ok = RunWorker(script, fields, NoStringParams, () => pixels, w, h, 5000, NoResolver, NoLoadFigure, NoLoadText, NoLoadImage, NoLoadMovie, NoAddEffect, NoAddDraw, NoSetAnchor, out bool dirty, out _, out _, out _, out _, out string? error);
Assert.True(ok, error);
Assert.True(dirty);
@@ -729,11 +1014,11 @@ namespace LuaScript.Tests
stored[3] = 255; stored[7] = 255; stored[11] = 255; stored[15] = 255;
var save = (byte[])stored.Clone();
bool ok = _worker.Execute("obj.copybuffer('cache:foo','obj')", Fields(w, h, 0d), NoStringParams, () => save, w, h, 5000, NoResolver, NoLoadFigure, NoLoadText, NoLoadImage, NoLoadMovie, NoAddEffect, NoAddDraw, NoSetAnchor, out _, out _, out _, out _, out _, out string? error);
bool ok = RunWorker("obj.copybuffer('cache:foo','obj')", Fields(w, h, 0d), NoStringParams, () => save, w, h, 5000, NoResolver, NoLoadFigure, NoLoadText, NoLoadImage, NoLoadMovie, NoAddEffect, NoAddDraw, NoSetAnchor, out _, out _, out _, out _, out _, out string? error);
Assert.True(ok, error);
var blank = new byte[w * h * 4];
ok = _worker.Execute("obj.copybuffer('obj','cache:foo')", Fields(w, h, 0d), NoStringParams, () => blank, w, h, 5000, NoResolver, NoLoadFigure, NoLoadText, NoLoadImage, NoLoadMovie, NoAddEffect, NoAddDraw, NoSetAnchor, out bool dirty, out _, out byte[]? restored, out _, out _, out error);
ok = RunWorker("obj.copybuffer('obj','cache:foo')", Fields(w, h, 0d), NoStringParams, () => blank, w, h, 5000, NoResolver, NoLoadFigure, NoLoadText, NoLoadImage, NoLoadMovie, NoAddEffect, NoAddDraw, NoSetAnchor, out bool dirty, out _, out byte[]? restored, out _, out _, out error);
Assert.True(ok, error);
Assert.True(dirty);
Assert.NotNull(restored);
@@ -750,7 +1035,7 @@ namespace LuaScript.Tests
Func<byte[]> loadPixels = () => { loads++; return pixels; };
var fields = Fields(2, 2, 1d);
bool ok = _worker.Execute(
bool ok = RunWorker(
"obj.x = obj.time * 10 obj.draw()",
fields, NoStringParams, loadPixels, 2, 2, 5000, NoResolver, NoLoadFigure, NoLoadText, NoLoadImage, NoLoadMovie, NoAddEffect, NoAddDraw, NoSetAnchor,
out bool dirty, out _, out _, out _, out _, out string? error);
@@ -771,7 +1056,7 @@ namespace LuaScript.Tests
int loads = 0;
Func<byte[]> loadPixels = () => { loads++; return pixels; };
bool ok = _worker.Execute(
bool ok = RunWorker(
"for y=0,obj.h-1 do for x=0,obj.w-1 do local r,g,b,a = obj.getpixel(x,y) obj.setpixel(x,y,r,g,b,a) end end",
Fields(2, 2, 0d), NoStringParams, loadPixels, 2, 2, 5000, NoResolver, NoLoadFigure, NoLoadText, NoLoadImage, NoLoadMovie, NoAddEffect, NoAddDraw, NoSetAnchor,
out bool dirty, out _, out _, out _, out _, out string? error);
@@ -791,11 +1076,11 @@ namespace LuaScript.Tests
stored[i] = (byte)((i * 41 + 13) & 0xFF);
stored[3] = 255; stored[7] = 255; stored[11] = 255; stored[15] = 255;
bool ok = _worker.Execute("obj.copybuffer('cache:sz','obj')", Fields(2, 2, 0d), NoStringParams, () => stored, 2, 2, 5000, NoResolver, NoLoadFigure, NoLoadText, NoLoadImage, NoLoadMovie, NoAddEffect, NoAddDraw, NoSetAnchor, out _, out _, out _, out _, out _, out string? error);
bool ok = RunWorker("obj.copybuffer('cache:sz','obj')", Fields(2, 2, 0d), NoStringParams, () => stored, 2, 2, 5000, NoResolver, NoLoadFigure, NoLoadText, NoLoadImage, NoLoadMovie, NoAddEffect, NoAddDraw, NoSetAnchor, out _, out _, out _, out _, out _, out string? error);
Assert.True(ok, error);
var bigger = new byte[4 * 4 * 4];
ok = _worker.Execute("obj.copybuffer('obj','cache:sz')", Fields(4, 4, 0d), NoStringParams, () => bigger, 4, 4, 5000, NoResolver, NoLoadFigure, NoLoadText, NoLoadImage, NoLoadMovie, NoAddEffect, NoAddDraw, NoSetAnchor, out bool dirty, out bool bufferReplaced, out byte[]? restored, out int rw, out int rh, out error);
ok = RunWorker("obj.copybuffer('obj','cache:sz')", Fields(4, 4, 0d), NoStringParams, () => bigger, 4, 4, 5000, NoResolver, NoLoadFigure, NoLoadText, NoLoadImage, NoLoadMovie, NoAddEffect, NoAddDraw, NoSetAnchor, out bool dirty, out bool bufferReplaced, out byte[]? restored, out int rw, out int rh, out error);
Assert.True(ok, error);
Assert.True(dirty);
Assert.True(bufferReplaced);
@@ -824,7 +1109,7 @@ namespace LuaScript.Tests
"obj.y = totalframe + framerate + layer " +
"obj.z = timelineframe + timelinetime";
bool ok = _worker.Execute(script, fields, NoStringParams, () => pixels, 2, 2, 5000, NoResolver, NoLoadFigure, NoLoadText, NoLoadImage, NoLoadMovie, NoAddEffect, NoAddDraw, NoSetAnchor, out _, out _, out _, out _, out _, out string? error);
bool ok = RunWorker(script, fields, NoStringParams, () => pixels, 2, 2, 5000, NoResolver, NoLoadFigure, NoLoadText, NoLoadImage, NoLoadMovie, NoAddEffect, NoAddDraw, NoSetAnchor, out _, out _, out _, out _, out _, out string? error);
Assert.True(ok, error);
Assert.Equal(30d, fields[NativeProtocol.X]);
@@ -839,19 +1124,245 @@ namespace LuaScript.Tests
var pixels = new byte[16];
bool ok = _worker.Execute(
bool ok = RunWorker(
"leak = 42 obj.leaked = 7 scene.custom = 1 ymm4.custom = 2",
Fields(2, 2, 0d), NoStringParams, () => pixels, 2, 2, 5000, NoResolver, NoLoadFigure, NoLoadText, NoLoadImage, NoLoadMovie, NoAddEffect, NoAddDraw, NoSetAnchor, out _, out _, out _, out _, out _, out string? error);
Assert.True(ok, error);
var fields = Fields(2, 2, 0d);
ok = _worker.Execute(
ok = RunWorker(
"obj.x = (leak == nil and 1 or 0) + (obj.leaked == nil and 10 or 0) + (scene.custom == nil and 100 or 0) + (ymm4.custom == nil and 1000 or 0)",
fields, NoStringParams, () => pixels, 2, 2, 5000, NoResolver, NoLoadFigure, NoLoadText, NoLoadImage, NoLoadMovie, NoAddEffect, NoAddDraw, NoSetAnchor, out _, out _, out _, out _, out _, out error);
Assert.True(ok, error);
Assert.Equal(1111d, fields[NativeProtocol.X]);
}
private Dictionary<string, SceneValue> BindSceneValues()
{
var values = new Dictionary<string, SceneValue>(StringComparer.Ordinal);
_sceneGet = name => values.TryGetValue(name, out var value) ? value : SceneValue.Nil;
_sceneSet = (name, value) =>
{
if (value.Kind == SceneValueKind.Nil)
values.Remove(name);
else
values[name] = value;
};
return values;
}
[Fact]
public void SceneSet_RoundTripsAllValueKinds()
{
Assert.True(LuaJitWorker.IsAvailable(NativeDir), "native/luajit.exe must be present");
var values = BindSceneValues();
var pixels = new byte[16];
const string script =
"scene.set('num', 12.5) " +
"scene.set('text', 'こんにちは') " +
"scene.set('flag', true) " +
"scene.set('gone', 1) scene.set('gone', nil) " +
"scene.set(1, 'ignored') " +
"scene.set('table', {})";
bool ok = RunWorker(script, Fields(2, 2, 0d), NoStringParams, () => pixels, 2, 2, 5000, NoResolver, NoLoadFigure, NoLoadText, NoLoadImage, NoLoadMovie, NoAddEffect, NoAddDraw, NoSetAnchor, out _, out _, out _, out _, out _, out string? error);
Assert.True(ok, error);
Assert.Equal(SceneValue.FromNumber(12.5), values["num"]);
Assert.Equal(SceneValue.FromString("こんにちは"), values["text"]);
Assert.Equal(SceneValue.FromBoolean(true), values["flag"]);
Assert.False(values.ContainsKey("gone"));
Assert.False(values.ContainsKey("table"));
}
[Fact]
public void SceneGet_ReturnsAllValueKinds()
{
Assert.True(LuaJitWorker.IsAvailable(NativeDir), "native/luajit.exe must be present");
var values = BindSceneValues();
values["num"] = SceneValue.FromNumber(-3.25);
values["text"] = SceneValue.FromString("値テキスト");
values["flag"] = SceneValue.FromBoolean(true);
var pixels = new byte[16];
var fields = Fields(2, 2, 0d);
const string script =
"obj.x = scene.get('num') " +
"obj.y = string.len(scene.get('text')) " +
"obj.z = scene.get('flag') == true and 1 or 0 " +
"obj.alpha = (scene.get('missing') == nil and 1 or 0) + (scene.get(7) == nil and 10 or 0)";
bool ok = RunWorker(script, fields, NoStringParams, () => pixels, 2, 2, 5000, NoResolver, NoLoadFigure, NoLoadText, NoLoadImage, NoLoadMovie, NoAddEffect, NoAddDraw, NoSetAnchor, out _, out _, out _, out _, out _, out string? error);
Assert.True(ok, error);
Assert.Equal(-3.25d, fields[NativeProtocol.X]);
Assert.Equal(System.Text.Encoding.UTF8.GetByteCount("値テキスト"), fields[NativeProtocol.Y]);
Assert.Equal(1d, fields[NativeProtocol.Z]);
Assert.Equal(11d, fields[NativeProtocol.Alpha]);
}
[Fact]
public void SceneValues_RoundTripAcrossWorkerRuns()
{
Assert.True(LuaJitWorker.IsAvailable(NativeDir), "native/luajit.exe must be present");
BindSceneValues();
var pixels = new byte[16];
var fields = Fields(2, 2, 0d);
const string script =
"scene.set('counter', (scene.get('counter') or 0) + 1) " +
"obj.x = scene.get('counter')";
for (int i = 1; i <= 3; i++)
{
bool ok = RunWorker(script, fields, NoStringParams, () => pixels, 2, 2, 5000, NoResolver, NoLoadFigure, NoLoadText, NoLoadImage, NoLoadMovie, NoAddEffect, NoAddDraw, NoSetAnchor, out _, out _, out _, out _, out _, out string? error);
Assert.True(ok, error);
Assert.Equal(i, fields[NativeProtocol.X]);
}
}
[Fact]
public void SceneGet_CachesRepeatedReadsWithinRun_AndResetsPerRun()
{
Assert.True(LuaJitWorker.IsAvailable(NativeDir), "native/luajit.exe must be present");
int hostReads = 0;
_sceneGet = _ => { hostReads++; return SceneValue.FromNumber(42d); };
var pixels = new byte[16];
const string script =
"local total = 0 " +
"for i = 1, 100 do total = total + scene.get('key') end " +
"obj.x = total";
for (int run = 1; run <= 2; run++)
{
var fields = Fields(2, 2, 0d);
bool ok = RunWorker(script, fields, NoStringParams, () => pixels, 2, 2, 5000, NoResolver, NoLoadFigure, NoLoadText, NoLoadImage, NoLoadMovie, NoAddEffect, NoAddDraw, NoSetAnchor, out _, out _, out _, out _, out _, out string? error);
Assert.True(ok, error);
Assert.Equal(4200d, fields[NativeProtocol.X]);
Assert.Equal(run, hostReads);
}
}
[Fact]
public void SceneSet_IsReadBackWithoutHostRead()
{
Assert.True(LuaJitWorker.IsAvailable(NativeDir), "native/luajit.exe must be present");
int hostReads = 0;
_sceneGet = _ => { hostReads++; return SceneValue.Nil; };
var pixels = new byte[16];
var fields = Fields(2, 2, 0d);
const string script =
"scene.set('key', 7) " +
"obj.x = scene.get('key') " +
"scene.set('key', nil) " +
"obj.y = scene.get('key') == nil and 1 or 0";
bool ok = RunWorker(script, fields, NoStringParams, () => pixels, 2, 2, 5000, NoResolver, NoLoadFigure, NoLoadText, NoLoadImage, NoLoadMovie, NoAddEffect, NoAddDraw, NoSetAnchor, out _, out _, out _, out _, out _, out string? error);
Assert.True(ok, error);
Assert.Equal(0, hostReads);
Assert.Equal(7d, fields[NativeProtocol.X]);
Assert.Equal(1d, fields[NativeProtocol.Y]);
}
[Fact]
public void SceneStrings_CarryMaximumLengthNameAndValue()
{
Assert.True(LuaJitWorker.IsAvailable(NativeDir), "native/luajit.exe must be present");
var values = BindSceneValues();
string longName = new string('n', SceneSharedValues.MaxNameBytes);
string longValue = new string('v', SceneSharedValues.MaxTextBytes);
values[longName] = SceneValue.FromString(longValue);
var pixels = new byte[16];
var fields = Fields(2, 2, 0d);
string script =
"local name = string.rep('n', " + SceneSharedValues.MaxNameBytes + ") " +
"obj.x = string.len(scene.get(name)) " +
"scene.set(name, string.rep('w', " + (SceneSharedValues.MaxTextBytes + 500) + ")) " +
"obj.y = string.len(scene.get(name))";
bool ok = RunWorker(script, fields, NoStringParams, () => pixels, 2, 2, 5000, NoResolver, NoLoadFigure, NoLoadText, NoLoadImage, NoLoadMovie, NoAddEffect, NoAddDraw, NoSetAnchor, out _, out _, out _, out _, out _, out string? error);
Assert.True(ok, error);
Assert.Equal(SceneSharedValues.MaxTextBytes, fields[NativeProtocol.X]);
Assert.Equal(SceneSharedValues.MaxTextBytes, fields[NativeProtocol.Y]);
Assert.Equal(SceneSharedValues.MaxTextBytes, values[longName].Text!.Length);
Assert.True(values[longName].Text!.All(c => c == 'w'));
}
[Fact]
public void SceneStrings_TruncateAtUtf8Boundary()
{
Assert.True(LuaJitWorker.IsAvailable(NativeDir), "native/luajit.exe must be present");
var values = BindSceneValues();
var pixels = new byte[16];
var fields = Fields(2, 2, 0d);
string script =
"scene.set('key', string.rep('あ', 2000)) " +
"obj.x = string.len(scene.get('key'))";
bool ok = RunWorker(script, fields, NoStringParams, () => pixels, 2, 2, 5000, NoResolver, NoLoadFigure, NoLoadText, NoLoadImage, NoLoadMovie, NoAddEffect, NoAddDraw, NoSetAnchor, out _, out _, out _, out _, out _, out string? error);
Assert.True(ok, error);
int expectedBytes = SceneSharedValues.MaxTextBytes / 3 * 3;
Assert.Equal(expectedBytes, fields[NativeProtocol.X]);
var stored = values["key"];
Assert.Equal(SceneValueKind.String, stored.Kind);
Assert.Equal(expectedBytes / 3, stored.Text!.Length);
Assert.True(stored.Text!.All(c => c == 'あ'));
}
[Fact]
public void GlobalFunctions_MatchOracleInsideWorker()
{
Assert.True(LuaJitWorker.IsAvailable(NativeDir), "native/luajit.exe must be present");
var pixels = new byte[16];
var fields = Fields(2, 2, 0d);
const string script =
"obj.x = OR(8, 3) + AND(12, 6) + XOR(25, 11) " +
"obj.y = SHIFT(5, 3) + SHIFT(91, -2) " +
"obj.z = RGB(64, 192, 255) " +
"obj.alpha = HSV(60, 100, 100)";
bool ok = RunWorker(script, fields, NoStringParams, () => pixels, 2, 2, 5000, NoResolver, NoLoadFigure, NoLoadText, NoLoadImage, NoLoadMovie, NoAddEffect, NoAddDraw, NoSetAnchor, out _, out _, out _, out _, out _, out string? error);
Assert.True(ok, error);
Assert.Equal(11d + 4d + 18d, fields[NativeProtocol.X]);
Assert.Equal(40d + 22d, fields[NativeProtocol.Y]);
Assert.Equal(0x40C0FF, fields[NativeProtocol.Z]);
Assert.Equal(0xFFFF00, fields[NativeProtocol.Alpha]);
}
[Fact]
public void RgbInterpolation_UsesObjectTimeRatio()
{
Assert.True(LuaJitWorker.IsAvailable(NativeDir), "native/luajit.exe must be present");
var pixels = new byte[16];
var fields = Fields(2, 2, 1d);
fields[NativeProtocol.TotalTime] = 4d;
bool ok = RunWorker(
"obj.x = RGB(0, 0, 0, 100, 200, 40)",
fields, NoStringParams, () => pixels, 2, 2, 5000, NoResolver, NoLoadFigure, NoLoadText, NoLoadImage, NoLoadMovie, NoAddEffect, NoAddDraw, NoSetAnchor, out _, out _, out _, out _, out _, out string? error);
Assert.True(ok, error);
Assert.Equal(Compat.AviUtlGlobalFunctions.RgbInterpolate(0, 0, 0, 100, 200, 40, 0.25), fields[NativeProtocol.X]);
}
[Fact]
public void RuntimeError_IsReported_AndWorkerSurvives()
{
@@ -860,12 +1371,12 @@ namespace LuaScript.Tests
var pixels = new byte[16];
var fields = Fields(2, 2, 0d);
bool ok = _worker.Execute("obj.x = missing.value", fields, NoStringParams, () => pixels, 2, 2, 5000, NoResolver, NoLoadFigure, NoLoadText, NoLoadImage, NoLoadMovie, NoAddEffect, NoAddDraw, NoSetAnchor, out _, out _, out _, out _, out _, out string? error);
bool ok = RunWorker("obj.x = missing.value", fields, NoStringParams, () => pixels, 2, 2, 5000, NoResolver, NoLoadFigure, NoLoadText, NoLoadImage, NoLoadMovie, NoAddEffect, NoAddDraw, NoSetAnchor, out _, out _, out _, out _, 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, NoStringParams, () => pixels, 2, 2, 5000, NoResolver, NoLoadFigure, NoLoadText, NoLoadImage, NoLoadMovie, NoAddEffect, NoAddDraw, NoSetAnchor, out _, out _, out _, out _, out _, out error);
bool ok2 = RunWorker("obj.x = obj.time", fields2, NoStringParams, () => pixels, 2, 2, 5000, NoResolver, NoLoadFigure, NoLoadText, NoLoadImage, NoLoadMovie, NoAddEffect, NoAddDraw, NoSetAnchor, out _, out _, out _, out _, out _, out error);
Assert.True(ok2, error);
Assert.Equal(7d, fields2[NativeProtocol.X]);
}
+188
ファイルの表示
@@ -0,0 +1,188 @@
namespace LuaScript.Tests
{
public class SceneSharedValuesTests
{
private static Dictionary<string, SceneValue> Writes(params (string Name, SceneValue Value)[] entries)
{
var writes = new Dictionary<string, SceneValue>(StringComparer.Ordinal);
foreach (var (name, value) in entries)
writes[name] = value;
return writes;
}
[Fact]
public void Publish_IsInvisibleAtOwnFrame_AndVisibleImmediatelyAfter()
{
var store = new SceneSharedValues();
store.Publish(10, 0, Writes(("key", SceneValue.FromNumber(1d))));
Assert.Equal(SceneValue.Nil, store.Read(10, "key"));
Assert.Equal(SceneValue.FromNumber(1d), store.Read(11, "key"));
Assert.Equal(SceneValue.FromNumber(1d), store.Read(1000, "key"));
}
[Fact]
public void Read_IsOrderIndependentWithinFrame()
{
var store = new SceneSharedValues();
store.Publish(0, 0, Writes(("key", SceneValue.FromNumber(1d))));
Assert.Equal(SceneValue.FromNumber(1d), store.Read(1, "key"));
store.Publish(1, 0, Writes(("key", SceneValue.FromNumber(2d))));
Assert.Equal(SceneValue.FromNumber(1d), store.Read(1, "key"));
store.Publish(1, 1, Writes(("other", SceneValue.FromNumber(3d))));
Assert.Equal(SceneValue.FromNumber(1d), store.Read(1, "key"));
Assert.Equal(SceneValue.FromNumber(2d), store.Read(2, "key"));
Assert.Equal(SceneValue.FromNumber(3d), store.Read(2, "other"));
}
[Fact]
public void RandomSeek_ReadsAreDeterministicPerFrame()
{
var store = new SceneSharedValues();
store.Publish(10, 0, Writes(("key", SceneValue.FromNumber(1d))));
store.Publish(20, 0, Writes(("key", SceneValue.FromNumber(2d))));
Assert.Equal(SceneValue.Nil, store.Read(5, "key"));
Assert.Equal(SceneValue.FromNumber(1d), store.Read(15, "key"));
Assert.Equal(SceneValue.FromNumber(2d), store.Read(25, "key"));
Assert.Equal(SceneValue.FromNumber(1d), store.Read(15, "key"));
Assert.Equal(SceneValue.Nil, store.Read(5, "key"));
store.Publish(30, 0, Writes(("key", SceneValue.FromNumber(3d))));
Assert.Equal(SceneValue.Nil, store.Read(5, "key"));
Assert.Equal(SceneValue.FromNumber(1d), store.Read(15, "key"));
Assert.Equal(SceneValue.FromNumber(2d), store.Read(25, "key"));
Assert.Equal(SceneValue.FromNumber(3d), store.Read(35, "key"));
}
[Fact]
public void BackwardSeekPublish_InsertsIntoHistoryInOrder()
{
var store = new SceneSharedValues();
store.Publish(20, 0, Writes(("key", SceneValue.FromNumber(2d))));
store.Publish(10, 0, Writes(("key", SceneValue.FromNumber(1d))));
Assert.Equal(SceneValue.Nil, store.Read(10, "key"));
Assert.Equal(SceneValue.FromNumber(1d), store.Read(15, "key"));
Assert.Equal(SceneValue.FromNumber(2d), store.Read(25, "key"));
}
[Fact]
public void NilWrite_RecordsRemovalWithoutErasingHistory()
{
var store = new SceneSharedValues();
store.Publish(10, 0, Writes(("key", SceneValue.FromNumber(1d))));
store.Publish(20, 0, Writes(("key", SceneValue.Nil)));
Assert.Equal(SceneValue.FromNumber(1d), store.Read(15, "key"));
Assert.Equal(SceneValue.Nil, store.Read(25, "key"));
store.Publish(30, 0, Writes(("key", SceneValue.FromNumber(3d))));
Assert.Equal(SceneValue.Nil, store.Read(25, "key"));
Assert.Equal(SceneValue.FromNumber(3d), store.Read(31, "key"));
}
[Fact]
public void SameFrameConflict_HigherLayerWinsRegardlessOfPublishOrder()
{
var forward = new SceneSharedValues();
forward.Publish(0, 3, Writes(("key", SceneValue.FromNumber(3d))));
forward.Publish(0, 5, Writes(("key", SceneValue.FromNumber(5d))));
var reverse = new SceneSharedValues();
reverse.Publish(0, 5, Writes(("key", SceneValue.FromNumber(5d))));
reverse.Publish(0, 3, Writes(("key", SceneValue.FromNumber(3d))));
Assert.Equal(SceneValue.FromNumber(5d), forward.Read(1, "key"));
Assert.Equal(SceneValue.FromNumber(5d), reverse.Read(1, "key"));
}
[Fact]
public void SameFrameSameLayer_LaterPublishReplaces()
{
var store = new SceneSharedValues();
store.Publish(0, 2, Writes(("key", SceneValue.FromNumber(1d))));
store.Publish(0, 2, Writes(("key", SceneValue.FromNumber(2d))));
Assert.Equal(SceneValue.FromNumber(2d), store.Read(1, "key"));
}
[Fact]
public void Republish_IsIdempotent()
{
var store = new SceneSharedValues();
for (int i = 0; i < 5; i++)
store.Publish(7, 1, Writes(("key", SceneValue.FromNumber(9d))));
Assert.Equal(SceneValue.Nil, store.Read(7, "key"));
Assert.Equal(SceneValue.FromNumber(9d), store.Read(8, "key"));
}
[Fact]
public void Capacity_LimitsDistinctNames_AndKeepsExistingUpdatable()
{
var store = new SceneSharedValues();
var writes = new Dictionary<string, SceneValue>(StringComparer.Ordinal);
for (int i = 0; i < SceneSharedValues.MaxEntries; i++)
writes["k" + i] = SceneValue.FromNumber(i);
store.Publish(0, 0, writes);
store.Publish(1, 0, Writes(
("overflow", SceneValue.FromNumber(1d)),
("k0", SceneValue.FromNumber(-1d))));
Assert.Equal(SceneValue.Nil, store.Read(2, "overflow"));
Assert.Equal(SceneValue.FromNumber(-1d), store.Read(2, "k0"));
store.Publish(2, 0, Writes(("k1", SceneValue.Nil)));
Assert.Equal(SceneValue.Nil, store.Read(3, "k1"));
}
[Fact]
public void NilWritesToUnknownNames_DoNotConsumeCapacity()
{
var store = new SceneSharedValues();
var removals = new Dictionary<string, SceneValue>(StringComparer.Ordinal);
for (int i = 0; i < SceneSharedValues.MaxEntries; i++)
removals["ghost" + i] = SceneValue.Nil;
store.Publish(0, 0, removals);
store.Publish(1, 0, Writes(("real", SceneValue.FromNumber(1d))));
Assert.Equal(SceneValue.FromNumber(1d), store.Read(2, "real"));
}
[Fact]
public void HistoryBudget_EvictsOldestVersionsAndKeepsNewest()
{
var store = new SceneSharedValues();
string payload = new('x', SceneSharedValues.MaxTextBytes - 5);
int frames = (int)(SceneSharedValues.MaxHistoryCostBytes /
(SceneSharedValues.MaxTextBytes * 2L)) + 200;
for (int i = 0; i < frames; i++)
store.Publish(i, 0, Writes(("key", SceneValue.FromString(payload + i.ToString("D5")))));
Assert.Equal(SceneValue.Nil, store.Read(1, "key"));
Assert.Equal(
SceneValue.FromString(payload + (frames - 1).ToString("D5")),
store.Read(frames, "key"));
}
[Fact]
public void ForScene_IsolatesScopesAndScenes_AndSharesWithinBoth()
{
object scopeA = new();
object scopeB = new();
string sceneA = Guid.NewGuid().ToString();
string sceneB = Guid.NewGuid().ToString();
SceneSharedValues.ForScene(scopeA, sceneA).Publish(0, 0, Writes(("key", SceneValue.FromNumber(1d))));
Assert.Equal(SceneValue.FromNumber(1d), SceneSharedValues.ForScene(scopeA, sceneA).Read(1, "key"));
Assert.Equal(SceneValue.Nil, SceneSharedValues.ForScene(scopeA, sceneB).Read(1, "key"));
Assert.Equal(SceneValue.Nil, SceneSharedValues.ForScene(scopeB, sceneA).Read(1, "key"));
Assert.Same(SceneSharedValues.ForScene(scopeA, sceneA), SceneSharedValues.ForScene(scopeA, sceneA));
}
}
}
+132
ファイルの表示
@@ -0,0 +1,132 @@
using MoonSharp.Interpreter;
namespace LuaScript.Tests
{
public class SceneTableRegistrarTests
{
private sealed class Harness
{
private readonly object _scope = new();
private readonly string _sceneId = Guid.NewGuid().ToString();
private long _generation;
public Script Script { get; }
public SceneValueSession Session { get; } = new();
public Harness()
{
Script = new Script(CoreModules.Basic | CoreModules.Math | CoreModules.String | CoreModules.Table);
var scene = new Table(Script);
SceneTableRegistrar.RegisterFunctions(scene, Session.Get, Session.Set);
Script.Globals["scene"] = scene;
Session.Begin(_scope, _sceneId, _generation, 0);
}
public DynValue Run(string code)
{
var result = Script.DoString(code);
Session.Publish();
return result;
}
public void NextFrame()
{
_generation++;
Session.Begin(_scope, _sceneId, _generation, 0);
}
public SceneValue Stored(string name)
{
NextFrame();
return Session.Get(name);
}
}
[Fact]
public void Set_StoresAllSupportedKinds()
{
var harness = new Harness();
harness.Run(
"scene.set('num', 4.25) " +
"scene.set('text', 'こんにちは') " +
"scene.set('flag', false)");
Assert.Equal(SceneValue.FromNumber(4.25), harness.Stored("num"));
Assert.Equal(SceneValue.FromString("こんにちは"), harness.Stored("text"));
Assert.Equal(SceneValue.FromBoolean(false), harness.Stored("flag"));
}
[Fact]
public void Set_NilOrMissingValue_Removes()
{
var harness = new Harness();
harness.Run("scene.set('a', 1) scene.set('b', 2)");
harness.NextFrame();
harness.Run("scene.set('a', nil) scene.set('b')");
Assert.Equal(SceneValue.Nil, harness.Stored("a"));
Assert.Equal(SceneValue.Nil, harness.Stored("b"));
}
[Fact]
public void Set_UnsupportedTypesAndNames_AreIgnored()
{
var harness = new Harness();
harness.Run("scene.set('keep', 9)");
harness.NextFrame();
harness.Run(
"scene.set('keep', {}) " +
"scene.set('fn', function() end) " +
"scene.set(12, 'x') " +
"scene.set()");
Assert.Equal(SceneValue.FromNumber(9d), harness.Stored("keep"));
Assert.Equal(SceneValue.Nil, harness.Stored("fn"));
}
[Fact]
public void Get_ReturnsStoredValuesWithLuaTypes()
{
var harness = new Harness();
harness.Run(
"scene.set('num', -8.5) " +
"scene.set('text', 'v') " +
"scene.set('flag', true)");
harness.NextFrame();
var result = harness.Run(
"return scene.get('num'), scene.get('text'), scene.get('flag'), scene.get('missing'), scene.get(1)");
Assert.Equal(DataType.Tuple, result.Type);
Assert.Equal(-8.5d, result.Tuple[0].Number);
Assert.Equal("v", result.Tuple[1].String);
Assert.True(result.Tuple[2].Boolean);
Assert.Equal(DataType.Nil, result.Tuple[3].Type);
Assert.Equal(DataType.Nil, result.Tuple[4].Type);
}
[Fact]
public void SetAndGet_RoundTripWithinScript()
{
var harness = new Harness();
var result = harness.Run(
"scene.set('counter', (scene.get('counter') or 0) + 1) " +
"scene.set('counter', (scene.get('counter') or 0) + 1) " +
"return scene.get('counter')");
Assert.Equal(2d, result.Number);
}
[Fact]
public void Counter_AccumulatesAcrossFrames()
{
var harness = new Harness();
const string script = "scene.set('counter', (scene.get('counter') or 0) + 1) return scene.get('counter')";
Assert.Equal(1d, harness.Run(script).Number);
harness.NextFrame();
Assert.Equal(2d, harness.Run(script).Number);
harness.NextFrame();
Assert.Equal(3d, harness.Run(script).Number);
}
}
}
+225
ファイルの表示
@@ -0,0 +1,225 @@
using System.Text;
namespace LuaScript.Tests
{
public class SceneValueSessionTests
{
private static string NewSceneId() => Guid.NewGuid().ToString();
[Fact]
public void Get_ReturnsOwnWriteWithinRun()
{
var session = new SceneValueSession();
session.Begin(new object(), NewSceneId(), 0, 0);
Assert.Equal(SceneValue.Nil, session.Get("key"));
session.Set("key", SceneValue.FromNumber(1d));
Assert.Equal(SceneValue.FromNumber(1d), session.Get("key"));
session.Set("key", SceneValue.Nil);
Assert.Equal(SceneValue.Nil, session.Get("key"));
}
[Fact]
public void Writes_AreDiscardedWithoutPublish()
{
object scope = new();
string sceneId = NewSceneId();
var session = new SceneValueSession();
session.Begin(scope, sceneId, 0, 0);
session.Set("key", SceneValue.FromNumber(1d));
session.Begin(scope, sceneId, 1, 0);
Assert.Equal(SceneValue.Nil, session.Get("key"));
}
[Fact]
public void PublishedWrites_AreVisibleFromNextFrame_WithoutIntermediateFrames()
{
object scope = new();
string sceneId = NewSceneId();
var writer = new SceneValueSession();
var reader = new SceneValueSession();
writer.Begin(scope, sceneId, 0, 0);
writer.Set("key", SceneValue.FromNumber(1d));
writer.Publish();
reader.Begin(scope, sceneId, 0, 1);
Assert.Equal(SceneValue.Nil, reader.Get("key"));
reader.Begin(scope, sceneId, 1, 1);
Assert.Equal(SceneValue.FromNumber(1d), reader.Get("key"));
reader.Begin(scope, sceneId, 1000, 1);
Assert.Equal(SceneValue.FromNumber(1d), reader.Get("key"));
}
[Fact]
public void ReadResults_AreStableWithinRun()
{
object scope = new();
string sceneId = NewSceneId();
var writer = new SceneValueSession();
var reader = new SceneValueSession();
writer.Begin(scope, sceneId, 0, 0);
writer.Set("key", SceneValue.FromNumber(1d));
writer.Publish();
reader.Begin(scope, sceneId, 1, 1);
Assert.Equal(SceneValue.FromNumber(1d), reader.Get("key"));
writer.Begin(scope, sceneId, 0, 0);
writer.Set("key", SceneValue.FromNumber(2d));
writer.Publish();
Assert.Equal(SceneValue.FromNumber(1d), reader.Get("key"));
}
[Fact]
public void BackwardSeek_ReadsValuesCommittedBeforeThatFrameOnly()
{
object scope = new();
string sceneId = NewSceneId();
var writer = new SceneValueSession();
var reader = new SceneValueSession();
writer.Begin(scope, sceneId, 10, 0);
writer.Set("key", SceneValue.FromNumber(1d));
writer.Publish();
writer.Begin(scope, sceneId, 20, 0);
writer.Set("key", SceneValue.FromNumber(2d));
writer.Publish();
reader.Begin(scope, sceneId, 25, 1);
Assert.Equal(SceneValue.FromNumber(2d), reader.Get("key"));
reader.Begin(scope, sceneId, 15, 1);
Assert.Equal(SceneValue.FromNumber(1d), reader.Get("key"));
reader.Begin(scope, sceneId, 5, 1);
Assert.Equal(SceneValue.Nil, reader.Get("key"));
}
[Fact]
public void SameFrame_HigherLayerWinsAcrossSessions()
{
object scope = new();
string sceneId = NewSceneId();
var lower = new SceneValueSession();
var upper = new SceneValueSession();
var reader = new SceneValueSession();
upper.Begin(scope, sceneId, 0, 5);
upper.Set("key", SceneValue.FromNumber(5d));
upper.Publish();
lower.Begin(scope, sceneId, 0, 3);
lower.Set("key", SceneValue.FromNumber(3d));
lower.Publish();
reader.Begin(scope, sceneId, 1, 0);
Assert.Equal(SceneValue.FromNumber(5d), reader.Get("key"));
}
[Fact]
public void Scopes_IsolateSessionsSharingSceneId()
{
string sceneId = NewSceneId();
var writer = new SceneValueSession();
var reader = new SceneValueSession();
writer.Begin(new object(), sceneId, 0, 0);
writer.Set("key", SceneValue.FromNumber(1d));
writer.Publish();
reader.Begin(new object(), sceneId, 1, 0);
Assert.Equal(SceneValue.Nil, reader.Get("key"));
}
[Fact]
public void Queries_TrackDistinctStoreReadsOnly()
{
var session = new SceneValueSession();
session.Begin(new object(), NewSceneId(), 0, 0);
session.Get("a");
session.Get("a");
session.Get("b");
session.Set("c", SceneValue.FromNumber(1d));
session.Get("c");
Assert.Equal(2, session.Queries.Count);
Assert.Equal("a", session.Queries[0].Name);
Assert.Equal("b", session.Queries[1].Name);
}
[Fact]
public void HasWrites_ReflectsWritesIncludingRemovals()
{
object scope = new();
var session = new SceneValueSession();
session.Begin(scope, NewSceneId(), 0, 0);
Assert.False(session.HasWrites);
session.Set("key", SceneValue.Nil);
Assert.True(session.HasWrites);
session.Begin(scope, NewSceneId(), 0, 0);
Assert.False(session.HasWrites);
}
[Fact]
public void Set_TruncatesLongTextAtUtf8Boundary()
{
var session = new SceneValueSession();
session.Begin(new object(), NewSceneId(), 0, 0);
string text = new('あ', 2000);
session.Set("key", SceneValue.FromString(text));
var stored = session.Get("key");
Assert.Equal(SceneValueKind.String, stored.Kind);
Assert.Equal(SceneSharedValues.MaxTextBytes / 3, stored.Text!.Length);
Assert.True(Encoding.UTF8.GetByteCount(stored.Text) <= SceneSharedValues.MaxTextBytes);
Assert.StartsWith(stored.Text, text, StringComparison.Ordinal);
}
[Fact]
public void LongNames_AreTruncatedConsistentlyAcrossSetAndGet()
{
object scope = new();
string sceneId = NewSceneId();
var session = new SceneValueSession();
string name = new('k', SceneSharedValues.MaxNameBytes + 100);
session.Begin(scope, sceneId, 0, 0);
session.Set(name, SceneValue.FromNumber(7d));
Assert.Equal(SceneValue.FromNumber(7d), session.Get(name));
session.Publish();
session.Begin(scope, sceneId, 1, 0);
Assert.Equal(SceneValue.FromNumber(7d), session.Get(name[..SceneSharedValues.MaxNameBytes]));
}
[Fact]
public void Sessions_FollowSceneIdChanges()
{
object scope = new();
string sceneA = NewSceneId();
string sceneB = NewSceneId();
var session = new SceneValueSession();
session.Begin(scope, sceneA, 0, 0);
session.Set("key", SceneValue.FromNumber(1d));
session.Publish();
session.Begin(scope, sceneB, 1, 0);
Assert.Equal(SceneValue.Nil, session.Get("key"));
session.Begin(scope, sceneA, 1, 0);
Assert.Equal(SceneValue.FromNumber(1d), session.Get("key"));
}
}
}
+44
ファイルの表示
@@ -0,0 +1,44 @@
using MoonSharp.Interpreter;
namespace LuaScript
{
internal sealed class AviUtlFontState
{
public string Family { get; private set; } = string.Empty;
public double Size { get; private set; } = 34d;
public bool Bold { get; private set; }
public bool Italic { get; private set; }
public int Color { get; private set; } = 0xFFFFFF;
public void Reset()
{
Family = string.Empty;
Size = 34d;
Bold = false;
Italic = false;
Color = 0xFFFFFF;
}
public void Apply(DynValue name, DynValue size, DynValue style, DynValue color)
{
if (name.Type == DataType.String)
Family = name.String;
else if (name.Type == DataType.Number)
Family = name.CastToString();
Size = size.CastToNumber() ?? Size;
if (style.CastToNumber() is double styleNumber)
{
double flags = Math.Floor(styleNumber);
Bold = FloorMod(flags, 2d) == 1d;
Italic = FloorMod(Math.Floor(flags / 2d), 2d) == 1d;
}
Color = (int)(color.CastToNumber() ?? Color);
}
private static double FloorMod(double value, double divisor) =>
value - Math.Floor(value / divisor) * divisor;
}
}
+81
ファイルの表示
@@ -0,0 +1,81 @@
using LuaScript.Compat;
using LuaScript.Diagnostics;
using MoonSharp.Interpreter;
namespace LuaScript
{
internal static class AviUtlGlobalRegistrar
{
internal static void RegisterFunctions(Table globals, Func<double> timeRatio)
{
globals["debug_print"] = DynValue.NewCallback((_, args) =>
{
if (args.Count > 0)
{
var value = args[0];
DebugOutput.Write(value.Type == DataType.String ? value.String : value.ToPrintString());
}
return DynValue.Void;
});
globals["RGB"] = DynValue.NewCallback((_, args) =>
{
int count = args.Count;
if (count >= 6)
return DynValue.NewNumber(AviUtlGlobalFunctions.RgbInterpolate(
Number(args, 0), Number(args, 1), Number(args, 2),
Number(args, 3), Number(args, 4), Number(args, 5),
timeRatio()));
if (count >= 3)
return DynValue.NewNumber(AviUtlGlobalFunctions.RgbCompose(
Number(args, 0), Number(args, 1), Number(args, 2)));
if (count >= 1)
{
AviUtlGlobalFunctions.RgbComponents(Number(args, 0), out int r, out int g, out int b);
return DynValue.NewTuple(
DynValue.NewNumber(r),
DynValue.NewNumber(g),
DynValue.NewNumber(b));
}
return DynValue.Nil;
});
globals["HSV"] = DynValue.NewCallback((_, args) =>
{
int count = args.Count;
if (count >= 6)
return DynValue.NewNumber(AviUtlGlobalFunctions.HsvInterpolate(
Number(args, 0), Number(args, 1), Number(args, 2),
Number(args, 3), Number(args, 4), Number(args, 5),
timeRatio()));
if (count >= 3)
return DynValue.NewNumber(AviUtlGlobalFunctions.HsvCompose(
Number(args, 0), Number(args, 1), Number(args, 2)));
if (count >= 1)
{
AviUtlGlobalFunctions.HsvComponents(Number(args, 0), out int h, out int s, out int v);
return DynValue.NewTuple(
DynValue.NewNumber(h),
DynValue.NewNumber(s),
DynValue.NewNumber(v));
}
return DynValue.Nil;
});
globals["OR"] = DynValue.NewCallback((_, args) =>
DynValue.NewNumber(AviUtlGlobalFunctions.BitOr(Number(args, 0), Number(args, 1))));
globals["AND"] = DynValue.NewCallback((_, args) =>
DynValue.NewNumber(AviUtlGlobalFunctions.BitAnd(Number(args, 0), Number(args, 1))));
globals["XOR"] = DynValue.NewCallback((_, args) =>
DynValue.NewNumber(AviUtlGlobalFunctions.BitXor(Number(args, 0), Number(args, 1))));
globals["SHIFT"] = DynValue.NewCallback((_, args) =>
DynValue.NewNumber(AviUtlGlobalFunctions.BitShift(Number(args, 0), Number(args, 1))));
}
private static double Number(CallbackArguments args, int index) =>
args.Count > index ? args[index].CastToNumber() ?? 0d : 0d;
}
}
+25 -2
ファイルの表示
@@ -83,6 +83,20 @@ namespace LuaScript
public IReadOnlyList<SceneObjectQuery> ObjectQueries => _objectQueries;
private readonly SceneValueSession _sceneValues = new();
public IReadOnlyList<SceneValueQuery> SceneValueQueries => _sceneValues.Queries;
internal object? SceneScope { get; set; }
internal void BeginSceneValues() => _sceneValues.Begin(SceneScope ?? this, SceneId, TimelineFrame, Layer);
internal void PublishSceneValues() => _sceneValues.Publish();
public SceneValue GetSceneValue(string name) => _sceneValues.Get(name);
public void SetSceneValue(string name, SceneValue value) => _sceneValues.Set(name, value);
private readonly List<AviUtlEffectRequest> _effectRequests = [];
public IReadOnlyList<AviUtlEffectRequest> EffectRequests => _effectRequests;
@@ -185,20 +199,29 @@ namespace LuaScript
private bool TryWriteBuffer(string id, byte[] data, int width, int height)
{
int n = width * height * 4;
switch (BufferKind(id, out string key))
{
case 'o':
ReplaceBuffer((byte[])data.Clone(), width, height);
if (_copyOutputBuffer is null || _copyOutputBuffer.Length != n)
_copyOutputBuffer = new byte[n];
Buffer.BlockCopy(data, 0, _copyOutputBuffer, 0, n);
ReplaceBuffer(_copyOutputBuffer, width, height);
return true;
case 't':
case 'c':
_buffers[key] = ((byte[])data.Clone(), width, height);
if (!_buffers.TryGetValue(key, out var existing) || existing.Data.Length != n)
existing.Data = new byte[n];
Buffer.BlockCopy(data, 0, existing.Data, 0, n);
_buffers[key] = (existing.Data, width, height);
return false;
default:
return false;
}
}
private byte[]? _copyOutputBuffer;
private static char BufferKind(string id, out string key)
{
key = string.Empty;
+137
ファイルの表示
@@ -0,0 +1,137 @@
namespace LuaScript.Compat
{
internal static class AviUtlGlobalFunctions
{
public static int BitOr(double a, double b) => ToBitOperand(a) | ToBitOperand(b);
public static int BitAnd(double a, double b) => ToBitOperand(a) & ToBitOperand(b);
public static int BitXor(double a, double b) => ToBitOperand(a) ^ ToBitOperand(b);
public static int BitShift(double value, double shift)
{
int v = ToBitOperand(value);
int n = ToBitOperand(shift);
return n >= 0 ? v << n : v >> -n;
}
public static int ToBitOperand(double value)
{
if (double.IsNaN(value))
return 0;
if (value <= int.MinValue)
return int.MinValue;
if (value >= int.MaxValue)
return int.MaxValue;
return (int)Math.Ceiling(value - 0.5);
}
public static int RgbCompose(double r, double g, double b) =>
(ToColorChannel(r) << 16) | (ToColorChannel(g) << 8) | ToColorChannel(b);
public static void RgbComponents(double color, out int r, out int g, out int b)
{
int c = ToColor(color);
r = (c >> 16) & 0xFF;
g = (c >> 8) & 0xFF;
b = c & 0xFF;
}
public static int RgbInterpolate(double r1, double g1, double b1, double r2, double g2, double b2, double t) =>
RgbCompose(r1 + (r2 - r1) * t, g1 + (g2 - g1) * t, b1 + (b2 - b1) * t);
public static int HsvCompose(double h, double s, double v)
{
h = WrapHue(h);
s = ClampRatio(s);
v = ClampRatio(v);
double c = v * s;
double x = c * (1d - Math.Abs(h / 60d % 2d - 1d));
double m = v - c;
int sector = (int)Math.Floor(h / 60d);
double r, g, b;
if (sector == 0) { r = c; g = x; b = 0d; }
else if (sector == 1) { r = x; g = c; b = 0d; }
else if (sector == 2) { r = 0d; g = c; b = x; }
else if (sector == 3) { r = 0d; g = x; b = c; }
else if (sector == 4) { r = x; g = 0d; b = c; }
else { r = c; g = 0d; b = x; }
return (ToColorChannel(RoundHalfUp((r + m) * 255d)) << 16) |
(ToColorChannel(RoundHalfUp((g + m) * 255d)) << 8) |
ToColorChannel(RoundHalfUp((b + m) * 255d));
}
public static void HsvComponents(double color, out int h, out int s, out int v)
{
RgbComponents(color, out int r, out int g, out int b);
double rf = r / 255d;
double gf = g / 255d;
double bf = b / 255d;
double max = Math.Max(rf, Math.Max(gf, bf));
double min = Math.Min(rf, Math.Min(gf, bf));
double delta = max - min;
double hue = 0d;
if (delta > 0d)
{
if (max == rf)
hue = 60d * (((gf - bf) / delta % 6d + 6d) % 6d);
else if (max == gf)
hue = 60d * ((bf - rf) / delta + 2d);
else
hue = 60d * ((rf - gf) / delta + 4d);
}
h = (int)RoundHalfUp(hue);
s = (int)RoundHalfUp(max > 0d ? delta / max * 100d : 0d);
v = (int)RoundHalfUp(max * 100d);
}
public static int HsvInterpolate(double h1, double s1, double v1, double h2, double s2, double v2, double t) =>
HsvCompose(h1 + (h2 - h1) * t, s1 + (s2 - s1) * t, v1 + (v2 - v1) * t);
private static int ToColorChannel(double value)
{
if (double.IsNaN(value) || value <= 0d)
return 0;
if (value >= 255d)
return 255;
return (int)Math.Floor(value);
}
private static int ToColor(double value)
{
if (double.IsNaN(value))
return 0;
if (value <= int.MinValue)
value = int.MinValue;
else if (value >= int.MaxValue)
value = int.MaxValue;
long floored = (long)Math.Floor(value);
return (int)(floored & 0xFFFFFF);
}
private static double WrapHue(double h)
{
if (double.IsNaN(h) || double.IsInfinity(h))
return 0d;
double wrapped = h - Math.Floor(h / 360d) * 360d;
return wrapped >= 360d ? 0d : wrapped;
}
private static double ClampRatio(double value)
{
if (double.IsNaN(value) || value <= 0d)
return 0d;
if (value >= 100d)
return 1d;
return value / 100d;
}
private static double RoundHalfUp(double value) => Math.Floor(value + 0.5);
}
}
+12
ファイルの表示
@@ -0,0 +1,12 @@
using System.Runtime.InteropServices;
namespace LuaScript.Diagnostics
{
internal static partial class DebugOutput
{
[LibraryImport("kernel32.dll", EntryPoint = "OutputDebugStringW", StringMarshalling = StringMarshalling.Utf16)]
private static partial void OutputDebugStringW(string message);
internal static void Write(string message) => OutputDebugStringW(message);
}
}
+71 -4
ファイルの表示
@@ -1,28 +1,95 @@
using System.Diagnostics;
using System.Runtime.Intrinsics;
using System.Threading.Tasks;
namespace LuaScript.Engine.Kernel
{
internal sealed class CpuKernel(CpuKernel.RowDelegate row)
internal sealed class CpuKernel(CpuKernel.RowDelegate row, CpuKernel.RowDelegate? block)
{
public delegate void RowDelegate(byte[] buffer, int width, int rowBase, double y, double[] uniforms);
public delegate void RowDelegate(byte[] buffer, int rowBase, int xStart, int xEnd, double y, double[] uniforms);
private const int ParallelThreshold = 64;
private const int WarmupRunsPerPath = 1;
private const int TimedRunsPerPath = 3;
private readonly RowDelegate _row = row;
private readonly RowDelegate? _block = block;
private long _rowTicks;
private long _blockTicks;
private int _rowRuns;
private int _blockRuns;
private bool _nextIsBlock = true;
private bool _decided;
private bool _useBlock;
public bool? BlockAdopted => _decided ? _useBlock : null;
public void Execute(byte[] buffer, int width, int height, double[] uniforms)
{
if (_block is null || !Vector256.IsHardwareAccelerated)
{
Run(buffer, width, height, uniforms, false);
return;
}
if (_decided)
{
Run(buffer, width, height, uniforms, _useBlock);
return;
}
bool useBlock = _nextIsBlock;
_nextIsBlock = !_nextIsBlock;
long start = Stopwatch.GetTimestamp();
Run(buffer, width, height, uniforms, useBlock);
long elapsed = Stopwatch.GetTimestamp() - start;
if (useBlock)
{
if (_blockRuns >= WarmupRunsPerPath)
_blockTicks += elapsed;
_blockRuns++;
}
else
{
if (_rowRuns >= WarmupRunsPerPath)
_rowTicks += elapsed;
_rowRuns++;
}
if (_rowRuns >= WarmupRunsPerPath + TimedRunsPerPath &&
_blockRuns >= WarmupRunsPerPath + TimedRunsPerPath)
{
_useBlock = _blockTicks < _rowTicks;
_decided = true;
}
}
private void Run(byte[] buffer, int width, int height, double[] uniforms, bool useBlock)
{
var row = _row;
var block = useBlock ? _block : null;
int stride = width * 4;
int blockWidth = block is null ? 0 : width & ~3;
void RunRow(int y)
{
int rowBase = y * stride;
if (blockWidth > 0)
block!(buffer, rowBase, 0, blockWidth, y, uniforms);
if (blockWidth < width)
row(buffer, rowBase, blockWidth, width, y, uniforms);
}
if (height < ParallelThreshold)
{
for (int y = 0; y < height; y++)
row(buffer, width, y * stride, y, uniforms);
RunRow(y);
return;
}
Parallel.For(0, height, y => row(buffer, width, y * stride, y, uniforms));
Parallel.For(0, height, RunRow);
}
}
}
+12 -6
ファイルの表示
@@ -31,11 +31,15 @@ namespace LuaScript.Engine.Kernel
[KFunc.Max] = Binary(nameof(Math.Max)),
};
public static CpuKernel Compile(KernelProgram program)
public static CpuKernel Compile(KernelProgram program) =>
new(CompileRow(program), SimdKernelCompiler.TryCompile(program));
public static CpuKernel.RowDelegate CompileRow(KernelProgram program)
{
var buffer = Expression.Parameter(typeof(byte[]), "buffer");
var width = Expression.Parameter(typeof(int), "width");
var rowBase = Expression.Parameter(typeof(int), "rowBase");
var xStart = Expression.Parameter(typeof(int), "xStart");
var xEnd = Expression.Parameter(typeof(int), "xEnd");
var y = Expression.Parameter(typeof(double), "y");
var uniforms = Expression.Parameter(typeof(double[]), "uniforms");
@@ -85,7 +89,7 @@ namespace LuaScript.Engine.Kernel
var breakLabel = Expression.Label("break");
var loop = Expression.Loop(
Expression.IfThenElse(
Expression.LessThan(x, width),
Expression.LessThan(x, xEnd),
Expression.Block(statements),
Expression.Break(breakLabel)),
breakLabel);
@@ -94,10 +98,10 @@ namespace LuaScript.Engine.Kernel
locals.AddRange(inputs);
locals.AddRange(slots);
var body = Expression.Block(locals, Expression.Assign(x, Constant(0)), loop);
var body = Expression.Block(locals, Expression.Assign(x, xStart), loop);
var lambda = Expression.Lambda<CpuKernel.RowDelegate>(body, buffer, width, rowBase, y, uniforms);
return new CpuKernel(lambda.Compile());
var lambda = Expression.Lambda<CpuKernel.RowDelegate>(body, buffer, rowBase, xStart, xEnd, y, uniforms);
return lambda.Compile();
}
private sealed record Context(
@@ -151,6 +155,8 @@ namespace LuaScript.Engine.Kernel
private static Expression BuildCall(KCall call, Context context)
{
if (call.Func == KFunc.Fmod)
return Expression.Modulo(Build(call.Arguments[0], context), Build(call.Arguments[1], context));
var method = Functions[call.Func];
if (call.Arguments.Count == 1)
return Expression.Call(method, Build(call.Arguments[0], context));
+172 -13
ファイルの表示
@@ -35,6 +35,9 @@ namespace LuaScript.Engine.Kernel
private string _widthVariable = string.Empty;
private string _heightVariable = string.Empty;
private bool _coordsEnabled;
private string? _pixelDataVariable;
private string _baseIndexVariable = string.Empty;
private readonly bool[] _writtenChannels = new bool[4];
public static KernelProgram? TryExtract(string runnableScript)
{
@@ -55,6 +58,11 @@ namespace LuaScript.Engine.Kernel
int index = 0;
while (index < block.Count && block[index] is LocalStmt prelude)
{
if (TryBindPixelData(prelude))
{
index++;
continue;
}
BindLocal(prelude);
index++;
}
@@ -72,11 +80,140 @@ namespace LuaScript.Engine.Kernel
return null;
if (outerAxis == innerAxis)
return null;
if (_pixelDataVariable is not null &&
(string.Equals(outerVar, _pixelDataVariable, StringComparison.Ordinal) ||
string.Equals(innerVar, _pixelDataVariable, StringComparison.Ordinal)))
return null;
if (_scope.ContainsKey(outerVar))
_scope.Remove(outerVar);
if (_scope.ContainsKey(innerVar))
_scope.Remove(innerVar);
_widthVariable = outerAxis == KAxis.X ? outerVar : innerVar;
_heightVariable = outerAxis == KAxis.Y ? outerVar : innerVar;
return BuildKernel(inner.Body);
return _pixelDataVariable is null ? BuildKernel(inner.Body) : BuildPixelDataKernel(inner.Body);
}
private bool TryBindPixelData(LocalStmt local)
{
if (local.Names.Count != 1 || local.Values.Count != 1 ||
local.Values[0] is not CallExpr { Target: MemberExpr { Target: NameExpr { Name: "obj" }, Name: "getpixeldata" }, Arguments.Count: 0 })
return false;
if (_pixelDataVariable is not null)
throw new KernelUnsupportedException("Multiple pixel-data handles are not supported.");
_pixelDataVariable = local.Names[0];
return true;
}
private KernelProgram? BuildPixelDataKernel(IReadOnlyList<LuaStmt> body)
{
if (body.Count < 5)
return null;
if (body[0] is not LocalStmt { Names.Count: 1, Values.Count: 1 } baseStmt || !IsBaseIndex(baseStmt.Values[0]))
return null;
EnsureNotCoordinateName(baseStmt.Names[0]);
_baseIndexVariable = baseStmt.Names[0];
_coordsEnabled = true;
KExpr? outR = null, outG = null, outB = null;
for (int i = 1; i < body.Count; i++)
{
switch (body[i])
{
case LocalStmt local:
BindLocal(local);
break;
case AssignStmt assign:
BindAssign(assign);
break;
case CallStmt { Call: MethodCallExpr set } when IsPixelDataSet(set, out int writeChannel):
var value = ClampChannel(Lower(set.Arguments[1]));
if (writeChannel == 0) outR = value;
else if (writeChannel == 1) outG = value;
else outB = value;
_writtenChannels[writeChannel] = true;
break;
default:
return null;
}
}
if (outR is null || outG is null || outB is null)
return null;
return new KernelProgram(_bindings, outR, outG, outB, new KInput(KChannel.A), [.. _uniforms]);
}
private bool IsBaseIndex(LuaExpr expression)
{
if (expression is not BinaryExpr { Operator: "*", Right: NumberExpr { Value: 4d } } scaled ||
scaled.Left is not BinaryExpr { Operator: "+" } sum)
return false;
if (!IsCoordinate(sum.Right, KAxis.X))
return false;
if (sum.Left is not BinaryExpr { Operator: "*" } stride)
return false;
return IsCoordinate(stride.Left, KAxis.Y) && IsWidth(stride.Right);
}
private bool IsWidth(LuaExpr expression)
{
if (expression is MemberExpr { Target: NameExpr { Name: "obj" }, Name: var field } &&
KernelUniforms.TryResolveMember("obj", field, out var uniform))
return uniform == KernelUniform.Width;
return _pixelDataVariable is not null &&
expression is MemberExpr { Target: NameExpr { } target, Name: "width" } &&
string.Equals(target.Name, _pixelDataVariable, StringComparison.Ordinal);
}
private bool TryPixelDataChannel(LuaExpr expression, out int channel)
{
channel = 0;
if (expression is not MethodCallExpr { Method: "get", Arguments.Count: 1 } call ||
call.Target is not NameExpr { } handle ||
!string.Equals(handle.Name, _pixelDataVariable, StringComparison.Ordinal))
return false;
if (!TryChannelOffset(call.Arguments[0], 1, 4, out channel))
return false;
channel--;
return !_writtenChannels[channel];
}
private bool IsPixelDataSet(MethodCallExpr call, out int channel)
{
channel = 0;
if (call.Method != "set" || call.Arguments.Count != 2 ||
call.Target is not NameExpr { } handle ||
!string.Equals(handle.Name, _pixelDataVariable, StringComparison.Ordinal))
return false;
if (!TryChannelOffset(call.Arguments[0], 1, 3, out channel))
return false;
channel--;
return true;
}
private KExpr ClampChannel(KExpr value)
{
var bound = new KLocalRef(AddBinding(value));
return new KSelect(
new KCompare(KCompareOp.Less, bound, new KConst(0d)),
new KConst(0d),
new KSelect(
new KCompare(KCompareOp.Greater, bound, new KConst(255d)),
new KConst(255d),
bound));
}
private bool TryChannelOffset(LuaExpr expression, int min, int max, out int offset)
{
offset = 0;
if (expression is not BinaryExpr { Operator: "+", Left: NameExpr baseName, Right: NumberExpr number } ||
!string.Equals(baseName.Name, _baseIndexVariable, StringComparison.Ordinal))
return false;
offset = (int)number.Value;
return offset == number.Value && offset >= min && offset <= max;
}
private KernelProgram? BuildKernel(IReadOnlyList<LuaStmt> body)
@@ -112,7 +249,7 @@ namespace LuaScript.Engine.Kernel
}
}
if (body[^1] is not CallStmt { Call: var call } || !IsObjectMethod(call, "setpixel"))
if (body[^1] is not CallStmt { Call: CallExpr call } || !IsObjectMethod(call, "setpixel"))
return null;
if (call.Arguments.Count is < 5 or > 6)
return null;
@@ -167,6 +304,10 @@ namespace LuaScript.Engine.Kernel
if (string.Equals(name, _widthVariable, StringComparison.Ordinal) ||
string.Equals(name, _heightVariable, StringComparison.Ordinal))
throw new KernelUnsupportedException("Local variable shadows a loop coordinate.");
if (_pixelDataVariable is not null && string.Equals(name, _pixelDataVariable, StringComparison.Ordinal))
throw new KernelUnsupportedException("Local variable shadows the pixel-data handle.");
if (_baseIndexVariable.Length > 0 && string.Equals(name, _baseIndexVariable, StringComparison.Ordinal))
throw new KernelUnsupportedException("Local variable shadows the base index.");
}
private int AddBinding(KExpr expression)
@@ -187,6 +328,8 @@ namespace LuaScript.Engine.Kernel
return LowerMember(member);
case CallExpr call:
return LowerCall(call);
case MethodCallExpr method when TryPixelDataChannel(method, out int channel):
return new KInput((KChannel)channel);
case UnaryExpr { Operator: "-" } unary:
return new KNegate(Lower(unary.Operand));
case BinaryExpr binary:
@@ -323,20 +466,36 @@ namespace LuaScript.Engine.Kernel
return false;
if (loop.Stop is not BinaryExpr { Operator: "-", Right: NumberExpr { Value: 1d } } bound)
return false;
if (bound.Left is not MemberExpr { Target: NameExpr { Name: "obj" }, Name: var field })
return false;
if (!KernelUniforms.TryResolveMember("obj", field, out var uniform))
return false;
if (uniform == KernelUniform.Width)
if (bound.Left is MemberExpr { Target: NameExpr { Name: "obj" }, Name: var field } &&
KernelUniforms.TryResolveMember("obj", field, out var uniform))
{
axis = KAxis.X;
return true;
if (uniform == KernelUniform.Width)
{
axis = KAxis.X;
return true;
}
if (uniform == KernelUniform.Height)
{
axis = KAxis.Y;
return true;
}
return false;
}
if (uniform == KernelUniform.Height)
if (_pixelDataVariable is not null &&
bound.Left is MemberExpr { Target: NameExpr { } handle, Name: var pixelField } &&
string.Equals(handle.Name, _pixelDataVariable, StringComparison.Ordinal))
{
axis = KAxis.Y;
return true;
if (pixelField == "width")
{
axis = KAxis.X;
return true;
}
if (pixelField == "height")
{
axis = KAxis.Y;
return true;
}
}
return false;
}
+3 -1
ファイルの表示
@@ -20,6 +20,8 @@ namespace LuaScript.Engine.Kernel
internal sealed record CallExpr(LuaExpr Target, IReadOnlyList<LuaExpr> Arguments) : LuaExpr;
internal sealed record MethodCallExpr(LuaExpr Target, string Method, IReadOnlyList<LuaExpr> Arguments) : LuaExpr;
internal sealed record UnaryExpr(string Operator, LuaExpr Operand) : LuaExpr;
internal sealed record BinaryExpr(string Operator, LuaExpr Left, LuaExpr Right) : LuaExpr;
@@ -30,7 +32,7 @@ namespace LuaScript.Engine.Kernel
internal sealed record AssignStmt(IReadOnlyList<LuaExpr> Targets, IReadOnlyList<LuaExpr> Values) : LuaStmt;
internal sealed record CallStmt(CallExpr Call) : LuaStmt;
internal sealed record CallStmt(LuaExpr Call) : LuaStmt;
internal sealed record IfClause(LuaExpr Condition, IReadOnlyList<LuaStmt> Body);
+8 -2
ファイルの表示
@@ -149,8 +149,8 @@ namespace LuaScript.Engine.Kernel
return new AssignStmt(targets, values);
}
if (first is CallExpr call)
return new CallStmt(call);
if (first is CallExpr or MethodCallExpr)
return new CallStmt(first);
throw new KernelUnsupportedException("Expression is not a valid statement.");
}
@@ -275,6 +275,12 @@ namespace LuaScript.Engine.Kernel
{
expression = new CallExpr(expression, ParseArguments());
}
else if (t.IsSymbol(":"))
{
Advance();
string method = ExpectName();
expression = new MethodCallExpr(expression, method, ParseArguments());
}
else
{
break;
+270
ファイルの表示
@@ -0,0 +1,270 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Expressions;
using System.Reflection;
using System.Runtime.Intrinsics;
namespace LuaScript.Engine.Kernel
{
internal static class SimdKernelCompiler
{
private static readonly Type Vec = typeof(Vector256<double>);
private static readonly MethodInfo Broadcast = typeof(Vector256).GetMethod(nameof(Vector256.Create), [typeof(double)])!;
private static readonly MethodInfo Create4 = typeof(Vector256).GetMethod(nameof(Vector256.Create), [typeof(double), typeof(double), typeof(double), typeof(double)])!;
private static readonly MethodInfo GetElement = VecOp(nameof(Vector256.GetElement), 1, 1);
private static readonly MethodInfo Add = VecOp(nameof(Vector256.Add), 2);
private static readonly MethodInfo Subtract = VecOp(nameof(Vector256.Subtract), 2);
private static readonly MethodInfo Multiply = VecOp(nameof(Vector256.Multiply), 2);
private static readonly MethodInfo Divide = VecOp(nameof(Vector256.Divide), 2);
private static readonly MethodInfo Negate = VecOp(nameof(Vector256.Negate), 1);
private static readonly MethodInfo Abs = VecOp(nameof(Vector256.Abs), 1);
private static readonly MethodInfo Sqrt = VecOp(nameof(Vector256.Sqrt), 1);
private static readonly MethodInfo FloorFn = typeof(Vector256).GetMethod(nameof(Vector256.Floor), [Vec])!;
private static readonly MethodInfo CeilingFn = typeof(Vector256).GetMethod(nameof(Vector256.Ceiling), [Vec])!;
private static readonly MethodInfo ConditionalSelect = VecOp(nameof(Vector256.ConditionalSelect), 3);
private static readonly MethodInfo LessThan = VecOp(nameof(Vector256.LessThan), 2);
private static readonly MethodInfo GreaterThan = VecOp(nameof(Vector256.GreaterThan), 2);
private static readonly MethodInfo LessThanOrEqual = VecOp(nameof(Vector256.LessThanOrEqual), 2);
private static readonly MethodInfo GreaterThanOrEqual = VecOp(nameof(Vector256.GreaterThanOrEqual), 2);
private static readonly MethodInfo EqualsFn = VecOp(nameof(Vector256.Equals), 2);
private static readonly MethodInfo BitwiseAnd = VecOp(nameof(Vector256.BitwiseAnd), 2);
private static readonly MethodInfo BitwiseOr = VecOp(nameof(Vector256.BitwiseOr), 2);
private static readonly MethodInfo OnesComplement = VecOp(nameof(Vector256.OnesComplement), 1);
private static readonly Expression Zero = Expression.Constant(Vector256<double>.Zero, Vec);
private static readonly Expression AllBits = Expression.Constant(Vector256<double>.AllBitsSet, Vec);
private static readonly Expression V255 = Expression.Constant(Vector256.Create(255d), Vec);
public static CpuKernel.RowDelegate? TryCompile(KernelProgram program)
{
try
{
return Compile(program);
}
catch (KernelUnsupportedException)
{
return null;
}
}
private static CpuKernel.RowDelegate Compile(KernelProgram program)
{
var buffer = Expression.Parameter(typeof(byte[]), "buffer");
var rowBase = Expression.Parameter(typeof(int), "rowBase");
var xStart = Expression.Parameter(typeof(int), "xStart");
var xEnd = Expression.Parameter(typeof(int), "xEnd");
var yScalar = Expression.Parameter(typeof(double), "y");
var uniforms = Expression.Parameter(typeof(double[]), "uniforms");
var x = Expression.Variable(typeof(int), "x");
var index = Expression.Variable(typeof(int), "index");
var yVec = Expression.Variable(Vec, "yVec");
var xVec = Expression.Variable(Vec, "xVec");
var alphaRaw = Expression.Variable(Vec, "alphaRaw");
var transparent = Expression.Variable(Vec, "transparent");
var scale = Expression.Variable(Vec, "scale");
var inputs = new[]
{
Expression.Variable(Vec, "inR"),
Expression.Variable(Vec, "inG"),
Expression.Variable(Vec, "inB"),
Expression.Variable(Vec, "inA"),
};
var slots = new ParameterExpression[program.Bindings.Count];
for (int i = 0; i < slots.Length; i++)
slots[i] = Expression.Variable(Vec, "slot" + i);
var context = new Context(xVec, yVec, uniforms, inputs, slots);
var statements = new List<Expression>
{
Expression.Assign(index, Expression.Add(rowBase, Expression.Multiply(x, Constant(4)))),
Expression.Assign(xVec, Expression.Call(Create4,
ToDouble(x),
ToDouble(Expression.Add(x, Constant(1))),
ToDouble(Expression.Add(x, Constant(2))),
ToDouble(Expression.Add(x, Constant(3))))),
Expression.Assign(alphaRaw, LoadChannel(buffer, index, 3)),
Expression.Assign(transparent, Call(LessThanOrEqual, alphaRaw, Zero)),
Expression.Assign(scale, Select(transparent, Zero, Call(Divide, V255, alphaRaw))),
Expression.Assign(inputs[3], Select(transparent, Zero, alphaRaw)),
Expression.Assign(inputs[0], Select(transparent, Zero, ClampByte(Call(Multiply, LoadChannel(buffer, index, 2), scale)))),
Expression.Assign(inputs[1], Select(transparent, Zero, ClampByte(Call(Multiply, LoadChannel(buffer, index, 1), scale)))),
Expression.Assign(inputs[2], Select(transparent, Zero, ClampByte(Call(Multiply, LoadChannel(buffer, index, 0), scale)))),
};
for (int i = 0; i < slots.Length; i++)
statements.Add(Expression.Assign(slots[i], Build(program.Bindings[i], context)));
var outA = Expression.Variable(Vec, "outA");
var alphaScale = Expression.Variable(Vec, "alphaScale");
statements.Add(Expression.Assign(outA, Build(program.OutputA, context)));
statements.Add(Expression.Assign(alphaScale, Call(Divide, ClampByte(outA), V255)));
statements.Add(StoreChannel(buffer, index, 0, ClampByte(Call(Multiply, Build(program.OutputB, context), alphaScale))));
statements.Add(StoreChannel(buffer, index, 1, ClampByte(Call(Multiply, Build(program.OutputG, context), alphaScale))));
statements.Add(StoreChannel(buffer, index, 2, ClampByte(Call(Multiply, Build(program.OutputR, context), alphaScale))));
statements.Add(StoreChannel(buffer, index, 3, ClampByte(outA)));
statements.Add(Expression.AddAssign(x, Constant(4)));
var breakLabel = Expression.Label("break");
var loop = Expression.Loop(
Expression.IfThenElse(
Expression.LessThan(x, xEnd),
Expression.Block(statements),
Expression.Break(breakLabel)),
breakLabel);
var locals = new List<ParameterExpression> { x, index, yVec, xVec, alphaRaw, transparent, scale, outA, alphaScale };
locals.AddRange(inputs);
locals.AddRange(slots);
var body = Expression.Block(
locals,
Expression.Assign(yVec, Expression.Call(Broadcast, yScalar)),
Expression.Assign(x, xStart),
loop);
var lambda = Expression.Lambda<CpuKernel.RowDelegate>(body, buffer, rowBase, xStart, xEnd, yScalar, uniforms);
return lambda.Compile();
}
private sealed record Context(
Expression X,
Expression Y,
ParameterExpression Uniforms,
Expression[] Inputs,
ParameterExpression[] Slots);
private static Expression Build(KExpr expression, Context context)
{
switch (expression)
{
case KConst value:
return Expression.Constant(Vector256.Create(value.Value), Vec);
case KInput input:
return context.Inputs[(int)input.Channel];
case KCoord coord:
return coord.Axis == KAxis.X ? context.X : context.Y;
case KUniformRef uniform:
return Expression.Call(Broadcast, Expression.ArrayIndex(context.Uniforms, Constant((int)uniform.Uniform)));
case KLocalRef local:
return context.Slots[local.Slot];
case KNegate negate:
return Call(Negate, Build(negate.Operand, context));
case KArith arithmetic:
return BuildArithmetic(arithmetic, context);
case KCall call:
return BuildCall(call, context);
case KSelect select:
return Select(BuildBool(select.Condition, context), Build(select.WhenTrue, context), Build(select.WhenFalse, context));
}
throw new KernelUnsupportedException("Unsupported SIMD expression.");
}
private static Expression BuildArithmetic(KArith arithmetic, Context context)
{
var left = Build(arithmetic.Left, context);
var right = Build(arithmetic.Right, context);
return arithmetic.Op switch
{
KArithOp.Add => Call(Add, left, right),
KArithOp.Subtract => Call(Subtract, left, right),
KArithOp.Multiply => Call(Multiply, left, right),
KArithOp.Divide => Call(Divide, left, right),
KArithOp.Modulo => Call(Subtract, left, Call(Multiply, Call(FloorFn, Call(Divide, left, right)), right)),
_ => throw new KernelUnsupportedException("Unsupported SIMD arithmetic operator."),
};
}
private static Expression BuildCall(KCall call, Context context)
{
var argument = Build(call.Arguments[0], context);
return call.Func switch
{
KFunc.Abs => Call(Abs, argument),
KFunc.Floor => Call(FloorFn, argument),
KFunc.Ceil => Call(CeilingFn, argument),
KFunc.Sqrt => Call(Sqrt, argument),
_ => throw new KernelUnsupportedException("Unsupported SIMD function."),
};
}
private static Expression BuildBool(KBool condition, Context context)
{
switch (condition)
{
case KBoolConst value:
return value.Value ? AllBits : Zero;
case KNot not:
return Call(OnesComplement, BuildBool(not.Operand, context));
case KLogical logical:
return logical.IsAnd
? Call(BitwiseAnd, BuildBool(logical.Left, context), BuildBool(logical.Right, context))
: Call(BitwiseOr, BuildBool(logical.Left, context), BuildBool(logical.Right, context));
case KCompare compare:
var left = Build(compare.Left, context);
var right = Build(compare.Right, context);
return compare.Op switch
{
KCompareOp.Less => Call(LessThan, left, right),
KCompareOp.Greater => Call(GreaterThan, left, right),
KCompareOp.LessEqual => Call(LessThanOrEqual, left, right),
KCompareOp.GreaterEqual => Call(GreaterThanOrEqual, left, right),
KCompareOp.Equal => Call(EqualsFn, left, right),
KCompareOp.NotEqual => Call(OnesComplement, Call(EqualsFn, left, right)),
_ => throw new KernelUnsupportedException("Unsupported SIMD comparison."),
};
}
throw new KernelUnsupportedException("Unsupported SIMD condition.");
}
private static Expression ClampByte(Expression value)
{
var low = Select(Call(LessThan, value, Zero), Zero, value);
return Select(Call(GreaterThan, low, V255), V255, low);
}
private static Expression Select(Expression condition, Expression whenTrue, Expression whenFalse) =>
Expression.Call(ConditionalSelect, condition, whenTrue, whenFalse);
private static Expression LoadChannel(ParameterExpression buffer, ParameterExpression index, int offset) =>
Expression.Call(Create4,
ToDouble(ReadByte(buffer, index, offset)),
ToDouble(ReadByte(buffer, index, offset + 4)),
ToDouble(ReadByte(buffer, index, offset + 8)),
ToDouble(ReadByte(buffer, index, offset + 12)));
private static Expression StoreChannel(ParameterExpression buffer, ParameterExpression index, int offset, Expression value)
{
var writes = new Expression[4];
for (int lane = 0; lane < 4; lane++)
writes[lane] = Expression.Assign(
Expression.ArrayAccess(buffer, Expression.Add(index, Constant(lane * 4 + offset))),
Expression.Convert(Expression.Call(GetElement, value, Constant(lane)), typeof(byte)));
return Expression.Block(writes);
}
private static Expression ReadByte(ParameterExpression buffer, ParameterExpression index, int offset) =>
Expression.ArrayIndex(buffer, offset == 0 ? index : Expression.Add(index, Constant(offset)));
private static Expression Call(MethodInfo method, params Expression[] arguments) =>
Expression.Call(method, arguments);
private static Expression ToDouble(Expression value) => Expression.Convert(value, typeof(double));
private static ConstantExpression Constant(int value) => Expression.Constant(value, typeof(int));
private static MethodInfo VecOp(string name, int vectorArgs, int intArgs = 0) =>
typeof(Vector256).GetMethods()
.Single(m => m.Name == name && m.IsGenericMethodDefinition &&
m.GetParameters().Length == vectorArgs + intArgs &&
m.GetParameters().Take(vectorArgs).All(p => IsVector(p.ParameterType)) &&
m.GetParameters().Skip(vectorArgs).All(p => p.ParameterType == typeof(int)))
.MakeGenericMethod(typeof(double));
private static bool IsVector(Type type) =>
type.IsGenericType && type.GetGenericTypeDefinition() == typeof(Vector256<>);
}
}
+169 -69
ファイルの表示
@@ -29,9 +29,13 @@ namespace LuaScript.Engine
private readonly double[] _anchorBuffer = new double[Anchor.AnchorSupport.MaxAnchors * 3];
private int _lastCallbackTagLength = -1;
private string _lastCallbackTagText = string.Empty;
private byte[]? _resultBuffer;
private int _scriptVersion;
private string? _lastScript;
private byte[] _lastScriptBytes = Array.Empty<byte>();
private bool _scriptWritten;
private readonly Dictionary<string, byte[]> _stringNameBytes = new(StringComparer.Ordinal);
private byte[] _stringValueBytes = new byte[256];
private byte[] _sceneValueBytes = new byte[256];
public LuaJitWorker(string nativeDir)
{
@@ -48,7 +52,7 @@ namespace LuaScript.Engine
string script,
double[] fields,
IReadOnlyDictionary<string, string> stringParameters,
Func<byte[]> loadPixels,
PixelRegionAccess loadPixels,
int width,
int height,
int timeoutMs,
@@ -60,25 +64,32 @@ namespace LuaScript.Engine
Action<string, IReadOnlyList<KeyValuePair<string, object>>> addEffect,
Action<DrawCommand> addDraw,
Action<string, int, bool, int, double[]> setAnchor,
Func<string, SceneValue> sceneGetValue,
Action<string, SceneValue> sceneSetValue,
out bool pixelsDirty,
out bool bufferReplaced,
out byte[]? resultPixels,
out int resultWidth,
out int resultHeight,
out string? error)
{
pixelsDirty = false;
bufferReplaced = false;
resultPixels = null;
resultWidth = width;
resultHeight = height;
error = null;
byte[] scriptBytes = Encoding.UTF8.GetBytes(script);
if (scriptBytes.Length > NativeProtocol.ScriptMax)
bool scriptChanged = !ReferenceEquals(script, _lastScript);
if (scriptChanged)
{
error = "script too large for native lane";
return false;
byte[] scriptBytes = Encoding.UTF8.GetBytes(script);
if (scriptBytes.Length > NativeProtocol.ScriptMax)
{
error = "script too large for native lane";
return false;
}
_lastScript = script;
_lastScriptBytes = scriptBytes;
_scriptVersion++;
}
int stringCapacity = ResolveStringCapacity(_stringParamsCapacity, MeasureStringParameters(stringParameters));
@@ -89,8 +100,13 @@ namespace LuaScript.Engine
WriteStringParameters(view, stringParameters);
view.Write(NativeProtocol.OffWidth, width);
view.Write(NativeProtocol.OffHeight, height);
view.Write(NativeProtocol.OffScriptLen, scriptBytes.Length);
view.WriteArray(NativeProtocol.ScriptOffset, scriptBytes, 0, scriptBytes.Length);
if (scriptChanged || !_scriptWritten)
{
view.Write(NativeProtocol.OffScriptLen, _lastScriptBytes.Length);
view.WriteArray(NativeProtocol.ScriptOffset, _lastScriptBytes, 0, _lastScriptBytes.Length);
_scriptWritten = true;
}
view.Write(NativeProtocol.OffScriptVersion, _scriptVersion);
view.Write(NativeProtocol.OffPixelsDirty, 0);
view.Write(NativeProtocol.OffErrorLen, 0);
view.Write(NativeProtocol.OffStatus, NativeProtocol.StatusIdle);
@@ -98,7 +114,6 @@ namespace LuaScript.Engine
_workEvent!.Set();
byte[]? uploadedPixels = null;
var stopwatch = Stopwatch.StartNew();
int status;
while (true)
@@ -115,14 +130,26 @@ namespace LuaScript.Engine
if (status != NativeProtocol.StatusCallback)
break;
if (view.ReadInt32(NativeProtocol.OffCallbackKind) == NativeProtocol.CbKindRequestPixels)
int callbackKind = view.ReadInt32(NativeProtocol.OffCallbackKind);
if (callbackKind == NativeProtocol.CbKindRequestPixels)
{
uploadedPixels ??= loadPixels();
WritePixelRegion(uploadedPixels, uploadedPixels.Length);
try
{
AccessPixelRegion(loadPixels);
}
catch
{
KillWorker();
throw;
}
}
else if (callbackKind == NativeProtocol.CbKindFlushDraws)
{
DrainDrawRing(view, addDraw);
}
else
{
DispatchCallback(view, resolveObject, loadFigure, loadText, loadImage, loadMovie, addEffect, addDraw, setAnchor);
DispatchCallback(view, resolveObject, loadFigure, loadText, loadImage, loadMovie, addEffect, setAnchor, sceneGetValue, sceneSetValue);
}
_workEvent.Set();
}
@@ -136,6 +163,8 @@ namespace LuaScript.Engine
return false;
}
DrainDrawRing(view, addDraw);
for (int i = NativeProtocol.FirstWritableField; i <= NativeProtocol.LastWritableField; i++)
fields[i] = view.ReadDouble(NativeProtocol.FieldsOffset + i * 8);
@@ -146,26 +175,33 @@ namespace LuaScript.Engine
bufferReplaced = resultWidth != width || resultHeight != height;
pixelsDirty = view.ReadInt32(NativeProtocol.OffPixelsDirty) != 0;
if (pixelsDirty)
if (pixelsDirty && (long)resultWidth * resultHeight * 4 > _allocatedSize - _pixelOffset)
{
int pixelSize = resultWidth * resultHeight * 4;
if (!bufferReplaced && uploadedPixels is not null)
{
ReadPixelRegion(uploadedPixels, pixelSize);
resultPixels = uploadedPixels;
}
else
{
if (_resultBuffer == null || _resultBuffer.Length < pixelSize)
_resultBuffer = new byte[pixelSize];
ReadPixelRegion(_resultBuffer, pixelSize);
resultPixels = _resultBuffer;
}
error = "native worker reported a pixel buffer beyond capacity";
return false;
}
return true;
}
public void ReadPixels(PixelRegionAccess reader) => AccessPixelRegion(reader);
private unsafe void AccessPixelRegion(PixelRegionAccess access)
{
var handle = _view!.SafeMemoryMappedViewHandle;
byte* ptr = null;
handle.AcquirePointer(ref ptr);
try
{
long offset = _view.PointerOffset + _pixelOffset;
access((nint)(ptr + offset), (long)handle.ByteLength - offset);
}
finally
{
handle.ReleasePointer();
}
}
private unsafe void WritePixelRegion(byte[] source, int length)
{
var handle = _view!.SafeMemoryMappedViewHandle;
@@ -182,22 +218,6 @@ namespace LuaScript.Engine
}
}
private unsafe void ReadPixelRegion(byte[] destination, int length)
{
var handle = _view!.SafeMemoryMappedViewHandle;
byte* ptr = null;
handle.AcquirePointer(ref ptr);
try
{
fixed (byte* dst = destination)
Buffer.MemoryCopy(ptr + _view.PointerOffset + _pixelOffset, dst, destination.Length, length);
}
finally
{
handle.ReleasePointer();
}
}
private static int MeasureStringParameters(IReadOnlyDictionary<string, string> stringParameters)
{
int total = 4;
@@ -259,8 +279,9 @@ namespace LuaScript.Engine
Func<string, (byte[] buffer, int w, int h)> loadImage,
Func<string, double, (byte[] buffer, int w, int h)> loadMovie,
Action<string, IReadOnlyList<KeyValuePair<string, object>>> addEffect,
Action<DrawCommand> addDraw,
Action<string, int, bool, int, double[]> setAnchor)
Action<string, int, bool, int, double[]> setAnchor,
Func<string, SceneValue> sceneGetValue,
Action<string, SceneValue> sceneSetValue)
{
int kind = view.ReadInt32(NativeProtocol.OffCallbackKind);
switch (kind)
@@ -283,18 +304,82 @@ namespace LuaScript.Engine
case NativeProtocol.CbKindEffect:
ResolveEffectCallback(view, addEffect);
break;
case NativeProtocol.CbKindDraw:
ResolveDrawCallback(view, addDraw);
break;
case NativeProtocol.CbKindDrawPoly:
ResolveDrawPolyCallback(view, addDraw);
break;
case NativeProtocol.CbKindSetAnchor:
ResolveSetAnchorCallback(view, setAnchor);
break;
case NativeProtocol.CbKindSceneGet:
ResolveSceneGetCallback(view, sceneGetValue);
break;
case NativeProtocol.CbKindSceneSet:
ResolveSceneSetCallback(view, sceneSetValue);
break;
}
}
private void ResolveSceneGetCallback(MemoryMappedViewAccessor view, Func<string, SceneValue> getValue)
{
int tagLen = Math.Clamp(view.ReadInt32(NativeProtocol.OffCallbackTagLen), 0, NativeProtocol.CallbackTagMax);
view.ReadArray(NativeProtocol.CallbackTagOffset, _callbackTag, 0, tagLen);
string name = ResolveTag(tagLen);
SceneValue value;
try { value = getValue(name); }
catch { value = SceneValue.Nil; }
long rOff = NativeProtocol.CallbackResultOffset;
view.Write(rOff + 0 * 8, (double)value.Kind);
view.Write(rOff + 1 * 8, value.Number);
if (value.Kind == SceneValueKind.String)
{
string text = value.Text ?? string.Empty;
int maxBytes = Encoding.UTF8.GetMaxByteCount(text.Length);
if (_sceneValueBytes.Length < maxBytes)
_sceneValueBytes = new byte[Math.Max(maxBytes, _sceneValueBytes.Length * 2)];
int length = Encoding.UTF8.GetBytes(text, 0, text.Length, _sceneValueBytes, 0);
if (length > NativeProtocol.CallbackTagMax)
length = NativeProtocol.CallbackTagMax;
view.WriteArray(NativeProtocol.CallbackTagOffset, _sceneValueBytes, 0, length);
view.Write(NativeProtocol.OffCallbackTagLen, length);
}
view.Write(NativeProtocol.OffCallbackFound, 1);
}
private void ResolveSceneSetCallback(MemoryMappedViewAccessor view, Action<string, SceneValue> setValue)
{
int tagLen = Math.Clamp(view.ReadInt32(NativeProtocol.OffCallbackTagLen), 0, NativeProtocol.CallbackTagMax);
view.ReadArray(NativeProtocol.CallbackTagOffset, _callbackTag, 0, tagLen);
long rOff = NativeProtocol.CallbackResultOffset;
var kind = (SceneValueKind)(int)view.ReadDouble(rOff + 0 * 8);
double number = view.ReadDouble(rOff + 1 * 8);
string name;
SceneValue value;
if (kind == SceneValueKind.String)
{
int separator = Array.IndexOf(_callbackTag, (byte)0, 0, tagLen);
int nameLength = separator >= 0 ? separator : tagLen;
name = Encoding.UTF8.GetString(_callbackTag, 0, nameLength);
value = SceneValue.FromString(separator >= 0
? Encoding.UTF8.GetString(_callbackTag, separator + 1, tagLen - separator - 1)
: string.Empty);
}
else
{
name = ResolveTag(tagLen);
value = kind switch
{
SceneValueKind.Number => SceneValue.FromNumber(number),
SceneValueKind.Boolean => SceneValue.FromBoolean(number != 0d),
_ => SceneValue.Nil,
};
}
try { setValue(name, value); }
catch { }
view.Write(NativeProtocol.OffCallbackFound, 1);
}
private void ResolveSetAnchorCallback(MemoryMappedViewAccessor view, Action<string, int, bool, int, double[]> setAnchor)
{
int tagLen = Math.Clamp(view.ReadInt32(NativeProtocol.OffCallbackTagLen), 0, NativeProtocol.CallbackTagMax);
@@ -316,34 +401,48 @@ namespace LuaScript.Engine
view.Write(NativeProtocol.OffCallbackFound, 1);
}
private static void ResolveDrawCallback(MemoryMappedViewAccessor view, Action<DrawCommand> addDraw)
private void DrainDrawRing(MemoryMappedViewAccessor view, Action<DrawCommand> addDraw)
{
long rOff = NativeProtocol.CallbackResultOffset;
double ox = view.ReadDouble(rOff + 0 * 8);
double oy = view.ReadDouble(rOff + 1 * 8);
double oz = view.ReadDouble(rOff + 2 * 8);
double zoom = view.ReadDouble(rOff + 3 * 8);
double alpha = view.ReadDouble(rOff + 4 * 8);
double aspect = view.ReadDouble(rOff + 5 * 8);
double antialias = view.ReadDouble(rOff + 6 * 8);
double blend = view.ReadDouble(rOff + 7 * 8);
long ringBase = NativeProtocol.DrawRingOffset(_stringParamsCapacity);
int count = Math.Clamp((int)view.ReadDouble(ringBase), 0, NativeProtocol.DrawRingCapacity);
for (int k = 0; k < count; k++)
{
long entry = ringBase + (1 + (long)k * NativeProtocol.DrawEntryDoubles) * 8;
int kind = (int)view.ReadDouble(entry);
long payload = entry + 8;
if (kind == NativeProtocol.CbKindDrawPoly)
DispatchRingDrawPoly(view, payload, addDraw);
else
DispatchRingDraw(view, payload, addDraw);
}
view.Write(ringBase, 0d);
}
private static void DispatchRingDraw(MemoryMappedViewAccessor view, long payload, Action<DrawCommand> addDraw)
{
double ox = view.ReadDouble(payload + 0 * 8);
double oy = view.ReadDouble(payload + 1 * 8);
double oz = view.ReadDouble(payload + 2 * 8);
double zoom = view.ReadDouble(payload + 3 * 8);
double alpha = view.ReadDouble(payload + 4 * 8);
double aspect = view.ReadDouble(payload + 5 * 8);
double antialias = view.ReadDouble(payload + 6 * 8);
double blend = view.ReadDouble(payload + 7 * 8);
try { addDraw(new DrawCommand(ox, oy, oz, zoom, alpha, aspect, null, antialias, blend)); }
catch { }
view.Write(NativeProtocol.OffCallbackFound, 1);
}
private static void ResolveDrawPolyCallback(MemoryMappedViewAccessor view, Action<DrawCommand> addDraw)
private static void DispatchRingDrawPoly(MemoryMappedViewAccessor view, long payload, Action<DrawCommand> addDraw)
{
var poly = new double[DrawPolyMath.Length];
for (int i = 0; i < DrawPolyMath.Length; i++)
poly[i] = view.ReadDouble(NativeProtocol.CallbackTagOffset + i * 8);
double antialias = view.ReadDouble(NativeProtocol.CallbackTagOffset + DrawPolyMath.Length * 8);
double blend = view.ReadDouble(NativeProtocol.CallbackTagOffset + (DrawPolyMath.Length + 1) * 8);
poly[i] = view.ReadDouble(payload + i * 8);
double antialias = view.ReadDouble(payload + DrawPolyMath.Length * 8);
double blend = view.ReadDouble(payload + (DrawPolyMath.Length + 1) * 8);
try { addDraw(new DrawCommand(0d, 0d, 0d, 1d, poly[20], 0d, poly, antialias, blend)); }
catch { }
view.Write(NativeProtocol.OffCallbackFound, 1);
}
private void ResolveGetObjectCallback(MemoryMappedViewAccessor view, Func<string, int, SceneObjectInfo?> resolveObject)
@@ -553,6 +652,7 @@ namespace LuaScript.Engine
private void StartWorker(int width, int height, int stringCapacity)
{
_stringParamsCapacity = stringCapacity;
_scriptWritten = false;
_pixelOffset = NativeProtocol.PixelOffset(stringCapacity);
long size = Math.Max(NativeProtocol.BufferSize(width, height, stringCapacity), _allocatedSize);
_allocatedSize = size;
+13 -2
ファイルの表示
@@ -27,6 +27,7 @@ namespace LuaScript.Engine
public const int OffLoadResultWidth = 48;
public const int OffLoadResultHeight = 52;
public const int OffStringParamsLen = 56;
public const int OffScriptVersion = 60;
public const int HeaderSize = 64;
@@ -40,7 +41,7 @@ namespace LuaScript.Engine
public const int ErrorMax = 4 * 1024;
public const int CallbackTagOffset = ErrorOffset + ErrorMax;
public const int CallbackTagMax = 4096;
public const int CallbackTagMax = 8192;
public const int CallbackResultOffset = CallbackTagOffset + CallbackTagMax;
public const int CallbackResultCount = 8;
@@ -57,6 +58,14 @@ namespace LuaScript.Engine
public const int CbKindLoadMovie = 7;
public const int CbKindSetAnchor = 8;
public const int CbKindRequestPixels = 9;
public const int CbKindFlushDraws = 10;
public const int CbKindSceneGet = 11;
public const int CbKindSceneSet = 12;
public const int DrawRingCapacity = 4096;
public const int DrawEntryDoubles = 24;
public const int DrawRingDoubles = 1 + DrawRingCapacity * DrawEntryDoubles;
public const long DrawRingBytes = (long)DrawRingDoubles * 8;
public const int CbExist = 0;
public const int CbX = 1;
@@ -67,7 +76,9 @@ namespace LuaScript.Engine
public const int CbAlpha = 6;
public const int CbLayer = 7;
public static int PixelOffset(int stringCapacity) => StringParamsOffset + stringCapacity;
public static long DrawRingOffset(int stringCapacity) => StringParamsOffset + stringCapacity;
public static long PixelOffset(int stringCapacity) => DrawRingOffset(stringCapacity) + DrawRingBytes;
public const int W = 0;
public const int H = 1;
+4
ファイルの表示
@@ -0,0 +1,4 @@
namespace LuaScript.Engine
{
internal delegate void PixelRegionAccess(nint address, long capacity);
}
+8 -3
ファイルの表示
@@ -21,6 +21,7 @@ namespace LuaScript
"obj", "scene", "anim", "ymm4",
"math", "string", "table", "bit32",
"type", "tostring", "tonumber", "select", "error", "assert", "print",
"debug_print", "RGB", "HSV", "OR", "AND", "XOR", "SHIFT",
"ipairs", "pairs", "next",
"unpack",
"setmetatable", "getmetatable", "rawget", "rawset", "rawequal", "rawlen",
@@ -46,8 +47,11 @@ namespace LuaScript
"obj.file_mp4", "obj.file_exo", "obj.file_subtitle", "obj.file_shader",
"obj.time", "obj.totaltime", "obj.t", "obj.frame", "obj.totalframe",
"obj.framerate", "obj.layer", "obj.index", "obj.num",
"obj.getpixel", "obj.setpixel",
"obj.getpixeldata", "obj.rand", "obj.load"
"obj.getobject", "obj.getpixel", "obj.setpixel",
"obj.getpixeldata", "obj.putpixeldata", "obj.rand", "obj.load",
"obj.setfont", "obj.draw", "obj.drawpoly", "obj.copybuffer",
"obj.getvalue", "obj.setoption", "obj.getoption", "obj.pixeloption",
"obj.setanchor", "obj.effect"
]),
("math", [
"math.abs", "math.ceil", "math.cos", "math.exp", "math.floor",
@@ -76,7 +80,8 @@ namespace LuaScript
"bit32.btest", "bit32.countlz", "bit32.countrz"
]),
("scene", [
"scene.width", "scene.height", "scene.cx", "scene.cy"
"scene.width", "scene.height", "scene.cx", "scene.cy",
"scene.set", "scene.get"
]),
("anim", [
"anim.tau", "anim.e", "anim.phi", "anim.sqrt2",
+1 -1
ファイルの表示
@@ -4,7 +4,7 @@
<TargetFramework>net10.0-windows10.0.19041.0</TargetFramework>
<UseWPF>true</UseWPF>
<ImplicitUsings>enable</ImplicitUsings>
<Version>1.11.4</Version>
<Version>1.13.3</Version>
<Platforms>AnyCPU;x64</Platforms>
<Nullable>enable</Nullable>
<AllowUnsafeBlocks>true</AllowUnsafeBlocks>
+102 -18
ファイルの表示
@@ -42,7 +42,7 @@ namespace LuaScript
bool Check3,
bool HasColor,
int Color,
string Script,
int ScriptVersion,
int StringsVersion,
TimelineSourceUsage Usage,
Guid SceneId,
@@ -76,6 +76,9 @@ namespace LuaScript
private bool _effectChainWarned;
private bool _gpuWarned;
private string? _scriptKeyRef;
private int _scriptKeyVersion;
private string _kernelSource = string.Empty;
private bool _kernelResolved;
private KernelProgram? _kernelProgram;
@@ -92,6 +95,8 @@ namespace LuaScript
private string _lastSceneId = string.Empty;
private bool _sceneIdCached;
private IGraphicsDevicesAndContext? _hostDevices;
private GraphicsDevicesAndContext? _ownCtx;
private PixelBufferManager? _pixelManager;
@@ -107,8 +112,14 @@ namespace LuaScript
private bool _hasExplicitDirective;
private ScriptEngineKind _explicitDirectiveKind;
private byte[]? _nativeInputPixels;
private Func<byte[]>? _nativeLoadInput;
private PixelRegionAccess? _nativeUpload;
private PixelRegionAccess? _nativeReadIntoResult;
private PixelRegionAccess? _nativeWriteOutput;
private byte[]? _nativeResultBuffer;
private int _nativeReadLength;
private int _nativeOutputWidth;
private int _nativeOutputHeight;
private bool _nativeUploaded;
private Func<string, int, SceneObjectInfo?>? _nativeResolveObject;
private Func<string, int, double, double, double, (byte[] buffer, int w, int h)>? _nativeLoadFigure;
private Func<string, string, double, bool, bool, int, (byte[] buffer, int w, int h)>? _nativeLoadText;
@@ -117,6 +128,8 @@ namespace LuaScript
private Action<string, IReadOnlyList<KeyValuePair<string, object>>>? _nativeAddEffect;
private Action<DrawCommand>? _nativeAddDraw;
private Action<string, int, bool, int, double[]>? _nativeSetAnchor;
private Func<string, SceneValue>? _nativeSceneGet;
private Action<string, SceneValue>? _nativeSceneSet;
private bool _isFirst = true;
private string _sourceScript = string.Empty;
@@ -126,6 +139,7 @@ namespace LuaScript
private ID2D1Image? _cachedInput;
private RenderKey _cachedKey;
private SceneObjectQuery[] _cachedQueries = [];
private SceneValueQuery[] _cachedSceneValueQueries = [];
private DrawDescription? _cachedOutputDesc;
private ID2D1Image? _cachedEffectOutput;
@@ -138,6 +152,7 @@ namespace LuaScript
protected override ID2D1Image? CreateEffect(IGraphicsDevicesAndContext devices)
{
_hostDevices = devices;
_ownCtx = new GraphicsDevicesAndContext(devices);
disposer.Collect(_ownCtx);
_pixelManager = new PixelBufferManager(_ownCtx);
@@ -242,6 +257,11 @@ namespace LuaScript
var fps = desc.FPS;
var time = desc.ItemPosition.Time.TotalSeconds;
var script = item.Script ?? string.Empty;
if (!ReferenceEquals(script, _scriptKeyRef))
{
_scriptKeyRef = script;
_scriptKeyVersion++;
}
var layout = item.Layout;
var t0 = ClampTrack(item.Track0.GetValue(frame, length, fps), layout, 0);
@@ -261,7 +281,7 @@ namespace LuaScript
t0, t1, t2, t3,
s0, s1, s2, s3,
c0, c1, c2, c3, hasColor, colorRgb,
script, RefreshStringParameters(),
_scriptKeyVersion, RefreshStringParameters(),
desc.Usage, desc.SceneId,
desc.TimelinePosition.Frame,
desc.TimelinePosition.Time.TotalSeconds,
@@ -278,7 +298,11 @@ namespace LuaScript
_frameResolverBuilt = false;
if (!_isFirst && key == _cachedKey &&
(_cachedQueries.Length == 0 || QueriesMatch(_cachedQueries, GetFrameResolver())))
(_cachedQueries.Length == 0 || QueriesMatch(_cachedQueries, GetFrameResolver())) &&
(_cachedSceneValueQueries.Length == 0 || SceneValuesMatch(
_cachedSceneValueQueries,
SceneSharedValues.ForScene(_hostDevices!, ResolveSceneId(key.SceneId)),
key.TimelineFrame)))
{
effectOutput = _cachedEffectOutput;
return _cachedOutputDesc ?? inDesc;
@@ -339,6 +363,8 @@ namespace LuaScript
}
}
ctx.PublishSceneValues();
if (ctx.DrawCommands.Count > 0)
{
ctx.EnsurePixelBuffer();
@@ -376,6 +402,7 @@ namespace LuaScript
effectOutput = null;
_context = CreateScriptContext();
_isFirst = true;
DebugOutput.Write(ex.Message);
Log.Default.Write(ex.Message, ex);
LuaScriptDiagnostics.Instance.Report(script, [CreateDiagnostic(LuaScriptDiagnosticKind.Timeout, ex.Message)]);
return inDesc;
@@ -384,6 +411,7 @@ namespace LuaScript
{
effectOutput = null;
outDesc = inDesc;
DebugOutput.Write(ex.Message);
Log.Default.Write(ex.Message, ex);
diagnostics = [CreateDiagnostic(ClassifyDiagnostic(ex), ex.Message)];
}
@@ -398,6 +426,7 @@ namespace LuaScript
_isFirst = false;
_cachedKey = key;
_cachedQueries = ctx.ObjectQueries.Count == 0 ? [] : [.. ctx.ObjectQueries];
_cachedSceneValueQueries = ctx.SceneValueQueries.Count == 0 ? [] : [.. ctx.SceneValueQueries];
_cachedOutputDesc = outDesc;
_cachedEffectOutput = effectOutput;
@@ -446,6 +475,16 @@ namespace LuaScript
return new SceneObjectResolver([.. entries], desc.FPS);
}
private static bool SceneValuesMatch(SceneValueQuery[] queries, SceneSharedValues values, long generation)
{
for (int i = 0; i < queries.Length; i++)
{
if (values.Read(generation, queries[i].Name) != queries[i].Result)
return false;
}
return true;
}
private static bool QueriesMatch(SceneObjectQuery[] queries, SceneObjectResolver resolver)
{
for (int i = 0; i < queries.Length; i++)
@@ -572,6 +611,8 @@ namespace LuaScript
ctx.SceneId = ResolveSceneId(key.SceneId);
ctx.TimeRatio = key.Length > 0 ? key.Frame / (double)key.Length : 0d;
PopulateStringParameters(ctx);
ctx.SceneScope = _hostDevices;
ctx.BeginSceneValues();
}
private static double ClampTrack(double value, AviUtlParameterLayout layout, int index)
@@ -840,7 +881,7 @@ namespace LuaScript
{
_nativeWorker ??= new LuaJitWorker(NativeDirectory);
_nativeFields ??= new double[NativeProtocol.FieldCount];
_nativeLoadInput ??= () => _nativeInputPixels ??= LoadPendingInputPixels();
_nativeUpload ??= UploadNativeInputPixels;
_nativeResolveObject ??= (tag, frame) => _context.ResolveObject(tag, frame, out var info) ? info : null;
_nativeLoadFigure ??= NativeLoadFigure;
_nativeLoadText ??= NativeLoadText;
@@ -849,12 +890,14 @@ namespace LuaScript
_nativeAddEffect ??= (name, args) => _context.AddEffect(new AviUtlEffectRequest(name, args));
_nativeAddDraw ??= command => _context.AddDraw(command);
_nativeSetAnchor ??= ResolveNativeAnchor;
_nativeSceneGet ??= name => _context.GetSceneValue(name);
_nativeSceneSet ??= (name, value) => _context.SetSceneValue(name, value);
NativeFieldMap.ToFields(ctx, _nativeFields);
_nativeInputPixels = null;
_nativeUploaded = false;
bool ok = _nativeWorker.Execute(
script, _nativeFields, ctx.StringParameters, _nativeLoadInput, imgW, imgH, NativeTimeoutMilliseconds,
script, _nativeFields, ctx.StringParameters, _nativeUpload, imgW, imgH, NativeTimeoutMilliseconds,
_nativeResolveObject,
_nativeLoadFigure,
_nativeLoadText,
@@ -863,7 +906,9 @@ namespace LuaScript
_nativeAddEffect,
_nativeAddDraw,
_nativeSetAnchor,
out bool dirty, out bool bufferReplaced, out byte[]? resultPixels,
_nativeSceneGet,
_nativeSceneSet,
out bool dirty, out bool bufferReplaced,
out int resultW, out int resultH, out string? error);
if (!ok)
@@ -877,31 +922,35 @@ namespace LuaScript
bool hasDraws = ctx.DrawCommands.Count > 0;
if (dirty && resultPixels is not null)
if (dirty)
{
int outW = bufferReplaced ? resultW : imgW;
int outH = bufferReplaced ? resultH : imgH;
if (bufferReplaced)
ctx.ReplaceBuffer(resultPixels, outW, outH);
if (hasDraws)
{
ctx.SetResolvedBuffer(resultPixels, outW, outH);
var result = ReadNativeResultPixels(outW, outH);
if (bufferReplaced)
ctx.ReplaceBuffer(result, outW, outH);
else
ctx.SetResolvedBuffer(result, outW, outH);
return true;
}
_pixelManager!.WritePixelsToOutput(resultPixels, outW, outH);
_nativeOutputWidth = outW;
_nativeOutputHeight = outH;
_nativeWorker.ReadPixels(_nativeWriteOutput ??= WriteNativeOutputPixels);
if (bufferReplaced)
effectOutput = _pixelManager.GetTransformOutput(-outW / 2f, -outH / 2f);
effectOutput = _pixelManager!.GetTransformOutput(-outW / 2f, -outH / 2f);
else
effectOutput = _pixelManager.GetTransformOutput(bounds.Left, bounds.Top);
effectOutput = _pixelManager!.GetTransformOutput(bounds.Left, bounds.Top);
return true;
}
if (hasDraws)
{
ctx.SetResolvedBuffer(_nativeLoadInput(), imgW, imgH);
if (_nativeUploaded)
ctx.SetResolvedBuffer(ReadNativeResultPixels(imgW, imgH), imgW, imgH);
return false;
}
@@ -909,6 +958,41 @@ namespace LuaScript
return false;
}
private void UploadNativeInputPixels(nint address, long capacity)
{
_nativeUploaded = true;
_pixelLoaderSemaphore.Wait();
try
{
_pixelManager!.LoadInputPixelsInto(input!, _pixelBounds, _pixelWidth, _pixelHeight, address, capacity);
}
finally
{
_pixelLoaderSemaphore.Release();
}
}
private byte[] ReadNativeResultPixels(int width, int height)
{
int length = width * height * 4;
if (_nativeResultBuffer is null || _nativeResultBuffer.Length < length)
_nativeResultBuffer = new byte[length];
_nativeReadLength = length;
_nativeWorker!.ReadPixels(_nativeReadIntoResult ??= ReadNativePixelsIntoResult);
return _nativeResultBuffer;
}
private unsafe void ReadNativePixelsIntoResult(nint address, long capacity)
{
fixed (byte* destination = _nativeResultBuffer)
Buffer.MemoryCopy((void*)address, destination, _nativeResultBuffer!.Length, Math.Min(_nativeReadLength, capacity));
}
private void WriteNativeOutputPixels(nint address, long capacity)
{
_pixelManager!.WritePixelsToOutput(address, _nativeOutputWidth, _nativeOutputHeight);
}
private void ResolveNativeAnchor(string group, int count, bool is3D, int connection, double[] positions)
{
_context.AddAnchorRequest(new AnchorRequestData(group, count, (AnchorConnection)connection, is3D));
+29 -25
ファイルの表示
@@ -60,11 +60,7 @@ namespace LuaScript
private TextRenderer? _textRenderer;
private ImageDecoder? _imageDecoder;
private MovieDecoder? _movieDecoder;
private string _fontFamily = string.Empty;
private double _fontSize = 34d;
private bool _fontBold;
private bool _fontItalic;
private int _fontColor = 0xFFFFFF;
private readonly AviUtlFontState _fontState = new();
private Script? _script;
private DynValue? _compiledChunk;
@@ -171,6 +167,7 @@ namespace LuaScript
CoreModules.ErrorHandling);
script.Options.ScriptLoader = new DisabledFileScriptLoader();
script.AttachDebugger(_debugger);
AviUtlGlobalRegistrar.RegisterFunctions(script.Globals, CurrentTimeRatio);
_script = script;
}
@@ -218,15 +215,12 @@ namespace LuaScript
_options.Clear();
_pixelOptions.Clear();
_fontFamily = string.Empty;
_fontSize = 34d;
_fontBold = false;
_fontItalic = false;
_fontColor = 0xFFFFFF;
_fontState.Reset();
if (isFirstSetup)
{
var sceneTable = new Table(script);
RegisterSceneCallbacks(sceneTable);
script.Globals["scene"] = sceneTable;
var objTable = new Table(script);
@@ -252,6 +246,7 @@ namespace LuaScript
if (!ReferenceEquals(script.Globals.Get("scene").Table, _sceneTable))
{
var sceneTable = new Table(script);
RegisterSceneCallbacks(sceneTable);
script.Globals["scene"] = sceneTable;
_sceneTable = sceneTable;
_sceneTableSnapshot = null;
@@ -425,6 +420,24 @@ namespace LuaScript
script.Globals[key] = DynValue.Nil;
}
private double CurrentTimeRatio() =>
_activeContext is { TotalTime: > 0d } context ? context.Time / context.TotalTime : 0d;
private void RegisterSceneCallbacks(Table scene) =>
SceneTableRegistrar.RegisterFunctions(scene, GetSceneValue, SetSceneValue);
private SceneValue GetSceneValue(string name)
{
_activeCancellation.ThrowIfCancellationRequested();
return _activeContext?.GetSceneValue(name) ?? SceneValue.Nil;
}
private void SetSceneValue(string name, SceneValue value)
{
_activeCancellation.ThrowIfCancellationRequested();
_activeContext?.SetSceneValue(name, value);
}
private void RegisterObjectCallbacks(Table obj)
{
obj["getobject"] = DynValue.NewCallback((execCtx, args) =>
@@ -531,20 +544,11 @@ namespace LuaScript
obj["setfont"] = DynValue.NewCallback((_, args) =>
{
_activeCancellation.ThrowIfCancellationRequested();
if (args.Count == 0)
return DynValue.Void;
if (args[0].Type == DataType.String)
_fontFamily = args[0].String;
if (args.Count > 1)
_fontSize = args[1].CastToNumber() ?? _fontSize;
if (args.Count > 2)
{
int type = (int)(args[2].CastToNumber() ?? 0d);
_fontBold = (type & 1) != 0;
_fontItalic = (type & 2) != 0;
}
if (args.Count > 3)
_fontColor = (int)(args[3].CastToNumber() ?? _fontColor);
_fontState.Apply(
args.Count > 0 ? args[0] : DynValue.Nil,
args.Count > 1 ? args[1] : DynValue.Nil,
args.Count > 2 ? args[2] : DynValue.Nil,
args.Count > 3 ? args[3] : DynValue.Nil);
return DynValue.Void;
});
@@ -760,7 +764,7 @@ namespace LuaScript
{
_textRenderer ??= new TextRenderer();
var buffer = _textRenderer.Render(
text, _fontFamily, _fontSize, _fontBold, _fontItalic, _fontColor,
text, _fontState.Family, _fontState.Size, _fontState.Bold, _fontState.Italic, _fontState.Color,
out int w, out int h);
_activeContext!.ReplaceBuffer(buffer, w, h);
RefreshObjDimensions();
+66 -30
ファイルの表示
@@ -1,7 +1,6 @@
using System;
using Vortice;
using System.Numerics;
using System.Runtime.InteropServices;
using Vortice.DCommon;
using Vortice.Direct2D1;
using Vortice.Direct2D1.Effects;
@@ -29,10 +28,56 @@ namespace LuaScript
_ctx = ctx;
}
public byte[] LoadInputPixels(ID2D1Image input, RawRectF bounds, int width, int height)
public unsafe byte[] LoadInputPixels(ID2D1Image input, RawRectF bounds, int width, int height)
{
EnsureBitmaps(width, height);
RenderToStaging(input, bounds);
var mapped = _stagingBitmap!.Map(MapOptions.Read);
try
{
fixed (byte* destination = _pixelBuffer)
CopyStagingRows(mapped.Bits, mapped.Pitch, destination, _pixelBuffer!.Length, width, height);
}
finally
{
_stagingBitmap.Unmap();
}
return _pixelBuffer!;
}
public unsafe void LoadInputPixelsInto(ID2D1Image input, RawRectF bounds, int width, int height, nint destination, long capacity)
{
EnsureBitmaps(width, height);
RenderToStaging(input, bounds);
var mapped = _stagingBitmap!.Map(MapOptions.Read);
try
{
CopyStagingRows(mapped.Bits, mapped.Pitch, (byte*)destination, capacity, width, height);
}
finally
{
_stagingBitmap.Unmap();
}
}
public unsafe void WritePixelsToOutput(byte[] pixels, int width, int height)
{
EnsureBitmaps(width, height);
fixed (byte* ptr = pixels)
_outputBitmap!.CopyFromMemory(new nint(ptr), width * 4);
}
public void WritePixelsToOutput(nint source, int width, int height)
{
EnsureBitmaps(width, height);
_outputBitmap!.CopyFromMemory(source, width * 4);
}
private void RenderToStaging(ID2D1Image input, RawRectF bounds)
{
var dc = _ctx.DeviceContext;
using var savedTarget = dc.Target;
@@ -44,37 +89,28 @@ namespace LuaScript
dc.Target = savedTarget;
_stagingBitmap!.CopyFromBitmap(_renderTarget!);
var mapped = _stagingBitmap.Map(MapOptions.Read);
try
{
if (mapped.Pitch == width * 4)
{
Marshal.Copy(mapped.Bits, _pixelBuffer!, 0, width * height * 4);
}
else
{
for (int row = 0; row < height; row++)
Marshal.Copy(
mapped.Bits + mapped.Pitch * row,
_pixelBuffer!,
row * width * 4,
width * 4);
}
}
finally
{
_stagingBitmap.Unmap();
}
return _pixelBuffer!;
}
public unsafe void WritePixelsToOutput(byte[] pixels, int width, int height)
private static unsafe void CopyStagingRows(nint bits, int pitch, byte* destination, long capacity, int width, int height)
{
EnsureBitmaps(width, height);
fixed (byte* ptr = pixels)
_outputBitmap!.CopyFromMemory(new nint(ptr), width * 4);
long required = (long)width * height * 4;
if (required > capacity)
throw new InvalidOperationException("Pixel destination is smaller than the mapped region.");
byte* source = (byte*)bits;
if (pitch == width * 4)
{
Buffer.MemoryCopy(source, destination, capacity, required);
return;
}
long rowBytes = (long)width * 4;
for (int row = 0; row < height; row++)
Buffer.MemoryCopy(
source + (long)pitch * row,
destination + rowBytes * row,
capacity - rowBytes * row,
rowBytes);
}
public ID2D1Image GetTransformOutput(float left, float top)
+8 -4
ファイルの表示
@@ -24,13 +24,17 @@ namespace LuaScript
{
byte* pixel = p + pixelIndex * 4;
double a = pixel[3];
if (channel == 3)
return a;
if (a <= 0d)
return 0d;
double scale = 255d / a;
return channel switch
{
0 => a > 0d ? Math.Clamp(pixel[2] * 255d / a, 0d, 255d) : 0d,
1 => a > 0d ? Math.Clamp(pixel[1] * 255d / a, 0d, 255d) : 0d,
2 => a > 0d ? Math.Clamp(pixel[0] * 255d / a, 0d, 255d) : 0d,
3 => a,
0 => Math.Clamp(pixel[2] * scale, 0d, 255d),
1 => Math.Clamp(pixel[1] * scale, 0d, 255d),
2 => Math.Clamp(pixel[0] * scale, 0d, 255d),
_ => throw new UnreachableException()
};
}
+197
ファイルの表示
@@ -0,0 +1,197 @@
using System.Collections.Concurrent;
using System.Runtime.CompilerServices;
using System.Text;
namespace LuaScript
{
internal enum SceneValueKind
{
Nil = 0,
Number = 1,
String = 2,
Boolean = 3,
}
internal readonly record struct SceneValue(SceneValueKind Kind, double Number, string? Text)
{
public static readonly SceneValue Nil = new(SceneValueKind.Nil, 0d, null);
public static SceneValue FromNumber(double value) => new(SceneValueKind.Number, value, null);
public static SceneValue FromBoolean(bool value) => new(SceneValueKind.Boolean, value ? 1d : 0d, null);
public static SceneValue FromString(string value) => new(SceneValueKind.String, 0d, value);
}
internal readonly record struct SceneValueQuery(string Name, SceneValue Result);
internal sealed class SceneSharedValues
{
public const int MaxNameBytes = 4095;
public const int MaxTextBytes = 4095;
public const int MaxEntries = 4096;
public const long MaxHistoryCostBytes = 16 * 1024 * 1024;
private const long VersionBaseCost = 64;
private readonly record struct SceneVersion(long Frame, int Layer, SceneValue Value);
private static readonly ConditionalWeakTable<object, ConcurrentDictionary<string, SceneSharedValues>> s_scopes = new();
private readonly Dictionary<string, List<SceneVersion>> _names = new(StringComparer.Ordinal);
private readonly object _gate = new();
private long _historyCost;
public static SceneSharedValues ForScene(object scope, string sceneId) =>
s_scopes.GetOrCreateValue(scope).GetOrAdd(sceneId, static _ => new SceneSharedValues());
public SceneValue Read(long generation, string name)
{
lock (_gate)
{
if (!_names.TryGetValue(name, out var versions))
return SceneValue.Nil;
int index = LatestBefore(versions, generation);
return index >= 0 ? versions[index].Value : SceneValue.Nil;
}
}
public void Publish(long generation, int layer, Dictionary<string, SceneValue> writes)
{
lock (_gate)
{
foreach (var pair in writes)
Upsert(generation, layer, pair.Key, pair.Value);
EnforceHistoryBudget();
}
}
private void Upsert(long generation, int layer, string name, SceneValue value)
{
if (!_names.TryGetValue(name, out var versions))
{
if (_names.Count >= MaxEntries)
return;
if (value == SceneValue.Nil)
return;
_names[name] = [new SceneVersion(generation, layer, value)];
return;
}
int index = LatestBefore(versions, generation + 1);
if (index >= 0 && versions[index].Frame == generation)
{
if (layer < versions[index].Layer)
return;
if (index < versions.Count - 1)
_historyCost += CostOf(value) - CostOf(versions[index].Value);
versions[index] = new SceneVersion(generation, layer, value);
return;
}
var previous = index >= 0 ? versions[index].Value : SceneValue.Nil;
if (value == previous)
return;
versions.Insert(index + 1, new SceneVersion(generation, layer, value));
if (index + 1 < versions.Count - 1)
_historyCost += CostOf(value);
else if (versions.Count > 1)
_historyCost += CostOf(versions[^2].Value);
}
private void EnforceHistoryBudget()
{
while (_historyCost > MaxHistoryCostBytes)
{
List<SceneVersion>? oldest = null;
string oldestName = string.Empty;
foreach (var pair in _names)
{
var versions = pair.Value;
if (versions.Count < 2)
continue;
if (oldest is null ||
versions[0].Frame < oldest[0].Frame ||
(versions[0].Frame == oldest[0].Frame && string.CompareOrdinal(pair.Key, oldestName) < 0))
{
oldest = versions;
oldestName = pair.Key;
}
}
if (oldest is null)
return;
_historyCost -= CostOf(oldest[0].Value);
oldest.RemoveAt(0);
}
}
private static long CostOf(SceneValue value) =>
VersionBaseCost + (value.Text is null ? 0 : value.Text.Length * 2L);
private static int LatestBefore(List<SceneVersion> versions, long generation)
{
int low = 0;
int high = versions.Count - 1;
int result = -1;
while (low <= high)
{
int mid = (low + high) >> 1;
if (versions[mid].Frame < generation)
{
result = mid;
low = mid + 1;
}
else
{
high = mid - 1;
}
}
return result;
}
public static string NormalizeName(string name) => TruncateUtf8(name, MaxNameBytes);
public static SceneValue NormalizeValue(SceneValue value) =>
value.Kind == SceneValueKind.String
? SceneValue.FromString(TruncateUtf8(value.Text ?? string.Empty, MaxTextBytes))
: value;
private static string TruncateUtf8(string text, int maxBytes)
{
if (text.Length <= maxBytes / 3 || Encoding.UTF8.GetByteCount(text) <= maxBytes)
return text;
int bytes = 0;
int length = 0;
while (length < text.Length)
{
char c = text[length];
int size;
int step = 1;
if (char.IsHighSurrogate(c) && length + 1 < text.Length && char.IsLowSurrogate(text[length + 1]))
{
size = 4;
step = 2;
}
else if (c < 0x80)
{
size = 1;
}
else if (c < 0x800)
{
size = 2;
}
else
{
size = 3;
}
if (bytes + size > maxBytes)
break;
bytes += size;
length += step;
}
return text[..length];
}
}
}
+54
ファイルの表示
@@ -0,0 +1,54 @@
using MoonSharp.Interpreter;
namespace LuaScript
{
internal static class SceneTableRegistrar
{
internal static void RegisterFunctions(Table scene, Func<string, SceneValue> getValue, Action<string, SceneValue> setValue)
{
scene["set"] = DynValue.NewCallback((_, args) =>
{
if (args.Count == 0 || args[0].Type != DataType.String)
return DynValue.Void;
var value = args.Count > 1 ? args[1] : DynValue.Nil;
SceneValue stored;
switch (value.Type)
{
case DataType.Number:
stored = SceneValue.FromNumber(value.Number);
break;
case DataType.String:
stored = SceneValue.FromString(value.String);
break;
case DataType.Boolean:
stored = SceneValue.FromBoolean(value.Boolean);
break;
case DataType.Nil:
case DataType.Void:
stored = SceneValue.Nil;
break;
default:
return DynValue.Void;
}
setValue(args[0].String, stored);
return DynValue.Void;
});
scene["get"] = DynValue.NewCallback((_, args) =>
{
if (args.Count == 0 || args[0].Type != DataType.String)
return DynValue.Nil;
var value = getValue(args[0].String);
return value.Kind switch
{
SceneValueKind.Number => DynValue.NewNumber(value.Number),
SceneValueKind.String => DynValue.NewString(value.Text ?? string.Empty),
SceneValueKind.Boolean => value.Number != 0d ? DynValue.True : DynValue.False,
_ => DynValue.Nil,
};
});
}
}
}
+69
ファイルの表示
@@ -0,0 +1,69 @@
namespace LuaScript
{
internal sealed class SceneValueSession
{
private readonly Dictionary<string, SceneValue> _writes = new(StringComparer.Ordinal);
private readonly Dictionary<string, SceneValue> _reads = new(StringComparer.Ordinal);
private readonly List<SceneValueQuery> _queries = [];
private SceneSharedValues? _store;
private object _scope = new();
private string _sceneId = string.Empty;
private long _generation;
private int _layer;
public bool HasWrites => _writes.Count > 0;
public IReadOnlyList<SceneValueQuery> Queries => _queries;
public void Begin(object scope, string sceneId, long generation, int layer)
{
if (!ReferenceEquals(_scope, scope) || !string.Equals(_sceneId, sceneId, StringComparison.Ordinal))
{
_store = null;
_scope = scope;
_sceneId = sceneId;
}
_generation = generation;
_layer = layer;
_writes.Clear();
_reads.Clear();
_queries.Clear();
}
public SceneValue Get(string name)
{
name = SceneSharedValues.NormalizeName(name);
if (_writes.TryGetValue(name, out var written))
return written;
if (_reads.TryGetValue(name, out var cached))
return cached;
var value = Store.Read(_generation, name);
_reads[name] = value;
_queries.Add(new SceneValueQuery(name, value));
return value;
}
public void Set(string name, SceneValue value)
{
name = SceneSharedValues.NormalizeName(name);
value = SceneSharedValues.NormalizeValue(value);
if (value.Kind != SceneValueKind.Nil &&
!_writes.ContainsKey(name) &&
_writes.Count >= SceneSharedValues.MaxEntries)
{
return;
}
_writes[name] = value;
}
public void Publish()
{
if (_writes.Count == 0)
return;
Store.Publish(_generation, _layer, _writes);
}
private SceneSharedValues Store => _store ??= SceneSharedValues.ForScene(_scope, _sceneId);
}
}
+70 -3
ファイルの表示
@@ -150,6 +150,32 @@
scene.width : الدقة الأفقية (بكسل) للمشهد (المشروع) [للقراءة فقط]
scene.height : الدقة الرأسية (بكسل) للمشهد (المشروع) [للقراءة فقط]
scene.set(name, value)
يخزّن قيمة في منطقة مشتركة على مستوى المشهد.
يمكن قراءة القيمة عبر scene.get(name) من جميع تأثيرات نصوص Lua
في المشهد نفسه، عبر العناصر والإطارات.
name : اسم القيمة (نص)
value : القيمة المراد تخزينها (رقم أو نص أو قيمة منطقية). تمرير nil
يحذفها.
* القيم غير الأرقام والنصوص والقيم المنطقية (الجداول والدوال وغيرها)
لا يتم تخزينها.
* تُقتطع الأسماء وقيم النصوص بعد 4095 بايت بترميز UTF-8.
مثال: scene.set("shared_x", obj.x)
scene.get(name)
يسترجع قيمة مخزّنة عبر scene.set()‎. يعيد nil للأسماء غير المعيّنة.
مثال: local x = scene.get("shared_x") or 0
* القيم التي كتبها النص البرمجي نفسه يمكن قراءتها فورًا عبر scene.get ضمن
التنفيذ نفسه. أما القيم التي كتبتها عناصر أخرى فتظهر اعتبارًا من الإطار
التالي، لذا لا تعتمد النتيجة على ترتيب تقييم العناصر داخل الإطار الواحد.
* عندما ينتهي النص البرمجي بخطأ أو بانتهاء المهلة، لا تُطبَّق أي من كتاباته
على المنطقة المشتركة.
* عند بدء تصدير الفيديو تبدأ المنطقة المشتركة فارغة، لذا يعطي تصدير المشروع
نفسه النتيجة نفسها في كل مرة.
* يمكن تخزين ما يصل إلى 4096 اسمًا لكل مشهد. تُتجاهل الكتابات إلى أسماء
جديدة تتجاوز الحد.
* القيم مستقلة لكل مشهد وتبقى في الذاكرة حتى إغلاق YMM4.
لا تُحفظ في ملف المشروع.
- جدول obj - المتغيرات -
@@ -602,6 +628,49 @@
anim.bezier(t, p0, p1, p2, p3): Evaluates cubic bezier curve at `t` (0.0~1.0)
- الدوال العامة المتوافقة مع AviUtl -
يمكن استدعاء الدوال التالية مباشرة في النطاق العام.
تعيد نتائج متطابقة على جميع محركات التنفيذ (MoonSharp / الأصلي).
RGB(r, g, b)
RGB(col)
RGB(r1, g1, b1, r2, g2, b2)
تحوّل بين قيمة اللون (0x000000-0xffffff) ومكوّناتها الأحمر والأخضر
والأزرق (0-255 لكل منها). بثلاث وسائط تركّب قيمة لون واحدة، وبوسيطة
واحدة تفكّكها إلى r وg وb. بست وسائط تعيد لونًا يتغيّر خطيًا من اللون
الأول إلى الثاني وفق الزمن المنقضي للكائن
(obj.time / obj.totaltime).
مثال: col = RGB(64, 192, 255) -- 0x40C0FF
مثال: r, g, b = RGB(0x0080FF) -- 0, 128, 255
مثال: col = RGB(64,192,255, 128,64,0) -- اللون الأول ← الثاني
HSV(h, s, v)
HSV(col)
HSV(h1, s1, v1, h2, s2, v2)
تحوّل بين قيمة اللون (0x000000-0xffffff) وتدرّج اللون (0-360)
والتشبع (0-100) والقيمة (0-100). تعمل الوسائط مثل RGB()‎.
مثال: col = HSV(60, 100, 100) -- 0xFFFF00
مثال: h, s, v = HSV(0x0080FF) -- 210, 100, 100
OR(a, b) / AND(a, b) / XOR(a, b)
تنفّذ عمليات على مستوى البتات (أو / و / أو حصرية) على أعداد صحيحة
بطول 32 بت. تُقتطع الكسور حتى 0.5 بالضبط عند التحويل إلى عدد صحيح
(2.50 ← 2، 2.51 ← 3).
مثال: result = OR(8, 3) -- 11
SHIFT(a, shift)
تنفّذ إزاحة حسابية. القيمة الموجبة تزيح لليسار والسالبة تزيح لليمين.
مثال: result = SHIFT(5, 3) -- 40
مثال: result = SHIFT(91, -2) -- 22
debug_print(text)
ترسل النص المحدد إلى OutputDebugString()‎. للتصحيح.
يمكن عرض الرسائل بأداة مراقبة تصحيح مثل DebugView. عند حدوث خطأ في
تنفيذ النص البرمجي تُرسل رسالة الخطأ تلقائيًا أيضًا.
مثال: debug_print(string.format("x = %d", obj.x))
- المكتبات القياسية المتاحة -
مكتبة math:
@@ -758,14 +827,12 @@
× تحميل الوحدات عبر require، والوصول العشوائي إلى الملفات مثل
io / dofile (تحميل الصور / الفيديو عبر obj.load مدعوم مع التحقق
من الترويسة).
× obj.setanchor، scene.set / scene.get وما شابه.
× obj.setanchor وما شابه.
- الميزات غير المدعومة / القيود -
× obj.rand1()، obj.mes()، obj.setanchor() وما شابه من AviUtl2 غير مدعومة.
× الدوال مثل scene.set() و scene.get() في جدول scene الخاص بـ AviUtl2 غير مدعومة.
(يمكن قراءة scene.width و scene.height فقط)
× الوصول العشوائي إلى الملفات من النصوص (require, dofile, io وما شابه) غير مدعوم.
فقط obj.load("image"/"movie") يحمّل الملفات المؤكَّد أنها وسائط أصلية عبر
التحقق من الترويسة الأولى.
+73 -3
ファイルの表示
@@ -157,6 +157,32 @@
scene.cx : Half of the scene's horizontal resolution (= scene.width / 2) [ReadOnly]
scene.cy : Half of the scene's vertical resolution (= scene.height / 2) [ReadOnly]
scene.set(name, value)
Stores a value in a shared area scoped to the scene.
The value can be read back with scene.get(name) from every Lua script
effect in the same scene, across items and frames.
name : Name of the value (string)
value : Value to store (number, string, or boolean). Passing nil removes it.
* Values other than numbers, strings, and booleans (tables, functions,
etc.) are not stored.
* Names and string values are truncated beyond 4095 bytes in UTF-8.
Example: scene.set("shared_x", obj.x)
scene.get(name)
Retrieves a value stored with scene.set(). Returns nil for unset names.
Example: local x = scene.get("shared_x") or 0
* Values written by your own script can be read back immediately with
scene.get within the same run. Values written by other items become
visible from the next frame, so the result does not depend on the order
in which items are evaluated within a frame.
* When a script ends with an error or a timeout, none of its writes are
applied to the shared area.
* When video export starts, the shared area starts empty, so exporting the
same project always produces the same result.
* Up to 4096 names can be stored per scene. Writes to new names beyond the
limit are ignored.
* Values are independent per scene and kept in memory until YMM4 exits.
They are not saved into the project file.
- obj Table - Variables -
@@ -623,6 +649,52 @@
anim.bezier(t, p0, p1, p2, p3): Evaluates cubic bezier curve at `t` (0.0~1.0)
- AviUtl-Compatible Global Functions -
The following functions can be called directly in the global scope.
They return identical results on every execution engine (MoonSharp / native).
RGB(r, g, b)
RGB(col)
RGB(r1, g1, b1, r2, g2, b2)
Converts between a color value (0x000000-0xffffff) and its red, green,
and blue components (0-255 each). With 3 arguments it composes a single
color value, and with 1 argument it decomposes into r, g, b. With 6
arguments it returns a color that changes linearly from the first color
to the second according to the object's elapsed time
(obj.time / obj.totaltime).
Example: col = RGB(64, 192, 255) -- 0x40C0FF
Example: r, g, b = RGB(0x0080FF) -- 0, 128, 255
Example: col = RGB(64,192,255, 128,64,0) -- start color -> end color
HSV(h, s, v)
HSV(col)
HSV(h1, s1, v1, h2, s2, v2)
Converts between a color value (0x000000-0xffffff) and hue (0-360),
saturation (0-100), and value (0-100). The arguments work like RGB().
Example: col = HSV(60, 100, 100) -- 0xFFFF00
Example: h, s, v = HSV(0x0080FF) -- 210, 100, 100
OR(a, b) / AND(a, b) / XOR(a, b)
Performs bitwise operations (or / and / exclusive or) on 32-bit
integers. Fractions up to exactly 0.5 are truncated when converting to
integers (2.50 -> 2, 2.51 -> 3).
Example: result = OR(8, 3) -- 11
SHIFT(a, shift)
Performs an arithmetic shift. A positive shift shifts left and a
negative shift shifts right.
Example: result = SHIFT(5, 3) -- 40
Example: result = SHIFT(91, -2) -- 22
debug_print(text)
Sends the given string to OutputDebugString(). For debugging.
Messages can be viewed with a debug monitor tool such as DebugView.
When a script execution error occurs, the error message is also sent
automatically.
Example: debug_print(string.format("x = %d", obj.x))
- Available Standard Libraries -
math library:
@@ -784,14 +856,12 @@
x Module loading via require, and arbitrary file access such as io /
dofile (image / video loading via obj.load is supported with header
validation).
x obj.setanchor, scene.set / scene.get, etc.
x obj.setanchor, etc.
- Unsupported Features / Limitations -
x obj.rand1(), obj.mes(), obj.setanchor(), etc. from AviUtl2 are not supported.
x Functions such as scene.set() and scene.get() in the AviUtl2 scene table are not supported.
(Only scene.width and scene.height can be read)
x Arbitrary file access from scripts (require, dofile, io, etc.) is not supported.
Only obj.load("image"/"movie") loads files confirmed to be genuine media by
leading-header validation.
+77 -3
ファイルの表示
@@ -155,6 +155,34 @@
scene.width : Resolución horizontal (píxeles) de la escena (proyecto) [Solo lectura]
scene.height : Resolución vertical (píxeles) de la escena (proyecto) [Solo lectura]
scene.set(name, value)
Guarda un valor en un área compartida a nivel de escena.
El valor puede leerse con scene.get(name) desde todos los efectos de
script Lua de la misma escena, a través de elementos y fotogramas.
name : Nombre del valor (cadena)
value : Valor a guardar (número, cadena o booleano). Pasar nil lo elimina.
* Los valores que no sean números, cadenas o booleanos (tablas,
funciones, etc.) no se guardan.
* Los nombres y los valores de cadena se truncan más allá de 4095
bytes en UTF-8.
Ejemplo: scene.set("shared_x", obj.x)
scene.get(name)
Obtiene un valor guardado con scene.set(). Devuelve nil para nombres
no establecidos.
Ejemplo: local x = scene.get("shared_x") or 0
* Los valores escritos por su propio script pueden leerse inmediatamente con
scene.get dentro de la misma ejecución. Los valores escritos por otros
elementos son visibles a partir del fotograma siguiente, por lo que el
resultado no depende del orden de evaluación dentro de un fotograma.
* Cuando un script termina con un error o por tiempo de espera, ninguna de
sus escrituras se aplica al área compartida.
* Al iniciar la exportación de video, el área compartida comienza vacía, por
lo que exportar el mismo proyecto siempre produce el mismo resultado.
* Se pueden guardar hasta 4096 nombres por escena. Las escrituras a nombres
nuevos por encima del límite se ignoran.
* Los valores son independientes por escena y se mantienen en memoria hasta
que YMM4 se cierra. No se guardan en el archivo del proyecto.
- Tabla obj - Variables -
@@ -627,6 +655,54 @@
anim.bezier(t, p0, p1, p2, p3): Evaluates cubic bezier curve at `t` (0.0~1.0)
- Funciones globales compatibles con AviUtl -
Las siguientes funciones pueden llamarse directamente en el ámbito global.
Devuelven resultados idénticos en todos los motores de ejecución
(MoonSharp / nativo).
RGB(r, g, b)
RGB(col)
RGB(r1, g1, b1, r2, g2, b2)
Convierte entre un valor de color (0x000000-0xffffff) y sus
componentes rojo, verde y azul (0-255 cada uno). Con 3 argumentos
compone un único valor de color y con 1 argumento lo descompone en
r, g, b. Con 6 argumentos devuelve un color que cambia linealmente
del primer color al segundo según el tiempo transcurrido del objeto
(obj.time / obj.totaltime).
Ejemplo: col = RGB(64, 192, 255) -- 0x40C0FF
Ejemplo: r, g, b = RGB(0x0080FF) -- 0, 128, 255
Ejemplo: col = RGB(64,192,255, 128,64,0) -- color inicial -> final
HSV(h, s, v)
HSV(col)
HSV(h1, s1, v1, h2, s2, v2)
Convierte entre un valor de color (0x000000-0xffffff) y tono (0-360),
saturación (0-100) y valor (0-100). Los argumentos funcionan como
en RGB().
Ejemplo: col = HSV(60, 100, 100) -- 0xFFFF00
Ejemplo: h, s, v = HSV(0x0080FF) -- 210, 100, 100
OR(a, b) / AND(a, b) / XOR(a, b)
Realiza operaciones bit a bit (or / and / or exclusivo) sobre enteros
de 32 bits. Las fracciones hasta exactamente 0.5 se truncan al
convertir a entero (2.50 -> 2, 2.51 -> 3).
Ejemplo: result = OR(8, 3) -- 11
SHIFT(a, shift)
Realiza un desplazamiento aritmético. Un shift positivo desplaza a la
izquierda y uno negativo a la derecha.
Ejemplo: result = SHIFT(5, 3) -- 40
Ejemplo: result = SHIFT(91, -2) -- 22
debug_print(text)
Envía la cadena indicada a OutputDebugString(). Para depuración.
Los mensajes pueden verse con una herramienta de monitorización como
DebugView. Cuando ocurre un error de ejecución del script, el mensaje
de error también se envía automáticamente.
Ejemplo: debug_print(string.format("x = %d", obj.x))
- Bibliotecas estándar disponibles -
Biblioteca math:
@@ -792,14 +868,12 @@
x Carga de módulos mediante require y acceso arbitrario a archivos como
io / dofile (la carga de imagen / vídeo con obj.load sí se admite con
validación de cabecera).
x obj.setanchor, scene.set / scene.get, etc.
x obj.setanchor, etc.
- Funciones no admitidas / Limitaciones -
x obj.rand1(), obj.mes(), obj.setanchor(), etc. de AviUtl2 no son compatibles.
x Las funciones como scene.set() y scene.get() de la tabla scene de AviUtl2 no son compatibles.
(Solo se pueden leer scene.width y scene.height)
x El acceso arbitrario a archivos desde scripts (require, dofile, io, etc.) no es compatible.
Solo obj.load("image"/"movie") carga archivos confirmados como medios genuinos
mediante validación de la cabecera inicial.
+76 -3
ファイルの表示
@@ -156,6 +156,34 @@
scene.width : Resolusi horizontal (piksel) adegan (proyek) [Hanya Baca]
scene.height : Resolusi vertikal (piksel) adegan (proyek) [Hanya Baca]
scene.set(name, value)
Menyimpan nilai ke area bersama yang dibatasi per adegan.
Nilai dapat dibaca kembali dengan scene.get(name) dari semua efek
skrip Lua dalam adegan yang sama, lintas item dan frame.
name : Nama nilai (string)
value : Nilai yang disimpan (angka, string, atau boolean). Mengirim
nil akan menghapusnya.
* Nilai selain angka, string, dan boolean (tabel, fungsi, dll.)
tidak disimpan.
* Nama dan nilai string dipotong setelah 4095 byte dalam UTF-8.
Contoh: scene.set("shared_x", obj.x)
scene.get(name)
Mengambil nilai yang disimpan dengan scene.set(). Mengembalikan nil
untuk nama yang belum diatur.
Contoh: local x = scene.get("shared_x") or 0
* Nilai yang ditulis oleh skrip Anda sendiri dapat langsung dibaca kembali
dengan scene.get dalam eksekusi yang sama. Nilai yang ditulis oleh item
lain terlihat mulai frame berikutnya, sehingga hasilnya tidak bergantung
pada urutan evaluasi item dalam satu frame.
* Saat skrip berakhir dengan kesalahan atau batas waktu, tidak ada
penulisannya yang diterapkan ke area bersama.
* Saat ekspor video dimulai, area bersama dimulai dari keadaan kosong,
sehingga mengekspor proyek yang sama selalu menghasilkan hasil yang sama.
* Hingga 4096 nama dapat disimpan per adegan. Penulisan ke nama baru di
atas batas akan diabaikan.
* Nilai bersifat independen per adegan dan disimpan di memori sampai YMM4
ditutup. Tidak disimpan ke berkas proyek.
- Tabel obj - Variabel -
@@ -623,6 +651,53 @@
anim.bezier(t, p0, p1, p2, p3): Evaluates cubic bezier curve at `t` (0.0~1.0)
- Fungsi Global yang Kompatibel dengan AviUtl -
Fungsi-fungsi berikut dapat dipanggil langsung di lingkup global.
Semuanya mengembalikan hasil identik di setiap mesin eksekusi
(MoonSharp / native).
RGB(r, g, b)
RGB(col)
RGB(r1, g1, b1, r2, g2, b2)
Mengonversi antara nilai warna (0x000000-0xffffff) dan komponen
merah, hijau, biru (masing-masing 0-255). Dengan 3 argumen menyusun
satu nilai warna, dan dengan 1 argumen menguraikannya menjadi
r, g, b. Dengan 6 argumen mengembalikan warna yang berubah linear
dari warna pertama ke warna kedua sesuai waktu objek
(obj.time / obj.totaltime).
Contoh: col = RGB(64, 192, 255) -- 0x40C0FF
Contoh: r, g, b = RGB(0x0080FF) -- 0, 128, 255
Contoh: col = RGB(64,192,255, 128,64,0) -- warna awal -> akhir
HSV(h, s, v)
HSV(col)
HSV(h1, s1, v1, h2, s2, v2)
Mengonversi antara nilai warna (0x000000-0xffffff) dan hue (0-360),
saturasi (0-100), serta value (0-100). Argumen bekerja seperti RGB().
Contoh: col = HSV(60, 100, 100) -- 0xFFFF00
Contoh: h, s, v = HSV(0x0080FF) -- 210, 100, 100
OR(a, b) / AND(a, b) / XOR(a, b)
Melakukan operasi bitwise (or / and / exclusive or) pada bilangan
bulat 32-bit. Pecahan hingga tepat 0.5 dibulatkan ke bawah saat
dikonversi ke bilangan bulat (2.50 -> 2, 2.51 -> 3).
Contoh: result = OR(8, 3) -- 11
SHIFT(a, shift)
Melakukan pergeseran aritmetika. Shift positif menggeser ke kiri dan
shift negatif menggeser ke kanan.
Contoh: result = SHIFT(5, 3) -- 40
Contoh: result = SHIFT(91, -2) -- 22
debug_print(text)
Mengirim string yang ditentukan ke OutputDebugString(). Untuk
debugging. Pesan dapat dilihat dengan alat pemantau debug seperti
DebugView. Saat terjadi kesalahan eksekusi skrip, pesan kesalahan
juga dikirim secara otomatis.
Contoh: debug_print(string.format("x = %d", obj.x))
- Pustaka Standar yang Tersedia -
Pustaka math:
@@ -785,14 +860,12 @@
x Pemuatan modul melalui require, dan akses berkas sembarang seperti
io / dofile (pemuatan gambar / video via obj.load didukung dengan
validasi header).
x obj.setanchor, scene.set / scene.get, dll.
x obj.setanchor, dll.
- Fitur yang Tidak Didukung / Batasan -
x obj.rand1(), obj.mes(), obj.setanchor(), dll. dari AviUtl2 tidak didukung.
x Fungsi seperti scene.set() dan scene.get() dalam tabel scene AviUtl2 tidak didukung.
(Hanya scene.width dan scene.height yang dapat dibaca)
x Akses berkas sembarang dari skrip (require, dofile, io, dll.) tidak didukung.
Hanya obj.load("image"/"movie") yang memuat berkas yang dipastikan sebagai
media asli melalui validasi header awal.
+70 -3
ファイルの表示
@@ -151,6 +151,31 @@
scene.cx : シーンの横解像度の半分 (= scene.width / 2) [ReadOnly]
scene.cy : シーンの縦解像度の半分 (= scene.height / 2) [ReadOnly]
scene.set(name, value)
シーン単位の共有領域へ値を保存します。
同じシーン内のすべての Lua スクリプトエフェクトから、アイテムや
フレームをまたいで scene.get(name) で参照できます。
name : 値の名前(文字列)
value : 保存する値(数値・文字列・真偽値)。nil を渡すと削除します。
※ 数値・文字列・真偽値以外(テーブル・関数など)は保存されません。
※ 名前と文字列値は UTF-8 換算で 4095 バイトを超える部分を切り捨てます。
例:scene.set("shared_x", obj.x)
scene.get(name)
scene.set() で保存した値を取得します。未設定の名前は nil を返します。
例:local x = scene.get("shared_x") or 0
※ 自分のスクリプトが書き込んだ値は、同じ実行の中で直後の scene.get から
そのまま読み取れます。他のアイテムが書き込んだ値は、次のフレームの
評価から読み取れます。同じフレームの中では、アイテムがどの順番で
評価されても読み取れる値は変わりません。
※ スクリプトがエラーまたはタイムアウトで終了した場合には、その実行の
書き込みは共有領域へ反映されません。
※ 動画出力を開始すると共有領域は空の状態から始まるため、同じ
プロジェクトを出力すれば毎回同じ結果になります。
※ 1 つのシーンに保存できる名前は 4096 個までです。上限を超えた新しい
名前への書き込みは無視されます。
※ 値はシーンごとに独立しており、YMM4 を終了するまでメモリ上に保持
されます。プロジェクトファイルには保存されません。
- obj テーブル - 変数 -
@@ -607,6 +632,50 @@
anim.bezier(t, p0, p1, p2, p3): t (0.0~1.0) における3次ベジェ曲線の値を計算
- AviUtl 互換のグローバル関数 -
以下の関数はグローバルスコープで直接呼び出せます。
すべての実行エンジン(MoonSharp / ネイティブ)で同一の結果を返します。
RGB(r, g, b)
RGB(col)
RGB(r1, g1, b1, r2, g2, b2)
色情報(0x000000~0xffffff)と赤・緑・青(各0~255)を相互変換します。
引数 3 つで 1 つの色情報へ合成し、引数 1 つで r, g, b の 3 値へ
分解します。引数 6 つでは、オブジェクトの時間経過
(obj.time / obj.totaltime)に応じて一色目から二色目へ直線的に
変化する色情報を返します。
例:col = RGB(64, 192, 255) -- 0x40C0FF
例:r, g, b = RGB(0x0080FF) -- 0, 128, 255
例:col = RGB(64,192,255, 128,64,0) -- 開始色→終了色
HSV(h, s, v)
HSV(col)
HSV(h1, s1, v1, h2, s2, v2)
色情報(0x000000~0xffffff)と色相(0~360)・彩度(0~100)・
明度(0~100)を相互変換します。引数の意味は RGB() と同様です。
例:col = HSV(60, 100, 100) -- 0xFFFF00
例:h, s, v = HSV(0x0080FF) -- 210, 100, 100
OR(a, b) / AND(a, b) / XOR(a, b)
32bit 整数としてビット演算(論理和・論理積・排他的論理和)をします。
小数は 0.5 ちょうどまでを切り捨てて整数化します(2.50→2、2.51→3)。
例:result = OR(8, 3) -- 11
SHIFT(a, shift)
算術シフトをします。shift が正の数だと左シフト、負の数だと
右シフトになります。
例:result = SHIFT(5, 3) -- 40
例:result = SHIFT(91, -2) -- 22
debug_print(text)
指定の文字列を OutputDebugString() へ送ります。デバッグ用です。
メッセージは DebugView などのデバッグモニタツールで確認できます。
また、スクリプトの実行エラーが発生したときにはエラーメッセージが
自動で送られます。
例:debug_print(string.format("x = %d", obj.x))
- 利用可能な標準ライブラリ -
math ライブラリ:
@@ -764,14 +833,12 @@
これらを呼び出すスクリプトは意図どおりには動作しません。
×require によるモジュール読み込み、io / dofile などの任意ファイル
アクセス(obj.load の画像 / 動画はヘッダー検証付きで対応)。
×obj.setanchor、scene.set / scene.get 等。
×obj.setanchor 等。
- 非対応・制限事項 -
×AviUtl2 の obj.rand1(), obj.mes(), obj.setanchor() 等には対応していません。
×AviUtl2 の scene テーブルの scene.set(), scene.get() 等の関数には対応していません。
(scene.width と scene.height の読み取りのみ対応)
×スクリプトからの任意ファイルアクセス(require, dofile, io 等)には対応して
いません。obj.load("image"/"movie") のみ、先頭ヘッダー検証で真正なメディアと
確認できたファイルを読み込みます。
+71 -3
ファイルの表示
@@ -148,6 +148,32 @@
scene.width : 씬(프로젝트)의 가로 해상도(픽셀) [읽기 전용]
scene.height : 씬(프로젝트)의 세로 해상도(픽셀) [읽기 전용]
scene.set(name, value)
씬 단위의 공유 영역에 값을 저장합니다.
같은 씬 안의 모든 Lua 스크립트 이펙트에서 아이템과 프레임을 넘어
scene.get(name)으로 참조할 수 있습니다.
name : 값의 이름(문자열)
value : 저장할 값(숫자·문자열·불리언). nil을 전달하면 삭제됩니다.
※ 숫자·문자열·불리언 이외(테이블·함수 등)는 저장되지 않습니다.
※ 이름과 문자열 값은 UTF-8 기준 4095바이트를 넘는 부분이 잘립니다.
예: scene.set("shared_x", obj.x)
scene.get(name)
scene.set()으로 저장한 값을 가져옵니다. 설정되지 않은 이름은 nil을
반환합니다.
예: local x = scene.get("shared_x") or 0
※ 자신의 스크립트가 기록한 값은 같은 실행 안에서 바로 다음의 scene.get으로
그대로 읽을 수 있습니다. 다른 아이템이 기록한 값은 다음 프레임의
평가부터 읽을 수 있으므로, 같은 프레임 안에서는 아이템의 평가 순서와
관계없이 결과가 같습니다.
※ 스크립트가 오류 또는 시간 초과로 종료된 경우, 그 실행의 기록은 공유
영역에 반영되지 않습니다.
※ 동영상 출력을 시작하면 공유 영역은 빈 상태에서 시작하므로, 같은
프로젝트를 출력하면 항상 같은 결과가 나옵니다.
※ 하나의 씬에 저장할 수 있는 이름은 4096개까지입니다. 상한을 넘는 새
이름에 대한 기록은 무시됩니다.
※ 값은 씬마다 독립적이며 YMM4를 종료할 때까지 메모리에 유지됩니다.
프로젝트 파일에는 저장되지 않습니다.
- obj 테이블 - 변수 -
@@ -599,6 +625,50 @@
anim.bezier(t, p0, p1, p2, p3): t(0.0~1.0)에서의 3차 베지어 곡선 값을 계산
- AviUtl 호환 전역 함수 -
다음 함수는 전역 스코프에서 직접 호출할 수 있습니다.
모든 실행 엔진(MoonSharp / 네이티브)에서 동일한 결과를 반환합니다.
RGB(r, g, b)
RGB(col)
RGB(r1, g1, b1, r2, g2, b2)
색 정보(0x000000~0xffffff)와 빨강·초록·파랑(각 0~255)을 상호
변환합니다. 인수 3개는 하나의 색 정보로 합성하고, 인수 1개는
r, g, b 세 값으로 분해합니다. 인수 6개는 오브젝트의 시간 경과
(obj.time / obj.totaltime)에 따라 첫 번째 색에서 두 번째 색으로
선형 변화하는 색 정보를 반환합니다.
예: col = RGB(64, 192, 255) -- 0x40C0FF
예: r, g, b = RGB(0x0080FF) -- 0, 128, 255
예: col = RGB(64,192,255, 128,64,0) -- 시작 색 → 종료 색
HSV(h, s, v)
HSV(col)
HSV(h1, s1, v1, h2, s2, v2)
색 정보(0x000000~0xffffff)와 색상(0~360)·채도(0~100)·
명도(0~100)를 상호 변환합니다. 인수의 의미는 RGB()와 같습니다.
예: col = HSV(60, 100, 100) -- 0xFFFF00
예: h, s, v = HSV(0x0080FF) -- 210, 100, 100
OR(a, b) / AND(a, b) / XOR(a, b)
32bit 정수로 비트 연산(논리합·논리곱·배타적 논리합)을 합니다.
소수는 정확히 0.5까지 내림하여 정수화합니다(2.50→2, 2.51→3).
예: result = OR(8, 3) -- 11
SHIFT(a, shift)
산술 시프트를 합니다. shift가 양수면 왼쪽, 음수면 오른쪽으로
시프트합니다.
예: result = SHIFT(5, 3) -- 40
예: result = SHIFT(91, -2) -- 22
debug_print(text)
지정한 문자열을 OutputDebugString()으로 보냅니다. 디버그용입니다.
메시지는 DebugView 등의 디버그 모니터 도구로 확인할 수 있습니다.
또한 스크립트 실행 오류가 발생하면 오류 메시지가 자동으로
전송됩니다.
예: debug_print(string.format("x = %d", obj.x))
- 사용 가능한 표준 라이브러리 -
math 라이브러리:
@@ -756,14 +826,12 @@
이를 호출하는 스크립트는 의도대로 동작하지 않습니다.
× require에 의한 모듈 로드 및 io / dofile 등의 임의 파일 접근
(obj.load의 이미지 / 동영상 로드는 헤더 검증과 함께 지원).
× obj.setanchor, scene.set / scene.get 등.
× obj.setanchor 등.
- 미지원·제한 사항 -
× AviUtl2의 obj.rand1(), obj.mes(), obj.setanchor() 등은 지원하지 않습니다.
× AviUtl2의 scene 테이블의 scene.set(), scene.get() 등의 함수는 지원하지 않습니다.
(scene.width와 scene.height의 읽기만 지원)
× 스크립트에서의 임의 파일 접근(require, dofile, io 등)은 지원하지 않습니다.
obj.load("image"/"movie")만 선두 헤더 검증으로 진짜 미디어로 확인된 파일을
읽습니다.
+64 -3
ファイルの表示
@@ -147,6 +147,28 @@
scene.width : 场景(项目)的水平分辨率(像素)[只读]
scene.height : 场景(项目)的垂直分辨率(像素)[只读]
scene.set(name, value)
将值保存到以场景为单位的共享区域。
同一场景内的所有 Lua 脚本效果都可以跨项目、跨帧通过
scene.get(name) 读取该值。
name : 值的名称(字符串)
value : 要保存的值(数值、字符串、布尔值)。传入 nil 时删除。
* 数值、字符串、布尔值以外的类型(表、函数等)不会被保存。
* 名称和字符串值按 UTF-8 计算超过 4095 字节的部分将被截断。
例:scene.set("shared_x", obj.x)
scene.get(name)
获取通过 scene.set() 保存的值。未设置的名称返回 nil。
例:local x = scene.get("shared_x") or 0
* 自己的脚本写入的值,在同一次执行中可以立即通过 scene.get 读取。
其他项目写入的值从下一帧的求值开始可见,因此同一帧内的结果不依赖
项目的求值顺序。
* 脚本因错误或超时而结束时,该次执行的写入不会反映到共享区域。
* 开始视频输出时,共享区域从空状态开始,因此输出同一项目时每次都会
得到相同的结果。
* 每个场景最多可保存 4096 个名称。超过上限的新名称写入将被忽略。
* 值按场景相互独立,在 YMM4 退出前一直保留在内存中。
不会保存到项目文件。
- obj 表 - 变量 -
@@ -585,6 +607,47 @@
anim.bezier(t, p0, p1, p2, p3): 计算 t(0.0~1.0) 时的三次贝塞尔曲线值
- AviUtl 兼容的全局函数 -
以下函数可在全局作用域中直接调用。
在所有执行引擎(MoonSharp / 原生)上返回完全相同的结果。
RGB(r, g, b)
RGB(col)
RGB(r1, g1, b1, r2, g2, b2)
在颜色信息(0x000000~0xffffff)与红、绿、蓝(各 0~255)之间相互
转换。3 个参数时合成为一个颜色信息,1 个参数时分解为 r, g, b 三个值。
6 个参数时,返回随对象时间经过(obj.time / obj.totaltime)从第一种
颜色向第二种颜色线性变化的颜色信息。
例:col = RGB(64, 192, 255) -- 0x40C0FF
例:r, g, b = RGB(0x0080FF) -- 0, 128, 255
例:col = RGB(64,192,255, 128,64,0) -- 起始色→结束色
HSV(h, s, v)
HSV(col)
HSV(h1, s1, v1, h2, s2, v2)
在颜色信息(0x000000~0xffffff)与色相(0~360)、饱和度(0~100)、
明度(0~100)之间相互转换。参数含义与 RGB() 相同。
例:col = HSV(60, 100, 100) -- 0xFFFF00
例:h, s, v = HSV(0x0080FF) -- 210, 100, 100
OR(a, b) / AND(a, b) / XOR(a, b)
以 32bit 整数进行位运算(或、与、异或)。
小数转换为整数时,恰好 0.5 及以下会被舍去(2.50→2、2.51→3)。
例:result = OR(8, 3) -- 11
SHIFT(a, shift)
进行算术移位。shift 为正数时左移,为负数时右移。
例:result = SHIFT(5, 3) -- 40
例:result = SHIFT(91, -2) -- 22
debug_print(text)
将指定字符串发送到 OutputDebugString()。用于调试。
可通过 DebugView 等调试监视工具查看消息。
此外,脚本发生执行错误时会自动发送错误消息。
例:debug_print(string.format("x = %d", obj.x))
- 可用标准库 -
math 库:
@@ -734,14 +797,12 @@
调用它们的脚本不会按预期运行。
× 通过 require 加载模块,以及 io / dofile 等任意文件访问
(obj.load 的图像 / 视频加载已带文件头校验支持)。
× obj.setanchor、scene.set / scene.get 等。
× obj.setanchor 等。
- 不支持项目·限制事项 -
× 不支持 AviUtl2 的 obj.rand1()、obj.mes()、obj.setanchor() 等。
× 不支持 AviUtl2 scene 表中的 scene.set()、scene.get() 等函数。
(仅支持读取 scene.width 和 scene.height)
× 不支持脚本进行任意文件访问(require、dofile、io 等)。
仅 obj.load("image"/"movie") 会加载经文件头校验确认为真正媒体的文件。
× 修改 obj.z 会反映到绘制中(包含在 ReadBack 中),
+64 -3
ファイルの表示
@@ -147,6 +147,28 @@
scene.width : 場景(專案)的水平解析度(像素)[唯讀]
scene.height : 場景(專案)的垂直解析度(像素)[唯讀]
scene.set(name, value)
將值儲存到以場景為單位的共享區域。
同一場景內的所有 Lua 腳本效果都可以跨項目、跨影格透過
scene.get(name) 讀取該值。
name : 值的名稱(字串)
value : 要儲存的值(數值、字串、布林值)。傳入 nil 時刪除。
* 數值、字串、布林值以外的型別(表、函式等)不會被儲存。
* 名稱和字串值按 UTF-8 計算超過 4095 位元組的部分將被截斷。
例:scene.set("shared_x", obj.x)
scene.get(name)
取得透過 scene.set() 儲存的值。未設定的名稱回傳 nil。
例:local x = scene.get("shared_x") or 0
* 自己的腳本寫入的值,在同一次執行中可以立即透過 scene.get 讀取。
其他項目寫入的值從下一影格的求值開始可見,因此同一影格內的結果不
依賴項目的求值順序。
* 腳本因錯誤或逾時而結束時,該次執行的寫入不會反映到共享區域。
* 開始影片輸出時,共享區域從空狀態開始,因此輸出同一專案時每次都會
得到相同的結果。
* 每個場景最多可儲存 4096 個名稱。超過上限的新名稱寫入將被忽略。
* 值按場景相互獨立,在 YMM4 結束前一直保留在記憶體中。
不會儲存到專案檔。
- obj 表 - 變數 -
@@ -586,6 +608,47 @@
anim.bezier(t, p0, p1, p2, p3): 計算 t(0.0~1.0) 時的三次貝茲曲線值
- AviUtl 相容的全域函式 -
以下函式可在全域範圍中直接呼叫。
在所有執行引擎(MoonSharp / 原生)上回傳完全相同的結果。
RGB(r, g, b)
RGB(col)
RGB(r1, g1, b1, r2, g2, b2)
在顏色資訊(0x000000~0xffffff)與紅、綠、藍(各 0~255)之間相互
轉換。3 個引數時合成為一個顏色資訊,1 個引數時分解為 r, g, b 三個值。
6 個引數時,回傳隨物件時間經過(obj.time / obj.totaltime)從第一種
顏色向第二種顏色線性變化的顏色資訊。
例:col = RGB(64, 192, 255) -- 0x40C0FF
例:r, g, b = RGB(0x0080FF) -- 0, 128, 255
例:col = RGB(64,192,255, 128,64,0) -- 起始色→結束色
HSV(h, s, v)
HSV(col)
HSV(h1, s1, v1, h2, s2, v2)
在顏色資訊(0x000000~0xffffff)與色相(0~360)、飽和度(0~100)、
明度(0~100)之間相互轉換。引數含義與 RGB() 相同。
例:col = HSV(60, 100, 100) -- 0xFFFF00
例:h, s, v = HSV(0x0080FF) -- 210, 100, 100
OR(a, b) / AND(a, b) / XOR(a, b)
以 32bit 整數進行位元運算(或、與、互斥或)。
小數轉換為整數時,恰好 0.5 及以下會被捨去(2.50→2、2.51→3)。
例:result = OR(8, 3) -- 11
SHIFT(a, shift)
進行算術移位。shift 為正數時左移,為負數時右移。
例:result = SHIFT(5, 3) -- 40
例:result = SHIFT(91, -2) -- 22
debug_print(text)
將指定字串傳送到 OutputDebugString()。用於除錯。
可透過 DebugView 等除錯監視工具查看訊息。
此外,腳本發生執行錯誤時會自動傳送錯誤訊息。
例:debug_print(string.format("x = %d", obj.x))
- 可用標準函式庫 -
math 函式庫:
@@ -735,14 +798,12 @@
呼叫它們的腳本不會如預期運作。
× 透過 require 載入模組,以及 io / dofile 等任意檔案存取
(obj.load 的影像 / 影片載入已附檔頭驗證支援)。
× obj.setanchor、scene.set / scene.get 等。
× obj.setanchor 等。
- 不支援項目·限制事項 -
× 不支援 AviUtl2 的 obj.rand1()、obj.mes()、obj.setanchor() 等。
× 不支援 AviUtl2 scene 表中的 scene.set()、scene.get() 等函式。
(僅支援讀取 scene.width 和 scene.height)
× 不支援腳本進行任意檔案存取(require、dofile、io 等)。
僅 obj.load("image"/"movie") 會載入經檔頭驗證確認為真正媒體的檔案。
× 修改 obj.z 會反映至繪製中(包含在 ReadBack 中),
+11 -5
ファイルの表示
@@ -117,12 +117,16 @@ YukkuriMovieMaker4(YMM4)上で動作する、**Luaスクリプトでオブ
### 4. scene テーブルと ymm4 テーブル
`scene` テーブルにはシーン(プロジェクト)の解像度情報が格納されています。いずれも読み取り専用です。
`scene` テーブルにはシーン(プロジェクト)の解像度情報と、シーン単位で値を共有する関数が格納されています。
| 変数 | 説明 |
| 変数 / 関数 | 説明 |
|---|---|
| `scene.width`, `scene.height` | シーンの横・縦解像度(ピクセル) |
| `scene.cx`, `scene.cy` | シーン解像度の半分(width/2, height/2) |
| `scene.width`, `scene.height` | シーンの横・縦解像度(ピクセル)。読み取り専用です |
| `scene.cx`, `scene.cy` | シーン解像度の半分(width/2, height/2)。読み取り専用です |
| `scene.set(name, value)` | シーン単位の共有領域へ値を保存します。同じシーン内のすべての Lua スクリプトエフェクトから、アイテムやフレームをまたいで参照できます。値は数値・文字列・真偽値のみで、`nil` を渡すと削除されます |
| `scene.get(name)` | `scene.set()` で保存した値を取得します。未設定の名前は `nil` を返します |
自分のスクリプトが書き込んだ値は、同じ実行の中で直後の `scene.get` からそのまま読み取れます。他のアイテムが書き込んだ値は、次のフレームの評価から読み取れます。同じフレームの中では、アイテムがどの順番で評価されても読み取れる値は変わりません。スクリプトがエラーまたはタイムアウトで終了した場合には、その実行の書き込みは反映されません。動画出力を開始すると共有領域は空の状態から始まるため、同じプロジェクトを出力すれば毎回同じ結果になります。名前と文字列の値は UTF-8 換算で 4095 バイトを超える部分が切り捨てられ、1 つのシーンに保存できる名前は 4096 個までです。値はシーンごとに独立しており、YMM4 を終了するまでメモリ上に保持されます。プロジェクトファイルには保存されません。MoonSharp と LuaJIT のどちらのエンジンでも同じ動作をします。
`ymm4` テーブルには YMM4 固有のメタ情報が格納されています。いずれも読み取り専用です。
@@ -217,9 +221,11 @@ AviUtl のアニメーション効果スクリプト(`.anm` 系)のうち、
- **`obj.setanchor(name, count [, option, ...])`**: プレビュー上にドラッグ可能なアンカーポイントを表示し、その座標を `name` の Lua 変数(`pos={x0,y0,x1,y1,…}`、`"xyz"` 指定時は `{x0,y0,z0,…}`)へ格納します。座標はオブジェクトの中心が原点で、ドラッグで調整した値はプロジェクトへ保存されます。最大 32 個で、`"line"` / `"loop"` / `"star"` / `"arm"` の線結びと `"xyz"` の 3D 指定に対応します。設置数を返し、従来エンジン(MoonSharp)と高速ランタイム(LuaJIT)の双方で動作します。`name` に `"track"` を指定するトラックバー連携は未対応です。
- **`obj.effect` の AviUtl/AviUtl2 互換マップ**: `obj.effect("エフェクト名", "パラメータ名", 値, …)` はまず互換マップを参照し、AviUtl/AviUtl2 の名前として宣言したエフェクトを、対応する YMM4 の映像エフェクトとプロパティへ変換して適用します。値の倍率とオフセットの変換まで宣言できます。互換マップに宣言が無い名前は、従来どおり YMM4 のエフェクト名・キーワードでそのまま解決するため、既存の呼び出しはそのまま動きます。この互換マップは YMM4 自身が AviUtl の `.exo` へ書き出す変換を逆向きにたどって構築しているため、往復しても結果が一致します。対象のエンジンは指定子 `--!aviutl` または `--!aviutl2` で切り替え、指定子を書かないときは `--!aviutl` として扱います。互換マップが対応するエフェクト名の一覧はドキュメントの「obj の関数」を参照してください。
- **AviUtl 互換のグローバル関数**: `RGB` / `HSV`(色情報と各要素の相互変換。6 引数指定で時間変化)、`OR` / `AND` / `XOR`(32bit 整数のビット演算)、`SHIFT`(算術シフト)、`debug_print`(`OutputDebugString()` への文字列送信。スクリプトの実行エラーも自動で送信されます)をグローバルスコープで呼び出せます。すべての実行エンジンで同一の結果を返します。
次のような機能は、この互換層では対象外です(呼び出しを含むスクリプトは意図どおりには動作しません)。
- `scene.set` / `scene.get` などの未実装関数
- `obj.mes` / `obj.rand1` などの未実装関数
- `require` によるモジュール読み込み、`io` / `dofile` などの任意ファイルアクセス(`obj.load("image"/"movie")` のみ、先頭ヘッダー検証付きで対応)
---
+14 -4
ファイルの表示
@@ -25,7 +25,7 @@
<tr><th>エンジン</th><th>指定子</th><th>特徴</th></tr>
<tr><td>ネイティブ(LuaJIT)</td><td><code>--!native</code>(既定)</td><td>別プロセスの LuaJIT で実行。ピクセル処理が大幅に高速</td></tr>
<tr><td>MoonSharp</td><td><code>--!moonsharp</code></td><td>Lua 5.2 互換。フォールバック用の従来エンジン</td></tr>
<tr><td>CPU カーネル</td><td><code>--!cpu</code></td><td>決まった形のピクセルループを並列実行に変換。MoonSharp と一致する結果</td></tr>
<tr><td>CPU カーネル</td><td><code>--!cpu</code></td><td>決まった形のピクセルループを並列実行へ変換。SIMD を実測で使い分け、MoonSharp と一致する結果</td></tr>
<tr><td>GPU カーネル</td><td><code>--!gpu</code></td><td>ピクセルループを GPU シェーダーに変換。最速だが float32 精度(明示指定のみ)</td></tr>
</table>
@@ -56,14 +56,17 @@ end</code></pre>
<p>指定子が無いときは、スクリプトの内容から自動でエンジンが選ばれます。</p>
<ul>
<li>後述のカーネル条件に当てはまるピクセルループは、CPU カーネルで実行します。結果は MoonSharp と一致します。</li>
<li>後述のカーネル条件に当てはまるピクセルループは、まず GPU カーネルを試します。初回に実機の GPU で
処理し、CPU カーネルと出力が許容差に収まるか検証します。収まれば以後は GPU カーネル、収まらなければ
CPU カーネルで実行します。CPU カーネルの結果は MoonSharp と一致します。</li>
<li>それ以外のスクリプトは、同梱の LuaJIT ネイティブで実行します。結果は MoonSharp と一致します。</li>
<li><code>native</code> フォルダが配備されていない環境と空のスクリプトは、MoonSharp で実行します。</li>
</ul>
<div class="note">
明示した指定子は自動振り分けより優先されます。
<code>--!gpu</code> は明示したときだけ使われ、自動では選ばれません(精度が float32 のため)。
明示した指定子は自動振り分けより優先されます。GPU カーネルは浮動小数点の 32 ビットで計算するため、
自動で選ぶときは初回の検証に通ったプログラムだけを対象とし、CPU カーネルと食い違うことはありません。
<code>--!gpu</code> を明示したときは検証に通れば GPU、通らなければ CPU カーネルで実行します。
</div>
<h2>カーネルに変換できる形</h2>
@@ -94,6 +97,13 @@ CPU / GPU カーネルは、次の決まった形のスクリプトだけを変
<code>time, frame, totalframe, framerate, timelineframe, timelinetime, layer, color</code></td></tr>
</table>
<div class="note">
CPU カーネルは、4 画素をまとめて計算する SIMD 経路を持ちます。SIMD が有利かどうかは
カーネルの内容と実行環境で変わるため、最初の数フレームでスカラ経路と SIMD 経路の両方を
実行して時間を計り、速かった経路をそのプログラムで使い続けます。どちらの経路でも出力は
同一です。
</div>
<h3>カーネルになるグレースケールの例</h3>
<pre><code>for y = 0, obj.h - 1 do
for x = 0, obj.w - 1 do
+25 -1
ファイルの表示
@@ -65,10 +65,34 @@ local b = bit32.band(color, 0x0000FF)</code></pre>
<tr><th>テーブル</th><th>役割</th><th>参照</th></tr>
<tr><td><code>obj</code></td><td>描画対象の座標・回転・拡大率・不透明度と各種関数</td><td><a href="obj.html">obj</a> / <a href="obj-functions.html">obj の関数</a></td></tr>
<tr><td><code>anim</code></td><td>補間・波・ノイズ・色変換などのアニメーション関数</td><td><a href="anim.html">anim</a></td></tr>
<tr><td><code>scene</code></td><td>シーンの解像度</td><td><a href="scene-ymm4.html">scene</a></td></tr>
<tr><td><code>scene</code></td><td>シーンの解像度と、シーン全体で共有する値</td><td><a href="scene-ymm4.html">scene</a></td></tr>
<tr><td><code>ymm4</code></td><td>グループ・タイムライン・再生状態などの環境情報</td><td><a href="scene-ymm4.html">ymm4</a></td></tr>
</table>
<h2>グローバル関数(AviUtl 互換)</h2>
<p>
以下の関数はグローバルスコープから直接呼び出せます。
MoonSharp とネイティブのどちらのエンジンでも同一の結果を返します。
</p>
<table>
<tr><th>関数</th><th>説明</th></tr>
<tr><td><code>RGB(r, g, b)</code></td><td>RGB 各要素(0 ~ 255)を 1 つの色情報(<code>0xRRGGBB</code>)へ合成</td></tr>
<tr><td><code>RGB(col)</code></td><td>色情報を <code>r, g, b</code> の 3 値へ分解</td></tr>
<tr><td><code>RGB(r1, g1, b1, r2, g2, b2)</code></td><td>オブジェクトの時間経過(<code>obj.time / obj.totaltime</code>)で一色目から二色目へ直線的に変化する色情報を返す</td></tr>
<tr><td><code>HSV(h, s, v)</code> / <code>HSV(col)</code> / <code>HSV(h1, s1, v1, h2, s2, v2)</code></td><td>色相(0 ~ 360)・彩度(0 ~ 100)・明度(0 ~ 100)と色情報の相互変換。引数の意味は <code>RGB()</code> と同様</td></tr>
<tr><td><code>OR(a, b)</code> / <code>AND(a, b)</code> / <code>XOR(a, b)</code></td><td>32bit 整数のビット演算。小数は 0.5 ちょうどまでを切り捨てて整数化(2.50 → 2、2.51 → 3)</td></tr>
<tr><td><code>SHIFT(a, shift)</code></td><td>算術シフト。<code>shift</code> が正で左シフト、負で右シフト</td></tr>
<tr><td><code>debug_print(text)</code></td><td>文字列を <code>OutputDebugString()</code> へ送信。DebugView などで確認できる。スクリプトの実行エラーも自動で送信される</td></tr>
</table>
<pre><code>col = RGB(64, 192, 255) -- 0x40C0FF
r, g, b = RGB(0x0080FF) -- 0, 128, 255
col = HSV(60, 100, 100) -- 0xFFFF00
result = SHIFT(5, 3) -- 40
debug_print(string.format("x = %d", obj.x))</code></pre>
<p>標準ライブラリのテーブルもグローバルに置かれています。</p>
<table>
+3 -2
ファイルの表示
@@ -21,8 +21,9 @@ YukkuriMovieMaker4 の映像エフェクト「Lua スクリプト」の公式ド
<p>
標準のスクリプトエンジンは LuaJIT で実行するネイティブレーンで、
決まった形のピクセル処理は <code>--!cpu</code> の CPU カーネルへ変換されます。
Lua 5.2 互換の MoonSharp はフォールバックとして使われ、明示指定の <code>--!gpu</code> レーンも用意しています。
決まった形のピクセル処理は CPU カーネルや GPU カーネルへ変換されます。
GPU カーネルは初回に CPU カーネルとの一致を検証したうえで自動選択します。
Lua 5.2 互換の MoonSharp はフォールバックとして使われます。
詳しくは<a href="engines.html">エンジンと高速化</a>を参照してください。
</p>
+4 -3
ファイルの表示
@@ -19,7 +19,8 @@
<li>タイムアウト 5 秒: 1 フレームのスクリプト実行が 5 秒を超えると中断され、そのフレームは
元の映像のままになります。無限ループや極端に重い処理に注意してください。</li>
<li>フレーム間で状態は保持されない: 組み込み以外のグローバル変数は毎フレームリセットされます。
前フレームの計算結果を変数に貯めることはできません。時間変化は <code>time</code> や <code>obj.t</code> から計算します。</li>
時間変化は <code>time</code> や <code>obj.t</code> から計算します。フレームやアイテムをまたいで値を
共有したい場合は <a href="scene-ymm4.html"><code>scene.set()</code> / <code>scene.get()</code></a> を使ってください。</li>
<li>ファイルアクセス不可: <code>require</code>・<code>dofile</code>・<code>io</code> などは使えません。</li>
<li>使えない標準ライブラリ: <code>io</code>・<code>os</code>・<code>debug</code>・<code>coroutine</code>・
<code>package</code>・<code>ffi</code> は無効です(<a href="stdlib.html">標準ライブラリ</a>)。</li>
@@ -38,7 +39,6 @@
<h2>非対応の機能</h2>
<ul>
<li><code>scene.set()</code> や <code>scene.get()</code> はありません。<code>scene</code> は解像度の読み取りだけに対応します。</li>
<li><code>obj.setanchor()</code> など、本ドキュメントに記載のない AviUtl 関数は対応していません。</li>
<li><code>obj.effect</code> は、AviUtl/AviUtl2 互換マップに宣言したエフェクト名と、YMM4 に読み込まれている映像エフェクトの名前・キーワードを解決します。
名前が見つからない・適用に失敗した場合は、そのフレームでは元の映像がそのまま使われます。
@@ -59,7 +59,8 @@
<tr><td>スクリプトを書いても見た目が変わらない</td><td>値を <code>obj</code> に代入しているか(グローバル変数に入れても反映されません)。
例: <code>obj.x = ...</code>。読み取り専用メンバーに代入していないか。</td></tr>
<tr><td>トラックバーや色が表示されない</td><td>指定子や使用状況によって表示が決まります。<a href="directives.html">パラメータ指定子</a> の表示条件を確認してください。</td></tr>
<tr><td>前のフレームの値が消える</td><td>仕様です。グローバル変数はフレーム間で保持されません。</td></tr>
<tr><td>前のフレームの値が消える</td><td>仕様です。グローバル変数はフレーム間で保持されません。
持ち越したい値は <code>scene.set()</code> / <code>scene.get()</code> で共有してください。</td></tr>
<tr><td>処理が中断される / フレームが描画されない</td><td>5 秒のタイムアウトに達している可能性があります。ループ回数を減らすか、
ピクセル処理を <a href="engines.html">カーネルやネイティブ</a>に任せられる形にしてください。</td></tr>
<tr><td><code>--!native</code> を指定しても速くならない</td><td>プラグインの隣に <code>native</code> フォルダが配置されていないと MoonSharp で実行されます。
+8 -6
ファイルの表示
@@ -116,17 +116,19 @@ A チャンネル(インデックス <code>base + 4</code>)を変更する
<h2>putpixeldata について</h2>
<p>
<code>obj.putpixeldata()</code> は AviUtl との互換のために存在しますが、このプラグインでは
変更が自動的に反映されるため、呼び出す必要はありません(何もしません)。
<code>obj.putpixeldata()</code> は AviUtl との互換のために存在します。このプラグインでは、
次の読み出しやスクリプトの終わりで変更が自動的に反映されるため、呼び出す必要はありません。
呼び出したときは、その時点で未反映の変更をまとめて反映します。
</p>
<h2>性能とエンジン</h2>
<p>
ピクセル処理は重くなりがちです。このプラグインは <code>getpixel</code> / <code>setpixel</code> を含むスクリプトを
自動的に高速なネイティブレーンへ振り分けます(利用できる場合)。さらに、二重ループで
<code>getpixel</code> → 計算 → <code>setpixel</code> という決まった形のスクリプトは、CPU カーネルへ
変換されてさらに高速に実行できます。<code>--!gpu</code> を明示すると GPU カーネルも使えます。詳しくは <a href="engines.html">エンジンと高速化</a> を参照してください。
ピクセル処理は重くなりがちです。このプラグインは <code>getpixel</code> / <code>setpixel</code> を含むスクリプトを、
利用できる環境では自動的に高速なネイティブレーンへ振り分けます。さらに、二重ループで
<code>getpixel</code> → 計算 → <code>setpixel</code> という決まった形のスクリプトは、CPU カーネルや GPU カーネルへ
変換してさらに高速に実行します。GPU カーネルは初回に CPU カーネルとの一致を検証したうえで自動選択します。
詳しくは <a href="engines.html">エンジンと高速化</a> を参照してください。
</p>
<div class="pager">
+12
ファイルの表示
@@ -30,6 +30,16 @@
<tr><td><code>math</code> / <code>string</code> / <code>table</code> / <code>bit32</code></td><td>標準ライブラリ</td></tr>
</table>
<h2>グローバル関数(AviUtl 互換)</h2>
<table>
<tr><th>関数</th><th>説明</th></tr>
<tr><td><code>RGB(r, g, b)</code> / <code>RGB(col)</code> / <code>RGB(r1, g1, b1, r2, g2, b2)</code></td><td>色情報と RGB 各要素の相互変換(6 引数は時間変化)</td></tr>
<tr><td><code>HSV(h, s, v)</code> / <code>HSV(col)</code> / <code>HSV(h1, s1, v1, h2, s2, v2)</code></td><td>色情報と HSV 各要素の相互変換(6 引数は時間変化)</td></tr>
<tr><td><code>OR(a, b)</code> / <code>AND(a, b)</code> / <code>XOR(a, b)</code></td><td>32bit 整数のビット演算</td></tr>
<tr><td><code>SHIFT(a, shift)</code></td><td>算術シフト(正で左、負で右)</td></tr>
<tr><td><code>debug_print(text)</code></td><td>OutputDebugString() へ文字列を送信</td></tr>
</table>
<h2>obj(変更可能)</h2>
<table>
<tr><th>メンバー</th><th>説明</th></tr>
@@ -108,6 +118,8 @@
<tr><th>メンバー</th><th>説明</th></tr>
<tr><td><code>scene.width</code> / <code>scene.height</code></td><td>シーンの解像度</td></tr>
<tr><td><code>scene.cx</code> / <code>scene.cy</code></td><td>解像度の半分</td></tr>
<tr><td><code>scene.set(name, value)</code></td><td>シーン全体で共有する値を保存します。nil を渡すと削除します</td></tr>
<tr><td><code>scene.get(name)</code></td><td>共有された値を取得します。未設定の名前は nil を返します</td></tr>
</table>
<h2>ymm4</h2>
+43 -7
ファイルの表示
@@ -14,8 +14,8 @@
<h1>scene と ymm4</h1>
<p>
<code>scene</code> はシーンの解像度を、<code>ymm4</code> はグループ・タイムライン・再生状態などの
環境情報を提供します。どちらも読み取り専用です。
<code>scene</code> はシーンの解像度とシーン単位の共有値を、<code>ymm4</code> はグループ・タイムライン・再生状態などの
環境情報を提供します。
</p>
<h2>scene — シーン情報</h2>
@@ -26,16 +26,52 @@
<tr><td><code>scene.height</code></td><td>シーンの縦解像度(ピクセル)</td></tr>
<tr><td><code>scene.cx</code></td><td>横解像度の半分(<code>scene.width / 2</code>)</td></tr>
<tr><td><code>scene.cy</code></td><td>縦解像度の半分(<code>scene.height / 2</code>)</td></tr>
<tr><td><code>scene.set(name, value)</code></td><td>シーン全体で共有する値を保存します</td></tr>
<tr><td><code>scene.get(name)</code></td><td><code>scene.set()</code> で保存した値を取得します</td></tr>
</table>
<div class="note">
このプラグインで使える <code>scene</code> は解像度の読み取りのみです。
AviUtl の <code>scene.set()</code> / <code>scene.get()</code> のような機能はありません。
</div>
<h3>シーンサイズに対する相対配置</h3>
<pre><code>obj.x = scene.cx * obj.track0 / 100</code></pre>
<h2>scene.set / scene.get — シーン内の値共有</h2>
<p>
<code>scene.set(name, value)</code> は、シーンごとに用意された共有領域へ値を保存します。
保存した値は、同じシーンに置かれたすべての Lua スクリプトエフェクトから
<code>scene.get(name)</code> で読み取れます。どちらの実行エンジンでも同じ動作をします。
</p>
<table>
<tr><th>引数</th><th>説明</th></tr>
<tr><td><code>name</code></td><td>値の名前を文字列で指定します</td></tr>
<tr><td><code>value</code></td><td>保存する値を指定します。数値と文字列と真偽値を保存できます。<code>nil</code> を渡すと値を削除します</td></tr>
</table>
<pre><code>-- アイテムA: 自分の座標を共有する
scene.set("leader_x", obj.x)
-- アイテムB: 共有された座標へ追従する
obj.x = scene.get("leader_x") or 0</code></pre>
<h3>値が見えるタイミング</h3>
<ul>
<li>自分のスクリプトが書き込んだ値は、同じ実行の中で直後の <code>scene.get</code> からそのまま読み取れます。</li>
<li>他のアイテムが書き込んだ値は、次のフレームの評価から読み取れます。同じフレームの中では、アイテムがどの順番で評価されても読み取れる値は変わりません。</li>
<li>スクリプトがエラーまたはタイムアウトで終了した場合には、その実行の書き込みは共有領域へ反映されません。</li>
<li>動画出力を開始すると、共有領域は空の状態から始まります。そのため、同じプロジェクトを出力すれば毎回同じ結果になります。</li>
</ul>
<h3>制限</h3>
<ul>
<li>保存できる値は数値と文字列と真偽値だけです。テーブルや関数を渡した呼び出しは無視されます。</li>
<li>名前と文字列の値は、UTF-8 で 4095 バイトを超える部分が切り捨てられます。</li>
<li>1 つのシーンに保存できる名前は 4096 個までです。上限を超えた新しい名前への書き込みは無視されます。</li>
<li>同じフレームの中で複数のアイテムが同じ名前へ書き込んだ場合には、どちらの値が残るかは保証されません。</li>
<li>値は YMM4 を終了するまでメモリ上に保持されます。プロジェクトファイルには保存されません。</li>
</ul>
<h2>ymm4 — 環境・メタ情報</h2>
<table>
+188
ファイルの表示
@@ -327,6 +327,194 @@ function aviutl_rand(a, b, seed, frame)
return v
end
ffi.cdef [[
int MultiByteToWideChar(unsigned int cp, unsigned long flags, const char* src, int srclen, wchar_t* dst, int dstlen);
void OutputDebugStringW(const wchar_t* text);
]]
local CP_UTF8 = 65001
local debugBuffer = ffi.new("wchar_t[?]", 256)
local debugCapacity = 256
function debug_print(text)
local s = tostring(text)
local wide = 0
if #s > 0 then
wide = ffi.C.MultiByteToWideChar(CP_UTF8, 0, s, #s, nil, 0)
if wide <= 0 then return end
end
if wide + 1 > debugCapacity then
debugCapacity = wide + 1
debugBuffer = ffi.new("wchar_t[?]", debugCapacity)
end
if wide > 0 then
ffi.C.MultiByteToWideChar(CP_UTF8, 0, s, #s, debugBuffer, wide)
end
debugBuffer[wide] = 0
ffi.C.OutputDebugStringW(debugBuffer)
end
local ceil = math.ceil
local function tobitop(v)
v = tonumber(v) or 0
if v ~= v then return 0 end
if v <= -2147483648 then return -2147483648 end
if v >= 2147483647 then return 2147483647 end
return ceil(v - 0.5)
end
function OR(a, b) return bit.bor(tobitop(a), tobitop(b)) end
function AND(a, b) return bit.band(tobitop(a), tobitop(b)) end
function XOR(a, b) return bit.bxor(tobitop(a), tobitop(b)) end
function SHIFT(a, shift)
local v = tobitop(a)
local n = tobitop(shift)
if n >= 0 then return bit.lshift(v, n) end
return bit.arshift(v, -n)
end
local function tocolorchannel(v)
if v ~= v or v <= 0 then return 0 end
if v >= 255 then return 255 end
return floor(v)
end
local function tocolor(v)
v = tonumber(v) or 0
if v ~= v then return 0 end
if v <= -2147483648 then
v = -2147483648
elseif v >= 2147483647 then
v = 2147483647
end
return floor(v) % 0x1000000
end
local function wraphue(h)
if h ~= h or h == math.huge or h == -math.huge then return 0 end
local wrapped = h - floor(h / 360) * 360
if wrapped >= 360 then return 0 end
return wrapped
end
local function clampratio(v)
if v ~= v or v <= 0 then return 0 end
if v >= 100 then return 1 end
return v / 100
end
local function roundhalfup(v)
return floor(v + 0.5)
end
local function rgbcompose(r, g, b)
r = tonumber(r) or 0
g = tonumber(g) or 0
b = tonumber(b) or 0
return tocolorchannel(r) * 0x10000 + tocolorchannel(g) * 0x100 + tocolorchannel(b)
end
local function hsvcompose(h, s, v)
h = wraphue(tonumber(h) or 0)
s = clampratio(tonumber(s) or 0)
v = clampratio(tonumber(v) or 0)
local c = v * s
local x = c * (1 - abs(fmod(h / 60, 2) - 1))
local m = v - c
local sector = floor(h / 60)
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 tocolorchannel(roundhalfup((r + m) * 255)) * 0x10000 +
tocolorchannel(roundhalfup((g + m) * 255)) * 0x100 +
tocolorchannel(roundhalfup((b + m) * 255))
end
local timeRatio = 0
function aviutl_set_time_ratio(t)
t = tonumber(t) or 0
if t ~= t then t = 0 end
timeRatio = t
end
function RGB(...)
local n = select("#", ...)
if n >= 6 then
local r1, g1, b1, r2, g2, b2 = ...
r1 = tonumber(r1) or 0
g1 = tonumber(g1) or 0
b1 = tonumber(b1) or 0
r2 = tonumber(r2) or 0
g2 = tonumber(g2) or 0
b2 = tonumber(b2) or 0
local t = timeRatio
return rgbcompose(r1 + (r2 - r1) * t, g1 + (g2 - g1) * t, b1 + (b2 - b1) * t)
end
if n >= 3 then
return rgbcompose(...)
end
if n >= 1 then
local c = tocolor((...))
return floor(c / 0x10000) % 0x100, floor(c / 0x100) % 0x100, c % 0x100
end
return nil
end
function HSV(...)
local n = select("#", ...)
if n >= 6 then
local h1, s1, v1, h2, s2, v2 = ...
h1 = tonumber(h1) or 0
s1 = tonumber(s1) or 0
v1 = tonumber(v1) or 0
h2 = tonumber(h2) or 0
s2 = tonumber(s2) or 0
v2 = tonumber(v2) or 0
local t = timeRatio
return hsvcompose(h1 + (h2 - h1) * t, s1 + (s2 - s1) * t, v1 + (v2 - v1) * t)
end
if n >= 3 then
return hsvcompose(...)
end
if n >= 1 then
local c = tocolor((...))
local r = floor(c / 0x10000) % 0x100
local g = floor(c / 0x100) % 0x100
local b = c % 0x100
local rf = r / 255
local gf = g / 255
local bf = b / 255
local max = math.max(rf, gf, bf)
local min = math.min(rf, gf, bf)
local delta = max - min
local hue = 0
if delta > 0 then
if max == rf then
hue = 60 * (fmod(fmod((gf - bf) / delta, 6) + 6, 6))
elseif max == gf then
hue = 60 * ((bf - rf) / delta + 2)
else
hue = 60 * ((rf - gf) / delta + 4)
end
end
local sat = max > 0 and delta / max * 100 or 0
return roundhalfup(hue), roundhalfup(sat), roundhalfup(max * 100)
end
return nil
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)
+243 -80
ファイルの表示
@@ -51,13 +51,19 @@ local OFF_CB_KIND = 11
local OFF_LOAD_RESULT_W = 12
local OFF_LOAD_RESULT_H = 13
local OFF_STRING_PARAMS_LEN = 14
local OFF_SCRIPT_VERSION = 15
local SCRIPT_OFFSET = 64 + 64 * 8
local ERROR_OFFSET = SCRIPT_OFFSET + 128 * 1024
local CB_TAG_OFFSET = ERROR_OFFSET + 4 * 1024
local CB_TAG_MAX = 4096
local CB_TAG_MAX = 8192
local CB_RESULT_OFFSET = CB_TAG_OFFSET + CB_TAG_MAX
local STRING_PARAMS_OFFSET = CB_RESULT_OFFSET + 8 * 8
local PIXEL_OFFSET = STRING_PARAMS_OFFSET + stringParamsCap
local DRAW_RING_CAPACITY = 4096
local DRAW_ENTRY_DOUBLES = 24
local DRAW_RING_DOUBLES = 1 + DRAW_RING_CAPACITY * DRAW_ENTRY_DOUBLES
local DRAW_RING_BYTES = DRAW_RING_DOUBLES * 8
local DRAW_RING_OFFSET = STRING_PARAMS_OFFSET + stringParamsCap
local PIXEL_OFFSET = DRAW_RING_OFFSET + DRAW_RING_BYTES
local FIRST_WRITABLE = 8
local LAST_WRITABLE = 25
local STATUS_CALLBACK = 3
@@ -71,6 +77,9 @@ local CB_KIND_LOADIMAGE = 6
local CB_KIND_LOADMOVIE = 7
local CB_KIND_SETANCHOR = 8
local CB_KIND_REQUESTPIXELS = 9
local CB_KIND_FLUSHDRAWS = 10
local CB_KIND_SCENEGET = 11
local CB_KIND_SCENESET = 12
assert(loadfile(shimPath))()
@@ -82,6 +91,7 @@ end
local width, height = 0, 0
local pixels = ffi.cast("uint8_t*", base + PIXEL_OFFSET)
local ringD = ffi.cast("double*", base + DRAW_RING_OFFSET)
local cbResult = ffi.cast("double*", base + CB_RESULT_OFFSET)
local cbTagD = ffi.cast("double*", base + CB_TAG_OFFSET)
local pixelCapacity = mapSize - PIXEL_OFFSET
@@ -91,6 +101,7 @@ local pixeloptions = {}
local dirty = false
local pixelsValid = false
local drawTarget = "frame"
local pdData, pdCapacity, pdValid, pdDirty = nil, 0, false, false
local function ensurePixels()
if pixelsValid then return end
@@ -101,6 +112,65 @@ local function ensurePixels()
pixelsValid = true
end
local function flushDraws()
i32[OFF_CB_KIND] = CB_KIND_FLUSHDRAWS
i32[OFF_STATUS] = STATUS_CALLBACK
k32.SetEvent(doneEvent)
k32.WaitForSingleObject(workEvent, INFINITE)
end
local function ringSlot(kind)
local n = ringD[0]
if n >= DRAW_RING_CAPACITY then
flushDraws()
n = 0
end
local eb = 1 + n * DRAW_ENTRY_DOUBLES
ringD[eb] = kind
ringD[0] = n + 1
return eb
end
local function rebuildPixelData()
local count = width * height * 4
if not pdData or pdCapacity < count then
pdData = ffi.new("double[?]", count)
pdCapacity = count
end
for pi = 0, width * height - 1 do
local p = pixels + pi * 4
local di = pi * 4
local a = p[3]
pdData[di + 3] = a
if a <= 0 then
pdData[di] = 0; pdData[di + 1] = 0; pdData[di + 2] = 0
else
local s = 255 / a
pdData[di] = clamp(p[2] * s, 0, 255)
pdData[di + 1] = clamp(p[1] * s, 0, 255)
pdData[di + 2] = clamp(p[0] * s, 0, 255)
end
end
pdValid = true
pdDirty = false
end
local function flushPixelData()
if not pdDirty then return end
for pi = 0, width * height - 1 do
local di = pi * 4
local a = math.floor(clamp(pdData[di + 3], 0, 255))
local aK = a / 255
local p = pixels + pi * 4
p[0] = math.floor(clamp(pdData[di + 2] * aK, 0, 255))
p[1] = math.floor(clamp(pdData[di + 1] * aK, 0, 255))
p[2] = math.floor(clamp(pdData[di] * aK, 0, 255))
p[3] = a
end
dirty = true
pdDirty = false
end
local function sampleSource(src, srcW, srcH, u, v, linear)
if not linear then
local su = clamp(math.floor(u), 0, srcW - 1)
@@ -245,6 +315,7 @@ 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
ensurePixels()
flushPixelData()
local p = pixels + (y * width + x) * 4
local a = p[3]
if a <= 0 then return 0, 0, 0, 0 end
@@ -256,6 +327,7 @@ 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
ensurePixels()
flushPixelData()
a = a or 255
dirty = true
local aK = clamp(a, 0, 255) / 255
@@ -264,58 +336,30 @@ function obj.setpixel(x, y, r, g, b, a)
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))
pdValid = false
end
function obj.getpixeldata()
ensurePixels()
if not pdValid then rebuildPixelData() end
local data = pdData
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)
return data[zb]
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
data[zb] = clamp(value, 0, 255)
pdDirty = true
end
return pd
end
function obj.putpixeldata() end
function obj.putpixeldata() flushPixelData() end
function obj.rand(a, b, seed, frame)
return aviutl_rand(a or 0, b or 0, seed or 0, frame or obj.frame or 0)
@@ -324,14 +368,22 @@ end
local font = { family = "", size = 34, bold = false, italic = false, color = 0xFFFFFF }
function obj.setfont(name, size, style, col1)
if name ~= nil then font.family = tostring(name) end
if size ~= nil then font.size = size end
if style ~= nil then
local s = math.floor(style)
font.bold = (s % 2) == 1
font.italic = (math.floor(s / 2) % 2) == 1
local nameType = type(name)
if nameType == "string" then
font.family = name
elseif nameType == "number" then
font.family = tostring(name)
end
if col1 ~= nil then font.color = col1 end
local sizeNumber = tonumber(size)
if sizeNumber ~= nil then font.size = sizeNumber end
local styleNumber = tonumber(style)
if styleNumber ~= nil then
local flags = math.floor(styleNumber)
font.bold = (flags % 2) == 1
font.italic = (math.floor(flags / 2) % 2) == 1
end
local colorNumber = tonumber(col1)
if colorNumber ~= nil then font.color = colorNumber end
end
local function applyLoadResult()
@@ -344,6 +396,8 @@ local function applyLoadResult()
i32[OFF_HEIGHT] = newH
dirty = true
pixelsValid = true
pdValid = false
pdDirty = false
obj.w = newW; obj.h = newH
obj.hw = newW / 2; obj.hh = newH / 2
obj.cx = newW / 2; obj.cy = newH / 2
@@ -463,23 +517,21 @@ end
function obj.draw(ox, oy, oz, zoom, alpha, aspect)
if drawTarget == "temp" then
ensurePixels()
flushPixelData()
local t = ensureTemp()
compositeDrawInto(t.data, t.w, t.h, pixels, width, height,
ox or 0, oy or 0, zoom or 1, aspect or 0, alpha or 1, (options.antialias or 1) ~= 0)
return
end
cbResult[0] = ox or 0
cbResult[1] = oy or 0
cbResult[2] = oz or 0
cbResult[3] = zoom or 1
cbResult[4] = alpha or 1
cbResult[5] = aspect or 0
cbResult[6] = options.antialias or 1
cbResult[7] = options.blend or 0
i32[OFF_CB_KIND] = CB_KIND_DRAW
i32[OFF_STATUS] = STATUS_CALLBACK
k32.SetEvent(doneEvent)
k32.WaitForSingleObject(workEvent, INFINITE)
local eb = ringSlot(CB_KIND_DRAW)
ringD[eb + 1] = ox or 0
ringD[eb + 2] = oy or 0
ringD[eb + 3] = oz or 0
ringD[eb + 4] = zoom or 1
ringD[eb + 5] = alpha or 1
ringD[eb + 6] = aspect or 0
ringD[eb + 7] = options.antialias or 1
ringD[eb + 8] = options.blend or 0
end
function obj.drawpoly(...)
@@ -505,17 +557,15 @@ function obj.drawpoly(...)
p[20] = alpha
if drawTarget == "temp" then
ensurePixels()
flushPixelData()
local t = ensureTemp()
compositeDrawPolyInto(t.data, t.w, t.h, pixels, width, height, p, alpha, (options.antialias or 1) ~= 0)
return
end
for i = 0, 20 do cbTagD[i] = p[i] end
cbTagD[21] = options.antialias or 1
cbTagD[22] = options.blend or 0
i32[OFF_CB_KIND] = CB_KIND_DRAWPOLY
i32[OFF_STATUS] = STATUS_CALLBACK
k32.SetEvent(doneEvent)
k32.WaitForSingleObject(workEvent, INFINITE)
local eb = ringSlot(CB_KIND_DRAWPOLY)
for i = 0, 20 do ringD[eb + 1 + i] = p[i] end
ringD[eb + 22] = options.antialias or 1
ringD[eb + 23] = options.blend or 0
end
function obj.getvalue(target)
@@ -602,6 +652,7 @@ function obj.copybuffer(dst, src)
local data, w, h
if sk == "o" then
ensurePixels()
flushPixelData()
data = pixels
w = width; h = height
elseif sk == "t" or sk == "c" then
@@ -620,6 +671,8 @@ function obj.copybuffer(dst, src)
i32[OFF_WIDTH] = w; i32[OFF_HEIGHT] = h
dirty = true
pixelsValid = true
pdValid = false
pdDirty = false
obj.w = w; obj.h = h
obj.hw = w / 2; obj.hh = h / 2
obj.cx = w / 2; obj.cy = h / 2
@@ -633,6 +686,99 @@ function obj.copybuffer(dst, src)
end
end
local SCENE_VALUE_MAX = 4095
local SCENE_NIL = {}
local sceneReads = {}
local sceneWrites = {}
local function sceneCut(s, max)
if #s <= max then return s end
local len = max
while len > 0 do
local b = string.byte(s, len + 1)
if b < 0x80 or b >= 0xC0 then break end
len = len - 1
end
return string.sub(s, 1, len)
end
function scene.get(name)
if type(name) ~= "string" then return nil end
name = sceneCut(name, SCENE_VALUE_MAX)
local written = sceneWrites[name]
if written ~= nil then
if written == SCENE_NIL then return nil end
return written
end
local cached = sceneReads[name]
if cached ~= nil then
if cached == SCENE_NIL then return nil end
return cached
end
local len = #name
ffi.copy(base + CB_TAG_OFFSET, name, len)
i32[OFF_CB_TAGLEN] = len
i32[OFF_CB_KIND] = CB_KIND_SCENEGET
i32[OFF_STATUS] = STATUS_CALLBACK
k32.SetEvent(doneEvent)
k32.WaitForSingleObject(workEvent, INFINITE)
local kind = cbResult[0]
local value
if kind == 1 then
value = cbResult[1]
elseif kind == 2 then
value = ffi.string(base + CB_TAG_OFFSET, i32[OFF_CB_TAGLEN])
elseif kind == 3 then
value = cbResult[1] ~= 0
end
if value == nil then
sceneReads[name] = SCENE_NIL
else
sceneReads[name] = value
end
return value
end
function scene.set(name, value)
if type(name) ~= "string" then return end
name = sceneCut(name, SCENE_VALUE_MAX)
local vt = type(value)
local kind, num
if vt == "number" then
kind, num = 1, value
elseif vt == "string" then
kind, num = 2, 0
value = sceneCut(value, SCENE_VALUE_MAX)
elseif vt == "boolean" then
kind, num = 3, value and 1 or 0
elseif vt == "nil" then
kind, num = 0, 0
else
return
end
if value == nil then
sceneWrites[name] = SCENE_NIL
else
sceneWrites[name] = value
end
local len = #name
ffi.copy(base + CB_TAG_OFFSET, name, len)
if kind == 2 then
base[CB_TAG_OFFSET + len] = 0
local vlen = #value
if vlen > 0 then ffi.copy(base + CB_TAG_OFFSET + len + 1, value, vlen) end
i32[OFF_CB_TAGLEN] = len + 1 + vlen
else
i32[OFF_CB_TAGLEN] = len
end
cbResult[0] = kind
cbResult[1] = num
i32[OFF_CB_KIND] = CB_KIND_SCENESET
i32[OFF_STATUS] = STATUS_CALLBACK
k32.SetEvent(doneEvent)
k32.WaitForSingleObject(workEvent, INFINITE)
end
local cacheTag, cacheFrame, cacheFound
local cacheExist, cacheX, cacheY, cacheZ, cacheZoom, cacheRz, cacheAlpha, cacheLayer
@@ -679,6 +825,8 @@ end
sandbox = {
obj = obj, scene = scene, ymm4 = ymm4,
anim = anim, bit32 = bit32, rawlen = rawlen,
RGB = RGB, HSV = HSV, OR = OR, AND = AND, XOR = XOR, SHIFT = SHIFT,
debug_print = debug_print,
math = math, string = string, table = table,
type = type, tostring = tostring, tonumber = tonumber, select = select,
error = error, assert = assert, ipairs = ipairs, pairs = pairs, next = next,
@@ -705,7 +853,8 @@ local objKeys = captureKeys(obj)
local sceneKeys = captureKeys(scene)
local ymm4Keys = captureKeys(ymm4)
local compiledCode, compiledChunk
local compiledCode, compiledChunk, compiledError
local lastScriptVersion
local function loadFields()
width = i32[OFF_WIDTH]
@@ -731,6 +880,7 @@ local function loadFields()
obj.timelineframe = f64[51]; obj.timelinetime = f64[52]
obj.check0 = f64[53] ~= 0; obj.check1 = f64[54] ~= 0; obj.check2 = f64[55] ~= 0; obj.check3 = f64[56] ~= 0
sandbox.color = (f64[57] >= 0) and f64[57] or nil
aviutl_set_time_ratio(f64[33] > 0 and f64[30] / f64[33] or 0)
sandbox.time = f64[30]; sandbox.frame = f64[31]; sandbox.totalframe = f64[32]
sandbox.framerate = f64[35]; sandbox.layer = f64[36]
sandbox.timelineframe = f64[51]; sandbox.timelinetime = f64[52]
@@ -769,25 +919,35 @@ while true do
dirty = false
pixelsValid = 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)
pdValid = false
pdDirty = false
ringD[0] = 0
local version = i32[OFF_SCRIPT_VERSION]
if version ~= lastScriptVersion then
lastScriptVersion = version
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
compiledError = nil
else
compiledChunk = nil
compiledCode = code
compiledError = err or "compile error"
end
end
end
if compiledChunk and code == compiledCode then
if not compiledChunk then
local msg = compiledError 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)
else
resetExtraKeys(sandbox, sandboxKeys)
resetExtraKeys(obj, objKeys)
resetExtraKeys(scene, sceneKeys)
@@ -797,12 +957,15 @@ while true do
cacheTag = nil
for k in pairs(options) do options[k] = nil end
for k in pairs(pixeloptions) do pixeloptions[k] = nil end
for k in pairs(sceneReads) do sceneReads[k] = nil end
for k in pairs(sceneWrites) do sceneWrites[k] = nil end
drawTarget = "frame"
font.family = ""; font.size = 34; font.bold = false; font.italic = false; font.color = 0xFFFFFF
math.randomseed(f64[31])
setfenv(compiledChunk, sandbox)
local ok, err = pcall(compiledChunk)
if ok then
flushPixelData()
storeFields()
local ds = options.draw_state
if ds == nil then f64[62] = 0 elseif ds == false or ds == 0 then f64[62] = 2 else f64[62] = 1 end