textureBlock.ts 18 KB

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