viewerModel.ts 27 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765
  1. import { ISceneLoaderPlugin, ISceneLoaderPluginAsync, AnimationGroup, Animatable, AbstractMesh, Tools, Scene, SceneLoader, Observable, SceneLoaderProgressEvent, Tags, ParticleSystem, Skeleton, IDisposable, Nullable, Animation, Quaternion, Material, Vector3, AnimationPropertiesOverride, QuinticEase, SineEase, CircleEase, BackEase, BounceEase, CubicEase, ElasticEase, ExponentialEase, PowerEase, QuadraticEase, QuarticEase, PBRMaterial, MultiMaterial } from "babylonjs";
  2. import { GLTFFileLoader, GLTF2 } from "babylonjs-loaders";
  3. import { IModelConfiguration } from "../configuration/interfaces/modelConfiguration";
  4. import { IModelAnimationConfiguration } from "../configuration/interfaces/modelAnimationConfiguration";
  5. import { IModelAnimation, GroupModelAnimation, AnimationPlayMode, ModelAnimationConfiguration, EasingFunction, AnimationState } from "./modelAnimation";
  6. import { deepmerge, extendClassWithConfig } from '../helper/';
  7. import { ObservablesManager } from "../managers/observablesManager";
  8. import { ConfigurationContainer } from "../configuration/configurationContainer";
  9. /**
  10. * The current state of the model
  11. */
  12. export enum ModelState {
  13. INIT,
  14. LOADING,
  15. LOADED,
  16. ENTRY,
  17. ENTRYDONE,
  18. COMPLETE,
  19. CANCELED,
  20. ERROR
  21. }
  22. /**
  23. * The viewer model is a container for all assets representing a sngle loaded model.
  24. */
  25. export class ViewerModel implements IDisposable {
  26. /**
  27. * The loader used to load this model.
  28. */
  29. public loader: ISceneLoaderPlugin | ISceneLoaderPluginAsync;
  30. private _animations: Array<IModelAnimation>;
  31. /**
  32. * the list of meshes that are a part of this model
  33. */
  34. private _meshes: Array<AbstractMesh> = [];
  35. /**
  36. * This model's root mesh (the parent of all other meshes).
  37. * This mesh does not(!) exist in the meshes array.
  38. */
  39. public rootMesh: AbstractMesh;
  40. private _pivotMesh: AbstractMesh;
  41. /**
  42. * ParticleSystems connected to this model
  43. */
  44. public particleSystems: Array<ParticleSystem> = [];
  45. /**
  46. * Skeletons defined in this model
  47. */
  48. public skeletons: Array<Skeleton> = [];
  49. /**
  50. * The current model animation.
  51. * On init, this will be undefined.
  52. */
  53. public currentAnimation: IModelAnimation;
  54. /**
  55. * Observers registered here will be executed when the model is done loading
  56. */
  57. public onLoadedObservable: Observable<ViewerModel>;
  58. /**
  59. * Observers registered here will be executed when the loader notified of a progress event
  60. */
  61. public onLoadProgressObservable: Observable<SceneLoaderProgressEvent>;
  62. /**
  63. * Observers registered here will be executed when the loader notified of an error.
  64. */
  65. public onLoadErrorObservable: Observable<{ message: string; exception: any }>;
  66. /**
  67. * Will be executed after the model finished loading and complete, including entry animation and lod
  68. */
  69. public onCompleteObservable: Observable<ViewerModel>;
  70. /**
  71. * Observers registered here will be executed every time the model is being configured.
  72. * This can be used to extend the model's configuration without extending the class itself
  73. */
  74. public onAfterConfigure: Observable<ViewerModel>;
  75. /**
  76. * The current model state (loaded, error, etc)
  77. */
  78. public state: ModelState;
  79. /**
  80. * A loadID provided by the modelLoader, unique to ths (Abstract)Viewer instance.
  81. */
  82. public loadId: number;
  83. public loadInfo: GLTF2.IAsset;
  84. private _loadedUrl: string;
  85. private _modelConfiguration: IModelConfiguration;
  86. private _loaderDone: boolean = false;
  87. private _entryAnimation: ModelAnimationConfiguration;
  88. private _exitAnimation: ModelAnimationConfiguration;
  89. private _scaleTransition: Animation;
  90. private _animatables: Array<Animatable> = [];
  91. private _frameRate: number = 60;
  92. private _shadowsRenderedAfterLoad: boolean = false;
  93. constructor(private _observablesManager: ObservablesManager, modelConfiguration: IModelConfiguration, private _configurationContainer?: ConfigurationContainer) {
  94. this.onLoadedObservable = new Observable();
  95. this.onLoadErrorObservable = new Observable();
  96. this.onLoadProgressObservable = new Observable();
  97. this.onCompleteObservable = new Observable();
  98. this.onAfterConfigure = new Observable();
  99. this.state = ModelState.INIT;
  100. this.rootMesh = new AbstractMesh("modelRootMesh");
  101. this._pivotMesh = new AbstractMesh("pivotMesh");
  102. this._pivotMesh.parent = this.rootMesh;
  103. // rotate 180, gltf fun
  104. this._pivotMesh.rotation.y += Math.PI;
  105. this._scaleTransition = new Animation("scaleAnimation", "scaling", this._frameRate, Animation.ANIMATIONTYPE_VECTOR3, Animation.ANIMATIONLOOPMODE_CONSTANT);
  106. this._animations = [];
  107. //create a copy of the configuration to make sure it doesn't change even after it is changed in the viewer
  108. this._modelConfiguration = deepmerge((this._configurationContainer && this._configurationContainer.configuration.model) || {}, modelConfiguration);
  109. if (this._observablesManager) { this._observablesManager.onModelAddedObservable.notifyObservers(this); }
  110. if (this._modelConfiguration.entryAnimation) {
  111. this.rootMesh.setEnabled(false);
  112. }
  113. this.onLoadedObservable.add(() => {
  114. this.updateConfiguration(this._modelConfiguration);
  115. if (this._observablesManager) { this._observablesManager.onModelLoadedObservable.notifyObservers(this); }
  116. this._initAnimations();
  117. });
  118. this.onCompleteObservable.add(() => {
  119. this.state = ModelState.COMPLETE;
  120. });
  121. }
  122. public get shadowsRenderedAfterLoad() {
  123. return this._shadowsRenderedAfterLoad;
  124. }
  125. public set shadowsRenderedAfterLoad(rendered: boolean) {
  126. if (!rendered) {
  127. throw new Error("can only be enabled");
  128. } else {
  129. this._shadowsRenderedAfterLoad = rendered;
  130. }
  131. }
  132. public getViewerId() {
  133. return this._configurationContainer && this._configurationContainer.viewerId;
  134. }
  135. /**
  136. * Is this model enabled?
  137. */
  138. public get enabled() {
  139. return this.rootMesh.isEnabled();
  140. }
  141. /**
  142. * Set whether this model is enabled or not.
  143. */
  144. public set enabled(enable: boolean) {
  145. this.rootMesh.setEnabled(enable);
  146. }
  147. public set loaderDone(done: boolean) {
  148. this._loaderDone = done;
  149. this._checkCompleteState();
  150. }
  151. private _checkCompleteState() {
  152. if (this._loaderDone && (this.state === ModelState.ENTRYDONE)) {
  153. this._modelComplete();
  154. }
  155. }
  156. /**
  157. * Add a mesh to this model.
  158. * Any mesh that has no parent will be provided with the root mesh as its new parent.
  159. *
  160. * @param mesh the new mesh to add
  161. * @param triggerLoaded should this mesh trigger the onLoaded observable. Used when adding meshes manually.
  162. */
  163. public addMesh(mesh: AbstractMesh, triggerLoaded?: boolean) {
  164. if (!mesh.parent) {
  165. mesh.parent = this._pivotMesh;
  166. }
  167. mesh.receiveShadows = !!this.configuration.receiveShadows;
  168. this._meshes.push(mesh);
  169. if (triggerLoaded) {
  170. return this.onLoadedObservable.notifyObserversWithPromise(this);
  171. }
  172. }
  173. /**
  174. * get the list of meshes (excluding the root mesh)
  175. */
  176. public get meshes() {
  177. return this._meshes;
  178. }
  179. /**
  180. * Get the model's configuration
  181. */
  182. public get configuration(): IModelConfiguration {
  183. return this._modelConfiguration;
  184. }
  185. /**
  186. * (Re-)set the model's entire configuration
  187. * @param newConfiguration the new configuration to replace the new one
  188. */
  189. public set configuration(newConfiguration: IModelConfiguration) {
  190. this._modelConfiguration = newConfiguration;
  191. this._configureModel();
  192. }
  193. /**
  194. * Update the current configuration with new values.
  195. * Configuration will not be overwritten, but merged with the new configuration.
  196. * Priority is to the new configuration
  197. * @param newConfiguration the configuration to be merged into the current configuration;
  198. */
  199. public updateConfiguration(newConfiguration: Partial<IModelConfiguration>) {
  200. this._modelConfiguration = deepmerge(this._modelConfiguration, newConfiguration);
  201. this._configureModel();
  202. }
  203. private _initAnimations() {
  204. // check if this is not a gltf loader and init the animations
  205. if (this.skeletons.length) {
  206. this.skeletons.forEach((skeleton, idx) => {
  207. let ag = new AnimationGroup("animation-" + idx);
  208. let add = false;
  209. skeleton.getAnimatables().forEach(a => {
  210. if (a.animations[0]) {
  211. ag.addTargetedAnimation(a.animations[0], a);
  212. add = true;
  213. }
  214. });
  215. if (add) {
  216. this.addAnimationGroup(ag);
  217. }
  218. });
  219. }
  220. let completeCallback = () => {
  221. }
  222. if (this._modelConfiguration.animation) {
  223. if (this._modelConfiguration.animation.playOnce) {
  224. this._animations.forEach(a => {
  225. a.playMode = AnimationPlayMode.ONCE;
  226. });
  227. }
  228. if (this._modelConfiguration.animation.autoStart && this._animations.length) {
  229. let animationName = this._modelConfiguration.animation.autoStart === true ?
  230. this._animations[0].name : this._modelConfiguration.animation.autoStart;
  231. completeCallback = () => {
  232. this.playAnimation(animationName);
  233. }
  234. }
  235. }
  236. this._enterScene(completeCallback);
  237. }
  238. /**
  239. * Animates the model from the current position to the default position
  240. * @param completeCallback A function to call when the animation has completed
  241. */
  242. private _enterScene(completeCallback?: () => void): void {
  243. const scene = this.rootMesh.getScene();
  244. let previousValue = scene.animationPropertiesOverride!.enableBlending;
  245. let callback = () => {
  246. this.state = ModelState.ENTRYDONE;
  247. scene.animationPropertiesOverride!.enableBlending = previousValue;
  248. this._checkCompleteState();
  249. if (completeCallback) completeCallback();
  250. }
  251. if (!this._entryAnimation) {
  252. callback();
  253. return;
  254. }
  255. this.rootMesh.setEnabled(true);
  256. // disable blending for the sake of the entry animation;
  257. scene.animationPropertiesOverride!.enableBlending = false;
  258. this._applyAnimation(this._entryAnimation, true, callback);
  259. }
  260. /**
  261. * Animates the model from the current position to the exit-screen position
  262. * @param completeCallback A function to call when the animation has completed
  263. */
  264. private _exitScene(completeCallback: () => void): void {
  265. if (!this._exitAnimation) {
  266. completeCallback();
  267. return;
  268. }
  269. this._applyAnimation(this._exitAnimation, false, completeCallback);
  270. }
  271. private _modelComplete() {
  272. //reapply material defines to be sure:
  273. let meshes = this._pivotMesh.getChildMeshes(false);
  274. meshes.filter(m => m.material).forEach((mesh) => {
  275. this._applyModelMaterialConfiguration(mesh.material!);
  276. });
  277. this.state = ModelState.COMPLETE;
  278. this.onCompleteObservable.notifyObservers(this);
  279. }
  280. /**
  281. * Add a new animation group to this model.
  282. * @param animationGroup the new animation group to be added
  283. */
  284. public addAnimationGroup(animationGroup: AnimationGroup) {
  285. this._animations.push(new GroupModelAnimation(animationGroup));
  286. }
  287. /**
  288. * Get the ModelAnimation array
  289. */
  290. public getAnimations(): Array<IModelAnimation> {
  291. return this._animations;
  292. }
  293. /**
  294. * Get the animations' names. Using the names you can play a specific animation.
  295. */
  296. public getAnimationNames(): Array<string> {
  297. return this._animations.map(a => a.name);
  298. }
  299. /**
  300. * Get an animation by the provided name. Used mainly when playing n animation.
  301. * @param name the name of the animation to find
  302. */
  303. protected _getAnimationByName(name: string): Nullable<IModelAnimation> {
  304. // can't use .find, noe available on IE
  305. let filtered = this._animations.filter(a => a.name === name);
  306. // what the next line means - if two animations have the same name, they will not be returned!
  307. if (filtered.length === 1) {
  308. return filtered[0];
  309. } else {
  310. return null;
  311. }
  312. }
  313. /**
  314. * Choose an initialized animation using its name and start playing it
  315. * @param name the name of the animation to play
  316. * @returns The model aniamtion to be played.
  317. */
  318. public playAnimation(name: string): IModelAnimation {
  319. let animation = this.setCurrentAnimationByName(name);
  320. if (animation) {
  321. animation.start();
  322. }
  323. return animation;
  324. }
  325. public setCurrentAnimationByName(name: string) {
  326. let animation = this._getAnimationByName(name);
  327. if (animation) {
  328. if (this.currentAnimation && this.currentAnimation.state !== AnimationState.STOPPED) {
  329. this.currentAnimation.stop();
  330. }
  331. this.currentAnimation = animation;
  332. return animation;
  333. } else {
  334. throw new Error("animation not found - " + name);
  335. }
  336. }
  337. private _configureModel() {
  338. // this can be changed to the meshes that have rootMesh a parent without breaking anything.
  339. let meshesWithNoParent: Array<AbstractMesh> = [this.rootMesh] //this._meshes.filter(m => m.parent === this.rootMesh);
  340. let updateMeshesWithNoParent = (variable: string, value: any, param?: string) => {
  341. meshesWithNoParent.forEach(mesh => {
  342. if (param) {
  343. mesh[variable][param] = value;
  344. } else {
  345. mesh[variable] = value;
  346. }
  347. });
  348. }
  349. let updateXYZ = (variable: string, configValues: { x: number, y: number, z: number, w?: number }) => {
  350. if (configValues.x !== undefined) {
  351. updateMeshesWithNoParent(variable, configValues.x, 'x');
  352. }
  353. if (configValues.y !== undefined) {
  354. updateMeshesWithNoParent(variable, configValues.y, 'y');
  355. }
  356. if (configValues.z !== undefined) {
  357. updateMeshesWithNoParent(variable, configValues.z, 'z');
  358. }
  359. if (configValues.w !== undefined) {
  360. updateMeshesWithNoParent(variable, configValues.w, 'w');
  361. }
  362. }
  363. if (this._modelConfiguration.normalize) {
  364. let center = false;
  365. let unitSize = false;
  366. let parentIndex;
  367. if (this._modelConfiguration.normalize === true) {
  368. center = true;
  369. unitSize = true;
  370. } else {
  371. center = !!this._modelConfiguration.normalize.center;
  372. unitSize = !!this._modelConfiguration.normalize.unitSize;
  373. parentIndex = this._modelConfiguration.normalize.parentIndex;
  374. }
  375. let meshesToNormalize: Array<AbstractMesh> = [];
  376. if (parentIndex !== undefined) {
  377. meshesToNormalize.push(this._meshes[parentIndex]);
  378. } else {
  379. meshesToNormalize = this._pivotMesh.getChildMeshes(true).length === 1 ? [this._pivotMesh] : meshesWithNoParent;
  380. }
  381. if (unitSize) {
  382. meshesToNormalize.forEach(mesh => {
  383. mesh.normalizeToUnitCube(true);
  384. mesh.computeWorldMatrix(true);
  385. });
  386. }
  387. if (center) {
  388. meshesToNormalize.forEach(mesh => {
  389. const boundingInfo = mesh.getHierarchyBoundingVectors(true);
  390. const sizeVec = boundingInfo.max.subtract(boundingInfo.min);
  391. const halfSizeVec = sizeVec.scale(0.5);
  392. const center = boundingInfo.min.add(halfSizeVec);
  393. mesh.position = center.scale(-1);
  394. mesh.position.y += halfSizeVec.y;
  395. // Recompute Info.
  396. mesh.computeWorldMatrix(true);
  397. });
  398. }
  399. } else {
  400. // if centered, should be done here
  401. }
  402. // position?
  403. if (this._modelConfiguration.position) {
  404. updateXYZ('position', this._modelConfiguration.position);
  405. }
  406. if (this._modelConfiguration.rotation) {
  407. //quaternion?
  408. if (this._modelConfiguration.rotation.w) {
  409. meshesWithNoParent.forEach(mesh => {
  410. if (!mesh.rotationQuaternion) {
  411. mesh.rotationQuaternion = new Quaternion();
  412. }
  413. })
  414. updateXYZ('rotationQuaternion', this._modelConfiguration.rotation);
  415. } else {
  416. updateXYZ('rotation', this._modelConfiguration.rotation);
  417. }
  418. }
  419. if (this._modelConfiguration.rotationOffsetAxis) {
  420. let rotationAxis = new Vector3(0, 0, 0).copyFrom(this._modelConfiguration.rotationOffsetAxis as Vector3);
  421. meshesWithNoParent.forEach(m => {
  422. if (this._modelConfiguration.rotationOffsetAngle) {
  423. m.rotate(rotationAxis, this._modelConfiguration.rotationOffsetAngle);
  424. }
  425. });
  426. }
  427. if (this._modelConfiguration.scaling) {
  428. updateXYZ('scaling', this._modelConfiguration.scaling);
  429. }
  430. if (this._modelConfiguration.castShadow) {
  431. this._meshes.forEach(mesh => {
  432. Tags.AddTagsTo(mesh, 'castShadow');
  433. });
  434. }
  435. let meshes = this._pivotMesh.getChildMeshes(false);
  436. meshes.filter(m => m.material).forEach((mesh) => {
  437. this._applyModelMaterialConfiguration(mesh.material!);
  438. });
  439. if (this._modelConfiguration.entryAnimation) {
  440. this._entryAnimation = this._modelAnimationConfigurationToObject(this._modelConfiguration.entryAnimation);
  441. }
  442. if (this._modelConfiguration.exitAnimation) {
  443. this._exitAnimation = this._modelAnimationConfigurationToObject(this._modelConfiguration.exitAnimation);
  444. }
  445. this.onAfterConfigure.notifyObservers(this);
  446. }
  447. private _modelAnimationConfigurationToObject(animConfig: IModelAnimationConfiguration): ModelAnimationConfiguration {
  448. let anim: ModelAnimationConfiguration = {
  449. time: 0.5
  450. };
  451. if (animConfig.scaling) {
  452. anim.scaling = Vector3.Zero();
  453. }
  454. if (animConfig.easingFunction !== undefined) {
  455. anim.easingFunction = animConfig.easingFunction;
  456. }
  457. if (animConfig.easingMode !== undefined) {
  458. anim.easingMode = animConfig.easingMode;
  459. }
  460. extendClassWithConfig(anim, animConfig);
  461. return anim;
  462. }
  463. /**
  464. * Apply a material configuration to a material
  465. * @param material Material to apply configuration to
  466. */
  467. public _applyModelMaterialConfiguration(material: Material) {
  468. if (!this._modelConfiguration.material) return;
  469. extendClassWithConfig(material, this._modelConfiguration.material);
  470. if (material instanceof PBRMaterial) {
  471. if (this._modelConfiguration.material.directIntensity !== undefined) {
  472. material.directIntensity = this._modelConfiguration.material.directIntensity;
  473. }
  474. if (this._modelConfiguration.material.emissiveIntensity !== undefined) {
  475. material.emissiveIntensity = this._modelConfiguration.material.emissiveIntensity;
  476. }
  477. if (this._modelConfiguration.material.environmentIntensity !== undefined) {
  478. material.environmentIntensity = this._modelConfiguration.material.environmentIntensity;
  479. }
  480. if (this._modelConfiguration.material.directEnabled !== undefined) {
  481. material.disableLighting = !this._modelConfiguration.material.directEnabled;
  482. }
  483. if (this._configurationContainer && this._configurationContainer.reflectionColor) {
  484. material.reflectionColor = this._configurationContainer.reflectionColor;
  485. }
  486. }
  487. else if (material instanceof MultiMaterial) {
  488. for (let i = 0; i < material.subMaterials.length; i++) {
  489. const subMaterial = material.subMaterials[i];
  490. if (subMaterial) {
  491. this._applyModelMaterialConfiguration(subMaterial);
  492. }
  493. }
  494. }
  495. }
  496. /**
  497. * Start entry/exit animation given an animation configuration
  498. * @param animationConfiguration Entry/Exit animation configuration
  499. * @param isEntry Pass true if the animation is an entry animation
  500. * @param completeCallback Callback to execute when the animation completes
  501. */
  502. private _applyAnimation(animationConfiguration: ModelAnimationConfiguration, isEntry: boolean, completeCallback?: () => void) {
  503. let animations: Animation[] = [];
  504. //scale
  505. if (animationConfiguration.scaling) {
  506. let scaleStart: Vector3 = isEntry ? animationConfiguration.scaling : new Vector3(1, 1, 1);
  507. let scaleEnd: Vector3 = isEntry ? new Vector3(1, 1, 1) : animationConfiguration.scaling;
  508. if (!scaleStart.equals(scaleEnd)) {
  509. this.rootMesh.scaling = scaleStart;
  510. this._setLinearKeys(
  511. this._scaleTransition,
  512. this.rootMesh.scaling,
  513. scaleEnd,
  514. animationConfiguration.time
  515. );
  516. animations.push(this._scaleTransition);
  517. }
  518. }
  519. //Start the animation(s)
  520. this.transitionTo(
  521. animations,
  522. animationConfiguration.time,
  523. this._createEasingFunction(animationConfiguration.easingFunction),
  524. animationConfiguration.easingMode,
  525. () => { if (completeCallback) completeCallback(); }
  526. );
  527. }
  528. /**
  529. * Begin @animations with the specified @easingFunction
  530. * @param animations The BABYLON Animations to begin
  531. * @param duration of transition, in seconds
  532. * @param easingFunction An easing function to apply
  533. * @param easingMode A easing mode to apply to the easingFunction
  534. * @param onAnimationEnd Call back trigger at the end of the animation.
  535. */
  536. public transitionTo(
  537. animations: Animation[],
  538. duration: number,
  539. easingFunction: any,
  540. easingMode: number = BABYLON.EasingFunction.EASINGMODE_EASEINOUT,
  541. onAnimationEnd: () => void): void {
  542. if (easingFunction) {
  543. for (let animation of animations) {
  544. easingFunction.setEasingMode(easingMode);
  545. animation.setEasingFunction(easingFunction);
  546. }
  547. }
  548. //Stop any current animations before starting the new one - merging not yet supported.
  549. this.stopAllAnimations();
  550. this.rootMesh.animations = animations;
  551. if (this.rootMesh.getScene().beginAnimation) {
  552. let animatable: Animatable = this.rootMesh.getScene().beginAnimation(this.rootMesh, 0, this._frameRate * duration, false, 1, () => {
  553. if (onAnimationEnd) {
  554. onAnimationEnd();
  555. }
  556. });
  557. this._animatables.push(animatable);
  558. }
  559. }
  560. /**
  561. * Sets key values on an Animation from first to last frame.
  562. * @param animation The Babylon animation object to set keys on
  563. * @param startValue The value of the first key
  564. * @param endValue The value of the last key
  565. * @param duration The duration of the animation, used to determine the end frame
  566. */
  567. private _setLinearKeys(animation: Animation, startValue: any, endValue: any, duration: number) {
  568. animation.setKeys([
  569. {
  570. frame: 0,
  571. value: startValue
  572. },
  573. {
  574. frame: this._frameRate * duration,
  575. value: endValue
  576. }
  577. ]);
  578. }
  579. /**
  580. * Creates and returns a Babylon easing funtion object based on a string representing the Easing function
  581. * @param easingFunctionID The enum of the easing funtion to create
  582. * @return The newly created Babylon easing function object
  583. */
  584. private _createEasingFunction(easingFunctionID?: number): any {
  585. let easingFunction;
  586. switch (easingFunctionID) {
  587. case EasingFunction.CircleEase:
  588. easingFunction = new CircleEase();
  589. break;
  590. case EasingFunction.BackEase:
  591. easingFunction = new BackEase(0.3);
  592. break;
  593. case EasingFunction.BounceEase:
  594. easingFunction = new BounceEase();
  595. break;
  596. case EasingFunction.CubicEase:
  597. easingFunction = new CubicEase();
  598. break;
  599. case EasingFunction.ElasticEase:
  600. easingFunction = new ElasticEase();
  601. break;
  602. case EasingFunction.ExponentialEase:
  603. easingFunction = new ExponentialEase();
  604. break;
  605. case EasingFunction.PowerEase:
  606. easingFunction = new PowerEase();
  607. break;
  608. case EasingFunction.QuadraticEase:
  609. easingFunction = new QuadraticEase();
  610. break;
  611. case EasingFunction.QuarticEase:
  612. easingFunction = new QuarticEase();
  613. break;
  614. case EasingFunction.QuinticEase:
  615. easingFunction = new QuinticEase();
  616. break;
  617. case EasingFunction.SineEase:
  618. easingFunction = new SineEase();
  619. break;
  620. default:
  621. Tools.Log("No ease function found");
  622. break;
  623. }
  624. return easingFunction;
  625. }
  626. /**
  627. * Stops and removes all animations that have been applied to the model
  628. */
  629. public stopAllAnimations(): void {
  630. if (this.rootMesh) {
  631. this.rootMesh.animations = [];
  632. }
  633. if (this.currentAnimation) {
  634. this.currentAnimation.stop();
  635. }
  636. while (this._animatables.length) {
  637. this._animatables[0].onAnimationEnd = null;
  638. this._animatables[0].stop();
  639. this._animatables.shift();
  640. }
  641. }
  642. /**
  643. * Will remove this model from the viewer (but NOT dispose it).
  644. */
  645. public remove() {
  646. this.stopAllAnimations();
  647. // hide it
  648. this.rootMesh.isVisible = false;
  649. if (this._observablesManager) { this._observablesManager.onModelRemovedObservable.notifyObservers(this); }
  650. }
  651. /**
  652. * Dispose this model, including all of its associated assets.
  653. */
  654. public dispose() {
  655. this.remove();
  656. this.onAfterConfigure.clear();
  657. this.onLoadedObservable.clear();
  658. this.onLoadErrorObservable.clear();
  659. this.onLoadProgressObservable.clear();
  660. if (this.loader && this.loader.name === "gltf") {
  661. (<GLTFFileLoader>this.loader).dispose();
  662. }
  663. this.particleSystems.forEach(ps => ps.dispose());
  664. this.particleSystems.length = 0;
  665. this.skeletons.forEach(s => s.dispose());
  666. this.skeletons.length = 0;
  667. this._animations.forEach(ag => ag.dispose());
  668. this._animations.length = 0;
  669. this.rootMesh.dispose(false, true);
  670. }
  671. }