KTX2Loader.js 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719
  1. /**
  2. * @author donmccurdy / https://www.donmccurdy.com
  3. * @author MarkCallow / https://github.com/MarkCallow
  4. *
  5. * References:
  6. * - KTX: http://github.khronos.org/KTX-Specification/
  7. * - DFD: https://www.khronos.org/registry/DataFormat/specs/1.3/dataformat.1.3.html#basicdescriptor
  8. *
  9. * To do:
  10. * - [ ] Cross-platform testing
  11. * - [ ] Specify JS/WASM transcoder path
  12. * - [ ] High-quality demo
  13. * - [ ] Documentation
  14. * - [ ] TypeScript definitions
  15. * - [ ] (Optional) Include BC5
  16. * - [ ] (Optional) Include EAC RG on mobile (WEBGL_compressed_texture_etc)
  17. * - [ ] (Optional) Include two-texture output mode (see: clearcoat + clearcoatRoughness)
  18. * - [ ] (Optional) Support Web Workers, after #18234
  19. */
  20. import {
  21. CompressedTexture,
  22. CompressedTextureLoader,
  23. FileLoader,
  24. LinearEncoding,
  25. LinearFilter,
  26. LinearMipmapLinearFilter,
  27. MathUtils,
  28. RGBAFormat,
  29. RGBA_ASTC_4x4_Format,
  30. RGBA_BPTC_Format,
  31. RGBA_ETC2_EAC_Format,
  32. RGBA_PVRTC_4BPPV1_Format,
  33. RGBA_S3TC_DXT5_Format,
  34. RGB_ETC1_Format,
  35. RGB_ETC2_Format,
  36. RGB_PVRTC_4BPPV1_Format,
  37. RGB_S3TC_DXT1_Format,
  38. UnsignedByteType,
  39. sRGBEncoding,
  40. } from '../../../build/three.module.js';
  41. // Data Format Descriptor (DFD) constants.
  42. const DFDModel = {
  43. ETC1S: 163,
  44. UASTC: 166,
  45. }
  46. const DFDChannel = {
  47. ETC1S: {
  48. RGB: 0,
  49. RRR: 3,
  50. GGG: 4,
  51. AAA: 15,
  52. },
  53. UASTC: {
  54. RGB: 0,
  55. RGBA: 3,
  56. RRR: 4,
  57. RRRG: 5
  58. },
  59. };
  60. //
  61. class KTX2Loader extends CompressedTextureLoader {
  62. constructor ( manager ) {
  63. super( manager );
  64. this.basisModule = null;
  65. this.basisModulePending = null;
  66. this.transcoderConfig = {};
  67. }
  68. detectSupport ( renderer ) {
  69. this.transcoderConfig = {
  70. astcSupported: renderer.extensions.has( 'WEBGL_compressed_texture_astc' ),
  71. etc1Supported: renderer.extensions.has( 'WEBGL_compressed_texture_etc1' ),
  72. etc2Supported: renderer.extensions.has( 'WEBGL_compressed_texture_etc' ),
  73. dxtSupported: renderer.extensions.has( 'WEBGL_compressed_texture_s3tc' ),
  74. bptcSupported: renderer.extensions.has( 'EXT_texture_compression_bptc' ),
  75. pvrtcSupported: renderer.extensions.has( 'WEBGL_compressed_texture_pvrtc' )
  76. || renderer.extensions.has( 'WEBKIT_WEBGL_compressed_texture_pvrtc' )
  77. };
  78. return this;
  79. }
  80. initModule () {
  81. if ( this.basisModulePending ) {
  82. return;
  83. }
  84. var scope = this;
  85. // The Emscripten wrapper returns a fake Promise, which can cause
  86. // infinite recursion when mixed with native Promises. Wrap the module
  87. // initialization to return a native Promise.
  88. scope.basisModulePending = new Promise( function ( resolve ) {
  89. MSC_TRANSCODER().then( function ( basisModule ) {
  90. scope.basisModule = basisModule;
  91. basisModule.initTranscoders();
  92. resolve();
  93. } );
  94. } );
  95. }
  96. load ( url, onLoad, onProgress, onError ) {
  97. var scope = this;
  98. var texture = new CompressedTexture();
  99. var bufferPending = new Promise( function (resolve, reject ) {
  100. new FileLoader( scope.manager )
  101. .setPath( scope.path )
  102. .setResponseType( 'arraybuffer' )
  103. .load( url, resolve, onProgress, reject );
  104. } );
  105. this.initModule();
  106. Promise.all( [ bufferPending, this.basisModulePending ] ).then( function ( [ buffer ] ) {
  107. scope.parse( buffer, function ( _texture ) {
  108. texture.copy( _texture );
  109. texture.needsUpdate = true;
  110. if ( onLoad ) onLoad( texture );
  111. }, onError );
  112. } );
  113. return texture;
  114. }
  115. parse ( buffer, onLoad, onError ) {
  116. var BasisLzEtc1sImageTranscoder = this.basisModule.BasisLzEtc1sImageTranscoder;
  117. var UastcImageTranscoder = this.basisModule.UastcImageTranscoder;
  118. var TextureFormat = this.basisModule.TextureFormat;
  119. var ktx = new KTX2Container( this.basisModule, buffer );
  120. // TODO(donmccurdy): Should test if texture is transcodable before attempting
  121. // any transcoding. If supercompressionScheme is KTX_SS_BASIS_LZ and dfd
  122. // colorModel is ETC1S (163) or if dfd colorModel is UASTCF (166)
  123. // then texture must be transcoded.
  124. var transcoder = ktx.getTexFormat() === TextureFormat.UASTC4x4
  125. ? new UastcImageTranscoder()
  126. : new BasisLzEtc1sImageTranscoder();
  127. ktx.initMipmaps( transcoder, this.transcoderConfig )
  128. .then( function () {
  129. var texture = new CompressedTexture(
  130. ktx.mipmaps,
  131. ktx.getWidth(),
  132. ktx.getHeight(),
  133. ktx.transcodedFormat,
  134. UnsignedByteType
  135. );
  136. texture.encoding = ktx.getEncoding();
  137. texture.premultiplyAlpha = ktx.getPremultiplyAlpha();
  138. texture.minFilter = ktx.mipmaps.length === 1 ? LinearFilter : LinearMipmapLinearFilter;
  139. texture.magFilter = LinearFilter;
  140. onLoad( texture );
  141. } )
  142. .catch( onError );
  143. return this;
  144. }
  145. }
  146. class KTX2Container {
  147. constructor ( basisModule, arrayBuffer ) {
  148. this.basisModule = basisModule;
  149. this.arrayBuffer = arrayBuffer;
  150. this.mipmaps = null;
  151. this.transcodedFormat = null;
  152. // Confirm this is a KTX 2.0 file, based on the identifier in the first 12 bytes.
  153. var idByteLength = 12;
  154. var id = new Uint8Array( this.arrayBuffer, 0, idByteLength );
  155. if ( id[ 0 ] !== 0xAB || // '´'
  156. id[ 1 ] !== 0x4B || // 'K'
  157. id[ 2 ] !== 0x54 || // 'T'
  158. id[ 3 ] !== 0x58 || // 'X'
  159. id[ 4 ] !== 0x20 || // ' '
  160. id[ 5 ] !== 0x32 || // '2'
  161. id[ 6 ] !== 0x30 || // '0'
  162. id[ 7 ] !== 0xBB || // 'ª'
  163. id[ 8 ] !== 0x0D || // '\r'
  164. id[ 9 ] !== 0x0A || // '\n'
  165. id[ 10 ] !== 0x1A || // '\x1A'
  166. id[ 11 ] !== 0x0A // '\n'
  167. ) {
  168. throw new Error( 'THREE.KTX2Loader: Missing KTX 2.0 identifier.' );
  169. }
  170. // TODO(donmccurdy): If we need to support BE, derive this from typeSize.
  171. var littleEndian = true;
  172. ///////////////////////////////////////////////////
  173. // Header.
  174. ///////////////////////////////////////////////////
  175. var headerByteLength = 17 * Uint32Array.BYTES_PER_ELEMENT;
  176. var headerReader = new KTX2BufferReader( this.arrayBuffer, idByteLength, headerByteLength, littleEndian );
  177. this.header = {
  178. vkFormat: headerReader.nextUint32(),
  179. typeSize: headerReader.nextUint32(),
  180. pixelWidth: headerReader.nextUint32(),
  181. pixelHeight: headerReader.nextUint32(),
  182. pixelDepth: headerReader.nextUint32(),
  183. arrayElementCount: headerReader.nextUint32(),
  184. faceCount: headerReader.nextUint32(),
  185. levelCount: headerReader.nextUint32(),
  186. supercompressionScheme: headerReader.nextUint32(),
  187. dfdByteOffset: headerReader.nextUint32(),
  188. dfdByteLength: headerReader.nextUint32(),
  189. kvdByteOffset: headerReader.nextUint32(),
  190. kvdByteLength: headerReader.nextUint32(),
  191. sgdByteOffset: headerReader.nextUint64(),
  192. sgdByteLength: headerReader.nextUint64(),
  193. };
  194. if ( this.header.pixelDepth > 0 ) {
  195. throw new Error( 'THREE.KTX2Loader: Only 2D textures are currently supported.' );
  196. }
  197. if ( this.header.arrayElementCount > 1 ) {
  198. throw new Error( 'THREE.KTX2Loader: Array textures are not currently supported.' );
  199. }
  200. if ( this.header.faceCount > 1 ) {
  201. throw new Error( 'THREE.KTX2Loader: Cube textures are not currently supported.' );
  202. }
  203. ///////////////////////////////////////////////////
  204. // Level index
  205. ///////////////////////////////////////////////////
  206. var levelByteLength = this.header.levelCount * 3 * 8;
  207. var levelReader = new KTX2BufferReader( this.arrayBuffer, idByteLength + headerByteLength, levelByteLength, littleEndian );
  208. this.levels = [];
  209. for ( var i = 0; i < this.header.levelCount; i ++ ) {
  210. this.levels.push( {
  211. byteOffset: levelReader.nextUint64(),
  212. byteLength: levelReader.nextUint64(),
  213. uncompressedByteLength: levelReader.nextUint64(),
  214. } );
  215. }
  216. ///////////////////////////////////////////////////
  217. // Data Format Descriptor (DFD)
  218. ///////////////////////////////////////////////////
  219. var dfdReader = new KTX2BufferReader(
  220. this.arrayBuffer,
  221. this.header.dfdByteOffset,
  222. this.header.dfdByteLength,
  223. littleEndian
  224. );
  225. const sampleStart = 6;
  226. const sampleWords = 4;
  227. this.dfd = {
  228. vendorId: dfdReader.skip( 4 /* totalSize */ ).nextUint16(),
  229. versionNumber: dfdReader.skip( 2 /* descriptorType */ ).nextUint16(),
  230. descriptorBlockSize: dfdReader.nextUint16(),
  231. colorModel: dfdReader.nextUint8(),
  232. colorPrimaries: dfdReader.nextUint8(),
  233. transferFunction: dfdReader.nextUint8(),
  234. flags: dfdReader.nextUint8(),
  235. texelBlockDimension: {
  236. x: dfdReader.nextUint8() + 1,
  237. y: dfdReader.nextUint8() + 1,
  238. z: dfdReader.nextUint8() + 1,
  239. w: dfdReader.nextUint8() + 1,
  240. },
  241. bytesPlane0: dfdReader.nextUint8(),
  242. numSamples: 0,
  243. samples: [],
  244. };
  245. this.dfd.numSamples = ( this.dfd.descriptorBlockSize / 4 - sampleStart ) / sampleWords;
  246. dfdReader.skip( 7 /* bytesPlane[1-7] */ );
  247. for ( var i = 0; i < this.dfd.numSamples; i++ ) {
  248. this.dfd.samples[i] = {
  249. channelID: dfdReader.skip( 3 /* bitOffset + bitLength */ ).nextUint8(),
  250. // ... remainder not implemented.
  251. };
  252. dfdReader.skip( 12 /* samplePosition[0-3], lower, upper */ );
  253. }
  254. if ( this.header.vkFormat !== 0x00 /* VK_FORMAT_UNDEFINED */ &&
  255. ! ( this.header.supercompressionScheme === 1 /* BasisLZ */ ||
  256. this.dfd.colorModel === DFDModel.UASTC ) ) {
  257. throw new Error( 'THREE.KTX2Loader: Only Basis Universal supercompression is currently supported.' );
  258. }
  259. ///////////////////////////////////////////////////
  260. // Key/Value Data (KVD)
  261. ///////////////////////////////////////////////////
  262. // Not implemented.
  263. this.kvd = {};
  264. ///////////////////////////////////////////////////
  265. // Supercompression Global Data (SGD)
  266. ///////////////////////////////////////////////////
  267. this.sgd = {};
  268. if ( this.header.sgdByteLength <= 0 ) return;
  269. var sgdReader = new KTX2BufferReader(
  270. this.arrayBuffer,
  271. this.header.sgdByteOffset,
  272. this.header.sgdByteLength,
  273. littleEndian
  274. );
  275. this.sgd.endpointCount = sgdReader.nextUint16();
  276. this.sgd.selectorCount = sgdReader.nextUint16();
  277. this.sgd.endpointsByteLength = sgdReader.nextUint32();
  278. this.sgd.selectorsByteLength = sgdReader.nextUint32();
  279. this.sgd.tablesByteLength = sgdReader.nextUint32();
  280. this.sgd.extendedByteLength = sgdReader.nextUint32();
  281. this.sgd.imageDescs = [];
  282. this.sgd.endpointsData = null;
  283. this.sgd.selectorsData = null;
  284. this.sgd.tablesData = null;
  285. this.sgd.extendedData = null;
  286. for ( var i = 0; i < this.header.levelCount; i ++ ) {
  287. this.sgd.imageDescs.push( {
  288. imageFlags: sgdReader.nextUint32(),
  289. rgbSliceByteOffset: sgdReader.nextUint32(),
  290. rgbSliceByteLength: sgdReader.nextUint32(),
  291. alphaSliceByteOffset: sgdReader.nextUint32(),
  292. alphaSliceByteLength: sgdReader.nextUint32(),
  293. } );
  294. }
  295. var endpointsByteOffset = this.header.sgdByteOffset + sgdReader.offset;
  296. var selectorsByteOffset = endpointsByteOffset + this.sgd.endpointsByteLength;
  297. var tablesByteOffset = selectorsByteOffset + this.sgd.selectorsByteLength;
  298. var extendedByteOffset = tablesByteOffset + this.sgd.tablesByteLength;
  299. this.sgd.endpointsData = new Uint8Array( this.arrayBuffer, endpointsByteOffset, this.sgd.endpointsByteLength );
  300. this.sgd.selectorsData = new Uint8Array( this.arrayBuffer, selectorsByteOffset, this.sgd.selectorsByteLength );
  301. this.sgd.tablesData = new Uint8Array( this.arrayBuffer, tablesByteOffset, this.sgd.tablesByteLength );
  302. this.sgd.extendedData = new Uint8Array( this.arrayBuffer, extendedByteOffset, this.sgd.extendedByteLength );
  303. }
  304. initMipmaps ( transcoder, config ) {
  305. var TranscodeTarget = this.basisModule.TranscodeTarget;
  306. var TextureFormat = this.basisModule.TextureFormat;
  307. var ImageInfo = this.basisModule.ImageInfo;
  308. var scope = this;
  309. var mipmaps = [];
  310. var width = this.getWidth();
  311. var height = this.getHeight();
  312. var texFormat = this.getTexFormat();
  313. var hasAlpha = this.getAlpha();
  314. var isVideo = false;
  315. // PVRTC1 transcoders (from both ETC1S and UASTC) only support power of 2 dimensions.
  316. var pvrtcTranscodable = MathUtils.isPowerOfTwo( width ) && MathUtils.isPowerOfTwo( height );
  317. if ( texFormat === TextureFormat.ETC1S ) {
  318. var numEndpoints = this.sgd.endpointCount;
  319. var numSelectors = this.sgd.selectorCount;
  320. var endpoints = this.sgd.endpointsData;
  321. var selectors = this.sgd.selectorsData;
  322. var tables = this.sgd.tablesData;
  323. transcoder.decodePalettes( numEndpoints, endpoints, numSelectors, selectors );
  324. transcoder.decodeTables( tables );
  325. }
  326. var targetFormat;
  327. if ( config.astcSupported ) {
  328. targetFormat = TranscodeTarget.ASTC_4x4_RGBA;
  329. this.transcodedFormat = RGBA_ASTC_4x4_Format;
  330. } else if ( config.bptcSupported && texFormat === TextureFormat.UASTC4x4 ) {
  331. targetFormat = hasAlpha ? TranscodeTarget.BC7_M5_RGBA : BC7_M6_RGB;
  332. this.transcodedFormat = RGBA_BPTC_Format;
  333. } else if ( config.dxtSupported ) {
  334. targetFormat = hasAlpha ? TranscodeTarget.BC3_RGBA : TranscodeTarget.BC1_RGB;
  335. this.transcodedFormat = hasAlpha ? RGBA_S3TC_DXT5_Format : RGB_S3TC_DXT1_Format;
  336. } else if ( config.pvrtcSupported && pvrtcTranscodable ) {
  337. targetFormat = hasAlpha ? TranscodeTarget.PVRTC1_4_RGBA : TranscodeTarget.PVRTC1_4_RGB;
  338. this.transcodedFormat = hasAlpha ? RGBA_PVRTC_4BPPV1_Format : RGB_PVRTC_4BPPV1_Format;
  339. } else if ( config.etc2Supported ) {
  340. targetFormat = hasAlpha ? TranscodeTarget.ETC2_RGBA : TranscodeTarget.ETC1_RGB /* subset of ETC2 */;
  341. this.transcodedFormat = hasAlpha ? RGBA_ETC2_EAC_Format : RGB_ETC2_Format;
  342. } else if ( config.etc1Supported ) {
  343. targetFormat = TranscodeTarget.ETC1_RGB;
  344. this.transcodedFormat = RGB_ETC1_Format;
  345. } else {
  346. console.warn( 'THREE.KTX2Loader: No suitable compressed texture format found. Decoding to RGBA32.' );
  347. targetFormat = TranscodeTarget.RGBA32;
  348. this.transcodedFormat = RGBAFormat;
  349. }
  350. if ( ! this.basisModule.isFormatSupported( targetFormat, texFormat ) ) {
  351. throw new Error( 'THREE.KTX2Loader: Selected texture format not supported by current transcoder build.' );
  352. }
  353. var imageDescIndex = 0;
  354. for ( var level = 0; level < this.header.levelCount; level ++ ) {
  355. var levelWidth = width / Math.pow( 2, level );
  356. var levelHeight = height / Math.pow( 2, level );
  357. var numImagesInLevel = 1; // TODO(donmccurdy): Support cubemaps, arrays and 3D.
  358. var imageOffsetInLevel = 0;
  359. var imageInfo = new ImageInfo( texFormat, levelWidth, levelHeight, level );
  360. var levelImageByteLength = imageInfo.numBlocksX * imageInfo.numBlocksY * this.dfd.bytesPlane0;
  361. for ( var imageIndex = 0; imageIndex < numImagesInLevel; imageIndex ++ ) {
  362. var result;
  363. var encodedData;
  364. if ( texFormat === TextureFormat.UASTC4x4 ) {
  365. // UASTC
  366. imageInfo.flags = 0;
  367. imageInfo.rgbByteOffset = 0;
  368. imageInfo.rgbByteLength = levelImageByteLength;
  369. imageInfo.alphaByteOffset = 0;
  370. imageInfo.alphaByteLength = 0;
  371. encodedData = new Uint8Array( this.arrayBuffer, this.levels[ level ].byteOffset + imageOffsetInLevel, levelImageByteLength );
  372. result = transcoder.transcodeImage( targetFormat, encodedData, imageInfo, 0, hasAlpha, isVideo );
  373. } else {
  374. // ETC1S
  375. var imageDesc = this.sgd.imageDescs[ imageDescIndex++ ];
  376. imageInfo.flags = imageDesc.imageFlags;
  377. imageInfo.rgbByteOffset = 0;
  378. imageInfo.rgbByteLength = imageDesc.rgbSliceByteLength;
  379. imageInfo.alphaByteOffset = imageDesc.alphaSliceByteOffset > 0 ? imageDesc.rgbSliceByteLength : 0;
  380. imageInfo.alphaByteLength = imageDesc.alphaSliceByteLength;
  381. encodedData = new Uint8Array( this.arrayBuffer, this.levels[ level ].byteOffset + imageDesc.rgbSliceByteOffset, imageDesc.rgbSliceByteLength + imageDesc.alphaSliceByteLength );
  382. result = transcoder.transcodeImage( targetFormat, encodedData, imageInfo, 0, isVideo );
  383. }
  384. if ( result.transcodedImage === undefined ) {
  385. throw new Error( 'THREE.KTX2Loader: Unable to transcode image.' );
  386. }
  387. // Transcoded image is written in memory allocated by WASM. We could avoid copying
  388. // the image by waiting until the image is uploaded to the GPU, then calling
  389. // delete(). However, (1) we don't know if the user will later need to re-upload it
  390. // e.g. after calling texture.clone(), and (2) this code will eventually be in a
  391. // Web Worker, and transferring WASM's memory seems like a very bad idea.
  392. var levelData = result.transcodedImage.get_typed_memory_view().slice();
  393. result.transcodedImage.delete();
  394. mipmaps.push( { data: levelData, width: levelWidth, height: levelHeight } );
  395. imageOffsetInLevel += levelImageByteLength;
  396. }
  397. }
  398. return new Promise( function ( resolve, reject ) {
  399. scope.mipmaps = mipmaps;
  400. resolve();
  401. } );
  402. }
  403. getWidth () { return this.header.pixelWidth; }
  404. getHeight () { return this.header.pixelHeight; }
  405. getEncoding () {
  406. return this.dfd.transferFunction === 2 /* KHR_DF_TRANSFER_SRGB */
  407. ? sRGBEncoding
  408. : LinearEncoding;
  409. }
  410. getTexFormat () {
  411. var TextureFormat = this.basisModule.TextureFormat;
  412. return this.dfd.colorModel === DFDModel.UASTC ? TextureFormat.UASTC4x4 : TextureFormat.ETC1S;
  413. }
  414. getAlpha () {
  415. var TextureFormat = this.basisModule.TextureFormat;
  416. // TODO(donmccurdy): Handle all channelIDs (i.e. the R & R+G cases),
  417. // choosing appropriate transcode target formats or providing queries
  418. // for applications so they know what to do with the content.
  419. if ( this.getTexFormat() === TextureFormat.UASTC4x4 ) {
  420. // UASTC
  421. if ( ( this.dfd.samples[ 0 ].channelID & 0xF ) === DFDChannel.UASTC.RGBA ) {
  422. return true;
  423. }
  424. return false;
  425. }
  426. // ETC1S
  427. if ( this.dfd.numSamples === 2 && ( this.dfd.samples[ 1 ].channelID & 0xF ) === DFDChannel.ETC1S.AAA ) {
  428. return true;
  429. }
  430. return false;
  431. }
  432. getPremultiplyAlpha () {
  433. return !! ( this.dfd.flags & 1 /* KHR_DF_FLAG_ALPHA_PREMULTIPLIED */ );
  434. }
  435. }
  436. class KTX2BufferReader {
  437. constructor ( arrayBuffer, byteOffset, byteLength, littleEndian ) {
  438. this.dataView = new DataView( arrayBuffer, byteOffset, byteLength );
  439. this.littleEndian = littleEndian;
  440. this.offset = 0;
  441. }
  442. nextUint8 () {
  443. var value = this.dataView.getUint8( this.offset, this.littleEndian );
  444. this.offset += 1;
  445. return value;
  446. }
  447. nextUint16 () {
  448. var value = this.dataView.getUint16( this.offset, this.littleEndian );
  449. this.offset += 2;
  450. return value;
  451. }
  452. nextUint32 () {
  453. var value = this.dataView.getUint32( this.offset, this.littleEndian );
  454. this.offset += 4;
  455. return value;
  456. }
  457. nextUint64 () {
  458. // https://stackoverflow.com/questions/53103695/
  459. var left = this.dataView.getUint32( this.offset, this.littleEndian );
  460. var right = this.dataView.getUint32( this.offset + 4, this.littleEndian );
  461. var value = this.littleEndian ? left + ( 2 ** 32 * right ) : ( 2 ** 32 * left ) + right;
  462. if ( ! Number.isSafeInteger( value ) ) {
  463. console.warn( 'THREE.KTX2Loader: ' + value + ' exceeds MAX_SAFE_INTEGER. Precision may be lost.' );
  464. }
  465. this.offset += 8;
  466. return value;
  467. }
  468. skip ( bytes ) {
  469. this.offset += bytes;
  470. return this;
  471. }
  472. }
  473. export { KTX2Loader };