ModelAnimationCollection.js 20 KB

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