equiRectangularCubeTexture.ts 7.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214
  1. import { PanoramaToCubeMapTools } from '../../Misc/HighDynamicRange/panoramaToCubemap';
  2. import { Engine } from "../../Engines/engine";
  3. import { BaseTexture } from './baseTexture';
  4. import { Texture } from './texture';
  5. import { Scene } from "../../scene";
  6. import { Nullable } from "../../types";
  7. import { Tools } from '../../Misc/tools';
  8. /**
  9. * This represents a texture coming from an equirectangular image supported by the web browser canvas.
  10. */
  11. export class EquiRectangularCubeTexture extends BaseTexture {
  12. /** The six faces of the cube. */
  13. private static _FacesMapping = ['right', 'left', 'up', 'down', 'front', 'back'];
  14. private _noMipmap: boolean;
  15. private _onLoad: Nullable<() => void> = null;
  16. private _onError: Nullable<() => void> = null;
  17. /** The size of the cubemap. */
  18. private _size: number;
  19. /** The buffer of the image. */
  20. private _buffer: ArrayBuffer;
  21. /** The width of the input image. */
  22. private _width: number;
  23. /** The height of the input image. */
  24. private _height: number;
  25. /** The URL to the image. */
  26. public url: string;
  27. /** The texture coordinates mode. As this texture is stored in a cube format, please modify carefully. */
  28. public coordinatesMode = Texture.CUBIC_MODE;
  29. /**
  30. * Instantiates an EquiRectangularCubeTexture from the following parameters.
  31. * @param url The location of the image
  32. * @param scene The scene the texture will be used in
  33. * @param size The cubemap desired size (the more it increases the longer the generation will be)
  34. * @param noMipmap Forces to not generate the mipmap if true
  35. * @param gammaSpace Specifies if the texture will be used in gamma or linear space
  36. * (the PBR material requires those textures in linear space, but the standard material would require them in Gamma space)
  37. * @param onLoad — defines a callback called when texture is loaded
  38. * @param onError — defines a callback called if there is an error
  39. */
  40. constructor(
  41. url: string,
  42. scene: Scene,
  43. size: number,
  44. noMipmap: boolean = false,
  45. gammaSpace: boolean = true,
  46. onLoad: Nullable<() => void> = null,
  47. onError: Nullable<(message?: string, exception?: any) => void> = null
  48. ) {
  49. super(scene);
  50. if (!url) {
  51. throw new Error('Image url is not set');
  52. }
  53. this.name = url;
  54. this.url = url;
  55. this._size = size;
  56. this._noMipmap = noMipmap;
  57. this.gammaSpace = gammaSpace;
  58. this._onLoad = onLoad;
  59. this._onError = onError;
  60. this.hasAlpha = false;
  61. this.isCube = true;
  62. this._texture = this._getFromCache(url, this._noMipmap);
  63. if (!this._texture) {
  64. if (!scene.useDelayedTextureLoading) {
  65. this.loadImage(this.loadTexture.bind(this), this._onError);
  66. } else {
  67. this.delayLoadState = Engine.DELAYLOADSTATE_NOTLOADED;
  68. }
  69. } else if (onLoad) {
  70. if (this._texture.isReady) {
  71. Tools.SetImmediate(() => onLoad());
  72. } else {
  73. this._texture.onLoadedObservable.add(onLoad);
  74. }
  75. }
  76. }
  77. /**
  78. * Load the image data, by putting the image on a canvas and extracting its buffer.
  79. */
  80. private loadImage(loadTextureCallback: () => void, onError: Nullable<(message?: string, exception?: any) => void>): void {
  81. const canvas = document.createElement('canvas');
  82. const image = new Image();
  83. image.addEventListener('load', () => {
  84. this._width = image.width;
  85. this._height = image.height;
  86. canvas.width = this._width;
  87. canvas.height = this._height;
  88. const ctx = canvas.getContext('2d') as CanvasRenderingContext2D;
  89. ctx.drawImage(image, 0, 0);
  90. const imageData = ctx.getImageData(0, 0, image.width, image.height);
  91. this._buffer = imageData.data.buffer as ArrayBuffer;
  92. canvas.remove();
  93. loadTextureCallback();
  94. });
  95. image.addEventListener('error', (error) => {
  96. if (onError) {
  97. onError(`${this.getClassName()} could not be loaded`, error);
  98. }
  99. });
  100. image.src = this.url;
  101. }
  102. /**
  103. * Convert the image buffer into a cubemap and create a CubeTexture.
  104. */
  105. private loadTexture(): void {
  106. const scene = this.getScene();
  107. const callback = (): Nullable<ArrayBufferView[]> => {
  108. const imageData = this.getFloat32ArrayFromArrayBuffer(this._buffer);
  109. // Extract the raw linear data.
  110. const data = PanoramaToCubeMapTools.ConvertPanoramaToCubemap(imageData, this._width, this._height, this._size);
  111. const results = [];
  112. // Push each faces.
  113. for (let i = 0; i < 6; i++) {
  114. const dataFace = (data as any)[EquiRectangularCubeTexture._FacesMapping[i]];
  115. results.push(dataFace);
  116. }
  117. return results;
  118. };
  119. if (!scene) {
  120. return;
  121. }
  122. this._texture = scene
  123. .getEngine()
  124. .createRawCubeTextureFromUrl(
  125. this.url,
  126. scene,
  127. this._size,
  128. Engine.TEXTUREFORMAT_RGB,
  129. scene.getEngine().getCaps().textureFloat
  130. ? Engine.TEXTURETYPE_FLOAT
  131. : Engine.TEXTURETYPE_UNSIGNED_INTEGER,
  132. this._noMipmap,
  133. callback,
  134. null,
  135. this._onLoad,
  136. this._onError
  137. );
  138. }
  139. /**
  140. * Convert the ArrayBuffer into a Float32Array and drop the transparency channel.
  141. * @param buffer The ArrayBuffer that should be converted.
  142. * @returns The buffer as Float32Array.
  143. */
  144. private getFloat32ArrayFromArrayBuffer(buffer: ArrayBuffer): Float32Array {
  145. const dataView = new DataView(buffer);
  146. const floatImageData = new Float32Array((buffer.byteLength * 3) / 4);
  147. let k = 0;
  148. for (let i = 0; i < buffer.byteLength; i++) {
  149. // We drop the transparency channel, because we do not need/want it
  150. if ((i + 1) % 4 !== 0) {
  151. floatImageData[k++] = dataView.getUint8(i) / 255;
  152. }
  153. }
  154. return floatImageData;
  155. }
  156. /**
  157. * Get the current class name of the texture useful for serialization or dynamic coding.
  158. * @returns "EquiRectangularCubeTexture"
  159. */
  160. public getClassName(): string {
  161. return "EquiRectangularCubeTexture";
  162. }
  163. /**
  164. * Create a clone of the current EquiRectangularCubeTexture and return it.
  165. * @returns A clone of the current EquiRectangularCubeTexture.
  166. */
  167. public clone(): EquiRectangularCubeTexture {
  168. const scene = this.getScene();
  169. if (!scene) {
  170. return this;
  171. }
  172. const newTexture = new EquiRectangularCubeTexture(this.url, scene, this._size, this._noMipmap, this.gammaSpace);
  173. // Base texture
  174. newTexture.level = this.level;
  175. newTexture.wrapU = this.wrapU;
  176. newTexture.wrapV = this.wrapV;
  177. newTexture.coordinatesIndex = this.coordinatesIndex;
  178. newTexture.coordinatesMode = this.coordinatesMode;
  179. return newTexture;
  180. }
  181. }