コミットを比較

...
78 コミット
作成者 SHA1 メッセージ 日付
routersys c8350161db バージョンをv1.7.0へ更新
リリース / build-and-release (workflow_dispatch) Actions がタグ v1.7.0 のコミットから作成しました
2026-06-28 14:35:28 +09:00
routersys 679cab03b5 LuaScriptEffectProcessorにobj.effectチェーン適用を統合し、失敗時は元画像へフォールバック 2026-06-28 14:35:14 +09:00
routersys 6783146231 YMM4映像エフェクトを名前/別名で解決し適用するVideoEffectChainを追加 2026-06-28 14:35:08 +09:00
routersys df303ee154 LuaScriptEngineにobj.effectコールバックを追加し要求を記録 2026-06-28 14:34:57 +09:00
routersys f49bd740a0 AviUtlScriptContextにobj.effect要求の記録/クリアを追加 2026-06-28 14:34:50 +09:00
routersys 80d1b75227 obj.effectの要求を表すAviUtlEffectRequest型を追加 2026-06-28 14:34:42 +09:00
routersys d7f981c38a バージョンをv1.6.0へ更新
リリース / build-and-release (workflow_dispatch) Actions がタグ v1.6.0 のコミットから作成しました
2026-06-28 10:49:58 +09:00
routersys df0c63a270 --check/--colorが展開されないことを検証するテストへ更新 2026-06-28 10:43:26 +09:00
routersys 7766b116dc AviUtlParameterLayoutの解析テストを追加 2026-06-28 10:43:21 +09:00
routersys eb8f4e8055 トラック値のディレクティブ範囲クランプとcheck/color反映を追加 2026-06-28 10:43:03 +09:00
routersys 04563a7242 --track/--check/--colorに応じた動的UIをLuaScriptEffectに実装 2026-06-28 10:42:57 +09:00
routersys 875d954520 --check/--colorの擬似展開を廃止しUI値を唯一のソースに変更 2026-06-28 10:42:48 +09:00
routersys bd7f2ae691 ネイティブ(LuaJIT)実行へcheck0〜3/colorフィールドを配線 2026-06-28 10:42:32 +09:00
routersys 36b3c880fe obj.check0〜3とcolorをスクリプトへ引き渡す処理を追加 2026-06-28 10:42:12 +09:00
routersys 230e6f010c チェック/色の動的パラメータ用ラベルを多言語リソースへ追加 2026-06-28 10:41:50 +09:00
routersys ef16ae64fb AviUtlヘッダ(--track/--check/--color)の解析クラスを追加 2026-06-28 10:41:37 +09:00
routersys 0204d480e2 バージョンをv1.5.0へ更新
リリース / build-and-release (workflow_dispatch) Actions がタグ v1.5.0 のコミットから作成しました
2026-06-28 02:27:37 +09:00
routersys 7e1f2c1d7c obj.load("figure")による図形描画を各ドキュメントへ追記 2026-06-28 02:27:17 +09:00
routersys bab81d27e5 obj.load("figure")による図形描画を実装 2026-06-28 02:15:44 +09:00
routersys a3efd55ce6 SDFベースの図形ラスタライザを追加 2026-06-28 02:14:07 +09:00
routersys 4f2389702a バージョンをv1.4.0へ更新
リリース / build-and-release (workflow_dispatch) Actions がタグ v1.4.0 のコミットから作成しました
2026-06-28 01:29:44 +09:00
routersys 247bb83230 AviUtl部分互換とobj.randを全ドキュメントへ追記 2026-06-28 01:28:32 +09:00
routersys 1d495039f0 AviUtlスクリプトのヘッダ・セクションを解釈する前処理層を追加 2026-06-28 01:28:15 +09:00
routersys 56d7937be1 AviUtlスクリプトのヘッダ・セクションを解釈する前処理層を追加 2026-06-28 01:27:31 +09:00
routersys cade7e8a8f バージョンをv1.3.4へ更新
リリース / build-and-release (workflow_dispatch) Actions がタグ v1.3.4 のコミットから作成しました
2026-06-27 19:51:21 +09:00
routersys 9e8e024db9 obj.getobjectのキャッシュ動作をREADMEに追記 2026-06-27 19:50:41 +09:00
routersys 69881878e4 obj.getobjectの同一タグ・同一フレーム問い合わせをキャッシュし往復を削減 2026-06-27 19:50:28 +09:00
routersys 42e0b2b0f7 バージョンをv1.3.3へ更新
リリース / build-and-release (workflow_dispatch) Actions がタグ v1.3.3 のコミットから作成しました
2026-06-27 17:56:46 +09:00
routersys 954b1bfc49 READMEからgetobjectのネイティブ制約の記載を削除 2026-06-27 17:56:40 +09:00
routersys 41defa1059 getobjectをネイティブ実行でも利用可能にした 2026-06-27 17:55:47 +09:00
routersys 876f05d277 バージョンをv1.3.2へ更新
リリース / build-and-release (workflow_dispatch) Actions がタグ v1.3.2 のコミットから作成しました
2026-06-27 17:31:39 +09:00
routersys 227af2c75c READMEにLuaJIT等のサードパーティ表記を追記 2026-06-27 17:26:53 +09:00
routersys 5cbd5ae8ff 同梱ライブラリのライセンスを追加しリリースに同梱 2026-06-27 17:26:50 +09:00
routersys bb97610454 luajitの残留プロセスをジョブで道連れ終了 2026-06-27 17:26:37 +09:00
routersys 968180c459 バージョンをv1.3.1へ更新
リリース / build-and-release (workflow_dispatch) Actions がタグ v1.3.1 のコミットから作成しました
2026-06-27 13:10:59 +09:00
routersys d9ad3692f2 プラグイン情報を追加 2026-06-27 13:06:29 +09:00
routersys 573234d727 nativeをリリースに同梱
リリース / build-and-release (workflow_dispatch) Actions がタグ v1.3.0 のコミットから作成しました
2026-06-27 12:59:28 +09:00
routersys 69a5f26260 テスト専用luaを配布から除外し必要な4ファイルのみ同梱 2026-06-27 12:40:33 +09:00
routersys ed4601a03a 実行エンジンの自動振り分け・高速化・制約をREADMEに追記 2026-06-27 12:34:49 +09:00
routersys 960569177c v1.3.0のリリースノートを記載 2026-06-27 12:34:48 +09:00
routersys 2831ea25ee バージョンを1.3.0へ更新 2026-06-27 12:34:48 +09:00
routersys a2caa2e910 ネイティブ実行でmath.randomseed(frame)を毎フレーム適用し決定論を維持 2026-06-27 12:34:47 +09:00
routersys 26bc21681f オートルーティングのテストを追加 2026-06-27 12:23:09 +09:00
routersys 7edbe189a2 getpixeldata往復テストを追加 2026-06-27 12:23:08 +09:00
routersys e8ae7d1189 自動振り分けを採用しネイティブ未配備時は一度だけ警告(サイレントフォールバック解消) 2026-06-27 12:23:08 +09:00
routersys ce7007c42e ピクセルAPI使用スクリプトをネイティブへ自動振り分け(ResolveAuto) 2026-06-27 12:23:07 +09:00
routersys f10f31ef2b ワーカーにgetpixeldata(PixelDataProxy相当)を実装 2026-06-27 12:23:07 +09:00
routersys 4a5043eb3a テストプロジェクトの参照を追加 2026-06-27 10:07:47 +09:00
routersys 640c9f5347 ネイティブワーカー往復テスト(変形/ピクセル/タイムアウト/エラー)を追加 2026-06-27 09:57:19 +09:00
routersys b339d60bd7 vendored nativeをリポジトリ直下へ集約し両プロジェクトから参照 2026-06-27 09:57:18 +09:00
routersys f94e0ea849 nativeランタイムをプラグイン出力へ同梱・配備(csproj) 2026-06-27 09:56:57 +09:00
routersys 729ba355d9 --!nativeをLuaJITワーカーへ振り分けるよう配線 2026-06-27 09:56:56 +09:00
routersys 67697930b7 常駐ワーカースクリプト(obj/scene/ymm4/pixel,サンドボックス)を追加 2026-06-27 09:56:56 +09:00
routersys f929c1a83a コンテキスト⇄ネイティブフィールド配列の写像を追加 2026-06-27 09:56:56 +09:00
routersys 6ee2784d6a 常駐LuaJITワーカー管理(別プロセス/共有メモリ/ハードキル)を追加 2026-06-27 09:56:55 +09:00
routersys 03db2d4faf ネイティブ実行の共有メモリプロトコルを定義 2026-06-27 09:56:55 +09:00
routersys fda89f726b 共有メモリでのBGRA授受の検証を追加 2026-06-27 09:33:34 +09:00
routersys d22035111a 共有メモリBGRA処理ワーカー(PoC)を追加 2026-06-27 09:33:34 +09:00
routersys 28bc23cd49 JIT無限ループのハードキル・タイムアウト検証を追加 2026-06-27 09:33:33 +09:00
routersys 796051015c animのMoonSharp×LuaJIT実機等価テストを追加 2026-06-27 09:33:33 +09:00
routersys 7184a89330 bit32のC#×LuaJIT実機等価テストを追加 2026-06-27 09:33:33 +09:00
routersys add78d673a クロスエンジン評価ランナーを追加 2026-06-27 09:33:33 +09:00
routersys f8522ad816 LuaJIT用 bit32/rawlen/anim シムを追加 2026-06-27 09:33:32 +09:00
routersys 45bee472e4 LuaJIT 2.1 x64バイナリを同梱(テストfixture) 2026-06-27 09:33:32 +09:00
routersys be411b596d animユーティリティの契約テストを追加 2026-06-27 09:33:14 +09:00
routersys 21741fc620 rawlen等の基本関数の挙動固定テストを追加 2026-06-27 09:33:14 +09:00
routersys 05ffdcc9d3 Bit32の正しさと安全域でのMoonSharp一致テストを追加 2026-06-27 09:33:13 +09:00
routersys 1f32ec59ce MoonSharpBit32のMoonSharp等価テストを追加 2026-06-27 09:33:13 +09:00
routersys 6af9153f50 ルータのテストを追加 2026-06-27 09:33:13 +09:00
routersys 4528748493 テスト用LuaJITレーン(別プロセス駆動)ヘルパを追加 2026-06-27 09:33:13 +09:00
routersys 3c0e13c85d テスト用MoonSharpレーンヘルパを追加 2026-06-27 09:33:13 +09:00
routersys 66786bfc98 テストプロジェクトLuaScript.Testsを追加 2026-06-27 09:33:12 +09:00
routersys 10dbb022bc 正しいLua5.2準拠のbit32実装を追加 2026-06-27 09:32:53 +09:00
routersys b0e47b82f5 MoonSharp挙動を完全再現するbit32実装(互換層)を追加 2026-06-27 09:32:53 +09:00
routersys 9e3381f0d0 エンジン振り分けディレクティブ(--!native等)を解析するルータを追加 2026-06-27 09:32:53 +09:00
routersys 6e29bf08b0 毎フレーム処理のアロケーションを削減し動画出力を高速化 2026-06-26 20:25:58 +09:00
routersys 21615a5461 マージ 2026-06-25 15:17:11 +09:00
routersys bc3bd511df Create CNAME 2026-06-25 07:46:55 +09:00
69個のファイルの変更、5839行の追加、242行の削除

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

+39 -39
ファイルの表示
@@ -1,54 +1,54 @@
# v1.2.0 - Lua スクリプト for YMM4
# v1.7.0 - Lua スクリプト for YMM4
他オブジェクトの情報を任意のフレーム時点で取得できるようにしたリリースです。
発射元が動いても弾の発射位置を固定するなど、フレームを指定した参照が可能になりました。
AviUtl のアニメーション効果スクリプト互換層に**映像エフェクトの適用(`obj.effect()`)**を
追加したリリースです。スクリプトから YMM4 に登録された映像エフェクトを呼び出し、
図形やピクセルで生成した画像へ連鎖適用できるようになりました。
---
## 新機能
### 1. obj.getobject へのフレーム指定引数の追加
### 1. obj.effect() による YMM4 映像エフェクトの適用
`obj.getobject(tag, frame)` の第2引数 `frame` を追加しました。指定したタイムライン
フレーム時点での対象オブジェクトの座標・回転・拡大率・不透明度を取得できます。
`frame` を省略した場合は従来どおり現在フレームの値を返します。
`obj.effect(エフェクト名, パラメータ名, 値, パラメータ名, 値, ...)` を実装しました。
スクリプトが生成した画像に対して、YMM4 の映像エフェクトを適用します。
弾の発射フレーム(弾アイテムの開始フレーム)は `timelineframe - frame` で求まるため、
そのフレームの発射元座標を取得すれば、発射元が動いても弾の原点を発射位置に固定できます。
- エフェクト名は YMM4 の登録名または別名で指定します。`EffectFactories` から取得できる
全映像エフェクト(標準エフェクトおよびユーザー製プラグインを含む)が対象です。
- パラメータは表示名またはプロパティ名で指定します。型に応じて設定され、Animation は
定数値、真偽値、列挙(名前または番号)、色(0xRRGGBB)、数値、文字列に対応します。
- パラメータはキー/値のペアで複数同時に指定できます。
- `obj.effect` を複数回呼び出すと、呼んだ順に**独立したエフェクトインスタンス**として
連鎖適用されます。同じエフェクトを複数回重ねて適用することもできます。
- エフェクトは、スクリプトが生成した画像(図形やピクセル)または入力画像に対して、
YMM4 本体と同じ `SetInput` → `Update` → `Output` のチェーンで適用されます。
- パラメータはフレームごとに再評価されるため、`obj.time` などに応じて値を計算すれば
エフェクトのパラメータをアニメーションさせられます。
```lua
local fire = timelineframe - frame
local src = obj.getobject("routersys", fire)
if src then
obj.x = src.x
obj.y = src.y
end
```
---
取得値は対象アイテム自身の座標・回転・拡大率であり、グループ制御・カメラ制御による
変形は含みません。同じタグのアイテムが複数ある場合は、対象フレームで表示中のものを
優先して返します。
## 注意事項
- `obj.effect`(および `obj.load`)は描画系 API のため MoonSharp エンジンで実行されます。
ネイティブ(LuaJIT)経路ではエフェクトは適用されません。
- エフェクトの登録名はローカライズされるため、指定名は実行環境の表示言語に依存する
場合があります。言語に依存させたくない場合は、英語の別名やプロパティ名を用いて
ください。
- Animation パラメータは定数値として設定されます。キーフレーム曲線は指定できません。
時間変化させたい場合はスクリプト側で値を計算してください。
- 指定したエフェクトが見つからない、または生成・更新に失敗した場合、その要求は安全に
スキップされ、画像はそのまま通過します。描画は停止しません。
- 対象エフェクトの解決は導入状況に依存します。ユーザー製エフェクトは未導入の場合、
名前が解決されずスキップされます。
---
## 内部実装
### 2. 参照方式の統一(依存クエリの再評価)
他オブジェクトの値を「現在フレームで事前に算出したスナップショット」を比較する方式から、
「参照したオブジェクトを保持し、要求されたフレームで評価する」方式へ統一しました。
- 取得対象のアイテムを保持し、任意のフレームで評価する `SceneObjectResolver` を追加
- スクリプト実行中に行われた参照 `(タグ, フレーム)` を記録し、出力キャッシュの
再利用判定では記録した参照を再評価して一致を確認
これにより、任意フレームの参照に対しても決定論的かつキャッシュ整合性を保った
取得が可能になります。評価はすべて描画スレッド側で行い、スクリプト実行スレッドへは
数値のみを渡します。
---
## ドキュメント
対応する 8 言語のスクリプト説明文に `frame` 引数の説明と発射位置を固定する例を
追記し、サンプル集ページにも同様の例を追加しました。
- スクリプトの `obj.effect` 呼び出しを実行コンテキストに記録し、スクリプト実行後に
描画スレッドで Direct2D エフェクトチェーンとして適用する仕組みを追加しました。
- `EffectFactories.VideoEffectFactories` を登録名・別名で索引し、リフレクションで
対象プロパティを解決してパラメータを設定します。
- YMM4 の API 変更に対する多層フォールバックを実装しました。レジストリ構築、
パラメータ解決、各エフェクトの生成・更新・適用をそれぞれ例外隔離し、失敗時は
当該エフェクトをスキップして元画像を通過させます(描画自体は停止しません)。
+32
ファイルの表示
@@ -0,0 +1,32 @@
Lua License
-----------
Lua is licensed under the terms of the MIT license reproduced below. This means
that Lua is free software and can be used for both academic and commercial
purposes at absolutely no cost.
For details and rationale, see https://www.lua.org/license.html .
===============================================================================
Copyright (C) 1994-2025 Lua.org, PUC-Rio.
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
===============================================================================
+56
ファイルの表示
@@ -0,0 +1,56 @@
===============================================================================
LuaJIT -- a Just-In-Time Compiler for Lua. https://luajit.org/
Copyright (C) 2005-2026 Mike Pall. All rights reserved.
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
[ MIT license: https://www.opensource.org/licenses/mit-license.php ]
===============================================================================
[ LuaJIT includes code from Lua 5.1/5.2, which has this license statement: ]
Copyright (C) 1994-2012 Lua.org, PUC-Rio.
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
===============================================================================
[ LuaJIT includes code from dlmalloc, which has this license statement: ]
This is a version (aka dlmalloc) of malloc/free/realloc written by
Doug Lea and released to the public domain, as explained at
https://creativecommons.org/licenses/publicdomain
===============================================================================
+38
ファイルの表示
@@ -0,0 +1,38 @@
Copyright (c) 2014-2016, Marco Mastropaolo
All rights reserved.
Parts of the string library are based on the KopiLua project (https://github.com/NLua/KopiLua)
Copyright (c) 2012 LoDC
Visual Studio Code debugger code is based on code from Microsoft vscode-mono-debug project (https://github.com/Microsoft/vscode-mono-debug).
Copyright (c) Microsoft Corporation - released under MIT license.
Remote Debugger icons are from the Eclipse project (https://www.eclipse.org/).
Copyright of The Eclipse Foundation
The MoonSharp icon is (c) Isaac, 2014-2015
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright notice, this
list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright notice,
this list of conditions and the following disclaimer in the documentation
and/or other materials provided with the distribution.
* Neither the name of the {organization} nor the names of its
contributors may be used to endorse or promote products derived from
this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+1 -1
ファイルの表示
@@ -1,5 +1,5 @@
========================================
Luaスクリプト for YMM4 v1.2.0
Luaスクリプト for YMM4 v1.7.0
========================================
YukkuriMovieMaker4(YMM4)上で動作する、Luaスクリプトで映像エフェクトのパラメータや
ピクセルを直接制御できるプラグインです。
+7
ファイルの表示
@@ -69,9 +69,15 @@ jobs:
$pkgName = "LuaScript_$version.ymme"
New-Item -ItemType Directory -Path "$stageRoot/docs" -Force | Out-Null
New-Item -ItemType Directory -Path "$stageRoot/native" -Force | Out-Null
New-Item -ItemType Directory -Path "$stageRoot/LICENSE" -Force | Out-Null
Copy-Item "$outDir/LuaScript.dll" "$stageRoot/"
Copy-Item "$outDir/MoonSharp.Interpreter.dll" "$stageRoot/"
Copy-Item "$outDir/native/luajit.exe" "$stageRoot/native/"
Copy-Item "$outDir/native/lua51.dll" "$stageRoot/native/"
Copy-Item "$outDir/native/worker.lua" "$stageRoot/native/"
Copy-Item "$outDir/native/shim.lua" "$stageRoot/native/"
foreach ($lang in @("ar-sa", "en-us", "es-es", "id-id", "ko-kr", "zh-cn", "zh-tw")) {
$src = "$outDir/$lang"
@@ -82,6 +88,7 @@ jobs:
}
Copy-Item "LuaScript/docs/LuaScript.*.txt" "$stageRoot/docs/"
Copy-Item ".github/LICENSE/*.txt" "$stageRoot/LICENSE/"
Copy-Item ".github/Plugin_Readme.txt" "$stageRoot/Readme.txt"
Compress-Archive -Path "stage/*" -DestinationPath $pkgName -CompressionLevel Optimal
+146
ファイルの表示
@@ -0,0 +1,146 @@
namespace LuaScript.Tests
{
public class AnimContractTests
{
private const int Precision = 9;
private readonly MoonSharpLane _lane = new();
private void Eq(double expected, string expression) =>
Assert.Equal(expected, _lane.Number(expression), Precision);
[Fact]
public void Constants()
{
Eq(Math.PI * 2d, "anim.tau");
Eq(Math.E, "anim.e");
Eq((1d + Math.Sqrt(5d)) / 2d, "anim.phi");
Eq(Math.Sqrt(2d), "anim.sqrt2");
}
[Fact]
public void LerpMapNormClamp()
{
Eq(5d, "anim.lerp(0,10,0.5)");
Eq(12.5d, "anim.lerp(10,20,0.25)");
Eq(50d, "anim.map(5,0,10,0,100)");
Eq(0.5d, "anim.norm(5,0,10)");
Eq(1d, "anim.clamp(5,0,1)");
Eq(0d, "anim.clamp(-1,0,1)");
Eq(0.5d, "anim.clamp(0.5,0,1)");
}
[Fact]
public void SmoothSteps()
{
Eq(0.5d, "anim.smoothstep(0,1,0.5)");
Eq(0d, "anim.smoothstep(0,1,0)");
Eq(1d, "anim.smoothstep(0,1,1)");
Eq(0.5d, "anim.smootherstep(0,1,0.5)");
}
[Fact]
public void WrapPingpong()
{
Eq(2d, "anim.wrap(7,0,5)");
Eq(4d, "anim.wrap(-1,0,5)");
Eq(3d, "anim.pingpong(7,5)");
Eq(3d, "anim.pingpong(3,5)");
}
[Fact]
public void Waves()
{
Eq(0.5d, "anim.oscillate(0,0,1,1)");
Eq(0d, "anim.triangle(0,1)");
Eq(0.5d, "anim.triangle(0.25,1)");
Eq(1d, "anim.triangle(0.5,1)");
Eq(0d, "anim.square(0.25,1)");
Eq(1d, "anim.square(0.5,1)");
}
[Fact]
public void Easings()
{
Eq(0.25d, "anim.ease_in(0.5)");
Eq(0.75d, "anim.ease_out(0.5)");
Eq(0.125d, "anim.ease_in_out(0.25)");
Eq(0.875d, "anim.ease_in_out(0.75)");
Eq(0d, "anim.back(0)");
Eq(1d, "anim.back(1)");
Eq(0d, "anim.elastic(0)");
Eq(1d, "anim.elastic(1)");
Eq(0d, "anim.bounce(0)");
}
[Fact]
public void Misc()
{
Eq(-1d, "anim.sign(-5)");
Eq(0d, "anim.sign(0)");
Eq(1d, "anim.sign(3)");
Eq(0.5d, "anim.duration(0.5,1)");
Eq(1d, "anim.duration(2,1)");
Eq(1d, "anim.delay(2,1)");
Eq(0d, "anim.delay(0.5,1)");
Eq(1d, "anim.step(0.5,0.6)");
Eq(0d, "anim.step(0.5,0.4)");
Eq(0.25d, "anim.fract(3.25)");
Eq(0.75d, "anim.fract(-0.25)");
}
[Fact]
public void Vectors()
{
Eq(5d, "anim.len(3,4)");
Eq(5d, "anim.dist(0,0,3,4)");
Eq(11d, "anim.dot(1,2,3,4)");
Eq(0d, "anim.bezier(0,0,1,2,3)");
Eq(3d, "anim.bezier(1,0,1,2,3)");
}
[Fact]
public void TupleFunctions()
{
var rgb = _lane.Tuple("anim.hsv_to_rgb(0,1,1)", 3);
Assert.Equal(255d, rgb[0], Precision);
Assert.Equal(0d, rgb[1], Precision);
Assert.Equal(0d, rgb[2], Precision);
var hsv = _lane.Tuple("anim.rgb_to_hsv(255,0,0)", 3);
Assert.Equal(0d, hsv[0], Precision);
Assert.Equal(1d, hsv[1], Precision);
Assert.Equal(1d, hsv[2], Precision);
var n = _lane.Tuple("anim.normalize(3,4)", 2);
Assert.Equal(0.6d, n[0], Precision);
Assert.Equal(0.8d, n[1], Precision);
var rot = _lane.Tuple("anim.rotate(1,0,90)", 2);
Assert.Equal(0d, rot[0], Precision);
Assert.Equal(1d, rot[1], Precision);
}
[Fact]
public void RandIsDeterministicAndBounded()
{
Assert.Equal(_lane.Number("anim.rand(5)"), _lane.Number("anim.rand(5)"));
Assert.NotEqual(_lane.Number("anim.rand(5)"), _lane.Number("anim.rand(6)"));
for (int seed = 0; seed < 50; seed++)
{
double r = _lane.Number($"anim.rand(10,20,{seed})");
Assert.InRange(r, 10d, 20d);
}
}
[Fact]
public void NoiseIsDeterministicAndBounded()
{
Assert.Equal(_lane.Number("anim.noise(1.5,2.5,0.5)"), _lane.Number("anim.noise(1.5,2.5,0.5)"));
for (double x = 0d; x < 5d; x += 0.37d)
{
double v = _lane.Number($"anim.noise({x.ToString(System.Globalization.CultureInfo.InvariantCulture)})");
Assert.InRange(v, 0d, 1d);
}
}
}
}
+120
ファイルの表示
@@ -0,0 +1,120 @@
using LuaScript.Compat;
namespace LuaScript.Tests
{
public class AviUtlParameterLayoutTests
{
[Fact]
public void NoDirectives_HasAnyIsFalse()
{
var layout = AviUtlParameterLayout.Parse("obj.x = 1\nobj.y = 2");
Assert.False(layout.HasAny);
Assert.False(layout.HasTrack(0));
Assert.False(layout.HasColor);
}
[Fact]
public void Track_ParsesNameRangeDefaultStep()
{
var layout = AviUtlParameterLayout.Parse("--track0:Amp,0,100,10,0.5\nobj.ox = obj.track0");
Assert.True(layout.HasAny);
var t = layout.GetTrack(0);
Assert.NotNull(t);
Assert.Equal("Amp", t!.Value.Name);
Assert.Equal(0d, t.Value.Min);
Assert.Equal(100d, t.Value.Max);
Assert.Equal(10d, t.Value.Default);
Assert.Equal(0.5d, t.Value.Step);
}
[Fact]
public void Track_DefaultIsClampedIntoRange()
{
var layout = AviUtlParameterLayout.Parse("--track1:V,0,10,999");
var t = layout.GetTrack(1);
Assert.Equal(10d, t!.Value.Default);
}
[Fact]
public void Track_SwapsInvertedMinMax()
{
var layout = AviUtlParameterLayout.Parse("--track0:V,100,0,50");
var t = layout.GetTrack(0);
Assert.Equal(0d, t!.Value.Min);
Assert.Equal(100d, t.Value.Max);
}
[Fact]
public void Track_NegativeRangeParses()
{
var layout = AviUtlParameterLayout.Parse("--track2:Off,-100,100,-25");
var t = layout.GetTrack(2);
Assert.Equal(-100d, t!.Value.Min);
Assert.Equal(-25d, t.Value.Default);
}
[Fact]
public void Track_IndexBeyondThreeIsIgnored()
{
var layout = AviUtlParameterLayout.Parse("--track4:V,0,10,5");
Assert.False(layout.HasAny);
}
[Fact]
public void Check_ParsesDefaultAsBool()
{
var layout = AviUtlParameterLayout.Parse("--check0:On,1\n--check1:Off,0");
Assert.True(layout.GetCheck(0)!.Value.Default);
Assert.False(layout.GetCheck(1)!.Value.Default);
Assert.Equal("On", layout.GetCheck(0)!.Value.Name);
}
[Fact]
public void Color_ParsesHexLiteral()
{
var layout = AviUtlParameterLayout.Parse("--color:0xff8800");
Assert.True(layout.HasColor);
Assert.Equal(0xff8800, layout.Color!.Value.Default);
}
[Fact]
public void Color_ParsesDecimalLiteral()
{
var layout = AviUtlParameterLayout.Parse("--color:255");
Assert.Equal(255, layout.Color!.Value.Default);
}
[Fact]
public void Combined_TrackCheckColorAllDetected()
{
const string src =
"--track0:Amp,0,100,10\n" +
"--track1:Spd,0,50,5\n" +
"--check0:Enable,1\n" +
"--color:0x112233\n" +
"obj.ox = obj.track0";
var layout = AviUtlParameterLayout.Parse(src);
Assert.True(layout.HasTrack(0));
Assert.True(layout.HasTrack(1));
Assert.False(layout.HasTrack(2));
Assert.True(layout.HasCheck(0));
Assert.True(layout.HasColor);
}
[Fact]
public void Section_OnlyFirstSectionHeaderIsScanned()
{
const string src = "@First\n--track0:A,0,10,3\n@Second\n--track1:B,0,10,4";
var layout = AviUtlParameterLayout.Parse(src);
Assert.True(layout.HasTrack(0));
Assert.False(layout.HasTrack(1));
}
[Fact]
public void EngineDirective_IsNotMistakenForParameter()
{
var layout = AviUtlParameterLayout.Parse("--!native\nobj.x = 1");
Assert.False(layout.HasAny);
}
}
}
+71
ファイルの表示
@@ -0,0 +1,71 @@
using System;
using System.Collections.Generic;
using System.Globalization;
using LuaScript.Compat;
namespace LuaScript.Tests
{
public class AviUtlRandomEquivalenceTests
{
[Fact]
public void Rand_StaysWithinRequestedRange()
{
for (int seed = 0; seed < 64; seed++)
{
double value = AviUtlRandom.Next(-3, 7, seed, seed * 3 + 1);
Assert.InRange(value, -3d, 7d);
Assert.Equal(Math.Floor(value), value);
}
}
[Fact]
public void Rand_IsDeterministicForSameInputs()
{
Assert.Equal(
AviUtlRandom.Next(0, 100, 5, 12),
AviUtlRandom.Next(0, 100, 5, 12));
}
[Fact]
public void Rand_MatchesBetweenMoonSharpAndLuaJit()
{
var lane = new LuaJitLane();
Assert.True(lane.Available, "native/luajit.exe must be present");
var cases = new List<(double A, double B, double Seed, double Frame)>();
for (int seed = 0; seed < 16; seed++)
for (int frame = 0; frame < 4; frame++)
{
cases.Add((0d, 100d, seed, frame));
cases.Add((-50d, 50d, seed + 1, frame * 7));
cases.Add((1d, 6d, seed * 13, frame));
cases.Add((-3.5d, 3.5d, seed, frame + 1000));
}
var exprs = new List<string>(cases.Count);
foreach (var c in cases)
exprs.Add($"aviutl_rand({L(c.A)},{L(c.B)},{L(c.Seed)},{L(c.Frame)})");
string[] lines = lane.Eval(exprs);
Assert.Equal(exprs.Count, lines.Length);
var failures = new List<string>();
for (int i = 0; i < cases.Count; i++)
{
double expected = AviUtlRandom.Next(cases[i].A, cases[i].B, cases[i].Seed, cases[i].Frame);
if (!double.TryParse(lines[i], NumberStyles.Float, CultureInfo.InvariantCulture, out var got))
{
failures.Add($"{exprs[i]} => luajit '{lines[i]}' (not a number), expected {expected}");
continue;
}
if (got != expected)
failures.Add($"{exprs[i]} => luajit {got}, moonsharp {expected}");
}
Assert.True(failures.Count == 0,
$"{failures.Count}/{cases.Count} mismatches:\n" + string.Join("\n", failures.GetRange(0, Math.Min(25, failures.Count))));
}
private static string L(double value) => value.ToString("R", CultureInfo.InvariantCulture);
}
}
+137
ファイルの表示
@@ -0,0 +1,137 @@
using LuaScript.Compat;
using MoonSharp.Interpreter;
namespace LuaScript.Tests
{
public class AviUtlScriptTests
{
private static Script NewScript()
{
var script = new Script(
CoreModules.Basic |
CoreModules.Math |
CoreModules.String |
CoreModules.Table |
CoreModules.Bit32 |
CoreModules.TableIterators |
CoreModules.Metatables |
CoreModules.ErrorHandling);
script.Globals["obj"] = new Table(script);
return script;
}
private static double RunNumber(string transformed, string global = "result")
{
var script = NewScript();
script.DoString(transformed);
return script.Globals.Get(global).Number;
}
[Fact]
public void PlainScript_IsReturnedUnchanged()
{
const string source = "obj.x = 1\nobj.y = 2";
Assert.Equal(source, AviUtlScript.Transform(source));
}
[Fact]
public void TrackOnlyHeader_IsReturnedUnchanged()
{
const string source = "--track0:Amp,0,100,10\nobj.ox = obj.track0";
Assert.Equal(source, AviUtlScript.Transform(source));
}
[Fact]
public void DirectiveComment_IsNotConfusedWithDirective()
{
const string source = "-- color reference note\nobj.x = 1";
Assert.Equal(source, AviUtlScript.Transform(source));
}
[Fact]
public void EngineDirective_IsPreserved()
{
const string source = "--!native\n--dialog:V,local v=3;\nresult = v";
string transformed = AviUtlScript.Transform(source);
Assert.Contains("--!native", transformed);
Assert.Equal(3d, RunNumber(transformed));
}
[Fact]
public void Dialog_InjectsDefaultDeclarations()
{
const string source = "--dialog:Angle,local angle=45;Dist,local dist=100;\nresult = dist";
double result = RunNumber(AviUtlScript.Transform(source));
Assert.Equal(100d, result);
}
[Fact]
public void Color_IsNotInjected_SurfacedAsUiParameter()
{
const string source = "--color:0x010203\nresult = color";
Assert.Equal(source, AviUtlScript.Transform(source));
}
[Fact]
public void Check_IsNotInjected_SurfacedAsUiParameter()
{
const string source = "--check0:Enable,1\nresult = obj.check0";
Assert.Equal(source, AviUtlScript.Transform(source));
}
[Fact]
public void Param_InjectsRawLua()
{
const string source = "--param:result = 7\nlocal x = 1";
double result = RunNumber(AviUtlScript.Transform(source));
Assert.Equal(7d, result);
}
[Fact]
public void Section_FirstSectionIsSelected()
{
const string source = "@First\n--dialog:A,local a=5;\nresult = a\n@Second\nresult = 999";
double result = RunNumber(AviUtlScript.Transform(source));
Assert.Equal(5d, result);
}
[Fact]
public void Section_PreambleBeforeFirstHeaderIsDiscarded()
{
const string source = "result = 111\n@Only\nresult = 222";
double result = RunNumber(AviUtlScript.Transform(source));
Assert.Equal(222d, result);
}
[Fact]
public void ClassicTransformScript_RunsAndMovesObject()
{
const string source =
"--track0:Range,0,2000,10\n" +
"--dialog:Seed,local seed=3;\n" +
"obj.ox = obj.ox + obj.track0 * obj.rand(-100,100,seed,obj.time) / 100";
var script = NewScript();
var obj = script.Globals.Get("obj").Table;
obj["ox"] = 0d;
obj["track0"] = 500d;
obj["time"] = 2d;
obj["frame"] = 4d;
obj["rand"] = DynValue.NewCallback((_, args) =>
{
double frameDefault = obj.Get("frame").CastToNumber() ?? 0d;
double a = args.Count > 0 ? args[0].CastToNumber() ?? 0d : 0d;
double b = args.Count > 1 ? args[1].CastToNumber() ?? 0d : 0d;
double seed = args.Count > 2 ? args[2].CastToNumber() ?? 0d : 0d;
double frame = args.Count > 3 ? args[3].CastToNumber() ?? frameDefault : frameDefault;
return DynValue.NewNumber(AviUtlRandom.Next(a, b, seed, frame));
});
script.DoString(AviUtlScript.Transform(source));
double moved = obj.Get("ox").Number;
double expectedRand = AviUtlRandom.Next(-100, 100, 3, 2);
Assert.Equal(500d * expectedRand / 100d, moved);
}
}
}
+113
ファイルの表示
@@ -0,0 +1,113 @@
using System.Collections.Generic;
using LuaScript.Compat;
namespace LuaScript.Tests
{
public class Bit32CleanTests
{
[Fact]
public void Correct_Lua52_Semantics()
{
Assert.Equal(0xFFFFFFFFu, Bit32.Band(4294967295d, 4294967295d));
Assert.Equal(0xFFFFFFFFu, Bit32.Bnot(0d));
Assert.Equal(2147483648u, Bit32.Lshift(1d, 31d));
Assert.Equal(0u, Bit32.Lshift(1d, 32d));
Assert.Equal(0u, Bit32.Lshift(1d, -1d));
Assert.Equal(1u, Bit32.Rshift(2147483648d, 31d));
Assert.Equal(3221225472u, Bit32.Arshift(2147483648d, 1d));
Assert.Equal(0xFFFFFFFFu, Bit32.Arshift(4294967295d, 40d));
Assert.Equal(2147483648u, Bit32.Lrotate(1d, -1d));
Assert.Equal(1u, Bit32.Lrotate(2147483648d, 1d));
}
[Fact]
public void Correct_Extract_Replace_AllowsFullRange()
{
Assert.Equal(1u, Bit32.Extract(4294967295d, 31, 1));
Assert.Equal(0xFFFFFFFFu, Bit32.Extract(4294967295d, 0, 32));
Assert.Equal(255u, Bit32.Extract(255d, 0, 8));
Assert.Equal(2147483648u, Bit32.Replace(0d, 1d, 31, 1));
}
[Theory]
[InlineData(32, 1)]
[InlineData(0, 33)]
[InlineData(-1, 1)]
[InlineData(0, 0)]
public void Extract_OutOfRange_Throws(int field, int width) =>
Assert.Throws<System.ArgumentException>(() => Bit32.Extract(1d, field, width));
public static readonly double[] SafeValues =
[
0d, 1d, 2d, 255d, 256d, 65535d, 65536d, 16777215d,
1073741824d, 2147483647d,
];
public static readonly int[] SafeShifts = [0, 1, 4, 8, 15, 16, 24, 31];
public static IEnumerable<object[]> SafeBinary()
{
foreach (var a in SafeValues)
foreach (var b in SafeValues)
yield return [a, b];
}
public static IEnumerable<object[]> SafeValueAndShift()
{
foreach (var a in SafeValues)
foreach (var n in SafeShifts)
yield return [a, n];
}
[Theory]
[MemberData(nameof(SafeBinary))]
public void Bitwise_MatchesMoonSharp_OnSafeDomain(double a, double b)
{
Assert.Equal(MoonSharpBit32.Band(a, b), Bit32.Band(a, b));
Assert.Equal(MoonSharpBit32.Bor(a, b), Bit32.Bor(a, b));
Assert.Equal(MoonSharpBit32.Bxor(a, b), Bit32.Bxor(a, b));
Assert.Equal(MoonSharpBit32.Btest(a, b), Bit32.Btest(a, b));
}
[Theory]
[MemberData(nameof(SafeValueAndShift))]
public void Shifts_MatchMoonSharp_OnSafeDomain(double a, int n)
{
Assert.Equal(MoonSharpBit32.Lshift(a, n), Bit32.Lshift(a, n));
Assert.Equal(MoonSharpBit32.Rshift(a, n), Bit32.Rshift(a, n));
Assert.Equal((double)MoonSharpBit32.Arshift(a, n), (double)Bit32.Arshift(a, n));
Assert.Equal(MoonSharpBit32.Lrotate(a, n), Bit32.Lrotate(a, n));
Assert.Equal(MoonSharpBit32.Rrotate(a, n), Bit32.Rrotate(a, n));
}
[Theory]
[InlineData(0, 1)]
[InlineData(0, 8)]
[InlineData(4, 4)]
[InlineData(8, 8)]
[InlineData(0, 16)]
[InlineData(15, 16)]
[InlineData(30, 1)]
public void Extract_MatchesMoonSharp_OnSafeDomain(int field, int width)
{
foreach (var a in SafeValues)
Assert.Equal(MoonSharpBit32.Extract(a, field, width), Bit32.Extract(a, field, width));
}
[Fact]
public void Replace_IsCorrectLua52_ShiftsReplacementIntoField()
{
Assert.Equal(0xF0u, Bit32.Replace(0d, 15d, 4, 4));
Assert.Equal(0x80000000u, Bit32.Replace(0d, 1d, 31, 1));
Assert.Equal(0xABCD0000u, Bit32.Replace(0d, 43981d, 16, 16));
}
[Fact]
public void Replace_DivergesFromMoonSharpBug_ForNonZeroField()
{
Assert.NotEqual((double)MoonSharpBit32.Replace(0d, 15d, 4, 4), (double)Bit32.Replace(0d, 15d, 4, 4));
Assert.Equal(0u, MoonSharpBit32.Replace(0d, 15d, 4, 4));
Assert.Equal(0xF0u, Bit32.Replace(0d, 15d, 4, 4));
}
}
}
+161
ファイルの表示
@@ -0,0 +1,161 @@
using System.Collections.Generic;
using System.Globalization;
using LuaScript.Compat;
using MoonSharp.Interpreter;
namespace LuaScript.Tests
{
public class Bit32EquivalenceTests
{
private static readonly Script Oracle = new(CoreModules.Basic | CoreModules.Math | CoreModules.Bit32);
private static double Eval(string expression) => Oracle.DoString("return " + expression).Number;
private static bool EvalBool(string expression) => Oracle.DoString("return " + expression).Boolean;
private static string Lit(double value) => value.ToString("R", CultureInfo.InvariantCulture);
public static readonly double[] RawInputs =
[
0d, 1d, 2d, 255d, 256d, 65535d, 65536d,
2147483647d, 2147483648d, 4294967295d,
4294967296d, 4294967301d,
-1d, -2d, -256d, -2147483648d,
];
public static readonly int[] Shifts =
[
0, 1, 4, 7, 8, 15, 16, 24, 31, 32, 33, 64,
-1, -4, -8, -16, -31, -32, -33,
];
public static IEnumerable<object[]> Unary()
{
foreach (var a in RawInputs)
yield return [a];
}
public static IEnumerable<object[]> Binary()
{
foreach (var a in RawInputs)
foreach (var b in RawInputs)
yield return [a, b];
}
public static IEnumerable<object[]> ValueAndShift()
{
foreach (var a in RawInputs)
foreach (var n in Shifts)
yield return [a, n];
}
[Theory]
[MemberData(nameof(Binary))]
public void Band(double a, double b) =>
Assert.Equal((double)MoonSharpBit32.Band(a, b), Eval($"bit32.band({Lit(a)},{Lit(b)})"));
[Theory]
[MemberData(nameof(Binary))]
public void Bor(double a, double b) =>
Assert.Equal((double)MoonSharpBit32.Bor(a, b), Eval($"bit32.bor({Lit(a)},{Lit(b)})"));
[Theory]
[MemberData(nameof(Binary))]
public void Bxor(double a, double b) =>
Assert.Equal((double)MoonSharpBit32.Bxor(a, b), Eval($"bit32.bxor({Lit(a)},{Lit(b)})"));
[Theory]
[MemberData(nameof(Binary))]
public void Btest(double a, double b) =>
Assert.Equal(MoonSharpBit32.Btest(a, b), EvalBool($"bit32.btest({Lit(a)},{Lit(b)})"));
[Theory]
[MemberData(nameof(Unary))]
public void Bnot(double a) =>
Assert.Equal((double)MoonSharpBit32.Bnot(a), Eval($"bit32.bnot({Lit(a)})"));
[Theory]
[MemberData(nameof(ValueAndShift))]
public void Lshift(double a, int n) =>
Assert.Equal((double)MoonSharpBit32.Lshift(a, n), Eval($"bit32.lshift({Lit(a)},{n})"));
[Theory]
[MemberData(nameof(ValueAndShift))]
public void Rshift(double a, int n) =>
Assert.Equal((double)MoonSharpBit32.Rshift(a, n), Eval($"bit32.rshift({Lit(a)},{n})"));
[Theory]
[MemberData(nameof(ValueAndShift))]
public void Arshift(double a, int n) =>
Assert.Equal((double)MoonSharpBit32.Arshift(a, n), Eval($"bit32.arshift({Lit(a)},{n})"));
[Theory]
[MemberData(nameof(ValueAndShift))]
public void Lrotate(double a, int n) =>
Assert.Equal((double)MoonSharpBit32.Lrotate(a, n), Eval($"bit32.lrotate({Lit(a)},{n})"));
[Theory]
[MemberData(nameof(ValueAndShift))]
public void Rrotate(double a, int n) =>
Assert.Equal((double)MoonSharpBit32.Rrotate(a, n), Eval($"bit32.rrotate({Lit(a)},{n})"));
[Theory]
[InlineData(0, 1)]
[InlineData(0, 8)]
[InlineData(4, 4)]
[InlineData(8, 8)]
[InlineData(0, 16)]
[InlineData(8, 16)]
[InlineData(0, 31)]
[InlineData(30, 1)]
[InlineData(15, 16)]
public void Extract(int field, int width)
{
foreach (var a in RawInputs)
Assert.Equal(
(double)MoonSharpBit32.Extract(a, field, width),
Eval($"bit32.extract({Lit(a)},{field},{width})"));
}
[Theory]
[InlineData(0, 1)]
[InlineData(0, 8)]
[InlineData(4, 4)]
[InlineData(8, 8)]
[InlineData(0, 16)]
[InlineData(8, 16)]
[InlineData(0, 31)]
[InlineData(30, 1)]
[InlineData(15, 16)]
public void Replace(int field, int width)
{
foreach (var a in RawInputs)
foreach (var v in RawInputs)
Assert.Equal(
(double)MoonSharpBit32.Replace(a, v, field, width),
Eval($"bit32.replace({Lit(a)},{Lit(v)},{field},{width})"));
}
[Theory]
[InlineData(31, 1)]
[InlineData(16, 16)]
[InlineData(0, 32)]
[InlineData(32, 0)]
public void Extract_OutOfRange_BothReject(int field, int width)
{
Assert.ThrowsAny<Exception>(() => MoonSharpBit32.Extract(1d, field, width));
Assert.ThrowsAny<ScriptRuntimeException>(() => Eval($"bit32.extract(1,{field},{width})"));
}
[Theory]
[InlineData(31, 1)]
[InlineData(16, 16)]
[InlineData(0, 32)]
[InlineData(32, 0)]
public void Replace_OutOfRange_BothReject(int field, int width)
{
Assert.ThrowsAny<Exception>(() => MoonSharpBit32.Replace(1d, 1d, field, width));
Assert.ThrowsAny<ScriptRuntimeException>(() => Eval($"bit32.replace(1,1,{field},{width})"));
}
}
}
+95
ファイルの表示
@@ -0,0 +1,95 @@
using LuaScript.Compat;
namespace LuaScript.Tests
{
public class FigureRendererTests
{
private static (int B, int G, int R, int A) Pixel(byte[] buffer, int width, int x, int y)
{
int i = (y * width + x) * 4;
return (buffer[i], buffer[i + 1], buffer[i + 2], buffer[i + 3]);
}
[Fact]
public void Render_ProducesBufferOfRequestedSize()
{
var buffer = FigureRenderer.Render("円", 64, 48, 0xFFFFFF, 0d);
Assert.Equal(64 * 48 * 4, buffer.Length);
}
[Fact]
public void FilledCircle_CenterIsOpaqueAndColored()
{
int w = 100, h = 100;
var buffer = FigureRenderer.Render("円", w, h, 0xFF0000, 0d);
var (b, g, r, a) = Pixel(buffer, w, w / 2, h / 2);
Assert.Equal(255, a);
Assert.Equal(255, r);
Assert.Equal(0, g);
Assert.Equal(0, b);
}
[Fact]
public void FilledCircle_CornerIsTransparent()
{
int w = 100, h = 100;
var buffer = FigureRenderer.Render("円", w, h, 0xFF0000, 0d);
var (_, _, _, a) = Pixel(buffer, w, 0, 0);
Assert.Equal(0, a);
}
[Fact]
public void Color_IsStoredPremultipliedAtHalfCoverageBoundary()
{
int w = 100, h = 100;
var buffer = FigureRenderer.Render("四角形", w, h, 0x102030, 0d);
var (b, g, r, a) = Pixel(buffer, w, w / 2, h / 2);
Assert.Equal(255, a);
Assert.Equal(0x10, r);
Assert.Equal(0x20, g);
Assert.Equal(0x30, b);
}
[Fact]
public void FilledRectangle_CornerIsOpaque()
{
int w = 80, h = 80;
var buffer = FigureRenderer.Render("四角形", w, h, 0xFFFFFF, 0d);
var (_, _, _, a) = Pixel(buffer, w, 1, 1);
Assert.Equal(255, a);
}
[Fact]
public void OutlinedCircle_IsHollowAtCenterButSolidNearEdge()
{
int w = 100, h = 100;
var buffer = FigureRenderer.Render("円", w, h, 0xFFFFFF, 8d);
var (_, _, _, center) = Pixel(buffer, w, w / 2, h / 2);
var (_, _, _, nearEdge) = Pixel(buffer, w, w / 2 + 46, h / 2);
Assert.Equal(0, center);
Assert.Equal(255, nearEdge);
}
[Fact]
public void Triangle_CornersEmptyCentroidFilled()
{
int w = 100, h = 100;
var buffer = FigureRenderer.Render("三角形", w, h, 0xFFFFFF, 0d);
var (_, _, _, topLeft) = Pixel(buffer, w, 2, 2);
var (_, _, _, topRight) = Pixel(buffer, w, w - 3, 2);
var (_, _, _, centroid) = Pixel(buffer, w, w / 2, h / 2);
Assert.Equal(0, topLeft);
Assert.Equal(0, topRight);
Assert.Equal(255, centroid);
}
[Fact]
public void UnknownName_FallsBackToRectangle()
{
int w = 40, h = 40;
var buffer = FigureRenderer.Render("unknown", w, h, 0xFFFFFF, 0d);
var (_, _, _, corner) = Pixel(buffer, w, 1, 1);
Assert.Equal(255, corner);
}
}
}
+48
ファイルの表示
@@ -0,0 +1,48 @@
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
namespace LuaScript.Tests
{
internal sealed class LuaJitLane
{
private readonly string _nativeDir = Path.Combine(AppContext.BaseDirectory, "native");
public bool Available => File.Exists(Path.Combine(_nativeDir, "luajit.exe"));
public string[] Eval(IReadOnlyList<string> expressions)
{
string vectors = Path.GetTempFileName();
File.WriteAllLines(vectors, expressions);
try
{
var psi = new ProcessStartInfo
{
FileName = Path.Combine(_nativeDir, "luajit.exe"),
WorkingDirectory = _nativeDir,
RedirectStandardOutput = true,
RedirectStandardError = true,
UseShellExecute = false,
};
psi.ArgumentList.Add("runner.lua");
psi.ArgumentList.Add(Path.Combine(_nativeDir, "shim.lua"));
psi.ArgumentList.Add(vectors);
using var process = Process.Start(psi)
?? throw new InvalidOperationException("Failed to start luajit.exe");
string stdout = process.StandardOutput.ReadToEnd();
string stderr = process.StandardError.ReadToEnd();
process.WaitForExit();
if (process.ExitCode != 0)
throw new InvalidOperationException("luajit exited " + process.ExitCode + ": " + stderr);
return stdout.Replace("\r\n", "\n").Split('\n');
}
finally
{
File.Delete(vectors);
}
}
}
}
+41
ファイルの表示
@@ -0,0 +1,41 @@
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<TargetFramework>net10.0</TargetFramework>
<ImplicitUsings>enable</ImplicitUsings>
<Nullable>enable</Nullable>
<IsPackable>false</IsPackable>
</PropertyGroup>
<ItemGroup>
<PackageReference Include="coverlet.collector" Version="6.0.4" />
<PackageReference Include="Microsoft.NET.Test.Sdk" Version="17.14.1" />
<PackageReference Include="MoonSharp" Version="2.0.0" />
<PackageReference Include="xunit" Version="2.9.3" />
<PackageReference Include="xunit.runner.visualstudio" Version="3.1.4" />
</ItemGroup>
<ItemGroup>
<Using Include="Xunit" />
</ItemGroup>
<ItemGroup>
<None Include="..\native\**" CopyToOutputDirectory="PreserveNewest" LinkBase="native" />
</ItemGroup>
<ItemGroup>
<Compile Include="..\LuaScript\Compat\MoonSharpBit32.cs" Link="Linked\MoonSharpBit32.cs" />
<Compile Include="..\LuaScript\Compat\Bit32.cs" Link="Linked\Bit32.cs" />
<Compile Include="..\LuaScript\Engine\ScriptEngineKind.cs" Link="Linked\ScriptEngineKind.cs" />
<Compile Include="..\LuaScript\Engine\NativeProtocol.cs" Link="Linked\NativeProtocol.cs" />
<Compile Include="..\LuaScript\Engine\ProcessJobObject.cs" Link="Linked\ProcessJobObject.cs" />
<Compile Include="..\LuaScript\Engine\LuaJitWorker.cs" Link="Linked\LuaJitWorker.cs" />
<Compile Include="..\LuaScript\SceneObjectInfo.cs" Link="Linked\SceneObjectInfo.cs" />
<Compile Include="..\LuaScript\AnimTableRegistrar.cs" Link="Linked\AnimTableRegistrar.cs" />
<Compile Include="..\LuaScript\Compat\AviUtlScript.cs" Link="Linked\AviUtlScript.cs" />
<Compile Include="..\LuaScript\Compat\AviUtlParameterLayout.cs" Link="Linked\AviUtlParameterLayout.cs" />
<Compile Include="..\LuaScript\Compat\AviUtlRandom.cs" Link="Linked\AviUtlRandom.cs" />
<Compile Include="..\LuaScript\Compat\FigureRenderer.cs" Link="Linked\FigureRenderer.cs" />
</ItemGroup>
</Project>
+46
ファイルの表示
@@ -0,0 +1,46 @@
using LuaScript;
using MoonSharp.Interpreter;
namespace LuaScript.Tests
{
internal sealed class MoonSharpLane
{
private readonly Script _script;
public MoonSharpLane()
{
_script = new Script(
CoreModules.Basic |
CoreModules.Math |
CoreModules.String |
CoreModules.Table |
CoreModules.Bit32 |
CoreModules.TableIterators |
CoreModules.Metatables |
CoreModules.ErrorHandling);
var anim = new Table(_script);
AnimTableRegistrar.RegisterFunctions(anim);
_script.Globals["anim"] = anim;
}
public DynValue Run(string code) => _script.DoString(code);
public double Number(string expression) => Run("return " + expression).Number;
public bool Boolean(string expression) => Run("return " + expression).Boolean;
public string? Text(string expression) => Run("return " + expression).CastToString();
public DataType Type(string expression) => Run("return " + expression).Type;
public double[] Tuple(string expression, int count)
{
var table = Run("return {" + expression + "}").Table;
var result = new double[count];
for (int i = 0; i < count; i++)
result[i] = table.Get(i + 1).Number;
return result;
}
}
}
+133
ファイルの表示
@@ -0,0 +1,133 @@
using System;
using System.Collections.Generic;
using System.Globalization;
namespace LuaScript.Tests
{
public class NativeAnimEquivalenceTests
{
private readonly MoonSharpLane _oracle = new();
[Fact]
public void Anim_MatchesBetweenMoonSharpAndLuaJit()
{
var lane = new LuaJitLane();
Assert.True(lane.Available, "native/luajit.exe must be present");
var exprs = new List<string>();
void Add(string e) => exprs.Add(e);
void Tuple(string call, int n)
{
for (int k = 1; k <= n; k++)
exprs.Add($"({{{call}}})[{k}]");
}
Add("anim.tau"); Add("anim.e"); Add("anim.phi"); Add("anim.sqrt2");
foreach (var (a, b, t) in new[] { (0d, 10d, 0.5d), (10d, 20d, 0.25d), (-5d, 5d, 0.75d), (100d, -100d, 0.1d) })
Add($"anim.lerp({L(a)},{L(b)},{L(t)})");
foreach (var (e0, e1, x) in new[] { (0d, 1d, 0.5d), (0d, 1d, 0.3d), (2d, 4d, 3d), (0d, 1d, -1d), (0d, 1d, 2d) })
{
Add($"anim.smoothstep({L(e0)},{L(e1)},{L(x)})");
Add($"anim.smootherstep({L(e0)},{L(e1)},{L(x)})");
}
foreach (var (v, lo, hi) in new[] { (5d, 0d, 1d), (-1d, 0d, 1d), (0.5d, 0d, 1d), (7d, 2d, 9d) })
{
Add($"anim.clamp({L(v)},{L(lo)},{L(hi)})");
Add($"anim.norm({L(v)},{L(lo)},{L(hi)})");
}
Add("anim.map(5,0,10,0,100)"); Add("anim.map(0.5,0,1,-1,1)");
foreach (var (v, lo, hi) in new[] { (7d, 0d, 5d), (-1d, 0d, 5d), (12d, 2d, 8d), (-7d, -3d, 3d) })
Add($"anim.wrap({L(v)},{L(lo)},{L(hi)})");
foreach (var (t, len) in new[] { (7d, 5d), (3d, 5d), (0d, 5d), (13d, 5d), (-2d, 5d) })
Add($"anim.pingpong({L(t)},{L(len)})");
foreach (var v in new[] { -5d, 0d, 3d, 0.1d, -0.1d })
Add($"anim.sign({L(v)})");
Add("anim.oscillate(0,0,1,1)"); Add("anim.oscillate(0.25,0,1,1)"); Add("anim.oscillate(1,0,10,2)");
foreach (var (t, f) in new[] { (0d, 1d), (0.25d, 1d), (0.5d, 1d), (0.75d, 1d), (1.3d, 2d) })
{
Add($"anim.triangle({L(t)},{L(f)})");
Add($"anim.square({L(t)},{L(f)})");
}
foreach (var (t, d) in new[] { (0.5d, 1d), (2d, 1d), (0d, 1d), (0.3d, 2d) })
Add($"anim.duration({L(t)},{L(d)})");
foreach (var (t, d) in new[] { (2d, 1d), (0.5d, 1d), (3d, 0.5d) })
Add($"anim.delay({L(t)},{L(d)})");
foreach (var t in new[] { 0d, 0.25d, 0.5d, 0.75d, 1d, 0.1d })
{
Add($"anim.ease_in({L(t)})");
Add($"anim.ease_out({L(t)})");
Add($"anim.ease_in_out({L(t)})");
Add($"anim.elastic({L(t)})");
Add($"anim.back({L(t)})");
Add($"anim.bounce({L(t)})");
Add($"anim.fract({L(t + 3d)})");
}
Add("anim.step(0.5,0.6)"); Add("anim.step(0.5,0.4)"); Add("anim.step(0.5,0.5)");
Add("anim.bezier(0,0,1,2,3)"); Add("anim.bezier(1,0,1,2,3)"); Add("anim.bezier(0.5,0,0.3,0.7,1)");
Add("anim.len(3,4)"); Add("anim.len(1,1)");
Add("anim.dist(0,0,3,4)"); Add("anim.dist(1,1,4,5)");
Add("anim.dot(1,2,3,4)"); Add("anim.dot(0,0,1,1)");
foreach (var (h, s, v) in new[] { (0d, 1d, 1d), (120d, 1d, 1d), (240d, 0.5d, 0.8d), (60d, 1d, 1d), (300d, 0.7d, 0.9d) })
Tuple($"anim.hsv_to_rgb({L(h)},{L(s)},{L(v)})", 3);
foreach (var (r, g, b) in new[] { (255d, 0d, 0d), (0d, 255d, 0d), (0d, 0d, 255d), (128d, 128d, 128d), (200d, 100d, 50d) })
Tuple($"anim.rgb_to_hsv({L(r)},{L(g)},{L(b)})", 3);
foreach (var (x, y) in new[] { (3d, 4d), (-1d, 1d), (5d, 0d) })
Tuple($"anim.normalize({L(x)},{L(y)})", 2);
foreach (var (r, a) in new[] { (1d, 0d), (1d, 90d), (2d, 45d) })
Tuple($"anim.polar({L(r)},{L(a)})", 2);
foreach (var (x, y, a) in new[] { (1d, 0d, 90d), (1d, 0d, 45d), (0d, 1d, 180d) })
Tuple($"anim.rotate({L(x)},{L(y)},{L(a)})", 2);
for (int seed = 0; seed < 12; seed++)
{
Add($"anim.rand({seed})");
Add($"anim.rand(10,20,{seed})");
Add($"anim.rand(-3,3,{seed * 7 + 1})");
}
foreach (var x in new[] { 0.3d, 1.5d, 2.7d, 5.1d, -1.2d })
{
Add($"anim.noise({L(x)})");
Add($"anim.noise({L(x)},{L(x + 0.5d)})");
Add($"anim.noise({L(x)},{L(x + 0.5d)},{L(x - 0.3d)})");
}
var expected = new double[exprs.Count];
for (int i = 0; i < exprs.Count; i++)
expected[i] = _oracle.Number(exprs[i]);
string[] lines = lane.Eval(exprs);
Assert.Equal(exprs.Count, lines.Length);
var failures = new List<string>();
for (int i = 0; i < exprs.Count; i++)
{
if (!double.TryParse(lines[i], NumberStyles.Float, CultureInfo.InvariantCulture, out var got))
{
failures.Add($"{exprs[i]} => luajit '{lines[i]}' (not a number), expected {expected[i]}");
continue;
}
double tol = 1e-9 * Math.Max(1d, Math.Abs(expected[i]));
if (Math.Abs(got - expected[i]) > tol)
failures.Add($"{exprs[i]} => luajit {got}, moonsharp {expected[i]}");
}
Assert.True(failures.Count == 0,
$"{failures.Count}/{exprs.Count} mismatches:\n" + string.Join("\n", failures.GetRange(0, Math.Min(25, failures.Count))));
}
private static string L(double value) => value.ToString("R", CultureInfo.InvariantCulture);
}
}
+108
ファイルの表示
@@ -0,0 +1,108 @@
using System;
using System.Collections.Generic;
using System.Globalization;
using LuaScript.Compat;
namespace LuaScript.Tests
{
public class NativeBit32EquivalenceTests
{
private static readonly double[] Values =
[
0d, 1d, 2d, 255d, 256d, 65535d, 65536d,
2147483647d, 2147483648d, 4294967295d,
4294967296d, 4294967301d,
-1d, -2d, -256d, -2147483648d,
];
private static readonly int[] Shifts =
[
0, 1, 4, 7, 8, 15, 16, 24, 31, 32, 33, 64,
-1, -4, -8, -16, -31, -32, -33,
];
private static readonly (int Field, int Width)[] ValidFields =
[
(0, 1), (0, 8), (4, 4), (8, 8), (0, 16), (15, 16), (30, 1), (0, 31), (0, 32),
];
private static readonly (int Field, int Width)[] InvalidFields =
[
(32, 1), (0, 33), (-1, 1), (0, 0),
];
private static string Lit(double value) => value.ToString("R", CultureInfo.InvariantCulture);
[Fact]
public void CorrectBit32_MatchesAcrossMoonSharpAndLuaJit()
{
var lane = new LuaJitLane();
Assert.True(lane.Available, "native/luajit.exe must be present");
var exprs = new List<string>();
var expects = new List<object>();
void Num(string e, double v) { exprs.Add(e); expects.Add(v); }
void Bool(string e, bool v) { exprs.Add(e); expects.Add(v); }
void Err(string e) { exprs.Add(e); expects.Add("ERROR"); }
foreach (var a in Values)
{
Num($"bit32.bnot({Lit(a)})", Bit32.Bnot(a));
foreach (var b in Values)
{
Num($"bit32.band({Lit(a)},{Lit(b)})", Bit32.Band(a, b));
Num($"bit32.bor({Lit(a)},{Lit(b)})", Bit32.Bor(a, b));
Num($"bit32.bxor({Lit(a)},{Lit(b)})", Bit32.Bxor(a, b));
Bool($"bit32.btest({Lit(a)},{Lit(b)})", Bit32.Btest(a, b));
}
foreach (var n in Shifts)
{
Num($"bit32.lshift({Lit(a)},{n})", Bit32.Lshift(a, n));
Num($"bit32.rshift({Lit(a)},{n})", Bit32.Rshift(a, n));
Num($"bit32.arshift({Lit(a)},{n})", Bit32.Arshift(a, n));
Num($"bit32.lrotate({Lit(a)},{n})", Bit32.Lrotate(a, n));
Num($"bit32.rrotate({Lit(a)},{n})", Bit32.Rrotate(a, n));
}
foreach (var (field, width) in ValidFields)
{
Num($"bit32.extract({Lit(a)},{field},{width})", Bit32.Extract(a, field, width));
foreach (var v in Values)
Num($"bit32.replace({Lit(a)},{Lit(v)},{field},{width})", Bit32.Replace(a, v, field, width));
}
foreach (var (field, width) in InvalidFields)
{
Err($"bit32.extract({Lit(a)},{field},{width})");
Err($"bit32.replace({Lit(a)},1,{field},{width})");
}
}
string[] lines = lane.Eval(exprs);
Assert.Equal(exprs.Count, lines.Length);
var failures = new List<string>();
for (int i = 0; i < exprs.Count; i++)
{
string actual = lines[i];
switch (expects[i])
{
case double d:
if (!double.TryParse(actual, NumberStyles.Float, CultureInfo.InvariantCulture, out var got) || got != d)
failures.Add($"{exprs[i]} => luajit '{actual}', expected {d}");
break;
case bool b:
if (actual != (b ? "true" : "false"))
failures.Add($"{exprs[i]} => luajit '{actual}', expected {b}");
break;
case string s:
if (actual != s)
failures.Add($"{exprs[i]} => luajit '{actual}', expected {s}");
break;
}
}
Assert.True(failures.Count == 0,
$"{failures.Count}/{exprs.Count} mismatches:\n" + string.Join("\n", failures.GetRange(0, Math.Min(20, failures.Count))));
}
}
}
+78
ファイルの表示
@@ -0,0 +1,78 @@
using System;
using System.Diagnostics;
using System.IO;
using System.IO.MemoryMappedFiles;
namespace LuaScript.Tests
{
public class NativeSharedMemoryTests
{
private static string NativeDir => Path.Combine(AppContext.BaseDirectory, "native");
[Fact]
public void Worker_ProcessesSharedBgraBuffer_ViaFfi()
{
string luajit = Path.Combine(NativeDir, "luajit.exe");
Assert.True(File.Exists(luajit), "native/luajit.exe must be present");
const int width = 8;
const int height = 8;
const int pixels = width * height;
long size = pixels * 4L;
string mapName = "LuaScriptShmPoC_" + Guid.NewGuid().ToString("N");
using var mmf = MemoryMappedFile.CreateNew(mapName, size);
var expectedGray = new byte[pixels];
using (var acc = mmf.CreateViewAccessor())
{
for (int i = 0; i < pixels; i++)
{
byte b = (byte)(i * 3 % 256);
byte g = (byte)(i * 5 % 256);
byte r = (byte)(i * 7 % 256);
acc.Write(i * 4 + 0, b);
acc.Write(i * 4 + 1, g);
acc.Write(i * 4 + 2, r);
acc.Write(i * 4 + 3, (byte)255);
expectedGray[i] = (byte)Math.Min(255, (int)Math.Floor(r * 0.299 + g * 0.587 + b * 0.114 + 0.5));
}
}
var psi = new ProcessStartInfo
{
FileName = luajit,
WorkingDirectory = NativeDir,
RedirectStandardOutput = true,
RedirectStandardError = true,
UseShellExecute = false,
};
psi.ArgumentList.Add("worker_grayscale.lua");
psi.ArgumentList.Add(mapName);
psi.ArgumentList.Add(size.ToString());
using var process = Process.Start(psi)!;
string stdout = process.StandardOutput.ReadToEnd();
string stderr = process.StandardError.ReadToEnd();
Assert.True(process.WaitForExit(5000), "worker should finish quickly");
Assert.Equal(0, process.ExitCode);
Assert.Equal("done", stdout);
Assert.Equal("", stderr);
using (var acc = mmf.CreateViewAccessor())
{
for (int i = 0; i < pixels; i++)
{
byte b = acc.ReadByte(i * 4 + 0);
byte g = acc.ReadByte(i * 4 + 1);
byte r = acc.ReadByte(i * 4 + 2);
byte a = acc.ReadByte(i * 4 + 3);
Assert.Equal(expectedGray[i], b);
Assert.Equal(expectedGray[i], g);
Assert.Equal(expectedGray[i], r);
Assert.Equal(255, a);
}
}
}
}
}
+264
ファイルの表示
@@ -0,0 +1,264 @@
using System;
using System.IO;
using LuaScript.Engine;
namespace LuaScript.Tests
{
public class NativeWorkerRoundTripTests : IDisposable
{
private static string NativeDir => Path.Combine(AppContext.BaseDirectory, "native");
private static readonly Func<string, int, SceneObjectInfo?> NoResolver = (_, _) => null;
private readonly LuaJitWorker _worker = new(NativeDir);
public void Dispose() => _worker.Dispose();
private static double[] Fields(int w, int h, double time)
{
var f = new double[NativeProtocol.FieldCount];
f[NativeProtocol.W] = w;
f[NativeProtocol.H] = h;
f[NativeProtocol.Time] = time;
f[NativeProtocol.Alpha] = 255d;
return f;
}
[Fact]
public void TransformScript_WritesBackObjFields()
{
Assert.True(LuaJitWorker.IsAvailable(NativeDir), "native/luajit.exe must be present");
var fields = Fields(4, 4, 2d);
var pixels = new byte[4 * 4 * 4];
bool ok = _worker.Execute(
"obj.rz = obj.time * 90\nobj.alpha = 128",
fields, pixels, 4, 4, 5000, NoResolver, out bool dirty, out string? error);
Assert.True(ok, error);
Assert.False(dirty);
Assert.Equal(180d, fields[NativeProtocol.Rz]);
Assert.Equal(128d, fields[NativeProtocol.Alpha]);
}
[Fact]
public void PixelScript_MatchesExpectedGrayscale()
{
Assert.True(LuaJitWorker.IsAvailable(NativeDir), "native/luajit.exe must be present");
const int w = 2, h = 2;
var pixels = new byte[w * h * 4];
void SetBgra(int i, byte b, byte g, byte r, byte a)
{
pixels[i * 4 + 0] = b; pixels[i * 4 + 1] = g; pixels[i * 4 + 2] = r; pixels[i * 4 + 3] = a;
}
SetBgra(0, 10, 20, 30, 255);
SetBgra(1, 0, 0, 0, 0);
SetBgra(2, 50, 100, 200, 128);
SetBgra(3, 255, 255, 255, 255);
var expected = (byte[])pixels.Clone();
for (int i = 0; i < w * h; i++)
Grayscale(expected, i);
var fields = Fields(w, h, 0d);
const string script =
"for y=0,obj.h-1 do for x=0,obj.w-1 do " +
"local r,g,b,a = obj.getpixel(x,y) " +
"local gray = r*0.299 + g*0.587 + b*0.114 " +
"obj.setpixel(x,y,gray,gray,gray,a) end end";
bool ok = _worker.Execute(script, fields, pixels, w, h, 5000, NoResolver, out bool dirty, out string? error);
Assert.True(ok, error);
Assert.True(dirty);
Assert.Equal(expected, pixels);
}
[Fact]
public void PixelDataProxy_MatchesExpectedGrayscale()
{
Assert.True(LuaJitWorker.IsAvailable(NativeDir), "native/luajit.exe must be present");
const int w = 2, h = 2;
var pixels = new byte[w * h * 4];
void SetBgra(int i, byte b, byte g, byte r, byte a)
{
pixels[i * 4 + 0] = b; pixels[i * 4 + 1] = g; pixels[i * 4 + 2] = r; pixels[i * 4 + 3] = a;
}
SetBgra(0, 10, 20, 30, 255);
SetBgra(1, 0, 0, 0, 0);
SetBgra(2, 50, 100, 200, 128);
SetBgra(3, 255, 255, 255, 255);
var expected = (byte[])pixels.Clone();
for (int i = 0; i < w * h; i++)
Grayscale(expected, i);
var fields = Fields(w, h, 0d);
const string script =
"local pd = obj.getpixeldata() local w,h = pd.width, pd.height " +
"for y=0,h-1 do for x=0,w-1 do local base=(y*w+x)*4 " +
"local r=pd:get(base+1) local g=pd:get(base+2) local b=pd:get(base+3) " +
"local gray=r*0.299+g*0.587+b*0.114 " +
"pd:set(base+1,gray) pd:set(base+2,gray) pd:set(base+3,gray) end end";
bool ok = _worker.Execute(script, fields, pixels, w, h, 5000, NoResolver, out bool dirty, out string? error);
Assert.True(ok, error);
Assert.True(dirty);
Assert.Equal(expected, pixels);
}
private static void Grayscale(byte[] px, int i)
{
double b = px[i * 4 + 0], g = px[i * 4 + 1], r = px[i * 4 + 2], a = px[i * 4 + 3];
double sr, sg, sb;
if (a <= 0d) { sr = sg = sb = 0d; }
else
{
double s = 255d / a;
sr = Math.Clamp(r * s, 0d, 255d);
sg = Math.Clamp(g * s, 0d, 255d);
sb = Math.Clamp(b * s, 0d, 255d);
}
double gray = sr * 0.299 + sg * 0.587 + sb * 0.114;
double aK = Math.Clamp(a, 0d, 255d) / 255d;
px[i * 4 + 0] = (byte)Math.Floor(Math.Clamp(gray * aK, 0d, 255d));
px[i * 4 + 1] = (byte)Math.Floor(Math.Clamp(gray * aK, 0d, 255d));
px[i * 4 + 2] = (byte)Math.Floor(Math.Clamp(gray * aK, 0d, 255d));
px[i * 4 + 3] = (byte)Math.Floor(Math.Clamp(a, 0d, 255d));
}
[Fact]
public void PersistentWorker_HandlesMultipleCalls()
{
Assert.True(LuaJitWorker.IsAvailable(NativeDir), "native/luajit.exe must be present");
var pixels = new byte[16];
for (int k = 1; k <= 5; k++)
{
var fields = Fields(2, 2, k);
bool ok = _worker.Execute("obj.x = obj.time * 10", fields, pixels, 2, 2, 5000, NoResolver, out _, out string? error);
Assert.True(ok, error);
Assert.Equal(k * 10d, fields[NativeProtocol.X]);
}
}
[Fact]
public void Timeout_KillsWorker_AndRecovers()
{
Assert.True(LuaJitWorker.IsAvailable(NativeDir), "native/luajit.exe must be present");
var pixels = new byte[16];
var fields = Fields(2, 2, 0d);
bool timedOut = _worker.Execute(
"local x=0 while true do x=x+1 end", fields, pixels, 2, 2, 1500, NoResolver, out _, out string? error);
Assert.False(timedOut);
Assert.Contains("timed out", error);
var fields2 = Fields(2, 2, 3d);
bool ok = _worker.Execute("obj.x = obj.time", fields2, pixels, 2, 2, 5000, NoResolver, out _, out error);
Assert.True(ok, error);
Assert.Equal(3d, fields2[NativeProtocol.X]);
}
[Fact]
public void GetObject_ResolvesThroughCallback()
{
Assert.True(LuaJitWorker.IsAvailable(NativeDir), "native/luajit.exe must be present");
var pixels = new byte[16];
var fields = Fields(2, 2, 0d);
var resolved = new SceneObjectInfo("a", true, 12d, 34d, 56d, 2d, 90d, 200d, 7);
Func<string, int, SceneObjectInfo?> resolver = (tag, frame) =>
tag == "a" && frame == 5 ? resolved : null;
const string script =
"local o = obj.getobject(\"a\", 5) " +
"obj.x = o.x obj.y = o.y obj.z = o.z " +
"obj.zoom = o.zoom obj.rz = o.rz obj.alpha = o.alpha " +
"obj.sx = o.sy obj.rzr = o.rzr";
bool ok = _worker.Execute(script, fields, pixels, 2, 2, 5000, resolver, out _, out string? error);
Assert.True(ok, error);
Assert.Equal(12d, fields[NativeProtocol.X]);
Assert.Equal(34d, fields[NativeProtocol.Y]);
Assert.Equal(56d, fields[NativeProtocol.Z]);
Assert.Equal(2d, fields[NativeProtocol.Zoom]);
Assert.Equal(90d, fields[NativeProtocol.Rz]);
Assert.Equal(200d, fields[NativeProtocol.Alpha]);
Assert.Equal(2d, fields[NativeProtocol.Sx]);
Assert.Equal(90d * Math.PI / 180d, fields[NativeProtocol.Rzr]);
}
[Fact]
public void GetObject_CachesRepeatedQueryAndResetsEachRun()
{
Assert.True(LuaJitWorker.IsAvailable(NativeDir), "native/luajit.exe must be present");
var pixels = new byte[16];
int calls = 0;
double x = 10d;
Func<string, int, SceneObjectInfo?> resolver = (tag, frame) =>
{
calls++;
return tag == "a" ? new SceneObjectInfo("a", true, x, 0, 0, 1, 0, 255, 0) : null;
};
const string script =
"local a = obj.getobject(\"a\") " +
"local b = obj.getobject(\"a\") " +
"obj.x = a.x + b.x";
bool ok = _worker.Execute(script, Fields(2, 2, 0d), pixels, 2, 2, 5000, resolver, 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, pixels, 2, 2, 5000, resolver, out _, out error);
Assert.True(ok, error);
Assert.Equal(2, calls);
Assert.Equal(40d, fields[NativeProtocol.X]);
}
[Fact]
public void GetObject_ReturnsNil_WhenUnresolved()
{
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 =
"local o = obj.getobject(\"missing\") obj.x = o == nil and 1 or 0";
bool ok = _worker.Execute(script, fields, pixels, 2, 2, 5000, NoResolver, out _, out string? error);
Assert.True(ok, error);
Assert.Equal(1d, fields[NativeProtocol.X]);
}
[Fact]
public void RuntimeError_IsReported_AndWorkerSurvives()
{
Assert.True(LuaJitWorker.IsAvailable(NativeDir), "native/luajit.exe must be present");
var pixels = new byte[16];
var fields = Fields(2, 2, 0d);
bool ok = _worker.Execute("obj.x = missing.value", fields, pixels, 2, 2, 5000, NoResolver, out _, out string? error);
Assert.False(ok);
Assert.False(string.IsNullOrEmpty(error));
var fields2 = Fields(2, 2, 7d);
bool ok2 = _worker.Execute("obj.x = obj.time", fields2, pixels, 2, 2, 5000, NoResolver, out _, out error);
Assert.True(ok2, error);
Assert.Equal(7d, fields2[NativeProtocol.X]);
}
}
}
+52
ファイルの表示
@@ -0,0 +1,52 @@
using System;
using System.Diagnostics;
using System.IO;
namespace LuaScript.Tests
{
public class NativeWorkerTimeoutTests
{
private static string LuaJit => Path.Combine(AppContext.BaseDirectory, "native", "luajit.exe");
private static Process Launch(string inlineScript)
{
var psi = new ProcessStartInfo
{
FileName = LuaJit,
WorkingDirectory = Path.GetDirectoryName(LuaJit)!,
RedirectStandardOutput = true,
RedirectStandardError = true,
UseShellExecute = false,
};
psi.ArgumentList.Add("-e");
psi.ArgumentList.Add(inlineScript);
return Process.Start(psi) ?? throw new InvalidOperationException("failed to start luajit");
}
[Fact]
public void JitCompiledInfiniteLoop_IsHardKilledWithinTimeout_AndHostRecovers()
{
Assert.True(File.Exists(LuaJit), "native/luajit.exe must be present");
const int timeoutMs = 1500;
using (var hung = Launch("local x=0 for i=1,1e9 do for j=1,1e9 do x=x+1 end end"))
{
bool exitedOnItsOwn = hung.WaitForExit(timeoutMs);
Assert.False(exitedOnItsOwn, "the hot loop should still be running at the timeout");
var sw = Stopwatch.StartNew();
hung.Kill(entireProcessTree: true);
Assert.True(hung.WaitForExit(2000), "the process must terminate promptly after Kill");
sw.Stop();
Assert.True(sw.ElapsedMilliseconds < 2000, "kill should take effect quickly");
}
using var ok = Launch("io.write('recovered')");
string output = ok.StandardOutput.ReadToEnd();
Assert.True(ok.WaitForExit(5000), "a fresh worker must run after the previous was killed");
Assert.Equal(0, ok.ExitCode);
Assert.Equal("recovered", output);
}
}
}
+85
ファイルの表示
@@ -0,0 +1,85 @@
using MoonSharp.Interpreter;
namespace LuaScript.Tests
{
public class RawAndBasicTests
{
private readonly MoonSharpLane _lane = new();
[Fact]
public void RawLen_Table() => Assert.Equal(3d, _lane.Number("rawlen({10,20,30})"));
[Fact]
public void RawLen_String() => Assert.Equal(5d, _lane.Number("rawlen('hello')"));
[Fact]
public void RawEqual_SameReference()
{
Assert.True(_lane.Boolean("(function() local t={} return rawequal(t,t) end)()"));
Assert.False(_lane.Boolean("rawequal({},{})"));
}
[Fact]
public void RawGetSet_BypassMetatable()
{
Assert.Equal(7d, _lane.Number(
"(function() local t=setmetatable({},{__index=function() return 99 end}) rawset(t,'k',7) return rawget(t,'k') end)()"));
Assert.Equal(99d, _lane.Number(
"(function() local t=setmetatable({},{__index=function() return 99 end}) return t.missing end)()"));
}
[Fact]
public void Select_Count() => Assert.Equal(3d, _lane.Number("select('#', 'a', 'b', 'c')"));
[Fact]
public void Select_Index() => Assert.Equal(20d, _lane.Number("(select(2, 10, 20, 30))"));
[Theory]
[InlineData("type(1)", "number")]
[InlineData("type('x')", "string")]
[InlineData("type({})", "table")]
[InlineData("type(nil)", "nil")]
[InlineData("type(true)", "boolean")]
[InlineData("type(print)", "function")]
public void Type_Names(string expression, string expected) =>
Assert.Equal(expected, _lane.Text(expression));
[Theory]
[InlineData("tonumber('42')", 42d)]
[InlineData("tonumber('10', 2)", 2d)]
[InlineData("tonumber('ff', 16)", 255d)]
public void ToNumber_Parsing(string expression, double expected) =>
Assert.Equal(expected, _lane.Number(expression));
[Fact]
public void ToNumber_InvalidIsNil() =>
Assert.Equal(DataType.Nil, _lane.Type("tonumber('not a number')"));
[Fact]
public void ToNumber_HexStringPrefix_IsNil_MoonSharpDivergence() =>
Assert.Equal(DataType.Nil, _lane.Type("tonumber('0x1F')"));
[Fact]
public void Unpack_Global() =>
Assert.Equal(6d, _lane.Number("(function() local a,b,c = unpack({1,2,3}) return a+b+c end)()"));
[Fact]
public void Pcall_CapturesError() =>
Assert.False(_lane.Boolean("(function() local ok = pcall(function() error('boom') end) return ok end)()"));
[Fact]
public void Pcall_SuccessReturnsTrue() =>
Assert.True(_lane.Boolean("(function() local ok = pcall(function() return 1 end) return ok end)()"));
[Fact]
public void StringFormat_Basic() =>
Assert.Equal("a=5 b=2.50", _lane.Text("string.format('a=%d b=%.2f', 5, 2.5)"));
[Fact]
public void MathFloorCeil()
{
Assert.Equal(3d, _lane.Number("math.floor(3.7)"));
Assert.Equal(4d, _lane.Number("math.ceil(3.2)"));
}
}
}
+48
ファイルの表示
@@ -0,0 +1,48 @@
using LuaScript.Engine;
namespace LuaScript.Tests
{
public class ScriptDirectiveTests
{
[Theory]
[InlineData(null, "MoonSharp")]
[InlineData("", "MoonSharp")]
[InlineData("obj.rz = time * 90", "MoonSharp")]
[InlineData("--!native", "Native")]
[InlineData("--!gpu", "Gpu")]
[InlineData("--!cpu", "Cpu")]
[InlineData("--!moonsharp", "MoonSharp")]
[InlineData("--! native ", "Native")]
[InlineData("--!NATIVE", "Native")]
[InlineData("\r\n --!gpu\r\nfunction pixel() end", "Gpu")]
[InlineData("-- normal comment\n--!native\nobj.x = 0", "Native")]
[InlineData("--!unknown", "MoonSharp")]
[InlineData("--!native extra", "MoonSharp")]
[InlineData("obj.x=0 --!native", "MoonSharp")]
public void Resolve_ReturnsExpectedEngine(string? script, string expected)
{
Assert.Equal(expected, ScriptDirective.Resolve(script).ToString());
}
[Fact]
public void Resolve_FirstDirectiveWins()
{
Assert.Equal("Native", ScriptDirective.Resolve("--!native\n--!gpu").ToString());
}
[Theory]
[InlineData("obj.rz = time * 90", "MoonSharp")]
[InlineData("local r,g,b,a = obj.getpixel(0,0)", "Native")]
[InlineData("obj.setpixel(0,0,255,0,0)", "Native")]
[InlineData("local pd = obj.getpixeldata()", "Native")]
[InlineData("--!moonsharp\nobj.setpixel(0,0,1,1,1)", "MoonSharp")]
[InlineData("--!native\nobj.rz = 1", "Native")]
[InlineData("obj.load(\"figure\", \"円\", 0xff0000, 100)", "MoonSharp")]
[InlineData("obj.load(\"figure\", \"円\", 0xff0000, 100)\nlocal r = obj.getpixel(0,0)", "MoonSharp")]
[InlineData("--!native\nobj.load(\"figure\", \"円\", 0xff0000, 100)", "Native")]
public void ResolveAuto_RoutesPixelScriptsToNative(string script, string expected)
{
Assert.Equal(expected, ScriptDirective.ResolveAuto(script).ToString());
}
}
}
+1
ファイルの表示
@@ -3,6 +3,7 @@
<Platform Name="Any CPU" />
<Platform Name="x64" />
</Configurations>
<Project Path="LuaScript.Tests/LuaScript.Tests.csproj" />
<Project Path="LuaScript/LuaScript.csproj">
<Platform Solution="*|x64" Project="x64" />
</Project>
+17
ファイルの表示
@@ -0,0 +1,17 @@
using System.Collections.Generic;
namespace LuaScript
{
internal sealed class AviUtlEffectRequest
{
public string Name { get; }
public IReadOnlyList<KeyValuePair<string, object>> Arguments { get; }
public AviUtlEffectRequest(string name, IReadOnlyList<KeyValuePair<string, object>> arguments)
{
Name = name;
Arguments = arguments;
}
}
}
+61 -29
ファイルの表示
@@ -2,12 +2,12 @@ namespace LuaScript
{
internal sealed class AviUtlScriptContext
{
public bool IsPlaying { get; init; }
public bool IsPaused { get; init; }
public string SceneId { get; init; } = string.Empty;
public bool IsPlaying { get; set; }
public bool IsPaused { get; set; }
public string SceneId { get; set; } = string.Empty;
public int ImageWidth { get; init; }
public int ImageHeight { get; init; }
public int ImageWidth { get; set; }
public int ImageHeight { get; set; }
public double X { get; set; }
public double Y { get; set; }
@@ -24,56 +24,87 @@ namespace LuaScript
public double Ry { get; set; }
public double Rz { get; set; }
public double Track0 { get; init; }
public double Track1 { get; init; }
public double Track2 { get; init; }
public double Track3 { get; init; }
public double Track0 { get; set; }
public double Track1 { get; set; }
public double Track2 { get; set; }
public double Track3 { get; set; }
public double Time { get; init; }
public int Frame { get; init; }
public int TotalFrame { get; init; }
public double TotalTime { get; init; }
public int Framerate { get; init; }
public int TimelineFrame { get; init; }
public double TimelineTime { get; init; }
public int SceneWidth { get; init; }
public int SceneHeight { get; init; }
public int Layer { get; init; }
public int Index { get; init; }
public int Num { get; init; }
public bool Check0 { get; set; }
public bool Check1 { get; set; }
public bool Check2 { get; set; }
public bool Check3 { get; set; }
public SceneObjectResolver? Resolver { get; init; }
public bool HasColor { get; set; }
public double ColorValue { get; set; }
public double Time { get; set; }
public int Frame { get; set; }
public int TotalFrame { get; set; }
public double TotalTime { get; set; }
public int Framerate { get; set; }
public int TimelineFrame { get; set; }
public double TimelineTime { get; set; }
public int SceneWidth { get; set; }
public int SceneHeight { get; set; }
public int Layer { get; set; }
public int Index { get; set; }
public int Num { get; set; }
public Func<SceneObjectResolver>? ResolverProvider { get; set; }
private readonly List<SceneObjectQuery> _objectQueries = [];
public IReadOnlyList<SceneObjectQuery> ObjectQueries => _objectQueries;
private readonly List<AviUtlEffectRequest> _effectRequests = [];
public IReadOnlyList<AviUtlEffectRequest> EffectRequests => _effectRequests;
internal void AddEffect(AviUtlEffectRequest request) => _effectRequests.Add(request);
internal void ClearEffects() => _effectRequests.Clear();
public double RxRad => Rx * Math.PI / 180d;
public double RyRad => Ry * Math.PI / 180d;
public double RzRad => Rz * Math.PI / 180d;
public int GroupIndex { get; init; }
public int GroupCount { get; init; }
public int TimelineTotalFrame { get; init; }
public double TimelineTotalTime { get; init; }
public bool IsSaving { get; init; }
public double TimeRatio { get; init; }
public int GroupIndex { get; set; }
public int GroupCount { get; set; }
public int TimelineTotalFrame { get; set; }
public double TimelineTotalTime { get; set; }
public bool IsSaving { get; set; }
public double TimeRatio { get; set; }
private Func<byte[]>? _pixelLoader;
private byte[]? _pixelBuffer;
private bool _pixelBufferLoaded;
private bool _isPixelsDirty;
private bool _bufferReplaced;
public bool IsPixelsDirty => _isPixelsDirty;
public bool BufferReplaced => _bufferReplaced;
internal int TotalChannels => ImageWidth * ImageHeight * 4;
internal void ClearQueries() => _objectQueries.Clear();
internal void SetPixelLoader(Func<byte[]> loader)
{
_pixelLoader = loader;
_pixelBuffer = null;
_pixelBufferLoaded = false;
_isPixelsDirty = false;
_bufferReplaced = false;
}
internal void ReplaceBuffer(byte[] buffer, int width, int height)
{
_pixelBuffer = buffer;
_pixelBufferLoaded = true;
_isPixelsDirty = true;
_bufferReplaced = true;
ImageWidth = width;
ImageHeight = height;
}
internal void EnsurePixelBuffer()
@@ -89,7 +120,8 @@ namespace LuaScript
public bool ResolveObject(string tag, int frame, out SceneObjectInfo info)
{
if (Resolver is not null && Resolver.TryResolve(tag, frame, out var resolved))
var resolver = ResolverProvider?.Invoke();
if (resolver is not null && resolver.TryResolve(tag, frame, out var resolved))
{
_objectQueries.Add(new SceneObjectQuery(tag, frame, resolved));
info = resolved;
+200
ファイルの表示
@@ -0,0 +1,200 @@
using System;
using System.Globalization;
namespace LuaScript.Compat
{
internal sealed class AviUtlParameterLayout
{
public const int MaxTracks = 4;
public const int MaxChecks = 4;
public readonly record struct TrackParam(int Index, string Name, double Min, double Max, double Default, double Step);
public readonly record struct CheckParam(int Index, string Name, bool Default);
public readonly record struct ColorParam(int Default);
private readonly TrackParam?[] _tracks = new TrackParam?[MaxTracks];
private readonly CheckParam?[] _checks = new CheckParam?[MaxChecks];
public static readonly AviUtlParameterLayout Empty = new();
public TrackParam? GetTrack(int index) => (uint)index < MaxTracks ? _tracks[index] : null;
public CheckParam? GetCheck(int index) => (uint)index < MaxChecks ? _checks[index] : null;
public ColorParam? Color { get; private set; }
public bool HasTrack(int index) => GetTrack(index).HasValue;
public bool HasCheck(int index) => GetCheck(index).HasValue;
public bool HasColor => Color.HasValue;
public bool HasAny
{
get
{
for (int i = 0; i < MaxTracks; i++)
if (_tracks[i].HasValue) return true;
for (int i = 0; i < MaxChecks; i++)
if (_checks[i].HasValue) return true;
return HasColor;
}
}
public static AviUtlParameterLayout Parse(string? source)
{
var layout = new AviUtlParameterLayout();
if (string.IsNullOrEmpty(source))
return layout;
var lines = source.Replace("\r\n", "\n").Replace("\r", "\n").Split('\n');
int sectionStart = 0;
int sectionEnd = lines.Length;
for (int i = 0; i < lines.Length; i++)
{
if (!IsSectionHeader(lines[i]))
continue;
sectionStart = i + 1;
sectionEnd = lines.Length;
for (int j = sectionStart; j < lines.Length; j++)
{
if (IsSectionHeader(lines[j]))
{
sectionEnd = j;
break;
}
}
break;
}
for (int i = sectionStart; i < sectionEnd; i++)
layout.ParseLine(lines[i]);
return layout;
}
private void ParseLine(string line)
{
int i = SkipSpaces(line, 0);
if (i + 1 >= line.Length || line[i] != '-' || line[i + 1] != '-')
return;
i += 2;
if (i < line.Length && line[i] == '!')
return;
int nameStart = i;
while (i < line.Length && IsNameChar(line[i]))
i++;
if (i >= line.Length || line[i] != ':')
return;
string name = line.Substring(nameStart, i - nameStart);
string content = line.Substring(i + 1);
if (name.StartsWith("track", StringComparison.OrdinalIgnoreCase) &&
TryGetIndex(name, 5, MaxTracks, out int trackIndex))
{
ParseTrack(trackIndex, content);
}
else if (name.StartsWith("check", StringComparison.OrdinalIgnoreCase) &&
TryGetIndex(name, 5, MaxChecks, out int checkIndex))
{
ParseCheck(checkIndex, content);
}
else if (name.Equals("color", StringComparison.OrdinalIgnoreCase))
{
ParseColor(content);
}
}
private void ParseTrack(int index, string content)
{
var parts = content.Split(',');
string trackName = parts.Length > 0 ? parts[0].Trim() : string.Empty;
double min = ParseNumber(parts, 1, 0d);
double max = ParseNumber(parts, 2, 100d);
double def = ParseNumber(parts, 3, min);
double step = ParseNumber(parts, 4, 0d);
if (max < min)
(min, max) = (max, min);
def = Math.Clamp(def, min, max);
_tracks[index] = new TrackParam(index, trackName, min, max, def, step);
}
private void ParseCheck(int index, string content)
{
var parts = content.Split(',');
string checkName = parts.Length > 0 ? parts[0].Trim() : string.Empty;
double def = ParseNumber(parts, 1, 0d);
_checks[index] = new CheckParam(index, checkName, def != 0d);
}
private void ParseColor(string content)
{
string token = FirstToken(content);
if (TryParseColorLiteral(token, out int rgb))
Color = new ColorParam(rgb);
}
private static bool TryGetIndex(string name, int start, int max, out int index)
{
index = -1;
if (name.Length != start + 1)
return false;
char c = name[start];
if (c < '0' || c > '9')
return false;
int value = c - '0';
if (value >= max)
return false;
index = value;
return true;
}
private static double ParseNumber(string[] parts, int idx, double fallback)
{
if (idx >= parts.Length)
return fallback;
string token = parts[idx].Trim();
return double.TryParse(token, NumberStyles.Float, CultureInfo.InvariantCulture, out double value)
? value
: fallback;
}
private static bool TryParseColorLiteral(string token, out int rgb)
{
rgb = 0;
if (token.Length == 0)
return false;
if (token.StartsWith("0x", StringComparison.OrdinalIgnoreCase) || token.StartsWith("0X", StringComparison.Ordinal))
{
if (token.Length <= 2)
return false;
return int.TryParse(token.AsSpan(2), NumberStyles.HexNumber, CultureInfo.InvariantCulture, out rgb);
}
return int.TryParse(token, NumberStyles.Integer, CultureInfo.InvariantCulture, out rgb);
}
private static string FirstToken(string content)
{
int start = SkipSpaces(content, 0);
int i = start;
while (i < content.Length && content[i] != ',' && content[i] != ' ' && content[i] != '\t')
i++;
return content.Substring(start, i - start);
}
private static bool IsSectionHeader(string line)
{
int i = SkipSpaces(line, 0);
return i < line.Length && line[i] == '@';
}
private static int SkipSpaces(string text, int index)
{
while (index < text.Length && (text[index] == ' ' || text[index] == '\t'))
index++;
return index;
}
private static bool IsNameChar(char c) =>
(c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z') || (c >= '0' && c <= '9');
}
}
+30
ファイルの表示
@@ -0,0 +1,30 @@
using System;
namespace LuaScript.Compat
{
internal static class AviUtlRandom
{
public static double Next(double a, double b, double seed, double frame)
{
long seedBits = BitConverter.DoubleToInt64Bits(seed);
long frameBits = BitConverter.DoubleToInt64Bits(frame);
uint s = (uint)(seedBits ^ (seedBits >> 32));
uint f = (uint)(frameBits ^ (frameBits >> 32));
uint h = s * 374761393u + f * 668265263u;
h = (h ^ (h >> 13)) * 1274126177u;
h ^= h >> 16;
double r = h / 4294967295.0;
long lo = (long)Math.Floor(Math.Min(a, b));
long hi = (long)Math.Floor(Math.Max(a, b));
long span = hi - lo + 1L;
if (span <= 1L)
return lo;
long value = lo + (long)(r * span);
return value > hi ? hi : value;
}
}
}
+139
ファイルの表示
@@ -0,0 +1,139 @@
using System;
using System.Collections.Generic;
using System.Text;
namespace LuaScript.Compat
{
internal static class AviUtlScript
{
private enum DirectiveKind
{
None,
Dialog,
Param,
}
public static string Transform(string source)
{
if (string.IsNullOrEmpty(source))
return source;
var lines = source.Replace("\r\n", "\n").Replace("\r", "\n").Split('\n');
int sectionStart = 0;
int sectionEnd = lines.Length;
bool hasSection = false;
for (int i = 0; i < lines.Length; i++)
{
if (!IsSectionHeader(lines[i]))
continue;
hasSection = true;
sectionStart = i + 1;
sectionEnd = lines.Length;
for (int j = sectionStart; j < lines.Length; j++)
{
if (IsSectionHeader(lines[j]))
{
sectionEnd = j;
break;
}
}
break;
}
var prelude = new List<string>();
for (int i = sectionStart; i < sectionEnd; i++)
AppendDeclarations(lines[i], prelude);
if (!hasSection && prelude.Count == 0)
return source;
var builder = new StringBuilder(source.Length + 64);
foreach (var declaration in prelude)
builder.Append(declaration).Append('\n');
for (int i = sectionStart; i < sectionEnd; i++)
builder.Append(lines[i]).Append('\n');
return builder.ToString();
}
private static bool IsSectionHeader(string line)
{
int i = SkipSpaces(line, 0);
return i < line.Length && line[i] == '@';
}
private static void AppendDeclarations(string line, List<string> prelude)
{
int i = SkipSpaces(line, 0);
if (i + 1 >= line.Length || line[i] != '-' || line[i + 1] != '-')
return;
i += 2;
if (i < line.Length && line[i] == '!')
return;
int nameStart = i;
while (i < line.Length && IsNameChar(line[i]))
i++;
if (i >= line.Length || line[i] != ':')
return;
string name = line.Substring(nameStart, i - nameStart);
string content = line.Substring(i + 1);
switch (Classify(name))
{
case DirectiveKind.Dialog:
AppendDialog(content, prelude);
break;
case DirectiveKind.Param:
AppendParam(content, prelude);
break;
}
}
private static DirectiveKind Classify(string name)
{
if (name.Equals("dialog", StringComparison.OrdinalIgnoreCase))
return DirectiveKind.Dialog;
if (name.Equals("param", StringComparison.OrdinalIgnoreCase))
return DirectiveKind.Param;
return DirectiveKind.None;
}
private static void AppendDialog(string content, List<string> prelude)
{
foreach (var segment in content.Split(';'))
{
string trimmed = segment.Trim();
if (trimmed.Length == 0)
continue;
int comma = trimmed.IndexOf(',');
if (comma < 0)
continue;
string declaration = trimmed.Substring(comma + 1).Trim();
if (declaration.Length != 0)
prelude.Add(declaration);
}
}
private static void AppendParam(string content, List<string> prelude)
{
string trimmed = content.Trim();
if (trimmed.Length != 0)
prelude.Add(trimmed);
}
private static int SkipSpaces(string text, int index)
{
while (index < text.Length && (text[index] == ' ' || text[index] == '\t'))
index++;
return index;
}
private static bool IsNameChar(char c) =>
(c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z') || (c >= '0' && c <= '9');
}
}
+109
ファイルの表示
@@ -0,0 +1,109 @@
using System;
namespace LuaScript.Compat
{
internal static class Bit32
{
public static uint ToUInt32(double value) => unchecked((uint)(long)value);
public static uint Band(params double[] values)
{
uint accum = 0xFFFFFFFFu;
foreach (var value in values)
accum &= ToUInt32(value);
return accum;
}
public static uint Bor(params double[] values)
{
uint accum = 0u;
foreach (var value in values)
accum |= ToUInt32(value);
return accum;
}
public static uint Bxor(params double[] values)
{
uint accum = 0u;
foreach (var value in values)
accum ^= ToUInt32(value);
return accum;
}
public static bool Btest(params double[] values) => Band(values) != 0u;
public static uint Bnot(double value) => ~ToUInt32(value);
public static uint Lshift(double value, double shift)
{
uint v = ToUInt32(value);
int a = (int)shift;
if (a <= -32 || a >= 32)
return 0u;
return a >= 0 ? v << a : v >> -a;
}
public static uint Rshift(double value, double shift) => Lshift(value, -shift);
public static uint Arshift(double value, double shift)
{
uint v = ToUInt32(value);
int a = (int)shift;
if (a < 0)
return Lshift(value, -shift);
bool negative = (v & 0x80000000u) != 0u;
if (a >= 32)
return negative ? 0xFFFFFFFFu : 0u;
if (a == 0)
return v;
uint result = v >> a;
if (negative)
result |= ~0u << (32 - a);
return result;
}
public static uint Lrotate(double value, double shift)
{
uint v = ToUInt32(value);
int a = ((int)shift % 32 + 32) % 32;
return a == 0 ? v : (v << a) | (v >> (32 - a));
}
public static uint Rrotate(double value, double shift) => Lrotate(value, -shift);
public static uint Extract(double value, double pos, double? width)
{
uint v = ToUInt32(value);
int p = (int)pos;
int w = width is null ? 1 : (int)width.Value;
ValidatePosWidth(p, w);
return (v >> p) & NBitMask(w);
}
public static uint Replace(double value, double replacement, double pos, double? width)
{
uint v = ToUInt32(value);
uint u = ToUInt32(replacement);
int p = (int)pos;
int w = width is null ? 1 : (int)width.Value;
ValidatePosWidth(p, w);
uint mask = NBitMask(w) << p;
return (v & ~mask) | ((u & NBitMask(w)) << p);
}
private static void ValidatePosWidth(int pos, int width)
{
if (pos < 0 || width < 1 || pos + width > 32)
throw new ArgumentException("trying to access non-existent bits");
}
private static uint NBitMask(int bits)
{
if (bits <= 0)
return 0u;
if (bits >= 32)
return 0xFFFFFFFFu;
return (1u << bits) - 1u;
}
}
}
+193
ファイルの表示
@@ -0,0 +1,193 @@
using System;
namespace LuaScript.Compat
{
internal static class FigureRenderer
{
private enum Shape
{
Ellipse,
Rectangle,
Triangle,
Pentagon,
Hexagon,
Star,
}
public static byte[] Render(string name, int width, int height, int colorRgb, double lineWidth)
{
width = Math.Max(1, width);
height = Math.Max(1, height);
var buffer = new byte[width * height * 4];
Shape shape = Resolve(name);
double hx = width / 2d;
double hy = height / 2d;
double r = (colorRgb >> 16) & 0xFF;
double g = (colorRgb >> 8) & 0xFF;
double b = colorRgb & 0xFF;
(double X, double Y)[]? polygon = shape switch
{
Shape.Triangle => RegularPolygon(3, hx, hy),
Shape.Pentagon => RegularPolygon(5, hx, hy),
Shape.Hexagon => RegularPolygon(6, hx, hy),
Shape.Star => StarPolygon(hx, hy),
_ => null,
};
bool filled = lineWidth <= 0d;
for (int y = 0; y < height; y++)
{
double py = y + 0.5 - hy;
int row = y * width * 4;
for (int x = 0; x < width; x++)
{
double px = x + 0.5 - hx;
double d = shape switch
{
Shape.Ellipse => EllipseSdf(px, py, hx, hy),
Shape.Rectangle => BoxSdf(px, py, hx, hy),
_ => PolygonSdf(px, py, polygon!),
};
if (!filled)
d = Math.Max(d, -d - lineWidth);
double coverage = 0.5 - d;
if (coverage <= 0d)
continue;
if (coverage > 1d)
coverage = 1d;
int i = row + x * 4;
buffer[i] = ToByte(b * coverage);
buffer[i + 1] = ToByte(g * coverage);
buffer[i + 2] = ToByte(r * coverage);
buffer[i + 3] = ToByte(255d * coverage);
}
}
return buffer;
}
private static Shape Resolve(string name)
{
switch (name.Trim())
{
case "円":
case "楕円":
case "circle":
case "ellipse":
return Shape.Ellipse;
case "三角形":
case "triangle":
return Shape.Triangle;
case "五角形":
case "pentagon":
return Shape.Pentagon;
case "六角形":
case "hexagon":
return Shape.Hexagon;
case "星形":
case "star":
return Shape.Star;
default:
return Shape.Rectangle;
}
}
private static (double X, double Y)[] RegularPolygon(int sides, double hx, double hy)
{
var vertices = new (double X, double Y)[sides];
for (int k = 0; k < sides; k++)
{
double angle = -Math.PI / 2d + 2d * Math.PI * k / sides;
vertices[k] = (Math.Cos(angle) * hx, Math.Sin(angle) * hy);
}
return vertices;
}
private static (double X, double Y)[] StarPolygon(double hx, double hy)
{
const double innerRatio = 0.38196601125010515d;
var vertices = new (double X, double Y)[10];
for (int k = 0; k < 10; k++)
{
double angle = -Math.PI / 2d + Math.PI * k / 5d;
double radius = (k & 1) == 0 ? 1d : innerRatio;
vertices[k] = (Math.Cos(angle) * hx * radius, Math.Sin(angle) * hy * radius);
}
return vertices;
}
private static double EllipseSdf(double px, double py, double ax, double ay)
{
if (ax <= 0d || ay <= 0d)
return double.MaxValue;
double kx = px / ax;
double ky = py / ay;
double k1 = Math.Sqrt(kx * kx + ky * ky);
if (k1 == 0d)
return -Math.Min(ax, ay);
double nx = kx / ax;
double ny = ky / ay;
double k2 = Math.Sqrt(nx * nx + ny * ny);
return k1 * (k1 - 1d) / k2;
}
private static double BoxSdf(double px, double py, double hx, double hy)
{
double qx = Math.Abs(px) - hx;
double qy = Math.Abs(py) - hy;
double ox = Math.Max(qx, 0d);
double oy = Math.Max(qy, 0d);
return Math.Sqrt(ox * ox + oy * oy) + Math.Min(Math.Max(qx, qy), 0d);
}
private static double PolygonSdf(double px, double py, (double X, double Y)[] v)
{
int n = v.Length;
double dx = px - v[0].X;
double dy = py - v[0].Y;
double d = dx * dx + dy * dy;
double s = 1d;
for (int i = 0, j = n - 1; i < n; j = i, i++)
{
double ex = v[j].X - v[i].X;
double ey = v[j].Y - v[i].Y;
double wx = px - v[i].X;
double wy = py - v[i].Y;
double t = Clamp((wx * ex + wy * ey) / (ex * ex + ey * ey), 0d, 1d);
double bx = wx - ex * t;
double by = wy - ey * t;
d = Math.Min(d, bx * bx + by * by);
bool c1 = py >= v[i].Y;
bool c2 = py < v[j].Y;
bool c3 = ex * wy > ey * wx;
if ((c1 && c2 && c3) || (!c1 && !c2 && !c3))
s = -s;
}
return s * Math.Sqrt(d);
}
private static double Clamp(double v, double lo, double hi)
{
if (v < lo) return lo;
if (v > hi) return hi;
return v;
}
private static byte ToByte(double v)
{
int i = (int)(v + 0.5d);
if (i < 0) return 0;
if (i > 255) return 255;
return (byte)i;
}
}
}
+111
ファイルの表示
@@ -0,0 +1,111 @@
using System;
namespace LuaScript.Compat
{
internal static class MoonSharpBit32
{
private const double Modulo = 4294967296.0;
public static uint ToUInt32(double value) => unchecked((uint)Math.IEEERemainder(value, Modulo));
public static int ToInt32(double value) => unchecked((int)Math.IEEERemainder(value, Modulo));
public static uint Band(params double[] values)
{
uint accum = ToUInt32(values[0]);
for (int i = 1; i < values.Length; i++)
accum &= ToUInt32(values[i]);
return accum;
}
public static uint Bor(params double[] values)
{
uint accum = ToUInt32(values[0]);
for (int i = 1; i < values.Length; i++)
accum |= ToUInt32(values[i]);
return accum;
}
public static uint Bxor(params double[] values)
{
uint accum = ToUInt32(values[0]);
for (int i = 1; i < values.Length; i++)
accum ^= ToUInt32(values[i]);
return accum;
}
public static bool Btest(params double[] values) => Band(values) != 0u;
public static uint Bnot(double value) => ~ToUInt32(value);
public static uint Lshift(double value, double shift)
{
uint v = ToUInt32(value);
int a = (int)shift;
return a < 0 ? v >> -a : v << a;
}
public static uint Rshift(double value, double shift)
{
uint v = ToUInt32(value);
int a = (int)shift;
return a < 0 ? v << -a : v >> a;
}
public static int Arshift(double value, double shift)
{
int v = ToInt32(value);
int a = (int)shift;
return a < 0 ? v << -a : v >> a;
}
public static uint Lrotate(double value, double shift)
{
uint v = ToUInt32(value);
int a = ((int)shift) % 32;
return a < 0 ? (v >> -a) | (v << (32 + a)) : (v << a) | (v >> (32 - a));
}
public static uint Rrotate(double value, double shift)
{
uint v = ToUInt32(value);
int a = ((int)shift) % 32;
return a < 0 ? (v << -a) | (v >> (32 + a)) : (v >> a) | (v << (32 - a));
}
public static uint Extract(double value, double pos, double? width)
{
uint v = ToUInt32(value);
int p = (int)pos;
int w = width is null ? 1 : (int)width.Value;
ValidatePosWidth(p, w);
return (v >> p) & NBitMask(w);
}
public static uint Replace(double value, double replacement, double pos, double? width)
{
uint v = ToUInt32(value);
uint u = ToUInt32(replacement);
int p = (int)pos;
int w = width is null ? 1 : (int)width.Value;
ValidatePosWidth(p, w);
uint mask = NBitMask(w) << p;
return (v & ~mask) | (u & mask);
}
private static void ValidatePosWidth(int pos, int width)
{
if (pos > 31 || pos + width > 31)
throw new ArgumentException("trying to access non-existent bits");
}
private static uint NBitMask(int bits)
{
if (bits <= 0)
return 0u;
if (bits >= 32)
return 0xFFFFFFFFu;
return (1u << bits) - 1u;
}
}
}
+242
ファイルの表示
@@ -0,0 +1,242 @@
using System;
using System.Diagnostics;
using System.IO;
using System.IO.MemoryMappedFiles;
using System.Text;
using System.Threading;
namespace LuaScript.Engine
{
internal sealed class LuaJitWorker : IDisposable
{
private readonly string _luajitPath;
private readonly string _workerScript;
private readonly string _shimScript;
private readonly string _nativeDir;
private MemoryMappedFile? _mmf;
private MemoryMappedViewAccessor? _view;
private EventWaitHandle? _workEvent;
private EventWaitHandle? _doneEvent;
private Process? _process;
private int _width;
private int _height;
private bool _alive;
private readonly byte[] _callbackTag = new byte[NativeProtocol.CallbackTagMax];
private readonly byte[] _lastCallbackTag = new byte[NativeProtocol.CallbackTagMax];
private int _lastCallbackTagLength = -1;
private string _lastCallbackTagText = string.Empty;
public LuaJitWorker(string nativeDir)
{
_nativeDir = nativeDir;
_luajitPath = Path.Combine(nativeDir, "luajit.exe");
_workerScript = Path.Combine(nativeDir, "worker.lua");
_shimScript = Path.Combine(nativeDir, "shim.lua");
}
public static bool IsAvailable(string nativeDir) =>
File.Exists(Path.Combine(nativeDir, "luajit.exe"));
public bool Execute(
string script,
double[] fields,
byte[] pixels,
int width,
int height,
int timeoutMs,
Func<string, int, SceneObjectInfo?> resolveObject,
out bool pixelsDirty,
out string? error)
{
pixelsDirty = false;
error = null;
byte[] scriptBytes = Encoding.UTF8.GetBytes(script);
if (scriptBytes.Length > NativeProtocol.ScriptMax)
{
error = "script too large for native lane";
return false;
}
EnsureWorker(width, height);
var view = _view!;
view.WriteArray(NativeProtocol.FieldsOffset, fields, 0, NativeProtocol.FieldCount);
view.Write(NativeProtocol.OffWidth, width);
view.Write(NativeProtocol.OffHeight, height);
view.Write(NativeProtocol.OffScriptLen, scriptBytes.Length);
view.WriteArray(NativeProtocol.ScriptOffset, scriptBytes, 0, scriptBytes.Length);
view.WriteArray(NativeProtocol.PixelOffset, pixels, 0, pixels.Length);
view.Write(NativeProtocol.OffPixelsDirty, 0);
view.Write(NativeProtocol.OffErrorLen, 0);
view.Write(NativeProtocol.OffStatus, NativeProtocol.StatusIdle);
view.Write(NativeProtocol.OffCommand, NativeProtocol.CmdRun);
_workEvent!.Set();
var stopwatch = Stopwatch.StartNew();
int status;
while (true)
{
long remaining = timeoutMs - stopwatch.ElapsedMilliseconds;
if (remaining <= 0 || !_doneEvent!.WaitOne((int)remaining))
{
KillWorker();
error = "native script execution timed out";
return false;
}
status = view.ReadInt32(NativeProtocol.OffStatus);
if (status != NativeProtocol.StatusCallback)
break;
ResolveCallback(view, resolveObject);
_workEvent.Set();
}
if (status == NativeProtocol.StatusError)
{
int len = view.ReadInt32(NativeProtocol.OffErrorLen);
var buffer = new byte[Math.Clamp(len, 0, NativeProtocol.ErrorMax)];
view.ReadArray(NativeProtocol.ErrorOffset, buffer, 0, buffer.Length);
error = Encoding.UTF8.GetString(buffer);
return false;
}
for (int i = NativeProtocol.FirstWritableField; i <= NativeProtocol.LastWritableField; i++)
fields[i] = view.ReadDouble(NativeProtocol.FieldsOffset + i * 8);
pixelsDirty = view.ReadInt32(NativeProtocol.OffPixelsDirty) != 0;
if (pixelsDirty)
view.ReadArray(NativeProtocol.PixelOffset, pixels, 0, pixels.Length);
return true;
}
private void ResolveCallback(MemoryMappedViewAccessor view, Func<string, int, SceneObjectInfo?> resolveObject)
{
int frame = view.ReadInt32(NativeProtocol.OffCallbackFrame);
int tagLen = Math.Clamp(view.ReadInt32(NativeProtocol.OffCallbackTagLen), 0, NativeProtocol.CallbackTagMax);
view.ReadArray(NativeProtocol.CallbackTagOffset, _callbackTag, 0, tagLen);
string tag = ResolveTag(tagLen);
SceneObjectInfo? info;
try { info = resolveObject(tag, frame); }
catch { info = null; }
if (info is { } value)
{
long result = NativeProtocol.CallbackResultOffset;
view.Write(result + NativeProtocol.CbExist * 8, value.Exist ? 1d : 0d);
view.Write(result + NativeProtocol.CbX * 8, value.X);
view.Write(result + NativeProtocol.CbY * 8, value.Y);
view.Write(result + NativeProtocol.CbZ * 8, value.Z);
view.Write(result + NativeProtocol.CbZoom * 8, value.Zoom);
view.Write(result + NativeProtocol.CbRz * 8, value.Rz);
view.Write(result + NativeProtocol.CbAlpha * 8, value.Alpha);
view.Write(result + NativeProtocol.CbLayer * 8, (double)value.Layer);
view.Write(NativeProtocol.OffCallbackFound, 1);
}
else
{
view.Write(NativeProtocol.OffCallbackFound, 0);
}
}
private string ResolveTag(int tagLen)
{
if (tagLen == _lastCallbackTagLength &&
_callbackTag.AsSpan(0, tagLen).SequenceEqual(_lastCallbackTag.AsSpan(0, tagLen)))
return _lastCallbackTagText;
_lastCallbackTagText = Encoding.UTF8.GetString(_callbackTag, 0, tagLen);
_callbackTag.AsSpan(0, tagLen).CopyTo(_lastCallbackTag);
_lastCallbackTagLength = tagLen;
return _lastCallbackTagText;
}
private void EnsureWorker(int width, int height)
{
if (_alive && _process is { HasExited: false } && _width == width && _height == height)
return;
KillWorker();
StartWorker(width, height);
}
private void StartWorker(int width, int height)
{
_width = width;
_height = height;
long size = NativeProtocol.BufferSize(width, height);
string suffix = Guid.NewGuid().ToString("N");
string mapName = "LuaScriptMap_" + suffix;
string workName = "LuaScriptWork_" + suffix;
string doneName = "LuaScriptDone_" + suffix;
_mmf = MemoryMappedFile.CreateNew(mapName, size);
_view = _mmf.CreateViewAccessor();
_view.Write(NativeProtocol.OffMagic, NativeProtocol.Magic);
_workEvent = new EventWaitHandle(false, EventResetMode.AutoReset, workName);
_doneEvent = new EventWaitHandle(false, EventResetMode.AutoReset, doneName);
var psi = new ProcessStartInfo
{
FileName = _luajitPath,
WorkingDirectory = _nativeDir,
UseShellExecute = false,
CreateNoWindow = true,
RedirectStandardError = true,
};
psi.ArgumentList.Add(_workerScript);
psi.ArgumentList.Add(mapName);
psi.ArgumentList.Add(size.ToString());
psi.ArgumentList.Add(workName);
psi.ArgumentList.Add(doneName);
psi.ArgumentList.Add(_shimScript);
_process = Process.Start(psi);
if (_process is not null)
ProcessJobObject.Assign(_process.Handle);
_alive = _process is not null;
}
private void KillWorker()
{
if (_process is { HasExited: false })
{
try { _process.Kill(entireProcessTree: true); }
catch { }
}
_process?.Dispose();
_process = null;
_view?.Dispose();
_view = null;
_mmf?.Dispose();
_mmf = null;
_workEvent?.Dispose();
_workEvent = null;
_doneEvent?.Dispose();
_doneEvent = null;
_alive = false;
}
public void Dispose()
{
if (_alive && _process is { HasExited: false } && _view is not null && _workEvent is not null)
{
try
{
_view.Write(NativeProtocol.OffCommand, NativeProtocol.CmdShutdown);
_workEvent.Set();
_process.WaitForExit(500);
}
catch { }
}
KillWorker();
}
}
}
+119
ファイルの表示
@@ -0,0 +1,119 @@
using System;
namespace LuaScript.Engine
{
internal static class NativeFieldMap
{
private const double Epsilon = 1e-10;
public static void ToFields(AviUtlScriptContext ctx, double[] f)
{
f[NativeProtocol.W] = ctx.ImageWidth;
f[NativeProtocol.H] = ctx.ImageHeight;
f[NativeProtocol.Hw] = ctx.ImageWidth / 2d;
f[NativeProtocol.Hh] = ctx.ImageHeight / 2d;
f[NativeProtocol.Cx] = ctx.ImageWidth / 2d;
f[NativeProtocol.Cy] = ctx.ImageHeight / 2d;
f[NativeProtocol.Cz] = 0d;
f[NativeProtocol.Diagonal] = Math.Sqrt((double)ctx.ImageWidth * ctx.ImageWidth + (double)ctx.ImageHeight * ctx.ImageHeight);
f[NativeProtocol.X] = ctx.X;
f[NativeProtocol.Y] = ctx.Y;
f[NativeProtocol.Z] = ctx.Z;
f[NativeProtocol.Ox] = ctx.Ox;
f[NativeProtocol.Oy] = ctx.Oy;
f[NativeProtocol.Oz] = ctx.Oz;
f[NativeProtocol.Sx] = ctx.Sx;
f[NativeProtocol.Sy] = ctx.Sy;
f[NativeProtocol.Sz] = 1d;
f[NativeProtocol.Zoom] = ctx.Zoom;
f[NativeProtocol.Aspect] = ctx.Aspect;
f[NativeProtocol.Alpha] = ctx.Alpha;
f[NativeProtocol.Rx] = ctx.Rx;
f[NativeProtocol.Ry] = ctx.Ry;
f[NativeProtocol.Rz] = ctx.Rz;
f[NativeProtocol.Rxr] = ctx.RxRad;
f[NativeProtocol.Ryr] = ctx.RyRad;
f[NativeProtocol.Rzr] = ctx.RzRad;
f[NativeProtocol.Track0] = ctx.Track0;
f[NativeProtocol.Track1] = ctx.Track1;
f[NativeProtocol.Track2] = ctx.Track2;
f[NativeProtocol.Track3] = ctx.Track3;
f[NativeProtocol.Check0] = ctx.Check0 ? 1d : 0d;
f[NativeProtocol.Check1] = ctx.Check1 ? 1d : 0d;
f[NativeProtocol.Check2] = ctx.Check2 ? 1d : 0d;
f[NativeProtocol.Check3] = ctx.Check3 ? 1d : 0d;
f[NativeProtocol.Color] = ctx.HasColor ? ctx.ColorValue : -1d;
f[NativeProtocol.Time] = ctx.Time;
f[NativeProtocol.Frame] = ctx.Frame;
f[NativeProtocol.TotalFrame] = ctx.TotalFrame;
f[NativeProtocol.TotalTime] = ctx.TotalTime;
f[NativeProtocol.T] = ctx.TotalFrame > 0 ? ctx.Frame / (double)ctx.TotalFrame : 0d;
f[NativeProtocol.Framerate] = ctx.Framerate;
f[NativeProtocol.Layer] = ctx.Layer;
f[NativeProtocol.Index] = ctx.Index;
f[NativeProtocol.Num] = ctx.Num;
f[NativeProtocol.SceneWidth] = ctx.SceneWidth;
f[NativeProtocol.SceneHeight] = ctx.SceneHeight;
f[NativeProtocol.SceneCx] = ctx.SceneWidth / 2d;
f[NativeProtocol.SceneCy] = ctx.SceneHeight / 2d;
f[NativeProtocol.GroupIndex] = ctx.GroupIndex;
f[NativeProtocol.GroupCount] = ctx.GroupCount;
f[NativeProtocol.TimelineTotalFrame] = ctx.TimelineTotalFrame;
f[NativeProtocol.TimelineTotalTime] = ctx.TimelineTotalTime;
f[NativeProtocol.TimeRatio] = ctx.TimeRatio;
f[NativeProtocol.IsSaving] = ctx.IsSaving ? 1d : 0d;
f[NativeProtocol.IsPlaying] = ctx.IsPlaying ? 1d : 0d;
f[NativeProtocol.IsPaused] = ctx.IsPaused ? 1d : 0d;
f[NativeProtocol.TimelineFrame] = ctx.TimelineFrame;
f[NativeProtocol.TimelineTime] = ctx.TimelineTime;
}
public static void FromFields(double[] f, AviUtlScriptContext ctx)
{
ctx.X = f[NativeProtocol.X];
ctx.Y = f[NativeProtocol.Y];
ctx.Z = f[NativeProtocol.Z];
ctx.Ox = f[NativeProtocol.Ox];
ctx.Oy = f[NativeProtocol.Oy];
ctx.Oz = f[NativeProtocol.Oz];
ctx.Alpha = f[NativeProtocol.Alpha];
double initialSx = ctx.Sx;
double initialSy = ctx.Sy;
double initialZoom = ctx.Zoom;
double initialAspect = ctx.Aspect;
ctx.Sx = f[NativeProtocol.Sx];
ctx.Sy = f[NativeProtocol.Sy];
ctx.Zoom = f[NativeProtocol.Zoom];
ctx.Aspect = f[NativeProtocol.Aspect];
bool sxsyChanged = Math.Abs(ctx.Sx - initialSx) > Epsilon || Math.Abs(ctx.Sy - initialSy) > Epsilon;
bool zoomAspectChanged = Math.Abs(ctx.Zoom - initialZoom) > Epsilon || Math.Abs(ctx.Aspect - initialAspect) > Epsilon;
if (zoomAspectChanged && !sxsyChanged)
{
ctx.Sx = ctx.Zoom * (1.0 + ctx.Aspect);
ctx.Sy = ctx.Zoom * (1.0 - ctx.Aspect);
}
double initialRxr = ctx.RxRad;
double rxrNew = f[NativeProtocol.Rxr];
ctx.Rx = Math.Abs(rxrNew - initialRxr) > Epsilon
? rxrNew * (180d / Math.PI)
: f[NativeProtocol.Rx];
double initialRyr = ctx.RyRad;
double ryrNew = f[NativeProtocol.Ryr];
ctx.Ry = Math.Abs(ryrNew - initialRyr) > Epsilon
? ryrNew * (180d / Math.PI)
: f[NativeProtocol.Ry];
double initialRzr = ctx.RzRad;
double rzrNew = f[NativeProtocol.Rzr];
ctx.Rz = Math.Abs(rzrNew - initialRzr) > Epsilon
? rzrNew * (180d / Math.PI)
: f[NativeProtocol.Rz];
}
}
}
+119
ファイルの表示
@@ -0,0 +1,119 @@
namespace LuaScript.Engine
{
internal static class NativeProtocol
{
public const int Magic = 0x4C4A4954;
public const int CmdRun = 0;
public const int CmdShutdown = 1;
public const int StatusIdle = 0;
public const int StatusOk = 1;
public const int StatusError = 2;
public const int StatusCallback = 3;
public const int OffMagic = 0;
public const int OffCommand = 4;
public const int OffStatus = 8;
public const int OffWidth = 12;
public const int OffHeight = 16;
public const int OffScriptLen = 20;
public const int OffPixelsDirty = 24;
public const int OffErrorLen = 28;
public const int OffCallbackFrame = 32;
public const int OffCallbackTagLen = 36;
public const int OffCallbackFound = 40;
public const int HeaderSize = 64;
public const int FieldCount = 64;
public const int FieldsOffset = HeaderSize;
public const int ScriptOffset = FieldsOffset + FieldCount * 8;
public const int ScriptMax = 128 * 1024;
public const int ErrorOffset = ScriptOffset + ScriptMax;
public const int ErrorMax = 4 * 1024;
public const int CallbackTagOffset = ErrorOffset + ErrorMax;
public const int CallbackTagMax = 256;
public const int CallbackResultOffset = CallbackTagOffset + CallbackTagMax;
public const int CallbackResultCount = 8;
public const int CbExist = 0;
public const int CbX = 1;
public const int CbY = 2;
public const int CbZ = 3;
public const int CbZoom = 4;
public const int CbRz = 5;
public const int CbAlpha = 6;
public const int CbLayer = 7;
public const int PixelOffset = CallbackResultOffset + CallbackResultCount * 8;
public const int W = 0;
public const int H = 1;
public const int Hw = 2;
public const int Hh = 3;
public const int Cx = 4;
public const int Cy = 5;
public const int Cz = 6;
public const int Diagonal = 7;
public const int X = 8;
public const int Y = 9;
public const int Z = 10;
public const int Ox = 11;
public const int Oy = 12;
public const int Oz = 13;
public const int Sx = 14;
public const int Sy = 15;
public const int Sz = 16;
public const int Zoom = 17;
public const int Aspect = 18;
public const int Alpha = 19;
public const int Rx = 20;
public const int Ry = 21;
public const int Rz = 22;
public const int Rxr = 23;
public const int Ryr = 24;
public const int Rzr = 25;
public const int Track0 = 26;
public const int Track1 = 27;
public const int Track2 = 28;
public const int Track3 = 29;
public const int Time = 30;
public const int Frame = 31;
public const int TotalFrame = 32;
public const int TotalTime = 33;
public const int T = 34;
public const int Framerate = 35;
public const int Layer = 36;
public const int Index = 37;
public const int Num = 38;
public const int SceneWidth = 39;
public const int SceneHeight = 40;
public const int SceneCx = 41;
public const int SceneCy = 42;
public const int GroupIndex = 43;
public const int GroupCount = 44;
public const int TimelineTotalFrame = 45;
public const int TimelineTotalTime = 46;
public const int TimeRatio = 47;
public const int IsSaving = 48;
public const int IsPlaying = 49;
public const int IsPaused = 50;
public const int TimelineFrame = 51;
public const int TimelineTime = 52;
public const int Check0 = 53;
public const int Check1 = 54;
public const int Check2 = 55;
public const int Check3 = 56;
public const int Color = 57;
public const int FirstWritableField = X;
public const int LastWritableField = Rzr;
public static long BufferSize(int width, int height) =>
PixelOffset + (long)width * height * 4;
}
}
+103
ファイルの表示
@@ -0,0 +1,103 @@
using System;
using System.Runtime.InteropServices;
namespace LuaScript.Engine
{
internal static class ProcessJobObject
{
private const uint JobObjectExtendedLimitInformation = 9;
private const uint JobObjectLimitKillOnJobClose = 0x2000;
private static readonly nint Handle = Create();
public static void Assign(nint processHandle)
{
if (Handle != nint.Zero && processHandle != nint.Zero)
AssignProcessToJobObject(Handle, processHandle);
}
private static nint Create()
{
nint job = CreateJobObject(nint.Zero, null);
if (job == nint.Zero)
return nint.Zero;
var information = new JobObjectExtendedLimitInformationData
{
BasicLimitInformation = new JobObjectBasicLimitInformationData
{
LimitFlags = JobObjectLimitKillOnJobClose
}
};
int length = Marshal.SizeOf<JobObjectExtendedLimitInformationData>();
nint buffer = Marshal.AllocHGlobal(length);
try
{
Marshal.StructureToPtr(information, buffer, false);
if (!SetInformationJobObject(job, JobObjectExtendedLimitInformation, buffer, (uint)length))
{
CloseHandle(job);
return nint.Zero;
}
}
finally
{
Marshal.FreeHGlobal(buffer);
}
return job;
}
[StructLayout(LayoutKind.Sequential)]
private struct JobObjectBasicLimitInformationData
{
public long PerProcessUserTimeLimit;
public long PerJobUserTimeLimit;
public uint LimitFlags;
public nuint MinimumWorkingSetSize;
public nuint MaximumWorkingSetSize;
public uint ActiveProcessLimit;
public nuint Affinity;
public uint PriorityClass;
public uint SchedulingClass;
}
[StructLayout(LayoutKind.Sequential)]
private struct IoCountersData
{
public ulong ReadOperationCount;
public ulong WriteOperationCount;
public ulong OtherOperationCount;
public ulong ReadTransferCount;
public ulong WriteTransferCount;
public ulong OtherTransferCount;
}
[StructLayout(LayoutKind.Sequential)]
private struct JobObjectExtendedLimitInformationData
{
public JobObjectBasicLimitInformationData BasicLimitInformation;
public IoCountersData IoInfo;
public nuint ProcessMemoryLimit;
public nuint JobMemoryLimit;
public nuint PeakProcessMemoryUsed;
public nuint PeakJobMemoryUsed;
}
[DllImport("kernel32.dll", CharSet = CharSet.Unicode, SetLastError = true)]
private static extern nint CreateJobObject(nint lpJobAttributes, string? lpName);
[DllImport("kernel32.dll", SetLastError = true)]
[return: MarshalAs(UnmanagedType.Bool)]
private static extern bool SetInformationJobObject(nint hJob, uint jobObjectInformationClass, nint lpJobObjectInformation, uint cbJobObjectInformationLength);
[DllImport("kernel32.dll", SetLastError = true)]
[return: MarshalAs(UnmanagedType.Bool)]
private static extern bool AssignProcessToJobObject(nint hJob, nint hProcess);
[DllImport("kernel32.dll", SetLastError = true)]
[return: MarshalAs(UnmanagedType.Bool)]
private static extern bool CloseHandle(nint hObject);
}
}
+116
ファイルの表示
@@ -0,0 +1,116 @@
using System;
namespace LuaScript.Engine
{
internal enum ScriptEngineKind
{
MoonSharp,
Native,
Gpu,
Cpu,
}
internal static class ScriptDirective
{
public static ScriptEngineKind Resolve(string? script) =>
TryGetDirective(script, out var kind) ? kind : ScriptEngineKind.MoonSharp;
public static ScriptEngineKind ResolveAuto(string? script)
{
if (TryGetDirective(script, out var kind))
return kind;
if (UsesDrawingApi(script))
return ScriptEngineKind.MoonSharp;
return UsesPixelApi(script) ? ScriptEngineKind.Native : ScriptEngineKind.MoonSharp;
}
public static bool UsesPixelApi(string? script) =>
script is not null && (script.Contains("getpixel", StringComparison.Ordinal) || script.Contains("setpixel", StringComparison.Ordinal));
public static bool UsesDrawingApi(string? script) =>
script is not null && (
script.Contains("obj.load", StringComparison.Ordinal) ||
script.Contains("obj.draw", StringComparison.Ordinal) ||
script.Contains("obj.effect", StringComparison.Ordinal) ||
script.Contains("obj.setoption", StringComparison.Ordinal) ||
script.Contains("obj.copybuffer", StringComparison.Ordinal));
private static bool TryGetDirective(string? script, out ScriptEngineKind kind)
{
kind = ScriptEngineKind.MoonSharp;
if (string.IsNullOrEmpty(script))
return false;
int index = 0;
int length = script.Length;
while (index < length)
{
int lineStart = index;
while (index < length && script[index] != '\n')
index++;
int lineEnd = index;
if (lineEnd > lineStart && script[lineEnd - 1] == '\r')
lineEnd--;
if (TryParseDirectiveLine(script, lineStart, lineEnd, out kind))
return true;
index++;
}
return false;
}
private static bool TryParseDirectiveLine(string script, int start, int end, out ScriptEngineKind kind)
{
kind = ScriptEngineKind.MoonSharp;
int i = start;
while (i < end && (script[i] == ' ' || script[i] == '\t'))
i++;
if (i + 3 > end || script[i] != '-' || script[i + 1] != '-' || script[i + 2] != '!')
return false;
i += 3;
while (i < end && (script[i] == ' ' || script[i] == '\t'))
i++;
int tokenStart = i;
while (i < end && IsTokenChar(script[i]))
i++;
int tokenEnd = i;
while (i < end && (script[i] == ' ' || script[i] == '\t'))
i++;
if (i != end)
return false;
var token = script.AsSpan(tokenStart, tokenEnd - tokenStart);
if (token.Equals("native", StringComparison.OrdinalIgnoreCase))
{
kind = ScriptEngineKind.Native;
return true;
}
if (token.Equals("gpu", StringComparison.OrdinalIgnoreCase))
{
kind = ScriptEngineKind.Gpu;
return true;
}
if (token.Equals("cpu", StringComparison.OrdinalIgnoreCase))
{
kind = ScriptEngineKind.Cpu;
return true;
}
if (token.Equals("moonsharp", StringComparison.OrdinalIgnoreCase))
{
kind = ScriptEngineKind.MoonSharp;
return true;
}
return false;
}
private static bool IsTokenChar(char c) =>
(c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z');
}
}
+1 -1
ファイルの表示
@@ -42,7 +42,7 @@ namespace LuaScript
"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.getpixeldata", "obj.rand", "obj.load"
]),
("math", [
"math.abs", "math.ceil", "math.cos", "math.exp", "math.floor",
+6 -2
ファイルの表示
@@ -4,7 +4,7 @@
<TargetFramework>net10.0-windows10.0.19041.0</TargetFramework>
<UseWPF>true</UseWPF>
<ImplicitUsings>enable</ImplicitUsings>
<Version>1.2.0</Version>
<Version>1.7.0</Version>
<Platforms>AnyCPU;x64</Platforms>
<Nullable>enable</Nullable>
<AllowUnsafeBlocks>true</AllowUnsafeBlocks>
@@ -102,10 +102,14 @@
<Resource Include="Resources\SyntaxDefinitions\Lua-Light.xshd" />
<Resource Include="Resources\SyntaxDefinitions\Lua-Black.xshd" />
<Resource Include="Resources\SyntaxDefinitions\Lua-Windows.xshd" />
<None Include="..\native\luajit.exe" Link="native\luajit.exe" CopyToOutputDirectory="PreserveNewest" />
<None Include="..\native\lua51.dll" Link="native\lua51.dll" CopyToOutputDirectory="PreserveNewest" />
<None Include="..\native\worker.lua" Link="native\worker.lua" CopyToOutputDirectory="PreserveNewest" />
<None Include="..\native\shim.lua" Link="native\shim.lua" CopyToOutputDirectory="PreserveNewest" />
</ItemGroup>
<Target Name="PostBuild" AfterTargets="PostBuildEvent" Condition="'$(CI)' != 'true'">
<Exec Command="mkdir &quot;$(YMM4DirPath)user\plugin\$(ProjectName)&quot; &gt; NUL 2&gt;&amp;1&#xD;&#xA;copy &quot;$(TargetPath)&quot; &quot;$(YMM4DirPath)user\plugin\$(ProjectName)\&quot;" />
<Exec Command="mkdir &quot;$(YMM4DirPath)user\plugin\$(ProjectName)&quot; &gt; NUL 2&gt;&amp;1&#xD;&#xA;copy &quot;$(TargetPath)&quot; &quot;$(YMM4DirPath)user\plugin\$(ProjectName)\&quot;&#xD;&#xA;xcopy /E /I /Y &quot;$(TargetDir)native&quot; &quot;$(YMM4DirPath)user\plugin\$(ProjectName)\native&quot;" />
</Target>
</Project>
+107 -1
ファイルの表示
@@ -1,13 +1,20 @@
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Windows.Media;
using LuaScript.Compat;
using Newtonsoft.Json;
using YukkuriMovieMaker.Commons;
using YukkuriMovieMaker.Controls;
using YukkuriMovieMaker.Exo;
using YukkuriMovieMaker.ItemEditor.CustomVisibilityAttributes;
using YukkuriMovieMaker.Player.Video;
using YukkuriMovieMaker.Plugin;
using YukkuriMovieMaker.Plugin.Effects;
namespace LuaScript
{
[PluginDetails(AuthorName = "routersys", ContentId = "nc487743")]
[VideoEffect(nameof(Texts.LuaScript), [VideoEffectCategories.Filtering], ["lua", "script", "スクリプト", "lua script", "アニメーション効果", "animation"], IsAviUtlSupported = false, ResourceType = typeof(Texts))]
internal class LuaScriptEffect : VideoEffectBase, IScriptProvider
{
@@ -24,27 +31,126 @@ namespace LuaScript
[Display(GroupName = nameof(Texts.ScriptGroup), ResourceType = typeof(Texts))]
[CodeEditor(Language = "pack://application:,,,/LuaScript;component/Resources/SyntaxDefinitions/Lua-{theme}.xshd", FoldingStrategyType = typeof(LuaFoldingStrategy), AutoCompletionStrategyType = typeof(LuaAutoCompletionStrategy), ToolBarStrategyType = typeof(EmptyToolBarStrategy), PropertyEditorSize = PropertyEditorSize.FullWidth)]
public string Script { get => _script; set => Set(ref _script, value); }
public string Script
{
get => _script;
set { if (Set(ref _script, value)) UpdateLayout(); }
}
string _script = DefaultScript;
string IScriptProvider.DefaultScript => DefaultScript;
internal AviUtlParameterLayout Layout { get; private set; } = AviUtlParameterLayout.Parse(DefaultScript);
[Display(GroupName = nameof(Texts.ParametersGroup), Name = nameof(Texts.Track0), Description = nameof(Texts.TrackDesc), ResourceType = typeof(Texts))]
[AnimationSlider("F2", "", -100, 100)]
[ShowPropertyEditorWhen(nameof(IsTrack0Visible), true)]
public Animation Track0 { get; } = new Animation(0, YMM4Constants.VerySmallValue, YMM4Constants.VeryLargeValue);
[Display(GroupName = nameof(Texts.ParametersGroup), Name = nameof(Texts.Track1), Description = nameof(Texts.TrackDesc), ResourceType = typeof(Texts))]
[AnimationSlider("F2", "", -100, 100)]
[ShowPropertyEditorWhen(nameof(IsTrack1Visible), true)]
public Animation Track1 { get; } = new Animation(0, YMM4Constants.VerySmallValue, YMM4Constants.VeryLargeValue);
[Display(GroupName = nameof(Texts.ParametersGroup), Name = nameof(Texts.Track2), Description = nameof(Texts.TrackDesc), ResourceType = typeof(Texts))]
[AnimationSlider("F2", "", -100, 100)]
[ShowPropertyEditorWhen(nameof(IsTrack2Visible), true)]
public Animation Track2 { get; } = new Animation(0, YMM4Constants.VerySmallValue, YMM4Constants.VeryLargeValue);
[Display(GroupName = nameof(Texts.ParametersGroup), Name = nameof(Texts.Track3), Description = nameof(Texts.TrackDesc), ResourceType = typeof(Texts))]
[AnimationSlider("F2", "", -100, 100)]
[ShowPropertyEditorWhen(nameof(IsTrack3Visible), true)]
public Animation Track3 { get; } = new Animation(0, YMM4Constants.VerySmallValue, YMM4Constants.VeryLargeValue);
[Display(GroupName = nameof(Texts.ParametersGroup), Name = nameof(Texts.Check0), Description = nameof(Texts.CheckDesc), ResourceType = typeof(Texts))]
[ToggleSlider]
[ShowPropertyEditorWhen(nameof(IsCheck0Visible), true)]
public bool Check0 { get => _check0; set => Set(ref _check0, value); }
bool _check0;
[Display(GroupName = nameof(Texts.ParametersGroup), Name = nameof(Texts.Check1), Description = nameof(Texts.CheckDesc), ResourceType = typeof(Texts))]
[ToggleSlider]
[ShowPropertyEditorWhen(nameof(IsCheck1Visible), true)]
public bool Check1 { get => _check1; set => Set(ref _check1, value); }
bool _check1;
[Display(GroupName = nameof(Texts.ParametersGroup), Name = nameof(Texts.Check2), Description = nameof(Texts.CheckDesc), ResourceType = typeof(Texts))]
[ToggleSlider]
[ShowPropertyEditorWhen(nameof(IsCheck2Visible), true)]
public bool Check2 { get => _check2; set => Set(ref _check2, value); }
bool _check2;
[Display(GroupName = nameof(Texts.ParametersGroup), Name = nameof(Texts.Check3), Description = nameof(Texts.CheckDesc), ResourceType = typeof(Texts))]
[ToggleSlider]
[ShowPropertyEditorWhen(nameof(IsCheck3Visible), true)]
public bool Check3 { get => _check3; set => Set(ref _check3, value); }
bool _check3;
[Display(GroupName = nameof(Texts.ParametersGroup), Name = nameof(Texts.Color), Description = nameof(Texts.ColorDesc), ResourceType = typeof(Texts))]
[ColorPicker]
[ShowPropertyEditorWhen(nameof(IsColorVisible), true)]
public Color Color { get => _color; set => Set(ref _color, value); }
Color _color = Colors.White;
[JsonIgnore] public bool IsTrack0Visible { get => _isTrack0Visible; private set => Set(ref _isTrack0Visible, value); }
[JsonIgnore] public bool IsTrack1Visible { get => _isTrack1Visible; private set => Set(ref _isTrack1Visible, value); }
[JsonIgnore] public bool IsTrack2Visible { get => _isTrack2Visible; private set => Set(ref _isTrack2Visible, value); }
[JsonIgnore] public bool IsTrack3Visible { get => _isTrack3Visible; private set => Set(ref _isTrack3Visible, value); }
[JsonIgnore] public bool IsCheck0Visible { get => _isCheck0Visible; private set => Set(ref _isCheck0Visible, value); }
[JsonIgnore] public bool IsCheck1Visible { get => _isCheck1Visible; private set => Set(ref _isCheck1Visible, value); }
[JsonIgnore] public bool IsCheck2Visible { get => _isCheck2Visible; private set => Set(ref _isCheck2Visible, value); }
[JsonIgnore] public bool IsCheck3Visible { get => _isCheck3Visible; private set => Set(ref _isCheck3Visible, value); }
[JsonIgnore] public bool IsColorVisible { get => _isColorVisible; private set => Set(ref _isColorVisible, value); }
bool _isTrack0Visible = true;
bool _isTrack1Visible = true;
bool _isTrack2Visible = true;
bool _isTrack3Visible = true;
bool _isCheck0Visible;
bool _isCheck1Visible;
bool _isCheck2Visible;
bool _isCheck3Visible;
bool _isColorVisible;
private void UpdateLayout()
{
var layout = AviUtlParameterLayout.Parse(_script);
Layout = layout;
bool hasAny = layout.HasAny;
IsTrack0Visible = !hasAny || layout.HasTrack(0);
IsTrack1Visible = !hasAny || layout.HasTrack(1);
IsTrack2Visible = !hasAny || layout.HasTrack(2);
IsTrack3Visible = !hasAny || layout.HasTrack(3);
IsCheck0Visible = layout.HasCheck(0);
IsCheck1Visible = layout.HasCheck(1);
IsCheck2Visible = layout.HasCheck(2);
IsCheck3Visible = layout.HasCheck(3);
IsColorVisible = layout.HasColor;
SeedDefaults(layout);
}
private void SeedDefaults(AviUtlParameterLayout layout)
{
if (layout.GetCheck(0) is { Default: true } && !_check0) Check0 = true;
if (layout.GetCheck(1) is { Default: true } && !_check1) Check1 = true;
if (layout.GetCheck(2) is { Default: true } && !_check2) Check2 = true;
if (layout.GetCheck(3) is { Default: true } && !_check3) Check3 = true;
if (layout.Color is { } color && _color == Colors.White)
Color = ToMediaColor(color.Default);
}
private static Color ToMediaColor(int rgb)
{
byte r = (byte)((rgb >> 16) & 0xFF);
byte g = (byte)((rgb >> 8) & 0xFF);
byte b = (byte)(rgb & 0xFF);
return Color.FromRgb(r, g, b);
}
public override IEnumerable<string> CreateExoVideoFilters(int keyFrameIndex, ExoOutputDescription exoOutputDescription) => [];
public override IVideoEffectProcessor CreateVideoEffect(IGraphicsDevicesAndContext devices)
+250 -70
ファイルの表示
@@ -1,5 +1,8 @@
using System.IO;
using System.Numerics;
using System.Runtime.InteropServices;
using LuaScript.Compat;
using LuaScript.Engine;
using Vortice;
using Vortice.DCommon;
using Vortice.Direct2D1;
@@ -25,6 +28,12 @@ namespace LuaScript
double Track1,
double Track2,
double Track3,
bool Check0,
bool Check1,
bool Check2,
bool Check3,
bool HasColor,
int Color,
string Script,
TimelineSourceUsage Usage,
Guid SceneId,
@@ -42,8 +51,27 @@ namespace LuaScript
DrawDescription InputDesc
);
private const int NativeTimeoutMilliseconds = 5000;
private static string NativeDirectory =>
Path.Combine(Path.GetDirectoryName(typeof(LuaScriptEffectProcessor).Assembly.Location) ?? AppContext.BaseDirectory, "native");
private readonly LuaScriptEngine _engine = new();
private readonly SemaphoreSlim _pixelLoaderSemaphore = new(1, 1);
private AviUtlScriptContext _context = new();
private LuaJitWorker? _nativeWorker;
private double[]? _nativeFields;
private bool _nativeWarned;
private bool _effectChainWarned;
private EffectDescription? _frameDesc;
private SceneObjectResolver? _frameResolver;
private bool _frameResolverBuilt;
private Guid _lastSceneGuid;
private string _lastSceneId = string.Empty;
private bool _sceneIdCached;
private GraphicsDevicesAndContext? _ownCtx;
@@ -57,19 +85,57 @@ namespace LuaScript
private RawRectF _cachedBounds;
private bool _isFirst = true;
private string _sourceScript = string.Empty;
private string _runnableScript = string.Empty;
private bool _runnableCached;
private ID2D1Image? _cachedInput;
private RenderKey _cachedKey;
private SceneObjectQuery[] _cachedQueries = [];
private DrawDescription? _cachedOutputDesc;
private bool _cachedPixelsModified;
private ID2D1Image? _cachedEffectOutput;
private VideoEffectChain? _effectChain;
protected override ID2D1Image? CreateEffect(IGraphicsDevicesAndContext devices)
{
_ownCtx = new GraphicsDevicesAndContext(devices);
disposer.Collect(_ownCtx);
_context.ResolverProvider = GetFrameResolver;
return null;
}
private SceneObjectResolver GetFrameResolver()
{
if (!_frameResolverBuilt)
{
_frameResolver = BuildSceneObjectResolver(_frameDesc!);
_frameResolverBuilt = true;
}
return _frameResolver!;
}
private string ResolveSceneId(Guid sceneId)
{
if (!_sceneIdCached || sceneId != _lastSceneGuid)
{
_lastSceneId = sceneId.ToString();
_lastSceneGuid = sceneId;
_sceneIdCached = true;
}
return _lastSceneId;
}
private string GetRunnableScript(string source)
{
if (_runnableCached && string.Equals(source, _sourceScript, StringComparison.Ordinal))
return _runnableScript;
_runnableScript = AviUtlScript.Transform(source);
_sourceScript = source;
_runnableCached = true;
return _runnableScript;
}
protected override void setInput(ID2D1Image? input)
{
if (!ReferenceEquals(_cachedInput, input))
@@ -93,16 +159,22 @@ namespace LuaScript
var time = desc.ItemPosition.Time.TotalSeconds;
var script = item.Script ?? string.Empty;
var t0 = item.Track0.GetValue(frame, length, fps);
var t1 = item.Track1.GetValue(frame, length, fps);
var t2 = item.Track2.GetValue(frame, length, fps);
var t3 = item.Track3.GetValue(frame, length, fps);
var layout = item.Layout;
var t0 = ClampTrack(item.Track0.GetValue(frame, length, fps), layout, 0);
var t1 = ClampTrack(item.Track1.GetValue(frame, length, fps), layout, 1);
var t2 = ClampTrack(item.Track2.GetValue(frame, length, fps), layout, 2);
var t3 = ClampTrack(item.Track3.GetValue(frame, length, fps), layout, 3);
bool c0 = item.Check0, c1 = item.Check1, c2 = item.Check2, c3 = item.Check3;
bool hasColor = layout.HasColor;
int colorRgb = hasColor ? (item.Color.R << 16) | (item.Color.G << 8) | item.Color.B : 0;
var inDesc = desc.DrawDescription;
var key = new RenderKey(
frame, time, length, fps,
t0, t1, t2, t3,
c0, c1, c2, c3, hasColor, colorRgb,
script, desc.Usage, desc.SceneId,
desc.TimelinePosition.Frame,
desc.TimelinePosition.Time.TotalSeconds,
@@ -113,12 +185,14 @@ namespace LuaScript
desc.TimelineDuration.Time.TotalSeconds,
inDesc);
var resolver = BuildSceneObjectResolver(desc);
_frameDesc = desc;
_frameResolver = null;
_frameResolverBuilt = false;
if (!_isFirst && key == _cachedKey &&
QueriesMatch(_cachedQueries, resolver))
(_cachedQueries.Length == 0 || QueriesMatch(_cachedQueries, GetFrameResolver())))
{
effectOutput = _cachedPixelsModified ? _transformEffect?.Output : null;
effectOutput = _cachedEffectOutput;
return _cachedOutputDesc ?? inDesc;
}
@@ -126,30 +200,69 @@ namespace LuaScript
int imgW = Math.Max(1, (int)Math.Ceiling(bounds.Right - bounds.Left));
int imgH = Math.Max(1, (int)Math.Ceiling(bounds.Bottom - bounds.Top));
var ctx = BuildContext(in key, imgW, imgH, resolver);
var ctx = _context;
PopulateContext(ctx, in key, imgW, imgH);
ctx.SetPixelLoader(() => LoadInputPixels(bounds, imgW, imgH));
DrawDescription outDesc = inDesc;
bool pixelsModified = false;
try
{
_engine.Execute(script, ctx);
string runnable = GetRunnableScript(script);
bool wantNative = ScriptDirective.ResolveAuto(runnable) == ScriptEngineKind.Native;
bool nativeReady = wantNative && LuaJitWorker.IsAvailable(NativeDirectory);
if (wantNative && !nativeReady)
WarnNativeUnavailableOnce();
if (ctx.IsPixelsDirty)
if (nativeReady)
{
EnsureBitmaps(imgW, imgH);
WritePixelsToOutput(ctx.GetPixelBuffer()!, imgW);
UpdateTransformEffect(bounds);
effectOutput = _transformEffect!.Output;
pixelsModified = true;
ExecuteNative(runnable, ctx, bounds, imgW, imgH);
}
else
{
effectOutput = null;
_engine.Execute(runnable, ctx);
if (ctx.IsPixelsDirty)
{
int bufW = ctx.ImageWidth;
int bufH = ctx.ImageHeight;
EnsureBitmaps(bufW, bufH);
WritePixelsToOutput(ctx.GetPixelBuffer()!, bufW);
if (ctx.BufferReplaced)
UpdateTransformEffect(-bufW / 2f, -bufH / 2f);
else
UpdateTransformEffect(bounds.Left, bounds.Top);
effectOutput = _transformEffect!.Output;
}
else
{
effectOutput = null;
}
}
outDesc = BuildOutputDesc(inDesc, ctx);
if (ctx.EffectRequests.Count > 0)
{
var source = effectOutput ?? input;
try
{
effectOutput = ApplyEffectChain(source, ctx.EffectRequests, desc, ref outDesc);
}
catch (Exception ex)
{
effectOutput = source;
WarnEffectChainFailureOnce(ex);
}
}
}
catch (LuaScriptTimeoutException ex)
{
effectOutput = null;
_context = new AviUtlScriptContext { ResolverProvider = GetFrameResolver };
_isFirst = true;
Log.Default.Write(ex.Message, ex);
return inDesc;
}
catch (LuaScriptException ex)
{
@@ -165,13 +278,19 @@ namespace LuaScript
_isFirst = false;
_cachedKey = key;
_cachedQueries = [.. ctx.ObjectQueries];
_cachedQueries = ctx.ObjectQueries.Count == 0 ? [] : [.. ctx.ObjectQueries];
_cachedOutputDesc = outDesc;
_cachedPixelsModified = pixelsModified;
_cachedEffectOutput = effectOutput;
return outDesc;
}
private ID2D1Image ApplyEffectChain(ID2D1Image source, IReadOnlyList<AviUtlEffectRequest> requests, EffectDescription desc, ref DrawDescription drawDescription)
{
_effectChain ??= new VideoEffectChain(_ownCtx!);
return _effectChain.Apply(source, requests, desc, ref drawDescription);
}
private static SceneObjectResolver BuildSceneObjectResolver(EffectDescription desc)
{
var scenes = desc.Scenes;
@@ -219,7 +338,7 @@ namespace LuaScript
return true;
}
private static AviUtlScriptContext BuildContext(in RenderKey key, int imgW, int imgH, SceneObjectResolver resolver)
private void PopulateContext(AviUtlScriptContext ctx, in RenderKey key, int imgW, int imgH)
{
var zoom = key.InputDesc.Zoom;
double zoomAvg = (zoom.X + zoom.Y) / 2d;
@@ -227,51 +346,61 @@ namespace LuaScript
? (zoom.X - zoom.Y) / (zoom.X + zoom.Y)
: 0d;
return new AviUtlScriptContext
{
ImageWidth = imgW,
ImageHeight = imgH,
X = key.InputDesc.Draw.X,
Y = key.InputDesc.Draw.Y,
Z = key.InputDesc.Draw.Z,
Ox = key.InputDesc.CenterPoint.X,
Oy = key.InputDesc.CenterPoint.Y,
Oz = 0d,
Sx = zoom.X,
Sy = zoom.Y,
Zoom = zoomAvg,
Aspect = aspect,
Alpha = key.InputDesc.Opacity * 255d,
Rx = key.InputDesc.Rotation.X,
Ry = key.InputDesc.Rotation.Y,
Rz = key.InputDesc.Rotation.Z,
Track0 = key.Track0,
Track1 = key.Track1,
Track2 = key.Track2,
Track3 = key.Track3,
Time = key.Time,
Frame = key.Frame,
TotalFrame = key.Length,
TotalTime = key.Fps > 0 ? key.Length / (double)key.Fps : 0d,
Framerate = key.Fps,
TimelineFrame = key.TimelineFrame,
TimelineTime = key.TimelineTime,
SceneWidth = key.SceneWidth,
SceneHeight = key.SceneHeight,
Layer = key.Layer,
Index = key.InputIndex,
Num = key.InputCount,
GroupIndex = key.GroupIndex,
GroupCount = key.GroupCount,
TimelineTotalFrame = key.TimelineTotalFrame,
TimelineTotalTime = key.TimelineTotalTime,
IsSaving = key.Usage == TimelineSourceUsage.Exporting,
IsPlaying = key.Usage == TimelineSourceUsage.Playing,
IsPaused = key.Usage == TimelineSourceUsage.Paused,
SceneId = key.SceneId.ToString(),
TimeRatio = key.Length > 0 ? key.Frame / (double)key.Length : 0d,
Resolver = resolver,
};
ctx.ClearQueries();
ctx.ClearEffects();
ctx.ImageWidth = imgW;
ctx.ImageHeight = imgH;
ctx.X = key.InputDesc.Draw.X;
ctx.Y = key.InputDesc.Draw.Y;
ctx.Z = key.InputDesc.Draw.Z;
ctx.Ox = key.InputDesc.CenterPoint.X;
ctx.Oy = key.InputDesc.CenterPoint.Y;
ctx.Oz = 0d;
ctx.Sx = zoom.X;
ctx.Sy = zoom.Y;
ctx.Zoom = zoomAvg;
ctx.Aspect = aspect;
ctx.Alpha = key.InputDesc.Opacity * 255d;
ctx.Rx = key.InputDesc.Rotation.X;
ctx.Ry = key.InputDesc.Rotation.Y;
ctx.Rz = key.InputDesc.Rotation.Z;
ctx.Track0 = key.Track0;
ctx.Track1 = key.Track1;
ctx.Track2 = key.Track2;
ctx.Track3 = key.Track3;
ctx.Check0 = key.Check0;
ctx.Check1 = key.Check1;
ctx.Check2 = key.Check2;
ctx.Check3 = key.Check3;
ctx.HasColor = key.HasColor;
ctx.ColorValue = key.Color;
ctx.Time = key.Time;
ctx.Frame = key.Frame;
ctx.TotalFrame = key.Length;
ctx.TotalTime = key.Fps > 0 ? key.Length / (double)key.Fps : 0d;
ctx.Framerate = key.Fps;
ctx.TimelineFrame = key.TimelineFrame;
ctx.TimelineTime = key.TimelineTime;
ctx.SceneWidth = key.SceneWidth;
ctx.SceneHeight = key.SceneHeight;
ctx.Layer = key.Layer;
ctx.Index = key.InputIndex;
ctx.Num = key.InputCount;
ctx.GroupIndex = key.GroupIndex;
ctx.GroupCount = key.GroupCount;
ctx.TimelineTotalFrame = key.TimelineTotalFrame;
ctx.TimelineTotalTime = key.TimelineTotalTime;
ctx.IsSaving = key.Usage == TimelineSourceUsage.Exporting;
ctx.IsPlaying = key.Usage == TimelineSourceUsage.Playing;
ctx.IsPaused = key.Usage == TimelineSourceUsage.Paused;
ctx.SceneId = ResolveSceneId(key.SceneId);
ctx.TimeRatio = key.Length > 0 ? key.Frame / (double)key.Length : 0d;
}
private static double ClampTrack(double value, AviUtlParameterLayout layout, int index)
{
return layout.GetTrack(index) is { } p ? Math.Clamp(value, p.Min, p.Max) : value;
}
private static DrawDescription BuildOutputDesc(DrawDescription inDesc, AviUtlScriptContext ctx)
@@ -286,6 +415,55 @@ namespace LuaScript
};
}
private void WarnNativeUnavailableOnce()
{
if (_nativeWarned) return;
_nativeWarned = true;
Log.Default.Write($"LuaScript: native runtime not found at '{NativeDirectory}'. Falling back to MoonSharp (slow). Deploy the 'native' folder next to the plugin.");
}
private void WarnEffectChainFailureOnce(Exception ex)
{
if (_effectChainWarned) return;
_effectChainWarned = true;
Log.Default.Write("LuaScript: obj.effect chain failed and was skipped for this frame. The source image is passed through unchanged.", ex);
}
private bool ExecuteNative(string script, AviUtlScriptContext ctx, RawRectF bounds, int imgW, int imgH)
{
_nativeWorker ??= new LuaJitWorker(NativeDirectory);
_nativeFields ??= new double[NativeProtocol.FieldCount];
NativeFieldMap.ToFields(ctx, _nativeFields);
byte[] buffer = LoadInputPixels(bounds, imgW, imgH);
bool ok = _nativeWorker.Execute(
script, _nativeFields, buffer, imgW, imgH, NativeTimeoutMilliseconds,
(tag, frame) => ctx.ResolveObject(tag, frame, out var info) ? info : null,
out bool dirty, out string? error);
if (!ok)
{
if (error is not null && error.Contains("timed out", StringComparison.Ordinal))
throw new LuaScriptTimeoutException(error);
throw new LuaScriptRuntimeException(error ?? "Native script execution failed.");
}
NativeFieldMap.FromFields(_nativeFields, ctx);
if (dirty)
{
EnsureBitmaps(imgW, imgH);
WritePixelsToOutput(buffer, imgW);
UpdateTransformEffect(bounds.Left, bounds.Top);
effectOutput = _transformEffect!.Output;
return true;
}
effectOutput = null;
return false;
}
private byte[] LoadInputPixels(RawRectF bounds, int width, int height)
{
_pixelLoaderSemaphore.Wait();
@@ -341,7 +519,7 @@ namespace LuaScript
_outputBitmap!.CopyFromMemory(new nint(ptr), width * 4);
}
private void UpdateTransformEffect(RawRectF bounds)
private void UpdateTransformEffect(float left, float top)
{
if (_transformEffect is null)
{
@@ -350,10 +528,10 @@ namespace LuaScript
_cachedBounds = default;
}
if (_cachedBounds.Left != bounds.Left || _cachedBounds.Top != bounds.Top)
if (_cachedBounds.Left != left || _cachedBounds.Top != top)
{
_transformEffect.TransformMatrix = Matrix3x2.CreateTranslation(bounds.Left, bounds.Top);
_cachedBounds = bounds;
_transformEffect.TransformMatrix = Matrix3x2.CreateTranslation(left, top);
_cachedBounds = new RawRectF(left, top, left, top);
}
}
@@ -398,6 +576,8 @@ namespace LuaScript
if (disposing)
{
_engine.Dispose();
_nativeWorker?.Dispose();
_effectChain?.Dispose();
_pixelLoaderSemaphore.Dispose();
_renderTarget?.Dispose();
_stagingBitmap?.Dispose();
+148 -62
ファイルの表示
@@ -1,4 +1,4 @@
using System.Collections.Concurrent;
using LuaScript.Compat;
using MoonSharp.Interpreter;
using MoonSharp.Interpreter.Debugging;
using MoonSharp.Interpreter.Loaders;
@@ -11,12 +11,6 @@ namespace LuaScript
LuaScriptException? Exception,
bool TimedOut);
private sealed record ExecutionJob(
string Code,
AviUtlScriptContext Context,
CancellationToken Cancellation,
TaskCompletionSource<ExecutionResult> Completion);
private sealed class ExecutionThread : IDisposable
{
private sealed class CancellationDebugger : IDebugger
@@ -46,10 +40,19 @@ namespace LuaScript
}
}
private readonly BlockingCollection<ExecutionJob> _queue = new(boundedCapacity: 1);
private readonly SemaphoreSlim _workSignal = new(0);
private readonly ManualResetEventSlim _doneSignal = new(false);
private readonly CancellationTokenSource _cts = new();
private readonly Thread _thread;
private readonly CancellationDebugger _debugger = new();
private string _jobCode = string.Empty;
private AviUtlScriptContext? _jobContext;
private LuaScriptException? _jobException;
private volatile bool _disposeRequested;
private readonly List<string> _removalBuffer = [];
private Script? _script;
private DynValue? _compiledChunk;
private string _lastCompiledCode = string.Empty;
@@ -67,6 +70,8 @@ namespace LuaScript
internal ExecutionThread()
{
_activeCancellation = _cts.Token;
_debugger.UpdateToken(_cts.Token);
_thread = new Thread(WorkerLoop)
{
IsBackground = true,
@@ -77,77 +82,65 @@ namespace LuaScript
internal ExecutionResult TryExecute(string code, AviUtlScriptContext ctx, int timeoutMs)
{
using var cts = new CancellationTokenSource();
var tcs = new TaskCompletionSource<ExecutionResult>(
TaskCreationOptions.RunContinuationsAsynchronously);
_jobCode = code;
_jobContext = ctx;
_jobException = null;
_doneSignal.Reset();
_workSignal.Release();
if (!_queue.TryAdd(new ExecutionJob(code, ctx, cts.Token, tcs)))
return new ExecutionResult(
new LuaScriptRuntimeException("Script execution queue is full."), false);
if (_doneSignal.Wait(timeoutMs))
return new ExecutionResult(_jobException, false);
if (tcs.Task.Wait(timeoutMs))
return tcs.Task.Result;
cts.Cancel();
_cts.Cancel();
return new ExecutionResult(null, TimedOut: true);
}
private void WorkerLoop()
{
try
while (true)
{
foreach (var job in _queue.GetConsumingEnumerable())
ProcessJob(job);
_workSignal.Wait();
if (_disposeRequested)
return;
ProcessJob();
_doneSignal.Set();
}
catch (OperationCanceledException) { }
catch (InvalidOperationException) { }
}
private void ProcessJob(ExecutionJob job)
private void ProcessJob()
{
if (job.Cancellation.IsCancellationRequested)
{
job.Completion.TrySetResult(new ExecutionResult(null, TimedOut: true));
return;
}
_activeCancellation = job.Cancellation;
_activeContext = job.Context;
_debugger.UpdateToken(job.Cancellation);
var context = _jobContext!;
_activeContext = context;
try
{
EnsureScript();
EnsureScriptIntegrity();
EnsureCompiled(job.Code);
SetupGlobals(job.Context);
EnsureCompiled(_jobCode);
SetupGlobals(context);
_script!.Call(_compiledChunk!);
ReadBackGlobals(job.Context);
job.Completion.TrySetResult(new ExecutionResult(null, false));
ReadBackGlobals(context);
_jobException = null;
}
catch (OperationCanceledException) when (job.Cancellation.IsCancellationRequested)
catch (OperationCanceledException) when (_cts.IsCancellationRequested)
{
job.Completion.TrySetResult(new ExecutionResult(null, TimedOut: true));
_jobException = null;
}
catch (LuaScriptException ex)
{
job.Completion.TrySetResult(new ExecutionResult(ex, false));
_jobException = ex;
}
catch (ScriptRuntimeException ex)
{
job.Completion.TrySetResult(new ExecutionResult(
new LuaScriptRuntimeException(ex.DecoratedMessage ?? ex.Message, ex), false));
_jobException = new LuaScriptRuntimeException(ex.DecoratedMessage ?? ex.Message, ex);
}
catch (Exception ex)
{
job.Completion.TrySetResult(new ExecutionResult(
new LuaScriptRuntimeException(ex.Message, ex), false));
_jobException = new LuaScriptRuntimeException(ex.Message, ex);
}
finally
{
_debugger.UpdateToken(default);
_activeContext = null;
_activeCancellation = default;
}
}
@@ -269,10 +262,10 @@ namespace LuaScript
_ymm4TableSnapshot = null;
}
ResetUserTableKeys(_objTable!, ref _objTableSnapshot);
ResetUserTableKeys(_sceneTable!, ref _sceneTableSnapshot);
ResetUserTableKeys(_animTable!, ref _animTableSnapshot);
ResetUserTableKeys(_ymm4Table!, ref _ymm4TableSnapshot);
ResetUserTableKeys(_objTable!, _objTableSnapshot);
ResetUserTableKeys(_sceneTable!, _sceneTableSnapshot);
ResetUserTableKeys(_animTable!, _animTableSnapshot);
ResetUserTableKeys(_ymm4Table!, _ymm4TableSnapshot);
}
script.Globals["time"] = ctx.Time;
@@ -320,6 +313,12 @@ namespace LuaScript
_objTable!["track1"] = ctx.Track1;
_objTable!["track2"] = ctx.Track2;
_objTable!["track3"] = ctx.Track3;
_objTable!["check0"] = ctx.Check0;
_objTable!["check1"] = ctx.Check1;
_objTable!["check2"] = ctx.Check2;
_objTable!["check3"] = ctx.Check3;
if (ctx.HasColor)
script.Globals["color"] = ctx.ColorValue;
_objTable!["time"] = ctx.Time;
_objTable!["frame"] = ctx.Frame;
_objTable!["totalframe"] = ctx.TotalFrame;
@@ -366,34 +365,36 @@ namespace LuaScript
return keys;
}
private static void ResetUserTableKeys(Table table, ref HashSet<string>? snapshot)
private void ResetUserTableKeys(Table table, HashSet<string>? snapshot)
{
if (snapshot is null) return;
var keysToRemove = new List<string>();
var buffer = _removalBuffer;
buffer.Clear();
foreach (var key in table.Keys)
{
if (key.Type == DataType.String &&
!snapshot.Contains(key.String))
{
keysToRemove.Add(key.String);
buffer.Add(key.String);
}
}
foreach (var key in keysToRemove)
foreach (var key in buffer)
table[key] = DynValue.Nil;
}
private void ResetUserGlobals(Script script)
{
var keysToRemove = new List<string>();
var buffer = _removalBuffer;
buffer.Clear();
foreach (var key in script.Globals.Keys)
{
if (key.Type == DataType.String &&
!_builtinGlobalSnapshot!.Contains(key.String))
{
keysToRemove.Add(key.String);
buffer.Add(key.String);
}
}
foreach (var key in keysToRemove)
foreach (var key in buffer)
script.Globals[key] = DynValue.Nil;
}
@@ -457,6 +458,84 @@ namespace LuaScript
});
obj["putpixeldata"] = DynValue.NewCallback((_, _) => DynValue.Void);
obj["rand"] = DynValue.NewCallback((_, args) =>
{
_activeCancellation.ThrowIfCancellationRequested();
double frameDefault = _activeContext?.Frame ?? 0d;
double a = args.Count > 0 ? args[0].CastToNumber() ?? 0d : 0d;
double b = args.Count > 1 ? args[1].CastToNumber() ?? 0d : 0d;
double seed = args.Count > 2 ? args[2].CastToNumber() ?? 0d : 0d;
double frame = args.Count > 3 ? args[3].CastToNumber() ?? frameDefault : frameDefault;
return DynValue.NewNumber(AviUtlRandom.Next(a, b, seed, frame));
});
obj["load"] = DynValue.NewCallback((_, args) =>
{
_activeCancellation.ThrowIfCancellationRequested();
if (_activeContext is null || args.Count < 4)
return DynValue.Void;
if (args[0].Type != DataType.String || args[0].String != "figure")
return DynValue.Void;
string name = args[1].Type == DataType.String ? args[1].String : string.Empty;
int color = (int)(args[2].CastToNumber() ?? 0d);
double size = args[3].CastToNumber() ?? 0d;
double line = args.Count > 4 ? args[4].CastToNumber() ?? 0d : 0d;
double aspect = args.Count > 5 ? Math.Clamp(args[5].CastToNumber() ?? 0d, -1d, 1d) : 0d;
LoadFigure(name, color, size, line, aspect);
return DynValue.Void;
});
obj["effect"] = DynValue.NewCallback((_, args) =>
{
_activeCancellation.ThrowIfCancellationRequested();
if (_activeContext is null || args.Count == 0 || args[0].Type != DataType.String)
return DynValue.Void;
string name = args[0].String;
var arguments = new List<KeyValuePair<string, object>>();
for (int i = 1; i + 1 < args.Count; i += 2)
{
if (args[i].Type != DataType.String)
continue;
var value = args[i + 1];
object boxed = value.Type switch
{
DataType.Number => value.Number,
DataType.Boolean => value.Boolean,
DataType.String => value.String,
_ => value.CastToNumber() ?? 0d,
};
arguments.Add(new KeyValuePair<string, object>(args[i].String, boxed));
}
_activeContext.AddEffect(new AviUtlEffectRequest(name, arguments));
return DynValue.Void;
});
}
private void LoadFigure(string name, int color, double size, double line, double aspect)
{
int boundingSize = Math.Max(1, (int)Math.Round(size));
double width = aspect >= 0d ? boundingSize * (1d - aspect) : boundingSize;
double height = aspect <= 0d ? boundingSize * (1d + aspect) : boundingSize;
int w = Math.Max(1, (int)Math.Round(width));
int h = Math.Max(1, (int)Math.Round(height));
var buffer = FigureRenderer.Render(name, w, h, color, line);
_activeContext!.ReplaceBuffer(buffer, w, h);
var obj = _objTable!;
obj["w"] = w;
obj["h"] = h;
obj["hw"] = w / 2d;
obj["hh"] = h / 2d;
obj["cx"] = w / 2d;
obj["cy"] = h / 2d;
obj["cz"] = 0d;
obj["diagonal"] = Math.Sqrt((double)w * w + (double)h * h);
}
private static DynValue BuildObjectTable(Script script, SceneObjectInfo info)
@@ -531,18 +610,25 @@ namespace LuaScript
public void Dispose()
{
_queue.CompleteAdding();
_disposeRequested = true;
_workSignal.Release();
_thread.Join();
_queue.Dispose();
_cts.Cancel();
_cts.Dispose();
_workSignal.Dispose();
_doneSignal.Dispose();
}
internal void AbandonAsync()
{
_queue.CompleteAdding();
_disposeRequested = true;
_workSignal.Release();
ThreadPool.QueueUserWorkItem(_ =>
{
_thread.Join();
_queue.Dispose();
_cts.Dispose();
_workSignal.Dispose();
_doneSignal.Dispose();
});
}
@@ -577,7 +663,7 @@ namespace LuaScript
var stale = _executionThread;
_executionThread = new ExecutionThread();
stale.AbandonAsync();
throw new LuaScriptRuntimeException(
throw new LuaScriptTimeoutException(
$"Script execution timed out after {ExecutionTimeoutMilliseconds} ms.");
}
+2
ファイルの表示
@@ -5,4 +5,6 @@ namespace LuaScript
internal sealed class LuaScriptCompilationException(string message, Exception? inner = null) : LuaScriptException(message, inner);
internal sealed class LuaScriptRuntimeException(string message, Exception? inner = null) : LuaScriptException(message, inner);
internal sealed class LuaScriptTimeoutException(string message, Exception? inner = null) : LuaScriptException(message, inner);
}
+7
ファイルの表示
@@ -69,6 +69,13 @@
<data name="Track2" xml:space="preserve"><value>مسار 2</value></data>
<data name="Track3" xml:space="preserve"><value>مسار 3</value></data>
<data name="TrackDesc" xml:space="preserve"><value>قيمة المنزلق (متوافق مع AviUtl: track0-3)</value></data>
<data name="Check0" xml:space="preserve"><value>خانة 0</value></data>
<data name="Check1" xml:space="preserve"><value>خانة 1</value></data>
<data name="Check2" xml:space="preserve"><value>خانة 2</value></data>
<data name="Check3" xml:space="preserve"><value>خانة 3</value></data>
<data name="CheckDesc" xml:space="preserve"><value>قيمة خانة الاختيار (متوافق مع AviUtl: check0-3)</value></data>
<data name="Color" xml:space="preserve"><value>اللون</value></data>
<data name="ColorDesc" xml:space="preserve"><value>اللون (متوافق مع AviUtl: --color)</value></data>
<data name="ToolBarImport" xml:space="preserve"><value>استيراد</value></data>
<data name="ToolBarExport" xml:space="preserve"><value>تصدير</value></data>
<data name="ToolBarClear" xml:space="preserve"><value>مسح</value></data>
+7
ファイルの表示
@@ -9,6 +9,13 @@ Track1,,トラック1,Track 1,轨道1,軌道1,트랙1,Pista 1,مسار 1,Jalur 1
Track2,,トラック2,Track 2,轨道2,軌道2,트랙2,Pista 2,مسار 2,Jalur 2
Track3,,トラック3,Track 3,轨道3,軌道3,트랙3,Pista 3,مسار 3,Jalur 3
TrackDesc,,スライダー値 (AviUtl準拠 track0〜3 に対応),Slider value (AviUtl compatible: track0–3),滑块值(AviUtl兼容: track0~3),滑塊值(AviUtl兼容: track0~3),슬라이더 값 (AviUtl 호환: track0~3),Valor del deslizador (compatible AviUtl: track0-3),قيمة المنزلق (متوافق مع AviUtl: track0-3),Nilai slider (kompatibel AviUtl: track0-3)
Check0,,チェック0,Check 0,复选框0,核取方塊0,체크0,Casilla 0,خانة 0,Centang 0
Check1,,チェック1,Check 1,复选框1,核取方塊1,체크1,Casilla 1,خانة 1,Centang 1
Check2,,チェック2,Check 2,复选框2,核取方塊2,체크2,Casilla 2,خانة 2,Centang 2
Check3,,チェック3,Check 3,复选框3,核取方塊3,체크3,Casilla 3,خانة 3,Centang 3
CheckDesc,,チェックボックス値 (AviUtl準拠 check0〜3 に対応),Checkbox value (AviUtl compatible: check0–3),复选框值(AviUtl兼容: check0~3),核取方塊值(AviUtl兼容: check0~3),체크박스 값 (AviUtl 호환: check0~3),Valor de casilla (compatible AviUtl: check0-3),قيمة خانة الاختيار (متوافق مع AviUtl: check0-3),Nilai kotak centang (kompatibel AviUtl: check0-3)
Color,,色,Color,颜色,顏色,색,Color,اللون,Warna
ColorDesc,,色 (AviUtl準拠 --color に対応),Color (AviUtl compatible: --color),颜色(AviUtl兼容: --color),顏色(AviUtl兼容: --color),색 (AviUtl 호환: --color),Color (compatible AviUtl: --color),اللون (متوافق مع AviUtl: --color),Warna (kompatibel AviUtl: --color)
ToolBarImport,,インポート,Import,导入,導入,가져오기,Importar,استيراد,Impor
ToolBarExport,,エクスポート,Export,导出,導出,내보내기,Exportar,تصدير,Ekspor
ToolBarClear,,クリア,Clear,清除,清除,지우기,Limpiar,مسح,Hapus
1 Key Parameter ja-jp en-us zh-cn zh-tw ko-kr es-es ar-sa id-id
9 Track2 トラック2 Track 2 轨道2 軌道2 트랙2 Pista 2 مسار 2 Jalur 2
10 Track3 トラック3 Track 3 轨道3 軌道3 트랙3 Pista 3 مسار 3 Jalur 3
11 TrackDesc スライダー値 (AviUtl準拠 track0〜3 に対応) Slider value (AviUtl compatible: track0–3) 滑块值(AviUtl兼容: track0~3) 滑塊值(AviUtl兼容: track0~3) 슬라이더 값 (AviUtl 호환: track0~3) Valor del deslizador (compatible AviUtl: track0-3) قيمة المنزلق (متوافق مع AviUtl: track0-3) Nilai slider (kompatibel AviUtl: track0-3)
12 Check0 チェック0 Check 0 复选框0 核取方塊0 체크0 Casilla 0 خانة 0 Centang 0
13 Check1 チェック1 Check 1 复选框1 核取方塊1 체크1 Casilla 1 خانة 1 Centang 1
14 Check2 チェック2 Check 2 复选框2 核取方塊2 체크2 Casilla 2 خانة 2 Centang 2
15 Check3 チェック3 Check 3 复选框3 核取方塊3 체크3 Casilla 3 خانة 3 Centang 3
16 CheckDesc チェックボックス値 (AviUtl準拠 check0〜3 に対応) Checkbox value (AviUtl compatible: check0–3) 复选框值(AviUtl兼容: check0~3) 核取方塊值(AviUtl兼容: check0~3) 체크박스 값 (AviUtl 호환: check0~3) Valor de casilla (compatible AviUtl: check0-3) قيمة خانة الاختيار (متوافق مع AviUtl: check0-3) Nilai kotak centang (kompatibel AviUtl: check0-3)
17 Color 色 Color 颜色 顏色 색 Color اللون Warna
18 ColorDesc 色 (AviUtl準拠 --color に対応) Color (AviUtl compatible: --color) 颜色(AviUtl兼容: --color) 顏色(AviUtl兼容: --color) 색 (AviUtl 호환: --color) Color (compatible AviUtl: --color) اللون (متوافق مع AviUtl: --color) Warna (kompatibel AviUtl: --color)
19 ToolBarImport インポート Import 导入 導入 가져오기 Importar استيراد Impor
20 ToolBarExport エクスポート Export 导出 導出 내보내기 Exportar تصدير Ekspor
21 ToolBarClear クリア Clear 清除 清除 지우기 Limpiar مسح Hapus
+7
ファイルの表示
@@ -69,6 +69,13 @@
<data name="Track2" xml:space="preserve"><value>Track 2</value></data>
<data name="Track3" xml:space="preserve"><value>Track 3</value></data>
<data name="TrackDesc" xml:space="preserve"><value>Slider value (AviUtl compatible: track0–3)</value></data>
<data name="Check0" xml:space="preserve"><value>Check 0</value></data>
<data name="Check1" xml:space="preserve"><value>Check 1</value></data>
<data name="Check2" xml:space="preserve"><value>Check 2</value></data>
<data name="Check3" xml:space="preserve"><value>Check 3</value></data>
<data name="CheckDesc" xml:space="preserve"><value>Checkbox value (AviUtl compatible: check0–3)</value></data>
<data name="Color" xml:space="preserve"><value>Color</value></data>
<data name="ColorDesc" xml:space="preserve"><value>Color (AviUtl compatible: --color)</value></data>
<data name="ToolBarImport" xml:space="preserve"><value>Import</value></data>
<data name="ToolBarExport" xml:space="preserve"><value>Export</value></data>
<data name="ToolBarClear" xml:space="preserve"><value>Clear</value></data>
+7
ファイルの表示
@@ -69,6 +69,13 @@
<data name="Track2" xml:space="preserve"><value>Pista 2</value></data>
<data name="Track3" xml:space="preserve"><value>Pista 3</value></data>
<data name="TrackDesc" xml:space="preserve"><value>Valor del deslizador (compatible AviUtl: track0-3)</value></data>
<data name="Check0" xml:space="preserve"><value>Casilla 0</value></data>
<data name="Check1" xml:space="preserve"><value>Casilla 1</value></data>
<data name="Check2" xml:space="preserve"><value>Casilla 2</value></data>
<data name="Check3" xml:space="preserve"><value>Casilla 3</value></data>
<data name="CheckDesc" xml:space="preserve"><value>Valor de casilla (compatible AviUtl: check0-3)</value></data>
<data name="Color" xml:space="preserve"><value>Color</value></data>
<data name="ColorDesc" xml:space="preserve"><value>Color (compatible AviUtl: --color)</value></data>
<data name="ToolBarImport" xml:space="preserve"><value>Importar</value></data>
<data name="ToolBarExport" xml:space="preserve"><value>Exportar</value></data>
<data name="ToolBarClear" xml:space="preserve"><value>Limpiar</value></data>
+7
ファイルの表示
@@ -69,6 +69,13 @@
<data name="Track2" xml:space="preserve"><value>Jalur 2</value></data>
<data name="Track3" xml:space="preserve"><value>Jalur 3</value></data>
<data name="TrackDesc" xml:space="preserve"><value>Nilai slider (kompatibel AviUtl: track0-3)</value></data>
<data name="Check0" xml:space="preserve"><value>Centang 0</value></data>
<data name="Check1" xml:space="preserve"><value>Centang 1</value></data>
<data name="Check2" xml:space="preserve"><value>Centang 2</value></data>
<data name="Check3" xml:space="preserve"><value>Centang 3</value></data>
<data name="CheckDesc" xml:space="preserve"><value>Nilai kotak centang (kompatibel AviUtl: check0-3)</value></data>
<data name="Color" xml:space="preserve"><value>Warna</value></data>
<data name="ColorDesc" xml:space="preserve"><value>Warna (kompatibel AviUtl: --color)</value></data>
<data name="ToolBarImport" xml:space="preserve"><value>Impor</value></data>
<data name="ToolBarExport" xml:space="preserve"><value>Ekspor</value></data>
<data name="ToolBarClear" xml:space="preserve"><value>Hapus</value></data>
+7
ファイルの表示
@@ -69,6 +69,13 @@
<data name="Track2" xml:space="preserve"><value>트랙2</value></data>
<data name="Track3" xml:space="preserve"><value>트랙3</value></data>
<data name="TrackDesc" xml:space="preserve"><value>슬라이더 값 (AviUtl 호환: track0~3)</value></data>
<data name="Check0" xml:space="preserve"><value>체크0</value></data>
<data name="Check1" xml:space="preserve"><value>체크1</value></data>
<data name="Check2" xml:space="preserve"><value>체크2</value></data>
<data name="Check3" xml:space="preserve"><value>체크3</value></data>
<data name="CheckDesc" xml:space="preserve"><value>체크박스 값 (AviUtl 호환: check0~3)</value></data>
<data name="Color" xml:space="preserve"><value>색</value></data>
<data name="ColorDesc" xml:space="preserve"><value>색 (AviUtl 호환: --color)</value></data>
<data name="ToolBarImport" xml:space="preserve"><value>가져오기</value></data>
<data name="ToolBarExport" xml:space="preserve"><value>내보내기</value></data>
<data name="ToolBarClear" xml:space="preserve"><value>지우기</value></data>
+7
ファイルの表示
@@ -69,6 +69,13 @@
<data name="Track2" xml:space="preserve"><value>トラック2</value></data>
<data name="Track3" xml:space="preserve"><value>トラック3</value></data>
<data name="TrackDesc" xml:space="preserve"><value>スライダー値 (AviUtl準拠 track0〜3 に対応)</value></data>
<data name="Check0" xml:space="preserve"><value>チェック0</value></data>
<data name="Check1" xml:space="preserve"><value>チェック1</value></data>
<data name="Check2" xml:space="preserve"><value>チェック2</value></data>
<data name="Check3" xml:space="preserve"><value>チェック3</value></data>
<data name="CheckDesc" xml:space="preserve"><value>チェックボックス値 (AviUtl準拠 check0〜3 に対応)</value></data>
<data name="Color" xml:space="preserve"><value>色</value></data>
<data name="ColorDesc" xml:space="preserve"><value>色 (AviUtl準拠 --color に対応)</value></data>
<data name="ToolBarImport" xml:space="preserve"><value>インポート</value></data>
<data name="ToolBarExport" xml:space="preserve"><value>エクスポート</value></data>
<data name="ToolBarClear" xml:space="preserve"><value>クリア</value></data>
+7
ファイルの表示
@@ -69,6 +69,13 @@
<data name="Track2" xml:space="preserve"><value>轨道2</value></data>
<data name="Track3" xml:space="preserve"><value>轨道3</value></data>
<data name="TrackDesc" xml:space="preserve"><value>滑块值(AviUtl兼容: track0~3)</value></data>
<data name="Check0" xml:space="preserve"><value>复选框0</value></data>
<data name="Check1" xml:space="preserve"><value>复选框1</value></data>
<data name="Check2" xml:space="preserve"><value>复选框2</value></data>
<data name="Check3" xml:space="preserve"><value>复选框3</value></data>
<data name="CheckDesc" xml:space="preserve"><value>复选框值(AviUtl兼容: check0~3)</value></data>
<data name="Color" xml:space="preserve"><value>颜色</value></data>
<data name="ColorDesc" xml:space="preserve"><value>颜色(AviUtl兼容: --color)</value></data>
<data name="ToolBarImport" xml:space="preserve"><value>导入</value></data>
<data name="ToolBarExport" xml:space="preserve"><value>导出</value></data>
<data name="ToolBarClear" xml:space="preserve"><value>清除</value></data>
+7
ファイルの表示
@@ -69,6 +69,13 @@
<data name="Track2" xml:space="preserve"><value>軌道2</value></data>
<data name="Track3" xml:space="preserve"><value>軌道3</value></data>
<data name="TrackDesc" xml:space="preserve"><value>滑塊值(AviUtl兼容: track0~3)</value></data>
<data name="Check0" xml:space="preserve"><value>核取方塊0</value></data>
<data name="Check1" xml:space="preserve"><value>核取方塊1</value></data>
<data name="Check2" xml:space="preserve"><value>核取方塊2</value></data>
<data name="Check3" xml:space="preserve"><value>核取方塊3</value></data>
<data name="CheckDesc" xml:space="preserve"><value>核取方塊值(AviUtl兼容: check0~3)</value></data>
<data name="Color" xml:space="preserve"><value>顏色</value></data>
<data name="ColorDesc" xml:space="preserve"><value>顏色(AviUtl兼容: --color)</value></data>
<data name="ToolBarImport" xml:space="preserve"><value>導入</value></data>
<data name="ToolBarExport" xml:space="preserve"><value>導出</value></data>
<data name="ToolBarClear" xml:space="preserve"><value>清除</value></data>
+297
ファイルの表示
@@ -0,0 +1,297 @@
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Globalization;
using System.Reflection;
using System.Windows.Media;
using Vortice.Direct2D1;
using YukkuriMovieMaker.Commons;
using YukkuriMovieMaker.Player.Video;
using YukkuriMovieMaker.Plugin;
using YukkuriMovieMaker.Plugin.Effects;
namespace LuaScript
{
internal sealed class VideoEffectChain : IDisposable
{
private sealed class Node
{
public required Type Type;
public required IVideoEffect Model;
public required IVideoEffectProcessor Processor;
public required int RequestIndex;
}
private static Dictionary<string, Type>? _registry;
private static readonly Dictionary<Type, Dictionary<string, PropertyInfo>> _propertyCache = [];
private readonly IGraphicsDevicesAndContext _devices;
private readonly List<Node> _nodes = [];
private string[] _signature = [];
public VideoEffectChain(IGraphicsDevicesAndContext devices)
{
_devices = devices;
}
public ID2D1Image Apply(ID2D1Image source, IReadOnlyList<AviUtlEffectRequest> requests, EffectDescription baseDesc, ref DrawDescription drawDescription)
{
try
{
SyncNodes(requests);
}
catch
{
return source;
}
var current = source;
var desc = drawDescription;
foreach (var node in _nodes)
{
try
{
ApplyParameters(node.Model, requests[node.RequestIndex].Arguments);
node.Processor.SetInput(current);
var effectDescription = new EffectDescription(baseDesc, desc, baseDesc.InputIndex, baseDesc.InputCount, baseDesc.GroupIndex, baseDesc.GroupCount);
desc = node.Processor.Update(effectDescription);
current = node.Processor.Output;
}
catch
{
}
}
drawDescription = desc;
return current;
}
private void SyncNodes(IReadOnlyList<AviUtlEffectRequest> requests)
{
if (SignatureMatches(requests))
return;
DisposeNodes();
_signature = new string[requests.Count];
for (int i = 0; i < requests.Count; i++)
_signature[i] = requests[i].Name;
for (int i = 0; i < requests.Count; i++)
{
var type = Resolve(requests[i].Name);
if (type is null)
continue;
IVideoEffect? model = null;
try
{
model = Activator.CreateInstance(type) as IVideoEffect;
}
catch
{
}
if (model is null)
continue;
IVideoEffectProcessor processor;
try
{
processor = model.CreateVideoEffect(_devices);
}
catch
{
continue;
}
_nodes.Add(new Node { Type = type, Model = model, Processor = processor, RequestIndex = i });
}
}
private bool SignatureMatches(IReadOnlyList<AviUtlEffectRequest> requests)
{
if (_signature.Length != requests.Count)
return false;
for (int i = 0; i < requests.Count; i++)
{
if (!string.Equals(_signature[i], requests[i].Name, StringComparison.Ordinal))
return false;
}
return true;
}
private static Type? Resolve(string name)
{
var registry = GetRegistry();
return registry.TryGetValue(Normalize(name), out var type) ? type : null;
}
private static Dictionary<string, Type> GetRegistry()
{
if (_registry is not null)
return _registry;
var map = new Dictionary<string, Type>(StringComparer.Ordinal);
try
{
foreach (var factory in EffectFactories.VideoEffectFactories)
{
try
{
Register(map, factory.Name, factory.EffectType);
foreach (var keyword in factory.Keywords)
Register(map, keyword, factory.EffectType);
}
catch
{
}
}
_registry = map;
}
catch
{
}
return map;
}
private static void Register(Dictionary<string, Type> map, string? key, Type type)
{
if (string.IsNullOrWhiteSpace(key))
return;
map.TryAdd(Normalize(key), type);
}
private static string Normalize(string value) => value.Trim().ToLowerInvariant();
private static void ApplyParameters(IVideoEffect model, IReadOnlyList<KeyValuePair<string, object>> arguments)
{
if (arguments.Count == 0)
return;
var properties = GetProperties(model.GetType());
foreach (var (key, value) in arguments)
{
if (!properties.TryGetValue(Normalize(key), out var property))
continue;
try
{
SetValue(model, property, value);
}
catch
{
}
}
}
private static Dictionary<string, PropertyInfo> GetProperties(Type type)
{
if (_propertyCache.TryGetValue(type, out var cached))
return cached;
var map = new Dictionary<string, PropertyInfo>(StringComparer.Ordinal);
foreach (var property in type.GetProperties(BindingFlags.Public | BindingFlags.Instance))
{
if (property.GetIndexParameters().Length != 0)
continue;
bool usable = property.PropertyType == typeof(Animation) || property.GetSetMethod() is not null;
if (!usable)
continue;
map.TryAdd(Normalize(property.Name), property);
try
{
var display = property.GetCustomAttribute<DisplayAttribute>()?.GetName();
if (!string.IsNullOrWhiteSpace(display))
map.TryAdd(Normalize(display), property);
}
catch
{
}
}
_propertyCache[type] = map;
return map;
}
private static void SetValue(IVideoEffect model, PropertyInfo property, object value)
{
var type = property.PropertyType;
if (type == typeof(Animation))
{
if (property.GetValue(model) is Animation animation)
animation.CopyFrom(new Animation(ToDouble(value)));
return;
}
if (type == typeof(bool))
{
property.SetValue(model, ToBool(value));
return;
}
if (type.IsEnum)
{
property.SetValue(model, ToEnum(type, value));
return;
}
if (type == typeof(Color))
{
property.SetValue(model, ToColor(value));
return;
}
if (type == typeof(double) || type == typeof(float) || type == typeof(int) || type == typeof(long) || type == typeof(short))
{
property.SetValue(model, Convert.ChangeType(ToDouble(value), type, CultureInfo.InvariantCulture));
return;
}
if (type == typeof(string))
property.SetValue(model, value?.ToString());
}
private static double ToDouble(object value) => value switch
{
double d => d,
bool b => b ? 1d : 0d,
string s => double.TryParse(s, NumberStyles.Float, CultureInfo.InvariantCulture, out var r) ? r : 0d,
_ => 0d,
};
private static bool ToBool(object value) => value switch
{
bool b => b,
double d => d != 0d,
string s => s.Equals("true", StringComparison.OrdinalIgnoreCase) || s == "1",
_ => false,
};
private static object ToEnum(Type type, object value)
{
if (value is string s && Enum.TryParse(type, s, true, out var parsed))
return parsed;
return Enum.ToObject(type, (int)ToDouble(value));
}
private static Color ToColor(object value)
{
int rgb = (int)ToDouble(value);
return Color.FromRgb((byte)((rgb >> 16) & 0xFF), (byte)((rgb >> 8) & 0xFF), (byte)(rgb & 0xFF));
}
private void DisposeNodes()
{
foreach (var node in _nodes)
{
try
{
node.Processor.ClearInput();
}
catch
{
}
node.Processor.Dispose();
}
_nodes.Clear();
}
public void Dispose() => DisposeNodes();
}
}
+81 -4
ファイルの表示
@@ -301,6 +301,38 @@
لكن في هذا المكوِّن الإضافي تنعكس التغييرات عبر setpixel/set تلقائياً،
لذا لا داعي لاستدعاء هذه الدالة.
○ obj.rand(st, ed [, seed [, frame]])
تُعيد قيمة عشوائية صحيحة حتمية ضمن النطاق st ~ ed.
* مع نفس seed و frame، تُعيد دائماً القيمة نفسها.
* عند حذف seed يُعتبر 0، وعند حذف frame يُستخدم الإطار الحالي (obj.frame).
* تُعيد القيمة نفسها على محرك MoonSharp وعلى زمن التشغيل LuaJIT.
إذا لزمت قيمة عشوائية عشرية مستقلة عن المحرك، فاستخدم anim.rand.
st : الحد الأدنى للنطاق (يُقتطع إلى عدد صحيح)
ed : الحد الأعلى للنطاق (يُقتطع إلى عدد صحيح)
seed : بذرة العشوائية (اختياري، الافتراضي 0)
frame : الإطار المستخدم للتغيير (اختياري، الافتراضي obj.frame)
النتيجة : عدد صحيح ضمن st ~ ed
مثال: obj.ox = obj.ox + obj.rand(-10, 10, 1, obj.frame)
○ obj.load(الهدف، ...)
يستبدل مخزن الكائن بمحتوى مُولَّد. في هذا الإصدار يُدعم الهدف "figure" فقط.
obj.load("figure", name, color, size [, line [, aspect]])
يُولّد شكلاً ويستبدل مخزن الكائن به
(يُعاد تحجيم الخرج ليطابق الشكل ويُتوسَّط).
name : اسم الشكل. أحد 円 / 四角形 / 三角形 / 五角形 /
六角形 / 星形 (وتُقبل الأسماء الإنجليزية circle, rect,
triangle, pentagon, hexagon, star).
color : لون التعبئة 0xRRGGBB.
size : الحجم الأساسي بالبكسل.
line : عرض الحد (اختياري). الحذف أو 0 يملأ الشكل،
والقيمة المساوية للحجم أو الأكبر منه تملؤه أيضاً.
aspect : التشويه -1.0 ~ 1.0 (اختياري). الموجب يقلّص العرض،
والسالب يقلّص الارتفاع.
مثال: obj.load("figure", "円", 0xff3366, 200)
※ المُنفَّذ هو obj.load("figure", ...) فقط. الأهداف الأخرى
(ملفات الصور و"text" و"tempbuffer" و"movie" وغيرها) لا تفعل شيئاً.
※ تُنفَّذ نصوص الرسم على محرك MoonSharp.
- ymm4 Table -
@@ -441,10 +473,53 @@
obj.zoom = obj.zoom * (1 + obj.track0 / 100)
- التوافق الجزئي مع نصوص AviUtl -
تتيح طبقة توافق تشغيل الأجزاء الخاصة بالتحويل والشفافية والأرقام العشوائية من
نصوص تأثير الحركة في AviUtl (عائلة *.anm) دون إعادة كتابة. عندما لا يحتوي النص
على صياغة خاصة بـ AviUtl، لا تتدخل هذه الطبقة على الإطلاق (تبقى سلوكيات النصوص
الحالية كما هي تماماً).
○ توجيهات ترويسة النص
تُفسَّر إعلانات المعاملات المكتوبة على هيئة تعليقات، وتُعرَّف المتغيرات التي
يشير إليها جسم النص قبل التنفيذ.
--dialog:التسمية,local var=الافتراضي;...
يوسّع جزء الإعلان لكل عنصر (مثل local var=الافتراضي) إلى بداية الجسم.
في AviUtl تُحرَّر هذه القيم في مربع حوار، وهنا تُستخدم القيم الافتراضية.
--color:0xRRGGBB
يُعرّف المتغير color باللون المحدد.
--check0:التسمية,الافتراضي
يُعرّف obj.check0 (من 0 إلى 3) بالقيمة الافتراضية.
--param:<عبارة Lua>
يوسّع عبارة Lua المكتوبة إلى بداية الجسم.
--track0: إلى --track3:
تُقرأ قيم أشرطة التتبع عبر obj.track0 إلى obj.track3 كما في السابق.
لا تنعكس التسمية والنطاق والقيمة الافتراضية في الترويسة على الواجهة.
○ أقسام متعددة باستخدام @
عندما يُعرّف نص واحد عدة تأثيرات باستخدام @الاسم، يُنفَّذ القسم الأول فقط.
○ obj.rand(st, ed [, seed [, frame]])
دالة أرقام عشوائية صحيحة حتمية متوافقة مع AviUtl. انظر "جدول obj - الدوال"
للتفاصيل.
○ رسم الأشكال
obj.load("figure", ...) يُولّد دائرة أو مربعاً أو مثلثاً أو خماسياً أو
سداسياً أو نجمة، ويستبدل مخزن الكائن به. انظر "جدول obj - الدوال" للتفاصيل.
تتطلب الميزات التالية التكامل مع خط أنابيب الرسم، لذا فهي خارج نطاق هذه الطبقة.
النصوص التي تستدعيها لن تعمل كما هو متوقع.
× الرسم والتركيب (obj.draw / obj.drawpoly)، وأهداف obj.load غير "figure"
(ملفات الصور و"text" و"movie" وغيرها)، وكذلك obj.setfont
× تأثيرات المرشّحات وعمليات المخزن المؤقت
(obj.effect / obj.copybuffer / obj.setoption وما شابه)
× تحميل الوحدات عبر require، والوصول إلى الملفات مثل io
- الميزات غير المدعومة / القيود -
× obj.effect()، obj.draw()، obj.drawpoly()، obj.load() وما شابه من AviUtl2 غير مدعومة.
× obj.rand()، obj.rand1()، obj.setfont()، obj.mes() وما شابه من AviUtl2 غير مدعومة.
× obj.effect()، obj.draw()، obj.drawpoly() وما شابه من AviUtl2 غير مدعومة (يُدعم obj.load("figure", ...) فقط؛ انظر "التوافق الجزئي مع نصوص AviUtl").
× obj.rand1()، obj.setfont()، obj.mes() وما شابه من AviUtl2 غير مدعومة.
× obj.setoption()، obj.getoption()، obj.getvalue()، obj.setanchor() وما شابه من AviUtl2 غير مدعومة.
× الدوال مثل scene.set() و scene.get() في جدول scene الخاص بـ AviUtl2 غير مدعومة.
(يمكن قراءة scene.width و scene.height فقط)
@@ -453,5 +528,7 @@
لكن دعم الرسم ثلاثي الأبعاد محدود.
× إذا تجاوز النص البرمجي مهلة الانتهاء (5 ثوانٍ)، يُنهى التنفيذ قسراً.
يجب الانتباه في التطبيق لتجنب الحلقات اللانهائية.
× توجيهات الترويسة من AviUtl2 مثل --track@ و --check@ غير مدعومة.
يمكن استخدام Track0 ~ Track3 فقط كمعاملات.
× توجيهات الترويسة من AviUtl2 مدعومة جزئياً فقط. تُفسَّر القيم الافتراضية لـ
--dialog / --color / --check / --param (انظر "التوافق الجزئي مع نصوص AviUtl")،
لكن التسمية والنطاق والقيمة الافتراضية لـ --track@ لا تنعكس على الواجهة،
وتُستخدم القيم عبر Track0 ~ Track3.
+88 -4
ファイルの表示
@@ -307,6 +307,40 @@
but in this plugin changes via setpixel/set are automatically applied,
so calling this function is unnecessary.
o obj.rand(st, ed [, seed [, frame]])
Returns a deterministic integer random value within the range st ~ ed.
* With the same seed and frame, it always returns the same value.
* When seed is omitted it is treated as 0; when frame is omitted the
current frame (obj.frame) is used.
* Returns the same value on both the MoonSharp engine and the LuaJIT
runtime. For an engine-independent floating-point random value, use anim.rand.
st : Lower bound of the range (truncated to an integer)
ed : Upper bound of the range (truncated to an integer)
seed : Random seed (optional, default 0)
frame : Frame used for variation (optional, default obj.frame)
Returns : An integer within st ~ ed
Example: obj.ox = obj.ox + obj.rand(-10, 10, 1, obj.frame)
o obj.load(target, ...)
Replaces the object buffer with generated content.
Only the "figure" target is supported in this version.
obj.load("figure", name, color, size [, line [, aspect]])
Generates a shape and replaces the object buffer with it
(the output is resized to the shape and centered).
name : Shape name. One of 円 / 四角形 / 三角形 / 五角形 /
六角形 / 星形 (English aliases circle, rect,
triangle, pentagon, hexagon, star are also accepted).
color : Fill color 0xRRGGBB.
size : Bounding size in pixels.
line : Outline width (optional). Omitted or 0 fills the
shape; a value at or above the size also fills it.
aspect : Distortion -1.0 ~ 1.0 (optional). Positive shrinks
the width, negative shrinks the height.
Example: obj.load("figure", "円", 0xff3366, 200)
* Only obj.load("figure", ...) is implemented. Other targets
(image files, "text", "tempbuffer", "movie", etc.) do nothing.
* Drawing scripts run on the MoonSharp engine.
- ymm4 Table -
@@ -447,10 +481,58 @@
obj.zoom = obj.zoom * (1 + obj.track0 / 100)
- AviUtl Script Compatibility (Partial) -
A compatibility layer lets the transform, opacity and random portions of
AviUtl animation effect scripts (the *.anm family) run without rewriting.
When a script contains no AviUtl-specific notation, this layer does not
intervene at all, and existing scripts behave exactly as before.
o Script header directives
Parameter declarations written as comments are interpreted, and the
variables that the script body references are defined before execution.
--dialog:label,local var=default;...
Expands the declaration part of each item
(such as local var=default) to the top of the body.
In AviUtl these are edited in a dialog; here the default
values are used.
--color:0xRRGGBB
Defines the variable color with the specified color.
--check0:label,default
Defines obj.check0 (0 to 3) with the default value.
--param:<Lua statement>
Expands the written Lua statement to the top of the body.
--track0: to --track3:
Trackbar values are referenced via obj.track0 to obj.track3
as before. The label, range and default written in the header
are not reflected in the UI.
o Multiple sections with @
When a single script defines multiple effects with @name, only the
first section is executed.
o obj.rand(st, ed [, seed [, frame]])
A deterministic integer random function compatible with AviUtl.
See "obj Table - Functions" for details.
o Figure drawing
obj.load("figure", ...) generates a basic shape (circle, rectangle,
triangle, pentagon, hexagon, star) and replaces the object buffer
with it. See "obj Table - Functions" for details.
The following require integration with the rendering pipeline and are out of
scope for this layer. Scripts that call them will not behave as intended.
x Drawing and compositing (obj.draw / obj.drawpoly), obj.load targets
other than "figure" (image files, "text", "movie", etc.) and obj.setfont
x Filter effects and buffer operations
(obj.effect / obj.copybuffer / obj.setoption, etc.)
x Module loading via require, and file access such as io
- Unsupported Features / Limitations -
x obj.effect(), obj.draw(), obj.drawpoly(), obj.load(), etc. from AviUtl2 are not supported.
x obj.rand(), obj.rand1(), obj.setfont(), obj.mes(), etc. from AviUtl2 are not supported.
x obj.effect(), obj.draw(), obj.drawpoly(), etc. from AviUtl2 are not supported (only obj.load("figure", ...) is supported; see "AviUtl Script Compatibility (Partial)").
x obj.rand1(), obj.setfont(), obj.mes(), etc. from AviUtl2 are not supported.
x obj.setoption(), obj.getoption(), obj.getvalue(), obj.setanchor(), etc. from AviUtl2 are not supported.
x Functions such as scene.set() and scene.get() in the AviUtl2 scene table are not supported.
(Only scene.width and scene.height can be read)
@@ -459,5 +541,7 @@
but 3D rendering support is limited.
x If the script timeout (5 seconds) is exceeded, execution is forcibly terminated.
Care must be taken in implementation to prevent infinite loops.
x AviUtl2 header directives such as --track@ and --check@ are not supported.
Only Track0 ~ Track3 can be used as parameters.
x AviUtl2 header directives are only partially supported. The default values of
--dialog / --color / --check / --param are interpreted (see "AviUtl Script
Compatibility (Partial)"), but the label, range and default of --track@ are
not reflected in the UI; values are used via Track0 ~ Track3.
+91 -4
ファイルの表示
@@ -305,6 +305,40 @@
pero en este plugin los cambios mediante setpixel/set se aplican automáticamente,
por lo que no es necesario llamar a esta función.
o obj.rand(st, ed [, seed [, frame]])
Devuelve un valor aleatorio entero determinista dentro del rango st ~ ed.
* Con el mismo seed y frame, siempre devuelve el mismo valor.
* Si se omite seed se trata como 0; si se omite frame se usa el
fotograma actual (obj.frame).
* Devuelve el mismo valor en el motor MoonSharp y en el runtime LuaJIT.
Para un valor aleatorio decimal independiente del motor, use anim.rand.
st : Límite inferior del rango (truncado a entero)
ed : Límite superior del rango (truncado a entero)
seed : Semilla aleatoria (opcional, predeterminado 0)
frame : Fotograma usado para la variación (opcional, predeterminado obj.frame)
Devuelve: Un entero dentro de st ~ ed
Ejemplo: obj.ox = obj.ox + obj.rand(-10, 10, 1, obj.frame)
o obj.load(target, ...)
Reemplaza el búfer del objeto con contenido generado.
En esta versión solo se admite el target "figure".
obj.load("figure", name, color, size [, line [, aspect]])
Genera una forma y reemplaza el búfer del objeto con ella
(la salida se redimensiona a la forma y se centra).
name : Nombre de la forma. Uno de 円 / 四角形 / 三角形 /
五角形 / 六角形 / 星形 (también se aceptan los alias
en inglés circle, rect, triangle, pentagon, hexagon, star).
color : Color de relleno 0xRRGGBB.
size : Tamaño base en píxeles.
line : Grosor del contorno (opcional). Omitido o 0 rellena la
forma; un valor igual o mayor que el tamaño también la rellena.
aspect : Distorsión -1.0 ~ 1.0 (opcional). Positivo reduce el
ancho, negativo reduce el alto.
Ejemplo: obj.load("figure", "円", 0xff3366, 200)
* Solo se implementa obj.load("figure", ...). Otros targets
(archivos de imagen, "text", "tempbuffer", "movie", etc.) no hacen nada.
* Los scripts de dibujo se ejecutan en el motor MoonSharp.
- ymm4 Table -
@@ -445,10 +479,61 @@
obj.zoom = obj.zoom * (1 + obj.track0 / 100)
- Compatibilidad parcial con scripts de AviUtl -
Una capa de compatibilidad permite ejecutar, sin reescritura, las partes de
los scripts de efecto de animación de AviUtl (la familia *.anm) relativas a
transformación, opacidad y números aleatorios. Cuando un script no contiene
notación específica de AviUtl, esta capa no interviene en absoluto (los
scripts existentes se comportan exactamente igual que antes).
o Directivas de encabezado del script
Las declaraciones de parámetros escritas como comentarios se
interpretan, y las variables que el cuerpo del script referencia se
definen antes de la ejecución.
--dialog:etiqueta,local var=predeterminado;...
Expande la parte de declaración de cada elemento
(como local var=predeterminado) al inicio del cuerpo.
En AviUtl se editan en un cuadro de diálogo; aquí se usan
los valores predeterminados.
--color:0xRRGGBB
Define la variable color con el color especificado.
--check0:etiqueta,predeterminado
Define obj.check0 (0 a 3) con el valor predeterminado.
--param:<sentencia Lua>
Expande la sentencia Lua escrita al inicio del cuerpo.
--track0: a --track3:
Los valores de las barras de seguimiento se referencian
mediante obj.track0 a obj.track3 como antes. La etiqueta, el
rango y el valor predeterminado del encabezado no se reflejan en la UI.
o Múltiples secciones con @
Cuando un único script define varios efectos con @nombre, solo se
ejecuta la primera sección.
o obj.rand(st, ed [, seed [, frame]])
Función de número aleatorio entero determinista compatible con AviUtl.
Consulte "Tabla obj - Funciones" para más detalles.
o Dibujo de figuras
obj.load("figure", ...) genera una forma básica (círculo, rectángulo,
triángulo, pentágono, hexágono, estrella) y reemplaza el búfer del
objeto con ella. Consulte "Tabla obj - Funciones" para más detalles.
Lo siguiente requiere integración con la canalización de renderizado y, por
tanto, queda fuera del alcance de esta capa. Los scripts que lo llamen no se
comportarán como se espera.
x Dibujo y composición (obj.draw / obj.drawpoly), targets de obj.load
distintos de "figure" (archivos de imagen, "text", "movie", etc.) y obj.setfont
x Efectos de filtro y operaciones de búfer
(obj.effect / obj.copybuffer / obj.setoption, etc.)
x Carga de módulos mediante require y acceso a archivos como io
- Funciones no admitidas / Limitaciones -
x obj.effect(), obj.draw(), obj.drawpoly(), obj.load(), etc. de AviUtl2 no son compatibles.
x obj.rand(), obj.rand1(), obj.setfont(), obj.mes(), etc. de AviUtl2 no son compatibles.
x obj.effect(), obj.draw(), obj.drawpoly(), etc. de AviUtl2 no son compatibles (solo se admite obj.load("figure", ...); consulte "Compatibilidad parcial con scripts de AviUtl").
x obj.rand1(), obj.setfont(), obj.mes(), etc. de AviUtl2 no son compatibles.
x obj.setoption(), obj.getoption(), obj.getvalue(), obj.setanchor(), etc. de AviUtl2 no son compatibles.
x Las funciones como scene.set() y scene.get() de la tabla scene de AviUtl2 no son compatibles.
(Solo se pueden leer scene.width y scene.height)
@@ -457,5 +542,7 @@
pero el soporte de renderizado 3D es limitado.
x Si se supera el tiempo de espera del script (5 segundos), la ejecución se termina forzosamente.
Se debe tener cuidado en la implementación para evitar bucles infinitos.
x Las directivas de encabezado de AviUtl2 como --track@ y --check@ no son compatibles.
Solo Track0 ~ Track3 pueden usarse como parámetros.
x Las directivas de encabezado de AviUtl2 solo son compatibles parcialmente. Los valores
predeterminados de --dialog / --color / --check / --param se interpretan (consulte
"Compatibilidad parcial con scripts de AviUtl"), pero la etiqueta, el rango y el valor
predeterminado de --track@ no se reflejan en la UI; los valores se usan vía Track0 ~ Track3.
+90 -4
ファイルの表示
@@ -303,6 +303,40 @@
tetapi dalam plugin ini perubahan melalui setpixel/set diterapkan secara otomatis,
sehingga tidak perlu memanggil fungsi ini.
o obj.rand(st, ed [, seed [, frame]])
Mengembalikan nilai acak bilangan bulat deterministik dalam rentang st ~ ed.
* Dengan seed dan frame yang sama, selalu mengembalikan nilai yang sama.
* Jika seed dihilangkan dianggap 0; jika frame dihilangkan digunakan
frame saat ini (obj.frame).
* Mengembalikan nilai yang sama pada mesin MoonSharp maupun runtime LuaJIT.
Untuk nilai acak desimal yang independen dari mesin, gunakan anim.rand.
st : Batas bawah rentang (dipotong menjadi bilangan bulat)
ed : Batas atas rentang (dipotong menjadi bilangan bulat)
seed : Seed acak (opsional, default 0)
frame : Frame yang digunakan untuk variasi (opsional, default obj.frame)
Hasil : Bilangan bulat dalam st ~ ed
Contoh: obj.ox = obj.ox + obj.rand(-10, 10, 1, obj.frame)
o obj.load(target, ...)
Mengganti buffer objek dengan konten yang dihasilkan.
Pada versi ini hanya target "figure" yang didukung.
obj.load("figure", name, color, size [, line [, aspect]])
Menghasilkan sebuah bentuk dan mengganti buffer objek dengannya
(output diubah ukurannya sesuai bentuk dan dipusatkan).
name : Nama bentuk. Salah satu dari 円 / 四角形 / 三角形 /
五角形 / 六角形 / 星形 (alias Inggris circle, rect,
triangle, pentagon, hexagon, star juga diterima).
color : Warna isi 0xRRGGBB.
size : Ukuran dasar dalam piksel.
line : Lebar garis tepi (opsional). Dihilangkan atau 0 mengisi
bentuk; nilai sama atau lebih besar dari ukuran juga mengisinya.
aspect : Distorsi -1.0 ~ 1.0 (opsional). Positif mengecilkan
lebar, negatif mengecilkan tinggi.
Contoh: obj.load("figure", "円", 0xff3366, 200)
* Hanya obj.load("figure", ...) yang diimplementasikan. Target lain
(berkas gambar, "text", "tempbuffer", "movie", dll.) tidak melakukan apa pun.
* Skrip penggambaran dijalankan pada mesin MoonSharp.
- ymm4 Table -
@@ -443,10 +477,60 @@
obj.zoom = obj.zoom * (1 + obj.track0 / 100)
- Kompatibilitas Parsial Skrip AviUtl -
Lapisan kompatibilitas memungkinkan bagian transformasi, opasitas, dan
bilangan acak dari skrip efek animasi AviUtl (keluarga *.anm) dijalankan
tanpa penulisan ulang. Ketika sebuah skrip tidak mengandung notasi khusus
AviUtl, lapisan ini tidak ikut campur sama sekali (skrip yang ada berperilaku
persis seperti sebelumnya).
o Direktif header skrip
Deklarasi parameter yang ditulis sebagai komentar diinterpretasikan,
dan variabel yang dirujuk oleh badan skrip didefinisikan sebelum eksekusi.
--dialog:label,local var=default;...
Memperluas bagian deklarasi setiap item
(seperti local var=default) ke awal badan skrip.
Di AviUtl nilai ini diedit dalam dialog; di sini digunakan
nilai default.
--color:0xRRGGBB
Mendefinisikan variabel color dengan warna yang ditentukan.
--check0:label,default
Mendefinisikan obj.check0 (0 sampai 3) dengan nilai default.
--param:<pernyataan Lua>
Memperluas pernyataan Lua yang ditulis ke awal badan skrip.
--track0: sampai --track3:
Nilai trackbar dirujuk melalui obj.track0 sampai obj.track3
seperti sebelumnya. Label, rentang, dan default pada header
tidak tercermin di UI.
o Beberapa bagian dengan @
Ketika satu skrip mendefinisikan beberapa efek dengan @nama, hanya
bagian pertama yang dijalankan.
o obj.rand(st, ed [, seed [, frame]])
Fungsi bilangan acak bulat deterministik yang kompatibel dengan AviUtl.
Lihat "Tabel obj - Fungsi" untuk detailnya.
o Penggambaran figur
obj.load("figure", ...) menghasilkan bentuk dasar (lingkaran, persegi,
segitiga, segilima, segienam, bintang) dan mengganti buffer objek
dengannya. Lihat "Tabel obj - Fungsi" untuk detailnya.
Berikut ini memerlukan integrasi dengan pipeline render sehingga berada di
luar cakupan lapisan ini. Skrip yang memanggilnya tidak akan berperilaku
seperti yang diharapkan.
x Penggambaran dan komposisi (obj.draw / obj.drawpoly), target obj.load
selain "figure" (berkas gambar, "text", "movie", dll.) dan obj.setfont
x Efek filter dan operasi buffer
(obj.effect / obj.copybuffer / obj.setoption, dll.)
x Pemuatan modul melalui require, dan akses file seperti io
- Fitur yang Tidak Didukung / Batasan -
x obj.effect(), obj.draw(), obj.drawpoly(), obj.load(), dll. dari AviUtl2 tidak didukung.
x obj.rand(), obj.rand1(), obj.setfont(), obj.mes(), dll. dari AviUtl2 tidak didukung.
x obj.effect(), obj.draw(), obj.drawpoly(), dll. dari AviUtl2 tidak didukung (hanya obj.load("figure", ...) yang didukung; lihat "Kompatibilitas Parsial Skrip AviUtl").
x obj.rand1(), obj.setfont(), obj.mes(), dll. dari AviUtl2 tidak didukung.
x obj.setoption(), obj.getoption(), obj.getvalue(), obj.setanchor(), dll. dari AviUtl2 tidak didukung.
x Fungsi seperti scene.set() dan scene.get() dalam tabel scene AviUtl2 tidak didukung.
(Hanya scene.width dan scene.height yang dapat dibaca)
@@ -455,5 +539,7 @@
tetapi dukungan render 3D terbatas.
x Jika batas waktu skrip (5 detik) terlampaui, eksekusi dihentikan paksa.
Perhatian harus diberikan dalam implementasi untuk mencegah loop tak terbatas.
x Direktif header AviUtl2 seperti --track@ dan --check@ tidak didukung.
Hanya Track0 ~ Track3 yang dapat digunakan sebagai parameter.
x Direktif header AviUtl2 hanya didukung sebagian. Nilai default dari
--dialog / --color / --check / --param diinterpretasikan (lihat "Kompatibilitas
Parsial Skrip AviUtl"), tetapi label, rentang, dan default dari --track@ tidak
tercermin di UI; nilai digunakan melalui Track0 ~ Track3.
+84 -4
ファイルの表示
@@ -303,6 +303,38 @@
このプラグインでは setpixel/set による変更が自動的に反映されるため、
本関数を呼び出す必要はありません。
○obj.rand(st, ed [, seed [, frame]])
指定範囲 st ~ ed の整数を返す決定論的な乱数です。
※ seed と frame が同じであれば常に同じ値を返します。
※ seed 省略時は 0、frame 省略時は現在のフレーム(obj.frame)を使用します。
※ 従来エンジン(MoonSharp)と高速ランタイム(LuaJIT)で同じ値を返します。
エンジンに依存しない小数の乱数が必要な場合は anim.rand を使用してください。
st : 範囲の下限 (小数は切り捨てて整数化)
ed : 範囲の上限 (小数は切り捨てて整数化)
seed : 乱数シード (省略可, デフォルト 0)
frame : 変化に用いるフレーム (省略可, デフォルト obj.frame)
戻り値 : st ~ ed の整数
例:obj.ox = obj.ox + obj.rand(-10, 10, 1, obj.frame)
○obj.load(対象, ...)
オブジェクトのバッファを生成した内容に置き換えます。
本バージョンでは "figure"(図形)のみ対応します。
obj.load("figure", 名前, 色, サイズ [, ライン [, アスペクト]])
図形を生成してオブジェクトのバッファを置き換えます
(出力は図形サイズに合わせて生成され、中心に配置されます)。
名前 : 図形名。円 / 四角形 / 三角形 / 五角形 / 六角形 /
星形 のいずれか(英語名 circle, rect, triangle,
pentagon, hexagon, star も使用可)。
色 : 塗り色 0xRRGGBB。
サイズ : 図形の基準サイズ(ピクセル)。
ライン : 輪郭の太さ(省略可)。省略または 0 で塗りつぶし。
サイズ以上の値を指定した場合も塗りつぶしになります。
アスペクト: 歪曲 -1.0 ~ 1.0(省略可)。正で横幅、負で縦幅が縮みます。
例:obj.load("figure", "円", 0xff3366, 200)
※ 実装されているのは obj.load("figure", ...) のみです。画像ファイルや
"text"・"tempbuffer"・"movie" 等の対象は何も行いません。
※ 描画系スクリプトは従来エンジン(MoonSharp)で実行されます。
- ymm4 テーブル -
@@ -443,10 +475,56 @@
obj.zoom = obj.zoom * (1 + obj.track0 / 100)
- AviUtl スクリプトの部分互換 -
AviUtl のアニメーション効果スクリプト(*.anm 系)のうち、座標・拡縮・回転・
不透明度の変形と乱数を用いる範囲を、追加の記述変更なしで実行できる互換層です。
スクリプトに AviUtl 固有の記法が含まれない場合、この互換層は一切介入しません
(従来のスクリプトの挙動は変わりません)。
○スクリプトヘッダの解釈
コメント形式のパラメータ宣言を解釈し、スクリプト本体が参照する変数を
実行前に定義します。
--dialog:項目名,local 変数=既定値;…
各項目の宣言部(local 変数=既定値 など)を本体の先頭へ展開します。
AviUtl では対話ダイアログで編集する値ですが、ここでは既定値で
動作します。
--color:0xRRGGBB
変数 color を指定色で定義します。
--check0:項目名,既定値
obj.check0 (0~3) を既定値で定義します。
--param:任意のLua文
記述した Lua 文をそのまま本体の先頭へ展開します。
--track0: ~ --track3:
トラックバーの値は従来どおり obj.track0 ~ obj.track3 から
参照します。ヘッダーのラベル・範囲・既定値は UI へ反映しません。
○@ による複数セクション
1 つのスクリプトに @名前 で複数の効果が定義されている場合、先頭の
セクションのみを実行します。
○obj.rand(st, ed [, seed [, frame]])
AviUtl 互換の決定論的な整数乱数です。詳細は「obj テーブル - 関数」を
参照してください。
○図形描画
obj.load("figure", ...) で円・四角形・三角形・五角形・六角形・星形を
生成し、オブジェクトのバッファを置き換えます。詳細は「obj テーブル -
関数」を参照してください。
次の機能は本体の描画パイプラインへの統合を要するため、この互換層では対象外です。
これらを呼び出すスクリプトは意図どおりには動作しません。
×描画・合成(obj.draw / obj.drawpoly)、obj.load の "figure" 以外の対象
(画像ファイル・"text"・"movie" 等)、および obj.setfont
×フィルタ効果やバッファ操作
(obj.effect / obj.copybuffer / obj.setoption など)
×require によるモジュール読み込み、io などのファイルアクセス
- 非対応・制限事項 -
×AviUtl2 の obj.effect(), obj.draw(), obj.drawpoly(), obj.load() 等には対応していません。
×AviUtl2 の obj.rand(), obj.rand1(), obj.setfont(), obj.mes() 等には対応していません。
×AviUtl2 の obj.effect(), obj.draw(), obj.drawpoly() 等には対応していません(obj.load は "figure" のみ対応。「AviUtl スクリプトの部分互換」を参照)。
×AviUtl2 の obj.rand1(), obj.setfont(), obj.mes() 等には対応していません。
×AviUtl2 の obj.setoption(), obj.getoption(), obj.getvalue(), obj.setanchor() 等には対応していません。
×AviUtl2 の scene テーブルの scene.set(), scene.get() 等の関数には対応していません。
(scene.width と scene.height の読み取りのみ対応)
@@ -455,5 +533,7 @@
3D 描画のサポートは限定的です。
×スクリプトのタイムアウト(5秒)を超えた場合、実行は強制終了されます。
無限ループが発生しないよう実装上の注意が必要です。
×AviUtl2 の --track@, --check@ 等のヘッダーディレクティブには対応していません。
パラメータは Track0 ~ Track3 のみ使用できます。
×AviUtl2 のヘッダーディレクティブは部分的にのみ対応します。
--dialog / --color / --check / --param の既定値は解釈されますが
(「AviUtl スクリプトの部分互換」を参照)、--track@ のラベル・範囲・
既定値は UI へ反映されず、値は Track0 ~ Track3 を使用します。
+83 -4
ファイルの表示
@@ -299,6 +299,38 @@
이 플러그인에서는 setpixel/set에 의한 변경이 자동으로 반영되므로,
이 함수를 호출할 필요가 없습니다.
○ obj.rand(st, ed [, seed [, frame]])
지정 범위 st ~ ed의 정수를 반환하는 결정론적 난수입니다.
※ seed와 frame이 같으면 항상 같은 값을 반환합니다.
※ seed 생략 시 0으로, frame 생략 시 현재 프레임(obj.frame)을 사용합니다.
※ 기존 엔진(MoonSharp)과 고속 런타임(LuaJIT)에서 같은 값을 반환합니다.
엔진에 의존하지 않는 소수 난수가 필요하면 anim.rand를 사용하세요.
st : 범위 하한 (소수는 버림하여 정수화)
ed : 범위 상한 (소수는 버림하여 정수화)
seed : 난수 시드 (생략 가능, 기본값 0)
frame : 변화에 사용하는 프레임 (생략 가능, 기본값 obj.frame)
반환값 : st ~ ed의 정수
예: obj.ox = obj.ox + obj.rand(-10, 10, 1, obj.frame)
○ obj.load(대상, ...)
오브젝트 버퍼를 생성한 내용으로 교체합니다.
이 버전에서는 "figure"(도형)만 지원합니다.
obj.load("figure", 이름, 색, 크기 [, 라인 [, 종횡비]])
도형을 생성하여 오브젝트 버퍼를 교체합니다
(출력은 도형 크기에 맞춰 생성되고 중심에 배치됩니다).
이름 : 도형 이름. 円 / 四角形 / 三角形 / 五角形 / 六角形 /
星形 중 하나(영어 circle, rect, triangle,
pentagon, hexagon, star 도 사용 가능).
색 : 채움 색 0xRRGGBB.
크기 : 도형의 기준 크기(픽셀).
라인 : 외곽선 두께(생략 가능). 생략 또는 0이면 채움.
크기 이상의 값을 지정한 경우에도 채움이 됩니다.
종횡비 : 왜곡 -1.0 ~ 1.0(생략 가능). 양수는 너비, 음수는 높이를 줄입니다.
예: obj.load("figure", "円", 0xff3366, 200)
※ 구현된 것은 obj.load("figure", ...) 뿐입니다. 이미지 파일,
"text"・"tempbuffer"・"movie" 등의 대상은 아무것도 하지 않습니다.
※ 그리기 계열 스크립트는 MoonSharp 엔진에서 실행됩니다.
- ymm4 테이블 -
@@ -439,10 +471,56 @@
obj.zoom = obj.zoom * (1 + obj.track0 / 100)
- AviUtl 스크립트 부분 호환 -
AviUtl 애니메이션 효과 스크립트(*.anm 계열) 중 좌표·확대축소·회전·
불투명도의 변형과 난수를 사용하는 범위를, 추가 수정 없이 실행할 수 있는
호환 계층입니다. 스크립트에 AviUtl 고유 표기가 포함되지 않은 경우 이
호환 계층은 전혀 개입하지 않습니다(기존 스크립트의 동작은 변하지 않습니다).
○ 스크립트 헤더 디렉티브 해석
주석 형식의 파라미터 선언을 해석하여, 스크립트 본문이 참조하는
변수를 실행 전에 정의합니다.
--dialog:항목명,local 변수=기본값;…
각 항목의 선언부(local 변수=기본값 등)를 본문 앞에 펼칩니다.
AviUtl에서는 대화 상자에서 편집하는 값이지만, 여기서는
기본값으로 동작합니다.
--color:0xRRGGBB
변수 color를 지정한 색으로 정의합니다.
--check0:항목명,기본값
obj.check0 (0~3)을 기본값으로 정의합니다.
--param:임의의 Lua 문
작성한 Lua 문을 그대로 본문 앞에 펼칩니다.
--track0: ~ --track3:
트랙바 값은 기존과 같이 obj.track0 ~ obj.track3에서
참조합니다. 헤더의 라벨·범위·기본값은 UI에 반영되지 않습니다.
○ @를 통한 복수 섹션
하나의 스크립트에 @이름으로 여러 효과가 정의된 경우, 첫 번째
섹션만 실행합니다.
○ obj.rand(st, ed [, seed [, frame]])
AviUtl 호환의 결정론적 정수 난수입니다. 자세한 내용은
"obj 테이블 - 함수"를 참조하세요.
○ 도형 그리기
obj.load("figure", ...) 로 원·사각형·삼각형·오각형·육각형·별형을
생성하여 오브젝트 버퍼를 교체합니다. 자세한 내용은
"obj 테이블 - 함수"를 참조하세요.
다음 기능은 본체의 렌더링 파이프라인과의 통합이 필요하므로 이 호환
계층의 범위 밖입니다. 이를 호출하는 스크립트는 의도대로 동작하지 않습니다.
× 그리기·합성(obj.draw / obj.drawpoly), obj.load의 "figure" 이외 대상
(이미지 파일·"text"・"movie" 등), 그리고 obj.setfont
× 필터 효과 및 버퍼 조작
(obj.effect / obj.copybuffer / obj.setoption 등)
× require에 의한 모듈 로드 및 io 등의 파일 접근
- 미지원·제한 사항 -
× AviUtl2의 obj.effect(), obj.draw(), obj.drawpoly(), obj.load() 등은 지원하지 않습니다.
× AviUtl2의 obj.rand(), obj.rand1(), obj.setfont(), obj.mes() 등은 지원하지 않습니다.
× AviUtl2의 obj.effect(), obj.draw(), obj.drawpoly() 등은 지원하지 않습니다(obj.load은 "figure"만 지원. "AviUtl 스크립트 부분 호환" 참조).
× AviUtl2의 obj.rand1(), obj.setfont(), obj.mes() 등은 지원하지 않습니다.
× AviUtl2의 obj.setoption(), obj.getoption(), obj.getvalue(), obj.setanchor() 등은 지원하지 않습니다.
× AviUtl2의 scene 테이블의 scene.set(), scene.get() 등의 함수는 지원하지 않습니다.
(scene.width와 scene.height의 읽기만 지원)
@@ -451,5 +529,6 @@
3D 렌더링 지원은 제한적입니다.
× 스크립트 타임아웃(5초)을 초과하면 실행이 강제 종료됩니다.
무한 루프가 발생하지 않도록 구현 시 주의가 필요합니다.
× AviUtl2의 --track@, --check@ 등의 헤더 디렉티브는 지원하지 않습니다.
파라미터는 Track0 ~ Track3만 사용할 수 있습니다.
× AviUtl2의 헤더 디렉티브는 부분적으로만 지원합니다. --dialog / --color /
--check / --param의 기본값은 해석되지만("AviUtl 스크립트 부분 호환" 참조),
--track@의 라벨·범위·기본값은 UI에 반영되지 않으며 값은 Track0 ~ Track3을 사용합니다.
+76 -4
ファイルの表示
@@ -297,6 +297,37 @@
但本插件中 setpixel/set 的修改会自动反映,
因此无需调用此函数。
○ obj.rand(st, ed [, seed [, frame]])
返回指定范围 st ~ ed 内整数的确定性随机数。
* seed 与 frame 相同时始终返回相同的值。
* 省略 seed 时按 0 处理,省略 frame 时使用当前帧 (obj.frame)。
* 在传统引擎 (MoonSharp) 与高速运行时 (LuaJIT) 上返回相同的值。
若需要不依赖引擎的小数随机数,请使用 anim.rand。
st : 范围下限(小数向下取整为整数)
ed : 范围上限(小数向下取整为整数)
seed : 随机种子(可省略,默认 0)
frame : 用于变化的帧(可省略,默认 obj.frame)
返回值 : st ~ ed 的整数
示例:obj.ox = obj.ox + obj.rand(-10, 10, 1, obj.frame)
○ obj.load(目标, ...)
将对象缓冲区替换为生成的内容。本版本仅支持 "figure"(图形)。
obj.load("figure", 名称, 颜色, 大小 [, 线宽 [, 纵横比]])
生成图形并替换对象缓冲区
(输出按图形大小生成并居中)。
名称 : 图形名。円 / 四角形 / 三角形 / 五角形 / 六角形 /
星形 之一(也可用英文 circle, rect, triangle,
pentagon, hexagon, star)。
颜色 : 填充色 0xRRGGBB。
大小 : 图形基准大小(像素)。
线宽 : 轮廓宽度(可省略)。省略或 0 为填充;
指定大于等于大小的值时也为填充。
纵横比 : 变形 -1.0 ~ 1.0(可省略)。正值缩小宽度,负值缩小高度。
示例:obj.load("figure", "円", 0xff3366, 200)
* 仅实现了 obj.load("figure", ...)。图像文件、"text"、"tempbuffer"、
"movie" 等目标不执行任何操作。
* 绘制类脚本在 MoonSharp 引擎上运行。
- ymm4 表 -
@@ -437,10 +468,50 @@
obj.zoom = obj.zoom * (1 + obj.track0 / 100)
- AviUtl 脚本的部分兼容 -
提供兼容层,使 AviUtl 动画效果脚本(*.anm 系列)中涉及坐标、缩放、旋转、
不透明度的变形以及随机数的部分,无需额外修改即可运行。当脚本中不包含
AviUtl 专有写法时,此兼容层完全不介入(传统脚本的行为不变)。
○ 脚本头部指令的解释
解释注释形式的参数声明,在执行前定义脚本主体所引用的变量。
--dialog:项目名,local 变量=默认值;…
将各项目的声明部分(如 local 变量=默认值)展开到主体开头。
在 AviUtl 中这些是通过对话框编辑的值,此处以默认值运行。
--color:0xRRGGBB
以指定颜色定义变量 color。
--check0:项目名,默认值
以默认值定义 obj.check0 (0~3)。
--param:任意 Lua 语句
将所写的 Lua 语句原样展开到主体开头。
--track0: ~ --track3:
轨道条的值仍通过 obj.track0 ~ obj.track3 引用。头部的标签、
范围与默认值不会反映到 UI。
○ 通过 @ 的多区段
当一个脚本以 @名称 定义了多个效果时,仅执行第一个区段。
○ obj.rand(st, ed [, seed [, frame]])
与 AviUtl 兼容的确定性整数随机数。详情请参阅“obj 表 - 函数”。
○ 图形绘制
obj.load("figure", ...) 生成圆、四角形、三角形、五角形、六角形、星形,
并替换对象缓冲区。详情请参阅“obj 表 - 函数”。
以下功能需要与本体的绘制管线集成,因此不在此兼容层的范围内。
调用它们的脚本不会按预期运行。
× 绘制与合成(obj.draw / obj.drawpoly)、obj.load 的 "figure" 以外目标
(图像文件、"text"、"movie" 等),以及 obj.setfont
× 滤镜效果与缓冲区操作
(obj.effect / obj.copybuffer / obj.setoption 等)
× 通过 require 加载模块,以及 io 等文件访问
- 不支持项目·限制事项 -
× 不支持 AviUtl2 的 obj.effect()、obj.draw()、obj.drawpoly()、obj.load() 等。
× 不支持 AviUtl2 的 obj.rand()、obj.rand1()、obj.setfont()、obj.mes() 等。
× 不支持 AviUtl2 的 obj.effect()、obj.draw()、obj.drawpoly() 等(obj.load 仅支持 "figure",参阅“AviUtl 脚本的部分兼容”)。
× 不支持 AviUtl2 的 obj.rand1()、obj.setfont()、obj.mes() 等。
× 不支持 AviUtl2 的 obj.setoption()、obj.getoption()、obj.getvalue()、obj.setanchor() 等。
× 不支持 AviUtl2 scene 表中的 scene.set()、scene.get() 等函数。
(仅支持读取 scene.width 和 scene.height)
@@ -449,5 +520,6 @@
但 3D 绘制支持有限。
× 超过脚本超时时间(5 秒)时,执行将被强制终止。
实现时需注意避免出现无限循环。
× 不支持 AviUtl2 的 --track@、--check@ 等头部指令。
参数仅可使用 Track0 ~ Track3。
× AviUtl2 的头部指令仅部分支持。--dialog / --color / --check / --param 的
默认值会被解释(参阅“AviUtl 脚本的部分兼容”),但 --track@ 的标签、范围
与默认值不会反映到 UI,值通过 Track0 ~ Track3 使用。
+76 -4
ファイルの表示
@@ -297,6 +297,37 @@
但本外掛中 setpixel/set 的修改會自動反映,
因此無需呼叫此函式。
○ obj.rand(st, ed [, seed [, frame]])
回傳指定範圍 st ~ ed 內整數的確定性亂數。
* seed 與 frame 相同時始終回傳相同的值。
* 省略 seed 時以 0 處理,省略 frame 時使用目前影格 (obj.frame)。
* 在傳統引擎 (MoonSharp) 與高速執行階段 (LuaJIT) 上回傳相同的值。
若需要不依賴引擎的小數亂數,請使用 anim.rand。
st : 範圍下限(小數無條件捨去為整數)
ed : 範圍上限(小數無條件捨去為整數)
seed : 亂數種子(可省略,預設 0)
frame : 用於變化的影格(可省略,預設 obj.frame)
回傳值 : st ~ ed 的整數
範例:obj.ox = obj.ox + obj.rand(-10, 10, 1, obj.frame)
○ obj.load(目標, ...)
將物件緩衝區替換為產生的內容。本版本僅支援 "figure"(圖形)。
obj.load("figure", 名稱, 顏色, 大小 [, 線寬 [, 長寬比]])
產生圖形並替換物件緩衝區
(輸出依圖形大小產生並置中)。
名稱 : 圖形名。円 / 四角形 / 三角形 / 五角形 / 六角形 /
星形 之一(亦可用英文 circle, rect, triangle,
pentagon, hexagon, star)。
顏色 : 填滿色 0xRRGGBB。
大小 : 圖形基準大小(像素)。
線寬 : 輪廓寬度(可省略)。省略或 0 為填滿;
指定大於等於大小的值時亦為填滿。
長寬比 : 變形 -1.0 ~ 1.0(可省略)。正值縮小寬度,負值縮小高度。
範例:obj.load("figure", "円", 0xff3366, 200)
* 僅實作了 obj.load("figure", ...)。影像檔、"text"、"tempbuffer"、
"movie" 等目標不執行任何動作。
* 繪製類腳本在 MoonSharp 引擎上執行。
- ymm4 表 -
@@ -437,10 +468,50 @@
obj.zoom = obj.zoom * (1 + obj.track0 / 100)
- AviUtl 腳本的部分相容 -
提供相容層,使 AviUtl 動畫效果腳本(*.anm 系列)中涉及座標、縮放、旋轉、
不透明度的變形以及亂數的部分,無需額外修改即可執行。當腳本中不包含
AviUtl 專有寫法時,此相容層完全不介入(傳統腳本的行為不變)。
○ 腳本標頭指令的解釋
解釋註解形式的參數宣告,在執行前定義腳本主體所參考的變數。
--dialog:項目名,local 變數=預設值;…
將各項目的宣告部分(如 local 變數=預設值)展開至主體開頭。
在 AviUtl 中這些是透過對話框編輯的值,此處以預設值執行。
--color:0xRRGGBB
以指定顏色定義變數 color。
--check0:項目名,預設值
以預設值定義 obj.check0 (0~3)。
--param:任意 Lua 陳述式
將所寫的 Lua 陳述式原樣展開至主體開頭。
--track0: ~ --track3:
軌道列的值仍透過 obj.track0 ~ obj.track3 參考。標頭的標籤、
範圍與預設值不會反映至 UI。
○ 透過 @ 的多區段
當一個腳本以 @名稱 定義了多個效果時,僅執行第一個區段。
○ obj.rand(st, ed [, seed [, frame]])
與 AviUtl 相容的確定性整數亂數。詳情請參閱「obj 表 - 函式」。
○ 圖形繪製
obj.load("figure", ...) 產生圓、四角形、三角形、五角形、六角形、星形,
並替換物件緩衝區。詳情請參閱「obj 表 - 函式」。
以下功能需要與本體的繪製管線整合,因此不在此相容層的範圍內。
呼叫它們的腳本不會如預期運作。
× 繪製與合成(obj.draw / obj.drawpoly)、obj.load 的 "figure" 以外目標
(影像檔、"text"、"movie" 等),以及 obj.setfont
× 濾鏡效果與緩衝區操作
(obj.effect / obj.copybuffer / obj.setoption 等)
× 透過 require 載入模組,以及 io 等檔案存取
- 不支援項目·限制事項 -
× 不支援 AviUtl2 的 obj.effect()、obj.draw()、obj.drawpoly()、obj.load() 等。
× 不支援 AviUtl2 的 obj.rand()、obj.rand1()、obj.setfont()、obj.mes() 等。
× 不支援 AviUtl2 的 obj.effect()、obj.draw()、obj.drawpoly() 等(obj.load 僅支援 "figure",參閱「AviUtl 腳本的部分相容」)。
× 不支援 AviUtl2 的 obj.rand1()、obj.setfont()、obj.mes() 等。
× 不支援 AviUtl2 的 obj.setoption()、obj.getoption()、obj.getvalue()、obj.setanchor() 等。
× 不支援 AviUtl2 scene 表中的 scene.set()、scene.get() 等函式。
(僅支援讀取 scene.width 和 scene.height)
@@ -449,5 +520,6 @@
但 3D 繪製支援有限。
× 超過腳本逾時時間(5 秒)時,執行將被強制終止。
實作時需注意避免出現無限迴圈。
× 不支援 AviUtl2 的 --track@、--check@ 等標頭指令。
參數僅可使用 Track0 ~ Track3。
× AviUtl2 的標頭指令僅部分支援。--dialog / --color / --check / --param 的
預設值會被解釋(參閱「AviUtl 腳本的部分相容」),但 --track@ 的標籤、範圍
與預設值不會反映至 UI,值透過 Track0 ~ Track3 使用。
+90 -5
ファイルの表示
@@ -29,7 +29,9 @@ YukkuriMovieMaker4(YMM4)上で動作する、**Luaスクリプトでオブ
- [6. トラックバー(Track0〜Track3)](#6-トラックバーtrack0track3)
- [7. スクリプトエディタの支援機能](#7-スクリプトエディタの支援機能)
- [8. インポート・エクスポート・クリア](#8-インポートエクスポートクリア)
- [9. AviUtl スクリプトの部分互換](#9-aviutl-スクリプトの部分互換)
5. [実行モデル](#実行モデル)
- [実行エンジンの自動振り分け](#実行エンジンの自動振り分け)
- [実行スレッドとタイムアウト](#実行スレッドとタイムアウト)
- [実行結果のキャッシュ](#実行結果のキャッシュ)
- [グローバル変数のリセットと整合性チェック](#グローバル変数のリセットと整合性チェック)
@@ -46,7 +48,7 @@ YukkuriMovieMaker4(YMM4)上で動作する、**Luaスクリプトでオブ
内部的には MoonSharp(Lua 5.2 互換のスクリプトエンジン)を組み込んでおり、ユーザーが記述した Lua スクリプトをフレームごとに実行します。スクリプト内で `obj.x` や `obj.alpha` といったグローバル変数を書き換えると、その値がオブジェクトの座標・拡縮・回転・不透明度として描画に反映されます。
このエフェクトは AviUtl2 のスクリプト仕様とは異なる独自実装であり、AviUtl 向けの EXO 出力(`.exo`)には対応していません。
このエフェクトは独自のスクリプト実行系を基盤としつつ、AviUtl のアニメーション効果スクリプト(`.anm` 系)の一部に対する互換層を備えています(詳細は[AviUtl スクリプトの部分互換](#9-aviutl-スクリプトの部分互換)を参照)。AviUtl 向けの EXO 出力(`.exo`)には対応していません。
---
@@ -74,7 +76,7 @@ YukkuriMovieMaker4(YMM4)上で動作する、**Luaスクリプトでオブ
### 1. スクリプトエンジン
スクリプトの実行エンジンには MoonSharp(Lua 5.2 互換)を使用しています。利用可能な標準ライブラリは以下に限定されています。
スクリプトの実行エンジンには MoonSharp(Lua 5.2 互換)を使用しています。加えて、ピクセル操作(`obj.getpixel` / `obj.setpixel` / `obj.getpixeldata`)を含むスクリプトは、同梱した高速ランタイム(LuaJIT)で自動的に実行され、大幅に高速化されます(詳細は[実行エンジンの自動振り分け](#実行エンジンの自動振り分け)を参照)。どちらのエンジンでも利用可能な標準ライブラリは以下に限定されています。
- `table`、`string`、`math`、`bit32`
- 基本関数: `type`、`tostring`、`tonumber`、`select`、`error`、`assert`、`print`、`ipairs`、`pairs`、`next`、`unpack`、`setmetatable`、`getmetatable`、`rawget`、`rawset`、`rawequal`、`rawlen`、`pcall`、`xpcall`
@@ -108,6 +110,8 @@ YukkuriMovieMaker4(YMM4)上で動作する、**Luaスクリプトでオブ
- **`obj.putpixeldata()`**: 互換性のために定義された空実装関数です。`setpixel` / `PixelDataProxy:set` による変更は自動的に反映されるため、呼び出す必要はありません。
`getpixel` / `setpixel` / `getpixeldata` のいずれかを最初に呼び出した時点で、GPU 上の画像データを CPU 側へ転送する処理が一度だけ発生します。ピクセル操作を行わないスクリプトではこの転送は発生しません。
これらのピクセル操作を含むスクリプトは、同梱の高速ランタイム(LuaJIT)で自動的に実行され、従来エンジンに比べて大幅(内部計測で数十倍)に高速化されます。出力結果は従来エンジンと一致します。詳細・制約は[実行エンジンの自動振り分け](#実行エンジンの自動振り分け)を参照してください。
### 4. scene テーブルと ymm4 テーブル
`scene` テーブルにはシーン(プロジェクト)の解像度情報が格納されています。いずれも読み取り専用です。
@@ -184,10 +188,56 @@ YukkuriMovieMaker4(YMM4)上で動作する、**Luaスクリプトでオブ
- **インポート**: `.lua` ファイルを選択して読み込み、選択中のすべてのアイテムのスクリプトを置き換えます。
- **エクスポート**: 現在のスクリプトを `.lua` ファイルとして保存します。複数のアイテムを選択している場合でも、書き出されるのは先頭の 1 件のスクリプトのみです。
- **クリア**: 確認ダイアログの表示後、選択中のすべてのアイテムのスクリプトをデフォルトスクリプト(`obj.alpha = math.min(time * 255, 255)`)に戻します。
### 9. AviUtl スクリプトの部分互換
AviUtl のアニメーション効果スクリプト(`.anm` 系)のうち、座標・拡縮・回転・不透明度の変形、乱数、および図形描画について、追加の記述変更なしに実行できる互換層を備えています。スクリプトに AviUtl 固有の記法が含まれない場合、この互換層は一切介入しません(従来のスクリプトの挙動は変わりません)。
対応している内容は次のとおりです。
- **スクリプトヘッダの解釈**: コメント形式のパラメータ宣言を解釈し、スクリプト本体が参照する変数を実行前に定義します。
- `--dialog:項目名,local 変数=既定値;…` … 各項目の宣言部(`local 変数=既定値` など)を本体の先頭に展開します。AviUtl では対話ダイアログで編集される値ですが、本プラグインでは既定値で動作します。
- `--color:0xRRGGBB` … 変数 `color` を指定色で定義します。
- `--check0:項目名,既定値` … `obj.check0`(`0`〜`3`)を既定値で定義します。
- `--param:任意のLua文` … 記述した Lua 文をそのまま本体の先頭に展開します。
- `--track0:`〜`--track3:` … トラックバーの値は従来どおり `obj.track0`〜`obj.track3` から参照します(ラベル・範囲・既定値の UI 反映は行いません)。
- **`@` による複数セクション**: 1 つのスクリプトに `@名前` で複数の効果が定義されている場合、先頭のセクションのみを実行します。
- **`obj.rand(st, ed [, seed [, frame]])`**: 指定範囲(`st`〜`ed`)の整数を返す決定論的な乱数です。`seed` と `frame` が同じであれば常に同じ値を返し、`frame` を省略すると現在のフレームを用います。従来エンジン(MoonSharp)と高速ランタイム(LuaJIT)で同じ値を返します。
- **`obj.load("figure", 名前, 色, サイズ [, ライン [, アスペクト]])`**: 円・四角形・三角形・五角形・六角形・星形を生成し、オブジェクトのバッファを置き換えて描画します(出力は図形サイズに合わせて生成され、中心に配置されます)。`ライン` を省略するか `0` で塗りつぶし、サイズ以上の値でも塗りつぶしになります。`アスペクト`(-1.0〜1.0)で幅・高さを歪曲できます。`figure` 以外の対象は本バージョンでは対象外です。描画系 API を含むスクリプトは従来エンジン(MoonSharp)で実行されます。
次のような機能は、本体の描画パイプラインへの統合を要するため、この互換層では対象外です(呼び出しを含むスクリプトは意図どおりには動作しません)。
- 描画・合成(`obj.draw` / `obj.drawpoly`)、`obj.load` の `"figure"` 以外の対象(画像ファイル・`"text"`・`"movie"` など)、および `obj.setfont`
- フィルタ効果やバッファ操作(`obj.effect` / `obj.copybuffer` / `obj.setoption` など)
- `require` によるモジュール読み込み、`io` などのファイルアクセス
---
## 実行モデル
### 実行エンジンの自動振り分け
スクリプトは内容に応じて 2 つのエンジンへ自動的に振り分けられます。
- **ピクセル操作を含むスクリプト**(`obj.getpixel` / `obj.setpixel` / `obj.getpixeldata` を含む)→ 同梱の高速ランタイム **LuaJIT** で実行(ネイティブ実行)。
- **変形のみのスクリプト** → 従来の **MoonSharp** で実行。
スクリプトの先頭行に次のディレクティブを書くと、エンジンを明示指定できます。
- `--!native` … 高速ランタイム(LuaJIT)で実行
- `--!moonsharp` … 従来エンジン(MoonSharp)で実行
ネイティブ実行は**専用の別プロセス**で行われ、ピクセルバッファは共有メモリ経由で受け渡されます。スクリプトが無限ループに陥った場合でも **5 秒のタイムアウトでプロセスを強制終了**するため本体は固まらず、終了後は自動的に復帰します。出力結果は従来エンジンと一致します。
`obj.getobject` はネイティブ実行でも利用できます。呼び出し時に本体プロセスへ同期的に問い合わせてシーンオブジェクトを解決するため、従来エンジンと同じ結果を返します。同じタグ・同じフレームへの連続した問い合わせはフレーム内でキャッシュされ、2 回目以降は往復を行いません。
ネイティブ実行には次の制約があります。
- `bit32` は正しい Lua 5.2 の挙動になります。実用域(0〜2³¹未満の値・0〜31 のシフト量)では従来と一致しますが、`bit32.lshift(1, 32)` のような範囲外の特殊ケースのみ結果が変わります(ネイティブ=0、従来=1)。
- `math.random` は両エンジンとも毎フレーム `frame` でシードし直す決定論的乱数ですが、乱数列の実装が異なるためエンジンをまたぐと同じシードでも値が変わります。エンジン非依存の乱数が必要な場合は `anim.rand(min, max, seed)` を使用してください。
> 高速ランタイム(`luajit.exe` / `lua51.dll` 等)はプラグインに同梱され、本体と同じ場所の `native` フォルダーへ自動配置されます。手動インストールは不要です。
### 実行スレッドとタイムアウト
スクリプトはエフェクトインスタンスごとに確保された専用のバックグラウンドスレッド上で実行されます。実行要求は容量 1 のキューを介してこのスレッドへ渡され、メイン側は実行完了またはタイムアウトまで待機します。
@@ -295,10 +345,10 @@ obj.alpha = anim.ease_out(t) * 255
## 注意事項
- **AviUtl 非対応**: 本プラグインは独自のスクリプト実行系であり、AviUtl 向けの EXO 出力(`.exo`)には対応していません。
- **AviUtl 互換は部分的**: AviUtl のアニメーション効果スクリプトのうち、変形・不透明度・乱数の範囲のみ実行できます([AviUtl スクリプトの部分互換](#9-aviutl-スクリプトの部分互換)を参照)。描画・フィルタ・ファイルアクセス系の関数、および AviUtl 向けの EXO 出力(`.exo`)には対応していません。
- **実行タイムアウト**: スクリプトの実行は 5000ms(5秒)でタイムアウトし、超過した場合は強制終了されエラーとして扱われます。無限ループが発生しないよう注意してください。
- **利用可能な標準ライブラリの制限**: `table`、`string`、`math`、`bit32` および基本関数のみ利用できます。`io`、`os`、`debug`、`ffi`、`require` は利用できません。
- **ピクセル操作の負荷**: `obj.getpixel` / `obj.setpixel` / `obj.getpixeldata` は実際の入力画像にアクセスするため、各フレームで最初に呼び出した際に GPU→CPU へのデータ転送が発生します。不要な場合は呼び出しを省略することで処理を高速化できます。
- **ピクセル操作の負荷**: `obj.getpixel` / `obj.setpixel` / `obj.getpixeldata` は実際の入力画像にアクセスするため、各フレームで最初に呼び出した際に GPU→CPU へのデータ転送が発生します。不要な場合は呼び出しを省略することで処理を高速化できます。これらを含むスクリプトは高速ランタイム(LuaJIT)で自動実行され大幅に高速化されます。詳細は[実行エンジンの自動振り分け](#実行エンジンの自動振り分け)を参照。
- **`math.random` はフレームごとの決定論的な乱数**: 毎フレーム `frame` の値でシードし直されるため、同一フレームでは常に同じ値になります。フレームをまたいで変化する乱数的な値が必要な場合は `anim.rand` の利用を検討してください。
- **`obj.oz` は出力に反映されません**: スクリプト実行後にコンテキストへ読み戻されますが、現在の実装では中心点オフセットの出力計算に使用されていません。
- **エクスポートは先頭の1件のみ**: 複数アイテムを選択した状態でも、エクスポートされるスクリプトは先頭のアイテムのもののみです(インポート・クリアは選択中のすべてのアイテムに適用されます)。
@@ -319,7 +369,14 @@ obj.alpha = anim.ease_out(t) * 255
## サードパーティライセンス
本プラグインは、Luaスクリプトの実行エンジンとして [MoonSharp](https://github.com/moonsharp-devs/moonsharp)(3-Clause BSD License)を使用しています。
本プラグインは以下のサードパーティソフトウェアを同梱・使用しています。各ライセンスの全文は、配布パッケージ(`.ymme`)内の `LICENSE` フォルダーおよびリポジトリの [`.github/LICENSE`](.github/LICENSE) に収録しています。
| ソフトウェア | 用途 | ライセンス |
|---|---|---|
| [MoonSharp](https://github.com/moonsharp-devs/moonsharp) | 標準のLua実行エンジン(Lua 5.2 互換) | 3-Clause BSD License |
| [LuaJIT](https://github.com/LuaJIT/LuaJIT) | ピクセル操作向け高速ランタイム(`native/luajit.exe`・`lua51.dll`) | MIT License |
### MoonSharp(3-Clause BSD License)
```
Copyright (c) 2014-2016, Marco Mastropaolo
@@ -352,6 +409,34 @@ OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
```
### LuaJIT(MIT License)
同梱の高速ランタイム(`native/luajit.exe`・`native/lua51.dll`)は LuaJIT v2.1 です。LuaJIT 本体は MIT License で配布されており、その中に Lua 5.1/5.2(Copyright © 1994-2012 Lua.org, PUC-Rio、MIT License)および dlmalloc(パブリックドメイン)のコードを含みます。以下は LuaJIT 本体の著作権表示です(Lua・dlmalloc を含む全文は `LICENSE/LuaJIT.txt` を参照)。
```
LuaJIT -- a Just-In-Time Compiler for Lua. https://luajit.org/
Copyright (C) 2005-2026 Mike Pall. All rights reserved.
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
```
---
## ライセンス
+1
ファイルの表示
@@ -0,0 +1 @@
luascript.routersys.com
バイナリ
ファイルの表示
バイナリファイルは表示されません。
バイナリ
ファイルの表示
バイナリファイルは表示されません。
+25
ファイルの表示
@@ -0,0 +1,25 @@
local shimPath = arg[1]
local vectorsPath = arg[2]
assert(loadfile(shimPath))()
local f = assert(io.open(vectorsPath, "r"))
local out = {}
for line in f:lines() do
local chunk = loadstring("return " .. line)
if not chunk then
out[#out + 1] = "ERROR"
else
local ok, res = pcall(chunk)
if not ok then
out[#out + 1] = "ERROR"
elseif type(res) == "boolean" then
out[#out + 1] = res and "true" or "false"
else
out[#out + 1] = string.format("%.17g", res)
end
end
end
f:close()
io.write(table.concat(out, "\n"))
+367
ファイルの表示
@@ -0,0 +1,367 @@
local ffi = require("ffi")
local bit = require("bit")
local i64 = ffi.typeof("int64_t")
local u32 = ffi.typeof("uint32_t")
local u64 = ffi.typeof("uint64_t")
local function tou(d)
return tonumber(u32(i64(d)))
end
local function umul32(a, b)
return tonumber(u32(u64(a) * u64(b)))
end
local function mask(width)
if width <= 0 then return 0 end
if width >= 32 then return tou(0xFFFFFFFF) end
return bit.lshift(1, width) - 1
end
local function validate(pos, width)
if pos < 0 or width < 1 or pos + width > 32 then
error("trying to access non-existent bits")
end
end
bit32 = {}
function bit32.band(...) return tou(bit.band(...)) end
function bit32.bor(...) return tou(bit.bor(...)) end
function bit32.bxor(...) return tou(bit.bxor(...)) end
function bit32.btest(...) return tou(bit.band(...)) ~= 0 end
function bit32.bnot(x) return tou(bit.bnot(x)) end
function bit32.lshift(x, n)
if n <= -32 or n >= 32 then return 0 end
if n >= 0 then return tou(bit.lshift(x, n)) end
return tou(bit.rshift(x, -n))
end
function bit32.rshift(x, n) return bit32.lshift(x, -n) end
function bit32.arshift(x, n)
if n < 0 then return bit32.lshift(x, -n) end
if n > 31 then n = 31 end
return tou(bit.arshift(x, n))
end
function bit32.lrotate(x, n) return tou(bit.rol(x, n)) end
function bit32.rrotate(x, n) return tou(bit.ror(x, n)) end
function bit32.extract(v, pos, width)
width = width or 1
validate(pos, width)
return tou(bit.band(bit.rshift(v, pos), mask(width)))
end
function bit32.replace(v, u, pos, width)
width = width or 1
validate(pos, width)
local m = bit.lshift(mask(width), pos)
return tou(bit.bor(bit.band(v, bit.bnot(m)), bit.band(bit.lshift(u, pos), m)))
end
if rawlen == nil then
rawlen = function(x)
local t = type(x)
if t == "table" then return #x end
if t == "string" then return string.len(x) end
error("table or string expected")
end
end
local floor = math.floor
local abs = math.abs
local sqrt = math.sqrt
local sin = math.sin
local cos = math.cos
local fmod = math.fmod
local pi = math.pi
local tau = pi * 2
local function clamp(v, lo, hi)
if v < lo then return lo end
if v > hi then return hi end
return v
end
anim = {}
anim.tau = tau
anim.e = math.exp(1)
anim.phi = (1 + sqrt(5)) / 2
anim.sqrt2 = sqrt(2)
function anim.lerp(a, b, t) return a + (b - a) * t end
function anim.smoothstep(e0, e1, x)
local span = e1 - e0
local t = span == 0 and 0 or clamp((x - e0) / span, 0, 1)
return t * t * (3 - 2 * t)
end
function anim.smootherstep(e0, e1, x)
local span = e1 - e0
local t = span == 0 and 0 or clamp((x - e0) / span, 0, 1)
return t * t * t * (t * (6 * t - 15) + 10)
end
function anim.clamp(v, lo, hi) return clamp(v, lo, hi) end
function anim.map(v, a1, b1, a2, b2)
local range = b1 - a1
if range == 0 then return a2 end
return a2 + (b2 - a2) * (v - a1) / range
end
function anim.norm(v, lo, hi)
local span = hi - lo
if span == 0 then return 0 end
return (v - lo) / span
end
function anim.wrap(v, lo, hi)
local range = hi - lo
if range <= 0 then return lo end
local result = fmod(v - lo, range)
if result < 0 then result = result + range end
return lo + result
end
function anim.pingpong(t, length)
if length <= 0 then return 0 end
local v = fmod(t, 2 * length)
if v < 0 then v = v + 2 * length end
if v > length then return 2 * length - v end
return v
end
function anim.sign(v)
if v > 0 then return 1 end
if v < 0 then return -1 end
return 0
end
function anim.oscillate(t, lo, hi, freq)
local wave = (sin(t * freq * tau) + 1) / 2
return lo + (hi - lo) * wave
end
function anim.triangle(t, freq)
local f = t * freq
f = f - floor(f)
return 1 - 2 * abs(f - 0.5)
end
function anim.square(t, freq)
local f = t * freq
f = f - floor(f)
return f >= 0.5 and 1 or 0
end
function anim.duration(t, dur)
if dur <= 0 then return 1 end
return clamp(t / dur, 0, 1)
end
function anim.delay(t, d) return math.max(0, t - d) end
function anim.ease_in(t) return t * t end
function anim.ease_out(t)
local inv = 1 - t
return 1 - inv * inv
end
function anim.ease_in_out(t)
if t < 0.5 then return 2 * t * t end
local inv = -2 * t + 2
return 1 - inv * inv / 2
end
function anim.elastic(t)
t = clamp(t, 0, 1)
if t == 0 then return 0 end
if t == 1 then return 1 end
return 2 ^ (-10 * t) * sin((t * 10 - 0.75) * (tau / 3)) + 1
end
function anim.back(t)
local c1 = 1.70158
local c3 = c1 + 1
local inv = t - 1
return 1 + c3 * inv * inv * inv + c1 * inv * inv
end
function anim.step(edge, x) return x >= edge and 1 or 0 end
function anim.fract(v) return v - floor(v) end
function anim.bounce(t)
local n1 = 7.5625
local d1 = 2.75
t = clamp(t, 0, 1)
if t < 1 / d1 then return n1 * t * t end
if t < 2 / d1 then
t = t - 1.5 / d1
return n1 * t * t + 0.75
end
if t < 2.5 / d1 then
t = t - 2.25 / d1
return n1 * t * t + 0.9375
end
t = t - 2.625 / d1
return n1 * t * t + 0.984375
end
function anim.hsv_to_rgb(h, s, v)
local c = v * s
local x = c * (1 - abs(fmod(h / 60, 2) - 1))
local m = v - c
local sector = floor(h / 60) % 6
local r, g, b
if sector == 0 then r, g, b = c, x, 0
elseif sector == 1 then r, g, b = x, c, 0
elseif sector == 2 then r, g, b = 0, c, x
elseif sector == 3 then r, g, b = 0, x, c
elseif sector == 4 then r, g, b = x, 0, c
else r, g, b = c, 0, x end
return (r + m) * 255, (g + m) * 255, (b + m) * 255
end
function anim.rgb_to_hsv(r, g, b)
r = r / 255; g = g / 255; b = b / 255
local max = math.max(r, g, b)
local min = math.min(r, g, b)
local delta = max - min
local h = 0
if delta > 0 then
if max == r then
h = 60 * fmod(fmod((g - b) / delta, 6) + 6, 6)
elseif max == g then
h = 60 * ((b - r) / delta + 2)
else
h = 60 * ((r - g) / delta + 4)
end
end
return h, max > 0 and delta / max or 0, max
end
function anim.len(x, y) return sqrt(x * x + y * y) end
function anim.dist(x1, y1, x2, y2)
local dx = x2 - x1
local dy = y2 - y1
return sqrt(dx * dx + dy * dy)
end
function anim.dot(x1, y1, x2, y2) return x1 * x2 + y1 * y2 end
function anim.normalize(x, y)
local m = sqrt(x * x + y * y)
if m == 0 then return 0, 0 end
return x / m, y / m
end
function anim.polar(r, a)
local rad = a * pi / 180
return r * cos(rad), r * sin(rad)
end
function anim.rotate(x, y, a)
local rad = a * pi / 180
local c = cos(rad)
local s = sin(rad)
return x * c - y * s, x * s + y * c
end
function anim.bezier(t, p0, p1, p2, p3)
t = clamp(t, 0, 1)
local inv = 1 - t
local b0 = inv * inv * inv
local b1 = 3 * inv * inv * t
local b2 = 3 * inv * t * t
local b3 = t * t * t
return b0 * p0 + b1 * p1 + b2 * p2 + b3 * p3
end
function anim.rand(...)
local a = { ... }
local n = select("#", ...)
if n == 0 then return 0 end
local min, max, seed = 0, 1, 0
if n == 1 then
seed = a[1]
elseif n == 2 then
max, seed = a[1], a[2]
else
min, max, seed = a[1], a[2], a[3]
end
local p = ffi.new("double[1]", seed)
local w = ffi.cast("uint32_t*", p)
local lo, hi = tonumber(w[0]), tonumber(w[1])
local h = umul32(tou(bit.bxor(lo, hi)), 374761393)
h = umul32(tou(bit.bxor(h, bit.rshift(h, 13))), 1274126177)
local r = tou(bit.bxor(h, bit.rshift(h, 16))) / 4294967295.0
return min + r * (max - min)
end
function aviutl_rand(a, b, seed, frame)
local ps = ffi.new("double[1]", seed)
local ws = ffi.cast("uint32_t*", ps)
local s = tou(bit.bxor(ws[0], ws[1]))
local pf = ffi.new("double[1]", frame)
local wf = ffi.cast("uint32_t*", pf)
local f = tou(bit.bxor(wf[0], wf[1]))
local h = tou(umul32(s, 374761393) + umul32(f, 668265263))
h = umul32(tou(bit.bxor(h, bit.rshift(h, 13))), 1274126177)
h = tou(bit.bxor(h, bit.rshift(h, 16)))
local r = h / 4294967295.0
local lo = floor(math.min(a, b))
local hi = floor(math.max(a, b))
local span = hi - lo + 1
if span <= 1 then return lo end
local v = lo + floor(r * span)
if v > hi then return hi end
return v
end
local function noise_hash(x, y, z)
local n = tou(umul32(tou(x), 374761393) + umul32(tou(y), 668265263) + umul32(tou(z), 1013904223))
n = umul32(tou(bit.bxor(n, bit.rshift(n, 13))), 1274126177)
return tou(bit.bxor(n, bit.rshift(n, 16))) / 4294967295.0
end
function anim.noise(x, y, z)
y = y or 0
z = z or 0
local xi = floor(x)
local yi = floor(y)
local zi = floor(z)
local xf = x - xi
local yf = y - yi
local zf = z - zi
local u = xf * xf * (3 - 2 * xf)
local v = yf * yf * (3 - 2 * yf)
local w = zf * zf * (3 - 2 * zf)
local c000 = noise_hash(xi, yi, zi)
local c100 = noise_hash(xi + 1, yi, zi)
local c010 = noise_hash(xi, yi + 1, zi)
local c110 = noise_hash(xi + 1, yi + 1, zi)
local c001 = noise_hash(xi, yi, zi + 1)
local c101 = noise_hash(xi + 1, yi, zi + 1)
local c011 = noise_hash(xi, yi + 1, zi + 1)
local c111 = noise_hash(xi + 1, yi + 1, zi + 1)
local x00 = c000 + u * (c100 - c000)
local x10 = c010 + u * (c110 - c010)
local x01 = c001 + u * (c101 - c001)
local x11 = c011 + u * (c111 - c011)
local y0 = x00 + v * (x10 - x00)
local y1 = x01 + v * (x11 - x01)
return y0 + w * (y1 - y0)
end
+292
ファイルの表示
@@ -0,0 +1,292 @@
local ffi = require("ffi")
ffi.cdef [[
typedef void* HANDLE;
HANDLE OpenFileMappingA(unsigned long, int, const char*);
void* MapViewOfFile(HANDLE, unsigned long, unsigned long, unsigned long, size_t);
int UnmapViewOfFile(const void*);
int CloseHandle(HANDLE);
HANDLE OpenEventA(unsigned long, int, const char*);
unsigned long WaitForSingleObject(HANDLE, unsigned long);
int SetEvent(HANDLE);
unsigned long GetLastError();
]]
local k32 = ffi.load("kernel32")
local FILE_MAP_ALL_ACCESS = 0x000F001F
local EVENT_ALL_ACCESS = 0x1F0003
local INFINITE = 0xFFFFFFFF
local mapName = arg[1]
local mapSize = tonumber(arg[2])
local workEventName = arg[3]
local doneEventName = arg[4]
local shimPath = arg[5]
local hMap = k32.OpenFileMappingA(FILE_MAP_ALL_ACCESS, 0, mapName)
assert(hMap ~= nil, "OpenFileMapping failed")
local view = k32.MapViewOfFile(hMap, FILE_MAP_ALL_ACCESS, 0, 0, mapSize)
assert(view ~= nil, "MapViewOfFile failed")
local workEvent = k32.OpenEventA(EVENT_ALL_ACCESS, 0, workEventName)
local doneEvent = k32.OpenEventA(EVENT_ALL_ACCESS, 0, doneEventName)
assert(workEvent ~= nil and doneEvent ~= nil, "OpenEvent failed")
local base = ffi.cast("uint8_t*", view)
local i32 = ffi.cast("int32_t*", base)
local f64 = ffi.cast("double*", base + 64)
local OFF_COMMAND = 1
local OFF_STATUS = 2
local OFF_WIDTH = 3
local OFF_HEIGHT = 4
local OFF_SCRIPTLEN = 5
local OFF_PIXELSDIRTY = 6
local OFF_ERRORLEN = 7
local OFF_CB_FRAME = 8
local OFF_CB_TAGLEN = 9
local OFF_CB_FOUND = 10
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 = 256
local CB_RESULT_OFFSET = CB_TAG_OFFSET + CB_TAG_MAX
local PIXEL_OFFSET = CB_RESULT_OFFSET + 8 * 8
local FIRST_WRITABLE = 8
local LAST_WRITABLE = 25
local STATUS_CALLBACK = 3
assert(loadfile(shimPath))()
local clamp = function(v, lo, hi)
if v < lo then return lo end
if v > hi then return hi end
return v
end
local width, height = 0, 0
local pixels = ffi.cast("uint8_t*", base + PIXEL_OFFSET)
local cbResult = ffi.cast("double*", base + CB_RESULT_OFFSET)
local dirty = false
local obj = {}
local scene = {}
local ymm4 = {}
function obj.getpixel(x, y)
x = math.floor(x); y = math.floor(y)
if x < 0 or y < 0 or x >= width or y >= height then return 0, 0, 0, 0 end
local p = pixels + (y * width + x) * 4
local a = p[3]
if a <= 0 then return 0, 0, 0, 0 end
local s = 255 / a
return clamp(p[2] * s, 0, 255), clamp(p[1] * s, 0, 255), clamp(p[0] * s, 0, 255), a
end
function obj.setpixel(x, y, r, g, b, a)
x = math.floor(x); y = math.floor(y)
if x < 0 or y < 0 or x >= width or y >= height then return end
a = a or 255
dirty = true
local aK = clamp(a, 0, 255) / 255
local p = pixels + (y * width + x) * 4
p[0] = math.floor(clamp(b * aK, 0, 255))
p[1] = math.floor(clamp(g * aK, 0, 255))
p[2] = math.floor(clamp(r * aK, 0, 255))
p[3] = math.floor(clamp(a, 0, 255))
end
function obj.getpixeldata()
local total = width * height * 4
local buf = pixels
local pd = { width = width, height = height }
function pd:get(index)
local zb = index - 1
if zb < 0 or zb >= total then return 0 end
local pi = math.floor(zb / 4)
local ch = zb - pi * 4
local p = buf + pi * 4
local a = p[3]
if ch == 3 then return a end
if a <= 0 then return 0 end
local sc = 255 / a
if ch == 0 then return clamp(p[2] * sc, 0, 255) end
if ch == 1 then return clamp(p[1] * sc, 0, 255) end
return clamp(p[0] * sc, 0, 255)
end
function pd:set(index, value)
local zb = index - 1
if zb < 0 or zb >= total then return end
dirty = true
local pi = math.floor(zb / 4)
local ch = zb - pi * 4
local p = buf + pi * 4
local clamped = clamp(value, 0, 255)
if ch == 3 then
local oldA = p[3]
local newA = clamped
if oldA > 0 and newA > 0 then
local f = newA / oldA
p[0] = math.floor(clamp(p[0] * f, 0, 255))
p[1] = math.floor(clamp(p[1] * f, 0, 255))
p[2] = math.floor(clamp(p[2] * f, 0, 255))
elseif newA <= 0 then
p[0] = 0; p[1] = 0; p[2] = 0
end
p[3] = math.floor(newA)
else
local a = p[3]
local pm = clamped * (a / 255)
local bo = (ch == 0) and 2 or ((ch == 1) and 1 or 0)
p[bo] = math.floor(clamp(pm, 0, 255))
end
end
return pd
end
function obj.putpixeldata() end
function obj.rand(a, b, seed, frame)
return aviutl_rand(a or 0, b or 0, seed or 0, frame or obj.frame or 0)
end
local cacheTag, cacheFrame, cacheFound
local cacheExist, cacheX, cacheY, cacheZ, cacheZoom, cacheRz, cacheAlpha, cacheLayer
local function buildObject()
return {
exist = cacheExist,
x = cacheX, y = cacheY, z = cacheZ,
zoom = cacheZoom, sx = cacheZoom, sy = cacheZoom,
rx = 0, ry = 0, rz = cacheRz,
rxr = 0, ryr = 0, rzr = cacheRz * math.pi / 180,
alpha = cacheAlpha, layer = cacheLayer,
}
end
function obj.getobject(tag, frame)
if type(tag) ~= "string" then return nil end
if frame then frame = math.floor(frame) else frame = math.floor(obj.timelineframe or 0) end
if tag == cacheTag and frame == cacheFrame then
if cacheFound then return buildObject() end
return nil
end
local len = #tag
if len > CB_TAG_MAX then len = CB_TAG_MAX end
ffi.copy(base + CB_TAG_OFFSET, tag, len)
i32[OFF_CB_TAGLEN] = len
i32[OFF_CB_FRAME] = frame
i32[OFF_STATUS] = STATUS_CALLBACK
k32.SetEvent(doneEvent)
k32.WaitForSingleObject(workEvent, INFINITE)
cacheTag = tag
cacheFrame = frame
if i32[OFF_CB_FOUND] == 0 then
cacheFound = false
return nil
end
cacheFound = true
cacheExist = cbResult[0] ~= 0
cacheX = cbResult[1]; cacheY = cbResult[2]; cacheZ = cbResult[3]
cacheZoom = cbResult[4]; cacheRz = cbResult[5]; cacheAlpha = cbResult[6]; cacheLayer = cbResult[7]
return buildObject()
end
local sandbox = {
obj = obj, scene = scene, ymm4 = ymm4,
anim = anim, bit32 = bit32, rawlen = rawlen,
math = math, string = string, table = table,
type = type, tostring = tostring, tonumber = tonumber, select = select,
error = error, assert = assert, ipairs = ipairs, pairs = pairs, next = next,
unpack = unpack, setmetatable = setmetatable, getmetatable = getmetatable,
rawget = rawget, rawset = rawset, rawequal = rawequal, rawlen = rawlen,
pcall = pcall, xpcall = xpcall, print = function() end,
}
sandbox._G = sandbox
local compiledCode, compiledChunk
local function loadFields()
width = i32[OFF_WIDTH]
height = i32[OFF_HEIGHT]
obj.w = f64[0]; obj.h = f64[1]; obj.hw = f64[2]; obj.hh = f64[3]
obj.cx = f64[4]; obj.cy = f64[5]; obj.cz = f64[6]; obj.diagonal = f64[7]
obj.x = f64[8]; obj.y = f64[9]; obj.z = f64[10]
obj.ox = f64[11]; obj.oy = f64[12]; obj.oz = f64[13]
obj.sx = f64[14]; obj.sy = f64[15]; obj.sz = f64[16]
obj.zoom = f64[17]; obj.aspect = f64[18]; obj.alpha = f64[19]
obj.rx = f64[20]; obj.ry = f64[21]; obj.rz = f64[22]
obj.rxr = f64[23]; obj.ryr = f64[24]; obj.rzr = f64[25]
obj.track0 = f64[26]; obj.track1 = f64[27]; obj.track2 = f64[28]; obj.track3 = f64[29]
obj.time = f64[30]; obj.frame = f64[31]; obj.totalframe = f64[32]; obj.totaltime = f64[33]
obj.t = f64[34]; obj.framerate = f64[35]; obj.layer = f64[36]; obj.index = f64[37]; obj.num = f64[38]
scene.width = f64[39]; scene.height = f64[40]; scene.cx = f64[41]; scene.cy = f64[42]
ymm4.group_index = f64[43]; ymm4.group_count = f64[44]
ymm4.timeline_totalframe = f64[45]; ymm4.timeline_totaltime = f64[46]
ymm4.time_ratio = f64[47]
ymm4.is_saving = f64[48] ~= 0; ymm4.is_playing = f64[49] ~= 0; ymm4.is_paused = f64[50] ~= 0
ymm4.group_ratio = (f64[44] ~= 0) and (f64[43] / f64[44]) or 0
obj.timelineframe = f64[51]; obj.timelinetime = f64[52]
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
end
local function storeFields()
for i = FIRST_WRITABLE, LAST_WRITABLE do
local key
if i == 8 then key = obj.x elseif i == 9 then key = obj.y elseif i == 10 then key = obj.z
elseif i == 11 then key = obj.ox elseif i == 12 then key = obj.oy elseif i == 13 then key = obj.oz
elseif i == 14 then key = obj.sx elseif i == 15 then key = obj.sy elseif i == 16 then key = obj.sz
elseif i == 17 then key = obj.zoom elseif i == 18 then key = obj.aspect elseif i == 19 then key = obj.alpha
elseif i == 20 then key = obj.rx elseif i == 21 then key = obj.ry elseif i == 22 then key = obj.rz
elseif i == 23 then key = obj.rxr elseif i == 24 then key = obj.ryr elseif i == 25 then key = obj.rzr end
f64[i] = tonumber(key) or f64[i]
end
end
while true do
k32.WaitForSingleObject(workEvent, INFINITE)
if i32[OFF_COMMAND] == 1 then break end
dirty = false
local scriptLen = i32[OFF_SCRIPTLEN]
local code = ffi.string(base + SCRIPT_OFFSET, scriptLen)
if code ~= compiledCode then
local chunk, err = loadstring(code, "LuaScript")
if chunk then
compiledChunk = chunk
compiledCode = code
else
compiledChunk = nil
local msg = err or "compile error"
ffi.copy(base + ERROR_OFFSET, msg, math.min(#msg, 4096))
i32[OFF_ERRORLEN] = math.min(#msg, 4096)
i32[OFF_STATUS] = 2
k32.SetEvent(doneEvent)
end
end
if compiledChunk and code == compiledCode then
loadFields()
cacheTag = nil
math.randomseed(f64[31])
setfenv(compiledChunk, sandbox)
local ok, err = pcall(compiledChunk)
if ok then
storeFields()
i32[OFF_PIXELSDIRTY] = dirty and 1 or 0
i32[OFF_STATUS] = 1
k32.SetEvent(doneEvent)
else
local msg = tostring(err)
ffi.copy(base + ERROR_OFFSET, msg, math.min(#msg, 4096))
i32[OFF_ERRORLEN] = math.min(#msg, 4096)
i32[OFF_STATUS] = 2
k32.SetEvent(doneEvent)
end
end
end
k32.UnmapViewOfFile(view)
k32.CloseHandle(hMap)
+42
ファイルの表示
@@ -0,0 +1,42 @@
local ffi = require("ffi")
ffi.cdef [[
typedef void* HANDLE;
HANDLE OpenFileMappingA(unsigned long dwDesiredAccess, int bInheritHandle, const char* lpName);
void* MapViewOfFile(HANDLE hFileMappingObject, unsigned long dwDesiredAccess, unsigned long dwFileOffsetHigh, unsigned long dwFileOffsetLow, size_t dwNumberOfBytesToMap);
int UnmapViewOfFile(const void* lpBaseAddress);
int CloseHandle(HANDLE hObject);
unsigned long GetLastError();
]]
local k32 = ffi.load("kernel32")
local FILE_MAP_ALL_ACCESS = 0x000F001F
local name = arg[1]
local size = tonumber(arg[2])
local h = k32.OpenFileMappingA(FILE_MAP_ALL_ACCESS, 0, name)
if h == nil then error("OpenFileMapping failed: " .. tonumber(k32.GetLastError())) end
local p = k32.MapViewOfFile(h, FILE_MAP_ALL_ACCESS, 0, 0, size)
if p == nil then
k32.CloseHandle(h)
error("MapViewOfFile failed: " .. tonumber(k32.GetLastError()))
end
local buf = ffi.cast("uint8_t*", p)
local pixels = size / 4
for i = 0, pixels - 1 do
local b = buf[i * 4]
local g = buf[i * 4 + 1]
local r = buf[i * 4 + 2]
local gray = math.floor(r * 0.299 + g * 0.587 + b * 0.114 + 0.5)
if gray > 255 then gray = 255 end
buf[i * 4] = gray
buf[i * 4 + 1] = gray
buf[i * 4 + 2] = gray
end
k32.UnmapViewOfFile(p)
k32.CloseHandle(h)
io.write("done")