animatable.ts 40 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000
  1. import { Animation } from "./animation";
  2. import { RuntimeAnimation } from "./runtimeAnimation";
  3. import { Nullable } from "../types";
  4. import { Observable } from "../Misc/observable";
  5. import { Scene } from "../scene";
  6. import { Matrix, Quaternion, Vector3, TmpVectors } from '../Maths/math.vector';
  7. import { PrecisionDate } from '../Misc/precisionDate';
  8. import { Bone } from '../Bones/bone';
  9. import { Node } from "../node";
  10. /**
  11. * Class used to store an actual running animation
  12. */
  13. export class Animatable {
  14. private _localDelayOffset: Nullable<number> = null;
  15. private _pausedDelay: Nullable<number> = null;
  16. private _runtimeAnimations = new Array<RuntimeAnimation>();
  17. private _paused = false;
  18. private _scene: Scene;
  19. private _speedRatio = 1;
  20. private _weight = -1.0;
  21. private _syncRoot: Nullable<Animatable> = null;
  22. /**
  23. * Gets or sets a boolean indicating if the animatable must be disposed and removed at the end of the animation.
  24. * This will only apply for non looping animation (default is true)
  25. */
  26. public disposeOnEnd = true;
  27. /**
  28. * Gets a boolean indicating if the animation has started
  29. */
  30. public animationStarted = false;
  31. /**
  32. * Observer raised when the animation ends
  33. */
  34. public onAnimationEndObservable = new Observable<Animatable>();
  35. /**
  36. * Observer raised when the animation loops
  37. */
  38. public onAnimationLoopObservable = new Observable<Animatable>();
  39. /**
  40. * Gets the root Animatable used to synchronize and normalize animations
  41. */
  42. public get syncRoot(): Nullable<Animatable> {
  43. return this._syncRoot;
  44. }
  45. /**
  46. * Gets the current frame of the first RuntimeAnimation
  47. * Used to synchronize Animatables
  48. */
  49. public get masterFrame(): number {
  50. if (this._runtimeAnimations.length === 0) {
  51. return 0;
  52. }
  53. return this._runtimeAnimations[0].currentFrame;
  54. }
  55. /**
  56. * Gets or sets the animatable weight (-1.0 by default meaning not weighted)
  57. */
  58. public get weight(): number {
  59. return this._weight;
  60. }
  61. public set weight(value: number) {
  62. if (value === -1) { // -1 is ok and means no weight
  63. this._weight = -1;
  64. return;
  65. }
  66. // Else weight must be in [0, 1] range
  67. this._weight = Math.min(Math.max(value, 0), 1.0);
  68. }
  69. /**
  70. * Gets or sets the speed ratio to apply to the animatable (1.0 by default)
  71. */
  72. public get speedRatio(): number {
  73. return this._speedRatio;
  74. }
  75. public set speedRatio(value: number) {
  76. for (var index = 0; index < this._runtimeAnimations.length; index++) {
  77. var animation = this._runtimeAnimations[index];
  78. animation._prepareForSpeedRatioChange(value);
  79. }
  80. this._speedRatio = value;
  81. }
  82. /**
  83. * Creates a new Animatable
  84. * @param scene defines the hosting scene
  85. * @param target defines the target object
  86. * @param fromFrame defines the starting frame number (default is 0)
  87. * @param toFrame defines the ending frame number (default is 100)
  88. * @param loopAnimation defines if the animation must loop (default is false)
  89. * @param speedRatio defines the factor to apply to animation speed (default is 1)
  90. * @param onAnimationEnd defines a callback to call when animation ends if it is not looping
  91. * @param animations defines a group of animation to add to the new Animatable
  92. * @param onAnimationLoop defines a callback to call when animation loops
  93. */
  94. constructor(scene: Scene,
  95. /** defines the target object */
  96. public target: any,
  97. /** defines the starting frame number (default is 0) */
  98. public fromFrame: number = 0,
  99. /** defines the ending frame number (default is 100) */
  100. public toFrame: number = 100,
  101. /** defines if the animation must loop (default is false) */
  102. public loopAnimation: boolean = false,
  103. speedRatio: number = 1.0,
  104. /** defines a callback to call when animation ends if it is not looping */
  105. public onAnimationEnd?: Nullable<() => void>,
  106. animations?: Animation[],
  107. /** defines a callback to call when animation loops */
  108. public onAnimationLoop?: Nullable<() => void>) {
  109. this._scene = scene;
  110. if (animations) {
  111. this.appendAnimations(target, animations);
  112. }
  113. this._speedRatio = speedRatio;
  114. scene._activeAnimatables.push(this);
  115. }
  116. // Methods
  117. /**
  118. * Synchronize and normalize current Animatable with a source Animatable
  119. * This is useful when using animation weights and when animations are not of the same length
  120. * @param root defines the root Animatable to synchronize with
  121. * @returns the current Animatable
  122. */
  123. public syncWith(root: Animatable): Animatable {
  124. this._syncRoot = root;
  125. if (root) {
  126. // Make sure this animatable will animate after the root
  127. let index = this._scene._activeAnimatables.indexOf(this);
  128. if (index > -1) {
  129. this._scene._activeAnimatables.splice(index, 1);
  130. this._scene._activeAnimatables.push(this);
  131. }
  132. }
  133. return this;
  134. }
  135. /**
  136. * Gets the list of runtime animations
  137. * @returns an array of RuntimeAnimation
  138. */
  139. public getAnimations(): RuntimeAnimation[] {
  140. return this._runtimeAnimations;
  141. }
  142. /**
  143. * Adds more animations to the current animatable
  144. * @param target defines the target of the animations
  145. * @param animations defines the new animations to add
  146. */
  147. public appendAnimations(target: any, animations: Animation[]): void {
  148. for (var index = 0; index < animations.length; index++) {
  149. var animation = animations[index];
  150. let newRuntimeAnimation = new RuntimeAnimation(target, animation, this._scene, this);
  151. newRuntimeAnimation._onLoop = () => {
  152. this.onAnimationLoopObservable.notifyObservers(this);
  153. if (this.onAnimationLoop) {
  154. this.onAnimationLoop();
  155. }
  156. };
  157. this._runtimeAnimations.push(newRuntimeAnimation);
  158. }
  159. }
  160. /**
  161. * Gets the source animation for a specific property
  162. * @param property defines the propertyu to look for
  163. * @returns null or the source animation for the given property
  164. */
  165. public getAnimationByTargetProperty(property: string): Nullable<Animation> {
  166. var runtimeAnimations = this._runtimeAnimations;
  167. for (var index = 0; index < runtimeAnimations.length; index++) {
  168. if (runtimeAnimations[index].animation.targetProperty === property) {
  169. return runtimeAnimations[index].animation;
  170. }
  171. }
  172. return null;
  173. }
  174. /**
  175. * Gets the runtime animation for a specific property
  176. * @param property defines the propertyu to look for
  177. * @returns null or the runtime animation for the given property
  178. */
  179. public getRuntimeAnimationByTargetProperty(property: string): Nullable<RuntimeAnimation> {
  180. var runtimeAnimations = this._runtimeAnimations;
  181. for (var index = 0; index < runtimeAnimations.length; index++) {
  182. if (runtimeAnimations[index].animation.targetProperty === property) {
  183. return runtimeAnimations[index];
  184. }
  185. }
  186. return null;
  187. }
  188. /**
  189. * Resets the animatable to its original state
  190. */
  191. public reset(): void {
  192. var runtimeAnimations = this._runtimeAnimations;
  193. for (var index = 0; index < runtimeAnimations.length; index++) {
  194. runtimeAnimations[index].reset(true);
  195. }
  196. this._localDelayOffset = null;
  197. this._pausedDelay = null;
  198. }
  199. /**
  200. * Allows the animatable to blend with current running animations
  201. * @see http://doc.babylonjs.com/babylon101/animations#animation-blending
  202. * @param blendingSpeed defines the blending speed to use
  203. */
  204. public enableBlending(blendingSpeed: number): void {
  205. var runtimeAnimations = this._runtimeAnimations;
  206. for (var index = 0; index < runtimeAnimations.length; index++) {
  207. runtimeAnimations[index].animation.enableBlending = true;
  208. runtimeAnimations[index].animation.blendingSpeed = blendingSpeed;
  209. }
  210. }
  211. /**
  212. * Disable animation blending
  213. * @see http://doc.babylonjs.com/babylon101/animations#animation-blending
  214. */
  215. public disableBlending(): void {
  216. var runtimeAnimations = this._runtimeAnimations;
  217. for (var index = 0; index < runtimeAnimations.length; index++) {
  218. runtimeAnimations[index].animation.enableBlending = false;
  219. }
  220. }
  221. /**
  222. * Jump directly to a given frame
  223. * @param frame defines the frame to jump to
  224. */
  225. public goToFrame(frame: number): void {
  226. var runtimeAnimations = this._runtimeAnimations;
  227. if (runtimeAnimations[0]) {
  228. var fps = runtimeAnimations[0].animation.framePerSecond;
  229. var currentFrame = runtimeAnimations[0].currentFrame;
  230. var adjustTime = frame - currentFrame;
  231. var delay = this.speedRatio !== 0 ? adjustTime * 1000 / (fps * this.speedRatio) : 0;
  232. if (this._localDelayOffset === null) {
  233. this._localDelayOffset = 0;
  234. }
  235. this._localDelayOffset -= delay;
  236. }
  237. for (var index = 0; index < runtimeAnimations.length; index++) {
  238. runtimeAnimations[index].goToFrame(frame);
  239. }
  240. }
  241. /**
  242. * Pause the animation
  243. */
  244. public pause(): void {
  245. if (this._paused) {
  246. return;
  247. }
  248. this._paused = true;
  249. }
  250. /**
  251. * Restart the animation
  252. */
  253. public restart(): void {
  254. this._paused = false;
  255. }
  256. private _raiseOnAnimationEnd() {
  257. if (this.onAnimationEnd) {
  258. this.onAnimationEnd();
  259. }
  260. this.onAnimationEndObservable.notifyObservers(this);
  261. }
  262. /**
  263. * Stop and delete the current animation
  264. * @param animationName defines a string used to only stop some of the runtime animations instead of all
  265. * @param targetMask - a function that determines if the animation should be stopped based on its target (all animations will be stopped if both this and animationName are empty)
  266. */
  267. public stop(animationName?: string, targetMask?: (target: any) => boolean): void {
  268. if (animationName || targetMask) {
  269. var idx = this._scene._activeAnimatables.indexOf(this);
  270. if (idx > -1) {
  271. var runtimeAnimations = this._runtimeAnimations;
  272. for (var index = runtimeAnimations.length - 1; index >= 0; index--) {
  273. const runtimeAnimation = runtimeAnimations[index];
  274. if (animationName && runtimeAnimation.animation.name != animationName) {
  275. continue;
  276. }
  277. if (targetMask && !targetMask(runtimeAnimation.target)) {
  278. continue;
  279. }
  280. runtimeAnimation.dispose();
  281. runtimeAnimations.splice(index, 1);
  282. }
  283. if (runtimeAnimations.length == 0) {
  284. this._scene._activeAnimatables.splice(idx, 1);
  285. this._raiseOnAnimationEnd();
  286. }
  287. }
  288. } else {
  289. var index = this._scene._activeAnimatables.indexOf(this);
  290. if (index > -1) {
  291. this._scene._activeAnimatables.splice(index, 1);
  292. var runtimeAnimations = this._runtimeAnimations;
  293. for (var index = 0; index < runtimeAnimations.length; index++) {
  294. runtimeAnimations[index].dispose();
  295. }
  296. this._raiseOnAnimationEnd();
  297. }
  298. }
  299. }
  300. /**
  301. * Wait asynchronously for the animation to end
  302. * @returns a promise which will be fullfilled when the animation ends
  303. */
  304. public waitAsync(): Promise<Animatable> {
  305. return new Promise((resolve, reject) => {
  306. this.onAnimationEndObservable.add(() => {
  307. resolve(this);
  308. }, undefined, undefined, this, true);
  309. });
  310. }
  311. /** @hidden */
  312. public _animate(delay: number): boolean {
  313. if (this._paused) {
  314. this.animationStarted = false;
  315. if (this._pausedDelay === null) {
  316. this._pausedDelay = delay;
  317. }
  318. return true;
  319. }
  320. if (this._localDelayOffset === null) {
  321. this._localDelayOffset = delay;
  322. this._pausedDelay = null;
  323. } else if (this._pausedDelay !== null) {
  324. this._localDelayOffset += delay - this._pausedDelay;
  325. this._pausedDelay = null;
  326. }
  327. if (this._weight === 0) { // We consider that an animation with a weight === 0 is "actively" paused
  328. return true;
  329. }
  330. // Animating
  331. var running = false;
  332. var runtimeAnimations = this._runtimeAnimations;
  333. var index: number;
  334. for (index = 0; index < runtimeAnimations.length; index++) {
  335. var animation = runtimeAnimations[index];
  336. var isRunning = animation.animate(delay - this._localDelayOffset, this.fromFrame,
  337. this.toFrame, this.loopAnimation, this._speedRatio, this._weight
  338. );
  339. running = running || isRunning;
  340. }
  341. this.animationStarted = running;
  342. if (!running) {
  343. if (this.disposeOnEnd) {
  344. // Remove from active animatables
  345. index = this._scene._activeAnimatables.indexOf(this);
  346. this._scene._activeAnimatables.splice(index, 1);
  347. // Dispose all runtime animations
  348. for (index = 0; index < runtimeAnimations.length; index++) {
  349. runtimeAnimations[index].dispose();
  350. }
  351. }
  352. this._raiseOnAnimationEnd();
  353. if (this.disposeOnEnd) {
  354. this.onAnimationEnd = null;
  355. this.onAnimationLoop = null;
  356. this.onAnimationLoopObservable.clear();
  357. this.onAnimationEndObservable.clear();
  358. }
  359. }
  360. return running;
  361. }
  362. }
  363. declare module "../scene" {
  364. export interface Scene {
  365. /** @hidden */
  366. _registerTargetForLateAnimationBinding(runtimeAnimation: RuntimeAnimation, originalValue: any): void;
  367. /** @hidden */
  368. _processLateAnimationBindingsForMatrices(holder: {
  369. totalWeight: number,
  370. animations: RuntimeAnimation[],
  371. originalValue: Matrix
  372. }): any;
  373. /** @hidden */
  374. _processLateAnimationBindingsForQuaternions(holder: {
  375. totalWeight: number,
  376. animations: RuntimeAnimation[],
  377. originalValue: Quaternion
  378. }, refQuaternion: Quaternion): Quaternion;
  379. /** @hidden */
  380. _processLateAnimationBindings(): void;
  381. /**
  382. * Will start the animation sequence of a given target
  383. * @param target defines the target
  384. * @param from defines from which frame should animation start
  385. * @param to defines until which frame should animation run.
  386. * @param weight defines the weight to apply to the animation (1.0 by default)
  387. * @param loop defines if the animation loops
  388. * @param speedRatio defines the speed in which to run the animation (1.0 by default)
  389. * @param onAnimationEnd defines the function to be executed when the animation ends
  390. * @param animatable defines an animatable object. If not provided a new one will be created from the given params
  391. * @param targetMask defines if the target should be animated if animations are present (this is called recursively on descendant animatables regardless of return value)
  392. * @param onAnimationLoop defines the callback to call when an animation loops
  393. * @returns the animatable object created for this animation
  394. */
  395. beginWeightedAnimation(target: any, from: number, to: number, weight: number, loop?: boolean, speedRatio?: number,
  396. onAnimationEnd?: () => void, animatable?: Animatable, targetMask?: (target: any) => boolean, onAnimationLoop?: () => void): Animatable;
  397. /**
  398. * Will start the animation sequence of a given target
  399. * @param target defines the target
  400. * @param from defines from which frame should animation start
  401. * @param to defines until which frame should animation run.
  402. * @param loop defines if the animation loops
  403. * @param speedRatio defines the speed in which to run the animation (1.0 by default)
  404. * @param onAnimationEnd defines the function to be executed when the animation ends
  405. * @param animatable defines an animatable object. If not provided a new one will be created from the given params
  406. * @param stopCurrent defines if the current animations must be stopped first (true by default)
  407. * @param targetMask defines if the target should be animate if animations are present (this is called recursively on descendant animatables regardless of return value)
  408. * @param onAnimationLoop defines the callback to call when an animation loops
  409. * @returns the animatable object created for this animation
  410. */
  411. beginAnimation(target: any, from: number, to: number, loop?: boolean, speedRatio?: number,
  412. onAnimationEnd?: () => void, animatable?: Animatable, stopCurrent?: boolean,
  413. targetMask?: (target: any) => boolean, onAnimationLoop?: () => void): Animatable;
  414. /**
  415. * Will start the animation sequence of a given target and its hierarchy
  416. * @param target defines the target
  417. * @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.
  418. * @param from defines from which frame should animation start
  419. * @param to defines until which frame should animation run.
  420. * @param loop defines if the animation loops
  421. * @param speedRatio defines the speed in which to run the animation (1.0 by default)
  422. * @param onAnimationEnd defines the function to be executed when the animation ends
  423. * @param animatable defines an animatable object. If not provided a new one will be created from the given params
  424. * @param stopCurrent defines if the current animations must be stopped first (true by default)
  425. * @param targetMask defines if the target should be animated if animations are present (this is called recursively on descendant animatables regardless of return value)
  426. * @param onAnimationLoop defines the callback to call when an animation loops
  427. * @returns the list of created animatables
  428. */
  429. beginHierarchyAnimation(target: any, directDescendantsOnly: boolean, from: number, to: number, loop?: boolean, speedRatio?: number,
  430. onAnimationEnd?: () => void, animatable?: Animatable, stopCurrent?: boolean,
  431. targetMask?: (target: any) => boolean, onAnimationLoop?: () => void): Animatable[];
  432. /**
  433. * Begin a new animation on a given node
  434. * @param target defines the target where the animation will take place
  435. * @param animations defines the list of animations to start
  436. * @param from defines the initial value
  437. * @param to defines the final value
  438. * @param loop defines if you want animation to loop (off by default)
  439. * @param speedRatio defines the speed ratio to apply to all animations
  440. * @param onAnimationEnd defines the callback to call when an animation ends (will be called once per node)
  441. * @param onAnimationLoop defines the callback to call when an animation loops
  442. * @returns the list of created animatables
  443. */
  444. beginDirectAnimation(target: any, animations: Animation[], from: number, to: number, loop?: boolean, speedRatio?: number, onAnimationEnd?: () => void, onAnimationLoop?: () => void): Animatable;
  445. /**
  446. * Begin a new animation on a given node and its hierarchy
  447. * @param target defines the root node where the animation will take place
  448. * @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.
  449. * @param animations defines the list of animations to start
  450. * @param from defines the initial value
  451. * @param to defines the final value
  452. * @param loop defines if you want animation to loop (off by default)
  453. * @param speedRatio defines the speed ratio to apply to all animations
  454. * @param onAnimationEnd defines the callback to call when an animation ends (will be called once per node)
  455. * @param onAnimationLoop defines the callback to call when an animation loops
  456. * @returns the list of animatables created for all nodes
  457. */
  458. beginDirectHierarchyAnimation(target: Node, directDescendantsOnly: boolean, animations: Animation[], from: number, to: number, loop?: boolean, speedRatio?: number, onAnimationEnd?: () => void, onAnimationLoop?: () => void): Animatable[];
  459. /**
  460. * Gets the animatable associated with a specific target
  461. * @param target defines the target of the animatable
  462. * @returns the required animatable if found
  463. */
  464. getAnimatableByTarget(target: any): Nullable<Animatable>;
  465. /**
  466. * Gets all animatables associated with a given target
  467. * @param target defines the target to look animatables for
  468. * @returns an array of Animatables
  469. */
  470. getAllAnimatablesByTarget(target: any): Array<Animatable>;
  471. /**
  472. * Stops and removes all animations that have been applied to the scene
  473. */
  474. stopAllAnimations(): void;
  475. }
  476. }
  477. Scene.prototype._animate = function(): void {
  478. if (!this.animationsEnabled) {
  479. return;
  480. }
  481. const animatables = this._activeAnimatables;
  482. if (animatables.length === 0) {
  483. return;
  484. }
  485. // Getting time
  486. var now = PrecisionDate.Now;
  487. if (!this._animationTimeLast) {
  488. if (this._pendingData.length > 0) {
  489. return;
  490. }
  491. this._animationTimeLast = now;
  492. }
  493. var deltaTime = this.useConstantAnimationDeltaTime ? 16.0 : (now - this._animationTimeLast) * this.animationTimeScale;
  494. this._animationTime += deltaTime;
  495. const animationTime = this._animationTime;
  496. this._animationTimeLast = now;
  497. for (let index = 0; index < animatables.length; index++) {
  498. let animatable = animatables[index];
  499. if (!animatable._animate(animationTime) && animatable.disposeOnEnd) {
  500. index--; // Array was updated
  501. }
  502. }
  503. // Late animation bindings
  504. this._processLateAnimationBindings();
  505. };
  506. Scene.prototype.beginWeightedAnimation = function(target: any, from: number, to: number, weight = 1.0, loop?: boolean, speedRatio: number = 1.0,
  507. onAnimationEnd?: () => void, animatable?: Animatable, targetMask?: (target: any) => boolean, onAnimationLoop?: () => void): Animatable {
  508. let returnedAnimatable = this.beginAnimation(target, from, to, loop, speedRatio, onAnimationEnd, animatable, false, targetMask, onAnimationLoop);
  509. returnedAnimatable.weight = weight;
  510. return returnedAnimatable;
  511. };
  512. Scene.prototype.beginAnimation = function(target: any, from: number, to: number, loop?: boolean, speedRatio: number = 1.0,
  513. onAnimationEnd?: () => void, animatable?: Animatable, stopCurrent = true,
  514. targetMask?: (target: any) => boolean, onAnimationLoop?: () => void): Animatable {
  515. if (from > to && speedRatio > 0) {
  516. speedRatio *= -1;
  517. }
  518. if (stopCurrent) {
  519. this.stopAnimation(target, undefined, targetMask);
  520. }
  521. if (!animatable) {
  522. animatable = new Animatable(this, target, from, to, loop, speedRatio, onAnimationEnd, undefined, onAnimationLoop);
  523. }
  524. const shouldRunTargetAnimations = targetMask ? targetMask(target) : true;
  525. // Local animations
  526. if (target.animations && shouldRunTargetAnimations) {
  527. animatable.appendAnimations(target, target.animations);
  528. }
  529. // Children animations
  530. if (target.getAnimatables) {
  531. var animatables = target.getAnimatables();
  532. for (var index = 0; index < animatables.length; index++) {
  533. this.beginAnimation(animatables[index], from, to, loop, speedRatio, onAnimationEnd, animatable, stopCurrent, targetMask, onAnimationLoop);
  534. }
  535. }
  536. animatable.reset();
  537. return animatable;
  538. };
  539. Scene.prototype.beginHierarchyAnimation = function(target: any, directDescendantsOnly: boolean, from: number, to: number, loop?: boolean, speedRatio: number = 1.0,
  540. onAnimationEnd?: () => void, animatable?: Animatable, stopCurrent = true,
  541. targetMask?: (target: any) => boolean, onAnimationLoop?: () => void): Animatable[] {
  542. let children = target.getDescendants(directDescendantsOnly);
  543. let result = [];
  544. result.push(this.beginAnimation(target, from, to, loop, speedRatio, onAnimationEnd, animatable, stopCurrent, targetMask));
  545. for (var child of children) {
  546. result.push(this.beginAnimation(child, from, to, loop, speedRatio, onAnimationEnd, animatable, stopCurrent, targetMask));
  547. }
  548. return result;
  549. };
  550. Scene.prototype.beginDirectAnimation = function(target: any, animations: Animation[], from: number, to: number, loop?: boolean, speedRatio?: number, onAnimationEnd?: () => void, onAnimationLoop?: () => void): Animatable {
  551. if (speedRatio === undefined) {
  552. speedRatio = 1.0;
  553. }
  554. var animatable = new Animatable(this, target, from, to, loop, speedRatio, onAnimationEnd, animations, onAnimationLoop);
  555. return animatable;
  556. };
  557. Scene.prototype.beginDirectHierarchyAnimation = function(target: Node, directDescendantsOnly: boolean, animations: Animation[], from: number, to: number, loop?: boolean, speedRatio?: number, onAnimationEnd?: () => void, onAnimationLoop?: () => void): Animatable[] {
  558. let children = target.getDescendants(directDescendantsOnly);
  559. let result = [];
  560. result.push(this.beginDirectAnimation(target, animations, from, to, loop, speedRatio, onAnimationEnd, onAnimationLoop));
  561. for (var child of children) {
  562. result.push(this.beginDirectAnimation(child, animations, from, to, loop, speedRatio, onAnimationEnd, onAnimationLoop));
  563. }
  564. return result;
  565. };
  566. Scene.prototype.getAnimatableByTarget = function(target: any): Nullable<Animatable> {
  567. for (var index = 0; index < this._activeAnimatables.length; index++) {
  568. if (this._activeAnimatables[index].target === target) {
  569. return this._activeAnimatables[index];
  570. }
  571. }
  572. return null;
  573. };
  574. Scene.prototype.getAllAnimatablesByTarget = function(target: any): Array<Animatable> {
  575. let result = [];
  576. for (var index = 0; index < this._activeAnimatables.length; index++) {
  577. if (this._activeAnimatables[index].target === target) {
  578. result.push(this._activeAnimatables[index]);
  579. }
  580. }
  581. return result;
  582. };
  583. /**
  584. * Will stop the animation of the given target
  585. * @param target - the target
  586. * @param animationName - the name of the animation to stop (all animations will be stopped if both this and targetMask are empty)
  587. * @param targetMask - a function that determines if the animation should be stopped based on its target (all animations will be stopped if both this and animationName are empty)
  588. */
  589. Scene.prototype.stopAnimation = function(target: any, animationName?: string, targetMask?: (target: any) => boolean): void {
  590. var animatables = this.getAllAnimatablesByTarget(target);
  591. for (var animatable of animatables) {
  592. animatable.stop(animationName, targetMask);
  593. }
  594. };
  595. /**
  596. * Stops and removes all animations that have been applied to the scene
  597. */
  598. Scene.prototype.stopAllAnimations = function(): void {
  599. if (this._activeAnimatables) {
  600. for (let i = 0; i < this._activeAnimatables.length; i++) {
  601. this._activeAnimatables[i].stop();
  602. }
  603. this._activeAnimatables = [];
  604. }
  605. for (var group of this.animationGroups) {
  606. group.stop();
  607. }
  608. };
  609. Scene.prototype._registerTargetForLateAnimationBinding = function(runtimeAnimation: RuntimeAnimation, originalValue: any): void {
  610. let target = runtimeAnimation.target;
  611. this._registeredForLateAnimationBindings.pushNoDuplicate(target);
  612. if (!target._lateAnimationHolders) {
  613. target._lateAnimationHolders = {};
  614. }
  615. if (!target._lateAnimationHolders[runtimeAnimation.targetPath]) {
  616. target._lateAnimationHolders[runtimeAnimation.targetPath] = {
  617. totalWeight: 0,
  618. animations: [],
  619. originalValue: originalValue
  620. };
  621. }
  622. target._lateAnimationHolders[runtimeAnimation.targetPath].animations.push(runtimeAnimation);
  623. target._lateAnimationHolders[runtimeAnimation.targetPath].totalWeight += runtimeAnimation.weight;
  624. };
  625. Scene.prototype._processLateAnimationBindingsForMatrices = function(holder: {
  626. totalWeight: number,
  627. animations: RuntimeAnimation[],
  628. originalValue: Matrix
  629. }): any {
  630. let normalizer = 1.0;
  631. let finalPosition = TmpVectors.Vector3[0];
  632. let finalScaling = TmpVectors.Vector3[1];
  633. let finalQuaternion = TmpVectors.Quaternion[0];
  634. let startIndex = 0;
  635. let originalAnimation = holder.animations[0];
  636. let originalValue = holder.originalValue;
  637. var scale = 1;
  638. if (holder.totalWeight < 1.0) {
  639. // We need to mix the original value in
  640. originalValue.decompose(finalScaling, finalQuaternion, finalPosition);
  641. scale = 1.0 - holder.totalWeight;
  642. } else {
  643. startIndex = 1;
  644. // We need to normalize the weights
  645. normalizer = holder.totalWeight;
  646. originalAnimation.currentValue.decompose(finalScaling, finalQuaternion, finalPosition);
  647. scale = originalAnimation.weight / normalizer;
  648. if (scale == 1) {
  649. return originalAnimation.currentValue;
  650. }
  651. }
  652. finalScaling.scaleInPlace(scale);
  653. finalPosition.scaleInPlace(scale);
  654. finalQuaternion.scaleInPlace(scale);
  655. for (var animIndex = startIndex; animIndex < holder.animations.length; animIndex++) {
  656. var runtimeAnimation = holder.animations[animIndex];
  657. var scale = runtimeAnimation.weight / normalizer;
  658. let currentPosition = TmpVectors.Vector3[2];
  659. let currentScaling = TmpVectors.Vector3[3];
  660. let currentQuaternion = TmpVectors.Quaternion[1];
  661. runtimeAnimation.currentValue.decompose(currentScaling, currentQuaternion, currentPosition);
  662. currentScaling.scaleAndAddToRef(scale, finalScaling);
  663. currentQuaternion.scaleAndAddToRef(scale, finalQuaternion);
  664. currentPosition.scaleAndAddToRef(scale, finalPosition);
  665. }
  666. let workValue = originalAnimation._animationState.workValue;
  667. Matrix.ComposeToRef(finalScaling, finalQuaternion, finalPosition, workValue);
  668. return workValue;
  669. };
  670. Scene.prototype._processLateAnimationBindingsForQuaternions = function(holder: {
  671. totalWeight: number,
  672. animations: RuntimeAnimation[],
  673. originalValue: Quaternion
  674. }, refQuaternion: Quaternion): Quaternion {
  675. let originalAnimation = holder.animations[0];
  676. let originalValue = holder.originalValue;
  677. if (holder.animations.length === 1) {
  678. Quaternion.SlerpToRef(originalValue, originalAnimation.currentValue, Math.min(1.0, holder.totalWeight), refQuaternion);
  679. return refQuaternion;
  680. }
  681. let normalizer = 1.0;
  682. let quaternions: Array<Quaternion>;
  683. let weights: Array<number>;
  684. if (holder.totalWeight < 1.0) {
  685. let scale = 1.0 - holder.totalWeight;
  686. quaternions = [];
  687. weights = [];
  688. quaternions.push(originalValue);
  689. weights.push(scale);
  690. } else {
  691. if (holder.animations.length === 2) { // Slerp as soon as we can
  692. Quaternion.SlerpToRef(holder.animations[0].currentValue, holder.animations[1].currentValue, holder.animations[1].weight / holder.totalWeight, refQuaternion);
  693. return refQuaternion;
  694. }
  695. quaternions = [];
  696. weights = [];
  697. normalizer = holder.totalWeight;
  698. }
  699. for (var animIndex = 0; animIndex < holder.animations.length; animIndex++) {
  700. let runtimeAnimation = holder.animations[animIndex];
  701. quaternions.push(runtimeAnimation.currentValue);
  702. weights.push(runtimeAnimation.weight / normalizer);
  703. }
  704. // https://gamedev.stackexchange.com/questions/62354/method-for-interpolation-between-3-quaternions
  705. let cumulativeAmount = 0;
  706. let cumulativeQuaternion: Nullable<Quaternion> = null;
  707. for (var index = 0; index < quaternions.length;) {
  708. if (!cumulativeQuaternion) {
  709. Quaternion.SlerpToRef(quaternions[index], quaternions[index + 1], weights[index + 1] / (weights[index] + weights[index + 1]), refQuaternion);
  710. cumulativeQuaternion = refQuaternion;
  711. cumulativeAmount = weights[index] + weights[index + 1];
  712. index += 2;
  713. continue;
  714. }
  715. cumulativeAmount += weights[index];
  716. Quaternion.SlerpToRef(cumulativeQuaternion, quaternions[index], weights[index] / cumulativeAmount, cumulativeQuaternion);
  717. index++;
  718. }
  719. return cumulativeQuaternion!;
  720. };
  721. Scene.prototype._processLateAnimationBindings = function(): void {
  722. if (!this._registeredForLateAnimationBindings.length) {
  723. return;
  724. }
  725. for (var index = 0; index < this._registeredForLateAnimationBindings.length; index++) {
  726. var target = this._registeredForLateAnimationBindings.data[index];
  727. for (var path in target._lateAnimationHolders) {
  728. var holder = target._lateAnimationHolders[path];
  729. let originalAnimation: RuntimeAnimation = holder.animations[0];
  730. let originalValue = holder.originalValue;
  731. let matrixDecomposeMode = Animation.AllowMatrixDecomposeForInterpolation && originalValue.m; // ie. data is matrix
  732. let finalValue: any = target[path];
  733. if (matrixDecomposeMode) {
  734. finalValue = this._processLateAnimationBindingsForMatrices(holder);
  735. } else {
  736. let quaternionMode = originalValue.w !== undefined;
  737. if (quaternionMode) {
  738. finalValue = this._processLateAnimationBindingsForQuaternions(holder, finalValue || Quaternion.Identity());
  739. } else {
  740. let startIndex = 0;
  741. let normalizer = 1.0;
  742. if (holder.totalWeight < 1.0) {
  743. // We need to mix the original value in
  744. if (originalValue.scale) {
  745. finalValue = originalValue.scale(1.0 - holder.totalWeight);
  746. } else {
  747. finalValue = originalValue * (1.0 - holder.totalWeight);
  748. }
  749. } else {
  750. // We need to normalize the weights
  751. normalizer = holder.totalWeight;
  752. let scale = originalAnimation.weight / normalizer;
  753. if (scale !== 1) {
  754. if (originalAnimation.currentValue.scale) {
  755. finalValue = originalAnimation.currentValue.scale(scale);
  756. } else {
  757. finalValue = originalAnimation.currentValue * scale;
  758. }
  759. } else {
  760. finalValue = originalAnimation.currentValue;
  761. }
  762. startIndex = 1;
  763. }
  764. for (var animIndex = startIndex; animIndex < holder.animations.length; animIndex++) {
  765. var runtimeAnimation = holder.animations[animIndex];
  766. var scale = runtimeAnimation.weight / normalizer;
  767. if (runtimeAnimation.currentValue.scaleAndAddToRef) {
  768. runtimeAnimation.currentValue.scaleAndAddToRef(scale, finalValue);
  769. } else {
  770. finalValue += runtimeAnimation.currentValue * scale;
  771. }
  772. }
  773. }
  774. }
  775. target[path] = finalValue;
  776. }
  777. target._lateAnimationHolders = {};
  778. }
  779. this._registeredForLateAnimationBindings.reset();
  780. };
  781. declare module "../Bones/bone" {
  782. export interface Bone {
  783. /**
  784. * Copy an animation range from another bone
  785. * @param source defines the source bone
  786. * @param rangeName defines the range name to copy
  787. * @param frameOffset defines the frame offset
  788. * @param rescaleAsRequired defines if rescaling must be applied if required
  789. * @param skelDimensionsRatio defines the scaling ratio
  790. * @returns true if operation was successful
  791. */
  792. copyAnimationRange(source: Bone, rangeName: string, frameOffset: number, rescaleAsRequired: boolean, skelDimensionsRatio: Nullable<Vector3>): boolean;
  793. }
  794. }
  795. Bone.prototype.copyAnimationRange = function(source: Bone, rangeName: string, frameOffset: number, rescaleAsRequired = false, skelDimensionsRatio: Nullable<Vector3> = null): boolean {
  796. // all animation may be coming from a library skeleton, so may need to create animation
  797. if (this.animations.length === 0) {
  798. this.animations.push(new Animation(this.name, "_matrix", source.animations[0].framePerSecond, Animation.ANIMATIONTYPE_MATRIX, 0));
  799. this.animations[0].setKeys([]);
  800. }
  801. // get animation info / verify there is such a range from the source bone
  802. var sourceRange = source.animations[0].getRange(rangeName);
  803. if (!sourceRange) {
  804. return false;
  805. }
  806. var from = sourceRange.from;
  807. var to = sourceRange.to;
  808. var sourceKeys = source.animations[0].getKeys();
  809. // rescaling prep
  810. var sourceBoneLength = source.length;
  811. var sourceParent = source.getParent();
  812. var parent = this.getParent();
  813. var parentScalingReqd = rescaleAsRequired && sourceParent && sourceBoneLength && this.length && sourceBoneLength !== this.length;
  814. var parentRatio = parentScalingReqd && parent && sourceParent ? parent.length / sourceParent.length : 1;
  815. var dimensionsScalingReqd = rescaleAsRequired && !parent && skelDimensionsRatio && (skelDimensionsRatio.x !== 1 || skelDimensionsRatio.y !== 1 || skelDimensionsRatio.z !== 1);
  816. var destKeys = this.animations[0].getKeys();
  817. // loop vars declaration
  818. var orig: { frame: number, value: Matrix };
  819. var origTranslation: Vector3;
  820. var mat: Matrix;
  821. for (var key = 0, nKeys = sourceKeys.length; key < nKeys; key++) {
  822. orig = sourceKeys[key];
  823. if (orig.frame >= from && orig.frame <= to) {
  824. if (rescaleAsRequired) {
  825. mat = orig.value.clone();
  826. // scale based on parent ratio, when bone has parent
  827. if (parentScalingReqd) {
  828. origTranslation = mat.getTranslation();
  829. mat.setTranslation(origTranslation.scaleInPlace(parentRatio));
  830. // scale based on skeleton dimension ratio when root bone, and value is passed
  831. } else if (dimensionsScalingReqd && skelDimensionsRatio) {
  832. origTranslation = mat.getTranslation();
  833. mat.setTranslation(origTranslation.multiplyInPlace(skelDimensionsRatio));
  834. // use original when root bone, and no data for skelDimensionsRatio
  835. } else {
  836. mat = orig.value;
  837. }
  838. } else {
  839. mat = orig.value;
  840. }
  841. destKeys.push({ frame: orig.frame + frameOffset, value: mat });
  842. }
  843. }
  844. this.animations[0].createRange(rangeName, from + frameOffset, to + frameOffset);
  845. return true;
  846. };