textureBlock.ts 19 KB

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