nodeMaterial.ts 49 KB

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