sceneManager.ts 56 KB

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