sceneManager.ts 28 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691
  1. import { Scene, ArcRotateCamera, Engine, Light, ShadowLight, Vector3, ShadowGenerator, Tags, CubeTexture, Quaternion, SceneOptimizer, EnvironmentHelper, SceneOptimizerOptions, Color3, IEnvironmentHelperOptions, AbstractMesh, FramingBehavior, Behavior, Observable } from 'babylonjs';
  2. import { AbstractViewer } from './viewer';
  3. import { ILightConfiguration, ISceneConfiguration, ISceneOptimizerConfiguration, ICameraConfiguration, ISkyboxConfiguration, ViewerConfiguration, IGroundConfiguration, IModelConfiguration } from '../configuration/configuration';
  4. import { ViewerModel } from '../model/viewerModel';
  5. import { extendClassWithConfig } from '../helper';
  6. import { CameraBehavior } from '../interfaces';
  7. /**
  8. * This interface describes the structure of the variable sent with the configuration observables of the scene manager.
  9. * O - the type of object we are dealing with (Light, ArcRotateCamera, Scene, etc')
  10. * T - the configuration type
  11. */
  12. export interface IPostConfigurationCallback<OBJ, CONF> {
  13. newConfiguration: CONF;
  14. sceneManager: SceneManager;
  15. object: OBJ;
  16. model?: ViewerModel;
  17. }
  18. export class SceneManager {
  19. //Observers
  20. onSceneInitObservable: Observable<Scene>;
  21. onSceneConfiguredObservable: Observable<IPostConfigurationCallback<Scene, ISceneConfiguration>>;
  22. onSceneOptimizerConfiguredObservable: Observable<IPostConfigurationCallback<SceneOptimizer, ISceneOptimizerConfiguration | boolean>>;
  23. onCameraConfiguredObservable: Observable<IPostConfigurationCallback<ArcRotateCamera, ICameraConfiguration>>;
  24. onLightsConfiguredObservable: Observable<IPostConfigurationCallback<Array<Light>, { [name: string]: ILightConfiguration | boolean }>>;
  25. onModelsConfiguredObservable: Observable<IPostConfigurationCallback<Array<ViewerModel>, IModelConfiguration>>;
  26. onEnvironmentConfiguredObservable: Observable<IPostConfigurationCallback<EnvironmentHelper, { skybox?: ISkyboxConfiguration | boolean, ground?: IGroundConfiguration | boolean }>>;
  27. /**
  28. * The Babylon Scene of this viewer
  29. */
  30. public scene: Scene;
  31. /**
  32. * The camera used in this viewer
  33. */
  34. public camera: ArcRotateCamera;
  35. /**
  36. * Babylon's scene optimizer
  37. */
  38. public sceneOptimizer: SceneOptimizer;
  39. /**
  40. * Models displayed in this viewer.
  41. */
  42. public models: Array<ViewerModel>;
  43. /**
  44. * Babylon's environment helper of this viewer
  45. */
  46. public environmentHelper: EnvironmentHelper;
  47. //The following are configuration objects, default values.
  48. protected _defaultHighpTextureType: number;
  49. protected _shadowGeneratorBias: number;
  50. protected _defaultPipelineTextureType: number;
  51. /**
  52. * The maximum number of shadows supported by the curent viewer
  53. */
  54. protected _maxShadows: number;
  55. /**
  56. * is HDR supported?
  57. */
  58. private _hdrSupport: boolean;
  59. private _globalConfiguration: ViewerConfiguration;
  60. /**
  61. * Returns a boolean representing HDR support
  62. */
  63. public get isHdrSupported() {
  64. return this._hdrSupport;
  65. }
  66. constructor(private _viewer: AbstractViewer) {
  67. this.models = [];
  68. this.onCameraConfiguredObservable = new Observable();
  69. this.onLightsConfiguredObservable = new Observable();
  70. this.onModelsConfiguredObservable = new Observable();
  71. this.onSceneConfiguredObservable = new Observable();
  72. this.onSceneInitObservable = new Observable();
  73. this.onSceneOptimizerConfiguredObservable = new Observable();
  74. this.onEnvironmentConfiguredObservable = new Observable();
  75. this._viewer.onEngineInitObservable.add(() => {
  76. this._handleHardwareLimitations();
  77. });
  78. this._viewer.onModelLoadedObservable.add((model) => {
  79. this._configureLights(this._viewer.configuration.lights, model);
  80. if (this._viewer.configuration.camera || !this.scene.activeCamera) {
  81. this._configureCamera(this._viewer.configuration.camera || {}, model);
  82. }
  83. return this._initEnvironment(model);
  84. })
  85. }
  86. /**
  87. * initialize the environment for a specific model.
  88. * Per default it will use the viewer's configuration.
  89. * @param model the model to use to configure the environment.
  90. * @returns a Promise that will resolve when the configuration is done.
  91. */
  92. protected _initEnvironment(model?: ViewerModel): Promise<Scene> {
  93. this._configureEnvironment(this._viewer.configuration.skybox, this._viewer.configuration.ground, model);
  94. return Promise.resolve(this.scene);
  95. }
  96. /**
  97. * initialize the scene. Calling this function again will dispose the old scene, if exists.
  98. */
  99. public initScene(sceneConfiguration?: ISceneConfiguration, optimizerConfiguration?: boolean | ISceneOptimizerConfiguration): Promise<Scene> {
  100. // if the scen exists, dispose it.
  101. if (this.scene) {
  102. this.scene.dispose();
  103. }
  104. // create a new scene
  105. this.scene = new Scene(this._viewer.engine);
  106. if (sceneConfiguration) {
  107. this._configureScene(sceneConfiguration);
  108. // Scene optimizer
  109. if (optimizerConfiguration) {
  110. this._configureOptimizer(optimizerConfiguration);
  111. }
  112. }
  113. return this.onSceneInitObservable.notifyObserversWithPromise(this.scene);
  114. }
  115. public clearScene(clearModels: boolean = true, clearLights: boolean = false) {
  116. if (clearModels) {
  117. this.models.forEach(m => m.dispose());
  118. this.models.length = 0;
  119. }
  120. if (clearLights) {
  121. this.scene.lights.forEach(l => l.dispose());
  122. }
  123. }
  124. /**
  125. * This will update the scene's configuration, including camera, lights, environment.
  126. * @param newConfiguration the delta that should be configured. This includes only the changes
  127. * @param globalConfiguration The global configuration object, after the new configuration was merged into it
  128. */
  129. public updateConfiguration(newConfiguration: Partial<ViewerConfiguration>, globalConfiguration: ViewerConfiguration) {
  130. // update scene configuration
  131. if (newConfiguration.scene) {
  132. this._configureScene(newConfiguration.scene);
  133. }
  134. // optimizer
  135. if (newConfiguration.optimizer) {
  136. this._configureOptimizer(newConfiguration.optimizer);
  137. }
  138. // lights
  139. this._configureLights(newConfiguration.lights);
  140. // environment
  141. if (newConfiguration.skybox !== undefined || newConfiguration.ground !== undefined) {
  142. this._configureEnvironment(newConfiguration.skybox, newConfiguration.ground);
  143. }
  144. // configure model
  145. if (newConfiguration.model && typeof newConfiguration.model === 'object') {
  146. this._configureModel(newConfiguration.model);
  147. }
  148. // camera
  149. this._configureCamera(newConfiguration.camera);
  150. }
  151. /**
  152. * internally configure the scene using the provided configuration.
  153. * The scene will not be recreated, but just updated.
  154. * @param sceneConfig the (new) scene configuration
  155. */
  156. protected _configureScene(sceneConfig: ISceneConfiguration) {
  157. // sanity check!
  158. if (!this.scene) {
  159. return;
  160. }
  161. if (sceneConfig.debug) {
  162. this.scene.debugLayer.show();
  163. } else {
  164. if (this.scene.debugLayer.isVisible()) {
  165. this.scene.debugLayer.hide();
  166. }
  167. }
  168. if (sceneConfig.clearColor) {
  169. let cc = sceneConfig.clearColor;
  170. let oldcc = this.scene.clearColor;
  171. if (cc.r !== undefined) {
  172. oldcc.r = cc.r;
  173. }
  174. if (cc.g !== undefined) {
  175. oldcc.g = cc.g
  176. }
  177. if (cc.b !== undefined) {
  178. oldcc.b = cc.b
  179. }
  180. if (cc.a !== undefined) {
  181. oldcc.a = cc.a
  182. }
  183. }
  184. // image processing configuration - optional.
  185. if (sceneConfig.imageProcessingConfiguration) {
  186. extendClassWithConfig(this.scene.imageProcessingConfiguration, sceneConfig.imageProcessingConfiguration);
  187. }
  188. if (sceneConfig.environmentTexture) {
  189. if (this.scene.environmentTexture) {
  190. this.scene.environmentTexture.dispose();
  191. }
  192. const environmentTexture = CubeTexture.CreateFromPrefilteredData(sceneConfig.environmentTexture, this.scene);
  193. this.scene.environmentTexture = environmentTexture;
  194. }
  195. this.onSceneConfiguredObservable.notifyObservers({
  196. sceneManager: this,
  197. object: this.scene,
  198. newConfiguration: sceneConfig
  199. });
  200. }
  201. /**
  202. * Configure the scene optimizer.
  203. * The existing scene optimizer will be disposed and a new one will be created.
  204. * @param optimizerConfig the (new) optimizer configuration
  205. */
  206. protected _configureOptimizer(optimizerConfig: ISceneOptimizerConfiguration | boolean) {
  207. if (typeof optimizerConfig === 'boolean') {
  208. if (this.sceneOptimizer) {
  209. this.sceneOptimizer.stop();
  210. this.sceneOptimizer.dispose();
  211. delete this.sceneOptimizer;
  212. }
  213. if (optimizerConfig) {
  214. this.sceneOptimizer = new SceneOptimizer(this.scene);
  215. this.sceneOptimizer.start();
  216. }
  217. } else {
  218. let optimizerOptions: SceneOptimizerOptions = new SceneOptimizerOptions(optimizerConfig.targetFrameRate, optimizerConfig.trackerDuration);
  219. // check for degradation
  220. if (optimizerConfig.degradation) {
  221. switch (optimizerConfig.degradation) {
  222. case "low":
  223. optimizerOptions = SceneOptimizerOptions.LowDegradationAllowed(optimizerConfig.targetFrameRate);
  224. break;
  225. case "moderate":
  226. optimizerOptions = SceneOptimizerOptions.ModerateDegradationAllowed(optimizerConfig.targetFrameRate);
  227. break;
  228. case "hight":
  229. optimizerOptions = SceneOptimizerOptions.HighDegradationAllowed(optimizerConfig.targetFrameRate);
  230. break;
  231. }
  232. }
  233. if (this.sceneOptimizer) {
  234. this.sceneOptimizer.stop();
  235. this.sceneOptimizer.dispose()
  236. }
  237. this.sceneOptimizer = new SceneOptimizer(this.scene, optimizerOptions, optimizerConfig.autoGeneratePriorities, optimizerConfig.improvementMode);
  238. this.sceneOptimizer.start();
  239. }
  240. this.onSceneOptimizerConfiguredObservable.notifyObservers({
  241. sceneManager: this,
  242. object: this.sceneOptimizer,
  243. newConfiguration: optimizerConfig
  244. });
  245. }
  246. /**
  247. * configure all models using the configuration.
  248. * @param modelConfiguration the configuration to use to reconfigure the models
  249. */
  250. protected _configureModel(modelConfiguration: Partial<IModelConfiguration>) {
  251. this.models.forEach(model => {
  252. model.updateConfiguration(modelConfiguration);
  253. });
  254. this.onModelsConfiguredObservable.notifyObservers({
  255. sceneManager: this,
  256. object: this.models,
  257. newConfiguration: modelConfiguration
  258. });
  259. }
  260. /**
  261. * (Re) configure the camera. The camera will only be created once and from this point will only be reconfigured.
  262. * @param cameraConfig the new camera configuration
  263. * @param model optionally use the model to configure the camera.
  264. */
  265. protected _configureCamera(cameraConfig: ICameraConfiguration = {}, model?: ViewerModel) {
  266. let focusMeshes = model ? model.meshes : this.scene.meshes;
  267. if (!this.scene.activeCamera) {
  268. this.scene.createDefaultCamera(true, true, true);
  269. this.camera = <ArcRotateCamera>this.scene.activeCamera!;
  270. }
  271. if (cameraConfig.position) {
  272. this.camera.position.copyFromFloats(cameraConfig.position.x || 0, cameraConfig.position.y || 0, cameraConfig.position.z || 0);
  273. }
  274. if (cameraConfig.rotation) {
  275. this.camera.rotationQuaternion = new Quaternion(cameraConfig.rotation.x || 0, cameraConfig.rotation.y || 0, cameraConfig.rotation.z || 0, cameraConfig.rotation.w || 0)
  276. }
  277. extendClassWithConfig(this.camera, cameraConfig);
  278. this.camera.minZ = cameraConfig.minZ || this.camera.minZ;
  279. this.camera.maxZ = cameraConfig.maxZ || this.camera.maxZ;
  280. if (cameraConfig.behaviors) {
  281. for (let name in cameraConfig.behaviors) {
  282. this._setCameraBehavior(cameraConfig.behaviors[name], focusMeshes);
  283. }
  284. };
  285. const sceneExtends = this.scene.getWorldExtends((mesh) => {
  286. return !this.environmentHelper || (mesh !== this.environmentHelper.ground && mesh !== this.environmentHelper.rootMesh && mesh !== this.environmentHelper.skybox);
  287. });
  288. const sceneDiagonal = sceneExtends.max.subtract(sceneExtends.min);
  289. const sceneDiagonalLenght = sceneDiagonal.length();
  290. if (isFinite(sceneDiagonalLenght))
  291. this.camera.upperRadiusLimit = sceneDiagonalLenght * 3;
  292. this.onCameraConfiguredObservable.notifyObservers({
  293. sceneManager: this,
  294. object: this.camera,
  295. newConfiguration: cameraConfig,
  296. model
  297. });
  298. }
  299. protected _configureEnvironment(skyboxConifguration?: ISkyboxConfiguration | boolean, groundConfiguration?: IGroundConfiguration | boolean, model?: ViewerModel) {
  300. if (!skyboxConifguration && !groundConfiguration) {
  301. if (this.environmentHelper) {
  302. this.environmentHelper.dispose();
  303. delete this.environmentHelper;
  304. };
  305. return Promise.resolve(this.scene);
  306. }
  307. const options: Partial<IEnvironmentHelperOptions> = {
  308. createGround: !!groundConfiguration,
  309. createSkybox: !!skyboxConifguration,
  310. setupImageProcessing: false // will be done at the scene level!
  311. };
  312. if (groundConfiguration) {
  313. let groundConfig = (typeof groundConfiguration === 'boolean') ? {} : groundConfiguration;
  314. let groundSize = groundConfig.size || (typeof skyboxConifguration === 'object' && skyboxConifguration.scale);
  315. if (groundSize) {
  316. options.groundSize = groundSize;
  317. }
  318. options.enableGroundShadow = groundConfig === true || groundConfig.receiveShadows;
  319. if (groundConfig.shadowLevel !== undefined) {
  320. options.groundShadowLevel = groundConfig.shadowLevel;
  321. }
  322. options.enableGroundMirror = !!groundConfig.mirror;
  323. if (groundConfig.texture) {
  324. options.groundTexture = groundConfig.texture;
  325. }
  326. if (groundConfig.color) {
  327. options.groundColor = new Color3(groundConfig.color.r, groundConfig.color.g, groundConfig.color.b)
  328. }
  329. if (groundConfig.opacity !== undefined) {
  330. options.groundOpacity = groundConfig.opacity;
  331. }
  332. if (groundConfig.mirror) {
  333. options.enableGroundMirror = true;
  334. // to prevent undefines
  335. if (typeof groundConfig.mirror === "object") {
  336. if (groundConfig.mirror.amount !== undefined)
  337. options.groundMirrorAmount = groundConfig.mirror.amount;
  338. if (groundConfig.mirror.sizeRatio !== undefined)
  339. options.groundMirrorSizeRatio = groundConfig.mirror.sizeRatio;
  340. if (groundConfig.mirror.blurKernel !== undefined)
  341. options.groundMirrorBlurKernel = groundConfig.mirror.blurKernel;
  342. if (groundConfig.mirror.fresnelWeight !== undefined)
  343. options.groundMirrorFresnelWeight = groundConfig.mirror.fresnelWeight;
  344. if (groundConfig.mirror.fallOffDistance !== undefined)
  345. options.groundMirrorFallOffDistance = groundConfig.mirror.fallOffDistance;
  346. if (this._defaultPipelineTextureType !== undefined)
  347. options.groundMirrorTextureType = this._defaultPipelineTextureType;
  348. }
  349. }
  350. }
  351. let postInitSkyboxMaterial = false;
  352. if (skyboxConifguration) {
  353. let conf = skyboxConifguration === true ? {} : skyboxConifguration;
  354. if (conf.material && conf.material.imageProcessingConfiguration) {
  355. options.setupImageProcessing = false; // will be configured later manually.
  356. }
  357. let skyboxSize = conf.scale;
  358. if (skyboxSize) {
  359. options.skyboxSize = skyboxSize;
  360. }
  361. options.sizeAuto = !options.skyboxSize;
  362. if (conf.color) {
  363. options.skyboxColor = new Color3(conf.color.r, conf.color.g, conf.color.b)
  364. }
  365. if (conf.cubeTexture && conf.cubeTexture.url) {
  366. if (typeof conf.cubeTexture.url === "string") {
  367. options.skyboxTexture = conf.cubeTexture.url;
  368. } else {
  369. // init later!
  370. postInitSkyboxMaterial = true;
  371. }
  372. }
  373. if (conf.material && conf.material.imageProcessingConfiguration) {
  374. postInitSkyboxMaterial = true;
  375. }
  376. }
  377. options.setupImageProcessing = false; // TMP
  378. if (!this.environmentHelper) {
  379. this.environmentHelper = this.scene.createDefaultEnvironment(options)!;
  380. } else {
  381. // there might be a new scene! we need to dispose.
  382. // get the scene used by the envHelper
  383. let scene: Scene = this.environmentHelper.rootMesh.getScene();
  384. // is it a different scene? Oh no!
  385. if (scene !== this.scene) {
  386. this.environmentHelper.dispose();
  387. this.environmentHelper = this.scene.createDefaultEnvironment(options)!;
  388. } else {
  389. this.environmentHelper.updateOptions(options)!;
  390. }
  391. }
  392. if (postInitSkyboxMaterial) {
  393. let skyboxMaterial = this.environmentHelper.skyboxMaterial;
  394. if (skyboxMaterial) {
  395. if (typeof skyboxConifguration === 'object' && skyboxConifguration.material && skyboxConifguration.material.imageProcessingConfiguration) {
  396. extendClassWithConfig(skyboxMaterial.imageProcessingConfiguration, skyboxConifguration.material.imageProcessingConfiguration);
  397. }
  398. }
  399. }
  400. this.onEnvironmentConfiguredObservable.notifyObservers({
  401. sceneManager: this,
  402. object: this.environmentHelper,
  403. newConfiguration: {
  404. skybox: skyboxConifguration,
  405. ground: groundConfiguration
  406. },
  407. model
  408. });
  409. }
  410. /**
  411. * configure the lights.
  412. *
  413. * @param lightsConfiguration the (new) light(s) configuration
  414. * @param model optionally use the model to configure the camera.
  415. */
  416. protected _configureLights(lightsConfiguration: { [name: string]: ILightConfiguration | boolean } = {}, model?: ViewerModel) {
  417. let focusMeshes = model ? model.meshes : this.scene.meshes;
  418. // sanity check!
  419. if (!Object.keys(lightsConfiguration).length) {
  420. if (!this.scene.lights.length)
  421. this.scene.createDefaultLight(true);
  422. return;
  423. };
  424. let lightsAvailable: Array<string> = this.scene.lights.map(light => light.name);
  425. // compare to the global (!) configuration object and dispose unneeded:
  426. let lightsToConfigure = Object.keys(this._viewer.configuration.lights || []);
  427. if (Object.keys(lightsToConfigure).length !== lightsAvailable.length) {
  428. lightsAvailable.forEach(lName => {
  429. if (lightsToConfigure.indexOf(lName) === -1) {
  430. this.scene.getLightByName(lName)!.dispose()
  431. }
  432. });
  433. }
  434. Object.keys(lightsConfiguration).forEach((name, idx) => {
  435. let lightConfig: ILightConfiguration = { type: 0 };
  436. if (typeof lightsConfiguration[name] === 'object') {
  437. lightConfig = <ILightConfiguration>lightsConfiguration[name];
  438. }
  439. lightConfig.name = name;
  440. let light: Light;
  441. // light is not already available
  442. if (lightsAvailable.indexOf(name) === -1) {
  443. let constructor = Light.GetConstructorFromName(lightConfig.type, lightConfig.name, this.scene);
  444. if (!constructor) return;
  445. light = constructor();
  446. } else {
  447. // available? get it from the scene
  448. light = <Light>this.scene.getLightByName(name);
  449. lightsAvailable = lightsAvailable.filter(ln => ln !== name);
  450. if (lightConfig.type !== undefined && light.getTypeID() !== lightConfig.type) {
  451. light.dispose();
  452. let constructor = Light.GetConstructorFromName(lightConfig.type, lightConfig.name, this.scene);
  453. if (!constructor) return;
  454. light = constructor();
  455. }
  456. }
  457. // if config set the light to false, dispose it.
  458. if (lightsConfiguration[name] === false) {
  459. light.dispose();
  460. return;
  461. }
  462. //enabled
  463. var enabled = lightConfig.enabled !== undefined ? lightConfig.enabled : !lightConfig.disabled;
  464. light.setEnabled(enabled);
  465. extendClassWithConfig(light, lightConfig);
  466. //position. Some lights don't support shadows
  467. if (light instanceof ShadowLight) {
  468. if (lightConfig.target) {
  469. if (light.setDirectionToTarget) {
  470. let target = Vector3.Zero().copyFrom(lightConfig.target as Vector3);
  471. light.setDirectionToTarget(target);
  472. }
  473. } else if (lightConfig.direction) {
  474. let direction = Vector3.Zero().copyFrom(lightConfig.direction as Vector3);
  475. light.direction = direction;
  476. }
  477. let shadowGenerator = light.getShadowGenerator();
  478. if (lightConfig.shadowEnabled && this._maxShadows) {
  479. if (!shadowGenerator) {
  480. shadowGenerator = new ShadowGenerator(512, light);
  481. // TODO blur kernel definition
  482. }
  483. extendClassWithConfig(shadowGenerator, lightConfig.shadowConfig || {});
  484. // add the focues meshes to the shadow list
  485. let shadownMap = shadowGenerator.getShadowMap();
  486. if (!shadownMap) return;
  487. let renderList = shadownMap.renderList;
  488. for (var index = 0; index < focusMeshes.length; index++) {
  489. if (Tags.MatchesQuery(focusMeshes[index], 'castShadow')) {
  490. renderList && renderList.push(focusMeshes[index]);
  491. }
  492. }
  493. } else if (shadowGenerator) {
  494. shadowGenerator.dispose();
  495. }
  496. }
  497. });
  498. this.onLightsConfiguredObservable.notifyObservers({
  499. sceneManager: this,
  500. object: this.scene.lights,
  501. newConfiguration: lightsConfiguration,
  502. model
  503. });
  504. }
  505. /**
  506. * Alters render settings to reduce features based on hardware feature limitations
  507. * @param enableHDR Allows the viewer to run in HDR mode.
  508. */
  509. protected _handleHardwareLimitations(enableHDR = true) {
  510. //flip rendering settings switches based on hardware support
  511. let maxVaryingRows = this._viewer.engine.getCaps().maxVaryingVectors;
  512. let maxFragmentSamplers = this._viewer.engine.getCaps().maxTexturesImageUnits;
  513. //shadows are disabled if there's not enough varyings for a single shadow
  514. if ((maxVaryingRows < 8) || (maxFragmentSamplers < 8)) {
  515. this._maxShadows = 0;
  516. } else {
  517. this._maxShadows = 3;
  518. }
  519. //can we render to any >= 16-bit targets (required for HDR)
  520. let caps = this._viewer.engine.getCaps();
  521. let linearHalfFloatTargets = caps.textureHalfFloatRender && caps.textureHalfFloatLinearFiltering;
  522. let linearFloatTargets = caps.textureFloatRender && caps.textureFloatLinearFiltering;
  523. this._hdrSupport = enableHDR && !!(linearFloatTargets || linearHalfFloatTargets);
  524. if (linearHalfFloatTargets) {
  525. this._defaultHighpTextureType = Engine.TEXTURETYPE_HALF_FLOAT;
  526. this._shadowGeneratorBias = 0.002;
  527. } else if (linearFloatTargets) {
  528. this._defaultHighpTextureType = Engine.TEXTURETYPE_FLOAT;
  529. this._shadowGeneratorBias = 0.001;
  530. } else {
  531. this._defaultHighpTextureType = Engine.TEXTURETYPE_UNSIGNED_INT;
  532. this._shadowGeneratorBias = 0.001;
  533. }
  534. this._defaultPipelineTextureType = this._hdrSupport ? this._defaultHighpTextureType : Engine.TEXTURETYPE_UNSIGNED_INT;
  535. }
  536. /**
  537. * Dispoe the entire viewer including the scene and the engine
  538. */
  539. public dispose() {
  540. if (this.sceneOptimizer) {
  541. this.sceneOptimizer.stop();
  542. this.sceneOptimizer.dispose();
  543. }
  544. if (this.environmentHelper) {
  545. this.environmentHelper.dispose();
  546. }
  547. this.models.forEach(model => {
  548. model.dispose();
  549. });
  550. this.models.length = 0;
  551. this.scene.dispose();
  552. }
  553. private _setCameraBehavior(behaviorConfig: number | {
  554. type: number;
  555. [propName: string]: any;
  556. }, payload: any) {
  557. let behavior: Behavior<ArcRotateCamera> | null;
  558. let type = (typeof behaviorConfig !== "object") ? behaviorConfig : behaviorConfig.type;
  559. let config: { [propName: string]: any } = (typeof behaviorConfig === "object") ? behaviorConfig : {};
  560. // constructing behavior
  561. switch (type) {
  562. case CameraBehavior.AUTOROTATION:
  563. this.camera.useAutoRotationBehavior = true;
  564. behavior = this.camera.autoRotationBehavior;
  565. break;
  566. case CameraBehavior.BOUNCING:
  567. this.camera.useBouncingBehavior = true;
  568. behavior = this.camera.bouncingBehavior;
  569. break;
  570. case CameraBehavior.FRAMING:
  571. this.camera.useFramingBehavior = true;
  572. behavior = this.camera.framingBehavior;
  573. break;
  574. default:
  575. behavior = null;
  576. break;
  577. }
  578. if (behavior) {
  579. if (typeof behaviorConfig === "object") {
  580. extendClassWithConfig(behavior, behaviorConfig);
  581. }
  582. }
  583. // post attach configuration. Some functionalities require the attached camera.
  584. switch (type) {
  585. case CameraBehavior.AUTOROTATION:
  586. break;
  587. case CameraBehavior.BOUNCING:
  588. break;
  589. case CameraBehavior.FRAMING:
  590. if (config.zoomOnBoundingInfo) {
  591. //payload is an array of meshes
  592. let meshes = <Array<AbstractMesh>>payload;
  593. let bounding = meshes[0].getHierarchyBoundingVectors();
  594. (<FramingBehavior>behavior).zoomOnBoundingInfo(bounding.min, bounding.max);
  595. }
  596. break;
  597. }
  598. }
  599. }