environmentTextureTools.ts 27 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641
  1. import { Nullable } from "../types";
  2. import { Tools } from "./tools";
  3. import { Vector3 } from "../Maths/math.vector";
  4. import { Scalar } from "../Maths/math.scalar";
  5. import { SphericalPolynomial } from "../Maths/sphericalPolynomial";
  6. import { InternalTexture, InternalTextureSource } from "../Materials/Textures/internalTexture";
  7. import { BaseTexture } from "../Materials/Textures/baseTexture";
  8. import { Constants } from "../Engines/constants";
  9. import { Scene } from "../scene";
  10. import { PostProcess } from "../PostProcesses/postProcess";
  11. import { Logger } from "../Misc/logger";
  12. import "../Engines/Extensions/engine.renderTargetCube";
  13. import "../Engines/Extensions/engine.readTexture";
  14. import "../Materials/Textures/baseTexture.polynomial";
  15. import "../Shaders/rgbdEncode.fragment";
  16. import "../Shaders/rgbdDecode.fragment";
  17. import { Engine } from '../Engines/engine';
  18. import { ThinEngine } from '../Engines/thinEngine';
  19. import { RGBDTextureTools } from './rgbdTextureTools';
  20. /**
  21. * Raw texture data and descriptor sufficient for WebGL texture upload
  22. */
  23. export interface EnvironmentTextureInfo {
  24. /**
  25. * Version of the environment map
  26. */
  27. version: number;
  28. /**
  29. * Width of image
  30. */
  31. width: number;
  32. /**
  33. * Irradiance information stored in the file.
  34. */
  35. irradiance: any;
  36. /**
  37. * Specular information stored in the file.
  38. */
  39. specular: any;
  40. }
  41. /**
  42. * Defines One Image in the file. It requires only the position in the file
  43. * as well as the length.
  44. */
  45. interface BufferImageData {
  46. /**
  47. * Length of the image data.
  48. */
  49. length: number;
  50. /**
  51. * Position of the data from the null terminator delimiting the end of the JSON.
  52. */
  53. position: number;
  54. }
  55. /**
  56. * Defines the specular data enclosed in the file.
  57. * This corresponds to the version 1 of the data.
  58. */
  59. export interface EnvironmentTextureSpecularInfoV1 {
  60. /**
  61. * Defines where the specular Payload is located. It is a runtime value only not stored in the file.
  62. */
  63. specularDataPosition?: number;
  64. /**
  65. * This contains all the images data needed to reconstruct the cubemap.
  66. */
  67. mipmaps: Array<BufferImageData>;
  68. /**
  69. * Defines the scale applied to environment texture. This manages the range of LOD level used for IBL according to the roughness.
  70. */
  71. lodGenerationScale: number;
  72. }
  73. /**
  74. * Defines the required storage to save the environment irradiance information.
  75. */
  76. interface EnvironmentTextureIrradianceInfoV1 {
  77. x: Array<number>;
  78. y: Array<number>;
  79. z: Array<number>;
  80. xx: Array<number>;
  81. yy: Array<number>;
  82. zz: Array<number>;
  83. yz: Array<number>;
  84. zx: Array<number>;
  85. xy: Array<number>;
  86. }
  87. /**
  88. * Sets of helpers addressing the serialization and deserialization of environment texture
  89. * stored in a BabylonJS env file.
  90. * Those files are usually stored as .env files.
  91. */
  92. export class EnvironmentTextureTools {
  93. /**
  94. * Magic number identifying the env file.
  95. */
  96. private static _MagicBytes = [0x86, 0x16, 0x87, 0x96, 0xf6, 0xd6, 0x96, 0x36];
  97. /**
  98. * Gets the environment info from an env file.
  99. * @param data The array buffer containing the .env bytes.
  100. * @returns the environment file info (the json header) if successfully parsed.
  101. */
  102. public static GetEnvInfo(data: ArrayBufferView): Nullable<EnvironmentTextureInfo> {
  103. let dataView = new DataView(data.buffer, data.byteOffset, data.byteLength);
  104. let pos = 0;
  105. for (let i = 0; i < EnvironmentTextureTools._MagicBytes.length; i++) {
  106. if (dataView.getUint8(pos++) !== EnvironmentTextureTools._MagicBytes[i]) {
  107. Logger.Error('Not a babylon environment map');
  108. return null;
  109. }
  110. }
  111. // Read json manifest - collect characters up to null terminator
  112. let manifestString = '';
  113. let charCode = 0x00;
  114. while ((charCode = dataView.getUint8(pos++))) {
  115. manifestString += String.fromCharCode(charCode);
  116. }
  117. let manifest: EnvironmentTextureInfo = JSON.parse(manifestString);
  118. if (manifest.specular) {
  119. // Extend the header with the position of the payload.
  120. manifest.specular.specularDataPosition = pos;
  121. // Fallback to 0.8 exactly if lodGenerationScale is not defined for backward compatibility.
  122. manifest.specular.lodGenerationScale = manifest.specular.lodGenerationScale || 0.8;
  123. }
  124. return manifest;
  125. }
  126. /**
  127. * Creates an environment texture from a loaded cube texture.
  128. * @param texture defines the cube texture to convert in env file
  129. * @return a promise containing the environment data if succesfull.
  130. */
  131. public static async CreateEnvTextureAsync(texture: BaseTexture): Promise<ArrayBuffer> {
  132. let internalTexture = texture.getInternalTexture();
  133. if (!internalTexture) {
  134. return Promise.reject("The cube texture is invalid.");
  135. }
  136. let engine = internalTexture.getEngine() as Engine;
  137. if (texture.textureType === Constants.TEXTURETYPE_UNSIGNED_INT) {
  138. return Promise.reject("The cube texture should allow HDR (Full Float or Half Float).");
  139. }
  140. let textureType = Constants.TEXTURETYPE_FLOAT;
  141. if (!engine.getCaps().textureFloatRender) {
  142. textureType = Constants.TEXTURETYPE_HALF_FLOAT;
  143. if (!engine.getCaps().textureHalfFloatRender) {
  144. return Promise.reject("Env texture can only be created when the browser supports half float or full float rendering.");
  145. }
  146. }
  147. let cubeWidth = internalTexture.width;
  148. let hostingScene = new Scene(engine);
  149. let specularTextures: { [key: number]: ArrayBuffer } = {};
  150. // As we are going to readPixels the faces of the cube, make sure the drawing/update commands for the cube texture are fully sent to the GPU in case it is drawn for the first time in this very frame!
  151. engine.flushFramebuffer();
  152. // Read and collect all mipmaps data from the cube.
  153. let mipmapsCount = Scalar.ILog2(internalTexture.width);
  154. for (let i = 0; i <= mipmapsCount; i++) {
  155. let faceWidth = Math.pow(2, mipmapsCount - i);
  156. // All faces of the cube.
  157. for (let face = 0; face < 6; face++) {
  158. let faceData = await texture.readPixels(face, i);
  159. let tempTexture = engine.createRawTexture(faceData, faceWidth, faceWidth, Constants.TEXTUREFORMAT_RGBA, false, true, Constants.TEXTURE_NEAREST_SAMPLINGMODE, null, textureType);
  160. await RGBDTextureTools.EncodeTextureToRGBD(tempTexture, hostingScene, textureType);
  161. engine.flushFramebuffer(); // make sure the tempTexture has its data up to date when reading them just below
  162. const rgbdEncodedData = await engine._readTexturePixels(tempTexture, faceWidth, faceWidth);
  163. const pngEncodedata = await Tools.DumpDataAsync(faceWidth, faceWidth, rgbdEncodedData, "image/png", undefined, false, true);
  164. specularTextures[i * 6 + face] = pngEncodedata as ArrayBuffer;
  165. tempTexture.dispose();
  166. }
  167. }
  168. // We can delete the hosting scene keeping track of all the creation objects
  169. hostingScene.dispose();
  170. // Creates the json header for the env texture
  171. let info: EnvironmentTextureInfo = {
  172. version: 1,
  173. width: cubeWidth,
  174. irradiance: this._CreateEnvTextureIrradiance(texture),
  175. specular: {
  176. mipmaps: [],
  177. lodGenerationScale: texture.lodGenerationScale
  178. }
  179. };
  180. // Sets the specular image data information
  181. let position = 0;
  182. for (let i = 0; i <= mipmapsCount; i++) {
  183. for (let face = 0; face < 6; face++) {
  184. let byteLength = specularTextures[i * 6 + face].byteLength;
  185. info.specular.mipmaps.push({
  186. length: byteLength,
  187. position: position
  188. });
  189. position += byteLength;
  190. }
  191. }
  192. // Encode the JSON as an array buffer
  193. let infoString = JSON.stringify(info);
  194. let infoBuffer = new ArrayBuffer(infoString.length + 1);
  195. let infoView = new Uint8Array(infoBuffer); // Limited to ascii subset matching unicode.
  196. for (let i = 0, strLen = infoString.length; i < strLen; i++) {
  197. infoView[i] = infoString.charCodeAt(i);
  198. }
  199. // Ends up with a null terminator for easier parsing
  200. infoView[infoString.length] = 0x00;
  201. // Computes the final required size and creates the storage
  202. let totalSize = EnvironmentTextureTools._MagicBytes.length + position + infoBuffer.byteLength;
  203. let finalBuffer = new ArrayBuffer(totalSize);
  204. let finalBufferView = new Uint8Array(finalBuffer);
  205. let dataView = new DataView(finalBuffer);
  206. // Copy the magic bytes identifying the file in
  207. let pos = 0;
  208. for (let i = 0; i < EnvironmentTextureTools._MagicBytes.length; i++) {
  209. dataView.setUint8(pos++, EnvironmentTextureTools._MagicBytes[i]);
  210. }
  211. // Add the json info
  212. finalBufferView.set(new Uint8Array(infoBuffer), pos);
  213. pos += infoBuffer.byteLength;
  214. // Finally inserts the texture data
  215. for (let i = 0; i <= mipmapsCount; i++) {
  216. for (let face = 0; face < 6; face++) {
  217. let dataBuffer = specularTextures[i * 6 + face];
  218. finalBufferView.set(new Uint8Array(dataBuffer), pos);
  219. pos += dataBuffer.byteLength;
  220. }
  221. }
  222. // Voila
  223. return finalBuffer;
  224. }
  225. /**
  226. * Creates a JSON representation of the spherical data.
  227. * @param texture defines the texture containing the polynomials
  228. * @return the JSON representation of the spherical info
  229. */
  230. private static _CreateEnvTextureIrradiance(texture: BaseTexture): Nullable<EnvironmentTextureIrradianceInfoV1> {
  231. let polynmials = texture.sphericalPolynomial;
  232. if (polynmials == null) {
  233. return null;
  234. }
  235. return {
  236. x: [polynmials.x.x, polynmials.x.y, polynmials.x.z],
  237. y: [polynmials.y.x, polynmials.y.y, polynmials.y.z],
  238. z: [polynmials.z.x, polynmials.z.y, polynmials.z.z],
  239. xx: [polynmials.xx.x, polynmials.xx.y, polynmials.xx.z],
  240. yy: [polynmials.yy.x, polynmials.yy.y, polynmials.yy.z],
  241. zz: [polynmials.zz.x, polynmials.zz.y, polynmials.zz.z],
  242. yz: [polynmials.yz.x, polynmials.yz.y, polynmials.yz.z],
  243. zx: [polynmials.zx.x, polynmials.zx.y, polynmials.zx.z],
  244. xy: [polynmials.xy.x, polynmials.xy.y, polynmials.xy.z]
  245. } as any;
  246. }
  247. /**
  248. * Creates the ArrayBufferViews used for initializing environment texture image data.
  249. * @param data the image data
  250. * @param info parameters that determine what views will be created for accessing the underlying buffer
  251. * @return the views described by info providing access to the underlying buffer
  252. */
  253. public static CreateImageDataArrayBufferViews(data: ArrayBufferView, info: EnvironmentTextureInfo): Array<Array<ArrayBufferView>> {
  254. if (info.version !== 1) {
  255. throw new Error(`Unsupported babylon environment map version "${info.version}"`);
  256. }
  257. const specularInfo = info.specular as EnvironmentTextureSpecularInfoV1;
  258. // Double checks the enclosed info
  259. let mipmapsCount = Scalar.Log2(info.width);
  260. mipmapsCount = Math.round(mipmapsCount) + 1;
  261. if (specularInfo.mipmaps.length !== 6 * mipmapsCount) {
  262. throw new Error(`Unsupported specular mipmaps number "${specularInfo.mipmaps.length}"`);
  263. }
  264. const imageData = new Array<Array<ArrayBufferView>>(mipmapsCount);
  265. for (let i = 0; i < mipmapsCount; i++) {
  266. imageData[i] = new Array<ArrayBufferView>(6);
  267. for (let face = 0; face < 6; face++) {
  268. const imageInfo = specularInfo.mipmaps[i * 6 + face];
  269. imageData[i][face] = new Uint8Array(data.buffer, data.byteOffset + specularInfo.specularDataPosition! + imageInfo.position, imageInfo.length);
  270. }
  271. }
  272. return imageData;
  273. }
  274. /**
  275. * Uploads the texture info contained in the env file to the GPU.
  276. * @param texture defines the internal texture to upload to
  277. * @param data defines the data to load
  278. * @param info defines the texture info retrieved through the GetEnvInfo method
  279. * @returns a promise
  280. */
  281. public static UploadEnvLevelsAsync(texture: InternalTexture, data: ArrayBufferView, info: EnvironmentTextureInfo): Promise<void> {
  282. if (info.version !== 1) {
  283. throw new Error(`Unsupported babylon environment map version "${info.version}"`);
  284. }
  285. const specularInfo = info.specular as EnvironmentTextureSpecularInfoV1;
  286. if (!specularInfo) {
  287. // Nothing else parsed so far
  288. return Promise.resolve();
  289. }
  290. texture._lodGenerationScale = specularInfo.lodGenerationScale;
  291. const imageData = EnvironmentTextureTools.CreateImageDataArrayBufferViews(data, info);
  292. return EnvironmentTextureTools.UploadLevelsAsync(texture, imageData);
  293. }
  294. private static _OnImageReadyAsync(image: HTMLImageElement | ImageBitmap, engine: Engine, expandTexture: boolean,
  295. rgbdPostProcess: Nullable<PostProcess>, url: string, face: number, i: number, generateNonLODTextures: boolean,
  296. lodTextures: Nullable<{ [lod: number]: BaseTexture }>, cubeRtt: Nullable<InternalTexture>, texture: InternalTexture
  297. ): Promise<void> {
  298. return new Promise((resolve, reject) => {
  299. if (expandTexture) {
  300. let tempTexture = engine.createTexture(null, true, true, null, Constants.TEXTURE_NEAREST_SAMPLINGMODE, null,
  301. (message) => {
  302. reject(message);
  303. },
  304. image);
  305. rgbdPostProcess!.getEffect().executeWhenCompiled(() => {
  306. // Uncompress the data to a RTT
  307. rgbdPostProcess!.onApply = (effect) => {
  308. effect._bindTexture("textureSampler", tempTexture);
  309. effect.setFloat2("scale", 1, 1);
  310. };
  311. engine.scenes[0].postProcessManager.directRender([rgbdPostProcess!], cubeRtt, true, face, i);
  312. // Cleanup
  313. engine.restoreDefaultFramebuffer();
  314. tempTexture.dispose();
  315. URL.revokeObjectURL(url);
  316. resolve();
  317. });
  318. }
  319. else {
  320. engine._uploadImageToTexture(texture, image, face, i);
  321. // Upload the face to the non lod texture support
  322. if (generateNonLODTextures) {
  323. let lodTexture = lodTextures![i];
  324. if (lodTexture) {
  325. engine._uploadImageToTexture(lodTexture._texture!, image, face, 0);
  326. }
  327. }
  328. resolve();
  329. }
  330. }
  331. );
  332. }
  333. /**
  334. * Uploads the levels of image data to the GPU.
  335. * @param texture defines the internal texture to upload to
  336. * @param imageData defines the array buffer views of image data [mipmap][face]
  337. * @returns a promise
  338. */
  339. public static UploadLevelsAsync(texture: InternalTexture, imageData: ArrayBufferView[][]): Promise<void> {
  340. if (!Tools.IsExponentOfTwo(texture.width)) {
  341. throw new Error("Texture size must be a power of two");
  342. }
  343. const mipmapsCount = Scalar.ILog2(texture.width) + 1;
  344. // Gets everything ready.
  345. let engine = texture.getEngine() as Engine;
  346. let expandTexture = false;
  347. let generateNonLODTextures = false;
  348. let rgbdPostProcess: Nullable<PostProcess> = null;
  349. let cubeRtt: Nullable<InternalTexture> = null;
  350. let lodTextures: Nullable<{ [lod: number]: BaseTexture }> = null;
  351. let caps = engine.getCaps();
  352. texture.format = Constants.TEXTUREFORMAT_RGBA;
  353. texture.type = Constants.TEXTURETYPE_UNSIGNED_INT;
  354. texture.generateMipMaps = true;
  355. texture._cachedAnisotropicFilteringLevel = null;
  356. engine.updateTextureSamplingMode(Constants.TEXTURE_TRILINEAR_SAMPLINGMODE, texture);
  357. // Add extra process if texture lod is not supported
  358. if (!caps.textureLOD) {
  359. expandTexture = false;
  360. generateNonLODTextures = true;
  361. lodTextures = {};
  362. }
  363. // in webgl 1 there are no ways to either render or copy lod level information for float textures.
  364. else if (!ThinEngine.Features.supportRenderAndCopyToLodForFloatTextures) {
  365. expandTexture = false;
  366. }
  367. // If half float available we can uncompress the texture
  368. else if (caps.textureHalfFloatRender && caps.textureHalfFloatLinearFiltering) {
  369. expandTexture = true;
  370. texture.type = Constants.TEXTURETYPE_HALF_FLOAT;
  371. }
  372. // If full float available we can uncompress the texture
  373. else if (caps.textureFloatRender && caps.textureFloatLinearFiltering) {
  374. expandTexture = true;
  375. texture.type = Constants.TEXTURETYPE_FLOAT;
  376. }
  377. // Expand the texture if possible
  378. if (expandTexture) {
  379. // Simply run through the decode PP
  380. rgbdPostProcess = new PostProcess("rgbdDecode", "rgbdDecode", null, null, 1, null, Constants.TEXTURE_TRILINEAR_SAMPLINGMODE, engine, false, undefined, texture.type, undefined, null, false);
  381. texture._isRGBD = false;
  382. texture.invertY = false;
  383. cubeRtt = engine.createRenderTargetCubeTexture(texture.width, {
  384. generateDepthBuffer: false,
  385. generateMipMaps: true,
  386. generateStencilBuffer: false,
  387. samplingMode: Constants.TEXTURE_TRILINEAR_SAMPLINGMODE,
  388. type: texture.type,
  389. format: Constants.TEXTUREFORMAT_RGBA
  390. });
  391. }
  392. else {
  393. texture._isRGBD = true;
  394. texture.invertY = true;
  395. // In case of missing support, applies the same patch than DDS files.
  396. if (generateNonLODTextures) {
  397. let mipSlices = 3;
  398. let scale = texture._lodGenerationScale;
  399. let offset = texture._lodGenerationOffset;
  400. for (let i = 0; i < mipSlices; i++) {
  401. //compute LOD from even spacing in smoothness (matching shader calculation)
  402. let smoothness = i / (mipSlices - 1);
  403. let roughness = 1 - smoothness;
  404. let minLODIndex = offset; // roughness = 0
  405. let maxLODIndex = (mipmapsCount - 1) * scale + offset; // roughness = 1 (mipmaps start from 0)
  406. let lodIndex = minLODIndex + (maxLODIndex - minLODIndex) * roughness;
  407. let mipmapIndex = Math.round(Math.min(Math.max(lodIndex, 0), maxLODIndex));
  408. let glTextureFromLod = new InternalTexture(engine, InternalTextureSource.Temp);
  409. glTextureFromLod.isCube = true;
  410. glTextureFromLod.invertY = true;
  411. glTextureFromLod.generateMipMaps = false;
  412. engine.updateTextureSamplingMode(Constants.TEXTURE_LINEAR_LINEAR, glTextureFromLod);
  413. // Wrap in a base texture for easy binding.
  414. let lodTexture = new BaseTexture(null);
  415. lodTexture.isCube = true;
  416. lodTexture._texture = glTextureFromLod;
  417. lodTextures![mipmapIndex] = lodTexture;
  418. switch (i) {
  419. case 0:
  420. texture._lodTextureLow = lodTexture;
  421. break;
  422. case 1:
  423. texture._lodTextureMid = lodTexture;
  424. break;
  425. case 2:
  426. texture._lodTextureHigh = lodTexture;
  427. break;
  428. }
  429. }
  430. }
  431. }
  432. let promises: Promise<void>[] = [];
  433. // All mipmaps up to provided number of images
  434. for (let i = 0; i < imageData.length; i++) {
  435. // All faces
  436. for (let face = 0; face < 6; face++) {
  437. // Constructs an image element from image data
  438. let bytes = imageData[i][face];
  439. let blob = new Blob([bytes], { type: 'image/png' });
  440. let url = URL.createObjectURL(blob);
  441. let promise: Promise<void>;
  442. if (typeof Image === "undefined" || ThinEngine.Features.forceBitmapOverHTMLImageElement) {
  443. promise = createImageBitmap(blob, { premultiplyAlpha: "none" }).then((img) => {
  444. return this._OnImageReadyAsync(img, engine, expandTexture, rgbdPostProcess, url, face, i, generateNonLODTextures, lodTextures, cubeRtt, texture);
  445. });
  446. } else {
  447. let image = new Image();
  448. image.src = url;
  449. // Enqueue promise to upload to the texture.
  450. promise = new Promise<void>((resolve, reject) => {
  451. image.onload = () => {
  452. this._OnImageReadyAsync(image, engine, expandTexture, rgbdPostProcess, url, face, i, generateNonLODTextures, lodTextures, cubeRtt, texture)
  453. .then(() => resolve())
  454. .catch((reason) => {
  455. reject(reason);
  456. });
  457. };
  458. image.onerror = (error) => {
  459. reject(error);
  460. };
  461. });
  462. }
  463. promises.push(promise);
  464. }
  465. }
  466. // Fill remaining mipmaps with black textures.
  467. if (imageData.length < mipmapsCount) {
  468. let data: ArrayBufferView;
  469. const size = Math.pow(2, mipmapsCount - 1 - imageData.length);
  470. const dataLength = size * size * 4;
  471. switch (texture.type) {
  472. case Constants.TEXTURETYPE_UNSIGNED_INT: {
  473. data = new Uint8Array(dataLength);
  474. break;
  475. }
  476. case Constants.TEXTURETYPE_HALF_FLOAT: {
  477. data = new Uint16Array(dataLength);
  478. break;
  479. }
  480. case Constants.TEXTURETYPE_FLOAT: {
  481. data = new Float32Array(dataLength);
  482. break;
  483. }
  484. }
  485. for (let i = imageData.length; i < mipmapsCount; i++) {
  486. for (let face = 0; face < 6; face++) {
  487. engine._uploadArrayBufferViewToTexture(texture, data!, face, i);
  488. }
  489. }
  490. }
  491. // Once all done, finishes the cleanup and return
  492. return Promise.all(promises).then(() => {
  493. // Release temp RTT.
  494. if (cubeRtt) {
  495. engine._releaseFramebufferObjects(cubeRtt);
  496. engine._releaseTexture(texture);
  497. cubeRtt._swapAndDie(texture);
  498. }
  499. // Release temp Post Process.
  500. if (rgbdPostProcess) {
  501. rgbdPostProcess.dispose();
  502. }
  503. // Flag internal texture as ready in case they are in use.
  504. if (generateNonLODTextures) {
  505. if (texture._lodTextureHigh && texture._lodTextureHigh._texture) {
  506. texture._lodTextureHigh._texture.isReady = true;
  507. }
  508. if (texture._lodTextureMid && texture._lodTextureMid._texture) {
  509. texture._lodTextureMid._texture.isReady = true;
  510. }
  511. if (texture._lodTextureLow && texture._lodTextureLow._texture) {
  512. texture._lodTextureLow._texture.isReady = true;
  513. }
  514. }
  515. });
  516. }
  517. /**
  518. * Uploads spherical polynomials information to the texture.
  519. * @param texture defines the texture we are trying to upload the information to
  520. * @param info defines the environment texture info retrieved through the GetEnvInfo method
  521. */
  522. public static UploadEnvSpherical(texture: InternalTexture, info: EnvironmentTextureInfo): void {
  523. if (info.version !== 1) {
  524. Logger.Warn('Unsupported babylon environment map version "' + info.version + '"');
  525. }
  526. let irradianceInfo = info.irradiance as EnvironmentTextureIrradianceInfoV1;
  527. if (!irradianceInfo) {
  528. return;
  529. }
  530. const sp = new SphericalPolynomial();
  531. Vector3.FromArrayToRef(irradianceInfo.x, 0, sp.x);
  532. Vector3.FromArrayToRef(irradianceInfo.y, 0, sp.y);
  533. Vector3.FromArrayToRef(irradianceInfo.z, 0, sp.z);
  534. Vector3.FromArrayToRef(irradianceInfo.xx, 0, sp.xx);
  535. Vector3.FromArrayToRef(irradianceInfo.yy, 0, sp.yy);
  536. Vector3.FromArrayToRef(irradianceInfo.zz, 0, sp.zz);
  537. Vector3.FromArrayToRef(irradianceInfo.yz, 0, sp.yz);
  538. Vector3.FromArrayToRef(irradianceInfo.zx, 0, sp.zx);
  539. Vector3.FromArrayToRef(irradianceInfo.xy, 0, sp.xy);
  540. texture._sphericalPolynomial = sp;
  541. }
  542. /** @hidden */
  543. public static _UpdateRGBDAsync(internalTexture: InternalTexture, data: ArrayBufferView[][], sphericalPolynomial: Nullable<SphericalPolynomial>, lodScale: number, lodOffset: number): Promise<void> {
  544. internalTexture._source = InternalTextureSource.CubeRawRGBD;
  545. internalTexture._bufferViewArrayArray = data;
  546. internalTexture._lodGenerationScale = lodScale;
  547. internalTexture._lodGenerationOffset = lodOffset;
  548. internalTexture._sphericalPolynomial = sphericalPolynomial;
  549. return EnvironmentTextureTools.UploadLevelsAsync(internalTexture, data).then(() => {
  550. internalTexture.isReady = true;
  551. });
  552. }
  553. }
  554. // References the dependencies.
  555. InternalTexture._UpdateRGBDAsync = EnvironmentTextureTools._UpdateRGBDAsync;