From 6e29bf08b0959015d357bc10a3ffdf3fbb4dd1db Mon Sep 17 00:00:00 2001 From: routersys Date: Fri, 26 Jun 2026 20:25:58 +0900 Subject: [PATCH] =?UTF-8?q?=E6=AF=8E=E3=83=95=E3=83=AC=E3=83=BC=E3=83=A0?= =?UTF-8?q?=E5=87=A6=E7=90=86=E3=81=AE=E3=82=A2=E3=83=AD=E3=82=B1=E3=83=BC?= =?UTF-8?q?=E3=82=B7=E3=83=A7=E3=83=B3=E3=82=92=E5=89=8A=E6=B8=9B=E3=81=97?= =?UTF-8?q?=E5=8B=95=E7=94=BB=E5=87=BA=E5=8A=9B=E3=82=92=E9=AB=98=E9=80=9F?= =?UTF-8?q?=E5=8C=96?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- LuaScript/AviUtlScriptContext.cs | 61 +++++------ LuaScript/LuaScriptEffectProcessor.cs | 140 +++++++++++++++++--------- LuaScript/LuaScriptEngine.cs | 125 +++++++++++------------ LuaScript/LuaScriptExceptions.cs | 2 + 4 files changed, 187 insertions(+), 141 deletions(-) diff --git a/LuaScript/AviUtlScriptContext.cs b/LuaScript/AviUtlScriptContext.cs index bfdac0a..2b82c38 100644 --- a/LuaScript/AviUtlScriptContext.cs +++ b/LuaScript/AviUtlScriptContext.cs @@ -2,12 +2,12 @@ namespace LuaScript { internal sealed class AviUtlScriptContext { - public bool IsPlaying { get; init; } - public bool IsPaused { get; init; } - public string SceneId { get; init; } = string.Empty; + public bool IsPlaying { get; set; } + public bool IsPaused { get; set; } + public string SceneId { get; set; } = string.Empty; - public int ImageWidth { get; init; } - public int ImageHeight { get; init; } + public int ImageWidth { get; set; } + public int ImageHeight { get; set; } public double X { get; set; } public double Y { get; set; } @@ -24,25 +24,25 @@ namespace LuaScript public double Ry { get; set; } public double Rz { get; set; } - public double Track0 { get; init; } - public double Track1 { get; init; } - public double Track2 { get; init; } - public double Track3 { get; init; } + public double Track0 { get; set; } + public double Track1 { get; set; } + public double Track2 { get; set; } + public double Track3 { get; set; } - public double Time { get; init; } - public int Frame { get; init; } - public int TotalFrame { get; init; } - public double TotalTime { get; init; } - public int Framerate { get; init; } - public int TimelineFrame { get; init; } - public double TimelineTime { get; init; } - public int SceneWidth { get; init; } - public int SceneHeight { get; init; } - public int Layer { get; init; } - public int Index { get; init; } - public int Num { get; init; } + public double 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 SceneObjectResolver? Resolver { get; init; } + public Func? ResolverProvider { get; set; } private readonly List _objectQueries = []; @@ -52,12 +52,12 @@ namespace LuaScript public double RyRad => Ry * Math.PI / 180d; public double RzRad => Rz * Math.PI / 180d; - public int GroupIndex { get; init; } - public int GroupCount { get; init; } - public int TimelineTotalFrame { get; init; } - public double TimelineTotalTime { get; init; } - public bool IsSaving { get; init; } - public double TimeRatio { get; init; } + 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? _pixelLoader; private byte[]? _pixelBuffer; @@ -68,6 +68,8 @@ namespace LuaScript internal int TotalChannels => ImageWidth * ImageHeight * 4; + internal void ClearQueries() => _objectQueries.Clear(); + internal void SetPixelLoader(Func loader) { _pixelLoader = loader; @@ -89,7 +91,8 @@ namespace LuaScript public bool ResolveObject(string tag, int frame, out SceneObjectInfo info) { - if (Resolver is not null && Resolver.TryResolve(tag, frame, out var resolved)) + 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; diff --git a/LuaScript/LuaScriptEffectProcessor.cs b/LuaScript/LuaScriptEffectProcessor.cs index 7981ed7..50ec6cd 100644 --- a/LuaScript/LuaScriptEffectProcessor.cs +++ b/LuaScript/LuaScriptEffectProcessor.cs @@ -44,6 +44,15 @@ namespace LuaScript private readonly LuaScriptEngine _engine = new(); private readonly SemaphoreSlim _pixelLoaderSemaphore = new(1, 1); + private AviUtlScriptContext _context = new(); + + private EffectDescription? _frameDesc; + private SceneObjectResolver? _frameResolver; + private bool _frameResolverBuilt; + + private Guid _lastSceneGuid; + private string _lastSceneId = string.Empty; + private bool _sceneIdCached; private GraphicsDevicesAndContext? _ownCtx; @@ -67,9 +76,31 @@ namespace LuaScript { _ownCtx = new GraphicsDevicesAndContext(devices); disposer.Collect(_ownCtx); + _context.ResolverProvider = GetFrameResolver; return null; } + private SceneObjectResolver GetFrameResolver() + { + if (!_frameResolverBuilt) + { + _frameResolver = BuildSceneObjectResolver(_frameDesc!); + _frameResolverBuilt = true; + } + return _frameResolver!; + } + + private string ResolveSceneId(Guid sceneId) + { + if (!_sceneIdCached || sceneId != _lastSceneGuid) + { + _lastSceneId = sceneId.ToString(); + _lastSceneGuid = sceneId; + _sceneIdCached = true; + } + return _lastSceneId; + } + protected override void setInput(ID2D1Image? input) { if (!ReferenceEquals(_cachedInput, input)) @@ -113,10 +144,12 @@ namespace LuaScript desc.TimelineDuration.Time.TotalSeconds, inDesc); - var resolver = BuildSceneObjectResolver(desc); + _frameDesc = desc; + _frameResolver = null; + _frameResolverBuilt = false; if (!_isFirst && key == _cachedKey && - QueriesMatch(_cachedQueries, resolver)) + (_cachedQueries.Length == 0 || QueriesMatch(_cachedQueries, GetFrameResolver()))) { effectOutput = _cachedPixelsModified ? _transformEffect?.Output : null; return _cachedOutputDesc ?? inDesc; @@ -126,7 +159,8 @@ namespace LuaScript int imgW = Math.Max(1, (int)Math.Ceiling(bounds.Right - bounds.Left)); int imgH = Math.Max(1, (int)Math.Ceiling(bounds.Bottom - bounds.Top)); - var ctx = BuildContext(in key, imgW, imgH, resolver); + var ctx = _context; + PopulateContext(ctx, in key, imgW, imgH); ctx.SetPixelLoader(() => LoadInputPixels(bounds, imgW, imgH)); DrawDescription outDesc = inDesc; @@ -151,6 +185,14 @@ namespace LuaScript outDesc = BuildOutputDesc(inDesc, ctx); } + catch (LuaScriptTimeoutException ex) + { + effectOutput = null; + _context = new AviUtlScriptContext { ResolverProvider = GetFrameResolver }; + _isFirst = true; + Log.Default.Write(ex.Message, ex); + return inDesc; + } catch (LuaScriptException ex) { effectOutput = null; @@ -165,7 +207,7 @@ namespace LuaScript _isFirst = false; _cachedKey = key; - _cachedQueries = [.. ctx.ObjectQueries]; + _cachedQueries = ctx.ObjectQueries.Count == 0 ? [] : [.. ctx.ObjectQueries]; _cachedOutputDesc = outDesc; _cachedPixelsModified = pixelsModified; @@ -219,7 +261,7 @@ namespace LuaScript return true; } - private static AviUtlScriptContext BuildContext(in RenderKey key, int imgW, int imgH, SceneObjectResolver resolver) + private void PopulateContext(AviUtlScriptContext ctx, in RenderKey key, int imgW, int imgH) { var zoom = key.InputDesc.Zoom; double zoomAvg = (zoom.X + zoom.Y) / 2d; @@ -227,51 +269,49 @@ namespace LuaScript ? (zoom.X - zoom.Y) / (zoom.X + zoom.Y) : 0d; - return new AviUtlScriptContext - { - ImageWidth = imgW, - ImageHeight = imgH, - X = key.InputDesc.Draw.X, - Y = key.InputDesc.Draw.Y, - Z = key.InputDesc.Draw.Z, - Ox = key.InputDesc.CenterPoint.X, - Oy = key.InputDesc.CenterPoint.Y, - Oz = 0d, - Sx = zoom.X, - Sy = zoom.Y, - Zoom = zoomAvg, - Aspect = aspect, - Alpha = key.InputDesc.Opacity * 255d, - Rx = key.InputDesc.Rotation.X, - Ry = key.InputDesc.Rotation.Y, - Rz = key.InputDesc.Rotation.Z, - Track0 = key.Track0, - Track1 = key.Track1, - Track2 = key.Track2, - Track3 = key.Track3, - Time = key.Time, - Frame = key.Frame, - TotalFrame = key.Length, - TotalTime = key.Fps > 0 ? key.Length / (double)key.Fps : 0d, - Framerate = key.Fps, - TimelineFrame = key.TimelineFrame, - TimelineTime = key.TimelineTime, - SceneWidth = key.SceneWidth, - SceneHeight = key.SceneHeight, - Layer = key.Layer, - Index = key.InputIndex, - Num = key.InputCount, - GroupIndex = key.GroupIndex, - GroupCount = key.GroupCount, - TimelineTotalFrame = key.TimelineTotalFrame, - TimelineTotalTime = key.TimelineTotalTime, - IsSaving = key.Usage == TimelineSourceUsage.Exporting, - IsPlaying = key.Usage == TimelineSourceUsage.Playing, - IsPaused = key.Usage == TimelineSourceUsage.Paused, - SceneId = key.SceneId.ToString(), - TimeRatio = key.Length > 0 ? key.Frame / (double)key.Length : 0d, - Resolver = resolver, - }; + ctx.ClearQueries(); + + ctx.ImageWidth = imgW; + ctx.ImageHeight = imgH; + ctx.X = key.InputDesc.Draw.X; + ctx.Y = key.InputDesc.Draw.Y; + ctx.Z = key.InputDesc.Draw.Z; + ctx.Ox = key.InputDesc.CenterPoint.X; + ctx.Oy = key.InputDesc.CenterPoint.Y; + ctx.Oz = 0d; + ctx.Sx = zoom.X; + ctx.Sy = zoom.Y; + ctx.Zoom = zoomAvg; + ctx.Aspect = aspect; + ctx.Alpha = key.InputDesc.Opacity * 255d; + ctx.Rx = key.InputDesc.Rotation.X; + ctx.Ry = key.InputDesc.Rotation.Y; + ctx.Rz = key.InputDesc.Rotation.Z; + ctx.Track0 = key.Track0; + ctx.Track1 = key.Track1; + ctx.Track2 = key.Track2; + ctx.Track3 = key.Track3; + ctx.Time = key.Time; + ctx.Frame = key.Frame; + ctx.TotalFrame = key.Length; + ctx.TotalTime = key.Fps > 0 ? key.Length / (double)key.Fps : 0d; + ctx.Framerate = key.Fps; + ctx.TimelineFrame = key.TimelineFrame; + ctx.TimelineTime = key.TimelineTime; + ctx.SceneWidth = key.SceneWidth; + ctx.SceneHeight = key.SceneHeight; + ctx.Layer = key.Layer; + ctx.Index = key.InputIndex; + ctx.Num = key.InputCount; + ctx.GroupIndex = key.GroupIndex; + ctx.GroupCount = key.GroupCount; + ctx.TimelineTotalFrame = key.TimelineTotalFrame; + ctx.TimelineTotalTime = key.TimelineTotalTime; + ctx.IsSaving = key.Usage == TimelineSourceUsage.Exporting; + ctx.IsPlaying = key.Usage == TimelineSourceUsage.Playing; + ctx.IsPaused = key.Usage == TimelineSourceUsage.Paused; + ctx.SceneId = ResolveSceneId(key.SceneId); + ctx.TimeRatio = key.Length > 0 ? key.Frame / (double)key.Length : 0d; } private static DrawDescription BuildOutputDesc(DrawDescription inDesc, AviUtlScriptContext ctx) diff --git a/LuaScript/LuaScriptEngine.cs b/LuaScript/LuaScriptEngine.cs index c202628..240c9ff 100644 --- a/LuaScript/LuaScriptEngine.cs +++ b/LuaScript/LuaScriptEngine.cs @@ -1,4 +1,3 @@ -using System.Collections.Concurrent; using MoonSharp.Interpreter; using MoonSharp.Interpreter.Debugging; using MoonSharp.Interpreter.Loaders; @@ -11,12 +10,6 @@ namespace LuaScript LuaScriptException? Exception, bool TimedOut); - private sealed record ExecutionJob( - string Code, - AviUtlScriptContext Context, - CancellationToken Cancellation, - TaskCompletionSource Completion); - private sealed class ExecutionThread : IDisposable { private sealed class CancellationDebugger : IDebugger @@ -46,10 +39,19 @@ namespace LuaScript } } - private readonly BlockingCollection _queue = new(boundedCapacity: 1); + 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 _removalBuffer = []; + private Script? _script; private DynValue? _compiledChunk; private string _lastCompiledCode = string.Empty; @@ -67,6 +69,8 @@ namespace LuaScript internal ExecutionThread() { + _activeCancellation = _cts.Token; + _debugger.UpdateToken(_cts.Token); _thread = new Thread(WorkerLoop) { IsBackground = true, @@ -77,77 +81,65 @@ namespace LuaScript internal ExecutionResult TryExecute(string code, AviUtlScriptContext ctx, int timeoutMs) { - using var cts = new CancellationTokenSource(); - var tcs = new TaskCompletionSource( - TaskCreationOptions.RunContinuationsAsynchronously); + _jobCode = code; + _jobContext = ctx; + _jobException = null; + _doneSignal.Reset(); + _workSignal.Release(); - if (!_queue.TryAdd(new ExecutionJob(code, ctx, cts.Token, tcs))) - return new ExecutionResult( - new LuaScriptRuntimeException("Script execution queue is full."), false); + if (_doneSignal.Wait(timeoutMs)) + return new ExecutionResult(_jobException, false); - if (tcs.Task.Wait(timeoutMs)) - return tcs.Task.Result; - - cts.Cancel(); + _cts.Cancel(); return new ExecutionResult(null, TimedOut: true); } private void WorkerLoop() { - try + while (true) { - foreach (var job in _queue.GetConsumingEnumerable()) - ProcessJob(job); + _workSignal.Wait(); + if (_disposeRequested) + return; + ProcessJob(); + _doneSignal.Set(); } - catch (OperationCanceledException) { } - catch (InvalidOperationException) { } } - private void ProcessJob(ExecutionJob job) + private void ProcessJob() { - if (job.Cancellation.IsCancellationRequested) - { - job.Completion.TrySetResult(new ExecutionResult(null, TimedOut: true)); - return; - } - - _activeCancellation = job.Cancellation; - _activeContext = job.Context; - _debugger.UpdateToken(job.Cancellation); + var context = _jobContext!; + _activeContext = context; try { EnsureScript(); EnsureScriptIntegrity(); - EnsureCompiled(job.Code); - SetupGlobals(job.Context); + EnsureCompiled(_jobCode); + SetupGlobals(context); _script!.Call(_compiledChunk!); - ReadBackGlobals(job.Context); - job.Completion.TrySetResult(new ExecutionResult(null, false)); + ReadBackGlobals(context); + _jobException = null; } - catch (OperationCanceledException) when (job.Cancellation.IsCancellationRequested) + catch (OperationCanceledException) when (_cts.IsCancellationRequested) { - job.Completion.TrySetResult(new ExecutionResult(null, TimedOut: true)); + _jobException = null; } catch (LuaScriptException ex) { - job.Completion.TrySetResult(new ExecutionResult(ex, false)); + _jobException = ex; } catch (ScriptRuntimeException ex) { - job.Completion.TrySetResult(new ExecutionResult( - new LuaScriptRuntimeException(ex.DecoratedMessage ?? ex.Message, ex), false)); + _jobException = new LuaScriptRuntimeException(ex.DecoratedMessage ?? ex.Message, ex); } catch (Exception ex) { - job.Completion.TrySetResult(new ExecutionResult( - new LuaScriptRuntimeException(ex.Message, ex), false)); + _jobException = new LuaScriptRuntimeException(ex.Message, ex); } finally { - _debugger.UpdateToken(default); _activeContext = null; - _activeCancellation = default; } } @@ -269,10 +261,10 @@ namespace LuaScript _ymm4TableSnapshot = null; } - ResetUserTableKeys(_objTable!, ref _objTableSnapshot); - ResetUserTableKeys(_sceneTable!, ref _sceneTableSnapshot); - ResetUserTableKeys(_animTable!, ref _animTableSnapshot); - ResetUserTableKeys(_ymm4Table!, ref _ymm4TableSnapshot); + ResetUserTableKeys(_objTable!, _objTableSnapshot); + ResetUserTableKeys(_sceneTable!, _sceneTableSnapshot); + ResetUserTableKeys(_animTable!, _animTableSnapshot); + ResetUserTableKeys(_ymm4Table!, _ymm4TableSnapshot); } script.Globals["time"] = ctx.Time; @@ -366,34 +358,36 @@ namespace LuaScript return keys; } - private static void ResetUserTableKeys(Table table, ref HashSet? snapshot) + private void ResetUserTableKeys(Table table, HashSet? snapshot) { if (snapshot is null) return; - var keysToRemove = new List(); + var buffer = _removalBuffer; + buffer.Clear(); foreach (var key in table.Keys) { if (key.Type == DataType.String && !snapshot.Contains(key.String)) { - keysToRemove.Add(key.String); + buffer.Add(key.String); } } - foreach (var key in keysToRemove) + foreach (var key in buffer) table[key] = DynValue.Nil; } private void ResetUserGlobals(Script script) { - var keysToRemove = new List(); + var buffer = _removalBuffer; + buffer.Clear(); foreach (var key in script.Globals.Keys) { if (key.Type == DataType.String && !_builtinGlobalSnapshot!.Contains(key.String)) { - keysToRemove.Add(key.String); + buffer.Add(key.String); } } - foreach (var key in keysToRemove) + foreach (var key in buffer) script.Globals[key] = DynValue.Nil; } @@ -531,18 +525,25 @@ namespace LuaScript public void Dispose() { - _queue.CompleteAdding(); + _disposeRequested = true; + _workSignal.Release(); _thread.Join(); - _queue.Dispose(); + _cts.Cancel(); + _cts.Dispose(); + _workSignal.Dispose(); + _doneSignal.Dispose(); } internal void AbandonAsync() { - _queue.CompleteAdding(); + _disposeRequested = true; + _workSignal.Release(); ThreadPool.QueueUserWorkItem(_ => { _thread.Join(); - _queue.Dispose(); + _cts.Dispose(); + _workSignal.Dispose(); + _doneSignal.Dispose(); }); } @@ -577,7 +578,7 @@ namespace LuaScript var stale = _executionThread; _executionThread = new ExecutionThread(); stale.AbandonAsync(); - throw new LuaScriptRuntimeException( + throw new LuaScriptTimeoutException( $"Script execution timed out after {ExecutionTimeoutMilliseconds} ms."); } diff --git a/LuaScript/LuaScriptExceptions.cs b/LuaScript/LuaScriptExceptions.cs index 859ca14..021dd8d 100644 --- a/LuaScript/LuaScriptExceptions.cs +++ b/LuaScript/LuaScriptExceptions.cs @@ -5,4 +5,6 @@ namespace LuaScript internal sealed class LuaScriptCompilationException(string message, Exception? inner = null) : LuaScriptException(message, inner); internal sealed class LuaScriptRuntimeException(string message, Exception? inner = null) : LuaScriptException(message, inner); + + internal sealed class LuaScriptTimeoutException(string message, Exception? inner = null) : LuaScriptException(message, inner); }