reflectionTextureBaseBlock.ts 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463
  1. import { NodeMaterialBlock } from '../../nodeMaterialBlock';
  2. import { NodeMaterialBuildState } from '../../nodeMaterialBuildState';
  3. import { NodeMaterialBlockTargets } from '../../Enums/nodeMaterialBlockTargets';
  4. import { NodeMaterialConnectionPoint } from '../../nodeMaterialBlockConnectionPoint';
  5. import { BaseTexture } from '../../../Textures/baseTexture';
  6. import { AbstractMesh } from '../../../../Meshes/abstractMesh';
  7. import { NodeMaterial, NodeMaterialDefines } from '../../nodeMaterial';
  8. import { Effect } from '../../../effect';
  9. import { Mesh } from '../../../../Meshes/mesh';
  10. import { Nullable } from '../../../../types';
  11. import { _TypeStore } from '../../../../Misc/typeStore';
  12. import { Scene } from '../../../../scene';
  13. import { InputBlock } from '../Input/inputBlock';
  14. import { NodeMaterialSystemValues } from '../../Enums/nodeMaterialSystemValues';
  15. import { Constants } from '../../../../Engines/constants';
  16. import "../../../../Shaders/ShadersInclude/reflectionFunction";
  17. import { CubeTexture } from '../../../Textures/cubeTexture';
  18. import { Texture } from '../../../Textures/texture';
  19. /**
  20. * Base block used to read a reflection texture from a sampler
  21. */
  22. export abstract class ReflectionTextureBaseBlock extends NodeMaterialBlock {
  23. /** @hidden */
  24. public _define3DName: string;
  25. /** @hidden */
  26. public _defineCubicName: string;
  27. /** @hidden */
  28. public _defineExplicitName: string;
  29. /** @hidden */
  30. public _defineProjectionName: string;
  31. /** @hidden */
  32. public _defineLocalCubicName: string;
  33. /** @hidden */
  34. public _defineSphericalName: string;
  35. /** @hidden */
  36. public _definePlanarName: string;
  37. /** @hidden */
  38. public _defineEquirectangularName: string;
  39. /** @hidden */
  40. public _defineMirroredEquirectangularFixedName: string;
  41. /** @hidden */
  42. public _defineEquirectangularFixedName: string;
  43. /** @hidden */
  44. public _defineSkyboxName: string;
  45. /** @hidden */
  46. public _defineOppositeZ: string;
  47. /** @hidden */
  48. public _cubeSamplerName: string;
  49. /** @hidden */
  50. public _2DSamplerName: string;
  51. protected _positionUVWName: string;
  52. protected _directionWName: string;
  53. protected _reflectionVectorName: string;
  54. /** @hidden */
  55. public _reflectionCoordsName: string;
  56. /** @hidden */
  57. public _reflectionMatrixName: string;
  58. protected _reflectionColorName: string;
  59. /**
  60. * Gets or sets the texture associated with the node
  61. */
  62. public texture: Nullable<BaseTexture>;
  63. /**
  64. * Create a new ReflectionTextureBaseBlock
  65. * @param name defines the block name
  66. */
  67. public constructor(name: string) {
  68. super(name, NodeMaterialBlockTargets.VertexAndFragment);
  69. }
  70. /**
  71. * Gets the current class name
  72. * @returns the class name
  73. */
  74. public getClassName() {
  75. return "ReflectionTextureBaseBlock";
  76. }
  77. /**
  78. * Gets the world position input component
  79. */
  80. public abstract get position(): NodeMaterialConnectionPoint;
  81. /**
  82. * Gets the world position input component
  83. */
  84. public abstract get worldPosition(): NodeMaterialConnectionPoint;
  85. /**
  86. * Gets the world normal input component
  87. */
  88. public abstract get worldNormal(): NodeMaterialConnectionPoint;
  89. /**
  90. * Gets the world input component
  91. */
  92. public abstract get world(): NodeMaterialConnectionPoint;
  93. /**
  94. * Gets the camera (or eye) position component
  95. */
  96. public abstract get cameraPosition(): NodeMaterialConnectionPoint;
  97. /**
  98. * Gets the view input component
  99. */
  100. public abstract get view(): NodeMaterialConnectionPoint;
  101. protected _getTexture(): Nullable<BaseTexture> {
  102. return this.texture;
  103. }
  104. public autoConfigure(material: NodeMaterial) {
  105. if (!this.position.isConnected) {
  106. let positionInput = material.getInputBlockByPredicate((b) => b.isAttribute && b.name === "position");
  107. if (!positionInput) {
  108. positionInput = new InputBlock("position");
  109. positionInput.setAsAttribute();
  110. }
  111. positionInput.output.connectTo(this.position);
  112. }
  113. if (!this.world.isConnected) {
  114. let worldInput = material.getInputBlockByPredicate((b) => b.systemValue === NodeMaterialSystemValues.World);
  115. if (!worldInput) {
  116. worldInput = new InputBlock("world");
  117. worldInput.setAsSystemValue(NodeMaterialSystemValues.World);
  118. }
  119. worldInput.output.connectTo(this.world);
  120. }
  121. if (!this.view.isConnected) {
  122. let viewInput = material.getInputBlockByPredicate((b) => b.systemValue === NodeMaterialSystemValues.View);
  123. if (!viewInput) {
  124. viewInput = new InputBlock("view");
  125. viewInput.setAsSystemValue(NodeMaterialSystemValues.View);
  126. }
  127. viewInput.output.connectTo(this.view);
  128. }
  129. }
  130. public prepareDefines(mesh: AbstractMesh, nodeMaterial: NodeMaterial, defines: NodeMaterialDefines) {
  131. if (!defines._areTexturesDirty) {
  132. return;
  133. }
  134. const texture = this._getTexture();
  135. if (!texture || !texture.getTextureMatrix) {
  136. return;
  137. }
  138. defines.setValue(this._define3DName, texture.isCube, true);
  139. defines.setValue(this._defineLocalCubicName, (<any>texture).boundingBoxSize ? true : false, true);
  140. defines.setValue(this._defineExplicitName, texture.coordinatesMode === Constants.TEXTURE_EXPLICIT_MODE, true);
  141. defines.setValue(this._defineSkyboxName, texture.coordinatesMode === Constants.TEXTURE_SKYBOX_MODE, true);
  142. defines.setValue(this._defineCubicName, texture.coordinatesMode === Constants.TEXTURE_CUBIC_MODE, true);
  143. defines.setValue(this._defineSphericalName, texture.coordinatesMode === Constants.TEXTURE_SPHERICAL_MODE, true);
  144. defines.setValue(this._definePlanarName, texture.coordinatesMode === Constants.TEXTURE_PLANAR_MODE, true);
  145. defines.setValue(this._defineProjectionName, texture.coordinatesMode === Constants.TEXTURE_PROJECTION_MODE, true);
  146. defines.setValue(this._defineEquirectangularName, texture.coordinatesMode === Constants.TEXTURE_EQUIRECTANGULAR_MODE, true);
  147. defines.setValue(this._defineEquirectangularFixedName, texture.coordinatesMode === Constants.TEXTURE_FIXED_EQUIRECTANGULAR_MODE, true);
  148. defines.setValue(this._defineMirroredEquirectangularFixedName, texture.coordinatesMode === Constants.TEXTURE_FIXED_EQUIRECTANGULAR_MIRRORED_MODE, true);
  149. }
  150. public isReady() {
  151. const texture = this._getTexture();
  152. if (texture && !texture.isReadyOrNotBlocking()) {
  153. return false;
  154. }
  155. return true;
  156. }
  157. public bind(effect: Effect, nodeMaterial: NodeMaterial, mesh?: Mesh) {
  158. const texture = this._getTexture();
  159. if (!mesh || !texture) {
  160. return;
  161. }
  162. effect.setMatrix(this._reflectionMatrixName, texture.getReflectionTextureMatrix());
  163. if (texture.isCube) {
  164. effect.setTexture(this._cubeSamplerName, texture);
  165. } else {
  166. effect.setTexture(this._2DSamplerName, texture);
  167. }
  168. }
  169. /**
  170. * Gets the code to inject in the vertex shader
  171. * @param state current state of the node material building
  172. * @returns the shader code
  173. */
  174. public handleVertexSide(state: NodeMaterialBuildState): string {
  175. this._define3DName = state._getFreeDefineName("REFLECTIONMAP_3D");
  176. this._defineCubicName = state._getFreeDefineName("REFLECTIONMAP_CUBIC");
  177. this._defineSphericalName = state._getFreeDefineName("REFLECTIONMAP_SPHERICAL");
  178. this._definePlanarName = state._getFreeDefineName("REFLECTIONMAP_PLANAR");
  179. this._defineProjectionName = state._getFreeDefineName("REFLECTIONMAP_PROJECTION");
  180. this._defineExplicitName = state._getFreeDefineName("REFLECTIONMAP_EXPLICIT");
  181. this._defineEquirectangularName = state._getFreeDefineName("REFLECTIONMAP_EQUIRECTANGULAR");
  182. this._defineLocalCubicName = state._getFreeDefineName("USE_LOCAL_REFLECTIONMAP_CUBIC");
  183. this._defineMirroredEquirectangularFixedName = state._getFreeDefineName("REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED");
  184. this._defineEquirectangularFixedName = state._getFreeDefineName("REFLECTIONMAP_EQUIRECTANGULAR_FIXED");
  185. this._defineSkyboxName = state._getFreeDefineName("REFLECTIONMAP_SKYBOX");
  186. this._defineOppositeZ = state._getFreeDefineName("REFLECTIONMAP_OPPOSITEZ");
  187. this._reflectionMatrixName = state._getFreeVariableName("reflectionMatrix");
  188. state._emitUniformFromString(this._reflectionMatrixName, "mat4");
  189. let code = "";
  190. let worldPosVaryingName = "v_" + this.worldPosition.associatedVariableName;
  191. if (state._emitVaryingFromString(worldPosVaryingName, "vec4")) {
  192. code += `${worldPosVaryingName} = ${this.worldPosition.associatedVariableName};\r\n`;
  193. }
  194. this._positionUVWName = state._getFreeVariableName("positionUVW");
  195. this._directionWName = state._getFreeVariableName("directionW");
  196. if (state._emitVaryingFromString(this._positionUVWName, "vec3", this._defineSkyboxName)) {
  197. code += `#ifdef ${this._defineSkyboxName}\r\n`;
  198. code += `${this._positionUVWName} = ${this.position.associatedVariableName}.xyz;\r\n`;
  199. code += `#endif\r\n`;
  200. }
  201. if (state._emitVaryingFromString(this._directionWName, "vec3", `defined(${this._defineEquirectangularFixedName}) || defined(${this._defineMirroredEquirectangularFixedName})`)) {
  202. code += `#if defined(${this._defineEquirectangularFixedName}) || defined(${this._defineMirroredEquirectangularFixedName})\r\n`;
  203. code += `${this._directionWName} = normalize(vec3(${this.world.associatedVariableName} * vec4(${this.position.associatedVariableName}.xyz, 0.0)));\r\n`;
  204. code += `#endif\r\n`;
  205. }
  206. return code;
  207. }
  208. /**
  209. * Handles the inits for the fragment code path
  210. * @param state node material build state
  211. */
  212. public handleFragmentSideInits(state: NodeMaterialBuildState) {
  213. state.sharedData.blockingBlocks.push(this);
  214. state.sharedData.textureBlocks.push(this);
  215. // Samplers
  216. this._cubeSamplerName = state._getFreeVariableName(this.name + "CubeSampler");
  217. state.samplers.push(this._cubeSamplerName);
  218. this._2DSamplerName = state._getFreeVariableName(this.name + "2DSampler");
  219. state.samplers.push(this._2DSamplerName);
  220. state._samplerDeclaration += `#ifdef ${this._define3DName}\r\n`;
  221. state._samplerDeclaration += `uniform samplerCube ${this._cubeSamplerName};\r\n`;
  222. state._samplerDeclaration += `#else\r\n`;
  223. state._samplerDeclaration += `uniform sampler2D ${this._2DSamplerName};\r\n`;
  224. state._samplerDeclaration += `#endif\r\n`;
  225. // Fragment
  226. state.sharedData.blocksWithDefines.push(this);
  227. state.sharedData.bindableBlocks.push(this);
  228. let comments = `//${this.name}`;
  229. state._emitFunction("ReciprocalPI", "#define RECIPROCAL_PI2 0.15915494", "");
  230. state._emitFunctionFromInclude("reflectionFunction", comments, {
  231. replaceStrings: [
  232. { search: /vec3 computeReflectionCoords/g, replace: "void DUMMYFUNC" }
  233. ]
  234. });
  235. this._reflectionColorName = state._getFreeVariableName("reflectionColor");
  236. this._reflectionVectorName = state._getFreeVariableName("reflectionUVW");
  237. this._reflectionCoordsName = state._getFreeVariableName("reflectionCoords");
  238. }
  239. /**
  240. * Generates the reflection coords code for the fragment code path
  241. * @param worldNormalVarName name of the world normal variable
  242. * @param worldPos name of the world position variable. If not provided, will use the world position connected to this block
  243. * @param onlyReflectionVector if true, generates code only for the reflection vector computation, not for the reflection coordinates
  244. * @returns the shader code
  245. */
  246. public handleFragmentSideCodeReflectionCoords(worldNormalVarName: string, worldPos?: string, onlyReflectionVector = false): string {
  247. if (!worldPos) {
  248. worldPos = `v_${this.worldPosition.associatedVariableName}`;
  249. }
  250. let reflectionMatrix = this._reflectionMatrixName;
  251. let direction = `normalize(${this._directionWName})`;
  252. let positionUVW = `${this._positionUVWName}`;
  253. let vEyePosition = `${this.cameraPosition.associatedVariableName}`;
  254. let view = `${this.view.associatedVariableName}`;
  255. worldNormalVarName += ".xyz";
  256. let code = `
  257. #ifdef ${this._defineMirroredEquirectangularFixedName}
  258. vec3 ${this._reflectionVectorName} = computeMirroredFixedEquirectangularCoords(${worldPos}, ${worldNormalVarName}, ${direction});
  259. #endif
  260. #ifdef ${this._defineEquirectangularFixedName}
  261. vec3 ${this._reflectionVectorName} = computeFixedEquirectangularCoords(${worldPos}, ${worldNormalVarName}, ${direction});
  262. #endif
  263. #ifdef ${this._defineEquirectangularName}
  264. vec3 ${this._reflectionVectorName} = computeEquirectangularCoords(${worldPos}, ${worldNormalVarName}, ${vEyePosition}.xyz, ${reflectionMatrix});
  265. #endif
  266. #ifdef ${this._defineSphericalName}
  267. vec3 ${this._reflectionVectorName} = computeSphericalCoords(${worldPos}, ${worldNormalVarName}, ${view}, ${reflectionMatrix});
  268. #endif
  269. #ifdef ${this._definePlanarName}
  270. vec3 ${this._reflectionVectorName} = computePlanarCoords(${worldPos}, ${worldNormalVarName}, ${vEyePosition}.xyz, ${reflectionMatrix});
  271. #endif
  272. #ifdef ${this._defineCubicName}
  273. #ifdef ${this._defineLocalCubicName}
  274. vec3 ${this._reflectionVectorName} = computeCubicLocalCoords(${worldPos}, ${worldNormalVarName}, ${vEyePosition}.xyz, ${reflectionMatrix}, vReflectionSize, vReflectionPosition);
  275. #else
  276. vec3 ${this._reflectionVectorName} = computeCubicCoords(${worldPos}, ${worldNormalVarName}, ${vEyePosition}.xyz, ${reflectionMatrix});
  277. #endif
  278. #endif
  279. #ifdef ${this._defineProjectionName}
  280. vec3 ${this._reflectionVectorName} = computeProjectionCoords(${worldPos}, ${view}, ${reflectionMatrix});
  281. #endif
  282. #ifdef ${this._defineSkyboxName}
  283. vec3 ${this._reflectionVectorName} = computeSkyBoxCoords(${positionUVW}, ${reflectionMatrix});
  284. #endif
  285. #ifdef ${this._defineExplicitName}
  286. vec3 ${this._reflectionVectorName} = vec3(0, 0, 0);
  287. #endif
  288. #ifdef ${this._defineOppositeZ}
  289. ${this._reflectionVectorName}.z *= -1.0;
  290. #endif\r\n`;
  291. if (!onlyReflectionVector) {
  292. code += `
  293. #ifdef ${this._define3DName}
  294. vec3 ${this._reflectionCoordsName} = ${this._reflectionVectorName};
  295. #else
  296. vec2 ${this._reflectionCoordsName} = ${this._reflectionVectorName}.xy;
  297. #ifdef ${this._defineProjectionName}
  298. ${this._reflectionCoordsName} /= ${this._reflectionVectorName}.z;
  299. #endif
  300. ${this._reflectionCoordsName}.y = 1.0 - ${this._reflectionCoordsName}.y;
  301. #endif\r\n`;
  302. }
  303. return code;
  304. }
  305. /**
  306. * Generates the reflection color code for the fragment code path
  307. * @param lodVarName name of the lod variable
  308. * @param swizzleLookupTexture swizzle to use for the final color variable
  309. * @returns the shader code
  310. */
  311. public handleFragmentSideCodeReflectionColor(lodVarName?: string, swizzleLookupTexture = ".rgb"): string {
  312. const colorType = "vec" + (swizzleLookupTexture.length === 0 ? "4" : (swizzleLookupTexture.length - 1));
  313. let code = `${colorType} ${this._reflectionColorName};
  314. #ifdef ${this._define3DName}\r\n`;
  315. if (lodVarName) {
  316. code += `${this._reflectionColorName} = textureCubeLodEXT(${this._cubeSamplerName}, ${this._reflectionVectorName}, ${lodVarName})${swizzleLookupTexture};\r\n`;
  317. } else {
  318. code += `${this._reflectionColorName} = textureCube(${this._cubeSamplerName}, ${this._reflectionVectorName})${swizzleLookupTexture};\r\n`;
  319. }
  320. code += `
  321. #else\r\n`;
  322. if (lodVarName) {
  323. code += `${this._reflectionColorName} = texture2DLodEXT(${this._2DSamplerName}, ${this._reflectionCoordsName}, ${lodVarName})${swizzleLookupTexture};\r\n`;
  324. } else {
  325. code += `${this._reflectionColorName} = texture2D(${this._2DSamplerName}, ${this._reflectionCoordsName})${swizzleLookupTexture};\r\n`;
  326. }
  327. code += `#endif\r\n`;
  328. return code;
  329. }
  330. /**
  331. * Generates the code corresponding to the connected output points
  332. * @param state node material build state
  333. * @param varName name of the variable to output
  334. * @returns the shader code
  335. */
  336. public writeOutputs(state: NodeMaterialBuildState, varName: string): string {
  337. let code = "";
  338. if (state.target === NodeMaterialBlockTargets.Fragment) {
  339. for (var output of this._outputs) {
  340. if (output.hasEndpoints) {
  341. code += `${this._declareOutput(output, state)} = ${varName}.${output.name};\r\n`;
  342. }
  343. }
  344. }
  345. return code;
  346. }
  347. protected _buildBlock(state: NodeMaterialBuildState) {
  348. super._buildBlock(state);
  349. return this;
  350. }
  351. protected _dumpPropertiesCode() {
  352. if (!this.texture) {
  353. return "";
  354. }
  355. let codeString: string;
  356. if (this.texture.isCube) {
  357. codeString = `${this._codeVariableName}.texture = new BABYLON.CubeTexture("${this.texture.name}");\r\n`;
  358. } else {
  359. codeString = `${this._codeVariableName}.texture = new BABYLON.Texture("${this.texture.name}");\r\n`;
  360. }
  361. codeString += `${this._codeVariableName}.texture.coordinatesMode = ${this.texture.coordinatesMode};\r\n`;
  362. return codeString;
  363. }
  364. public serialize(): any {
  365. let serializationObject = super.serialize();
  366. if (this.texture) {
  367. serializationObject.texture = this.texture.serialize();
  368. }
  369. return serializationObject;
  370. }
  371. public _deserialize(serializationObject: any, scene: Scene, rootUrl: string) {
  372. super._deserialize(serializationObject, scene, rootUrl);
  373. if (serializationObject.texture) {
  374. rootUrl = serializationObject.texture.url.indexOf("data:") === 0 ? "" : rootUrl;
  375. if (serializationObject.texture.isCube) {
  376. this.texture = CubeTexture.Parse(serializationObject.texture, scene, rootUrl);
  377. } else {
  378. this.texture = Texture.Parse(serializationObject.texture, scene, rootUrl);
  379. }
  380. }
  381. }
  382. }
  383. _TypeStore.RegisteredTypes["BABYLON.ReflectionTextureBaseBlock"] = ReflectionTextureBaseBlock;