babylon.terrainMaterial.ts 23 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595
  1. /// <reference path="../../../dist/preview release/babylon.d.ts"/>
  2. module BABYLON {
  3. var maxSimultaneousLights = 4;
  4. class TerrainMaterialDefines extends MaterialDefines {
  5. public DIFFUSE = false;
  6. public BUMP = false;
  7. public CLIPPLANE = false;
  8. public ALPHATEST = false;
  9. public POINTSIZE = false;
  10. public FOG = false;
  11. public LIGHT0 = false;
  12. public LIGHT1 = false;
  13. public LIGHT2 = false;
  14. public LIGHT3 = false;
  15. public SPOTLIGHT0 = false;
  16. public SPOTLIGHT1 = false;
  17. public SPOTLIGHT2 = false;
  18. public SPOTLIGHT3 = false;
  19. public HEMILIGHT0 = false;
  20. public HEMILIGHT1 = false;
  21. public HEMILIGHT2 = false;
  22. public HEMILIGHT3 = false;
  23. public DIRLIGHT0 = false;
  24. public DIRLIGHT1 = false;
  25. public DIRLIGHT2 = false;
  26. public DIRLIGHT3 = false;
  27. public POINTLIGHT0 = false;
  28. public POINTLIGHT1 = false;
  29. public POINTLIGHT2 = false;
  30. public POINTLIGHT3 = false;
  31. public SHADOW0 = false;
  32. public SHADOW1 = false;
  33. public SHADOW2 = false;
  34. public SHADOW3 = false;
  35. public SHADOWS = false;
  36. public SHADOWVSM0 = false;
  37. public SHADOWVSM1 = false;
  38. public SHADOWVSM2 = false;
  39. public SHADOWVSM3 = false;
  40. public SHADOWPCF0 = false;
  41. public SHADOWPCF1 = false;
  42. public SHADOWPCF2 = false;
  43. public SHADOWPCF3 = false;
  44. public SPECULARTERM = false;
  45. public NORMAL = false;
  46. public UV1 = false;
  47. public UV2 = false;
  48. public VERTEXCOLOR = false;
  49. public VERTEXALPHA = false;
  50. public BONES = false;
  51. public BONES4 = false;
  52. public BonesPerMesh = 0;
  53. public INSTANCES = false;
  54. constructor() {
  55. super();
  56. this._keys = Object.keys(this);
  57. }
  58. }
  59. export class TerrainMaterial extends Material {
  60. @serializeAsTexture()
  61. public mixTexture: BaseTexture;
  62. @serializeAsTexture()
  63. public diffuseTexture1: Texture;
  64. @serializeAsTexture()
  65. public diffuseTexture2: Texture;
  66. @serializeAsTexture()
  67. public diffuseTexture3: Texture;
  68. @serializeAsTexture()
  69. public bumpTexture1: Texture;
  70. @serializeAsTexture()
  71. public bumpTexture2: Texture;
  72. @serializeAsTexture()
  73. public bumpTexture3: Texture;
  74. @serializeAsColor3()
  75. public diffuseColor = new Color3(1, 1, 1);
  76. @serializeAsColor3()
  77. public specularColor = new Color3(0, 0, 0);
  78. @serialize()
  79. public specularPower = 64;
  80. @serialize()
  81. public disableLighting = false;
  82. private _worldViewProjectionMatrix = Matrix.Zero();
  83. private _scaledDiffuse = new Color3();
  84. private _scaledSpecular = new Color3();
  85. private _renderId: number;
  86. private _defines = new TerrainMaterialDefines();
  87. private _cachedDefines = new TerrainMaterialDefines();
  88. constructor(name: string, scene: Scene) {
  89. super(name, scene);
  90. this._cachedDefines.BonesPerMesh = -1;
  91. }
  92. public needAlphaBlending(): boolean {
  93. return (this.alpha < 1.0);
  94. }
  95. public needAlphaTesting(): boolean {
  96. return false;
  97. }
  98. public getAlphaTestTexture(): BaseTexture {
  99. return null;
  100. }
  101. // Methods
  102. private _checkCache(scene: Scene, mesh?: AbstractMesh, useInstances?: boolean): boolean {
  103. if (!mesh) {
  104. return true;
  105. }
  106. if (this._defines.INSTANCES !== useInstances) {
  107. return false;
  108. }
  109. if (mesh._materialDefines && mesh._materialDefines.isEqual(this._defines)) {
  110. return true;
  111. }
  112. return false;
  113. }
  114. public isReady(mesh?: AbstractMesh, useInstances?: boolean): boolean {
  115. if (this.checkReadyOnlyOnce) {
  116. if (this._wasPreviouslyReady) {
  117. return true;
  118. }
  119. }
  120. var scene = this.getScene();
  121. if (!this.checkReadyOnEveryCall) {
  122. if (this._renderId === scene.getRenderId()) {
  123. if (this._checkCache(scene, mesh, useInstances)) {
  124. return true;
  125. }
  126. }
  127. }
  128. var engine = scene.getEngine();
  129. var needNormals = false;
  130. var needUVs = false;
  131. this._defines.reset();
  132. // Textures
  133. if (scene.texturesEnabled) {
  134. if (this.mixTexture && StandardMaterial.DiffuseTextureEnabled) {
  135. if (!this.mixTexture.isReady()) {
  136. return false;
  137. } else {
  138. needUVs = true;
  139. this._defines.DIFFUSE = true;
  140. }
  141. }
  142. if ((this.bumpTexture1 || this.bumpTexture2 || this.bumpTexture3) && StandardMaterial.BumpTextureEnabled) {
  143. needUVs = true;
  144. needNormals = true;
  145. this._defines.BUMP = true;
  146. }
  147. }
  148. // Effect
  149. if (scene.clipPlane) {
  150. this._defines.CLIPPLANE = true;
  151. }
  152. if (engine.getAlphaTesting()) {
  153. this._defines.ALPHATEST = true;
  154. }
  155. // Point size
  156. if (this.pointsCloud || scene.forcePointsCloud) {
  157. this._defines.POINTSIZE = true;
  158. }
  159. // Fog
  160. if (scene.fogEnabled && mesh && mesh.applyFog && scene.fogMode !== Scene.FOGMODE_NONE && this.fogEnabled) {
  161. this._defines.FOG = true;
  162. }
  163. var lightIndex = 0;
  164. if (scene.lightsEnabled && !this.disableLighting) {
  165. for (var index = 0; index < scene.lights.length; index++) {
  166. var light = scene.lights[index];
  167. if (!light.isEnabled()) {
  168. continue;
  169. }
  170. // Excluded check
  171. if (light._excludedMeshesIds.length > 0) {
  172. for (var excludedIndex = 0; excludedIndex < light._excludedMeshesIds.length; excludedIndex++) {
  173. var excludedMesh = scene.getMeshByID(light._excludedMeshesIds[excludedIndex]);
  174. if (excludedMesh) {
  175. light.excludedMeshes.push(excludedMesh);
  176. }
  177. }
  178. light._excludedMeshesIds = [];
  179. }
  180. // Included check
  181. if (light._includedOnlyMeshesIds.length > 0) {
  182. for (var includedOnlyIndex = 0; includedOnlyIndex < light._includedOnlyMeshesIds.length; includedOnlyIndex++) {
  183. var includedOnlyMesh = scene.getMeshByID(light._includedOnlyMeshesIds[includedOnlyIndex]);
  184. if (includedOnlyMesh) {
  185. light.includedOnlyMeshes.push(includedOnlyMesh);
  186. }
  187. }
  188. light._includedOnlyMeshesIds = [];
  189. }
  190. if (!light.canAffectMesh(mesh)) {
  191. continue;
  192. }
  193. needNormals = true;
  194. this._defines["LIGHT" + lightIndex] = true;
  195. var type;
  196. if (light instanceof SpotLight) {
  197. type = "SPOTLIGHT" + lightIndex;
  198. } else if (light instanceof HemisphericLight) {
  199. type = "HEMILIGHT" + lightIndex;
  200. } else if (light instanceof PointLight) {
  201. type = "POINTLIGHT" + lightIndex;
  202. } else {
  203. type = "DIRLIGHT" + lightIndex;
  204. }
  205. this._defines[type] = true;
  206. // Specular
  207. if (!light.specular.equalsFloats(0, 0, 0)) {
  208. this._defines.SPECULARTERM = true;
  209. }
  210. // Shadows
  211. if (scene.shadowsEnabled) {
  212. var shadowGenerator = light.getShadowGenerator();
  213. if (mesh && mesh.receiveShadows && shadowGenerator) {
  214. this._defines["SHADOW" + lightIndex] = true;
  215. this._defines.SHADOWS = true;
  216. if (shadowGenerator.useVarianceShadowMap || shadowGenerator.useBlurVarianceShadowMap) {
  217. this._defines["SHADOWVSM" + lightIndex] = true;
  218. }
  219. if (shadowGenerator.usePoissonSampling) {
  220. this._defines["SHADOWPCF" + lightIndex] = true;
  221. }
  222. }
  223. }
  224. lightIndex++;
  225. if (lightIndex === maxSimultaneousLights)
  226. break;
  227. }
  228. }
  229. // Attribs
  230. if (mesh) {
  231. if (needNormals && mesh.isVerticesDataPresent(VertexBuffer.NormalKind)) {
  232. this._defines.NORMAL = true;
  233. }
  234. if (needUVs) {
  235. if (mesh.isVerticesDataPresent(VertexBuffer.UVKind)) {
  236. this._defines.UV1 = true;
  237. }
  238. if (mesh.isVerticesDataPresent(VertexBuffer.UV2Kind)) {
  239. this._defines.UV2 = true;
  240. }
  241. }
  242. if (mesh.useVertexColors && mesh.isVerticesDataPresent(VertexBuffer.ColorKind)) {
  243. this._defines.VERTEXCOLOR = true;
  244. if (mesh.hasVertexAlpha) {
  245. this._defines.VERTEXALPHA = true;
  246. }
  247. }
  248. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  249. this._defines.BONES = true;
  250. this._defines.BonesPerMesh = (mesh.skeleton.bones.length + 1);
  251. this._defines.BONES4 = true;
  252. }
  253. // Instances
  254. if (useInstances) {
  255. this._defines.INSTANCES = true;
  256. }
  257. }
  258. // Get correct effect
  259. if (!this._defines.isEqual(this._cachedDefines)) {
  260. this._defines.cloneTo(this._cachedDefines);
  261. scene.resetCachedMaterial();
  262. // Fallbacks
  263. var fallbacks = new EffectFallbacks();
  264. if (this._defines.FOG) {
  265. fallbacks.addFallback(1, "FOG");
  266. }
  267. for (lightIndex = 0; lightIndex < maxSimultaneousLights; lightIndex++) {
  268. if (!this._defines["LIGHT" + lightIndex]) {
  269. continue;
  270. }
  271. if (lightIndex > 0) {
  272. fallbacks.addFallback(lightIndex, "LIGHT" + lightIndex);
  273. }
  274. if (this._defines["SHADOW" + lightIndex]) {
  275. fallbacks.addFallback(0, "SHADOW" + lightIndex);
  276. }
  277. if (this._defines["SHADOWPCF" + lightIndex]) {
  278. fallbacks.addFallback(0, "SHADOWPCF" + lightIndex);
  279. }
  280. if (this._defines["SHADOWVSM" + lightIndex]) {
  281. fallbacks.addFallback(0, "SHADOWVSM" + lightIndex);
  282. }
  283. }
  284. if (this._defines.BONES4) {
  285. fallbacks.addFallback(0, "BONES4");
  286. }
  287. //Attributes
  288. var attribs = [VertexBuffer.PositionKind];
  289. if (this._defines.NORMAL) {
  290. attribs.push(VertexBuffer.NormalKind);
  291. }
  292. if (this._defines.UV1) {
  293. attribs.push(VertexBuffer.UVKind);
  294. }
  295. if (this._defines.UV2) {
  296. attribs.push(VertexBuffer.UV2Kind);
  297. }
  298. if (this._defines.VERTEXCOLOR) {
  299. attribs.push(VertexBuffer.ColorKind);
  300. }
  301. if (this._defines.BONES) {
  302. attribs.push(VertexBuffer.MatricesIndicesKind);
  303. attribs.push(VertexBuffer.MatricesWeightsKind);
  304. }
  305. if (this._defines.INSTANCES) {
  306. attribs.push("world0");
  307. attribs.push("world1");
  308. attribs.push("world2");
  309. attribs.push("world3");
  310. }
  311. // Legacy browser patch
  312. var shaderName = "terrain";
  313. var join = this._defines.toString();
  314. this._effect = scene.getEngine().createEffect(shaderName,
  315. attribs,
  316. ["world", "view", "viewProjection", "vEyePosition", "vLightsType", "vDiffuseColor", "vSpecularColor",
  317. "vLightData0", "vLightDiffuse0", "vLightSpecular0", "vLightDirection0", "vLightGround0", "lightMatrix0",
  318. "vLightData1", "vLightDiffuse1", "vLightSpecular1", "vLightDirection1", "vLightGround1", "lightMatrix1",
  319. "vLightData2", "vLightDiffuse2", "vLightSpecular2", "vLightDirection2", "vLightGround2", "lightMatrix2",
  320. "vLightData3", "vLightDiffuse3", "vLightSpecular3", "vLightDirection3", "vLightGround3", "lightMatrix3",
  321. "vFogInfos", "vFogColor", "pointSize",
  322. "vTextureInfos",
  323. "mBones",
  324. "vClipPlane", "textureMatrix",
  325. "shadowsInfo0", "shadowsInfo1", "shadowsInfo2", "shadowsInfo3",
  326. "diffuse1Infos", "diffuse2Infos", "diffuse3Infos"
  327. ],
  328. ["textureSampler", "diffuse1Sampler", "diffuse2Sampler", "diffuse3Sampler",
  329. "bump1Sampler", "bump2Sampler", "bump3Sampler",
  330. "shadowSampler0", "shadowSampler1", "shadowSampler2", "shadowSampler3"
  331. ],
  332. join, fallbacks, this.onCompiled, this.onError);
  333. }
  334. if (!this._effect.isReady()) {
  335. return false;
  336. }
  337. this._renderId = scene.getRenderId();
  338. this._wasPreviouslyReady = true;
  339. if (mesh) {
  340. if (!mesh._materialDefines) {
  341. mesh._materialDefines = new TerrainMaterialDefines();
  342. }
  343. this._defines.cloneTo(mesh._materialDefines);
  344. }
  345. return true;
  346. }
  347. public bindOnlyWorldMatrix(world: Matrix): void {
  348. this._effect.setMatrix("world", world);
  349. }
  350. public bind(world: Matrix, mesh?: Mesh): void {
  351. var scene = this.getScene();
  352. // Matrices
  353. this.bindOnlyWorldMatrix(world);
  354. this._effect.setMatrix("viewProjection", scene.getTransformMatrix());
  355. // Bones
  356. if (mesh && mesh.useBones && mesh.computeBonesUsingShaders) {
  357. this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  358. }
  359. if (scene.getCachedMaterial() !== this) {
  360. // Textures
  361. if (this.mixTexture) {
  362. this._effect.setTexture("textureSampler", this.mixTexture);
  363. this._effect.setFloat2("vTextureInfos", this.mixTexture.coordinatesIndex, this.mixTexture.level);
  364. this._effect.setMatrix("textureMatrix", this.mixTexture.getTextureMatrix());
  365. if (StandardMaterial.DiffuseTextureEnabled) {
  366. if (this.diffuseTexture1) {
  367. this._effect.setTexture("diffuse1Sampler", this.diffuseTexture1);
  368. this._effect.setFloat2("diffuse1Infos", this.diffuseTexture1.uScale, this.diffuseTexture1.vScale);
  369. }
  370. if (this.diffuseTexture2) {
  371. this._effect.setTexture("diffuse2Sampler", this.diffuseTexture2);
  372. this._effect.setFloat2("diffuse2Infos", this.diffuseTexture2.uScale, this.diffuseTexture2.vScale);
  373. }
  374. if (this.diffuseTexture3) {
  375. this._effect.setTexture("diffuse3Sampler", this.diffuseTexture3);
  376. this._effect.setFloat2("diffuse3Infos", this.diffuseTexture3.uScale, this.diffuseTexture3.vScale);
  377. }
  378. }
  379. if (StandardMaterial.BumpTextureEnabled && scene.getEngine().getCaps().standardDerivatives) {
  380. if (this.bumpTexture1) {
  381. this._effect.setTexture("bump1Sampler", this.bumpTexture1);
  382. }
  383. if (this.bumpTexture2) {
  384. this._effect.setTexture("bump2Sampler", this.bumpTexture2);
  385. }
  386. if (this.bumpTexture3) {
  387. this._effect.setTexture("bump3Sampler", this.bumpTexture3);
  388. }
  389. }
  390. }
  391. // Clip plane
  392. if (scene.clipPlane) {
  393. var clipPlane = scene.clipPlane;
  394. this._effect.setFloat4("vClipPlane", clipPlane.normal.x, clipPlane.normal.y, clipPlane.normal.z, clipPlane.d);
  395. }
  396. // Point size
  397. if (this.pointsCloud) {
  398. this._effect.setFloat("pointSize", this.pointSize);
  399. }
  400. this._effect.setVector3("vEyePosition", scene._mirroredCameraPosition ? scene._mirroredCameraPosition : scene.activeCamera.position);
  401. }
  402. this._effect.setColor4("vDiffuseColor", this._scaledDiffuse, this.alpha * mesh.visibility);
  403. if (this._defines.SPECULARTERM) {
  404. this._effect.setColor4("vSpecularColor", this.specularColor, this.specularPower);
  405. }
  406. if (scene.lightsEnabled && !this.disableLighting) {
  407. var lightIndex = 0;
  408. for (var index = 0; index < scene.lights.length; index++) {
  409. var light = scene.lights[index];
  410. if (!light.isEnabled()) {
  411. continue;
  412. }
  413. if (!light.canAffectMesh(mesh)) {
  414. continue;
  415. }
  416. if (light instanceof PointLight) {
  417. // Point Light
  418. light.transferToEffect(this._effect, "vLightData" + lightIndex);
  419. } else if (light instanceof DirectionalLight) {
  420. // Directional Light
  421. light.transferToEffect(this._effect, "vLightData" + lightIndex);
  422. } else if (light instanceof SpotLight) {
  423. // Spot Light
  424. light.transferToEffect(this._effect, "vLightData" + lightIndex, "vLightDirection" + lightIndex);
  425. } else if (light instanceof HemisphericLight) {
  426. // Hemispheric Light
  427. light.transferToEffect(this._effect, "vLightData" + lightIndex, "vLightGround" + lightIndex);
  428. }
  429. light.diffuse.scaleToRef(light.intensity, this._scaledDiffuse);
  430. this._effect.setColor4("vLightDiffuse" + lightIndex, this._scaledDiffuse, light.range);
  431. if (this._defines.SPECULARTERM) {
  432. light.specular.scaleToRef(light.intensity, this._scaledSpecular);
  433. this._effect.setColor3("vLightSpecular" + lightIndex, this._scaledSpecular);
  434. }
  435. // Shadows
  436. if (scene.shadowsEnabled) {
  437. var shadowGenerator = light.getShadowGenerator();
  438. if (mesh.receiveShadows && shadowGenerator) {
  439. this._effect.setMatrix("lightMatrix" + lightIndex, shadowGenerator.getTransformMatrix());
  440. this._effect.setTexture("shadowSampler" + lightIndex, shadowGenerator.getShadowMapForRendering());
  441. this._effect.setFloat3("shadowsInfo" + lightIndex, shadowGenerator.getDarkness(), shadowGenerator.getShadowMap().getSize().width, shadowGenerator.bias);
  442. }
  443. }
  444. lightIndex++;
  445. if (lightIndex === maxSimultaneousLights)
  446. break;
  447. }
  448. }
  449. // View
  450. if (scene.fogEnabled && mesh.applyFog && scene.fogMode !== Scene.FOGMODE_NONE) {
  451. this._effect.setMatrix("view", scene.getViewMatrix());
  452. }
  453. // Fog
  454. if (scene.fogEnabled && mesh.applyFog && scene.fogMode !== Scene.FOGMODE_NONE) {
  455. this._effect.setFloat4("vFogInfos", scene.fogMode, scene.fogStart, scene.fogEnd, scene.fogDensity);
  456. this._effect.setColor3("vFogColor", scene.fogColor);
  457. }
  458. super.bind(world, mesh);
  459. }
  460. public getAnimatables(): IAnimatable[] {
  461. var results = [];
  462. if (this.mixTexture && this.mixTexture.animations && this.mixTexture.animations.length > 0) {
  463. results.push(this.mixTexture);
  464. }
  465. return results;
  466. }
  467. public dispose(forceDisposeEffect?: boolean): void {
  468. if (this.mixTexture) {
  469. this.mixTexture.dispose();
  470. }
  471. super.dispose(forceDisposeEffect);
  472. }
  473. public clone(name: string): TerrainMaterial {
  474. return SerializationHelper.Clone(() => new TerrainMaterial(name, this.getScene()), this);
  475. }
  476. public serialize(): any {
  477. var serializationObject = SerializationHelper.Serialize(this);
  478. serializationObject.customType = "BABYLON.TerrainMaterial";
  479. return serializationObject;
  480. }
  481. // Statics
  482. public static Parse(source: any, scene: Scene, rootUrl: string): TerrainMaterial {
  483. return SerializationHelper.Parse(() => new TerrainMaterial(source.name, scene), source, scene, rootUrl);
  484. }
  485. }
  486. }