material.ts 46 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466
  1. import { serialize, SerializationHelper } from "../Misc/decorators";
  2. import { Tools } from "../Misc/tools";
  3. import { IAnimatable } from '../Animations/animatable.interface';
  4. import { SmartArray } from "../Misc/smartArray";
  5. import { Observer, Observable } from "../Misc/observable";
  6. import { Nullable } from "../types";
  7. import { Scene } from "../scene";
  8. import { Matrix } from "../Maths/math.vector";
  9. import { EngineStore } from "../Engines/engineStore";
  10. import { SubMesh } from "../Meshes/subMesh";
  11. import { Geometry } from "../Meshes/geometry";
  12. import { AbstractMesh } from "../Meshes/abstractMesh";
  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 { MaterialDefines } from "./materialDefines";
  18. import { Constants } from "../Engines/constants";
  19. import { Logger } from "../Misc/logger";
  20. import { IInspectable } from '../Misc/iInspectable';
  21. import { Plane } from '../Maths/math.plane';
  22. import { ShadowDepthWrapper } from './shadowDepthWrapper';
  23. declare type PrePassRenderer = import("../Rendering/prePassRenderer").PrePassRenderer;
  24. declare type Mesh = import("../Meshes/mesh").Mesh;
  25. declare type Animation = import("../Animations/animation").Animation;
  26. declare type InstancedMesh = import('../Meshes/instancedMesh').InstancedMesh;
  27. declare var BABYLON: any;
  28. /**
  29. * Options for compiling materials.
  30. */
  31. export interface IMaterialCompilationOptions {
  32. /**
  33. * Defines whether clip planes are enabled.
  34. */
  35. clipPlane: boolean;
  36. /**
  37. * Defines whether instances are enabled.
  38. */
  39. useInstances: boolean;
  40. }
  41. /**
  42. * Options passed when calling customShaderNameResolve
  43. */
  44. export interface ICustomShaderNameResolveOptions {
  45. /**
  46. * If provided, will be called two times with the vertex and fragment code so that this code can be updated before it is compiled by the GPU
  47. */
  48. processFinalCode?: Nullable<(shaderType: string, code: string) => string>;
  49. }
  50. /**
  51. * Base class for the main features of a material in Babylon.js
  52. */
  53. export class Material implements IAnimatable {
  54. /**
  55. * Returns the triangle fill mode
  56. */
  57. public static readonly TriangleFillMode = Constants.MATERIAL_TriangleFillMode;
  58. /**
  59. * Returns the wireframe mode
  60. */
  61. public static readonly WireFrameFillMode = Constants.MATERIAL_WireFrameFillMode;
  62. /**
  63. * Returns the point fill mode
  64. */
  65. public static readonly PointFillMode = Constants.MATERIAL_PointFillMode;
  66. /**
  67. * Returns the point list draw mode
  68. */
  69. public static readonly PointListDrawMode = Constants.MATERIAL_PointListDrawMode;
  70. /**
  71. * Returns the line list draw mode
  72. */
  73. public static readonly LineListDrawMode = Constants.MATERIAL_LineListDrawMode;
  74. /**
  75. * Returns the line loop draw mode
  76. */
  77. public static readonly LineLoopDrawMode = Constants.MATERIAL_LineLoopDrawMode;
  78. /**
  79. * Returns the line strip draw mode
  80. */
  81. public static readonly LineStripDrawMode = Constants.MATERIAL_LineStripDrawMode;
  82. /**
  83. * Returns the triangle strip draw mode
  84. */
  85. public static readonly TriangleStripDrawMode = Constants.MATERIAL_TriangleStripDrawMode;
  86. /**
  87. * Returns the triangle fan draw mode
  88. */
  89. public static readonly TriangleFanDrawMode = Constants.MATERIAL_TriangleFanDrawMode;
  90. /**
  91. * Stores the clock-wise side orientation
  92. */
  93. public static readonly ClockWiseSideOrientation = Constants.MATERIAL_ClockWiseSideOrientation;
  94. /**
  95. * Stores the counter clock-wise side orientation
  96. */
  97. public static readonly CounterClockWiseSideOrientation = Constants.MATERIAL_CounterClockWiseSideOrientation;
  98. /**
  99. * The dirty texture flag value
  100. */
  101. public static readonly TextureDirtyFlag = Constants.MATERIAL_TextureDirtyFlag;
  102. /**
  103. * The dirty light flag value
  104. */
  105. public static readonly LightDirtyFlag = Constants.MATERIAL_LightDirtyFlag;
  106. /**
  107. * The dirty fresnel flag value
  108. */
  109. public static readonly FresnelDirtyFlag = Constants.MATERIAL_FresnelDirtyFlag;
  110. /**
  111. * The dirty attribute flag value
  112. */
  113. public static readonly AttributesDirtyFlag = Constants.MATERIAL_AttributesDirtyFlag;
  114. /**
  115. * The dirty misc flag value
  116. */
  117. public static readonly MiscDirtyFlag = Constants.MATERIAL_MiscDirtyFlag;
  118. /**
  119. * The dirty prepass flag value
  120. */
  121. public static readonly PrePassDirtyFlag = Constants.MATERIAL_PrePassDirtyFlag;
  122. /**
  123. * The all dirty flag value
  124. */
  125. public static readonly AllDirtyFlag = Constants.MATERIAL_AllDirtyFlag;
  126. /**
  127. * MaterialTransparencyMode: No transparency mode, Alpha channel is not use.
  128. */
  129. public static readonly MATERIAL_OPAQUE = 0;
  130. /**
  131. * MaterialTransparencyMode: Alpha Test mode, pixel are discarded below a certain threshold defined by the alpha cutoff value.
  132. */
  133. public static readonly MATERIAL_ALPHATEST = 1;
  134. /**
  135. * MaterialTransparencyMode: Pixels are blended (according to the alpha mode) with the already drawn pixels in the current frame buffer.
  136. */
  137. public static readonly MATERIAL_ALPHABLEND = 2;
  138. /**
  139. * MaterialTransparencyMode: Pixels are blended (according to the alpha mode) with the already drawn pixels in the current frame buffer.
  140. * They are also discarded below the alpha cutoff threshold to improve performances.
  141. */
  142. public static readonly MATERIAL_ALPHATESTANDBLEND = 3;
  143. /**
  144. * The Whiteout method is used to blend normals.
  145. * Details of the algorithm can be found here: https://blog.selfshadow.com/publications/blending-in-detail/
  146. */
  147. public static readonly MATERIAL_NORMALBLENDMETHOD_WHITEOUT = 0;
  148. /**
  149. * The Reoriented Normal Mapping method is used to blend normals.
  150. * Details of the algorithm can be found here: https://blog.selfshadow.com/publications/blending-in-detail/
  151. */
  152. public static readonly MATERIAL_NORMALBLENDMETHOD_RNM = 1;
  153. /**
  154. * Custom callback helping to override the default shader used in the material.
  155. */
  156. public customShaderNameResolve: (shaderName: string, uniforms: string[], uniformBuffers: string[], samplers: string[], defines: MaterialDefines | string[], attributes?: string[], options?: ICustomShaderNameResolveOptions) => string;
  157. /**
  158. * Custom shadow depth material to use for shadow rendering instead of the in-built one
  159. */
  160. public shadowDepthWrapper: Nullable<ShadowDepthWrapper> = null;
  161. /**
  162. * Gets or sets a boolean indicating that the material is allowed (if supported) to do shader hot swapping.
  163. * This means that the material can keep using a previous shader while a new one is being compiled.
  164. * This is mostly used when shader parallel compilation is supported (true by default)
  165. */
  166. public allowShaderHotSwapping = true;
  167. /**
  168. * The ID of the material
  169. */
  170. @serialize()
  171. public id: string;
  172. /**
  173. * Gets or sets the unique id of the material
  174. */
  175. @serialize()
  176. public uniqueId: number;
  177. /**
  178. * The name of the material
  179. */
  180. @serialize()
  181. public name: string;
  182. /**
  183. * Gets or sets user defined metadata
  184. */
  185. public metadata: any = null;
  186. /**
  187. * For internal use only. Please do not use.
  188. */
  189. public reservedDataStore: any = null;
  190. /**
  191. * Specifies if the ready state should be checked on each call
  192. */
  193. @serialize()
  194. public checkReadyOnEveryCall = false;
  195. /**
  196. * Specifies if the ready state should be checked once
  197. */
  198. @serialize()
  199. public checkReadyOnlyOnce = false;
  200. /**
  201. * The state of the material
  202. */
  203. @serialize()
  204. public state = "";
  205. /**
  206. * If the material can be rendered to several textures with MRT extension
  207. */
  208. public get canRenderToMRT() : boolean {
  209. // By default, shaders are not compatible with MRTs
  210. // Base classes should override that if their shader supports MRT
  211. return false;
  212. }
  213. /**
  214. * The alpha value of the material
  215. */
  216. @serialize("alpha")
  217. protected _alpha = 1.0;
  218. /**
  219. * List of inspectable custom properties (used by the Inspector)
  220. * @see https://doc.babylonjs.com/how_to/debug_layer#extensibility
  221. */
  222. public inspectableCustomProperties: IInspectable[];
  223. /**
  224. * Sets the alpha value of the material
  225. */
  226. public set alpha(value: number) {
  227. if (this._alpha === value) {
  228. return;
  229. }
  230. this._alpha = value;
  231. this.markAsDirty(Material.MiscDirtyFlag);
  232. }
  233. /**
  234. * Gets the alpha value of the material
  235. */
  236. public get alpha(): number {
  237. return this._alpha;
  238. }
  239. /**
  240. * Specifies if back face culling is enabled
  241. */
  242. @serialize("backFaceCulling")
  243. protected _backFaceCulling = true;
  244. /**
  245. * Sets the back-face culling state
  246. */
  247. public set backFaceCulling(value: boolean) {
  248. if (this._backFaceCulling === value) {
  249. return;
  250. }
  251. this._backFaceCulling = value;
  252. this.markAsDirty(Material.TextureDirtyFlag);
  253. }
  254. /**
  255. * Gets the back-face culling state
  256. */
  257. public get backFaceCulling(): boolean {
  258. return this._backFaceCulling;
  259. }
  260. /**
  261. * Stores the value for side orientation
  262. */
  263. @serialize()
  264. public sideOrientation: number;
  265. /**
  266. * Callback triggered when the material is compiled
  267. */
  268. public onCompiled: Nullable<(effect: Effect) => void> = null;
  269. /**
  270. * Callback triggered when an error occurs
  271. */
  272. public onError: Nullable<(effect: Effect, errors: string) => void> = null;
  273. /**
  274. * Callback triggered to get the render target textures
  275. */
  276. public getRenderTargetTextures: Nullable<() => SmartArray<RenderTargetTexture>> = null;
  277. /**
  278. * Gets a boolean indicating that current material needs to register RTT
  279. */
  280. public get hasRenderTargetTextures(): boolean {
  281. return false;
  282. }
  283. /**
  284. * Specifies if the material should be serialized
  285. */
  286. public doNotSerialize = false;
  287. /**
  288. * @hidden
  289. */
  290. public _storeEffectOnSubMeshes = false;
  291. /**
  292. * Stores the animations for the material
  293. */
  294. public animations: Nullable<Array<Animation>> = null;
  295. /**
  296. * An event triggered when the material is disposed
  297. */
  298. public onDisposeObservable = new Observable<Material>();
  299. /**
  300. * An observer which watches for dispose events
  301. */
  302. private _onDisposeObserver: Nullable<Observer<Material>> = null;
  303. private _onUnBindObservable: Nullable<Observable<Material>> = null;
  304. /**
  305. * Called during a dispose event
  306. */
  307. public set onDispose(callback: () => void) {
  308. if (this._onDisposeObserver) {
  309. this.onDisposeObservable.remove(this._onDisposeObserver);
  310. }
  311. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  312. }
  313. private _onBindObservable: Nullable<Observable<AbstractMesh>>;
  314. /**
  315. * An event triggered when the material is bound
  316. */
  317. public get onBindObservable(): Observable<AbstractMesh> {
  318. if (!this._onBindObservable) {
  319. this._onBindObservable = new Observable<AbstractMesh>();
  320. }
  321. return this._onBindObservable;
  322. }
  323. /**
  324. * An observer which watches for bind events
  325. */
  326. private _onBindObserver: Nullable<Observer<AbstractMesh>> = null;
  327. /**
  328. * Called during a bind event
  329. */
  330. public set onBind(callback: (Mesh: AbstractMesh) => void) {
  331. if (this._onBindObserver) {
  332. this.onBindObservable.remove(this._onBindObserver);
  333. }
  334. this._onBindObserver = this.onBindObservable.add(callback);
  335. }
  336. /**
  337. * An event triggered when the material is unbound
  338. */
  339. public get onUnBindObservable(): Observable<Material> {
  340. if (!this._onUnBindObservable) {
  341. this._onUnBindObservable = new Observable<Material>();
  342. }
  343. return this._onUnBindObservable;
  344. }
  345. protected _onEffectCreatedObservable: Nullable<Observable<{ effect: Effect, subMesh: Nullable<SubMesh>}>>;
  346. /**
  347. * An event triggered when the effect is (re)created
  348. */
  349. public get onEffectCreatedObservable(): Observable<{ effect: Effect, subMesh: Nullable<SubMesh>}> {
  350. if (!this._onEffectCreatedObservable) {
  351. this._onEffectCreatedObservable = new Observable<{effect: Effect, subMesh: Nullable<SubMesh>}>();
  352. }
  353. return this._onEffectCreatedObservable;
  354. }
  355. /**
  356. * Stores the value of the alpha mode
  357. */
  358. @serialize("alphaMode")
  359. private _alphaMode: number = Constants.ALPHA_COMBINE;
  360. /**
  361. * Sets the value of the alpha mode.
  362. *
  363. * | Value | Type | Description |
  364. * | --- | --- | --- |
  365. * | 0 | ALPHA_DISABLE | |
  366. * | 1 | ALPHA_ADD | |
  367. * | 2 | ALPHA_COMBINE | |
  368. * | 3 | ALPHA_SUBTRACT | |
  369. * | 4 | ALPHA_MULTIPLY | |
  370. * | 5 | ALPHA_MAXIMIZED | |
  371. * | 6 | ALPHA_ONEONE | |
  372. * | 7 | ALPHA_PREMULTIPLIED | |
  373. * | 8 | ALPHA_PREMULTIPLIED_PORTERDUFF | |
  374. * | 9 | ALPHA_INTERPOLATE | |
  375. * | 10 | ALPHA_SCREENMODE | |
  376. *
  377. */
  378. public set alphaMode(value: number) {
  379. if (this._alphaMode === value) {
  380. return;
  381. }
  382. this._alphaMode = value;
  383. this.markAsDirty(Material.TextureDirtyFlag);
  384. }
  385. /**
  386. * Gets the value of the alpha mode
  387. */
  388. public get alphaMode(): number {
  389. return this._alphaMode;
  390. }
  391. /**
  392. * Stores the state of the need depth pre-pass value
  393. */
  394. @serialize()
  395. private _needDepthPrePass = false;
  396. /**
  397. * Sets the need depth pre-pass value
  398. */
  399. public set needDepthPrePass(value: boolean) {
  400. if (this._needDepthPrePass === value) {
  401. return;
  402. }
  403. this._needDepthPrePass = value;
  404. if (this._needDepthPrePass) {
  405. this.checkReadyOnEveryCall = true;
  406. }
  407. }
  408. /**
  409. * Gets the depth pre-pass value
  410. */
  411. public get needDepthPrePass(): boolean {
  412. return this._needDepthPrePass;
  413. }
  414. /**
  415. * Specifies if depth writing should be disabled
  416. */
  417. @serialize()
  418. public disableDepthWrite = false;
  419. /**
  420. * Specifies if color writing should be disabled
  421. */
  422. @serialize()
  423. public disableColorWrite = false;
  424. /**
  425. * Specifies if depth writing should be forced
  426. */
  427. @serialize()
  428. public forceDepthWrite = false;
  429. /**
  430. * Specifies the depth function that should be used. 0 means the default engine function
  431. */
  432. @serialize()
  433. public depthFunction = 0;
  434. /**
  435. * Specifies if there should be a separate pass for culling
  436. */
  437. @serialize()
  438. public separateCullingPass = false;
  439. /**
  440. * Stores the state specifing if fog should be enabled
  441. */
  442. @serialize("fogEnabled")
  443. private _fogEnabled = true;
  444. /**
  445. * Sets the state for enabling fog
  446. */
  447. public set fogEnabled(value: boolean) {
  448. if (this._fogEnabled === value) {
  449. return;
  450. }
  451. this._fogEnabled = value;
  452. this.markAsDirty(Material.MiscDirtyFlag);
  453. }
  454. /**
  455. * Gets the value of the fog enabled state
  456. */
  457. public get fogEnabled(): boolean {
  458. return this._fogEnabled;
  459. }
  460. /**
  461. * Stores the size of points
  462. */
  463. @serialize()
  464. public pointSize = 1.0;
  465. /**
  466. * Stores the z offset value
  467. */
  468. @serialize()
  469. public zOffset = 0;
  470. public get wireframe(): boolean {
  471. switch (this._fillMode) {
  472. case Material.WireFrameFillMode:
  473. case Material.LineListDrawMode:
  474. case Material.LineLoopDrawMode:
  475. case Material.LineStripDrawMode:
  476. return true;
  477. }
  478. return this._scene.forceWireframe;
  479. }
  480. /**
  481. * Sets the state of wireframe mode
  482. */
  483. public set wireframe(value: boolean) {
  484. this.fillMode = (value ? Material.WireFrameFillMode : Material.TriangleFillMode);
  485. }
  486. /**
  487. * Gets the value specifying if point clouds are enabled
  488. */
  489. @serialize()
  490. public get pointsCloud(): boolean {
  491. switch (this._fillMode) {
  492. case Material.PointFillMode:
  493. case Material.PointListDrawMode:
  494. return true;
  495. }
  496. return this._scene.forcePointsCloud;
  497. }
  498. /**
  499. * Sets the state of point cloud mode
  500. */
  501. public set pointsCloud(value: boolean) {
  502. this.fillMode = (value ? Material.PointFillMode : Material.TriangleFillMode);
  503. }
  504. /**
  505. * Gets the material fill mode
  506. */
  507. @serialize()
  508. public get fillMode(): number {
  509. return this._fillMode;
  510. }
  511. /**
  512. * Sets the material fill mode
  513. */
  514. public set fillMode(value: number) {
  515. if (this._fillMode === value) {
  516. return;
  517. }
  518. this._fillMode = value;
  519. this.markAsDirty(Material.MiscDirtyFlag);
  520. }
  521. /**
  522. * @hidden
  523. * Stores the effects for the material
  524. */
  525. public _effect: Nullable<Effect> = null;
  526. /**
  527. * Specifies if uniform buffers should be used
  528. */
  529. private _useUBO: boolean = false;
  530. /**
  531. * Stores a reference to the scene
  532. */
  533. private _scene: Scene;
  534. /**
  535. * Stores the fill mode state
  536. */
  537. private _fillMode = Material.TriangleFillMode;
  538. /**
  539. * Specifies if the depth write state should be cached
  540. */
  541. private _cachedDepthWriteState: boolean = false;
  542. /**
  543. * Specifies if the color write state should be cached
  544. */
  545. private _cachedColorWriteState: boolean = false;
  546. /**
  547. * Specifies if the depth function state should be cached
  548. */
  549. private _cachedDepthFunctionState: number = 0;
  550. /**
  551. * Stores the uniform buffer
  552. */
  553. protected _uniformBuffer: UniformBuffer;
  554. /** @hidden */
  555. public _indexInSceneMaterialArray = -1;
  556. /** @hidden */
  557. public meshMap: Nullable<{ [id: string]: AbstractMesh | undefined }> = null;
  558. /**
  559. * Creates a material instance
  560. * @param name defines the name of the material
  561. * @param scene defines the scene to reference
  562. * @param doNotAdd specifies if the material should be added to the scene
  563. */
  564. constructor(name: string, scene: Scene, doNotAdd?: boolean) {
  565. this.name = name;
  566. let idSubscript = 1;
  567. this._scene = scene || EngineStore.LastCreatedScene;
  568. this.id = name || Tools.RandomId();
  569. while (this._scene.getMaterialByID(this.id)) {
  570. this.id = name + " " + idSubscript++;
  571. }
  572. this.uniqueId = this._scene.getUniqueId();
  573. if (this._scene.useRightHandedSystem) {
  574. this.sideOrientation = Material.ClockWiseSideOrientation;
  575. } else {
  576. this.sideOrientation = Material.CounterClockWiseSideOrientation;
  577. }
  578. this._uniformBuffer = new UniformBuffer(this._scene.getEngine());
  579. this._useUBO = this.getScene().getEngine().supportsUniformBuffers;
  580. if (!doNotAdd) {
  581. this._scene.addMaterial(this);
  582. }
  583. if (this._scene.useMaterialMeshMap) {
  584. this.meshMap = {};
  585. }
  586. }
  587. /**
  588. * Returns a string representation of the current material
  589. * @param fullDetails defines a boolean indicating which levels of logging is desired
  590. * @returns a string with material information
  591. */
  592. public toString(fullDetails?: boolean): string {
  593. var ret = "Name: " + this.name;
  594. if (fullDetails) {
  595. }
  596. return ret;
  597. }
  598. /**
  599. * Gets the class name of the material
  600. * @returns a string with the class name of the material
  601. */
  602. public getClassName(): string {
  603. return "Material";
  604. }
  605. /**
  606. * Specifies if updates for the material been locked
  607. */
  608. public get isFrozen(): boolean {
  609. return this.checkReadyOnlyOnce;
  610. }
  611. /**
  612. * Locks updates for the material
  613. */
  614. public freeze(): void {
  615. this.markDirty();
  616. this.checkReadyOnlyOnce = true;
  617. }
  618. /**
  619. * Unlocks updates for the material
  620. */
  621. public unfreeze(): void {
  622. this.markDirty();
  623. this.checkReadyOnlyOnce = false;
  624. }
  625. /**
  626. * Specifies if the material is ready to be used
  627. * @param mesh defines the mesh to check
  628. * @param useInstances specifies if instances should be used
  629. * @returns a boolean indicating if the material is ready to be used
  630. */
  631. public isReady(mesh?: AbstractMesh, useInstances?: boolean): boolean {
  632. return true;
  633. }
  634. /**
  635. * Specifies that the submesh is ready to be used
  636. * @param mesh defines the mesh to check
  637. * @param subMesh defines which submesh to check
  638. * @param useInstances specifies that instances should be used
  639. * @returns a boolean indicating that the submesh is ready or not
  640. */
  641. public isReadyForSubMesh(mesh: AbstractMesh, subMesh: SubMesh, useInstances?: boolean): boolean {
  642. return false;
  643. }
  644. /**
  645. * Returns the material effect
  646. * @returns the effect associated with the material
  647. */
  648. public getEffect(): Nullable<Effect> {
  649. return this._effect;
  650. }
  651. /**
  652. * Returns the current scene
  653. * @returns a Scene
  654. */
  655. public getScene(): Scene {
  656. return this._scene;
  657. }
  658. /**
  659. * Enforces alpha test in opaque or blend mode in order to improve the performances of some situations.
  660. */
  661. protected _forceAlphaTest = false;
  662. /**
  663. * The transparency mode of the material.
  664. */
  665. protected _transparencyMode: Nullable<number> = null;
  666. /**
  667. * Gets the current transparency mode.
  668. */
  669. @serialize()
  670. public get transparencyMode(): Nullable<number> {
  671. return this._transparencyMode;
  672. }
  673. /**
  674. * Sets the transparency mode of the material.
  675. *
  676. * | Value | Type | Description |
  677. * | ----- | ----------------------------------- | ----------- |
  678. * | 0 | OPAQUE | |
  679. * | 1 | ALPHATEST | |
  680. * | 2 | ALPHABLEND | |
  681. * | 3 | ALPHATESTANDBLEND | |
  682. *
  683. */
  684. public set transparencyMode(value: Nullable<number>) {
  685. if (this._transparencyMode === value) {
  686. return;
  687. }
  688. this._transparencyMode = value;
  689. this._forceAlphaTest = (value === Material.MATERIAL_ALPHATESTANDBLEND);
  690. this._markAllSubMeshesAsTexturesAndMiscDirty();
  691. }
  692. /**
  693. * Returns true if alpha blending should be disabled.
  694. */
  695. protected get _disableAlphaBlending(): boolean {
  696. return (this._transparencyMode === Material.MATERIAL_OPAQUE ||
  697. this._transparencyMode === Material.MATERIAL_ALPHATEST);
  698. }
  699. /**
  700. * Specifies whether or not this material should be rendered in alpha blend mode.
  701. * @returns a boolean specifying if alpha blending is needed
  702. */
  703. public needAlphaBlending(): boolean {
  704. if (this._disableAlphaBlending) {
  705. return false;
  706. }
  707. return (this.alpha < 1.0);
  708. }
  709. /**
  710. * Specifies if the mesh will require alpha blending
  711. * @param mesh defines the mesh to check
  712. * @returns a boolean specifying if alpha blending is needed for the mesh
  713. */
  714. public needAlphaBlendingForMesh(mesh: AbstractMesh): boolean {
  715. if (this._disableAlphaBlending && mesh.visibility >= 1.0) {
  716. return false;
  717. }
  718. return this.needAlphaBlending() || (mesh.visibility < 1.0) || mesh.hasVertexAlpha;
  719. }
  720. /**
  721. * Specifies whether or not this material should be rendered in alpha test mode.
  722. * @returns a boolean specifying if an alpha test is needed.
  723. */
  724. public needAlphaTesting(): boolean {
  725. if (this._forceAlphaTest) {
  726. return true;
  727. }
  728. return false;
  729. }
  730. /**
  731. * Specifies if material alpha testing should be turned on for the mesh
  732. * @param mesh defines the mesh to check
  733. */
  734. protected _shouldTurnAlphaTestOn(mesh: AbstractMesh): boolean {
  735. return (!this.needAlphaBlendingForMesh(mesh) && this.needAlphaTesting());
  736. }
  737. /**
  738. * Gets the texture used for the alpha test
  739. * @returns the texture to use for alpha testing
  740. */
  741. public getAlphaTestTexture(): Nullable<BaseTexture> {
  742. return null;
  743. }
  744. /**
  745. * Marks the material to indicate that it needs to be re-calculated
  746. */
  747. public markDirty(): void {
  748. const meshes = this.getScene().meshes;
  749. for (var mesh of meshes) {
  750. if (!mesh.subMeshes) {
  751. continue;
  752. }
  753. for (var subMesh of mesh.subMeshes) {
  754. if (subMesh.getMaterial() !== this) {
  755. continue;
  756. }
  757. if (!subMesh.effect) {
  758. continue;
  759. }
  760. subMesh.effect._wasPreviouslyReady = false;
  761. }
  762. }
  763. }
  764. /** @hidden */
  765. public _preBind(effect?: Effect, overrideOrientation: Nullable<number> = null): boolean {
  766. var engine = this._scene.getEngine();
  767. var orientation = (overrideOrientation == null) ? this.sideOrientation : overrideOrientation;
  768. var reverse = orientation === Material.ClockWiseSideOrientation;
  769. engine.enableEffect(effect ? effect : this._effect);
  770. engine.setState(this.backFaceCulling, this.zOffset, false, reverse);
  771. return reverse;
  772. }
  773. /**
  774. * Binds the material to the mesh
  775. * @param world defines the world transformation matrix
  776. * @param mesh defines the mesh to bind the material to
  777. */
  778. public bind(world: Matrix, mesh?: Mesh): void {
  779. }
  780. /**
  781. * Binds the submesh to the material
  782. * @param world defines the world transformation matrix
  783. * @param mesh defines the mesh containing the submesh
  784. * @param subMesh defines the submesh to bind the material to
  785. */
  786. public bindForSubMesh(world: Matrix, mesh: Mesh, subMesh: SubMesh): void {
  787. }
  788. /**
  789. * Binds the world matrix to the material
  790. * @param world defines the world transformation matrix
  791. */
  792. public bindOnlyWorldMatrix(world: Matrix): void {
  793. }
  794. /**
  795. * Binds the scene's uniform buffer to the effect.
  796. * @param effect defines the effect to bind to the scene uniform buffer
  797. * @param sceneUbo defines the uniform buffer storing scene data
  798. */
  799. public bindSceneUniformBuffer(effect: Effect, sceneUbo: UniformBuffer): void {
  800. sceneUbo.bindToEffect(effect, "Scene");
  801. }
  802. /**
  803. * Binds the view matrix to the effect
  804. * @param effect defines the effect to bind the view matrix to
  805. */
  806. public bindView(effect: Effect): void {
  807. if (!this._useUBO) {
  808. effect.setMatrix("view", this.getScene().getViewMatrix());
  809. } else {
  810. this.bindSceneUniformBuffer(effect, this.getScene().getSceneUniformBuffer());
  811. }
  812. }
  813. /**
  814. * Binds the view projection matrix to the effect
  815. * @param effect defines the effect to bind the view projection matrix to
  816. */
  817. public bindViewProjection(effect: Effect): void {
  818. if (!this._useUBO) {
  819. effect.setMatrix("viewProjection", this.getScene().getTransformMatrix());
  820. } else {
  821. this.bindSceneUniformBuffer(effect, this.getScene().getSceneUniformBuffer());
  822. }
  823. }
  824. /**
  825. * Processes to execute after binding the material to a mesh
  826. * @param mesh defines the rendered mesh
  827. */
  828. protected _afterBind(mesh?: Mesh): void {
  829. this._scene._cachedMaterial = this;
  830. if (mesh) {
  831. this._scene._cachedVisibility = mesh.visibility;
  832. } else {
  833. this._scene._cachedVisibility = 1;
  834. }
  835. if (this._onBindObservable && mesh) {
  836. this._onBindObservable.notifyObservers(mesh);
  837. }
  838. if (this.disableDepthWrite) {
  839. var engine = this._scene.getEngine();
  840. this._cachedDepthWriteState = engine.getDepthWrite();
  841. engine.setDepthWrite(false);
  842. }
  843. if (this.disableColorWrite) {
  844. var engine = this._scene.getEngine();
  845. this._cachedColorWriteState = engine.getColorWrite();
  846. engine.setColorWrite(false);
  847. }
  848. if (this.depthFunction !== 0) {
  849. var engine = this._scene.getEngine();
  850. this._cachedDepthFunctionState = engine.getDepthFunction() || 0;
  851. engine.setDepthFunction(this.depthFunction);
  852. }
  853. }
  854. /**
  855. * Unbinds the material from the mesh
  856. */
  857. public unbind(): void {
  858. if (this._onUnBindObservable) {
  859. this._onUnBindObservable.notifyObservers(this);
  860. }
  861. if (this.depthFunction !== 0) {
  862. var engine = this._scene.getEngine();
  863. engine.setDepthFunction(this._cachedDepthFunctionState);
  864. }
  865. if (this.disableDepthWrite) {
  866. var engine = this._scene.getEngine();
  867. engine.setDepthWrite(this._cachedDepthWriteState);
  868. }
  869. if (this.disableColorWrite) {
  870. var engine = this._scene.getEngine();
  871. engine.setColorWrite(this._cachedColorWriteState);
  872. }
  873. }
  874. /**
  875. * Gets the active textures from the material
  876. * @returns an array of textures
  877. */
  878. public getActiveTextures(): BaseTexture[] {
  879. return [];
  880. }
  881. /**
  882. * Specifies if the material uses a texture
  883. * @param texture defines the texture to check against the material
  884. * @returns a boolean specifying if the material uses the texture
  885. */
  886. public hasTexture(texture: BaseTexture): boolean {
  887. return false;
  888. }
  889. /**
  890. * Makes a duplicate of the material, and gives it a new name
  891. * @param name defines the new name for the duplicated material
  892. * @returns the cloned material
  893. */
  894. public clone(name: string): Nullable<Material> {
  895. return null;
  896. }
  897. /**
  898. * Gets the meshes bound to the material
  899. * @returns an array of meshes bound to the material
  900. */
  901. public getBindedMeshes(): AbstractMesh[] {
  902. if (this.meshMap) {
  903. var result = new Array<AbstractMesh>();
  904. for (let meshId in this.meshMap) {
  905. const mesh = this.meshMap[meshId];
  906. if (mesh) {
  907. result.push(mesh);
  908. }
  909. }
  910. return result;
  911. }
  912. else {
  913. const meshes = this._scene.meshes;
  914. return meshes.filter((mesh) => mesh.material === this);
  915. }
  916. }
  917. /**
  918. * Force shader compilation
  919. * @param mesh defines the mesh associated with this material
  920. * @param onCompiled defines a function to execute once the material is compiled
  921. * @param options defines the options to configure the compilation
  922. * @param onError defines a function to execute if the material fails compiling
  923. */
  924. public forceCompilation(mesh: AbstractMesh, onCompiled?: (material: Material) => void, options?: Partial<IMaterialCompilationOptions>, onError?: (reason: string) => void): void {
  925. let localOptions = {
  926. clipPlane: false,
  927. useInstances: false,
  928. ...options
  929. };
  930. var scene = this.getScene();
  931. let currentHotSwapingState = this.allowShaderHotSwapping;
  932. this.allowShaderHotSwapping = false; // Turned off to let us evaluate the real compilation state
  933. var checkReady = () => {
  934. if (!this._scene || !this._scene.getEngine()) {
  935. return;
  936. }
  937. var clipPlaneState = scene.clipPlane;
  938. if (localOptions.clipPlane) {
  939. scene.clipPlane = new Plane(0, 0, 0, 1);
  940. }
  941. if (this._storeEffectOnSubMeshes) {
  942. var allDone = true, lastError = null;
  943. if (mesh.subMeshes) {
  944. let tempSubMesh = new SubMesh(0, 0, 0, 0, 0, mesh, undefined, false, false);
  945. if (tempSubMesh._materialDefines) {
  946. tempSubMesh._materialDefines._renderId = -1;
  947. }
  948. if (!this.isReadyForSubMesh(mesh, tempSubMesh, localOptions.useInstances)) {
  949. if (tempSubMesh.effect && tempSubMesh.effect.getCompilationError() && tempSubMesh.effect.allFallbacksProcessed()) {
  950. lastError = tempSubMesh.effect.getCompilationError();
  951. } else {
  952. allDone = false;
  953. setTimeout(checkReady, 16);
  954. }
  955. }
  956. }
  957. if (allDone) {
  958. this.allowShaderHotSwapping = currentHotSwapingState;
  959. if (lastError) {
  960. if (onError) {
  961. onError(lastError);
  962. }
  963. }
  964. if (onCompiled) {
  965. onCompiled(this);
  966. }
  967. }
  968. } else {
  969. if (this.isReady()) {
  970. this.allowShaderHotSwapping = currentHotSwapingState;
  971. if (onCompiled) {
  972. onCompiled(this);
  973. }
  974. }
  975. else {
  976. setTimeout(checkReady, 16);
  977. }
  978. }
  979. if (localOptions.clipPlane) {
  980. scene.clipPlane = clipPlaneState;
  981. }
  982. };
  983. checkReady();
  984. }
  985. /**
  986. * Force shader compilation
  987. * @param mesh defines the mesh that will use this material
  988. * @param options defines additional options for compiling the shaders
  989. * @returns a promise that resolves when the compilation completes
  990. */
  991. public forceCompilationAsync(mesh: AbstractMesh, options?: Partial<IMaterialCompilationOptions>): Promise<void> {
  992. return new Promise((resolve, reject) => {
  993. this.forceCompilation(mesh, () => {
  994. resolve();
  995. }, options, (reason) => {
  996. reject(reason);
  997. });
  998. });
  999. }
  1000. private static readonly _AllDirtyCallBack = (defines: MaterialDefines) => defines.markAllAsDirty();
  1001. private static readonly _ImageProcessingDirtyCallBack = (defines: MaterialDefines) => defines.markAsImageProcessingDirty();
  1002. private static readonly _TextureDirtyCallBack = (defines: MaterialDefines) => defines.markAsTexturesDirty();
  1003. private static readonly _FresnelDirtyCallBack = (defines: MaterialDefines) => defines.markAsFresnelDirty();
  1004. private static readonly _MiscDirtyCallBack = (defines: MaterialDefines) => defines.markAsMiscDirty();
  1005. private static readonly _PrePassDirtyCallBack = (defines: MaterialDefines) => defines.markAsPrePassDirty();
  1006. private static readonly _LightsDirtyCallBack = (defines: MaterialDefines) => defines.markAsLightDirty();
  1007. private static readonly _AttributeDirtyCallBack = (defines: MaterialDefines) => defines.markAsAttributesDirty();
  1008. private static _FresnelAndMiscDirtyCallBack = (defines: MaterialDefines) => {
  1009. Material._FresnelDirtyCallBack(defines);
  1010. Material._MiscDirtyCallBack(defines);
  1011. }
  1012. private static _TextureAndMiscDirtyCallBack = (defines: MaterialDefines) => {
  1013. Material._TextureDirtyCallBack(defines);
  1014. Material._MiscDirtyCallBack(defines);
  1015. }
  1016. private static readonly _DirtyCallbackArray: Array<(defines: MaterialDefines) => void> = [];
  1017. private static readonly _RunDirtyCallBacks = (defines: MaterialDefines) => {
  1018. for (const cb of Material._DirtyCallbackArray) {
  1019. cb(defines);
  1020. }
  1021. }
  1022. /**
  1023. * Marks a define in the material to indicate that it needs to be re-computed
  1024. * @param flag defines a flag used to determine which parts of the material have to be marked as dirty
  1025. */
  1026. public markAsDirty(flag: number): void {
  1027. if (this.getScene().blockMaterialDirtyMechanism) {
  1028. return;
  1029. }
  1030. Material._DirtyCallbackArray.length = 0;
  1031. if (flag & Material.TextureDirtyFlag) {
  1032. Material._DirtyCallbackArray.push(Material._TextureDirtyCallBack);
  1033. }
  1034. if (flag & Material.LightDirtyFlag) {
  1035. Material._DirtyCallbackArray.push(Material._LightsDirtyCallBack);
  1036. }
  1037. if (flag & Material.FresnelDirtyFlag) {
  1038. Material._DirtyCallbackArray.push(Material._FresnelDirtyCallBack);
  1039. }
  1040. if (flag & Material.AttributesDirtyFlag) {
  1041. Material._DirtyCallbackArray.push(Material._AttributeDirtyCallBack);
  1042. }
  1043. if (flag & Material.MiscDirtyFlag) {
  1044. Material._DirtyCallbackArray.push(Material._MiscDirtyCallBack);
  1045. }
  1046. if (flag & Material.PrePassDirtyFlag) {
  1047. Material._DirtyCallbackArray.push(Material._PrePassDirtyCallBack);
  1048. }
  1049. if (Material._DirtyCallbackArray.length) {
  1050. this._markAllSubMeshesAsDirty(Material._RunDirtyCallBacks);
  1051. }
  1052. this.getScene().resetCachedMaterial();
  1053. }
  1054. /**
  1055. * Marks all submeshes of a material to indicate that their material defines need to be re-calculated
  1056. * @param func defines a function which checks material defines against the submeshes
  1057. */
  1058. protected _markAllSubMeshesAsDirty(func: (defines: MaterialDefines) => void) {
  1059. if (this.getScene().blockMaterialDirtyMechanism) {
  1060. return;
  1061. }
  1062. const meshes = this.getScene().meshes;
  1063. for (var mesh of meshes) {
  1064. if (!mesh.subMeshes) {
  1065. continue;
  1066. }
  1067. for (var subMesh of mesh.subMeshes) {
  1068. if (subMesh.getMaterial() !== this) {
  1069. continue;
  1070. }
  1071. if (!subMesh._materialDefines) {
  1072. continue;
  1073. }
  1074. func(subMesh._materialDefines);
  1075. }
  1076. }
  1077. }
  1078. /**
  1079. * Indicates that the scene should check if the rendering now needs a prepass
  1080. */
  1081. protected _markScenePrePassDirty() {
  1082. if (this.getScene().blockMaterialDirtyMechanism) {
  1083. return;
  1084. }
  1085. const prePassRenderer = this.getScene().enablePrePassRenderer();
  1086. if (prePassRenderer) {
  1087. prePassRenderer.markAsDirty();
  1088. }
  1089. }
  1090. /**
  1091. * Indicates that we need to re-calculated for all submeshes
  1092. */
  1093. protected _markAllSubMeshesAsAllDirty() {
  1094. this._markAllSubMeshesAsDirty(Material._AllDirtyCallBack);
  1095. }
  1096. /**
  1097. * Indicates that image processing needs to be re-calculated for all submeshes
  1098. */
  1099. protected _markAllSubMeshesAsImageProcessingDirty() {
  1100. this._markAllSubMeshesAsDirty(Material._ImageProcessingDirtyCallBack);
  1101. }
  1102. /**
  1103. * Indicates that textures need to be re-calculated for all submeshes
  1104. */
  1105. protected _markAllSubMeshesAsTexturesDirty() {
  1106. this._markAllSubMeshesAsDirty(Material._TextureDirtyCallBack);
  1107. }
  1108. /**
  1109. * Indicates that fresnel needs to be re-calculated for all submeshes
  1110. */
  1111. protected _markAllSubMeshesAsFresnelDirty() {
  1112. this._markAllSubMeshesAsDirty(Material._FresnelDirtyCallBack);
  1113. }
  1114. /**
  1115. * Indicates that fresnel and misc need to be re-calculated for all submeshes
  1116. */
  1117. protected _markAllSubMeshesAsFresnelAndMiscDirty() {
  1118. this._markAllSubMeshesAsDirty(Material._FresnelAndMiscDirtyCallBack);
  1119. }
  1120. /**
  1121. * Indicates that lights need to be re-calculated for all submeshes
  1122. */
  1123. protected _markAllSubMeshesAsLightsDirty() {
  1124. this._markAllSubMeshesAsDirty(Material._LightsDirtyCallBack);
  1125. }
  1126. /**
  1127. * Indicates that attributes need to be re-calculated for all submeshes
  1128. */
  1129. protected _markAllSubMeshesAsAttributesDirty() {
  1130. this._markAllSubMeshesAsDirty(Material._AttributeDirtyCallBack);
  1131. }
  1132. /**
  1133. * Indicates that misc needs to be re-calculated for all submeshes
  1134. */
  1135. protected _markAllSubMeshesAsMiscDirty() {
  1136. this._markAllSubMeshesAsDirty(Material._MiscDirtyCallBack);
  1137. }
  1138. /**
  1139. * Indicates that prepass needs to be re-calculated for all submeshes
  1140. */
  1141. protected _markAllSubMeshesAsPrePassDirty() {
  1142. this._markAllSubMeshesAsDirty(Material._MiscDirtyCallBack);
  1143. }
  1144. /**
  1145. * Indicates that textures and misc need to be re-calculated for all submeshes
  1146. */
  1147. protected _markAllSubMeshesAsTexturesAndMiscDirty() {
  1148. this._markAllSubMeshesAsDirty(Material._TextureAndMiscDirtyCallBack);
  1149. }
  1150. /**
  1151. * Sets the required values to the prepass renderer.
  1152. * @param prePassRenderer defines the prepass renderer to setup.
  1153. * @returns true if the pre pass is needed.
  1154. */
  1155. public setPrePassRenderer(prePassRenderer: PrePassRenderer): boolean {
  1156. // Do Nothing by default
  1157. return false;
  1158. }
  1159. /**
  1160. * Disposes the material
  1161. * @param forceDisposeEffect specifies if effects should be forcefully disposed
  1162. * @param forceDisposeTextures specifies if textures should be forcefully disposed
  1163. * @param notBoundToMesh specifies if the material that is being disposed is known to be not bound to any mesh
  1164. */
  1165. public dispose(forceDisposeEffect?: boolean, forceDisposeTextures?: boolean, notBoundToMesh?: boolean): void {
  1166. const scene = this.getScene();
  1167. // Animations
  1168. scene.stopAnimation(this);
  1169. scene.freeProcessedMaterials();
  1170. // Remove from scene
  1171. scene.removeMaterial(this);
  1172. if (notBoundToMesh !== true) {
  1173. // Remove from meshes
  1174. if (this.meshMap) {
  1175. for (let meshId in this.meshMap) {
  1176. const mesh = this.meshMap[meshId];
  1177. if (mesh) {
  1178. mesh.material = null; // will set the entry in the map to undefined
  1179. this.releaseVertexArrayObject(mesh, forceDisposeEffect);
  1180. }
  1181. }
  1182. }
  1183. else {
  1184. const meshes = scene.meshes;
  1185. for (let mesh of meshes) {
  1186. if (mesh.material === this && !(mesh as InstancedMesh).sourceMesh) {
  1187. mesh.material = null;
  1188. this.releaseVertexArrayObject(mesh, forceDisposeEffect);
  1189. }
  1190. }
  1191. }
  1192. }
  1193. this._uniformBuffer.dispose();
  1194. // Shader are kept in cache for further use but we can get rid of this by using forceDisposeEffect
  1195. if (forceDisposeEffect && this._effect) {
  1196. if (!this._storeEffectOnSubMeshes) {
  1197. this._effect.dispose();
  1198. }
  1199. this._effect = null;
  1200. }
  1201. // Callback
  1202. this.onDisposeObservable.notifyObservers(this);
  1203. this.onDisposeObservable.clear();
  1204. if (this._onBindObservable) {
  1205. this._onBindObservable.clear();
  1206. }
  1207. if (this._onUnBindObservable) {
  1208. this._onUnBindObservable.clear();
  1209. }
  1210. if (this._onEffectCreatedObservable) {
  1211. this._onEffectCreatedObservable.clear();
  1212. }
  1213. }
  1214. /** @hidden */
  1215. private releaseVertexArrayObject(mesh: AbstractMesh, forceDisposeEffect?: boolean) {
  1216. if ((<Mesh>mesh).geometry) {
  1217. var geometry = <Geometry>((<Mesh>mesh).geometry);
  1218. if (this._storeEffectOnSubMeshes) {
  1219. for (var subMesh of mesh.subMeshes) {
  1220. geometry._releaseVertexArrayObject(subMesh._materialEffect);
  1221. if (forceDisposeEffect && subMesh._materialEffect) {
  1222. subMesh._materialEffect.dispose();
  1223. }
  1224. }
  1225. } else {
  1226. geometry._releaseVertexArrayObject(this._effect);
  1227. }
  1228. }
  1229. }
  1230. /**
  1231. * Serializes this material
  1232. * @returns the serialized material object
  1233. */
  1234. public serialize(): any {
  1235. return SerializationHelper.Serialize(this);
  1236. }
  1237. /**
  1238. * Creates a material from parsed material data
  1239. * @param parsedMaterial defines parsed material data
  1240. * @param scene defines the hosting scene
  1241. * @param rootUrl defines the root URL to use to load textures
  1242. * @returns a new material
  1243. */
  1244. public static Parse(parsedMaterial: any, scene: Scene, rootUrl: string): Nullable<Material> {
  1245. if (!parsedMaterial.customType) {
  1246. parsedMaterial.customType = "BABYLON.StandardMaterial";
  1247. }
  1248. else if (parsedMaterial.customType === "BABYLON.PBRMaterial" && parsedMaterial.overloadedAlbedo) {
  1249. parsedMaterial.customType = "BABYLON.LegacyPBRMaterial";
  1250. if (!BABYLON.LegacyPBRMaterial) {
  1251. Logger.Error("Your scene is trying to load a legacy version of the PBRMaterial, please, include it from the materials library.");
  1252. return null;
  1253. }
  1254. }
  1255. var materialType = Tools.Instantiate(parsedMaterial.customType);
  1256. return materialType.Parse(parsedMaterial, scene, rootUrl);
  1257. }
  1258. }