コミットを比較
| 作成者 | SHA1 | 日付 | |
|---|---|---|---|
|
|
20a119c6c8
|
||
|
|
cfa8141424
|
||
|
|
7a2a7e5593
|
||
|
|
1a61091ec2
|
||
|
|
bbb1bd3562
|
||
|
|
db8017a8ce
|
||
|
|
bc69ec5681
|
||
|
|
8f6c3105ef
|
||
|
|
de6c1b8b44
|
||
|
|
ffd57fabd0
|
||
|
|
a80d5dec88
|
||
|
|
8bccf5ed01
|
||
|
|
7c831441fc
|
||
|
|
7cd54ff3e8
|
||
|
|
3c3f5aed69
|
||
|
|
913e1a8643
|
||
|
|
f6c7dac970
|
||
|
|
95db23f253
|
||
|
|
62044a3351
|
||
|
|
694b50d375
|
||
|
|
122d85068d
|
||
|
|
620670915f
|
||
|
|
10974242aa
|
||
|
|
36b2ada16a
|
||
|
|
8428057eb4
|
||
|
|
1133daf764
|
||
|
|
b09070e8df
|
||
|
|
cde0b8f498
|
||
|
|
916dd278b2
|
||
|
|
d6d0792207
|
||
|
|
a7bae506a7
|
||
|
|
d05906de7b
|
||
|
|
a8300041e3
|
||
|
|
8bd0d2bc0e
|
||
|
|
cf5f4acf72
|
||
|
|
0d6709d518
|
||
|
|
12bd10164b
|
||
|
|
6287e74fe5
|
||
|
|
8956b7c8d5
|
||
|
|
60c6a37f89
|
||
|
|
9a9c2ec405
|
||
|
|
103b612082
|
||
|
|
9e1da1839e
|
||
|
|
c19e12aa87
|
||
|
|
ed4c38772f
|
||
|
|
d31fd77aee
|
||
|
|
eb0199131d
|
||
|
|
36935bdf1d
|
||
|
|
7d9a9f1cb8
|
||
|
|
3ce2483062
|
||
|
|
fc8a07f935
|
||
|
|
d1279c25fa
|
||
|
|
048c6d6707
|
||
|
|
3a29862423
|
||
|
|
8c69864456
|
||
|
|
8a7b328db4
|
||
|
|
8517bf5f50
|
||
|
|
b928101e3e
|
||
|
|
7fb671e8c6
|
||
|
|
20ff47edce
|
||
|
|
8f9b7c725f
|
||
|
|
499f8ba078
|
||
|
|
66f2d398b7
|
||
|
|
935bca6fbb
|
||
|
|
4c7ef12361
|
||
|
|
65e7864221
|
||
|
|
25430c4dcf
|
||
|
|
f0234d21e4
|
||
|
|
bfe23707f0
|
||
|
|
e74af227d8
|
||
|
|
2b5901379f
|
||
|
|
deb94b3f29
|
||
|
|
74a65b7a8b
|
||
|
|
a4cc0f3220
|
||
|
|
86f889cbd2
|
||
|
|
c2f48230f3
|
||
|
|
4153956b37
|
||
|
|
3763db1cfc
|
||
|
|
9bcab1ae28
|
||
|
|
6e13a4d1c2
|
||
|
|
8dc87d63be
|
||
|
|
0afb7afc21
|
||
|
|
2769a29808
|
||
|
|
1f21b4c49c
|
||
|
|
cafc6d6e48
|
||
|
|
49a2ce29b2
|
||
|
|
d728c8d056
|
||
|
|
b6eac20941
|
||
|
|
d8589007b3
|
||
|
|
85596f76f7
|
||
|
|
018999ff5e
|
||
|
|
c5da497bb3
|
||
|
|
f46cb08f85
|
||
|
|
b0a5293b89
|
||
|
|
67a1b4fa31
|
||
|
|
2d0fb2c47a
|
||
|
|
45d5164afa
|
||
|
|
ba20fc8187
|
||
|
|
669b24c2b3
|
||
|
|
91a3e3f762
|
||
|
|
722ae62326
|
||
|
|
fee1f293c7
|
||
|
|
b6764fe637
|
||
|
|
01e368207d
|
||
|
|
29ea2ea45c
|
||
|
|
1d60d8b245
|
||
|
|
8f2aafdffd
|
検索条件に一致するファイルはありません
+18
-26
@@ -1,43 +1,35 @@
|
||||
# v1.13.4 - Lua スクリプト for YMM4
|
||||
# v1.16.3 - Lua スクリプト for YMM4
|
||||
|
||||
環境情報を取得する obj.getinfo を追加したリリースです。
|
||||
スクリプトの設置フォルダのパスや動画の出力状態に加えて、最大画像サイズ、BPMグリッドの情報、経過時間、本体のバージョンを名前で取得できます。MoonSharp とネイティブの両エンジンで同一の関数として動作します。
|
||||
あわせて、プラグインの内部構成を依存関係の層ごとの複数アセンブリへ分割し、Lua API の登録と入力補完をソースジェネレータによる宣言的な生成へ移行しました。既存のスクリプトの書き方と実行結果に変更はありません。
|
||||
再生中の毎フレームのヒープ割り当てを一箇所排除した保守リリースです。エフェクトプロセッサは、キャッシュが一致しないフレームの末尾で、シーンの照会の結果を配列へ写し取り、次フレームの一致判定に備えます。再生中はフレーム番号が毎フレーム変わるため描画鍵が必ず変化し、この末尾が毎フレーム実行されます。従来はここで、シーンのオブジェクトやシーン共有値を照会するスクリプトのために SceneObjectQuery と SceneValueQuery の配列を毎フレーム新規に確保していました。本リリースでは、照会の個数が安定している通常の場合にスナップショットの配列を使い回し、この場合の毎フレームの割り当てをゼロにします。実行結果に変更はなく、スクリプトの挙動もエンジンの振り分けも従来のままです。
|
||||
|
||||
---
|
||||
|
||||
## 新機能
|
||||
## パフォーマンス
|
||||
|
||||
### obj.getinfo による環境情報の取得
|
||||
### シーンの照会のスナップショットの配列の使い回し
|
||||
|
||||
obj.getinfo(名前) は、名前で指定した環境情報を返します。対応していない名前を指定した場合は nil を返します。取得できる情報は次のとおりです。
|
||||
エフェクトプロセッサの非キャッシュ経路の末尾で毎フレーム起きていた配列の確保を、通常の場合に排除しました。
|
||||
|
||||
- "script_path" は、プラグインの設置フォルダのパスを返します。末尾には区切り文字が付きます。
|
||||
- "filter" は、フィルタ効果として処理中かどうかを返します。本プラグインでは常に true を返します。
|
||||
- "saving" は、動画を出力中のときだけ true を返します。
|
||||
- "image_max" は、最大画像サイズを横幅と高さの2つの値で返します。
|
||||
- "bpm" は、BPMグリッドのテンポと拍子と基準時間の3つの値を返します。基準時間の単位は秒です。BPMグリッドを設定していない場合はテンポが 0 になります。
|
||||
- "clock" は、YMM4 の起動からの経過時間を秒で返します。
|
||||
- "script_time" は、スクリプトの実行開始からの経過時間をミリ秒で返します。
|
||||
- "version" は、本体のバージョンを major×10000+minor×100+build の数値で返します。
|
||||
|
||||
編集中のみプレビューへ枠を描き、出力時には描かないといった分岐へ利用できます。
|
||||
- エフェクトプロセッサは、描画鍵と照会の結果が前フレームと一致するときは前フレームの出力をそのまま返し、一致しないときだけスクリプトを実行します。再生中はフレーム番号が毎フレーム変わり描画鍵が必ず変化するため、非キャッシュ経路が毎フレーム走ります。この経路の末尾では、次フレームの一致判定のために、そのフレームで行われたシーンの照会の結果をスナップショットとして配列へ写し取ります。
|
||||
- 従来はこの写し取りを毎フレーム新しい配列の確保で行っていました。obj.getoption などでシーンのオブジェクトを照会するスクリプトや、シーン共有値を読むスクリプトでは、SceneObjectQuery または SceneValueQuery の配列がフレームごとに確保され、ガベージコレクションの圧力になっていました。
|
||||
- 本リリースでは、照会の個数が前フレームと同じであればスナップショットの配列を使い回し、要素だけを書き戻します。同じスクリプトが同じ個数の照会を行う通常の場合、毎フレームの割り当てが起きなくなります。個数が変わったフレームだけ新しい配列を確保します。
|
||||
- 照会を一切行わないスクリプトは、従来どおり共有の空配列を用い、割り当ては起きません。
|
||||
- 対象はエフェクトプロセッサの内部の毎フレームの固定費だけです。カーネルレーン、高速ランタイム、MoonSharp のいずれの実行経路も、選び方も、実行結果も変わりません。
|
||||
|
||||
---
|
||||
|
||||
## 互換性・後方互換
|
||||
|
||||
- 既存のスクリプトの書き方と実行結果に変更はありません。obj.getinfo は新規の関数であり、従来の呼び出しへは影響しません。
|
||||
- obj.getinfo は MoonSharp とネイティブの両エンジンで動作します。script_path、filter、saving、image_max、bpm、version は両エンジンで同一の値を返します。clock と script_time は経過時間の計測であり、値そのものは実行のたびに変わります。
|
||||
- v1.13.3 までの仕様に変更はありません。
|
||||
- 実行結果に変更はありません。本変更は毎フレームの割り当ての排除だけを目的とし、スクリプトの挙動、出力、描画記述のいずれも変わりません。
|
||||
- スナップショットの配列は、そのフレームで行われた照会の結果を毎フレームすべて書き戻すため、使い回しても内容は毎フレーム新規に確保していた従来と同一です。一致判定に使う値に差は生じません。
|
||||
- エンジンの自動振り分け、エンジン指定ディレクティブの仕様と優先順位、カーネル化の対象、v1.16.2 までの構文拡張と既存の API に変更はありません。
|
||||
|
||||
---
|
||||
|
||||
## 内部実装
|
||||
|
||||
- プラグインを依存関係の層ごとに 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 の両エンジンでの実行結果の検証と、補完カタログの回帰検証、およびエンジンのテーブルライフサイクルの特性化検証を追加しました。
|
||||
- 追加した `SnapshotQueries<T>(IReadOnlyList<T> source, T[] existing)` は、照会の個数が 0 のときは共有の空配列を返し、既存の配列の長さが個数と一致するときはその配列へ要素を書き戻し、一致しないときだけ新しい配列を確保します。照会の個数はスクリプトが同じであればフレーム間で安定するため、その場合は毎フレームの割り当てが起きません。
|
||||
- 使い回しが安全なのは、SceneObjectQuery と SceneValueQuery がいずれも readonly record struct の値であり、前フレームのスナップショットが当該フレームのキャッシュの一致判定で読み終えた後に上書きされるためです。判定より前に上書きが起きることはなく、配列の使い回しによる別名の干渉はありません。既存の compute-once / zero per-frame allocation の設計思想に沿った統一的な変更です。
|
||||
- あわせて、他の毎フレームの経路がいずれも自らのレーンの中で割り当てを持たないことを再確認しました。GPU カーネルの適用は定数の緩衝と出力を再利用し、CPU カーネルと SIMD、ネイティブレーンのワーカー、カーネルのユニフォームの充填、ネイティブのフィールドの写し取り、コンテキストの充填、構造体の複製による出力記述の生成のいずれにも毎フレームの割り当てはありません。
|
||||
- 精査の上で見送った項目があります。ネイティブレーンの文字列パラメータの毎フレームの再エンコードは、短い文字列に対する処理であり、それが乗るプロセス間の往復に比べて無視できる量のため据え置きました。ディレクティブ解決の二重の走査は、参照の同一性でキャッシュされスクリプトの編集ごとに一度だけ走るため据え置きました。MoonSharp レーンの数値のボックス化は、低速フォールバック専用として従来どおり据え置きました。
|
||||
- テストは 3317 件で変更はありません。本変更は実行結果を変えないため、既存のキャッシュとシーンの照会の一致判定の検証で挙動が担保されます。ソリューションは Release x64 で 0 個の警告、0 個のエラーです。
|
||||
@@ -1,5 +1,5 @@
|
||||
========================================
|
||||
Luaスクリプト for YMM4 v1.13.4
|
||||
Luaスクリプト for YMM4 v1.16.3
|
||||
========================================
|
||||
YukkuriMovieMaker4(YMM4)上で動作する、Luaスクリプトで映像エフェクトのパラメータや
|
||||
ピクセルを直接制御できるプラグインです。
|
||||
|
||||
@@ -1,9 +1,9 @@
|
||||
<Project Sdk="Microsoft.NET.Sdk">
|
||||
<Project Sdk="Microsoft.NET.Sdk">
|
||||
|
||||
<PropertyGroup>
|
||||
<TargetFramework>net10.0-windows10.0.19041.0</TargetFramework>
|
||||
<ImplicitUsings>enable</ImplicitUsings>
|
||||
<Version>1.13.4</Version>
|
||||
<Version>1.16.3</Version>
|
||||
<Platforms>AnyCPU;x64</Platforms>
|
||||
<Nullable>enable</Nullable>
|
||||
</PropertyGroup>
|
||||
@@ -16,6 +16,7 @@
|
||||
|
||||
<ItemGroup>
|
||||
<ProjectReference Include="..\LuaScript.Kernel\LuaScript.Kernel.csproj" />
|
||||
<ProjectReference Include="..\LuaScript.Generator\LuaScript.Generator.csproj" OutputItemType="Analyzer" ReferenceOutputAssembly="false" />
|
||||
</ItemGroup>
|
||||
|
||||
<ItemGroup>
|
||||
|
||||
@@ -0,0 +1,85 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
|
||||
namespace LuaScript.Compat
|
||||
{
|
||||
internal sealed class AviUtlPixelShaderLibrary
|
||||
{
|
||||
private const string SectionMarker = "--[[pixelshader@";
|
||||
|
||||
public static AviUtlPixelShaderLibrary Empty { get; } = new(null);
|
||||
|
||||
private readonly Dictionary<string, string>? _shaders;
|
||||
|
||||
private AviUtlPixelShaderLibrary(Dictionary<string, string>? shaders) => _shaders = shaders;
|
||||
|
||||
public int Count => _shaders?.Count ?? 0;
|
||||
|
||||
public static AviUtlPixelShaderLibrary Parse(string? source)
|
||||
{
|
||||
if (string.IsNullOrEmpty(source))
|
||||
return Empty;
|
||||
|
||||
Dictionary<string, string>? shaders = null;
|
||||
int index = 0;
|
||||
while (index < source.Length)
|
||||
{
|
||||
int lineStart = index;
|
||||
int lineBreak = source.IndexOf('\n', index);
|
||||
index = lineBreak < 0 ? source.Length : lineBreak + 1;
|
||||
|
||||
int i = ScriptParserHelper.SkipSpaces(source, lineStart);
|
||||
if (!MatchesMarker(source, i))
|
||||
continue;
|
||||
i += SectionMarker.Length;
|
||||
|
||||
int nameStart = i;
|
||||
while (i < source.Length && IsEntryPointChar(source[i]))
|
||||
i++;
|
||||
if (i == nameStart || i >= source.Length || source[i] != ':')
|
||||
continue;
|
||||
|
||||
string name = source[nameStart..i];
|
||||
int bodyStart = i + 1;
|
||||
int bodyEnd = source.IndexOf("]]", bodyStart, StringComparison.Ordinal);
|
||||
if (bodyEnd < 0)
|
||||
continue;
|
||||
|
||||
shaders ??= new Dictionary<string, string>(StringComparer.Ordinal);
|
||||
shaders.TryAdd(name, source[bodyStart..bodyEnd]);
|
||||
index = bodyEnd + 2;
|
||||
}
|
||||
|
||||
return shaders is null ? Empty : new AviUtlPixelShaderLibrary(shaders);
|
||||
}
|
||||
|
||||
public bool TryGet(string name, out string hlsl)
|
||||
{
|
||||
hlsl = string.Empty;
|
||||
if (_shaders is null || string.IsNullOrEmpty(name))
|
||||
return false;
|
||||
|
||||
int at = name.IndexOf('@');
|
||||
string local = at < 0 ? name : name[..at];
|
||||
if (_shaders.TryGetValue(local, out var found))
|
||||
{
|
||||
hlsl = found;
|
||||
return true;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
public static string EntryPointOf(string name)
|
||||
{
|
||||
int at = name.IndexOf('@');
|
||||
return at < 0 ? name : name[..at];
|
||||
}
|
||||
|
||||
private static bool MatchesMarker(string text, int index) =>
|
||||
index + SectionMarker.Length <= text.Length &&
|
||||
string.CompareOrdinal(text, index, SectionMarker, 0, SectionMarker.Length) == 0;
|
||||
|
||||
private static bool IsEntryPointChar(char c) =>
|
||||
ScriptParserHelper.IsNameChar(c) || c == '_';
|
||||
}
|
||||
}
|
||||
@@ -15,10 +15,10 @@ namespace LuaScript.Compat
|
||||
|
||||
public static string Transform(string source) => TransformWithMap(source).Code;
|
||||
|
||||
public static (string Code, int[] LineMap) TransformWithMap(string source)
|
||||
public static (string Code, int[] LineMap, int[] ChangedLines) TransformWithMap(string source)
|
||||
{
|
||||
if (string.IsNullOrEmpty(source))
|
||||
return (source, []);
|
||||
return (source, [], []);
|
||||
|
||||
var lines = ScriptParserHelper.SplitLines(source);
|
||||
bool hasSection = ScriptParserHelper.TryFindSection(lines, out int sectionStart, out int sectionEnd);
|
||||
@@ -28,7 +28,10 @@ namespace LuaScript.Compat
|
||||
AppendDeclarations(lines[i], prelude);
|
||||
|
||||
if (!hasSection && prelude.Count == 0)
|
||||
return (source, []);
|
||||
{
|
||||
var (code, changed) = LuaSyntaxExtensions.RewriteWithMap(source);
|
||||
return (code, [], changed);
|
||||
}
|
||||
|
||||
var builder = new StringBuilder(source.Length + 64);
|
||||
var lineMap = new int[prelude.Count + (sectionEnd - sectionStart)];
|
||||
@@ -45,7 +48,8 @@ namespace LuaScript.Compat
|
||||
lineMap[row++] = i;
|
||||
}
|
||||
|
||||
return (builder.ToString(), lineMap);
|
||||
var (rewritten, changedLines) = LuaSyntaxExtensions.RewriteWithMap(builder.ToString());
|
||||
return (rewritten, lineMap, changedLines);
|
||||
}
|
||||
|
||||
private static void AppendDeclarations(string line, List<string> prelude)
|
||||
|
||||
@@ -0,0 +1,48 @@
|
||||
using LuaScript.Compat.Syntax;
|
||||
|
||||
namespace LuaScript.Compat
|
||||
{
|
||||
internal static class LuaSyntaxExtensions
|
||||
{
|
||||
public static string Rewrite(string source) => RewriteWithMap(source).Code;
|
||||
|
||||
public static (string Code, int[] ChangedLines) RewriteWithMap(string source)
|
||||
{
|
||||
if (string.IsNullOrEmpty(source))
|
||||
return (source, []);
|
||||
|
||||
var tokens = LuaSyntaxLexer.Tokenize(source);
|
||||
var context = new LuaRewriteContext(tokens);
|
||||
var rules = LuaSyntaxRuleRegistry.Rules;
|
||||
|
||||
while (!context.AtEnd)
|
||||
{
|
||||
var current = context.Current;
|
||||
if (current.IsTrivia || current.Kind == LuaSyntaxTokenKind.String)
|
||||
{
|
||||
context.Emit(current);
|
||||
context.Advance();
|
||||
continue;
|
||||
}
|
||||
|
||||
bool matched = false;
|
||||
foreach (var rule in rules)
|
||||
{
|
||||
if (rule.TryApply(context))
|
||||
{
|
||||
matched = true;
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
if (!matched)
|
||||
{
|
||||
context.Emit(current);
|
||||
context.Advance();
|
||||
}
|
||||
}
|
||||
|
||||
return context.Changed ? (context.Serialize(), context.ChangedLines) : (source, []);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,6 +1,6 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using LuaScript.Engine.Kernel;
|
||||
using LuaScript.Compat.Syntax;
|
||||
|
||||
namespace LuaScript.Compat
|
||||
{
|
||||
@@ -35,15 +35,7 @@ namespace LuaScript.Compat
|
||||
if (string.IsNullOrEmpty(script))
|
||||
return None;
|
||||
|
||||
List<LuaToken> tokens;
|
||||
try
|
||||
{
|
||||
tokens = LuaLexer.Tokenize(script);
|
||||
}
|
||||
catch (KernelUnsupportedException)
|
||||
{
|
||||
return None;
|
||||
}
|
||||
var tokens = LuaSyntaxLexer.Tokenize(script);
|
||||
|
||||
HashSet<string>? members = null;
|
||||
bool color = false;
|
||||
@@ -51,26 +43,52 @@ namespace LuaScript.Compat
|
||||
for (int i = 0; i < tokens.Count; i++)
|
||||
{
|
||||
var token = tokens[i];
|
||||
if (token.Kind != LuaTokenKind.Name)
|
||||
if (token.Kind != LuaSyntaxTokenKind.Name)
|
||||
continue;
|
||||
|
||||
if (token.Text == "color")
|
||||
{
|
||||
if (i == 0 || !tokens[i - 1].IsSymbol("."))
|
||||
int previous = PreviousSignificant(tokens, i);
|
||||
if (previous < 0 || !tokens[previous].IsOperator("."))
|
||||
color = true;
|
||||
continue;
|
||||
}
|
||||
|
||||
if (token.Text == "obj" &&
|
||||
i + 2 < tokens.Count &&
|
||||
tokens[i + 1].IsSymbol(".") &&
|
||||
tokens[i + 2].Kind == LuaTokenKind.Name)
|
||||
if (token.Text == "obj")
|
||||
{
|
||||
(members ??= new HashSet<string>(StringComparer.Ordinal)).Add(tokens[i + 2].Text);
|
||||
int dot = NextSignificant(tokens, i + 1);
|
||||
if (dot < 0 || !tokens[dot].IsOperator("."))
|
||||
continue;
|
||||
|
||||
int member = NextSignificant(tokens, dot + 1);
|
||||
if (member < 0 || tokens[member].Kind != LuaSyntaxTokenKind.Name)
|
||||
continue;
|
||||
|
||||
(members ??= new HashSet<string>(StringComparer.Ordinal)).Add(tokens[member].Text);
|
||||
}
|
||||
}
|
||||
|
||||
return new ScriptParameterUsage(members, color);
|
||||
}
|
||||
|
||||
private static int PreviousSignificant(List<LuaSyntaxToken> tokens, int from)
|
||||
{
|
||||
for (int i = from - 1; i >= 0; i--)
|
||||
{
|
||||
if (!tokens[i].IsTrivia)
|
||||
return i;
|
||||
}
|
||||
return -1;
|
||||
}
|
||||
|
||||
private static int NextSignificant(List<LuaSyntaxToken> tokens, int from)
|
||||
{
|
||||
for (int i = from; i < tokens.Count; i++)
|
||||
{
|
||||
if (!tokens[i].IsTrivia)
|
||||
return i;
|
||||
}
|
||||
return -1;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,7 @@
|
||||
namespace LuaScript.Compat.Syntax
|
||||
{
|
||||
internal interface ILuaSyntaxRule
|
||||
{
|
||||
bool TryApply(LuaRewriteContext context);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,23 @@
|
||||
using System.Collections.Generic;
|
||||
|
||||
namespace LuaScript.Compat.Syntax
|
||||
{
|
||||
internal static class LuaKeywords
|
||||
{
|
||||
private static readonly HashSet<string> Reserved = new()
|
||||
{
|
||||
"and", "break", "do", "else", "elseif", "end", "false", "for", "function",
|
||||
"goto", "if", "in", "local", "nil", "not", "or", "repeat", "return",
|
||||
"then", "true", "until", "while",
|
||||
};
|
||||
|
||||
private static readonly HashSet<string> ExpressionSafe = new()
|
||||
{
|
||||
"and", "or", "not", "nil", "true", "false",
|
||||
};
|
||||
|
||||
public static bool IsReserved(string name) => Reserved.Contains(name);
|
||||
|
||||
public static bool IsExpressionBoundary(string name) => Reserved.Contains(name) && !ExpressionSafe.Contains(name);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,130 @@
|
||||
using System.Collections.Generic;
|
||||
using System.Text;
|
||||
|
||||
namespace LuaScript.Compat.Syntax
|
||||
{
|
||||
internal readonly struct LuaRangeParts
|
||||
{
|
||||
public LuaRangeParts(string start, string stop, string? step, bool exclusive)
|
||||
{
|
||||
Start = start;
|
||||
Stop = stop;
|
||||
Step = step;
|
||||
Exclusive = exclusive;
|
||||
}
|
||||
|
||||
public string Start { get; }
|
||||
|
||||
public string Stop { get; }
|
||||
|
||||
public string? Step { get; }
|
||||
|
||||
public bool Exclusive { get; }
|
||||
}
|
||||
|
||||
internal static class LuaRangeSyntax
|
||||
{
|
||||
public static bool TryParse(IReadOnlyList<LuaSyntaxToken> input, int open, out LuaRangeParts parts, out int end)
|
||||
{
|
||||
parts = default;
|
||||
end = open;
|
||||
|
||||
if (open < 0 || open >= input.Count || !input[open].IsOperator("<"))
|
||||
return false;
|
||||
|
||||
int position = open + 1;
|
||||
if (!TryReadSegment(input, ref position, "..", ">", out string start, out string startTerminator) || startTerminator != "..")
|
||||
return false;
|
||||
|
||||
bool exclusive = false;
|
||||
int caret = NextSignificant(input, position);
|
||||
if (caret >= 0 && input[caret].IsOperator("<"))
|
||||
{
|
||||
exclusive = true;
|
||||
position = caret + 1;
|
||||
}
|
||||
|
||||
if (!TryReadSegment(input, ref position, ",", ">", out string stop, out string stopTerminator))
|
||||
return false;
|
||||
|
||||
string? step = null;
|
||||
if (stopTerminator == ",")
|
||||
{
|
||||
if (!TryReadSegment(input, ref position, ">", ">", out string stepText, out string stepTerminator) || stepTerminator != ">")
|
||||
return false;
|
||||
step = stepText;
|
||||
}
|
||||
else if (stopTerminator != ">")
|
||||
{
|
||||
return false;
|
||||
}
|
||||
|
||||
if (start.Length == 0 || stop.Length == 0 || (step is not null && step.Length == 0))
|
||||
return false;
|
||||
|
||||
parts = new LuaRangeParts(start, stop, step, exclusive);
|
||||
end = position;
|
||||
return true;
|
||||
}
|
||||
|
||||
private static bool TryReadSegment(IReadOnlyList<LuaSyntaxToken> input, ref int position, string primaryStop, string secondaryStop, out string text, out string terminator)
|
||||
{
|
||||
text = string.Empty;
|
||||
terminator = string.Empty;
|
||||
int start = position;
|
||||
int depth = 0;
|
||||
int count = input.Count;
|
||||
|
||||
while (position < count)
|
||||
{
|
||||
var token = input[position];
|
||||
if (token.Kind == LuaSyntaxTokenKind.Newline && depth == 0)
|
||||
return false;
|
||||
if (token.Kind == LuaSyntaxTokenKind.Operator)
|
||||
{
|
||||
if (token.Text is "(" or "[" or "{")
|
||||
{
|
||||
depth++;
|
||||
}
|
||||
else if (token.Text is ")" or "]" or "}")
|
||||
{
|
||||
if (depth == 0)
|
||||
return false;
|
||||
depth--;
|
||||
}
|
||||
else if (depth == 0 && (token.Text == primaryStop || token.Text == secondaryStop))
|
||||
{
|
||||
terminator = token.Text;
|
||||
text = Trim(input, start, position);
|
||||
position++;
|
||||
return true;
|
||||
}
|
||||
}
|
||||
position++;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
private static int NextSignificant(IReadOnlyList<LuaSyntaxToken> input, int from)
|
||||
{
|
||||
for (int i = from; i < input.Count; i++)
|
||||
{
|
||||
if (!input[i].IsTrivia)
|
||||
return i;
|
||||
}
|
||||
return -1;
|
||||
}
|
||||
|
||||
private static string Trim(IReadOnlyList<LuaSyntaxToken> input, int begin, int end)
|
||||
{
|
||||
while (begin < end && input[begin].IsTrivia)
|
||||
begin++;
|
||||
while (end > begin && input[end - 1].IsTrivia)
|
||||
end--;
|
||||
var builder = new StringBuilder();
|
||||
for (int i = begin; i < end; i++)
|
||||
builder.Append(input[i].Text);
|
||||
return builder.ToString();
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,318 @@
|
||||
using System.Collections.Generic;
|
||||
using System.Text;
|
||||
|
||||
namespace LuaScript.Compat.Syntax
|
||||
{
|
||||
internal sealed class LuaRewriteContext
|
||||
{
|
||||
private readonly List<LuaSyntaxToken> _input;
|
||||
private readonly List<LuaSyntaxToken> _output;
|
||||
private List<int>? _changedLines;
|
||||
private int _line = 1;
|
||||
private int _lastChangedLine;
|
||||
private int _temporaries;
|
||||
|
||||
public LuaRewriteContext(List<LuaSyntaxToken> input)
|
||||
{
|
||||
_input = input;
|
||||
_output = new List<LuaSyntaxToken>(input.Count);
|
||||
}
|
||||
|
||||
public IReadOnlyList<LuaSyntaxToken> Input => _input;
|
||||
|
||||
public List<LuaSyntaxToken> Output => _output;
|
||||
|
||||
public int Index { get; set; }
|
||||
|
||||
public bool Changed { get; private set; }
|
||||
|
||||
public int[] ChangedLines => _changedLines is null ? [] : _changedLines.ToArray();
|
||||
|
||||
public bool AtEnd => Index >= _input.Count;
|
||||
|
||||
public LuaSyntaxToken Current => _input[Index];
|
||||
|
||||
public void Advance() => Index++;
|
||||
|
||||
public void Emit(LuaSyntaxToken token)
|
||||
{
|
||||
_output.Add(token);
|
||||
if (token.Kind == LuaSyntaxTokenKind.Newline)
|
||||
_line++;
|
||||
}
|
||||
|
||||
public void EmitRaw(string text)
|
||||
{
|
||||
_output.Add(new LuaSyntaxToken(LuaSyntaxTokenKind.Name, text));
|
||||
MarkChanged();
|
||||
}
|
||||
|
||||
public void EmitOperator(string text)
|
||||
{
|
||||
_output.Add(new LuaSyntaxToken(LuaSyntaxTokenKind.Operator, text));
|
||||
MarkChanged();
|
||||
}
|
||||
|
||||
public string NextTemporary() => "__lc" + _temporaries++;
|
||||
|
||||
public int NextSignificant(int from)
|
||||
{
|
||||
for (int i = from; i < _input.Count; i++)
|
||||
{
|
||||
if (!_input[i].IsTrivia)
|
||||
return i;
|
||||
}
|
||||
return -1;
|
||||
}
|
||||
|
||||
public bool TryPreviousOutputSignificantSameLine(out LuaSyntaxToken token)
|
||||
{
|
||||
for (int i = _output.Count - 1; i >= 0; i--)
|
||||
{
|
||||
if (_output[i].Kind == LuaSyntaxTokenKind.Newline)
|
||||
break;
|
||||
if (_output[i].IsTrivia)
|
||||
continue;
|
||||
token = _output[i];
|
||||
return true;
|
||||
}
|
||||
token = default;
|
||||
return false;
|
||||
}
|
||||
|
||||
public int NextSignificantSameLine(int from)
|
||||
{
|
||||
for (int i = from; i < _input.Count; i++)
|
||||
{
|
||||
if (_input[i].Kind == LuaSyntaxTokenKind.Newline)
|
||||
return -1;
|
||||
if (_input[i].IsTrivia)
|
||||
continue;
|
||||
return i;
|
||||
}
|
||||
return -1;
|
||||
}
|
||||
|
||||
public void EmitWord(string word)
|
||||
{
|
||||
if (_output.Count > 0 && !_output[_output.Count - 1].IsTrivia)
|
||||
_output.Add(new LuaSyntaxToken(LuaSyntaxTokenKind.Whitespace, " "));
|
||||
_output.Add(new LuaSyntaxToken(LuaSyntaxTokenKind.Name, word));
|
||||
if (Index < _input.Count && !_input[Index].IsTrivia)
|
||||
_output.Add(new LuaSyntaxToken(LuaSyntaxTokenKind.Whitespace, " "));
|
||||
MarkChanged();
|
||||
}
|
||||
|
||||
private void MarkChanged()
|
||||
{
|
||||
Changed = true;
|
||||
if (_line == _lastChangedLine)
|
||||
return;
|
||||
(_changedLines ??= new List<int>()).Add(_line);
|
||||
_lastChangedLine = _line;
|
||||
}
|
||||
|
||||
public bool TryReadTrailingLvalue(out int start, out string text)
|
||||
{
|
||||
start = _output.Count;
|
||||
text = string.Empty;
|
||||
int end = _output.Count;
|
||||
while (end > 0 && _output[end - 1].IsTrivia)
|
||||
end--;
|
||||
if (end == 0)
|
||||
return false;
|
||||
|
||||
int depth = 0;
|
||||
int begin = end;
|
||||
for (int i = end - 1; i >= 0; i--)
|
||||
{
|
||||
var token = _output[i];
|
||||
if (token.Kind == LuaSyntaxTokenKind.Operator)
|
||||
{
|
||||
if (token.Text is ")" or "]" or "}")
|
||||
{
|
||||
depth++;
|
||||
begin = i;
|
||||
continue;
|
||||
}
|
||||
if (token.Text is "(" or "[" or "{")
|
||||
{
|
||||
if (depth == 0)
|
||||
break;
|
||||
depth--;
|
||||
begin = i;
|
||||
continue;
|
||||
}
|
||||
if (depth > 0 || token.Text == ".")
|
||||
{
|
||||
begin = i;
|
||||
continue;
|
||||
}
|
||||
break;
|
||||
}
|
||||
if (token.Kind == LuaSyntaxTokenKind.Name)
|
||||
{
|
||||
if (depth == 0 && LuaKeywords.IsReserved(token.Text))
|
||||
break;
|
||||
begin = i;
|
||||
continue;
|
||||
}
|
||||
if (depth > 0)
|
||||
{
|
||||
begin = i;
|
||||
continue;
|
||||
}
|
||||
break;
|
||||
}
|
||||
|
||||
while (begin < end && _output[begin].IsTrivia)
|
||||
begin++;
|
||||
if (begin >= end)
|
||||
return false;
|
||||
|
||||
start = begin;
|
||||
text = Concat(begin, end);
|
||||
return true;
|
||||
}
|
||||
|
||||
public bool TryPopOrOperand(out string text)
|
||||
{
|
||||
text = string.Empty;
|
||||
int end = _output.Count;
|
||||
while (end > 0 && _output[end - 1].IsTrivia)
|
||||
end--;
|
||||
if (end == 0)
|
||||
return false;
|
||||
|
||||
int depth = 0;
|
||||
int begin = end;
|
||||
for (int i = end - 1; i >= 0; i--)
|
||||
{
|
||||
var token = _output[i];
|
||||
if (token.Kind == LuaSyntaxTokenKind.Operator)
|
||||
{
|
||||
if (token.Text is ")" or "]" or "}")
|
||||
{
|
||||
depth++;
|
||||
begin = i;
|
||||
continue;
|
||||
}
|
||||
if (token.Text is "(" or "[" or "{")
|
||||
{
|
||||
if (depth == 0)
|
||||
break;
|
||||
depth--;
|
||||
begin = i;
|
||||
continue;
|
||||
}
|
||||
if (depth == 0 && token.Text is "=" or "," or ";")
|
||||
break;
|
||||
begin = i;
|
||||
continue;
|
||||
}
|
||||
if (token.Kind == LuaSyntaxTokenKind.Newline && depth == 0)
|
||||
break;
|
||||
if (token.Kind == LuaSyntaxTokenKind.Name && depth == 0 && LuaKeywords.IsExpressionBoundary(token.Text))
|
||||
break;
|
||||
begin = i;
|
||||
}
|
||||
|
||||
while (begin < end && _output[begin].IsTrivia)
|
||||
begin++;
|
||||
if (begin >= end)
|
||||
return false;
|
||||
|
||||
text = Concat(begin, end);
|
||||
_output.RemoveRange(begin, _output.Count - begin);
|
||||
return true;
|
||||
}
|
||||
|
||||
public void RemoveOutputFrom(int start) => _output.RemoveRange(start, _output.Count - start);
|
||||
|
||||
public bool LastOutputIsTrivia() => _output.Count == 0 || _output[_output.Count - 1].IsTrivia;
|
||||
|
||||
public string ReadLineExpression()
|
||||
{
|
||||
int start = Index;
|
||||
int depth = 0;
|
||||
while (Index < _input.Count)
|
||||
{
|
||||
var token = _input[Index];
|
||||
if (token.Kind == LuaSyntaxTokenKind.Newline && depth == 0)
|
||||
break;
|
||||
if (token.Kind == LuaSyntaxTokenKind.Operator)
|
||||
{
|
||||
if (token.Text is "(" or "[" or "{")
|
||||
depth++;
|
||||
else if (token.Text is ")" or "]" or "}")
|
||||
{
|
||||
if (depth == 0)
|
||||
break;
|
||||
depth--;
|
||||
}
|
||||
else if (depth == 0 && token.Text == ";")
|
||||
break;
|
||||
}
|
||||
Index++;
|
||||
}
|
||||
return TrimmedRange(start, Index);
|
||||
}
|
||||
|
||||
public string ReadForwardOrOperand()
|
||||
{
|
||||
int start = Index;
|
||||
int depth = 0;
|
||||
while (Index < _input.Count)
|
||||
{
|
||||
var token = _input[Index];
|
||||
if (token.Kind == LuaSyntaxTokenKind.Newline && depth == 0)
|
||||
break;
|
||||
if (token.Kind == LuaSyntaxTokenKind.Operator)
|
||||
{
|
||||
if (token.Text is "(" or "[" or "{")
|
||||
depth++;
|
||||
else if (token.Text is ")" or "]" or "}")
|
||||
{
|
||||
if (depth == 0)
|
||||
break;
|
||||
depth--;
|
||||
}
|
||||
else if (depth == 0 && token.Text is "," or ";")
|
||||
break;
|
||||
}
|
||||
else if (token.Kind == LuaSyntaxTokenKind.Name && depth == 0 && LuaKeywords.IsExpressionBoundary(token.Text))
|
||||
break;
|
||||
Index++;
|
||||
}
|
||||
return TrimmedRange(start, Index);
|
||||
}
|
||||
|
||||
public string Serialize()
|
||||
{
|
||||
var builder = new StringBuilder();
|
||||
foreach (var token in _output)
|
||||
builder.Append(token.Text);
|
||||
return builder.ToString();
|
||||
}
|
||||
|
||||
private string Concat(int begin, int end)
|
||||
{
|
||||
var builder = new StringBuilder();
|
||||
for (int i = begin; i < end; i++)
|
||||
builder.Append(_output[i].Text);
|
||||
return builder.ToString();
|
||||
}
|
||||
|
||||
private string TrimmedRange(int begin, int end)
|
||||
{
|
||||
while (begin < end && _input[begin].IsTrivia)
|
||||
begin++;
|
||||
while (end > begin && _input[end - 1].IsTrivia)
|
||||
end--;
|
||||
var builder = new StringBuilder();
|
||||
for (int i = begin; i < end; i++)
|
||||
builder.Append(_input[i].Text);
|
||||
return builder.ToString();
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,21 @@
|
||||
namespace LuaScript.Compat.Syntax
|
||||
{
|
||||
internal static class LuaSyntaxFacts
|
||||
{
|
||||
public static bool IsValueEnd(LuaSyntaxToken token) => token.Kind switch
|
||||
{
|
||||
LuaSyntaxTokenKind.Number or LuaSyntaxTokenKind.String => true,
|
||||
LuaSyntaxTokenKind.Name => !LuaKeywords.IsReserved(token.Text) || token.Text is "nil" or "true" or "false",
|
||||
LuaSyntaxTokenKind.Operator => token.Text is ")" or "]" or "}",
|
||||
_ => false,
|
||||
};
|
||||
|
||||
public static bool IsValueStart(LuaSyntaxToken token) => token.Kind switch
|
||||
{
|
||||
LuaSyntaxTokenKind.Number or LuaSyntaxTokenKind.String => true,
|
||||
LuaSyntaxTokenKind.Name => !LuaKeywords.IsReserved(token.Text) || token.Text is "nil" or "true" or "false" or "not" or "function",
|
||||
LuaSyntaxTokenKind.Operator => token.Text is "(" or "{" or "-" or "#" or "~",
|
||||
_ => false,
|
||||
};
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,246 @@
|
||||
using System.Collections.Generic;
|
||||
|
||||
namespace LuaScript.Compat.Syntax
|
||||
{
|
||||
internal static class LuaSyntaxLexer
|
||||
{
|
||||
private static readonly string[] Operators =
|
||||
{
|
||||
"...", "..=", "??=", "||=", "&&=",
|
||||
"==", "~=", "<=", ">=", "..", "::", "??", "||", "&&", "!=", "++",
|
||||
"=>", "|>",
|
||||
"+=", "-=", "*=", "/=", "%=", "^=",
|
||||
"+", "-", "*", "/", "%", "^", "#", "<", ">", "=",
|
||||
"(", ")", "{", "}", "[", "]", ";", ":", ",", ".",
|
||||
"!", "&", "|", "?", "~",
|
||||
};
|
||||
|
||||
public static List<LuaSyntaxToken> Tokenize(string source)
|
||||
{
|
||||
var tokens = new List<LuaSyntaxToken>();
|
||||
int i = 0;
|
||||
int length = source.Length;
|
||||
|
||||
while (i < length)
|
||||
{
|
||||
char c = source[i];
|
||||
|
||||
if (c == '\r' || c == '\n')
|
||||
{
|
||||
int start = i;
|
||||
if (c == '\r' && i + 1 < length && source[i + 1] == '\n')
|
||||
i += 2;
|
||||
else
|
||||
i++;
|
||||
tokens.Add(new LuaSyntaxToken(LuaSyntaxTokenKind.Newline, source.Substring(start, i - start)));
|
||||
continue;
|
||||
}
|
||||
|
||||
if (c == ' ' || c == '\t' || c == '\f' || c == '\v')
|
||||
{
|
||||
int start = i;
|
||||
while (i < length && (source[i] == ' ' || source[i] == '\t' || source[i] == '\f' || source[i] == '\v'))
|
||||
i++;
|
||||
tokens.Add(new LuaSyntaxToken(LuaSyntaxTokenKind.Whitespace, source.Substring(start, i - start)));
|
||||
continue;
|
||||
}
|
||||
|
||||
if (c == '-' && i + 1 < length && source[i + 1] == '-')
|
||||
{
|
||||
int start = i;
|
||||
i = SkipComment(source, i + 2);
|
||||
tokens.Add(new LuaSyntaxToken(LuaSyntaxTokenKind.Comment, source.Substring(start, i - start)));
|
||||
continue;
|
||||
}
|
||||
|
||||
if (c == '[')
|
||||
{
|
||||
int level = LongBracketLevel(source, i);
|
||||
if (level >= 0)
|
||||
{
|
||||
int start = i;
|
||||
i = SkipLongBracket(source, i, level);
|
||||
tokens.Add(new LuaSyntaxToken(LuaSyntaxTokenKind.String, source.Substring(start, i - start)));
|
||||
continue;
|
||||
}
|
||||
}
|
||||
|
||||
if (c == '"' || c == '\'')
|
||||
{
|
||||
int start = i;
|
||||
i = SkipShortString(source, i);
|
||||
tokens.Add(new LuaSyntaxToken(LuaSyntaxTokenKind.String, source.Substring(start, i - start)));
|
||||
continue;
|
||||
}
|
||||
|
||||
if (c == '`')
|
||||
{
|
||||
int start = i;
|
||||
i = SkipShortString(source, i);
|
||||
tokens.Add(new LuaSyntaxToken(LuaSyntaxTokenKind.InterpolatedString, source.Substring(start, i - start)));
|
||||
continue;
|
||||
}
|
||||
|
||||
if (IsDigit(c) || (c == '.' && i + 1 < length && IsDigit(source[i + 1])))
|
||||
{
|
||||
int start = i;
|
||||
i = SkipNumber(source, i);
|
||||
tokens.Add(new LuaSyntaxToken(LuaSyntaxTokenKind.Number, source.Substring(start, i - start)));
|
||||
continue;
|
||||
}
|
||||
|
||||
if (IsNameStart(c))
|
||||
{
|
||||
int start = i;
|
||||
while (i < length && IsNamePart(source[i]))
|
||||
i++;
|
||||
tokens.Add(new LuaSyntaxToken(LuaSyntaxTokenKind.Name, source.Substring(start, i - start)));
|
||||
continue;
|
||||
}
|
||||
|
||||
string? op = MatchOperator(source, i);
|
||||
if (op is not null)
|
||||
{
|
||||
tokens.Add(new LuaSyntaxToken(LuaSyntaxTokenKind.Operator, op));
|
||||
i += op.Length;
|
||||
continue;
|
||||
}
|
||||
|
||||
tokens.Add(new LuaSyntaxToken(LuaSyntaxTokenKind.Operator, source.Substring(i, 1)));
|
||||
i++;
|
||||
}
|
||||
|
||||
return tokens;
|
||||
}
|
||||
|
||||
private static string? MatchOperator(string source, int index)
|
||||
{
|
||||
int remaining = source.Length - index;
|
||||
foreach (var op in Operators)
|
||||
{
|
||||
if (op.Length > remaining)
|
||||
continue;
|
||||
if (string.CompareOrdinal(source, index, op, 0, op.Length) == 0)
|
||||
return op;
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
private static int SkipNumber(string source, int i)
|
||||
{
|
||||
int length = source.Length;
|
||||
if (source[i] == '0' && i + 1 < length && (source[i + 1] == 'x' || source[i + 1] == 'X'))
|
||||
{
|
||||
i += 2;
|
||||
while (i < length && (IsHexDigit(source[i]) || source[i] == '.'))
|
||||
i++;
|
||||
if (i < length && (source[i] == 'p' || source[i] == 'P'))
|
||||
{
|
||||
i++;
|
||||
if (i < length && (source[i] == '+' || source[i] == '-'))
|
||||
i++;
|
||||
while (i < length && IsDigit(source[i]))
|
||||
i++;
|
||||
}
|
||||
return i;
|
||||
}
|
||||
|
||||
while (i < length && IsDigit(source[i]))
|
||||
i++;
|
||||
if (i < length && source[i] == '.' && !(i + 1 < length && source[i + 1] == '.'))
|
||||
{
|
||||
i++;
|
||||
while (i < length && IsDigit(source[i]))
|
||||
i++;
|
||||
}
|
||||
if (i < length && (source[i] == 'e' || source[i] == 'E'))
|
||||
{
|
||||
i++;
|
||||
if (i < length && (source[i] == '+' || source[i] == '-'))
|
||||
i++;
|
||||
while (i < length && IsDigit(source[i]))
|
||||
i++;
|
||||
}
|
||||
return i;
|
||||
}
|
||||
|
||||
private static int SkipComment(string source, int i)
|
||||
{
|
||||
int level = LongBracketLevel(source, i);
|
||||
if (level >= 0)
|
||||
return SkipLongBracket(source, i, level);
|
||||
|
||||
int length = source.Length;
|
||||
while (i < length && source[i] != '\n' && source[i] != '\r')
|
||||
i++;
|
||||
return i;
|
||||
}
|
||||
|
||||
private static int LongBracketLevel(string source, int i)
|
||||
{
|
||||
if (i >= source.Length || source[i] != '[')
|
||||
return -1;
|
||||
int j = i + 1;
|
||||
int level = 0;
|
||||
while (j < source.Length && source[j] == '=')
|
||||
{
|
||||
level++;
|
||||
j++;
|
||||
}
|
||||
return j < source.Length && source[j] == '[' ? level : -1;
|
||||
}
|
||||
|
||||
private static int SkipLongBracket(string source, int i, int level)
|
||||
{
|
||||
int length = source.Length;
|
||||
i += level + 2;
|
||||
while (i < length)
|
||||
{
|
||||
if (source[i] == ']')
|
||||
{
|
||||
int j = i + 1;
|
||||
int count = 0;
|
||||
while (j < length && source[j] == '=')
|
||||
{
|
||||
count++;
|
||||
j++;
|
||||
}
|
||||
if (count == level && j < length && source[j] == ']')
|
||||
return j + 1;
|
||||
}
|
||||
i++;
|
||||
}
|
||||
return length;
|
||||
}
|
||||
|
||||
private static int SkipShortString(string source, int start)
|
||||
{
|
||||
char quote = source[start];
|
||||
int i = start + 1;
|
||||
int length = source.Length;
|
||||
while (i < length)
|
||||
{
|
||||
char c = source[i];
|
||||
if (c == '\\')
|
||||
{
|
||||
i += 2;
|
||||
continue;
|
||||
}
|
||||
if (c == quote)
|
||||
return i + 1;
|
||||
if (c == '\n' || c == '\r')
|
||||
return i;
|
||||
i++;
|
||||
}
|
||||
return length;
|
||||
}
|
||||
|
||||
private static bool IsNameStart(char c) => c == '_' || char.IsLetter(c);
|
||||
|
||||
private static bool IsNamePart(char c) => c == '_' || char.IsLetterOrDigit(c);
|
||||
|
||||
private static bool IsDigit(char c) => c >= '0' && c <= '9';
|
||||
|
||||
private static bool IsHexDigit(char c) => IsDigit(c) || (c >= 'a' && c <= 'f') || (c >= 'A' && c <= 'F');
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,10 @@
|
||||
using System;
|
||||
|
||||
namespace LuaScript.Compat.Syntax
|
||||
{
|
||||
[AttributeUsage(AttributeTargets.Class, Inherited = false, AllowMultiple = false)]
|
||||
internal sealed class LuaSyntaxRuleAttribute(int order) : Attribute
|
||||
{
|
||||
public int Order { get; } = order;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,21 @@
|
||||
namespace LuaScript.Compat.Syntax
|
||||
{
|
||||
internal readonly struct LuaSyntaxToken
|
||||
{
|
||||
public LuaSyntaxToken(LuaSyntaxTokenKind kind, string text)
|
||||
{
|
||||
Kind = kind;
|
||||
Text = text;
|
||||
}
|
||||
|
||||
public LuaSyntaxTokenKind Kind { get; }
|
||||
|
||||
public string Text { get; }
|
||||
|
||||
public bool IsTrivia => Kind is LuaSyntaxTokenKind.Whitespace or LuaSyntaxTokenKind.Newline or LuaSyntaxTokenKind.Comment;
|
||||
|
||||
public bool IsName(string value) => Kind == LuaSyntaxTokenKind.Name && Text == value;
|
||||
|
||||
public bool IsOperator(string value) => Kind == LuaSyntaxTokenKind.Operator && Text == value;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,14 @@
|
||||
namespace LuaScript.Compat.Syntax
|
||||
{
|
||||
internal enum LuaSyntaxTokenKind
|
||||
{
|
||||
Whitespace,
|
||||
Newline,
|
||||
Comment,
|
||||
String,
|
||||
InterpolatedString,
|
||||
Number,
|
||||
Name,
|
||||
Operator,
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,73 @@
|
||||
namespace LuaScript.Compat.Syntax.Rules
|
||||
{
|
||||
[LuaSyntaxRule(70)]
|
||||
internal sealed class AugmentedAssignmentRule : ILuaSyntaxRule
|
||||
{
|
||||
public bool TryApply(LuaRewriteContext context)
|
||||
{
|
||||
if (context.Current.Kind != LuaSyntaxTokenKind.Operator)
|
||||
return false;
|
||||
|
||||
string? connective = Connective(context.Current.Text);
|
||||
if (connective is null)
|
||||
return false;
|
||||
if (!context.TryReadTrailingLvalue(out _, out string target))
|
||||
return false;
|
||||
|
||||
context.Advance();
|
||||
string value = context.ReadLineExpression();
|
||||
string separator = context.LastOutputIsTrivia() ? string.Empty : " ";
|
||||
context.EmitRaw($"{separator}= {target} {connective} ({value})");
|
||||
return true;
|
||||
}
|
||||
|
||||
private static string? Connective(string op) => op switch
|
||||
{
|
||||
"+=" => "+",
|
||||
"-=" => "-",
|
||||
"*=" => "*",
|
||||
"/=" => "/",
|
||||
"%=" => "%",
|
||||
"^=" => "^",
|
||||
"..=" => "..",
|
||||
"||=" => "or",
|
||||
"&&=" => "and",
|
||||
_ => null,
|
||||
};
|
||||
}
|
||||
|
||||
[LuaSyntaxRule(80)]
|
||||
internal sealed class NilCoalesceAssignRule : ILuaSyntaxRule
|
||||
{
|
||||
public bool TryApply(LuaRewriteContext context)
|
||||
{
|
||||
if (!context.Current.IsOperator("??="))
|
||||
return false;
|
||||
if (!context.TryReadTrailingLvalue(out int start, out string target))
|
||||
return false;
|
||||
|
||||
context.RemoveOutputFrom(start);
|
||||
context.Advance();
|
||||
string value = context.ReadLineExpression();
|
||||
context.EmitRaw($"if {target} == nil then {target} = ({value}) end");
|
||||
return true;
|
||||
}
|
||||
}
|
||||
|
||||
[LuaSyntaxRule(90)]
|
||||
internal sealed class IncrementRule : ILuaSyntaxRule
|
||||
{
|
||||
public bool TryApply(LuaRewriteContext context)
|
||||
{
|
||||
if (!context.Current.IsOperator("++"))
|
||||
return false;
|
||||
if (!context.TryReadTrailingLvalue(out _, out string target))
|
||||
return false;
|
||||
|
||||
context.Advance();
|
||||
string separator = context.LastOutputIsTrivia() ? string.Empty : " ";
|
||||
context.EmitRaw($"{separator}= {target} + 1");
|
||||
return true;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,60 @@
|
||||
namespace LuaScript.Compat.Syntax.Rules
|
||||
{
|
||||
[LuaSyntaxRule(10)]
|
||||
internal sealed class IsNotRule : ILuaSyntaxRule
|
||||
{
|
||||
public bool TryApply(LuaRewriteContext context)
|
||||
{
|
||||
if (!context.Current.IsName("is"))
|
||||
return false;
|
||||
if (!context.TryPreviousOutputSignificantSameLine(out var previous) || !LuaSyntaxFacts.IsValueEnd(previous))
|
||||
return false;
|
||||
|
||||
int notIndex = context.NextSignificantSameLine(context.Index + 1);
|
||||
if (notIndex < 0 || !context.Input[notIndex].IsName("not"))
|
||||
return false;
|
||||
|
||||
int after = context.NextSignificant(notIndex + 1);
|
||||
if (after < 0 || !LuaSyntaxFacts.IsValueStart(context.Input[after]))
|
||||
return false;
|
||||
|
||||
context.EmitOperator("~=");
|
||||
context.Index = notIndex + 1;
|
||||
return true;
|
||||
}
|
||||
}
|
||||
|
||||
[LuaSyntaxRule(20)]
|
||||
internal sealed class IsRule : ILuaSyntaxRule
|
||||
{
|
||||
public bool TryApply(LuaRewriteContext context)
|
||||
{
|
||||
if (!context.Current.IsName("is"))
|
||||
return false;
|
||||
if (!context.TryPreviousOutputSignificantSameLine(out var previous) || !LuaSyntaxFacts.IsValueEnd(previous))
|
||||
return false;
|
||||
|
||||
int next = context.NextSignificantSameLine(context.Index + 1);
|
||||
if (next < 0 || !LuaSyntaxFacts.IsValueStart(context.Input[next]))
|
||||
return false;
|
||||
|
||||
context.EmitOperator("==");
|
||||
context.Advance();
|
||||
return true;
|
||||
}
|
||||
}
|
||||
|
||||
[LuaSyntaxRule(30)]
|
||||
internal sealed class NotEqualRule : ILuaSyntaxRule
|
||||
{
|
||||
public bool TryApply(LuaRewriteContext context)
|
||||
{
|
||||
if (!context.Current.IsOperator("!="))
|
||||
return false;
|
||||
|
||||
context.EmitOperator("~=");
|
||||
context.Advance();
|
||||
return true;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,117 @@
|
||||
using System.Collections.Generic;
|
||||
using System.Text;
|
||||
|
||||
namespace LuaScript.Compat.Syntax.Rules
|
||||
{
|
||||
[LuaSyntaxRule(5)]
|
||||
internal sealed class LuaInterpolatedStringRule : ILuaSyntaxRule
|
||||
{
|
||||
public bool TryApply(LuaRewriteContext context)
|
||||
{
|
||||
if (context.Current.Kind != LuaSyntaxTokenKind.InterpolatedString)
|
||||
return false;
|
||||
|
||||
string text = context.Current.Text;
|
||||
int end = text.Length;
|
||||
if (end >= 2 && text[end - 1] == '`')
|
||||
end--;
|
||||
string content = text.Substring(1, end - 1);
|
||||
|
||||
var pieces = new List<string>();
|
||||
var literal = new StringBuilder();
|
||||
int i = 0;
|
||||
while (i < content.Length)
|
||||
{
|
||||
char c = content[i];
|
||||
if (c == '\\' && i + 1 < content.Length)
|
||||
{
|
||||
literal.Append(content[i]);
|
||||
literal.Append(content[i + 1]);
|
||||
i += 2;
|
||||
continue;
|
||||
}
|
||||
if (c == '{')
|
||||
{
|
||||
int close = FindClosingBrace(content, i + 1);
|
||||
if (close < 0)
|
||||
{
|
||||
literal.Append(c);
|
||||
i++;
|
||||
continue;
|
||||
}
|
||||
string expression = content.Substring(i + 1, close - i - 1).Trim();
|
||||
if (expression.Length > 0)
|
||||
{
|
||||
FlushLiteral(pieces, literal);
|
||||
pieces.Add($"tostring({LuaSyntaxExtensions.Rewrite(expression)})");
|
||||
}
|
||||
i = close + 1;
|
||||
continue;
|
||||
}
|
||||
literal.Append(c);
|
||||
i++;
|
||||
}
|
||||
FlushLiteral(pieces, literal);
|
||||
|
||||
context.Advance();
|
||||
if (pieces.Count == 0)
|
||||
{
|
||||
context.EmitRaw("\"\"");
|
||||
return true;
|
||||
}
|
||||
if (pieces.Count == 1)
|
||||
{
|
||||
context.EmitRaw(pieces[0]);
|
||||
return true;
|
||||
}
|
||||
context.EmitRaw($"({string.Join(" .. ", pieces)})");
|
||||
return true;
|
||||
}
|
||||
|
||||
private static void FlushLiteral(List<string> pieces, StringBuilder literal)
|
||||
{
|
||||
if (literal.Length == 0)
|
||||
return;
|
||||
pieces.Add($"\"{literal.ToString().Replace("\"", "\\\"")}\"");
|
||||
literal.Clear();
|
||||
}
|
||||
|
||||
private static int FindClosingBrace(string content, int from)
|
||||
{
|
||||
int depth = 0;
|
||||
char quote = '\0';
|
||||
for (int i = from; i < content.Length; i++)
|
||||
{
|
||||
char c = content[i];
|
||||
if (quote != '\0')
|
||||
{
|
||||
if (c == '\\')
|
||||
{
|
||||
i++;
|
||||
continue;
|
||||
}
|
||||
if (c == quote)
|
||||
quote = '\0';
|
||||
continue;
|
||||
}
|
||||
if (c == '"' || c == '\'')
|
||||
{
|
||||
quote = c;
|
||||
continue;
|
||||
}
|
||||
if (c == '{')
|
||||
{
|
||||
depth++;
|
||||
continue;
|
||||
}
|
||||
if (c == '}')
|
||||
{
|
||||
if (depth == 0)
|
||||
return i;
|
||||
depth--;
|
||||
}
|
||||
}
|
||||
return -1;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,74 @@
|
||||
namespace LuaScript.Compat.Syntax.Rules
|
||||
{
|
||||
[LuaSyntaxRule(35)]
|
||||
internal sealed class LuaLambdaRule : ILuaSyntaxRule
|
||||
{
|
||||
public bool TryApply(LuaRewriteContext context)
|
||||
{
|
||||
if (!context.Current.IsOperator("=>"))
|
||||
return false;
|
||||
if (!context.TryReadTrailingLvalue(out int start, out string target))
|
||||
return false;
|
||||
if (!TryNormalizeParameters(target, out string parameters))
|
||||
return false;
|
||||
|
||||
int body = context.NextSignificant(context.Index + 1);
|
||||
if (body < 0 || !LuaSyntaxFacts.IsValueStart(context.Input[body]))
|
||||
return false;
|
||||
|
||||
context.RemoveOutputFrom(start);
|
||||
context.Advance();
|
||||
string expression = context.ReadForwardOrOperand();
|
||||
if (expression.Length == 0)
|
||||
return false;
|
||||
|
||||
context.EmitRaw($"(function({parameters}) return {LuaSyntaxExtensions.Rewrite(expression)} end)");
|
||||
return true;
|
||||
}
|
||||
|
||||
private static bool TryNormalizeParameters(string text, out string parameters)
|
||||
{
|
||||
parameters = string.Empty;
|
||||
text = text.Trim();
|
||||
bool wrapped = text.StartsWith("(") && text.EndsWith(")");
|
||||
if (wrapped)
|
||||
text = text.Substring(1, text.Length - 2).Trim();
|
||||
|
||||
if (text.Length == 0)
|
||||
return wrapped;
|
||||
|
||||
var names = text.Split(',');
|
||||
for (int i = 0; i < names.Length; i++)
|
||||
{
|
||||
string name = names[i].Trim();
|
||||
if (name == "...")
|
||||
{
|
||||
if (i != names.Length - 1)
|
||||
return false;
|
||||
continue;
|
||||
}
|
||||
if (!IsName(name) || LuaKeywords.IsReserved(name))
|
||||
return false;
|
||||
if (!wrapped && names.Length > 1)
|
||||
return false;
|
||||
}
|
||||
|
||||
parameters = string.Join(", ", System.Array.ConvertAll(names, static n => n.Trim()));
|
||||
return true;
|
||||
}
|
||||
|
||||
private static bool IsName(string text)
|
||||
{
|
||||
if (text.Length == 0)
|
||||
return false;
|
||||
if (text[0] != '_' && !char.IsLetter(text[0]))
|
||||
return false;
|
||||
for (int i = 1; i < text.Length; i++)
|
||||
{
|
||||
if (text[i] != '_' && !char.IsLetterOrDigit(text[i]))
|
||||
return false;
|
||||
}
|
||||
return true;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,44 @@
|
||||
namespace LuaScript.Compat.Syntax.Rules
|
||||
{
|
||||
[LuaSyntaxRule(40)]
|
||||
internal sealed class LogicalNotRule : ILuaSyntaxRule
|
||||
{
|
||||
public bool TryApply(LuaRewriteContext context)
|
||||
{
|
||||
if (!context.Current.IsOperator("!"))
|
||||
return false;
|
||||
|
||||
context.Advance();
|
||||
context.EmitWord("not");
|
||||
return true;
|
||||
}
|
||||
}
|
||||
|
||||
[LuaSyntaxRule(50)]
|
||||
internal sealed class AndAliasRule : ILuaSyntaxRule
|
||||
{
|
||||
public bool TryApply(LuaRewriteContext context)
|
||||
{
|
||||
if (!context.Current.IsOperator("&&"))
|
||||
return false;
|
||||
|
||||
context.Advance();
|
||||
context.EmitWord("and");
|
||||
return true;
|
||||
}
|
||||
}
|
||||
|
||||
[LuaSyntaxRule(60)]
|
||||
internal sealed class OrAliasRule : ILuaSyntaxRule
|
||||
{
|
||||
public bool TryApply(LuaRewriteContext context)
|
||||
{
|
||||
if (!context.Current.IsOperator("||"))
|
||||
return false;
|
||||
|
||||
context.Advance();
|
||||
context.EmitWord("or");
|
||||
return true;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,20 @@
|
||||
namespace LuaScript.Compat.Syntax.Rules
|
||||
{
|
||||
[LuaSyntaxRule(100)]
|
||||
internal sealed class NilCoalesceRule : ILuaSyntaxRule
|
||||
{
|
||||
public bool TryApply(LuaRewriteContext context)
|
||||
{
|
||||
if (!context.Current.IsOperator("??"))
|
||||
return false;
|
||||
if (!context.TryPopOrOperand(out string left))
|
||||
return false;
|
||||
|
||||
context.Advance();
|
||||
string right = context.ReadForwardOrOperand();
|
||||
string temporary = context.NextTemporary();
|
||||
context.EmitRaw($"(function() local {temporary} = ({left}) if {temporary} ~= nil then return {temporary} else return ({right}) end end)()");
|
||||
return true;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,26 @@
|
||||
namespace LuaScript.Compat.Syntax.Rules
|
||||
{
|
||||
[LuaSyntaxRule(110)]
|
||||
internal sealed class LuaNumericRangeRule : ILuaSyntaxRule
|
||||
{
|
||||
public bool TryApply(LuaRewriteContext context)
|
||||
{
|
||||
if (!context.Current.IsName("in"))
|
||||
return false;
|
||||
|
||||
int open = context.NextSignificant(context.Index + 1);
|
||||
if (open < 0 || !context.Input[open].IsOperator("<"))
|
||||
return false;
|
||||
if (!LuaRangeSyntax.TryParse(context.Input, open, out var parts, out int end))
|
||||
return false;
|
||||
|
||||
string stopExpression = parts.Exclusive ? $"({parts.Stop}) - 1" : parts.Stop;
|
||||
string replacement = parts.Step is null
|
||||
? $"= {parts.Start}, {stopExpression}"
|
||||
: $"= {parts.Start}, {stopExpression}, {parts.Step}";
|
||||
context.EmitRaw(replacement);
|
||||
context.Index = end;
|
||||
return true;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,122 @@
|
||||
using System.Collections.Generic;
|
||||
using System.Text;
|
||||
|
||||
namespace LuaScript.Compat.Syntax.Rules
|
||||
{
|
||||
[LuaSyntaxRule(98)]
|
||||
internal sealed class LuaPipeRule : ILuaSyntaxRule
|
||||
{
|
||||
public bool TryApply(LuaRewriteContext context)
|
||||
{
|
||||
if (!context.Current.IsOperator("|>"))
|
||||
return false;
|
||||
|
||||
int targetStart = context.NextSignificant(context.Index + 1);
|
||||
if (targetStart < 0 || !LuaSyntaxFacts.IsValueStart(context.Input[targetStart]))
|
||||
return false;
|
||||
|
||||
if (!context.TryPopOrOperand(out string left))
|
||||
return false;
|
||||
|
||||
context.Advance();
|
||||
var segment = ReadSegment(context);
|
||||
string call = BuildCall(segment, left);
|
||||
context.EmitRaw(call);
|
||||
return true;
|
||||
}
|
||||
|
||||
private static List<LuaSyntaxToken> ReadSegment(LuaRewriteContext context)
|
||||
{
|
||||
var tokens = new List<LuaSyntaxToken>();
|
||||
int depth = 0;
|
||||
while (!context.AtEnd)
|
||||
{
|
||||
var token = context.Current;
|
||||
if (token.Kind == LuaSyntaxTokenKind.Newline && depth == 0)
|
||||
break;
|
||||
if (token.Kind == LuaSyntaxTokenKind.Name && depth == 0 && LuaKeywords.IsExpressionBoundary(token.Text))
|
||||
break;
|
||||
if (token.Kind == LuaSyntaxTokenKind.Operator)
|
||||
{
|
||||
if (token.Text is "(" or "[" or "{")
|
||||
{
|
||||
depth++;
|
||||
}
|
||||
else if (token.Text is ")" or "]" or "}")
|
||||
{
|
||||
if (depth == 0)
|
||||
break;
|
||||
depth--;
|
||||
}
|
||||
else if (depth == 0 && token.Text is "," or ";" or "|>")
|
||||
{
|
||||
break;
|
||||
}
|
||||
}
|
||||
tokens.Add(token);
|
||||
context.Advance();
|
||||
}
|
||||
while (tokens.Count > 0 && tokens[0].IsTrivia)
|
||||
tokens.RemoveAt(0);
|
||||
while (tokens.Count > 0 && tokens[tokens.Count - 1].IsTrivia)
|
||||
tokens.RemoveAt(tokens.Count - 1);
|
||||
return tokens;
|
||||
}
|
||||
|
||||
private static string BuildCall(List<LuaSyntaxToken> segment, string left)
|
||||
{
|
||||
string argument = $"({left})";
|
||||
if (segment.Count == 0)
|
||||
return argument;
|
||||
|
||||
if (segment[segment.Count - 1].IsOperator(")"))
|
||||
{
|
||||
int open = FindOpeningParen(segment);
|
||||
if (open > 0)
|
||||
{
|
||||
string callee = Concat(segment, 0, open);
|
||||
string arguments = Concat(segment, open + 1, segment.Count - 1);
|
||||
return arguments.Length == 0
|
||||
? $"{callee}({argument})"
|
||||
: $"{callee}({argument}, {arguments})";
|
||||
}
|
||||
}
|
||||
|
||||
return $"{Concat(segment, 0, segment.Count)}({argument})";
|
||||
}
|
||||
|
||||
private static int FindOpeningParen(List<LuaSyntaxToken> segment)
|
||||
{
|
||||
int depth = 0;
|
||||
for (int i = segment.Count - 1; i >= 0; i--)
|
||||
{
|
||||
var token = segment[i];
|
||||
if (token.Kind != LuaSyntaxTokenKind.Operator)
|
||||
continue;
|
||||
if (token.Text is ")" or "]" or "}")
|
||||
{
|
||||
depth++;
|
||||
}
|
||||
else if (token.Text is "(" or "[" or "{")
|
||||
{
|
||||
depth--;
|
||||
if (depth == 0)
|
||||
return token.Text == "(" ? i : -1;
|
||||
}
|
||||
}
|
||||
return -1;
|
||||
}
|
||||
|
||||
private static string Concat(List<LuaSyntaxToken> segment, int begin, int end)
|
||||
{
|
||||
while (begin < end && segment[begin].IsTrivia)
|
||||
begin++;
|
||||
while (end > begin && segment[end - 1].IsTrivia)
|
||||
end--;
|
||||
var builder = new StringBuilder();
|
||||
for (int i = begin; i < end; i++)
|
||||
builder.Append(segment[i].Text);
|
||||
return builder.ToString();
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,49 @@
|
||||
namespace LuaScript.Compat.Syntax.Rules
|
||||
{
|
||||
[LuaSyntaxRule(108)]
|
||||
internal sealed class LuaRangeMembershipRule : ILuaSyntaxRule
|
||||
{
|
||||
public bool TryApply(LuaRewriteContext context)
|
||||
{
|
||||
if (!context.Current.IsName("in"))
|
||||
return false;
|
||||
if (IsForHeader(context))
|
||||
return false;
|
||||
|
||||
int open = context.NextSignificant(context.Index + 1);
|
||||
if (open < 0 || !context.Input[open].IsOperator("<"))
|
||||
return false;
|
||||
if (!LuaRangeSyntax.TryParse(context.Input, open, out var parts, out int end))
|
||||
return false;
|
||||
if (parts.Step is not null)
|
||||
return false;
|
||||
|
||||
if (!context.TryPopOrOperand(out string left))
|
||||
return false;
|
||||
|
||||
string temporary = context.NextTemporary();
|
||||
string upper = parts.Exclusive ? "<" : "<=";
|
||||
context.EmitRaw($"(function() local {temporary} = ({left}) return {temporary} >= ({LuaSyntaxExtensions.Rewrite(parts.Start)}) and {temporary} {upper} ({LuaSyntaxExtensions.Rewrite(parts.Stop)}) end)()");
|
||||
context.Index = end;
|
||||
return true;
|
||||
}
|
||||
|
||||
private static bool IsForHeader(LuaRewriteContext context)
|
||||
{
|
||||
var output = context.Output;
|
||||
for (int i = output.Count - 1; i >= 0; i--)
|
||||
{
|
||||
var token = output[i];
|
||||
if (token.Kind == LuaSyntaxTokenKind.Newline)
|
||||
return false;
|
||||
if (token.Kind != LuaSyntaxTokenKind.Name)
|
||||
continue;
|
||||
if (token.Text is "do" or "then")
|
||||
return false;
|
||||
if (token.Text == "for")
|
||||
return true;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,105 @@
|
||||
using System.Text;
|
||||
|
||||
namespace LuaScript.Compat.Syntax.Rules
|
||||
{
|
||||
[LuaSyntaxRule(92)]
|
||||
internal sealed class LuaSafeNavigationRule : ILuaSyntaxRule
|
||||
{
|
||||
public bool TryApply(LuaRewriteContext context)
|
||||
{
|
||||
if (!context.Current.IsOperator("?"))
|
||||
return false;
|
||||
|
||||
int accessor = context.NextSignificantSameLine(context.Index + 1);
|
||||
if (accessor < 0)
|
||||
return false;
|
||||
|
||||
if (context.Input[accessor].IsOperator("."))
|
||||
return TryApplyMember(context, accessor);
|
||||
if (context.Input[accessor].IsOperator("["))
|
||||
return TryApplyIndex(context, accessor);
|
||||
return false;
|
||||
}
|
||||
|
||||
private static bool TryApplyMember(LuaRewriteContext context, int accessor)
|
||||
{
|
||||
int name = context.NextSignificantSameLine(accessor + 1);
|
||||
if (name < 0)
|
||||
return false;
|
||||
var token = context.Input[name];
|
||||
if (token.Kind != LuaSyntaxTokenKind.Name || LuaKeywords.IsReserved(token.Text))
|
||||
return false;
|
||||
|
||||
if (!context.TryReadTrailingLvalue(out int start, out string target))
|
||||
return false;
|
||||
|
||||
context.RemoveOutputFrom(start);
|
||||
context.Index = name + 1;
|
||||
string temporary = context.NextTemporary();
|
||||
context.EmitRaw($"(function() local {temporary} = ({target}) if {temporary} == nil then return nil end return {temporary}.{token.Text} end)()");
|
||||
return true;
|
||||
}
|
||||
|
||||
private static bool TryApplyIndex(LuaRewriteContext context, int accessor)
|
||||
{
|
||||
int close = FindClosingBracket(context, accessor + 1);
|
||||
if (close < 0)
|
||||
return false;
|
||||
|
||||
string key = Concat(context, accessor + 1, close);
|
||||
if (key.Length == 0)
|
||||
return false;
|
||||
|
||||
if (!context.TryReadTrailingLvalue(out int start, out string target))
|
||||
return false;
|
||||
|
||||
context.RemoveOutputFrom(start);
|
||||
context.Index = close + 1;
|
||||
string temporary = context.NextTemporary();
|
||||
context.EmitRaw($"(function() local {temporary} = ({target}) if {temporary} == nil then return nil end return {temporary}[{LuaSyntaxExtensions.Rewrite(key)}] end)()");
|
||||
return true;
|
||||
}
|
||||
|
||||
private static int FindClosingBracket(LuaRewriteContext context, int from)
|
||||
{
|
||||
int depth = 0;
|
||||
for (int i = from; i < context.Input.Count; i++)
|
||||
{
|
||||
var token = context.Input[i];
|
||||
if (token.Kind != LuaSyntaxTokenKind.Operator)
|
||||
continue;
|
||||
if (token.Text is "(" or "[" or "{")
|
||||
{
|
||||
depth++;
|
||||
continue;
|
||||
}
|
||||
if (token.Text is ")" or "}")
|
||||
{
|
||||
if (depth == 0)
|
||||
return -1;
|
||||
depth--;
|
||||
continue;
|
||||
}
|
||||
if (token.Text == "]")
|
||||
{
|
||||
if (depth == 0)
|
||||
return i;
|
||||
depth--;
|
||||
}
|
||||
}
|
||||
return -1;
|
||||
}
|
||||
|
||||
private static string Concat(LuaRewriteContext context, int begin, int end)
|
||||
{
|
||||
while (begin < end && context.Input[begin].IsTrivia)
|
||||
begin++;
|
||||
while (end > begin && context.Input[end - 1].IsTrivia)
|
||||
end--;
|
||||
var builder = new StringBuilder();
|
||||
for (int i = begin; i < end; i++)
|
||||
builder.Append(context.Input[i].Text);
|
||||
return builder.ToString();
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,85 @@
|
||||
namespace LuaScript.Compat.Syntax.Rules
|
||||
{
|
||||
[LuaSyntaxRule(96)]
|
||||
internal sealed class LuaTernaryRule : ILuaSyntaxRule
|
||||
{
|
||||
public bool TryApply(LuaRewriteContext context)
|
||||
{
|
||||
if (!context.Current.IsOperator("?"))
|
||||
return false;
|
||||
if (!context.TryPreviousOutputSignificantSameLine(out var previous) || !LuaSyntaxFacts.IsValueEnd(previous))
|
||||
return false;
|
||||
|
||||
int thenStart = context.NextSignificantSameLine(context.Index + 1);
|
||||
if (thenStart < 0 || !LuaSyntaxFacts.IsValueStart(context.Input[thenStart]))
|
||||
return false;
|
||||
|
||||
int colon = FindColon(context, context.Index + 1);
|
||||
if (colon < 0)
|
||||
return false;
|
||||
|
||||
int elseStart = context.NextSignificantSameLine(colon + 1);
|
||||
if (elseStart < 0 || !LuaSyntaxFacts.IsValueStart(context.Input[elseStart]))
|
||||
return false;
|
||||
|
||||
if (!context.TryPopOrOperand(out string condition))
|
||||
return false;
|
||||
|
||||
context.Index++;
|
||||
string thenExpression = ReadUntil(context, colon);
|
||||
context.Index = colon + 1;
|
||||
string elseExpression = context.ReadForwardOrOperand();
|
||||
|
||||
context.EmitRaw($"(function() if {condition} then return ({LuaSyntaxExtensions.Rewrite(thenExpression)}) else return ({LuaSyntaxExtensions.Rewrite(elseExpression)}) end end)()");
|
||||
return true;
|
||||
}
|
||||
|
||||
private static int FindColon(LuaRewriteContext context, int from)
|
||||
{
|
||||
int depth = 0;
|
||||
for (int i = from; i < context.Input.Count; i++)
|
||||
{
|
||||
var token = context.Input[i];
|
||||
if (token.Kind == LuaSyntaxTokenKind.Newline)
|
||||
return -1;
|
||||
if (token.Kind == LuaSyntaxTokenKind.Name && depth == 0 && LuaKeywords.IsExpressionBoundary(token.Text))
|
||||
return -1;
|
||||
if (token.Kind != LuaSyntaxTokenKind.Operator)
|
||||
continue;
|
||||
if (token.Text is "(" or "[" or "{")
|
||||
{
|
||||
depth++;
|
||||
continue;
|
||||
}
|
||||
if (token.Text is ")" or "]" or "}")
|
||||
{
|
||||
if (depth == 0)
|
||||
return -1;
|
||||
depth--;
|
||||
continue;
|
||||
}
|
||||
if (depth > 0)
|
||||
continue;
|
||||
if (token.Text is "," or ";" or "?")
|
||||
return -1;
|
||||
if (token.Text == ":")
|
||||
return i;
|
||||
}
|
||||
return -1;
|
||||
}
|
||||
|
||||
private static string ReadUntil(LuaRewriteContext context, int stop)
|
||||
{
|
||||
var builder = new System.Text.StringBuilder();
|
||||
int begin = context.Index;
|
||||
int end = stop;
|
||||
while (begin < end && context.Input[begin].IsTrivia)
|
||||
begin++;
|
||||
while (end > begin && context.Input[end - 1].IsTrivia)
|
||||
end--;
|
||||
for (int i = begin; i < end; i++)
|
||||
builder.Append(context.Input[i].Text);
|
||||
return builder.ToString();
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,11 +1,11 @@
|
||||
<Project Sdk="Microsoft.NET.Sdk">
|
||||
<Project Sdk="Microsoft.NET.Sdk">
|
||||
|
||||
<PropertyGroup>
|
||||
<TargetFramework>netstandard2.0</TargetFramework>
|
||||
<LangVersion>latest</LangVersion>
|
||||
<Nullable>enable</Nullable>
|
||||
<ImplicitUsings>enable</ImplicitUsings>
|
||||
<Version>1.13.4</Version>
|
||||
<Version>1.16.3</Version>
|
||||
<IsRoslynComponent>true</IsRoslynComponent>
|
||||
<EnforceExtendedAnalyzerRules>true</EnforceExtendedAnalyzerRules>
|
||||
</PropertyGroup>
|
||||
|
||||
@@ -0,0 +1,76 @@
|
||||
using System;
|
||||
using System.Collections.Immutable;
|
||||
using System.Linq;
|
||||
using System.Text;
|
||||
using Microsoft.CodeAnalysis;
|
||||
using Microsoft.CodeAnalysis.CSharp.Syntax;
|
||||
using Microsoft.CodeAnalysis.Text;
|
||||
|
||||
namespace LuaScript.Generator
|
||||
{
|
||||
internal sealed record LuaSyntaxRuleModel(string TypeName, int Order);
|
||||
|
||||
[Generator]
|
||||
public sealed class LuaSyntaxRuleGenerator : IIncrementalGenerator
|
||||
{
|
||||
private const string RuleAttributeName = "LuaScript.Compat.Syntax.LuaSyntaxRuleAttribute";
|
||||
private const string RuleInterfaceName = "LuaScript.Compat.Syntax.ILuaSyntaxRule";
|
||||
|
||||
public void Initialize(IncrementalGeneratorInitializationContext context)
|
||||
{
|
||||
var rules = context.SyntaxProvider
|
||||
.ForAttributeWithMetadataName(
|
||||
RuleAttributeName,
|
||||
static (node, _) => node is ClassDeclarationSyntax,
|
||||
static (ctx, _) => CreateModel(ctx))
|
||||
.Where(static model => model is not null)
|
||||
.Select(static (model, _) => model!);
|
||||
|
||||
context.RegisterSourceOutput(rules.Collect(), static (ctx, models) =>
|
||||
{
|
||||
if (models.Length == 0)
|
||||
return;
|
||||
ctx.AddSource("LuaSyntaxRuleRegistry.g.cs", SourceText.From(Emit(models), Encoding.UTF8));
|
||||
});
|
||||
}
|
||||
|
||||
private static LuaSyntaxRuleModel? CreateModel(GeneratorAttributeSyntaxContext context)
|
||||
{
|
||||
if (context.TargetSymbol is not INamedTypeSymbol symbol)
|
||||
return null;
|
||||
|
||||
if (!symbol.AllInterfaces.Any(static contract => contract.ToDisplayString() == RuleInterfaceName))
|
||||
return null;
|
||||
|
||||
int order = 0;
|
||||
var arguments = context.Attributes[0].ConstructorArguments;
|
||||
if (arguments.Length > 0 && arguments[0].Value is int value)
|
||||
order = value;
|
||||
|
||||
return new LuaSyntaxRuleModel(symbol.ToDisplayString(), order);
|
||||
}
|
||||
|
||||
private static string Emit(ImmutableArray<LuaSyntaxRuleModel> models)
|
||||
{
|
||||
var ordered = models
|
||||
.OrderBy(static m => m.Order)
|
||||
.ThenBy(static m => m.TypeName, StringComparer.Ordinal)
|
||||
.ToArray();
|
||||
|
||||
var builder = new StringBuilder();
|
||||
builder.AppendLine("#nullable enable");
|
||||
builder.AppendLine("namespace LuaScript.Compat.Syntax");
|
||||
builder.AppendLine("{");
|
||||
builder.AppendLine(" internal static class LuaSyntaxRuleRegistry");
|
||||
builder.AppendLine(" {");
|
||||
builder.AppendLine(" internal static readonly global::LuaScript.Compat.Syntax.ILuaSyntaxRule[] Rules = new global::LuaScript.Compat.Syntax.ILuaSyntaxRule[]");
|
||||
builder.AppendLine(" {");
|
||||
foreach (var model in ordered)
|
||||
builder.AppendLine($" new global::{model.TypeName}(),");
|
||||
builder.AppendLine(" };");
|
||||
builder.AppendLine(" }");
|
||||
builder.AppendLine("}");
|
||||
return builder.ToString();
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -6,7 +6,7 @@ namespace LuaScript.Engine.Kernel
|
||||
internal sealed class KernelExtractor
|
||||
{
|
||||
private readonly List<KExpr> _bindings = [];
|
||||
private readonly Dictionary<string, int> _scope = new(StringComparer.Ordinal);
|
||||
private Dictionary<string, int> _scope = new(StringComparer.Ordinal);
|
||||
private readonly SortedSet<KernelUniform> _uniforms = [];
|
||||
|
||||
private string _widthVariable = string.Empty;
|
||||
@@ -46,25 +46,26 @@ namespace LuaScript.Engine.Kernel
|
||||
|
||||
if (index >= block.Count || block[index] is not NumericForStmt outer)
|
||||
return null;
|
||||
if (index + 1 != block.Count)
|
||||
int tail = index + 1;
|
||||
if (tail < block.Count && IsPutPixelData(block[tail]))
|
||||
tail++;
|
||||
if (tail != block.Count)
|
||||
return null;
|
||||
|
||||
if (!TryAxis(outer, out string outerVar, out KAxis outerAxis))
|
||||
return null;
|
||||
_scope.Remove(outerVar);
|
||||
if (outer.Body.Count != 1 || outer.Body[0] is not NumericForStmt inner)
|
||||
return null;
|
||||
if (!TryAxis(inner, out string innerVar, out KAxis innerAxis))
|
||||
return null;
|
||||
_scope.Remove(innerVar);
|
||||
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;
|
||||
@@ -72,6 +73,13 @@ namespace LuaScript.Engine.Kernel
|
||||
return _pixelDataVariable is null ? BuildKernel(inner.Body) : BuildPixelDataKernel(inner.Body);
|
||||
}
|
||||
|
||||
private bool IsPutPixelData(LuaStmt statement) =>
|
||||
_pixelDataVariable is not null &&
|
||||
statement is CallStmt { Call: CallExpr { Arguments.Count: 1 } call } &&
|
||||
IsObjectMethod(call, "putpixeldata") &&
|
||||
call.Arguments[0] is NameExpr { } handle &&
|
||||
string.Equals(handle.Name, _pixelDataVariable, StringComparison.Ordinal);
|
||||
|
||||
private bool TryBindPixelData(LocalStmt local)
|
||||
{
|
||||
if (local.Names.Count != 1 || local.Values.Count != 1 ||
|
||||
@@ -105,6 +113,9 @@ namespace LuaScript.Engine.Kernel
|
||||
case AssignStmt assign:
|
||||
BindAssign(assign);
|
||||
break;
|
||||
case IfStmt conditional:
|
||||
LowerConditional(conditional);
|
||||
break;
|
||||
case CallStmt { Call: MethodCallExpr set } when IsPixelDataSet(set, out int writeChannel):
|
||||
var value = ClampChannel(Lower(set.Arguments[1]));
|
||||
if (writeChannel == 0) outR = value;
|
||||
@@ -140,11 +151,25 @@ namespace LuaScript.Engine.Kernel
|
||||
if (expression is MemberExpr { Target: NameExpr { Name: "obj" }, Name: var field } &&
|
||||
KernelUniforms.TryResolveMember("obj", field, out var uniform))
|
||||
return uniform == KernelUniform.Width;
|
||||
if (expression is NameExpr { } alias &&
|
||||
TryUniformAlias(alias.Name, out var aliased))
|
||||
return aliased == KernelUniform.Width;
|
||||
return _pixelDataVariable is not null &&
|
||||
expression is MemberExpr { Target: NameExpr { } target, Name: "width" } &&
|
||||
string.Equals(target.Name, _pixelDataVariable, StringComparison.Ordinal);
|
||||
}
|
||||
|
||||
private bool TryUniformAlias(string name, out KernelUniform uniform)
|
||||
{
|
||||
if (_scope.TryGetValue(name, out int slot) && _bindings[slot] is KUniformRef reference)
|
||||
{
|
||||
uniform = reference.Uniform;
|
||||
return true;
|
||||
}
|
||||
uniform = default;
|
||||
return false;
|
||||
}
|
||||
|
||||
private bool TryPixelDataChannel(LuaExpr expression, out int channel)
|
||||
{
|
||||
channel = 0;
|
||||
@@ -221,6 +246,9 @@ namespace LuaScript.Engine.Kernel
|
||||
case AssignStmt assign:
|
||||
BindAssign(assign);
|
||||
break;
|
||||
case IfStmt conditional:
|
||||
LowerConditional(conditional);
|
||||
break;
|
||||
default:
|
||||
return null;
|
||||
}
|
||||
@@ -276,6 +304,76 @@ namespace LuaScript.Engine.Kernel
|
||||
_scope[((NameExpr)assign.Targets[i]).Name] = AddBinding(lowered[i]);
|
||||
}
|
||||
|
||||
private void LowerConditional(IfStmt statement) =>
|
||||
LowerConditional(statement.Clauses, 0, statement.ElseBody);
|
||||
|
||||
private void LowerConditional(IReadOnlyList<IfClause> clauses, int index, IReadOnlyList<LuaStmt>? elseBody)
|
||||
{
|
||||
var clause = clauses[index];
|
||||
var condition = LowerBool(clause.Condition);
|
||||
var baseline = _scope;
|
||||
|
||||
_scope = new Dictionary<string, int>(baseline, StringComparer.Ordinal);
|
||||
LowerBranchBody(clause.Body);
|
||||
var taken = _scope;
|
||||
|
||||
_scope = new Dictionary<string, int>(baseline, StringComparer.Ordinal);
|
||||
if (index + 1 < clauses.Count)
|
||||
LowerConditional(clauses, index + 1, elseBody);
|
||||
else if (elseBody is not null)
|
||||
LowerBranchBody(elseBody);
|
||||
var skipped = _scope;
|
||||
|
||||
var merged = new Dictionary<string, int>(baseline.Count, StringComparer.Ordinal);
|
||||
foreach (var name in baseline.Keys)
|
||||
{
|
||||
int whenTrue = taken[name];
|
||||
int whenFalse = skipped[name];
|
||||
merged[name] = whenTrue == whenFalse
|
||||
? whenTrue
|
||||
: AddBinding(new KSelect(condition, new KLocalRef(whenTrue), new KLocalRef(whenFalse)));
|
||||
}
|
||||
_scope = merged;
|
||||
}
|
||||
|
||||
private void LowerBranchBody(IReadOnlyList<LuaStmt> body)
|
||||
{
|
||||
Dictionary<string, int>? shadowed = null;
|
||||
HashSet<string>? introduced = null;
|
||||
foreach (var statement in body)
|
||||
{
|
||||
switch (statement)
|
||||
{
|
||||
case LocalStmt local:
|
||||
foreach (var name in local.Names)
|
||||
{
|
||||
if (introduced?.Contains(name) == true || shadowed?.ContainsKey(name) == true)
|
||||
continue;
|
||||
if (_scope.TryGetValue(name, out int slot))
|
||||
(shadowed ??= new(StringComparer.Ordinal))[name] = slot;
|
||||
else
|
||||
(introduced ??= new(StringComparer.Ordinal)).Add(name);
|
||||
}
|
||||
BindLocal(local);
|
||||
break;
|
||||
case AssignStmt assign:
|
||||
BindAssign(assign);
|
||||
break;
|
||||
case IfStmt nested:
|
||||
LowerConditional(nested);
|
||||
break;
|
||||
default:
|
||||
throw new KernelUnsupportedException("Unsupported statement in a conditional branch.");
|
||||
}
|
||||
}
|
||||
if (shadowed is not null)
|
||||
foreach (var (name, slot) in shadowed)
|
||||
_scope[name] = slot;
|
||||
if (introduced is not null)
|
||||
foreach (var name in introduced)
|
||||
_scope.Remove(name);
|
||||
}
|
||||
|
||||
private void EnsureNotCoordinateName(string name)
|
||||
{
|
||||
if (string.Equals(name, _widthVariable, StringComparison.Ordinal) ||
|
||||
@@ -343,6 +441,16 @@ namespace LuaScript.Engine.Kernel
|
||||
if (member.Target is NameExpr target && KernelUniforms.TryResolveMember(target.Name, member.Name, out var uniform))
|
||||
return UseUniform(uniform);
|
||||
|
||||
if (_pixelDataVariable is not null &&
|
||||
member.Target is NameExpr { } handle &&
|
||||
string.Equals(handle.Name, _pixelDataVariable, StringComparison.Ordinal))
|
||||
{
|
||||
if (string.Equals(member.Name, "width", StringComparison.Ordinal))
|
||||
return UseUniform(KernelUniform.Width);
|
||||
if (string.Equals(member.Name, "height", StringComparison.Ordinal))
|
||||
return UseUniform(KernelUniform.Height);
|
||||
}
|
||||
|
||||
throw new KernelUnsupportedException("Unsupported member access in pixel kernel.");
|
||||
}
|
||||
|
||||
@@ -474,6 +582,20 @@ namespace LuaScript.Engine.Kernel
|
||||
return true;
|
||||
}
|
||||
}
|
||||
|
||||
if (bound.Left is NameExpr { } alias && TryUniformAlias(alias.Name, out var aliased))
|
||||
{
|
||||
if (aliased == KernelUniform.Width)
|
||||
{
|
||||
axis = KAxis.X;
|
||||
return true;
|
||||
}
|
||||
if (aliased == KernelUniform.Height)
|
||||
{
|
||||
axis = KAxis.Y;
|
||||
return true;
|
||||
}
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
|
||||
@@ -1,9 +1,9 @@
|
||||
<Project Sdk="Microsoft.NET.Sdk">
|
||||
<Project Sdk="Microsoft.NET.Sdk">
|
||||
|
||||
<PropertyGroup>
|
||||
<TargetFramework>net10.0-windows10.0.19041.0</TargetFramework>
|
||||
<ImplicitUsings>enable</ImplicitUsings>
|
||||
<Version>1.13.4</Version>
|
||||
<Version>1.16.3</Version>
|
||||
<Platforms>AnyCPU;x64</Platforms>
|
||||
<Nullable>enable</Nullable>
|
||||
</PropertyGroup>
|
||||
|
||||
@@ -1,9 +1,9 @@
|
||||
<Project Sdk="Microsoft.NET.Sdk">
|
||||
<Project Sdk="Microsoft.NET.Sdk">
|
||||
|
||||
<PropertyGroup>
|
||||
<TargetFramework>net10.0-windows10.0.19041.0</TargetFramework>
|
||||
<ImplicitUsings>enable</ImplicitUsings>
|
||||
<Version>1.13.4</Version>
|
||||
<Version>1.16.3</Version>
|
||||
<Platforms>AnyCPU;x64</Platforms>
|
||||
<Nullable>enable</Nullable>
|
||||
<AllowUnsafeBlocks>true</AllowUnsafeBlocks>
|
||||
|
||||
@@ -9,6 +9,13 @@ namespace LuaScript.Anchor
|
||||
|
||||
public static int ClampCount(int count) => Math.Clamp(count, 0, MaxAnchors);
|
||||
|
||||
public static int NormalizeCount(string group, int count)
|
||||
{
|
||||
if (count <= 0 && string.Equals(group, TrackGroup, StringComparison.Ordinal))
|
||||
return 1;
|
||||
return ClampCount(count);
|
||||
}
|
||||
|
||||
public static void ApplyOption(string option, ref AnchorConnection connection, ref bool is3D)
|
||||
{
|
||||
switch (option)
|
||||
@@ -52,6 +59,35 @@ namespace LuaScript.Anchor
|
||||
z = 0d;
|
||||
}
|
||||
|
||||
public static ImmutableList<LuaAnchorPoint> SetPosition(
|
||||
ImmutableList<LuaAnchorPoint> source, string group, int index, double x, double y, double z)
|
||||
{
|
||||
for (int i = 0; i < source.Count; i++)
|
||||
{
|
||||
var a = source[i];
|
||||
if (a.Index == index && string.Equals(a.Group, group, StringComparison.Ordinal))
|
||||
{
|
||||
return source.SetItem(i, new LuaAnchorPoint
|
||||
{
|
||||
Group = group,
|
||||
Index = index,
|
||||
X = x,
|
||||
Y = y,
|
||||
Z = z,
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
return source.Add(new LuaAnchorPoint
|
||||
{
|
||||
Group = group,
|
||||
Index = index,
|
||||
X = x,
|
||||
Y = y,
|
||||
Z = z,
|
||||
});
|
||||
}
|
||||
|
||||
public static ImmutableList<LuaAnchorPoint> ApplyDrag(
|
||||
ImmutableList<LuaAnchorPoint> source, string group, int index, double dx, double dy, double dz)
|
||||
{
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
using LuaScript.Anchor;
|
||||
using LuaScript.Compat;
|
||||
|
||||
namespace LuaScript
|
||||
{
|
||||
@@ -155,11 +156,69 @@ namespace LuaScript
|
||||
_buffers["t"] = temp;
|
||||
}
|
||||
|
||||
Compositor.TryCompose(temp.Data, temp.Width, temp.Height, src, ImageWidth, ImageHeight, command);
|
||||
Compositor.TryCompose(temp.Data, temp.Width, temp.Height, src, ImageWidth, ImageHeight, command with { Blend = 0d });
|
||||
}
|
||||
|
||||
private readonly Dictionary<string, (byte[] Data, int Width, int Height)> _buffers = new(StringComparer.Ordinal);
|
||||
|
||||
internal IPixelShaderRunner? ShaderRunner { get; set; }
|
||||
|
||||
internal AviUtlPixelShaderLibrary PixelShaders { get; set; } = AviUtlPixelShaderLibrary.Empty;
|
||||
|
||||
internal bool TryGetShaderResource(string id, out byte[] data, out int width, out int height) =>
|
||||
TryReadBuffer(id, out data, out width, out height);
|
||||
|
||||
internal bool TryGetShaderTarget(string id, out byte[] data, out int width, out int height)
|
||||
{
|
||||
data = [];
|
||||
width = 0;
|
||||
height = 0;
|
||||
switch (BufferKind(id, out string key))
|
||||
{
|
||||
case 'o':
|
||||
EnsurePixelBuffer();
|
||||
if (_pixelBuffer is null)
|
||||
return false;
|
||||
data = _pixelBuffer;
|
||||
width = ImageWidth;
|
||||
height = ImageHeight;
|
||||
return true;
|
||||
case 't':
|
||||
case 'c':
|
||||
if (!_buffers.TryGetValue(key, out var stored))
|
||||
{
|
||||
int w = Math.Max(1, ImageWidth);
|
||||
int h = Math.Max(1, ImageHeight);
|
||||
stored = (new byte[w * h * 4], w, h);
|
||||
_buffers[key] = stored;
|
||||
}
|
||||
data = stored.Data;
|
||||
width = stored.Width;
|
||||
height = stored.Height;
|
||||
return true;
|
||||
case 'f':
|
||||
GetFrameBuffer(out data, out width, out height);
|
||||
return true;
|
||||
default:
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
internal bool NotifyShaderTargetWritten(string id)
|
||||
{
|
||||
switch (BufferKind(id, out _))
|
||||
{
|
||||
case 'o':
|
||||
MarkPixelsDirty();
|
||||
return false;
|
||||
case 'f':
|
||||
ReplaceBuffer(_frameBuffer, _frameBufferWidth, _frameBufferHeight);
|
||||
return true;
|
||||
default:
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
internal bool CopyBuffer(string dst, string src)
|
||||
{
|
||||
if (!TryReadBuffer(src, out var data, out int w, out int h))
|
||||
@@ -192,11 +251,47 @@ namespace LuaScript
|
||||
return true;
|
||||
}
|
||||
return false;
|
||||
case 'f':
|
||||
GetFrameBuffer(out data, out width, out height);
|
||||
return true;
|
||||
default:
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
private byte[] _frameBuffer = [];
|
||||
private int _frameBufferWidth;
|
||||
private int _frameBufferHeight;
|
||||
private bool _frameBufferValid;
|
||||
|
||||
internal void ResetFrameBuffer() => _frameBufferValid = false;
|
||||
|
||||
private void GetFrameBuffer(out byte[] data, out int width, out int height)
|
||||
{
|
||||
int w = Math.Max(1, SceneWidth);
|
||||
int h = Math.Max(1, SceneHeight);
|
||||
int length = w * h * 4;
|
||||
if (_frameBuffer.Length < length)
|
||||
{
|
||||
_frameBuffer = new byte[length];
|
||||
_frameBufferValid = false;
|
||||
}
|
||||
if (!_frameBufferValid || _frameBufferWidth != w || _frameBufferHeight != h)
|
||||
{
|
||||
Array.Clear(_frameBuffer, 0, length);
|
||||
_frameBufferWidth = w;
|
||||
_frameBufferHeight = h;
|
||||
EnsurePixelBuffer();
|
||||
if (_pixelBuffer is not null && !ReferenceEquals(_pixelBuffer, _frameBuffer))
|
||||
Compositor.TryCompose(_frameBuffer, w, h, _pixelBuffer, ImageWidth, ImageHeight,
|
||||
new DrawCommand(w * 0.5 + X, h * 0.5 + Y, 0d, Zoom, Alpha / 255d, Aspect, null, 1d, 0d));
|
||||
_frameBufferValid = true;
|
||||
}
|
||||
data = _frameBuffer;
|
||||
width = w;
|
||||
height = h;
|
||||
}
|
||||
|
||||
private bool TryWriteBuffer(string id, byte[] data, int width, int height)
|
||||
{
|
||||
int n = width * height * 4;
|
||||
|
||||
@@ -38,6 +38,14 @@ namespace LuaScript.Engine
|
||||
private byte[] _stringValueBytes = new byte[256];
|
||||
private byte[] _sceneValueBytes = new byte[256];
|
||||
|
||||
private static readonly byte[] s_shaderTransparentPixel = new byte[4];
|
||||
private readonly PixelShaderInput[] _shaderInputs = new PixelShaderInput[NativeProtocol.ShaderResourcesMax];
|
||||
private readonly byte[]?[] _shaderResourceData = new byte[NativeProtocol.ShaderResourcesMax][];
|
||||
private readonly float[] _shaderConstants = new float[NativeProtocol.ShaderConstantsMax];
|
||||
private byte[] _shaderTarget = [];
|
||||
|
||||
private long PixelRegionCapacity => _allocatedSize - _pixelOffset - NativeProtocol.ShaderRegionBytes;
|
||||
|
||||
public LuaJitWorker(string nativeDir, string scriptPath)
|
||||
{
|
||||
_nativeDir = nativeDir;
|
||||
@@ -68,6 +76,7 @@ namespace LuaScript.Engine
|
||||
Action<string, int, bool, int, double[]> setAnchor,
|
||||
Func<string, SceneValue> sceneGetValue,
|
||||
Action<string, SceneValue> sceneSetValue,
|
||||
PixelShaderInvoke? runPixelShader,
|
||||
out bool pixelsDirty,
|
||||
out bool bufferReplaced,
|
||||
out int resultWidth,
|
||||
@@ -151,7 +160,7 @@ namespace LuaScript.Engine
|
||||
}
|
||||
else
|
||||
{
|
||||
DispatchCallback(view, resolveObject, loadFigure, loadText, loadImage, loadMovie, addEffect, setAnchor, sceneGetValue, sceneSetValue);
|
||||
DispatchCallback(view, resolveObject, loadFigure, loadText, loadImage, loadMovie, addEffect, setAnchor, sceneGetValue, sceneSetValue, runPixelShader);
|
||||
}
|
||||
_workEvent.Set();
|
||||
}
|
||||
@@ -177,7 +186,7 @@ namespace LuaScript.Engine
|
||||
bufferReplaced = resultWidth != width || resultHeight != height;
|
||||
|
||||
pixelsDirty = view.ReadInt32(NativeProtocol.OffPixelsDirty) != 0;
|
||||
if (pixelsDirty && (long)resultWidth * resultHeight * 4 > _allocatedSize - _pixelOffset)
|
||||
if (pixelsDirty && (long)resultWidth * resultHeight * 4 > PixelRegionCapacity)
|
||||
{
|
||||
error = "native worker reported a pixel buffer beyond capacity";
|
||||
return false;
|
||||
@@ -196,7 +205,39 @@ namespace LuaScript.Engine
|
||||
try
|
||||
{
|
||||
long offset = _view.PointerOffset + _pixelOffset;
|
||||
access((nint)(ptr + offset), (long)handle.ByteLength - offset);
|
||||
access((nint)(ptr + offset), PixelRegionCapacity);
|
||||
}
|
||||
finally
|
||||
{
|
||||
handle.ReleasePointer();
|
||||
}
|
||||
}
|
||||
|
||||
private unsafe void ReadRegion(long offset, byte[] destination, int length)
|
||||
{
|
||||
var handle = _view!.SafeMemoryMappedViewHandle;
|
||||
byte* ptr = null;
|
||||
handle.AcquirePointer(ref ptr);
|
||||
try
|
||||
{
|
||||
fixed (byte* dst = destination)
|
||||
Buffer.MemoryCopy(ptr + _view.PointerOffset + offset, dst, destination.Length, length);
|
||||
}
|
||||
finally
|
||||
{
|
||||
handle.ReleasePointer();
|
||||
}
|
||||
}
|
||||
|
||||
private unsafe void WriteRegion(long offset, byte[] source, int length)
|
||||
{
|
||||
var handle = _view!.SafeMemoryMappedViewHandle;
|
||||
byte* ptr = null;
|
||||
handle.AcquirePointer(ref ptr);
|
||||
try
|
||||
{
|
||||
fixed (byte* src = source)
|
||||
Buffer.MemoryCopy(src, ptr + _view.PointerOffset + offset, (ulong)handle.ByteLength - (ulong)(_view.PointerOffset + offset), (ulong)length);
|
||||
}
|
||||
finally
|
||||
{
|
||||
@@ -283,7 +324,8 @@ namespace LuaScript.Engine
|
||||
Action<string, IReadOnlyList<KeyValuePair<string, object>>> addEffect,
|
||||
Action<string, int, bool, int, double[]> setAnchor,
|
||||
Func<string, SceneValue> sceneGetValue,
|
||||
Action<string, SceneValue> sceneSetValue)
|
||||
Action<string, SceneValue> sceneSetValue,
|
||||
PixelShaderInvoke? runPixelShader)
|
||||
{
|
||||
int kind = view.ReadInt32(NativeProtocol.OffCallbackKind);
|
||||
switch (kind)
|
||||
@@ -315,9 +357,142 @@ namespace LuaScript.Engine
|
||||
case NativeProtocol.CbKindSceneSet:
|
||||
ResolveSceneSetCallback(view, sceneSetValue);
|
||||
break;
|
||||
case NativeProtocol.CbKindPixelShaderStage:
|
||||
ResolveShaderStageCallback(view);
|
||||
break;
|
||||
case NativeProtocol.CbKindPixelShaderRun:
|
||||
ResolveShaderRunCallback(view, runPixelShader);
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
private void ResolveShaderStageCallback(MemoryMappedViewAccessor view)
|
||||
{
|
||||
long meta = NativeProtocol.ShaderMetaOffset(_allocatedSize);
|
||||
int width = (int)view.ReadDouble(meta + NativeProtocol.ShaderMetaImageWidth * 8);
|
||||
int height = (int)view.ReadDouble(meta + NativeProtocol.ShaderMetaImageHeight * 8);
|
||||
int slot = (int)view.ReadDouble(meta + NativeProtocol.ShaderMetaImageKind * 8);
|
||||
if ((uint)slot >= NativeProtocol.ShaderResourcesMax ||
|
||||
!TryStageShaderInput(slot, width, height, NativeProtocol.ShaderImageOffset(_allocatedSize)))
|
||||
{
|
||||
view.Write(NativeProtocol.OffCallbackFound, 0);
|
||||
return;
|
||||
}
|
||||
view.Write(NativeProtocol.OffCallbackFound, 1);
|
||||
}
|
||||
|
||||
private bool TryStageShaderInput(int slot, int width, int height, long sourceOffset)
|
||||
{
|
||||
long length = (long)width * height * 4;
|
||||
if (width <= 0 || height <= 0 || length > NativeProtocol.MaxPixelBufferSize)
|
||||
return false;
|
||||
|
||||
ref byte[]? data = ref _shaderResourceData[slot];
|
||||
if (data is null || data.Length < length)
|
||||
data = new byte[length];
|
||||
ReadRegion(sourceOffset, data, (int)length);
|
||||
_shaderInputs[slot] = new PixelShaderInput(data, width, height);
|
||||
return true;
|
||||
}
|
||||
|
||||
private void ResolveShaderRunCallback(MemoryMappedViewAccessor view, PixelShaderInvoke? runPixelShader)
|
||||
{
|
||||
long meta = NativeProtocol.ShaderMetaOffset(_allocatedSize);
|
||||
int tagLen = Math.Clamp(view.ReadInt32(NativeProtocol.OffCallbackTagLen), 0, NativeProtocol.CallbackTagMax);
|
||||
view.ReadArray(NativeProtocol.CallbackTagOffset, _callbackTag, 0, tagLen);
|
||||
string name = ResolveTag(tagLen);
|
||||
|
||||
int resourceCount = Math.Clamp((int)view.ReadDouble(meta + NativeProtocol.ShaderMetaResourceCount * 8), 0, NativeProtocol.ShaderResourcesMax);
|
||||
int blendMode = (int)view.ReadDouble(meta + NativeProtocol.ShaderMetaBlendMode * 8);
|
||||
double compositeBlend = view.ReadDouble(meta + NativeProtocol.ShaderMetaCompositeBlend * 8);
|
||||
int samplerValue = (int)view.ReadDouble(meta + NativeProtocol.ShaderMetaSampler * 8);
|
||||
int constantCount = Math.Clamp((int)view.ReadDouble(meta + NativeProtocol.ShaderMetaConstantCount * 8), 0, NativeProtocol.ShaderConstantsMax);
|
||||
int targetWidth = (int)view.ReadDouble(meta + NativeProtocol.ShaderMetaImageWidth * 8);
|
||||
int targetHeight = (int)view.ReadDouble(meta + NativeProtocol.ShaderMetaImageHeight * 8);
|
||||
int targetKind = (int)view.ReadDouble(meta + NativeProtocol.ShaderMetaImageKind * 8);
|
||||
|
||||
for (int i = 0; i < resourceCount; i++)
|
||||
{
|
||||
int kind = (int)view.ReadDouble(meta + (NativeProtocol.ShaderMetaResourceKinds + i) * 8);
|
||||
switch (kind)
|
||||
{
|
||||
case NativeProtocol.ShaderResourceStaged:
|
||||
break;
|
||||
case NativeProtocol.ShaderResourceRandom:
|
||||
_shaderInputs[i] = PixelShaderInput.Random;
|
||||
break;
|
||||
case NativeProtocol.ShaderResourceObject:
|
||||
if (!TryStageShaderInput(i, view.ReadInt32(NativeProtocol.OffWidth), view.ReadInt32(NativeProtocol.OffHeight), _pixelOffset))
|
||||
_shaderInputs[i] = new PixelShaderInput(s_shaderTransparentPixel, 1, 1);
|
||||
break;
|
||||
default:
|
||||
_shaderInputs[i] = new PixelShaderInput(s_shaderTransparentPixel, 1, 1);
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
if (constantCount > 0)
|
||||
view.ReadArray(NativeProtocol.ShaderConstantsOffset(_allocatedSize), _shaderConstants, 0, constantCount);
|
||||
|
||||
var status = PixelShaderRunStatus.Unavailable;
|
||||
string? error = null;
|
||||
long targetLength = (long)targetWidth * targetHeight * 4;
|
||||
if (runPixelShader is not null &&
|
||||
targetWidth > 0 && targetHeight > 0 &&
|
||||
targetLength <= NativeProtocol.MaxPixelBufferSize &&
|
||||
(targetKind != NativeProtocol.ShaderTargetObject || targetLength <= PixelRegionCapacity))
|
||||
{
|
||||
int length = (int)targetLength;
|
||||
if (_shaderTarget.Length < length)
|
||||
_shaderTarget = new byte[length];
|
||||
long targetOffset = targetKind == NativeProtocol.ShaderTargetObject
|
||||
? _pixelOffset
|
||||
: NativeProtocol.ShaderImageOffset(_allocatedSize);
|
||||
ReadRegion(targetOffset, _shaderTarget, length);
|
||||
|
||||
var blend = blendMode switch
|
||||
{
|
||||
(int)PixelShaderBlendMode.Mask => PixelShaderBlend.Mask,
|
||||
(int)PixelShaderBlendMode.Draw => PixelShaderBlend.Draw,
|
||||
(int)PixelShaderBlendMode.Add => PixelShaderBlend.Add,
|
||||
(int)PixelShaderBlendMode.Composite => PixelShaderBlend.Composite(compositeBlend),
|
||||
_ => PixelShaderBlend.Copy,
|
||||
};
|
||||
var sampler = (uint)samplerValue <= (uint)PixelShaderSampler.Dot
|
||||
? (PixelShaderSampler)samplerValue
|
||||
: PixelShaderSampler.None;
|
||||
|
||||
try
|
||||
{
|
||||
status = runPixelShader(
|
||||
name,
|
||||
_shaderInputs.AsSpan(0, resourceCount),
|
||||
_shaderConstants.AsSpan(0, constantCount),
|
||||
blend, sampler,
|
||||
_shaderTarget, targetWidth, targetHeight,
|
||||
out error);
|
||||
}
|
||||
catch
|
||||
{
|
||||
status = PixelShaderRunStatus.Unavailable;
|
||||
}
|
||||
|
||||
if (status == PixelShaderRunStatus.Success)
|
||||
WriteRegion(targetOffset, _shaderTarget, length);
|
||||
}
|
||||
|
||||
if (status == PixelShaderRunStatus.CompileError)
|
||||
{
|
||||
var bytes = Encoding.UTF8.GetBytes(error ?? "obj.pixelshader: compile error");
|
||||
int errorLength = Math.Min(bytes.Length, NativeProtocol.CallbackTagMax);
|
||||
view.WriteArray(NativeProtocol.CallbackTagOffset, bytes, 0, errorLength);
|
||||
view.Write(NativeProtocol.OffCallbackTagLen, errorLength);
|
||||
}
|
||||
|
||||
view.Write(meta + NativeProtocol.ShaderMetaStatus * 8, (double)status);
|
||||
view.Write(NativeProtocol.OffCallbackFound, 1);
|
||||
}
|
||||
|
||||
private void ResolveSceneGetCallback(MemoryMappedViewAccessor view, Func<string, SceneValue> getValue)
|
||||
{
|
||||
int tagLen = Math.Clamp(view.ReadInt32(NativeProtocol.OffCallbackTagLen), 0, NativeProtocol.CallbackTagMax);
|
||||
@@ -496,7 +671,7 @@ namespace LuaScript.Engine
|
||||
catch { result = (new byte[4], 1, 1); }
|
||||
|
||||
int pixelSize = result.w * result.h * 4;
|
||||
long capacity = view.Capacity - _pixelOffset;
|
||||
long capacity = PixelRegionCapacity;
|
||||
if (pixelSize > capacity)
|
||||
{
|
||||
result = (new byte[4], 1, 1);
|
||||
@@ -531,7 +706,7 @@ namespace LuaScript.Engine
|
||||
catch { result = (new byte[4], 1, 1); }
|
||||
|
||||
int pixelSize = result.w * result.h * 4;
|
||||
long capacity = view.Capacity - _pixelOffset;
|
||||
long capacity = PixelRegionCapacity;
|
||||
if (pixelSize > capacity)
|
||||
{
|
||||
result = (new byte[4], 1, 1);
|
||||
@@ -557,7 +732,7 @@ namespace LuaScript.Engine
|
||||
catch { result = (new byte[4], 1, 1); }
|
||||
|
||||
int pixelSize = result.w * result.h * 4;
|
||||
long capacity = view.Capacity - _pixelOffset;
|
||||
long capacity = PixelRegionCapacity;
|
||||
if (pixelSize > capacity)
|
||||
{
|
||||
result = (new byte[4], 1, 1);
|
||||
@@ -584,7 +759,7 @@ namespace LuaScript.Engine
|
||||
catch { result = (new byte[4], 1, 1); }
|
||||
|
||||
int pixelSize = result.w * result.h * 4;
|
||||
long capacity = view.Capacity - _pixelOffset;
|
||||
long capacity = PixelRegionCapacity;
|
||||
if (pixelSize > capacity)
|
||||
{
|
||||
result = (new byte[4], 1, 1);
|
||||
@@ -643,7 +818,7 @@ namespace LuaScript.Engine
|
||||
|
||||
private void EnsureWorker(int width, int height, int stringCapacity)
|
||||
{
|
||||
long required = NativeProtocol.PixelOffset(stringCapacity) + (long)width * height * 4;
|
||||
long required = NativeProtocol.PixelOffset(stringCapacity) + (long)width * height * 4 + NativeProtocol.ShaderRegionBytes;
|
||||
if (_alive && _process is { HasExited: false } && _stringParamsCapacity == stringCapacity && required <= _allocatedSize)
|
||||
return;
|
||||
|
||||
|
||||
@@ -632,6 +632,135 @@ namespace LuaScript
|
||||
return DynValue.Void;
|
||||
}
|
||||
|
||||
[LuaFunction("pixelshader")]
|
||||
private DynValue PixelShader(CallbackArguments args)
|
||||
{
|
||||
_activeCancellation.ThrowIfCancellationRequested();
|
||||
if (_activeContext is null || args.Count < 2 ||
|
||||
args[0].Type != DataType.String || args[1].Type != DataType.String)
|
||||
return DynValue.Void;
|
||||
|
||||
var ctx = _activeContext;
|
||||
var runner = ctx.ShaderRunner;
|
||||
if (runner is null)
|
||||
return DynValue.Void;
|
||||
|
||||
string name = args[0].String;
|
||||
if (!ctx.PixelShaders.TryGet(name, out string hlsl))
|
||||
throw new ScriptRuntimeException($"obj.pixelshader: shader '{name}' is not defined in this script.");
|
||||
|
||||
int resourceCount = CollectShaderResources(ctx, args.Count > 2 ? args[2] : DynValue.Nil);
|
||||
int constantCount = CollectShaderConstants(args.Count > 3 ? args[3] : DynValue.Nil);
|
||||
var blend = ParseShaderBlend(args.Count > 4 ? args[4] : DynValue.Nil);
|
||||
var sampler = ParseShaderSampler(args.Count > 5 ? args[5] : DynValue.Nil);
|
||||
|
||||
string target = args[1].String;
|
||||
if (!ctx.TryGetShaderTarget(target, out byte[] targetData, out int targetWidth, out int targetHeight))
|
||||
return DynValue.Void;
|
||||
|
||||
var status = runner.TryRun(
|
||||
hlsl,
|
||||
AviUtlPixelShaderLibrary.EntryPointOf(name),
|
||||
_shaderResources.AsSpan(0, resourceCount),
|
||||
_shaderConstants.AsSpan(0, constantCount),
|
||||
blend, sampler,
|
||||
targetData, targetWidth, targetHeight,
|
||||
out string? error);
|
||||
|
||||
if (status == PixelShaderRunStatus.CompileError)
|
||||
throw new ScriptRuntimeException($"obj.pixelshader: shader '{name}' failed to compile.\n{error}");
|
||||
if (status == PixelShaderRunStatus.Success && ctx.NotifyShaderTargetWritten(target))
|
||||
RefreshObjDimensions();
|
||||
return DynValue.Void;
|
||||
}
|
||||
|
||||
private const int MaxShaderResources = 8;
|
||||
private const int MaxShaderConstants = 1024;
|
||||
|
||||
private static readonly byte[] s_transparentPixel = new byte[4];
|
||||
|
||||
private readonly PixelShaderInput[] _shaderResources = new PixelShaderInput[MaxShaderResources];
|
||||
private readonly float[] _shaderConstants = new float[MaxShaderConstants];
|
||||
|
||||
private static PixelShaderInput TransparentShaderResource => new(s_transparentPixel, 1, 1);
|
||||
|
||||
private int CollectShaderResources(AviUtlScriptContext ctx, DynValue value)
|
||||
{
|
||||
if (value.Type == DataType.String)
|
||||
{
|
||||
_shaderResources[0] = ResolveShaderResource(ctx, value.String);
|
||||
return 1;
|
||||
}
|
||||
if (value.Type != DataType.Table)
|
||||
return 0;
|
||||
|
||||
var table = value.Table;
|
||||
int count = table.Length;
|
||||
if (count > MaxShaderResources)
|
||||
throw new ScriptRuntimeException($"obj.pixelshader: too many resources ({count}). Up to {MaxShaderResources} are supported.");
|
||||
for (int i = 0; i < count; i++)
|
||||
{
|
||||
var entry = table.Get(i + 1);
|
||||
_shaderResources[i] = entry.Type == DataType.String
|
||||
? ResolveShaderResource(ctx, entry.String)
|
||||
: TransparentShaderResource;
|
||||
}
|
||||
return count;
|
||||
}
|
||||
|
||||
private static PixelShaderInput ResolveShaderResource(AviUtlScriptContext ctx, string id)
|
||||
{
|
||||
if (string.Equals(id, "random", StringComparison.Ordinal))
|
||||
return PixelShaderInput.Random;
|
||||
if (ctx.TryGetShaderResource(id, out var data, out int width, out int height))
|
||||
return new PixelShaderInput(data, width, height);
|
||||
return TransparentShaderResource;
|
||||
}
|
||||
|
||||
private int CollectShaderConstants(DynValue value)
|
||||
{
|
||||
if (value.Type != DataType.Table)
|
||||
return 0;
|
||||
var table = value.Table;
|
||||
int count = table.Length;
|
||||
if (count > MaxShaderConstants)
|
||||
throw new ScriptRuntimeException($"obj.pixelshader: too many constants ({count}). Up to {MaxShaderConstants} are supported.");
|
||||
for (int i = 0; i < count; i++)
|
||||
_shaderConstants[i] = (float)(table.Get(i + 1).CastToNumber() ?? 0d);
|
||||
return count;
|
||||
}
|
||||
|
||||
private static PixelShaderBlend ParseShaderBlend(DynValue value)
|
||||
{
|
||||
if (value.Type == DataType.Number)
|
||||
return PixelShaderBlend.Composite(value.Number);
|
||||
if (value.Type != DataType.String)
|
||||
return PixelShaderBlend.Copy;
|
||||
return value.String switch
|
||||
{
|
||||
"copy" => PixelShaderBlend.Copy,
|
||||
"mask" => PixelShaderBlend.Mask,
|
||||
"draw" => PixelShaderBlend.Draw,
|
||||
"add" => PixelShaderBlend.Add,
|
||||
_ => throw new ScriptRuntimeException($"obj.pixelshader: unknown blend '{value.String}'. Use copy, mask, draw, add or a blend number."),
|
||||
};
|
||||
}
|
||||
|
||||
private static PixelShaderSampler ParseShaderSampler(DynValue value)
|
||||
{
|
||||
if (value.Type != DataType.String)
|
||||
return PixelShaderSampler.None;
|
||||
return value.String switch
|
||||
{
|
||||
"clip" => PixelShaderSampler.Clip,
|
||||
"clamp" => PixelShaderSampler.Clamp,
|
||||
"loop" => PixelShaderSampler.Loop,
|
||||
"mirror" => PixelShaderSampler.Mirror,
|
||||
"dot" => PixelShaderSampler.Dot,
|
||||
_ => throw new ScriptRuntimeException($"obj.pixelshader: unknown sampler '{value.String}'. Use clip, clamp, loop, mirror or dot."),
|
||||
};
|
||||
}
|
||||
|
||||
[LuaFunction("getvalue")]
|
||||
private DynValue GetValue(CallbackArguments args)
|
||||
{
|
||||
@@ -699,9 +828,7 @@ namespace LuaScript
|
||||
return DynValue.NewNumber(0d);
|
||||
|
||||
var anchorName = args[0].String;
|
||||
int count = AnchorSupport.ClampCount((int)(args[1].CastToNumber() ?? 0d));
|
||||
if (string.Equals(anchorName, AnchorSupport.TrackGroup, StringComparison.Ordinal))
|
||||
return DynValue.NewNumber(0d);
|
||||
int count = AnchorSupport.NormalizeCount(anchorName, (int)(args[1].CastToNumber() ?? 0d));
|
||||
|
||||
var connection = AnchorConnection.None;
|
||||
bool is3D = false;
|
||||
|
||||
@@ -61,6 +61,8 @@ namespace LuaScript.Engine
|
||||
public const int CbKindFlushDraws = 10;
|
||||
public const int CbKindSceneGet = 11;
|
||||
public const int CbKindSceneSet = 12;
|
||||
public const int CbKindPixelShaderStage = 13;
|
||||
public const int CbKindPixelShaderRun = 14;
|
||||
|
||||
public const int DrawRingCapacity = 4096;
|
||||
public const int DrawEntryDoubles = 24;
|
||||
@@ -153,7 +155,41 @@ namespace LuaScript.Engine
|
||||
|
||||
public const int MaxPixelBufferSize = 3840 * 2160 * 4;
|
||||
|
||||
public const int ShaderMetaDoubles = 20;
|
||||
public const int ShaderConstantsMax = 1024;
|
||||
public const int ShaderResourcesMax = 8;
|
||||
|
||||
public const int ShaderMetaResourceCount = 0;
|
||||
public const int ShaderMetaBlendMode = 1;
|
||||
public const int ShaderMetaCompositeBlend = 2;
|
||||
public const int ShaderMetaSampler = 3;
|
||||
public const int ShaderMetaConstantCount = 4;
|
||||
public const int ShaderMetaImageWidth = 5;
|
||||
public const int ShaderMetaImageHeight = 6;
|
||||
public const int ShaderMetaImageKind = 7;
|
||||
public const int ShaderMetaStatus = 8;
|
||||
public const int ShaderMetaResourceKinds = 9;
|
||||
|
||||
public const int ShaderResourceStaged = 0;
|
||||
public const int ShaderResourceRandom = 1;
|
||||
public const int ShaderResourceTransparent = 2;
|
||||
public const int ShaderResourceObject = 3;
|
||||
|
||||
public const int ShaderTargetExchange = 0;
|
||||
public const int ShaderTargetObject = 1;
|
||||
|
||||
public const long ShaderRegionBytes = ShaderMetaDoubles * 8 + ShaderConstantsMax * 4 + MaxPixelBufferSize;
|
||||
|
||||
public static long ShaderMetaOffset(long bufferSize) => bufferSize - ShaderRegionBytes;
|
||||
|
||||
public static long ShaderConstantsOffset(long bufferSize) => ShaderMetaOffset(bufferSize) + ShaderMetaDoubles * 8;
|
||||
|
||||
public static long ShaderImageOffset(long bufferSize) => ShaderConstantsOffset(bufferSize) + ShaderConstantsMax * 4;
|
||||
|
||||
public static long BufferSize(int width, int height, int stringCapacity) =>
|
||||
PixelOffset(stringCapacity) + Math.Max((long)width * height * 4, MaxPixelBufferSize);
|
||||
PixelOffset(stringCapacity) + PixelRegionSize(width, height) + ShaderRegionBytes;
|
||||
|
||||
public static long PixelRegionSize(int width, int height) =>
|
||||
(Math.Max((long)width * height * 4, MaxPixelBufferSize) + 7) & ~7L;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,15 @@
|
||||
using System;
|
||||
|
||||
namespace LuaScript.Engine
|
||||
{
|
||||
internal delegate PixelShaderRunStatus PixelShaderInvoke(
|
||||
string name,
|
||||
ReadOnlySpan<PixelShaderInput> resources,
|
||||
ReadOnlySpan<float> constants,
|
||||
PixelShaderBlend blend,
|
||||
PixelShaderSampler sampler,
|
||||
byte[] target,
|
||||
int targetWidth,
|
||||
int targetHeight,
|
||||
out string? error);
|
||||
}
|
||||
@@ -3,7 +3,7 @@
|
||||
<PropertyGroup>
|
||||
<TargetFramework>net10.0-windows10.0.19041.0</TargetFramework>
|
||||
<ImplicitUsings>enable</ImplicitUsings>
|
||||
<Version>1.13.4</Version>
|
||||
<Version>1.16.3</Version>
|
||||
<Platforms>AnyCPU;x64</Platforms>
|
||||
<Nullable>enable</Nullable>
|
||||
<AllowUnsafeBlocks>true</AllowUnsafeBlocks>
|
||||
|
||||
@@ -0,0 +1,19 @@
|
||||
using System;
|
||||
|
||||
namespace LuaScript
|
||||
{
|
||||
internal interface IPixelShaderRunner
|
||||
{
|
||||
PixelShaderRunStatus TryRun(
|
||||
string hlsl,
|
||||
string entryPoint,
|
||||
ReadOnlySpan<PixelShaderInput> resources,
|
||||
ReadOnlySpan<float> constants,
|
||||
PixelShaderBlend blend,
|
||||
PixelShaderSampler sampler,
|
||||
byte[] target,
|
||||
int targetWidth,
|
||||
int targetHeight,
|
||||
out string? error);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,15 @@
|
||||
namespace LuaScript
|
||||
{
|
||||
internal readonly record struct PixelShaderBlend(PixelShaderBlendMode Mode, double CompositeBlend)
|
||||
{
|
||||
public static PixelShaderBlend Copy { get; } = new(PixelShaderBlendMode.Copy, 0d);
|
||||
|
||||
public static PixelShaderBlend Mask { get; } = new(PixelShaderBlendMode.Mask, 0d);
|
||||
|
||||
public static PixelShaderBlend Draw { get; } = new(PixelShaderBlendMode.Draw, 0d);
|
||||
|
||||
public static PixelShaderBlend Add { get; } = new(PixelShaderBlendMode.Add, 0d);
|
||||
|
||||
public static PixelShaderBlend Composite(double blend) => new(PixelShaderBlendMode.Composite, blend);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,11 @@
|
||||
namespace LuaScript
|
||||
{
|
||||
internal enum PixelShaderBlendMode
|
||||
{
|
||||
Copy,
|
||||
Mask,
|
||||
Draw,
|
||||
Add,
|
||||
Composite,
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,11 @@
|
||||
namespace LuaScript
|
||||
{
|
||||
internal readonly record struct PixelShaderInput(byte[]? Data, int Width, int Height)
|
||||
{
|
||||
public const int RandomSize = 256;
|
||||
|
||||
public static PixelShaderInput Random { get; } = new(null, RandomSize, RandomSize);
|
||||
|
||||
public bool IsRandom => Data is null;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,9 @@
|
||||
namespace LuaScript
|
||||
{
|
||||
internal enum PixelShaderRunStatus
|
||||
{
|
||||
Success,
|
||||
Unavailable,
|
||||
CompileError,
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,12 @@
|
||||
namespace LuaScript
|
||||
{
|
||||
internal enum PixelShaderSampler
|
||||
{
|
||||
None,
|
||||
Clip,
|
||||
Clamp,
|
||||
Loop,
|
||||
Mirror,
|
||||
Dot,
|
||||
}
|
||||
}
|
||||
@@ -13,6 +13,35 @@ namespace LuaScript.Tests
|
||||
Assert.Equal(AnchorSupport.MaxAnchors, AnchorSupport.ClampCount(100));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void NormalizeCount_DefaultsTrackToSinglePoint()
|
||||
{
|
||||
Assert.Equal(1, AnchorSupport.NormalizeCount(AnchorSupport.TrackGroup, 0));
|
||||
Assert.Equal(1, AnchorSupport.NormalizeCount(AnchorSupport.TrackGroup, -3));
|
||||
Assert.Equal(4, AnchorSupport.NormalizeCount(AnchorSupport.TrackGroup, 4));
|
||||
Assert.Equal(0, AnchorSupport.NormalizeCount("pos", 0));
|
||||
Assert.Equal(AnchorSupport.MaxAnchors, AnchorSupport.NormalizeCount("pos", 100));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void SetPosition_ReplacesOrAppendsAbsolute()
|
||||
{
|
||||
var source = ImmutableList.Create(new LuaAnchorPoint { Group = "pos", Index = 2, X = 10, Y = 20, Z = 30 });
|
||||
|
||||
var replaced = AnchorSupport.SetPosition(source, "pos", 2, 1, 2, 3);
|
||||
Assert.Single(replaced);
|
||||
Assert.Equal(1, replaced[0].X);
|
||||
Assert.Equal(2, replaced[0].Y);
|
||||
Assert.Equal(3, replaced[0].Z);
|
||||
|
||||
var appended = AnchorSupport.SetPosition(source, "pos", 5, 7, 8, 9);
|
||||
Assert.Equal(2, appended.Count);
|
||||
Assert.Equal(5, appended[1].Index);
|
||||
Assert.Equal(7, appended[1].X);
|
||||
Assert.Equal(8, appended[1].Y);
|
||||
Assert.Equal(9, appended[1].Z);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void ApplyOption_SetsConnectionAndDimension()
|
||||
{
|
||||
|
||||
@@ -0,0 +1,144 @@
|
||||
using LuaScript.Compat;
|
||||
|
||||
namespace LuaScript.Tests
|
||||
{
|
||||
public sealed class AviUtlPixelShaderLibraryTests
|
||||
{
|
||||
[Fact]
|
||||
public void Parse_EmptyOrNull_ReturnsEmpty()
|
||||
{
|
||||
Assert.Equal(0, AviUtlPixelShaderLibrary.Parse(null).Count);
|
||||
Assert.Equal(0, AviUtlPixelShaderLibrary.Parse(string.Empty).Count);
|
||||
Assert.Same(AviUtlPixelShaderLibrary.Empty, AviUtlPixelShaderLibrary.Parse(string.Empty));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Parse_SingleShader_ExtractsBody()
|
||||
{
|
||||
var source = "--[[pixelshader@psmain:\nfloat4 psmain(float4 pos : SV_Position) : SV_Target { return 0; }\n]]\nobj.pixelshader(\"psmain\", \"object\", \"object\")";
|
||||
var library = AviUtlPixelShaderLibrary.Parse(source);
|
||||
|
||||
Assert.Equal(1, library.Count);
|
||||
Assert.True(library.TryGet("psmain", out var hlsl));
|
||||
Assert.Contains("float4 psmain", hlsl);
|
||||
Assert.DoesNotContain("]]", hlsl);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Parse_MultipleShaders_AllExtracted()
|
||||
{
|
||||
var source = "--[[pixelshader@first:\nA\n]]\ncode\n--[[pixelshader@second:\nB\n]]";
|
||||
var library = AviUtlPixelShaderLibrary.Parse(source);
|
||||
|
||||
Assert.Equal(2, library.Count);
|
||||
Assert.True(library.TryGet("first", out var a));
|
||||
Assert.Equal("\nA\n", a);
|
||||
Assert.True(library.TryGet("second", out var b));
|
||||
Assert.Equal("\nB\n", b);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Parse_NameWithUnderscoreAndDigits_Extracted()
|
||||
{
|
||||
var library = AviUtlPixelShaderLibrary.Parse("--[[pixelshader@dithering_z2:\nX\n]]");
|
||||
Assert.True(library.TryGet("dithering_z2", out _));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Parse_LeadingWhitespace_Extracted()
|
||||
{
|
||||
var library = AviUtlPixelShaderLibrary.Parse(" \t--[[pixelshader@ps:\nX\n]]");
|
||||
Assert.True(library.TryGet("ps", out _));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Parse_MarkerNotAtLineStart_Ignored()
|
||||
{
|
||||
var library = AviUtlPixelShaderLibrary.Parse("local x = 1 --[[pixelshader@ps:\nX\n]]");
|
||||
Assert.Equal(0, library.Count);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Parse_BodyEndsAtFirstDoubleBracket()
|
||||
{
|
||||
var library = AviUtlPixelShaderLibrary.Parse("--[[pixelshader@ps:\nsrc[a[0]]\n]]");
|
||||
Assert.True(library.TryGet("ps", out var hlsl));
|
||||
Assert.Equal("\nsrc[a[0", hlsl);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Parse_UnterminatedBlock_Ignored()
|
||||
{
|
||||
var library = AviUtlPixelShaderLibrary.Parse("--[[pixelshader@ps:\nfloat4 ps() : SV_Target { return 0; }");
|
||||
Assert.Equal(0, library.Count);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Parse_MissingColon_Ignored()
|
||||
{
|
||||
var library = AviUtlPixelShaderLibrary.Parse("--[[pixelshader@ps\nX\n]]");
|
||||
Assert.Equal(0, library.Count);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Parse_EmptyName_Ignored()
|
||||
{
|
||||
var library = AviUtlPixelShaderLibrary.Parse("--[[pixelshader@:\nX\n]]");
|
||||
Assert.Equal(0, library.Count);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Parse_DuplicateName_FirstDefinitionWins()
|
||||
{
|
||||
var library = AviUtlPixelShaderLibrary.Parse("--[[pixelshader@ps:\nA\n]]\n--[[pixelshader@ps:\nB\n]]");
|
||||
Assert.True(library.TryGet("ps", out var hlsl));
|
||||
Assert.Equal("\nA\n", hlsl);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Parse_CrlfSource_Extracted()
|
||||
{
|
||||
var library = AviUtlPixelShaderLibrary.Parse("--[[pixelshader@ps:\r\nX\r\n]]\r\n");
|
||||
Assert.True(library.TryGet("ps", out var hlsl));
|
||||
Assert.Equal("\r\nX\r\n", hlsl);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Parse_InsideSectionBody_Extracted()
|
||||
{
|
||||
var source = "@通常\n--track@a:A,0,100,0\n--[[pixelshader@ps:\nX\n]]\nobj.pixelshader(\"ps\", \"object\", \"object\")";
|
||||
var library = AviUtlPixelShaderLibrary.Parse(source);
|
||||
Assert.True(library.TryGet("ps", out _));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void TryGet_CrossScriptName_ResolvesLocalPart()
|
||||
{
|
||||
var library = AviUtlPixelShaderLibrary.Parse("--[[pixelshader@ps:\nX\n]]");
|
||||
Assert.True(library.TryGet("ps@OtherScript", out var hlsl));
|
||||
Assert.Equal("\nX\n", hlsl);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void TryGet_UnknownOrEmptyName_ReturnsFalse()
|
||||
{
|
||||
var library = AviUtlPixelShaderLibrary.Parse("--[[pixelshader@ps:\nX\n]]");
|
||||
Assert.False(library.TryGet("other", out _));
|
||||
Assert.False(library.TryGet(string.Empty, out _));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void EntryPointOf_StripsScriptSuffix()
|
||||
{
|
||||
Assert.Equal("ps", AviUtlPixelShaderLibrary.EntryPointOf("ps@Script"));
|
||||
Assert.Equal("ps", AviUtlPixelShaderLibrary.EntryPointOf("ps"));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Parse_ComputeShaderBlock_Ignored()
|
||||
{
|
||||
var library = AviUtlPixelShaderLibrary.Parse("--[[computeshader@cs:\nX\n]]");
|
||||
Assert.Equal(0, library.Count);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,31 @@
|
||||
using LuaScript.Compat;
|
||||
|
||||
namespace LuaScript.Tests
|
||||
{
|
||||
public sealed class AviUtlScriptShaderTests
|
||||
{
|
||||
private const string ShaderBlock = "--[[pixelshader@ps:\nTexture2D src : register(t0);\nfloat4 ps(float4 pos : SV_Position) : SV_Target\n{\n float4 c = src[uint2(floor(pos.xy))];\n return (c.a != 0.0 && c.r > 0.5) ? c : float4(0, 0, 0, 0);\n}\n]]";
|
||||
|
||||
[Fact]
|
||||
public void Transform_PreservesShaderBlockVerbatim()
|
||||
{
|
||||
var source = ShaderBlock + "\nobj.pixelshader(\"ps\", \"object\", \"object\")";
|
||||
var transformed = AviUtlScript.Transform(source);
|
||||
|
||||
Assert.Contains(ShaderBlock, transformed.Replace("\r\n", "\n"));
|
||||
var library = AviUtlPixelShaderLibrary.Parse(source);
|
||||
Assert.True(library.TryGet("ps", out var hlsl));
|
||||
Assert.Contains("c.a != 0.0 && c.r > 0.5", hlsl);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Transform_SectionedScript_ShaderStaysInSourceLibrary()
|
||||
{
|
||||
var source = "@main\n--track@a:A,0,100,0\n" + ShaderBlock + "\nobj.pixelshader(\"ps\", \"object\", \"object\")\n@sub\nobj.x = 1";
|
||||
var transformed = AviUtlScript.Transform(source);
|
||||
|
||||
Assert.Contains("obj.pixelshader", transformed);
|
||||
Assert.True(AviUtlPixelShaderLibrary.Parse(source).TryGet("ps", out _));
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -133,5 +133,42 @@ namespace LuaScript.Tests
|
||||
double expectedRand = AviUtlRandom.Next(-100, 100, 3, 2);
|
||||
Assert.Equal(500d * expectedRand / 100d, moved);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void ChangedLines_EmptyWhenNoRewrite()
|
||||
{
|
||||
var (_, _, changed) = AviUtlScript.TransformWithMap("obj.x = 1\nobj.y = 2");
|
||||
Assert.Empty(changed);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void ChangedLines_ReportRewrittenLineInRunnableSpace()
|
||||
{
|
||||
var (_, _, changed) = AviUtlScript.TransformWithMap("obj.x = 1\nobj.y = obj.x != 0\nobj.z = 3");
|
||||
Assert.Equal(new[] { 2 }, changed);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void ChangedLines_AreSortedAndCoverEveryRewrittenLine()
|
||||
{
|
||||
var (_, _, changed) = AviUtlScript.TransformWithMap("a = x != 0\nb = y\nc = z ?? 5\nw++");
|
||||
Assert.Equal(new[] { 1, 3, 4 }, changed);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void ChangedLines_DeduplicateMultipleRewritesOnOneLine()
|
||||
{
|
||||
var (_, _, changed) = AviUtlScript.TransformWithMap("a = x != 0 and y != 1 and z != 2");
|
||||
Assert.Equal(new[] { 1 }, changed);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void ChangedLines_TrackRunnableLineAfterHoistedPrelude()
|
||||
{
|
||||
var (_, _, changed) = AviUtlScript.TransformWithMap("--dialog:V,local v=3;\nresult = v != 0");
|
||||
Assert.NotEmpty(changed);
|
||||
for (int i = 1; i < changed.Length; i++)
|
||||
Assert.True(changed[i] > changed[i - 1]);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -23,6 +23,12 @@ namespace LuaScript.Tests
|
||||
[InlineData("for y=0,obj.h-1 do for x=0,obj.w-1 do local r,g,b,a=obj.getpixel(x,y) obj.setpixel(x,y,r%64,math.abs(g-128),math.sqrt(b*255),a) end end")]
|
||||
[InlineData("local x=99 local k=3 for y=0,obj.h-1 do for x=0,obj.w-1 do local r,g,b,a=obj.getpixel(x,y) obj.setpixel(x,y,x/obj.w*255+k,g,b,a) end end")]
|
||||
[InlineData("for y=0,obj.h-1 do for x=0,obj.w-1 do local r,g,b,a=obj.getpixel(x,y) obj.setpixel(x,y,math.fmod(r,64),math.fmod(g,7)*36,math.fmod(b-128,60)+128,a) end end")]
|
||||
[InlineData("for y=0,obj.h-1 do for x=0,obj.w-1 do local r,g,b,a=obj.getpixel(x,y) if r>128 then r=255 end obj.setpixel(x,y,r,g,b,a) end end")]
|
||||
[InlineData("for y=0,obj.h-1 do for x=0,obj.w-1 do local r,g,b,a=obj.getpixel(x,y) local v=(r+g+b)/3 local o=0 if v>128 then o=255 else o=32 end obj.setpixel(x,y,o,o,o,a) end end")]
|
||||
[InlineData("for y=0,obj.h-1 do for x=0,obj.w-1 do local r,g,b,a=obj.getpixel(x,y) local v=(r+g+b)/3 local o=0 if v>170 then o=255 elseif v>85 then o=128 elseif v>40 then o=64 end obj.setpixel(x,y,o,g,b,a) end end")]
|
||||
[InlineData("for y=0,obj.h-1 do for x=0,obj.w-1 do local r,g,b,a=obj.getpixel(x,y) if r>g then r=g end if b<64 and g>32 then b=g elseif b>192 then b=192 end obj.setpixel(x,y,r,g,b,a) end end")]
|
||||
[InlineData("for y=0,obj.h-1 do for x=0,obj.w-1 do local r,g,b,a=obj.getpixel(x,y) local v=0 if r>128 then local r=g*0.5 v=r+1 if v>100 then v=100 end else v=r end obj.setpixel(x,y,v,g,b,a) end end")]
|
||||
[InlineData("local w=obj.w local h=obj.h for y=0,h-1 do for x=0,w-1 do local r,g,b,a=obj.getpixel(x,y) obj.setpixel(x,y,x/w*255,y/h*255,b,a) end end")]
|
||||
public void CpuKernelMatchesMoonSharp(string script)
|
||||
{
|
||||
var fields = new Dictionary<string, double> { ["w"] = Width, ["h"] = Height };
|
||||
@@ -46,6 +52,9 @@ namespace LuaScript.Tests
|
||||
[InlineData("local pd=obj.getpixeldata() for y=0,pd.height-1 do for x=0,pd.width-1 do local i=(y*pd.width+x)*4 local r=pd:get(i+1) local g=pd:get(i+2) local b=pd:get(i+3) pd:set(i+1,b) pd:set(i+2,g) pd:set(i+3,r) end end")]
|
||||
[InlineData("local pd=obj.getpixeldata() for y=0,obj.h-1 do for x=0,obj.w-1 do local i=(y*obj.w+x)*4 local r=pd:get(i+1) local a=pd:get(i+4) pd:set(i+1,r*a/255) pd:set(i+2,pd:get(i+2)*obj.track0/100) pd:set(i+3,math.min(255,pd:get(i+3)+50)) end end")]
|
||||
[InlineData("local pd=obj.getpixeldata() for y=0,pd.height-1 do for x=0,pd.width-1 do local i=(y*pd.width+x)*4 local r=pd:get(i+1) local g=pd:get(i+2) local b=pd:get(i+3) pd:set(i+1,r*3) pd:set(i+2,g-300) pd:set(i+3,b*2-255) end end")]
|
||||
[InlineData("local pd=obj.getpixeldata() for y=0,pd.height-1 do for x=0,pd.width-1 do local i=(y*pd.width+x)*4 local r=pd:get(i+1) local g=pd:get(i+2) local b=pd:get(i+3) pd:set(i+1,255-r) pd:set(i+2,255-g) pd:set(i+3,255-b) end end obj.putpixeldata(pd)")]
|
||||
[InlineData("local data=obj.getpixeldata() local w=data.width local h=data.height for y=0,h-1 do for x=0,w-1 do local i=(y*w+x)*4 local r=data:get(i+1) local g=data:get(i+2) local b=data:get(i+3) data:set(i+1,g) data:set(i+2,b) data:set(i+3,r) end end obj.putpixeldata(data)")]
|
||||
[InlineData("local pd=obj.getpixeldata() for y=0,pd.height-1 do for x=0,pd.width-1 do local i=(y*pd.width+x)*4 local r=pd:get(i+1) local g=pd:get(i+2) local b=pd:get(i+3) local v=(r+g+b)/3 local o=0 if v>128 then o=255 end pd:set(i+1,o) pd:set(i+2,o) pd:set(i+3,o) end end")]
|
||||
public void GetPixelDataKernelMatchesMoonSharp(string script)
|
||||
{
|
||||
var fields = new Dictionary<string, double> { ["w"] = Width, ["h"] = Height, ["track0"] = 73d };
|
||||
@@ -60,6 +69,9 @@ namespace LuaScript.Tests
|
||||
[InlineData("local pd=obj.getpixeldata() for y=0,pd.height-1 do for x=0,pd.width-1 do local i=(y*pd.width+x)*4 local i=i+4 pd:set(i+1,0) pd:set(i+2,0) pd:set(i+3,0) end end")]
|
||||
[InlineData("local pd=obj.getpixeldata() for y=0,pd.height-1 do for pd=0,pd.width-1 do local i=(y*2+pd)*4 pd:set(i+1,0) pd:set(i+2,0) pd:set(i+3,0) end end")]
|
||||
[InlineData("local pd=obj.getpixeldata() for y=0,pd.height-1 do for x=0,pd.width-1 do local i=(y*pd.width+x)*4 local pd=0 pd:set(i+1,0) end end")]
|
||||
[InlineData("local pd=obj.getpixeldata() for y=0,pd.height-1 do for x=0,pd.width-1 do local i=(y*pd.width+x)*4 local r=pd:get(i+1) if r>128 then pd:set(i+1,255) end pd:set(i+2,0) pd:set(i+3,0) end end")]
|
||||
[InlineData("local pd=obj.getpixeldata() for y=0,pd.height-1 do for x=0,pd.width-1 do local i=(y*pd.width+x)*4 pd:set(i+1,0) pd:set(i+2,0) pd:set(i+3,0) end end obj.putpixeldata(other)")]
|
||||
[InlineData("local pd=obj.getpixeldata() for y=0,pd.height-1 do for x=0,pd.width-1 do local i=(y*pd.width+x)*4 pd:set(i+1,0) pd:set(i+2,0) pd:set(i+3,0) end end obj.putpixeldata(pd) obj.putpixeldata(pd)")]
|
||||
public void GetPixelDataNonKernelScriptsAreRejected(string script)
|
||||
{
|
||||
Assert.Null(KernelExtractor.TryExtract(script));
|
||||
@@ -92,8 +104,12 @@ namespace LuaScript.Tests
|
||||
[InlineData("for y=0,obj.h-1 do for x=0,obj.w-1 do local r,g,b,a=obj.getpixel(x,y) total=total+r obj.setpixel(x,y,r,g,b,a) end end")]
|
||||
[InlineData("for y=0,obj.h-1 do for x=0,obj.w-1 do local r,g,b,a=obj.getpixel(x+1,y) obj.setpixel(x,y,r,g,b,a) end end")]
|
||||
[InlineData("for i=0,10 do end")]
|
||||
[InlineData("for y=0,obj.h-1 do for x=0,obj.w-1 do local r,g,b,a=obj.getpixel(x,y) if r>128 then r=255 end obj.setpixel(x,y,r,g,b,a) end end")]
|
||||
[InlineData("for y=0,obj.h-1 do for x=0,obj.w-1 do local r,g,b,a=obj.getpixel(x,y) obj.setpixel(x,y,obj.rand(0,255),g,b,a) end end")]
|
||||
[InlineData("for y=0,obj.h-1 do for x=0,obj.w-1 do local r,g,b,a=obj.getpixel(x,y) if r>128 then obj.setpixel(x,y,255,g,b,a) end end end")]
|
||||
[InlineData("for y=0,obj.h-1 do for x=0,obj.w-1 do local r,g,b,a=obj.getpixel(x,y) if r then r=255 end obj.setpixel(x,y,r,g,b,a) end end")]
|
||||
[InlineData("for y=0,obj.h-1 do for x=0,obj.w-1 do local r,g,b,a=obj.getpixel(x,y) if r>128 then local y=0 r=y end obj.setpixel(x,y,r,g,b,a) end end")]
|
||||
[InlineData("for y=0,obj.h-1 do for x=0,obj.w-1 do local r,g,b,a=obj.getpixel(x,y) obj.setpixel(x,y,r,g,b,a) end end obj.putpixeldata(pd)")]
|
||||
[InlineData("local w=5 for y=0,obj.h-1 do for x=0,w-1 do local r,g,b,a=obj.getpixel(x,y) obj.setpixel(x,y,r,g,b,a) end end")]
|
||||
public void NonKernelScriptsAreRejected(string script)
|
||||
{
|
||||
Assert.Null(KernelExtractor.TryExtract(script));
|
||||
@@ -178,6 +194,8 @@ namespace LuaScript.Tests
|
||||
return DynValue.NewTable(pd);
|
||||
});
|
||||
|
||||
obj["putpixeldata"] = DynValue.NewCallback((_, _) => DynValue.Void);
|
||||
|
||||
engine.Globals["obj"] = obj;
|
||||
engine.DoString(script);
|
||||
}
|
||||
|
||||
@@ -62,6 +62,18 @@ namespace LuaScript.Tests
|
||||
Assert.Contains($"uniforms[{index / 4}].{"xyzw"[index % 4]}", hlsl);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void ConditionalStatementEmitsTernary()
|
||||
{
|
||||
const string script =
|
||||
"for y=0,obj.h-1 do for x=0,obj.w-1 do local r,g,b,a=obj.getpixel(x,y) " +
|
||||
"local v=(r+g+b)/3 local o=0 if v>170 then o=255 elseif v>85 then o=128 end " +
|
||||
"obj.setpixel(x,y,o,o,o,a) end end";
|
||||
string hlsl = HlslKernelEmitter.Emit(Extract(script));
|
||||
Assert.Contains(" ? (", hlsl);
|
||||
Assert.Contains(" > ", hlsl);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void EmissionIsDeterministic()
|
||||
{
|
||||
|
||||
@@ -24,6 +24,7 @@ namespace LuaScript.Tests
|
||||
[InlineData("for y=0,obj.h-1 do for x=0,obj.w-1 do local r,g,b,a=obj.getpixel(x,y) obj.setpixel(x,y,((r>128 and g<64) or (not (b>200))) and 255 or 0,g,b,a) end end")]
|
||||
[InlineData("for y=0,obj.h-1 do for x=0,obj.w-1 do local r,g,b,a=obj.getpixel(x,y) obj.setpixel(x,y,(r>=200) and 255 or 0,(g<=50) and 255 or 0,(b==0) and 255 or ((b~=0) and 100 or 0),a) end end")]
|
||||
[InlineData("local pd=obj.getpixeldata() for y=0,pd.height-1 do for x=0,pd.width-1 do local i=(y*pd.width+x)*4 local r=pd:get(i+1) local g=pd:get(i+2) local b=pd:get(i+3) pd:set(i+1,r*3) pd:set(i+2,g-300) pd:set(i+3,b*2-255) end end")]
|
||||
[InlineData("for y=0,obj.h-1 do for x=0,obj.w-1 do local r,g,b,a=obj.getpixel(x,y) local v=(r+g+b)/3 local o=0 if v>170 then o=255 elseif v>85 then o=128 else o=r end obj.setpixel(x,y,o,o,o,a) end end")]
|
||||
public void SimdBlockMatchesScalarRow(string script)
|
||||
{
|
||||
var program = KernelExtractor.TryExtract(script);
|
||||
|
||||
@@ -47,6 +47,7 @@ namespace LuaScript.Tests
|
||||
"obj.getobject", "obj.getpixel", "obj.setpixel",
|
||||
"obj.getpixeldata", "obj.putpixeldata", "obj.rand", "obj.load",
|
||||
"obj.setfont", "obj.draw", "obj.drawpoly", "obj.copybuffer",
|
||||
"obj.pixelshader",
|
||||
"obj.getvalue", "obj.setoption", "obj.getoption", "obj.pixeloption",
|
||||
"obj.setanchor", "obj.effect", "obj.getinfo"
|
||||
]),
|
||||
|
||||
@@ -0,0 +1,582 @@
|
||||
using LuaScript.Compat;
|
||||
using MoonSharp.Interpreter;
|
||||
|
||||
namespace LuaScript.Tests
|
||||
{
|
||||
public class LuaSyntaxExtensionsTests
|
||||
{
|
||||
private static string Rewrite(string source) => LuaSyntaxExtensions.Rewrite(source);
|
||||
|
||||
private static DynValue Eval(string source)
|
||||
{
|
||||
var script = new Script(CoreModules.Preset_SoftSandbox);
|
||||
script.DoString(AviUtlScript.Transform(source));
|
||||
return script.Globals.Get("result");
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[InlineData("a is not b", "a ~= b")]
|
||||
[InlineData("if x is not nil then end", "if x ~= nil then end")]
|
||||
[InlineData("a is not b", "a ~= b")]
|
||||
[InlineData("a is\tnot b", "a ~= b")]
|
||||
[InlineData("a is\t not b", "a ~= b")]
|
||||
[InlineData("a is not b and c is not d", "a ~= b and c ~= d")]
|
||||
[InlineData("f() is not nil", "f() ~= nil")]
|
||||
public void IsNot_RewritesToNotEqual(string source, string expected)
|
||||
{
|
||||
Assert.Equal(expected, Rewrite(source));
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[InlineData("a is b", "a == b")]
|
||||
[InlineData("x = a is b", "x = a == b")]
|
||||
[InlineData("if a is b then end", "if a == b then end")]
|
||||
[InlineData("a is nothing", "a == nothing")]
|
||||
[InlineData("f() is g()", "f() == g()")]
|
||||
public void Is_RewritesToEqual(string source, string expected)
|
||||
{
|
||||
Assert.Equal(expected, Rewrite(source));
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[InlineData("local is = 1\nx = is + 1")]
|
||||
[InlineData("is = 1")]
|
||||
[InlineData("obj.is = 1")]
|
||||
[InlineData("return is")]
|
||||
[InlineData("f(is)")]
|
||||
[InlineData("x = is")]
|
||||
[InlineData("print(x)\nis(y)")]
|
||||
[InlineData("island")]
|
||||
[InlineData("basis not x")]
|
||||
[InlineData("a isnot b")]
|
||||
public void Is_DoesNotClobberIdentifier(string source)
|
||||
{
|
||||
Assert.Equal(source, Rewrite(source));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Newline_BetweenIsAndNot_IsNotAnOperator()
|
||||
{
|
||||
const string source = "a is\nnot b";
|
||||
Assert.Equal(source, Rewrite(source));
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[InlineData("a.is not b")]
|
||||
[InlineData("a:is not b")]
|
||||
public void MemberAccess_IsNotRewritten(string source)
|
||||
{
|
||||
Assert.Equal(source, Rewrite(source));
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[InlineData("a != b", "a ~= b")]
|
||||
[InlineData("x = a != b", "x = a ~= b")]
|
||||
public void NotEqual_RewritesToTildeEqual(string source, string expected)
|
||||
{
|
||||
Assert.Equal(expected, Rewrite(source));
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[InlineData("x = !y", "x = not y")]
|
||||
[InlineData("!flag", "not flag")]
|
||||
[InlineData("a = !b and !c", "a = not b and not c")]
|
||||
public void Bang_RewritesToNot(string source, string expected)
|
||||
{
|
||||
Assert.Equal(expected, Rewrite(source));
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[InlineData("a && b", "a and b")]
|
||||
[InlineData("a&&b", "a and b")]
|
||||
[InlineData("a || b", "a or b")]
|
||||
[InlineData("a||b", "a or b")]
|
||||
[InlineData("a && b || c", "a and b or c")]
|
||||
public void LogicalAliases_Rewrite(string source, string expected)
|
||||
{
|
||||
Assert.Equal(expected, Rewrite(source));
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[InlineData("x += 1", "x = x + (1)")]
|
||||
[InlineData("x -= 1", "x = x - (1)")]
|
||||
[InlineData("x *= 2", "x = x * (2)")]
|
||||
[InlineData("x /= 2", "x = x / (2)")]
|
||||
[InlineData("x %= 2", "x = x % (2)")]
|
||||
[InlineData("x ^= 2", "x = x ^ (2)")]
|
||||
[InlineData("s ..= \"b\"", "s = s .. (\"b\")")]
|
||||
[InlineData("x ||= y", "x = x or (y)")]
|
||||
[InlineData("x &&= y", "x = x and (y)")]
|
||||
[InlineData("x *= a + b", "x = x * (a + b)")]
|
||||
[InlineData("t[i] += 1", "t[i] = t[i] + (1)")]
|
||||
[InlineData("obj.count += 1", "obj.count = obj.count + (1)")]
|
||||
[InlineData("x += f(a, b)", "x = x + (f(a, b))")]
|
||||
public void AugmentedAssignment_Rewrites(string source, string expected)
|
||||
{
|
||||
Assert.Equal(expected, Rewrite(source));
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[InlineData("x ??= y", "if x == nil then x = (y) end")]
|
||||
[InlineData("obj.field ??= 5", "if obj.field == nil then obj.field = (5) end")]
|
||||
[InlineData(" x ??= y", " if x == nil then x = (y) end")]
|
||||
public void NilCoalesceAssignment_Rewrites(string source, string expected)
|
||||
{
|
||||
Assert.Equal(expected, Rewrite(source));
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[InlineData("i++", "i = i + 1")]
|
||||
[InlineData("count ++", "count = count + 1")]
|
||||
[InlineData("t[k]++", "t[k] = t[k] + 1")]
|
||||
public void Increment_Rewrites(string source, string expected)
|
||||
{
|
||||
Assert.Equal(expected, Rewrite(source));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void NilCoalesce_LowersToInlineFunction()
|
||||
{
|
||||
Assert.Equal(
|
||||
"x = (function() local __lc0 = (a) if __lc0 ~= nil then return __lc0 else return (b) end end)()",
|
||||
Rewrite("x = a ?? b"));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void NilCoalesce_CapturesFullOrOperand()
|
||||
{
|
||||
Assert.Equal(
|
||||
"x = (function() local __lc0 = (foo(a)) if __lc0 ~= nil then return __lc0 else return (b) end end)()",
|
||||
Rewrite("x = foo(a) ?? b"));
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[InlineData("for i in <0..10> do end", "for i = 0, 10 do end")]
|
||||
[InlineData("for i in <0..<10> do end", "for i = 0, (10) - 1 do end")]
|
||||
[InlineData("for i in <0..10, 2> do end", "for i = 0, 10, 2 do end")]
|
||||
[InlineData("for i in <0..<10, 2> do end", "for i = 0, (10) - 1, 2 do end")]
|
||||
[InlineData("for i in <a..b> do end", "for i = a, b do end")]
|
||||
public void NumericRange_Rewrites(string source, string expected)
|
||||
{
|
||||
Assert.Equal(expected, Rewrite(source));
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[InlineData("for k, v in pairs(t) do end")]
|
||||
[InlineData("for i, x in ipairs(list) do end")]
|
||||
[InlineData("for i in <0> do end")]
|
||||
public void NumericRange_DoesNotTouchGenericFor(string source)
|
||||
{
|
||||
Assert.Equal(source, Rewrite(source));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Comment_ContentIsPreserved()
|
||||
{
|
||||
const string source = "-- a is not b\nx = 1";
|
||||
Assert.Equal(source, Rewrite(source));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void LongComment_ContentIsPreserved()
|
||||
{
|
||||
const string source = "--[[ a is not b ]]\nx = 1";
|
||||
Assert.Equal(source, Rewrite(source));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void ShortString_ContentIsPreserved()
|
||||
{
|
||||
const string source = "x = \"a is not b ?? c += 1\"";
|
||||
Assert.Equal(source, Rewrite(source));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void LongString_ContentIsPreserved()
|
||||
{
|
||||
const string source = "x = [==[ a is not b ]==]";
|
||||
Assert.Equal(source, Rewrite(source));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void RewrittenCode_PreservesLineCount()
|
||||
{
|
||||
const string source = "a = 1\nb = a is not 2\nc = 3";
|
||||
string rewritten = Rewrite(source);
|
||||
Assert.Equal(source.Split('\n').Length, rewritten.Split('\n').Length);
|
||||
Assert.Contains("b = a ~= 2", rewritten);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void NoTrigger_ReturnsSameReference()
|
||||
{
|
||||
const string source = "obj.x = 1\nobj.y = 2";
|
||||
Assert.Same(source, Rewrite(source));
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[InlineData("", "")]
|
||||
public void Empty_IsUnchanged(string source, string expected)
|
||||
{
|
||||
Assert.Equal(expected, Rewrite(source));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Is_EvaluatesEquality()
|
||||
{
|
||||
Assert.True(Eval("result = (1 is 1)").Boolean);
|
||||
Assert.False(Eval("result = (1 is 2)").Boolean);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void IsNot_EvaluatesInequality()
|
||||
{
|
||||
Assert.True(Eval("result = (1 is not 2)").Boolean);
|
||||
Assert.False(Eval("result = (2 is not 2)").Boolean);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void NotEqual_Evaluates()
|
||||
{
|
||||
Assert.True(Eval("result = (1 != 2)").Boolean);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Bang_Evaluates()
|
||||
{
|
||||
Assert.True(Eval("result = (!false)").Boolean);
|
||||
Assert.False(Eval("result = (!true)").Boolean);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void LogicalAliases_Evaluate()
|
||||
{
|
||||
Assert.False(Eval("result = (true && false)").Boolean);
|
||||
Assert.Equal(4d, Eval("result = (false || 4)").Number);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void NilCoalesce_FallsBackOnlyOnNil()
|
||||
{
|
||||
Assert.Equal(7d, Eval("result = nil ?? 7").Number);
|
||||
Assert.Equal(3d, Eval("result = 3 ?? 7").Number);
|
||||
var falseResult = Eval("result = false ?? 7");
|
||||
Assert.Equal(DataType.Boolean, falseResult.Type);
|
||||
Assert.False(falseResult.Boolean);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void NilCoalesce_EvaluatesLeftOnce()
|
||||
{
|
||||
const string source = "calls = 0\nfunction f() calls = calls + 1 return 42 end\nresult = f() ?? 0\nassert(calls == 1)";
|
||||
var script = new Script(CoreModules.Preset_SoftSandbox);
|
||||
script.DoString(AviUtlScript.Transform(source));
|
||||
Assert.Equal(42d, script.Globals.Get("result").Number);
|
||||
Assert.Equal(1d, script.Globals.Get("calls").Number);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void NilCoalesceAssignment_Evaluates()
|
||||
{
|
||||
Assert.Equal(9d, Eval("x = nil\nx ??= 9\nresult = x").Number);
|
||||
Assert.Equal(4d, Eval("x = 4\nx ??= 9\nresult = x").Number);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void AugmentedAssignment_Evaluates()
|
||||
{
|
||||
Assert.Equal(8d, Eval("x = 5\nx += 3\nresult = x").Number);
|
||||
Assert.Equal(2d, Eval("x = 5\nx -= 3\nresult = x").Number);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void AugmentedAssignment_PreservesPrecedence()
|
||||
{
|
||||
Assert.Equal(14d, Eval("a = 5\nb = 2\nx = 2\nx *= a + b\nresult = x").Number);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void ConcatAssignment_Evaluates()
|
||||
{
|
||||
Assert.Equal("ab", Eval("s = \"a\"\ns ..= \"b\"\nresult = s").String);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void LogicalAssignment_Evaluates()
|
||||
{
|
||||
Assert.Equal(10d, Eval("x = false\nx ||= 10\nresult = x").Number);
|
||||
Assert.Equal(2d, Eval("x = 2\nx ||= 10\nresult = x").Number);
|
||||
Assert.Equal(5d, Eval("x = 1\nx &&= 5\nresult = x").Number);
|
||||
Assert.False(Eval("x = false\nx &&= 5\nresult = x").Boolean);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Increment_Evaluates()
|
||||
{
|
||||
Assert.Equal(2d, Eval("x = 1\nx++\nresult = x").Number);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void NumericRange_InclusiveEvaluates()
|
||||
{
|
||||
Assert.Equal(6d, Eval("s = 0\nfor i in <1..3> do s = s + i end\nresult = s").Number);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void NumericRange_ExclusiveEvaluates()
|
||||
{
|
||||
Assert.Equal(6d, Eval("s = 0\nfor i in <1..<4> do s = s + i end\nresult = s").Number);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void NumericRange_SteppedEvaluates()
|
||||
{
|
||||
Assert.Equal(30d, Eval("s = 0\nfor i in <0..10, 2> do s = s + i end\nresult = s").Number);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Ternary_Rewrites()
|
||||
{
|
||||
Assert.Equal(
|
||||
"x = (function() if c then return (1) else return (2) end end)()",
|
||||
Rewrite("x = c ? 1 : 2"));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Ternary_Evaluates()
|
||||
{
|
||||
Assert.Equal(1d, Eval("result = true ? 1 : 2").Number);
|
||||
Assert.Equal(2d, Eval("result = false ? 1 : 2").Number);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Ternary_ReturnsFalsyBranch()
|
||||
{
|
||||
var value = Eval("result = true ? false : 1");
|
||||
Assert.Equal(DataType.Boolean, value.Type);
|
||||
Assert.False(value.Boolean);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Ternary_InsideCallArgument()
|
||||
{
|
||||
Assert.Equal(3d, Eval("function f(v, w) return v + w end\nresult = f(true ? 1 : 2, 2)").Number);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Ternary_NestedInElse()
|
||||
{
|
||||
Assert.Equal(3d, Eval("a = 3\nresult = a == 1 ? 1 : a == 2 ? 2 : 3").Number);
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[InlineData("x = a and b or c")]
|
||||
[InlineData("t = { x = 1, y = 2 }")]
|
||||
[InlineData("obj:draw()")]
|
||||
[InlineData("::label::")]
|
||||
public void Ternary_DoesNotTouchOtherCode(string source)
|
||||
{
|
||||
Assert.Equal(source, Rewrite(source));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void SafeNavigation_ReturnsNilForNilTarget()
|
||||
{
|
||||
Assert.True(Eval("t = nil\nresult = t?.x == nil").Boolean);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void SafeNavigation_ReadsMember()
|
||||
{
|
||||
Assert.Equal(5d, Eval("t = { x = 5 }\nresult = t?.x").Number);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void SafeNavigation_Chains()
|
||||
{
|
||||
Assert.True(Eval("t = { a = nil }\nresult = t?.a?.b == nil").Boolean);
|
||||
Assert.Equal(7d, Eval("t = { a = { b = 7 } }\nresult = t?.a?.b").Number);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void SafeNavigation_Index()
|
||||
{
|
||||
Assert.True(Eval("t = nil\nresult = t?[1] == nil").Boolean);
|
||||
Assert.Equal(9d, Eval("t = { 9 }\nresult = t?[1]").Number);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void SafeNavigation_EvaluatesTargetOnce()
|
||||
{
|
||||
const string source = "calls = 0\nfunction f() calls = calls + 1 return { x = 3 } end\nresult = f()?.x";
|
||||
var script = new Script(CoreModules.Preset_SoftSandbox);
|
||||
script.DoString(AviUtlScript.Transform(source));
|
||||
Assert.Equal(3d, script.Globals.Get("result").Number);
|
||||
Assert.Equal(1d, script.Globals.Get("calls").Number);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void SafeNavigation_CombinesWithNilCoalesce()
|
||||
{
|
||||
Assert.Equal(4d, Eval("t = nil\nresult = t?.x ?? 4").Number);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Lambda_Rewrites()
|
||||
{
|
||||
Assert.Equal(
|
||||
"f = (function(a, b) return a + b end)",
|
||||
Rewrite("f = (a, b) => a + b"));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Lambda_SingleParameterWithoutParens()
|
||||
{
|
||||
Assert.Equal(9d, Eval("f = x => x * 3\nresult = f(3)").Number);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Lambda_NoParameters()
|
||||
{
|
||||
Assert.Equal(1d, Eval("f = () => 1\nresult = f()").Number);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Lambda_AsSortComparer()
|
||||
{
|
||||
const string source = "t = { 3, 1, 2 }\ntable.sort(t, (a, b) => a < b)\nresult = t[1]";
|
||||
Assert.Equal(1d, Eval(source).Number);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Lambda_DoesNotTouchComparisons()
|
||||
{
|
||||
Assert.Equal("x = a >= b", Rewrite("x = a >= b"));
|
||||
Assert.Equal("x = a <= b", Rewrite("x = a <= b"));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void InterpolatedString_Rewrites()
|
||||
{
|
||||
Assert.Equal(
|
||||
"s = (\"x=\" .. tostring(a))",
|
||||
Rewrite("s = `x={a}`"));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void InterpolatedString_Evaluates()
|
||||
{
|
||||
Assert.Equal("x=5 y=6", Eval("a = 5\nb = 6\nresult = `x={a} y={b}`").String);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void InterpolatedString_PlainLiteral()
|
||||
{
|
||||
Assert.Equal("hello", Eval("result = `hello`").String);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void InterpolatedString_ExpressionOnly()
|
||||
{
|
||||
Assert.Equal("7", Eval("result = `{3 + 4}`").String);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void InterpolatedString_NestedExtensionSyntax()
|
||||
{
|
||||
Assert.Equal("4", Eval("t = nil\nresult = `{t ?? 4}`").String);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void InterpolatedString_Empty()
|
||||
{
|
||||
Assert.Equal("", Eval("result = ``").String);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Backtick_InsideStringOrComment_IsPreserved()
|
||||
{
|
||||
const string source = "x = \"a ` b\"";
|
||||
Assert.Equal(source, Rewrite(source));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Pipe_Rewrites()
|
||||
{
|
||||
Assert.Equal("x = f((v))", Rewrite("x = v |> f"));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Pipe_Evaluates()
|
||||
{
|
||||
Assert.Equal(4d, Eval("function double(v) return v * 2 end\nresult = 2 |> double").Number);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Pipe_InsertsAsFirstArgument()
|
||||
{
|
||||
Assert.Equal(
|
||||
"x = clamp((v), 0, 255)",
|
||||
Rewrite("x = v |> clamp(0, 255)"));
|
||||
Assert.Equal(5d, Eval("function clamp(v, lo, hi) return math.min(math.max(v, lo), hi) end\nresult = 5 |> clamp(0, 255)").Number);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Pipe_Chains()
|
||||
{
|
||||
const string source = "function inc(v) return v + 1 end\nfunction double(v) return v * 2 end\nresult = 3 |> inc |> double";
|
||||
Assert.Equal(8d, Eval(source).Number);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Pipe_MemberFunction()
|
||||
{
|
||||
Assert.Equal(2d, Eval("result = 2.9 |> math.floor").Number);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void RangeMembership_Rewrites()
|
||||
{
|
||||
Assert.Equal(
|
||||
"x = (function() local __lc0 = (v) return __lc0 >= (1) and __lc0 <= (5) end)()",
|
||||
Rewrite("x = v in <1..5>"));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void RangeMembership_Evaluates()
|
||||
{
|
||||
Assert.True(Eval("result = 3 in <1..5>").Boolean);
|
||||
Assert.True(Eval("result = 5 in <1..5>").Boolean);
|
||||
Assert.False(Eval("result = 6 in <1..5>").Boolean);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void RangeMembership_ExclusiveEvaluates()
|
||||
{
|
||||
Assert.False(Eval("result = 5 in <1..<5>").Boolean);
|
||||
Assert.True(Eval("result = 4 in <1..<5>").Boolean);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void RangeMembership_InsideIf()
|
||||
{
|
||||
Assert.Equal(1d, Eval("v = 40\nresult = 0\nif v in <30..60> then result = 1 end").Number);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void RangeMembership_EvaluatesLeftOnce()
|
||||
{
|
||||
const string source = "calls = 0\nfunction f() calls = calls + 1 return 3 end\nresult = f() in <1..5>";
|
||||
var script = new Script(CoreModules.Preset_SoftSandbox);
|
||||
script.DoString(AviUtlScript.Transform(source));
|
||||
Assert.True(script.Globals.Get("result").Boolean);
|
||||
Assert.Equal(1d, script.Globals.Get("calls").Number);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void RangeMembership_DoesNotTouchForHeaders()
|
||||
{
|
||||
Assert.Equal("for i = 0, 10 do end", Rewrite("for i in <0..10> do end"));
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,5 +1,6 @@
|
||||
using System;
|
||||
using System.IO;
|
||||
using LuaScript.Compat;
|
||||
using LuaScript.Engine;
|
||||
|
||||
namespace LuaScript.Tests
|
||||
@@ -23,6 +24,7 @@ namespace LuaScript.Tests
|
||||
|
||||
private Func<string, SceneValue> _sceneGet = _ => SceneValue.Nil;
|
||||
private Action<string, SceneValue> _sceneSet = (_, _) => { };
|
||||
private PixelShaderInvoke? _runPixelShader;
|
||||
|
||||
public void Dispose() => _worker.Dispose();
|
||||
|
||||
@@ -70,6 +72,7 @@ namespace LuaScript.Tests
|
||||
width, height, timeoutMs,
|
||||
resolveObject, loadFigure, loadText, loadImage, loadMovie, addEffect, addDraw, setAnchor,
|
||||
_sceneGet, _sceneSet,
|
||||
_runPixelShader,
|
||||
out pixelsDirty, out bufferReplaced, out resultWidth, out resultHeight, out error);
|
||||
|
||||
resultPixels = null;
|
||||
@@ -105,6 +108,7 @@ namespace LuaScript.Tests
|
||||
},
|
||||
w, h, 5000, NoResolver, NoLoadFigure, NoLoadText, NoLoadImage, NoLoadMovie, NoAddEffect, NoAddDraw, NoSetAnchor,
|
||||
_sceneGet, _sceneSet,
|
||||
_runPixelShader,
|
||||
out _, out _, out _, out _, out string? error);
|
||||
|
||||
Assert.True(ok, error);
|
||||
@@ -151,6 +155,25 @@ namespace LuaScript.Tests
|
||||
Assert.Equal(System.Text.Encoding.UTF8.GetByteCount("C:/サンプル/画像.png"), fields[NativeProtocol.Alpha]);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void IsNotOperator_RunsAfterTransform()
|
||||
{
|
||||
Assert.True(LuaJitWorker.IsAvailable(NativeDir), "native/luajit.exe must be present");
|
||||
|
||||
var fields = Fields(2, 2, 0d);
|
||||
var pixels = new byte[16];
|
||||
|
||||
string script = AviUtlScript.Transform("obj.x = (1 is not 2) and 7 or 0\nobj.y = (2 is not 2) and 7 or 0");
|
||||
|
||||
bool ok = RunWorker(
|
||||
script,
|
||||
fields, NoStringParams, () => pixels, 2, 2, 5000, NoResolver, NoLoadFigure, NoLoadText, NoLoadImage, NoLoadMovie, NoAddEffect, NoAddDraw, NoSetAnchor, out _, out _, out _, out _, out _, out string? error);
|
||||
|
||||
Assert.True(ok, error);
|
||||
Assert.Equal(7d, fields[NativeProtocol.X]);
|
||||
Assert.Equal(0d, fields[NativeProtocol.Y]);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void GetInfo_ExposesEnvironmentInfo()
|
||||
{
|
||||
@@ -1410,6 +1433,164 @@ namespace LuaScript.Tests
|
||||
Assert.Equal(Compat.AviUtlGlobalFunctions.RgbInterpolate(0, 0, 0, 100, 200, 40, 0.25), fields[NativeProtocol.X]);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void PixelShader_RoundTrip_StagesResourcesAndWritesTarget()
|
||||
{
|
||||
Assert.True(LuaJitWorker.IsAvailable(NativeDir), "native/luajit.exe must be present");
|
||||
|
||||
var pixels = new byte[16];
|
||||
for (int i = 0; i < pixels.Length; i++)
|
||||
pixels[i] = (byte)(i + 1);
|
||||
var original = (byte[])pixels.Clone();
|
||||
var fields = Fields(2, 2, 0d);
|
||||
|
||||
string? observedName = null;
|
||||
PixelShaderInput[] observedResources = [];
|
||||
float[] observedConstants = [];
|
||||
PixelShaderBlend observedBlend = default;
|
||||
PixelShaderSampler observedSampler = default;
|
||||
int observedWidth = 0;
|
||||
int observedHeight = 0;
|
||||
_runPixelShader = (string name, ReadOnlySpan<PixelShaderInput> resources, ReadOnlySpan<float> constants, PixelShaderBlend blend, PixelShaderSampler sampler, byte[] target, int targetWidth, int targetHeight, out string? shaderError) =>
|
||||
{
|
||||
observedName = name;
|
||||
observedResources = resources.ToArray();
|
||||
observedConstants = constants.ToArray();
|
||||
observedBlend = blend;
|
||||
observedSampler = sampler;
|
||||
observedWidth = targetWidth;
|
||||
observedHeight = targetHeight;
|
||||
for (int i = 0; i < targetWidth * targetHeight * 4; i++)
|
||||
target[i] = 0x5A;
|
||||
shaderError = null;
|
||||
return PixelShaderRunStatus.Success;
|
||||
};
|
||||
|
||||
bool ok = RunWorker(
|
||||
"obj.pixelshader(\"ps\", \"object\", {\"object\", \"random\"}, {1, 2.5}, 25, \"clamp\")",
|
||||
fields, NoStringParams, () => pixels, 2, 2, 5000, NoResolver, NoLoadFigure, NoLoadText, NoLoadImage, NoLoadMovie, NoAddEffect, NoAddDraw, NoSetAnchor, out bool dirty, out _, out byte[]? resultPixels, out _, out _, out string? error);
|
||||
|
||||
Assert.True(ok, error);
|
||||
Assert.True(dirty);
|
||||
Assert.Equal("ps", observedName);
|
||||
Assert.Equal(2, observedResources.Length);
|
||||
Assert.False(observedResources[0].IsRandom);
|
||||
Assert.Equal(2, observedResources[0].Width);
|
||||
Assert.Equal(2, observedResources[0].Height);
|
||||
Assert.Equal(original, observedResources[0].Data!.AsSpan(0, 16).ToArray());
|
||||
Assert.True(observedResources[1].IsRandom);
|
||||
Assert.Equal([1f, 2.5f], observedConstants);
|
||||
Assert.Equal(PixelShaderBlend.Composite(25d), observedBlend);
|
||||
Assert.Equal(PixelShaderSampler.Clamp, observedSampler);
|
||||
Assert.Equal(2, observedWidth);
|
||||
Assert.Equal(2, observedHeight);
|
||||
Assert.NotNull(resultPixels);
|
||||
Assert.All(resultPixels.AsSpan(0, 16).ToArray(), static b => Assert.Equal(0x5A, b));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void PixelShader_TempBufferTarget_RoundTripsThroughCopyBuffer()
|
||||
{
|
||||
Assert.True(LuaJitWorker.IsAvailable(NativeDir), "native/luajit.exe must be present");
|
||||
|
||||
var pixels = new byte[16];
|
||||
var fields = Fields(2, 2, 0d);
|
||||
|
||||
_runPixelShader = (string name, ReadOnlySpan<PixelShaderInput> resources, ReadOnlySpan<float> constants, PixelShaderBlend blend, PixelShaderSampler sampler, byte[] target, int targetWidth, int targetHeight, out string? shaderError) =>
|
||||
{
|
||||
for (int i = 0; i < targetWidth * targetHeight * 4; i++)
|
||||
target[i] = 0x33;
|
||||
shaderError = null;
|
||||
return PixelShaderRunStatus.Success;
|
||||
};
|
||||
|
||||
bool ok = RunWorker(
|
||||
"obj.pixelshader(\"ps\", \"tempbuffer\", \"object\")\nobj.copybuffer(\"obj\", \"tmp\")",
|
||||
fields, NoStringParams, () => pixels, 2, 2, 5000, NoResolver, NoLoadFigure, NoLoadText, NoLoadImage, NoLoadMovie, NoAddEffect, NoAddDraw, NoSetAnchor, out bool dirty, out _, out byte[]? resultPixels, out _, out _, out string? error);
|
||||
|
||||
Assert.True(ok, error);
|
||||
Assert.True(dirty);
|
||||
Assert.NotNull(resultPixels);
|
||||
Assert.All(resultPixels.AsSpan(0, 16).ToArray(), static b => Assert.Equal(0x33, b));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void PixelShader_FramebufferTarget_ReplacesObjectWithSceneSize()
|
||||
{
|
||||
Assert.True(LuaJitWorker.IsAvailable(NativeDir), "native/luajit.exe must be present");
|
||||
|
||||
var pixels = new byte[16];
|
||||
var fields = Fields(2, 2, 0d);
|
||||
fields[NativeProtocol.SceneWidth] = 4;
|
||||
fields[NativeProtocol.SceneHeight] = 3;
|
||||
|
||||
int observedWidth = 0;
|
||||
int observedHeight = 0;
|
||||
_runPixelShader = (string name, ReadOnlySpan<PixelShaderInput> resources, ReadOnlySpan<float> constants, PixelShaderBlend blend, PixelShaderSampler sampler, byte[] target, int targetWidth, int targetHeight, out string? shaderError) =>
|
||||
{
|
||||
observedWidth = targetWidth;
|
||||
observedHeight = targetHeight;
|
||||
for (int i = 0; i < targetWidth * targetHeight * 4; i++)
|
||||
target[i] = 0x77;
|
||||
shaderError = null;
|
||||
return PixelShaderRunStatus.Success;
|
||||
};
|
||||
|
||||
bool ok = RunWorker(
|
||||
"obj.pixelshader(\"ps\", \"framebuffer\", \"object\")",
|
||||
fields, NoStringParams, () => pixels, 2, 2, 5000, NoResolver, NoLoadFigure, NoLoadText, NoLoadImage, NoLoadMovie, NoAddEffect, NoAddDraw, NoSetAnchor, out bool dirty, out bool replaced, out byte[]? resultPixels, out int resultW, out int resultH, out string? error);
|
||||
|
||||
Assert.True(ok, error);
|
||||
Assert.True(dirty);
|
||||
Assert.True(replaced);
|
||||
Assert.Equal(4, observedWidth);
|
||||
Assert.Equal(3, observedHeight);
|
||||
Assert.Equal(4, resultW);
|
||||
Assert.Equal(3, resultH);
|
||||
Assert.NotNull(resultPixels);
|
||||
Assert.All(resultPixels.AsSpan(0, 48).ToArray(), static b => Assert.Equal(0x77, b));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void PixelShader_CompileError_IsReportedToScript()
|
||||
{
|
||||
Assert.True(LuaJitWorker.IsAvailable(NativeDir), "native/luajit.exe must be present");
|
||||
|
||||
var pixels = new byte[16];
|
||||
var fields = Fields(2, 2, 0d);
|
||||
|
||||
_runPixelShader = (string name, ReadOnlySpan<PixelShaderInput> resources, ReadOnlySpan<float> constants, PixelShaderBlend blend, PixelShaderSampler sampler, byte[] target, int targetWidth, int targetHeight, out string? shaderError) =>
|
||||
{
|
||||
shaderError = "obj.pixelshader: shader 'ps' failed to compile.\nerror X3000: syntax error";
|
||||
return PixelShaderRunStatus.CompileError;
|
||||
};
|
||||
|
||||
bool ok = RunWorker(
|
||||
"obj.pixelshader(\"ps\", \"object\", \"object\")",
|
||||
fields, NoStringParams, () => pixels, 2, 2, 5000, NoResolver, NoLoadFigure, NoLoadText, NoLoadImage, NoLoadMovie, NoAddEffect, NoAddDraw, NoSetAnchor, out _, out _, out _, out _, out _, out string? error);
|
||||
|
||||
Assert.False(ok);
|
||||
Assert.Contains("X3000", error);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void PixelShader_WithoutHost_IsSilentlySkipped()
|
||||
{
|
||||
Assert.True(LuaJitWorker.IsAvailable(NativeDir), "native/luajit.exe must be present");
|
||||
|
||||
var pixels = new byte[16];
|
||||
var fields = Fields(2, 2, 0d);
|
||||
_runPixelShader = null;
|
||||
|
||||
bool ok = RunWorker(
|
||||
"obj.pixelshader(\"ps\", \"object\", \"object\")\nobj.x = 12",
|
||||
fields, NoStringParams, () => pixels, 2, 2, 5000, NoResolver, NoLoadFigure, NoLoadText, NoLoadImage, NoLoadMovie, NoAddEffect, NoAddDraw, NoSetAnchor, out bool dirty, out _, out _, out _, out _, out string? error);
|
||||
|
||||
Assert.True(ok, error);
|
||||
Assert.False(dirty);
|
||||
Assert.Equal(12d, fields[NativeProtocol.X]);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void RuntimeError_IsReported_AndWorkerSurvives()
|
||||
{
|
||||
|
||||
@@ -0,0 +1,356 @@
|
||||
using LuaScript.Compat;
|
||||
|
||||
namespace LuaScript.Tests
|
||||
{
|
||||
public sealed class PixelShaderMoonSharpTests
|
||||
{
|
||||
private const string ShaderSource = "--[[pixelshader@ps:\nfloat4 ps(float4 pos : SV_Position) : SV_Target { return 0; }\n]]";
|
||||
|
||||
private sealed class StubMediaLoader : IMediaSourceLoader
|
||||
{
|
||||
public byte[] RenderText(string text, string fontFamily, double fontSize, bool bold, bool italic, int colorRgb, out int width, out int height)
|
||||
{
|
||||
width = 1;
|
||||
height = 1;
|
||||
return new byte[4];
|
||||
}
|
||||
|
||||
public byte[] DecodeImage(string path, out int width, out int height)
|
||||
{
|
||||
width = 1;
|
||||
height = 1;
|
||||
return new byte[4];
|
||||
}
|
||||
|
||||
public byte[] DecodeMovie(string path, double time, out int width, out int height)
|
||||
{
|
||||
width = 1;
|
||||
height = 1;
|
||||
return new byte[4];
|
||||
}
|
||||
|
||||
public void Dispose() { }
|
||||
}
|
||||
|
||||
private sealed class RecordingRunner : IPixelShaderRunner
|
||||
{
|
||||
public PixelShaderRunStatus Result = PixelShaderRunStatus.Success;
|
||||
public string? Error;
|
||||
public int CallCount;
|
||||
public string? Hlsl;
|
||||
public string? EntryPoint;
|
||||
public PixelShaderInput[] Resources = [];
|
||||
public float[] Constants = [];
|
||||
public PixelShaderBlend Blend;
|
||||
public PixelShaderSampler Sampler;
|
||||
public byte[]? Target;
|
||||
public int TargetWidth;
|
||||
public int TargetHeight;
|
||||
|
||||
public PixelShaderRunStatus TryRun(
|
||||
string hlsl,
|
||||
string entryPoint,
|
||||
ReadOnlySpan<PixelShaderInput> resources,
|
||||
ReadOnlySpan<float> constants,
|
||||
PixelShaderBlend blend,
|
||||
PixelShaderSampler sampler,
|
||||
byte[] target,
|
||||
int targetWidth,
|
||||
int targetHeight,
|
||||
out string? error)
|
||||
{
|
||||
CallCount++;
|
||||
Hlsl = hlsl;
|
||||
EntryPoint = entryPoint;
|
||||
Resources = resources.ToArray();
|
||||
Constants = constants.ToArray();
|
||||
Blend = blend;
|
||||
Sampler = sampler;
|
||||
Target = target;
|
||||
TargetWidth = targetWidth;
|
||||
TargetHeight = targetHeight;
|
||||
error = Error;
|
||||
return Result;
|
||||
}
|
||||
}
|
||||
|
||||
private static LuaScriptEngine CreateEngine() => new(static () => new StubMediaLoader());
|
||||
|
||||
private static (AviUtlScriptContext Context, RecordingRunner Runner) NewContext(string script)
|
||||
{
|
||||
var runner = new RecordingRunner();
|
||||
var ctx = new AviUtlScriptContext
|
||||
{
|
||||
ImageWidth = 4,
|
||||
ImageHeight = 3,
|
||||
ShaderRunner = runner,
|
||||
PixelShaders = AviUtlPixelShaderLibrary.Parse(script),
|
||||
};
|
||||
ctx.SetPixelLoader(static () => new byte[4 * 3 * 4]);
|
||||
return (ctx, runner);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void PixelShader_PassesParsedArgumentsToRunner()
|
||||
{
|
||||
using var engine = CreateEngine();
|
||||
var (ctx, runner) = NewContext(ShaderSource);
|
||||
|
||||
engine.Execute(ShaderSource + "\nobj.pixelshader(\"ps\", \"object\", {\"object\"}, {1, 2.5}, \"draw\", \"clamp\")", ctx);
|
||||
|
||||
Assert.Equal(1, runner.CallCount);
|
||||
Assert.Contains("float4 ps", runner.Hlsl);
|
||||
Assert.Equal("ps", runner.EntryPoint);
|
||||
Assert.Single(runner.Resources);
|
||||
Assert.Equal(4, runner.Resources[0].Width);
|
||||
Assert.Equal(3, runner.Resources[0].Height);
|
||||
Assert.Equal([1f, 2.5f], runner.Constants);
|
||||
Assert.Equal(PixelShaderBlend.Draw, runner.Blend);
|
||||
Assert.Equal(PixelShaderSampler.Clamp, runner.Sampler);
|
||||
Assert.Equal(4, runner.TargetWidth);
|
||||
Assert.Equal(3, runner.TargetHeight);
|
||||
Assert.True(ctx.IsPixelsDirty);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void PixelShader_SingleStringResourceForm()
|
||||
{
|
||||
using var engine = CreateEngine();
|
||||
var (ctx, runner) = NewContext(ShaderSource);
|
||||
|
||||
engine.Execute(ShaderSource + "\nobj.pixelshader(\"ps\", \"object\", \"object\")", ctx);
|
||||
|
||||
Assert.Single(runner.Resources);
|
||||
Assert.False(runner.Resources[0].IsRandom);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void PixelShader_DefaultsAreCopyAndNoSampler()
|
||||
{
|
||||
using var engine = CreateEngine();
|
||||
var (ctx, runner) = NewContext(ShaderSource);
|
||||
|
||||
engine.Execute(ShaderSource + "\nobj.pixelshader(\"ps\", \"object\", \"object\")", ctx);
|
||||
|
||||
Assert.Equal(PixelShaderBlend.Copy, runner.Blend);
|
||||
Assert.Equal(PixelShaderSampler.None, runner.Sampler);
|
||||
Assert.Empty(runner.Constants);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void PixelShader_RandomResource()
|
||||
{
|
||||
using var engine = CreateEngine();
|
||||
var (ctx, runner) = NewContext(ShaderSource);
|
||||
|
||||
engine.Execute(ShaderSource + "\nobj.pixelshader(\"ps\", \"object\", {\"object\", \"random\"})", ctx);
|
||||
|
||||
Assert.Equal(2, runner.Resources.Length);
|
||||
Assert.True(runner.Resources[1].IsRandom);
|
||||
Assert.Equal(PixelShaderInput.RandomSize, runner.Resources[1].Width);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void PixelShader_MissingResourceBuffer_BindsTransparentPixel()
|
||||
{
|
||||
using var engine = CreateEngine();
|
||||
var (ctx, runner) = NewContext(ShaderSource);
|
||||
|
||||
engine.Execute(ShaderSource + "\nobj.pixelshader(\"ps\", \"object\", {\"cache:none\", \"tempbuffer\"})", ctx);
|
||||
|
||||
Assert.Equal(2, runner.Resources.Length);
|
||||
Assert.All(runner.Resources, static r =>
|
||||
{
|
||||
Assert.False(r.IsRandom);
|
||||
Assert.Equal(1, r.Width);
|
||||
Assert.Equal(1, r.Height);
|
||||
});
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void PixelShader_TempBufferTarget_CreatedAtObjectSize()
|
||||
{
|
||||
using var engine = CreateEngine();
|
||||
var (ctx, runner) = NewContext(ShaderSource);
|
||||
|
||||
engine.Execute(ShaderSource + "\nobj.pixelshader(\"ps\", \"tempbuffer\", \"object\")", ctx);
|
||||
|
||||
Assert.Equal(4, runner.TargetWidth);
|
||||
Assert.Equal(3, runner.TargetHeight);
|
||||
Assert.False(ctx.IsPixelsDirty);
|
||||
Assert.True(ctx.TryGetShaderResource("tempbuffer", out var data, out int w, out int h));
|
||||
Assert.Same(runner.Target, data);
|
||||
Assert.Equal(4, w);
|
||||
Assert.Equal(3, h);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void PixelShader_CacheTarget_CreatedAndReused()
|
||||
{
|
||||
using var engine = CreateEngine();
|
||||
var (ctx, runner) = NewContext(ShaderSource);
|
||||
|
||||
engine.Execute(ShaderSource + "\nobj.pixelshader(\"ps\", \"cache:tmp\", \"object\")\nobj.pixelshader(\"ps\", \"object\", \"cache:tmp\")", ctx);
|
||||
|
||||
Assert.Equal(2, runner.CallCount);
|
||||
Assert.Single(runner.Resources);
|
||||
Assert.Equal(4, runner.Resources[0].Width);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void PixelShader_FramebufferResource_UsesSceneSize()
|
||||
{
|
||||
using var engine = CreateEngine();
|
||||
var (ctx, runner) = NewContext(ShaderSource);
|
||||
ctx.SceneWidth = 8;
|
||||
ctx.SceneHeight = 6;
|
||||
|
||||
engine.Execute(ShaderSource + "\nobj.pixelshader(\"ps\", \"object\", \"framebuffer\")", ctx);
|
||||
|
||||
Assert.Single(runner.Resources);
|
||||
Assert.Equal(8, runner.Resources[0].Width);
|
||||
Assert.Equal(6, runner.Resources[0].Height);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void PixelShader_FramebufferTarget_ReplacesObjectBuffer()
|
||||
{
|
||||
using var engine = CreateEngine();
|
||||
var (ctx, runner) = NewContext(ShaderSource);
|
||||
ctx.SceneWidth = 8;
|
||||
ctx.SceneHeight = 6;
|
||||
|
||||
engine.Execute(ShaderSource + "\nobj.pixelshader(\"ps\", \"framebuffer\", \"object\")", ctx);
|
||||
|
||||
Assert.Equal(1, runner.CallCount);
|
||||
Assert.Equal(8, runner.TargetWidth);
|
||||
Assert.Equal(6, runner.TargetHeight);
|
||||
Assert.True(ctx.IsPixelsDirty);
|
||||
Assert.True(ctx.BufferReplaced);
|
||||
Assert.Equal(8, ctx.ImageWidth);
|
||||
Assert.Equal(6, ctx.ImageHeight);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void PixelShader_UnknownShaderName_Throws()
|
||||
{
|
||||
using var engine = CreateEngine();
|
||||
var (ctx, _) = NewContext(ShaderSource);
|
||||
|
||||
var ex = Assert.Throws<LuaScriptRuntimeException>(() =>
|
||||
engine.Execute(ShaderSource + "\nobj.pixelshader(\"missing\", \"object\", \"object\")", ctx));
|
||||
Assert.Contains("missing", ex.Message);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void PixelShader_CompileError_ThrowsWithCompilerMessage()
|
||||
{
|
||||
using var engine = CreateEngine();
|
||||
var (ctx, runner) = NewContext(ShaderSource);
|
||||
runner.Result = PixelShaderRunStatus.CompileError;
|
||||
runner.Error = "error X3000: syntax error";
|
||||
|
||||
var ex = Assert.Throws<LuaScriptRuntimeException>(() =>
|
||||
engine.Execute(ShaderSource + "\nobj.pixelshader(\"ps\", \"object\", \"object\")", ctx));
|
||||
Assert.Contains("X3000", ex.Message);
|
||||
Assert.False(ctx.IsPixelsDirty);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void PixelShader_Unavailable_IsSilentlySkipped()
|
||||
{
|
||||
using var engine = CreateEngine();
|
||||
var (ctx, runner) = NewContext(ShaderSource);
|
||||
runner.Result = PixelShaderRunStatus.Unavailable;
|
||||
|
||||
engine.Execute(ShaderSource + "\nobj.pixelshader(\"ps\", \"object\", \"object\")", ctx);
|
||||
|
||||
Assert.Equal(1, runner.CallCount);
|
||||
Assert.False(ctx.IsPixelsDirty);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void PixelShader_NoRunner_IsSilentlySkipped()
|
||||
{
|
||||
using var engine = CreateEngine();
|
||||
var (ctx, _) = NewContext(ShaderSource);
|
||||
ctx.ShaderRunner = null;
|
||||
|
||||
engine.Execute(ShaderSource + "\nobj.pixelshader(\"ps\", \"object\", \"object\")", ctx);
|
||||
|
||||
Assert.False(ctx.IsPixelsDirty);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void PixelShader_NumericBlend_IsComposite()
|
||||
{
|
||||
using var engine = CreateEngine();
|
||||
var (ctx, runner) = NewContext(ShaderSource);
|
||||
|
||||
engine.Execute(ShaderSource + "\nobj.pixelshader(\"ps\", \"object\", \"object\", {}, 11)", ctx);
|
||||
|
||||
Assert.Equal(PixelShaderBlend.Composite(11d), runner.Blend);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void PixelShader_UnknownBlend_Throws()
|
||||
{
|
||||
using var engine = CreateEngine();
|
||||
var (ctx, _) = NewContext(ShaderSource);
|
||||
|
||||
Assert.Throws<LuaScriptRuntimeException>(() =>
|
||||
engine.Execute(ShaderSource + "\nobj.pixelshader(\"ps\", \"object\", \"object\", {}, \"multiply\")", ctx));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void PixelShader_UnknownSampler_Throws()
|
||||
{
|
||||
using var engine = CreateEngine();
|
||||
var (ctx, _) = NewContext(ShaderSource);
|
||||
|
||||
Assert.Throws<LuaScriptRuntimeException>(() =>
|
||||
engine.Execute(ShaderSource + "\nobj.pixelshader(\"ps\", \"object\", \"object\", {}, \"copy\", \"point\")", ctx));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void PixelShader_TooManyConstants_Throws()
|
||||
{
|
||||
using var engine = CreateEngine();
|
||||
var (ctx, _) = NewContext(ShaderSource);
|
||||
|
||||
var ex = Assert.Throws<LuaScriptRuntimeException>(() =>
|
||||
engine.Execute(ShaderSource + "\nlocal c = {}\nfor i = 1, 1025 do c[i] = 0 end\nobj.pixelshader(\"ps\", \"object\", \"object\", c)", ctx));
|
||||
Assert.Contains("constants", ex.Message);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void PixelShader_TooManyResources_Throws()
|
||||
{
|
||||
using var engine = CreateEngine();
|
||||
var (ctx, _) = NewContext(ShaderSource);
|
||||
|
||||
var ex = Assert.Throws<LuaScriptRuntimeException>(() =>
|
||||
engine.Execute(ShaderSource + "\nlocal r = {}\nfor i = 1, 9 do r[i] = \"object\" end\nobj.pixelshader(\"ps\", \"object\", r)", ctx));
|
||||
Assert.Contains("resources", ex.Message);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void PixelShader_CrossScriptName_UsesLocalEntryPoint()
|
||||
{
|
||||
using var engine = CreateEngine();
|
||||
var (ctx, runner) = NewContext(ShaderSource);
|
||||
|
||||
engine.Execute(ShaderSource + "\nobj.pixelshader(\"ps@Other\", \"object\", \"object\")", ctx);
|
||||
|
||||
Assert.Equal("ps", runner.EntryPoint);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void ResolveAuto_PixelShaderScript_RoutesToNative()
|
||||
{
|
||||
Assert.Equal(Engine.ScriptEngineKind.Native, Engine.ScriptDirective.ResolveAuto("obj.pixelshader(\"ps\", \"object\", \"object\")"));
|
||||
Assert.Equal(Engine.ScriptEngineKind.Native, Engine.ScriptDirective.ResolveAuto("obj.setpixel(0, 0, 1, 2, 3)"));
|
||||
Assert.Equal(Engine.ScriptEngineKind.MoonSharp, Engine.ScriptDirective.ResolveAuto("--!moonsharp\nobj.pixelshader(\"ps\", \"object\", \"object\")"));
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -64,5 +64,46 @@ namespace LuaScript.Tests
|
||||
for (int i = 0; i < 4; i++)
|
||||
Assert.False(usage.Check(i));
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[InlineData("if obj.check0 != nil then obj.alpha = 0 end", 0)]
|
||||
[InlineData("local v = obj.check1 ?? 1", 1)]
|
||||
[InlineData("obj.check2 ??= true", 2)]
|
||||
[InlineData("local v = not obj.check3 && true", 3)]
|
||||
[InlineData("for i in <0..obj.check0> do end", 0)]
|
||||
public void DetectsCheckThroughExtendedSyntax(string script, int index)
|
||||
{
|
||||
var usage = ScriptParameterUsage.Detect(script);
|
||||
for (int i = 0; i < 4; i++)
|
||||
Assert.Equal(i == index, usage.Check(i));
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[InlineData("obj.x = obj.slider0 ?? 50", 0)]
|
||||
[InlineData("obj.zoom += obj.slider2 != 0 and 1 or 0", 2)]
|
||||
public void DetectsSliderThroughExtendedSyntax(string script, int index)
|
||||
{
|
||||
var usage = ScriptParameterUsage.Detect(script);
|
||||
for (int i = 0; i < 4; i++)
|
||||
Assert.Equal(i == index, usage.Slider(i));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void DetectsColorThroughExtendedSyntax()
|
||||
{
|
||||
var usage = ScriptParameterUsage.Detect("obj.rz = color != 0 and color || 1");
|
||||
Assert.True(usage.Color);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void DetectsMultipleReferencesAcrossExtendedSyntax()
|
||||
{
|
||||
var usage = ScriptParameterUsage.Detect("local a = obj.check0 && obj.check3 != 0\nobj.x = obj.slider1 ?? 0");
|
||||
Assert.True(usage.Check0);
|
||||
Assert.False(usage.Check1);
|
||||
Assert.False(usage.Check2);
|
||||
Assert.True(usage.Check3);
|
||||
Assert.True(usage.Slider(1));
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,11 +1,15 @@
|
||||
using System;
|
||||
using System.Numerics;
|
||||
using System.Runtime.InteropServices;
|
||||
using LuaScript.Compat;
|
||||
using Vortice.DCommon;
|
||||
using Vortice.Direct2D1;
|
||||
using Vortice.Direct2D1.Effects;
|
||||
using Vortice.DXGI;
|
||||
using Vortice.Mathematics;
|
||||
using YukkuriMovieMaker.Commons;
|
||||
using YukkuriMovieMaker.Player;
|
||||
using Blend = YukkuriMovieMaker.Project.Blend;
|
||||
|
||||
namespace LuaScript
|
||||
{
|
||||
@@ -17,6 +21,8 @@ namespace LuaScript
|
||||
private ID2D1Bitmap1? _source;
|
||||
private ID2D1Bitmap1? _target;
|
||||
private ID2D1Bitmap1? _staging;
|
||||
private Opacity? _opacityEffect;
|
||||
private ID2D1Image? _opacityOutput;
|
||||
private int _sourceWidth;
|
||||
private int _sourceHeight;
|
||||
private int _targetWidth;
|
||||
@@ -53,6 +59,7 @@ namespace LuaScript
|
||||
var interpolation = command.Antialias != 0d
|
||||
? BitmapInterpolationMode.Linear
|
||||
: BitmapInterpolationMode.NearestNeighbor;
|
||||
var blend = BlendModeMap.Resolve(command.Blend);
|
||||
|
||||
var dc = _ctx.DeviceContext;
|
||||
var rt = (ID2D1RenderTarget)dc;
|
||||
@@ -62,7 +69,7 @@ namespace LuaScript
|
||||
{
|
||||
dc.BeginDraw();
|
||||
rt.Transform = transform;
|
||||
rt.DrawBitmap(_source!, opacity, interpolation);
|
||||
DrawSource(rt, opacity, interpolation, blend);
|
||||
rt.Transform = Matrix3x2.Identity;
|
||||
dc.EndDraw();
|
||||
}
|
||||
@@ -92,6 +99,25 @@ namespace LuaScript
|
||||
return true;
|
||||
}
|
||||
|
||||
private void DrawSource(ID2D1RenderTarget rt, float opacity, BitmapInterpolationMode interpolation, Blend blend)
|
||||
{
|
||||
if (blend == Blend.Normal)
|
||||
{
|
||||
rt.DrawBitmap(_source!, opacity, interpolation);
|
||||
return;
|
||||
}
|
||||
|
||||
var interp = ToImageInterpolation(interpolation);
|
||||
_opacityEffect!.Value = opacity;
|
||||
if (blend.IsCompositionEffect())
|
||||
_ctx.DeviceContext.DrawImage(_opacityOutput!, interpolationMode: interp, compositeMode: blend.ToD2DCompositionMode());
|
||||
else
|
||||
_ctx.DeviceContext.BlendImage(_opacityOutput!, blend.ToD2DBlendMode(), null, null, interp);
|
||||
}
|
||||
|
||||
private static InterpolationMode ToImageInterpolation(BitmapInterpolationMode mode) =>
|
||||
mode == BitmapInterpolationMode.Linear ? InterpolationMode.Linear : InterpolationMode.NearestNeighbor;
|
||||
|
||||
private void EnsureSource(int width, int height)
|
||||
{
|
||||
if (_source is not null && _sourceWidth == width && _sourceHeight == height)
|
||||
@@ -101,6 +127,13 @@ namespace LuaScript
|
||||
_source = _ctx.DeviceContext.CreateEmptyBitmap(width, height, BitmapOptions.Target);
|
||||
_sourceWidth = width;
|
||||
_sourceHeight = height;
|
||||
|
||||
if (_opacityEffect is null)
|
||||
{
|
||||
_opacityEffect = new Opacity(_ctx.DeviceContext);
|
||||
_opacityOutput = _opacityEffect.Output;
|
||||
}
|
||||
_opacityEffect.SetInput(0, _source, true);
|
||||
}
|
||||
|
||||
private void EnsureTarget(int width, int height)
|
||||
@@ -128,9 +161,13 @@ namespace LuaScript
|
||||
|
||||
public void Dispose()
|
||||
{
|
||||
_opacityOutput?.Dispose();
|
||||
_opacityEffect?.Dispose();
|
||||
_source?.Dispose();
|
||||
_target?.Dispose();
|
||||
_staging?.Dispose();
|
||||
_opacityOutput = null;
|
||||
_opacityEffect = null;
|
||||
_source = null;
|
||||
_target = null;
|
||||
_staging = null;
|
||||
|
||||
@@ -295,6 +295,35 @@ namespace LuaScript
|
||||
return Color.FromRgb(r, g, b);
|
||||
}
|
||||
|
||||
[Display(GroupName = nameof(Texts.AnchorGroup), Name = nameof(Texts.AnchorX), Description = nameof(Texts.AnchorDesc), ResourceType = typeof(Texts))]
|
||||
[TextBoxSlider("F1", "", -9999, 9999)]
|
||||
[ShowPropertyEditorWhen(nameof(IsAnchorSelected), true)]
|
||||
[JsonIgnore]
|
||||
public double AnchorX { get => _anchorX; set { if (Set(ref _anchorX, value) && !_anchorSyncing) ApplyAnchorEdit(); } }
|
||||
double _anchorX;
|
||||
|
||||
[Display(GroupName = nameof(Texts.AnchorGroup), Name = nameof(Texts.AnchorY), Description = nameof(Texts.AnchorDesc), ResourceType = typeof(Texts))]
|
||||
[TextBoxSlider("F1", "", -9999, 9999)]
|
||||
[ShowPropertyEditorWhen(nameof(IsAnchorSelected), true)]
|
||||
[JsonIgnore]
|
||||
public double AnchorY { get => _anchorY; set { if (Set(ref _anchorY, value) && !_anchorSyncing) ApplyAnchorEdit(); } }
|
||||
double _anchorY;
|
||||
|
||||
[Display(GroupName = nameof(Texts.AnchorGroup), Name = nameof(Texts.AnchorZ), Description = nameof(Texts.AnchorDesc), ResourceType = typeof(Texts))]
|
||||
[TextBoxSlider("F1", "", -9999, 9999)]
|
||||
[ShowPropertyEditorWhen(nameof(IsAnchorZVisible), true)]
|
||||
[JsonIgnore]
|
||||
public double AnchorZ { get => _anchorZ; set { if (Set(ref _anchorZ, value) && !_anchorSyncing) ApplyAnchorEdit(); } }
|
||||
double _anchorZ;
|
||||
|
||||
[JsonIgnore] public bool IsAnchorSelected { get => _isAnchorSelected; private set => Set(ref _isAnchorSelected, value); }
|
||||
[JsonIgnore] public bool IsAnchorZVisible { get => _isAnchorZVisible; private set => Set(ref _isAnchorZVisible, value); }
|
||||
bool _isAnchorSelected;
|
||||
bool _isAnchorZVisible;
|
||||
string _selectedAnchorGroup = string.Empty;
|
||||
int _selectedAnchorIndex;
|
||||
bool _anchorSyncing;
|
||||
|
||||
public ImmutableList<LuaAnchorPoint> Anchors
|
||||
{
|
||||
get => _anchors;
|
||||
@@ -306,7 +335,37 @@ namespace LuaScript
|
||||
internal int AnchorVersion { get; private set; }
|
||||
|
||||
internal void ApplyAnchorDrag(string group, int index, double dx, double dy, double dz)
|
||||
=> Anchors = AnchorSupport.ApplyDrag(Anchors, group, index, dx, dy, dz);
|
||||
{
|
||||
Anchors = AnchorSupport.ApplyDrag(Anchors, group, index, dx, dy, dz);
|
||||
if (IsAnchorSelected && index == _selectedAnchorIndex && group == _selectedAnchorGroup)
|
||||
RefreshSelectedAnchor();
|
||||
}
|
||||
|
||||
internal void BeginAnchorEdit(string group, int index, bool is3D)
|
||||
{
|
||||
_selectedAnchorGroup = group;
|
||||
_selectedAnchorIndex = index;
|
||||
RefreshSelectedAnchor();
|
||||
IsAnchorSelected = true;
|
||||
IsAnchorZVisible = is3D;
|
||||
}
|
||||
|
||||
private void RefreshSelectedAnchor()
|
||||
{
|
||||
AnchorSupport.ResolvePosition(_anchors, _selectedAnchorGroup, _selectedAnchorIndex, out double x, out double y, out double z);
|
||||
_anchorSyncing = true;
|
||||
AnchorX = x;
|
||||
AnchorY = y;
|
||||
AnchorZ = z;
|
||||
_anchorSyncing = false;
|
||||
}
|
||||
|
||||
private void ApplyAnchorEdit()
|
||||
{
|
||||
if (!IsAnchorSelected)
|
||||
return;
|
||||
Anchors = AnchorSupport.SetPosition(_anchors, _selectedAnchorGroup, _selectedAnchorIndex, _anchorX, _anchorY, _anchorZ);
|
||||
}
|
||||
|
||||
public override IEnumerable<string> CreateExoVideoFilters(int keyFrameIndex, ExoOutputDescription exoOutputDescription) => [];
|
||||
|
||||
|
||||
@@ -7,6 +7,7 @@ using LuaScript.Compat;
|
||||
using LuaScript.Diagnostics;
|
||||
using LuaScript.Engine;
|
||||
using LuaScript.Engine.Kernel;
|
||||
using LuaScript.Engine.Shader;
|
||||
using Vortice;
|
||||
using Vortice.DCommon;
|
||||
using Vortice.Direct2D1;
|
||||
@@ -142,11 +143,13 @@ namespace LuaScript
|
||||
private Action<string, int, bool, int, double[]>? _nativeSetAnchor;
|
||||
private Func<string, SceneValue>? _nativeSceneGet;
|
||||
private Action<string, SceneValue>? _nativeSceneSet;
|
||||
private PixelShaderInvoke? _nativeRunPixelShader;
|
||||
|
||||
private bool _isFirst = true;
|
||||
private string _sourceScript = string.Empty;
|
||||
private string _runnableScript = string.Empty;
|
||||
private int[] _runnableLineMap = [];
|
||||
private int[] _runnableChangedLines = [];
|
||||
private bool _runnableCached;
|
||||
private ID2D1Image? _cachedInput;
|
||||
private RenderKey _cachedKey;
|
||||
@@ -155,6 +158,10 @@ namespace LuaScript
|
||||
private DrawDescription? _cachedOutputDesc;
|
||||
private ID2D1Image? _cachedEffectOutput;
|
||||
|
||||
private PixelShaderRunner? _pixelShaderRunner;
|
||||
private AviUtlPixelShaderLibrary _pixelShaderLibrary = AviUtlPixelShaderLibrary.Empty;
|
||||
private string? _pixelShaderSourceRef;
|
||||
|
||||
private VideoEffectChain? _effectChain;
|
||||
private DrawCompositor? _drawCompositor;
|
||||
private FallbackCompositor? _bufferCompositor;
|
||||
@@ -172,6 +179,7 @@ namespace LuaScript
|
||||
new SynchronizedCompositor(new HardwareCompositor(_ownCtx), _pixelLoaderSemaphore),
|
||||
SoftwareCompositor.Instance,
|
||||
WarnBufferCompositorDegraded);
|
||||
_pixelShaderRunner = new PixelShaderRunner { Compositor = _bufferCompositor };
|
||||
_context.ResolverProvider = GetFrameResolver;
|
||||
_context.Compositor = _bufferCompositor;
|
||||
return null;
|
||||
@@ -211,17 +219,29 @@ namespace LuaScript
|
||||
|
||||
private string GetRunnableScript(string source)
|
||||
{
|
||||
if (_runnableCached && string.Equals(source, _sourceScript, StringComparison.Ordinal))
|
||||
if (_runnableCached && ReferenceEquals(source, _sourceScript))
|
||||
return _runnableScript;
|
||||
|
||||
var (code, lineMap) = AviUtlScript.TransformWithMap(source);
|
||||
var (code, lineMap, changedLines) = AviUtlScript.TransformWithMap(source);
|
||||
_runnableScript = code;
|
||||
_runnableLineMap = lineMap;
|
||||
_runnableChangedLines = changedLines;
|
||||
_sourceScript = source;
|
||||
_runnableCached = true;
|
||||
return _runnableScript;
|
||||
}
|
||||
|
||||
private AviUtlPixelShaderLibrary GetPixelShaderLibrary(string source)
|
||||
{
|
||||
if (!ReferenceEquals(_pixelShaderSourceRef, source))
|
||||
{
|
||||
_pixelShaderLibrary = AviUtlPixelShaderLibrary.Parse(source);
|
||||
_pixelShaderSourceRef = source;
|
||||
_pixelShaderRunner?.Invalidate();
|
||||
}
|
||||
return _pixelShaderLibrary;
|
||||
}
|
||||
|
||||
private static LuaScriptDiagnosticKind ClassifyDiagnostic(LuaScriptException exception) => exception switch
|
||||
{
|
||||
LuaScriptCompilationException => LuaScriptDiagnosticKind.Compile,
|
||||
@@ -232,11 +252,19 @@ namespace LuaScript
|
||||
private LuaScriptDiagnostic CreateDiagnostic(LuaScriptDiagnosticKind kind, string message)
|
||||
{
|
||||
var diagnostic = LuaScriptDiagnosticParser.Parse(kind, message);
|
||||
return diagnostic.Line > 0
|
||||
? diagnostic with { Line = MapRunnableLine(diagnostic.Line) }
|
||||
: diagnostic;
|
||||
if (diagnostic.Line <= 0)
|
||||
return diagnostic;
|
||||
|
||||
if (IsRunnableLineRewritten(diagnostic.Line))
|
||||
diagnostic = diagnostic with { Column = 0, Length = 0 };
|
||||
|
||||
return diagnostic with { Line = MapRunnableLine(diagnostic.Line) };
|
||||
}
|
||||
|
||||
private bool IsRunnableLineRewritten(int runnableLine)
|
||||
=> _runnableChangedLines.Length != 0
|
||||
&& Array.BinarySearch(_runnableChangedLines, runnableLine) >= 0;
|
||||
|
||||
private int MapRunnableLine(int runnableLine)
|
||||
{
|
||||
int index = runnableLine - 1;
|
||||
@@ -333,6 +361,8 @@ namespace LuaScript
|
||||
_pixelWidth = imgW;
|
||||
_pixelHeight = imgH;
|
||||
ctx.SetPixelLoader(_pixelLoader ??= LoadPendingInputPixels);
|
||||
ctx.ShaderRunner = _pixelShaderRunner;
|
||||
ctx.PixelShaders = GetPixelShaderLibrary(script);
|
||||
|
||||
DrawDescription outDesc = inDesc;
|
||||
IReadOnlyList<LuaScriptDiagnostic> diagnostics = [];
|
||||
@@ -440,19 +470,31 @@ namespace LuaScript
|
||||
|
||||
_isFirst = false;
|
||||
_cachedKey = key;
|
||||
_cachedQueries = ctx.ObjectQueries.Count == 0 ? [] : [.. ctx.ObjectQueries];
|
||||
_cachedSceneValueQueries = ctx.SceneValueQueries.Count == 0 ? [] : [.. ctx.SceneValueQueries];
|
||||
_cachedQueries = SnapshotQueries(ctx.ObjectQueries, _cachedQueries);
|
||||
_cachedSceneValueQueries = SnapshotQueries(ctx.SceneValueQueries, _cachedSceneValueQueries);
|
||||
_cachedOutputDesc = outDesc;
|
||||
_cachedEffectOutput = effectOutput;
|
||||
|
||||
return outDesc;
|
||||
}
|
||||
|
||||
private string? _effectTargetSource;
|
||||
private AviUtlEngine _effectTarget;
|
||||
|
||||
private AviUtlEngine ResolveEffectTarget(string? script)
|
||||
{
|
||||
if (!ReferenceEquals(_effectTargetSource, script) || _effectTargetSource is null)
|
||||
{
|
||||
_effectTarget = AviUtlCompatMap.ResolveTarget(script);
|
||||
_effectTargetSource = script;
|
||||
}
|
||||
return _effectTarget;
|
||||
}
|
||||
|
||||
private ID2D1Image ApplyEffectChain(ID2D1Image source, IReadOnlyList<AviUtlEffectRequest> requests, EffectDescription desc, ref DrawDescription drawDescription)
|
||||
{
|
||||
_effectChain ??= new VideoEffectChain(_ownCtx!);
|
||||
var target = AviUtlCompatMap.ResolveTarget(item.Script);
|
||||
return _effectChain.Apply(source, requests, desc, target, ref drawDescription);
|
||||
return _effectChain.Apply(source, requests, desc, ResolveEffectTarget(item.Script), ref drawDescription);
|
||||
}
|
||||
|
||||
private static (double Bpm, int Beat, double Offset) ResolveBpm(EffectDescription desc)
|
||||
@@ -519,6 +561,17 @@ namespace LuaScript
|
||||
return true;
|
||||
}
|
||||
|
||||
private static T[] SnapshotQueries<T>(IReadOnlyList<T> source, T[] existing)
|
||||
{
|
||||
int count = source.Count;
|
||||
if (count == 0)
|
||||
return [];
|
||||
var target = existing.Length == count ? existing : new T[count];
|
||||
for (int i = 0; i < count; i++)
|
||||
target[i] = source[i];
|
||||
return target;
|
||||
}
|
||||
|
||||
private static bool QueriesMatch(SceneObjectQuery[] queries, SceneObjectResolver resolver)
|
||||
{
|
||||
for (int i = 0; i < queries.Length; i++)
|
||||
@@ -592,6 +645,7 @@ namespace LuaScript
|
||||
ctx.AnchorSource = item.Anchors;
|
||||
ctx.DrawStateOverride = null;
|
||||
ctx.ResetDrawTarget();
|
||||
ctx.ResetFrameBuffer();
|
||||
|
||||
ctx.ImageWidth = imgW;
|
||||
ctx.ImageHeight = imgH;
|
||||
@@ -723,6 +777,7 @@ namespace LuaScript
|
||||
arg => item.ApplyAnchorDrag(group, index, arg.Delta.X, arg.Delta.Y, is3D ? arg.Delta.Z : 0d))
|
||||
{
|
||||
Shape = VideoControllerPointShape.Circle,
|
||||
OnDragStart = _ => item.BeginAnchorEdit(group, index, is3D),
|
||||
};
|
||||
builder.Add(new VideoEffectController(item, [point]));
|
||||
}
|
||||
@@ -810,7 +865,7 @@ namespace LuaScript
|
||||
|
||||
private void EnsureKernel(string runnable)
|
||||
{
|
||||
if (_kernelResolved && string.Equals(runnable, _kernelSource, StringComparison.Ordinal))
|
||||
if (_kernelResolved && ReferenceEquals(runnable, _kernelSource))
|
||||
return;
|
||||
|
||||
_kernelSource = runnable;
|
||||
@@ -824,7 +879,7 @@ namespace LuaScript
|
||||
|
||||
private void EnsureDirective(string runnable)
|
||||
{
|
||||
if (_directiveCached && string.Equals(runnable, _directiveSource, StringComparison.Ordinal))
|
||||
if (_directiveCached && ReferenceEquals(runnable, _directiveSource))
|
||||
return;
|
||||
|
||||
_directiveSource = runnable;
|
||||
@@ -931,6 +986,7 @@ namespace LuaScript
|
||||
_nativeSetAnchor ??= ResolveNativeAnchor;
|
||||
_nativeSceneGet ??= name => _context.GetSceneValue(name);
|
||||
_nativeSceneSet ??= (name, value) => _context.SetSceneValue(name, value);
|
||||
_nativeRunPixelShader ??= NativeRunPixelShader;
|
||||
|
||||
NativeFieldMap.ToFields(ctx, _nativeFields);
|
||||
_nativeUploaded = false;
|
||||
@@ -947,6 +1003,7 @@ namespace LuaScript
|
||||
_nativeSetAnchor,
|
||||
_nativeSceneGet,
|
||||
_nativeSceneSet,
|
||||
_nativeRunPixelShader,
|
||||
out bool dirty, out bool bufferReplaced,
|
||||
out int resultW, out int resultH, out string? error);
|
||||
|
||||
@@ -997,6 +1054,39 @@ namespace LuaScript
|
||||
return false;
|
||||
}
|
||||
|
||||
private PixelShaderRunStatus NativeRunPixelShader(
|
||||
string name,
|
||||
ReadOnlySpan<PixelShaderInput> resources,
|
||||
ReadOnlySpan<float> constants,
|
||||
PixelShaderBlend blend,
|
||||
PixelShaderSampler sampler,
|
||||
byte[] target,
|
||||
int targetWidth,
|
||||
int targetHeight,
|
||||
out string? error)
|
||||
{
|
||||
error = null;
|
||||
if (!_context.PixelShaders.TryGet(name, out string hlsl))
|
||||
{
|
||||
error = $"obj.pixelshader: shader '{name}' is not defined in this script.";
|
||||
return PixelShaderRunStatus.CompileError;
|
||||
}
|
||||
|
||||
var runner = _pixelShaderRunner;
|
||||
if (runner is null)
|
||||
return PixelShaderRunStatus.Unavailable;
|
||||
|
||||
var status = runner.TryRun(
|
||||
hlsl,
|
||||
AviUtlPixelShaderLibrary.EntryPointOf(name),
|
||||
resources, constants, blend, sampler,
|
||||
target, targetWidth, targetHeight,
|
||||
out error);
|
||||
if (status == PixelShaderRunStatus.CompileError)
|
||||
error = $"obj.pixelshader: shader '{name}' failed to compile.\n{error}";
|
||||
return status;
|
||||
}
|
||||
|
||||
private void UploadNativeInputPixels(nint address, long capacity)
|
||||
{
|
||||
_nativeUploaded = true;
|
||||
@@ -1102,6 +1192,7 @@ namespace LuaScript
|
||||
{
|
||||
_engine.Dispose();
|
||||
_gpuKernel?.Dispose();
|
||||
_pixelShaderRunner?.Dispose();
|
||||
_nativeWorker?.Dispose();
|
||||
_effectChain?.Dispose();
|
||||
_drawCompositor?.Dispose();
|
||||
|
||||
@@ -0,0 +1,578 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Text;
|
||||
using System.Threading;
|
||||
using Vortice.D3DCompiler;
|
||||
using Vortice.Direct3D;
|
||||
using Vortice.Direct3D11;
|
||||
using Vortice.DXGI;
|
||||
using Vortice.Mathematics;
|
||||
using YukkuriMovieMaker.Commons;
|
||||
|
||||
namespace LuaScript.Engine.Shader
|
||||
{
|
||||
internal sealed unsafe class PixelShaderRunner : IPixelShaderRunner, IDisposable
|
||||
{
|
||||
private const int MaxResources = 8;
|
||||
private const int ConstantBufferSize = 4096;
|
||||
private const int RandomSeed = 20260704;
|
||||
|
||||
private const string VertexShaderSource = """
|
||||
struct VsOutput { float4 pos : SV_Position; float2 uv : TEXCOORD0; };
|
||||
VsOutput vsmain(uint id : SV_VertexID)
|
||||
{
|
||||
VsOutput output;
|
||||
float2 t = float2((id << 1) & 2, id & 2);
|
||||
output.uv = t;
|
||||
output.pos = float4(t.x * 2.0 - 1.0, 1.0 - t.y * 2.0, 0.0, 1.0);
|
||||
return output;
|
||||
}
|
||||
""";
|
||||
|
||||
private static readonly FeatureLevel[] s_featureLevels = [FeatureLevel.Level_11_0];
|
||||
|
||||
private sealed record CompiledShader(ID3D11PixelShader? Shader, string? Error);
|
||||
|
||||
private struct InputSlot
|
||||
{
|
||||
public ID3D11Texture2D? Texture;
|
||||
public ID3D11ShaderResourceView? View;
|
||||
public int Width;
|
||||
public int Height;
|
||||
}
|
||||
|
||||
private readonly Lock _locker = new();
|
||||
private readonly Dictionary<(string Hlsl, string Entry), CompiledShader> _shaders = [];
|
||||
private readonly InputSlot[] _inputs = new InputSlot[MaxResources];
|
||||
private readonly ID3D11ShaderResourceView[] _boundViews = new ID3D11ShaderResourceView[MaxResources];
|
||||
private readonly ID3D11ShaderResourceView[] _nullViews = new ID3D11ShaderResourceView[MaxResources];
|
||||
|
||||
private byte[] _compositeBuffer = [];
|
||||
|
||||
public IBufferCompositor Compositor { get; set; } = SoftwareCompositor.Instance;
|
||||
|
||||
private ID3D11Device? _device;
|
||||
private ID3D11DeviceContext? _context;
|
||||
private ID3D11VertexShader? _vertexShader;
|
||||
private ID3D11Buffer? _constantBuffer;
|
||||
private ID3D11RasterizerState? _rasterizer;
|
||||
private readonly ID3D11BlendState?[] _blendStates = new ID3D11BlendState?[4];
|
||||
private readonly ID3D11SamplerState?[] _samplerStates = new ID3D11SamplerState?[6];
|
||||
private ID3D11Texture2D? _randomTexture;
|
||||
private ID3D11ShaderResourceView? _randomView;
|
||||
private ID3D11Texture2D? _targetTexture;
|
||||
private ID3D11RenderTargetView? _targetView;
|
||||
private int _targetWidth;
|
||||
private int _targetHeight;
|
||||
private ID3D11Texture2D? _stagingTexture;
|
||||
private int _stagingWidth;
|
||||
private int _stagingHeight;
|
||||
|
||||
private bool _disposed;
|
||||
private bool _unavailable;
|
||||
private bool _failureLogged;
|
||||
private int _recreateBudget = 3;
|
||||
|
||||
public PixelShaderRunStatus TryRun(
|
||||
string hlsl,
|
||||
string entryPoint,
|
||||
ReadOnlySpan<PixelShaderInput> resources,
|
||||
ReadOnlySpan<float> constants,
|
||||
PixelShaderBlend blend,
|
||||
PixelShaderSampler sampler,
|
||||
byte[] target,
|
||||
int targetWidth,
|
||||
int targetHeight,
|
||||
out string? error)
|
||||
{
|
||||
error = null;
|
||||
lock (_locker)
|
||||
{
|
||||
if (_disposed || _unavailable)
|
||||
return PixelShaderRunStatus.Unavailable;
|
||||
if (targetWidth <= 0 || targetHeight <= 0 || (long)target.Length < (long)targetWidth * targetHeight * 4)
|
||||
return PixelShaderRunStatus.Unavailable;
|
||||
|
||||
try
|
||||
{
|
||||
if (!EnsureDevice())
|
||||
return PixelShaderRunStatus.Unavailable;
|
||||
|
||||
var compiled = GetOrCompile(hlsl, entryPoint);
|
||||
if (compiled.Shader is null)
|
||||
{
|
||||
error = compiled.Error;
|
||||
return PixelShaderRunStatus.CompileError;
|
||||
}
|
||||
|
||||
Execute(compiled.Shader, resources, constants, blend, sampler, target, targetWidth, targetHeight);
|
||||
return PixelShaderRunStatus.Success;
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
HandleFailure(ex);
|
||||
return PixelShaderRunStatus.Unavailable;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
public void Invalidate()
|
||||
{
|
||||
lock (_locker)
|
||||
{
|
||||
ReleaseShaders();
|
||||
}
|
||||
}
|
||||
|
||||
public void Dispose()
|
||||
{
|
||||
lock (_locker)
|
||||
{
|
||||
if (_disposed)
|
||||
return;
|
||||
_disposed = true;
|
||||
ReleaseDeviceObjects();
|
||||
}
|
||||
}
|
||||
|
||||
private bool EnsureDevice()
|
||||
{
|
||||
if (_device is not null)
|
||||
return true;
|
||||
if (_recreateBudget <= 0)
|
||||
{
|
||||
MarkUnavailable(null);
|
||||
return false;
|
||||
}
|
||||
_recreateBudget--;
|
||||
|
||||
if (!TryCreateDevice(DriverType.Hardware, out var device, out var context) &&
|
||||
!TryCreateDevice(DriverType.Warp, out device, out context))
|
||||
{
|
||||
MarkUnavailable(null);
|
||||
return false;
|
||||
}
|
||||
|
||||
try
|
||||
{
|
||||
var vsBytecode = CompileOrThrow(VertexShaderSource, "vsmain", "vs_4_0");
|
||||
var vertexShader = device!.CreateVertexShader(vsBytecode);
|
||||
_device = device;
|
||||
_context = context;
|
||||
_vertexShader = vertexShader;
|
||||
_constantBuffer = device.CreateBuffer(new BufferDescription(
|
||||
ConstantBufferSize, BindFlags.ConstantBuffer, ResourceUsage.Dynamic, CpuAccessFlags.Write));
|
||||
_rasterizer = device.CreateRasterizerState(RasterizerDescription.CullNone);
|
||||
CreateBlendStates(device);
|
||||
CreateSamplerStates(device);
|
||||
return true;
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
if (ReferenceEquals(_device, device))
|
||||
{
|
||||
ReleaseDeviceObjects();
|
||||
}
|
||||
else
|
||||
{
|
||||
context?.Dispose();
|
||||
device?.Dispose();
|
||||
}
|
||||
MarkUnavailable(ex);
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
private static bool TryCreateDevice(DriverType driverType, out ID3D11Device? device, out ID3D11DeviceContext? context)
|
||||
{
|
||||
device = null;
|
||||
context = null;
|
||||
try
|
||||
{
|
||||
var result = D3D11.D3D11CreateDevice(
|
||||
null, driverType, DeviceCreationFlags.BgraSupport, s_featureLevels,
|
||||
out device, out context);
|
||||
if (result.Success && device is not null && context is not null)
|
||||
return true;
|
||||
}
|
||||
catch
|
||||
{
|
||||
}
|
||||
context?.Dispose();
|
||||
device?.Dispose();
|
||||
device = null;
|
||||
context = null;
|
||||
return false;
|
||||
}
|
||||
|
||||
private void CreateBlendStates(ID3D11Device device)
|
||||
{
|
||||
_blendStates[(int)PixelShaderBlendMode.Copy] = null;
|
||||
_blendStates[(int)PixelShaderBlendMode.Mask] = device.CreateBlendState(new BlendDescription(
|
||||
Blend.Zero, Blend.One, Blend.Zero, Blend.SourceAlpha));
|
||||
_blendStates[(int)PixelShaderBlendMode.Draw] = device.CreateBlendState(new BlendDescription(
|
||||
Blend.One, Blend.InverseSourceAlpha, Blend.One, Blend.InverseSourceAlpha));
|
||||
_blendStates[(int)PixelShaderBlendMode.Add] = device.CreateBlendState(new BlendDescription(
|
||||
Blend.One, Blend.One, Blend.One, Blend.One));
|
||||
}
|
||||
|
||||
private void CreateSamplerStates(ID3D11Device device)
|
||||
{
|
||||
_samplerStates[(int)PixelShaderSampler.None] = null;
|
||||
_samplerStates[(int)PixelShaderSampler.Clip] = CreateSampler(device, Filter.MinMagMipLinear, TextureAddressMode.Border);
|
||||
_samplerStates[(int)PixelShaderSampler.Clamp] = CreateSampler(device, Filter.MinMagMipLinear, TextureAddressMode.Clamp);
|
||||
_samplerStates[(int)PixelShaderSampler.Loop] = CreateSampler(device, Filter.MinMagMipLinear, TextureAddressMode.Wrap);
|
||||
_samplerStates[(int)PixelShaderSampler.Mirror] = CreateSampler(device, Filter.MinMagMipLinear, TextureAddressMode.Mirror);
|
||||
_samplerStates[(int)PixelShaderSampler.Dot] = CreateSampler(device, Filter.MinMagMipPoint, TextureAddressMode.Border);
|
||||
}
|
||||
|
||||
private static ID3D11SamplerState CreateSampler(ID3D11Device device, Filter filter, TextureAddressMode address)
|
||||
{
|
||||
var description = new SamplerDescription(filter, address, address, address)
|
||||
{
|
||||
BorderColor = new Color4(0f, 0f, 0f, 0f),
|
||||
};
|
||||
return device.CreateSamplerState(description);
|
||||
}
|
||||
|
||||
private CompiledShader GetOrCompile(string hlsl, string entryPoint)
|
||||
{
|
||||
var key = (hlsl, entryPoint);
|
||||
if (_shaders.TryGetValue(key, out var cached))
|
||||
return cached;
|
||||
|
||||
CompiledShader compiled;
|
||||
byte[] source = Encoding.UTF8.GetBytes(hlsl);
|
||||
var result = Compiler.Compile(source, entryPoint, string.Empty, "ps_5_0", out var bytecode, out var errors);
|
||||
if (result.Failure || bytecode is null)
|
||||
{
|
||||
compiled = new CompiledShader(null, errors?.AsString()?.Trim() ?? result.ToString());
|
||||
errors?.Dispose();
|
||||
bytecode?.Dispose();
|
||||
}
|
||||
else
|
||||
{
|
||||
try
|
||||
{
|
||||
compiled = new CompiledShader(_device!.CreatePixelShader(bytecode.AsSpan()), null);
|
||||
}
|
||||
finally
|
||||
{
|
||||
errors?.Dispose();
|
||||
bytecode.Dispose();
|
||||
}
|
||||
}
|
||||
|
||||
_shaders[key] = compiled;
|
||||
return compiled;
|
||||
}
|
||||
|
||||
private static byte[] CompileOrThrow(string source, string entryPoint, string profile)
|
||||
{
|
||||
var result = Compiler.Compile(Encoding.UTF8.GetBytes(source), entryPoint, string.Empty, profile, out var bytecode, out var errors);
|
||||
try
|
||||
{
|
||||
if (result.Failure || bytecode is null)
|
||||
throw new InvalidOperationException(errors?.AsString() ?? result.ToString());
|
||||
return bytecode.AsBytes();
|
||||
}
|
||||
finally
|
||||
{
|
||||
errors?.Dispose();
|
||||
bytecode?.Dispose();
|
||||
}
|
||||
}
|
||||
|
||||
private void Execute(
|
||||
ID3D11PixelShader shader,
|
||||
ReadOnlySpan<PixelShaderInput> resources,
|
||||
ReadOnlySpan<float> constants,
|
||||
PixelShaderBlend blend,
|
||||
PixelShaderSampler sampler,
|
||||
byte[] target,
|
||||
int width,
|
||||
int height)
|
||||
{
|
||||
var context = _context!;
|
||||
|
||||
bool composite = blend.Mode == PixelShaderBlendMode.Composite;
|
||||
EnsureTarget(width, height);
|
||||
if (!composite && blend.Mode != PixelShaderBlendMode.Copy)
|
||||
UploadPixels(_targetTexture!, target, width, height);
|
||||
|
||||
UploadConstants(constants);
|
||||
BindResources(resources);
|
||||
|
||||
context.OMSetRenderTargets(_targetView!);
|
||||
context.OMSetBlendState(composite ? null : _blendStates[(int)blend.Mode]);
|
||||
context.RSSetViewport(0f, 0f, width, height);
|
||||
context.RSSetState(_rasterizer);
|
||||
context.IASetInputLayout(null);
|
||||
context.IASetPrimitiveTopology(PrimitiveTopology.TriangleList);
|
||||
context.VSSetShader(_vertexShader);
|
||||
context.PSSetShader(shader);
|
||||
context.PSSetConstantBuffer(0, _constantBuffer);
|
||||
context.PSSetSampler(0, _samplerStates[(int)sampler]);
|
||||
context.PSSetShaderResources(0, _boundViews);
|
||||
context.Draw(3, 0);
|
||||
context.PSSetShaderResources(0, _nullViews);
|
||||
context.UnsetRenderTargets();
|
||||
|
||||
if (composite)
|
||||
{
|
||||
int length = width * height * 4;
|
||||
if (_compositeBuffer.Length < length)
|
||||
_compositeBuffer = new byte[length];
|
||||
ReadBack(_compositeBuffer, width, height);
|
||||
Compositor.TryCompose(target, width, height, _compositeBuffer, width, height,
|
||||
new DrawCommand(width * 0.5, height * 0.5, 0d, 1d, 1d, 0d, null, 0d, blend.CompositeBlend));
|
||||
}
|
||||
else
|
||||
{
|
||||
ReadBack(target, width, height);
|
||||
}
|
||||
}
|
||||
|
||||
private void EnsureTarget(int width, int height)
|
||||
{
|
||||
if (_targetTexture is null || _targetWidth != width || _targetHeight != height)
|
||||
{
|
||||
_targetView?.Dispose();
|
||||
_targetTexture?.Dispose();
|
||||
_targetTexture = _device!.CreateTexture2D(new Texture2DDescription
|
||||
{
|
||||
Width = width,
|
||||
Height = height,
|
||||
MipLevels = 1,
|
||||
ArraySize = 1,
|
||||
Format = Format.B8G8R8A8_UNorm,
|
||||
SampleDescription = new SampleDescription(1, 0),
|
||||
Usage = ResourceUsage.Default,
|
||||
BindFlags = BindFlags.RenderTarget,
|
||||
});
|
||||
_targetView = _device.CreateRenderTargetView(_targetTexture);
|
||||
_targetWidth = width;
|
||||
_targetHeight = height;
|
||||
}
|
||||
|
||||
if (_stagingTexture is null || _stagingWidth != width || _stagingHeight != height)
|
||||
{
|
||||
_stagingTexture?.Dispose();
|
||||
_stagingTexture = _device!.CreateTexture2D(new Texture2DDescription
|
||||
{
|
||||
Width = width,
|
||||
Height = height,
|
||||
MipLevels = 1,
|
||||
ArraySize = 1,
|
||||
Format = Format.B8G8R8A8_UNorm,
|
||||
SampleDescription = new SampleDescription(1, 0),
|
||||
Usage = ResourceUsage.Staging,
|
||||
CPUAccessFlags = CpuAccessFlags.Read,
|
||||
});
|
||||
_stagingWidth = width;
|
||||
_stagingHeight = height;
|
||||
}
|
||||
}
|
||||
|
||||
private void UploadPixels(ID3D11Texture2D texture, byte[] pixels, int width, int height)
|
||||
{
|
||||
fixed (byte* source = pixels)
|
||||
_context!.UpdateSubresource(texture, 0, null, (nint)source, width * 4, 0);
|
||||
}
|
||||
|
||||
private void UploadConstants(ReadOnlySpan<float> constants)
|
||||
{
|
||||
var mapped = _context!.Map(_constantBuffer!, MapMode.WriteDiscard);
|
||||
try
|
||||
{
|
||||
var destination = new Span<float>((void*)mapped.DataPointer, ConstantBufferSize / sizeof(float));
|
||||
constants.CopyTo(destination);
|
||||
destination[constants.Length..].Clear();
|
||||
}
|
||||
finally
|
||||
{
|
||||
_context.Unmap(_constantBuffer!);
|
||||
}
|
||||
}
|
||||
|
||||
private void BindResources(ReadOnlySpan<PixelShaderInput> resources)
|
||||
{
|
||||
for (int i = 0; i < MaxResources; i++)
|
||||
{
|
||||
if (i >= resources.Length)
|
||||
{
|
||||
_boundViews[i] = null!;
|
||||
continue;
|
||||
}
|
||||
|
||||
var resource = resources[i];
|
||||
if (resource.IsRandom)
|
||||
{
|
||||
_boundViews[i] = EnsureRandomView();
|
||||
continue;
|
||||
}
|
||||
|
||||
ref var slot = ref _inputs[i];
|
||||
if (slot.Texture is null || slot.Width != resource.Width || slot.Height != resource.Height)
|
||||
{
|
||||
slot.View?.Dispose();
|
||||
slot.Texture?.Dispose();
|
||||
slot.Texture = _device!.CreateTexture2D(new Texture2DDescription
|
||||
{
|
||||
Width = resource.Width,
|
||||
Height = resource.Height,
|
||||
MipLevels = 1,
|
||||
ArraySize = 1,
|
||||
Format = Format.B8G8R8A8_UNorm,
|
||||
SampleDescription = new SampleDescription(1, 0),
|
||||
Usage = ResourceUsage.Default,
|
||||
BindFlags = BindFlags.ShaderResource,
|
||||
});
|
||||
slot.View = _device.CreateShaderResourceView(slot.Texture);
|
||||
slot.Width = resource.Width;
|
||||
slot.Height = resource.Height;
|
||||
}
|
||||
|
||||
UploadPixels(slot.Texture, resource.Data!, resource.Width, resource.Height);
|
||||
_boundViews[i] = slot.View!;
|
||||
}
|
||||
}
|
||||
|
||||
private ID3D11ShaderResourceView EnsureRandomView()
|
||||
{
|
||||
if (_randomView is not null)
|
||||
return _randomView;
|
||||
|
||||
int size = PixelShaderInput.RandomSize;
|
||||
var values = new float[size * size];
|
||||
var random = new Random(RandomSeed);
|
||||
for (int i = 0; i < values.Length; i++)
|
||||
values[i] = (float)random.NextDouble();
|
||||
|
||||
fixed (float* source = values)
|
||||
{
|
||||
_randomTexture = _device!.CreateTexture2D(new Texture2DDescription
|
||||
{
|
||||
Width = size,
|
||||
Height = size,
|
||||
MipLevels = 1,
|
||||
ArraySize = 1,
|
||||
Format = Format.R32_Float,
|
||||
SampleDescription = new SampleDescription(1, 0),
|
||||
Usage = ResourceUsage.Immutable,
|
||||
BindFlags = BindFlags.ShaderResource,
|
||||
}, [new SubresourceData((nint)source, size * sizeof(float))]);
|
||||
}
|
||||
_randomView = _device!.CreateShaderResourceView(_randomTexture);
|
||||
return _randomView;
|
||||
}
|
||||
|
||||
private void ReadBack(byte[] target, int width, int height)
|
||||
{
|
||||
var context = _context!;
|
||||
context.CopyResource(_stagingTexture!, _targetTexture!);
|
||||
var mapped = context.Map(_stagingTexture!, 0, MapMode.Read);
|
||||
try
|
||||
{
|
||||
int rowBytes = width * 4;
|
||||
byte* source = (byte*)mapped.DataPointer;
|
||||
fixed (byte* destination = target)
|
||||
{
|
||||
if (mapped.RowPitch == rowBytes)
|
||||
{
|
||||
Buffer.MemoryCopy(source, destination, target.Length, (long)rowBytes * height);
|
||||
}
|
||||
else
|
||||
{
|
||||
for (int row = 0; row < height; row++)
|
||||
Buffer.MemoryCopy(
|
||||
source + (long)mapped.RowPitch * row,
|
||||
destination + (long)rowBytes * row,
|
||||
rowBytes, rowBytes);
|
||||
}
|
||||
}
|
||||
}
|
||||
finally
|
||||
{
|
||||
context.Unmap(_stagingTexture!, 0);
|
||||
}
|
||||
}
|
||||
|
||||
private void HandleFailure(Exception ex)
|
||||
{
|
||||
if (!_failureLogged)
|
||||
{
|
||||
_failureLogged = true;
|
||||
Log.Default.Write("LuaScript: obj.pixelshader execution failed; the call is skipped.", ex);
|
||||
}
|
||||
ReleaseDeviceObjects();
|
||||
if (_recreateBudget <= 0)
|
||||
_unavailable = true;
|
||||
}
|
||||
|
||||
private void MarkUnavailable(Exception? ex)
|
||||
{
|
||||
_unavailable = true;
|
||||
if (_failureLogged)
|
||||
return;
|
||||
_failureLogged = true;
|
||||
if (ex is null)
|
||||
Log.Default.Write("LuaScript: Direct3D 11 is unavailable; obj.pixelshader is disabled.");
|
||||
else
|
||||
Log.Default.Write("LuaScript: Direct3D 11 initialization failed; obj.pixelshader is disabled.", ex);
|
||||
}
|
||||
|
||||
private void ReleaseShaders()
|
||||
{
|
||||
foreach (var compiled in _shaders.Values)
|
||||
compiled.Shader?.Dispose();
|
||||
_shaders.Clear();
|
||||
}
|
||||
|
||||
private void ReleaseDeviceObjects()
|
||||
{
|
||||
ReleaseShaders();
|
||||
for (int i = 0; i < _inputs.Length; i++)
|
||||
{
|
||||
_inputs[i].View?.Dispose();
|
||||
_inputs[i].Texture?.Dispose();
|
||||
_inputs[i] = default;
|
||||
_boundViews[i] = null!;
|
||||
}
|
||||
for (int i = 0; i < _blendStates.Length; i++)
|
||||
{
|
||||
_blendStates[i]?.Dispose();
|
||||
_blendStates[i] = null;
|
||||
}
|
||||
for (int i = 0; i < _samplerStates.Length; i++)
|
||||
{
|
||||
_samplerStates[i]?.Dispose();
|
||||
_samplerStates[i] = null;
|
||||
}
|
||||
_randomView?.Dispose();
|
||||
_randomView = null;
|
||||
_randomTexture?.Dispose();
|
||||
_randomTexture = null;
|
||||
_targetView?.Dispose();
|
||||
_targetView = null;
|
||||
_targetTexture?.Dispose();
|
||||
_targetTexture = null;
|
||||
_targetWidth = 0;
|
||||
_targetHeight = 0;
|
||||
_stagingTexture?.Dispose();
|
||||
_stagingTexture = null;
|
||||
_stagingWidth = 0;
|
||||
_stagingHeight = 0;
|
||||
_constantBuffer?.Dispose();
|
||||
_constantBuffer = null;
|
||||
_rasterizer?.Dispose();
|
||||
_rasterizer = null;
|
||||
_vertexShader?.Dispose();
|
||||
_vertexShader = null;
|
||||
_context?.Dispose();
|
||||
_context = null;
|
||||
_device?.Dispose();
|
||||
_device = null;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -107,4 +107,9 @@
|
||||
<data name="DiagnosticCompile" xml:space="preserve"><value>خطأ في بناء الجملة</value></data>
|
||||
<data name="DiagnosticRuntime" xml:space="preserve"><value>خطأ وقت التشغيل</value></data>
|
||||
<data name="DiagnosticTimeout" xml:space="preserve"><value>انتهت المهلة</value></data>
|
||||
<data name="AnchorGroup" xml:space="preserve"><value>مرساة</value></data>
|
||||
<data name="AnchorX" xml:space="preserve"><value>X</value></data>
|
||||
<data name="AnchorY" xml:space="preserve"><value>Y</value></data>
|
||||
<data name="AnchorZ" xml:space="preserve"><value>Z</value></data>
|
||||
<data name="AnchorDesc" xml:space="preserve"><value>إحداثيات نقطة الإرساء المحددة</value></data>
|
||||
</root>
|
||||
@@ -47,3 +47,8 @@ LuaFileFilter,,Luaスクリプト (*.lua)|*.lua|すべてのファイル (*.*)|*
|
||||
DiagnosticCompile,,構文エラー,Syntax error,语法错误,語法錯誤,구문 오류,Error de sintaxis,خطأ في بناء الجملة,Kesalahan sintaksis
|
||||
DiagnosticRuntime,,実行時エラー,Runtime error,运行时错误,執行時錯誤,런타임 오류,Error de ejecución,خطأ وقت التشغيل,Kesalahan runtime
|
||||
DiagnosticTimeout,,タイムアウト,Timed out,执行超时,執行逾時,시간 초과,Tiempo de espera agotado,انتهت المهلة,Waktu habis
|
||||
AnchorGroup,,アンカー,Anchor,锚点,錨點,앵커,Anclaje,مرساة,Jangkar
|
||||
AnchorX,,X,X,X,X,X,X,X,X
|
||||
AnchorY,,Y,Y,Y,Y,Y,Y,Y,Y
|
||||
AnchorZ,,Z,Z,Z,Z,Z,Z,Z,Z
|
||||
AnchorDesc,,選択中のアンカーポイントの座標,Coordinate of the selected anchor point,所选锚点的坐标,所選錨點的座標,선택한 앵커 포인트의 좌표,Coordenada del punto de anclaje seleccionado,إحداثيات نقطة الإرساء المحددة,Koordinat titik jangkar yang dipilih
|
||||
|
@@ -107,4 +107,9 @@
|
||||
<data name="DiagnosticCompile" xml:space="preserve"><value>Syntax error</value></data>
|
||||
<data name="DiagnosticRuntime" xml:space="preserve"><value>Runtime error</value></data>
|
||||
<data name="DiagnosticTimeout" xml:space="preserve"><value>Timed out</value></data>
|
||||
<data name="AnchorGroup" xml:space="preserve"><value>Anchor</value></data>
|
||||
<data name="AnchorX" xml:space="preserve"><value>X</value></data>
|
||||
<data name="AnchorY" xml:space="preserve"><value>Y</value></data>
|
||||
<data name="AnchorZ" xml:space="preserve"><value>Z</value></data>
|
||||
<data name="AnchorDesc" xml:space="preserve"><value>Coordinate of the selected anchor point</value></data>
|
||||
</root>
|
||||
@@ -107,4 +107,9 @@
|
||||
<data name="DiagnosticCompile" xml:space="preserve"><value>Error de sintaxis</value></data>
|
||||
<data name="DiagnosticRuntime" xml:space="preserve"><value>Error de ejecución</value></data>
|
||||
<data name="DiagnosticTimeout" xml:space="preserve"><value>Tiempo de espera agotado</value></data>
|
||||
<data name="AnchorGroup" xml:space="preserve"><value>Anclaje</value></data>
|
||||
<data name="AnchorX" xml:space="preserve"><value>X</value></data>
|
||||
<data name="AnchorY" xml:space="preserve"><value>Y</value></data>
|
||||
<data name="AnchorZ" xml:space="preserve"><value>Z</value></data>
|
||||
<data name="AnchorDesc" xml:space="preserve"><value>Coordenada del punto de anclaje seleccionado</value></data>
|
||||
</root>
|
||||
@@ -107,4 +107,9 @@
|
||||
<data name="DiagnosticCompile" xml:space="preserve"><value>Kesalahan sintaksis</value></data>
|
||||
<data name="DiagnosticRuntime" xml:space="preserve"><value>Kesalahan runtime</value></data>
|
||||
<data name="DiagnosticTimeout" xml:space="preserve"><value>Waktu habis</value></data>
|
||||
<data name="AnchorGroup" xml:space="preserve"><value>Jangkar</value></data>
|
||||
<data name="AnchorX" xml:space="preserve"><value>X</value></data>
|
||||
<data name="AnchorY" xml:space="preserve"><value>Y</value></data>
|
||||
<data name="AnchorZ" xml:space="preserve"><value>Z</value></data>
|
||||
<data name="AnchorDesc" xml:space="preserve"><value>Koordinat titik jangkar yang dipilih</value></data>
|
||||
</root>
|
||||
@@ -107,4 +107,9 @@
|
||||
<data name="DiagnosticCompile" xml:space="preserve"><value>구문 오류</value></data>
|
||||
<data name="DiagnosticRuntime" xml:space="preserve"><value>런타임 오류</value></data>
|
||||
<data name="DiagnosticTimeout" xml:space="preserve"><value>시간 초과</value></data>
|
||||
<data name="AnchorGroup" xml:space="preserve"><value>앵커</value></data>
|
||||
<data name="AnchorX" xml:space="preserve"><value>X</value></data>
|
||||
<data name="AnchorY" xml:space="preserve"><value>Y</value></data>
|
||||
<data name="AnchorZ" xml:space="preserve"><value>Z</value></data>
|
||||
<data name="AnchorDesc" xml:space="preserve"><value>선택한 앵커 포인트의 좌표</value></data>
|
||||
</root>
|
||||
@@ -107,4 +107,9 @@
|
||||
<data name="DiagnosticCompile" xml:space="preserve"><value>構文エラー</value></data>
|
||||
<data name="DiagnosticRuntime" xml:space="preserve"><value>実行時エラー</value></data>
|
||||
<data name="DiagnosticTimeout" xml:space="preserve"><value>タイムアウト</value></data>
|
||||
<data name="AnchorGroup" xml:space="preserve"><value>アンカー</value></data>
|
||||
<data name="AnchorX" xml:space="preserve"><value>X</value></data>
|
||||
<data name="AnchorY" xml:space="preserve"><value>Y</value></data>
|
||||
<data name="AnchorZ" xml:space="preserve"><value>Z</value></data>
|
||||
<data name="AnchorDesc" xml:space="preserve"><value>選択中のアンカーポイントの座標</value></data>
|
||||
</root>
|
||||
@@ -107,4 +107,9 @@
|
||||
<data name="DiagnosticCompile" xml:space="preserve"><value>语法错误</value></data>
|
||||
<data name="DiagnosticRuntime" xml:space="preserve"><value>运行时错误</value></data>
|
||||
<data name="DiagnosticTimeout" xml:space="preserve"><value>执行超时</value></data>
|
||||
<data name="AnchorGroup" xml:space="preserve"><value>锚点</value></data>
|
||||
<data name="AnchorX" xml:space="preserve"><value>X</value></data>
|
||||
<data name="AnchorY" xml:space="preserve"><value>Y</value></data>
|
||||
<data name="AnchorZ" xml:space="preserve"><value>Z</value></data>
|
||||
<data name="AnchorDesc" xml:space="preserve"><value>所选锚点的坐标</value></data>
|
||||
</root>
|
||||
@@ -107,4 +107,9 @@
|
||||
<data name="DiagnosticCompile" xml:space="preserve"><value>語法錯誤</value></data>
|
||||
<data name="DiagnosticRuntime" xml:space="preserve"><value>執行時錯誤</value></data>
|
||||
<data name="DiagnosticTimeout" xml:space="preserve"><value>執行逾時</value></data>
|
||||
<data name="AnchorGroup" xml:space="preserve"><value>錨點</value></data>
|
||||
<data name="AnchorX" xml:space="preserve"><value>X</value></data>
|
||||
<data name="AnchorY" xml:space="preserve"><value>Y</value></data>
|
||||
<data name="AnchorZ" xml:space="preserve"><value>Z</value></data>
|
||||
<data name="AnchorDesc" xml:space="preserve"><value>所選錨點的座標</value></data>
|
||||
</root>
|
||||
@@ -4,7 +4,7 @@
|
||||
<TargetFramework>net10.0-windows10.0.19041.0</TargetFramework>
|
||||
<UseWPF>true</UseWPF>
|
||||
<ImplicitUsings>enable</ImplicitUsings>
|
||||
<Version>1.13.4</Version>
|
||||
<Version>1.16.3</Version>
|
||||
<Platforms>AnyCPU;x64</Platforms>
|
||||
<Nullable>enable</Nullable>
|
||||
<AllowUnsafeBlocks>true</AllowUnsafeBlocks>
|
||||
|
||||
@@ -58,14 +58,28 @@
|
||||
obj.setpixel(x, y, r2, g2, b2 [, a2])
|
||||
end
|
||||
end
|
||||
الشكل التالي الذي يستخدم getpixeldata يتحول إلى نواة أيضاً.
|
||||
local data = obj.getpixeldata()
|
||||
for y = 0, data.height - 1 do
|
||||
for x = 0, data.width - 1 do
|
||||
local i = (y * data.width + x) * 4
|
||||
local r = data:get(i + 1)
|
||||
data:set(i + 1, r2)
|
||||
data:set(i + 2, g2)
|
||||
data:set(i + 3, b2)
|
||||
end
|
||||
end
|
||||
obj.putpixeldata(data)
|
||||
· يجوز في الجسم استخدام العمليات الحسابية و math.* والمقارنات
|
||||
وصيغة العتبة "cond and value1 or value2" ومتغيرات local فقط.
|
||||
· يجوز الإشارة فقط إلى البكسل الجاري معالجته (getpixel(x, y))
|
||||
وقيم مثل obj/scene/time.
|
||||
وصيغة العتبة "cond and value1 or value2" والإسناد الشرطي إلى
|
||||
متغيرات local عبر if/elseif/else ومتغيرات local فقط.
|
||||
· يجوز أيضاً استخدام أسماء بديلة لحدود الحلقة مثل local w = obj.w.
|
||||
· يجوز الإشارة فقط إلى البكسل الجاري معالجته وقيم مثل
|
||||
obj/scene/time.
|
||||
· أي استخدام لأخذ عينات الجوار (التمويه، إلخ) أو الكتابة إلى
|
||||
إحداثيات أخرى أو getpixeldata أو getobject أو عمليات
|
||||
الجداول/السلاسل أو جُمَل if لا يتحول إلى نواة ويُنفَّذ تلقائياً
|
||||
على المحرك التقليدي.
|
||||
إحداثيات أخرى أو استدعاء setpixel أو set داخل جملة if أو
|
||||
getobject أو عمليات الجداول/السلاسل لا يتحول إلى نواة
|
||||
ويُنفَّذ تلقائياً على المحرك التقليدي.
|
||||
|
||||
مثال (يجعل شكلاً أبيض أحمر):
|
||||
--!gpu
|
||||
@@ -502,7 +516,47 @@
|
||||
"cache:الاسم" : ذاكرة مخبّأة مُسمّاة (تُحفظ بين الإطارات)
|
||||
مثال: obj.copybuffer("tmp", "obj") -- حفظ
|
||||
obj.copybuffer("obj", "tmp") -- استعادة
|
||||
※ "frm" (مخزن الإطار / الخلفية) لا يمكن الحصول عليه بسبب بنية YMM4.
|
||||
※ يمكن استخدام "frm" (مخزن الإطار) كمصدر نسخ. محتواه صورة افتراضية
|
||||
تنشأ بتركيب الكائن في موضعه الحالي فوق منطقة شفافة بحجم المشهد.
|
||||
لا يستطيع YMM4 الوصول إلى الخلفية، لذلك لا تتضمن الخلفية.
|
||||
لا يمكن استخدامه كوجهة نسخ.
|
||||
|
||||
○ obj.pixelshader(الاسم، الوجهة، الموارد [, الثوابت [, blend [, sampler]]])
|
||||
ينفذ على وحدة معالجة الرسومات مظلل بكسلات HLSL معرفا داخل السكربت.
|
||||
تعرف المظللات في تعليق متعدد الأسطر بنفس صيغة AviUtl ExEdit2،
|
||||
ويصبح الاسم المسجل نقطة الدخول.
|
||||
--[[pixelshader@name:
|
||||
Texture2D src : register(t0);
|
||||
float4 name(float4 pos : SV_Position) : SV_Target { ... }
|
||||
]]
|
||||
الاسم : اسم المظلل المعرف كسلسلة نصية.
|
||||
الوجهة : واحدة من "object" أو "tempbuffer" أو "cache:اسم" أو
|
||||
"framebuffer". يرسم "framebuffer" في مخزن إطار افتراضي
|
||||
بحجم المشهد ويستبدل صورة الكائن بالنتيجة.
|
||||
الموارد : مصفوفة أسماء المخازن المؤقتة المربوطة بالسجلات t0-t7.
|
||||
يمكن تمرير اسم واحد مباشرة كسلسلة نصية. يربط "random"
|
||||
منطقة 256x256 بتنسيق R32_FLOAT من قيم عشوائية بين
|
||||
0.0 و1.0. يربط "framebuffer" مخزن الإطار الافتراضي
|
||||
بحجم المشهد مع الكائن مركبا في موضعه الحالي.
|
||||
الثوابت : مصفوفة أرقام تعبأ في مخزن الثوابت b0 كمصفوفة float.
|
||||
blend : واحد من "copy" (كما هو) أو "mask" (ضرب قيمة ألفا فقط)
|
||||
أو "draw" (مزج ألفا) أو "add" (إضافي). الافتراضي "copy".
|
||||
تمرير رقم مطابق لوضع obj.setoption("blend", n) يركب
|
||||
مخرج المظلل على الوجهة بوضع المزج المقابل في YMM4.
|
||||
sampler : واحد من "clip" أو "clamp" أو "loop" أو "mirror" أو
|
||||
"dot". يربط بـ SamplerState s0. غير معين عند الحذف.
|
||||
يمكن أن يكون مدخل مظلل البكسلات أحد التالي.
|
||||
float4 name(float4 pos : SV_Position) : SV_Target
|
||||
float4 name(float4 pos : SV_Position, float2 uv : TEXCOORD) : SV_Target
|
||||
يعين uv بحيث تمتد منطقة الرسم من 0.0 إلى 1.0.
|
||||
مثال: obj.pixelshader("ps", "object", "object", {obj.track0}, "copy")
|
||||
* يعمل على المحركين معا. ينفذ المظلل نفسه دائما على وحدة معالجة
|
||||
الرسومات في جانب المضيف.
|
||||
* لا يستطيع YMM4 الوصول إلى الخلفية، لذلك المحتوى الأولي لـ
|
||||
"framebuffer" صورة افتراضية تنشأ بتركيب الكائن فوق منطقة شفافة
|
||||
بحجم المشهد.
|
||||
* يتخطى الاستدعاء في البيئات التي لا تتوفر فيها وحدة معالجة
|
||||
رسومات صالحة.
|
||||
|
||||
○ obj.getvalue(الهدف)
|
||||
يحصل على القيمة الحالية لـ obj (مثل obj.x و obj.track0).
|
||||
@@ -579,7 +633,8 @@
|
||||
"arm" : يصل مركز الكائن بكل نقطة إرساء بالترتيب.
|
||||
"xyz" : يعامل النقاط كإحداثيات ثلاثية الأبعاد. الافتراضي ثنائي.
|
||||
يعيد عدد نقاط الإرساء. يعمل في المحركين معاً.
|
||||
وضع شريط "track" غير مدعوم حالياً ويعيد 0.
|
||||
يُدعم أيضاً الاسم "track"؛ وتضع القيمة 0 نقطة واحدة.
|
||||
يمكن ضبط نقطة الإرساء المحددة رقمياً عبر منزلقات X / Y / Z في مجموعة مرساة.
|
||||
مثال:
|
||||
num = obj.track0
|
||||
obj.setanchor("pos", num, "loop")
|
||||
@@ -725,6 +780,63 @@
|
||||
pcall, xpcall
|
||||
|
||||
|
||||
- امتدادات الصياغة -
|
||||
|
||||
تمت إضافة بعض الصيغ غير الموجودة في Lua القياسية. يجري تحويل النص البرمجي
|
||||
قبل التنفيذ، لذلك تعمل بالطريقة نفسها على جميع المحركات. لا يجري تحويل ما
|
||||
بداخل السلاسل النصية والتعليقات.
|
||||
|
||||
○ is / is not
|
||||
a is b تعني a == b، و a is not b تعني a ~= b.
|
||||
مثال: if frame is not 0 then
|
||||
obj.x = 100
|
||||
end
|
||||
|
||||
○ != / ! / && / ||
|
||||
!= تعني ~=، و ! تعني not، و && تعني and، و || تعني or.
|
||||
|
||||
○ الإسناد المركب (+= -= *= /= %= ^= ..=)
|
||||
x += 1 يتوسع إلى x = x + (1). و ..= لدمج السلاسل النصية.
|
||||
|
||||
○ ?? (دمج القيمة الفارغة)
|
||||
a ?? b يعيد b فقط عندما تكون a فارغة (nil)، ولا يرجع إلى false.
|
||||
|
||||
○ ??= / ||= / &&=
|
||||
x ??= b يسند فقط عندما تكون x فارغة (nil).
|
||||
x ||= b هو x = x or (b)، و x &&= b هو x = x and (b).
|
||||
|
||||
○ ++
|
||||
x++ يتوسع إلى x = x + 1. استخدمه كعبارة في سطر مستقل.
|
||||
|
||||
○ حلقة النطاق (<البداية..النهاية>)
|
||||
for i in <0..10> do مثل for i = 0, 10 do ويشمل النهاية.
|
||||
<0..<10> لا يشمل النهاية. <0..10, 2> يستخدم خطوة 2.
|
||||
|
||||
○ العامل الثلاثي (? :)
|
||||
cond ? a : b يعيد a عندما يكون cond صحيحًا، و b خلاف ذلك.
|
||||
يعيد فرع false أو nil كما هو.
|
||||
|
||||
○ المعامل الشرطي للقيمة الفارغة nil (?. ?[ ])
|
||||
t?.x يعيد nil عندما تكون t فارغة (nil)، وإلا فإنه يعيد t.x.
|
||||
t?[k] وصول بالفهرس. تُقيَّم t مرة واحدة.
|
||||
|
||||
○ دالة لامدا (=>)
|
||||
(a, b) => expr يتوسع إلى (function(a, b) return expr end).
|
||||
استخدم x => expr لوسيط واحد، أو () => expr لعدم وجود وسائط.
|
||||
|
||||
○ الأنبوب (|>)
|
||||
x |> f يتوسع إلى f((x))، ويمرر الطرف الأيسر كوسيط أول.
|
||||
x |> f(a, b) يصبح f((x), a, b). يمكن تسلسل |>.
|
||||
|
||||
○ السلسلة النصية المُدمَجة (`...`)
|
||||
`x={a}` يتوسع إلى ("x=" .. tostring(a)).
|
||||
اكتب تعبيرًا داخل { }، حيث تتوفر أيضًا الصيغ الموسّعة.
|
||||
|
||||
○ فحص النطاق (in <..>)
|
||||
x in <1..5> يفحص 1 <= x and x <= 5.
|
||||
<1..<5> لا يشمل الحد الأعلى. يُقيَّم الطرف الأيسر مرة واحدة.
|
||||
|
||||
|
||||
- أمثلة على النصوص البرمجية -
|
||||
|
||||
○ تلاشٍ تدريجي للظهور - fade-in (النص الافتراضي)
|
||||
@@ -846,12 +958,11 @@
|
||||
× تحميل الوحدات عبر require، والوصول العشوائي إلى الملفات مثل
|
||||
io / dofile (تحميل الصور / الفيديو عبر obj.load مدعوم مع التحقق
|
||||
من الترويسة).
|
||||
× obj.setanchor وما شابه.
|
||||
|
||||
|
||||
- الميزات غير المدعومة / القيود -
|
||||
|
||||
× obj.rand1()، obj.mes()، obj.setanchor() وما شابه من AviUtl2 غير مدعومة.
|
||||
× obj.rand1()، obj.mes() وما شابه من AviUtl2 غير مدعومة.
|
||||
× الوصول العشوائي إلى الملفات من النصوص (require, dofile, io وما شابه) غير مدعوم.
|
||||
فقط obj.load("image"/"movie") يحمّل الملفات المؤكَّد أنها وسائط أصلية عبر
|
||||
التحقق من الترويسة الأولى.
|
||||
|
||||
@@ -60,15 +60,29 @@
|
||||
obj.setpixel(x, y, r2, g2, b2 [, a2])
|
||||
end
|
||||
end
|
||||
The following form using getpixeldata becomes a kernel as well.
|
||||
local data = obj.getpixeldata()
|
||||
for y = 0, data.height - 1 do
|
||||
for x = 0, data.width - 1 do
|
||||
local i = (y * data.width + x) * 4
|
||||
local r = data:get(i + 1)
|
||||
data:set(i + 1, r2)
|
||||
data:set(i + 2, g2)
|
||||
data:set(i + 3, b2)
|
||||
end
|
||||
end
|
||||
obj.putpixeldata(data)
|
||||
- The body may use only arithmetic, math.*, comparisons, the
|
||||
threshold idiom "cond and value1 or value2", and local
|
||||
threshold idiom "cond and value1 or value2", conditional
|
||||
assignment to local variables via if/elseif/else, and local
|
||||
variables.
|
||||
- It may reference only the current pixel being processed
|
||||
(getpixel(x, y)) and values such as obj/scene/time.
|
||||
- Loop bounds may also use aliases such as local w = obj.w.
|
||||
- It may reference only the current pixel being processed and
|
||||
values such as obj/scene/time.
|
||||
- Anything using neighbor sampling (blur, etc.), writes to other
|
||||
coordinates, getpixeldata, getobject, table/string operations,
|
||||
or if statements is not turned into a kernel and automatically
|
||||
runs on the classic engine.
|
||||
coordinates, setpixel or set calls inside an if statement,
|
||||
getobject, or table/string operations is not turned into a
|
||||
kernel and automatically runs on the classic engine.
|
||||
|
||||
Example (turns a white figure red):
|
||||
--!gpu
|
||||
@@ -518,8 +532,50 @@
|
||||
"cache:name" : Named cache (kept across frames)
|
||||
Example: obj.copybuffer("tmp", "obj") -- save
|
||||
obj.copybuffer("obj", "tmp") -- restore
|
||||
* "frm" (frame buffer / background) cannot be obtained due to the
|
||||
structure of YMM4.
|
||||
* "frm" (frame buffer) can be used as a copy source. Its content is
|
||||
a virtual image made by compositing the object at its current
|
||||
position onto a transparent scene-sized area. YMM4 cannot access
|
||||
the background, so the background is not included. It cannot be
|
||||
used as a copy destination.
|
||||
|
||||
o obj.pixelshader(name, target, resources [, constants [, blend [, sampler]]])
|
||||
Runs an HLSL pixel shader defined inside the script on the GPU.
|
||||
Shaders are defined in a multi-line comment using the same notation
|
||||
as AviUtl ExEdit2; the registered name becomes the entry point.
|
||||
--[[pixelshader@name:
|
||||
Texture2D src : register(t0);
|
||||
float4 name(float4 pos : SV_Position) : SV_Target { ... }
|
||||
]]
|
||||
name : Name of the defined shader as a string.
|
||||
target : One of "object", "tempbuffer", "cache:name",
|
||||
"framebuffer". "framebuffer" renders into a scene-sized
|
||||
virtual frame buffer and replaces the object image with
|
||||
the result.
|
||||
resources : Array of buffer names bound to t0-t7. A single name can
|
||||
be passed directly as a string. "random" binds a 256x256
|
||||
region (R32_FLOAT) of random values in 0.0-1.0.
|
||||
"framebuffer" binds the scene-sized virtual frame buffer
|
||||
with the object composited at its current position.
|
||||
constants : Array of numbers, packed into constant buffer b0 as an
|
||||
array of floats.
|
||||
blend : "copy" (as is), "mask" (multiplies alpha only), "draw"
|
||||
(alpha blend), "add" (additive). Default is "copy".
|
||||
Passing a number equal to an obj.setoption("blend", n)
|
||||
mode composites the shader output onto the target with
|
||||
the corresponding YMM4 blend mode.
|
||||
sampler : One of "clip", "clamp", "loop", "mirror", "dot". Bound
|
||||
to SamplerState s0. Unset when omitted.
|
||||
The pixel shader input can be either of the following.
|
||||
float4 name(float4 pos : SV_Position) : SV_Target
|
||||
float4 name(float4 pos : SV_Position, float2 uv : TEXCOORD) : SV_Target
|
||||
uv is set so that the drawing area spans 0.0-1.0.
|
||||
Example: obj.pixelshader("ps", "object", "object", {obj.track0}, "copy")
|
||||
* Runs on both engines. The shader itself always executes on the
|
||||
host GPU.
|
||||
* YMM4 cannot access the background, so the initial content of
|
||||
"framebuffer" is a virtual image made by compositing the object
|
||||
onto a transparent scene-sized area.
|
||||
* The call is skipped in environments without a usable GPU.
|
||||
|
||||
o obj.getvalue(target)
|
||||
Gets the current value of obj (same as obj.x, obj.track0, etc.).
|
||||
@@ -603,7 +659,8 @@
|
||||
"arm" : connect the object center to each anchor point in order.
|
||||
"xyz" : treat the anchor points as 3D coordinates. 2D by default.
|
||||
Returns the number of anchor points. It works in both engines.
|
||||
The "track" trackbar mode is not supported yet and returns 0.
|
||||
The "track" name is also supported; a count of 0 places 1 point.
|
||||
The selected anchor can be adjusted numerically via the X / Y / Z sliders in the Anchor group.
|
||||
Example:
|
||||
num = obj.track0
|
||||
obj.setanchor("pos", num, "loop")
|
||||
@@ -752,6 +809,63 @@
|
||||
pcall, xpcall
|
||||
|
||||
|
||||
- Syntax Extensions -
|
||||
|
||||
A few notations that plain Lua does not have are added. The script is
|
||||
transformed before execution, so they work the same on every engine.
|
||||
The insides of strings and comments are not transformed.
|
||||
|
||||
o is / is not
|
||||
a is b means a == b, and a is not b means a ~= b.
|
||||
Example: if frame is not 0 then
|
||||
obj.x = 100
|
||||
end
|
||||
|
||||
o != / ! / && / ||
|
||||
!= means ~=, ! means not, && means and, and || means or.
|
||||
|
||||
o Compound assignment (+= -= *= /= %= ^= ..=)
|
||||
x += 1 expands to x = x + (1). ..= concatenates strings.
|
||||
|
||||
o ?? (nil coalescing)
|
||||
a ?? b returns b only when a is nil. It does not fall back on false.
|
||||
|
||||
o ??= / ||= / &&=
|
||||
x ??= b assigns only when x is nil.
|
||||
x ||= b is x = x or (b), and x &&= b is x = x and (b).
|
||||
|
||||
o ++
|
||||
x++ expands to x = x + 1. Use it as a statement on its own line.
|
||||
|
||||
o Range for (<start..stop>)
|
||||
for i in <0..10> do is the same as for i = 0, 10 do and includes the end.
|
||||
<0..<10> excludes the end. <0..10, 2> uses a step of 2.
|
||||
|
||||
o Ternary (? :)
|
||||
cond ? a : b returns a when cond is truthy and b otherwise.
|
||||
It returns the false or nil branch as is.
|
||||
|
||||
o nil-conditional (?. ?[ ])
|
||||
t?.x returns nil when t is nil, otherwise t.x.
|
||||
t?[k] is index access. t is evaluated once.
|
||||
|
||||
o Lambda (=>)
|
||||
(a, b) => expr expands to (function(a, b) return expr end).
|
||||
Use x => expr for a single parameter, or () => expr for none.
|
||||
|
||||
o Pipe (|>)
|
||||
x |> f expands to f((x)), passing the left side as the first argument.
|
||||
x |> f(a, b) becomes f((x), a, b). |> can be chained.
|
||||
|
||||
o Interpolated string (`...`)
|
||||
`x={a}` expands to ("x=" .. tostring(a)).
|
||||
Write an expression inside { }, where extension syntax is also available.
|
||||
|
||||
o Range check (in <..>)
|
||||
x in <1..5> tests 1 <= x and x <= 5.
|
||||
<1..<5> excludes the upper bound. The left side is evaluated once.
|
||||
|
||||
|
||||
- Script Examples -
|
||||
|
||||
o Fade in (default script)
|
||||
@@ -878,12 +992,11 @@
|
||||
x Module loading via require, and arbitrary file access such as io /
|
||||
dofile (image / video loading via obj.load is supported with header
|
||||
validation).
|
||||
x obj.setanchor, etc.
|
||||
|
||||
|
||||
- Unsupported Features / Limitations -
|
||||
|
||||
x obj.rand1(), obj.mes(), obj.setanchor(), etc. from AviUtl2 are not supported.
|
||||
x obj.rand1(), obj.mes(), etc. from AviUtl2 are not supported.
|
||||
x Arbitrary file access from scripts (require, dofile, io, etc.) is not supported.
|
||||
Only obj.load("image"/"movie") loads files confirmed to be genuine media by
|
||||
leading-header validation.
|
||||
|
||||
@@ -61,14 +61,31 @@
|
||||
obj.setpixel(x, y, r2, g2, b2 [, a2])
|
||||
end
|
||||
end
|
||||
La siguiente forma con getpixeldata también se convierte en núcleo.
|
||||
local data = obj.getpixeldata()
|
||||
for y = 0, data.height - 1 do
|
||||
for x = 0, data.width - 1 do
|
||||
local i = (y * data.width + x) * 4
|
||||
local r = data:get(i + 1)
|
||||
data:set(i + 1, r2)
|
||||
data:set(i + 2, g2)
|
||||
data:set(i + 3, b2)
|
||||
end
|
||||
end
|
||||
obj.putpixeldata(data)
|
||||
- El cuerpo solo puede usar aritmética, math.*, comparaciones, el
|
||||
modismo de umbral "cond and valor1 or valor2" y variables local.
|
||||
- Solo puede referenciar el píxel actual en proceso
|
||||
(getpixel(x, y)) y valores como obj/scene/time.
|
||||
modismo de umbral "cond and valor1 or valor2", la asignación
|
||||
condicional a variables local mediante if/elseif/else y
|
||||
variables local.
|
||||
- Los límites del bucle también pueden usar alias como
|
||||
local w = obj.w.
|
||||
- Solo puede referenciar el píxel actual en proceso y valores
|
||||
como obj/scene/time.
|
||||
- Todo lo que use muestreo de vecinos (desenfoque, etc.),
|
||||
escrituras en otras coordenadas, getpixeldata, getobject,
|
||||
operaciones de tabla/cadena o sentencias if no se convierte en
|
||||
núcleo y se ejecuta automáticamente en el motor clásico.
|
||||
escrituras en otras coordenadas, llamadas a setpixel o set
|
||||
dentro de una sentencia if, getobject u operaciones de
|
||||
tabla/cadena no se convierte en núcleo y se ejecuta
|
||||
automáticamente en el motor clásico.
|
||||
|
||||
Ejemplo (vuelve roja una figura blanca):
|
||||
--!gpu
|
||||
@@ -518,8 +535,53 @@
|
||||
"cache:nombre" : Caché con nombre (se conserva entre fotogramas)
|
||||
Ejemplo: obj.copybuffer("tmp", "obj") -- guardar
|
||||
obj.copybuffer("obj", "tmp") -- restaurar
|
||||
* "frm" (búfer de fotograma / fondo) no puede obtenerse por la
|
||||
estructura de YMM4.
|
||||
* "frm" (búfer de fotograma) puede usarse como origen de copia. Su
|
||||
contenido es una imagen virtual creada componiendo el objeto en su
|
||||
posicion actual sobre un area transparente del tamano de la
|
||||
escena. YMM4 no puede acceder al fondo, por lo que el fondo no se
|
||||
incluye. No puede usarse como destino de copia.
|
||||
|
||||
o obj.pixelshader(nombre, destino, recursos [, constantes [, blend [, sampler]]])
|
||||
Ejecuta en la GPU un sombreador de pixeles HLSL definido dentro del
|
||||
script. Los sombreadores se definen en un comentario multilinea con
|
||||
la misma notacion que AviUtl ExEdit2; el nombre registrado se
|
||||
convierte en el punto de entrada.
|
||||
--[[pixelshader@nombre:
|
||||
Texture2D src : register(t0);
|
||||
float4 nombre(float4 pos : SV_Position) : SV_Target { ... }
|
||||
]]
|
||||
nombre : Nombre del sombreador definido, como cadena.
|
||||
destino : Uno de "object", "tempbuffer", "cache:nombre",
|
||||
"framebuffer". "framebuffer" dibuja en un bufer de
|
||||
fotograma virtual del tamano de la escena y reemplaza
|
||||
la imagen del objeto con el resultado.
|
||||
recursos : Arreglo de nombres de bufer asignados a t0-t7. Un solo
|
||||
nombre puede pasarse directamente como cadena. "random"
|
||||
asigna una region de 256x256 (R32_FLOAT) con valores
|
||||
aleatorios entre 0.0 y 1.0. "framebuffer" asigna el
|
||||
bufer de fotograma virtual del tamano de la escena con
|
||||
el objeto compuesto en su posicion actual.
|
||||
constantes : Arreglo de numeros, empaquetado en el bufer de
|
||||
constantes b0 como arreglo de floats.
|
||||
blend : "copy" (tal cual), "mask" (multiplica solo el alfa),
|
||||
"draw" (mezcla alfa), "add" (aditivo). Por defecto
|
||||
"copy". Pasar un numero igual a un modo de
|
||||
obj.setoption("blend", n) compone la salida del
|
||||
sombreador sobre el destino con el modo de fusion de
|
||||
YMM4 correspondiente.
|
||||
sampler : Uno de "clip", "clamp", "loop", "mirror", "dot". Se
|
||||
asigna a SamplerState s0. Sin asignar si se omite.
|
||||
La entrada del sombreador puede ser cualquiera de las siguientes.
|
||||
float4 nombre(float4 pos : SV_Position) : SV_Target
|
||||
float4 nombre(float4 pos : SV_Position, float2 uv : TEXCOORD) : SV_Target
|
||||
uv se configura para que el area de dibujo abarque 0.0-1.0.
|
||||
Ejemplo: obj.pixelshader("ps", "object", "object", {obj.track0}, "copy")
|
||||
* Funciona en ambos motores. El sombreador siempre se ejecuta en la
|
||||
GPU del lado del host.
|
||||
* YMM4 no puede acceder al fondo, por lo que el contenido inicial de
|
||||
"framebuffer" es una imagen virtual creada componiendo el objeto
|
||||
sobre un area transparente del tamano de la escena.
|
||||
* La llamada se omite en entornos sin una GPU utilizable.
|
||||
|
||||
o obj.getvalue(target)
|
||||
Obtiene el valor actual de obj (igual que obj.x, obj.track0, etc.).
|
||||
@@ -611,7 +673,8 @@
|
||||
"arm" : une el centro del objeto con cada punto en orden.
|
||||
"xyz" : trata los puntos como coordenadas 3D. 2D por defecto.
|
||||
Devuelve el número de puntos de anclaje. Funciona en ambos motores.
|
||||
El modo de barra "track" aún no se admite y devuelve 0.
|
||||
El nombre "track" también se admite; una cantidad de 0 coloca 1 punto.
|
||||
El ancla seleccionada puede ajustarse numéricamente con los deslizadores X / Y / Z del grupo Anclaje.
|
||||
Ejemplo:
|
||||
num = obj.track0
|
||||
obj.setanchor("pos", num, "loop")
|
||||
@@ -762,6 +825,63 @@
|
||||
pcall, xpcall
|
||||
|
||||
|
||||
- Extensiones de sintaxis -
|
||||
|
||||
Se añaden algunas notaciones que Lua estándar no tiene. El script se
|
||||
transforma antes de ejecutarse, por lo que funcionan igual en todos los
|
||||
motores. El interior de las cadenas y los comentarios no se transforma.
|
||||
|
||||
o is / is not
|
||||
a is b significa a == b, y a is not b significa a ~= b.
|
||||
Ejemplo: if frame is not 0 then
|
||||
obj.x = 100
|
||||
end
|
||||
|
||||
o != / ! / && / ||
|
||||
!= significa ~=, ! significa not, && significa and y || significa or.
|
||||
|
||||
o Asignación compuesta (+= -= *= /= %= ^= ..=)
|
||||
x += 1 se expande a x = x + (1). ..= concatena cadenas.
|
||||
|
||||
o ?? (fusión de nil)
|
||||
a ?? b devuelve b solo cuando a es nil. No recurre a false.
|
||||
|
||||
o ??= / ||= / &&=
|
||||
x ??= b asigna solo cuando x es nil.
|
||||
x ||= b es x = x or (b), y x &&= b es x = x and (b).
|
||||
|
||||
o ++
|
||||
x++ se expande a x = x + 1. Úsalo como una sentencia en su propia línea.
|
||||
|
||||
o for de rango (<inicio..fin>)
|
||||
for i in <0..10> do es igual que for i = 0, 10 do e incluye el final.
|
||||
<0..<10> excluye el final. <0..10, 2> usa un incremento de 2.
|
||||
|
||||
o Operador ternario (? :)
|
||||
cond ? a : b devuelve a cuando cond es verdadero y b en caso contrario.
|
||||
Devuelve la rama false o nil tal cual.
|
||||
|
||||
o Condicional de nil (?. ?[ ])
|
||||
t?.x devuelve nil cuando t es nil; en caso contrario, t.x.
|
||||
t?[k] es acceso por índice. t se evalúa una sola vez.
|
||||
|
||||
o Lambda (=>)
|
||||
(a, b) => expr se expande a (function(a, b) return expr end).
|
||||
Usa x => expr para un solo parámetro, o () => expr para ninguno.
|
||||
|
||||
o Tubería (|>)
|
||||
x |> f se expande a f((x)), pasando el lado izquierdo como primer argumento.
|
||||
x |> f(a, b) se convierte en f((x), a, b). |> se puede encadenar.
|
||||
|
||||
o Cadena interpolada (`...`)
|
||||
`x={a}` se expande a ("x=" .. tostring(a)).
|
||||
Escribe una expresión dentro de { }, donde también está disponible la sintaxis extendida.
|
||||
|
||||
o Comprobación de rango (in <..>)
|
||||
x in <1..5> comprueba 1 <= x and x <= 5.
|
||||
<1..<5> excluye el límite superior. El lado izquierdo se evalúa una sola vez.
|
||||
|
||||
|
||||
- Ejemplos de script -
|
||||
|
||||
o Fundido de entrada (script predeterminado)
|
||||
@@ -892,12 +1012,11 @@
|
||||
x Carga de módulos mediante require y acceso arbitrario a archivos como
|
||||
io / dofile (la carga de imagen / vídeo con obj.load sí se admite con
|
||||
validación de cabecera).
|
||||
x obj.setanchor, etc.
|
||||
|
||||
|
||||
- Funciones no admitidas / Limitaciones -
|
||||
|
||||
x obj.rand1(), obj.mes(), obj.setanchor(), etc. de AviUtl2 no son compatibles.
|
||||
x obj.rand1(), obj.mes(), etc. de AviUtl2 no son compatibles.
|
||||
x El acceso arbitrario a archivos desde scripts (require, dofile, io, etc.) no es compatible.
|
||||
Solo obj.load("image"/"movie") carga archivos confirmados como medios genuinos
|
||||
mediante validación de la cabecera inicial.
|
||||
|
||||
@@ -62,14 +62,29 @@
|
||||
obj.setpixel(x, y, r2, g2, b2 [, a2])
|
||||
end
|
||||
end
|
||||
Bentuk berikut yang memakai getpixeldata juga menjadi kernel.
|
||||
local data = obj.getpixeldata()
|
||||
for y = 0, data.height - 1 do
|
||||
for x = 0, data.width - 1 do
|
||||
local i = (y * data.width + x) * 4
|
||||
local r = data:get(i + 1)
|
||||
data:set(i + 1, r2)
|
||||
data:set(i + 2, g2)
|
||||
data:set(i + 3, b2)
|
||||
end
|
||||
end
|
||||
obj.putpixeldata(data)
|
||||
- Badan hanya boleh memakai aritmetika, math.*, perbandingan,
|
||||
idiom ambang "cond and nilai1 or nilai2", dan variabel local.
|
||||
- Hanya boleh mereferensikan piksel yang sedang diproses
|
||||
(getpixel(x, y)) dan nilai seperti obj/scene/time.
|
||||
idiom ambang "cond and nilai1 or nilai2", penugasan bersyarat
|
||||
ke variabel local melalui if/elseif/else, dan variabel local.
|
||||
- Batas perulangan juga boleh memakai alias seperti
|
||||
local w = obj.w.
|
||||
- Hanya boleh mereferensikan piksel yang sedang diproses dan
|
||||
nilai seperti obj/scene/time.
|
||||
- Apa pun yang memakai sampling tetangga (blur, dll.), penulisan
|
||||
ke koordinat lain, getpixeldata, getobject, operasi
|
||||
tabel/string, atau pernyataan if tidak diubah menjadi kernel dan
|
||||
otomatis berjalan di mesin klasik.
|
||||
ke koordinat lain, pemanggilan setpixel atau set di dalam
|
||||
pernyataan if, getobject, atau operasi tabel/string tidak
|
||||
diubah menjadi kernel dan otomatis berjalan di mesin klasik.
|
||||
|
||||
Contoh (membuat figur putih menjadi merah):
|
||||
--!gpu
|
||||
@@ -517,7 +532,52 @@
|
||||
"cache:nama" : Cache bernama (dipertahankan antar frame)
|
||||
Contoh: obj.copybuffer("tmp", "obj") -- simpan
|
||||
obj.copybuffer("obj", "tmp") -- pulihkan
|
||||
* "frm" (buffer frame / latar) tidak dapat diperoleh karena struktur YMM4.
|
||||
* "frm" (buffer frame) dapat digunakan sebagai sumber salin. Isinya
|
||||
adalah gambar virtual yang dibuat dengan mengomposisikan objek
|
||||
pada posisinya saat ini ke area transparan seukuran adegan. YMM4
|
||||
tidak dapat mengakses latar, sehingga latar tidak disertakan.
|
||||
Tidak dapat digunakan sebagai tujuan salin.
|
||||
|
||||
o obj.pixelshader(nama, target, sumber [, konstanta [, blend [, sampler]]])
|
||||
Menjalankan pixel shader HLSL yang didefinisikan di dalam skrip pada
|
||||
GPU. Shader didefinisikan dalam komentar multibaris dengan notasi
|
||||
yang sama seperti AviUtl ExEdit2; nama terdaftar menjadi entry point.
|
||||
--[[pixelshader@nama:
|
||||
Texture2D src : register(t0);
|
||||
float4 nama(float4 pos : SV_Position) : SV_Target { ... }
|
||||
]]
|
||||
nama : Nama shader yang didefinisikan, berupa string.
|
||||
target : Salah satu dari "object", "tempbuffer", "cache:nama",
|
||||
"framebuffer". "framebuffer" menggambar ke buffer frame
|
||||
virtual seukuran adegan dan mengganti gambar objek
|
||||
dengan hasilnya.
|
||||
sumber : Array nama buffer yang diikat ke t0-t7. Satu nama dapat
|
||||
diberikan langsung sebagai string. "random" mengikat
|
||||
wilayah 256x256 (R32_FLOAT) berisi nilai acak 0.0-1.0.
|
||||
"framebuffer" mengikat buffer frame virtual seukuran
|
||||
adegan dengan objek yang dikomposisikan pada posisinya
|
||||
saat ini.
|
||||
konstanta : Array angka, dikemas ke constant buffer b0 sebagai array
|
||||
float.
|
||||
blend : "copy" (apa adanya), "mask" (hanya mengalikan alfa),
|
||||
"draw" (alpha blend), "add" (aditif). Bawaan "copy".
|
||||
Memberikan angka yang sama dengan mode
|
||||
obj.setoption("blend", n) akan mengomposisikan keluaran
|
||||
shader ke target dengan mode campuran YMM4 yang sesuai.
|
||||
sampler : Salah satu dari "clip", "clamp", "loop", "mirror",
|
||||
"dot". Diikat ke SamplerState s0. Tidak diatur jika
|
||||
dihilangkan.
|
||||
Input pixel shader dapat berupa salah satu dari berikut.
|
||||
float4 nama(float4 pos : SV_Position) : SV_Target
|
||||
float4 nama(float4 pos : SV_Position, float2 uv : TEXCOORD) : SV_Target
|
||||
uv diatur sehingga area gambar mencakup 0.0-1.0.
|
||||
Contoh: obj.pixelshader("ps", "object", "object", {obj.track0}, "copy")
|
||||
* Berjalan pada kedua mesin. Shader itu sendiri selalu dijalankan
|
||||
pada GPU di sisi host.
|
||||
* YMM4 tidak dapat mengakses latar, sehingga isi awal "framebuffer"
|
||||
adalah gambar virtual yang dibuat dengan mengomposisikan objek ke
|
||||
area transparan seukuran adegan.
|
||||
* Panggilan dilewati pada lingkungan tanpa GPU yang dapat digunakan.
|
||||
|
||||
o obj.getvalue(target)
|
||||
Mengambil nilai saat ini dari obj (sama dengan obj.x, obj.track0, dll.).
|
||||
@@ -608,7 +668,8 @@
|
||||
"arm" : menghubungkan pusat objek ke tiap titik secara berurutan.
|
||||
"xyz" : memperlakukan titik sebagai koordinat 3D. Bawaan 2D.
|
||||
Mengembalikan jumlah titik jangkar. Bekerja pada kedua mesin.
|
||||
Mode bilah "track" belum didukung dan mengembalikan 0.
|
||||
Nama "track" juga didukung; jumlah 0 menempatkan 1 titik.
|
||||
Jangkar yang dipilih dapat disesuaikan secara numerik melalui slider X / Y / Z di grup Jangkar.
|
||||
Contoh:
|
||||
num = obj.track0
|
||||
obj.setanchor("pos", num, "loop")
|
||||
@@ -758,6 +819,63 @@
|
||||
pcall, xpcall
|
||||
|
||||
|
||||
- Ekstensi Sintaks -
|
||||
|
||||
Beberapa notasi yang tidak ada pada Lua standar ditambahkan. Skrip
|
||||
ditransformasikan sebelum dijalankan, sehingga bekerja sama pada semua
|
||||
mesin. Bagian dalam string dan komentar tidak ditransformasikan.
|
||||
|
||||
o is / is not
|
||||
a is b berarti a == b, dan a is not b berarti a ~= b.
|
||||
Contoh: if frame is not 0 then
|
||||
obj.x = 100
|
||||
end
|
||||
|
||||
o != / ! / && / ||
|
||||
!= berarti ~=, ! berarti not, && berarti and, dan || berarti or.
|
||||
|
||||
o Penugasan majemuk (+= -= *= /= %= ^= ..=)
|
||||
x += 1 diperluas menjadi x = x + (1). ..= menggabungkan string.
|
||||
|
||||
o ?? (koalesing nil)
|
||||
a ?? b mengembalikan b hanya saat a bernilai nil. Tidak beralih ke false.
|
||||
|
||||
o ??= / ||= / &&=
|
||||
x ??= b menetapkan hanya saat x bernilai nil.
|
||||
x ||= b adalah x = x or (b), dan x &&= b adalah x = x and (b).
|
||||
|
||||
o ++
|
||||
x++ diperluas menjadi x = x + 1. Gunakan sebagai pernyataan satu baris.
|
||||
|
||||
o for rentang (<awal..akhir>)
|
||||
for i in <0..10> do sama dengan for i = 0, 10 do dan menyertakan akhir.
|
||||
<0..<10> tidak menyertakan akhir. <0..10, 2> memakai langkah 2.
|
||||
|
||||
o Ternari (? :)
|
||||
cond ? a : b mengembalikan a saat cond bernilai benar, dan b jika tidak.
|
||||
Cabang false atau nil dikembalikan apa adanya.
|
||||
|
||||
o Kondisional nil (?. ?[ ])
|
||||
t?.x mengembalikan nil saat t bernilai nil, jika tidak t.x.
|
||||
t?[k] adalah akses indeks. t dievaluasi sekali.
|
||||
|
||||
o Lambda (=>)
|
||||
(a, b) => expr diperluas menjadi (function(a, b) return expr end).
|
||||
Gunakan x => expr untuk satu parameter, atau () => expr untuk tanpa parameter.
|
||||
|
||||
o Pipa (|>)
|
||||
x |> f diperluas menjadi f((x)), meneruskan sisi kiri sebagai argumen pertama.
|
||||
x |> f(a, b) menjadi f((x), a, b). |> dapat dirantai.
|
||||
|
||||
o String interpolasi (`...`)
|
||||
`x={a}` diperluas menjadi ("x=" .. tostring(a)).
|
||||
Tulis ekspresi di dalam { }, yang juga mendukung sintaks ekstensi.
|
||||
|
||||
o Pemeriksaan rentang (in <..>)
|
||||
x in <1..5> menguji 1 <= x and x <= 5.
|
||||
<1..<5> tidak menyertakan batas atas. Sisi kiri dievaluasi sekali.
|
||||
|
||||
|
||||
- Contoh Skrip -
|
||||
|
||||
o Fade in (skrip default)
|
||||
@@ -885,12 +1003,11 @@
|
||||
x Pemuatan modul melalui require, dan akses berkas sembarang seperti
|
||||
io / dofile (pemuatan gambar / video via obj.load didukung dengan
|
||||
validasi header).
|
||||
x obj.setanchor, dll.
|
||||
|
||||
|
||||
- Fitur yang Tidak Didukung / Batasan -
|
||||
|
||||
x obj.rand1(), obj.mes(), obj.setanchor(), dll. dari AviUtl2 tidak didukung.
|
||||
x obj.rand1(), obj.mes(), dll. dari AviUtl2 tidak didukung.
|
||||
x Akses berkas sembarang dari skrip (require, dofile, io, dll.) tidak didukung.
|
||||
Hanya obj.load("image"/"movie") yang memuat berkas yang dipastikan sebagai
|
||||
media asli melalui validasi header awal.
|
||||
|
||||
@@ -57,13 +57,28 @@
|
||||
obj.setpixel(x, y, r2, g2, b2 [, a2])
|
||||
end
|
||||
end
|
||||
getpixeldata を使う次の形も同様にカーネル化されます。
|
||||
local data = obj.getpixeldata()
|
||||
for y = 0, data.height - 1 do
|
||||
for x = 0, data.width - 1 do
|
||||
local i = (y * data.width + x) * 4
|
||||
local r = data:get(i + 1)
|
||||
data:set(i + 1, r2)
|
||||
data:set(i + 2, g2)
|
||||
data:set(i + 3, b2)
|
||||
end
|
||||
end
|
||||
obj.putpixeldata(data)
|
||||
・本体で使えるのは四則演算・math.*・比較・しきい値の
|
||||
「条件 and 値1 or 値2」・local 変数のみです。
|
||||
・参照できるのは処理中の自ピクセル(getpixel(x, y))と
|
||||
obj/scene/time 等の値だけです。
|
||||
・近傍参照(ぼかし等)、別座標への書き込み、getpixeldata、
|
||||
getobject、テーブル/文字列操作、if 文などを含む場合は
|
||||
カーネル化されず、自動的に従来エンジンで実行されます。
|
||||
「条件 and 値1 or 値2」・if/elseif/else による local 変数への
|
||||
条件代入・local 変数のみです。
|
||||
・ループの上限には local w = obj.w のような別名も使えます。
|
||||
・参照できるのは処理中の自ピクセルと obj/scene/time 等の
|
||||
値だけです。
|
||||
・近傍参照(ぼかし等)、別座標への書き込み、if 文の中での
|
||||
setpixel や set の呼び出し、getobject、テーブル/文字列操作
|
||||
などを含む場合はカーネル化されず、自動的に従来エンジンで
|
||||
実行されます。
|
||||
|
||||
例(白い図形が赤くなる):
|
||||
--!gpu
|
||||
@@ -503,7 +518,48 @@
|
||||
"cache:名前" : 名前付きキャッシュ(フレーム間で保持)
|
||||
例:obj.copybuffer("tmp", "obj") -- 退避
|
||||
obj.copybuffer("obj", "tmp") -- 復元
|
||||
※ "frm"(フレームバッファ/背景)はYMM4の構造上取得できません。
|
||||
※ "frm"(フレームバッファ)はコピー元として使用できます。内容は
|
||||
シーンサイズの透明な領域へオブジェクトを現在位置に合成した
|
||||
仮想の画像です。YMM4は背景を参照できないため、背景は含まれ
|
||||
ません。コピー先には使用できません。
|
||||
|
||||
○obj.pixelshader(登録名, 出力先, リソース [, 定数 [, blend [, sampler]]])
|
||||
スクリプト内に定義したHLSLのピクセルシェーダーをGPUで実行します。
|
||||
シェーダーは AviUtl ExEdit2 と同じ記法の複数行コメントで定義し、
|
||||
登録名がエントリーポイントになります。
|
||||
--[[pixelshader@登録名:
|
||||
Texture2D src : register(t0);
|
||||
float4 登録名(float4 pos : SV_Position) : SV_Target { ... }
|
||||
]]
|
||||
登録名 : 定義したシェーダーの名前を文字列で指定します。
|
||||
出力先 : "object", "tempbuffer", "cache:名前", "framebuffer" の
|
||||
いずれか。"framebuffer" はシーンサイズの仮想フレーム
|
||||
バッファへ描画し、結果でオブジェクト画像を置き換え
|
||||
ます。
|
||||
リソース : 参照するバッファ名の配列。t0~t7 に設定されます。1つの
|
||||
場合は文字列で直接指定できます。"random" を指定すると
|
||||
0.0~1.0 の乱数値の 256x256 領域(R32_FLOAT)になります。
|
||||
"framebuffer" を指定すると、オブジェクトを現在位置に
|
||||
合成したシーンサイズの仮想フレームバッファになります。
|
||||
定数 : 数値の配列。定数バッファ(b0)へfloatの配列として設定
|
||||
されます。
|
||||
blend : "copy"(そのまま), "mask"(α値のみ乗算), "draw"(アルファ
|
||||
ブレンド), "add"(加算)のいずれか。省略時は "copy"。
|
||||
obj.setoption("blend", 番号) と同じ番号を数値で指定
|
||||
すると、シェーダーの出力をYMM4の合成モードで出力先へ
|
||||
合成します。
|
||||
sampler : "clip", "clamp", "loop", "mirror", "dot" のいずれか。
|
||||
SamplerState(s0)に設定されます。省略時は未設定。
|
||||
ピクセルシェーダーの入力は下記のいずれかを使用できます。
|
||||
float4 名前(float4 pos : SV_Position) : SV_Target
|
||||
float4 名前(float4 pos : SV_Position, float2 uv : TEXCOORD) : SV_Target
|
||||
uv は描画範囲が 0.0~1.0 になるように設定されます。
|
||||
例:obj.pixelshader("ps", "object", "object", {obj.track0}, "copy")
|
||||
※ 両エンジンで動きます。シェーダーの実行自体はどちらのエンジン
|
||||
でもホスト側のGPUで行われます。
|
||||
※ YMM4は背景を参照できないため、"framebuffer" の初期内容は透明な
|
||||
シーンサイズ領域へオブジェクトを合成した仮想の画像です。
|
||||
※ GPUが使用できない環境では呼び出しはスキップされます。
|
||||
|
||||
○obj.getvalue(対象)
|
||||
obj の現在値を取得します(obj.x や obj.track0 等と同値)。
|
||||
@@ -583,7 +639,8 @@
|
||||
"arm" : オブジェクトの中心から各アンカーポイントへ順に線で結びます。
|
||||
"xyz" : アンカーポイントを 3D 座標で扱います。既定は 2D です。
|
||||
戻り値は設置したアンカーポイントの数です。両エンジンで動きます。
|
||||
名前に "track" を指定するトラックバー連携は現在未対応で、0 を返します。
|
||||
名前に "track" を指定した場合も対応し、個数 0 は 1 個として設置します。
|
||||
選択中のアンカーは アンカー グループの X / Y / Z スライダーで数値調整できます。
|
||||
例:
|
||||
num = obj.track0
|
||||
obj.setanchor("pos", num, "loop")
|
||||
@@ -730,6 +787,62 @@
|
||||
pcall, xpcall
|
||||
|
||||
|
||||
- 構文の拡張 -
|
||||
|
||||
標準の Lua に無い記法を追加しています。実行前にスクリプトを変換するため、
|
||||
すべての実行エンジンで同じように使えます。文字列とコメントの内側は変換しません。
|
||||
|
||||
○is / is not
|
||||
a is b は a == b、a is not b は a ~= b と同じ意味になります。
|
||||
例:if frame is not 0 then
|
||||
obj.x = 100
|
||||
end
|
||||
|
||||
○!= / ! / && / ||
|
||||
!= は ~=、! は not、&& は and、|| は or と同じ意味になります。
|
||||
|
||||
○複合代入(+= -= *= /= %= ^= ..=)
|
||||
x += 1 は x = x + (1) に展開します。..= は文字列の連結です。
|
||||
|
||||
○??(nil 合体)
|
||||
a ?? b は a が nil のときだけ b を返します。false は返しません。
|
||||
|
||||
○??= / ||= / &&=
|
||||
x ??= b は x が nil のときだけ代入します。
|
||||
x ||= b は x = x or (b)、x &&= b は x = x and (b) です。
|
||||
|
||||
○++
|
||||
x++ は x = x + 1 に展開します。行単位の文として使います。
|
||||
|
||||
○範囲 for(<開始..終了>)
|
||||
for i in <0..10> do は for i = 0, 10 do と同じで終端を含みます。
|
||||
<0..<10> は終端を含みません。<0..10, 2> は増分 2 です。
|
||||
|
||||
○三項演算子(? :)
|
||||
cond ? a : b は cond が真なら a、偽なら b を返します。
|
||||
false や nil の分岐もそのまま返します。
|
||||
|
||||
○nil 条件演算子(?. ?[ ])
|
||||
t?.x は t が nil なら nil、そうでなければ t.x を返します。
|
||||
t?[k] は添字アクセスです。t は 1 度だけ評価します。
|
||||
|
||||
○ラムダ式(=>)
|
||||
(a, b) => expr は (function(a, b) return expr end) に展開します。
|
||||
引数が 1 つなら x => expr、無しなら () => expr と書けます。
|
||||
|
||||
○パイプ(|>)
|
||||
x |> f は f((x)) に展開し、左辺を第 1 引数として渡します。
|
||||
x |> f(a, b) は f((x), a, b) です。|> は連結できます。
|
||||
|
||||
○補間文字列(`...`)
|
||||
`x={a}` は ("x=" .. tostring(a)) に展開します。
|
||||
{ } の中には式を書け、拡張構文も使えます。
|
||||
|
||||
○範囲判定(in <..>)
|
||||
x in <1..5> は 1 <= x and x <= 5 を判定します。
|
||||
<1..<5> は上限を含みません。左辺は 1 度だけ評価します。
|
||||
|
||||
|
||||
- スクリプト例 -
|
||||
|
||||
○フェードイン(デフォルトスクリプト)
|
||||
@@ -852,12 +965,11 @@
|
||||
これらを呼び出すスクリプトは意図どおりには動作しません。
|
||||
×require によるモジュール読み込み、io / dofile などの任意ファイル
|
||||
アクセス(obj.load の画像 / 動画はヘッダー検証付きで対応)。
|
||||
×obj.setanchor 等。
|
||||
|
||||
|
||||
- 非対応・制限事項 -
|
||||
|
||||
×AviUtl2 の obj.rand1(), obj.mes(), obj.setanchor() 等には対応していません。
|
||||
×AviUtl2 の obj.rand1(), obj.mes() 等には対応していません。
|
||||
×スクリプトからの任意ファイルアクセス(require, dofile, io 等)には対応して
|
||||
いません。obj.load("image"/"movie") のみ、先頭ヘッダー検証で真正なメディアと
|
||||
確認できたファイルを読み込みます。
|
||||
|
||||
@@ -57,13 +57,28 @@
|
||||
obj.setpixel(x, y, r2, g2, b2 [, a2])
|
||||
end
|
||||
end
|
||||
getpixeldata를 사용하는 다음 형태도 마찬가지로 커널화됩니다.
|
||||
local data = obj.getpixeldata()
|
||||
for y = 0, data.height - 1 do
|
||||
for x = 0, data.width - 1 do
|
||||
local i = (y * data.width + x) * 4
|
||||
local r = data:get(i + 1)
|
||||
data:set(i + 1, r2)
|
||||
data:set(i + 2, g2)
|
||||
data:set(i + 3, b2)
|
||||
end
|
||||
end
|
||||
obj.putpixeldata(data)
|
||||
· 본문에서 사용할 수 있는 것은 사칙연산・math.*・비교・임계값
|
||||
「조건 and 값1 or 값2」・local 변수뿐입니다.
|
||||
· 참조할 수 있는 것은 처리 중인 자기 픽셀(getpixel(x, y))과
|
||||
obj/scene/time 등의 값뿐입니다.
|
||||
· 이웃 참조(블러 등), 다른 좌표로의 쓰기, getpixeldata,
|
||||
getobject, 테이블/문자열 조작, if 문 등을 포함하는 경우에는
|
||||
커널화되지 않고 자동으로 기존 엔진에서 실행됩니다.
|
||||
「조건 and 값1 or 값2」・if/elseif/else에 의한 local 변수에
|
||||
대한 조건 대입・local 변수뿐입니다.
|
||||
· 루프의 상한에는 local w = obj.w 같은 별칭도 사용할 수 있습니다.
|
||||
· 참조할 수 있는 것은 처리 중인 자기 픽셀과 obj/scene/time
|
||||
등의 값뿐입니다.
|
||||
· 이웃 참조(블러 등), 다른 좌표로의 쓰기, if 문 안에서의
|
||||
setpixel이나 set 호출, getobject, 테이블/문자열 조작 등을
|
||||
포함하는 경우에는 커널화되지 않고 자동으로 기존 엔진에서
|
||||
실행됩니다.
|
||||
|
||||
예(흰색 도형이 빨갛게 됨):
|
||||
--!gpu
|
||||
@@ -498,7 +513,46 @@
|
||||
"cache:이름" : 명명 캐시(프레임 간 유지)
|
||||
예: obj.copybuffer("tmp", "obj") -- 저장
|
||||
obj.copybuffer("obj", "tmp") -- 복원
|
||||
※ "frm"(프레임 버퍼 / 배경)은 YMM4의 구조상 가져올 수 없습니다.
|
||||
※ "frm"(프레임 버퍼)은 복사 원본으로 사용할 수 있습니다. 내용은
|
||||
장면 크기의 투명한 영역에 오브젝트를 현재 위치로 합성한 가상
|
||||
이미지입니다. YMM4는 배경을 참조할 수 없으므로 배경은 포함되지
|
||||
않습니다. 복사 대상으로는 사용할 수 없습니다.
|
||||
|
||||
○ obj.pixelshader(등록명, 출력 대상, 리소스 [, 상수 [, blend [, sampler]]])
|
||||
스크립트 안에 정의한 HLSL 픽셀 셰이더를 GPU에서 실행합니다.
|
||||
셰이더는 AviUtl ExEdit2와 같은 표기의 여러 줄 주석으로 정의하며,
|
||||
등록명이 엔트리 포인트가 됩니다.
|
||||
--[[pixelshader@등록명:
|
||||
Texture2D src : register(t0);
|
||||
float4 등록명(float4 pos : SV_Position) : SV_Target { ... }
|
||||
]]
|
||||
등록명 : 정의한 셰이더의 이름을 문자열로 지정합니다.
|
||||
출력 대상 : "object", "tempbuffer", "cache:이름", "framebuffer" 중
|
||||
하나. "framebuffer"는 장면 크기의 가상 프레임 버퍼에
|
||||
그리고, 결과로 오브젝트 이미지를 대체합니다.
|
||||
리소스 : 참조할 버퍼 이름의 배열이며 t0~t7에 설정됩니다. 하나뿐인
|
||||
경우 문자열로 직접 지정할 수 있습니다. "random"을
|
||||
지정하면 0.0~1.0 난수 값의 256x256 영역(R32_FLOAT)이
|
||||
됩니다. "framebuffer"를 지정하면 오브젝트를 현재
|
||||
위치로 합성한 장면 크기의 가상 프레임 버퍼가 됩니다.
|
||||
상수 : 숫자 배열이며 상수 버퍼(b0)에 float 배열로 설정됩니다.
|
||||
blend : "copy"(그대로), "mask"(알파 값만 곱함), "draw"(알파
|
||||
블렌드), "add"(가산) 중 하나. 생략 시 "copy".
|
||||
obj.setoption("blend", 번호)와 같은 번호를 숫자로
|
||||
지정하면 셰이더 출력을 YMM4의 합성 모드로 출력
|
||||
대상에 합성합니다.
|
||||
sampler : "clip", "clamp", "loop", "mirror", "dot" 중 하나.
|
||||
SamplerState(s0)에 설정됩니다. 생략 시 미설정.
|
||||
픽셀 셰이더의 입력은 다음 중 하나를 사용할 수 있습니다.
|
||||
float4 이름(float4 pos : SV_Position) : SV_Target
|
||||
float4 이름(float4 pos : SV_Position, float2 uv : TEXCOORD) : SV_Target
|
||||
uv는 그리기 범위가 0.0~1.0이 되도록 설정됩니다.
|
||||
예: obj.pixelshader("ps", "object", "object", {obj.track0}, "copy")
|
||||
※ 두 엔진 모두에서 동작합니다. 셰이더 자체는 항상 호스트 측
|
||||
GPU에서 실행됩니다.
|
||||
※ YMM4는 배경을 참조할 수 없으므로 "framebuffer"의 초기 내용은
|
||||
장면 크기의 투명한 영역에 오브젝트를 합성한 가상 이미지입니다.
|
||||
※ GPU를 사용할 수 없는 환경에서는 호출이 건너뛰어집니다.
|
||||
|
||||
○ obj.getvalue(대상)
|
||||
obj의 현재 값을 가져옵니다(obj.x, obj.track0 등과 동일).
|
||||
@@ -576,7 +630,8 @@
|
||||
"arm" : 오브젝트 중심에서 각 앵커 포인트로 차례로 잇습니다.
|
||||
"xyz" : 앵커 포인트를 3D 좌표로 다룹니다. 기본은 2D입니다.
|
||||
설치한 앵커 포인트 수를 반환합니다. 두 엔진 모두에서 동작합니다.
|
||||
이름에 "track"을 지정하는 트랙바 연동은 현재 미지원이며 0을 반환합니다.
|
||||
이름에 "track"을 지정하는 경우도 지원하며, 개수 0은 1개로 배치합니다.
|
||||
선택 중인 앵커는 앵커 그룹의 X / Y / Z 슬라이더로 수치 조정할 수 있습니다.
|
||||
예:
|
||||
num = obj.track0
|
||||
obj.setanchor("pos", num, "loop")
|
||||
@@ -723,6 +778,62 @@
|
||||
pcall, xpcall
|
||||
|
||||
|
||||
- 구문 확장 -
|
||||
|
||||
표준 Lua에 없는 표기를 추가했습니다. 스크립트는 실행 전에 변환되므로 모든
|
||||
엔진에서 동일하게 동작합니다. 문자열과 주석의 내부는 변환하지 않습니다.
|
||||
|
||||
○ is / is not
|
||||
a is b는 a == b, a is not b는 a ~= b와 같은 의미입니다.
|
||||
예: if frame is not 0 then
|
||||
obj.x = 100
|
||||
end
|
||||
|
||||
○ != / ! / && / ||
|
||||
!=는 ~=, !는 not, &&는 and, ||는 or와 같은 의미입니다.
|
||||
|
||||
○ 복합 대입 (+= -= *= /= %= ^= ..=)
|
||||
x += 1은 x = x + (1)로 확장됩니다. ..=는 문자열 연결입니다.
|
||||
|
||||
○ ?? (nil 병합)
|
||||
a ?? b는 a가 nil일 때만 b를 반환합니다. false로는 대체하지 않습니다.
|
||||
|
||||
○ ??= / ||= / &&=
|
||||
x ??= b는 x가 nil일 때만 대입합니다.
|
||||
x ||= b는 x = x or (b), x &&= b는 x = x and (b)입니다.
|
||||
|
||||
○ ++
|
||||
x++는 x = x + 1로 확장됩니다. 한 줄짜리 문으로 사용합니다.
|
||||
|
||||
○ 범위 for (<시작..끝>)
|
||||
for i in <0..10> do는 for i = 0, 10 do와 같으며 끝을 포함합니다.
|
||||
<0..<10>는 끝을 포함하지 않습니다. <0..10, 2>는 증분이 2입니다.
|
||||
|
||||
○ 삼항 연산자 (? :)
|
||||
cond ? a : b는 cond가 참이면 a를, 거짓이면 b를 반환합니다.
|
||||
false나 nil 분기도 그대로 반환합니다.
|
||||
|
||||
○ nil 조건 연산자 (?. ?[ ])
|
||||
t?.x는 t가 nil이면 nil을, 그렇지 않으면 t.x를 반환합니다.
|
||||
t?[k]는 첨자 접근입니다. t는 한 번만 평가합니다.
|
||||
|
||||
○ 람다 (=>)
|
||||
(a, b) => expr는 (function(a, b) return expr end)로 확장됩니다.
|
||||
매개변수가 하나면 x => expr, 없으면 () => expr로 씁니다.
|
||||
|
||||
○ 파이프 (|>)
|
||||
x |> f는 f((x))로 확장되며, 왼쪽 값을 첫 번째 인수로 전달합니다.
|
||||
x |> f(a, b)는 f((x), a, b)입니다. |>는 연결할 수 있습니다.
|
||||
|
||||
○ 문자열 보간 (`...`)
|
||||
`x={a}`는 ("x=" .. tostring(a))로 확장됩니다.
|
||||
{ } 안에는 식을 쓸 수 있으며 확장 구문도 사용할 수 있습니다.
|
||||
|
||||
○ 범위 검사 (in <..>)
|
||||
x in <1..5>는 1 <= x and x <= 5를 판정합니다.
|
||||
<1..<5>는 상한을 포함하지 않습니다. 왼쪽 값은 한 번만 평가합니다.
|
||||
|
||||
|
||||
- 스크립트 예 -
|
||||
|
||||
○ 페이드인(기본 스크립트)
|
||||
@@ -845,12 +956,11 @@
|
||||
이를 호출하는 스크립트는 의도대로 동작하지 않습니다.
|
||||
× require에 의한 모듈 로드 및 io / dofile 등의 임의 파일 접근
|
||||
(obj.load의 이미지 / 동영상 로드는 헤더 검증과 함께 지원).
|
||||
× obj.setanchor 등.
|
||||
|
||||
|
||||
- 미지원·제한 사항 -
|
||||
|
||||
× AviUtl2의 obj.rand1(), obj.mes(), obj.setanchor() 등은 지원하지 않습니다.
|
||||
× AviUtl2의 obj.rand1(), obj.mes() 등은 지원하지 않습니다.
|
||||
× 스크립트에서의 임의 파일 접근(require, dofile, io 등)은 지원하지 않습니다.
|
||||
obj.load("image"/"movie")만 선두 헤더 검증으로 진짜 미디어로 확인된 파일을
|
||||
읽습니다.
|
||||
|
||||
@@ -57,13 +57,26 @@
|
||||
obj.setpixel(x, y, r2, g2, b2 [, a2])
|
||||
end
|
||||
end
|
||||
使用 getpixeldata 的下列形式同样会被内核化。
|
||||
local data = obj.getpixeldata()
|
||||
for y = 0, data.height - 1 do
|
||||
for x = 0, data.width - 1 do
|
||||
local i = (y * data.width + x) * 4
|
||||
local r = data:get(i + 1)
|
||||
data:set(i + 1, r2)
|
||||
data:set(i + 2, g2)
|
||||
data:set(i + 3, b2)
|
||||
end
|
||||
end
|
||||
obj.putpixeldata(data)
|
||||
· 主体中仅可使用四则运算、math.*、比较、阈值写法
|
||||
“条件 and 值1 or 值2”以及 local 变量。
|
||||
· 仅可引用正在处理的自像素(getpixel(x, y))
|
||||
以及 obj/scene/time 等值。
|
||||
· 含有邻域参照(模糊等)、写入其他坐标、getpixeldata、
|
||||
getobject、表/字符串操作、if 语句等的脚本不会被内核化,
|
||||
会自动由传统引擎执行。
|
||||
“条件 and 值1 or 值2”、通过 if/elseif/else 对 local 变量的
|
||||
条件赋值以及 local 变量。
|
||||
· 循环上限也可以使用 local w = obj.w 这样的别名。
|
||||
· 仅可引用正在处理的自像素以及 obj/scene/time 等值。
|
||||
· 含有邻域参照(模糊等)、写入其他坐标、在 if 语句中调用
|
||||
setpixel 或 set、getobject、表/字符串操作等的脚本不会被
|
||||
内核化,会自动由传统引擎执行。
|
||||
|
||||
示例(让白色图形变红):
|
||||
--!gpu
|
||||
@@ -488,7 +501,43 @@
|
||||
"cache:名称" : 命名缓存(跨帧保留)
|
||||
示例:obj.copybuffer("tmp", "obj") -- 保存
|
||||
obj.copybuffer("obj", "tmp") -- 恢复
|
||||
※ 由于 YMM4 的结构,无法获取 "frm"(帧缓冲区 / 背景)。
|
||||
※ "frm"(帧缓冲区)可以作为复制源使用。其内容是把对象按当前位置
|
||||
合成到场景大小的透明区域而得到的虚拟图像。由于YMM4无法访问
|
||||
背景,因此不包含背景。不能作为复制目标使用。
|
||||
|
||||
○ obj.pixelshader(注册名, 输出目标, 资源 [, 常量 [, blend [, sampler]]])
|
||||
在GPU上执行脚本内定义的HLSL像素着色器。
|
||||
着色器使用与 AviUtl ExEdit2 相同写法的多行注释来定义,
|
||||
注册名即为入口点。
|
||||
--[[pixelshader@注册名:
|
||||
Texture2D src : register(t0);
|
||||
float4 注册名(float4 pos : SV_Position) : SV_Target { ... }
|
||||
]]
|
||||
注册名 : 以字符串指定已定义着色器的名称。
|
||||
输出目标 : "object"、"tempbuffer"、"cache:名称"、"framebuffer"
|
||||
之一。"framebuffer" 会绘制到场景大小的虚拟帧缓冲区,
|
||||
并用结果替换对象图像。
|
||||
资源 : 要引用的缓冲区名称数组,绑定到 t0~t7。只有一个时可以
|
||||
直接用字符串指定。指定 "random" 时会绑定 0.0~1.0
|
||||
随机值的 256x256 区域(R32_FLOAT)。指定 "framebuffer"
|
||||
时会绑定把对象按当前位置合成后的场景大小虚拟帧
|
||||
缓冲区。
|
||||
常量 : 数值数组,以float数组形式设置到常量缓冲区(b0)。
|
||||
blend : "copy"(原样)、"mask"(仅乘算α值)、"draw"(alpha混合)、
|
||||
"add"(加算)之一。省略时为 "copy"。以数值指定与
|
||||
obj.setoption("blend", 编号) 相同的编号时,会以YMM4
|
||||
的合成模式把着色器输出合成到输出目标。
|
||||
sampler : "clip"、"clamp"、"loop"、"mirror"、"dot" 之一。
|
||||
设置到 SamplerState(s0)。省略时不设置。
|
||||
像素着色器的输入可以使用以下任意一种。
|
||||
float4 名称(float4 pos : SV_Position) : SV_Target
|
||||
float4 名称(float4 pos : SV_Position, float2 uv : TEXCOORD) : SV_Target
|
||||
uv 会被设置为绘制范围对应 0.0~1.0。
|
||||
例: obj.pixelshader("ps", "object", "object", {obj.track0}, "copy")
|
||||
※ 在两个引擎中均可使用。着色器本身始终在宿主端的GPU上执行。
|
||||
※ 由于YMM4无法访问背景,"framebuffer" 的初始内容是把对象合成到
|
||||
场景大小透明区域后的虚拟图像。
|
||||
※ 在无法使用GPU的环境中会跳过该调用。
|
||||
|
||||
○ obj.getvalue(目标)
|
||||
获取 obj 的当前值(与 obj.x、obj.track0 等相同)。
|
||||
@@ -555,7 +604,8 @@
|
||||
"arm" : 从对象中心依次连接到各锚点。
|
||||
"xyz" : 以 3D 坐标处理锚点。默认是 2D。
|
||||
返回设置的锚点数量。两个引擎都可用。
|
||||
名称指定 "track" 的轨道条联动暂不支持,返回 0。
|
||||
名称指定 "track" 时也已支持,个数为 0 时放置 1 个。
|
||||
选中的锚点可通过锚点组的 X / Y / Z 滑块进行数值调整。
|
||||
示例:
|
||||
num = obj.track0
|
||||
obj.setanchor("pos", num, "loop")
|
||||
@@ -699,6 +749,62 @@
|
||||
pcall, xpcall
|
||||
|
||||
|
||||
- 语法扩展 -
|
||||
|
||||
添加了标准 Lua 没有的写法。脚本在执行前会被转换,因此在所有引擎上表现一致。
|
||||
字符串和注释的内部不会被转换。
|
||||
|
||||
○ is / is not
|
||||
a is b 与 a == b 相同,a is not b 与 a ~= b 相同。
|
||||
示例:if frame is not 0 then
|
||||
obj.x = 100
|
||||
end
|
||||
|
||||
○ != / ! / && / ||
|
||||
!= 相当于 ~=,! 相当于 not,&& 相当于 and,|| 相当于 or。
|
||||
|
||||
○ 复合赋值(+= -= *= /= %= ^= ..=)
|
||||
x += 1 展开为 x = x + (1)。..= 用于字符串连接。
|
||||
|
||||
○ ??(nil 合并)
|
||||
a ?? b 仅当 a 为 nil 时返回 b。不会因 false 而回退。
|
||||
|
||||
○ ??= / ||= / &&=
|
||||
x ??= b 仅当 x 为 nil 时赋值。
|
||||
x ||= b 即 x = x or (b),x &&= b 即 x = x and (b)。
|
||||
|
||||
○ ++
|
||||
x++ 展开为 x = x + 1。作为独立一行的语句使用。
|
||||
|
||||
○ 范围 for(<起始..结束>)
|
||||
for i in <0..10> do 与 for i = 0, 10 do 相同,包含结束值。
|
||||
<0..<10> 不包含结束值。<0..10, 2> 的步长为 2。
|
||||
|
||||
○ 三元运算符(? :)
|
||||
cond ? a : b 在 cond 为真时返回 a,否则返回 b。
|
||||
false 或 nil 分支也会原样返回。
|
||||
|
||||
○ nil 条件运算符(?. ?[ ])
|
||||
t?.x 在 t 为 nil 时返回 nil,否则返回 t.x。
|
||||
t?[k] 是下标访问。t 只求值一次。
|
||||
|
||||
○ Lambda(=>)
|
||||
(a, b) => expr 展开为 (function(a, b) return expr end)。
|
||||
只有一个参数时写作 x => expr,没有参数时写作 () => expr。
|
||||
|
||||
○ 管道(|>)
|
||||
x |> f 展开为 f((x)),将左侧作为第一个参数传入。
|
||||
x |> f(a, b) 即 f((x), a, b)。|> 可以链式连接。
|
||||
|
||||
○ 插值字符串(`...`)
|
||||
`x={a}` 展开为 ("x=" .. tostring(a))。
|
||||
{ } 中可以写表达式,也能使用扩展语法。
|
||||
|
||||
○ 范围检查(in <..>)
|
||||
x in <1..5> 判断 1 <= x and x <= 5。
|
||||
<1..<5> 不包含上限。左侧只求值一次。
|
||||
|
||||
|
||||
- 脚本示例 -
|
||||
|
||||
○ 淡入(默认脚本)
|
||||
@@ -813,12 +919,11 @@
|
||||
调用它们的脚本不会按预期运行。
|
||||
× 通过 require 加载模块,以及 io / dofile 等任意文件访问
|
||||
(obj.load 的图像 / 视频加载已带文件头校验支持)。
|
||||
× obj.setanchor 等。
|
||||
|
||||
|
||||
- 不支持项目·限制事项 -
|
||||
|
||||
× 不支持 AviUtl2 的 obj.rand1()、obj.mes()、obj.setanchor() 等。
|
||||
× 不支持 AviUtl2 的 obj.rand1()、obj.mes() 等。
|
||||
× 不支持脚本进行任意文件访问(require、dofile、io 等)。
|
||||
仅 obj.load("image"/"movie") 会加载经文件头校验确认为真正媒体的文件。
|
||||
× 修改 obj.z 会反映到绘制中(包含在 ReadBack 中),
|
||||
|
||||
@@ -57,13 +57,26 @@
|
||||
obj.setpixel(x, y, r2, g2, b2 [, a2])
|
||||
end
|
||||
end
|
||||
使用 getpixeldata 的下列形式同樣會被核心化。
|
||||
local data = obj.getpixeldata()
|
||||
for y = 0, data.height - 1 do
|
||||
for x = 0, data.width - 1 do
|
||||
local i = (y * data.width + x) * 4
|
||||
local r = data:get(i + 1)
|
||||
data:set(i + 1, r2)
|
||||
data:set(i + 2, g2)
|
||||
data:set(i + 3, b2)
|
||||
end
|
||||
end
|
||||
obj.putpixeldata(data)
|
||||
· 主體中僅可使用四則運算、math.*、比較、閾值寫法
|
||||
「條件 and 值1 or 值2」以及 local 變數。
|
||||
· 僅可參照正在處理的自像素(getpixel(x, y))
|
||||
以及 obj/scene/time 等值。
|
||||
· 含有鄰域參照(模糊等)、寫入其他座標、getpixeldata、
|
||||
getobject、表/字串操作、if 陳述式等的腳本不會被核心化,
|
||||
會自動由傳統引擎執行。
|
||||
「條件 and 值1 or 值2」、透過 if/elseif/else 對 local 變數的
|
||||
條件賦值以及 local 變數。
|
||||
· 迴圈上限也可以使用 local w = obj.w 這樣的別名。
|
||||
· 僅可參照正在處理的自像素以及 obj/scene/time 等值。
|
||||
· 含有鄰域參照(模糊等)、寫入其他座標、在 if 陳述式中呼叫
|
||||
setpixel 或 set、getobject、表/字串操作等的腳本不會被
|
||||
核心化,會自動由傳統引擎執行。
|
||||
|
||||
範例(讓白色圖形變紅):
|
||||
--!gpu
|
||||
@@ -488,7 +501,43 @@
|
||||
"cache:名稱" : 具名快取(跨影格保留)
|
||||
範例:obj.copybuffer("tmp", "obj") -- 儲存
|
||||
obj.copybuffer("obj", "tmp") -- 還原
|
||||
※ 由於 YMM4 的結構,無法取得 "frm"(影格緩衝區 / 背景)。
|
||||
※ "frm"(影格緩衝區)可以作為複製來源使用。其內容是把物件按目前
|
||||
位置合成到場景大小的透明區域而得到的虛擬影像。由於YMM4無法
|
||||
存取背景,因此不包含背景。不能作為複製目標使用。
|
||||
|
||||
○ obj.pixelshader(註冊名, 輸出目標, 資源 [, 常數 [, blend [, sampler]]])
|
||||
在GPU上執行腳本內定義的HLSL像素著色器。
|
||||
著色器使用與 AviUtl ExEdit2 相同寫法的多行註解來定義,
|
||||
註冊名即為進入點。
|
||||
--[[pixelshader@註冊名:
|
||||
Texture2D src : register(t0);
|
||||
float4 註冊名(float4 pos : SV_Position) : SV_Target { ... }
|
||||
]]
|
||||
註冊名 : 以字串指定已定義著色器的名稱。
|
||||
輸出目標 : "object"、"tempbuffer"、"cache:名稱"、"framebuffer"
|
||||
之一。"framebuffer" 會繪製到場景大小的虛擬影格緩衝區,
|
||||
並用結果取代物件影像。
|
||||
資源 : 要參照的緩衝區名稱陣列,綁定到 t0~t7。只有一個時可以
|
||||
直接用字串指定。指定 "random" 時會綁定 0.0~1.0
|
||||
亂數值的 256x256 區域(R32_FLOAT)。指定 "framebuffer"
|
||||
時會綁定把物件按目前位置合成後的場景大小虛擬影格
|
||||
緩衝區。
|
||||
常數 : 數值陣列,以float陣列形式設定到常數緩衝區(b0)。
|
||||
blend : "copy"(原樣)、"mask"(僅乘算α值)、"draw"(alpha混合)、
|
||||
"add"(加算)之一。省略時為 "copy"。以數值指定與
|
||||
obj.setoption("blend", 編號) 相同的編號時,會以YMM4
|
||||
的合成模式把著色器輸出合成到輸出目標。
|
||||
sampler : "clip"、"clamp"、"loop"、"mirror"、"dot" 之一。
|
||||
設定到 SamplerState(s0)。省略時不設定。
|
||||
像素著色器的輸入可以使用以下任一種。
|
||||
float4 名稱(float4 pos : SV_Position) : SV_Target
|
||||
float4 名稱(float4 pos : SV_Position, float2 uv : TEXCOORD) : SV_Target
|
||||
uv 會被設定為繪製範圍對應 0.0~1.0。
|
||||
例: obj.pixelshader("ps", "object", "object", {obj.track0}, "copy")
|
||||
※ 在兩個引擎中均可使用。著色器本身始終在宿主端的GPU上執行。
|
||||
※ 由於YMM4無法存取背景,"framebuffer" 的初始內容是把物件合成到
|
||||
場景大小透明區域後的虛擬影像。
|
||||
※ 在無法使用GPU的環境中會跳過該呼叫。
|
||||
|
||||
○ obj.getvalue(目標)
|
||||
取得 obj 的目前值(與 obj.x、obj.track0 等相同)。
|
||||
@@ -556,7 +605,8 @@
|
||||
"arm" : 從物件中心依序連接到各錨點。
|
||||
"xyz" : 以 3D 座標處理錨點。預設是 2D。
|
||||
回傳設置的錨點數量。兩個引擎都可用。
|
||||
名稱指定 "track" 的軌道條連動暫不支援,回傳 0。
|
||||
名稱指定 "track" 時也已支援,個數為 0 時放置 1 個。
|
||||
選取的錨點可透過錨點群組的 X / Y / Z 滑桿進行數值調整。
|
||||
範例:
|
||||
num = obj.track0
|
||||
obj.setanchor("pos", num, "loop")
|
||||
@@ -700,6 +750,62 @@
|
||||
pcall, xpcall
|
||||
|
||||
|
||||
- 語法擴充 -
|
||||
|
||||
新增了標準 Lua 沒有的寫法。腳本在執行前會被轉換,因此在所有引擎上表現一致。
|
||||
字串與註解的內部不會被轉換。
|
||||
|
||||
○ is / is not
|
||||
a is b 與 a == b 相同,a is not b 與 a ~= b 相同。
|
||||
範例:if frame is not 0 then
|
||||
obj.x = 100
|
||||
end
|
||||
|
||||
○ != / ! / && / ||
|
||||
!= 相當於 ~=,! 相當於 not,&& 相當於 and,|| 相當於 or。
|
||||
|
||||
○ 複合指派(+= -= *= /= %= ^= ..=)
|
||||
x += 1 會展開為 x = x + (1)。..= 用於字串連接。
|
||||
|
||||
○ ??(nil 合併)
|
||||
a ?? b 僅在 a 為 nil 時回傳 b。不會因 false 而回退。
|
||||
|
||||
○ ??= / ||= / &&=
|
||||
x ??= b 僅在 x 為 nil 時指派。
|
||||
x ||= b 即 x = x or (b),x &&= b 即 x = x and (b)。
|
||||
|
||||
○ ++
|
||||
x++ 會展開為 x = x + 1。作為獨立一行的敘述使用。
|
||||
|
||||
○ 範圍 for(<起始..結束>)
|
||||
for i in <0..10> do 與 for i = 0, 10 do 相同,包含結束值。
|
||||
<0..<10> 不包含結束值。<0..10, 2> 的步長為 2。
|
||||
|
||||
○ 三元運算子(? :)
|
||||
cond ? a : b 在 cond 為真時回傳 a,否則回傳 b。
|
||||
false 或 nil 分支也會原樣回傳。
|
||||
|
||||
○ nil 條件運算子(?. ?[ ])
|
||||
t?.x 在 t 為 nil 時回傳 nil,否則回傳 t.x。
|
||||
t?[k] 是索引存取。t 只求值一次。
|
||||
|
||||
○ Lambda(=>)
|
||||
(a, b) => expr 會展開為 (function(a, b) return expr end)。
|
||||
只有一個參數時寫作 x => expr,沒有參數時寫作 () => expr。
|
||||
|
||||
○ 管道(|>)
|
||||
x |> f 會展開為 f((x)),將左側作為第一個參數傳入。
|
||||
x |> f(a, b) 即 f((x), a, b)。|> 可以鏈式連接。
|
||||
|
||||
○ 插值字串(`...`)
|
||||
`x={a}` 會展開為 ("x=" .. tostring(a))。
|
||||
{ } 中可以寫運算式,也能使用擴充語法。
|
||||
|
||||
○ 範圍檢查(in <..>)
|
||||
x in <1..5> 判斷 1 <= x and x <= 5。
|
||||
<1..<5> 不包含上限。左側只求值一次。
|
||||
|
||||
|
||||
- 腳本範例 -
|
||||
|
||||
○ 淡入(預設腳本)
|
||||
@@ -814,12 +920,11 @@
|
||||
呼叫它們的腳本不會如預期運作。
|
||||
× 透過 require 載入模組,以及 io / dofile 等任意檔案存取
|
||||
(obj.load 的影像 / 影片載入已附檔頭驗證支援)。
|
||||
× obj.setanchor 等。
|
||||
|
||||
|
||||
- 不支援項目·限制事項 -
|
||||
|
||||
× 不支援 AviUtl2 的 obj.rand1()、obj.mes()、obj.setanchor() 等。
|
||||
× 不支援 AviUtl2 的 obj.rand1()、obj.mes() 等。
|
||||
× 不支援腳本進行任意檔案存取(require、dofile、io 等)。
|
||||
僅 obj.load("image"/"movie") 會載入經檔頭驗證確認為真正媒體的檔案。
|
||||
× 修改 obj.z 會反映至繪製中(包含在 ReadBack 中),
|
||||
|
||||
@@ -30,6 +30,7 @@ YukkuriMovieMaker4(YMM4)上で動作する、**Luaスクリプトでオブ
|
||||
- [7. スクリプトエディタの支援機能](#7-スクリプトエディタの支援機能)
|
||||
- [8. インポート・エクスポート・クリア](#8-インポートエクスポートクリア)
|
||||
- [9. AviUtl スクリプトの部分互換](#9-aviutl-スクリプトの部分互換)
|
||||
- [10. 構文拡張](#10-構文拡張)
|
||||
5. [実行モデル](#実行モデル)
|
||||
- [実行エンジンの自動振り分け](#実行エンジンの自動振り分け)
|
||||
- [実行スレッドとタイムアウト](#実行スレッドとタイムアウト)
|
||||
@@ -80,7 +81,7 @@ YukkuriMovieMaker4(YMM4)上で動作する、**Luaスクリプトでオブ
|
||||
|
||||
- `table`、`string`、`math`、`bit32`
|
||||
- 基本関数: `type`、`tostring`、`tonumber`、`select`、`error`、`assert`、`print`、`ipairs`、`pairs`、`next`、`unpack`、`setmetatable`、`getmetatable`、`rawget`、`rawset`、`rawequal`、`rawlen`、`pcall`、`xpcall`
|
||||
`io`、`os`、`debug`、`ffi`、`require` 等は利用できません。ファイルへのアクセス(`require` を含む)はスクリプトローダー側で明示的に禁止されており、呼び出すと例外になります。
|
||||
`io`、`os`、`debug`、`ffi`、`require` 等は利用できません。ファイルへのアクセス(`require` を含む)はスクリプトローダー側で明示的に禁止されており、呼び出すと例外になります。標準の Lua に無い記法の追加については[構文拡張](#10-構文拡張)を参照してください。
|
||||
|
||||
### 2. obj テーブルによる描画制御
|
||||
|
||||
@@ -218,9 +219,11 @@ AviUtl のアニメーション効果スクリプト(`.anm` 系)のうち、
|
||||
- **`obj.rand(st, ed [, seed [, frame]])`**: 指定範囲(`st`〜`ed`)の整数を返す決定論的な乱数です。`seed` と `frame` が同じであれば常に同じ値を返し、`frame` を省略すると現在のフレームを用います。従来エンジン(MoonSharp)と高速ランタイム(LuaJIT)で同じ値を返します。
|
||||
- **`obj.load("figure", 名前, 色, サイズ [, ライン [, アスペクト]])`**: 円・四角形・三角形・五角形・六角形・星形を生成し、オブジェクトのバッファを置き換えて描画します(出力は図形サイズに合わせて生成され、中心に配置されます)。`ライン` を省略するか `0` で塗りつぶし、サイズ以上の値でも塗りつぶしになります。`アスペクト`(-1.0〜1.0)で幅・高さを歪曲できます。
|
||||
- **描画・メディア・バッファ・オプション API**: `obj.draw` / `obj.drawpoly` による描画合成、`obj.load` の `"text"` / `"image"` / `"movie"`、`obj.setfont`、`obj.copybuffer`、`obj.effect`、`obj.getvalue`、`obj.getinfo`、`obj.setoption` / `obj.getoption` / `obj.pixeloption` に対応しています。これらは従来エンジン(MoonSharp)と高速ランタイム(LuaJIT)の双方で動作します。`obj.getinfo` は `"script_path"` / `"filter"` / `"saving"` / `"image_max"` / `"bpm"` / `"clock"` / `"script_time"` / `"version"` の環境情報を名前で取得します。`obj.setoption` では `antialias` に加えて、`obj.draw` / `obj.drawpoly` の合成モードを YMM4 の並びで指定する `blend`、描画先を `"framebuffer"` / `"tempbuffer"` で切り替える `drawtarget`、作業画像の出力可否を切り替える `draw_state` に対応します。MoonSharp では `tempbuffer` への合成を GPU で実行し、GPU を利用できない環境では CPU の合成へ自動的に切り替わります。丸めの違いにより、合成の結果はエンジン間でごく僅かに異なることがあります。
|
||||
- **`obj.setanchor(name, count [, option, ...])`**: プレビュー上にドラッグ可能なアンカーポイントを表示し、その座標を `name` の Lua 変数(`pos={x0,y0,x1,y1,…}`、`"xyz"` 指定時は `{x0,y0,z0,…}`)へ格納します。座標はオブジェクトの中心が原点で、ドラッグで調整した値はプロジェクトへ保存されます。最大 32 個で、`"line"` / `"loop"` / `"star"` / `"arm"` の線結びと `"xyz"` の 3D 指定に対応します。設置数を返し、従来エンジン(MoonSharp)と高速ランタイム(LuaJIT)の双方で動作します。`name` に `"track"` を指定するトラックバー連携は未対応です。
|
||||
- **`obj.setanchor(name, count [, option, ...])`**: プレビュー上にドラッグ可能なアンカーポイントを表示し、その座標を `name` の Lua 変数(`pos={x0,y0,x1,y1,…}`、`"xyz"` 指定時は `{x0,y0,z0,…}`)へ格納します。座標はオブジェクトの中心が原点で、ドラッグで調整した値はプロジェクトへ保存されます。最大 32 個で、`"line"` / `"loop"` / `"star"` / `"arm"` の線結びと `"xyz"` の 3D 指定に対応します。設置数を返し、従来エンジン(MoonSharp)と高速ランタイム(LuaJIT)の双方で動作します。`name` に `"track"` を指定した場合も対応し、個数 0 は 1 個として設置します。選択中のアンカーは「アンカー」グループの `X` / `Y` / `Z` スライダーで数値調整できます。
|
||||
- **`obj.effect` の AviUtl/AviUtl2 互換マップ**: `obj.effect("エフェクト名", "パラメータ名", 値, …)` はまず互換マップを参照し、AviUtl/AviUtl2 の名前として宣言したエフェクトを、対応する YMM4 の映像エフェクトとプロパティへ変換して適用します。値の倍率とオフセットの変換まで宣言できます。互換マップに宣言が無い名前は、従来どおり YMM4 のエフェクト名・キーワードでそのまま解決するため、既存の呼び出しはそのまま動きます。この互換マップは YMM4 自身が AviUtl の `.exo` へ書き出す変換を逆向きにたどって構築しているため、往復しても結果が一致します。対象のエンジンは指定子 `--!aviutl` または `--!aviutl2` で切り替え、指定子を書かないときは `--!aviutl` として扱います。互換マップが対応するエフェクト名の一覧はドキュメントの「obj の関数」を参照してください。
|
||||
|
||||
- **`obj.pixelshader` による AviUtl ExEdit2 互換のピクセルシェーダー**: スクリプト内の `--[[pixelshader@登録名: … ]]` コメントに HLSL で記述したピクセルシェーダーを、`obj.pixelshader("登録名", 出力先, リソース, 定数, blend, sampler)` で GPU 実行します。記法は AviUtl ExEdit2 と同一で、登録名がエントリーポイントになり、リソースはシェーダーリソース `t0`~`t7`、定数は定数バッファ `b0`、サンプラーは `SamplerState` `s0` に設定されます。出力先とリソースは `"object"` / `"tempbuffer"` / `"cache:名前"` / `"framebuffer"` のバッファに対応し、リソースでは 0.0~1.0 の乱数値の 256x256 領域である `"random"` も指定できます。`"framebuffer"` はシーンサイズの仮想フレームバッファで、リソースとして指定するとオブジェクトを現在位置に合成した画像になり、出力先として指定すると結果でオブジェクト画像を置き換えます。YMM4 は背景を参照できないため、初期内容に背景は含まれません。合成方法は `"copy"` / `"mask"` / `"draw"` / `"add"` に加えて、`obj.setoption("blend", 番号)` と同じ番号の数値指定に対応し、数値指定ではシェーダーの出力を YMM4 の合成モードで出力先へ合成します。サンプラーは `"clip"` / `"clamp"` / `"loop"` / `"mirror"` / `"dot"` に対応します。実行は Direct3D 11 で行い、GPU を利用できない環境では WARP ラスタライザーへ、それも利用できないときは呼び出しのスキップへ自動的に切り替わります。HLSL のコンパイルエラーはエディターの診断へ表示されます。`obj.pixelshader` は従来エンジン(MoonSharp)と高速ランタイム(LuaJIT)の双方で動作し、シェーダーの実行自体はどちらのエンジンでもホスト側の GPU で行われます。
|
||||
|
||||
- **AviUtl 互換のグローバル関数**: `RGB` / `HSV`(色情報と各要素の相互変換。6 引数指定で時間変化)、`OR` / `AND` / `XOR`(32bit 整数のビット演算)、`SHIFT`(算術シフト)、`debug_print`(`OutputDebugString()` への文字列送信。スクリプトの実行エラーも自動で送信されます)をグローバルスコープで呼び出せます。すべての実行エンジンで同一の結果を返します。
|
||||
|
||||
次のような機能は、この互換層では対象外です(呼び出しを含むスクリプトは意図どおりには動作しません)。
|
||||
@@ -228,6 +231,26 @@ AviUtl のアニメーション効果スクリプト(`.anm` 系)のうち、
|
||||
- `obj.mes` / `obj.rand1` などの未実装関数
|
||||
- `require` によるモジュール読み込み、`io` / `dofile` などの任意ファイルアクセス(`obj.load("image"/"movie")` のみ、先頭ヘッダー検証付きで対応)
|
||||
|
||||
### 10. 構文拡張
|
||||
|
||||
標準の Lua には無い簡易な記法をいくつか追加しています。キーボードで打ちやすく入力量を減らすための糖衣構文で、スクリプトは実行前に等価な標準 Lua へ変換されます。変換はすべての実行エンジン(LuaJIT・MoonSharp・CPU カーネル)に適用され、文字列とコメントの内側は変換しません。Lua に存在しない記号だけを入口にしているため、既存のスクリプトはそのまま動作します。
|
||||
|
||||
- **比較**: `a is b`(`a == b`)、`a is not b`(`a ~= b`)、`a != b`(`a ~= b`)
|
||||
- **論理**: `!a`(`not a`)、`a && b`(`a and b`)、`a || b`(`a or b`)
|
||||
- **複合代入**: `+=` `-=` `*=` `/=` `%=` `^=` `..=`(例: `x += 1` は `x = x + (1)`)
|
||||
- **nil 合体**: `a ?? b`(`a` が `nil` のときだけ `b` を返す。`false` は返しません)、`x ??= b`
|
||||
- **論理代入**: `x ||= b`(`x = x or (b)`)、`x &&= b`(`x = x and (b)`)
|
||||
- **インクリメント**: `x++`(`x = x + 1`)
|
||||
- **範囲 for**: `for i in <0..10>`(`for i = 0, 10`。終端を含む)、`<0..<10>`(終端を含まない)、`<0..10, 2>`(増分 2)
|
||||
- **三項演算子**: `cond ? a : b`(`cond` が真なら `a`、偽なら `b`。`false` や `nil` の分岐もそのまま返す)
|
||||
- **nil 条件演算子**: `t?.x`(`t` が `nil` なら `nil`、そうでなければ `t.x`)、`t?[k]`(添字アクセス。対象は 1 度だけ評価)
|
||||
- **ラムダ式**: `(a, b) => a + b`(`(function(a, b) return a + b end)`)、引数が 1 つなら `x => x * 2`、無しなら `() => 1`
|
||||
- **パイプ**: `x |> f`(`f((x))`。左辺を第 1 引数に渡す)、`x |> clamp(0, 255)`(`clamp((x), 0, 255)`)
|
||||
- **補間文字列**: `` `x={a}` ``(`("x=" .. tostring(a))`。`{ }` の中に式を書く。拡張構文も使える)
|
||||
- **範囲判定**: `x in <1..5>`(`1 <= x and x <= 5`)、`<1..<5>`(上限を含まない)
|
||||
|
||||
各記法の詳しい説明と例はドキュメント(`LuaScript/docs`)およびサイトの「構文拡張」を参照してください。
|
||||
|
||||
---
|
||||
|
||||
## 実行モデル
|
||||
@@ -249,7 +272,7 @@ AviUtl のアニメーション効果スクリプト(`.anm` 系)のうち、
|
||||
|
||||
いずれのディレクティブも、利用不可・非対応の場合は出力を壊さずに下位のエンジンへ自動的にフォールバックします(例:`--!gpu` の初期化に失敗した場合は CPU カーネル、さらに MoonSharp へ縮退します)。
|
||||
|
||||
CPU / GPU カーネルが成立するのは、四則演算・`math.*`・比較・しきい値の「条件 and 値1 or 値2」・`local` 変数のみを使い、処理中の自ピクセル(`obj.getpixel(x, y)`)と `obj` / `scene` / `time` 等の値だけを参照する純粋な写像(色変換・グレースケール・ガンマ・しきい値・チャンネル混合など)の場合です。近傍参照(ぼかし等)・別座標への書き込み・`getpixeldata`・`getobject`・テーブル/文字列操作・`if` 文などを含む場合はカーネル化されず、自動的に LuaJIT または MoonSharp で実行されます。コンパイル済みのカーネルはスクリプト本文をキーにキャッシュされ、初回フレームのみコンパイルコストを払います。
|
||||
CPU / GPU カーネルが成立するのは、四則演算・`math.*`・比較・しきい値の「条件 and 値1 or 値2」・`if` / `elseif` / `else` による `local` 変数への条件代入・`local` 変数のみを使い、処理中の自ピクセルと `obj` / `scene` / `time` 等の値だけを参照する純粋な写像(色変換・グレースケール・ガンマ・しきい値・チャンネル混合など)の場合です。`obj.getpixel` / `obj.setpixel` の二重ループに加えて、`obj.getpixeldata()` のハンドルを基底インデックス `local i = (y * data.width + x) * 4` で読み書きする形(末尾の `obj.putpixeldata(data)` は任意)もカーネル化されます。ループの上限には `local w = obj.w` のような別名も使えます。近傍参照(ぼかし等)・別座標への書き込み・`if` 文の中での `setpixel` / `set` 呼び出し・`getobject`・テーブル/文字列操作などを含む場合はカーネル化されず、自動的に LuaJIT または MoonSharp で実行されます。コンパイル済みのカーネルはスクリプト本文をキーにキャッシュされ、初回フレームのみコンパイルコストを払います。
|
||||
|
||||
ネイティブ実行は**専用の別プロセス**で行われ、ピクセルバッファは共有メモリ経由で受け渡されます。ピクセルの転送はスクリプトがピクセルへ初めてアクセスした時点でのみ行われるため、変形や描画だけのスクリプトでは転送が発生しません。ワーカープロセスは入力画像のサイズが変わっても再起動せず、フレームをまたいで再利用されます。スクリプトが無限ループに陥った場合でも **5 秒のタイムアウトでプロセスを強制終了**するため本体は固まらず、終了後は自動的に復帰します。出力結果は MoonSharp と一致します。
|
||||
|
||||
|
||||
+2
-1
@@ -11,7 +11,8 @@
|
||||
group: "Lua 言語",
|
||||
items: [
|
||||
{ title: "Lua の基礎", href: "lua-basics.html" },
|
||||
{ title: "標準ライブラリ", href: "stdlib.html" }
|
||||
{ title: "標準ライブラリ", href: "stdlib.html" },
|
||||
{ title: "構文拡張", href: "syntax.html" }
|
||||
]
|
||||
},
|
||||
{
|
||||
|
||||
+10
-2
@@ -79,12 +79,20 @@ CPU / GPU カーネルは、次の決まった形のスクリプトだけを変
|
||||
<ul>
|
||||
<li>先頭に <code>local</code> 宣言を置いてもよい。</li>
|
||||
<li>本体は二重の数値 for ループ 1 組だけ。外側と内側で <code>obj.h</code> と <code>obj.w</code> をそれぞれ
|
||||
<code>0</code> から <code>-1</code> まで回す。</li>
|
||||
<code>0</code> から <code>-1</code> まで回す。上限には <code>local w = obj.w</code> のような別名も使える。</li>
|
||||
<li>内側ループの最初が <code>local r, g, b[, a] = obj.getpixel(x, y)</code>、最後が
|
||||
<code>obj.setpixel(x, y, ...)</code>。</li>
|
||||
<li>その間は <code>local</code> 宣言と代入のみ。</li>
|
||||
<li>その間は <code>local</code> 宣言と代入、および <code>if</code> / <code>elseif</code> / <code>else</code> による
|
||||
<code>local</code> 変数への条件代入のみ。</li>
|
||||
</ul>
|
||||
|
||||
<p>
|
||||
<code>obj.getpixeldata()</code> で得たハンドルの <code>get</code> / <code>set</code> を
|
||||
<code>local i = (y * data.width + x) * 4</code> の基底インデックスで使う形も同様にカーネル化されます。
|
||||
ループの後の <code>obj.putpixeldata(data)</code> は置いても置かなくてもかまいません。
|
||||
<code>if</code> 文の中で <code>obj.setpixel</code> や <code>set</code> を呼ぶ形はカーネル化されません。
|
||||
</p>
|
||||
|
||||
<p>カーネル内で使える要素は限られます。</p>
|
||||
|
||||
<table>
|
||||
|
||||
+1
-1
@@ -106,7 +106,7 @@ debug_print(string.format("x = %d", obj.x))</code></pre>
|
||||
<p>これらの中身は <a href="stdlib.html">標準ライブラリ</a> にまとめています。</p>
|
||||
|
||||
<div class="pager">
|
||||
<a href="stdlib.html">← 標準ライブラリ</a>
|
||||
<a href="syntax.html">← 構文拡張</a>
|
||||
<a href="obj.html">obj オブジェクト →</a>
|
||||
</div>
|
||||
|
||||
|
||||
+1
-1
@@ -39,7 +39,7 @@
|
||||
<h2>非対応の機能</h2>
|
||||
|
||||
<ul>
|
||||
<li><code>obj.setanchor()</code> など、本ドキュメントに記載のない AviUtl 関数は対応していません。</li>
|
||||
<li><code>obj.mes()</code> など、本ドキュメントに記載のない AviUtl 関数は対応していません。</li>
|
||||
<li><code>obj.effect</code> は、AviUtl/AviUtl2 互換マップに宣言したエフェクト名と、YMM4 に読み込まれている映像エフェクトの名前・キーワードを解決します。
|
||||
名前が見つからない・適用に失敗した場合は、そのフレームでは元の映像がそのまま使われます。
|
||||
互換マップが対応するエフェクト名の一覧は<a href="obj-functions.html">obj の関数</a>を参照してください。</li>
|
||||
|
||||
@@ -95,6 +95,11 @@ x, y = y, x</code></pre>
|
||||
local v = amp ~= 0 and amp or 50
|
||||
obj.x = obj.x + v</code></pre>
|
||||
|
||||
<p>
|
||||
このプラグインは、標準の Lua に無い記法(<code>is not</code>・<code>??</code>・複合代入・範囲 for など)も追加しています。
|
||||
詳しくは<a href="syntax.html">構文拡張</a>を参照してください。
|
||||
</p>
|
||||
|
||||
<h2>条件分岐</h2>
|
||||
|
||||
<pre><code>if obj.t < 0.5 then
|
||||
|
||||
+46
-2
@@ -166,7 +166,8 @@ obj.load("text", "サンプル")</code></pre>
|
||||
<tr><td><code>obj.effect(name, key1, val1, ...)</code></td><td>AviUtl/AviUtl2 のエフェクト名で YMM4 の映像エフェクトを適用する。<code>key, val</code> の組は AviUtl のパラメータ名で指定し、互換マップを通じて YMM4 のプロパティへ変換される</td></tr>
|
||||
<tr><td><code>obj.draw([ox, oy, oz, zoom, alpha, aspect])</code></td><td>現在のバッファをオフセット・拡大率・不透明度を指定して描画する</td></tr>
|
||||
<tr><td><code>obj.drawpoly(x0,y0,z0, x1,y1,z1, x2,y2,z2, x3,y3,z3 [, u0,v0, ... ,u3,v3] [, alpha])</code></td><td>4 頂点のテクスチャ付きポリゴンを描画する。UV を省略すると画像全体を使う</td></tr>
|
||||
<tr><td><code>obj.copybuffer(dst, src)</code></td><td>バッファ間でコピーする。ID は <code>obj</code>(作業画像)・<code>tmp</code>・<code>cache:名前</code>。書き込み先が <code>obj</code> のときのみ作業画像を置き換える</td></tr>
|
||||
<tr><td><code>obj.copybuffer(dst, src)</code></td><td>バッファ間でコピーする。ID は <code>obj</code>(作業画像)・<code>tmp</code>・<code>cache:名前</code>・<code>frm</code>(コピー元のみ・仮想フレームバッファ)。書き込み先が <code>obj</code> のときのみ作業画像を置き換える</td></tr>
|
||||
<tr><td><code>obj.pixelshader(name, target, resources [, constants, blend, sampler])</code></td><td>スクリプト内に定義した HLSL のピクセルシェーダーを GPU で実行する。詳細は下記の「ピクセルシェーダー」を参照</td></tr>
|
||||
<tr><td><code>obj.setoption(name [, value])</code></td><td>オプションを設定する。<code>antialias</code> は <code>obj.draw</code> で参照される。<code>blend</code> は <code>obj.draw</code>/<code>obj.drawpoly</code> の合成モードを番号で指定する。番号は下記の「合成モード」を参照。<code>draw_state</code> は真偽値で、<code>true</code> なら作業画像を出力し、<code>false</code> なら入力をそのまま通す。<code>drawtarget</code> は <code>obj.draw</code>/<code>obj.drawpoly</code> の描画先を <code>"framebuffer"</code> と <code>"tempbuffer"</code> で切り替える。詳細は下記の「描画先」を参照</td></tr>
|
||||
<tr><td><code>obj.getoption(name)</code></td><td>設定したオプションを取得する</td></tr>
|
||||
<tr><td><code>obj.getvalue(name)</code></td><td><code>obj</code> の数値メンバーを名前で取得する</td></tr>
|
||||
@@ -245,6 +246,49 @@ obj.draw()
|
||||
obj.setoption("drawtarget", "framebuffer")
|
||||
obj.copybuffer("obj", "tmp")</code></pre>
|
||||
|
||||
<h3>ピクセルシェーダー</h3>
|
||||
|
||||
<p>
|
||||
<code>obj.pixelshader</code> は、スクリプト内に AviUtl ExEdit2 と同じ記法で定義した HLSL のピクセルシェーダーを GPU で実行します。
|
||||
シェーダーは <code>--[[pixelshader@登録名:</code> で始まる複数行コメントに記述し、登録名がエントリーポイントになります。
|
||||
</p>
|
||||
|
||||
<pre><code>--[[pixelshader@ps:
|
||||
Texture2D src : register(t0);
|
||||
cbuffer constant0 : register(b0) { float strength; }
|
||||
float4 ps(float4 pos : SV_Position) : SV_Target
|
||||
{
|
||||
float4 c = src[uint2(floor(pos.xy))];
|
||||
return float4(c.rgb * strength, c.a);
|
||||
}
|
||||
]]
|
||||
obj.pixelshader("ps", "object", "object", { obj.track0 / 100 })</code></pre>
|
||||
|
||||
<table>
|
||||
<tr><th>引数</th><th>説明</th></tr>
|
||||
<tr><td><code>name</code></td><td>定義したシェーダーの登録名。エントリーポイントの関数名と一致させる</td></tr>
|
||||
<tr><td><code>target</code></td><td>出力先のバッファ名。<code>"object"</code>・<code>"tempbuffer"</code>・<code>"cache:名前"</code>・<code>"framebuffer"</code> に対応する。<code>"framebuffer"</code> はシーンサイズの仮想フレームバッファへ描画し、結果でオブジェクト画像を置き換える</td></tr>
|
||||
<tr><td><code>resources</code></td><td>参照するバッファ名の配列で、シェーダーリソース <code>t0</code>~<code>t7</code> に設定される。1 つの場合は文字列で直接指定できる。<code>"random"</code> は 0.0~1.0 の乱数値の 256x256 領域(<code>R32_FLOAT</code>)になる。<code>"framebuffer"</code> はオブジェクトを現在位置に合成したシーンサイズの仮想フレームバッファになる</td></tr>
|
||||
<tr><td><code>constants</code></td><td>数値の配列で、定数バッファ(<code>b0</code>)へ <code>float</code> の配列として設定される</td></tr>
|
||||
<tr><td><code>blend</code></td><td>出力先への合成方法。<code>"copy"</code>(そのまま・既定)・<code>"mask"</code>(α値のみ乗算)・<code>"draw"</code>(アルファブレンド)・<code>"add"</code>(加算)に対応する。<code>obj.setoption("blend", 番号)</code> と同じ番号を数値で指定すると、シェーダーの出力を YMM4 の合成モードで出力先へ合成する</td></tr>
|
||||
<tr><td><code>sampler</code></td><td><code>SamplerState</code>(<code>s0</code>)の種別。<code>"clip"</code>・<code>"clamp"</code>・<code>"loop"</code>・<code>"mirror"</code>・<code>"dot"</code> に対応し、省略時は未設定になる</td></tr>
|
||||
</table>
|
||||
|
||||
<p>
|
||||
ピクセルシェーダーの入力は次のどちらかのシグネチャを使用できます。
|
||||
<code>uv</code> は描画範囲が 0.0~1.0 になるように設定されます。
|
||||
</p>
|
||||
|
||||
<pre><code>float4 名前(float4 pos : SV_Position) : SV_Target
|
||||
float4 名前(float4 pos : SV_Position, float2 uv : TEXCOORD) : SV_Target</code></pre>
|
||||
|
||||
<p>
|
||||
<code>obj.pixelshader</code> は両エンジンで動作し、シェーダーの実行自体はどちらのエンジンでもホスト側の GPU で行われます。
|
||||
YMM4 は背景を参照できないため、<code>"framebuffer"</code> の初期内容は透明なシーンサイズ領域へオブジェクトを合成した仮想の画像です。
|
||||
HLSL のコンパイルエラーはエディターの診断へ表示されます。
|
||||
GPU を利用できない環境では呼び出しはスキップされ、画像は変化しません。
|
||||
</p>
|
||||
|
||||
<h3>アンカーポイント</h3>
|
||||
|
||||
<p>
|
||||
@@ -265,7 +309,7 @@ obj.copybuffer("obj", "tmp")</code></pre>
|
||||
|
||||
<p>
|
||||
戻り値は設置したアンカーポイントの数です。両エンジンで動きます。
|
||||
<code>name</code> に <code>"track"</code> を指定するトラックバー連携は現在未対応で、<code>0</code> を返します。
|
||||
<code>name</code> に <code>"track"</code> を指定した場合も対応し、個数 0 は 1 個として設置します。選択中のアンカーは アンカー グループの <code>X</code> / <code>Y</code> / <code>Z</code> スライダーで数値調整できます。
|
||||
</p>
|
||||
|
||||
<pre><code>num = obj.track0
|
||||
|
||||
+3
-2
@@ -126,8 +126,9 @@ A チャンネル(インデックス <code>base + 4</code>)を変更する
|
||||
<p>
|
||||
ピクセル処理は重くなりがちです。このプラグインは <code>getpixel</code> / <code>setpixel</code> を含むスクリプトを、
|
||||
利用できる環境では自動的に高速なネイティブレーンへ振り分けます。さらに、二重ループで
|
||||
<code>getpixel</code> → 計算 → <code>setpixel</code> という決まった形のスクリプトは、CPU カーネルや GPU カーネルへ
|
||||
変換してさらに高速に実行します。GPU カーネルは初回に CPU カーネルとの一致を検証したうえで自動選択します。
|
||||
<code>getpixel</code> → 計算 → <code>setpixel</code> という決まった形のスクリプトや、
|
||||
<code>getpixeldata</code> のハンドルを基底インデックスで読み書きする決まった形のスクリプトは、
|
||||
CPU カーネルや GPU カーネルへ変換してさらに高速に実行します。GPU カーネルは初回に CPU カーネルとの一致を検証したうえで自動選択します。
|
||||
詳しくは <a href="engines.html">エンジンと高速化</a> を参照してください。
|
||||
</p>
|
||||
|
||||
|
||||
@@ -77,6 +77,11 @@
|
||||
<priority>0.7</priority>
|
||||
<lastmod>2026-06-30T12:31:48+09:00</lastmod>
|
||||
</url>
|
||||
<url>
|
||||
<loc>https://luascript.routersys.com/syntax.html</loc>
|
||||
<priority>0.7</priority>
|
||||
<lastmod>2026-07-03T00:00:00+09:00</lastmod>
|
||||
</url>
|
||||
<url>
|
||||
<loc>https://luascript.routersys.com/reference.html</loc>
|
||||
<priority>0.7</priority>
|
||||
|
||||
+1
-1
@@ -142,7 +142,7 @@ extract, replace, btest, countlz, countrz</code></pre>
|
||||
|
||||
<div class="pager">
|
||||
<a href="lua-basics.html">← Lua の基礎</a>
|
||||
<a href="globals.html">グローバル変数 →</a>
|
||||
<a href="syntax.html">構文拡張 →</a>
|
||||
</div>
|
||||
|
||||
</main>
|
||||
|
||||
+260
@@ -0,0 +1,260 @@
|
||||
<!DOCTYPE html>
|
||||
<html lang="ja">
|
||||
<head>
|
||||
<meta charset="utf-8">
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1">
|
||||
<title>構文拡張 | Lua スクリプト for YMM4</title>
|
||||
<link rel="stylesheet" href="assets/style.css">
|
||||
</head>
|
||||
<body>
|
||||
<button id="navtoggle" aria-label="メニュー">☰</button>
|
||||
<nav id="sidebar"></nav>
|
||||
<main>
|
||||
|
||||
<h1>構文拡張</h1>
|
||||
|
||||
<p>
|
||||
このプラグインは、標準の Lua には無い簡易な記法をいくつか追加しています。キーボードで打ちやすく、
|
||||
入力量と読み替えの手間を減らすための糖衣構文です。スクリプトは実行前に等価な標準 Lua へ変換されるため、
|
||||
すべての実行エンジン(LuaJIT・MoonSharp・CPU カーネル)で同じように動きます。
|
||||
</p>
|
||||
|
||||
<div class="note">
|
||||
変換は字句単位で行い、<strong>文字列とコメントの内側は変換しません</strong>。
|
||||
また Lua に存在しない記号(<code>?</code> <code>!</code> <code>&</code> <code>|</code> <code>=></code> <code>`</code> や <code>in <</code> の並び)だけを入口にしているため、
|
||||
通常の Lua スクリプトはそのまま動作します。
|
||||
</div>
|
||||
|
||||
<h2>比較演算子</h2>
|
||||
|
||||
<p><code>is</code> と <code>is not</code> は、値どうしを比べる位置に書いたときだけ演算子として扱います。変数名としての <code>is</code> は変換しません。</p>
|
||||
|
||||
<table>
|
||||
<tr><th>書き方</th><th>意味</th></tr>
|
||||
<tr><td><code>a is b</code></td><td><code>a == b</code></td></tr>
|
||||
<tr><td><code>a is not b</code></td><td><code>a ~= b</code></td></tr>
|
||||
<tr><td><code>a != b</code></td><td><code>a ~= b</code></td></tr>
|
||||
</table>
|
||||
|
||||
<pre><code>if frame is not 0 then
|
||||
obj.x = 100
|
||||
end</code></pre>
|
||||
|
||||
<h2>論理演算子</h2>
|
||||
|
||||
<p>他言語でなじみのある記号を、Lua の <code>and</code> / <code>or</code> / <code>not</code> の別名として使えます。</p>
|
||||
|
||||
<table>
|
||||
<tr><th>書き方</th><th>意味</th></tr>
|
||||
<tr><td><code>!a</code></td><td><code>not a</code></td></tr>
|
||||
<tr><td><code>a && b</code></td><td><code>a and b</code></td></tr>
|
||||
<tr><td><code>a || b</code></td><td><code>a or b</code></td></tr>
|
||||
</table>
|
||||
|
||||
<pre><code>if !hidden && frame != 0 then
|
||||
obj.alpha = 255
|
||||
end</code></pre>
|
||||
|
||||
<h2>複合代入</h2>
|
||||
|
||||
<p>左辺の値を使って計算し、同じ場所へ書き戻す記法です。右辺は括弧で包んで展開するため、演算子の優先順位はそのまま保たれます。</p>
|
||||
|
||||
<table>
|
||||
<tr><th>書き方</th><th>展開後</th></tr>
|
||||
<tr><td><code>x += 1</code></td><td><code>x = x + (1)</code></td></tr>
|
||||
<tr><td><code>x -= 1</code></td><td><code>x = x - (1)</code></td></tr>
|
||||
<tr><td><code>x *= 2</code></td><td><code>x = x * (2)</code></td></tr>
|
||||
<tr><td><code>x /= 2</code></td><td><code>x = x / (2)</code></td></tr>
|
||||
<tr><td><code>x %= 2</code></td><td><code>x = x % (2)</code></td></tr>
|
||||
<tr><td><code>x ^= 2</code></td><td><code>x = x ^ (2)</code></td></tr>
|
||||
<tr><td><code>s ..= "b"</code></td><td><code>s = s .. ("b")</code>(文字列の連結)</td></tr>
|
||||
</table>
|
||||
|
||||
<pre><code>local total = 0
|
||||
total += obj.track0
|
||||
total *= 2</code></pre>
|
||||
|
||||
<h2>インクリメント</h2>
|
||||
|
||||
<p><code>++</code> は行単位の文として使い、1 を加えて書き戻します。</p>
|
||||
|
||||
<pre><code>count++</code></pre>
|
||||
|
||||
<p>上の <code>count++</code> は <code>count = count + 1</code> に展開します。</p>
|
||||
|
||||
<h2>nil 合体演算子</h2>
|
||||
|
||||
<p>
|
||||
<code>a ?? b</code> は、<code>a</code> が <code>nil</code> のときだけ <code>b</code> を返します。
|
||||
<code>a and b or c</code> と違い、<code>a</code> が <code>false</code> のときは <code>false</code> をそのまま返します。既定値を安全に書けます。
|
||||
</p>
|
||||
|
||||
<pre><code>obj.x = obj.track0 ?? 100</code></pre>
|
||||
|
||||
<div class="note">
|
||||
<code>a ?? b</code> は左辺を 1 度だけ評価する無名関数に展開します。<code>b</code> は左辺が <code>nil</code> のときだけ評価されます。
|
||||
</div>
|
||||
|
||||
<h2>代入をともなう演算子</h2>
|
||||
|
||||
<p>変数が未設定・偽のときにまとめて代入する記法です。</p>
|
||||
|
||||
<table>
|
||||
<tr><th>書き方</th><th>意味</th></tr>
|
||||
<tr><td><code>x ??= b</code></td><td><code>x</code> が <code>nil</code> のときだけ <code>b</code> を代入</td></tr>
|
||||
<tr><td><code>x ||= b</code></td><td><code>x = x or (b)</code></td></tr>
|
||||
<tr><td><code>x &&= b</code></td><td><code>x = x and (b)</code></td></tr>
|
||||
</table>
|
||||
|
||||
<pre><code>speed ??= 90
|
||||
obj.rz = time * speed</code></pre>
|
||||
|
||||
<h2>範囲 for</h2>
|
||||
|
||||
<p>
|
||||
数値 for を、範囲を視覚的に表す <code><開始..終了></code> で書けます。<code>..</code> は終端を含み、
|
||||
<code>..<</code> は終端を含みません。<code>,</code> のあとに増分を指定できます。
|
||||
</p>
|
||||
|
||||
<table>
|
||||
<tr><th>書き方</th><th>意味</th></tr>
|
||||
<tr><td><code>for i in <0..10> do</code></td><td><code>for i = 0, 10 do</code>(10 を含む)</td></tr>
|
||||
<tr><td><code>for i in <0..<10> do</code></td><td><code>for i = 0, (10) - 1 do</code>(10 を含まない)</td></tr>
|
||||
<tr><td><code>for i in <0..10, 2> do</code></td><td><code>for i = 0, 10, 2 do</code>(増分 2)</td></tr>
|
||||
</table>
|
||||
|
||||
<pre><code>local sum = 0
|
||||
for i in <1..10> do
|
||||
sum = sum + i
|
||||
end</code></pre>
|
||||
|
||||
<div class="note">
|
||||
<code>in <</code> の並びは通常の Lua には現れないため、<code>ipairs</code> や <code>pairs</code> を使う汎用 for には影響しません。
|
||||
</div>
|
||||
|
||||
<h2>三項演算子</h2>
|
||||
|
||||
<p>
|
||||
<code>条件 ? A : B</code> は、条件が真のとき <code>A</code> を、偽のとき <code>B</code> を返します。
|
||||
<code>a and A or B</code> と違い、<code>A</code> が <code>false</code> や <code>nil</code> のときも、その値をそのまま返します。
|
||||
</p>
|
||||
|
||||
<table>
|
||||
<tr><th>書き方</th><th>意味</th></tr>
|
||||
<tr><td><code>c ? 1 : 2</code></td><td><code>c</code> が真なら <code>1</code>、偽なら <code>2</code></td></tr>
|
||||
</table>
|
||||
|
||||
<pre><code>obj.alpha = obj.frame == 0 ? 0 : 255</code></pre>
|
||||
|
||||
<div class="note">
|
||||
<code>? :</code> は条件を 1 度だけ評価する無名関数に展開します。<code>:</code> のあとにもう一度 <code>? :</code> を書けば、else 側で分岐を続けられます。
|
||||
</div>
|
||||
|
||||
<h2>nil 条件演算子</h2>
|
||||
|
||||
<p>
|
||||
<code>t?.name</code> は、<code>t</code> が <code>nil</code> のときは <code>nil</code> を返し、そうでなければ <code>t.name</code> を返します。
|
||||
<code>nil</code> の値へ添字アクセスして落ちるのを防ぎます。<code>t?[k]</code> と書けば添字でも同じことができます。
|
||||
</p>
|
||||
|
||||
<table>
|
||||
<tr><th>書き方</th><th>意味</th></tr>
|
||||
<tr><td><code>t?.x</code></td><td><code>t</code> が <code>nil</code> なら <code>nil</code>、そうでなければ <code>t.x</code></td></tr>
|
||||
<tr><td><code>t?[k]</code></td><td><code>t</code> が <code>nil</code> なら <code>nil</code>、そうでなければ <code>t[k]</code></td></tr>
|
||||
</table>
|
||||
|
||||
<pre><code>local title = data?.title ?? "無題"</code></pre>
|
||||
|
||||
<div class="note">
|
||||
<code>?.</code> は対象を 1 度だけ評価する無名関数に展開します。<code>a?.b?.c</code> のように連ねれば、途中が <code>nil</code> でも安全にたどれます。
|
||||
</div>
|
||||
|
||||
<h2>ラムダ式</h2>
|
||||
|
||||
<p>
|
||||
<code>(引数) => 式</code> は、その式を返す無名関数に展開します。引数が 1 つのときは括弧を省いて <code>x => 式</code>、
|
||||
引数が無いときは <code>() => 式</code> と書けます。本体には 1 つの式を書きます。
|
||||
</p>
|
||||
|
||||
<table>
|
||||
<tr><th>書き方</th><th>展開後</th></tr>
|
||||
<tr><td><code>(a, b) => a + b</code></td><td><code>(function(a, b) return a + b end)</code></td></tr>
|
||||
<tr><td><code>x => x * 2</code></td><td><code>(function(x) return x * 2 end)</code></td></tr>
|
||||
<tr><td><code>() => 1</code></td><td><code>(function() return 1 end)</code></td></tr>
|
||||
</table>
|
||||
|
||||
<pre><code>local t = { 3, 1, 2 }
|
||||
table.sort(t, (a, b) => a < b)</code></pre>
|
||||
|
||||
<div class="note">
|
||||
<code>=></code> だけを入口にしているため、比較演算子の <code>>=</code> や <code><=</code> には影響しません。
|
||||
</div>
|
||||
|
||||
<h2>パイプ</h2>
|
||||
|
||||
<p>
|
||||
<code>x |> f</code> は <code>f(x)</code> の形に展開し、左辺を関数の第 1 引数として渡します。
|
||||
<code>x |> f(a, b)</code> のように引数を書いたときは、左辺が第 1 引数に入り、残りの引数は後ろへ続きます。
|
||||
</p>
|
||||
|
||||
<table>
|
||||
<tr><th>書き方</th><th>展開後</th></tr>
|
||||
<tr><td><code>x |> f</code></td><td><code>f((x))</code></td></tr>
|
||||
<tr><td><code>x |> clamp(0, 255)</code></td><td><code>clamp((x), 0, 255)</code></td></tr>
|
||||
</table>
|
||||
|
||||
<pre><code>local v = obj.track0 |> math.floor |> tostring</code></pre>
|
||||
|
||||
<div class="note">
|
||||
<code>|></code> は左から右へ連ねられます。<code>a |> f |> g</code> は <code>g(f(a))</code> と同じ順序で評価します。
|
||||
</div>
|
||||
|
||||
<h2>補間文字列</h2>
|
||||
|
||||
<p>
|
||||
バッククォート <code>`</code> で囲んだ文字列の中に <code>{式}</code> を書くと、その値を <code>tostring</code> で文字列にして差し込みます。
|
||||
<code>{ }</code> の中では拡張構文もそのまま使えます。
|
||||
</p>
|
||||
|
||||
<table>
|
||||
<tr><th>書き方</th><th>展開後</th></tr>
|
||||
<tr><td><code>`x={a}`</code></td><td><code>("x=" .. tostring(a))</code></td></tr>
|
||||
<tr><td><code>`hello`</code></td><td><code>"hello"</code></td></tr>
|
||||
</table>
|
||||
|
||||
<pre><code>obj.text = `フレーム {obj.frame} / {obj.totalframe}`</code></pre>
|
||||
|
||||
<div class="note">
|
||||
バッククォートを入口にしているため、通常の文字列やコメントの中の <code>`</code> は変換しません。
|
||||
</div>
|
||||
|
||||
<h2>範囲判定</h2>
|
||||
|
||||
<p>
|
||||
<code>x in <開始..終了></code> は、<code>x</code> がその範囲に入っているかどうかを判定します。
|
||||
<code>..</code> は終端を含み、<code>..<</code> は終端を含みません。
|
||||
</p>
|
||||
|
||||
<table>
|
||||
<tr><th>書き方</th><th>意味</th></tr>
|
||||
<tr><td><code>x in <1..5></code></td><td><code>1 <= x and x <= 5</code></td></tr>
|
||||
<tr><td><code>x in <1..<5></code></td><td><code>1 <= x and x < 5</code>(5 を含まない)</td></tr>
|
||||
</table>
|
||||
|
||||
<pre><code>if obj.frame in <0..9> then
|
||||
obj.alpha = 255
|
||||
end</code></pre>
|
||||
|
||||
<div class="note">
|
||||
左辺は 1 度だけ評価する無名関数に展開します。範囲 for の <code>for i in <0..10></code> とは書く位置が異なるため、for のヘッダーには影響しません。
|
||||
</div>
|
||||
|
||||
<div class="pager">
|
||||
<a href="stdlib.html">← 標準ライブラリ</a>
|
||||
<a href="globals.html">グローバル変数 →</a>
|
||||
</div>
|
||||
|
||||
</main>
|
||||
<script src="assets/nav.js"></script>
|
||||
</body>
|
||||
</html>
|
||||
+212
-2
@@ -93,6 +93,16 @@ local CB_KIND_REQUESTPIXELS = 9
|
||||
local CB_KIND_FLUSHDRAWS = 10
|
||||
local CB_KIND_SCENEGET = 11
|
||||
local CB_KIND_SCENESET = 12
|
||||
local CB_KIND_PIXELSHADER_STAGE = 13
|
||||
local CB_KIND_PIXELSHADER_RUN = 14
|
||||
local MAX_PIXEL_BUFFER = 3840 * 2160 * 4
|
||||
local SHADER_META_DOUBLES = 20
|
||||
local SHADER_CONSTANTS_MAX = 1024
|
||||
local SHADER_RESOURCES_MAX = 8
|
||||
local SHADER_REGION_BYTES = SHADER_META_DOUBLES * 8 + SHADER_CONSTANTS_MAX * 4 + MAX_PIXEL_BUFFER
|
||||
local SHADER_META_OFFSET = mapSize - SHADER_REGION_BYTES
|
||||
local SHADER_CONST_OFFSET = SHADER_META_OFFSET + SHADER_META_DOUBLES * 8
|
||||
local SHADER_IMAGE_OFFSET = SHADER_CONST_OFFSET + SHADER_CONSTANTS_MAX * 4
|
||||
|
||||
assert(loadfile(shimPath))()
|
||||
|
||||
@@ -107,7 +117,10 @@ local pixels = ffi.cast("uint8_t*", base + PIXEL_OFFSET)
|
||||
local ringD = ffi.cast("double*", base + DRAW_RING_OFFSET)
|
||||
local cbResult = ffi.cast("double*", base + CB_RESULT_OFFSET)
|
||||
local cbTagD = ffi.cast("double*", base + CB_TAG_OFFSET)
|
||||
local pixelCapacity = mapSize - PIXEL_OFFSET
|
||||
local shaderMeta = ffi.cast("double*", base + SHADER_META_OFFSET)
|
||||
local shaderConst = ffi.cast("float*", base + SHADER_CONST_OFFSET)
|
||||
local shaderImage = base + SHADER_IMAGE_OFFSET
|
||||
local pixelCapacity = SHADER_META_OFFSET - PIXEL_OFFSET
|
||||
local buffers = {}
|
||||
local options = {}
|
||||
local pixeloptions = {}
|
||||
@@ -298,6 +311,32 @@ local function compositeDrawPolyInto(dst, dstW, dstH, src, srcW, srcH, poly, alp
|
||||
end
|
||||
end
|
||||
|
||||
local frameBufferData, frameBufferCapacity = nil, 0
|
||||
local frameBufferW, frameBufferH = 0, 0
|
||||
local frameBufferValid = false
|
||||
|
||||
local function ensureFrameBuffer()
|
||||
local sw = math.max(1, math.floor(f64[39]))
|
||||
local sh = math.max(1, math.floor(f64[40]))
|
||||
local n = sw * sh * 4
|
||||
if not frameBufferData or frameBufferCapacity < n then
|
||||
frameBufferData = ffi.new("uint8_t[?]", n)
|
||||
frameBufferCapacity = n
|
||||
frameBufferValid = false
|
||||
end
|
||||
if not frameBufferValid or frameBufferW ~= sw or frameBufferH ~= sh then
|
||||
ffi.fill(frameBufferData, n)
|
||||
ensurePixels()
|
||||
flushPixelData()
|
||||
frameBufferW = sw
|
||||
frameBufferH = sh
|
||||
compositeDrawInto(frameBufferData, sw, sh, pixels, width, height,
|
||||
sw * 0.5 + f64[8], sh * 0.5 + f64[9], f64[17], f64[18], f64[19] / 255, true)
|
||||
frameBufferValid = true
|
||||
end
|
||||
return frameBufferData, frameBufferW, frameBufferH
|
||||
end
|
||||
|
||||
local function ensureTemp()
|
||||
local t = buffers["t"]
|
||||
if not t then
|
||||
@@ -635,7 +674,7 @@ function obj.setanchor(name, count, ...)
|
||||
if type(name) ~= "string" then return 0 end
|
||||
count = math.floor(count or 0)
|
||||
if count < 0 then count = 0 elseif count > 32 then count = 32 end
|
||||
if name == "track" then return 0 end
|
||||
if name == "track" and count == 0 then count = 1 end
|
||||
|
||||
local connection, is3d = 0, false
|
||||
local optCount = select("#", ...)
|
||||
@@ -684,6 +723,8 @@ function obj.copybuffer(dst, src)
|
||||
local b = buffers[skey]
|
||||
if not b then return end
|
||||
data, w, h = b.data, b.w, b.h
|
||||
elseif sk == "f" then
|
||||
data, w, h = ensureFrameBuffer()
|
||||
else
|
||||
return
|
||||
end
|
||||
@@ -818,6 +859,174 @@ local function buildObject()
|
||||
}
|
||||
end
|
||||
|
||||
local SHADER_BLEND_MODES = { copy = 0, mask = 1, draw = 2, add = 3 }
|
||||
local SHADER_SAMPLERS = { clip = 1, clamp = 2, loop = 3, mirror = 4, dot = 5 }
|
||||
|
||||
local function stageShaderImage(slot, data, w, h)
|
||||
if w * h * 4 > MAX_PIXEL_BUFFER then
|
||||
error("obj.pixelshader: resource is too large for the native engine.", 4)
|
||||
end
|
||||
ffi.copy(shaderImage, data, w * h * 4)
|
||||
shaderMeta[5] = w
|
||||
shaderMeta[6] = h
|
||||
shaderMeta[7] = slot
|
||||
i32[OFF_CB_KIND] = CB_KIND_PIXELSHADER_STAGE
|
||||
i32[OFF_STATUS] = STATUS_CALLBACK
|
||||
k32.SetEvent(doneEvent)
|
||||
k32.WaitForSingleObject(workEvent, INFINITE)
|
||||
end
|
||||
|
||||
local function resolveShaderResource(slot, id)
|
||||
if type(id) ~= "string" then return 2 end
|
||||
if id == "random" then return 1 end
|
||||
local bk, bkey = bufferKind(id)
|
||||
if bk == "o" then
|
||||
ensurePixels()
|
||||
flushPixelData()
|
||||
return 3
|
||||
end
|
||||
if bk == "f" then
|
||||
local data, w, h = ensureFrameBuffer()
|
||||
stageShaderImage(slot, data, w, h)
|
||||
return 0
|
||||
end
|
||||
if bk == "t" or bk == "c" then
|
||||
local b = buffers[bkey]
|
||||
if b then
|
||||
stageShaderImage(slot, b.data, b.w, b.h)
|
||||
return 0
|
||||
end
|
||||
end
|
||||
return 2
|
||||
end
|
||||
|
||||
function obj.pixelshader(name, target, resources, constants, blend, sampler)
|
||||
if type(name) ~= "string" or type(target) ~= "string" then return end
|
||||
|
||||
local blendMode, compositeBlend = 0, 0
|
||||
local blendType = type(blend)
|
||||
if blendType == "number" then
|
||||
blendMode = 4
|
||||
compositeBlend = blend
|
||||
elseif blendType == "string" then
|
||||
blendMode = SHADER_BLEND_MODES[blend]
|
||||
if not blendMode then
|
||||
error("obj.pixelshader: unknown blend '" .. blend .. "'. Use copy, mask, draw, add or a blend number.", 2)
|
||||
end
|
||||
end
|
||||
|
||||
local samplerMode = 0
|
||||
if type(sampler) == "string" then
|
||||
samplerMode = SHADER_SAMPLERS[sampler]
|
||||
if not samplerMode then
|
||||
error("obj.pixelshader: unknown sampler '" .. sampler .. "'. Use clip, clamp, loop, mirror or dot.", 2)
|
||||
end
|
||||
end
|
||||
|
||||
local constantCount = 0
|
||||
if type(constants) == "table" then
|
||||
constantCount = #constants
|
||||
if constantCount > SHADER_CONSTANTS_MAX then
|
||||
error("obj.pixelshader: too many constants (" .. constantCount .. "). Up to " .. SHADER_CONSTANTS_MAX .. " are supported.", 2)
|
||||
end
|
||||
for i = 1, constantCount do
|
||||
shaderConst[i - 1] = tonumber(constants[i]) or 0
|
||||
end
|
||||
end
|
||||
|
||||
local resourceCount = 0
|
||||
if type(resources) == "string" then
|
||||
resourceCount = 1
|
||||
shaderMeta[9] = resolveShaderResource(0, resources)
|
||||
elseif type(resources) == "table" then
|
||||
resourceCount = #resources
|
||||
if resourceCount > SHADER_RESOURCES_MAX then
|
||||
error("obj.pixelshader: too many resources (" .. resourceCount .. "). Up to " .. SHADER_RESOURCES_MAX .. " are supported.", 2)
|
||||
end
|
||||
for i = 1, resourceCount do
|
||||
shaderMeta[9 + (i - 1)] = resolveShaderResource(i - 1, resources[i])
|
||||
end
|
||||
end
|
||||
|
||||
local tk, tkey = bufferKind(target)
|
||||
local targetKind, targetW, targetH, targetData
|
||||
if tk == "o" then
|
||||
ensurePixels()
|
||||
flushPixelData()
|
||||
targetKind, targetW, targetH = 1, width, height
|
||||
elseif tk == "t" or tk == "c" then
|
||||
local b = buffers[tkey]
|
||||
if not b then
|
||||
b = { data = ffi.new("uint8_t[?]", width * height * 4), w = width, h = height }
|
||||
buffers[tkey] = b
|
||||
end
|
||||
targetKind, targetW, targetH, targetData = 0, b.w, b.h, b.data
|
||||
elseif tk == "f" then
|
||||
local data, w, h = ensureFrameBuffer()
|
||||
targetKind, targetW, targetH, targetData = 0, w, h, data
|
||||
else
|
||||
return
|
||||
end
|
||||
|
||||
if targetData then
|
||||
if targetW * targetH * 4 > MAX_PIXEL_BUFFER then
|
||||
error("obj.pixelshader: target is too large for the native engine.", 2)
|
||||
end
|
||||
ffi.copy(shaderImage, targetData, targetW * targetH * 4)
|
||||
end
|
||||
|
||||
shaderMeta[0] = resourceCount
|
||||
shaderMeta[1] = blendMode
|
||||
shaderMeta[2] = compositeBlend
|
||||
shaderMeta[3] = samplerMode
|
||||
shaderMeta[4] = constantCount
|
||||
shaderMeta[5] = targetW
|
||||
shaderMeta[6] = targetH
|
||||
shaderMeta[7] = targetKind
|
||||
|
||||
local len = #name
|
||||
if len > CB_TAG_MAX then len = CB_TAG_MAX end
|
||||
ffi.copy(base + CB_TAG_OFFSET, name, len)
|
||||
i32[OFF_CB_TAGLEN] = len
|
||||
i32[OFF_CB_KIND] = CB_KIND_PIXELSHADER_RUN
|
||||
i32[OFF_STATUS] = STATUS_CALLBACK
|
||||
k32.SetEvent(doneEvent)
|
||||
k32.WaitForSingleObject(workEvent, INFINITE)
|
||||
|
||||
local status = shaderMeta[8]
|
||||
if status == 2 then
|
||||
error(ffi.string(base + CB_TAG_OFFSET, i32[OFF_CB_TAGLEN]), 2)
|
||||
end
|
||||
if status ~= 0 then return end
|
||||
|
||||
if tk == "o" then
|
||||
dirty = true
|
||||
pixelsValid = true
|
||||
pdValid = false
|
||||
pdDirty = false
|
||||
return
|
||||
end
|
||||
|
||||
ffi.copy(targetData, shaderImage, targetW * targetH * 4)
|
||||
if tk == "f" then
|
||||
local need = targetW * targetH * 4
|
||||
if need <= pixelCapacity then
|
||||
ffi.copy(pixels, targetData, need)
|
||||
width = targetW; height = targetH
|
||||
i32[OFF_WIDTH] = targetW; i32[OFF_HEIGHT] = targetH
|
||||
dirty = true
|
||||
pixelsValid = true
|
||||
pdValid = false
|
||||
pdDirty = false
|
||||
obj.w = targetW; obj.h = targetH
|
||||
obj.hw = targetW / 2; obj.hh = targetH / 2
|
||||
obj.cx = targetW / 2; obj.cy = targetH / 2
|
||||
obj.cz = 0
|
||||
obj.diagonal = math.sqrt(targetW * targetW + targetH * targetH)
|
||||
end
|
||||
end
|
||||
end
|
||||
|
||||
function obj.getobject(tag, frame)
|
||||
if type(tag) ~= "string" then return nil end
|
||||
if frame then frame = math.floor(frame) else frame = math.floor(obj.timelineframe or 0) end
|
||||
@@ -947,6 +1156,7 @@ while true do
|
||||
pixelsValid = false
|
||||
pdValid = false
|
||||
pdDirty = false
|
||||
frameBufferValid = false
|
||||
ringD[0] = 0
|
||||
local version = i32[OFF_SCRIPT_VERSION]
|
||||
if version ~= lastScriptVersion then
|
||||
|
||||
新しいイシューから参照
ユーザーをブロックする