babylon.waterMaterial.js 58 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662
  1. /// <reference path="../../../dist/preview release/babylon.d.ts"/>
  2. /// <reference path="../simple/babylon.simpleMaterial.ts"/>
  3. var BABYLON;
  4. (function (BABYLON) {
  5. var maxSimultaneousLights = 4;
  6. var WaterMaterialDefines = (function (_super) {
  7. __extends(WaterMaterialDefines, _super);
  8. function WaterMaterialDefines() {
  9. _super.call(this);
  10. this.BUMP = false;
  11. this.REFLECTION = false;
  12. this.CLIPPLANE = false;
  13. this.ALPHATEST = false;
  14. this.POINTSIZE = false;
  15. this.FOG = false;
  16. this.LIGHT0 = false;
  17. this.LIGHT1 = false;
  18. this.LIGHT2 = false;
  19. this.LIGHT3 = false;
  20. this.SPOTLIGHT0 = false;
  21. this.SPOTLIGHT1 = false;
  22. this.SPOTLIGHT2 = false;
  23. this.SPOTLIGHT3 = false;
  24. this.HEMILIGHT0 = false;
  25. this.HEMILIGHT1 = false;
  26. this.HEMILIGHT2 = false;
  27. this.HEMILIGHT3 = false;
  28. this.DIRLIGHT0 = false;
  29. this.DIRLIGHT1 = false;
  30. this.DIRLIGHT2 = false;
  31. this.DIRLIGHT3 = false;
  32. this.POINTLIGHT0 = false;
  33. this.POINTLIGHT1 = false;
  34. this.POINTLIGHT2 = false;
  35. this.POINTLIGHT3 = false;
  36. this.SHADOW0 = false;
  37. this.SHADOW1 = false;
  38. this.SHADOW2 = false;
  39. this.SHADOW3 = false;
  40. this.SHADOWS = false;
  41. this.SHADOWVSM0 = false;
  42. this.SHADOWVSM1 = false;
  43. this.SHADOWVSM2 = false;
  44. this.SHADOWVSM3 = false;
  45. this.SHADOWPCF0 = false;
  46. this.SHADOWPCF1 = false;
  47. this.SHADOWPCF2 = false;
  48. this.SHADOWPCF3 = false;
  49. this.NORMAL = false;
  50. this.UV1 = false;
  51. this.UV2 = false;
  52. this.VERTEXCOLOR = false;
  53. this.VERTEXALPHA = false;
  54. this.BONES = false;
  55. this.BONES4 = false;
  56. this.BonesPerMesh = 0;
  57. this.INSTANCES = false;
  58. this.SPECULARTERM = false;
  59. this._keys = Object.keys(this);
  60. }
  61. return WaterMaterialDefines;
  62. })(BABYLON.MaterialDefines);
  63. var WaterMaterial = (function (_super) {
  64. __extends(WaterMaterial, _super);
  65. /**
  66. * Constructor
  67. */
  68. function WaterMaterial(name, scene, renderTargetSize) {
  69. if (renderTargetSize === void 0) { renderTargetSize = new BABYLON.Vector2(512, 512); }
  70. _super.call(this, name, scene);
  71. this.renderTargetSize = renderTargetSize;
  72. this.diffuseColor = new BABYLON.Color3(1, 1, 1);
  73. this.specularColor = new BABYLON.Color3(0, 0, 0);
  74. this.specularPower = 64;
  75. this.disableLighting = false;
  76. /**
  77. * @param {number}: Represents the wind force
  78. */
  79. this.windForce = 6;
  80. /**
  81. * @param {Vector2}: The direction of the wind in the plane (X, Z)
  82. */
  83. this.windDirection = new BABYLON.Vector2(0, 1);
  84. /**
  85. * @param {number}: Wave height, represents the height of the waves
  86. */
  87. this.waveHeight = 0.4;
  88. /**
  89. * @param {number}: Bump height, represents the bump height related to the bump map
  90. */
  91. this.bumpHeight = 0.4;
  92. /**
  93. * @param {number}: The water color blended with the reflection and refraction samplers
  94. */
  95. this.waterColor = new BABYLON.Color3(0.1, 0.1, 0.6);
  96. /**
  97. * @param {number}: The blend factor related to the water color
  98. */
  99. this.colorBlendFactor = 0.2;
  100. /**
  101. * @param {number}: Represents the maximum length of a wave
  102. */
  103. this.waveLength = 0.1;
  104. /**
  105. * @param {number}: Defines the waves speed
  106. */
  107. this.waveSpeed = 1.0;
  108. /*
  109. * Private members
  110. */
  111. this._mesh = null;
  112. this._reflectionTransform = BABYLON.Matrix.Zero();
  113. this._lastTime = 0;
  114. this._scaledDiffuse = new BABYLON.Color3();
  115. this._scaledSpecular = new BABYLON.Color3();
  116. this._defines = new WaterMaterialDefines();
  117. this._cachedDefines = new WaterMaterialDefines();
  118. // Create render targets
  119. this._createRenderTargets(scene, renderTargetSize);
  120. }
  121. Object.defineProperty(WaterMaterial.prototype, "refractionTexture", {
  122. // Get / Set
  123. get: function () {
  124. return this._refractionRTT;
  125. },
  126. enumerable: true,
  127. configurable: true
  128. });
  129. Object.defineProperty(WaterMaterial.prototype, "reflectionTexture", {
  130. get: function () {
  131. return this._reflectionRTT;
  132. },
  133. enumerable: true,
  134. configurable: true
  135. });
  136. // Methods
  137. WaterMaterial.prototype.addToRenderList = function (node) {
  138. this._refractionRTT.renderList.push(node);
  139. this._reflectionRTT.renderList.push(node);
  140. };
  141. WaterMaterial.prototype.enableRenderTargets = function (enable) {
  142. var refreshRate = enable ? 1 : 0;
  143. this._refractionRTT.refreshRate = refreshRate;
  144. this._reflectionRTT.refreshRate = refreshRate;
  145. };
  146. WaterMaterial.prototype.needAlphaBlending = function () {
  147. return (this.alpha < 1.0);
  148. };
  149. WaterMaterial.prototype.needAlphaTesting = function () {
  150. return false;
  151. };
  152. WaterMaterial.prototype.getAlphaTestTexture = function () {
  153. return null;
  154. };
  155. WaterMaterial.prototype._checkCache = function (scene, mesh, useInstances) {
  156. if (!mesh) {
  157. return true;
  158. }
  159. if (this._defines.INSTANCES !== useInstances) {
  160. return false;
  161. }
  162. if (mesh._materialDefines && mesh._materialDefines.isEqual(this._defines)) {
  163. return true;
  164. }
  165. return false;
  166. };
  167. WaterMaterial.prototype.isReady = function (mesh, useInstances) {
  168. if (this.checkReadyOnlyOnce) {
  169. if (this._wasPreviouslyReady) {
  170. return true;
  171. }
  172. }
  173. var scene = this.getScene();
  174. if (!this.checkReadyOnEveryCall) {
  175. if (this._renderId === scene.getRenderId()) {
  176. if (this._checkCache(scene, mesh, useInstances)) {
  177. return true;
  178. }
  179. }
  180. }
  181. var engine = scene.getEngine();
  182. var needNormals = false;
  183. var needUVs = false;
  184. this._defines.reset();
  185. // Textures
  186. if (scene.texturesEnabled) {
  187. if (this.bumpTexture && BABYLON.StandardMaterial.BumpTextureEnabled) {
  188. if (!this.bumpTexture.isReady()) {
  189. return false;
  190. }
  191. else {
  192. needUVs = true;
  193. this._defines.BUMP = true;
  194. }
  195. }
  196. if (BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  197. this._defines.REFLECTION = true;
  198. }
  199. }
  200. // Effect
  201. if (scene.clipPlane) {
  202. this._defines.CLIPPLANE = true;
  203. }
  204. if (engine.getAlphaTesting()) {
  205. this._defines.ALPHATEST = true;
  206. }
  207. // Point size
  208. if (this.pointsCloud || scene.forcePointsCloud) {
  209. this._defines.POINTSIZE = true;
  210. }
  211. // Fog
  212. if (scene.fogEnabled && mesh && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE && this.fogEnabled) {
  213. this._defines.FOG = true;
  214. }
  215. var lightIndex = 0;
  216. if (scene.lightsEnabled && !this.disableLighting) {
  217. for (var index = 0; index < scene.lights.length; index++) {
  218. var light = scene.lights[index];
  219. if (!light.isEnabled()) {
  220. continue;
  221. }
  222. // Excluded check
  223. if (light._excludedMeshesIds.length > 0) {
  224. for (var excludedIndex = 0; excludedIndex < light._excludedMeshesIds.length; excludedIndex++) {
  225. var excludedMesh = scene.getMeshByID(light._excludedMeshesIds[excludedIndex]);
  226. if (excludedMesh) {
  227. light.excludedMeshes.push(excludedMesh);
  228. }
  229. }
  230. light._excludedMeshesIds = [];
  231. }
  232. // Included check
  233. if (light._includedOnlyMeshesIds.length > 0) {
  234. for (var includedOnlyIndex = 0; includedOnlyIndex < light._includedOnlyMeshesIds.length; includedOnlyIndex++) {
  235. var includedOnlyMesh = scene.getMeshByID(light._includedOnlyMeshesIds[includedOnlyIndex]);
  236. if (includedOnlyMesh) {
  237. light.includedOnlyMeshes.push(includedOnlyMesh);
  238. }
  239. }
  240. light._includedOnlyMeshesIds = [];
  241. }
  242. if (!light.canAffectMesh(mesh)) {
  243. continue;
  244. }
  245. needNormals = true;
  246. this._defines["LIGHT" + lightIndex] = true;
  247. var type;
  248. if (light instanceof BABYLON.SpotLight) {
  249. type = "SPOTLIGHT" + lightIndex;
  250. }
  251. else if (light instanceof BABYLON.HemisphericLight) {
  252. type = "HEMILIGHT" + lightIndex;
  253. }
  254. else if (light instanceof BABYLON.PointLight) {
  255. type = "POINTLIGHT" + lightIndex;
  256. }
  257. else {
  258. type = "DIRLIGHT" + lightIndex;
  259. }
  260. this._defines[type] = true;
  261. // Specular
  262. if (!light.specular.equalsFloats(0, 0, 0)) {
  263. this._defines.SPECULARTERM = true;
  264. }
  265. // Shadows
  266. if (scene.shadowsEnabled) {
  267. var shadowGenerator = light.getShadowGenerator();
  268. if (mesh && mesh.receiveShadows && shadowGenerator) {
  269. this._defines["SHADOW" + lightIndex] = true;
  270. this._defines.SHADOWS = true;
  271. if (shadowGenerator.useVarianceShadowMap || shadowGenerator.useBlurVarianceShadowMap) {
  272. this._defines["SHADOWVSM" + lightIndex] = true;
  273. }
  274. if (shadowGenerator.usePoissonSampling) {
  275. this._defines["SHADOWPCF" + lightIndex] = true;
  276. }
  277. }
  278. }
  279. lightIndex++;
  280. if (lightIndex === maxSimultaneousLights)
  281. break;
  282. }
  283. }
  284. // Attribs
  285. if (mesh) {
  286. if (needNormals && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  287. this._defines.NORMAL = true;
  288. }
  289. if (needUVs) {
  290. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  291. this._defines.UV1 = true;
  292. }
  293. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  294. this._defines.UV2 = true;
  295. }
  296. }
  297. if (mesh.useVertexColors && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  298. this._defines.VERTEXCOLOR = true;
  299. if (mesh.hasVertexAlpha) {
  300. this._defines.VERTEXALPHA = true;
  301. }
  302. }
  303. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  304. this._defines.BONES = true;
  305. this._defines.BonesPerMesh = (mesh.skeleton.bones.length + 1);
  306. this._defines.BONES4 = true;
  307. }
  308. // Instances
  309. if (useInstances) {
  310. this._defines.INSTANCES = true;
  311. }
  312. }
  313. this._mesh = mesh;
  314. // Get correct effect
  315. if (!this._defines.isEqual(this._cachedDefines)) {
  316. this._defines.cloneTo(this._cachedDefines);
  317. scene.resetCachedMaterial();
  318. // Fallbacks
  319. var fallbacks = new BABYLON.EffectFallbacks();
  320. if (this._defines.FOG) {
  321. fallbacks.addFallback(1, "FOG");
  322. }
  323. for (lightIndex = 0; lightIndex < maxSimultaneousLights; lightIndex++) {
  324. if (!this._defines["LIGHT" + lightIndex]) {
  325. continue;
  326. }
  327. if (lightIndex > 0) {
  328. fallbacks.addFallback(lightIndex, "LIGHT" + lightIndex);
  329. }
  330. if (this._defines["SHADOW" + lightIndex]) {
  331. fallbacks.addFallback(0, "SHADOW" + lightIndex);
  332. }
  333. if (this._defines["SHADOWPCF" + lightIndex]) {
  334. fallbacks.addFallback(0, "SHADOWPCF" + lightIndex);
  335. }
  336. if (this._defines["SHADOWVSM" + lightIndex]) {
  337. fallbacks.addFallback(0, "SHADOWVSM" + lightIndex);
  338. }
  339. }
  340. if (this._defines.BONES4) {
  341. fallbacks.addFallback(0, "BONES4");
  342. }
  343. //Attributes
  344. var attribs = [BABYLON.VertexBuffer.PositionKind];
  345. if (this._defines.NORMAL) {
  346. attribs.push(BABYLON.VertexBuffer.NormalKind);
  347. }
  348. if (this._defines.UV1) {
  349. attribs.push(BABYLON.VertexBuffer.UVKind);
  350. }
  351. if (this._defines.UV2) {
  352. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  353. }
  354. if (this._defines.VERTEXCOLOR) {
  355. attribs.push(BABYLON.VertexBuffer.ColorKind);
  356. }
  357. if (this._defines.BONES) {
  358. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  359. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  360. }
  361. if (this._defines.INSTANCES) {
  362. attribs.push("world0");
  363. attribs.push("world1");
  364. attribs.push("world2");
  365. attribs.push("world3");
  366. }
  367. // Legacy browser patch
  368. var shaderName = "water";
  369. var join = this._defines.toString();
  370. this._effect = scene.getEngine().createEffect(shaderName, attribs, ["world", "view", "viewProjection", "vEyePosition", "vLightsType", "vDiffuseColor", "vSpecularColor",
  371. "vLightData0", "vLightDiffuse0", "vLightSpecular0", "vLightDirection0", "vLightGround0", "lightMatrix0",
  372. "vLightData1", "vLightDiffuse1", "vLightSpecular1", "vLightDirection1", "vLightGround1", "lightMatrix1",
  373. "vLightData2", "vLightDiffuse2", "vLightSpecular2", "vLightDirection2", "vLightGround2", "lightMatrix2",
  374. "vLightData3", "vLightDiffuse3", "vLightSpecular3", "vLightDirection3", "vLightGround3", "lightMatrix3",
  375. "vFogInfos", "vFogColor", "pointSize",
  376. "vNormalInfos",
  377. "mBones",
  378. "vClipPlane", "normalMatrix",
  379. "shadowsInfo0", "shadowsInfo1", "shadowsInfo2", "shadowsInfo3",
  380. // Water
  381. "worldReflectionViewProjection", "windDirection", "waveLength", "time", "windForce",
  382. "cameraPosition", "bumpHeight", "waveHeight", "waterColor", "colorBlendFactor", "waveSpeed"
  383. ], ["normalSampler",
  384. "shadowSampler0", "shadowSampler1", "shadowSampler2", "shadowSampler3",
  385. // Water
  386. "refractionSampler", "reflectionSampler"
  387. ], join, fallbacks, this.onCompiled, this.onError);
  388. }
  389. if (!this._effect.isReady()) {
  390. return false;
  391. }
  392. this._renderId = scene.getRenderId();
  393. this._wasPreviouslyReady = true;
  394. if (mesh) {
  395. if (!mesh._materialDefines) {
  396. mesh._materialDefines = new WaterMaterialDefines();
  397. }
  398. this._defines.cloneTo(mesh._materialDefines);
  399. }
  400. return true;
  401. };
  402. WaterMaterial.prototype.bindOnlyWorldMatrix = function (world) {
  403. this._effect.setMatrix("world", world);
  404. };
  405. WaterMaterial.prototype.bind = function (world, mesh) {
  406. var scene = this.getScene();
  407. // Matrices
  408. this.bindOnlyWorldMatrix(world);
  409. this._effect.setMatrix("viewProjection", scene.getTransformMatrix());
  410. // Bones
  411. if (mesh && mesh.useBones && mesh.computeBonesUsingShaders) {
  412. this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  413. }
  414. if (scene.getCachedMaterial() !== this) {
  415. // Textures
  416. if (this.bumpTexture && BABYLON.StandardMaterial.BumpTextureEnabled) {
  417. this._effect.setTexture("normalSampler", this.bumpTexture);
  418. this._effect.setFloat2("vNormalInfos", this.bumpTexture.coordinatesIndex, this.bumpTexture.level);
  419. this._effect.setMatrix("normalMatrix", this.bumpTexture.getTextureMatrix());
  420. }
  421. // Clip plane
  422. if (scene.clipPlane) {
  423. var clipPlane = scene.clipPlane;
  424. this._effect.setFloat4("vClipPlane", clipPlane.normal.x, clipPlane.normal.y, clipPlane.normal.z, clipPlane.d);
  425. }
  426. // Point size
  427. if (this.pointsCloud) {
  428. this._effect.setFloat("pointSize", this.pointSize);
  429. }
  430. this._effect.setVector3("vEyePosition", scene._mirroredCameraPosition ? scene._mirroredCameraPosition : scene.activeCamera.position);
  431. }
  432. this._effect.setColor4("vDiffuseColor", this._scaledDiffuse, this.alpha * mesh.visibility);
  433. if (this._defines.SPECULARTERM) {
  434. this._effect.setColor4("vSpecularColor", this.specularColor, this.specularPower);
  435. }
  436. if (scene.lightsEnabled && !this.disableLighting) {
  437. var lightIndex = 0;
  438. for (var index = 0; index < scene.lights.length; index++) {
  439. var light = scene.lights[index];
  440. if (!light.isEnabled()) {
  441. continue;
  442. }
  443. if (!light.canAffectMesh(mesh)) {
  444. continue;
  445. }
  446. if (light instanceof BABYLON.PointLight) {
  447. // Point Light
  448. light.transferToEffect(this._effect, "vLightData" + lightIndex);
  449. }
  450. else if (light instanceof BABYLON.DirectionalLight) {
  451. // Directional Light
  452. light.transferToEffect(this._effect, "vLightData" + lightIndex);
  453. }
  454. else if (light instanceof BABYLON.SpotLight) {
  455. // Spot Light
  456. light.transferToEffect(this._effect, "vLightData" + lightIndex, "vLightDirection" + lightIndex);
  457. }
  458. else if (light instanceof BABYLON.HemisphericLight) {
  459. // Hemispheric Light
  460. light.transferToEffect(this._effect, "vLightData" + lightIndex, "vLightGround" + lightIndex);
  461. }
  462. light.diffuse.scaleToRef(light.intensity, this._scaledDiffuse);
  463. this._effect.setColor4("vLightDiffuse" + lightIndex, this._scaledDiffuse, light.range);
  464. if (this._defines.SPECULARTERM) {
  465. light.specular.scaleToRef(light.intensity, this._scaledSpecular);
  466. this._effect.setColor3("vLightSpecular" + lightIndex, this._scaledSpecular);
  467. }
  468. // Shadows
  469. if (scene.shadowsEnabled) {
  470. var shadowGenerator = light.getShadowGenerator();
  471. if (mesh.receiveShadows && shadowGenerator) {
  472. this._effect.setMatrix("lightMatrix" + lightIndex, shadowGenerator.getTransformMatrix());
  473. this._effect.setTexture("shadowSampler" + lightIndex, shadowGenerator.getShadowMapForRendering());
  474. this._effect.setFloat3("shadowsInfo" + lightIndex, shadowGenerator.getDarkness(), shadowGenerator.getShadowMap().getSize().width, shadowGenerator.bias);
  475. }
  476. }
  477. lightIndex++;
  478. if (lightIndex === maxSimultaneousLights)
  479. break;
  480. }
  481. }
  482. // View
  483. if (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE) {
  484. this._effect.setMatrix("view", scene.getViewMatrix());
  485. }
  486. // Fog
  487. if (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE) {
  488. this._effect.setFloat4("vFogInfos", scene.fogMode, scene.fogStart, scene.fogEnd, scene.fogDensity);
  489. this._effect.setColor3("vFogColor", scene.fogColor);
  490. }
  491. // Water
  492. if (BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  493. this._effect.setTexture("refractionSampler", this._refractionRTT);
  494. this._effect.setTexture("reflectionSampler", this._reflectionRTT);
  495. }
  496. var wrvp = this._mesh.getWorldMatrix().multiply(this._reflectionTransform).multiply(scene.getProjectionMatrix());
  497. this._lastTime += scene.getEngine().getDeltaTime();
  498. this._effect.setMatrix("worldReflectionViewProjection", wrvp);
  499. this._effect.setVector2("windDirection", this.windDirection);
  500. this._effect.setFloat("waveLength", this.waveLength);
  501. this._effect.setFloat("time", this._lastTime / 100000);
  502. this._effect.setFloat("windForce", this.windForce);
  503. this._effect.setFloat("waveHeight", this.waveHeight);
  504. this._effect.setFloat("bumpHeight", this.bumpHeight);
  505. this._effect.setColor4("waterColor", this.waterColor, 1.0);
  506. this._effect.setFloat("colorBlendFactor", this.colorBlendFactor);
  507. this._effect.setFloat("waveSpeed", this.waveSpeed);
  508. _super.prototype.bind.call(this, world, mesh);
  509. };
  510. WaterMaterial.prototype._createRenderTargets = function (scene, renderTargetSize) {
  511. var _this = this;
  512. // Render targets
  513. this._refractionRTT = new BABYLON.RenderTargetTexture(name + "_refraction", { width: renderTargetSize.x, height: renderTargetSize.y }, scene, false, true);
  514. this._reflectionRTT = new BABYLON.RenderTargetTexture(name + "_reflection", { width: renderTargetSize.x, height: renderTargetSize.y }, scene, false, true);
  515. scene.customRenderTargets.push(this._refractionRTT);
  516. scene.customRenderTargets.push(this._reflectionRTT);
  517. var isVisible;
  518. var clipPlane = null;
  519. var savedViewMatrix;
  520. var mirrorMatrix = BABYLON.Matrix.Zero();
  521. this._refractionRTT.onBeforeRender = function () {
  522. if (_this._mesh) {
  523. isVisible = _this._mesh.isVisible;
  524. _this._mesh.isVisible = false;
  525. }
  526. // Clip plane
  527. clipPlane = scene.clipPlane;
  528. var positiony = _this._mesh ? _this._mesh.position.y : 0.0;
  529. scene.clipPlane = BABYLON.Plane.FromPositionAndNormal(new BABYLON.Vector3(0, positiony + 0.05, 0), new BABYLON.Vector3(0, 1, 0));
  530. };
  531. this._refractionRTT.onAfterRender = function () {
  532. if (_this._mesh) {
  533. _this._mesh.isVisible = isVisible;
  534. }
  535. // Clip plane
  536. scene.clipPlane = clipPlane;
  537. };
  538. this._reflectionRTT.onBeforeRender = function () {
  539. if (_this._mesh) {
  540. isVisible = _this._mesh.isVisible;
  541. _this._mesh.isVisible = false;
  542. }
  543. // Clip plane
  544. clipPlane = scene.clipPlane;
  545. var positiony = _this._mesh ? _this._mesh.position.y : 0.0;
  546. scene.clipPlane = BABYLON.Plane.FromPositionAndNormal(new BABYLON.Vector3(0, positiony - 0.05, 0), new BABYLON.Vector3(0, -1, 0));
  547. // Transform
  548. BABYLON.Matrix.ReflectionToRef(scene.clipPlane, mirrorMatrix);
  549. savedViewMatrix = scene.getViewMatrix();
  550. mirrorMatrix.multiplyToRef(savedViewMatrix, _this._reflectionTransform);
  551. scene.setTransformMatrix(_this._reflectionTransform, scene.getProjectionMatrix());
  552. scene.getEngine().cullBackFaces = false;
  553. scene._mirroredCameraPosition = BABYLON.Vector3.TransformCoordinates(scene.activeCamera.position, mirrorMatrix);
  554. };
  555. this._reflectionRTT.onAfterRender = function () {
  556. if (_this._mesh) {
  557. _this._mesh.isVisible = isVisible;
  558. }
  559. // Clip plane
  560. scene.clipPlane = clipPlane;
  561. // Transform
  562. scene.setTransformMatrix(savedViewMatrix, scene.getProjectionMatrix());
  563. scene.getEngine().cullBackFaces = true;
  564. scene._mirroredCameraPosition = null;
  565. };
  566. };
  567. WaterMaterial.prototype.getAnimatables = function () {
  568. var results = [];
  569. if (this.bumpTexture && this.bumpTexture.animations && this.bumpTexture.animations.length > 0) {
  570. results.push(this.bumpTexture);
  571. }
  572. if (this._reflectionRTT && this._reflectionRTT.animations && this._reflectionRTT.animations.length > 0) {
  573. results.push(this._reflectionRTT);
  574. }
  575. if (this._refractionRTT && this._refractionRTT.animations && this._refractionRTT.animations.length > 0) {
  576. results.push(this._refractionRTT);
  577. }
  578. return results;
  579. };
  580. WaterMaterial.prototype.dispose = function (forceDisposeEffect) {
  581. if (this.bumpTexture) {
  582. this.bumpTexture.dispose();
  583. }
  584. if (this._reflectionRTT) {
  585. this._reflectionRTT.dispose();
  586. }
  587. if (this._refractionRTT) {
  588. this._refractionRTT.dispose();
  589. }
  590. _super.prototype.dispose.call(this, forceDisposeEffect);
  591. };
  592. WaterMaterial.prototype.clone = function (name) {
  593. var newMaterial = new WaterMaterial(name, this.getScene());
  594. // Base material
  595. this.copyTo(newMaterial);
  596. // water material
  597. if (this.bumpTexture && this.bumpTexture.clone) {
  598. newMaterial.bumpTexture = this.bumpTexture.clone();
  599. }
  600. newMaterial.diffuseColor = this.diffuseColor.clone();
  601. return newMaterial;
  602. };
  603. WaterMaterial.prototype.serialize = function () {
  604. var serializationObject = _super.prototype.serialize.call(this);
  605. serializationObject.customType = "BABYLON.WaterMaterial";
  606. serializationObject.diffuseColor = this.diffuseColor.asArray();
  607. serializationObject.specularColor = this.specularColor.asArray();
  608. serializationObject.specularPower = this.specularPower;
  609. serializationObject.disableLighting = this.disableLighting;
  610. serializationObject.windForce = this.windForce;
  611. serializationObject.windDirection = this.windDirection.asArray();
  612. serializationObject.waveHeight = this.waveHeight;
  613. serializationObject.bumpHeight = this.bumpHeight;
  614. serializationObject.waterColor = this.waterColor.asArray();
  615. serializationObject.colorBlendFactor = this.colorBlendFactor;
  616. serializationObject.waveLength = this.waveLength;
  617. serializationObject.renderTargetSize = this.renderTargetSize.asArray();
  618. if (this.bumpTexture) {
  619. serializationObject.bumpTexture = this.bumpTexture.serialize();
  620. }
  621. return serializationObject;
  622. };
  623. WaterMaterial.Parse = function (source, scene, rootUrl) {
  624. var renderTargetSize = source.renderTargetSize ? BABYLON.Vector2.FromArray(source.renderTargetSize) : null;
  625. var material = new WaterMaterial(source.name, scene, renderTargetSize);
  626. material.diffuseColor = BABYLON.Color3.FromArray(source.diffuseColor);
  627. material.specularColor = BABYLON.Color3.FromArray(source.specularColor);
  628. material.specularPower = source.specularPower;
  629. material.disableLighting = source.disableLighting;
  630. material.windForce = source.windForce;
  631. material.windDirection = BABYLON.Vector2.FromArray(source.windDirection);
  632. material.waveHeight = source.waveHeight;
  633. material.bumpHeight = source.bumpHeight;
  634. material.waterColor = BABYLON.Color3.FromArray(source.waterColor);
  635. material.colorBlendFactor = source.colorBlendFactor;
  636. material.waveLength = source.waveLength;
  637. material.renderTargetSize = BABYLON.Vector2.FromArray(source.renderTargetSize);
  638. material.alpha = source.alpha;
  639. material.id = source.id;
  640. BABYLON.Tags.AddTagsTo(material, source.tags);
  641. material.backFaceCulling = source.backFaceCulling;
  642. material.wireframe = source.wireframe;
  643. if (source.bumpTexture) {
  644. material.bumpTexture = BABYLON.Texture.Parse(source.bumpTexture, scene, rootUrl);
  645. }
  646. if (source.checkReadyOnlyOnce) {
  647. material.checkReadyOnlyOnce = source.checkReadyOnlyOnce;
  648. }
  649. return material;
  650. };
  651. WaterMaterial.CreateDefaultMesh = function (name, scene) {
  652. var mesh = BABYLON.Mesh.CreateGround(name, 512, 512, 32, scene, false);
  653. return mesh;
  654. };
  655. return WaterMaterial;
  656. })(BABYLON.Material);
  657. BABYLON.WaterMaterial = WaterMaterial;
  658. })(BABYLON || (BABYLON = {}));
  659. BABYLON.Effect.ShadersStore['waterVertexShader'] = "precision highp float;\r\n\r\n// Attributes\r\nattribute vec3 position;\r\n#ifdef NORMAL\r\nattribute vec3 normal;\r\n#endif\r\n#ifdef UV1\r\nattribute vec2 uv;\r\n#endif\r\n#ifdef UV2\r\nattribute vec2 uv2;\r\n#endif\r\n#ifdef VERTEXCOLOR\r\nattribute vec4 color;\r\n#endif\r\n#ifdef BONES\r\nattribute vec4 matricesIndices;\r\nattribute vec4 matricesWeights;\r\n#endif\r\n\r\n// Uniforms\r\n\r\n#ifdef INSTANCES\r\nattribute vec4 world0;\r\nattribute vec4 world1;\r\nattribute vec4 world2;\r\nattribute vec4 world3;\r\n#else\r\nuniform mat4 world;\r\n#endif\r\n\r\nuniform mat4 view;\r\nuniform mat4 viewProjection;\r\n\r\n#ifdef BUMP\r\nvarying vec2 vNormalUV;\r\nuniform mat4 normalMatrix;\r\nuniform vec2 vNormalInfos;\r\n#endif\r\n\r\n#ifdef BONES\r\nuniform mat4 mBones[BonesPerMesh];\r\n#endif\r\n\r\n#ifdef POINTSIZE\r\nuniform float pointSize;\r\n#endif\r\n\r\n// Output\r\nvarying vec3 vPositionW;\r\n#ifdef NORMAL\r\nvarying vec3 vNormalW;\r\n#endif\r\n\r\n#ifdef VERTEXCOLOR\r\nvarying vec4 vColor;\r\n#endif\r\n\r\n#ifdef CLIPPLANE\r\nuniform vec4 vClipPlane;\r\nvarying float fClipDistance;\r\n#endif\r\n\r\n#ifdef FOG\r\nvarying float fFogDistance;\r\n#endif\r\n\r\n#ifdef SHADOWS\r\n#if defined(SPOTLIGHT0) || defined(DIRLIGHT0)\r\nuniform mat4 lightMatrix0;\r\nvarying vec4 vPositionFromLight0;\r\n#endif\r\n#if defined(SPOTLIGHT1) || defined(DIRLIGHT1)\r\nuniform mat4 lightMatrix1;\r\nvarying vec4 vPositionFromLight1;\r\n#endif\r\n#if defined(SPOTLIGHT2) || defined(DIRLIGHT2)\r\nuniform mat4 lightMatrix2;\r\nvarying vec4 vPositionFromLight2;\r\n#endif\r\n#if defined(SPOTLIGHT3) || defined(DIRLIGHT3)\r\nuniform mat4 lightMatrix3;\r\nvarying vec4 vPositionFromLight3;\r\n#endif\r\n#endif\r\n\r\n// Water uniforms\r\nuniform mat4 worldReflectionViewProjection;\r\nuniform vec2 windDirection;\r\nuniform float waveLength;\r\nuniform float time;\r\nuniform float windForce;\r\nuniform float waveHeight;\r\nuniform float waveSpeed;\r\n\r\n// Water varyings\r\nvarying vec3 vPosition;\r\nvarying vec3 vRefractionMapTexCoord;\r\nvarying vec3 vReflectionMapTexCoord;\r\n\r\nvoid main(void) {\r\n\tmat4 finalWorld;\r\n\r\n#ifdef INSTANCES\r\n\tfinalWorld = mat4(world0, world1, world2, world3);\r\n#else\r\n\tfinalWorld = world;\r\n#endif\r\n\r\n#ifdef BONES\r\n\tmat4 m0 = mBones[int(matricesIndices.x)] * matricesWeights.x;\r\n\tmat4 m1 = mBones[int(matricesIndices.y)] * matricesWeights.y;\r\n\tmat4 m2 = mBones[int(matricesIndices.z)] * matricesWeights.z;\r\n\r\n#ifdef BONES4\r\n\tmat4 m3 = mBones[int(matricesIndices.w)] * matricesWeights.w;\r\n\tfinalWorld = finalWorld * (m0 + m1 + m2 + m3);\r\n#else\r\n\tfinalWorld = finalWorld * (m0 + m1 + m2);\r\n#endif \r\n\r\n#endif\r\n\r\n\tvec4 worldPos = finalWorld * vec4(position, 1.0);\r\n\tvPositionW = vec3(worldPos);\r\n\r\n#ifdef NORMAL\r\n\tvNormalW = normalize(vec3(finalWorld * vec4(normal, 0.0)));\r\n#endif\r\n\r\n\t// Texture coordinates\r\n#ifndef UV1\r\n\tvec2 uv = vec2(0., 0.);\r\n#endif\r\n#ifndef UV2\r\n\tvec2 uv2 = vec2(0., 0.);\r\n#endif\r\n\r\n#ifdef BUMP\r\n\tif (vNormalInfos.x == 0.)\r\n\t{\r\n\t\tvNormalUV = vec2(normalMatrix * vec4((uv * 1.0) / waveLength + time * windForce * windDirection, 1.0, 0.0));\r\n\t}\r\n\telse\r\n\t{\r\n\t\tvNormalUV = vec2(normalMatrix * vec4((uv2 * 1.0) / waveLength + time * windForce * windDirection, 1.0, 0.0));\r\n\t}\r\n#endif\r\n\r\n\t// Clip plane\r\n#ifdef CLIPPLANE\r\n\tfClipDistance = dot(worldPos, vClipPlane);\r\n#endif\r\n\r\n\t// Fog\r\n#ifdef FOG\r\n\tfFogDistance = (view * worldPos).z;\r\n#endif\r\n\r\n\t// Shadows\r\n#ifdef SHADOWS\r\n#if defined(SPOTLIGHT0) || defined(DIRLIGHT0)\r\n\tvPositionFromLight0 = lightMatrix0 * worldPos;\r\n#endif\r\n#if defined(SPOTLIGHT1) || defined(DIRLIGHT1)\r\n\tvPositionFromLight1 = lightMatrix1 * worldPos;\r\n#endif\r\n#if defined(SPOTLIGHT2) || defined(DIRLIGHT2)\r\n\tvPositionFromLight2 = lightMatrix2 * worldPos;\r\n#endif\r\n#if defined(SPOTLIGHT3) || defined(DIRLIGHT3)\r\n\tvPositionFromLight3 = lightMatrix3 * worldPos;\r\n#endif\r\n#endif\r\n\r\n\t// Vertex color\r\n#ifdef VERTEXCOLOR\r\n\tvColor = color;\r\n#endif\r\n\r\n\t// Point size\r\n#ifdef POINTSIZE\r\n\tgl_PointSize = pointSize;\r\n#endif\r\n\r\n\tvec3 p = position;\r\n\tfloat newY = (sin(((p.x / 0.05) + time * waveSpeed)) * waveHeight * windDirection.x * 5.0)\r\n\t\t\t + (cos(((p.z / 0.05) + time * waveSpeed)) * waveHeight * windDirection.y * 5.0);\r\n\tp.y += abs(newY);\r\n\t\r\n\tgl_Position = viewProjection * finalWorld * vec4(p, 1.0);\r\n\r\n#ifdef REFLECTION\r\n\tworldPos = viewProjection * finalWorld * vec4(p, 1.0);\r\n\t\r\n\t// Water\r\n\tvPosition = position;\r\n\t\r\n\tvRefractionMapTexCoord.x = 0.5 * (worldPos.w + worldPos.x);\r\n\tvRefractionMapTexCoord.y = 0.5 * (worldPos.w + worldPos.y);\r\n\tvRefractionMapTexCoord.z = worldPos.w;\r\n\t\r\n\tworldPos = worldReflectionViewProjection * vec4(position, 1.0);\r\n\tvReflectionMapTexCoord.x = 0.5 * (worldPos.w + worldPos.x);\r\n\tvReflectionMapTexCoord.y = 0.5 * (worldPos.w + worldPos.y);\r\n\tvReflectionMapTexCoord.z = worldPos.w;\r\n#endif\r\n}\r\n";
  660. BABYLON.Effect.ShadersStore['waterPixelShader'] = "precision highp float;\r\n\r\n// Constants\r\nuniform vec3 vEyePosition;\r\nuniform vec4 vDiffuseColor;\r\n\r\n#ifdef SPECULARTERM\r\nuniform vec4 vSpecularColor;\r\n#endif\r\n\r\n// Input\r\nvarying vec3 vPositionW;\r\n\r\n#ifdef NORMAL\r\nvarying vec3 vNormalW;\r\n#endif\r\n\r\n#ifdef VERTEXCOLOR\r\nvarying vec4 vColor;\r\n#endif\r\n\r\n// Lights\r\n#ifdef LIGHT0\r\nuniform vec4 vLightData0;\r\nuniform vec4 vLightDiffuse0;\r\n#ifdef SPECULARTERM\r\nuniform vec3 vLightSpecular0;\r\n#endif\r\n#ifdef SHADOW0\r\n#if defined(SPOTLIGHT0) || defined(DIRLIGHT0)\r\nvarying vec4 vPositionFromLight0;\r\nuniform sampler2D shadowSampler0;\r\n#else\r\nuniform samplerCube shadowSampler0;\r\n#endif\r\nuniform vec3 shadowsInfo0;\r\n#endif\r\n#ifdef SPOTLIGHT0\r\nuniform vec4 vLightDirection0;\r\n#endif\r\n#ifdef HEMILIGHT0\r\nuniform vec3 vLightGround0;\r\n#endif\r\n#endif\r\n\r\n#ifdef LIGHT1\r\nuniform vec4 vLightData1;\r\nuniform vec4 vLightDiffuse1;\r\n#ifdef SPECULARTERM\r\nuniform vec3 vLightSpecular1;\r\n#endif\r\n#ifdef SHADOW1\r\n#if defined(SPOTLIGHT1) || defined(DIRLIGHT1)\r\nvarying vec4 vPositionFromLight1;\r\nuniform sampler2D shadowSampler1;\r\n#else\r\nuniform samplerCube shadowSampler1;\r\n#endif\r\nuniform vec3 shadowsInfo1;\r\n#endif\r\n#ifdef SPOTLIGHT1\r\nuniform vec4 vLightDirection1;\r\n#endif\r\n#ifdef HEMILIGHT1\r\nuniform vec3 vLightGround1;\r\n#endif\r\n#endif\r\n\r\n#ifdef LIGHT2\r\nuniform vec4 vLightData2;\r\nuniform vec4 vLightDiffuse2;\r\n#ifdef SPECULARTERM\r\nuniform vec3 vLightSpecular2;\r\n#endif\r\n#ifdef SHADOW2\r\n#if defined(SPOTLIGHT2) || defined(DIRLIGHT2)\r\nvarying vec4 vPositionFromLight2;\r\nuniform sampler2D shadowSampler2;\r\n#else\r\nuniform samplerCube shadowSampler2;\r\n#endif\r\nuniform vec3 shadowsInfo2;\r\n#endif\r\n#ifdef SPOTLIGHT2\r\nuniform vec4 vLightDirection2;\r\n#endif\r\n#ifdef HEMILIGHT2\r\nuniform vec3 vLightGround2;\r\n#endif\r\n#endif\r\n\r\n#ifdef LIGHT3\r\nuniform vec4 vLightData3;\r\nuniform vec4 vLightDiffuse3;\r\n#ifdef SPECULARTERM\r\nuniform vec3 vLightSpecular3;\r\n#endif\r\n#ifdef SHADOW3\r\n#if defined(SPOTLIGHT3) || defined(DIRLIGHT3)\r\nvarying vec4 vPositionFromLight3;\r\nuniform sampler2D shadowSampler3;\r\n#else\r\nuniform samplerCube shadowSampler3;\r\n#endif\r\nuniform vec3 shadowsInfo3;\r\n#endif\r\n#ifdef SPOTLIGHT3\r\nuniform vec4 vLightDirection3;\r\n#endif\r\n#ifdef HEMILIGHT3\r\nuniform vec3 vLightGround3;\r\n#endif\r\n#endif\r\n\r\n// Samplers\r\n#ifdef BUMP\r\nvarying vec2 vNormalUV;\r\nuniform sampler2D normalSampler;\r\nuniform vec2 vNormalInfos;\r\n#endif\r\n\r\nuniform sampler2D refractionSampler;\r\nuniform sampler2D reflectionSampler;\r\n\r\n// Water uniforms\r\nconst float LOG2 = 1.442695;\r\n\r\nuniform vec3 cameraPosition;\r\n\r\nuniform vec4 waterColor;\r\nuniform float colorBlendFactor;\r\n\r\nuniform float bumpHeight;\r\n\r\n// Water varyings\r\nvarying vec3 vRefractionMapTexCoord;\r\nvarying vec3 vReflectionMapTexCoord;\r\nvarying vec3 vPosition;\r\n\r\n// Shadows\r\n#ifdef SHADOWS\r\n\r\nfloat unpack(vec4 color)\r\n{\r\n\tconst vec4 bit_shift = vec4(1.0 / (255.0 * 255.0 * 255.0), 1.0 / (255.0 * 255.0), 1.0 / 255.0, 1.0);\r\n\treturn dot(color, bit_shift);\r\n}\r\n\r\n#if defined(POINTLIGHT0) || defined(POINTLIGHT1) || defined(POINTLIGHT2) || defined(POINTLIGHT3)\r\nfloat computeShadowCube(vec3 lightPosition, samplerCube shadowSampler, float darkness, float bias)\r\n{\r\n\tvec3 directionToLight = vPositionW - lightPosition;\r\n\tfloat depth = length(directionToLight);\r\n\tdepth = clamp(depth, 0., 1.0);\r\n\r\n\tdirectionToLight = normalize(directionToLight);\r\n\tdirectionToLight.y = - directionToLight.y;\r\n\r\n\tfloat shadow = unpack(textureCube(shadowSampler, directionToLight)) + bias;\r\n\r\n\tif (depth > shadow)\r\n\t{\r\n\t\treturn darkness;\r\n\t}\r\n\treturn 1.0;\r\n}\r\n\r\nfloat computeShadowWithPCFCube(vec3 lightPosition, samplerCube shadowSampler, float bias, float darkness, float mapSize)\r\n{\r\n\tvec3 directionToLight = vPositionW - lightPosition;\r\n\tfloat depth = length(directionToLight);\r\n\r\n\tdepth = clamp(depth, 0., 1.0);\r\n\tfloat diskScale = 2.0 / mapSize;\r\n\r\n\tdirectionToLight = normalize(directionToLight);\r\n\tdirectionToLight.y = -directionToLight.y;\r\n\r\n\tfloat visibility = 1.;\r\n\r\n\tvec3 poissonDisk[4];\r\n\tpoissonDisk[0] = vec3(-0.094201624, 0.04, -0.039906216);\r\n\tpoissonDisk[1] = vec3(0.094558609, -0.04, -0.076890725);\r\n\tpoissonDisk[2] = vec3(-0.094184101, 0.01, -0.092938870);\r\n\tpoissonDisk[3] = vec3(0.034495938, -0.01, 0.029387760);\r\n\r\n\t// Poisson Sampling\r\n\tfloat biasedDepth = depth - bias;\r\n\r\n\tif (unpack(textureCube(shadowSampler, directionToLight + poissonDisk[0])) < biasedDepth) visibility -= 0.25;\r\n\tif (unpack(textureCube(shadowSampler, directionToLight + poissonDisk[1])) < biasedDepth) visibility -= 0.25;\r\n\tif (unpack(textureCube(shadowSampler, directionToLight + poissonDisk[2])) < biasedDepth) visibility -= 0.25;\r\n\tif (unpack(textureCube(shadowSampler, directionToLight + poissonDisk[3])) < biasedDepth) visibility -= 0.25;\r\n\r\n\treturn min(1.0, visibility + darkness);\r\n}\r\n#endif\r\n\r\n#if defined(SPOTLIGHT0) || defined(SPOTLIGHT1) || defined(SPOTLIGHT2) || defined(SPOTLIGHT3) || defined(DIRLIGHT0) || defined(DIRLIGHT1) || defined(DIRLIGHT2) || defined(DIRLIGHT3)\r\nfloat computeShadow(vec4 vPositionFromLight, sampler2D shadowSampler, float darkness, float bias)\r\n{\r\n\tvec3 depth = vPositionFromLight.xyz / vPositionFromLight.w;\r\n\tdepth = 0.5 * depth + vec3(0.5);\r\n\tvec2 uv = depth.xy;\r\n\r\n\tif (uv.x < 0. || uv.x > 1.0 || uv.y < 0. || uv.y > 1.0)\r\n\t{\r\n\t\treturn 1.0;\r\n\t}\r\n\r\n\tfloat shadow = unpack(texture2D(shadowSampler, uv)) + bias;\r\n\r\n\tif (depth.z > shadow)\r\n\t{\r\n\t\treturn darkness;\r\n\t}\r\n\treturn 1.;\r\n}\r\n\r\nfloat computeShadowWithPCF(vec4 vPositionFromLight, sampler2D shadowSampler, float mapSize, float bias, float darkness)\r\n{\r\n\tvec3 depth = vPositionFromLight.xyz / vPositionFromLight.w;\r\n\tdepth = 0.5 * depth + vec3(0.5);\r\n\tvec2 uv = depth.xy;\r\n\r\n\tif (uv.x < 0. || uv.x > 1.0 || uv.y < 0. || uv.y > 1.0)\r\n\t{\r\n\t\treturn 1.0;\r\n\t}\r\n\r\n\tfloat visibility = 1.;\r\n\r\n\tvec2 poissonDisk[4];\r\n\tpoissonDisk[0] = vec2(-0.94201624, -0.39906216);\r\n\tpoissonDisk[1] = vec2(0.94558609, -0.76890725);\r\n\tpoissonDisk[2] = vec2(-0.094184101, -0.92938870);\r\n\tpoissonDisk[3] = vec2(0.34495938, 0.29387760);\r\n\r\n\t// Poisson Sampling\r\n\tfloat biasedDepth = depth.z - bias;\r\n\r\n\tif (unpack(texture2D(shadowSampler, uv + poissonDisk[0] / mapSize)) < biasedDepth) visibility -= 0.25;\r\n\tif (unpack(texture2D(shadowSampler, uv + poissonDisk[1] / mapSize)) < biasedDepth) visibility -= 0.25;\r\n\tif (unpack(texture2D(shadowSampler, uv + poissonDisk[2] / mapSize)) < biasedDepth) visibility -= 0.25;\r\n\tif (unpack(texture2D(shadowSampler, uv + poissonDisk[3] / mapSize)) < biasedDepth) visibility -= 0.25;\r\n\r\n\treturn min(1.0, visibility + darkness);\r\n}\r\n\r\n// Thanks to http://devmaster.net/\r\nfloat unpackHalf(vec2 color)\r\n{\r\n\treturn color.x + (color.y / 255.0);\r\n}\r\n\r\nfloat linstep(float low, float high, float v) {\r\n\treturn clamp((v - low) / (high - low), 0.0, 1.0);\r\n}\r\n\r\nfloat ChebychevInequality(vec2 moments, float compare, float bias)\r\n{\r\n\tfloat p = smoothstep(compare - bias, compare, moments.x);\r\n\tfloat variance = max(moments.y - moments.x * moments.x, 0.02);\r\n\tfloat d = compare - moments.x;\r\n\tfloat p_max = linstep(0.2, 1.0, variance / (variance + d * d));\r\n\r\n\treturn clamp(max(p, p_max), 0.0, 1.0);\r\n}\r\n\r\nfloat computeShadowWithVSM(vec4 vPositionFromLight, sampler2D shadowSampler, float bias, float darkness)\r\n{\r\n\tvec3 depth = vPositionFromLight.xyz / vPositionFromLight.w;\r\n\tdepth = 0.5 * depth + vec3(0.5);\r\n\tvec2 uv = depth.xy;\r\n\r\n\tif (uv.x < 0. || uv.x > 1.0 || uv.y < 0. || uv.y > 1.0 || depth.z >= 1.0)\r\n\t{\r\n\t\treturn 1.0;\r\n\t}\r\n\r\n\tvec4 texel = texture2D(shadowSampler, uv);\r\n\r\n\tvec2 moments = vec2(unpackHalf(texel.xy), unpackHalf(texel.zw));\r\n\treturn min(1.0, 1.0 - ChebychevInequality(moments, depth.z, bias) + darkness);\r\n}\r\n#endif\r\n#endif\r\n\r\n#ifdef CLIPPLANE\r\nvarying float fClipDistance;\r\n#endif\r\n\r\n// Fog\r\n#ifdef FOG\r\n\r\n#define FOGMODE_NONE 0.\r\n#define FOGMODE_EXP 1.\r\n#define FOGMODE_EXP2 2.\r\n#define FOGMODE_LINEAR 3.\r\n#define E 2.71828\r\n\r\nuniform vec4 vFogInfos;\r\nuniform vec3 vFogColor;\r\nvarying float fFogDistance;\r\n\r\nfloat CalcFogFactor()\r\n{\r\n\tfloat fogCoeff = 1.0;\r\n\tfloat fogStart = vFogInfos.y;\r\n\tfloat fogEnd = vFogInfos.z;\r\n\tfloat fogDensity = vFogInfos.w;\r\n\r\n\tif (FOGMODE_LINEAR == vFogInfos.x)\r\n\t{\r\n\t\tfogCoeff = (fogEnd - fFogDistance) / (fogEnd - fogStart);\r\n\t}\r\n\telse if (FOGMODE_EXP == vFogInfos.x)\r\n\t{\r\n\t\tfogCoeff = 1.0 / pow(E, fFogDistance * fogDensity);\r\n\t}\r\n\telse if (FOGMODE_EXP2 == vFogInfos.x)\r\n\t{\r\n\t\tfogCoeff = 1.0 / pow(E, fFogDistance * fFogDistance * fogDensity * fogDensity);\r\n\t}\r\n\r\n\treturn clamp(fogCoeff, 0.0, 1.0);\r\n}\r\n#endif\r\n\r\n// Light Computing\r\nstruct lightingInfo\r\n{\r\n\tvec3 diffuse;\r\n#ifdef SPECULARTERM\r\n\tvec3 specular;\r\n#endif\r\n};\r\n\r\nlightingInfo computeLighting(vec3 viewDirectionW, vec3 vNormal, vec4 lightData, vec3 diffuseColor, vec3 specularColor, float range, float glossiness, vec3 bumpColor) {\r\n\tlightingInfo result;\r\n\r\n\tvec3 lightVectorW;\r\n\tfloat attenuation = 1.0;\r\n\tif (lightData.w == 0.)\r\n\t{\r\n\t\tvec3 direction = lightData.xyz - vPositionW;\r\n\r\n\t\tattenuation = max(0., 1.0 - length(direction) / range);\r\n\t\tlightVectorW = normalize(direction);\r\n\t}\r\n\telse\r\n\t{\r\n\t\tlightVectorW = normalize(-lightData.xyz);\r\n\t}\r\n\r\n\t// diffuse\r\n\tfloat ndl = max(0., dot(vNormal, lightVectorW));\r\n\tresult.diffuse = ndl * diffuseColor * attenuation;\r\n\r\n\t// Specular\r\n#ifdef SPECULARTERM\r\n\tvec3 angleW = normalize(viewDirectionW + lightVectorW);\r\n\tvec3 perturbation = bumpHeight * (bumpColor.rgb - 0.5);\r\n\tvec3 halfvec = normalize(angleW + lightVectorW + vec3(perturbation.x, perturbation.y, perturbation.z));\r\n\t\r\n\tfloat temp = max(0., dot(vNormal, halfvec));\r\n\ttemp = pow(temp, max(1., glossiness));\r\n\t\r\n\tresult.specular = temp * specularColor * attenuation;\r\n#endif\r\n\r\n\treturn result;\r\n}\r\n\r\nlightingInfo computeSpotLighting(vec3 viewDirectionW, vec3 vNormal, vec4 lightData, vec4 lightDirection, vec3 specularColor, vec3 diffuseColor, float range, float glossiness, vec3 bumpColor) {\r\n\tlightingInfo result;\r\n\r\n\tvec3 direction = lightData.xyz - vPositionW;\r\n\tvec3 lightVectorW = normalize(direction);\r\n\tfloat attenuation = max(0., 1.0 - length(direction) / range);\r\n\r\n\t// diffuse\r\n\tfloat cosAngle = max(0., dot(-lightDirection.xyz, lightVectorW));\r\n\tfloat spotAtten = 0.0;\r\n\r\n\tif (cosAngle >= lightDirection.w)\r\n\t{\r\n\t\tcosAngle = max(0., pow(cosAngle, lightData.w));\r\n\t\tspotAtten = clamp((cosAngle - lightDirection.w) / (1. - cosAngle), 0.0, 1.0);\r\n\r\n\t\t// Diffuse\r\n\t\tfloat ndl = max(0., dot(vNormal, -lightDirection.xyz));\r\n\t\tresult.diffuse = ndl * spotAtten * diffuseColor * attenuation;\r\n\r\n\t\t// Specular\r\n#ifdef SPECULARTERM\t\t\r\n\t\tvec3 angleW = normalize(viewDirectionW - lightDirection.xyz);\r\n\t\tvec3 perturbation = bumpHeight * (bumpColor.rgb - 0.5);\r\n\t\tvec3 halfvec = normalize(angleW + vec3(perturbation.x, perturbation.y, perturbation.z));\r\n\t\t\r\n\t\tfloat temp = max(0., dot(vNormal, halfvec));\r\n\t\ttemp = pow(temp, max(1., glossiness));\r\n\t\t\r\n\t\tresult.specular = specularColor * temp * spotAtten * attenuation;\r\n#endif\r\n\t\treturn result;\r\n\t}\r\n\r\n\tresult.diffuse = vec3(0.);\r\n#ifdef SPECULARTERM\r\n\tresult.specular = vec3(0.);\r\n#endif\r\n\r\n\treturn result;\r\n}\r\n\r\nlightingInfo computeHemisphericLighting(vec3 viewDirectionW, vec3 vNormal, vec4 lightData, vec3 diffuseColor, vec3 specularColor, vec3 groundColor, float glossiness, vec3 bumpColor) {\r\n\tlightingInfo result;\r\n\r\n\t// Diffuse\r\n\tfloat ndl = dot(vNormal, lightData.xyz) * 0.5 + 0.5;\r\n\tresult.diffuse = mix(groundColor, diffuseColor, ndl);\r\n\t\r\n\t// Specular\r\n#ifdef SPECULARTERM\r\n\tvec3 angleW = normalize(viewDirectionW + lightData.xyz);\r\n\tvec3 perturbation = bumpHeight * (bumpColor.rgb - 0.5);\r\n\tvec3 halfvec = normalize(angleW + vec3(perturbation.x, perturbation.y, perturbation.z));\r\n\t\r\n\tfloat temp = max(0.0, dot(vNormal, halfvec));\r\n\ttemp = pow(temp, max(1.0, glossiness));\r\n\t\r\n\tresult.specular = temp * specularColor;\r\n#endif\r\n\r\n\treturn result;\r\n}\r\n\r\nvoid main(void) {\r\n\t// Clip plane\r\n#ifdef CLIPPLANE\r\n\tif (fClipDistance > 0.0)\r\n\t\tdiscard;\r\n#endif\r\n\r\n\tvec3 viewDirectionW = normalize(vEyePosition - vPositionW);\r\n\r\n\t// Base color\r\n\tvec4 baseColor = vec4(1., 1., 1., 1.);\r\n\tvec3 diffuseColor = vDiffuseColor.rgb;\r\n\t\r\n#ifdef SPECULARTERM\r\n\tfloat glossiness = vSpecularColor.a;\r\n\tvec3 specularColor = vSpecularColor.rgb;\r\n#else\r\n\tfloat glossiness = 0.;\r\n#endif\r\n\r\n\t// Alpha\r\n\tfloat alpha = vDiffuseColor.a;\r\n\r\n#ifdef BUMP\r\n\tbaseColor = texture2D(normalSampler, vNormalUV);\r\n\tvec3 bumpColor = baseColor.rgb;\r\n\r\n#ifdef ALPHATEST\r\n\tif (baseColor.a < 0.4)\r\n\t\tdiscard;\r\n#endif\r\n\r\n\tbaseColor.rgb *= vNormalInfos.y;\r\n#else\r\n\tvec3 bumpColor = vec3(1.0);\r\n#endif\r\n\r\n#ifdef VERTEXCOLOR\r\n\tbaseColor.rgb *= vColor.rgb;\r\n#endif\r\n\r\n\t// Bump\r\n#ifdef NORMAL\r\n\tvec3 normalW = normalize(vNormalW);\r\n\tvec2 perturbation = bumpHeight * (baseColor.rg - 0.5);\r\n#else\r\n\tvec3 normalW = vec3(1.0, 1.0, 1.0);\r\n\tvec2 perturbation = bumpHeight * (vec2(1.0, 1.0) - 0.5);\r\n#endif\r\n\r\n#ifdef REFLECTION\r\n\t// Water\r\n\tvec3 eyeVector = normalize(vEyePosition - vPosition);\r\n\t\r\n\tvec2 projectedRefractionTexCoords = clamp(vRefractionMapTexCoord.xy / vRefractionMapTexCoord.z + perturbation, 0.0, 1.0);\r\n\tvec4 refractiveColor = texture2D(refractionSampler, projectedRefractionTexCoords);\r\n\t\r\n\tvec2 projectedReflectionTexCoords = clamp(vReflectionMapTexCoord.xy / vReflectionMapTexCoord.z + perturbation, 0.0, 1.0);\r\n\tvec4 reflectiveColor = texture2D(reflectionSampler, projectedReflectionTexCoords);\r\n\t\r\n\tvec3 upVector = vec3(0.0, 1.0, 0.0);\r\n\t\r\n\tfloat fresnelTerm = max(dot(eyeVector, upVector), 0.0);\r\n\t\r\n\tvec4 combinedColor = refractiveColor * fresnelTerm + reflectiveColor * (1.0 - fresnelTerm);\r\n\t\r\n\tbaseColor = colorBlendFactor * waterColor + (1.0 - colorBlendFactor) * combinedColor;\r\n#endif\r\n\r\n\t// Lighting\r\n\tvec3 diffuseBase = vec3(0., 0., 0.);\r\n#ifdef SPECULARTERM\r\n\tvec3 specularBase = vec3(0., 0., 0.);\r\n#endif\r\n\tfloat shadow = 1.;\r\n\r\n#ifdef LIGHT0\r\n#ifndef SPECULARTERM\r\n\tvec3 vLightSpecular0 = vec3(0.0);\r\n#endif\r\n#ifdef SPOTLIGHT0\r\n\tlightingInfo info = computeSpotLighting(viewDirectionW, normalW, vLightData0, vLightDirection0, vLightDiffuse0.rgb, vLightSpecular0, vLightDiffuse0.a, glossiness, bumpColor);\r\n#endif\r\n#ifdef HEMILIGHT0\r\n\tlightingInfo info = computeHemisphericLighting(viewDirectionW, normalW, vLightData0, vLightDiffuse0.rgb, vLightSpecular0, vLightGround0, glossiness, bumpColor);\r\n#endif\r\n#if defined(POINTLIGHT0) || defined(DIRLIGHT0)\r\n\tlightingInfo info = computeLighting(viewDirectionW, normalW, vLightData0, vLightDiffuse0.rgb, vLightSpecular0, vLightDiffuse0.a, glossiness, bumpColor);\r\n#endif\r\n#ifdef SHADOW0\r\n#ifdef SHADOWVSM0\r\n\tshadow = computeShadowWithVSM(vPositionFromLight0, shadowSampler0, shadowsInfo0.z, shadowsInfo0.x);\r\n#else\r\n#ifdef SHADOWPCF0\r\n\t#if defined(POINTLIGHT0)\r\n\tshadow = computeShadowWithPCFCube(vLightData0.xyz, shadowSampler0, shadowsInfo0.z, shadowsInfo0.x, shadowsInfo0.y);\r\n\t#else\r\n\tshadow = computeShadowWithPCF(vPositionFromLight0, shadowSampler0, shadowsInfo0.y, shadowsInfo0.z, shadowsInfo0.x);\r\n\t#endif\r\n#else\r\n\t#if defined(POINTLIGHT0)\r\n\tshadow = computeShadowCube(vLightData0.xyz, shadowSampler0, shadowsInfo0.x, shadowsInfo0.z);\r\n\t#else\r\n\tshadow = computeShadow(vPositionFromLight0, shadowSampler0, shadowsInfo0.x, shadowsInfo0.z);\r\n\t#endif\r\n#endif\r\n#endif\r\n#else\r\n\tshadow = 1.;\r\n#endif\r\n\tdiffuseBase += info.diffuse * shadow;\r\n#ifdef SPECULARTERM\r\n\tspecularBase += info.specular * shadow;\r\n#endif\r\n#endif\r\n\r\n#ifdef LIGHT1\r\n#ifndef SPECULARTERM\r\n\tvec3 vLightSpecular1 = vec3(0.0);\r\n#endif\r\n#ifdef SPOTLIGHT1\r\n\tinfo = computeSpotLighting(viewDirectionW, normalW, vLightData1, vLightDirection1, vLightDiffuse1.rgb, vLightSpecular1, vLightDiffuse1.a, glossiness, bumpColor);\r\n#endif\r\n#ifdef HEMILIGHT1\r\n\tinfo = computeHemisphericLighting(viewDirectionW, normalW, vLightData1, vLightDiffuse1.rgb, vLightSpecular1, vLightGround1.a, glossiness, bumpColor);\r\n#endif\r\n#if defined(POINTLIGHT1) || defined(DIRLIGHT1)\r\n\tinfo = computeLighting(viewDirectionW, normalW, vLightData1, vLightDiffuse1.rgb, vLightSpecular1, vLightDiffuse1.a, glossiness, bumpColor);\r\n#endif\r\n#ifdef SHADOW1\r\n#ifdef SHADOWVSM1\r\n\tshadow = computeShadowWithVSM(vPositionFromLight1, shadowSampler1, shadowsInfo1.z, shadowsInfo1.x);\r\n#else\r\n#ifdef SHADOWPCF1\r\n#if defined(POINTLIGHT1)\r\n\tshadow = computeShadowWithPCFCube(vLightData1.xyz, shadowSampler1, shadowsInfo1.z, shadowsInfo1.x, shadowsInfo1.y);\r\n#else\r\n\tshadow = computeShadowWithPCF(vPositionFromLight1, shadowSampler1, shadowsInfo1.y, shadowsInfo1.z, shadowsInfo1.x);\r\n#endif\r\n#else\r\n\t#if defined(POINTLIGHT1)\r\n\tshadow = computeShadowCube(vLightData1.xyz, shadowSampler1, shadowsInfo1.x, shadowsInfo1.z);\r\n\t#else\r\n\tshadow = computeShadow(vPositionFromLight1, shadowSampler1, shadowsInfo1.x, shadowsInfo1.z);\r\n\t#endif\r\n#endif\r\n#endif\r\n#else\r\n\tshadow = 1.;\r\n#endif\r\n\tdiffuseBase += info.diffuse * shadow;\r\n#ifdef SPECULARTERM\r\n\tspecularBase += info.specular * shadow;\r\n#endif\r\n#endif\r\n\r\n#ifdef LIGHT2\r\n#ifndef SPECULARTERM\r\n\tvec3 vLightSpecular2 = vec3(0.0);\r\n#endif\r\n#ifdef SPOTLIGHT2\r\n\tinfo = computeSpotLighting(viewDirectionW, normalW, vLightData2, vLightDirection2, vLightDiffuse2.rgb, vLightSpecular2, vLightDiffuse2.a, glossiness, bumpColor);\r\n#endif\r\n#ifdef HEMILIGHT2\r\n\tinfo = computeHemisphericLighting(viewDirectionW, normalW, vLightData2, vLightDiffuse2.rgb, vLightSpecular2, vLightGround2, glossiness, bumpColor);\r\n#endif\r\n#if defined(POINTLIGHT2) || defined(DIRLIGHT2)\r\n\tinfo = computeLighting(viewDirectionW, normalW, vLightData2, vLightDiffuse2.rgb, vLightSpecular2, vLightDiffuse2.a, glossiness, bumpColor);\r\n#endif\r\n#ifdef SHADOW2\r\n#ifdef SHADOWVSM2\r\n\tshadow = computeShadowWithVSM(vPositionFromLight2, shadowSampler2, shadowsInfo2.z, shadowsInfo2.x);\r\n#else\r\n#ifdef SHADOWPCF2\r\n#if defined(POINTLIGHT2)\r\n\tshadow = computeShadowWithPCFCube(vLightData2.xyz, shadowSampler2, shadowsInfo2.z, shadowsInfo2.x, shadowsInfo2.y);\r\n#else\r\n\tshadow = computeShadowWithPCF(vPositionFromLight2, shadowSampler2, shadowsInfo2.y, shadowsInfo2.z, shadowsInfo2.x);\r\n#endif\r\n#else\r\n\t#if defined(POINTLIGHT2)\r\n\tshadow = computeShadowCube(vLightData2.xyz, shadowSampler2, shadowsInfo2.x, shadowsInfo2.z);\r\n\t#else\r\n\tshadow = computeShadow(vPositionFromLight2, shadowSampler2, shadowsInfo2.x, shadowsInfo2.z);\r\n\t#endif\r\n#endif\t\r\n#endif\t\r\n#else\r\n\tshadow = 1.;\r\n#endif\r\n\tdiffuseBase += info.diffuse * shadow;\r\n#ifdef SPECULARTERM\r\n\tspecularBase += info.specular * shadow;\r\n#endif\r\n#endif\r\n\r\n#ifdef LIGHT3\r\n#ifndef SPECULARTERM\r\n\tvec3 vLightSpecular3 = vec3(0.0);\r\n#endif\r\n#ifdef SPOTLIGHT3\r\n\tinfo = computeSpotLighting(viewDirectionW, normalW, vLightData3, vLightDirection3, vLightDiffuse3.rgb, vLightSpecular3, vLightDiffuse3.a, glossiness, bumpColor);\r\n#endif\r\n#ifdef HEMILIGHT3\r\n\tinfo = computeHemisphericLighting(viewDirectionW, normalW, vLightData3, vLightDiffuse3.rgb, vLightSpecular3, vLightGround3, glossiness, bumpColor);\r\n#endif\r\n#if defined(POINTLIGHT3) || defined(DIRLIGHT3)\r\n\tinfo = computeLighting(viewDirectionW, normalW, vLightData3, vLightDiffuse3.rgb, vLightSpecular3, vLightDiffuse3.a, glossiness, bumpColor);\r\n#endif\r\n#ifdef SHADOW3\r\n#ifdef SHADOWVSM3\r\n\t\tshadow = computeShadowWithVSM(vPositionFromLight3, shadowSampler3, shadowsInfo3.z, shadowsInfo3.x);\r\n#else\r\n#ifdef SHADOWPCF3\r\n#if defined(POINTLIGHT3)\r\n\tshadow = computeShadowWithPCFCube(vLightData3.xyz, shadowSampler3, shadowsInfo3.z, shadowsInfo3.x, shadowsInfo3.y);\r\n#else\r\n\tshadow = computeShadowWithPCF(vPositionFromLight3, shadowSampler3, shadowsInfo3.y, shadowsInfo3.z, shadowsInfo3.x);\r\n#endif\r\n#else\r\n\t#if defined(POINTLIGHT3)\r\n\tshadow = computeShadowCube(vLightData3.xyz, shadowSampler3, shadowsInfo3.x, shadowsInfo3.z);\r\n\t#else\r\n\tshadow = computeShadow(vPositionFromLight3, shadowSampler3, shadowsInfo3.x, shadowsInfo3.z);\r\n\t#endif\r\n#endif\t\r\n#endif\t\r\n#else\r\n\tshadow = 1.;\r\n#endif\r\n\tdiffuseBase += info.diffuse * shadow;\r\n#ifdef SPECULARTERM\r\n\tspecularBase += info.specular * shadow;\r\n#endif\r\n#endif\r\n\r\n#ifdef VERTEXALPHA\r\n\talpha *= vColor.a;\r\n#endif\r\n\r\n#ifdef SPECULARTERM\r\n\tvec3 finalSpecular = specularBase * specularColor;\r\n#else\r\n\tvec3 finalSpecular = vec3(0.0);\r\n#endif\r\n\r\n\tvec3 finalDiffuse = clamp(diffuseBase * diffuseColor, 0.0, 1.0) * baseColor.rgb;\r\n\r\n\t// Composition\r\n\tvec4 color = vec4(finalDiffuse + finalSpecular, alpha);\r\n\r\n#ifdef FOG\r\n\tfloat fog = CalcFogFactor();\r\n\tcolor.rgb = fog * color.rgb + (1.0 - fog) * vFogColor;\r\n#endif\r\n\t\r\n\tgl_FragColor = color;\r\n}";