SerializableProperty.cs 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417
  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. // Cast if possible
  112. if (typeof(T) != internalType)
  113. {
  114. // Note: Not checking cast operators
  115. if (internalType.IsPrimitive || internalType.IsEnum)
  116. {
  117. if (internalType == typeof(bool) || typeof(T) == typeof(bool))
  118. throw new Exception("Attempted to retrieve a serializable value using an invalid type. " +
  119. "Provided type: " + typeof(T) + ". Needed type: " + internalType);
  120. return (T) Convert.ChangeType(getter(), typeof(T));
  121. }
  122. if(!typeof(T).IsAssignableFrom(internalType))
  123. throw new Exception("Attempted to retrieve a serializable value using an invalid type. " +
  124. "Provided type: " + typeof(T) + ". Needed type: " + internalType);
  125. }
  126. return (T)getter();
  127. }
  128. /// <summary>
  129. /// Changes the value of the property.
  130. /// </summary>
  131. /// <typeparam name="T">Type of the value to set. Caller must ensure the type matches the property type.</typeparam>
  132. /// <param name="value">New value to assign to the property.</param>
  133. public void SetValue<T>(T value)
  134. {
  135. if (!typeof(T).IsAssignableFrom(internalType))
  136. throw new Exception("Attempted to set a serializable value using an invalid type. Provided type: " + typeof(T) + ". Needed type: " + internalType);
  137. setter(value);
  138. }
  139. /// <summary>
  140. /// Returns a serializable object wrapper around the value contained in the property.
  141. /// </summary>
  142. /// <returns>Serializable object wrapper around the value contained in the property.</returns>
  143. public SerializableObject GetObject()
  144. {
  145. if (type != FieldType.Object)
  146. throw new Exception("Attempting to retrieve object information from a field that doesn't contain an object.");
  147. return Internal_CreateObject(mCachedPtr, this);
  148. }
  149. /// <summary>
  150. /// Returns a serializable array around the value contained in the property. Caller must ensure the property
  151. /// contains an array.
  152. /// </summary>
  153. /// <returns>Serializable array around the value contained in the property.</returns>
  154. public SerializableArray GetArray()
  155. {
  156. if (type != FieldType.Array)
  157. throw new Exception("Attempting to retrieve array information from a field that doesn't contain an array.");
  158. return Internal_CreateArray(mCachedPtr, this);
  159. }
  160. /// <summary>
  161. /// Returns a serializable list around the value contained in the property. Caller must ensure the property
  162. /// contains a list.
  163. /// </summary>
  164. /// <returns>Serializable list around the value contained in the property.</returns>
  165. public SerializableList GetList()
  166. {
  167. if (type != FieldType.List)
  168. throw new Exception("Attempting to retrieve array information from a field that doesn't contain a list.");
  169. return Internal_CreateList(mCachedPtr, this);
  170. }
  171. /// <summary>
  172. /// Returns a serializable dictionary around the value contained in the property. Caller must ensure the property
  173. /// contains a dictionary.
  174. /// </summary>
  175. /// <returns>Serializable dictionary around the value contained in the property.</returns>
  176. public SerializableDictionary GetDictionary()
  177. {
  178. if (type != FieldType.Dictionary)
  179. throw new Exception("Attempting to retrieve array information from a field that doesn't contain a dictionary.");
  180. return Internal_CreateDictionary(mCachedPtr, this);
  181. }
  182. /// <summary>
  183. /// Creates a new instance of the type wrapped by this property.
  184. /// </summary>
  185. /// <typeparam name="T">Type of the object to create. Caller must ensure the type matches the property type and that
  186. /// the property wraps an object.</typeparam>
  187. /// <returns>A new instance of an object of type <typeparamref name="T"/>.</returns>
  188. public T CreateObjectInstance<T>()
  189. {
  190. if (type != FieldType.Object)
  191. throw new Exception("Attempting to retrieve object information from a field that doesn't contain an object.");
  192. return (T)Internal_CreateManagedObjectInstance(mCachedPtr);
  193. }
  194. /// <summary>
  195. /// Creates a new instance of the array wrapped by this property. Caller must ensure this property contains an array.
  196. /// </summary>
  197. /// <param name="lengths">Size of each dimension of the array. Number of dimensions must match the number
  198. /// of dimensions in the array wrapped by this property.</param>
  199. /// <returns>A new array containing the same element type as the array wrapped by this property, of
  200. /// <paramref name="lengths"/> sizes.</returns>
  201. public Array CreateArrayInstance(int[] lengths)
  202. {
  203. if (type != FieldType.Array)
  204. throw new Exception("Attempting to retrieve array information from a field that doesn't contain an array.");
  205. return Internal_CreateManagedArrayInstance(mCachedPtr, lengths);
  206. }
  207. /// <summary>
  208. /// Creates a new instance of the list wrapped by this property. Caller must ensure this property contains a list.
  209. /// </summary>
  210. /// <param name="length">Size of the list.</param>
  211. /// <returns>A new list containing the same element type as the list wrapped by this property, of
  212. /// <paramref name="length"/> size.</returns>
  213. public IList CreateListInstance(int length)
  214. {
  215. if (type != FieldType.List)
  216. throw new Exception("Attempting to retrieve array information from a field that doesn't contain a list.");
  217. return Internal_CreateManagedListInstance(mCachedPtr, length);
  218. }
  219. /// <summary>
  220. /// Creates a new instance of the dictionary wrapped by this property. Caller must ensure this property contains
  221. /// a dictionary.
  222. /// </summary>
  223. /// <returns>A new dictionary containing the same key/value types as the dictionary wrapped by this property.
  224. /// </returns>
  225. public IDictionary CreateDictionaryInstance()
  226. {
  227. if (type != FieldType.Dictionary)
  228. throw new Exception("Attempting to retrieve array information from a field that doesn't contain a dictionary.");
  229. return Internal_CreateManagedDictionaryInstance(mCachedPtr);
  230. }
  231. /// <summary>
  232. /// Helper method used for finding child properties of the specified property, using a property path.
  233. /// <see cref="SerializableObject.FindProperty(string)"/>.
  234. /// </summary>
  235. /// <param name="pathElements">Path elements representing field names and keys to look for.</param>
  236. /// <param name="elementIdx">Index in the <paramref name="pathElements"/> array to start the search at.</param>
  237. /// <returns>Property representing the final path element, or null if not found (array index is out of range, or
  238. /// property with that path doesn't exist).</returns>
  239. internal SerializableProperty FindProperty(PropertyPathElement[] pathElements, int elementIdx)
  240. {
  241. switch (type)
  242. {
  243. case FieldType.Object:
  244. {
  245. SerializableObject childObject = GetObject();
  246. return childObject.FindProperty(pathElements, elementIdx);
  247. }
  248. case FieldType.Array:
  249. {
  250. SerializableArray childArray = GetArray();
  251. return childArray.FindProperty(pathElements, elementIdx);
  252. }
  253. case FieldType.List:
  254. {
  255. SerializableList childList = GetList();
  256. return childList.FindProperty(pathElements, elementIdx);
  257. }
  258. case FieldType.Dictionary:
  259. {
  260. SerializableDictionary childDictionary = GetDictionary();
  261. return childDictionary.FindProperty(pathElements, elementIdx);
  262. }
  263. }
  264. return null;
  265. }
  266. [MethodImpl(MethodImplOptions.InternalCall)]
  267. private static extern void Internal_CreateInstance(SerializableProperty instance, Type type);
  268. [MethodImpl(MethodImplOptions.InternalCall)]
  269. private static extern SerializableObject Internal_CreateObject(IntPtr nativeInstance, object managedInstance);
  270. [MethodImpl(MethodImplOptions.InternalCall)]
  271. private static extern SerializableArray Internal_CreateArray(IntPtr nativeInstance, object managedInstance);
  272. [MethodImpl(MethodImplOptions.InternalCall)]
  273. private static extern SerializableList Internal_CreateList(IntPtr nativeInstance, object managedInstance);
  274. [MethodImpl(MethodImplOptions.InternalCall)]
  275. private static extern SerializableDictionary Internal_CreateDictionary(IntPtr nativeInstance, object managedInstance);
  276. [MethodImpl(MethodImplOptions.InternalCall)]
  277. private static extern object Internal_CreateManagedObjectInstance(IntPtr nativeInstance);
  278. [MethodImpl(MethodImplOptions.InternalCall)]
  279. private static extern Array Internal_CreateManagedArrayInstance(IntPtr nativeInstance, int[] lengths);
  280. [MethodImpl(MethodImplOptions.InternalCall)]
  281. private static extern IList Internal_CreateManagedListInstance(IntPtr nativeInstance, int length);
  282. [MethodImpl(MethodImplOptions.InternalCall)]
  283. private static extern IDictionary Internal_CreateManagedDictionaryInstance(IntPtr nativeInstance);
  284. [MethodImpl(MethodImplOptions.InternalCall)]
  285. private static extern object Internal_CloneManagedInstance(IntPtr nativeInstance, object original);
  286. /// <summary>
  287. /// Converts a C# type into Banshee-specific serialization type.
  288. /// </summary>
  289. /// <param name="internalType">C# to convert.</param>
  290. /// <returns>Banshee-specific serialization type. Throws an exception if matching type cannot be found.</returns>
  291. public static FieldType DetermineFieldType(Type internalType)
  292. {
  293. if (!internalType.IsArray)
  294. {
  295. if (internalType == typeof (Byte))
  296. return FieldType.Int;
  297. else if (internalType == typeof (SByte))
  298. return FieldType.Int;
  299. else if (internalType == typeof (Int16))
  300. return FieldType.Int;
  301. else if (internalType == typeof (UInt16))
  302. return FieldType.Int;
  303. else if (internalType == typeof (Int32))
  304. return FieldType.Int;
  305. else if (internalType == typeof (UInt32))
  306. return FieldType.Int;
  307. else if (internalType == typeof (Int64))
  308. return FieldType.Int;
  309. else if (internalType == typeof (UInt64))
  310. return FieldType.Int;
  311. else if (internalType == typeof (bool))
  312. return FieldType.Bool;
  313. else if (internalType == typeof (float))
  314. return FieldType.Float;
  315. else if (internalType == typeof (double))
  316. return FieldType.Float;
  317. else if (internalType == typeof (string))
  318. return FieldType.String;
  319. else if (internalType == typeof (Vector2))
  320. return FieldType.Vector2;
  321. else if (internalType == typeof (Vector3))
  322. return FieldType.Vector3;
  323. else if (internalType == typeof (Vector4))
  324. return FieldType.Vector4;
  325. else if (internalType == typeof(Quaternion))
  326. return FieldType.Vector4;
  327. else if (internalType == typeof (Color))
  328. return FieldType.Color;
  329. else if (internalType == typeof(ColorGradient))
  330. return FieldType.ColorGradient;
  331. else if (internalType == typeof(AnimationCurve))
  332. return FieldType.Curve;
  333. else if (internalType == typeof(FloatDistribution))
  334. return FieldType.FloatDistribution;
  335. else if (internalType == typeof(ColorDistribution))
  336. return FieldType.ColorDistribution;
  337. else if (internalType.IsSubclassOf(typeof (GameObject)))
  338. return FieldType.GameObjectRef;
  339. else if (internalType.IsSubclassOf(typeof (Resource)))
  340. return FieldType.Resource;
  341. else if (internalType.IsSubclassOf(typeof (RRefBase)))
  342. return FieldType.RRef;
  343. else if (internalType.IsGenericType)
  344. {
  345. Type genericType = internalType.GetGenericTypeDefinition();
  346. if (genericType == typeof (List<>))
  347. return FieldType.List;
  348. else if (genericType == typeof (Dictionary<,>))
  349. return FieldType.Dictionary;
  350. else if (genericType == typeof(RRef<>))
  351. return FieldType.RRef;
  352. // Shouldn't happen because native code should only supply us with supported types
  353. throw new Exception("Cannot determine field type. Found an unsupported generic type.");
  354. }
  355. // Otherwise the type must be an object, unless some error occurred
  356. return FieldType.Object;
  357. }
  358. return FieldType.Array;
  359. }
  360. }
  361. /** @} */
  362. }