viewerModel.ts 28 KB

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