Commit graph

189 commits

Author SHA1 Message Date
Rémi Verschelde
b8e1d6585c
Merge pull request #69971 from neikeq/csharp-vararg-ret-premature-free
C#: Fix premature free of returned Variant in vararg methods
2022-12-14 23:27:40 +01:00
Ignacio Roldán Etcheverry
833b252ce7 C#: Fix premature free of returned Variant in vararg methods
Notably, this fixes obscure issues after calling `script.New()` when
the returned instance is a `RefCounted`.
2022-12-12 17:54:28 +01:00
Raul Santos
1ab4f26cc4
C#: Fix bindings generator for methods that return signals 2022-12-12 17:04:03 +01:00
Ignacio Roldán Etcheverry
17b2838f39 C#: Cleanup Variant marshaling code in source/bindings generators
This change aims to reduce the number of places that need to be changed
when adding or editing a Godot type to the bindings.

Since the addition of `Variant.From<T>/As<T>` and
`VariantUtils.CreateFrom<T>/ConvertTo<T>`, we can now replace a lot of
the previous code in the bindings generator and the source generators
that specify these conversions for each type manually.

The only exceptions are the generic Godot collections (`Array<T>` and
`Dictionary<TKey, TValue>`) which still use the old version, as that
one cannot be matched by our new conversion methods (limitation in the
language with generics, forcing us to use delegate pointers).

The cleanup applies to:

- Bindings generator:
  - `TypeInterface.cs_variant_to_managed`
  - `TypeInterface.cs_managed_to_variant`
- Source generators:
  - `MarshalUtils.AppendNativeVariantToManagedExpr`
  - `MarshalUtils.AppendManagedToNativeVariantExpr`
  - `MarshalUtils.AppendVariantToManagedExpr`
  - `MarshalUtils.AppendManagedToVariantExpr`
2022-12-02 14:47:12 +01:00
Raul Santos
3ff181096a
C#: Remove VariantSpanDisposer and use constants in stackalloc
- Remove `VariantSpanDisposer`, no need to dispose of the Variant Spans
since we are now borrowing the Variants instead of copying them.
- Remove `VariantSpanExtensions.Cleared` that was only used so the
Span was initialized for `VariantSpanDisposer` to know what to dispose.
- Fix stackalloc Spans to use constant VarArgsSpanThreshold
and avoid bound checks.
2022-11-27 03:04:34 +01:00
Ignacio Roldán Etcheverry
3f645f980c C#: Optimize Variant conversion callbacks
These callbacks are used for marshaling by callables and generic Godot
collections.

C# generics don't support specialization the way C++ templates do.
I knew NativeAOT could optimize away many type checks when the types
are known at compile time, but I didn't trust the JIT would do as good
a job, so I initially went with cached function pointers.

Well, it turns out the JIT is also very good at optimizing in this
scenario, so I'm changing the methods to do the conversion directly,
rather than returning a function pointer for the conversion.

The methods were moved to `VariantUtils`, and were renamed from
`GetFromVariantCallback/GetToVariantCallback` to `ConvertTo/CreateFrom`.

The new implementation looks like it goes through many `if` checks
at runtime to find the right branch for the type, but in practice it
works pretty much like template specialization. The JIT only generates
code for the relevant branch. Together with inlining, the result is
very close or the same as doing the conversion manually:

```cs
godot_variant variant;

int foo = variant.Int;
int bar = VariantUtils.ConvertTo<int>(variant);
```

If the type is a generic Godot collection, the conversion still goes
through a function pointer call.

The new code happens to be much shorter as well, with the file going
from 1057 lines to 407.

Side note: `Variant.cs` was mistakenly created in the wrong folder,
so I moved it to the `Core` folder.
2022-11-25 03:14:10 +01:00
Ignacio Roldán Etcheverry
282bd37e5c C#: Remove need for reflection to invoking callable delegates
We aim to make the C# API reflection-free, mainly for concerns about
performance, and to be able to target NativeAOT in refletion-free mode,
which reduces the binary size.

One of the main usages of reflection still left was the dynamic
invokation of callable delegates, and for some time I wasn't sure
I would find an alternative solution that I'd be happy with.

The new solution uses trampoline functions to invoke the delegates:

```
static void Trampoline(object delegateObj, NativeVariantPtrArgs args, out godot_variant ret)
{
    if (args.Count != 1)
        throw new ArgumentException($"Callable expected 1 arguments but received {args.Count}.");

    string res = ((Func<int, string>)delegateObj)(
        VariantConversionCallbacks.GetToManagedCallback<int>()(args[0])
    );

    ret = VariantConversionCallbacks.GetToVariantCallback<string>()(res);
}

Callable.CreateWithUnsafeTrampoline((int num) => "Foo" + num, &Trampoline);
```

Of course, this is too much boilerplate for user code. To improve this,
the `Callable.From` methods were added. These are overloads that take
`Action` and `Func` delegates, which covers the most common use cases:
lambdas and method groups:

```
// Lambda
Callable.From((int num) => "Foo" + num);

// Method group
string AppendNum(int num) => "Foo" + num;
Callable.From(AppendNum);
```

Unfortunately, due to limitations in the C# language, implicit
conversions from delegates to `Callable` are not supported.

`Callable.From` does not support custom delegates. These should be
uncommon, but the Godot C# API actually uses them for event signals.
As such, the bindings generator was updated to generate trampoline
functions for event signals. It was also optimized to use `Action`
instead of a custom delegate for parameterless signals, which removes
the need for the trampoline functions for those signals.

The change to reflection-free invokation removes one of the last needs
for `ConvertVariantToManagedObjectOfType`. The only remaining usage is
from calling script constructors with parameters from the engine
(`CreateManagedForGodotObjectScriptInstance`). Once that one is made
reflection-free, `ConvertVariantToManagedObjectOfType` can be removed.
2022-10-30 01:24:15 +02:00
Raul Santos
333f88dc49
Guard against more potential conflicts in C# bindings generator 2022-10-15 12:47:10 +02:00
Aaron Franke
2cea42cc7f
Rename Projection matrix to columns 2022-10-04 12:34:19 -05:00
Raul Santos
70b4533c47
C#: Add documentation to signal delegates 2022-09-16 09:56:59 +02:00
Raul Santos
a5ffd25292
C#: Move signal documentation to the event
Move signal documentation from the delegate to the event and also
deprecate the event if the signal is deprecated.
2022-09-15 13:24:41 +02:00
Rémi Verschelde
6c818da55e
Merge pull request #65321 from rburing/physics_server_2d_extension
Create GDExtension classes for PhysicsServer2D
2022-09-05 12:44:58 +02:00
Ricardo Buring
d22ff48b3d Create GDExtension classes for PhysicsServer2D
This allows a 2D physics server created entirely from GDExtension.
Based on the structure of PhysicsServer3DExtension by reduz.
2022-09-04 12:04:08 +02:00
Raul Santos
9a10701c69
C#: Assume 64-bit types when type has no meta
When the C# bindings generator finds a type without meta assume the type
refers to the 64-bit version of the type:
- `float` is converted to `double`
- `int` is converted to `long`
2022-09-01 10:29:52 +02:00
Aaron Franke
10a56981dc
Rename String plus_file to path_join 2022-08-29 19:38:13 -05:00
Raul Santos
9c9b8fcd34
Remove [Signal] attribute from events
- Remove event as a valid target of `SignalAttribute`
- Stop adding the `[Signal]` attribute to events in bindings_generator
- Make bindings_generator use the `EventHandler` suffix to be consistent with the C# source generator
- Remove obsolete comment about the signal's delegate name
2022-08-26 00:53:45 +02:00
Magian
c371d1bac9 C# Generate StringName(SnakeName) for all class members 2022-08-25 23:07:20 +08:00
Ignacio Roldán Etcheverry
0c30c678f0 C#: Re-introduce generic Godot Array and Dictionary
This new version does not support the following type arguments:

- Generic types
- Array of Godot Object (Godot.Object[]) or derived types

The new implementation uses delegate pointers to call the Variant
conversion methods. We do type checking only once in the static
constructor to get the conversion delegates.
Now, we no longer need to do type checking every time, and we no
longer have to box value types.
This is the best implementation I could come up with, as C# generics
don't support anything similar to C++ template specializations.
2022-08-22 03:36:52 +02:00
Ignacio Roldán Etcheverry
3123be2384 C#: Array, Dictionary and marshaling refactoring
- Array and Dictionary now store `Variant` instead of `System.Object`.
- Removed generic Array and Dictionary.
  They cause too much issues, heavily relying on reflection and
  very limited by the lack of a generic specialization.
- Removed support for non-Godot collections.
  Support for them also relied heavily on reflection for marshaling.
  Support for them will likely be re-introduced in the future, but
  it will have to rely on source generators instead of reflection.
- Reduced our use of reflection.
  The remaining usages will be moved to source generators soon.
  The only usage that I'm not sure yet how to replace is dynamic
  invocation of delegates.
2022-08-22 03:36:52 +02:00
Ignacio Roldán Etcheverry
344f5028d4 C#: Add dedicated Variant struct, replacing System.Object 2022-08-22 03:36:52 +02:00
Ignacio Roldán Etcheverry
18f805b3aa C#: Upgrade to .NET 6 (5.0 -> 6.0) 2022-08-22 03:36:51 +02:00
Ignacio Roldán Etcheverry
e22dd3bc6a C#: Static marshaling for bindings and source generators
Previously, we added source generators for invoking/accessing methods,
properties and fields in scripts. This freed us from the overhead of
reflection. However, the generated code still used our dynamic
marshaling functions, which do runtime type checking and box value
types.

This commit changes the bindings and source generators to include
'static' marshaling. Based on the types known at compile time, now
we generate the appropriate marshaling call for each type.
2022-08-22 03:36:51 +02:00
Ignacio Roldán Etcheverry
92503ae8db C#: Add source generator for properties and exports default values
The editor no longer needs to create temporary instances to get the
default values. The initializer values of the exported properties are
still evaluated at runtime. For example, in the following example,
`GetInitialValue()` will be called when first looks for default values:

```
[Export] int MyValue = GetInitialValue();
```

Exporting fields with a non-supported type now results in a compiler
error rather than a runtime error when the script is used.
2022-08-22 03:36:51 +02:00
Ignacio Roldán Etcheverry
88e367a406 C#/netcore: Add base desktop game export implementation
This base implementation is still very barebones but it defines the path
for how exporting will work (at least when embedding the .NET runtime).

Many manual steps are still needed, which should be automatized in the
future. For example, in addition to the API assemblies, now you also
need to copy the GodotPlugins assembly to each game project.
2022-08-22 03:36:51 +02:00
Ignacio Roldán Etcheverry
f88d8902cf C#: Ensure native handles are freed after switch to .NET Core
Finalizers are longer guaranteed to be called on exit now that
we switched to .NET Core. This results in native instances leaking.

The only solution I can think of so far is to keep a list of all
instances alive to dispose when the AssemblyLoadContext.Unloading
event is raised.
2022-08-22 03:36:51 +02:00
Ignacio Roldán Etcheverry
4d710bf659 C#: Add initial implementation of source generator for script members
This replaces the way we invoke methods and set/get properties.
This first iteration rids us of runtime type checking in those
cases, as it's now done at compile time.
Later it will also stop needing the use of reflection. After that,
we will only depend on reflection for generic Godot Array and
Dictionary. We're stuck with reflection in generic collections
for now as C# doesn't support generic/template specialization.

This is only the initial implementation. Further iterations are
coming, specially once we switch to the native extension system
which completely changes the way members are accessed/invoked.
For example, with the native extension system we will likely need
to create `UnmanagedCallersOnly` invoke wrapper methods and return
function pointers to the engine.

Other kind of members, like event signals will be receiving the
same treatment in the future.
2022-08-22 03:36:51 +02:00
Ignacio Roldán Etcheverry
e5e7a795b1 C#: Code cleanup and greatly reduce use of C# pointers 2022-08-22 03:36:51 +02:00
Ignacio Roldán Etcheverry
f9a67ee9da C#: Begin move to .NET Core
We're targeting .NET 5 for now to make development easier while
.NET 6 is not yet released.

TEMPORARY REGRESSIONS
---------------------

Assembly unloading is not implemented yet. As such, many Godot
resources are leaked at exit. This will be re-implemented later
together with assembly hot-reloading.
2022-08-22 03:35:59 +02:00
Ignacio Roldán Etcheverry
513ee857a9 C#: Restructure code prior move to .NET Core
The main focus here was to remove the majority of code that relied on
Mono's embedding APIs, specially the reflection APIs. The embedding
APIs we still use are the bare minimum we need for things to work.
A lot of code was moved to C#. We no longer deal with any managed
objects (`MonoObject*`, and such) in native code, and all marshaling
is done in C#.

The reason for restructuring the code and move away from embedding APIs
is that once we move to .NET Core, we will be limited by the much more
minimal .NET hosting.

PERFORMANCE REGRESSIONS
-----------------------

Some parts of the code were written with little to no concern about
performance. This includes code that calls into script methods and
accesses script fields, properties and events.
The reason for this is that all of that will be moved to source
generators, so any work prior to that would be a waste of time.

DISABLED FEATURES
-----------------

Some code was removed as it no longer makes sense (or won't make sense
in the future).
Other parts were commented out with `#if 0`s and TODO warnings because
it doesn't make much sense to work on them yet as those parts will
change heavily when we switch to .NET Core but also when we start
introducing source generators.
As such, the following features were disabled temporarily:
- Assembly-reloading (will be done with ALCs in .NET Core).
- Properties/fields exports and script method listing (will be
  handled by source generators in the future).
- Exception logging in the editor and stack info for errors.
- Exporting games.
- Building of C# projects. We no longer copy the Godot API assemblies
  to the project directory, so MSBuild won't be able to find them. The
  idea is to turn them into NuGet packages in the future, which could
  also be obtained from local NuGet sources during development.
2022-08-22 03:35:59 +02:00
Ignacio Roldán Etcheverry
124fbf95f8 C#: Move marshaling logic and generated glue to C#
We will be progressively moving most code to C#.
The plan is to only use Mono's embedding APIs to set things at launch.
This will make it much easier to later support CoreCLR too which
doesn't have rich embedding APIs.

Additionally the code in C# is more maintainable and makes it easier
to implement new features, e.g.: runtime codegen which we could use to
avoid using reflection for marshaling everytime a field, property or
method is accessed.

SOME NOTES ON INTEROP

We make the same assumptions as GDNative about the size of the Godot
structures we use. We take it a bit further by also assuming the layout
of fields in some cases, which is riskier but let's us squeeze out some
performance by avoiding unnecessary managed to native calls.

Code that deals with native structs is less safe than before as there's
no RAII and copy constructors in C#. It's like using the GDNative C API
directly. One has to take special care to free values they own.
Perhaps we could use roslyn analyzers to check this, but I don't know
any that uses attributes to determine what's owned or borrowed.

As to why we maily use pointers for native structs instead of ref/out:
- AFAIK (and confirmed with a benchmark) ref/out are pinned
  during P/Invoke calls and that has a cost.
- Native struct fields can't be ref/out in the first place.
- A `using` local can't be passed as ref/out, only `in`. Calling a
  method or property on an `in` value makes a silent copy, so we want
  to avoid `in`.

REGARDING THE BUILD SYSTEM

There's no longer a `mono_glue=yes/no` SCons options. We no longer
need to build with `mono_glue=no`, generate the glue and then build
again with `mono_glue=yes`. We build only once and generate the glue
(which is in C# now).
However, SCons no longer builds the C# projects for us. Instead one
must run `build_assemblies.py`, e.g.:
```sh
%godot_src_root%/modules/mono/build_scripts/build_assemblies.py \
        --godot-output-dir=%godot_src_root%/bin \
        --godot-target=release_debug`
```
We could turn this into a custom build target, but I don't know how
to do that with SCons (it's possible with Meson).

OTHER NOTES

Most of the moved code doesn't follow the C# naming convention and
still has the word Mono in the names despite no longer dealing with
Mono's embedding APIs. This is just temporary while transitioning,
to make it easier to understand what was moved where.
2022-08-22 03:35:59 +02:00
reduz
455c06ecd4 Implement Vector4, Vector4i, Projection
Implement built-in classes Vector4, Vector4i and Projection.

* Two versions of Vector4 (float and integer).
* A Projection class, which is a 4x4 matrix specialized in projection types.

These types have been requested for a long time, but given they were very corner case they were not added before.
Because in Godot 4, reimplementing parts of the rendering engine is now possible, access to these types (heavily used by the rendering code) becomes a necessity.

**Q**: Why Projection and not Matrix4?
**A**: Godot does not use Matrix2, Matrix3, Matrix4x3, etc. naming convention because, within the engine, these types always have a *purpose*. As such, Godot names them: Transform2D, Transform3D or Basis. In this case, this 4x4 matrix is _always_ used as a _Projection_, hence the naming.
2022-07-23 14:00:01 +02:00
Raul Santos
f9c43c5489
Add C# support for bitfield enums (flags) 2022-07-06 17:49:37 +02:00
reduz
5ac42cf576 Implement a BitField hint
Allows to specify the binder that an enum must be treated as a bitfield.
2022-07-05 22:13:37 +02:00
bruvzg
860e24683f
Make enum/constant binds 64-bit. 2022-06-17 16:36:26 +03:00
Raul Santos
8dec74f22f
Generate typed array parameters in C# bindings
Adds support for generating C# bindings that use the generic `Array<T>`
type instead of the non-generic `Array` type when the registered ClassDB
method specifies the array element type.
2022-06-03 05:17:53 +02:00
reduz
746dddc067 Replace most uses of Map by HashMap
* Map is unnecessary and inefficient in almost every case.
* Replaced by the new HashMap.
* Renamed Map to RBMap and Set to RBSet for cases that still make sense
  (order matters) but use is discouraged.

There were very few cases where replacing by HashMap was undesired because
keeping the key order was intended.
I tried to keep those (as RBMap) as much as possible, but might have missed
some. Review appreciated!
2022-05-16 10:37:48 +02:00
reduz
8b7c7f5a75 Add a new HashMap implementation
Adds a new, cleaned up, HashMap implementation.

* Uses Robin Hood Hashing (https://en.wikipedia.org/wiki/Hash_table#Robin_Hood_hashing).
* Keeps elements in a double linked list for simpler, ordered, iteration.
* Allows keeping iterators for later use in removal (Unlike Map<>, it does not do much
  for performance vs keeping the key, but helps replace old code).
* Uses a more modern C++ iterator API, deprecates the old one.
* Supports custom allocator (in case there is a wish to use a paged one).

This class aims to unify all the associative template usage and replace it by this one:
* Map<> (whereas key order does not matter, which is 99% of cases)
* HashMap<>
* OrderedHashMap<>
* OAHashMap<>
2022-05-12 11:21:29 +02:00
Aaron Franke
b831fb0a54
Rename Transform2D "elements" to "columns" 2022-04-29 08:02:39 -05:00
bruvzg
9381acb6a4
Make FileAccess and DirAccess classes reference counted. 2022-04-11 13:28:51 +03:00
Raul Santos
83e0e13f4a
Support static methods in C# bindings generator 2022-03-22 19:36:57 +01:00
Raul Santos
4bbfd20aa9
Ignore PhysicsServer3DExtension class in C#
PhysicsServer3DExtension inherits from PhysicsServer3D which is a
singleton class, since singleton classes are generated as static in C#
it would generate invalid C# so for now we'll be
ignoring PhysicsServer3DExtension.
2022-03-18 17:28:48 +01:00
Raul Santos
eaddb79ec6
Refactor bbcode_to_xml into multiple specific methods
The specific `_append_xml_*` methods implement the logic that generates
the proper XML documentation for the given BBCode tag and target and
appends it to the output.
2022-03-03 23:35:10 +01:00
Raul Santos
84615b4b53
Find inherited members in C# documentation generator 2022-03-03 19:53:06 +01:00
Raul Santos
42989befd6
Add theme_item support to C# documentation generator 2022-03-03 18:54:49 +01:00
Raul Santos
e601c9eb8f
Fix checking for @GlobalScope in C# documentation generator 2022-03-03 18:54:41 +01:00
Raul Santos
424817039a
Check for missing methods/members in C# documentation generator
- Outputs errors for missing members or methods when generating the C#
documentation.
- Hardcodes a special case for the `_init` method, in C# we'll reference
the constructor.
- Ignores properties with slashes (since they are not declared in C# and
can't be referenced in the documentation).
2022-03-03 18:53:15 +01:00
Raul Santos
47a7d85cc4
Fix references to global constants in C# documentation generator
Tries to find the referenced constants in the GlobalScope
if not found in the target class or if no class is specified.
2022-03-03 18:53:15 +01:00
Rémi Verschelde
b8b4580448
Style: Cleanup single-line blocks, semicolons, dead code
Remove currently unused implementation of TextureBasisU, could be re-added
later on if needed and ported.
2022-02-16 14:06:29 +01:00
Raul Santos
f380a8e0ec Support signals in C# documentation 2022-02-10 16:02:31 +01:00
bruvzg
244db37508
Cleanup and move char functions to the char_utils.h header. 2022-02-04 11:35:01 +02:00