コミットを比較

..
475 コミット
作成者 SHA1 メッセージ 日付
routersys 8428057eb4 バージョンをv1.16.0へ更新
リリース / build-and-release (workflow_dispatch) Actions がタグ v1.16.0 のコミットから作成しました
2026-07-04 15:21:03 +09:00
routersys 1133daf764 READMEの構文名称をnil条件演算子と範囲判定へ改称 2026-07-04 15:01:49 +09:00
routersys b09070e8df サイトの構文名称をnil条件演算子と範囲判定へ改称 2026-07-04 15:01:46 +09:00
routersys cde0b8f498 全言語ドキュメントの構文名称をnil条件演算子と範囲判定へ改称 2026-07-04 15:01:45 +09:00
routersys 916dd278b2 READMEの構文拡張に新構文を追加 2026-07-04 14:53:00 +09:00
routersys d6d0792207 サイトの構文拡張ページに新構文を追加 2026-07-04 14:52:56 +09:00
routersys a7bae506a7 全言語ドキュメントに新構文の説明を追加 2026-07-04 14:52:55 +09:00
routersys d05906de7b 構文糖衣の単体テストを追加 2026-07-04 14:42:59 +09:00
routersys a8300041e3 範囲メンバーシップの構文糖衣を追加 2026-07-04 14:42:53 +09:00
routersys 8bd0d2bc0e 安全ナビゲーションの構文糖衣を追加 2026-07-04 14:42:47 +09:00
routersys cf5f4acf72 三項演算子の構文糖衣を追加 2026-07-04 14:42:41 +09:00
routersys 0d6709d518 パイプ演算子の構文糖衣を追加 2026-07-04 14:42:34 +09:00
routersys 12bd10164b ラムダ式の構文糖衣を追加 2026-07-04 14:42:28 +09:00
routersys 6287e74fe5 補間文字列の構文糖衣を追加 2026-07-04 14:42:27 +09:00
routersys 8956b7c8d5 範囲構文の解析を共通ヘルパーへ抽出 2026-07-04 14:42:13 +09:00
routersys 60c6a37f89 字句解析器に補間文字列とラムダ・パイプ演算子を追加 2026-07-04 14:42:05 +09:00
routersys 9a9c2ec405 バージョンをv1.15.0へ更新
リリース / build-and-release (workflow_dispatch) Actions がタグ v1.15.0 のコミットから作成しました
2026-07-04 12:29:04 +09:00
routersys 103b612082 シェーダー領域の整列と容量判定を補正 2026-07-04 12:08:09 +09:00
routersys 9e1da1839e READMEのピクセルシェーダー記述を更新 2026-07-04 12:06:27 +09:00
routersys c19e12aa87 サイトのピクセルシェーダー節を更新 2026-07-04 12:05:45 +09:00
routersys ed4c38772f 各言語ドキュメントのpixelshader節を更新 2026-07-04 12:04:44 +09:00
routersys d31fd77aee pixelshaderの自動振分けをnativeへ変更 2026-07-04 11:59:12 +09:00
routersys eb0199131d workerへobj.pixelshaderと仮想フレームバッファを実装 2026-07-04 11:58:07 +09:00
routersys 36935bdf1d ネイティブワーカーへシェーダー実行呼出を実装 2026-07-04 11:52:59 +09:00
routersys 7d9a9f1cb8 ピクセルシェーダー呼出デリゲートを追加 2026-07-04 11:49:48 +09:00
routersys 3ce2483062 ネイティブ手順へシェーダー交換領域を追加 2026-07-04 11:49:12 +09:00
routersys fc8a07f935 プロセッサへ合成器配線とフレームバッファ初期化を追加 2026-07-04 11:48:25 +09:00
routersys d1279c25fa フレームバッファ出力後にobj寸法を更新 2026-07-04 11:47:37 +09:00
routersys 048c6d6707 コンテキストへ仮想フレームバッファを追加 2026-07-04 11:46:49 +09:00
routersys 3a29862423 数値合成指定のテストを追加 2026-07-04 11:44:32 +09:00
routersys 8c69864456 pixelshaderの合成指定を構造体化し数値合成へ対応 2026-07-04 11:43:43 +09:00
routersys 8a7b328db4 ピクセルシェーダー合成モード列挙を追加 2026-07-04 11:43:41 +09:00
routersys 8517bf5f50 ハードウェア合成へ合成モード適用を追加 2026-07-04 11:40:40 +09:00
routersys b928101e3e tempbuffer合成の合成モードを通常へ固定 2026-07-04 11:39:13 +09:00
routersys 7fb671e8c6 変換がシェーダー定義を保持するテストを追加 2026-07-04 11:16:01 +09:00
routersys 20ff47edce READMEへピクセルシェーダー対応を追記 2026-07-04 11:14:38 +09:00
routersys 8f9b7c725f サイトへピクセルシェーダーの節を追加 2026-07-04 11:14:36 +09:00
routersys 499f8ba078 各言語ドキュメントへobj.pixelshaderを追加 2026-07-04 11:12:51 +09:00
routersys 66f2d398b7 nativeでのpixelshaderエラーのテストを追加 2026-07-04 11:07:19 +09:00
routersys 935bca6fbb native実行時のpixelshaderへ明示エラーを追加 2026-07-04 11:07:17 +09:00
routersys 4c7ef12361 プロセッサへシェーダー実行器を配線 2026-07-04 11:02:04 +09:00
routersys 65e7864221 D3D11ピクセルシェーダー実行器を追加 2026-07-04 11:02:02 +09:00
routersys 25430c4dcf obj.pixelshaderのテストを追加 2026-07-04 11:01:59 +09:00
routersys f0234d21e4 pixelshader使用時はMoonSharpへ自動転送 2026-07-04 11:01:57 +09:00
routersys bfe23707f0 obj.pixelshaderをobjテーブルへ追加 2026-07-04 11:01:54 +09:00
routersys e74af227d8 コンテキストへシェーダーバッファ操作を追加 2026-07-04 11:01:51 +09:00
routersys 2b5901379f ピクセルシェーダー実行契約を追加 2026-07-04 11:01:50 +09:00
routersys deb94b3f29 シェーダー定義解析のテストを追加 2026-07-04 11:01:46 +09:00
routersys 74a65b7a8b シェーダー定義の解析器を追加 2026-07-04 11:01:44 +09:00
routersys a4cc0f3220 バージョンをv1.14.0へ更新
リリース / build-and-release (workflow_dispatch) Actions がタグ v1.14.0 のコミットから作成しました
2026-07-03 23:20:02 +09:00
routersys 86f889cbd2 変更行マップのテストを追加 2026-07-03 23:07:25 +09:00
routersys c2f48230f3 拡張構文でのパラメータ検出テストを追加 2026-07-03 23:07:21 +09:00
routersys 4153956b37 変更行の診断を行単位へ補正 2026-07-03 23:07:18 +09:00
routersys 3763db1cfc 変換に変更行情報を伝播 2026-07-03 23:07:15 +09:00
routersys 9bcab1ae28 変更行を返す書き換えAPIを追加 2026-07-03 23:07:11 +09:00
routersys 6e13a4d1c2 書き換えた行番号を記録 2026-07-03 23:07:09 +09:00
routersys 8dc87d63be パラメータ検出を汎用字句解析器へ移行 2026-07-03 23:07:08 +09:00
routersys 0afb7afc21 READMEに構文拡張の節を新設 2026-07-03 21:50:22 +09:00
routersys 2769a29808 サイトに構文拡張ページを追加 2026-07-03 21:48:25 +09:00
routersys 1f21b4c49c 各言語ドキュメントの構文拡張を拡充 2026-07-03 21:45:59 +09:00
routersys cafc6d6e48 構文拡張の攻撃的テストを追加 2026-07-03 21:32:57 +09:00
routersys 49a2ce29b2 変換をトークン規則方式へ刷新 2026-07-03 21:32:46 +09:00
routersys d728c8d056 生成器をアナライザ参照に追加 2026-07-03 21:32:38 +09:00
routersys b6eac20941 構文規則レジストリ生成器を追加 2026-07-03 21:32:27 +09:00
routersys d8589007b3 範囲for<a..b>規則を実装 2026-07-03 21:32:20 +09:00
routersys 85596f76f7 nil合体演算子??規則を実装 2026-07-03 21:32:10 +09:00
routersys 018999ff5e 複合代入/nil合体代入/++規則を実装 2026-07-03 21:32:00 +09:00
routersys c5da497bb3 論理演算子!/&&/||規則を実装 2026-07-03 21:31:52 +09:00
routersys f46cb08f85 is/is not/!=規則を実装 2026-07-03 21:31:46 +09:00
routersys b0a5293b89 書き換え文脈とオペランド抽出を実装 2026-07-03 21:31:24 +09:00
routersys 67a1b4fa31 構文規則インターフェースを定義 2026-07-03 21:31:14 +09:00
routersys 2d0fb2c47a 構文規則属性を定義 2026-07-03 21:31:03 +09:00
routersys 45d5164afa 式境界判定ヘルパを追加 2026-07-03 21:30:55 +09:00
routersys ba20fc8187 Lua予約語判定を追加 2026-07-03 21:30:44 +09:00
routersys 669b24c2b3 可逆字句解析器を実装 2026-07-03 21:30:35 +09:00
routersys 91a3e3f762 構文トークン型を定義 2026-07-03 21:30:26 +09:00
routersys 722ae62326 構文トークン種別を定義 2026-07-03 21:30:19 +09:00
routersys fee1f293c7 READMEにis not構文を追記 2026-07-03 19:44:03 +09:00
routersys b6764fe637 サイトにis not構文の説明を追加 2026-07-03 19:43:11 +09:00
routersys 01e368207d 各言語ドキュメントにis not構文を追記 2026-07-03 19:42:35 +09:00
routersys 29ea2ea45c is not 構文のテストを追加 2026-07-03 19:40:28 +09:00
routersys 1d60d8b245 変換パイプラインへ構文拡張を組み込む 2026-07-03 19:40:23 +09:00
routersys 8f2aafdffd is not 構文の書き換えを実装 2026-07-03 19:40:19 +09:00
routersys f26816343f バージョンをv1.13.4へ更新
リリース / build-and-release (workflow_dispatch) Actions がタグ v1.13.4 のコミットから作成しました
2026-07-03 19:26:11 +09:00
routersys 0cab8972e0 READMEにobj.getinfoを追記 2026-07-03 19:18:26 +09:00
routersys f2aa668cf6 サイトにobj.getinfoの説明を追加 2026-07-03 19:17:45 +09:00
routersys ed27979f64 各言語ドキュメントにobj.getinfoを追記 2026-07-03 19:15:46 +09:00
routersys 7b958ea171 obj.getinfoの実行テストを追加 2026-07-03 19:11:12 +09:00
routersys 332dab3889 補完目録にobj.getinfoを追加 2026-07-03 19:11:05 +09:00
routersys 75d457a7ab プラグインからgetinfoへ情報を供給 2026-07-03 19:10:58 +09:00
routersys 50e1801878 MoonSharpにobj.getinfoを実装 2026-07-03 19:10:52 +09:00
routersys 793d010bdb ネイティブにobj.getinfoを実装 2026-07-03 19:10:45 +09:00
routersys b564b0b185 script_pathをワーカー起動引数へ渡す 2026-07-03 19:10:39 +09:00
routersys 6d83fe93d8 getinfo情報をネイティブフィールドへ転送 2026-07-03 19:10:32 +09:00
routersys db9c3747ea getinfo用のネイティブフィールド枠を追加 2026-07-03 19:10:27 +09:00
routersys 7d887afe5a getinfo用の環境情報フィールドを追加 2026-07-03 19:10:21 +09:00
routersys ac34830367 ViewModelをフレームワーク非依存へ整理 2026-07-03 18:29:48 +09:00
routersys 8ed188d0e2 ツールバーをView/ViewModelへMVVM分離 2026-07-03 18:10:21 +09:00
routersys 9c55c08caf エフェクト本体をEffectsフォルダへ整理 2026-07-03 18:02:53 +09:00
routersys 42868023f3 メディア/シーン解決をEngine・Sceneへ整理 2026-07-03 18:02:49 +09:00
routersys e146b36fa0 描画合成をDrawingフォルダへ整理 2026-07-03 18:02:45 +09:00
routersys 5fac495848 エディタ関連をEditorフォルダへ整理 2026-07-03 18:02:42 +09:00
routersys 4fd519249f Texts をLocalizationフォルダへ集約 2026-07-03 17:59:54 +09:00
routersys 1b26df959f デコーダを LuaScript.Media プロジェクトへ分離 2026-07-03 17:25:43 +09:00
routersys 3cd67212a1 Compat を1ファイル1クラス化しフォルダへ整理 2026-07-03 17:11:46 +09:00
routersys 46692dfe95 Compat の重複パーサを ScriptParserHelper へ集約 2026-07-03 17:08:16 +09:00
routersys e8d9cef129 KFunc メタデータを単一カタログへ集約 2026-07-03 16:59:34 +09:00
routersys 18036cd74e Kernel を1ファイル1クラス化しフォルダへ整理 2026-07-03 16:58:14 +09:00
routersys c8f857d2b4 MoonSharpBit32 を Compat プロジェクトへ移動 2026-07-03 16:31:01 +09:00
routersys ac7f797566 Scene 値型を1ファイル1クラス化 2026-07-03 16:18:13 +09:00
routersys 8beae1a277 Diagnostics のトップレベル型を1ファイル1クラス化 2026-07-03 16:18:04 +09:00
routersys 6eb4d7c9af Anchor のトップレベル型を1ファイル1クラス化 2026-07-03 16:17:55 +09:00
routersys a843f460de Api のトップレベル型を1ファイル1クラス化 2026-07-03 16:17:45 +09:00
routersys 27f04c7560 テーブル登録を LuaScope で汎用化 2026-07-03 16:17:35 +09:00
routersys 43c0ce88b3 エンジンのテーブルライフサイクル特性化テストを追加 2026-07-03 16:17:27 +09:00
routersys 00f0d991c1 Runtime のファイルをドメイン別フォルダへ整理 2026-07-03 14:13:33 +09:00
routersys 784d294ca6 補完カタログの回帰テストを追加 2026-07-03 14:05:16 +09:00
routersys 260d427bcf 補完ストラテジをカタログ消費へ置換 2026-07-03 14:05:14 +09:00
routersys b62f4a3a7d 登録と毎フレーム変数を属性ベース生成へ移行 2026-07-03 14:05:12 +09:00
routersys 79a408cafd 宣言的 API カタログ基盤を追加し生成器を接続 2026-07-03 14:05:11 +09:00
routersys 807df7df8a Lua API ソースジェネレータを新設 2026-07-03 14:05:10 +09:00
routersys 0c5e3066c1 リリース配布物へ分離アセンブリを追加 2026-07-03 11:50:45 +09:00
routersys fbaff95503 テストをリンク方式から ProjectReference へ移行 2026-07-03 11:50:43 +09:00
routersys 8dec38a911 ソリューションへ分離プロジェクトを追加 2026-07-03 11:50:42 +09:00
routersys 902d729c19 プラグイン本体を分離プロジェクト参照へ移行 2026-07-03 11:50:40 +09:00
routersys 79f8ff8839 LuaScript.Runtime へ実行コアを分離し依存を逆転 2026-07-03 11:50:23 +09:00
routersys 9a630ecb5a LuaScript.Compat を新設し AviUtl 互換層を移設 2026-07-03 11:50:08 +09:00
routersys d9e6132a1f LuaScript.Kernel を新設しカーネルコンパイラ群を移設 2026-07-03 11:49:33 +09:00
routersys e685e7aa40 バージョンをv1.13.3へ更新
リリース / build-and-release (workflow_dispatch) Actions がタグ v1.13.3 のコミットから作成しました
2026-07-03 08:57:03 +09:00
routersys bf49fe9984 入力補完へ obj テーブルの関数 12 件を追加 2026-07-03 08:57:03 +09:00
routersys c05a1479f9 ワーカーの setfont 引数変換の等価性テストを追加 2026-07-03 08:57:02 +09:00
routersys 80ddb663b0 AviUtlFontState の変換規則と床剰余セマンティクスのテストを追加 2026-07-03 08:57:02 +09:00
routersys 2f1bbc3828 setfont へ型検査と数値変換を導入し ffi 変換エラーを排除 2026-07-03 08:57:02 +09:00
routersys e911f6e83f フォント状態を AviUtlFontState への委譲へ変更 2026-07-03 08:48:05 +09:00
routersys 6162ce5c19 setfont の引数解釈を AviUtlFontState へ抽出し床剰余でスタイルを判定 2026-07-03 08:47:57 +09:00
routersys 59dcb82b49 バージョンをv1.13.2へ更新
リリース / build-and-release (workflow_dispatch) Actions がタグ v1.13.2 のコミットから作成しました
2026-07-03 08:31:31 +09:00
routersys d37726cdf6 scene テーブルのテストをスコープ付きセッションへ追随 2026-07-03 08:31:16 +09:00
routersys 0c09cf4a51 セッションのテストへスコープ分離と後戻りシークとレイヤー優先の検証を追加 2026-07-03 08:30:56 +09:00
routersys 0d4809924d ストアのテストをランダムシークの決定論とレイヤー競合と履歴上限の検証へ書き換え 2026-07-03 08:30:49 +09:00
routersys 1e97e7d8fe 描画デバイスをスコープとして引き当てキャッシュ検証を履歴照合へ変更 2026-07-03 08:30:38 +09:00
routersys 06cfefe1b4 シーン共有値のスコープを保持し未使用の SceneValuesWritten を削除 2026-07-03 08:30:31 +09:00
routersys 37b1371f57 セッションへスコープとレイヤーを導入し発行を履歴への即時確定へ変更 2026-07-03 08:30:24 +09:00
routersys 9db756c974 シーン共有値ストアをフレーム索引付きの履歴方式へ再設計 2026-07-03 08:30:15 +09:00
routersys 43f3161ebb バージョンをv1.13.1へ更新
リリース / build-and-release (workflow_dispatch) Actions がタグ v1.13.1 のコミットから作成しました
2026-07-03 08:04:35 +09:00
routersys 4b3b74edae README の scene.set / scene.get の説明を新しいセマンティクスへ更新 2026-07-03 07:54:18 +09:00
routersys 5129ece749 全言語ドキュメントへ scene 共有値の可視性と出力時リセットを追記 2026-07-03 07:53:32 +09:00
routersys 24ef4135cf サイトへ scene.set / scene.get の可視性の規則と説明、制限を追記 2026-07-03 07:53:18 +09:00
routersys 044fdbf1eb ワーカーのシーン共有値テストへ IPC 回数と最大長往復の検証を追加 2026-07-03 07:52:50 +09:00
routersys 9e1ad6c133 scene テーブルのテストをセッション経由の検証へ書き換え 2026-07-03 07:52:40 +09:00
routersys 6d8def9f08 SceneValueSession の可視性とトランザクション性のテストを追加 2026-07-03 07:52:32 +09:00
routersys 7a9f1ff6e8 ストアのテストを世代・出力リセット・容量上限の検証へ書き換え 2026-07-03 07:52:18 +09:00
routersys 82db144b86 scene.set / scene.get へ実行内キャッシュと UTF-8 境界の切り詰めを追加 2026-07-03 07:52:08 +09:00
routersys d3fb73ed94 コールバックタグ領域を8192バイトへ拡張 2026-07-03 07:52:00 +09:00
routersys 7dd777fbc6 シーン共有値の発行を実行成功時のみに限定しキャッシュ検証を世代対応へ変更 2026-07-03 07:51:52 +09:00
routersys aa17df08d8 シーン共有値のアクセスを SceneValueSession への委譲へ変更 2026-07-03 07:51:42 +09:00
routersys e5c4485f16 アイテム単位の書き込みバッファと読み取りメモ化を担う SceneValueSession を追加 2026-07-03 07:51:33 +09:00
routersys 9b901f91b6 シーン共有値ストアを世代スナップショット方式へ再設計 2026-07-03 07:51:26 +09:00
routersys 2b24a407e6 バージョンをv1.13.0へ更新
リリース / build-and-release (workflow_dispatch) Actions がタグ v1.13.0 のコミットから作成しました
2026-07-02 23:33:31 +09:00
routersys 150b4818d4 README へ scene.set / scene.get と AviUtl 互換グローバル関数を追記 2026-07-02 23:20:29 +09:00
routersys 34b7d60ca6 サイトへ scene.set / scene.get とグローバル関数を追記 2026-07-02 23:18:24 +09:00
routersys 7dc6083fd7 全言語ドキュメントへ scene.set / scene.get とグローバル関数を追記 2026-07-02 23:17:26 +09:00
routersys 245fb9c323 テストレーンへグローバル関数登録と time_ratio を追加 2026-07-02 23:16:52 +09:00
routersys 42c3bc4f4b ネイティブワーカーの scene.set / scene.get 往復テストを追加 2026-07-02 23:16:20 +09:00
routersys d273f99593 グローバル関数のエンジン間等価性テストを追加 2026-07-02 23:15:48 +09:00
routersys e1763e0c81 scene.set / scene.get 登録のテストを追加 2026-07-02 23:14:35 +09:00
routersys 7221ce3aca シーン共有値のテストを追加 2026-07-02 23:14:08 +09:00
routersys 5f3ad96ea2 ネイティブワーカーへ scene.set / scene.get のブリッジとグローバル関数の公開を追加 2026-07-02 23:13:47 +09:00
routersys 4e0bf831c5 ネイティブ shim へ RGB / HSV などのグローバル関数と debug_print を追加 2026-07-02 23:13:27 +09:00
routersys 0fedfd5804 補完候補へ scene.set / scene.get とグローバル関数を追加 2026-07-02 23:13:08 +09:00
routersys f11225e2a1 LuaJIT ワーカーへ scene.set / scene.get のコールバック処理を追加 2026-07-02 23:12:36 +09:00
routersys 92e8c43160 ネイティブ経路へ scene 取得・設定のコールバック種別を追加 2026-07-02 23:12:23 +09:00
routersys 5fb9eae7a0 シーン共有値の変化を検知してフレームキャッシュを無効化 2026-07-02 23:12:00 +09:00
routersys f109232cae MoonSharp へ scene.set / scene.get と AviUtl 互換グローバル関数を登録 2026-07-02 23:11:44 +09:00
routersys 1596a048cd スクリプトコンテキストへシーン共有値の取得・書き込みと変化追跡を追加 2026-07-02 23:11:22 +09:00
routersys 0b0c795d7a debug_print 向けの OutputDebugString 出力を追加 2026-07-02 23:11:05 +09:00
routersys 2be3c3d28b AviUtl 互換グローバル関数と debug_print の登録処理を追加 2026-07-02 23:10:46 +09:00
routersys 3f9e4ebca4 AviUtl 互換の RGB / HSV / OR / AND / XOR / SHIFT を実装 2026-07-02 23:10:26 +09:00
routersys 03042b17e7 scene テーブルへ scene.set / scene.get の登録処理を追加 2026-07-02 23:10:10 +09:00
routersys 5e6d74dfee シーン単位で値を共有するストア SceneSharedValues を追加 2026-07-02 23:09:49 +09:00
routersys 40d68416c2 サイトへGPUカーネルの自動選択とSIMD判定記述を追加 2026-07-02 20:47:41 +09:00
routersys de6472c34b バージョンをv1.12.0へ更新
リリース / build-and-release (workflow_dispatch) Actions がタグ v1.12.0 のコミットから作成しました
2026-07-02 19:54:36 +09:00
routersys 55c8bffb70 SIMD経路の採用を初回フレームの実測で自動判定 2026-07-02 19:52:59 +09:00
routersys 8ca66bceb8 ネイティブ画素転送をD2DステージングとMMFの直結へ変更 2026-07-02 19:28:01 +09:00
routersys 865f5117ea カーネル抽出の検査漏れとfmodの剰余実装を修正 2026-07-02 19:04:05 +09:00
routersys b30f7a818b drawリングの読み出し件数を容量へクランプ 2026-07-02 19:03:41 +09:00
routersys 95786a1f0a getpixeldataの遅延書き込みをフレーム置換時に破棄 2026-07-02 19:03:23 +09:00
routersys cc07e2a83d CPUカーネルにVector256のSIMD経路を追加 2026-07-02 18:36:43 +09:00
routersys 08e5e432b7 getpixeldata添字ループをカーネル抽出へ対応 2026-07-02 17:48:59 +09:00
routersys 1e9b039cef draw/drawpolyをMMFリングバッファでバッチ化 2026-07-02 17:26:12 +09:00
routersys bad39fe0db getpixeldataをストレートFFI配列の遅延反映へ変更 2026-07-02 14:39:22 +09:00
routersys a5567a804d copybufferの複製をバッファ再利用へ変更 2026-07-02 14:20:01 +09:00
routersys a9cb4a9cda RenderKeyのスクリプト比較を参照バージョンへ変更 2026-07-02 14:17:57 +09:00
routersys 9e9b5277af スクリプト本文をバージョンスタンプで変更時のみ転送 2026-07-02 14:16:09 +09:00
routersys 1d8705c7ee バージョンをv1.11.4へ更新
リリース / build-and-release (workflow_dispatch) Actions がタグ v1.11.4 のコミットから作成しました
2026-07-02 13:58:38 +09:00
routersys 14683c7909 HlslKernelEmitterの座標原点と出力の切り捨てを検証するテストを追加 2026-07-02 13:58:23 +09:00
routersys 42b123ebc3 検証に通ったGpuKernelのみ採用しカーネルの自動GPU選択を有効化 2026-07-02 13:58:14 +09:00
routersys b0114abdb7 GpuKernelへCpuKernelとの出力一致を実機で確かめるVerifyを追加 2026-07-02 13:58:06 +09:00
routersys c21de5b3eb GpuKernelの座標原点と出力の丸めをCpuKernelへ合わせて修正 2026-07-02 13:57:49 +09:00
routersys bd891d9a1e バージョンをv1.11.3へ更新
リリース / build-and-release (workflow_dispatch) Actions がタグ v1.11.3 のコミットから作成しました
2026-07-02 13:19:45 +09:00
routersys d2bef10085 SoftwareCompositorのテストをTryComposeとInstanceへ更新 2026-07-02 13:19:30 +09:00
routersys 3eafcdc70e FallbackCompositorへ引き受け拒否経路のテストを追加しTryComposeへ更新 2026-07-02 13:19:10 +09:00
routersys 6f26fc95fa SynchronizedCompositorのユニットテストを追加 2026-07-02 13:18:55 +09:00
routersys 88ce786d05 GpuKernelで効果のOutputを生成時に一度だけ取得してキャッシュ 2026-07-02 13:18:39 +09:00
routersys d69ae5f06e PixelBufferManagerで変換のOutputをキャッシュし取得したTargetを破棄 2026-07-02 13:18:29 +09:00
routersys d42d8a6764 DrawCompositorでplacementのOutputをキャッシュし取得したTargetを破棄 2026-07-02 13:18:17 +09:00
routersys 8f9ace2dc8 HardwareCompositorをSynchronizedCompositorで包みピクセル読み出しと直列化 2026-07-02 13:18:07 +09:00
routersys c416e955a4 tempbuffer合成をSoftwareCompositor.InstanceのTryCompose呼び出しへ変更 2026-07-02 13:17:57 +09:00
routersys 7362e70ab8 GPU合成をセマフォで直列化するSynchronizedCompositorを追加 2026-07-02 13:17:46 +09:00
routersys c9741836a5 HardwareCompositorへ寸法上限8192を設け取得したTargetを破棄 2026-07-02 13:17:35 +09:00
routersys afd57d758d FallbackCompositorで引き受け拒否を降格扱いせず次段へ委譲 2026-07-02 13:17:24 +09:00
routersys c56432dbd6 SoftwareCompositorを共有インスタンス化しTryComposeで常に処理を引き受け 2026-07-02 13:17:14 +09:00
routersys 9493aef779 IBufferCompositorのComposeを委譲可否を返すTryComposeへ変更 2026-07-02 13:17:04 +09:00
routersys 5d55f2c083 バージョンをv1.11.2へ更新
リリース / build-and-release (workflow_dispatch) Actions がタグ v1.11.2 のコミットから作成しました
2026-07-02 12:54:31 +09:00
routersys 09918c2858 READMEへtempbuffer合成のGPU実行を追記 2026-07-02 12:54:27 +09:00
routersys a687bba0ff サイトへtempbuffer合成のGPU実行を追記 2026-07-02 12:54:18 +09:00
routersys bb591b6fef 全言語ドキュメントへtempbuffer合成のGPU実行を追記 2026-07-02 12:54:10 +09:00
routersys 27d7294290 SoftwareCompositorのComposeディスパッチのテストを追加 2026-07-02 12:54:01 +09:00
routersys 8d1cf91499 FallbackCompositorのユニットテストを追加 2026-07-02 12:53:44 +09:00
routersys b2a1900616 DrawTransformのユニットテストを追加 2026-07-02 12:53:35 +09:00
routersys f786250866 tempbuffer合成へGPU優先のFallbackCompositorを配線 2026-07-02 12:53:19 +09:00
routersys 20dfba6e7e DrawCompositorの変換行列構築をDrawTransformへ集約 2026-07-02 12:53:13 +09:00
routersys 5e40f45910 tempbuffer合成を注入された合成器経由へ変更 2026-07-02 12:52:56 +09:00
routersys ea4f096bc4 Direct2DでGPU合成を行うHardwareCompositorを追加 2026-07-02 12:52:48 +09:00
routersys d7812f39dc SoftwareCompositorをIBufferCompositorの実装へ変更 2026-07-02 12:52:29 +09:00
routersys 77fdf60ec9 合成失敗時にCPUへ降格するFallbackCompositorを追加 2026-07-02 12:52:11 +09:00
routersys bcb9925953 描画コマンドから変換行列を求めるDrawTransformを追加 2026-07-02 12:52:00 +09:00
routersys ec7d8a1da4 バッファ合成の契約IBufferCompositorを追加 2026-07-02 12:51:51 +09:00
routersys 098d6e498b バージョンをv1.11.1へ更新
リリース / build-and-release (workflow_dispatch) Actions がタグ v1.11.1 のコミットから作成しました
2026-07-02 08:43:27 +09:00
routersys ccf37dd1d3 サイトを既定エンジンのnative化に合わせて更新 2026-07-02 08:42:43 +09:00
routersys 2ce3068d54 READMEを既定エンジンのnative化に合わせて更新 2026-07-02 08:36:04 +09:00
routersys c2a1990501 全言語ドキュメントを既定エンジンのnative化に合わせて更新 2026-07-02 08:35:27 +09:00
routersys 4ac25584b9 既定エンジンのnative化に合わせてルーティング期待値を更新 2026-07-02 08:01:52 +09:00
routersys 5e40f30124 自動ルーティングの既定エンジンをnativeへ変更 2026-07-02 08:01:46 +09:00
routersys 9d541e06b9 遅延転送・ワーカー永続性・グローバルパリティのテストを追加 2026-07-02 08:01:18 +09:00
routersys bca7b5707e nativeレーンの入力ピクセルをメモ化付き遅延読み込みへ変更 2026-07-02 08:01:12 +09:00
routersys a17289a2da ピクセル転送を遅延化し再起動判定をgrow-only容量ベースへ変更 2026-07-02 08:00:59 +09:00
routersys 71e6b71056 ワーカーのピクセル遅延要求と裸グローバル・環境リセットのパリティを実装 2026-07-02 08:00:34 +09:00
routersys 13a0602adb ピクセル要求コールバック種別をネイティブプロトコルへ追加 2026-07-02 08:00:28 +09:00
routersys 6a0c993755 Updateホットパスのフレーム毎アロケーションを削減 2026-07-02 07:33:08 +09:00
routersys 484a26ec45 バージョンをv1.11.0へ更新
リリース / build-and-release (workflow_dispatch) Actions がタグ v1.11.0 のコミットから作成しました
2026-07-01 22:29:26 +09:00
routersys a121a598b6 setanchorのプレビュー反映漏れを修正 2026-07-01 22:19:49 +09:00
routersys 6dd70413a9 setanchorを両エンジン対応として更新 2026-07-01 17:52:54 +09:00
routersys ac482b6041 setanchorを実装済みAPIへ移しsetoptionの追加オプションを追記 2026-07-01 17:52:49 +09:00
routersys c2761c0796 LuaJITレーンのsetanchor往復をテスト 2026-07-01 17:52:41 +09:00
routersys 3bbd411d86 LuaJITレーンでsetanchorコールバックを仲介 2026-07-01 17:52:34 +09:00
routersys 324faabb96 LuaJITワーカーにobj.setanchorをコールバックで実装 2026-07-01 17:52:27 +09:00
routersys 32b706cb8b setanchorコールバック種別を追加 2026-07-01 17:52:18 +09:00
routersys aa97c52b38 アンカーの線結びをPuppetDeform+準拠のペアワイズ辺へ変更しネイティブ座標解決を追加 2026-07-01 17:52:10 +09:00
routersys a2f0231739 サイトにobj.setanchorを追記 2026-07-01 17:36:59 +09:00
routersys 2905192d3a 全言語ドキュメントにobj.setanchorを追記 2026-07-01 17:36:53 +09:00
routersys ee6f6bd9c1 AnchorSupportの単体テストを追加 2026-07-01 17:36:46 +09:00
routersys 8853f5e403 アンカーのドラッグ用コントローラを構築しDrawDescriptionへ付与 2026-07-01 17:36:35 +09:00
routersys 867de7aa73 setanchorを含むスクリプトをMoonSharpへ振り分け 2026-07-01 17:36:28 +09:00
routersys e384d7e490 obj.setanchorを実装しLua変数へ座標を格納 2026-07-01 17:36:16 +09:00
routersys 87e060d71d アンカーの入力元と要求リストをコンテキストへ追加 2026-07-01 17:36:07 +09:00
routersys 9c6167d224 アンカー座標をプロジェクトへ保存する状態を追加 2026-07-01 17:35:56 +09:00
routersys a8a91103e1 setanchorのオプション解析・既定位置・座標解決・ドラッグ適用を追加 2026-07-01 17:35:44 +09:00
routersys 4a2f4b2dbb アンカー座標のプレーン値モデルを追加 2026-07-01 17:35:33 +09:00
routersys 33fc45639b drawtargetを両エンジン対応としてサイトを更新 2026-07-01 16:58:42 +09:00
routersys 7af803e46e drawtargetを両エンジン対応として全言語ドキュメントを更新 2026-07-01 16:58:33 +09:00
routersys 48e8287704 LuaJITレーンのdrawtarget往復をテスト 2026-07-01 16:58:17 +09:00
routersys 7eff4591f0 LuaJITワーカーにdrawtargetのCPU合成を実装しtmpバッファを可変化 2026-07-01 16:58:05 +09:00
routersys 5b1bb4ad6e サイトにdrawtargetを追記しdraw_stateを両エンジン対応へ更新 2026-07-01 14:04:10 +09:00
routersys 7f3e6b0019 全言語ドキュメントにdrawtargetを追記しdraw_stateを両エンジン対応へ更新 2026-07-01 14:03:59 +09:00
routersys 7519a11851 LuaJITレーンのdraw_state書き戻しをテスト 2026-07-01 14:03:36 +09:00
routersys 4193c40f41 CPUソフトウェア合成のユニットテストを追加 2026-07-01 14:03:24 +09:00
routersys cd68bf86b0 draw_stateフィールドをコンテキストへ反映 2026-07-01 14:02:58 +09:00
routersys 9948204265 LuaJITレーンでdraw_stateを読み戻す 2026-07-01 14:02:51 +09:00
routersys 25670bde90 LuaJITワーカーでdraw_stateをフィールドへ書き出す 2026-07-01 14:02:39 +09:00
routersys ae230c0e10 draw_state用のフィールドを予約 2026-07-01 14:02:26 +09:00
routersys 7ee8f1ccf0 フレーム毎に描画先をframebufferへ戻す 2026-07-01 14:01:53 +09:00
routersys da88898a67 obj.drawをSubmitDrawへ回しdrawtargetをコンテキストへ橋渡し 2026-07-01 14:01:38 +09:00
routersys 3c63ba0729 drawtargetの描画先切り替えとtmpへの即時合成を追加 2026-07-01 14:01:28 +09:00
routersys e7382ac289 tempbuffer用のCPUソフトウェア合成を追加 2026-07-01 14:01:16 +09:00
routersys ee7e4f43bc サイトにsetoptionのdraw_stateを追記 2026-07-01 13:49:57 +09:00
routersys 7dc6e9fb40 全言語ドキュメントにsetoptionのdraw_stateを追記 2026-07-01 13:49:50 +09:00
routersys 803534d804 draw_stateで作業画像の出力を強制または抑制 2026-07-01 13:49:41 +09:00
routersys a25803fa30 setoptionのdraw_stateをコンテキストへ橋渡し 2026-07-01 13:49:35 +09:00
routersys e42401670f draw_stateの出力上書き状態をコンテキストに追加 2026-07-01 13:49:30 +09:00
routersys a139326c39 合成描画のOpacity出力をキャッシュして毎描画のCOM確保を無くす 2026-07-01 13:49:24 +09:00
routersys 496c237f50 サイトにsetoptionの合成モードを追記 2026-07-01 13:08:27 +09:00
routersys dfbcbded98 全言語ドキュメントにsetoptionの合成モードを追記 2026-07-01 13:08:17 +09:00
routersys 2ebbe3ced0 LuaJITレーンの合成モード受け渡しをテスト 2026-07-01 13:08:05 +09:00
routersys 9671cba5a1 LuaJITレーンで合成モードの番号を受け渡し 2026-07-01 13:07:57 +09:00
routersys 947532f064 MoonSharpでobj.setoptionのblendを描画へ反映 2026-07-01 13:07:45 +09:00
routersys 6e3594eb01 obj.drawの描画合成に合成モードを適用 2026-07-01 13:07:36 +09:00
routersys abc7b2cde2 合成モードの番号とYMM4 Blendの対応表を追加 2026-07-01 13:07:27 +09:00
routersys 68d862ded0 DrawCommandに合成モードの番号を追加 2026-07-01 13:07:19 +09:00
routersys d3060fd202 未使用のEpsilon定数をNativeFieldMapから削除 2026-07-01 08:30:04 +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
295個のファイルの変更、31909行の追加、2510行の削除

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

+60 -39
ファイルの表示
@@ -1,54 +1,75 @@
# v1.2.0 - Lua スクリプト for YMM4
# v1.16.0 - Lua スクリプト for YMM4
他オブジェクトの情報を任意のフレーム時点で取得できるようにしたリリースです。
発射元が動いても弾の発射位置を固定するなど、フレームを指定した参照が可能になりました。
標準の Lua には無い簡易な記法を構文拡張へ 6 種類追加したリリースです。三項演算子、nil 条件演算子、ラムダ式、パイプ、補間文字列、範囲判定を書けるようになりました。いずれもスクリプトの実行前に等価な標準 Lua へ変換するため、LuaJIT、MoonSharp、CPU カーネルのどの実行エンジンでも同じ結果になります。変換は字句単位で行い、文字列とコメントの内側は変換しません。入口とする記号は通常の Lua には現れないため、既存のスクリプトの書き方と実行結果に変更はありません。
---
## 新機能
### 1. obj.getobject へのフレーム指定引数の追加
### 三項演算子
`obj.getobject(tag, frame)` の第2引数 `frame` を追加しました。指定したタイムライン
フレーム時点での対象オブジェクトの座標・回転・拡大率・不透明度を取得できます。
`frame` を省略した場合は従来どおり現在フレームの値を返します。
条件 ? A : B を追加しました。条件が真のとき A を、偽のとき B を返します。条件と両辺は同じ行に式として書きます。
弾の発射フレーム(弾アイテムの開始フレーム)は `timelineframe - frame` で求まるため、
そのフレームの発射元座標を取得すれば、発射元が動いても弾の原点を発射位置に固定できます。
- (function() if 条件 then return (A) else return (B) end end)() へ展開します。条件は 1 度だけ評価し、選ばれた側の式だけを評価します。
- a and b or c と違い、真の側の値が false や nil であっても、その値をそのまま返します。
- : のあとにもう一度 ? : を書けば、else 側で分岐を続けられます。
- 関数呼び出しの引数の位置にも書けます。? を値の位置に書いたときだけ変換するため、テーブルリテラルやメソッド呼び出し、ラベルなど、通常のコードには影響しません。
```lua
local fire = timelineframe - frame
local src = obj.getobject("routersys", fire)
if src then
obj.x = src.x
obj.y = src.y
end
```
### nil 条件演算子
取得値は対象アイテム自身の座標・回転・拡大率であり、グループ制御・カメラ制御による
変形は含みません。同じタグのアイテムが複数ある場合は、対象フレームで表示中のものを
優先して返します。
t?.x と t?[k] を追加しました。t が nil のときは nil を返し、そうでなければ t.x や t[k] を返します。nil の値へ添字アクセスして実行時エラーになるのを防ぎます。
- 対象を一時変数へ受けて 1 度だけ評価する無名関数へ展開します。(function() local tmp = (t) if tmp == nil then return nil end return tmp.x end)() の形になります。
- a?.b?.c のように連ねれば、途中の値が nil でも安全にたどれます。
- nil 合体演算子と組み合わせて、t?.x ?? 既定値 のように書けます。左辺が nil のときだけ既定値を返します。
### ラムダ式
(a, b) => 式 を追加しました。その式を返す無名関数へ展開し、(function(a, b) return 式 end) になります。
- 引数が 1 つのときは括弧を省いて x => 式、引数が無いときは () => 式 と書けます。最後の引数として ... を受け取れます。本体には 1 つの式を書きます。
- table.sort の比較関数のように、関数を引数へ直接渡す場面で使えます。
- 入口は => だけのため、比較演算子の >= や <= には影響しません。
### パイプ
x |> f を追加しました。f((x)) へ展開し、左辺を関数の第 1 引数として渡します。
- x |> f(a, b) のように引数を書いたときは、左辺が第 1 引数に入り、残りの引数は後ろへ続いて f((x), a, b) になります。
- |> は左から右へ連ねられます。a |> f |> g は g(f(a)) と同じ順序で評価します。
- math.floor のようなメンバー関数も呼べます。
### 補間文字列
バッククォートで囲む文字列を追加しました。中に {式} を書くと、その値を tostring で文字列にして差し込みます。
- `x={a}` は ("x=" .. tostring(a)) へ展開します。式を含まない `hello` は "hello" に、空の `` は "" になります。
- { } の中では拡張構文もそのまま使えます。バックスラッシュによるエスケープは保持します。
- 入口はバッククォートのため、通常の文字列やコメントの中のバッククォートは変換しません。
### 範囲判定
x in <1..5> を追加しました。x がその範囲に入っているかどうかを判定します。.. は終端を含み、..< は終端を含みません。
- 左辺を一時変数へ受けて 1 度だけ評価する無名関数へ展開し、1 <= x and x <= 5 に相当する判定を返します。<1..<5> は上限を含まず、1 <= x and x < 5 になります。
- 範囲 for の for i in <0..10> とは書く位置が異なるため、for のヘッダーや、ipairs、pairs を使う汎用 for には影響しません。
- 増分を伴う <開始..終了, 増分> の書き方は、範囲判定では扱いません。
---
## 互換性・後方互換
- 追加した記法はいずれも、標準の Lua には現れない記号、つまり ? と => と |> とバッククォートと in < の並びを入口にしています。既存のスクリプトはそのまま動作し、実行結果も変わりません。
- 変換はすべての実行エンジンに適用され、LuaJIT、MoonSharp、CPU カーネルのいずれでも同じ結果になります。文字列とコメントの内側は変換しません。
- 分岐の各辺、ラムダの本体、パイプの対象、補間文字列の {式}、範囲判定の両端など、入れ子になった式にも構文拡張の変換を再帰的に適用します。
- v1.15.0 までの仕様に変更はありません。obj.pixelshader をはじめとする既存の API と、実行エンジンの自動振り分けに変更はありません。
---
## 内部実装
### 2. 参照方式の統一(依存クエリの再評価)
他オブジェクトの値を「現在フレームで事前に算出したスナップショット」を比較する方式から、
「参照したオブジェクトを保持し、要求されたフレームで評価する」方式へ統一しました。
- 取得対象のアイテムを保持し、任意のフレームで評価する `SceneObjectResolver` を追加
- スクリプト実行中に行われた参照 `(タグ, フレーム)` を記録し、出力キャッシュの
再利用判定では記録した参照を再評価して一致を確認
これにより、任意フレームの参照に対しても決定論的かつキャッシュ整合性を保った
取得が可能になります。評価はすべて描画スレッド側で行い、スクリプト実行スレッドへは
数値のみを渡します。
---
## ドキュメント
対応する 8 言語のスクリプト説明文に `frame` 引数の説明と発射位置を固定する例を
追記し、サンプル集ページにも同様の例を追加しました。
- 字句解析器に補間文字列のトークン種別を追加し、バッククォートで囲む文字列を 1 つのトークンとして読み取ります。あわせて演算子として => と |> を追加しました。
- 範囲の解析を共通のヘルパーへ切り出しました。開始・終了・増分と、終端を含むかどうかを 1 か所で判定し、範囲 for と範囲判定の両方がこのヘルパーを使います。
- 各記法は、属性で優先順位を与えた変換規則として実装しました。nil 条件演算子の規則は三項演算子より先に走り、?. と ?[ を単独の ? より先に処理します。既存の変換基盤はそのまま流用し、変換文脈に変更はありません。
- ドキュメントは付属の 8 言語、サイトの構文拡張のページ、README を更新しました。
- テストは 3297 件です。v1.15.0 の 3259 件から、三項演算子、nil 条件演算子、ラムダ式、パイプ、補間文字列、範囲判定の各変換と評価、入れ子になった式の変換、比較演算子や for のヘッダーを変換しないこと、対象や左辺を 1 度だけ評価することの検証を追加しました。
+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.16.0
========================================
YukkuriMovieMaker4(YMM4)上で動作する、Luaスクリプトで映像エフェクトのパラメータや
ピクセルを直接制御できるプラグインです。
@@ -26,7 +26,9 @@ obj.x/y/zoom/alpha等の値はキーフレームアニメーションと連動
- スクリプトエラー時の挙動: コンパイルエラーまたは実行時エラーが発生した場合、
そのフレームでの座標・透明度・回転・ピクセルの変更は適用されず、入力された
元の状態がそのまま出力されます。エラー内容はログへ出力されます。
元の状態がそのまま出力されます。エラー内容はログへ出力されるほか、スクリプト
エディタの該当箇所へ赤い波線が表示され、ポイントするとエラー内容をツールチップ
で確認できます。
- ファイルアクセスの制限: スクリプトからのファイル読み込みは許可されておらず、
io・os等のモジュールも有効化されていません。
+11
ファイルの表示
@@ -69,9 +69,19 @@ jobs:
$pkgName = "LuaScript_$version.ymme"
New-Item -ItemType Directory -Path "$stageRoot/docs" -Force | Out-Null
New-Item -ItemType Directory -Path "$stageRoot/native" -Force | Out-Null
New-Item -ItemType Directory -Path "$stageRoot/LICENSE" -Force | Out-Null
Copy-Item "$outDir/LuaScript.dll" "$stageRoot/"
Copy-Item "$outDir/LuaScript.Kernel.dll" "$stageRoot/"
Copy-Item "$outDir/LuaScript.Compat.dll" "$stageRoot/"
Copy-Item "$outDir/LuaScript.Media.dll" "$stageRoot/"
Copy-Item "$outDir/LuaScript.Runtime.dll" "$stageRoot/"
Copy-Item "$outDir/MoonSharp.Interpreter.dll" "$stageRoot/"
Copy-Item "$outDir/native/luajit.exe" "$stageRoot/native/"
Copy-Item "$outDir/native/lua51.dll" "$stageRoot/native/"
Copy-Item "$outDir/native/worker.lua" "$stageRoot/native/"
Copy-Item "$outDir/native/shim.lua" "$stageRoot/native/"
foreach ($lang in @("ar-sa", "en-us", "es-es", "id-id", "ko-kr", "zh-cn", "zh-tw")) {
$src = "$outDir/$lang"
@@ -82,6 +92,7 @@ jobs:
}
Copy-Item "LuaScript/docs/LuaScript.*.txt" "$stageRoot/docs/"
Copy-Item ".github/LICENSE/*.txt" "$stageRoot/LICENSE/"
Copy-Item ".github/Plugin_Readme.txt" "$stageRoot/Readme.txt"
Compress-Archive -Path "stage/*" -DestinationPath $pkgName -CompressionLevel Optimal
+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>
+137
ファイルの表示
@@ -0,0 +1,137 @@
namespace LuaScript.Compat
{
internal static class AviUtlGlobalFunctions
{
public static int BitOr(double a, double b) => ToBitOperand(a) | ToBitOperand(b);
public static int BitAnd(double a, double b) => ToBitOperand(a) & ToBitOperand(b);
public static int BitXor(double a, double b) => ToBitOperand(a) ^ ToBitOperand(b);
public static int BitShift(double value, double shift)
{
int v = ToBitOperand(value);
int n = ToBitOperand(shift);
return n >= 0 ? v << n : v >> -n;
}
public static int ToBitOperand(double value)
{
if (double.IsNaN(value))
return 0;
if (value <= int.MinValue)
return int.MinValue;
if (value >= int.MaxValue)
return int.MaxValue;
return (int)Math.Ceiling(value - 0.5);
}
public static int RgbCompose(double r, double g, double b) =>
(ToColorChannel(r) << 16) | (ToColorChannel(g) << 8) | ToColorChannel(b);
public static void RgbComponents(double color, out int r, out int g, out int b)
{
int c = ToColor(color);
r = (c >> 16) & 0xFF;
g = (c >> 8) & 0xFF;
b = c & 0xFF;
}
public static int RgbInterpolate(double r1, double g1, double b1, double r2, double g2, double b2, double t) =>
RgbCompose(r1 + (r2 - r1) * t, g1 + (g2 - g1) * t, b1 + (b2 - b1) * t);
public static int HsvCompose(double h, double s, double v)
{
h = WrapHue(h);
s = ClampRatio(s);
v = ClampRatio(v);
double c = v * s;
double x = c * (1d - Math.Abs(h / 60d % 2d - 1d));
double m = v - c;
int sector = (int)Math.Floor(h / 60d);
double r, g, b;
if (sector == 0) { r = c; g = x; b = 0d; }
else if (sector == 1) { r = x; g = c; b = 0d; }
else if (sector == 2) { r = 0d; g = c; b = x; }
else if (sector == 3) { r = 0d; g = x; b = c; }
else if (sector == 4) { r = x; g = 0d; b = c; }
else { r = c; g = 0d; b = x; }
return (ToColorChannel(RoundHalfUp((r + m) * 255d)) << 16) |
(ToColorChannel(RoundHalfUp((g + m) * 255d)) << 8) |
ToColorChannel(RoundHalfUp((b + m) * 255d));
}
public static void HsvComponents(double color, out int h, out int s, out int v)
{
RgbComponents(color, out int r, out int g, out int b);
double rf = r / 255d;
double gf = g / 255d;
double bf = b / 255d;
double max = Math.Max(rf, Math.Max(gf, bf));
double min = Math.Min(rf, Math.Min(gf, bf));
double delta = max - min;
double hue = 0d;
if (delta > 0d)
{
if (max == rf)
hue = 60d * (((gf - bf) / delta % 6d + 6d) % 6d);
else if (max == gf)
hue = 60d * ((bf - rf) / delta + 2d);
else
hue = 60d * ((rf - gf) / delta + 4d);
}
h = (int)RoundHalfUp(hue);
s = (int)RoundHalfUp(max > 0d ? delta / max * 100d : 0d);
v = (int)RoundHalfUp(max * 100d);
}
public static int HsvInterpolate(double h1, double s1, double v1, double h2, double s2, double v2, double t) =>
HsvCompose(h1 + (h2 - h1) * t, s1 + (s2 - s1) * t, v1 + (v2 - v1) * t);
private static int ToColorChannel(double value)
{
if (double.IsNaN(value) || value <= 0d)
return 0;
if (value >= 255d)
return 255;
return (int)Math.Floor(value);
}
private static int ToColor(double value)
{
if (double.IsNaN(value))
return 0;
if (value <= int.MinValue)
value = int.MinValue;
else if (value >= int.MaxValue)
value = int.MaxValue;
long floored = (long)Math.Floor(value);
return (int)(floored & 0xFFFFFF);
}
private static double WrapHue(double h)
{
if (double.IsNaN(h) || double.IsInfinity(h))
return 0d;
double wrapped = h - Math.Floor(h / 360d) * 360d;
return wrapped >= 360d ? 0d : wrapped;
}
private static double ClampRatio(double value)
{
if (double.IsNaN(value) || value <= 0d)
return 0d;
if (value >= 100d)
return 1d;
return value / 100d;
}
private static double RoundHalfUp(double value) => Math.Floor(value + 0.5);
}
}
+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;
}
}
}
+109
ファイルの表示
@@ -0,0 +1,109 @@
using System;
namespace LuaScript.Compat
{
internal static class Bit32
{
public static uint ToUInt32(double value) => unchecked((uint)(long)value);
public static uint Band(params double[] values)
{
uint accum = 0xFFFFFFFFu;
foreach (var value in values)
accum &= ToUInt32(value);
return accum;
}
public static uint Bor(params double[] values)
{
uint accum = 0u;
foreach (var value in values)
accum |= ToUInt32(value);
return accum;
}
public static uint Bxor(params double[] values)
{
uint accum = 0u;
foreach (var value in values)
accum ^= ToUInt32(value);
return accum;
}
public static bool Btest(params double[] values) => Band(values) != 0u;
public static uint Bnot(double value) => ~ToUInt32(value);
public static uint Lshift(double value, double shift)
{
uint v = ToUInt32(value);
int a = (int)shift;
if (a <= -32 || a >= 32)
return 0u;
return a >= 0 ? v << a : v >> -a;
}
public static uint Rshift(double value, double shift) => Lshift(value, -shift);
public static uint Arshift(double value, double shift)
{
uint v = ToUInt32(value);
int a = (int)shift;
if (a < 0)
return Lshift(value, -shift);
bool negative = (v & 0x80000000u) != 0u;
if (a >= 32)
return negative ? 0xFFFFFFFFu : 0u;
if (a == 0)
return v;
uint result = v >> a;
if (negative)
result |= ~0u << (32 - a);
return result;
}
public static uint Lrotate(double value, double shift)
{
uint v = ToUInt32(value);
int a = ((int)shift % 32 + 32) % 32;
return a == 0 ? v : (v << a) | (v >> (32 - a));
}
public static uint Rrotate(double value, double shift) => Lrotate(value, -shift);
public static uint Extract(double value, double pos, double? width)
{
uint v = ToUInt32(value);
int p = (int)pos;
int w = width is null ? 1 : (int)width.Value;
ValidatePosWidth(p, w);
return (v >> p) & NBitMask(w);
}
public static uint Replace(double value, double replacement, double pos, double? width)
{
uint v = ToUInt32(value);
uint u = ToUInt32(replacement);
int p = (int)pos;
int w = width is null ? 1 : (int)width.Value;
ValidatePosWidth(p, w);
uint mask = NBitMask(w) << p;
return (v & ~mask) | ((u & NBitMask(w)) << p);
}
private static void ValidatePosWidth(int pos, int width)
{
if (pos < 0 || width < 1 || pos + width > 32)
throw new ArgumentException("trying to access non-existent bits");
}
private static uint NBitMask(int bits)
{
if (bits <= 0)
return 0u;
if (bits >= 32)
return 0xFFFFFFFFu;
return (1u << bits) - 1u;
}
}
}
+111
ファイルの表示
@@ -0,0 +1,111 @@
using System;
namespace LuaScript.Compat
{
internal static class MoonSharpBit32
{
private const double Modulo = 4294967296.0;
public static uint ToUInt32(double value) => unchecked((uint)Math.IEEERemainder(value, Modulo));
public static int ToInt32(double value) => unchecked((int)Math.IEEERemainder(value, Modulo));
public static uint Band(params double[] values)
{
uint accum = ToUInt32(values[0]);
for (int i = 1; i < values.Length; i++)
accum &= ToUInt32(values[i]);
return accum;
}
public static uint Bor(params double[] values)
{
uint accum = ToUInt32(values[0]);
for (int i = 1; i < values.Length; i++)
accum |= ToUInt32(values[i]);
return accum;
}
public static uint Bxor(params double[] values)
{
uint accum = ToUInt32(values[0]);
for (int i = 1; i < values.Length; i++)
accum ^= ToUInt32(values[i]);
return accum;
}
public static bool Btest(params double[] values) => Band(values) != 0u;
public static uint Bnot(double value) => ~ToUInt32(value);
public static uint Lshift(double value, double shift)
{
uint v = ToUInt32(value);
int a = (int)shift;
return a < 0 ? v >> -a : v << a;
}
public static uint Rshift(double value, double shift)
{
uint v = ToUInt32(value);
int a = (int)shift;
return a < 0 ? v << -a : v >> a;
}
public static int Arshift(double value, double shift)
{
int v = ToInt32(value);
int a = (int)shift;
return a < 0 ? v << -a : v >> a;
}
public static uint Lrotate(double value, double shift)
{
uint v = ToUInt32(value);
int a = ((int)shift) % 32;
return a < 0 ? (v >> -a) | (v << (32 + a)) : (v << a) | (v >> (32 - a));
}
public static uint Rrotate(double value, double shift)
{
uint v = ToUInt32(value);
int a = ((int)shift) % 32;
return a < 0 ? (v << -a) | (v >> (32 + a)) : (v >> a) | (v << (32 - a));
}
public static uint Extract(double value, double pos, double? width)
{
uint v = ToUInt32(value);
int p = (int)pos;
int w = width is null ? 1 : (int)width.Value;
ValidatePosWidth(p, w);
return (v >> p) & NBitMask(w);
}
public static uint Replace(double value, double replacement, double pos, double? width)
{
uint v = ToUInt32(value);
uint u = ToUInt32(replacement);
int p = (int)pos;
int w = width is null ? 1 : (int)width.Value;
ValidatePosWidth(p, w);
uint mask = NBitMask(w) << p;
return (v & ~mask) | (u & mask);
}
private static void ValidatePosWidth(int pos, int width)
{
if (pos > 31 || pos + width > 31)
throw new ArgumentException("trying to access non-existent bits");
}
private static uint NBitMask(int bits)
{
if (bits <= 0)
return 0u;
if (bits >= 32)
return 0xFFFFFFFFu;
return (1u << bits) - 1u;
}
}
}
+26
ファイルの表示
@@ -0,0 +1,26 @@
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<TargetFramework>net10.0-windows10.0.19041.0</TargetFramework>
<ImplicitUsings>enable</ImplicitUsings>
<Version>1.16.0</Version>
<Platforms>AnyCPU;x64</Platforms>
<Nullable>enable</Nullable>
</PropertyGroup>
<ItemGroup>
<InternalsVisibleTo Include="LuaScript" />
<InternalsVisibleTo Include="LuaScript.Runtime" />
<InternalsVisibleTo Include="LuaScript.Tests" />
</ItemGroup>
<ItemGroup>
<ProjectReference Include="..\LuaScript.Kernel\LuaScript.Kernel.csproj" />
<ProjectReference Include="..\LuaScript.Generator\LuaScript.Generator.csproj" OutputItemType="Analyzer" ReferenceOutputAssembly="false" />
</ItemGroup>
<ItemGroup>
<EmbeddedResource Include="AviUtlCompatMap.xml" />
</ItemGroup>
</Project>
+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 ScriptParserHelper.SplitLines(script))
{
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);
}
}
}
+25
ファイルの表示
@@ -0,0 +1,25 @@
using System.Collections.Generic;
namespace LuaScript.Compat
{
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);
}
}
+9
ファイルの表示
@@ -0,0 +1,9 @@
namespace LuaScript.Compat
{
internal enum AviUtlEngine
{
AviUtl,
AviUtl2,
Both,
}
}
+27
ファイルの表示
@@ -0,0 +1,27 @@
namespace LuaScript.Compat
{
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;
}
}
}
}
+7
ファイルの表示
@@ -0,0 +1,7 @@
namespace LuaScript.Compat
{
internal readonly record struct AviUtlParameterMapping(string Source, string Property, double Scale, double Offset)
{
public double Transform(double value) => value * Scale + Offset;
}
}
+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;
}
}
}
+153
ファイルの表示
@@ -0,0 +1,153 @@
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 = ScriptParserHelper.SplitLines(source);
ScriptParserHelper.TryFindSection(lines, out int sectionStart, out int sectionEnd);
for (int i = sectionStart; i < sectionEnd; i++)
layout.ParseLine(lines[i]);
return layout;
}
private void ParseLine(string line)
{
if (!ScriptParserHelper.TryParseDirective(line, out string name, out string content))
return;
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);
}
}
}
+85
ファイルの表示
@@ -0,0 +1,85 @@
using System;
using System.Collections.Generic;
namespace LuaScript.Compat
{
internal sealed class AviUtlPixelShaderLibrary
{
private const string SectionMarker = "--[[pixelshader@";
public static AviUtlPixelShaderLibrary Empty { get; } = new(null);
private readonly Dictionary<string, string>? _shaders;
private AviUtlPixelShaderLibrary(Dictionary<string, string>? shaders) => _shaders = shaders;
public int Count => _shaders?.Count ?? 0;
public static AviUtlPixelShaderLibrary Parse(string? source)
{
if (string.IsNullOrEmpty(source))
return Empty;
Dictionary<string, string>? shaders = null;
int index = 0;
while (index < source.Length)
{
int lineStart = index;
int lineBreak = source.IndexOf('\n', index);
index = lineBreak < 0 ? source.Length : lineBreak + 1;
int i = ScriptParserHelper.SkipSpaces(source, lineStart);
if (!MatchesMarker(source, i))
continue;
i += SectionMarker.Length;
int nameStart = i;
while (i < source.Length && IsEntryPointChar(source[i]))
i++;
if (i == nameStart || i >= source.Length || source[i] != ':')
continue;
string name = source[nameStart..i];
int bodyStart = i + 1;
int bodyEnd = source.IndexOf("]]", bodyStart, StringComparison.Ordinal);
if (bodyEnd < 0)
continue;
shaders ??= new Dictionary<string, string>(StringComparer.Ordinal);
shaders.TryAdd(name, source[bodyStart..bodyEnd]);
index = bodyEnd + 2;
}
return shaders is null ? Empty : new AviUtlPixelShaderLibrary(shaders);
}
public bool TryGet(string name, out string hlsl)
{
hlsl = string.Empty;
if (_shaders is null || string.IsNullOrEmpty(name))
return false;
int at = name.IndexOf('@');
string local = at < 0 ? name : name[..at];
if (_shaders.TryGetValue(local, out var found))
{
hlsl = found;
return true;
}
return false;
}
public static string EntryPointOf(string name)
{
int at = name.IndexOf('@');
return at < 0 ? name : name[..at];
}
private static bool MatchesMarker(string text, int index) =>
index + SectionMarker.Length <= text.Length &&
string.CompareOrdinal(text, index, SectionMarker, 0, SectionMarker.Length) == 0;
private static bool IsEntryPointChar(char c) =>
ScriptParserHelper.IsNameChar(c) || c == '_';
}
}
+103
ファイルの表示
@@ -0,0 +1,103 @@
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, int[] ChangedLines) TransformWithMap(string source)
{
if (string.IsNullOrEmpty(source))
return (source, [], []);
var lines = ScriptParserHelper.SplitLines(source);
bool hasSection = ScriptParserHelper.TryFindSection(lines, out int sectionStart, out int sectionEnd);
var prelude = new List<string>();
for (int i = sectionStart; i < sectionEnd; i++)
AppendDeclarations(lines[i], prelude);
if (!hasSection && prelude.Count == 0)
{
var (code, changed) = LuaSyntaxExtensions.RewriteWithMap(source);
return (code, [], changed);
}
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;
}
var (rewritten, changedLines) = LuaSyntaxExtensions.RewriteWithMap(builder.ToString());
return (rewritten, lineMap, changedLines);
}
private static void AppendDeclarations(string line, List<string> prelude)
{
if (!ScriptParserHelper.TryParseDirective(line, out string name, out string content))
return;
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);
}
}
}
+48
ファイルの表示
@@ -0,0 +1,48 @@
using LuaScript.Compat.Syntax;
namespace LuaScript.Compat
{
internal static class LuaSyntaxExtensions
{
public static string Rewrite(string source) => RewriteWithMap(source).Code;
public static (string Code, int[] ChangedLines) RewriteWithMap(string source)
{
if (string.IsNullOrEmpty(source))
return (source, []);
var tokens = LuaSyntaxLexer.Tokenize(source);
var context = new LuaRewriteContext(tokens);
var rules = LuaSyntaxRuleRegistry.Rules;
while (!context.AtEnd)
{
var current = context.Current;
if (current.IsTrivia || current.Kind == LuaSyntaxTokenKind.String)
{
context.Emit(current);
context.Advance();
continue;
}
bool matched = false;
foreach (var rule in rules)
{
if (rule.TryApply(context))
{
matched = true;
break;
}
}
if (!matched)
{
context.Emit(current);
context.Advance();
}
}
return context.Changed ? (context.Serialize(), context.ChangedLines) : (source, []);
}
}
}
+94
ファイルの表示
@@ -0,0 +1,94 @@
using System;
using System.Collections.Generic;
using LuaScript.Compat.Syntax;
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;
var tokens = LuaSyntaxLexer.Tokenize(script);
HashSet<string>? members = null;
bool color = false;
for (int i = 0; i < tokens.Count; i++)
{
var token = tokens[i];
if (token.Kind != LuaSyntaxTokenKind.Name)
continue;
if (token.Text == "color")
{
int previous = PreviousSignificant(tokens, i);
if (previous < 0 || !tokens[previous].IsOperator("."))
color = true;
continue;
}
if (token.Text == "obj")
{
int dot = NextSignificant(tokens, i + 1);
if (dot < 0 || !tokens[dot].IsOperator("."))
continue;
int member = NextSignificant(tokens, dot + 1);
if (member < 0 || tokens[member].Kind != LuaSyntaxTokenKind.Name)
continue;
(members ??= new HashSet<string>(StringComparer.Ordinal)).Add(tokens[member].Text);
}
}
return new ScriptParameterUsage(members, color);
}
private static int PreviousSignificant(List<LuaSyntaxToken> tokens, int from)
{
for (int i = from - 1; i >= 0; i--)
{
if (!tokens[i].IsTrivia)
return i;
}
return -1;
}
private static int NextSignificant(List<LuaSyntaxToken> tokens, int from)
{
for (int i = from; i < tokens.Count; i++)
{
if (!tokens[i].IsTrivia)
return i;
}
return -1;
}
}
}
+69
ファイルの表示
@@ -0,0 +1,69 @@
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');
public static string[] SplitLines(string source) =>
source.Replace("\r\n", "\n").Replace("\r", "\n").Split('\n');
public static bool TryFindSection(string[] lines, out int start, out int end)
{
start = 0;
end = lines.Length;
for (int i = 0; i < lines.Length; i++)
{
if (!IsSectionHeader(lines[i]))
continue;
start = i + 1;
end = lines.Length;
for (int j = start; j < lines.Length; j++)
{
if (IsSectionHeader(lines[j]))
{
end = j;
break;
}
}
return true;
}
return false;
}
public static bool TryParseDirective(string line, out string name, out string content)
{
name = string.Empty;
content = string.Empty;
int i = SkipSpaces(line, 0);
if (i + 1 >= line.Length || line[i] != '-' || line[i + 1] != '-')
return false;
i += 2;
if (i < line.Length && line[i] == '!')
return false;
int nameStart = i;
while (i < line.Length && IsNameChar(line[i]))
i++;
if (i >= line.Length || line[i] != ':')
return false;
name = line.Substring(nameStart, i - nameStart);
content = line.Substring(i + 1);
return true;
}
}
}
+7
ファイルの表示
@@ -0,0 +1,7 @@
namespace LuaScript.Compat.Syntax
{
internal interface ILuaSyntaxRule
{
bool TryApply(LuaRewriteContext context);
}
}
+23
ファイルの表示
@@ -0,0 +1,23 @@
using System.Collections.Generic;
namespace LuaScript.Compat.Syntax
{
internal static class LuaKeywords
{
private static readonly HashSet<string> Reserved = new()
{
"and", "break", "do", "else", "elseif", "end", "false", "for", "function",
"goto", "if", "in", "local", "nil", "not", "or", "repeat", "return",
"then", "true", "until", "while",
};
private static readonly HashSet<string> ExpressionSafe = new()
{
"and", "or", "not", "nil", "true", "false",
};
public static bool IsReserved(string name) => Reserved.Contains(name);
public static bool IsExpressionBoundary(string name) => Reserved.Contains(name) && !ExpressionSafe.Contains(name);
}
}
+130
ファイルの表示
@@ -0,0 +1,130 @@
using System.Collections.Generic;
using System.Text;
namespace LuaScript.Compat.Syntax
{
internal readonly struct LuaRangeParts
{
public LuaRangeParts(string start, string stop, string? step, bool exclusive)
{
Start = start;
Stop = stop;
Step = step;
Exclusive = exclusive;
}
public string Start { get; }
public string Stop { get; }
public string? Step { get; }
public bool Exclusive { get; }
}
internal static class LuaRangeSyntax
{
public static bool TryParse(IReadOnlyList<LuaSyntaxToken> input, int open, out LuaRangeParts parts, out int end)
{
parts = default;
end = open;
if (open < 0 || open >= input.Count || !input[open].IsOperator("<"))
return false;
int position = open + 1;
if (!TryReadSegment(input, ref position, "..", ">", out string start, out string startTerminator) || startTerminator != "..")
return false;
bool exclusive = false;
int caret = NextSignificant(input, position);
if (caret >= 0 && input[caret].IsOperator("<"))
{
exclusive = true;
position = caret + 1;
}
if (!TryReadSegment(input, ref position, ",", ">", out string stop, out string stopTerminator))
return false;
string? step = null;
if (stopTerminator == ",")
{
if (!TryReadSegment(input, ref position, ">", ">", out string stepText, out string stepTerminator) || stepTerminator != ">")
return false;
step = stepText;
}
else if (stopTerminator != ">")
{
return false;
}
if (start.Length == 0 || stop.Length == 0 || (step is not null && step.Length == 0))
return false;
parts = new LuaRangeParts(start, stop, step, exclusive);
end = position;
return true;
}
private static bool TryReadSegment(IReadOnlyList<LuaSyntaxToken> input, ref int position, string primaryStop, string secondaryStop, out string text, out string terminator)
{
text = string.Empty;
terminator = string.Empty;
int start = position;
int depth = 0;
int count = input.Count;
while (position < count)
{
var token = input[position];
if (token.Kind == LuaSyntaxTokenKind.Newline && depth == 0)
return false;
if (token.Kind == LuaSyntaxTokenKind.Operator)
{
if (token.Text is "(" or "[" or "{")
{
depth++;
}
else if (token.Text is ")" or "]" or "}")
{
if (depth == 0)
return false;
depth--;
}
else if (depth == 0 && (token.Text == primaryStop || token.Text == secondaryStop))
{
terminator = token.Text;
text = Trim(input, start, position);
position++;
return true;
}
}
position++;
}
return false;
}
private static int NextSignificant(IReadOnlyList<LuaSyntaxToken> input, int from)
{
for (int i = from; i < input.Count; i++)
{
if (!input[i].IsTrivia)
return i;
}
return -1;
}
private static string Trim(IReadOnlyList<LuaSyntaxToken> input, int begin, int end)
{
while (begin < end && input[begin].IsTrivia)
begin++;
while (end > begin && input[end - 1].IsTrivia)
end--;
var builder = new StringBuilder();
for (int i = begin; i < end; i++)
builder.Append(input[i].Text);
return builder.ToString();
}
}
}
+318
ファイルの表示
@@ -0,0 +1,318 @@
using System.Collections.Generic;
using System.Text;
namespace LuaScript.Compat.Syntax
{
internal sealed class LuaRewriteContext
{
private readonly List<LuaSyntaxToken> _input;
private readonly List<LuaSyntaxToken> _output;
private List<int>? _changedLines;
private int _line = 1;
private int _lastChangedLine;
private int _temporaries;
public LuaRewriteContext(List<LuaSyntaxToken> input)
{
_input = input;
_output = new List<LuaSyntaxToken>(input.Count);
}
public IReadOnlyList<LuaSyntaxToken> Input => _input;
public List<LuaSyntaxToken> Output => _output;
public int Index { get; set; }
public bool Changed { get; private set; }
public int[] ChangedLines => _changedLines is null ? [] : _changedLines.ToArray();
public bool AtEnd => Index >= _input.Count;
public LuaSyntaxToken Current => _input[Index];
public void Advance() => Index++;
public void Emit(LuaSyntaxToken token)
{
_output.Add(token);
if (token.Kind == LuaSyntaxTokenKind.Newline)
_line++;
}
public void EmitRaw(string text)
{
_output.Add(new LuaSyntaxToken(LuaSyntaxTokenKind.Name, text));
MarkChanged();
}
public void EmitOperator(string text)
{
_output.Add(new LuaSyntaxToken(LuaSyntaxTokenKind.Operator, text));
MarkChanged();
}
public string NextTemporary() => "__lc" + _temporaries++;
public int NextSignificant(int from)
{
for (int i = from; i < _input.Count; i++)
{
if (!_input[i].IsTrivia)
return i;
}
return -1;
}
public bool TryPreviousOutputSignificantSameLine(out LuaSyntaxToken token)
{
for (int i = _output.Count - 1; i >= 0; i--)
{
if (_output[i].Kind == LuaSyntaxTokenKind.Newline)
break;
if (_output[i].IsTrivia)
continue;
token = _output[i];
return true;
}
token = default;
return false;
}
public int NextSignificantSameLine(int from)
{
for (int i = from; i < _input.Count; i++)
{
if (_input[i].Kind == LuaSyntaxTokenKind.Newline)
return -1;
if (_input[i].IsTrivia)
continue;
return i;
}
return -1;
}
public void EmitWord(string word)
{
if (_output.Count > 0 && !_output[_output.Count - 1].IsTrivia)
_output.Add(new LuaSyntaxToken(LuaSyntaxTokenKind.Whitespace, " "));
_output.Add(new LuaSyntaxToken(LuaSyntaxTokenKind.Name, word));
if (Index < _input.Count && !_input[Index].IsTrivia)
_output.Add(new LuaSyntaxToken(LuaSyntaxTokenKind.Whitespace, " "));
MarkChanged();
}
private void MarkChanged()
{
Changed = true;
if (_line == _lastChangedLine)
return;
(_changedLines ??= new List<int>()).Add(_line);
_lastChangedLine = _line;
}
public bool TryReadTrailingLvalue(out int start, out string text)
{
start = _output.Count;
text = string.Empty;
int end = _output.Count;
while (end > 0 && _output[end - 1].IsTrivia)
end--;
if (end == 0)
return false;
int depth = 0;
int begin = end;
for (int i = end - 1; i >= 0; i--)
{
var token = _output[i];
if (token.Kind == LuaSyntaxTokenKind.Operator)
{
if (token.Text is ")" or "]" or "}")
{
depth++;
begin = i;
continue;
}
if (token.Text is "(" or "[" or "{")
{
if (depth == 0)
break;
depth--;
begin = i;
continue;
}
if (depth > 0 || token.Text == ".")
{
begin = i;
continue;
}
break;
}
if (token.Kind == LuaSyntaxTokenKind.Name)
{
if (depth == 0 && LuaKeywords.IsReserved(token.Text))
break;
begin = i;
continue;
}
if (depth > 0)
{
begin = i;
continue;
}
break;
}
while (begin < end && _output[begin].IsTrivia)
begin++;
if (begin >= end)
return false;
start = begin;
text = Concat(begin, end);
return true;
}
public bool TryPopOrOperand(out string text)
{
text = string.Empty;
int end = _output.Count;
while (end > 0 && _output[end - 1].IsTrivia)
end--;
if (end == 0)
return false;
int depth = 0;
int begin = end;
for (int i = end - 1; i >= 0; i--)
{
var token = _output[i];
if (token.Kind == LuaSyntaxTokenKind.Operator)
{
if (token.Text is ")" or "]" or "}")
{
depth++;
begin = i;
continue;
}
if (token.Text is "(" or "[" or "{")
{
if (depth == 0)
break;
depth--;
begin = i;
continue;
}
if (depth == 0 && token.Text is "=" or "," or ";")
break;
begin = i;
continue;
}
if (token.Kind == LuaSyntaxTokenKind.Newline && depth == 0)
break;
if (token.Kind == LuaSyntaxTokenKind.Name && depth == 0 && LuaKeywords.IsExpressionBoundary(token.Text))
break;
begin = i;
}
while (begin < end && _output[begin].IsTrivia)
begin++;
if (begin >= end)
return false;
text = Concat(begin, end);
_output.RemoveRange(begin, _output.Count - begin);
return true;
}
public void RemoveOutputFrom(int start) => _output.RemoveRange(start, _output.Count - start);
public bool LastOutputIsTrivia() => _output.Count == 0 || _output[_output.Count - 1].IsTrivia;
public string ReadLineExpression()
{
int start = Index;
int depth = 0;
while (Index < _input.Count)
{
var token = _input[Index];
if (token.Kind == LuaSyntaxTokenKind.Newline && depth == 0)
break;
if (token.Kind == LuaSyntaxTokenKind.Operator)
{
if (token.Text is "(" or "[" or "{")
depth++;
else if (token.Text is ")" or "]" or "}")
{
if (depth == 0)
break;
depth--;
}
else if (depth == 0 && token.Text == ";")
break;
}
Index++;
}
return TrimmedRange(start, Index);
}
public string ReadForwardOrOperand()
{
int start = Index;
int depth = 0;
while (Index < _input.Count)
{
var token = _input[Index];
if (token.Kind == LuaSyntaxTokenKind.Newline && depth == 0)
break;
if (token.Kind == LuaSyntaxTokenKind.Operator)
{
if (token.Text is "(" or "[" or "{")
depth++;
else if (token.Text is ")" or "]" or "}")
{
if (depth == 0)
break;
depth--;
}
else if (depth == 0 && token.Text is "," or ";")
break;
}
else if (token.Kind == LuaSyntaxTokenKind.Name && depth == 0 && LuaKeywords.IsExpressionBoundary(token.Text))
break;
Index++;
}
return TrimmedRange(start, Index);
}
public string Serialize()
{
var builder = new StringBuilder();
foreach (var token in _output)
builder.Append(token.Text);
return builder.ToString();
}
private string Concat(int begin, int end)
{
var builder = new StringBuilder();
for (int i = begin; i < end; i++)
builder.Append(_output[i].Text);
return builder.ToString();
}
private string TrimmedRange(int begin, int end)
{
while (begin < end && _input[begin].IsTrivia)
begin++;
while (end > begin && _input[end - 1].IsTrivia)
end--;
var builder = new StringBuilder();
for (int i = begin; i < end; i++)
builder.Append(_input[i].Text);
return builder.ToString();
}
}
}
+21
ファイルの表示
@@ -0,0 +1,21 @@
namespace LuaScript.Compat.Syntax
{
internal static class LuaSyntaxFacts
{
public static bool IsValueEnd(LuaSyntaxToken token) => token.Kind switch
{
LuaSyntaxTokenKind.Number or LuaSyntaxTokenKind.String => true,
LuaSyntaxTokenKind.Name => !LuaKeywords.IsReserved(token.Text) || token.Text is "nil" or "true" or "false",
LuaSyntaxTokenKind.Operator => token.Text is ")" or "]" or "}",
_ => false,
};
public static bool IsValueStart(LuaSyntaxToken token) => token.Kind switch
{
LuaSyntaxTokenKind.Number or LuaSyntaxTokenKind.String => true,
LuaSyntaxTokenKind.Name => !LuaKeywords.IsReserved(token.Text) || token.Text is "nil" or "true" or "false" or "not" or "function",
LuaSyntaxTokenKind.Operator => token.Text is "(" or "{" or "-" or "#" or "~",
_ => false,
};
}
}
+246
ファイルの表示
@@ -0,0 +1,246 @@
using System.Collections.Generic;
namespace LuaScript.Compat.Syntax
{
internal static class LuaSyntaxLexer
{
private static readonly string[] Operators =
{
"...", "..=", "??=", "||=", "&&=",
"==", "~=", "<=", ">=", "..", "::", "??", "||", "&&", "!=", "++",
"=>", "|>",
"+=", "-=", "*=", "/=", "%=", "^=",
"+", "-", "*", "/", "%", "^", "#", "<", ">", "=",
"(", ")", "{", "}", "[", "]", ";", ":", ",", ".",
"!", "&", "|", "?", "~",
};
public static List<LuaSyntaxToken> Tokenize(string source)
{
var tokens = new List<LuaSyntaxToken>();
int i = 0;
int length = source.Length;
while (i < length)
{
char c = source[i];
if (c == '\r' || c == '\n')
{
int start = i;
if (c == '\r' && i + 1 < length && source[i + 1] == '\n')
i += 2;
else
i++;
tokens.Add(new LuaSyntaxToken(LuaSyntaxTokenKind.Newline, source.Substring(start, i - start)));
continue;
}
if (c == ' ' || c == '\t' || c == '\f' || c == '\v')
{
int start = i;
while (i < length && (source[i] == ' ' || source[i] == '\t' || source[i] == '\f' || source[i] == '\v'))
i++;
tokens.Add(new LuaSyntaxToken(LuaSyntaxTokenKind.Whitespace, source.Substring(start, i - start)));
continue;
}
if (c == '-' && i + 1 < length && source[i + 1] == '-')
{
int start = i;
i = SkipComment(source, i + 2);
tokens.Add(new LuaSyntaxToken(LuaSyntaxTokenKind.Comment, source.Substring(start, i - start)));
continue;
}
if (c == '[')
{
int level = LongBracketLevel(source, i);
if (level >= 0)
{
int start = i;
i = SkipLongBracket(source, i, level);
tokens.Add(new LuaSyntaxToken(LuaSyntaxTokenKind.String, source.Substring(start, i - start)));
continue;
}
}
if (c == '"' || c == '\'')
{
int start = i;
i = SkipShortString(source, i);
tokens.Add(new LuaSyntaxToken(LuaSyntaxTokenKind.String, source.Substring(start, i - start)));
continue;
}
if (c == '`')
{
int start = i;
i = SkipShortString(source, i);
tokens.Add(new LuaSyntaxToken(LuaSyntaxTokenKind.InterpolatedString, source.Substring(start, i - start)));
continue;
}
if (IsDigit(c) || (c == '.' && i + 1 < length && IsDigit(source[i + 1])))
{
int start = i;
i = SkipNumber(source, i);
tokens.Add(new LuaSyntaxToken(LuaSyntaxTokenKind.Number, source.Substring(start, i - start)));
continue;
}
if (IsNameStart(c))
{
int start = i;
while (i < length && IsNamePart(source[i]))
i++;
tokens.Add(new LuaSyntaxToken(LuaSyntaxTokenKind.Name, source.Substring(start, i - start)));
continue;
}
string? op = MatchOperator(source, i);
if (op is not null)
{
tokens.Add(new LuaSyntaxToken(LuaSyntaxTokenKind.Operator, op));
i += op.Length;
continue;
}
tokens.Add(new LuaSyntaxToken(LuaSyntaxTokenKind.Operator, source.Substring(i, 1)));
i++;
}
return tokens;
}
private static string? MatchOperator(string source, int index)
{
int remaining = source.Length - index;
foreach (var op in Operators)
{
if (op.Length > remaining)
continue;
if (string.CompareOrdinal(source, index, op, 0, op.Length) == 0)
return op;
}
return null;
}
private static int SkipNumber(string source, int i)
{
int length = source.Length;
if (source[i] == '0' && i + 1 < length && (source[i + 1] == 'x' || source[i + 1] == 'X'))
{
i += 2;
while (i < length && (IsHexDigit(source[i]) || source[i] == '.'))
i++;
if (i < length && (source[i] == 'p' || source[i] == 'P'))
{
i++;
if (i < length && (source[i] == '+' || source[i] == '-'))
i++;
while (i < length && IsDigit(source[i]))
i++;
}
return i;
}
while (i < length && IsDigit(source[i]))
i++;
if (i < length && source[i] == '.' && !(i + 1 < length && source[i + 1] == '.'))
{
i++;
while (i < length && 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 && IsDigit(source[i]))
i++;
}
return i;
}
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' && source[i] != '\r')
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++;
}
return length;
}
private static int SkipShortString(string source, int start)
{
char quote = source[start];
int i = start + 1;
int length = source.Length;
while (i < length)
{
char c = source[i];
if (c == '\\')
{
i += 2;
continue;
}
if (c == quote)
return i + 1;
if (c == '\n' || c == '\r')
return i;
i++;
}
return length;
}
private static bool IsNameStart(char c) => c == '_' || char.IsLetter(c);
private static bool IsNamePart(char c) => c == '_' || char.IsLetterOrDigit(c);
private static bool IsDigit(char c) => c >= '0' && c <= '9';
private static bool IsHexDigit(char c) => IsDigit(c) || (c >= 'a' && c <= 'f') || (c >= 'A' && c <= 'F');
}
}
+10
ファイルの表示
@@ -0,0 +1,10 @@
using System;
namespace LuaScript.Compat.Syntax
{
[AttributeUsage(AttributeTargets.Class, Inherited = false, AllowMultiple = false)]
internal sealed class LuaSyntaxRuleAttribute(int order) : Attribute
{
public int Order { get; } = order;
}
}
+21
ファイルの表示
@@ -0,0 +1,21 @@
namespace LuaScript.Compat.Syntax
{
internal readonly struct LuaSyntaxToken
{
public LuaSyntaxToken(LuaSyntaxTokenKind kind, string text)
{
Kind = kind;
Text = text;
}
public LuaSyntaxTokenKind Kind { get; }
public string Text { get; }
public bool IsTrivia => Kind is LuaSyntaxTokenKind.Whitespace or LuaSyntaxTokenKind.Newline or LuaSyntaxTokenKind.Comment;
public bool IsName(string value) => Kind == LuaSyntaxTokenKind.Name && Text == value;
public bool IsOperator(string value) => Kind == LuaSyntaxTokenKind.Operator && Text == value;
}
}
+14
ファイルの表示
@@ -0,0 +1,14 @@
namespace LuaScript.Compat.Syntax
{
internal enum LuaSyntaxTokenKind
{
Whitespace,
Newline,
Comment,
String,
InterpolatedString,
Number,
Name,
Operator,
}
}
+73
ファイルの表示
@@ -0,0 +1,73 @@
namespace LuaScript.Compat.Syntax.Rules
{
[LuaSyntaxRule(70)]
internal sealed class AugmentedAssignmentRule : ILuaSyntaxRule
{
public bool TryApply(LuaRewriteContext context)
{
if (context.Current.Kind != LuaSyntaxTokenKind.Operator)
return false;
string? connective = Connective(context.Current.Text);
if (connective is null)
return false;
if (!context.TryReadTrailingLvalue(out _, out string target))
return false;
context.Advance();
string value = context.ReadLineExpression();
string separator = context.LastOutputIsTrivia() ? string.Empty : " ";
context.EmitRaw($"{separator}= {target} {connective} ({value})");
return true;
}
private static string? Connective(string op) => op switch
{
"+=" => "+",
"-=" => "-",
"*=" => "*",
"/=" => "/",
"%=" => "%",
"^=" => "^",
"..=" => "..",
"||=" => "or",
"&&=" => "and",
_ => null,
};
}
[LuaSyntaxRule(80)]
internal sealed class NilCoalesceAssignRule : ILuaSyntaxRule
{
public bool TryApply(LuaRewriteContext context)
{
if (!context.Current.IsOperator("??="))
return false;
if (!context.TryReadTrailingLvalue(out int start, out string target))
return false;
context.RemoveOutputFrom(start);
context.Advance();
string value = context.ReadLineExpression();
context.EmitRaw($"if {target} == nil then {target} = ({value}) end");
return true;
}
}
[LuaSyntaxRule(90)]
internal sealed class IncrementRule : ILuaSyntaxRule
{
public bool TryApply(LuaRewriteContext context)
{
if (!context.Current.IsOperator("++"))
return false;
if (!context.TryReadTrailingLvalue(out _, out string target))
return false;
context.Advance();
string separator = context.LastOutputIsTrivia() ? string.Empty : " ";
context.EmitRaw($"{separator}= {target} + 1");
return true;
}
}
}
+60
ファイルの表示
@@ -0,0 +1,60 @@
namespace LuaScript.Compat.Syntax.Rules
{
[LuaSyntaxRule(10)]
internal sealed class IsNotRule : ILuaSyntaxRule
{
public bool TryApply(LuaRewriteContext context)
{
if (!context.Current.IsName("is"))
return false;
if (!context.TryPreviousOutputSignificantSameLine(out var previous) || !LuaSyntaxFacts.IsValueEnd(previous))
return false;
int notIndex = context.NextSignificantSameLine(context.Index + 1);
if (notIndex < 0 || !context.Input[notIndex].IsName("not"))
return false;
int after = context.NextSignificant(notIndex + 1);
if (after < 0 || !LuaSyntaxFacts.IsValueStart(context.Input[after]))
return false;
context.EmitOperator("~=");
context.Index = notIndex + 1;
return true;
}
}
[LuaSyntaxRule(20)]
internal sealed class IsRule : ILuaSyntaxRule
{
public bool TryApply(LuaRewriteContext context)
{
if (!context.Current.IsName("is"))
return false;
if (!context.TryPreviousOutputSignificantSameLine(out var previous) || !LuaSyntaxFacts.IsValueEnd(previous))
return false;
int next = context.NextSignificantSameLine(context.Index + 1);
if (next < 0 || !LuaSyntaxFacts.IsValueStart(context.Input[next]))
return false;
context.EmitOperator("==");
context.Advance();
return true;
}
}
[LuaSyntaxRule(30)]
internal sealed class NotEqualRule : ILuaSyntaxRule
{
public bool TryApply(LuaRewriteContext context)
{
if (!context.Current.IsOperator("!="))
return false;
context.EmitOperator("~=");
context.Advance();
return true;
}
}
}
+117
ファイルの表示
@@ -0,0 +1,117 @@
using System.Collections.Generic;
using System.Text;
namespace LuaScript.Compat.Syntax.Rules
{
[LuaSyntaxRule(5)]
internal sealed class LuaInterpolatedStringRule : ILuaSyntaxRule
{
public bool TryApply(LuaRewriteContext context)
{
if (context.Current.Kind != LuaSyntaxTokenKind.InterpolatedString)
return false;
string text = context.Current.Text;
int end = text.Length;
if (end >= 2 && text[end - 1] == '`')
end--;
string content = text.Substring(1, end - 1);
var pieces = new List<string>();
var literal = new StringBuilder();
int i = 0;
while (i < content.Length)
{
char c = content[i];
if (c == '\\' && i + 1 < content.Length)
{
literal.Append(content[i]);
literal.Append(content[i + 1]);
i += 2;
continue;
}
if (c == '{')
{
int close = FindClosingBrace(content, i + 1);
if (close < 0)
{
literal.Append(c);
i++;
continue;
}
string expression = content.Substring(i + 1, close - i - 1).Trim();
if (expression.Length > 0)
{
FlushLiteral(pieces, literal);
pieces.Add($"tostring({LuaSyntaxExtensions.Rewrite(expression)})");
}
i = close + 1;
continue;
}
literal.Append(c);
i++;
}
FlushLiteral(pieces, literal);
context.Advance();
if (pieces.Count == 0)
{
context.EmitRaw("\"\"");
return true;
}
if (pieces.Count == 1)
{
context.EmitRaw(pieces[0]);
return true;
}
context.EmitRaw($"({string.Join(" .. ", pieces)})");
return true;
}
private static void FlushLiteral(List<string> pieces, StringBuilder literal)
{
if (literal.Length == 0)
return;
pieces.Add($"\"{literal.ToString().Replace("\"", "\\\"")}\"");
literal.Clear();
}
private static int FindClosingBrace(string content, int from)
{
int depth = 0;
char quote = '\0';
for (int i = from; i < content.Length; i++)
{
char c = content[i];
if (quote != '\0')
{
if (c == '\\')
{
i++;
continue;
}
if (c == quote)
quote = '\0';
continue;
}
if (c == '"' || c == '\'')
{
quote = c;
continue;
}
if (c == '{')
{
depth++;
continue;
}
if (c == '}')
{
if (depth == 0)
return i;
depth--;
}
}
return -1;
}
}
}
+74
ファイルの表示
@@ -0,0 +1,74 @@
namespace LuaScript.Compat.Syntax.Rules
{
[LuaSyntaxRule(35)]
internal sealed class LuaLambdaRule : ILuaSyntaxRule
{
public bool TryApply(LuaRewriteContext context)
{
if (!context.Current.IsOperator("=>"))
return false;
if (!context.TryReadTrailingLvalue(out int start, out string target))
return false;
if (!TryNormalizeParameters(target, out string parameters))
return false;
int body = context.NextSignificant(context.Index + 1);
if (body < 0 || !LuaSyntaxFacts.IsValueStart(context.Input[body]))
return false;
context.RemoveOutputFrom(start);
context.Advance();
string expression = context.ReadForwardOrOperand();
if (expression.Length == 0)
return false;
context.EmitRaw($"(function({parameters}) return {LuaSyntaxExtensions.Rewrite(expression)} end)");
return true;
}
private static bool TryNormalizeParameters(string text, out string parameters)
{
parameters = string.Empty;
text = text.Trim();
bool wrapped = text.StartsWith("(") && text.EndsWith(")");
if (wrapped)
text = text.Substring(1, text.Length - 2).Trim();
if (text.Length == 0)
return wrapped;
var names = text.Split(',');
for (int i = 0; i < names.Length; i++)
{
string name = names[i].Trim();
if (name == "...")
{
if (i != names.Length - 1)
return false;
continue;
}
if (!IsName(name) || LuaKeywords.IsReserved(name))
return false;
if (!wrapped && names.Length > 1)
return false;
}
parameters = string.Join(", ", System.Array.ConvertAll(names, static n => n.Trim()));
return true;
}
private static bool IsName(string text)
{
if (text.Length == 0)
return false;
if (text[0] != '_' && !char.IsLetter(text[0]))
return false;
for (int i = 1; i < text.Length; i++)
{
if (text[i] != '_' && !char.IsLetterOrDigit(text[i]))
return false;
}
return true;
}
}
}
+44
ファイルの表示
@@ -0,0 +1,44 @@
namespace LuaScript.Compat.Syntax.Rules
{
[LuaSyntaxRule(40)]
internal sealed class LogicalNotRule : ILuaSyntaxRule
{
public bool TryApply(LuaRewriteContext context)
{
if (!context.Current.IsOperator("!"))
return false;
context.Advance();
context.EmitWord("not");
return true;
}
}
[LuaSyntaxRule(50)]
internal sealed class AndAliasRule : ILuaSyntaxRule
{
public bool TryApply(LuaRewriteContext context)
{
if (!context.Current.IsOperator("&&"))
return false;
context.Advance();
context.EmitWord("and");
return true;
}
}
[LuaSyntaxRule(60)]
internal sealed class OrAliasRule : ILuaSyntaxRule
{
public bool TryApply(LuaRewriteContext context)
{
if (!context.Current.IsOperator("||"))
return false;
context.Advance();
context.EmitWord("or");
return true;
}
}
}
+20
ファイルの表示
@@ -0,0 +1,20 @@
namespace LuaScript.Compat.Syntax.Rules
{
[LuaSyntaxRule(100)]
internal sealed class NilCoalesceRule : ILuaSyntaxRule
{
public bool TryApply(LuaRewriteContext context)
{
if (!context.Current.IsOperator("??"))
return false;
if (!context.TryPopOrOperand(out string left))
return false;
context.Advance();
string right = context.ReadForwardOrOperand();
string temporary = context.NextTemporary();
context.EmitRaw($"(function() local {temporary} = ({left}) if {temporary} ~= nil then return {temporary} else return ({right}) end end)()");
return true;
}
}
}
+26
ファイルの表示
@@ -0,0 +1,26 @@
namespace LuaScript.Compat.Syntax.Rules
{
[LuaSyntaxRule(110)]
internal sealed class LuaNumericRangeRule : ILuaSyntaxRule
{
public bool TryApply(LuaRewriteContext context)
{
if (!context.Current.IsName("in"))
return false;
int open = context.NextSignificant(context.Index + 1);
if (open < 0 || !context.Input[open].IsOperator("<"))
return false;
if (!LuaRangeSyntax.TryParse(context.Input, open, out var parts, out int end))
return false;
string stopExpression = parts.Exclusive ? $"({parts.Stop}) - 1" : parts.Stop;
string replacement = parts.Step is null
? $"= {parts.Start}, {stopExpression}"
: $"= {parts.Start}, {stopExpression}, {parts.Step}";
context.EmitRaw(replacement);
context.Index = end;
return true;
}
}
}
+122
ファイルの表示
@@ -0,0 +1,122 @@
using System.Collections.Generic;
using System.Text;
namespace LuaScript.Compat.Syntax.Rules
{
[LuaSyntaxRule(98)]
internal sealed class LuaPipeRule : ILuaSyntaxRule
{
public bool TryApply(LuaRewriteContext context)
{
if (!context.Current.IsOperator("|>"))
return false;
int targetStart = context.NextSignificant(context.Index + 1);
if (targetStart < 0 || !LuaSyntaxFacts.IsValueStart(context.Input[targetStart]))
return false;
if (!context.TryPopOrOperand(out string left))
return false;
context.Advance();
var segment = ReadSegment(context);
string call = BuildCall(segment, left);
context.EmitRaw(call);
return true;
}
private static List<LuaSyntaxToken> ReadSegment(LuaRewriteContext context)
{
var tokens = new List<LuaSyntaxToken>();
int depth = 0;
while (!context.AtEnd)
{
var token = context.Current;
if (token.Kind == LuaSyntaxTokenKind.Newline && depth == 0)
break;
if (token.Kind == LuaSyntaxTokenKind.Name && depth == 0 && LuaKeywords.IsExpressionBoundary(token.Text))
break;
if (token.Kind == LuaSyntaxTokenKind.Operator)
{
if (token.Text is "(" or "[" or "{")
{
depth++;
}
else if (token.Text is ")" or "]" or "}")
{
if (depth == 0)
break;
depth--;
}
else if (depth == 0 && token.Text is "," or ";" or "|>")
{
break;
}
}
tokens.Add(token);
context.Advance();
}
while (tokens.Count > 0 && tokens[0].IsTrivia)
tokens.RemoveAt(0);
while (tokens.Count > 0 && tokens[tokens.Count - 1].IsTrivia)
tokens.RemoveAt(tokens.Count - 1);
return tokens;
}
private static string BuildCall(List<LuaSyntaxToken> segment, string left)
{
string argument = $"({left})";
if (segment.Count == 0)
return argument;
if (segment[segment.Count - 1].IsOperator(")"))
{
int open = FindOpeningParen(segment);
if (open > 0)
{
string callee = Concat(segment, 0, open);
string arguments = Concat(segment, open + 1, segment.Count - 1);
return arguments.Length == 0
? $"{callee}({argument})"
: $"{callee}({argument}, {arguments})";
}
}
return $"{Concat(segment, 0, segment.Count)}({argument})";
}
private static int FindOpeningParen(List<LuaSyntaxToken> segment)
{
int depth = 0;
for (int i = segment.Count - 1; i >= 0; i--)
{
var token = segment[i];
if (token.Kind != LuaSyntaxTokenKind.Operator)
continue;
if (token.Text is ")" or "]" or "}")
{
depth++;
}
else if (token.Text is "(" or "[" or "{")
{
depth--;
if (depth == 0)
return token.Text == "(" ? i : -1;
}
}
return -1;
}
private static string Concat(List<LuaSyntaxToken> segment, int begin, int end)
{
while (begin < end && segment[begin].IsTrivia)
begin++;
while (end > begin && segment[end - 1].IsTrivia)
end--;
var builder = new StringBuilder();
for (int i = begin; i < end; i++)
builder.Append(segment[i].Text);
return builder.ToString();
}
}
}
+49
ファイルの表示
@@ -0,0 +1,49 @@
namespace LuaScript.Compat.Syntax.Rules
{
[LuaSyntaxRule(108)]
internal sealed class LuaRangeMembershipRule : ILuaSyntaxRule
{
public bool TryApply(LuaRewriteContext context)
{
if (!context.Current.IsName("in"))
return false;
if (IsForHeader(context))
return false;
int open = context.NextSignificant(context.Index + 1);
if (open < 0 || !context.Input[open].IsOperator("<"))
return false;
if (!LuaRangeSyntax.TryParse(context.Input, open, out var parts, out int end))
return false;
if (parts.Step is not null)
return false;
if (!context.TryPopOrOperand(out string left))
return false;
string temporary = context.NextTemporary();
string upper = parts.Exclusive ? "<" : "<=";
context.EmitRaw($"(function() local {temporary} = ({left}) return {temporary} >= ({LuaSyntaxExtensions.Rewrite(parts.Start)}) and {temporary} {upper} ({LuaSyntaxExtensions.Rewrite(parts.Stop)}) end)()");
context.Index = end;
return true;
}
private static bool IsForHeader(LuaRewriteContext context)
{
var output = context.Output;
for (int i = output.Count - 1; i >= 0; i--)
{
var token = output[i];
if (token.Kind == LuaSyntaxTokenKind.Newline)
return false;
if (token.Kind != LuaSyntaxTokenKind.Name)
continue;
if (token.Text is "do" or "then")
return false;
if (token.Text == "for")
return true;
}
return false;
}
}
}
+105
ファイルの表示
@@ -0,0 +1,105 @@
using System.Text;
namespace LuaScript.Compat.Syntax.Rules
{
[LuaSyntaxRule(92)]
internal sealed class LuaSafeNavigationRule : ILuaSyntaxRule
{
public bool TryApply(LuaRewriteContext context)
{
if (!context.Current.IsOperator("?"))
return false;
int accessor = context.NextSignificantSameLine(context.Index + 1);
if (accessor < 0)
return false;
if (context.Input[accessor].IsOperator("."))
return TryApplyMember(context, accessor);
if (context.Input[accessor].IsOperator("["))
return TryApplyIndex(context, accessor);
return false;
}
private static bool TryApplyMember(LuaRewriteContext context, int accessor)
{
int name = context.NextSignificantSameLine(accessor + 1);
if (name < 0)
return false;
var token = context.Input[name];
if (token.Kind != LuaSyntaxTokenKind.Name || LuaKeywords.IsReserved(token.Text))
return false;
if (!context.TryReadTrailingLvalue(out int start, out string target))
return false;
context.RemoveOutputFrom(start);
context.Index = name + 1;
string temporary = context.NextTemporary();
context.EmitRaw($"(function() local {temporary} = ({target}) if {temporary} == nil then return nil end return {temporary}.{token.Text} end)()");
return true;
}
private static bool TryApplyIndex(LuaRewriteContext context, int accessor)
{
int close = FindClosingBracket(context, accessor + 1);
if (close < 0)
return false;
string key = Concat(context, accessor + 1, close);
if (key.Length == 0)
return false;
if (!context.TryReadTrailingLvalue(out int start, out string target))
return false;
context.RemoveOutputFrom(start);
context.Index = close + 1;
string temporary = context.NextTemporary();
context.EmitRaw($"(function() local {temporary} = ({target}) if {temporary} == nil then return nil end return {temporary}[{LuaSyntaxExtensions.Rewrite(key)}] end)()");
return true;
}
private static int FindClosingBracket(LuaRewriteContext context, int from)
{
int depth = 0;
for (int i = from; i < context.Input.Count; i++)
{
var token = context.Input[i];
if (token.Kind != LuaSyntaxTokenKind.Operator)
continue;
if (token.Text is "(" or "[" or "{")
{
depth++;
continue;
}
if (token.Text is ")" or "}")
{
if (depth == 0)
return -1;
depth--;
continue;
}
if (token.Text == "]")
{
if (depth == 0)
return i;
depth--;
}
}
return -1;
}
private static string Concat(LuaRewriteContext context, int begin, int end)
{
while (begin < end && context.Input[begin].IsTrivia)
begin++;
while (end > begin && context.Input[end - 1].IsTrivia)
end--;
var builder = new StringBuilder();
for (int i = begin; i < end; i++)
builder.Append(context.Input[i].Text);
return builder.ToString();
}
}
}
+85
ファイルの表示
@@ -0,0 +1,85 @@
namespace LuaScript.Compat.Syntax.Rules
{
[LuaSyntaxRule(96)]
internal sealed class LuaTernaryRule : ILuaSyntaxRule
{
public bool TryApply(LuaRewriteContext context)
{
if (!context.Current.IsOperator("?"))
return false;
if (!context.TryPreviousOutputSignificantSameLine(out var previous) || !LuaSyntaxFacts.IsValueEnd(previous))
return false;
int thenStart = context.NextSignificantSameLine(context.Index + 1);
if (thenStart < 0 || !LuaSyntaxFacts.IsValueStart(context.Input[thenStart]))
return false;
int colon = FindColon(context, context.Index + 1);
if (colon < 0)
return false;
int elseStart = context.NextSignificantSameLine(colon + 1);
if (elseStart < 0 || !LuaSyntaxFacts.IsValueStart(context.Input[elseStart]))
return false;
if (!context.TryPopOrOperand(out string condition))
return false;
context.Index++;
string thenExpression = ReadUntil(context, colon);
context.Index = colon + 1;
string elseExpression = context.ReadForwardOrOperand();
context.EmitRaw($"(function() if {condition} then return ({LuaSyntaxExtensions.Rewrite(thenExpression)}) else return ({LuaSyntaxExtensions.Rewrite(elseExpression)}) end end)()");
return true;
}
private static int FindColon(LuaRewriteContext context, int from)
{
int depth = 0;
for (int i = from; i < context.Input.Count; i++)
{
var token = context.Input[i];
if (token.Kind == LuaSyntaxTokenKind.Newline)
return -1;
if (token.Kind == LuaSyntaxTokenKind.Name && depth == 0 && LuaKeywords.IsExpressionBoundary(token.Text))
return -1;
if (token.Kind != LuaSyntaxTokenKind.Operator)
continue;
if (token.Text is "(" or "[" or "{")
{
depth++;
continue;
}
if (token.Text is ")" or "]" or "}")
{
if (depth == 0)
return -1;
depth--;
continue;
}
if (depth > 0)
continue;
if (token.Text is "," or ";" or "?")
return -1;
if (token.Text == ":")
return i;
}
return -1;
}
private static string ReadUntil(LuaRewriteContext context, int stop)
{
var builder = new System.Text.StringBuilder();
int begin = context.Index;
int end = stop;
while (begin < end && context.Input[begin].IsTrivia)
begin++;
while (end > begin && context.Input[end - 1].IsTrivia)
end--;
for (int i = begin; i < end; i++)
builder.Append(context.Input[i].Text);
return builder.ToString();
}
}
}
+45
ファイルの表示
@@ -0,0 +1,45 @@
using System.Collections;
namespace LuaScript.Generator
{
internal readonly struct EquatableArray<T>(T[] items) : IEquatable<EquatableArray<T>>, IReadOnlyList<T>
where T : IEquatable<T>
{
private readonly T[] _items = items;
public static readonly EquatableArray<T> Empty = new([]);
public int Count => _items?.Length ?? 0;
public T this[int index] => _items[index];
public bool Equals(EquatableArray<T> other)
{
var a = _items ?? [];
var b = other._items ?? [];
if (a.Length != b.Length)
return false;
for (int i = 0; i < a.Length; i++)
{
if (!a[i].Equals(b[i]))
return false;
}
return true;
}
public override bool Equals(object? obj) => obj is EquatableArray<T> other && Equals(other);
public override int GetHashCode()
{
var items = _items ?? [];
int hash = 17;
foreach (var item in items)
hash = hash * 31 + (item?.GetHashCode() ?? 0);
return hash;
}
public IEnumerator<T> GetEnumerator() => ((IEnumerable<T>)(_items ?? [])).GetEnumerator();
IEnumerator IEnumerable.GetEnumerator() => GetEnumerator();
}
}
+4
ファイルの表示
@@ -0,0 +1,4 @@
namespace System.Runtime.CompilerServices
{
internal static class IsExternalInit;
}
+486
ファイルの表示
@@ -0,0 +1,486 @@
using System.Text;
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.CSharp.Syntax;
using Microsoft.CodeAnalysis.Text;
namespace LuaScript.Generator
{
internal enum LuaParameterKind
{
ExecutionContext,
Arguments,
DynValue,
Double,
Int,
Bool,
}
internal enum LuaReturnKind
{
DynValue,
Double,
Void,
}
internal sealed record LuaParameterModel(string Name, LuaParameterKind Kind, string DefaultLiteral);
internal sealed record LuaFunctionModel(
string LuaName,
string MethodName,
LuaReturnKind ReturnKind,
EquatableArray<LuaParameterModel> Parameters);
internal sealed record LuaConstantModel(string LuaName, string MemberName);
internal enum LuaUpdateKind
{
Direct,
OptionalValue,
OptionalReference,
}
internal sealed record LuaUpdateModel(string LuaName, string MethodName, LuaUpdateKind Kind);
internal sealed record LuaCatalogEntry(
string Table,
string Name,
bool IsFunction,
EquatableArray<string> Parameters);
internal sealed record LuaTypePart(string Name, bool IsStatic);
internal sealed record LuaTableModel(
string Namespace,
EquatableArray<LuaTypePart> TypeChain,
string TableName,
string ContextType,
EquatableArray<LuaFunctionModel> Functions,
EquatableArray<LuaConstantModel> Constants,
EquatableArray<LuaUpdateModel> Updates,
EquatableArray<LuaCatalogEntry> Entries);
[Generator]
public sealed class LuaApiGenerator : IIncrementalGenerator
{
private const string TableAttributeName = "LuaScript.Api.LuaTableAttribute";
private const string FunctionAttributeName = "LuaScript.Api.LuaFunctionAttribute";
private const string ConstantAttributeName = "LuaScript.Api.LuaConstantAttribute";
private const string VariableAttributeName = "LuaScript.Api.LuaVariableAttribute";
private const string BuiltinAttributeName = "LuaScript.Api.LuaBuiltinAttribute";
public void Initialize(IncrementalGeneratorInitializationContext context)
{
var tables = context.SyntaxProvider
.ForAttributeWithMetadataName(
TableAttributeName,
static (node, _) => node is ClassDeclarationSyntax,
static (ctx, _) => CreateModel(ctx))
.Where(static model => model is not null)
.Select(static (model, _) => model!);
var assemblyEntries = context.CompilationProvider
.Select(static (compilation, _) => CollectAssemblyEntries(compilation));
context.RegisterSourceOutput(tables, static (ctx, model) =>
{
if (model.Functions.Count == 0 && model.Constants.Count == 0 && model.Updates.Count == 0)
return;
ctx.AddSource(RegistrationHintName(model), SourceText.From(EmitRegistration(model), Encoding.UTF8));
});
var catalog = tables.Collect().Combine(assemblyEntries);
context.RegisterSourceOutput(catalog, static (ctx, source) =>
{
var (models, extra) = source;
var entries = models
.OrderBy(static m => m.Namespace, StringComparer.Ordinal)
.ThenBy(static m => string.Join("+", m.TypeChain.Select(static p => p.Name)), StringComparer.Ordinal)
.SelectMany(static m => m.Entries)
.Concat(extra)
.ToArray();
if (entries.Length == 0)
return;
ctx.AddSource("LuaApiCatalog.g.cs", SourceText.From(EmitCatalog(entries), Encoding.UTF8));
});
}
private static LuaTableModel? CreateModel(GeneratorAttributeSyntaxContext context)
{
if (context.TargetSymbol is not INamedTypeSymbol symbol)
return null;
var tableArguments = context.Attributes[0].ConstructorArguments;
string tableName = tableArguments.Length > 0 && tableArguments[0].Value is string name ? name : string.Empty;
var chain = new List<LuaTypePart>();
for (var type = symbol; type is not null; type = type.ContainingType)
chain.Insert(0, new LuaTypePart(type.Name, type.IsStatic));
var entries = new List<(int Position, LuaCatalogEntry Entry)>();
foreach (var attribute in symbol.GetAttributes())
{
string? attributeName = attribute.AttributeClass?.ToDisplayString();
if (attributeName is not (VariableAttributeName or BuiltinAttributeName or FunctionAttributeName))
continue;
var entry = CreateAttributeEntry(attribute, tableName);
if (entry is null)
continue;
int position = attribute.ApplicationSyntaxReference?.Span.Start ?? 0;
entries.Add((position, entry));
}
var classEntries = entries.OrderBy(static e => e.Position).Select(static e => e.Entry).ToList();
var functions = new List<(int Position, LuaFunctionModel Function, LuaCatalogEntry Entry)>();
var constants = new List<(int Position, LuaConstantModel Constant, LuaCatalogEntry Entry)>();
var updates = new List<(int Position, LuaUpdateModel Update, LuaCatalogEntry? Entry)>();
string contextType = string.Empty;
foreach (var member in symbol.GetMembers())
{
int position = member.DeclaringSyntaxReferences.Length > 0
? member.DeclaringSyntaxReferences[0].Span.Start
: 0;
if (member is IMethodSymbol method)
{
var functionAttribute = FindAttribute(method, FunctionAttributeName);
if (functionAttribute is not null)
{
var function = CreateFunctionModel(method, functionAttribute, out var catalogParameters);
if (function is null)
continue;
functions.Add((position, function, new LuaCatalogEntry(tableName, function.LuaName, true, catalogParameters)));
continue;
}
var variableAttribute = FindAttribute(method, VariableAttributeName);
if (variableAttribute is not null)
{
var update = CreateUpdateModel(method, variableAttribute, tableName, ref contextType, out var entry);
if (update is not null)
updates.Add((position, update, entry));
}
continue;
}
if (member is IFieldSymbol or IPropertySymbol)
{
var attribute = FindAttribute(member, ConstantAttributeName);
if (attribute is null)
continue;
if (attribute.ConstructorArguments.Length == 0 || attribute.ConstructorArguments[0].Value is not string constantName)
continue;
constants.Add((
position,
new LuaConstantModel(constantName, member.Name),
new LuaCatalogEntry(tableName, constantName, false, EquatableArray<string>.Empty)));
}
}
var orderedMembers = functions
.Select(static f => (Position: f.Position, Entry: f.Entry))
.Concat(constants.Select(static c => (Position: c.Position, Entry: c.Entry)))
.Concat(updates.Where(static u => u.Entry is not null).Select(static u => (Position: u.Position, Entry: u.Entry!)))
.OrderBy(static e => e.Position)
.Select(static e => e.Entry);
return new LuaTableModel(
symbol.ContainingNamespace.ToDisplayString(),
new EquatableArray<LuaTypePart>([.. chain]),
tableName,
contextType,
new EquatableArray<LuaFunctionModel>([.. functions.OrderBy(static f => f.Position).Select(static f => f.Function)]),
new EquatableArray<LuaConstantModel>([.. constants.OrderBy(static c => c.Position).Select(static c => c.Constant)]),
new EquatableArray<LuaUpdateModel>([.. updates.OrderBy(static u => u.Position).Select(static u => u.Update)]),
new EquatableArray<LuaCatalogEntry>([.. classEntries, .. orderedMembers]));
}
private static AttributeData? FindAttribute(ISymbol symbol, string attributeName)
{
foreach (var attribute in symbol.GetAttributes())
{
if (attribute.AttributeClass?.ToDisplayString() == attributeName)
return attribute;
}
return null;
}
private static LuaCatalogEntry? CreateAttributeEntry(AttributeData attribute, string defaultTable)
{
if (attribute.ConstructorArguments.Length == 0 || attribute.ConstructorArguments[0].Value is not string name)
return null;
string table = defaultTable;
foreach (var argument in attribute.NamedArguments)
{
if (argument.Key == "Table" && argument.Value.Value is string overridden)
table = overridden;
}
bool isFunction = attribute.AttributeClass?.ToDisplayString() is (BuiltinAttributeName or FunctionAttributeName);
var parameters = isFunction && attribute.ConstructorArguments.Length > 1
? ExtractStringArray(attribute.ConstructorArguments[1])
: EquatableArray<string>.Empty;
return new LuaCatalogEntry(table, name, isFunction, parameters);
}
private static EquatableArray<string> ExtractStringArray(TypedConstant constant)
{
if (constant.Kind != TypedConstantKind.Array)
return EquatableArray<string>.Empty;
return new EquatableArray<string>([.. constant.Values.Select(static v => v.Value as string ?? string.Empty)]);
}
private static LuaFunctionModel? CreateFunctionModel(IMethodSymbol method, AttributeData attribute, out EquatableArray<string> catalogParameters)
{
catalogParameters = EquatableArray<string>.Empty;
if (attribute.ConstructorArguments.Length == 0 || attribute.ConstructorArguments[0].Value is not string luaName)
return null;
LuaReturnKind returnKind;
if (method.ReturnsVoid)
returnKind = LuaReturnKind.Void;
else if (method.ReturnType.ToDisplayString() == "MoonSharp.Interpreter.DynValue")
returnKind = LuaReturnKind.DynValue;
else if (method.ReturnType.SpecialType == SpecialType.System_Double)
returnKind = LuaReturnKind.Double;
else
return null;
var parameters = new List<LuaParameterModel>();
foreach (var parameter in method.Parameters)
{
LuaParameterKind kind;
string defaultLiteral = string.Empty;
switch (parameter.Type.ToDisplayString())
{
case "MoonSharp.Interpreter.ScriptExecutionContext":
kind = LuaParameterKind.ExecutionContext;
break;
case "MoonSharp.Interpreter.CallbackArguments":
kind = LuaParameterKind.Arguments;
break;
case "MoonSharp.Interpreter.DynValue":
kind = LuaParameterKind.DynValue;
break;
case "double":
kind = LuaParameterKind.Double;
defaultLiteral = FormatDouble(parameter.HasExplicitDefaultValue ? (double)parameter.ExplicitDefaultValue! : 0d);
break;
case "int":
kind = LuaParameterKind.Int;
defaultLiteral = FormatDouble(parameter.HasExplicitDefaultValue ? (int)parameter.ExplicitDefaultValue! : 0);
break;
case "bool":
kind = LuaParameterKind.Bool;
defaultLiteral = parameter.HasExplicitDefaultValue && (bool)parameter.ExplicitDefaultValue! ? "true" : "false";
break;
default:
return null;
}
parameters.Add(new LuaParameterModel(parameter.Name, kind, defaultLiteral));
}
var explicitParameters = attribute.ConstructorArguments.Length > 1
? ExtractStringArray(attribute.ConstructorArguments[1])
: EquatableArray<string>.Empty;
catalogParameters = explicitParameters.Count > 0
? explicitParameters
: new EquatableArray<string>([.. parameters
.Where(static p => p.Kind is not (LuaParameterKind.ExecutionContext or LuaParameterKind.Arguments))
.Select(static p => p.Name)]);
return new LuaFunctionModel(luaName, method.Name, returnKind, new EquatableArray<LuaParameterModel>([.. parameters]));
}
private static LuaUpdateModel? CreateUpdateModel(IMethodSymbol method, AttributeData attribute, string tableName, ref string contextType, out LuaCatalogEntry? entry)
{
entry = null;
if (attribute.ConstructorArguments.Length == 0 || attribute.ConstructorArguments[0].Value is not string luaName)
return null;
if (method.Parameters.Length != 1)
return null;
string parameterType = method.Parameters[0].Type.ToDisplayString();
if (contextType.Length == 0)
contextType = parameterType;
else if (contextType != parameterType)
return null;
var returnType = method.ReturnType;
LuaUpdateKind kind;
if (returnType.OriginalDefinition.SpecialType == SpecialType.System_Nullable_T)
kind = LuaUpdateKind.OptionalValue;
else if (returnType.IsReferenceType)
kind = LuaUpdateKind.OptionalReference;
else
kind = LuaUpdateKind.Direct;
bool inCatalog = true;
foreach (var argument in attribute.NamedArguments)
{
if (argument.Key == "InCatalog" && argument.Value.Value is bool value)
inCatalog = value;
}
if (inCatalog)
entry = new LuaCatalogEntry(tableName, luaName, false, EquatableArray<string>.Empty);
return new LuaUpdateModel(luaName, method.Name, kind);
}
private static string FormatDouble(double value) =>
value.ToString("R", System.Globalization.CultureInfo.InvariantCulture) + "d";
private static string RegistrationHintName(LuaTableModel model)
{
var chain = string.Join(".", model.TypeChain.Select(static p => p.Name));
return $"{model.Namespace}.{chain}.LuaRegistration.g.cs";
}
private static string EmitRegistration(LuaTableModel model)
{
var builder = new StringBuilder();
builder.AppendLine("#nullable enable");
builder.AppendLine($"namespace {model.Namespace}");
builder.AppendLine("{");
string indent = " ";
foreach (var part in model.TypeChain)
{
builder.AppendLine($"{indent}{(part.IsStatic ? "static partial class " : "partial class ")}{part.Name}");
builder.AppendLine($"{indent}{{");
indent += " ";
}
bool isStatic = model.TypeChain[model.TypeChain.Count - 1].IsStatic;
string body = indent + " ";
if (model.Constants.Count > 0 || model.Functions.Count > 0)
{
builder.AppendLine($"{indent}internal {(isStatic ? "static " : "")}void RegisterLuaMembers(global::MoonSharp.Interpreter.Table table)");
builder.AppendLine($"{indent}{{");
foreach (var constant in model.Constants)
builder.AppendLine($"{body}table[\"{constant.LuaName}\"] = {constant.MemberName};");
foreach (var function in model.Functions)
{
string call = $"{function.MethodName}({EmitArguments(function.Parameters)})";
string lambda = function.ReturnKind switch
{
LuaReturnKind.DynValue => $"(execCtx, args) => {call}",
LuaReturnKind.Double => $"(execCtx, args) => global::MoonSharp.Interpreter.DynValue.NewNumber({call})",
_ => $"(execCtx, args) => {{ {call}; return global::MoonSharp.Interpreter.DynValue.Void; }}",
};
builder.AppendLine($"{body}table[\"{function.LuaName}\"] = global::MoonSharp.Interpreter.DynValue.NewCallback({lambda});");
}
builder.AppendLine($"{indent}}}");
}
if (model.Updates.Count > 0)
{
builder.AppendLine($"{indent}internal {(isStatic ? "static " : "")}void UpdateLuaMembers(global::MoonSharp.Interpreter.Table table, global::{model.ContextType} context)");
builder.AppendLine($"{indent}{{");
foreach (var update in model.Updates)
{
switch (update.Kind)
{
case LuaUpdateKind.OptionalValue:
builder.AppendLine($"{body}{{ var value = {update.MethodName}(context); if (value.HasValue) table[\"{update.LuaName}\"] = value.Value; }}");
break;
case LuaUpdateKind.OptionalReference:
builder.AppendLine($"{body}{{ var value = {update.MethodName}(context); if (value is not null) table[\"{update.LuaName}\"] = value; }}");
break;
default:
builder.AppendLine($"{body}table[\"{update.LuaName}\"] = {update.MethodName}(context);");
break;
}
}
builder.AppendLine($"{indent}}}");
}
for (int i = model.TypeChain.Count - 1; i >= 0; i--)
{
indent = new string(' ', 4 * (i + 1));
builder.AppendLine($"{indent}}}");
}
builder.AppendLine("}");
return builder.ToString();
}
private static string EmitArguments(EquatableArray<LuaParameterModel> parameters)
{
var rendered = new List<string>();
int position = 0;
foreach (var parameter in parameters)
{
if (parameter.Kind == LuaParameterKind.ExecutionContext)
{
rendered.Add("execCtx");
continue;
}
if (parameter.Kind == LuaParameterKind.Arguments)
{
rendered.Add("args");
continue;
}
rendered.Add(parameter.Kind switch
{
LuaParameterKind.DynValue => $"args.Count > {position} ? args[{position}] : global::MoonSharp.Interpreter.DynValue.Nil",
LuaParameterKind.Double => $"args.Count > {position} ? args[{position}].CastToNumber() ?? {parameter.DefaultLiteral} : {parameter.DefaultLiteral}",
LuaParameterKind.Int => $"(int)(args.Count > {position} ? args[{position}].CastToNumber() ?? {parameter.DefaultLiteral} : {parameter.DefaultLiteral})",
_ => $"args.Count > {position} ? args[{position}].CastToBool() : {parameter.DefaultLiteral}",
});
position++;
}
return string.Join(", ", rendered);
}
private static string EmitCatalog(LuaCatalogEntry[] entries)
{
var builder = new StringBuilder();
builder.AppendLine("#nullable enable");
builder.AppendLine("namespace LuaScript.Generated");
builder.AppendLine("{");
builder.AppendLine(" internal static class LuaApiModuleInitializer");
builder.AppendLine(" {");
builder.AppendLine(" [global::System.Runtime.CompilerServices.ModuleInitializer]");
builder.AppendLine(" internal static void Initialize()");
builder.AppendLine(" {");
builder.AppendLine(" global::LuaScript.Api.LuaApiCatalog.Register(new global::LuaScript.Api.LuaApiMember[]");
builder.AppendLine(" {");
foreach (var entry in entries)
{
string kind = entry.IsFunction
? "global::LuaScript.Api.LuaApiMemberKind.Function"
: "global::LuaScript.Api.LuaApiMemberKind.Variable";
string parameters = entry.Parameters.Count == 0
? "global::System.Array.Empty<string>()"
: $"new string[] {{ {string.Join(", ", entry.Parameters.Select(static p => $"\"{p}\""))} }}";
builder.AppendLine($" new(\"{entry.Table}\", \"{entry.Name}\", {kind}, {parameters}),");
}
builder.AppendLine(" });");
builder.AppendLine(" }");
builder.AppendLine(" }");
builder.AppendLine("}");
return builder.ToString();
}
private static IReadOnlyList<LuaCatalogEntry> CollectAssemblyEntries(Compilation compilation)
{
var entries = new List<(int Position, LuaCatalogEntry Entry)>();
foreach (var attribute in compilation.Assembly.GetAttributes())
{
string? attributeName = attribute.AttributeClass?.ToDisplayString();
if (attributeName is not (VariableAttributeName or BuiltinAttributeName or FunctionAttributeName))
continue;
var entry = CreateAttributeEntry(attribute, string.Empty);
if (entry is null)
continue;
entries.Add((attribute.ApplicationSyntaxReference?.Span.Start ?? 0, entry));
}
return [.. entries.OrderBy(static e => e.Position).Select(static e => e.Entry)];
}
}
}
+21
ファイルの表示
@@ -0,0 +1,21 @@
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<TargetFramework>netstandard2.0</TargetFramework>
<LangVersion>latest</LangVersion>
<Nullable>enable</Nullable>
<ImplicitUsings>enable</ImplicitUsings>
<Version>1.16.0</Version>
<IsRoslynComponent>true</IsRoslynComponent>
<EnforceExtendedAnalyzerRules>true</EnforceExtendedAnalyzerRules>
</PropertyGroup>
<ItemGroup>
<PackageReference Include="Microsoft.CodeAnalysis.Analyzers" Version="5.3.0">
<PrivateAssets>all</PrivateAssets>
<IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets>
</PackageReference>
<PackageReference Include="Microsoft.CodeAnalysis.CSharp" Version="5.3.0" PrivateAssets="all" />
</ItemGroup>
</Project>
+76
ファイルの表示
@@ -0,0 +1,76 @@
using System;
using System.Collections.Immutable;
using System.Linq;
using System.Text;
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.CSharp.Syntax;
using Microsoft.CodeAnalysis.Text;
namespace LuaScript.Generator
{
internal sealed record LuaSyntaxRuleModel(string TypeName, int Order);
[Generator]
public sealed class LuaSyntaxRuleGenerator : IIncrementalGenerator
{
private const string RuleAttributeName = "LuaScript.Compat.Syntax.LuaSyntaxRuleAttribute";
private const string RuleInterfaceName = "LuaScript.Compat.Syntax.ILuaSyntaxRule";
public void Initialize(IncrementalGeneratorInitializationContext context)
{
var rules = context.SyntaxProvider
.ForAttributeWithMetadataName(
RuleAttributeName,
static (node, _) => node is ClassDeclarationSyntax,
static (ctx, _) => CreateModel(ctx))
.Where(static model => model is not null)
.Select(static (model, _) => model!);
context.RegisterSourceOutput(rules.Collect(), static (ctx, models) =>
{
if (models.Length == 0)
return;
ctx.AddSource("LuaSyntaxRuleRegistry.g.cs", SourceText.From(Emit(models), Encoding.UTF8));
});
}
private static LuaSyntaxRuleModel? CreateModel(GeneratorAttributeSyntaxContext context)
{
if (context.TargetSymbol is not INamedTypeSymbol symbol)
return null;
if (!symbol.AllInterfaces.Any(static contract => contract.ToDisplayString() == RuleInterfaceName))
return null;
int order = 0;
var arguments = context.Attributes[0].ConstructorArguments;
if (arguments.Length > 0 && arguments[0].Value is int value)
order = value;
return new LuaSyntaxRuleModel(symbol.ToDisplayString(), order);
}
private static string Emit(ImmutableArray<LuaSyntaxRuleModel> models)
{
var ordered = models
.OrderBy(static m => m.Order)
.ThenBy(static m => m.TypeName, StringComparer.Ordinal)
.ToArray();
var builder = new StringBuilder();
builder.AppendLine("#nullable enable");
builder.AppendLine("namespace LuaScript.Compat.Syntax");
builder.AppendLine("{");
builder.AppendLine(" internal static class LuaSyntaxRuleRegistry");
builder.AppendLine(" {");
builder.AppendLine(" internal static readonly global::LuaScript.Compat.Syntax.ILuaSyntaxRule[] Rules = new global::LuaScript.Compat.Syntax.ILuaSyntaxRule[]");
builder.AppendLine(" {");
foreach (var model in ordered)
builder.AppendLine($" new global::{model.TypeName}(),");
builder.AppendLine(" };");
builder.AppendLine(" }");
builder.AppendLine("}");
return builder.ToString();
}
}
}
+95
ファイルの表示
@@ -0,0 +1,95 @@
using System.Diagnostics;
using System.Runtime.Intrinsics;
using System.Threading.Tasks;
namespace LuaScript.Engine.Kernel
{
internal sealed class CpuKernel(CpuKernel.RowDelegate row, CpuKernel.RowDelegate? block)
{
public delegate void RowDelegate(byte[] buffer, int rowBase, int xStart, int xEnd, double y, double[] uniforms);
private const int ParallelThreshold = 64;
private const int WarmupRunsPerPath = 1;
private const int TimedRunsPerPath = 3;
private readonly RowDelegate _row = row;
private readonly RowDelegate? _block = block;
private long _rowTicks;
private long _blockTicks;
private int _rowRuns;
private int _blockRuns;
private bool _nextIsBlock = true;
private bool _decided;
private bool _useBlock;
public bool? BlockAdopted => _decided ? _useBlock : null;
public void Execute(byte[] buffer, int width, int height, double[] uniforms)
{
if (_block is null || !Vector256.IsHardwareAccelerated)
{
Run(buffer, width, height, uniforms, false);
return;
}
if (_decided)
{
Run(buffer, width, height, uniforms, _useBlock);
return;
}
bool useBlock = _nextIsBlock;
_nextIsBlock = !_nextIsBlock;
long start = Stopwatch.GetTimestamp();
Run(buffer, width, height, uniforms, useBlock);
long elapsed = Stopwatch.GetTimestamp() - start;
if (useBlock)
{
if (_blockRuns >= WarmupRunsPerPath)
_blockTicks += elapsed;
_blockRuns++;
}
else
{
if (_rowRuns >= WarmupRunsPerPath)
_rowTicks += elapsed;
_rowRuns++;
}
if (_rowRuns >= WarmupRunsPerPath + TimedRunsPerPath &&
_blockRuns >= WarmupRunsPerPath + TimedRunsPerPath)
{
_useBlock = _blockTicks < _rowTicks;
_decided = true;
}
}
private void Run(byte[] buffer, int width, int height, double[] uniforms, bool useBlock)
{
var row = _row;
var block = useBlock ? _block : null;
int stride = width * 4;
int blockWidth = block is null ? 0 : width & ~3;
void RunRow(int y)
{
int rowBase = y * stride;
if (blockWidth > 0)
block!(buffer, rowBase, 0, blockWidth, y, uniforms);
if (blockWidth < width)
row(buffer, rowBase, blockWidth, width, y, uniforms);
}
if (height < ParallelThreshold)
{
for (int y = 0; y < height; y++)
RunRow(y);
return;
}
Parallel.For(0, height, RunRow);
}
}
}
+222
ファイルの表示
@@ -0,0 +1,222 @@
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) =>
new(CompileRow(program), SimdKernelCompiler.TryCompile(program));
public static CpuKernel.RowDelegate CompileRow(KernelProgram program)
{
var buffer = Expression.Parameter(typeof(byte[]), "buffer");
var rowBase = Expression.Parameter(typeof(int), "rowBase");
var xStart = Expression.Parameter(typeof(int), "xStart");
var xEnd = Expression.Parameter(typeof(int), "xEnd");
var 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, xEnd),
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, xStart), loop);
var lambda = Expression.Lambda<CpuKernel.RowDelegate>(body, buffer, rowBase, xStart, xEnd, y, uniforms);
return 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)
{
if (call.Func == KFunc.Fmod)
return Expression.Modulo(Build(call.Arguments[0], context), Build(call.Arguments[1], context));
var method = Functions[call.Func];
if (call.Arguments.Count == 1)
return Expression.Call(method, Build(call.Arguments[0], context));
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)])!;
}
}
+219
ファイルの表示
@@ -0,0 +1,219 @@
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;
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(" - 0.5;\n");
builder.Append(" float py = uv.y * ").Append(Uniform(KernelUniform.Height)).Append(" - 0.5;\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 = clamp(");
EmitExpression(builder, program.OutputA);
builder.Append(", 0.0, 255.0);\n");
builder.Append(" float alphaK = outA / 255.0;\n");
builder.Append(" float oR = floor(clamp((");
EmitExpression(builder, program.OutputR);
builder.Append(") * alphaK, 0.0, 255.0)) / 255.0;\n");
builder.Append(" float oG = floor(clamp((");
EmitExpression(builder, program.OutputG);
builder.Append(") * alphaK, 0.0, 255.0)) / 255.0;\n");
builder.Append(" float oB = floor(clamp((");
EmitExpression(builder, program.OutputB);
builder.Append(") * alphaK, 0.0, 255.0)) / 255.0;\n");
builder.Append(" float oA = floor(outA) / 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(KFunctions.Intrinsic(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;
}
}
}
+493
ファイルの表示
@@ -0,0 +1,493 @@
using System;
using System.Collections.Generic;
namespace LuaScript.Engine.Kernel
{
internal sealed class KernelExtractor
{
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;
private string? _pixelDataVariable;
private string _baseIndexVariable = string.Empty;
private readonly bool[] _writtenChannels = new bool[4];
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)
{
if (TryBindPixelData(prelude))
{
index++;
continue;
}
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;
if (_pixelDataVariable is not null &&
(string.Equals(outerVar, _pixelDataVariable, StringComparison.Ordinal) ||
string.Equals(innerVar, _pixelDataVariable, StringComparison.Ordinal)))
return null;
if (_scope.ContainsKey(outerVar))
_scope.Remove(outerVar);
if (_scope.ContainsKey(innerVar))
_scope.Remove(innerVar);
_widthVariable = outerAxis == KAxis.X ? outerVar : innerVar;
_heightVariable = outerAxis == KAxis.Y ? outerVar : innerVar;
return _pixelDataVariable is null ? BuildKernel(inner.Body) : BuildPixelDataKernel(inner.Body);
}
private bool TryBindPixelData(LocalStmt local)
{
if (local.Names.Count != 1 || local.Values.Count != 1 ||
local.Values[0] is not CallExpr { Target: MemberExpr { Target: NameExpr { Name: "obj" }, Name: "getpixeldata" }, Arguments.Count: 0 })
return false;
if (_pixelDataVariable is not null)
throw new KernelUnsupportedException("Multiple pixel-data handles are not supported.");
_pixelDataVariable = local.Names[0];
return true;
}
private KernelProgram? BuildPixelDataKernel(IReadOnlyList<LuaStmt> body)
{
if (body.Count < 5)
return null;
if (body[0] is not LocalStmt { Names.Count: 1, Values.Count: 1 } baseStmt || !IsBaseIndex(baseStmt.Values[0]))
return null;
EnsureNotCoordinateName(baseStmt.Names[0]);
_baseIndexVariable = baseStmt.Names[0];
_coordsEnabled = true;
KExpr? outR = null, outG = null, outB = null;
for (int i = 1; i < body.Count; i++)
{
switch (body[i])
{
case LocalStmt local:
BindLocal(local);
break;
case AssignStmt assign:
BindAssign(assign);
break;
case CallStmt { Call: MethodCallExpr set } when IsPixelDataSet(set, out int writeChannel):
var value = ClampChannel(Lower(set.Arguments[1]));
if (writeChannel == 0) outR = value;
else if (writeChannel == 1) outG = value;
else outB = value;
_writtenChannels[writeChannel] = true;
break;
default:
return null;
}
}
if (outR is null || outG is null || outB is null)
return null;
return new KernelProgram(_bindings, outR, outG, outB, new KInput(KChannel.A), [.. _uniforms]);
}
private bool IsBaseIndex(LuaExpr expression)
{
if (expression is not BinaryExpr { Operator: "*", Right: NumberExpr { Value: 4d } } scaled ||
scaled.Left is not BinaryExpr { Operator: "+" } sum)
return false;
if (!IsCoordinate(sum.Right, KAxis.X))
return false;
if (sum.Left is not BinaryExpr { Operator: "*" } stride)
return false;
return IsCoordinate(stride.Left, KAxis.Y) && IsWidth(stride.Right);
}
private bool IsWidth(LuaExpr expression)
{
if (expression is MemberExpr { Target: NameExpr { Name: "obj" }, Name: var field } &&
KernelUniforms.TryResolveMember("obj", field, out var uniform))
return uniform == KernelUniform.Width;
return _pixelDataVariable is not null &&
expression is MemberExpr { Target: NameExpr { } target, Name: "width" } &&
string.Equals(target.Name, _pixelDataVariable, StringComparison.Ordinal);
}
private bool TryPixelDataChannel(LuaExpr expression, out int channel)
{
channel = 0;
if (expression is not MethodCallExpr { Method: "get", Arguments.Count: 1 } call ||
call.Target is not NameExpr { } handle ||
!string.Equals(handle.Name, _pixelDataVariable, StringComparison.Ordinal))
return false;
if (!TryChannelOffset(call.Arguments[0], 1, 4, out channel))
return false;
channel--;
return !_writtenChannels[channel];
}
private bool IsPixelDataSet(MethodCallExpr call, out int channel)
{
channel = 0;
if (call.Method != "set" || call.Arguments.Count != 2 ||
call.Target is not NameExpr { } handle ||
!string.Equals(handle.Name, _pixelDataVariable, StringComparison.Ordinal))
return false;
if (!TryChannelOffset(call.Arguments[0], 1, 3, out channel))
return false;
channel--;
return true;
}
private KExpr ClampChannel(KExpr value)
{
var bound = new KLocalRef(AddBinding(value));
return new KSelect(
new KCompare(KCompareOp.Less, bound, new KConst(0d)),
new KConst(0d),
new KSelect(
new KCompare(KCompareOp.Greater, bound, new KConst(255d)),
new KConst(255d),
bound));
}
private bool TryChannelOffset(LuaExpr expression, int min, int max, out int offset)
{
offset = 0;
if (expression is not BinaryExpr { Operator: "+", Left: NameExpr baseName, Right: NumberExpr number } ||
!string.Equals(baseName.Name, _baseIndexVariable, StringComparison.Ordinal))
return false;
offset = (int)number.Value;
return offset == number.Value && offset >= min && offset <= max;
}
private KernelProgram? BuildKernel(IReadOnlyList<LuaStmt> body)
{
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: CallExpr 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.");
if (_pixelDataVariable is not null && string.Equals(name, _pixelDataVariable, StringComparison.Ordinal))
throw new KernelUnsupportedException("Local variable shadows the pixel-data handle.");
if (_baseIndexVariable.Length > 0 && string.Equals(name, _baseIndexVariable, StringComparison.Ordinal))
throw new KernelUnsupportedException("Local variable shadows the base index.");
}
private int AddBinding(KExpr expression)
{
_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 MethodCallExpr method when TryPixelDataChannel(method, out int channel):
return new KInput((KChannel)channel);
case UnaryExpr { Operator: "-" } unary:
return new KNegate(Lower(unary.Operand));
case BinaryExpr binary:
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 } ||
!KFunctions.TryResolve(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 MemberExpr { Target: NameExpr { Name: "obj" }, Name: var field } &&
KernelUniforms.TryResolveMember("obj", field, out var uniform))
{
if (uniform == KernelUniform.Width)
{
axis = KAxis.X;
return true;
}
if (uniform == KernelUniform.Height)
{
axis = KAxis.Y;
return true;
}
return false;
}
if (_pixelDataVariable is not null &&
bound.Left is MemberExpr { Target: NameExpr { } handle, Name: var pixelField } &&
string.Equals(handle.Name, _pixelDataVariable, StringComparison.Ordinal))
{
if (pixelField == "width")
{
axis = KAxis.X;
return true;
}
if (pixelField == "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);
}
}
+4
ファイルの表示
@@ -0,0 +1,4 @@
namespace LuaScript.Engine.Kernel
{
internal sealed class KernelUnsupportedException(string reason) : Exception(reason);
}
+270
ファイルの表示
@@ -0,0 +1,270 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Expressions;
using System.Reflection;
using System.Runtime.Intrinsics;
namespace LuaScript.Engine.Kernel
{
internal static class SimdKernelCompiler
{
private static readonly Type Vec = typeof(Vector256<double>);
private static readonly MethodInfo Broadcast = typeof(Vector256).GetMethod(nameof(Vector256.Create), [typeof(double)])!;
private static readonly MethodInfo Create4 = typeof(Vector256).GetMethod(nameof(Vector256.Create), [typeof(double), typeof(double), typeof(double), typeof(double)])!;
private static readonly MethodInfo GetElement = VecOp(nameof(Vector256.GetElement), 1, 1);
private static readonly MethodInfo Add = VecOp(nameof(Vector256.Add), 2);
private static readonly MethodInfo Subtract = VecOp(nameof(Vector256.Subtract), 2);
private static readonly MethodInfo Multiply = VecOp(nameof(Vector256.Multiply), 2);
private static readonly MethodInfo Divide = VecOp(nameof(Vector256.Divide), 2);
private static readonly MethodInfo Negate = VecOp(nameof(Vector256.Negate), 1);
private static readonly MethodInfo Abs = VecOp(nameof(Vector256.Abs), 1);
private static readonly MethodInfo Sqrt = VecOp(nameof(Vector256.Sqrt), 1);
private static readonly MethodInfo FloorFn = typeof(Vector256).GetMethod(nameof(Vector256.Floor), [Vec])!;
private static readonly MethodInfo CeilingFn = typeof(Vector256).GetMethod(nameof(Vector256.Ceiling), [Vec])!;
private static readonly MethodInfo ConditionalSelect = VecOp(nameof(Vector256.ConditionalSelect), 3);
private static readonly MethodInfo LessThan = VecOp(nameof(Vector256.LessThan), 2);
private static readonly MethodInfo GreaterThan = VecOp(nameof(Vector256.GreaterThan), 2);
private static readonly MethodInfo LessThanOrEqual = VecOp(nameof(Vector256.LessThanOrEqual), 2);
private static readonly MethodInfo GreaterThanOrEqual = VecOp(nameof(Vector256.GreaterThanOrEqual), 2);
private static readonly MethodInfo EqualsFn = VecOp(nameof(Vector256.Equals), 2);
private static readonly MethodInfo BitwiseAnd = VecOp(nameof(Vector256.BitwiseAnd), 2);
private static readonly MethodInfo BitwiseOr = VecOp(nameof(Vector256.BitwiseOr), 2);
private static readonly MethodInfo OnesComplement = VecOp(nameof(Vector256.OnesComplement), 1);
private static readonly Expression Zero = Expression.Constant(Vector256<double>.Zero, Vec);
private static readonly Expression AllBits = Expression.Constant(Vector256<double>.AllBitsSet, Vec);
private static readonly Expression V255 = Expression.Constant(Vector256.Create(255d), Vec);
public static CpuKernel.RowDelegate? TryCompile(KernelProgram program)
{
try
{
return Compile(program);
}
catch (KernelUnsupportedException)
{
return null;
}
}
private static CpuKernel.RowDelegate Compile(KernelProgram program)
{
var buffer = Expression.Parameter(typeof(byte[]), "buffer");
var rowBase = Expression.Parameter(typeof(int), "rowBase");
var xStart = Expression.Parameter(typeof(int), "xStart");
var xEnd = Expression.Parameter(typeof(int), "xEnd");
var yScalar = Expression.Parameter(typeof(double), "y");
var uniforms = Expression.Parameter(typeof(double[]), "uniforms");
var x = Expression.Variable(typeof(int), "x");
var index = Expression.Variable(typeof(int), "index");
var yVec = Expression.Variable(Vec, "yVec");
var xVec = Expression.Variable(Vec, "xVec");
var alphaRaw = Expression.Variable(Vec, "alphaRaw");
var transparent = Expression.Variable(Vec, "transparent");
var scale = Expression.Variable(Vec, "scale");
var inputs = new[]
{
Expression.Variable(Vec, "inR"),
Expression.Variable(Vec, "inG"),
Expression.Variable(Vec, "inB"),
Expression.Variable(Vec, "inA"),
};
var slots = new ParameterExpression[program.Bindings.Count];
for (int i = 0; i < slots.Length; i++)
slots[i] = Expression.Variable(Vec, "slot" + i);
var context = new Context(xVec, yVec, uniforms, inputs, slots);
var statements = new List<Expression>
{
Expression.Assign(index, Expression.Add(rowBase, Expression.Multiply(x, Constant(4)))),
Expression.Assign(xVec, Expression.Call(Create4,
ToDouble(x),
ToDouble(Expression.Add(x, Constant(1))),
ToDouble(Expression.Add(x, Constant(2))),
ToDouble(Expression.Add(x, Constant(3))))),
Expression.Assign(alphaRaw, LoadChannel(buffer, index, 3)),
Expression.Assign(transparent, Call(LessThanOrEqual, alphaRaw, Zero)),
Expression.Assign(scale, Select(transparent, Zero, Call(Divide, V255, alphaRaw))),
Expression.Assign(inputs[3], Select(transparent, Zero, alphaRaw)),
Expression.Assign(inputs[0], Select(transparent, Zero, ClampByte(Call(Multiply, LoadChannel(buffer, index, 2), scale)))),
Expression.Assign(inputs[1], Select(transparent, Zero, ClampByte(Call(Multiply, LoadChannel(buffer, index, 1), scale)))),
Expression.Assign(inputs[2], Select(transparent, Zero, ClampByte(Call(Multiply, LoadChannel(buffer, index, 0), scale)))),
};
for (int i = 0; i < slots.Length; i++)
statements.Add(Expression.Assign(slots[i], Build(program.Bindings[i], context)));
var outA = Expression.Variable(Vec, "outA");
var alphaScale = Expression.Variable(Vec, "alphaScale");
statements.Add(Expression.Assign(outA, Build(program.OutputA, context)));
statements.Add(Expression.Assign(alphaScale, Call(Divide, ClampByte(outA), V255)));
statements.Add(StoreChannel(buffer, index, 0, ClampByte(Call(Multiply, Build(program.OutputB, context), alphaScale))));
statements.Add(StoreChannel(buffer, index, 1, ClampByte(Call(Multiply, Build(program.OutputG, context), alphaScale))));
statements.Add(StoreChannel(buffer, index, 2, ClampByte(Call(Multiply, Build(program.OutputR, context), alphaScale))));
statements.Add(StoreChannel(buffer, index, 3, ClampByte(outA)));
statements.Add(Expression.AddAssign(x, Constant(4)));
var breakLabel = Expression.Label("break");
var loop = Expression.Loop(
Expression.IfThenElse(
Expression.LessThan(x, xEnd),
Expression.Block(statements),
Expression.Break(breakLabel)),
breakLabel);
var locals = new List<ParameterExpression> { x, index, yVec, xVec, alphaRaw, transparent, scale, outA, alphaScale };
locals.AddRange(inputs);
locals.AddRange(slots);
var body = Expression.Block(
locals,
Expression.Assign(yVec, Expression.Call(Broadcast, yScalar)),
Expression.Assign(x, xStart),
loop);
var lambda = Expression.Lambda<CpuKernel.RowDelegate>(body, buffer, rowBase, xStart, xEnd, yScalar, uniforms);
return lambda.Compile();
}
private sealed record Context(
Expression X,
Expression Y,
ParameterExpression Uniforms,
Expression[] Inputs,
ParameterExpression[] Slots);
private static Expression Build(KExpr expression, Context context)
{
switch (expression)
{
case KConst value:
return Expression.Constant(Vector256.Create(value.Value), Vec);
case KInput input:
return context.Inputs[(int)input.Channel];
case KCoord coord:
return coord.Axis == KAxis.X ? context.X : context.Y;
case KUniformRef uniform:
return Expression.Call(Broadcast, Expression.ArrayIndex(context.Uniforms, Constant((int)uniform.Uniform)));
case KLocalRef local:
return context.Slots[local.Slot];
case KNegate negate:
return Call(Negate, Build(negate.Operand, context));
case KArith arithmetic:
return BuildArithmetic(arithmetic, context);
case KCall call:
return BuildCall(call, context);
case KSelect select:
return Select(BuildBool(select.Condition, context), Build(select.WhenTrue, context), Build(select.WhenFalse, context));
}
throw new KernelUnsupportedException("Unsupported SIMD expression.");
}
private static Expression BuildArithmetic(KArith arithmetic, Context context)
{
var left = Build(arithmetic.Left, context);
var right = Build(arithmetic.Right, context);
return arithmetic.Op switch
{
KArithOp.Add => Call(Add, left, right),
KArithOp.Subtract => Call(Subtract, left, right),
KArithOp.Multiply => Call(Multiply, left, right),
KArithOp.Divide => Call(Divide, left, right),
KArithOp.Modulo => Call(Subtract, left, Call(Multiply, Call(FloorFn, Call(Divide, left, right)), right)),
_ => throw new KernelUnsupportedException("Unsupported SIMD arithmetic operator."),
};
}
private static Expression BuildCall(KCall call, Context context)
{
var argument = Build(call.Arguments[0], context);
return call.Func switch
{
KFunc.Abs => Call(Abs, argument),
KFunc.Floor => Call(FloorFn, argument),
KFunc.Ceil => Call(CeilingFn, argument),
KFunc.Sqrt => Call(Sqrt, argument),
_ => throw new KernelUnsupportedException("Unsupported SIMD function."),
};
}
private static Expression BuildBool(KBool condition, Context context)
{
switch (condition)
{
case KBoolConst value:
return value.Value ? AllBits : Zero;
case KNot not:
return Call(OnesComplement, BuildBool(not.Operand, context));
case KLogical logical:
return logical.IsAnd
? Call(BitwiseAnd, BuildBool(logical.Left, context), BuildBool(logical.Right, context))
: Call(BitwiseOr, BuildBool(logical.Left, context), BuildBool(logical.Right, context));
case KCompare compare:
var left = Build(compare.Left, context);
var right = Build(compare.Right, context);
return compare.Op switch
{
KCompareOp.Less => Call(LessThan, left, right),
KCompareOp.Greater => Call(GreaterThan, left, right),
KCompareOp.LessEqual => Call(LessThanOrEqual, left, right),
KCompareOp.GreaterEqual => Call(GreaterThanOrEqual, left, right),
KCompareOp.Equal => Call(EqualsFn, left, right),
KCompareOp.NotEqual => Call(OnesComplement, Call(EqualsFn, left, right)),
_ => throw new KernelUnsupportedException("Unsupported SIMD comparison."),
};
}
throw new KernelUnsupportedException("Unsupported SIMD condition.");
}
private static Expression ClampByte(Expression value)
{
var low = Select(Call(LessThan, value, Zero), Zero, value);
return Select(Call(GreaterThan, low, V255), V255, low);
}
private static Expression Select(Expression condition, Expression whenTrue, Expression whenFalse) =>
Expression.Call(ConditionalSelect, condition, whenTrue, whenFalse);
private static Expression LoadChannel(ParameterExpression buffer, ParameterExpression index, int offset) =>
Expression.Call(Create4,
ToDouble(ReadByte(buffer, index, offset)),
ToDouble(ReadByte(buffer, index, offset + 4)),
ToDouble(ReadByte(buffer, index, offset + 8)),
ToDouble(ReadByte(buffer, index, offset + 12)));
private static Expression StoreChannel(ParameterExpression buffer, ParameterExpression index, int offset, Expression value)
{
var writes = new Expression[4];
for (int lane = 0; lane < 4; lane++)
writes[lane] = Expression.Assign(
Expression.ArrayAccess(buffer, Expression.Add(index, Constant(lane * 4 + offset))),
Expression.Convert(Expression.Call(GetElement, value, Constant(lane)), typeof(byte)));
return Expression.Block(writes);
}
private static Expression ReadByte(ParameterExpression buffer, ParameterExpression index, int offset) =>
Expression.ArrayIndex(buffer, offset == 0 ? index : Expression.Add(index, Constant(offset)));
private static Expression Call(MethodInfo method, params Expression[] arguments) =>
Expression.Call(method, arguments);
private static Expression ToDouble(Expression value) => Expression.Convert(value, typeof(double));
private static ConstantExpression Constant(int value) => Expression.Constant(value, typeof(int));
private static MethodInfo VecOp(string name, int vectorArgs, int intArgs = 0) =>
typeof(Vector256).GetMethods()
.Single(m => m.Name == name && m.IsGenericMethodDefinition &&
m.GetParameters().Length == vectorArgs + intArgs &&
m.GetParameters().Take(vectorArgs).All(p => IsVector(p.ParameterType)) &&
m.GetParameters().Skip(vectorArgs).All(p => p.ParameterType == typeof(int)))
.MakeGenericMethod(typeof(double));
private static bool IsVector(Type type) =>
type.IsGenericType && type.GetGenericTypeDefinition() == typeof(Vector256<>);
}
}
+4
ファイルの表示
@@ -0,0 +1,4 @@
namespace LuaScript.Engine.Kernel
{
internal sealed record KArith(KArithOp Op, KExpr Left, KExpr Right) : KExpr;
}
+12
ファイルの表示
@@ -0,0 +1,12 @@
namespace LuaScript.Engine.Kernel
{
internal enum KArithOp
{
Add,
Subtract,
Multiply,
Divide,
Modulo,
Power,
}
}
+8
ファイルの表示
@@ -0,0 +1,8 @@
namespace LuaScript.Engine.Kernel
{
internal enum KAxis
{
X,
Y,
}
}
+4
ファイルの表示
@@ -0,0 +1,4 @@
namespace LuaScript.Engine.Kernel
{
internal abstract record KBool;
}
+4
ファイルの表示
@@ -0,0 +1,4 @@
namespace LuaScript.Engine.Kernel
{
internal sealed record KBoolConst(bool Value) : KBool;
}
+4
ファイルの表示
@@ -0,0 +1,4 @@
namespace LuaScript.Engine.Kernel
{
internal sealed record KCall(KFunc Func, IReadOnlyList<KExpr> Arguments) : KExpr;
}
+10
ファイルの表示
@@ -0,0 +1,10 @@
namespace LuaScript.Engine.Kernel
{
internal enum KChannel
{
R,
G,
B,
A,
}
}
+4
ファイルの表示
@@ -0,0 +1,4 @@
namespace LuaScript.Engine.Kernel
{
internal sealed record KCompare(KCompareOp Op, KExpr Left, KExpr Right) : KBool;
}
+12
ファイルの表示
@@ -0,0 +1,12 @@
namespace LuaScript.Engine.Kernel
{
internal enum KCompareOp
{
Less,
Greater,
LessEqual,
GreaterEqual,
Equal,
NotEqual,
}
}
+4
ファイルの表示
@@ -0,0 +1,4 @@
namespace LuaScript.Engine.Kernel
{
internal sealed record KConst(double Value) : KExpr;
}
+4
ファイルの表示
@@ -0,0 +1,4 @@
namespace LuaScript.Engine.Kernel
{
internal sealed record KCoord(KAxis Axis) : KExpr;
}
+4
ファイルの表示
@@ -0,0 +1,4 @@
namespace LuaScript.Engine.Kernel
{
internal abstract record KExpr;
}
+23
ファイルの表示
@@ -0,0 +1,23 @@
namespace LuaScript.Engine.Kernel
{
internal enum KFunc
{
Abs,
Floor,
Ceil,
Sqrt,
Sin,
Cos,
Tan,
Asin,
Acos,
Atan,
Atan2,
Exp,
Log,
Pow,
Min,
Max,
Fmod,
}
}
+4
ファイルの表示
@@ -0,0 +1,4 @@
namespace LuaScript.Engine.Kernel
{
internal readonly record struct KFunctionInfo(KFunc Func, string Name, int MinArgs, int MaxArgs);
}
+52
ファイルの表示
@@ -0,0 +1,52 @@
using System;
using System.Collections.Generic;
namespace LuaScript.Engine.Kernel
{
internal static class KFunctions
{
private static readonly KFunctionInfo[] Catalog =
[
new(KFunc.Abs, "abs", 1, 1),
new(KFunc.Floor, "floor", 1, 1),
new(KFunc.Ceil, "ceil", 1, 1),
new(KFunc.Sqrt, "sqrt", 1, 1),
new(KFunc.Sin, "sin", 1, 1),
new(KFunc.Cos, "cos", 1, 1),
new(KFunc.Tan, "tan", 1, 1),
new(KFunc.Asin, "asin", 1, 1),
new(KFunc.Acos, "acos", 1, 1),
new(KFunc.Atan, "atan", 1, 1),
new(KFunc.Atan2, "atan2", 2, 2),
new(KFunc.Exp, "exp", 1, 1),
new(KFunc.Log, "log", 1, 1),
new(KFunc.Pow, "pow", 2, 2),
new(KFunc.Min, "min", 2, int.MaxValue),
new(KFunc.Max, "max", 2, int.MaxValue),
new(KFunc.Fmod, "fmod", 2, 2),
];
private static readonly Dictionary<string, KFunctionInfo> ByName = BuildByName();
private static readonly string[] Intrinsics = BuildIntrinsics();
public static bool TryResolve(string name, out KFunctionInfo info) => ByName.TryGetValue(name, out info);
public static string Intrinsic(KFunc func) => Intrinsics[(int)func];
private static Dictionary<string, KFunctionInfo> BuildByName()
{
var map = new Dictionary<string, KFunctionInfo>(Catalog.Length, StringComparer.Ordinal);
foreach (var info in Catalog)
map[info.Name] = info;
return map;
}
private static string[] BuildIntrinsics()
{
var names = new string[Enum.GetValues<KFunc>().Length];
foreach (var info in Catalog)
names[(int)info.Func] = info.Name;
return names;
}
}
}
+4
ファイルの表示
@@ -0,0 +1,4 @@
namespace LuaScript.Engine.Kernel
{
internal sealed record KInput(KChannel Channel) : KExpr;
}
+4
ファイルの表示
@@ -0,0 +1,4 @@
namespace LuaScript.Engine.Kernel
{
internal sealed record KLocalRef(int Slot) : KExpr;
}
+4
ファイルの表示
@@ -0,0 +1,4 @@
namespace LuaScript.Engine.Kernel
{
internal sealed record KLogical(bool IsAnd, KBool Left, KBool Right) : KBool;
}
+4
ファイルの表示
@@ -0,0 +1,4 @@
namespace LuaScript.Engine.Kernel
{
internal sealed record KNegate(KExpr Operand) : KExpr;
}
+4
ファイルの表示
@@ -0,0 +1,4 @@
namespace LuaScript.Engine.Kernel
{
internal sealed record KNot(KBool Operand) : KBool;
}
+4
ファイルの表示
@@ -0,0 +1,4 @@
namespace LuaScript.Engine.Kernel
{
internal sealed record KSelect(KBool Condition, KExpr WhenTrue, KExpr WhenFalse) : KExpr;
}
+4
ファイルの表示
@@ -0,0 +1,4 @@
namespace LuaScript.Engine.Kernel
{
internal sealed record KUniformRef(KernelUniform Uniform) : KExpr;
}
+10
ファイルの表示
@@ -0,0 +1,10 @@
namespace LuaScript.Engine.Kernel
{
internal sealed record KernelProgram(
IReadOnlyList<KExpr> Bindings,
KExpr OutputR,
KExpr OutputG,
KExpr OutputB,
KExpr OutputA,
IReadOnlyList<KernelUniform> Uniforms);
}
+60
ファイルの表示
@@ -0,0 +1,60 @@
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,
}
}
+97
ファイルの表示
@@ -0,0 +1,97 @@
using System;
using System.Collections.Generic;
namespace LuaScript.Engine.Kernel
{
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;
}
}
+4
ファイルの表示
@@ -0,0 +1,4 @@
namespace LuaScript.Engine.Kernel
{
internal sealed record AssignStmt(IReadOnlyList<LuaExpr> Targets, IReadOnlyList<LuaExpr> Values) : LuaStmt;
}
+4
ファイルの表示
@@ -0,0 +1,4 @@
namespace LuaScript.Engine.Kernel
{
internal sealed record BinaryExpr(string Operator, LuaExpr Left, LuaExpr Right) : LuaExpr;
}
+4
ファイルの表示
@@ -0,0 +1,4 @@
namespace LuaScript.Engine.Kernel
{
internal sealed record BoolExpr(bool Value) : LuaExpr;
}
+4
ファイルの表示
@@ -0,0 +1,4 @@
namespace LuaScript.Engine.Kernel
{
internal sealed record CallExpr(LuaExpr Target, IReadOnlyList<LuaExpr> Arguments) : LuaExpr;
}
+4
ファイルの表示
@@ -0,0 +1,4 @@
namespace LuaScript.Engine.Kernel
{
internal sealed record CallStmt(LuaExpr Call) : LuaStmt;
}
+4
ファイルの表示
@@ -0,0 +1,4 @@
namespace LuaScript.Engine.Kernel
{
internal sealed record IfClause(LuaExpr Condition, IReadOnlyList<LuaStmt> Body);
}
+4
ファイルの表示
@@ -0,0 +1,4 @@
namespace LuaScript.Engine.Kernel
{
internal sealed record IfStmt(IReadOnlyList<IfClause> Clauses, IReadOnlyList<LuaStmt>? ElseBody) : LuaStmt;
}
+4
ファイルの表示
@@ -0,0 +1,4 @@
namespace LuaScript.Engine.Kernel
{
internal sealed record IndexExpr(LuaExpr Target, LuaExpr Key) : LuaExpr;
}
+4
ファイルの表示
@@ -0,0 +1,4 @@
namespace LuaScript.Engine.Kernel
{
internal sealed record LocalStmt(IReadOnlyList<string> Names, IReadOnlyList<LuaExpr> Values) : LuaStmt;
}
+4
ファイルの表示
@@ -0,0 +1,4 @@
namespace LuaScript.Engine.Kernel
{
internal abstract record LuaExpr;
}
+4
ファイルの表示
@@ -0,0 +1,4 @@
namespace LuaScript.Engine.Kernel
{
internal abstract record LuaStmt;
}
+4
ファイルの表示
@@ -0,0 +1,4 @@
namespace LuaScript.Engine.Kernel
{
internal sealed record MemberExpr(LuaExpr Target, string Name) : LuaExpr;
}
+4
ファイルの表示
@@ -0,0 +1,4 @@
namespace LuaScript.Engine.Kernel
{
internal sealed record MethodCallExpr(LuaExpr Target, string Method, IReadOnlyList<LuaExpr> Arguments) : LuaExpr;
}
+4
ファイルの表示
@@ -0,0 +1,4 @@
namespace LuaScript.Engine.Kernel
{
internal sealed record NameExpr(string Name) : LuaExpr;
}
+4
ファイルの表示
@@ -0,0 +1,4 @@
namespace LuaScript.Engine.Kernel
{
internal sealed record NilExpr : LuaExpr;
}
+4
ファイルの表示
@@ -0,0 +1,4 @@
namespace LuaScript.Engine.Kernel
{
internal sealed record NumberExpr(double Value) : LuaExpr;
}
+9
ファイルの表示
@@ -0,0 +1,9 @@
namespace LuaScript.Engine.Kernel
{
internal sealed record NumericForStmt(
string Variable,
LuaExpr Start,
LuaExpr Stop,
LuaExpr? Step,
IReadOnlyList<LuaStmt> Body) : LuaStmt;
}
+4
ファイルの表示
@@ -0,0 +1,4 @@
namespace LuaScript.Engine.Kernel
{
internal sealed record StringExpr(string Value) : LuaExpr;
}
+4
ファイルの表示
@@ -0,0 +1,4 @@
namespace LuaScript.Engine.Kernel
{
internal sealed record UnaryExpr(string Operator, LuaExpr Operand) : LuaExpr;
}
+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);
}
}
295ファイル中100ファイルを読み込みました。 変更されたファイルが多すぎるため、それ以降のファイルは表示していません。 さらに表示