BsCommandQueue.h 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399
  1. #pragma once
  2. #include "BsCorePrerequisites.h"
  3. #include "BsAsyncOp.h"
  4. #include <functional>
  5. namespace BansheeEngine
  6. {
  7. /**
  8. * @brief Command queue policy that provides no synchonization. Should be used
  9. * with command queues that are used on a single thread only.
  10. */
  11. class CommandQueueNoSync
  12. {
  13. public:
  14. CommandQueueNoSync() {}
  15. virtual ~CommandQueueNoSync() {}
  16. bool isValidThread(BS_THREAD_ID_TYPE ownerThread) const
  17. {
  18. return BS_THREAD_CURRENT_ID == ownerThread;
  19. }
  20. void lock() { };
  21. void unlock() { }
  22. };
  23. /**
  24. * @brief Command queue policy that provides synchonization. Should be used
  25. * with command queues that are used on multiple threads.
  26. */
  27. class CommandQueueSync
  28. {
  29. public:
  30. CommandQueueSync()
  31. :mLock(mCommandQueueMutex, BS_DEFER_LOCK)
  32. { }
  33. virtual ~CommandQueueSync() {}
  34. bool isValidThread(BS_THREAD_ID_TYPE ownerThread) const
  35. {
  36. return true;
  37. }
  38. void lock()
  39. {
  40. mLock.lock();
  41. };
  42. void unlock()
  43. {
  44. mLock.unlock();
  45. }
  46. private:
  47. BS_MUTEX(mCommandQueueMutex);
  48. BS_LOCK_TYPE mLock;
  49. };
  50. /**
  51. * @brief Represents a single queued command in the command list. Contains all the data for executing the command
  52. * and checking up on the command status.
  53. */
  54. struct QueuedCommand
  55. {
  56. #if BS_DEBUG_MODE
  57. QueuedCommand(std::function<void(AsyncOp&)> _callback, UINT32 _debugId, bool _notifyWhenComplete = false, UINT32 _callbackId = 0)
  58. :callbackWithReturnValue(_callback), debugId(_debugId), returnsValue(true), notifyWhenComplete(_notifyWhenComplete), callbackId(_callbackId), asyncOp(bs_new<AsyncOp>()), ownsData(true)
  59. { }
  60. QueuedCommand(std::function<void()> _callback, UINT32 _debugId, bool _notifyWhenComplete = false, UINT32 _callbackId = 0)
  61. :callback(_callback), debugId(_debugId), returnsValue(false), notifyWhenComplete(_notifyWhenComplete), callbackId(_callbackId), asyncOp(nullptr), ownsData(true)
  62. { }
  63. UINT32 debugId;
  64. #else
  65. QueuedCommand(std::function<void(AsyncOp&)> _callback, bool _notifyWhenComplete = false, UINT32 _callbackId = 0)
  66. :callbackWithReturnValue(_callback), returnsValue(true), notifyWhenComplete(_notifyWhenComplete), callbackId(_callbackId), asyncOp(bs_new<AsyncOp>()), ownsData(true)
  67. { }
  68. QueuedCommand(std::function<void()> _callback, bool _notifyWhenComplete = false, UINT32 _callbackId = 0)
  69. :callback(_callback), returnsValue(false), notifyWhenComplete(_notifyWhenComplete), callbackId(_callbackId), asyncOp(nullptr), ownsData(true)
  70. { }
  71. #endif
  72. ~QueuedCommand()
  73. {
  74. if(ownsData && asyncOp != nullptr)
  75. bs_delete(asyncOp);
  76. }
  77. QueuedCommand(const QueuedCommand& source)
  78. {
  79. ownsData = true;
  80. source.ownsData = false;
  81. callback = source.callback;
  82. callbackWithReturnValue = source.callbackWithReturnValue;
  83. asyncOp = source.asyncOp;
  84. returnsValue = source.returnsValue;
  85. callbackId = source.callbackId;
  86. notifyWhenComplete = source.notifyWhenComplete;
  87. }
  88. QueuedCommand& operator=(const QueuedCommand& rhs)
  89. {
  90. ownsData = true;
  91. rhs.ownsData = false;
  92. callback = rhs.callback;
  93. callbackWithReturnValue = rhs.callbackWithReturnValue;
  94. asyncOp = rhs.asyncOp;
  95. returnsValue = rhs.returnsValue;
  96. callbackId = rhs.callbackId;
  97. notifyWhenComplete = rhs.notifyWhenComplete;
  98. return *this;
  99. }
  100. std::function<void()> callback;
  101. std::function<void(AsyncOp&)> callbackWithReturnValue;
  102. AsyncOp* asyncOp;
  103. bool returnsValue;
  104. UINT32 callbackId;
  105. bool notifyWhenComplete;
  106. mutable bool ownsData;
  107. };
  108. /**
  109. * @brief Contains a list of commands you may queue for later execution on the core thread.
  110. */
  111. class BS_CORE_EXPORT CommandQueueBase
  112. {
  113. public:
  114. /**
  115. * @brief Constructor.
  116. *
  117. * @param threadId Identifier for the thread the command queue will be getting commands from.
  118. */
  119. CommandQueueBase(BS_THREAD_ID_TYPE threadId);
  120. virtual ~CommandQueueBase();
  121. /**
  122. * @brief Gets the thread identifier the command queue is used on.
  123. *
  124. * @note If the command queue is using a synchonized access policy generally this
  125. * is not relevant as it may be used on multiple threads.
  126. */
  127. BS_THREAD_ID_TYPE getThreadId() const { return mMyThreadId; }
  128. /**
  129. * @brief Executes all provided commands one by one in order. To get the commands you should call flush().
  130. *
  131. * @param notifyCallback Callback that will be called if a command that has "notifyOnComplete" flag set.
  132. * The callback will receive "callbackId" of the command.
  133. */
  134. void playbackWithNotify(Queue<QueuedCommand>* commands, std::function<void(UINT32)> notifyCallback);
  135. /**
  136. * @brief Executes all provided commands one by one in order. To get the commands you should call flush().
  137. */
  138. void playback(Queue<QueuedCommand>* commands);
  139. /**
  140. * @brief Allows you to set a breakpoint that will trigger when the specified command is executed.
  141. *
  142. * @note This is helpful when you receive an error on the executing thread and you cannot tell from where was
  143. * the command that caused the error queued from. However you can make a note of the queue and command index
  144. * and set a breakpoint so that it gets triggered next time you run the program. At that point you can know
  145. * exactly which part of code queued the command by examining the stack trace.
  146. *
  147. * @param queueIdx Zero-based index of the queue the command was queued on.
  148. * @param commandIdx Zero-based index of the command.
  149. */
  150. static void addBreakpoint(UINT32 queueIdx, UINT32 commandIdx);
  151. /**
  152. * @brief Queue up a new command to execute. Make sure the provided function has all of its
  153. * parameters properly bound. Last parameter must be unbound and of AsyncOp& type.
  154. * This is used to signal that the command is completed, and also for storing the return
  155. * value.
  156. *
  157. * @note Callback method also needs to call AsyncOp::markAsResolved once it is done
  158. * processing. (If it doesn't it will still be called automatically, but the return
  159. * value will default to nullptr)
  160. *
  161. * @param _notifyWhenComplete (optional) Call the notify method (provided in the call to CommandQueue::playback)
  162. * when the command is complete.
  163. * @param _callbackId (optional) Identifier for the callback so you can then later find it
  164. * if needed.
  165. *
  166. * @return Async operation object that you can continuously check until the command completes. After
  167. * it completes AsyncOp::isResolved will return true and return data will be valid (if
  168. * the callback provided any).
  169. */
  170. AsyncOp queueReturn(std::function<void(AsyncOp&)> commandCallback, bool _notifyWhenComplete = false, UINT32 _callbackId = 0);
  171. /**
  172. * @brief Queue up a new command to execute. Make sure the provided function has all of its
  173. * parameters properly bound. Provided command is not expected to return a value. If you
  174. * wish to return a value from the callback use the queueReturn which accepts an AsyncOp parameter.
  175. *
  176. * @param _notifyWhenComplete (optional) Call the notify method (provided in the call to CommandQueue::playback)
  177. * when the command is complete.
  178. * @param _callbackId (optional) Identifier for the callback so you can then later find
  179. * it if needed.
  180. */
  181. void queue(std::function<void()> commandCallback, bool _notifyWhenComplete = false, UINT32 _callbackId = 0);
  182. /**
  183. * @brief Returns a copy of all queued commands and makes room for new ones. Must be called from the thread
  184. * that created the command queue. Returned commands MUST be passed to "playback" method.
  185. */
  186. BansheeEngine::Queue<QueuedCommand>* flush();
  187. /**
  188. * @brief Cancels all currently queued commands.
  189. */
  190. void cancelAll();
  191. /**
  192. * @brief Returns true if no commands are queued.
  193. */
  194. bool isEmpty();
  195. protected:
  196. /**
  197. * @brief Helper method that throws an "Invalid thread" exception. Used primarily
  198. * so we can avoid including Exception include in this header.
  199. */
  200. void throwInvalidThreadException(const String& message) const;
  201. private:
  202. BansheeEngine::Queue<QueuedCommand>* mCommands;
  203. Stack<BansheeEngine::Queue<QueuedCommand>*> mEmptyCommandQueues; // List of empty queues for reuse
  204. BS_THREAD_ID_TYPE mMyThreadId;
  205. // Various variables that allow for easier debugging by allowing us to trigger breakpoints
  206. // when a certain command was queued.
  207. #if BS_DEBUG_MODE
  208. struct QueueBreakpoint
  209. {
  210. class HashFunction
  211. {
  212. public:
  213. size_t operator()(const QueueBreakpoint &key) const;
  214. };
  215. class EqualFunction
  216. {
  217. public:
  218. bool operator()(const QueueBreakpoint &a, const QueueBreakpoint &b) const;
  219. };
  220. QueueBreakpoint(UINT32 _queueIdx, UINT32 _commandIdx)
  221. :queueIdx(_queueIdx), commandIdx(_commandIdx)
  222. { }
  223. UINT32 queueIdx;
  224. UINT32 commandIdx;
  225. inline size_t operator()(const QueueBreakpoint& v) const;
  226. };
  227. UINT32 mMaxDebugIdx;
  228. UINT32 mCommandQueueIdx;
  229. static UINT32 MaxCommandQueueIdx;
  230. static UnorderedSet<QueueBreakpoint, QueueBreakpoint::HashFunction, QueueBreakpoint::EqualFunction> SetBreakpoints;
  231. BS_STATIC_MUTEX(CommandQueueBreakpointMutex);
  232. /**
  233. * @brief Checks if the specified command has a breakpoint and throw an assert if it does.
  234. */
  235. static void breakIfNeeded(UINT32 queueIdx, UINT32 commandIdx);
  236. #endif
  237. };
  238. /**
  239. * @copydoc CommandQueueBase
  240. *
  241. * @brief Use SyncPolicy to choose whether you want command queue be synchonized or not. Synchonized
  242. * command queues may be used across multiple threads and non-synchonized only on one.
  243. */
  244. template<class SyncPolicy = CommandQueueNoSync>
  245. class CommandQueue : public CommandQueueBase, public SyncPolicy
  246. {
  247. public:
  248. /**
  249. * @copydoc CommandQueueBase::CommandQueueBase
  250. */
  251. CommandQueue(BS_THREAD_ID_TYPE threadId)
  252. :CommandQueueBase(threadId)
  253. { }
  254. ~CommandQueue()
  255. {
  256. #if BS_DEBUG_MODE
  257. #if BS_THREAD_SUPPORT != 0
  258. if(!isValidThread(getThreadId()))
  259. throwInvalidThreadException("Command queue accessed outside of its creation thread.");
  260. #endif
  261. #endif
  262. }
  263. /**
  264. * @copydoc CommandQueueBase::queueReturn
  265. */
  266. AsyncOp queueReturn(std::function<void(AsyncOp&)> commandCallback, bool _notifyWhenComplete = false, UINT32 _callbackId = 0)
  267. {
  268. #if BS_DEBUG_MODE
  269. #if BS_THREAD_SUPPORT != 0
  270. if(!isValidThread(getThreadId()))
  271. throwInvalidThreadException("Command queue accessed outside of its creation thread.");
  272. #endif
  273. #endif
  274. lock();
  275. AsyncOp asyncOp = CommandQueueBase::queueReturn(commandCallback, _notifyWhenComplete, _callbackId);
  276. unlock();
  277. return asyncOp;
  278. }
  279. /**
  280. * @copydoc CommandQueueBase::queue
  281. */
  282. void queue(std::function<void()> commandCallback, bool _notifyWhenComplete = false, UINT32 _callbackId = 0)
  283. {
  284. #if BS_DEBUG_MODE
  285. #if BS_THREAD_SUPPORT != 0
  286. if(!isValidThread(getThreadId()))
  287. throwInvalidThreadException("Command queue accessed outside of its creation thread.");
  288. #endif
  289. #endif
  290. lock();
  291. CommandQueueBase::queue(commandCallback, _notifyWhenComplete, _callbackId);
  292. unlock();
  293. }
  294. /**
  295. * @copydoc CommandQueueBase::flush
  296. */
  297. BansheeEngine::Queue<QueuedCommand>* flush()
  298. {
  299. #if BS_DEBUG_MODE
  300. #if BS_THREAD_SUPPORT != 0
  301. if(!isValidThread(getThreadId()))
  302. throwInvalidThreadException("Command queue accessed outside of its creation thread.");
  303. #endif
  304. #endif
  305. lock();
  306. BansheeEngine::Queue<QueuedCommand>* commands = CommandQueueBase::flush();
  307. unlock();
  308. return commands;
  309. }
  310. /**
  311. * @copydoc CommandQueueBase::cancelAll
  312. */
  313. void cancelAll()
  314. {
  315. #if BS_DEBUG_MODE
  316. #if BS_THREAD_SUPPORT != 0
  317. if(!isValidThread(getThreadId()))
  318. throwInvalidThreadException("Command queue accessed outside of its creation thread.");
  319. #endif
  320. #endif
  321. lock();
  322. CommandQueueBase::cancelAll();
  323. unlock();
  324. }
  325. /**
  326. * @copydoc CommandQueueBase::isEmpty
  327. */
  328. bool isEmpty()
  329. {
  330. #if BS_DEBUG_MODE
  331. #if BS_THREAD_SUPPORT != 0
  332. if(!isValidThread(getThreadId()))
  333. throwInvalidThreadException("Command queue accessed outside of its creation thread.");
  334. #endif
  335. #endif
  336. lock();
  337. bool empty = CommandQueueBase::isEmpty();
  338. unlock();
  339. return empty;
  340. }
  341. };
  342. }