babylon.material.ts 44 KB

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