viewer.ts 30 KB

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