diff --git a/LuaScript/Engine/Kernel/GpuKernel.cs b/LuaScript/Engine/Kernel/GpuKernel.cs new file mode 100644 index 0000000..abf1df3 --- /dev/null +++ b/LuaScript/Engine/Kernel/GpuKernel.cs @@ -0,0 +1,29 @@ +using System; +using Vortice.Direct2D1; +using YukkuriMovieMaker.Commons; + +namespace LuaScript.Engine.Kernel +{ + internal sealed class GpuKernel : IDisposable + { + private readonly GpuKernelEffect _effect; + private readonly float[] _packed = new float[HlslKernelEmitter.ConstantFloatCount]; + private readonly byte[] _bytes = new byte[HlslKernelEmitter.ConstantFloatCount * sizeof(float)]; + + public GpuKernel(IGraphicsDevicesAndContext devices, KernelProgram program) + => _effect = new GpuKernelEffect(devices, HlslKernelEmitter.Emit(program)); + + public bool IsReady => _effect.IsReady; + + public ID2D1Image Apply(ID2D1Image input, double[] uniforms) + { + KernelUniformBinding.Pack(uniforms, _packed); + Buffer.BlockCopy(_packed, 0, _bytes, 0, _bytes.Length); + _effect.SetConstants(_bytes); + _effect.SetInput(0, input, true); + return _effect.Output; + } + + public void Dispose() => _effect.Dispose(); + } +} diff --git a/LuaScript/Engine/Kernel/GpuKernelEffect.cs b/LuaScript/Engine/Kernel/GpuKernelEffect.cs new file mode 100644 index 0000000..b7b744e --- /dev/null +++ b/LuaScript/Engine/Kernel/GpuKernelEffect.cs @@ -0,0 +1,193 @@ +using System; +using System.Collections.Generic; +using System.Runtime.InteropServices; +using System.Text; +using System.Threading; +using Vortice; +using Vortice.D3DCompiler; +using Vortice.Direct2D1; +using Vortice.Direct3D; +using Vortice.Mathematics; +using YukkuriMovieMaker.Commons; + +namespace LuaScript.Engine.Kernel +{ + internal sealed class GpuKernelEffect : ID2D1Effect + { + private const int ConstantsIndex = 0; + private const int InitializedIndex = 1; + + [StructLayout(LayoutKind.Sequential)] + private unsafe struct ConstantBuffer + { + public fixed float Values[HlslKernelEmitter.ConstantFloatCount]; + } + + [CustomEffect(1, null, null, null, null)] + private sealed class Impl(Guid guid, string hlsl) : CustomEffectBase, ID2D1DrawTransform + { + private ConstantBuffer _constants; + private ID2D1DrawInfo? _drawInfo; + + [CustomEffectProperty(PropertyType.Blob, ConstantsIndex)] + public byte[] Constants + { + get => ToBytes(_constants); + set + { + FromBytes(value, ref _constants); + _drawInfo?.SetPixelShaderConstantBuffer(in _constants); + } + } + + [CustomEffectProperty(PropertyType.Bool, InitializedIndex)] + public bool Initialized { get; private set; } + + public override void Initialize(ID2D1EffectContext effectContext, ID2D1TransformGraph transformGraph) + { + byte[] source = Encoding.ASCII.GetBytes(hlsl); + var result = Compiler.Compile(source, "main", string.Empty, "ps_4_1", out var bytecode, out var errors); + if (result.Failure || bytecode is null) + { + Initialized = false; + Log.Default.Write("LuaScript: GPU kernel shader compilation failed.\n" + (errors?.AsString() ?? string.Empty)); + errors?.Dispose(); + bytecode?.Dispose(); + return; + } + + try + { + byte[] shader = bytecode.AsBytes(); + effectContext.LoadPixelShader(guid, shader, shader.Length); + transformGraph.SetSingleTransformNode(this); + Initialized = true; + } + finally + { + errors?.Dispose(); + bytecode.Dispose(); + } + } + + public void SetDrawInfo(ID2D1DrawInfo drawInfo) + { + _drawInfo = drawInfo; + drawInfo.SetPixelShader(guid, PixelOptions.None); + drawInfo.SetInputDescription(0, new InputDescription { Filter = (Filter)21, LevelOfDetailCount = 1 }); + drawInfo.SetPixelShaderConstantBuffer(in _constants); + } + + public int GetInputCount() => 1; + + public void MapOutputRectToInputRects(RawRect outputRect, RawRect[] inputRects) => + inputRects[0] = outputRect; + + public void MapInputRectsToOutputRect(RawRect[] inputRects, RawRect[] inputOpaqueSubRects, out RawRect outputRect, out RawRect outputOpaqueSubRect) + { + outputRect = inputRects[0]; + outputOpaqueSubRect = default; + } + + public RawRect MapInvalidRect(int inputIndex, RawRect invalidInputRect) => invalidInputRect; + + private static unsafe byte[] ToBytes(ConstantBuffer constants) + { + byte[] bytes = new byte[sizeof(ConstantBuffer)]; + fixed (byte* destination = bytes) + *(ConstantBuffer*)destination = constants; + return bytes; + } + + private static unsafe void FromBytes(byte[] bytes, ref ConstantBuffer constants) + { + int length = Math.Min(bytes.Length, sizeof(ConstantBuffer)); + fixed (byte* source = bytes) + fixed (ConstantBuffer* destination = &constants) + Buffer.MemoryCopy(source, destination, sizeof(ConstantBuffer), length); + } + } + + private sealed class Manager + { + private readonly Lock _locker = new(); + private readonly Dictionary> _registered = []; + + public Guid Acquire(IGraphicsDevicesAndContext devices, string hlsl) + { + lock (_locker) + { + int device = devices.GetHashCode(); + if (!_registered.TryGetValue(device, out var byHlsl)) + { + byHlsl = []; + _registered[device] = byHlsl; + } + if (byHlsl.TryGetValue(hlsl, out var entry)) + { + byHlsl[hlsl] = (entry.Guid, entry.Count + 1); + return entry.Guid; + } + + var guid = Guid.NewGuid(); + byHlsl[hlsl] = (guid, 1); + ((ID2D1Factory1)devices.D2D.Factory).RegisterEffect(() => new Impl(guid, hlsl), guid); + return guid; + } + } + + public void Release(IGraphicsDevicesAndContext devices, string hlsl) + { + lock (_locker) + { + int device = devices.GetHashCode(); + if (!_registered.TryGetValue(device, out var byHlsl) || !byHlsl.TryGetValue(hlsl, out var entry)) + return; + if (entry.Count > 1) + { + byHlsl[hlsl] = (entry.Guid, entry.Count - 1); + return; + } + byHlsl.Remove(hlsl); + ((ID2D1Factory1)devices.D2D.Factory).UnregisterEffect(entry.Guid); + } + } + } + + private static readonly Manager Effects = new(); + + private readonly IGraphicsDevicesAndContext _devices; + private readonly string _hlsl; + + public GpuKernelEffect(IGraphicsDevicesAndContext devices, string hlsl) + : base(Create(devices, hlsl)) + { + _devices = devices; + _hlsl = hlsl; + } + + public bool IsReady => NativePointer != nint.Zero && ((ID2D1Properties)this).GetBoolValue(InitializedIndex); + + public void SetConstants(byte[] bytes) => ((ID2D1Properties)this).SetValue(ConstantsIndex, bytes); + + private static nint Create(IGraphicsDevicesAndContext devices, string hlsl) + { + try + { + var guid = Effects.Acquire(devices, hlsl); + return ((ID2D1DeviceContext)devices.DeviceContext).CreateEffect(guid); + } + catch (Exception ex) + { + Log.Default.Write("LuaScript: failed to create GPU kernel effect.", ex); + return nint.Zero; + } + } + + protected override void DisposeCore(nint nativePointer, bool disposing) + { + base.DisposeCore(nativePointer, disposing); + Effects.Release(_devices, _hlsl); + } + } +} diff --git a/LuaScript/Engine/Kernel/HlslKernelEmitter.cs b/LuaScript/Engine/Kernel/HlslKernelEmitter.cs index ab52a23..4d10a71 100644 --- a/LuaScript/Engine/Kernel/HlslKernelEmitter.cs +++ b/LuaScript/Engine/Kernel/HlslKernelEmitter.cs @@ -5,7 +5,9 @@ namespace LuaScript.Engine.Kernel { internal static class HlslKernelEmitter { - public static int ConstantVectorCount { get; } = (KernelUniforms.Count + 3) / 4; + public const int ConstantVectorCount = 16; + + public const int ConstantFloatCount = ConstantVectorCount * 4; private static readonly string[] Intrinsics = [ diff --git a/LuaScript/Engine/Kernel/KernelUniformBinding.cs b/LuaScript/Engine/Kernel/KernelUniformBinding.cs new file mode 100644 index 0000000..55a9591 --- /dev/null +++ b/LuaScript/Engine/Kernel/KernelUniformBinding.cs @@ -0,0 +1,72 @@ +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.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; + } + } +}