BsCoreObject.h 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269
  1. //__________________________ Banshee Project - A modern game development toolkit _________________________________//
  2. //_____________________________________ www.banshee-project.com __________________________________________________//
  3. //________________________ Copyright (c) 2014 Marko Pintera. All rights reserved. ________________________________//
  4. #pragma once
  5. #include "BsCorePrerequisites.h"
  6. #include "BsAsyncOp.h"
  7. namespace BansheeEngine
  8. {
  9. /**
  10. * @brief This class provides some common functionality that all low-level objects
  11. * used on the core thread need to implement.
  12. *
  13. * @note This involves initializing, keeping track of, and releasing GPU resources.
  14. * All core GPU objects are initialized on the core thread, and destroyed on the core thread,
  15. * so majority of these methods will just schedule object initialization/destruction.
  16. * Non-GPU core objects can normally be initialized on the caller thread.
  17. */
  18. class BS_CORE_EXPORT CoreObject
  19. {
  20. protected:
  21. /**
  22. * @brief Values that represent current state of the object
  23. */
  24. enum Flags
  25. {
  26. CGO_INITIALIZED = 0x01, /**< Object has been fully initialized and may be used. */
  27. CGO_INIT_ON_CORE_THREAD = 0x02, /**< Object requires initialization on core thread. */
  28. CGO_SCHEDULED_FOR_INIT = 0x04, /**< Object has been scheduled for initialization but core thread has not completed it yet. */
  29. CGO_SCHEDULED_FOR_DELETE = 0x08 /**< Object has been scheduled for deletion but core thread has not completed it yet. */
  30. };
  31. public:
  32. /**
  33. * @brief Constructs a new core object.
  34. *
  35. * @param requiresGpuInit (optional) If true the objects initialize_internal and destroy_internal methods
  36. * will be called from the core thread asynchronously. Otherwise they will be called
  37. * by the caller thread synchronously.
  38. */
  39. CoreObject(bool requiresGpuInit = true);
  40. virtual ~CoreObject();
  41. /**
  42. * @brief Destroys all GPU resources of this object.
  43. *
  44. * @note If is created with "CGO_INIT_ON_CORE_THREAD" flag destruction is not done immediately,
  45. * and is instead just scheduled on the core thread.
  46. * Unless called from core thread in which case it is executed immediately.
  47. * Objects without "CGO_INIT_ON_CORE_THREAD" flag are destructed immediately.
  48. */
  49. virtual void destroy();
  50. /**
  51. * @brief Initializes all the internal resources of this object. Should be called by the
  52. * factory creation methods automatically after construction and not by user directly.
  53. *
  54. * @note If is created with "CGO_INIT_ON_CORE_THREAD" flag initialization is not done immediately,
  55. * and is instead just scheduled on the core thread.
  56. * Unless called from core thread in which case it is executed immediately.
  57. * Objects without "CGO_INIT_ON_CORE_THREAD" flag are initialized immediately.
  58. */
  59. virtual void initialize();
  60. /**
  61. * @brief Returns true if the object has been properly initialized. You are not
  62. * allowed to call any methods on the resource until you are sure resource is initialized.
  63. *
  64. * @note Normally CPU objects are initialized on creation and this will never be false, and GPU
  65. * objects are initialized when the core thread processes them.
  66. */
  67. bool isInitialized() const { return (mFlags & CGO_INITIALIZED) != 0; }
  68. /**
  69. * @brief Blocks the current thread until the resource is fully initialized.
  70. *
  71. * @note If you call this without calling initialize first a deadlock will occur.
  72. * You should not call this from core thread.
  73. */
  74. void synchronize();
  75. /**
  76. * @brief Internal method. Sets a shared this pointer to this object. This MUST be called immediately after construction.
  77. *
  78. * @note Called automatically by the factory creation methods so user should not call this manually.
  79. */
  80. void _setThisPtr(std::shared_ptr<CoreObject> ptrThis);
  81. /**
  82. * @brief Returns an unique identifier for this object.
  83. */
  84. UINT64 getInternalID() const { return mInternalID; }
  85. /**
  86. * @brief Internal method. Schedules the object to be destroyed, and then deleted.
  87. */
  88. template<class T, class MemAlloc>
  89. static void _deleteDelayed(CoreObject* obj)
  90. {
  91. _deleteDelayedInternal(obj);
  92. if(obj->isInitialized())
  93. {
  94. std::shared_ptr<CoreObject> thisPtr(obj);
  95. obj->_setThisPtr(thisPtr);
  96. obj->destroy();
  97. }
  98. else
  99. {
  100. bs_delete<MemAlloc, T>((T*)obj);
  101. }
  102. }
  103. /**
  104. * @brief Returns a shared_ptr version of "this" pointer.
  105. */
  106. std::shared_ptr<CoreObject> getThisPtr() const { return mThis.lock(); }
  107. protected:
  108. /**
  109. * @brief Frees all of the objects dynamically allocated memory. All derived classes that have something to free
  110. * should do it here instead of their destructor. All derived classes need to call this base method when they're done.
  111. *
  112. * @note For objects with "CGO_INIT_ON_CORE_THREAD" flag this is scheduled to be executed on the core thread,
  113. * so normally you want to destroy all GPU specific resources here.
  114. */
  115. virtual void destroy_internal();
  116. /**
  117. * @brief Initializes all the internal resources of this object. Needs to be called before doing
  118. * any operations with the object. All derived classes also need to call this base method.
  119. *
  120. * @note For objects with "CGO_INIT_ON_CORE_THREAD" flag this is scheduled to be executed on the core thread,
  121. * so normally you want to initialize all GPU specific resources here.
  122. */
  123. virtual void initialize_internal();
  124. /**
  125. * @brief Performs some internal checks when an object is being deleted.
  126. */
  127. static void _deleteDelayedInternal(CoreObject* obj);
  128. /**
  129. * @brief Queues a command to be executed on the core thread, without a return value.
  130. *
  131. * @note Requires a shared pointer to the object this function will be executed on, in order to
  132. * make sure the object is not deleted before the command executes. Can be null if the
  133. * function is static or global.
  134. */
  135. static void queueGpuCommand(std::shared_ptr<CoreObject>& obj, std::function<void()> func);
  136. /**
  137. * @brief Queues a command to be executed on the core thread, with a return value in the form of AsyncOp.
  138. *
  139. * @see AsyncOp
  140. *
  141. * @note Requires a shared pointer to the object this function will be executed on, in order to
  142. * make sure the object is not deleted before the command executes. Can be null if the
  143. * function is static or global.
  144. */
  145. static AsyncOp queueReturnGpuCommand(std::shared_ptr<CoreObject>& obj, std::function<void(AsyncOp&)> func);
  146. bool isScheduledToBeInitialized() const { return (mFlags & CGO_SCHEDULED_FOR_INIT) != 0; }
  147. bool isScheduledToBeDeleted() const { return (mFlags & CGO_SCHEDULED_FOR_DELETE) != 0; }
  148. bool requiresInitOnCoreThread() const { return (mFlags & CGO_INIT_ON_CORE_THREAD) != 0; }
  149. void setIsInitialized(bool initialized) { mFlags = initialized ? mFlags | CGO_INITIALIZED : mFlags & ~CGO_INITIALIZED; }
  150. void setScheduledToBeInitialized(bool scheduled) { mFlags = scheduled ? mFlags | CGO_SCHEDULED_FOR_INIT : mFlags & ~CGO_SCHEDULED_FOR_INIT; }
  151. void setScheduledToBeDeleted(bool scheduled) { mFlags = scheduled ? mFlags | CGO_SCHEDULED_FOR_DELETE : mFlags & ~CGO_SCHEDULED_FOR_DELETE; }
  152. private:
  153. friend class CoreObjectManager;
  154. volatile UINT8 mFlags;
  155. UINT64 mInternalID; // ID == 0 is not a valid ID
  156. std::weak_ptr<CoreObject> mThis;
  157. BS_STATIC_THREAD_SYNCHRONISER(mCoreGpuObjectLoadedCondition)
  158. BS_STATIC_MUTEX(mCoreGpuObjectLoadedMutex)
  159. /**
  160. * @brief Queues object initialization command on the core thread. The command is added to the
  161. * primary core thread queue and will be executed as soon as the core thread is ready.
  162. */
  163. static void queueInitializeGpuCommand(std::shared_ptr<CoreObject>& obj);
  164. /**
  165. * @brief Queues object destruction command on the core thread. The command is added to the
  166. * core thread accessor of this thread and will be executed after accessor commands
  167. * are submitted and any previously queued commands are executed.
  168. *
  169. * @note It is up to the caller to ensure no other accessors attempt to use this object.
  170. */
  171. static void queueDestroyGpuCommand(std::shared_ptr<CoreObject>& obj);
  172. /**
  173. * @brief Helper wrapper method used for queuing commands with no return value on the core thread.
  174. */
  175. static void executeGpuCommand(std::shared_ptr<CoreObject> obj, std::function<void()> func);
  176. /**
  177. * @brief Helper wrapper method used for queuing commands with a return value on the core thread.
  178. */
  179. static void executeReturnGpuCommand(std::shared_ptr<CoreObject> obj, std::function<void(AsyncOp&)> func, AsyncOp& op);
  180. };
  181. /**
  182. * @brief Creates a new core object using the specified allocators and returns a shared pointer to it.
  183. *
  184. * @note All core thread object shared pointers must be created using this method or its overloads
  185. * and you should not create them manually.
  186. */
  187. template<class Type, class MainAlloc, class PtrDataAlloc, class... Args>
  188. std::shared_ptr<Type> bs_core_ptr(Args &&...args)
  189. {
  190. return std::shared_ptr<Type>(bs_new<Type, MainAlloc>(std::forward<Args>(args)...),
  191. &CoreObject::_deleteDelayed<Type, MainAlloc>, StdAlloc<PtrDataAlloc>());
  192. }
  193. /**
  194. * @brief Creates a new core object using the specified allocator and returns a shared pointer to it.
  195. *
  196. * @note All core thread object shared pointers must be created using this method or its overloads
  197. * and you should not create them manually.
  198. */
  199. template<class Type, class MainAlloc, class... Args>
  200. std::shared_ptr<Type> bs_core_ptr(Args &&...args)
  201. {
  202. return std::shared_ptr<Type>(bs_new<Type, MainAlloc>(std::forward<Args>(args)...),
  203. &CoreObject::_deleteDelayed<Type, MainAlloc>, StdAlloc<GenAlloc>());
  204. }
  205. /**
  206. * @brief Creates a new core object and returns a shared pointer to it.
  207. *
  208. * @note All core thread object shared pointers must be created using this method or its overloads
  209. * and you should not create them manually.
  210. */
  211. template<class Type, class... Args>
  212. std::shared_ptr<Type> bs_core_ptr(Args &&...args)
  213. {
  214. return std::shared_ptr<Type>(bs_new<Type, GenAlloc>(std::forward<Args>(args)...),
  215. &CoreObject::_deleteDelayed<Type, GenAlloc>, StdAlloc<GenAlloc>());
  216. }
  217. /**
  218. * @brief Creates a core object shared pointer using a previously constructed object.
  219. *
  220. * @note All core thread object shared pointers must be created using this method or its overloads
  221. * and you should not create them manually.
  222. */
  223. template<class Type, class MainAlloc>
  224. std::shared_ptr<Type> bs_core_ptr(Type* data)
  225. {
  226. return std::shared_ptr<Type>(data, &CoreObject::_deleteDelayed<Type, MainAlloc>, StdAlloc<GenAlloc>());
  227. }
  228. /**
  229. * @brief Creates a core object shared pointer using a previously constructed object.
  230. *
  231. * @note All core thread object shared pointers must be created using this method or its overloads
  232. * and you should not create them manually.
  233. */
  234. template<class Type, class MainAlloc, class PtrDataAlloc>
  235. std::shared_ptr<Type> bs_core_ptr(Type* data)
  236. {
  237. return std::shared_ptr<Type>(data, &CoreObject::_deleteDelayed<Type, MainAlloc>, StdAlloc<PtrDataAlloc>());
  238. }
  239. }