animation.ts 49 KB

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