nodeMaterialBlock.ts 15 KB

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