nodeMaterialBlock.ts 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437
  1. import { NodeMaterialBlockConnectionPointTypes } from './nodeMaterialBlockConnectionPointTypes';
  2. import { NodeMaterialBuildState } from './nodeMaterialBuildState';
  3. import { Nullable } from '../../types';
  4. import { NodeMaterialConnectionPoint } from './nodeMaterialBlockConnectionPoint';
  5. import { NodeMaterialBlockTargets } from './nodeMaterialBlockTargets';
  6. import { Effect, EffectFallbacks } from '../effect';
  7. import { AbstractMesh } from '../../Meshes/abstractMesh';
  8. import { Mesh } from '../../Meshes/mesh';
  9. import { NodeMaterial, NodeMaterialDefines } from './nodeMaterial';
  10. /**
  11. * Defines a block that can be used inside a node based material
  12. */
  13. export class NodeMaterialBlock {
  14. private _buildId: number;
  15. private _target: NodeMaterialBlockTargets;
  16. private _isFinalMerger = false;
  17. private _isInput = false;
  18. /** @hidden */
  19. public _inputs = new Array<NodeMaterialConnectionPoint>();
  20. /** @hidden */
  21. public _outputs = new Array<NodeMaterialConnectionPoint>();
  22. /**
  23. * Gets or sets the name of the block
  24. */
  25. public name: string;
  26. /**
  27. * Gets a boolean indicating that this block is an end block (e.g. it is generating a system value)
  28. */
  29. public get isFinalMerger(): boolean {
  30. return this._isFinalMerger;
  31. }
  32. /**
  33. * Gets a boolean indicating that this block is an input (e.g. it sends data to the shader)
  34. */
  35. public get isInput(): boolean {
  36. return this._isInput;
  37. }
  38. /**
  39. * Gets or sets the build Id
  40. */
  41. public get buildId(): number {
  42. return this._buildId;
  43. }
  44. public set buildId(value: number) {
  45. this._buildId = value;
  46. }
  47. /**
  48. * Gets or sets the target of the block
  49. */
  50. public get target() {
  51. return this._target;
  52. }
  53. public set target(value: NodeMaterialBlockTargets) {
  54. if ((this._target & value) !== 0) {
  55. return;
  56. }
  57. this._target = value;
  58. }
  59. /**
  60. * Gets the list of input points
  61. */
  62. public get inputs(): NodeMaterialConnectionPoint[] {
  63. return this._inputs;
  64. }
  65. /** Gets the list of output points */
  66. public get outputs(): NodeMaterialConnectionPoint[] {
  67. return this._outputs;
  68. }
  69. /**
  70. * Find an input by its name
  71. * @param name defines the name of the input to look for
  72. * @returns the input or null if not found
  73. */
  74. public getInputByName(name: string) {
  75. let filter = this._inputs.filter((e) => e.name === name);
  76. if (filter.length) {
  77. return filter[0];
  78. }
  79. return null;
  80. }
  81. /**
  82. * Find an output by its name
  83. * @param name defines the name of the outputto look for
  84. * @returns the output or null if not found
  85. */
  86. public getOutputByName(name: string) {
  87. let filter = this._outputs.filter((e) => e.name === name);
  88. if (filter.length) {
  89. return filter[0];
  90. }
  91. return null;
  92. }
  93. /**
  94. * Creates a new NodeMaterialBlock
  95. * @param name defines the block name
  96. * @param target defines the target of that block (Vertex by default)
  97. * @param isFinalMerger defines a boolean indicating that this block is an end block (e.g. it is generating a system value). Default is false
  98. * @param isInput defines a boolean indicating that this block is an input (e.g. it sends data to the shader). Default is false
  99. */
  100. public constructor(name: string, target = NodeMaterialBlockTargets.Vertex, isFinalMerger = false, isInput = false) {
  101. this.name = name;
  102. this._target = target;
  103. this._isFinalMerger = isFinalMerger;
  104. this._isInput = isInput;
  105. }
  106. /**
  107. * Initialize the block and prepare the context for build
  108. * @param state defines the state that will be used for the build
  109. */
  110. public initialize(state: NodeMaterialBuildState) {
  111. // Do nothing
  112. }
  113. /**
  114. * Bind data to effect. Will only be called for blocks with isBindable === true
  115. * @param effect defines the effect to bind data to
  116. * @param nodeMaterial defines the hosting NodeMaterial
  117. * @param mesh defines the mesh that will be rendered
  118. */
  119. public bind(effect: Effect, nodeMaterial: NodeMaterial, mesh?: Mesh) {
  120. // Do nothing
  121. }
  122. protected _declareOutput(output: NodeMaterialConnectionPoint, state: NodeMaterialBuildState): string {
  123. // if (output.isVarying) {
  124. // return `${output.associatedVariableName}`;
  125. // }
  126. return `${state._getGLType(output.type)} ${output.associatedVariableName}`;
  127. }
  128. protected _writeVariable(currentPoint: NodeMaterialConnectionPoint): string {
  129. let connectionPoint = currentPoint.connectedPoint!;
  130. return `${currentPoint.associatedVariableName}${connectionPoint.swizzle ? "." + connectionPoint.swizzle : ""}`;
  131. }
  132. protected _writeFloat(value: number) {
  133. let stringVersion = value.toString();
  134. if (stringVersion.indexOf(".") === -1) {
  135. stringVersion += ".0";
  136. }
  137. return `${stringVersion}`;
  138. }
  139. /**
  140. * Gets the current class name e.g. "NodeMaterialBlock"
  141. * @returns the class name
  142. */
  143. public getClassName() {
  144. return "NodeMaterialBlock";
  145. }
  146. /**
  147. * Register a new input. Must be called inside a block constructor
  148. * @param name defines the connection point name
  149. * @param type defines the connection point type
  150. * @param isOptional defines a boolean indicating that this input can be omitted
  151. * @param target defines the target to use to limit the connection point (will be VetexAndFragment by default)
  152. * @returns the current block
  153. */
  154. public registerInput(name: string, type: NodeMaterialBlockConnectionPointTypes, isOptional: boolean = false, target?: NodeMaterialBlockTargets) {
  155. let point = new NodeMaterialConnectionPoint(name, this);
  156. point.type = type;
  157. point.isOptional = isOptional;
  158. if (target) {
  159. point.target = target;
  160. }
  161. this._inputs.push(point);
  162. return this;
  163. }
  164. /**
  165. * Register a new output. Must be called inside a block constructor
  166. * @param name defines the connection point name
  167. * @param type defines the connection point type
  168. * @param target defines the target to use to limit the connection point (will be VetexAndFragment by default)
  169. * @returns the current block
  170. */
  171. public registerOutput(name: string, type: NodeMaterialBlockConnectionPointTypes, target?: NodeMaterialBlockTargets) {
  172. let point = new NodeMaterialConnectionPoint(name, this);
  173. point.type = type;
  174. if (target) {
  175. point.target = target;
  176. }
  177. this._outputs.push(point);
  178. return this;
  179. }
  180. /**
  181. * Will return the first available input e.g. the first one which is not an uniform or an attribute
  182. * @param forOutput defines an optional connection point to check compatibility with
  183. * @returns the first available input or null
  184. */
  185. public getFirstAvailableInput(forOutput: Nullable<NodeMaterialConnectionPoint> = null) {
  186. for (var input of this._inputs) {
  187. if (!input.connectedPoint) {
  188. if (!forOutput || (forOutput.type & input.type) !== 0 || input.type === NodeMaterialBlockConnectionPointTypes.AutoDetect) {
  189. return input;
  190. }
  191. }
  192. }
  193. return null;
  194. }
  195. /**
  196. * Will return the first available output e.g. the first one which is not yet connected and not a varying
  197. * @param forBlock defines an optional block to check compatibility with
  198. * @returns the first available input or null
  199. */
  200. public getFirstAvailableOutput(forBlock: Nullable<NodeMaterialBlock> = null) {
  201. for (var output of this._outputs) {
  202. if (!forBlock || !forBlock.target || (forBlock.target & output.target) !== 0) {
  203. return output;
  204. }
  205. }
  206. return null;
  207. }
  208. /**
  209. * Connect current block with another block
  210. * @param other defines the block to connect with
  211. * @param options define the various options to help pick the right connections
  212. * @returns the current block
  213. */
  214. public connectTo(other: NodeMaterialBlock, options?: {
  215. input?: string,
  216. output?: string,
  217. outputSwizzle?: string
  218. }) {
  219. if (this._outputs.length === 0) {
  220. return;
  221. }
  222. let output = options && options.output ? this.getOutputByName(options.output) : this.getFirstAvailableOutput(other);
  223. let input = options && options.input ? other.getInputByName(options.input) : other.getFirstAvailableInput(output);
  224. if (output && input) {
  225. output.swizzle = options ? options.outputSwizzle || "" : "";
  226. output.connectTo(input);
  227. } else {
  228. throw "Unable to find a compatible match";
  229. }
  230. return this;
  231. }
  232. protected _buildBlock(state: NodeMaterialBuildState) {
  233. // Empty. Must be defined by child nodes
  234. }
  235. protected _emit(state: NodeMaterialBuildState, define?: string) {
  236. // Empty. Must be defined by child nodes
  237. }
  238. /**
  239. * Add uniforms, samplers and uniform buffers at compilation time
  240. * @param state defines the state to update
  241. * @param nodeMaterial defines the node material requesting the update
  242. * @param defines defines the material defines to update
  243. */
  244. public updateUniformsAndSamples(state: NodeMaterialBuildState, nodeMaterial: NodeMaterial, defines: NodeMaterialDefines) {
  245. // Do nothing
  246. }
  247. /**
  248. * Add potential fallbacks if shader compilation fails
  249. * @param mesh defines the mesh to be rendered
  250. * @param fallbacks defines the current prioritized list of fallbacks
  251. */
  252. public provideFallbacks(mesh: AbstractMesh, fallbacks: EffectFallbacks) {
  253. // Do nothing
  254. }
  255. /**
  256. * Update defines for shader compilation
  257. * @param mesh defines the mesh to be rendered
  258. * @param nodeMaterial defines the node material requesting the update
  259. * @param defines defines the material defines to update
  260. * @param useInstances specifies that instances should be used
  261. */
  262. public prepareDefines(mesh: AbstractMesh, nodeMaterial: NodeMaterial, defines: NodeMaterialDefines, useInstances: boolean = false) {
  263. // Do nothing
  264. }
  265. /**
  266. * Lets the block try to connect some inputs automatically
  267. */
  268. public autoConfigure() {
  269. // Do nothing
  270. }
  271. /**
  272. * Function called when a block is declared as repeatable content generator
  273. * @param vertexShaderState defines the current compilation state for the vertex shader
  274. * @param fragmentShaderState defines the current compilation state for the fragment shader
  275. * @param mesh defines the mesh to be rendered
  276. * @param defines defines the material defines to update
  277. */
  278. public replaceRepeatableContent(vertexShaderState: NodeMaterialBuildState, fragmentShaderState: NodeMaterialBuildState, mesh: AbstractMesh, defines: NodeMaterialDefines) {
  279. // Do nothing
  280. }
  281. /**
  282. * Checks if the block is ready
  283. * @param mesh defines the mesh to be rendered
  284. * @param nodeMaterial defines the node material requesting the update
  285. * @param defines defines the material defines to update
  286. * @param useInstances specifies that instances should be used
  287. * @returns true if the block is ready
  288. */
  289. public isReady(mesh: AbstractMesh, nodeMaterial: NodeMaterial, defines: NodeMaterialDefines, useInstances: boolean = false) {
  290. return true;
  291. }
  292. /**
  293. * Compile the current node and generate the shader code
  294. * @param state defines the current compilation state (uniforms, samplers, current string)
  295. * @returns the current block
  296. */
  297. public build(state: NodeMaterialBuildState) {
  298. if (this._buildId === state.sharedData.buildId) {
  299. return;
  300. }
  301. // Check if "parent" blocks are compiled
  302. for (var input of this._inputs) {
  303. if (!input.connectedPoint) {
  304. if (!input.isOptional) { // Emit a warning
  305. state.sharedData.checks.notConnectedNonOptionalInputs.push(input);
  306. }
  307. continue;
  308. }
  309. if ((input.target & this.target!) === 0) {
  310. continue;
  311. }
  312. if ((input.target & state.target!) === 0) {
  313. continue;
  314. }
  315. let block = input.connectedPoint.ownerBlock;
  316. if (block && block !== this && block.buildId !== state.sharedData.buildId) {
  317. block.build(state);
  318. }
  319. }
  320. if (this._buildId === state.sharedData.buildId) {
  321. return; // Need to check again as inputs can be connected multiple time to this endpoint
  322. }
  323. // Logs
  324. if (state.sharedData.verbose) {
  325. console.log(`${state.target === NodeMaterialBlockTargets.Vertex ? "Vertex shader" : "Fragment shader"}: Building ${this.name} [${this.getClassName()}]`);
  326. }
  327. /** Emit input blocks */
  328. this._emit(state);
  329. /** Prepare outputs */
  330. for (var output of this._outputs) {
  331. if ((output.target & this.target!) === 0) {
  332. continue;
  333. }
  334. if ((output.target & state.target!) === 0) {
  335. continue;
  336. }
  337. if (!output.associatedVariableName) {
  338. output.associatedVariableName = state._getFreeVariableName(output.name);
  339. }
  340. }
  341. // Checks final outputs
  342. if (this.isFinalMerger) {
  343. switch (state.target) {
  344. case NodeMaterialBlockTargets.Vertex:
  345. state.sharedData.checks.emitVertex = true;
  346. break;
  347. case NodeMaterialBlockTargets.Fragment:
  348. state.sharedData.checks.emitFragment = true;
  349. break;
  350. }
  351. }
  352. if (!this.isInput && state.sharedData.emitComments) {
  353. state.compilationString += `\r\n//${this.name}\r\n`;
  354. }
  355. this._buildBlock(state);
  356. this._buildId = state.sharedData.buildId;
  357. // Compile connected blocks
  358. for (var output of this._outputs) {
  359. if ((output.target & state.target) === 0) {
  360. continue;
  361. }
  362. for (var block of output.connectedBlocks) {
  363. if (block && (block.target & state.target) !== 0) {
  364. block.build(state);
  365. }
  366. }
  367. }
  368. return this;
  369. }
  370. }