nodeMaterialBlock.ts 23 KB

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