textureBlock.ts 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384
  1. import { NodeMaterialBlock } from '../../nodeMaterialBlock';
  2. import { NodeMaterialBlockConnectionPointTypes } from '../../Enums/nodeMaterialBlockConnectionPointTypes';
  3. import { NodeMaterialBuildState } from '../../nodeMaterialBuildState';
  4. import { NodeMaterialBlockTargets } from '../../Enums/nodeMaterialBlockTargets';
  5. import { NodeMaterialConnectionPoint } from '../../nodeMaterialBlockConnectionPoint';
  6. import { AbstractMesh } from '../../../../Meshes/abstractMesh';
  7. import { NodeMaterial, NodeMaterialDefines } from '../../nodeMaterial';
  8. import { InputBlock } from '../Input/inputBlock';
  9. import { Effect } from '../../../effect';
  10. import { Mesh } from '../../../../Meshes/mesh';
  11. import { Nullable } from '../../../../types';
  12. import { _TypeStore } from '../../../../Misc/typeStore';
  13. import { Texture } from '../../../Textures/texture';
  14. import { Scene } from '../../../../scene';
  15. import "../../../../Shaders/ShadersInclude/helperFunctions";
  16. /**
  17. * Block used to read a texture from a sampler
  18. */
  19. export class TextureBlock extends NodeMaterialBlock {
  20. private _defineName: string;
  21. private _linearDefineName: string;
  22. private _samplerName: string;
  23. private _transformedUVName: string;
  24. private _textureTransformName: string;
  25. private _textureInfoName: string;
  26. private _mainUVName: string;
  27. private _mainUVDefineName: string;
  28. /**
  29. * Gets or sets the texture associated with the node
  30. */
  31. public texture: Nullable<Texture>;
  32. /**
  33. * Create a new TextureBlock
  34. * @param name defines the block name
  35. */
  36. public constructor(name: string) {
  37. super(name, NodeMaterialBlockTargets.VertexAndFragment);
  38. this.registerInput("uv", NodeMaterialBlockConnectionPointTypes.Vector2, false, NodeMaterialBlockTargets.VertexAndFragment);
  39. this.registerOutput("rgba", NodeMaterialBlockConnectionPointTypes.Color4, NodeMaterialBlockTargets.Neutral);
  40. this.registerOutput("rgb", NodeMaterialBlockConnectionPointTypes.Color3, NodeMaterialBlockTargets.Neutral);
  41. this.registerOutput("r", NodeMaterialBlockConnectionPointTypes.Float, NodeMaterialBlockTargets.Neutral);
  42. this.registerOutput("g", NodeMaterialBlockConnectionPointTypes.Float, NodeMaterialBlockTargets.Neutral);
  43. this.registerOutput("b", NodeMaterialBlockConnectionPointTypes.Float, NodeMaterialBlockTargets.Neutral);
  44. this.registerOutput("a", NodeMaterialBlockConnectionPointTypes.Float, NodeMaterialBlockTargets.Neutral);
  45. this._inputs[0].acceptedConnectionPointTypes.push(NodeMaterialBlockConnectionPointTypes.Vector3);
  46. this._inputs[0].acceptedConnectionPointTypes.push(NodeMaterialBlockConnectionPointTypes.Vector4);
  47. this._inputs[0]._prioritizeVertex = true;
  48. }
  49. /**
  50. * Gets the current class name
  51. * @returns the class name
  52. */
  53. public getClassName() {
  54. return "TextureBlock";
  55. }
  56. /**
  57. * Gets the uv input component
  58. */
  59. public get uv(): NodeMaterialConnectionPoint {
  60. return this._inputs[0];
  61. }
  62. /**
  63. * Gets the rgba output component
  64. */
  65. public get rgba(): NodeMaterialConnectionPoint {
  66. return this._outputs[0];
  67. }
  68. /**
  69. * Gets the rgb output component
  70. */
  71. public get rgb(): NodeMaterialConnectionPoint {
  72. return this._outputs[1];
  73. }
  74. /**
  75. * Gets the r output component
  76. */
  77. public get r(): NodeMaterialConnectionPoint {
  78. return this._outputs[2];
  79. }
  80. /**
  81. * Gets the g output component
  82. */
  83. public get g(): NodeMaterialConnectionPoint {
  84. return this._outputs[3];
  85. }
  86. /**
  87. * Gets the b output component
  88. */
  89. public get b(): NodeMaterialConnectionPoint {
  90. return this._outputs[4];
  91. }
  92. /**
  93. * Gets the a output component
  94. */
  95. public get a(): NodeMaterialConnectionPoint {
  96. return this._outputs[5];
  97. }
  98. public get target() {
  99. // TextureBlock has a special optimizations for uvs that come from the vertex shaders as they can be packed into a single varyings.
  100. // But we need to detect uvs coming from fragment then
  101. if (!this.uv.isConnected) {
  102. return NodeMaterialBlockTargets.VertexAndFragment;
  103. }
  104. if (this.uv.sourceBlock!.isInput) {
  105. return NodeMaterialBlockTargets.VertexAndFragment;
  106. }
  107. let parent = this.uv.connectedPoint;
  108. while (parent) {
  109. if (parent.target === NodeMaterialBlockTargets.Fragment) {
  110. return NodeMaterialBlockTargets.Fragment;
  111. }
  112. if (parent.target === NodeMaterialBlockTargets.Vertex) {
  113. return NodeMaterialBlockTargets.VertexAndFragment;
  114. }
  115. if (parent.target === NodeMaterialBlockTargets.Neutral || parent.target === NodeMaterialBlockTargets.VertexAndFragment) {
  116. let parentBlock = parent.ownerBlock;
  117. parent = null;
  118. for (var input of parentBlock.inputs) {
  119. if (input.connectedPoint) {
  120. parent = input.connectedPoint;
  121. break;
  122. }
  123. }
  124. }
  125. }
  126. return NodeMaterialBlockTargets.VertexAndFragment;
  127. }
  128. public autoConfigure(material: NodeMaterial) {
  129. if (!this.uv.isConnected) {
  130. let uvInput = material.getInputBlockByPredicate((b) => b.isAttribute && b.name === "uv");
  131. if (!uvInput) {
  132. uvInput = new InputBlock("uv");
  133. uvInput.setAsAttribute();
  134. }
  135. uvInput.output.connectTo(this.uv);
  136. }
  137. }
  138. public initializeDefines(mesh: AbstractMesh, nodeMaterial: NodeMaterial, defines: NodeMaterialDefines, useInstances: boolean = false) {
  139. if (!defines._areTexturesDirty) {
  140. return;
  141. }
  142. defines.setValue(this._mainUVDefineName, false);
  143. }
  144. public prepareDefines(mesh: AbstractMesh, nodeMaterial: NodeMaterial, defines: NodeMaterialDefines) {
  145. if (!defines._areTexturesDirty) {
  146. return;
  147. }
  148. if (!this.texture || !this.texture.getTextureMatrix) {
  149. defines.setValue(this._defineName, false);
  150. defines.setValue(this._mainUVDefineName, true);
  151. return;
  152. }
  153. defines.setValue(this._linearDefineName, !this.texture.gammaSpace);
  154. if (this._isMixed) {
  155. if (!this.texture.getTextureMatrix().isIdentityAs3x2()) {
  156. defines.setValue(this._defineName, true);
  157. } else {
  158. defines.setValue(this._defineName, false);
  159. defines.setValue(this._mainUVDefineName, true);
  160. }
  161. }
  162. }
  163. public isReady() {
  164. if (this.texture && !this.texture.isReadyOrNotBlocking()) {
  165. return false;
  166. }
  167. return true;
  168. }
  169. public bind(effect: Effect, nodeMaterial: NodeMaterial, mesh?: Mesh) {
  170. if (!mesh || !this.texture) {
  171. return;
  172. }
  173. if (this._isMixed) {
  174. effect.setFloat(this._textureInfoName, this.texture.level);
  175. effect.setMatrix(this._textureTransformName, this.texture.getTextureMatrix());
  176. }
  177. effect.setTexture(this._samplerName, this.texture);
  178. }
  179. private get _isMixed() {
  180. return this.target !== NodeMaterialBlockTargets.Fragment;
  181. }
  182. private _injectVertexCode(state: NodeMaterialBuildState) {
  183. let uvInput = this.uv;
  184. // Inject code in vertex
  185. this._defineName = state._getFreeDefineName("UVTRANSFORM");
  186. this._mainUVDefineName = "VMAIN" + uvInput.associatedVariableName.toUpperCase();
  187. if (uvInput.connectedPoint!.ownerBlock.isInput) {
  188. let uvInputOwnerBlock = uvInput.connectedPoint!.ownerBlock as InputBlock;
  189. if (!uvInputOwnerBlock.isAttribute) {
  190. state._emitUniformFromString(uvInput.associatedVariableName, "vec2");
  191. }
  192. }
  193. this._mainUVName = "vMain" + uvInput.associatedVariableName;
  194. this._transformedUVName = state._getFreeVariableName("transformedUV");
  195. this._textureTransformName = state._getFreeVariableName("textureTransform");
  196. this._textureInfoName = state._getFreeVariableName("textureInfoName");
  197. state._emitVaryingFromString(this._transformedUVName, "vec2", this._defineName);
  198. state._emitVaryingFromString(this._mainUVName, "vec2", this._mainUVDefineName);
  199. state._emitUniformFromString(this._textureTransformName, "mat4", this._defineName);
  200. state.compilationString += `#ifdef ${this._defineName}\r\n`;
  201. state.compilationString += `${this._transformedUVName} = vec2(${this._textureTransformName} * vec4(${uvInput.associatedVariableName}.xy, 1.0, 0.0));\r\n`;
  202. state.compilationString += `#endif\r\n`;
  203. state.compilationString += `#ifdef ${this._mainUVDefineName}\r\n`;
  204. state.compilationString += `${this._mainUVName} = ${uvInput.associatedVariableName}.xy;\r\n`;
  205. state.compilationString += `#endif\r\n`;
  206. if (!this._outputs.some((o) => o.isConnectedInVertexShader)) {
  207. return;
  208. }
  209. for (var output of this._outputs) {
  210. if (output.hasEndpoints) {
  211. this._writeOutput(state, output, output.name, true);
  212. }
  213. }
  214. }
  215. private _writeOutput(state: NodeMaterialBuildState, output: NodeMaterialConnectionPoint, swizzle: string, vertexMode = false) {
  216. let uvInput = this.uv;
  217. if (vertexMode) {
  218. if (state.target === NodeMaterialBlockTargets.Fragment) {
  219. return;
  220. }
  221. state.compilationString += `${this._declareOutput(output, state)} = texture2D(${this._samplerName}, ${uvInput.associatedVariableName}).${swizzle};\r\n`;
  222. return;
  223. }
  224. if (this.uv.ownerBlock.target === NodeMaterialBlockTargets.Fragment) {
  225. state.compilationString += `${this._declareOutput(output, state)} = texture2D(${this._samplerName}, ${uvInput.associatedVariableName}).${swizzle};\r\n`;
  226. return;
  227. }
  228. const complement = ` * ${this._textureInfoName}`;
  229. state.compilationString += `#ifdef ${this._defineName}\r\n`;
  230. state.compilationString += `${this._declareOutput(output, state)} = texture2D(${this._samplerName}, ${this._transformedUVName}).${swizzle}${complement};\r\n`;
  231. state.compilationString += `#endif\r\n`;
  232. state.compilationString += `#ifdef ${this._mainUVDefineName}\r\n`;
  233. state.compilationString += `${this._declareOutput(output, state)} = texture2D(${this._samplerName}, ${this._mainUVName}).${swizzle}${complement};\r\n`;
  234. state.compilationString += `#endif\r\n`;
  235. state.compilationString += `#ifdef ${this._linearDefineName}\r\n`;
  236. state.compilationString += `${output.associatedVariableName} = toGammaSpace(${output.associatedVariableName});\r\n`;
  237. state.compilationString += `#endif\r\n`;
  238. }
  239. protected _buildBlock(state: NodeMaterialBuildState) {
  240. super._buildBlock(state);
  241. if (!this._isMixed && state.target === NodeMaterialBlockTargets.Fragment || this._isMixed && state.target === NodeMaterialBlockTargets.Vertex) {
  242. this._samplerName = state._getFreeVariableName(this.name + "Sampler");
  243. state._emit2DSampler(this._samplerName);
  244. // Declarations
  245. state.sharedData.blockingBlocks.push(this);
  246. state.sharedData.textureBlocks.push(this);
  247. state.sharedData.blocksWithDefines.push(this);
  248. state.sharedData.bindableBlocks.push(this);
  249. }
  250. if (state.target !== NodeMaterialBlockTargets.Fragment) {
  251. // Vertex
  252. this._injectVertexCode(state);
  253. return;
  254. }
  255. // Fragment
  256. if (!this._outputs.some((o) => o.isConnectedInFragmentShader)) {
  257. return;
  258. }
  259. if (this._isMixed) {
  260. // Reexport the sampler
  261. state._emit2DSampler(this._samplerName);
  262. }
  263. this._linearDefineName = state._getFreeDefineName("ISLINEAR");
  264. let comments = `//${this.name}`;
  265. state._emitFunctionFromInclude("helperFunctions", comments);
  266. if (this._isMixed) {
  267. state._emitUniformFromString(this._textureInfoName, "float");
  268. }
  269. for (var output of this._outputs) {
  270. if (output.hasEndpoints) {
  271. this._writeOutput(state, output, output.name);
  272. }
  273. }
  274. return this;
  275. }
  276. protected _dumpPropertiesCode() {
  277. if (!this.texture) {
  278. return "";
  279. }
  280. var codeString = `${this._codeVariableName}.texture = new BABYLON.Texture("${this.texture.name}");\r\n`;
  281. codeString += `${this._codeVariableName}.texture.wrapU = ${this.texture.wrapU};\r\n`;
  282. codeString += `${this._codeVariableName}.texture.wrapV = ${this.texture.wrapV};\r\n`;
  283. codeString += `${this._codeVariableName}.texture.uAng = ${this.texture.uAng};\r\n`;
  284. codeString += `${this._codeVariableName}.texture.vAng = ${this.texture.vAng};\r\n`;
  285. codeString += `${this._codeVariableName}.texture.wAng = ${this.texture.wAng};\r\n`;
  286. codeString += `${this._codeVariableName}.texture.uOffset = ${this.texture.uOffset};\r\n`;
  287. codeString += `${this._codeVariableName}.texture.vOffset = ${this.texture.vOffset};\r\n`;
  288. codeString += `${this._codeVariableName}.texture.uScale = ${this.texture.uScale};\r\n`;
  289. codeString += `${this._codeVariableName}.texture.vScale = ${this.texture.vScale};\r\n`;
  290. codeString += `${this._codeVariableName}.texture.gammaSpace = ${this.texture.gammaSpace};\r\n`;
  291. return codeString;
  292. }
  293. public serialize(): any {
  294. let serializationObject = super.serialize();
  295. if (this.texture) {
  296. serializationObject.texture = this.texture.serialize();
  297. }
  298. return serializationObject;
  299. }
  300. public _deserialize(serializationObject: any, scene: Scene, rootUrl: string) {
  301. super._deserialize(serializationObject, scene, rootUrl);
  302. if (serializationObject.texture) {
  303. rootUrl = serializationObject.texture.url.indexOf("data:") === 0 ? "" : rootUrl;
  304. this.texture = Texture.Parse(serializationObject.texture, scene, rootUrl) as Texture;
  305. }
  306. }
  307. }
  308. _TypeStore.RegisteredTypes["BABYLON.TextureBlock"] = TextureBlock;