environmentTools.ts 2.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657
  1. import { HDRCubeTexture } from 'babylonjs/Materials/Textures/hdrCubeTexture';
  2. import { CubeTexture } from 'babylonjs/Materials/Textures/cubeTexture';
  3. import { Scene } from 'babylonjs/scene';
  4. import { LocalStorageHelper } from './localStorageHelper';
  5. import { GlobalState } from '../globalState';
  6. import { Engine } from 'babylonjs/Engines/engine';
  7. import { StandardMaterial } from 'babylonjs/Materials/standardMaterial';
  8. import { PBRMaterial } from 'babylonjs/Materials/PBR/pbrMaterial';
  9. import { Texture } from 'babylonjs/Materials/Textures/texture';
  10. export class EnvironmentTools {
  11. public static SkyboxPath = "";
  12. public static Skyboxes = [
  13. "https://assets.babylonjs.com/environments/environmentSpecular.env",
  14. "https://assets.babylonjs.com/environments/studio.env",
  15. ];
  16. public static SkyboxesNames = [
  17. "Default",
  18. "Studio",
  19. ];
  20. public static LoadSkyboxPathTexture(scene: Scene) {
  21. var defaultSkyboxIndex = LocalStorageHelper.ReadLocalStorageValue("defaultSkyboxId", 0);
  22. let path = this.SkyboxPath || this.Skyboxes[defaultSkyboxIndex];
  23. if (path.indexOf(".hdr") === (path.length - 4)) {
  24. return new HDRCubeTexture(path, scene, 256, false, true, false, true);
  25. }
  26. return CubeTexture.CreateFromPrefilteredData(path, scene);
  27. }
  28. public static HookWithEnvironmentChange(globalState: GlobalState) {
  29. globalState.onEnvironmentChanged.add(option => {
  30. this.SkyboxPath = "";
  31. let index = EnvironmentTools.SkyboxesNames.indexOf(option);
  32. if (typeof (Storage) !== "undefined") {
  33. localStorage.setItem("defaultSkyboxId", index.toString());
  34. }
  35. var currentScene = Engine.LastCreatedScene!;
  36. currentScene.environmentTexture = this.LoadSkyboxPathTexture(currentScene);
  37. for (var i = 0; i < currentScene.materials.length; i++) {
  38. var material = currentScene.materials[i] as (StandardMaterial | PBRMaterial);
  39. if (material.name === "skyBox") {
  40. var reflectionTexture = material.reflectionTexture;
  41. if (reflectionTexture && reflectionTexture.coordinatesMode === Texture.SKYBOX_MODE) {
  42. material.reflectionTexture = currentScene.environmentTexture.clone();
  43. if (material.reflectionTexture) {
  44. material.reflectionTexture.coordinatesMode = Texture.SKYBOX_MODE;
  45. }
  46. }
  47. }
  48. }
  49. });
  50. }
  51. }