SerializableProperty.cs 19 KB

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