viewer.ts 42 KB

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