sceneManager.ts 56 KB

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