babylon.environmentTextureTools.ts 25 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554
  1. module BABYLON {
  2. /**
  3. * Raw texture data and descriptor sufficient for WebGL texture upload
  4. */
  5. export interface EnvironmentTextureInfo {
  6. /**
  7. * Version of the environment map
  8. */
  9. version: number;
  10. /**
  11. * Width of image
  12. */
  13. width: number;
  14. /**
  15. * Irradiance information stored in the file.
  16. */
  17. irradiance: any;
  18. /**
  19. * Specular information stored in the file.
  20. */
  21. specular: any;
  22. }
  23. /**
  24. * Defines One Image in the file. It requires only the position in the file
  25. * as well as the length.
  26. */
  27. interface BufferImageData {
  28. /**
  29. * Length of the image data.
  30. */
  31. length: number;
  32. /**
  33. * Position of the data from the null terminator delimiting the end of the JSON.
  34. */
  35. position: number;
  36. }
  37. /**
  38. * Defines the specular data enclosed in the file.
  39. * This corresponds to the version 1 of the data.
  40. */
  41. interface EnvironmentTextureSpecularInfoV1 {
  42. /**
  43. * Defines where the specular Payload is located. It is a runtime value only not stored in the file.
  44. */
  45. specularDataPosition?: number;
  46. /**
  47. * This contains all the images data needed to reconstruct the cubemap.
  48. */
  49. mipmaps: Array<BufferImageData>
  50. }
  51. /**
  52. * Defines the required storage to save the environment irradiance information.
  53. */
  54. interface EnvironmentTextureIrradianceInfoV1 {
  55. x: Array<number>;
  56. y: Array<number>;
  57. z: Array<number>;
  58. xx: Array<number>;
  59. yy: Array<number>;
  60. zz: Array<number>;
  61. yz: Array<number>;
  62. zx: Array<number>;
  63. xy: Array<number>;
  64. }
  65. /**
  66. * Sets of helpers addressing the serialization and deserialization of environment texture
  67. * stored in a BabylonJS env file.
  68. * Those files are usually stored as .env files.
  69. */
  70. export class EnvironmentTextureTools {
  71. /**
  72. * Magic number identifying the env file.
  73. */
  74. private static _MagicBytes = [0x86, 0x16, 0x87, 0x96, 0xf6, 0xd6, 0x96, 0x36];
  75. /**
  76. * Gets the environment info from an env file.
  77. * @param data The array buffer containing the .env bytes.
  78. * @returns the environment file info (the json header) if successfully parsed.
  79. */
  80. public static GetEnvInfo(data: ArrayBuffer): Nullable<EnvironmentTextureInfo> {
  81. let dataView = new DataView(data);
  82. let pos = 0;
  83. for (let i = 0; i < EnvironmentTextureTools._MagicBytes.length; i++) {
  84. if (dataView.getUint8(pos++) !== EnvironmentTextureTools._MagicBytes[i]) {
  85. Tools.Error('Not a babylon environment map');
  86. return null;
  87. }
  88. }
  89. // Read json manifest - collect characters up to null terminator
  90. let manifestString = '';
  91. let charCode = 0x00;
  92. while ((charCode = dataView.getUint8(pos++))) {
  93. manifestString += String.fromCharCode(charCode);
  94. }
  95. let manifest: EnvironmentTextureInfo = JSON.parse(manifestString);
  96. if (manifest.specular) {
  97. // Extend the header with the position of the payload.
  98. manifest.specular.specularDataPosition = pos;
  99. }
  100. return manifest;
  101. }
  102. /**
  103. * Creates an environment texture from a loaded cube texture.
  104. * @param texture defines the cube texture to convert in env file
  105. * @return a promise containing the environment data if succesfull.
  106. */
  107. public static CreateEnvTextureAsync(texture: CubeTexture): Promise<ArrayBuffer> {
  108. let internalTexture = texture.getInternalTexture();
  109. if (!internalTexture) {
  110. return Promise.reject("The cube texture is invalid.");
  111. }
  112. if (!texture._prefiltered) {
  113. return Promise.reject("The cube texture is invalid (not prefiltered).");
  114. }
  115. let engine = internalTexture.getEngine();
  116. if (engine && engine.premultipliedAlpha) {
  117. return Promise.reject("Env texture can only be created when the engine is created with the premultipliedAlpha option set to false.");
  118. }
  119. let canvas = engine.getRenderingCanvas();
  120. if (!canvas) {
  121. return Promise.reject("Env texture can only be created when the engine is associated to a canvas.");
  122. }
  123. let textureType = Engine.TEXTURETYPE_FLOAT;
  124. if (!engine.getCaps().textureFloatRender) {
  125. textureType = Engine.TEXTURETYPE_HALF_FLOAT;
  126. if (!engine.getCaps().textureHalfFloatRender) {
  127. return Promise.reject("Env texture can only be created when the browser supports half float or full float rendering.");
  128. }
  129. }
  130. let cubeWidth = internalTexture.width;
  131. let hostingScene = new Scene(engine);
  132. let specularTextures: { [key: number]: ArrayBuffer } = {};
  133. let promises: Promise<void>[] = [];
  134. // Read and collect all mipmaps data from the cube.
  135. let mipmapsCount = Scalar.Log2(internalTexture.width);
  136. mipmapsCount = Math.round(mipmapsCount);
  137. for (let i = 0; i <= mipmapsCount; i++) {
  138. let faceWidth = Math.pow(2, mipmapsCount - i);
  139. // All faces of the cube.
  140. for (let face = 0; face < 6; face++) {
  141. let data = texture.readPixels(face, i);
  142. // Creates a temp texture with the face data.
  143. let tempTexture = engine.createRawTexture(data, faceWidth, faceWidth, Engine.TEXTUREFORMAT_RGBA, false, false, Texture.NEAREST_SAMPLINGMODE, null, textureType);
  144. // And rgbdEncode them.
  145. let promise = new Promise<void>((resolve, reject) => {
  146. let rgbdPostProcess = new PostProcess("rgbdEncode", "rgbdEncode", null, null, 1, null, Texture.NEAREST_SAMPLINGMODE, engine, false, undefined, Engine.TEXTURETYPE_UNSIGNED_INT, undefined, null, false);
  147. rgbdPostProcess.getEffect().executeWhenCompiled(() => {
  148. rgbdPostProcess.onApply = (effect) => {
  149. effect._bindTexture("textureSampler", tempTexture);
  150. }
  151. // As the process needs to happen on the main canvas, keep track of the current size
  152. let currentW = engine.getRenderWidth();
  153. let currentH = engine.getRenderHeight();
  154. // Set the desired size for the texture
  155. engine.setSize(faceWidth, faceWidth);
  156. hostingScene.postProcessManager.directRender([rgbdPostProcess], null);
  157. // Reading datas from WebGL
  158. Tools.ToBlob(canvas!, (blob) => {
  159. let fileReader = new FileReader();
  160. fileReader.onload = (event: any) => {
  161. let arrayBuffer = event.target!.result as ArrayBuffer;
  162. specularTextures[i * 6 + face] = arrayBuffer;
  163. resolve();
  164. };
  165. fileReader.readAsArrayBuffer(blob!);
  166. });
  167. // Reapply the previous canvas size
  168. engine.setSize(currentW, currentH);
  169. });
  170. });
  171. promises.push(promise);
  172. }
  173. }
  174. // Once all the textures haves been collected as RGBD stored in PNGs
  175. return Promise.all(promises).then(() => {
  176. // We can delete the hosting scene keeping track of all the creation objects
  177. hostingScene.dispose();
  178. // Creates the json header for the env texture
  179. let info: EnvironmentTextureInfo = {
  180. version: 1,
  181. width: cubeWidth,
  182. irradiance: this._CreateEnvTextureIrradiance(texture),
  183. specular: {
  184. mipmaps: []
  185. }
  186. };
  187. // Sets the specular image data information
  188. let position = 0;
  189. for (let i = 0; i <= mipmapsCount; i++) {
  190. for (let face = 0; face < 6; face++) {
  191. let byteLength = specularTextures[i * 6 + face].byteLength;
  192. info.specular.mipmaps.push({
  193. length: byteLength,
  194. position: position
  195. });
  196. position += byteLength;
  197. }
  198. }
  199. // Encode the JSON as an array buffer
  200. let infoString = JSON.stringify(info);
  201. let infoBuffer = new ArrayBuffer(infoString.length + 1);
  202. let infoView = new Uint8Array(infoBuffer); // Limited to ascii subset matching unicode.
  203. for (let i = 0, strLen = infoString.length; i < strLen; i++) {
  204. infoView[i] = infoString.charCodeAt(i);
  205. }
  206. // Ends up with a null terminator for easier parsing
  207. infoView[infoString.length] = 0x00;
  208. // Computes the final required size and creates the storage
  209. let totalSize = EnvironmentTextureTools._MagicBytes.length + position + infoBuffer.byteLength;
  210. let finalBuffer = new ArrayBuffer(totalSize);
  211. let finalBufferView = new Uint8Array(finalBuffer);
  212. let dataView = new DataView(finalBuffer);
  213. // Copy the magic bytes identifying the file in
  214. let pos = 0;
  215. for (let i = 0; i < EnvironmentTextureTools._MagicBytes.length; i++) {
  216. dataView.setUint8(pos++, EnvironmentTextureTools._MagicBytes[i]);
  217. }
  218. // Add the json info
  219. finalBufferView.set(new Uint8Array(infoBuffer), pos);
  220. pos += infoBuffer.byteLength;
  221. // Finally inserts the texture data
  222. for (let i = 0; i <= mipmapsCount; i++) {
  223. for (let face = 0; face < 6; face++) {
  224. let dataBuffer = specularTextures[i * 6 + face];
  225. finalBufferView.set(new Uint8Array(dataBuffer), pos);
  226. pos += dataBuffer.byteLength;
  227. }
  228. }
  229. // Voila
  230. return finalBuffer;
  231. });
  232. }
  233. /**
  234. * Creates a JSON representation of the spherical data.
  235. * @param texture defines the texture containing the polynomials
  236. * @return the JSON representation of the spherical info
  237. */
  238. private static _CreateEnvTextureIrradiance(texture: CubeTexture): Nullable<EnvironmentTextureIrradianceInfoV1> {
  239. let polynmials = texture.sphericalPolynomial;
  240. if (polynmials == null) {
  241. return null;
  242. }
  243. return {
  244. x: [polynmials.x.x, polynmials.x.y, polynmials.x.z],
  245. y: [polynmials.y.x, polynmials.y.y, polynmials.y.z],
  246. z: [polynmials.z.x, polynmials.z.y, polynmials.z.z],
  247. xx: [polynmials.xx.x, polynmials.xx.y, polynmials.xx.z],
  248. yy: [polynmials.yy.x, polynmials.yy.y, polynmials.yy.z],
  249. zz: [polynmials.zz.x, polynmials.zz.y, polynmials.zz.z],
  250. yz: [polynmials.yz.x, polynmials.yz.y, polynmials.yz.z],
  251. zx: [polynmials.zx.x, polynmials.zx.y, polynmials.zx.z],
  252. xy: [polynmials.xy.x, polynmials.xy.y, polynmials.xy.z]
  253. } as any;
  254. }
  255. /**
  256. * Uploads the texture info contained in the env file to the GPU.
  257. * @param texture defines the internal texture to upload to
  258. * @param arrayBuffer defines the buffer cotaining the data to load
  259. * @param info defines the texture info retrieved through the GetEnvInfo method
  260. * @returns a promise
  261. */
  262. public static UploadEnvLevelsAsync(texture: InternalTexture, arrayBuffer: any, info: EnvironmentTextureInfo): Promise<void> {
  263. if (info.version !== 1) {
  264. Tools.Warn('Unsupported babylon environment map version "' + info.version + '"');
  265. }
  266. let specularInfo = info.specular as EnvironmentTextureSpecularInfoV1;
  267. if (!specularInfo) {
  268. // Nothing else parsed so far
  269. return Promise.resolve();
  270. }
  271. // Double checks the enclosed info
  272. let mipmapsCount = Scalar.Log2(info.width);
  273. mipmapsCount = Math.round(mipmapsCount) + 1;
  274. if (specularInfo.mipmaps.length !== 6 * mipmapsCount) {
  275. Tools.Warn('Unsupported specular mipmaps number "' + specularInfo.mipmaps.length + '"');
  276. }
  277. const imageData = new Array<Array<ArrayBufferView>>(mipmapsCount);
  278. for (let i = 0; i < mipmapsCount; i++) {
  279. imageData[i] = new Array<ArrayBufferView>(6);
  280. for (let face = 0; face < 6; face++) {
  281. const imageInfo = specularInfo.mipmaps[i * 6 + face];
  282. imageData[i][face] = new Uint8Array(arrayBuffer, specularInfo.specularDataPosition! + imageInfo.position, imageInfo.length);
  283. }
  284. }
  285. return EnvironmentTextureTools.UploadLevelsAsync(texture, imageData);
  286. }
  287. /**
  288. * Uploads the levels of image data to the GPU.
  289. * @param texture defines the internal texture to upload to
  290. * @param imageData defines the array buffer views of image data [mipmap][face]
  291. * @returns a promise
  292. */
  293. public static UploadLevelsAsync(texture: InternalTexture, imageData: ArrayBufferView[][]): Promise<void> {
  294. const mipmapsCount = imageData.length;
  295. // Gets everything ready.
  296. let engine = texture.getEngine();
  297. let expandTexture = false;
  298. let generateNonLODTextures = false;
  299. let rgbdPostProcess: Nullable<PostProcess> = null;
  300. let cubeRtt: Nullable<InternalTexture> = null;
  301. let lodTextures: Nullable<{ [lod: number]: BaseTexture }> = null;
  302. let caps = engine.getCaps();
  303. texture.format = Engine.TEXTUREFORMAT_RGBA;
  304. texture.type = Engine.TEXTURETYPE_UNSIGNED_INT;
  305. texture.samplingMode = Texture.TRILINEAR_SAMPLINGMODE;
  306. // Add extra process if texture lod is not supported
  307. if (!caps.textureLOD) {
  308. expandTexture = false;
  309. generateNonLODTextures = true;
  310. lodTextures = {};
  311. }
  312. // in webgl 1 there are no ways to either render or copy lod level information for float textures.
  313. else if (engine.webGLVersion < 2) {
  314. expandTexture = false;
  315. }
  316. // If half float available we can uncompress the texture
  317. else if (caps.textureHalfFloatRender && caps.textureHalfFloatLinearFiltering) {
  318. expandTexture = true;
  319. texture.type = Engine.TEXTURETYPE_HALF_FLOAT;
  320. }
  321. // If full float available we can uncompress the texture
  322. else if (caps.textureFloatRender && caps.textureFloatLinearFiltering) {
  323. expandTexture = true;
  324. texture.type = Engine.TEXTURETYPE_FLOAT;
  325. }
  326. // Expand the texture if possible
  327. if (expandTexture) {
  328. // Simply run through the decode PP
  329. rgbdPostProcess = new PostProcess("rgbdDecode", "rgbdDecode", null, null, 1, null, Texture.TRILINEAR_SAMPLINGMODE, engine, false, undefined, texture.type, undefined, null, false);
  330. texture._isRGBD = false;
  331. texture.invertY = false;
  332. cubeRtt = engine.createRenderTargetCubeTexture(texture.width, {
  333. generateDepthBuffer: false,
  334. generateMipMaps: true,
  335. generateStencilBuffer: false,
  336. samplingMode: Texture.TRILINEAR_SAMPLINGMODE,
  337. type: texture.type,
  338. format: Engine.TEXTUREFORMAT_RGBA
  339. });
  340. }
  341. else {
  342. texture._isRGBD = true;
  343. texture.invertY = true;
  344. // In case of missing support, applies the same patch than DDS files.
  345. if (generateNonLODTextures) {
  346. let mipSlices = 3;
  347. let scale = texture._lodGenerationScale;
  348. let offset = texture._lodGenerationOffset;
  349. for (let i = 0; i < mipSlices; i++) {
  350. //compute LOD from even spacing in smoothness (matching shader calculation)
  351. let smoothness = i / (mipSlices - 1);
  352. let roughness = 1 - smoothness;
  353. let minLODIndex = offset; // roughness = 0
  354. let maxLODIndex = (mipmapsCount - 1) * scale + offset; // roughness = 1 (mipmaps start from 0)
  355. let lodIndex = minLODIndex + (maxLODIndex - minLODIndex) * roughness;
  356. let mipmapIndex = Math.round(Math.min(Math.max(lodIndex, 0), maxLODIndex));
  357. let glTextureFromLod = new InternalTexture(engine, InternalTexture.DATASOURCE_TEMP);
  358. glTextureFromLod.isCube = true;
  359. glTextureFromLod.invertY = true;
  360. glTextureFromLod.generateMipMaps = false;
  361. engine.updateTextureSamplingMode(Texture.LINEAR_LINEAR, glTextureFromLod);
  362. // Wrap in a base texture for easy binding.
  363. let lodTexture = new BaseTexture(null);
  364. lodTexture.isCube = true;
  365. lodTexture._texture = glTextureFromLod;
  366. lodTextures![mipmapIndex] = lodTexture;
  367. switch (i) {
  368. case 0:
  369. texture._lodTextureLow = lodTexture;
  370. break;
  371. case 1:
  372. texture._lodTextureMid = lodTexture;
  373. break;
  374. case 2:
  375. texture._lodTextureHigh = lodTexture;
  376. break;
  377. }
  378. }
  379. }
  380. }
  381. let promises: Promise<void>[] = [];
  382. // All mipmaps
  383. for (let i = 0; i < mipmapsCount; i++) {
  384. // All faces
  385. for (let face = 0; face < 6; face++) {
  386. // Constructs an image element from image data
  387. let bytes = imageData[i][face];
  388. let blob = new Blob([bytes], { type: 'image/png' });
  389. let url = URL.createObjectURL(blob);
  390. let image = new Image();
  391. image.src = url;
  392. // Enqueue promise to upload to the texture.
  393. let promise = new Promise<void>((resolve, reject) => {
  394. image.onload = () => {
  395. if (expandTexture) {
  396. let tempTexture = engine.createTexture(null, true, true, null, Texture.NEAREST_SAMPLINGMODE, null,
  397. (message) => {
  398. reject(message);
  399. },
  400. image);
  401. rgbdPostProcess!.getEffect().executeWhenCompiled(() => {
  402. // Uncompress the data to a RTT
  403. rgbdPostProcess!.onApply = (effect) => {
  404. effect._bindTexture("textureSampler", tempTexture);
  405. effect.setFloat2("scale", 1, 1);
  406. }
  407. engine.scenes[0].postProcessManager.directRender([rgbdPostProcess!], cubeRtt, true, face, i);
  408. // Cleanup
  409. engine.restoreDefaultFramebuffer();
  410. tempTexture.dispose();
  411. window.URL.revokeObjectURL(url);
  412. resolve();
  413. });
  414. }
  415. else {
  416. engine._uploadImageToTexture(texture, image, face, i);
  417. // Upload the face to the none lod texture support
  418. if (generateNonLODTextures) {
  419. let lodTexture = lodTextures![i];
  420. if (lodTexture) {
  421. engine._uploadImageToTexture(lodTexture._texture!, image, face, 0);
  422. }
  423. }
  424. resolve();
  425. }
  426. };
  427. image.onerror = (error) => {
  428. reject(error);
  429. };
  430. });
  431. promises.push(promise);
  432. }
  433. }
  434. // Once all done, finishes the cleanup and return
  435. return Promise.all(promises).then(() => {
  436. // Relase temp RTT.
  437. if (cubeRtt) {
  438. engine._releaseFramebufferObjects(cubeRtt);
  439. cubeRtt._swapAndDie(texture);
  440. }
  441. // Relase temp Post Process.
  442. if (rgbdPostProcess) {
  443. rgbdPostProcess.dispose();
  444. }
  445. // Flag internal texture as ready in case they are in use.
  446. if (generateNonLODTextures) {
  447. if (texture._lodTextureHigh && texture._lodTextureHigh._texture) {
  448. texture._lodTextureHigh._texture.isReady = true;
  449. }
  450. if (texture._lodTextureMid && texture._lodTextureMid._texture) {
  451. texture._lodTextureMid._texture.isReady = true;
  452. }
  453. if (texture._lodTextureLow && texture._lodTextureLow._texture) {
  454. texture._lodTextureLow._texture.isReady = true;
  455. }
  456. }
  457. });
  458. }
  459. /**
  460. * Uploads spherical polynomials information to the texture.
  461. * @param texture defines the texture we are trying to upload the information to
  462. * @param info defines the environment texture info retrieved through the GetEnvInfo method
  463. */
  464. public static UploadEnvSpherical(texture: InternalTexture, info: EnvironmentTextureInfo): void {
  465. if (info.version !== 1) {
  466. Tools.Warn('Unsupported babylon environment map version "' + info.version + '"');
  467. }
  468. let irradianceInfo = info.irradiance as EnvironmentTextureIrradianceInfoV1;
  469. if (!irradianceInfo) {
  470. return;
  471. }
  472. const sp = new SphericalPolynomial();
  473. Vector3.FromArrayToRef(irradianceInfo.x, 0, sp.x);
  474. Vector3.FromArrayToRef(irradianceInfo.y, 0, sp.y);
  475. Vector3.FromArrayToRef(irradianceInfo.z, 0, sp.z);
  476. Vector3.FromArrayToRef(irradianceInfo.xx, 0, sp.xx);
  477. Vector3.FromArrayToRef(irradianceInfo.yy, 0, sp.yy);
  478. Vector3.FromArrayToRef(irradianceInfo.zz, 0, sp.zz);
  479. Vector3.FromArrayToRef(irradianceInfo.yz, 0, sp.yz);
  480. Vector3.FromArrayToRef(irradianceInfo.zx, 0, sp.zx);
  481. Vector3.FromArrayToRef(irradianceInfo.xy, 0, sp.xy);
  482. texture._sphericalPolynomial = sp;
  483. }
  484. }
  485. }