runtimeAnimation.ts 23 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649
  1. import { DeepImmutable } from "../types";
  2. import { Quaternion, Vector3, Vector2, Size, Color3, Matrix } from "../Maths/math";
  3. import { Animation } from "./animation";
  4. import { AnimationEvent } from "./animationEvent";
  5. declare type Animatable = import("./animatable").Animatable;
  6. import { Scene } from "../scene";
  7. import { IAnimationKey } from './animationKey';
  8. // Static values to help the garbage collector
  9. // Quaternion
  10. const _staticOffsetValueQuaternion: DeepImmutable<Quaternion> = Object.freeze(new Quaternion(0, 0, 0, 0));
  11. // Vector3
  12. const _staticOffsetValueVector3: DeepImmutable<Vector3> = Object.freeze(Vector3.Zero());
  13. // Vector2
  14. const _staticOffsetValueVector2: DeepImmutable<Vector2> = Object.freeze(Vector2.Zero());
  15. // Size
  16. const _staticOffsetValueSize: DeepImmutable<Size> = Object.freeze(Size.Zero());
  17. // Color3
  18. const _staticOffsetValueColor3: DeepImmutable<Color3> = Object.freeze(Color3.Black());
  19. /**
  20. * Defines a runtime animation
  21. */
  22. export class RuntimeAnimation {
  23. private _events = new Array<AnimationEvent>();
  24. /**
  25. * The current frame of the runtime animation
  26. */
  27. private _currentFrame: number = 0;
  28. /**
  29. * The animation used by the runtime animation
  30. */
  31. private _animation: Animation;
  32. /**
  33. * The target of the runtime animation
  34. */
  35. private _target: any;
  36. /**
  37. * The initiating animatable
  38. */
  39. private _host: Animatable;
  40. /**
  41. * The original value of the runtime animation
  42. */
  43. private _originalValue = new Array<any>();
  44. /**
  45. * The original blend value of the runtime animation
  46. */
  47. private _originalBlendValue: any;
  48. /**
  49. * The offsets cache of the runtime animation
  50. */
  51. private _offsetsCache: { [key: string]: any } = {};
  52. /**
  53. * The high limits cache of the runtime animation
  54. */
  55. private _highLimitsCache: { [key: string]: any } = {};
  56. /**
  57. * Specifies if the runtime animation has been stopped
  58. */
  59. private _stopped = false;
  60. /**
  61. * The blending factor of the runtime animation
  62. */
  63. private _blendingFactor = 0;
  64. /**
  65. * The BabylonJS scene
  66. */
  67. private _scene: Scene;
  68. /**
  69. * The current value of the runtime animation
  70. */
  71. private _currentValue: any;
  72. /** @hidden */
  73. public _workValue: any;
  74. /**
  75. * The active target of the runtime animation
  76. */
  77. private _activeTargets: any[];
  78. private _currentActiveTarget: any;
  79. private _directTarget: any;
  80. /**
  81. * The target path of the runtime animation
  82. */
  83. private _targetPath: string = "";
  84. /**
  85. * The weight of the runtime animation
  86. */
  87. private _weight = 1.0;
  88. /**
  89. * The ratio offset of the runtime animation
  90. */
  91. private _ratioOffset = 0;
  92. /**
  93. * The previous delay of the runtime animation
  94. */
  95. private _previousDelay: number = 0;
  96. /**
  97. * The previous ratio of the runtime animation
  98. */
  99. private _previousRatio: number = 0;
  100. private _enableBlending: boolean;
  101. private _correctLoopMode: number | undefined;
  102. private _keys: IAnimationKey[];
  103. private _minFrame: number;
  104. private _maxFrame: number;
  105. private _minValue: any;
  106. private _maxValue: any;
  107. /**
  108. * Gets the current frame of the runtime animation
  109. */
  110. public get currentFrame(): number {
  111. return this._currentFrame;
  112. }
  113. /**
  114. * Gets the weight of the runtime animation
  115. */
  116. public get weight(): number {
  117. return this._weight;
  118. }
  119. /**
  120. * Gets the current value of the runtime animation
  121. */
  122. public get currentValue(): any {
  123. return this._currentValue;
  124. }
  125. /**
  126. * Gets the target path of the runtime animation
  127. */
  128. public get targetPath(): string {
  129. return this._targetPath;
  130. }
  131. /**
  132. * Gets the actual target of the runtime animation
  133. */
  134. public get target(): any {
  135. return this._currentActiveTarget;
  136. }
  137. /**
  138. * Create a new RuntimeAnimation object
  139. * @param target defines the target of the animation
  140. * @param animation defines the source animation object
  141. * @param scene defines the hosting scene
  142. * @param host defines the initiating Animatable
  143. */
  144. public constructor(target: any, animation: Animation, scene: Scene, host: Animatable) {
  145. this._animation = animation;
  146. this._target = target;
  147. this._scene = scene;
  148. this._host = host;
  149. this._activeTargets = [];
  150. animation._runtimeAnimations.push(this);
  151. // Normalization
  152. if (this._host && this._host.syncRoot) {
  153. this._normalizationProcessor = this._defaultNormalizationProcessor;
  154. }
  155. // Limits
  156. this._keys = this._animation.getKeys();
  157. this._minFrame = this._keys[0].frame;
  158. this._maxFrame = this._keys[this._keys.length - 1].frame;
  159. this._minValue = this._keys[0].value;
  160. this._maxValue = this._keys[this._keys.length - 1].value;
  161. // Add a start key at frame 0 if missing
  162. if (this._minFrame !== 0) {
  163. const newKey = { frame: 0, value: this._minValue };
  164. this._keys.splice(0, 0, newKey);
  165. }
  166. // Check data
  167. if (this._target instanceof Array) {
  168. var index = 0;
  169. for (const target of this._target) {
  170. this._preparePath(target, index);
  171. this._getOriginalValues(index);
  172. index++;
  173. }
  174. this.setValue = this._setValueForArray;
  175. }
  176. else {
  177. this._preparePath(this._target);
  178. this._getOriginalValues();
  179. this.setValue = this._setValueForDirect;
  180. this._directTarget = this._activeTargets[0];
  181. }
  182. // Cloning events locally
  183. var events = animation.getEvents();
  184. if (events && events.length > 0) {
  185. events.forEach((e) => {
  186. this._events.push(e._clone());
  187. });
  188. }
  189. this._correctLoopMode = this._getCorrectLoopMode();
  190. this._enableBlending = target && target.animationPropertiesOverride ? target.animationPropertiesOverride.enableBlending : this._animation.enableBlending;
  191. if (this._enableBlending) {
  192. this._activeBlendingProcessor = this._blendingProcessor;
  193. } else {
  194. this._activeBlendingProcessor = this._noBlendingProcessor;
  195. }
  196. }
  197. private _normalizationProcessor = (returnValue: boolean, range: number, ratio: number, from: number, to: number) => {
  198. return (returnValue && range !== 0) ? from + ratio % range : to;;
  199. };
  200. private _defaultNormalizationProcessor = (returnValue: boolean, range: number, ratio: number, from: number, to: number) => {
  201. const syncRoot = this._host.syncRoot;
  202. const hostNormalizedFrame = (syncRoot.masterFrame - syncRoot.fromFrame) / (syncRoot.toFrame - syncRoot.fromFrame);
  203. return from + (to - from) * hostNormalizedFrame;
  204. }
  205. private _preparePath(target: any, targetIndex = 0) {
  206. let targetPropertyPath = this._animation.targetPropertyPath;
  207. if (targetPropertyPath.length > 1) {
  208. var property = target[targetPropertyPath[0]];
  209. for (var index = 1; index < targetPropertyPath.length - 1; index++) {
  210. property = property[targetPropertyPath[index]];
  211. }
  212. this._targetPath = targetPropertyPath[targetPropertyPath.length - 1];
  213. this._activeTargets[targetIndex] = property;
  214. } else {
  215. this._targetPath = targetPropertyPath[0];
  216. this._activeTargets[targetIndex] = target;
  217. }
  218. }
  219. /**
  220. * Gets the animation from the runtime animation
  221. */
  222. public get animation(): Animation {
  223. return this._animation;
  224. }
  225. /**
  226. * Resets the runtime animation to the beginning
  227. * @param restoreOriginal defines whether to restore the target property to the original value
  228. */
  229. public reset(restoreOriginal = false): void {
  230. if (restoreOriginal) {
  231. if (this._target instanceof Array) {
  232. var index = 0;
  233. for (const target of this._target) {
  234. if (this._originalValue[index] !== undefined) {
  235. this._setValue(target, this._activeTargets[index], this._originalValue[index], -1, index);
  236. }
  237. index++;
  238. }
  239. }
  240. else {
  241. if (this._originalValue[0] !== undefined) {
  242. this._setValue(this._target, this._directTarget, this._originalValue[0], -1, 0);
  243. }
  244. }
  245. }
  246. this._offsetsCache = {};
  247. this._highLimitsCache = {};
  248. this._currentFrame = 0;
  249. this._blendingFactor = 0;
  250. // Events
  251. for (var index = 0; index < this._events.length; index++) {
  252. this._events[index].isDone = false;
  253. }
  254. }
  255. /**
  256. * Specifies if the runtime animation is stopped
  257. * @returns Boolean specifying if the runtime animation is stopped
  258. */
  259. public isStopped(): boolean {
  260. return this._stopped;
  261. }
  262. /**
  263. * Disposes of the runtime animation
  264. */
  265. public dispose(): void {
  266. let index = this._animation.runtimeAnimations.indexOf(this);
  267. if (index > -1) {
  268. this._animation.runtimeAnimations.splice(index, 1);
  269. }
  270. }
  271. /**
  272. * Interpolates the animation from the current frame
  273. * @param currentFrame The frame to interpolate the animation to
  274. * @param repeatCount The number of times that the animation should loop
  275. * @param loopMode The type of looping mode to use
  276. * @param offsetValue Animation offset value
  277. * @param highLimitValue The high limit value
  278. * @returns The interpolated value
  279. */
  280. private _interpolate(currentFrame: number, repeatCount: number, loopMode?: number, offsetValue?: any, highLimitValue?: any): any {
  281. this._currentFrame = currentFrame;
  282. if (this._animation.dataType === Animation.ANIMATIONTYPE_MATRIX && !this._workValue) {
  283. this._workValue = Matrix.Zero();
  284. }
  285. return this._animation._interpolate(currentFrame, repeatCount, this._workValue, loopMode, offsetValue, highLimitValue);
  286. }
  287. /**
  288. * Apply the interpolated value to the target
  289. * @param currentValue defines the value computed by the animation
  290. * @param weight defines the weight to apply to this value (Defaults to 1.0)
  291. */
  292. public setValue: (currentValue: any, weight: number) => void;
  293. private _setValueForArray = (currentValue: any, weight = 1.0) => {
  294. for (var index = 0; index < this._target.length; index++) {
  295. const target = this._target[index];
  296. this._setValue(target, this._activeTargets[index], currentValue, weight, index);
  297. }
  298. }
  299. private _setValueForDirect = (currentValue: any, weight = 1.0) => {
  300. this._setValue(this._target, this._directTarget, currentValue, weight, 0);
  301. }
  302. private _getOriginalValues(targetIndex = 0) {
  303. let originalValue: any;
  304. let target = this._activeTargets[targetIndex];
  305. if (target.getRestPose && this._targetPath === "_matrix") { // For bones
  306. originalValue = target.getRestPose();
  307. } else {
  308. originalValue = target[this._targetPath];
  309. }
  310. if (originalValue && originalValue.clone) {
  311. this._originalValue[targetIndex] = originalValue.clone();
  312. } else {
  313. this._originalValue[targetIndex] = originalValue;
  314. }
  315. }
  316. private _activeBlendingProcessor: (currentValue: any, target: any) => void;
  317. private _noBlendingProcessor = (currentValue: any) => {
  318. this._currentValue = currentValue;
  319. }
  320. private _blendingProcessor = (currentValue: any, target: any) => {
  321. if (this._blendingFactor <= 1.0) {
  322. if (!this._originalBlendValue) {
  323. let originalValue = this._currentActiveTarget[this._targetPath];
  324. if (originalValue.clone) {
  325. this._originalBlendValue = originalValue.clone();
  326. } else {
  327. this._originalBlendValue = originalValue;
  328. }
  329. }
  330. if (this._originalBlendValue.m) { // Matrix
  331. if (Animation.AllowMatrixDecomposeForInterpolation) {
  332. if (this._currentValue) {
  333. Matrix.DecomposeLerpToRef(this._originalBlendValue, currentValue, this._blendingFactor, this._currentValue);
  334. } else {
  335. this._currentValue = Matrix.DecomposeLerp(this._originalBlendValue, currentValue, this._blendingFactor);
  336. }
  337. } else {
  338. if (this._currentValue) {
  339. Matrix.LerpToRef(this._originalBlendValue, currentValue, this._blendingFactor, this._currentValue);
  340. } else {
  341. this._currentValue = Matrix.Lerp(this._originalBlendValue, currentValue, this._blendingFactor);
  342. }
  343. }
  344. } else {
  345. this._currentValue = Animation._UniversalLerp(this._originalBlendValue, currentValue, this._blendingFactor);
  346. }
  347. const blendingSpeed = target && target.animationPropertiesOverride ? target.animationPropertiesOverride.blendingSpeed : this._animation.blendingSpeed;
  348. this._blendingFactor += blendingSpeed;
  349. } else {
  350. this._currentValue = currentValue;
  351. }
  352. }
  353. private _setValue(target: any, destination: any, currentValue: any, weight: number, targetIndex: number): void {
  354. // Set value
  355. this._currentActiveTarget = destination;
  356. this._weight = weight;
  357. this._activeBlendingProcessor(currentValue, target);
  358. if (weight !== -1.0) {
  359. this._scene._registerTargetForLateAnimationBinding(this, this._originalValue[targetIndex]);
  360. } else {
  361. destination[this._targetPath] = this._currentValue;
  362. }
  363. if (target.markAsDirty) {
  364. target.markAsDirty(this._animation.targetProperty);
  365. }
  366. }
  367. /**
  368. * Gets the loop pmode of the runtime animation
  369. * @returns Loop Mode
  370. */
  371. private _getCorrectLoopMode(): number | undefined {
  372. if (this._target && this._target.animationPropertiesOverride) {
  373. return this._target.animationPropertiesOverride.loopMode;
  374. }
  375. return this._animation.loopMode;
  376. }
  377. /**
  378. * Move the current animation to a given frame
  379. * @param frame defines the frame to move to
  380. */
  381. public goToFrame(frame: number): void {
  382. let keys = this._animation.getKeys();
  383. if (frame < keys[0].frame) {
  384. frame = keys[0].frame;
  385. } else if (frame > keys[keys.length - 1].frame) {
  386. frame = keys[keys.length - 1].frame;
  387. }
  388. var currentValue = this._interpolate(frame, 0, this._correctLoopMode);
  389. this.setValue(currentValue, -1);
  390. }
  391. /**
  392. * @hidden Internal use only
  393. */
  394. public _prepareForSpeedRatioChange(newSpeedRatio: number): void {
  395. let newRatio = this._previousDelay * (this._animation.framePerSecond * newSpeedRatio) / 1000.0;
  396. this._ratioOffset = this._previousRatio - newRatio;
  397. }
  398. /**
  399. * Execute the current animation
  400. * @param delay defines the delay to add to the current frame
  401. * @param from defines the lower bound of the animation range
  402. * @param to defines the upper bound of the animation range
  403. * @param loop defines if the current animation must loop
  404. * @param speedRatio defines the current speed ratio
  405. * @param weight defines the weight of the animation (default is -1 so no weight)
  406. * @param onLoop optional callback called when animation loops
  407. * @returns a boolean indicating if the animation is running
  408. */
  409. public animate(delay: number, from: number, to: number, loop: boolean, speedRatio: number, weight = -1.0, onLoop?: () => void): boolean {
  410. let targetPropertyPath = this._animation.targetPropertyPath;
  411. if (!targetPropertyPath || targetPropertyPath.length < 1) {
  412. this._stopped = true;
  413. return false;
  414. }
  415. let returnValue = true;
  416. // Check limits
  417. if (from < this._minFrame || from > this._maxFrame) {
  418. from = this._minFrame;
  419. }
  420. if (to < this._minFrame || to > this._maxFrame) {
  421. to = this._maxFrame;
  422. }
  423. const range = to - from;
  424. let offsetValue: any;
  425. // Compute ratio which represents the frame delta between from and to
  426. const ratio = (delay * (this._animation.framePerSecond * speedRatio) / 1000.0) + this._ratioOffset;
  427. let highLimitValue = 0;
  428. this._previousDelay = delay;
  429. this._previousRatio = ratio;
  430. if (!loop && (to > from && ratio >= range)) { // If we are out of range and not looping get back to caller
  431. returnValue = false;
  432. highLimitValue = this._animation._getKeyValue(this._maxValue);
  433. } else if (!loop && (from > to && ratio <= range)) {
  434. returnValue = false;
  435. highLimitValue = this._animation._getKeyValue(this._minValue);
  436. } else if (this._correctLoopMode !== Animation.ANIMATIONLOOPMODE_CYCLE) {
  437. var keyOffset = to.toString() + from.toString();
  438. if (!this._offsetsCache[keyOffset]) {
  439. var fromValue = this._interpolate(from, 0, Animation.ANIMATIONLOOPMODE_CYCLE);
  440. var toValue = this._interpolate(to, 0, Animation.ANIMATIONLOOPMODE_CYCLE);
  441. switch (this._animation.dataType) {
  442. // Float
  443. case Animation.ANIMATIONTYPE_FLOAT:
  444. this._offsetsCache[keyOffset] = toValue - fromValue;
  445. break;
  446. // Quaternion
  447. case Animation.ANIMATIONTYPE_QUATERNION:
  448. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  449. break;
  450. // Vector3
  451. case Animation.ANIMATIONTYPE_VECTOR3:
  452. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  453. // Vector2
  454. case Animation.ANIMATIONTYPE_VECTOR2:
  455. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  456. // Size
  457. case Animation.ANIMATIONTYPE_SIZE:
  458. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  459. // Color3
  460. case Animation.ANIMATIONTYPE_COLOR3:
  461. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  462. default:
  463. break;
  464. }
  465. this._highLimitsCache[keyOffset] = toValue;
  466. }
  467. highLimitValue = this._highLimitsCache[keyOffset];
  468. offsetValue = this._offsetsCache[keyOffset];
  469. }
  470. if (offsetValue === undefined) {
  471. switch (this._animation.dataType) {
  472. // Float
  473. case Animation.ANIMATIONTYPE_FLOAT:
  474. offsetValue = 0;
  475. break;
  476. // Quaternion
  477. case Animation.ANIMATIONTYPE_QUATERNION:
  478. offsetValue = _staticOffsetValueQuaternion;
  479. break;
  480. // Vector3
  481. case Animation.ANIMATIONTYPE_VECTOR3:
  482. offsetValue = _staticOffsetValueVector3;
  483. break;
  484. // Vector2
  485. case Animation.ANIMATIONTYPE_VECTOR2:
  486. offsetValue = _staticOffsetValueVector2;
  487. break;
  488. // Size
  489. case Animation.ANIMATIONTYPE_SIZE:
  490. offsetValue = _staticOffsetValueSize;
  491. break;
  492. // Color3
  493. case Animation.ANIMATIONTYPE_COLOR3:
  494. offsetValue = _staticOffsetValueColor3;
  495. }
  496. }
  497. // Compute value
  498. let currentFrame = this._normalizationProcessor(returnValue, range, ratio, from, to);
  499. // Reset events if looping
  500. const events = this._events;
  501. if (range > 0 && this.currentFrame > currentFrame ||
  502. range < 0 && this.currentFrame < currentFrame) {
  503. if (onLoop) {
  504. onLoop();
  505. }
  506. // Need to reset animation events
  507. if (events.length) {
  508. for (var index = 0; index < events.length; index++) {
  509. if (!events[index].onlyOnce) {
  510. // reset event, the animation is looping
  511. events[index].isDone = false;
  512. }
  513. }
  514. }
  515. }
  516. const repeatCount = range === 0 ? 0 : (ratio / range) >> 0;
  517. const currentValue = this._interpolate(currentFrame, repeatCount, this._correctLoopMode, offsetValue, highLimitValue);
  518. // Set value
  519. this.setValue(currentValue, weight);
  520. // Check events
  521. if (events.length) {
  522. for (var index = 0; index < events.length; index++) {
  523. // Make sure current frame has passed event frame and that event frame is within the current range
  524. // Also, handle both forward and reverse animations
  525. if (
  526. (range > 0 && currentFrame >= events[index].frame && events[index].frame >= from) ||
  527. (range < 0 && currentFrame <= events[index].frame && events[index].frame <= from)
  528. ) {
  529. var event = events[index];
  530. if (!event.isDone) {
  531. // If event should be done only once, remove it.
  532. if (event.onlyOnce) {
  533. events.splice(index, 1);
  534. index--;
  535. }
  536. event.isDone = true;
  537. event.action(currentFrame);
  538. } // Don't do anything if the event has already be done.
  539. }
  540. }
  541. }
  542. if (!returnValue) {
  543. this._stopped = true;
  544. }
  545. return returnValue;
  546. }
  547. }