nodeMaterial.ts 33 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966
  1. import { NodeMaterialBlock } from './nodeMaterialBlock';
  2. import { PushMaterial } from '../pushMaterial';
  3. import { Scene } from '../../scene';
  4. import { AbstractMesh } from '../../Meshes/abstractMesh';
  5. import { Matrix } from '../../Maths/math.vector';
  6. import { Color4 } from '../../Maths/math.color';
  7. import { Mesh } from '../../Meshes/mesh';
  8. import { Engine } from '../../Engines/engine';
  9. import { NodeMaterialBuildState } from './nodeMaterialBuildState';
  10. import { EffectCreationOptions, EffectFallbacks } from '../effect';
  11. import { BaseTexture } from '../../Materials/Textures/baseTexture';
  12. import { Observable, Observer } from '../../Misc/observable';
  13. import { NodeMaterialBlockTargets } from './nodeMaterialBlockTargets';
  14. import { NodeMaterialBuildStateSharedData } from './nodeMaterialBuildStateSharedData';
  15. import { SubMesh } from '../../Meshes/subMesh';
  16. import { MaterialDefines } from '../../Materials/materialDefines';
  17. import { NodeMaterialOptimizer } from './Optimizers/nodeMaterialOptimizer';
  18. import { ImageProcessingConfiguration, IImageProcessingConfigurationDefines } from '../imageProcessingConfiguration';
  19. import { Nullable } from '../../types';
  20. import { VertexBuffer } from '../../Meshes/buffer';
  21. import { Tools } from '../../Misc/tools';
  22. import { VectorTransformBlock } from './Blocks/vectorTransformBlock';
  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. // declare NODEEDITOR namespace for compilation issue
  29. declare var NODEEDITOR: any;
  30. declare var BABYLON: any;
  31. /**
  32. * Interface used to configure the node material editor
  33. */
  34. export interface INodeMaterialEditorOptions {
  35. /** Define the URl to load node editor script */
  36. editorURL?: string;
  37. }
  38. /** @hidden */
  39. export class NodeMaterialDefines extends MaterialDefines implements IImageProcessingConfigurationDefines {
  40. /** BONES */
  41. public NUM_BONE_INFLUENCERS = 0;
  42. public BonesPerMesh = 0;
  43. public BONETEXTURE = false;
  44. /** MORPH TARGETS */
  45. public MORPHTARGETS = false;
  46. public MORPHTARGETS_NORMAL = false;
  47. public MORPHTARGETS_TANGENT = false;
  48. public MORPHTARGETS_UV = false;
  49. public NUM_MORPH_INFLUENCERS = 0;
  50. /** IMAGE PROCESSING */
  51. public IMAGEPROCESSING = false;
  52. public VIGNETTE = false;
  53. public VIGNETTEBLENDMODEMULTIPLY = false;
  54. public VIGNETTEBLENDMODEOPAQUE = false;
  55. public TONEMAPPING = false;
  56. public TONEMAPPING_ACES = false;
  57. public CONTRAST = false;
  58. public EXPOSURE = false;
  59. public COLORCURVES = false;
  60. public COLORGRADING = false;
  61. public COLORGRADING3D = false;
  62. public SAMPLER3DGREENDEPTH = false;
  63. public SAMPLER3DBGRMAP = false;
  64. public IMAGEPROCESSINGPOSTPROCESS = false;
  65. constructor() {
  66. super();
  67. this.rebuild();
  68. }
  69. public setValue(name: string, value: boolean) {
  70. if (this[name] === undefined) {
  71. this._keys.push(name);
  72. }
  73. this[name] = value;
  74. }
  75. }
  76. /**
  77. * Class used to configure NodeMaterial
  78. */
  79. export interface INodeMaterialOptions {
  80. /**
  81. * Defines if blocks should emit comments
  82. */
  83. emitComments: boolean;
  84. }
  85. /**
  86. * Class used to create a node based material built by assembling shader blocks
  87. */
  88. export class NodeMaterial extends PushMaterial {
  89. private _options: INodeMaterialOptions;
  90. private _vertexCompilationState: NodeMaterialBuildState;
  91. private _fragmentCompilationState: NodeMaterialBuildState;
  92. private _sharedData: NodeMaterialBuildStateSharedData;
  93. private _buildId: number = 0;
  94. private _buildWasSuccessful = false;
  95. private _cachedWorldViewMatrix = new Matrix();
  96. private _cachedWorldViewProjectionMatrix = new Matrix();
  97. private _optimizers = new Array<NodeMaterialOptimizer>();
  98. /** Define the URl to load node editor script */
  99. public static EditorURL = `https://unpkg.com/babylonjs-node-editor@${Engine.Version}/babylon.nodeEditor.js`;
  100. private BJSNODEMATERIALEDITOR = this._getGlobalNodeMaterialEditor();
  101. /** Get the inspector from bundle or global */
  102. private _getGlobalNodeMaterialEditor(): any {
  103. // UMD Global name detection from Webpack Bundle UMD Name.
  104. if (typeof NODEEDITOR !== 'undefined') {
  105. return NODEEDITOR;
  106. }
  107. // In case of module let's check the global emitted from the editor entry point.
  108. if (typeof BABYLON !== 'undefined' && typeof BABYLON.NodeEditor !== 'undefined') {
  109. return BABYLON;
  110. }
  111. return undefined;
  112. }
  113. /**
  114. * Defines the maximum number of lights that can be used in the material
  115. */
  116. public maxSimultaneousLights = 4;
  117. /**
  118. * Observable raised when the material is built
  119. */
  120. public onBuildObservable = new Observable<NodeMaterial>();
  121. /**
  122. * Gets or sets the root nodes of the material vertex shader
  123. */
  124. public _vertexOutputNodes = new Array<NodeMaterialBlock>();
  125. /**
  126. * Gets or sets the root nodes of the material fragment (pixel) shader
  127. */
  128. public _fragmentOutputNodes = new Array<NodeMaterialBlock>();
  129. /** Gets or sets options to control the node material overall behavior */
  130. public get options() {
  131. return this._options;
  132. }
  133. public set options(options: INodeMaterialOptions) {
  134. this._options = options;
  135. }
  136. /**
  137. * Default configuration related to image processing available in the standard Material.
  138. */
  139. protected _imageProcessingConfiguration: ImageProcessingConfiguration;
  140. /**
  141. * Gets the image processing configuration used either in this material.
  142. */
  143. public get imageProcessingConfiguration(): ImageProcessingConfiguration {
  144. return this._imageProcessingConfiguration;
  145. }
  146. /**
  147. * Sets the Default image processing configuration used either in the this material.
  148. *
  149. * If sets to null, the scene one is in use.
  150. */
  151. public set imageProcessingConfiguration(value: ImageProcessingConfiguration) {
  152. this._attachImageProcessingConfiguration(value);
  153. // Ensure the effect will be rebuilt.
  154. this._markAllSubMeshesAsTexturesDirty();
  155. }
  156. /**
  157. * Create a new node based material
  158. * @param name defines the material name
  159. * @param scene defines the hosting scene
  160. * @param options defines creation option
  161. */
  162. constructor(name: string, scene?: Scene, options: Partial<INodeMaterialOptions> = {}) {
  163. super(name, scene || Engine.LastCreatedScene!);
  164. this._options = {
  165. emitComments: false,
  166. ...options
  167. };
  168. // Setup the default processing configuration to the scene.
  169. this._attachImageProcessingConfiguration(null);
  170. }
  171. /**
  172. * Gets the current class name of the material e.g. "NodeMaterial"
  173. * @returns the class name
  174. */
  175. public getClassName(): string {
  176. return "NodeMaterial";
  177. }
  178. /**
  179. * Keep track of the image processing observer to allow dispose and replace.
  180. */
  181. private _imageProcessingObserver: Nullable<Observer<ImageProcessingConfiguration>>;
  182. /**
  183. * Attaches a new image processing configuration to the Standard Material.
  184. * @param configuration
  185. */
  186. protected _attachImageProcessingConfiguration(configuration: Nullable<ImageProcessingConfiguration>): void {
  187. if (configuration === this._imageProcessingConfiguration) {
  188. return;
  189. }
  190. // Detaches observer.
  191. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  192. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  193. }
  194. // Pick the scene configuration if needed.
  195. if (!configuration) {
  196. this._imageProcessingConfiguration = this.getScene().imageProcessingConfiguration;
  197. }
  198. else {
  199. this._imageProcessingConfiguration = configuration;
  200. }
  201. // Attaches observer.
  202. if (this._imageProcessingConfiguration) {
  203. this._imageProcessingObserver = this._imageProcessingConfiguration.onUpdateParameters.add(() => {
  204. this._markAllSubMeshesAsImageProcessingDirty();
  205. });
  206. }
  207. }
  208. /**
  209. * Adds a new optimizer to the list of optimizers
  210. * @param optimizer defines the optimizers to add
  211. * @returns the current material
  212. */
  213. public registerOptimizer(optimizer: NodeMaterialOptimizer) {
  214. let index = this._optimizers.indexOf(optimizer);
  215. if (index > -1) {
  216. return;
  217. }
  218. this._optimizers.push(optimizer);
  219. return this;
  220. }
  221. /**
  222. * Remove an optimizer from the list of optimizers
  223. * @param optimizer defines the optimizers to remove
  224. * @returns the current material
  225. */
  226. public unregisterOptimizer(optimizer: NodeMaterialOptimizer) {
  227. let index = this._optimizers.indexOf(optimizer);
  228. if (index === -1) {
  229. return;
  230. }
  231. this._optimizers.splice(index, 1);
  232. return this;
  233. }
  234. /**
  235. * Add a new block to the list of output nodes
  236. * @param node defines the node to add
  237. * @returns the current material
  238. */
  239. public addOutputNode(node: NodeMaterialBlock) {
  240. if (node.target === null) {
  241. throw "This node is not meant to be an output node. You may want to explicitly set its target value.";
  242. }
  243. if ((node.target & NodeMaterialBlockTargets.Vertex) !== 0) {
  244. this._addVertexOutputNode(node);
  245. }
  246. if ((node.target & NodeMaterialBlockTargets.Fragment) !== 0) {
  247. this._addFragmentOutputNode(node);
  248. }
  249. return this;
  250. }
  251. /**
  252. * Remove a block from the list of root nodes
  253. * @param node defines the node to remove
  254. * @returns the current material
  255. */
  256. public removeOutputNode(node: NodeMaterialBlock) {
  257. if (node.target === null) {
  258. return this;
  259. }
  260. if ((node.target & NodeMaterialBlockTargets.Vertex) !== 0) {
  261. this._removeVertexOutputNode(node);
  262. }
  263. if ((node.target & NodeMaterialBlockTargets.Fragment) !== 0) {
  264. this._removeFragmentOutputNode(node);
  265. }
  266. return this;
  267. }
  268. private _addVertexOutputNode(node: NodeMaterialBlock) {
  269. if (this._vertexOutputNodes.indexOf(node) !== -1) {
  270. return;
  271. }
  272. node.target = NodeMaterialBlockTargets.Vertex;
  273. this._vertexOutputNodes.push(node);
  274. return this;
  275. }
  276. private _removeVertexOutputNode(node: NodeMaterialBlock) {
  277. let index = this._vertexOutputNodes.indexOf(node);
  278. if (index === -1) {
  279. return;
  280. }
  281. this._vertexOutputNodes.splice(index, 1);
  282. return this;
  283. }
  284. private _addFragmentOutputNode(node: NodeMaterialBlock) {
  285. if (this._fragmentOutputNodes.indexOf(node) !== -1) {
  286. return;
  287. }
  288. node.target = NodeMaterialBlockTargets.Fragment;
  289. this._fragmentOutputNodes.push(node);
  290. return this;
  291. }
  292. private _removeFragmentOutputNode(node: NodeMaterialBlock) {
  293. let index = this._fragmentOutputNodes.indexOf(node);
  294. if (index === -1) {
  295. return;
  296. }
  297. this._fragmentOutputNodes.splice(index, 1);
  298. return this;
  299. }
  300. /**
  301. * Specifies if the material will require alpha blending
  302. * @returns a boolean specifying if alpha blending is needed
  303. */
  304. public needAlphaBlending(): boolean {
  305. return (this.alpha < 1.0) || this._sharedData.hints.needAlphaBlending;
  306. }
  307. /**
  308. * Specifies if this material should be rendered in alpha test mode
  309. * @returns a boolean specifying if an alpha test is needed.
  310. */
  311. public needAlphaTesting(): boolean {
  312. return this._sharedData.hints.needAlphaTesting;
  313. }
  314. private _initializeBlock(node: NodeMaterialBlock, state: NodeMaterialBuildState, nodesToProcessForOtherBuildState: NodeMaterialBlock[]) {
  315. node.initialize(state);
  316. node.autoConfigure();
  317. if (node.isInput) {
  318. (node as InputBlock).associatedVariableName = "";
  319. }
  320. for (var input of node.inputs) {
  321. input.associatedVariableName = "";
  322. let connectedPoint = input.connectedPoint;
  323. if (connectedPoint) {
  324. let block = connectedPoint.ownerBlock;
  325. if (block !== node) {
  326. if (block.target === NodeMaterialBlockTargets.VertexAndFragment) {
  327. nodesToProcessForOtherBuildState.push(block);
  328. }
  329. this._initializeBlock(block, state, nodesToProcessForOtherBuildState);
  330. }
  331. }
  332. }
  333. for (var output of node.outputs) {
  334. output.associatedVariableName = "";
  335. }
  336. }
  337. private _resetDualBlocks(node: NodeMaterialBlock, id: number) {
  338. if (node.target === NodeMaterialBlockTargets.VertexAndFragment) {
  339. node.buildId = id;
  340. }
  341. for (var inputs of node.inputs) {
  342. let connectedPoint = inputs.connectedPoint;
  343. if (connectedPoint) {
  344. let block = connectedPoint.ownerBlock;
  345. if (block !== node) {
  346. this._resetDualBlocks(block, id);
  347. }
  348. }
  349. }
  350. }
  351. /**
  352. * Build the material and generates the inner effect
  353. * @param verbose defines if the build should log activity
  354. */
  355. public build(verbose: boolean = false) {
  356. this._buildWasSuccessful = false;
  357. var engine = this.getScene().getEngine();
  358. if (this._vertexOutputNodes.length === 0) {
  359. throw "You must define at least one vertexOutputNode";
  360. }
  361. if (this._fragmentOutputNodes.length === 0) {
  362. throw "You must define at least one fragmentOutputNode";
  363. }
  364. // Compilation state
  365. this._vertexCompilationState = new NodeMaterialBuildState();
  366. this._vertexCompilationState.supportUniformBuffers = engine.supportsUniformBuffers;
  367. this._vertexCompilationState.target = NodeMaterialBlockTargets.Vertex;
  368. this._fragmentCompilationState = new NodeMaterialBuildState();
  369. this._fragmentCompilationState.supportUniformBuffers = engine.supportsUniformBuffers;
  370. this._fragmentCompilationState.target = NodeMaterialBlockTargets.Fragment;
  371. // Shared data
  372. this._sharedData = new NodeMaterialBuildStateSharedData();
  373. this._vertexCompilationState.sharedData = this._sharedData;
  374. this._fragmentCompilationState.sharedData = this._sharedData;
  375. this._sharedData.buildId = this._buildId;
  376. this._sharedData.emitComments = this._options.emitComments;
  377. this._sharedData.verbose = verbose;
  378. // Initialize blocks
  379. let vertexNodes: NodeMaterialBlock[] = [];
  380. let fragmentNodes: NodeMaterialBlock[] = [];
  381. for (var vertexOutputNode of this._vertexOutputNodes) {
  382. vertexNodes.push(vertexOutputNode);
  383. this._initializeBlock(vertexOutputNode, this._vertexCompilationState, fragmentNodes);
  384. }
  385. for (var fragmentOutputNode of this._fragmentOutputNodes) {
  386. fragmentNodes.push(fragmentOutputNode);
  387. this._initializeBlock(fragmentOutputNode, this._fragmentCompilationState, vertexNodes);
  388. }
  389. // Optimize
  390. this.optimize();
  391. // Vertex
  392. for (var vertexOutputNode of vertexNodes) {
  393. vertexOutputNode.build(this._vertexCompilationState);
  394. }
  395. // Fragment
  396. this._fragmentCompilationState._vertexState = this._vertexCompilationState;
  397. for (var fragmentOutputNode of fragmentNodes) {
  398. this._resetDualBlocks(fragmentOutputNode, this._buildId - 1);
  399. }
  400. for (var fragmentOutputNode of fragmentNodes) {
  401. fragmentOutputNode.build(this._fragmentCompilationState);
  402. }
  403. // Finalize
  404. this._vertexCompilationState.finalize(this._vertexCompilationState);
  405. this._fragmentCompilationState.finalize(this._fragmentCompilationState);
  406. this._buildId++;
  407. // Errors
  408. this._sharedData.emitErrors();
  409. if (verbose) {
  410. console.log("Vertex shader:");
  411. console.log(this._vertexCompilationState.compilationString);
  412. console.log("Fragment shader:");
  413. console.log(this._fragmentCompilationState.compilationString);
  414. }
  415. this._buildWasSuccessful = true;
  416. this.onBuildObservable.notifyObservers(this);
  417. this._markAllSubMeshesAsAllDirty();
  418. }
  419. /**
  420. * Runs an otpimization phase to try to improve the shader code
  421. */
  422. public optimize() {
  423. for (var optimizer of this._optimizers) {
  424. optimizer.optimize(this._vertexOutputNodes, this._fragmentOutputNodes);
  425. }
  426. }
  427. private _prepareDefinesForAttributes(mesh: AbstractMesh, defines: NodeMaterialDefines) {
  428. if (!defines._areAttributesDirty) {
  429. return;
  430. }
  431. defines["NORMAL"] = mesh.isVerticesDataPresent(VertexBuffer.NormalKind);
  432. defines["TANGENT"] = mesh.isVerticesDataPresent(VertexBuffer.TangentKind);
  433. defines["UV1"] = mesh.isVerticesDataPresent(VertexBuffer.UVKind);
  434. }
  435. /**
  436. * Get if the submesh is ready to be used and all its information available.
  437. * Child classes can use it to update shaders
  438. * @param mesh defines the mesh to check
  439. * @param subMesh defines which submesh to check
  440. * @param useInstances specifies that instances should be used
  441. * @returns a boolean indicating that the submesh is ready or not
  442. */
  443. public isReadyForSubMesh(mesh: AbstractMesh, subMesh: SubMesh, useInstances: boolean = false): boolean {
  444. if (!this._buildWasSuccessful) {
  445. return false;
  446. }
  447. if (subMesh.effect && this.isFrozen) {
  448. if (this._wasPreviouslyReady) {
  449. return true;
  450. }
  451. }
  452. if (!subMesh._materialDefines) {
  453. subMesh._materialDefines = new NodeMaterialDefines();
  454. }
  455. var scene = this.getScene();
  456. var defines = <NodeMaterialDefines>subMesh._materialDefines;
  457. if (!this.checkReadyOnEveryCall && subMesh.effect) {
  458. if (defines._renderId === scene.getRenderId()) {
  459. return true;
  460. }
  461. }
  462. var engine = scene.getEngine();
  463. this._prepareDefinesForAttributes(mesh, defines);
  464. // Check if blocks are ready
  465. if (this._sharedData.blockingBlocks.some((b) => !b.isReady(mesh, this, defines, useInstances))) {
  466. return false;
  467. }
  468. // Shared defines
  469. this._sharedData.blocksWithDefines.forEach((b) => {
  470. b.initializeDefines(mesh, this, defines, useInstances);
  471. });
  472. this._sharedData.blocksWithDefines.forEach((b) => {
  473. b.prepareDefines(mesh, this, defines, useInstances);
  474. });
  475. // Need to recompile?
  476. if (defines.isDirty) {
  477. defines.markAsProcessed();
  478. // Repeatable content generators
  479. this._vertexCompilationState.compilationString = this._vertexCompilationState._builtCompilationString;
  480. this._fragmentCompilationState.compilationString = this._fragmentCompilationState._builtCompilationString;
  481. this._sharedData.repeatableContentBlocks.forEach((b) => {
  482. b.replaceRepeatableContent(this._vertexCompilationState, this._fragmentCompilationState, mesh, defines);
  483. });
  484. // Uniforms
  485. this._sharedData.dynamicUniformBlocks.forEach((b) => {
  486. b.updateUniformsAndSamples(this._vertexCompilationState, this, defines);
  487. });
  488. let mergedUniforms = this._vertexCompilationState.uniforms;
  489. this._fragmentCompilationState.uniforms.forEach((u) => {
  490. let index = mergedUniforms.indexOf(u);
  491. if (index === -1) {
  492. mergedUniforms.push(u);
  493. }
  494. });
  495. // Uniform buffers
  496. let mergedUniformBuffers = this._vertexCompilationState.uniformBuffers;
  497. this._fragmentCompilationState.uniformBuffers.forEach((u) => {
  498. let index = mergedUniformBuffers.indexOf(u);
  499. if (index === -1) {
  500. mergedUniformBuffers.push(u);
  501. }
  502. });
  503. // Samplers
  504. let mergedSamplers = this._vertexCompilationState.samplers;
  505. this._fragmentCompilationState.samplers.forEach((s) => {
  506. let index = mergedSamplers.indexOf(s);
  507. if (index === -1) {
  508. mergedSamplers.push(s);
  509. }
  510. });
  511. var fallbacks = new EffectFallbacks();
  512. this._sharedData.blocksWithFallbacks.forEach((b) => {
  513. b.provideFallbacks(mesh, fallbacks);
  514. });
  515. let previousEffect = subMesh.effect;
  516. // Compilation
  517. var join = defines.toString();
  518. var effect = engine.createEffect({
  519. vertex: "nodeMaterial" + this._buildId,
  520. fragment: "nodeMaterial" + this._buildId,
  521. vertexSource: this._vertexCompilationState.compilationString,
  522. fragmentSource: this._fragmentCompilationState.compilationString
  523. }, <EffectCreationOptions>{
  524. attributes: this._vertexCompilationState.attributes,
  525. uniformsNames: mergedUniforms,
  526. uniformBuffersNames: mergedUniformBuffers,
  527. samplers: mergedSamplers,
  528. defines: join,
  529. fallbacks: fallbacks,
  530. onCompiled: this.onCompiled,
  531. onError: this.onError,
  532. indexParameters: { maxSimultaneousLights: this.maxSimultaneousLights, maxSimultaneousMorphTargets: defines.NUM_MORPH_INFLUENCERS }
  533. }, engine);
  534. if (effect) {
  535. // Use previous effect while new one is compiling
  536. if (this.allowShaderHotSwapping && previousEffect && !effect.isReady()) {
  537. effect = previousEffect;
  538. defines.markAsUnprocessed();
  539. } else {
  540. scene.resetCachedMaterial();
  541. subMesh.setEffect(effect, defines);
  542. }
  543. }
  544. }
  545. if (!subMesh.effect || !subMesh.effect.isReady()) {
  546. return false;
  547. }
  548. defines._renderId = scene.getRenderId();
  549. this._wasPreviouslyReady = true;
  550. return true;
  551. }
  552. /**
  553. * Get a string representing the shaders built by the current node graph
  554. */
  555. public get compiledShaders() {
  556. return `// Vertex shader\r\n${this._vertexCompilationState.compilationString}\r\n\r\n// Fragment shader\r\n${this._fragmentCompilationState.compilationString}`;
  557. }
  558. /**
  559. * Binds the world matrix to the material
  560. * @param world defines the world transformation matrix
  561. */
  562. public bindOnlyWorldMatrix(world: Matrix): void {
  563. var scene = this.getScene();
  564. if (!this._activeEffect) {
  565. return;
  566. }
  567. let hints = this._sharedData.hints;
  568. if (hints.needWorldViewMatrix) {
  569. world.multiplyToRef(scene.getViewMatrix(), this._cachedWorldViewMatrix);
  570. }
  571. if (hints.needWorldViewProjectionMatrix) {
  572. world.multiplyToRef(scene.getTransformMatrix(), this._cachedWorldViewProjectionMatrix);
  573. }
  574. // Connection points
  575. for (var inputBlock of this._sharedData.inputBlocks) {
  576. inputBlock._transmitWorld(this._activeEffect, world, this._cachedWorldViewMatrix, this._cachedWorldViewProjectionMatrix);
  577. }
  578. }
  579. /**
  580. * Binds the submesh to this material by preparing the effect and shader to draw
  581. * @param world defines the world transformation matrix
  582. * @param mesh defines the mesh containing the submesh
  583. * @param subMesh defines the submesh to bind the material to
  584. */
  585. public bindForSubMesh(world: Matrix, mesh: Mesh, subMesh: SubMesh): void {
  586. let scene = this.getScene();
  587. var effect = subMesh.effect;
  588. if (!effect) {
  589. return;
  590. }
  591. this._activeEffect = effect;
  592. // Matrices
  593. this.bindOnlyWorldMatrix(world);
  594. let mustRebind = this._mustRebind(scene, effect, mesh.visibility);
  595. if (mustRebind) {
  596. let sharedData = this._sharedData;
  597. if (effect && scene.getCachedMaterial() !== this) {
  598. // Bindable blocks
  599. for (var block of sharedData.bindableBlocks) {
  600. block.bind(effect, this, mesh);
  601. }
  602. // Connection points
  603. for (var inputBlock of sharedData.inputBlocks) {
  604. inputBlock._transmit(effect, scene);
  605. }
  606. }
  607. }
  608. this._afterBind(mesh, this._activeEffect);
  609. }
  610. /**
  611. * Gets the active textures from the material
  612. * @returns an array of textures
  613. */
  614. public getActiveTextures(): BaseTexture[] {
  615. var activeTextures = super.getActiveTextures();
  616. activeTextures.push(...this._sharedData.textureBlocks.filter((tb) => tb.texture).map((tb) => tb.texture!));
  617. return activeTextures;
  618. }
  619. /**
  620. * Specifies if the material uses a texture
  621. * @param texture defines the texture to check against the material
  622. * @returns a boolean specifying if the material uses the texture
  623. */
  624. public hasTexture(texture: BaseTexture): boolean {
  625. if (super.hasTexture(texture)) {
  626. return true;
  627. }
  628. for (var t of this._sharedData.textureBlocks) {
  629. if (t.texture === texture) {
  630. return true;
  631. }
  632. }
  633. return false;
  634. }
  635. /**
  636. * Disposes the material
  637. * @param forceDisposeEffect specifies if effects should be forcefully disposed
  638. * @param forceDisposeTextures specifies if textures should be forcefully disposed
  639. * @param notBoundToMesh specifies if the material that is being disposed is known to be not bound to any mesh
  640. */
  641. public dispose(forceDisposeEffect?: boolean, forceDisposeTextures?: boolean, notBoundToMesh?: boolean): void {
  642. if (forceDisposeTextures) {
  643. for (var texture of this._sharedData.textureBlocks.filter((tb) => tb.texture).map((tb) => tb.texture!)) {
  644. texture.dispose();
  645. }
  646. }
  647. this.onBuildObservable.clear();
  648. super.dispose(forceDisposeEffect, forceDisposeTextures, notBoundToMesh);
  649. }
  650. /** Creates the node editor window. */
  651. private _createNodeEditor() {
  652. this.BJSNODEMATERIALEDITOR = this.BJSNODEMATERIALEDITOR || this._getGlobalNodeMaterialEditor();
  653. this.BJSNODEMATERIALEDITOR.NodeEditor.Show({
  654. nodeMaterial: this
  655. });
  656. }
  657. /**
  658. * Launch the node material editor
  659. * @param config Define the configuration of the editor
  660. * @return a promise fulfilled when the node editor is visible
  661. */
  662. public edit(config?: INodeMaterialEditorOptions): Promise<void> {
  663. return new Promise((resolve, reject) => {
  664. if (typeof this.BJSNODEMATERIALEDITOR == 'undefined') {
  665. const editorUrl = config && config.editorURL ? config.editorURL : NodeMaterial.EditorURL;
  666. // Load editor and add it to the DOM
  667. Tools.LoadScript(editorUrl, () => {
  668. this._createNodeEditor();
  669. resolve();
  670. });
  671. } else {
  672. // Otherwise creates the editor
  673. this._createNodeEditor();
  674. resolve();
  675. }
  676. });
  677. }
  678. /**
  679. * Clear the current material
  680. */
  681. public clear() {
  682. this._vertexOutputNodes = [];
  683. this._fragmentOutputNodes = [];
  684. }
  685. /**
  686. * Clear the current material and set it to a default state
  687. */
  688. public setToDefault() {
  689. this.clear();
  690. var positionInput = new InputBlock("position");
  691. positionInput.setAsAttribute("position");
  692. var worldInput = new InputBlock("world");
  693. worldInput.setAsWellKnownValue(BABYLON.NodeMaterialWellKnownValues.World);
  694. var worldPos = new VectorTransformBlock("worldPos");
  695. positionInput.connectTo(worldPos);
  696. worldInput.connectTo(worldPos);
  697. var viewProjectionInput = new InputBlock("viewProjection");
  698. viewProjectionInput.setAsWellKnownValue(BABYLON.NodeMaterialWellKnownValues.ViewProjection);
  699. var worldPosdMultipliedByViewProjection = new VectorTransformBlock("worldPos * viewProjectionTransform");
  700. worldPos.connectTo(worldPosdMultipliedByViewProjection);
  701. viewProjectionInput.connectTo(worldPosdMultipliedByViewProjection);
  702. var vertexOutput = new VertexOutputBlock("vertexOutput");
  703. worldPosdMultipliedByViewProjection.connectTo(vertexOutput);
  704. // Pixel
  705. var pixelColor = new InputBlock("color");
  706. pixelColor.value = new Color4(0.8, 0.8, 0.8, 1);
  707. var pixelOutput = new FragmentOutputBlock("pixelOutput");
  708. pixelColor.connectTo(pixelOutput);
  709. // Add to nodes
  710. this.addOutputNode(vertexOutput);
  711. this.addOutputNode(pixelOutput);
  712. }
  713. _gatherBlocks(rootNode: NodeMaterialBlock, list: NodeMaterialBlock[]) {
  714. if (list.indexOf(rootNode) !== -1) {
  715. return;
  716. }
  717. list.push(rootNode);
  718. for (var inputs of rootNode.inputs) {
  719. let connectedPoint = inputs.connectedPoint;
  720. if (connectedPoint) {
  721. let block = connectedPoint.ownerBlock;
  722. if (block !== rootNode) {
  723. this._gatherBlocks(block, list);
  724. }
  725. }
  726. }
  727. }
  728. /**
  729. * Serializes this material in a JSON representation
  730. * @returns the serialized material object
  731. */
  732. public serialize(): any {
  733. var serializationObject = SerializationHelper.Serialize(this);
  734. serializationObject.customType = "BABYLON.NodeMaterial";
  735. serializationObject.outputNodes = [];
  736. let blocks: NodeMaterialBlock[] = [];
  737. // Outputs
  738. for (var outputNode of this._vertexOutputNodes) {
  739. this._gatherBlocks(outputNode, blocks);
  740. serializationObject.outputNodes.push(outputNode.uniqueId);
  741. }
  742. for (var outputNode of this._fragmentOutputNodes) {
  743. this._gatherBlocks(outputNode, blocks);
  744. serializationObject.outputNodes.push(outputNode.uniqueId);
  745. }
  746. // Blocks
  747. serializationObject.blocks = [];
  748. for (var block of blocks) {
  749. serializationObject.blocks.push(block.serialize());
  750. }
  751. return serializationObject;
  752. }
  753. /**
  754. * Creates a node material from parsed material data
  755. * @param source defines the JSON representation of the material
  756. * @param scene defines the hosting scene
  757. * @param rootUrl defines the root URL to use to load textures and relative dependencies
  758. * @returns a new node material
  759. */
  760. public static Parse(source: any, scene: Scene, rootUrl: string): NodeMaterial {
  761. let nodeMaterial = SerializationHelper.Parse(() => new NodeMaterial(source.name, scene), source, scene, rootUrl);
  762. let map: {[key: number]: NodeMaterialBlock} = {};
  763. // Create blocks
  764. for (var parsedBlock of source.blocks) {
  765. let blockType = _TypeStore.GetClass(parsedBlock.customType);
  766. if (blockType) {
  767. let block: NodeMaterialBlock = new blockType;
  768. map[parsedBlock.id] = block;
  769. }
  770. }
  771. // Connections
  772. // for (var parsedBlock of source.blocks) {
  773. // let block = map[parsedBlock.id];
  774. // for (var input of parsedBlock.inputs) {
  775. // }
  776. // }
  777. // Outputs
  778. for (var outputNodeId of source.outputNodes) {
  779. nodeMaterial.addOutputNode(map[outputNodeId]);
  780. }
  781. return nodeMaterial;
  782. }
  783. }
  784. _TypeStore.RegisteredTypes["BABYLON.NodeMaterial"] = NodeMaterial;