sceneManager.ts 65 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549
  1. import { Scene, ArcRotateCamera, Engine, Light, ShadowLight, Vector3, ShadowGenerator, Tags, CubeTexture, Quaternion, SceneOptimizer, EnvironmentHelper, SceneOptimizerOptions, Color3, IEnvironmentHelperOptions, AbstractMesh, FramingBehavior, Behavior, Observable, Color4, IGlowLayerOptions, PostProcessRenderPipeline, DefaultRenderingPipeline, StandardRenderingPipeline, SSAORenderingPipeline, SSAO2RenderingPipeline, LensRenderingPipeline, RenderTargetTexture, AnimationPropertiesOverride, Animation, Scalar, StandardMaterial, PBRMaterial, Nullable, Mesh, VRExperienceHelperOptions, VRExperienceHelper, Axis, Matrix } from 'babylonjs';
  2. import { ILightConfiguration, ISceneConfiguration, ISceneOptimizerConfiguration, ICameraConfiguration, ISkyboxConfiguration, ViewerConfiguration, IGroundConfiguration, IModelConfiguration, getConfigurationKey, IDefaultRenderingPipelineConfiguration, IVRConfiguration } from '../configuration';
  3. import { ViewerModel, ModelState } from '../model/viewerModel';
  4. import { extendClassWithConfig } from '../helper';
  5. import { CameraBehavior } from '../interfaces';
  6. import { ViewerLabs } from '../labs/viewerLabs';
  7. import { getCustomOptimizerByName } from '../optimizer/custom/';
  8. import { ObservablesManager } from '../managers/observablesManager';
  9. import { ConfigurationContainer } from '../configuration/configurationContainer';
  10. import { deepmerge } from '../helper';
  11. import { IEnvironmentMapConfiguration } from '../configuration/interfaces/environmentMapConfiguration';
  12. /**
  13. * This interface describes the structure of the variable sent with the configuration observables of the scene manager.
  14. * O - the type of object we are dealing with (Light, ArcRotateCamera, Scene, etc')
  15. * T - the configuration type
  16. */
  17. export interface IPostConfigurationCallback<OBJ, CONF> {
  18. newConfiguration: CONF;
  19. sceneManager: SceneManager;
  20. object: OBJ;
  21. model?: ViewerModel;
  22. }
  23. export class SceneManager {
  24. //Observers
  25. /**
  26. * Will notify when the scene was initialized
  27. */
  28. onSceneInitObservable: Observable<Scene>;
  29. /**
  30. * Will notify after the scene was configured. Can be used to further configure the scene
  31. */
  32. onSceneConfiguredObservable: Observable<IPostConfigurationCallback<Scene, ISceneConfiguration>>;
  33. /**
  34. * Will notify after the scene optimized was configured. Can be used to further configure the scene optimizer
  35. */
  36. onSceneOptimizerConfiguredObservable: Observable<IPostConfigurationCallback<SceneOptimizer, ISceneOptimizerConfiguration | boolean>>;
  37. /**
  38. * Will notify after the camera was configured. Can be used to further configure the camera
  39. */
  40. onCameraConfiguredObservable: Observable<IPostConfigurationCallback<ArcRotateCamera, ICameraConfiguration>>;
  41. /**
  42. * Will notify after the lights were configured. Can be used to further configure lights
  43. */
  44. onLightsConfiguredObservable: Observable<IPostConfigurationCallback<Array<Light>, { [name: string]: ILightConfiguration | boolean | number }>>;
  45. /**
  46. * Will notify after the model(s) were configured. Can be used to further configure models
  47. */
  48. onModelsConfiguredObservable: Observable<IPostConfigurationCallback<Array<ViewerModel>, IModelConfiguration>>;
  49. /**
  50. * Will notify after the envirnoment was configured. Can be used to further configure the environment
  51. */
  52. onEnvironmentConfiguredObservable: Observable<IPostConfigurationCallback<EnvironmentHelper, { skybox?: ISkyboxConfiguration | boolean, ground?: IGroundConfiguration | boolean }>>;
  53. /**
  54. * Will notify after the model(s) were configured. Can be used to further configure models
  55. */
  56. onVRConfiguredObservable: Observable<IPostConfigurationCallback<VRExperienceHelper, IVRConfiguration>>;
  57. onEnteringVRObservable: Observable<any>;
  58. onExitingVRObservable: Observable<any>;
  59. /**
  60. * The Babylon Scene of this viewer
  61. */
  62. public scene: Scene;
  63. /**
  64. * The camera used in this viewer
  65. */
  66. public camera: ArcRotateCamera;
  67. /**
  68. * Babylon's scene optimizer
  69. */
  70. public sceneOptimizer: SceneOptimizer;
  71. /**
  72. * Models displayed in this viewer.
  73. */
  74. public models: Array<ViewerModel>;
  75. /**
  76. * Babylon's environment helper of this viewer
  77. */
  78. public environmentHelper?: EnvironmentHelper;
  79. private _animationBlendingEnabled: boolean = true;
  80. //The following are configuration objects, default values.
  81. protected _defaultHighpTextureType: number;
  82. protected _shadowGeneratorBias: number;
  83. protected _defaultPipelineTextureType: number;
  84. /**
  85. * The maximum number of shadows supported by the curent viewer
  86. */
  87. protected _maxShadows: number;
  88. /**
  89. * is HDR supported?
  90. */
  91. private _hdrSupport: boolean;
  92. private readonly _white = Color3.White();
  93. private _forceShadowUpdate: boolean = false;
  94. /**
  95. * The labs variable consists of objects that will have their API change.
  96. * Please be careful when using labs in production.
  97. */
  98. public labs: ViewerLabs;
  99. private _defaultRenderingPipeline: Nullable<DefaultRenderingPipeline>;
  100. private _assetsRootURL: string;
  101. public get defaultRenderingPipeline() {
  102. return this._defaultRenderingPipeline;
  103. }
  104. protected _vrHelper?: VRExperienceHelper;
  105. public get vrHelper() {
  106. return this._vrHelper;
  107. }
  108. constructor(private _engine: Engine, private _configurationContainer: ConfigurationContainer, private _observablesManager?: ObservablesManager) {
  109. this.models = [];
  110. this.onCameraConfiguredObservable = new Observable();
  111. this.onLightsConfiguredObservable = new Observable();
  112. this.onModelsConfiguredObservable = new Observable();
  113. this.onSceneConfiguredObservable = new Observable();
  114. this.onSceneInitObservable = new Observable();
  115. this.onSceneOptimizerConfiguredObservable = new Observable();
  116. this.onEnvironmentConfiguredObservable = new Observable();
  117. this.onVRConfiguredObservable = new Observable();
  118. this.onEnteringVRObservable = new Observable();
  119. this.onExitingVRObservable = new Observable();
  120. //this._viewer.onEngineInitObservable.add(() => {
  121. this._handleHardwareLimitations();
  122. //});
  123. this.onSceneInitObservable.add((scene) => {
  124. this.scene.animationPropertiesOverride = this.scene.animationPropertiesOverride || new AnimationPropertiesOverride();
  125. this.labs = new ViewerLabs(scene);
  126. let updateShadows = () => {
  127. for (let light of this.scene.lights) {
  128. let generator = light.getShadowGenerator();
  129. if (generator) {
  130. // Processing shadows if animates
  131. let shadowMap = generator.getShadowMap();
  132. if (shadowMap) {
  133. shadowMap.refreshRate = RenderTargetTexture.REFRESHRATE_RENDER_ONCE;
  134. }
  135. }
  136. }
  137. }
  138. scene.registerBeforeRender(() => {
  139. if (this._forceShadowUpdate || (scene.animatables && scene.animatables.length > 0)) {
  140. // make sure all models are loaded
  141. updateShadows();
  142. this._forceShadowUpdate = false;
  143. } else if (!(this.models.every((model) => {
  144. if (!model.shadowsRenderedAfterLoad) {
  145. model.shadowsRenderedAfterLoad = true;
  146. return false;
  147. }
  148. return model.state === ModelState.COMPLETE && !model.currentAnimation
  149. }))) {
  150. updateShadows();
  151. }
  152. });
  153. return this._observablesManager && this._observablesManager.onSceneInitObservable.notifyObserversWithPromise(this.scene);
  154. });
  155. if (this._observablesManager) {
  156. this._observablesManager.onModelLoadedObservable.add((model) => {
  157. for (let light of this.scene.lights) {
  158. let generator = light.getShadowGenerator();
  159. if (generator) {
  160. // Processing shadows if animates
  161. let shadowMap = generator.getShadowMap();
  162. if (shadowMap) {
  163. shadowMap.refreshRate = RenderTargetTexture.REFRESHRATE_RENDER_ONCE;
  164. }
  165. }
  166. }
  167. this._focusOnModel(model);
  168. });
  169. this._observablesManager.onModelAddedObservable.add(model => {
  170. this.models.push(model);
  171. });
  172. this._observablesManager.onModelRemovedObservable.add(model => {
  173. this.models.splice(this.models.indexOf(model), 1);
  174. })
  175. }
  176. }
  177. /**
  178. * Returns a boolean representing HDR support
  179. */
  180. public get isHdrSupported() {
  181. return this._hdrSupport;
  182. }
  183. /**
  184. * Return the main color defined in the configuration.
  185. */
  186. public get mainColor(): Color3 {
  187. return this._configurationContainer.mainColor;
  188. }
  189. public get reflectionColor(): Color3 {
  190. return this._configurationContainer.reflectionColor;
  191. }
  192. public get animationBlendingEnabled() {
  193. return this.scene && this.scene.animationPropertiesOverride!.enableBlending;
  194. }
  195. public set animationBlendingEnabled(value: boolean) {
  196. this.scene.animationPropertiesOverride!.enableBlending = value;
  197. }
  198. public get observablesManager() {
  199. return this._observablesManager;
  200. }
  201. private _processShadows: boolean = true;
  202. /**
  203. * The flag defining whether shadows are rendered constantly or once.
  204. */
  205. public get processShadows() {
  206. return this._processShadows;
  207. }
  208. /**
  209. * Should shadows be rendered every frame, or only once and stop.
  210. * This can be used to optimize a scene.
  211. *
  212. * Not that the shadows will NOT disapear but will remain in place.
  213. * @param process if true shadows will be updated once every frame. if false they will stop being updated.
  214. */
  215. public set processShadows(process: boolean) {
  216. let refreshType = process ? RenderTargetTexture.REFRESHRATE_RENDER_ONEVERYFRAME : RenderTargetTexture.REFRESHRATE_RENDER_ONCE;
  217. for (let light of this.scene.lights) {
  218. let generator = light.getShadowGenerator();
  219. if (generator) {
  220. let shadowMap = generator.getShadowMap();
  221. if (shadowMap) {
  222. shadowMap.refreshRate = refreshType;
  223. }
  224. }
  225. }
  226. this._processShadows = process;
  227. }
  228. private _groundEnabled: boolean = true;
  229. public get groundEnabled() {
  230. return this._groundEnabled;
  231. }
  232. public set groundEnabled(newValue: boolean) {
  233. if (newValue === this._groundEnabled) return;
  234. this._groundEnabled = newValue;
  235. if (this.environmentHelper && this.environmentHelper.ground) {
  236. this.environmentHelper.ground.setEnabled(this._groundEnabled);
  237. }
  238. }
  239. private _groundMirrorEnabled = true;
  240. /**
  241. * gets wether the reflection is disabled.
  242. */
  243. public get groundMirrorEnabled(): boolean {
  244. return this._groundMirrorEnabled;
  245. }
  246. /**
  247. * sets wether the reflection is disabled.
  248. */
  249. public set groundMirrorEnabled(value: boolean) {
  250. if (this._groundMirrorEnabled === value) {
  251. return;
  252. }
  253. this._groundMirrorEnabled = value;
  254. if (this.environmentHelper && this.environmentHelper.groundMaterial && this.environmentHelper.groundMirror) {
  255. if (!value) {
  256. this.environmentHelper.groundMaterial.reflectionTexture = null;
  257. } else {
  258. this.environmentHelper.groundMaterial.reflectionTexture = this.environmentHelper.groundMirror;
  259. }
  260. }
  261. }
  262. private _defaultRenderingPipelineEnabled: boolean = false;
  263. public get defaultRenderingPipelineEnabled() {
  264. return this._defaultRenderingPipelineEnabled;
  265. }
  266. public set defaultRenderingPipelineEnabled(value: boolean) {
  267. if (value === this._defaultRenderingPipelineEnabled) {
  268. return;
  269. }
  270. this._defaultRenderingPipelineEnabled = value;
  271. this._rebuildPostprocesses();
  272. if (this._defaultRenderingPipeline) {
  273. this._defaultRenderingPipelineShouldBuild = false;
  274. this._defaultRenderingPipeline.prepare();
  275. this.scene.imageProcessingConfiguration.applyByPostProcess = true;
  276. }
  277. }
  278. /**
  279. * Sets the engine flags to unlock all babylon features.
  280. * Can also be configured using the scene.flags configuration object
  281. */
  282. public unlockBabylonFeatures() {
  283. this.scene.shadowsEnabled = true;
  284. this.scene.particlesEnabled = true;
  285. this.scene.postProcessesEnabled = true;
  286. this.scene.collisionsEnabled = true;
  287. this.scene.lightsEnabled = true;
  288. this.scene.texturesEnabled = true;
  289. this.scene.lensFlaresEnabled = true;
  290. this.scene.proceduralTexturesEnabled = true;
  291. this.scene.renderTargetsEnabled = true;
  292. this.scene.spritesEnabled = true;
  293. this.scene.skeletonsEnabled = true;
  294. this.scene.audioEnabled = true;
  295. }
  296. /**
  297. * initialize the scene. Calling this function again will dispose the old scene, if exists.
  298. */
  299. public initScene(sceneConfiguration: ISceneConfiguration = {}, optimizerConfiguration?: boolean | ISceneOptimizerConfiguration): Promise<Scene> {
  300. // if the scen exists, dispose it.
  301. if (this.scene) {
  302. this.scene.dispose();
  303. }
  304. // create a new scene
  305. this.scene = new Scene(this._engine);
  306. this._configurationContainer.scene = this.scene;
  307. // set a default PBR material
  308. if (!sceneConfiguration.defaultMaterial) {
  309. var defaultMaterial = new BABYLON.PBRMaterial('defaultMaterial', this.scene);
  310. defaultMaterial.reflectivityColor = new BABYLON.Color3(0.1, 0.1, 0.1);
  311. defaultMaterial.microSurface = 0.6;
  312. if (this.scene.defaultMaterial) {
  313. this.scene.defaultMaterial.dispose();
  314. }
  315. this.scene.defaultMaterial = defaultMaterial;
  316. }
  317. this.scene.animationPropertiesOverride = new AnimationPropertiesOverride();
  318. Animation.AllowMatricesInterpolation = true;
  319. /*if (sceneConfiguration.glow) {
  320. let options: Partial<IGlowLayerOptions> = {
  321. mainTextureFixedSize: 512
  322. };
  323. if (typeof sceneConfiguration.glow === 'object') {
  324. options = sceneConfiguration.glow
  325. }
  326. var gl = new BABYLON.GlowLayer("glow", this.scene, options);
  327. }*/
  328. return this.onSceneInitObservable.notifyObserversWithPromise(this.scene);
  329. }
  330. public clearScene(clearModels: boolean = true, clearLights: boolean = false) {
  331. if (clearModels) {
  332. this.models.forEach(m => m.dispose());
  333. this.models.length = 0;
  334. }
  335. if (clearLights) {
  336. this.scene.lights.forEach(l => l.dispose());
  337. }
  338. }
  339. private _globalConfiguration: ViewerConfiguration = {};
  340. /**
  341. * This will update the scene's configuration, including camera, lights, environment.
  342. * @param newConfiguration the delta that should be configured. This includes only the changes
  343. * @param globalConfiguration The global configuration object, after the new configuration was merged into it
  344. */
  345. public updateConfiguration(newConfiguration: Partial<ViewerConfiguration>) {
  346. if (this._configurationContainer) {
  347. this._globalConfiguration = this._configurationContainer.configuration;
  348. } else {
  349. this._globalConfiguration = newConfiguration;
  350. }
  351. // update scene configuration
  352. if (newConfiguration.scene) {
  353. this._configureScene(newConfiguration.scene);
  354. }
  355. // optimizer
  356. if (newConfiguration.optimizer !== undefined) {
  357. this._configureOptimizer(newConfiguration.optimizer);
  358. }
  359. // configure model
  360. /*if (newConfiguration.model && typeof newConfiguration.model === 'object') {
  361. this._configureModel(newConfiguration.model);
  362. }*/
  363. // lights
  364. this._configureLights(newConfiguration.lights);
  365. // environment
  366. if (newConfiguration.skybox !== undefined || newConfiguration.ground !== undefined) {
  367. this._configureEnvironment(newConfiguration.skybox, newConfiguration.ground);
  368. }
  369. // camera
  370. this._configureCamera(newConfiguration.camera);
  371. if (newConfiguration.environmentMap !== undefined) {
  372. this._configureEnvironmentMap(newConfiguration.environmentMap);
  373. }
  374. if (newConfiguration.vr !== undefined) {
  375. this._configureVR(newConfiguration.vr);
  376. }
  377. if (newConfiguration.lab) {
  378. // rendering piplines
  379. if (newConfiguration.lab.defaultRenderingPipelines) {
  380. let pipelineConfig = newConfiguration.lab.defaultRenderingPipelines;
  381. if (typeof pipelineConfig === 'boolean') {
  382. this.defaultRenderingPipelineEnabled = pipelineConfig;
  383. } else {
  384. this.defaultRenderingPipelineEnabled = true;
  385. }
  386. }
  387. if (this.environmentHelper && newConfiguration.lab.environmentMainColor) {
  388. let mainColor = new Color3().copyFrom(newConfiguration.lab.environmentMainColor as Color3);
  389. this.environmentHelper.setMainColor(mainColor);
  390. }
  391. if (newConfiguration.lab.globalLightRotation !== undefined) {
  392. // rotate all lights that are shadow lights
  393. this.scene.lights.filter(light => light instanceof ShadowLight).forEach(light => {
  394. // casting and '!' are safe, due to the constraints tested before
  395. this.labs.rotateShadowLight(<ShadowLight>light, newConfiguration.lab!.globalLightRotation!);
  396. });
  397. this._forceShadowUpdate = true;
  398. }
  399. }
  400. if (this._defaultRenderingPipeline && this._defaultRenderingPipeline.imageProcessing) {
  401. this._defaultRenderingPipeline.imageProcessing.fromLinearSpace = true;
  402. }
  403. if (this._defaultRenderingPipelineShouldBuild && this._defaultRenderingPipeline) {
  404. this._defaultRenderingPipelineShouldBuild = false;
  405. this._defaultRenderingPipeline.prepare();
  406. }
  407. }
  408. private _defaultRenderingPipelineShouldBuild: boolean = true;
  409. private _rebuildPostprocesses(configuration?: IDefaultRenderingPipelineConfiguration): void {
  410. if (!this._defaultRenderingPipelineEnabled || !getConfigurationKey("scene.imageProcessingConfiguration.isEnabled", this._globalConfiguration)) {
  411. if (this._defaultRenderingPipeline) {
  412. this._defaultRenderingPipeline.dispose();
  413. this._defaultRenderingPipeline = null;
  414. this.scene.autoClearDepthAndStencil = true;
  415. this.scene.autoClear = true;
  416. this.scene.imageProcessingConfiguration.applyByPostProcess = false;
  417. }
  418. return;
  419. }
  420. let pipelineConfig = configuration || (this._globalConfiguration.lab && this._globalConfiguration.lab.defaultRenderingPipelines);
  421. if (pipelineConfig) {
  422. if (!this._defaultRenderingPipeline) {
  423. // Create pipeline in manual mode to avoid triggering multiple shader compilations
  424. this._defaultRenderingPipeline = new DefaultRenderingPipeline("default rendering pipeline", this._hdrSupport, this.scene, [this.camera], false);
  425. }
  426. this.scene.autoClear = false;
  427. this.scene.autoClearDepthAndStencil = false;
  428. this._defaultRenderingPipelineShouldBuild = true;
  429. let bloomEnabled = this._bloomEnabled;
  430. if (typeof pipelineConfig !== 'boolean') {
  431. extendClassWithConfig(this._defaultRenderingPipeline, pipelineConfig);
  432. this._bloomEnabled = !!pipelineConfig.bloomEnabled;
  433. this._fxaaEnabled = !!pipelineConfig.fxaaEnabled;
  434. bloomEnabled = this._bloomEnabled && pipelineConfig.bloomWeight !== undefined && pipelineConfig.bloomWeight > 0;
  435. this._defaultRenderingPipeline.bloomWeight = (pipelineConfig.bloomWeight !== undefined && pipelineConfig.bloomWeight) || (this._defaultRenderingPipeline.bloomWeight);
  436. }
  437. this._defaultRenderingPipeline.bloomEnabled = bloomEnabled;
  438. this._defaultRenderingPipeline.fxaaEnabled = this.fxaaEnabled;
  439. }
  440. }
  441. // default from rendering pipeline
  442. private _bloomEnabled: boolean = false;
  443. public get bloomEnabled() {
  444. return this._bloomEnabled;
  445. }
  446. public set bloomEnabled(value: boolean) {
  447. if (this._bloomEnabled === value) {
  448. return;
  449. }
  450. this._bloomEnabled = value;
  451. this._rebuildPostprocesses();
  452. if (this._defaultRenderingPipeline) {
  453. this._defaultRenderingPipelineShouldBuild = false;
  454. this._defaultRenderingPipeline.prepare();
  455. this.scene.imageProcessingConfiguration.applyByPostProcess = true;
  456. }
  457. }
  458. // default from rendering pipeline
  459. private _fxaaEnabled: boolean = false;
  460. public get fxaaEnabled() {
  461. return this._fxaaEnabled;
  462. }
  463. public set fxaaEnabled(value: boolean) {
  464. if (this._fxaaEnabled === value) {
  465. return;
  466. }
  467. this._fxaaEnabled = value;
  468. this._rebuildPostprocesses();
  469. if (this._defaultRenderingPipeline) {
  470. this._defaultRenderingPipelineShouldBuild = false;
  471. this._defaultRenderingPipeline.prepare();
  472. this.scene.imageProcessingConfiguration.applyByPostProcess = true;
  473. }
  474. }
  475. /**
  476. * internally configure the scene using the provided configuration.
  477. * The scene will not be recreated, but just updated.
  478. * @param sceneConfig the (new) scene configuration
  479. */
  480. protected _configureScene(sceneConfig: ISceneConfiguration) {
  481. // sanity check!
  482. if (!this.scene) {
  483. return;
  484. }
  485. let cc = sceneConfig.clearColor;
  486. let oldcc = this.scene.clearColor;
  487. if (cc) {
  488. if (cc.r !== undefined) {
  489. oldcc.r = cc.r;
  490. }
  491. if (cc.g !== undefined) {
  492. oldcc.g = cc.g
  493. }
  494. if (cc.b !== undefined) {
  495. oldcc.b = cc.b
  496. }
  497. if (cc.a !== undefined) {
  498. oldcc.a = cc.a
  499. }
  500. }
  501. if (sceneConfig.assetsRootURL) {
  502. this._assetsRootURL = sceneConfig.assetsRootURL;
  503. }
  504. // image processing configuration - optional.
  505. if (sceneConfig.imageProcessingConfiguration) {
  506. extendClassWithConfig(this.scene.imageProcessingConfiguration, sceneConfig.imageProcessingConfiguration);
  507. }
  508. //animation properties override
  509. if (sceneConfig.animationPropertiesOverride) {
  510. extendClassWithConfig(this.scene.animationPropertiesOverride, sceneConfig.animationPropertiesOverride);
  511. }
  512. if (sceneConfig.environmentTexture) {
  513. if (!(this.scene.environmentTexture && (<CubeTexture>this.scene.environmentTexture).url === sceneConfig.environmentTexture)) {
  514. if (this.scene.environmentTexture && this.scene.environmentTexture.dispose) {
  515. this.scene.environmentTexture.dispose();
  516. }
  517. const environmentTexture = CubeTexture.CreateFromPrefilteredData(sceneConfig.environmentTexture, this.scene);
  518. this.scene.environmentTexture = environmentTexture;
  519. }
  520. }
  521. if (sceneConfig.debug === true) {
  522. this.scene.debugLayer.show();
  523. } else if (sceneConfig.debug === false) {
  524. if (this.scene.debugLayer.isVisible()) {
  525. this.scene.debugLayer.hide();
  526. }
  527. }
  528. if (sceneConfig.disableHdr) {
  529. this._handleHardwareLimitations(false);
  530. } else {
  531. this._handleHardwareLimitations(true);
  532. }
  533. if (sceneConfig.renderInBackground !== undefined) {
  534. this._engine.renderEvenInBackground = !!sceneConfig.renderInBackground;
  535. }
  536. let canvas = this._engine.getRenderingCanvas();
  537. if (canvas) {
  538. if (this.camera && sceneConfig.disableCameraControl) {
  539. this.camera.detachControl(canvas);
  540. } else if (this.camera && sceneConfig.disableCameraControl === false) {
  541. this.camera.attachControl(canvas);
  542. }
  543. }
  544. if (sceneConfig.defaultMaterial) {
  545. let conf = sceneConfig.defaultMaterial;
  546. if ((conf.materialType === 'standard' && this.scene.defaultMaterial.getClassName() !== 'StandardMaterial') ||
  547. (conf.materialType === 'pbr' && this.scene.defaultMaterial.getClassName() !== 'PBRMaterial')) {
  548. this.scene.defaultMaterial.dispose();
  549. if (conf.materialType === 'standard') {
  550. this.scene.defaultMaterial = new StandardMaterial("defaultMaterial", this.scene);
  551. } else {
  552. this.scene.defaultMaterial = new PBRMaterial("defaultMaterial", this.scene);
  553. }
  554. }
  555. extendClassWithConfig(this.scene.defaultMaterial, conf);
  556. }
  557. if (sceneConfig.flags) {
  558. extendClassWithConfig(this.scene, sceneConfig.flags);
  559. }
  560. this.onSceneConfiguredObservable.notifyObservers({
  561. sceneManager: this,
  562. object: this.scene,
  563. newConfiguration: sceneConfig
  564. });
  565. }
  566. /**
  567. * Configure the scene optimizer.
  568. * The existing scene optimizer will be disposed and a new one will be created.
  569. * @param optimizerConfig the (new) optimizer configuration
  570. */
  571. protected _configureOptimizer(optimizerConfig: ISceneOptimizerConfiguration | boolean) {
  572. if (typeof optimizerConfig === 'boolean') {
  573. if (this.sceneOptimizer) {
  574. this.sceneOptimizer.stop();
  575. this.sceneOptimizer.dispose();
  576. delete this.sceneOptimizer;
  577. }
  578. if (optimizerConfig) {
  579. this.sceneOptimizer = new SceneOptimizer(this.scene);
  580. this.sceneOptimizer.start();
  581. }
  582. } else {
  583. let optimizerOptions: SceneOptimizerOptions = new SceneOptimizerOptions(optimizerConfig.targetFrameRate, optimizerConfig.trackerDuration);
  584. // check for degradation
  585. if (optimizerConfig.degradation) {
  586. switch (optimizerConfig.degradation) {
  587. case "low":
  588. optimizerOptions = SceneOptimizerOptions.LowDegradationAllowed(optimizerConfig.targetFrameRate);
  589. break;
  590. case "moderate":
  591. optimizerOptions = SceneOptimizerOptions.ModerateDegradationAllowed(optimizerConfig.targetFrameRate);
  592. break;
  593. case "hight":
  594. optimizerOptions = SceneOptimizerOptions.HighDegradationAllowed(optimizerConfig.targetFrameRate);
  595. break;
  596. }
  597. }
  598. if (this.sceneOptimizer) {
  599. this.sceneOptimizer.stop();
  600. this.sceneOptimizer.dispose()
  601. }
  602. if (optimizerConfig.custom) {
  603. let customOptimizer = getCustomOptimizerByName(optimizerConfig.custom, optimizerConfig.improvementMode);
  604. if (customOptimizer) {
  605. optimizerOptions.addCustomOptimization(() => {
  606. return customOptimizer(this);
  607. }, () => {
  608. return `Babylon Viewer ${optimizerConfig.custom} custom optimization`;
  609. });
  610. }
  611. }
  612. this.sceneOptimizer = new SceneOptimizer(this.scene, optimizerOptions, optimizerConfig.autoGeneratePriorities, optimizerConfig.improvementMode);
  613. this.sceneOptimizer.start();
  614. }
  615. this.onSceneOptimizerConfiguredObservable.notifyObservers({
  616. sceneManager: this,
  617. object: this.sceneOptimizer,
  618. newConfiguration: optimizerConfig
  619. });
  620. }
  621. /**
  622. * configure all models using the configuration.
  623. * @param modelConfiguration the configuration to use to reconfigure the models
  624. */
  625. /*protected _configureModel(modelConfiguration: Partial<IModelConfiguration>) {
  626. this.models.forEach(model => {
  627. model.updateConfiguration(modelConfiguration);
  628. });
  629. this.onModelsConfiguredObservable.notifyObservers({
  630. sceneManager: this,
  631. object: this.models,
  632. newConfiguration: modelConfiguration
  633. });
  634. }*/
  635. protected _configureVR(vrConfig: IVRConfiguration) {
  636. if (vrConfig.disabled) {
  637. if (this._vrHelper) {
  638. if (this._vrHelper.isInVRMode) {
  639. this._vrHelper.exitVR();
  640. }
  641. this._vrHelper.dispose();
  642. this._vrHelper = undefined;
  643. }
  644. return;
  645. }
  646. let vrOptions: VRExperienceHelperOptions = deepmerge({
  647. useCustomVRButton: true,
  648. createDeviceOrientationCamera: false,
  649. trackPosition: true
  650. }, vrConfig.vrOptions || {});
  651. this._vrHelper = this.scene.createDefaultVRExperience(vrOptions);
  652. if (!vrConfig.disableInteractions) {
  653. this._vrHelper.enableInteractions();
  654. }
  655. if (!vrConfig.disableTeleportation) {
  656. let floorMeshName = vrConfig.overrideFloorMeshName || "BackgroundPlane";
  657. this._vrHelper.enableTeleportation({
  658. floorMeshName
  659. });
  660. }
  661. if (vrConfig.rotateUsingControllers) {
  662. let rotationOffset: Quaternion | null;
  663. this._vrHelper.onControllerMeshLoadedObservable.add((controller) => {
  664. controller.onTriggerStateChangedObservable.add((data) => {
  665. if (controller.mesh && controller.mesh.rotationQuaternion) {
  666. if (data.pressed) {
  667. if (!rotationOffset) {
  668. this.models[0].rootMesh.rotationQuaternion = this.models[0].rootMesh.rotationQuaternion || new Quaternion();
  669. rotationOffset = controller.mesh.rotationQuaternion.conjugate().multiply(this.models[0].rootMesh.rotationQuaternion!);
  670. }
  671. } else {
  672. rotationOffset = null;
  673. }
  674. }
  675. });
  676. this.scene.registerBeforeRender(() => {
  677. if (this.models[0]) {
  678. if (rotationOffset && controller.mesh && controller.mesh.rotationQuaternion) {
  679. this.models[0].rootMesh.rotationQuaternion!.copyFrom(controller.mesh.rotationQuaternion).multiplyInPlace(rotationOffset);
  680. } else {
  681. this.models[0].rootMesh.rotationQuaternion = null;
  682. }
  683. }
  684. });
  685. });
  686. }
  687. this._vrHelper.onEnteringVRObservable.add(() => {
  688. this.onEnteringVRObservable.notifyObservers(this);
  689. });
  690. this._vrHelper.onExitingVRObservable.add(() => {
  691. this.onExitingVRObservable.notifyObservers(this);
  692. });
  693. this.onVRConfiguredObservable.notifyObservers({
  694. sceneManager: this,
  695. object: this._vrHelper,
  696. newConfiguration: vrConfig
  697. });
  698. }
  699. protected _configureEnvironmentMap(environmentMapConfiguration: IEnvironmentMapConfiguration): any {
  700. if (environmentMapConfiguration.texture) {
  701. this.scene.environmentTexture = new BABYLON.CubeTexture(this._getAssetUrl(environmentMapConfiguration.texture), this.scene);
  702. }
  703. //sanity check
  704. if (this.scene.environmentTexture) {
  705. let rotatquatRotationionY = Quaternion.RotationAxis(Axis.Y, environmentMapConfiguration.rotationY || 0);
  706. Matrix.FromQuaternionToRef(rotatquatRotationionY, this.scene.environmentTexture.getReflectionTextureMatrix());
  707. }
  708. // process mainColor changes:
  709. if (environmentMapConfiguration.mainColor) {
  710. this._configurationContainer.mainColor = this.mainColor || Color3.White();
  711. let mc = environmentMapConfiguration.mainColor;
  712. if (mc.r !== undefined) {
  713. this.mainColor.r = mc.r;
  714. }
  715. if (mc.g !== undefined) {
  716. this.mainColor.g = mc.g
  717. }
  718. if (mc.b !== undefined) {
  719. this.mainColor.b = mc.b
  720. }
  721. this.reflectionColor.copyFrom(this.mainColor);
  722. let environmentTint = getConfigurationKey("environmentMap.tintLevel", this._globalConfiguration) || 0;
  723. // reflection color
  724. this.reflectionColor.toLinearSpaceToRef(this.reflectionColor);
  725. this.reflectionColor.scaleToRef(1 / this.scene.imageProcessingConfiguration.exposure, this.reflectionColor);
  726. let tmpColor3 = Color3.Lerp(this._white, this.reflectionColor, environmentTint);
  727. this.reflectionColor.copyFrom(tmpColor3);
  728. //update the environment, if exists
  729. if (this.environmentHelper) {
  730. if (this.environmentHelper.groundMaterial) {
  731. this.environmentHelper.groundMaterial._perceptualColor = this.mainColor;
  732. }
  733. if (this.environmentHelper.skyboxMaterial) {
  734. this.environmentHelper.skyboxMaterial._perceptualColor = this.mainColor;
  735. }
  736. }
  737. }
  738. }
  739. /**
  740. * (Re) configure the camera. The camera will only be created once and from this point will only be reconfigured.
  741. * @param cameraConfig the new camera configuration
  742. * @param model optionally use the model to configure the camera.
  743. */
  744. protected _configureCamera(cameraConfig: ICameraConfiguration = {}) {
  745. if (!this.scene.activeCamera) {
  746. let attachControl = true;
  747. if (this._globalConfiguration.scene && this._globalConfiguration.scene.disableCameraControl) {
  748. attachControl = false;
  749. }
  750. this.scene.createDefaultCamera(true, true, attachControl);
  751. this.camera = <ArcRotateCamera>this.scene.activeCamera!;
  752. this.camera.setTarget(Vector3.Zero());
  753. }
  754. if (!this.camera) {
  755. this.camera = <ArcRotateCamera>this.scene.activeCamera!;
  756. }
  757. if (cameraConfig.position) {
  758. let newPosition = this.camera.position.clone();
  759. extendClassWithConfig(newPosition, cameraConfig.position);
  760. this.camera.setPosition(newPosition);
  761. }
  762. if (cameraConfig.target) {
  763. let newTarget = this.camera.target.clone();
  764. extendClassWithConfig(newTarget, cameraConfig.target);
  765. this.camera.setTarget(newTarget);
  766. } /*else if (this.models.length && !cameraConfig.disableAutoFocus) {
  767. this._focusOnModel(this.models[0]);
  768. }*/
  769. if (cameraConfig.rotation) {
  770. this.camera.rotationQuaternion = new Quaternion(cameraConfig.rotation.x || 0, cameraConfig.rotation.y || 0, cameraConfig.rotation.z || 0, cameraConfig.rotation.w || 0)
  771. }
  772. if (cameraConfig.behaviors) {
  773. for (let name in cameraConfig.behaviors) {
  774. if (cameraConfig.behaviors[name] !== undefined) {
  775. this._setCameraBehavior(name, cameraConfig.behaviors[name]);
  776. }
  777. }
  778. };
  779. const sceneExtends = this.scene.getWorldExtends((mesh) => {
  780. return !this.environmentHelper || (mesh !== this.environmentHelper.ground && mesh !== this.environmentHelper.rootMesh && mesh !== this.environmentHelper.skybox);
  781. });
  782. const sceneDiagonal = sceneExtends.max.subtract(sceneExtends.min);
  783. const sceneDiagonalLength = sceneDiagonal.length();
  784. if (isFinite(sceneDiagonalLength)) {
  785. this.camera.upperRadiusLimit = sceneDiagonalLength * 4;
  786. }
  787. // sanity check!
  788. if (this.scene.imageProcessingConfiguration) {
  789. this.scene.imageProcessingConfiguration.colorCurvesEnabled = true;
  790. this.scene.imageProcessingConfiguration.vignetteEnabled = true;
  791. this.scene.imageProcessingConfiguration.toneMappingEnabled = !!getConfigurationKey("camera.toneMappingEnabled", this._globalConfiguration);
  792. }
  793. extendClassWithConfig(this.camera, cameraConfig);
  794. this.onCameraConfiguredObservable.notifyObservers({
  795. sceneManager: this,
  796. object: this.camera,
  797. newConfiguration: cameraConfig
  798. });
  799. }
  800. private _focusOnModel = (model: ViewerModel) => {
  801. const boundingInfo = model.rootMesh.getHierarchyBoundingVectors(true);
  802. const sizeVec = boundingInfo.max.subtract(boundingInfo.min);
  803. const halfSizeVec = sizeVec.scale(0.5);
  804. const center = boundingInfo.min.add(halfSizeVec);
  805. this.camera.setTarget(center);
  806. this.camera.alpha = (this._globalConfiguration.camera && this._globalConfiguration.camera.alpha) || this.camera.alpha;
  807. this.camera.beta = (this._globalConfiguration.camera && this._globalConfiguration.camera.beta) || this.camera.beta;
  808. this.camera.radius = (this._globalConfiguration.camera && this._globalConfiguration.camera.radius) || this.camera.radius;
  809. const sceneDiagonalLenght = sizeVec.length();
  810. if (isFinite(sceneDiagonalLenght))
  811. this.camera.upperRadiusLimit = sceneDiagonalLenght * 4;
  812. if (this._configurationContainer.configuration)
  813. this._configureEnvironment(this._configurationContainer.configuration.skybox, this._configurationContainer.configuration.ground);
  814. /*this.scene.lights.filter(light => light instanceof ShadowLight).forEach(light => {
  815. // casting ais safe, due to the constraints tested before
  816. (<ShadowLight>light).setDirectionToTarget(center);
  817. });*/
  818. }
  819. protected _configureEnvironment(skyboxConifguration?: ISkyboxConfiguration | boolean, groundConfiguration?: IGroundConfiguration | boolean) {
  820. if (!skyboxConifguration && !groundConfiguration) {
  821. if (this.environmentHelper) {
  822. this.environmentHelper.dispose();
  823. this.environmentHelper = undefined;
  824. };
  825. } else {
  826. const options: Partial<IEnvironmentHelperOptions> = {
  827. createGround: !!groundConfiguration && this._groundEnabled,
  828. createSkybox: !!skyboxConifguration,
  829. setupImageProcessing: false, // will be done at the scene level!,
  830. };
  831. // will that cause problems with model ground configuration?
  832. /*if (model) {
  833. const boundingInfo = model.rootMesh.getHierarchyBoundingVectors(true);
  834. const sizeVec = boundingInfo.max.subtract(boundingInfo.min);
  835. const halfSizeVec = sizeVec.scale(0.5);
  836. const center = boundingInfo.min.add(halfSizeVec);
  837. options.groundYBias = -center.y;
  838. }*/
  839. if (groundConfiguration) {
  840. let groundConfig = (typeof groundConfiguration === 'boolean') ? {} : groundConfiguration;
  841. let groundSize = groundConfig.size || (typeof skyboxConifguration === 'object' && skyboxConifguration.scale);
  842. if (groundSize) {
  843. options.groundSize = groundSize;
  844. }
  845. options.enableGroundShadow = groundConfig === true || groundConfig.receiveShadows;
  846. if (groundConfig.shadowLevel !== undefined) {
  847. options.groundShadowLevel = groundConfig.shadowLevel;
  848. }
  849. options.enableGroundMirror = !!groundConfig.mirror && this.groundMirrorEnabled;
  850. if (groundConfig.texture) {
  851. options.groundTexture = this._getAssetUrl(groundConfig.texture);
  852. }
  853. if (groundConfig.color) {
  854. options.groundColor = new Color3(groundConfig.color.r, groundConfig.color.g, groundConfig.color.b)
  855. }
  856. if (groundConfig.opacity !== undefined) {
  857. options.groundOpacity = groundConfig.opacity;
  858. }
  859. if (groundConfig.mirror) {
  860. options.enableGroundMirror = true;
  861. // to prevent undefines
  862. if (typeof groundConfig.mirror === "object") {
  863. if (groundConfig.mirror.amount !== undefined)
  864. options.groundMirrorAmount = groundConfig.mirror.amount;
  865. if (groundConfig.mirror.sizeRatio !== undefined)
  866. options.groundMirrorSizeRatio = groundConfig.mirror.sizeRatio;
  867. if (groundConfig.mirror.blurKernel !== undefined)
  868. options.groundMirrorBlurKernel = groundConfig.mirror.blurKernel;
  869. if (groundConfig.mirror.fresnelWeight !== undefined)
  870. options.groundMirrorFresnelWeight = groundConfig.mirror.fresnelWeight;
  871. if (groundConfig.mirror.fallOffDistance !== undefined)
  872. options.groundMirrorFallOffDistance = groundConfig.mirror.fallOffDistance;
  873. if (this._defaultPipelineTextureType !== undefined)
  874. options.groundMirrorTextureType = this._defaultPipelineTextureType;
  875. }
  876. }
  877. }
  878. let postInitSkyboxMaterial = false;
  879. if (skyboxConifguration) {
  880. let conf = skyboxConifguration === true ? {} : skyboxConifguration;
  881. if (conf.material && conf.material.imageProcessingConfiguration) {
  882. options.setupImageProcessing = false; // will be configured later manually.
  883. }
  884. let skyboxSize = conf.scale;
  885. if (skyboxSize) {
  886. options.skyboxSize = skyboxSize;
  887. }
  888. options.sizeAuto = !options.skyboxSize;
  889. if (conf.color) {
  890. options.skyboxColor = new Color3(conf.color.r, conf.color.g, conf.color.b)
  891. }
  892. if (conf.cubeTexture && conf.cubeTexture.url) {
  893. if (typeof conf.cubeTexture.url === "string") {
  894. options.skyboxTexture = this._getAssetUrl(conf.cubeTexture.url);
  895. } else {
  896. // init later!
  897. postInitSkyboxMaterial = true;
  898. }
  899. }
  900. if (conf.material) {
  901. postInitSkyboxMaterial = true;
  902. }
  903. }
  904. options.setupImageProcessing = false; // TMP
  905. if (!this.environmentHelper) {
  906. this.environmentHelper = this.scene.createDefaultEnvironment(options)!;
  907. } else {
  908. // unlikely, but there might be a new scene! we need to dispose.
  909. // get the scene used by the envHelper
  910. let scene: Scene = this.environmentHelper.rootMesh.getScene();
  911. // is it a different scene? Oh no!
  912. if (scene !== this.scene) {
  913. this.environmentHelper.dispose();
  914. this.environmentHelper = this.scene.createDefaultEnvironment(options)!;
  915. } else {
  916. // recreate the ground
  917. if (this.environmentHelper.ground) {
  918. this.environmentHelper.ground.dispose();
  919. }
  920. // recreate the skybox
  921. if (this.environmentHelper.skybox) {
  922. this.environmentHelper.skybox.dispose();
  923. }
  924. this.environmentHelper.updateOptions(options)!;
  925. // update doesn't change the size of the skybox and ground, so we have to recreate!
  926. //this.environmentHelper.dispose();
  927. //this.environmentHelper = this.scene.createDefaultEnvironment(options)!;
  928. }
  929. }
  930. if (this.environmentHelper.rootMesh && this._globalConfiguration.scene && this._globalConfiguration.scene.environmentRotationY !== undefined) {
  931. this.environmentHelper.rootMesh.rotation.y = this._globalConfiguration.scene.environmentRotationY;
  932. }
  933. let groundConfig = (typeof groundConfiguration === 'boolean') ? {} : groundConfiguration;
  934. if (this.environmentHelper.groundMaterial && groundConfig) {
  935. this.environmentHelper.groundMaterial._perceptualColor = this.mainColor;
  936. if (groundConfig.material) {
  937. extendClassWithConfig(this.environmentHelper.groundMaterial, groundConfig.material);
  938. }
  939. if (this.environmentHelper.groundMirror) {
  940. const mirrorClearColor = this.environmentHelper.groundMaterial._perceptualColor.toLinearSpace();
  941. // TODO user camera exposure value to set the mirror clear color
  942. let exposure = Math.pow(2.0, -this.scene.imageProcessingConfiguration.exposure) * Math.PI;
  943. mirrorClearColor.scaleToRef(1 / exposure, mirrorClearColor);
  944. this.environmentHelper.groundMirror.clearColor.r = Scalar.Clamp(mirrorClearColor.r);
  945. this.environmentHelper.groundMirror.clearColor.g = Scalar.Clamp(mirrorClearColor.g);
  946. this.environmentHelper.groundMirror.clearColor.b = Scalar.Clamp(mirrorClearColor.b);
  947. this.environmentHelper.groundMirror.clearColor.a = 1;
  948. if (!this.groundMirrorEnabled) {
  949. this.environmentHelper.groundMaterial.reflectionTexture = null;
  950. }
  951. }
  952. }
  953. let skyboxMaterial = this.environmentHelper.skyboxMaterial;
  954. if (skyboxMaterial) {
  955. skyboxMaterial._perceptualColor = this.mainColor;
  956. if (postInitSkyboxMaterial) {
  957. if (typeof skyboxConifguration === 'object' && skyboxConifguration.material) {
  958. extendClassWithConfig(skyboxMaterial, skyboxConifguration.material);
  959. }
  960. }
  961. }
  962. }
  963. this._observablesManager && this._observablesManager.onModelLoadedObservable.add((model) => {
  964. this._updateGroundMirrorRenderList(model);
  965. });
  966. this.onEnvironmentConfiguredObservable.notifyObservers({
  967. sceneManager: this,
  968. object: this.environmentHelper!,
  969. newConfiguration: {
  970. skybox: skyboxConifguration,
  971. ground: groundConfiguration
  972. }
  973. });
  974. }
  975. /**
  976. * configure the lights.
  977. *
  978. * @param lightsConfiguration the (new) light(s) configuration
  979. * @param model optionally use the model to configure the camera.
  980. */
  981. protected _configureLights(lightsConfiguration: { [name: string]: ILightConfiguration | boolean | number } = {}) {
  982. // sanity check!
  983. let lightKeys = Object.keys(lightsConfiguration).filter(name => name !== 'globalRotation');
  984. if (!lightKeys.length) {
  985. if (!this.scene.lights.length)
  986. this.scene.createDefaultLight(true);
  987. } else {
  988. let lightsAvailable: Array<string> = this.scene.lights.map(light => light.name);
  989. // compare to the global (!) configuration object and dispose unneeded:
  990. let lightsToConfigure = Object.keys(this._globalConfiguration.lights || []);
  991. if (Object.keys(lightsToConfigure).length !== lightsAvailable.length) {
  992. lightsAvailable.forEach(lName => {
  993. if (lightsToConfigure.indexOf(lName) === -1) {
  994. this.scene.getLightByName(lName)!.dispose();
  995. }
  996. });
  997. }
  998. lightKeys.forEach((name, idx) => {
  999. let lightConfig: ILightConfiguration = { type: 0 };
  1000. if (typeof lightsConfiguration[name] === 'object') {
  1001. lightConfig = <ILightConfiguration>lightsConfiguration[name];
  1002. }
  1003. if (typeof lightsConfiguration[name] === 'number') {
  1004. lightConfig.type = <number>lightsConfiguration[name];
  1005. }
  1006. lightConfig.name = name;
  1007. let light: Light;
  1008. // light is not already available
  1009. if (lightsAvailable.indexOf(name) === -1) {
  1010. let constructor = Light.GetConstructorFromName(lightConfig.type, lightConfig.name, this.scene);
  1011. if (!constructor) return;
  1012. light = constructor();
  1013. } else {
  1014. // available? get it from the scene
  1015. light = <Light>this.scene.getLightByName(name);
  1016. if (typeof lightsConfiguration[name] === 'boolean') {
  1017. lightConfig.type = light.getTypeID();
  1018. }
  1019. lightsAvailable = lightsAvailable.filter(ln => ln !== name);
  1020. if (lightConfig.type !== undefined && light.getTypeID() !== lightConfig.type) {
  1021. light.dispose();
  1022. let constructor = Light.GetConstructorFromName(lightConfig.type, lightConfig.name, this.scene);
  1023. if (!constructor) return;
  1024. light = constructor();
  1025. }
  1026. }
  1027. // if config set the light to false, dispose it.
  1028. if (lightsConfiguration[name] === false) {
  1029. light.dispose();
  1030. return;
  1031. }
  1032. //enabled
  1033. var enabled = lightConfig.enabled !== undefined ? lightConfig.enabled : !lightConfig.disabled;
  1034. light.setEnabled(enabled);
  1035. extendClassWithConfig(light, lightConfig);
  1036. //position. Some lights don't support shadows
  1037. if (light instanceof ShadowLight) {
  1038. // set default values
  1039. light.shadowMinZ = light.shadowMinZ || 0.2;
  1040. light.shadowMaxZ = Math.min(10, light.shadowMaxZ || 10); //large far clips reduce shadow depth precision
  1041. if (lightConfig.target) {
  1042. if (light.setDirectionToTarget) {
  1043. let target = Vector3.Zero().copyFrom(lightConfig.target as Vector3);
  1044. light.setDirectionToTarget(target);
  1045. }
  1046. } else if (lightConfig.direction) {
  1047. let direction = Vector3.Zero().copyFrom(lightConfig.direction as Vector3);
  1048. light.direction = direction;
  1049. }
  1050. let isShadowEnabled = false;
  1051. if (light.getTypeID() === BABYLON.Light.LIGHTTYPEID_DIRECTIONALLIGHT) {
  1052. (<BABYLON.DirectionalLight>light).shadowFrustumSize = lightConfig.shadowFrustumSize || 2;
  1053. isShadowEnabled = true;
  1054. }
  1055. else if (light.getTypeID() === BABYLON.Light.LIGHTTYPEID_SPOTLIGHT) {
  1056. let spotLight: BABYLON.SpotLight = <BABYLON.SpotLight>light;
  1057. if (lightConfig.spotAngle !== undefined) {
  1058. spotLight.angle = lightConfig.spotAngle * Math.PI / 180;
  1059. }
  1060. if (spotLight.angle && lightConfig.shadowFieldOfView) {
  1061. spotLight.shadowAngleScale = lightConfig.shadowFieldOfView / spotLight.angle;
  1062. }
  1063. isShadowEnabled = true;
  1064. }
  1065. else if (light.getTypeID() === BABYLON.Light.LIGHTTYPEID_POINTLIGHT) {
  1066. if (lightConfig.shadowFieldOfView) {
  1067. (<BABYLON.PointLight>light).shadowAngle = lightConfig.shadowFieldOfView * Math.PI / 180;
  1068. }
  1069. isShadowEnabled = true;
  1070. }
  1071. let shadowGenerator = <BABYLON.ShadowGenerator>light.getShadowGenerator();
  1072. if (isShadowEnabled && lightConfig.shadowEnabled && this._maxShadows) {
  1073. let bufferSize = lightConfig.shadowBufferSize || 256;
  1074. if (!shadowGenerator) {
  1075. shadowGenerator = new ShadowGenerator(bufferSize, light);
  1076. }
  1077. var blurKernel = this.getBlurKernel(light, bufferSize);
  1078. shadowGenerator.bias = this._shadowGeneratorBias;
  1079. shadowGenerator.blurKernel = blurKernel;
  1080. //override defaults
  1081. extendClassWithConfig(shadowGenerator, lightConfig.shadowConfig || {});
  1082. // add the focues meshes to the shadow list
  1083. this._observablesManager && this._observablesManager.onModelLoadedObservable.add((model) => {
  1084. this._updateShadowRenderList(shadowGenerator, model);
  1085. });
  1086. //if (model) {
  1087. this._updateShadowRenderList(shadowGenerator);
  1088. //}
  1089. } else if (shadowGenerator) {
  1090. shadowGenerator.dispose();
  1091. }
  1092. }
  1093. });
  1094. // render priority
  1095. let globalLightsConfiguration = this._globalConfiguration.lights || {};
  1096. Object.keys(globalLightsConfiguration).sort().forEach((name, idx) => {
  1097. let configuration = globalLightsConfiguration[name];
  1098. let light = this.scene.getLightByName(name);
  1099. // sanity check
  1100. if (!light) return;
  1101. light.renderPriority = -idx;
  1102. });
  1103. }
  1104. this.onLightsConfiguredObservable.notifyObservers({
  1105. sceneManager: this,
  1106. object: this.scene.lights,
  1107. newConfiguration: lightsConfiguration
  1108. });
  1109. }
  1110. private _shadowGroundPlane: Nullable<AbstractMesh>;
  1111. private _updateShadowRenderList(shadowGenerator: ShadowGenerator, model?: ViewerModel, resetList?: boolean) {
  1112. let focusMeshes = model ? model.meshes : this.scene.meshes;
  1113. // add the focues meshes to the shadow list
  1114. let shadownMap = shadowGenerator.getShadowMap();
  1115. if (!shadownMap) return;
  1116. if (resetList && shadownMap.renderList) {
  1117. shadownMap.renderList.length = 0;
  1118. } else {
  1119. shadownMap.renderList = shadownMap.renderList || []
  1120. }
  1121. for (var index = 0; index < focusMeshes.length; index++) {
  1122. let mesh = focusMeshes[index];
  1123. if (Tags.MatchesQuery(mesh, 'castShadow') && shadownMap.renderList.indexOf(mesh) === -1) {
  1124. shadownMap.renderList.push(mesh);
  1125. }
  1126. }
  1127. if (!this._shadowGroundPlane) {
  1128. if (shadowGenerator.useBlurCloseExponentialShadowMap) {
  1129. let shadowGroundPlane = Mesh.CreatePlane("shadowGroundPlane", 100, this.scene, false);
  1130. shadowGroundPlane.useVertexColors = false;
  1131. //material isn't ever used in rendering, just used to set back face culling
  1132. shadowGroundPlane.material = new StandardMaterial('shadowGroundPlaneMaterial', this.scene);
  1133. shadowGroundPlane.material.backFaceCulling = false;
  1134. shadowGroundPlane.rotation.x = Math.PI * 0.5;
  1135. shadowGroundPlane.freezeWorldMatrix();
  1136. this._shadowGroundPlane = shadowGroundPlane;
  1137. this.scene.removeMesh(shadowGroundPlane);
  1138. }
  1139. } else {
  1140. if (!shadowGenerator.useBlurCloseExponentialShadowMap) {
  1141. this._shadowGroundPlane.dispose();
  1142. this._shadowGroundPlane = null;
  1143. }
  1144. }
  1145. if (this._shadowGroundPlane && shadownMap.renderList.indexOf(this._shadowGroundPlane) === -1) {
  1146. shadownMap.renderList.push(this._shadowGroundPlane);
  1147. }
  1148. }
  1149. private _updateGroundMirrorRenderList(model?: ViewerModel, resetList?: boolean) {
  1150. if (this.environmentHelper && this.environmentHelper.groundMirror && this.environmentHelper.groundMirror.renderList) {
  1151. let focusMeshes = model ? model.meshes : this.scene.meshes;
  1152. let renderList = this.environmentHelper.groundMirror.renderList;
  1153. if (resetList) {
  1154. renderList.length = 0;
  1155. }
  1156. for (var index = 0; index < focusMeshes.length; index++) {
  1157. let mesh = focusMeshes[index];
  1158. if (renderList.indexOf(mesh) === -1) {
  1159. renderList.push(mesh);
  1160. }
  1161. }
  1162. }
  1163. }
  1164. /**
  1165. * Gets the shadow map blur kernel according to the light configuration.
  1166. * @param light The light used to generate the shadows
  1167. * @param bufferSize The size of the shadow map
  1168. * @return the kernel blur size
  1169. */
  1170. public getBlurKernel(light: BABYLON.IShadowLight, bufferSize: number): number {
  1171. var normalizedBlurKernel = 0.05; // TODO Should come from the config.
  1172. if (light.getTypeID() === BABYLON.Light.LIGHTTYPEID_DIRECTIONALLIGHT) {
  1173. normalizedBlurKernel = normalizedBlurKernel / (<BABYLON.DirectionalLight>light).shadowFrustumSize;
  1174. }
  1175. else if (light.getTypeID() === BABYLON.Light.LIGHTTYPEID_POINTLIGHT) {
  1176. normalizedBlurKernel = normalizedBlurKernel / (<BABYLON.PointLight>light).shadowAngle;
  1177. }
  1178. else if (light.getTypeID() === BABYLON.Light.LIGHTTYPEID_SPOTLIGHT) {
  1179. normalizedBlurKernel = normalizedBlurKernel / ((<BABYLON.SpotLight>light).angle * (<BABYLON.SpotLight>light).shadowAngleScale);
  1180. }
  1181. let minimumBlurKernel = 5 / (bufferSize / 256); //magic number that aims to keep away sawtooth shadows
  1182. var blurKernel = Math.max(bufferSize * normalizedBlurKernel, minimumBlurKernel);
  1183. return blurKernel;
  1184. }
  1185. /**
  1186. * Alters render settings to reduce features based on hardware feature limitations
  1187. * @param enableHDR Allows the viewer to run in HDR mode.
  1188. */
  1189. protected _handleHardwareLimitations(enableHDR = true) {
  1190. //flip rendering settings switches based on hardware support
  1191. let maxVaryingRows = this._engine.getCaps().maxVaryingVectors;
  1192. let maxFragmentSamplers = this._engine.getCaps().maxTexturesImageUnits;
  1193. //shadows are disabled if there's not enough varyings for a single shadow
  1194. if ((maxVaryingRows < 8) || (maxFragmentSamplers < 8)) {
  1195. this._maxShadows = 0;
  1196. } else {
  1197. this._maxShadows = 3;
  1198. }
  1199. //can we render to any >= 16-bit targets (required for HDR)
  1200. let caps = this._engine.getCaps();
  1201. let linearHalfFloatTargets = caps.textureHalfFloatRender && caps.textureHalfFloatLinearFiltering;
  1202. let linearFloatTargets = caps.textureFloatRender && caps.textureFloatLinearFiltering;
  1203. this._hdrSupport = enableHDR && !!(linearFloatTargets || linearHalfFloatTargets);
  1204. if (linearHalfFloatTargets) {
  1205. this._defaultHighpTextureType = Engine.TEXTURETYPE_HALF_FLOAT;
  1206. this._shadowGeneratorBias = 0.002;
  1207. } else if (linearFloatTargets) {
  1208. this._defaultHighpTextureType = Engine.TEXTURETYPE_FLOAT;
  1209. this._shadowGeneratorBias = 0.001;
  1210. } else {
  1211. this._defaultHighpTextureType = Engine.TEXTURETYPE_UNSIGNED_INT;
  1212. this._shadowGeneratorBias = 0.001;
  1213. }
  1214. this._defaultPipelineTextureType = this._hdrSupport ? this._defaultHighpTextureType : Engine.TEXTURETYPE_UNSIGNED_INT;
  1215. }
  1216. /**
  1217. * Dispoe the entire viewer including the scene and the engine
  1218. */
  1219. public dispose() {
  1220. // this.onCameraConfiguredObservable.clear();
  1221. this.onEnvironmentConfiguredObservable.clear();
  1222. this.onLightsConfiguredObservable.clear();
  1223. this.onModelsConfiguredObservable.clear();
  1224. this.onSceneConfiguredObservable.clear();
  1225. this.onSceneInitObservable.clear();
  1226. this.onSceneOptimizerConfiguredObservable.clear();
  1227. this.onVRConfiguredObservable.clear();
  1228. this.onEnteringVRObservable.clear();
  1229. this.onExitingVRObservable.clear();
  1230. if (this.sceneOptimizer) {
  1231. this.sceneOptimizer.stop();
  1232. this.sceneOptimizer.dispose();
  1233. }
  1234. if (this.environmentHelper) {
  1235. this.environmentHelper.dispose();
  1236. }
  1237. this.models.forEach(model => {
  1238. model.dispose();
  1239. });
  1240. if (this._defaultRenderingPipeline) {
  1241. this._defaultRenderingPipeline.dispose();
  1242. }
  1243. this.models.length = 0;
  1244. if (this.scene) {
  1245. this.scene.dispose();
  1246. }
  1247. }
  1248. /**
  1249. * Get an environment asset url by using the configuration if the path is not absolute.
  1250. * @param url Asset url
  1251. * @returns The Asset url using the `environmentAssetsRootURL` if the url is not an absolute path.
  1252. */
  1253. private _getAssetUrl(url: string): string {
  1254. let returnUrl = url;
  1255. if (url && url.toLowerCase().indexOf("//") === -1) {
  1256. if (!this._assetsRootURL) {
  1257. // Tools.Warn("Please, specify the root url of your assets before loading the configuration (labs.environmentAssetsRootURL) or disable the background through the viewer options.");
  1258. return url;
  1259. }
  1260. returnUrl = this._assetsRootURL + returnUrl;
  1261. }
  1262. return returnUrl;
  1263. }
  1264. private _cameraBehaviorMapping: { [name: string]: number } = {};
  1265. private _setCameraBehavior(name: string, behaviorConfig: boolean | number | {
  1266. type: number;
  1267. [propName: string]: any;
  1268. }, payload?: any) {
  1269. let behavior: Behavior<ArcRotateCamera> | null;
  1270. let type: number;
  1271. if (typeof behaviorConfig === 'object') {
  1272. type = behaviorConfig.type
  1273. } else if (typeof behaviorConfig === 'number') {
  1274. type = behaviorConfig;
  1275. } else {
  1276. type = this._cameraBehaviorMapping[name];
  1277. }
  1278. if (type === undefined) return;
  1279. let config: { [propName: string]: any } = (typeof behaviorConfig === "object") ? behaviorConfig : {};
  1280. let enabled = true;
  1281. if (typeof behaviorConfig === 'boolean') {
  1282. enabled = behaviorConfig;
  1283. }
  1284. // constructing behavior
  1285. switch (type) {
  1286. case CameraBehavior.AUTOROTATION:
  1287. this.camera.useAutoRotationBehavior = enabled;
  1288. behavior = this.camera.autoRotationBehavior;
  1289. break;
  1290. case CameraBehavior.BOUNCING:
  1291. this.camera.useBouncingBehavior = enabled;
  1292. behavior = this.camera.bouncingBehavior;
  1293. break;
  1294. case CameraBehavior.FRAMING:
  1295. this.camera.useFramingBehavior = enabled;
  1296. behavior = this.camera.framingBehavior;
  1297. break;
  1298. default:
  1299. behavior = null;
  1300. break;
  1301. }
  1302. if (behavior) {
  1303. this._cameraBehaviorMapping[name] = type;
  1304. if (typeof behaviorConfig === "object") {
  1305. extendClassWithConfig(behavior, behaviorConfig);
  1306. }
  1307. }
  1308. // post attach configuration. Some functionalities require the attached camera.
  1309. switch (type) {
  1310. case CameraBehavior.AUTOROTATION:
  1311. break;
  1312. case CameraBehavior.BOUNCING:
  1313. break;
  1314. case CameraBehavior.FRAMING:
  1315. this._observablesManager && this._observablesManager.onModelLoadedObservable.add((model) => {
  1316. if (config.zoomOnBoundingInfo) {
  1317. (<FramingBehavior>behavior).zoomOnMeshHierarchy(model.rootMesh);
  1318. }
  1319. });
  1320. break;
  1321. }
  1322. }
  1323. }