コミットを比較

..
187 コミット
作成者 SHA1 メッセージ 日付
routersys 381a717942 画像の参照先をGiteaへ移す 2026-11-08 21:44:06 +09:00
routersys 1d92d80a86 バージョンをv1.10.0へ更新
リリース / build-and-release (workflow_dispatch) Actions がタグ v1.10.0 のコミットから作成しました
2026-07-01 08:20:00 +09:00
routersys 86ad19105f サイトにslider/文字列パラメータと両エンジン対応を追記 2026-07-01 08:12:32 +09:00
routersys 2cd5ab273a READMEにslider/文字列パラメータを追記 2026-07-01 08:10:28 +09:00
routersys d75aeee3c2 全言語ドキュメントにslider/文字列パラメータを追記 2026-07-01 08:09:57 +09:00
routersys 981fb2ceeb ネイティブ文字列容量を必要量に応じ動的に拡張縮小 2026-07-01 07:58:28 +09:00
routersys 01a0dcb9ae ネイティブ文字列領域の容量を起動時パラメータ化 2026-07-01 07:56:57 +09:00
routersys 460b5e6252 ネイティブ文字列書込でname byteをキャッシュしvalue bufferを再利用 2026-07-01 07:49:02 +09:00
routersys fb02580836 文字列パラメータ変更検出をバージョン方式にし毎フレームのアロケーションを排除 2026-07-01 07:48:08 +09:00
routersys 58a5f59b19 ネイティブレーンで文字列パラメータをobjへ展開 2026-06-30 23:38:26 +09:00
routersys 95598b1a88 ネイティブ共有メモリに文字列パラメータ領域を確保 2026-06-30 23:33:36 +09:00
routersys 7f436ebe17 ファイル選択からtransition/tachie/texture/thumbnailを削除 2026-06-30 23:32:36 +09:00
routersys d620f7ea3b スライダーを整数値に変更し小数を排除 2026-06-30 23:31:24 +09:00
routersys ad377a0923 補完候補に文字列パラメータを追加 2026-06-30 23:21:45 +09:00
routersys f374038000 補完候補にobj.slider0〜3を追加 2026-06-30 23:17:11 +09:00
routersys ddba8d63c2 FileGroupType別のファイル選択を追加しobj.file_*を公開 2026-06-30 23:10:11 +09:00
routersys ab2e195139 フォルダ選択を追加しobj.dirを公開 2026-06-30 23:08:41 +09:00
routersys 85c585db89 フォントセレクターを追加しobj.fontを公開 2026-06-30 23:07:42 +09:00
routersys 93eb681b0e テキストエディタを追加しobj.textを公開 2026-06-30 23:06:50 +09:00
routersys 30ca75f65e MoonSharpに文字列パラメータをobjへ公開 2026-06-30 23:05:00 +09:00
routersys a07916de6b スクリプトコンテキストに文字列パラメータ格納を追加 2026-06-30 23:04:26 +09:00
routersys 467a4b0dd8 文字列パラメータのローカライズ文字列を追加 2026-06-30 23:03:49 +09:00
routersys 03aad4cc6e TextBoxSlider4本のUIと描画パラメータ連携を追加 2026-06-30 19:19:14 +09:00
routersys b638c7b9c2 スクリプト使用検出をobjメンバ汎用方式に再設計しslider検出を追加 2026-06-30 19:18:32 +09:00
routersys ede56971cd GPU/CPUカーネルのuniformにslider0〜3を追加 2026-06-30 19:18:05 +09:00
routersys 94c11dffcb ネイティブLuaJITにslider0〜3を伝達 2026-06-30 19:17:21 +09:00
routersys 28c1f70fa1 MoonSharpにobj.slider0〜3を公開 2026-06-30 19:16:48 +09:00
routersys 2ecde28980 スクリプトコンテキストにSlider0〜3を追加 2026-06-30 19:16:14 +09:00
routersys 1c2c3915e9 スライダー0〜3のローカライズ文字列を追加 2026-06-30 19:15:41 +09:00
routersys 9f2cab9961 バージョンをv1.9.4へ更新
リリース / build-and-release (workflow_dispatch) Actions がタグ v1.9.4 のコミットから作成しました
2026-06-30 18:00:10 +09:00
routersys e1778c7c73 内蔵ドキュメントのeffect解説を二段階解決に更新 2026-06-30 17:56:50 +09:00
routersys 98426f4ca8 制限事項のeffect解説を二段階解決に更新 2026-06-30 17:56:35 +09:00
routersys 7358e2b0a1 obj関数ページを二段階解決の説明に更新 2026-06-30 17:56:26 +09:00
routersys 1af7b8fc8b READMEのobj.effect解説を二段階解決に更新 2026-06-30 17:56:07 +09:00
routersys 26d7b0c470 obj.effectを二段階解決化し直接解決へ退避 2026-06-30 17:55:57 +09:00
routersys 96400605ba 互換マップの読み込みを例外安全化 2026-06-30 17:55:35 +09:00
routersys 695cb2f04d バージョンをv1.9.3へ更新
リリース / build-and-release (workflow_dispatch) Actions がタグ v1.9.3 のコミットから作成しました
2026-06-30 17:35:38 +09:00
routersys 6b39a4cceb クイックリファレンスのeffect説明を更新 2026-06-30 17:24:59 +09:00
routersys 4b4252855b 制限事項のeffect解説を互換マップ準拠に更新 2026-06-30 17:24:54 +09:00
routersys 0d6c3285e1 指定子ページに互換マップの対象エンジンを追加 2026-06-30 17:24:46 +09:00
routersys 3bcf206a95 obj関数ページに互換マップの解説と一覧を追加 2026-06-30 17:24:12 +09:00
routersys c65bb5b08f READMEにobj.effect互換マップの説明を追加 2026-06-30 17:23:52 +09:00
routersys e5b9b98a27 互換マップの対応エフェクト一覧を全言語ドキュメントに追加 2026-06-30 17:23:43 +09:00
routersys 7906d4c735 互換マップのテストを追加 2026-06-30 14:37:30 +09:00
routersys d879f3c6fa obj.effectの解決を互換マップ駆動へ置換 2026-06-30 14:37:02 +09:00
routersys e7ae3bf290 AviUtl/AviUtl2互換マップを宣言形式で追加 2026-06-30 14:35:22 +09:00
routersys 735fd86bed サイトマップを追加 2026-06-30 12:42:44 +09:00
routersys 813b3d6686 検索機能を全ページ本文検索に作り替えた 2026-06-30 12:31:04 +09:00
routersys ca43e3706b ドキュメントを多ページ構成へ刷新 2026-06-30 12:19:58 +09:00
routersys ef4d7e8024 バージョンをv1.9.2へ更新
リリース / build-and-release (workflow_dispatch) Actions がタグ v1.9.2 のコミットから作成しました
2026-06-30 08:04:38 +09:00
routersys 299da15bb8 マージ 2026-06-30 08:01:26 +09:00
routersys ffba68aeb0 エディタ参照の取得を型ベース探索に変更 2026-06-30 08:00:37 +09:00
routersys 1085294aa0 実行時にエラー診断を報告する処理を追加 2026-06-30 07:56:52 +09:00
routersys cb7e4622e8 エディタにエラーの赤い波線表示を追加 2026-06-30 07:56:50 +09:00
routersys 06e2afa7ed スクリプト変換に行番号マッピングを追加 2026-06-30 07:56:48 +09:00
routersys 3e60c6d77f 診断種別のローカライズ文字列を追加 2026-06-30 07:56:46 +09:00
routersys 594517b436 スクリプト診断を保持する診断サービスを追加 2026-06-30 07:56:44 +09:00
routersys 1d3b924492 Lua診断モデルとエラー解析処理を追加 2026-06-30 07:56:43 +09:00
routersys b6cd4bb43e バージョンをv1.9.1へ更新
リリース / build-and-release (workflow_dispatch) Actions がタグ v1.9.1 のコミットから作成しました
2026-06-29 23:26:21 +09:00
routersys 5c0745e039 補完候補にobj.check0〜3とcolorを登録 2026-06-29 23:14:06 +09:00
routersys c5fd507ab5 checkとcolorの参照自動表示を全言語ドキュメントに追記 2026-06-29 23:12:14 +09:00
routersys dfc39e9e19 check/color参照検出のテストを追加 2026-06-29 23:12:10 +09:00
routersys 48d7969a84 スクリプト参照でcheckとcolorのUIを自動表示 2026-06-29 23:12:08 +09:00
routersys 9eb5a44f2d バージョンをv1.9.0へ更新
リリース / build-and-release (workflow_dispatch) Actions がタグ v1.9.0 のコミットから作成しました
2026-06-29 20:00:12 +09:00
routersys fc2fc6ab77 READMEを三層ルーティングと描画API対応へ更新 2026-06-29 19:59:14 +09:00
routersys bc7fa914a4 実行エンジン指定と自動高速化を全言語ドキュメントに追記 2026-06-29 19:48:19 +09:00
routersys c436f24ee0 マージ 2026-06-29 19:39:51 +09:00
routersysとClaude Opus 4.8 5a192f5a6f ディレクティブ付きカーネルの抽出とルーティング検証を追加
Co-Authored-By: Claude Opus 4.8 <[email protected]>
2026-06-29 19:31:53 +09:00
routersysとClaude Opus 4.8 a032f0728f カーネル検出による三層ルーティングとフォールバックを統合
Co-Authored-By: Claude Opus 4.8 <[email protected]>
2026-06-29 19:13:03 +09:00
routersysとClaude Opus 4.8 548432f3a9 Direct2Dピクセルシェーダで動くGPUカーネル実行時を追加
Co-Authored-By: Claude Opus 4.8 <[email protected]>
2026-06-29 19:12:53 +09:00
routersysとClaude Opus 4.8 3bd1e5384e HLSL生成器の構造検証テストを追加
Co-Authored-By: Claude Opus 4.8 <[email protected]>
2026-06-29 19:00:55 +09:00
routersysとClaude Opus 4.8 738da05e59 カーネルIRからHLSLピクセルシェーダを生成する出力器を追加
Co-Authored-By: Claude Opus 4.8 <[email protected]>
2026-06-29 19:00:47 +09:00
routersysとClaude Opus 4.8 d457b65f44 CPUカーネルとMoonSharpの等価性テストを追加
Co-Authored-By: Claude Opus 4.8 <[email protected]>
2026-06-29 18:56:43 +09:00
routersysとClaude Opus 4.8 270cf025ff カーネルIRを式ツリーへコンパイルするCPUレーンを追加
Co-Authored-By: Claude Opus 4.8 <[email protected]>
2026-06-29 18:56:39 +09:00
routersysとClaude Opus 4.8 c657892b7b ピクセル写像カーネルのIRと抽出器を追加
Co-Authored-By: Claude Opus 4.8 <[email protected]>
2026-06-29 18:51:43 +09:00
routersysとClaude Opus 4.8 87cdd4ed90 カーネル構文解析器とASTを追加
Co-Authored-By: Claude Opus 4.8 <[email protected]>
2026-06-29 18:44:51 +09:00
routersysとClaude Opus 4.8 5c1c1272db カーネル部分集合のLua字句解析器を追加
Co-Authored-By: Claude Opus 4.8 <[email protected]>
2026-06-29 18:44:43 +09:00
routersys bcac943775 バージョンをv1.8.0へ更新
リリース / build-and-release (workflow_dispatch) Actions がタグ v1.8.0 のコミットから作成しました
2026-06-29 18:21:46 +09:00
routersys 3d0ff687e2 drawpolyの座標12個+不透明度形式を全ドキュメントに追記 2026-06-29 17:32:06 +09:00
routersys ce0da92ac8 マージ 2026-06-29 17:25:40 +09:00
routersys 7dbe063ac8 ドキュメントアラビア語をAviUtl互換実装へ更新 2026-06-29 14:52:55 +09:00
routersys 1acaef291c ドキュメントインドネシア語をAviUtl互換実装へ更新 2026-06-29 14:51:18 +09:00
routersys 26c96b302f ドキュメントスペイン語をAviUtl互換実装へ更新 2026-06-29 14:49:51 +09:00
routersys c4011d8eef ドキュメント韓国語をAviUtl互換実装へ更新 2026-06-29 14:48:19 +09:00
routersys 451b017f6f ドキュメント繁体字中国語をAviUtl互換実装へ更新 2026-06-29 14:46:57 +09:00
routersys d6b6e440bf ドキュメント簡体字中国語をAviUtl互換実装へ更新 2026-06-29 14:45:37 +09:00
routersys 7601b77902 ドキュメント英語をAviUtl互換実装へ更新 2026-06-29 14:44:24 +09:00
routersys 0799785cad ドキュメント日本語をAviUtl互換実装へ更新 2026-06-29 14:43:02 +09:00
routersys d607e4ec49 ヘッダー検証付きobj.load(movie)を両エンジンで実装 2026-06-29 14:38:32 +09:00
routersys c7e5b91509 マージ 2026-06-29 10:26:56 +09:00
routersys cf23d184fe ヘッダー検証付きobj.load(image)を両エンジンで実装 2026-06-29 10:08:59 +09:00
routersys d2b518f611 obj.load(text)とsetfontをネイティブエンジンへ対応 2026-06-29 10:01:06 +09:00
routersys c186a6b27d obj.load(text)とsetfontを従来エンジンで実装 2026-06-29 09:55:12 +09:00
routersys 5f411e89ec オプションAPIと描画補間反映を両エンジンで実装 2026-06-29 08:41:21 +09:00
routersys 16ed6336c3 obj.getvalueで現在のobj値取得を両エンジンで実装 2026-06-29 08:34:50 +09:00
routersys 6d2a5cbe24 obj.copybufferのバッファ保存復元を両エンジンで実装 2026-06-29 08:31:53 +09:00
routersys 94f7ad4f50 obj.drawpolyのアフィン四角形描画を両エンジンで実装 2026-06-29 08:26:00 +09:00
routersys 3ba77aab18 obj.drawをネイティブエンジンへ対応 2026-06-29 08:16:51 +09:00
routersys 90fe288f66 obj.drawの蓄積描画合成を従来エンジンで実装 2026-06-29 08:11:26 +09:00
routersys 6b2b5d879f Create CNAME 2026-06-29 07:26:46 +09:00
routersys d01d5d6df5 Delete CNAME 2026-06-29 07:26:40 +09:00
routersys a093c458a2 バージョンをv1.7.1へ更新
リリース / build-and-release (workflow_dispatch) Actions がタグ v1.7.1 のコミットから作成しました
2026-06-28 22:47:30 +09:00
routersys 0e65bf1883 ネイティブ環境でのobj.load及びobj.effect対応 2026-06-28 22:39:09 +09:00
routersys d8f728b3f9 Direct2Dピクセル管理の責務分離 2026-06-28 16:17:19 +09:00
routersys 244e75a238 Transform書き戻し処理の共通化 2026-06-28 16:16:54 +09:00
routersys 75cc4bd62e トークン解析処理の共通化と抽出 2026-06-28 16:16:35 +09:00
routersys 6385dbeb6d ScriptDirectiveクラスの抽出分離 2026-06-28 16:16:02 +09:00
routersys bc395a0181 SceneObjectQueryを個別ファイルへ分離 2026-06-28 16:15:37 +09:00
routersys a0dec019fe 例外クラス群を個別ファイルへ分離 2026-06-28 16:15:02 +09:00
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
130個のファイルの変更、16112行の追加、1013行の削除

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

+47 -40
ファイルの表示
@@ -1,54 +1,61 @@
# v1.2.0 - Lua スクリプト for YMM4 # v1.10.0 - Lua スクリプト for YMM4
他オブジェクトの情報を任意のフレーム時点で取得できるようにしたリリースです。 エフェクトパネルへ新しいパラメータ入力欄を追加したリリースです。整数スライダー 4 本と、
発射元が動いても弾の発射位置を固定するなど、フレームを指定した参照が可能になりました。 テキスト・フォント・フォルダ・ファイルの文字列入力をスクリプトから参照できるようにしました。
文字列パラメータは MoonSharp とネイティブの両エンジンで同じ名前から参照でき、ネイティブでは
共有メモリの文字列領域を必要量に応じて拡張・縮小します。あわせて毎フレームのアロケーションを
見直し、補完候補を拡充しました。
--- ---
## 新機能 ## 新機能・機能改善
### 1. obj.getobject へのフレーム指定引数の追加 ### 1. 整数スライダー obj.slider0〜3
`obj.getobject(tag, frame)` の第2引数 `frame` を追加しました。指定したタイムライン 数値スライダーを 4 本追加しました。各値は `obj.slider0`〜`obj.slider3` として参照できます。
フレーム時点での対象オブジェクトの座標・回転・拡大率・不透明度を取得できます。
`frame` を省略した場合は従来どおり現在フレームの値を返します。
弾の発射フレーム(弾アイテムの開始フレーム)は `timelineframe - frame` で求まるため、 - 値は整数で、小数は扱いません。表示範囲は `obj.slider0` が 1〜10、`obj.slider1` が 0〜100、
そのフレームの発射元座標を取得すれば、発射元が動いても弾の原点を発射位置に固定できます。 `obj.slider2` が 0〜1000、`obj.slider3` が -1000〜1000 です。
- 状態の切り替えなど、補間を伴わない整数値の受け渡しに使えます。
- MoonSharp・ネイティブ・CPU/GPU カーネルのいずれのレーンからも参照できます。
```lua ### 2. 文字列パラメータ obj.text / obj.font / obj.dir / obj.file_*
local fire = timelineframe - frame
local src = obj.getobject("routersys", fire)
if src then
obj.x = src.x
obj.y = src.y
end
```
取得値は対象アイテム自身の座標・回転・拡大率であり、グループ制御・カメラ制御による テキスト・フォント・フォルダ・ファイルの入力欄を追加しました。
変形は含みません。同じタグのアイテムが複数ある場合は、対象フレームで表示中のものを
優先して返します。 - `obj.text` はテキスト入力欄の文字列、`obj.font` はフォント名、`obj.dir` はフォルダのパスです。
- ファイル選択は種類ごとに `obj.file_video` / `obj.file_audio` / `obj.file_image` /
`obj.file_project` / `obj.file_mp4` / `obj.file_exo` / `obj.file_subtitle` /
`obj.file_shader` で参照し、選択したファイルのパスを取得します。
- 取得したパスは `obj.load` へ渡して画像・動画の読み込みに使えます。
- MoonSharp とネイティブの両エンジンで同じ名前から参照できます。
### 3. 補完候補の拡充
スクリプトエディタの補完候補へ `obj.slider0`〜`obj.slider3` と、追加した文字列パラメータの
各名前を加えました。
---
## 互換性・後方互換
- スライダーと文字列パラメータは、スクリプト本体でそれらを参照したときだけエフェクトパネルへ
表示されます。参照しない既存スクリプトの表示と挙動は変わりません。
- CPU/GPU カーネルは数値計算に特化するため、文字列パラメータは扱いません。文字列を参照する
スクリプトは MoonSharp かネイティブで実行してください。
- トラックバー・チェックボックス・カラー・AviUtl 互換ヘッダの既存挙動は変わりません。
--- ---
## 内部実装 ## 内部実装
### 2. 参照方式の統一(依存クエリの再評価) - ネイティブの共有メモリへ文字列パラメータ領域を追加し、容量をワーカーの起動引数にしました。
必要量が容量を超えると 2 倍へ拡張し、容量の半分以下に収まると縮小します。最小は 64KB で、
他オブジェクトの値を「現在フレームで事前に算出したスナップショット」を比較する方式から、 容量の変化はワーカーの再生成のみで完結します。
「参照したオブジェクトを保持し、要求されたフレームで評価する」方式へ統一しました。 - 文字列パラメータの変更検出をバージョン方式へ変更し、フレームごとの署名文字列の生成を
やめました。値の参照が変わったときだけ版数を進めます。
- 取得対象のアイテムを保持し、任意のフレームで評価する `SceneObjectResolver` を追加 - ネイティブの文字列書き込みで、名前のバイト列をキャッシュし、値のエンコード先バッファを
- スクリプト実行中に行われた参照 `(タグ, フレーム)` を記録し、出力キャッシュの 再利用します。
再利用判定では記録した参照を再評価して一致を確認 - スライダーの値は MoonSharp の obj テーブル・ネイティブのフィールド・CPU/GPU カーネルの
ユニフォームへ配線しました。スクリプトの使用検出は obj メンバを汎用的に走査する方式へ
これにより、任意フレームの参照に対しても決定論的かつキャッシュ整合性を保った 再設計しました。
取得が可能になります。評価はすべて描画スレッド側で行い、スクリプト実行スレッドへは
数値のみを渡します。
---
## ドキュメント
対応する 8 言語のスクリプト説明文に `frame` 引数の説明と発射位置を固定する例を
追記し、サンプル集ページにも同様の例を追加しました。
+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.
+4 -2
ファイルの表示
@@ -1,5 +1,5 @@
======================================== ========================================
Luaスクリプト for YMM4 v1.2.0 Luaスクリプト for YMM4 v1.10.0
======================================== ========================================
YukkuriMovieMaker4(YMM4)上で動作する、Luaスクリプトで映像エフェクトのパラメータや YukkuriMovieMaker4(YMM4)上で動作する、Luaスクリプトで映像エフェクトのパラメータや
ピクセルを直接制御できるプラグインです。 ピクセルを直接制御できるプラグインです。
@@ -26,7 +26,9 @@ obj.x/y/zoom/alpha等の値はキーフレームアニメーションと連動
- スクリプトエラー時の挙動: コンパイルエラーまたは実行時エラーが発生した場合、 - スクリプトエラー時の挙動: コンパイルエラーまたは実行時エラーが発生した場合、
そのフレームでの座標・透明度・回転・ピクセルの変更は適用されず、入力された そのフレームでの座標・透明度・回転・ピクセルの変更は適用されず、入力された
元の状態がそのまま出力されます。エラー内容はログへ出力されます。 元の状態がそのまま出力されます。エラー内容はログへ出力されるほか、スクリプト
エディタの該当箇所へ赤い波線が表示され、ポイントするとエラー内容をツールチップ
で確認できます。
- ファイルアクセスの制限: スクリプトからのファイル読み込みは許可されておらず、 - ファイルアクセスの制限: スクリプトからのファイル読み込みは許可されておらず、
io・os等のモジュールも有効化されていません。 io・os等のモジュールも有効化されていません。
+7
ファイルの表示
@@ -69,9 +69,15 @@ jobs:
$pkgName = "LuaScript_$version.ymme" $pkgName = "LuaScript_$version.ymme"
New-Item -ItemType Directory -Path "$stageRoot/docs" -Force | Out-Null 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/LuaScript.dll" "$stageRoot/"
Copy-Item "$outDir/MoonSharp.Interpreter.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")) { foreach ($lang in @("ar-sa", "en-us", "es-es", "id-id", "ko-kr", "zh-cn", "zh-tw")) {
$src = "$outDir/$lang" $src = "$outDir/$lang"
@@ -82,6 +88,7 @@ jobs:
} }
Copy-Item "LuaScript/docs/LuaScript.*.txt" "$stageRoot/docs/" Copy-Item "LuaScript/docs/LuaScript.*.txt" "$stageRoot/docs/"
Copy-Item ".github/LICENSE/*.txt" "$stageRoot/LICENSE/"
Copy-Item ".github/Plugin_Readme.txt" "$stageRoot/Readme.txt" Copy-Item ".github/Plugin_Readme.txt" "$stageRoot/Readme.txt"
Compress-Archive -Path "stage/*" -DestinationPath $pkgName -CompressionLevel Optimal 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);
}
}
}
}
+64
ファイルの表示
@@ -0,0 +1,64 @@
using LuaScript.Compat;
namespace LuaScript.Tests
{
public class AviUtlCompatMapTests
{
[Fact]
public void Resolve_KnownEffect_ReturnsTargetType()
{
Assert.True(AviUtlCompatMap.Default.TryResolve("ぼかし", AviUtlEngine.AviUtl, out var mapping));
Assert.Equal("GaussianBlurEffect", mapping.TargetType);
}
[Fact]
public void Resolve_ParameterTransform_IsInverseOfExoExport()
{
AviUtlCompatMap.Default.TryResolve("ぼかし", AviUtlEngine.AviUtl, out var mapping);
Assert.True(mapping.TryGetParameter("範囲", out var parameter));
Assert.Equal("Blur", parameter.Property);
Assert.Equal(5d, parameter.Transform(10d));
}
[Fact]
public void Resolve_AngleParameter_IsIdentity()
{
AviUtlCompatMap.Default.TryResolve("方向ブラー", AviUtlEngine.AviUtl, out var mapping);
Assert.True(mapping.TryGetParameter("角度", out var parameter));
Assert.Equal(45d, parameter.Transform(45d));
}
[Fact]
public void Resolve_BothEngine_MatchesAviUtl2()
{
Assert.True(AviUtlCompatMap.Default.TryResolve("クロマキー", AviUtlEngine.AviUtl2, out var mapping));
Assert.Equal("ChromaKeyEffect", mapping.TargetType);
}
[Fact]
public void Resolve_UndeclaredEffect_DoesNotResolve()
{
Assert.False(AviUtlCompatMap.Default.TryResolve("存在しないエフェクト", AviUtlEngine.AviUtl, out _));
}
[Fact]
public void ResolveTarget_DefaultsToAviUtl()
{
Assert.Equal(AviUtlEngine.AviUtl, AviUtlCompatMap.ResolveTarget("obj.effect(\"ぼかし\", \"範囲\", 10)"));
}
[Fact]
public void ResolveTarget_DirectiveSelectsAviUtl2()
{
Assert.Equal(AviUtlEngine.AviUtl2, AviUtlCompatMap.ResolveTarget("--!aviutl2\nobj.effect(\"ぼかし\", \"範囲\", 10)"));
}
[Fact]
public void Engine_BothIncludesEveryTarget()
{
Assert.True(AviUtlEngine.Both.Includes(AviUtlEngine.AviUtl));
Assert.True(AviUtlEngine.Both.Includes(AviUtlEngine.AviUtl2));
Assert.False(AviUtlEngine.AviUtl.Includes(AviUtlEngine.AviUtl2));
}
}
}
+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})"));
}
}
}
+63
ファイルの表示
@@ -0,0 +1,63 @@
using System.Numerics;
using LuaScript;
namespace LuaScript.Tests
{
public class DrawPolyMathTests
{
private static double[] Quad(
double x0, double y0, double x1, double y1,
double x2, double y2, double x3, double y3,
double u0, double v0, double u1, double v1,
double u2, double v2, double u3, double v3,
double alpha)
=> [x0, y0, 0, x1, y1, 0, x2, y2, 0, x3, y3, 0, u0, v0, u1, v1, u2, v2, u3, v3, alpha];
[Fact]
public void TrySolveAffine_MapsUvCornersToQuad()
{
var poly = Quad(
10, 20, 18, 20, 18, 32, 10, 32,
0, 0, 4, 0, 4, 4, 0, 4, 1);
Assert.True(DrawPolyMath.TrySolveAffine(poly, out var m));
AssertMaps(m, 0, 0, 10, 20);
AssertMaps(m, 4, 0, 18, 20);
AssertMaps(m, 4, 4, 18, 32);
AssertMaps(m, 0, 4, 10, 32);
AssertMaps(m, 2, 2, 14, 26);
}
[Fact]
public void TrySolveAffine_HandlesRotatedQuad()
{
var poly = Quad(
0, 0, 0, 10, -10, 10, -10, 0,
0, 0, 10, 0, 10, 10, 0, 10, 1);
Assert.True(DrawPolyMath.TrySolveAffine(poly, out var m));
AssertMaps(m, 0, 0, 0, 0);
AssertMaps(m, 10, 0, 0, 10);
AssertMaps(m, 0, 10, -10, 0);
}
[Fact]
public void TrySolveAffine_ReturnsFalse_OnDegenerateUv()
{
var poly = Quad(
0, 0, 10, 0, 10, 10, 0, 10,
0, 0, 0, 0, 0, 0, 0, 0, 1);
Assert.False(DrawPolyMath.TrySolveAffine(poly, out _));
}
private static void AssertMaps(Matrix3x2 m, float u, float v, float x, float y)
{
var p = Vector2.Transform(new Vector2(u, v), m);
Assert.Equal(x, p.X, 3);
Assert.Equal(y, p.Y, 3);
}
}
}
+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);
}
}
}
+172
ファイルの表示
@@ -0,0 +1,172 @@
using System;
using System.Collections.Generic;
using LuaScript.Engine;
using LuaScript.Engine.Kernel;
using MoonSharp.Interpreter;
namespace LuaScript.Tests
{
public sealed class KernelCpuEquivalenceTests
{
private const int Width = 23;
private const int Height = 17;
[Theory]
[InlineData("for y=0,obj.h-1 do for x=0,obj.w-1 do local r,g,b,a=obj.getpixel(x,y) obj.setpixel(x,y,r,g,b,a) end end")]
[InlineData("for y=0,obj.h-1 do for x=0,obj.w-1 do local r,g,b,a=obj.getpixel(x,y) local l=0.298912*r+0.586611*g+0.114478*b obj.setpixel(x,y,l,l,l,a) end end")]
[InlineData("for y=0,obj.h-1 do for x=0,obj.w-1 do local r,g,b,a=obj.getpixel(x,y) obj.setpixel(x,y,b,g,r,a) end end")]
[InlineData("for x=0,obj.w-1 do for y=0,obj.h-1 do local r,g,b,a=obj.getpixel(x,y) obj.setpixel(x,y,255-r,255-g,255-b,a) end end")]
[InlineData("for y=0,obj.h-1 do for x=0,obj.w-1 do local r,g,b,a=obj.getpixel(x,y) obj.setpixel(x,y,r*r/255,g*g/255,b*b/255,a) end end")]
[InlineData("for y=0,obj.h-1 do for x=0,obj.w-1 do local r,g,b,a=obj.getpixel(x,y) obj.setpixel(x,y,255*math.pow(r/255,0.45),255*math.pow(g/255,0.45),255*math.pow(b/255,0.45),a) end end")]
[InlineData("for y=0,obj.h-1 do for x=0,obj.w-1 do local r,g,b,a=obj.getpixel(x,y) local v=(r+g+b)/3 obj.setpixel(x,y,v>128 and 255 or 0,v>128 and 255 or 0,v>128 and 255 or 0,a) end end")]
[InlineData("for y=0,obj.h-1 do for x=0,obj.w-1 do local r,g,b,a=obj.getpixel(x,y) obj.setpixel(x,y,math.min(255,r+50),math.max(0,g-50),math.floor(b/16)*16,a) end end")]
[InlineData("for y=0,obj.h-1 do for x=0,obj.w-1 do local r,g,b,a=obj.getpixel(x,y) obj.setpixel(x,y,r%64,math.abs(g-128),math.sqrt(b*255),a) end end")]
public void CpuKernelMatchesMoonSharp(string script)
{
var fields = new Dictionary<string, double> { ["w"] = Width, ["h"] = Height };
AssertEquivalent(script, fields, new Dictionary<string, double>());
}
[Fact]
public void CpuKernelMatchesMoonSharpWithUniforms()
{
const string script =
"for y=0,obj.h-1 do for x=0,obj.w-1 do local r,g,b,a=obj.getpixel(x,y) " +
"obj.setpixel(x,y,r*obj.track0/100,g*math.sin(time)*0.5+g*0.5,b+x/obj.w*obj.track1,a) end end";
var fields = new Dictionary<string, double> { ["w"] = Width, ["h"] = Height, ["track0"] = 73d, ["track1"] = 40d };
var globals = new Dictionary<string, double> { ["time"] = 1.2345d };
AssertEquivalent(script, fields, globals);
}
[Theory]
[InlineData("--!cpu\nfor y=0,obj.h-1 do for x=0,obj.w-1 do local r,g,b,a=obj.getpixel(x,y) obj.setpixel(x,y,255-r,255-g,255-b,a) end end")]
[InlineData("--!gpu\nfor y=0,obj.h-1 do for x=0,obj.w-1 do local r,g,b,a=obj.getpixel(x,y) local l=0.298912*r+0.586611*g+0.114478*b obj.setpixel(x,y,l,l,l,a) end end")]
[InlineData("--!cpu\r\nfor y=0,obj.h-1 do for x=0,obj.w-1 do local r,g,b,a=obj.getpixel(x,y) obj.setpixel(x,y,x/obj.w*255,y/obj.h*255,b,a) end end")]
public void DirectivePrefixedKernelsMatchMoonSharp(string script)
{
var fields = new Dictionary<string, double> { ["w"] = Width, ["h"] = Height };
AssertEquivalent(script, fields, new Dictionary<string, double>());
}
[Theory]
[InlineData("--!cpu", "Cpu")]
[InlineData("--!gpu", "Gpu")]
public void DirectivePrefixedKernelsRouteToAcceleratedLane(string directive, string expected)
{
string script = directive + "\nfor y=0,obj.h-1 do for x=0,obj.w-1 do local r,g,b,a=obj.getpixel(x,y) obj.setpixel(x,y,r,g,b,a) end end";
Assert.True(ScriptDirective.TryResolveExplicit(script, out var kind));
Assert.Equal(expected, kind.ToString());
Assert.NotNull(KernelExtractor.TryExtract(script));
}
[Theory]
[InlineData("obj.setpixel(0,0,0,0,0,0)")]
[InlineData("for y=0,obj.h-1 do for x=0,obj.w-1 do local r,g,b,a=obj.getpixel(x,y) total=total+r obj.setpixel(x,y,r,g,b,a) end end")]
[InlineData("for y=0,obj.h-1 do for x=0,obj.w-1 do local r,g,b,a=obj.getpixel(x+1,y) obj.setpixel(x,y,r,g,b,a) end end")]
[InlineData("for i=0,10 do end")]
[InlineData("for y=0,obj.h-1 do for x=0,obj.w-1 do local r,g,b,a=obj.getpixel(x,y) if r>128 then r=255 end obj.setpixel(x,y,r,g,b,a) end end")]
[InlineData("for y=0,obj.h-1 do for x=0,obj.w-1 do local r,g,b,a=obj.getpixel(x,y) obj.setpixel(x,y,obj.rand(0,255),g,b,a) end end")]
public void NonKernelScriptsAreRejected(string script)
{
Assert.Null(KernelExtractor.TryExtract(script));
}
private static void AssertEquivalent(string script, Dictionary<string, double> fields, Dictionary<string, double> globals)
{
var program = KernelExtractor.TryExtract(script);
Assert.NotNull(program);
byte[] source = CreateBuffer(20260629);
byte[] oracle = (byte[])source.Clone();
byte[] candidate = (byte[])source.Clone();
RunMoonSharp(script, oracle, fields, globals);
double[] uniforms = new double[KernelUniforms.Count];
foreach (var (name, value) in fields)
if (KernelUniforms.TryResolveMember("obj", name, out var uniform))
uniforms[(int)uniform] = value;
foreach (var (name, value) in globals)
if (KernelUniforms.TryResolveGlobal(name, out var uniform))
uniforms[(int)uniform] = value;
CpuKernelCompiler.Compile(program!).Execute(candidate, Width, Height, uniforms);
Assert.Equal(oracle, candidate);
}
private static byte[] CreateBuffer(int seed)
{
var random = new Random(seed);
var buffer = new byte[Width * Height * 4];
random.NextBytes(buffer);
return buffer;
}
private static void RunMoonSharp(string script, byte[] buffer, Dictionary<string, double> fields, Dictionary<string, double> globals)
{
var engine = new Script(CoreModules.Basic | CoreModules.Math | CoreModules.Bit32);
var obj = new Table(engine);
foreach (var (name, value) in fields)
obj[name] = value;
foreach (var (name, value) in globals)
engine.Globals[name] = value;
obj["getpixel"] = DynValue.NewCallback((_, args) =>
{
int x = (int)(args[0].CastToNumber() ?? 0d);
int y = (int)(args[1].CastToNumber() ?? 0d);
var (r, g, b, a) = GetPixel(buffer, x, y);
return DynValue.NewTuple(
DynValue.NewNumber(r), DynValue.NewNumber(g), DynValue.NewNumber(b), DynValue.NewNumber(a));
});
obj["setpixel"] = DynValue.NewCallback((_, args) =>
{
int x = (int)(args[0].CastToNumber() ?? 0d);
int y = (int)(args[1].CastToNumber() ?? 0d);
double r = args[2].CastToNumber() ?? 0d;
double g = args[3].CastToNumber() ?? 0d;
double b = args[4].CastToNumber() ?? 0d;
double a = args.Count > 5 ? args[5].CastToNumber() ?? 255d : 255d;
SetPixel(buffer, x, y, r, g, b, a);
return DynValue.Void;
});
engine.Globals["obj"] = obj;
engine.DoString(script);
}
private static (double r, double g, double b, double a) GetPixel(byte[] buffer, int x, int y)
{
if ((uint)x >= Width || (uint)y >= Height)
return (0d, 0d, 0d, 0d);
int p = (y * Width + x) * 4;
double alpha = buffer[p + 3];
if (alpha <= 0d)
return (0d, 0d, 0d, 0d);
double scale = 255d / alpha;
return (
Math.Clamp(buffer[p + 2] * scale, 0d, 255d),
Math.Clamp(buffer[p + 1] * scale, 0d, 255d),
Math.Clamp(buffer[p] * scale, 0d, 255d),
alpha);
}
private static void SetPixel(byte[] buffer, int x, int y, double r, double g, double b, double a)
{
if ((uint)x >= Width || (uint)y >= Height)
return;
int p = (y * Width + x) * 4;
double k = Math.Clamp(a, 0d, 255d) / 255d;
buffer[p] = (byte)Math.Clamp(b * k, 0d, 255d);
buffer[p + 1] = (byte)Math.Clamp(g * k, 0d, 255d);
buffer[p + 2] = (byte)Math.Clamp(r * k, 0d, 255d);
buffer[p + 3] = (byte)Math.Clamp(a, 0d, 255d);
}
}
}
+64
ファイルの表示
@@ -0,0 +1,64 @@
using LuaScript.Engine.Kernel;
namespace LuaScript.Tests
{
public sealed class KernelHlslEmitterTests
{
private const string Grayscale =
"for y=0,obj.h-1 do for x=0,obj.w-1 do local r,g,b,a=obj.getpixel(x,y) " +
"local l=0.298912*r+0.586611*g+0.114478*b obj.setpixel(x,y,l,l,l,a) end end";
private const string Threshold =
"for y=0,obj.h-1 do for x=0,obj.w-1 do local r,g,b,a=obj.getpixel(x,y) " +
"obj.setpixel(x,y,r>128 and 255 or 0,g,b,a) end end";
private const string WithTrack =
"for y=0,obj.h-1 do for x=0,obj.w-1 do local r,g,b,a=obj.getpixel(x,y) " +
"obj.setpixel(x,y,r*obj.track0/100,g,b,a) end end";
[Fact]
public void EmitsValidShaderSkeleton()
{
string hlsl = HlslKernelEmitter.Emit(Extract(Grayscale));
Assert.Contains("Texture2D InputTexture : register(t0);", hlsl);
Assert.Contains("cbuffer constants : register(b0)", hlsl);
Assert.Contains("float4 main(float4 pos : SV_POSITION", hlsl);
Assert.Contains("InputTexture.Sample(InputSampler, uv.xy)", hlsl);
Assert.Contains("return float4(oR, oG, oB, oA);", hlsl);
Assert.Contains("inR", hlsl);
Assert.Contains("inG", hlsl);
Assert.Contains("inB", hlsl);
}
[Fact]
public void ThresholdEmitsTernary()
{
string hlsl = HlslKernelEmitter.Emit(Extract(Threshold));
Assert.Contains(" ? (", hlsl);
Assert.Contains(" > ", hlsl);
}
[Fact]
public void UniformReferencesUsePackedConstantBuffer()
{
string hlsl = HlslKernelEmitter.Emit(Extract(WithTrack));
int index = (int)KernelUniform.Track0;
Assert.Contains($"uniforms[{index / 4}].{"xyzw"[index % 4]}", hlsl);
}
[Fact]
public void EmissionIsDeterministic()
{
var program = Extract(Grayscale);
Assert.Equal(HlslKernelEmitter.Emit(program), HlslKernelEmitter.Emit(program));
}
private static KernelProgram Extract(string script)
{
var program = KernelExtractor.TryExtract(script);
Assert.NotNull(program);
return program!;
}
}
}
+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);
}
}
}
}
+62
ファイルの表示
@@ -0,0 +1,62 @@
<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\ScriptDirective.cs" Link="Linked\ScriptDirective.cs" />
<Compile Include="..\LuaScript\Engine\NativeProtocol.cs" Link="Linked\NativeProtocol.cs" />
<Compile Include="..\LuaScript\Engine\ProcessJobObject.cs" Link="Linked\ProcessJobObject.cs" />
<Compile Include="..\LuaScript\Engine\LuaJitWorker.cs" Link="Linked\LuaJitWorker.cs" />
<Compile Include="..\LuaScript\DrawCommand.cs" Link="Linked\DrawCommand.cs" />
<Compile Include="..\LuaScript\DrawPolyMath.cs" Link="Linked\DrawPolyMath.cs" />
<Compile Include="..\LuaScript\SceneObjectInfo.cs" Link="Linked\SceneObjectInfo.cs" />
<Compile Include="..\LuaScript\SceneObjectQuery.cs" Link="Linked\SceneObjectQuery.cs" />
<Compile Include="..\LuaScript\AnimTableRegistrar.cs" Link="Linked\AnimTableRegistrar.cs" />
<Compile Include="..\LuaScript\Compat\AviUtlScript.cs" Link="Linked\AviUtlScript.cs" />
<Compile Include="..\LuaScript\Compat\ScriptParserHelper.cs" Link="Linked\ScriptParserHelper.cs" />
<Compile Include="..\LuaScript\Compat\AviUtlParameterLayout.cs" Link="Linked\AviUtlParameterLayout.cs" />
<Compile Include="..\LuaScript\Compat\ScriptParameterUsage.cs" Link="Linked\ScriptParameterUsage.cs" />
<Compile Include="..\LuaScript\Compat\AviUtlRandom.cs" Link="Linked\AviUtlRandom.cs" />
<Compile Include="..\LuaScript\Compat\AviUtlEngine.cs" Link="Linked\AviUtlEngine.cs" />
<Compile Include="..\LuaScript\Compat\AviUtlEffectMapping.cs" Link="Linked\AviUtlEffectMapping.cs" />
<Compile Include="..\LuaScript\Compat\AviUtlCompatMap.cs" Link="Linked\AviUtlCompatMap.cs" />
<EmbeddedResource Include="..\LuaScript\Compat\AviUtlCompatMap.xml" Link="Linked\AviUtlCompatMap.xml" />
<Compile Include="..\LuaScript\Compat\FigureRenderer.cs" Link="Linked\FigureRenderer.cs" />
<Compile Include="..\LuaScript\Engine\Kernel\KernelUnsupportedException.cs" Link="Linked\Kernel\KernelUnsupportedException.cs" />
<Compile Include="..\LuaScript\Engine\Kernel\LuaToken.cs" Link="Linked\Kernel\LuaToken.cs" />
<Compile Include="..\LuaScript\Engine\Kernel\LuaLexer.cs" Link="Linked\Kernel\LuaLexer.cs" />
<Compile Include="..\LuaScript\Engine\Kernel\LuaAst.cs" Link="Linked\Kernel\LuaAst.cs" />
<Compile Include="..\LuaScript\Engine\Kernel\LuaParser.cs" Link="Linked\Kernel\LuaParser.cs" />
<Compile Include="..\LuaScript\Engine\Kernel\KernelUniform.cs" Link="Linked\Kernel\KernelUniform.cs" />
<Compile Include="..\LuaScript\Engine\Kernel\KernelModel.cs" Link="Linked\Kernel\KernelModel.cs" />
<Compile Include="..\LuaScript\Engine\Kernel\KernelExtractor.cs" Link="Linked\Kernel\KernelExtractor.cs" />
<Compile Include="..\LuaScript\Engine\Kernel\CpuKernel.cs" Link="Linked\Kernel\CpuKernel.cs" />
<Compile Include="..\LuaScript\Engine\Kernel\CpuKernelCompiler.cs" Link="Linked\Kernel\CpuKernelCompiler.cs" />
<Compile Include="..\LuaScript\Engine\Kernel\HlslKernelEmitter.cs" Link="Linked\Kernel\HlslKernelEmitter.cs" />
</ItemGroup>
</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);
}
}
}
}
}
+608
ファイルの表示
@@ -0,0 +1,608 @@
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 static readonly Func<string, int, double, double, double, (byte[] buffer, int w, int h)> NoLoadFigure = (_, _, _, _, _) => ([], 1, 1);
private static readonly Func<string, string, double, bool, bool, int, (byte[] buffer, int w, int h)> NoLoadText = (_, _, _, _, _, _) => ([], 1, 1);
private static readonly Func<string, (byte[] buffer, int w, int h)> NoLoadImage = _ => ([], 1, 1);
private static readonly Func<string, double, (byte[] buffer, int w, int h)> NoLoadMovie = (_, _) => ([], 1, 1);
private static readonly Action<string, System.Collections.Generic.IReadOnlyList<System.Collections.Generic.KeyValuePair<string, object>>> NoAddEffect = (_, _) => { };
private static readonly Action<DrawCommand> NoAddDraw = _ => { };
private static readonly System.Collections.Generic.IReadOnlyDictionary<string, string> NoStringParams = new System.Collections.Generic.Dictionary<string, string>();
private readonly LuaJitWorker _worker = new(NativeDir);
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, NoStringParams, pixels, 4, 4, 5000, NoResolver, NoLoadFigure, NoLoadText, NoLoadImage, NoLoadMovie, NoAddEffect, NoAddDraw, out bool dirty, out _, out _, out _, out _, out string? error);
Assert.True(ok, error);
Assert.False(dirty);
Assert.Equal(180d, fields[NativeProtocol.Rz]);
Assert.Equal(128d, fields[NativeProtocol.Alpha]);
}
[Fact]
public void StringParameters_AreExposedOnObj()
{
Assert.True(LuaJitWorker.IsAvailable(NativeDir), "native/luajit.exe must be present");
var fields = Fields(2, 2, 0d);
var pixels = new byte[16];
var stringParameters = new System.Collections.Generic.Dictionary<string, string>
{
["text"] = "hello",
["file_image"] = "C:/サンプル/画像.png",
};
bool ok = _worker.Execute(
"obj.x = string.len(obj.text) obj.alpha = string.len(obj.file_image)",
fields, stringParameters, pixels, 2, 2, 5000, NoResolver, NoLoadFigure, NoLoadText, NoLoadImage, NoLoadMovie, NoAddEffect, NoAddDraw, out _, out _, out _, out _, out _, out string? error);
Assert.True(ok, error);
Assert.Equal(5d, fields[NativeProtocol.X]);
Assert.Equal(System.Text.Encoding.UTF8.GetByteCount("C:/サンプル/画像.png"), fields[NativeProtocol.Alpha]);
}
[Fact]
public void StringParameters_GrowAndShrinkAroundCapacity()
{
Assert.True(LuaJitWorker.IsAvailable(NativeDir), "native/luajit.exe must be present");
var pixels = new byte[16];
string big = new string('x', 100 * 1024);
var large = new System.Collections.Generic.Dictionary<string, string> { ["text"] = big };
var fieldsLarge = Fields(2, 2, 0d);
bool ok = _worker.Execute(
"obj.x = string.len(obj.text)",
fieldsLarge, large, pixels, 2, 2, 5000, NoResolver, NoLoadFigure, NoLoadText, NoLoadImage, NoLoadMovie, NoAddEffect, NoAddDraw, out _, out _, out _, out _, out _, out string? error);
Assert.True(ok, error);
Assert.Equal(big.Length, fieldsLarge[NativeProtocol.X]);
var small = new System.Collections.Generic.Dictionary<string, string> { ["text"] = "ok" };
var fieldsSmall = Fields(2, 2, 0d);
ok = _worker.Execute(
"obj.x = string.len(obj.text)",
fieldsSmall, small, pixels, 2, 2, 5000, NoResolver, NoLoadFigure, NoLoadText, NoLoadImage, NoLoadMovie, NoAddEffect, NoAddDraw, out _, out _, out _, out _, out _, out error);
Assert.True(ok, error);
Assert.Equal(2d, fieldsSmall[NativeProtocol.X]);
}
[Fact]
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, NoStringParams, pixels, w, h, 5000, NoResolver, NoLoadFigure, NoLoadText, NoLoadImage, NoLoadMovie, NoAddEffect, NoAddDraw, out bool dirty, out _, out _, out _, out _, out string? error);
Assert.True(ok, error);
Assert.True(dirty);
Assert.Equal(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, NoStringParams, pixels, w, h, 5000, NoResolver, NoLoadFigure, NoLoadText, NoLoadImage, NoLoadMovie, NoAddEffect, NoAddDraw, out bool dirty, out _, out _, out _, out _, out string? error);
Assert.True(ok, error);
Assert.True(dirty);
Assert.Equal(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, NoStringParams, pixels, 2, 2, 5000, NoResolver, NoLoadFigure, NoLoadText, NoLoadImage, NoLoadMovie, NoAddEffect, NoAddDraw, out _, out _, out _, out _, out _, out string? error);
Assert.True(ok, error);
Assert.Equal(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, NoStringParams, pixels, 2, 2, 1500, NoResolver, NoLoadFigure, NoLoadText, NoLoadImage, NoLoadMovie, NoAddEffect, NoAddDraw, out _, out _, out _, out _, out _, out string? error);
Assert.False(timedOut);
Assert.Contains("timed out", error);
var fields2 = Fields(2, 2, 3d);
bool ok = _worker.Execute("obj.x = obj.time", fields2, NoStringParams, pixels, 2, 2, 5000, NoResolver, NoLoadFigure, NoLoadText, NoLoadImage, NoLoadMovie, NoAddEffect, NoAddDraw, out _, out _, out _, out _, 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, NoStringParams, pixels, 2, 2, 5000, resolver, NoLoadFigure, NoLoadText, NoLoadImage, NoLoadMovie, NoAddEffect, NoAddDraw, out _, out _, out _, out _, out _, out string? error);
Assert.True(ok, error);
Assert.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), NoStringParams, pixels, 2, 2, 5000, resolver, NoLoadFigure, NoLoadText, NoLoadImage, NoLoadMovie, NoAddEffect, NoAddDraw, out _, out _, out _, out _, out _, out string? error);
Assert.True(ok, error);
Assert.Equal(1, calls);
var fields = Fields(2, 2, 0d);
x = 20d;
ok = _worker.Execute(script, fields, NoStringParams, pixels, 2, 2, 5000, resolver, NoLoadFigure, NoLoadText, NoLoadImage, NoLoadMovie, NoAddEffect, NoAddDraw, out _, out _, out _, out _, 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, NoStringParams, pixels, 2, 2, 5000, NoResolver, NoLoadFigure, NoLoadText, NoLoadImage, NoLoadMovie, NoAddEffect, NoAddDraw, out _, out _, out _, out _, out _, out string? error);
Assert.True(ok, error);
Assert.Equal(1d, fields[NativeProtocol.X]);
}
[Fact]
public void Draw_RecordsCommandsThroughCallback()
{
Assert.True(LuaJitWorker.IsAvailable(NativeDir), "native/luajit.exe must be present");
var pixels = new byte[16];
var fields = Fields(2, 2, 0d);
var commands = new System.Collections.Generic.List<DrawCommand>();
Action<DrawCommand> addDraw = commands.Add;
bool ok = _worker.Execute(
"obj.draw() obj.draw(10, 20, 30, 2, 0.5, 0.25)",
fields, NoStringParams, pixels, 2, 2, 5000, NoResolver, NoLoadFigure, NoLoadText, NoLoadImage, NoLoadMovie, NoAddEffect, addDraw,
out _, out _, out _, out _, out _, out string? error);
Assert.True(ok, error);
Assert.Equal(2, commands.Count);
Assert.Equal(new DrawCommand(0d, 0d, 0d, 1d, 1d, 0d), commands[0]);
Assert.Equal(new DrawCommand(10d, 20d, 30d, 2d, 0.5d, 0.25d), commands[1]);
}
[Fact]
public void DrawPoly_RecordsDefaultUvAndAlpha()
{
Assert.True(LuaJitWorker.IsAvailable(NativeDir), "native/luajit.exe must be present");
var pixels = new byte[4 * 4 * 4];
var fields = Fields(4, 4, 0d);
var commands = new System.Collections.Generic.List<DrawCommand>();
Action<DrawCommand> addDraw = commands.Add;
bool ok = _worker.Execute(
"obj.drawpoly(0,0,0, 10,0,0, 10,10,0, 0,10,0)",
fields, NoStringParams, pixels, 4, 4, 5000, NoResolver, NoLoadFigure, NoLoadText, NoLoadImage, NoLoadMovie, NoAddEffect, addDraw,
out _, out _, out _, out _, out _, out string? error);
Assert.True(ok, error);
Assert.Single(commands);
var poly = commands[0].Poly;
Assert.NotNull(poly);
Assert.Equal(new double[] { 0, 0, 0, 10, 0, 0, 10, 10, 0, 0, 10, 0, 0, 0, 4, 0, 4, 4, 0, 4, 1 }, poly);
}
[Fact]
public void DrawPoly_RecordsExplicitUvAndAlpha()
{
Assert.True(LuaJitWorker.IsAvailable(NativeDir), "native/luajit.exe must be present");
var pixels = new byte[4 * 4 * 4];
var fields = Fields(4, 4, 0d);
var commands = new System.Collections.Generic.List<DrawCommand>();
Action<DrawCommand> addDraw = commands.Add;
bool ok = _worker.Execute(
"obj.drawpoly(0,0,0, 8,0,0, 8,8,0, 0,8,0, 1,1, 3,1, 3,3, 1,3, 0.5)",
fields, NoStringParams, pixels, 4, 4, 5000, NoResolver, NoLoadFigure, NoLoadText, NoLoadImage, NoLoadMovie, NoAddEffect, addDraw,
out _, out _, out _, out _, out _, out string? error);
Assert.True(ok, error);
Assert.Single(commands);
var poly = commands[0].Poly;
Assert.NotNull(poly);
Assert.Equal(new double[] { 0, 0, 0, 8, 0, 0, 8, 8, 0, 0, 8, 0, 1, 1, 3, 1, 3, 3, 1, 3, 0.5 }, poly);
Assert.Equal(0.5d, commands[0].Alpha);
}
[Fact]
public void SetOption_GetOption_RoundTrips()
{
Assert.True(LuaJitWorker.IsAvailable(NativeDir), "native/luajit.exe must be present");
var pixels = new byte[16];
var fields = Fields(2, 2, 0d);
bool ok = _worker.Execute(
"obj.setoption('antialias', 0) obj.x = obj.getoption('antialias') obj.y = obj.getoption('unset')",
fields, NoStringParams, pixels, 2, 2, 5000, NoResolver, NoLoadFigure, NoLoadText, NoLoadImage, NoLoadMovie, NoAddEffect, NoAddDraw,
out _, out _, out _, out _, out _, out string? error);
Assert.True(ok, error);
Assert.Equal(0d, fields[NativeProtocol.X]);
Assert.Equal(0d, fields[NativeProtocol.Y]);
}
[Fact]
public void Draw_CarriesAntialiasFromOption()
{
Assert.True(LuaJitWorker.IsAvailable(NativeDir), "native/luajit.exe must be present");
var pixels = new byte[16];
var commands = new System.Collections.Generic.List<DrawCommand>();
Action<DrawCommand> addDraw = commands.Add;
bool ok = _worker.Execute(
"obj.draw() obj.setoption('antialias', 0) obj.draw()",
Fields(2, 2, 0d), NoStringParams, pixels, 2, 2, 5000, NoResolver, NoLoadFigure, NoLoadText, NoLoadImage, NoLoadMovie, NoAddEffect, addDraw,
out _, out _, out _, out _, out _, out string? error);
Assert.True(ok, error);
Assert.Equal(2, commands.Count);
Assert.Equal(1d, commands[0].Antialias);
Assert.Equal(0d, commands[1].Antialias);
}
[Fact]
public void LoadText_RoundTripsThroughCallback()
{
Assert.True(LuaJitWorker.IsAvailable(NativeDir), "native/luajit.exe must be present");
const int tw = 3, th = 2;
var rendered = new byte[tw * th * 4];
for (int i = 0; i < rendered.Length; i++)
rendered[i] = (byte)((i * 17 + 5) & 0xFF);
string? capturedFamily = null;
string? capturedText = null;
double capturedSize = 0;
bool capturedBold = false, capturedItalic = false;
int capturedColor = 0;
Func<string, string, double, bool, bool, int, (byte[], int, int)> loadText =
(family, text, size, bold, italic, color) =>
{
capturedFamily = family; capturedText = text; capturedSize = size;
capturedBold = bold; capturedItalic = italic; capturedColor = color;
return (rendered, tw, th);
};
var pixels = new byte[4 * 4 * 4];
var fields = Fields(4, 4, 0d);
bool ok = _worker.Execute(
"obj.setfont('Meiryo', 40, 3, 0x112233) obj.load('text', 'Hi')",
fields, NoStringParams, pixels, 4, 4, 5000, NoResolver, NoLoadFigure, loadText, NoLoadImage, NoLoadMovie, NoAddEffect, NoAddDraw,
out bool dirty, out bool bufferReplaced, out byte[]? newPixels, out int rw, out int rh, out string? error);
Assert.True(ok, error);
Assert.Equal("Meiryo", capturedFamily);
Assert.Equal("Hi", capturedText);
Assert.Equal(40d, capturedSize);
Assert.True(capturedBold);
Assert.True(capturedItalic);
Assert.Equal(0x112233, capturedColor);
Assert.True(dirty);
Assert.True(bufferReplaced);
Assert.Equal(tw, rw);
Assert.Equal(th, rh);
Assert.NotNull(newPixels);
Assert.Equal(rendered, newPixels!.AsSpan(0, rendered.Length).ToArray());
}
[Fact]
public void LoadImage_RoundTripsThroughCallback()
{
Assert.True(LuaJitWorker.IsAvailable(NativeDir), "native/luajit.exe must be present");
const int iw = 2, ih = 2;
var decoded = new byte[iw * ih * 4];
for (int i = 0; i < decoded.Length; i++)
decoded[i] = (byte)((i * 23 + 9) & 0xFF);
string? capturedPath = null;
Func<string, (byte[], int, int)> loadImage = path =>
{
capturedPath = path;
return (decoded, iw, ih);
};
var pixels = new byte[4 * 4 * 4];
var fields = Fields(4, 4, 0d);
bool ok = _worker.Execute(
"obj.load('image', 'C:/sample.png')",
fields, NoStringParams, pixels, 4, 4, 5000, NoResolver, NoLoadFigure, NoLoadText, loadImage, NoLoadMovie, NoAddEffect, NoAddDraw,
out bool dirty, out bool bufferReplaced, out byte[]? newPixels, out int rw, out int rh, out string? error);
Assert.True(ok, error);
Assert.Equal("C:/sample.png", capturedPath);
Assert.True(dirty);
Assert.True(bufferReplaced);
Assert.Equal(iw, rw);
Assert.Equal(ih, rh);
Assert.NotNull(newPixels);
Assert.Equal(decoded, newPixels!.AsSpan(0, decoded.Length).ToArray());
}
[Fact]
public void LoadMovie_RoundTripsPathAndTime()
{
Assert.True(LuaJitWorker.IsAvailable(NativeDir), "native/luajit.exe must be present");
const int mw = 2, mh = 2;
var frame = new byte[mw * mh * 4];
for (int i = 0; i < frame.Length; i++)
frame[i] = (byte)((i * 31 + 3) & 0xFF);
string? capturedPath = null;
double capturedTime = -1;
Func<string, double, (byte[], int, int)> loadMovie = (path, time) =>
{
capturedPath = path;
capturedTime = time;
return (frame, mw, mh);
};
var pixels = new byte[4 * 4 * 4];
var fields = Fields(4, 4, 0d);
bool ok = _worker.Execute(
"obj.load('movie', 'C:/clip.mp4', 1.5)",
fields, NoStringParams, pixels, 4, 4, 5000, NoResolver, NoLoadFigure, NoLoadText, NoLoadImage, loadMovie, NoAddEffect, NoAddDraw,
out bool dirty, out bool bufferReplaced, out byte[]? newPixels, out int rw, out int rh, out string? error);
Assert.True(ok, error);
Assert.Equal("C:/clip.mp4", capturedPath);
Assert.Equal(1.5d, capturedTime);
Assert.True(dirty);
Assert.True(bufferReplaced);
Assert.Equal(mw, rw);
Assert.Equal(mh, rh);
Assert.NotNull(newPixels);
Assert.Equal(frame, newPixels!.AsSpan(0, frame.Length).ToArray());
}
[Fact]
public void GetValue_ReturnsObjFields()
{
Assert.True(LuaJitWorker.IsAvailable(NativeDir), "native/luajit.exe must be present");
var pixels = new byte[16];
var fields = Fields(2, 2, 0d);
fields[NativeProtocol.Track0] = 42d;
bool ok = _worker.Execute(
"obj.x = obj.getvalue('track0') obj.y = obj.getvalue('alpha') obj.z = obj.getvalue('unknown')",
fields, NoStringParams, pixels, 2, 2, 5000, NoResolver, NoLoadFigure, NoLoadText, NoLoadImage, NoLoadMovie, NoAddEffect, NoAddDraw,
out _, out _, out _, out _, out _, out string? error);
Assert.True(ok, error);
Assert.Equal(42d, fields[NativeProtocol.X]);
Assert.Equal(255d, fields[NativeProtocol.Y]);
Assert.Equal(0d, fields[NativeProtocol.Z]);
}
[Fact]
public void CopyBuffer_TmpSaveRestore_RoundTripsPixels()
{
Assert.True(LuaJitWorker.IsAvailable(NativeDir), "native/luajit.exe must be present");
const int w = 2, h = 2;
var pixels = new byte[w * h * 4];
for (int i = 0; i < pixels.Length; i++)
pixels[i] = (byte)((i * 37 + 11) & 0xFF);
pixels[3] = 255; pixels[7] = 255; pixels[11] = 255; pixels[15] = 255;
var original = (byte[])pixels.Clone();
var fields = Fields(w, h, 0d);
const string script =
"obj.copybuffer('tmp','obj') " +
"for y=0,obj.h-1 do for x=0,obj.w-1 do obj.setpixel(x,y,0,0,0,0) end end " +
"obj.copybuffer('obj','tmp')";
bool ok = _worker.Execute(script, fields, NoStringParams, pixels, w, h, 5000, NoResolver, NoLoadFigure, NoLoadText, NoLoadImage, NoLoadMovie, NoAddEffect, NoAddDraw, out bool dirty, out _, out _, out _, out _, out string? error);
Assert.True(ok, error);
Assert.True(dirty);
Assert.Equal(original, pixels);
}
[Fact]
public void CopyBuffer_CachePersistsAcrossRuns()
{
Assert.True(LuaJitWorker.IsAvailable(NativeDir), "native/luajit.exe must be present");
const int w = 2, h = 2;
var stored = new byte[w * h * 4];
for (int i = 0; i < stored.Length; i++)
stored[i] = (byte)((i * 53 + 7) & 0xFF);
stored[3] = 255; stored[7] = 255; stored[11] = 255; stored[15] = 255;
var save = (byte[])stored.Clone();
bool ok = _worker.Execute("obj.copybuffer('cache:foo','obj')", Fields(w, h, 0d), NoStringParams, save, w, h, 5000, NoResolver, NoLoadFigure, NoLoadText, NoLoadImage, NoLoadMovie, NoAddEffect, NoAddDraw, out _, out _, out _, out _, out _, out string? error);
Assert.True(ok, error);
var blank = new byte[w * h * 4];
ok = _worker.Execute("obj.copybuffer('obj','cache:foo')", Fields(w, h, 0d), NoStringParams, blank, w, h, 5000, NoResolver, NoLoadFigure, NoLoadText, NoLoadImage, NoLoadMovie, NoAddEffect, NoAddDraw, out bool dirty, out _, out _, out _, out _, out error);
Assert.True(ok, error);
Assert.True(dirty);
Assert.Equal(stored, blank);
}
[Fact]
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, NoStringParams, pixels, 2, 2, 5000, NoResolver, NoLoadFigure, NoLoadText, NoLoadImage, NoLoadMovie, NoAddEffect, NoAddDraw, out _, out _, out _, out _, out _, out string? error);
Assert.False(ok);
Assert.False(string.IsNullOrEmpty(error));
var fields2 = Fields(2, 2, 7d);
bool ok2 = _worker.Execute("obj.x = obj.time", fields2, NoStringParams, pixels, 2, 2, 5000, NoResolver, NoLoadFigure, NoLoadText, NoLoadImage, NoLoadMovie, NoAddEffect, NoAddDraw, out _, out _, out _, out _, 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)"));
}
}
}
+50
ファイルの表示
@@ -0,0 +1,50 @@
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)", "Native")]
[InlineData("obj.draw()", "MoonSharp")]
[InlineData("obj.draw()\nlocal r = obj.getpixel(0,0)", "Native")]
[InlineData("--!native\nobj.load(\"figure\", \"円\", 0xff0000, 100)", "Native")]
public void ResolveAuto_RoutesPixelScriptsToNative(string script, string expected)
{
Assert.Equal(expected, ScriptDirective.ResolveAuto(script).ToString());
}
}
}
+68
ファイルの表示
@@ -0,0 +1,68 @@
using LuaScript.Compat;
namespace LuaScript.Tests
{
public sealed class ScriptParameterUsageTests
{
[Theory]
[InlineData("if obj.check0 then obj.alpha = 0 end", 0)]
[InlineData("local v = obj.check3 and 255 or 0", 3)]
[InlineData("obj . check1 = true", 1)]
public void DetectsReferencedCheck(string script, int index)
{
var usage = ScriptParameterUsage.Detect(script);
for (int i = 0; i < 4; i++)
Assert.Equal(i == index, usage.Check(i));
Assert.False(usage.Color);
}
[Fact]
public void DetectsReferencedColor()
{
var usage = ScriptParameterUsage.Detect("obj.rz = color / 1000");
Assert.True(usage.Color);
}
[Fact]
public void DetectsMultipleChecks()
{
var usage = ScriptParameterUsage.Detect("local a = obj.check0\nlocal b = obj.check2");
Assert.True(usage.Check0);
Assert.False(usage.Check1);
Assert.True(usage.Check2);
Assert.False(usage.Check3);
}
[Theory]
[InlineData("obj.setoption(\"color\", 1)")]
[InlineData("-- color and obj.check0 in a comment")]
[InlineData("local colorful = 1")]
[InlineData("scene.color = 0")]
public void IgnoresStringsCommentsAndUnrelatedNames(string script)
{
var usage = ScriptParameterUsage.Detect(script);
Assert.False(usage.Color);
for (int i = 0; i < 4; i++)
Assert.False(usage.Check(i));
}
[Theory]
[InlineData(null)]
[InlineData("")]
[InlineData("local s = \"unterminated")]
public void ReturnsNoneForEmptyOrInvalid(string? script)
{
var usage = ScriptParameterUsage.Detect(script);
Assert.False(usage.Color);
Assert.False(usage.Check0);
}
[Fact]
public void DoesNotDetectOutOfRangeCheck()
{
var usage = ScriptParameterUsage.Detect("local a = obj.check4");
for (int i = 0; i < 4; i++)
Assert.False(usage.Check(i));
}
}
}
+1
ファイルの表示
@@ -3,6 +3,7 @@
<Platform Name="Any CPU" /> <Platform Name="Any CPU" />
<Platform Name="x64" /> <Platform Name="x64" />
</Configurations> </Configurations>
<Project Path="LuaScript.Tests/LuaScript.Tests.csproj" />
<Project Path="LuaScript/LuaScript.csproj"> <Project Path="LuaScript/LuaScript.csproj">
<Platform Solution="*|x64" Project="x64" /> <Platform Solution="*|x64" Project="x64" />
</Project> </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;
}
}
}
+204 -29
ファイルの表示
@@ -2,12 +2,12 @@ namespace LuaScript
{ {
internal sealed class AviUtlScriptContext internal sealed class AviUtlScriptContext
{ {
public bool IsPlaying { get; init; } public bool IsPlaying { get; set; }
public bool IsPaused { get; init; } public bool IsPaused { get; set; }
public string SceneId { get; init; } = string.Empty; public string SceneId { get; set; } = string.Empty;
public int ImageWidth { get; init; } public int ImageWidth { get; set; }
public int ImageHeight { get; init; } public int ImageHeight { get; set; }
public double X { get; set; } public double X { get; set; }
public double Y { get; set; } public double Y { get; set; }
@@ -24,56 +24,182 @@ namespace LuaScript
public double Ry { get; set; } public double Ry { get; set; }
public double Rz { get; set; } public double Rz { get; set; }
public double Track0 { get; init; } public double Track0 { get; set; }
public double Track1 { get; init; } public double Track1 { get; set; }
public double Track2 { get; init; } public double Track2 { get; set; }
public double Track3 { get; init; } public double Track3 { get; set; }
public double Time { get; init; } public double Slider0 { get; set; }
public int Frame { get; init; } public double Slider1 { get; set; }
public int TotalFrame { get; init; } public double Slider2 { get; set; }
public double TotalTime { get; init; } public double Slider3 { get; set; }
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 SceneObjectResolver? Resolver { get; init; } public bool Check0 { get; set; }
public bool Check1 { get; set; }
public bool Check2 { get; set; }
public bool Check3 { get; set; }
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 Dictionary<string, string> _stringParameters = new(StringComparer.Ordinal);
public IReadOnlyDictionary<string, string> StringParameters => _stringParameters;
internal void SetStringParameter(string name, string? value) => _stringParameters[name] = value ?? string.Empty;
private const double Epsilon = 1e-10;
private readonly List<SceneObjectQuery> _objectQueries = []; private readonly List<SceneObjectQuery> _objectQueries = [];
public IReadOnlyList<SceneObjectQuery> ObjectQueries => _objectQueries; public IReadOnlyList<SceneObjectQuery> ObjectQueries => _objectQueries;
private readonly List<AviUtlEffectRequest> _effectRequests = [];
public IReadOnlyList<AviUtlEffectRequest> EffectRequests => _effectRequests;
internal void AddEffect(AviUtlEffectRequest request) => _effectRequests.Add(request);
internal void ClearEffects() => _effectRequests.Clear();
private readonly List<DrawCommand> _drawCommands = [];
public IReadOnlyList<DrawCommand> DrawCommands => _drawCommands;
internal void AddDraw(DrawCommand command) => _drawCommands.Add(command);
internal void ClearDraws() => _drawCommands.Clear();
private readonly Dictionary<string, (byte[] Data, int Width, int Height)> _buffers = new(StringComparer.Ordinal);
internal bool CopyBuffer(string dst, string src)
{
if (!TryReadBuffer(src, out var data, out int w, out int h))
return false;
return TryWriteBuffer(dst, data, w, h);
}
private bool TryReadBuffer(string id, out byte[] data, out int width, out int height)
{
data = [];
width = 0;
height = 0;
switch (BufferKind(id, out string key))
{
case 'o':
EnsurePixelBuffer();
if (_pixelBuffer is null)
return false;
data = _pixelBuffer;
width = ImageWidth;
height = ImageHeight;
return true;
case 't':
case 'c':
if (_buffers.TryGetValue(key, out var stored))
{
data = stored.Data;
width = stored.Width;
height = stored.Height;
return true;
}
return false;
default:
return false;
}
}
private bool TryWriteBuffer(string id, byte[] data, int width, int height)
{
switch (BufferKind(id, out string key))
{
case 'o':
ReplaceBuffer((byte[])data.Clone(), width, height);
return true;
case 't':
case 'c':
_buffers[key] = ((byte[])data.Clone(), width, height);
return false;
default:
return false;
}
}
private static char BufferKind(string id, out string key)
{
key = string.Empty;
int i = 0;
while (i < id.Length && (id[i] == ' ' || id[i] == '\t'))
i++;
if (i >= id.Length)
return '\0';
char kind = char.ToLowerInvariant(id[i]);
if (kind == 't')
key = "t";
else if (kind == 'c')
{
int colon = id.IndexOf(':', i);
key = colon >= 0 ? "c:" + id[(colon + 1)..].Trim() : "c";
}
return kind;
}
public double RxRad => Rx * Math.PI / 180d; public double RxRad => Rx * Math.PI / 180d;
public double RyRad => Ry * Math.PI / 180d; public double RyRad => Ry * Math.PI / 180d;
public double RzRad => Rz * Math.PI / 180d; public double RzRad => Rz * Math.PI / 180d;
public int GroupIndex { get; init; } public int GroupIndex { get; set; }
public int GroupCount { get; init; } public int GroupCount { get; set; }
public int TimelineTotalFrame { get; init; } public int TimelineTotalFrame { get; set; }
public double TimelineTotalTime { get; init; } public double TimelineTotalTime { get; set; }
public bool IsSaving { get; init; } public bool IsSaving { get; set; }
public double TimeRatio { get; init; } public double TimeRatio { get; set; }
private Func<byte[]>? _pixelLoader; private Func<byte[]>? _pixelLoader;
private byte[]? _pixelBuffer; private byte[]? _pixelBuffer;
private bool _pixelBufferLoaded; private bool _pixelBufferLoaded;
private bool _isPixelsDirty; private bool _isPixelsDirty;
private bool _bufferReplaced;
public bool IsPixelsDirty => _isPixelsDirty; public bool IsPixelsDirty => _isPixelsDirty;
public bool BufferReplaced => _bufferReplaced;
internal int TotalChannels => ImageWidth * ImageHeight * 4; internal int TotalChannels => ImageWidth * ImageHeight * 4;
internal void ClearQueries() => _objectQueries.Clear();
internal void SetPixelLoader(Func<byte[]> loader) internal void SetPixelLoader(Func<byte[]> loader)
{ {
_pixelLoader = loader; _pixelLoader = loader;
_pixelBuffer = null; _pixelBuffer = null;
_pixelBufferLoaded = false; _pixelBufferLoaded = false;
_isPixelsDirty = 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() internal void EnsurePixelBuffer()
@@ -83,13 +209,22 @@ namespace LuaScript
_pixelBufferLoaded = true; _pixelBufferLoaded = true;
} }
internal void SetResolvedBuffer(byte[] buffer, int width, int height)
{
_pixelBuffer = buffer;
_pixelBufferLoaded = true;
ImageWidth = width;
ImageHeight = height;
}
internal byte[]? GetPixelBuffer() => _pixelBuffer; internal byte[]? GetPixelBuffer() => _pixelBuffer;
internal void MarkPixelsDirty() => _isPixelsDirty = true; internal void MarkPixelsDirty() => _isPixelsDirty = true;
public bool ResolveObject(string tag, int frame, out SceneObjectInfo info) 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)); _objectQueries.Add(new SceneObjectQuery(tag, frame, resolved));
info = resolved; info = resolved;
@@ -101,6 +236,46 @@ namespace LuaScript
return false; return false;
} }
public void ApplyWriteBack(
double newSx, double newSy, double newZoom, double newAspect,
double newRx, double newRy, double newRz,
double newRxr, double newRyr, double newRzr)
{
double initialSx = Sx;
double initialSy = Sy;
double initialZoom = Zoom;
double initialAspect = Aspect;
Sx = newSx;
Sy = newSy;
Zoom = newZoom;
Aspect = newAspect;
bool sxsyChanged = Math.Abs(Sx - initialSx) > Epsilon || Math.Abs(Sy - initialSy) > Epsilon;
bool zoomAspectChanged = Math.Abs(Zoom - initialZoom) > Epsilon || Math.Abs(Aspect - initialAspect) > Epsilon;
if (zoomAspectChanged && !sxsyChanged)
{
Sx = Zoom * (1.0 + Aspect);
Sy = Zoom * (1.0 - Aspect);
}
double initialRxr = RxRad;
Rx = Math.Abs(newRxr - initialRxr) > Epsilon
? newRxr * (180d / Math.PI)
: newRx;
double initialRyr = RyRad;
Ry = Math.Abs(newRyr - initialRyr) > Epsilon
? newRyr * (180d / Math.PI)
: newRy;
double initialRzr = RzRad;
Rz = Math.Abs(newRzr - initialRzr) > Epsilon
? newRzr * (180d / Math.PI)
: newRz;
}
public unsafe (double r, double g, double b, double a) GetPixel(int x, int y) public unsafe (double r, double g, double b, double a) GetPixel(int x, int y)
{ {
EnsurePixelBuffer(); EnsurePixelBuffer();
+138
ファイルの表示
@@ -0,0 +1,138 @@
using System.Collections.Generic;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Xml.Linq;
namespace LuaScript.Compat
{
internal sealed class AviUtlCompatMap
{
private const string ResourceSuffix = "AviUtlCompatMap.xml";
private readonly Dictionary<string, List<AviUtlEffectMapping>> _effects;
public static AviUtlCompatMap Default { get; } = Load();
private AviUtlCompatMap(Dictionary<string, List<AviUtlEffectMapping>> effects)
{
_effects = effects;
}
public bool TryResolve(string name, AviUtlEngine target, out AviUtlEffectMapping mapping)
{
mapping = null!;
if (string.IsNullOrEmpty(name) || !_effects.TryGetValue(Normalize(name), out var candidates))
return false;
foreach (var candidate in candidates)
{
if (candidate.Engine.Includes(target))
{
mapping = candidate;
return true;
}
}
return false;
}
public static AviUtlEngine ResolveTarget(string? script)
{
if (string.IsNullOrEmpty(script))
return AviUtlEngine.AviUtl;
foreach (var raw in script.Replace("\r\n", "\n").Replace("\r", "\n").Split('\n'))
{
var line = raw.Trim();
if (!line.StartsWith("--!", System.StringComparison.Ordinal))
continue;
var token = line[3..].Trim().ToLowerInvariant();
if (token == "aviutl2")
return AviUtlEngine.AviUtl2;
if (token == "aviutl")
return AviUtlEngine.AviUtl;
}
return AviUtlEngine.AviUtl;
}
private static AviUtlCompatMap Load()
{
var effects = new Dictionary<string, List<AviUtlEffectMapping>>(StringComparer.OrdinalIgnoreCase);
try
{
using var stream = OpenResource();
if (stream is not null)
Populate(effects, stream);
}
catch
{
}
return new AviUtlCompatMap(effects);
}
private static void Populate(Dictionary<string, List<AviUtlEffectMapping>> effects, Stream stream)
{
var root = XDocument.Load(stream).Root;
if (root is null)
return;
foreach (var element in root.Elements("effect"))
{
var target = (string?)element.Attribute("target");
if (string.IsNullOrWhiteSpace(target))
continue;
if (!AviUtlEngineExtensions.TryParse(((string?)element.Attribute("engine"))?.Trim().ToLowerInvariant(), out var engine))
engine = AviUtlEngine.Both;
var parameters = element.Elements("param").Select(ParseParameter).ToArray();
var mapping = new AviUtlEffectMapping(engine, target.Trim(), parameters);
foreach (var name in SplitNames((string?)element.Attribute("names")))
{
if (!effects.TryGetValue(name, out var list))
{
list = [];
effects[name] = list;
}
list.Add(mapping);
}
}
}
private static AviUtlParameterMapping ParseParameter(XElement element)
{
var source = ((string?)element.Attribute("name") ?? string.Empty).Trim();
var property = ((string?)element.Attribute("property") ?? string.Empty).Trim();
double scale = ParseDouble((string?)element.Attribute("scale"), 1d);
double offset = ParseDouble((string?)element.Attribute("offset"), 0d);
return new AviUtlParameterMapping(source, property, scale, offset);
}
private static IEnumerable<string> SplitNames(string? names)
{
if (string.IsNullOrWhiteSpace(names))
yield break;
foreach (var part in names.Split(','))
{
var trimmed = part.Trim();
if (trimmed.Length != 0)
yield return Normalize(trimmed);
}
}
private static double ParseDouble(string? value, double fallback) =>
double.TryParse(value, NumberStyles.Float, CultureInfo.InvariantCulture, out double result) ? result : fallback;
private static string Normalize(string value) => value.Trim().ToLowerInvariant();
private static Stream? OpenResource()
{
var assembly = typeof(AviUtlCompatMap).Assembly;
var name = assembly.GetManifestResourceNames()
.FirstOrDefault(n => n.EndsWith(ResourceSuffix, System.StringComparison.Ordinal));
return name is null ? null : assembly.GetManifestResourceStream(name);
}
}
}
+114
ファイルの表示
@@ -0,0 +1,114 @@
<?xml version="1.0" encoding="utf-8"?>
<aviUtlCompat>
<effect engine="both" names="ぼかし" target="GaussianBlurEffect">
<param name="範囲" property="Blur" scale="0.5" />
<param name="サイズ固定" property="IsHardBorderMode" />
</effect>
<effect engine="both" names="境界ぼかし" target="BorderBlurEffect">
<param name="範囲" property="Blur" />
</effect>
<effect engine="both" names="方向ブラー" target="DirectionalBlurEffect">
<param name="範囲" property="StandardDeviation" scale="0.5" />
<param name="角度" property="Angle" />
<param name="サイズ固定" property="IsHardBorderMode" />
</effect>
<effect engine="both" names="放射ブラー" target="RadialBlurEffect">
<param name="範囲" property="Blur" />
<param name="X" property="X" />
<param name="Y" property="Y" />
<param name="サイズを固定" property="IsHardBorderMode" />
</effect>
<effect engine="both" names="閃光" target="RadialLightEffect">
<param name="範囲" property="Value" />
<param name="X" property="X" />
<param name="Y" property="Y" />
<param name="サイズを固定" property="IsHardBorderMode" />
</effect>
<effect engine="both" names="クロマキー" target="ChromaKeyEffect">
<param name="色相範囲" property="Tolerance" scale="0.390625" />
<param name="境界補正" property="Feather" />
</effect>
<effect engine="both" names="クリッピング" target="CropEffect">
<param name="上" property="Top" />
<param name="下" property="Bottom" />
<param name="左" property="Left" />
<param name="右" property="Right" />
<param name="中心の位置を変更" property="IsCentering" />
</effect>
<effect engine="both" names="斜めクリッピング" target="CropByAngleEffect">
<param name="中心X" property="X" />
<param name="中心Y" property="Y" />
<param name="角度" property="Angle" />
<param name="ぼかし" property="Blur" scale="0.5" />
<param name="幅" property="Width" />
</effect>
<effect engine="both" names="領域拡張" target="MarginEffect">
<param name="上" property="Top" />
<param name="下" property="Bottom" />
<param name="左" property="Left" />
<param name="右" property="Right" />
</effect>
<effect engine="both" names="座標" target="DrawPositionEffect">
<param name="X" property="X" />
<param name="Y" property="Y" />
<param name="Z" property="Z" />
</effect>
<effect engine="both" names="回転" target="RotateEffect">
<param name="X" property="X" />
<param name="Y" property="Y" />
<param name="Z" property="Z" />
</effect>
<effect engine="both" names="リサイズ" target="ZoomEffect">
<param name="拡大率" property="Zoom" />
<param name="X" property="ZoomX" />
<param name="Y" property="ZoomY" />
<param name="補間なし" property="IsNearestNeighbor" />
</effect>
<effect engine="both" names="画像ループ" target="TilingEffect">
<param name="横回数" property="X" />
<param name="縦回数" property="Y" />
</effect>
<effect engine="both" names="極座標変換" target="PolarTransformEffect">
<param name="中心幅" property="CoreWidth" />
<param name="渦巻" property="TwistAngle" scale="360" />
</effect>
<effect engine="both" names="グラデーション" target="GradientEffect">
<param name="強さ" property="Opacity" />
<param name="中心X" property="X" />
<param name="中心Y" property="Y" />
<param name="角度" property="Rotation" />
<param name="幅" property="Size" />
</effect>
<effect engine="both" names="単色化" target="MonocolorizationEffect">
<param name="強さ" property="Strength" />
<param name="輝度を保持する" property="KeepBrightness" />
</effect>
<effect engine="both" names="縁取り" target="OutlineEffect">
<param name="サイズ" property="StrokeThickness" />
<param name="ぼかし" property="Blur" />
</effect>
<effect engine="both" names="反転" target="InvertEffect" />
<effect engine="both" names="モザイク" target="MosaicEffect">
<param name="サイズ" property="Size" />
</effect>
<effect engine="both" names="ディスプレイスメントマップ" target="DisplacementMapEffect">
<param name="ぼかし" property="Blur" scale="0.5" />
</effect>
<effect engine="both" names="動画ファイル合成" target="TextureEffect">
<param name="X" property="X" />
<param name="Y" property="Y" />
<param name="拡大率" property="Zoom" />
</effect>
<effect engine="both" names="色調補正" target="ColorCorrectionEffect">
<param name="明るさ" property="Lightness" />
<param name="コントラスト" property="Contrast" />
<param name="色相" property="HueRotation" />
<param name="輝度" property="Brightness" />
<param name="彩度" property="Saturation" />
</effect>
<effect engine="both" names="色ずれ" target="ColorShiftEffect">
<param name="ずれ幅" property="Shift" />
<param name="角度" property="Angle" />
<param name="強さ" property="Strength" />
</effect>
</aviUtlCompat>
+30
ファイルの表示
@@ -0,0 +1,30 @@
using System.Collections.Generic;
namespace LuaScript.Compat
{
internal readonly record struct AviUtlParameterMapping(string Source, string Property, double Scale, double Offset)
{
public double Transform(double value) => value * Scale + Offset;
}
internal sealed class AviUtlEffectMapping
{
private readonly Dictionary<string, AviUtlParameterMapping> _parameters;
public AviUtlEngine Engine { get; }
public string TargetType { get; }
public AviUtlEffectMapping(AviUtlEngine engine, string targetType, IEnumerable<AviUtlParameterMapping> parameters)
{
Engine = engine;
TargetType = targetType;
_parameters = new Dictionary<string, AviUtlParameterMapping>(StringComparer.OrdinalIgnoreCase);
foreach (var parameter in parameters)
_parameters[parameter.Source] = parameter;
}
public bool TryGetParameter(string source, out AviUtlParameterMapping mapping) =>
_parameters.TryGetValue(source, out mapping);
}
}
+34
ファイルの表示
@@ -0,0 +1,34 @@
namespace LuaScript.Compat
{
internal enum AviUtlEngine
{
AviUtl,
AviUtl2,
Both,
}
internal static class AviUtlEngineExtensions
{
public static bool Includes(this AviUtlEngine scope, AviUtlEngine target) =>
scope == AviUtlEngine.Both || scope == target;
public static bool TryParse(string? value, out AviUtlEngine engine)
{
switch (value)
{
case "aviutl":
engine = AviUtlEngine.AviUtl;
return true;
case "aviutl2":
engine = AviUtlEngine.AviUtl2;
return true;
case "both":
engine = AviUtlEngine.Both;
return true;
default:
engine = AviUtlEngine.AviUtl;
return false;
}
}
}
}
+184
ファイルの表示
@@ -0,0 +1,184 @@
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 (!ScriptParserHelper.IsSectionHeader(lines[i]))
continue;
sectionStart = i + 1;
sectionEnd = lines.Length;
for (int j = sectionStart; j < lines.Length; j++)
{
if (ScriptParserHelper.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 = ScriptParserHelper.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 && ScriptParserHelper.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 = ScriptParserHelper.SkipSpaces(content, 0);
int i = start;
while (i < content.Length && content[i] != ',' && content[i] != ' ' && content[i] != '\t')
i++;
return content.Substring(start, i - start);
}
}
}
+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;
}
}
}
+134
ファイルの表示
@@ -0,0 +1,134 @@
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) => TransformWithMap(source).Code;
public static (string Code, int[] LineMap) TransformWithMap(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 (!ScriptParserHelper.IsSectionHeader(lines[i]))
continue;
hasSection = true;
sectionStart = i + 1;
sectionEnd = lines.Length;
for (int j = sectionStart; j < lines.Length; j++)
{
if (ScriptParserHelper.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);
var lineMap = new int[prelude.Count + (sectionEnd - sectionStart)];
int row = 0;
foreach (var declaration in prelude)
{
builder.Append(declaration).Append('\n');
lineMap[row++] = -1;
}
for (int i = sectionStart; i < sectionEnd; i++)
{
builder.Append(lines[i]).Append('\n');
lineMap[row++] = i;
}
return (builder.ToString(), lineMap);
}
private static void AppendDeclarations(string line, List<string> prelude)
{
int i = ScriptParserHelper.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 && ScriptParserHelper.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);
}
}
}
+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;
}
}
}
+76
ファイルの表示
@@ -0,0 +1,76 @@
using System;
using System.Collections.Generic;
using LuaScript.Engine.Kernel;
namespace LuaScript.Compat
{
internal readonly struct ScriptParameterUsage
{
private readonly HashSet<string>? _members;
private readonly bool _color;
private ScriptParameterUsage(HashSet<string>? members, bool color)
{
_members = members;
_color = color;
}
public static readonly ScriptParameterUsage None = default;
public bool Color => _color;
public bool Uses(string member) => _members is not null && _members.Contains(member);
public bool Check0 => Uses("check0");
public bool Check1 => Uses("check1");
public bool Check2 => Uses("check2");
public bool Check3 => Uses("check3");
public bool Check(int index) => (uint)index < 4 && Uses("check" + (char)('0' + index));
public bool Slider(int index) => (uint)index < 4 && Uses("slider" + (char)('0' + index));
public static ScriptParameterUsage Detect(string? script)
{
if (string.IsNullOrEmpty(script))
return None;
List<LuaToken> tokens;
try
{
tokens = LuaLexer.Tokenize(script);
}
catch (KernelUnsupportedException)
{
return None;
}
HashSet<string>? members = null;
bool color = false;
for (int i = 0; i < tokens.Count; i++)
{
var token = tokens[i];
if (token.Kind != LuaTokenKind.Name)
continue;
if (token.Text == "color")
{
if (i == 0 || !tokens[i - 1].IsSymbol("."))
color = true;
continue;
}
if (token.Text == "obj" &&
i + 2 < tokens.Count &&
tokens[i + 1].IsSymbol(".") &&
tokens[i + 2].Kind == LuaTokenKind.Name)
{
(members ??= new HashSet<string>(StringComparer.Ordinal)).Add(tokens[i + 2].Text);
}
}
return new ScriptParameterUsage(members, color);
}
}
}
+21
ファイルの表示
@@ -0,0 +1,21 @@
namespace LuaScript.Compat
{
internal static class ScriptParserHelper
{
public static bool IsSectionHeader(string line)
{
int i = SkipSpaces(line, 0);
return i < line.Length && line[i] == '@';
}
public static int SkipSpaces(string text, int index)
{
while (index < text.Length && (text[index] == ' ' || text[index] == '\t'))
index++;
return index;
}
public static bool IsNameChar(char c) =>
(c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z') || (c >= '0' && c <= '9');
}
}
+42
ファイルの表示
@@ -0,0 +1,42 @@
using System;
using System.Text.RegularExpressions;
namespace LuaScript.Diagnostics
{
internal enum LuaScriptDiagnosticKind
{
Compile,
Runtime,
Timeout,
}
internal readonly record struct LuaScriptDiagnostic(
LuaScriptDiagnosticKind Kind,
int Line,
int Column,
int Length,
string Message);
internal static partial class LuaScriptDiagnosticParser
{
[GeneratedRegex(@"^LuaScript:\((\d+),(\d+)(?:-(\d+)(?:,(\d+))?)?\):\s*", RegexOptions.None)]
private static partial Regex LocationPattern();
public static LuaScriptDiagnostic Parse(LuaScriptDiagnosticKind kind, string? message)
{
var text = message ?? string.Empty;
var match = LocationPattern().Match(text);
if (!match.Success)
return new LuaScriptDiagnostic(kind, 0, 0, 0, text.Trim());
int line = int.Parse(match.Groups[1].Value);
int columnStart = int.Parse(match.Groups[2].Value);
int length = 0;
if (match.Groups[3].Success && !match.Groups[4].Success)
length = Math.Max(0, int.Parse(match.Groups[3].Value) - columnStart);
return new LuaScriptDiagnostic(kind, line, columnStart + 1, length, text[match.Length..].Trim());
}
}
}
+263
ファイルの表示
@@ -0,0 +1,263 @@
using System;
using System.Collections.Generic;
using System.Reflection;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Controls.Primitives;
using System.Windows.Input;
using System.Windows.Media;
using ICSharpCode.AvalonEdit.Document;
using ICSharpCode.AvalonEdit.Folding;
using ICSharpCode.AvalonEdit.Rendering;
namespace LuaScript.Diagnostics
{
internal sealed class LuaScriptDiagnosticOverlay : IBackgroundRenderer, ILuaScriptDiagnosticsListener
{
private static readonly FieldInfo? s_textViewsField = ResolveTextViewsField();
private static readonly Pen s_squigglePen = CreateSquigglePen();
private sealed class Marker : ISegment
{
public required int Offset { get; init; }
public required int Length { get; init; }
public int EndOffset => Offset + Length;
public required LuaScriptDiagnostic Diagnostic { get; init; }
}
private readonly TextView _textView;
private readonly ToolTip _toolTip = new() { Placement = PlacementMode.Mouse };
private readonly List<Marker> _markers = [];
private object? _renderedText;
private bool _isDirty = true;
public static void Attach(FoldingManager manager)
{
var textView = ResolveTextView(manager);
if (textView is null)
return;
foreach (var renderer in textView.BackgroundRenderers)
{
if (renderer is LuaScriptDiagnosticOverlay)
return;
}
_ = new LuaScriptDiagnosticOverlay(textView);
}
private LuaScriptDiagnosticOverlay(TextView textView)
{
_textView = textView;
textView.BackgroundRenderers.Add(this);
textView.MouseHover += OnMouseHover;
textView.MouseHoverStopped += OnMouseHoverStopped;
LuaScriptDiagnostics.Instance.Subscribe(this);
}
public KnownLayer Layer => KnownLayer.Selection;
public void OnDiagnosticsChanged()
{
_textView.Dispatcher.BeginInvoke(() =>
{
_isDirty = true;
_textView.InvalidateLayer(KnownLayer.Selection);
});
}
public void Draw(TextView textView, DrawingContext drawingContext)
{
var document = textView.Document;
if (document is null)
return;
if (_isDirty || !ReferenceEquals(document.Text, _renderedText))
Rebuild(document);
if (_markers.Count == 0 || !textView.VisualLinesValid)
return;
foreach (var marker in _markers)
{
foreach (var rect in BackgroundGeometryBuilder.GetRectsForSegment(textView, marker, false))
DrawSquiggle(drawingContext, rect);
}
}
private void Rebuild(TextDocument document)
{
_isDirty = false;
_renderedText = document.Text;
_markers.Clear();
foreach (var diagnostic in LuaScriptDiagnostics.Instance.Get(document.Text))
{
if (TryCreateMarker(document, diagnostic, out var marker))
_markers.Add(marker);
}
}
private static bool TryCreateMarker(TextDocument document, LuaScriptDiagnostic diagnostic, out Marker marker)
{
marker = null!;
int lineNumber = diagnostic.Line > 0 ? diagnostic.Line : 1;
if (lineNumber > document.LineCount)
return false;
var line = document.GetLineByNumber(lineNumber);
int offset;
int length;
if (diagnostic.Line > 0 && diagnostic.Column > 0 && diagnostic.Length > 0)
{
offset = Math.Min(line.Offset + diagnostic.Column - 1, line.EndOffset);
length = Math.Min(diagnostic.Length, line.EndOffset - offset);
}
else
{
offset = SkipLeadingWhitespace(document, line);
length = line.EndOffset - offset;
}
if (length <= 0)
{
if (line.Length == 0)
return false;
offset = line.Offset;
length = line.Length;
}
marker = new Marker { Offset = offset, Length = length, Diagnostic = diagnostic };
return true;
}
private static int SkipLeadingWhitespace(TextDocument document, DocumentLine line)
{
int offset = line.Offset;
while (offset < line.EndOffset)
{
char c = document.GetCharAt(offset);
if (c != ' ' && c != '\t')
break;
offset++;
}
return offset;
}
private void OnMouseHover(object? sender, MouseEventArgs e)
{
var document = _textView.Document;
if (document is null)
return;
var position = _textView.GetPositionFloor(e.GetPosition(_textView) + _textView.ScrollOffset);
if (position is null)
return;
int offset = document.GetOffset(position.Value.Location);
foreach (var marker in _markers)
{
if (offset < marker.Offset || offset > marker.EndOffset)
continue;
_toolTip.Content = BuildToolTipContent(marker.Diagnostic);
_toolTip.IsOpen = true;
e.Handled = true;
return;
}
}
private void OnMouseHoverStopped(object? sender, MouseEventArgs e)
{
_toolTip.IsOpen = false;
}
private static object BuildToolTipContent(LuaScriptDiagnostic diagnostic)
{
var panel = new StackPanel { MaxWidth = 480 };
panel.Children.Add(new TextBlock { Text = KindLabel(diagnostic.Kind), FontWeight = FontWeights.Bold });
if (!string.IsNullOrEmpty(diagnostic.Message))
panel.Children.Add(new TextBlock { Text = diagnostic.Message, TextWrapping = TextWrapping.Wrap });
return panel;
}
private static string KindLabel(LuaScriptDiagnosticKind kind) => kind switch
{
LuaScriptDiagnosticKind.Compile => Texts.DiagnosticCompile,
LuaScriptDiagnosticKind.Timeout => Texts.DiagnosticTimeout,
_ => Texts.DiagnosticRuntime,
};
private static void DrawSquiggle(DrawingContext drawingContext, Rect rect)
{
if (rect.Width <= 0)
return;
const double step = 3.0;
double baseline = rect.Bottom - 0.5;
var geometry = new StreamGeometry();
using (var context = geometry.Open())
{
context.BeginFigure(new Point(rect.Left, baseline), false, false);
var points = new List<Point>();
int index = 0;
for (double x = rect.Left; x <= rect.Right; x += step)
{
points.Add(new Point(x, baseline - (index % 2 == 0 ? 0.0 : step)));
index++;
}
context.PolyLineTo(points, true, false);
}
geometry.Freeze();
drawingContext.DrawGeometry(null, s_squigglePen, geometry);
}
private static Pen CreateSquigglePen()
{
var pen = new Pen(new SolidColorBrush(Color.FromRgb(0xE5, 0x1A, 0x1A)), 1.0);
pen.Brush.Freeze();
pen.Freeze();
return pen;
}
private static FieldInfo? ResolveTextViewsField()
{
foreach (var field in typeof(FoldingManager).GetFields(BindingFlags.Instance | BindingFlags.NonPublic))
{
if (typeof(IEnumerable<TextView>).IsAssignableFrom(field.FieldType))
return field;
}
return null;
}
private static TextView? ResolveTextView(FoldingManager? manager)
{
if (manager is null || s_textViewsField is null)
return null;
try
{
if (s_textViewsField.GetValue(manager) is IEnumerable<TextView> views)
{
foreach (var view in views)
{
if (view is not null)
return view;
}
}
}
catch
{
return null;
}
return null;
}
}
}
+110
ファイルの表示
@@ -0,0 +1,110 @@
using System;
using System.Collections.Generic;
namespace LuaScript.Diagnostics
{
internal interface ILuaScriptDiagnosticsListener
{
void OnDiagnosticsChanged();
}
internal sealed class LuaScriptDiagnostics
{
public static LuaScriptDiagnostics Instance { get; } = new();
private const int MaxTrackedScripts = 64;
private readonly object _gate = new();
private readonly Dictionary<string, IReadOnlyList<LuaScriptDiagnostic>> _entries = new(StringComparer.Ordinal);
private readonly Queue<string> _insertionOrder = new();
private readonly List<WeakReference<ILuaScriptDiagnosticsListener>> _listeners = [];
private LuaScriptDiagnostics()
{
}
public void Subscribe(ILuaScriptDiagnosticsListener listener)
{
lock (_gate)
{
PruneDeadListeners();
_listeners.Add(new WeakReference<ILuaScriptDiagnosticsListener>(listener));
}
}
public IReadOnlyList<LuaScriptDiagnostic> Get(string? script)
{
if (script is null)
return [];
lock (_gate)
return _entries.TryGetValue(script, out var diagnostics) ? diagnostics : [];
}
public void Report(string? script, IReadOnlyList<LuaScriptDiagnostic> diagnostics)
{
if (script is null)
return;
diagnostics ??= [];
ILuaScriptDiagnosticsListener[] targets;
lock (_gate)
{
if (_entries.TryGetValue(script, out var existing) && AreEqual(existing, diagnostics))
return;
if (!_entries.ContainsKey(script))
_insertionOrder.Enqueue(script);
_entries[script] = diagnostics;
while (_entries.Count > MaxTrackedScripts && _insertionOrder.Count > 0)
{
var oldest = _insertionOrder.Dequeue();
if (!string.Equals(oldest, script, StringComparison.Ordinal))
_entries.Remove(oldest);
}
targets = CollectLiveListeners();
}
foreach (var target in targets)
target.OnDiagnosticsChanged();
}
private ILuaScriptDiagnosticsListener[] CollectLiveListeners()
{
var live = new List<ILuaScriptDiagnosticsListener>(_listeners.Count);
for (int i = _listeners.Count - 1; i >= 0; i--)
{
if (_listeners[i].TryGetTarget(out var listener))
live.Add(listener);
else
_listeners.RemoveAt(i);
}
return [.. live];
}
private void PruneDeadListeners()
{
for (int i = _listeners.Count - 1; i >= 0; i--)
{
if (!_listeners[i].TryGetTarget(out _))
_listeners.RemoveAt(i);
}
}
private static bool AreEqual(IReadOnlyList<LuaScriptDiagnostic> a, IReadOnlyList<LuaScriptDiagnostic> b)
{
if (a.Count != b.Count)
return false;
for (int i = 0; i < a.Count; i++)
{
if (!a[i].Equals(b[i]))
return false;
}
return true;
}
}
}
+12
ファイルの表示
@@ -0,0 +1,12 @@
namespace LuaScript
{
internal readonly record struct DrawCommand(
double Ox,
double Oy,
double Oz,
double Zoom,
double Alpha,
double Aspect,
double[]? Poly = null,
double Antialias = 1d);
}
+149
ファイルの表示
@@ -0,0 +1,149 @@
using System;
using System.Collections.Generic;
using System.Numerics;
using Vortice.Direct2D1;
using Vortice.Direct2D1.Effects;
using YukkuriMovieMaker.Commons;
namespace LuaScript
{
internal sealed class DrawCompositor : IDisposable
{
private const int MaxDimension = 8192;
private readonly GraphicsDevicesAndContext _ctx;
private ID2D1Bitmap1? _source;
private ID2D1Bitmap1? _target;
private AffineTransform2D? _placement;
private int _sourceWidth;
private int _sourceHeight;
private int _targetWidth;
private int _targetHeight;
public DrawCompositor(GraphicsDevicesAndContext ctx)
{
_ctx = ctx;
}
public unsafe ID2D1Image Compose(byte[] pixels, int width, int height, IReadOnlyList<DrawCommand> commands)
{
EnsureSource(width, height);
fixed (byte* ptr = pixels)
_source!.CopyFromMemory(new nint(ptr), width * 4);
double minX = double.MaxValue, minY = double.MaxValue;
double maxX = double.MinValue, maxY = double.MinValue;
for (int i = 0; i < commands.Count; i++)
{
var cmd = commands[i];
if (cmd.Poly is { } poly)
{
DrawPolyMath.Bounds(poly, out double pMinX, out double pMinY, out double pMaxX, out double pMaxY);
minX = Math.Min(minX, pMinX);
maxX = Math.Max(maxX, pMaxX);
minY = Math.Min(minY, pMinY);
maxY = Math.Max(maxY, pMaxY);
continue;
}
double aspect = Math.Clamp(cmd.Aspect, -1d, 1d);
double zx = cmd.Zoom * (1d + aspect);
double zy = cmd.Zoom * (1d - aspect);
double halfW = width * 0.5 * zx;
double halfH = height * 0.5 * zy;
minX = Math.Min(minX, cmd.Ox - halfW);
maxX = Math.Max(maxX, cmd.Ox + halfW);
minY = Math.Min(minY, cmd.Oy - halfH);
maxY = Math.Max(maxY, cmd.Oy + halfH);
}
int originX = (int)Math.Floor(minX);
int originY = (int)Math.Floor(minY);
int targetW = Math.Clamp((int)Math.Ceiling(maxX) - originX, 1, MaxDimension);
int targetH = Math.Clamp((int)Math.Ceiling(maxY) - originY, 1, MaxDimension);
EnsureTarget(targetW, targetH);
var dc = _ctx.DeviceContext;
var rt = (ID2D1RenderTarget)dc;
var savedTarget = dc.Target;
dc.Target = _target;
dc.BeginDraw();
dc.Clear(null);
var toTarget = Matrix3x2.CreateTranslation(-originX, -originY);
for (int i = 0; i < commands.Count; i++)
{
var cmd = commands[i];
var interpolation = cmd.Antialias != 0d
? BitmapInterpolationMode.Linear
: BitmapInterpolationMode.NearestNeighbor;
if (cmd.Poly is { } poly)
{
if (!DrawPolyMath.TrySolveAffine(poly, out var affine))
continue;
rt.Transform = affine * toTarget;
rt.DrawBitmap(_source, (float)Math.Clamp(poly[20], 0d, 1d), interpolation);
continue;
}
double aspect = Math.Clamp(cmd.Aspect, -1d, 1d);
float zx = (float)(cmd.Zoom * (1d + aspect));
float zy = (float)(cmd.Zoom * (1d - aspect));
float opacity = (float)Math.Clamp(cmd.Alpha, 0d, 1d);
var matrix =
Matrix3x2.CreateTranslation(-width * 0.5f, -height * 0.5f) *
Matrix3x2.CreateScale(zx, zy) *
Matrix3x2.CreateTranslation((float)(cmd.Ox - originX), (float)(cmd.Oy - originY));
rt.Transform = matrix;
rt.DrawBitmap(_source, opacity, interpolation);
}
rt.Transform = Matrix3x2.Identity;
dc.EndDraw();
dc.Target = savedTarget;
_placement!.TransformMatrix = Matrix3x2.CreateTranslation(originX, originY);
return _placement.Output;
}
private void EnsureSource(int width, int height)
{
if (_source is not null && _sourceWidth == width && _sourceHeight == height)
return;
_source?.Dispose();
_source = _ctx.DeviceContext.CreateEmptyBitmap(width, height, BitmapOptions.Target);
_sourceWidth = width;
_sourceHeight = height;
}
private void EnsureTarget(int width, int height)
{
if (_target is not null && _targetWidth == width && _targetHeight == height)
return;
_placement?.Dispose();
_target?.Dispose();
_placement = null;
_target = _ctx.DeviceContext.CreateEmptyBitmap(width, height, BitmapOptions.Target);
_targetWidth = width;
_targetHeight = height;
_placement = new AffineTransform2D(_ctx.DeviceContext);
_placement.SetInput(0, _target, true);
}
public void Dispose()
{
_placement?.Dispose();
_source?.Dispose();
_target?.Dispose();
_placement = null;
_source = null;
_target = null;
}
}
}
+53
ファイルの表示
@@ -0,0 +1,53 @@
using System;
using System.Numerics;
namespace LuaScript
{
internal static class DrawPolyMath
{
public const int Length = 21;
public static bool TrySolveAffine(double[] poly, out Matrix3x2 matrix)
{
double x0 = poly[0], y0 = poly[1];
double x1 = poly[3], y1 = poly[4];
double x3 = poly[9], y3 = poly[10];
double u0 = poly[12], v0 = poly[13];
double u1 = poly[14], v1 = poly[15];
double u3 = poly[18], v3 = poly[19];
double det = u0 * (v1 - v3) - v0 * (u1 - u3) + (u1 * v3 - v1 * u3);
if (Math.Abs(det) < 1e-9)
{
matrix = Matrix3x2.Identity;
return false;
}
double inv = 1d / det;
double a = (x0 * (v1 - v3) - v0 * (x1 - x3) + (x1 * v3 - v1 * x3)) * inv;
double b = (u0 * (x1 - x3) - x0 * (u1 - u3) + (u1 * x3 - x1 * u3)) * inv;
double c = (u0 * (v1 * x3 - x1 * v3) - v0 * (u1 * x3 - x1 * u3) + x0 * (u1 * v3 - v1 * u3)) * inv;
double d = (y0 * (v1 - v3) - v0 * (y1 - y3) + (y1 * v3 - v1 * y3)) * inv;
double e = (u0 * (y1 - y3) - y0 * (u1 - u3) + (u1 * y3 - y1 * u3)) * inv;
double f = (u0 * (v1 * y3 - y1 * v3) - v0 * (u1 * y3 - y1 * u3) + y0 * (u1 * v3 - v1 * u3)) * inv;
matrix = new Matrix3x2((float)a, (float)d, (float)b, (float)e, (float)c, (float)f);
return true;
}
public static void Bounds(double[] poly, out double minX, out double minY, out double maxX, out double maxY)
{
minX = minY = double.MaxValue;
maxX = maxY = double.MinValue;
for (int i = 0; i < 4; i++)
{
double x = poly[i * 3];
double y = poly[i * 3 + 1];
if (x < minX) minX = x;
if (x > maxX) maxX = x;
if (y < minY) minY = y;
if (y > maxY) maxY = y;
}
}
}
}
+28
ファイルの表示
@@ -0,0 +1,28 @@
using System.Threading.Tasks;
namespace LuaScript.Engine.Kernel
{
internal sealed class CpuKernel(CpuKernel.RowDelegate row)
{
public delegate void RowDelegate(byte[] buffer, int width, int rowBase, double y, double[] uniforms);
private const int ParallelThreshold = 64;
private readonly RowDelegate _row = row;
public void Execute(byte[] buffer, int width, int height, double[] uniforms)
{
var row = _row;
int stride = width * 4;
if (height < ParallelThreshold)
{
for (int y = 0; y < height; y++)
row(buffer, width, y * stride, y, uniforms);
return;
}
Parallel.For(0, height, y => row(buffer, width, y * stride, y, uniforms));
}
}
}
+216
ファイルの表示
@@ -0,0 +1,216 @@
using System;
using System.Collections.Generic;
using System.Linq.Expressions;
using System.Reflection;
namespace LuaScript.Engine.Kernel
{
internal static class CpuKernelCompiler
{
private static readonly MethodInfo Clamp = typeof(Math).GetMethod(nameof(Math.Clamp), [typeof(double), typeof(double), typeof(double)])!;
private static readonly MethodInfo Floor = Unary(nameof(Math.Floor));
private static readonly MethodInfo Pow = Binary(nameof(Math.Pow));
private static readonly Dictionary<KFunc, MethodInfo> Functions = new()
{
[KFunc.Abs] = Unary(nameof(Math.Abs)),
[KFunc.Floor] = Floor,
[KFunc.Ceil] = Unary(nameof(Math.Ceiling)),
[KFunc.Sqrt] = Unary(nameof(Math.Sqrt)),
[KFunc.Sin] = Unary(nameof(Math.Sin)),
[KFunc.Cos] = Unary(nameof(Math.Cos)),
[KFunc.Tan] = Unary(nameof(Math.Tan)),
[KFunc.Asin] = Unary(nameof(Math.Asin)),
[KFunc.Acos] = Unary(nameof(Math.Acos)),
[KFunc.Atan] = Unary(nameof(Math.Atan)),
[KFunc.Atan2] = Binary(nameof(Math.Atan2)),
[KFunc.Exp] = Unary(nameof(Math.Exp)),
[KFunc.Log] = Unary(nameof(Math.Log)),
[KFunc.Pow] = Pow,
[KFunc.Min] = Binary(nameof(Math.Min)),
[KFunc.Max] = Binary(nameof(Math.Max)),
};
public static CpuKernel Compile(KernelProgram program)
{
var buffer = Expression.Parameter(typeof(byte[]), "buffer");
var width = Expression.Parameter(typeof(int), "width");
var rowBase = Expression.Parameter(typeof(int), "rowBase");
var y = Expression.Parameter(typeof(double), "y");
var uniforms = Expression.Parameter(typeof(double[]), "uniforms");
var x = Expression.Variable(typeof(int), "x");
var index = Expression.Variable(typeof(int), "index");
var alphaRaw = Expression.Variable(typeof(double), "alphaRaw");
var transparent = Expression.Variable(typeof(bool), "transparent");
var scale = Expression.Variable(typeof(double), "scale");
var inputs = new[]
{
Expression.Variable(typeof(double), "inR"),
Expression.Variable(typeof(double), "inG"),
Expression.Variable(typeof(double), "inB"),
Expression.Variable(typeof(double), "inA"),
};
var slots = new ParameterExpression[program.Bindings.Count];
for (int i = 0; i < slots.Length; i++)
slots[i] = Expression.Variable(typeof(double), "slot" + i);
var context = new Context(x, y, uniforms, inputs, slots);
var statements = new List<Expression>
{
Expression.Assign(index, Expression.Add(rowBase, Expression.Multiply(x, Constant(4)))),
Expression.Assign(alphaRaw, ToDouble(ReadByte(buffer, index, 3))),
Expression.Assign(transparent, Expression.LessThanOrEqual(alphaRaw, Constant(0d))),
Expression.Assign(scale, Select(transparent, Constant(0d), Expression.Divide(Constant(255d), alphaRaw))),
Expression.Assign(inputs[3], Select(transparent, Constant(0d), alphaRaw)),
Expression.Assign(inputs[0], Select(transparent, Constant(0d), ClampByte(Expression.Multiply(ToDouble(ReadByte(buffer, index, 2)), scale)))),
Expression.Assign(inputs[1], Select(transparent, Constant(0d), ClampByte(Expression.Multiply(ToDouble(ReadByte(buffer, index, 1)), scale)))),
Expression.Assign(inputs[2], Select(transparent, Constant(0d), ClampByte(Expression.Multiply(ToDouble(ReadByte(buffer, index, 0)), scale)))),
};
for (int i = 0; i < slots.Length; i++)
statements.Add(Expression.Assign(slots[i], Build(program.Bindings[i], context)));
var outA = Expression.Variable(typeof(double), "outA");
var alphaScale = Expression.Variable(typeof(double), "alphaScale");
statements.Add(Expression.Assign(outA, Build(program.OutputA, context)));
statements.Add(Expression.Assign(alphaScale, Expression.Divide(ClampByte(outA), Constant(255d))));
statements.Add(WriteByte(buffer, index, 0, ClampByte(Expression.Multiply(Build(program.OutputB, context), alphaScale))));
statements.Add(WriteByte(buffer, index, 1, ClampByte(Expression.Multiply(Build(program.OutputG, context), alphaScale))));
statements.Add(WriteByte(buffer, index, 2, ClampByte(Expression.Multiply(Build(program.OutputR, context), alphaScale))));
statements.Add(WriteByte(buffer, index, 3, ClampByte(outA)));
statements.Add(Expression.PostIncrementAssign(x));
var breakLabel = Expression.Label("break");
var loop = Expression.Loop(
Expression.IfThenElse(
Expression.LessThan(x, width),
Expression.Block(statements),
Expression.Break(breakLabel)),
breakLabel);
var locals = new List<ParameterExpression> { x, index, alphaRaw, transparent, scale, outA, alphaScale };
locals.AddRange(inputs);
locals.AddRange(slots);
var body = Expression.Block(locals, Expression.Assign(x, Constant(0)), loop);
var lambda = Expression.Lambda<CpuKernel.RowDelegate>(body, buffer, width, rowBase, y, uniforms);
return new CpuKernel(lambda.Compile());
}
private sealed record Context(
ParameterExpression X,
ParameterExpression Y,
ParameterExpression Uniforms,
ParameterExpression[] Inputs,
ParameterExpression[] Slots);
private static Expression Build(KExpr expression, Context context)
{
switch (expression)
{
case KConst value:
return Constant(value.Value);
case KInput input:
return context.Inputs[(int)input.Channel];
case KCoord coord:
return coord.Axis == KAxis.X ? ToDouble(context.X) : context.Y;
case KUniformRef uniform:
return Expression.ArrayIndex(context.Uniforms, Constant((int)uniform.Uniform));
case KLocalRef local:
return context.Slots[local.Slot];
case KNegate negate:
return Expression.Negate(Build(negate.Operand, context));
case KArith arithmetic:
return BuildArithmetic(arithmetic, context);
case KCall call:
return BuildCall(call, context);
case KSelect select:
return Select(BuildBool(select.Condition, context), Build(select.WhenTrue, context), Build(select.WhenFalse, context));
}
throw new KernelUnsupportedException("Unsupported CPU expression.");
}
private static Expression BuildArithmetic(KArith arithmetic, Context context)
{
var left = Build(arithmetic.Left, context);
var right = Build(arithmetic.Right, context);
return arithmetic.Op switch
{
KArithOp.Add => Expression.Add(left, right),
KArithOp.Subtract => Expression.Subtract(left, right),
KArithOp.Multiply => Expression.Multiply(left, right),
KArithOp.Divide => Expression.Divide(left, right),
KArithOp.Modulo => FlooredModulo(left, right),
KArithOp.Power => Expression.Call(Pow, left, right),
_ => throw new KernelUnsupportedException("Unsupported arithmetic operator."),
};
}
private static Expression BuildCall(KCall call, Context context)
{
var method = Functions[call.Func];
if (call.Arguments.Count == 1)
return Expression.Call(method, Build(call.Arguments[0], context));
return Expression.Call(method, Build(call.Arguments[0], context), Build(call.Arguments[1], context));
}
private static Expression BuildBool(KBool condition, Context context)
{
switch (condition)
{
case KBoolConst value:
return Expression.Constant(value.Value);
case KNot not:
return Expression.Not(BuildBool(not.Operand, context));
case KLogical logical:
return logical.IsAnd
? Expression.AndAlso(BuildBool(logical.Left, context), BuildBool(logical.Right, context))
: Expression.OrElse(BuildBool(logical.Left, context), BuildBool(logical.Right, context));
case KCompare compare:
var left = Build(compare.Left, context);
var right = Build(compare.Right, context);
return compare.Op switch
{
KCompareOp.Less => Expression.LessThan(left, right),
KCompareOp.Greater => Expression.GreaterThan(left, right),
KCompareOp.LessEqual => Expression.LessThanOrEqual(left, right),
KCompareOp.GreaterEqual => Expression.GreaterThanOrEqual(left, right),
KCompareOp.Equal => Expression.Equal(left, right),
KCompareOp.NotEqual => Expression.NotEqual(left, right),
_ => throw new KernelUnsupportedException("Unsupported comparison."),
};
}
throw new KernelUnsupportedException("Unsupported CPU condition.");
}
private static Expression FlooredModulo(Expression left, Expression right) =>
Expression.Subtract(left, Expression.Multiply(Expression.Call(Floor, Expression.Divide(left, right)), right));
private static Expression Select(Expression condition, Expression whenTrue, Expression whenFalse) =>
Expression.Condition(condition, whenTrue, whenFalse);
private static Expression ClampByte(Expression value) =>
Expression.Call(Clamp, value, Constant(0d), Constant(255d));
private static Expression ReadByte(ParameterExpression buffer, ParameterExpression index, int offset) =>
Expression.ArrayIndex(buffer, offset == 0 ? index : Expression.Add(index, Constant(offset)));
private static Expression WriteByte(ParameterExpression buffer, ParameterExpression index, int offset, Expression value) =>
Expression.Assign(
Expression.ArrayAccess(buffer, offset == 0 ? index : Expression.Add(index, Constant(offset))),
Expression.Convert(value, typeof(byte)));
private static Expression ToDouble(Expression value) => Expression.Convert(value, typeof(double));
private static ConstantExpression Constant(double value) => Expression.Constant(value, typeof(double));
private static ConstantExpression Constant(int value) => Expression.Constant(value, typeof(int));
private static MethodInfo Unary(string name) => typeof(Math).GetMethod(name, [typeof(double)])!;
private static MethodInfo Binary(string name) => typeof(Math).GetMethod(name, [typeof(double), typeof(double)])!;
}
}
+29
ファイルの表示
@@ -0,0 +1,29 @@
using System;
using Vortice.Direct2D1;
using YukkuriMovieMaker.Commons;
namespace LuaScript.Engine.Kernel
{
internal sealed class GpuKernel : IDisposable
{
private readonly GpuKernelEffect _effect;
private readonly float[] _packed = new float[HlslKernelEmitter.ConstantFloatCount];
private readonly byte[] _bytes = new byte[HlslKernelEmitter.ConstantFloatCount * sizeof(float)];
public GpuKernel(IGraphicsDevicesAndContext devices, KernelProgram program)
=> _effect = new GpuKernelEffect(devices, HlslKernelEmitter.Emit(program));
public bool IsReady => _effect.IsReady;
public ID2D1Image Apply(ID2D1Image input, double[] uniforms)
{
KernelUniformBinding.Pack(uniforms, _packed);
Buffer.BlockCopy(_packed, 0, _bytes, 0, _bytes.Length);
_effect.SetConstants(_bytes);
_effect.SetInput(0, input, true);
return _effect.Output;
}
public void Dispose() => _effect.Dispose();
}
}
+193
ファイルの表示
@@ -0,0 +1,193 @@
using System;
using System.Collections.Generic;
using System.Runtime.InteropServices;
using System.Text;
using System.Threading;
using Vortice;
using Vortice.D3DCompiler;
using Vortice.Direct2D1;
using Vortice.Direct3D;
using Vortice.Mathematics;
using YukkuriMovieMaker.Commons;
namespace LuaScript.Engine.Kernel
{
internal sealed class GpuKernelEffect : ID2D1Effect
{
private const int ConstantsIndex = 0;
private const int InitializedIndex = 1;
[StructLayout(LayoutKind.Sequential)]
private unsafe struct ConstantBuffer
{
public fixed float Values[HlslKernelEmitter.ConstantFloatCount];
}
[CustomEffect(1, null, null, null, null)]
private sealed class Impl(Guid guid, string hlsl) : CustomEffectBase, ID2D1DrawTransform
{
private ConstantBuffer _constants;
private ID2D1DrawInfo? _drawInfo;
[CustomEffectProperty(PropertyType.Blob, ConstantsIndex)]
public byte[] Constants
{
get => ToBytes(_constants);
set
{
FromBytes(value, ref _constants);
_drawInfo?.SetPixelShaderConstantBuffer(in _constants);
}
}
[CustomEffectProperty(PropertyType.Bool, InitializedIndex)]
public bool Initialized { get; private set; }
public override void Initialize(ID2D1EffectContext effectContext, ID2D1TransformGraph transformGraph)
{
byte[] source = Encoding.ASCII.GetBytes(hlsl);
var result = Compiler.Compile(source, "main", string.Empty, "ps_4_1", out var bytecode, out var errors);
if (result.Failure || bytecode is null)
{
Initialized = false;
Log.Default.Write("LuaScript: GPU kernel shader compilation failed.\n" + (errors?.AsString() ?? string.Empty));
errors?.Dispose();
bytecode?.Dispose();
return;
}
try
{
byte[] shader = bytecode.AsBytes();
effectContext.LoadPixelShader(guid, shader, shader.Length);
transformGraph.SetSingleTransformNode(this);
Initialized = true;
}
finally
{
errors?.Dispose();
bytecode.Dispose();
}
}
public void SetDrawInfo(ID2D1DrawInfo drawInfo)
{
_drawInfo = drawInfo;
drawInfo.SetPixelShader(guid, PixelOptions.None);
drawInfo.SetInputDescription(0, new InputDescription { Filter = (Filter)21, LevelOfDetailCount = 1 });
drawInfo.SetPixelShaderConstantBuffer(in _constants);
}
public int GetInputCount() => 1;
public void MapOutputRectToInputRects(RawRect outputRect, RawRect[] inputRects) =>
inputRects[0] = outputRect;
public void MapInputRectsToOutputRect(RawRect[] inputRects, RawRect[] inputOpaqueSubRects, out RawRect outputRect, out RawRect outputOpaqueSubRect)
{
outputRect = inputRects[0];
outputOpaqueSubRect = default;
}
public RawRect MapInvalidRect(int inputIndex, RawRect invalidInputRect) => invalidInputRect;
private static unsafe byte[] ToBytes(ConstantBuffer constants)
{
byte[] bytes = new byte[sizeof(ConstantBuffer)];
fixed (byte* destination = bytes)
*(ConstantBuffer*)destination = constants;
return bytes;
}
private static unsafe void FromBytes(byte[] bytes, ref ConstantBuffer constants)
{
int length = Math.Min(bytes.Length, sizeof(ConstantBuffer));
fixed (byte* source = bytes)
fixed (ConstantBuffer* destination = &constants)
Buffer.MemoryCopy(source, destination, sizeof(ConstantBuffer), length);
}
}
private sealed class Manager
{
private readonly Lock _locker = new();
private readonly Dictionary<int, Dictionary<string, (Guid Guid, int Count)>> _registered = [];
public Guid Acquire(IGraphicsDevicesAndContext devices, string hlsl)
{
lock (_locker)
{
int device = devices.GetHashCode();
if (!_registered.TryGetValue(device, out var byHlsl))
{
byHlsl = [];
_registered[device] = byHlsl;
}
if (byHlsl.TryGetValue(hlsl, out var entry))
{
byHlsl[hlsl] = (entry.Guid, entry.Count + 1);
return entry.Guid;
}
var guid = Guid.NewGuid();
byHlsl[hlsl] = (guid, 1);
((ID2D1Factory1)devices.D2D.Factory).RegisterEffect<Impl>(() => new Impl(guid, hlsl), guid);
return guid;
}
}
public void Release(IGraphicsDevicesAndContext devices, string hlsl)
{
lock (_locker)
{
int device = devices.GetHashCode();
if (!_registered.TryGetValue(device, out var byHlsl) || !byHlsl.TryGetValue(hlsl, out var entry))
return;
if (entry.Count > 1)
{
byHlsl[hlsl] = (entry.Guid, entry.Count - 1);
return;
}
byHlsl.Remove(hlsl);
((ID2D1Factory1)devices.D2D.Factory).UnregisterEffect(entry.Guid);
}
}
}
private static readonly Manager Effects = new();
private readonly IGraphicsDevicesAndContext _devices;
private readonly string _hlsl;
public GpuKernelEffect(IGraphicsDevicesAndContext devices, string hlsl)
: base(Create(devices, hlsl))
{
_devices = devices;
_hlsl = hlsl;
}
public bool IsReady => NativePointer != nint.Zero && ((ID2D1Properties)this).GetBoolValue(InitializedIndex);
public void SetConstants(byte[] bytes) => ((ID2D1Properties)this).SetValue(ConstantsIndex, bytes);
private static nint Create(IGraphicsDevicesAndContext devices, string hlsl)
{
try
{
var guid = Effects.Acquire(devices, hlsl);
return ((ID2D1DeviceContext)devices.DeviceContext).CreateEffect(guid);
}
catch (Exception ex)
{
Log.Default.Write("LuaScript: failed to create GPU kernel effect.", ex);
return nint.Zero;
}
}
protected override void DisposeCore(nint nativePointer, bool disposing)
{
base.DisposeCore(nativePointer, disposing);
Effects.Release(_devices, _hlsl);
}
}
}
+225
ファイルの表示
@@ -0,0 +1,225 @@
using System.Globalization;
using System.Text;
namespace LuaScript.Engine.Kernel
{
internal static class HlslKernelEmitter
{
public const int ConstantVectorCount = 16;
public const int ConstantFloatCount = ConstantVectorCount * 4;
private static readonly string[] Intrinsics =
[
"abs", "floor", "ceil", "sqrt", "sin", "cos", "tan", "asin", "acos",
"atan", "atan2", "exp", "log", "pow", "min", "max", "fmod",
];
public static string Emit(KernelProgram program)
{
var builder = new StringBuilder(1024);
builder.Append("Texture2D InputTexture : register(t0);\n");
builder.Append("SamplerState InputSampler : register(s0);\n");
builder.Append("cbuffer constants : register(b0)\n{\n");
builder.Append(" float4 uniforms[").Append(ConstantVectorCount).Append("];\n");
builder.Append("};\n\n");
builder.Append("float4 main(float4 pos : SV_POSITION, float4 posScene : SCENE_POSITION, float4 uv : TEXCOORD0) : SV_Target\n{\n");
builder.Append(" float4 src = InputTexture.Sample(InputSampler, uv.xy);\n");
builder.Append(" float srcA = src.a;\n");
builder.Append(" float invA = srcA <= 0.0 ? 0.0 : 1.0 / srcA;\n");
builder.Append(" float inR = clamp(src.r * invA * 255.0, 0.0, 255.0);\n");
builder.Append(" float inG = clamp(src.g * invA * 255.0, 0.0, 255.0);\n");
builder.Append(" float inB = clamp(src.b * invA * 255.0, 0.0, 255.0);\n");
builder.Append(" float inA = srcA * 255.0;\n");
builder.Append(" float px = uv.x * ").Append(Uniform(KernelUniform.Width)).Append(";\n");
builder.Append(" float py = uv.y * ").Append(Uniform(KernelUniform.Height)).Append(";\n");
for (int i = 0; i < program.Bindings.Count; i++)
{
builder.Append(" float slot").Append(i).Append(" = ");
EmitExpression(builder, program.Bindings[i]);
builder.Append(";\n");
}
builder.Append(" float outA = ");
EmitExpression(builder, program.OutputA);
builder.Append(";\n");
builder.Append(" float alphaK = clamp(outA, 0.0, 255.0) / 255.0;\n");
builder.Append(" float oR = clamp((");
EmitExpression(builder, program.OutputR);
builder.Append(") * alphaK, 0.0, 255.0) / 255.0;\n");
builder.Append(" float oG = clamp((");
EmitExpression(builder, program.OutputG);
builder.Append(") * alphaK, 0.0, 255.0) / 255.0;\n");
builder.Append(" float oB = clamp((");
EmitExpression(builder, program.OutputB);
builder.Append(") * alphaK, 0.0, 255.0) / 255.0;\n");
builder.Append(" float oA = clamp(outA, 0.0, 255.0) / 255.0;\n");
builder.Append(" return float4(oR, oG, oB, oA);\n}\n");
return builder.ToString();
}
private static void EmitExpression(StringBuilder builder, KExpr expression)
{
switch (expression)
{
case KConst value:
builder.Append(Number(value.Value));
return;
case KInput input:
builder.Append(input.Channel switch
{
KChannel.R => "inR",
KChannel.G => "inG",
KChannel.B => "inB",
_ => "inA",
});
return;
case KCoord coord:
builder.Append(coord.Axis == KAxis.X ? "px" : "py");
return;
case KUniformRef uniform:
builder.Append(Uniform(uniform.Uniform));
return;
case KLocalRef local:
builder.Append("slot").Append(local.Slot);
return;
case KNegate negate:
builder.Append("(-(");
EmitExpression(builder, negate.Operand);
builder.Append("))");
return;
case KArith arithmetic:
EmitArithmetic(builder, arithmetic);
return;
case KCall call:
EmitCall(builder, call);
return;
case KSelect select:
builder.Append('(');
EmitCondition(builder, select.Condition);
builder.Append(" ? (");
EmitExpression(builder, select.WhenTrue);
builder.Append(") : (");
EmitExpression(builder, select.WhenFalse);
builder.Append("))");
return;
}
throw new KernelUnsupportedException("Unsupported HLSL expression.");
}
private static void EmitArithmetic(StringBuilder builder, KArith arithmetic)
{
if (arithmetic.Op == KArithOp.Power)
{
builder.Append("pow(");
EmitExpression(builder, arithmetic.Left);
builder.Append(", ");
EmitExpression(builder, arithmetic.Right);
builder.Append(')');
return;
}
if (arithmetic.Op == KArithOp.Modulo)
{
builder.Append('(');
EmitExpression(builder, arithmetic.Left);
builder.Append(" - floor((");
EmitExpression(builder, arithmetic.Left);
builder.Append(") / (");
EmitExpression(builder, arithmetic.Right);
builder.Append(")) * (");
EmitExpression(builder, arithmetic.Right);
builder.Append("))");
return;
}
builder.Append('(');
EmitExpression(builder, arithmetic.Left);
builder.Append(arithmetic.Op switch
{
KArithOp.Add => " + ",
KArithOp.Subtract => " - ",
KArithOp.Multiply => " * ",
KArithOp.Divide => " / ",
_ => throw new KernelUnsupportedException("Unsupported arithmetic operator."),
});
EmitExpression(builder, arithmetic.Right);
builder.Append(')');
}
private static void EmitCall(StringBuilder builder, KCall call)
{
builder.Append(Intrinsics[(int)call.Func]).Append('(');
for (int i = 0; i < call.Arguments.Count; i++)
{
if (i > 0)
builder.Append(", ");
EmitExpression(builder, call.Arguments[i]);
}
builder.Append(')');
}
private static void EmitCondition(StringBuilder builder, KBool condition)
{
switch (condition)
{
case KBoolConst value:
builder.Append(value.Value ? "true" : "false");
return;
case KNot not:
builder.Append("(!(");
EmitCondition(builder, not.Operand);
builder.Append("))");
return;
case KLogical logical:
builder.Append('(');
EmitCondition(builder, logical.Left);
builder.Append(logical.IsAnd ? " && " : " || ");
EmitCondition(builder, logical.Right);
builder.Append(')');
return;
case KCompare compare:
builder.Append('(');
EmitExpression(builder, compare.Left);
builder.Append(compare.Op switch
{
KCompareOp.Less => " < ",
KCompareOp.Greater => " > ",
KCompareOp.LessEqual => " <= ",
KCompareOp.GreaterEqual => " >= ",
KCompareOp.Equal => " == ",
_ => " != ",
});
EmitExpression(builder, compare.Right);
builder.Append(')');
return;
}
throw new KernelUnsupportedException("Unsupported HLSL condition.");
}
private static string Uniform(KernelUniform uniform)
{
int index = (int)uniform;
return $"uniforms[{index / 4}].{"xyzw"[index % 4]}";
}
private static string Number(double value)
{
if (double.IsPositiveInfinity(value))
return "3.4028235e38";
if (double.IsNegativeInfinity(value))
return "-3.4028235e38";
if (double.IsNaN(value))
return "(0.0 / 0.0)";
string text = value.ToString("R", CultureInfo.InvariantCulture);
if (!text.Contains('.') && !text.Contains('e') && !text.Contains('E'))
text += ".0";
return text;
}
}
}
+357
ファイルの表示
@@ -0,0 +1,357 @@
using System;
using System.Collections.Generic;
namespace LuaScript.Engine.Kernel
{
internal sealed class KernelExtractor
{
private readonly record struct FuncSpec(KFunc Func, int MinArgs, int MaxArgs);
private static readonly Dictionary<string, FuncSpec> MathFunctions = new(StringComparer.Ordinal)
{
["abs"] = new(KFunc.Abs, 1, 1),
["floor"] = new(KFunc.Floor, 1, 1),
["ceil"] = new(KFunc.Ceil, 1, 1),
["sqrt"] = new(KFunc.Sqrt, 1, 1),
["sin"] = new(KFunc.Sin, 1, 1),
["cos"] = new(KFunc.Cos, 1, 1),
["tan"] = new(KFunc.Tan, 1, 1),
["asin"] = new(KFunc.Asin, 1, 1),
["acos"] = new(KFunc.Acos, 1, 1),
["atan"] = new(KFunc.Atan, 1, 1),
["atan2"] = new(KFunc.Atan2, 2, 2),
["exp"] = new(KFunc.Exp, 1, 1),
["log"] = new(KFunc.Log, 1, 1),
["pow"] = new(KFunc.Pow, 2, 2),
["fmod"] = new(KFunc.Fmod, 2, 2),
["min"] = new(KFunc.Min, 2, int.MaxValue),
["max"] = new(KFunc.Max, 2, int.MaxValue),
};
private readonly List<KExpr> _bindings = [];
private readonly Dictionary<string, int> _scope = new(StringComparer.Ordinal);
private readonly SortedSet<KernelUniform> _uniforms = [];
private string _widthVariable = string.Empty;
private string _heightVariable = string.Empty;
private bool _coordsEnabled;
public static KernelProgram? TryExtract(string runnableScript)
{
try
{
return new KernelExtractor().Extract(runnableScript);
}
catch (KernelUnsupportedException)
{
return null;
}
}
private KernelProgram? Extract(string runnableScript)
{
var block = LuaParser.Parse(runnableScript);
int index = 0;
while (index < block.Count && block[index] is LocalStmt prelude)
{
BindLocal(prelude);
index++;
}
if (index >= block.Count || block[index] is not NumericForStmt outer)
return null;
if (index + 1 != block.Count)
return null;
if (!TryAxis(outer, out string outerVar, out KAxis outerAxis))
return null;
if (outer.Body.Count != 1 || outer.Body[0] is not NumericForStmt inner)
return null;
if (!TryAxis(inner, out string innerVar, out KAxis innerAxis))
return null;
if (outerAxis == innerAxis)
return null;
_widthVariable = outerAxis == KAxis.X ? outerVar : innerVar;
_heightVariable = outerAxis == KAxis.Y ? outerVar : innerVar;
return BuildKernel(inner.Body);
}
private KernelProgram? BuildKernel(IReadOnlyList<LuaStmt> body)
{
if (body.Count < 2)
return null;
if (body[0] is not LocalStmt sample || sample.Values.Count != 1 ||
!IsGetPixel(sample.Values[0]))
return null;
if (sample.Names.Count is < 1 or > 4)
return null;
_coordsEnabled = true;
for (int i = 0; i < sample.Names.Count; i++)
{
EnsureNotCoordinateName(sample.Names[i]);
_scope[sample.Names[i]] = AddBinding(new KInput((KChannel)i));
}
for (int i = 1; i < body.Count - 1; i++)
{
switch (body[i])
{
case LocalStmt local:
BindLocal(local);
break;
case AssignStmt assign:
BindAssign(assign);
break;
default:
return null;
}
}
if (body[^1] is not CallStmt { Call: var call } || !IsObjectMethod(call, "setpixel"))
return null;
if (call.Arguments.Count is < 5 or > 6)
return null;
if (!IsCoordinate(call.Arguments[0], KAxis.X) || !IsCoordinate(call.Arguments[1], KAxis.Y))
return null;
var outR = Lower(call.Arguments[2]);
var outG = Lower(call.Arguments[3]);
var outB = Lower(call.Arguments[4]);
var outA = call.Arguments.Count == 6 ? Lower(call.Arguments[5]) : new KConst(255d);
return new KernelProgram(_bindings, outR, outG, outB, outA, [.. _uniforms]);
}
private void BindLocal(LocalStmt local)
{
if (local.Values.Count == 1 && IsGetPixel(local.Values[0]))
throw new KernelUnsupportedException("Unexpected pixel sample.");
if (local.Names.Count != local.Values.Count)
throw new KernelUnsupportedException("Multiple-value assignment is not supported.");
var lowered = new KExpr[local.Values.Count];
for (int i = 0; i < local.Values.Count; i++)
lowered[i] = Lower(local.Values[i]);
for (int i = 0; i < local.Names.Count; i++)
{
EnsureNotCoordinateName(local.Names[i]);
_scope[local.Names[i]] = AddBinding(lowered[i]);
}
}
private void BindAssign(AssignStmt assign)
{
if (assign.Targets.Count != assign.Values.Count)
throw new KernelUnsupportedException("Unbalanced assignment is not supported.");
foreach (var target in assign.Targets)
{
if (target is not NameExpr name || !_scope.ContainsKey(name.Name))
throw new KernelUnsupportedException("Assignment target must be a local variable.");
}
var lowered = new KExpr[assign.Values.Count];
for (int i = 0; i < assign.Values.Count; i++)
lowered[i] = Lower(assign.Values[i]);
for (int i = 0; i < assign.Targets.Count; i++)
_scope[((NameExpr)assign.Targets[i]).Name] = AddBinding(lowered[i]);
}
private void EnsureNotCoordinateName(string name)
{
if (string.Equals(name, _widthVariable, StringComparison.Ordinal) ||
string.Equals(name, _heightVariable, StringComparison.Ordinal))
throw new KernelUnsupportedException("Local variable shadows a loop coordinate.");
}
private int AddBinding(KExpr expression)
{
_bindings.Add(expression);
return _bindings.Count - 1;
}
private KExpr Lower(LuaExpr expression)
{
switch (expression)
{
case NumberExpr number:
return new KConst(number.Value);
case NameExpr name:
return LowerName(name.Name);
case MemberExpr member:
return LowerMember(member);
case CallExpr call:
return LowerCall(call);
case UnaryExpr { Operator: "-" } unary:
return new KNegate(Lower(unary.Operand));
case BinaryExpr binary:
return LowerBinary(binary);
}
throw new KernelUnsupportedException("Unsupported expression in pixel kernel.");
}
private KExpr LowerName(string name)
{
if (_scope.TryGetValue(name, out int slot))
return new KLocalRef(slot);
if (_coordsEnabled && string.Equals(name, _widthVariable, StringComparison.Ordinal))
return new KCoord(KAxis.X);
if (_coordsEnabled && string.Equals(name, _heightVariable, StringComparison.Ordinal))
return new KCoord(KAxis.Y);
if (KernelUniforms.TryResolveGlobal(name, out var uniform))
return UseUniform(uniform);
throw new KernelUnsupportedException($"Unknown identifier '{name}'.");
}
private KExpr LowerMember(MemberExpr member)
{
if (member.Target is NameExpr { Name: "math" })
{
return member.Name switch
{
"pi" => new KConst(Math.PI),
"huge" => new KConst(double.PositiveInfinity),
_ => throw new KernelUnsupportedException($"Unsupported math field '{member.Name}'."),
};
}
if (member.Target is NameExpr target && KernelUniforms.TryResolveMember(target.Name, member.Name, out var uniform))
return UseUniform(uniform);
throw new KernelUnsupportedException("Unsupported member access in pixel kernel.");
}
private KExpr LowerCall(CallExpr call)
{
if (call.Target is not MemberExpr { Target: NameExpr { Name: "math" }, Name: var function } ||
!MathFunctions.TryGetValue(function, out var spec))
throw new KernelUnsupportedException("Unsupported function call in pixel kernel.");
int count = call.Arguments.Count;
if (count < spec.MinArgs || count > spec.MaxArgs)
throw new KernelUnsupportedException($"Wrong argument count for 'math.{function}'.");
var arguments = new KExpr[count];
for (int i = 0; i < count; i++)
arguments[i] = Lower(call.Arguments[i]);
if (spec.Func is KFunc.Min or KFunc.Max)
{
var folded = arguments[0];
for (int i = 1; i < count; i++)
folded = new KCall(spec.Func, [folded, arguments[i]]);
return folded;
}
return new KCall(spec.Func, arguments);
}
private KExpr LowerBinary(BinaryExpr binary)
{
switch (binary.Operator)
{
case "+": return new KArith(KArithOp.Add, Lower(binary.Left), Lower(binary.Right));
case "-": return new KArith(KArithOp.Subtract, Lower(binary.Left), Lower(binary.Right));
case "*": return new KArith(KArithOp.Multiply, Lower(binary.Left), Lower(binary.Right));
case "/": return new KArith(KArithOp.Divide, Lower(binary.Left), Lower(binary.Right));
case "%": return new KArith(KArithOp.Modulo, Lower(binary.Left), Lower(binary.Right));
case "^": return new KArith(KArithOp.Power, Lower(binary.Left), Lower(binary.Right));
case "or" when binary.Left is BinaryExpr { Operator: "and" } conditional:
return new KSelect(LowerBool(conditional.Left), Lower(conditional.Right), Lower(binary.Right));
}
throw new KernelUnsupportedException($"Unsupported operator '{binary.Operator}' in value position.");
}
private KBool LowerBool(LuaExpr expression)
{
switch (expression)
{
case BoolExpr boolean:
return new KBoolConst(boolean.Value);
case UnaryExpr { Operator: "not" } unary:
return new KNot(LowerBool(unary.Operand));
case BinaryExpr { Operator: "and" } conjunction:
return new KLogical(true, LowerBool(conjunction.Left), LowerBool(conjunction.Right));
case BinaryExpr { Operator: "or" } disjunction:
return new KLogical(false, LowerBool(disjunction.Left), LowerBool(disjunction.Right));
case BinaryExpr binary when TryCompareOp(binary.Operator, out var op):
return new KCompare(op, Lower(binary.Left), Lower(binary.Right));
case NameExpr name when IsCheck(LowerName(name.Name)):
return new KCompare(KCompareOp.NotEqual, LowerName(name.Name), new KConst(0d));
case MemberExpr member when IsCheck(LowerMember(member)):
return new KCompare(KCompareOp.NotEqual, LowerMember(member), new KConst(0d));
}
throw new KernelUnsupportedException("Unsupported condition in pixel kernel.");
}
private static bool IsCheck(KExpr expression) =>
expression is KUniformRef { Uniform: KernelUniform.Check0 or KernelUniform.Check1 or KernelUniform.Check2 or KernelUniform.Check3 };
private static bool TryCompareOp(string symbol, out KCompareOp op)
{
switch (symbol)
{
case "<": op = KCompareOp.Less; return true;
case ">": op = KCompareOp.Greater; return true;
case "<=": op = KCompareOp.LessEqual; return true;
case ">=": op = KCompareOp.GreaterEqual; return true;
case "==": op = KCompareOp.Equal; return true;
case "~=": op = KCompareOp.NotEqual; return true;
default: op = default; return false;
}
}
private KExpr UseUniform(KernelUniform uniform)
{
_uniforms.Add(uniform);
return new KUniformRef(uniform);
}
private bool TryAxis(NumericForStmt loop, out string variable, out KAxis axis)
{
variable = loop.Variable;
axis = default;
if (loop.Start is not NumberExpr { Value: 0d })
return false;
if (loop.Step is not null && loop.Step is not NumberExpr { Value: 1d })
return false;
if (loop.Stop is not BinaryExpr { Operator: "-", Right: NumberExpr { Value: 1d } } bound)
return false;
if (bound.Left is not MemberExpr { Target: NameExpr { Name: "obj" }, Name: var field })
return false;
if (!KernelUniforms.TryResolveMember("obj", field, out var uniform))
return false;
if (uniform == KernelUniform.Width)
{
axis = KAxis.X;
return true;
}
if (uniform == KernelUniform.Height)
{
axis = KAxis.Y;
return true;
}
return false;
}
private bool IsGetPixel(LuaExpr expression) =>
expression is CallExpr call && IsObjectMethod(call, "getpixel") &&
call.Arguments.Count == 2 &&
IsCoordinate(call.Arguments[0], KAxis.X) && IsCoordinate(call.Arguments[1], KAxis.Y);
private bool IsCoordinate(LuaExpr expression, KAxis axis) =>
expression is NameExpr name &&
string.Equals(name.Name, axis == KAxis.X ? _widthVariable : _heightVariable, StringComparison.Ordinal);
private static bool IsObjectMethod(CallExpr call, string method) =>
call.Target is MemberExpr { Target: NameExpr { Name: "obj" }, Name: var name } &&
string.Equals(name, method, StringComparison.Ordinal);
}
}
+97
ファイルの表示
@@ -0,0 +1,97 @@
using System.Collections.Generic;
namespace LuaScript.Engine.Kernel
{
internal enum KChannel
{
R,
G,
B,
A,
}
internal enum KAxis
{
X,
Y,
}
internal enum KArithOp
{
Add,
Subtract,
Multiply,
Divide,
Modulo,
Power,
}
internal enum KCompareOp
{
Less,
Greater,
LessEqual,
GreaterEqual,
Equal,
NotEqual,
}
internal enum KFunc
{
Abs,
Floor,
Ceil,
Sqrt,
Sin,
Cos,
Tan,
Asin,
Acos,
Atan,
Atan2,
Exp,
Log,
Pow,
Min,
Max,
Fmod,
}
internal abstract record KExpr;
internal sealed record KConst(double Value) : KExpr;
internal sealed record KInput(KChannel Channel) : KExpr;
internal sealed record KCoord(KAxis Axis) : KExpr;
internal sealed record KUniformRef(KernelUniform Uniform) : KExpr;
internal sealed record KLocalRef(int Slot) : KExpr;
internal sealed record KArith(KArithOp Op, KExpr Left, KExpr Right) : KExpr;
internal sealed record KNegate(KExpr Operand) : KExpr;
internal sealed record KCall(KFunc Func, IReadOnlyList<KExpr> Arguments) : KExpr;
internal sealed record KSelect(KBool Condition, KExpr WhenTrue, KExpr WhenFalse) : KExpr;
internal abstract record KBool;
internal sealed record KCompare(KCompareOp Op, KExpr Left, KExpr Right) : KBool;
internal sealed record KLogical(bool IsAnd, KBool Left, KBool Right) : KBool;
internal sealed record KNot(KBool Operand) : KBool;
internal sealed record KBoolConst(bool Value) : KBool;
internal sealed record KernelProgram(
IReadOnlyList<KExpr> Bindings,
KExpr OutputR,
KExpr OutputG,
KExpr OutputB,
KExpr OutputA,
IReadOnlyList<KernelUniform> Uniforms);
}
+155
ファイルの表示
@@ -0,0 +1,155 @@
using System;
using System.Collections.Generic;
namespace LuaScript.Engine.Kernel
{
internal enum KernelUniform
{
Width,
Height,
HalfWidth,
HalfHeight,
CenterX,
CenterY,
CenterZ,
Diagonal,
X,
Y,
Z,
Ox,
Oy,
Oz,
Sx,
Sy,
Sz,
Zoom,
Aspect,
Alpha,
Rx,
Ry,
Rz,
Rxr,
Ryr,
Rzr,
Track0,
Track1,
Track2,
Track3,
Slider0,
Slider1,
Slider2,
Slider3,
Check0,
Check1,
Check2,
Check3,
Color,
Time,
Frame,
TotalFrame,
TotalTime,
T,
Framerate,
Layer,
Index,
Num,
SceneWidth,
SceneHeight,
SceneCenterX,
SceneCenterY,
TimelineFrame,
TimelineTime,
}
internal static class KernelUniforms
{
public static int Count { get; } = Enum.GetValues<KernelUniform>().Length;
private static readonly Dictionary<string, KernelUniform> Globals = new(StringComparer.Ordinal)
{
["time"] = KernelUniform.Time,
["frame"] = KernelUniform.Frame,
["totalframe"] = KernelUniform.TotalFrame,
["framerate"] = KernelUniform.Framerate,
["timelineframe"] = KernelUniform.TimelineFrame,
["timelinetime"] = KernelUniform.TimelineTime,
["layer"] = KernelUniform.Layer,
["color"] = KernelUniform.Color,
};
private static readonly Dictionary<string, KernelUniform> ObjectFields = new(StringComparer.Ordinal)
{
["w"] = KernelUniform.Width,
["h"] = KernelUniform.Height,
["hw"] = KernelUniform.HalfWidth,
["hh"] = KernelUniform.HalfHeight,
["cx"] = KernelUniform.CenterX,
["cy"] = KernelUniform.CenterY,
["cz"] = KernelUniform.CenterZ,
["diagonal"] = KernelUniform.Diagonal,
["x"] = KernelUniform.X,
["y"] = KernelUniform.Y,
["z"] = KernelUniform.Z,
["ox"] = KernelUniform.Ox,
["oy"] = KernelUniform.Oy,
["oz"] = KernelUniform.Oz,
["sx"] = KernelUniform.Sx,
["sy"] = KernelUniform.Sy,
["sz"] = KernelUniform.Sz,
["zoom"] = KernelUniform.Zoom,
["aspect"] = KernelUniform.Aspect,
["alpha"] = KernelUniform.Alpha,
["rx"] = KernelUniform.Rx,
["ry"] = KernelUniform.Ry,
["rz"] = KernelUniform.Rz,
["rxr"] = KernelUniform.Rxr,
["ryr"] = KernelUniform.Ryr,
["rzr"] = KernelUniform.Rzr,
["track0"] = KernelUniform.Track0,
["track1"] = KernelUniform.Track1,
["track2"] = KernelUniform.Track2,
["track3"] = KernelUniform.Track3,
["slider0"] = KernelUniform.Slider0,
["slider1"] = KernelUniform.Slider1,
["slider2"] = KernelUniform.Slider2,
["slider3"] = KernelUniform.Slider3,
["check0"] = KernelUniform.Check0,
["check1"] = KernelUniform.Check1,
["check2"] = KernelUniform.Check2,
["check3"] = KernelUniform.Check3,
["time"] = KernelUniform.Time,
["frame"] = KernelUniform.Frame,
["totalframe"] = KernelUniform.TotalFrame,
["totaltime"] = KernelUniform.TotalTime,
["t"] = KernelUniform.T,
["framerate"] = KernelUniform.Framerate,
["layer"] = KernelUniform.Layer,
["index"] = KernelUniform.Index,
["num"] = KernelUniform.Num,
};
private static readonly Dictionary<string, KernelUniform> SceneFields = new(StringComparer.Ordinal)
{
["width"] = KernelUniform.SceneWidth,
["height"] = KernelUniform.SceneHeight,
["cx"] = KernelUniform.SceneCenterX,
["cy"] = KernelUniform.SceneCenterY,
};
public static bool TryResolveGlobal(string name, out KernelUniform uniform) =>
Globals.TryGetValue(name, out uniform);
public static bool TryResolveMember(string target, string field, out KernelUniform uniform)
{
uniform = default;
return target switch
{
"obj" => ObjectFields.TryGetValue(field, out uniform),
"scene" => SceneFields.TryGetValue(field, out uniform),
_ => false,
};
}
public static string Field(KernelUniform uniform) => "u_" + uniform;
}
}
+76
ファイルの表示
@@ -0,0 +1,76 @@
using System;
namespace LuaScript.Engine.Kernel
{
internal static class KernelUniformBinding
{
public static double[] Create() => new double[KernelUniforms.Count];
public static void Fill(AviUtlScriptContext ctx, double[] values)
{
values[(int)KernelUniform.Width] = ctx.ImageWidth;
values[(int)KernelUniform.Height] = ctx.ImageHeight;
values[(int)KernelUniform.HalfWidth] = ctx.ImageWidth / 2d;
values[(int)KernelUniform.HalfHeight] = ctx.ImageHeight / 2d;
values[(int)KernelUniform.CenterX] = ctx.ImageWidth / 2d;
values[(int)KernelUniform.CenterY] = ctx.ImageHeight / 2d;
values[(int)KernelUniform.CenterZ] = 0d;
values[(int)KernelUniform.Diagonal] = Math.Sqrt((double)ctx.ImageWidth * ctx.ImageWidth + (double)ctx.ImageHeight * ctx.ImageHeight);
values[(int)KernelUniform.X] = ctx.X;
values[(int)KernelUniform.Y] = ctx.Y;
values[(int)KernelUniform.Z] = ctx.Z;
values[(int)KernelUniform.Ox] = ctx.Ox;
values[(int)KernelUniform.Oy] = ctx.Oy;
values[(int)KernelUniform.Oz] = ctx.Oz;
values[(int)KernelUniform.Sx] = ctx.Sx;
values[(int)KernelUniform.Sy] = ctx.Sy;
values[(int)KernelUniform.Sz] = 1d;
values[(int)KernelUniform.Zoom] = ctx.Zoom;
values[(int)KernelUniform.Aspect] = ctx.Aspect;
values[(int)KernelUniform.Alpha] = ctx.Alpha;
values[(int)KernelUniform.Rx] = ctx.Rx;
values[(int)KernelUniform.Ry] = ctx.Ry;
values[(int)KernelUniform.Rz] = ctx.Rz;
values[(int)KernelUniform.Rxr] = ctx.RxRad;
values[(int)KernelUniform.Ryr] = ctx.RyRad;
values[(int)KernelUniform.Rzr] = ctx.RzRad;
values[(int)KernelUniform.Track0] = ctx.Track0;
values[(int)KernelUniform.Track1] = ctx.Track1;
values[(int)KernelUniform.Track2] = ctx.Track2;
values[(int)KernelUniform.Track3] = ctx.Track3;
values[(int)KernelUniform.Slider0] = ctx.Slider0;
values[(int)KernelUniform.Slider1] = ctx.Slider1;
values[(int)KernelUniform.Slider2] = ctx.Slider2;
values[(int)KernelUniform.Slider3] = ctx.Slider3;
values[(int)KernelUniform.Check0] = ctx.Check0 ? 1d : 0d;
values[(int)KernelUniform.Check1] = ctx.Check1 ? 1d : 0d;
values[(int)KernelUniform.Check2] = ctx.Check2 ? 1d : 0d;
values[(int)KernelUniform.Check3] = ctx.Check3 ? 1d : 0d;
values[(int)KernelUniform.Color] = ctx.HasColor ? ctx.ColorValue : -1d;
values[(int)KernelUniform.Time] = ctx.Time;
values[(int)KernelUniform.Frame] = ctx.Frame;
values[(int)KernelUniform.TotalFrame] = ctx.TotalFrame;
values[(int)KernelUniform.TotalTime] = ctx.TotalTime;
values[(int)KernelUniform.T] = ctx.TotalFrame > 0 ? ctx.Frame / (double)ctx.TotalFrame : 0d;
values[(int)KernelUniform.Framerate] = ctx.Framerate;
values[(int)KernelUniform.Layer] = ctx.Layer;
values[(int)KernelUniform.Index] = ctx.Index;
values[(int)KernelUniform.Num] = ctx.Num;
values[(int)KernelUniform.SceneWidth] = ctx.SceneWidth;
values[(int)KernelUniform.SceneHeight] = ctx.SceneHeight;
values[(int)KernelUniform.SceneCenterX] = ctx.SceneWidth / 2d;
values[(int)KernelUniform.SceneCenterY] = ctx.SceneHeight / 2d;
values[(int)KernelUniform.TimelineFrame] = ctx.TimelineFrame;
values[(int)KernelUniform.TimelineTime] = ctx.TimelineTime;
}
public static void Pack(double[] values, float[] packed)
{
int count = Math.Min(values.Length, packed.Length);
for (int i = 0; i < count; i++)
packed[i] = (float)values[i];
for (int i = count; i < packed.Length; i++)
packed[i] = 0f;
}
}
}
+4
ファイルの表示
@@ -0,0 +1,4 @@
namespace LuaScript.Engine.Kernel
{
internal sealed class KernelUnsupportedException(string reason) : Exception(reason);
}
+45
ファイルの表示
@@ -0,0 +1,45 @@
using System.Collections.Generic;
namespace LuaScript.Engine.Kernel
{
internal abstract record LuaExpr;
internal sealed record NumberExpr(double Value) : LuaExpr;
internal sealed record BoolExpr(bool Value) : LuaExpr;
internal sealed record NilExpr : LuaExpr;
internal sealed record StringExpr(string Value) : LuaExpr;
internal sealed record NameExpr(string Name) : LuaExpr;
internal sealed record MemberExpr(LuaExpr Target, string Name) : LuaExpr;
internal sealed record IndexExpr(LuaExpr Target, LuaExpr Key) : LuaExpr;
internal sealed record CallExpr(LuaExpr Target, IReadOnlyList<LuaExpr> Arguments) : LuaExpr;
internal sealed record UnaryExpr(string Operator, LuaExpr Operand) : LuaExpr;
internal sealed record BinaryExpr(string Operator, LuaExpr Left, LuaExpr Right) : LuaExpr;
internal abstract record LuaStmt;
internal sealed record LocalStmt(IReadOnlyList<string> Names, IReadOnlyList<LuaExpr> Values) : LuaStmt;
internal sealed record AssignStmt(IReadOnlyList<LuaExpr> Targets, IReadOnlyList<LuaExpr> Values) : LuaStmt;
internal sealed record CallStmt(CallExpr Call) : LuaStmt;
internal sealed record IfClause(LuaExpr Condition, IReadOnlyList<LuaStmt> Body);
internal sealed record IfStmt(IReadOnlyList<IfClause> Clauses, IReadOnlyList<LuaStmt>? ElseBody) : LuaStmt;
internal sealed record NumericForStmt(
string Variable,
LuaExpr Start,
LuaExpr Stop,
LuaExpr? Step,
IReadOnlyList<LuaStmt> Body) : LuaStmt;
}
+310
ファイルの表示
@@ -0,0 +1,310 @@
using System;
using System.Collections.Generic;
using System.Globalization;
namespace LuaScript.Engine.Kernel
{
internal static class LuaLexer
{
private static readonly HashSet<string> Keywords = new(StringComparer.Ordinal)
{
"and", "break", "do", "else", "elseif", "end", "false", "for", "function",
"if", "in", "local", "nil", "not", "or", "repeat", "return", "then",
"true", "until", "while",
};
public static List<LuaToken> Tokenize(string source)
{
var tokens = new List<LuaToken>();
int i = 0;
int length = source.Length;
while (i < length)
{
char c = source[i];
if (c is ' ' or '\t' or '\r' or '\n' or '\f' or '\v')
{
i++;
continue;
}
if (c == '-' && i + 1 < length && source[i + 1] == '-')
{
i = SkipComment(source, i + 2);
continue;
}
if (c == '"' || c == '\'')
{
i = ReadShortString(source, i, tokens);
continue;
}
if (c == '[' && i + 1 < length && (source[i + 1] == '[' || source[i + 1] == '='))
{
int level = LongBracketLevel(source, i);
if (level >= 0)
{
i = ReadLongString(source, i, level, tokens);
continue;
}
}
if (char.IsDigit(c) || (c == '.' && i + 1 < length && char.IsDigit(source[i + 1])))
{
i = ReadNumber(source, i, tokens);
continue;
}
if (IsNameStart(c))
{
i = ReadName(source, i, tokens);
continue;
}
i = ReadSymbol(source, i, tokens);
}
tokens.Add(new LuaToken(LuaTokenKind.Eof, string.Empty, 0d));
return tokens;
}
private static int SkipComment(string source, int i)
{
int level = LongBracketLevel(source, i);
if (level >= 0)
return SkipLongBracket(source, i, level);
int length = source.Length;
while (i < length && source[i] != '\n')
i++;
return i;
}
private static int LongBracketLevel(string source, int i)
{
if (i >= source.Length || source[i] != '[')
return -1;
int j = i + 1;
int level = 0;
while (j < source.Length && source[j] == '=')
{
level++;
j++;
}
return j < source.Length && source[j] == '[' ? level : -1;
}
private static int SkipLongBracket(string source, int i, int level)
{
int length = source.Length;
i += level + 2;
while (i < length)
{
if (source[i] == ']')
{
int j = i + 1;
int count = 0;
while (j < length && source[j] == '=')
{
count++;
j++;
}
if (count == level && j < length && source[j] == ']')
return j + 1;
}
i++;
}
throw new KernelUnsupportedException("Unterminated long bracket.");
}
private static int ReadLongString(string source, int start, int level, List<LuaToken> tokens)
{
int end = SkipLongBracket(source, start, level);
int contentStart = start + level + 2;
int contentEnd = end - level - 2;
string text = source.Substring(contentStart, Math.Max(0, contentEnd - contentStart));
tokens.Add(new LuaToken(LuaTokenKind.String, text, 0d));
return end;
}
private static int ReadShortString(string source, int start, List<LuaToken> tokens)
{
char quote = source[start];
int i = start + 1;
int length = source.Length;
var value = new System.Text.StringBuilder();
while (i < length)
{
char c = source[i];
if (c == quote)
{
tokens.Add(new LuaToken(LuaTokenKind.String, value.ToString(), 0d));
return i + 1;
}
if (c == '\n')
throw new KernelUnsupportedException("Unterminated string.");
if (c == '\\')
{
i = ReadEscape(source, i + 1, value);
continue;
}
value.Append(c);
i++;
}
throw new KernelUnsupportedException("Unterminated string.");
}
private static int ReadEscape(string source, int i, System.Text.StringBuilder value)
{
if (i >= source.Length)
throw new KernelUnsupportedException("Unterminated string escape.");
char c = source[i];
switch (c)
{
case 'n': value.Append('\n'); return i + 1;
case 't': value.Append('\t'); return i + 1;
case 'r': value.Append('\r'); return i + 1;
case 'a': value.Append('\a'); return i + 1;
case 'b': value.Append('\b'); return i + 1;
case 'f': value.Append('\f'); return i + 1;
case 'v': value.Append('\v'); return i + 1;
case '\\': value.Append('\\'); return i + 1;
case '"': value.Append('"'); return i + 1;
case '\'': value.Append('\''); return i + 1;
case '\n': value.Append('\n'); return i + 1;
default:
if (char.IsDigit(c))
{
int n = 0;
int count = 0;
while (i < source.Length && count < 3 && char.IsDigit(source[i]))
{
n = n * 10 + (source[i] - '0');
i++;
count++;
}
value.Append((char)n);
return i;
}
value.Append(c);
return i + 1;
}
}
private static int ReadNumber(string source, int start, List<LuaToken> tokens)
{
int length = source.Length;
int i = start;
if (source[i] == '0' && i + 1 < length && (source[i + 1] == 'x' || source[i + 1] == 'X'))
{
i += 2;
int digitsStart = i;
while (i < length && Uri.IsHexDigit(source[i]))
i++;
if (i == digitsStart)
throw new KernelUnsupportedException("Malformed hexadecimal literal.");
string hex = source.Substring(digitsStart, i - digitsStart);
double hexValue = (double)ulong.Parse(hex, NumberStyles.HexNumber, CultureInfo.InvariantCulture);
tokens.Add(new LuaToken(LuaTokenKind.Number, source.Substring(start, i - start), hexValue));
return i;
}
while (i < length && char.IsDigit(source[i]))
i++;
if (i < length && source[i] == '.')
{
i++;
while (i < length && char.IsDigit(source[i]))
i++;
}
if (i < length && (source[i] == 'e' || source[i] == 'E'))
{
i++;
if (i < length && (source[i] == '+' || source[i] == '-'))
i++;
while (i < length && char.IsDigit(source[i]))
i++;
}
string text = source.Substring(start, i - start);
double value = double.Parse(text, NumberStyles.Float, CultureInfo.InvariantCulture);
tokens.Add(new LuaToken(LuaTokenKind.Number, text, value));
return i;
}
private static int ReadName(string source, int start, List<LuaToken> tokens)
{
int i = start;
int length = source.Length;
while (i < length && IsNamePart(source[i]))
i++;
string text = source.Substring(start, i - start);
tokens.Add(new LuaToken(Keywords.Contains(text) ? LuaTokenKind.Keyword : LuaTokenKind.Name, text, 0d));
return i;
}
private static int ReadSymbol(string source, int start, List<LuaToken> tokens)
{
int length = source.Length;
char c = source[start];
if (c == '.' && start + 2 < length && source[start + 1] == '.' && source[start + 2] == '.')
{
tokens.Add(new LuaToken(LuaTokenKind.Symbol, "...", 0d));
return start + 3;
}
if (start + 1 < length)
{
string two = source.Substring(start, 2);
switch (two)
{
case "==":
case "~=":
case "<=":
case ">=":
case "..":
tokens.Add(new LuaToken(LuaTokenKind.Symbol, two, 0d));
return start + 2;
}
}
switch (c)
{
case '+':
case '-':
case '*':
case '/':
case '%':
case '^':
case '#':
case '<':
case '>':
case '=':
case '(':
case ')':
case '{':
case '}':
case '[':
case ']':
case ';':
case ':':
case ',':
case '.':
tokens.Add(new LuaToken(LuaTokenKind.Symbol, c.ToString(), 0d));
return start + 1;
default:
throw new KernelUnsupportedException($"Unexpected character '{c}'.");
}
}
private static bool IsNameStart(char c) => c == '_' || char.IsLetter(c);
private static bool IsNamePart(char c) => c == '_' || char.IsLetterOrDigit(c);
}
}
+349
ファイルの表示
@@ -0,0 +1,349 @@
using System.Collections.Generic;
namespace LuaScript.Engine.Kernel
{
internal sealed class LuaParser
{
private readonly List<LuaToken> _tokens;
private int _pos;
private LuaParser(List<LuaToken> tokens) => _tokens = tokens;
public static IReadOnlyList<LuaStmt> Parse(string source)
{
var parser = new LuaParser(LuaLexer.Tokenize(source));
var block = parser.ParseBlock();
parser.Expect(LuaTokenKind.Eof);
return block;
}
private LuaToken Current => _tokens[_pos];
private LuaToken Advance() => _tokens[_pos++];
private bool IsBlockEnd()
{
var t = Current;
return t.Kind == LuaTokenKind.Eof ||
t.IsKeyword("end") || t.IsKeyword("else") || t.IsKeyword("elseif") || t.IsKeyword("until");
}
private IReadOnlyList<LuaStmt> ParseBlock()
{
var statements = new List<LuaStmt>();
while (!IsBlockEnd())
{
if (Current.IsSymbol(";"))
{
Advance();
continue;
}
statements.Add(ParseStatement());
}
return statements;
}
private LuaStmt ParseStatement()
{
var t = Current;
if (t.IsKeyword("local"))
return ParseLocal();
if (t.IsKeyword("if"))
return ParseIf();
if (t.IsKeyword("for"))
return ParseFor();
if (t.Kind == LuaTokenKind.Keyword)
throw new KernelUnsupportedException($"Unsupported statement '{t.Text}'.");
return ParseExpressionStatement();
}
private LuaStmt ParseLocal()
{
Advance();
if (Current.IsKeyword("function"))
throw new KernelUnsupportedException("Local functions are not supported.");
var names = new List<string> { ExpectName() };
while (Current.IsSymbol(","))
{
Advance();
names.Add(ExpectName());
}
IReadOnlyList<LuaExpr> values = [];
if (Current.IsSymbol("="))
{
Advance();
values = ParseExpressionList();
}
return new LocalStmt(names, values);
}
private LuaStmt ParseIf()
{
Advance();
var clauses = new List<IfClause>();
var condition = ParseExpression();
ExpectKeyword("then");
clauses.Add(new IfClause(condition, ParseBlock()));
while (Current.IsKeyword("elseif"))
{
Advance();
var elseifCondition = ParseExpression();
ExpectKeyword("then");
clauses.Add(new IfClause(elseifCondition, ParseBlock()));
}
IReadOnlyList<LuaStmt>? elseBody = null;
if (Current.IsKeyword("else"))
{
Advance();
elseBody = ParseBlock();
}
ExpectKeyword("end");
return new IfStmt(clauses, elseBody);
}
private LuaStmt ParseFor()
{
Advance();
string variable = ExpectName();
if (!Current.IsSymbol("="))
throw new KernelUnsupportedException("Generic for loops are not supported.");
Advance();
var start = ParseExpression();
ExpectSymbol(",");
var stop = ParseExpression();
LuaExpr? step = null;
if (Current.IsSymbol(","))
{
Advance();
step = ParseExpression();
}
ExpectKeyword("do");
var body = ParseBlock();
ExpectKeyword("end");
return new NumericForStmt(variable, start, stop, step, body);
}
private LuaStmt ParseExpressionStatement()
{
var first = ParseSuffixedExpression();
if (Current.IsSymbol("=") || Current.IsSymbol(","))
{
var targets = new List<LuaExpr> { first };
while (Current.IsSymbol(","))
{
Advance();
targets.Add(ParseSuffixedExpression());
}
ExpectSymbol("=");
var values = ParseExpressionList();
return new AssignStmt(targets, values);
}
if (first is CallExpr call)
return new CallStmt(call);
throw new KernelUnsupportedException("Expression is not a valid statement.");
}
private List<LuaExpr> ParseExpressionList()
{
var values = new List<LuaExpr> { ParseExpression() };
while (Current.IsSymbol(","))
{
Advance();
values.Add(ParseExpression());
}
return values;
}
private LuaExpr ParseExpression(int minPrecedence = 0)
{
var left = ParseUnary();
while (true)
{
var (op, precedence, rightAssociative) = PeekBinaryOperator();
if (op is null || precedence < minPrecedence)
break;
Advance();
int nextMinimum = rightAssociative ? precedence : precedence + 1;
var right = ParseExpression(nextMinimum);
left = new BinaryExpr(op, left, right);
}
return left;
}
private LuaExpr ParseUnary()
{
var t = Current;
if (t.IsKeyword("not") || t.IsSymbol("-") || t.IsSymbol("#"))
{
Advance();
return new UnaryExpr(t.Text, ParseExpression(7));
}
return ParseValue();
}
private (string? Operator, int Precedence, bool RightAssociative) PeekBinaryOperator()
{
var t = Current;
if (t.IsKeyword("or")) return ("or", 1, false);
if (t.IsKeyword("and")) return ("and", 2, false);
if (t.Kind == LuaTokenKind.Symbol)
{
switch (t.Text)
{
case "<":
case ">":
case "<=":
case ">=":
case "~=":
case "==":
return (t.Text, 3, false);
case "..":
return ("..", 4, true);
case "+":
case "-":
return (t.Text, 5, false);
case "*":
case "/":
case "%":
return (t.Text, 6, false);
case "^":
return ("^", 8, true);
}
}
return (null, 0, false);
}
private LuaExpr ParseValue()
{
var t = Current;
switch (t.Kind)
{
case LuaTokenKind.Number:
Advance();
return new NumberExpr(t.Number);
case LuaTokenKind.String:
Advance();
return new StringExpr(t.Text);
case LuaTokenKind.Keyword when t.Text == "true":
Advance();
return new BoolExpr(true);
case LuaTokenKind.Keyword when t.Text == "false":
Advance();
return new BoolExpr(false);
case LuaTokenKind.Keyword when t.Text == "nil":
Advance();
return new NilExpr();
}
if (t.IsKeyword("function") || t.IsSymbol("{") || t.IsSymbol("..."))
throw new KernelUnsupportedException($"Unsupported expression near '{t.Text}'.");
return ParseSuffixedExpression();
}
private LuaExpr ParseSuffixedExpression()
{
var expression = ParsePrimaryExpression();
while (true)
{
var t = Current;
if (t.IsSymbol("."))
{
Advance();
expression = new MemberExpr(expression, ExpectName());
}
else if (t.IsSymbol("["))
{
Advance();
var key = ParseExpression();
ExpectSymbol("]");
expression = new IndexExpr(expression, key);
}
else if (t.IsSymbol("("))
{
expression = new CallExpr(expression, ParseArguments());
}
else
{
break;
}
}
return expression;
}
private LuaExpr ParsePrimaryExpression()
{
var t = Current;
if (t.IsSymbol("("))
{
Advance();
var inner = ParseExpression();
ExpectSymbol(")");
return inner;
}
if (t.Kind == LuaTokenKind.Name)
{
Advance();
return new NameExpr(t.Text);
}
throw new KernelUnsupportedException($"Unexpected token '{t.Text}'.");
}
private List<LuaExpr> ParseArguments()
{
ExpectSymbol("(");
var arguments = new List<LuaExpr>();
if (!Current.IsSymbol(")"))
{
arguments.Add(ParseExpression());
while (Current.IsSymbol(","))
{
Advance();
arguments.Add(ParseExpression());
}
}
ExpectSymbol(")");
return arguments;
}
private string ExpectName()
{
if (Current.Kind != LuaTokenKind.Name)
throw new KernelUnsupportedException($"Expected a name but found '{Current.Text}'.");
return Advance().Text;
}
private void Expect(LuaTokenKind kind)
{
if (Current.Kind != kind)
throw new KernelUnsupportedException($"Expected {kind} but found '{Current.Text}'.");
Advance();
}
private void ExpectSymbol(string symbol)
{
if (!Current.IsSymbol(symbol))
throw new KernelUnsupportedException($"Expected '{symbol}' but found '{Current.Text}'.");
Advance();
}
private void ExpectKeyword(string keyword)
{
if (!Current.IsKeyword(keyword))
throw new KernelUnsupportedException($"Expected '{keyword}' but found '{Current.Text}'.");
Advance();
}
}
}
+28
ファイルの表示
@@ -0,0 +1,28 @@
using System;
namespace LuaScript.Engine.Kernel
{
internal enum LuaTokenKind
{
Name,
Number,
String,
Keyword,
Symbol,
Eof,
}
internal readonly struct LuaToken(LuaTokenKind kind, string text, double number)
{
public LuaTokenKind Kind { get; } = kind;
public string Text { get; } = text;
public double Number { get; } = number;
public bool Is(LuaTokenKind kind, string text) =>
Kind == kind && string.Equals(Text, text, StringComparison.Ordinal);
public bool IsSymbol(string text) => Is(LuaTokenKind.Symbol, text);
public bool IsKeyword(string text) => Is(LuaTokenKind.Keyword, text);
}
}
+559
ファイルの表示
@@ -0,0 +1,559 @@
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 int _stringParamsCapacity = NativeProtocol.MinStringParamsCapacity;
private long _pixelOffset = NativeProtocol.PixelOffset(NativeProtocol.MinStringParamsCapacity);
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;
private byte[]? _resultBuffer;
private readonly Dictionary<string, byte[]> _stringNameBytes = new(StringComparer.Ordinal);
private byte[] _stringValueBytes = new byte[256];
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,
IReadOnlyDictionary<string, string> stringParameters,
byte[] pixels,
int width,
int height,
int timeoutMs,
Func<string, int, SceneObjectInfo?> resolveObject,
Func<string, int, double, double, double, (byte[] buffer, int w, int h)> loadFigure,
Func<string, string, double, bool, bool, int, (byte[] buffer, int w, int h)> loadText,
Func<string, (byte[] buffer, int w, int h)> loadImage,
Func<string, double, (byte[] buffer, int w, int h)> loadMovie,
Action<string, IReadOnlyList<KeyValuePair<string, object>>> addEffect,
Action<DrawCommand> addDraw,
out bool pixelsDirty,
out bool bufferReplaced,
out byte[]? newPixels,
out int resultWidth,
out int resultHeight,
out string? error)
{
pixelsDirty = false;
bufferReplaced = false;
newPixels = null;
resultWidth = width;
resultHeight = height;
error = null;
byte[] scriptBytes = Encoding.UTF8.GetBytes(script);
if (scriptBytes.Length > NativeProtocol.ScriptMax)
{
error = "script too large for native lane";
return false;
}
int stringCapacity = ResolveStringCapacity(_stringParamsCapacity, MeasureStringParameters(stringParameters));
EnsureWorker(width, height, stringCapacity);
var view = _view!;
view.WriteArray(NativeProtocol.FieldsOffset, fields, 0, NativeProtocol.FieldCount);
WriteStringParameters(view, stringParameters);
view.Write(NativeProtocol.OffWidth, width);
view.Write(NativeProtocol.OffHeight, height);
view.Write(NativeProtocol.OffScriptLen, scriptBytes.Length);
view.WriteArray(NativeProtocol.ScriptOffset, scriptBytes, 0, scriptBytes.Length);
view.WriteArray(_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;
DispatchCallback(view, resolveObject, loadFigure, loadText, loadImage, loadMovie, addEffect, addDraw);
_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);
resultWidth = view.ReadInt32(NativeProtocol.OffWidth);
resultHeight = view.ReadInt32(NativeProtocol.OffHeight);
bufferReplaced = resultWidth != width || resultHeight != height;
pixelsDirty = view.ReadInt32(NativeProtocol.OffPixelsDirty) != 0;
if (pixelsDirty)
{
if (bufferReplaced)
{
int pixelSize = resultWidth * resultHeight * 4;
if (_resultBuffer == null || _resultBuffer.Length < pixelSize)
_resultBuffer = new byte[pixelSize];
view.ReadArray(_pixelOffset, _resultBuffer, 0, pixelSize);
newPixels = _resultBuffer;
}
else
{
view.ReadArray(_pixelOffset, pixels, 0, pixels.Length);
}
}
return true;
}
private static int MeasureStringParameters(IReadOnlyDictionary<string, string> stringParameters)
{
int total = 4;
foreach (var pair in stringParameters)
total += 8 + Encoding.UTF8.GetByteCount(pair.Key) + Encoding.UTF8.GetByteCount(pair.Value ?? string.Empty);
return total;
}
private static int ResolveStringCapacity(int current, int required)
{
int capacity = current;
while (capacity < required)
{
if (capacity > int.MaxValue / 2)
{
capacity = required;
break;
}
capacity *= 2;
}
while (capacity > NativeProtocol.MinStringParamsCapacity && required <= capacity / 2)
capacity /= 2;
return capacity;
}
private void WriteStringParameters(MemoryMappedViewAccessor view, IReadOnlyDictionary<string, string> stringParameters)
{
long basePos = NativeProtocol.StringParamsOffset;
long limit = basePos + _stringParamsCapacity;
long pos = basePos + 4;
int count = 0;
foreach (var pair in stringParameters)
{
if (!_stringNameBytes.TryGetValue(pair.Key, out var name))
{
name = Encoding.UTF8.GetBytes(pair.Key);
_stringNameBytes[pair.Key] = name;
}
string value = pair.Value ?? string.Empty;
int maxValueBytes = Encoding.UTF8.GetMaxByteCount(value.Length);
if (_stringValueBytes.Length < maxValueBytes)
_stringValueBytes = new byte[Math.Max(maxValueBytes, _stringValueBytes.Length * 2)];
int valueLen = Encoding.UTF8.GetBytes(value, 0, value.Length, _stringValueBytes, 0);
if (pos + 8 + name.Length + valueLen > limit)
break;
view.Write(pos, name.Length); pos += 4;
view.WriteArray(pos, name, 0, name.Length); pos += name.Length;
view.Write(pos, valueLen); pos += 4;
view.WriteArray(pos, _stringValueBytes, 0, valueLen); pos += valueLen;
count++;
}
view.Write(basePos, count);
view.Write(NativeProtocol.OffStringParamsLen, (int)(pos - basePos));
}
private void DispatchCallback(
MemoryMappedViewAccessor view,
Func<string, int, SceneObjectInfo?> resolveObject,
Func<string, int, double, double, double, (byte[] buffer, int w, int h)> loadFigure,
Func<string, string, double, bool, bool, int, (byte[] buffer, int w, int h)> loadText,
Func<string, (byte[] buffer, int w, int h)> loadImage,
Func<string, double, (byte[] buffer, int w, int h)> loadMovie,
Action<string, IReadOnlyList<KeyValuePair<string, object>>> addEffect,
Action<DrawCommand> addDraw)
{
int kind = view.ReadInt32(NativeProtocol.OffCallbackKind);
switch (kind)
{
case NativeProtocol.CbKindGetObject:
ResolveGetObjectCallback(view, resolveObject);
break;
case NativeProtocol.CbKindLoadFigure:
ResolveLoadFigureCallback(view, loadFigure);
break;
case NativeProtocol.CbKindLoadText:
ResolveLoadTextCallback(view, loadText);
break;
case NativeProtocol.CbKindLoadImage:
ResolveLoadImageCallback(view, loadImage);
break;
case NativeProtocol.CbKindLoadMovie:
ResolveLoadMovieCallback(view, loadMovie);
break;
case NativeProtocol.CbKindEffect:
ResolveEffectCallback(view, addEffect);
break;
case NativeProtocol.CbKindDraw:
ResolveDrawCallback(view, addDraw);
break;
case NativeProtocol.CbKindDrawPoly:
ResolveDrawPolyCallback(view, addDraw);
break;
}
}
private static void ResolveDrawCallback(MemoryMappedViewAccessor view, Action<DrawCommand> addDraw)
{
long rOff = NativeProtocol.CallbackResultOffset;
double ox = view.ReadDouble(rOff + 0 * 8);
double oy = view.ReadDouble(rOff + 1 * 8);
double oz = view.ReadDouble(rOff + 2 * 8);
double zoom = view.ReadDouble(rOff + 3 * 8);
double alpha = view.ReadDouble(rOff + 4 * 8);
double aspect = view.ReadDouble(rOff + 5 * 8);
double antialias = view.ReadDouble(rOff + 6 * 8);
try { addDraw(new DrawCommand(ox, oy, oz, zoom, alpha, aspect, null, antialias)); }
catch { }
view.Write(NativeProtocol.OffCallbackFound, 1);
}
private static void ResolveDrawPolyCallback(MemoryMappedViewAccessor view, Action<DrawCommand> addDraw)
{
var poly = new double[DrawPolyMath.Length];
for (int i = 0; i < DrawPolyMath.Length; i++)
poly[i] = view.ReadDouble(NativeProtocol.CallbackTagOffset + i * 8);
double antialias = view.ReadDouble(NativeProtocol.CallbackTagOffset + DrawPolyMath.Length * 8);
try { addDraw(new DrawCommand(0d, 0d, 0d, 1d, poly[20], 0d, poly, antialias)); }
catch { }
view.Write(NativeProtocol.OffCallbackFound, 1);
}
private void ResolveGetObjectCallback(MemoryMappedViewAccessor view, Func<string, int, SceneObjectInfo?> resolveObject)
{
int frame = view.ReadInt32(NativeProtocol.OffCallbackFrame);
int 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 void ResolveLoadFigureCallback(
MemoryMappedViewAccessor view,
Func<string, int, double, double, double, (byte[] buffer, int w, int h)> loadFigure)
{
int tagLen = Math.Clamp(view.ReadInt32(NativeProtocol.OffCallbackTagLen), 0, NativeProtocol.CallbackTagMax);
view.ReadArray(NativeProtocol.CallbackTagOffset, _callbackTag, 0, tagLen);
string name = Encoding.UTF8.GetString(_callbackTag, 0, tagLen);
long rOff = NativeProtocol.CallbackResultOffset;
int color = (int)view.ReadDouble(rOff + 0 * 8);
double size = view.ReadDouble(rOff + 1 * 8);
double lineWidth = view.ReadDouble(rOff + 2 * 8);
double aspect = view.ReadDouble(rOff + 3 * 8);
(byte[] buffer, int w, int h) result;
try { result = loadFigure(name, color, size, lineWidth, aspect); }
catch { result = (new byte[4], 1, 1); }
int pixelSize = result.w * result.h * 4;
long capacity = view.Capacity - _pixelOffset;
if (pixelSize > capacity)
{
result = (new byte[4], 1, 1);
pixelSize = 4;
}
view.Write(NativeProtocol.OffLoadResultWidth, result.w);
view.Write(NativeProtocol.OffLoadResultHeight, result.h);
view.WriteArray(_pixelOffset, result.buffer, 0, pixelSize);
view.Write(NativeProtocol.OffCallbackFound, 1);
}
private void ResolveLoadTextCallback(
MemoryMappedViewAccessor view,
Func<string, string, double, bool, bool, int, (byte[] buffer, int w, int h)> loadText)
{
int tagLen = Math.Clamp(view.ReadInt32(NativeProtocol.OffCallbackTagLen), 0, NativeProtocol.CallbackTagMax);
view.ReadArray(NativeProtocol.CallbackTagOffset, _callbackTag, 0, tagLen);
string payload = Encoding.UTF8.GetString(_callbackTag, 0, tagLen);
int separator = payload.IndexOf('\0');
string family = separator >= 0 ? payload[..separator] : string.Empty;
string text = separator >= 0 ? payload[(separator + 1)..] : payload;
long rOff = NativeProtocol.CallbackResultOffset;
double size = view.ReadDouble(rOff + 0 * 8);
bool bold = view.ReadDouble(rOff + 1 * 8) != 0;
bool italic = view.ReadDouble(rOff + 2 * 8) != 0;
int color = (int)view.ReadDouble(rOff + 3 * 8);
(byte[] buffer, int w, int h) result;
try { result = loadText(family, text, size, bold, italic, color); }
catch { result = (new byte[4], 1, 1); }
int pixelSize = result.w * result.h * 4;
long capacity = view.Capacity - _pixelOffset;
if (pixelSize > capacity)
{
result = (new byte[4], 1, 1);
pixelSize = 4;
}
view.Write(NativeProtocol.OffLoadResultWidth, result.w);
view.Write(NativeProtocol.OffLoadResultHeight, result.h);
view.WriteArray(_pixelOffset, result.buffer, 0, pixelSize);
view.Write(NativeProtocol.OffCallbackFound, 1);
}
private void ResolveLoadImageCallback(
MemoryMappedViewAccessor view,
Func<string, (byte[] buffer, int w, int h)> loadImage)
{
int tagLen = Math.Clamp(view.ReadInt32(NativeProtocol.OffCallbackTagLen), 0, NativeProtocol.CallbackTagMax);
view.ReadArray(NativeProtocol.CallbackTagOffset, _callbackTag, 0, tagLen);
string path = Encoding.UTF8.GetString(_callbackTag, 0, tagLen);
(byte[] buffer, int w, int h) result;
try { result = loadImage(path); }
catch { result = (new byte[4], 1, 1); }
int pixelSize = result.w * result.h * 4;
long capacity = view.Capacity - _pixelOffset;
if (pixelSize > capacity)
{
result = (new byte[4], 1, 1);
pixelSize = 4;
}
view.Write(NativeProtocol.OffLoadResultWidth, result.w);
view.Write(NativeProtocol.OffLoadResultHeight, result.h);
view.WriteArray(_pixelOffset, result.buffer, 0, pixelSize);
view.Write(NativeProtocol.OffCallbackFound, 1);
}
private void ResolveLoadMovieCallback(
MemoryMappedViewAccessor view,
Func<string, double, (byte[] buffer, int w, int h)> loadMovie)
{
int tagLen = Math.Clamp(view.ReadInt32(NativeProtocol.OffCallbackTagLen), 0, NativeProtocol.CallbackTagMax);
view.ReadArray(NativeProtocol.CallbackTagOffset, _callbackTag, 0, tagLen);
string path = Encoding.UTF8.GetString(_callbackTag, 0, tagLen);
double time = view.ReadDouble(NativeProtocol.CallbackResultOffset);
(byte[] buffer, int w, int h) result;
try { result = loadMovie(path, time); }
catch { result = (new byte[4], 1, 1); }
int pixelSize = result.w * result.h * 4;
long capacity = view.Capacity - _pixelOffset;
if (pixelSize > capacity)
{
result = (new byte[4], 1, 1);
pixelSize = 4;
}
view.Write(NativeProtocol.OffLoadResultWidth, result.w);
view.Write(NativeProtocol.OffLoadResultHeight, result.h);
view.WriteArray(_pixelOffset, result.buffer, 0, pixelSize);
view.Write(NativeProtocol.OffCallbackFound, 1);
}
private void ResolveEffectCallback(MemoryMappedViewAccessor view, Action<string, IReadOnlyList<KeyValuePair<string, object>>> addEffect)
{
int tagLen = Math.Clamp(view.ReadInt32(NativeProtocol.OffCallbackTagLen), 0, NativeProtocol.CallbackTagMax);
view.ReadArray(NativeProtocol.CallbackTagOffset, _callbackTag, 0, tagLen);
var segments = Encoding.UTF8.GetString(_callbackTag, 0, tagLen).Split('\0');
if (segments.Length == 0)
return;
string effectName = segments[0];
var arguments = new List<KeyValuePair<string, object>>();
for (int i = 1; i + 1 < segments.Length; i += 2)
{
string key = segments[i];
string raw = segments[i + 1];
object value;
if (raw.Length > 0 && raw[0] == 'n')
value = double.TryParse(raw.AsSpan(1), System.Globalization.NumberStyles.Float, System.Globalization.CultureInfo.InvariantCulture, out var d) ? d : 0d;
else if (raw.Length > 0 && raw[0] == 'b')
value = raw.Length > 1 && raw[1] == '1';
else if (raw.Length > 0 && raw[0] == 's')
value = raw.Substring(1);
else
value = raw;
arguments.Add(new KeyValuePair<string, object>(key, value));
}
try { addEffect(effectName, arguments); }
catch { }
view.Write(NativeProtocol.OffCallbackFound, 1);
}
private string ResolveTag(int tagLen)
{
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, int stringCapacity)
{
if (_alive && _process is { HasExited: false } && _width == width && _height == height && _stringParamsCapacity == stringCapacity)
return;
KillWorker();
StartWorker(width, height, stringCapacity);
}
private void StartWorker(int width, int height, int stringCapacity)
{
_width = width;
_height = height;
_stringParamsCapacity = stringCapacity;
_pixelOffset = NativeProtocol.PixelOffset(stringCapacity);
long size = NativeProtocol.BufferSize(width, height, stringCapacity);
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);
psi.ArgumentList.Add(stringCapacity.ToString());
_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();
}
}
}
+98
ファイルの表示
@@ -0,0 +1,98 @@
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.Slider0] = ctx.Slider0;
f[NativeProtocol.Slider1] = ctx.Slider1;
f[NativeProtocol.Slider2] = ctx.Slider2;
f[NativeProtocol.Slider3] = ctx.Slider3;
f[NativeProtocol.Check0] = ctx.Check0 ? 1d : 0d;
f[NativeProtocol.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];
ctx.ApplyWriteBack(
f[NativeProtocol.Sx],
f[NativeProtocol.Sy],
f[NativeProtocol.Zoom],
f[NativeProtocol.Aspect],
f[NativeProtocol.Rx],
f[NativeProtocol.Ry],
f[NativeProtocol.Rz],
f[NativeProtocol.Rxr],
f[NativeProtocol.Ryr],
f[NativeProtocol.Rzr]);
}
}
}
+141
ファイルの表示
@@ -0,0 +1,141 @@
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 OffCallbackKind = 44;
public const int OffLoadResultWidth = 48;
public const int OffLoadResultHeight = 52;
public const int OffStringParamsLen = 56;
public const int HeaderSize = 64;
public const int 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 = 4096;
public const int CallbackResultOffset = CallbackTagOffset + CallbackTagMax;
public const int CallbackResultCount = 8;
public const int StringParamsOffset = CallbackResultOffset + CallbackResultCount * 8;
public const int MinStringParamsCapacity = 64 * 1024;
public const int CbKindGetObject = 0;
public const int CbKindLoadFigure = 1;
public const int CbKindEffect = 2;
public const int CbKindDraw = 3;
public const int CbKindDrawPoly = 4;
public const int CbKindLoadText = 5;
public const int CbKindLoadImage = 6;
public const int CbKindLoadMovie = 7;
public const int CbExist = 0;
public const int 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 static int PixelOffset(int stringCapacity) => StringParamsOffset + stringCapacity;
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 Slider0 = 58;
public const int Slider1 = 59;
public const int Slider2 = 60;
public const int Slider3 = 61;
public const int FirstWritableField = X;
public const int LastWritableField = Rzr;
public const int MaxPixelBufferSize = 3840 * 2160 * 4;
public static long BufferSize(int width, int height, int stringCapacity) =>
PixelOffset(stringCapacity) + Math.Max((long)width * height * 4, MaxPixelBufferSize);
}
}
+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);
}
}
+107
ファイルの表示
@@ -0,0 +1,107 @@
using System;
namespace LuaScript.Engine
{
internal static class ScriptDirective
{
public static ScriptEngineKind Resolve(string? script) =>
TryGetDirective(script, out var kind) ? kind : ScriptEngineKind.MoonSharp;
public static ScriptEngineKind ResolveAuto(string? script)
{
if (TryGetDirective(script, out var kind))
return kind;
if (UsesDrawingApi(script))
return ScriptEngineKind.MoonSharp;
return UsesPixelApi(script) ? ScriptEngineKind.Native : ScriptEngineKind.MoonSharp;
}
public static bool TryResolveExplicit(string? script, out ScriptEngineKind kind) =>
TryGetDirective(script, out kind);
public static bool UsesPixelApi(string? script) =>
script is not null && (script.Contains("getpixel", StringComparison.Ordinal) || script.Contains("setpixel", StringComparison.Ordinal));
public static bool UsesDrawingApi(string? script) =>
script is not null &&
script.Contains("obj.setoption", StringComparison.Ordinal);
private static bool TryGetDirective(string? script, out ScriptEngineKind kind)
{
kind = ScriptEngineKind.MoonSharp;
if (string.IsNullOrEmpty(script))
return false;
int index = 0;
int length = script.Length;
while (index < length)
{
int lineStart = index;
while (index < length && script[index] != '\n')
index++;
int lineEnd = index;
if (lineEnd > lineStart && script[lineEnd - 1] == '\r')
lineEnd--;
if (TryParseDirectiveLine(script, lineStart, lineEnd, out kind))
return true;
index++;
}
return false;
}
private static bool TryParseDirectiveLine(string script, int start, int end, out ScriptEngineKind kind)
{
kind = ScriptEngineKind.MoonSharp;
int i = start;
while (i < end && (script[i] == ' ' || script[i] == '\t'))
i++;
if (i + 3 > end || script[i] != '-' || script[i + 1] != '-' || script[i + 2] != '!')
return false;
i += 3;
while (i < end && (script[i] == ' ' || script[i] == '\t'))
i++;
int tokenStart = i;
while (i < end && IsTokenChar(script[i]))
i++;
int tokenEnd = i;
while (i < end && (script[i] == ' ' || script[i] == '\t'))
i++;
if (i != end)
return false;
var token = script.AsSpan(tokenStart, tokenEnd - tokenStart);
if (token.Equals("native", StringComparison.OrdinalIgnoreCase))
{
kind = ScriptEngineKind.Native;
return true;
}
if (token.Equals("gpu", StringComparison.OrdinalIgnoreCase))
{
kind = ScriptEngineKind.Gpu;
return true;
}
if (token.Equals("cpu", StringComparison.OrdinalIgnoreCase))
{
kind = ScriptEngineKind.Cpu;
return true;
}
if (token.Equals("moonsharp", StringComparison.OrdinalIgnoreCase))
{
kind = ScriptEngineKind.MoonSharp;
return true;
}
return false;
}
private static bool IsTokenChar(char c) =>
(c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z');
}
}
+12
ファイルの表示
@@ -0,0 +1,12 @@
using System;
namespace LuaScript.Engine
{
internal enum ScriptEngineKind
{
MoonSharp,
Native,
Gpu,
Cpu,
}
}
+97
ファイルの表示
@@ -0,0 +1,97 @@
using System;
using System.IO;
using Vortice.Mathematics;
using Vortice.WIC;
namespace LuaScript
{
internal sealed class ImageDecoder : IDisposable
{
private const int MaxDimension = 8192;
private IWICImagingFactory? _factory;
public unsafe byte[] Decode(string path, out int width, out int height)
{
width = 1;
height = 1;
if (string.IsNullOrEmpty(path) || !IsSupportedImage(path))
return new byte[4];
try
{
_factory ??= new IWICImagingFactory();
using var stream = _factory.CreateStream(path, FileAccess.Read);
using var decoder = _factory.CreateDecoderFromStream(stream, DecodeOptions.CacheOnDemand);
using var frame = decoder.GetFrame(0);
using var converter = _factory.CreateFormatConverter();
converter.Initialize(
frame,
Vortice.WIC.PixelFormat.Format32bppPBGRA,
BitmapDitherType.None,
null,
0d,
BitmapPaletteType.Custom);
converter.GetSize(out int w, out int h);
if (w <= 0 || h <= 0 || w > MaxDimension || h > MaxDimension)
return new byte[4];
var buffer = new byte[w * h * 4];
fixed (byte* p = buffer)
converter.CopyPixels(new RectI(0, 0, w, h), w * 4, buffer.Length, (nint)p);
width = w;
height = h;
return buffer;
}
catch
{
width = 1;
height = 1;
return new byte[4];
}
}
private static bool IsSupportedImage(string path)
{
try
{
if (!File.Exists(path))
return false;
Span<byte> head = stackalloc byte[12];
using var stream = File.OpenRead(path);
int read = stream.Read(head);
if (read < 4)
return false;
if (head[0] == 0x89 && head[1] == 0x50 && head[2] == 0x4E && head[3] == 0x47)
return true;
if (head[0] == 0xFF && head[1] == 0xD8 && head[2] == 0xFF)
return true;
if (head[0] == 0x47 && head[1] == 0x49 && head[2] == 0x46 && head[3] == 0x38)
return true;
if (head[0] == 0x42 && head[1] == 0x4D)
return true;
if ((head[0] == 0x49 && head[1] == 0x49 && head[2] == 0x2A && head[3] == 0x00) ||
(head[0] == 0x4D && head[1] == 0x4D && head[2] == 0x00 && head[3] == 0x2A))
return true;
if (read >= 12 &&
head[0] == 0x52 && head[1] == 0x49 && head[2] == 0x46 && head[3] == 0x46 &&
head[8] == 0x57 && head[9] == 0x45 && head[10] == 0x42 && head[11] == 0x50)
return true;
return false;
}
catch
{
return false;
}
}
public void Dispose()
{
_factory?.Dispose();
_factory = null;
}
}
}
+7 -2
ファイルの表示
@@ -17,7 +17,7 @@ namespace LuaScript
private static readonly string[] s_globals = private static readonly string[] s_globals =
[ [
"time", "frame", "totalframe", "framerate", "time", "frame", "totalframe", "framerate",
"timelineframe", "timelinetime", "layer", "timelineframe", "timelinetime", "layer", "color",
"obj", "scene", "anim", "ymm4", "obj", "scene", "anim", "ymm4",
"math", "string", "table", "bit32", "math", "string", "table", "bit32",
"type", "tostring", "tonumber", "select", "error", "assert", "print", "type", "tostring", "tonumber", "select", "error", "assert", "print",
@@ -39,10 +39,15 @@ namespace LuaScript
"obj.rx", "obj.ry", "obj.rz", "obj.rx", "obj.ry", "obj.rz",
"obj.rxr", "obj.ryr", "obj.rzr", "obj.rxr", "obj.ryr", "obj.rzr",
"obj.track0", "obj.track1", "obj.track2", "obj.track3", "obj.track0", "obj.track1", "obj.track2", "obj.track3",
"obj.slider0", "obj.slider1", "obj.slider2", "obj.slider3",
"obj.check0", "obj.check1", "obj.check2", "obj.check3",
"obj.text", "obj.font", "obj.dir",
"obj.file_video", "obj.file_audio", "obj.file_image", "obj.file_project",
"obj.file_mp4", "obj.file_exo", "obj.file_subtitle", "obj.file_shader",
"obj.time", "obj.totaltime", "obj.t", "obj.frame", "obj.totalframe", "obj.time", "obj.totaltime", "obj.t", "obj.frame", "obj.totalframe",
"obj.framerate", "obj.layer", "obj.index", "obj.num", "obj.framerate", "obj.layer", "obj.index", "obj.num",
"obj.getpixel", "obj.setpixel", "obj.getpixel", "obj.setpixel",
"obj.getpixeldata" "obj.getpixeldata", "obj.rand", "obj.load"
]), ]),
("math", [ ("math", [
"math.abs", "math.ceil", "math.cos", "math.exp", "math.floor", "math.abs", "math.ceil", "math.cos", "math.exp", "math.floor",
+2
ファイルの表示
@@ -2,6 +2,7 @@ using System.Collections.Generic;
using System.Text.RegularExpressions; using System.Text.RegularExpressions;
using ICSharpCode.AvalonEdit.Document; using ICSharpCode.AvalonEdit.Document;
using ICSharpCode.AvalonEdit.Folding; using ICSharpCode.AvalonEdit.Folding;
using LuaScript.Diagnostics;
using YukkuriMovieMaker.Controls.AvalonEdit.FoldingStrategy; using YukkuriMovieMaker.Controls.AvalonEdit.FoldingStrategy;
namespace LuaScript namespace LuaScript
@@ -25,6 +26,7 @@ namespace LuaScript
public void UpdateFoldings(FoldingManager manager, TextDocument document) public void UpdateFoldings(FoldingManager manager, TextDocument document)
{ {
manager.UpdateFoldings(CreateNewFoldings(document, out int firstErrorOffset), firstErrorOffset); manager.UpdateFoldings(CreateNewFoldings(document, out int firstErrorOffset), firstErrorOffset);
LuaScriptDiagnosticOverlay.Attach(manager);
} }
private static IEnumerable<NewFolding> CreateNewFoldings(TextDocument document, out int firstErrorOffset) private static IEnumerable<NewFolding> CreateNewFoldings(TextDocument document, out int firstErrorOffset)
+14 -2
ファイルの表示
@@ -4,7 +4,7 @@
<TargetFramework>net10.0-windows10.0.19041.0</TargetFramework> <TargetFramework>net10.0-windows10.0.19041.0</TargetFramework>
<UseWPF>true</UseWPF> <UseWPF>true</UseWPF>
<ImplicitUsings>enable</ImplicitUsings> <ImplicitUsings>enable</ImplicitUsings>
<Version>1.2.0</Version> <Version>1.10.0</Version>
<Platforms>AnyCPU;x64</Platforms> <Platforms>AnyCPU;x64</Platforms>
<Nullable>enable</Nullable> <Nullable>enable</Nullable>
<AllowUnsafeBlocks>true</AllowUnsafeBlocks> <AllowUnsafeBlocks>true</AllowUnsafeBlocks>
@@ -67,6 +67,10 @@
<HintPath>$(YMM4DirPath)Vortice.Mathematics.dll</HintPath> <HintPath>$(YMM4DirPath)Vortice.Mathematics.dll</HintPath>
<Private>false</Private> <Private>false</Private>
</Reference> </Reference>
<Reference Include="Vortice.MediaFoundation">
<HintPath>$(YMM4DirPath)Vortice.MediaFoundation.dll</HintPath>
<Private>false</Private>
</Reference>
<Reference Include="YukkuriMovieMaker"> <Reference Include="YukkuriMovieMaker">
<HintPath>$(YMM4DirPath)YukkuriMovieMaker.dll</HintPath> <HintPath>$(YMM4DirPath)YukkuriMovieMaker.dll</HintPath>
<Private>false</Private> <Private>false</Private>
@@ -90,6 +94,10 @@
<AdditionalFiles Include="**/*.csv" /> <AdditionalFiles Include="**/*.csv" />
</ItemGroup> </ItemGroup>
<ItemGroup>
<EmbeddedResource Include="Compat\AviUtlCompatMap.xml" />
</ItemGroup>
<ItemGroup> <ItemGroup>
<PackageReference Include="MoonSharp" Version="2.0.0" /> <PackageReference Include="MoonSharp" Version="2.0.0" />
</ItemGroup> </ItemGroup>
@@ -102,10 +110,14 @@
<Resource Include="Resources\SyntaxDefinitions\Lua-Light.xshd" /> <Resource Include="Resources\SyntaxDefinitions\Lua-Light.xshd" />
<Resource Include="Resources\SyntaxDefinitions\Lua-Black.xshd" /> <Resource Include="Resources\SyntaxDefinitions\Lua-Black.xshd" />
<Resource Include="Resources\SyntaxDefinitions\Lua-Windows.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> </ItemGroup>
<Target Name="PostBuild" AfterTargets="PostBuildEvent" Condition="'$(CI)' != 'true'"> <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> </Target>
</Project> </Project>
+6
ファイルの表示
@@ -0,0 +1,6 @@
using System;
namespace LuaScript
{
internal sealed class LuaScriptCompilationException(string message, Exception? inner = null) : LuaScriptException(message, inner);
}
+249 -1
ファイルの表示
@@ -1,13 +1,22 @@
using System.Collections.Generic; using System.Collections.Generic;
using System.ComponentModel;
using System.ComponentModel.DataAnnotations; using System.ComponentModel.DataAnnotations;
using System.Windows.Media;
using LuaScript.Compat;
using Newtonsoft.Json;
using YukkuriMovieMaker.Commons; using YukkuriMovieMaker.Commons;
using YukkuriMovieMaker.Controls; using YukkuriMovieMaker.Controls;
using YukkuriMovieMaker.Exo; using YukkuriMovieMaker.Exo;
using YukkuriMovieMaker.ItemEditor.CustomVisibilityAttributes;
using YukkuriMovieMaker.Player.Video; using YukkuriMovieMaker.Player.Video;
using YukkuriMovieMaker.Plugin;
using YukkuriMovieMaker.Plugin.Effects; using YukkuriMovieMaker.Plugin.Effects;
using YukkuriMovieMaker.Settings;
namespace LuaScript namespace LuaScript
{ {
[PluginDetails(AuthorName = "routersys", ContentId = "nc487743")]
[VideoEffect(nameof(Texts.LuaScript), [VideoEffectCategories.Filtering], ["lua", "script", "スクリプト", "lua script", "アニメーション効果", "animation"], IsAviUtlSupported = false, ResourceType = typeof(Texts))] [VideoEffect(nameof(Texts.LuaScript), [VideoEffectCategories.Filtering], ["lua", "script", "スクリプト", "lua script", "アニメーション効果", "animation"], IsAviUtlSupported = false, ResourceType = typeof(Texts))]
internal class LuaScriptEffect : VideoEffectBase, IScriptProvider internal class LuaScriptEffect : VideoEffectBase, IScriptProvider
{ {
@@ -24,27 +33,266 @@ namespace LuaScript
[Display(GroupName = nameof(Texts.ScriptGroup), ResourceType = typeof(Texts))] [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)] [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 _script = DefaultScript;
string IScriptProvider.DefaultScript => 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))] [Display(GroupName = nameof(Texts.ParametersGroup), Name = nameof(Texts.Track0), Description = nameof(Texts.TrackDesc), ResourceType = typeof(Texts))]
[AnimationSlider("F2", "", -100, 100)] [AnimationSlider("F2", "", -100, 100)]
[ShowPropertyEditorWhen(nameof(IsTrack0Visible), true)]
public Animation Track0 { get; } = new Animation(0, YMM4Constants.VerySmallValue, YMM4Constants.VeryLargeValue); 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))] [Display(GroupName = nameof(Texts.ParametersGroup), Name = nameof(Texts.Track1), Description = nameof(Texts.TrackDesc), ResourceType = typeof(Texts))]
[AnimationSlider("F2", "", -100, 100)] [AnimationSlider("F2", "", -100, 100)]
[ShowPropertyEditorWhen(nameof(IsTrack1Visible), true)]
public Animation Track1 { get; } = new Animation(0, YMM4Constants.VerySmallValue, YMM4Constants.VeryLargeValue); 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))] [Display(GroupName = nameof(Texts.ParametersGroup), Name = nameof(Texts.Track2), Description = nameof(Texts.TrackDesc), ResourceType = typeof(Texts))]
[AnimationSlider("F2", "", -100, 100)] [AnimationSlider("F2", "", -100, 100)]
[ShowPropertyEditorWhen(nameof(IsTrack2Visible), true)]
public Animation Track2 { get; } = new Animation(0, YMM4Constants.VerySmallValue, YMM4Constants.VeryLargeValue); 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))] [Display(GroupName = nameof(Texts.ParametersGroup), Name = nameof(Texts.Track3), Description = nameof(Texts.TrackDesc), ResourceType = typeof(Texts))]
[AnimationSlider("F2", "", -100, 100)] [AnimationSlider("F2", "", -100, 100)]
[ShowPropertyEditorWhen(nameof(IsTrack3Visible), true)]
public Animation Track3 { get; } = new Animation(0, YMM4Constants.VerySmallValue, YMM4Constants.VeryLargeValue); public Animation Track3 { get; } = new Animation(0, YMM4Constants.VerySmallValue, YMM4Constants.VeryLargeValue);
[Display(GroupName = nameof(Texts.ParametersGroup), Name = nameof(Texts.Slider0), Description = nameof(Texts.SliderDesc), ResourceType = typeof(Texts))]
[TextBoxSlider("F0", "", 1, 10)]
[DefaultValue(1)]
[ShowPropertyEditorWhen(nameof(IsSlider0Visible), true)]
public int Slider0 { get => _slider0; set => Set(ref _slider0, value); }
int _slider0 = 1;
[Display(GroupName = nameof(Texts.ParametersGroup), Name = nameof(Texts.Slider1), Description = nameof(Texts.SliderDesc), ResourceType = typeof(Texts))]
[TextBoxSlider("F0", "", 0, 100)]
[DefaultValue(0)]
[ShowPropertyEditorWhen(nameof(IsSlider1Visible), true)]
public int Slider1 { get => _slider1; set => Set(ref _slider1, value); }
int _slider1;
[Display(GroupName = nameof(Texts.ParametersGroup), Name = nameof(Texts.Slider2), Description = nameof(Texts.SliderDesc), ResourceType = typeof(Texts))]
[TextBoxSlider("F0", "", 0, 1000)]
[DefaultValue(0)]
[ShowPropertyEditorWhen(nameof(IsSlider2Visible), true)]
public int Slider2 { get => _slider2; set => Set(ref _slider2, value); }
int _slider2;
[Display(GroupName = nameof(Texts.ParametersGroup), Name = nameof(Texts.Slider3), Description = nameof(Texts.SliderDesc), ResourceType = typeof(Texts))]
[TextBoxSlider("F0", "", -1000, 1000)]
[DefaultValue(0)]
[ShowPropertyEditorWhen(nameof(IsSlider3Visible), true)]
public int Slider3 { get => _slider3; set => Set(ref _slider3, value); }
int _slider3;
[Display(GroupName = nameof(Texts.ParametersGroup), Name = nameof(Texts.Check0), Description = nameof(Texts.CheckDesc), ResourceType = typeof(Texts))]
[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;
[Display(GroupName = nameof(Texts.ParametersGroup), Name = nameof(Texts.Text), Description = nameof(Texts.TextDesc), ResourceType = typeof(Texts))]
[TextEditor(AcceptsReturn = true, PropertyEditorSize = PropertyEditorSize.FullWidth)]
[ShowPropertyEditorWhen(nameof(IsTextVisible), true)]
public string Text { get => _text; set => Set(ref _text, value); }
string _text = string.Empty;
[Display(GroupName = nameof(Texts.ParametersGroup), Name = nameof(Texts.Font), Description = nameof(Texts.FontDesc), ResourceType = typeof(Texts))]
[FontComboBox]
[ShowPropertyEditorWhen(nameof(IsFontVisible), true)]
public string Font { get => _font; set => Set(ref _font, value); }
string _font = "メイリオ";
[Display(GroupName = nameof(Texts.ParametersGroup), Name = nameof(Texts.Directory), Description = nameof(Texts.DirectoryDesc), ResourceType = typeof(Texts))]
[DirectorySelector(PropertyEditorSize = PropertyEditorSize.FullWidth)]
[ShowPropertyEditorWhen(nameof(IsDirectoryVisible), true)]
public string Directory { get => _directory; set => Set(ref _directory, value); }
string _directory = string.Empty;
[Display(GroupName = nameof(Texts.ParametersGroup), Name = nameof(Texts.FileVideo), Description = nameof(Texts.FileDesc), ResourceType = typeof(Texts))]
[FileSelector(FileGroupType.VideoItem)]
[ShowPropertyEditorWhen(nameof(IsFileVideoVisible), true)]
public string FileVideo { get => _fileVideo; set => Set(ref _fileVideo, value); }
string _fileVideo = string.Empty;
[Display(GroupName = nameof(Texts.ParametersGroup), Name = nameof(Texts.FileAudio), Description = nameof(Texts.FileDesc), ResourceType = typeof(Texts))]
[FileSelector(FileGroupType.AudioItem)]
[ShowPropertyEditorWhen(nameof(IsFileAudioVisible), true)]
public string FileAudio { get => _fileAudio; set => Set(ref _fileAudio, value); }
string _fileAudio = string.Empty;
[Display(GroupName = nameof(Texts.ParametersGroup), Name = nameof(Texts.FileImage), Description = nameof(Texts.FileDesc), ResourceType = typeof(Texts))]
[FileSelector(FileGroupType.ImageItem)]
[ShowPropertyEditorWhen(nameof(IsFileImageVisible), true)]
public string FileImage { get => _fileImage; set => Set(ref _fileImage, value); }
string _fileImage = string.Empty;
[Display(GroupName = nameof(Texts.ParametersGroup), Name = nameof(Texts.FileProject), Description = nameof(Texts.FileDesc), ResourceType = typeof(Texts))]
[FileSelector(FileGroupType.Project)]
[ShowPropertyEditorWhen(nameof(IsFileProjectVisible), true)]
public string FileProject { get => _fileProject; set => Set(ref _fileProject, value); }
string _fileProject = string.Empty;
[Display(GroupName = nameof(Texts.ParametersGroup), Name = nameof(Texts.FileMp4), Description = nameof(Texts.FileDesc), ResourceType = typeof(Texts))]
[FileSelector(FileGroupType.MP4)]
[ShowPropertyEditorWhen(nameof(IsFileMp4Visible), true)]
public string FileMp4 { get => _fileMp4; set => Set(ref _fileMp4, value); }
string _fileMp4 = string.Empty;
[Display(GroupName = nameof(Texts.ParametersGroup), Name = nameof(Texts.FileExo), Description = nameof(Texts.FileDesc), ResourceType = typeof(Texts))]
[FileSelector(FileGroupType.Exo)]
[ShowPropertyEditorWhen(nameof(IsFileExoVisible), true)]
public string FileExo { get => _fileExo; set => Set(ref _fileExo, value); }
string _fileExo = string.Empty;
[Display(GroupName = nameof(Texts.ParametersGroup), Name = nameof(Texts.FileSubtitle), Description = nameof(Texts.FileDesc), ResourceType = typeof(Texts))]
[FileSelector(FileGroupType.Subtitle)]
[ShowPropertyEditorWhen(nameof(IsFileSubtitleVisible), true)]
public string FileSubtitle { get => _fileSubtitle; set => Set(ref _fileSubtitle, value); }
string _fileSubtitle = string.Empty;
[Display(GroupName = nameof(Texts.ParametersGroup), Name = nameof(Texts.FileShader), Description = nameof(Texts.FileDesc), ResourceType = typeof(Texts))]
[FileSelector(FileGroupType.PixelShaderSource)]
[ShowPropertyEditorWhen(nameof(IsFileShaderVisible), true)]
public string FileShader { get => _fileShader; set => Set(ref _fileShader, value); }
string _fileShader = string.Empty;
[JsonIgnore] public bool IsSlider0Visible { get => _isSlider0Visible; private set => Set(ref _isSlider0Visible, value); }
[JsonIgnore] public bool IsSlider1Visible { get => _isSlider1Visible; private set => Set(ref _isSlider1Visible, value); }
[JsonIgnore] public bool IsSlider2Visible { get => _isSlider2Visible; private set => Set(ref _isSlider2Visible, value); }
[JsonIgnore] public bool IsSlider3Visible { get => _isSlider3Visible; private set => Set(ref _isSlider3Visible, value); }
[JsonIgnore] public bool IsTrack0Visible { get => _isTrack0Visible; private set => Set(ref _isTrack0Visible, value); }
[JsonIgnore] public bool 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); }
[JsonIgnore] public bool IsTextVisible { get => _isTextVisible; private set => Set(ref _isTextVisible, value); }
[JsonIgnore] public bool IsFontVisible { get => _isFontVisible; private set => Set(ref _isFontVisible, value); }
[JsonIgnore] public bool IsDirectoryVisible { get => _isDirectoryVisible; private set => Set(ref _isDirectoryVisible, value); }
[JsonIgnore] public bool IsFileVideoVisible { get => _isFileVideoVisible; private set => Set(ref _isFileVideoVisible, value); }
[JsonIgnore] public bool IsFileAudioVisible { get => _isFileAudioVisible; private set => Set(ref _isFileAudioVisible, value); }
[JsonIgnore] public bool IsFileImageVisible { get => _isFileImageVisible; private set => Set(ref _isFileImageVisible, value); }
[JsonIgnore] public bool IsFileProjectVisible { get => _isFileProjectVisible; private set => Set(ref _isFileProjectVisible, value); }
[JsonIgnore] public bool IsFileMp4Visible { get => _isFileMp4Visible; private set => Set(ref _isFileMp4Visible, value); }
[JsonIgnore] public bool IsFileExoVisible { get => _isFileExoVisible; private set => Set(ref _isFileExoVisible, value); }
[JsonIgnore] public bool IsFileSubtitleVisible { get => _isFileSubtitleVisible; private set => Set(ref _isFileSubtitleVisible, value); }
[JsonIgnore] public bool IsFileShaderVisible { get => _isFileShaderVisible; private set => Set(ref _isFileShaderVisible, value); }
bool _isSlider0Visible;
bool _isSlider1Visible;
bool _isSlider2Visible;
bool _isSlider3Visible;
bool _isTrack0Visible = true;
bool _isTrack1Visible = true;
bool _isTrack2Visible = true;
bool _isTrack3Visible = true;
bool _isCheck0Visible;
bool _isCheck1Visible;
bool _isCheck2Visible;
bool _isCheck3Visible;
bool _isColorVisible;
bool _isTextVisible;
bool _isFontVisible;
bool _isDirectoryVisible;
bool _isFileVideoVisible;
bool _isFileAudioVisible;
bool _isFileImageVisible;
bool _isFileProjectVisible;
bool _isFileMp4Visible;
bool _isFileExoVisible;
bool _isFileSubtitleVisible;
bool _isFileShaderVisible;
private void UpdateLayout()
{
var layout = AviUtlParameterLayout.Parse(_script);
Layout = layout;
bool hasAny = layout.HasAny;
var usage = ScriptParameterUsage.Detect(_script);
IsSlider0Visible = usage.Slider(0);
IsSlider1Visible = usage.Slider(1);
IsSlider2Visible = usage.Slider(2);
IsSlider3Visible = usage.Slider(3);
IsTrack0Visible = !hasAny || layout.HasTrack(0);
IsTrack1Visible = !hasAny || layout.HasTrack(1);
IsTrack2Visible = !hasAny || layout.HasTrack(2);
IsTrack3Visible = !hasAny || layout.HasTrack(3);
IsCheck0Visible = layout.HasCheck(0) || (!hasAny && usage.Check0);
IsCheck1Visible = layout.HasCheck(1) || (!hasAny && usage.Check1);
IsCheck2Visible = layout.HasCheck(2) || (!hasAny && usage.Check2);
IsCheck3Visible = layout.HasCheck(3) || (!hasAny && usage.Check3);
IsColorVisible = layout.HasColor || (!hasAny && usage.Color);
IsTextVisible = usage.Uses("text");
IsFontVisible = usage.Uses("font");
IsDirectoryVisible = usage.Uses("dir");
IsFileVideoVisible = usage.Uses("file_video");
IsFileAudioVisible = usage.Uses("file_audio");
IsFileImageVisible = usage.Uses("file_image");
IsFileProjectVisible = usage.Uses("file_project");
IsFileMp4Visible = usage.Uses("file_mp4");
IsFileExoVisible = usage.Uses("file_exo");
IsFileSubtitleVisible = usage.Uses("file_subtitle");
IsFileShaderVisible = usage.Uses("file_shader");
SeedDefaults(layout);
}
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 IEnumerable<string> CreateExoVideoFilters(int keyFrameIndex, ExoOutputDescription exoOutputDescription) => [];
public override IVideoEffectProcessor CreateVideoEffect(IGraphicsDevicesAndContext devices) public override IVideoEffectProcessor CreateVideoEffect(IGraphicsDevicesAndContext devices)
+520 -175
ファイルの表示
@@ -1,5 +1,10 @@
using System.IO;
using System.Numerics; using System.Numerics;
using System.Runtime.InteropServices; using System.Runtime.InteropServices;
using LuaScript.Compat;
using LuaScript.Diagnostics;
using LuaScript.Engine;
using LuaScript.Engine.Kernel;
using Vortice; using Vortice;
using Vortice.DCommon; using Vortice.DCommon;
using Vortice.Direct2D1; using Vortice.Direct2D1;
@@ -25,7 +30,18 @@ namespace LuaScript
double Track1, double Track1,
double Track2, double Track2,
double Track3, double Track3,
double Slider0,
double Slider1,
double Slider2,
double Slider3,
bool Check0,
bool Check1,
bool Check2,
bool Check3,
bool HasColor,
int Color,
string Script, string Script,
int StringsVersion,
TimelineSourceUsage Usage, TimelineSourceUsage Usage,
Guid SceneId, Guid SceneId,
int TimelineFrame, int TimelineFrame,
@@ -42,34 +58,126 @@ namespace LuaScript
DrawDescription InputDesc 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 LuaScriptEngine _engine = new();
private readonly SemaphoreSlim _pixelLoaderSemaphore = new(1, 1); private readonly SemaphoreSlim _pixelLoaderSemaphore = new(1, 1);
private AviUtlScriptContext _context = new();
private LuaJitWorker? _nativeWorker;
private double[]? _nativeFields;
private bool _nativeWarned;
private bool _effectChainWarned;
private bool _gpuWarned;
private string _kernelSource = string.Empty;
private bool _kernelResolved;
private KernelProgram? _kernelProgram;
private CpuKernel? _cpuKernel;
private GpuKernel? _gpuKernel;
private bool _gpuKernelChecked;
private double[]? _kernelUniforms;
private EffectDescription? _frameDesc;
private SceneObjectResolver? _frameResolver;
private bool _frameResolverBuilt;
private Guid _lastSceneGuid;
private string _lastSceneId = string.Empty;
private bool _sceneIdCached;
private GraphicsDevicesAndContext? _ownCtx; private GraphicsDevicesAndContext? _ownCtx;
private ID2D1Bitmap1? _renderTarget; private PixelBufferManager? _pixelManager;
private ID2D1Bitmap1? _stagingBitmap;
private ID2D1Bitmap1? _outputBitmap;
private AffineTransform2D? _transformEffect;
private byte[]? _pixelBuffer;
private int _bitmapWidth;
private int _bitmapHeight;
private RawRectF _cachedBounds;
private bool _isFirst = true; private bool _isFirst = true;
private string _sourceScript = string.Empty;
private string _runnableScript = string.Empty;
private int[] _runnableLineMap = [];
private bool _runnableCached;
private ID2D1Image? _cachedInput; private ID2D1Image? _cachedInput;
private RenderKey _cachedKey; private RenderKey _cachedKey;
private SceneObjectQuery[] _cachedQueries = []; private SceneObjectQuery[] _cachedQueries = [];
private DrawDescription? _cachedOutputDesc; private DrawDescription? _cachedOutputDesc;
private bool _cachedPixelsModified; private ID2D1Image? _cachedEffectOutput;
private VideoEffectChain? _effectChain;
private DrawCompositor? _drawCompositor;
private TextRenderer? _nativeTextRenderer;
private ImageDecoder? _nativeImageDecoder;
private MovieDecoder? _nativeMovieDecoder;
protected override ID2D1Image? CreateEffect(IGraphicsDevicesAndContext devices) protected override ID2D1Image? CreateEffect(IGraphicsDevicesAndContext devices)
{ {
_ownCtx = new GraphicsDevicesAndContext(devices); _ownCtx = new GraphicsDevicesAndContext(devices);
disposer.Collect(_ownCtx); disposer.Collect(_ownCtx);
_pixelManager = new PixelBufferManager(_ownCtx);
_context.ResolverProvider = GetFrameResolver;
return null; 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;
var (code, lineMap) = AviUtlScript.TransformWithMap(source);
_runnableScript = code;
_runnableLineMap = lineMap;
_sourceScript = source;
_runnableCached = true;
return _runnableScript;
}
private static LuaScriptDiagnosticKind ClassifyDiagnostic(LuaScriptException exception) => exception switch
{
LuaScriptCompilationException => LuaScriptDiagnosticKind.Compile,
LuaScriptTimeoutException => LuaScriptDiagnosticKind.Timeout,
_ => LuaScriptDiagnosticKind.Runtime,
};
private LuaScriptDiagnostic CreateDiagnostic(LuaScriptDiagnosticKind kind, string message)
{
var diagnostic = LuaScriptDiagnosticParser.Parse(kind, message);
return diagnostic.Line > 0
? diagnostic with { Line = MapRunnableLine(diagnostic.Line) }
: diagnostic;
}
private int MapRunnableLine(int runnableLine)
{
int index = runnableLine - 1;
if (index < 0 || index >= _runnableLineMap.Length)
return runnableLine;
int sourceLine = _runnableLineMap[index];
return sourceLine >= 0 ? sourceLine + 1 : 0;
}
protected override void setInput(ID2D1Image? input) protected override void setInput(ID2D1Image? input)
{ {
if (!ReferenceEquals(_cachedInput, input)) if (!ReferenceEquals(_cachedInput, input))
@@ -93,17 +201,26 @@ namespace LuaScript
var time = desc.ItemPosition.Time.TotalSeconds; var time = desc.ItemPosition.Time.TotalSeconds;
var script = item.Script ?? string.Empty; var script = item.Script ?? string.Empty;
var t0 = item.Track0.GetValue(frame, length, fps); var layout = item.Layout;
var t1 = item.Track1.GetValue(frame, length, fps); var t0 = ClampTrack(item.Track0.GetValue(frame, length, fps), layout, 0);
var t2 = item.Track2.GetValue(frame, length, fps); var t1 = ClampTrack(item.Track1.GetValue(frame, length, fps), layout, 1);
var t3 = item.Track3.GetValue(frame, length, fps); 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;
double s0 = item.Slider0, s1 = item.Slider1, s2 = item.Slider2, s3 = item.Slider3;
bool hasColor = item.IsColorVisible;
int colorRgb = hasColor ? (item.Color.R << 16) | (item.Color.G << 8) | item.Color.B : 0;
var inDesc = desc.DrawDescription; var inDesc = desc.DrawDescription;
var key = new RenderKey( var key = new RenderKey(
frame, time, length, fps, frame, time, length, fps,
t0, t1, t2, t3, t0, t1, t2, t3,
script, desc.Usage, desc.SceneId, s0, s1, s2, s3,
c0, c1, c2, c3, hasColor, colorRgb,
script, RefreshStringParameters(),
desc.Usage, desc.SceneId,
desc.TimelinePosition.Frame, desc.TimelinePosition.Frame,
desc.TimelinePosition.Time.TotalSeconds, desc.TimelinePosition.Time.TotalSeconds,
desc.ScreenSize.Width, desc.ScreenSize.Height, desc.ScreenSize.Width, desc.ScreenSize.Height,
@@ -113,12 +230,14 @@ namespace LuaScript
desc.TimelineDuration.Time.TotalSeconds, desc.TimelineDuration.Time.TotalSeconds,
inDesc); inDesc);
var resolver = BuildSceneObjectResolver(desc); _frameDesc = desc;
_frameResolver = null;
_frameResolverBuilt = false;
if (!_isFirst && key == _cachedKey && if (!_isFirst && key == _cachedKey &&
QueriesMatch(_cachedQueries, resolver)) (_cachedQueries.Length == 0 || QueriesMatch(_cachedQueries, GetFrameResolver())))
{ {
effectOutput = _cachedPixelsModified ? _transformEffect?.Output : null; effectOutput = _cachedEffectOutput;
return _cachedOutputDesc ?? inDesc; return _cachedOutputDesc ?? inDesc;
} }
@@ -126,36 +245,96 @@ namespace LuaScript
int imgW = Math.Max(1, (int)Math.Ceiling(bounds.Right - bounds.Left)); int imgW = Math.Max(1, (int)Math.Ceiling(bounds.Right - bounds.Left));
int imgH = Math.Max(1, (int)Math.Ceiling(bounds.Bottom - bounds.Top)); 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)); ctx.SetPixelLoader(() => LoadInputPixels(bounds, imgW, imgH));
DrawDescription outDesc = inDesc; DrawDescription outDesc = inDesc;
bool pixelsModified = false; IReadOnlyList<LuaScriptDiagnostic> diagnostics = [];
try try
{ {
_engine.Execute(script, ctx); string runnable = GetRunnableScript(script);
EnsureKernel(runnable);
if (ExecuteKernelLane(runnable, ctx, bounds, imgW, imgH))
{
outDesc = inDesc;
}
else
{
bool wantNative = ScriptDirective.ResolveAuto(runnable) == ScriptEngineKind.Native;
bool nativeReady = wantNative && LuaJitWorker.IsAvailable(NativeDirectory);
if (wantNative && !nativeReady)
WarnNativeUnavailableOnce();
if (nativeReady)
{
ExecuteNative(runnable, ctx, bounds, imgW, imgH);
}
else
{
_engine.Execute(runnable, ctx);
if (ctx.IsPixelsDirty) if (ctx.IsPixelsDirty)
{ {
EnsureBitmaps(imgW, imgH); int bufW = ctx.ImageWidth;
WritePixelsToOutput(ctx.GetPixelBuffer()!, imgW); int bufH = ctx.ImageHeight;
UpdateTransformEffect(bounds); _pixelManager!.WritePixelsToOutput(ctx.GetPixelBuffer()!, bufW, bufH);
effectOutput = _transformEffect!.Output; if (ctx.BufferReplaced)
pixelsModified = true; effectOutput = _pixelManager.GetTransformOutput(-bufW / 2f, -bufH / 2f);
else
effectOutput = _pixelManager.GetTransformOutput(bounds.Left, bounds.Top);
} }
else else
{ {
effectOutput = null; effectOutput = null;
} }
}
if (ctx.DrawCommands.Count > 0)
{
ctx.EnsurePixelBuffer();
var drawBuffer = ctx.GetPixelBuffer();
if (drawBuffer is not null)
{
_drawCompositor ??= new DrawCompositor(_ownCtx);
effectOutput = _drawCompositor.Compose(drawBuffer, ctx.ImageWidth, ctx.ImageHeight, ctx.DrawCommands);
}
}
outDesc = BuildOutputDesc(inDesc, ctx); 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);
LuaScriptDiagnostics.Instance.Report(script, [CreateDiagnostic(LuaScriptDiagnosticKind.Timeout, ex.Message)]);
return inDesc;
} }
catch (LuaScriptException ex) catch (LuaScriptException ex)
{ {
effectOutput = null; effectOutput = null;
outDesc = inDesc; outDesc = inDesc;
Log.Default.Write(ex.Message, ex); Log.Default.Write(ex.Message, ex);
diagnostics = [CreateDiagnostic(ClassifyDiagnostic(ex), ex.Message)];
} }
finally finally
{ {
@@ -163,15 +342,24 @@ namespace LuaScript
_pixelLoaderSemaphore.Release(); _pixelLoaderSemaphore.Release();
} }
LuaScriptDiagnostics.Instance.Report(script, diagnostics);
_isFirst = false; _isFirst = false;
_cachedKey = key; _cachedKey = key;
_cachedQueries = [.. ctx.ObjectQueries]; _cachedQueries = ctx.ObjectQueries.Count == 0 ? [] : [.. ctx.ObjectQueries];
_cachedOutputDesc = outDesc; _cachedOutputDesc = outDesc;
_cachedPixelsModified = pixelsModified; _cachedEffectOutput = effectOutput;
return outDesc; return outDesc;
} }
private ID2D1Image ApplyEffectChain(ID2D1Image source, IReadOnlyList<AviUtlEffectRequest> requests, EffectDescription desc, ref DrawDescription drawDescription)
{
_effectChain ??= new VideoEffectChain(_ownCtx!);
var target = AviUtlCompatMap.ResolveTarget(item.Script);
return _effectChain.Apply(source, requests, desc, target, ref drawDescription);
}
private static SceneObjectResolver BuildSceneObjectResolver(EffectDescription desc) private static SceneObjectResolver BuildSceneObjectResolver(EffectDescription desc)
{ {
var scenes = desc.Scenes; var scenes = desc.Scenes;
@@ -219,7 +407,53 @@ namespace LuaScript
return true; return true;
} }
private static AviUtlScriptContext BuildContext(in RenderKey key, int imgW, int imgH, SceneObjectResolver resolver) private static readonly string[] s_stringParameterNames =
[
"text", "font", "dir",
"file_video", "file_audio", "file_image", "file_project",
"file_mp4", "file_exo", "file_subtitle", "file_shader",
];
private readonly string?[] _stringParameterValues = new string?[s_stringParameterNames.Length];
private int _stringParametersVersion;
private int RefreshStringParameters()
{
var values = _stringParameterValues;
bool changed = false;
changed |= UpdateStringSlot(values, 0, item.Text);
changed |= UpdateStringSlot(values, 1, item.Font);
changed |= UpdateStringSlot(values, 2, item.Directory);
changed |= UpdateStringSlot(values, 3, item.FileVideo);
changed |= UpdateStringSlot(values, 4, item.FileAudio);
changed |= UpdateStringSlot(values, 5, item.FileImage);
changed |= UpdateStringSlot(values, 6, item.FileProject);
changed |= UpdateStringSlot(values, 7, item.FileMp4);
changed |= UpdateStringSlot(values, 8, item.FileExo);
changed |= UpdateStringSlot(values, 9, item.FileSubtitle);
changed |= UpdateStringSlot(values, 10, item.FileShader);
if (changed)
_stringParametersVersion++;
return _stringParametersVersion;
}
private static bool UpdateStringSlot(string?[] values, int index, string value)
{
if (ReferenceEquals(values[index], value))
return false;
values[index] = value;
return true;
}
private void PopulateStringParameters(AviUtlScriptContext ctx)
{
var names = s_stringParameterNames;
var values = _stringParameterValues;
for (int i = 0; i < names.Length; i++)
ctx.SetStringParameter(names[i], values[i]);
}
private void PopulateContext(AviUtlScriptContext ctx, in RenderKey key, int imgW, int imgH)
{ {
var zoom = key.InputDesc.Zoom; var zoom = key.InputDesc.Zoom;
double zoomAvg = (zoom.X + zoom.Y) / 2d; double zoomAvg = (zoom.X + zoom.Y) / 2d;
@@ -227,51 +461,67 @@ namespace LuaScript
? (zoom.X - zoom.Y) / (zoom.X + zoom.Y) ? (zoom.X - zoom.Y) / (zoom.X + zoom.Y)
: 0d; : 0d;
return new AviUtlScriptContext ctx.ClearQueries();
ctx.ClearEffects();
ctx.ClearDraws();
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.Slider0 = key.Slider0;
ctx.Slider1 = key.Slider1;
ctx.Slider2 = key.Slider2;
ctx.Slider3 = key.Slider3;
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;
PopulateStringParameters(ctx);
}
private static double ClampTrack(double value, AviUtlParameterLayout layout, int index)
{ {
ImageWidth = imgW, return layout.GetTrack(index) is { } p ? Math.Clamp(value, p.Min, p.Max) : value;
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,
};
} }
private static DrawDescription BuildOutputDesc(DrawDescription inDesc, AviUtlScriptContext ctx) private static DrawDescription BuildOutputDesc(DrawDescription inDesc, AviUtlScriptContext ctx)
@@ -286,48 +536,201 @@ namespace LuaScript
}; };
} }
private void EnsureKernel(string runnable)
{
if (_kernelResolved && string.Equals(runnable, _kernelSource, StringComparison.Ordinal))
return;
_kernelSource = runnable;
_kernelResolved = true;
_kernelProgram = KernelExtractor.TryExtract(runnable);
_cpuKernel = _kernelProgram is null ? null : CpuKernelCompiler.Compile(_kernelProgram);
_gpuKernel?.Dispose();
_gpuKernel = null;
_gpuKernelChecked = false;
}
private bool ExecuteKernelLane(string runnable, AviUtlScriptContext ctx, RawRectF bounds, int imgW, int imgH)
{
if (_kernelProgram is null || _cpuKernel is null)
return false;
bool explicitDirective = ScriptDirective.TryResolveExplicit(runnable, out var kind);
if (explicitDirective && kind is not (ScriptEngineKind.Gpu or ScriptEngineKind.Cpu))
return false;
_kernelUniforms ??= KernelUniformBinding.Create();
KernelUniformBinding.Fill(ctx, _kernelUniforms);
if (explicitDirective && kind == ScriptEngineKind.Gpu)
{
var gpu = GetGpuKernel();
if (gpu is not null)
{
effectOutput = gpu.Apply(input!, _kernelUniforms);
return true;
}
WarnGpuUnavailableOnce();
}
byte[] buffer = LoadInputPixels(bounds, imgW, imgH);
_cpuKernel.Execute(buffer, imgW, imgH, _kernelUniforms);
_pixelManager!.WritePixelsToOutput(buffer, imgW, imgH);
effectOutput = _pixelManager.GetTransformOutput(bounds.Left, bounds.Top);
return true;
}
private GpuKernel? GetGpuKernel()
{
if (_gpuKernelChecked)
return _gpuKernel;
_gpuKernelChecked = true;
if (_kernelProgram is null)
return null;
try
{
var kernel = new GpuKernel(_ownCtx!, _kernelProgram);
if (kernel.IsReady)
_gpuKernel = kernel;
else
kernel.Dispose();
}
catch (Exception ex)
{
Log.Default.Write("LuaScript: GPU kernel initialization failed; falling back to CPU.", ex);
}
return _gpuKernel;
}
private void WarnGpuUnavailableOnce()
{
if (_gpuWarned) return;
_gpuWarned = true;
Log.Default.Write("LuaScript: GPU kernel unavailable; using the CPU kernel lane instead.");
}
private void WarnNativeUnavailableOnce()
{
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, ctx.StringParameters, buffer, imgW, imgH, NativeTimeoutMilliseconds,
(tag, frame) => ctx.ResolveObject(tag, frame, out var info) ? info : null,
NativeLoadFigure,
NativeLoadText,
NativeLoadImage,
NativeLoadMovie,
(name, args) => ctx.AddEffect(new AviUtlEffectRequest(name, args)),
ctx.AddDraw,
out bool dirty, out bool bufferReplaced, out byte[]? newPixels,
out int resultW, out int resultH, out string? error);
if (!ok)
{
if (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);
bool hasDraws = ctx.DrawCommands.Count > 0;
if (dirty)
{
int outW = bufferReplaced ? resultW : imgW;
int outH = bufferReplaced ? resultH : imgH;
byte[] outPixels = buffer;
if (bufferReplaced && newPixels != null)
{
outPixels = newPixels;
ctx.ReplaceBuffer(outPixels, outW, outH);
}
if (hasDraws)
{
ctx.SetResolvedBuffer(outPixels, outW, outH);
return true;
}
_pixelManager!.WritePixelsToOutput(outPixels, outW, outH);
if (bufferReplaced)
effectOutput = _pixelManager.GetTransformOutput(-outW / 2f, -outH / 2f);
else
effectOutput = _pixelManager.GetTransformOutput(bounds.Left, bounds.Top);
return true;
}
if (hasDraws)
{
ctx.SetResolvedBuffer(buffer, imgW, imgH);
return false;
}
effectOutput = null;
return false;
}
private (byte[] buffer, int w, int h) NativeLoadText(string family, string text, double size, bool bold, bool italic, int color)
{
_nativeTextRenderer ??= new TextRenderer();
var buffer = _nativeTextRenderer.Render(text, family, size, bold, italic, color, out int w, out int h);
return (buffer, w, h);
}
private (byte[] buffer, int w, int h) NativeLoadImage(string path)
{
_nativeImageDecoder ??= new ImageDecoder();
var buffer = _nativeImageDecoder.Decode(path, out int w, out int h);
return (buffer, w, h);
}
private (byte[] buffer, int w, int h) NativeLoadMovie(string path, double time)
{
_nativeMovieDecoder ??= new MovieDecoder();
var buffer = _nativeMovieDecoder.Decode(path, time, out int w, out int h);
return (buffer, w, h);
}
private static (byte[] buffer, int w, int h) NativeLoadFigure(string name, int color, double size, double lineWidth, double aspect)
{
aspect = Math.Clamp(aspect, -1d, 1d);
int boundingSize = Math.Max(1, (int)Math.Round(size));
double w = aspect >= 0d ? boundingSize * (1d - aspect) : boundingSize;
double h = aspect <= 0d ? boundingSize * (1d + aspect) : boundingSize;
int fw = Math.Max(1, (int)Math.Round(w));
int fh = Math.Max(1, (int)Math.Round(h));
var buffer = FigureRenderer.Render(name, fw, fh, color, lineWidth);
return (buffer, fw, fh);
}
private byte[] LoadInputPixels(RawRectF bounds, int width, int height) private byte[] LoadInputPixels(RawRectF bounds, int width, int height)
{ {
_pixelLoaderSemaphore.Wait(); _pixelLoaderSemaphore.Wait();
try try
{ {
EnsureBitmaps(width, height); return _pixelManager!.LoadInputPixels(input!, bounds, width, height);
var dc = _ownCtx!.DeviceContext;
var savedTarget = dc.Target;
dc.Target = _renderTarget;
dc.BeginDraw();
dc.Clear(null);
dc.DrawImage(input!, new Vector2(-bounds.Left, -bounds.Top));
dc.EndDraw();
dc.Target = savedTarget;
_stagingBitmap!.CopyFromBitmap(_renderTarget!);
var mapped = _stagingBitmap.Map(MapOptions.Read);
try
{
if (mapped.Pitch == width * 4)
{
Marshal.Copy(mapped.Bits, _pixelBuffer!, 0, width * height * 4);
}
else
{
for (int row = 0; row < height; row++)
Marshal.Copy(
mapped.Bits + mapped.Pitch * row,
_pixelBuffer!,
row * width * 4,
width * 4);
}
}
finally
{
_stagingBitmap.Unmap();
}
return _pixelBuffer!;
} }
finally finally
{ {
@@ -335,78 +738,20 @@ namespace LuaScript
} }
} }
private unsafe void WritePixelsToOutput(byte[] pixels, int width)
{
fixed (byte* ptr = pixels)
_outputBitmap!.CopyFromMemory(new nint(ptr), width * 4);
}
private void UpdateTransformEffect(RawRectF bounds)
{
if (_transformEffect is null)
{
_transformEffect = new AffineTransform2D(_ownCtx!.DeviceContext);
_transformEffect.SetInput(0, _outputBitmap, true);
_cachedBounds = default;
}
if (_cachedBounds.Left != bounds.Left || _cachedBounds.Top != bounds.Top)
{
_transformEffect.TransformMatrix = Matrix3x2.CreateTranslation(bounds.Left, bounds.Top);
_cachedBounds = bounds;
}
}
private void EnsureBitmaps(int width, int height)
{
if (_bitmapWidth == width && _bitmapHeight == height) return;
_renderTarget?.Dispose();
_stagingBitmap?.Dispose();
_outputBitmap?.Dispose();
_transformEffect?.Dispose();
_renderTarget = null;
_stagingBitmap = null;
_outputBitmap = null;
_transformEffect = null;
_bitmapWidth = 0;
_bitmapHeight = 0;
var dc = _ownCtx!.DeviceContext;
_renderTarget = dc.CreateEmptyBitmap(width, height, BitmapOptions.Target);
var stagingProps = new BitmapProperties1(
new PixelFormat(Format.B8G8R8A8_UNorm, Vortice.DCommon.AlphaMode.Premultiplied),
96f, 96f,
BitmapOptions.CpuRead | BitmapOptions.CannotDraw);
_stagingBitmap = dc.CreateBitmap(
new SizeI(width, height),
nint.Zero,
width * 4,
stagingProps);
_outputBitmap = dc.CreateEmptyBitmap(width, height, BitmapOptions.Target);
_pixelBuffer = new byte[width * height * 4];
_bitmapWidth = width;
_bitmapHeight = height;
}
protected override void Dispose(bool disposing) protected override void Dispose(bool disposing)
{ {
if (disposing) if (disposing)
{ {
_engine.Dispose(); _engine.Dispose();
_gpuKernel?.Dispose();
_nativeWorker?.Dispose();
_effectChain?.Dispose();
_drawCompositor?.Dispose();
_nativeTextRenderer?.Dispose();
_nativeImageDecoder?.Dispose();
_pixelLoaderSemaphore.Dispose(); _pixelLoaderSemaphore.Dispose();
_renderTarget?.Dispose(); _pixelManager?.Dispose();
_stagingBitmap?.Dispose(); _pixelManager = null;
_outputBitmap?.Dispose();
_transformEffect?.Dispose();
_renderTarget = null;
_stagingBitmap = null;
_outputBitmap = null;
_transformEffect = null;
} }
base.Dispose(disposing); base.Dispose(disposing);
} }
+363 -96
ファイルの表示
@@ -1,4 +1,4 @@
using System.Collections.Concurrent; using LuaScript.Compat;
using MoonSharp.Interpreter; using MoonSharp.Interpreter;
using MoonSharp.Interpreter.Debugging; using MoonSharp.Interpreter.Debugging;
using MoonSharp.Interpreter.Loaders; using MoonSharp.Interpreter.Loaders;
@@ -11,12 +11,6 @@ namespace LuaScript
LuaScriptException? Exception, LuaScriptException? Exception,
bool TimedOut); bool TimedOut);
private sealed record ExecutionJob(
string Code,
AviUtlScriptContext Context,
CancellationToken Cancellation,
TaskCompletionSource<ExecutionResult> Completion);
private sealed class ExecutionThread : IDisposable private sealed class ExecutionThread : IDisposable
{ {
private sealed class CancellationDebugger : IDebugger private sealed class CancellationDebugger : IDebugger
@@ -46,10 +40,31 @@ 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 Thread _thread;
private readonly CancellationDebugger _debugger = new(); 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 readonly Dictionary<string, DynValue> _options = new(StringComparer.Ordinal);
private readonly Dictionary<string, DynValue> _pixelOptions = new(StringComparer.Ordinal);
private TextRenderer? _textRenderer;
private ImageDecoder? _imageDecoder;
private MovieDecoder? _movieDecoder;
private string _fontFamily = string.Empty;
private double _fontSize = 34d;
private bool _fontBold;
private bool _fontItalic;
private int _fontColor = 0xFFFFFF;
private Script? _script; private Script? _script;
private DynValue? _compiledChunk; private DynValue? _compiledChunk;
private string _lastCompiledCode = string.Empty; private string _lastCompiledCode = string.Empty;
@@ -67,6 +82,8 @@ namespace LuaScript
internal ExecutionThread() internal ExecutionThread()
{ {
_activeCancellation = _cts.Token;
_debugger.UpdateToken(_cts.Token);
_thread = new Thread(WorkerLoop) _thread = new Thread(WorkerLoop)
{ {
IsBackground = true, IsBackground = true,
@@ -77,77 +94,65 @@ namespace LuaScript
internal ExecutionResult TryExecute(string code, AviUtlScriptContext ctx, int timeoutMs) internal ExecutionResult TryExecute(string code, AviUtlScriptContext ctx, int timeoutMs)
{ {
using var cts = new CancellationTokenSource(); _jobCode = code;
var tcs = new TaskCompletionSource<ExecutionResult>( _jobContext = ctx;
TaskCreationOptions.RunContinuationsAsynchronously); _jobException = null;
_doneSignal.Reset();
_workSignal.Release();
if (!_queue.TryAdd(new ExecutionJob(code, ctx, cts.Token, tcs))) if (_doneSignal.Wait(timeoutMs))
return new ExecutionResult( return new ExecutionResult(_jobException, false);
new LuaScriptRuntimeException("Script execution queue is full."), false);
if (tcs.Task.Wait(timeoutMs)) _cts.Cancel();
return tcs.Task.Result;
cts.Cancel();
return new ExecutionResult(null, TimedOut: true); return new ExecutionResult(null, TimedOut: true);
} }
private void WorkerLoop() private void WorkerLoop()
{ {
try while (true)
{ {
foreach (var job in _queue.GetConsumingEnumerable()) _workSignal.Wait();
ProcessJob(job); if (_disposeRequested)
}
catch (OperationCanceledException) { }
catch (InvalidOperationException) { }
}
private void ProcessJob(ExecutionJob job)
{
if (job.Cancellation.IsCancellationRequested)
{
job.Completion.TrySetResult(new ExecutionResult(null, TimedOut: true));
return; return;
ProcessJob();
_doneSignal.Set();
}
} }
_activeCancellation = job.Cancellation; private void ProcessJob()
_activeContext = job.Context; {
_debugger.UpdateToken(job.Cancellation); var context = _jobContext!;
_activeContext = context;
try try
{ {
EnsureScript(); EnsureScript();
EnsureScriptIntegrity(); EnsureScriptIntegrity();
EnsureCompiled(job.Code); EnsureCompiled(_jobCode);
SetupGlobals(job.Context); SetupGlobals(context);
_script!.Call(_compiledChunk!); _script!.Call(_compiledChunk!);
ReadBackGlobals(job.Context); ReadBackGlobals(context);
job.Completion.TrySetResult(new ExecutionResult(null, false)); _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) catch (LuaScriptException ex)
{ {
job.Completion.TrySetResult(new ExecutionResult(ex, false)); _jobException = ex;
} }
catch (ScriptRuntimeException ex) catch (ScriptRuntimeException ex)
{ {
job.Completion.TrySetResult(new ExecutionResult( _jobException = new LuaScriptRuntimeException(ex.DecoratedMessage ?? ex.Message, ex);
new LuaScriptRuntimeException(ex.DecoratedMessage ?? ex.Message, ex), false));
} }
catch (Exception ex) catch (Exception ex)
{ {
job.Completion.TrySetResult(new ExecutionResult( _jobException = new LuaScriptRuntimeException(ex.Message, ex);
new LuaScriptRuntimeException(ex.Message, ex), false));
} }
finally finally
{ {
_debugger.UpdateToken(default);
_activeContext = null; _activeContext = null;
_activeCancellation = default;
} }
} }
@@ -210,6 +215,14 @@ namespace LuaScript
var script = _script!; var script = _script!;
bool isFirstSetup = _objTable is null; bool isFirstSetup = _objTable is null;
_options.Clear();
_pixelOptions.Clear();
_fontFamily = string.Empty;
_fontSize = 34d;
_fontBold = false;
_fontItalic = false;
_fontColor = 0xFFFFFF;
if (isFirstSetup) if (isFirstSetup)
{ {
var sceneTable = new Table(script); var sceneTable = new Table(script);
@@ -269,10 +282,10 @@ namespace LuaScript
_ymm4TableSnapshot = null; _ymm4TableSnapshot = null;
} }
ResetUserTableKeys(_objTable!, ref _objTableSnapshot); ResetUserTableKeys(_objTable!, _objTableSnapshot);
ResetUserTableKeys(_sceneTable!, ref _sceneTableSnapshot); ResetUserTableKeys(_sceneTable!, _sceneTableSnapshot);
ResetUserTableKeys(_animTable!, ref _animTableSnapshot); ResetUserTableKeys(_animTable!, _animTableSnapshot);
ResetUserTableKeys(_ymm4Table!, ref _ymm4TableSnapshot); ResetUserTableKeys(_ymm4Table!, _ymm4TableSnapshot);
} }
script.Globals["time"] = ctx.Time; script.Globals["time"] = ctx.Time;
@@ -320,6 +333,18 @@ namespace LuaScript
_objTable!["track1"] = ctx.Track1; _objTable!["track1"] = ctx.Track1;
_objTable!["track2"] = ctx.Track2; _objTable!["track2"] = ctx.Track2;
_objTable!["track3"] = ctx.Track3; _objTable!["track3"] = ctx.Track3;
_objTable!["slider0"] = ctx.Slider0;
_objTable!["slider1"] = ctx.Slider1;
_objTable!["slider2"] = ctx.Slider2;
_objTable!["slider3"] = ctx.Slider3;
foreach (var parameter in ctx.StringParameters)
_objTable![parameter.Key] = parameter.Value;
_objTable!["check0"] = ctx.Check0;
_objTable!["check1"] = ctx.Check1;
_objTable!["check2"] = ctx.Check2;
_objTable!["check3"] = ctx.Check3;
if (ctx.HasColor)
script.Globals["color"] = ctx.ColorValue;
_objTable!["time"] = ctx.Time; _objTable!["time"] = ctx.Time;
_objTable!["frame"] = ctx.Frame; _objTable!["frame"] = ctx.Frame;
_objTable!["totalframe"] = ctx.TotalFrame; _objTable!["totalframe"] = ctx.TotalFrame;
@@ -366,34 +391,36 @@ namespace LuaScript
return keys; 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; if (snapshot is null) return;
var keysToRemove = new List<string>(); var buffer = _removalBuffer;
buffer.Clear();
foreach (var key in table.Keys) foreach (var key in table.Keys)
{ {
if (key.Type == DataType.String && if (key.Type == DataType.String &&
!snapshot.Contains(key.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; table[key] = DynValue.Nil;
} }
private void ResetUserGlobals(Script script) private void ResetUserGlobals(Script script)
{ {
var keysToRemove = new List<string>(); var buffer = _removalBuffer;
buffer.Clear();
foreach (var key in script.Globals.Keys) foreach (var key in script.Globals.Keys)
{ {
if (key.Type == DataType.String && if (key.Type == DataType.String &&
!_builtinGlobalSnapshot!.Contains(key.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; script.Globals[key] = DynValue.Nil;
} }
@@ -457,6 +484,255 @@ namespace LuaScript
}); });
obj["putpixeldata"] = DynValue.NewCallback((_, _) => DynValue.Void); 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 == 0 || args[0].Type != DataType.String)
return DynValue.Void;
switch (args[0].String)
{
case "figure" when args.Count >= 4:
LoadFigure(
args[1].Type == DataType.String ? args[1].String : string.Empty,
(int)(args[2].CastToNumber() ?? 0d),
args[3].CastToNumber() ?? 0d,
args.Count > 4 ? args[4].CastToNumber() ?? 0d : 0d,
args.Count > 5 ? Math.Clamp(args[5].CastToNumber() ?? 0d, -1d, 1d) : 0d);
break;
case "text":
LoadText(args.Count > 1 && args[1].Type == DataType.String ? args[1].String : string.Empty);
break;
case "image" when args.Count > 1 && args[1].Type == DataType.String:
LoadImage(args[1].String);
break;
case "movie" when args.Count > 1 && args[1].Type == DataType.String:
LoadMovie(
args[1].String,
args.Count > 2 ? args[2].CastToNumber() ?? _activeContext.Time : _activeContext.Time);
break;
}
return DynValue.Void;
});
obj["setfont"] = DynValue.NewCallback((_, args) =>
{
_activeCancellation.ThrowIfCancellationRequested();
if (args.Count == 0)
return DynValue.Void;
if (args[0].Type == DataType.String)
_fontFamily = args[0].String;
if (args.Count > 1)
_fontSize = args[1].CastToNumber() ?? _fontSize;
if (args.Count > 2)
{
int type = (int)(args[2].CastToNumber() ?? 0d);
_fontBold = (type & 1) != 0;
_fontItalic = (type & 2) != 0;
}
if (args.Count > 3)
_fontColor = (int)(args[3].CastToNumber() ?? _fontColor);
return DynValue.Void;
});
obj["effect"] = DynValue.NewCallback((_, args) =>
{
_activeCancellation.ThrowIfCancellationRequested();
if (_activeContext is null || args.Count == 0 || args[0].Type != DataType.String)
return DynValue.Void;
string name = args[0].String;
var arguments = new List<KeyValuePair<string, object>>();
for (int i = 1; i + 1 < args.Count; i += 2)
{
if (args[i].Type != DataType.String)
continue;
var value = args[i + 1];
object boxed = value.Type switch
{
DataType.Number => value.Number,
DataType.Boolean => value.Boolean,
DataType.String => value.String,
_ => value.CastToNumber() ?? 0d,
};
arguments.Add(new KeyValuePair<string, object>(args[i].String, boxed));
}
_activeContext.AddEffect(new AviUtlEffectRequest(name, arguments));
return DynValue.Void;
});
obj["draw"] = DynValue.NewCallback((_, args) =>
{
_activeCancellation.ThrowIfCancellationRequested();
if (_activeContext is null)
return DynValue.Void;
double ox = args.Count > 0 ? args[0].CastToNumber() ?? 0d : 0d;
double oy = args.Count > 1 ? args[1].CastToNumber() ?? 0d : 0d;
double oz = args.Count > 2 ? args[2].CastToNumber() ?? 0d : 0d;
double zoom = args.Count > 3 ? args[3].CastToNumber() ?? 1d : 1d;
double alpha = args.Count > 4 ? args[4].CastToNumber() ?? 1d : 1d;
double aspect = args.Count > 5 ? args[5].CastToNumber() ?? 0d : 0d;
_activeContext.AddDraw(new DrawCommand(ox, oy, oz, zoom, alpha, aspect, null, CurrentAntialias()));
return DynValue.Void;
});
obj["drawpoly"] = DynValue.NewCallback((_, args) =>
{
_activeCancellation.ThrowIfCancellationRequested();
if (_activeContext is null || args.Count < 12)
return DynValue.Void;
var poly = new double[DrawPolyMath.Length];
for (int i = 0; i < 12; i++)
poly[i] = args[i].CastToNumber() ?? 0d;
if (args.Count >= 20)
{
for (int i = 0; i < 8; i++)
poly[12 + i] = args[12 + i].CastToNumber() ?? 0d;
}
else
{
double w = _activeContext.ImageWidth;
double h = _activeContext.ImageHeight;
poly[12] = 0d; poly[13] = 0d;
poly[14] = w; poly[15] = 0d;
poly[16] = w; poly[17] = h;
poly[18] = 0d; poly[19] = h;
}
poly[20] = args.Count switch
{
13 => args[12].CastToNumber() ?? 1d,
>= 21 => args[20].CastToNumber() ?? 1d,
_ => 1d,
};
_activeContext.AddDraw(new DrawCommand(0d, 0d, 0d, 1d, poly[20], 0d, poly, CurrentAntialias()));
return DynValue.Void;
});
obj["copybuffer"] = DynValue.NewCallback((_, args) =>
{
_activeCancellation.ThrowIfCancellationRequested();
if (_activeContext is null || args.Count < 2 ||
args[0].Type != DataType.String || args[1].Type != DataType.String)
return DynValue.Void;
if (_activeContext.CopyBuffer(args[0].String, args[1].String))
RefreshObjDimensions();
return DynValue.Void;
});
obj["getvalue"] = DynValue.NewCallback((_, args) =>
{
_activeCancellation.ThrowIfCancellationRequested();
if (args.Count == 0 || args[0].Type != DataType.String)
return DynValue.NewNumber(0d);
var value = _objTable!.Get(args[0].String);
return value.Type == DataType.Number ? value : DynValue.NewNumber(0d);
});
obj["setoption"] = DynValue.NewCallback((_, args) =>
{
_activeCancellation.ThrowIfCancellationRequested();
if (args.Count == 0 || args[0].Type != DataType.String)
return DynValue.Void;
_options[args[0].String] = args.Count > 1 ? args[1] : DynValue.True;
return DynValue.Void;
});
obj["getoption"] = DynValue.NewCallback((_, args) =>
{
_activeCancellation.ThrowIfCancellationRequested();
if (args.Count == 0 || args[0].Type != DataType.String)
return DynValue.NewNumber(0d);
return _options.TryGetValue(args[0].String, out var value) ? value : DynValue.NewNumber(0d);
});
obj["pixeloption"] = DynValue.NewCallback((_, args) =>
{
_activeCancellation.ThrowIfCancellationRequested();
if (args.Count == 0 || args[0].Type != DataType.String)
return DynValue.Void;
_pixelOptions[args[0].String] = args.Count > 1 ? args[1] : DynValue.True;
return DynValue.Void;
});
}
private double CurrentAntialias() =>
_options.TryGetValue("antialias", out var value) && value.Type == DataType.Number
? value.Number
: 1d;
private void LoadFigure(string name, int color, double size, double line, double aspect)
{
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);
RefreshObjDimensions();
}
private void LoadText(string text)
{
_textRenderer ??= new TextRenderer();
var buffer = _textRenderer.Render(
text, _fontFamily, _fontSize, _fontBold, _fontItalic, _fontColor,
out int w, out int h);
_activeContext!.ReplaceBuffer(buffer, w, h);
RefreshObjDimensions();
}
private void LoadImage(string path)
{
_imageDecoder ??= new ImageDecoder();
var buffer = _imageDecoder.Decode(path, out int w, out int h);
_activeContext!.ReplaceBuffer(buffer, w, h);
RefreshObjDimensions();
}
private void LoadMovie(string path, double time)
{
_movieDecoder ??= new MovieDecoder();
var buffer = _movieDecoder.Decode(path, time, out int w, out int h);
_activeContext!.ReplaceBuffer(buffer, w, h);
RefreshObjDimensions();
}
private void RefreshObjDimensions()
{
int w = _activeContext!.ImageWidth;
int h = _activeContext.ImageHeight;
var obj = _objTable!;
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) private static DynValue BuildObjectTable(Script script, SceneObjectInfo info)
@@ -494,55 +770,46 @@ namespace LuaScript
ctx.Oz = _objTable.Get("oz").CastToNumber() ?? ctx.Oz; ctx.Oz = _objTable.Get("oz").CastToNumber() ?? ctx.Oz;
ctx.Alpha = _objTable.Get("alpha").CastToNumber() ?? ctx.Alpha; ctx.Alpha = _objTable.Get("alpha").CastToNumber() ?? ctx.Alpha;
double initialSx = ctx.Sx; ctx.ApplyWriteBack(
double initialSy = ctx.Sy; _objTable.Get("sx").CastToNumber() ?? ctx.Sx,
double initialZoom = ctx.Zoom; _objTable.Get("sy").CastToNumber() ?? ctx.Sy,
double initialAspect = ctx.Aspect; _objTable.Get("zoom").CastToNumber() ?? ctx.Zoom,
_objTable.Get("aspect").CastToNumber() ?? ctx.Aspect,
ctx.Sx = _objTable.Get("sx").CastToNumber() ?? ctx.Sx; _objTable.Get("rx").CastToNumber() ?? ctx.Rx,
ctx.Sy = _objTable.Get("sy").CastToNumber() ?? ctx.Sy; _objTable.Get("ry").CastToNumber() ?? ctx.Ry,
ctx.Zoom = _objTable.Get("zoom").CastToNumber() ?? ctx.Zoom; _objTable.Get("rz").CastToNumber() ?? ctx.Rz,
ctx.Aspect = _objTable.Get("aspect").CastToNumber() ?? ctx.Aspect; _objTable.Get("rxr").CastToNumber() ?? ctx.RxRad,
_objTable.Get("ryr").CastToNumber() ?? ctx.RyRad,
bool sxsyChanged = Math.Abs(ctx.Sx - initialSx) > 1e-10 || Math.Abs(ctx.Sy - initialSy) > 1e-10; _objTable.Get("rzr").CastToNumber() ?? ctx.RzRad);
bool zoomAspectChanged = Math.Abs(ctx.Zoom - initialZoom) > 1e-10 || Math.Abs(ctx.Aspect - initialAspect) > 1e-10;
if (zoomAspectChanged && !sxsyChanged)
{
ctx.Sx = ctx.Zoom * (1.0 + ctx.Aspect);
ctx.Sy = ctx.Zoom * (1.0 - ctx.Aspect);
}
double rxrNew = _objTable.Get("rxr").CastToNumber() ?? ctx.RxRad;
ctx.Rx = Math.Abs(rxrNew - ctx.RxRad) > 1e-10
? rxrNew * (180d / Math.PI)
: _objTable.Get("rx").CastToNumber() ?? ctx.Rx;
double ryrNew = _objTable.Get("ryr").CastToNumber() ?? ctx.RyRad;
ctx.Ry = Math.Abs(ryrNew - ctx.RyRad) > 1e-10
? ryrNew * (180d / Math.PI)
: _objTable.Get("ry").CastToNumber() ?? ctx.Ry;
double rzrNew = _objTable.Get("rzr").CastToNumber() ?? ctx.RzRad;
ctx.Rz = Math.Abs(rzrNew - ctx.RzRad) > 1e-10
? rzrNew * (180d / Math.PI)
: _objTable.Get("rz").CastToNumber() ?? ctx.Rz;
} }
public void Dispose() public void Dispose()
{ {
_queue.CompleteAdding(); _disposeRequested = true;
_workSignal.Release();
_thread.Join(); _thread.Join();
_queue.Dispose(); _textRenderer?.Dispose();
_imageDecoder?.Dispose();
_movieDecoder?.Dispose();
_cts.Cancel();
_cts.Dispose();
_workSignal.Dispose();
_doneSignal.Dispose();
} }
internal void AbandonAsync() internal void AbandonAsync()
{ {
_queue.CompleteAdding(); _disposeRequested = true;
_workSignal.Release();
ThreadPool.QueueUserWorkItem(_ => ThreadPool.QueueUserWorkItem(_ =>
{ {
_thread.Join(); _thread.Join();
_queue.Dispose(); _textRenderer?.Dispose();
_imageDecoder?.Dispose();
_movieDecoder?.Dispose();
_cts.Dispose();
_workSignal.Dispose();
_doneSignal.Dispose();
}); });
} }
@@ -577,7 +844,7 @@ namespace LuaScript
var stale = _executionThread; var stale = _executionThread;
_executionThread = new ExecutionThread(); _executionThread = new ExecutionThread();
stale.AbandonAsync(); stale.AbandonAsync();
throw new LuaScriptRuntimeException( throw new LuaScriptTimeoutException(
$"Script execution timed out after {ExecutionTimeoutMilliseconds} ms."); $"Script execution timed out after {ExecutionTimeoutMilliseconds} ms.");
} }
+6
ファイルの表示
@@ -0,0 +1,6 @@
using System;
namespace LuaScript
{
internal abstract class LuaScriptException(string message, Exception? inner = null) : Exception(message, inner);
}
-8
ファイルの表示
@@ -1,8 +0,0 @@
namespace LuaScript
{
internal abstract class LuaScriptException(string message, Exception? inner = null) : Exception(message, inner);
internal sealed class LuaScriptCompilationException(string message, Exception? inner = null) : LuaScriptException(message, inner);
internal sealed class LuaScriptRuntimeException(string message, Exception? inner = null) : LuaScriptException(message, inner);
}
+6
ファイルの表示
@@ -0,0 +1,6 @@
using System;
namespace LuaScript
{
internal sealed class LuaScriptRuntimeException(string message, Exception? inner = null) : LuaScriptException(message, inner);
}
+6
ファイルの表示
@@ -0,0 +1,6 @@
using System;
namespace LuaScript
{
internal sealed class LuaScriptTimeoutException(string message, Exception? inner = null) : LuaScriptException(message, inner);
}
+213
ファイルの表示
@@ -0,0 +1,213 @@
using System;
using System.IO;
using SharpGen.Runtime.Win32;
using Vortice.MediaFoundation;
namespace LuaScript
{
internal sealed class MovieDecoder : IDisposable
{
private const int MaxDimension = 8192;
private const int FirstVideoStream = -4;
private const int AllStreams = -2;
private const int EndOfStreamFlag = 0x2;
private bool _mfStarted;
private string? _path;
private IMFSourceReader? _reader;
private int _width;
private int _height;
private int _stride;
public unsafe byte[] Decode(string path, double timeSeconds, out int width, out int height)
{
width = 1;
height = 1;
if (string.IsNullOrEmpty(path) || !IsSupportedVideo(path))
return new byte[4];
try
{
EnsureReader(path);
if (_reader is null || _width <= 0 || _height <= 0)
return new byte[4];
SetPosition(_reader, (long)(Math.Max(0d, timeSeconds) * 10_000_000d));
using var sample = ReadVideoSample(_reader);
if (sample is null)
return new byte[4];
using var buffer = sample.ConvertToContiguousBuffer();
buffer.Lock(out nint data, out _, out _);
try
{
int w = _width;
int h = _height;
int absStride = Math.Abs(_stride);
bool bottomUp = _stride < 0;
var result = new byte[w * h * 4];
byte* src = (byte*)data;
fixed (byte* dst = result)
{
for (int y = 0; y < h; y++)
{
int sourceRow = bottomUp ? h - 1 - y : y;
byte* s = src + sourceRow * absStride;
byte* d = dst + y * w * 4;
for (int x = 0; x < w; x++)
{
d[0] = s[0];
d[1] = s[1];
d[2] = s[2];
d[3] = 255;
s += 4;
d += 4;
}
}
}
width = w;
height = h;
return result;
}
finally
{
buffer.Unlock();
}
}
catch
{
width = 1;
height = 1;
return new byte[4];
}
}
private void EnsureReader(string path)
{
if (_reader is not null && string.Equals(_path, path, StringComparison.Ordinal))
return;
DisposeReader();
if (!_mfStarted)
{
MediaFactory.MFStartup(false);
_mfStarted = true;
}
using var attributes = MediaFactory.MFCreateAttributes(1);
attributes.Set(SourceReaderAttributeKeys.EnableAdvancedVideoProcessing, 1);
var reader = MediaFactory.MFCreateSourceReaderFromURL(path, attributes);
reader.SetStreamSelection(AllStreams, false);
reader.SetStreamSelection(FirstVideoStream, true);
using (var mediaType = MediaFactory.MFCreateMediaType())
{
mediaType.Set(MediaTypeAttributeKeys.MajorType, MediaTypeGuids.Video);
mediaType.Set(MediaTypeAttributeKeys.Subtype, VideoFormatGuids.Rgb32);
reader.SetCurrentMediaType(FirstVideoStream, mediaType);
}
using var current = reader.GetCurrentMediaType(FirstVideoStream);
var mediaAttributes = (IMFAttributes)current;
ulong frameSize = Convert.ToUInt64(mediaAttributes.Get(MediaTypeAttributeKeys.FrameSize));
int w = (int)(frameSize >> 32);
int h = (int)(frameSize & 0xFFFFFFFF);
int stride;
try { stride = Convert.ToInt32(mediaAttributes.Get(MediaTypeAttributeKeys.DefaultStride)); }
catch { stride = w * 4; }
if (stride == 0)
stride = w * 4;
if (w <= 0 || h <= 0 || w > MaxDimension || h > MaxDimension)
{
reader.Dispose();
return;
}
_reader = reader;
_path = path;
_width = w;
_height = h;
_stride = stride;
}
private static void SetPosition(IMFSourceReader reader, long ticks)
{
var variant = new Variant
{
Value = ticks,
ElementType = (VariantElementType)20,
};
reader.SetCurrentPosition(Guid.Empty, variant);
}
private static IMFSample? ReadVideoSample(IMFSourceReader reader)
{
for (int guard = 0; guard < 256; guard++)
{
reader.ReadSample(FirstVideoStream, 0, out _, out int flags, out _, out IMFSample? sample);
if (sample is not null)
return sample;
if ((flags & EndOfStreamFlag) != 0)
return null;
}
return null;
}
private static bool IsSupportedVideo(string path)
{
try
{
if (!File.Exists(path))
return false;
Span<byte> head = stackalloc byte[16];
using var stream = File.OpenRead(path);
int read = stream.Read(head);
if (read < 12)
return false;
if (head[4] == 0x66 && head[5] == 0x74 && head[6] == 0x79 && head[7] == 0x70)
return true;
if (head[0] == 0x1A && head[1] == 0x45 && head[2] == 0xDF && head[3] == 0xA3)
return true;
if (head[0] == 0x52 && head[1] == 0x49 && head[2] == 0x46 && head[3] == 0x46 &&
head[8] == 0x41 && head[9] == 0x56 && head[10] == 0x49 && head[11] == 0x20)
return true;
if (head[0] == 0x46 && head[1] == 0x4C && head[2] == 0x56)
return true;
if (head[0] == 0x30 && head[1] == 0x26 && head[2] == 0xB2 && head[3] == 0x75)
return true;
return false;
}
catch
{
return false;
}
}
private void DisposeReader()
{
_reader?.Dispose();
_reader = null;
_path = null;
_width = 0;
_height = 0;
_stride = 0;
}
public void Dispose()
{
DisposeReader();
if (_mfStarted)
{
try { MediaFactory.MFShutdown(); }
catch { }
_mfStarted = false;
}
}
}
}
+145
ファイルの表示
@@ -0,0 +1,145 @@
using System;
using Vortice;
using System.Numerics;
using System.Runtime.InteropServices;
using Vortice.DCommon;
using Vortice.Direct2D1;
using Vortice.Direct2D1.Effects;
using Vortice.DXGI;
using Vortice.Mathematics;
using YukkuriMovieMaker.Commons;
namespace LuaScript
{
internal sealed class PixelBufferManager : IDisposable
{
private readonly GraphicsDevicesAndContext _ctx;
private ID2D1Bitmap1? _renderTarget;
private ID2D1Bitmap1? _stagingBitmap;
private ID2D1Bitmap1? _outputBitmap;
private AffineTransform2D? _transformEffect;
private byte[]? _pixelBuffer;
private int _bitmapWidth;
private int _bitmapHeight;
private RawRectF _cachedBounds;
public PixelBufferManager(GraphicsDevicesAndContext ctx)
{
_ctx = ctx;
}
public byte[] LoadInputPixels(ID2D1Image input, RawRectF bounds, int width, int height)
{
EnsureBitmaps(width, height);
var dc = _ctx.DeviceContext;
var savedTarget = dc.Target;
dc.Target = _renderTarget;
dc.BeginDraw();
dc.Clear(null);
dc.DrawImage(input, new Vector2(-bounds.Left, -bounds.Top));
dc.EndDraw();
dc.Target = savedTarget;
_stagingBitmap!.CopyFromBitmap(_renderTarget!);
var mapped = _stagingBitmap.Map(MapOptions.Read);
try
{
if (mapped.Pitch == width * 4)
{
Marshal.Copy(mapped.Bits, _pixelBuffer!, 0, width * height * 4);
}
else
{
for (int row = 0; row < height; row++)
Marshal.Copy(
mapped.Bits + mapped.Pitch * row,
_pixelBuffer!,
row * width * 4,
width * 4);
}
}
finally
{
_stagingBitmap.Unmap();
}
return _pixelBuffer!;
}
public unsafe void WritePixelsToOutput(byte[] pixels, int width, int height)
{
EnsureBitmaps(width, height);
fixed (byte* ptr = pixels)
_outputBitmap!.CopyFromMemory(new nint(ptr), width * 4);
}
public ID2D1Image GetTransformOutput(float left, float top)
{
if (_transformEffect is null)
{
_transformEffect = new AffineTransform2D(_ctx.DeviceContext);
_transformEffect.SetInput(0, _outputBitmap, true);
_cachedBounds = default;
}
if (_cachedBounds.Left != left || _cachedBounds.Top != top)
{
_transformEffect.TransformMatrix = Matrix3x2.CreateTranslation(left, top);
_cachedBounds = new RawRectF(left, top, left, top);
}
return _transformEffect.Output;
}
private void EnsureBitmaps(int width, int height)
{
if (_bitmapWidth == width && _bitmapHeight == height) return;
_renderTarget?.Dispose();
_stagingBitmap?.Dispose();
_outputBitmap?.Dispose();
_transformEffect?.Dispose();
_renderTarget = null;
_stagingBitmap = null;
_outputBitmap = null;
_transformEffect = null;
_bitmapWidth = 0;
_bitmapHeight = 0;
var dc = _ctx.DeviceContext;
_renderTarget = dc.CreateEmptyBitmap(width, height, BitmapOptions.Target);
var stagingProps = new BitmapProperties1(
new PixelFormat(Format.B8G8R8A8_UNorm, Vortice.DCommon.AlphaMode.Premultiplied),
96f, 96f,
BitmapOptions.CpuRead | BitmapOptions.CannotDraw);
_stagingBitmap = dc.CreateBitmap(
new SizeI(width, height),
nint.Zero,
width * 4,
stagingProps);
_outputBitmap = dc.CreateEmptyBitmap(width, height, BitmapOptions.Target);
_pixelBuffer = new byte[width * height * 4];
_bitmapWidth = width;
_bitmapHeight = height;
}
public void Dispose()
{
_renderTarget?.Dispose();
_stagingBitmap?.Dispose();
_outputBitmap?.Dispose();
_transformEffect?.Dispose();
_renderTarget = null;
_stagingBitmap = null;
_outputBitmap = null;
_transformEffect = null;
}
}
}
-5
ファイルの表示
@@ -10,9 +10,4 @@ namespace LuaScript
double Rz, double Rz,
double Alpha, double Alpha,
int Layer); int Layer);
internal readonly record struct SceneObjectQuery(
string Tag,
int Frame,
SceneObjectInfo? Result);
} }
+7
ファイルの表示
@@ -0,0 +1,7 @@
namespace LuaScript
{
internal readonly record struct SceneObjectQuery(
string Tag,
int Frame,
SceneObjectInfo? Result);
}
+97
ファイルの表示
@@ -0,0 +1,97 @@
using System;
using System.Numerics;
using Vortice.Direct2D1;
using Vortice.DirectWrite;
using Vortice.Mathematics;
using Vortice.WIC;
namespace LuaScript
{
internal sealed class TextRenderer : IDisposable
{
private const int MaxDimension = 8192;
private const string FallbackFamily = "Yu Gothic UI";
private ID2D1Factory? _d2dFactory;
private IWICImagingFactory? _wicFactory;
private IDWriteFactory? _dwriteFactory;
private void EnsureFactories()
{
_d2dFactory ??= D2D1.D2D1CreateFactory<ID2D1Factory>(
Vortice.Direct2D1.FactoryType.MultiThreaded, DebugLevel.None);
_wicFactory ??= new IWICImagingFactory();
_dwriteFactory ??= DWrite.DWriteCreateFactory<IDWriteFactory>(
Vortice.DirectWrite.FactoryType.Shared);
}
public unsafe byte[] Render(
string text, string fontFamily, double fontSize,
bool bold, bool italic, int colorRgb,
out int width, out int height)
{
width = 1;
height = 1;
if (string.IsNullOrEmpty(text))
return new byte[4];
EnsureFactories();
float size = (float)Math.Clamp(fontSize, 1d, 4096d);
using var format = _dwriteFactory!.CreateTextFormat(
string.IsNullOrWhiteSpace(fontFamily) ? FallbackFamily : fontFamily,
null,
bold ? FontWeight.Bold : FontWeight.Normal,
italic ? FontStyle.Italic : FontStyle.Normal,
FontStretch.Normal,
size,
string.Empty);
using var layout = _dwriteFactory.CreateTextLayout(text, format, MaxDimension, MaxDimension);
var metrics = layout.Metrics;
int w = Math.Clamp((int)Math.Ceiling(metrics.WidthIncludingTrailingWhitespace), 1, MaxDimension);
int h = Math.Clamp((int)Math.Ceiling(metrics.Height), 1, MaxDimension);
using var wic = _wicFactory!.CreateBitmap(
w, h, Vortice.WIC.PixelFormat.Format32bppPBGRA, BitmapCreateCacheOption.CacheOnLoad);
var properties = new RenderTargetProperties(
RenderTargetType.Default,
new Vortice.DCommon.PixelFormat(Vortice.DXGI.Format.B8G8R8A8_UNorm, Vortice.DCommon.AlphaMode.Premultiplied),
96f, 96f,
RenderTargetUsage.None,
FeatureLevel.Default);
float r = ((colorRgb >> 16) & 0xFF) / 255f;
float g = ((colorRgb >> 8) & 0xFF) / 255f;
float b = (colorRgb & 0xFF) / 255f;
using (var target = _d2dFactory!.CreateWicBitmapRenderTarget(wic, properties))
{
target.BeginDraw();
target.Clear(new Color4(0f, 0f, 0f, 0f));
using (var brush = target.CreateSolidColorBrush(new Color4(r, g, b, 1f)))
target.DrawTextLayout(new Vector2(-metrics.Left, -metrics.Top), layout, brush);
target.EndDraw();
}
var buffer = new byte[w * h * 4];
fixed (byte* p = buffer)
wic.CopyPixels(new RectI(0, 0, w, h), w * 4, buffer.Length, (nint)p);
width = w;
height = h;
return buffer;
}
public void Dispose()
{
_dwriteFactory?.Dispose();
_wicFactory?.Dispose();
_d2dFactory?.Dispose();
_dwriteFactory = null;
_wicFactory = null;
_d2dFactory = null;
}
}
}
+30
ファイルの表示
@@ -69,6 +69,33 @@
<data name="Track2" xml:space="preserve"><value>مسار 2</value></data> <data name="Track2" xml:space="preserve"><value>مسار 2</value></data>
<data name="Track3" xml:space="preserve"><value>مسار 3</value></data> <data name="Track3" xml:space="preserve"><value>مسار 3</value></data>
<data name="TrackDesc" xml:space="preserve"><value>قيمة المنزلق (متوافق مع AviUtl: track0-3)</value></data> <data name="TrackDesc" xml:space="preserve"><value>قيمة المنزلق (متوافق مع AviUtl: track0-3)</value></data>
<data name="Slider0" xml:space="preserve"><value>منزلق 0</value></data>
<data name="Slider1" xml:space="preserve"><value>منزلق 1</value></data>
<data name="Slider2" xml:space="preserve"><value>منزلق 2</value></data>
<data name="Slider3" xml:space="preserve"><value>منزلق 3</value></data>
<data name="SliderDesc" xml:space="preserve"><value>منزلق رقمي (obj.slider0-3)</value></data>
<data name="Check0" xml:space="preserve"><value>خانة 0</value></data>
<data name="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="Text" xml:space="preserve"><value>نص</value></data>
<data name="TextDesc" xml:space="preserve"><value>إدخال نص (obj.text)</value></data>
<data name="Font" xml:space="preserve"><value>خط</value></data>
<data name="FontDesc" xml:space="preserve"><value>اختيار الخط (obj.font)</value></data>
<data name="Directory" xml:space="preserve"><value>مجلد</value></data>
<data name="DirectoryDesc" xml:space="preserve"><value>اختيار المجلد (obj.dir)</value></data>
<data name="FileDesc" xml:space="preserve"><value>اختيار الملف (obj.file_*)</value></data>
<data name="FileVideo" xml:space="preserve"><value>ملف فيديو</value></data>
<data name="FileAudio" xml:space="preserve"><value>ملف صوتي</value></data>
<data name="FileImage" xml:space="preserve"><value>ملف صورة</value></data>
<data name="FileProject" xml:space="preserve"><value>ملف المشروع</value></data>
<data name="FileMp4" xml:space="preserve"><value>ملف MP4</value></data>
<data name="FileExo" xml:space="preserve"><value>ملف EXO</value></data>
<data name="FileSubtitle" xml:space="preserve"><value>ملف الترجمة</value></data>
<data name="FileShader" xml:space="preserve"><value>ملف التظليل</value></data>
<data name="ToolBarImport" xml:space="preserve"><value>استيراد</value></data> <data name="ToolBarImport" xml:space="preserve"><value>استيراد</value></data>
<data name="ToolBarExport" xml:space="preserve"><value>تصدير</value></data> <data name="ToolBarExport" xml:space="preserve"><value>تصدير</value></data>
<data name="ToolBarClear" xml:space="preserve"><value>مسح</value></data> <data name="ToolBarClear" xml:space="preserve"><value>مسح</value></data>
@@ -77,4 +104,7 @@
<data name="ToolBarImportErrorTitle" xml:space="preserve"><value>خطأ في الاستيراد</value></data> <data name="ToolBarImportErrorTitle" xml:space="preserve"><value>خطأ في الاستيراد</value></data>
<data name="ToolBarExportErrorTitle" xml:space="preserve"><value>خطأ في التصدير</value></data> <data name="ToolBarExportErrorTitle" xml:space="preserve"><value>خطأ في التصدير</value></data>
<data name="LuaFileFilter" xml:space="preserve"><value>نص Lua (*.lua)|*.lua|جميع الملفات (*.*)|*.*</value></data> <data name="LuaFileFilter" xml:space="preserve"><value>نص Lua (*.lua)|*.lua|جميع الملفات (*.*)|*.*</value></data>
<data name="DiagnosticCompile" xml:space="preserve"><value>خطأ في بناء الجملة</value></data>
<data name="DiagnosticRuntime" xml:space="preserve"><value>خطأ وقت التشغيل</value></data>
<data name="DiagnosticTimeout" xml:space="preserve"><value>انتهت المهلة</value></data>
</root> </root>
+30
ファイルの表示
@@ -9,6 +9,33 @@ Track1,,トラック1,Track 1,轨道1,軌道1,트랙1,Pista 1,مسار 1,Jalur 1
Track2,,トラック2,Track 2,轨道2,軌道2,트랙2,Pista 2,مسار 2,Jalur 2 Track2,,トラック2,Track 2,轨道2,軌道2,트랙2,Pista 2,مسار 2,Jalur 2
Track3,,トラック3,Track 3,轨道3,軌道3,트랙3,Pista 3,مسار 3,Jalur 3 Track3,,トラック3,Track 3,轨道3,軌道3,트랙3,Pista 3,مسار 3,Jalur 3
TrackDesc,,スライダー値 (AviUtl準拠 track0〜3 に対応),Slider value (AviUtl compatible: track0–3),滑块值(AviUtl兼容: track0~3),滑塊值(AviUtl兼容: track0~3),슬라이더 값 (AviUtl 호환: track0~3),Valor del deslizador (compatible AviUtl: track0-3),قيمة المنزلق (متوافق مع AviUtl: track0-3),Nilai slider (kompatibel AviUtl: track0-3) TrackDesc,,スライダー値 (AviUtl準拠 track0〜3 に対応),Slider value (AviUtl compatible: track0–3),滑块值(AviUtl兼容: track0~3),滑塊值(AviUtl兼容: track0~3),슬라이더 값 (AviUtl 호환: track0~3),Valor del deslizador (compatible AviUtl: track0-3),قيمة المنزلق (متوافق مع AviUtl: track0-3),Nilai slider (kompatibel AviUtl: track0-3)
Slider0,,スライダー0,Slider 0,滑块0,滑塊0,슬라이더0,Deslizador 0,منزلق 0,Slider 0
Slider1,,スライダー1,Slider 1,滑块1,滑塊1,슬라이더1,Deslizador 1,منزلق 1,Slider 1
Slider2,,スライダー2,Slider 2,滑块2,滑塊2,슬라이더2,Deslizador 2,منزلق 2,Slider 2
Slider3,,スライダー3,Slider 3,滑块3,滑塊3,슬라이더3,Deslizador 3,منزلق 3,Slider 3
SliderDesc,,数値スライダー (obj.slider0〜3 で参照),Numeric slider (obj.slider0–3),数值滑块 (obj.slider0~3),數值滑塊 (obj.slider0~3),숫자 슬라이더 (obj.slider0~3),Deslizador numérico (obj.slider0-3),منزلق رقمي (obj.slider0-3),Slider numerik (obj.slider0-3)
Check0,,チェック0,Check 0,复选框0,核取方塊0,체크0,Casilla 0,خانة 0,Centang 0
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)
Text,,テキスト,Text,文本,文字,텍스트,Texto,نص,Teks
TextDesc,,テキスト入力 (obj.text で参照),Text input (obj.text),文本输入 (obj.text),文字輸入 (obj.text),텍스트 입력 (obj.text),Entrada de texto (obj.text),إدخال نص (obj.text),Masukan teks (obj.text)
Font,,フォント,Font,字体,字型,글꼴,Fuente,خط,Font
FontDesc,,フォント選択 (obj.font で参照),Font selection (obj.font),字体选择 (obj.font),字型選擇 (obj.font),글꼴 선택 (obj.font),Selección de fuente (obj.font),اختيار الخط (obj.font),Pilihan font (obj.font)
Directory,,フォルダ,Folder,文件夹,資料夾,폴더,Carpeta,مجلد,Folder
DirectoryDesc,,フォルダ選択 (obj.dir で参照),Folder selection (obj.dir),文件夹选择 (obj.dir),資料夾選擇 (obj.dir),폴더 선택 (obj.dir),Selección de carpeta (obj.dir),اختيار المجلد (obj.dir),Pilihan folder (obj.dir)
FileDesc,,ファイル選択 (obj.file_* で参照),File selection (obj.file_*),文件选择 (obj.file_*),檔案選擇 (obj.file_*),파일 선택 (obj.file_*),Selección de archivo (obj.file_*),اختيار الملف (obj.file_*),Pilihan file (obj.file_*)
FileVideo,,動画ファイル,Video File,视频文件,影片檔案,동영상 파일,Archivo de video,ملف فيديو,File Video
FileAudio,,音声ファイル,Audio File,音频文件,音訊檔案,음성 파일,Archivo de audio,ملف صوتي,File Audio
FileImage,,画像ファイル,Image File,图像文件,圖片檔案,이미지 파일,Archivo de imagen,ملف صورة,File Gambar
FileProject,,プロジェクトファイル,Project File,项目文件,專案檔案,프로젝트 파일,Archivo de proyecto,ملف المشروع,File Proyek
FileMp4,,MP4ファイル,MP4 File,MP4文件,MP4檔案,MP4 파일,Archivo MP4,ملف MP4,File MP4
FileExo,,EXOファイル,EXO File,EXO文件,EXO檔案,EXO 파일,Archivo EXO,ملف EXO,File EXO
FileSubtitle,,字幕ファイル,Subtitle File,字幕文件,字幕檔案,자막 파일,Archivo de subtítulos,ملف الترجمة,File Subtitle
FileShader,,シェーダーファイル,Shader File,着色器文件,著色器檔案,셰이더 파일,Archivo de sombreador,ملف التظليل,File Shader
ToolBarImport,,インポート,Import,导入,導入,가져오기,Importar,استيراد,Impor ToolBarImport,,インポート,Import,导入,導入,가져오기,Importar,استيراد,Impor
ToolBarExport,,エクスポート,Export,导出,導出,내보내기,Exportar,تصدير,Ekspor ToolBarExport,,エクスポート,Export,导出,導出,내보내기,Exportar,تصدير,Ekspor
ToolBarClear,,クリア,Clear,清除,清除,지우기,Limpiar,مسح,Hapus ToolBarClear,,クリア,Clear,清除,清除,지우기,Limpiar,مسح,Hapus
@@ -17,3 +44,6 @@ ToolBarClearTitle,,確認,Confirm,确认,確認,확인,Confirmar,تأكيد,Konf
ToolBarImportErrorTitle,,インポートエラー,Import Error,导入错误,導入錯誤,가져오기 오류,Error de importación,خطأ في الاستيراد,Kesalahan impor ToolBarImportErrorTitle,,インポートエラー,Import Error,导入错误,導入錯誤,가져오기 오류,Error de importación,خطأ في الاستيراد,Kesalahan impor
ToolBarExportErrorTitle,,エクスポートエラー,Export Error,导出错误,導出錯誤,내보내기 오류,Error de exportación,خطأ في التصدير,Kesalahan ekspor ToolBarExportErrorTitle,,エクスポートエラー,Export Error,导出错误,導出錯誤,내보내기 오류,Error de exportación,خطأ في التصدير,Kesalahan ekspor
LuaFileFilter,,Luaスクリプト (*.lua)|*.lua|すべてのファイル (*.*)|*.*,Lua Script (*.lua)|*.lua|All Files (*.*)|*.*,Lua脚本 (*.lua)|*.lua|所有文件 (*.*)|*.*,Lua腳本 (*.lua)|*.lua|所有檔案 (*.*)|*.*,Lua 스크립트 (*.lua)|*.lua|모든 파일 (*.*)|*.*,Script Lua (*.lua)|*.lua|Todos los archivos (*.*)|*.*,نص Lua (*.lua)|*.lua|جميع الملفات (*.*)|*.*,Skrip Lua (*.lua)|*.lua|Semua File (*.*)|*.* LuaFileFilter,,Luaスクリプト (*.lua)|*.lua|すべてのファイル (*.*)|*.*,Lua Script (*.lua)|*.lua|All Files (*.*)|*.*,Lua脚本 (*.lua)|*.lua|所有文件 (*.*)|*.*,Lua腳本 (*.lua)|*.lua|所有檔案 (*.*)|*.*,Lua 스크립트 (*.lua)|*.lua|모든 파일 (*.*)|*.*,Script Lua (*.lua)|*.lua|Todos los archivos (*.*)|*.*,نص Lua (*.lua)|*.lua|جميع الملفات (*.*)|*.*,Skrip Lua (*.lua)|*.lua|Semua File (*.*)|*.*
DiagnosticCompile,,構文エラー,Syntax error,语法错误,語法錯誤,구문 오류,Error de sintaxis,خطأ في بناء الجملة,Kesalahan sintaksis
DiagnosticRuntime,,実行時エラー,Runtime error,运行时错误,執行時錯誤,런타임 오류,Error de ejecución,خطأ وقت التشغيل,Kesalahan runtime
DiagnosticTimeout,,タイムアウト,Timed out,执行超时,執行逾時,시간 초과,Tiempo de espera agotado,انتهت المهلة,Waktu habis
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 Slider0 スライダー0 Slider 0 滑块0 滑塊0 슬라이더0 Deslizador 0 منزلق 0 Slider 0
13 Slider1 スライダー1 Slider 1 滑块1 滑塊1 슬라이더1 Deslizador 1 منزلق 1 Slider 1
14 Slider2 スライダー2 Slider 2 滑块2 滑塊2 슬라이더2 Deslizador 2 منزلق 2 Slider 2
15 Slider3 スライダー3 Slider 3 滑块3 滑塊3 슬라이더3 Deslizador 3 منزلق 3 Slider 3
16 SliderDesc 数値スライダー (obj.slider0〜3 で参照) Numeric slider (obj.slider0–3) 数值滑块 (obj.slider0~3) 數值滑塊 (obj.slider0~3) 숫자 슬라이더 (obj.slider0~3) Deslizador numérico (obj.slider0-3) منزلق رقمي (obj.slider0-3) Slider numerik (obj.slider0-3)
17 Check0 チェック0 Check 0 复选框0 核取方塊0 체크0 Casilla 0 خانة 0 Centang 0
18 Check1 チェック1 Check 1 复选框1 核取方塊1 체크1 Casilla 1 خانة 1 Centang 1
19 Check2 チェック2 Check 2 复选框2 核取方塊2 체크2 Casilla 2 خانة 2 Centang 2
20 Check3 チェック3 Check 3 复选框3 核取方塊3 체크3 Casilla 3 خانة 3 Centang 3
21 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)
22 Color 色 Color 颜色 顏色 색 Color اللون Warna
23 ColorDesc 色 (AviUtl準拠 --color に対応) Color (AviUtl compatible: --color) 颜色(AviUtl兼容: --color) 顏色(AviUtl兼容: --color) 색 (AviUtl 호환: --color) Color (compatible AviUtl: --color) اللون (متوافق مع AviUtl: --color) Warna (kompatibel AviUtl: --color)
24 Text テキスト Text 文本 文字 텍스트 Texto نص Teks
25 TextDesc テキスト入力 (obj.text で参照) Text input (obj.text) 文本输入 (obj.text) 文字輸入 (obj.text) 텍스트 입력 (obj.text) Entrada de texto (obj.text) إدخال نص (obj.text) Masukan teks (obj.text)
26 Font フォント Font 字体 字型 글꼴 Fuente خط Font
27 FontDesc フォント選択 (obj.font で参照) Font selection (obj.font) 字体选择 (obj.font) 字型選擇 (obj.font) 글꼴 선택 (obj.font) Selección de fuente (obj.font) اختيار الخط (obj.font) Pilihan font (obj.font)
28 Directory フォルダ Folder 文件夹 資料夾 폴더 Carpeta مجلد Folder
29 DirectoryDesc フォルダ選択 (obj.dir で参照) Folder selection (obj.dir) 文件夹选择 (obj.dir) 資料夾選擇 (obj.dir) 폴더 선택 (obj.dir) Selección de carpeta (obj.dir) اختيار المجلد (obj.dir) Pilihan folder (obj.dir)
30 FileDesc ファイル選択 (obj.file_* で参照) File selection (obj.file_*) 文件选择 (obj.file_*) 檔案選擇 (obj.file_*) 파일 선택 (obj.file_*) Selección de archivo (obj.file_*) اختيار الملف (obj.file_*) Pilihan file (obj.file_*)
31 FileVideo 動画ファイル Video File 视频文件 影片檔案 동영상 파일 Archivo de video ملف فيديو File Video
32 FileAudio 音声ファイル Audio File 音频文件 音訊檔案 음성 파일 Archivo de audio ملف صوتي File Audio
33 FileImage 画像ファイル Image File 图像文件 圖片檔案 이미지 파일 Archivo de imagen ملف صورة File Gambar
34 FileProject プロジェクトファイル Project File 项目文件 專案檔案 프로젝트 파일 Archivo de proyecto ملف المشروع File Proyek
35 FileMp4 MP4ファイル MP4 File MP4文件 MP4檔案 MP4 파일 Archivo MP4 ملف MP4 File MP4
36 FileExo EXOファイル EXO File EXO文件 EXO檔案 EXO 파일 Archivo EXO ملف EXO File EXO
37 FileSubtitle 字幕ファイル Subtitle File 字幕文件 字幕檔案 자막 파일 Archivo de subtítulos ملف الترجمة File Subtitle
38 FileShader シェーダーファイル Shader File 着色器文件 著色器檔案 셰이더 파일 Archivo de sombreador ملف التظليل File Shader
39 ToolBarImport インポート Import 导入 導入 가져오기 Importar استيراد Impor
40 ToolBarExport エクスポート Export 导出 導出 내보내기 Exportar تصدير Ekspor
41 ToolBarClear クリア Clear 清除 清除 지우기 Limpiar مسح Hapus
44 ToolBarImportErrorTitle インポートエラー Import Error 导入错误 導入錯誤 가져오기 오류 Error de importación خطأ في الاستيراد Kesalahan impor
45 ToolBarExportErrorTitle エクスポートエラー Export Error 导出错误 導出錯誤 내보내기 오류 Error de exportación خطأ في التصدير Kesalahan ekspor
46 LuaFileFilter Luaスクリプト (*.lua)|*.lua|すべてのファイル (*.*)|*.* Lua Script (*.lua)|*.lua|All Files (*.*)|*.* Lua脚本 (*.lua)|*.lua|所有文件 (*.*)|*.* Lua腳本 (*.lua)|*.lua|所有檔案 (*.*)|*.* Lua 스크립트 (*.lua)|*.lua|모든 파일 (*.*)|*.* Script Lua (*.lua)|*.lua|Todos los archivos (*.*)|*.* نص Lua (*.lua)|*.lua|جميع الملفات (*.*)|*.* Skrip Lua (*.lua)|*.lua|Semua File (*.*)|*.*
47 DiagnosticCompile 構文エラー Syntax error 语法错误 語法錯誤 구문 오류 Error de sintaxis خطأ في بناء الجملة Kesalahan sintaksis
48 DiagnosticRuntime 実行時エラー Runtime error 运行时错误 執行時錯誤 런타임 오류 Error de ejecución خطأ وقت التشغيل Kesalahan runtime
49 DiagnosticTimeout タイムアウト Timed out 执行超时 執行逾時 시간 초과 Tiempo de espera agotado انتهت المهلة Waktu habis
+30
ファイルの表示
@@ -69,6 +69,33 @@
<data name="Track2" xml:space="preserve"><value>Track 2</value></data> <data name="Track2" xml:space="preserve"><value>Track 2</value></data>
<data name="Track3" xml:space="preserve"><value>Track 3</value></data> <data name="Track3" xml:space="preserve"><value>Track 3</value></data>
<data name="TrackDesc" xml:space="preserve"><value>Slider value (AviUtl compatible: track0–3)</value></data> <data name="TrackDesc" xml:space="preserve"><value>Slider value (AviUtl compatible: track0–3)</value></data>
<data name="Slider0" xml:space="preserve"><value>Slider 0</value></data>
<data name="Slider1" xml:space="preserve"><value>Slider 1</value></data>
<data name="Slider2" xml:space="preserve"><value>Slider 2</value></data>
<data name="Slider3" xml:space="preserve"><value>Slider 3</value></data>
<data name="SliderDesc" xml:space="preserve"><value>Numeric slider (obj.slider0–3)</value></data>
<data name="Check0" xml:space="preserve"><value>Check 0</value></data>
<data name="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="Text" xml:space="preserve"><value>Text</value></data>
<data name="TextDesc" xml:space="preserve"><value>Text input (obj.text)</value></data>
<data name="Font" xml:space="preserve"><value>Font</value></data>
<data name="FontDesc" xml:space="preserve"><value>Font selection (obj.font)</value></data>
<data name="Directory" xml:space="preserve"><value>Folder</value></data>
<data name="DirectoryDesc" xml:space="preserve"><value>Folder selection (obj.dir)</value></data>
<data name="FileDesc" xml:space="preserve"><value>File selection (obj.file_*)</value></data>
<data name="FileVideo" xml:space="preserve"><value>Video File</value></data>
<data name="FileAudio" xml:space="preserve"><value>Audio File</value></data>
<data name="FileImage" xml:space="preserve"><value>Image File</value></data>
<data name="FileProject" xml:space="preserve"><value>Project File</value></data>
<data name="FileMp4" xml:space="preserve"><value>MP4 File</value></data>
<data name="FileExo" xml:space="preserve"><value>EXO File</value></data>
<data name="FileSubtitle" xml:space="preserve"><value>Subtitle File</value></data>
<data name="FileShader" xml:space="preserve"><value>Shader File</value></data>
<data name="ToolBarImport" xml:space="preserve"><value>Import</value></data> <data name="ToolBarImport" xml:space="preserve"><value>Import</value></data>
<data name="ToolBarExport" xml:space="preserve"><value>Export</value></data> <data name="ToolBarExport" xml:space="preserve"><value>Export</value></data>
<data name="ToolBarClear" xml:space="preserve"><value>Clear</value></data> <data name="ToolBarClear" xml:space="preserve"><value>Clear</value></data>
@@ -77,4 +104,7 @@
<data name="ToolBarImportErrorTitle" xml:space="preserve"><value>Import Error</value></data> <data name="ToolBarImportErrorTitle" xml:space="preserve"><value>Import Error</value></data>
<data name="ToolBarExportErrorTitle" xml:space="preserve"><value>Export Error</value></data> <data name="ToolBarExportErrorTitle" xml:space="preserve"><value>Export Error</value></data>
<data name="LuaFileFilter" xml:space="preserve"><value>Lua Script (*.lua)|*.lua|All Files (*.*)|*.*</value></data> <data name="LuaFileFilter" xml:space="preserve"><value>Lua Script (*.lua)|*.lua|All Files (*.*)|*.*</value></data>
<data name="DiagnosticCompile" xml:space="preserve"><value>Syntax error</value></data>
<data name="DiagnosticRuntime" xml:space="preserve"><value>Runtime error</value></data>
<data name="DiagnosticTimeout" xml:space="preserve"><value>Timed out</value></data>
</root> </root>
+30
ファイルの表示
@@ -69,6 +69,33 @@
<data name="Track2" xml:space="preserve"><value>Pista 2</value></data> <data name="Track2" xml:space="preserve"><value>Pista 2</value></data>
<data name="Track3" xml:space="preserve"><value>Pista 3</value></data> <data name="Track3" xml:space="preserve"><value>Pista 3</value></data>
<data name="TrackDesc" xml:space="preserve"><value>Valor del deslizador (compatible AviUtl: track0-3)</value></data> <data name="TrackDesc" xml:space="preserve"><value>Valor del deslizador (compatible AviUtl: track0-3)</value></data>
<data name="Slider0" xml:space="preserve"><value>Deslizador 0</value></data>
<data name="Slider1" xml:space="preserve"><value>Deslizador 1</value></data>
<data name="Slider2" xml:space="preserve"><value>Deslizador 2</value></data>
<data name="Slider3" xml:space="preserve"><value>Deslizador 3</value></data>
<data name="SliderDesc" xml:space="preserve"><value>Deslizador numérico (obj.slider0-3)</value></data>
<data name="Check0" xml:space="preserve"><value>Casilla 0</value></data>
<data name="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="Text" xml:space="preserve"><value>Texto</value></data>
<data name="TextDesc" xml:space="preserve"><value>Entrada de texto (obj.text)</value></data>
<data name="Font" xml:space="preserve"><value>Fuente</value></data>
<data name="FontDesc" xml:space="preserve"><value>Selección de fuente (obj.font)</value></data>
<data name="Directory" xml:space="preserve"><value>Carpeta</value></data>
<data name="DirectoryDesc" xml:space="preserve"><value>Selección de carpeta (obj.dir)</value></data>
<data name="FileDesc" xml:space="preserve"><value>Selección de archivo (obj.file_*)</value></data>
<data name="FileVideo" xml:space="preserve"><value>Archivo de video</value></data>
<data name="FileAudio" xml:space="preserve"><value>Archivo de audio</value></data>
<data name="FileImage" xml:space="preserve"><value>Archivo de imagen</value></data>
<data name="FileProject" xml:space="preserve"><value>Archivo de proyecto</value></data>
<data name="FileMp4" xml:space="preserve"><value>Archivo MP4</value></data>
<data name="FileExo" xml:space="preserve"><value>Archivo EXO</value></data>
<data name="FileSubtitle" xml:space="preserve"><value>Archivo de subtítulos</value></data>
<data name="FileShader" xml:space="preserve"><value>Archivo de sombreador</value></data>
<data name="ToolBarImport" xml:space="preserve"><value>Importar</value></data> <data name="ToolBarImport" xml:space="preserve"><value>Importar</value></data>
<data name="ToolBarExport" xml:space="preserve"><value>Exportar</value></data> <data name="ToolBarExport" xml:space="preserve"><value>Exportar</value></data>
<data name="ToolBarClear" xml:space="preserve"><value>Limpiar</value></data> <data name="ToolBarClear" xml:space="preserve"><value>Limpiar</value></data>
@@ -77,4 +104,7 @@
<data name="ToolBarImportErrorTitle" xml:space="preserve"><value>Error de importación</value></data> <data name="ToolBarImportErrorTitle" xml:space="preserve"><value>Error de importación</value></data>
<data name="ToolBarExportErrorTitle" xml:space="preserve"><value>Error de exportación</value></data> <data name="ToolBarExportErrorTitle" xml:space="preserve"><value>Error de exportación</value></data>
<data name="LuaFileFilter" xml:space="preserve"><value>Script Lua (*.lua)|*.lua|Todos los archivos (*.*)|*.*</value></data> <data name="LuaFileFilter" xml:space="preserve"><value>Script Lua (*.lua)|*.lua|Todos los archivos (*.*)|*.*</value></data>
<data name="DiagnosticCompile" xml:space="preserve"><value>Error de sintaxis</value></data>
<data name="DiagnosticRuntime" xml:space="preserve"><value>Error de ejecución</value></data>
<data name="DiagnosticTimeout" xml:space="preserve"><value>Tiempo de espera agotado</value></data>
</root> </root>
+30
ファイルの表示
@@ -69,6 +69,33 @@
<data name="Track2" xml:space="preserve"><value>Jalur 2</value></data> <data name="Track2" xml:space="preserve"><value>Jalur 2</value></data>
<data name="Track3" xml:space="preserve"><value>Jalur 3</value></data> <data name="Track3" xml:space="preserve"><value>Jalur 3</value></data>
<data name="TrackDesc" xml:space="preserve"><value>Nilai slider (kompatibel AviUtl: track0-3)</value></data> <data name="TrackDesc" xml:space="preserve"><value>Nilai slider (kompatibel AviUtl: track0-3)</value></data>
<data name="Slider0" xml:space="preserve"><value>Slider 0</value></data>
<data name="Slider1" xml:space="preserve"><value>Slider 1</value></data>
<data name="Slider2" xml:space="preserve"><value>Slider 2</value></data>
<data name="Slider3" xml:space="preserve"><value>Slider 3</value></data>
<data name="SliderDesc" xml:space="preserve"><value>Slider numerik (obj.slider0-3)</value></data>
<data name="Check0" xml:space="preserve"><value>Centang 0</value></data>
<data name="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="Text" xml:space="preserve"><value>Teks</value></data>
<data name="TextDesc" xml:space="preserve"><value>Masukan teks (obj.text)</value></data>
<data name="Font" xml:space="preserve"><value>Font</value></data>
<data name="FontDesc" xml:space="preserve"><value>Pilihan font (obj.font)</value></data>
<data name="Directory" xml:space="preserve"><value>Folder</value></data>
<data name="DirectoryDesc" xml:space="preserve"><value>Pilihan folder (obj.dir)</value></data>
<data name="FileDesc" xml:space="preserve"><value>Pilihan file (obj.file_*)</value></data>
<data name="FileVideo" xml:space="preserve"><value>File Video</value></data>
<data name="FileAudio" xml:space="preserve"><value>File Audio</value></data>
<data name="FileImage" xml:space="preserve"><value>File Gambar</value></data>
<data name="FileProject" xml:space="preserve"><value>File Proyek</value></data>
<data name="FileMp4" xml:space="preserve"><value>File MP4</value></data>
<data name="FileExo" xml:space="preserve"><value>File EXO</value></data>
<data name="FileSubtitle" xml:space="preserve"><value>File Subtitle</value></data>
<data name="FileShader" xml:space="preserve"><value>File Shader</value></data>
<data name="ToolBarImport" xml:space="preserve"><value>Impor</value></data> <data name="ToolBarImport" xml:space="preserve"><value>Impor</value></data>
<data name="ToolBarExport" xml:space="preserve"><value>Ekspor</value></data> <data name="ToolBarExport" xml:space="preserve"><value>Ekspor</value></data>
<data name="ToolBarClear" xml:space="preserve"><value>Hapus</value></data> <data name="ToolBarClear" xml:space="preserve"><value>Hapus</value></data>
@@ -77,4 +104,7 @@
<data name="ToolBarImportErrorTitle" xml:space="preserve"><value>Kesalahan impor</value></data> <data name="ToolBarImportErrorTitle" xml:space="preserve"><value>Kesalahan impor</value></data>
<data name="ToolBarExportErrorTitle" xml:space="preserve"><value>Kesalahan ekspor</value></data> <data name="ToolBarExportErrorTitle" xml:space="preserve"><value>Kesalahan ekspor</value></data>
<data name="LuaFileFilter" xml:space="preserve"><value>Skrip Lua (*.lua)|*.lua|Semua File (*.*)|*.*</value></data> <data name="LuaFileFilter" xml:space="preserve"><value>Skrip Lua (*.lua)|*.lua|Semua File (*.*)|*.*</value></data>
<data name="DiagnosticCompile" xml:space="preserve"><value>Kesalahan sintaksis</value></data>
<data name="DiagnosticRuntime" xml:space="preserve"><value>Kesalahan runtime</value></data>
<data name="DiagnosticTimeout" xml:space="preserve"><value>Waktu habis</value></data>
</root> </root>
+30
ファイルの表示
@@ -69,6 +69,33 @@
<data name="Track2" xml:space="preserve"><value>트랙2</value></data> <data name="Track2" xml:space="preserve"><value>트랙2</value></data>
<data name="Track3" xml:space="preserve"><value>트랙3</value></data> <data name="Track3" xml:space="preserve"><value>트랙3</value></data>
<data name="TrackDesc" xml:space="preserve"><value>슬라이더 값 (AviUtl 호환: track0~3)</value></data> <data name="TrackDesc" xml:space="preserve"><value>슬라이더 값 (AviUtl 호환: track0~3)</value></data>
<data name="Slider0" xml:space="preserve"><value>슬라이더0</value></data>
<data name="Slider1" xml:space="preserve"><value>슬라이더1</value></data>
<data name="Slider2" xml:space="preserve"><value>슬라이더2</value></data>
<data name="Slider3" xml:space="preserve"><value>슬라이더3</value></data>
<data name="SliderDesc" xml:space="preserve"><value>숫자 슬라이더 (obj.slider0~3)</value></data>
<data name="Check0" xml:space="preserve"><value>체크0</value></data>
<data name="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="Text" xml:space="preserve"><value>텍스트</value></data>
<data name="TextDesc" xml:space="preserve"><value>텍스트 입력 (obj.text)</value></data>
<data name="Font" xml:space="preserve"><value>글꼴</value></data>
<data name="FontDesc" xml:space="preserve"><value>글꼴 선택 (obj.font)</value></data>
<data name="Directory" xml:space="preserve"><value>폴더</value></data>
<data name="DirectoryDesc" xml:space="preserve"><value>폴더 선택 (obj.dir)</value></data>
<data name="FileDesc" xml:space="preserve"><value>파일 선택 (obj.file_*)</value></data>
<data name="FileVideo" xml:space="preserve"><value>동영상 파일</value></data>
<data name="FileAudio" xml:space="preserve"><value>음성 파일</value></data>
<data name="FileImage" xml:space="preserve"><value>이미지 파일</value></data>
<data name="FileProject" xml:space="preserve"><value>프로젝트 파일</value></data>
<data name="FileMp4" xml:space="preserve"><value>MP4 파일</value></data>
<data name="FileExo" xml:space="preserve"><value>EXO 파일</value></data>
<data name="FileSubtitle" xml:space="preserve"><value>자막 파일</value></data>
<data name="FileShader" xml:space="preserve"><value>셰이더 파일</value></data>
<data name="ToolBarImport" xml:space="preserve"><value>가져오기</value></data> <data name="ToolBarImport" xml:space="preserve"><value>가져오기</value></data>
<data name="ToolBarExport" xml:space="preserve"><value>내보내기</value></data> <data name="ToolBarExport" xml:space="preserve"><value>내보내기</value></data>
<data name="ToolBarClear" xml:space="preserve"><value>지우기</value></data> <data name="ToolBarClear" xml:space="preserve"><value>지우기</value></data>
@@ -77,4 +104,7 @@
<data name="ToolBarImportErrorTitle" xml:space="preserve"><value>가져오기 오류</value></data> <data name="ToolBarImportErrorTitle" xml:space="preserve"><value>가져오기 오류</value></data>
<data name="ToolBarExportErrorTitle" xml:space="preserve"><value>내보내기 오류</value></data> <data name="ToolBarExportErrorTitle" xml:space="preserve"><value>내보내기 오류</value></data>
<data name="LuaFileFilter" xml:space="preserve"><value>Lua 스크립트 (*.lua)|*.lua|모든 파일 (*.*)|*.*</value></data> <data name="LuaFileFilter" xml:space="preserve"><value>Lua 스크립트 (*.lua)|*.lua|모든 파일 (*.*)|*.*</value></data>
<data name="DiagnosticCompile" xml:space="preserve"><value>구문 오류</value></data>
<data name="DiagnosticRuntime" xml:space="preserve"><value>런타임 오류</value></data>
<data name="DiagnosticTimeout" xml:space="preserve"><value>시간 초과</value></data>
</root> </root>
+30
ファイルの表示
@@ -69,6 +69,33 @@
<data name="Track2" xml:space="preserve"><value>トラック2</value></data> <data name="Track2" xml:space="preserve"><value>トラック2</value></data>
<data name="Track3" xml:space="preserve"><value>トラック3</value></data> <data name="Track3" xml:space="preserve"><value>トラック3</value></data>
<data name="TrackDesc" xml:space="preserve"><value>スライダー値 (AviUtl準拠 track0〜3 に対応)</value></data> <data name="TrackDesc" xml:space="preserve"><value>スライダー値 (AviUtl準拠 track0〜3 に対応)</value></data>
<data name="Slider0" xml:space="preserve"><value>スライダー0</value></data>
<data name="Slider1" xml:space="preserve"><value>スライダー1</value></data>
<data name="Slider2" xml:space="preserve"><value>スライダー2</value></data>
<data name="Slider3" xml:space="preserve"><value>スライダー3</value></data>
<data name="SliderDesc" xml:space="preserve"><value>数値スライダー (obj.slider0〜3 で参照)</value></data>
<data name="Check0" xml:space="preserve"><value>チェック0</value></data>
<data name="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="Text" xml:space="preserve"><value>テキスト</value></data>
<data name="TextDesc" xml:space="preserve"><value>テキスト入力 (obj.text で参照)</value></data>
<data name="Font" xml:space="preserve"><value>フォント</value></data>
<data name="FontDesc" xml:space="preserve"><value>フォント選択 (obj.font で参照)</value></data>
<data name="Directory" xml:space="preserve"><value>フォルダ</value></data>
<data name="DirectoryDesc" xml:space="preserve"><value>フォルダ選択 (obj.dir で参照)</value></data>
<data name="FileDesc" xml:space="preserve"><value>ファイル選択 (obj.file_* で参照)</value></data>
<data name="FileVideo" xml:space="preserve"><value>動画ファイル</value></data>
<data name="FileAudio" xml:space="preserve"><value>音声ファイル</value></data>
<data name="FileImage" xml:space="preserve"><value>画像ファイル</value></data>
<data name="FileProject" xml:space="preserve"><value>プロジェクトファイル</value></data>
<data name="FileMp4" xml:space="preserve"><value>MP4ファイル</value></data>
<data name="FileExo" xml:space="preserve"><value>EXOファイル</value></data>
<data name="FileSubtitle" xml:space="preserve"><value>字幕ファイル</value></data>
<data name="FileShader" xml:space="preserve"><value>シェーダーファイル</value></data>
<data name="ToolBarImport" xml:space="preserve"><value>インポート</value></data> <data name="ToolBarImport" xml:space="preserve"><value>インポート</value></data>
<data name="ToolBarExport" xml:space="preserve"><value>エクスポート</value></data> <data name="ToolBarExport" xml:space="preserve"><value>エクスポート</value></data>
<data name="ToolBarClear" xml:space="preserve"><value>クリア</value></data> <data name="ToolBarClear" xml:space="preserve"><value>クリア</value></data>
@@ -77,4 +104,7 @@
<data name="ToolBarImportErrorTitle" xml:space="preserve"><value>インポートエラー</value></data> <data name="ToolBarImportErrorTitle" xml:space="preserve"><value>インポートエラー</value></data>
<data name="ToolBarExportErrorTitle" xml:space="preserve"><value>エクスポートエラー</value></data> <data name="ToolBarExportErrorTitle" xml:space="preserve"><value>エクスポートエラー</value></data>
<data name="LuaFileFilter" xml:space="preserve"><value>Luaスクリプト (*.lua)|*.lua|すべてのファイル (*.*)|*.*</value></data> <data name="LuaFileFilter" xml:space="preserve"><value>Luaスクリプト (*.lua)|*.lua|すべてのファイル (*.*)|*.*</value></data>
<data name="DiagnosticCompile" xml:space="preserve"><value>構文エラー</value></data>
<data name="DiagnosticRuntime" xml:space="preserve"><value>実行時エラー</value></data>
<data name="DiagnosticTimeout" xml:space="preserve"><value>タイムアウト</value></data>
</root> </root>
+30
ファイルの表示
@@ -69,6 +69,33 @@
<data name="Track2" xml:space="preserve"><value>轨道2</value></data> <data name="Track2" xml:space="preserve"><value>轨道2</value></data>
<data name="Track3" xml:space="preserve"><value>轨道3</value></data> <data name="Track3" xml:space="preserve"><value>轨道3</value></data>
<data name="TrackDesc" xml:space="preserve"><value>滑块值(AviUtl兼容: track0~3)</value></data> <data name="TrackDesc" xml:space="preserve"><value>滑块值(AviUtl兼容: track0~3)</value></data>
<data name="Slider0" xml:space="preserve"><value>滑块0</value></data>
<data name="Slider1" xml:space="preserve"><value>滑块1</value></data>
<data name="Slider2" xml:space="preserve"><value>滑块2</value></data>
<data name="Slider3" xml:space="preserve"><value>滑块3</value></data>
<data name="SliderDesc" xml:space="preserve"><value>数值滑块 (obj.slider0~3)</value></data>
<data name="Check0" xml:space="preserve"><value>复选框0</value></data>
<data name="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="Text" xml:space="preserve"><value>文本</value></data>
<data name="TextDesc" xml:space="preserve"><value>文本输入 (obj.text)</value></data>
<data name="Font" xml:space="preserve"><value>字体</value></data>
<data name="FontDesc" xml:space="preserve"><value>字体选择 (obj.font)</value></data>
<data name="Directory" xml:space="preserve"><value>文件夹</value></data>
<data name="DirectoryDesc" xml:space="preserve"><value>文件夹选择 (obj.dir)</value></data>
<data name="FileDesc" xml:space="preserve"><value>文件选择 (obj.file_*)</value></data>
<data name="FileVideo" xml:space="preserve"><value>视频文件</value></data>
<data name="FileAudio" xml:space="preserve"><value>音频文件</value></data>
<data name="FileImage" xml:space="preserve"><value>图像文件</value></data>
<data name="FileProject" xml:space="preserve"><value>项目文件</value></data>
<data name="FileMp4" xml:space="preserve"><value>MP4文件</value></data>
<data name="FileExo" xml:space="preserve"><value>EXO文件</value></data>
<data name="FileSubtitle" xml:space="preserve"><value>字幕文件</value></data>
<data name="FileShader" xml:space="preserve"><value>着色器文件</value></data>
<data name="ToolBarImport" xml:space="preserve"><value>导入</value></data> <data name="ToolBarImport" xml:space="preserve"><value>导入</value></data>
<data name="ToolBarExport" xml:space="preserve"><value>导出</value></data> <data name="ToolBarExport" xml:space="preserve"><value>导出</value></data>
<data name="ToolBarClear" xml:space="preserve"><value>清除</value></data> <data name="ToolBarClear" xml:space="preserve"><value>清除</value></data>
@@ -77,4 +104,7 @@
<data name="ToolBarImportErrorTitle" xml:space="preserve"><value>导入错误</value></data> <data name="ToolBarImportErrorTitle" xml:space="preserve"><value>导入错误</value></data>
<data name="ToolBarExportErrorTitle" xml:space="preserve"><value>导出错误</value></data> <data name="ToolBarExportErrorTitle" xml:space="preserve"><value>导出错误</value></data>
<data name="LuaFileFilter" xml:space="preserve"><value>Lua脚本 (*.lua)|*.lua|所有文件 (*.*)|*.*</value></data> <data name="LuaFileFilter" xml:space="preserve"><value>Lua脚本 (*.lua)|*.lua|所有文件 (*.*)|*.*</value></data>
<data name="DiagnosticCompile" xml:space="preserve"><value>语法错误</value></data>
<data name="DiagnosticRuntime" xml:space="preserve"><value>运行时错误</value></data>
<data name="DiagnosticTimeout" xml:space="preserve"><value>执行超时</value></data>
</root> </root>
+30
ファイルの表示
@@ -69,6 +69,33 @@
<data name="Track2" xml:space="preserve"><value>軌道2</value></data> <data name="Track2" xml:space="preserve"><value>軌道2</value></data>
<data name="Track3" xml:space="preserve"><value>軌道3</value></data> <data name="Track3" xml:space="preserve"><value>軌道3</value></data>
<data name="TrackDesc" xml:space="preserve"><value>滑塊值(AviUtl兼容: track0~3)</value></data> <data name="TrackDesc" xml:space="preserve"><value>滑塊值(AviUtl兼容: track0~3)</value></data>
<data name="Slider0" xml:space="preserve"><value>滑塊0</value></data>
<data name="Slider1" xml:space="preserve"><value>滑塊1</value></data>
<data name="Slider2" xml:space="preserve"><value>滑塊2</value></data>
<data name="Slider3" xml:space="preserve"><value>滑塊3</value></data>
<data name="SliderDesc" xml:space="preserve"><value>數值滑塊 (obj.slider0~3)</value></data>
<data name="Check0" xml:space="preserve"><value>核取方塊0</value></data>
<data name="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="Text" xml:space="preserve"><value>文字</value></data>
<data name="TextDesc" xml:space="preserve"><value>文字輸入 (obj.text)</value></data>
<data name="Font" xml:space="preserve"><value>字型</value></data>
<data name="FontDesc" xml:space="preserve"><value>字型選擇 (obj.font)</value></data>
<data name="Directory" xml:space="preserve"><value>資料夾</value></data>
<data name="DirectoryDesc" xml:space="preserve"><value>資料夾選擇 (obj.dir)</value></data>
<data name="FileDesc" xml:space="preserve"><value>檔案選擇 (obj.file_*)</value></data>
<data name="FileVideo" xml:space="preserve"><value>影片檔案</value></data>
<data name="FileAudio" xml:space="preserve"><value>音訊檔案</value></data>
<data name="FileImage" xml:space="preserve"><value>圖片檔案</value></data>
<data name="FileProject" xml:space="preserve"><value>專案檔案</value></data>
<data name="FileMp4" xml:space="preserve"><value>MP4檔案</value></data>
<data name="FileExo" xml:space="preserve"><value>EXO檔案</value></data>
<data name="FileSubtitle" xml:space="preserve"><value>字幕檔案</value></data>
<data name="FileShader" xml:space="preserve"><value>著色器檔案</value></data>
<data name="ToolBarImport" xml:space="preserve"><value>導入</value></data> <data name="ToolBarImport" xml:space="preserve"><value>導入</value></data>
<data name="ToolBarExport" xml:space="preserve"><value>導出</value></data> <data name="ToolBarExport" xml:space="preserve"><value>導出</value></data>
<data name="ToolBarClear" xml:space="preserve"><value>清除</value></data> <data name="ToolBarClear" xml:space="preserve"><value>清除</value></data>
@@ -77,4 +104,7 @@
<data name="ToolBarImportErrorTitle" xml:space="preserve"><value>導入錯誤</value></data> <data name="ToolBarImportErrorTitle" xml:space="preserve"><value>導入錯誤</value></data>
<data name="ToolBarExportErrorTitle" xml:space="preserve"><value>導出錯誤</value></data> <data name="ToolBarExportErrorTitle" xml:space="preserve"><value>導出錯誤</value></data>
<data name="LuaFileFilter" xml:space="preserve"><value>Lua腳本 (*.lua)|*.lua|所有檔案 (*.*)|*.*</value></data> <data name="LuaFileFilter" xml:space="preserve"><value>Lua腳本 (*.lua)|*.lua|所有檔案 (*.*)|*.*</value></data>
<data name="DiagnosticCompile" xml:space="preserve"><value>語法錯誤</value></data>
<data name="DiagnosticRuntime" xml:space="preserve"><value>執行時錯誤</value></data>
<data name="DiagnosticTimeout" xml:space="preserve"><value>執行逾時</value></data>
</root> </root>
+339
ファイルの表示
@@ -0,0 +1,339 @@
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Globalization;
using System.Reflection;
using System.Windows.Media;
using Vortice.Direct2D1;
using YukkuriMovieMaker.Commons;
using YukkuriMovieMaker.Player.Video;
using YukkuriMovieMaker.Plugin;
using YukkuriMovieMaker.Plugin.Effects;
using LuaScript.Compat;
namespace LuaScript
{
internal sealed class VideoEffectChain : IDisposable
{
private sealed class Node
{
public required IVideoEffect Model;
public required IVideoEffectProcessor Processor;
public required AviUtlEffectMapping? Mapping;
public required int RequestIndex;
}
private static readonly AviUtlParameterMapping Identity = new(string.Empty, string.Empty, 1d, 0d);
private static Dictionary<string, Type>? _typeRegistry;
private static Dictionary<string, Type>? _nameRegistry;
private static readonly Dictionary<Type, Dictionary<string, PropertyInfo>> _propertyCache = [];
private readonly IGraphicsDevicesAndContext _devices;
private readonly List<Node> _nodes = [];
private string[] _signature = [];
private AviUtlEngine _signatureTarget = AviUtlEngine.Both;
public VideoEffectChain(IGraphicsDevicesAndContext devices)
{
_devices = devices;
}
public ID2D1Image Apply(ID2D1Image source, IReadOnlyList<AviUtlEffectRequest> requests, EffectDescription baseDesc, AviUtlEngine target, ref DrawDescription drawDescription)
{
try
{
SyncNodes(requests, target);
}
catch
{
return source;
}
var current = source;
var desc = drawDescription;
foreach (var node in _nodes)
{
try
{
ApplyParameters(node.Model, node.Mapping, requests[node.RequestIndex].Arguments);
node.Processor.SetInput(current);
var effectDescription = new EffectDescription(baseDesc, desc, baseDesc.InputIndex, baseDesc.InputCount, baseDesc.GroupIndex, baseDesc.GroupCount);
desc = node.Processor.Update(effectDescription);
current = node.Processor.Output;
}
catch
{
}
}
drawDescription = desc;
return current;
}
private void SyncNodes(IReadOnlyList<AviUtlEffectRequest> requests, AviUtlEngine target)
{
if (SignatureMatches(requests, target))
return;
DisposeNodes();
_signatureTarget = target;
_signature = new string[requests.Count];
for (int i = 0; i < requests.Count; i++)
_signature[i] = requests[i].Name;
for (int i = 0; i < requests.Count; i++)
{
Type? type;
AviUtlEffectMapping? mapping;
if (AviUtlCompatMap.Default.TryResolve(requests[i].Name, target, out var resolved) &&
ResolveType(resolved.TargetType) is { } mappedType)
{
mapping = resolved;
type = mappedType;
}
else
{
mapping = null;
type = ResolveName(requests[i].Name);
}
if (type is null)
continue;
IVideoEffect? model = null;
try
{
model = Activator.CreateInstance(type) as IVideoEffect;
}
catch
{
}
if (model is null)
continue;
IVideoEffectProcessor processor;
try
{
processor = model.CreateVideoEffect(_devices);
}
catch
{
continue;
}
_nodes.Add(new Node { Model = model, Processor = processor, Mapping = mapping, RequestIndex = i });
}
}
private bool SignatureMatches(IReadOnlyList<AviUtlEffectRequest> requests, AviUtlEngine target)
{
if (_signatureTarget != target || _signature.Length != requests.Count)
return false;
for (int i = 0; i < requests.Count; i++)
{
if (!string.Equals(_signature[i], requests[i].Name, StringComparison.Ordinal))
return false;
}
return true;
}
private static Type? ResolveType(string targetType)
{
EnsureRegistries();
return _typeRegistry!.TryGetValue(Normalize(targetType), out var type) ? type : null;
}
private static Type? ResolveName(string name)
{
EnsureRegistries();
return _nameRegistry!.TryGetValue(Normalize(name), out var type) ? type : null;
}
private static void EnsureRegistries()
{
if (_typeRegistry is not null && _nameRegistry is not null)
return;
var byType = new Dictionary<string, Type>(StringComparer.Ordinal);
var byName = new Dictionary<string, Type>(StringComparer.Ordinal);
try
{
foreach (var factory in EffectFactories.VideoEffectFactories)
{
try
{
var type = factory.EffectType;
if (type is null)
continue;
byType.TryAdd(Normalize(type.Name), type);
Register(byName, factory.Name, type);
foreach (var keyword in factory.Keywords)
Register(byName, keyword, type);
}
catch
{
}
}
}
catch
{
}
_typeRegistry = byType;
_nameRegistry = byName;
}
private static void Register(Dictionary<string, Type> map, string? key, Type type)
{
if (string.IsNullOrWhiteSpace(key))
return;
map.TryAdd(Normalize(key), type);
}
private static string Normalize(string value) => value.Trim().ToLowerInvariant();
private static void ApplyParameters(IVideoEffect model, AviUtlEffectMapping? mapping, IReadOnlyList<KeyValuePair<string, object>> arguments)
{
if (arguments.Count == 0)
return;
var properties = GetProperties(model.GetType());
foreach (var (key, value) in arguments)
{
PropertyInfo? property;
AviUtlParameterMapping parameter;
if (mapping is not null)
{
if (!mapping.TryGetParameter(key, out parameter) ||
!properties.TryGetValue(Normalize(parameter.Property), out property))
continue;
}
else
{
if (!properties.TryGetValue(Normalize(key), out property))
continue;
parameter = Identity;
}
try
{
SetValue(model, property, value, parameter);
}
catch
{
}
}
}
private static Dictionary<string, PropertyInfo> GetProperties(Type type)
{
if (_propertyCache.TryGetValue(type, out var cached))
return cached;
var map = new Dictionary<string, PropertyInfo>(StringComparer.Ordinal);
foreach (var property in type.GetProperties(BindingFlags.Public | BindingFlags.Instance))
{
if (property.GetIndexParameters().Length != 0)
continue;
bool usable = property.PropertyType == typeof(Animation) || property.GetSetMethod() is not null;
if (!usable)
continue;
map.TryAdd(Normalize(property.Name), property);
try
{
var display = property.GetCustomAttribute<DisplayAttribute>()?.GetName();
if (!string.IsNullOrWhiteSpace(display))
map.TryAdd(Normalize(display), property);
}
catch
{
}
}
_propertyCache[type] = map;
return map;
}
private static void SetValue(IVideoEffect model, PropertyInfo property, object value, AviUtlParameterMapping parameter)
{
var type = property.PropertyType;
if (type == typeof(Animation))
{
if (property.GetValue(model) is Animation animation)
animation.CopyFrom(new Animation(parameter.Transform(ToDouble(value))));
return;
}
if (type == typeof(bool))
{
property.SetValue(model, ToBool(value));
return;
}
if (type.IsEnum)
{
property.SetValue(model, ToEnum(type, value));
return;
}
if (type == typeof(Color))
{
property.SetValue(model, ToColor(value));
return;
}
if (type == typeof(double) || type == typeof(float) || type == typeof(int) || type == typeof(long) || type == typeof(short))
{
property.SetValue(model, Convert.ChangeType(parameter.Transform(ToDouble(value)), type, CultureInfo.InvariantCulture));
return;
}
if (type == typeof(string))
property.SetValue(model, value?.ToString());
}
private static double ToDouble(object value) => value switch
{
double d => d,
bool b => b ? 1d : 0d,
string s => double.TryParse(s, NumberStyles.Float, CultureInfo.InvariantCulture, out var r) ? r : 0d,
_ => 0d,
};
private static bool ToBool(object value) => value switch
{
bool b => b,
double d => d != 0d,
string s => s.Equals("true", StringComparison.OrdinalIgnoreCase) || s == "1",
_ => false,
};
private static object ToEnum(Type type, object value)
{
if (value is string s && Enum.TryParse(type, s, true, out var parsed))
return parsed;
return Enum.ToObject(type, (int)ToDouble(value));
}
private static Color ToColor(object value)
{
int rgb = (int)ToDouble(value);
return Color.FromRgb((byte)((rgb >> 16) & 0xFF), (byte)((rgb >> 8) & 0xFF), (byte)(rgb & 0xFF));
}
private void DisposeNodes()
{
foreach (var node in _nodes)
{
try
{
node.Processor.ClearInput();
}
catch
{
}
node.Processor.Dispose();
}
_nodes.Clear();
}
public void Dispose() => DisposeNodes();
}
}
+280 -6
ファイルの表示
@@ -24,6 +24,58 @@
حذف هذه الاستدعاءات عند عدم الحاجة يسرّع المعالجة. حذف هذه الاستدعاءات عند عدم الحاجة يسرّع المعالجة.
- محركات التنفيذ والتسريع التلقائي -
النصوص التي تحتوي على معالجة بكسل (حلقة getpixel/setpixel متداخلة)
يُحلَّل تركيبها وتُوجَّه تلقائياً إلى محرك أسرع.
أما النصوص العادية (الإحداثيات، الدوران، الشفافية، إلخ) فتظل تعمل على
MoonSharp كما في السابق دون أي تغيير في السلوك.
○ التوجيه التلقائي (عند عدم وجود توجيه)
· تخطيط بكسل مكتفٍ بنفسه (انظر الشروط أدناه)
→ نواة CPU (سريعة ودقيقة)
· عمليات البكسل الأخرى → Native (LuaJIT، فقط عند نشره)
· بلا عمليات بكسل → MoonSharp
○ توجيهات المحرك (تعليق في السطر الأول من النص)
--!cpu : نواة CPU. تُترجَم وقت التشغيل إلى شجرة تعابير
وتُنفَّذ بالتوازي على كل أنوية CPU (مطابقة تماماً لـ MoonSharp).
--!gpu : نواة GPU. تُنفَّذ كمظلِّل بكسل Direct2D،
وتلغي نقل GPU→CPU لأقصى سرعة.
قد تختلف النتائج اختلافاً طفيفاً بسبب دقة float32 (اختياري).
--!native : LuaJIT (عملية منفصلة). سريع ومطابق لـ MoonSharp.
يتطلب نشر مجلد native.
--!moonsharp : يفرض محرك MoonSharp التقليدي.
※ إذا كان التوجيه غير متاح/غير مدعوم، يرجع تلقائياً إلى محرك أدنى
(لا يتلف الإخراج أبداً).
○ التركيب المؤهَّل للنواة السريعة (تخطيط بكسل خالص)
فقط الحلقة المتداخلة بالشكل التالي تتحول إلى نواة.
for y = 0, obj.h - 1 do
for x = 0, obj.w - 1 do
local r, g, b, a = obj.getpixel(x, y)
obj.setpixel(x, y, r2, g2, b2 [, a2])
end
end
· يجوز في الجسم استخدام العمليات الحسابية و math.* والمقارنات
وصيغة العتبة "cond and value1 or value2" ومتغيرات local فقط.
· يجوز الإشارة فقط إلى البكسل الجاري معالجته (getpixel(x, y))
وقيم مثل obj/scene/time.
· أي استخدام لأخذ عينات الجوار (التمويه، إلخ) أو الكتابة إلى
إحداثيات أخرى أو getpixeldata أو getobject أو عمليات
الجداول/السلاسل أو جُمَل if لا يتحول إلى نواة ويُنفَّذ تلقائياً
على المحرك التقليدي.
مثال (يجعل شكلاً أبيض أحمر):
--!gpu
for y = 0, obj.h - 1 do
for x = 0, obj.w - 1 do
local r, g, b, a = obj.getpixel(x, y)
obj.setpixel(x, y, r, g / 2, b / 2, a)
end
end
- المعاملات - - المعاملات -
يحتوي لوح التأثيرات على 4 أشرطة تتبع (تدعم الرسوم المتحركة) على النحو التالي. يحتوي لوح التأثيرات على 4 أشرطة تتبع (تدعم الرسوم المتحركة) على النحو التالي.
@@ -36,6 +88,36 @@
* كل شريط تتبع يدعم شرائح الرسوم المتحركة (مع الاستيفاء). * كل شريط تتبع يدعم شرائح الرسوم المتحركة (مع الاستيفاء).
* يمكن استيراد/تصدير ملفات .lua من شريط أدوات محرر النصوص. * يمكن استيراد/تصدير ملفات .lua من شريط أدوات محرر النصوص.
* تظهر مربعات الاختيار (obj.check0 إلى obj.check3) واللون (color) في لوح التأثيرات
تلقائياً عندما يشير إليها النص البرمجي (تظهر أشرطة التتبع دائماً). هذا الاستخدام
العام لا يصاحبه إعلان نطاق/قيمة افتراضية، لذا تعامل مع نطاقات القيم داخل النص.
وتبقى رؤوس AviUtl ‏--track / --check / --color تعمل كما كانت.
توجد 4 منزلقات رقمية، ويُشار إليها عبر obj.slider0 إلى obj.slider3.
القيم أعداد صحيحة ولا تحمل كسوراً عشرية.
Slider0 : منزلق صحيح (النطاق: 1 ~ 10)
Slider1 : منزلق صحيح (النطاق: 0 ~ 100)
Slider2 : منزلق صحيح (النطاق: 0 ~ 1000)
Slider3 : منزلق صحيح (النطاق: -1000 ~ 1000)
تتوفر أيضاً معاملات نصية، ويُشار إلى كل قيمة بالأسماء التالية.
obj.text : نص حقل إدخال النص
obj.font : اسم الخط من محدد الخطوط
obj.dir : مسار محدد المجلدات
obj.file_video : مسار ملف فيديو
obj.file_audio : مسار ملف صوتي
obj.file_image : مسار ملف صورة
obj.file_project : مسار ملف مشروع
obj.file_mp4 : مسار ملف MP4
obj.file_exo : مسار ملف EXO
obj.file_subtitle : مسار ملف ترجمة
obj.file_shader : مسار ملف تظليل
※تظهر المنزلقات والمعاملات النصية في لوح التأثيرات تلقائياً عندما يشير إليها النص البرمجي.
※يمكن تمرير مسار الملف إلى obj.load لتحميل صورة أو فيديو.
※تتوفر هذه المعاملات في محركَي MoonSharp والمحرك الأصلي معاً.
- المتغيرات العامة - - المتغيرات العامة -
@@ -157,6 +239,18 @@
obj.track2 : القيمة الحالية لـ Track2 في لوح التأثيرات [للقراءة فقط] obj.track2 : القيمة الحالية لـ Track2 في لوح التأثيرات [للقراءة فقط]
obj.track3 : القيمة الحالية لـ Track3 في لوح التأثيرات [للقراءة فقط] obj.track3 : القيمة الحالية لـ Track3 في لوح التأثيرات [للقراءة فقط]
○ المنزلقات
obj.slider0 : القيمة الحالية لـ Slider0 في لوح التأثيرات (عدد صحيح) [للقراءة فقط]
obj.slider1 : القيمة الحالية لـ Slider1 في لوح التأثيرات (عدد صحيح) [للقراءة فقط]
obj.slider2 : القيمة الحالية لـ Slider2 في لوح التأثيرات (عدد صحيح) [للقراءة فقط]
obj.slider3 : القيمة الحالية لـ Slider3 في لوح التأثيرات (عدد صحيح) [للقراءة فقط]
○ المعاملات النصية
obj.text : نص حقل إدخال النص [للقراءة فقط]
obj.font : اسم الخط من محدد الخطوط [للقراءة فقط]
obj.dir : مسار محدد المجلدات [للقراءة فقط]
obj.file_video ~ obj.file_shader : مسار كل محدد ملفات [للقراءة فقط]
○ الطبقة ○ الطبقة
obj.layer : رقم الطبقة التي يوجد فيها الكائن [للقراءة فقط] obj.layer : رقم الطبقة التي يوجد فيها الكائن [للقراءة فقط]
* نفس قيمة المتغير العام layer. * نفس قيمة المتغير العام layer.
@@ -301,6 +395,104 @@
لكن في هذا المكوِّن الإضافي تنعكس التغييرات عبر setpixel/set تلقائياً، لكن في هذا المكوِّن الإضافي تنعكس التغييرات عبر 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" و"text"
و"image" (ملف صورة) و"movie" (ملف فيديو). بعد التحميل تُحدَّث
obj.w / obj.h وغيرها إلى الحجم المُولَّد، ويمكن قراءتها بـ getpixel
مباشرة بعد التحميل. يعمل على محرك MoonSharp والمحرك السريع (LuaJIT).
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("text", string)
يرسم النص بالخط والحجم واللون المحددة بـ obj.setfont ويستبدل
المخزن (يُرسم بـ DirectWrite).
مثال: obj.setfont("Yu Gothic UI", 48); obj.load("text", "字幕")
obj.load("image", path)
يحمّل ملف صورة ويستبدل المخزن.
※ للأمان يُتحقَّق من الترويسة الأولى، ولا تُحمَّل إلا الصور
الأصلية (PNG / JPEG / GIF / BMP / TIFF / WebP).
مثال: obj.load("image", "C:\\img\\logo.png")
obj.load("movie", path [, time])
يحمّل الإطار عند الزمن المحدد من ملف فيديو ويستبدل المخزن
(يُفكَّك بـ Media Foundation).
time : بالثواني. الافتراضي obj.time عند الحذف.
※ للأمان يُتحقَّق من الترويسة الأولى، ولا تُحمَّل إلا مقاطع
الفيديو الأصلية (MP4 / MOV / MKV / WebM / AVI / FLV / ASF).
مثال: obj.load("movie", "C:\\mov\\clip.mp4", obj.time)
○ obj.setfont(font [, size [, style [, color]]])
يحدد الخط المستخدم في obj.load("text").
style : أعلام بِتّية. 1=عريض، 2=مائل، 3=عريض+مائل.
color : 0xRRGGBB.
مثال: obj.setfont("Meiryo", 64, 1, 0xffffff)
○ obj.draw([ox, oy, oz [, zoom [, alpha [, aspect]]]])
يدمج صورة الكائن الحالية في مخزن التراكم ويرسمها.
استدعاؤها عدة مرات يرسم نسخاً متراكبة (صور لاحقة، جزيئات، إلخ).
ox, oy, oz : الإزاحة من المركز (افتراضي 0).
zoom : 1.0 هو الحجم الأصلي (افتراضي 1.0).
alpha : 0.0 ~ 1.0 (افتراضي 1.0).
aspect : -1.0 ~ 1.0 (افتراضي 0).
※ بعد الاستدعاء يُكبَت الرسم القياسي ويُخرَج الناتج المدموج.
○ obj.drawpoly(x0,y0,z0, x1,y1,z1, x2,y2,z2, x3,y3,z3
[, u0,v0, u1,v1, u2,v2, u3,v3 [, alpha]])
يطبّق صورة الكائن كنسيج على رباعي محدد بأربع رؤوس.
ترتيب الرؤوس: أعلى-يسار، أعلى-يمين، أسفل-يمين، أسفل-يسار.
عند حذف UV تُستخدم الصورة كاملة.
※ عند حذف UV وإعطاء المعامل الثالث عشر فقط، يُستخدم كقيمة ألفا
(12 إحداثياً + ألفا).
※ يُسقَط بتحويل أفيني (دقيق لمتوازي الأضلاع، تقريبي لغيره).
○ obj.copybuffer(الوجهة، المصدر)
ينسخ صورة بين المخازن، يُحدَّد بالحرف الأول.
"obj" : مخزن صورة الكائن
"tmp" : مخزن مؤقت
"cache:الاسم" : ذاكرة مخبّأة مُسمّاة (تُحفظ بين الإطارات)
مثال: obj.copybuffer("tmp", "obj") -- حفظ
obj.copybuffer("obj", "tmp") -- استعادة
※ "frm" (مخزن الإطار / الخلفية) لا يمكن الحصول عليه بسبب بنية YMM4.
○ obj.getvalue(الهدف)
يحصل على القيمة الحالية لـ obj (مثل obj.x و obj.track0).
الهدف : "x","y","z","ox","oy","rx","ry","rz","zoom","aspect",
"alpha","sx","sy","track0"~"track3","time","frame" إلخ.
المُرجَع : رقم (0 لهدف غير معروف).
○ obj.setoption(name, value) / obj.getoption(name)
يضبط / يحصل على خيار. الخيارات غير المدعومة تُقبَل كي لا توقف
النص (getoption يُرجع القيمة المحفوظة، و0 إن لم تُضبط).
الخيارات التي تؤثر على الرسم حالياً:
"antialias" : 0 = أقرب جار، وإلا استيفاء خطّي
(obj.draw / obj.drawpoly).
○ obj.pixeloption(name, value)
يحفظ خياراً لعمليات البكسل كحالة.
- ymm4 Table - - ymm4 Table -
@@ -441,17 +633,99 @@
obj.zoom = obj.zoom * (1 + obj.track0 / 100) 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.draw / obj.drawpoly، وعمليات المخزن
عبر obj.copybuffer، والتوليد والتحميل عبر
obj.load("figure"/"text"/"image"/"movie")، و obj.setfont، و obj.effect،
و obj.getvalue، و obj.setoption / obj.getoption / obj.pixeloption.
انظر "جدول obj - الدوال" للتفاصيل.
○ خريطة توافق AviUtl / AviUtl2 لـ obj.effect
يَرجع obj.effect("اسم التأثير"، "اسم المعامل"، القيمة، ...) إلى خريطة
التوافق أولًا. التأثيرات المُعلَنة بأسماء AviUtl / AviUtl2 تمر عبر تحويل
المقياس/الإزاحة المُعلَن قبل الوصول إلى خصائص YMM4. الأسماء غير المُعلَنة في
الخريطة تُحَلّ مباشرةً عبر اسم تأثير YMM4 أو كلمته المفتاحية، لذا تظل
الاستدعاءات الحالية تعمل.
بُنيت الخريطة كمعكوس لتصدير AviUtl الخاص بـ YMM4 نفسه (مخرجات .exo)، لذا
تتطابق ذهابًا وإيابًا. يُختار المحرك الهدف عبر --!aviutl (الافتراضي) /
--!aviutl2.
أسماء التأثيرات المُعلَنة في الخريطة ومعاملاتها الرئيسية كما يلي:
ぼかし: 範囲, サイズ固定
境界ぼかし: 範囲
方向ブラー: 範囲, 角度, サイズ固定
放射ブラー: 範囲, X, Y, サイズを固定
閃光: 範囲, X, Y, サイズを固定
クロマキー: 色相範囲, 境界補正
クリッピング: 上, 下, 左, 右, 中心の位置を変更
斜めクリッピング: 中心X, 中心Y, 角度, ぼかし, 幅
領域拡張: 上, 下, 左, 右
座標: X, Y, Z
回転: X, Y, Z
リサイズ: 拡大率, X, Y, 補間なし
画像ループ: 横回数, 縦回数
極座標変換: 中心幅, 渦巻
グラデーション: 強さ, 中心X, 中心Y, 角度, 幅
単色化: 強さ, 輝度を保持する
縁取り: サイズ, ぼかし
反転: -
モザイク: サイズ
ディスプレイスメントマップ: ぼかし
動画ファイル合成: X, Y, 拡大率
色調補正: 明るさ, コントラスト, 色相, 輝度, 彩度
色ずれ: ずれ幅, 角度, 強さ
يتوافق 色調補正 و 色ずれ مع تأثيرات إضافة المجتمع.
الميزات التالية خارج نطاق هذه الطبقة.
النصوص التي تستدعيها لن تعمل كما هو متوقع.
× تحميل الوحدات عبر require، والوصول العشوائي إلى الملفات مثل
io / dofile (تحميل الصور / الفيديو عبر obj.load مدعوم مع التحقق
من الترويسة).
× obj.setanchor، scene.set / scene.get وما شابه.
- الميزات غير المدعومة / القيود - - الميزات غير المدعومة / القيود -
× obj.effect()، obj.draw()، obj.drawpoly()، obj.load() وما شابه من AviUtl2 غير مدعومة. × obj.rand1()، obj.mes()، obj.setanchor() وما شابه من AviUtl2 غير مدعومة.
× obj.rand()، obj.rand1()، obj.setfont()، obj.mes() وما شابه من AviUtl2 غير مدعومة.
× obj.setoption()، obj.getoption()، obj.getvalue()، obj.setanchor() وما شابه من AviUtl2 غير مدعومة.
× الدوال مثل scene.set() و scene.get() في جدول scene الخاص بـ AviUtl2 غير مدعومة. × الدوال مثل scene.set() و scene.get() في جدول scene الخاص بـ AviUtl2 غير مدعومة.
(يمكن قراءة scene.width و scene.height فقط) (يمكن قراءة scene.width و scene.height فقط)
× الوصول إلى الملفات (require, dofile, io وما شابه) غير مدعوم. × الوصول العشوائي إلى الملفات من النصوص (require, dofile, io وما شابه) غير مدعوم.
فقط obj.load("image"/"movie") يحمّل الملفات المؤكَّد أنها وسائط أصلية عبر
التحقق من الترويسة الأولى.
× تعديل obj.z ينعكس في الرسم (مضمَّن في ReadBack)، × تعديل obj.z ينعكس في الرسم (مضمَّن في ReadBack)،
لكن دعم الرسم ثلاثي الأبعاد محدود. لكن دعم الرسم ثلاثي الأبعاد محدود.
× إذا تجاوز النص البرمجي مهلة الانتهاء (5 ثوانٍ)، يُنهى التنفيذ قسراً. × إذا تجاوز النص البرمجي مهلة الانتهاء (5 ثوانٍ)، يُنهى التنفيذ قسراً.
يجب الانتباه في التطبيق لتجنب الحلقات اللانهائية. يجب الانتباه في التطبيق لتجنب الحلقات اللانهائية.
× توجيهات الترويسة من AviUtl2 مثل --track@ و --check@ غير مدعومة. × توجيهات الترويسة من AviUtl2 مدعومة جزئياً فقط. تُفسَّر القيم الافتراضية لـ
يمكن استخدام Track0 ~ Track3 فقط كمعاملات. --dialog / --color / --check / --param (انظر "التوافق الجزئي مع نصوص AviUtl")،
لكن التسمية والنطاق والقيمة الافتراضية لـ --track@ لا تنعكس على الواجهة،
وتُستخدم القيم عبر Track0 ~ Track3.
+296 -6
ファイルの表示
@@ -24,6 +24,61 @@
Omitting these calls when unnecessary will speed up processing. Omitting these calls when unnecessary will speed up processing.
- Execution Engines and Automatic Acceleration -
Scripts that contain pixel processing (a nested getpixel/setpixel loop)
are analyzed and automatically routed to a faster engine.
Ordinary scripts (coordinate, rotation, opacity changes, etc.) keep
running on MoonSharp as before, with no change in behavior.
o Automatic routing (when no directive is present)
- A self-contained per-pixel map (see conditions below)
-> CPU kernel (fast, exact)
- Other pixel operations -> Native (LuaJIT, only when deployed)
- No pixel operations -> MoonSharp
o Engine directives (a comment on the first line of the script)
--!cpu : CPU kernel. Compiled at runtime to an expression
tree and run in parallel on all CPU cores
(bit-identical to MoonSharp).
--!gpu : GPU kernel. Run as a Direct2D pixel shader,
eliminating the GPU->CPU transfer for top speed.
Results may differ slightly due to float32
precision (opt-in).
--!native : LuaJIT (separate process). Fast and identical to
MoonSharp. Requires the native folder deployed.
--!moonsharp : Forces the classic MoonSharp engine.
* If a directive is unavailable or unsupported, it automatically
falls back to a lower engine (the output is never broken).
o Syntax eligible for the fast kernel (a pure per-pixel map)
Only a nested loop of the following form becomes a kernel.
for y = 0, obj.h - 1 do
for x = 0, obj.w - 1 do
local r, g, b, a = obj.getpixel(x, y)
obj.setpixel(x, y, r2, g2, b2 [, a2])
end
end
- The body may use only arithmetic, math.*, comparisons, the
threshold idiom "cond and value1 or value2", and local
variables.
- It may reference only the current pixel being processed
(getpixel(x, y)) and values such as obj/scene/time.
- Anything using neighbor sampling (blur, etc.), writes to other
coordinates, getpixeldata, getobject, table/string operations,
or if statements is not turned into a kernel and automatically
runs on the classic engine.
Example (turns a white figure red):
--!gpu
for y = 0, obj.h - 1 do
for x = 0, obj.w - 1 do
local r, g, b, a = obj.getpixel(x, y)
obj.setpixel(x, y, r, g / 2, b / 2, a)
end
end
- Parameters - - Parameters -
The effect panel has 4 trackbars (animation-enabled) as follows. The effect panel has 4 trackbars (animation-enabled) as follows.
@@ -36,6 +91,38 @@
* Each trackbar supports animation sliders (with interpolation). * Each trackbar supports animation sliders (with interpolation).
* .lua files can be imported/exported from the script editor toolbar. * .lua files can be imported/exported from the script editor toolbar.
* The checkboxes (obj.check0 - obj.check3) and the color (color) appear in the
effect panel automatically when the script references them (the trackbars are
always shown). This general use carries no range/default declaration, so handle
value ranges within the script. The AviUtl --track / --check / --color headers
still work as before.
There are 4 numeric sliders, referenced as obj.slider0 through obj.slider3.
The values are integers and do not hold decimals.
Slider0 : Integer slider (Range: 1 ~ 10)
Slider1 : Integer slider (Range: 0 ~ 100)
Slider2 : Integer slider (Range: 0 ~ 1000)
Slider3 : Integer slider (Range: -1000 ~ 1000)
String parameters are also available, referenced by the following names.
obj.text : String from the text input field
obj.font : Font name from the font selector
obj.dir : Path from the folder selector
obj.file_video : Path of a video file
obj.file_audio : Path of an audio file
obj.file_image : Path of an image file
obj.file_project : Path of a project file
obj.file_mp4 : Path of an MP4 file
obj.file_exo : Path of an EXO file
obj.file_subtitle : Path of a subtitle file
obj.file_shader : Path of a shader file
* The sliders and string parameters appear in the effect panel automatically
when the script references them.
* A file path can be passed to obj.load to load an image or movie.
* These parameters are available in both the MoonSharp and native engines.
- Global Variables - - Global Variables -
@@ -160,6 +247,18 @@
obj.track2 : Current value of Track2 in the effect panel [ReadOnly] obj.track2 : Current value of Track2 in the effect panel [ReadOnly]
obj.track3 : Current value of Track3 in the effect panel [ReadOnly] obj.track3 : Current value of Track3 in the effect panel [ReadOnly]
o Sliders
obj.slider0 : Current value of Slider0 in the effect panel (integer) [ReadOnly]
obj.slider1 : Current value of Slider1 in the effect panel (integer) [ReadOnly]
obj.slider2 : Current value of Slider2 in the effect panel (integer) [ReadOnly]
obj.slider3 : Current value of Slider3 in the effect panel (integer) [ReadOnly]
o String parameters
obj.text : String from the text input field [ReadOnly]
obj.font : Font name from the font selector [ReadOnly]
obj.dir : Path from the folder selector [ReadOnly]
obj.file_video ~ obj.file_shader : Path from each file selector [ReadOnly]
o Layer o Layer
obj.layer : Layer number where the object is placed [ReadOnly] obj.layer : Layer number where the object is placed [ReadOnly]
* Same value as global variable layer. * Same value as global variable layer.
@@ -307,6 +406,110 @@
but in this plugin changes via setpixel/set are automatically applied, but in this plugin changes via setpixel/set are automatically applied,
so calling this function is unnecessary. 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. The targets
"figure", "text", "image" (image file) and "movie" (video file)
are supported. After loading, obj.w / obj.h, etc. are updated to the
generated size and can be read by getpixel right after the load.
Works on both the MoonSharp and the fast (LuaJIT) engine.
obj.load("figure", name, color, size [, line [, aspect]])
Generates a shape and replaces the buffer (centered).
name : 円 / 四角形 / 三角形 / 五角形 / 六角形 / 星形
(English aliases circle, rect, triangle, pentagon,
hexagon, star are also accepted).
color : Fill color 0xRRGGBB.
size : Bounding size in pixels.
line : Outline width (optional). 0 fills the shape.
aspect : Distortion -1.0 ~ 1.0 (optional).
Example: obj.load("figure", "円", 0xff3366, 200)
obj.load("text", string)
Draws the string with the font, size and color set by
obj.setfont and replaces the buffer (rendered with DirectWrite).
Example: obj.setfont("Yu Gothic UI", 48); obj.load("text", "字幕")
obj.load("image", path)
Loads an image file and replaces the buffer.
* For safety the leading header is validated and only genuine
images (PNG / JPEG / GIF / BMP / TIFF / WebP) are loaded.
Example: obj.load("image", "C:\\img\\logo.png")
obj.load("movie", path [, time])
Loads the frame at the given time of a video file and replaces
the buffer (decoded with Media Foundation).
time : Seconds. Defaults to obj.time when omitted.
* For safety the leading header is validated and only genuine
videos (MP4 / MOV / MKV / WebM / AVI / FLV / ASF) are loaded.
Example: obj.load("movie", "C:\\mov\\clip.mp4", obj.time)
o obj.setfont(font [, size [, style [, color]]])
Sets the font used by obj.load("text").
style : Bit flags. 1=bold, 2=italic, 3=bold+italic.
color : 0xRRGGBB.
Example: obj.setfont("Meiryo", 64, 1, 0xffffff)
o obj.draw([ox, oy, oz [, zoom [, alpha [, aspect]]]])
Composites the current object image onto the accumulation buffer.
Calling it multiple times draws overlapping copies (afterimages,
particles, etc.).
ox, oy, oz : Offset from the center (default 0).
zoom : 1.0 is original size (default 1.0).
alpha : 0.0 ~ 1.0 (default 1.0).
aspect : -1.0 ~ 1.0 (default 0).
* Once called, the standard draw is suppressed and the composited
result is output.
o obj.drawpoly(x0,y0,z0, x1,y1,z1, x2,y2,z2, x3,y3,z3
[, u0,v0, u1,v1, u2,v2, u3,v3 [, alpha]])
Texture-maps the object image onto a quad given by 4 vertices.
Vertex order is top-left, top-right, bottom-right, bottom-left.
When UVs are omitted the whole image is used.
* If only a 13th argument is given (UVs omitted), it is used as the
alpha (12 coordinates + alpha).
* Mapped with an affine transform (exact for parallelograms,
approximate for non-parallelograms).
o obj.copybuffer(destination, source)
Copies an image between buffers, selected by the first character.
"obj" : Object image buffer
"tmp" : Temporary buffer
"cache:name" : Named cache (kept across frames)
Example: obj.copybuffer("tmp", "obj") -- save
obj.copybuffer("obj", "tmp") -- restore
* "frm" (frame buffer / background) cannot be obtained due to the
structure of YMM4.
o obj.getvalue(target)
Gets the current value of obj (same as obj.x, obj.track0, etc.).
target : "x","y","z","ox","oy","rx","ry","rz","zoom","aspect",
"alpha","sx","sy","track0"~"track3","time","frame", etc.
Returns: a number (0 for an unknown target).
o obj.setoption(name, value) / obj.getoption(name)
Sets / gets an option. Unsupported options are accepted so they do
not stop the script (getoption returns the stored value, 0 if unset).
Options that currently affect drawing:
"antialias" : 0 = nearest neighbor, otherwise linear interpolation
(obj.draw / obj.drawpoly).
o obj.pixeloption(name, value)
Stores an option for pixel operations as state.
- ymm4 Table - - ymm4 Table -
@@ -447,17 +650,104 @@
obj.zoom = obj.zoom * (1 + obj.track0 / 100) 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 Drawing, compositing and loading
Drawing and compositing with obj.draw / obj.drawpoly, buffer
operations with obj.copybuffer, generation and loading with
obj.load("figure"/"text"/"image"/"movie"), obj.setfont, obj.effect,
obj.getvalue, and obj.setoption / obj.getoption / obj.pixeloption are
supported. See "obj Table - Functions" for details.
o AviUtl / AviUtl2 compatibility map for obj.effect
obj.effect("effect name", "parameter name", value, ...) first consults
the compatibility map. Effects declared as AviUtl / AviUtl2 names pass
through the declared scale/offset conversion before reaching the YMM4
properties. Names not declared in the map are resolved directly by the
YMM4 effect name or keyword, so existing calls keep working. The map is
built as the inverse of YMM4's own AviUtl export (.exo output), so it
round-trips exactly. The target engine is selected with --!aviutl
(default) / --!aviutl2.
The effect names declared in the map and their main parameters are as
follows.
ぼかし: 範囲, サイズ固定
境界ぼかし: 範囲
方向ブラー: 範囲, 角度, サイズ固定
放射ブラー: 範囲, X, Y, サイズを固定
閃光: 範囲, X, Y, サイズを固定
クロマキー: 色相範囲, 境界補正
クリッピング: 上, 下, 左, 右, 中心の位置を変更
斜めクリッピング: 中心X, 中心Y, 角度, ぼかし, 幅
領域拡張: 上, 下, 左, 右
座標: X, Y, Z
回転: X, Y, Z
リサイズ: 拡大率, X, Y, 補間なし
画像ループ: 横回数, 縦回数
極座標変換: 中心幅, 渦巻
グラデーション: 強さ, 中心X, 中心Y, 角度, 幅
単色化: 強さ, 輝度を保持する
縁取り: サイズ, ぼかし
反転: -
モザイク: サイズ
ディスプレイスメントマップ: ぼかし
動画ファイル合成: X, Y, 拡大率
色調補正: 明るさ, コントラスト, 色相, 輝度, 彩度
色ずれ: ずれ幅, 角度, 強さ
色調補正 and 色ずれ correspond to community plugin effects.
The following are out of scope for this layer. Scripts that call them will not
behave as intended.
x Module loading via require, and arbitrary file access such as io /
dofile (image / video loading via obj.load is supported with header
validation).
x obj.setanchor, scene.set / scene.get, etc.
- Unsupported Features / Limitations - - Unsupported Features / Limitations -
x obj.effect(), obj.draw(), obj.drawpoly(), obj.load(), etc. from AviUtl2 are not supported. x obj.rand1(), obj.mes(), obj.setanchor(), etc. from AviUtl2 are not supported.
x obj.rand(), obj.rand1(), obj.setfont(), obj.mes(), etc. from AviUtl2 are not supported.
x obj.setoption(), obj.getoption(), obj.getvalue(), obj.setanchor(), etc. from AviUtl2 are not supported.
x Functions such as scene.set() and scene.get() in the AviUtl2 scene table are not supported. x Functions such as scene.set() and scene.get() in the AviUtl2 scene table are not supported.
(Only scene.width and scene.height can be read) (Only scene.width and scene.height can be read)
x File access (require, dofile, io, etc.) is not supported. x Arbitrary file access from scripts (require, dofile, io, etc.) is not supported.
Only obj.load("image"/"movie") loads files confirmed to be genuine media by
leading-header validation.
x Modifying obj.z is reflected in rendering (included in ReadBack), x Modifying obj.z is reflected in rendering (included in ReadBack),
but 3D rendering support is limited. but 3D rendering support is limited.
x If the script timeout (5 seconds) is exceeded, execution is forcibly terminated. x If the script timeout (5 seconds) is exceeded, execution is forcibly terminated.
Care must be taken in implementation to prevent infinite loops. Care must be taken in implementation to prevent infinite loops.
x AviUtl2 header directives such as --track@ and --check@ are not supported. x AviUtl2 header directives are only partially supported. The default values of
Only Track0 ~ Track3 can be used as parameters. --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.
+301 -6
ファイルの表示
@@ -24,6 +24,61 @@
primer acceso. Omitir estas llamadas cuando no sean necesarias acelera el procesamiento. primer acceso. Omitir estas llamadas cuando no sean necesarias acelera el procesamiento.
- Motores de ejecución y aceleración automática -
Los scripts que contienen procesamiento de píxeles (un bucle anidado
getpixel/setpixel) se analizan y se enrutan automáticamente a un motor
más rápido. Los scripts normales (coordenadas, rotación, opacidad, etc.)
siguen ejecutándose en MoonSharp como antes, sin cambios de comportamiento.
o Enrutamiento automático (cuando no hay directiva)
- Un mapeo por píxel autocontenido (ver condiciones abajo)
-> núcleo CPU (rápido, exacto)
- Otras operaciones de píxeles -> Nativo (LuaJIT, solo si está
desplegado)
- Sin operaciones de píxeles -> MoonSharp
o Directivas de motor (un comentario en la primera línea del script)
--!cpu : Núcleo CPU. Compilado en tiempo de ejecución a un
árbol de expresiones y ejecutado en paralelo en
todos los núcleos de la CPU (idéntico a MoonSharp).
--!gpu : Núcleo GPU. Ejecutado como un sombreador de píxeles
de Direct2D, eliminando la transferencia GPU->CPU
para máxima velocidad. Los resultados pueden diferir
levemente por la precisión float32 (opcional).
--!native : LuaJIT (proceso aparte). Rápido e idéntico a
MoonSharp. Requiere la carpeta native desplegada.
--!moonsharp : Fuerza el motor clásico MoonSharp.
* Si una directiva no está disponible o no es compatible, recurre
automáticamente a un motor inferior (la salida nunca se rompe).
o Sintaxis apta para el núcleo rápido (un mapeo por píxel puro)
Solo un bucle anidado con la forma siguiente se convierte en núcleo.
for y = 0, obj.h - 1 do
for x = 0, obj.w - 1 do
local r, g, b, a = obj.getpixel(x, y)
obj.setpixel(x, y, r2, g2, b2 [, a2])
end
end
- El cuerpo solo puede usar aritmética, math.*, comparaciones, el
modismo de umbral "cond and valor1 or valor2" y variables local.
- Solo puede referenciar el píxel actual en proceso
(getpixel(x, y)) y valores como obj/scene/time.
- Todo lo que use muestreo de vecinos (desenfoque, etc.),
escrituras en otras coordenadas, getpixeldata, getobject,
operaciones de tabla/cadena o sentencias if no se convierte en
núcleo y se ejecuta automáticamente en el motor clásico.
Ejemplo (vuelve roja una figura blanca):
--!gpu
for y = 0, obj.h - 1 do
for x = 0, obj.w - 1 do
local r, g, b, a = obj.getpixel(x, y)
obj.setpixel(x, y, r, g / 2, b / 2, a)
end
end
- Parámetros - - Parámetros -
El panel de efectos tiene los siguientes 4 controles deslizantes (con soporte de animación). El panel de efectos tiene los siguientes 4 controles deslizantes (con soporte de animación).
@@ -36,6 +91,38 @@
* Cada control deslizante es compatible con los deslizadores de animación (con interpolación). * Cada control deslizante es compatible con los deslizadores de animación (con interpolación).
* Los archivos .lua pueden importarse/exportarse desde la barra de herramientas del editor de scripts. * Los archivos .lua pueden importarse/exportarse desde la barra de herramientas del editor de scripts.
* Las casillas (obj.check0 - obj.check3) y el color (color) aparecen en el panel de
efectos automáticamente cuando el script los referencia (las barras siempre se
muestran). Este uso general no conlleva declaración de rango/valor predeterminado,
así que gestione los rangos dentro del script. Las cabeceras --track / --check /
--color de AviUtl siguen funcionando como antes.
Hay 4 deslizadores numéricos, referenciados como obj.slider0 ~ obj.slider3.
Los valores son enteros y no contienen decimales.
Slider0 : Deslizador entero (Rango: 1 ~ 10)
Slider1 : Deslizador entero (Rango: 0 ~ 100)
Slider2 : Deslizador entero (Rango: 0 ~ 1000)
Slider3 : Deslizador entero (Rango: -1000 ~ 1000)
También hay parámetros de cadena, referenciados por los siguientes nombres.
obj.text : Cadena del campo de entrada de texto
obj.font : Nombre de fuente del selector de fuentes
obj.dir : Ruta del selector de carpetas
obj.file_video : Ruta de un archivo de video
obj.file_audio : Ruta de un archivo de audio
obj.file_image : Ruta de un archivo de imagen
obj.file_project : Ruta de un archivo de proyecto
obj.file_mp4 : Ruta de un archivo MP4
obj.file_exo : Ruta de un archivo EXO
obj.file_subtitle : Ruta de un archivo de subtítulos
obj.file_shader : Ruta de un archivo de sombreador
* Los deslizadores y los parámetros de cadena aparecen en el panel de efectos
automáticamente cuando el script los referencia.
* Una ruta de archivo puede pasarse a obj.load para cargar una imagen o un video.
* Estos parámetros están disponibles en los motores MoonSharp y nativo.
- Variables globales - - Variables globales -
@@ -157,6 +244,18 @@
obj.track2 : Valor actual de Track2 en el panel de efectos [Solo lectura] obj.track2 : Valor actual de Track2 en el panel de efectos [Solo lectura]
obj.track3 : Valor actual de Track3 en el panel de efectos [Solo lectura] obj.track3 : Valor actual de Track3 en el panel de efectos [Solo lectura]
o Deslizadores
obj.slider0 : Valor actual de Slider0 en el panel de efectos (entero) [Solo lectura]
obj.slider1 : Valor actual de Slider1 en el panel de efectos (entero) [Solo lectura]
obj.slider2 : Valor actual de Slider2 en el panel de efectos (entero) [Solo lectura]
obj.slider3 : Valor actual de Slider3 en el panel de efectos (entero) [Solo lectura]
o Parámetros de cadena
obj.text : Cadena del campo de entrada de texto [Solo lectura]
obj.font : Nombre de fuente del selector de fuentes [Solo lectura]
obj.dir : Ruta del selector de carpetas [Solo lectura]
obj.file_video ~ obj.file_shader : Ruta de cada selector de archivos [Solo lectura]
o Capa o Capa
obj.layer : Número de capa donde se encuentra el objeto [Solo lectura] obj.layer : Número de capa donde se encuentra el objeto [Solo lectura]
* Mismo valor que la variable global layer. * Mismo valor que la variable global layer.
@@ -305,6 +404,111 @@
pero en este plugin los cambios mediante setpixel/set se aplican automáticamente, pero en este plugin los cambios mediante setpixel/set se aplican automáticamente,
por lo que no es necesario llamar a esta función. 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. Se admiten los
targets "figure", "text", "image" (archivo de imagen) y "movie"
(archivo de vídeo). Tras la carga, obj.w / obj.h, etc. se actualizan al
tamaño generado y pueden leerse con getpixel justo después de la carga.
Funciona en el motor MoonSharp y en el motor rápido (LuaJIT).
obj.load("figure", name, color, size [, line [, aspect]])
Genera una forma y reemplaza el búfer (centrada).
name : 円 / 四角形 / 三角形 / 五角形 / 六角形 / 星形
(también 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). 0 rellena la forma.
aspect : Distorsión -1.0 ~ 1.0 (opcional).
Ejemplo: obj.load("figure", "円", 0xff3366, 200)
obj.load("text", cadena)
Dibuja la cadena con la fuente, el tamaño y el color definidos
por obj.setfont y reemplaza el búfer (con DirectWrite).
Ejemplo: obj.setfont("Yu Gothic UI", 48); obj.load("text", "字幕")
obj.load("image", ruta)
Carga un archivo de imagen y reemplaza el búfer.
* Por seguridad se valida la cabecera inicial y solo se cargan
imágenes genuinas (PNG / JPEG / GIF / BMP / TIFF / WebP).
Ejemplo: obj.load("image", "C:\\img\\logo.png")
obj.load("movie", ruta [, tiempo])
Carga el fotograma en el tiempo indicado de un archivo de vídeo
y reemplaza el búfer (decodificado con Media Foundation).
tiempo : Segundos. Por defecto obj.time si se omite.
* Por seguridad se valida la cabecera inicial y solo se cargan
vídeos genuinos (MP4 / MOV / MKV / WebM / AVI / FLV / ASF).
Ejemplo: obj.load("movie", "C:\\mov\\clip.mp4", obj.time)
o obj.setfont(fuente [, tamaño [, estilo [, color]]])
Establece la fuente usada por obj.load("text").
estilo : Bits. 1=negrita, 2=cursiva, 3=negrita+cursiva.
color : 0xRRGGBB.
Ejemplo: obj.setfont("Meiryo", 64, 1, 0xffffff)
o obj.draw([ox, oy, oz [, zoom [, alpha [, aspect]]]])
Compone la imagen actual del objeto en el búfer de acumulación.
Llamarla varias veces dibuja copias superpuestas (estelas,
partículas, etc.).
ox, oy, oz : Desplazamiento desde el centro (por defecto 0).
zoom : 1.0 es tamaño original (por defecto 1.0).
alpha : 0.0 ~ 1.0 (por defecto 1.0).
aspect : -1.0 ~ 1.0 (por defecto 0).
* Una vez llamada, se suprime el dibujo estándar y se emite el
resultado compuesto.
o obj.drawpoly(x0,y0,z0, x1,y1,z1, x2,y2,z2, x3,y3,z3
[, u0,v0, u1,v1, u2,v2, u3,v3 [, alpha]])
Aplica la imagen del objeto como textura sobre un cuadrilátero dado por
4 vértices. El orden es superior-izq, superior-der, inferior-der,
inferior-izq. Si se omiten las UV se usa toda la imagen.
* Si solo se da un 13.º argumento (UV omitidas), se usa como alpha
(12 coordenadas + alpha).
* Se mapea con una transformación afín (exacta para paralelogramos,
aproximada para no paralelogramos).
o obj.copybuffer(destino, origen)
Copia una imagen entre búferes, seleccionado por el primer carácter.
"obj" : Búfer de imagen del objeto
"tmp" : Búfer temporal
"cache:nombre" : Caché con nombre (se conserva entre fotogramas)
Ejemplo: obj.copybuffer("tmp", "obj") -- guardar
obj.copybuffer("obj", "tmp") -- restaurar
* "frm" (búfer de fotograma / fondo) no puede obtenerse por la
estructura de YMM4.
o obj.getvalue(target)
Obtiene el valor actual de obj (igual que obj.x, obj.track0, etc.).
target : "x","y","z","ox","oy","rx","ry","rz","zoom","aspect",
"alpha","sx","sy","track0"~"track3","time","frame", etc.
Devuelve: un número (0 para un target desconocido).
o obj.setoption(nombre, valor) / obj.getoption(nombre)
Establece / obtiene una opción. Las opciones no admitidas se aceptan
para no detener el script (getoption devuelve el valor guardado, 0 si
no está establecido).
Opciones que afectan al dibujo actualmente:
"antialias" : 0 = vecino más cercano, en otro caso interpolación
lineal (obj.draw / obj.drawpoly).
o obj.pixeloption(nombre, valor)
Guarda como estado una opción para las operaciones de píxeles.
- ymm4 Table - - ymm4 Table -
@@ -445,17 +649,108 @@
obj.zoom = obj.zoom * (1 + obj.track0 / 100) 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, composición y carga
Se admiten el dibujo y composición con obj.draw / obj.drawpoly, las
operaciones de búfer con obj.copybuffer, la generación y carga con
obj.load("figure"/"text"/"image"/"movie"), obj.setfont, obj.effect,
obj.getvalue y obj.setoption / obj.getoption / obj.pixeloption.
Consulte "Tabla obj - Funciones" para más detalles.
o Mapa de compatibilidad AviUtl / AviUtl2 para obj.effect
obj.effect("nombre de efecto", "nombre de parámetro", valor, ...)
consulta primero el mapa de compatibilidad. Los efectos declarados como
nombres de AviUtl / AviUtl2 pasan por la conversión de
escala/desplazamiento declarada antes de llegar a las propiedades de
YMM4. Los nombres no declarados en el mapa se resuelven directamente por
el nombre de efecto o la palabra clave de YMM4, por lo que las llamadas
existentes siguen funcionando. El mapa se construye como la inversa de
la propia exportación de AviUtl de YMM4 (salida .exo), por lo que es
reversible de forma exacta. El motor de destino se selecciona con
--!aviutl (predeterminado) / --!aviutl2.
Los nombres de efecto declarados en el mapa y sus parámetros principales
son los siguientes.
ぼかし: 範囲, サイズ固定
境界ぼかし: 範囲
方向ブラー: 範囲, 角度, サイズ固定
放射ブラー: 範囲, X, Y, サイズを固定
閃光: 範囲, X, Y, サイズを固定
クロマキー: 色相範囲, 境界補正
クリッピング: 上, 下, 左, 右, 中心の位置を変更
斜めクリッピング: 中心X, 中心Y, 角度, ぼかし, 幅
領域拡張: 上, 下, 左, 右
座標: X, Y, Z
回転: X, Y, Z
リサイズ: 拡大率, X, Y, 補間なし
画像ループ: 横回数, 縦回数
極座標変換: 中心幅, 渦巻
グラデーション: 強さ, 中心X, 中心Y, 角度, 幅
単色化: 強さ, 輝度を保持する
縁取り: サイズ, ぼかし
反転: -
モザイク: サイズ
ディスプレイスメントマップ: ぼかし
動画ファイル合成: X, Y, 拡大率
色調補正: 明るさ, コントラスト, 色相, 輝度, 彩度
色ずれ: ずれ幅, 角度, 強さ
色調補正 y 色ずれ corresponden a efectos del complemento de la comunidad.
Lo siguiente queda fuera del alcance de esta capa. Los scripts que lo llamen no
se comportarán como se espera.
x Carga de módulos mediante require y acceso arbitrario a archivos como
io / dofile (la carga de imagen / vídeo con obj.load sí se admite con
validación de cabecera).
x obj.setanchor, scene.set / scene.get, etc.
- Funciones no admitidas / Limitaciones - - Funciones no admitidas / Limitaciones -
x obj.effect(), obj.draw(), obj.drawpoly(), obj.load(), etc. de AviUtl2 no son compatibles. x obj.rand1(), obj.mes(), obj.setanchor(), etc. de AviUtl2 no son compatibles.
x obj.rand(), obj.rand1(), obj.setfont(), obj.mes(), etc. de AviUtl2 no son compatibles.
x obj.setoption(), obj.getoption(), obj.getvalue(), obj.setanchor(), etc. de AviUtl2 no son compatibles.
x Las funciones como scene.set() y scene.get() de la tabla scene de AviUtl2 no son compatibles. x Las funciones como scene.set() y scene.get() de la tabla scene de AviUtl2 no son compatibles.
(Solo se pueden leer scene.width y scene.height) (Solo se pueden leer scene.width y scene.height)
x El acceso a archivos (require, dofile, io, etc.) no es compatible. x El acceso arbitrario a archivos desde scripts (require, dofile, io, etc.) no es compatible.
Solo obj.load("image"/"movie") carga archivos confirmados como medios genuinos
mediante validación de la cabecera inicial.
x Modificar obj.z se refleja en el renderizado (incluido en ReadBack), x Modificar obj.z se refleja en el renderizado (incluido en ReadBack),
pero el soporte de renderizado 3D es limitado. pero el soporte de renderizado 3D es limitado.
x Si se supera el tiempo de espera del script (5 segundos), la ejecución se termina forzosamente. x Si se supera el tiempo de espera del script (5 segundos), la ejecución se termina forzosamente.
Se debe tener cuidado en la implementación para evitar bucles infinitos. 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. x Las directivas de encabezado de AviUtl2 solo son compatibles parcialmente. Los valores
Solo Track0 ~ Track3 pueden usarse como parámetros. 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.
+296 -6
ファイルの表示
@@ -24,6 +24,60 @@
Menghilangkan panggilan ini saat tidak diperlukan akan mempercepat pemrosesan. Menghilangkan panggilan ini saat tidak diperlukan akan mempercepat pemrosesan.
- Mesin Eksekusi dan Akselerasi Otomatis -
Skrip yang berisi pemrosesan piksel (loop bersarang getpixel/setpixel)
dianalisis sintaksnya dan secara otomatis dialihkan ke mesin yang lebih
cepat. Skrip biasa (koordinat, rotasi, opasitas, dll.) tetap berjalan di
MoonSharp seperti sebelumnya, tanpa perubahan perilaku.
o Pengalihan otomatis (saat tidak ada direktif)
- Pemetaan per-piksel mandiri (lihat syarat di bawah)
-> kernel CPU (cepat, tepat)
- Operasi piksel lainnya -> Native (LuaJIT, hanya jika di-deploy)
- Tanpa operasi piksel -> MoonSharp
o Direktif mesin (komentar pada baris pertama skrip)
--!cpu : Kernel CPU. Dikompilasi saat runtime menjadi pohon
ekspresi dan dijalankan paralel di semua inti CPU
(identik dengan MoonSharp).
--!gpu : Kernel GPU. Dijalankan sebagai pixel shader Direct2D,
menghilangkan transfer GPU->CPU untuk kecepatan
tertinggi. Hasil dapat sedikit berbeda karena
presisi float32 (opsional/opt-in).
--!native : LuaJIT (proses terpisah). Cepat dan identik dengan
MoonSharp. Memerlukan folder native yang di-deploy.
--!moonsharp : Memaksa mesin MoonSharp klasik.
* Jika direktif tidak tersedia/tidak didukung, secara otomatis
jatuh ke mesin yang lebih rendah (output tidak pernah rusak).
o Sintaks yang memenuhi syarat kernel cepat (pemetaan per-piksel murni)
Hanya loop bersarang dengan bentuk berikut yang menjadi kernel.
for y = 0, obj.h - 1 do
for x = 0, obj.w - 1 do
local r, g, b, a = obj.getpixel(x, y)
obj.setpixel(x, y, r2, g2, b2 [, a2])
end
end
- Badan hanya boleh memakai aritmetika, math.*, perbandingan,
idiom ambang "cond and nilai1 or nilai2", dan variabel local.
- Hanya boleh mereferensikan piksel yang sedang diproses
(getpixel(x, y)) dan nilai seperti obj/scene/time.
- Apa pun yang memakai sampling tetangga (blur, dll.), penulisan
ke koordinat lain, getpixeldata, getobject, operasi
tabel/string, atau pernyataan if tidak diubah menjadi kernel dan
otomatis berjalan di mesin klasik.
Contoh (membuat figur putih menjadi merah):
--!gpu
for y = 0, obj.h - 1 do
for x = 0, obj.w - 1 do
local r, g, b, a = obj.getpixel(x, y)
obj.setpixel(x, y, r, g / 2, b / 2, a)
end
end
- Parameter - - Parameter -
Panel efek memiliki 4 trackbar berikut (mendukung animasi). Panel efek memiliki 4 trackbar berikut (mendukung animasi).
@@ -36,6 +90,38 @@
* Setiap trackbar mendukung slider animasi (dengan interpolasi). * Setiap trackbar mendukung slider animasi (dengan interpolasi).
* File .lua dapat diimpor/diekspor dari toolbar editor skrip. * File .lua dapat diimpor/diekspor dari toolbar editor skrip.
* Kotak centang (obj.check0 - obj.check3) dan warna (color) muncul di panel efek
secara otomatis saat skrip mereferensikannya (trackbar selalu ditampilkan).
Penggunaan umum ini tidak disertai deklarasi rentang/nilai default, jadi tangani
rentang nilai di dalam skrip. Header --track / --check / --color AviUtl tetap
berfungsi seperti sebelumnya.
Ada 4 slider numerik, direferensikan sebagai obj.slider0 hingga obj.slider3.
Nilainya berupa bilangan bulat dan tidak memuat desimal.
Slider0 : Slider bilangan bulat (Rentang: 1 ~ 10)
Slider1 : Slider bilangan bulat (Rentang: 0 ~ 100)
Slider2 : Slider bilangan bulat (Rentang: 0 ~ 1000)
Slider3 : Slider bilangan bulat (Rentang: -1000 ~ 1000)
Parameter string juga tersedia, direferensikan dengan nama berikut.
obj.text : String dari kolom input teks
obj.font : Nama font dari pemilih font
obj.dir : Path dari pemilih folder
obj.file_video : Path file video
obj.file_audio : Path file audio
obj.file_image : Path file gambar
obj.file_project : Path file proyek
obj.file_mp4 : Path file MP4
obj.file_exo : Path file EXO
obj.file_subtitle : Path file subtitle
obj.file_shader : Path file shader
* Slider dan parameter string muncul di panel efek secara otomatis saat skrip
mereferensikannya.
* Path file dapat diteruskan ke obj.load untuk memuat gambar atau video.
* Parameter ini tersedia pada mesin MoonSharp maupun native.
- Variabel Global - - Variabel Global -
@@ -157,6 +243,18 @@
obj.track2 : Nilai saat ini Track2 di panel efek [Hanya Baca] obj.track2 : Nilai saat ini Track2 di panel efek [Hanya Baca]
obj.track3 : Nilai saat ini Track3 di panel efek [Hanya Baca] obj.track3 : Nilai saat ini Track3 di panel efek [Hanya Baca]
o Slider
obj.slider0 : Nilai saat ini Slider0 di panel efek (bilangan bulat) [Hanya Baca]
obj.slider1 : Nilai saat ini Slider1 di panel efek (bilangan bulat) [Hanya Baca]
obj.slider2 : Nilai saat ini Slider2 di panel efek (bilangan bulat) [Hanya Baca]
obj.slider3 : Nilai saat ini Slider3 di panel efek (bilangan bulat) [Hanya Baca]
o Parameter string
obj.text : String dari kolom input teks [Hanya Baca]
obj.font : Nama font dari pemilih font [Hanya Baca]
obj.dir : Path dari pemilih folder [Hanya Baca]
obj.file_video ~ obj.file_shader : Path dari setiap pemilih file [Hanya Baca]
o Layer o Layer
obj.layer : Nomor layer tempat objek ditempatkan [Hanya Baca] obj.layer : Nomor layer tempat objek ditempatkan [Hanya Baca]
* Nilai yang sama dengan variabel global layer. * Nilai yang sama dengan variabel global layer.
@@ -303,6 +401,110 @@
tetapi dalam plugin ini perubahan melalui setpixel/set diterapkan secara otomatis, tetapi dalam plugin ini perubahan melalui setpixel/set diterapkan secara otomatis,
sehingga tidak perlu memanggil fungsi ini. 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. Target "figure",
"text", "image" (berkas gambar) dan "movie" (berkas video) didukung.
Setelah dimuat, obj.w / obj.h, dll. diperbarui ke ukuran yang
dihasilkan dan dapat dibaca oleh getpixel tepat setelah pemuatan.
Berfungsi pada mesin MoonSharp maupun mesin cepat (LuaJIT).
obj.load("figure", name, color, size [, line [, aspect]])
Menghasilkan bentuk dan mengganti buffer (dipusatkan).
name : 円 / 四角形 / 三角形 / 五角形 / 六角形 / 星形
(alias Inggris circle, rect, triangle, pentagon,
hexagon, star juga diterima).
color : Warna isi 0xRRGGBB.
size : Ukuran dasar dalam piksel.
line : Lebar garis tepi (opsional). 0 mengisi bentuk.
aspect : Distorsi -1.0 ~ 1.0 (opsional).
Contoh: obj.load("figure", "円", 0xff3366, 200)
obj.load("text", string)
Menggambar string dengan font, ukuran, dan warna yang diatur
oleh obj.setfont dan mengganti buffer (digambar dengan DirectWrite).
Contoh: obj.setfont("Yu Gothic UI", 48); obj.load("text", "字幕")
obj.load("image", path)
Memuat berkas gambar dan mengganti buffer.
* Demi keamanan, header awal divalidasi dan hanya gambar asli
(PNG / JPEG / GIF / BMP / TIFF / WebP) yang dimuat.
Contoh: obj.load("image", "C:\\img\\logo.png")
obj.load("movie", path [, time])
Memuat frame pada waktu tertentu dari berkas video dan mengganti
buffer (didekode dengan Media Foundation).
time : Detik. Default obj.time jika dihilangkan.
* Demi keamanan, header awal divalidasi dan hanya video asli
(MP4 / MOV / MKV / WebM / AVI / FLV / ASF) yang dimuat.
Contoh: obj.load("movie", "C:\\mov\\clip.mp4", obj.time)
o obj.setfont(font [, size [, style [, color]]])
Mengatur font yang digunakan oleh obj.load("text").
style : Flag bit. 1=tebal, 2=miring, 3=tebal+miring.
color : 0xRRGGBB.
Contoh: obj.setfont("Meiryo", 64, 1, 0xffffff)
o obj.draw([ox, oy, oz [, zoom [, alpha [, aspect]]]])
Mengomposit gambar objek saat ini ke buffer akumulasi.
Memanggilnya beberapa kali menggambar salinan bertumpuk (afterimage,
partikel, dll.).
ox, oy, oz : Offset dari pusat (default 0).
zoom : 1.0 adalah ukuran asli (default 1.0).
alpha : 0.0 ~ 1.0 (default 1.0).
aspect : -1.0 ~ 1.0 (default 0).
* Setelah dipanggil, penggambaran standar ditekan dan hasil komposit
dikeluarkan.
o obj.drawpoly(x0,y0,z0, x1,y1,z1, x2,y2,z2, x3,y3,z3
[, u0,v0, u1,v1, u2,v2, u3,v3 [, alpha]])
Memetakan gambar objek sebagai tekstur ke quad dari 4 verteks.
Urutan verteks: kiri-atas, kanan-atas, kanan-bawah, kiri-bawah.
Jika UV dihilangkan, seluruh gambar digunakan.
* Jika hanya argumen ke-13 yang diberikan (UV dihilangkan), nilainya
dipakai sebagai alpha (12 koordinat + alpha).
* Dipetakan dengan transformasi afin (tepat untuk jajaran genjang,
perkiraan untuk non-jajaran genjang).
o obj.copybuffer(tujuan, sumber)
Menyalin gambar antar buffer, dipilih oleh karakter pertama.
"obj" : Buffer gambar objek
"tmp" : Buffer sementara
"cache:nama" : Cache bernama (dipertahankan antar frame)
Contoh: obj.copybuffer("tmp", "obj") -- simpan
obj.copybuffer("obj", "tmp") -- pulihkan
* "frm" (buffer frame / latar) tidak dapat diperoleh karena struktur YMM4.
o obj.getvalue(target)
Mengambil nilai saat ini dari obj (sama dengan obj.x, obj.track0, dll.).
target : "x","y","z","ox","oy","rx","ry","rz","zoom","aspect",
"alpha","sx","sy","track0"~"track3","time","frame", dll.
Mengembalikan: sebuah angka (0 untuk target yang tidak dikenal).
o obj.setoption(name, value) / obj.getoption(name)
Mengatur / mengambil opsi. Opsi yang tidak didukung tetap diterima
sehingga tidak menghentikan skrip (getoption mengembalikan nilai
tersimpan, 0 jika belum diatur).
Opsi yang saat ini memengaruhi penggambaran:
"antialias" : 0 = tetangga terdekat, selain itu interpolasi linear
(obj.draw / obj.drawpoly).
o obj.pixeloption(name, value)
Menyimpan opsi untuk operasi piksel sebagai status.
- ymm4 Table - - ymm4 Table -
@@ -443,17 +645,105 @@
obj.zoom = obj.zoom * (1 + obj.track0 / 100) 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, komposisi, dan pemuatan
Penggambaran dan komposisi dengan obj.draw / obj.drawpoly, operasi
buffer dengan obj.copybuffer, pembuatan dan pemuatan dengan
obj.load("figure"/"text"/"image"/"movie"), obj.setfont, obj.effect,
obj.getvalue, serta obj.setoption / obj.getoption / obj.pixeloption
didukung. Lihat "Tabel obj - Fungsi" untuk detailnya.
o Peta kompatibilitas AviUtl / AviUtl2 untuk obj.effect
obj.effect("nama efek", "nama parameter", nilai, ...) pertama-tama
merujuk peta kompatibilitas. Efek yang dideklarasikan sebagai nama
AviUtl / AviUtl2 melewati konversi skala/offset yang dideklarasikan
sebelum mencapai properti YMM4. Nama yang tidak dideklarasikan dalam peta
diselesaikan langsung melalui nama efek atau kata kunci YMM4, sehingga
pemanggilan yang sudah ada tetap berfungsi. Peta ini dibuat sebagai kebalikan dari ekspor AviUtl milik YMM4
sendiri (keluaran .exo), sehingga konsisten secara bolak-balik. Mesin
target dipilih dengan --!aviutl (bawaan) / --!aviutl2.
Nama efek yang dideklarasikan dalam peta beserta parameter utamanya
adalah sebagai berikut.
ぼかし: 範囲, サイズ固定
境界ぼかし: 範囲
方向ブラー: 範囲, 角度, サイズ固定
放射ブラー: 範囲, X, Y, サイズを固定
閃光: 範囲, X, Y, サイズを固定
クロマキー: 色相範囲, 境界補正
クリッピング: 上, 下, 左, 右, 中心の位置を変更
斜めクリッピング: 中心X, 中心Y, 角度, ぼかし, 幅
領域拡張: 上, 下, 左, 右
座標: X, Y, Z
回転: X, Y, Z
リサイズ: 拡大率, X, Y, 補間なし
画像ループ: 横回数, 縦回数
極座標変換: 中心幅, 渦巻
グラデーション: 強さ, 中心X, 中心Y, 角度, 幅
単色化: 強さ, 輝度を保持する
縁取り: サイズ, ぼかし
反転: -
モザイク: サイズ
ディスプレイスメントマップ: ぼかし
動画ファイル合成: X, Y, 拡大率
色調補正: 明るさ, コントラスト, 色相, 輝度, 彩度
色ずれ: ずれ幅, 角度, 強さ
色調補正 dan 色ずれ sesuai dengan efek plugin komunitas.
Berikut ini berada di luar cakupan lapisan ini. Skrip yang memanggilnya tidak
akan berperilaku seperti yang diharapkan.
x Pemuatan modul melalui require, dan akses berkas sembarang seperti
io / dofile (pemuatan gambar / video via obj.load didukung dengan
validasi header).
x obj.setanchor, scene.set / scene.get, dll.
- Fitur yang Tidak Didukung / Batasan - - Fitur yang Tidak Didukung / Batasan -
x obj.effect(), obj.draw(), obj.drawpoly(), obj.load(), dll. dari AviUtl2 tidak didukung. x obj.rand1(), obj.mes(), obj.setanchor(), dll. dari AviUtl2 tidak didukung.
x obj.rand(), obj.rand1(), obj.setfont(), obj.mes(), dll. dari AviUtl2 tidak didukung.
x obj.setoption(), obj.getoption(), obj.getvalue(), obj.setanchor(), dll. dari AviUtl2 tidak didukung.
x Fungsi seperti scene.set() dan scene.get() dalam tabel scene AviUtl2 tidak didukung. x Fungsi seperti scene.set() dan scene.get() dalam tabel scene AviUtl2 tidak didukung.
(Hanya scene.width dan scene.height yang dapat dibaca) (Hanya scene.width dan scene.height yang dapat dibaca)
x Akses file (require, dofile, io, dll.) tidak didukung. x Akses berkas sembarang dari skrip (require, dofile, io, dll.) tidak didukung.
Hanya obj.load("image"/"movie") yang memuat berkas yang dipastikan sebagai
media asli melalui validasi header awal.
x Memodifikasi obj.z tercermin dalam render (termasuk dalam ReadBack), x Memodifikasi obj.z tercermin dalam render (termasuk dalam ReadBack),
tetapi dukungan render 3D terbatas. tetapi dukungan render 3D terbatas.
x Jika batas waktu skrip (5 detik) terlampaui, eksekusi dihentikan paksa. x Jika batas waktu skrip (5 detik) terlampaui, eksekusi dihentikan paksa.
Perhatian harus diberikan dalam implementasi untuk mencegah loop tak terbatas. Perhatian harus diberikan dalam implementasi untuk mencegah loop tak terbatas.
x Direktif header AviUtl2 seperti --track@ dan --check@ tidak didukung. x Direktif header AviUtl2 hanya didukung sebagian. Nilai default dari
Hanya Track0 ~ Track3 yang dapat digunakan sebagai parameter. --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.
130ファイル中100ファイルを読み込みました。 変更されたファイルが多すぎるため、それ以降のファイルは表示していません。 さらに表示