viewer.ts 34 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833
  1. import { viewerManager } from './viewerManager';
  2. import { TemplateManager } from './../templateManager';
  3. import configurationLoader from './../configuration/loader';
  4. import { CubeTexture, Color3, IEnvironmentHelperOptions, EnvironmentHelper, Effect, SceneOptimizer, SceneOptimizerOptions, Observable, Engine, Scene, ArcRotateCamera, Vector3, SceneLoader, AbstractMesh, Mesh, HemisphericLight, Database, SceneLoaderProgressEvent, ISceneLoaderPlugin, ISceneLoaderPluginAsync, Quaternion, Light, ShadowLight, ShadowGenerator, Tags, AutoRotationBehavior, BouncingBehavior, FramingBehavior, Behavior } from 'babylonjs';
  5. import { ViewerConfiguration, ISceneConfiguration, ISceneOptimizerConfiguration, IObserversConfiguration, IModelConfiguration, ISkyboxConfiguration, IGroundConfiguration, ILightConfiguration, ICameraConfiguration } from '../configuration/configuration';
  6. import * as deepmerge from '../../assets/deepmerge.min.js';
  7. import { CameraBehavior } from 'src/interfaces';
  8. export abstract class AbstractViewer {
  9. public templateManager: TemplateManager;
  10. public engine: Engine;
  11. public scene: Scene;
  12. public camera: ArcRotateCamera;
  13. public sceneOptimizer: SceneOptimizer;
  14. public baseId: string;
  15. /**
  16. * The last loader used to load a model.
  17. *
  18. * @type {(ISceneLoaderPlugin | ISceneLoaderPluginAsync)}
  19. * @memberof AbstractViewer
  20. */
  21. public lastUsedLoader: ISceneLoaderPlugin | ISceneLoaderPluginAsync;
  22. protected configuration: ViewerConfiguration;
  23. protected environmentHelper: EnvironmentHelper;
  24. protected defaultHighpTextureType: number;
  25. protected shadowGeneratorBias: number;
  26. protected defaultPipelineTextureType: number;
  27. protected maxShadows: number;
  28. // observables
  29. public onSceneInitObservable: Observable<Scene>;
  30. public onEngineInitObservable: Observable<Engine>;
  31. public onModelLoadedObservable: Observable<AbstractMesh[]>;
  32. public onModelLoadProgressObservable: Observable<SceneLoaderProgressEvent>;
  33. public onModelLoadErrorObservable: Observable<{ message: string; exception: any }>;
  34. public onLoaderInitObservable: Observable<ISceneLoaderPlugin | ISceneLoaderPluginAsync>;
  35. public onInitDoneObservable: Observable<AbstractViewer>;
  36. protected canvas: HTMLCanvasElement;
  37. protected registeredOnBeforerenderFunctions: Array<() => void>;
  38. constructor(public containerElement: HTMLElement, initialConfiguration: ViewerConfiguration = {}) {
  39. // if exists, use the container id. otherwise, generate a random string.
  40. if (containerElement.id) {
  41. this.baseId = containerElement.id;
  42. } else {
  43. this.baseId = containerElement.id = 'bjs' + Math.random().toString(32).substr(2, 8);
  44. }
  45. this.onSceneInitObservable = new Observable();
  46. this.onEngineInitObservable = new Observable();
  47. this.onModelLoadedObservable = new Observable();
  48. this.onModelLoadProgressObservable = new Observable();
  49. this.onModelLoadErrorObservable = new Observable();
  50. this.onInitDoneObservable = new Observable();
  51. this.onLoaderInitObservable = new Observable();
  52. this.registeredOnBeforerenderFunctions = [];
  53. // add this viewer to the viewer manager
  54. viewerManager.addViewer(this);
  55. // create a new template manager. TODO - singleton?
  56. this.templateManager = new TemplateManager(containerElement);
  57. this.prepareContainerElement();
  58. // extend the configuration
  59. configurationLoader.loadConfiguration(initialConfiguration).then((configuration) => {
  60. this.configuration = configuration;
  61. if (this.configuration.observers) {
  62. this.configureObservers(this.configuration.observers);
  63. }
  64. //this.updateConfiguration(configuration);
  65. // initialize the templates
  66. let templateConfiguration = this.configuration.templates || {};
  67. this.templateManager.initTemplate(templateConfiguration);
  68. // when done, execute onTemplatesLoaded()
  69. this.templateManager.onAllLoaded.add(() => {
  70. let canvas = this.templateManager.getCanvas();
  71. if (canvas) {
  72. this.canvas = canvas;
  73. }
  74. this._onTemplateLoaded();
  75. });
  76. });
  77. //this.onModelLoadedObservable.add(this.initEnvironment.bind(this));
  78. }
  79. public getBaseId(): string {
  80. return this.baseId;
  81. }
  82. public isCanvasInDOM(): boolean {
  83. return !!this.canvas && !!this.canvas.parentElement;
  84. }
  85. protected resize = (): void => {
  86. // Only resize if Canvas is in the DOM
  87. if (!this.isCanvasInDOM()) {
  88. return;
  89. }
  90. if (this.canvas.clientWidth <= 0 || this.canvas.clientHeight <= 0) {
  91. return;
  92. }
  93. this.engine.resize();
  94. }
  95. protected render = (): void => {
  96. this.scene && this.scene.activeCamera && this.scene.render();
  97. }
  98. /**
  99. * Update the current viewer configuration with new values.
  100. * Only provided information will be updated, old configuration values will be kept.
  101. * If this.configuration was manually changed, you can trigger this function with no parameters,
  102. * and the entire configuration will be updated.
  103. * @param newConfiguration
  104. */
  105. public updateConfiguration(newConfiguration: Partial<ViewerConfiguration> = this.configuration) {
  106. // update scene configuration
  107. if (newConfiguration.scene) {
  108. this.configureScene(newConfiguration.scene);
  109. }
  110. // optimizer
  111. if (newConfiguration.optimizer) {
  112. this.configureOptimizer(newConfiguration.optimizer);
  113. }
  114. // observers in configuration
  115. if (newConfiguration.observers) {
  116. this.configureObservers(newConfiguration.observers);
  117. }
  118. // configure model
  119. if (newConfiguration.model && typeof newConfiguration.model === 'object') {
  120. this.configureModel(newConfiguration.model);
  121. }
  122. // lights
  123. if (newConfiguration.lights) {
  124. this.configureLights(newConfiguration.lights);
  125. }
  126. // environment
  127. if (newConfiguration.skybox !== undefined || newConfiguration.ground !== undefined) {
  128. this.configureEnvironment(newConfiguration.skybox, newConfiguration.ground);
  129. }
  130. // update this.configuration with the new data
  131. this.configuration = deepmerge(this.configuration || {}, newConfiguration);
  132. }
  133. protected configureEnvironment(skyboxConifguration?: ISkyboxConfiguration | boolean, groundConfiguration?: IGroundConfiguration | boolean) {
  134. if (!skyboxConifguration && !groundConfiguration) {
  135. if (this.environmentHelper) {
  136. this.environmentHelper.dispose();
  137. };
  138. return Promise.resolve(this.scene);
  139. }
  140. const options: Partial<IEnvironmentHelperOptions> = {
  141. createGround: !!groundConfiguration,
  142. createSkybox: !!skyboxConifguration,
  143. setupImageProcessing: false // will be done at the scene level!
  144. };
  145. if (groundConfiguration) {
  146. let groundConfig = (typeof groundConfiguration === 'boolean') ? {} : groundConfiguration;
  147. let groundSize = groundConfig.size || (typeof skyboxConifguration === 'object' && skyboxConifguration.scale);
  148. if (groundSize) {
  149. options.groundSize = groundSize;
  150. }
  151. options.enableGroundShadow = groundConfig === true || groundConfig.receiveShadows;
  152. if (groundConfig.shadowLevel) {
  153. options.groundShadowLevel = groundConfig.shadowLevel;
  154. }
  155. options.enableGroundMirror = !!groundConfig.mirror;
  156. if (groundConfig.texture) {
  157. options.groundTexture = groundConfig.texture;
  158. }
  159. if (groundConfig.color) {
  160. options.groundColor = new Color3(groundConfig.color.r, groundConfig.color.g, groundConfig.color.b)
  161. }
  162. if (groundConfig.mirror) {
  163. options.enableGroundMirror = true;
  164. // to prevent undefines
  165. if (typeof groundConfig.mirror === "object") {
  166. if (groundConfig.mirror.amount)
  167. options.groundMirrorAmount = groundConfig.mirror.amount;
  168. if (groundConfig.mirror.sizeRatio)
  169. options.groundMirrorSizeRatio = groundConfig.mirror.sizeRatio;
  170. if (groundConfig.mirror.blurKernel)
  171. options.groundMirrorBlurKernel = groundConfig.mirror.blurKernel;
  172. if (groundConfig.mirror.fresnelWeight)
  173. options.groundMirrorFresnelWeight = groundConfig.mirror.fresnelWeight;
  174. if (groundConfig.mirror.fallOffDistance)
  175. options.groundMirrorFallOffDistance = groundConfig.mirror.fallOffDistance;
  176. if (this.defaultHighpTextureType !== undefined)
  177. options.groundMirrorTextureType = this.defaultHighpTextureType;
  178. }
  179. }
  180. }
  181. let postInitSkyboxMaterial = false;
  182. if (skyboxConifguration) {
  183. let conf = skyboxConifguration === true ? {} : skyboxConifguration;
  184. if (conf.material && conf.material.imageProcessingConfiguration) {
  185. options.setupImageProcessing = false; // will be configured later manually.
  186. }
  187. let skyboxSize = conf.scale;
  188. if (skyboxSize) {
  189. options.skyboxSize = skyboxSize;
  190. }
  191. options.sizeAuto = !options.skyboxSize;
  192. if (conf.color) {
  193. options.skyboxColor = new Color3(conf.color.r, conf.color.g, conf.color.b)
  194. }
  195. if (conf.cubeTexture && conf.cubeTexture.url) {
  196. if (typeof conf.cubeTexture.url === "string") {
  197. options.skyboxTexture = conf.cubeTexture.url;
  198. } else {
  199. // init later!
  200. postInitSkyboxMaterial = true;
  201. }
  202. }
  203. if (conf.material && conf.material.imageProcessingConfiguration) {
  204. postInitSkyboxMaterial = true;
  205. }
  206. }
  207. if (!this.environmentHelper) {
  208. this.environmentHelper = this.scene.createDefaultEnvironment(options)!;
  209. } else {
  210. // there might be a new scene! we need to dispose.
  211. // get the scene used by the envHelper
  212. let scene: Scene = this.environmentHelper.rootMesh.getScene();
  213. // is it a different scene? Oh no!
  214. if (scene !== this.scene) {
  215. this.environmentHelper.dispose();
  216. this.environmentHelper = this.scene.createDefaultEnvironment(options)!;
  217. } else {
  218. this.environmentHelper.updateOptions(options)!;
  219. }
  220. }
  221. if (postInitSkyboxMaterial) {
  222. let skyboxMaterial = this.environmentHelper.skyboxMaterial;
  223. if (skyboxMaterial) {
  224. if (typeof skyboxConifguration === 'object' && skyboxConifguration.material && skyboxConifguration.material.imageProcessingConfiguration) {
  225. this.extendClassWithConfig(skyboxMaterial.imageProcessingConfiguration, skyboxConifguration.material.imageProcessingConfiguration);
  226. }
  227. }
  228. }
  229. }
  230. protected configureScene(sceneConfig: ISceneConfiguration, optimizerConfig?: ISceneOptimizerConfiguration) {
  231. // sanity check!
  232. if (!this.scene) {
  233. return;
  234. }
  235. if (sceneConfig.debug) {
  236. this.scene.debugLayer.show();
  237. } else {
  238. if (this.scene.debugLayer.isVisible()) {
  239. this.scene.debugLayer.hide();
  240. }
  241. }
  242. if (sceneConfig.clearColor) {
  243. let cc = sceneConfig.clearColor;
  244. let oldcc = this.scene.clearColor;
  245. if (cc.r !== undefined) {
  246. oldcc.r = cc.r;
  247. }
  248. if (cc.g !== undefined) {
  249. oldcc.g = cc.g
  250. }
  251. if (cc.b !== undefined) {
  252. oldcc.b = cc.b
  253. }
  254. if (cc.a !== undefined) {
  255. oldcc.a = cc.a
  256. }
  257. }
  258. // image processing configuration - optional.
  259. if (sceneConfig.imageProcessingConfiguration) {
  260. this.extendClassWithConfig(this.scene.imageProcessingConfiguration, sceneConfig.imageProcessingConfiguration);
  261. }
  262. if (sceneConfig.environmentTexture) {
  263. if (this.scene.environmentTexture) {
  264. this.scene.environmentTexture.dispose();
  265. }
  266. const environmentTexture = CubeTexture.CreateFromPrefilteredData(sceneConfig.environmentTexture, this.scene);
  267. this.scene.environmentTexture = environmentTexture;
  268. }
  269. if (sceneConfig.autoRotate) {
  270. this.camera.useAutoRotationBehavior = true;
  271. }
  272. }
  273. protected configureOptimizer(optimizerConfig: ISceneOptimizerConfiguration | boolean) {
  274. if (typeof optimizerConfig === 'boolean') {
  275. if (this.sceneOptimizer) {
  276. this.sceneOptimizer.stop();
  277. this.sceneOptimizer.dispose();
  278. delete this.sceneOptimizer;
  279. }
  280. if (optimizerConfig) {
  281. this.sceneOptimizer = new SceneOptimizer(this.scene);
  282. this.sceneOptimizer.start();
  283. }
  284. } else {
  285. let optimizerOptions: SceneOptimizerOptions = new SceneOptimizerOptions(optimizerConfig.targetFrameRate, optimizerConfig.trackerDuration);
  286. // check for degradation
  287. if (optimizerConfig.degradation) {
  288. switch (optimizerConfig.degradation) {
  289. case "low":
  290. optimizerOptions = SceneOptimizerOptions.LowDegradationAllowed(optimizerConfig.targetFrameRate);
  291. break;
  292. case "moderate":
  293. optimizerOptions = SceneOptimizerOptions.ModerateDegradationAllowed(optimizerConfig.targetFrameRate);
  294. break;
  295. case "hight":
  296. optimizerOptions = SceneOptimizerOptions.HighDegradationAllowed(optimizerConfig.targetFrameRate);
  297. break;
  298. }
  299. }
  300. if (this.sceneOptimizer) {
  301. this.sceneOptimizer.stop();
  302. this.sceneOptimizer.dispose()
  303. }
  304. this.sceneOptimizer = new SceneOptimizer(this.scene, optimizerOptions, optimizerConfig.autoGeneratePriorities, optimizerConfig.improvementMode);
  305. this.sceneOptimizer.start();
  306. }
  307. }
  308. protected configureObservers(observersConfiguration: IObserversConfiguration) {
  309. if (observersConfiguration.onEngineInit) {
  310. this.onEngineInitObservable.add(window[observersConfiguration.onEngineInit]);
  311. } else {
  312. if (observersConfiguration.onEngineInit === '' && this.configuration.observers && this.configuration.observers!.onEngineInit) {
  313. this.onEngineInitObservable.removeCallback(window[this.configuration.observers!.onEngineInit!]);
  314. }
  315. }
  316. if (observersConfiguration.onSceneInit) {
  317. this.onSceneInitObservable.add(window[observersConfiguration.onSceneInit]);
  318. } else {
  319. if (observersConfiguration.onSceneInit === '' && this.configuration.observers && this.configuration.observers!.onSceneInit) {
  320. this.onSceneInitObservable.removeCallback(window[this.configuration.observers!.onSceneInit!]);
  321. }
  322. }
  323. if (observersConfiguration.onModelLoaded) {
  324. this.onModelLoadedObservable.add(window[observersConfiguration.onModelLoaded]);
  325. } else {
  326. if (observersConfiguration.onModelLoaded === '' && this.configuration.observers && this.configuration.observers!.onModelLoaded) {
  327. this.onModelLoadedObservable.removeCallback(window[this.configuration.observers!.onModelLoaded!]);
  328. }
  329. }
  330. }
  331. protected configureCamera(cameraConfig: ICameraConfiguration, focusMeshes: Array<AbstractMesh> = this.scene.meshes) {
  332. if (!this.scene.activeCamera) {
  333. this.scene.createDefaultCamera(true, true, true);
  334. this.camera = <ArcRotateCamera>this.scene.activeCamera!;
  335. }
  336. if (cameraConfig.position) {
  337. this.camera.position.copyFromFloats(cameraConfig.position.x || 0, cameraConfig.position.y || 0, cameraConfig.position.z || 0);
  338. }
  339. if (cameraConfig.rotation) {
  340. this.camera.rotationQuaternion = new Quaternion(cameraConfig.rotation.x || 0, cameraConfig.rotation.y || 0, cameraConfig.rotation.z || 0, cameraConfig.rotation.w || 0)
  341. }
  342. this.camera.minZ = cameraConfig.minZ || this.camera.minZ;
  343. this.camera.maxZ = cameraConfig.maxZ || this.camera.maxZ;
  344. if (cameraConfig.behaviors) {
  345. for (let name in cameraConfig.behaviors) {
  346. this.setCameraBehavior(cameraConfig.behaviors[name], focusMeshes);
  347. }
  348. };
  349. const sceneExtends = this.scene.getWorldExtends();
  350. const sceneDiagonal = sceneExtends.max.subtract(sceneExtends.min);
  351. const sceneDiagonalLenght = sceneDiagonal.length();
  352. this.camera.upperRadiusLimit = sceneDiagonalLenght * 3;
  353. }
  354. protected configureLights(lightsConfiguration: { [name: string]: ILightConfiguration | boolean } = {}, focusMeshes: Array<AbstractMesh> = this.scene.meshes) {
  355. // sanity check!
  356. if (!Object.keys(lightsConfiguration).length) return;
  357. let lightsAvailable: Array<string> = this.scene.lights.map(light => light.name);
  358. Object.keys(lightsConfiguration).forEach((name, idx) => {
  359. let lightConfig: ILightConfiguration = { type: 0 };
  360. if (typeof lightsConfiguration[name] === 'object') {
  361. lightConfig = <ILightConfiguration>lightsConfiguration[name];
  362. }
  363. lightConfig.name = name;
  364. let light;
  365. // light is not already available
  366. if (lightsAvailable.indexOf(name) === -1) {
  367. let constructor = Light.GetConstructorFromName(lightConfig.type, lightConfig.name, this.scene);
  368. if (!constructor) return;
  369. light = constructor();
  370. } else {
  371. // available? get it from the scene
  372. light = this.scene.getLightByName(name);
  373. lightsAvailable = lightsAvailable.filter(ln => ln !== name);
  374. }
  375. // if config set the light to false, dispose it.
  376. if (lightsConfiguration[name] === false) {
  377. light.dispose();
  378. return;
  379. }
  380. //enabled
  381. if (light.isEnabled() !== !lightConfig.disabled) {
  382. light.setEnabled(!lightConfig.disabled);
  383. }
  384. this.extendClassWithConfig(light, lightConfig);
  385. //position. Some lights don't support shadows
  386. if (light instanceof ShadowLight) {
  387. let shadowGenerator = light.getShadowGenerator();
  388. if (lightConfig.shadowEnabled && this.maxShadows) {
  389. if (!shadowGenerator) {
  390. shadowGenerator = new ShadowGenerator(512, light);
  391. }
  392. this.extendClassWithConfig(shadowGenerator, lightConfig.shadowConfig || {});
  393. // add the focues meshes to the shadow list
  394. let shadownMap = shadowGenerator.getShadowMap();
  395. if (!shadownMap) return;
  396. let renderList = shadownMap.renderList;
  397. for (var index = 0; index < focusMeshes.length; index++) {
  398. if (Tags.MatchesQuery(focusMeshes[index], 'castShadow')) {
  399. // renderList && renderList.push(focusMeshes[index]);
  400. }
  401. }
  402. } else if (shadowGenerator) {
  403. shadowGenerator.dispose();
  404. }
  405. }
  406. });
  407. // remove the unneeded lights
  408. /*lightsAvailable.forEach(name => {
  409. let light = this.scene.getLightByName(name);
  410. if (light) {
  411. light.dispose();
  412. }
  413. });*/
  414. }
  415. protected configureModel(modelConfiguration: Partial<IModelConfiguration>, focusMeshes: Array<AbstractMesh> = this.scene.meshes) {
  416. let meshesWithNoParent: Array<AbstractMesh> = focusMeshes.filter(m => !m.parent);
  417. let updateMeshesWithNoParent = (variable: string, value: any, param?: string) => {
  418. meshesWithNoParent.forEach(mesh => {
  419. if (param) {
  420. mesh[variable][param] = value;
  421. } else {
  422. mesh[variable] = value;
  423. }
  424. });
  425. }
  426. let updateXYZ = (variable: string, configValues: { x: number, y: number, z: number, w?: number }) => {
  427. if (configValues.x !== undefined) {
  428. updateMeshesWithNoParent(variable, configValues.x, 'x');
  429. }
  430. if (configValues.y !== undefined) {
  431. updateMeshesWithNoParent(variable, configValues.y, 'y');
  432. }
  433. if (configValues.z !== undefined) {
  434. updateMeshesWithNoParent(variable, configValues.z, 'z');
  435. }
  436. if (configValues.w !== undefined) {
  437. updateMeshesWithNoParent(variable, configValues.w, 'w');
  438. }
  439. }
  440. // position?
  441. if (modelConfiguration.position) {
  442. updateXYZ('position', modelConfiguration.position);
  443. }
  444. if (modelConfiguration.rotation) {
  445. if (modelConfiguration.rotation.w) {
  446. meshesWithNoParent.forEach(mesh => {
  447. if (!mesh.rotationQuaternion) {
  448. mesh.rotationQuaternion = new Quaternion();
  449. }
  450. })
  451. updateXYZ('rotationQuaternion', modelConfiguration.rotation);
  452. } else {
  453. updateXYZ('rotation', modelConfiguration.rotation);
  454. }
  455. }
  456. if (modelConfiguration.scaling) {
  457. updateXYZ('scaling', modelConfiguration.scaling);
  458. }
  459. if (modelConfiguration.castShadow) {
  460. focusMeshes.forEach(mesh => {
  461. Tags.AddTagsTo(mesh, 'castShadow');
  462. });
  463. }
  464. }
  465. public dispose() {
  466. window.removeEventListener('resize', this.resize);
  467. this.sceneOptimizer.stop();
  468. this.sceneOptimizer.dispose();
  469. if (this.scene.activeCamera) {
  470. this.scene.activeCamera.detachControl(this.canvas);
  471. }
  472. this.scene.dispose();
  473. this.engine.dispose();
  474. this.templateManager.dispose();
  475. }
  476. protected abstract prepareContainerElement();
  477. /**
  478. * This function will execute when the HTML templates finished initializing.
  479. * It should initialize the engine and continue execution.
  480. *
  481. * @protected
  482. * @returns {Promise<AbstractViewer>} The viewer object will be returned after the object was loaded.
  483. * @memberof AbstractViewer
  484. */
  485. protected onTemplatesLoaded(): Promise<AbstractViewer> {
  486. return Promise.resolve(this);
  487. }
  488. /**
  489. * This will force the creation of an engine and a scene.
  490. * It will also load a model if preconfigured.
  491. * But first - it will load the extendible onTemplateLoaded()!
  492. */
  493. private _onTemplateLoaded(): Promise<AbstractViewer> {
  494. return this.onTemplatesLoaded().then(() => {
  495. let autoLoadModel = !!this.configuration.model;
  496. return this.initEngine().then((engine) => {
  497. return this.onEngineInitObservable.notifyObserversWithPromise(engine);
  498. }).then(() => {
  499. if (autoLoadModel) {
  500. return this.loadModel();
  501. } else {
  502. return this.scene || this.initScene();
  503. }
  504. }).then((scene) => {
  505. return this.onSceneInitObservable.notifyObserversWithPromise(scene);
  506. }).then(() => {
  507. return this.onInitDoneObservable.notifyObserversWithPromise(this);
  508. }).then(() => {
  509. return this;
  510. });
  511. })
  512. }
  513. /**
  514. * Initialize the engine. Retruns a promise in case async calls are needed.
  515. *
  516. * @protected
  517. * @returns {Promise<Engine>}
  518. * @memberof Viewer
  519. */
  520. protected initEngine(): Promise<Engine> {
  521. // init custom shaders
  522. this.injectCustomShaders();
  523. let canvasElement = this.templateManager.getCanvas();
  524. if (!canvasElement) {
  525. return Promise.reject('Canvas element not found!');
  526. }
  527. let config = this.configuration.engine || {};
  528. // TDO enable further configuration
  529. this.engine = new Engine(canvasElement, !!config.antialiasing, config.engineOptions);
  530. // Disable manifest checking
  531. Database.IDBStorageEnabled = false;
  532. if (!config.disableResize) {
  533. window.addEventListener('resize', this.resize);
  534. }
  535. this.engine.runRenderLoop(this.render);
  536. if (this.configuration.engine && this.configuration.engine.adaptiveQuality) {
  537. var scale = Math.max(0.5, 1 / (window.devicePixelRatio || 2));
  538. this.engine.setHardwareScalingLevel(scale);
  539. }
  540. // set hardware limitations for scene initialization
  541. this.handleHardwareLimitations();
  542. return Promise.resolve(this.engine);
  543. }
  544. protected initScene(): Promise<Scene> {
  545. // if the scen exists, dispose it.
  546. if (this.scene) {
  547. this.scene.dispose();
  548. }
  549. // create a new scene
  550. this.scene = new Scene(this.engine);
  551. // make sure there is a default camera and light.
  552. this.scene.createDefaultLight(true);
  553. if (this.configuration.scene) {
  554. this.configureScene(this.configuration.scene);
  555. // Scene optimizer
  556. if (this.configuration.optimizer) {
  557. this.configureOptimizer(this.configuration.optimizer);
  558. }
  559. }
  560. return Promise.resolve(this.scene);
  561. }
  562. public loadModel(model: any = this.configuration.model, clearScene: boolean = true): Promise<Scene> {
  563. this.configuration.model = model;
  564. let modelUrl = (typeof model === 'string') ? model : model.url;
  565. let parts = modelUrl.split('/');
  566. let filename = parts.pop();
  567. let base = parts.join('/') + '/';
  568. let plugin = (typeof model === 'string') ? undefined : model.loader;
  569. return Promise.resolve(this.scene).then((scene) => {
  570. if (!scene) return this.initScene();
  571. if (clearScene) {
  572. scene.meshes.forEach(mesh => {
  573. mesh.dispose();
  574. });
  575. }
  576. return scene!;
  577. }).then(() => {
  578. return new Promise<Array<AbstractMesh>>((resolve, reject) => {
  579. this.lastUsedLoader = SceneLoader.ImportMesh(undefined, base, filename, this.scene, (meshes) => {
  580. resolve(meshes);
  581. }, (progressEvent) => {
  582. this.onModelLoadProgressObservable.notifyObserversWithPromise(progressEvent);
  583. }, (e, m, exception) => {
  584. // console.log(m, exception);
  585. this.onModelLoadErrorObservable.notifyObserversWithPromise({ message: m, exception: exception }).then(() => {
  586. reject(exception);
  587. });
  588. }, plugin)!;
  589. this.onLoaderInitObservable.notifyObserversWithPromise(this.lastUsedLoader);
  590. });
  591. }).then((meshes: Array<AbstractMesh>) => {
  592. return this.onModelLoadedObservable.notifyObserversWithPromise(meshes)
  593. .then(() => {
  594. // update the models' configuration
  595. this.configureModel(model, meshes);
  596. this.configureLights(this.configuration.lights);
  597. if (this.configuration.camera) {
  598. this.configureCamera(this.configuration.camera, meshes);
  599. }
  600. return this.initEnvironment(meshes);
  601. }).then(() => {
  602. return this.scene;
  603. });
  604. });
  605. }
  606. protected initEnvironment(focusMeshes: Array<AbstractMesh> = []): Promise<Scene> {
  607. this.configureEnvironment(this.configuration.skybox, this.configuration.ground);
  608. return Promise.resolve(this.scene);
  609. }
  610. /**
  611. * Alters render settings to reduce features based on hardware feature limitations
  612. * @param options Viewer options to modify
  613. */
  614. protected handleHardwareLimitations() {
  615. //flip rendering settings switches based on hardware support
  616. let maxVaryingRows = this.engine.getCaps().maxVaryingVectors;
  617. let maxFragmentSamplers = this.engine.getCaps().maxTexturesImageUnits;
  618. //shadows are disabled if there's not enough varyings for a single shadow
  619. if ((maxVaryingRows < 8) || (maxFragmentSamplers < 8)) {
  620. this.maxShadows = 0;
  621. } else {
  622. this.maxShadows = 3;
  623. }
  624. //can we render to any >= 16-bit targets (required for HDR)
  625. let caps = this.engine.getCaps();
  626. let linearHalfFloatTargets = caps.textureHalfFloatRender && caps.textureHalfFloatLinearFiltering;
  627. let linearFloatTargets = caps.textureFloatRender && caps.textureFloatLinearFiltering;
  628. let supportsHDR: boolean = !!(linearFloatTargets || linearHalfFloatTargets);
  629. if (linearHalfFloatTargets) {
  630. this.defaultHighpTextureType = Engine.TEXTURETYPE_HALF_FLOAT;
  631. this.shadowGeneratorBias = 0.002;
  632. } else if (linearFloatTargets) {
  633. this.defaultHighpTextureType = Engine.TEXTURETYPE_FLOAT;
  634. this.shadowGeneratorBias = 0.001;
  635. } else {
  636. this.defaultHighpTextureType = Engine.TEXTURETYPE_UNSIGNED_INT;
  637. this.shadowGeneratorBias = 0.001;
  638. }
  639. this.defaultPipelineTextureType = supportsHDR ? this.defaultHighpTextureType : Engine.TEXTURETYPE_UNSIGNED_INT;
  640. }
  641. /**
  642. * Injects all the spectre shader in the babylon shader store
  643. */
  644. protected injectCustomShaders(): void {
  645. let customShaders = this.configuration.customShaders;
  646. // Inject all the spectre shader in the babylon shader store.
  647. if (!customShaders) {
  648. return;
  649. }
  650. if (customShaders.shaders) {
  651. Object.keys(customShaders.shaders).forEach(key => {
  652. // typescript considers a callback "unsafe", so... '!'
  653. Effect.ShadersStore[key] = customShaders!.shaders![key];
  654. });
  655. }
  656. if (customShaders.includes) {
  657. Object.keys(customShaders.includes).forEach(key => {
  658. // typescript considers a callback "unsafe", so... '!'
  659. Effect.IncludesShadersStore[key] = customShaders!.includes![key];
  660. });
  661. }
  662. }
  663. protected extendClassWithConfig(object: any, config: any) {
  664. if (!config) return;
  665. Object.keys(config).forEach(key => {
  666. if (key in object && typeof object[key] !== 'function') {
  667. if (typeof object[key] === 'function') return;
  668. // if it is an object, iterate internally until reaching basic types
  669. if (typeof object[key] === 'object') {
  670. this.extendClassWithConfig(object[key], config[key]);
  671. } else {
  672. object[key] = config[key];
  673. }
  674. }
  675. });
  676. }
  677. private setCameraBehavior(behaviorConfig: number | {
  678. type: number;
  679. [propName: string]: any;
  680. }, payload: any) {
  681. let behavior: Behavior<ArcRotateCamera> | null;
  682. let type = (typeof behaviorConfig !== "object") ? behaviorConfig : behaviorConfig.type;
  683. let config: { [propName: string]: any } = (typeof behaviorConfig === "object") ? behaviorConfig : {};
  684. // constructing behavior
  685. switch (type) {
  686. case CameraBehavior.AUTOROTATION:
  687. behavior = new AutoRotationBehavior();
  688. break;
  689. case CameraBehavior.BOUNCING:
  690. behavior = new BouncingBehavior();
  691. break;
  692. case CameraBehavior.FRAMING:
  693. behavior = new FramingBehavior();
  694. break;
  695. default:
  696. behavior = null;
  697. break;
  698. }
  699. if (behavior) {
  700. if (typeof behaviorConfig === "object") {
  701. this.extendClassWithConfig(behavior, behaviorConfig);
  702. }
  703. this.camera.addBehavior(behavior);
  704. }
  705. // post attach configuration. Some functionalities require the attached camera.
  706. switch (type) {
  707. case CameraBehavior.AUTOROTATION:
  708. break;
  709. case CameraBehavior.BOUNCING:
  710. break;
  711. case CameraBehavior.FRAMING:
  712. if (config.zoomOnBoundingInfo) {
  713. //payload is an array of meshes
  714. let meshes = <Array<AbstractMesh>>payload;
  715. let bounding = meshes[0].getHierarchyBoundingVectors();
  716. (<FramingBehavior>behavior).zoomOnBoundingInfo(bounding.min, bounding.max);
  717. }
  718. break;
  719. }
  720. }
  721. }