diff --git a/LuaScript.Tests/KernelCpuEquivalenceTests.cs b/LuaScript.Tests/KernelCpuEquivalenceTests.cs index 96259cd..120e652 100644 --- a/LuaScript.Tests/KernelCpuEquivalenceTests.cs +++ b/LuaScript.Tests/KernelCpuEquivalenceTests.cs @@ -38,6 +38,27 @@ namespace LuaScript.Tests AssertEquivalent(script, fields, globals); } + [Theory] + [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")] + [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 g=pd:get(i+2) local b=pd:get(i+3) local l=0.298912*r+0.586611*g+0.114478*b pd:set(i+1,l) pd:set(i+2,l) pd:set(i+3,l) 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,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")] + public void GetPixelDataKernelMatchesMoonSharp(string script) + { + var fields = new Dictionary { ["w"] = Width, ["h"] = Height, ["track0"] = 73d }; + AssertEquivalent(script, fields, new Dictionary()); + } + + [Theory] + [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+4,128) 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,pd:get(i+5)) 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+1)*pd.width+x)*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 pd:set(i+1,pd:get(i+3)) pd:set(i+2,pd:get(i+2)) pd:set(i+3,pd:get(i+1)) end end")] + public void GetPixelDataNonKernelScriptsAreRejected(string script) + { + Assert.Null(KernelExtractor.TryExtract(script)); + } + [Theory] [InlineData("--!cpu\nfor y=0,obj.h-1 do for x=0,obj.w-1 do local r,g,b,a=obj.getpixel(x,y) obj.setpixel(x,y,255-r,255-g,255-b,a) end end")] [InlineData("--!gpu\nfor y=0,obj.h-1 do for x=0,obj.w-1 do local r,g,b,a=obj.getpixel(x,y) local l=0.298912*r+0.586611*g+0.114478*b obj.setpixel(x,y,l,l,l,a) end end")] @@ -134,10 +155,60 @@ namespace LuaScript.Tests return DynValue.Void; }); + obj["getpixeldata"] = DynValue.NewCallback((_, _) => + { + var pd = new Table(engine); + pd["width"] = Width; + pd["height"] = Height; + pd["get"] = DynValue.NewCallback((_, a) => + DynValue.NewNumber(PixelDataGet(buffer, (int)(a[1].CastToNumber() ?? 0d)))); + pd["set"] = DynValue.NewCallback((_, a) => + { + PixelDataSet(buffer, (int)(a[1].CastToNumber() ?? 0d), a[2].CastToNumber() ?? 0d); + return DynValue.Void; + }); + return DynValue.NewTable(pd); + }); + engine.Globals["obj"] = obj; engine.DoString(script); } + private static double PixelDataGet(byte[] buffer, int index) + { + int zeroBased = index - 1; + if ((uint)zeroBased >= (uint)buffer.Length) + return 0d; + int pixel = Math.DivRem(zeroBased, 4, out int channel); + int p = pixel * 4; + double a = buffer[p + 3]; + if (channel == 3) + return a; + if (a <= 0d) + return 0d; + double scale = 255d / a; + return channel switch + { + 0 => Math.Clamp(buffer[p + 2] * scale, 0d, 255d), + 1 => Math.Clamp(buffer[p + 1] * scale, 0d, 255d), + _ => Math.Clamp(buffer[p] * scale, 0d, 255d), + }; + } + + private static void PixelDataSet(byte[] buffer, int index, double value) + { + int zeroBased = index - 1; + if ((uint)zeroBased >= (uint)buffer.Length) + return; + int pixel = Math.DivRem(zeroBased, 4, out int channel); + int p = pixel * 4; + double clamped = Math.Clamp(value, 0d, 255d); + double a = buffer[p + 3]; + double premultiplied = clamped * (a / 255d); + int byteOffset = channel switch { 0 => 2, 1 => 1, _ => 0 }; + buffer[p + byteOffset] = (byte)Math.Clamp(premultiplied, 0d, 255d); + } + private static (double r, double g, double b, double a) GetPixel(byte[] buffer, int x, int y) { if ((uint)x >= Width || (uint)y >= Height) diff --git a/LuaScript/Engine/Kernel/KernelExtractor.cs b/LuaScript/Engine/Kernel/KernelExtractor.cs index 4f1abb9..54c2030 100644 --- a/LuaScript/Engine/Kernel/KernelExtractor.cs +++ b/LuaScript/Engine/Kernel/KernelExtractor.cs @@ -35,6 +35,9 @@ namespace LuaScript.Engine.Kernel private string _widthVariable = string.Empty; private string _heightVariable = string.Empty; private bool _coordsEnabled; + private string? _pixelDataVariable; + private string _baseIndexVariable = string.Empty; + private readonly bool[] _writtenChannels = new bool[4]; public static KernelProgram? TryExtract(string runnableScript) { @@ -55,6 +58,11 @@ namespace LuaScript.Engine.Kernel int index = 0; while (index < block.Count && block[index] is LocalStmt prelude) { + if (TryBindPixelData(prelude)) + { + index++; + continue; + } BindLocal(prelude); index++; } @@ -76,7 +84,116 @@ namespace LuaScript.Engine.Kernel _widthVariable = outerAxis == KAxis.X ? outerVar : innerVar; _heightVariable = outerAxis == KAxis.Y ? outerVar : innerVar; - return BuildKernel(inner.Body); + return _pixelDataVariable is null ? BuildKernel(inner.Body) : BuildPixelDataKernel(inner.Body); + } + + private bool TryBindPixelData(LocalStmt local) + { + if (local.Names.Count != 1 || local.Values.Count != 1 || + local.Values[0] is not CallExpr { Target: MemberExpr { Target: NameExpr { Name: "obj" }, Name: "getpixeldata" }, Arguments.Count: 0 }) + return false; + if (_pixelDataVariable is not null) + throw new KernelUnsupportedException("Multiple pixel-data handles are not supported."); + _pixelDataVariable = local.Names[0]; + return true; + } + + private KernelProgram? BuildPixelDataKernel(IReadOnlyList body) + { + if (body.Count < 5) + return null; + if (body[0] is not LocalStmt { Names.Count: 1, Values.Count: 1 } baseStmt || !IsBaseIndex(baseStmt.Values[0])) + return null; + + _baseIndexVariable = baseStmt.Names[0]; + EnsureNotCoordinateName(_baseIndexVariable); + _coordsEnabled = true; + + KExpr? outR = null, outG = null, outB = null; + for (int i = 1; i < body.Count; i++) + { + switch (body[i]) + { + case LocalStmt local: + BindLocal(local); + break; + case AssignStmt assign: + BindAssign(assign); + break; + case CallStmt { Call: MethodCallExpr set } when IsPixelDataSet(set, out int writeChannel): + var value = Lower(set.Arguments[1]); + if (writeChannel == 0) outR = value; + else if (writeChannel == 1) outG = value; + else outB = value; + _writtenChannels[writeChannel] = true; + break; + default: + return null; + } + } + + if (outR is null || outG is null || outB is null) + return null; + + return new KernelProgram(_bindings, outR, outG, outB, new KInput(KChannel.A), [.. _uniforms]); + } + + private bool IsBaseIndex(LuaExpr expression) + { + if (expression is not BinaryExpr { Operator: "*", Right: NumberExpr { Value: 4d } } scaled || + scaled.Left is not BinaryExpr { Operator: "+" } sum) + return false; + if (!IsCoordinate(sum.Right, KAxis.X)) + return false; + if (sum.Left is not BinaryExpr { Operator: "*" } stride) + return false; + return IsCoordinate(stride.Left, KAxis.Y) && IsWidth(stride.Right); + } + + private bool IsWidth(LuaExpr expression) + { + if (expression is MemberExpr { Target: NameExpr { Name: "obj" }, Name: var field } && + KernelUniforms.TryResolveMember("obj", field, out var uniform)) + return uniform == KernelUniform.Width; + return _pixelDataVariable is not null && + expression is MemberExpr { Target: NameExpr { } target, Name: "width" } && + string.Equals(target.Name, _pixelDataVariable, StringComparison.Ordinal); + } + + private bool TryPixelDataChannel(LuaExpr expression, out int channel) + { + channel = 0; + if (expression is not MethodCallExpr { Method: "get", Arguments.Count: 1 } call || + call.Target is not NameExpr { } handle || + !string.Equals(handle.Name, _pixelDataVariable, StringComparison.Ordinal)) + return false; + if (!TryChannelOffset(call.Arguments[0], 1, 4, out channel)) + return false; + channel--; + return !_writtenChannels[channel]; + } + + private bool IsPixelDataSet(MethodCallExpr call, out int channel) + { + channel = 0; + if (call.Method != "set" || call.Arguments.Count != 2 || + call.Target is not NameExpr { } handle || + !string.Equals(handle.Name, _pixelDataVariable, StringComparison.Ordinal)) + return false; + if (!TryChannelOffset(call.Arguments[0], 1, 3, out channel)) + return false; + channel--; + return true; + } + + private bool TryChannelOffset(LuaExpr expression, int min, int max, out int offset) + { + offset = 0; + if (expression is not BinaryExpr { Operator: "+", Left: NameExpr baseName, Right: NumberExpr number } || + !string.Equals(baseName.Name, _baseIndexVariable, StringComparison.Ordinal)) + return false; + offset = (int)number.Value; + return offset == number.Value && offset >= min && offset <= max; } private KernelProgram? BuildKernel(IReadOnlyList body) @@ -112,7 +229,7 @@ namespace LuaScript.Engine.Kernel } } - if (body[^1] is not CallStmt { Call: var call } || !IsObjectMethod(call, "setpixel")) + if (body[^1] is not CallStmt { Call: CallExpr call } || !IsObjectMethod(call, "setpixel")) return null; if (call.Arguments.Count is < 5 or > 6) return null; @@ -187,6 +304,8 @@ namespace LuaScript.Engine.Kernel return LowerMember(member); case CallExpr call: return LowerCall(call); + case MethodCallExpr method when TryPixelDataChannel(method, out int channel): + return new KInput((KChannel)channel); case UnaryExpr { Operator: "-" } unary: return new KNegate(Lower(unary.Operand)); case BinaryExpr binary: @@ -323,20 +442,36 @@ namespace LuaScript.Engine.Kernel return false; if (loop.Stop is not BinaryExpr { Operator: "-", Right: NumberExpr { Value: 1d } } bound) return false; - if (bound.Left is not MemberExpr { Target: NameExpr { Name: "obj" }, Name: var field }) - return false; - if (!KernelUniforms.TryResolveMember("obj", field, out var uniform)) - return false; - - if (uniform == KernelUniform.Width) + if (bound.Left is MemberExpr { Target: NameExpr { Name: "obj" }, Name: var field } && + KernelUniforms.TryResolveMember("obj", field, out var uniform)) { - axis = KAxis.X; - return true; + if (uniform == KernelUniform.Width) + { + axis = KAxis.X; + return true; + } + if (uniform == KernelUniform.Height) + { + axis = KAxis.Y; + return true; + } + return false; } - if (uniform == KernelUniform.Height) + + if (_pixelDataVariable is not null && + bound.Left is MemberExpr { Target: NameExpr { } handle, Name: var pixelField } && + string.Equals(handle.Name, _pixelDataVariable, StringComparison.Ordinal)) { - axis = KAxis.Y; - return true; + if (pixelField == "width") + { + axis = KAxis.X; + return true; + } + if (pixelField == "height") + { + axis = KAxis.Y; + return true; + } } return false; } diff --git a/LuaScript/Engine/Kernel/LuaAst.cs b/LuaScript/Engine/Kernel/LuaAst.cs index f425bb8..ab18075 100644 --- a/LuaScript/Engine/Kernel/LuaAst.cs +++ b/LuaScript/Engine/Kernel/LuaAst.cs @@ -20,6 +20,8 @@ namespace LuaScript.Engine.Kernel internal sealed record CallExpr(LuaExpr Target, IReadOnlyList Arguments) : LuaExpr; + internal sealed record MethodCallExpr(LuaExpr Target, string Method, IReadOnlyList Arguments) : LuaExpr; + internal sealed record UnaryExpr(string Operator, LuaExpr Operand) : LuaExpr; internal sealed record BinaryExpr(string Operator, LuaExpr Left, LuaExpr Right) : LuaExpr; @@ -30,7 +32,7 @@ namespace LuaScript.Engine.Kernel internal sealed record AssignStmt(IReadOnlyList Targets, IReadOnlyList Values) : LuaStmt; - internal sealed record CallStmt(CallExpr Call) : LuaStmt; + internal sealed record CallStmt(LuaExpr Call) : LuaStmt; internal sealed record IfClause(LuaExpr Condition, IReadOnlyList Body); diff --git a/LuaScript/Engine/Kernel/LuaParser.cs b/LuaScript/Engine/Kernel/LuaParser.cs index e0e21c8..ce3474f 100644 --- a/LuaScript/Engine/Kernel/LuaParser.cs +++ b/LuaScript/Engine/Kernel/LuaParser.cs @@ -149,8 +149,8 @@ namespace LuaScript.Engine.Kernel return new AssignStmt(targets, values); } - if (first is CallExpr call) - return new CallStmt(call); + if (first is CallExpr or MethodCallExpr) + return new CallStmt(first); throw new KernelUnsupportedException("Expression is not a valid statement."); } @@ -275,6 +275,12 @@ namespace LuaScript.Engine.Kernel { expression = new CallExpr(expression, ParseArguments()); } + else if (t.IsSymbol(":")) + { + Advance(); + string method = ExpectName(); + expression = new MethodCallExpr(expression, method, ParseArguments()); + } else { break; diff --git a/LuaScript/PixelDataProxy.cs b/LuaScript/PixelDataProxy.cs index 940a8aa..fec5a3a 100644 --- a/LuaScript/PixelDataProxy.cs +++ b/LuaScript/PixelDataProxy.cs @@ -24,13 +24,17 @@ namespace LuaScript { byte* pixel = p + pixelIndex * 4; double a = pixel[3]; + if (channel == 3) + return a; + if (a <= 0d) + return 0d; + double scale = 255d / a; return channel switch { - 0 => a > 0d ? Math.Clamp(pixel[2] * 255d / a, 0d, 255d) : 0d, - 1 => a > 0d ? Math.Clamp(pixel[1] * 255d / a, 0d, 255d) : 0d, - 2 => a > 0d ? Math.Clamp(pixel[0] * 255d / a, 0d, 255d) : 0d, - 3 => a, + 0 => Math.Clamp(pixel[2] * scale, 0d, 255d), + 1 => Math.Clamp(pixel[1] * scale, 0d, 255d), + 2 => Math.Clamp(pixel[0] * scale, 0d, 255d), _ => throw new UnreachableException() }; }