KTX2Loader.js 23 KB

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