KTX2Loader.js 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807
  1. /**
  2. * Loader for KTX 2.0 GPU Texture containers.
  3. *
  4. * KTX 2.0 is a container format for various GPU texture formats. The loader
  5. * supports Basis Universal GPU textures, which can be quickly transcoded to
  6. * a wide variety of GPU texture compression formats, as well as some
  7. * uncompressed DataTexture and Data3DTexture formats.
  8. *
  9. * References:
  10. * - KTX: http://github.khronos.org/KTX-Specification/
  11. * - DFD: https://www.khronos.org/registry/DataFormat/specs/1.3/dataformat.1.3.html#basicdescriptor
  12. */
  13. import {
  14. CompressedTexture,
  15. CompressedArrayTexture,
  16. Data3DTexture,
  17. DataTexture,
  18. FileLoader,
  19. FloatType,
  20. HalfFloatType,
  21. NoColorSpace,
  22. LinearFilter,
  23. LinearMipmapLinearFilter,
  24. Loader,
  25. RedFormat,
  26. RGB_ETC1_Format,
  27. RGB_ETC2_Format,
  28. RGB_PVRTC_4BPPV1_Format,
  29. RGB_S3TC_DXT1_Format,
  30. RGBA_ASTC_4x4_Format,
  31. RGBA_BPTC_Format,
  32. RGBA_ETC2_EAC_Format,
  33. RGBA_PVRTC_4BPPV1_Format,
  34. RGBA_S3TC_DXT5_Format,
  35. RGBAFormat,
  36. RGFormat,
  37. SRGBColorSpace,
  38. UnsignedByteType,
  39. } from 'three';
  40. import { WorkerPool } from '../utils/WorkerPool.js';
  41. import {
  42. read,
  43. KHR_DF_FLAG_ALPHA_PREMULTIPLIED,
  44. KHR_DF_TRANSFER_SRGB,
  45. KHR_SUPERCOMPRESSION_NONE,
  46. KHR_SUPERCOMPRESSION_ZSTD,
  47. VK_FORMAT_UNDEFINED,
  48. VK_FORMAT_R16_SFLOAT,
  49. VK_FORMAT_R16G16_SFLOAT,
  50. VK_FORMAT_R16G16B16A16_SFLOAT,
  51. VK_FORMAT_R32_SFLOAT,
  52. VK_FORMAT_R32G32_SFLOAT,
  53. VK_FORMAT_R32G32B32A32_SFLOAT,
  54. VK_FORMAT_R8_SRGB,
  55. VK_FORMAT_R8_UNORM,
  56. VK_FORMAT_R8G8_SRGB,
  57. VK_FORMAT_R8G8_UNORM,
  58. VK_FORMAT_R8G8B8A8_SRGB,
  59. VK_FORMAT_R8G8B8A8_UNORM,
  60. } from '../libs/ktx-parse.module.js';
  61. import { ZSTDDecoder } from '../libs/zstddec.module.js';
  62. const _taskCache = new WeakMap();
  63. let _activeLoaders = 0;
  64. let _zstd;
  65. class KTX2Loader extends Loader {
  66. constructor( manager ) {
  67. super( manager );
  68. this.transcoderPath = '';
  69. this.transcoderBinary = null;
  70. this.transcoderPending = null;
  71. this.workerPool = new WorkerPool();
  72. this.workerSourceURL = '';
  73. this.workerConfig = null;
  74. if ( typeof MSC_TRANSCODER !== 'undefined' ) {
  75. console.warn(
  76. 'THREE.KTX2Loader: Please update to latest "basis_transcoder".'
  77. + ' "msc_basis_transcoder" is no longer supported in three.js r125+.'
  78. );
  79. }
  80. }
  81. setTranscoderPath( path ) {
  82. this.transcoderPath = path;
  83. return this;
  84. }
  85. setWorkerLimit( num ) {
  86. this.workerPool.setWorkerLimit( num );
  87. return this;
  88. }
  89. detectSupport( renderer ) {
  90. if ( renderer.isWebGPURenderer === true ) {
  91. this.workerConfig = {
  92. astcSupported: renderer.hasFeature( 'texture-compression-astc' ),
  93. etc1Supported: false,
  94. etc2Supported: renderer.hasFeature( 'texture-compression-etc2' ),
  95. dxtSupported: renderer.hasFeature( 'texture-compression-bc' ),
  96. bptcSupported: false,
  97. pvrtcSupported: false
  98. };
  99. } else {
  100. this.workerConfig = {
  101. astcSupported: renderer.extensions.has( 'WEBGL_compressed_texture_astc' ),
  102. etc1Supported: renderer.extensions.has( 'WEBGL_compressed_texture_etc1' ),
  103. etc2Supported: renderer.extensions.has( 'WEBGL_compressed_texture_etc' ),
  104. dxtSupported: renderer.extensions.has( 'WEBGL_compressed_texture_s3tc' ),
  105. bptcSupported: renderer.extensions.has( 'EXT_texture_compression_bptc' ),
  106. pvrtcSupported: renderer.extensions.has( 'WEBGL_compressed_texture_pvrtc' )
  107. || renderer.extensions.has( 'WEBKIT_WEBGL_compressed_texture_pvrtc' )
  108. };
  109. if ( renderer.capabilities.isWebGL2 ) {
  110. // https://github.com/mrdoob/three.js/pull/22928
  111. this.workerConfig.etc1Supported = false;
  112. }
  113. }
  114. return this;
  115. }
  116. init() {
  117. if ( ! this.transcoderPending ) {
  118. // Load transcoder wrapper.
  119. const jsLoader = new FileLoader( this.manager );
  120. jsLoader.setPath( this.transcoderPath );
  121. jsLoader.setWithCredentials( this.withCredentials );
  122. const jsContent = jsLoader.loadAsync( 'basis_transcoder.js' );
  123. // Load transcoder WASM binary.
  124. const binaryLoader = new FileLoader( this.manager );
  125. binaryLoader.setPath( this.transcoderPath );
  126. binaryLoader.setResponseType( 'arraybuffer' );
  127. binaryLoader.setWithCredentials( this.withCredentials );
  128. const binaryContent = binaryLoader.loadAsync( 'basis_transcoder.wasm' );
  129. this.transcoderPending = Promise.all( [ jsContent, binaryContent ] )
  130. .then( ( [ jsContent, binaryContent ] ) => {
  131. const fn = KTX2Loader.BasisWorker.toString();
  132. const body = [
  133. '/* constants */',
  134. 'let _EngineFormat = ' + JSON.stringify( KTX2Loader.EngineFormat ),
  135. 'let _TranscoderFormat = ' + JSON.stringify( KTX2Loader.TranscoderFormat ),
  136. 'let _BasisFormat = ' + JSON.stringify( KTX2Loader.BasisFormat ),
  137. '/* basis_transcoder.js */',
  138. jsContent,
  139. '/* worker */',
  140. fn.substring( fn.indexOf( '{' ) + 1, fn.lastIndexOf( '}' ) )
  141. ].join( '\n' );
  142. this.workerSourceURL = URL.createObjectURL( new Blob( [ body ] ) );
  143. this.transcoderBinary = binaryContent;
  144. this.workerPool.setWorkerCreator( () => {
  145. const worker = new Worker( this.workerSourceURL );
  146. const transcoderBinary = this.transcoderBinary.slice( 0 );
  147. worker.postMessage( { type: 'init', config: this.workerConfig, transcoderBinary }, [ transcoderBinary ] );
  148. return worker;
  149. } );
  150. } );
  151. if ( _activeLoaders > 0 ) {
  152. // Each instance loads a transcoder and allocates workers, increasing network and memory cost.
  153. console.warn(
  154. 'THREE.KTX2Loader: Multiple active KTX2 loaders may cause performance issues.'
  155. + ' Use a single KTX2Loader instance, or call .dispose() on old instances.'
  156. );
  157. }
  158. _activeLoaders ++;
  159. }
  160. return this.transcoderPending;
  161. }
  162. load( url, onLoad, onProgress, onError ) {
  163. if ( this.workerConfig === null ) {
  164. throw new Error( 'THREE.KTX2Loader: Missing initialization with `.detectSupport( renderer )`.' );
  165. }
  166. const loader = new FileLoader( this.manager );
  167. loader.setResponseType( 'arraybuffer' );
  168. loader.setWithCredentials( this.withCredentials );
  169. loader.load( url, ( buffer ) => {
  170. // Check for an existing task using this buffer. A transferred buffer cannot be transferred
  171. // again from this thread.
  172. if ( _taskCache.has( buffer ) ) {
  173. const cachedTask = _taskCache.get( buffer );
  174. return cachedTask.promise.then( onLoad ).catch( onError );
  175. }
  176. this._createTexture( buffer )
  177. .then( ( texture ) => onLoad ? onLoad( texture ) : null )
  178. .catch( onError );
  179. }, onProgress, onError );
  180. }
  181. _createTextureFrom( transcodeResult, container ) {
  182. const { mipmaps, width, height, format, type, error, dfdTransferFn, dfdFlags } = transcodeResult;
  183. if ( type === 'error' ) return Promise.reject( error );
  184. const texture = container.layerCount > 1
  185. ? new CompressedArrayTexture( mipmaps, width, height, container.layerCount, format, UnsignedByteType )
  186. : new CompressedTexture( mipmaps, width, height, format, UnsignedByteType );
  187. texture.minFilter = mipmaps.length === 1 ? LinearFilter : LinearMipmapLinearFilter;
  188. texture.magFilter = LinearFilter;
  189. texture.generateMipmaps = false;
  190. texture.needsUpdate = true;
  191. // TODO: Detect NoColorSpace vs. LinearSRGBColorSpace based on primaries.
  192. texture.colorSpace = dfdTransferFn === KHR_DF_TRANSFER_SRGB ? SRGBColorSpace : NoColorSpace;
  193. texture.premultiplyAlpha = !! ( dfdFlags & KHR_DF_FLAG_ALPHA_PREMULTIPLIED );
  194. return texture;
  195. }
  196. /**
  197. * @param {ArrayBuffer} buffer
  198. * @param {object?} config
  199. * @return {Promise<CompressedTexture|CompressedArrayTexture|DataTexture|Data3DTexture>}
  200. */
  201. async _createTexture( buffer, config = {} ) {
  202. const container = read( new Uint8Array( buffer ) );
  203. if ( container.vkFormat !== VK_FORMAT_UNDEFINED ) {
  204. return createDataTexture( container );
  205. }
  206. //
  207. const taskConfig = config;
  208. const texturePending = this.init().then( () => {
  209. return this.workerPool.postMessage( { type: 'transcode', buffer, taskConfig: taskConfig }, [ buffer ] );
  210. } ).then( ( e ) => this._createTextureFrom( e.data, container ) );
  211. // Cache the task result.
  212. _taskCache.set( buffer, { promise: texturePending } );
  213. return texturePending;
  214. }
  215. dispose() {
  216. this.workerPool.dispose();
  217. if ( this.workerSourceURL ) URL.revokeObjectURL( this.workerSourceURL );
  218. _activeLoaders --;
  219. return this;
  220. }
  221. }
  222. /* CONSTANTS */
  223. KTX2Loader.BasisFormat = {
  224. ETC1S: 0,
  225. UASTC_4x4: 1,
  226. };
  227. KTX2Loader.TranscoderFormat = {
  228. ETC1: 0,
  229. ETC2: 1,
  230. BC1: 2,
  231. BC3: 3,
  232. BC4: 4,
  233. BC5: 5,
  234. BC7_M6_OPAQUE_ONLY: 6,
  235. BC7_M5: 7,
  236. PVRTC1_4_RGB: 8,
  237. PVRTC1_4_RGBA: 9,
  238. ASTC_4x4: 10,
  239. ATC_RGB: 11,
  240. ATC_RGBA_INTERPOLATED_ALPHA: 12,
  241. RGBA32: 13,
  242. RGB565: 14,
  243. BGR565: 15,
  244. RGBA4444: 16,
  245. };
  246. KTX2Loader.EngineFormat = {
  247. RGBAFormat: RGBAFormat,
  248. RGBA_ASTC_4x4_Format: RGBA_ASTC_4x4_Format,
  249. RGBA_BPTC_Format: RGBA_BPTC_Format,
  250. RGBA_ETC2_EAC_Format: RGBA_ETC2_EAC_Format,
  251. RGBA_PVRTC_4BPPV1_Format: RGBA_PVRTC_4BPPV1_Format,
  252. RGBA_S3TC_DXT5_Format: RGBA_S3TC_DXT5_Format,
  253. RGB_ETC1_Format: RGB_ETC1_Format,
  254. RGB_ETC2_Format: RGB_ETC2_Format,
  255. RGB_PVRTC_4BPPV1_Format: RGB_PVRTC_4BPPV1_Format,
  256. RGB_S3TC_DXT1_Format: RGB_S3TC_DXT1_Format,
  257. };
  258. /* WEB WORKER */
  259. KTX2Loader.BasisWorker = function () {
  260. let config;
  261. let transcoderPending;
  262. let BasisModule;
  263. const EngineFormat = _EngineFormat; // eslint-disable-line no-undef
  264. const TranscoderFormat = _TranscoderFormat; // eslint-disable-line no-undef
  265. const BasisFormat = _BasisFormat; // eslint-disable-line no-undef
  266. self.addEventListener( 'message', function ( e ) {
  267. const message = e.data;
  268. switch ( message.type ) {
  269. case 'init':
  270. config = message.config;
  271. init( message.transcoderBinary );
  272. break;
  273. case 'transcode':
  274. transcoderPending.then( () => {
  275. try {
  276. const { width, height, hasAlpha, mipmaps, format, dfdTransferFn, dfdFlags } = transcode( message.buffer );
  277. const buffers = [];
  278. for ( let i = 0; i < mipmaps.length; ++ i ) {
  279. buffers.push( mipmaps[ i ].data.buffer );
  280. }
  281. self.postMessage( { type: 'transcode', id: message.id, width, height, hasAlpha, mipmaps, format, dfdTransferFn, dfdFlags }, buffers );
  282. } catch ( error ) {
  283. console.error( error );
  284. self.postMessage( { type: 'error', id: message.id, error: error.message } );
  285. }
  286. } );
  287. break;
  288. }
  289. } );
  290. function init( wasmBinary ) {
  291. transcoderPending = new Promise( ( resolve ) => {
  292. BasisModule = { wasmBinary, onRuntimeInitialized: resolve };
  293. BASIS( BasisModule ); // eslint-disable-line no-undef
  294. } ).then( () => {
  295. BasisModule.initializeBasis();
  296. if ( BasisModule.KTX2File === undefined ) {
  297. console.warn( 'THREE.KTX2Loader: Please update Basis Universal transcoder.' );
  298. }
  299. } );
  300. }
  301. function transcode( buffer ) {
  302. const ktx2File = new BasisModule.KTX2File( new Uint8Array( buffer ) );
  303. function cleanup() {
  304. ktx2File.close();
  305. ktx2File.delete();
  306. }
  307. if ( ! ktx2File.isValid() ) {
  308. cleanup();
  309. throw new Error( 'THREE.KTX2Loader: Invalid or unsupported .ktx2 file' );
  310. }
  311. const basisFormat = ktx2File.isUASTC() ? BasisFormat.UASTC_4x4 : BasisFormat.ETC1S;
  312. const width = ktx2File.getWidth();
  313. const height = ktx2File.getHeight();
  314. const layers = ktx2File.getLayers() || 1;
  315. const levels = ktx2File.getLevels();
  316. const hasAlpha = ktx2File.getHasAlpha();
  317. const dfdTransferFn = ktx2File.getDFDTransferFunc();
  318. const dfdFlags = ktx2File.getDFDFlags();
  319. const { transcoderFormat, engineFormat } = getTranscoderFormat( basisFormat, width, height, hasAlpha );
  320. if ( ! width || ! height || ! levels ) {
  321. cleanup();
  322. throw new Error( 'THREE.KTX2Loader: Invalid texture' );
  323. }
  324. if ( ! ktx2File.startTranscoding() ) {
  325. cleanup();
  326. throw new Error( 'THREE.KTX2Loader: .startTranscoding failed' );
  327. }
  328. const mipmaps = [];
  329. for ( let mip = 0; mip < levels; mip ++ ) {
  330. const layerMips = [];
  331. let mipWidth, mipHeight;
  332. for ( let layer = 0; layer < layers; layer ++ ) {
  333. const levelInfo = ktx2File.getImageLevelInfo( mip, layer, 0 );
  334. mipWidth = levelInfo.origWidth < 4 ? levelInfo.origWidth : levelInfo.width;
  335. mipHeight = levelInfo.origHeight < 4 ? levelInfo.origHeight : levelInfo.height;
  336. const dst = new Uint8Array( ktx2File.getImageTranscodedSizeInBytes( mip, layer, 0, transcoderFormat ) );
  337. const status = ktx2File.transcodeImage(
  338. dst,
  339. mip,
  340. layer,
  341. 0,
  342. transcoderFormat,
  343. 0,
  344. - 1,
  345. - 1,
  346. );
  347. if ( ! status ) {
  348. cleanup();
  349. throw new Error( 'THREE.KTX2Loader: .transcodeImage failed.' );
  350. }
  351. layerMips.push( dst );
  352. }
  353. mipmaps.push( { data: concat( layerMips ), width: mipWidth, height: mipHeight } );
  354. }
  355. cleanup();
  356. return { width, height, hasAlpha, mipmaps, format: engineFormat, dfdTransferFn, dfdFlags };
  357. }
  358. //
  359. // Optimal choice of a transcoder target format depends on the Basis format (ETC1S or UASTC),
  360. // device capabilities, and texture dimensions. The list below ranks the formats separately
  361. // for ETC1S and UASTC.
  362. //
  363. // In some cases, transcoding UASTC to RGBA32 might be preferred for higher quality (at
  364. // significant memory cost) compared to ETC1/2, BC1/3, and PVRTC. The transcoder currently
  365. // chooses RGBA32 only as a last resort and does not expose that option to the caller.
  366. const FORMAT_OPTIONS = [
  367. {
  368. if: 'astcSupported',
  369. basisFormat: [ BasisFormat.UASTC_4x4 ],
  370. transcoderFormat: [ TranscoderFormat.ASTC_4x4, TranscoderFormat.ASTC_4x4 ],
  371. engineFormat: [ EngineFormat.RGBA_ASTC_4x4_Format, EngineFormat.RGBA_ASTC_4x4_Format ],
  372. priorityETC1S: Infinity,
  373. priorityUASTC: 1,
  374. needsPowerOfTwo: false,
  375. },
  376. {
  377. if: 'bptcSupported',
  378. basisFormat: [ BasisFormat.ETC1S, BasisFormat.UASTC_4x4 ],
  379. transcoderFormat: [ TranscoderFormat.BC7_M5, TranscoderFormat.BC7_M5 ],
  380. engineFormat: [ EngineFormat.RGBA_BPTC_Format, EngineFormat.RGBA_BPTC_Format ],
  381. priorityETC1S: 3,
  382. priorityUASTC: 2,
  383. needsPowerOfTwo: false,
  384. },
  385. {
  386. if: 'dxtSupported',
  387. basisFormat: [ BasisFormat.ETC1S, BasisFormat.UASTC_4x4 ],
  388. transcoderFormat: [ TranscoderFormat.BC1, TranscoderFormat.BC3 ],
  389. engineFormat: [ EngineFormat.RGB_S3TC_DXT1_Format, EngineFormat.RGBA_S3TC_DXT5_Format ],
  390. priorityETC1S: 4,
  391. priorityUASTC: 5,
  392. needsPowerOfTwo: false,
  393. },
  394. {
  395. if: 'etc2Supported',
  396. basisFormat: [ BasisFormat.ETC1S, BasisFormat.UASTC_4x4 ],
  397. transcoderFormat: [ TranscoderFormat.ETC1, TranscoderFormat.ETC2 ],
  398. engineFormat: [ EngineFormat.RGB_ETC2_Format, EngineFormat.RGBA_ETC2_EAC_Format ],
  399. priorityETC1S: 1,
  400. priorityUASTC: 3,
  401. needsPowerOfTwo: false,
  402. },
  403. {
  404. if: 'etc1Supported',
  405. basisFormat: [ BasisFormat.ETC1S, BasisFormat.UASTC_4x4 ],
  406. transcoderFormat: [ TranscoderFormat.ETC1 ],
  407. engineFormat: [ EngineFormat.RGB_ETC1_Format ],
  408. priorityETC1S: 2,
  409. priorityUASTC: 4,
  410. needsPowerOfTwo: false,
  411. },
  412. {
  413. if: 'pvrtcSupported',
  414. basisFormat: [ BasisFormat.ETC1S, BasisFormat.UASTC_4x4 ],
  415. transcoderFormat: [ TranscoderFormat.PVRTC1_4_RGB, TranscoderFormat.PVRTC1_4_RGBA ],
  416. engineFormat: [ EngineFormat.RGB_PVRTC_4BPPV1_Format, EngineFormat.RGBA_PVRTC_4BPPV1_Format ],
  417. priorityETC1S: 5,
  418. priorityUASTC: 6,
  419. needsPowerOfTwo: true,
  420. },
  421. ];
  422. const ETC1S_OPTIONS = FORMAT_OPTIONS.sort( function ( a, b ) {
  423. return a.priorityETC1S - b.priorityETC1S;
  424. } );
  425. const UASTC_OPTIONS = FORMAT_OPTIONS.sort( function ( a, b ) {
  426. return a.priorityUASTC - b.priorityUASTC;
  427. } );
  428. function getTranscoderFormat( basisFormat, width, height, hasAlpha ) {
  429. let transcoderFormat;
  430. let engineFormat;
  431. const options = basisFormat === BasisFormat.ETC1S ? ETC1S_OPTIONS : UASTC_OPTIONS;
  432. for ( let i = 0; i < options.length; i ++ ) {
  433. const opt = options[ i ];
  434. if ( ! config[ opt.if ] ) continue;
  435. if ( ! opt.basisFormat.includes( basisFormat ) ) continue;
  436. if ( hasAlpha && opt.transcoderFormat.length < 2 ) continue;
  437. if ( opt.needsPowerOfTwo && ! ( isPowerOfTwo( width ) && isPowerOfTwo( height ) ) ) continue;
  438. transcoderFormat = opt.transcoderFormat[ hasAlpha ? 1 : 0 ];
  439. engineFormat = opt.engineFormat[ hasAlpha ? 1 : 0 ];
  440. return { transcoderFormat, engineFormat };
  441. }
  442. console.warn( 'THREE.KTX2Loader: No suitable compressed texture format found. Decoding to RGBA32.' );
  443. transcoderFormat = TranscoderFormat.RGBA32;
  444. engineFormat = EngineFormat.RGBAFormat;
  445. return { transcoderFormat, engineFormat };
  446. }
  447. function isPowerOfTwo( value ) {
  448. if ( value <= 2 ) return true;
  449. return ( value & ( value - 1 ) ) === 0 && value !== 0;
  450. }
  451. /** Concatenates N byte arrays. */
  452. function concat( arrays ) {
  453. let totalByteLength = 0;
  454. for ( const array of arrays ) {
  455. totalByteLength += array.byteLength;
  456. }
  457. const result = new Uint8Array( totalByteLength );
  458. let byteOffset = 0;
  459. for ( const array of arrays ) {
  460. result.set( array, byteOffset );
  461. byteOffset += array.byteLength;
  462. }
  463. return result;
  464. }
  465. };
  466. //
  467. // DataTexture and Data3DTexture parsing.
  468. const FORMAT_MAP = {
  469. [ VK_FORMAT_R32G32B32A32_SFLOAT ]: RGBAFormat,
  470. [ VK_FORMAT_R16G16B16A16_SFLOAT ]: RGBAFormat,
  471. [ VK_FORMAT_R8G8B8A8_UNORM ]: RGBAFormat,
  472. [ VK_FORMAT_R8G8B8A8_SRGB ]: RGBAFormat,
  473. [ VK_FORMAT_R32G32_SFLOAT ]: RGFormat,
  474. [ VK_FORMAT_R16G16_SFLOAT ]: RGFormat,
  475. [ VK_FORMAT_R8G8_UNORM ]: RGFormat,
  476. [ VK_FORMAT_R8G8_SRGB ]: RGFormat,
  477. [ VK_FORMAT_R32_SFLOAT ]: RedFormat,
  478. [ VK_FORMAT_R16_SFLOAT ]: RedFormat,
  479. [ VK_FORMAT_R8_SRGB ]: RedFormat,
  480. [ VK_FORMAT_R8_UNORM ]: RedFormat,
  481. };
  482. const TYPE_MAP = {
  483. [ VK_FORMAT_R32G32B32A32_SFLOAT ]: FloatType,
  484. [ VK_FORMAT_R16G16B16A16_SFLOAT ]: HalfFloatType,
  485. [ VK_FORMAT_R8G8B8A8_UNORM ]: UnsignedByteType,
  486. [ VK_FORMAT_R8G8B8A8_SRGB ]: UnsignedByteType,
  487. [ VK_FORMAT_R32G32_SFLOAT ]: FloatType,
  488. [ VK_FORMAT_R16G16_SFLOAT ]: HalfFloatType,
  489. [ VK_FORMAT_R8G8_UNORM ]: UnsignedByteType,
  490. [ VK_FORMAT_R8G8_SRGB ]: UnsignedByteType,
  491. [ VK_FORMAT_R32_SFLOAT ]: FloatType,
  492. [ VK_FORMAT_R16_SFLOAT ]: HalfFloatType,
  493. [ VK_FORMAT_R8_SRGB ]: UnsignedByteType,
  494. [ VK_FORMAT_R8_UNORM ]: UnsignedByteType,
  495. };
  496. const COLOR_SPACE_MAP = {
  497. [ VK_FORMAT_R8G8B8A8_SRGB ]: SRGBColorSpace,
  498. [ VK_FORMAT_R8G8_SRGB ]: SRGBColorSpace,
  499. [ VK_FORMAT_R8_SRGB ]: SRGBColorSpace,
  500. };
  501. async function createDataTexture( container ) {
  502. const { vkFormat, pixelWidth, pixelHeight, pixelDepth } = container;
  503. if ( FORMAT_MAP[ vkFormat ] === undefined ) {
  504. throw new Error( 'THREE.KTX2Loader: Unsupported vkFormat.' );
  505. }
  506. const level = container.levels[ 0 ];
  507. let levelData;
  508. let view;
  509. if ( container.supercompressionScheme === KHR_SUPERCOMPRESSION_NONE ) {
  510. levelData = level.levelData;
  511. } else if ( container.supercompressionScheme === KHR_SUPERCOMPRESSION_ZSTD ) {
  512. if ( ! _zstd ) {
  513. _zstd = new Promise( async ( resolve ) => {
  514. const zstd = new ZSTDDecoder();
  515. await zstd.init();
  516. resolve( zstd );
  517. } );
  518. }
  519. levelData = ( await _zstd ).decode( level.levelData, level.uncompressedByteLength );
  520. } else {
  521. throw new Error( 'THREE.KTX2Loader: Unsupported supercompressionScheme.' );
  522. }
  523. if ( TYPE_MAP[ vkFormat ] === FloatType ) {
  524. view = new Float32Array(
  525. levelData.buffer,
  526. levelData.byteOffset,
  527. levelData.byteLength / Float32Array.BYTES_PER_ELEMENT
  528. );
  529. } else if ( TYPE_MAP[ vkFormat ] === HalfFloatType ) {
  530. view = new Uint16Array(
  531. levelData.buffer,
  532. levelData.byteOffset,
  533. levelData.byteLength / Uint16Array.BYTES_PER_ELEMENT
  534. );
  535. } else {
  536. view = levelData;
  537. }
  538. //
  539. const texture = pixelDepth === 0
  540. ? new DataTexture( view, pixelWidth, pixelHeight )
  541. : new Data3DTexture( view, pixelWidth, pixelHeight, pixelDepth );
  542. texture.type = TYPE_MAP[ vkFormat ];
  543. texture.format = FORMAT_MAP[ vkFormat ];
  544. texture.colorSpace = COLOR_SPACE_MAP[ vkFormat ] || NoColorSpace;
  545. texture.needsUpdate = true;
  546. //
  547. return Promise.resolve( texture );
  548. }
  549. export { KTX2Loader };