skyMaterial.ts 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347
  1. import { MaterialDefines, PushMaterial, serialize, serializeAsVector3, Vector3, Scene, Nullable, BaseTexture, AbstractMesh, SubMesh, MaterialHelper, EffectFallbacks, VertexBuffer, Matrix, Mesh, IAnimatable, SerializationHelper } from "babylonjs";
  2. import "./sky.fragment";
  3. import "./sky.vertex";
  4. /** @hidden */
  5. class SkyMaterialDefines extends MaterialDefines {
  6. public CLIPPLANE = false;
  7. public CLIPPLANE2 = false;
  8. public CLIPPLANE3 = false;
  9. public CLIPPLANE4 = false;
  10. public POINTSIZE = false;
  11. public FOG = false;
  12. public VERTEXCOLOR = false;
  13. public VERTEXALPHA = false;
  14. constructor() {
  15. super();
  16. this.rebuild();
  17. }
  18. }
  19. /**
  20. * This is the sky material which allows to create dynamic and texture free effects for skyboxes.
  21. * @see https://doc.babylonjs.com/extensions/sky
  22. */
  23. export class SkyMaterial extends PushMaterial {
  24. /**
  25. * Defines the overall luminance of sky in interval ]0, 1[.
  26. */
  27. @serialize()
  28. public luminance: number = 1.0;
  29. /**
  30. * Defines the amount (scattering) of haze as opposed to molecules in atmosphere.
  31. */
  32. @serialize()
  33. public turbidity: number = 10.0;
  34. /**
  35. * Defines the sky appearance (light intensity).
  36. */
  37. @serialize()
  38. public rayleigh: number = 2.0;
  39. /**
  40. * Defines the mieCoefficient in interval [0, 0.1] which affects the property .mieDirectionalG.
  41. */
  42. @serialize()
  43. public mieCoefficient: number = 0.005;
  44. /**
  45. * Defines the amount of haze particles following the Mie scattering theory.
  46. */
  47. @serialize()
  48. public mieDirectionalG: number = 0.8;
  49. /**
  50. * Defines the distance of the sun according to the active scene camera.
  51. */
  52. @serialize()
  53. public distance: number = 500;
  54. /**
  55. * Defines the sun inclination, in interval [-0.5, 0.5]. When the inclination is not 0, the sun is said
  56. * "inclined".
  57. */
  58. @serialize()
  59. public inclination: number = 0.49;
  60. /**
  61. * Defines the solar azimuth in interval [0, 1]. The azimuth is the angle in the horizontal plan between
  62. * an object direction and a reference direction.
  63. */
  64. @serialize()
  65. public azimuth: number = 0.25;
  66. /**
  67. * Defines the sun position in the sky on (x,y,z). If the property .useSunPosition is set to false, then
  68. * the property is overriden by the inclination and the azimuth and can be read at any moment.
  69. */
  70. @serializeAsVector3()
  71. public sunPosition: Vector3 = new Vector3(0, 100, 0);
  72. /**
  73. * Defines if the sun position should be computed (inclination and azimuth) according to the given
  74. * .sunPosition property.
  75. */
  76. @serialize()
  77. public useSunPosition: boolean = false;
  78. /**
  79. * Defines an offset vector used to get a horizon offset.
  80. * @example skyMaterial.cameraOffset.y = camera.globalPosition.y // Set horizon relative to 0 on the Y axis
  81. */
  82. @serialize()
  83. public cameraOffset: Vector3 = Vector3.Zero();
  84. // Private members
  85. private _cameraPosition: Vector3 = Vector3.Zero();
  86. private _renderId: number;
  87. /**
  88. * Instantiates a new sky material.
  89. * This material allows to create dynamic and texture free
  90. * effects for skyboxes by taking care of the atmosphere state.
  91. * @see https://doc.babylonjs.com/extensions/sky
  92. * @param name Define the name of the material in the scene
  93. * @param scene Define the scene the material belong to
  94. */
  95. constructor(name: string, scene: Scene) {
  96. super(name, scene);
  97. }
  98. /**
  99. * Specifies if the material will require alpha blending
  100. * @returns a boolean specifying if alpha blending is needed
  101. */
  102. public needAlphaBlending(): boolean {
  103. return (this.alpha < 1.0);
  104. }
  105. /**
  106. * Specifies if this material should be rendered in alpha test mode
  107. * @returns false as the sky material doesn't need alpha testing.
  108. */
  109. public needAlphaTesting(): boolean {
  110. return false;
  111. }
  112. /**
  113. * Get the texture used for alpha test purpose.
  114. * @returns null as the sky material has no texture.
  115. */
  116. public getAlphaTestTexture(): Nullable<BaseTexture> {
  117. return null;
  118. }
  119. /**
  120. * Get if the submesh is ready to be used and all its information available.
  121. * Child classes can use it to update shaders
  122. * @param mesh defines the mesh to check
  123. * @param subMesh defines which submesh to check
  124. * @param useInstances specifies that instances should be used
  125. * @returns a boolean indicating that the submesh is ready or not
  126. */
  127. public isReadyForSubMesh(mesh: AbstractMesh, subMesh: SubMesh, useInstances?: boolean): boolean {
  128. if (this.isFrozen) {
  129. if (this._wasPreviouslyReady && subMesh.effect) {
  130. return true;
  131. }
  132. }
  133. if (!subMesh._materialDefines) {
  134. subMesh._materialDefines = new SkyMaterialDefines();
  135. }
  136. var defines = <SkyMaterialDefines>subMesh._materialDefines;
  137. var scene = this.getScene();
  138. if (!this.checkReadyOnEveryCall && subMesh.effect) {
  139. if (this._renderId === scene.getRenderId()) {
  140. return true;
  141. }
  142. }
  143. MaterialHelper.PrepareDefinesForMisc(mesh, scene, false, this.pointsCloud, this.fogEnabled, false, defines);
  144. // Attribs
  145. MaterialHelper.PrepareDefinesForAttributes(mesh, defines, true, false);
  146. // Get correct effect
  147. if (defines.isDirty) {
  148. defines.markAsProcessed();
  149. scene.resetCachedMaterial();
  150. // Fallbacks
  151. var fallbacks = new EffectFallbacks();
  152. if (defines.FOG) {
  153. fallbacks.addFallback(1, "FOG");
  154. }
  155. //Attributes
  156. var attribs = [VertexBuffer.PositionKind];
  157. if (defines.VERTEXCOLOR) {
  158. attribs.push(VertexBuffer.ColorKind);
  159. }
  160. var shaderName = "sky";
  161. var join = defines.toString();
  162. subMesh.setEffect(scene.getEngine().createEffect(shaderName,
  163. attribs,
  164. ["world", "viewProjection", "view",
  165. "vFogInfos", "vFogColor", "pointSize", "vClipPlane", "vClipPlane2", "vClipPlane3", "vClipPlane4",
  166. "luminance", "turbidity", "rayleigh", "mieCoefficient", "mieDirectionalG", "sunPosition",
  167. "cameraPosition", "cameraOffset"
  168. ],
  169. [],
  170. join, fallbacks, this.onCompiled, this.onError), defines);
  171. }
  172. if (!subMesh.effect || !subMesh.effect.isReady()) {
  173. return false;
  174. }
  175. this._renderId = scene.getRenderId();
  176. this._wasPreviouslyReady = true;
  177. return true;
  178. }
  179. /**
  180. * Binds the submesh to this material by preparing the effect and shader to draw
  181. * @param world defines the world transformation matrix
  182. * @param mesh defines the mesh containing the submesh
  183. * @param subMesh defines the submesh to bind the material to
  184. */
  185. public bindForSubMesh(world: Matrix, mesh: Mesh, subMesh: SubMesh): void {
  186. var scene = this.getScene();
  187. var defines = <SkyMaterialDefines>subMesh._materialDefines;
  188. if (!defines) {
  189. return;
  190. }
  191. var effect = subMesh.effect;
  192. if (!effect) {
  193. return;
  194. }
  195. this._activeEffect = effect;
  196. // Matrices
  197. this.bindOnlyWorldMatrix(world);
  198. this._activeEffect.setMatrix("viewProjection", scene.getTransformMatrix());
  199. if (this._mustRebind(scene, effect)) {
  200. MaterialHelper.BindClipPlane(this._activeEffect, scene);
  201. // Point size
  202. if (this.pointsCloud) {
  203. this._activeEffect.setFloat("pointSize", this.pointSize);
  204. }
  205. }
  206. // View
  207. if (scene.fogEnabled && mesh.applyFog && scene.fogMode !== Scene.FOGMODE_NONE) {
  208. this._activeEffect.setMatrix("view", scene.getViewMatrix());
  209. }
  210. // Fog
  211. MaterialHelper.BindFogParameters(scene, mesh, this._activeEffect);
  212. // Sky
  213. var camera = scene.activeCamera;
  214. if (camera) {
  215. var cameraWorldMatrix = camera.getWorldMatrix();
  216. this._cameraPosition.x = cameraWorldMatrix.m[12];
  217. this._cameraPosition.y = cameraWorldMatrix.m[13];
  218. this._cameraPosition.z = cameraWorldMatrix.m[14];
  219. this._activeEffect.setVector3("cameraPosition", this._cameraPosition);
  220. }
  221. this._activeEffect.setVector3("cameraOffset", this.cameraOffset);
  222. if (this.luminance > 0) {
  223. this._activeEffect.setFloat("luminance", this.luminance);
  224. }
  225. this._activeEffect.setFloat("turbidity", this.turbidity);
  226. this._activeEffect.setFloat("rayleigh", this.rayleigh);
  227. this._activeEffect.setFloat("mieCoefficient", this.mieCoefficient);
  228. this._activeEffect.setFloat("mieDirectionalG", this.mieDirectionalG);
  229. if (!this.useSunPosition) {
  230. var theta = Math.PI * (this.inclination - 0.5);
  231. var phi = 2 * Math.PI * (this.azimuth - 0.5);
  232. this.sunPosition.x = this.distance * Math.cos(phi);
  233. this.sunPosition.y = this.distance * Math.sin(phi) * Math.sin(theta);
  234. this.sunPosition.z = this.distance * Math.sin(phi) * Math.cos(theta);
  235. }
  236. this._activeEffect.setVector3("sunPosition", this.sunPosition);
  237. this._afterBind(mesh, this._activeEffect);
  238. }
  239. /**
  240. * Get the list of animatables in the material.
  241. * @returns the list of animatables object used in the material
  242. */
  243. public getAnimatables(): IAnimatable[] {
  244. return [];
  245. }
  246. /**
  247. * Disposes the material
  248. * @param forceDisposeEffect specifies if effects should be forcefully disposed
  249. */
  250. public dispose(forceDisposeEffect?: boolean): void {
  251. super.dispose(forceDisposeEffect);
  252. }
  253. /**
  254. * Makes a duplicate of the material, and gives it a new name
  255. * @param name defines the new name for the duplicated material
  256. * @returns the cloned material
  257. */
  258. public clone(name: string): SkyMaterial {
  259. return SerializationHelper.Clone<SkyMaterial>(() => new SkyMaterial(name, this.getScene()), this);
  260. }
  261. /**
  262. * Serializes this material in a JSON representation
  263. * @returns the serialized material object
  264. */
  265. public serialize(): any {
  266. var serializationObject = SerializationHelper.Serialize(this);
  267. serializationObject.customType = "BABYLON.SkyMaterial";
  268. return serializationObject;
  269. }
  270. /**
  271. * Gets the current class name of the material e.g. "SkyMaterial"
  272. * Mainly use in serialization.
  273. * @returns the class name
  274. */
  275. public getClassName(): string {
  276. return "SkyMaterial";
  277. }
  278. /**
  279. * Creates a sky material from parsed material data
  280. * @param source defines the JSON representation of the material
  281. * @param scene defines the hosting scene
  282. * @param rootUrl defines the root URL to use to load textures and relative dependencies
  283. * @returns a new sky material
  284. */
  285. public static Parse(source: any, scene: Scene, rootUrl: string): SkyMaterial {
  286. return SerializationHelper.Parse(() => new SkyMaterial(source.name, scene), source, scene, rootUrl);
  287. }
  288. }