KTX2Loader.js 22 KB

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