nodeMaterialBlock.ts 18 KB

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