sceneManager.ts 68 KB

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