diff --git a/LuaScript/AnimTableRegistrar.cs b/LuaScript/AnimTableRegistrar.cs new file mode 100644 index 0000000..c7fa9e5 --- /dev/null +++ b/LuaScript/AnimTableRegistrar.cs @@ -0,0 +1,419 @@ +using MoonSharp.Interpreter; + +namespace LuaScript +{ + internal static class AnimTableRegistrar + { + private static readonly double s_tau = Math.PI * 2d; + private static readonly double s_e = Math.E; + private static readonly double s_phi = (1d + Math.Sqrt(5d)) / 2d; + private static readonly double s_sqrt2 = Math.Sqrt(2d); + + internal static void RegisterFunctions(Table anim) + { + anim["tau"] = s_tau; + anim["e"] = s_e; + anim["phi"] = s_phi; + anim["sqrt2"] = s_sqrt2; + + anim["lerp"] = DynValue.NewCallback((_, args) => + { + double a = args[0].CastToNumber() ?? 0d; + double b = args[1].CastToNumber() ?? 0d; + double t = args[2].CastToNumber() ?? 0d; + return DynValue.NewNumber(a + (b - a) * t); + }); + + anim["smoothstep"] = DynValue.NewCallback((_, args) => + { + double edge0 = args[0].CastToNumber() ?? 0d; + double edge1 = args[1].CastToNumber() ?? 1d; + double x = args[2].CastToNumber() ?? 0d; + double span = edge1 - edge0; + double t = span == 0d ? 0d : Math.Clamp((x - edge0) / span, 0d, 1d); + return DynValue.NewNumber(t * t * (3d - 2d * t)); + }); + + anim["smootherstep"] = DynValue.NewCallback((_, args) => + { + double edge0 = args[0].CastToNumber() ?? 0d; + double edge1 = args[1].CastToNumber() ?? 1d; + double x = args[2].CastToNumber() ?? 0d; + double span = edge1 - edge0; + double t = span == 0d ? 0d : Math.Clamp((x - edge0) / span, 0d, 1d); + return DynValue.NewNumber(t * t * t * (t * (6d * t - 15d) + 10d)); + }); + + anim["clamp"] = DynValue.NewCallback((_, args) => + { + double v = args[0].CastToNumber() ?? 0d; + double lo = args[1].CastToNumber() ?? 0d; + double hi = args[2].CastToNumber() ?? 1d; + return DynValue.NewNumber(Math.Clamp(v, lo, hi)); + }); + + anim["map"] = DynValue.NewCallback((_, args) => + { + double v = args[0].CastToNumber() ?? 0d; + double a1 = args[1].CastToNumber() ?? 0d; + double b1 = args[2].CastToNumber() ?? 1d; + double a2 = args[3].CastToNumber() ?? 0d; + double b2 = args[4].CastToNumber() ?? 1d; + double range = b1 - a1; + if (range == 0d) return DynValue.NewNumber(a2); + return DynValue.NewNumber(a2 + (b2 - a2) * (v - a1) / range); + }); + + anim["norm"] = DynValue.NewCallback((_, args) => + { + double v = args[0].CastToNumber() ?? 0d; + double lo = args[1].CastToNumber() ?? 0d; + double hi = args[2].CastToNumber() ?? 1d; + double span = hi - lo; + if (span == 0d) return DynValue.NewNumber(0d); + return DynValue.NewNumber((v - lo) / span); + }); + + anim["wrap"] = DynValue.NewCallback((_, args) => + { + double v = args[0].CastToNumber() ?? 0d; + double lo = args[1].CastToNumber() ?? 0d; + double hi = args[2].CastToNumber() ?? 1d; + double range = hi - lo; + if (range <= 0d) return DynValue.NewNumber(lo); + double result = (v - lo) % range; + if (result < 0d) result += range; + return DynValue.NewNumber(lo + result); + }); + + anim["pingpong"] = DynValue.NewCallback((_, args) => + { + double t = args[0].CastToNumber() ?? 0d; + double length = args[1].CastToNumber() ?? 1d; + if (length <= 0d) return DynValue.NewNumber(0d); + double v = t % (2d * length); + if (v < 0d) v += 2d * length; + return DynValue.NewNumber(v > length ? 2d * length - v : v); + }); + + anim["sign"] = DynValue.NewCallback((_, args) => + { + double v = args[0].CastToNumber() ?? 0d; + return DynValue.NewNumber(Math.Sign(v)); + }); + + anim["oscillate"] = DynValue.NewCallback((_, args) => + { + double t = args[0].CastToNumber() ?? 0d; + double lo = args[1].CastToNumber() ?? 0d; + double hi = args[2].CastToNumber() ?? 1d; + double freq = args[3].CastToNumber() ?? 1d; + double wave = (Math.Sin(t * freq * s_tau) + 1d) / 2d; + return DynValue.NewNumber(lo + (hi - lo) * wave); + }); + + anim["triangle"] = DynValue.NewCallback((_, args) => + { + double t = args[0].CastToNumber() ?? 0d; + double freq = args[1].CastToNumber() ?? 1d; + double f = t * freq; + f -= Math.Floor(f); + return DynValue.NewNumber(1d - 2d * Math.Abs(f - 0.5d)); + }); + + anim["square"] = DynValue.NewCallback((_, args) => + { + double t = args[0].CastToNumber() ?? 0d; + double freq = args[1].CastToNumber() ?? 1d; + double f = t * freq; + f -= Math.Floor(f); + return DynValue.NewNumber(f >= 0.5d ? 1d : 0d); + }); + + anim["duration"] = DynValue.NewCallback((_, args) => + { + double t = args[0].CastToNumber() ?? 0d; + double dur = args[1].CastToNumber() ?? 1d; + if (dur <= 0d) return DynValue.NewNumber(1d); + return DynValue.NewNumber(Math.Clamp(t / dur, 0d, 1d)); + }); + + anim["delay"] = DynValue.NewCallback((_, args) => + { + double t = args[0].CastToNumber() ?? 0d; + double d = args[1].CastToNumber() ?? 0d; + return DynValue.NewNumber(Math.Max(0d, t - d)); + }); + + anim["ease_in"] = DynValue.NewCallback((_, args) => + { + double t = args[0].CastToNumber() ?? 0d; + return DynValue.NewNumber(t * t); + }); + + anim["ease_out"] = DynValue.NewCallback((_, args) => + { + double t = args[0].CastToNumber() ?? 0d; + double inv = 1d - t; + return DynValue.NewNumber(1d - inv * inv); + }); + + anim["ease_in_out"] = DynValue.NewCallback((_, args) => + { + double t = args[0].CastToNumber() ?? 0d; + if (t < 0.5d) + return DynValue.NewNumber(2d * t * t); + double inv = -2d * t + 2d; + return DynValue.NewNumber(1d - inv * inv / 2d); + }); + + anim["elastic"] = DynValue.NewCallback((_, args) => + { + double t = Math.Clamp(args[0].CastToNumber() ?? 0d, 0d, 1d); + if (t == 0d) return DynValue.NewNumber(0d); + if (t == 1d) return DynValue.NewNumber(1d); + return DynValue.NewNumber(Math.Pow(2d, -10d * t) * Math.Sin((t * 10d - 0.75d) * (s_tau / 3d)) + 1d); + }); + + anim["back"] = DynValue.NewCallback((_, args) => + { + const double c1 = 1.70158d; + const double c3 = c1 + 1d; + double t = args[0].CastToNumber() ?? 0d; + double inv = t - 1d; + return DynValue.NewNumber(1d + c3 * inv * inv * inv + c1 * inv * inv); + }); + + anim["step"] = DynValue.NewCallback((_, args) => + { + double edge = args[0].CastToNumber() ?? 0d; + double x = args[1].CastToNumber() ?? 0d; + return DynValue.NewNumber(x >= edge ? 1d : 0d); + }); + + anim["fract"] = DynValue.NewCallback((_, args) => + { + double v = args[0].CastToNumber() ?? 0d; + return DynValue.NewNumber(v - Math.Floor(v)); + }); + + anim["bounce"] = DynValue.NewCallback((_, args) => + { + const double n1 = 7.5625d; + const double d1 = 2.75d; + double t = Math.Clamp(args[0].CastToNumber() ?? 0d, 0d, 1d); + if (t < 1d / d1) + return DynValue.NewNumber(n1 * t * t); + if (t < 2d / d1) + { + t -= 1.5d / d1; + return DynValue.NewNumber(n1 * t * t + 0.75d); + } + if (t < 2.5d / d1) + { + t -= 2.25d / d1; + return DynValue.NewNumber(n1 * t * t + 0.9375d); + } + t -= 2.625d / d1; + return DynValue.NewNumber(n1 * t * t + 0.984375d); + }); + + anim["hsv_to_rgb"] = DynValue.NewCallback((_, args) => + { + double h = args[0].CastToNumber() ?? 0d; + double s = args[1].CastToNumber() ?? 0d; + double v = args[2].CastToNumber() ?? 0d; + double c = v * s; + double x = c * (1d - Math.Abs((h / 60d) % 2d - 1d)); + double m = v - c; + int sector = ((int)Math.Floor(h / 60d) % 6 + 6) % 6; + (double r, double g, double b) = sector switch + { + 0 => (c, x, 0d), + 1 => (x, c, 0d), + 2 => (0d, c, x), + 3 => (0d, x, c), + 4 => (x, 0d, c), + _ => (c, 0d, x), + }; + return DynValue.NewTuple( + DynValue.NewNumber((r + m) * 255d), + DynValue.NewNumber((g + m) * 255d), + DynValue.NewNumber((b + m) * 255d)); + }); + + anim["rgb_to_hsv"] = DynValue.NewCallback((_, args) => + { + double r = (args[0].CastToNumber() ?? 0d) / 255d; + double g = (args[1].CastToNumber() ?? 0d) / 255d; + double b = (args[2].CastToNumber() ?? 0d) / 255d; + double max = Math.Max(r, Math.Max(g, b)); + double min = Math.Min(r, Math.Min(g, b)); + double delta = max - min; + double h = 0d; + if (delta > 0d) + { + if (max == r) h = 60d * ((((g - b) / delta) % 6d + 6d) % 6d); + else if (max == g) h = 60d * ((b - r) / delta + 2d); + else h = 60d * ((r - g) / delta + 4d); + } + return DynValue.NewTuple( + DynValue.NewNumber(h), + DynValue.NewNumber(max > 0d ? delta / max : 0d), + DynValue.NewNumber(max)); + }); + + anim["len"] = DynValue.NewCallback((_, args) => + { + double x = args[0].CastToNumber() ?? 0d; + double y = args[1].CastToNumber() ?? 0d; + return DynValue.NewNumber(Math.Sqrt(x * x + y * y)); + }); + + anim["dist"] = DynValue.NewCallback((_, args) => + { + double x1 = args[0].CastToNumber() ?? 0d; + double y1 = args[1].CastToNumber() ?? 0d; + double x2 = args[2].CastToNumber() ?? 0d; + double y2 = args[3].CastToNumber() ?? 0d; + double dx = x2 - x1; + double dy = y2 - y1; + return DynValue.NewNumber(Math.Sqrt(dx * dx + dy * dy)); + }); + + anim["dot"] = DynValue.NewCallback((_, args) => + { + double x1 = args[0].CastToNumber() ?? 0d; + double y1 = args[1].CastToNumber() ?? 0d; + double x2 = args[2].CastToNumber() ?? 0d; + double y2 = args[3].CastToNumber() ?? 0d; + return DynValue.NewNumber(x1 * x2 + y1 * y2); + }); + + anim["normalize"] = DynValue.NewCallback((_, args) => + { + double x = args[0].CastToNumber() ?? 0d; + double y = args[1].CastToNumber() ?? 0d; + double magnitude = Math.Sqrt(x * x + y * y); + if (magnitude == 0d) + return DynValue.NewTuple(DynValue.NewNumber(0d), DynValue.NewNumber(0d)); + return DynValue.NewTuple( + DynValue.NewNumber(x / magnitude), + DynValue.NewNumber(y / magnitude)); + }); + + anim["polar"] = DynValue.NewCallback((_, args) => + { + double r = args[0].CastToNumber() ?? 0d; + double a = args[1].CastToNumber() ?? 0d; + double rad = a * Math.PI / 180d; + return DynValue.NewTuple( + DynValue.NewNumber(r * Math.Cos(rad)), + DynValue.NewNumber(r * Math.Sin(rad)) + ); + }); + + anim["rotate"] = DynValue.NewCallback((_, args) => + { + double x = args[0].CastToNumber() ?? 0d; + double y = args[1].CastToNumber() ?? 0d; + double a = args[2].CastToNumber() ?? 0d; + double rad = a * Math.PI / 180d; + double c = Math.Cos(rad); + double s = Math.Sin(rad); + return DynValue.NewTuple( + DynValue.NewNumber(x * c - y * s), + DynValue.NewNumber(x * s + y * c) + ); + }); + + anim["bezier"] = DynValue.NewCallback((_, args) => + { + double t = Math.Clamp(args[0].CastToNumber() ?? 0d, 0d, 1d); + double p0 = args[1].CastToNumber() ?? 0d; + double p1 = args[2].CastToNumber() ?? 0d; + double p2 = args[3].CastToNumber() ?? 1d; + double p3 = args[4].CastToNumber() ?? 1d; + + double inv = 1d - t; + double b0 = inv * inv * inv; + double b1 = 3d * inv * inv * t; + double b2 = 3d * inv * t * t; + double b3 = t * t * t; + + return DynValue.NewNumber(b0 * p0 + b1 * p1 + b2 * p2 + b3 * p3); + }); + + anim["rand"] = DynValue.NewCallback((_, args) => + { + if (args.Count == 0) return DynValue.NewNumber(0d); + double seed, min = 0d, max = 1d; + if (args.Count == 1) + { + seed = args[0].CastToNumber() ?? 0d; + } + else if (args.Count == 2) + { + max = args[0].CastToNumber() ?? 1d; + seed = args[1].CastToNumber() ?? 0d; + } + else + { + min = args[0].CastToNumber() ?? 0d; + max = args[1].CastToNumber() ?? 1d; + seed = args[2].CastToNumber() ?? 0d; + } + long bits = BitConverter.DoubleToInt64Bits(seed); + uint h = (uint)((bits ^ (bits >> 32)) * 374761393); + h = (h ^ (h >> 13)) * 1274126177; + double r = (double)(h ^ (h >> 16)) / 4294967295.0; + return DynValue.NewNumber(min + r * (max - min)); + }); + + anim["noise"] = DynValue.NewCallback((_, args) => + { + double x = args[0].CastToNumber() ?? 0d; + double y = args.Count > 1 ? args[1].CastToNumber() ?? 0d : 0d; + double z = args.Count > 2 ? args[2].CastToNumber() ?? 0d : 0d; + + int xi = (int)Math.Floor(x); + int yi = (int)Math.Floor(y); + int zi = (int)Math.Floor(z); + + double xf = x - xi; + double yf = y - yi; + double zf = z - zi; + + double u = xf * xf * (3d - 2d * xf); + double v = yf * yf * (3d - 2d * yf); + double w = zf * zf * (3d - 2d * zf); + + double c000 = GetNoiseHash(xi, yi, zi); + double c100 = GetNoiseHash(xi + 1, yi, zi); + double c010 = GetNoiseHash(xi, yi + 1, zi); + double c110 = GetNoiseHash(xi + 1, yi + 1, zi); + double c001 = GetNoiseHash(xi, yi, zi + 1); + double c101 = GetNoiseHash(xi + 1, yi, zi + 1); + double c011 = GetNoiseHash(xi, yi + 1, zi + 1); + double c111 = GetNoiseHash(xi + 1, yi + 1, zi + 1); + + double x00 = c000 + u * (c100 - c000); + double x10 = c010 + u * (c110 - c010); + double x01 = c001 + u * (c101 - c001); + double x11 = c011 + u * (c111 - c011); + + double y0 = x00 + v * (x10 - x00); + double y1 = x01 + v * (x11 - x01); + + return DynValue.NewNumber(y0 + w * (y1 - y0)); + }); + } + + private static double GetNoiseHash(int x, int y, int z) + { + uint n = (uint)(x * 374761393 + y * 668265263 + z * 1013904223); + n = (n ^ (n >> 13)) * 1274126177; + return (double)(n ^ (n >> 16)) / 4294967295.0; + } + } +} diff --git a/LuaScript/AviUtlScriptContext.cs b/LuaScript/AviUtlScriptContext.cs new file mode 100644 index 0000000..8e61fee --- /dev/null +++ b/LuaScript/AviUtlScriptContext.cs @@ -0,0 +1,125 @@ +namespace LuaScript +{ + internal sealed class AviUtlScriptContext + { + public bool IsPlaying { get; init; } + public bool IsPaused { get; init; } + public string SceneId { get; init; } = string.Empty; + + public int ImageWidth { get; init; } + public int ImageHeight { get; init; } + + public double X { get; set; } + public double Y { get; set; } + public double Z { get; set; } + public double Ox { get; set; } + public double Oy { get; set; } + public double Oz { get; set; } + public double Sx { get; set; } + public double Sy { get; set; } + public double Zoom { get; set; } + public double Aspect { get; set; } + public double Alpha { get; set; } + public double Rx { get; set; } + public double Ry { get; set; } + public double Rz { get; set; } + + public double Track0 { get; init; } + public double Track1 { get; init; } + public double Track2 { get; init; } + public double Track3 { get; init; } + + public double Time { get; init; } + public int Frame { get; init; } + public int TotalFrame { get; init; } + public double TotalTime { get; init; } + public int Framerate { get; init; } + public int TimelineFrame { get; init; } + public double TimelineTime { get; init; } + public int SceneWidth { get; init; } + public int SceneHeight { get; init; } + public int Layer { get; init; } + public int Index { get; init; } + public int Num { get; init; } + + public double RxRad => Rx * Math.PI / 180d; + public double RyRad => Ry * Math.PI / 180d; + public double RzRad => Rz * Math.PI / 180d; + + public int GroupIndex { get; init; } + public int GroupCount { get; init; } + public int TimelineTotalFrame { get; init; } + public double TimelineTotalTime { get; init; } + public bool IsSaving { get; init; } + public double TimeRatio { get; init; } + + private Func? _pixelLoader; + private byte[]? _pixelBuffer; + private bool _pixelBufferLoaded; + private bool _isPixelsDirty; + + public bool IsPixelsDirty => _isPixelsDirty; + + internal int TotalChannels => ImageWidth * ImageHeight * 4; + + internal void SetPixelLoader(Func loader) + { + _pixelLoader = loader; + _pixelBuffer = null; + _pixelBufferLoaded = false; + _isPixelsDirty = false; + } + + internal void EnsurePixelBuffer() + { + if (_pixelBufferLoaded) return; + _pixelBuffer = _pixelLoader?.Invoke(); + _pixelBufferLoaded = true; + } + + internal byte[]? GetPixelBuffer() => _pixelBuffer; + + internal void MarkPixelsDirty() => _isPixelsDirty = true; + + public unsafe (double r, double g, double b, double a) GetPixel(int x, int y) + { + EnsurePixelBuffer(); + if (_pixelBuffer is null || (uint)x >= (uint)ImageWidth || (uint)y >= (uint)ImageHeight) + return (0d, 0d, 0d, 0d); + + fixed (byte* buf = _pixelBuffer) + { + byte* p = buf + (y * ImageWidth + x) * 4; + double a = p[3]; + if (a <= 0d) return (0d, 0d, 0d, 0d); + + double scale = 255d / a; + return ( + Math.Clamp(p[2] * scale, 0d, 255d), + Math.Clamp(p[1] * scale, 0d, 255d), + Math.Clamp(p[0] * scale, 0d, 255d), + a + ); + } + } + + public unsafe void SetPixel(int x, int y, double r, double g, double b, double a = 255d) + { + EnsurePixelBuffer(); + if (_pixelBuffer is null || (uint)x >= (uint)ImageWidth || (uint)y >= (uint)ImageHeight) + return; + + _isPixelsDirty = true; + double aK = Math.Clamp(a, 0d, 255d) / 255d; + + fixed (byte* buf = _pixelBuffer) + { + byte* p = buf + (y * ImageWidth + x) * 4; + p[0] = (byte)Math.Clamp(b * aK, 0d, 255d); + p[1] = (byte)Math.Clamp(g * aK, 0d, 255d); + p[2] = (byte)Math.Clamp(r * aK, 0d, 255d); + p[3] = (byte)Math.Clamp(a, 0d, 255d); + } + } + } +} diff --git a/LuaScript/EmptyToolBarStrategy.cs b/LuaScript/EmptyToolBarStrategy.cs new file mode 100644 index 0000000..50daeea --- /dev/null +++ b/LuaScript/EmptyToolBarStrategy.cs @@ -0,0 +1,10 @@ +using System.Collections.Generic; +using YukkuriMovieMaker.Controls.AvalonEdit.ToolBarStrategy; + +namespace LuaScript +{ + internal sealed class EmptyToolBarStrategy : IToolBarStrategy + { + public IEnumerable GetToolBarGroups() => []; + } +} diff --git a/LuaScript/IScriptProvider.cs b/LuaScript/IScriptProvider.cs new file mode 100644 index 0000000..2e25cd1 --- /dev/null +++ b/LuaScript/IScriptProvider.cs @@ -0,0 +1,8 @@ +namespace LuaScript +{ + internal interface IScriptProvider + { + string Script { get; set; } + string DefaultScript { get; } + } +} diff --git a/LuaScript/LuaAutoCompletionStrategy.cs b/LuaScript/LuaAutoCompletionStrategy.cs new file mode 100644 index 0000000..7f9a89f --- /dev/null +++ b/LuaScript/LuaAutoCompletionStrategy.cs @@ -0,0 +1,158 @@ +using System.Collections.Generic; +using System.Linq; +using System.Text.RegularExpressions; +using YukkuriMovieMaker.Controls.AvalonEdit.AutoCompletionStrategy; + +namespace LuaScript +{ + internal sealed partial class LuaAutoCompletionStrategy : IAutoCompletionStrategy + { + private static readonly string[] s_keywords = + [ + "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 string[] s_globals = + [ + "time", "frame", "totalframe", "framerate", + "timelineframe", "timelinetime", "layer", + "obj", "scene", "anim", "ymm4", + "math", "string", "table", "bit32", + "type", "tostring", "tonumber", "select", "error", "assert", "print", + "ipairs", "pairs", "next", + "unpack", + "setmetatable", "getmetatable", "rawget", "rawset", "rawequal", "rawlen", + "pcall", "xpcall", + ]; + + private static readonly (string Prefix, string[] Members)[] s_namespaces = + [ + ("obj", [ + "obj.w", "obj.h", "obj.hw", "obj.hh", "obj.diagonal", + "obj.cx", "obj.cy", "obj.cz", + "obj.x", "obj.y", "obj.z", + "obj.ox", "obj.oy", "obj.oz", + "obj.sx", "obj.sy", + "obj.zoom", "obj.alpha", "obj.aspect", + "obj.rx", "obj.ry", "obj.rz", + "obj.rxr", "obj.ryr", "obj.rzr", + "obj.track0", "obj.track1", "obj.track2", "obj.track3", + "obj.time", "obj.totaltime", "obj.t", "obj.frame", "obj.totalframe", + "obj.framerate", "obj.layer", "obj.index", "obj.num", + "obj.getpixel", "obj.setpixel", + "obj.getpixeldata" + ]), + ("math", [ + "math.abs", "math.ceil", "math.cos", "math.exp", "math.floor", + "math.fmod", "math.huge", "math.log", "math.max", "math.min", + "math.modf", "math.pi", "math.random", "math.randomseed", + "math.sin", "math.sqrt", "math.tan", "math.atan", "math.atan2", + "math.deg", "math.rad", "math.ldexp", "math.frexp", + "math.sinh", "math.cosh", "math.tanh", "math.type", + "math.tointeger", "math.maxinteger", "math.mininteger" + ]), + ("string", [ + "string.format", "string.len", "string.sub", "string.upper", + "string.lower", "string.rep", "string.reverse", "string.find", + "string.match", "string.gmatch", "string.gsub", "string.byte", + "string.char", "string.dump", "string.pack", "string.unpack", + "string.packsize" + ]), + ("table", [ + "table.insert", "table.remove", "table.sort", + "table.concat", "table.unpack", "table.move" + ]), + ("bit32", [ + "bit32.band", "bit32.bor", "bit32.bxor", "bit32.bnot", + "bit32.lshift", "bit32.rshift", "bit32.arshift", + "bit32.extract", "bit32.replace", + "bit32.btest", "bit32.countlz", "bit32.countrz" + ]), + ("scene", [ + "scene.width", "scene.height", "scene.cx", "scene.cy" + ]), + ("anim", [ + "anim.tau", "anim.e", "anim.phi", "anim.sqrt2", + "anim.lerp", "anim.smoothstep", "anim.smootherstep", "anim.clamp", + "anim.map", "anim.norm", "anim.wrap", "anim.pingpong", + "anim.sign", "anim.oscillate", "anim.triangle", "anim.square", + "anim.duration", "anim.delay", + "anim.ease_in", "anim.ease_out", "anim.ease_in_out", "anim.elastic", "anim.back", + "anim.step", "anim.fract", "anim.bounce", + "anim.hsv_to_rgb", "anim.rgb_to_hsv", + "anim.len", "anim.dist", "anim.dot", "anim.normalize", + "anim.noise", "anim.rand", "anim.polar", "anim.rotate", "anim.bezier" + ]), + ("ymm4", [ + "ymm4.group_index", "ymm4.group_count", "ymm4.group_ratio", + "ymm4.timeline_totalframe", "ymm4.timeline_totaltime", + "ymm4.is_saving", "ymm4.time_ratio", + "ymm4.is_playing", "ymm4.is_paused", "ymm4.scene_id" + ]), + ]; + + private static readonly string[] s_staticCandidates = + s_keywords + .Concat(s_globals) + .Concat(s_namespaces.SelectMany(n => n.Members)) + .Distinct() + .OrderBy(x => x.Length) + .ThenBy(x => x, StringComparer.OrdinalIgnoreCase) + .ToArray(); + + [GeneratedRegex(@"[a-zA-Z_][a-zA-Z_0-9]*$", RegexOptions.None)] + private static partial Regex IdentifierPattern(); + + [GeneratedRegex(@"(? GetCompletionItems(string input, string line, string sourceCode) + { + if (string.IsNullOrEmpty(input)) + return []; + + var lastDot = line.LastIndexOf('.'); + if (lastDot >= 0) + { + var beforeDot = line[..lastDot]; + var nsMatch = IdentifierPattern().Match(beforeDot); + if (!nsMatch.Success) + return []; + + var ns = nsMatch.Value; + foreach (var (prefix, members) in s_namespaces) + { + if (ns == prefix) + return members; + } + return []; + } + + if (input[0] is (>= 'a' and <= 'z') or (>= 'A' and <= 'Z') or '_') + { + var userFunctions = GetUserDefinedFunctions(sourceCode); + return s_staticCandidates + .Concat(userFunctions) + .Distinct() + .OrderBy(x => x.Length) + .ThenBy(x => x, StringComparer.OrdinalIgnoreCase); + } + + return []; + } + + private static IEnumerable GetUserDefinedFunctions(string sourceCode) + { + foreach (Match m in FunctionPattern().Matches(sourceCode)) + yield return m.Groups[1].Value; + + foreach (Match m in LocalFunctionPattern().Matches(sourceCode)) + yield return m.Groups[1].Value; + } + } +} diff --git a/LuaScript/LuaFoldingStrategy.cs b/LuaScript/LuaFoldingStrategy.cs new file mode 100644 index 0000000..9f3e1a8 --- /dev/null +++ b/LuaScript/LuaFoldingStrategy.cs @@ -0,0 +1,90 @@ +using System.Collections.Generic; +using System.Text.RegularExpressions; +using ICSharpCode.AvalonEdit.Document; +using ICSharpCode.AvalonEdit.Folding; +using YukkuriMovieMaker.Controls.AvalonEdit.FoldingStrategy; + +namespace LuaScript +{ + internal sealed partial class LuaFoldingStrategy : IFoldingStrategy + { + [GeneratedRegex( + @"--\[(?=*)\[.*?\]\k\]" + + @"|\[(?=*)\[.*?\]\k\]" + + @"|--[^\r\n]*" + + @"|""(?:[^""\\]|\\.)*""|'(?:[^'\\]|\\.)*'" + + @"|(?\brepeat\b)" + + @"|(?\buntil\b)" + + @"|(?\b(?:function|do|if)\b)" + + @"|(?\bend\b)", + RegexOptions.Singleline)] + private static partial Regex TokenPattern(); + + private readonly record struct Frame(int Offset, bool IsRepeat); + + public void UpdateFoldings(FoldingManager manager, TextDocument document) + { + manager.UpdateFoldings(CreateNewFoldings(document, out int firstErrorOffset), firstErrorOffset); + } + + private static IEnumerable CreateNewFoldings(TextDocument document, out int firstErrorOffset) + { + firstErrorOffset = -1; + var text = document.Text; + var newFoldings = new List(); + var openStack = new Stack(); + + foreach (Match m in TokenPattern().Matches(text)) + { + if (m.Groups["repeat"].Success) + { + openStack.Push(new Frame(m.Index + m.Length, IsRepeat: true)); + } + else if (m.Groups["open"].Success) + { + openStack.Push(new Frame(m.Index + m.Length, IsRepeat: false)); + } + else if (m.Groups["until"].Success) + { + if (openStack.Count > 0 && openStack.Peek().IsRepeat) + { + var frame = openStack.Pop(); + int blockEnd = m.Index + m.Length; + if (document.GetLineByOffset(frame.Offset).LineNumber < + document.GetLineByOffset(blockEnd).LineNumber) + { + newFoldings.Add(new NewFolding(frame.Offset, blockEnd)); + } + } + else + { + firstErrorOffset = m.Index; + } + } + else if (m.Groups["close"].Success) + { + if (openStack.Count > 0 && !openStack.Peek().IsRepeat) + { + var frame = openStack.Pop(); + int blockEnd = m.Index + m.Length; + if (document.GetLineByOffset(frame.Offset).LineNumber < + document.GetLineByOffset(blockEnd).LineNumber) + { + newFoldings.Add(new NewFolding(frame.Offset, blockEnd)); + } + } + else + { + firstErrorOffset = m.Index; + } + } + } + + if (firstErrorOffset < 0 && openStack.Count > 0) + firstErrorOffset = openStack.Peek().Offset; + + newFoldings.Sort((a, b) => a.StartOffset.CompareTo(b.StartOffset)); + return newFoldings; + } + } +} diff --git a/LuaScript/LuaScript.csproj b/LuaScript/LuaScript.csproj index ae2f256..1be1bec 100644 --- a/LuaScript/LuaScript.csproj +++ b/LuaScript/LuaScript.csproj @@ -7,6 +7,7 @@ 1.0.0 AnyCPU;x64 enable + true @@ -14,6 +15,9 @@ $(YMM4DirPath)AvalonDock.dll false + + C:\Program Files\YukkuriMovieMaker_v4_Lite_Dev\ICSharpCode.AvalonEdit.dll + $(YMM4DirPath)NAudio.dll false @@ -84,6 +88,18 @@ + + + + + + + PreserveNewest + + + + + diff --git a/LuaScript/LuaScriptEffect.cs b/LuaScript/LuaScriptEffect.cs new file mode 100644 index 0000000..3634fb0 --- /dev/null +++ b/LuaScript/LuaScriptEffect.cs @@ -0,0 +1,58 @@ +using System.Collections.Generic; +using System.ComponentModel.DataAnnotations; +using YukkuriMovieMaker.Commons; +using YukkuriMovieMaker.Controls; +using YukkuriMovieMaker.Exo; +using YukkuriMovieMaker.Player.Video; +using YukkuriMovieMaker.Plugin.Effects; + +namespace LuaScript +{ + [VideoEffect(nameof(Texts.LuaScript), [VideoEffectCategories.Filtering], ["lua", "script", "スクリプト", "lua script", "アニメーション効果", "animation"], IsAviUtlSupported = false, ResourceType = typeof(Texts))] + internal class LuaScriptEffect : VideoEffectBase, IScriptProvider + { + internal const string DefaultScript = + """ + obj.alpha = math.min(time * 255, 255) + """; + + public override string Label => Texts.LuaScript; + + [Display(GroupName = nameof(Texts.ScriptGroup), Name = nameof(Texts.ScriptCode), Description = nameof(Texts.ScriptCodeDesc), ResourceType = typeof(Texts))] + [LuaScriptToolBar] + public object? ToolBar => null; + + [Display(GroupName = nameof(Texts.ScriptGroup), ResourceType = typeof(Texts))] + [CodeEditor(Language = "pack://application:,,,/LuaScript;component/Resources/SyntaxDefinitions/Lua-{theme}.xshd", FoldingStrategyType = typeof(LuaFoldingStrategy), AutoCompletionStrategyType = typeof(LuaAutoCompletionStrategy), ToolBarStrategyType = typeof(EmptyToolBarStrategy), PropertyEditorSize = PropertyEditorSize.FullWidth)] + public string Script { get => _script; set => Set(ref _script, value); } + string _script = DefaultScript; + + string IScriptProvider.DefaultScript => DefaultScript; + + [Display(GroupName = nameof(Texts.ParametersGroup), Name = nameof(Texts.Track0), Description = nameof(Texts.TrackDesc), ResourceType = typeof(Texts))] + [AnimationSlider("F2", "", -100, 100)] + public Animation Track0 { get; } = new Animation(0, YMM4Constants.VerySmallValue, YMM4Constants.VeryLargeValue); + + [Display(GroupName = nameof(Texts.ParametersGroup), Name = nameof(Texts.Track1), Description = nameof(Texts.TrackDesc), ResourceType = typeof(Texts))] + [AnimationSlider("F2", "", -100, 100)] + public Animation Track1 { get; } = new Animation(0, YMM4Constants.VerySmallValue, YMM4Constants.VeryLargeValue); + + [Display(GroupName = nameof(Texts.ParametersGroup), Name = nameof(Texts.Track2), Description = nameof(Texts.TrackDesc), ResourceType = typeof(Texts))] + [AnimationSlider("F2", "", -100, 100)] + public Animation Track2 { get; } = new Animation(0, YMM4Constants.VerySmallValue, YMM4Constants.VeryLargeValue); + + [Display(GroupName = nameof(Texts.ParametersGroup), Name = nameof(Texts.Track3), Description = nameof(Texts.TrackDesc), ResourceType = typeof(Texts))] + [AnimationSlider("F2", "", -100, 100)] + public Animation Track3 { get; } = new Animation(0, YMM4Constants.VerySmallValue, YMM4Constants.VeryLargeValue); + + public override IEnumerable CreateExoVideoFilters(int keyFrameIndex, ExoOutputDescription exoOutputDescription) => []; + + public override IVideoEffectProcessor CreateVideoEffect(IGraphicsDevicesAndContext devices) + => new LuaScriptEffectProcessor(devices, this); + + protected override IEnumerable GetAnimatables() => + [ + Track0, Track1, Track2, Track3, + ]; + } +} diff --git a/LuaScript/LuaScriptEffectProcessor.cs b/LuaScript/LuaScriptEffectProcessor.cs new file mode 100644 index 0000000..423ae8b --- /dev/null +++ b/LuaScript/LuaScriptEffectProcessor.cs @@ -0,0 +1,359 @@ +using System.Numerics; +using System.Runtime.InteropServices; +using Vortice; +using Vortice.DCommon; +using Vortice.Direct2D1; +using Vortice.Direct2D1.Effects; +using Vortice.DXGI; +using Vortice.Mathematics; +using YukkuriMovieMaker.Commons; +using YukkuriMovieMaker.Player.Video; +using YukkuriMovieMaker.Player.Video.Effects; + +namespace LuaScript +{ + internal sealed class LuaScriptEffectProcessor(IGraphicsDevicesAndContext devices, LuaScriptEffect item) : VideoEffectProcessorBase(devices) + { + private readonly record struct RenderKey( + int Frame, + double Time, + int Length, + int Fps, + double Track0, + double Track1, + double Track2, + double Track3, + string Script, + TimelineSourceUsage Usage, + Guid SceneId, + int TimelineFrame, + double TimelineTime, + int SceneWidth, + int SceneHeight, + int Layer, + int InputIndex, + int InputCount, + int GroupIndex, + int GroupCount, + int TimelineTotalFrame, + double TimelineTotalTime, + DrawDescription InputDesc + ); + + private readonly LuaScriptEngine _engine = new(); + private readonly SemaphoreSlim _pixelLoaderSemaphore = new(1, 1); + + private GraphicsDevicesAndContext? _ownCtx; + + private ID2D1Bitmap1? _renderTarget; + private ID2D1Bitmap1? _stagingBitmap; + private ID2D1Bitmap1? _outputBitmap; + private AffineTransform2D? _transformEffect; + private byte[]? _pixelBuffer; + private int _bitmapWidth; + private int _bitmapHeight; + private RawRectF _cachedBounds; + + private bool _isFirst = true; + private ID2D1Image? _cachedInput; + private RenderKey _cachedKey; + private DrawDescription? _cachedOutputDesc; + private bool _cachedPixelsModified; + + protected override ID2D1Image? CreateEffect(IGraphicsDevicesAndContext devices) + { + _ownCtx = new GraphicsDevicesAndContext(devices); + disposer.Collect(_ownCtx); + return null; + } + + protected override void setInput(ID2D1Image? input) + { + if (!ReferenceEquals(_cachedInput, input)) + _isFirst = true; + _cachedInput = input; + } + + protected override void ClearEffectChain() + { + effectOutput = null; + } + + public override DrawDescription Update(EffectDescription desc) + { + if (input is null || _ownCtx is null) + return desc.DrawDescription; + + var frame = desc.ItemPosition.Frame; + var length = desc.ItemDuration.Frame; + var fps = desc.FPS; + var time = desc.ItemPosition.Time.TotalSeconds; + var script = item.Script ?? string.Empty; + + var t0 = item.Track0.GetValue(frame, length, fps); + var t1 = item.Track1.GetValue(frame, length, fps); + var t2 = item.Track2.GetValue(frame, length, fps); + var t3 = item.Track3.GetValue(frame, length, fps); + + var inDesc = desc.DrawDescription; + + var key = new RenderKey( + frame, time, length, fps, + t0, t1, t2, t3, + script, desc.Usage, desc.SceneId, + desc.TimelinePosition.Frame, + desc.TimelinePosition.Time.TotalSeconds, + desc.ScreenSize.Width, desc.ScreenSize.Height, + desc.Layer, desc.InputIndex, desc.InputCount, + desc.GroupIndex, desc.GroupCount, + desc.TimelineDuration.Frame, + desc.TimelineDuration.Time.TotalSeconds, + inDesc); + + if (!_isFirst && key == _cachedKey) + { + effectOutput = _cachedPixelsModified ? _transformEffect?.Output : null; + return _cachedOutputDesc ?? inDesc; + } + + var bounds = _ownCtx.DeviceContext.GetImageLocalBounds(input); + int imgW = Math.Max(1, (int)Math.Ceiling(bounds.Right - bounds.Left)); + int imgH = Math.Max(1, (int)Math.Ceiling(bounds.Bottom - bounds.Top)); + + var ctx = BuildContext(in key, imgW, imgH); + ctx.SetPixelLoader(() => LoadInputPixels(bounds, imgW, imgH)); + + DrawDescription outDesc = inDesc; + bool pixelsModified = false; + + try + { + _engine.Execute(script, ctx); + + if (ctx.IsPixelsDirty) + { + EnsureBitmaps(imgW, imgH); + WritePixelsToOutput(ctx.GetPixelBuffer()!, imgW); + UpdateTransformEffect(bounds); + effectOutput = _transformEffect!.Output; + pixelsModified = true; + } + else + { + effectOutput = null; + } + + outDesc = BuildOutputDesc(inDesc, ctx); + } + catch (LuaScriptException ex) + { + effectOutput = null; + outDesc = inDesc; + Log.Default.Write(ex.Message, ex); + } + finally + { + _pixelLoaderSemaphore.Wait(); + _pixelLoaderSemaphore.Release(); + } + + _isFirst = false; + _cachedKey = key; + _cachedOutputDesc = outDesc; + _cachedPixelsModified = pixelsModified; + + return outDesc; + } + + private static AviUtlScriptContext BuildContext(in RenderKey key, int imgW, int imgH) + { + var zoom = key.InputDesc.Zoom; + double zoomAvg = (zoom.X + zoom.Y) / 2d; + double aspect = zoomAvg > 0d + ? (zoom.X - zoom.Y) / (zoom.X + zoom.Y) + : 0d; + + return new AviUtlScriptContext + { + ImageWidth = imgW, + ImageHeight = imgH, + X = key.InputDesc.Draw.X, + Y = key.InputDesc.Draw.Y, + Z = key.InputDesc.Draw.Z, + Ox = key.InputDesc.CenterPoint.X, + Oy = key.InputDesc.CenterPoint.Y, + Oz = 0d, + Sx = zoom.X, + Sy = zoom.Y, + Zoom = zoomAvg, + Aspect = aspect, + Alpha = key.InputDesc.Opacity * 255d, + Rx = key.InputDesc.Rotation.X, + Ry = key.InputDesc.Rotation.Y, + Rz = key.InputDesc.Rotation.Z, + Track0 = key.Track0, + Track1 = key.Track1, + Track2 = key.Track2, + Track3 = key.Track3, + Time = key.Time, + Frame = key.Frame, + TotalFrame = key.Length, + TotalTime = key.Fps > 0 ? key.Length / (double)key.Fps : 0d, + Framerate = key.Fps, + TimelineFrame = key.TimelineFrame, + TimelineTime = key.TimelineTime, + SceneWidth = key.SceneWidth, + SceneHeight = key.SceneHeight, + Layer = key.Layer, + Index = key.InputIndex, + Num = key.InputCount, + GroupIndex = key.GroupIndex, + GroupCount = key.GroupCount, + TimelineTotalFrame = key.TimelineTotalFrame, + TimelineTotalTime = key.TimelineTotalTime, + IsSaving = key.Usage == TimelineSourceUsage.Exporting, + IsPlaying = key.Usage == TimelineSourceUsage.Playing, + IsPaused = key.Usage == TimelineSourceUsage.Paused, + SceneId = key.SceneId.ToString(), + TimeRatio = key.Length > 0 ? key.Frame / (double)key.Length : 0d, + }; + } + + private static DrawDescription BuildOutputDesc(DrawDescription inDesc, AviUtlScriptContext ctx) + { + return inDesc with + { + Draw = new Vector3((float)ctx.X, (float)ctx.Y, (float)ctx.Z), + CenterPoint = new Vector2((float)ctx.Ox, (float)ctx.Oy), + Zoom = new Vector2((float)ctx.Sx, (float)ctx.Sy), + Opacity = Math.Clamp(ctx.Alpha / 255d, 0d, 1d), + Rotation = new Vector3((float)ctx.Rx, (float)ctx.Ry, (float)ctx.Rz), + }; + } + + private byte[] LoadInputPixels(RawRectF bounds, int width, int height) + { + _pixelLoaderSemaphore.Wait(); + try + { + EnsureBitmaps(width, height); + + var dc = _ownCtx!.DeviceContext; + var savedTarget = dc.Target; + + dc.Target = _renderTarget; + dc.BeginDraw(); + dc.Clear(null); + dc.DrawImage(input!, new Vector2(-bounds.Left, -bounds.Top)); + dc.EndDraw(); + dc.Target = savedTarget; + + _stagingBitmap!.CopyFromBitmap(_renderTarget!); + + var mapped = _stagingBitmap.Map(MapOptions.Read); + try + { + if (mapped.Pitch == width * 4) + { + Marshal.Copy(mapped.Bits, _pixelBuffer!, 0, width * height * 4); + } + else + { + for (int row = 0; row < height; row++) + Marshal.Copy( + mapped.Bits + mapped.Pitch * row, + _pixelBuffer!, + row * width * 4, + width * 4); + } + } + finally + { + _stagingBitmap.Unmap(); + } + + return _pixelBuffer!; + } + finally + { + _pixelLoaderSemaphore.Release(); + } + } + + private unsafe void WritePixelsToOutput(byte[] pixels, int width) + { + fixed (byte* ptr = pixels) + _outputBitmap!.CopyFromMemory(new nint(ptr), width * 4); + } + + private void UpdateTransformEffect(RawRectF bounds) + { + if (_transformEffect is null) + { + _transformEffect = new AffineTransform2D(_ownCtx!.DeviceContext); + _transformEffect.SetInput(0, _outputBitmap, true); + _cachedBounds = default; + } + + if (_cachedBounds.Left != bounds.Left || _cachedBounds.Top != bounds.Top) + { + _transformEffect.TransformMatrix = Matrix3x2.CreateTranslation(bounds.Left, bounds.Top); + _cachedBounds = bounds; + } + } + + private void EnsureBitmaps(int width, int height) + { + if (_bitmapWidth == width && _bitmapHeight == height) return; + + _renderTarget?.Dispose(); + _stagingBitmap?.Dispose(); + _outputBitmap?.Dispose(); + _transformEffect?.Dispose(); + _renderTarget = null; + _stagingBitmap = null; + _outputBitmap = null; + _transformEffect = null; + _bitmapWidth = 0; + _bitmapHeight = 0; + + var dc = _ownCtx!.DeviceContext; + + _renderTarget = dc.CreateEmptyBitmap(width, height, BitmapOptions.Target); + + var stagingProps = new BitmapProperties1( + new PixelFormat(Format.B8G8R8A8_UNorm, Vortice.DCommon.AlphaMode.Premultiplied), + 96f, 96f, + BitmapOptions.CpuRead | BitmapOptions.CannotDraw); + _stagingBitmap = dc.CreateBitmap( + new SizeI(width, height), + nint.Zero, + width * 4, + stagingProps); + + _outputBitmap = dc.CreateEmptyBitmap(width, height, BitmapOptions.Target); + _pixelBuffer = new byte[width * height * 4]; + + _bitmapWidth = width; + _bitmapHeight = height; + } + + protected override void Dispose(bool disposing) + { + if (disposing) + { + _engine.Dispose(); + _pixelLoaderSemaphore.Dispose(); + _renderTarget?.Dispose(); + _stagingBitmap?.Dispose(); + _outputBitmap?.Dispose(); + _transformEffect?.Dispose(); + _renderTarget = null; + _stagingBitmap = null; + _outputBitmap = null; + _transformEffect = null; + } + base.Dispose(disposing); + } + } +} diff --git a/LuaScript/LuaScriptEngine.cs b/LuaScript/LuaScriptEngine.cs new file mode 100644 index 0000000..fb20a54 --- /dev/null +++ b/LuaScript/LuaScriptEngine.cs @@ -0,0 +1,551 @@ +using System.Collections.Concurrent; +using MoonSharp.Interpreter; +using MoonSharp.Interpreter.Debugging; +using MoonSharp.Interpreter.Loaders; + +namespace LuaScript +{ + internal sealed class LuaScriptEngine : IDisposable + { + private readonly record struct ExecutionResult( + LuaScriptException? Exception, + bool TimedOut); + + private sealed record ExecutionJob( + string Code, + AviUtlScriptContext Context, + CancellationToken Cancellation, + TaskCompletionSource Completion); + + private sealed class ExecutionThread : IDisposable + { + private sealed class CancellationDebugger : IDebugger + { + private static readonly DebuggerAction s_runAction = new() { Action = DebuggerAction.ActionType.Run }; + + private CancellationToken _token; + + internal void UpdateToken(CancellationToken token) => _token = token; + + public DebuggerCaps GetDebuggerCaps() => 0; + public void SetDebugService(DebugService debugService) { } + public void SetSourceCode(SourceCode sourceCode) { } + public void SetByteCode(string[] byteCode) { } + public bool SignalRuntimeException(ScriptRuntimeException ex) => false; + public void SignalExecutionEnded() { } + public void Update(WatchType watchType, IEnumerable items) { } + public List GetWatchItems() => []; + public void RefreshBreakpoints(IEnumerable refs) { } + + public bool IsPauseRequested() => _token.IsCancellationRequested; + + public DebuggerAction GetAction(int ip, SourceRef sourceref) + { + _token.ThrowIfCancellationRequested(); + return s_runAction; + } + } + + private readonly BlockingCollection _queue = new(boundedCapacity: 1); + private readonly Thread _thread; + private readonly CancellationDebugger _debugger = new(); + + private Script? _script; + private DynValue? _compiledChunk; + private string _lastCompiledCode = string.Empty; + private Table? _objTable; + private Table? _sceneTable; + private Table? _animTable; + private Table? _ymm4Table; + private HashSet? _builtinGlobalSnapshot; + private HashSet? _objTableSnapshot; + private HashSet? _sceneTableSnapshot; + private HashSet? _animTableSnapshot; + private HashSet? _ymm4TableSnapshot; + private CancellationToken _activeCancellation; + private AviUtlScriptContext? _activeContext; + + internal ExecutionThread() + { + _thread = new Thread(WorkerLoop) + { + IsBackground = true, + Name = "LuaScriptWorker" + }; + _thread.Start(); + } + + internal ExecutionResult TryExecute(string code, AviUtlScriptContext ctx, int timeoutMs) + { + using var cts = new CancellationTokenSource(); + var tcs = new TaskCompletionSource( + TaskCreationOptions.RunContinuationsAsynchronously); + + if (!_queue.TryAdd(new ExecutionJob(code, ctx, cts.Token, tcs))) + return new ExecutionResult( + new LuaScriptRuntimeException("Script execution queue is full."), false); + + if (tcs.Task.Wait(timeoutMs)) + return tcs.Task.Result; + + cts.Cancel(); + return new ExecutionResult(null, TimedOut: true); + } + + private void WorkerLoop() + { + try + { + foreach (var job in _queue.GetConsumingEnumerable()) + ProcessJob(job); + } + catch (OperationCanceledException) { } + catch (InvalidOperationException) { } + } + + private void ProcessJob(ExecutionJob job) + { + if (job.Cancellation.IsCancellationRequested) + { + job.Completion.TrySetResult(new ExecutionResult(null, TimedOut: true)); + return; + } + + _activeCancellation = job.Cancellation; + _activeContext = job.Context; + _debugger.UpdateToken(job.Cancellation); + + try + { + EnsureScript(); + EnsureScriptIntegrity(); + EnsureCompiled(job.Code); + SetupGlobals(job.Context); + _script!.Call(_compiledChunk!); + ReadBackGlobals(job.Context); + job.Completion.TrySetResult(new ExecutionResult(null, false)); + } + catch (OperationCanceledException) when (job.Cancellation.IsCancellationRequested) + { + job.Completion.TrySetResult(new ExecutionResult(null, TimedOut: true)); + } + catch (LuaScriptException ex) + { + job.Completion.TrySetResult(new ExecutionResult(ex, false)); + } + catch (ScriptRuntimeException ex) + { + job.Completion.TrySetResult(new ExecutionResult( + new LuaScriptRuntimeException(ex.DecoratedMessage ?? ex.Message, ex), false)); + } + catch (Exception ex) + { + job.Completion.TrySetResult(new ExecutionResult( + new LuaScriptRuntimeException(ex.Message, ex), false)); + } + finally + { + _debugger.UpdateToken(default); + _activeContext = null; + _activeCancellation = default; + } + } + + private void EnsureScript() + { + if (_script is not null) return; + var script = new Script( + CoreModules.Basic | + CoreModules.Math | + CoreModules.String | + CoreModules.Table | + CoreModules.Bit32 | + CoreModules.TableIterators | + CoreModules.Metatables | + CoreModules.ErrorHandling); + script.Options.ScriptLoader = new DisabledFileScriptLoader(); + script.AttachDebugger(_debugger); + _script = script; + } + + private void EnsureScriptIntegrity() + { + if (_script is null) return; + if (_script.Globals.Get("math").Type == DataType.Table) return; + _script = null; + _compiledChunk = null; + _lastCompiledCode = string.Empty; + _objTable = null; + _sceneTable = null; + _animTable = null; + _ymm4Table = null; + _builtinGlobalSnapshot = null; + _objTableSnapshot = null; + _sceneTableSnapshot = null; + _animTableSnapshot = null; + _ymm4TableSnapshot = null; + EnsureScript(); + } + + private void EnsureCompiled(string code) + { + if (_compiledChunk is not null && code == _lastCompiledCode) return; + + DynValue chunk; + try + { + chunk = _script!.LoadString(code, null, "LuaScript"); + } + catch (SyntaxErrorException ex) + { + throw new LuaScriptCompilationException(ex.DecoratedMessage ?? ex.Message, ex); + } + + _compiledChunk = chunk; + _lastCompiledCode = code; + } + + private void SetupGlobals(AviUtlScriptContext ctx) + { + var script = _script!; + bool isFirstSetup = _objTable is null; + + if (isFirstSetup) + { + var sceneTable = new Table(script); + script.Globals["scene"] = sceneTable; + + var objTable = new Table(script); + RegisterPixelCallbacks(objTable); + script.Globals["obj"] = objTable; + + var animTable = new Table(script); + AnimTableRegistrar.RegisterFunctions(animTable); + script.Globals["anim"] = animTable; + + var ymm4Table = new Table(script); + script.Globals["ymm4"] = ymm4Table; + + _sceneTable = sceneTable; + _animTable = animTable; + _ymm4Table = ymm4Table; + _objTable = objTable; + } + else + { + ResetUserGlobals(script); + + if (!ReferenceEquals(script.Globals.Get("scene").Table, _sceneTable)) + { + var sceneTable = new Table(script); + script.Globals["scene"] = sceneTable; + _sceneTable = sceneTable; + _sceneTableSnapshot = null; + } + + if (!ReferenceEquals(script.Globals.Get("obj").Table, _objTable)) + { + var objTable = new Table(script); + RegisterPixelCallbacks(objTable); + script.Globals["obj"] = objTable; + _objTable = objTable; + _objTableSnapshot = null; + } + + if (!ReferenceEquals(script.Globals.Get("anim").Table, _animTable)) + { + var animTable = new Table(script); + AnimTableRegistrar.RegisterFunctions(animTable); + script.Globals["anim"] = animTable; + _animTable = animTable; + _animTableSnapshot = null; + } + + if (!ReferenceEquals(script.Globals.Get("ymm4").Table, _ymm4Table)) + { + var ymm4Table = new Table(script); + script.Globals["ymm4"] = ymm4Table; + _ymm4Table = ymm4Table; + _ymm4TableSnapshot = null; + } + + ResetUserTableKeys(_objTable!, ref _objTableSnapshot); + ResetUserTableKeys(_sceneTable!, ref _sceneTableSnapshot); + ResetUserTableKeys(_animTable!, ref _animTableSnapshot); + ResetUserTableKeys(_ymm4Table!, ref _ymm4TableSnapshot); + } + + script.Globals["time"] = ctx.Time; + script.Globals["frame"] = ctx.Frame; + script.Globals["totalframe"] = ctx.TotalFrame; + script.Globals["framerate"] = ctx.Framerate; + script.Globals["timelineframe"] = ctx.TimelineFrame; + script.Globals["timelinetime"] = ctx.TimelineTime; + script.Globals["layer"] = ctx.Layer; + + _sceneTable!["width"] = ctx.SceneWidth; + _sceneTable!["height"] = ctx.SceneHeight; + _sceneTable!["cx"] = ctx.SceneWidth / 2d; + _sceneTable!["cy"] = ctx.SceneHeight / 2d; + + Ymm4TableRegistrar.UpdateVariables(_ymm4Table!, ctx); + + _objTable!["w"] = ctx.ImageWidth; + _objTable!["h"] = ctx.ImageHeight; + _objTable!["hw"] = ctx.ImageWidth / 2d; + _objTable!["hh"] = ctx.ImageHeight / 2d; + _objTable!["cx"] = ctx.ImageWidth / 2d; + _objTable!["cy"] = ctx.ImageHeight / 2d; + _objTable!["cz"] = 0d; + _objTable!["diagonal"] = Math.Sqrt((double)ctx.ImageWidth * ctx.ImageWidth + (double)ctx.ImageHeight * ctx.ImageHeight); + _objTable!["x"] = ctx.X; + _objTable!["y"] = ctx.Y; + _objTable!["z"] = ctx.Z; + _objTable!["ox"] = ctx.Ox; + _objTable!["oy"] = ctx.Oy; + _objTable!["oz"] = ctx.Oz; + _objTable!["sx"] = ctx.Sx; + _objTable!["sy"] = ctx.Sy; + _objTable!["sz"] = 1d; + _objTable!["zoom"] = ctx.Zoom; + _objTable!["aspect"] = ctx.Aspect; + _objTable!["alpha"] = ctx.Alpha; + _objTable!["rx"] = ctx.Rx; + _objTable!["ry"] = ctx.Ry; + _objTable!["rz"] = ctx.Rz; + _objTable!["rxr"] = ctx.RxRad; + _objTable!["ryr"] = ctx.RyRad; + _objTable!["rzr"] = ctx.RzRad; + _objTable!["track0"] = ctx.Track0; + _objTable!["track1"] = ctx.Track1; + _objTable!["track2"] = ctx.Track2; + _objTable!["track3"] = ctx.Track3; + _objTable!["time"] = ctx.Time; + _objTable!["frame"] = ctx.Frame; + _objTable!["totalframe"] = ctx.TotalFrame; + _objTable!["totaltime"] = ctx.TotalTime; + _objTable!["t"] = ctx.TotalFrame > 0 ? ctx.Frame / (double)ctx.TotalFrame : 0d; + _objTable!["framerate"] = ctx.Framerate; + _objTable!["layer"] = ctx.Layer; + _objTable!["index"] = ctx.Index; + _objTable!["num"] = ctx.Num; + + if (isFirstSetup) + { + _builtinGlobalSnapshot = CaptureGlobalKeys(script); + _objTableSnapshot = CaptureTableKeys(_objTable!); + _sceneTableSnapshot = CaptureTableKeys(_sceneTable!); + _animTableSnapshot = CaptureTableKeys(_animTable!); + _ymm4TableSnapshot = CaptureTableKeys(_ymm4Table!); + } + + script.Call( + script.Globals.Get("math").Table.Get("randomseed"), + DynValue.NewNumber(ctx.Frame)); + } + + private static HashSet CaptureGlobalKeys(Script script) + { + var keys = new HashSet(StringComparer.Ordinal); + foreach (var key in script.Globals.Keys) + { + if (key.Type == DataType.String) + keys.Add(key.String); + } + return keys; + } + + private static HashSet CaptureTableKeys(Table table) + { + var keys = new HashSet(StringComparer.Ordinal); + foreach (var key in table.Keys) + { + if (key.Type == DataType.String) + keys.Add(key.String); + } + return keys; + } + + private static void ResetUserTableKeys(Table table, ref HashSet? snapshot) + { + if (snapshot is null) return; + var keysToRemove = new List(); + foreach (var key in table.Keys) + { + if (key.Type == DataType.String && + !snapshot.Contains(key.String)) + { + keysToRemove.Add(key.String); + } + } + foreach (var key in keysToRemove) + table[key] = DynValue.Nil; + } + + private void ResetUserGlobals(Script script) + { + var keysToRemove = new List(); + foreach (var key in script.Globals.Keys) + { + if (key.Type == DataType.String && + !_builtinGlobalSnapshot!.Contains(key.String)) + { + keysToRemove.Add(key.String); + } + } + foreach (var key in keysToRemove) + script.Globals[key] = DynValue.Nil; + } + + private void RegisterPixelCallbacks(Table obj) + { + obj["getpixel"] = DynValue.NewCallback((_, args) => + { + _activeCancellation.ThrowIfCancellationRequested(); + if (_activeContext is null) return DynValue.Nil; + int x = (int)(args[0].CastToNumber() ?? 0d); + int y = (int)(args[1].CastToNumber() ?? 0d); + var (r, g, b, a) = _activeContext.GetPixel(x, y); + return DynValue.NewTuple( + DynValue.NewNumber(r), + DynValue.NewNumber(g), + DynValue.NewNumber(b), + DynValue.NewNumber(a)); + }); + + obj["setpixel"] = DynValue.NewCallback((_, args) => + { + _activeCancellation.ThrowIfCancellationRequested(); + if (_activeContext is null) return DynValue.Void; + int x = (int)(args[0].CastToNumber() ?? 0d); + int y = (int)(args[1].CastToNumber() ?? 0d); + double r = args[2].CastToNumber() ?? 0d; + double g = args[3].CastToNumber() ?? 0d; + double b = args[4].CastToNumber() ?? 0d; + double a = args.Count > 5 ? args[5].CastToNumber() ?? 255d : 255d; + _activeContext.SetPixel(x, y, r, g, b, a); + return DynValue.Void; + }); + + obj["getpixeldata"] = DynValue.NewCallback((_, _) => + { + _activeCancellation.ThrowIfCancellationRequested(); + if (_activeContext is null) return DynValue.Nil; + _activeContext.EnsurePixelBuffer(); + return UserData.Create(new PixelDataProxy(_activeContext)); + }); + + obj["putpixeldata"] = DynValue.NewCallback((_, _) => DynValue.Void); + } + + private void ReadBackGlobals(AviUtlScriptContext ctx) + { + if (_objTable is null) return; + + ctx.X = _objTable.Get("x").CastToNumber() ?? ctx.X; + ctx.Y = _objTable.Get("y").CastToNumber() ?? ctx.Y; + ctx.Z = _objTable.Get("z").CastToNumber() ?? ctx.Z; + ctx.Ox = _objTable.Get("ox").CastToNumber() ?? ctx.Ox; + ctx.Oy = _objTable.Get("oy").CastToNumber() ?? ctx.Oy; + ctx.Oz = _objTable.Get("oz").CastToNumber() ?? ctx.Oz; + ctx.Alpha = _objTable.Get("alpha").CastToNumber() ?? ctx.Alpha; + + double initialSx = ctx.Sx; + double initialSy = ctx.Sy; + double initialZoom = ctx.Zoom; + double initialAspect = ctx.Aspect; + + ctx.Sx = _objTable.Get("sx").CastToNumber() ?? ctx.Sx; + ctx.Sy = _objTable.Get("sy").CastToNumber() ?? ctx.Sy; + ctx.Zoom = _objTable.Get("zoom").CastToNumber() ?? ctx.Zoom; + ctx.Aspect = _objTable.Get("aspect").CastToNumber() ?? ctx.Aspect; + + bool sxsyChanged = Math.Abs(ctx.Sx - initialSx) > 1e-10 || Math.Abs(ctx.Sy - initialSy) > 1e-10; + bool zoomAspectChanged = Math.Abs(ctx.Zoom - initialZoom) > 1e-10 || Math.Abs(ctx.Aspect - initialAspect) > 1e-10; + + if (zoomAspectChanged && !sxsyChanged) + { + ctx.Sx = ctx.Zoom * (1.0 + ctx.Aspect); + ctx.Sy = ctx.Zoom * (1.0 - ctx.Aspect); + } + + double rxrNew = _objTable.Get("rxr").CastToNumber() ?? ctx.RxRad; + ctx.Rx = Math.Abs(rxrNew - ctx.RxRad) > 1e-10 + ? rxrNew * (180d / Math.PI) + : _objTable.Get("rx").CastToNumber() ?? ctx.Rx; + + double ryrNew = _objTable.Get("ryr").CastToNumber() ?? ctx.RyRad; + ctx.Ry = Math.Abs(ryrNew - ctx.RyRad) > 1e-10 + ? ryrNew * (180d / Math.PI) + : _objTable.Get("ry").CastToNumber() ?? ctx.Ry; + + double rzrNew = _objTable.Get("rzr").CastToNumber() ?? ctx.RzRad; + ctx.Rz = Math.Abs(rzrNew - ctx.RzRad) > 1e-10 + ? rzrNew * (180d / Math.PI) + : _objTable.Get("rz").CastToNumber() ?? ctx.Rz; + } + + public void Dispose() + { + _queue.CompleteAdding(); + _thread.Join(); + _queue.Dispose(); + } + + internal void AbandonAsync() + { + _queue.CompleteAdding(); + ThreadPool.QueueUserWorkItem(_ => + { + _thread.Join(); + _queue.Dispose(); + }); + } + + private sealed class DisabledFileScriptLoader : ScriptLoaderBase + { + public override object LoadFile(string file, Table globalContext) + => throw new NotSupportedException( + "File access is not allowed in Lua script effects."); + + public override bool ScriptFileExists(string name) => false; + } + } + + private const int ExecutionTimeoutMilliseconds = 5000; + + static LuaScriptEngine() + { + UserData.RegisterType(); + } + + private ExecutionThread _executionThread = new(); + private bool _disposed; + + public void Execute(string code, AviUtlScriptContext ctx) + { + ObjectDisposedException.ThrowIf(_disposed, this); + + var result = _executionThread.TryExecute(code, ctx, ExecutionTimeoutMilliseconds); + + if (result.TimedOut) + { + var stale = _executionThread; + _executionThread = new ExecutionThread(); + stale.AbandonAsync(); + throw new LuaScriptRuntimeException( + $"Script execution timed out after {ExecutionTimeoutMilliseconds} ms."); + } + + if (result.Exception is not null) + throw result.Exception; + } + + public void Dispose() + { + if (_disposed) return; + _disposed = true; + _executionThread.Dispose(); + } + } +} diff --git a/LuaScript/LuaScriptExceptions.cs b/LuaScript/LuaScriptExceptions.cs new file mode 100644 index 0000000..859ca14 --- /dev/null +++ b/LuaScript/LuaScriptExceptions.cs @@ -0,0 +1,8 @@ +namespace LuaScript +{ + internal abstract class LuaScriptException(string message, Exception? inner = null) : Exception(message, inner); + + internal sealed class LuaScriptCompilationException(string message, Exception? inner = null) : LuaScriptException(message, inner); + + internal sealed class LuaScriptRuntimeException(string message, Exception? inner = null) : LuaScriptException(message, inner); +} diff --git a/LuaScript/LuaScriptToolBar.xaml b/LuaScript/LuaScriptToolBar.xaml new file mode 100644 index 0000000..568500f --- /dev/null +++ b/LuaScript/LuaScriptToolBar.xaml @@ -0,0 +1,16 @@ + + + +