feat: automatic injection of elements in scene.

This commit is contained in:
redglow
2026-07-17 15:14:40 +02:00
parent 659baff30c
commit 5ad3af84b2
15 changed files with 86 additions and 219 deletions
@@ -0,0 +1,109 @@
#if TOOLS
using System;
using System.Collections.Concurrent;
using System.Diagnostics.CodeAnalysis;
using System.Linq;
using System.Reflection;
using System.Runtime.Loader;
using Godot;
namespace GodotHostTest.GodotDI.Editor;
/// <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();
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);
}
public static Type? GetCSharpScriptType(this GodotObject node)
{
if (node.GetScript().AsGodotObject() is CSharpScript script &&
TryGetTypeFromPath(script.ResourcePath, out var type))
return type;
return null;
}
public static bool IsServiceSource(this GodotObject node)
{
return node.GetScript().AsGodotObject() is CSharpScript script &&
TryGetTypeFromPath(script.ResourcePath, out var type) &&
type.IsAssignableTo(typeof(ServiceSource));
}
}
#endif
@@ -0,0 +1 @@
uid://brjpccpd5ta6x
+1
View File
@@ -0,0 +1 @@
uid://dtvb8nb6d2j4m
@@ -0,0 +1 @@
uid://cl7d2h5juc2gh
@@ -0,0 +1,97 @@
#if TOOLS
using System;
using System.Linq;
using Godot;
namespace GodotHostTest.GodotDI.Editor;
public partial class ScopePickerEditor : EditorProperty
{
/// <summary>
/// The currently chosen type.
/// </summary>
private string _currentType;
/// <summary>
/// All the known fully qualified names for scopes.
/// </summary>
private string[] _fullyQualifiedNames;
/// <summary>
/// The "combo box" that picks a choice from the scopes.
/// </summary>
private OptionButton _optionButton = new();
/// <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);
}
}
#endif
@@ -0,0 +1 @@
uid://cy4jjk14my305