diff --git a/Source/Editor/CustomEditors/CustomEditorsUtil.cs b/Source/Editor/CustomEditors/CustomEditorsUtil.cs index 476219960..d70557047 100644 --- a/Source/Editor/CustomEditors/CustomEditorsUtil.cs +++ b/Source/Editor/CustomEditors/CustomEditorsUtil.cs @@ -58,9 +58,9 @@ namespace FlaxEditor.CustomEditors if (targetType.Type == typeof(object) && values.Count > 0 && values[0] != null && !values.HasDifferentTypes) return CreateEditor(TypeUtils.GetObjectType(values[0]), canUseRefPicker); - // Special case if property is interface but the value is implemented as Scripting Object that should use reference picker - if (targetType.IsInterface && canUseRefPicker && values.Count > 0 && values[0] is FlaxEngine.Object) - return new DummyEditor(); + // Special case if property is interface but the value is implemented as Scripting Object that should use reference picker (or all interface impl are by Scripting Objects) + if (canUseRefPicker && targetType.IsInterface && values.Count > 0 && values[0] is FlaxEngine.Object) + return new FlaxObjectRefEditor(); // Use editor for the property type return CreateEditor(targetType, canUseRefPicker); diff --git a/Source/Editor/CustomEditors/Editors/DictionaryEditor.cs b/Source/Editor/CustomEditors/Editors/DictionaryEditor.cs index 1fe849f09..7dfce6055 100644 --- a/Source/Editor/CustomEditors/Editors/DictionaryEditor.cs +++ b/Source/Editor/CustomEditors/Editors/DictionaryEditor.cs @@ -260,7 +260,7 @@ namespace FlaxEditor.CustomEditors.Editors var overrideEditor = overrideEditorType != null ? (CustomEditor)Activator.CreateInstance(overrideEditorType) : null; var property = panel.AddPropertyItem(new DictionaryItemLabel(this, key)); var itemLayout = useSharedLayout ? (LayoutElementsContainer)property : property.VerticalPanel(); - itemLayout.Object(new DictionaryValueContainer(valuesType, key, Values), overrideEditor); + itemLayout.Object(new DictionaryValueContainer(valuesType, key, Values, attributes), overrideEditor); if (_readOnly && itemLayout.Children.Count > 0) GenericEditor.OnReadOnlyProperty(itemLayout); } diff --git a/Source/Editor/CustomEditors/Editors/FlaxObjectRefEditor.cs b/Source/Editor/CustomEditors/Editors/FlaxObjectRefEditor.cs index a6a02ae1f..f522310db 100644 --- a/Source/Editor/CustomEditors/Editors/FlaxObjectRefEditor.cs +++ b/Source/Editor/CustomEditors/Editors/FlaxObjectRefEditor.cs @@ -2,6 +2,7 @@ using System; using System.Linq; +using System.Reflection; using FlaxEditor.Content; using FlaxEditor.CustomEditors.Elements; using FlaxEditor.GUI; @@ -48,7 +49,7 @@ namespace FlaxEditor.CustomEditors.Editors public IPresenterOwner PresenterContext; /// - /// Gets or sets the allowed objects type (given type and all subclasses). Must be type of any subclass. + /// Gets or sets the allowed objects type (given type and all subclasses). Must be type of any subclass or a scripting interface. /// public ScriptType Type { @@ -57,11 +58,12 @@ namespace FlaxEditor.CustomEditors.Editors { if (_type == value) return; - if (value == ScriptType.Null || (value.Type != typeof(Object) && !value.IsSubclassOf(ScriptType.Object))) + if (value == ScriptType.Null || (!value.IsInterface && value.Type != typeof(Object) && !value.IsSubclassOf(ScriptType.Object))) throw new ArgumentException(string.Format("Invalid type for FlaxObjectRefEditor. Input type: {0}", value != ScriptType.Null ? value.TypeName : "null")); _type = value; - _supportsPickDropDown = new ScriptType(typeof(Actor)).IsAssignableFrom(value) || + _supportsPickDropDown = value.IsInterface || + new ScriptType(typeof(Actor)).IsAssignableFrom(value) || new ScriptType(typeof(Script)).IsAssignableFrom(value); // Deselect value if it's not valid now @@ -149,41 +151,38 @@ namespace FlaxEditor.CustomEditors.Editors protected virtual bool IsValid(Object obj) { var type = TypeUtils.GetObjectType(obj); - return obj == null || _type.IsAssignableFrom(type) && (CheckValid == null || CheckValid(obj, type)); + return obj == null || (!_type.IsInterface || obj is SceneObject) && _type.IsAssignableFrom(type) && (CheckValid == null || CheckValid(obj, type)); } private void ShowDropDownMenu() { Focus(); - if (new ScriptType(typeof(Actor)).IsAssignableFrom(_type)) + var pos = new Float2(0, Height); + if (_type.IsInterface) { - ActorSearchPopup.Show(this, new Float2(0, Height), IsValid, actor => - { - Value = actor; - RootWindow.Focus(); - Focus(); - }, PresenterContext); + SceneObjectSearchPopup.Show(this, pos, IsValid, SetDropDownResult, PresenterContext); + } + else if (new ScriptType(typeof(Actor)).IsAssignableFrom(_type)) + { + ActorSearchPopup.Show(this, pos, IsValid, SetDropDownResult, PresenterContext); } else if (new ScriptType(typeof(Control)).IsAssignableFrom(_type)) { - ActorSearchPopup.Show(this, new Float2(0, Height), IsValid, actor => - { - Value = actor as UIControl; - RootWindow.Focus(); - Focus(); - }, PresenterContext); + ActorSearchPopup.Show(this, pos, IsValid, actor => { SetDropDownResult(actor as UIControl); }, PresenterContext); } else { - ScriptSearchPopup.Show(this, new Float2(0, Height), IsValid, script => - { - Value = script; - RootWindow.Focus(); - Focus(); - }, PresenterContext); + ScriptSearchPopup.Show(this, pos, IsValid, SetDropDownResult, PresenterContext); } } + private void SetDropDownResult(Object value) + { + Value = value; + RootWindow.Focus(); + Focus(); + } + /// /// Called when value gets changed. /// @@ -218,7 +217,7 @@ namespace FlaxEditor.CustomEditors.Editors { // Draw info Render2D.PushClip(nameRect); - Render2D.DrawText(style.FontMedium, Type != null ? $"Multiple Values ({Utilities.Utils.GetPropertyNameUI(Type.ToString())})" : "-", nameRect, isEnabled ? style.ForegroundGrey : style.ForegroundGrey.AlphaMultiplied(0.75f), TextAlignment.Near, TextAlignment.Center); + Render2D.DrawText(style.FontMedium, Type != null ? $"Multiple Values ({Utilities.Utils.GetTypeNameUI(_type)})" : "-", nameRect, isEnabled ? style.ForegroundGrey : style.ForegroundGrey.AlphaMultiplied(0.75f), TextAlignment.Near, TextAlignment.Center); Render2D.PopClip(); } else if (isSelected) @@ -235,7 +234,7 @@ namespace FlaxEditor.CustomEditors.Editors { // Draw info Render2D.PushClip(nameRect); - Render2D.DrawText(style.FontMedium, Type != null ? $"None ({Utilities.Utils.GetPropertyNameUI(Type.ToString())})" : "-", nameRect, isEnabled ? style.ForegroundGrey : style.ForegroundGrey.AlphaMultiplied(0.75f), TextAlignment.Near, TextAlignment.Center); + Render2D.DrawText(style.FontMedium, Type != null ? $"None ({Utilities.Utils.GetTypeNameUI(_type)})" : "-", nameRect, isEnabled ? style.ForegroundGrey : style.ForegroundGrey.AlphaMultiplied(0.75f), TextAlignment.Near, TextAlignment.Center); Render2D.PopClip(); } @@ -660,4 +659,58 @@ namespace FlaxEditor.CustomEditors.Editors } } } + + /// + /// Default implementation of the inspector used to edit reference to the . + /// + internal sealed class ScriptingObjectInterfaceReferenceEditor : CustomEditor + { + private CustomElement _element; + + /// + public override DisplayStyle Style => DisplayStyle.Inline; + + /// + public override void Initialize(LayoutElementsContainer layout) + { + if (!HasDifferentTypes) + { + _element = layout.Custom(); + _element.CustomControl.PresenterContext = Presenter.Owner; + _element.CustomControl.Type = new ScriptType(Values.Type.GetGenericArguments()[0]); + _element.CustomControl.ValueChanged += OnValueChanged; + } + } + + private void OnValueChanged() + { + // Set value + var obj = _element.CustomControl.Value; + var v = Values.Type.CreateInstance(); + var objectField = v.GetType().GetField("_object", BindingFlags.Instance | BindingFlags.NonPublic); + objectField.SetValue(v, obj); + SetValue(v); + } + + /// + public override void Refresh() + { + base.Refresh(); + + var differentValues = HasDifferentValues; + _element.CustomControl.DifferentValues = differentValues; + if (!differentValues) + { + // Get value + var v = Values[0]; + var obj = v as Object; + if (v != null && obj == null) + { + var objectField = v.GetType().GetField("_object", BindingFlags.Instance | BindingFlags.NonPublic); + obj = objectField.GetValue(v) as Object; + } + _element.CustomControl.Value = obj; + } + } + } } diff --git a/Source/Editor/CustomEditors/Values/DictionaryValueContainer.cs b/Source/Editor/CustomEditors/Values/DictionaryValueContainer.cs index b143b44b1..b08d39beb 100644 --- a/Source/Editor/CustomEditors/Values/DictionaryValueContainer.cs +++ b/Source/Editor/CustomEditors/Values/DictionaryValueContainer.cs @@ -14,6 +14,8 @@ namespace FlaxEditor.CustomEditors [HideInEditor] public class DictionaryValueContainer : ValueContainer { + private readonly object[] _attributes; + /// /// The key in the collection. /// @@ -24,9 +26,11 @@ namespace FlaxEditor.CustomEditors /// /// Type of the collection elements. /// The key. - public DictionaryValueContainer(ScriptType elementType, object key) + /// The dictionary property attributes to inherit. + public DictionaryValueContainer(ScriptType elementType, object key, object[] attributes = null) : base(ScriptMemberInfo.Null, elementType) { + _attributes = attributes; Key = key; } @@ -36,8 +40,9 @@ namespace FlaxEditor.CustomEditors /// Type of the collection elements. /// The key. /// The collection values. - public DictionaryValueContainer(ScriptType elementType, object key, ValueContainer values) - : this(elementType, key) + /// The dictionary property attributes to inherit. + public DictionaryValueContainer(ScriptType elementType, object key, ValueContainer values, object[] attributes = null) + : this(elementType, key, attributes) { Capacity = values.Count; for (int i = 0; i < values.Count; i++) @@ -123,5 +128,11 @@ namespace FlaxEditor.CustomEditors _hasReferenceValue = true; } } + + /// + public override object[] GetAttributes() + { + return _attributes ?? base.GetAttributes(); + } } } diff --git a/Source/Editor/CustomEditors/Values/ValueContainer.cs b/Source/Editor/CustomEditors/Values/ValueContainer.cs index c8d44b32a..b9bd66623 100644 --- a/Source/Editor/CustomEditors/Values/ValueContainer.cs +++ b/Source/Editor/CustomEditors/Values/ValueContainer.cs @@ -297,6 +297,11 @@ namespace FlaxEditor.CustomEditors else if (Type.Type == typeof(long)) _defaultValue = Convert.ToInt64(_defaultValue); } + else if (_defaultValue == null && Type.IsValueType) + { + // Use zero value for value-types that have null as default value for some reason + _defaultValue = Type.CreateInstance(); + } } } if (instanceValues._hasReferenceValue) diff --git a/Source/Editor/GUI/ItemsListContextMenu.cs b/Source/Editor/GUI/ItemsListContextMenu.cs index 5f09342c7..95a9a2164 100644 --- a/Source/Editor/GUI/ItemsListContextMenu.cs +++ b/Source/Editor/GUI/ItemsListContextMenu.cs @@ -52,7 +52,7 @@ namespace FlaxEditor.GUI public float SortScore; /// - /// Wether the query highlights should be draw. + /// Whether the query highlights should be drawn. /// public bool DrawHighlights = true; @@ -261,6 +261,11 @@ namespace FlaxEditor.GUI /// public readonly VerticalPanel ItemsPanel; + /// + /// Gets a list of panels with item categories. + /// + public IEnumerable CategoryPanels => (IEnumerable)_categoryPanels ?? Array.Empty(); + /// /// Initializes a new instance of the class. /// @@ -504,6 +509,12 @@ namespace FlaxEditor.GUI category.Visible = true; category.Close(false); } + + if (_categoryPanels.Count == 1 && items.Count == 1) + { + // Expand the only category if there are no items outside of it + _categoryPanels[0].Open(false); + } } _searchBox?.Clear(); diff --git a/Source/Editor/GUI/Popups/SceneObjectSearchPopup.cs b/Source/Editor/GUI/Popups/SceneObjectSearchPopup.cs new file mode 100644 index 000000000..4868dd049 --- /dev/null +++ b/Source/Editor/GUI/Popups/SceneObjectSearchPopup.cs @@ -0,0 +1,146 @@ +// Copyright (c) Wojciech Figat. All rights reserved. + +using System; +using FlaxEditor.Windows; +using FlaxEditor.Windows.Assets; +using FlaxEngine; +using FlaxEngine.GUI; +using FlaxEngine.Utilities; + +namespace FlaxEditor.GUI +{ + /// + /// Popup that shows the list of scene objects to pick. Supports searching and basic type filtering. + /// + /// + public class SceneObjectSearchPopup : ItemsListContextMenu + { + /// + /// The scene object item. + /// + /// + public class SceneObjectItemView : Item + { + private SceneObject _object; + + /// + /// Gets the scene object. + /// + public SceneObject Object => _object; + + /// + /// Initializes a new instance of the class. + /// + /// The object. + public SceneObjectItemView(SceneObject obj) + { + _object = obj; + Category = obj is Actor ? "Actors" : "Scripts"; + if (obj is Script script) + { + var type = TypeUtils.GetObjectType(script); + Name = script.Actor ? $"{type.Name} ({script.Actor.Name})" : type.Name; + } + else if (obj is Actor actor) + { + Name = actor.Name; + } + else + { + Name = obj.ToString(); + } + TooltipText = Utilities.Utils.GetTooltip(obj); + } + + /// + public override void OnDestroy() + { + _object = null; + base.OnDestroy(); + } + } + + /// + /// Validates if the given scene object item can be used to pick it. + /// + /// The scene object. + /// True if is valid. + public delegate bool IsValidDelegate(SceneObject obj); + + private IsValidDelegate _isValid; + private Action _selected; + + private SceneObjectSearchPopup(IsValidDelegate isValid, Action selected, CustomEditors.IPresenterOwner context) + { + _isValid = isValid; + _selected = selected; + + ItemClicked += OnItemClicked; + + if (context is PropertiesWindow || context == null) + { + // TODO: use async thread to search scenes + for (int i = 0; i < Level.ScenesCount; i++) + { + Find(Level.GetScene(i)); + } + } + else if (context is PrefabWindow prefabWindow) + { + Find(prefabWindow.Graph.MainActor); + } + + SortItems(); + } + + private void OnItemClicked(Item item) + { + _selected(((SceneObjectItemView)item).Object); + } + + private void Find(Actor actor) + { + if (!actor) + return; + + if (_isValid(actor)) + AddItem(new SceneObjectItemView(actor)); + + for (int i = 0; i < actor.ScriptsCount; i++) + { + var script = actor.GetScript(i); + if (_isValid(script)) + AddItem(new SceneObjectItemView(script)); + } + + for (int i = 0; i < actor.ChildrenCount; i++) + { + Find(actor.GetChild(i)); + } + } + + /// + /// Shows the popup. + /// + /// The show target. + /// The show target location. + /// Event called to check if a given scene object item is valid to be used. + /// Event called on scene object item pick. + /// The presenter owner context (i.e. PrefabWindow, PropertiesWindow). + /// The dialog. + public static SceneObjectSearchPopup Show(Control showTarget, Float2 showTargetLocation, IsValidDelegate isValid, Action selected, CustomEditors.IPresenterOwner context) + { + var popup = new SceneObjectSearchPopup(isValid, selected, context); + popup.Show(showTarget, showTargetLocation); + return popup; + } + + /// + public override void OnDestroy() + { + _isValid = null; + _selected = null; + base.OnDestroy(); + } + } +} diff --git a/Source/Editor/Scripting/ScriptType.cs b/Source/Editor/Scripting/ScriptType.cs index 6db13e07a..1d26fc162 100644 --- a/Source/Editor/Scripting/ScriptType.cs +++ b/Source/Editor/Scripting/ScriptType.cs @@ -1,15 +1,62 @@ // Copyright (c) Wojciech Figat. All rights reserved. +using FlaxEditor.Content; +using FlaxEngine; +using FlaxEngine.TypeConverters; +using FlaxEngine.Utilities; using System; using System.Collections.Generic; using System.ComponentModel; +using System.ComponentModel.Design.Serialization; +using System.Globalization; using System.Linq; using System.Reflection; using System.Runtime.CompilerServices; using System.Text; -using FlaxEditor.Content; -using FlaxEngine; -using FlaxEngine.Utilities; + +namespace FlaxEngine.TypeConverters +{ + /// + /// Internal ITypeDescriptorContext used to pass some context for custom TypeConvert implementations. + /// Allows passing CurrentType to TypeConverter.ConvertFrom method to support custom type conversion for FlaxEngine types (simpler than PropertyDescriptor.PropertyType). + /// + internal sealed class DummyTypeDescriptorContext : ITypeDescriptorContext + { + private static DummyTypeDescriptorContext _cached; + + public Type CurrentType; + + public static object ConvertFrom(TypeConverter converter, object value, Type type) + { + if (_cached == null) + _cached = new DummyTypeDescriptorContext(); + _cached.CurrentType = type; + var result = converter.ConvertFrom(_cached, CultureInfo.CurrentUICulture, value); + _cached.CurrentType = null; + return result; + } + + public object GetService(Type serviceType) + { + return null; + } + + public void OnComponentChanged() + { + } + + public bool OnComponentChanging() + { + return false; + } + + public IContainer Container => null; + + public object Instance => null; + + public PropertyDescriptor PropertyDescriptor => null; + } +} namespace FlaxEditor.Scripting { @@ -681,7 +728,7 @@ namespace FlaxEditor.Scripting if (converter.CanConvertTo(type)) value = converter.ConvertTo(value, type); else if (converter.CanConvertFrom(valueType)) - value = converter.ConvertFrom(null, null, value); + value = DummyTypeDescriptorContext.ConvertFrom(converter, value, type); } if (_managed is PropertyInfo propertyInfo) diff --git a/Source/Editor/Surface/SurfaceStyle.cs b/Source/Editor/Surface/SurfaceStyle.cs index e6bc82fe3..0738c6dd5 100644 --- a/Source/Editor/Surface/SurfaceStyle.cs +++ b/Source/Editor/Surface/SurfaceStyle.cs @@ -212,7 +212,7 @@ namespace FlaxEditor.Surface color = Colors.Enum; else if (type.IsValueType) color = Colors.Structures; - else if (type.IsScriptingObject || type.IsInterface) + else if (type.IsScriptingObject || type.IsInterface || type.Name.StartsWith("ScriptingObjectInterfaceReference")) color = Colors.Object; else if (hint == ConnectionsHint.Vector) color = Colors.Vector; diff --git a/Source/Editor/Utilities/Utils.cs b/Source/Editor/Utilities/Utils.cs index 5955ccf60..8f5df866d 100644 --- a/Source/Editor/Utilities/Utils.cs +++ b/Source/Editor/Utilities/Utils.cs @@ -833,6 +833,24 @@ namespace FlaxEditor.Utilities } } + /// + /// Gets the type name for UI. Removes unnecessary characters and filters text. Makes it more user-friendly. + /// + /// The type. + /// The result. + public static string GetTypeNameUI(Scripting.ScriptType type) + { + var name = type.ToString(); + + // Don't format interfaces to maintain code-name (eg. prefix 'I') + if (type.IsInterface) + return name; + if (type.IsGenericType && name.StartsWith("ScriptingObjectInterfaceReference", StringComparison.Ordinal)) + return type.GetGenericArguments()[0].GetTypeDisplayName(); + + return GetPropertyNameUI(name); + } + /// /// Gets the property name for UI. Removes unnecessary characters and filters text. Makes it more user-friendly. /// diff --git a/Source/Engine/AI/BehaviorKnowledgeSelector.cs b/Source/Engine/AI/BehaviorKnowledgeSelector.cs index 67d8bbf0c..580646b17 100644 --- a/Source/Engine/AI/BehaviorKnowledgeSelector.cs +++ b/Source/Engine/AI/BehaviorKnowledgeSelector.cs @@ -188,7 +188,7 @@ namespace FlaxEngine /// /// The knowledge container to access. /// The value to set. - /// True if set value value, otherwise false. + /// True if set value, otherwise false. public bool Set(BehaviorKnowledge knowledge, T value) { return knowledge != null && knowledge.Set(Path, value); diff --git a/Source/Engine/Engine/NativeInterop.cs b/Source/Engine/Engine/NativeInterop.cs index 304270b34..9648c204f 100644 --- a/Source/Engine/Engine/NativeInterop.cs +++ b/Source/Engine/Engine/NativeInterop.cs @@ -263,12 +263,36 @@ namespace FlaxEngine.Interop /// The output array. public static TDst[] ConvertArray(this TSrc[] src, Func convertFunc) { - TDst[] dst = new TDst[src.Length]; + if (src == null) + return null; + var dst = new TDst[src.Length]; for (int i = 0; i < src.Length; i++) dst[i] = convertFunc(src[i]); return dst; } + /// + /// Converts dictionary with a custom converter function for each pair of keys and values. + /// + /// Input dictionary key type. + /// Input dictionary value type. + /// Output dictionary key type. + /// Output dictionary value type. + /// The input dictionary. + /// Converter callback for keys. + /// Converter callback for values. + /// The output dictionary. + public static Dictionary ConvertDictionary(this Dictionary src, Func convertFuncKey, Func convertFuncValue) + { + if (src == null) + return null; + var dst = new Dictionary(); + dst.EnsureCapacity(src.Count); + foreach (var e in src) + dst.Add(convertFuncKey(e.Key), convertFuncValue(e.Value)); + return dst; + } + /// Find among the scripting assemblies. /// The name to find /// If true, partial names should be allowed to be resolved. diff --git a/Source/Engine/Scripting/Internal/InternalCalls.h b/Source/Engine/Scripting/Internal/InternalCalls.h index 4535952ea..d179fd8fd 100644 --- a/Source/Engine/Scripting/Internal/InternalCalls.h +++ b/Source/Engine/Scripting/Internal/InternalCalls.h @@ -37,7 +37,7 @@ struct FLAXENGINE_API VTableFunctionInjector #if USE_NETCORE #define ADD_INTERNAL_CALL(fullName, method) -#define DEFINE_INTERNAL_CALL(returnType) extern "C" DLLEXPORT returnType +#define DEFINE_INTERNAL_CALL(returnType) extern "C" DLLEXPORT USED returnType #else extern "C" FLAXENGINE_API void mono_add_internal_call(const char* name, const void* method); #define ADD_INTERNAL_CALL(fullName, method) mono_add_internal_call(fullName, (const void*)method) diff --git a/Source/Engine/Scripting/ManagedCLR/MUtils.h b/Source/Engine/Scripting/ManagedCLR/MUtils.h index 5598dbee0..6becee4f7 100644 --- a/Source/Engine/Scripting/ManagedCLR/MUtils.h +++ b/Source/Engine/Scripting/ManagedCLR/MUtils.h @@ -278,57 +278,25 @@ struct MConverter::Val // Converter for ScriptingObject References. template class ScriptingObjectReference; - template -struct MConverter> -{ - MObject* Box(const ScriptingObjectReference& data, const MClass* klass) - { - return data.GetManagedInstance(); - } - - void Unbox(ScriptingObjectReference& result, MObject* data) - { - result = (T*)ScriptingObject::ToNative(data); - } - - void ToManagedArray(MArray* result, const Span>& data) - { - if (data.Length() == 0) - return; - MObject** objects = (MObject**)Allocator::Allocate(data.Length() * sizeof(MObject*)); - for (int32 i = 0; i < data.Length(); i++) - objects[i] = data[i].GetManagedInstance(); - MCore::GC::WriteArrayRef(result, Span(objects, data.Length())); - Allocator::Free(objects); - } - - void ToNativeArray(Span>& result, const MArray* data) - { - MObject** dataPtr = MCore::Array::GetAddress(data); - for (int32 i = 0; i < result.Length(); i++) - result.Get()[i] = (T*)ScriptingObject::ToNative(dataPtr[i]); - } -}; - -// Converter for Asset References. +class ScriptingObjectInterfaceReference; template class AssetReference; -template -struct MConverter> +template +struct MObjectReferenceConverter { - MObject* Box(const AssetReference& data, const MClass* klass) + MObject* Box(const Reference& data, const MClass* klass) { return data.GetManagedInstance(); } - void Unbox(AssetReference& result, MObject* data) + void Unbox(Reference& result, MObject* data) { - result = (T*)ScriptingObject::ToNative(data); + result = (Object*)ScriptingObject::ToNative(data); } - void ToManagedArray(MArray* result, const Span>& data) + void ToManagedArray(MArray* result, const Span& data) { if (data.Length() == 0) return; @@ -339,14 +307,29 @@ struct MConverter> Allocator::Free(objects); } - void ToNativeArray(Span>& result, const MArray* data) + void ToNativeArray(Span& result, const MArray* data) { MObject** dataPtr = MCore::Array::GetAddress(data); for (int32 i = 0; i < result.Length(); i++) - result.Get()[i] = (T*)ScriptingObject::ToNative(dataPtr[i]); + result.Get()[i] = (Object*)ScriptingObject::ToNative(dataPtr[i]); } }; +template +struct MConverter> : MObjectReferenceConverter, T> +{ +}; + +template +struct MConverter> : MObjectReferenceConverter, ScriptingObject> +{ +}; + +template +struct MConverter> : MObjectReferenceConverter, T> +{ +}; + // TODO: use MarshalAs=Guid on SoftAssetReference to pass guid over bindings and not load asset in glue code template class SoftAssetReference; diff --git a/Source/Engine/Scripting/ScriptingObject.cpp b/Source/Engine/Scripting/ScriptingObject.cpp index dee97a849..dd530c50f 100644 --- a/Source/Engine/Scripting/ScriptingObject.cpp +++ b/Source/Engine/Scripting/ScriptingObject.cpp @@ -717,6 +717,12 @@ DEFINE_INTERNAL_CALL(MString*) ObjectInternal_GetTypeName(ScriptingObject* obj) return MUtils::ToString(obj->GetType().Fullname); } +FORCE_INLINE bool ObjectInternal_MatchesType(ScriptingObject* obj, MClass* klass) +{ + return !klass || + (klass->IsInterface() ? obj->GetClass()->HasInterface(klass) : obj->Is(klass)); +} + DEFINE_INTERNAL_CALL(MObject*) ObjectInternal_FindObject(Guid* id, MTypeObject* type, bool skipLog = false) { if (!id->IsValid()) @@ -732,7 +738,7 @@ DEFINE_INTERNAL_CALL(MObject*) ObjectInternal_FindObject(Guid* id, MTypeObject* } if (obj) { - if (klass && !obj->Is(klass)) + if (!ObjectInternal_MatchesType(obj, klass)) { if (!skipLog) { @@ -762,7 +768,7 @@ DEFINE_INTERNAL_CALL(MObject*) ObjectInternal_FindObject(Guid* id, MTypeObject* DEFINE_INTERNAL_CALL(MObject*) ObjectInternal_TryFindObject(Guid* id, MTypeObject* type) { ScriptingObject* obj = Scripting::TryFindObject(*id); - if (obj && !obj->Is(MUtils::GetClass(type))) + if (obj && !ObjectInternal_MatchesType(obj, MUtils::GetClass(type))) obj = nullptr; return obj ? obj->GetOrCreateManagedInstance() : nullptr; } diff --git a/Source/Engine/Scripting/ScriptingObjectInterfaceReference.cs b/Source/Engine/Scripting/ScriptingObjectInterfaceReference.cs new file mode 100644 index 000000000..46cbbef24 --- /dev/null +++ b/Source/Engine/Scripting/ScriptingObjectInterfaceReference.cs @@ -0,0 +1,188 @@ +// Copyright (c) Wojciech Figat. All rights reserved. + +using System; +#if FLAX_EDITOR +using System.Globalization; +using System.ComponentModel; +#endif + +namespace FlaxEngine +{ + /// + /// The scripting object reference with interface. + /// + /// The type of the scripting interface. +#if FLAX_EDITOR + [CustomEditor(typeof(FlaxEditor.CustomEditors.Editors.ScriptingObjectInterfaceReferenceEditor))] + [TypeConverter(typeof(TypeConverters.ScriptingObjectInterfaceReferenceConverter))] +#endif + public struct ScriptingObjectInterfaceReference : IComparable, IComparable> where T : class + { + private Object _object; + + /// + /// Gets or sets the referenced object that implements the interface. + /// + public Object Object + { + get => _object; + set => _object = value != null && value is T ? value : null; + } + + /// + /// Gets or sets the referenced object that implements the interface. + /// + [NoSerialize] + public T Interface + { + get => _object as T; + set + { + var obj = value as Object; + if (value == null || obj != null) + _object = obj; + else + throw new InvalidCastException($"Cannot use object of type {value.GetType().FullName} for ScriptingObjectInterfaceReference<{typeof(T).FullName}>. It needs to inherit from {typeof(Object).FullName}."); + } + } + + /// + /// Initializes a new instance of the structure. + /// + /// The object to link. + public ScriptingObjectInterfaceReference(Object obj) + { + Object = obj; + } + + /// + /// Initializes a new instance of the structure. + /// + /// The interface object to link. + public ScriptingObjectInterfaceReference(T interfaceObj) + { + Interface = interfaceObj; + } + + /// + /// Implicit cast operator to typed interface. + /// + /// Reference + /// Interface + public static explicit operator T(ScriptingObjectInterfaceReference value) + { + return value._object as T; + } + + /// + /// Implicit cast operator from object to reference. + /// + /// The object to link. + /// Reference + public static explicit operator ScriptingObjectInterfaceReference(T obj) + { + return new ScriptingObjectInterfaceReference(obj); + } + + /// + /// Implicit cast operator to object. + /// + /// Reference + /// Object + public static implicit operator Object(ScriptingObjectInterfaceReference value) + { + return value._object; + } + + /// + /// Implicit cast operator from object to reference. + /// + /// Object + /// Reference + public static implicit operator ScriptingObjectInterfaceReference(Object obj) + { + return new ScriptingObjectInterfaceReference(obj); + } + + /// + public override string ToString() + { + return _object?.ToString() ?? ""; + } + + /// + public override int GetHashCode() + { + return Object.GetUnmanagedPtr(_object).GetHashCode(); + } + + /// + public int CompareTo(object obj) + { + if (obj is ScriptingObjectInterfaceReference other) + return CompareTo(other); + return 0; + } + + /// + public int CompareTo(ScriptingObjectInterfaceReference other) + { + return Object.GetUnmanagedPtr(_object).CompareTo(Object.GetUnmanagedPtr(other._object)); + } + } +} + +#if FLAX_EDITOR +namespace FlaxEngine.TypeConverters +{ + internal class ScriptingObjectInterfaceReferenceConverter : TypeConverter + { + /// + public override bool CanConvertFrom(ITypeDescriptorContext context, Type sourceType) + { + if (sourceType == typeof(string)) + return true; + return base.CanConvertFrom(context, sourceType); + } + + /// + public override bool CanConvertTo(ITypeDescriptorContext context, Type destinationType) + { + if (destinationType == typeof(string)) + return false; + return base.CanConvertTo(context, destinationType); + } + + /// + public override object ConvertFrom(ITypeDescriptorContext context, CultureInfo culture, object value) + { + if (value is string str && context is DummyTypeDescriptorContext internalContext) + { + var type = internalContext.CurrentType; + Json.JsonSerializer.ParseID(str, out var id); + var obj = Object.Find(ref id, type.GetGenericArguments()[0]); + var objectField = type.GetField("_object", System.Reflection.BindingFlags.Instance | System.Reflection.BindingFlags.NonPublic); + value = Activator.CreateInstance(type); + objectField.SetValue(value, obj); + return value; + } + return base.ConvertFrom(context, culture, value); + } + + /// + public override unsafe object ConvertTo(ITypeDescriptorContext context, CultureInfo culture, object value, Type destinationType) + { + if (destinationType == typeof(string)) + { + var objectField = value.GetType().GetField("_object", System.Reflection.BindingFlags.Instance | System.Reflection.BindingFlags.NonPublic); + var obj = objectField.GetValue(value) as Object; + if (obj == null) + return string.Empty; + var id = obj.ID; + return Json.JsonSerializer.GetStringID(&id); + } + return base.ConvertTo(context, culture, value, destinationType); + } + } +} +#endif diff --git a/Source/Engine/Scripting/ScriptingObjectInterfaceReference.h b/Source/Engine/Scripting/ScriptingObjectInterfaceReference.h new file mode 100644 index 000000000..46687074a --- /dev/null +++ b/Source/Engine/Scripting/ScriptingObjectInterfaceReference.h @@ -0,0 +1,193 @@ +// Copyright (c) Wojciech Figat. All rights reserved. + +#pragma once + +#include "ScriptingObjectReference.h" + +/// +/// The scripting object reference with interface. +/// +/// The type of the scripting interface. +template +API_CLASS(Template, MarshalAs=ScriptingObject*) class ScriptingObjectInterfaceReference : public ScriptingObjectReferenceBase +{ +public: + typedef ScriptingObjectInterfaceReference Type; + +public: + /// + /// Initializes a new instance of the class. + /// + ScriptingObjectInterfaceReference() + { + } + + /// + /// Initializes a new instance of the class. + /// + /// The object to link. + ScriptingObjectInterfaceReference(ScriptingObject* obj) + : ScriptingObjectReferenceBase(IsValid(obj) ? obj : nullptr) + { + } + + /// + /// Initializes a new instance of the class. + /// + /// The interface object to link. + ScriptingObjectInterfaceReference(T* interfaceObj) + : ScriptingObjectReferenceBase(ScriptingObject::FromInterface(interfaceObj)) + { + } + + /// + /// Initializes a new instance of the class. + /// + /// The other property. + ScriptingObjectInterfaceReference(const ScriptingObjectInterfaceReference& other) + : ScriptingObjectReferenceBase(other._object) + { + } + + ScriptingObjectInterfaceReference(ScriptingObjectInterfaceReference&& other) noexcept + : ScriptingObjectReferenceBase(MoveTemp(other)) + { + } + + /// + /// Finalizes an instance of the class. + /// + ~ScriptingObjectInterfaceReference() + { + } + +public: + FORCE_INLINE bool operator==(ScriptingObject* other) const + { + return _object == other; + } + + FORCE_INLINE bool operator!=(ScriptingObject* other) const + { + return _object != other; + } + + FORCE_INLINE bool operator==(T* other) const + { + return Get() == other; + } + + FORCE_INLINE bool operator!=(T* other) const + { + return Get() != other; + } + + FORCE_INLINE bool operator==(const ScriptingObjectInterfaceReference& other) const + { + return _object == other._object; + } + + FORCE_INLINE bool operator!=(const ScriptingObjectInterfaceReference& other) const + { + return _object != other._object; + } + + FORCE_INLINE ScriptingObjectInterfaceReference& operator=(ScriptingObject* other) + { + OnSet(IsValid(other) ? other : nullptr); + return *this; + } + + FORCE_INLINE ScriptingObjectInterfaceReference& operator=(T* other) + { + OnSet(ScriptingObject::FromInterface(other)); + return *this; + } + + FORCE_INLINE ScriptingObjectInterfaceReference& operator=(const ScriptingObjectInterfaceReference& other) + { + OnSet(other._object); + return *this; + } + + FORCE_INLINE ScriptingObjectInterfaceReference& operator=(ScriptingObjectInterfaceReference&& other) noexcept + { + ScriptingObjectReferenceBase::operator=(MoveTemp(other)); + return *this; + } + + ScriptingObjectInterfaceReference& operator=(const Guid& id) + { + ScriptingObject* obj = FindObject(id, ScriptingObject::GetStaticClass()); + OnSet(IsValid(obj) ? obj : nullptr); + return *this; + } + + /// + /// Implicit conversion to the interface. + /// + FORCE_INLINE operator T*() const + { + return Get(); + } + + /// + /// Implicit conversion to the object. + /// + FORCE_INLINE operator ScriptingObject*() const + { + return _object; + } + + /// + /// Implicit conversion to boolean value. + /// + FORCE_INLINE operator bool() const + { + return _object != nullptr; + } + + /// + /// Interface accessor. + /// + FORCE_INLINE T* operator->() const + { + return Get(); + } + + /// + /// Gets the interface pointer. + /// + FORCE_INLINE T* Get() const + { + return ScriptingObject::ToInterface(_object); + } + + /// + /// Gets the referenced object. + /// + FORCE_INLINE ScriptingObject* GetObject() const + { + return _object; + } + + /// + /// Gets managed instance object. + /// + FORCE_INLINE MObject* GetManagedInstance() const + { + return _object ? _object->GetOrCreateManagedInstance() : nullptr; + } + +private: + FORCE_INLINE static bool IsValid(const ScriptingObject* obj) + { + return !obj || obj->GetType().GetInterface(T::TypeInitializer); + } +}; + +template +uint32 GetHash(const ScriptingObjectInterfaceReference& key) +{ + return GetHash(key.GetID()); +} diff --git a/Source/Engine/Scripting/ScriptingObjectReference.h b/Source/Engine/Scripting/ScriptingObjectReference.h index 58fed7668..21e4ecd66 100644 --- a/Source/Engine/Scripting/ScriptingObjectReference.h +++ b/Source/Engine/Scripting/ScriptingObjectReference.h @@ -72,7 +72,7 @@ public: } /// - /// Gets managed instance object (or null if no object linked). + /// Gets managed instance object. /// FORCE_INLINE MObject* GetManagedInstance() const { diff --git a/Source/Engine/Scripting/SoftObjectReference.h b/Source/Engine/Scripting/SoftObjectReference.h index 3fd85200e..b07702e44 100644 --- a/Source/Engine/Scripting/SoftObjectReference.h +++ b/Source/Engine/Scripting/SoftObjectReference.h @@ -233,7 +233,7 @@ public: } /// - /// Gets managed instance object (or null if no object linked). + /// Gets managed instance object. /// MObject* GetManagedInstance() const { diff --git a/Source/Engine/Serialization/JsonConverters.cs b/Source/Engine/Serialization/JsonConverters.cs index a45ae558a..71094b127 100644 --- a/Source/Engine/Serialization/JsonConverters.cs +++ b/Source/Engine/Serialization/JsonConverters.cs @@ -1,8 +1,8 @@ // Copyright (c) Wojciech Figat. All rights reserved. -using System; using FlaxEngine.GUI; using Newtonsoft.Json; +using System; namespace FlaxEngine.Json { @@ -138,6 +138,52 @@ namespace FlaxEngine.Json } } + /// + /// Serialize as path string in internal format. + /// + /// + internal class ScriptingObjectInterfaceReferenceConverter : JsonConverter + { + /// + public override unsafe void WriteJson(JsonWriter writer, object value, Newtonsoft.Json.JsonSerializer serializer) + { + if (value == null) + writer.WriteNull(); + else + { + var objectField = value.GetType().GetField("_object", System.Reflection.BindingFlags.Instance | System.Reflection.BindingFlags.NonPublic); + var obj = objectField.GetValue(value) as Object; + if (obj == null) + { + writer.WriteNull(); + return; + } + var id = obj.ID; + writer.WriteValue(JsonSerializer.GetStringID(&id)); + } + } + + /// + public override object ReadJson(JsonReader reader, Type objectType, object existingValue, Newtonsoft.Json.JsonSerializer serializer) + { + var result = existingValue ?? Activator.CreateInstance(objectType); + if (reader.TokenType == JsonToken.String) + { + JsonSerializer.ParseID((string)reader.Value, out var id); + var obj = Object.Find(ref id, objectType.GetGenericArguments()[0]); + var objectField = objectType.GetField("_object", System.Reflection.BindingFlags.Instance | System.Reflection.BindingFlags.NonPublic); + objectField.SetValue(result, obj); + } + return result; + } + + /// + public override bool CanConvert(Type objectType) + { + return objectType.IsGenericType && objectType.GetGenericTypeDefinition() == typeof(ScriptingObjectInterfaceReference<>); + } + } + /// /// Serialize as path string in internal format. /// diff --git a/Source/Engine/Serialization/JsonCustomSerializers/ExtendedDefaultContractResolver.cs b/Source/Engine/Serialization/JsonCustomSerializers/ExtendedDefaultContractResolver.cs index 4f2690863..5a1a7c92d 100644 --- a/Source/Engine/Serialization/JsonCustomSerializers/ExtendedDefaultContractResolver.cs +++ b/Source/Engine/Serialization/JsonCustomSerializers/ExtendedDefaultContractResolver.cs @@ -34,6 +34,15 @@ namespace FlaxEngine.Json.JsonCustomSerializers _attributesIgnoreList = isManagedOnly ? AttributesIgnoreListManaged : AttributesIgnoreList; } + private void SetupProperty(JsonProperty jsonProperty, Type type, IEnumerable attributes) + { + if (_flaxType.IsAssignableFrom(type)) + { + jsonProperty.ReferenceLoopHandling = ReferenceLoopHandling.Serialize; + jsonProperty.Converter = JsonSerializer.ObjectConverter; + } + } + /// protected override JsonContract CreateContract(Type objectType) { @@ -116,11 +125,7 @@ namespace FlaxEngine.Json.JsonCustomSerializers jsonProperty.Writable = true; jsonProperty.Readable = true; - if (_flaxType.IsAssignableFrom(f.FieldType)) - { - jsonProperty.ReferenceLoopHandling = ReferenceLoopHandling.Serialize; - jsonProperty.Converter = JsonSerializer.ObjectConverter; - } + SetupProperty(jsonProperty, f.FieldType, attributes); result.Add(jsonProperty); } @@ -159,11 +164,7 @@ namespace FlaxEngine.Json.JsonCustomSerializers jsonProperty.Writable = true; jsonProperty.Readable = !isObsolete; - if (_flaxType.IsAssignableFrom(p.PropertyType)) - { - jsonProperty.ReferenceLoopHandling = ReferenceLoopHandling.Serialize; - jsonProperty.Converter = JsonSerializer.ObjectConverter; - } + SetupProperty(jsonProperty, p.PropertyType, attributes); result.Add(jsonProperty); } diff --git a/Source/Engine/Serialization/JsonSerializer.cs b/Source/Engine/Serialization/JsonSerializer.cs index c8d00567a..f08e273ae 100644 --- a/Source/Engine/Serialization/JsonSerializer.cs +++ b/Source/Engine/Serialization/JsonSerializer.cs @@ -198,6 +198,7 @@ namespace FlaxEngine.Json settings.Converters.Add(new SceneReferenceConverter()); settings.Converters.Add(new SoftObjectReferenceConverter()); settings.Converters.Add(new SoftTypeReferenceConverter()); + settings.Converters.Add(new ScriptingObjectInterfaceReferenceConverter()); settings.Converters.Add(new BehaviorKnowledgeSelectorAnyConverter()); settings.Converters.Add(new ControlReferenceConverter()); settings.Converters.Add(new MarginConverter()); @@ -619,84 +620,34 @@ namespace FlaxEngine.Json } /// - /// Parses the given object identifier represented in the internal serialization format. + /// Tries to parse the given object identifier represented in the internal serialization format. /// /// The ID string. /// The identifier. - public static unsafe void ParseID(string str, out Guid id) + /// True if cannot parse text, otherwise false + public static unsafe bool ParseID(string str, out Guid id) { + bool result = true; GuidInterop g; - - // Broken after VS 15.5 - /*fixed (char* a = str) + if (str != null && str.Length == 32) { - 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; - } - - [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++; + // Matches Flax Guid parsing of FormatType::N + result = 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); } - - result = sum; + id = *(Guid*)&g; + return result; } [MethodImpl(MethodImplOptions.AggressiveInlining)] - internal static void ParseHex(string str, int start, int length, out uint result) + internal static bool ParseHex(string str, int start, int length, out uint result) { uint sum = 0; int p = start; int end = start + length; - if (str.Length < end) - { - result = 0; - return; - } - - if (str[p] == '0' && str[p + 1] == 'x') - p += 2; - while (p < end && str[p] != 0) { int c = str[p] - '0'; @@ -707,16 +658,16 @@ namespace FlaxEngine.Json if (c < 10 || c > 15) { result = 0; - return; + return true; } } sum = 16 * sum + (uint)c; - p++; } result = sum; + return p != end; } } } diff --git a/Source/Engine/Serialization/ReadStream.h b/Source/Engine/Serialization/ReadStream.h index cc2b7e73b..06c52b64f 100644 --- a/Source/Engine/Serialization/ReadStream.h +++ b/Source/Engine/Serialization/ReadStream.h @@ -133,6 +133,14 @@ public: v = ptr; } + template + FORCE_INLINE void Read(ScriptingObjectInterfaceReference& v) + { + uint32 id[4]; + ReadBytes(id, sizeof(id)); + v = *(Guid*)id; + } + template FORCE_INLINE void Read(SoftObjectReference& v) { diff --git a/Source/Engine/Serialization/Serialization.h b/Source/Engine/Serialization/Serialization.h index 41ae4898a..b588a5d78 100644 --- a/Source/Engine/Serialization/Serialization.h +++ b/Source/Engine/Serialization/Serialization.h @@ -14,6 +14,8 @@ struct VariantType; template class ScriptingObjectReference; template +class ScriptingObjectInterfaceReference; +template class SoftObjectReference; template class AssetReference; @@ -458,7 +460,6 @@ namespace Serialization } FLAXENGINE_API bool ShouldSerializeRef(const SceneObject* v, const SceneObject* other); - template inline typename TEnableIf, TNot>>::Value, bool>::Type ShouldSerialize(const T* v, const void* otherObj) { @@ -474,7 +475,7 @@ namespace Serialization { Guid id; Deserialize(stream, id, modifier); - modifier->IdsMapping.TryGet(id, id); + modifier->IdsMapping.TryGet(id, id); v = (T*)::FindObject(id, T::GetStaticClass()); } @@ -501,7 +502,28 @@ namespace Serialization { Guid id; Deserialize(stream, id, modifier); - modifier->IdsMapping.TryGet(id, id); + modifier->IdsMapping.TryGet(id, id); + v = id; + } + + // Scripting Interface Reference + + template + inline bool ShouldSerialize(const ScriptingObjectInterfaceReference& v, const void* otherObj) + { + return !otherObj || ShouldSerializeRef(v.GetObject(), ((ScriptingObjectInterfaceReference*)otherObj)->GetObject()); + } + template + inline void Serialize(ISerializable::SerializeStream& stream, const ScriptingObjectInterfaceReference& v, const void* otherObj) + { + stream.Guid(v.GetID()); + } + template + inline void Deserialize(ISerializable::DeserializeStream& stream, ScriptingObjectInterfaceReference& v, ISerializeModifier* modifier) + { + Guid id; + Deserialize(stream, id, modifier); + modifier->IdsMapping.TryGet(id, id); v = id; } @@ -522,7 +544,7 @@ namespace Serialization { Guid id; Deserialize(stream, id, modifier); - modifier->IdsMapping.TryGet(id, id); + modifier->IdsMapping.TryGet(id, id); v = id; } diff --git a/Source/Engine/Serialization/Stream.h b/Source/Engine/Serialization/Stream.h index 7e82467f5..4e517effe 100644 --- a/Source/Engine/Serialization/Stream.h +++ b/Source/Engine/Serialization/Stream.h @@ -17,6 +17,8 @@ class ScriptingObject; template class ScriptingObjectReference; template +class ScriptingObjectInterfaceReference; +template class SoftObjectReference; template class AssetReference; diff --git a/Source/Engine/Serialization/WriteStream.h b/Source/Engine/Serialization/WriteStream.h index f027deabb..a5130ed8e 100644 --- a/Source/Engine/Serialization/WriteStream.h +++ b/Source/Engine/Serialization/WriteStream.h @@ -156,11 +156,19 @@ public: { Write(v.Get()); } + + template + FORCE_INLINE void Write(const ScriptingObjectInterfaceReference& v) + { + Write(v.GetObject()); + } + template FORCE_INLINE void Write(const SoftObjectReference& v) { Write(v.Get()); } + template FORCE_INLINE void Write(const AssetReference& v) { diff --git a/Source/Engine/Tests/TestScripting.cpp b/Source/Engine/Tests/TestScripting.cpp index 506291b36..8a3541def 100644 --- a/Source/Engine/Tests/TestScripting.cpp +++ b/Source/Engine/Tests/TestScripting.cpp @@ -37,9 +37,7 @@ TEST_CASE("Scripting") MMethod* method = klass->GetMethod("TestLibraryImports"); CHECK(method); MObject* result = method->Invoke(nullptr, nullptr, nullptr); - CHECK(result); - int32 resultValue = MUtils::Unbox(result); - CHECK(resultValue == 0); + CHECK(MUtils::Unbox(result) == 0); } SECTION("Test Class") @@ -167,4 +165,15 @@ TEST_CASE("Scripting") CHECK(interfaceObject); CHECK(interfaceObject == object); } + + SECTION("Test Interface Reference") + { + // Test native interface implementation + MClass* klass = Scripting::FindClass("FlaxEngine.Tests.TestScripting"); + CHECK(klass); + MMethod* method = klass->GetMethod("TestInterfaceReference"); + CHECK(method); + MObject* result = method->Invoke(nullptr, nullptr, nullptr); + CHECK(MUtils::Unbox(result) == 0); + } } diff --git a/Source/Engine/Tests/TestScripting.cs b/Source/Engine/Tests/TestScripting.cs index edbe18016..5846b569d 100644 --- a/Source/Engine/Tests/TestScripting.cs +++ b/Source/Engine/Tests/TestScripting.cs @@ -2,6 +2,7 @@ #if FLAX_TESTS using System; +using System.Collections.Generic; using System.Reflection; using System.Runtime.InteropServices; @@ -42,6 +43,33 @@ namespace FlaxEngine.Tests NativeLibrary.Free(library); return result; } + + /// + /// Tests usage with marshalling. + /// + public static int TestInterfaceReference() + { + var native = new TestClassNative(); + native.InterfaceRef = native; + var returned = native.InterfaceRef; + if (returned != native) + return 1; + returned = native.TestPassInterface(native); + if (returned != native) + return 2; + returned = native.TestPassInterfaceArray(new ScriptingObjectInterfaceReference[1] { native })[0]; + if (returned != native) + return 3; + var dic = new Dictionary>(); + dic.Add("key", native); + returned = native.TestPassInterfaceDictionary(dic)["key"]; + if (returned != native) + return 4; + var res = returned.Interface.TestInterfaceMethod("123"); + if (res != 3) + return 5; + return 0; + } } } diff --git a/Source/Engine/Tests/TestScripting.h b/Source/Engine/Tests/TestScripting.h index ca13ac307..e9440bb03 100644 --- a/Source/Engine/Tests/TestScripting.h +++ b/Source/Engine/Tests/TestScripting.h @@ -5,7 +5,9 @@ #include "Engine/Core/ISerializable.h" #include "Engine/Core/Math/Vector3.h" #include "Engine/Core/Collections/Array.h" +#include "Engine/Core/Collections/Dictionary.h" #include "Engine/Scripting/ScriptingObject.h" +#include "Engine/Scripting/ScriptingObjectInterfaceReference.h" #include "Engine/Scripting/SerializableScriptingObject.h" #include "Engine/Scripting/SoftTypeReference.h" #include "Engine/Content/SceneReference.h" @@ -178,6 +180,9 @@ public: // Test struct API_FIELD() TestStruct SimpleStruct; + // Test interface reference + API_FIELD() ScriptingObjectInterfaceReference InterfaceRef; + // Test event API_EVENT() Delegate&, Array&> SimpleEvent; @@ -200,6 +205,24 @@ public: // Test nameless arguments API_FUNCTION() void TestNamelessArguments(int32, float, bool){} + // Test pass interface ref in function + API_FUNCTION() ScriptingObjectInterfaceReference TestPassInterface(ScriptingObjectInterfaceReference param1) const + { + return param1; + } + + // Test pass interface ref array in function + API_FUNCTION() Array> TestPassInterfaceArray(Array> param1) const + { + return param1; + } + + // Test pass interface ref dictionary in function + API_FUNCTION() Dictionary> TestPassInterfaceDictionary(Dictionary> param1) const + { + return param1; + } + int32 TestInterfaceMethod(const String& str) override { return str.Length(); diff --git a/Source/Tools/Flax.Build/Bindings/BindingsGenerator.CSharp.cs b/Source/Tools/Flax.Build/Bindings/BindingsGenerator.CSharp.cs index 174c6de2c..e56d15149 100644 --- a/Source/Tools/Flax.Build/Bindings/BindingsGenerator.CSharp.cs +++ b/Source/Tools/Flax.Build/Bindings/BindingsGenerator.CSharp.cs @@ -107,8 +107,6 @@ namespace Flax.Build.Bindings { if (attribute && valueType != null && !valueType.IsArray) { - //if (valueType.Type == "") - //ScriptingObjectReference apiType = FindApiTypeInfo(buildData, valueType, caller); // Object reference @@ -371,7 +369,7 @@ namespace Flax.Build.Bindings if (arrayApiType != null && arrayApiType.MarshalAs != null) arrayTypeInfo = arrayApiType.MarshalAs; } - return GenerateCSharpNativeToManaged(buildData, arrayTypeInfo, caller) + "[]"; + return GenerateCSharpNativeToManaged(buildData, arrayTypeInfo, caller, marshalling) + "[]"; } // Dictionary @@ -555,6 +553,21 @@ namespace Flax.Build.Bindings return $"{{0}}.ConvertArray(x => ({GenerateCSharpNativeToManaged(buildData, arrayApiType.MarshalAs, caller)})x)"; } return string.Empty; + case "Dictionary": + if (typeInfo.GenericArgs != null && typeInfo.GenericArgs.Count == 2) + { + // Convert dictionary that uses different type for marshalling + var keyApiType = FindApiTypeInfo(buildData, typeInfo.GenericArgs[0], caller); + var valueApiType = FindApiTypeInfo(buildData, typeInfo.GenericArgs[1], caller); + if ((keyApiType != null && keyApiType.MarshalAs != null) || (valueApiType != null && valueApiType.MarshalAs != null)) + { + var keyConverter = keyApiType != null && keyApiType.MarshalAs != null ? $"({GenerateCSharpNativeToManaged(buildData, keyApiType.MarshalAs, caller)})" : ""; + var valueConverter = valueApiType != null && valueApiType.MarshalAs != null ? $"({GenerateCSharpNativeToManaged(buildData, valueApiType.MarshalAs, caller)})" : ""; + //return $"{{0}} != null ? System.Linq.Enumerable.ToDictionary({{0}}, x => {keyConverter}, x => {valueConverter}) : null"; + return $"{{0}}.ConvertDictionary(key => {keyConverter}key, value => {valueConverter}value)"; + } + } + return string.Empty; default: var apiType = FindApiTypeInfo(buildData, typeInfo, caller); if (apiType != null) @@ -778,10 +791,12 @@ namespace Flax.Build.Bindings } } #endif + var returnType = functionInfo.ReturnType; + if (functionInfo.Glue.UseReferenceForResult) { } - else if (!functionInfo.ReturnType.IsVoid) + else if (!returnType.IsVoid) { contents.Append("return "); } @@ -851,14 +866,27 @@ namespace Flax.Build.Bindings } contents.Append(')'); - if ((functionInfo.ReturnType.Type == "Array" || functionInfo.ReturnType.Type == "Span" || functionInfo.ReturnType.Type == "DataContainer") && functionInfo.ReturnType.GenericArgs != null) + if ((returnType.Type == "Array" || returnType.Type == "Span" || returnType.Type == "DataContainer") && returnType.GenericArgs != null) { // Convert array that uses different type for marshalling - var arrayTypeInfo = functionInfo.ReturnType.GenericArgs[0]; + var arrayTypeInfo = returnType.GenericArgs[0]; var arrayApiType = FindApiTypeInfo(buildData, arrayTypeInfo, caller); if (arrayApiType != null && arrayApiType.MarshalAs != null) contents.Append($".ConvertArray(x => ({GenerateCSharpNativeToManaged(buildData, arrayTypeInfo, caller)})x)"); } + else if (returnType.Type == "Dictionary" && returnType.GenericArgs != null && returnType.GenericArgs.Count == 2) + { + // Convert dictionary that uses different type for marshalling + var keyApiType = FindApiTypeInfo(buildData, returnType.GenericArgs[0], caller); + var valueApiType = FindApiTypeInfo(buildData, returnType.GenericArgs[1], caller); + if ((keyApiType != null && keyApiType.MarshalAs != null) || (valueApiType != null && valueApiType.MarshalAs != null)) + { + var keyConverter = keyApiType != null && keyApiType.MarshalAs != null ? $"({GenerateCSharpNativeToManaged(buildData, returnType.GenericArgs[0], caller)})" : ""; + var valueConverter = valueApiType != null && valueApiType.MarshalAs != null ? $"({GenerateCSharpNativeToManaged(buildData, returnType.GenericArgs[1], caller)})" : ""; + contents.Append($".ConvertDictionary(key => {keyConverter}key, value => {valueConverter}value)"); + } + } + contents.Append(';'); // Return result diff --git a/Source/Tools/Flax.Build/Bindings/BindingsGenerator.Cpp.cs b/Source/Tools/Flax.Build/Bindings/BindingsGenerator.Cpp.cs index c8d73c559..56798f797 100644 --- a/Source/Tools/Flax.Build/Bindings/BindingsGenerator.Cpp.cs +++ b/Source/Tools/Flax.Build/Bindings/BindingsGenerator.Cpp.cs @@ -171,6 +171,8 @@ namespace Flax.Build.Bindings return $"Variant({value}.Get())"; if (typeInfo.Type == "SoftTypeReference") return $"Variant::Typename(StringAnsiView({value}))"; + if (typeInfo.Type == "ScriptingObjectInterfaceReference") + return $"Variant({value}.GetObject())"; if (typeInfo.IsArray) { var wrapperName = GenerateCppWrapperNativeToVariantMethodName(typeInfo); @@ -305,12 +307,12 @@ namespace Flax.Build.Bindings return $"(StringAnsiView){value}"; if (typeInfo.IsPtr && typeInfo.IsConst && typeInfo.Type == "Char") return $"((StringView){value}).GetText()"; // (StringView)Variant, if not empty, is guaranteed to point to a null-terminated buffer. - if (typeInfo.Type == "ScriptingObjectReference" || typeInfo.Type == "SoftObjectReference") - return $"ScriptingObject::Cast<{typeInfo.GenericArgs[0].Type}>((ScriptingObject*){value})"; if (typeInfo.IsObjectRef) - return $"ScriptingObject::Cast<{typeInfo.GenericArgs[0].Type}>((Asset*){value})"; + return $"ScriptingObject::Cast<{typeInfo.GenericArgs[0].Type}>((ScriptingObject*){value})"; if (typeInfo.Type == "SoftTypeReference") return $"(StringAnsiView){value}"; + if (typeInfo.Type == "ScriptingObjectInterfaceReference") + return $"ScriptingObjectInterfaceReference<{typeInfo.GenericArgs[0].Type}>((ScriptingObject*){value})"; if (typeInfo.IsArray) throw new Exception($"Not supported type to convert from the Variant to fixed-size array '{typeInfo}[{typeInfo.ArraySize}]'."); if (typeInfo.Type == "Array" && typeInfo.GenericArgs != null) diff --git a/Source/Tools/Flax.Build/Bindings/ClassInfo.cs b/Source/Tools/Flax.Build/Bindings/ClassInfo.cs index f2d82cc6e..36c47138e 100644 --- a/Source/Tools/Flax.Build/Bindings/ClassInfo.cs +++ b/Source/Tools/Flax.Build/Bindings/ClassInfo.cs @@ -18,6 +18,7 @@ namespace Flax.Build.Bindings "ManagedScriptingObject", "PersistentScriptingObject", "ScriptingObjectReference", + "ScriptingObjectInterfaceReference", "AssetReference", "BinaryAsset", "SceneObject",