ModelAnimationCollection.js 18 KB

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