From c657892b7b7c876351c1ffc6d7b3e595788b1de5 Mon Sep 17 00:00:00 2001 From: routersys Date: Mon, 29 Jun 2026 18:51:43 +0900 Subject: [PATCH] =?UTF-8?q?=E3=83=94=E3=82=AF=E3=82=BB=E3=83=AB=E5=86=99?= =?UTF-8?q?=E5=83=8F=E3=82=AB=E3=83=BC=E3=83=8D=E3=83=AB=E3=81=AEIR?= =?UTF-8?q?=E3=81=A8=E6=8A=BD=E5=87=BA=E5=99=A8=E3=82=92=E8=BF=BD=E5=8A=A0?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Co-Authored-By: Claude Opus 4.8 --- LuaScript.Tests/LuaScript.Tests.csproj | 3 + LuaScript/Engine/Kernel/KernelExtractor.cs | 357 +++++++++++++++++++++ LuaScript/Engine/Kernel/KernelModel.cs | 97 ++++++ LuaScript/Engine/Kernel/KernelUniform.cs | 147 +++++++++ 4 files changed, 604 insertions(+) create mode 100644 LuaScript/Engine/Kernel/KernelExtractor.cs create mode 100644 LuaScript/Engine/Kernel/KernelModel.cs create mode 100644 LuaScript/Engine/Kernel/KernelUniform.cs diff --git a/LuaScript.Tests/LuaScript.Tests.csproj b/LuaScript.Tests/LuaScript.Tests.csproj index b662af6..591a5fd 100644 --- a/LuaScript.Tests/LuaScript.Tests.csproj +++ b/LuaScript.Tests/LuaScript.Tests.csproj @@ -46,6 +46,9 @@ + + + \ No newline at end of file diff --git a/LuaScript/Engine/Kernel/KernelExtractor.cs b/LuaScript/Engine/Kernel/KernelExtractor.cs new file mode 100644 index 0000000..4f1abb9 --- /dev/null +++ b/LuaScript/Engine/Kernel/KernelExtractor.cs @@ -0,0 +1,357 @@ +using System; +using System.Collections.Generic; + +namespace LuaScript.Engine.Kernel +{ + internal sealed class KernelExtractor + { + private readonly record struct FuncSpec(KFunc Func, int MinArgs, int MaxArgs); + + private static readonly Dictionary MathFunctions = new(StringComparer.Ordinal) + { + ["abs"] = new(KFunc.Abs, 1, 1), + ["floor"] = new(KFunc.Floor, 1, 1), + ["ceil"] = new(KFunc.Ceil, 1, 1), + ["sqrt"] = new(KFunc.Sqrt, 1, 1), + ["sin"] = new(KFunc.Sin, 1, 1), + ["cos"] = new(KFunc.Cos, 1, 1), + ["tan"] = new(KFunc.Tan, 1, 1), + ["asin"] = new(KFunc.Asin, 1, 1), + ["acos"] = new(KFunc.Acos, 1, 1), + ["atan"] = new(KFunc.Atan, 1, 1), + ["atan2"] = new(KFunc.Atan2, 2, 2), + ["exp"] = new(KFunc.Exp, 1, 1), + ["log"] = new(KFunc.Log, 1, 1), + ["pow"] = new(KFunc.Pow, 2, 2), + ["fmod"] = new(KFunc.Fmod, 2, 2), + ["min"] = new(KFunc.Min, 2, int.MaxValue), + ["max"] = new(KFunc.Max, 2, int.MaxValue), + }; + + private readonly List _bindings = []; + private readonly Dictionary _scope = new(StringComparer.Ordinal); + private readonly SortedSet _uniforms = []; + + private string _widthVariable = string.Empty; + private string _heightVariable = string.Empty; + private bool _coordsEnabled; + + public static KernelProgram? TryExtract(string runnableScript) + { + try + { + return new KernelExtractor().Extract(runnableScript); + } + catch (KernelUnsupportedException) + { + return null; + } + } + + private KernelProgram? Extract(string runnableScript) + { + var block = LuaParser.Parse(runnableScript); + + int index = 0; + while (index < block.Count && block[index] is LocalStmt prelude) + { + BindLocal(prelude); + index++; + } + + if (index >= block.Count || block[index] is not NumericForStmt outer) + return null; + if (index + 1 != block.Count) + return null; + + if (!TryAxis(outer, out string outerVar, out KAxis outerAxis)) + return null; + if (outer.Body.Count != 1 || outer.Body[0] is not NumericForStmt inner) + return null; + if (!TryAxis(inner, out string innerVar, out KAxis innerAxis)) + return null; + if (outerAxis == innerAxis) + return null; + + _widthVariable = outerAxis == KAxis.X ? outerVar : innerVar; + _heightVariable = outerAxis == KAxis.Y ? outerVar : innerVar; + + return BuildKernel(inner.Body); + } + + private KernelProgram? BuildKernel(IReadOnlyList body) + { + if (body.Count < 2) + return null; + + if (body[0] is not LocalStmt sample || sample.Values.Count != 1 || + !IsGetPixel(sample.Values[0])) + return null; + if (sample.Names.Count is < 1 or > 4) + return null; + + _coordsEnabled = true; + for (int i = 0; i < sample.Names.Count; i++) + { + EnsureNotCoordinateName(sample.Names[i]); + _scope[sample.Names[i]] = AddBinding(new KInput((KChannel)i)); + } + + for (int i = 1; i < body.Count - 1; i++) + { + switch (body[i]) + { + case LocalStmt local: + BindLocal(local); + break; + case AssignStmt assign: + BindAssign(assign); + break; + default: + return null; + } + } + + if (body[^1] is not CallStmt { Call: var call } || !IsObjectMethod(call, "setpixel")) + return null; + if (call.Arguments.Count is < 5 or > 6) + return null; + if (!IsCoordinate(call.Arguments[0], KAxis.X) || !IsCoordinate(call.Arguments[1], KAxis.Y)) + return null; + + var outR = Lower(call.Arguments[2]); + var outG = Lower(call.Arguments[3]); + var outB = Lower(call.Arguments[4]); + var outA = call.Arguments.Count == 6 ? Lower(call.Arguments[5]) : new KConst(255d); + + return new KernelProgram(_bindings, outR, outG, outB, outA, [.. _uniforms]); + } + + private void BindLocal(LocalStmt local) + { + if (local.Values.Count == 1 && IsGetPixel(local.Values[0])) + throw new KernelUnsupportedException("Unexpected pixel sample."); + if (local.Names.Count != local.Values.Count) + throw new KernelUnsupportedException("Multiple-value assignment is not supported."); + + var lowered = new KExpr[local.Values.Count]; + for (int i = 0; i < local.Values.Count; i++) + lowered[i] = Lower(local.Values[i]); + for (int i = 0; i < local.Names.Count; i++) + { + EnsureNotCoordinateName(local.Names[i]); + _scope[local.Names[i]] = AddBinding(lowered[i]); + } + } + + private void BindAssign(AssignStmt assign) + { + if (assign.Targets.Count != assign.Values.Count) + throw new KernelUnsupportedException("Unbalanced assignment is not supported."); + + foreach (var target in assign.Targets) + { + if (target is not NameExpr name || !_scope.ContainsKey(name.Name)) + throw new KernelUnsupportedException("Assignment target must be a local variable."); + } + + var lowered = new KExpr[assign.Values.Count]; + for (int i = 0; i < assign.Values.Count; i++) + lowered[i] = Lower(assign.Values[i]); + for (int i = 0; i < assign.Targets.Count; i++) + _scope[((NameExpr)assign.Targets[i]).Name] = AddBinding(lowered[i]); + } + + private void EnsureNotCoordinateName(string name) + { + if (string.Equals(name, _widthVariable, StringComparison.Ordinal) || + string.Equals(name, _heightVariable, StringComparison.Ordinal)) + throw new KernelUnsupportedException("Local variable shadows a loop coordinate."); + } + + private int AddBinding(KExpr expression) + { + _bindings.Add(expression); + return _bindings.Count - 1; + } + + private KExpr Lower(LuaExpr expression) + { + switch (expression) + { + case NumberExpr number: + return new KConst(number.Value); + case NameExpr name: + return LowerName(name.Name); + case MemberExpr member: + return LowerMember(member); + case CallExpr call: + return LowerCall(call); + case UnaryExpr { Operator: "-" } unary: + return new KNegate(Lower(unary.Operand)); + case BinaryExpr binary: + return LowerBinary(binary); + } + throw new KernelUnsupportedException("Unsupported expression in pixel kernel."); + } + + private KExpr LowerName(string name) + { + if (_scope.TryGetValue(name, out int slot)) + return new KLocalRef(slot); + if (_coordsEnabled && string.Equals(name, _widthVariable, StringComparison.Ordinal)) + return new KCoord(KAxis.X); + if (_coordsEnabled && string.Equals(name, _heightVariable, StringComparison.Ordinal)) + return new KCoord(KAxis.Y); + if (KernelUniforms.TryResolveGlobal(name, out var uniform)) + return UseUniform(uniform); + throw new KernelUnsupportedException($"Unknown identifier '{name}'."); + } + + private KExpr LowerMember(MemberExpr member) + { + if (member.Target is NameExpr { Name: "math" }) + { + return member.Name switch + { + "pi" => new KConst(Math.PI), + "huge" => new KConst(double.PositiveInfinity), + _ => throw new KernelUnsupportedException($"Unsupported math field '{member.Name}'."), + }; + } + + if (member.Target is NameExpr target && KernelUniforms.TryResolveMember(target.Name, member.Name, out var uniform)) + return UseUniform(uniform); + + throw new KernelUnsupportedException("Unsupported member access in pixel kernel."); + } + + private KExpr LowerCall(CallExpr call) + { + if (call.Target is not MemberExpr { Target: NameExpr { Name: "math" }, Name: var function } || + !MathFunctions.TryGetValue(function, out var spec)) + throw new KernelUnsupportedException("Unsupported function call in pixel kernel."); + + int count = call.Arguments.Count; + if (count < spec.MinArgs || count > spec.MaxArgs) + throw new KernelUnsupportedException($"Wrong argument count for 'math.{function}'."); + + var arguments = new KExpr[count]; + for (int i = 0; i < count; i++) + arguments[i] = Lower(call.Arguments[i]); + + if (spec.Func is KFunc.Min or KFunc.Max) + { + var folded = arguments[0]; + for (int i = 1; i < count; i++) + folded = new KCall(spec.Func, [folded, arguments[i]]); + return folded; + } + + return new KCall(spec.Func, arguments); + } + + private KExpr LowerBinary(BinaryExpr binary) + { + switch (binary.Operator) + { + case "+": return new KArith(KArithOp.Add, Lower(binary.Left), Lower(binary.Right)); + case "-": return new KArith(KArithOp.Subtract, Lower(binary.Left), Lower(binary.Right)); + case "*": return new KArith(KArithOp.Multiply, Lower(binary.Left), Lower(binary.Right)); + case "/": return new KArith(KArithOp.Divide, Lower(binary.Left), Lower(binary.Right)); + case "%": return new KArith(KArithOp.Modulo, Lower(binary.Left), Lower(binary.Right)); + case "^": return new KArith(KArithOp.Power, Lower(binary.Left), Lower(binary.Right)); + case "or" when binary.Left is BinaryExpr { Operator: "and" } conditional: + return new KSelect(LowerBool(conditional.Left), Lower(conditional.Right), Lower(binary.Right)); + } + throw new KernelUnsupportedException($"Unsupported operator '{binary.Operator}' in value position."); + } + + private KBool LowerBool(LuaExpr expression) + { + switch (expression) + { + case BoolExpr boolean: + return new KBoolConst(boolean.Value); + case UnaryExpr { Operator: "not" } unary: + return new KNot(LowerBool(unary.Operand)); + case BinaryExpr { Operator: "and" } conjunction: + return new KLogical(true, LowerBool(conjunction.Left), LowerBool(conjunction.Right)); + case BinaryExpr { Operator: "or" } disjunction: + return new KLogical(false, LowerBool(disjunction.Left), LowerBool(disjunction.Right)); + case BinaryExpr binary when TryCompareOp(binary.Operator, out var op): + return new KCompare(op, Lower(binary.Left), Lower(binary.Right)); + case NameExpr name when IsCheck(LowerName(name.Name)): + return new KCompare(KCompareOp.NotEqual, LowerName(name.Name), new KConst(0d)); + case MemberExpr member when IsCheck(LowerMember(member)): + return new KCompare(KCompareOp.NotEqual, LowerMember(member), new KConst(0d)); + } + throw new KernelUnsupportedException("Unsupported condition in pixel kernel."); + } + + private static bool IsCheck(KExpr expression) => + expression is KUniformRef { Uniform: KernelUniform.Check0 or KernelUniform.Check1 or KernelUniform.Check2 or KernelUniform.Check3 }; + + private static bool TryCompareOp(string symbol, out KCompareOp op) + { + switch (symbol) + { + case "<": op = KCompareOp.Less; return true; + case ">": op = KCompareOp.Greater; return true; + case "<=": op = KCompareOp.LessEqual; return true; + case ">=": op = KCompareOp.GreaterEqual; return true; + case "==": op = KCompareOp.Equal; return true; + case "~=": op = KCompareOp.NotEqual; return true; + default: op = default; return false; + } + } + + private KExpr UseUniform(KernelUniform uniform) + { + _uniforms.Add(uniform); + return new KUniformRef(uniform); + } + + private bool TryAxis(NumericForStmt loop, out string variable, out KAxis axis) + { + variable = loop.Variable; + axis = default; + + if (loop.Start is not NumberExpr { Value: 0d }) + return false; + if (loop.Step is not null && loop.Step is not NumberExpr { Value: 1d }) + return false; + if (loop.Stop is not BinaryExpr { Operator: "-", Right: NumberExpr { Value: 1d } } bound) + return false; + if (bound.Left is not MemberExpr { Target: NameExpr { Name: "obj" }, Name: var field }) + return false; + if (!KernelUniforms.TryResolveMember("obj", field, out var uniform)) + return false; + + if (uniform == KernelUniform.Width) + { + axis = KAxis.X; + return true; + } + if (uniform == KernelUniform.Height) + { + axis = KAxis.Y; + return true; + } + return false; + } + + private bool IsGetPixel(LuaExpr expression) => + expression is CallExpr call && IsObjectMethod(call, "getpixel") && + call.Arguments.Count == 2 && + IsCoordinate(call.Arguments[0], KAxis.X) && IsCoordinate(call.Arguments[1], KAxis.Y); + + private bool IsCoordinate(LuaExpr expression, KAxis axis) => + expression is NameExpr name && + string.Equals(name.Name, axis == KAxis.X ? _widthVariable : _heightVariable, StringComparison.Ordinal); + + private static bool IsObjectMethod(CallExpr call, string method) => + call.Target is MemberExpr { Target: NameExpr { Name: "obj" }, Name: var name } && + string.Equals(name, method, StringComparison.Ordinal); + } +} diff --git a/LuaScript/Engine/Kernel/KernelModel.cs b/LuaScript/Engine/Kernel/KernelModel.cs new file mode 100644 index 0000000..6c690c9 --- /dev/null +++ b/LuaScript/Engine/Kernel/KernelModel.cs @@ -0,0 +1,97 @@ +using System.Collections.Generic; + +namespace LuaScript.Engine.Kernel +{ + internal enum KChannel + { + R, + G, + B, + A, + } + + internal enum KAxis + { + X, + Y, + } + + internal enum KArithOp + { + Add, + Subtract, + Multiply, + Divide, + Modulo, + Power, + } + + internal enum KCompareOp + { + Less, + Greater, + LessEqual, + GreaterEqual, + Equal, + NotEqual, + } + + internal enum KFunc + { + Abs, + Floor, + Ceil, + Sqrt, + Sin, + Cos, + Tan, + Asin, + Acos, + Atan, + Atan2, + Exp, + Log, + Pow, + Min, + Max, + Fmod, + } + + internal abstract record KExpr; + + internal sealed record KConst(double Value) : KExpr; + + internal sealed record KInput(KChannel Channel) : KExpr; + + internal sealed record KCoord(KAxis Axis) : KExpr; + + internal sealed record KUniformRef(KernelUniform Uniform) : KExpr; + + internal sealed record KLocalRef(int Slot) : KExpr; + + internal sealed record KArith(KArithOp Op, KExpr Left, KExpr Right) : KExpr; + + internal sealed record KNegate(KExpr Operand) : KExpr; + + internal sealed record KCall(KFunc Func, IReadOnlyList Arguments) : KExpr; + + internal sealed record KSelect(KBool Condition, KExpr WhenTrue, KExpr WhenFalse) : KExpr; + + internal abstract record KBool; + + internal sealed record KCompare(KCompareOp Op, KExpr Left, KExpr Right) : KBool; + + internal sealed record KLogical(bool IsAnd, KBool Left, KBool Right) : KBool; + + internal sealed record KNot(KBool Operand) : KBool; + + internal sealed record KBoolConst(bool Value) : KBool; + + internal sealed record KernelProgram( + IReadOnlyList Bindings, + KExpr OutputR, + KExpr OutputG, + KExpr OutputB, + KExpr OutputA, + IReadOnlyList Uniforms); +} diff --git a/LuaScript/Engine/Kernel/KernelUniform.cs b/LuaScript/Engine/Kernel/KernelUniform.cs new file mode 100644 index 0000000..e0dac8c --- /dev/null +++ b/LuaScript/Engine/Kernel/KernelUniform.cs @@ -0,0 +1,147 @@ +using System; +using System.Collections.Generic; + +namespace LuaScript.Engine.Kernel +{ + internal enum KernelUniform + { + Width, + Height, + HalfWidth, + HalfHeight, + CenterX, + CenterY, + CenterZ, + Diagonal, + X, + Y, + Z, + Ox, + Oy, + Oz, + Sx, + Sy, + Sz, + Zoom, + Aspect, + Alpha, + Rx, + Ry, + Rz, + Rxr, + Ryr, + Rzr, + Track0, + Track1, + Track2, + Track3, + Check0, + Check1, + Check2, + Check3, + Color, + Time, + Frame, + TotalFrame, + TotalTime, + T, + Framerate, + Layer, + Index, + Num, + SceneWidth, + SceneHeight, + SceneCenterX, + SceneCenterY, + TimelineFrame, + TimelineTime, + } + + internal static class KernelUniforms + { + public static int Count { get; } = Enum.GetValues().Length; + + private static readonly Dictionary Globals = new(StringComparer.Ordinal) + { + ["time"] = KernelUniform.Time, + ["frame"] = KernelUniform.Frame, + ["totalframe"] = KernelUniform.TotalFrame, + ["framerate"] = KernelUniform.Framerate, + ["timelineframe"] = KernelUniform.TimelineFrame, + ["timelinetime"] = KernelUniform.TimelineTime, + ["layer"] = KernelUniform.Layer, + ["color"] = KernelUniform.Color, + }; + + private static readonly Dictionary ObjectFields = new(StringComparer.Ordinal) + { + ["w"] = KernelUniform.Width, + ["h"] = KernelUniform.Height, + ["hw"] = KernelUniform.HalfWidth, + ["hh"] = KernelUniform.HalfHeight, + ["cx"] = KernelUniform.CenterX, + ["cy"] = KernelUniform.CenterY, + ["cz"] = KernelUniform.CenterZ, + ["diagonal"] = KernelUniform.Diagonal, + ["x"] = KernelUniform.X, + ["y"] = KernelUniform.Y, + ["z"] = KernelUniform.Z, + ["ox"] = KernelUniform.Ox, + ["oy"] = KernelUniform.Oy, + ["oz"] = KernelUniform.Oz, + ["sx"] = KernelUniform.Sx, + ["sy"] = KernelUniform.Sy, + ["sz"] = KernelUniform.Sz, + ["zoom"] = KernelUniform.Zoom, + ["aspect"] = KernelUniform.Aspect, + ["alpha"] = KernelUniform.Alpha, + ["rx"] = KernelUniform.Rx, + ["ry"] = KernelUniform.Ry, + ["rz"] = KernelUniform.Rz, + ["rxr"] = KernelUniform.Rxr, + ["ryr"] = KernelUniform.Ryr, + ["rzr"] = KernelUniform.Rzr, + ["track0"] = KernelUniform.Track0, + ["track1"] = KernelUniform.Track1, + ["track2"] = KernelUniform.Track2, + ["track3"] = KernelUniform.Track3, + ["check0"] = KernelUniform.Check0, + ["check1"] = KernelUniform.Check1, + ["check2"] = KernelUniform.Check2, + ["check3"] = KernelUniform.Check3, + ["time"] = KernelUniform.Time, + ["frame"] = KernelUniform.Frame, + ["totalframe"] = KernelUniform.TotalFrame, + ["totaltime"] = KernelUniform.TotalTime, + ["t"] = KernelUniform.T, + ["framerate"] = KernelUniform.Framerate, + ["layer"] = KernelUniform.Layer, + ["index"] = KernelUniform.Index, + ["num"] = KernelUniform.Num, + }; + + private static readonly Dictionary SceneFields = new(StringComparer.Ordinal) + { + ["width"] = KernelUniform.SceneWidth, + ["height"] = KernelUniform.SceneHeight, + ["cx"] = KernelUniform.SceneCenterX, + ["cy"] = KernelUniform.SceneCenterY, + }; + + public static bool TryResolveGlobal(string name, out KernelUniform uniform) => + Globals.TryGetValue(name, out uniform); + + public static bool TryResolveMember(string target, string field, out KernelUniform uniform) + { + uniform = default; + return target switch + { + "obj" => ObjectFields.TryGetValue(field, out uniform), + "scene" => SceneFields.TryGetValue(field, out uniform), + _ => false, + }; + } + + public static string Field(KernelUniform uniform) => "u_" + uniform; + } +}