runtimeAnimation.js 23 KB

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