nodeMaterialBlock.ts 27 KB

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