viewer.ts 42 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066
  1. import { viewerManager } from './viewerManager';
  2. import { TemplateManager } from './../templateManager';
  3. import { ConfigurationLoader } from './../configuration/loader';
  4. import { Skeleton, AnimationGroup, ParticleSystem, 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, Tools } 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 { ViewerModel } from '../model/viewerModel';
  8. import { GroupModelAnimation } from '../model/modelAnimation';
  9. import { ModelLoader } from '../model/modelLoader';
  10. import { CameraBehavior } from '../interfaces';
  11. /**
  12. * The AbstractViewr is the center of Babylon's viewer.
  13. * It is the basic implementation of the default viewer and is responsible of loading and showing the model and the templates
  14. */
  15. export abstract class AbstractViewer {
  16. /**
  17. * The corresponsing template manager of this viewer.
  18. */
  19. public templateManager: TemplateManager;
  20. /**
  21. * Babylon Engine corresponding with this viewer
  22. */
  23. public engine: Engine;
  24. /**
  25. * The Babylon Scene of this viewer
  26. */
  27. public scene: Scene;
  28. /**
  29. * The camera used in this viewer
  30. */
  31. public camera: ArcRotateCamera;
  32. /**
  33. * Babylon's scene optimizer
  34. */
  35. public sceneOptimizer: SceneOptimizer;
  36. /**
  37. * The ID of this viewer. it will be generated randomly or use the HTML Element's ID.
  38. */
  39. public readonly baseId: string;
  40. /**
  41. * Models displayed in this viewer.
  42. */
  43. public models: Array<ViewerModel>;
  44. /**
  45. * The last loader used to load a model.
  46. */
  47. public lastUsedLoader: ISceneLoaderPlugin | ISceneLoaderPluginAsync;
  48. /**
  49. * The ModelLoader instance connected with this viewer.
  50. */
  51. public modelLoader: ModelLoader;
  52. /**
  53. * the viewer configuration object
  54. */
  55. protected _configuration: ViewerConfiguration;
  56. /**
  57. * Babylon's environment helper of this viewer
  58. */
  59. public environmentHelper: EnvironmentHelper;
  60. //The following are configuration objects, default values.
  61. protected _defaultHighpTextureType: number;
  62. protected _shadowGeneratorBias: number;
  63. protected _defaultPipelineTextureType: number;
  64. /**
  65. * The maximum number of shadows supported by the curent viewer
  66. */
  67. protected _maxShadows: number;
  68. /**
  69. * is HDR supported?
  70. */
  71. private _hdrSupport: boolean;
  72. /**
  73. * is this viewer disposed?
  74. */
  75. protected _isDisposed: boolean = false;
  76. /**
  77. * Returns a boolean representing HDR support
  78. */
  79. public get isHdrSupported() {
  80. return this._hdrSupport;
  81. }
  82. // observables
  83. /**
  84. * Will notify when the scene was initialized
  85. */
  86. public onSceneInitObservable: Observable<Scene>;
  87. /**
  88. * will notify when the engine was initialized
  89. */
  90. public onEngineInitObservable: Observable<Engine>;
  91. /**
  92. * will notify after every model load
  93. */
  94. public onModelLoadedObservable: Observable<ViewerModel>;
  95. /**
  96. * will notify when any model notify of progress
  97. */
  98. public onModelLoadProgressObservable: Observable<SceneLoaderProgressEvent>;
  99. /**
  100. * will notify when any model load failed.
  101. */
  102. public onModelLoadErrorObservable: Observable<{ message: string; exception: any }>;
  103. /**
  104. * will notify when a new loader was initialized.
  105. * Used mainly to know when a model starts loading.
  106. */
  107. public onLoaderInitObservable: Observable<ISceneLoaderPlugin | ISceneLoaderPluginAsync>;
  108. /**
  109. * Observers registered here will be executed when the entire load process has finished.
  110. */
  111. public onInitDoneObservable: Observable<AbstractViewer>;
  112. /**
  113. * The canvas associated with this viewer
  114. */
  115. protected _canvas: HTMLCanvasElement;
  116. /**
  117. * The (single) canvas of this viewer
  118. */
  119. public get canvas(): HTMLCanvasElement {
  120. return this._canvas;
  121. }
  122. /**
  123. * registered onBeforeRender functions.
  124. * This functions are also registered at the native scene. The reference can be used to unregister them.
  125. */
  126. protected _registeredOnBeforeRenderFunctions: Array<() => void>;
  127. /**
  128. * The configuration loader of this viewer
  129. */
  130. protected _configurationLoader: ConfigurationLoader;
  131. constructor(public containerElement: HTMLElement, initialConfiguration: ViewerConfiguration = {}) {
  132. // if exists, use the container id. otherwise, generate a random string.
  133. if (containerElement.id) {
  134. this.baseId = containerElement.id;
  135. } else {
  136. this.baseId = containerElement.id = 'bjs' + Math.random().toString(32).substr(2, 8);
  137. }
  138. this.onSceneInitObservable = new Observable();
  139. this.onEngineInitObservable = new Observable();
  140. this.onModelLoadedObservable = new Observable();
  141. this.onModelLoadProgressObservable = new Observable();
  142. this.onModelLoadErrorObservable = new Observable();
  143. this.onInitDoneObservable = new Observable();
  144. this.onLoaderInitObservable = new Observable();
  145. this._registeredOnBeforeRenderFunctions = [];
  146. this.models = [];
  147. this.modelLoader = new ModelLoader(this);
  148. // add this viewer to the viewer manager
  149. viewerManager.addViewer(this);
  150. // create a new template manager. TODO - singleton?
  151. this.templateManager = new TemplateManager(containerElement);
  152. this._prepareContainerElement();
  153. // extend the configuration
  154. this._configurationLoader = new ConfigurationLoader();
  155. this._configurationLoader.loadConfiguration(initialConfiguration, (configuration) => {
  156. this._configuration = deepmerge(this._configuration || {}, configuration);
  157. if (this._configuration.observers) {
  158. this._configureObservers(this._configuration.observers);
  159. }
  160. //this.updateConfiguration(configuration);
  161. // initialize the templates
  162. let templateConfiguration = this._configuration.templates || {};
  163. this.templateManager.initTemplate(templateConfiguration);
  164. // when done, execute onTemplatesLoaded()
  165. this.templateManager.onAllLoaded.add(() => {
  166. let canvas = this.templateManager.getCanvas();
  167. if (canvas) {
  168. this._canvas = canvas;
  169. }
  170. this._onTemplateLoaded();
  171. });
  172. });
  173. }
  174. /**
  175. * get the baseId of this viewer
  176. */
  177. public getBaseId(): string {
  178. return this.baseId;
  179. }
  180. /**
  181. * Do we have a canvas to render on, and is it a part of the scene
  182. */
  183. public isCanvasInDOM(): boolean {
  184. return !!this._canvas && !!this._canvas.parentElement;
  185. }
  186. /**
  187. * The resize function that will be registered with the window object
  188. */
  189. protected _resize = (): void => {
  190. // Only resize if Canvas is in the DOM
  191. if (!this.isCanvasInDOM()) {
  192. return;
  193. }
  194. if (this.canvas.clientWidth <= 0 || this.canvas.clientHeight <= 0) {
  195. return;
  196. }
  197. this.engine.resize();
  198. }
  199. /**
  200. * render loop that will be executed by the engine
  201. */
  202. protected _render = (): void => {
  203. this.scene && this.scene.activeCamera && this.scene.render();
  204. }
  205. /**
  206. * Update the current viewer configuration with new values.
  207. * Only provided information will be updated, old configuration values will be kept.
  208. * If this.configuration was manually changed, you can trigger this function with no parameters,
  209. * and the entire configuration will be updated.
  210. * @param newConfiguration
  211. */
  212. public updateConfiguration(newConfiguration: Partial<ViewerConfiguration> = this._configuration) {
  213. // update this.configuration with the new data
  214. this._configuration = deepmerge(this._configuration || {}, newConfiguration);
  215. // update scene configuration
  216. if (newConfiguration.scene) {
  217. this._configureScene(newConfiguration.scene);
  218. }
  219. // optimizer
  220. if (newConfiguration.optimizer) {
  221. this._configureOptimizer(newConfiguration.optimizer);
  222. }
  223. // observers in configuration
  224. if (newConfiguration.observers) {
  225. this._configureObservers(newConfiguration.observers);
  226. }
  227. // configure model
  228. if (newConfiguration.model && typeof newConfiguration.model === 'object') {
  229. this._configureModel(newConfiguration.model);
  230. }
  231. // lights
  232. if (newConfiguration.lights) {
  233. this._configureLights(newConfiguration.lights);
  234. }
  235. // environment
  236. if (newConfiguration.skybox !== undefined || newConfiguration.ground !== undefined) {
  237. this._configureEnvironment(newConfiguration.skybox, newConfiguration.ground);
  238. }
  239. // camera
  240. if (newConfiguration.camera) {
  241. this._configureCamera(newConfiguration.camera);
  242. }
  243. }
  244. protected _configureEnvironment(skyboxConifguration?: ISkyboxConfiguration | boolean, groundConfiguration?: IGroundConfiguration | boolean) {
  245. if (!skyboxConifguration && !groundConfiguration) {
  246. if (this.environmentHelper) {
  247. this.environmentHelper.dispose();
  248. delete this.environmentHelper;
  249. };
  250. return Promise.resolve(this.scene);
  251. }
  252. const options: Partial<IEnvironmentHelperOptions> = {
  253. createGround: !!groundConfiguration,
  254. createSkybox: !!skyboxConifguration,
  255. setupImageProcessing: false // will be done at the scene level!
  256. };
  257. if (groundConfiguration) {
  258. let groundConfig = (typeof groundConfiguration === 'boolean') ? {} : groundConfiguration;
  259. let groundSize = groundConfig.size || (typeof skyboxConifguration === 'object' && skyboxConifguration.scale);
  260. if (groundSize) {
  261. options.groundSize = groundSize;
  262. }
  263. options.enableGroundShadow = groundConfig === true || groundConfig.receiveShadows;
  264. if (groundConfig.shadowLevel !== undefined) {
  265. options.groundShadowLevel = groundConfig.shadowLevel;
  266. }
  267. options.enableGroundMirror = !!groundConfig.mirror;
  268. if (groundConfig.texture) {
  269. options.groundTexture = groundConfig.texture;
  270. }
  271. if (groundConfig.color) {
  272. options.groundColor = new Color3(groundConfig.color.r, groundConfig.color.g, groundConfig.color.b)
  273. }
  274. if (groundConfig.opacity !== undefined) {
  275. options.groundOpacity = groundConfig.opacity;
  276. }
  277. if (groundConfig.mirror) {
  278. options.enableGroundMirror = true;
  279. // to prevent undefines
  280. if (typeof groundConfig.mirror === "object") {
  281. if (groundConfig.mirror.amount !== undefined)
  282. options.groundMirrorAmount = groundConfig.mirror.amount;
  283. if (groundConfig.mirror.sizeRatio !== undefined)
  284. options.groundMirrorSizeRatio = groundConfig.mirror.sizeRatio;
  285. if (groundConfig.mirror.blurKernel !== undefined)
  286. options.groundMirrorBlurKernel = groundConfig.mirror.blurKernel;
  287. if (groundConfig.mirror.fresnelWeight !== undefined)
  288. options.groundMirrorFresnelWeight = groundConfig.mirror.fresnelWeight;
  289. if (groundConfig.mirror.fallOffDistance !== undefined)
  290. options.groundMirrorFallOffDistance = groundConfig.mirror.fallOffDistance;
  291. if (this._defaultPipelineTextureType !== undefined)
  292. options.groundMirrorTextureType = this._defaultPipelineTextureType;
  293. }
  294. }
  295. }
  296. let postInitSkyboxMaterial = false;
  297. if (skyboxConifguration) {
  298. let conf = skyboxConifguration === true ? {} : skyboxConifguration;
  299. if (conf.material && conf.material.imageProcessingConfiguration) {
  300. options.setupImageProcessing = false; // will be configured later manually.
  301. }
  302. let skyboxSize = conf.scale;
  303. if (skyboxSize) {
  304. options.skyboxSize = skyboxSize;
  305. }
  306. options.sizeAuto = !options.skyboxSize;
  307. if (conf.color) {
  308. options.skyboxColor = new Color3(conf.color.r, conf.color.g, conf.color.b)
  309. }
  310. if (conf.cubeTexture && conf.cubeTexture.url) {
  311. if (typeof conf.cubeTexture.url === "string") {
  312. options.skyboxTexture = conf.cubeTexture.url;
  313. } else {
  314. // init later!
  315. postInitSkyboxMaterial = true;
  316. }
  317. }
  318. if (conf.material && conf.material.imageProcessingConfiguration) {
  319. postInitSkyboxMaterial = true;
  320. }
  321. }
  322. options.setupImageProcessing = false; // TMP
  323. if (!this.environmentHelper) {
  324. this.environmentHelper = this.scene.createDefaultEnvironment(options)!;
  325. } else {
  326. // there might be a new scene! we need to dispose.
  327. // get the scene used by the envHelper
  328. let scene: Scene = this.environmentHelper.rootMesh.getScene();
  329. // is it a different scene? Oh no!
  330. if (scene !== this.scene) {
  331. this.environmentHelper.dispose();
  332. this.environmentHelper = this.scene.createDefaultEnvironment(options)!;
  333. } else {
  334. this.environmentHelper.updateOptions(options)!;
  335. }
  336. }
  337. if (postInitSkyboxMaterial) {
  338. let skyboxMaterial = this.environmentHelper.skyboxMaterial;
  339. if (skyboxMaterial) {
  340. if (typeof skyboxConifguration === 'object' && skyboxConifguration.material && skyboxConifguration.material.imageProcessingConfiguration) {
  341. this._extendClassWithConfig(skyboxMaterial.imageProcessingConfiguration, skyboxConifguration.material.imageProcessingConfiguration);
  342. }
  343. }
  344. }
  345. }
  346. /**
  347. * internally configure the scene using the provided configuration.
  348. * The scene will not be recreated, but just updated.
  349. * @param sceneConfig the (new) scene configuration
  350. */
  351. protected _configureScene(sceneConfig: ISceneConfiguration) {
  352. // sanity check!
  353. if (!this.scene) {
  354. return;
  355. }
  356. if (sceneConfig.debug) {
  357. this.scene.debugLayer.show();
  358. } else {
  359. if (this.scene.debugLayer.isVisible()) {
  360. this.scene.debugLayer.hide();
  361. }
  362. }
  363. if (sceneConfig.clearColor) {
  364. let cc = sceneConfig.clearColor;
  365. let oldcc = this.scene.clearColor;
  366. if (cc.r !== undefined) {
  367. oldcc.r = cc.r;
  368. }
  369. if (cc.g !== undefined) {
  370. oldcc.g = cc.g
  371. }
  372. if (cc.b !== undefined) {
  373. oldcc.b = cc.b
  374. }
  375. if (cc.a !== undefined) {
  376. oldcc.a = cc.a
  377. }
  378. }
  379. // image processing configuration - optional.
  380. if (sceneConfig.imageProcessingConfiguration) {
  381. this._extendClassWithConfig(this.scene.imageProcessingConfiguration, sceneConfig.imageProcessingConfiguration);
  382. }
  383. if (sceneConfig.environmentTexture) {
  384. if (this.scene.environmentTexture) {
  385. this.scene.environmentTexture.dispose();
  386. }
  387. const environmentTexture = CubeTexture.CreateFromPrefilteredData(sceneConfig.environmentTexture, this.scene);
  388. this.scene.environmentTexture = environmentTexture;
  389. }
  390. if (sceneConfig.autoRotate) {
  391. this.camera.useAutoRotationBehavior = true;
  392. }
  393. }
  394. /**
  395. * Configure the scene optimizer.
  396. * The existing scene optimizer will be disposed and a new one will be created.
  397. * @param optimizerConfig the (new) optimizer configuration
  398. */
  399. protected _configureOptimizer(optimizerConfig: ISceneOptimizerConfiguration | boolean) {
  400. if (typeof optimizerConfig === 'boolean') {
  401. if (this.sceneOptimizer) {
  402. this.sceneOptimizer.stop();
  403. this.sceneOptimizer.dispose();
  404. delete this.sceneOptimizer;
  405. }
  406. if (optimizerConfig) {
  407. this.sceneOptimizer = new SceneOptimizer(this.scene);
  408. this.sceneOptimizer.start();
  409. }
  410. } else {
  411. let optimizerOptions: SceneOptimizerOptions = new SceneOptimizerOptions(optimizerConfig.targetFrameRate, optimizerConfig.trackerDuration);
  412. // check for degradation
  413. if (optimizerConfig.degradation) {
  414. switch (optimizerConfig.degradation) {
  415. case "low":
  416. optimizerOptions = SceneOptimizerOptions.LowDegradationAllowed(optimizerConfig.targetFrameRate);
  417. break;
  418. case "moderate":
  419. optimizerOptions = SceneOptimizerOptions.ModerateDegradationAllowed(optimizerConfig.targetFrameRate);
  420. break;
  421. case "hight":
  422. optimizerOptions = SceneOptimizerOptions.HighDegradationAllowed(optimizerConfig.targetFrameRate);
  423. break;
  424. }
  425. }
  426. if (this.sceneOptimizer) {
  427. this.sceneOptimizer.stop();
  428. this.sceneOptimizer.dispose()
  429. }
  430. this.sceneOptimizer = new SceneOptimizer(this.scene, optimizerOptions, optimizerConfig.autoGeneratePriorities, optimizerConfig.improvementMode);
  431. this.sceneOptimizer.start();
  432. }
  433. }
  434. /**
  435. * this is used to register native functions using the configuration object.
  436. * This will configure the observers.
  437. * @param observersConfiguration observers configuration
  438. */
  439. protected _configureObservers(observersConfiguration: IObserversConfiguration) {
  440. if (observersConfiguration.onEngineInit) {
  441. this.onEngineInitObservable.add(window[observersConfiguration.onEngineInit]);
  442. } else {
  443. if (observersConfiguration.onEngineInit === '' && this._configuration.observers && this._configuration.observers!.onEngineInit) {
  444. this.onEngineInitObservable.removeCallback(window[this._configuration.observers!.onEngineInit!]);
  445. }
  446. }
  447. if (observersConfiguration.onSceneInit) {
  448. this.onSceneInitObservable.add(window[observersConfiguration.onSceneInit]);
  449. } else {
  450. if (observersConfiguration.onSceneInit === '' && this._configuration.observers && this._configuration.observers!.onSceneInit) {
  451. this.onSceneInitObservable.removeCallback(window[this._configuration.observers!.onSceneInit!]);
  452. }
  453. }
  454. if (observersConfiguration.onModelLoaded) {
  455. this.onModelLoadedObservable.add(window[observersConfiguration.onModelLoaded]);
  456. } else {
  457. if (observersConfiguration.onModelLoaded === '' && this._configuration.observers && this._configuration.observers!.onModelLoaded) {
  458. this.onModelLoadedObservable.removeCallback(window[this._configuration.observers!.onModelLoaded!]);
  459. }
  460. }
  461. }
  462. /**
  463. * (Re) configure the camera. The camera will only be created once and from this point will only be reconfigured.
  464. * @param cameraConfig the new camera configuration
  465. * @param model optionally use the model to configure the camera.
  466. */
  467. protected _configureCamera(cameraConfig: ICameraConfiguration, model?: ViewerModel) {
  468. let focusMeshes = model ? model.meshes : this.scene.meshes;
  469. if (!this.scene.activeCamera) {
  470. this.scene.createDefaultCamera(true, true, true);
  471. this.camera = <ArcRotateCamera>this.scene.activeCamera!;
  472. }
  473. if (cameraConfig.position) {
  474. this.camera.position.copyFromFloats(cameraConfig.position.x || 0, cameraConfig.position.y || 0, cameraConfig.position.z || 0);
  475. }
  476. if (cameraConfig.rotation) {
  477. this.camera.rotationQuaternion = new Quaternion(cameraConfig.rotation.x || 0, cameraConfig.rotation.y || 0, cameraConfig.rotation.z || 0, cameraConfig.rotation.w || 0)
  478. }
  479. this._extendClassWithConfig(this.camera, cameraConfig);
  480. this.camera.minZ = cameraConfig.minZ || this.camera.minZ;
  481. this.camera.maxZ = cameraConfig.maxZ || this.camera.maxZ;
  482. if (cameraConfig.behaviors) {
  483. for (let name in cameraConfig.behaviors) {
  484. this._setCameraBehavior(cameraConfig.behaviors[name], focusMeshes);
  485. }
  486. };
  487. const sceneExtends = this.scene.getWorldExtends((mesh) => {
  488. return !this.environmentHelper || (mesh !== this.environmentHelper.ground && mesh !== this.environmentHelper.rootMesh && mesh !== this.environmentHelper.skybox);
  489. });
  490. const sceneDiagonal = sceneExtends.max.subtract(sceneExtends.min);
  491. const sceneDiagonalLenght = sceneDiagonal.length();
  492. if (isFinite(sceneDiagonalLenght))
  493. this.camera.upperRadiusLimit = sceneDiagonalLenght * 3;
  494. }
  495. /**
  496. * configure the lights.
  497. *
  498. * @param lightsConfiguration the (new) light(s) configuration
  499. * @param model optionally use the model to configure the camera.
  500. */
  501. protected _configureLights(lightsConfiguration: { [name: string]: ILightConfiguration | boolean } = {}, model?: ViewerModel) {
  502. let focusMeshes = model ? model.meshes : this.scene.meshes;
  503. // sanity check!
  504. if (!Object.keys(lightsConfiguration).length) return;
  505. let lightsAvailable: Array<string> = this.scene.lights.map(light => light.name);
  506. // compare to the global (!) configuration object and dispose unneeded:
  507. let lightsToConfigure = Object.keys(this._configuration.lights || []);
  508. if (Object.keys(lightsToConfigure).length !== lightsAvailable.length) {
  509. lightsAvailable.forEach(lName => {
  510. if (lightsToConfigure.indexOf(lName) === -1) {
  511. this.scene.getLightByName(lName)!.dispose()
  512. }
  513. });
  514. }
  515. Object.keys(lightsConfiguration).forEach((name, idx) => {
  516. let lightConfig: ILightConfiguration = { type: 0 };
  517. if (typeof lightsConfiguration[name] === 'object') {
  518. lightConfig = <ILightConfiguration>lightsConfiguration[name];
  519. }
  520. lightConfig.name = name;
  521. let light: Light;
  522. // light is not already available
  523. if (lightsAvailable.indexOf(name) === -1) {
  524. let constructor = Light.GetConstructorFromName(lightConfig.type, lightConfig.name, this.scene);
  525. if (!constructor) return;
  526. light = constructor();
  527. } else {
  528. // available? get it from the scene
  529. light = <Light>this.scene.getLightByName(name);
  530. lightsAvailable = lightsAvailable.filter(ln => ln !== name);
  531. if (lightConfig.type !== undefined && light.getTypeID() !== lightConfig.type) {
  532. light.dispose();
  533. let constructor = Light.GetConstructorFromName(lightConfig.type, lightConfig.name, this.scene);
  534. if (!constructor) return;
  535. light = constructor();
  536. }
  537. }
  538. // if config set the light to false, dispose it.
  539. if (lightsConfiguration[name] === false) {
  540. light.dispose();
  541. return;
  542. }
  543. //enabled
  544. var enabled = lightConfig.enabled !== undefined ? lightConfig.enabled : !lightConfig.disabled;
  545. light.setEnabled(enabled);
  546. this._extendClassWithConfig(light, lightConfig);
  547. //position. Some lights don't support shadows
  548. if (light instanceof ShadowLight) {
  549. if (lightConfig.target) {
  550. if (light.setDirectionToTarget) {
  551. let target = Vector3.Zero().copyFrom(lightConfig.target as Vector3);
  552. light.setDirectionToTarget(target);
  553. }
  554. } else if (lightConfig.direction) {
  555. let direction = Vector3.Zero().copyFrom(lightConfig.direction as Vector3);
  556. light.direction = direction;
  557. }
  558. let shadowGenerator = light.getShadowGenerator();
  559. if (lightConfig.shadowEnabled && this._maxShadows) {
  560. if (!shadowGenerator) {
  561. shadowGenerator = new ShadowGenerator(512, light);
  562. // TODO blur kernel definition
  563. }
  564. this._extendClassWithConfig(shadowGenerator, lightConfig.shadowConfig || {});
  565. // add the focues meshes to the shadow list
  566. let shadownMap = shadowGenerator.getShadowMap();
  567. if (!shadownMap) return;
  568. let renderList = shadownMap.renderList;
  569. for (var index = 0; index < focusMeshes.length; index++) {
  570. if (Tags.MatchesQuery(focusMeshes[index], 'castShadow')) {
  571. renderList && renderList.push(focusMeshes[index]);
  572. }
  573. }
  574. } else if (shadowGenerator) {
  575. shadowGenerator.dispose();
  576. }
  577. }
  578. });
  579. }
  580. /**
  581. * configure all models using the configuration.
  582. * @param modelConfiguration the configuration to use to reconfigure the models
  583. */
  584. protected _configureModel(modelConfiguration: Partial<IModelConfiguration>) {
  585. this.models.forEach(model => {
  586. model.updateConfiguration(modelConfiguration);
  587. })
  588. }
  589. /**
  590. * Dispoe the entire viewer including the scene and the engine
  591. */
  592. public dispose() {
  593. if (this._isDisposed) {
  594. return;
  595. }
  596. window.removeEventListener('resize', this._resize);
  597. if (this.sceneOptimizer) {
  598. this.sceneOptimizer.stop();
  599. this.sceneOptimizer.dispose();
  600. }
  601. if (this.environmentHelper) {
  602. this.environmentHelper.dispose();
  603. }
  604. if (this._configurationLoader) {
  605. this._configurationLoader.dispose();
  606. }
  607. //observers
  608. this.onEngineInitObservable.clear();
  609. delete this.onEngineInitObservable;
  610. this.onInitDoneObservable.clear();
  611. delete this.onInitDoneObservable;
  612. this.onLoaderInitObservable.clear();
  613. delete this.onLoaderInitObservable;
  614. this.onModelLoadedObservable.clear();
  615. delete this.onModelLoadedObservable;
  616. this.onModelLoadErrorObservable.clear();
  617. delete this.onModelLoadErrorObservable;
  618. this.onModelLoadProgressObservable.clear();
  619. delete this.onModelLoadProgressObservable;
  620. this.onSceneInitObservable.clear();
  621. delete this.onSceneInitObservable;
  622. if (this.scene.activeCamera) {
  623. this.scene.activeCamera.detachControl(this.canvas);
  624. }
  625. this.modelLoader.dispose();
  626. this.models.forEach(model => {
  627. model.dispose();
  628. });
  629. this.models.length = 0;
  630. this.scene.dispose();
  631. this.engine.dispose();
  632. this.templateManager.dispose();
  633. viewerManager.removeViewer(this);
  634. this._isDisposed = true;
  635. }
  636. /**
  637. * This will prepare the container element for the viewer
  638. */
  639. protected abstract _prepareContainerElement();
  640. /**
  641. * This function will execute when the HTML templates finished initializing.
  642. * It should initialize the engine and continue execution.
  643. *
  644. * @returns {Promise<AbstractViewer>} The viewer object will be returned after the object was loaded.
  645. */
  646. protected _onTemplatesLoaded(): Promise<AbstractViewer> {
  647. return Promise.resolve(this);
  648. }
  649. /**
  650. * This will force the creation of an engine and a scene.
  651. * It will also load a model if preconfigured.
  652. * But first - it will load the extendible onTemplateLoaded()!
  653. */
  654. private _onTemplateLoaded(): Promise<AbstractViewer> {
  655. return this._onTemplatesLoaded().then(() => {
  656. let autoLoadModel = this._configuration.model;
  657. return this._initEngine().then((engine) => {
  658. return this.onEngineInitObservable.notifyObserversWithPromise(engine);
  659. }).then(() => {
  660. if (autoLoadModel) {
  661. return this.loadModel().catch(e => { }).then(() => { return this.scene });
  662. } else {
  663. return this.scene || this._initScene();
  664. }
  665. }).then((scene) => {
  666. return this.onSceneInitObservable.notifyObserversWithPromise(scene);
  667. }).then(() => {
  668. return this.onInitDoneObservable.notifyObserversWithPromise(this);
  669. }).catch(e => {
  670. Tools.Warn(e.toString());
  671. return this;
  672. });
  673. })
  674. }
  675. /**
  676. * Initialize the engine. Retruns a promise in case async calls are needed.
  677. *
  678. * @protected
  679. * @returns {Promise<Engine>}
  680. * @memberof Viewer
  681. */
  682. protected _initEngine(): Promise<Engine> {
  683. // init custom shaders
  684. this._injectCustomShaders();
  685. let canvasElement = this.templateManager.getCanvas();
  686. if (!canvasElement) {
  687. return Promise.reject('Canvas element not found!');
  688. }
  689. let config = this._configuration.engine || {};
  690. // TDO enable further configuration
  691. this.engine = new Engine(canvasElement, !!config.antialiasing, config.engineOptions);
  692. // Disable manifest checking
  693. Database.IDBStorageEnabled = false;
  694. if (!config.disableResize) {
  695. window.addEventListener('resize', this._resize);
  696. }
  697. this.engine.runRenderLoop(this._render);
  698. if (this._configuration.engine && this._configuration.engine.adaptiveQuality) {
  699. var scale = Math.max(0.5, 1 / (window.devicePixelRatio || 2));
  700. this.engine.setHardwareScalingLevel(scale);
  701. }
  702. // set hardware limitations for scene initialization
  703. this._handleHardwareLimitations();
  704. return Promise.resolve(this.engine);
  705. }
  706. /**
  707. * initialize the scene. Calling thsi function again will dispose the old scene, if exists.
  708. */
  709. protected _initScene(): Promise<Scene> {
  710. // if the scen exists, dispose it.
  711. if (this.scene) {
  712. this.scene.dispose();
  713. }
  714. // create a new scene
  715. this.scene = new Scene(this.engine);
  716. // make sure there is a default camera and light.
  717. this.scene.createDefaultLight(true);
  718. if (this._configuration.scene) {
  719. this._configureScene(this._configuration.scene);
  720. // Scene optimizer
  721. if (this._configuration.optimizer) {
  722. this._configureOptimizer(this._configuration.optimizer);
  723. }
  724. }
  725. return Promise.resolve(this.scene);
  726. }
  727. private _isLoading: boolean;
  728. private _nextLoading: Function;
  729. /**
  730. * Initialize a model loading. The returns object (a ViewerModel object) will be loaded in the background.
  731. * The difference between this and loadModel is that loadModel will fulfill the promise when the model finished loading.
  732. *
  733. * @param modelConfig model configuration to use when loading the model.
  734. * @param clearScene should the scene be cleared before loading this model
  735. * @returns a ViewerModel object that is not yet fully loaded.
  736. */
  737. public initModel(modelConfig: IModelConfiguration, clearScene: boolean = true): ViewerModel {
  738. if (clearScene) {
  739. this.models.forEach(m => m.dispose());
  740. this.models.length = 0;
  741. }
  742. let model = this.modelLoader.load(modelConfig);
  743. this.lastUsedLoader = model.loader;
  744. model.onLoadErrorObservable.add((errorObject) => {
  745. this.onModelLoadErrorObservable.notifyObserversWithPromise(errorObject);
  746. });
  747. model.onLoadProgressObservable.add((progressEvent) => {
  748. return this.onModelLoadProgressObservable.notifyObserversWithPromise(progressEvent);
  749. });
  750. this.onLoaderInitObservable.notifyObserversWithPromise(this.lastUsedLoader);
  751. model.onLoadedObservable.add(() => {
  752. this.onModelLoadedObservable.notifyObserversWithPromise(model)
  753. .then(() => {
  754. this._configureLights(this._configuration.lights);
  755. if (this._configuration.camera || !this.scene.activeCamera) {
  756. this._configureCamera(this._configuration.camera || {}, model);
  757. }
  758. return this._initEnvironment(model);
  759. }).then(() => {
  760. this._isLoading = false;
  761. return model;
  762. });
  763. });
  764. return model;
  765. }
  766. /**
  767. * load a model using the provided configuration
  768. *
  769. * @param modelConfig the model configuration or URL to load.
  770. * @param clearScene Should the scene be cleared before loading the model
  771. * @returns a Promise the fulfills when the model finished loading successfully.
  772. */
  773. public loadModel(modelConfig: any = this._configuration.model, clearScene: boolean = true): Promise<ViewerModel> {
  774. // no model was provided? Do nothing!
  775. let modelUrl = (typeof modelConfig === 'string') ? modelConfig : modelConfig.url;
  776. if (!modelUrl) {
  777. return Promise.reject("no model configuration found");
  778. }
  779. if (this._isLoading) {
  780. // We can decide here whether or not to cancel the lst load, but the developer can do that.
  781. return Promise.reject("another model is curently being loaded.");
  782. }
  783. this._isLoading = true;
  784. if ((typeof modelConfig === 'string')) {
  785. if (this._configuration.model && typeof this._configuration.model === 'object') {
  786. this._configuration.model.url = modelConfig;
  787. }
  788. } else {
  789. if (this._configuration.model) {
  790. deepmerge(this._configuration.model, modelConfig)
  791. } else {
  792. this._configuration.model = modelConfig;
  793. }
  794. }
  795. return Promise.resolve(this.scene).then((scene) => {
  796. if (!scene) return this._initScene();
  797. return scene;
  798. }).then(() => {
  799. return new Promise<ViewerModel>((resolve, reject) => {
  800. // at this point, configuration.model is an object, not a string
  801. return this.initModel(modelConfig, clearScene);
  802. });
  803. })
  804. }
  805. /**
  806. * initialize the environment for a specific model.
  807. * Per default it will use the viewer'S configuration.
  808. * @param model the model to use to configure the environment.
  809. * @returns a Promise that will resolve when the configuration is done.
  810. */
  811. protected _initEnvironment(model?: ViewerModel): Promise<Scene> {
  812. this._configureEnvironment(this._configuration.skybox, this._configuration.ground);
  813. return Promise.resolve(this.scene);
  814. }
  815. /**
  816. * Alters render settings to reduce features based on hardware feature limitations
  817. * @param enableHDR Allows the viewer to run in HDR mode.
  818. */
  819. protected _handleHardwareLimitations(enableHDR = true) {
  820. //flip rendering settings switches based on hardware support
  821. let maxVaryingRows = this.engine.getCaps().maxVaryingVectors;
  822. let maxFragmentSamplers = this.engine.getCaps().maxTexturesImageUnits;
  823. //shadows are disabled if there's not enough varyings for a single shadow
  824. if ((maxVaryingRows < 8) || (maxFragmentSamplers < 8)) {
  825. this._maxShadows = 0;
  826. } else {
  827. this._maxShadows = 3;
  828. }
  829. //can we render to any >= 16-bit targets (required for HDR)
  830. let caps = this.engine.getCaps();
  831. let linearHalfFloatTargets = caps.textureHalfFloatRender && caps.textureHalfFloatLinearFiltering;
  832. let linearFloatTargets = caps.textureFloatRender && caps.textureFloatLinearFiltering;
  833. this._hdrSupport = enableHDR && !!(linearFloatTargets || linearHalfFloatTargets);
  834. if (linearHalfFloatTargets) {
  835. this._defaultHighpTextureType = Engine.TEXTURETYPE_HALF_FLOAT;
  836. this._shadowGeneratorBias = 0.002;
  837. } else if (linearFloatTargets) {
  838. this._defaultHighpTextureType = Engine.TEXTURETYPE_FLOAT;
  839. this._shadowGeneratorBias = 0.001;
  840. } else {
  841. this._defaultHighpTextureType = Engine.TEXTURETYPE_UNSIGNED_INT;
  842. this._shadowGeneratorBias = 0.001;
  843. }
  844. this._defaultPipelineTextureType = this._hdrSupport ? this._defaultHighpTextureType : Engine.TEXTURETYPE_UNSIGNED_INT;
  845. }
  846. /**
  847. * Injects all the spectre shader in the babylon shader store
  848. */
  849. protected _injectCustomShaders(): void {
  850. let customShaders = this._configuration.customShaders;
  851. // Inject all the spectre shader in the babylon shader store.
  852. if (!customShaders) {
  853. return;
  854. }
  855. if (customShaders.shaders) {
  856. Object.keys(customShaders.shaders).forEach(key => {
  857. // typescript considers a callback "unsafe", so... '!'
  858. Effect.ShadersStore[key] = customShaders!.shaders![key];
  859. });
  860. }
  861. if (customShaders.includes) {
  862. Object.keys(customShaders.includes).forEach(key => {
  863. // typescript considers a callback "unsafe", so... '!'
  864. Effect.IncludesShadersStore[key] = customShaders!.includes![key];
  865. });
  866. }
  867. }
  868. /**
  869. * This will extend an object with configuration values.
  870. * What it practically does it take the keys from the configuration and set them on the object.
  871. * I the configuration is a tree, it will traverse into the tree.
  872. * @param object the object to extend
  873. * @param config the configuration object that will extend the object
  874. */
  875. protected _extendClassWithConfig(object: any, config: any) {
  876. if (!config) return;
  877. Object.keys(config).forEach(key => {
  878. if (key in object && typeof object[key] !== 'function') {
  879. // if (typeof object[key] === 'function') return;
  880. // if it is an object, iterate internally until reaching basic types
  881. if (typeof object[key] === 'object') {
  882. this._extendClassWithConfig(object[key], config[key]);
  883. } else {
  884. if (config[key] !== undefined) {
  885. object[key] = config[key];
  886. }
  887. }
  888. }
  889. });
  890. }
  891. private _setCameraBehavior(behaviorConfig: number | {
  892. type: number;
  893. [propName: string]: any;
  894. }, payload: any) {
  895. let behavior: Behavior<ArcRotateCamera> | null;
  896. let type = (typeof behaviorConfig !== "object") ? behaviorConfig : behaviorConfig.type;
  897. let config: { [propName: string]: any } = (typeof behaviorConfig === "object") ? behaviorConfig : {};
  898. // constructing behavior
  899. switch (type) {
  900. case CameraBehavior.AUTOROTATION:
  901. this.camera.useAutoRotationBehavior = true;
  902. behavior = this.camera.autoRotationBehavior;
  903. break;
  904. case CameraBehavior.BOUNCING:
  905. this.camera.useBouncingBehavior = true;
  906. behavior = this.camera.bouncingBehavior;
  907. break;
  908. case CameraBehavior.FRAMING:
  909. this.camera.useFramingBehavior = true;
  910. behavior = this.camera.framingBehavior;
  911. break;
  912. default:
  913. behavior = null;
  914. break;
  915. }
  916. if (behavior) {
  917. if (typeof behaviorConfig === "object") {
  918. this._extendClassWithConfig(behavior, behaviorConfig);
  919. }
  920. }
  921. // post attach configuration. Some functionalities require the attached camera.
  922. switch (type) {
  923. case CameraBehavior.AUTOROTATION:
  924. break;
  925. case CameraBehavior.BOUNCING:
  926. break;
  927. case CameraBehavior.FRAMING:
  928. if (config.zoomOnBoundingInfo) {
  929. //payload is an array of meshes
  930. let meshes = <Array<AbstractMesh>>payload;
  931. let bounding = meshes[0].getHierarchyBoundingVectors();
  932. (<FramingBehavior>behavior).zoomOnBoundingInfo(bounding.min, bounding.max);
  933. }
  934. break;
  935. }
  936. }
  937. }