nodeMaterial.ts 29 KB

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