nodeMaterial.ts 44 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289
  1. import { NodeMaterialBlock } from './nodeMaterialBlock';
  2. import { PushMaterial } from '../pushMaterial';
  3. import { Scene } from '../../scene';
  4. import { AbstractMesh } from '../../Meshes/abstractMesh';
  5. import { Matrix } from '../../Maths/math.vector';
  6. import { Color4 } from '../../Maths/math.color';
  7. import { Mesh } from '../../Meshes/mesh';
  8. import { Engine } from '../../Engines/engine';
  9. import { NodeMaterialBuildState } from './nodeMaterialBuildState';
  10. import { IEffectCreationOptions } from '../effect';
  11. import { BaseTexture } from '../../Materials/Textures/baseTexture';
  12. import { Observable, Observer } from '../../Misc/observable';
  13. import { NodeMaterialBlockTargets } from './Enums/nodeMaterialBlockTargets';
  14. import { NodeMaterialBuildStateSharedData } from './nodeMaterialBuildStateSharedData';
  15. import { SubMesh } from '../../Meshes/subMesh';
  16. import { MaterialDefines } from '../../Materials/materialDefines';
  17. import { NodeMaterialOptimizer } from './Optimizers/nodeMaterialOptimizer';
  18. import { ImageProcessingConfiguration, IImageProcessingConfigurationDefines } from '../imageProcessingConfiguration';
  19. import { Nullable } from '../../types';
  20. import { VertexBuffer } from '../../Meshes/buffer';
  21. import { Tools } from '../../Misc/tools';
  22. import { TransformBlock } from './Blocks/transformBlock';
  23. import { VertexOutputBlock } from './Blocks/Vertex/vertexOutputBlock';
  24. import { FragmentOutputBlock } from './Blocks/Fragment/fragmentOutputBlock';
  25. import { InputBlock } from './Blocks/Input/inputBlock';
  26. import { _TypeStore } from '../../Misc/typeStore';
  27. import { SerializationHelper } from '../../Misc/decorators';
  28. import { TextureBlock } from './Blocks/Dual/textureBlock';
  29. import { ReflectionTextureBlock } from './Blocks/Dual/reflectionTextureBlock';
  30. import { EffectFallbacks } from '../effectFallbacks';
  31. // declare NODEEDITOR namespace for compilation issue
  32. declare var NODEEDITOR: any;
  33. declare var BABYLON: any;
  34. /**
  35. * Interface used to configure the node material editor
  36. */
  37. export interface INodeMaterialEditorOptions {
  38. /** Define the URl to load node editor script */
  39. editorURL?: string;
  40. }
  41. /** @hidden */
  42. export class NodeMaterialDefines extends MaterialDefines implements IImageProcessingConfigurationDefines {
  43. /** BONES */
  44. public NUM_BONE_INFLUENCERS = 0;
  45. public BonesPerMesh = 0;
  46. public BONETEXTURE = false;
  47. /** MORPH TARGETS */
  48. public MORPHTARGETS = false;
  49. public MORPHTARGETS_NORMAL = false;
  50. public MORPHTARGETS_TANGENT = false;
  51. public MORPHTARGETS_UV = false;
  52. public NUM_MORPH_INFLUENCERS = 0;
  53. /** IMAGE PROCESSING */
  54. public IMAGEPROCESSING = false;
  55. public VIGNETTE = false;
  56. public VIGNETTEBLENDMODEMULTIPLY = false;
  57. public VIGNETTEBLENDMODEOPAQUE = false;
  58. public TONEMAPPING = false;
  59. public TONEMAPPING_ACES = false;
  60. public CONTRAST = false;
  61. public EXPOSURE = false;
  62. public COLORCURVES = false;
  63. public COLORGRADING = false;
  64. public COLORGRADING3D = false;
  65. public SAMPLER3DGREENDEPTH = false;
  66. public SAMPLER3DBGRMAP = false;
  67. public IMAGEPROCESSINGPOSTPROCESS = false;
  68. /** MISC. */
  69. public BUMPDIRECTUV = 0;
  70. constructor() {
  71. super();
  72. this.rebuild();
  73. }
  74. public setValue(name: string, value: boolean) {
  75. if (this[name] === undefined) {
  76. this._keys.push(name);
  77. }
  78. this[name] = value;
  79. }
  80. }
  81. /**
  82. * Class used to configure NodeMaterial
  83. */
  84. export interface INodeMaterialOptions {
  85. /**
  86. * Defines if blocks should emit comments
  87. */
  88. emitComments: boolean;
  89. }
  90. /**
  91. * Class used to create a node based material built by assembling shader blocks
  92. */
  93. export class NodeMaterial extends PushMaterial {
  94. private static _BuildIdGenerator: number = 0;
  95. private _options: INodeMaterialOptions;
  96. private _vertexCompilationState: NodeMaterialBuildState;
  97. private _fragmentCompilationState: NodeMaterialBuildState;
  98. private _sharedData: NodeMaterialBuildStateSharedData;
  99. private _buildId: number = NodeMaterial._BuildIdGenerator++;
  100. private _buildWasSuccessful = false;
  101. private _cachedWorldViewMatrix = new Matrix();
  102. private _cachedWorldViewProjectionMatrix = new Matrix();
  103. private _optimizers = new Array<NodeMaterialOptimizer>();
  104. private _animationFrame = -1;
  105. /** Define the URl to load node editor script */
  106. public static EditorURL = `https://unpkg.com/babylonjs-node-editor@${Engine.Version}/babylon.nodeEditor.js`;
  107. private BJSNODEMATERIALEDITOR = this._getGlobalNodeMaterialEditor();
  108. /** Get the inspector from bundle or global */
  109. private _getGlobalNodeMaterialEditor(): any {
  110. // UMD Global name detection from Webpack Bundle UMD Name.
  111. if (typeof NODEEDITOR !== 'undefined') {
  112. return NODEEDITOR;
  113. }
  114. // In case of module let's check the global emitted from the editor entry point.
  115. if (typeof BABYLON !== 'undefined' && typeof BABYLON.NodeEditor !== 'undefined') {
  116. return BABYLON;
  117. }
  118. return undefined;
  119. }
  120. /**
  121. * Gets or sets data used by visual editor
  122. * @see https://nme.babylonjs.com
  123. */
  124. public editorData: any = null;
  125. /**
  126. * Gets or sets a boolean indicating that alpha value must be ignored (This will turn alpha blending off even if an alpha value is produced by the material)
  127. */
  128. public ignoreAlpha = false;
  129. /**
  130. * Defines the maximum number of lights that can be used in the material
  131. */
  132. public maxSimultaneousLights = 4;
  133. /**
  134. * Observable raised when the material is built
  135. */
  136. public onBuildObservable = new Observable<NodeMaterial>();
  137. /**
  138. * Gets or sets the root nodes of the material vertex shader
  139. */
  140. public _vertexOutputNodes = new Array<NodeMaterialBlock>();
  141. /**
  142. * Gets or sets the root nodes of the material fragment (pixel) shader
  143. */
  144. public _fragmentOutputNodes = new Array<NodeMaterialBlock>();
  145. /** Gets or sets options to control the node material overall behavior */
  146. public get options() {
  147. return this._options;
  148. }
  149. public set options(options: INodeMaterialOptions) {
  150. this._options = options;
  151. }
  152. /**
  153. * Default configuration related to image processing available in the standard Material.
  154. */
  155. protected _imageProcessingConfiguration: ImageProcessingConfiguration;
  156. /**
  157. * Gets the image processing configuration used either in this material.
  158. */
  159. public get imageProcessingConfiguration(): ImageProcessingConfiguration {
  160. return this._imageProcessingConfiguration;
  161. }
  162. /**
  163. * Sets the Default image processing configuration used either in the this material.
  164. *
  165. * If sets to null, the scene one is in use.
  166. */
  167. public set imageProcessingConfiguration(value: ImageProcessingConfiguration) {
  168. this._attachImageProcessingConfiguration(value);
  169. // Ensure the effect will be rebuilt.
  170. this._markAllSubMeshesAsTexturesDirty();
  171. }
  172. /**
  173. * Gets an array of blocks that needs to be serialized even if they are not yet connected
  174. */
  175. public attachedBlocks = new Array<NodeMaterialBlock>();
  176. /**
  177. * Create a new node based material
  178. * @param name defines the material name
  179. * @param scene defines the hosting scene
  180. * @param options defines creation option
  181. */
  182. constructor(name: string, scene?: Scene, options: Partial<INodeMaterialOptions> = {}) {
  183. super(name, scene || Engine.LastCreatedScene!);
  184. this._options = {
  185. emitComments: false,
  186. ...options
  187. };
  188. // Setup the default processing configuration to the scene.
  189. this._attachImageProcessingConfiguration(null);
  190. }
  191. /**
  192. * Gets the current class name of the material e.g. "NodeMaterial"
  193. * @returns the class name
  194. */
  195. public getClassName(): string {
  196. return "NodeMaterial";
  197. }
  198. /**
  199. * Keep track of the image processing observer to allow dispose and replace.
  200. */
  201. private _imageProcessingObserver: Nullable<Observer<ImageProcessingConfiguration>>;
  202. /**
  203. * Attaches a new image processing configuration to the Standard Material.
  204. * @param configuration
  205. */
  206. protected _attachImageProcessingConfiguration(configuration: Nullable<ImageProcessingConfiguration>): void {
  207. if (configuration === this._imageProcessingConfiguration) {
  208. return;
  209. }
  210. // Detaches observer.
  211. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  212. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  213. }
  214. // Pick the scene configuration if needed.
  215. if (!configuration) {
  216. this._imageProcessingConfiguration = this.getScene().imageProcessingConfiguration;
  217. }
  218. else {
  219. this._imageProcessingConfiguration = configuration;
  220. }
  221. // Attaches observer.
  222. if (this._imageProcessingConfiguration) {
  223. this._imageProcessingObserver = this._imageProcessingConfiguration.onUpdateParameters.add(() => {
  224. this._markAllSubMeshesAsImageProcessingDirty();
  225. });
  226. }
  227. }
  228. /**
  229. * Get a block by its name
  230. * @param name defines the name of the block to retrieve
  231. * @returns the required block or null if not found
  232. */
  233. public getBlockByName(name: string) {
  234. for (var block of this.attachedBlocks) {
  235. if (block.name === name) {
  236. return block;
  237. }
  238. }
  239. return null;
  240. }
  241. /**
  242. * Get a block by its name
  243. * @param predicate defines the predicate used to find the good candidate
  244. * @returns the required block or null if not found
  245. */
  246. public getBlockByPredicate(predicate: (block: NodeMaterialBlock) => boolean) {
  247. for (var block of this.attachedBlocks) {
  248. if (predicate(block)) {
  249. return block;
  250. }
  251. }
  252. return null;
  253. }
  254. /**
  255. * Get an input block by its name
  256. * @param predicate defines the predicate used to find the good candidate
  257. * @returns the required input block or null if not found
  258. */
  259. public getInputBlockByPredicate(predicate: (block: InputBlock) => boolean): Nullable<InputBlock> {
  260. for (var block of this.attachedBlocks) {
  261. if (block.isInput && predicate(block as InputBlock)) {
  262. return block as InputBlock;
  263. }
  264. }
  265. return null;
  266. }
  267. /**
  268. * Gets the list of input blocks attached to this material
  269. * @returns an array of InputBlocks
  270. */
  271. public getInputBlocks() {
  272. let blocks: InputBlock[] = [];
  273. for (var block of this.attachedBlocks) {
  274. if (block.isInput) {
  275. blocks.push(block as InputBlock);
  276. }
  277. }
  278. return blocks;
  279. }
  280. /**
  281. * Adds a new optimizer to the list of optimizers
  282. * @param optimizer defines the optimizers to add
  283. * @returns the current material
  284. */
  285. public registerOptimizer(optimizer: NodeMaterialOptimizer) {
  286. let index = this._optimizers.indexOf(optimizer);
  287. if (index > -1) {
  288. return;
  289. }
  290. this._optimizers.push(optimizer);
  291. return this;
  292. }
  293. /**
  294. * Remove an optimizer from the list of optimizers
  295. * @param optimizer defines the optimizers to remove
  296. * @returns the current material
  297. */
  298. public unregisterOptimizer(optimizer: NodeMaterialOptimizer) {
  299. let index = this._optimizers.indexOf(optimizer);
  300. if (index === -1) {
  301. return;
  302. }
  303. this._optimizers.splice(index, 1);
  304. return this;
  305. }
  306. /**
  307. * Add a new block to the list of output nodes
  308. * @param node defines the node to add
  309. * @returns the current material
  310. */
  311. public addOutputNode(node: NodeMaterialBlock) {
  312. if (node.target === null) {
  313. throw "This node is not meant to be an output node. You may want to explicitly set its target value.";
  314. }
  315. if ((node.target & NodeMaterialBlockTargets.Vertex) !== 0) {
  316. this._addVertexOutputNode(node);
  317. }
  318. if ((node.target & NodeMaterialBlockTargets.Fragment) !== 0) {
  319. this._addFragmentOutputNode(node);
  320. }
  321. return this;
  322. }
  323. /**
  324. * Remove a block from the list of root nodes
  325. * @param node defines the node to remove
  326. * @returns the current material
  327. */
  328. public removeOutputNode(node: NodeMaterialBlock) {
  329. if (node.target === null) {
  330. return this;
  331. }
  332. if ((node.target & NodeMaterialBlockTargets.Vertex) !== 0) {
  333. this._removeVertexOutputNode(node);
  334. }
  335. if ((node.target & NodeMaterialBlockTargets.Fragment) !== 0) {
  336. this._removeFragmentOutputNode(node);
  337. }
  338. return this;
  339. }
  340. private _addVertexOutputNode(node: NodeMaterialBlock) {
  341. if (this._vertexOutputNodes.indexOf(node) !== -1) {
  342. return;
  343. }
  344. node.target = NodeMaterialBlockTargets.Vertex;
  345. this._vertexOutputNodes.push(node);
  346. return this;
  347. }
  348. private _removeVertexOutputNode(node: NodeMaterialBlock) {
  349. let index = this._vertexOutputNodes.indexOf(node);
  350. if (index === -1) {
  351. return;
  352. }
  353. this._vertexOutputNodes.splice(index, 1);
  354. return this;
  355. }
  356. private _addFragmentOutputNode(node: NodeMaterialBlock) {
  357. if (this._fragmentOutputNodes.indexOf(node) !== -1) {
  358. return;
  359. }
  360. node.target = NodeMaterialBlockTargets.Fragment;
  361. this._fragmentOutputNodes.push(node);
  362. return this;
  363. }
  364. private _removeFragmentOutputNode(node: NodeMaterialBlock) {
  365. let index = this._fragmentOutputNodes.indexOf(node);
  366. if (index === -1) {
  367. return;
  368. }
  369. this._fragmentOutputNodes.splice(index, 1);
  370. return this;
  371. }
  372. /**
  373. * Specifies if the material will require alpha blending
  374. * @returns a boolean specifying if alpha blending is needed
  375. */
  376. public needAlphaBlending(): boolean {
  377. if (this.ignoreAlpha) {
  378. return false;
  379. }
  380. return (this.alpha < 1.0) || (this._sharedData && this._sharedData.hints.needAlphaBlending);
  381. }
  382. /**
  383. * Specifies if this material should be rendered in alpha test mode
  384. * @returns a boolean specifying if an alpha test is needed.
  385. */
  386. public needAlphaTesting(): boolean {
  387. return this._sharedData && this._sharedData.hints.needAlphaTesting;
  388. }
  389. private _initializeBlock(node: NodeMaterialBlock, state: NodeMaterialBuildState, nodesToProcessForOtherBuildState: NodeMaterialBlock[]) {
  390. node.initialize(state);
  391. node.autoConfigure(this);
  392. node._preparationId = this._buildId;
  393. if (this.attachedBlocks.indexOf(node) === -1) {
  394. if (node.isUnique) {
  395. const className = node.getClassName();
  396. for (var other of this.attachedBlocks) {
  397. if (other.getClassName() === className) {
  398. throw `Cannot have multiple blocks of type ${className} in the same NodeMaterial`;
  399. }
  400. }
  401. }
  402. this.attachedBlocks.push(node);
  403. }
  404. for (var input of node.inputs) {
  405. input.associatedVariableName = "";
  406. let connectedPoint = input.connectedPoint;
  407. if (connectedPoint) {
  408. let block = connectedPoint.ownerBlock;
  409. if (block !== node) {
  410. if (block.target === NodeMaterialBlockTargets.VertexAndFragment) {
  411. nodesToProcessForOtherBuildState.push(block);
  412. } else if (state.target === NodeMaterialBlockTargets.Fragment
  413. && block.target === NodeMaterialBlockTargets.Vertex
  414. && block._preparationId !== this._buildId) {
  415. nodesToProcessForOtherBuildState.push(block);
  416. }
  417. this._initializeBlock(block, state, nodesToProcessForOtherBuildState);
  418. }
  419. }
  420. }
  421. for (var output of node.outputs) {
  422. output.associatedVariableName = "";
  423. }
  424. }
  425. private _resetDualBlocks(node: NodeMaterialBlock, id: number) {
  426. if (node.target === NodeMaterialBlockTargets.VertexAndFragment) {
  427. node.buildId = id;
  428. }
  429. for (var inputs of node.inputs) {
  430. let connectedPoint = inputs.connectedPoint;
  431. if (connectedPoint) {
  432. let block = connectedPoint.ownerBlock;
  433. if (block !== node) {
  434. this._resetDualBlocks(block, id);
  435. }
  436. }
  437. }
  438. }
  439. /**
  440. * Remove a block from the current node material
  441. * @param block defines the block to remove
  442. */
  443. public removeBlock(block: NodeMaterialBlock) {
  444. let attachedBlockIndex = this.attachedBlocks.indexOf(block);
  445. if (attachedBlockIndex > -1) {
  446. this.attachedBlocks.splice(attachedBlockIndex, 1);
  447. }
  448. if (block.isFinalMerger) {
  449. this.removeOutputNode(block);
  450. }
  451. }
  452. /**
  453. * Build the material and generates the inner effect
  454. * @param verbose defines if the build should log activity
  455. */
  456. public build(verbose: boolean = false) {
  457. this._buildWasSuccessful = false;
  458. var engine = this.getScene().getEngine();
  459. if (this._vertexOutputNodes.length === 0) {
  460. throw "You must define at least one vertexOutputNode";
  461. }
  462. if (this._fragmentOutputNodes.length === 0) {
  463. throw "You must define at least one fragmentOutputNode";
  464. }
  465. // Compilation state
  466. this._vertexCompilationState = new NodeMaterialBuildState();
  467. this._vertexCompilationState.supportUniformBuffers = engine.supportsUniformBuffers;
  468. this._vertexCompilationState.target = NodeMaterialBlockTargets.Vertex;
  469. this._fragmentCompilationState = new NodeMaterialBuildState();
  470. this._fragmentCompilationState.supportUniformBuffers = engine.supportsUniformBuffers;
  471. this._fragmentCompilationState.target = NodeMaterialBlockTargets.Fragment;
  472. // Shared data
  473. this._sharedData = new NodeMaterialBuildStateSharedData();
  474. this._vertexCompilationState.sharedData = this._sharedData;
  475. this._fragmentCompilationState.sharedData = this._sharedData;
  476. this._sharedData.buildId = this._buildId;
  477. this._sharedData.emitComments = this._options.emitComments;
  478. this._sharedData.verbose = verbose;
  479. this._sharedData.scene = this.getScene();
  480. // Initialize blocks
  481. let vertexNodes: NodeMaterialBlock[] = [];
  482. let fragmentNodes: NodeMaterialBlock[] = [];
  483. for (var vertexOutputNode of this._vertexOutputNodes) {
  484. vertexNodes.push(vertexOutputNode);
  485. this._initializeBlock(vertexOutputNode, this._vertexCompilationState, fragmentNodes);
  486. }
  487. for (var fragmentOutputNode of this._fragmentOutputNodes) {
  488. fragmentNodes.push(fragmentOutputNode);
  489. this._initializeBlock(fragmentOutputNode, this._fragmentCompilationState, vertexNodes);
  490. }
  491. // Optimize
  492. this.optimize();
  493. // Vertex
  494. for (var vertexOutputNode of vertexNodes) {
  495. vertexOutputNode.build(this._vertexCompilationState, vertexNodes);
  496. }
  497. // Fragment
  498. this._fragmentCompilationState.uniforms = this._vertexCompilationState.uniforms.slice(0);
  499. this._fragmentCompilationState._uniformDeclaration = this._vertexCompilationState._uniformDeclaration;
  500. this._fragmentCompilationState._constantDeclaration = this._vertexCompilationState._constantDeclaration;
  501. this._fragmentCompilationState._vertexState = this._vertexCompilationState;
  502. for (var fragmentOutputNode of fragmentNodes) {
  503. this._resetDualBlocks(fragmentOutputNode, this._buildId - 1);
  504. }
  505. for (var fragmentOutputNode of fragmentNodes) {
  506. fragmentOutputNode.build(this._fragmentCompilationState, fragmentNodes);
  507. }
  508. // Finalize
  509. this._vertexCompilationState.finalize(this._vertexCompilationState);
  510. this._fragmentCompilationState.finalize(this._fragmentCompilationState);
  511. this._buildId = NodeMaterial._BuildIdGenerator++;
  512. // Errors
  513. this._sharedData.emitErrors();
  514. if (verbose) {
  515. console.log("Vertex shader:");
  516. console.log(this._vertexCompilationState.compilationString);
  517. console.log("Fragment shader:");
  518. console.log(this._fragmentCompilationState.compilationString);
  519. }
  520. this._buildWasSuccessful = true;
  521. this.onBuildObservable.notifyObservers(this);
  522. // Wipe defines
  523. const meshes = this.getScene().meshes;
  524. for (var mesh of meshes) {
  525. if (!mesh.subMeshes) {
  526. continue;
  527. }
  528. for (var subMesh of mesh.subMeshes) {
  529. if (subMesh.getMaterial() !== this) {
  530. continue;
  531. }
  532. if (!subMesh._materialDefines) {
  533. continue;
  534. }
  535. let defines = subMesh._materialDefines;
  536. defines.markAllAsDirty();
  537. defines.reset();
  538. }
  539. }
  540. }
  541. /**
  542. * Runs an otpimization phase to try to improve the shader code
  543. */
  544. public optimize() {
  545. for (var optimizer of this._optimizers) {
  546. optimizer.optimize(this._vertexOutputNodes, this._fragmentOutputNodes);
  547. }
  548. }
  549. private _prepareDefinesForAttributes(mesh: AbstractMesh, defines: NodeMaterialDefines) {
  550. if (!defines._areAttributesDirty) {
  551. return;
  552. }
  553. defines["NORMAL"] = mesh.isVerticesDataPresent(VertexBuffer.NormalKind);
  554. defines["TANGENT"] = mesh.isVerticesDataPresent(VertexBuffer.TangentKind);
  555. defines["UV1"] = mesh.isVerticesDataPresent(VertexBuffer.UVKind);
  556. }
  557. /**
  558. * Get if the submesh is ready to be used and all its information available.
  559. * Child classes can use it to update shaders
  560. * @param mesh defines the mesh to check
  561. * @param subMesh defines which submesh to check
  562. * @param useInstances specifies that instances should be used
  563. * @returns a boolean indicating that the submesh is ready or not
  564. */
  565. public isReadyForSubMesh(mesh: AbstractMesh, subMesh: SubMesh, useInstances: boolean = false): boolean {
  566. if (!this._buildWasSuccessful) {
  567. return false;
  568. }
  569. var scene = this.getScene();
  570. if (this._sharedData.animatedInputs) {
  571. let frameId = scene.getFrameId();
  572. if (this._animationFrame !== frameId) {
  573. for (var input of this._sharedData.animatedInputs) {
  574. input.animate(scene);
  575. }
  576. this._animationFrame = frameId;
  577. }
  578. }
  579. if (subMesh.effect && this.isFrozen) {
  580. if (this._wasPreviouslyReady) {
  581. return true;
  582. }
  583. }
  584. if (!subMesh._materialDefines) {
  585. subMesh._materialDefines = new NodeMaterialDefines();
  586. }
  587. var defines = <NodeMaterialDefines>subMesh._materialDefines;
  588. if (!this.checkReadyOnEveryCall && subMesh.effect) {
  589. if (defines._renderId === scene.getRenderId()) {
  590. return true;
  591. }
  592. }
  593. var engine = scene.getEngine();
  594. this._prepareDefinesForAttributes(mesh, defines);
  595. // Check if blocks are ready
  596. if (this._sharedData.blockingBlocks.some((b) => !b.isReady(mesh, this, defines, useInstances))) {
  597. return false;
  598. }
  599. // Shared defines
  600. this._sharedData.blocksWithDefines.forEach((b) => {
  601. b.initializeDefines(mesh, this, defines, useInstances);
  602. });
  603. this._sharedData.blocksWithDefines.forEach((b) => {
  604. b.prepareDefines(mesh, this, defines, useInstances);
  605. });
  606. // Need to recompile?
  607. if (defines.isDirty) {
  608. defines.markAsProcessed();
  609. // Repeatable content generators
  610. this._vertexCompilationState.compilationString = this._vertexCompilationState._builtCompilationString;
  611. this._fragmentCompilationState.compilationString = this._fragmentCompilationState._builtCompilationString;
  612. this._sharedData.repeatableContentBlocks.forEach((b) => {
  613. b.replaceRepeatableContent(this._vertexCompilationState, this._fragmentCompilationState, mesh, defines);
  614. });
  615. // Uniforms
  616. let uniformBuffers: string[] = [];
  617. this._sharedData.dynamicUniformBlocks.forEach((b) => {
  618. b.updateUniformsAndSamples(this._vertexCompilationState, this, defines, uniformBuffers);
  619. });
  620. let mergedUniforms = this._vertexCompilationState.uniforms;
  621. this._fragmentCompilationState.uniforms.forEach((u) => {
  622. let index = mergedUniforms.indexOf(u);
  623. if (index === -1) {
  624. mergedUniforms.push(u);
  625. }
  626. });
  627. // Samplers
  628. let mergedSamplers = this._vertexCompilationState.samplers;
  629. this._fragmentCompilationState.samplers.forEach((s) => {
  630. let index = mergedSamplers.indexOf(s);
  631. if (index === -1) {
  632. mergedSamplers.push(s);
  633. }
  634. });
  635. var fallbacks = new EffectFallbacks();
  636. this._sharedData.blocksWithFallbacks.forEach((b) => {
  637. b.provideFallbacks(mesh, fallbacks);
  638. });
  639. let previousEffect = subMesh.effect;
  640. // Compilation
  641. var join = defines.toString();
  642. var effect = engine.createEffect({
  643. vertex: "nodeMaterial" + this._buildId,
  644. fragment: "nodeMaterial" + this._buildId,
  645. vertexSource: this._vertexCompilationState.compilationString,
  646. fragmentSource: this._fragmentCompilationState.compilationString
  647. }, <IEffectCreationOptions>{
  648. attributes: this._vertexCompilationState.attributes,
  649. uniformsNames: mergedUniforms,
  650. uniformBuffersNames: uniformBuffers,
  651. samplers: mergedSamplers,
  652. defines: join,
  653. fallbacks: fallbacks,
  654. onCompiled: this.onCompiled,
  655. onError: this.onError,
  656. indexParameters: { maxSimultaneousLights: this.maxSimultaneousLights, maxSimultaneousMorphTargets: defines.NUM_MORPH_INFLUENCERS }
  657. }, engine);
  658. if (effect) {
  659. // Use previous effect while new one is compiling
  660. if (this.allowShaderHotSwapping && previousEffect && !effect.isReady()) {
  661. effect = previousEffect;
  662. defines.markAsUnprocessed();
  663. } else {
  664. scene.resetCachedMaterial();
  665. subMesh.setEffect(effect, defines);
  666. }
  667. }
  668. }
  669. if (!subMesh.effect || !subMesh.effect.isReady()) {
  670. return false;
  671. }
  672. defines._renderId = scene.getRenderId();
  673. this._wasPreviouslyReady = true;
  674. return true;
  675. }
  676. /**
  677. * Get a string representing the shaders built by the current node graph
  678. */
  679. public get compiledShaders() {
  680. return `// Vertex shader\r\n${this._vertexCompilationState.compilationString}\r\n\r\n// Fragment shader\r\n${this._fragmentCompilationState.compilationString}`;
  681. }
  682. /**
  683. * Binds the world matrix to the material
  684. * @param world defines the world transformation matrix
  685. */
  686. public bindOnlyWorldMatrix(world: Matrix): void {
  687. var scene = this.getScene();
  688. if (!this._activeEffect) {
  689. return;
  690. }
  691. let hints = this._sharedData.hints;
  692. if (hints.needWorldViewMatrix) {
  693. world.multiplyToRef(scene.getViewMatrix(), this._cachedWorldViewMatrix);
  694. }
  695. if (hints.needWorldViewProjectionMatrix) {
  696. world.multiplyToRef(scene.getTransformMatrix(), this._cachedWorldViewProjectionMatrix);
  697. }
  698. // Connection points
  699. for (var inputBlock of this._sharedData.inputBlocks) {
  700. inputBlock._transmitWorld(this._activeEffect, world, this._cachedWorldViewMatrix, this._cachedWorldViewProjectionMatrix);
  701. }
  702. }
  703. /**
  704. * Binds the submesh to this material by preparing the effect and shader to draw
  705. * @param world defines the world transformation matrix
  706. * @param mesh defines the mesh containing the submesh
  707. * @param subMesh defines the submesh to bind the material to
  708. */
  709. public bindForSubMesh(world: Matrix, mesh: Mesh, subMesh: SubMesh): void {
  710. let scene = this.getScene();
  711. var effect = subMesh.effect;
  712. if (!effect) {
  713. return;
  714. }
  715. this._activeEffect = effect;
  716. // Matrices
  717. this.bindOnlyWorldMatrix(world);
  718. let mustRebind = this._mustRebind(scene, effect, mesh.visibility);
  719. if (mustRebind) {
  720. let sharedData = this._sharedData;
  721. if (effect && scene.getCachedMaterial() !== this) {
  722. // Bindable blocks
  723. for (var block of sharedData.bindableBlocks) {
  724. block.bind(effect, this, mesh);
  725. }
  726. // Connection points
  727. for (var inputBlock of sharedData.inputBlocks) {
  728. inputBlock._transmit(effect, scene);
  729. }
  730. }
  731. }
  732. this._afterBind(mesh, this._activeEffect);
  733. }
  734. /**
  735. * Gets the active textures from the material
  736. * @returns an array of textures
  737. */
  738. public getActiveTextures(): BaseTexture[] {
  739. var activeTextures = super.getActiveTextures();
  740. activeTextures.push(...this._sharedData.textureBlocks.filter((tb) => tb.texture).map((tb) => tb.texture!));
  741. return activeTextures;
  742. }
  743. /**
  744. * Gets the list of texture blocks
  745. * @returns an array of texture blocks
  746. */
  747. public getTextureBlocks(): (TextureBlock | ReflectionTextureBlock)[] {
  748. if (!this._sharedData) {
  749. return [];
  750. }
  751. return this._sharedData.textureBlocks;
  752. }
  753. /**
  754. * Specifies if the material uses a texture
  755. * @param texture defines the texture to check against the material
  756. * @returns a boolean specifying if the material uses the texture
  757. */
  758. public hasTexture(texture: BaseTexture): boolean {
  759. if (super.hasTexture(texture)) {
  760. return true;
  761. }
  762. if (!this._sharedData) {
  763. return false;
  764. }
  765. for (var t of this._sharedData.textureBlocks) {
  766. if (t.texture === texture) {
  767. return true;
  768. }
  769. }
  770. return false;
  771. }
  772. /**
  773. * Disposes the material
  774. * @param forceDisposeEffect specifies if effects should be forcefully disposed
  775. * @param forceDisposeTextures specifies if textures should be forcefully disposed
  776. * @param notBoundToMesh specifies if the material that is being disposed is known to be not bound to any mesh
  777. */
  778. public dispose(forceDisposeEffect?: boolean, forceDisposeTextures?: boolean, notBoundToMesh?: boolean): void {
  779. if (forceDisposeTextures) {
  780. for (var texture of this._sharedData.textureBlocks.filter((tb) => tb.texture).map((tb) => tb.texture!)) {
  781. texture.dispose();
  782. }
  783. }
  784. for (var block of this.attachedBlocks) {
  785. block.dispose();
  786. }
  787. this.onBuildObservable.clear();
  788. super.dispose(forceDisposeEffect, forceDisposeTextures, notBoundToMesh);
  789. }
  790. /** Creates the node editor window. */
  791. private _createNodeEditor() {
  792. this.BJSNODEMATERIALEDITOR = this.BJSNODEMATERIALEDITOR || this._getGlobalNodeMaterialEditor();
  793. this.BJSNODEMATERIALEDITOR.NodeEditor.Show({
  794. nodeMaterial: this
  795. });
  796. }
  797. /**
  798. * Launch the node material editor
  799. * @param config Define the configuration of the editor
  800. * @return a promise fulfilled when the node editor is visible
  801. */
  802. public edit(config?: INodeMaterialEditorOptions): Promise<void> {
  803. return new Promise((resolve, reject) => {
  804. if (typeof this.BJSNODEMATERIALEDITOR == 'undefined') {
  805. const editorUrl = config && config.editorURL ? config.editorURL : NodeMaterial.EditorURL;
  806. // Load editor and add it to the DOM
  807. Tools.LoadScript(editorUrl, () => {
  808. this._createNodeEditor();
  809. resolve();
  810. });
  811. } else {
  812. // Otherwise creates the editor
  813. this._createNodeEditor();
  814. resolve();
  815. }
  816. });
  817. }
  818. /**
  819. * Clear the current material
  820. */
  821. public clear() {
  822. this._vertexOutputNodes = [];
  823. this._fragmentOutputNodes = [];
  824. this.attachedBlocks = [];
  825. }
  826. /**
  827. * Clear the current material and set it to a default state
  828. */
  829. public setToDefault() {
  830. this.clear();
  831. this.editorData = null;
  832. var positionInput = new InputBlock("position");
  833. positionInput.setAsAttribute("position");
  834. var worldInput = new InputBlock("world");
  835. worldInput.setAsSystemValue(BABYLON.NodeMaterialSystemValues.World);
  836. var worldPos = new TransformBlock("worldPos");
  837. positionInput.connectTo(worldPos);
  838. worldInput.connectTo(worldPos);
  839. var viewProjectionInput = new InputBlock("viewProjection");
  840. viewProjectionInput.setAsSystemValue(BABYLON.NodeMaterialSystemValues.ViewProjection);
  841. var worldPosdMultipliedByViewProjection = new TransformBlock("worldPos * viewProjectionTransform");
  842. worldPos.connectTo(worldPosdMultipliedByViewProjection);
  843. viewProjectionInput.connectTo(worldPosdMultipliedByViewProjection);
  844. var vertexOutput = new VertexOutputBlock("vertexOutput");
  845. worldPosdMultipliedByViewProjection.connectTo(vertexOutput);
  846. // Pixel
  847. var pixelColor = new InputBlock("color");
  848. pixelColor.value = new Color4(0.8, 0.8, 0.8, 1);
  849. var fragmentOutput = new FragmentOutputBlock("fragmentOutput");
  850. pixelColor.connectTo(fragmentOutput);
  851. // Add to nodes
  852. this.addOutputNode(vertexOutput);
  853. this.addOutputNode(fragmentOutput);
  854. }
  855. /**
  856. * Loads the current Node Material from a url pointing to a file save by the Node Material Editor
  857. * @param url defines the url to load from
  858. * @returns a promise that will fullfil when the material is fully loaded
  859. */
  860. public loadAsync(url: string) {
  861. return this.getScene()._loadFileAsync(url).then((data) => {
  862. const serializationObject = JSON.parse(data as string);
  863. this.loadFromSerialization(serializationObject, "");
  864. });
  865. }
  866. private _gatherBlocks(rootNode: NodeMaterialBlock, list: NodeMaterialBlock[]) {
  867. if (list.indexOf(rootNode) !== -1) {
  868. return;
  869. }
  870. list.push(rootNode);
  871. for (var input of rootNode.inputs) {
  872. let connectedPoint = input.connectedPoint;
  873. if (connectedPoint) {
  874. let block = connectedPoint.ownerBlock;
  875. if (block !== rootNode) {
  876. this._gatherBlocks(block, list);
  877. }
  878. }
  879. }
  880. }
  881. /**
  882. * Generate a string containing the code declaration required to create an equivalent of this material
  883. * @returns a string
  884. */
  885. public generateCode() {
  886. let alreadyDumped: NodeMaterialBlock[] = [];
  887. let vertexBlocks: NodeMaterialBlock[] = [];
  888. let uniqueNames: string[] = [];
  889. // Gets active blocks
  890. for (var outputNode of this._vertexOutputNodes) {
  891. this._gatherBlocks(outputNode, vertexBlocks);
  892. }
  893. let fragmentBlocks: NodeMaterialBlock[] = [];
  894. for (var outputNode of this._fragmentOutputNodes) {
  895. this._gatherBlocks(outputNode, fragmentBlocks);
  896. }
  897. // Generate vertex shader
  898. let codeString = `var nodeMaterial = new BABYLON.NodeMaterial("${this.name || "node material"}");\r\n`;
  899. for (var node of vertexBlocks) {
  900. if (node.isInput && alreadyDumped.indexOf(node) === -1) {
  901. codeString += node._dumpCode(uniqueNames, alreadyDumped);
  902. }
  903. }
  904. // Generate fragment shader
  905. for (var node of fragmentBlocks) {
  906. if (node.isInput && alreadyDumped.indexOf(node) === -1) {
  907. codeString += node._dumpCode(uniqueNames, alreadyDumped);
  908. }
  909. }
  910. // Connections
  911. alreadyDumped = [];
  912. codeString += "\r\n// Connections\r\n";
  913. for (var node of this._vertexOutputNodes) {
  914. codeString += node._dumpCodeForOutputConnections(alreadyDumped);
  915. }
  916. for (var node of this._fragmentOutputNodes) {
  917. codeString += node._dumpCodeForOutputConnections(alreadyDumped);
  918. }
  919. // Output nodes
  920. codeString += "\r\n// Output nodes\r\n";
  921. for (var node of this._vertexOutputNodes) {
  922. codeString += `nodeMaterial.addOutputNode(${node._codeVariableName});\r\n`;
  923. }
  924. for (var node of this._fragmentOutputNodes) {
  925. codeString += `nodeMaterial.addOutputNode(${node._codeVariableName});\r\n`;
  926. }
  927. codeString += `nodeMaterial.build();\r\n`;
  928. return codeString;
  929. }
  930. /**
  931. * Serializes this material in a JSON representation
  932. * @returns the serialized material object
  933. */
  934. public serialize(): any {
  935. var serializationObject = SerializationHelper.Serialize(this);
  936. serializationObject.customType = "BABYLON.NodeMaterial";
  937. serializationObject.outputNodes = [];
  938. serializationObject.editorData = this.editorData;
  939. let blocks: NodeMaterialBlock[] = [];
  940. // Outputs
  941. for (var outputNode of this._vertexOutputNodes) {
  942. this._gatherBlocks(outputNode, blocks);
  943. serializationObject.outputNodes.push(outputNode.uniqueId);
  944. }
  945. for (var outputNode of this._fragmentOutputNodes) {
  946. this._gatherBlocks(outputNode, blocks);
  947. if (serializationObject.outputNodes.indexOf(outputNode.uniqueId) === -1) {
  948. serializationObject.outputNodes.push(outputNode.uniqueId);
  949. }
  950. }
  951. // Blocks
  952. serializationObject.blocks = [];
  953. for (var block of blocks) {
  954. serializationObject.blocks.push(block.serialize());
  955. }
  956. for (var block of this.attachedBlocks) {
  957. if (blocks.indexOf(block) !== -1) {
  958. continue;
  959. }
  960. serializationObject.blocks.push(block.serialize());
  961. }
  962. return serializationObject;
  963. }
  964. private _restoreConnections(block: NodeMaterialBlock, source: any, map: {[key: number]: NodeMaterialBlock}) {
  965. for (var outputPoint of block.outputs) {
  966. for (var candidate of source.blocks) {
  967. let target = map[candidate.id];
  968. for (var input of candidate.inputs) {
  969. if (map[input.targetBlockId] === block && input.targetConnectionName === outputPoint.name) {
  970. let inputPoint = target.getInputByName(input.inputName);
  971. if (!inputPoint || inputPoint.isConnected) {
  972. continue;
  973. }
  974. outputPoint.connectTo(inputPoint, true);
  975. this._restoreConnections(target, source, map);
  976. continue;
  977. }
  978. }
  979. }
  980. }
  981. }
  982. /**
  983. * Clear the current graph and load a new one from a serialization object
  984. * @param source defines the JSON representation of the material
  985. * @param rootUrl defines the root URL to use to load textures and relative dependencies
  986. */
  987. public loadFromSerialization(source: any, rootUrl: string = "") {
  988. this.clear();
  989. let map: {[key: number]: NodeMaterialBlock} = {};
  990. // Create blocks
  991. for (var parsedBlock of source.blocks) {
  992. let blockType = _TypeStore.GetClass(parsedBlock.customType);
  993. if (blockType) {
  994. let block: NodeMaterialBlock = new blockType();
  995. block._deserialize(parsedBlock, this.getScene(), rootUrl);
  996. map[parsedBlock.id] = block;
  997. this.attachedBlocks.push(block);
  998. }
  999. }
  1000. // Connections
  1001. // Starts with input blocks only
  1002. for (var blockIndex = 0; blockIndex < source.blocks.length; blockIndex++) {
  1003. let parsedBlock = source.blocks[blockIndex];
  1004. let block = map[parsedBlock.id];
  1005. if (block.inputs.length) {
  1006. continue;
  1007. }
  1008. this._restoreConnections(block, source, map);
  1009. }
  1010. // Outputs
  1011. for (var outputNodeId of source.outputNodes) {
  1012. this.addOutputNode(map[outputNodeId]);
  1013. }
  1014. // UI related info
  1015. if (source.locations || source.editorData && source.editorData.locations) {
  1016. let locations: {
  1017. blockId: number;
  1018. x: number;
  1019. y: number;
  1020. }[] = source.locations || source.editorData.locations;
  1021. for (var location of locations) {
  1022. location.blockId = map[location.blockId].uniqueId;
  1023. }
  1024. if (source.locations) {
  1025. this.editorData = {
  1026. locations: locations
  1027. };
  1028. } else {
  1029. this.editorData = source.editorData;
  1030. this.editorData.locations = locations;
  1031. }
  1032. }
  1033. }
  1034. /**
  1035. * Creates a node material from parsed material data
  1036. * @param source defines the JSON representation of the material
  1037. * @param scene defines the hosting scene
  1038. * @param rootUrl defines the root URL to use to load textures and relative dependencies
  1039. * @returns a new node material
  1040. */
  1041. public static Parse(source: any, scene: Scene, rootUrl: string = ""): NodeMaterial {
  1042. let nodeMaterial = SerializationHelper.Parse(() => new NodeMaterial(source.name, scene), source, scene, rootUrl);
  1043. nodeMaterial.loadFromSerialization(source, rootUrl);
  1044. nodeMaterial.build();
  1045. return nodeMaterial;
  1046. }
  1047. /**
  1048. * Creates a new node material set to default basic configuration
  1049. * @param name defines the name of the material
  1050. * @param scene defines the hosting scene
  1051. * @returns a new NodeMaterial
  1052. */
  1053. public static CreateDefault(name: string, scene?: Scene) {
  1054. let newMaterial = new NodeMaterial(name, scene);
  1055. newMaterial.setToDefault();
  1056. newMaterial.build();
  1057. return newMaterial;
  1058. }
  1059. }
  1060. _TypeStore.RegisteredTypes["BABYLON.NodeMaterial"] = NodeMaterial;