ModelAnimationCollection.js 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438
  1. /*global define*/
  2. define([
  3. '../Core/clone',
  4. '../Core/defaultValue',
  5. '../Core/defined',
  6. '../Core/defineProperties',
  7. '../Core/DeveloperError',
  8. '../Core/Event',
  9. '../Core/JulianDate',
  10. '../Core/Math',
  11. './ModelAnimation',
  12. './ModelAnimationLoop',
  13. './ModelAnimationState'
  14. ], function(
  15. clone,
  16. defaultValue,
  17. defined,
  18. defineProperties,
  19. DeveloperError,
  20. Event,
  21. JulianDate,
  22. CesiumMath,
  23. ModelAnimation,
  24. ModelAnimationLoop,
  25. ModelAnimationState) {
  26. "use strict";
  27. /**
  28. * A collection of active model animations. Access this using {@link Model#activeAnimations}.
  29. *
  30. * @alias ModelAnimationCollection
  31. * @internalConstructor
  32. *
  33. * @see Model#activeAnimations
  34. */
  35. var ModelAnimationCollection = function(model) {
  36. /**
  37. * The event fired when an animation is added to the collection. This can be used, for
  38. * example, to keep a UI in sync.
  39. *
  40. * @type {Event}
  41. * @default new Event()
  42. *
  43. * @example
  44. * model.activeAnimations.animationAdded.addEventListener(function(model, animation) {
  45. * console.log('Animation added: ' + animation.name);
  46. * });
  47. */
  48. this.animationAdded = new Event();
  49. /**
  50. * The event fired when an animation is removed from the collection. This can be used, for
  51. * example, to keep a UI in sync.
  52. *
  53. * @type {Event}
  54. * @default new Event()
  55. *
  56. * @example
  57. * model.activeAnimations.animationRemoved.addEventListener(function(model, animation) {
  58. * console.log('Animation removed: ' + animation.name);
  59. * });
  60. */
  61. this.animationRemoved = new Event();
  62. this._model = model;
  63. this._scheduledAnimations = [];
  64. this._previousTime = undefined;
  65. };
  66. defineProperties(ModelAnimationCollection.prototype, {
  67. /**
  68. * The number of animations in the collection.
  69. *
  70. * @memberof ModelAnimationCollection.prototype
  71. *
  72. * @type {Number}
  73. * @readonly
  74. */
  75. length : {
  76. get : function() {
  77. return this._scheduledAnimations.length;
  78. }
  79. }
  80. });
  81. /**
  82. * Creates and adds an animation with the specified initial properties to the collection.
  83. * <p>
  84. * This raises the {@link ModelAnimationCollection#animationAdded} event so, for example, a UI can stay in sync.
  85. * </p>
  86. *
  87. * @param {Object} options Object with the following properties:
  88. * @param {String} options.name The glTF animation name that identifies the animation.
  89. * @param {JulianDate} [options.startTime] The scene time to start playing the animation. When this is <code>undefined</code>, the animation starts at the next frame.
  90. * @param {Number} [options.delay=0.0] The delay, in seconds, from <code>startTime</code> to start playing.
  91. * @param {JulianDate} [options.stopTime] The scene time to stop playing the animation. When this is <code>undefined</code>, the animation is played for its full duration.
  92. * @param {Boolean} [options.removeOnStop=false] When <code>true</code>, the animation is removed after it stops playing.
  93. * @param {Number} [options.speedup=1.0] Values greater than <code>1.0</code> increase the speed that the animation is played relative to the scene clock speed; values less than <code>1.0</code> decrease the speed.
  94. * @param {Boolean} [options.reverse=false] When <code>true</code>, the animation is played in reverse.
  95. * @param {ModelAnimationLoop} [options.loop=ModelAnimationLoop.NONE] Determines if and how the animation is looped.
  96. * @returns {ModelAnimation} The animation that was added to the collection.
  97. *
  98. * @exception {DeveloperError} Animations are not loaded. Wait for the {@link Model#readyToRender} event.
  99. * @exception {DeveloperError} options.name must be a valid animation name.
  100. * @exception {DeveloperError} options.speedup must be greater than zero.
  101. *
  102. * @example
  103. * // Example 1. Add an animation
  104. * model.activeAnimations.add({
  105. * name : 'animation name'
  106. * });
  107. *
  108. * @example
  109. * // Example 2. Add an animation and provide all properties and events
  110. * var startTime = Cesium.JulianDate.now();
  111. *
  112. * var animation = model.activeAnimations.add({
  113. * name : 'another animation name',
  114. * startTime : startTime,
  115. * delay : 0.0, // Play at startTime (default)
  116. * stopTime : Cesium.JulianDate.addSeconds(startTime, 4.0, new Cesium.JulianDate()),
  117. * removeOnStop : false, // Do not remove when animation stops (default)
  118. * speedup : 2.0, // Play at double speed
  119. * reverse : true, // Play in reverse
  120. * loop : Cesium.ModelAnimationLoop.REPEAT // Loop the animation
  121. * });
  122. *
  123. * animation.start.addEventListener(function(model, animation) {
  124. * console.log('Animation started: ' + animation.name);
  125. * });
  126. * animation.update.addEventListener(function(model, animation, time) {
  127. * console.log('Animation updated: ' + animation.name + '. glTF animation time: ' + time);
  128. * });
  129. * animation.stop.addEventListener(function(model, animation) {
  130. * console.log('Animation stopped: ' + animation.name);
  131. * });
  132. */
  133. ModelAnimationCollection.prototype.add = function(options) {
  134. options = defaultValue(options, defaultValue.EMPTY_OBJECT);
  135. var model = this._model;
  136. var animations = model._runtime.animations;
  137. //>>includeStart('debug', pragmas.debug);
  138. if (!defined(animations)) {
  139. throw new DeveloperError('Animations are not loaded. Wait for the model\'s readyToRender event or ready property.');
  140. }
  141. //>>includeEnd('debug');
  142. var animation = animations[options.name];
  143. //>>includeStart('debug', pragmas.debug);
  144. if (!defined(animation)) {
  145. throw new DeveloperError('options.name must be a valid animation name.');
  146. }
  147. if (defined(options.speedup) && (options.speedup <= 0.0)) {
  148. throw new DeveloperError('options.speedup must be greater than zero.');
  149. }
  150. //>>includeEnd('debug');
  151. var scheduledAnimation = new ModelAnimation(options, model, animation);
  152. this._scheduledAnimations.push(scheduledAnimation);
  153. this.animationAdded.raiseEvent(model, scheduledAnimation);
  154. return scheduledAnimation;
  155. };
  156. /**
  157. * Creates and adds an animation with the specified initial properties to the collection
  158. * for each animation in the model.
  159. * <p>
  160. * This raises the {@link ModelAnimationCollection#animationAdded} event for each model so, for example, a UI can stay in sync.
  161. * </p>
  162. *
  163. * @param {Object} [options] Object with the following properties:
  164. * @param {JulianDate} [options.startTime] The scene time to start playing the animations. When this is <code>undefined</code>, the animations starts at the next frame.
  165. * @param {Number} [options.delay=0.0] The delay, in seconds, from <code>startTime</code> to start playing.
  166. * @param {JulianDate} [options.stopTime] The scene time to stop playing the animations. When this is <code>undefined</code>, the animations are played for its full duration.
  167. * @param {Boolean} [options.removeOnStop=false] When <code>true</code>, the animations are removed after they stop playing.
  168. * @param {Number} [options.speedup=1.0] Values greater than <code>1.0</code> increase the speed that the animations play relative to the scene clock speed; values less than <code>1.0</code> decrease the speed.
  169. * @param {Boolean} [options.reverse=false] When <code>true</code>, the animations are played in reverse.
  170. * @param {ModelAnimationLoop} [options.loop=ModelAnimationLoop.NONE] Determines if and how the animations are looped.
  171. * @returns {ModelAnimation[]} An array of {@link ModelAnimation} objects, one for each animation added to the collection. If there are no glTF animations, the array is empty.
  172. *
  173. * @exception {DeveloperError} Animations are not loaded. Wait for the {@link Model#readyToRender} event.
  174. * @exception {DeveloperError} options.speedup must be greater than zero.
  175. *
  176. * @example
  177. * model.activeAnimations.addAll({
  178. * speedup : 0.5, // Play at half-speed
  179. * loop : Cesium.ModelAnimationLoop.REPEAT // Loop the animations
  180. * });
  181. */
  182. ModelAnimationCollection.prototype.addAll = function(options) {
  183. options = defaultValue(options, defaultValue.EMPTY_OBJECT);
  184. //>>includeStart('debug', pragmas.debug);
  185. if (!defined(this._model._runtime.animations)) {
  186. throw new DeveloperError('Animations are not loaded. Wait for the model\'s readyToRender event or ready property.');
  187. }
  188. if (defined(options.speedup) && (options.speedup <= 0.0)) {
  189. throw new DeveloperError('options.speedup must be greater than zero.');
  190. }
  191. //>>includeEnd('debug');
  192. options = clone(options);
  193. var scheduledAnimations = [];
  194. var animationIds = this._model._animationIds;
  195. var length = animationIds.length;
  196. for (var i = 0; i < length; ++i) {
  197. options.name = animationIds[i];
  198. scheduledAnimations.push(this.add(options));
  199. }
  200. return scheduledAnimations;
  201. };
  202. /**
  203. * Removes an animation from the collection.
  204. * <p>
  205. * This raises the {@link ModelAnimationCollection#animationRemoved} event so, for example, a UI can stay in sync.
  206. * </p>
  207. * <p>
  208. * An animation can also be implicitly removed from the collection by setting {@link ModelAnimation#removeOnStop} to
  209. * <code>true</code>. The {@link ModelAnimationCollection#animationRemoved} event is still fired when the animation is removed.
  210. * </p>
  211. *
  212. * @param {ModelAnimation} animation The animation to remove.
  213. * @returns {Boolean} <code>true</code> if the animation was removed; <code>false</code> if the animation was not found in the collection.
  214. *
  215. * @example
  216. * var a = model.activeAnimations.add({
  217. * name : 'animation name'
  218. * });
  219. * model.activeAnimations.remove(a); // Returns true
  220. */
  221. ModelAnimationCollection.prototype.remove = function(animation) {
  222. if (defined(animation)) {
  223. var animations = this._scheduledAnimations;
  224. var i = animations.indexOf(animation);
  225. if (i !== -1) {
  226. animations.splice(i, 1);
  227. this.animationRemoved.raiseEvent(this._model, animation);
  228. return true;
  229. }
  230. }
  231. return false;
  232. };
  233. /**
  234. * Removes all animations from the collection.
  235. * <p>
  236. * This raises the {@link ModelAnimationCollection#animationRemoved} event for each
  237. * animation so, for example, a UI can stay in sync.
  238. * </p>
  239. */
  240. ModelAnimationCollection.prototype.removeAll = function() {
  241. var model = this._model;
  242. var animations = this._scheduledAnimations;
  243. var length = animations.length;
  244. this._scheduledAnimations = [];
  245. for (var i = 0; i < length; ++i) {
  246. this.animationRemoved.raiseEvent(model, animations[i]);
  247. }
  248. };
  249. /**
  250. * Determines whether this collection contains a given animation.
  251. *
  252. * @param {ModelAnimation} animation The animation to check for.
  253. * @returns {Boolean} <code>true</code> if this collection contains the animation, <code>false</code> otherwise.
  254. */
  255. ModelAnimationCollection.prototype.contains = function(animation) {
  256. if (defined(animation)) {
  257. return (this._scheduledAnimations.indexOf(animation) !== -1);
  258. }
  259. return false;
  260. };
  261. /**
  262. * Returns the animation in the collection at the specified index. Indices are zero-based
  263. * and increase as animations are added. Removing an animation shifts all animations after
  264. * it to the left, changing their indices. This function is commonly used to iterate over
  265. * all the animations in the collection.
  266. *
  267. * @param {Number} index The zero-based index of the animation.
  268. * @returns {ModelAnimation} The animation at the specified index.
  269. *
  270. * @example
  271. * // Output the names of all the animations in the collection.
  272. * var animations = model.activeAnimations;
  273. * var length = animations.length;
  274. * for (var i = 0; i < length; ++i) {
  275. * console.log(animations.get(i).name);
  276. * }
  277. */
  278. ModelAnimationCollection.prototype.get = function(index) {
  279. //>>includeStart('debug', pragmas.debug);
  280. if (!defined(index)) {
  281. throw new DeveloperError('index is required.');
  282. }
  283. //>>includeEnd('debug');
  284. return this._scheduledAnimations[index];
  285. };
  286. function animateChannels(runtimeAnimation, localAnimationTime) {
  287. var channelEvaluators = runtimeAnimation.channelEvaluators;
  288. var length = channelEvaluators.length;
  289. for (var i = 0; i < length; ++i) {
  290. channelEvaluators[i](localAnimationTime);
  291. }
  292. }
  293. var animationsToRemove = [];
  294. function createAnimationRemovedFunction(modelAnimationCollection, model, animation) {
  295. return function() {
  296. modelAnimationCollection.animationRemoved.raiseEvent(model, animation);
  297. };
  298. }
  299. /**
  300. * @private
  301. */
  302. ModelAnimationCollection.prototype.update = function(frameState) {
  303. if (JulianDate.equals(frameState.time, this._previousTime)) {
  304. // Animations are currently only time-dependent so do not animate when paused or picking
  305. return false;
  306. }
  307. this._previousTime = JulianDate.clone(frameState.time, this._previousTime);
  308. var animationOccured = false;
  309. var sceneTime = frameState.time;
  310. var model = this._model;
  311. var scheduledAnimations = this._scheduledAnimations;
  312. var length = scheduledAnimations.length;
  313. for (var i = 0; i < length; ++i) {
  314. var scheduledAnimation = scheduledAnimations[i];
  315. var runtimeAnimation = scheduledAnimation._runtimeAnimation;
  316. if (!defined(scheduledAnimation._computedStartTime)) {
  317. scheduledAnimation._computedStartTime = JulianDate.addSeconds(defaultValue(scheduledAnimation.startTime, sceneTime), scheduledAnimation.delay, new JulianDate());
  318. }
  319. if (!defined(scheduledAnimation._duration)) {
  320. scheduledAnimation._duration = runtimeAnimation.stopTime * (1.0 / scheduledAnimation.speedup);
  321. }
  322. var startTime = scheduledAnimation._computedStartTime;
  323. var duration = scheduledAnimation._duration;
  324. var stopTime = scheduledAnimation.stopTime;
  325. // [0.0, 1.0] normalized local animation time
  326. var delta = (duration !== 0.0) ? (JulianDate.secondsDifference(sceneTime, startTime) / duration) : 0.0;
  327. var pastStartTime = (delta >= 0.0);
  328. // Play animation if
  329. // * we are after the start time, and
  330. // * before the end of the animation's duration or the animation is being repeated, and
  331. // * we did not reach a user-provided stop time.
  332. var play = pastStartTime &&
  333. ((delta <= 1.0) ||
  334. ((scheduledAnimation.loop === ModelAnimationLoop.REPEAT) ||
  335. (scheduledAnimation.loop === ModelAnimationLoop.MIRRORED_REPEAT))) &&
  336. (!defined(stopTime) || JulianDate.lessThanOrEquals(sceneTime, stopTime));
  337. if (play) {
  338. // STOPPED -> ANIMATING state transition?
  339. if (scheduledAnimation._state === ModelAnimationState.STOPPED) {
  340. scheduledAnimation._state = ModelAnimationState.ANIMATING;
  341. if (scheduledAnimation.start.numberOfListeners > 0) {
  342. frameState.afterRender.push(scheduledAnimation._raiseStartEvent);
  343. }
  344. }
  345. // Truncate to [0.0, 1.0] for repeating animations
  346. if (scheduledAnimation.loop === ModelAnimationLoop.REPEAT) {
  347. delta = delta - Math.floor(delta);
  348. } else if (scheduledAnimation.loop === ModelAnimationLoop.MIRRORED_REPEAT) {
  349. var floor = Math.floor(delta);
  350. var fract = delta - floor;
  351. // When even use (1.0 - fract) to mirror repeat
  352. delta = (floor % 2 === 1.0) ? (1.0 - fract) : fract;
  353. }
  354. if (scheduledAnimation.reverse) {
  355. delta = 1.0 - delta;
  356. }
  357. var localAnimationTime = delta * duration * scheduledAnimation.speedup;
  358. // Clamp in case floating-point roundoff goes outside the animation's first or last keyframe
  359. localAnimationTime = CesiumMath.clamp(localAnimationTime, runtimeAnimation.startTime, runtimeAnimation.stopTime);
  360. animateChannels(runtimeAnimation, localAnimationTime);
  361. if (scheduledAnimation.update.numberOfListeners > 0) {
  362. scheduledAnimation._updateEventTime = localAnimationTime;
  363. frameState.afterRender.push(scheduledAnimation._raiseUpdateEvent);
  364. }
  365. animationOccured = true;
  366. } else {
  367. // ANIMATING -> STOPPED state transition?
  368. if (pastStartTime && (scheduledAnimation._state === ModelAnimationState.ANIMATING)) {
  369. scheduledAnimation._state = ModelAnimationState.STOPPED;
  370. if (scheduledAnimation.stop.numberOfListeners > 0) {
  371. frameState.afterRender.push(scheduledAnimation._raiseStopEvent);
  372. }
  373. if (scheduledAnimation.removeOnStop) {
  374. animationsToRemove.push(scheduledAnimation);
  375. }
  376. }
  377. }
  378. }
  379. // Remove animations that stopped
  380. length = animationsToRemove.length;
  381. for (var j = 0; j < length; ++j) {
  382. var animationToRemove = animationsToRemove[j];
  383. scheduledAnimations.splice(scheduledAnimations.indexOf(animationToRemove), 1);
  384. frameState.afterRender.push(createAnimationRemovedFunction(this, model, animationToRemove));
  385. }
  386. animationsToRemove.length = 0;
  387. return animationOccured;
  388. };
  389. return ModelAnimationCollection;
  390. });