コミットを比較
| 作成者 | SHA1 | 日付 | |
|---|---|---|---|
|
|
f26816343f
|
||
|
|
0cab8972e0
|
||
|
|
f2aa668cf6
|
||
|
|
ed27979f64
|
||
|
|
7b958ea171
|
||
|
|
332dab3889
|
||
|
|
75d457a7ab
|
||
|
|
50e1801878
|
||
|
|
793d010bdb
|
||
|
|
b564b0b185
|
||
|
|
6d83fe93d8
|
||
|
|
db9c3747ea
|
||
|
|
7d887afe5a
|
||
|
|
ac34830367
|
||
|
|
8ed188d0e2
|
||
|
|
9c55c08caf
|
||
|
|
42868023f3
|
||
|
|
e146b36fa0
|
||
|
|
5fac495848
|
||
|
|
4fd519249f
|
||
|
|
1b26df959f
|
||
|
|
3cd67212a1
|
||
|
|
46692dfe95
|
||
|
|
e8d9cef129
|
||
|
|
18036cd74e
|
||
|
|
c8f857d2b4
|
||
|
|
ac7f797566
|
||
|
|
8beae1a277
|
||
|
|
6eb4d7c9af
|
||
|
|
a843f460de
|
||
|
|
27f04c7560
|
||
|
|
43c0ce88b3
|
||
|
|
00f0d991c1
|
||
|
|
784d294ca6
|
||
|
|
260d427bcf
|
||
|
|
b62f4a3a7d
|
||
|
|
79a408cafd
|
||
|
|
807df7df8a
|
||
|
|
0c5e3066c1
|
||
|
|
fbaff95503
|
||
|
|
8dec38a911
|
||
|
|
902d729c19
|
||
|
|
79f8ff8839
|
||
|
|
9a630ecb5a
|
||
|
|
d9e6132a1f
|
||
|
|
e685e7aa40
|
||
|
|
bf49fe9984
|
||
|
|
c05a1479f9
|
||
|
|
80ddb663b0
|
||
|
|
2f1bbc3828
|
||
|
|
e911f6e83f
|
||
|
|
6162ce5c19
|
||
|
|
59dcb82b49
|
||
|
|
d37726cdf6
|
||
|
|
0c09cf4a51
|
||
|
|
0d4809924d
|
||
|
|
1e97e7d8fe
|
||
|
|
06cfefe1b4
|
||
|
|
37b1371f57
|
||
|
|
9db756c974
|
||
|
|
43f3161ebb
|
||
|
|
4b3b74edae
|
||
|
|
5129ece749
|
||
|
|
24ef4135cf
|
||
|
|
044fdbf1eb
|
||
|
|
9e1ad6c133
|
||
|
|
6d8def9f08
|
||
|
|
7a9f1ff6e8
|
||
|
|
82db144b86
|
||
|
|
d3fb73ed94
|
||
|
|
7dd777fbc6
|
||
|
|
aa17df08d8
|
||
|
|
e5c4485f16
|
||
|
|
9b901f91b6
|
||
|
|
2b24a407e6
|
||
|
|
150b4818d4
|
||
|
|
34b7d60ca6
|
||
|
|
7dc6083fd7
|
||
|
|
245fb9c323
|
||
|
|
42c3bc4f4b
|
||
|
|
d273f99593
|
||
|
|
e1763e0c81
|
||
|
|
7221ce3aca
|
||
|
|
5f3ad96ea2
|
||
|
|
4e0bf831c5
|
||
|
|
0fedfd5804
|
||
|
|
f11225e2a1
|
||
|
|
92e8c43160
|
||
|
|
5fb9eae7a0
|
||
|
|
f109232cae
|
||
|
|
1596a048cd
|
||
|
|
0b0c795d7a
|
||
|
|
2be3c3d28b
|
||
|
|
3f9e4ebca4
|
||
|
|
03042b17e7
|
||
|
|
5e6d74dfee
|
||
|
|
40d68416c2
|
||
|
|
de6472c34b
|
||
|
|
55c8bffb70
|
||
|
|
8ca66bceb8
|
||
|
|
865f5117ea
|
||
|
|
b30f7a818b
|
||
|
|
95786a1f0a
|
||
|
|
cc07e2a83d
|
||
|
|
08e5e432b7
|
||
|
|
1e9b039cef
|
||
|
|
bad39fe0db
|
||
|
|
a5567a804d
|
||
|
|
a9cb4a9cda
|
||
|
|
9e9b5277af
|
検索条件に一致するファイルはありません
+25
-57
@@ -1,75 +1,43 @@
|
||||
# v1.11.4 - Lua スクリプト for YMM4
|
||||
# v1.13.4 - Lua スクリプト for YMM4
|
||||
|
||||
毎ピクセル処理のスクリプト(カーネル)の実行先を、GPU と CPU から自動で選べるように
|
||||
したリリースです。これまで GPU カーネルは `--!gpu` を明示したときだけ使っていましたが、
|
||||
指定が無いときも利用できるかを自動で判断し、利用できる場合は GPU で実行します。正確性を
|
||||
最優先し、初回に実機の GPU で CPU カーネルとの出力一致を検証し、許容差に収まった
|
||||
プログラムだけ GPU で実行します。あわせて、GPU カーネルと CPU カーネルで食い違って
|
||||
いた HLSL の座標原点と出力の丸めを、CPU カーネルに合わせて修正しました。
|
||||
環境情報を取得する obj.getinfo を追加したリリースです。
|
||||
スクリプトの設置フォルダのパスや動画の出力状態に加えて、最大画像サイズ、BPMグリッドの情報、経過時間、本体のバージョンを名前で取得できます。MoonSharp とネイティブの両エンジンで同一の関数として動作します。
|
||||
あわせて、プラグインの内部構成を依存関係の層ごとの複数アセンブリへ分割し、Lua API の登録と入力補完をソースジェネレータによる宣言的な生成へ移行しました。既存のスクリプトの書き方と実行結果に変更はありません。
|
||||
|
||||
---
|
||||
|
||||
## 改善
|
||||
## 新機能
|
||||
|
||||
### 1. カーネルの GPU/CPU 自動選択
|
||||
### obj.getinfo による環境情報の取得
|
||||
|
||||
これまで毎ピクセル処理のスクリプトは、`--!gpu` を明示したときだけ GPU カーネルで実行し、
|
||||
指定が無いときは CPU カーネルで実行していました。本リリースでは、指定が無いときも
|
||||
GPU カーネルを利用できるかを自動で判断し、利用できる場合は GPU で実行します。GPU
|
||||
カーネルは CPU カーネルが必要とするピクセルの読み戻しとアップロードを伴わないため、
|
||||
そのぶん高速です。実行先はプログラム単位で一度だけ決まり、フレームや画像サイズによって
|
||||
切り替わらないため、途中で結果がちらつくことはありません。
|
||||
obj.getinfo(名前) は、名前で指定した環境情報を返します。対応していない名前を指定した場合は nil を返します。取得できる情報は次のとおりです。
|
||||
|
||||
### 2. 実行時のセルフ検証で正確性を担保
|
||||
- "script_path" は、プラグインの設置フォルダのパスを返します。末尾には区切り文字が付きます。
|
||||
- "filter" は、フィルタ効果として処理中かどうかを返します。本プラグインでは常に true を返します。
|
||||
- "saving" は、動画を出力中のときだけ true を返します。
|
||||
- "image_max" は、最大画像サイズを横幅と高さの2つの値で返します。
|
||||
- "bpm" は、BPMグリッドのテンポと拍子と基準時間の3つの値を返します。基準時間の単位は秒です。BPMグリッドを設定していない場合はテンポが 0 になります。
|
||||
- "clock" は、YMM4 の起動からの経過時間を秒で返します。
|
||||
- "script_time" は、スクリプトの実行開始からの経過時間をミリ秒で返します。
|
||||
- "version" は、本体のバージョンを major×10000+minor×100+build の数値で返します。
|
||||
|
||||
GPU カーネルを初めて構築したとき、固定の 64×64 の検証用画像を実機の GPU で処理し、
|
||||
その結果を CPU カーネルの結果と比較します。全チャンネルの差が許容範囲に収まった
|
||||
プログラムだけを GPU で実行し、収まらない場合や検証を実行できない場合は CPU カーネルで
|
||||
実行します。GPU の出力が CPU カーネルと食い違うことはありません。検証の結果はログに
|
||||
記録します。
|
||||
|
||||
---
|
||||
|
||||
## 不具合修正
|
||||
|
||||
### GPU カーネルの座標原点のずれを修正
|
||||
|
||||
GPU カーネルの HLSL は、ピクセル座標を「テクスチャ座標 × 寸法」で求めていました。
|
||||
テクスチャ座標はピクセルの中心を指すため、求まる座標は CPU カーネルが用いる整数の
|
||||
添字より 0.5 大きく、ループ変数 `x`・`y` を参照するスクリプトで結果がずれていました。
|
||||
テクスチャ座標から 0.5 を引くように変更し、CPU カーネルの整数座標と一致させました。
|
||||
|
||||
### GPU カーネルの出力の丸めを修正
|
||||
|
||||
Direct2D は出力を四捨五入で 8 ビットへ量子化する一方、CPU カーネルは切り捨てていた
|
||||
ため、両者に系統的な 1 階調のずれがありました。シェーダ側で各チャンネルを切り捨てて
|
||||
から量子化するように変更し、丸め方を CPU カーネルへ統一しました。
|
||||
編集中のみプレビューへ枠を描き、出力時には描かないといった分岐へ利用できます。
|
||||
|
||||
---
|
||||
|
||||
## 互換性・後方互換
|
||||
|
||||
- スクリプトの書き方と API に変更はありません。
|
||||
- `--!cpu` は従来どおり CPU カーネルで実行します。`--!gpu` は GPU カーネルで実行しますが、
|
||||
検証に通らない場合は CPU カーネルへ切り替え、一度だけ警告を記録します。
|
||||
- 指定の無いカーネルは、検証に通れば GPU、通らなければ CPU で実行します。いずれも
|
||||
出力は CPU カーネルと許容差の範囲で一致します。
|
||||
- GPU カーネルは浮動小数点で計算するため、CPU カーネルと 1 階調程度異なることが
|
||||
あります。この差が許容範囲に収まることを検証で確認したプログラムだけを GPU で
|
||||
実行します。
|
||||
- GPU を利用できない環境では、従来どおり CPU カーネルで実行します。
|
||||
- 既存のスクリプトの書き方と実行結果に変更はありません。obj.getinfo は新規の関数であり、従来の呼び出しへは影響しません。
|
||||
- obj.getinfo は MoonSharp とネイティブの両エンジンで動作します。script_path、filter、saving、image_max、bpm、version は両エンジンで同一の値を返します。clock と script_time は経過時間の計測であり、値そのものは実行のたびに変わります。
|
||||
- v1.13.3 までの仕様に変更はありません。
|
||||
|
||||
---
|
||||
|
||||
## 内部実装
|
||||
|
||||
- `HlslKernelEmitter` の座標を「テクスチャ座標 × 寸法 - 0.5」へ、出力の各チャンネルを
|
||||
`floor(clamp(...))` へ変更し、CPU カーネルの整数座標と切り捨てへ揃えました。
|
||||
- `GpuKernel` へ `Verify` を追加しました。検証用画像を効果で描画して読み戻し、
|
||||
`CpuKernel` の結果と比較します。差が許容範囲に収まらない場合は GPU カーネルを
|
||||
採用しません。
|
||||
- `LuaScriptEffectProcessor` の `GetGpuKernel` は検証に通った GPU カーネルだけを返し、
|
||||
判定をプログラム単位でキャッシュします。`ExecuteKernelLane` は指定が無いときと
|
||||
`--!gpu` のときに検証済みの GPU カーネルを優先し、無ければ CPU カーネルで実行します。
|
||||
- テストへ HLSL の座標原点と出力の丸めを検証するケースを追加しました(全 2994 件)。
|
||||
GPU カーネルの実行と検証は実機の GPU が必要なため、YMM4 上での確認が対象です。
|
||||
- プラグインを依存関係の層ごとに LuaScript.Kernel、LuaScript.Compat、LuaScript.Media、LuaScript.Runtime、および本体の 5 つのアセンブリへ分割しました。名前空間は据え置き、参照の向きを一方向へ整理しています。
|
||||
- Lua API の登録と毎フレームの変数投影を、属性から生成するソースジェネレータへ移行しました。入力補完の候補もこの宣言から生成し、手書きの一覧を廃止しました。関数を 1 つ追加すると、登録と補完へ自動的に反映されます。
|
||||
- Kernel、Compat、Runtime の各プロジェクトを 1 ファイル 1 クラスへ整理し、ドメインごとのフォルダへ再配置しました。エンジンのテーブル管理は LuaScope へ汎用化しています。
|
||||
- 映像デコーダを LuaScript.Media プロジェクトへ分離し、ツールバーを View と ViewModel へ分離しました。ViewModel はフレームワークに依存しない構成へ整理しています。
|
||||
- obj.getinfo の実装では、BPMグリッドの情報を YMM4 のシーンから取得し、script_path と version は本体からエンジンへ渡します。経過時間は両エンジンがそれぞれ高精度タイマーで計測します。
|
||||
- テストは 3113 件です。v1.13.3 の 3092 件から、obj.getinfo の両エンジンでの実行結果の検証と、補完カタログの回帰検証、およびエンジンのテーブルライフサイクルの特性化検証を追加しました。
|
||||
@@ -1,5 +1,5 @@
|
||||
========================================
|
||||
Luaスクリプト for YMM4 v1.11.4
|
||||
Luaスクリプト for YMM4 v1.13.4
|
||||
========================================
|
||||
YukkuriMovieMaker4(YMM4)上で動作する、Luaスクリプトで映像エフェクトのパラメータや
|
||||
ピクセルを直接制御できるプラグインです。
|
||||
|
||||
@@ -73,6 +73,10 @@ jobs:
|
||||
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/"
|
||||
|
||||
@@ -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);
|
||||
}
|
||||
}
|
||||
差分なしでファイル名を変更。
@@ -0,0 +1,25 @@
|
||||
<Project Sdk="Microsoft.NET.Sdk">
|
||||
|
||||
<PropertyGroup>
|
||||
<TargetFramework>net10.0-windows10.0.19041.0</TargetFramework>
|
||||
<ImplicitUsings>enable</ImplicitUsings>
|
||||
<Version>1.13.4</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" />
|
||||
</ItemGroup>
|
||||
|
||||
<ItemGroup>
|
||||
<EmbeddedResource Include="AviUtlCompatMap.xml" />
|
||||
</ItemGroup>
|
||||
|
||||
</Project>
|
||||
@@ -42,7 +42,7 @@ namespace LuaScript.Compat
|
||||
if (string.IsNullOrEmpty(script))
|
||||
return AviUtlEngine.AviUtl;
|
||||
|
||||
foreach (var raw in script.Replace("\r\n", "\n").Replace("\r", "\n").Split('\n'))
|
||||
foreach (var raw in ScriptParserHelper.SplitLines(script))
|
||||
{
|
||||
var line = raw.Trim();
|
||||
if (!line.StartsWith("--!", System.StringComparison.Ordinal))
|
||||
-5
@@ -2,11 +2,6 @@ using System.Collections.Generic;
|
||||
|
||||
namespace LuaScript.Compat
|
||||
{
|
||||
internal readonly record struct AviUtlParameterMapping(string Source, string Property, double Scale, double Offset)
|
||||
{
|
||||
public double Transform(double value) => value * Scale + Offset;
|
||||
}
|
||||
|
||||
internal sealed class AviUtlEffectMapping
|
||||
{
|
||||
private readonly Dictionary<string, AviUtlParameterMapping> _parameters;
|
||||
@@ -0,0 +1,9 @@
|
||||
namespace LuaScript.Compat
|
||||
{
|
||||
internal enum AviUtlEngine
|
||||
{
|
||||
AviUtl,
|
||||
AviUtl2,
|
||||
Both,
|
||||
}
|
||||
}
|
||||
@@ -1,12 +1,5 @@
|
||||
namespace LuaScript.Compat
|
||||
{
|
||||
internal enum AviUtlEngine
|
||||
{
|
||||
AviUtl,
|
||||
AviUtl2,
|
||||
Both,
|
||||
}
|
||||
|
||||
internal static class AviUtlEngineExtensions
|
||||
{
|
||||
public static bool Includes(this AviUtlEngine scope, AviUtlEngine target) =>
|
||||
@@ -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;
|
||||
}
|
||||
}
|
||||
差分なしでファイル名を変更。
+3
-34
@@ -43,26 +43,8 @@ namespace LuaScript.Compat
|
||||
if (string.IsNullOrEmpty(source))
|
||||
return layout;
|
||||
|
||||
var lines = source.Replace("\r\n", "\n").Replace("\r", "\n").Split('\n');
|
||||
|
||||
int sectionStart = 0;
|
||||
int sectionEnd = lines.Length;
|
||||
for (int i = 0; i < lines.Length; i++)
|
||||
{
|
||||
if (!ScriptParserHelper.IsSectionHeader(lines[i]))
|
||||
continue;
|
||||
sectionStart = i + 1;
|
||||
sectionEnd = lines.Length;
|
||||
for (int j = sectionStart; j < lines.Length; j++)
|
||||
{
|
||||
if (ScriptParserHelper.IsSectionHeader(lines[j]))
|
||||
{
|
||||
sectionEnd = j;
|
||||
break;
|
||||
}
|
||||
}
|
||||
break;
|
||||
}
|
||||
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]);
|
||||
@@ -72,21 +54,8 @@ namespace LuaScript.Compat
|
||||
|
||||
private void ParseLine(string line)
|
||||
{
|
||||
int i = ScriptParserHelper.SkipSpaces(line, 0);
|
||||
if (i + 1 >= line.Length || line[i] != '-' || line[i + 1] != '-')
|
||||
if (!ScriptParserHelper.TryParseDirective(line, out string name, out string content))
|
||||
return;
|
||||
i += 2;
|
||||
if (i < line.Length && line[i] == '!')
|
||||
return;
|
||||
|
||||
int nameStart = i;
|
||||
while (i < line.Length && ScriptParserHelper.IsNameChar(line[i]))
|
||||
i++;
|
||||
if (i >= line.Length || line[i] != ':')
|
||||
return;
|
||||
|
||||
string name = line.Substring(nameStart, i - nameStart);
|
||||
string content = line.Substring(i + 1);
|
||||
|
||||
if (name.StartsWith("track", StringComparison.OrdinalIgnoreCase) &&
|
||||
TryGetIndex(name, 5, MaxTracks, out int trackIndex))
|
||||
@@ -20,30 +20,8 @@ namespace LuaScript.Compat
|
||||
if (string.IsNullOrEmpty(source))
|
||||
return (source, []);
|
||||
|
||||
var lines = source.Replace("\r\n", "\n").Replace("\r", "\n").Split('\n');
|
||||
|
||||
int sectionStart = 0;
|
||||
int sectionEnd = lines.Length;
|
||||
bool hasSection = false;
|
||||
|
||||
for (int i = 0; i < lines.Length; i++)
|
||||
{
|
||||
if (!ScriptParserHelper.IsSectionHeader(lines[i]))
|
||||
continue;
|
||||
|
||||
hasSection = true;
|
||||
sectionStart = i + 1;
|
||||
sectionEnd = lines.Length;
|
||||
for (int j = sectionStart; j < lines.Length; j++)
|
||||
{
|
||||
if (ScriptParserHelper.IsSectionHeader(lines[j]))
|
||||
{
|
||||
sectionEnd = j;
|
||||
break;
|
||||
}
|
||||
}
|
||||
break;
|
||||
}
|
||||
var 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++)
|
||||
@@ -72,21 +50,8 @@ namespace LuaScript.Compat
|
||||
|
||||
private static void AppendDeclarations(string line, List<string> prelude)
|
||||
{
|
||||
int i = ScriptParserHelper.SkipSpaces(line, 0);
|
||||
if (i + 1 >= line.Length || line[i] != '-' || line[i + 1] != '-')
|
||||
if (!ScriptParserHelper.TryParseDirective(line, out string name, out string content))
|
||||
return;
|
||||
i += 2;
|
||||
if (i < line.Length && line[i] == '!')
|
||||
return;
|
||||
|
||||
int nameStart = i;
|
||||
while (i < line.Length && ScriptParserHelper.IsNameChar(line[i]))
|
||||
i++;
|
||||
if (i >= line.Length || line[i] != ':')
|
||||
return;
|
||||
|
||||
string name = line.Substring(nameStart, i - nameStart);
|
||||
string content = line.Substring(i + 1);
|
||||
|
||||
switch (Classify(name))
|
||||
{
|
||||
差分なしでファイル名を変更。
@@ -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;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -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();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,4 @@
|
||||
namespace System.Runtime.CompilerServices
|
||||
{
|
||||
internal static class IsExternalInit;
|
||||
}
|
||||
@@ -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)];
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -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.13.4</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>
|
||||
@@ -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);
|
||||
}
|
||||
}
|
||||
}
|
||||
+12
-6
@@ -31,11 +31,15 @@ namespace LuaScript.Engine.Kernel
|
||||
[KFunc.Max] = Binary(nameof(Math.Max)),
|
||||
};
|
||||
|
||||
public static CpuKernel Compile(KernelProgram program)
|
||||
public static CpuKernel Compile(KernelProgram program) =>
|
||||
new(CompileRow(program), SimdKernelCompiler.TryCompile(program));
|
||||
|
||||
public static CpuKernel.RowDelegate CompileRow(KernelProgram program)
|
||||
{
|
||||
var buffer = Expression.Parameter(typeof(byte[]), "buffer");
|
||||
var width = Expression.Parameter(typeof(int), "width");
|
||||
var rowBase = Expression.Parameter(typeof(int), "rowBase");
|
||||
var xStart = Expression.Parameter(typeof(int), "xStart");
|
||||
var xEnd = Expression.Parameter(typeof(int), "xEnd");
|
||||
var y = Expression.Parameter(typeof(double), "y");
|
||||
var uniforms = Expression.Parameter(typeof(double[]), "uniforms");
|
||||
|
||||
@@ -85,7 +89,7 @@ namespace LuaScript.Engine.Kernel
|
||||
var breakLabel = Expression.Label("break");
|
||||
var loop = Expression.Loop(
|
||||
Expression.IfThenElse(
|
||||
Expression.LessThan(x, width),
|
||||
Expression.LessThan(x, xEnd),
|
||||
Expression.Block(statements),
|
||||
Expression.Break(breakLabel)),
|
||||
breakLabel);
|
||||
@@ -94,10 +98,10 @@ namespace LuaScript.Engine.Kernel
|
||||
locals.AddRange(inputs);
|
||||
locals.AddRange(slots);
|
||||
|
||||
var body = Expression.Block(locals, Expression.Assign(x, Constant(0)), loop);
|
||||
var body = Expression.Block(locals, Expression.Assign(x, xStart), loop);
|
||||
|
||||
var lambda = Expression.Lambda<CpuKernel.RowDelegate>(body, buffer, width, rowBase, y, uniforms);
|
||||
return new CpuKernel(lambda.Compile());
|
||||
var lambda = Expression.Lambda<CpuKernel.RowDelegate>(body, buffer, rowBase, xStart, xEnd, y, uniforms);
|
||||
return lambda.Compile();
|
||||
}
|
||||
|
||||
private sealed record Context(
|
||||
@@ -151,6 +155,8 @@ namespace LuaScript.Engine.Kernel
|
||||
|
||||
private static Expression BuildCall(KCall call, Context context)
|
||||
{
|
||||
if (call.Func == KFunc.Fmod)
|
||||
return Expression.Modulo(Build(call.Arguments[0], context), Build(call.Arguments[1], context));
|
||||
var method = Functions[call.Func];
|
||||
if (call.Arguments.Count == 1)
|
||||
return Expression.Call(method, Build(call.Arguments[0], context));
|
||||
+1
-7
@@ -9,12 +9,6 @@ namespace LuaScript.Engine.Kernel
|
||||
|
||||
public const int ConstantFloatCount = ConstantVectorCount * 4;
|
||||
|
||||
private static readonly string[] Intrinsics =
|
||||
[
|
||||
"abs", "floor", "ceil", "sqrt", "sin", "cos", "tan", "asin", "acos",
|
||||
"atan", "atan2", "exp", "log", "pow", "min", "max", "fmod",
|
||||
];
|
||||
|
||||
public static string Emit(KernelProgram program)
|
||||
{
|
||||
var builder = new StringBuilder(1024);
|
||||
@@ -153,7 +147,7 @@ namespace LuaScript.Engine.Kernel
|
||||
|
||||
private static void EmitCall(StringBuilder builder, KCall call)
|
||||
{
|
||||
builder.Append(Intrinsics[(int)call.Func]).Append('(');
|
||||
builder.Append(KFunctions.Intrinsic(call.Func)).Append('(');
|
||||
for (int i = 0; i < call.Arguments.Count; i++)
|
||||
{
|
||||
if (i > 0)
|
||||
+173
-37
@@ -5,29 +5,6 @@ namespace LuaScript.Engine.Kernel
|
||||
{
|
||||
internal sealed class KernelExtractor
|
||||
{
|
||||
private readonly record struct FuncSpec(KFunc Func, int MinArgs, int MaxArgs);
|
||||
|
||||
private static readonly Dictionary<string, FuncSpec> MathFunctions = new(StringComparer.Ordinal)
|
||||
{
|
||||
["abs"] = new(KFunc.Abs, 1, 1),
|
||||
["floor"] = new(KFunc.Floor, 1, 1),
|
||||
["ceil"] = new(KFunc.Ceil, 1, 1),
|
||||
["sqrt"] = new(KFunc.Sqrt, 1, 1),
|
||||
["sin"] = new(KFunc.Sin, 1, 1),
|
||||
["cos"] = new(KFunc.Cos, 1, 1),
|
||||
["tan"] = new(KFunc.Tan, 1, 1),
|
||||
["asin"] = new(KFunc.Asin, 1, 1),
|
||||
["acos"] = new(KFunc.Acos, 1, 1),
|
||||
["atan"] = new(KFunc.Atan, 1, 1),
|
||||
["atan2"] = new(KFunc.Atan2, 2, 2),
|
||||
["exp"] = new(KFunc.Exp, 1, 1),
|
||||
["log"] = new(KFunc.Log, 1, 1),
|
||||
["pow"] = new(KFunc.Pow, 2, 2),
|
||||
["fmod"] = new(KFunc.Fmod, 2, 2),
|
||||
["min"] = new(KFunc.Min, 2, int.MaxValue),
|
||||
["max"] = new(KFunc.Max, 2, int.MaxValue),
|
||||
};
|
||||
|
||||
private readonly List<KExpr> _bindings = [];
|
||||
private readonly Dictionary<string, int> _scope = new(StringComparer.Ordinal);
|
||||
private readonly SortedSet<KernelUniform> _uniforms = [];
|
||||
@@ -35,6 +12,9 @@ namespace LuaScript.Engine.Kernel
|
||||
private string _widthVariable = string.Empty;
|
||||
private string _heightVariable = string.Empty;
|
||||
private bool _coordsEnabled;
|
||||
private string? _pixelDataVariable;
|
||||
private string _baseIndexVariable = string.Empty;
|
||||
private readonly bool[] _writtenChannels = new bool[4];
|
||||
|
||||
public static KernelProgram? TryExtract(string runnableScript)
|
||||
{
|
||||
@@ -55,6 +35,11 @@ namespace LuaScript.Engine.Kernel
|
||||
int index = 0;
|
||||
while (index < block.Count && block[index] is LocalStmt prelude)
|
||||
{
|
||||
if (TryBindPixelData(prelude))
|
||||
{
|
||||
index++;
|
||||
continue;
|
||||
}
|
||||
BindLocal(prelude);
|
||||
index++;
|
||||
}
|
||||
@@ -72,11 +57,140 @@ namespace LuaScript.Engine.Kernel
|
||||
return null;
|
||||
if (outerAxis == innerAxis)
|
||||
return null;
|
||||
if (_pixelDataVariable is not null &&
|
||||
(string.Equals(outerVar, _pixelDataVariable, StringComparison.Ordinal) ||
|
||||
string.Equals(innerVar, _pixelDataVariable, StringComparison.Ordinal)))
|
||||
return null;
|
||||
if (_scope.ContainsKey(outerVar))
|
||||
_scope.Remove(outerVar);
|
||||
if (_scope.ContainsKey(innerVar))
|
||||
_scope.Remove(innerVar);
|
||||
|
||||
_widthVariable = outerAxis == KAxis.X ? outerVar : innerVar;
|
||||
_heightVariable = outerAxis == KAxis.Y ? outerVar : innerVar;
|
||||
|
||||
return BuildKernel(inner.Body);
|
||||
return _pixelDataVariable is null ? BuildKernel(inner.Body) : BuildPixelDataKernel(inner.Body);
|
||||
}
|
||||
|
||||
private bool TryBindPixelData(LocalStmt local)
|
||||
{
|
||||
if (local.Names.Count != 1 || local.Values.Count != 1 ||
|
||||
local.Values[0] is not CallExpr { Target: MemberExpr { Target: NameExpr { Name: "obj" }, Name: "getpixeldata" }, Arguments.Count: 0 })
|
||||
return false;
|
||||
if (_pixelDataVariable is not null)
|
||||
throw new KernelUnsupportedException("Multiple pixel-data handles are not supported.");
|
||||
_pixelDataVariable = local.Names[0];
|
||||
return true;
|
||||
}
|
||||
|
||||
private KernelProgram? BuildPixelDataKernel(IReadOnlyList<LuaStmt> body)
|
||||
{
|
||||
if (body.Count < 5)
|
||||
return null;
|
||||
if (body[0] is not LocalStmt { Names.Count: 1, Values.Count: 1 } baseStmt || !IsBaseIndex(baseStmt.Values[0]))
|
||||
return null;
|
||||
|
||||
EnsureNotCoordinateName(baseStmt.Names[0]);
|
||||
_baseIndexVariable = baseStmt.Names[0];
|
||||
_coordsEnabled = true;
|
||||
|
||||
KExpr? outR = null, outG = null, outB = null;
|
||||
for (int i = 1; i < body.Count; i++)
|
||||
{
|
||||
switch (body[i])
|
||||
{
|
||||
case LocalStmt local:
|
||||
BindLocal(local);
|
||||
break;
|
||||
case AssignStmt assign:
|
||||
BindAssign(assign);
|
||||
break;
|
||||
case CallStmt { Call: MethodCallExpr set } when IsPixelDataSet(set, out int writeChannel):
|
||||
var value = ClampChannel(Lower(set.Arguments[1]));
|
||||
if (writeChannel == 0) outR = value;
|
||||
else if (writeChannel == 1) outG = value;
|
||||
else outB = value;
|
||||
_writtenChannels[writeChannel] = true;
|
||||
break;
|
||||
default:
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
if (outR is null || outG is null || outB is null)
|
||||
return null;
|
||||
|
||||
return new KernelProgram(_bindings, outR, outG, outB, new KInput(KChannel.A), [.. _uniforms]);
|
||||
}
|
||||
|
||||
private bool IsBaseIndex(LuaExpr expression)
|
||||
{
|
||||
if (expression is not BinaryExpr { Operator: "*", Right: NumberExpr { Value: 4d } } scaled ||
|
||||
scaled.Left is not BinaryExpr { Operator: "+" } sum)
|
||||
return false;
|
||||
if (!IsCoordinate(sum.Right, KAxis.X))
|
||||
return false;
|
||||
if (sum.Left is not BinaryExpr { Operator: "*" } stride)
|
||||
return false;
|
||||
return IsCoordinate(stride.Left, KAxis.Y) && IsWidth(stride.Right);
|
||||
}
|
||||
|
||||
private bool IsWidth(LuaExpr expression)
|
||||
{
|
||||
if (expression is MemberExpr { Target: NameExpr { Name: "obj" }, Name: var field } &&
|
||||
KernelUniforms.TryResolveMember("obj", field, out var uniform))
|
||||
return uniform == KernelUniform.Width;
|
||||
return _pixelDataVariable is not null &&
|
||||
expression is MemberExpr { Target: NameExpr { } target, Name: "width" } &&
|
||||
string.Equals(target.Name, _pixelDataVariable, StringComparison.Ordinal);
|
||||
}
|
||||
|
||||
private bool TryPixelDataChannel(LuaExpr expression, out int channel)
|
||||
{
|
||||
channel = 0;
|
||||
if (expression is not MethodCallExpr { Method: "get", Arguments.Count: 1 } call ||
|
||||
call.Target is not NameExpr { } handle ||
|
||||
!string.Equals(handle.Name, _pixelDataVariable, StringComparison.Ordinal))
|
||||
return false;
|
||||
if (!TryChannelOffset(call.Arguments[0], 1, 4, out channel))
|
||||
return false;
|
||||
channel--;
|
||||
return !_writtenChannels[channel];
|
||||
}
|
||||
|
||||
private bool IsPixelDataSet(MethodCallExpr call, out int channel)
|
||||
{
|
||||
channel = 0;
|
||||
if (call.Method != "set" || call.Arguments.Count != 2 ||
|
||||
call.Target is not NameExpr { } handle ||
|
||||
!string.Equals(handle.Name, _pixelDataVariable, StringComparison.Ordinal))
|
||||
return false;
|
||||
if (!TryChannelOffset(call.Arguments[0], 1, 3, out channel))
|
||||
return false;
|
||||
channel--;
|
||||
return true;
|
||||
}
|
||||
|
||||
private KExpr ClampChannel(KExpr value)
|
||||
{
|
||||
var bound = new KLocalRef(AddBinding(value));
|
||||
return new KSelect(
|
||||
new KCompare(KCompareOp.Less, bound, new KConst(0d)),
|
||||
new KConst(0d),
|
||||
new KSelect(
|
||||
new KCompare(KCompareOp.Greater, bound, new KConst(255d)),
|
||||
new KConst(255d),
|
||||
bound));
|
||||
}
|
||||
|
||||
private bool TryChannelOffset(LuaExpr expression, int min, int max, out int offset)
|
||||
{
|
||||
offset = 0;
|
||||
if (expression is not BinaryExpr { Operator: "+", Left: NameExpr baseName, Right: NumberExpr number } ||
|
||||
!string.Equals(baseName.Name, _baseIndexVariable, StringComparison.Ordinal))
|
||||
return false;
|
||||
offset = (int)number.Value;
|
||||
return offset == number.Value && offset >= min && offset <= max;
|
||||
}
|
||||
|
||||
private KernelProgram? BuildKernel(IReadOnlyList<LuaStmt> body)
|
||||
@@ -112,7 +226,7 @@ namespace LuaScript.Engine.Kernel
|
||||
}
|
||||
}
|
||||
|
||||
if (body[^1] is not CallStmt { Call: var call } || !IsObjectMethod(call, "setpixel"))
|
||||
if (body[^1] is not CallStmt { Call: CallExpr call } || !IsObjectMethod(call, "setpixel"))
|
||||
return null;
|
||||
if (call.Arguments.Count is < 5 or > 6)
|
||||
return null;
|
||||
@@ -167,6 +281,10 @@ namespace LuaScript.Engine.Kernel
|
||||
if (string.Equals(name, _widthVariable, StringComparison.Ordinal) ||
|
||||
string.Equals(name, _heightVariable, StringComparison.Ordinal))
|
||||
throw new KernelUnsupportedException("Local variable shadows a loop coordinate.");
|
||||
if (_pixelDataVariable is not null && string.Equals(name, _pixelDataVariable, StringComparison.Ordinal))
|
||||
throw new KernelUnsupportedException("Local variable shadows the pixel-data handle.");
|
||||
if (_baseIndexVariable.Length > 0 && string.Equals(name, _baseIndexVariable, StringComparison.Ordinal))
|
||||
throw new KernelUnsupportedException("Local variable shadows the base index.");
|
||||
}
|
||||
|
||||
private int AddBinding(KExpr expression)
|
||||
@@ -187,6 +305,8 @@ namespace LuaScript.Engine.Kernel
|
||||
return LowerMember(member);
|
||||
case CallExpr call:
|
||||
return LowerCall(call);
|
||||
case MethodCallExpr method when TryPixelDataChannel(method, out int channel):
|
||||
return new KInput((KChannel)channel);
|
||||
case UnaryExpr { Operator: "-" } unary:
|
||||
return new KNegate(Lower(unary.Operand));
|
||||
case BinaryExpr binary:
|
||||
@@ -229,7 +349,7 @@ namespace LuaScript.Engine.Kernel
|
||||
private KExpr LowerCall(CallExpr call)
|
||||
{
|
||||
if (call.Target is not MemberExpr { Target: NameExpr { Name: "math" }, Name: var function } ||
|
||||
!MathFunctions.TryGetValue(function, out var spec))
|
||||
!KFunctions.TryResolve(function, out var spec))
|
||||
throw new KernelUnsupportedException("Unsupported function call in pixel kernel.");
|
||||
|
||||
int count = call.Arguments.Count;
|
||||
@@ -323,20 +443,36 @@ namespace LuaScript.Engine.Kernel
|
||||
return false;
|
||||
if (loop.Stop is not BinaryExpr { Operator: "-", Right: NumberExpr { Value: 1d } } bound)
|
||||
return false;
|
||||
if (bound.Left is not MemberExpr { Target: NameExpr { Name: "obj" }, Name: var field })
|
||||
return false;
|
||||
if (!KernelUniforms.TryResolveMember("obj", field, out var uniform))
|
||||
return false;
|
||||
|
||||
if (uniform == KernelUniform.Width)
|
||||
if (bound.Left is MemberExpr { Target: NameExpr { Name: "obj" }, Name: var field } &&
|
||||
KernelUniforms.TryResolveMember("obj", field, out var uniform))
|
||||
{
|
||||
axis = KAxis.X;
|
||||
return true;
|
||||
if (uniform == KernelUniform.Width)
|
||||
{
|
||||
axis = KAxis.X;
|
||||
return true;
|
||||
}
|
||||
if (uniform == KernelUniform.Height)
|
||||
{
|
||||
axis = KAxis.Y;
|
||||
return true;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
if (uniform == KernelUniform.Height)
|
||||
|
||||
if (_pixelDataVariable is not null &&
|
||||
bound.Left is MemberExpr { Target: NameExpr { } handle, Name: var pixelField } &&
|
||||
string.Equals(handle.Name, _pixelDataVariable, StringComparison.Ordinal))
|
||||
{
|
||||
axis = KAxis.Y;
|
||||
return true;
|
||||
if (pixelField == "width")
|
||||
{
|
||||
axis = KAxis.X;
|
||||
return true;
|
||||
}
|
||||
if (pixelField == "height")
|
||||
{
|
||||
axis = KAxis.Y;
|
||||
return true;
|
||||
}
|
||||
}
|
||||
return false;
|
||||
}
|
||||
差分なしでファイル名を変更。
@@ -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<>);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,4 @@
|
||||
namespace LuaScript.Engine.Kernel
|
||||
{
|
||||
internal sealed record KArith(KArithOp Op, KExpr Left, KExpr Right) : KExpr;
|
||||
}
|
||||
@@ -0,0 +1,12 @@
|
||||
namespace LuaScript.Engine.Kernel
|
||||
{
|
||||
internal enum KArithOp
|
||||
{
|
||||
Add,
|
||||
Subtract,
|
||||
Multiply,
|
||||
Divide,
|
||||
Modulo,
|
||||
Power,
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,8 @@
|
||||
namespace LuaScript.Engine.Kernel
|
||||
{
|
||||
internal enum KAxis
|
||||
{
|
||||
X,
|
||||
Y,
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,4 @@
|
||||
namespace LuaScript.Engine.Kernel
|
||||
{
|
||||
internal abstract record KBool;
|
||||
}
|
||||
@@ -0,0 +1,4 @@
|
||||
namespace LuaScript.Engine.Kernel
|
||||
{
|
||||
internal sealed record KBoolConst(bool Value) : KBool;
|
||||
}
|
||||
@@ -0,0 +1,4 @@
|
||||
namespace LuaScript.Engine.Kernel
|
||||
{
|
||||
internal sealed record KCall(KFunc Func, IReadOnlyList<KExpr> Arguments) : KExpr;
|
||||
}
|
||||
@@ -0,0 +1,10 @@
|
||||
namespace LuaScript.Engine.Kernel
|
||||
{
|
||||
internal enum KChannel
|
||||
{
|
||||
R,
|
||||
G,
|
||||
B,
|
||||
A,
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,4 @@
|
||||
namespace LuaScript.Engine.Kernel
|
||||
{
|
||||
internal sealed record KCompare(KCompareOp Op, KExpr Left, KExpr Right) : KBool;
|
||||
}
|
||||
@@ -0,0 +1,12 @@
|
||||
namespace LuaScript.Engine.Kernel
|
||||
{
|
||||
internal enum KCompareOp
|
||||
{
|
||||
Less,
|
||||
Greater,
|
||||
LessEqual,
|
||||
GreaterEqual,
|
||||
Equal,
|
||||
NotEqual,
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,4 @@
|
||||
namespace LuaScript.Engine.Kernel
|
||||
{
|
||||
internal sealed record KConst(double Value) : KExpr;
|
||||
}
|
||||
@@ -0,0 +1,4 @@
|
||||
namespace LuaScript.Engine.Kernel
|
||||
{
|
||||
internal sealed record KCoord(KAxis Axis) : KExpr;
|
||||
}
|
||||
@@ -0,0 +1,4 @@
|
||||
namespace LuaScript.Engine.Kernel
|
||||
{
|
||||
internal abstract record KExpr;
|
||||
}
|
||||
@@ -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,
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,4 @@
|
||||
namespace LuaScript.Engine.Kernel
|
||||
{
|
||||
internal readonly record struct KFunctionInfo(KFunc Func, string Name, int MinArgs, int MaxArgs);
|
||||
}
|
||||
@@ -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;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,4 @@
|
||||
namespace LuaScript.Engine.Kernel
|
||||
{
|
||||
internal sealed record KInput(KChannel Channel) : KExpr;
|
||||
}
|
||||
@@ -0,0 +1,4 @@
|
||||
namespace LuaScript.Engine.Kernel
|
||||
{
|
||||
internal sealed record KLocalRef(int Slot) : KExpr;
|
||||
}
|
||||
@@ -0,0 +1,4 @@
|
||||
namespace LuaScript.Engine.Kernel
|
||||
{
|
||||
internal sealed record KLogical(bool IsAnd, KBool Left, KBool Right) : KBool;
|
||||
}
|
||||
@@ -0,0 +1,4 @@
|
||||
namespace LuaScript.Engine.Kernel
|
||||
{
|
||||
internal sealed record KNegate(KExpr Operand) : KExpr;
|
||||
}
|
||||
@@ -0,0 +1,4 @@
|
||||
namespace LuaScript.Engine.Kernel
|
||||
{
|
||||
internal sealed record KNot(KBool Operand) : KBool;
|
||||
}
|
||||
@@ -0,0 +1,4 @@
|
||||
namespace LuaScript.Engine.Kernel
|
||||
{
|
||||
internal sealed record KSelect(KBool Condition, KExpr WhenTrue, KExpr WhenFalse) : KExpr;
|
||||
}
|
||||
@@ -0,0 +1,4 @@
|
||||
namespace LuaScript.Engine.Kernel
|
||||
{
|
||||
internal sealed record KUniformRef(KernelUniform Uniform) : KExpr;
|
||||
}
|
||||
@@ -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);
|
||||
}
|
||||
@@ -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,
|
||||
}
|
||||
}
|
||||
@@ -3,64 +3,6 @@ using System.Collections.Generic;
|
||||
|
||||
namespace LuaScript.Engine.Kernel
|
||||
{
|
||||
internal enum KernelUniform
|
||||
{
|
||||
Width,
|
||||
Height,
|
||||
HalfWidth,
|
||||
HalfHeight,
|
||||
CenterX,
|
||||
CenterY,
|
||||
CenterZ,
|
||||
Diagonal,
|
||||
X,
|
||||
Y,
|
||||
Z,
|
||||
Ox,
|
||||
Oy,
|
||||
Oz,
|
||||
Sx,
|
||||
Sy,
|
||||
Sz,
|
||||
Zoom,
|
||||
Aspect,
|
||||
Alpha,
|
||||
Rx,
|
||||
Ry,
|
||||
Rz,
|
||||
Rxr,
|
||||
Ryr,
|
||||
Rzr,
|
||||
Track0,
|
||||
Track1,
|
||||
Track2,
|
||||
Track3,
|
||||
Slider0,
|
||||
Slider1,
|
||||
Slider2,
|
||||
Slider3,
|
||||
Check0,
|
||||
Check1,
|
||||
Check2,
|
||||
Check3,
|
||||
Color,
|
||||
Time,
|
||||
Frame,
|
||||
TotalFrame,
|
||||
TotalTime,
|
||||
T,
|
||||
Framerate,
|
||||
Layer,
|
||||
Index,
|
||||
Num,
|
||||
SceneWidth,
|
||||
SceneHeight,
|
||||
SceneCenterX,
|
||||
SceneCenterY,
|
||||
TimelineFrame,
|
||||
TimelineTime,
|
||||
}
|
||||
|
||||
internal static class KernelUniforms
|
||||
{
|
||||
public static int Count { get; } = Enum.GetValues<KernelUniform>().Length;
|
||||
@@ -0,0 +1,4 @@
|
||||
namespace LuaScript.Engine.Kernel
|
||||
{
|
||||
internal sealed record AssignStmt(IReadOnlyList<LuaExpr> Targets, IReadOnlyList<LuaExpr> Values) : LuaStmt;
|
||||
}
|
||||
@@ -0,0 +1,4 @@
|
||||
namespace LuaScript.Engine.Kernel
|
||||
{
|
||||
internal sealed record BinaryExpr(string Operator, LuaExpr Left, LuaExpr Right) : LuaExpr;
|
||||
}
|
||||
@@ -0,0 +1,4 @@
|
||||
namespace LuaScript.Engine.Kernel
|
||||
{
|
||||
internal sealed record BoolExpr(bool Value) : LuaExpr;
|
||||
}
|
||||
@@ -0,0 +1,4 @@
|
||||
namespace LuaScript.Engine.Kernel
|
||||
{
|
||||
internal sealed record CallExpr(LuaExpr Target, IReadOnlyList<LuaExpr> Arguments) : LuaExpr;
|
||||
}
|
||||
@@ -0,0 +1,4 @@
|
||||
namespace LuaScript.Engine.Kernel
|
||||
{
|
||||
internal sealed record CallStmt(LuaExpr Call) : LuaStmt;
|
||||
}
|
||||
@@ -0,0 +1,4 @@
|
||||
namespace LuaScript.Engine.Kernel
|
||||
{
|
||||
internal sealed record IfClause(LuaExpr Condition, IReadOnlyList<LuaStmt> Body);
|
||||
}
|
||||
@@ -0,0 +1,4 @@
|
||||
namespace LuaScript.Engine.Kernel
|
||||
{
|
||||
internal sealed record IfStmt(IReadOnlyList<IfClause> Clauses, IReadOnlyList<LuaStmt>? ElseBody) : LuaStmt;
|
||||
}
|
||||
@@ -0,0 +1,4 @@
|
||||
namespace LuaScript.Engine.Kernel
|
||||
{
|
||||
internal sealed record IndexExpr(LuaExpr Target, LuaExpr Key) : LuaExpr;
|
||||
}
|
||||
@@ -0,0 +1,4 @@
|
||||
namespace LuaScript.Engine.Kernel
|
||||
{
|
||||
internal sealed record LocalStmt(IReadOnlyList<string> Names, IReadOnlyList<LuaExpr> Values) : LuaStmt;
|
||||
}
|
||||
@@ -0,0 +1,4 @@
|
||||
namespace LuaScript.Engine.Kernel
|
||||
{
|
||||
internal abstract record LuaExpr;
|
||||
}
|
||||
@@ -0,0 +1,4 @@
|
||||
namespace LuaScript.Engine.Kernel
|
||||
{
|
||||
internal abstract record LuaStmt;
|
||||
}
|
||||
@@ -0,0 +1,4 @@
|
||||
namespace LuaScript.Engine.Kernel
|
||||
{
|
||||
internal sealed record MemberExpr(LuaExpr Target, string Name) : LuaExpr;
|
||||
}
|
||||
@@ -0,0 +1,4 @@
|
||||
namespace LuaScript.Engine.Kernel
|
||||
{
|
||||
internal sealed record MethodCallExpr(LuaExpr Target, string Method, IReadOnlyList<LuaExpr> Arguments) : LuaExpr;
|
||||
}
|
||||
@@ -0,0 +1,4 @@
|
||||
namespace LuaScript.Engine.Kernel
|
||||
{
|
||||
internal sealed record NameExpr(string Name) : LuaExpr;
|
||||
}
|
||||
@@ -0,0 +1,4 @@
|
||||
namespace LuaScript.Engine.Kernel
|
||||
{
|
||||
internal sealed record NilExpr : LuaExpr;
|
||||
}
|
||||
@@ -0,0 +1,4 @@
|
||||
namespace LuaScript.Engine.Kernel
|
||||
{
|
||||
internal sealed record NumberExpr(double Value) : LuaExpr;
|
||||
}
|
||||
@@ -0,0 +1,9 @@
|
||||
namespace LuaScript.Engine.Kernel
|
||||
{
|
||||
internal sealed record NumericForStmt(
|
||||
string Variable,
|
||||
LuaExpr Start,
|
||||
LuaExpr Stop,
|
||||
LuaExpr? Step,
|
||||
IReadOnlyList<LuaStmt> Body) : LuaStmt;
|
||||
}
|
||||
@@ -0,0 +1,4 @@
|
||||
namespace LuaScript.Engine.Kernel
|
||||
{
|
||||
internal sealed record StringExpr(string Value) : LuaExpr;
|
||||
}
|
||||
@@ -0,0 +1,4 @@
|
||||
namespace LuaScript.Engine.Kernel
|
||||
{
|
||||
internal sealed record UnaryExpr(string Operator, LuaExpr Operand) : LuaExpr;
|
||||
}
|
||||
@@ -149,8 +149,8 @@ namespace LuaScript.Engine.Kernel
|
||||
return new AssignStmt(targets, values);
|
||||
}
|
||||
|
||||
if (first is CallExpr call)
|
||||
return new CallStmt(call);
|
||||
if (first is CallExpr or MethodCallExpr)
|
||||
return new CallStmt(first);
|
||||
|
||||
throw new KernelUnsupportedException("Expression is not a valid statement.");
|
||||
}
|
||||
@@ -275,6 +275,12 @@ namespace LuaScript.Engine.Kernel
|
||||
{
|
||||
expression = new CallExpr(expression, ParseArguments());
|
||||
}
|
||||
else if (t.IsSymbol(":"))
|
||||
{
|
||||
Advance();
|
||||
string method = ExpectName();
|
||||
expression = new MethodCallExpr(expression, method, ParseArguments());
|
||||
}
|
||||
else
|
||||
{
|
||||
break;
|
||||
@@ -2,16 +2,6 @@ using System;
|
||||
|
||||
namespace LuaScript.Engine.Kernel
|
||||
{
|
||||
internal enum LuaTokenKind
|
||||
{
|
||||
Name,
|
||||
Number,
|
||||
String,
|
||||
Keyword,
|
||||
Symbol,
|
||||
Eof,
|
||||
}
|
||||
|
||||
internal readonly struct LuaToken(LuaTokenKind kind, string text, double number)
|
||||
{
|
||||
public LuaTokenKind Kind { get; } = kind;
|
||||
@@ -0,0 +1,12 @@
|
||||
namespace LuaScript.Engine.Kernel
|
||||
{
|
||||
internal enum LuaTokenKind
|
||||
{
|
||||
Name,
|
||||
Number,
|
||||
String,
|
||||
Keyword,
|
||||
Symbol,
|
||||
Eof,
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,18 @@
|
||||
<Project Sdk="Microsoft.NET.Sdk">
|
||||
|
||||
<PropertyGroup>
|
||||
<TargetFramework>net10.0-windows10.0.19041.0</TargetFramework>
|
||||
<ImplicitUsings>enable</ImplicitUsings>
|
||||
<Version>1.13.4</Version>
|
||||
<Platforms>AnyCPU;x64</Platforms>
|
||||
<Nullable>enable</Nullable>
|
||||
</PropertyGroup>
|
||||
|
||||
<ItemGroup>
|
||||
<InternalsVisibleTo Include="LuaScript" />
|
||||
<InternalsVisibleTo Include="LuaScript.Compat" />
|
||||
<InternalsVisibleTo Include="LuaScript.Runtime" />
|
||||
<InternalsVisibleTo Include="LuaScript.Tests" />
|
||||
</ItemGroup>
|
||||
|
||||
</Project>
|
||||
@@ -0,0 +1,48 @@
|
||||
<Project Sdk="Microsoft.NET.Sdk">
|
||||
|
||||
<PropertyGroup>
|
||||
<TargetFramework>net10.0-windows10.0.19041.0</TargetFramework>
|
||||
<ImplicitUsings>enable</ImplicitUsings>
|
||||
<Version>1.13.4</Version>
|
||||
<Platforms>AnyCPU;x64</Platforms>
|
||||
<Nullable>enable</Nullable>
|
||||
<AllowUnsafeBlocks>true</AllowUnsafeBlocks>
|
||||
</PropertyGroup>
|
||||
|
||||
<ItemGroup>
|
||||
<InternalsVisibleTo Include="LuaScript" />
|
||||
<InternalsVisibleTo Include="LuaScript.Tests" />
|
||||
</ItemGroup>
|
||||
|
||||
<ItemGroup>
|
||||
<Reference Include="SharpGen.Runtime">
|
||||
<HintPath>$(YMM4DirPath)SharpGen.Runtime.dll</HintPath>
|
||||
<Private>false</Private>
|
||||
</Reference>
|
||||
<Reference Include="SharpGen.Runtime.COM">
|
||||
<HintPath>$(YMM4DirPath)SharpGen.Runtime.COM.dll</HintPath>
|
||||
<Private>false</Private>
|
||||
</Reference>
|
||||
<Reference Include="Vortice.Direct2D1">
|
||||
<HintPath>$(YMM4DirPath)Vortice.Direct2D1.dll</HintPath>
|
||||
<Private>false</Private>
|
||||
</Reference>
|
||||
<Reference Include="Vortice.DirectX">
|
||||
<HintPath>$(YMM4DirPath)Vortice.DirectX.dll</HintPath>
|
||||
<Private>false</Private>
|
||||
</Reference>
|
||||
<Reference Include="Vortice.DXGI.dll">
|
||||
<HintPath>$(YMM4DirPath)Vortice.DXGI.dll</HintPath>
|
||||
<Private>false</Private>
|
||||
</Reference>
|
||||
<Reference Include="Vortice.Mathematics">
|
||||
<HintPath>$(YMM4DirPath)Vortice.Mathematics.dll</HintPath>
|
||||
<Private>false</Private>
|
||||
</Reference>
|
||||
<Reference Include="Vortice.MediaFoundation">
|
||||
<HintPath>$(YMM4DirPath)Vortice.MediaFoundation.dll</HintPath>
|
||||
<Private>false</Private>
|
||||
</Reference>
|
||||
</ItemGroup>
|
||||
|
||||
</Project>
|
||||
@@ -0,0 +1,11 @@
|
||||
namespace LuaScript.Anchor
|
||||
{
|
||||
internal enum AnchorConnection
|
||||
{
|
||||
None,
|
||||
Line,
|
||||
Loop,
|
||||
Star,
|
||||
Arm,
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,4 @@
|
||||
namespace LuaScript.Anchor
|
||||
{
|
||||
internal readonly record struct AnchorOptions(AnchorConnection Connection, bool Is3D);
|
||||
}
|
||||
@@ -0,0 +1,4 @@
|
||||
namespace LuaScript.Anchor
|
||||
{
|
||||
internal readonly record struct AnchorRequestData(string Group, int Count, AnchorConnection Connection, bool Is3D);
|
||||
}
|
||||
@@ -1,22 +1,7 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Collections.Immutable;
|
||||
|
||||
namespace LuaScript.Anchor
|
||||
{
|
||||
internal enum AnchorConnection
|
||||
{
|
||||
None,
|
||||
Line,
|
||||
Loop,
|
||||
Star,
|
||||
Arm,
|
||||
}
|
||||
|
||||
internal readonly record struct AnchorOptions(AnchorConnection Connection, bool Is3D);
|
||||
|
||||
internal readonly record struct AnchorRequestData(string Group, int Count, AnchorConnection Connection, bool Is3D);
|
||||
|
||||
internal static class AnchorSupport
|
||||
{
|
||||
public const int MaxAnchors = 32;
|
||||
差分なしでファイル名を変更。
@@ -0,0 +1,38 @@
|
||||
namespace LuaScript.Api
|
||||
{
|
||||
internal static class LuaApiCatalog
|
||||
{
|
||||
private static readonly object s_gate = new();
|
||||
private static readonly List<LuaApiMember> s_members = [];
|
||||
private static LuaApiMember[]? s_snapshot;
|
||||
private static int s_version;
|
||||
|
||||
internal static int Version
|
||||
{
|
||||
get
|
||||
{
|
||||
lock (s_gate)
|
||||
return s_version;
|
||||
}
|
||||
}
|
||||
|
||||
internal static void Register(IReadOnlyList<LuaApiMember> members)
|
||||
{
|
||||
lock (s_gate)
|
||||
{
|
||||
s_members.AddRange(members);
|
||||
s_snapshot = null;
|
||||
s_version++;
|
||||
}
|
||||
}
|
||||
|
||||
internal static IReadOnlyList<LuaApiMember> Members
|
||||
{
|
||||
get
|
||||
{
|
||||
lock (s_gate)
|
||||
return s_snapshot ??= [.. s_members];
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,11 @@
|
||||
namespace LuaScript.Api
|
||||
{
|
||||
internal sealed record LuaApiMember(
|
||||
string Table,
|
||||
string Name,
|
||||
LuaApiMemberKind Kind,
|
||||
IReadOnlyList<string> Parameters)
|
||||
{
|
||||
public string QualifiedName => Table.Length == 0 ? Name : $"{Table}.{Name}";
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,8 @@
|
||||
namespace LuaScript.Api
|
||||
{
|
||||
internal enum LuaApiMemberKind
|
||||
{
|
||||
Function,
|
||||
Variable,
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,24 @@
|
||||
namespace LuaScript.Api
|
||||
{
|
||||
[LuaTable("")]
|
||||
[LuaBuiltin("type", "v")]
|
||||
[LuaBuiltin("tostring", "v")]
|
||||
[LuaBuiltin("tonumber", "e", "base")]
|
||||
[LuaBuiltin("select", "n", "...")]
|
||||
[LuaBuiltin("error", "message", "level")]
|
||||
[LuaBuiltin("assert", "v", "message")]
|
||||
[LuaBuiltin("print", "...")]
|
||||
[LuaBuiltin("ipairs", "t")]
|
||||
[LuaBuiltin("pairs", "t")]
|
||||
[LuaBuiltin("next", "table", "index")]
|
||||
[LuaBuiltin("unpack", "list", "i", "j")]
|
||||
[LuaBuiltin("setmetatable", "table", "metatable")]
|
||||
[LuaBuiltin("getmetatable", "object")]
|
||||
[LuaBuiltin("rawget", "table", "index")]
|
||||
[LuaBuiltin("rawset", "table", "index", "value")]
|
||||
[LuaBuiltin("rawequal", "v1", "v2")]
|
||||
[LuaBuiltin("rawlen", "v")]
|
||||
[LuaBuiltin("pcall", "f", "...")]
|
||||
[LuaBuiltin("xpcall", "f", "msgh", "...")]
|
||||
internal static class LuaBasicLibrary;
|
||||
}
|
||||
@@ -0,0 +1,17 @@
|
||||
namespace LuaScript.Api
|
||||
{
|
||||
[LuaTable("bit32")]
|
||||
[LuaBuiltin("band", "...")]
|
||||
[LuaBuiltin("bor", "...")]
|
||||
[LuaBuiltin("bxor", "...")]
|
||||
[LuaBuiltin("bnot", "x")]
|
||||
[LuaBuiltin("lshift", "x", "disp")]
|
||||
[LuaBuiltin("rshift", "x", "disp")]
|
||||
[LuaBuiltin("arshift", "x", "disp")]
|
||||
[LuaBuiltin("extract", "n", "field", "width")]
|
||||
[LuaBuiltin("replace", "n", "v", "field", "width")]
|
||||
[LuaBuiltin("btest", "...")]
|
||||
[LuaBuiltin("countlz", "x")]
|
||||
[LuaBuiltin("countrz", "x")]
|
||||
internal static class LuaBit32Library;
|
||||
}
|
||||
@@ -0,0 +1,10 @@
|
||||
namespace LuaScript.Api
|
||||
{
|
||||
[AttributeUsage(AttributeTargets.Class | AttributeTargets.Assembly, Inherited = false, AllowMultiple = true)]
|
||||
internal sealed class LuaBuiltinAttribute(string name, params string[] parameters) : Attribute
|
||||
{
|
||||
public string Name { get; } = name;
|
||||
public string[] Parameters { get; } = parameters;
|
||||
public string Table { get; init; } = string.Empty;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,78 @@
|
||||
namespace LuaScript.Api
|
||||
{
|
||||
internal static class LuaCompletionSource
|
||||
{
|
||||
internal static readonly string[] Keywords =
|
||||
[
|
||||
"and", "break", "do", "else", "elseif", "end", "false", "for",
|
||||
"function", "goto", "if", "in", "local", "nil", "not", "or",
|
||||
"repeat", "return", "then", "true", "until", "while"
|
||||
];
|
||||
|
||||
private sealed record Snapshot(
|
||||
int Version,
|
||||
string[] StaticCandidates,
|
||||
IReadOnlyDictionary<string, string[]> TableMembers);
|
||||
|
||||
private static Snapshot? s_snapshot;
|
||||
|
||||
internal static string[] StaticCandidates => Current().StaticCandidates;
|
||||
|
||||
internal static bool TryGetTableMembers(string table, out string[] members)
|
||||
{
|
||||
if (Current().TableMembers.TryGetValue(table, out var found))
|
||||
{
|
||||
members = found;
|
||||
return true;
|
||||
}
|
||||
members = [];
|
||||
return false;
|
||||
}
|
||||
|
||||
private static Snapshot Current()
|
||||
{
|
||||
var snapshot = s_snapshot;
|
||||
int version = LuaApiCatalog.Version;
|
||||
if (snapshot is null || snapshot.Version != version)
|
||||
s_snapshot = snapshot = Build(version);
|
||||
return snapshot;
|
||||
}
|
||||
|
||||
private static Snapshot Build(int version)
|
||||
{
|
||||
var members = LuaApiCatalog.Members;
|
||||
|
||||
var tableMembers = new Dictionary<string, List<string>>(StringComparer.Ordinal);
|
||||
var globals = new List<string>();
|
||||
foreach (var member in members)
|
||||
{
|
||||
if (member.Table.Length == 0)
|
||||
{
|
||||
globals.Add(member.Name);
|
||||
continue;
|
||||
}
|
||||
if (!tableMembers.TryGetValue(member.Table, out var list))
|
||||
{
|
||||
list = [];
|
||||
tableMembers[member.Table] = list;
|
||||
}
|
||||
list.Add(member.QualifiedName);
|
||||
}
|
||||
|
||||
var candidates = Keywords
|
||||
.Concat(globals)
|
||||
.Concat(tableMembers.Keys)
|
||||
.Concat(tableMembers.Values.SelectMany(x => x))
|
||||
.Distinct()
|
||||
.OrderBy(x => x.Length)
|
||||
.ThenBy(x => x, StringComparer.OrdinalIgnoreCase)
|
||||
.ToArray();
|
||||
|
||||
var frozen = new Dictionary<string, string[]>(StringComparer.Ordinal);
|
||||
foreach (var (table, list) in tableMembers)
|
||||
frozen[table] = [.. list.Distinct()];
|
||||
|
||||
return new Snapshot(version, candidates, frozen);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,8 @@
|
||||
namespace LuaScript.Api
|
||||
{
|
||||
[AttributeUsage(AttributeTargets.Field | AttributeTargets.Property, Inherited = false)]
|
||||
internal sealed class LuaConstantAttribute(string name) : Attribute
|
||||
{
|
||||
public string Name { get; } = name;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,10 @@
|
||||
namespace LuaScript.Api
|
||||
{
|
||||
[AttributeUsage(AttributeTargets.Method | AttributeTargets.Class | AttributeTargets.Assembly, Inherited = false, AllowMultiple = true)]
|
||||
internal sealed class LuaFunctionAttribute(string name, params string[] parameters) : Attribute
|
||||
{
|
||||
public string Name { get; } = name;
|
||||
public string[] Parameters { get; } = parameters;
|
||||
public string Table { get; init; } = string.Empty;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,35 @@
|
||||
namespace LuaScript.Api
|
||||
{
|
||||
[LuaTable("math")]
|
||||
[LuaBuiltin("abs", "x")]
|
||||
[LuaBuiltin("ceil", "x")]
|
||||
[LuaBuiltin("cos", "x")]
|
||||
[LuaBuiltin("exp", "x")]
|
||||
[LuaBuiltin("floor", "x")]
|
||||
[LuaBuiltin("fmod", "x", "y")]
|
||||
[LuaVariable("huge")]
|
||||
[LuaBuiltin("log", "x", "base")]
|
||||
[LuaBuiltin("max", "x", "...")]
|
||||
[LuaBuiltin("min", "x", "...")]
|
||||
[LuaBuiltin("modf", "x")]
|
||||
[LuaVariable("pi")]
|
||||
[LuaBuiltin("random", "m", "n")]
|
||||
[LuaBuiltin("randomseed", "x")]
|
||||
[LuaBuiltin("sin", "x")]
|
||||
[LuaBuiltin("sqrt", "x")]
|
||||
[LuaBuiltin("tan", "x")]
|
||||
[LuaBuiltin("atan", "y", "x")]
|
||||
[LuaBuiltin("atan2", "y", "x")]
|
||||
[LuaBuiltin("deg", "x")]
|
||||
[LuaBuiltin("rad", "x")]
|
||||
[LuaBuiltin("ldexp", "m", "e")]
|
||||
[LuaBuiltin("frexp", "x")]
|
||||
[LuaBuiltin("sinh", "x")]
|
||||
[LuaBuiltin("cosh", "x")]
|
||||
[LuaBuiltin("tanh", "x")]
|
||||
[LuaBuiltin("type", "x")]
|
||||
[LuaBuiltin("tointeger", "x")]
|
||||
[LuaVariable("maxinteger")]
|
||||
[LuaVariable("mininteger")]
|
||||
internal static class LuaMathLibrary;
|
||||
}
|
||||
@@ -0,0 +1,22 @@
|
||||
namespace LuaScript.Api
|
||||
{
|
||||
[LuaTable("string")]
|
||||
[LuaBuiltin("format", "formatstring", "...")]
|
||||
[LuaBuiltin("len", "s")]
|
||||
[LuaBuiltin("sub", "s", "i", "j")]
|
||||
[LuaBuiltin("upper", "s")]
|
||||
[LuaBuiltin("lower", "s")]
|
||||
[LuaBuiltin("rep", "s", "n", "sep")]
|
||||
[LuaBuiltin("reverse", "s")]
|
||||
[LuaBuiltin("find", "s", "pattern", "init", "plain")]
|
||||
[LuaBuiltin("match", "s", "pattern", "init")]
|
||||
[LuaBuiltin("gmatch", "s", "pattern")]
|
||||
[LuaBuiltin("gsub", "s", "pattern", "repl", "n")]
|
||||
[LuaBuiltin("byte", "s", "i", "j")]
|
||||
[LuaBuiltin("char", "...")]
|
||||
[LuaBuiltin("dump", "function")]
|
||||
[LuaBuiltin("pack", "fmt", "...")]
|
||||
[LuaBuiltin("unpack", "fmt", "s", "pos")]
|
||||
[LuaBuiltin("packsize", "fmt")]
|
||||
internal static class LuaStringLibrary;
|
||||
}
|
||||
@@ -0,0 +1,8 @@
|
||||
namespace LuaScript.Api
|
||||
{
|
||||
[AttributeUsage(AttributeTargets.Class, Inherited = false)]
|
||||
internal sealed class LuaTableAttribute(string name) : Attribute
|
||||
{
|
||||
public string Name { get; } = name;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,11 @@
|
||||
namespace LuaScript.Api
|
||||
{
|
||||
[LuaTable("table")]
|
||||
[LuaBuiltin("insert", "list", "pos", "value")]
|
||||
[LuaBuiltin("remove", "list", "pos")]
|
||||
[LuaBuiltin("sort", "list", "comp")]
|
||||
[LuaBuiltin("concat", "list", "sep", "i", "j")]
|
||||
[LuaBuiltin("unpack", "list", "i", "j")]
|
||||
[LuaBuiltin("move", "a1", "f", "e", "t", "a2")]
|
||||
internal static class LuaTableLibrary;
|
||||
}
|
||||
213ファイル中100ファイルを読み込みました。 変更されたファイルが多すぎるため、それ以降のファイルは表示していません。
さらに表示
新しいイシューから参照
ユーザーをブロックする