refractionBlock.ts 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338
  1. import { NodeMaterialBlockConnectionPointTypes } from '../../Enums/nodeMaterialBlockConnectionPointTypes';
  2. import { NodeMaterialBuildState } from '../../nodeMaterialBuildState';
  3. import { NodeMaterialConnectionPoint, NodeMaterialConnectionPointDirection } from '../../nodeMaterialBlockConnectionPoint';
  4. import { NodeMaterialBlockTargets } from '../../Enums/nodeMaterialBlockTargets';
  5. import { NodeMaterial, NodeMaterialDefines } from '../../nodeMaterial';
  6. import { _TypeStore } from '../../../../Misc/typeStore';
  7. import { InputBlock } from '../Input/inputBlock';
  8. import { NodeMaterialConnectionPointCustomObject } from "../../nodeMaterialConnectionPointCustomObject";
  9. import { AbstractMesh } from '../../../../Meshes/abstractMesh';
  10. import { Nullable } from '../../../../types';
  11. import { BaseTexture } from '../../../Textures/baseTexture';
  12. import { Mesh } from '../../../../Meshes/mesh';
  13. import { SubMesh } from '../../../../Meshes/subMesh';
  14. import { Effect } from '../../../effect';
  15. import { editableInPropertyPage, PropertyTypeForEdition } from "../../nodeMaterialDecorator";
  16. import { Scene } from '../../../../scene';
  17. import { NodeMaterialBlock } from '../../nodeMaterialBlock';
  18. import { CubeTexture } from '../../../Textures/cubeTexture';
  19. import { Texture } from '../../../Textures/texture';
  20. import { NodeMaterialSystemValues } from '../../Enums/nodeMaterialSystemValues';
  21. /**
  22. * Block used to implement the refraction part of the sub surface module of the PBR material
  23. */
  24. export class RefractionBlock extends NodeMaterialBlock {
  25. /** @hidden */
  26. public _define3DName: string;
  27. /** @hidden */
  28. public _refractionMatrixName: string;
  29. /** @hidden */
  30. public _defineLODRefractionAlpha: string;
  31. /** @hidden */
  32. public _defineLinearSpecularRefraction: string;
  33. /** @hidden */
  34. public _defineOppositeZ: string;
  35. /** @hidden */
  36. public _cubeSamplerName: string;
  37. /** @hidden */
  38. public _2DSamplerName: string;
  39. /** @hidden */
  40. public _vRefractionMicrosurfaceInfosName: string;
  41. /** @hidden */
  42. public _vRefractionInfosName: string;
  43. private _scene: Scene;
  44. /**
  45. * This parameters will make the material used its opacity to control how much it is refracting aginst not.
  46. * Materials half opaque for instance using refraction could benefit from this control.
  47. */
  48. @editableInPropertyPage("Link refraction to transparency", PropertyTypeForEdition.Boolean, "ADVANCED", { "notifiers": { "update": true }})
  49. public linkRefractionWithTransparency: boolean = false;
  50. /**
  51. * Controls if refraction needs to be inverted on Y. This could be useful for procedural texture.
  52. */
  53. @editableInPropertyPage("Invert refraction Y", PropertyTypeForEdition.Boolean, "ADVANCED", { "notifiers": { "update": true }})
  54. public invertRefractionY: boolean = false;
  55. /**
  56. * Gets or sets the texture associated with the node
  57. */
  58. public texture: Nullable<BaseTexture>;
  59. /**
  60. * Create a new RefractionBlock
  61. * @param name defines the block name
  62. */
  63. public constructor(name: string) {
  64. super(name, NodeMaterialBlockTargets.Fragment);
  65. this._isUnique = true;
  66. this.registerInput("intensity", NodeMaterialBlockConnectionPointTypes.Float, false, NodeMaterialBlockTargets.Fragment);
  67. this.registerInput("indexOfRefraction", NodeMaterialBlockConnectionPointTypes.Float, true, NodeMaterialBlockTargets.Fragment);
  68. this.registerInput("tintAtDistance", NodeMaterialBlockConnectionPointTypes.Float, true, NodeMaterialBlockTargets.Fragment);
  69. this.registerInput("view", NodeMaterialBlockConnectionPointTypes.Matrix, false, NodeMaterialBlockTargets.Fragment);
  70. this.registerOutput("refraction", NodeMaterialBlockConnectionPointTypes.Object, NodeMaterialBlockTargets.Fragment,
  71. new NodeMaterialConnectionPointCustomObject("refraction", this, NodeMaterialConnectionPointDirection.Output, RefractionBlock, "RefractionBlock"));
  72. }
  73. /**
  74. * Gets the current class name
  75. * @returns the class name
  76. */
  77. public getClassName() {
  78. return "RefractionBlock";
  79. }
  80. /**
  81. * Gets the intensity input component
  82. */
  83. public get intensity(): NodeMaterialConnectionPoint {
  84. return this._inputs[0];
  85. }
  86. /**
  87. * Gets the index of refraction input component
  88. */
  89. public get indexOfRefraction(): NodeMaterialConnectionPoint {
  90. return this._inputs[1];
  91. }
  92. /**
  93. * Gets the tint at distance input component
  94. */
  95. public get tintAtDistance(): NodeMaterialConnectionPoint {
  96. return this._inputs[2];
  97. }
  98. /**
  99. * Gets the view input component
  100. */
  101. public get view(): NodeMaterialConnectionPoint {
  102. return this._inputs[3];
  103. }
  104. /**
  105. * Gets the refraction object output component
  106. */
  107. public get refraction(): NodeMaterialConnectionPoint {
  108. return this._outputs[0];
  109. }
  110. /**
  111. * Returns true if the block has a texture
  112. */
  113. public get hasTexture(): boolean {
  114. return !!this._getTexture();
  115. }
  116. protected _getTexture(): Nullable<BaseTexture> {
  117. if (this.texture) {
  118. return this.texture;
  119. }
  120. return this._scene.environmentTexture;
  121. }
  122. public autoConfigure(material: NodeMaterial) {
  123. if (!this.intensity.isConnected) {
  124. let intensityInput = new InputBlock("Refraction intensity", NodeMaterialBlockTargets.Fragment, NodeMaterialBlockConnectionPointTypes.Float);
  125. intensityInput.value = 1;
  126. intensityInput.output.connectTo(this.intensity);
  127. }
  128. if (!this.view.isConnected) {
  129. let viewInput = material.getInputBlockByPredicate((b) => b.systemValue === NodeMaterialSystemValues.View);
  130. if (!viewInput) {
  131. viewInput = new InputBlock("view");
  132. viewInput.setAsSystemValue(NodeMaterialSystemValues.View);
  133. }
  134. viewInput.output.connectTo(this.view);
  135. }
  136. }
  137. public prepareDefines(mesh: AbstractMesh, nodeMaterial: NodeMaterial, defines: NodeMaterialDefines) {
  138. super.prepareDefines(mesh, nodeMaterial, defines);
  139. const refractionTexture = this._getTexture();
  140. const refraction = refractionTexture && refractionTexture.getTextureMatrix;
  141. defines.setValue("SS_REFRACTION", refraction, true);
  142. if (!refraction) {
  143. return;
  144. }
  145. defines.setValue(this._define3DName, refractionTexture!.isCube, true);
  146. defines.setValue(this._defineLODRefractionAlpha, refractionTexture!.lodLevelInAlpha, true);
  147. defines.setValue(this._defineLinearSpecularRefraction, refractionTexture!.linearSpecularLOD, true);
  148. defines.setValue(this._defineOppositeZ, this._scene.useRightHandedSystem ? !refractionTexture!.invertZ : refractionTexture!.invertZ, true);
  149. defines.setValue("SS_LINKREFRACTIONTOTRANSPARENCY", this.linkRefractionWithTransparency, true);
  150. }
  151. public isReady() {
  152. const texture = this._getTexture();
  153. if (texture && !texture.isReadyOrNotBlocking()) {
  154. return false;
  155. }
  156. return true;
  157. }
  158. public bind(effect: Effect, nodeMaterial: NodeMaterial, mesh?: Mesh, subMesh?: SubMesh) {
  159. super.bind(effect, nodeMaterial, mesh);
  160. const refractionTexture = this._getTexture();
  161. if (!refractionTexture) {
  162. return;
  163. }
  164. if (refractionTexture.isCube) {
  165. effect.setTexture(this._cubeSamplerName, refractionTexture);
  166. } else {
  167. effect.setTexture(this._2DSamplerName, refractionTexture);
  168. }
  169. effect.setMatrix(this._refractionMatrixName, refractionTexture.getReflectionTextureMatrix());
  170. let depth = 1.0;
  171. if (!refractionTexture.isCube) {
  172. if ((<any>refractionTexture).depth) {
  173. depth = (<any>refractionTexture).depth;
  174. }
  175. }
  176. const indexOfRefraction = this.indexOfRefraction.connectInputBlock?.value ?? 1.0;
  177. effect.setFloat4(this._vRefractionInfosName, refractionTexture.level, 1 / indexOfRefraction, depth, this.invertRefractionY ? -1 : 1);
  178. effect.setFloat3(this._vRefractionMicrosurfaceInfosName, refractionTexture.getSize().width, refractionTexture.lodGenerationScale, refractionTexture.lodGenerationOffset);
  179. }
  180. /**
  181. * Gets the main code of the block (fragment side)
  182. * @param state current state of the node material building
  183. * @returns the shader code
  184. */
  185. public getCode(state: NodeMaterialBuildState): string {
  186. let code = "";
  187. state.sharedData.blockingBlocks.push(this);
  188. state.sharedData.textureBlocks.push(this);
  189. // Samplers
  190. this._cubeSamplerName = state._getFreeVariableName(this.name + "CubeSampler");
  191. state.samplers.push(this._cubeSamplerName);
  192. this._2DSamplerName = state._getFreeVariableName(this.name + "2DSampler");
  193. state.samplers.push(this._2DSamplerName);
  194. this._define3DName = state._getFreeDefineName("SS_REFRACTIONMAP_3D");
  195. state._samplerDeclaration += `#ifdef ${this._define3DName}\r\n`;
  196. state._samplerDeclaration += `uniform samplerCube ${this._cubeSamplerName};\r\n`;
  197. state._samplerDeclaration += `#else\r\n`;
  198. state._samplerDeclaration += `uniform sampler2D ${this._2DSamplerName};\r\n`;
  199. state._samplerDeclaration += `#endif\r\n`;
  200. // Fragment
  201. state.sharedData.blocksWithDefines.push(this);
  202. state.sharedData.bindableBlocks.push(this);
  203. this._defineLODRefractionAlpha = state._getFreeDefineName("SS_LODINREFRACTIONALPHA");
  204. this._defineLinearSpecularRefraction = state._getFreeDefineName("SS_LINEARSPECULARREFRACTION");
  205. this._defineOppositeZ = state._getFreeDefineName("SS_REFRACTIONMAP_OPPOSITEZ");
  206. this._refractionMatrixName = state._getFreeVariableName("refractionMatrix");
  207. state._emitUniformFromString(this._refractionMatrixName, "mat4");
  208. state._emitFunction("sampleRefraction", `
  209. #ifdef ${this._define3DName}
  210. #define sampleRefraction(s, c) textureCube(s, c)
  211. #else
  212. #define sampleRefraction(s, c) texture2D(s, c)
  213. #endif\r\n`, `//${this.name}`);
  214. state._emitFunction("sampleRefractionLod", `
  215. #ifdef ${this._define3DName}
  216. #define sampleRefractionLod(s, c, l) textureCubeLodEXT(s, c, l)
  217. #else
  218. #define sampleRefractionLod(s, c, l) texture2DLodEXT(s, c, l)
  219. #endif\r\n`, `//${this.name}`);
  220. this._vRefractionMicrosurfaceInfosName = state._getFreeVariableName("vRefractionMicrosurfaceInfos");
  221. state._emitUniformFromString(this._vRefractionMicrosurfaceInfosName, "vec3");
  222. this._vRefractionInfosName = state._getFreeVariableName("vRefractionInfos");
  223. state._emitUniformFromString(this._vRefractionInfosName, "vec4");
  224. return code;
  225. }
  226. protected _buildBlock(state: NodeMaterialBuildState) {
  227. this._scene = state.sharedData.scene;
  228. return this;
  229. }
  230. protected _dumpPropertiesCode() {
  231. let codeString: string = super._dumpPropertiesCode();
  232. if (this.texture) {
  233. if (this.texture.isCube) {
  234. codeString = `${this._codeVariableName}.texture = new BABYLON.CubeTexture("${this.texture.name}");\r\n`;
  235. } else {
  236. codeString = `${this._codeVariableName}.texture = new BABYLON.Texture("${this.texture.name}");\r\n`;
  237. }
  238. codeString += `${this._codeVariableName}.texture.coordinatesMode = ${this.texture.coordinatesMode};\r\n`;
  239. }
  240. codeString += `${this._codeVariableName}.linkRefractionWithTransparency = ${this.linkRefractionWithTransparency};\r\n`;
  241. codeString += `${this._codeVariableName}.invertRefractionY = ${this.invertRefractionY};\r\n`;
  242. return codeString;
  243. }
  244. public serialize(): any {
  245. let serializationObject = super.serialize();
  246. if (this.texture) {
  247. serializationObject.texture = this.texture.serialize();
  248. }
  249. serializationObject.linkRefractionWithTransparency = this.linkRefractionWithTransparency;
  250. serializationObject.invertRefractionY = this.invertRefractionY;
  251. return serializationObject;
  252. }
  253. public _deserialize(serializationObject: any, scene: Scene, rootUrl: string) {
  254. super._deserialize(serializationObject, scene, rootUrl);
  255. if (serializationObject.texture) {
  256. rootUrl = serializationObject.texture.url.indexOf("data:") === 0 ? "" : rootUrl;
  257. if (serializationObject.texture.isCube) {
  258. this.texture = CubeTexture.Parse(serializationObject.texture, scene, rootUrl);
  259. } else {
  260. this.texture = Texture.Parse(serializationObject.texture, scene, rootUrl);
  261. }
  262. }
  263. this.linkRefractionWithTransparency = serializationObject.linkRefractionWithTransparency;
  264. this.invertRefractionY = serializationObject.invertRefractionY;
  265. }
  266. }
  267. _TypeStore.RegisteredTypes["BABYLON.RefractionBlock"] = RefractionBlock;