SerializableProperty.cs 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402
  1. //********************************** Banshee Engine (www.banshee3d.com) **************************************************//
  2. //**************** Copyright (c) 2016 Marko Pintera ([email protected]). All rights reserved. **********************//
  3. using System;
  4. using System.Collections;
  5. using System.Collections.Generic;
  6. using System.Runtime.CompilerServices;
  7. namespace BansheeEngine
  8. {
  9. /** @addtogroup Serialization
  10. * @{
  11. */
  12. /// <summary>
  13. /// Allows you to transparently retrieve and set values of an entry, whether that entry is an object field or
  14. /// an array/list/dictionary entry.
  15. /// </summary>
  16. public sealed class SerializableProperty : ScriptObject
  17. {
  18. /// <summary>
  19. /// Object field types support by the serializable property.
  20. /// </summary>
  21. public enum FieldType
  22. {
  23. Int,
  24. Float,
  25. Bool,
  26. String,
  27. Color,
  28. Vector2,
  29. Vector3,
  30. Vector4,
  31. GameObjectRef,
  32. Resource,
  33. Object,
  34. Array,
  35. List,
  36. Dictionary,
  37. RRef,
  38. ColorGradient,
  39. Curve,
  40. FloatDistribution,
  41. ColorDistribution
  42. }
  43. public delegate object Getter();
  44. public delegate void Setter(object value);
  45. private FieldType type;
  46. private Type internalType;
  47. private Getter getter;
  48. private Setter setter;
  49. /// <summary>
  50. /// Constructor for internal use by the native code.
  51. /// </summary>
  52. private SerializableProperty()
  53. { }
  54. /// <summary>
  55. /// Creates a new serializable property.
  56. /// </summary>
  57. /// <param name="type">Type of data the property contains.</param>
  58. /// <param name="internalType">Type of data the property contains, as C# type.</param>
  59. /// <param name="getter">Method that allows you to retrieve contents of the property.</param>
  60. /// <param name="setter">Method that allows you to set contents of the property</param>
  61. public SerializableProperty(FieldType type, Type internalType, Getter getter, Setter setter)
  62. {
  63. this.type = type;
  64. this.internalType = internalType;
  65. this.getter = getter;
  66. this.setter = setter;
  67. Internal_CreateInstance(this, internalType);
  68. }
  69. /// <summary>
  70. /// Finalizes construction of the serializable property. Must be called after creation.
  71. /// </summary>
  72. /// <param name="type">Type of data the property contains.</param>
  73. /// <param name="internalType">Type of data the property contains, as C# type.</param>
  74. /// <param name="getter">Method that allows you to retrieve contents of the property.</param>
  75. /// <param name="setter">Method that allows you to set contents of the property</param>
  76. internal void Construct(FieldType type, Type internalType, Getter getter, Setter setter)
  77. {
  78. this.type = type;
  79. this.internalType = internalType;
  80. this.getter = getter;
  81. this.setter = setter;
  82. }
  83. /// <summary>
  84. /// Returns type of data the property contains.
  85. /// </summary>
  86. public FieldType Type
  87. {
  88. get { return type; }
  89. }
  90. /// <summary>
  91. /// Returns type of data the property contains, as C# type.
  92. /// </summary>
  93. public Type InternalType
  94. {
  95. get { return internalType; }
  96. }
  97. /// <summary>
  98. /// Is the containing type a value type (true), or a reference type (false).
  99. /// </summary>
  100. public bool IsValueType
  101. {
  102. get { return internalType.IsValueType; }
  103. }
  104. /// <summary>
  105. /// Retrieves the value contained in the property.
  106. /// </summary>
  107. /// <typeparam name="T">Type of the value to retrieve. Caller must ensure the type matches the property type.</typeparam>
  108. /// <returns>Value of the property.</returns>
  109. public T GetValue<T>()
  110. {
  111. if (!typeof(T).IsAssignableFrom(internalType))
  112. throw new Exception("Attempted to retrieve a serializable value using an invalid type. Provided type: " + typeof(T) + ". Needed type: " + internalType);
  113. return (T)getter();
  114. }
  115. /// <summary>
  116. /// Changes the value of the property.
  117. /// </summary>
  118. /// <typeparam name="T">Type of the value to set. Caller must ensure the type matches the property type.</typeparam>
  119. /// <param name="value">New value to assign to the property.</param>
  120. public void SetValue<T>(T value)
  121. {
  122. if (!typeof(T).IsAssignableFrom(internalType))
  123. throw new Exception("Attempted to set a serializable value using an invalid type. Provided type: " + typeof(T) + ". Needed type: " + internalType);
  124. setter(value);
  125. }
  126. /// <summary>
  127. /// Returns a serializable object wrapper around the value contained in the property.
  128. /// </summary>
  129. /// <returns>Serializable object wrapper around the value contained in the property.</returns>
  130. public SerializableObject GetObject()
  131. {
  132. if (type != FieldType.Object)
  133. throw new Exception("Attempting to retrieve object information from a field that doesn't contain an object.");
  134. return Internal_CreateObject(mCachedPtr, this);
  135. }
  136. /// <summary>
  137. /// Returns a serializable array around the value contained in the property. Caller must ensure the property
  138. /// contains an array.
  139. /// </summary>
  140. /// <returns>Serializable array around the value contained in the property.</returns>
  141. public SerializableArray GetArray()
  142. {
  143. if (type != FieldType.Array)
  144. throw new Exception("Attempting to retrieve array information from a field that doesn't contain an array.");
  145. return Internal_CreateArray(mCachedPtr, this);
  146. }
  147. /// <summary>
  148. /// Returns a serializable list around the value contained in the property. Caller must ensure the property
  149. /// contains a list.
  150. /// </summary>
  151. /// <returns>Serializable list around the value contained in the property.</returns>
  152. public SerializableList GetList()
  153. {
  154. if (type != FieldType.List)
  155. throw new Exception("Attempting to retrieve array information from a field that doesn't contain a list.");
  156. return Internal_CreateList(mCachedPtr, this);
  157. }
  158. /// <summary>
  159. /// Returns a serializable dictionary around the value contained in the property. Caller must ensure the property
  160. /// contains a dictionary.
  161. /// </summary>
  162. /// <returns>Serializable dictionary around the value contained in the property.</returns>
  163. public SerializableDictionary GetDictionary()
  164. {
  165. if (type != FieldType.Dictionary)
  166. throw new Exception("Attempting to retrieve array information from a field that doesn't contain a dictionary.");
  167. return Internal_CreateDictionary(mCachedPtr, this);
  168. }
  169. /// <summary>
  170. /// Creates a new instance of the type wrapped by this property.
  171. /// </summary>
  172. /// <typeparam name="T">Type of the object to create. Caller must ensure the type matches the property type and that
  173. /// the property wraps an object.</typeparam>
  174. /// <returns>A new instance of an object of type <typeparamref name="T"/>.</returns>
  175. public T CreateObjectInstance<T>()
  176. {
  177. if (type != FieldType.Object)
  178. throw new Exception("Attempting to retrieve object information from a field that doesn't contain an object.");
  179. return (T)Internal_CreateManagedObjectInstance(mCachedPtr);
  180. }
  181. /// <summary>
  182. /// Creates a new instance of the array wrapped by this property. Caller must ensure this property contains an array.
  183. /// </summary>
  184. /// <param name="lengths">Size of each dimension of the array. Number of dimensions must match the number
  185. /// of dimensions in the array wrapped by this property.</param>
  186. /// <returns>A new array containing the same element type as the array wrapped by this property, of
  187. /// <paramref name="lengths"/> sizes.</returns>
  188. public Array CreateArrayInstance(int[] lengths)
  189. {
  190. if (type != FieldType.Array)
  191. throw new Exception("Attempting to retrieve array information from a field that doesn't contain an array.");
  192. return Internal_CreateManagedArrayInstance(mCachedPtr, lengths);
  193. }
  194. /// <summary>
  195. /// Creates a new instance of the list wrapped by this property. Caller must ensure this property contains a list.
  196. /// </summary>
  197. /// <param name="length">Size of the list.</param>
  198. /// <returns>A new list containing the same element type as the list wrapped by this property, of
  199. /// <paramref name="length"/> size.</returns>
  200. public IList CreateListInstance(int length)
  201. {
  202. if (type != FieldType.List)
  203. throw new Exception("Attempting to retrieve array information from a field that doesn't contain a list.");
  204. return Internal_CreateManagedListInstance(mCachedPtr, length);
  205. }
  206. /// <summary>
  207. /// Creates a new instance of the dictionary wrapped by this property. Caller must ensure this property contains
  208. /// a dictionary.
  209. /// </summary>
  210. /// <returns>A new dictionary containing the same key/value types as the dictionary wrapped by this property.
  211. /// </returns>
  212. public IDictionary CreateDictionaryInstance()
  213. {
  214. if (type != FieldType.Dictionary)
  215. throw new Exception("Attempting to retrieve array information from a field that doesn't contain a dictionary.");
  216. return Internal_CreateManagedDictionaryInstance(mCachedPtr);
  217. }
  218. /// <summary>
  219. /// Helper method used for finding child properties of the specified property, using a property path.
  220. /// <see cref="SerializableObject.FindProperty(string)"/>.
  221. /// </summary>
  222. /// <param name="pathElements">Path elements representing field names and keys to look for.</param>
  223. /// <param name="elementIdx">Index in the <paramref name="pathElements"/> array to start the search at.</param>
  224. /// <returns>Property representing the final path element, or null if not found (array index is out of range, or
  225. /// property with that path doesn't exist).</returns>
  226. internal SerializableProperty FindProperty(PropertyPathElement[] pathElements, int elementIdx)
  227. {
  228. switch (type)
  229. {
  230. case FieldType.Object:
  231. {
  232. SerializableObject childObject = GetObject();
  233. return childObject.FindProperty(pathElements, elementIdx);
  234. }
  235. case FieldType.Array:
  236. {
  237. SerializableArray childArray = GetArray();
  238. return childArray.FindProperty(pathElements, elementIdx);
  239. }
  240. case FieldType.List:
  241. {
  242. SerializableList childList = GetList();
  243. return childList.FindProperty(pathElements, elementIdx);
  244. }
  245. case FieldType.Dictionary:
  246. {
  247. SerializableDictionary childDictionary = GetDictionary();
  248. return childDictionary.FindProperty(pathElements, elementIdx);
  249. }
  250. }
  251. return null;
  252. }
  253. [MethodImpl(MethodImplOptions.InternalCall)]
  254. private static extern void Internal_CreateInstance(SerializableProperty instance, Type type);
  255. [MethodImpl(MethodImplOptions.InternalCall)]
  256. private static extern SerializableObject Internal_CreateObject(IntPtr nativeInstance, object managedInstance);
  257. [MethodImpl(MethodImplOptions.InternalCall)]
  258. private static extern SerializableArray Internal_CreateArray(IntPtr nativeInstance, object managedInstance);
  259. [MethodImpl(MethodImplOptions.InternalCall)]
  260. private static extern SerializableList Internal_CreateList(IntPtr nativeInstance, object managedInstance);
  261. [MethodImpl(MethodImplOptions.InternalCall)]
  262. private static extern SerializableDictionary Internal_CreateDictionary(IntPtr nativeInstance, object managedInstance);
  263. [MethodImpl(MethodImplOptions.InternalCall)]
  264. private static extern object Internal_CreateManagedObjectInstance(IntPtr nativeInstance);
  265. [MethodImpl(MethodImplOptions.InternalCall)]
  266. private static extern Array Internal_CreateManagedArrayInstance(IntPtr nativeInstance, int[] lengths);
  267. [MethodImpl(MethodImplOptions.InternalCall)]
  268. private static extern IList Internal_CreateManagedListInstance(IntPtr nativeInstance, int length);
  269. [MethodImpl(MethodImplOptions.InternalCall)]
  270. private static extern IDictionary Internal_CreateManagedDictionaryInstance(IntPtr nativeInstance);
  271. [MethodImpl(MethodImplOptions.InternalCall)]
  272. private static extern object Internal_CloneManagedInstance(IntPtr nativeInstance, object original);
  273. /// <summary>
  274. /// Converts a C# type into Banshee-specific serialization type.
  275. /// </summary>
  276. /// <param name="internalType">C# to convert.</param>
  277. /// <returns>Banshee-specific serialization type. Throws an exception if matching type cannot be found.</returns>
  278. public static FieldType DetermineFieldType(Type internalType)
  279. {
  280. if (!internalType.IsArray)
  281. {
  282. if (internalType == typeof (Byte))
  283. return FieldType.Int;
  284. else if (internalType == typeof (SByte))
  285. return FieldType.Int;
  286. else if (internalType == typeof (Int16))
  287. return FieldType.Int;
  288. else if (internalType == typeof (UInt16))
  289. return FieldType.Int;
  290. else if (internalType == typeof (Int32))
  291. return FieldType.Int;
  292. else if (internalType == typeof (UInt32))
  293. return FieldType.Int;
  294. else if (internalType == typeof (Int64))
  295. return FieldType.Int;
  296. else if (internalType == typeof (UInt64))
  297. return FieldType.Int;
  298. else if (internalType == typeof (bool))
  299. return FieldType.Bool;
  300. else if (internalType == typeof (float))
  301. return FieldType.Float;
  302. else if (internalType == typeof (double))
  303. return FieldType.Float;
  304. else if (internalType == typeof (string))
  305. return FieldType.String;
  306. else if (internalType == typeof (Vector2))
  307. return FieldType.Vector2;
  308. else if (internalType == typeof (Vector3))
  309. return FieldType.Vector3;
  310. else if (internalType == typeof (Vector4))
  311. return FieldType.Vector4;
  312. else if (internalType == typeof(Quaternion))
  313. return FieldType.Vector4;
  314. else if (internalType == typeof (Color))
  315. return FieldType.Color;
  316. else if (internalType == typeof(ColorGradient))
  317. return FieldType.ColorGradient;
  318. else if (internalType == typeof(AnimationCurve))
  319. return FieldType.Curve;
  320. else if (internalType == typeof(FloatDistribution))
  321. return FieldType.FloatDistribution;
  322. else if (internalType == typeof(ColorDistribution))
  323. return FieldType.ColorDistribution;
  324. else if (internalType.IsSubclassOf(typeof (GameObject)))
  325. return FieldType.GameObjectRef;
  326. else if (internalType.IsSubclassOf(typeof (Resource)))
  327. return FieldType.Resource;
  328. else if (internalType.IsSubclassOf(typeof (RRefBase)))
  329. return FieldType.RRef;
  330. else if (internalType.IsGenericType)
  331. {
  332. Type genericType = internalType.GetGenericTypeDefinition();
  333. if (genericType == typeof (List<>))
  334. return FieldType.List;
  335. else if (genericType == typeof (Dictionary<,>))
  336. return FieldType.Dictionary;
  337. else if (genericType == typeof(RRef<>))
  338. return FieldType.RRef;
  339. // Shouldn't happen because native code should only supply us with supported types
  340. throw new Exception("Cannot determine field type. Found an unsupported generic type.");
  341. }
  342. // Otherwise the type must be an object, unless some error occurred
  343. return FieldType.Object;
  344. }
  345. return FieldType.Array;
  346. }
  347. }
  348. /** @} */
  349. }