nodeMaterialBlock.ts 24 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681
  1. import { NodeMaterialBlockConnectionPointTypes } from './Enums/nodeMaterialBlockConnectionPointTypes';
  2. import { NodeMaterialBuildState } from './nodeMaterialBuildState';
  3. import { Nullable } from '../../types';
  4. import { NodeMaterialConnectionPoint, NodeMaterialConnectionPointDirection } from './nodeMaterialBlockConnectionPoint';
  5. import { NodeMaterialBlockTargets } from './Enums/nodeMaterialBlockTargets';
  6. import { Effect } 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. import { _TypeStore } from '../../Misc/typeStore';
  14. import { EffectFallbacks } from '../effectFallbacks';
  15. /**
  16. * Defines a block that can be used inside a node based material
  17. */
  18. export class NodeMaterialBlock {
  19. private _buildId: number;
  20. private _buildTarget: NodeMaterialBlockTargets;
  21. private _target: NodeMaterialBlockTargets;
  22. private _isFinalMerger = false;
  23. private _isInput = false;
  24. protected _isUnique = false;
  25. /** @hidden */
  26. public _codeVariableName = "";
  27. /** @hidden */
  28. public _inputs = new Array<NodeMaterialConnectionPoint>();
  29. /** @hidden */
  30. public _outputs = new Array<NodeMaterialConnectionPoint>();
  31. /** @hidden */
  32. public _preparationId: number;
  33. /**
  34. * Gets or sets the name of the block
  35. */
  36. public name: string;
  37. /**
  38. * Gets or sets the unique id of the node
  39. */
  40. public uniqueId: number;
  41. /**
  42. * Gets or sets the comments associated with this block
  43. */
  44. public comments: string = "";
  45. /**
  46. * Gets a boolean indicating that this block can only be used once per NodeMaterial
  47. */
  48. public get isUnique() {
  49. return this._isUnique;
  50. }
  51. /**
  52. * Gets a boolean indicating that this block is an end block (e.g. it is generating a system value)
  53. */
  54. public get isFinalMerger(): boolean {
  55. return this._isFinalMerger;
  56. }
  57. /**
  58. * Gets a boolean indicating that this block is an input (e.g. it sends data to the shader)
  59. */
  60. public get isInput(): boolean {
  61. return this._isInput;
  62. }
  63. /**
  64. * Gets or sets the build Id
  65. */
  66. public get buildId(): number {
  67. return this._buildId;
  68. }
  69. public set buildId(value: number) {
  70. this._buildId = value;
  71. }
  72. /**
  73. * Gets or sets the target of the block
  74. */
  75. public get target() {
  76. return this._target;
  77. }
  78. public set target(value: NodeMaterialBlockTargets) {
  79. if ((this._target & value) !== 0) {
  80. return;
  81. }
  82. this._target = value;
  83. }
  84. /**
  85. * Gets the list of input points
  86. */
  87. public get inputs(): NodeMaterialConnectionPoint[] {
  88. return this._inputs;
  89. }
  90. /** Gets the list of output points */
  91. public get outputs(): NodeMaterialConnectionPoint[] {
  92. return this._outputs;
  93. }
  94. /**
  95. * Find an input by its name
  96. * @param name defines the name of the input to look for
  97. * @returns the input or null if not found
  98. */
  99. public getInputByName(name: string) {
  100. let filter = this._inputs.filter((e) => e.name === name);
  101. if (filter.length) {
  102. return filter[0];
  103. }
  104. return null;
  105. }
  106. /**
  107. * Find an output by its name
  108. * @param name defines the name of the outputto look for
  109. * @returns the output or null if not found
  110. */
  111. public getOutputByName(name: string) {
  112. let filter = this._outputs.filter((e) => e.name === name);
  113. if (filter.length) {
  114. return filter[0];
  115. }
  116. return null;
  117. }
  118. /**
  119. * Creates a new NodeMaterialBlock
  120. * @param name defines the block name
  121. * @param target defines the target of that block (Vertex by default)
  122. * @param isFinalMerger defines a boolean indicating that this block is an end block (e.g. it is generating a system value). Default is false
  123. * @param isInput defines a boolean indicating that this block is an input (e.g. it sends data to the shader). Default is false
  124. */
  125. public constructor(name: string, target = NodeMaterialBlockTargets.Vertex, isFinalMerger = false, isInput = false) {
  126. this.name = name;
  127. this._target = target;
  128. this._isFinalMerger = isFinalMerger;
  129. this._isInput = isInput;
  130. this.uniqueId = UniqueIdGenerator.UniqueId;
  131. }
  132. /**
  133. * Initialize the block and prepare the context for build
  134. * @param state defines the state that will be used for the build
  135. */
  136. public initialize(state: NodeMaterialBuildState) {
  137. // Do nothing
  138. }
  139. /**
  140. * Bind data to effect. Will only be called for blocks with isBindable === true
  141. * @param effect defines the effect to bind data to
  142. * @param nodeMaterial defines the hosting NodeMaterial
  143. * @param mesh defines the mesh that will be rendered
  144. */
  145. public bind(effect: Effect, nodeMaterial: NodeMaterial, mesh?: Mesh) {
  146. // Do nothing
  147. }
  148. protected _declareOutput(output: NodeMaterialConnectionPoint, state: NodeMaterialBuildState): string {
  149. return `${state._getGLType(output.type)} ${output.associatedVariableName}`;
  150. }
  151. protected _writeVariable(currentPoint: NodeMaterialConnectionPoint): string {
  152. let connectionPoint = currentPoint.connectedPoint;
  153. if (connectionPoint) {
  154. return `${currentPoint.associatedVariableName}`;
  155. }
  156. return `0.`;
  157. }
  158. protected _writeFloat(value: number) {
  159. let stringVersion = value.toString();
  160. if (stringVersion.indexOf(".") === -1) {
  161. stringVersion += ".0";
  162. }
  163. return `${stringVersion}`;
  164. }
  165. /**
  166. * Gets the current class name e.g. "NodeMaterialBlock"
  167. * @returns the class name
  168. */
  169. public getClassName() {
  170. return "NodeMaterialBlock";
  171. }
  172. /**
  173. * Register a new input. Must be called inside a block constructor
  174. * @param name defines the connection point name
  175. * @param type defines the connection point type
  176. * @param isOptional defines a boolean indicating that this input can be omitted
  177. * @param target defines the target to use to limit the connection point (will be VertexAndFragment by default)
  178. * @returns the current block
  179. */
  180. public registerInput(name: string, type: NodeMaterialBlockConnectionPointTypes, isOptional: boolean = false, target?: NodeMaterialBlockTargets) {
  181. let point = new NodeMaterialConnectionPoint(name, this, NodeMaterialConnectionPointDirection.Input);
  182. point.type = type;
  183. point.isOptional = isOptional;
  184. if (target) {
  185. point.target = target;
  186. }
  187. this._inputs.push(point);
  188. return this;
  189. }
  190. /**
  191. * Register a new output. Must be called inside a block constructor
  192. * @param name defines the connection point name
  193. * @param type defines the connection point type
  194. * @param target defines the target to use to limit the connection point (will be VertexAndFragment by default)
  195. * @returns the current block
  196. */
  197. public registerOutput(name: string, type: NodeMaterialBlockConnectionPointTypes, target?: NodeMaterialBlockTargets) {
  198. let point = new NodeMaterialConnectionPoint(name, this, NodeMaterialConnectionPointDirection.Output);
  199. point.type = type;
  200. if (target) {
  201. point.target = target;
  202. }
  203. this._outputs.push(point);
  204. return this;
  205. }
  206. /**
  207. * Will return the first available input e.g. the first one which is not an uniform or an attribute
  208. * @param forOutput defines an optional connection point to check compatibility with
  209. * @returns the first available input or null
  210. */
  211. public getFirstAvailableInput(forOutput: Nullable<NodeMaterialConnectionPoint> = null) {
  212. for (var input of this._inputs) {
  213. if (!input.connectedPoint) {
  214. if (!forOutput || (forOutput.type === input.type) || (input.type === NodeMaterialBlockConnectionPointTypes.AutoDetect)) {
  215. return input;
  216. }
  217. }
  218. }
  219. return null;
  220. }
  221. /**
  222. * Will return the first available output e.g. the first one which is not yet connected and not a varying
  223. * @param forBlock defines an optional block to check compatibility with
  224. * @returns the first available input or null
  225. */
  226. public getFirstAvailableOutput(forBlock: Nullable<NodeMaterialBlock> = null) {
  227. for (var output of this._outputs) {
  228. if (!forBlock || !forBlock.target || forBlock.target === NodeMaterialBlockTargets.Neutral || (forBlock.target & output.target) !== 0) {
  229. return output;
  230. }
  231. }
  232. return null;
  233. }
  234. /**
  235. * Gets the sibling of the given output
  236. * @param current defines the current output
  237. * @returns the next output in the list or null
  238. */
  239. public getSiblingOutput(current: NodeMaterialConnectionPoint) {
  240. let index = this._outputs.indexOf(current);
  241. if (index === -1 || index >= this._outputs.length) {
  242. return null;
  243. }
  244. return this._outputs[index + 1];
  245. }
  246. /**
  247. * Connect current block with another block
  248. * @param other defines the block to connect with
  249. * @param options define the various options to help pick the right connections
  250. * @returns the current block
  251. */
  252. public connectTo(other: NodeMaterialBlock, options?: {
  253. input?: string,
  254. output?: string,
  255. outputSwizzle?: string
  256. }) {
  257. if (this._outputs.length === 0) {
  258. return;
  259. }
  260. let output = options && options.output ? this.getOutputByName(options.output) : this.getFirstAvailableOutput(other);
  261. let notFound = true;
  262. while (notFound) {
  263. let input = options && options.input ? other.getInputByName(options.input) : other.getFirstAvailableInput(output);
  264. if (output && input && output.canConnectTo(input)) {
  265. output.connectTo(input);
  266. notFound = false;
  267. } else if (!output) {
  268. throw "Unable to find a compatible match";
  269. } else {
  270. output = this.getSiblingOutput(output);
  271. }
  272. }
  273. return this;
  274. }
  275. protected _buildBlock(state: NodeMaterialBuildState) {
  276. // Empty. Must be defined by child nodes
  277. }
  278. /**
  279. * Add uniforms, samplers and uniform buffers at compilation time
  280. * @param state defines the state to update
  281. * @param nodeMaterial defines the node material requesting the update
  282. * @param defines defines the material defines to update
  283. * @param uniformBuffers defines the list of uniform buffer names
  284. */
  285. public updateUniformsAndSamples(state: NodeMaterialBuildState, nodeMaterial: NodeMaterial, defines: NodeMaterialDefines, uniformBuffers: string[]) {
  286. // Do nothing
  287. }
  288. /**
  289. * Add potential fallbacks if shader compilation fails
  290. * @param mesh defines the mesh to be rendered
  291. * @param fallbacks defines the current prioritized list of fallbacks
  292. */
  293. public provideFallbacks(mesh: AbstractMesh, fallbacks: EffectFallbacks) {
  294. // Do nothing
  295. }
  296. /**
  297. * Initialize defines for shader compilation
  298. * @param mesh defines the mesh to be rendered
  299. * @param nodeMaterial defines the node material requesting the update
  300. * @param defines defines the material defines to update
  301. * @param useInstances specifies that instances should be used
  302. */
  303. public initializeDefines(mesh: AbstractMesh, nodeMaterial: NodeMaterial, defines: NodeMaterialDefines, useInstances: boolean = false) {
  304. }
  305. /**
  306. * Update defines for shader compilation
  307. * @param mesh defines the mesh to be rendered
  308. * @param nodeMaterial defines the node material requesting the update
  309. * @param defines defines the material defines to update
  310. * @param useInstances specifies that instances should be used
  311. */
  312. public prepareDefines(mesh: AbstractMesh, nodeMaterial: NodeMaterial, defines: NodeMaterialDefines, useInstances: boolean = false) {
  313. // Do nothing
  314. }
  315. /**
  316. * Lets the block try to connect some inputs automatically
  317. * @param material defines the hosting NodeMaterial
  318. */
  319. public autoConfigure(material: NodeMaterial) {
  320. // Do nothing
  321. }
  322. /**
  323. * Function called when a block is declared as repeatable content generator
  324. * @param vertexShaderState defines the current compilation state for the vertex shader
  325. * @param fragmentShaderState defines the current compilation state for the fragment shader
  326. * @param mesh defines the mesh to be rendered
  327. * @param defines defines the material defines to update
  328. */
  329. public replaceRepeatableContent(vertexShaderState: NodeMaterialBuildState, fragmentShaderState: NodeMaterialBuildState, mesh: AbstractMesh, defines: NodeMaterialDefines) {
  330. // Do nothing
  331. }
  332. /**
  333. * Checks if the block is ready
  334. * @param mesh defines the mesh to be rendered
  335. * @param nodeMaterial defines the node material requesting the update
  336. * @param defines defines the material defines to update
  337. * @param useInstances specifies that instances should be used
  338. * @returns true if the block is ready
  339. */
  340. public isReady(mesh: AbstractMesh, nodeMaterial: NodeMaterial, defines: NodeMaterialDefines, useInstances: boolean = false) {
  341. return true;
  342. }
  343. protected _linkConnectionTypes(inputIndex0: number, inputIndex1: number) {
  344. this._inputs[inputIndex0]._linkedConnectionSource = this._inputs[inputIndex1];
  345. this._inputs[inputIndex1]._linkedConnectionSource = this._inputs[inputIndex0];
  346. }
  347. private _processBuild(block: NodeMaterialBlock, state: NodeMaterialBuildState, input: NodeMaterialConnectionPoint, activeBlocks: NodeMaterialBlock[]) {
  348. block.build(state, activeBlocks);
  349. const localBlockIsFragment = (state._vertexState != null);
  350. const otherBlockWasGeneratedInVertexShader = block._buildTarget === NodeMaterialBlockTargets.Vertex && block.target !== NodeMaterialBlockTargets.VertexAndFragment;
  351. if (localBlockIsFragment && (
  352. ((block.target & input.target) === 0) ||
  353. (this.target !== NodeMaterialBlockTargets.VertexAndFragment && otherBlockWasGeneratedInVertexShader)
  354. )) { // context switch! We need a varying
  355. if ((!block.isInput && state.target !== block._buildTarget) // block was already emitted by vertex shader
  356. || (block.isInput && (block as InputBlock).isAttribute) // block is an attribute
  357. ) {
  358. let connectedPoint = input.connectedPoint!;
  359. if (state._vertexState._emitVaryingFromString("v_" + connectedPoint.associatedVariableName, state._getGLType(connectedPoint.type))) {
  360. state._vertexState.compilationString += `${"v_" + connectedPoint.associatedVariableName} = ${connectedPoint.associatedVariableName};\r\n`;
  361. }
  362. input.associatedVariableName = "v_" + connectedPoint.associatedVariableName;
  363. input._enforceAssociatedVariableName = true;
  364. }
  365. }
  366. }
  367. /**
  368. * Compile the current node and generate the shader code
  369. * @param state defines the current compilation state (uniforms, samplers, current string)
  370. * @param activeBlocks defines the list of active blocks (i.e. blocks to compile)
  371. * @returns true if already built
  372. */
  373. public build(state: NodeMaterialBuildState, activeBlocks: NodeMaterialBlock[]): boolean {
  374. if (this._buildId === state.sharedData.buildId) {
  375. return true;
  376. }
  377. if (!this.isInput) {
  378. /** Prepare outputs */
  379. for (var output of this._outputs) {
  380. if (!output.associatedVariableName) {
  381. output.associatedVariableName = state._getFreeVariableName(output.name);
  382. }
  383. }
  384. }
  385. // Check if "parent" blocks are compiled
  386. for (var input of this._inputs) {
  387. if (!input.connectedPoint) {
  388. if (!input.isOptional) { // Emit a warning
  389. state.sharedData.checks.notConnectedNonOptionalInputs.push(input);
  390. }
  391. continue;
  392. }
  393. if (this.target !== NodeMaterialBlockTargets.Neutral) {
  394. if ((input.target & this.target!) === 0) {
  395. continue;
  396. }
  397. if ((input.target & state.target!) === 0) {
  398. continue;
  399. }
  400. }
  401. let block = input.connectedPoint.ownerBlock;
  402. if (block && block !== this) {
  403. this._processBuild(block, state, input, activeBlocks);
  404. }
  405. }
  406. if (this._buildId === state.sharedData.buildId) {
  407. return true; // Need to check again as inputs can be connected multiple time to this endpoint
  408. }
  409. // Logs
  410. if (state.sharedData.verbose) {
  411. console.log(`${state.target === NodeMaterialBlockTargets.Vertex ? "Vertex shader" : "Fragment shader"}: Building ${this.name} [${this.getClassName()}]`);
  412. }
  413. // Checks final outputs
  414. if (this.isFinalMerger) {
  415. switch (state.target) {
  416. case NodeMaterialBlockTargets.Vertex:
  417. state.sharedData.checks.emitVertex = true;
  418. break;
  419. case NodeMaterialBlockTargets.Fragment:
  420. state.sharedData.checks.emitFragment = true;
  421. break;
  422. }
  423. }
  424. if (!this.isInput && state.sharedData.emitComments) {
  425. state.compilationString += `\r\n//${this.name}\r\n`;
  426. }
  427. this._buildBlock(state);
  428. this._buildId = state.sharedData.buildId;
  429. this._buildTarget = state.target;
  430. // Compile connected blocks
  431. for (var output of this._outputs) {
  432. if ((output.target & state.target) === 0) {
  433. continue;
  434. }
  435. for (var endpoint of output.endpoints) {
  436. let block = endpoint.ownerBlock;
  437. if (block && (block.target & state.target) !== 0 && activeBlocks.indexOf(block) !== -1) {
  438. this._processBuild(block, state, endpoint, activeBlocks);
  439. }
  440. }
  441. }
  442. return false;
  443. }
  444. protected _inputRename(name: string) {
  445. return name;
  446. }
  447. protected _outputRename(name: string) {
  448. return name;
  449. }
  450. protected _dumpPropertiesCode() {
  451. return "";
  452. }
  453. /** @hidden */
  454. public _dumpCode(uniqueNames: string[], alreadyDumped: NodeMaterialBlock[]) {
  455. alreadyDumped.push(this);
  456. let codeString: string;
  457. // Get unique name
  458. let nameAsVariableName = this.name.replace(/[^A-Za-z_]+/g, "");
  459. this._codeVariableName = nameAsVariableName || `${this.getClassName()}_${this.uniqueId}`;
  460. if (uniqueNames.indexOf(this._codeVariableName) !== -1) {
  461. let index = 0;
  462. do {
  463. index++;
  464. this._codeVariableName = nameAsVariableName + index;
  465. }
  466. while (uniqueNames.indexOf(this._codeVariableName) !== -1);
  467. }
  468. uniqueNames.push(this._codeVariableName);
  469. // Declaration
  470. codeString = `\r\n// ${this.getClassName()}\r\n`;
  471. if (this.comments) {
  472. codeString += `// ${this.comments}\r\n`;
  473. }
  474. codeString += `var ${this._codeVariableName} = new BABYLON.${this.getClassName()}("${this.name}");\r\n`;
  475. // Properties
  476. codeString += this._dumpPropertiesCode();
  477. // Inputs
  478. for (var input of this.inputs) {
  479. if (!input.isConnected) {
  480. continue;
  481. }
  482. var connectedOutput = input.connectedPoint!;
  483. var connectedBlock = connectedOutput.ownerBlock;
  484. if (alreadyDumped.indexOf(connectedBlock) === -1) {
  485. codeString += connectedBlock._dumpCode(uniqueNames, alreadyDumped);
  486. }
  487. }
  488. // Outputs
  489. for (var output of this.outputs) {
  490. if (!output.hasEndpoints) {
  491. continue;
  492. }
  493. for (var endpoint of output.endpoints) {
  494. var connectedBlock = endpoint.ownerBlock;
  495. if (connectedBlock && alreadyDumped.indexOf(connectedBlock) === -1) {
  496. codeString += connectedBlock._dumpCode(uniqueNames, alreadyDumped);
  497. }
  498. }
  499. }
  500. return codeString;
  501. }
  502. /** @hidden */
  503. public _dumpCodeForOutputConnections(alreadyDumped: NodeMaterialBlock[]) {
  504. let codeString = "";
  505. if (alreadyDumped.indexOf(this) !== -1) {
  506. return codeString;
  507. }
  508. alreadyDumped.push(this);
  509. for (var input of this.inputs) {
  510. if (!input.isConnected) {
  511. continue;
  512. }
  513. var connectedOutput = input.connectedPoint!;
  514. var connectedBlock = connectedOutput.ownerBlock;
  515. codeString += connectedBlock._dumpCodeForOutputConnections(alreadyDumped);
  516. codeString += `${connectedBlock._codeVariableName}.${connectedBlock._outputRename(connectedOutput.name)}.connectTo(${this._codeVariableName}.${this._inputRename(input.name)});\r\n`;
  517. }
  518. return codeString;
  519. }
  520. /**
  521. * Clone the current block to a new identical block
  522. * @param scene defines the hosting scene
  523. * @param rootUrl defines the root URL to use to load textures and relative dependencies
  524. * @returns a copy of the current block
  525. */
  526. public clone(scene: Scene, rootUrl: string = "") {
  527. let serializationObject = this.serialize();
  528. let blockType = _TypeStore.GetClass(serializationObject.customType);
  529. if (blockType) {
  530. let block: NodeMaterialBlock = new blockType();
  531. block._deserialize(serializationObject, scene, rootUrl);
  532. return block;
  533. }
  534. return null;
  535. }
  536. /**
  537. * Serializes this block in a JSON representation
  538. * @returns the serialized block object
  539. */
  540. public serialize(): any {
  541. let serializationObject: any = {};
  542. serializationObject.customType = "BABYLON." + this.getClassName();
  543. serializationObject.id = this.uniqueId;
  544. serializationObject.name = this.name;
  545. serializationObject.comments = this.comments;
  546. serializationObject.inputs = [];
  547. for (var input of this.inputs) {
  548. serializationObject.inputs.push(input.serialize());
  549. }
  550. return serializationObject;
  551. }
  552. /** @hidden */
  553. public _deserialize(serializationObject: any, scene: Scene, rootUrl: string) {
  554. this.name = serializationObject.name;
  555. this.comments = serializationObject.comments;
  556. }
  557. /**
  558. * Release resources
  559. */
  560. public dispose() {
  561. for (var input of this.inputs) {
  562. input.dispose();
  563. }
  564. for (var output of this.outputs) {
  565. output.dispose();
  566. }
  567. }
  568. }