mirror of
https://github.com/aharabada/glitchy-engine-beef.git
synced 2026-09-05 13:01:52 +00:00
Fixed calling engine functions from scripts
- Removed mono references in generator - Implemented StringView type in C#
This commit is contained in:
@@ -427,13 +427,18 @@ public class Entity : EngineObject
|
||||
/// <returns>The new <see cref="Entity"/>.</returns>
|
||||
public static Entity CreateInstance(Entity entity)
|
||||
{
|
||||
if (entity == null)
|
||||
{
|
||||
throw new ArgumentException("The provided instance must not be null!", nameof(entity));
|
||||
}
|
||||
|
||||
ScriptGlue.Entity_CreateInstance(entity.UUID, out UUID newEntityId);
|
||||
|
||||
return new Entity(newEntityId);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Will be executed once after the entity has be created.
|
||||
/// Will be called once after the entity has be created.
|
||||
/// </summary>
|
||||
protected internal virtual void OnCreate() { }
|
||||
|
||||
@@ -443,7 +448,7 @@ public class Entity : EngineObject
|
||||
protected internal virtual void OnUpdate(float deltaTime) { }
|
||||
|
||||
/// <summary>
|
||||
/// Will be executed once when the entity is being destroyed.
|
||||
/// Will be called once when the entity is being destroyed.
|
||||
/// </summary>
|
||||
protected internal virtual void OnDestroy() { }
|
||||
}
|
||||
|
||||
@@ -0,0 +1,73 @@
|
||||
using GlitchyEngine.Core;
|
||||
using System;
|
||||
using System.Diagnostics;
|
||||
using System.Runtime.InteropServices;
|
||||
using System.Text;
|
||||
|
||||
namespace GlitchyEngine.Native;
|
||||
|
||||
[DebuggerDisplay("{ToString(),raw}")]
|
||||
[StructLayout(LayoutKind.Sequential, Pack = 0)]
|
||||
[EngineClass("System.StringView")]
|
||||
internal unsafe struct StringView
|
||||
{
|
||||
public byte* Utf8Ptr;
|
||||
public long Length;
|
||||
|
||||
public StringView()
|
||||
{
|
||||
Utf8Ptr = null;
|
||||
Length = 0;
|
||||
}
|
||||
|
||||
public StringView(byte* utf8Ptr, long length)
|
||||
{
|
||||
Utf8Ptr = utf8Ptr;
|
||||
Length = length;
|
||||
}
|
||||
|
||||
public override string? ToString()
|
||||
{
|
||||
if (Utf8Ptr == null)
|
||||
return null;
|
||||
|
||||
if (Length == 0)
|
||||
return string.Empty;
|
||||
|
||||
if (Length is < 0 or > int.MaxValue)
|
||||
{
|
||||
throw new InvalidOperationException($"String length is invalid: {Length}.");
|
||||
}
|
||||
|
||||
return Encoding.UTF8.GetString(Utf8Ptr, (int)Length);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Creates a String<see cref="StringView"/>View that can be passed to native code. This method allocates native memory that must be freed using
|
||||
/// <see cref="NativeMemory.Free"/>.
|
||||
/// </summary>
|
||||
/// <param name="s">The string to convert.</param>
|
||||
/// <returns>The <see cref="StringView"/> pointing to the native memory containing the UTF8-text; or null, if <see cref="s"/> was null.</returns>
|
||||
/// <remarks>
|
||||
/// The allocated string is guaranteed to have a null terminator.
|
||||
/// The null terminator is not counted into the length of the resulting <see cref="StringView"/>.
|
||||
/// </remarks>
|
||||
public static StringView FromManagedString(string? s)
|
||||
{
|
||||
if (s == null)
|
||||
return new StringView();
|
||||
|
||||
int maxByteCount = Encoding.UTF8.GetMaxByteCount(s.Length);
|
||||
|
||||
byte* pointer = (byte*)NativeMemory.Alloc((nuint) checked (maxByteCount + 1));
|
||||
int bytes = Encoding.UTF8.GetBytes((ReadOnlySpan<char>) s, new Span<byte>(pointer, maxByteCount));
|
||||
pointer[bytes] = (byte) 0;
|
||||
|
||||
return new StringView(pointer, bytes);
|
||||
}
|
||||
|
||||
public static void FreeNativeMemory(StringView s)
|
||||
{
|
||||
NativeMemory.Free(s.Utf8Ptr);
|
||||
}
|
||||
}
|
||||
@@ -17,6 +17,6 @@ public static class Physics2D
|
||||
ScriptGlue.Physics2D_GetGravity(out float2 gravity);
|
||||
return gravity;
|
||||
}
|
||||
set => ScriptGlue.Physics2D_SetGravity(in value);
|
||||
set => ScriptGlue.Physics2D_SetGravity(value);
|
||||
}
|
||||
}
|
||||
+36
-16
@@ -8,18 +8,24 @@ using System.Collections.Generic;
|
||||
using System.Diagnostics;
|
||||
using System.IO;
|
||||
using System.Reflection;
|
||||
using System.Runtime.CompilerServices;
|
||||
using System.Runtime.InteropServices;
|
||||
using System.Runtime.Loader;
|
||||
using GlitchyEngine.Native;
|
||||
using GlitchyEngine.Physics;
|
||||
|
||||
namespace GlitchyEngine;
|
||||
|
||||
/// <summary>
|
||||
/// Contains functions pointer to engine functions that can be called form scripts.
|
||||
/// </summary>
|
||||
[StructLayout(LayoutKind.Sequential)]
|
||||
internal unsafe partial struct EngineFunctions
|
||||
{
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// All methods in here are glued to the ScriptGlue.bf in the engine.
|
||||
/// Provides the interface between engine and scripts.
|
||||
/// </summary>
|
||||
internal static unsafe partial class ScriptGlue
|
||||
{
|
||||
@@ -187,7 +193,16 @@ internal static unsafe partial class ScriptGlue
|
||||
|
||||
static ScriptMethods HasMethod(Type type, string methodName, ScriptMethods methodFlag)
|
||||
{
|
||||
MethodInfo? methodInfo = type.GetMethod(methodName, BindingFlags.NonPublic | BindingFlags.Instance | BindingFlags.DeclaredOnly);
|
||||
MethodInfo? methodInfo = null;
|
||||
Type? currentType = type;
|
||||
|
||||
while (methodInfo == null && currentType != typeof(Entity) && currentType != null)
|
||||
{
|
||||
methodInfo = currentType.GetMethod(methodName,
|
||||
BindingFlags.NonPublic | BindingFlags.Instance | BindingFlags.DeclaredOnly);
|
||||
|
||||
currentType = currentType.BaseType;
|
||||
}
|
||||
|
||||
return methodInfo != null ? methodFlag : ScriptMethods.None;
|
||||
}
|
||||
@@ -280,8 +295,8 @@ internal static unsafe partial class ScriptGlue
|
||||
Log.Exception(e);
|
||||
}
|
||||
}
|
||||
|
||||
[UnmanagedCallersOnly]
|
||||
|
||||
[UnmanagedCallersOnly(CallConvs = [typeof(CallConvCdecl)])]
|
||||
public static void InvokeEntityOnUpdate(UUID entityId, float deltaTime)
|
||||
{
|
||||
try
|
||||
@@ -340,7 +355,7 @@ internal static unsafe partial class ScriptGlue
|
||||
|
||||
Debug.Assert(scriptInstance != null, "Failed to create script instance.");
|
||||
|
||||
EntityScriptInstances.Add(entityId, (scriptInstance!, scriptType));
|
||||
EntityScriptInstances.Add(entityId, (scriptInstance, scriptType));
|
||||
}
|
||||
catch (Exception e)
|
||||
{
|
||||
@@ -489,6 +504,8 @@ internal static unsafe partial class ScriptGlue
|
||||
|
||||
#endregion
|
||||
|
||||
#region Custom engine call implementations
|
||||
|
||||
public static void Entity_AddComponent(UUID entityId, Type componentType)
|
||||
{
|
||||
ComponentTypeFunctions[componentType].AddComponent(entityId);
|
||||
@@ -520,8 +537,8 @@ internal static unsafe partial class ScriptGlue
|
||||
|
||||
public static void Serialization_SerializeField(IntPtr serializationContext, SerializationType type, string fieldName, object? valueObject, string fullTypeName)
|
||||
{
|
||||
byte* fieldNameConverted = (byte*)Marshal.StringToCoTaskMemUTF8(fieldName);
|
||||
byte* fullTypeNameConverted = (byte*)Marshal.StringToCoTaskMemUTF8(fullTypeName);
|
||||
StringView fieldNameConverted = StringView.FromManagedString(fieldName);
|
||||
StringView fullTypeNameConverted = StringView.FromManagedString(fullTypeName);
|
||||
|
||||
void* valueObjectConverted = null;
|
||||
bool deleteValueObject = false;
|
||||
@@ -530,29 +547,32 @@ internal static unsafe partial class ScriptGlue
|
||||
{
|
||||
case SerializationType.String:
|
||||
case SerializationType.Enum:
|
||||
if (valueObject is String stringValue)
|
||||
if (valueObject is string stringValue)
|
||||
{
|
||||
valueObjectConverted = (void*)Marshal.StringToCoTaskMemUTF8(stringValue);
|
||||
StringView nativeString = StringView.FromManagedString(stringValue);
|
||||
valueObjectConverted = nativeString.Utf8Ptr;
|
||||
deleteValueObject = true;
|
||||
}
|
||||
break;
|
||||
default:
|
||||
if (valueObject is not null)
|
||||
{
|
||||
void* p = &valueObject;
|
||||
#pragma warning disable CS8500 // This takes the address of, gets the size of, or declares a pointer to a managed type
|
||||
object?* objectRef = &valueObject;
|
||||
// Skip Object Header (IntPtr) + Method Table (IntPtr)
|
||||
valueObjectConverted = (byte*)*(IntPtr*)p + sizeof(IntPtr);
|
||||
float i = *(float*)valueObjectConverted;
|
||||
valueObjectConverted = (byte*)*(IntPtr*)objectRef + sizeof(IntPtr);
|
||||
}
|
||||
break;
|
||||
}
|
||||
|
||||
_engineFunctions.Serialization_SerializeField((void*)serializationContext, type, fieldNameConverted, valueObjectConverted, fullTypeNameConverted);
|
||||
|
||||
Marshal.FreeCoTaskMem((IntPtr)fieldNameConverted);
|
||||
Marshal.FreeCoTaskMem((IntPtr)fullTypeNameConverted);
|
||||
|
||||
NativeMemory.Free(fieldNameConverted.Utf8Ptr);
|
||||
NativeMemory.Free(fullTypeNameConverted.Utf8Ptr);
|
||||
|
||||
if (deleteValueObject)
|
||||
Marshal.FreeCoTaskMem((IntPtr)valueObjectConverted);
|
||||
NativeMemory.Free(valueObjectConverted);
|
||||
}
|
||||
|
||||
#endregion Custom engine call implementations
|
||||
}
|
||||
|
||||
@@ -11,6 +11,7 @@ using System.Runtime.CompilerServices;
|
||||
using System.Runtime.InteropServices;
|
||||
using System.Text;
|
||||
using GlitchyEngine.Editor;
|
||||
using GlitchyEngine.Native;
|
||||
|
||||
namespace GlitchyEngine.Serialization;
|
||||
|
||||
@@ -105,13 +106,13 @@ public class DeserializationObject
|
||||
return type;
|
||||
}
|
||||
|
||||
public DeserializationObject? GetDeserializedObject(UUID id)
|
||||
public unsafe DeserializationObject? GetDeserializedObject(UUID id)
|
||||
{
|
||||
DeserializationObject context;
|
||||
|
||||
if (DeserializedClasses.TryGetValue(id, out context))
|
||||
return context;
|
||||
|
||||
|
||||
ScriptGlue.Serialization_GetObject(_internalContext, id, out IntPtr contextPtr);
|
||||
|
||||
if (contextPtr == IntPtr.Zero)
|
||||
@@ -148,15 +149,8 @@ public class DeserializationObject
|
||||
}
|
||||
|
||||
[StructLayout(LayoutKind.Explicit)]
|
||||
public struct DataHelper
|
||||
internal struct DataHelper
|
||||
{
|
||||
[StructLayout(LayoutKind.Sequential)]
|
||||
public unsafe struct StringView
|
||||
{
|
||||
public byte* Utf8Ptr;
|
||||
public long Length;
|
||||
}
|
||||
|
||||
[FieldOffset(0)]
|
||||
public EngineObjectReferenceHelper EngineObjectReference;
|
||||
|
||||
@@ -187,27 +181,11 @@ public class DeserializationObject
|
||||
|
||||
ScriptGlue.Serialization_DeserializeField(_internalContext, expectedType, completeFieldName, rawData, out SerializationType actualType);
|
||||
|
||||
string? GetString()
|
||||
{
|
||||
if (dataHelper.String.Utf8Ptr == null)
|
||||
return null;
|
||||
|
||||
if (dataHelper.String.Length == 0)
|
||||
return string.Empty;
|
||||
|
||||
if (dataHelper.String.Length is < 0 or > int.MaxValue)
|
||||
{
|
||||
throw new InvalidOperationException($"String length is invalid: {dataHelper.String.Length}");
|
||||
}
|
||||
|
||||
return Encoding.UTF8.GetString(dataHelper.String.Utf8Ptr, (int)dataHelper.String.Utf8Ptr);
|
||||
}
|
||||
|
||||
object? value = actualType switch
|
||||
{
|
||||
SerializationType.Bool => *(bool*)rawData,
|
||||
SerializationType.Char => *(char*)rawData,
|
||||
SerializationType.String => GetString(),
|
||||
SerializationType.String => dataHelper.String.ToString(),
|
||||
SerializationType.Int8 => *(sbyte*)rawData,
|
||||
SerializationType.Int16 => *(short*)rawData,
|
||||
SerializationType.Int32 => *(int*)rawData,
|
||||
@@ -219,7 +197,7 @@ public class DeserializationObject
|
||||
SerializationType.Float => *(float*)rawData,
|
||||
SerializationType.Double => *(double*)rawData,
|
||||
SerializationType.Decimal => *(decimal*)rawData,
|
||||
SerializationType.Enum => GetString(),
|
||||
SerializationType.Enum => dataHelper.String.ToString(),
|
||||
SerializationType.EngineObjectReference => dataHelper.EngineObjectReference,
|
||||
SerializationType.ObjectReference => dataHelper.UUID,
|
||||
_ => NoValueDeserialized
|
||||
@@ -522,7 +500,7 @@ public class DeserializationObject
|
||||
}
|
||||
catch
|
||||
{
|
||||
Log.Error($"Failed to parse \"{valueName}\" as enum-type \"{enumType}\"");
|
||||
Log.Error($"Failed to deserialize field \"{fieldName}\": Could not parse \"{valueName}\" as enum-type \"{enumType}\"");
|
||||
}
|
||||
|
||||
return NoValueDeserialized;
|
||||
|
||||
Reference in New Issue
Block a user