nodeMaterial.ts 29 KB

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