nodeMaterial.ts 48 KB

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