viewer.ts 44 KB

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