nodeMaterial.ts 42 KB

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