animation.ts 40 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041
  1. import { IEasingFunction, EasingFunction } from "./easing";
  2. import { Vector3, Quaternion, Vector2, Color3, Size, Matrix } from "../Maths/math";
  3. import { Scalar } from "../Maths/math.scalar";
  4. import { Nullable } from "../types";
  5. import { Scene } from "../scene";
  6. import { IAnimatable } from "../Misc/tools";
  7. import { SerializationHelper } from "../Misc/decorators";
  8. import { _TypeStore } from '../Misc/typeStore';
  9. import { IAnimationKey, AnimationKeyInterpolation } from './animationKey';
  10. import { AnimationRange } from './animationRange';
  11. import { AnimationEvent } from './animationEvent';
  12. import { Node } from "../node";
  13. declare type Animatable = import("./animatable").Animatable;
  14. declare type RuntimeAnimation = import("./runtimeAnimation").RuntimeAnimation;
  15. /**
  16. * Class used to store any kind of animation
  17. */
  18. export class Animation {
  19. /**
  20. * Use matrix interpolation instead of using direct key value when animating matrices
  21. */
  22. public static AllowMatricesInterpolation = false;
  23. /**
  24. * When matrix interpolation is enabled, this boolean forces the system to use Matrix.DecomposeLerp instead of Matrix.Lerp. Interpolation is more precise but slower
  25. */
  26. public static AllowMatrixDecomposeForInterpolation = true;
  27. /**
  28. * Stores the key frames of the animation
  29. */
  30. private _keys: Array<IAnimationKey>;
  31. /**
  32. * Stores the easing function of the animation
  33. */
  34. private _easingFunction: IEasingFunction;
  35. /**
  36. * @hidden Internal use only
  37. */
  38. public _runtimeAnimations = new Array<RuntimeAnimation>();
  39. /**
  40. * The set of event that will be linked to this animation
  41. */
  42. private _events = new Array<AnimationEvent>();
  43. /**
  44. * Stores an array of target property paths
  45. */
  46. public targetPropertyPath: string[];
  47. /**
  48. * Stores the blending speed of the animation
  49. */
  50. public blendingSpeed = 0.01;
  51. /**
  52. * Stores the animation ranges for the animation
  53. */
  54. private _ranges: { [name: string]: Nullable<AnimationRange> } = {};
  55. /**
  56. * @hidden Internal use
  57. */
  58. public static _PrepareAnimation(name: string, targetProperty: string, framePerSecond: number, totalFrame: number,
  59. from: any, to: any, loopMode?: number, easingFunction?: EasingFunction): Nullable<Animation> {
  60. var dataType = undefined;
  61. if (!isNaN(parseFloat(from)) && isFinite(from)) {
  62. dataType = Animation.ANIMATIONTYPE_FLOAT;
  63. } else if (from instanceof Quaternion) {
  64. dataType = Animation.ANIMATIONTYPE_QUATERNION;
  65. } else if (from instanceof Vector3) {
  66. dataType = Animation.ANIMATIONTYPE_VECTOR3;
  67. } else if (from instanceof Vector2) {
  68. dataType = Animation.ANIMATIONTYPE_VECTOR2;
  69. } else if (from instanceof Color3) {
  70. dataType = Animation.ANIMATIONTYPE_COLOR3;
  71. } else if (from instanceof Size) {
  72. dataType = Animation.ANIMATIONTYPE_SIZE;
  73. }
  74. if (dataType == undefined) {
  75. return null;
  76. }
  77. var animation = new Animation(name, targetProperty, framePerSecond, dataType, loopMode);
  78. var keys: Array<IAnimationKey> = [{ frame: 0, value: from }, { frame: totalFrame, value: to }];
  79. animation.setKeys(keys);
  80. if (easingFunction !== undefined) {
  81. animation.setEasingFunction(easingFunction);
  82. }
  83. return animation;
  84. }
  85. /**
  86. * Sets up an animation
  87. * @param property The property to animate
  88. * @param animationType The animation type to apply
  89. * @param framePerSecond The frames per second of the animation
  90. * @param easingFunction The easing function used in the animation
  91. * @returns The created animation
  92. */
  93. public static CreateAnimation(property: string, animationType: number, framePerSecond: number, easingFunction: EasingFunction): Animation {
  94. var animation: Animation = new Animation(property + "Animation",
  95. property,
  96. framePerSecond,
  97. animationType,
  98. Animation.ANIMATIONLOOPMODE_CONSTANT);
  99. animation.setEasingFunction(easingFunction);
  100. return animation;
  101. }
  102. /**
  103. * Create and start an animation on a node
  104. * @param name defines the name of the global animation that will be run on all nodes
  105. * @param node defines the root node where the animation will take place
  106. * @param targetProperty defines property to animate
  107. * @param framePerSecond defines the number of frame per second yo use
  108. * @param totalFrame defines the number of frames in total
  109. * @param from defines the initial value
  110. * @param to defines the final value
  111. * @param loopMode defines which loop mode you want to use (off by default)
  112. * @param easingFunction defines the easing function to use (linear by default)
  113. * @param onAnimationEnd defines the callback to call when animation end
  114. * @returns the animatable created for this animation
  115. */
  116. public static CreateAndStartAnimation(name: string, node: Node, targetProperty: string,
  117. framePerSecond: number, totalFrame: number,
  118. from: any, to: any, loopMode?: number, easingFunction?: EasingFunction, onAnimationEnd?: () => void): Nullable<Animatable> {
  119. var animation = Animation._PrepareAnimation(name, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction);
  120. if (!animation) {
  121. return null;
  122. }
  123. return node.getScene().beginDirectAnimation(node, [animation], 0, totalFrame, (animation.loopMode === 1), 1.0, onAnimationEnd);
  124. }
  125. /**
  126. * Create and start an animation on a node and its descendants
  127. * @param name defines the name of the global animation that will be run on all nodes
  128. * @param node defines the root node where the animation will take place
  129. * @param directDescendantsOnly if true only direct descendants will be used, if false direct and also indirect (children of children, an so on in a recursive manner) descendants will be used
  130. * @param targetProperty defines property to animate
  131. * @param framePerSecond defines the number of frame per second to use
  132. * @param totalFrame defines the number of frames in total
  133. * @param from defines the initial value
  134. * @param to defines the final value
  135. * @param loopMode defines which loop mode you want to use (off by default)
  136. * @param easingFunction defines the easing function to use (linear by default)
  137. * @param onAnimationEnd defines the callback to call when an animation ends (will be called once per node)
  138. * @returns the list of animatables created for all nodes
  139. * @example https://www.babylonjs-playground.com/#MH0VLI
  140. */
  141. public static CreateAndStartHierarchyAnimation(name: string, node: Node, directDescendantsOnly: boolean, targetProperty: string,
  142. framePerSecond: number, totalFrame: number,
  143. from: any, to: any, loopMode?: number, easingFunction?: EasingFunction, onAnimationEnd?: () => void): Nullable<Animatable[]> {
  144. var animation = Animation._PrepareAnimation(name, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction);
  145. if (!animation) {
  146. return null;
  147. }
  148. let scene = node.getScene();
  149. return scene.beginDirectHierarchyAnimation(node, directDescendantsOnly, [animation], 0, totalFrame, (animation.loopMode === 1), 1.0, onAnimationEnd);
  150. }
  151. /**
  152. * Creates a new animation, merges it with the existing animations and starts it
  153. * @param name Name of the animation
  154. * @param node Node which contains the scene that begins the animations
  155. * @param targetProperty Specifies which property to animate
  156. * @param framePerSecond The frames per second of the animation
  157. * @param totalFrame The total number of frames
  158. * @param from The frame at the beginning of the animation
  159. * @param to The frame at the end of the animation
  160. * @param loopMode Specifies the loop mode of the animation
  161. * @param easingFunction (Optional) The easing function of the animation, which allow custom mathematical formulas for animations
  162. * @param onAnimationEnd Callback to run once the animation is complete
  163. * @returns Nullable animation
  164. */
  165. public static CreateMergeAndStartAnimation(name: string, node: Node, targetProperty: string,
  166. framePerSecond: number, totalFrame: number,
  167. from: any, to: any, loopMode?: number, easingFunction?: EasingFunction, onAnimationEnd?: () => void): Nullable<Animatable> {
  168. var animation = Animation._PrepareAnimation(name, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction);
  169. if (!animation) {
  170. return null;
  171. }
  172. node.animations.push(animation);
  173. return node.getScene().beginAnimation(node, 0, totalFrame, (animation.loopMode === 1), 1.0, onAnimationEnd);
  174. }
  175. /**
  176. * Transition property of an host to the target Value
  177. * @param property The property to transition
  178. * @param targetValue The target Value of the property
  179. * @param host The object where the property to animate belongs
  180. * @param scene Scene used to run the animation
  181. * @param frameRate Framerate (in frame/s) to use
  182. * @param transition The transition type we want to use
  183. * @param duration The duration of the animation, in milliseconds
  184. * @param onAnimationEnd Callback trigger at the end of the animation
  185. * @returns Nullable animation
  186. */
  187. public static TransitionTo(property: string, targetValue: any, host: any, scene: Scene, frameRate: number, transition: Animation, duration: number, onAnimationEnd: Nullable<() => void> = null): Nullable<Animatable> {
  188. if (duration <= 0) {
  189. host[property] = targetValue;
  190. if (onAnimationEnd) {
  191. onAnimationEnd();
  192. }
  193. return null;
  194. }
  195. var endFrame: number = frameRate * (duration / 1000);
  196. transition.setKeys([{
  197. frame: 0,
  198. value: host[property].clone ? host[property].clone() : host[property]
  199. },
  200. {
  201. frame: endFrame,
  202. value: targetValue
  203. }]);
  204. if (!host.animations) {
  205. host.animations = [];
  206. }
  207. host.animations.push(transition);
  208. var animation: Animatable = scene.beginAnimation(host, 0, endFrame, false);
  209. animation.onAnimationEnd = onAnimationEnd;
  210. return animation;
  211. }
  212. /**
  213. * Return the array of runtime animations currently using this animation
  214. */
  215. public get runtimeAnimations(): RuntimeAnimation[] {
  216. return this._runtimeAnimations;
  217. }
  218. /**
  219. * Specifies if any of the runtime animations are currently running
  220. */
  221. public get hasRunningRuntimeAnimations(): boolean {
  222. for (var runtimeAnimation of this._runtimeAnimations) {
  223. if (!runtimeAnimation.isStopped) {
  224. return true;
  225. }
  226. }
  227. return false;
  228. }
  229. /**
  230. * Initializes the animation
  231. * @param name Name of the animation
  232. * @param targetProperty Property to animate
  233. * @param framePerSecond The frames per second of the animation
  234. * @param dataType The data type of the animation
  235. * @param loopMode The loop mode of the animation
  236. * @param enableBlending Specifies if blending should be enabled
  237. */
  238. constructor(
  239. /**Name of the animation */
  240. public name: string,
  241. /**Property to animate */
  242. public targetProperty: string,
  243. /**The frames per second of the animation */
  244. public framePerSecond: number,
  245. /**The data type of the animation */
  246. public dataType: number,
  247. /**The loop mode of the animation */
  248. public loopMode?: number,
  249. /**Specifies if blending should be enabled */
  250. public enableBlending?: boolean) {
  251. this.targetPropertyPath = targetProperty.split(".");
  252. this.dataType = dataType;
  253. this.loopMode = loopMode === undefined ? Animation.ANIMATIONLOOPMODE_CYCLE : loopMode;
  254. }
  255. // Methods
  256. /**
  257. * Converts the animation to a string
  258. * @param fullDetails support for multiple levels of logging within scene loading
  259. * @returns String form of the animation
  260. */
  261. public toString(fullDetails?: boolean): string {
  262. var ret = "Name: " + this.name + ", property: " + this.targetProperty;
  263. ret += ", datatype: " + (["Float", "Vector3", "Quaternion", "Matrix", "Color3", "Vector2"])[this.dataType];
  264. ret += ", nKeys: " + (this._keys ? this._keys.length : "none");
  265. ret += ", nRanges: " + (this._ranges ? Object.keys(this._ranges).length : "none");
  266. if (fullDetails) {
  267. ret += ", Ranges: {";
  268. var first = true;
  269. for (var name in this._ranges) {
  270. if (first) {
  271. ret += ", ";
  272. first = false;
  273. }
  274. ret += name;
  275. }
  276. ret += "}";
  277. }
  278. return ret;
  279. }
  280. /**
  281. * Add an event to this animation
  282. * @param event Event to add
  283. */
  284. public addEvent(event: AnimationEvent): void {
  285. this._events.push(event);
  286. }
  287. /**
  288. * Remove all events found at the given frame
  289. * @param frame The frame to remove events from
  290. */
  291. public removeEvents(frame: number): void {
  292. for (var index = 0; index < this._events.length; index++) {
  293. if (this._events[index].frame === frame) {
  294. this._events.splice(index, 1);
  295. index--;
  296. }
  297. }
  298. }
  299. /**
  300. * Retrieves all the events from the animation
  301. * @returns Events from the animation
  302. */
  303. public getEvents(): AnimationEvent[] {
  304. return this._events;
  305. }
  306. /**
  307. * Creates an animation range
  308. * @param name Name of the animation range
  309. * @param from Starting frame of the animation range
  310. * @param to Ending frame of the animation
  311. */
  312. public createRange(name: string, from: number, to: number): void {
  313. // check name not already in use; could happen for bones after serialized
  314. if (!this._ranges[name]) {
  315. this._ranges[name] = new AnimationRange(name, from, to);
  316. }
  317. }
  318. /**
  319. * Deletes an animation range by name
  320. * @param name Name of the animation range to delete
  321. * @param deleteFrames Specifies if the key frames for the range should also be deleted (true) or not (false)
  322. */
  323. public deleteRange(name: string, deleteFrames = true): void {
  324. let range = this._ranges[name];
  325. if (!range) {
  326. return;
  327. }
  328. if (deleteFrames) {
  329. var from = range.from;
  330. var to = range.to;
  331. // this loop MUST go high to low for multiple splices to work
  332. for (var key = this._keys.length - 1; key >= 0; key--) {
  333. if (this._keys[key].frame >= from && this._keys[key].frame <= to) {
  334. this._keys.splice(key, 1);
  335. }
  336. }
  337. }
  338. this._ranges[name] = null; // said much faster than 'delete this._range[name]'
  339. }
  340. /**
  341. * Gets the animation range by name, or null if not defined
  342. * @param name Name of the animation range
  343. * @returns Nullable animation range
  344. */
  345. public getRange(name: string): Nullable<AnimationRange> {
  346. return this._ranges[name];
  347. }
  348. /**
  349. * Gets the key frames from the animation
  350. * @returns The key frames of the animation
  351. */
  352. public getKeys(): Array<IAnimationKey> {
  353. return this._keys;
  354. }
  355. /**
  356. * Gets the highest frame rate of the animation
  357. * @returns Highest frame rate of the animation
  358. */
  359. public getHighestFrame(): number {
  360. var ret = 0;
  361. for (var key = 0, nKeys = this._keys.length; key < nKeys; key++) {
  362. if (ret < this._keys[key].frame) {
  363. ret = this._keys[key].frame;
  364. }
  365. }
  366. return ret;
  367. }
  368. /**
  369. * Gets the easing function of the animation
  370. * @returns Easing function of the animation
  371. */
  372. public getEasingFunction(): IEasingFunction {
  373. return this._easingFunction;
  374. }
  375. /**
  376. * Sets the easing function of the animation
  377. * @param easingFunction A custom mathematical formula for animation
  378. */
  379. public setEasingFunction(easingFunction: EasingFunction): void {
  380. this._easingFunction = easingFunction;
  381. }
  382. /**
  383. * Interpolates a scalar linearly
  384. * @param startValue Start value of the animation curve
  385. * @param endValue End value of the animation curve
  386. * @param gradient Scalar amount to interpolate
  387. * @returns Interpolated scalar value
  388. */
  389. public floatInterpolateFunction(startValue: number, endValue: number, gradient: number): number {
  390. return Scalar.Lerp(startValue, endValue, gradient);
  391. }
  392. /**
  393. * Interpolates a scalar cubically
  394. * @param startValue Start value of the animation curve
  395. * @param outTangent End tangent of the animation
  396. * @param endValue End value of the animation curve
  397. * @param inTangent Start tangent of the animation curve
  398. * @param gradient Scalar amount to interpolate
  399. * @returns Interpolated scalar value
  400. */
  401. public floatInterpolateFunctionWithTangents(startValue: number, outTangent: number, endValue: number, inTangent: number, gradient: number): number {
  402. return Scalar.Hermite(startValue, outTangent, endValue, inTangent, gradient);
  403. }
  404. /**
  405. * Interpolates a quaternion using a spherical linear interpolation
  406. * @param startValue Start value of the animation curve
  407. * @param endValue End value of the animation curve
  408. * @param gradient Scalar amount to interpolate
  409. * @returns Interpolated quaternion value
  410. */
  411. public quaternionInterpolateFunction(startValue: Quaternion, endValue: Quaternion, gradient: number): Quaternion {
  412. return Quaternion.Slerp(startValue, endValue, gradient);
  413. }
  414. /**
  415. * Interpolates a quaternion cubically
  416. * @param startValue Start value of the animation curve
  417. * @param outTangent End tangent of the animation curve
  418. * @param endValue End value of the animation curve
  419. * @param inTangent Start tangent of the animation curve
  420. * @param gradient Scalar amount to interpolate
  421. * @returns Interpolated quaternion value
  422. */
  423. public quaternionInterpolateFunctionWithTangents(startValue: Quaternion, outTangent: Quaternion, endValue: Quaternion, inTangent: Quaternion, gradient: number): Quaternion {
  424. return Quaternion.Hermite(startValue, outTangent, endValue, inTangent, gradient).normalize();
  425. }
  426. /**
  427. * Interpolates a Vector3 linearl
  428. * @param startValue Start value of the animation curve
  429. * @param endValue End value of the animation curve
  430. * @param gradient Scalar amount to interpolate
  431. * @returns Interpolated scalar value
  432. */
  433. public vector3InterpolateFunction(startValue: Vector3, endValue: Vector3, gradient: number): Vector3 {
  434. return Vector3.Lerp(startValue, endValue, gradient);
  435. }
  436. /**
  437. * Interpolates a Vector3 cubically
  438. * @param startValue Start value of the animation curve
  439. * @param outTangent End tangent of the animation
  440. * @param endValue End value of the animation curve
  441. * @param inTangent Start tangent of the animation curve
  442. * @param gradient Scalar amount to interpolate
  443. * @returns InterpolatedVector3 value
  444. */
  445. public vector3InterpolateFunctionWithTangents(startValue: Vector3, outTangent: Vector3, endValue: Vector3, inTangent: Vector3, gradient: number): Vector3 {
  446. return Vector3.Hermite(startValue, outTangent, endValue, inTangent, gradient);
  447. }
  448. /**
  449. * Interpolates a Vector2 linearly
  450. * @param startValue Start value of the animation curve
  451. * @param endValue End value of the animation curve
  452. * @param gradient Scalar amount to interpolate
  453. * @returns Interpolated Vector2 value
  454. */
  455. public vector2InterpolateFunction(startValue: Vector2, endValue: Vector2, gradient: number): Vector2 {
  456. return Vector2.Lerp(startValue, endValue, gradient);
  457. }
  458. /**
  459. * Interpolates a Vector2 cubically
  460. * @param startValue Start value of the animation curve
  461. * @param outTangent End tangent of the animation
  462. * @param endValue End value of the animation curve
  463. * @param inTangent Start tangent of the animation curve
  464. * @param gradient Scalar amount to interpolate
  465. * @returns Interpolated Vector2 value
  466. */
  467. public vector2InterpolateFunctionWithTangents(startValue: Vector2, outTangent: Vector2, endValue: Vector2, inTangent: Vector2, gradient: number): Vector2 {
  468. return Vector2.Hermite(startValue, outTangent, endValue, inTangent, gradient);
  469. }
  470. /**
  471. * Interpolates a size linearly
  472. * @param startValue Start value of the animation curve
  473. * @param endValue End value of the animation curve
  474. * @param gradient Scalar amount to interpolate
  475. * @returns Interpolated Size value
  476. */
  477. public sizeInterpolateFunction(startValue: Size, endValue: Size, gradient: number): Size {
  478. return Size.Lerp(startValue, endValue, gradient);
  479. }
  480. /**
  481. * Interpolates a Color3 linearly
  482. * @param startValue Start value of the animation curve
  483. * @param endValue End value of the animation curve
  484. * @param gradient Scalar amount to interpolate
  485. * @returns Interpolated Color3 value
  486. */
  487. public color3InterpolateFunction(startValue: Color3, endValue: Color3, gradient: number): Color3 {
  488. return Color3.Lerp(startValue, endValue, gradient);
  489. }
  490. /**
  491. * @hidden Internal use only
  492. */
  493. public _getKeyValue(value: any): any {
  494. if (typeof value === "function") {
  495. return value();
  496. }
  497. return value;
  498. }
  499. /**
  500. * @hidden Internal use only
  501. */
  502. public _interpolate(currentFrame: number, repeatCount: number, workValue?: any, loopMode?: number, offsetValue?: any, highLimitValue?: any): any {
  503. if (loopMode === Animation.ANIMATIONLOOPMODE_CONSTANT && repeatCount > 0) {
  504. return highLimitValue.clone ? highLimitValue.clone() : highLimitValue;
  505. }
  506. const keys = this._keys;
  507. if (keys.length === 1) {
  508. return this._getKeyValue(keys[0].value);
  509. }
  510. // Try to get a hash to find the right key
  511. var startKeyIndex = Math.max(0, Math.min(keys.length - 1, Math.floor(keys.length * (currentFrame - keys[0].frame) / (keys[keys.length - 1].frame - keys[0].frame)) - 1));
  512. if (keys[startKeyIndex].frame >= currentFrame) {
  513. while (startKeyIndex - 1 >= 0 && keys[startKeyIndex].frame >= currentFrame) {
  514. startKeyIndex--;
  515. }
  516. }
  517. for (var key = startKeyIndex; key < keys.length; key++) {
  518. var endKey = keys[key + 1];
  519. if (endKey.frame >= currentFrame) {
  520. var startKey = keys[key];
  521. var startValue = this._getKeyValue(startKey.value);
  522. if (startKey.interpolation === AnimationKeyInterpolation.STEP) {
  523. return startValue;
  524. }
  525. var endValue = this._getKeyValue(endKey.value);
  526. var useTangent = startKey.outTangent !== undefined && endKey.inTangent !== undefined;
  527. var frameDelta = endKey.frame - startKey.frame;
  528. // gradient : percent of currentFrame between the frame inf and the frame sup
  529. var gradient = (currentFrame - startKey.frame) / frameDelta;
  530. // check for easingFunction and correction of gradient
  531. let easingFunction = this.getEasingFunction();
  532. if (easingFunction != null) {
  533. gradient = easingFunction.ease(gradient);
  534. }
  535. switch (this.dataType) {
  536. // Float
  537. case Animation.ANIMATIONTYPE_FLOAT:
  538. var floatValue = useTangent ? this.floatInterpolateFunctionWithTangents(startValue, startKey.outTangent * frameDelta, endValue, endKey.inTangent * frameDelta, gradient) : this.floatInterpolateFunction(startValue, endValue, gradient);
  539. switch (loopMode) {
  540. case Animation.ANIMATIONLOOPMODE_CYCLE:
  541. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  542. return floatValue;
  543. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  544. return offsetValue * repeatCount + floatValue;
  545. }
  546. break;
  547. // Quaternion
  548. case Animation.ANIMATIONTYPE_QUATERNION:
  549. var quatValue = useTangent ? this.quaternionInterpolateFunctionWithTangents(startValue, startKey.outTangent.scale(frameDelta), endValue, endKey.inTangent.scale(frameDelta), gradient) : this.quaternionInterpolateFunction(startValue, endValue, gradient);
  550. switch (loopMode) {
  551. case Animation.ANIMATIONLOOPMODE_CYCLE:
  552. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  553. return quatValue;
  554. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  555. return quatValue.addInPlace(offsetValue.scale(repeatCount));
  556. }
  557. return quatValue;
  558. // Vector3
  559. case Animation.ANIMATIONTYPE_VECTOR3:
  560. var vec3Value = useTangent ? this.vector3InterpolateFunctionWithTangents(startValue, startKey.outTangent.scale(frameDelta), endValue, endKey.inTangent.scale(frameDelta), gradient) : this.vector3InterpolateFunction(startValue, endValue, gradient);
  561. switch (loopMode) {
  562. case Animation.ANIMATIONLOOPMODE_CYCLE:
  563. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  564. return vec3Value;
  565. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  566. return vec3Value.add(offsetValue.scale(repeatCount));
  567. }
  568. // Vector2
  569. case Animation.ANIMATIONTYPE_VECTOR2:
  570. var vec2Value = useTangent ? this.vector2InterpolateFunctionWithTangents(startValue, startKey.outTangent.scale(frameDelta), endValue, endKey.inTangent.scale(frameDelta), gradient) : this.vector2InterpolateFunction(startValue, endValue, gradient);
  571. switch (loopMode) {
  572. case Animation.ANIMATIONLOOPMODE_CYCLE:
  573. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  574. return vec2Value;
  575. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  576. return vec2Value.add(offsetValue.scale(repeatCount));
  577. }
  578. // Size
  579. case Animation.ANIMATIONTYPE_SIZE:
  580. switch (loopMode) {
  581. case Animation.ANIMATIONLOOPMODE_CYCLE:
  582. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  583. return this.sizeInterpolateFunction(startValue, endValue, gradient);
  584. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  585. return this.sizeInterpolateFunction(startValue, endValue, gradient).add(offsetValue.scale(repeatCount));
  586. }
  587. // Color3
  588. case Animation.ANIMATIONTYPE_COLOR3:
  589. switch (loopMode) {
  590. case Animation.ANIMATIONLOOPMODE_CYCLE:
  591. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  592. return this.color3InterpolateFunction(startValue, endValue, gradient);
  593. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  594. return this.color3InterpolateFunction(startValue, endValue, gradient).add(offsetValue.scale(repeatCount));
  595. }
  596. // Matrix
  597. case Animation.ANIMATIONTYPE_MATRIX:
  598. switch (loopMode) {
  599. case Animation.ANIMATIONLOOPMODE_CYCLE:
  600. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  601. if (Animation.AllowMatricesInterpolation) {
  602. return this.matrixInterpolateFunction(startValue, endValue, gradient, workValue);
  603. }
  604. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  605. return startValue;
  606. }
  607. default:
  608. break;
  609. }
  610. break;
  611. }
  612. }
  613. return this._getKeyValue(keys[keys.length - 1].value);
  614. }
  615. /**
  616. * Defines the function to use to interpolate matrices
  617. * @param startValue defines the start matrix
  618. * @param endValue defines the end matrix
  619. * @param gradient defines the gradient between both matrices
  620. * @param result defines an optional target matrix where to store the interpolation
  621. * @returns the interpolated matrix
  622. */
  623. public matrixInterpolateFunction(startValue: Matrix, endValue: Matrix, gradient: number, result?: Matrix): Matrix {
  624. if (Animation.AllowMatrixDecomposeForInterpolation) {
  625. if (result) {
  626. Matrix.DecomposeLerpToRef(startValue, endValue, gradient, result);
  627. return result;
  628. }
  629. return Matrix.DecomposeLerp(startValue, endValue, gradient);
  630. }
  631. if (result) {
  632. Matrix.LerpToRef(startValue, endValue, gradient, result);
  633. return result;
  634. }
  635. return Matrix.Lerp(startValue, endValue, gradient);
  636. }
  637. /**
  638. * Makes a copy of the animation
  639. * @returns Cloned animation
  640. */
  641. public clone(): Animation {
  642. var clone = new Animation(this.name, this.targetPropertyPath.join("."), this.framePerSecond, this.dataType, this.loopMode);
  643. clone.enableBlending = this.enableBlending;
  644. clone.blendingSpeed = this.blendingSpeed;
  645. if (this._keys) {
  646. clone.setKeys(this._keys);
  647. }
  648. if (this._ranges) {
  649. clone._ranges = {};
  650. for (var name in this._ranges) {
  651. let range = this._ranges[name];
  652. if (!range) {
  653. continue;
  654. }
  655. clone._ranges[name] = range.clone();
  656. }
  657. }
  658. return clone;
  659. }
  660. /**
  661. * Sets the key frames of the animation
  662. * @param values The animation key frames to set
  663. */
  664. public setKeys(values: Array<IAnimationKey>): void {
  665. this._keys = values.slice(0);
  666. }
  667. /**
  668. * Serializes the animation to an object
  669. * @returns Serialized object
  670. */
  671. public serialize(): any {
  672. var serializationObject: any = {};
  673. serializationObject.name = this.name;
  674. serializationObject.property = this.targetProperty;
  675. serializationObject.framePerSecond = this.framePerSecond;
  676. serializationObject.dataType = this.dataType;
  677. serializationObject.loopBehavior = this.loopMode;
  678. serializationObject.enableBlending = this.enableBlending;
  679. serializationObject.blendingSpeed = this.blendingSpeed;
  680. var dataType = this.dataType;
  681. serializationObject.keys = [];
  682. var keys = this.getKeys();
  683. for (var index = 0; index < keys.length; index++) {
  684. var animationKey = keys[index];
  685. var key: any = {};
  686. key.frame = animationKey.frame;
  687. switch (dataType) {
  688. case Animation.ANIMATIONTYPE_FLOAT:
  689. key.values = [animationKey.value];
  690. break;
  691. case Animation.ANIMATIONTYPE_QUATERNION:
  692. case Animation.ANIMATIONTYPE_MATRIX:
  693. case Animation.ANIMATIONTYPE_VECTOR3:
  694. case Animation.ANIMATIONTYPE_COLOR3:
  695. key.values = animationKey.value.asArray();
  696. break;
  697. }
  698. serializationObject.keys.push(key);
  699. }
  700. serializationObject.ranges = [];
  701. for (var name in this._ranges) {
  702. let source = this._ranges[name];
  703. if (!source) {
  704. continue;
  705. }
  706. var range: any = {};
  707. range.name = name;
  708. range.from = source.from;
  709. range.to = source.to;
  710. serializationObject.ranges.push(range);
  711. }
  712. return serializationObject;
  713. }
  714. // Statics
  715. /**
  716. * Float animation type
  717. */
  718. private static _ANIMATIONTYPE_FLOAT = 0;
  719. /**
  720. * Vector3 animation type
  721. */
  722. private static _ANIMATIONTYPE_VECTOR3 = 1;
  723. /**
  724. * Quaternion animation type
  725. */
  726. private static _ANIMATIONTYPE_QUATERNION = 2;
  727. /**
  728. * Matrix animation type
  729. */
  730. private static _ANIMATIONTYPE_MATRIX = 3;
  731. /**
  732. * Color3 animation type
  733. */
  734. private static _ANIMATIONTYPE_COLOR3 = 4;
  735. /**
  736. * Vector2 animation type
  737. */
  738. private static _ANIMATIONTYPE_VECTOR2 = 5;
  739. /**
  740. * Size animation type
  741. */
  742. private static _ANIMATIONTYPE_SIZE = 6;
  743. /**
  744. * Relative Loop Mode
  745. */
  746. private static _ANIMATIONLOOPMODE_RELATIVE = 0;
  747. /**
  748. * Cycle Loop Mode
  749. */
  750. private static _ANIMATIONLOOPMODE_CYCLE = 1;
  751. /**
  752. * Constant Loop Mode
  753. */
  754. private static _ANIMATIONLOOPMODE_CONSTANT = 2;
  755. /**
  756. * Get the float animation type
  757. */
  758. public static get ANIMATIONTYPE_FLOAT(): number {
  759. return Animation._ANIMATIONTYPE_FLOAT;
  760. }
  761. /**
  762. * Get the Vector3 animation type
  763. */
  764. public static get ANIMATIONTYPE_VECTOR3(): number {
  765. return Animation._ANIMATIONTYPE_VECTOR3;
  766. }
  767. /**
  768. * Get the Vector2 animation type
  769. */
  770. public static get ANIMATIONTYPE_VECTOR2(): number {
  771. return Animation._ANIMATIONTYPE_VECTOR2;
  772. }
  773. /**
  774. * Get the Size animation type
  775. */
  776. public static get ANIMATIONTYPE_SIZE(): number {
  777. return Animation._ANIMATIONTYPE_SIZE;
  778. }
  779. /**
  780. * Get the Quaternion animation type
  781. */
  782. public static get ANIMATIONTYPE_QUATERNION(): number {
  783. return Animation._ANIMATIONTYPE_QUATERNION;
  784. }
  785. /**
  786. * Get the Matrix animation type
  787. */
  788. public static get ANIMATIONTYPE_MATRIX(): number {
  789. return Animation._ANIMATIONTYPE_MATRIX;
  790. }
  791. /**
  792. * Get the Color3 animation type
  793. */
  794. public static get ANIMATIONTYPE_COLOR3(): number {
  795. return Animation._ANIMATIONTYPE_COLOR3;
  796. }
  797. /**
  798. * Get the Relative Loop Mode
  799. */
  800. public static get ANIMATIONLOOPMODE_RELATIVE(): number {
  801. return Animation._ANIMATIONLOOPMODE_RELATIVE;
  802. }
  803. /**
  804. * Get the Cycle Loop Mode
  805. */
  806. public static get ANIMATIONLOOPMODE_CYCLE(): number {
  807. return Animation._ANIMATIONLOOPMODE_CYCLE;
  808. }
  809. /**
  810. * Get the Constant Loop Mode
  811. */
  812. public static get ANIMATIONLOOPMODE_CONSTANT(): number {
  813. return Animation._ANIMATIONLOOPMODE_CONSTANT;
  814. }
  815. /** @hidden */
  816. public static _UniversalLerp(left: any, right: any, amount: number): any {
  817. let constructor = left.constructor;
  818. if (constructor.Lerp) { // Lerp supported
  819. return constructor.Lerp(left, right, amount);
  820. } else if (constructor.Slerp) { // Slerp supported
  821. return constructor.Slerp(left, right, amount);
  822. } else if (left.toFixed) { // Number
  823. return left * (1.0 - amount) + amount * right;
  824. } else { // Blending not supported
  825. return right;
  826. }
  827. }
  828. /**
  829. * Parses an animation object and creates an animation
  830. * @param parsedAnimation Parsed animation object
  831. * @returns Animation object
  832. */
  833. public static Parse(parsedAnimation: any): Animation {
  834. var animation = new Animation(parsedAnimation.name, parsedAnimation.property, parsedAnimation.framePerSecond, parsedAnimation.dataType, parsedAnimation.loopBehavior);
  835. var dataType = parsedAnimation.dataType;
  836. var keys: Array<IAnimationKey> = [];
  837. var data;
  838. var index: number;
  839. if (parsedAnimation.enableBlending) {
  840. animation.enableBlending = parsedAnimation.enableBlending;
  841. }
  842. if (parsedAnimation.blendingSpeed) {
  843. animation.blendingSpeed = parsedAnimation.blendingSpeed;
  844. }
  845. for (index = 0; index < parsedAnimation.keys.length; index++) {
  846. var key = parsedAnimation.keys[index];
  847. var inTangent: any;
  848. var outTangent: any;
  849. switch (dataType) {
  850. case Animation.ANIMATIONTYPE_FLOAT:
  851. data = key.values[0];
  852. if (key.values.length >= 1) {
  853. inTangent = key.values[1];
  854. }
  855. if (key.values.length >= 2) {
  856. outTangent = key.values[2];
  857. }
  858. break;
  859. case Animation.ANIMATIONTYPE_QUATERNION:
  860. data = Quaternion.FromArray(key.values);
  861. if (key.values.length >= 8) {
  862. var _inTangent = Quaternion.FromArray(key.values.slice(4, 8));
  863. if (!_inTangent.equals(Quaternion.Zero())) {
  864. inTangent = _inTangent;
  865. }
  866. }
  867. if (key.values.length >= 12) {
  868. var _outTangent = Quaternion.FromArray(key.values.slice(8, 12));
  869. if (!_outTangent.equals(Quaternion.Zero())) {
  870. outTangent = _outTangent;
  871. }
  872. }
  873. break;
  874. case Animation.ANIMATIONTYPE_MATRIX:
  875. data = Matrix.FromArray(key.values);
  876. break;
  877. case Animation.ANIMATIONTYPE_COLOR3:
  878. data = Color3.FromArray(key.values);
  879. break;
  880. case Animation.ANIMATIONTYPE_VECTOR3:
  881. default:
  882. data = Vector3.FromArray(key.values);
  883. break;
  884. }
  885. var keyData: any = {};
  886. keyData.frame = key.frame;
  887. keyData.value = data;
  888. if (inTangent != undefined) {
  889. keyData.inTangent = inTangent;
  890. }
  891. if (outTangent != undefined) {
  892. keyData.outTangent = outTangent;
  893. }
  894. keys.push(keyData);
  895. }
  896. animation.setKeys(keys);
  897. if (parsedAnimation.ranges) {
  898. for (index = 0; index < parsedAnimation.ranges.length; index++) {
  899. data = parsedAnimation.ranges[index];
  900. animation.createRange(data.name, data.from, data.to);
  901. }
  902. }
  903. return animation;
  904. }
  905. /**
  906. * Appends the serialized animations from the source animations
  907. * @param source Source containing the animations
  908. * @param destination Target to store the animations
  909. */
  910. public static AppendSerializedAnimations(source: IAnimatable, destination: any): void {
  911. SerializationHelper.AppendSerializedAnimations(source, destination);
  912. }
  913. }
  914. _TypeStore.RegisteredTypes["BABYLON.Animation"] = Animation;
  915. Node._AnimationRangeFactory = (name: string, from: number, to: number) => new AnimationRange(name, from, to);