viewerModel.ts 28 KB

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