feat: update Godot integration and coordinated package dependencies

This commit is contained in:
cneicy committed 2026-11-06 19:13:24 +08:00
1 parent e355bbfd35
commit 6c2cca5735
5 files changed
+422 -125

No files matched your search

+101 -112
View File
@@ -1,15 +1,11 @@
#nullable enable
using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Reflection;
using System.Threading;
using System.Threading.Tasks;
using Cysharp.Threading.Tasks;
using Godot;
using ShrinkEventBus;
using ShrinkDataSaver;
using ShrinkApp;
using ShrinkNetwork;
using ShrinkSDK.Runtime;
@@ -17,138 +13,131 @@ using ShrinkSDK.Runtime;
namespace ShrinkSDK.Godot;
public partial class ShrinkGodotHost : Node, IShrinkMainThreadDispatcher,
IShrinkLogger, IShrinkClock, IShrinkPathProvider, IShrinkScreenshotProvider,
IShrinkApplicationLifecycle
IShrinkDeferredMainThreadDispatcher, IShrinkLogger, IShrinkClock, IShrinkPathProvider,
IShrinkScreenshotProvider, IShrinkApplicationLifecycle
{
private readonly ConcurrentQueue<Action> _dispatchQueue = new();
private readonly Dictionary<ShrinkNetworkService, ShrinkNetworkDispatchQueue> _networkServices = new();
private int _mainThreadId;
private bool _networkPumpRunning;
private ShrinkAppRuntime? _appRuntime;
private readonly ShrinkGodotRuntime _runtime = new();
private SceneTree? _tree;
private ulong _lastTickFrame = ulong.MaxValue;
private bool _signalsConnected;
public event Action? Paused;
public event Action? Resumed;
public event Action? Exiting;
public ShrinkGodotRuntime Runtime => _runtime;
[Export] public int DispatchBudgetPerFrame { get; set; } = 256;
[Export] public int NetworkDispatchBudgetPerFrame { get; set; } = 256;
[Export]
public int DispatchBudgetPerFrame
{
get => _runtime.DispatchBudgetPerFrame;
set => _runtime.DispatchBudgetPerFrame = value;
}
public bool IsMainThread => Thread.CurrentThread.ManagedThreadId == _mainThreadId;
public DateTimeOffset UtcNow => DateTimeOffset.UtcNow;
public double UnscaledTimeSeconds => Time.GetTicksMsec() / 1000d;
public string PersistentDataPath => ProjectSettings.GlobalizePath("user://");
public string TemporaryDataPath => OS.GetCacheDir();
[Export]
public int NetworkDispatchBudgetPerFrame
{
get => _runtime.NetworkDispatchBudgetPerFrame;
set => _runtime.NetworkDispatchBudgetPerFrame = value;
}
public event Action? Paused
{
add => _runtime.Paused += value;
remove => _runtime.Paused -= value;
}
public event Action? Resumed
{
add => _runtime.Resumed += value;
remove => _runtime.Resumed -= value;
}
public event Action? Exiting
{
add => _runtime.Exiting += value;
remove => _runtime.Exiting -= value;
}
public bool IsMainThread => _runtime.IsMainThread;
public bool IsInitialized => _runtime.IsInitialized;
public bool IsShutdown => _runtime.IsShutdown;
public DateTimeOffset UtcNow => _runtime.UtcNow;
public double UnscaledTimeSeconds => _runtime.UnscaledTimeSeconds;
public string PersistentDataPath => _runtime.PersistentDataPath;
public string TemporaryDataPath => _runtime.TemporaryDataPath;
public override void _Ready()
{
_mainThreadId = Thread.CurrentThread.ManagedThreadId;
ShrinkRuntimeServices.Configure(this, this, this, this, this, this);
ShrinkEventBusRuntime.ConfigureMainThreadDispatcher(this);
ShrinkDataSaverPlatform.Configure(this, this, this, this);
_runtime.Initialize(this);
SetProcess(true);
if (_signalsConnected || !IsInsideTree())
return;
_tree = GetTree();
_tree.ProcessFrame += OnProcessFrame;
TreeExiting += OnTreeExiting;
TreeExited += OnTreeExited;
_signalsConnected = true;
}
public override void _Process(double delta)
public override void _Process(double delta) => Tick(delta);
public override void _Notification(int what) => _runtime.Notify(what);
public override void _ExitTree()
{
var budget = Math.Max(1, DispatchBudgetPerFrame);
while (budget-- > 0 && _dispatchQueue.TryDequeue(out var action))
action();
PumpNetworkAsync().Forget();
if (_runtime.IsInitialized && !_runtime.IsShutdown)
_runtime.ShutdownAsync().Forget();
}
public override void _Notification(int what)
private void OnProcessFrame() => Tick(GetProcessDeltaTime());
private void Tick(double delta)
{
switch ((long)what)
var frame = Engine.GetProcessFrames();
if (frame == _lastTickFrame)
return;
_lastTickFrame = frame;
_runtime.Tick(delta);
}
private void OnTreeExiting()
{
if (_runtime.IsInitialized && !_runtime.IsShutdown)
_runtime.ShutdownAsync().Forget();
}
private void OnTreeExited()
{
if (_tree != null)
{
case NotificationApplicationPaused:
case NotificationApplicationFocusOut:
Paused?.Invoke();
break;
case NotificationApplicationResumed:
case NotificationApplicationFocusIn:
Resumed?.Invoke();
break;
case NotificationWMCloseRequest:
case NotificationPredelete:
Exiting?.Invoke();
break;
_tree.ProcessFrame -= OnProcessFrame;
_tree = null;
}
TreeExiting -= OnTreeExiting;
TreeExited -= OnTreeExited;
_signalsConnected = false;
if (_runtime.IsInitialized && !_runtime.IsShutdown)
_runtime.ShutdownAsync().Forget();
}
public async UniTask<ShrinkAppRuntime> StartAppAsync(ShrinkAppSettings? settings = null, ShrinkAppServices? services = null)
{
if (_appRuntime?.IsRunning == true) return _appRuntime;
_appRuntime = new ShrinkAppRuntime(this, settings, services);
await _appRuntime.StartAsync();
return _appRuntime;
}
public UniTask<ShrinkAppRuntime> StartAppAsync(ShrinkAppSettings? settings = null,
ShrinkAppServices? services = null) => _runtime.StartAppAsync(settings, services);
public async UniTask ShutdownAppAsync()
{
if (_appRuntime == null) return;
await _appRuntime.ShutdownAsync();
_appRuntime = null;
}
public UniTask ShutdownAsync() => _runtime.ShutdownAsync();
public bool TryPost(Action action)
{
if (action == null) throw new ArgumentNullException(nameof(action));
_dispatchQueue.Enqueue(action);
return true;
}
public UniTask ShutdownAppAsync() => _runtime.StopAppAsync();
public void AddNetworkService(ShrinkNetworkService service)
{
if (service == null) throw new ArgumentNullException(nameof(service));
if (_networkServices.ContainsKey(service)) return;
var queue = new ShrinkNetworkDispatchQueue(Math.Max(1, NetworkDispatchBudgetPerFrame * 4));
service.DispatchScheduler = queue;
_networkServices.Add(service, queue);
}
public bool TryPost(Action action) => _runtime.TryPost(action);
public bool RemoveNetworkService(ShrinkNetworkService service)
{
if (!_networkServices.Remove(service, out var queue)) return false;
service.DispatchScheduler = ShrinkNetworkDispatchSchedulers.Inline;
queue.Dispose();
return true;
}
public bool TryPostDeferred(Action action) => _runtime.TryPostDeferred(action);
public static ShrinkCodeGenWovenAttribute RequireWoven(Assembly assembly)
{
if (assembly == null) throw new ArgumentNullException(nameof(assembly));
return assembly.GetCustomAttribute<ShrinkCodeGenWovenAttribute>() ??
throw new InvalidOperationException(
$"Assembly '{assembly.GetName().Name}' was not woven by ShrinkSDK.CodeGen. Ensure the package is installed and ShrinkCodeGenEnabled is not false.");
}
public void AddNetworkService(ShrinkNetworkService service) => _runtime.AddNetworkService(service);
public void Log(ShrinkLogLevel level, string message, Exception? exception = null)
{
var text = exception == null ? message : $"{message}{System.Environment.NewLine}{exception}";
if (level >= ShrinkLogLevel.Error) GD.PushError(text);
else if (level >= ShrinkLogLevel.Warning) GD.PushWarning(text);
else GD.Print(text);
}
public bool RemoveNetworkService(ShrinkNetworkService service) => _runtime.RemoveNetworkService(service);
public ValueTask<byte[]> CapturePngAsync(CancellationToken cancellationToken = default)
{
cancellationToken.ThrowIfCancellationRequested();
var image = GetViewport().GetTexture().GetImage();
return ValueTask.FromResult(image.SavePngToBuffer());
}
public static ShrinkCodeGenWovenAttribute RequireWoven(Assembly assembly) =>
ShrinkGodotRuntime.RequireWoven(assembly);
private async UniTaskVoid PumpNetworkAsync()
{
if (_networkPumpRunning) return;
_networkPumpRunning = true;
try
{
foreach (var queue in _networkServices.Values)
await queue.PumpAsync(Math.Max(1, NetworkDispatchBudgetPerFrame));
}
finally
{
_networkPumpRunning = false;
}
}
public void Log(ShrinkLogLevel level, string message, Exception? exception = null) =>
_runtime.Log(level, message, exception);
public ValueTask<byte[]> CapturePngAsync(CancellationToken cancellationToken = default) =>
_runtime.CapturePngAsync(cancellationToken);
}