babylon.baseTexture.ts 24 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704
  1. module BABYLON {
  2. /**
  3. * Base class of all the textures in babylon.
  4. * It groups all the common properties the materials, post process, lights... might need
  5. * in order to make a correct use of the texture.
  6. */
  7. export class BaseTexture {
  8. /**
  9. * Default anisotropic filtering level for the application.
  10. * It is set to 4 as a good tradeoff between perf and quality.
  11. */
  12. public static DEFAULT_ANISOTROPIC_FILTERING_LEVEL = 4;
  13. /**
  14. * Gets or sets the unique id of the texture
  15. */
  16. @serialize()
  17. public uniqueId: number;
  18. /**
  19. * Define the name of the texture.
  20. */
  21. @serialize()
  22. public name: string;
  23. /**
  24. * Gets or sets an object used to store user defined information.
  25. */
  26. @serialize()
  27. public metadata: any = null;
  28. /**
  29. * For internal use only. Please do not use.
  30. */
  31. public reservedDataStore: any = null;
  32. @serialize("hasAlpha")
  33. private _hasAlpha = false;
  34. /**
  35. * Define if the texture is having a usable alpha value (can be use for transparency or glossiness for instance).
  36. */
  37. public set hasAlpha(value: boolean) {
  38. if (this._hasAlpha === value) {
  39. return;
  40. }
  41. this._hasAlpha = value;
  42. if (this._scene) {
  43. this._scene.markAllMaterialsAsDirty(Material.TextureDirtyFlag | Material.MiscDirtyFlag);
  44. }
  45. }
  46. public get hasAlpha(): boolean {
  47. return this._hasAlpha;
  48. }
  49. /**
  50. * Defines if the alpha value should be determined via the rgb values.
  51. * If true the luminance of the pixel might be used to find the corresponding alpha value.
  52. */
  53. @serialize()
  54. public getAlphaFromRGB = false;
  55. /**
  56. * Intensity or strength of the texture.
  57. * It is commonly used by materials to fine tune the intensity of the texture
  58. */
  59. @serialize()
  60. public level = 1;
  61. /**
  62. * Define the UV chanel to use starting from 0 and defaulting to 0.
  63. * This is part of the texture as textures usually maps to one uv set.
  64. */
  65. @serialize()
  66. public coordinatesIndex = 0;
  67. @serialize("coordinatesMode")
  68. private _coordinatesMode = Texture.EXPLICIT_MODE;
  69. /**
  70. * How a texture is mapped.
  71. *
  72. * | Value | Type | Description |
  73. * | ----- | ----------------------------------- | ----------- |
  74. * | 0 | EXPLICIT_MODE | |
  75. * | 1 | SPHERICAL_MODE | |
  76. * | 2 | PLANAR_MODE | |
  77. * | 3 | CUBIC_MODE | |
  78. * | 4 | PROJECTION_MODE | |
  79. * | 5 | SKYBOX_MODE | |
  80. * | 6 | INVCUBIC_MODE | |
  81. * | 7 | EQUIRECTANGULAR_MODE | |
  82. * | 8 | FIXED_EQUIRECTANGULAR_MODE | |
  83. * | 9 | FIXED_EQUIRECTANGULAR_MIRRORED_MODE | |
  84. */
  85. public set coordinatesMode(value: number) {
  86. if (this._coordinatesMode === value) {
  87. return;
  88. }
  89. this._coordinatesMode = value;
  90. if (this._scene) {
  91. this._scene.markAllMaterialsAsDirty(Material.TextureDirtyFlag);
  92. }
  93. }
  94. public get coordinatesMode(): number {
  95. return this._coordinatesMode;
  96. }
  97. /**
  98. * | Value | Type | Description |
  99. * | ----- | ------------------ | ----------- |
  100. * | 0 | CLAMP_ADDRESSMODE | |
  101. * | 1 | WRAP_ADDRESSMODE | |
  102. * | 2 | MIRROR_ADDRESSMODE | |
  103. */
  104. @serialize()
  105. public wrapU = Texture.WRAP_ADDRESSMODE;
  106. /**
  107. * | Value | Type | Description |
  108. * | ----- | ------------------ | ----------- |
  109. * | 0 | CLAMP_ADDRESSMODE | |
  110. * | 1 | WRAP_ADDRESSMODE | |
  111. * | 2 | MIRROR_ADDRESSMODE | |
  112. */
  113. @serialize()
  114. public wrapV = Texture.WRAP_ADDRESSMODE;
  115. /**
  116. * | Value | Type | Description |
  117. * | ----- | ------------------ | ----------- |
  118. * | 0 | CLAMP_ADDRESSMODE | |
  119. * | 1 | WRAP_ADDRESSMODE | |
  120. * | 2 | MIRROR_ADDRESSMODE | |
  121. */
  122. @serialize()
  123. public wrapR = Texture.WRAP_ADDRESSMODE;
  124. /**
  125. * With compliant hardware and browser (supporting anisotropic filtering)
  126. * this defines the level of anisotropic filtering in the texture.
  127. * The higher the better but the slower. This defaults to 4 as it seems to be the best tradeoff.
  128. */
  129. @serialize()
  130. public anisotropicFilteringLevel = BaseTexture.DEFAULT_ANISOTROPIC_FILTERING_LEVEL;
  131. /**
  132. * Define if the texture is a cube texture or if false a 2d texture.
  133. */
  134. @serialize()
  135. public isCube = false;
  136. /**
  137. * Define if the texture is a 3d texture (webgl 2) or if false a 2d texture.
  138. */
  139. @serialize()
  140. public is3D = false;
  141. /**
  142. * Define if the texture contains data in gamma space (most of the png/jpg aside bump).
  143. * HDR texture are usually stored in linear space.
  144. * This only impacts the PBR and Background materials
  145. */
  146. @serialize()
  147. public gammaSpace = true;
  148. /**
  149. * Gets whether or not the texture contains RGBD data.
  150. */
  151. public get isRGBD(): boolean {
  152. return this._texture != null && this._texture._isRGBD;
  153. }
  154. /**
  155. * Is Z inverted in the texture (useful in a cube texture).
  156. */
  157. @serialize()
  158. public invertZ = false;
  159. /**
  160. * Are mip maps generated for this texture or not.
  161. */
  162. public get noMipmap(): boolean {
  163. return false;
  164. }
  165. /**
  166. * @hidden
  167. */
  168. @serialize()
  169. public lodLevelInAlpha = false;
  170. /**
  171. * With prefiltered texture, defined the offset used during the prefiltering steps.
  172. */
  173. @serialize()
  174. public get lodGenerationOffset(): number {
  175. if (this._texture) { return this._texture._lodGenerationOffset; }
  176. return 0.0;
  177. }
  178. public set lodGenerationOffset(value: number) {
  179. if (this._texture) { this._texture._lodGenerationOffset = value; }
  180. }
  181. /**
  182. * With prefiltered texture, defined the scale used during the prefiltering steps.
  183. */
  184. @serialize()
  185. public get lodGenerationScale(): number {
  186. if (this._texture) { return this._texture._lodGenerationScale; }
  187. return 0.0;
  188. }
  189. public set lodGenerationScale(value: number) {
  190. if (this._texture) { this._texture._lodGenerationScale = value; }
  191. }
  192. /**
  193. * Define if the texture is a render target.
  194. */
  195. @serialize()
  196. public isRenderTarget = false;
  197. /**
  198. * Define the unique id of the texture in the scene.
  199. */
  200. public get uid(): string {
  201. if (!this._uid) {
  202. this._uid = Tools.RandomId();
  203. }
  204. return this._uid;
  205. }
  206. /**
  207. * Return a string representation of the texture.
  208. * @returns the texture as a string
  209. */
  210. public toString(): string {
  211. return this.name;
  212. }
  213. /**
  214. * Get the class name of the texture.
  215. * @returns "BaseTexture"
  216. */
  217. public getClassName(): string {
  218. return "BaseTexture";
  219. }
  220. /**
  221. * Define the list of animation attached to the texture.
  222. */
  223. public animations = new Array<Animation>();
  224. /**
  225. * An event triggered when the texture is disposed.
  226. */
  227. public onDisposeObservable = new Observable<BaseTexture>();
  228. private _onDisposeObserver: Nullable<Observer<BaseTexture>>;
  229. /**
  230. * Callback triggered when the texture has been disposed.
  231. * Kept for back compatibility, you can use the onDisposeObservable instead.
  232. */
  233. public set onDispose(callback: () => void) {
  234. if (this._onDisposeObserver) {
  235. this.onDisposeObservable.remove(this._onDisposeObserver);
  236. }
  237. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  238. }
  239. /**
  240. * Define the current state of the loading sequence when in delayed load mode.
  241. */
  242. public delayLoadState = Engine.DELAYLOADSTATE_NONE;
  243. private _scene: Nullable<Scene>;
  244. /** @hidden */
  245. public _samplingMode: number;
  246. /** @hidden */
  247. public _texture: Nullable<InternalTexture>;
  248. private _uid: Nullable<string>;
  249. /**
  250. * Define if the texture is preventinga material to render or not.
  251. * If not and the texture is not ready, the engine will use a default black texture instead.
  252. */
  253. public get isBlocking(): boolean {
  254. return true;
  255. }
  256. /**
  257. * Instantiates a new BaseTexture.
  258. * Base class of all the textures in babylon.
  259. * It groups all the common properties the materials, post process, lights... might need
  260. * in order to make a correct use of the texture.
  261. * @param scene Define the scene the texture blongs to
  262. */
  263. constructor(scene: Nullable<Scene>) {
  264. this._scene = scene || Engine.LastCreatedScene;
  265. if (this._scene) {
  266. this.uniqueId = this._scene.getUniqueId();
  267. this._scene.addTexture(this);
  268. }
  269. this._uid = null;
  270. }
  271. /**
  272. * Get the scene the texture belongs to.
  273. * @returns the scene or null if undefined
  274. */
  275. public getScene(): Nullable<Scene> {
  276. return this._scene;
  277. }
  278. /**
  279. * Get the texture transform matrix used to offset tile the texture for istance.
  280. * @returns the transformation matrix
  281. */
  282. public getTextureMatrix(): Matrix {
  283. return <Matrix>Matrix.IdentityReadOnly;
  284. }
  285. /**
  286. * Get the texture reflection matrix used to rotate/transform the reflection.
  287. * @returns the reflection matrix
  288. */
  289. public getReflectionTextureMatrix(): Matrix {
  290. return <Matrix>Matrix.IdentityReadOnly;
  291. }
  292. /**
  293. * Get the underlying lower level texture from Babylon.
  294. * @returns the insternal texture
  295. */
  296. public getInternalTexture(): Nullable<InternalTexture> {
  297. return this._texture;
  298. }
  299. /**
  300. * Get if the texture is ready to be consumed (either it is ready or it is not blocking)
  301. * @returns true if ready or not blocking
  302. */
  303. public isReadyOrNotBlocking(): boolean {
  304. return !this.isBlocking || this.isReady();
  305. }
  306. /**
  307. * Get if the texture is ready to be used (downloaded, converted, mip mapped...).
  308. * @returns true if fully ready
  309. */
  310. public isReady(): boolean {
  311. if (this.delayLoadState === Engine.DELAYLOADSTATE_NOTLOADED) {
  312. this.delayLoad();
  313. return false;
  314. }
  315. if (this._texture) {
  316. return this._texture.isReady;
  317. }
  318. return false;
  319. }
  320. private _cachedSize: ISize = Size.Zero();
  321. /**
  322. * Get the size of the texture.
  323. * @returns the texture size.
  324. */
  325. public getSize(): ISize {
  326. if (this._texture) {
  327. if (this._texture.width) {
  328. this._cachedSize.width = this._texture.width;
  329. this._cachedSize.height = this._texture.height;
  330. return this._cachedSize;
  331. }
  332. if (this._texture._size) {
  333. this._cachedSize.width = this._texture._size;
  334. this._cachedSize.height = this._texture._size;
  335. return this._cachedSize;
  336. }
  337. }
  338. return this._cachedSize;
  339. }
  340. /**
  341. * Get the base size of the texture.
  342. * It can be different from the size if the texture has been resized for POT for instance
  343. * @returns the base size
  344. */
  345. public getBaseSize(): ISize {
  346. if (!this.isReady() || !this._texture) {
  347. return Size.Zero();
  348. }
  349. if (this._texture._size) {
  350. return new Size(this._texture._size, this._texture._size);
  351. }
  352. return new Size(this._texture.baseWidth, this._texture.baseHeight);
  353. }
  354. /**
  355. * Update the sampling mode of the texture.
  356. * Default is Trilinear mode.
  357. *
  358. * | Value | Type | Description |
  359. * | ----- | ------------------ | ----------- |
  360. * | 1 | NEAREST_SAMPLINGMODE or NEAREST_NEAREST_MIPLINEAR | Nearest is: mag = nearest, min = nearest, mip = linear |
  361. * | 2 | BILINEAR_SAMPLINGMODE or LINEAR_LINEAR_MIPNEAREST | Bilinear is: mag = linear, min = linear, mip = nearest |
  362. * | 3 | TRILINEAR_SAMPLINGMODE or LINEAR_LINEAR_MIPLINEAR | Trilinear is: mag = linear, min = linear, mip = linear |
  363. * | 4 | NEAREST_NEAREST_MIPNEAREST | |
  364. * | 5 | NEAREST_LINEAR_MIPNEAREST | |
  365. * | 6 | NEAREST_LINEAR_MIPLINEAR | |
  366. * | 7 | NEAREST_LINEAR | |
  367. * | 8 | NEAREST_NEAREST | |
  368. * | 9 | LINEAR_NEAREST_MIPNEAREST | |
  369. * | 10 | LINEAR_NEAREST_MIPLINEAR | |
  370. * | 11 | LINEAR_LINEAR | |
  371. * | 12 | LINEAR_NEAREST | |
  372. *
  373. * > _mag_: magnification filter (close to the viewer)
  374. * > _min_: minification filter (far from the viewer)
  375. * > _mip_: filter used between mip map levels
  376. *@param samplingMode Define the new sampling mode of the texture
  377. */
  378. public updateSamplingMode(samplingMode: number): void {
  379. if (!this._texture) {
  380. return;
  381. }
  382. let scene = this.getScene();
  383. if (!scene) {
  384. return;
  385. }
  386. this._samplingMode = samplingMode;
  387. scene.getEngine().updateTextureSamplingMode(samplingMode, this._texture);
  388. }
  389. /**
  390. * Scales the texture if is `canRescale()`
  391. * @param ratio the resize factor we want to use to rescale
  392. */
  393. public scale(ratio: number): void {
  394. }
  395. /**
  396. * Get if the texture can rescale.
  397. */
  398. public get canRescale(): boolean {
  399. return false;
  400. }
  401. /** @hidden */
  402. public _getFromCache(url: Nullable<string>, noMipmap: boolean, sampling?: number): Nullable<InternalTexture> {
  403. if (!this._scene) {
  404. return null;
  405. }
  406. var texturesCache = this._scene.getEngine().getLoadedTexturesCache();
  407. for (var index = 0; index < texturesCache.length; index++) {
  408. var texturesCacheEntry = texturesCache[index];
  409. if (texturesCacheEntry.url === url && texturesCacheEntry.generateMipMaps === !noMipmap) {
  410. if (!sampling || sampling === texturesCacheEntry.samplingMode) {
  411. texturesCacheEntry.incrementReferences();
  412. return texturesCacheEntry;
  413. }
  414. }
  415. }
  416. return null;
  417. }
  418. /** @hidden */
  419. public _rebuild(): void {
  420. }
  421. /**
  422. * Triggers the load sequence in delayed load mode.
  423. */
  424. public delayLoad(): void {
  425. }
  426. /**
  427. * Clones the texture.
  428. * @returns the cloned texture
  429. */
  430. public clone(): Nullable<BaseTexture> {
  431. return null;
  432. }
  433. /**
  434. * Get the texture underlying type (INT, FLOAT...)
  435. */
  436. public get textureType(): number {
  437. if (!this._texture) {
  438. return Engine.TEXTURETYPE_UNSIGNED_INT;
  439. }
  440. return (this._texture.type !== undefined) ? this._texture.type : Engine.TEXTURETYPE_UNSIGNED_INT;
  441. }
  442. /**
  443. * Get the texture underlying format (RGB, RGBA...)
  444. */
  445. public get textureFormat(): number {
  446. if (!this._texture) {
  447. return Engine.TEXTUREFORMAT_RGBA;
  448. }
  449. return (this._texture.format !== undefined) ? this._texture.format : Engine.TEXTUREFORMAT_RGBA;
  450. }
  451. /**
  452. * Reads the pixels stored in the webgl texture and returns them as an ArrayBuffer.
  453. * This will returns an RGBA array buffer containing either in values (0-255) or
  454. * float values (0-1) depending of the underlying buffer type.
  455. * @param faceIndex defines the face of the texture to read (in case of cube texture)
  456. * @param level defines the LOD level of the texture to read (in case of Mip Maps)
  457. * @param buffer defines a user defined buffer to fill with data (can be null)
  458. * @returns The Array buffer containing the pixels data.
  459. */
  460. public readPixels(faceIndex = 0, level = 0, buffer: Nullable<ArrayBufferView> = null): Nullable<ArrayBufferView> {
  461. if (!this._texture) {
  462. return null;
  463. }
  464. var size = this.getSize();
  465. var width = size.width;
  466. var height = size.height;
  467. let scene = this.getScene();
  468. if (!scene) {
  469. return null;
  470. }
  471. var engine = scene.getEngine();
  472. if (level != 0) {
  473. width = width / Math.pow(2, level);
  474. height = height / Math.pow(2, level);
  475. width = Math.round(width);
  476. height = Math.round(height);
  477. }
  478. if (this._texture.isCube) {
  479. return engine._readTexturePixels(this._texture, width, height, faceIndex, level, buffer);
  480. }
  481. return engine._readTexturePixels(this._texture, width, height, -1, level, buffer);
  482. }
  483. /**
  484. * Release and destroy the underlying lower level texture aka internalTexture.
  485. */
  486. public releaseInternalTexture(): void {
  487. if (this._texture) {
  488. this._texture.dispose();
  489. this._texture = null;
  490. }
  491. }
  492. /**
  493. * Get the polynomial representation of the texture data.
  494. * This is mainly use as a fast way to recover IBL Diffuse irradiance data.
  495. * @see https://learnopengl.com/PBR/IBL/Diffuse-irradiance
  496. */
  497. public get sphericalPolynomial(): Nullable<SphericalPolynomial> {
  498. if (!this._texture || !CubeMapToSphericalPolynomialTools || !this.isReady()) {
  499. return null;
  500. }
  501. if (!this._texture._sphericalPolynomial) {
  502. this._texture._sphericalPolynomial =
  503. CubeMapToSphericalPolynomialTools.ConvertCubeMapTextureToSphericalPolynomial(this);
  504. }
  505. return this._texture._sphericalPolynomial;
  506. }
  507. public set sphericalPolynomial(value: Nullable<SphericalPolynomial>) {
  508. if (this._texture) {
  509. this._texture._sphericalPolynomial = value;
  510. }
  511. }
  512. /** @hidden */
  513. public get _lodTextureHigh(): Nullable<BaseTexture> {
  514. if (this._texture) {
  515. return this._texture._lodTextureHigh;
  516. }
  517. return null;
  518. }
  519. /** @hidden */
  520. public get _lodTextureMid(): Nullable<BaseTexture> {
  521. if (this._texture) {
  522. return this._texture._lodTextureMid;
  523. }
  524. return null;
  525. }
  526. /** @hidden */
  527. public get _lodTextureLow(): Nullable<BaseTexture> {
  528. if (this._texture) {
  529. return this._texture._lodTextureLow;
  530. }
  531. return null;
  532. }
  533. /**
  534. * Dispose the texture and release its associated resources.
  535. */
  536. public dispose(): void {
  537. if (!this._scene) {
  538. return;
  539. }
  540. // Animations
  541. this._scene.stopAnimation(this);
  542. // Remove from scene
  543. this._scene._removePendingData(this);
  544. var index = this._scene.textures.indexOf(this);
  545. if (index >= 0) {
  546. this._scene.textures.splice(index, 1);
  547. }
  548. this._scene.onTextureRemovedObservable.notifyObservers(this);
  549. if (this._texture === undefined) {
  550. return;
  551. }
  552. // Release
  553. this.releaseInternalTexture();
  554. // Callback
  555. this.onDisposeObservable.notifyObservers(this);
  556. this.onDisposeObservable.clear();
  557. }
  558. /**
  559. * Serialize the texture into a JSON representation that can be parsed later on.
  560. * @returns the JSON representation of the texture
  561. */
  562. public serialize(): any {
  563. if (!this.name) {
  564. return null;
  565. }
  566. var serializationObject = SerializationHelper.Serialize(this);
  567. // Animations
  568. Animation.AppendSerializedAnimations(this, serializationObject);
  569. return serializationObject;
  570. }
  571. /**
  572. * Helper function to be called back once a list of texture contains only ready textures.
  573. * @param textures Define the list of textures to wait for
  574. * @param callback Define the callback triggered once the entire list will be ready
  575. */
  576. public static WhenAllReady(textures: BaseTexture[], callback: () => void): void {
  577. let numRemaining = textures.length;
  578. if (numRemaining === 0) {
  579. callback();
  580. return;
  581. }
  582. for (var i = 0; i < textures.length; i++) {
  583. var texture = textures[i];
  584. if (texture.isReady()) {
  585. if (--numRemaining === 0) {
  586. callback();
  587. }
  588. }
  589. else {
  590. var onLoadObservable = (texture as any).onLoadObservable as Observable<Texture>;
  591. let onLoadCallback = () => {
  592. onLoadObservable.removeCallback(onLoadCallback);
  593. if (--numRemaining === 0) {
  594. callback();
  595. }
  596. };
  597. onLoadObservable.add(onLoadCallback);
  598. }
  599. }
  600. }
  601. }
  602. }