From 344f5028d48d4a5caf321abdf023c34f52aae0a4 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Ignacio=20Rold=C3=A1n=20Etcheverry?= Date: Thu, 28 Jul 2022 17:41:49 +0200 Subject: [PATCH] C#: Add dedicated Variant struct, replacing System.Object --- modules/mono/csharp_script.cpp | 2 +- .../ExportedFields.cs | 3 +- .../ExportedProperties.cs | 3 +- .../ScriptBoilerplate.cs | 2 +- .../Godot.SourceGenerators/MarshalType.cs | 3 +- .../Godot.SourceGenerators/MarshalUtils.cs | 24 +- .../GodotTools/Build/BuildOutputView.cs | 2 +- .../GodotTools/GodotTools/GodotSharpEditor.cs | 6 +- .../GodotTools/Ides/GodotIdeManager.cs | 2 +- .../GodotTools/Ides/Rider/RiderPathManager.cs | 2 +- modules/mono/editor/bindings_generator.cpp | 41 +- modules/mono/editor/bindings_generator.h | 2 +- .../CharacterBody2D/basic_movement.cs | 2 +- .../CharacterBody3D/basic_movement.cs | 2 +- .../glue/GodotSharp/GodotSharp/Core/Array.cs | 6 + .../Core/Bridge/CSharpInstanceBridge.cs | 6 +- .../GodotSharp/GodotSharp/Core/Dictionary.cs | 7 + .../Core/NativeInterop/Marshaling.cs | 55 +- .../Core/NativeInterop/NativeFuncs.cs | 3 + .../NativeInterop/NativeFuncs.extended.cs | 38 + .../Core/NativeInterop/VariantUtils.cs | 14 - .../GodotSharp/GodotSharp/Core/Object.base.cs | 2 - .../GodotSharp/GodotSharp/GodotSharp.csproj | 1 + .../glue/GodotSharp/GodotSharp/Variant.cs | 665 ++++++++++++++++++ modules/mono/glue/runtime_interop.cpp | 7 +- 25 files changed, 776 insertions(+), 124 deletions(-) create mode 100644 modules/mono/glue/GodotSharp/GodotSharp/Variant.cs diff --git a/modules/mono/csharp_script.cpp b/modules/mono/csharp_script.cpp index c69a149d9ca..182970e18d5 100644 --- a/modules/mono/csharp_script.cpp +++ b/modules/mono/csharp_script.cpp @@ -104,7 +104,7 @@ Error CSharpLanguage::execute_file(const String &p_path) { return OK; } -extern void *godotsharp_pinvoke_funcs[185]; +extern void *godotsharp_pinvoke_funcs[186]; [[maybe_unused]] volatile void **do_not_strip_godotsharp_pinvoke_funcs; #ifdef TOOLS_ENABLED extern void *godotsharp_editor_pinvoke_funcs[30]; diff --git a/modules/mono/editor/Godot.NET.Sdk/Godot.SourceGenerators.Sample/ExportedFields.cs b/modules/mono/editor/Godot.NET.Sdk/Godot.SourceGenerators.Sample/ExportedFields.cs index 7b106ef63cb..86c639f7b6c 100644 --- a/modules/mono/editor/Godot.NET.Sdk/Godot.SourceGenerators.Sample/ExportedFields.cs +++ b/modules/mono/editor/Godot.NET.Sdk/Godot.SourceGenerators.Sample/ExportedFields.cs @@ -80,7 +80,6 @@ namespace Godot.SourceGenerators.Sample [Export] private Vector3[] field_Vector3Array = { Vector3.Up, Vector3.Down, Vector3.Left, Vector3.Right }; [Export] private Color[] field_ColorArray = { Colors.Aqua, Colors.Aquamarine, Colors.Azure, Colors.Beige }; [Export] private Godot.Object[] field_GodotObjectOrDerivedArray = { null }; - [Export] private object[] field_SystemObjectArray = { 0, 1f, 2d, "foo", Vector3i.Up }; // Generics [Export] private Godot.Collections.Dictionary field_GodotGenericDictionary = @@ -105,7 +104,7 @@ namespace Godot.SourceGenerators.Sample new System.Collections.Generic.List { "elem1", "elem2", "elem3" }; // Variant - [Export] private object field_SystemObject = "foo"; + [Export] private Variant field_Variant = "foo"; // Classes [Export] private Godot.Object field_GodotObjectOrDerived; diff --git a/modules/mono/editor/Godot.NET.Sdk/Godot.SourceGenerators.Sample/ExportedProperties.cs b/modules/mono/editor/Godot.NET.Sdk/Godot.SourceGenerators.Sample/ExportedProperties.cs index 71025c1d43f..665eb7f2a88 100644 --- a/modules/mono/editor/Godot.NET.Sdk/Godot.SourceGenerators.Sample/ExportedProperties.cs +++ b/modules/mono/editor/Godot.NET.Sdk/Godot.SourceGenerators.Sample/ExportedProperties.cs @@ -80,7 +80,6 @@ namespace Godot.SourceGenerators.Sample [Export] private Vector3[] property_Vector3Array { get; set; } = { Vector3.Up, Vector3.Down, Vector3.Left, Vector3.Right }; [Export] private Color[] property_ColorArray { get; set; } = { Colors.Aqua, Colors.Aquamarine, Colors.Azure, Colors.Beige }; [Export] private Godot.Object[] property_GodotObjectOrDerivedArray { get; set; } = { null }; - [Export] private object[] property_SystemObjectArray { get; set; } = { 0, 1f, 2d, "foo", Vector3i.Up }; // Generics [Export] private Godot.Collections.Dictionary property_GodotGenericDictionary { get; set; } = @@ -105,7 +104,7 @@ namespace Godot.SourceGenerators.Sample new System.Collections.Generic.List { "elem1", "elem2", "elem3" }; // Variant - [Export] private object property_SystemObject { get; set; } = "foo"; + [Export] private Variant property_Variant { get; set; } = "foo"; // Classes [Export] private Godot.Object property_GodotObjectOrDerived { get; set; } diff --git a/modules/mono/editor/Godot.NET.Sdk/Godot.SourceGenerators.Sample/ScriptBoilerplate.cs b/modules/mono/editor/Godot.NET.Sdk/Godot.SourceGenerators.Sample/ScriptBoilerplate.cs index bfc8ef2fb5c..a1667dbb8f9 100644 --- a/modules/mono/editor/Godot.NET.Sdk/Godot.SourceGenerators.Sample/ScriptBoilerplate.cs +++ b/modules/mono/editor/Godot.NET.Sdk/Godot.SourceGenerators.Sample/ScriptBoilerplate.cs @@ -30,7 +30,7 @@ namespace Godot.SourceGenerators.Sample { public partial class NesterClass : RefCounted { - public override object _Get(StringName property) => null; + public override Variant _Get(StringName property) => default; } } } diff --git a/modules/mono/editor/Godot.NET.Sdk/Godot.SourceGenerators/MarshalType.cs b/modules/mono/editor/Godot.NET.Sdk/Godot.SourceGenerators/MarshalType.cs index 3b7a50e7a66..e967cbe6629 100644 --- a/modules/mono/editor/Godot.NET.Sdk/Godot.SourceGenerators/MarshalType.cs +++ b/modules/mono/editor/Godot.NET.Sdk/Godot.SourceGenerators/MarshalType.cs @@ -53,7 +53,6 @@ namespace Godot.SourceGenerators Vector3Array, ColorArray, GodotObjectOrDerivedArray, - SystemObjectArray, SystemArrayOfSupportedType, // Generics @@ -66,7 +65,7 @@ namespace Godot.SourceGenerators GenericIEnumerable, // Variant - SystemObject, + Variant, // Classes GodotObjectOrDerived, diff --git a/modules/mono/editor/Godot.NET.Sdk/Godot.SourceGenerators/MarshalUtils.cs b/modules/mono/editor/Godot.NET.Sdk/Godot.SourceGenerators/MarshalUtils.cs index cd4c8ff828e..d132b6304fe 100644 --- a/modules/mono/editor/Godot.NET.Sdk/Godot.SourceGenerators/MarshalUtils.cs +++ b/modules/mono/editor/Godot.NET.Sdk/Godot.SourceGenerators/MarshalUtils.cs @@ -86,7 +86,6 @@ namespace Godot.SourceGenerators MarshalType.Vector3Array => VariantType.PackedVector3Array, MarshalType.ColorArray => VariantType.PackedColorArray, MarshalType.GodotObjectOrDerivedArray => VariantType.Array, - MarshalType.SystemObjectArray => VariantType.Array, MarshalType.SystemArrayOfSupportedType => VariantType.Array, MarshalType.GodotGenericDictionary => VariantType.Dictionary, MarshalType.GodotGenericArray => VariantType.Array, @@ -95,7 +94,7 @@ namespace Godot.SourceGenerators MarshalType.GenericIDictionary => VariantType.Dictionary, MarshalType.GenericICollection => VariantType.Array, MarshalType.GenericIEnumerable => VariantType.Array, - MarshalType.SystemObject => VariantType.Nil, + MarshalType.Variant => VariantType.Nil, MarshalType.GodotObjectOrDerived => VariantType.Object, MarshalType.StringName => VariantType.StringName, MarshalType.NodePath => VariantType.NodePath, @@ -140,8 +139,6 @@ namespace Godot.SourceGenerators return MarshalType.Double; case SpecialType.System_String: return MarshalType.String; - case SpecialType.System_Object: - return MarshalType.SystemObject; default: { var typeKind = type.TypeKind; @@ -175,6 +172,7 @@ namespace Godot.SourceGenerators { Name: "RID" } => MarshalType.RID, { Name: "Callable" } => MarshalType.Callable, { Name: "SignalInfo" } => MarshalType.SignalInfo, + { Name: "Variant" } => MarshalType.Variant, _ => null }; } @@ -198,8 +196,6 @@ namespace Godot.SourceGenerators return MarshalType.Float64Array; case SpecialType.System_String: return MarshalType.StringArray; - case SpecialType.System_Object: - return MarshalType.SystemObjectArray; } if (elementType.SimpleDerivesFrom(typeCache.GodotObjectType)) @@ -323,6 +319,9 @@ namespace Godot.SourceGenerators return null; } + private static StringBuilder Append(this StringBuilder source, string a, string b) + => source.Append(a).Append(b); + private static StringBuilder Append(this StringBuilder source, string a, string b, string c) => source.Append(a).Append(b).Append(c); @@ -346,7 +345,6 @@ namespace Godot.SourceGenerators string c, string d, string e, string f, string g, string h) => source.Append(a).Append(b).Append(c).Append(d).Append(e).Append(f).Append(g).Append(h); - private const string Marshaling = "global::Godot.NativeInterop.Marshaling"; private const string VariantUtils = "global::Godot.NativeInterop.VariantUtils"; public static StringBuilder AppendVariantToManagedExpr(this StringBuilder source, @@ -440,8 +438,6 @@ namespace Godot.SourceGenerators MarshalType.GodotObjectOrDerivedArray => source.Append(VariantUtils, ".ConvertToSystemArrayOfGodotObject<", ((IArrayTypeSymbol)typeSymbol).ElementType.FullQualifiedName(), ">(", inputExpr, ")"), - MarshalType.SystemObjectArray => - source.Append(VariantUtils, ".ConvertToSystemArrayOfVariant(", inputExpr, ")"), MarshalType.SystemArrayOfSupportedType => source.Append(VariantUtils, ".ConvertToSystemArrayOfSupportedType<", ((IArrayTypeSymbol)typeSymbol).ElementType.FullQualifiedName(), ">(", inputExpr, ")"), @@ -466,8 +462,8 @@ namespace Godot.SourceGenerators MarshalType.GenericICollection or MarshalType.GenericIEnumerable => source.Append(VariantUtils, ".ConvertToGenericArrayObject<", ((INamedTypeSymbol)typeSymbol).TypeArguments[0].FullQualifiedName(), ">(", inputExpr, ")"), - MarshalType.SystemObject => - source.Append(Marshaling, ".ConvertVariantToManagedObject(", inputExpr, ")"), + MarshalType.Variant => + source.Append("global::Godot.Variant.CreateCopyingBorrowed(", inputExpr, ")"), MarshalType.GodotObjectOrDerived => source.Append("(", typeSymbol.FullQualifiedName(), ")", VariantUtils, ".ConvertToGodotObject(", inputExpr, ")"), @@ -579,8 +575,6 @@ namespace Godot.SourceGenerators source.Append(VariantUtils, ".CreateFromPackedColorArray(", inputExpr, ")"), MarshalType.GodotObjectOrDerivedArray => source.Append(VariantUtils, ".CreateFromSystemArrayOfGodotObject(", inputExpr, ")"), - MarshalType.SystemObjectArray => - source.Append(VariantUtils, ".CreateFromSystemArrayOfVariant(", inputExpr, ")"), MarshalType.SystemArrayOfSupportedType => source.Append(VariantUtils, ".CreateFromSystemArrayOfSupportedType(", inputExpr, ")"), MarshalType.GodotGenericDictionary => @@ -597,8 +591,8 @@ namespace Godot.SourceGenerators source.Append(VariantUtils, ".CreateFromSystemGenericICollection(", inputExpr, ")"), MarshalType.GenericIEnumerable => source.Append(VariantUtils, ".CreateFromSystemGenericIEnumerable(", inputExpr, ")"), - MarshalType.SystemObject => - source.Append(Marshaling, ".ConvertManagedObjectToVariant(", inputExpr, ")"), + MarshalType.Variant => + source.Append(inputExpr, ".CopyNativeVariant()"), MarshalType.GodotObjectOrDerived => source.Append(VariantUtils, ".CreateFromGodotObject(", inputExpr, ")"), MarshalType.StringName => diff --git a/modules/mono/editor/GodotTools/GodotTools/Build/BuildOutputView.cs b/modules/mono/editor/GodotTools/GodotTools/Build/BuildOutputView.cs index 5ba3e3e4c08..38d2eefd02a 100644 --- a/modules/mono/editor/GodotTools/GodotTools/Build/BuildOutputView.cs +++ b/modules/mono/editor/GodotTools/GodotTools/Build/BuildOutputView.cs @@ -124,7 +124,7 @@ namespace GodotTools.Build throw new IndexOutOfRangeException("Item list index out of range"); // Get correct issue idx from issue list - int issueIndex = (int)(long)_issuesList.GetItemMetadata(idx); + int issueIndex = (int)_issuesList.GetItemMetadata(idx); if (issueIndex < 0 || issueIndex >= _issues.Count) throw new IndexOutOfRangeException("Issue index out of range"); diff --git a/modules/mono/editor/GodotTools/GodotTools/GodotSharpEditor.cs b/modules/mono/editor/GodotTools/GodotTools/GodotSharpEditor.cs index fe83e6a2813..362bb18b364 100644 --- a/modules/mono/editor/GodotTools/GodotTools/GodotSharpEditor.cs +++ b/modules/mono/editor/GodotTools/GodotTools/GodotSharpEditor.cs @@ -175,7 +175,7 @@ namespace GodotTools [UsedImplicitly] public Error OpenInExternalEditor(Script script, int line, int col) { - var editorId = (ExternalEditorId)_editorSettings.GetSetting("mono/editor/external_editor"); + var editorId = (ExternalEditorId)(int)_editorSettings.GetSetting("mono/editor/external_editor"); switch (editorId) { @@ -327,7 +327,7 @@ namespace GodotTools [UsedImplicitly] public bool OverridesExternalEditor() { - return (ExternalEditorId)_editorSettings.GetSetting("mono/editor/external_editor") != ExternalEditorId.None; + return (ExternalEditorId)(int)_editorSettings.GetSetting("mono/editor/external_editor") != ExternalEditorId.None; } public override bool _Build() @@ -521,7 +521,7 @@ namespace GodotTools // Otherwise, if the GC disposes it at a later time, EditorExportPlatformAndroid // will be freed after EditorSettings already was, and its device polling thread // will try to access the EditorSettings singleton, resulting in null dereferencing. - (_exportPluginWeak.GetRef() as ExportPlugin)?.Dispose(); + (_exportPluginWeak.GetRef().AsGodotObject() as ExportPlugin)?.Dispose(); _exportPluginWeak.Dispose(); } diff --git a/modules/mono/editor/GodotTools/GodotTools/Ides/GodotIdeManager.cs b/modules/mono/editor/GodotTools/GodotTools/Ides/GodotIdeManager.cs index 9acdeb4183c..95b60aded12 100644 --- a/modules/mono/editor/GodotTools/GodotTools/Ides/GodotIdeManager.cs +++ b/modules/mono/editor/GodotTools/GodotTools/Ides/GodotIdeManager.cs @@ -76,7 +76,7 @@ namespace GodotTools.Ides public async Task LaunchIdeAsync(int millisecondsTimeout = 10000) { - var editorId = (ExternalEditorId)GodotSharpEditor.Instance.GetEditorInterface() + var editorId = (ExternalEditorId)(int)GodotSharpEditor.Instance.GetEditorInterface() .GetEditorSettings().GetSetting("mono/editor/external_editor"); string editorIdentity = GetExternalEditorIdentity(editorId); diff --git a/modules/mono/editor/GodotTools/GodotTools/Ides/Rider/RiderPathManager.cs b/modules/mono/editor/GodotTools/GodotTools/Ides/Rider/RiderPathManager.cs index 3440eb701ce..a62fe29e7ec 100644 --- a/modules/mono/editor/GodotTools/GodotTools/Ides/Rider/RiderPathManager.cs +++ b/modules/mono/editor/GodotTools/GodotTools/Ides/Rider/RiderPathManager.cs @@ -22,7 +22,7 @@ namespace GodotTools.Ides.Rider public static void Initialize() { var editorSettings = GodotSharpEditor.Instance.GetEditorInterface().GetEditorSettings(); - var editor = (ExternalEditorId)editorSettings.GetSetting("mono/editor/external_editor"); + var editor = (ExternalEditorId)(int)editorSettings.GetSetting("mono/editor/external_editor"); if (editor == ExternalEditorId.Rider) { if (!editorSettings.HasSetting(EditorPathSettingName)) diff --git a/modules/mono/editor/bindings_generator.cpp b/modules/mono/editor/bindings_generator.cpp index 1f6a74ff4b1..50820c63840 100644 --- a/modules/mono/editor/bindings_generator.cpp +++ b/modules/mono/editor/bindings_generator.cpp @@ -105,8 +105,6 @@ StringBuilder &operator<<(StringBuilder &r_sb, const char *p_cstring) { #define C_METHOD_ENGINE_GET_SINGLETON C_NS_MONOUTILS ".EngineGetSingleton" #define C_NS_MONOMARSHAL "Marshaling" -#define C_METHOD_MANAGED_TO_VARIANT C_NS_MONOMARSHAL ".ConvertManagedObjectToVariant" -#define C_METHOD_MANAGED_FROM_VARIANT C_NS_MONOMARSHAL ".ConvertVariantToManagedObject" #define C_METHOD_MONOSTR_TO_GODOT C_NS_MONOMARSHAL ".ConvertStringToNative" #define C_METHOD_MONOSTR_FROM_GODOT C_NS_MONOMARSHAL ".ConvertStringToManaged" #define C_METHOD_MONOARRAY_TO(m_type) C_NS_MONOMARSHAL ".ConvertSystemArrayToNative" #m_type @@ -844,15 +842,12 @@ Error BindingsGenerator::_populate_method_icalls_table(const TypeInterface &p_it } // Get arguments information - int i = 0; for (const ArgumentInterface &iarg : imethod.arguments) { const TypeInterface *arg_type = _get_type_or_null(iarg.type); ERR_FAIL_NULL_V(arg_type, ERR_BUG); // Argument type not found im_unique_sig += ","; im_unique_sig += get_arg_unique_sig(*arg_type); - - i++; } // godot_icall_{argc}_{icallcount} @@ -1011,9 +1006,9 @@ void BindingsGenerator::_generate_global_constants(StringBuilder &p_output) { CRASH_COND(enum_class_name != "Variant"); // Hard-coded... - _log("Declaring global enum '%s' inside static class '%s'\n", enum_proxy_name.utf8().get_data(), enum_class_name.utf8().get_data()); + _log("Declaring global enum '%s' inside struct '%s'\n", enum_proxy_name.utf8().get_data(), enum_class_name.utf8().get_data()); - p_output.append("\npublic static partial class "); + p_output.append("\npublic partial struct "); p_output.append(enum_class_name); p_output.append("\n" OPEN_BLOCK); } @@ -2462,7 +2457,7 @@ Error BindingsGenerator::_generate_cs_native_calls(const InternalCall &p_icall, r_output << INDENT2 "using var variantSpanDisposer = new VariantSpanDisposer(varargs_span);\n"; - r_output << INDENT2 "fixed (godot_variant* varargs = &MemoryMarshal.GetReference(varargs_span).DangerousSelfRef)\n" + r_output << INDENT2 "fixed (godot_variant.movable* varargs = &MemoryMarshal.GetReference(varargs_span))\n" << INDENT2 "fixed (IntPtr* " C_LOCAL_PTRCALL_ARGS " = " "&MemoryMarshal.GetReference(" C_LOCAL_PTRCALL_ARGS "_span))\n" << OPEN_BLOCK_L2; @@ -2470,7 +2465,7 @@ Error BindingsGenerator::_generate_cs_native_calls(const InternalCall &p_icall, r_output << c_in_statements.as_string(); r_output << INDENT3 "for (int i = 0; i < vararg_length; i++) " OPEN_BLOCK - << INDENT4 "varargs[i] = " C_METHOD_MANAGED_TO_VARIANT "(" << vararg_arg << "[i]);\n" + << INDENT4 "varargs[i] = " << vararg_arg << "[i].NativeVar;\n" << INDENT4 C_LOCAL_PTRCALL_ARGS "[" << real_argc_str << " + i] = new IntPtr(&varargs[i]);\n" << CLOSE_BLOCK_L3; @@ -3181,7 +3176,7 @@ bool BindingsGenerator::_arg_default_value_from_variant(const Variant &p_val, Ar switch (p_val.get_type()) { case Variant::NIL: // Either Object type or Variant - r_iarg.default_argument = "null"; + r_iarg.default_argument = "default"; break; // Atomic types case Variant::BOOL: @@ -3352,8 +3347,8 @@ bool BindingsGenerator::_arg_default_value_from_variant(const Variant &p_val, Ar break; } - if (r_iarg.def_param_mode == ArgumentInterface::CONSTANT && r_iarg.type.cname == name_cache.type_Variant && r_iarg.default_argument != "null") { - r_iarg.def_param_mode = ArgumentInterface::NULLABLE_REF; + if (r_iarg.def_param_mode == ArgumentInterface::CONSTANT && r_iarg.type.cname == name_cache.type_Variant && r_iarg.default_argument != "default") { + r_iarg.def_param_mode = ArgumentInterface::NULLABLE_VAL; } return true; @@ -3558,17 +3553,18 @@ void BindingsGenerator::_populate_builtin_type_interfaces() { itype = TypeInterface(); itype.name = "Variant"; itype.cname = itype.name; - itype.proxy_name = "object"; + itype.proxy_name = "Variant"; itype.cs_type = itype.proxy_name; - itype.c_in = "%5using %0 %1_in = " C_METHOD_MANAGED_TO_VARIANT "(%1);\n"; - itype.c_out = "%5return " C_METHOD_MANAGED_FROM_VARIANT "(%1);\n"; + itype.c_in = "%5%0 %1_in = (%0)%1.NativeVar;\n"; + itype.c_out = "%5return Variant.CreateTakingOwnershipOfDisposableValue(%1);\n"; itype.c_arg_in = "&%s_in"; itype.c_type = "godot_variant"; itype.c_type_in = itype.cs_type; itype.c_type_out = itype.cs_type; - itype.c_type_is_disposable_struct = true; - itype.cs_variant_to_managed = C_METHOD_MANAGED_FROM_VARIANT "(%0)"; - itype.cs_managed_to_variant = C_METHOD_MANAGED_TO_VARIANT "(%0)"; + itype.c_type_is_disposable_struct = false; // [c_out] takes ownership + itype.c_ret_needs_default_initialization = true; + itype.cs_variant_to_managed = "Variant.CreateCopyingBorrowed(%0)"; + itype.cs_managed_to_variant = "%0.CopyNativeVariant()"; builtin_types.insert(itype.cname, itype); // Callable @@ -3607,14 +3603,13 @@ void BindingsGenerator::_populate_builtin_type_interfaces() { itype = TypeInterface(); itype.name = "VarArg"; itype.cname = itype.name; - itype.proxy_name = "object[]"; - itype.cs_type = "params object[]"; - itype.cs_in_expr = "%0 ?? Array.Empty()"; + itype.proxy_name = "Variant[]"; + itype.cs_type = "params Variant[]"; + itype.cs_in_expr = "%0 ?? Array.Empty()"; // c_type, c_in and c_arg_in are hard-coded in the generator. // c_out and c_type_out are not applicable to VarArg. itype.c_arg_in = "&%s_in"; - itype.c_type_in = "object[]"; - itype.cs_variant_to_managed = "VariantUtils.ConvertToSystemArray(%0)"; + itype.c_type_in = "Variant[]"; builtin_types.insert(itype.cname, itype); #define INSERT_ARRAY_FULL(m_name, m_type, m_managed_type, m_proxy_t) \ diff --git a/modules/mono/editor/bindings_generator.h b/modules/mono/editor/bindings_generator.h index afdb898b887..c1295385dcc 100644 --- a/modules/mono/editor/bindings_generator.h +++ b/modules/mono/editor/bindings_generator.h @@ -240,7 +240,7 @@ class BindingsGenerator { * Determines whether the native return value of this type must be zero initialized * before its address is passed to ptrcall. This is required for types whose destructor * is called before being assigned the return value by `PtrToArg::encode`, e.g.: - * Array, Dictionary, String, StringName. + * Array, Dictionary, String, StringName, Variant. * It's not necessary to set this to `true` if [c_type_is_disposable_struct] is already `true`. */ bool c_ret_needs_default_initialization = false; diff --git a/modules/mono/editor/script_templates/CharacterBody2D/basic_movement.cs b/modules/mono/editor/script_templates/CharacterBody2D/basic_movement.cs index 2ca81ab7cdf..c34f1a17f3c 100644 --- a/modules/mono/editor/script_templates/CharacterBody2D/basic_movement.cs +++ b/modules/mono/editor/script_templates/CharacterBody2D/basic_movement.cs @@ -9,7 +9,7 @@ public partial class _CLASS_ : _BASE_ public const float JumpVelocity = -400.0f; // Get the gravity from the project settings to be synced with RigidDynamicBody nodes. - public float gravity = (float)ProjectSettings.GetSetting("physics/2d/default_gravity"); + public float gravity = ProjectSettings.GetSetting("physics/2d/default_gravity").AsSingle(); public override void _PhysicsProcess(float delta) { diff --git a/modules/mono/editor/script_templates/CharacterBody3D/basic_movement.cs b/modules/mono/editor/script_templates/CharacterBody3D/basic_movement.cs index a6935fe4974..188bbb775cb 100644 --- a/modules/mono/editor/script_templates/CharacterBody3D/basic_movement.cs +++ b/modules/mono/editor/script_templates/CharacterBody3D/basic_movement.cs @@ -9,7 +9,7 @@ public partial class _CLASS_ : _BASE_ public const float JumpVelocity = 4.5f; // Get the gravity from the project settings to be synced with RigidDynamicBody nodes. - public float gravity = (float)ProjectSettings.GetSetting("physics/3d/default_gravity"); + public float gravity = ProjectSettings.GetSetting("physics/3d/default_gravity").AsSingle(); public override void _PhysicsProcess(float delta) { diff --git a/modules/mono/glue/GodotSharp/GodotSharp/Core/Array.cs b/modules/mono/glue/GodotSharp/GodotSharp/Core/Array.cs index afe295126ea..8ceb7ea882a 100644 --- a/modules/mono/glue/GodotSharp/GodotSharp/Core/Array.cs +++ b/modules/mono/glue/GodotSharp/GodotSharp/Core/Array.cs @@ -714,5 +714,11 @@ namespace Godot.Collections /// /// A string representation of this array. public override string ToString() => _underlyingArray.ToString(); + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static implicit operator Variant(Array from) => Variant.From(from); + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static explicit operator Array(Variant from) => from.AsGodotGenericArray(); } } diff --git a/modules/mono/glue/GodotSharp/GodotSharp/Core/Bridge/CSharpInstanceBridge.cs b/modules/mono/glue/GodotSharp/GodotSharp/Core/Bridge/CSharpInstanceBridge.cs index 9ede67b285e..3636a08377e 100644 --- a/modules/mono/glue/GodotSharp/GodotSharp/Core/Bridge/CSharpInstanceBridge.cs +++ b/modules/mono/glue/GodotSharp/GodotSharp/Core/Bridge/CSharpInstanceBridge.cs @@ -63,7 +63,7 @@ namespace Godot.Bridge var nameManaged = StringName.CreateTakingOwnershipOfDisposableValue( NativeFuncs.godotsharp_string_name_new_copy(CustomUnsafe.AsRef(name))); - object valueManaged = Marshaling.ConvertVariantToManagedObject(CustomUnsafe.AsRef(value)); + Variant valueManaged = Variant.CreateCopyingBorrowed(*value); return godotObject._Set(nameManaged, valueManaged).ToGodotBool(); } @@ -94,9 +94,9 @@ namespace Godot.Bridge var nameManaged = StringName.CreateTakingOwnershipOfDisposableValue( NativeFuncs.godotsharp_string_name_new_copy(CustomUnsafe.AsRef(name))); - object ret = godotObject._Get(nameManaged); + Variant ret = godotObject._Get(nameManaged); - if (ret == null) + if (ret.VariantType == Variant.Type.Nil) { *outRet = default; return godot_bool.False; diff --git a/modules/mono/glue/GodotSharp/GodotSharp/Core/Dictionary.cs b/modules/mono/glue/GodotSharp/GodotSharp/Core/Dictionary.cs index 106cd7619fa..a71ee1190ee 100644 --- a/modules/mono/glue/GodotSharp/GodotSharp/Core/Dictionary.cs +++ b/modules/mono/glue/GodotSharp/GodotSharp/Core/Dictionary.cs @@ -5,6 +5,7 @@ using Godot.NativeInterop; using System.Diagnostics.CodeAnalysis; using System.Runtime.CompilerServices; using System.Linq; +using System.Runtime.CompilerServices; namespace Godot.Collections { @@ -805,5 +806,11 @@ namespace Godot.Collections /// /// A string representation of this dictionary. public override string ToString() => _underlyingDict.ToString(); + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static implicit operator Variant(Dictionary from) => Variant.From(from); + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static explicit operator Dictionary(Variant from) => from.AsGodotGenericDictionary(); } } diff --git a/modules/mono/glue/GodotSharp/GodotSharp/Core/NativeInterop/Marshaling.cs b/modules/mono/glue/GodotSharp/GodotSharp/Core/NativeInterop/Marshaling.cs index 563af91ae58..8802f229b3e 100644 --- a/modules/mono/glue/GodotSharp/GodotSharp/Core/NativeInterop/Marshaling.cs +++ b/modules/mono/glue/GodotSharp/GodotSharp/Core/NativeInterop/Marshaling.cs @@ -148,9 +148,6 @@ namespace Godot.NativeInterop if (typeof(Godot.Object[]).IsAssignableFrom(type)) return Variant.Type.Array; - - if (type == typeof(object[])) - return Variant.Type.Array; } else if (type.IsGenericType) { @@ -178,7 +175,7 @@ namespace Godot.NativeInterop if (typeof(Godot.Object).IsAssignableFrom(type)) return Variant.Type.Object; } - else if (type == typeof(object)) + else if (type == typeof(Variant)) { r_nil_is_variant = true; return Variant.Type.Nil; @@ -315,16 +312,6 @@ namespace Godot.NativeInterop return VariantUtils.CreateFromSystemArrayOfSupportedType(ridArray); case Godot.Object[] godotObjectArray: return VariantUtils.CreateFromSystemArrayOfGodotObject(godotObjectArray); - case object[] objectArray: // Last one to avoid catching others like string[] and Godot.Object[] - { - // The pattern match for `object[]` catches arrays on any reference type, - // so we need to check the actual type to make sure it's truly `object[]`. - if (objectArray.GetType() == typeof(object[])) - return VariantUtils.CreateFromSystemArrayOfVariant(objectArray); - - GD.PushError("Attempted to convert a managed array of unmarshallable element type to Variant."); - return new godot_variant(); - } case Godot.Object godotObject: return VariantUtils.CreateFromGodotObject(godotObject); case StringName stringName: @@ -337,6 +324,8 @@ namespace Godot.NativeInterop return VariantUtils.CreateFromDictionary(godotDictionary); case Collections.Array godotArray: return VariantUtils.CreateFromArray(godotArray); + case Variant variant: + return NativeFuncs.godotsharp_variant_new_copy((godot_variant)variant.NativeVar); case Collections.IGenericGodotDictionary genericGodotDictionary: { var godotDict = genericGodotDictionary.UnderlyingDictionary; @@ -509,8 +498,9 @@ namespace Godot.NativeInterop return ConvertVariantToSystemArrayOfType(p_var, type); else if (type.IsGenericType) return ConvertVariantToManagedObjectOfGenericType(p_var, type); - else if (type == typeof(object)) - return ConvertVariantToManagedObject(p_var); + else if (type == typeof(Variant)) + return Variant.CreateCopyingBorrowed(p_var); + if (ConvertVariantToManagedObjectOfClass(p_var, type, out object? res)) return res; @@ -564,9 +554,6 @@ namespace Godot.NativeInterop if (typeof(Godot.Object[]).IsAssignableFrom(type)) return VariantUtils.ConvertToSystemArrayOfGodotObject(p_var, type); - if (type == typeof(object[])) - return VariantUtils.ConvertToSystemArrayOfVariant(p_var); - GD.PushError("Attempted to convert Variant to array of unsupported element type. Name: " + type.GetElementType()!.FullName + "."); return null; @@ -962,19 +949,6 @@ namespace Godot.NativeInterop // Array - public static object[] ConvertNativeGodotArrayToSystemArray(in godot_array p_array) - { - var array = Collections.Array.CreateTakingOwnershipOfDisposableValue( - NativeFuncs.godotsharp_array_new_copy(p_array)); - - int length = array.Count; - var ret = new object[length]; - - array.CopyTo(ret, 0); // ConvertVariantToManagedObject handled by Collections.Array - - return ret; - } - internal static T[] ConvertNativeGodotArrayToSystemArrayOfType(in godot_array p_array) { var array = Collections.Array.CreateTakingOwnershipOfDisposableValue( @@ -1019,23 +993,6 @@ namespace Godot.NativeInterop return ret; } - public static godot_array ConvertSystemArrayToNativeGodotArray(object[] p_array) - { - int length = p_array.Length; - - if (length == 0) - return NativeFuncs.godotsharp_array_new(); - - using var array = new Collections.Array(); - array.Resize(length); - - for (int i = 0; i < length; i++) - array[i] = p_array[i]; - - var src = (godot_array)array.NativeValue; - return NativeFuncs.godotsharp_array_new_copy(src); - } - public static godot_array ConvertSystemArrayToNativeGodotArray(T[] p_array) { int length = p_array.Length; diff --git a/modules/mono/glue/GodotSharp/GodotSharp/Core/NativeInterop/NativeFuncs.cs b/modules/mono/glue/GodotSharp/GodotSharp/Core/NativeInterop/NativeFuncs.cs index b2df6e16b19..e56e4944b0c 100644 --- a/modules/mono/glue/GodotSharp/GodotSharp/Core/NativeInterop/NativeFuncs.cs +++ b/modules/mono/glue/GodotSharp/GodotSharp/Core/NativeInterop/NativeFuncs.cs @@ -199,6 +199,9 @@ namespace Godot.NativeInterop public static extern void godotsharp_variant_new_string_name(out godot_variant r_dest, in godot_string_name p_s); + [DllImport(GodotDllName)] + public static extern void godotsharp_variant_new_copy(out godot_variant r_dest, in godot_variant p_src); + [DllImport(GodotDllName)] public static extern void godotsharp_variant_new_node_path(out godot_variant r_dest, in godot_node_path p_np); diff --git a/modules/mono/glue/GodotSharp/GodotSharp/Core/NativeInterop/NativeFuncs.extended.cs b/modules/mono/glue/GodotSharp/GodotSharp/Core/NativeInterop/NativeFuncs.extended.cs index 0c49660cf0e..2ea3c18d26a 100644 --- a/modules/mono/glue/GodotSharp/GodotSharp/Core/NativeInterop/NativeFuncs.extended.cs +++ b/modules/mono/glue/GodotSharp/GodotSharp/Core/NativeInterop/NativeFuncs.extended.cs @@ -4,6 +4,44 @@ namespace Godot.NativeInterop { public static partial class NativeFuncs { + public static godot_variant godotsharp_variant_new_copy(in godot_variant src) + { + switch (src.Type) + { + case Variant.Type.Nil: + return default; + case Variant.Type.Bool: + return new godot_variant() { Bool = src.Bool }; + case Variant.Type.Int: + return new godot_variant() { Int = src.Int }; + case Variant.Type.Float: + return new godot_variant() { Float = src.Float }; + case Variant.Type.Vector2: + return new godot_variant() { Vector2 = src.Vector2 }; + case Variant.Type.Vector2i: + return new godot_variant() { Vector2i = src.Vector2i }; + case Variant.Type.Rect2: + return new godot_variant() { Rect2 = src.Rect2 }; + case Variant.Type.Rect2i: + return new godot_variant() { Rect2i = src.Rect2i }; + case Variant.Type.Vector3: + return new godot_variant() { Vector3 = src.Vector3 }; + case Variant.Type.Vector3i: + return new godot_variant() { Vector3i = src.Vector3i }; + case Variant.Type.Plane: + return new godot_variant() { Plane = src.Plane }; + case Variant.Type.Quaternion: + return new godot_variant() { Quaternion = src.Quaternion }; + case Variant.Type.Color: + return new godot_variant() { Color = src.Color }; + case Variant.Type.Rid: + return new godot_variant() { RID = src.RID }; + } + + godotsharp_variant_new_copy(out godot_variant ret, src); + return ret; + } + public static godot_string_name godotsharp_string_name_new_copy(in godot_string_name src) { if (src.IsEmpty) diff --git a/modules/mono/glue/GodotSharp/GodotSharp/Core/NativeInterop/VariantUtils.cs b/modules/mono/glue/GodotSharp/GodotSharp/Core/NativeInterop/VariantUtils.cs index 7aa27c2867c..fe0d7104ea4 100644 --- a/modules/mono/glue/GodotSharp/GodotSharp/Core/NativeInterop/VariantUtils.cs +++ b/modules/mono/glue/GodotSharp/GodotSharp/Core/NativeInterop/VariantUtils.cs @@ -227,14 +227,6 @@ namespace Godot.NativeInterop return CreateFromArray(array); } - public static godot_variant CreateFromSystemArrayOfVariant(object[]? from) - { - if (from == null) - return default; // Nil - using godot_array array = Marshaling.ConvertSystemArrayToNativeGodotArray(from); - return CreateFromArray(array); - } - public static godot_variant CreateFromArray(godot_array from) { NativeFuncs.godotsharp_variant_new_array(out godot_variant ret, from); @@ -671,12 +663,6 @@ namespace Godot.NativeInterop return Marshaling.ConvertNativeGodotArrayToSystemArrayOfGodotObjectType(godotArray, type); } - public static object[] ConvertToSystemArrayOfVariant(in godot_variant p_var) - { - using var godotArray = NativeFuncs.godotsharp_variant_as_array(p_var); - return Marshaling.ConvertNativeGodotArrayToSystemArray(godotArray); - } - public static Array ConvertToGenericArrayObject(in godot_variant p_var) => new(ConvertToArrayObject(p_var)); diff --git a/modules/mono/glue/GodotSharp/GodotSharp/Core/Object.base.cs b/modules/mono/glue/GodotSharp/GodotSharp/Core/Object.base.cs index dd3f8477d9e..04920ccfab3 100644 --- a/modules/mono/glue/GodotSharp/GodotSharp/Core/Object.base.cs +++ b/modules/mono/glue/GodotSharp/GodotSharp/Core/Object.base.cs @@ -1,6 +1,4 @@ using System; -using System.Linq; -using System.Reflection; using System.Runtime.InteropServices; using Godot.Bridge; using Godot.NativeInterop; diff --git a/modules/mono/glue/GodotSharp/GodotSharp/GodotSharp.csproj b/modules/mono/glue/GodotSharp/GodotSharp/GodotSharp.csproj index d95b839767f..0a61069a1e2 100644 --- a/modules/mono/glue/GodotSharp/GodotSharp/GodotSharp.csproj +++ b/modules/mono/glue/GodotSharp/GodotSharp/GodotSharp.csproj @@ -124,6 +124,7 @@ +