Add live runtime assembly reload

This commit is contained in:
Meta Vens 2026-05-08 16:04:52 +01:00
commit d594e0803b
18 changed files with 375 additions and 31 deletions

View file

@ -0,0 +1,9 @@
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<TargetFramework>net10.0</TargetFramework>
<ImplicitUsings>enable</ImplicitUsings>
<Nullable>enable</Nullable>
</PropertyGroup>
</Project>

View file

@ -0,0 +1,6 @@
using System.Numerics;
namespace Aquarium.Engine;
public readonly record struct AquariumFrame(GridFrame Grid, Vector3 CameraPosition, float TimeSeconds);

View file

@ -0,0 +1,22 @@
using Aquarium.Engine.Input;
namespace Aquarium.Engine;
public interface IAquariumRuntime : IDisposable
{
AquariumRuntimeOptions Options { get; }
AquariumFrame Frame { get; }
void Start();
void Update(float deltaSeconds, InputState input);
}
public interface IAquariumRuntimeFactory
{
IAquariumRuntime Create(AquariumRuntimeOptions options);
}
public readonly record struct AquariumRuntimeOptions(bool Headless, string? CultCachePath);

View file

@ -4,8 +4,8 @@ namespace Aquarium.Engine;
public readonly record struct GridFrame(Vector2 Center, float Radius)
{
public static GridFrame FromCamera(OrbitCameraRig camera)
public static GridFrame FromCamera(Vector2 target, float distance)
{
return new GridFrame(camera.Target, camera.Distance);
return new GridFrame(target, distance);
}
}

View file

@ -0,0 +1,16 @@
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<TargetFramework>net10.0</TargetFramework>
<ImplicitUsings>enable</ImplicitUsings>
<Nullable>enable</Nullable>
<CopyLocalLockFileAssemblies>true</CopyLocalLockFileAssemblies>
</PropertyGroup>
<ItemGroup>
<ProjectReference Include="..\Aquarium.Engine.Contracts\Aquarium.Engine.Contracts.csproj" />
<ProjectReference Include="..\..\..\CultLib\src\GameCult.Caching.MessagePack\GameCult.Caching.MessagePack.csproj" />
<ProjectReference Include="..\..\..\CultLib\src\GameCult.Networking\GameCult.Networking.csproj" />
</ItemGroup>
</Project>

View file

@ -4,7 +4,7 @@ using Aquarium.Engine.State;
namespace Aquarium.Engine;
public sealed class AquariumRuntime : IDisposable
public sealed class AquariumRuntime : IAquariumRuntime
{
private const float StateSaveIntervalSeconds = 0.20f;
@ -26,7 +26,7 @@ public sealed class AquariumRuntime : IDisposable
pitchRadians: liveState.CameraPitchRadians,
distance: liveState.CameraDistance);
timeSeconds = liveState.TimeSeconds;
gridFrame = GridFrame.FromCamera(cameraRig);
gridFrame = GridFrame.FromCamera(cameraRig.Target, cameraRig.Distance);
}
public AquariumRuntimeOptions Options { get; }
@ -46,7 +46,7 @@ public sealed class AquariumRuntime : IDisposable
{
timeSeconds += Math.Max(deltaSeconds, 0.0f);
cameraRig.ApplyInput(input, deltaSeconds);
gridFrame = GridFrame.FromCamera(cameraRig);
gridFrame = GridFrame.FromCamera(cameraRig.Target, cameraRig.Distance);
secondsSinceStateSave += Math.Max(deltaSeconds, 0.0f);
if (secondsSinceStateSave >= StateSaveIntervalSeconds)
{
@ -75,6 +75,10 @@ public sealed class AquariumRuntime : IDisposable
}
}
public readonly record struct AquariumRuntimeOptions(bool Headless, string? CultCachePath);
public readonly record struct AquariumFrame(GridFrame Grid, System.Numerics.Vector3 CameraPosition, float TimeSeconds);
public sealed class AquariumRuntimeFactory : IAquariumRuntimeFactory
{
public IAquariumRuntime Create(AquariumRuntimeOptions options)
{
return new AquariumRuntime(options);
}
}

View file

@ -9,6 +9,7 @@
</PropertyGroup>
<ItemGroup>
<ProjectReference Include="..\Aquarium.Engine.Contracts\Aquarium.Engine.Contracts.csproj" />
<PackageReference Include="Vortice.Direct3D11" Version="3.8.3" />
<PackageReference Include="Vortice.D3DCompiler" Version="3.8.3" />
<PackageReference Include="Vortice.DXGI" Version="3.8.3" />
@ -17,8 +18,6 @@
<ItemGroup>
<ProjectReference Include="..\..\..\CultMath\src\CultMath\CultMath.csproj" />
<ProjectReference Include="..\..\..\CultLib\src\GameCult.Caching.MessagePack\GameCult.Caching.MessagePack.csproj" />
<ProjectReference Include="..\..\..\CultLib\src\GameCult.Networking\GameCult.Networking.csproj" />
</ItemGroup>
<ItemGroup>

View file

@ -1,5 +1,6 @@
using System.Diagnostics;
using Aquarium.Engine.Input;
using Aquarium.Engine.Live;
using Aquarium.Engine.Platform;
using Aquarium.Engine.Render;
@ -9,7 +10,9 @@ public static class AquariumHost
{
public static int Run(string[] args)
{
using var runtime = new AquariumRuntime(new AquariumRuntimeOptions(ParseHeadless(args), ParseCachePath(args)));
var runtimeOptions = new AquariumRuntimeOptions(ParseHeadless(args), ParseCachePath(args));
using var runtimeLoader = new LiveRuntimeLoader(runtimeOptions, ParseLiveAssemblyPath(args), ParseLiveReloadPointerPath(args));
var runtime = runtimeLoader.Load();
var input = new InputState();
var width = runtime.Options.Headless ? 640 : 1280;
var height = runtime.Options.Headless ? 360 : 720;
@ -18,8 +21,6 @@ public static class AquariumHost
window.PaintSplash();
using var renderer = new D3D11Renderer(window.Handle, window.ClientWidth, window.ClientHeight, ParseShaderPath(args));
runtime.Start();
var frameClock = Stopwatch.StartNew();
var lastFrame = frameClock.Elapsed;
var frames = 0;
@ -36,8 +37,8 @@ public static class AquariumHost
var deltaSeconds = (float)(now - lastFrame).TotalSeconds;
lastFrame = now;
runtime.Update(deltaSeconds, input);
renderer.Render(runtime.Frame);
runtimeLoader.Update(deltaSeconds, input);
renderer.Render(runtimeLoader.Runtime.Frame);
if (runtime.Options.Headless && ++frames >= 2)
{
@ -80,4 +81,32 @@ public static class AquariumHost
return Environment.GetEnvironmentVariable("AQUARIUM_SHADER_SOURCE");
}
private static string? ParseLiveAssemblyPath(IReadOnlyCollection<string> args)
{
var values = args.ToArray();
for (var index = 0; index < values.Length - 1; index++)
{
if (string.Equals(values[index], "--live-assembly", StringComparison.OrdinalIgnoreCase))
{
return values[index + 1];
}
}
return Environment.GetEnvironmentVariable("AQUARIUM_LIVE_ASSEMBLY");
}
private static string? ParseLiveReloadPointerPath(IReadOnlyCollection<string> args)
{
var values = args.ToArray();
for (var index = 0; index < values.Length - 1; index++)
{
if (string.Equals(values[index], "--live-reload-pointer", StringComparison.OrdinalIgnoreCase))
{
return values[index + 1];
}
}
return Environment.GetEnvironmentVariable("AQUARIUM_LIVE_RELOAD_POINTER");
}
}

View file

@ -0,0 +1,157 @@
using System.Reflection;
using System.Runtime.Loader;
using System.Diagnostics;
namespace Aquarium.Engine.Live;
public sealed class LiveRuntimeLoader : IDisposable
{
private const string LiveAssemblyName = "Aquarium.Engine.Live.dll";
private const string FactoryTypeName = "Aquarium.Engine.AquariumRuntimeFactory";
private readonly string liveAssemblyPath;
private readonly string? liveReloadPointerPath;
private readonly Stopwatch reloadClock = Stopwatch.StartNew();
private readonly AquariumRuntimeOptions options;
private ReloadedRuntime? current;
private TimeSpan lastReloadCheck;
private string? currentAssemblyPath;
public LiveRuntimeLoader(AquariumRuntimeOptions options, string? liveAssemblyPath = null, string? liveReloadPointerPath = null)
{
this.liveAssemblyPath = liveAssemblyPath ?? Path.Combine(AppContext.BaseDirectory, LiveAssemblyName);
this.liveReloadPointerPath = liveReloadPointerPath;
this.options = options;
}
public IAquariumRuntime Runtime
{
get
{
if (current == null)
{
Reload(liveAssemblyPath, options);
}
return current!.Runtime;
}
}
public IAquariumRuntime Load()
{
Reload(liveAssemblyPath, options);
return Runtime;
}
public void Reload(string assemblyPath, AquariumRuntimeOptions options)
{
var previous = current;
var loadContext = new LiveAssemblyLoadContext(assemblyPath);
IAquariumRuntime? nextRuntime = null;
try
{
var assembly = loadContext.LoadFromAssemblyPath(assemblyPath);
var factoryType = assembly.GetType(FactoryTypeName, throwOnError: true)
?? throw new InvalidOperationException($"Live runtime factory was not found: {FactoryTypeName}");
var factory = (IAquariumRuntimeFactory?)Activator.CreateInstance(factoryType)
?? throw new InvalidOperationException($"Live runtime factory could not be created: {FactoryTypeName}");
nextRuntime = factory.Create(options);
nextRuntime.Start();
}
catch
{
nextRuntime?.Dispose();
loadContext.Unload();
throw;
}
current = new ReloadedRuntime(loadContext, nextRuntime);
currentAssemblyPath = assemblyPath;
previous?.Runtime.Dispose();
previous?.Unload();
}
public void Update(float deltaSeconds, Input.InputState input)
{
TryReloadFromPointer();
Runtime.Update(deltaSeconds, input);
}
private void TryReloadFromPointer()
{
if (string.IsNullOrWhiteSpace(liveReloadPointerPath) || reloadClock.Elapsed - lastReloadCheck < TimeSpan.FromMilliseconds(500))
{
return;
}
lastReloadCheck = reloadClock.Elapsed;
string candidatePath;
try
{
candidatePath = File.ReadAllText(liveReloadPointerPath).Trim();
}
catch
{
return;
}
if (string.IsNullOrWhiteSpace(candidatePath)
|| string.Equals(candidatePath, currentAssemblyPath, StringComparison.OrdinalIgnoreCase)
|| !File.Exists(candidatePath))
{
return;
}
try
{
Reload(candidatePath, options);
Console.WriteLine($"Live runtime reload applied: {candidatePath}");
}
catch (Exception error)
{
Console.Error.WriteLine($"Live runtime reload failed; keeping previous runtime. {error.Message}");
}
}
public void Dispose()
{
var runtime = current;
current = null;
runtime?.Runtime.Dispose();
runtime?.Unload();
}
private sealed class ReloadedRuntime(LiveAssemblyLoadContext loadContext, IAquariumRuntime runtime)
{
public IAquariumRuntime Runtime { get; } = runtime;
public void Unload()
{
loadContext.Unload();
}
}
private sealed class LiveAssemblyLoadContext(string assemblyPath) : AssemblyLoadContext(isCollectible: true)
{
private readonly AssemblyDependencyResolver resolver = new(assemblyPath);
protected override Assembly? Load(AssemblyName assemblyName)
{
if (assemblyName.Name == typeof(IAquariumRuntime).Assembly.GetName().Name)
{
return null;
}
var path = resolver.ResolveAssemblyToPath(assemblyName);
return path == null ? null : LoadFromAssemblyPath(path);
}
protected override IntPtr LoadUnmanagedDll(string unmanagedDllName)
{
var path = resolver.ResolveUnmanagedDllToPath(unmanagedDllName);
return path == null ? IntPtr.Zero : LoadUnmanagedDllFromPath(path);
}
}
}