Upd: Fixed C# script resolution bug, fixed object lookup for interfaces, fixed serialization bug.

This commit is contained in:
Andrei Gagua
2026-05-24 19:45:22 +03:00
parent 54a103d840
commit d6fb11cca3
4 changed files with 242 additions and 124 deletions
@@ -12,6 +12,7 @@ namespace FlaxEngine.Json.JsonCustomSerializers
internal class ExtendedDefaultContractResolver : DefaultContractResolver
{
private readonly Type _flaxType = typeof(Object);
private static readonly JsonConverter InterfaceObjectReferenceConverterInstance = new InterfaceObjectReferenceConverter();
private readonly Type[] AttributesIgnoreList =
{
@@ -33,6 +34,88 @@ namespace FlaxEngine.Json.JsonCustomSerializers
_attributesIgnoreList = isManagedOnly ? AttributesIgnoreListManaged : AttributesIgnoreList;
}
private static bool HasObjectInterfaceReferenceAttribute(IEnumerable<Attribute> attributes)
{
return attributes.Any(x => x is ScriptingObjectInterfaceReferenceAttribute || x is SoftObjectInterfaceReferenceAttribute);
}
private static Type GetCollectionItemType(Type type)
{
if (type.IsArray)
return type.GetElementType();
if (!type.IsGenericType || type == typeof(string))
return null;
var types = type.GetInterfaces().Concat(new[] { type });
var dictionaryType = types.FirstOrDefault(x => x.IsGenericType && x.GetGenericTypeDefinition() == typeof(IDictionary<,>));
if (dictionaryType != null)
return dictionaryType.GetGenericArguments()[1];
var enumerableType = types.FirstOrDefault(x => x.IsGenericType && x.GetGenericTypeDefinition() == typeof(IEnumerable<>));
return enumerableType?.GetGenericArguments()[0];
}
private static void SetupInterfaceObjectReferenceItems(JsonContainerContract contract, Type itemType)
{
if (itemType?.IsInterface == true)
{
contract.ItemReferenceLoopHandling = ReferenceLoopHandling.Serialize;
contract.ItemConverter = InterfaceObjectReferenceConverterInstance;
}
}
private void SetupObjectReferenceProperty(JsonProperty jsonProperty, Type type, IEnumerable<Attribute> attributes)
{
var hasObjectInterfaceReferenceAttribute = HasObjectInterfaceReferenceAttribute(attributes);
if (_flaxType.IsAssignableFrom(type) || (type.IsInterface && hasObjectInterfaceReferenceAttribute))
{
jsonProperty.ReferenceLoopHandling = ReferenceLoopHandling.Serialize;
jsonProperty.Converter = JsonSerializer.ObjectConverter;
}
if (hasObjectInterfaceReferenceAttribute && GetCollectionItemType(type)?.IsInterface == true)
{
jsonProperty.ItemReferenceLoopHandling = ReferenceLoopHandling.Serialize;
jsonProperty.ItemConverter = JsonSerializer.ObjectConverter;
}
}
private sealed class InterfaceObjectReferenceConverter : JsonConverter
{
public override unsafe void WriteJson(JsonWriter writer, object value, Newtonsoft.Json.JsonSerializer serializer)
{
if (value is Object obj)
{
var id = obj.ID;
writer.WriteValue(JsonSerializer.GetStringID(&id));
}
else if (value == null)
{
writer.WriteNull();
}
else
{
serializer.Serialize(writer, value, value.GetType());
}
}
public override object ReadJson(JsonReader reader, Type objectType, object existingValue, Newtonsoft.Json.JsonSerializer serializer)
{
if (reader.TokenType == JsonToken.String && JsonSerializer.TryParseID((string)reader.Value, out var id))
{
return Object.Find(ref id, objectType, true);
}
if (reader.TokenType == JsonToken.Null)
return null;
// objectType is the same interface item type that selected this converter. Passing it back to
// Newtonsoft can cause this converter to be chosen again and recurse until the stack overflows.
return Newtonsoft.Json.Linq.JToken.Load(reader).ToObject<object>(serializer);
}
public override bool CanConvert(Type objectType)
{
return objectType.IsInterface;
}
}
/// <inheritdoc />
protected override JsonContract CreateContract(Type objectType)
{
@@ -47,11 +130,23 @@ namespace FlaxEngine.Json.JsonCustomSerializers
return contract;
}
/// <inheritdoc />
protected override JsonArrayContract CreateArrayContract(Type objectType)
{
var contract = base.CreateArrayContract(objectType);
SetupInterfaceObjectReferenceItems(contract, contract.CollectionItemType);
return contract;
}
/// <inheritdoc />
protected override JsonDictionaryContract CreateDictionaryContract(Type objectType)
{
var contract = base.CreateDictionaryContract(objectType);
SetupInterfaceObjectReferenceItems(contract, contract.DictionaryValueType);
// Override contract to save enums keys as integer
if (contract.DictionaryKeyType?.IsEnum ?? false)
{
@@ -108,11 +203,7 @@ namespace FlaxEngine.Json.JsonCustomSerializers
jsonProperty.Writable = true;
jsonProperty.Readable = true;
if (_flaxType.IsAssignableFrom(f.FieldType))
{
jsonProperty.ReferenceLoopHandling = ReferenceLoopHandling.Serialize;
jsonProperty.Converter = JsonSerializer.ObjectConverter;
}
SetupObjectReferenceProperty(jsonProperty, f.FieldType, attributes);
result.Add(jsonProperty);
}
@@ -151,11 +242,7 @@ namespace FlaxEngine.Json.JsonCustomSerializers
jsonProperty.Writable = true;
jsonProperty.Readable = !isObsolete;
if (_flaxType.IsAssignableFrom(p.PropertyType))
{
jsonProperty.ReferenceLoopHandling = ReferenceLoopHandling.Serialize;
jsonProperty.Converter = JsonSerializer.ObjectConverter;
}
SetupObjectReferenceProperty(jsonProperty, p.PropertyType, attributes);
result.Add(jsonProperty);
}
+46 -56
View File
@@ -618,6 +618,31 @@ namespace FlaxEngine.Json
return id;
}
/// <summary>
/// Tries to parse the given object identifier represented in the internal serialization format.
/// </summary>
/// <param name="str">The ID string.</param>
/// <param name="id">The identifier.</param>
/// <returns>True if parsing succeeded, otherwise false.</returns>
public static unsafe bool TryParseID(string str, out Guid id)
{
id = Guid.Empty;
if (str == null || str.Length != 32)
return false;
GuidInterop g;
if (!TryParseHex(str, 0, 8, out g.A) ||
!TryParseHex(str, 8, 8, out g.B) ||
!TryParseHex(str, 16, 8, out g.C) ||
!TryParseHex(str, 24, 8, out g.D))
{
return false;
}
id = *(Guid*)&g;
return true;
}
/// <summary>
/// Parses the given object identifier represented in the internal serialization format.
/// </summary>
@@ -625,76 +650,40 @@ namespace FlaxEngine.Json
/// <param name="id">The identifier.</param>
public static unsafe void ParseID(string str, out Guid id)
{
GuidInterop g;
// Broken after VS 15.5
/*fixed (char* a = str)
{
char* b = a + 8;
char* c = b + 8;
char* d = c + 8;
ParseHex(a, 8, out g.A);
ParseHex(b, 8, out g.B);
ParseHex(c, 8, out g.C);
ParseHex(d, 8, out g.D);
}*/
// Temporary fix (not using raw char* pointer)
ParseHex(str, 0, 8, out g.A);
ParseHex(str, 8, 8, out g.B);
ParseHex(str, 16, 8, out g.C);
ParseHex(str, 24, 8, out g.D);
id = *(Guid*)&g;
TryParseID(str, out id);
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
internal static unsafe void ParseHex(char* str, int length, out uint result)
{
uint sum = 0;
char* p = str;
char* end = str + length;
if (*p == '0' && *(p + 1) == 'x')
p += 2;
while (p < end && *p != 0)
{
int c = *p - '0';
if (c < 0 || c > 9)
{
c = char.ToLower(*p) - 'a' + 10;
if (c < 10 || c > 15)
{
result = 0;
return;
}
}
sum = 16 * sum + (uint)c;
p++;
}
result = sum;
TryParseHex(new ReadOnlySpan<char>(str, length), out result);
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
internal static void ParseHex(string str, int start, int length, out uint result)
{
uint sum = 0;
int p = start;
int end = start + length;
TryParseHex(str, start, length, out result);
}
if (str.Length < end)
[MethodImpl(MethodImplOptions.AggressiveInlining)]
internal static bool TryParseHex(string str, int start, int length, out uint result)
{
if (str.Length < start + length)
{
result = 0;
return;
return false;
}
return TryParseHex(str.AsSpan(start, length), out result);
}
if (str[p] == '0' && str[p + 1] == 'x')
[MethodImpl(MethodImplOptions.AggressiveInlining)]
internal static bool TryParseHex(ReadOnlySpan<char> str, out uint result)
{
uint sum = 0;
int p = 0;
int end = str.Length;
if (p + 1 < end && str[p] == '0' && str[p + 1] == 'x')
p += 2;
while (p < end && str[p] != 0)
@@ -707,7 +696,7 @@ namespace FlaxEngine.Json
if (c < 10 || c > 15)
{
result = 0;
return;
return false;
}
}
@@ -717,6 +706,7 @@ namespace FlaxEngine.Json
}
result = sum;
return p == end;
}
}
}