nodeMaterial.ts 42 KB

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