LuaScript.Runtime へ実行コアを分離し依存を逆転

このコミットが含まれているのは:
routersys committed 2026-07-03 11:50:23 +09:00
1 親 9a630ecb5a
コミット 79f8ff8839
41ファイル変更
+64 -19

検索条件に一致するファイルはありません

+100
ファイルの表示
@@ -0,0 +1,100 @@
using System;
using System.Collections.Generic;
using System.Collections.Immutable;
namespace LuaScript.Anchor
{
internal enum AnchorConnection
{
None,
Line,
Loop,
Star,
Arm,
}
internal readonly record struct AnchorOptions(AnchorConnection Connection, bool Is3D);
internal readonly record struct AnchorRequestData(string Group, int Count, AnchorConnection Connection, bool Is3D);
internal static class AnchorSupport
{
public const int MaxAnchors = 32;
public const string TrackGroup = "track";
public static int ClampCount(int count) => Math.Clamp(count, 0, MaxAnchors);
public static void ApplyOption(string option, ref AnchorConnection connection, ref bool is3D)
{
switch (option)
{
case "line": connection = AnchorConnection.Line; break;
case "loop": connection = AnchorConnection.Loop; break;
case "star": connection = AnchorConnection.Star; break;
case "arm": connection = AnchorConnection.Arm; break;
case "xyz": is3D = true; break;
}
}
public static (double X, double Y) DefaultPosition(int index)
{
int col = index % 8;
int row = index / 8;
return ((col - 3.5) * 60d, (row - 1.5) * 60d);
}
public static void ResolvePosition(IReadOnlyList<LuaAnchorPoint>? source, string group, int index,
out double x, out double y, out double z)
{
if (source is not null)
{
for (int i = 0; i < source.Count; i++)
{
var a = source[i];
if (a.Index == index && string.Equals(a.Group, group, StringComparison.Ordinal))
{
x = a.X;
y = a.Y;
z = a.Z;
return;
}
}
}
var (dx, dy) = DefaultPosition(index);
x = dx;
y = dy;
z = 0d;
}
public static ImmutableList<LuaAnchorPoint> ApplyDrag(
ImmutableList<LuaAnchorPoint> source, string group, int index, double dx, double dy, double dz)
{
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 = a.X + dx,
Y = a.Y + dy,
Z = a.Z + dz,
});
}
}
var (bx, by) = DefaultPosition(index);
return source.Add(new LuaAnchorPoint
{
Group = group,
Index = index,
X = bx + dx,
Y = by + dy,
Z = dz,
});
}
}
}
+11
ファイルの表示
@@ -0,0 +1,11 @@
namespace LuaScript.Anchor
{
public sealed class LuaAnchorPoint
{
public string Group { get; set; } = string.Empty;
public int Index { get; set; }
public double X { get; set; }
public double Y { get; set; }
public double Z { get; set; }
}
}
+419
ファイルの表示
@@ -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;
}
}
}
+17
ファイルの表示
@@ -0,0 +1,17 @@
using System.Collections.Generic;
namespace LuaScript
{
internal sealed class AviUtlEffectRequest
{
public string Name { get; }
public IReadOnlyList<KeyValuePair<string, object>> Arguments { get; }
public AviUtlEffectRequest(string name, IReadOnlyList<KeyValuePair<string, object>> arguments)
{
Name = name;
Arguments = arguments;
}
}
}
+44
ファイルの表示
@@ -0,0 +1,44 @@
using MoonSharp.Interpreter;
namespace LuaScript
{
internal sealed class AviUtlFontState
{
public string Family { get; private set; } = string.Empty;
public double Size { get; private set; } = 34d;
public bool Bold { get; private set; }
public bool Italic { get; private set; }
public int Color { get; private set; } = 0xFFFFFF;
public void Reset()
{
Family = string.Empty;
Size = 34d;
Bold = false;
Italic = false;
Color = 0xFFFFFF;
}
public void Apply(DynValue name, DynValue size, DynValue style, DynValue color)
{
if (name.Type == DataType.String)
Family = name.String;
else if (name.Type == DataType.Number)
Family = name.CastToString();
Size = size.CastToNumber() ?? Size;
if (style.CastToNumber() is double styleNumber)
{
double flags = Math.Floor(styleNumber);
Bold = FloorMod(flags, 2d) == 1d;
Italic = FloorMod(Math.Floor(flags / 2d), 2d) == 1d;
}
Color = (int)(color.CastToNumber() ?? Color);
}
private static double FloorMod(double value, double divisor) =>
value - Math.Floor(value / divisor) * divisor;
}
}
+81
ファイルの表示
@@ -0,0 +1,81 @@
using LuaScript.Compat;
using LuaScript.Diagnostics;
using MoonSharp.Interpreter;
namespace LuaScript
{
internal static class AviUtlGlobalRegistrar
{
internal static void RegisterFunctions(Table globals, Func<double> timeRatio)
{
globals["debug_print"] = DynValue.NewCallback((_, args) =>
{
if (args.Count > 0)
{
var value = args[0];
DebugOutput.Write(value.Type == DataType.String ? value.String : value.ToPrintString());
}
return DynValue.Void;
});
globals["RGB"] = DynValue.NewCallback((_, args) =>
{
int count = args.Count;
if (count >= 6)
return DynValue.NewNumber(AviUtlGlobalFunctions.RgbInterpolate(
Number(args, 0), Number(args, 1), Number(args, 2),
Number(args, 3), Number(args, 4), Number(args, 5),
timeRatio()));
if (count >= 3)
return DynValue.NewNumber(AviUtlGlobalFunctions.RgbCompose(
Number(args, 0), Number(args, 1), Number(args, 2)));
if (count >= 1)
{
AviUtlGlobalFunctions.RgbComponents(Number(args, 0), out int r, out int g, out int b);
return DynValue.NewTuple(
DynValue.NewNumber(r),
DynValue.NewNumber(g),
DynValue.NewNumber(b));
}
return DynValue.Nil;
});
globals["HSV"] = DynValue.NewCallback((_, args) =>
{
int count = args.Count;
if (count >= 6)
return DynValue.NewNumber(AviUtlGlobalFunctions.HsvInterpolate(
Number(args, 0), Number(args, 1), Number(args, 2),
Number(args, 3), Number(args, 4), Number(args, 5),
timeRatio()));
if (count >= 3)
return DynValue.NewNumber(AviUtlGlobalFunctions.HsvCompose(
Number(args, 0), Number(args, 1), Number(args, 2)));
if (count >= 1)
{
AviUtlGlobalFunctions.HsvComponents(Number(args, 0), out int h, out int s, out int v);
return DynValue.NewTuple(
DynValue.NewNumber(h),
DynValue.NewNumber(s),
DynValue.NewNumber(v));
}
return DynValue.Nil;
});
globals["OR"] = DynValue.NewCallback((_, args) =>
DynValue.NewNumber(AviUtlGlobalFunctions.BitOr(Number(args, 0), Number(args, 1))));
globals["AND"] = DynValue.NewCallback((_, args) =>
DynValue.NewNumber(AviUtlGlobalFunctions.BitAnd(Number(args, 0), Number(args, 1))));
globals["XOR"] = DynValue.NewCallback((_, args) =>
DynValue.NewNumber(AviUtlGlobalFunctions.BitXor(Number(args, 0), Number(args, 1))));
globals["SHIFT"] = DynValue.NewCallback((_, args) =>
DynValue.NewNumber(AviUtlGlobalFunctions.BitShift(Number(args, 0), Number(args, 1))));
}
private static double Number(CallbackArguments args, int index) =>
args.Count > index ? args[index].CastToNumber() ?? 0d : 0d;
}
}
+402
ファイルの表示
@@ -0,0 +1,402 @@
using LuaScript.Anchor;
namespace LuaScript
{
internal sealed class AviUtlScriptContext
{
public IReadOnlyList<LuaAnchorPoint>? AnchorSource { get; set; }
private readonly List<AnchorRequestData> _anchorRequests = [];
public IReadOnlyList<AnchorRequestData> AnchorRequests => _anchorRequests;
internal void AddAnchorRequest(in AnchorRequestData request) => _anchorRequests.Add(request);
internal void ClearAnchorRequests() => _anchorRequests.Clear();
public bool IsPlaying { get; set; }
public bool IsPaused { get; set; }
public string SceneId { get; set; } = string.Empty;
public int ImageWidth { get; set; }
public int ImageHeight { get; set; }
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; set; }
public double Track1 { get; set; }
public double Track2 { get; set; }
public double Track3 { get; set; }
public double Slider0 { get; set; }
public double Slider1 { get; set; }
public double Slider2 { get; set; }
public double Slider3 { get; set; }
public bool Check0 { get; set; }
public bool Check1 { get; set; }
public bool Check2 { get; set; }
public bool Check3 { get; set; }
public bool HasColor { get; set; }
public double ColorValue { get; set; }
public bool? DrawStateOverride { get; set; }
public double Time { get; set; }
public int Frame { get; set; }
public int TotalFrame { get; set; }
public double TotalTime { get; set; }
public int Framerate { get; set; }
public int TimelineFrame { get; set; }
public double TimelineTime { get; set; }
public int SceneWidth { get; set; }
public int SceneHeight { get; set; }
public int Layer { get; set; }
public int Index { get; set; }
public int Num { get; set; }
public Func<ISceneObjectResolver>? ResolverProvider { get; set; }
private readonly Dictionary<string, string> _stringParameters = new(StringComparer.Ordinal);
public IReadOnlyDictionary<string, string> StringParameters => _stringParameters;
internal void SetStringParameter(string name, string? value) => _stringParameters[name] = value ?? string.Empty;
private const double Epsilon = 1e-10;
private readonly List<SceneObjectQuery> _objectQueries = [];
public IReadOnlyList<SceneObjectQuery> ObjectQueries => _objectQueries;
private readonly SceneValueSession _sceneValues = new();
public IReadOnlyList<SceneValueQuery> SceneValueQueries => _sceneValues.Queries;
internal object? SceneScope { get; set; }
internal void BeginSceneValues() => _sceneValues.Begin(SceneScope ?? this, SceneId, TimelineFrame, Layer);
internal void PublishSceneValues() => _sceneValues.Publish();
public SceneValue GetSceneValue(string name) => _sceneValues.Get(name);
public void SetSceneValue(string name, SceneValue value) => _sceneValues.Set(name, value);
private readonly List<AviUtlEffectRequest> _effectRequests = [];
public IReadOnlyList<AviUtlEffectRequest> EffectRequests => _effectRequests;
internal void AddEffect(AviUtlEffectRequest request) => _effectRequests.Add(request);
internal void ClearEffects() => _effectRequests.Clear();
internal IBufferCompositor Compositor { get; set; } = SoftwareCompositor.Instance;
private readonly List<DrawCommand> _drawCommands = [];
public IReadOnlyList<DrawCommand> DrawCommands => _drawCommands;
internal void AddDraw(DrawCommand command) => _drawCommands.Add(command);
internal void ClearDraws() => _drawCommands.Clear();
private bool _drawTargetTemp;
internal void ResetDrawTarget() => _drawTargetTemp = false;
internal void SetDrawTarget(bool temp, int width, int height, bool hasSize)
{
_drawTargetTemp = temp;
if (temp && hasSize)
{
int w = Math.Max(1, width);
int h = Math.Max(1, height);
_buffers["t"] = (new byte[w * h * 4], w, h);
}
}
internal void SubmitDraw(DrawCommand command)
{
if (!_drawTargetTemp)
{
_drawCommands.Add(command);
return;
}
CompositeToTemp(command);
}
private void CompositeToTemp(DrawCommand command)
{
EnsurePixelBuffer();
var src = _pixelBuffer;
if (src is null)
return;
if (!_buffers.TryGetValue("t", out var temp))
{
int w = Math.Max(1, ImageWidth);
int h = Math.Max(1, ImageHeight);
temp = (new byte[w * h * 4], w, h);
_buffers["t"] = temp;
}
Compositor.TryCompose(temp.Data, temp.Width, temp.Height, src, ImageWidth, ImageHeight, command);
}
private readonly Dictionary<string, (byte[] Data, int Width, int Height)> _buffers = new(StringComparer.Ordinal);
internal bool CopyBuffer(string dst, string src)
{
if (!TryReadBuffer(src, out var data, out int w, out int h))
return false;
return TryWriteBuffer(dst, data, w, h);
}
private bool TryReadBuffer(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))
{
data = stored.Data;
width = stored.Width;
height = stored.Height;
return true;
}
return false;
default:
return false;
}
}
private bool TryWriteBuffer(string id, byte[] data, int width, int height)
{
int n = width * height * 4;
switch (BufferKind(id, out string key))
{
case 'o':
if (_copyOutputBuffer is null || _copyOutputBuffer.Length != n)
_copyOutputBuffer = new byte[n];
Buffer.BlockCopy(data, 0, _copyOutputBuffer, 0, n);
ReplaceBuffer(_copyOutputBuffer, width, height);
return true;
case 't':
case 'c':
if (!_buffers.TryGetValue(key, out var existing) || existing.Data.Length != n)
existing.Data = new byte[n];
Buffer.BlockCopy(data, 0, existing.Data, 0, n);
_buffers[key] = (existing.Data, width, height);
return false;
default:
return false;
}
}
private byte[]? _copyOutputBuffer;
private static char BufferKind(string id, out string key)
{
key = string.Empty;
int i = 0;
while (i < id.Length && (id[i] == ' ' || id[i] == '\t'))
i++;
if (i >= id.Length)
return '\0';
char kind = char.ToLowerInvariant(id[i]);
if (kind == 't')
key = "t";
else if (kind == 'c')
{
int colon = id.IndexOf(':', i);
key = colon >= 0 ? "c:" + id[(colon + 1)..].Trim() : "c";
}
return kind;
}
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; set; }
public int GroupCount { get; set; }
public int TimelineTotalFrame { get; set; }
public double TimelineTotalTime { get; set; }
public bool IsSaving { get; set; }
public double TimeRatio { get; set; }
private Func<byte[]>? _pixelLoader;
private byte[]? _pixelBuffer;
private bool _pixelBufferLoaded;
private bool _isPixelsDirty;
private bool _bufferReplaced;
public bool IsPixelsDirty => _isPixelsDirty;
public bool BufferReplaced => _bufferReplaced;
internal int TotalChannels => ImageWidth * ImageHeight * 4;
internal void ClearQueries() => _objectQueries.Clear();
internal void SetPixelLoader(Func<byte[]> loader)
{
_pixelLoader = loader;
_pixelBuffer = null;
_pixelBufferLoaded = false;
_isPixelsDirty = false;
_bufferReplaced = false;
}
internal void ReplaceBuffer(byte[] buffer, int width, int height)
{
_pixelBuffer = buffer;
_pixelBufferLoaded = true;
_isPixelsDirty = true;
_bufferReplaced = true;
ImageWidth = width;
ImageHeight = height;
}
internal void EnsurePixelBuffer()
{
if (_pixelBufferLoaded) return;
_pixelBuffer = _pixelLoader?.Invoke();
_pixelBufferLoaded = true;
}
internal void SetResolvedBuffer(byte[] buffer, int width, int height)
{
_pixelBuffer = buffer;
_pixelBufferLoaded = true;
ImageWidth = width;
ImageHeight = height;
}
internal byte[]? GetPixelBuffer() => _pixelBuffer;
internal void MarkPixelsDirty() => _isPixelsDirty = true;
public bool ResolveObject(string tag, int frame, out SceneObjectInfo info)
{
var resolver = ResolverProvider?.Invoke();
if (resolver is not null && resolver.TryResolve(tag, frame, out var resolved))
{
_objectQueries.Add(new SceneObjectQuery(tag, frame, resolved));
info = resolved;
return true;
}
_objectQueries.Add(new SceneObjectQuery(tag, frame, null));
info = default;
return false;
}
public void ApplyWriteBack(
double newSx, double newSy, double newZoom, double newAspect,
double newRx, double newRy, double newRz,
double newRxr, double newRyr, double newRzr)
{
double initialSx = Sx;
double initialSy = Sy;
double initialZoom = Zoom;
double initialAspect = Aspect;
Sx = newSx;
Sy = newSy;
Zoom = newZoom;
Aspect = newAspect;
bool sxsyChanged = Math.Abs(Sx - initialSx) > Epsilon || Math.Abs(Sy - initialSy) > Epsilon;
bool zoomAspectChanged = Math.Abs(Zoom - initialZoom) > Epsilon || Math.Abs(Aspect - initialAspect) > Epsilon;
if (zoomAspectChanged && !sxsyChanged)
{
Sx = Zoom * (1.0 + Aspect);
Sy = Zoom * (1.0 - Aspect);
}
double initialRxr = RxRad;
Rx = Math.Abs(newRxr - initialRxr) > Epsilon
? newRxr * (180d / Math.PI)
: newRx;
double initialRyr = RyRad;
Ry = Math.Abs(newRyr - initialRyr) > Epsilon
? newRyr * (180d / Math.PI)
: newRy;
double initialRzr = RzRad;
Rz = Math.Abs(newRzr - initialRzr) > Epsilon
? newRzr * (180d / Math.PI)
: newRz;
}
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);
}
}
}
}
+111
ファイルの表示
@@ -0,0 +1,111 @@
using System;
namespace LuaScript.Compat
{
internal static class MoonSharpBit32
{
private const double Modulo = 4294967296.0;
public static uint ToUInt32(double value) => unchecked((uint)Math.IEEERemainder(value, Modulo));
public static int ToInt32(double value) => unchecked((int)Math.IEEERemainder(value, Modulo));
public static uint Band(params double[] values)
{
uint accum = ToUInt32(values[0]);
for (int i = 1; i < values.Length; i++)
accum &= ToUInt32(values[i]);
return accum;
}
public static uint Bor(params double[] values)
{
uint accum = ToUInt32(values[0]);
for (int i = 1; i < values.Length; i++)
accum |= ToUInt32(values[i]);
return accum;
}
public static uint Bxor(params double[] values)
{
uint accum = ToUInt32(values[0]);
for (int i = 1; i < values.Length; i++)
accum ^= ToUInt32(values[i]);
return accum;
}
public static bool Btest(params double[] values) => Band(values) != 0u;
public static uint Bnot(double value) => ~ToUInt32(value);
public static uint Lshift(double value, double shift)
{
uint v = ToUInt32(value);
int a = (int)shift;
return a < 0 ? v >> -a : v << a;
}
public static uint Rshift(double value, double shift)
{
uint v = ToUInt32(value);
int a = (int)shift;
return a < 0 ? v << -a : v >> a;
}
public static int Arshift(double value, double shift)
{
int v = ToInt32(value);
int a = (int)shift;
return a < 0 ? v << -a : v >> a;
}
public static uint Lrotate(double value, double shift)
{
uint v = ToUInt32(value);
int a = ((int)shift) % 32;
return a < 0 ? (v >> -a) | (v << (32 + a)) : (v << a) | (v >> (32 - a));
}
public static uint Rrotate(double value, double shift)
{
uint v = ToUInt32(value);
int a = ((int)shift) % 32;
return a < 0 ? (v << -a) | (v >> (32 + a)) : (v >> a) | (v << (32 - a));
}
public static uint Extract(double value, double pos, double? width)
{
uint v = ToUInt32(value);
int p = (int)pos;
int w = width is null ? 1 : (int)width.Value;
ValidatePosWidth(p, w);
return (v >> p) & NBitMask(w);
}
public static uint Replace(double value, double replacement, double pos, double? width)
{
uint v = ToUInt32(value);
uint u = ToUInt32(replacement);
int p = (int)pos;
int w = width is null ? 1 : (int)width.Value;
ValidatePosWidth(p, w);
uint mask = NBitMask(w) << p;
return (v & ~mask) | (u & mask);
}
private static void ValidatePosWidth(int pos, int width)
{
if (pos > 31 || pos + width > 31)
throw new ArgumentException("trying to access non-existent bits");
}
private static uint NBitMask(int bits)
{
if (bits <= 0)
return 0u;
if (bits >= 32)
return 0xFFFFFFFFu;
return (1u << bits) - 1u;
}
}
}
+12
ファイルの表示
@@ -0,0 +1,12 @@
using System.Runtime.InteropServices;
namespace LuaScript.Diagnostics
{
internal static partial class DebugOutput
{
[LibraryImport("kernel32.dll", EntryPoint = "OutputDebugStringW", StringMarshalling = StringMarshalling.Utf16)]
private static partial void OutputDebugStringW(string message);
internal static void Write(string message) => OutputDebugStringW(message);
}
}
+42
ファイルの表示
@@ -0,0 +1,42 @@
using System;
using System.Text.RegularExpressions;
namespace LuaScript.Diagnostics
{
internal enum LuaScriptDiagnosticKind
{
Compile,
Runtime,
Timeout,
}
internal readonly record struct LuaScriptDiagnostic(
LuaScriptDiagnosticKind Kind,
int Line,
int Column,
int Length,
string Message);
internal static partial class LuaScriptDiagnosticParser
{
[GeneratedRegex(@"^LuaScript:\((\d+),(\d+)(?:-(\d+)(?:,(\d+))?)?\):\s*", RegexOptions.None)]
private static partial Regex LocationPattern();
public static LuaScriptDiagnostic Parse(LuaScriptDiagnosticKind kind, string? message)
{
var text = message ?? string.Empty;
var match = LocationPattern().Match(text);
if (!match.Success)
return new LuaScriptDiagnostic(kind, 0, 0, 0, text.Trim());
int line = int.Parse(match.Groups[1].Value);
int columnStart = int.Parse(match.Groups[2].Value);
int length = 0;
if (match.Groups[3].Success && !match.Groups[4].Success)
length = Math.Max(0, int.Parse(match.Groups[3].Value) - columnStart);
return new LuaScriptDiagnostic(kind, line, columnStart + 1, length, text[match.Length..].Trim());
}
}
}
+110
ファイルの表示
@@ -0,0 +1,110 @@
using System;
using System.Collections.Generic;
namespace LuaScript.Diagnostics
{
internal interface ILuaScriptDiagnosticsListener
{
void OnDiagnosticsChanged();
}
internal sealed class LuaScriptDiagnostics
{
public static LuaScriptDiagnostics Instance { get; } = new();
private const int MaxTrackedScripts = 64;
private readonly object _gate = new();
private readonly Dictionary<string, IReadOnlyList<LuaScriptDiagnostic>> _entries = new(StringComparer.Ordinal);
private readonly Queue<string> _insertionOrder = new();
private readonly List<WeakReference<ILuaScriptDiagnosticsListener>> _listeners = [];
private LuaScriptDiagnostics()
{
}
public void Subscribe(ILuaScriptDiagnosticsListener listener)
{
lock (_gate)
{
PruneDeadListeners();
_listeners.Add(new WeakReference<ILuaScriptDiagnosticsListener>(listener));
}
}
public IReadOnlyList<LuaScriptDiagnostic> Get(string? script)
{
if (script is null)
return [];
lock (_gate)
return _entries.TryGetValue(script, out var diagnostics) ? diagnostics : [];
}
public void Report(string? script, IReadOnlyList<LuaScriptDiagnostic> diagnostics)
{
if (script is null)
return;
diagnostics ??= [];
ILuaScriptDiagnosticsListener[] targets;
lock (_gate)
{
if (_entries.TryGetValue(script, out var existing) && AreEqual(existing, diagnostics))
return;
if (!_entries.ContainsKey(script))
_insertionOrder.Enqueue(script);
_entries[script] = diagnostics;
while (_entries.Count > MaxTrackedScripts && _insertionOrder.Count > 0)
{
var oldest = _insertionOrder.Dequeue();
if (!string.Equals(oldest, script, StringComparison.Ordinal))
_entries.Remove(oldest);
}
targets = CollectLiveListeners();
}
foreach (var target in targets)
target.OnDiagnosticsChanged();
}
private ILuaScriptDiagnosticsListener[] CollectLiveListeners()
{
var live = new List<ILuaScriptDiagnosticsListener>(_listeners.Count);
for (int i = _listeners.Count - 1; i >= 0; i--)
{
if (_listeners[i].TryGetTarget(out var listener))
live.Add(listener);
else
_listeners.RemoveAt(i);
}
return [.. live];
}
private void PruneDeadListeners()
{
for (int i = _listeners.Count - 1; i >= 0; i--)
{
if (!_listeners[i].TryGetTarget(out _))
_listeners.RemoveAt(i);
}
}
private static bool AreEqual(IReadOnlyList<LuaScriptDiagnostic> a, IReadOnlyList<LuaScriptDiagnostic> b)
{
if (a.Count != b.Count)
return false;
for (int i = 0; i < a.Count; i++)
{
if (!a[i].Equals(b[i]))
return false;
}
return true;
}
}
}
+13
ファイルの表示
@@ -0,0 +1,13 @@
namespace LuaScript
{
internal readonly record struct DrawCommand(
double Ox,
double Oy,
double Oz,
double Zoom,
double Alpha,
double Aspect,
double[]? Poly = null,
double Antialias = 1d,
double Blend = 0d);
}
+53
ファイルの表示
@@ -0,0 +1,53 @@
using System;
using System.Numerics;
namespace LuaScript
{
internal static class DrawPolyMath
{
public const int Length = 21;
public static bool TrySolveAffine(double[] poly, out Matrix3x2 matrix)
{
double x0 = poly[0], y0 = poly[1];
double x1 = poly[3], y1 = poly[4];
double x3 = poly[9], y3 = poly[10];
double u0 = poly[12], v0 = poly[13];
double u1 = poly[14], v1 = poly[15];
double u3 = poly[18], v3 = poly[19];
double det = u0 * (v1 - v3) - v0 * (u1 - u3) + (u1 * v3 - v1 * u3);
if (Math.Abs(det) < 1e-9)
{
matrix = Matrix3x2.Identity;
return false;
}
double inv = 1d / det;
double a = (x0 * (v1 - v3) - v0 * (x1 - x3) + (x1 * v3 - v1 * x3)) * inv;
double b = (u0 * (x1 - x3) - x0 * (u1 - u3) + (u1 * x3 - x1 * u3)) * inv;
double c = (u0 * (v1 * x3 - x1 * v3) - v0 * (u1 * x3 - x1 * u3) + x0 * (u1 * v3 - v1 * u3)) * inv;
double d = (y0 * (v1 - v3) - v0 * (y1 - y3) + (y1 * v3 - v1 * y3)) * inv;
double e = (u0 * (y1 - y3) - y0 * (u1 - u3) + (u1 * y3 - y1 * u3)) * inv;
double f = (u0 * (v1 * y3 - y1 * v3) - v0 * (u1 * y3 - y1 * u3) + y0 * (u1 * v3 - v1 * u3)) * inv;
matrix = new Matrix3x2((float)a, (float)d, (float)b, (float)e, (float)c, (float)f);
return true;
}
public static void Bounds(double[] poly, out double minX, out double minY, out double maxX, out double maxY)
{
minX = minY = double.MaxValue;
maxX = maxY = double.MinValue;
for (int i = 0; i < 4; i++)
{
double x = poly[i * 3];
double y = poly[i * 3 + 1];
if (x < minX) minX = x;
if (x > maxX) maxX = x;
if (y < minY) minY = y;
if (y > maxY) maxY = y;
}
}
}
}
+29
ファイルの表示
@@ -0,0 +1,29 @@
using System;
using System.Numerics;
namespace LuaScript
{
internal static class DrawTransform
{
public static bool TryResolve(in DrawCommand command, int srcW, int srcH, out Matrix3x2 matrix)
{
if (command.Poly is { } poly)
return DrawPolyMath.TrySolveAffine(poly, out matrix);
double aspect = Math.Clamp(command.Aspect, -1d, 1d);
double zx = command.Zoom * (1d + aspect);
double zy = command.Zoom * (1d - aspect);
if (zx == 0d || zy == 0d)
{
matrix = Matrix3x2.Identity;
return false;
}
matrix =
Matrix3x2.CreateTranslation(-srcW * 0.5f, -srcH * 0.5f) *
Matrix3x2.CreateScale((float)zx, (float)zy) *
Matrix3x2.CreateTranslation((float)command.Ox, (float)command.Oy);
return true;
}
}
}
+76
ファイルの表示
@@ -0,0 +1,76 @@
using System;
namespace LuaScript.Engine.Kernel
{
internal static class KernelUniformBinding
{
public static double[] Create() => new double[KernelUniforms.Count];
public static void Fill(AviUtlScriptContext ctx, double[] values)
{
values[(int)KernelUniform.Width] = ctx.ImageWidth;
values[(int)KernelUniform.Height] = ctx.ImageHeight;
values[(int)KernelUniform.HalfWidth] = ctx.ImageWidth / 2d;
values[(int)KernelUniform.HalfHeight] = ctx.ImageHeight / 2d;
values[(int)KernelUniform.CenterX] = ctx.ImageWidth / 2d;
values[(int)KernelUniform.CenterY] = ctx.ImageHeight / 2d;
values[(int)KernelUniform.CenterZ] = 0d;
values[(int)KernelUniform.Diagonal] = Math.Sqrt((double)ctx.ImageWidth * ctx.ImageWidth + (double)ctx.ImageHeight * ctx.ImageHeight);
values[(int)KernelUniform.X] = ctx.X;
values[(int)KernelUniform.Y] = ctx.Y;
values[(int)KernelUniform.Z] = ctx.Z;
values[(int)KernelUniform.Ox] = ctx.Ox;
values[(int)KernelUniform.Oy] = ctx.Oy;
values[(int)KernelUniform.Oz] = ctx.Oz;
values[(int)KernelUniform.Sx] = ctx.Sx;
values[(int)KernelUniform.Sy] = ctx.Sy;
values[(int)KernelUniform.Sz] = 1d;
values[(int)KernelUniform.Zoom] = ctx.Zoom;
values[(int)KernelUniform.Aspect] = ctx.Aspect;
values[(int)KernelUniform.Alpha] = ctx.Alpha;
values[(int)KernelUniform.Rx] = ctx.Rx;
values[(int)KernelUniform.Ry] = ctx.Ry;
values[(int)KernelUniform.Rz] = ctx.Rz;
values[(int)KernelUniform.Rxr] = ctx.RxRad;
values[(int)KernelUniform.Ryr] = ctx.RyRad;
values[(int)KernelUniform.Rzr] = ctx.RzRad;
values[(int)KernelUniform.Track0] = ctx.Track0;
values[(int)KernelUniform.Track1] = ctx.Track1;
values[(int)KernelUniform.Track2] = ctx.Track2;
values[(int)KernelUniform.Track3] = ctx.Track3;
values[(int)KernelUniform.Slider0] = ctx.Slider0;
values[(int)KernelUniform.Slider1] = ctx.Slider1;
values[(int)KernelUniform.Slider2] = ctx.Slider2;
values[(int)KernelUniform.Slider3] = ctx.Slider3;
values[(int)KernelUniform.Check0] = ctx.Check0 ? 1d : 0d;
values[(int)KernelUniform.Check1] = ctx.Check1 ? 1d : 0d;
values[(int)KernelUniform.Check2] = ctx.Check2 ? 1d : 0d;
values[(int)KernelUniform.Check3] = ctx.Check3 ? 1d : 0d;
values[(int)KernelUniform.Color] = ctx.HasColor ? ctx.ColorValue : -1d;
values[(int)KernelUniform.Time] = ctx.Time;
values[(int)KernelUniform.Frame] = ctx.Frame;
values[(int)KernelUniform.TotalFrame] = ctx.TotalFrame;
values[(int)KernelUniform.TotalTime] = ctx.TotalTime;
values[(int)KernelUniform.T] = ctx.TotalFrame > 0 ? ctx.Frame / (double)ctx.TotalFrame : 0d;
values[(int)KernelUniform.Framerate] = ctx.Framerate;
values[(int)KernelUniform.Layer] = ctx.Layer;
values[(int)KernelUniform.Index] = ctx.Index;
values[(int)KernelUniform.Num] = ctx.Num;
values[(int)KernelUniform.SceneWidth] = ctx.SceneWidth;
values[(int)KernelUniform.SceneHeight] = ctx.SceneHeight;
values[(int)KernelUniform.SceneCenterX] = ctx.SceneWidth / 2d;
values[(int)KernelUniform.SceneCenterY] = ctx.SceneHeight / 2d;
values[(int)KernelUniform.TimelineFrame] = ctx.TimelineFrame;
values[(int)KernelUniform.TimelineTime] = ctx.TimelineTime;
}
public static void Pack(double[] values, float[] packed)
{
int count = Math.Min(values.Length, packed.Length);
for (int i = 0; i < count; i++)
packed[i] = (float)values[i];
for (int i = count; i < packed.Length; i++)
packed[i] = 0f;
}
}
}
+728
ファイルの表示
@@ -0,0 +1,728 @@
using System;
using System.Diagnostics;
using System.IO;
using System.IO.MemoryMappedFiles;
using System.Text;
using System.Threading;
namespace LuaScript.Engine
{
internal sealed class LuaJitWorker : IDisposable
{
private readonly string _luajitPath;
private readonly string _workerScript;
private readonly string _shimScript;
private readonly string _nativeDir;
private MemoryMappedFile? _mmf;
private MemoryMappedViewAccessor? _view;
private EventWaitHandle? _workEvent;
private EventWaitHandle? _doneEvent;
private Process? _process;
private int _stringParamsCapacity = NativeProtocol.MinStringParamsCapacity;
private long _pixelOffset = NativeProtocol.PixelOffset(NativeProtocol.MinStringParamsCapacity);
private long _allocatedSize;
private bool _alive;
private readonly byte[] _callbackTag = new byte[NativeProtocol.CallbackTagMax];
private readonly byte[] _lastCallbackTag = new byte[NativeProtocol.CallbackTagMax];
private readonly double[] _anchorBuffer = new double[Anchor.AnchorSupport.MaxAnchors * 3];
private int _lastCallbackTagLength = -1;
private string _lastCallbackTagText = string.Empty;
private int _scriptVersion;
private string? _lastScript;
private byte[] _lastScriptBytes = Array.Empty<byte>();
private bool _scriptWritten;
private readonly Dictionary<string, byte[]> _stringNameBytes = new(StringComparer.Ordinal);
private byte[] _stringValueBytes = new byte[256];
private byte[] _sceneValueBytes = new byte[256];
public LuaJitWorker(string nativeDir)
{
_nativeDir = nativeDir;
_luajitPath = Path.Combine(nativeDir, "luajit.exe");
_workerScript = Path.Combine(nativeDir, "worker.lua");
_shimScript = Path.Combine(nativeDir, "shim.lua");
}
public static bool IsAvailable(string nativeDir) =>
File.Exists(Path.Combine(nativeDir, "luajit.exe"));
public bool Execute(
string script,
double[] fields,
IReadOnlyDictionary<string, string> stringParameters,
PixelRegionAccess loadPixels,
int width,
int height,
int timeoutMs,
Func<string, int, SceneObjectInfo?> resolveObject,
Func<string, int, double, double, double, (byte[] buffer, int w, int h)> loadFigure,
Func<string, string, double, bool, bool, int, (byte[] buffer, int w, int h)> loadText,
Func<string, (byte[] buffer, int w, int h)> loadImage,
Func<string, double, (byte[] buffer, int w, int h)> loadMovie,
Action<string, IReadOnlyList<KeyValuePair<string, object>>> addEffect,
Action<DrawCommand> addDraw,
Action<string, int, bool, int, double[]> setAnchor,
Func<string, SceneValue> sceneGetValue,
Action<string, SceneValue> sceneSetValue,
out bool pixelsDirty,
out bool bufferReplaced,
out int resultWidth,
out int resultHeight,
out string? error)
{
pixelsDirty = false;
bufferReplaced = false;
resultWidth = width;
resultHeight = height;
error = null;
bool scriptChanged = !ReferenceEquals(script, _lastScript);
if (scriptChanged)
{
byte[] scriptBytes = Encoding.UTF8.GetBytes(script);
if (scriptBytes.Length > NativeProtocol.ScriptMax)
{
error = "script too large for native lane";
return false;
}
_lastScript = script;
_lastScriptBytes = scriptBytes;
_scriptVersion++;
}
int stringCapacity = ResolveStringCapacity(_stringParamsCapacity, MeasureStringParameters(stringParameters));
EnsureWorker(width, height, stringCapacity);
var view = _view!;
view.WriteArray(NativeProtocol.FieldsOffset, fields, 0, NativeProtocol.FieldCount);
WriteStringParameters(view, stringParameters);
view.Write(NativeProtocol.OffWidth, width);
view.Write(NativeProtocol.OffHeight, height);
if (scriptChanged || !_scriptWritten)
{
view.Write(NativeProtocol.OffScriptLen, _lastScriptBytes.Length);
view.WriteArray(NativeProtocol.ScriptOffset, _lastScriptBytes, 0, _lastScriptBytes.Length);
_scriptWritten = true;
}
view.Write(NativeProtocol.OffScriptVersion, _scriptVersion);
view.Write(NativeProtocol.OffPixelsDirty, 0);
view.Write(NativeProtocol.OffErrorLen, 0);
view.Write(NativeProtocol.OffStatus, NativeProtocol.StatusIdle);
view.Write(NativeProtocol.OffCommand, NativeProtocol.CmdRun);
_workEvent!.Set();
var stopwatch = Stopwatch.StartNew();
int status;
while (true)
{
long remaining = timeoutMs - stopwatch.ElapsedMilliseconds;
if (remaining <= 0 || !_doneEvent!.WaitOne((int)remaining))
{
KillWorker();
error = "native script execution timed out";
return false;
}
status = view.ReadInt32(NativeProtocol.OffStatus);
if (status != NativeProtocol.StatusCallback)
break;
int callbackKind = view.ReadInt32(NativeProtocol.OffCallbackKind);
if (callbackKind == NativeProtocol.CbKindRequestPixels)
{
try
{
AccessPixelRegion(loadPixels);
}
catch
{
KillWorker();
throw;
}
}
else if (callbackKind == NativeProtocol.CbKindFlushDraws)
{
DrainDrawRing(view, addDraw);
}
else
{
DispatchCallback(view, resolveObject, loadFigure, loadText, loadImage, loadMovie, addEffect, setAnchor, sceneGetValue, sceneSetValue);
}
_workEvent.Set();
}
if (status == NativeProtocol.StatusError)
{
int len = view.ReadInt32(NativeProtocol.OffErrorLen);
var buffer = new byte[Math.Clamp(len, 0, NativeProtocol.ErrorMax)];
view.ReadArray(NativeProtocol.ErrorOffset, buffer, 0, buffer.Length);
error = Encoding.UTF8.GetString(buffer);
return false;
}
DrainDrawRing(view, addDraw);
for (int i = NativeProtocol.FirstWritableField; i <= NativeProtocol.LastWritableField; i++)
fields[i] = view.ReadDouble(NativeProtocol.FieldsOffset + i * 8);
fields[NativeProtocol.DrawState] = view.ReadDouble(NativeProtocol.FieldsOffset + NativeProtocol.DrawState * 8);
resultWidth = view.ReadInt32(NativeProtocol.OffWidth);
resultHeight = view.ReadInt32(NativeProtocol.OffHeight);
bufferReplaced = resultWidth != width || resultHeight != height;
pixelsDirty = view.ReadInt32(NativeProtocol.OffPixelsDirty) != 0;
if (pixelsDirty && (long)resultWidth * resultHeight * 4 > _allocatedSize - _pixelOffset)
{
error = "native worker reported a pixel buffer beyond capacity";
return false;
}
return true;
}
public void ReadPixels(PixelRegionAccess reader) => AccessPixelRegion(reader);
private unsafe void AccessPixelRegion(PixelRegionAccess access)
{
var handle = _view!.SafeMemoryMappedViewHandle;
byte* ptr = null;
handle.AcquirePointer(ref ptr);
try
{
long offset = _view.PointerOffset + _pixelOffset;
access((nint)(ptr + offset), (long)handle.ByteLength - offset);
}
finally
{
handle.ReleasePointer();
}
}
private unsafe void WritePixelRegion(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 + _pixelOffset, handle.ByteLength - (ulong)(_view.PointerOffset + _pixelOffset), (ulong)length);
}
finally
{
handle.ReleasePointer();
}
}
private static int MeasureStringParameters(IReadOnlyDictionary<string, string> stringParameters)
{
int total = 4;
foreach (var pair in stringParameters)
total += 8 + Encoding.UTF8.GetByteCount(pair.Key) + Encoding.UTF8.GetByteCount(pair.Value ?? string.Empty);
return total;
}
private static int ResolveStringCapacity(int current, int required)
{
int capacity = current;
while (capacity < required)
{
if (capacity > int.MaxValue / 2)
{
capacity = required;
break;
}
capacity *= 2;
}
return capacity;
}
private void WriteStringParameters(MemoryMappedViewAccessor view, IReadOnlyDictionary<string, string> stringParameters)
{
long basePos = NativeProtocol.StringParamsOffset;
long limit = basePos + _stringParamsCapacity;
long pos = basePos + 4;
int count = 0;
foreach (var pair in stringParameters)
{
if (!_stringNameBytes.TryGetValue(pair.Key, out var name))
{
name = Encoding.UTF8.GetBytes(pair.Key);
_stringNameBytes[pair.Key] = name;
}
string value = pair.Value ?? string.Empty;
int maxValueBytes = Encoding.UTF8.GetMaxByteCount(value.Length);
if (_stringValueBytes.Length < maxValueBytes)
_stringValueBytes = new byte[Math.Max(maxValueBytes, _stringValueBytes.Length * 2)];
int valueLen = Encoding.UTF8.GetBytes(value, 0, value.Length, _stringValueBytes, 0);
if (pos + 8 + name.Length + valueLen > limit)
break;
view.Write(pos, name.Length); pos += 4;
view.WriteArray(pos, name, 0, name.Length); pos += name.Length;
view.Write(pos, valueLen); pos += 4;
view.WriteArray(pos, _stringValueBytes, 0, valueLen); pos += valueLen;
count++;
}
view.Write(basePos, count);
view.Write(NativeProtocol.OffStringParamsLen, (int)(pos - basePos));
}
private void DispatchCallback(
MemoryMappedViewAccessor view,
Func<string, int, SceneObjectInfo?> resolveObject,
Func<string, int, double, double, double, (byte[] buffer, int w, int h)> loadFigure,
Func<string, string, double, bool, bool, int, (byte[] buffer, int w, int h)> loadText,
Func<string, (byte[] buffer, int w, int h)> loadImage,
Func<string, double, (byte[] buffer, int w, int h)> loadMovie,
Action<string, IReadOnlyList<KeyValuePair<string, object>>> addEffect,
Action<string, int, bool, int, double[]> setAnchor,
Func<string, SceneValue> sceneGetValue,
Action<string, SceneValue> sceneSetValue)
{
int kind = view.ReadInt32(NativeProtocol.OffCallbackKind);
switch (kind)
{
case NativeProtocol.CbKindGetObject:
ResolveGetObjectCallback(view, resolveObject);
break;
case NativeProtocol.CbKindLoadFigure:
ResolveLoadFigureCallback(view, loadFigure);
break;
case NativeProtocol.CbKindLoadText:
ResolveLoadTextCallback(view, loadText);
break;
case NativeProtocol.CbKindLoadImage:
ResolveLoadImageCallback(view, loadImage);
break;
case NativeProtocol.CbKindLoadMovie:
ResolveLoadMovieCallback(view, loadMovie);
break;
case NativeProtocol.CbKindEffect:
ResolveEffectCallback(view, addEffect);
break;
case NativeProtocol.CbKindSetAnchor:
ResolveSetAnchorCallback(view, setAnchor);
break;
case NativeProtocol.CbKindSceneGet:
ResolveSceneGetCallback(view, sceneGetValue);
break;
case NativeProtocol.CbKindSceneSet:
ResolveSceneSetCallback(view, sceneSetValue);
break;
}
}
private void ResolveSceneGetCallback(MemoryMappedViewAccessor view, Func<string, SceneValue> getValue)
{
int tagLen = Math.Clamp(view.ReadInt32(NativeProtocol.OffCallbackTagLen), 0, NativeProtocol.CallbackTagMax);
view.ReadArray(NativeProtocol.CallbackTagOffset, _callbackTag, 0, tagLen);
string name = ResolveTag(tagLen);
SceneValue value;
try { value = getValue(name); }
catch { value = SceneValue.Nil; }
long rOff = NativeProtocol.CallbackResultOffset;
view.Write(rOff + 0 * 8, (double)value.Kind);
view.Write(rOff + 1 * 8, value.Number);
if (value.Kind == SceneValueKind.String)
{
string text = value.Text ?? string.Empty;
int maxBytes = Encoding.UTF8.GetMaxByteCount(text.Length);
if (_sceneValueBytes.Length < maxBytes)
_sceneValueBytes = new byte[Math.Max(maxBytes, _sceneValueBytes.Length * 2)];
int length = Encoding.UTF8.GetBytes(text, 0, text.Length, _sceneValueBytes, 0);
if (length > NativeProtocol.CallbackTagMax)
length = NativeProtocol.CallbackTagMax;
view.WriteArray(NativeProtocol.CallbackTagOffset, _sceneValueBytes, 0, length);
view.Write(NativeProtocol.OffCallbackTagLen, length);
}
view.Write(NativeProtocol.OffCallbackFound, 1);
}
private void ResolveSceneSetCallback(MemoryMappedViewAccessor view, Action<string, SceneValue> setValue)
{
int tagLen = Math.Clamp(view.ReadInt32(NativeProtocol.OffCallbackTagLen), 0, NativeProtocol.CallbackTagMax);
view.ReadArray(NativeProtocol.CallbackTagOffset, _callbackTag, 0, tagLen);
long rOff = NativeProtocol.CallbackResultOffset;
var kind = (SceneValueKind)(int)view.ReadDouble(rOff + 0 * 8);
double number = view.ReadDouble(rOff + 1 * 8);
string name;
SceneValue value;
if (kind == SceneValueKind.String)
{
int separator = Array.IndexOf(_callbackTag, (byte)0, 0, tagLen);
int nameLength = separator >= 0 ? separator : tagLen;
name = Encoding.UTF8.GetString(_callbackTag, 0, nameLength);
value = SceneValue.FromString(separator >= 0
? Encoding.UTF8.GetString(_callbackTag, separator + 1, tagLen - separator - 1)
: string.Empty);
}
else
{
name = ResolveTag(tagLen);
value = kind switch
{
SceneValueKind.Number => SceneValue.FromNumber(number),
SceneValueKind.Boolean => SceneValue.FromBoolean(number != 0d),
_ => SceneValue.Nil,
};
}
try { setValue(name, value); }
catch { }
view.Write(NativeProtocol.OffCallbackFound, 1);
}
private void ResolveSetAnchorCallback(MemoryMappedViewAccessor view, Action<string, int, bool, int, double[]> setAnchor)
{
int tagLen = Math.Clamp(view.ReadInt32(NativeProtocol.OffCallbackTagLen), 0, NativeProtocol.CallbackTagMax);
view.ReadArray(NativeProtocol.CallbackTagOffset, _callbackTag, 0, tagLen);
string group = Encoding.UTF8.GetString(_callbackTag, 0, tagLen);
long rOff = NativeProtocol.CallbackResultOffset;
int count = Math.Clamp((int)view.ReadDouble(rOff + 0 * 8), 0, Anchor.AnchorSupport.MaxAnchors);
bool is3D = view.ReadDouble(rOff + 1 * 8) != 0d;
int connection = (int)view.ReadDouble(rOff + 2 * 8);
Array.Clear(_anchorBuffer, 0, _anchorBuffer.Length);
try { setAnchor(group, count, is3D, connection, _anchorBuffer); }
catch { }
int stride = is3D ? 3 : 2;
for (int i = 0; i < count * stride; i++)
view.Write(NativeProtocol.CallbackTagOffset + i * 8, _anchorBuffer[i]);
view.Write(NativeProtocol.OffCallbackFound, 1);
}
private void DrainDrawRing(MemoryMappedViewAccessor view, Action<DrawCommand> addDraw)
{
long ringBase = NativeProtocol.DrawRingOffset(_stringParamsCapacity);
int count = Math.Clamp((int)view.ReadDouble(ringBase), 0, NativeProtocol.DrawRingCapacity);
for (int k = 0; k < count; k++)
{
long entry = ringBase + (1 + (long)k * NativeProtocol.DrawEntryDoubles) * 8;
int kind = (int)view.ReadDouble(entry);
long payload = entry + 8;
if (kind == NativeProtocol.CbKindDrawPoly)
DispatchRingDrawPoly(view, payload, addDraw);
else
DispatchRingDraw(view, payload, addDraw);
}
view.Write(ringBase, 0d);
}
private static void DispatchRingDraw(MemoryMappedViewAccessor view, long payload, Action<DrawCommand> addDraw)
{
double ox = view.ReadDouble(payload + 0 * 8);
double oy = view.ReadDouble(payload + 1 * 8);
double oz = view.ReadDouble(payload + 2 * 8);
double zoom = view.ReadDouble(payload + 3 * 8);
double alpha = view.ReadDouble(payload + 4 * 8);
double aspect = view.ReadDouble(payload + 5 * 8);
double antialias = view.ReadDouble(payload + 6 * 8);
double blend = view.ReadDouble(payload + 7 * 8);
try { addDraw(new DrawCommand(ox, oy, oz, zoom, alpha, aspect, null, antialias, blend)); }
catch { }
}
private static void DispatchRingDrawPoly(MemoryMappedViewAccessor view, long payload, Action<DrawCommand> addDraw)
{
var poly = new double[DrawPolyMath.Length];
for (int i = 0; i < DrawPolyMath.Length; i++)
poly[i] = view.ReadDouble(payload + i * 8);
double antialias = view.ReadDouble(payload + DrawPolyMath.Length * 8);
double blend = view.ReadDouble(payload + (DrawPolyMath.Length + 1) * 8);
try { addDraw(new DrawCommand(0d, 0d, 0d, 1d, poly[20], 0d, poly, antialias, blend)); }
catch { }
}
private void ResolveGetObjectCallback(MemoryMappedViewAccessor view, Func<string, int, SceneObjectInfo?> resolveObject)
{
int frame = view.ReadInt32(NativeProtocol.OffCallbackFrame);
int tagLen = Math.Clamp(view.ReadInt32(NativeProtocol.OffCallbackTagLen), 0, NativeProtocol.CallbackTagMax);
view.ReadArray(NativeProtocol.CallbackTagOffset, _callbackTag, 0, tagLen);
string tag = ResolveTag(tagLen);
SceneObjectInfo? info;
try { info = resolveObject(tag, frame); }
catch { info = null; }
if (info is { } value)
{
long result = NativeProtocol.CallbackResultOffset;
view.Write(result + NativeProtocol.CbExist * 8, value.Exist ? 1d : 0d);
view.Write(result + NativeProtocol.CbX * 8, value.X);
view.Write(result + NativeProtocol.CbY * 8, value.Y);
view.Write(result + NativeProtocol.CbZ * 8, value.Z);
view.Write(result + NativeProtocol.CbZoom * 8, value.Zoom);
view.Write(result + NativeProtocol.CbRz * 8, value.Rz);
view.Write(result + NativeProtocol.CbAlpha * 8, value.Alpha);
view.Write(result + NativeProtocol.CbLayer * 8, (double)value.Layer);
view.Write(NativeProtocol.OffCallbackFound, 1);
}
else
{
view.Write(NativeProtocol.OffCallbackFound, 0);
}
}
private void ResolveLoadFigureCallback(
MemoryMappedViewAccessor view,
Func<string, int, double, double, double, (byte[] buffer, int w, int h)> loadFigure)
{
int tagLen = Math.Clamp(view.ReadInt32(NativeProtocol.OffCallbackTagLen), 0, NativeProtocol.CallbackTagMax);
view.ReadArray(NativeProtocol.CallbackTagOffset, _callbackTag, 0, tagLen);
string name = Encoding.UTF8.GetString(_callbackTag, 0, tagLen);
long rOff = NativeProtocol.CallbackResultOffset;
int color = (int)view.ReadDouble(rOff + 0 * 8);
double size = view.ReadDouble(rOff + 1 * 8);
double lineWidth = view.ReadDouble(rOff + 2 * 8);
double aspect = view.ReadDouble(rOff + 3 * 8);
(byte[] buffer, int w, int h) result;
try { result = loadFigure(name, color, size, lineWidth, aspect); }
catch { result = (new byte[4], 1, 1); }
int pixelSize = result.w * result.h * 4;
long capacity = view.Capacity - _pixelOffset;
if (pixelSize > capacity)
{
result = (new byte[4], 1, 1);
pixelSize = 4;
}
view.Write(NativeProtocol.OffLoadResultWidth, result.w);
view.Write(NativeProtocol.OffLoadResultHeight, result.h);
WritePixelRegion(result.buffer, pixelSize);
view.Write(NativeProtocol.OffCallbackFound, 1);
}
private void ResolveLoadTextCallback(
MemoryMappedViewAccessor view,
Func<string, string, double, bool, bool, int, (byte[] buffer, int w, int h)> loadText)
{
int tagLen = Math.Clamp(view.ReadInt32(NativeProtocol.OffCallbackTagLen), 0, NativeProtocol.CallbackTagMax);
view.ReadArray(NativeProtocol.CallbackTagOffset, _callbackTag, 0, tagLen);
string payload = Encoding.UTF8.GetString(_callbackTag, 0, tagLen);
int separator = payload.IndexOf('\0');
string family = separator >= 0 ? payload[..separator] : string.Empty;
string text = separator >= 0 ? payload[(separator + 1)..] : payload;
long rOff = NativeProtocol.CallbackResultOffset;
double size = view.ReadDouble(rOff + 0 * 8);
bool bold = view.ReadDouble(rOff + 1 * 8) != 0;
bool italic = view.ReadDouble(rOff + 2 * 8) != 0;
int color = (int)view.ReadDouble(rOff + 3 * 8);
(byte[] buffer, int w, int h) result;
try { result = loadText(family, text, size, bold, italic, color); }
catch { result = (new byte[4], 1, 1); }
int pixelSize = result.w * result.h * 4;
long capacity = view.Capacity - _pixelOffset;
if (pixelSize > capacity)
{
result = (new byte[4], 1, 1);
pixelSize = 4;
}
view.Write(NativeProtocol.OffLoadResultWidth, result.w);
view.Write(NativeProtocol.OffLoadResultHeight, result.h);
WritePixelRegion(result.buffer, pixelSize);
view.Write(NativeProtocol.OffCallbackFound, 1);
}
private void ResolveLoadImageCallback(
MemoryMappedViewAccessor view,
Func<string, (byte[] buffer, int w, int h)> loadImage)
{
int tagLen = Math.Clamp(view.ReadInt32(NativeProtocol.OffCallbackTagLen), 0, NativeProtocol.CallbackTagMax);
view.ReadArray(NativeProtocol.CallbackTagOffset, _callbackTag, 0, tagLen);
string path = Encoding.UTF8.GetString(_callbackTag, 0, tagLen);
(byte[] buffer, int w, int h) result;
try { result = loadImage(path); }
catch { result = (new byte[4], 1, 1); }
int pixelSize = result.w * result.h * 4;
long capacity = view.Capacity - _pixelOffset;
if (pixelSize > capacity)
{
result = (new byte[4], 1, 1);
pixelSize = 4;
}
view.Write(NativeProtocol.OffLoadResultWidth, result.w);
view.Write(NativeProtocol.OffLoadResultHeight, result.h);
WritePixelRegion(result.buffer, pixelSize);
view.Write(NativeProtocol.OffCallbackFound, 1);
}
private void ResolveLoadMovieCallback(
MemoryMappedViewAccessor view,
Func<string, double, (byte[] buffer, int w, int h)> loadMovie)
{
int tagLen = Math.Clamp(view.ReadInt32(NativeProtocol.OffCallbackTagLen), 0, NativeProtocol.CallbackTagMax);
view.ReadArray(NativeProtocol.CallbackTagOffset, _callbackTag, 0, tagLen);
string path = Encoding.UTF8.GetString(_callbackTag, 0, tagLen);
double time = view.ReadDouble(NativeProtocol.CallbackResultOffset);
(byte[] buffer, int w, int h) result;
try { result = loadMovie(path, time); }
catch { result = (new byte[4], 1, 1); }
int pixelSize = result.w * result.h * 4;
long capacity = view.Capacity - _pixelOffset;
if (pixelSize > capacity)
{
result = (new byte[4], 1, 1);
pixelSize = 4;
}
view.Write(NativeProtocol.OffLoadResultWidth, result.w);
view.Write(NativeProtocol.OffLoadResultHeight, result.h);
WritePixelRegion(result.buffer, pixelSize);
view.Write(NativeProtocol.OffCallbackFound, 1);
}
private void ResolveEffectCallback(MemoryMappedViewAccessor view, Action<string, IReadOnlyList<KeyValuePair<string, object>>> addEffect)
{
int tagLen = Math.Clamp(view.ReadInt32(NativeProtocol.OffCallbackTagLen), 0, NativeProtocol.CallbackTagMax);
view.ReadArray(NativeProtocol.CallbackTagOffset, _callbackTag, 0, tagLen);
var segments = Encoding.UTF8.GetString(_callbackTag, 0, tagLen).Split('\0');
if (segments.Length == 0)
return;
string effectName = segments[0];
var arguments = new List<KeyValuePair<string, object>>();
for (int i = 1; i + 1 < segments.Length; i += 2)
{
string key = segments[i];
string raw = segments[i + 1];
object value;
if (raw.Length > 0 && raw[0] == 'n')
value = double.TryParse(raw.AsSpan(1), System.Globalization.NumberStyles.Float, System.Globalization.CultureInfo.InvariantCulture, out var d) ? d : 0d;
else if (raw.Length > 0 && raw[0] == 'b')
value = raw.Length > 1 && raw[1] == '1';
else if (raw.Length > 0 && raw[0] == 's')
value = raw.Substring(1);
else
value = raw;
arguments.Add(new KeyValuePair<string, object>(key, value));
}
try { addEffect(effectName, arguments); }
catch { }
view.Write(NativeProtocol.OffCallbackFound, 1);
}
private string ResolveTag(int tagLen)
{
if (tagLen == _lastCallbackTagLength &&
_callbackTag.AsSpan(0, tagLen).SequenceEqual(_lastCallbackTag.AsSpan(0, tagLen)))
return _lastCallbackTagText;
_lastCallbackTagText = Encoding.UTF8.GetString(_callbackTag, 0, tagLen);
_callbackTag.AsSpan(0, tagLen).CopyTo(_lastCallbackTag);
_lastCallbackTagLength = tagLen;
return _lastCallbackTagText;
}
private void EnsureWorker(int width, int height, int stringCapacity)
{
long required = NativeProtocol.PixelOffset(stringCapacity) + (long)width * height * 4;
if (_alive && _process is { HasExited: false } && _stringParamsCapacity == stringCapacity && required <= _allocatedSize)
return;
KillWorker();
StartWorker(width, height, stringCapacity);
}
private void StartWorker(int width, int height, int stringCapacity)
{
_stringParamsCapacity = stringCapacity;
_scriptWritten = false;
_pixelOffset = NativeProtocol.PixelOffset(stringCapacity);
long size = Math.Max(NativeProtocol.BufferSize(width, height, stringCapacity), _allocatedSize);
_allocatedSize = size;
string suffix = Guid.NewGuid().ToString("N");
string mapName = "LuaScriptMap_" + suffix;
string workName = "LuaScriptWork_" + suffix;
string doneName = "LuaScriptDone_" + suffix;
_mmf = MemoryMappedFile.CreateNew(mapName, size);
_view = _mmf.CreateViewAccessor();
_view.Write(NativeProtocol.OffMagic, NativeProtocol.Magic);
_workEvent = new EventWaitHandle(false, EventResetMode.AutoReset, workName);
_doneEvent = new EventWaitHandle(false, EventResetMode.AutoReset, doneName);
var psi = new ProcessStartInfo
{
FileName = _luajitPath,
WorkingDirectory = _nativeDir,
UseShellExecute = false,
CreateNoWindow = true,
RedirectStandardError = true,
};
psi.ArgumentList.Add(_workerScript);
psi.ArgumentList.Add(mapName);
psi.ArgumentList.Add(size.ToString());
psi.ArgumentList.Add(workName);
psi.ArgumentList.Add(doneName);
psi.ArgumentList.Add(_shimScript);
psi.ArgumentList.Add(stringCapacity.ToString());
_process = Process.Start(psi);
if (_process is not null)
ProcessJobObject.Assign(_process.Handle);
_alive = _process is not null;
}
private void KillWorker()
{
if (_process is { HasExited: false })
{
try { _process.Kill(entireProcessTree: true); }
catch { }
}
_process?.Dispose();
_process = null;
_view?.Dispose();
_view = null;
_mmf?.Dispose();
_mmf = null;
_workEvent?.Dispose();
_workEvent = null;
_doneEvent?.Dispose();
_doneEvent = null;
_alive = false;
}
public void Dispose()
{
if (_alive && _process is { HasExited: false } && _view is not null && _workEvent is not null)
{
try
{
_view.Write(NativeProtocol.OffCommand, NativeProtocol.CmdShutdown);
_workEvent.Set();
_process.WaitForExit(500);
}
catch { }
}
KillWorker();
}
}
}
+103
ファイルの表示
@@ -0,0 +1,103 @@
using System;
namespace LuaScript.Engine
{
internal static class NativeFieldMap
{
public static void ToFields(AviUtlScriptContext ctx, double[] f)
{
f[NativeProtocol.W] = ctx.ImageWidth;
f[NativeProtocol.H] = ctx.ImageHeight;
f[NativeProtocol.Hw] = ctx.ImageWidth / 2d;
f[NativeProtocol.Hh] = ctx.ImageHeight / 2d;
f[NativeProtocol.Cx] = ctx.ImageWidth / 2d;
f[NativeProtocol.Cy] = ctx.ImageHeight / 2d;
f[NativeProtocol.Cz] = 0d;
f[NativeProtocol.Diagonal] = Math.Sqrt((double)ctx.ImageWidth * ctx.ImageWidth + (double)ctx.ImageHeight * ctx.ImageHeight);
f[NativeProtocol.X] = ctx.X;
f[NativeProtocol.Y] = ctx.Y;
f[NativeProtocol.Z] = ctx.Z;
f[NativeProtocol.Ox] = ctx.Ox;
f[NativeProtocol.Oy] = ctx.Oy;
f[NativeProtocol.Oz] = ctx.Oz;
f[NativeProtocol.Sx] = ctx.Sx;
f[NativeProtocol.Sy] = ctx.Sy;
f[NativeProtocol.Sz] = 1d;
f[NativeProtocol.Zoom] = ctx.Zoom;
f[NativeProtocol.Aspect] = ctx.Aspect;
f[NativeProtocol.Alpha] = ctx.Alpha;
f[NativeProtocol.Rx] = ctx.Rx;
f[NativeProtocol.Ry] = ctx.Ry;
f[NativeProtocol.Rz] = ctx.Rz;
f[NativeProtocol.Rxr] = ctx.RxRad;
f[NativeProtocol.Ryr] = ctx.RyRad;
f[NativeProtocol.Rzr] = ctx.RzRad;
f[NativeProtocol.Track0] = ctx.Track0;
f[NativeProtocol.Track1] = ctx.Track1;
f[NativeProtocol.Track2] = ctx.Track2;
f[NativeProtocol.Track3] = ctx.Track3;
f[NativeProtocol.Slider0] = ctx.Slider0;
f[NativeProtocol.Slider1] = ctx.Slider1;
f[NativeProtocol.Slider2] = ctx.Slider2;
f[NativeProtocol.Slider3] = ctx.Slider3;
f[NativeProtocol.Check0] = ctx.Check0 ? 1d : 0d;
f[NativeProtocol.Check1] = ctx.Check1 ? 1d : 0d;
f[NativeProtocol.Check2] = ctx.Check2 ? 1d : 0d;
f[NativeProtocol.Check3] = ctx.Check3 ? 1d : 0d;
f[NativeProtocol.Color] = ctx.HasColor ? ctx.ColorValue : -1d;
f[NativeProtocol.Time] = ctx.Time;
f[NativeProtocol.Frame] = ctx.Frame;
f[NativeProtocol.TotalFrame] = ctx.TotalFrame;
f[NativeProtocol.TotalTime] = ctx.TotalTime;
f[NativeProtocol.T] = ctx.TotalFrame > 0 ? ctx.Frame / (double)ctx.TotalFrame : 0d;
f[NativeProtocol.Framerate] = ctx.Framerate;
f[NativeProtocol.Layer] = ctx.Layer;
f[NativeProtocol.Index] = ctx.Index;
f[NativeProtocol.Num] = ctx.Num;
f[NativeProtocol.SceneWidth] = ctx.SceneWidth;
f[NativeProtocol.SceneHeight] = ctx.SceneHeight;
f[NativeProtocol.SceneCx] = ctx.SceneWidth / 2d;
f[NativeProtocol.SceneCy] = ctx.SceneHeight / 2d;
f[NativeProtocol.GroupIndex] = ctx.GroupIndex;
f[NativeProtocol.GroupCount] = ctx.GroupCount;
f[NativeProtocol.TimelineTotalFrame] = ctx.TimelineTotalFrame;
f[NativeProtocol.TimelineTotalTime] = ctx.TimelineTotalTime;
f[NativeProtocol.TimeRatio] = ctx.TimeRatio;
f[NativeProtocol.IsSaving] = ctx.IsSaving ? 1d : 0d;
f[NativeProtocol.IsPlaying] = ctx.IsPlaying ? 1d : 0d;
f[NativeProtocol.IsPaused] = ctx.IsPaused ? 1d : 0d;
f[NativeProtocol.TimelineFrame] = ctx.TimelineFrame;
f[NativeProtocol.TimelineTime] = ctx.TimelineTime;
}
public static void FromFields(double[] f, AviUtlScriptContext ctx)
{
ctx.X = f[NativeProtocol.X];
ctx.Y = f[NativeProtocol.Y];
ctx.Z = f[NativeProtocol.Z];
ctx.Ox = f[NativeProtocol.Ox];
ctx.Oy = f[NativeProtocol.Oy];
ctx.Oz = f[NativeProtocol.Oz];
ctx.Alpha = f[NativeProtocol.Alpha];
ctx.ApplyWriteBack(
f[NativeProtocol.Sx],
f[NativeProtocol.Sy],
f[NativeProtocol.Zoom],
f[NativeProtocol.Aspect],
f[NativeProtocol.Rx],
f[NativeProtocol.Ry],
f[NativeProtocol.Rz],
f[NativeProtocol.Rxr],
f[NativeProtocol.Ryr],
f[NativeProtocol.Rzr]);
ctx.DrawStateOverride = f[NativeProtocol.DrawState] switch
{
1d => true,
2d => false,
_ => null,
};
}
}
}
+155
ファイルの表示
@@ -0,0 +1,155 @@
namespace LuaScript.Engine
{
internal static class NativeProtocol
{
public const int Magic = 0x4C4A4954;
public const int CmdRun = 0;
public const int CmdShutdown = 1;
public const int StatusIdle = 0;
public const int StatusOk = 1;
public const int StatusError = 2;
public const int StatusCallback = 3;
public const int OffMagic = 0;
public const int OffCommand = 4;
public const int OffStatus = 8;
public const int OffWidth = 12;
public const int OffHeight = 16;
public const int OffScriptLen = 20;
public const int OffPixelsDirty = 24;
public const int OffErrorLen = 28;
public const int OffCallbackFrame = 32;
public const int OffCallbackTagLen = 36;
public const int OffCallbackFound = 40;
public const int OffCallbackKind = 44;
public const int OffLoadResultWidth = 48;
public const int OffLoadResultHeight = 52;
public const int OffStringParamsLen = 56;
public const int OffScriptVersion = 60;
public const int HeaderSize = 64;
public const int FieldCount = 64;
public const int FieldsOffset = HeaderSize;
public const int ScriptOffset = FieldsOffset + FieldCount * 8;
public const int ScriptMax = 128 * 1024;
public const int ErrorOffset = ScriptOffset + ScriptMax;
public const int ErrorMax = 4 * 1024;
public const int CallbackTagOffset = ErrorOffset + ErrorMax;
public const int CallbackTagMax = 8192;
public const int CallbackResultOffset = CallbackTagOffset + CallbackTagMax;
public const int CallbackResultCount = 8;
public const int StringParamsOffset = CallbackResultOffset + CallbackResultCount * 8;
public const int MinStringParamsCapacity = 64 * 1024;
public const int CbKindGetObject = 0;
public const int CbKindLoadFigure = 1;
public const int CbKindEffect = 2;
public const int CbKindDraw = 3;
public const int CbKindDrawPoly = 4;
public const int CbKindLoadText = 5;
public const int CbKindLoadImage = 6;
public const int CbKindLoadMovie = 7;
public const int CbKindSetAnchor = 8;
public const int CbKindRequestPixels = 9;
public const int CbKindFlushDraws = 10;
public const int CbKindSceneGet = 11;
public const int CbKindSceneSet = 12;
public const int DrawRingCapacity = 4096;
public const int DrawEntryDoubles = 24;
public const int DrawRingDoubles = 1 + DrawRingCapacity * DrawEntryDoubles;
public const long DrawRingBytes = (long)DrawRingDoubles * 8;
public const int CbExist = 0;
public const int CbX = 1;
public const int CbY = 2;
public const int CbZ = 3;
public const int CbZoom = 4;
public const int CbRz = 5;
public const int CbAlpha = 6;
public const int CbLayer = 7;
public static long DrawRingOffset(int stringCapacity) => StringParamsOffset + stringCapacity;
public static long PixelOffset(int stringCapacity) => DrawRingOffset(stringCapacity) + DrawRingBytes;
public const int W = 0;
public const int H = 1;
public const int Hw = 2;
public const int Hh = 3;
public const int Cx = 4;
public const int Cy = 5;
public const int Cz = 6;
public const int Diagonal = 7;
public const int X = 8;
public const int Y = 9;
public const int Z = 10;
public const int Ox = 11;
public const int Oy = 12;
public const int Oz = 13;
public const int Sx = 14;
public const int Sy = 15;
public const int Sz = 16;
public const int Zoom = 17;
public const int Aspect = 18;
public const int Alpha = 19;
public const int Rx = 20;
public const int Ry = 21;
public const int Rz = 22;
public const int Rxr = 23;
public const int Ryr = 24;
public const int Rzr = 25;
public const int Track0 = 26;
public const int Track1 = 27;
public const int Track2 = 28;
public const int Track3 = 29;
public const int Time = 30;
public const int Frame = 31;
public const int TotalFrame = 32;
public const int TotalTime = 33;
public const int T = 34;
public const int Framerate = 35;
public const int Layer = 36;
public const int Index = 37;
public const int Num = 38;
public const int SceneWidth = 39;
public const int SceneHeight = 40;
public const int SceneCx = 41;
public const int SceneCy = 42;
public const int GroupIndex = 43;
public const int GroupCount = 44;
public const int TimelineTotalFrame = 45;
public const int TimelineTotalTime = 46;
public const int TimeRatio = 47;
public const int IsSaving = 48;
public const int IsPlaying = 49;
public const int IsPaused = 50;
public const int TimelineFrame = 51;
public const int TimelineTime = 52;
public const int Check0 = 53;
public const int Check1 = 54;
public const int Check2 = 55;
public const int Check3 = 56;
public const int Color = 57;
public const int Slider0 = 58;
public const int Slider1 = 59;
public const int Slider2 = 60;
public const int Slider3 = 61;
public const int DrawState = 62;
public const int FirstWritableField = X;
public const int LastWritableField = Rzr;
public const int MaxPixelBufferSize = 3840 * 2160 * 4;
public static long BufferSize(int width, int height, int stringCapacity) =>
PixelOffset(stringCapacity) + Math.Max((long)width * height * 4, MaxPixelBufferSize);
}
}
+4
ファイルの表示
@@ -0,0 +1,4 @@
namespace LuaScript.Engine
{
internal delegate void PixelRegionAccess(nint address, long capacity);
}
+103
ファイルの表示
@@ -0,0 +1,103 @@
using System;
using System.Runtime.InteropServices;
namespace LuaScript.Engine
{
internal static class ProcessJobObject
{
private const uint JobObjectExtendedLimitInformation = 9;
private const uint JobObjectLimitKillOnJobClose = 0x2000;
private static readonly nint Handle = Create();
public static void Assign(nint processHandle)
{
if (Handle != nint.Zero && processHandle != nint.Zero)
AssignProcessToJobObject(Handle, processHandle);
}
private static nint Create()
{
nint job = CreateJobObject(nint.Zero, null);
if (job == nint.Zero)
return nint.Zero;
var information = new JobObjectExtendedLimitInformationData
{
BasicLimitInformation = new JobObjectBasicLimitInformationData
{
LimitFlags = JobObjectLimitKillOnJobClose
}
};
int length = Marshal.SizeOf<JobObjectExtendedLimitInformationData>();
nint buffer = Marshal.AllocHGlobal(length);
try
{
Marshal.StructureToPtr(information, buffer, false);
if (!SetInformationJobObject(job, JobObjectExtendedLimitInformation, buffer, (uint)length))
{
CloseHandle(job);
return nint.Zero;
}
}
finally
{
Marshal.FreeHGlobal(buffer);
}
return job;
}
[StructLayout(LayoutKind.Sequential)]
private struct JobObjectBasicLimitInformationData
{
public long PerProcessUserTimeLimit;
public long PerJobUserTimeLimit;
public uint LimitFlags;
public nuint MinimumWorkingSetSize;
public nuint MaximumWorkingSetSize;
public uint ActiveProcessLimit;
public nuint Affinity;
public uint PriorityClass;
public uint SchedulingClass;
}
[StructLayout(LayoutKind.Sequential)]
private struct IoCountersData
{
public ulong ReadOperationCount;
public ulong WriteOperationCount;
public ulong OtherOperationCount;
public ulong ReadTransferCount;
public ulong WriteTransferCount;
public ulong OtherTransferCount;
}
[StructLayout(LayoutKind.Sequential)]
private struct JobObjectExtendedLimitInformationData
{
public JobObjectBasicLimitInformationData BasicLimitInformation;
public IoCountersData IoInfo;
public nuint ProcessMemoryLimit;
public nuint JobMemoryLimit;
public nuint PeakProcessMemoryUsed;
public nuint PeakJobMemoryUsed;
}
[DllImport("kernel32.dll", CharSet = CharSet.Unicode, SetLastError = true)]
private static extern nint CreateJobObject(nint lpJobAttributes, string? lpName);
[DllImport("kernel32.dll", SetLastError = true)]
[return: MarshalAs(UnmanagedType.Bool)]
private static extern bool SetInformationJobObject(nint hJob, uint jobObjectInformationClass, nint lpJobObjectInformation, uint cbJobObjectInformationLength);
[DllImport("kernel32.dll", SetLastError = true)]
[return: MarshalAs(UnmanagedType.Bool)]
private static extern bool AssignProcessToJobObject(nint hJob, nint hProcess);
[DllImport("kernel32.dll", SetLastError = true)]
[return: MarshalAs(UnmanagedType.Bool)]
private static extern bool CloseHandle(nint hObject);
}
}
+98
ファイルの表示
@@ -0,0 +1,98 @@
using System;
namespace LuaScript.Engine
{
internal static class ScriptDirective
{
public static ScriptEngineKind Resolve(string? script) =>
TryGetDirective(script, out var kind) ? kind : ScriptEngineKind.MoonSharp;
public static ScriptEngineKind ResolveAuto(string? script)
{
if (string.IsNullOrEmpty(script))
return ScriptEngineKind.MoonSharp;
return TryGetDirective(script, out var kind) ? kind : ScriptEngineKind.Native;
}
public static bool TryResolveExplicit(string? script, out ScriptEngineKind kind) =>
TryGetDirective(script, out kind);
private static bool TryGetDirective(string? script, out ScriptEngineKind kind)
{
kind = ScriptEngineKind.MoonSharp;
if (string.IsNullOrEmpty(script))
return false;
int index = 0;
int length = script.Length;
while (index < length)
{
int lineStart = index;
while (index < length && script[index] != '\n')
index++;
int lineEnd = index;
if (lineEnd > lineStart && script[lineEnd - 1] == '\r')
lineEnd--;
if (TryParseDirectiveLine(script, lineStart, lineEnd, out kind))
return true;
index++;
}
return false;
}
private static bool TryParseDirectiveLine(string script, int start, int end, out ScriptEngineKind kind)
{
kind = ScriptEngineKind.MoonSharp;
int i = start;
while (i < end && (script[i] == ' ' || script[i] == '\t'))
i++;
if (i + 3 > end || script[i] != '-' || script[i + 1] != '-' || script[i + 2] != '!')
return false;
i += 3;
while (i < end && (script[i] == ' ' || script[i] == '\t'))
i++;
int tokenStart = i;
while (i < end && IsTokenChar(script[i]))
i++;
int tokenEnd = i;
while (i < end && (script[i] == ' ' || script[i] == '\t'))
i++;
if (i != end)
return false;
var token = script.AsSpan(tokenStart, tokenEnd - tokenStart);
if (token.Equals("native", StringComparison.OrdinalIgnoreCase))
{
kind = ScriptEngineKind.Native;
return true;
}
if (token.Equals("gpu", StringComparison.OrdinalIgnoreCase))
{
kind = ScriptEngineKind.Gpu;
return true;
}
if (token.Equals("cpu", StringComparison.OrdinalIgnoreCase))
{
kind = ScriptEngineKind.Cpu;
return true;
}
if (token.Equals("moonsharp", StringComparison.OrdinalIgnoreCase))
{
kind = ScriptEngineKind.MoonSharp;
return true;
}
return false;
}
private static bool IsTokenChar(char c) =>
(c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z');
}
}
+12
ファイルの表示
@@ -0,0 +1,12 @@
using System;
namespace LuaScript.Engine
{
internal enum ScriptEngineKind
{
MoonSharp,
Native,
Gpu,
Cpu,
}
}
+38
ファイルの表示
@@ -0,0 +1,38 @@
using System;
namespace LuaScript
{
internal sealed class FallbackCompositor(
IBufferCompositor primary,
IBufferCompositor fallback,
Action<Exception>? onDegraded = null) : IBufferCompositor, IDisposable
{
private bool _degraded;
public bool IsDegraded => _degraded;
public bool TryCompose(byte[] dst, int dstW, int dstH, byte[] src, int srcW, int srcH, in DrawCommand command)
{
if (!_degraded)
{
try
{
if (primary.TryCompose(dst, dstW, dstH, src, srcW, srcH, command))
return true;
}
catch (Exception ex)
{
_degraded = true;
onDegraded?.Invoke(ex);
}
}
return fallback.TryCompose(dst, dstW, dstH, src, srcW, srcH, command);
}
public void Dispose()
{
(primary as IDisposable)?.Dispose();
(fallback as IDisposable)?.Dispose();
}
}
}
+7
ファイルの表示
@@ -0,0 +1,7 @@
namespace LuaScript
{
internal interface IBufferCompositor
{
bool TryCompose(byte[] dst, int dstW, int dstH, byte[] src, int srcW, int srcH, in DrawCommand command);
}
}
+9
ファイルの表示
@@ -0,0 +1,9 @@
namespace LuaScript
{
internal interface IMediaSourceLoader : IDisposable
{
byte[] RenderText(string text, string fontFamily, double fontSize, bool bold, bool italic, int colorRgb, out int width, out int height);
byte[] DecodeImage(string path, out int width, out int height);
byte[] DecodeMovie(string path, double time, out int width, out int height);
}
}
+7
ファイルの表示
@@ -0,0 +1,7 @@
namespace LuaScript
{
internal interface ISceneObjectResolver
{
bool TryResolve(string tag, int timelineFrame, out SceneObjectInfo info);
}
}
+26
ファイルの表示
@@ -0,0 +1,26 @@
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<TargetFramework>net10.0-windows10.0.19041.0</TargetFramework>
<ImplicitUsings>enable</ImplicitUsings>
<Version>1.13.3</Version>
<Platforms>AnyCPU;x64</Platforms>
<Nullable>enable</Nullable>
<AllowUnsafeBlocks>true</AllowUnsafeBlocks>
</PropertyGroup>
<ItemGroup>
<InternalsVisibleTo Include="LuaScript" />
<InternalsVisibleTo Include="LuaScript.Tests" />
</ItemGroup>
<ItemGroup>
<ProjectReference Include="..\LuaScript.Kernel\LuaScript.Kernel.csproj" />
<ProjectReference Include="..\LuaScript.Compat\LuaScript.Compat.csproj" />
</ItemGroup>
<ItemGroup>
<PackageReference Include="MoonSharp" Version="2.0.0" />
</ItemGroup>
</Project>
+6
ファイルの表示
@@ -0,0 +1,6 @@
using System;
namespace LuaScript
{
internal sealed class LuaScriptCompilationException(string message, Exception? inner = null) : LuaScriptException(message, inner);
}
+931
ファイルの表示
@@ -0,0 +1,931 @@
using LuaScript.Anchor;
using LuaScript.Compat;
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 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<WatchItem> items) { }
public List<DynamicExpression> GetWatchItems() => [];
public void RefreshBreakpoints(IEnumerable<SourceRef> refs) { }
public bool IsPauseRequested() => _token.IsCancellationRequested;
public DebuggerAction GetAction(int ip, SourceRef sourceref)
{
_token.ThrowIfCancellationRequested();
return s_runAction;
}
}
private readonly SemaphoreSlim _workSignal = new(0);
private readonly ManualResetEventSlim _doneSignal = new(false);
private readonly CancellationTokenSource _cts = new();
private readonly Thread _thread;
private readonly CancellationDebugger _debugger = new();
private string _jobCode = string.Empty;
private AviUtlScriptContext? _jobContext;
private LuaScriptException? _jobException;
private volatile bool _disposeRequested;
private readonly List<string> _removalBuffer = [];
private readonly Dictionary<string, DynValue> _options = new(StringComparer.Ordinal);
private readonly Dictionary<string, DynValue> _pixelOptions = new(StringComparer.Ordinal);
private readonly Func<IMediaSourceLoader> _mediaLoaderFactory;
private IMediaSourceLoader? _mediaLoader;
private readonly AviUtlFontState _fontState = 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<string>? _builtinGlobalSnapshot;
private HashSet<string>? _objTableSnapshot;
private HashSet<string>? _sceneTableSnapshot;
private HashSet<string>? _animTableSnapshot;
private HashSet<string>? _ymm4TableSnapshot;
private CancellationToken _activeCancellation;
private AviUtlScriptContext? _activeContext;
internal ExecutionThread(Func<IMediaSourceLoader> mediaLoaderFactory)
{
_mediaLoaderFactory = mediaLoaderFactory;
_activeCancellation = _cts.Token;
_debugger.UpdateToken(_cts.Token);
_thread = new Thread(WorkerLoop)
{
IsBackground = true,
Name = "LuaScriptWorker"
};
_thread.Start();
}
internal ExecutionResult TryExecute(string code, AviUtlScriptContext ctx, int timeoutMs)
{
_jobCode = code;
_jobContext = ctx;
_jobException = null;
_doneSignal.Reset();
_workSignal.Release();
if (_doneSignal.Wait(timeoutMs))
return new ExecutionResult(_jobException, false);
_cts.Cancel();
return new ExecutionResult(null, TimedOut: true);
}
private void WorkerLoop()
{
while (true)
{
_workSignal.Wait();
if (_disposeRequested)
return;
ProcessJob();
_doneSignal.Set();
}
}
private void ProcessJob()
{
var context = _jobContext!;
_activeContext = context;
try
{
EnsureScript();
EnsureScriptIntegrity();
EnsureCompiled(_jobCode);
SetupGlobals(context);
_script!.Call(_compiledChunk!);
ReadBackGlobals(context);
_jobException = null;
}
catch (OperationCanceledException) when (_cts.IsCancellationRequested)
{
_jobException = null;
}
catch (LuaScriptException ex)
{
_jobException = ex;
}
catch (ScriptRuntimeException ex)
{
_jobException = new LuaScriptRuntimeException(ex.DecoratedMessage ?? ex.Message, ex);
}
catch (Exception ex)
{
_jobException = new LuaScriptRuntimeException(ex.Message, ex);
}
finally
{
_activeContext = null;
}
}
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);
AviUtlGlobalRegistrar.RegisterFunctions(script.Globals, CurrentTimeRatio);
_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;
_options.Clear();
_pixelOptions.Clear();
_fontState.Reset();
if (isFirstSetup)
{
var sceneTable = new Table(script);
RegisterSceneCallbacks(sceneTable);
script.Globals["scene"] = sceneTable;
var objTable = new Table(script);
RegisterObjectCallbacks(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);
RegisterSceneCallbacks(sceneTable);
script.Globals["scene"] = sceneTable;
_sceneTable = sceneTable;
_sceneTableSnapshot = null;
}
if (!ReferenceEquals(script.Globals.Get("obj").Table, _objTable))
{
var objTable = new Table(script);
RegisterObjectCallbacks(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!, _objTableSnapshot);
ResetUserTableKeys(_sceneTable!, _sceneTableSnapshot);
ResetUserTableKeys(_animTable!, _animTableSnapshot);
ResetUserTableKeys(_ymm4Table!, _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!["slider0"] = ctx.Slider0;
_objTable!["slider1"] = ctx.Slider1;
_objTable!["slider2"] = ctx.Slider2;
_objTable!["slider3"] = ctx.Slider3;
foreach (var parameter in ctx.StringParameters)
_objTable![parameter.Key] = parameter.Value;
_objTable!["check0"] = ctx.Check0;
_objTable!["check1"] = ctx.Check1;
_objTable!["check2"] = ctx.Check2;
_objTable!["check3"] = ctx.Check3;
if (ctx.HasColor)
script.Globals["color"] = ctx.ColorValue;
_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<string> CaptureGlobalKeys(Script script)
{
var keys = new HashSet<string>(StringComparer.Ordinal);
foreach (var key in script.Globals.Keys)
{
if (key.Type == DataType.String)
keys.Add(key.String);
}
return keys;
}
private static HashSet<string> CaptureTableKeys(Table table)
{
var keys = new HashSet<string>(StringComparer.Ordinal);
foreach (var key in table.Keys)
{
if (key.Type == DataType.String)
keys.Add(key.String);
}
return keys;
}
private void ResetUserTableKeys(Table table, HashSet<string>? snapshot)
{
if (snapshot is null) return;
var buffer = _removalBuffer;
buffer.Clear();
foreach (var key in table.Keys)
{
if (key.Type == DataType.String &&
!snapshot.Contains(key.String))
{
buffer.Add(key.String);
}
}
foreach (var key in buffer)
table[key] = DynValue.Nil;
}
private void ResetUserGlobals(Script script)
{
var buffer = _removalBuffer;
buffer.Clear();
foreach (var key in script.Globals.Keys)
{
if (key.Type == DataType.String &&
!_builtinGlobalSnapshot!.Contains(key.String))
{
buffer.Add(key.String);
}
}
foreach (var key in buffer)
script.Globals[key] = DynValue.Nil;
}
private double CurrentTimeRatio() =>
_activeContext is { TotalTime: > 0d } context ? context.Time / context.TotalTime : 0d;
private void RegisterSceneCallbacks(Table scene) =>
SceneTableRegistrar.RegisterFunctions(scene, GetSceneValue, SetSceneValue);
private SceneValue GetSceneValue(string name)
{
_activeCancellation.ThrowIfCancellationRequested();
return _activeContext?.GetSceneValue(name) ?? SceneValue.Nil;
}
private void SetSceneValue(string name, SceneValue value)
{
_activeCancellation.ThrowIfCancellationRequested();
_activeContext?.SetSceneValue(name, value);
}
private void RegisterObjectCallbacks(Table obj)
{
obj["getobject"] = DynValue.NewCallback((execCtx, args) =>
{
_activeCancellation.ThrowIfCancellationRequested();
if (_activeContext is null || args.Count == 0)
return DynValue.Nil;
var tag = args[0];
if (tag.Type != DataType.String)
return DynValue.Nil;
int frame = _activeContext.TimelineFrame;
if (args.Count >= 2)
{
var frameArg = args[1];
if (frameArg.Type != DataType.Number)
return DynValue.Nil;
frame = (int)frameArg.Number;
}
if (!_activeContext.ResolveObject(tag.String, frame, out var info))
return DynValue.Nil;
return BuildObjectTable(execCtx.GetScript(), info);
});
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);
obj["rand"] = DynValue.NewCallback((_, args) =>
{
_activeCancellation.ThrowIfCancellationRequested();
double frameDefault = _activeContext?.Frame ?? 0d;
double a = args.Count > 0 ? args[0].CastToNumber() ?? 0d : 0d;
double b = args.Count > 1 ? args[1].CastToNumber() ?? 0d : 0d;
double seed = args.Count > 2 ? args[2].CastToNumber() ?? 0d : 0d;
double frame = args.Count > 3 ? args[3].CastToNumber() ?? frameDefault : frameDefault;
return DynValue.NewNumber(AviUtlRandom.Next(a, b, seed, frame));
});
obj["load"] = DynValue.NewCallback((_, args) =>
{
_activeCancellation.ThrowIfCancellationRequested();
if (_activeContext is null || args.Count == 0 || args[0].Type != DataType.String)
return DynValue.Void;
switch (args[0].String)
{
case "figure" when args.Count >= 4:
LoadFigure(
args[1].Type == DataType.String ? args[1].String : string.Empty,
(int)(args[2].CastToNumber() ?? 0d),
args[3].CastToNumber() ?? 0d,
args.Count > 4 ? args[4].CastToNumber() ?? 0d : 0d,
args.Count > 5 ? Math.Clamp(args[5].CastToNumber() ?? 0d, -1d, 1d) : 0d);
break;
case "text":
LoadText(args.Count > 1 && args[1].Type == DataType.String ? args[1].String : string.Empty);
break;
case "image" when args.Count > 1 && args[1].Type == DataType.String:
LoadImage(args[1].String);
break;
case "movie" when args.Count > 1 && args[1].Type == DataType.String:
LoadMovie(
args[1].String,
args.Count > 2 ? args[2].CastToNumber() ?? _activeContext.Time : _activeContext.Time);
break;
}
return DynValue.Void;
});
obj["setfont"] = DynValue.NewCallback((_, args) =>
{
_activeCancellation.ThrowIfCancellationRequested();
_fontState.Apply(
args.Count > 0 ? args[0] : DynValue.Nil,
args.Count > 1 ? args[1] : DynValue.Nil,
args.Count > 2 ? args[2] : DynValue.Nil,
args.Count > 3 ? args[3] : DynValue.Nil);
return DynValue.Void;
});
obj["effect"] = DynValue.NewCallback((_, args) =>
{
_activeCancellation.ThrowIfCancellationRequested();
if (_activeContext is null || args.Count == 0 || args[0].Type != DataType.String)
return DynValue.Void;
string name = args[0].String;
var arguments = new List<KeyValuePair<string, object>>();
for (int i = 1; i + 1 < args.Count; i += 2)
{
if (args[i].Type != DataType.String)
continue;
var value = args[i + 1];
object boxed = value.Type switch
{
DataType.Number => value.Number,
DataType.Boolean => value.Boolean,
DataType.String => value.String,
_ => value.CastToNumber() ?? 0d,
};
arguments.Add(new KeyValuePair<string, object>(args[i].String, boxed));
}
_activeContext.AddEffect(new AviUtlEffectRequest(name, arguments));
return DynValue.Void;
});
obj["draw"] = DynValue.NewCallback((_, args) =>
{
_activeCancellation.ThrowIfCancellationRequested();
if (_activeContext is null)
return DynValue.Void;
double ox = args.Count > 0 ? args[0].CastToNumber() ?? 0d : 0d;
double oy = args.Count > 1 ? args[1].CastToNumber() ?? 0d : 0d;
double oz = args.Count > 2 ? args[2].CastToNumber() ?? 0d : 0d;
double zoom = args.Count > 3 ? args[3].CastToNumber() ?? 1d : 1d;
double alpha = args.Count > 4 ? args[4].CastToNumber() ?? 1d : 1d;
double aspect = args.Count > 5 ? args[5].CastToNumber() ?? 0d : 0d;
_activeContext.SubmitDraw(new DrawCommand(ox, oy, oz, zoom, alpha, aspect, null, CurrentAntialias(), CurrentBlend()));
return DynValue.Void;
});
obj["drawpoly"] = DynValue.NewCallback((_, args) =>
{
_activeCancellation.ThrowIfCancellationRequested();
if (_activeContext is null || args.Count < 12)
return DynValue.Void;
var poly = new double[DrawPolyMath.Length];
for (int i = 0; i < 12; i++)
poly[i] = args[i].CastToNumber() ?? 0d;
if (args.Count >= 20)
{
for (int i = 0; i < 8; i++)
poly[12 + i] = args[12 + i].CastToNumber() ?? 0d;
}
else
{
double w = _activeContext.ImageWidth;
double h = _activeContext.ImageHeight;
poly[12] = 0d; poly[13] = 0d;
poly[14] = w; poly[15] = 0d;
poly[16] = w; poly[17] = h;
poly[18] = 0d; poly[19] = h;
}
poly[20] = args.Count switch
{
13 => args[12].CastToNumber() ?? 1d,
>= 21 => args[20].CastToNumber() ?? 1d,
_ => 1d,
};
_activeContext.SubmitDraw(new DrawCommand(0d, 0d, 0d, 1d, poly[20], 0d, poly, CurrentAntialias(), CurrentBlend()));
return DynValue.Void;
});
obj["copybuffer"] = DynValue.NewCallback((_, args) =>
{
_activeCancellation.ThrowIfCancellationRequested();
if (_activeContext is null || args.Count < 2 ||
args[0].Type != DataType.String || args[1].Type != DataType.String)
return DynValue.Void;
if (_activeContext.CopyBuffer(args[0].String, args[1].String))
RefreshObjDimensions();
return DynValue.Void;
});
obj["getvalue"] = DynValue.NewCallback((_, args) =>
{
_activeCancellation.ThrowIfCancellationRequested();
if (args.Count == 0 || args[0].Type != DataType.String)
return DynValue.NewNumber(0d);
var value = _objTable!.Get(args[0].String);
return value.Type == DataType.Number ? value : DynValue.NewNumber(0d);
});
obj["setanchor"] = DynValue.NewCallback((_, args) =>
{
_activeCancellation.ThrowIfCancellationRequested();
if (_activeContext is null || _script is null || args.Count < 2 || args[0].Type != DataType.String)
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);
var connection = AnchorConnection.None;
bool is3D = false;
for (int i = 2; i < args.Count; i++)
{
if (args[i].Type == DataType.String)
AnchorSupport.ApplyOption(args[i].String, ref connection, ref is3D);
}
int stride = is3D ? 3 : 2;
var table = new Table(_script);
var source = _activeContext.AnchorSource;
for (int i = 0; i < count; i++)
{
AnchorSupport.ResolvePosition(source, anchorName, i, out double x, out double y, out double z);
table.Set(i * stride + 1, DynValue.NewNumber(x));
table.Set(i * stride + 2, DynValue.NewNumber(y));
if (is3D)
table.Set(i * stride + 3, DynValue.NewNumber(z));
}
_script.Globals.Set(anchorName, DynValue.NewTable(table));
_activeContext.AddAnchorRequest(new AnchorRequestData(anchorName, count, connection, is3D));
return DynValue.NewNumber(count);
});
obj["setoption"] = DynValue.NewCallback((_, args) =>
{
_activeCancellation.ThrowIfCancellationRequested();
if (args.Count == 0 || args[0].Type != DataType.String)
return DynValue.Void;
var name = args[0].String;
var value = args.Count > 1 ? args[1] : DynValue.True;
_options[name] = value;
if (name == "draw_state" && _activeContext is not null)
_activeContext.DrawStateOverride = value.Type == DataType.Boolean
? value.Boolean
: (value.CastToNumber() ?? 0d) != 0d;
if (name == "drawtarget" && _activeContext is not null)
{
if (value.Type == DataType.String && value.String == "tempbuffer")
{
bool hasSize = args.Count > 3;
int w = hasSize ? (int)(args[2].CastToNumber() ?? 0d) : 0;
int h = hasSize ? (int)(args[3].CastToNumber() ?? 0d) : 0;
_activeContext.SetDrawTarget(true, w, h, hasSize);
}
else
{
_activeContext.SetDrawTarget(false, 0, 0, false);
}
}
return DynValue.Void;
});
obj["getoption"] = DynValue.NewCallback((_, args) =>
{
_activeCancellation.ThrowIfCancellationRequested();
if (args.Count == 0 || args[0].Type != DataType.String)
return DynValue.NewNumber(0d);
return _options.TryGetValue(args[0].String, out var value) ? value : DynValue.NewNumber(0d);
});
obj["pixeloption"] = DynValue.NewCallback((_, args) =>
{
_activeCancellation.ThrowIfCancellationRequested();
if (args.Count == 0 || args[0].Type != DataType.String)
return DynValue.Void;
_pixelOptions[args[0].String] = args.Count > 1 ? args[1] : DynValue.True;
return DynValue.Void;
});
}
private double CurrentAntialias() =>
_options.TryGetValue("antialias", out var value) && value.Type == DataType.Number
? value.Number
: 1d;
private double CurrentBlend() =>
_options.TryGetValue("blend", out var value) && value.Type == DataType.Number
? value.Number
: 0d;
private void LoadFigure(string name, int color, double size, double line, double aspect)
{
int boundingSize = Math.Max(1, (int)Math.Round(size));
double width = aspect >= 0d ? boundingSize * (1d - aspect) : boundingSize;
double height = aspect <= 0d ? boundingSize * (1d + aspect) : boundingSize;
int w = Math.Max(1, (int)Math.Round(width));
int h = Math.Max(1, (int)Math.Round(height));
var buffer = FigureRenderer.Render(name, w, h, color, line);
_activeContext!.ReplaceBuffer(buffer, w, h);
RefreshObjDimensions();
}
private void LoadText(string text)
{
_mediaLoader ??= _mediaLoaderFactory();
var buffer = _mediaLoader.RenderText(
text, _fontState.Family, _fontState.Size, _fontState.Bold, _fontState.Italic, _fontState.Color,
out int w, out int h);
_activeContext!.ReplaceBuffer(buffer, w, h);
RefreshObjDimensions();
}
private void LoadImage(string path)
{
_mediaLoader ??= _mediaLoaderFactory();
var buffer = _mediaLoader.DecodeImage(path, out int w, out int h);
_activeContext!.ReplaceBuffer(buffer, w, h);
RefreshObjDimensions();
}
private void LoadMovie(string path, double time)
{
_mediaLoader ??= _mediaLoaderFactory();
var buffer = _mediaLoader.DecodeMovie(path, time, out int w, out int h);
_activeContext!.ReplaceBuffer(buffer, w, h);
RefreshObjDimensions();
}
private void RefreshObjDimensions()
{
int w = _activeContext!.ImageWidth;
int h = _activeContext.ImageHeight;
var obj = _objTable!;
obj["w"] = w;
obj["h"] = h;
obj["hw"] = w / 2d;
obj["hh"] = h / 2d;
obj["cx"] = w / 2d;
obj["cy"] = h / 2d;
obj["cz"] = 0d;
obj["diagonal"] = Math.Sqrt((double)w * w + (double)h * h);
}
private static DynValue BuildObjectTable(Script script, SceneObjectInfo info)
{
var table = new Table(script)
{
["exist"] = info.Exist,
["x"] = info.X,
["y"] = info.Y,
["z"] = info.Z,
["zoom"] = info.Zoom,
["sx"] = info.Zoom,
["sy"] = info.Zoom,
["rx"] = 0d,
["ry"] = 0d,
["rz"] = info.Rz,
["rxr"] = 0d,
["ryr"] = 0d,
["rzr"] = info.Rz * Math.PI / 180d,
["alpha"] = info.Alpha,
["layer"] = info.Layer,
};
return DynValue.NewTable(table);
}
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;
ctx.ApplyWriteBack(
_objTable.Get("sx").CastToNumber() ?? ctx.Sx,
_objTable.Get("sy").CastToNumber() ?? ctx.Sy,
_objTable.Get("zoom").CastToNumber() ?? ctx.Zoom,
_objTable.Get("aspect").CastToNumber() ?? ctx.Aspect,
_objTable.Get("rx").CastToNumber() ?? ctx.Rx,
_objTable.Get("ry").CastToNumber() ?? ctx.Ry,
_objTable.Get("rz").CastToNumber() ?? ctx.Rz,
_objTable.Get("rxr").CastToNumber() ?? ctx.RxRad,
_objTable.Get("ryr").CastToNumber() ?? ctx.RyRad,
_objTable.Get("rzr").CastToNumber() ?? ctx.RzRad);
}
public void Dispose()
{
_disposeRequested = true;
_workSignal.Release();
_thread.Join();
_mediaLoader?.Dispose();
_cts.Cancel();
_cts.Dispose();
_workSignal.Dispose();
_doneSignal.Dispose();
}
internal void AbandonAsync()
{
_disposeRequested = true;
_workSignal.Release();
ThreadPool.QueueUserWorkItem(_ =>
{
_thread.Join();
_mediaLoader?.Dispose();
_cts.Dispose();
_workSignal.Dispose();
_doneSignal.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<PixelDataProxy>();
}
private readonly Func<IMediaSourceLoader> _mediaLoaderFactory;
private ExecutionThread _executionThread;
private bool _disposed;
internal LuaScriptEngine(Func<IMediaSourceLoader> mediaLoaderFactory)
{
_mediaLoaderFactory = mediaLoaderFactory;
_executionThread = new ExecutionThread(mediaLoaderFactory);
}
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(_mediaLoaderFactory);
stale.AbandonAsync();
throw new LuaScriptTimeoutException(
$"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();
}
}
}
+6
ファイルの表示
@@ -0,0 +1,6 @@
using System;
namespace LuaScript
{
internal abstract class LuaScriptException(string message, Exception? inner = null) : Exception(message, inner);
}
+6
ファイルの表示
@@ -0,0 +1,6 @@
using System;
namespace LuaScript
{
internal sealed class LuaScriptRuntimeException(string message, Exception? inner = null) : LuaScriptException(message, inner);
}
+6
ファイルの表示
@@ -0,0 +1,6 @@
using System;
namespace LuaScript
{
internal sealed class LuaScriptTimeoutException(string message, Exception? inner = null) : LuaScriptException(message, inner);
}
+88
ファイルの表示
@@ -0,0 +1,88 @@
using System.Diagnostics;
using MoonSharp.Interpreter;
namespace LuaScript
{
[MoonSharpUserData]
internal sealed class PixelDataProxy(AviUtlScriptContext ctx)
{
public int width => ctx.ImageWidth;
public int height => ctx.ImageHeight;
public unsafe double get(int index)
{
ctx.EnsurePixelBuffer();
var buf = ctx.GetPixelBuffer();
if (buf is null) return 0d;
int zeroBasedIndex = index - 1;
if ((uint)zeroBasedIndex >= (uint)ctx.TotalChannels) return 0d;
int pixelIndex = Math.DivRem(zeroBasedIndex, 4, out int channel);
fixed (byte* p = buf)
{
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 => 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()
};
}
}
public unsafe void set(int index, double value)
{
ctx.EnsurePixelBuffer();
var buf = ctx.GetPixelBuffer();
if (buf is null) return;
int zeroBasedIndex = index - 1;
if ((uint)zeroBasedIndex >= (uint)ctx.TotalChannels) return;
ctx.MarkPixelsDirty();
int pixelIndex = Math.DivRem(zeroBasedIndex, 4, out int channel);
double clamped = Math.Clamp(value, 0d, 255d);
fixed (byte* p = buf)
{
byte* pixel = p + pixelIndex * 4;
if (channel == 3)
{
double oldA = pixel[3];
double newA = clamped;
if (oldA > 0d && newA > 0d)
{
double factor = newA / oldA;
pixel[0] = (byte)Math.Clamp(pixel[0] * factor, 0d, 255d);
pixel[1] = (byte)Math.Clamp(pixel[1] * factor, 0d, 255d);
pixel[2] = (byte)Math.Clamp(pixel[2] * factor, 0d, 255d);
}
else if (newA <= 0d)
{
pixel[0] = pixel[1] = pixel[2] = 0;
}
pixel[3] = (byte)newA;
}
else
{
double a = pixel[3];
double premultiplied = clamped * (a / 255d);
int byteOffset = channel switch { 0 => 2, 1 => 1, 2 => 0, _ => throw new UnreachableException() };
pixel[byteOffset] = (byte)Math.Clamp(premultiplied, 0d, 255d);
}
}
}
}
}
+13
ファイルの表示
@@ -0,0 +1,13 @@
namespace LuaScript
{
internal readonly record struct SceneObjectInfo(
string Tag,
bool Exist,
double X,
double Y,
double Z,
double Zoom,
double Rz,
double Alpha,
int Layer);
}
+7
ファイルの表示
@@ -0,0 +1,7 @@
namespace LuaScript
{
internal readonly record struct SceneObjectQuery(
string Tag,
int Frame,
SceneObjectInfo? Result);
}
+197
ファイルの表示
@@ -0,0 +1,197 @@
using System.Collections.Concurrent;
using System.Runtime.CompilerServices;
using System.Text;
namespace LuaScript
{
internal enum SceneValueKind
{
Nil = 0,
Number = 1,
String = 2,
Boolean = 3,
}
internal readonly record struct SceneValue(SceneValueKind Kind, double Number, string? Text)
{
public static readonly SceneValue Nil = new(SceneValueKind.Nil, 0d, null);
public static SceneValue FromNumber(double value) => new(SceneValueKind.Number, value, null);
public static SceneValue FromBoolean(bool value) => new(SceneValueKind.Boolean, value ? 1d : 0d, null);
public static SceneValue FromString(string value) => new(SceneValueKind.String, 0d, value);
}
internal readonly record struct SceneValueQuery(string Name, SceneValue Result);
internal sealed class SceneSharedValues
{
public const int MaxNameBytes = 4095;
public const int MaxTextBytes = 4095;
public const int MaxEntries = 4096;
public const long MaxHistoryCostBytes = 16 * 1024 * 1024;
private const long VersionBaseCost = 64;
private readonly record struct SceneVersion(long Frame, int Layer, SceneValue Value);
private static readonly ConditionalWeakTable<object, ConcurrentDictionary<string, SceneSharedValues>> s_scopes = new();
private readonly Dictionary<string, List<SceneVersion>> _names = new(StringComparer.Ordinal);
private readonly object _gate = new();
private long _historyCost;
public static SceneSharedValues ForScene(object scope, string sceneId) =>
s_scopes.GetOrCreateValue(scope).GetOrAdd(sceneId, static _ => new SceneSharedValues());
public SceneValue Read(long generation, string name)
{
lock (_gate)
{
if (!_names.TryGetValue(name, out var versions))
return SceneValue.Nil;
int index = LatestBefore(versions, generation);
return index >= 0 ? versions[index].Value : SceneValue.Nil;
}
}
public void Publish(long generation, int layer, Dictionary<string, SceneValue> writes)
{
lock (_gate)
{
foreach (var pair in writes)
Upsert(generation, layer, pair.Key, pair.Value);
EnforceHistoryBudget();
}
}
private void Upsert(long generation, int layer, string name, SceneValue value)
{
if (!_names.TryGetValue(name, out var versions))
{
if (_names.Count >= MaxEntries)
return;
if (value == SceneValue.Nil)
return;
_names[name] = [new SceneVersion(generation, layer, value)];
return;
}
int index = LatestBefore(versions, generation + 1);
if (index >= 0 && versions[index].Frame == generation)
{
if (layer < versions[index].Layer)
return;
if (index < versions.Count - 1)
_historyCost += CostOf(value) - CostOf(versions[index].Value);
versions[index] = new SceneVersion(generation, layer, value);
return;
}
var previous = index >= 0 ? versions[index].Value : SceneValue.Nil;
if (value == previous)
return;
versions.Insert(index + 1, new SceneVersion(generation, layer, value));
if (index + 1 < versions.Count - 1)
_historyCost += CostOf(value);
else if (versions.Count > 1)
_historyCost += CostOf(versions[^2].Value);
}
private void EnforceHistoryBudget()
{
while (_historyCost > MaxHistoryCostBytes)
{
List<SceneVersion>? oldest = null;
string oldestName = string.Empty;
foreach (var pair in _names)
{
var versions = pair.Value;
if (versions.Count < 2)
continue;
if (oldest is null ||
versions[0].Frame < oldest[0].Frame ||
(versions[0].Frame == oldest[0].Frame && string.CompareOrdinal(pair.Key, oldestName) < 0))
{
oldest = versions;
oldestName = pair.Key;
}
}
if (oldest is null)
return;
_historyCost -= CostOf(oldest[0].Value);
oldest.RemoveAt(0);
}
}
private static long CostOf(SceneValue value) =>
VersionBaseCost + (value.Text is null ? 0 : value.Text.Length * 2L);
private static int LatestBefore(List<SceneVersion> versions, long generation)
{
int low = 0;
int high = versions.Count - 1;
int result = -1;
while (low <= high)
{
int mid = (low + high) >> 1;
if (versions[mid].Frame < generation)
{
result = mid;
low = mid + 1;
}
else
{
high = mid - 1;
}
}
return result;
}
public static string NormalizeName(string name) => TruncateUtf8(name, MaxNameBytes);
public static SceneValue NormalizeValue(SceneValue value) =>
value.Kind == SceneValueKind.String
? SceneValue.FromString(TruncateUtf8(value.Text ?? string.Empty, MaxTextBytes))
: value;
private static string TruncateUtf8(string text, int maxBytes)
{
if (text.Length <= maxBytes / 3 || Encoding.UTF8.GetByteCount(text) <= maxBytes)
return text;
int bytes = 0;
int length = 0;
while (length < text.Length)
{
char c = text[length];
int size;
int step = 1;
if (char.IsHighSurrogate(c) && length + 1 < text.Length && char.IsLowSurrogate(text[length + 1]))
{
size = 4;
step = 2;
}
else if (c < 0x80)
{
size = 1;
}
else if (c < 0x800)
{
size = 2;
}
else
{
size = 3;
}
if (bytes + size > maxBytes)
break;
bytes += size;
length += step;
}
return text[..length];
}
}
}
+54
ファイルの表示
@@ -0,0 +1,54 @@
using MoonSharp.Interpreter;
namespace LuaScript
{
internal static class SceneTableRegistrar
{
internal static void RegisterFunctions(Table scene, Func<string, SceneValue> getValue, Action<string, SceneValue> setValue)
{
scene["set"] = DynValue.NewCallback((_, args) =>
{
if (args.Count == 0 || args[0].Type != DataType.String)
return DynValue.Void;
var value = args.Count > 1 ? args[1] : DynValue.Nil;
SceneValue stored;
switch (value.Type)
{
case DataType.Number:
stored = SceneValue.FromNumber(value.Number);
break;
case DataType.String:
stored = SceneValue.FromString(value.String);
break;
case DataType.Boolean:
stored = SceneValue.FromBoolean(value.Boolean);
break;
case DataType.Nil:
case DataType.Void:
stored = SceneValue.Nil;
break;
default:
return DynValue.Void;
}
setValue(args[0].String, stored);
return DynValue.Void;
});
scene["get"] = DynValue.NewCallback((_, args) =>
{
if (args.Count == 0 || args[0].Type != DataType.String)
return DynValue.Nil;
var value = getValue(args[0].String);
return value.Kind switch
{
SceneValueKind.Number => DynValue.NewNumber(value.Number),
SceneValueKind.String => DynValue.NewString(value.Text ?? string.Empty),
SceneValueKind.Boolean => value.Number != 0d ? DynValue.True : DynValue.False,
_ => DynValue.Nil,
};
});
}
}
}
+69
ファイルの表示
@@ -0,0 +1,69 @@
namespace LuaScript
{
internal sealed class SceneValueSession
{
private readonly Dictionary<string, SceneValue> _writes = new(StringComparer.Ordinal);
private readonly Dictionary<string, SceneValue> _reads = new(StringComparer.Ordinal);
private readonly List<SceneValueQuery> _queries = [];
private SceneSharedValues? _store;
private object _scope = new();
private string _sceneId = string.Empty;
private long _generation;
private int _layer;
public bool HasWrites => _writes.Count > 0;
public IReadOnlyList<SceneValueQuery> Queries => _queries;
public void Begin(object scope, string sceneId, long generation, int layer)
{
if (!ReferenceEquals(_scope, scope) || !string.Equals(_sceneId, sceneId, StringComparison.Ordinal))
{
_store = null;
_scope = scope;
_sceneId = sceneId;
}
_generation = generation;
_layer = layer;
_writes.Clear();
_reads.Clear();
_queries.Clear();
}
public SceneValue Get(string name)
{
name = SceneSharedValues.NormalizeName(name);
if (_writes.TryGetValue(name, out var written))
return written;
if (_reads.TryGetValue(name, out var cached))
return cached;
var value = Store.Read(_generation, name);
_reads[name] = value;
_queries.Add(new SceneValueQuery(name, value));
return value;
}
public void Set(string name, SceneValue value)
{
name = SceneSharedValues.NormalizeName(name);
value = SceneSharedValues.NormalizeValue(value);
if (value.Kind != SceneValueKind.Nil &&
!_writes.ContainsKey(name) &&
_writes.Count >= SceneSharedValues.MaxEntries)
{
return;
}
_writes[name] = value;
}
public void Publish()
{
if (_writes.Count == 0)
return;
Store.Publish(_generation, _layer, _writes);
}
private SceneSharedValues Store => _store ??= SceneSharedValues.ForScene(_scope, _sceneId);
}
}
+154
ファイルの表示
@@ -0,0 +1,154 @@
using System;
using System.Numerics;
namespace LuaScript
{
internal sealed class SoftwareCompositor : IBufferCompositor
{
public static readonly SoftwareCompositor Instance = new();
private SoftwareCompositor()
{
}
public bool TryCompose(byte[] dst, int dstW, int dstH, byte[] src, int srcW, int srcH, in DrawCommand command)
{
bool linear = command.Antialias != 0d;
if (command.Poly is { } poly)
DrawPolyInto(dst, dstW, dstH, src, srcW, srcH, poly, command.Alpha, linear);
else
DrawInto(dst, dstW, dstH, src, srcW, srcH, command.Ox, command.Oy, command.Zoom, command.Aspect, command.Alpha, linear);
return true;
}
public static void DrawInto(
byte[] dst, int dstW, int dstH,
byte[] src, int srcW, int srcH,
double ox, double oy, double zoom, double aspect, double alpha, bool linear)
{
if (srcW <= 0 || srcH <= 0 || dstW <= 0 || dstH <= 0)
return;
double clampedAspect = Math.Clamp(aspect, -1d, 1d);
double zx = zoom * (1d + clampedAspect);
double zy = zoom * (1d - clampedAspect);
if (zx == 0d || zy == 0d)
return;
double ka = Math.Clamp(alpha, 0d, 1d);
if (ka <= 0d)
return;
double halfW = srcW * 0.5;
double halfH = srcH * 0.5;
double spanX = Math.Abs(halfW * zx);
double spanY = Math.Abs(halfH * zy);
int x0 = Math.Max(0, (int)Math.Floor(ox - spanX));
int x1 = Math.Min(dstW - 1, (int)Math.Ceiling(ox + spanX));
int y0 = Math.Max(0, (int)Math.Floor(oy - spanY));
int y1 = Math.Min(dstH - 1, (int)Math.Ceiling(oy + spanY));
for (int py = y0; py <= y1; py++)
{
for (int px = x0; px <= x1; px++)
{
double u = (px + 0.5 - ox) / zx + halfW;
double v = (py + 0.5 - oy) / zy + halfH;
if (u < 0d || u >= srcW || v < 0d || v >= srcH)
continue;
Sample(src, srcW, srcH, u, v, linear, out double sb, out double sg, out double sr, out double sa);
CompositeOver(dst, (py * dstW + px) * 4, sb * ka, sg * ka, sr * ka, sa * ka);
}
}
}
public static void DrawPolyInto(
byte[] dst, int dstW, int dstH,
byte[] src, int srcW, int srcH,
double[] poly, double alpha, bool linear)
{
if (srcW <= 0 || srcH <= 0 || dstW <= 0 || dstH <= 0)
return;
if (!DrawPolyMath.TrySolveAffine(poly, out var forward))
return;
if (!Matrix3x2.Invert(forward, out var inverse))
return;
double ka = Math.Clamp(alpha, 0d, 1d);
if (ka <= 0d)
return;
DrawPolyMath.Bounds(poly, out double minX, out double minY, out double maxX, out double maxY);
int x0 = Math.Max(0, (int)Math.Floor(minX));
int x1 = Math.Min(dstW - 1, (int)Math.Ceiling(maxX));
int y0 = Math.Max(0, (int)Math.Floor(minY));
int y1 = Math.Min(dstH - 1, (int)Math.Ceiling(maxY));
for (int py = y0; py <= y1; py++)
{
for (int px = x0; px <= x1; px++)
{
var uv = Vector2.Transform(new Vector2(px + 0.5f, py + 0.5f), inverse);
double u = uv.X;
double v = uv.Y;
if (u < 0d || u >= srcW || v < 0d || v >= srcH)
continue;
Sample(src, srcW, srcH, u, v, linear, out double sb, out double sg, out double sr, out double sa);
CompositeOver(dst, (py * dstW + px) * 4, sb * ka, sg * ka, sr * ka, sa * ka);
}
}
}
private static void Sample(byte[] src, int srcW, int srcH, double u, double v, bool linear,
out double b, out double g, out double r, out double a)
{
if (!linear)
{
int su = Math.Clamp((int)Math.Floor(u), 0, srcW - 1);
int sv = Math.Clamp((int)Math.Floor(v), 0, srcH - 1);
int si = (sv * srcW + su) * 4;
b = src[si];
g = src[si + 1];
r = src[si + 2];
a = src[si + 3];
return;
}
double fx = u - 0.5;
double fy = v - 0.5;
int x0 = (int)Math.Floor(fx);
int y0 = (int)Math.Floor(fy);
double tx = fx - x0;
double ty = fy - y0;
b = g = r = a = 0d;
for (int j = 0; j < 2; j++)
{
int sy = Math.Clamp(y0 + j, 0, srcH - 1);
double wy = j == 0 ? 1d - ty : ty;
for (int i = 0; i < 2; i++)
{
int sx = Math.Clamp(x0 + i, 0, srcW - 1);
double w = wy * (i == 0 ? 1d - tx : tx);
int si = (sy * srcW + sx) * 4;
b += src[si] * w;
g += src[si + 1] * w;
r += src[si + 2] * w;
a += src[si + 3] * w;
}
}
}
private static void CompositeOver(byte[] dst, int di, double sb, double sg, double sr, double sa)
{
double inv = 1d - sa / 255d;
dst[di] = (byte)Math.Clamp(sb + dst[di] * inv, 0d, 255d);
dst[di + 1] = (byte)Math.Clamp(sg + dst[di + 1] * inv, 0d, 255d);
dst[di + 2] = (byte)Math.Clamp(sr + dst[di + 2] * inv, 0d, 255d);
dst[di + 3] = (byte)Math.Clamp(sa + dst[di + 3] * inv, 0d, 255d);
}
}
}
+23
ファイルの表示
@@ -0,0 +1,23 @@
using System;
using System.Threading;
namespace LuaScript
{
internal sealed class SynchronizedCompositor(IBufferCompositor inner, SemaphoreSlim gate) : IBufferCompositor, IDisposable
{
public bool TryCompose(byte[] dst, int dstW, int dstH, byte[] src, int srcW, int srcH, in DrawCommand command)
{
gate.Wait();
try
{
return inner.TryCompose(dst, dstW, dstH, src, srcW, srcH, command);
}
finally
{
gate.Release();
}
}
public void Dispose() => (inner as IDisposable)?.Dispose();
}
}
+21
ファイルの表示
@@ -0,0 +1,21 @@
using MoonSharp.Interpreter;
namespace LuaScript
{
internal static class Ymm4TableRegistrar
{
internal static void UpdateVariables(Table ymm4, AviUtlScriptContext ctx)
{
ymm4["group_index"] = ctx.GroupIndex;
ymm4["group_count"] = ctx.GroupCount;
ymm4["group_ratio"] = ctx.GroupCount > 0 ? ctx.GroupIndex / (double)ctx.GroupCount : 0d;
ymm4["timeline_totalframe"] = ctx.TimelineTotalFrame;
ymm4["timeline_totaltime"] = ctx.TimelineTotalTime;
ymm4["is_saving"] = ctx.IsSaving;
ymm4["time_ratio"] = ctx.TimeRatio;
ymm4["is_playing"] = ctx.IsPlaying;
ymm4["is_paused"] = ctx.IsPaused;
ymm4["scene_id"] = ctx.SceneId;
}
}
}