material.ts 35 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166
  1. import { serialize, SerializationHelper } from "../Misc/decorators";
  2. import { Tools, IAnimatable } from "../Misc/tools";
  3. import { SmartArray } from "../Misc/smartArray";
  4. import { Observer, Observable } from "../Misc/observable";
  5. import { Nullable } from "../types";
  6. import { Scene } from "../scene";
  7. import { Plane, Matrix } from "../Maths/math";
  8. import { EngineStore } from "../Engines/engineStore";
  9. import { BaseSubMesh, SubMesh } from "../Meshes/subMesh";
  10. import { Geometry } from "../Meshes/geometry";
  11. import { AbstractMesh } from "../Meshes/abstractMesh";
  12. import { Mesh } from "../Meshes/mesh";
  13. import { UniformBuffer } from "./uniformBuffer";
  14. import { Effect } from "./effect";
  15. import { BaseTexture } from "../Materials/Textures/baseTexture";
  16. import { RenderTargetTexture } from "../Materials/Textures/renderTargetTexture";
  17. import { Animation } from "../Animations/animation";
  18. import { MaterialDefines } from "./materialDefines";
  19. import { Constants } from "../Engines/constants";
  20. import { Logger } from "../Misc/logger";
  21. declare var BABYLON: any;
  22. /**
  23. * Base class for the main features of a material in Babylon.js
  24. */
  25. export class Material implements IAnimatable {
  26. /**
  27. * Returns the triangle fill mode
  28. */
  29. public static readonly TriangleFillMode = Constants.MATERIAL_TriangleFillMode;
  30. /**
  31. * Returns the wireframe mode
  32. */
  33. public static readonly WireFrameFillMode = Constants.MATERIAL_WireFrameFillMode;
  34. /**
  35. * Returns the point fill mode
  36. */
  37. public static readonly PointFillMode = Constants.MATERIAL_PointFillMode;
  38. /**
  39. * Returns the point list draw mode
  40. */
  41. public static readonly PointListDrawMode = Constants.MATERIAL_PointListDrawMode;
  42. /**
  43. * Returns the line list draw mode
  44. */
  45. public static readonly LineListDrawMode = Constants.MATERIAL_LineListDrawMode;
  46. /**
  47. * Returns the line loop draw mode
  48. */
  49. public static readonly LineLoopDrawMode = Constants.MATERIAL_LineLoopDrawMode;
  50. /**
  51. * Returns the line strip draw mode
  52. */
  53. public static readonly LineStripDrawMode = Constants.MATERIAL_LineStripDrawMode;
  54. /**
  55. * Returns the triangle strip draw mode
  56. */
  57. public static readonly TriangleStripDrawMode = Constants.MATERIAL_TriangleStripDrawMode;
  58. /**
  59. * Returns the triangle fan draw mode
  60. */
  61. public static readonly TriangleFanDrawMode = Constants.MATERIAL_TriangleFanDrawMode;
  62. /**
  63. * Stores the clock-wise side orientation
  64. */
  65. public static readonly ClockWiseSideOrientation = Constants.MATERIAL_ClockWiseSideOrientation;
  66. /**
  67. * Stores the counter clock-wise side orientation
  68. */
  69. public static readonly CounterClockWiseSideOrientation = Constants.MATERIAL_CounterClockWiseSideOrientation;
  70. /**
  71. * The dirty texture flag value
  72. */
  73. public static readonly TextureDirtyFlag = Constants.MATERIAL_TextureDirtyFlag;
  74. /**
  75. * The dirty light flag value
  76. */
  77. public static readonly LightDirtyFlag = Constants.MATERIAL_LightDirtyFlag;
  78. /**
  79. * The dirty fresnel flag value
  80. */
  81. public static readonly FresnelDirtyFlag = Constants.MATERIAL_FresnelDirtyFlag;
  82. /**
  83. * The dirty attribute flag value
  84. */
  85. public static readonly AttributesDirtyFlag = Constants.MATERIAL_AttributesDirtyFlag;
  86. /**
  87. * The dirty misc flag value
  88. */
  89. public static readonly MiscDirtyFlag = Constants.MATERIAL_MiscDirtyFlag;
  90. /**
  91. * The all dirty flag value
  92. */
  93. public static readonly AllDirtyFlag = Constants.MATERIAL_AllDirtyFlag;
  94. /**
  95. * The ID of the material
  96. */
  97. @serialize()
  98. public id: string;
  99. /**
  100. * Gets or sets the unique id of the material
  101. */
  102. @serialize()
  103. public uniqueId: number;
  104. /**
  105. * The name of the material
  106. */
  107. @serialize()
  108. public name: string;
  109. /**
  110. * Gets or sets user defined metadata
  111. */
  112. public metadata: any = null;
  113. /**
  114. * For internal use only. Please do not use.
  115. */
  116. public reservedDataStore: any = null;
  117. /**
  118. * Specifies if the ready state should be checked on each call
  119. */
  120. @serialize()
  121. public checkReadyOnEveryCall = false;
  122. /**
  123. * Specifies if the ready state should be checked once
  124. */
  125. @serialize()
  126. public checkReadyOnlyOnce = false;
  127. /**
  128. * The state of the material
  129. */
  130. @serialize()
  131. public state = "";
  132. /**
  133. * The alpha value of the material
  134. */
  135. @serialize("alpha")
  136. protected _alpha = 1.0;
  137. /**
  138. * Sets the alpha value of the material
  139. */
  140. public set alpha(value: number) {
  141. if (this._alpha === value) {
  142. return;
  143. }
  144. this._alpha = value;
  145. this.markAsDirty(Material.MiscDirtyFlag);
  146. }
  147. /**
  148. * Gets the alpha value of the material
  149. */
  150. public get alpha(): number {
  151. return this._alpha;
  152. }
  153. /**
  154. * Specifies if back face culling is enabled
  155. */
  156. @serialize("backFaceCulling")
  157. protected _backFaceCulling = true;
  158. /**
  159. * Sets the back-face culling state
  160. */
  161. public set backFaceCulling(value: boolean) {
  162. if (this._backFaceCulling === value) {
  163. return;
  164. }
  165. this._backFaceCulling = value;
  166. this.markAsDirty(Material.TextureDirtyFlag);
  167. }
  168. /**
  169. * Gets the back-face culling state
  170. */
  171. public get backFaceCulling(): boolean {
  172. return this._backFaceCulling;
  173. }
  174. /**
  175. * Stores the value for side orientation
  176. */
  177. @serialize()
  178. public sideOrientation: number;
  179. /**
  180. * Callback triggered when the material is compiled
  181. */
  182. public onCompiled: (effect: Effect) => void;
  183. /**
  184. * Callback triggered when an error occurs
  185. */
  186. public onError: (effect: Effect, errors: string) => void;
  187. /**
  188. * Callback triggered to get the render target textures
  189. */
  190. public getRenderTargetTextures: () => SmartArray<RenderTargetTexture>;
  191. /**
  192. * Gets a boolean indicating that current material needs to register RTT
  193. */
  194. public get hasRenderTargetTextures(): boolean {
  195. return false;
  196. }
  197. /**
  198. * Specifies if the material should be serialized
  199. */
  200. public doNotSerialize = false;
  201. /**
  202. * @hidden
  203. */
  204. public _storeEffectOnSubMeshes = false;
  205. /**
  206. * Stores the animations for the material
  207. */
  208. public animations: Array<Animation>;
  209. /**
  210. * An event triggered when the material is disposed
  211. */
  212. public onDisposeObservable = new Observable<Material>();
  213. /**
  214. * An observer which watches for dispose events
  215. */
  216. private _onDisposeObserver: Nullable<Observer<Material>>;
  217. private _onUnBindObservable: Nullable<Observable<Material>>;
  218. /**
  219. * Called during a dispose event
  220. */
  221. public set onDispose(callback: () => void) {
  222. if (this._onDisposeObserver) {
  223. this.onDisposeObservable.remove(this._onDisposeObserver);
  224. }
  225. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  226. }
  227. private _onBindObservable: Nullable<Observable<AbstractMesh>>;
  228. /**
  229. * An event triggered when the material is bound
  230. */
  231. public get onBindObservable(): Observable<AbstractMesh> {
  232. if (!this._onBindObservable) {
  233. this._onBindObservable = new Observable<AbstractMesh>();
  234. }
  235. return this._onBindObservable;
  236. }
  237. /**
  238. * An observer which watches for bind events
  239. */
  240. private _onBindObserver: Nullable<Observer<AbstractMesh>>;
  241. /**
  242. * Called during a bind event
  243. */
  244. public set onBind(callback: (Mesh: AbstractMesh) => void) {
  245. if (this._onBindObserver) {
  246. this.onBindObservable.remove(this._onBindObserver);
  247. }
  248. this._onBindObserver = this.onBindObservable.add(callback);
  249. }
  250. /**
  251. * An event triggered when the material is unbound
  252. */
  253. public get onUnBindObservable(): Observable<Material> {
  254. if (!this._onUnBindObservable) {
  255. this._onUnBindObservable = new Observable<Material>();
  256. }
  257. return this._onUnBindObservable;
  258. }
  259. /**
  260. * Stores the value of the alpha mode
  261. */
  262. @serialize("alphaMode")
  263. private _alphaMode: number = Constants.ALPHA_COMBINE;
  264. /**
  265. * Sets the value of the alpha mode.
  266. *
  267. * | Value | Type | Description |
  268. * | --- | --- | --- |
  269. * | 0 | ALPHA_DISABLE | |
  270. * | 1 | ALPHA_ADD | |
  271. * | 2 | ALPHA_COMBINE | |
  272. * | 3 | ALPHA_SUBTRACT | |
  273. * | 4 | ALPHA_MULTIPLY | |
  274. * | 5 | ALPHA_MAXIMIZED | |
  275. * | 6 | ALPHA_ONEONE | |
  276. * | 7 | ALPHA_PREMULTIPLIED | |
  277. * | 8 | ALPHA_PREMULTIPLIED_PORTERDUFF | |
  278. * | 9 | ALPHA_INTERPOLATE | |
  279. * | 10 | ALPHA_SCREENMODE | |
  280. *
  281. */
  282. public set alphaMode(value: number) {
  283. if (this._alphaMode === value) {
  284. return;
  285. }
  286. this._alphaMode = value;
  287. this.markAsDirty(Material.TextureDirtyFlag);
  288. }
  289. /**
  290. * Gets the value of the alpha mode
  291. */
  292. public get alphaMode(): number {
  293. return this._alphaMode;
  294. }
  295. /**
  296. * Stores the state of the need depth pre-pass value
  297. */
  298. @serialize()
  299. private _needDepthPrePass = false;
  300. /**
  301. * Sets the need depth pre-pass value
  302. */
  303. public set needDepthPrePass(value: boolean) {
  304. if (this._needDepthPrePass === value) {
  305. return;
  306. }
  307. this._needDepthPrePass = value;
  308. if (this._needDepthPrePass) {
  309. this.checkReadyOnEveryCall = true;
  310. }
  311. }
  312. /**
  313. * Gets the depth pre-pass value
  314. */
  315. public get needDepthPrePass(): boolean {
  316. return this._needDepthPrePass;
  317. }
  318. /**
  319. * Specifies if depth writing should be disabled
  320. */
  321. @serialize()
  322. public disableDepthWrite = false;
  323. /**
  324. * Specifies if depth writing should be forced
  325. */
  326. @serialize()
  327. public forceDepthWrite = false;
  328. /**
  329. * Specifies if there should be a separate pass for culling
  330. */
  331. @serialize()
  332. public separateCullingPass = false;
  333. /**
  334. * Stores the state specifing if fog should be enabled
  335. */
  336. @serialize("fogEnabled")
  337. private _fogEnabled = true;
  338. /**
  339. * Sets the state for enabling fog
  340. */
  341. public set fogEnabled(value: boolean) {
  342. if (this._fogEnabled === value) {
  343. return;
  344. }
  345. this._fogEnabled = value;
  346. this.markAsDirty(Material.MiscDirtyFlag);
  347. }
  348. /**
  349. * Gets the value of the fog enabled state
  350. */
  351. public get fogEnabled(): boolean {
  352. return this._fogEnabled;
  353. }
  354. /**
  355. * Stores the size of points
  356. */
  357. @serialize()
  358. public pointSize = 1.0;
  359. /**
  360. * Stores the z offset value
  361. */
  362. @serialize()
  363. public zOffset = 0;
  364. /**
  365. * Gets a value specifying if wireframe mode is enabled
  366. */
  367. @serialize()
  368. public get wireframe(): boolean {
  369. switch (this._fillMode) {
  370. case Material.WireFrameFillMode:
  371. case Material.LineListDrawMode:
  372. case Material.LineLoopDrawMode:
  373. case Material.LineStripDrawMode:
  374. return true;
  375. }
  376. return this._scene.forceWireframe;
  377. }
  378. /**
  379. * Sets the state of wireframe mode
  380. */
  381. public set wireframe(value: boolean) {
  382. this.fillMode = (value ? Material.WireFrameFillMode : Material.TriangleFillMode);
  383. }
  384. /**
  385. * Gets the value specifying if point clouds are enabled
  386. */
  387. @serialize()
  388. public get pointsCloud(): boolean {
  389. switch (this._fillMode) {
  390. case Material.PointFillMode:
  391. case Material.PointListDrawMode:
  392. return true;
  393. }
  394. return this._scene.forcePointsCloud;
  395. }
  396. /**
  397. * Sets the state of point cloud mode
  398. */
  399. public set pointsCloud(value: boolean) {
  400. this.fillMode = (value ? Material.PointFillMode : Material.TriangleFillMode);
  401. }
  402. /**
  403. * Gets the material fill mode
  404. */
  405. @serialize()
  406. public get fillMode(): number {
  407. return this._fillMode;
  408. }
  409. /**
  410. * Sets the material fill mode
  411. */
  412. public set fillMode(value: number) {
  413. if (this._fillMode === value) {
  414. return;
  415. }
  416. this._fillMode = value;
  417. this.markAsDirty(Material.MiscDirtyFlag);
  418. }
  419. /**
  420. * @hidden
  421. * Stores the effects for the material
  422. */
  423. public _effect: Nullable<Effect>;
  424. /**
  425. * @hidden
  426. * Specifies if the material was previously ready
  427. */
  428. public _wasPreviouslyReady = false;
  429. /**
  430. * Specifies if uniform buffers should be used
  431. */
  432. private _useUBO: boolean;
  433. /**
  434. * Stores a reference to the scene
  435. */
  436. private _scene: Scene;
  437. /**
  438. * Stores the fill mode state
  439. */
  440. private _fillMode = Material.TriangleFillMode;
  441. /**
  442. * Specifies if the depth write state should be cached
  443. */
  444. private _cachedDepthWriteState: boolean;
  445. /**
  446. * Stores the uniform buffer
  447. */
  448. protected _uniformBuffer: UniformBuffer;
  449. /** @hidden */
  450. public _indexInSceneMaterialArray = -1;
  451. /** @hidden */
  452. public meshMap: Nullable<{ [id: string]: AbstractMesh | undefined }>;
  453. /**
  454. * Creates a material instance
  455. * @param name defines the name of the material
  456. * @param scene defines the scene to reference
  457. * @param doNotAdd specifies if the material should be added to the scene
  458. */
  459. constructor(name: string, scene: Scene, doNotAdd?: boolean) {
  460. this.name = name;
  461. this.id = name || Tools.RandomId();
  462. this._scene = scene || EngineStore.LastCreatedScene;
  463. this.uniqueId = this._scene.getUniqueId();
  464. if (this._scene.useRightHandedSystem) {
  465. this.sideOrientation = Material.ClockWiseSideOrientation;
  466. } else {
  467. this.sideOrientation = Material.CounterClockWiseSideOrientation;
  468. }
  469. this._uniformBuffer = new UniformBuffer(this._scene.getEngine());
  470. this._useUBO = this.getScene().getEngine().supportsUniformBuffers;
  471. if (!doNotAdd) {
  472. this._scene.addMaterial(this);
  473. }
  474. if (this._scene.useMaterialMeshMap) {
  475. this.meshMap = {};
  476. }
  477. }
  478. /**
  479. * Returns a string representation of the current material
  480. * @param fullDetails defines a boolean indicating which levels of logging is desired
  481. * @returns a string with material information
  482. */
  483. public toString(fullDetails?: boolean): string {
  484. var ret = "Name: " + this.name;
  485. if (fullDetails) {
  486. }
  487. return ret;
  488. }
  489. /**
  490. * Gets the class name of the material
  491. * @returns a string with the class name of the material
  492. */
  493. public getClassName(): string {
  494. return "Material";
  495. }
  496. /**
  497. * Specifies if updates for the material been locked
  498. */
  499. public get isFrozen(): boolean {
  500. return this.checkReadyOnlyOnce;
  501. }
  502. /**
  503. * Locks updates for the material
  504. */
  505. public freeze(): void {
  506. this.checkReadyOnlyOnce = true;
  507. }
  508. /**
  509. * Unlocks updates for the material
  510. */
  511. public unfreeze(): void {
  512. this.checkReadyOnlyOnce = false;
  513. }
  514. /**
  515. * Specifies if the material is ready to be used
  516. * @param mesh defines the mesh to check
  517. * @param useInstances specifies if instances should be used
  518. * @returns a boolean indicating if the material is ready to be used
  519. */
  520. public isReady(mesh?: AbstractMesh, useInstances?: boolean): boolean {
  521. return true;
  522. }
  523. /**
  524. * Specifies that the submesh is ready to be used
  525. * @param mesh defines the mesh to check
  526. * @param subMesh defines which submesh to check
  527. * @param useInstances specifies that instances should be used
  528. * @returns a boolean indicating that the submesh is ready or not
  529. */
  530. public isReadyForSubMesh(mesh: AbstractMesh, subMesh: BaseSubMesh, useInstances?: boolean): boolean {
  531. return false;
  532. }
  533. /**
  534. * Returns the material effect
  535. * @returns the effect associated with the material
  536. */
  537. public getEffect(): Nullable<Effect> {
  538. return this._effect;
  539. }
  540. /**
  541. * Returns the current scene
  542. * @returns a Scene
  543. */
  544. public getScene(): Scene {
  545. return this._scene;
  546. }
  547. /**
  548. * Specifies if the material will require alpha blending
  549. * @returns a boolean specifying if alpha blending is needed
  550. */
  551. public needAlphaBlending(): boolean {
  552. return (this.alpha < 1.0);
  553. }
  554. /**
  555. * Specifies if the mesh will require alpha blending
  556. * @param mesh defines the mesh to check
  557. * @returns a boolean specifying if alpha blending is needed for the mesh
  558. */
  559. public needAlphaBlendingForMesh(mesh: AbstractMesh): boolean {
  560. return this.needAlphaBlending() || (mesh.visibility < 1.0) || mesh.hasVertexAlpha;
  561. }
  562. /**
  563. * Specifies if this material should be rendered in alpha test mode
  564. * @returns a boolean specifying if an alpha test is needed.
  565. */
  566. public needAlphaTesting(): boolean {
  567. return false;
  568. }
  569. /**
  570. * Gets the texture used for the alpha test
  571. * @returns the texture to use for alpha testing
  572. */
  573. public getAlphaTestTexture(): Nullable<BaseTexture> {
  574. return null;
  575. }
  576. /**
  577. * Marks the material to indicate that it needs to be re-calculated
  578. */
  579. public markDirty(): void {
  580. this._wasPreviouslyReady = false;
  581. }
  582. /** @hidden */
  583. public _preBind(effect?: Effect, overrideOrientation: Nullable<number> = null): boolean {
  584. var engine = this._scene.getEngine();
  585. var orientation = (overrideOrientation == null) ? this.sideOrientation : overrideOrientation;
  586. var reverse = orientation === Material.ClockWiseSideOrientation;
  587. engine.enableEffect(effect ? effect : this._effect);
  588. engine.setState(this.backFaceCulling, this.zOffset, false, reverse);
  589. return reverse;
  590. }
  591. /**
  592. * Binds the material to the mesh
  593. * @param world defines the world transformation matrix
  594. * @param mesh defines the mesh to bind the material to
  595. */
  596. public bind(world: Matrix, mesh?: Mesh): void {
  597. }
  598. /**
  599. * Binds the submesh to the material
  600. * @param world defines the world transformation matrix
  601. * @param mesh defines the mesh containing the submesh
  602. * @param subMesh defines the submesh to bind the material to
  603. */
  604. public bindForSubMesh(world: Matrix, mesh: Mesh, subMesh: SubMesh): void {
  605. }
  606. /**
  607. * Binds the world matrix to the material
  608. * @param world defines the world transformation matrix
  609. */
  610. public bindOnlyWorldMatrix(world: Matrix): void {
  611. }
  612. /**
  613. * Binds the scene's uniform buffer to the effect.
  614. * @param effect defines the effect to bind to the scene uniform buffer
  615. * @param sceneUbo defines the uniform buffer storing scene data
  616. */
  617. public bindSceneUniformBuffer(effect: Effect, sceneUbo: UniformBuffer): void {
  618. sceneUbo.bindToEffect(effect, "Scene");
  619. }
  620. /**
  621. * Binds the view matrix to the effect
  622. * @param effect defines the effect to bind the view matrix to
  623. */
  624. public bindView(effect: Effect): void {
  625. if (!this._useUBO) {
  626. effect.setMatrix("view", this.getScene().getViewMatrix());
  627. } else {
  628. this.bindSceneUniformBuffer(effect, this.getScene().getSceneUniformBuffer());
  629. }
  630. }
  631. /**
  632. * Binds the view projection matrix to the effect
  633. * @param effect defines the effect to bind the view projection matrix to
  634. */
  635. public bindViewProjection(effect: Effect): void {
  636. if (!this._useUBO) {
  637. effect.setMatrix("viewProjection", this.getScene().getTransformMatrix());
  638. } else {
  639. this.bindSceneUniformBuffer(effect, this.getScene().getSceneUniformBuffer());
  640. }
  641. }
  642. /**
  643. * Specifies if material alpha testing should be turned on for the mesh
  644. * @param mesh defines the mesh to check
  645. */
  646. protected _shouldTurnAlphaTestOn(mesh: AbstractMesh): boolean {
  647. return (!this.needAlphaBlendingForMesh(mesh) && this.needAlphaTesting());
  648. }
  649. /**
  650. * Processes to execute after binding the material to a mesh
  651. * @param mesh defines the rendered mesh
  652. */
  653. protected _afterBind(mesh?: Mesh): void {
  654. this._scene._cachedMaterial = this;
  655. if (mesh) {
  656. this._scene._cachedVisibility = mesh.visibility;
  657. } else {
  658. this._scene._cachedVisibility = 1;
  659. }
  660. if (this._onBindObservable && mesh) {
  661. this._onBindObservable.notifyObservers(mesh);
  662. }
  663. if (this.disableDepthWrite) {
  664. var engine = this._scene.getEngine();
  665. this._cachedDepthWriteState = engine.getDepthWrite();
  666. engine.setDepthWrite(false);
  667. }
  668. }
  669. /**
  670. * Unbinds the material from the mesh
  671. */
  672. public unbind(): void {
  673. if (this._onUnBindObservable) {
  674. this._onUnBindObservable.notifyObservers(this);
  675. }
  676. if (this.disableDepthWrite) {
  677. var engine = this._scene.getEngine();
  678. engine.setDepthWrite(this._cachedDepthWriteState);
  679. }
  680. }
  681. /**
  682. * Gets the active textures from the material
  683. * @returns an array of textures
  684. */
  685. public getActiveTextures(): BaseTexture[] {
  686. return [];
  687. }
  688. /**
  689. * Specifies if the material uses a texture
  690. * @param texture defines the texture to check against the material
  691. * @returns a boolean specifying if the material uses the texture
  692. */
  693. public hasTexture(texture: BaseTexture): boolean {
  694. return false;
  695. }
  696. /**
  697. * Makes a duplicate of the material, and gives it a new name
  698. * @param name defines the new name for the duplicated material
  699. * @returns the cloned material
  700. */
  701. public clone(name: string): Nullable<Material> {
  702. return null;
  703. }
  704. /**
  705. * Gets the meshes bound to the material
  706. * @returns an array of meshes bound to the material
  707. */
  708. public getBindedMeshes(): AbstractMesh[] {
  709. if (this.meshMap) {
  710. var result = new Array<AbstractMesh>();
  711. for (let meshId in this.meshMap) {
  712. const mesh = this.meshMap[meshId];
  713. if (mesh) {
  714. result.push(mesh);
  715. }
  716. }
  717. return result;
  718. }
  719. else {
  720. const meshes = this._scene.meshes;
  721. return meshes.filter((mesh) => mesh.material === this);
  722. }
  723. }
  724. /**
  725. * Force shader compilation
  726. * @param mesh defines the mesh associated with this material
  727. * @param onCompiled defines a function to execute once the material is compiled
  728. * @param options defines the options to configure the compilation
  729. */
  730. public forceCompilation(mesh: AbstractMesh, onCompiled?: (material: Material) => void, options?: Partial<{ clipPlane: boolean }>): void {
  731. let localOptions = {
  732. clipPlane: false,
  733. ...options
  734. };
  735. var subMesh = new BaseSubMesh();
  736. var scene = this.getScene();
  737. var checkReady = () => {
  738. if (!this._scene || !this._scene.getEngine()) {
  739. return;
  740. }
  741. if (subMesh._materialDefines) {
  742. subMesh._materialDefines._renderId = -1;
  743. }
  744. var clipPlaneState = scene.clipPlane;
  745. if (localOptions.clipPlane) {
  746. scene.clipPlane = new Plane(0, 0, 0, 1);
  747. }
  748. if (this._storeEffectOnSubMeshes) {
  749. if (this.isReadyForSubMesh(mesh, subMesh)) {
  750. if (onCompiled) {
  751. onCompiled(this);
  752. }
  753. }
  754. else {
  755. setTimeout(checkReady, 16);
  756. }
  757. } else {
  758. if (this.isReady()) {
  759. if (onCompiled) {
  760. onCompiled(this);
  761. }
  762. }
  763. else {
  764. setTimeout(checkReady, 16);
  765. }
  766. }
  767. if (localOptions.clipPlane) {
  768. scene.clipPlane = clipPlaneState;
  769. }
  770. };
  771. checkReady();
  772. }
  773. /**
  774. * Force shader compilation
  775. * @param mesh defines the mesh that will use this material
  776. * @param options defines additional options for compiling the shaders
  777. * @returns a promise that resolves when the compilation completes
  778. */
  779. public forceCompilationAsync(mesh: AbstractMesh, options?: Partial<{ clipPlane: boolean }>): Promise<void> {
  780. return new Promise((resolve) => {
  781. this.forceCompilation(mesh, () => {
  782. resolve();
  783. }, options);
  784. });
  785. }
  786. private static readonly _ImageProcessingDirtyCallBack = (defines: MaterialDefines) => defines.markAsImageProcessingDirty();
  787. private static readonly _TextureDirtyCallBack = (defines: MaterialDefines) => defines.markAsTexturesDirty();
  788. private static readonly _FresnelDirtyCallBack = (defines: MaterialDefines) => defines.markAsFresnelDirty();
  789. private static readonly _MiscDirtyCallBack = (defines: MaterialDefines) => defines.markAsMiscDirty();
  790. private static readonly _LightsDirtyCallBack = (defines: MaterialDefines) => defines.markAsLightDirty();
  791. private static readonly _AttributeDirtyCallBack = (defines: MaterialDefines) => defines.markAsAttributesDirty();
  792. private static _FresnelAndMiscDirtyCallBack = (defines: MaterialDefines) => {
  793. Material._FresnelDirtyCallBack(defines);
  794. Material._MiscDirtyCallBack(defines);
  795. }
  796. private static _TextureAndMiscDirtyCallBack = (defines: MaterialDefines) => {
  797. Material._TextureDirtyCallBack(defines);
  798. Material._MiscDirtyCallBack(defines);
  799. }
  800. private static readonly _DirtyCallbackArray: Array<(defines: MaterialDefines) => void> = [];
  801. private static readonly _RunDirtyCallBacks = (defines: MaterialDefines) => {
  802. for (const cb of Material._DirtyCallbackArray) {
  803. cb(defines);
  804. }
  805. }
  806. /**
  807. * Marks a define in the material to indicate that it needs to be re-computed
  808. * @param flag defines a flag used to determine which parts of the material have to be marked as dirty
  809. */
  810. public markAsDirty(flag: number): void {
  811. if (this.getScene().blockMaterialDirtyMechanism) {
  812. return;
  813. }
  814. Material._DirtyCallbackArray.length = 0;
  815. if (flag & Material.TextureDirtyFlag) {
  816. Material._DirtyCallbackArray.push(Material._TextureDirtyCallBack);
  817. }
  818. if (flag & Material.LightDirtyFlag) {
  819. Material._DirtyCallbackArray.push(Material._LightsDirtyCallBack);
  820. }
  821. if (flag & Material.FresnelDirtyFlag) {
  822. Material._DirtyCallbackArray.push(Material._FresnelDirtyCallBack);
  823. }
  824. if (flag & Material.AttributesDirtyFlag) {
  825. Material._DirtyCallbackArray.push(Material._AttributeDirtyCallBack);
  826. }
  827. if (flag & Material.MiscDirtyFlag) {
  828. Material._DirtyCallbackArray.push(Material._MiscDirtyCallBack);
  829. }
  830. if (Material._DirtyCallbackArray.length) {
  831. this._markAllSubMeshesAsDirty(Material._RunDirtyCallBacks);
  832. }
  833. this.getScene().resetCachedMaterial();
  834. }
  835. /**
  836. * Marks all submeshes of a material to indicate that their material defines need to be re-calculated
  837. * @param func defines a function which checks material defines against the submeshes
  838. */
  839. protected _markAllSubMeshesAsDirty(func: (defines: MaterialDefines) => void) {
  840. if (this.getScene().blockMaterialDirtyMechanism) {
  841. return;
  842. }
  843. const meshes = this.getScene().meshes;
  844. for (var mesh of meshes) {
  845. if (!mesh.subMeshes) {
  846. continue;
  847. }
  848. for (var subMesh of mesh.subMeshes) {
  849. if (subMesh.getMaterial() !== this) {
  850. continue;
  851. }
  852. if (!subMesh._materialDefines) {
  853. continue;
  854. }
  855. func(subMesh._materialDefines);
  856. }
  857. }
  858. }
  859. /**
  860. * Indicates that image processing needs to be re-calculated for all submeshes
  861. */
  862. protected _markAllSubMeshesAsImageProcessingDirty() {
  863. this._markAllSubMeshesAsDirty(Material._ImageProcessingDirtyCallBack);
  864. }
  865. /**
  866. * Indicates that textures need to be re-calculated for all submeshes
  867. */
  868. protected _markAllSubMeshesAsTexturesDirty() {
  869. this._markAllSubMeshesAsDirty(Material._TextureDirtyCallBack);
  870. }
  871. /**
  872. * Indicates that fresnel needs to be re-calculated for all submeshes
  873. */
  874. protected _markAllSubMeshesAsFresnelDirty() {
  875. this._markAllSubMeshesAsDirty(Material._FresnelDirtyCallBack);
  876. }
  877. /**
  878. * Indicates that fresnel and misc need to be re-calculated for all submeshes
  879. */
  880. protected _markAllSubMeshesAsFresnelAndMiscDirty() {
  881. this._markAllSubMeshesAsDirty(Material._FresnelAndMiscDirtyCallBack);
  882. }
  883. /**
  884. * Indicates that lights need to be re-calculated for all submeshes
  885. */
  886. protected _markAllSubMeshesAsLightsDirty() {
  887. this._markAllSubMeshesAsDirty(Material._LightsDirtyCallBack);
  888. }
  889. /**
  890. * Indicates that attributes need to be re-calculated for all submeshes
  891. */
  892. protected _markAllSubMeshesAsAttributesDirty() {
  893. this._markAllSubMeshesAsDirty(Material._AttributeDirtyCallBack);
  894. }
  895. /**
  896. * Indicates that misc needs to be re-calculated for all submeshes
  897. */
  898. protected _markAllSubMeshesAsMiscDirty() {
  899. this._markAllSubMeshesAsDirty(Material._MiscDirtyCallBack);
  900. }
  901. /**
  902. * Indicates that textures and misc need to be re-calculated for all submeshes
  903. */
  904. protected _markAllSubMeshesAsTexturesAndMiscDirty() {
  905. this._markAllSubMeshesAsDirty(Material._TextureAndMiscDirtyCallBack);
  906. }
  907. /**
  908. * Disposes the material
  909. * @param forceDisposeEffect specifies if effects should be forcefully disposed
  910. * @param forceDisposeTextures specifies if textures should be forcefully disposed
  911. * @param notBoundToMesh specifies if the material that is being disposed is known to be not bound to any mesh
  912. */
  913. public dispose(forceDisposeEffect?: boolean, forceDisposeTextures?: boolean, notBoundToMesh?: boolean): void {
  914. const scene = this.getScene();
  915. // Animations
  916. scene.stopAnimation(this);
  917. scene.freeProcessedMaterials();
  918. // Remove from scene
  919. scene.removeMaterial(this);
  920. if (notBoundToMesh !== true) {
  921. // Remove from meshes
  922. if (this.meshMap) {
  923. for (let meshId in this.meshMap) {
  924. const mesh = this.meshMap[meshId];
  925. if (mesh) {
  926. mesh.material = null; // will set the entry in the map to undefined
  927. this.releaseVertexArrayObject(mesh, forceDisposeEffect);
  928. }
  929. }
  930. }
  931. else {
  932. const meshes = scene.meshes;
  933. for (let mesh of meshes) {
  934. if (mesh.material === this) {
  935. mesh.material = null;
  936. this.releaseVertexArrayObject(mesh, forceDisposeEffect);
  937. }
  938. }
  939. }
  940. }
  941. this._uniformBuffer.dispose();
  942. // Shader are kept in cache for further use but we can get rid of this by using forceDisposeEffect
  943. if (forceDisposeEffect && this._effect) {
  944. if (!this._storeEffectOnSubMeshes) {
  945. scene.getEngine()._releaseEffect(this._effect);
  946. }
  947. this._effect = null;
  948. }
  949. // Callback
  950. this.onDisposeObservable.notifyObservers(this);
  951. this.onDisposeObservable.clear();
  952. if (this._onBindObservable) {
  953. this._onBindObservable.clear();
  954. }
  955. if (this._onUnBindObservable) {
  956. this._onUnBindObservable.clear();
  957. }
  958. }
  959. /** @hidden */
  960. private releaseVertexArrayObject(mesh: AbstractMesh, forceDisposeEffect?: boolean) {
  961. if ((<Mesh>mesh).geometry) {
  962. var geometry = <Geometry>((<Mesh>mesh).geometry);
  963. const scene = this.getScene();
  964. if (this._storeEffectOnSubMeshes) {
  965. for (var subMesh of mesh.subMeshes) {
  966. geometry._releaseVertexArrayObject(subMesh._materialEffect);
  967. if (forceDisposeEffect && subMesh._materialEffect) {
  968. scene.getEngine()._releaseEffect(subMesh._materialEffect);
  969. }
  970. }
  971. } else {
  972. geometry._releaseVertexArrayObject(this._effect);
  973. }
  974. }
  975. }
  976. /**
  977. * Serializes this material
  978. * @returns the serialized material object
  979. */
  980. public serialize(): any {
  981. return SerializationHelper.Serialize(this);
  982. }
  983. /**
  984. * Creates a material from parsed material data
  985. * @param parsedMaterial defines parsed material data
  986. * @param scene defines the hosting scene
  987. * @param rootUrl defines the root URL to use to load textures
  988. * @returns a new material
  989. */
  990. public static Parse(parsedMaterial: any, scene: Scene, rootUrl: string): any {
  991. if (!parsedMaterial.customType) {
  992. parsedMaterial.customType = "BABYLON.StandardMaterial";
  993. }
  994. else if (parsedMaterial.customType === "BABYLON.PBRMaterial" && parsedMaterial.overloadedAlbedo) {
  995. parsedMaterial.customType = "BABYLON.LegacyPBRMaterial";
  996. if (!BABYLON.LegacyPBRMaterial) {
  997. Logger.Error("Your scene is trying to load a legacy version of the PBRMaterial, please, include it from the materials library.");
  998. return;
  999. }
  1000. }
  1001. var materialType = Tools.Instantiate(parsedMaterial.customType);
  1002. return materialType.Parse(parsedMaterial, scene, rootUrl);
  1003. }
  1004. }