sceneManager.ts 65 KB

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