CCScheduler.cpp 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523
  1. /****************************************************************************
  2. Copyright (c) 2008-2010 Ricardo Quesada
  3. Copyright (c) 2010-2012 cocos2d-x.org
  4. Copyright (c) 2011 Zynga Inc.
  5. Copyright (c) 2013-2016 Chukong Technologies Inc.
  6. Copyright (c) 2017-2018 Xiamen Yaji Software Co., Ltd.
  7. http://www.cocos2d-x.org
  8. Permission is hereby granted, free of charge, to any person obtaining a copy
  9. of this software and associated documentation files (the "Software"), to deal
  10. in the Software without restriction, including without limitation the rights
  11. to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  12. copies of the Software, and to permit persons to whom the Software is
  13. furnished to do so, subject to the following conditions:
  14. The above copyright notice and this permission notice shall be included in
  15. all copies or substantial portions of the Software.
  16. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  17. IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  18. FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  19. AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  20. LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  21. OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
  22. THE SOFTWARE.
  23. ****************************************************************************/
  24. #include "base/CCScheduler.h"
  25. #include "base/ccMacros.h"
  26. #include "base/utlist.h"
  27. #include "base/ccCArray.h"
  28. #define CC_REPEAT_FOREVER (UINT_MAX -1)
  29. NS_CC_BEGIN
  30. // data structures
  31. // A list double-linked list used for "updates with priority"
  32. typedef struct _listEntry
  33. {
  34. struct _listEntry *prev, *next;
  35. ccSchedulerFunc callback;
  36. void *target;
  37. int priority;
  38. bool paused;
  39. bool markedForDeletion; // selector will no longer be called and entry will be removed at end of the next tick
  40. } tListEntry;
  41. typedef struct _hashUpdateEntry
  42. {
  43. tListEntry **list; // Which list does it belong to ?
  44. tListEntry *entry; // entry in the list
  45. void *target;
  46. ccSchedulerFunc callback;
  47. UT_hash_handle hh;
  48. } tHashUpdateEntry;
  49. // Hash Element used for "selectors with interval"
  50. typedef struct _hashSelectorEntry
  51. {
  52. ccArray *timers;
  53. void *target;
  54. int timerIndex;
  55. Timer *currentTimer;
  56. bool currentTimerSalvaged;
  57. bool paused;
  58. UT_hash_handle hh;
  59. } tHashTimerEntry;
  60. // implementation Timer
  61. Timer::Timer()
  62. {
  63. }
  64. void Timer::setupTimerWithInterval(float seconds, unsigned int repeat, float delay)
  65. {
  66. _elapsed = -1;
  67. _interval = seconds;
  68. _delay = delay;
  69. _useDelay = (_delay > 0.0f) ? true : false;
  70. _repeat = repeat;
  71. _runForever = (_repeat == CC_REPEAT_FOREVER) ? true : false;
  72. }
  73. void Timer::update(float dt)
  74. {
  75. if (_elapsed == -1)
  76. {
  77. _elapsed = 0;
  78. _timesExecuted = 0;
  79. return;
  80. }
  81. // accumulate elapsed time
  82. _elapsed += dt;
  83. // deal with delay
  84. if (_useDelay)
  85. {
  86. if (_elapsed < _delay)
  87. {
  88. return;
  89. }
  90. trigger(_delay);
  91. _elapsed = _elapsed - _delay;
  92. _timesExecuted += 1;
  93. _useDelay = false;
  94. // after delay, the rest time should compare with interval
  95. if (!_runForever && _timesExecuted > _repeat)
  96. { //unschedule timer
  97. cancel();
  98. return;
  99. }
  100. }
  101. // if _interval == 0, should trigger once every frame
  102. float interval = (_interval > 0) ? _interval : _elapsed;
  103. while (_elapsed >= interval)
  104. {
  105. trigger(interval);
  106. _elapsed -= interval;
  107. _timesExecuted += 1;
  108. if (!_runForever && _timesExecuted > _repeat)
  109. {
  110. cancel();
  111. break;
  112. }
  113. if (_elapsed <= 0.f)
  114. {
  115. break;
  116. }
  117. if (_scheduler->isCurrentTargetSalvaged())
  118. {
  119. break;
  120. }
  121. }
  122. }
  123. // TimerTargetCallback
  124. TimerTargetCallback::TimerTargetCallback()
  125. {
  126. }
  127. bool TimerTargetCallback::initWithCallback(Scheduler* scheduler, const ccSchedulerFunc& callback, void *target, const std::string& key, float seconds, unsigned int repeat, float delay)
  128. {
  129. _scheduler = scheduler;
  130. _target = target;
  131. _callback = callback;
  132. _key = key;
  133. setupTimerWithInterval(seconds, repeat, delay);
  134. return true;
  135. }
  136. void TimerTargetCallback::trigger(float dt)
  137. {
  138. if (_callback)
  139. {
  140. _callback(dt);
  141. }
  142. }
  143. void TimerTargetCallback::cancel()
  144. {
  145. _scheduler->unschedule(_key, _target);
  146. }
  147. // implementation of Scheduler
  148. Scheduler::Scheduler()
  149. {
  150. // I don't expect to have more than 30 functions to all per frame
  151. _functionsToPerform.reserve(30);
  152. }
  153. Scheduler::~Scheduler(void)
  154. {
  155. unscheduleAll();
  156. }
  157. void Scheduler::removeHashElement(_hashSelectorEntry *element)
  158. {
  159. ccArrayFree(element->timers);
  160. HASH_DEL(_hashForTimers, element);
  161. free(element);
  162. }
  163. void Scheduler::schedule(const ccSchedulerFunc& callback, void *target, float interval, bool paused, const std::string& key)
  164. {
  165. this->schedule(callback, target, interval, CC_REPEAT_FOREVER, 0.0f, paused, key);
  166. }
  167. void Scheduler::schedule(const ccSchedulerFunc& callback, void *target, float interval, unsigned int repeat, float delay, bool paused, const std::string& key)
  168. {
  169. CCASSERT(target, "Argument target must be non-nullptr");
  170. CCASSERT(!key.empty(), "key should not be empty!");
  171. tHashTimerEntry *element = nullptr;
  172. HASH_FIND_PTR(_hashForTimers, &target, element);
  173. if (! element)
  174. {
  175. element = (tHashTimerEntry *)calloc(sizeof(*element), 1);
  176. element->target = target;
  177. HASH_ADD_PTR(_hashForTimers, target, element);
  178. // Is this the 1st element ? Then set the pause level to all the selectors of this target
  179. element->paused = paused;
  180. }
  181. else
  182. {
  183. CCASSERT(element->paused == paused, "element's paused should be paused!");
  184. }
  185. if (element->timers == nullptr)
  186. {
  187. element->timers = ccArrayNew(10);
  188. }
  189. else
  190. {
  191. for (int i = 0; i < element->timers->num; ++i)
  192. {
  193. TimerTargetCallback *timer = dynamic_cast<TimerTargetCallback*>(element->timers->arr[i]);
  194. if (timer && key == timer->getKey())
  195. {
  196. CCLOG("CCScheduler#scheduleSelector. Selector already scheduled. Updating interval from: %.4f to %.4f", timer->getInterval(), interval);
  197. timer->setInterval(interval);
  198. return;
  199. }
  200. }
  201. ccArrayEnsureExtraCapacity(element->timers, 1);
  202. }
  203. TimerTargetCallback *timer = new (std::nothrow) TimerTargetCallback();
  204. timer->initWithCallback(this, callback, target, key, interval, repeat, delay);
  205. ccArrayAppendObject(element->timers, timer);
  206. timer->release();
  207. }
  208. void Scheduler::unschedule(const std::string &key, void *target)
  209. {
  210. // explicit handle nil arguments when removing an object
  211. if (target == nullptr || key.empty())
  212. {
  213. return;
  214. }
  215. //CCASSERT(target);
  216. //CCASSERT(selector);
  217. tHashTimerEntry *element = nullptr;
  218. HASH_FIND_PTR(_hashForTimers, &target, element);
  219. if (element)
  220. {
  221. for (int i = 0; i < element->timers->num; ++i)
  222. {
  223. TimerTargetCallback *timer = dynamic_cast<TimerTargetCallback*>(element->timers->arr[i]);
  224. if (timer && key == timer->getKey())
  225. {
  226. if (timer == element->currentTimer && (! element->currentTimerSalvaged))
  227. {
  228. element->currentTimer->retain();
  229. element->currentTimerSalvaged = true;
  230. }
  231. ccArrayRemoveObjectAtIndex(element->timers, i, true);
  232. // update timerIndex in case we are in tick:, looping over the actions
  233. if (element->timerIndex >= i)
  234. {
  235. element->timerIndex--;
  236. }
  237. if (element->timers->num == 0)
  238. {
  239. if (_currentTarget == element)
  240. {
  241. _currentTargetSalvaged = true;
  242. }
  243. else
  244. {
  245. removeHashElement(element);
  246. }
  247. }
  248. return;
  249. }
  250. }
  251. }
  252. }
  253. bool Scheduler::isScheduled(const std::string& key, void *target)
  254. {
  255. CCASSERT(!key.empty(), "Argument key must not be empty");
  256. CCASSERT(target, "Argument target must be non-nullptr");
  257. tHashTimerEntry *element = nullptr;
  258. HASH_FIND_PTR(_hashForTimers, &target, element);
  259. if (!element)
  260. {
  261. return false;
  262. }
  263. if (element->timers == nullptr)
  264. {
  265. return false;
  266. }
  267. else
  268. {
  269. for (int i = 0; i < element->timers->num; ++i)
  270. {
  271. TimerTargetCallback *timer = dynamic_cast<TimerTargetCallback*>(element->timers->arr[i]);
  272. if (timer && key == timer->getKey())
  273. {
  274. return true;
  275. }
  276. }
  277. return false;
  278. }
  279. return false; // should never get here
  280. }
  281. void Scheduler::unscheduleAll()
  282. {
  283. for (tHashTimerEntry *element = _hashForTimers, *nextElement = nullptr; element != nullptr;)
  284. {
  285. // element may be removed in unscheduleAllSelectorsForTarget
  286. nextElement = (tHashTimerEntry *)element->hh.next;
  287. unscheduleAllForTarget(element->target);
  288. element = nextElement;
  289. }
  290. }
  291. void Scheduler::unscheduleAllForTarget(void *target)
  292. {
  293. // explicit nullptr handling
  294. if (target == nullptr)
  295. {
  296. return;
  297. }
  298. // Custom Selectors
  299. tHashTimerEntry *element = nullptr;
  300. HASH_FIND_PTR(_hashForTimers, &target, element);
  301. if (element)
  302. {
  303. if (ccArrayContainsObject(element->timers, element->currentTimer)
  304. && (! element->currentTimerSalvaged))
  305. {
  306. element->currentTimer->retain();
  307. element->currentTimerSalvaged = true;
  308. }
  309. ccArrayRemoveAllObjects(element->timers);
  310. if (_currentTarget == element)
  311. {
  312. _currentTargetSalvaged = true;
  313. }
  314. else
  315. {
  316. removeHashElement(element);
  317. }
  318. }
  319. }
  320. void Scheduler::resumeTarget(void *target)
  321. {
  322. CCASSERT(target != nullptr, "target can't be nullptr!");
  323. // custom selectors
  324. tHashTimerEntry *element = nullptr;
  325. HASH_FIND_PTR(_hashForTimers, &target, element);
  326. if (element)
  327. {
  328. element->paused = false;
  329. }
  330. }
  331. void Scheduler::pauseTarget(void *target)
  332. {
  333. CCASSERT(target != nullptr, "target can't be nullptr!");
  334. // custom selectors
  335. tHashTimerEntry *element = nullptr;
  336. HASH_FIND_PTR(_hashForTimers, &target, element);
  337. if (element)
  338. {
  339. element->paused = true;
  340. }
  341. }
  342. bool Scheduler::isTargetPaused(void *target)
  343. {
  344. CCASSERT( target != nullptr, "target must be non nil" );
  345. // Custom selectors
  346. tHashTimerEntry *element = nullptr;
  347. HASH_FIND_PTR(_hashForTimers, &target, element);
  348. if( element )
  349. {
  350. return element->paused;
  351. }
  352. return false; // should never get here
  353. }
  354. std::set<void*> Scheduler::pauseAllTargets()
  355. {
  356. std::set<void*> idsWithSelectors;
  357. // Custom Selectors
  358. for(tHashTimerEntry *element = _hashForTimers; element != nullptr;
  359. element = (tHashTimerEntry*)element->hh.next)
  360. {
  361. element->paused = true;
  362. idsWithSelectors.insert(element->target);
  363. }
  364. return idsWithSelectors;
  365. }
  366. void Scheduler::resumeTargets(const std::set<void*>& targetsToResume)
  367. {
  368. for(const auto &obj : targetsToResume) {
  369. this->resumeTarget(obj);
  370. }
  371. }
  372. void Scheduler::performFunctionInCocosThread(const std::function<void ()> &function)
  373. {
  374. _performMutex.lock();
  375. _functionsToPerform.push_back(function);
  376. _performMutex.unlock();
  377. }
  378. void Scheduler::removeAllFunctionsToBePerformedInCocosThread()
  379. {
  380. std::unique_lock<std::mutex> lock(_performMutex);
  381. _functionsToPerform.clear();
  382. }
  383. // main loop
  384. void Scheduler::update(float dt)
  385. {
  386. _updateHashLocked = true;
  387. // Iterate over all the custom selectors
  388. for (tHashTimerEntry *elt = _hashForTimers; elt != nullptr; )
  389. {
  390. _currentTarget = elt;
  391. _currentTargetSalvaged = false;
  392. if (! _currentTarget->paused)
  393. {
  394. // The 'timers' array may change while inside this loop
  395. for (elt->timerIndex = 0; elt->timerIndex < elt->timers->num; ++(elt->timerIndex))
  396. {
  397. elt->currentTimer = (Timer*)(elt->timers->arr[elt->timerIndex]);
  398. elt->currentTimerSalvaged = false;
  399. elt->currentTimer->update(dt);
  400. if (elt->currentTimerSalvaged)
  401. {
  402. // The currentTimer told the remove itself. To prevent the timer from
  403. // accidentally deallocating itself before finishing its step, we retained
  404. // it. Now that step is done, it's safe to release it.
  405. elt->currentTimer->release();
  406. }
  407. elt->currentTimer = nullptr;
  408. }
  409. }
  410. // elt, at this moment, is still valid
  411. // so it is safe to ask this here (issue #490)
  412. elt = (tHashTimerEntry *)elt->hh.next;
  413. // only delete currentTarget if no actions were scheduled during the cycle (issue #481)
  414. if (_currentTargetSalvaged && _currentTarget->timers->num == 0)
  415. {
  416. removeHashElement(_currentTarget);
  417. }
  418. }
  419. _updateHashLocked = false;
  420. _currentTarget = nullptr;
  421. //
  422. // Functions allocated from another thread
  423. //
  424. // Testing size is faster than locking / unlocking.
  425. // And almost never there will be functions scheduled to be called.
  426. if( !_functionsToPerform.empty() ) {
  427. _performMutex.lock();
  428. // fixed #4123: Save the callback functions, they must be invoked after '_performMutex.unlock()', otherwise if new functions are added in callback, it will cause thread deadlock.
  429. auto temp = _functionsToPerform;
  430. _functionsToPerform.clear();
  431. _performMutex.unlock();
  432. for( const auto &function : temp ) {
  433. function();
  434. }
  435. }
  436. }
  437. NS_CC_END