viewer.ts 30 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776
  1. import { viewerManager } from './viewerManager';
  2. import { SceneManager } from '../managers/sceneManager';
  3. import { ConfigurationLoader } from '../configuration/loader';
  4. import { Effect, Observable, Engine, Scene, Database, SceneLoaderProgressEvent, ISceneLoaderPlugin, ISceneLoaderPluginAsync, Tools, RenderingManager, TargetCamera, WebVRFreeCamera, Vector3 } from 'babylonjs';
  5. import { ViewerConfiguration, IObserversConfiguration, IModelConfiguration } from '../configuration/';
  6. import { ViewerModel } from '../model/viewerModel';
  7. import { ModelLoader } from '../loader/modelLoader';
  8. import { viewerGlobals } from '../configuration/globals';
  9. import { telemetryManager } from '../managers/telemetryManager';
  10. import { deepmerge } from '../helper/';
  11. import { ObservablesManager } from '../managers/observablesManager';
  12. import { ConfigurationContainer } from '../configuration/configurationContainer';
  13. import { TemplateManager } from '../templating/templateManager';
  14. /**
  15. * The AbstractViewr is the center of Babylon's viewer.
  16. * It is the basic implementation of the default viewer and is responsible of loading and showing the model and the templates
  17. */
  18. export abstract class AbstractViewer {
  19. /**
  20. * The corresponsing template manager of this viewer.
  21. */
  22. public templateManager: TemplateManager;
  23. // TODO get the template manager to the default viewer, if no one is extending the abstract viewer
  24. /**
  25. * Babylon Engine corresponding with this viewer
  26. */
  27. public engine: Engine;
  28. /**
  29. * The ID of this viewer. it will be generated randomly or use the HTML Element's ID.
  30. */
  31. public readonly baseId: string;
  32. /**
  33. * The last loader used to load a model.
  34. * @deprecated
  35. */
  36. public lastUsedLoader: ISceneLoaderPlugin | ISceneLoaderPluginAsync;
  37. /**
  38. * The ModelLoader instance connected with this viewer.
  39. */
  40. public modelLoader: ModelLoader;
  41. /**
  42. * A flag that controls whether or not the render loop should be executed
  43. */
  44. public runRenderLoop: boolean = true;
  45. /**
  46. * The scene manager connected with this viewer instance
  47. */
  48. public sceneManager: SceneManager;
  49. // observables
  50. /**
  51. * Will notify when the scene was initialized
  52. */
  53. public get onSceneInitObservable(): Observable<Scene> {
  54. return this.observablesManager.onSceneInitObservable;
  55. }
  56. /**
  57. * will notify when the engine was initialized
  58. */
  59. public get onEngineInitObservable(): Observable<Engine> {
  60. return this.observablesManager.onEngineInitObservable;
  61. }
  62. /**
  63. * Will notify when a new model was added to the scene.
  64. * Note that added does not neccessarily mean loaded!
  65. */
  66. public get onModelAddedObservable(): Observable<ViewerModel> {
  67. return this.observablesManager.onModelAddedObservable;
  68. }
  69. /**
  70. * will notify after every model load
  71. */
  72. public get onModelLoadedObservable(): Observable<ViewerModel> {
  73. return this.observablesManager.onModelLoadedObservable;
  74. }
  75. /**
  76. * will notify when any model notify of progress
  77. */
  78. public get onModelLoadProgressObservable(): Observable<SceneLoaderProgressEvent> {
  79. return this.observablesManager.onModelLoadProgressObservable;
  80. }
  81. /**
  82. * will notify when any model load failed.
  83. */
  84. public get onModelLoadErrorObservable(): Observable<{ message: string; exception: any }> {
  85. return this.observablesManager.onModelLoadErrorObservable;
  86. }
  87. /**
  88. * Will notify when a model was removed from the scene;
  89. */
  90. public get onModelRemovedObservable(): Observable<ViewerModel> {
  91. return this.observablesManager.onModelRemovedObservable;
  92. }
  93. /**
  94. * will notify when a new loader was initialized.
  95. * Used mainly to know when a model starts loading.
  96. */
  97. public get onLoaderInitObservable(): Observable<ISceneLoaderPlugin | ISceneLoaderPluginAsync> {
  98. return this.observablesManager.onLoaderInitObservable;
  99. }
  100. /**
  101. * Observers registered here will be executed when the entire load process has finished.
  102. */
  103. public get onInitDoneObservable(): Observable<AbstractViewer> {
  104. return this.observablesManager.onViewerInitDoneObservable;
  105. }
  106. /**
  107. * Functions added to this observable will be executed on each frame rendered.
  108. */
  109. public get onFrameRenderedObservable(): Observable<AbstractViewer> {
  110. return this.observablesManager.onFrameRenderedObservable;
  111. }
  112. public observablesManager: ObservablesManager;
  113. /**
  114. * The canvas associated with this viewer
  115. */
  116. protected _canvas: HTMLCanvasElement;
  117. /**
  118. * The (single) canvas of this viewer
  119. */
  120. public get canvas(): HTMLCanvasElement {
  121. return this._canvas;
  122. }
  123. /**
  124. * is this viewer disposed?
  125. */
  126. protected _isDisposed: boolean = false;
  127. /**
  128. * registered onBeforeRender functions.
  129. * This functions are also registered at the native scene. The reference can be used to unregister them.
  130. */
  131. protected _registeredOnBeforeRenderFunctions: Array<() => void>;
  132. /**
  133. * The configuration loader of this viewer
  134. */
  135. protected _configurationLoader: ConfigurationLoader;
  136. /**
  137. * Is the viewer already initialized. for internal use.
  138. */
  139. protected _isInit: boolean;
  140. protected _configurationContainer: ConfigurationContainer;
  141. public get configurationContainer() {
  142. return this._configurationContainer;
  143. }
  144. constructor(public containerElement: HTMLElement, initialConfiguration: ViewerConfiguration = {}) {
  145. // if exists, use the container id. otherwise, generate a random string.
  146. if (containerElement.id) {
  147. this.baseId = containerElement.id;
  148. } else {
  149. this.baseId = containerElement.id = 'bjs' + Math.random().toString(32).substr(2, 8);
  150. }
  151. this._registeredOnBeforeRenderFunctions = [];
  152. this._configurationContainer = new ConfigurationContainer();
  153. // add this viewer to the viewer manager
  154. viewerManager.addViewer(this);
  155. this.observablesManager = new ObservablesManager();
  156. this.modelLoader = new ModelLoader(this.observablesManager, this._configurationContainer);
  157. RenderingManager.AUTOCLEAR = false;
  158. // extend the configuration
  159. this._configurationLoader = new ConfigurationLoader();
  160. this._configurationLoader.loadConfiguration(initialConfiguration, (configuration) => {
  161. this._onConfigurationLoaded(configuration);
  162. });
  163. this.onSceneInitObservable.add(() => {
  164. this.updateConfiguration();
  165. });
  166. this.onInitDoneObservable.add(() => {
  167. this._isInit = true;
  168. this.engine.runRenderLoop(this._render);
  169. });
  170. this._prepareContainerElement();
  171. }
  172. /**
  173. * get the baseId of this viewer
  174. */
  175. public getBaseId(): string {
  176. return this.baseId;
  177. }
  178. /**
  179. * Do we have a canvas to render on, and is it a part of the scene
  180. */
  181. public isCanvasInDOM(): boolean {
  182. return !!this._canvas && !!this._canvas.parentElement;
  183. }
  184. /**
  185. * Is the engine currently set to rende even when the page is in background
  186. */
  187. public get renderInBackground() {
  188. return this.engine && this.engine.renderEvenInBackground;
  189. }
  190. /**
  191. * Set the viewer's background rendering flag.
  192. */
  193. public set renderInBackground(value: boolean) {
  194. if (this.engine) {
  195. this.engine.renderEvenInBackground = value;
  196. }
  197. }
  198. /**
  199. * Get the configuration object. This is a reference only.
  200. * The configuration can ONLY be updated using the updateConfiguration function.
  201. * changing this object will have no direct effect on the scene.
  202. */
  203. public get configuration(): ViewerConfiguration {
  204. return this._configurationContainer.configuration;
  205. }
  206. /**
  207. * force resizing the engine.
  208. */
  209. public forceResize() {
  210. this._resize();
  211. }
  212. protected _hdToggled: boolean = false;
  213. public toggleHD() {
  214. this._hdToggled = !this._hdToggled;
  215. var scale = this._hdToggled ? Math.max(0.5, 1 / (window.devicePixelRatio || 2)) : 1;
  216. this.engine.setHardwareScalingLevel(scale);
  217. }
  218. protected _vrToggled: boolean = false;
  219. private _vrModelRepositioning: number = 0;
  220. protected _vrScale: number = 1;
  221. public toggleVR() {
  222. this._vrToggled = !this._vrToggled;
  223. if (this._vrToggled && this.sceneManager.vrHelper) {
  224. // make sure the floor is set
  225. if (this.sceneManager.environmentHelper && this.sceneManager.environmentHelper.ground) {
  226. this.sceneManager.vrHelper.addFloorMesh(this.sceneManager.environmentHelper.ground);
  227. }
  228. this.sceneManager.vrHelper.enterVR();
  229. // calculate position and vr scale
  230. if (this.sceneManager.environmentHelper) {
  231. this.sceneManager.environmentHelper.ground && this.sceneManager.environmentHelper.ground.scaling.scaleInPlace(this._vrScale);
  232. this.sceneManager.environmentHelper.skybox && this.sceneManager.environmentHelper.skybox.scaling.scaleInPlace(this._vrScale);
  233. }
  234. // position the vr camera to be in front of the object
  235. if (this.sceneManager.vrHelper.currentVRCamera) {
  236. if (this.configuration.vr && this.configuration.vr.cameraPosition !== undefined) {
  237. this.sceneManager.vrHelper.currentVRCamera.position.copyFrom(this.configuration.vr.cameraPosition as Vector3);
  238. } else {
  239. this.sceneManager.vrHelper.currentVRCamera.position.copyFromFloats(0, this.sceneManager.vrHelper.currentVRCamera.position.y, -1);
  240. }
  241. (<TargetCamera>this.sceneManager.vrHelper.currentVRCamera).rotationQuaternion && (<TargetCamera>this.sceneManager.vrHelper.currentVRCamera).rotationQuaternion.copyFromFloats(0, 0, 0, 1);
  242. if (this.configuration.vr && this.configuration.vr.modelHeightCorrection !== undefined) {
  243. if (typeof this.configuration.vr.modelHeightCorrection === 'number') {
  244. this._vrModelRepositioning = this.configuration.vr.modelHeightCorrection
  245. } else if (this.configuration.vr.modelHeightCorrection) {
  246. this._vrModelRepositioning = this.sceneManager.vrHelper.currentVRCamera.position.y / 2;
  247. } else {
  248. this._vrModelRepositioning = 0;
  249. }
  250. }
  251. } else {
  252. this._vrModelRepositioning = 0;
  253. }
  254. if (this.sceneManager.models.length) {
  255. let boundingVectors = this.sceneManager.models[0].rootMesh.getHierarchyBoundingVectors();
  256. let sizeVec = boundingVectors.max.subtract(boundingVectors.min);
  257. let maxDimension = Math.max(sizeVec.x, sizeVec.y, sizeVec.z);
  258. this._vrScale = (1 / maxDimension);
  259. if (this.configuration.vr && this.configuration.vr.objectScaleFactor) {
  260. this._vrScale *= this.configuration.vr.objectScaleFactor;
  261. }
  262. this.sceneManager.models[0].rootMesh.scaling.scaleInPlace(this._vrScale);
  263. // reposition the object to "float" in front of the user
  264. this.sceneManager.models[0].rootMesh.position.y += this._vrModelRepositioning;
  265. this.sceneManager.models[0].rootMesh.rotationQuaternion = null;
  266. }
  267. // post processing
  268. if (this.sceneManager.defaultRenderingPipelineEnabled && this.sceneManager.defaultRenderingPipeline) {
  269. this.sceneManager.defaultRenderingPipeline.imageProcessingEnabled = false;
  270. this.sceneManager.defaultRenderingPipeline.prepare();
  271. }
  272. } else {
  273. if (this.sceneManager.vrHelper) {
  274. this.sceneManager.vrHelper.exitVR();
  275. //this.sceneManager.scene.activeCamera = this.sceneManager.camera;
  276. if (this.sceneManager.models.length) {
  277. this.sceneManager.models[0].rootMesh.scaling.scaleInPlace(1 / this._vrScale);
  278. this.sceneManager.models[0].rootMesh.position.y -= this._vrModelRepositioning;
  279. }
  280. if (this.sceneManager.environmentHelper) {
  281. this.sceneManager.environmentHelper.ground && this.sceneManager.environmentHelper.ground.scaling.scaleInPlace(1 / this._vrScale);
  282. this.sceneManager.environmentHelper.skybox && this.sceneManager.environmentHelper.skybox.scaling.scaleInPlace(1 / this._vrScale);
  283. }
  284. // post processing
  285. if (this.sceneManager.defaultRenderingPipelineEnabled && this.sceneManager.defaultRenderingPipeline) {
  286. this.sceneManager.defaultRenderingPipeline.imageProcessingEnabled = true;
  287. this.sceneManager.defaultRenderingPipeline.prepare();
  288. }
  289. }
  290. }
  291. }
  292. /**
  293. * The resize function that will be registered with the window object
  294. */
  295. protected _resize = (): void => {
  296. // Only resize if Canvas is in the DOM
  297. if (!this.isCanvasInDOM()) {
  298. return;
  299. }
  300. if (this.canvas.clientWidth <= 0 || this.canvas.clientHeight <= 0) {
  301. return;
  302. }
  303. if (this.configuration.engine && this.configuration.engine.disableResize) {
  304. return;
  305. }
  306. this.engine.resize();
  307. }
  308. protected _onConfigurationLoaded(configuration: ViewerConfiguration) {
  309. this._configurationContainer.configuration = deepmerge(this.configuration || {}, configuration);
  310. if (this.configuration.observers) {
  311. this._configureObservers(this.configuration.observers);
  312. }
  313. // TODO remove this after testing, as this is done in the updateConfiguration as well.
  314. if (this.configuration.loaderPlugins) {
  315. Object.keys(this.configuration.loaderPlugins).forEach((name => {
  316. if (this.configuration.loaderPlugins && this.configuration.loaderPlugins[name]) {
  317. this.modelLoader.addPlugin(name);
  318. }
  319. }))
  320. }
  321. this.templateManager = new TemplateManager(this.containerElement);
  322. this.observablesManager.onViewerInitStartedObservable.notifyObservers(this);
  323. }
  324. /**
  325. * Force a single render loop execution.
  326. */
  327. public forceRender() {
  328. this._render(true);
  329. }
  330. /**
  331. * render loop that will be executed by the engine
  332. */
  333. protected _render = (force: boolean = false): void => {
  334. if (force || (this.sceneManager.scene && this.sceneManager.scene.activeCamera)) {
  335. if (this.runRenderLoop || force) {
  336. this.engine.performanceMonitor.enable();
  337. this.sceneManager.scene.render();
  338. this.onFrameRenderedObservable.notifyObservers(this);
  339. } else {
  340. this.engine.performanceMonitor.disable();
  341. // update camera instead of rendering
  342. this.sceneManager.scene.activeCamera && this.sceneManager.scene.activeCamera.update();
  343. }
  344. }
  345. }
  346. /**
  347. * Takes a screenshot of the scene and returns it as a base64 encoded png.
  348. * @param callback optional callback that will be triggered when screenshot is done.
  349. * @param width Optional screenshot width (default to 512).
  350. * @param height Optional screenshot height (default to 512).
  351. * @returns a promise with the screenshot data
  352. */
  353. public takeScreenshot(callback?: (data: string) => void, width = 0, height = 0): Promise<string> {
  354. width = width || this.canvas.clientWidth;
  355. height = height || this.canvas.clientHeight;
  356. // Create the screenshot
  357. return new Promise<string>((resolve, reject) => {
  358. try {
  359. BABYLON.Tools.CreateScreenshot(this.engine, this.sceneManager.camera, { width, height }, (data) => {
  360. if (callback) {
  361. callback(data);
  362. }
  363. resolve(data);
  364. });
  365. } catch (e) {
  366. reject(e);
  367. }
  368. });
  369. }
  370. /**
  371. * Update the current viewer configuration with new values.
  372. * Only provided information will be updated, old configuration values will be kept.
  373. * If this.configuration was manually changed, you can trigger this function with no parameters,
  374. * and the entire configuration will be updated.
  375. * @param newConfiguration the partial configuration to update or a URL to a JSON holding the updated configuration
  376. *
  377. */
  378. public updateConfiguration(newConfiguration: Partial<ViewerConfiguration> | string = this.configuration) {
  379. if (typeof newConfiguration === "string") {
  380. Tools.LoadFile(newConfiguration, (data) => {
  381. try {
  382. const newData = JSON.parse(data.toString()) as ViewerConfiguration;
  383. return this.updateConfiguration(newData);
  384. } catch (e) {
  385. console.log("Error parsing file " + newConfiguration);
  386. }
  387. }, undefined, undefined, undefined, (error) => {
  388. console.log("Error parsing file " + newConfiguration, error);
  389. });
  390. } else {
  391. // update this.configuration with the new data
  392. this._configurationContainer.configuration = deepmerge(this.configuration || {}, newConfiguration);
  393. this.sceneManager.updateConfiguration(newConfiguration);
  394. // observers in configuration
  395. if (newConfiguration.observers) {
  396. this._configureObservers(newConfiguration.observers);
  397. }
  398. if (newConfiguration.loaderPlugins) {
  399. Object.keys(newConfiguration.loaderPlugins).forEach((name => {
  400. if (newConfiguration.loaderPlugins && newConfiguration.loaderPlugins[name]) {
  401. this.modelLoader.addPlugin(name);
  402. }
  403. }));
  404. }
  405. }
  406. }
  407. /**
  408. * this is used to register native functions using the configuration object.
  409. * This will configure the observers.
  410. * @param observersConfiguration observers configuration
  411. */
  412. protected _configureObservers(observersConfiguration: IObserversConfiguration) {
  413. if (observersConfiguration.onEngineInit) {
  414. this.onEngineInitObservable.add(window[observersConfiguration.onEngineInit]);
  415. } else {
  416. if (observersConfiguration.onEngineInit === '' && this.configuration.observers && this.configuration.observers!.onEngineInit) {
  417. this.onEngineInitObservable.removeCallback(window[this.configuration.observers!.onEngineInit!]);
  418. }
  419. }
  420. if (observersConfiguration.onSceneInit) {
  421. this.onSceneInitObservable.add(window[observersConfiguration.onSceneInit]);
  422. } else {
  423. if (observersConfiguration.onSceneInit === '' && this.configuration.observers && this.configuration.observers!.onSceneInit) {
  424. this.onSceneInitObservable.removeCallback(window[this.configuration.observers!.onSceneInit!]);
  425. }
  426. }
  427. if (observersConfiguration.onModelLoaded) {
  428. this.onModelLoadedObservable.add(window[observersConfiguration.onModelLoaded]);
  429. } else {
  430. if (observersConfiguration.onModelLoaded === '' && this.configuration.observers && this.configuration.observers!.onModelLoaded) {
  431. this.onModelLoadedObservable.removeCallback(window[this.configuration.observers!.onModelLoaded!]);
  432. }
  433. }
  434. }
  435. /**
  436. * Dispoe the entire viewer including the scene and the engine
  437. */
  438. public dispose() {
  439. if (this._isDisposed) {
  440. return;
  441. }
  442. window.removeEventListener('resize', this._resize);
  443. if (this.sceneManager) {
  444. if (this.sceneManager.scene && this.sceneManager.scene.activeCamera) {
  445. this.sceneManager.scene.activeCamera.detachControl(this.canvas);
  446. }
  447. this.sceneManager.dispose();
  448. }
  449. this._fpsTimeoutInterval && clearInterval(this._fpsTimeoutInterval);
  450. this.observablesManager.dispose();
  451. this.modelLoader.dispose();
  452. if (this.engine) {
  453. this.engine.dispose();
  454. }
  455. viewerManager.removeViewer(this);
  456. this._isDisposed = true;
  457. }
  458. /**
  459. * This will prepare the container element for the viewer
  460. */
  461. protected abstract _prepareContainerElement();
  462. /**
  463. * This function will execute when the HTML templates finished initializing.
  464. * It should initialize the engine and continue execution.
  465. *
  466. * @returns {Promise<AbstractViewer>} The viewer object will be returned after the object was loaded.
  467. */
  468. protected _onTemplatesLoaded(): Promise<AbstractViewer> {
  469. return Promise.resolve(this);
  470. }
  471. /**
  472. * This will force the creation of an engine and a scene.
  473. * It will also load a model if preconfigured.
  474. * But first - it will load the extendible onTemplateLoaded()!
  475. */
  476. protected _onTemplateLoaded(): Promise<AbstractViewer> {
  477. // check if viewer was disposed right after created
  478. if (this._isDisposed) {
  479. return Promise.reject("viewer was disposed");
  480. }
  481. return this._onTemplatesLoaded().then(() => {
  482. let autoLoad = typeof this.configuration.model === 'string' || (this.configuration.model && this.configuration.model.url);
  483. return this._initEngine().then((engine) => {
  484. return this.onEngineInitObservable.notifyObserversWithPromise(engine);
  485. }).then(() => {
  486. this._initTelemetryEvents();
  487. if (autoLoad) {
  488. return this.loadModel(this.configuration.model!).catch(() => { }).then(() => { return this.sceneManager.scene });
  489. } else {
  490. return this.sceneManager.scene || this.sceneManager.initScene(this.configuration.scene);
  491. }
  492. }).then(() => {
  493. return this.onInitDoneObservable.notifyObserversWithPromise(this);
  494. }).catch(e => {
  495. Tools.Warn(e.toString());
  496. return this;
  497. });
  498. })
  499. }
  500. /**
  501. * Initialize the engine. Retruns a promise in case async calls are needed.
  502. *
  503. * @protected
  504. * @returns {Promise<Engine>}
  505. * @memberof Viewer
  506. */
  507. protected _initEngine(): Promise<Engine> {
  508. // init custom shaders
  509. this._injectCustomShaders();
  510. //let canvasElement = this.templateManager.getCanvas();
  511. if (!this.canvas) {
  512. return Promise.reject('Canvas element not found!');
  513. }
  514. let config = this.configuration.engine || {};
  515. // TDO enable further configuration
  516. // check for webgl2 support, force-disable if needed.
  517. if (viewerGlobals.disableWebGL2Support) {
  518. config.engineOptions = config.engineOptions || {};
  519. config.engineOptions.disableWebGL2Support = true;
  520. }
  521. this.engine = new Engine(this.canvas, !!config.antialiasing, config.engineOptions);
  522. // Disable manifest checking
  523. Database.IDBStorageEnabled = false;
  524. if (!config.disableResize) {
  525. window.addEventListener('resize', this._resize);
  526. }
  527. if (this.configuration.engine) {
  528. if (this.configuration.engine.adaptiveQuality) {
  529. var scale = Math.max(0.5, 1 / (window.devicePixelRatio || 2));
  530. this.engine.setHardwareScalingLevel(scale);
  531. }
  532. if (this.configuration.engine.hdEnabled) {
  533. this.toggleHD();
  534. }
  535. }
  536. // create a new template manager for this viewer
  537. this.sceneManager = new SceneManager(this.engine, this._configurationContainer, this.observablesManager);
  538. return Promise.resolve(this.engine);
  539. }
  540. private _isLoading: boolean;
  541. /**
  542. * Initialize a model loading. The returned object (a ViewerModel object) will be loaded in the background.
  543. * The difference between this and loadModel is that loadModel will fulfill the promise when the model finished loading.
  544. *
  545. * @param modelConfig model configuration to use when loading the model.
  546. * @param clearScene should the scene be cleared before loading this model
  547. * @returns a ViewerModel object that is not yet fully loaded.
  548. */
  549. public initModel(modelConfig: string | File | IModelConfiguration, clearScene: boolean = true): ViewerModel {
  550. let configuration: IModelConfiguration;
  551. if (typeof modelConfig === 'string') {
  552. configuration = {
  553. url: modelConfig
  554. }
  555. } else if (modelConfig instanceof File) {
  556. configuration = {
  557. file: modelConfig,
  558. root: "file:"
  559. }
  560. } else {
  561. configuration = modelConfig
  562. }
  563. if (!configuration.url && !configuration.file) {
  564. throw new Error("no model provided");
  565. }
  566. if (clearScene) {
  567. this.sceneManager.clearScene(true, false);
  568. }
  569. //merge the configuration for future models:
  570. if (this.configuration.model && typeof this.configuration.model === 'object') {
  571. let globalConfig = deepmerge({}, this.configuration.model)
  572. configuration = deepmerge(globalConfig, configuration);
  573. if (modelConfig instanceof File) {
  574. configuration.file = modelConfig;
  575. }
  576. } else {
  577. this.configuration.model = configuration;
  578. }
  579. this._isLoading = true;
  580. let model = this.modelLoader.load(configuration);
  581. this.lastUsedLoader = model.loader;
  582. model.onLoadErrorObservable.add((errorObject) => {
  583. this.onModelLoadErrorObservable.notifyObserversWithPromise(errorObject);
  584. });
  585. model.onLoadProgressObservable.add((progressEvent) => {
  586. this.onModelLoadProgressObservable.notifyObserversWithPromise(progressEvent);
  587. });
  588. this.onLoaderInitObservable.notifyObserversWithPromise(this.lastUsedLoader);
  589. model.onLoadedObservable.add(() => {
  590. this._isLoading = false;
  591. });
  592. return model;
  593. }
  594. /**
  595. * load a model using the provided configuration.
  596. * This function, as opposed to initModel, will return a promise that resolves when the model is loaded, and rejects with error.
  597. * If you want to attach to the observables of the model, use initModle instead.
  598. *
  599. * @param modelConfig the model configuration or URL to load.
  600. * @param clearScene Should the scene be cleared before loading the model
  601. * @returns a Promise the fulfills when the model finished loading successfully.
  602. */
  603. public loadModel(modelConfig: string | File | IModelConfiguration, clearScene: boolean = true): Promise<ViewerModel> {
  604. if (this._isLoading) {
  605. // We can decide here whether or not to cancel the lst load, but the developer can do that.
  606. return Promise.reject("another model is curently being loaded.");
  607. }
  608. return Promise.resolve(this.sceneManager.scene).then((scene) => {
  609. if (!scene) return this.sceneManager.initScene(this.configuration.scene, this.configuration.optimizer);
  610. return scene;
  611. }).then(() => {
  612. let model = this.initModel(modelConfig, clearScene);
  613. return new Promise<ViewerModel>((resolve, reject) => {
  614. // at this point, configuration.model is an object, not a string
  615. model.onLoadedObservable.add(() => {
  616. resolve(model);
  617. });
  618. model.onLoadErrorObservable.add((error) => {
  619. reject(error);
  620. });
  621. });
  622. })
  623. }
  624. private _fpsTimeoutInterval: number;
  625. protected _initTelemetryEvents() {
  626. telemetryManager.broadcast("Engine Capabilities", this.baseId, this.engine.getCaps());
  627. telemetryManager.broadcast("Platform Details", this.baseId, {
  628. userAgent: navigator.userAgent,
  629. platform: navigator.platform
  630. });
  631. telemetryManager.flushWebGLErrors(this.engine, this.baseId);
  632. let trackFPS: Function = () => {
  633. telemetryManager.broadcast("Current FPS", this.baseId, { fps: this.engine.getFps() });
  634. };
  635. trackFPS();
  636. // Track the FPS again after 60 seconds
  637. this._fpsTimeoutInterval = window.setInterval(trackFPS, 60 * 1000);
  638. }
  639. /**
  640. * Injects all the spectre shader in the babylon shader store
  641. */
  642. protected _injectCustomShaders(): void {
  643. let customShaders = this.configuration.customShaders;
  644. // Inject all the spectre shader in the babylon shader store.
  645. if (!customShaders) {
  646. return;
  647. }
  648. if (customShaders.shaders) {
  649. Object.keys(customShaders.shaders).forEach(key => {
  650. // typescript considers a callback "unsafe", so... '!'
  651. Effect.ShadersStore[key] = customShaders!.shaders![key];
  652. });
  653. }
  654. if (customShaders.includes) {
  655. Object.keys(customShaders.includes).forEach(key => {
  656. // typescript considers a callback "unsafe", so... '!'
  657. Effect.IncludesShadersStore[key] = customShaders!.includes![key];
  658. });
  659. }
  660. }
  661. }