skyMaterial.ts 12 KB

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