base structure

This commit is contained in:
redglow
2026-07-17 09:59:07 +02:00
parent e560a743fb
commit 96fffb2f9e
25 changed files with 466 additions and 55 deletions
@@ -5,7 +5,7 @@ using Microsoft.Extensions.DependencyInjection;
namespace GodotHostTest.Game;
public partial class GameRootScope : RootScope
public partial class GameRootServiceSource : RootServiceSource
{
[Export] private TargetSpawner _targetSpawner = null!;
+5
View File
@@ -0,0 +1,5 @@
using OwofGames.GodotLume;
namespace GodotHostTest.Game;
public class LevelScope: RootScope;
+3 -1
View File
@@ -6,7 +6,7 @@ using GodotHostTest.Interfaces;
namespace GodotHostTest.Game;
public partial class Score : Control
public partial class Score : Control, IScore
{
[Export] private AnimationPlayer _animationPlayer = null!;
[Export] private Label _label = null!;
@@ -34,4 +34,6 @@ public partial class Score : Control
{
_label.Text = $"Score: {_score}";
}
int IScore.Score => _score;
}
+1 -1
View File
@@ -1,7 +1,7 @@
[gd_scene format=3 uid="uid://brbufibn7hi3o"]
[ext_resource type="Script" uid="uid://dc5mvle8lc40j" path="res://Game/Projectile.cs" id="1_80yud"]
[ext_resource type="Script" uid="uid://qjonl8stia46" path="res://GodotDI/Scope.cs" id="2_3kmdq"]
[ext_resource type="Script" uid="uid://qjonl8stia46" path="res://addons/GodotDI/ServiceSource.cs" id="2_3kmdq"]
[ext_resource type="Texture2D" uid="uid://y1ros3y7hag2" path="res://icon.svg" id="3_1i54g"]
[node name="Projectile" type="Node2D" unique_id=1686616504]
-6
View File
@@ -1,6 +0,0 @@
using System;
namespace GodotHostTest.GodotDI;
[AttributeUsage(AttributeTargets.Field)]
public class InjectAttribute: Attribute;
-29
View File
@@ -1,29 +0,0 @@
using System;
using System.Reflection;
using Godot;
using Microsoft.Extensions.DependencyInjection;
namespace GodotHostTest.GodotDI;
public partial class Scope : Node
{
[Export] protected Node?[] InjectedNodes = [];
internal void ResolveInjectedNodes(IServiceProvider serviceProvider)
{
// resolve the injected nodes
// TODO: move to source generator, make it the only way for injection
foreach (var node in InjectedNodes)
{
if (node == null) continue;
foreach (var field in node.GetType()
.GetFields(BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic))
{
if (field.GetCustomAttribute<InjectAttribute>() == null) continue;
var fieldType = field.FieldType;
var service = serviceProvider.GetRequiredService(fieldType);
field.SetValue(node, service);
}
}
}
}
-10
View File
@@ -5,16 +5,6 @@ namespace GodotHostTest.Interfaces;
/// </summary>
public interface IScore
{
/// <summary>
/// A target has been hit.
/// </summary>
void TargetHit();
/// <summary>
/// A target has timed out.
/// </summary>
void TargetTimedOut();
/// <summary>
/// The current score.
/// </summary>
+90
View File
@@ -0,0 +1,90 @@
using System;
using System.Collections.Concurrent;
using System.Diagnostics.CodeAnalysis;
using System.Linq;
using System.Reflection;
using Godot;
namespace GodotHostTest.addons.godot_di;
/// <summary>
/// Taken from https://github.com/godotengine/godot-proposals/issues/12294
/// </summary>
public static class GodotScriptPathCache
{
private static readonly ConcurrentDictionary<Type, string> TypeToPath = new();
private static readonly ConcurrentDictionary<string, Type> PathToType = new();
private static readonly Type GodotObject = typeof(GodotObject);
private static readonly Type ScriptPathAttribute = typeof(ScriptPathAttribute);
private static AssemblyLoadEventHandler? _assemblyLoadEventHandler;
private static void InitializeIfNeeded()
{
if (_assemblyLoadEventHandler != null) return;
Initialize();
System.Runtime.Loader.AssemblyLoadContext.GetLoadContext(Assembly.GetExecutingAssembly())!
.Unloading += _ => { Deinitialize(); };
}
private static void Initialize()
{
GD.Print($"Initializing {nameof(GodotScriptPathCache)}");
TypeToPath.Clear();
PathToType.Clear();
_assemblyLoadEventHandler = (sender, args) => CacheScriptsInAssembly(args.LoadedAssembly);
AppDomain.CurrentDomain.AssemblyLoad += _assemblyLoadEventHandler;
foreach (var assembly in AppDomain.CurrentDomain.GetAssemblies())
CacheScriptsInAssembly(assembly);
return;
void CacheScriptsInAssembly(Assembly assembly)
{
foreach (var type in assembly.GetTypes()
.Where(t => t.IsClass)
.Where(t => t.IsSubclassOf(GodotObject)))
// get script path attribute
if (type.GetCustomAttributes(ScriptPathAttribute, false).FirstOrDefault() is ScriptPathAttribute
scriptPath)
{
TypeToPath[type] = scriptPath.Path;
PathToType[scriptPath.Path] = type;
}
}
}
private static void Deinitialize()
{
GD.Print($"Deinitializing {nameof(GodotScriptPathCache)}");
AppDomain.CurrentDomain.AssemblyLoad -= _assemblyLoadEventHandler;
_assemblyLoadEventHandler = null;
TypeToPath.Clear();
PathToType.Clear();
}
public static bool TryGetScriptPath(Type type, [MaybeNullWhen(false)] out string path)
{
InitializeIfNeeded();
return TypeToPath.TryGetValue(type, out path);
}
public static Script GetScriptFromType(Type type)
{
InitializeIfNeeded();
return TryGetScriptPath(type, out string path)
? GD.Load<Script>(path)
: throw new InvalidOperationException("Script path not found in cache.");
}
public static Script GetScriptFromType<T>()
{
InitializeIfNeeded();
return GetScriptFromType(typeof(T));
}
public static bool TryGetTypeFromPath(string path, [MaybeNullWhen(false)] out Type type)
{
InitializeIfNeeded();
return PathToType.TryGetValue(path, out type);
}
}
+6
View File
@@ -0,0 +1,6 @@
using System;
namespace GodotHostTest.GodotDI;
[AttributeUsage(AttributeTargets.Field | AttributeTargets.Method)]
public class InjectAttribute: Attribute;
+64
View File
@@ -0,0 +1,64 @@
namespace GodotHostTest.addons.godot_di;
// RandomIntEditor.cs
#if TOOLS
using Godot;
public partial class RandomIntEditor : EditorProperty
{
// The main control for editing the property.
private Button _propertyControl = new Button();
// An internal value of the property.
private int _currentValue = 0;
// A guard against internal changes when the property is updated.
private bool _updating = false;
public RandomIntEditor()
{
// Add the control as a direct child of EditorProperty node.
AddChild(_propertyControl);
// Make sure the control is able to retain the focus.
AddFocusable(_propertyControl);
// Setup the initial state and connect to the signal to track changes.
RefreshControlText();
_propertyControl.Pressed += OnButtonPressed;
}
private void OnButtonPressed()
{
// Ignore the signal if the property is currently being updated.
if (_updating)
{
return;
}
// Generate a new random integer between 0 and 99.
_currentValue = (int)GD.Randi() % 100;
RefreshControlText();
EmitChanged(GetEditedProperty(), _currentValue);
}
public override void _UpdateProperty()
{
// Read the current value from the property.
var newValue = (int)GetEditedObject().Get(GetEditedProperty());
if (newValue == _currentValue)
{
return;
}
// Update the control with the new value.
_updating = true;
_currentValue = newValue;
RefreshControlText();
_updating = false;
}
private void RefreshControlText()
{
_propertyControl.Text = $"Value: {_currentValue}";
}
}
#endif
@@ -4,13 +4,14 @@ using Godot;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using OwofGames.GodotHost;
using OwofGames.GodotLume.Microsoft.DependencyInjection;
namespace GodotHostTest.GodotDI;
/// <summary>
/// The base class for a root scope. Implement this class and its abstract methods to kick off the DI system.
/// </summary>
public abstract partial class RootScope : Scope, ISceneInstantiator
public abstract partial class RootServiceSource : ServiceSource, ISceneInstantiator
{
private Host? _host;
@@ -22,15 +23,16 @@ public abstract partial class RootScope : Scope, ISceneInstantiator
set => _host = value;
}
private ILogger<RootScope>? _logger;
private ILogger<RootServiceSource>? _logger;
private ILogger<RootScope> Logger => _logger ??= Host.GetLogger<RootScope>();
private ILogger<RootServiceSource> Logger => _logger ??= Host.GetLogger<RootServiceSource>();
public override void _EnterTree()
{
// create the host
Host = new HostBuilder()
.SetServiceCollectionBuilder(InnerConfigure)
.SetServiceProviderFactory(new LumeServiceProviderFactory())
.Build();
// resolve nodes
@@ -53,7 +55,7 @@ public abstract partial class RootScope : Scope, ISceneInstantiator
public Node Instantiate(PackedScene packedScene)
{
var node = packedScene.Instantiate();
var scope = node.GetChildren().OfType<Scope>().SingleOrDefault();
var scope = node.GetChildren().OfType<ServiceSource>().SingleOrDefault();
if (scope == null)
{
Logger.LogDebug(
+31
View File
@@ -0,0 +1,31 @@
#if TOOLS
using Godot;
using GodotHostTest.addons.godot_di;
namespace GodotHostTest.GodotDI;
public partial class ScopeInspectorPlugin : EditorInspectorPlugin
{
public override bool _CanHandle(GodotObject @object)
{
var result = @object.GetScript().AsGodotObject() is CSharpScript script &&
GodotScriptPathCache.TryGetTypeFromPath(script.ResourcePath, out var type) &&
type.IsAssignableTo(typeof(ServiceSource));
return result;
}
public override bool _ParseProperty(GodotObject @object, Variant.Type type, string name, PropertyHint hintType,
string hintString,
PropertyUsageFlags usageFlags, bool wide)
{
// We handle properties of type integer.
if (name != "_serviceScope") return false;
// Create an instance of the custom property editor and register
// it to a specific property path.
AddPropertyEditor(name, new ScopePickerEditor());
// Inform the editor to remove the default property editor for
// this property type.
return true;
}
}
#endif
+95
View File
@@ -0,0 +1,95 @@
using System;
using System.Linq;
using Godot;
namespace GodotHostTest.GodotDI;
public partial class ScopePickerEditor : EditorProperty
{
/// <summary>
/// The "combo box" that picks a choice from the scopes.
/// </summary>
private OptionButton _optionButton = new();
/// <summary>
/// The currently chosen type.
/// </summary>
private string _currentType;
/// <summary>
/// All the known fully qualified names for scopes.
/// </summary>
private string[] _fullyQualifiedNames;
/// <summary>
/// A guard against internal changes while the property is being updated.
/// </summary>
private bool _updating;
public ScopePickerEditor()
{
// save all the known fully qualified names
_fullyQualifiedNames = ScopeTypesAndNames.GetQualifiedNames().ToArray();
// fill the options button
for (var i = 0; i < _fullyQualifiedNames.Length; i++)
{
// root scope is always the first, and root scope = not scoped
_optionButton.AddItem(
i == 0
? "not a scope boundary"
: ScopeTypesAndNames.GetSimpleNameFromQualifiedName(_fullyQualifiedNames[i]), i);
}
// add the control as a direct child of EditorProperty node.
AddChild(_optionButton);
// make sure the control is able to retain the focus.
AddFocusable(_optionButton);
// initialize the starting value
_currentType = _fullyQualifiedNames[0];
// update the property when the button value changes
_optionButton.ItemSelected += OnOptionButtonItemSelected;
}
public override void _UpdateProperty()
{
// get the new value and immediately return if it's already the selected one.
var newValue = GetEditedObject().Get(GetEditedProperty()).AsString();
if (newValue == _currentType) return;
_updating = true;
try
{
var nameIndex = Array.IndexOf(_fullyQualifiedNames, newValue);
if (nameIndex < 0)
{
GD.PushWarning($"Could not find name {newValue} in the list of scope names, resetting to root scope");
_currentType = _fullyQualifiedNames[0];
EmitChanged(GetEditedProperty(), _currentType);
return;
}
_currentType = newValue;
UpdateControl();
}
finally
{
_updating = false;
}
}
private void OnOptionButtonItemSelected(long index)
{
_currentType = _fullyQualifiedNames[index];
UpdateControl();
EmitChanged(GetEditedProperty(), _currentType);
}
private void UpdateControl()
{
_optionButton.Selected = Array.IndexOf(_fullyQualifiedNames, _currentType);
}
}
+88
View File
@@ -0,0 +1,88 @@
using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using Godot;
using OwofGames.GodotLume;
namespace GodotHostTest.GodotDI;
public static class ScopeTypesAndNames
{
private static readonly ConcurrentDictionary<Type, string> TypeToQualifiedName = new();
private static readonly ConcurrentDictionary<string, Type> QualifiedNameToType = new();
private static readonly ConcurrentDictionary<string, string> QualifiedNameToSimpleName = new();
private static readonly Type RootScopeType = typeof(RootScope);
private static AssemblyLoadEventHandler? _assemblyLoadEventHandler;
private static void InitializeIfNeeded()
{
if (_assemblyLoadEventHandler != null) return;
Initialize();
System.Runtime.Loader.AssemblyLoadContext.GetLoadContext(Assembly.GetExecutingAssembly())!
.Unloading += _ => { Deinitialize(); };
}
private static void Initialize()
{
GD.Print($"Initializing {nameof(ScopeTypesAndNames)}");
TypeToQualifiedName.Clear();
QualifiedNameToType.Clear();
QualifiedNameToSimpleName.Clear();
_assemblyLoadEventHandler = (sender, args) => CacheScriptsInAssembly(args.LoadedAssembly);
AppDomain.CurrentDomain.AssemblyLoad += _assemblyLoadEventHandler;
foreach (var assembly in AppDomain.CurrentDomain.GetAssemblies())
CacheScriptsInAssembly(assembly);
return;
void CacheScriptsInAssembly(Assembly assembly)
{
foreach (var type in assembly.GetTypes()
.Where(t => t.IsClass)
.Where(t => t == RootScopeType || t.IsSubclassOf(RootScopeType)))
{
if (type.AssemblyQualifiedName == null)
{
GD.PrintErr("Assembly qualified name of {type} is null");
continue;
}
TypeToQualifiedName[type] = type.AssemblyQualifiedName;
QualifiedNameToType[type.AssemblyQualifiedName] = type;
QualifiedNameToSimpleName[type.AssemblyQualifiedName] = type.Name;
}
}
}
private static void Deinitialize()
{
GD.Print($"Deinitializing {nameof(ScopeTypesAndNames)}");
AppDomain.CurrentDomain.AssemblyLoad -= _assemblyLoadEventHandler;
_assemblyLoadEventHandler = null;
TypeToQualifiedName.Clear();
QualifiedNameToType.Clear();
QualifiedNameToSimpleName.Clear();
}
public static IEnumerable<string> GetQualifiedNames()
{
InitializeIfNeeded();
return from p in TypeToQualifiedName
orderby p.Key == RootScopeType ? 0 : 1
select p.Value;
}
public static Type GetType(string qualifiedName)
{
InitializeIfNeeded();
return QualifiedNameToType[qualifiedName];
}
public static string GetSimpleNameFromQualifiedName(string qualifiedName)
{
InitializeIfNeeded();
return QualifiedNameToSimpleName[qualifiedName];
}
}
+58
View File
@@ -0,0 +1,58 @@
using System;
using System.Reflection;
using Godot;
using Microsoft.Extensions.DependencyInjection;
using OwofGames.GodotLume;
namespace GodotHostTest.GodotDI;
[Icon("res://addons/GodotDI/ServiceSource.svg")]
public partial class ServiceSource : Node
{
[Export] private string _serviceScope = typeof(RootScope).AssemblyQualifiedName!;
[Export] protected Node?[] InjectedNodes = [];
internal void ResolveInjectedNodes(IServiceProvider serviceProvider)
{
// if this service source must also act as a scope, create the scope and use its service provider
if (_serviceScope != "")
{
serviceProvider = serviceProvider
.CreateScope()
.ServiceProvider;
}
// resolve the injected nodes against the chosen service provider
// TODO: move to source generator, make it the only way for injection
foreach (var node in InjectedNodes)
{
if (node == null) continue;
var nodeType = node.GetType();
foreach (var field in nodeType
.GetFields(BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic))
{
if (field.GetCustomAttribute<InjectAttribute>() == null) continue;
var fieldType = field.FieldType;
var service = serviceProvider.GetRequiredService(fieldType);
field.SetValue(node, service);
}
foreach (var method in nodeType.GetMethods(BindingFlags.Instance | BindingFlags.Public |
BindingFlags.NonPublic))
{
if (method.GetCustomAttribute<InjectAttribute>() == null) continue;
var parameters = method.GetParameters();
var values = new object?[parameters.Length];
var i = 0;
foreach (var parameter in parameters)
{
var parameterType = parameter.ParameterType;
var service = serviceProvider.GetRequiredService(parameterType);
values[i++] = service;
}
method.Invoke(node, values);
}
}
}
}
+2 -2
View File
@@ -1,7 +1,7 @@
{
"sdk": {
"version": "9.0.0",
"version": "10.0.0",
"rollForward": "latestMajor",
"allowPrerelease": true
"allowPrerelease": false
}
}
+6
View File
@@ -24,5 +24,11 @@
<PackageReference Include="Microsoft.Extensions.FileProviders.Physical" Version="10.0.0"/>
<PackageReference Include="Microsoft.Extensions.Logging" Version="10.0.0"/>
<PackageReference Include="Microsoft.Extensions.Logging.Configuration" Version="10.0.0"/>
<Reference Include="OwofGames.GodotLume">
<HintPath>..\OwofGames.Godot\OwofGames.GodotLume\bin\Debug\net8.0\OwofGames.GodotLume.dll</HintPath>
</Reference>
<Reference Include="OwofGames.GodotLume.Microsoft.DependencyInjection">
<HintPath>..\OwofGames.Godot\OwofGames.GodotLume.Microsoft.DependencyInjection\bin\Debug\net8.0\OwofGames.GodotLume.Microsoft.DependencyInjection.dll</HintPath>
</Reference>
</ItemGroup>
</Project>
+6 -1
View File
@@ -1,5 +1,10 @@
<wpf:ResourceDictionary xml:space="preserve" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" xmlns:s="clr-namespace:System;assembly=mscorlib" xmlns:ss="urn:shemas-jetbrains-com:settings-storage-xaml" xmlns:wpf="http://schemas.microsoft.com/winfx/2006/xaml/presentation">
<s:Boolean x:Key="/Default/AddReferences/RecentPaths/=_002Fhome_002Fredglow_002Fsources_002FOwofGames_002EGodot_002FOwofGames_002EGodotHost_002Fbin_002FDebug_002Fnet8_002E0_002FOwofGames_002EGodotHost_002Edll/@EntryIndexedValue">True</s:Boolean>
<s:Boolean x:Key="/Default/AddReferences/RecentPaths/=_002Fhome_002Fredglow_002Fsources_002FOwofGames_002EGodot_002FOwofGames_002EGodotHost_002Fbin_002FDebug_002Fnet8_002E0_002FOwofGames_002EGodotLogger_002Edll/@EntryIndexedValue">True</s:Boolean>
<s:Boolean x:Key="/Default/AddReferences/RecentPaths/=_002Fhome_002Fredglow_002Fsources_002FOwofGames_002EGodot_002FOwofGames_002EGodotLume_002EMicrosoft_002EDependencyInjection_002Fbin_002FDebug_002Fnet8_002E0_002FOwofGames_002EGodotLume_002EMicrosoft_002EDependencyInjection_002Edll/@EntryIndexedValue">True</s:Boolean>
<s:Boolean x:Key="/Default/AddReferences/RecentPaths/=_002Fhome_002Fredglow_002Fsources_002FOwofGames_002EGodot_002FOwofGames_002EGodotLume_002Fbin_002FDebug_002Fnet8_002E0_002FOwofGames_002EGodotLume_002Edll/@EntryIndexedValue">True</s:Boolean>
<s:String x:Key="/Default/CodeInspection/ExcludedFiles/FilesAndFoldersToSkip2/=7020124F_002D9FFC_002D4AC3_002D8F3D_002DAAB8E0240759_002Ff_003AEnumerable_002Ecs_002Fl_003A_002E_002E_003F_002E_002E_003F_002Econfig_003FJetBrains_003FRider2026_002E1_003Fresharper_002Dhost_003FDecompilerCache_003Fdecompiler_003F71c28e8d0d254cb69b7b78690e099f6183800_003Fa8_003F2e82b19d_003FEnumerable_002Ecs/@EntryIndexedValue">ForceIncluded</s:String>
<s:String x:Key="/Default/CodeInspection/ExcludedFiles/FilesAndFoldersToSkip2/=7020124F_002D9FFC_002D4AC3_002D8F3D_002DAAB8E0240759_002Ff_003AThrowHelper_002Ecs_002Fl_003A_002E_002E_003F_002E_002E_003F_002Econfig_003FJetBrains_003FRider2026_002E1_003Fresharper_002Dhost_003FDecompilerCache_003Fdecompiler_003F71c28e8d0d254cb69b7b78690e099f6183800_003F72_003F2da75270_003FThrowHelper_002Ecs/@EntryIndexedValue">ForceIncluded</s:String>
<s:String x:Key="/Default/Environment/Hierarchy/Build/BuildTool/DotNetCliExePath/@EntryValue">/usr/lib/dotnet/dotnet</s:String>
<s:String x:Key="/Default/Environment/Hierarchy/Build/BuildTool/CustomBuildToolPath/@EntryValue">/usr/lib/dotnet/sdk/10.0.109/MSBuild.dll</s:String></wpf:ResourceDictionary>
<s:String x:Key="/Default/Environment/Hierarchy/Build/BuildTool/CustomBuildToolPath/@EntryValue">/usr/lib/dotnet/sdk/10.0.109/MSBuild.dll</s:String>
</wpf:ResourceDictionary>
+4
View File
@@ -24,6 +24,10 @@ window/stretch/aspect="expand"
project/assembly_name="godot-host-test"
[editor_plugins]
enabled=PackedStringArray("res://addons/GodotDI/plugin.cfg")
[physics]
3d/physics_engine="Jolt Physics"