POPAnimationInternal.h 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505
  1. /**
  2. Copyright (c) 2014-present, Facebook, Inc.
  3. All rights reserved.
  4. This source code is licensed under the BSD-style license found in the
  5. LICENSE file in the root directory of this source tree. An additional grant
  6. of patent rights can be found in the PATENTS file in the same directory.
  7. */
  8. #import "POPAnimation.h"
  9. #import <QuartzCore/CAMediaTimingFunction.h>
  10. #import "POPAction.h"
  11. #import "POPAnimationRuntime.h"
  12. #import "POPAnimationTracerInternal.h"
  13. #import "POPSpringSolver.h"
  14. using namespace POP;
  15. /**
  16. Enumeration of supported animation types.
  17. */
  18. enum POPAnimationType
  19. {
  20. kPOPAnimationSpring,
  21. kPOPAnimationDecay,
  22. kPOPAnimationBasic,
  23. kPOPAnimationCustom,
  24. };
  25. typedef struct
  26. {
  27. CGFloat progress;
  28. bool reached;
  29. } POPProgressMarker;
  30. typedef void (^POPAnimationDidStartBlock)(POPAnimation *anim);
  31. typedef void (^POPAnimationDidReachToValueBlock)(POPAnimation *anim);
  32. typedef void (^POPAnimationCompletionBlock)(POPAnimation *anim, BOOL finished);
  33. typedef void (^POPAnimationDidApplyBlock)(POPAnimation *anim);
  34. @interface POPAnimation()
  35. - (instancetype)_init;
  36. @property (assign, nonatomic) SpringSolver4d *solver;
  37. @property (readonly, nonatomic) POPAnimationType type;
  38. /**
  39. The current animation value, updated while animation is progressing.
  40. */
  41. @property (copy, nonatomic, readonly) id currentValue;
  42. /**
  43. An array of optional progress markers. For each marker specified, the animation delegate will be informed when progress meets or exceeds the value specified. Specifying values outside of the [0, 1] range will give undefined results.
  44. */
  45. @property (copy, nonatomic) NSArray *progressMarkers;
  46. /**
  47. Return YES to indicate animation should continue animating.
  48. */
  49. - (BOOL)_advance:(id)object currentTime:(CFTimeInterval)currentTime elapsedTime:(CFTimeInterval)elapsedTime;
  50. /**
  51. Subclass override point to append animation description.
  52. */
  53. - (void)_appendDescription:(NSMutableString *)s debug:(BOOL)debug;
  54. @end
  55. NS_INLINE NSString *describe(VectorConstRef vec)
  56. {
  57. return NULL == vec ? @"null" : vec->toString();
  58. }
  59. NS_INLINE Vector4r vector4(VectorConstRef vec)
  60. {
  61. return NULL == vec ? Vector4r::Zero() : vec->vector4r();
  62. }
  63. NS_INLINE Vector4d vector4d(VectorConstRef vec)
  64. {
  65. if (NULL == vec) {
  66. return Vector4d::Zero();
  67. } else {
  68. return vec->vector4r().cast<double>();
  69. }
  70. }
  71. NS_INLINE bool vec_equal(VectorConstRef v1, VectorConstRef v2)
  72. {
  73. if (v1 == v2) {
  74. return true;
  75. }
  76. if (!v1 || !v2) {
  77. return false;
  78. }
  79. return *v1 == *v2;
  80. }
  81. NS_INLINE CGFloat * vec_data(VectorRef vec)
  82. {
  83. return NULL == vec ? NULL : vec->data();
  84. }
  85. template<class T>
  86. struct ComputeProgressFunctor {
  87. CGFloat operator()(const T &value, const T &start, const T &end) const {
  88. return 0;
  89. }
  90. };
  91. template<>
  92. struct ComputeProgressFunctor<Vector4r> {
  93. CGFloat operator()(const Vector4r &value, const Vector4r &start, const Vector4r &end) const {
  94. CGFloat s = (value - start).squaredNorm(); // distance from start
  95. CGFloat e = (value - end).squaredNorm(); // distance from end
  96. CGFloat d = (end - start).squaredNorm(); // distance from start to end
  97. if (0 == d) {
  98. return 1;
  99. } else if (s > e) {
  100. // s -------- p ---- e OR s ------- e ---- p
  101. return sqrtr(s/d);
  102. } else {
  103. // s --- p --------- e OR p ---- s ------- e
  104. return 1 - sqrtr(e/d);
  105. }
  106. }
  107. };
  108. struct _POPAnimationState;
  109. struct _POPDecayAnimationState;
  110. struct _POPPropertyAnimationState;
  111. extern _POPAnimationState *POPAnimationGetState(POPAnimation *a);
  112. #define FB_FLAG_GET(stype, flag, getter) \
  113. - (BOOL)getter { \
  114. return ((stype *)_state)->flag; \
  115. }
  116. #define FB_FLAG_SET(stype, flag, mutator) \
  117. - (void)mutator (BOOL)value { \
  118. if (value == ((stype *)_state)->flag) \
  119. return; \
  120. ((stype *)_state)->flag = value; \
  121. }
  122. #define DEFINE_RW_FLAG(stype, flag, getter, mutator) \
  123. FB_FLAG_GET (stype, flag, getter) \
  124. FB_FLAG_SET (stype, flag, mutator)
  125. #define FB_PROPERTY_GET(stype, property, ctype) \
  126. - (ctype)property { \
  127. return ((stype *)_state)->property; \
  128. }
  129. #define FB_PROPERTY_SET(stype, property, mutator, ctype, ...) \
  130. - (void)mutator (ctype)value { \
  131. if (value == ((stype *)_state)->property) \
  132. return; \
  133. ((stype *)_state)->property = value; \
  134. __VA_ARGS__ \
  135. }
  136. #define FB_PROPERTY_SET_OBJ_COPY(stype, property, mutator, ctype, ...) \
  137. - (void)mutator (ctype)value { \
  138. if (value == ((stype *)_state)->property) \
  139. return; \
  140. ((stype *)_state)->property = [value copy]; \
  141. __VA_ARGS__ \
  142. }
  143. #define DEFINE_RW_PROPERTY(stype, flag, mutator, ctype, ...) \
  144. FB_PROPERTY_GET (stype, flag, ctype) \
  145. FB_PROPERTY_SET (stype, flag, mutator, ctype, __VA_ARGS__)
  146. #define DEFINE_RW_PROPERTY_OBJ(stype, flag, mutator, ctype, ...) \
  147. FB_PROPERTY_GET (stype, flag, ctype) \
  148. FB_PROPERTY_SET (stype, flag, mutator, ctype, __VA_ARGS__)
  149. #define DEFINE_RW_PROPERTY_OBJ_COPY(stype, flag, mutator, ctype, ...) \
  150. FB_PROPERTY_GET (stype, flag, ctype) \
  151. FB_PROPERTY_SET_OBJ_COPY (stype, flag, mutator, ctype, __VA_ARGS__)
  152. /**
  153. Internal delegate definition.
  154. */
  155. @interface NSObject (POPAnimationDelegateInternal)
  156. - (void)pop_animation:(POPAnimation *)anim didReachProgress:(CGFloat)progress;
  157. @end
  158. struct _POPAnimationState
  159. {
  160. id __unsafe_unretained self;
  161. POPAnimationType type;
  162. NSString *name;
  163. NSUInteger ID;
  164. CFTimeInterval beginTime;
  165. CFTimeInterval startTime;
  166. CFTimeInterval lastTime;
  167. id __weak delegate;
  168. POPAnimationDidStartBlock animationDidStartBlock;
  169. POPAnimationDidReachToValueBlock animationDidReachToValueBlock;
  170. POPAnimationCompletionBlock completionBlock;
  171. POPAnimationDidApplyBlock animationDidApplyBlock;
  172. NSMutableDictionary *dict;
  173. POPAnimationTracer *tracer;
  174. CGFloat progress;
  175. NSInteger repeatCount;
  176. bool active:1;
  177. bool paused:1;
  178. bool removedOnCompletion:1;
  179. bool delegateDidStart:1;
  180. bool delegateDidStop:1;
  181. bool delegateDidProgress:1;
  182. bool delegateDidApply:1;
  183. bool delegateDidReachToValue:1;
  184. bool additive:1;
  185. bool didReachToValue:1;
  186. bool tracing:1; // corresponds to tracer started
  187. bool userSpecifiedDynamics:1;
  188. bool autoreverses:1;
  189. bool repeatForever:1;
  190. bool customFinished:1;
  191. _POPAnimationState(id __unsafe_unretained anim) :
  192. self(anim),
  193. type((POPAnimationType)0),
  194. name(nil),
  195. ID(0),
  196. beginTime(0),
  197. startTime(0),
  198. lastTime(0),
  199. delegate(nil),
  200. animationDidStartBlock(nil),
  201. animationDidReachToValueBlock(nil),
  202. completionBlock(nil),
  203. animationDidApplyBlock(nil),
  204. dict(nil),
  205. tracer(nil),
  206. progress(0),
  207. repeatCount(0),
  208. active(false),
  209. paused(true),
  210. removedOnCompletion(true),
  211. delegateDidStart(false),
  212. delegateDidStop(false),
  213. delegateDidProgress(false),
  214. delegateDidApply(false),
  215. delegateDidReachToValue(false),
  216. additive(false),
  217. didReachToValue(false),
  218. tracing(false),
  219. userSpecifiedDynamics(false),
  220. autoreverses(false),
  221. repeatForever(false),
  222. customFinished(false) {}
  223. virtual ~_POPAnimationState()
  224. {
  225. name = nil;
  226. dict = nil;
  227. tracer = nil;
  228. animationDidStartBlock = NULL;
  229. animationDidReachToValueBlock = NULL;
  230. completionBlock = NULL;
  231. animationDidApplyBlock = NULL;
  232. }
  233. bool isCustom() {
  234. return kPOPAnimationCustom == type;
  235. }
  236. bool isStarted() {
  237. return 0 != startTime;
  238. }
  239. id getDelegate() {
  240. return delegate;
  241. }
  242. void setDelegate(id d) {
  243. if (d != delegate) {
  244. delegate = d;
  245. delegateDidStart = [d respondsToSelector:@selector(pop_animationDidStart:)];
  246. delegateDidStop = [d respondsToSelector:@selector(pop_animationDidStop:finished:)];
  247. delegateDidProgress = [d respondsToSelector:@selector(pop_animation:didReachProgress:)];
  248. delegateDidApply = [d respondsToSelector:@selector(pop_animationDidApply:)];
  249. delegateDidReachToValue = [d respondsToSelector:@selector(pop_animationDidReachToValue:)];
  250. }
  251. }
  252. bool getPaused() {
  253. return paused;
  254. }
  255. void setPaused(bool f) {
  256. if (f != paused) {
  257. paused = f;
  258. if (!paused) {
  259. reset(false);
  260. }
  261. }
  262. }
  263. CGFloat getProgress() {
  264. return progress;
  265. }
  266. /* returns true if started */
  267. bool startIfNeeded(id obj, CFTimeInterval time, CFTimeInterval offset)
  268. {
  269. bool started = false;
  270. // detect start based on time
  271. if (0 == startTime && time >= beginTime + offset) {
  272. // activate & unpause
  273. active = true;
  274. setPaused(false);
  275. // note start time
  276. startTime = lastTime = time;
  277. started = true;
  278. }
  279. // ensure values for running animation
  280. bool running = active && !paused;
  281. if (running) {
  282. willRun(started, obj);
  283. }
  284. // handle start
  285. if (started) {
  286. handleDidStart();
  287. }
  288. return started;
  289. }
  290. void stop(bool removing, bool done) {
  291. if (active)
  292. {
  293. // delegate progress one last time
  294. if (done) {
  295. delegateProgress();
  296. }
  297. if (removing) {
  298. active = false;
  299. }
  300. handleDidStop(done);
  301. } else {
  302. // stopped before even started
  303. // delegate start and stop regardless; matches CA behavior
  304. if (!isStarted()) {
  305. handleDidStart();
  306. handleDidStop(false);
  307. }
  308. }
  309. setPaused(true);
  310. }
  311. virtual void handleDidStart()
  312. {
  313. if (delegateDidStart) {
  314. ActionEnabler enabler;
  315. [delegate pop_animationDidStart:self];
  316. }
  317. POPAnimationDidStartBlock block = animationDidStartBlock;
  318. if (block != NULL) {
  319. ActionEnabler enabler;
  320. block(self);
  321. }
  322. if (tracing) {
  323. [tracer didStart];
  324. }
  325. }
  326. void handleDidStop(BOOL done)
  327. {
  328. if (delegateDidStop) {
  329. ActionEnabler enabler;
  330. [delegate pop_animationDidStop:self finished:done];
  331. }
  332. // add another strong reference to completion block before callout
  333. POPAnimationCompletionBlock block = completionBlock;
  334. if (block != NULL) {
  335. ActionEnabler enabler;
  336. block(self, done);
  337. }
  338. if (tracing) {
  339. [tracer didStop:done];
  340. }
  341. }
  342. /* virtual functions */
  343. virtual bool isDone() {
  344. if (isCustom()) {
  345. return customFinished;
  346. }
  347. return false;
  348. }
  349. bool advanceTime(CFTimeInterval time, id obj) {
  350. bool advanced = false;
  351. bool computedProgress = false;
  352. CFTimeInterval dt = time - lastTime;
  353. switch (type) {
  354. case kPOPAnimationSpring:
  355. advanced = advance(time, dt, obj);
  356. break;
  357. case kPOPAnimationDecay:
  358. advanced = advance(time, dt, obj);
  359. break;
  360. case kPOPAnimationBasic: {
  361. advanced = advance(time, dt, obj);
  362. computedProgress = true;
  363. break;
  364. }
  365. case kPOPAnimationCustom: {
  366. customFinished = [self _advance:obj currentTime:time elapsedTime:dt] ? false : true;
  367. advanced = true;
  368. break;
  369. }
  370. default:
  371. break;
  372. }
  373. if (advanced) {
  374. // estimate progress
  375. if (!computedProgress) {
  376. computeProgress();
  377. }
  378. // delegate progress
  379. delegateProgress();
  380. // update time
  381. lastTime = time;
  382. }
  383. return advanced;
  384. }
  385. virtual void willRun(bool started, id obj) {}
  386. virtual bool advance(CFTimeInterval time, CFTimeInterval dt, id obj) { return false; }
  387. virtual void computeProgress() {}
  388. virtual void delegateProgress() {}
  389. virtual void delegateApply() {
  390. if (delegateDidApply) {
  391. ActionEnabler enabler;
  392. [delegate pop_animationDidApply:self];
  393. }
  394. POPAnimationDidApplyBlock block = animationDidApplyBlock;
  395. if (block != NULL) {
  396. ActionEnabler enabler;
  397. block(self);
  398. }
  399. }
  400. virtual void reset(bool all) {
  401. startTime = 0;
  402. lastTime = 0;
  403. }
  404. };
  405. typedef struct _POPAnimationState POPAnimationState;
  406. @interface POPAnimation ()
  407. {
  408. @protected
  409. struct _POPAnimationState *_state;
  410. }
  411. @end
  412. // NSProxy extensions, for testing pursposes
  413. @interface NSProxy (POP)
  414. - (void)pop_addAnimation:(POPAnimation *)anim forKey:(NSString *)key;
  415. - (void)pop_removeAllAnimations;
  416. - (void)pop_removeAnimationForKey:(NSString *)key;
  417. - (NSArray *)pop_animationKeys;
  418. - (POPAnimation *)pop_animationForKey:(NSString *)key;
  419. @end