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