KTX2Loader.js 35 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257
  1. import {
  2. CompressedArrayTexture,
  3. CompressedCubeTexture,
  4. CompressedTexture,
  5. Data3DTexture,
  6. DataTexture,
  7. FileLoader,
  8. FloatType,
  9. HalfFloatType,
  10. LinearFilter,
  11. LinearMipmapLinearFilter,
  12. NearestFilter,
  13. NearestMipmapNearestFilter,
  14. LinearSRGBColorSpace,
  15. Loader,
  16. NoColorSpace,
  17. RGBAFormat,
  18. RGBA_ASTC_4x4_Format,
  19. RGBA_ASTC_6x6_Format,
  20. RGBA_BPTC_Format,
  21. RGBA_ETC2_EAC_Format,
  22. R11_EAC_Format,
  23. SIGNED_R11_EAC_Format,
  24. RG11_EAC_Format,
  25. SIGNED_RG11_EAC_Format,
  26. RGBA_PVRTC_4BPPV1_Format,
  27. RGBA_PVRTC_2BPPV1_Format,
  28. RGBA_S3TC_DXT1_Format,
  29. RGBA_S3TC_DXT5_Format,
  30. RGB_BPTC_UNSIGNED_Format,
  31. RGB_ETC1_Format,
  32. RGB_ETC2_Format,
  33. RGB_PVRTC_4BPPV1_Format,
  34. RGB_S3TC_DXT1_Format,
  35. SIGNED_RED_GREEN_RGTC2_Format,
  36. SIGNED_RED_RGTC1_Format,
  37. RED_GREEN_RGTC2_Format,
  38. RED_RGTC1_Format,
  39. RGBFormat,
  40. RGFormat,
  41. RedFormat,
  42. SRGBColorSpace,
  43. UnsignedByteType,
  44. UnsignedInt5999Type,
  45. UnsignedInt101111Type,
  46. UnsignedShortType
  47. } from 'three';
  48. import { WorkerPool } from '../utils/WorkerPool.js';
  49. import {
  50. read,
  51. KHR_DF_FLAG_ALPHA_PREMULTIPLIED,
  52. KHR_DF_PRIMARIES_BT709,
  53. KHR_DF_PRIMARIES_DISPLAYP3,
  54. KHR_DF_PRIMARIES_UNSPECIFIED,
  55. KHR_DF_TRANSFER_SRGB,
  56. KHR_SUPERCOMPRESSION_NONE,
  57. KHR_SUPERCOMPRESSION_ZSTD,
  58. VK_FORMAT_ASTC_4x4_SFLOAT_BLOCK_EXT,
  59. VK_FORMAT_ASTC_6x6_SFLOAT_BLOCK_EXT,
  60. VK_FORMAT_ASTC_4x4_SRGB_BLOCK,
  61. VK_FORMAT_ASTC_4x4_UNORM_BLOCK,
  62. VK_FORMAT_ASTC_6x6_SRGB_BLOCK,
  63. VK_FORMAT_ASTC_6x6_UNORM_BLOCK,
  64. VK_FORMAT_BC1_RGBA_SRGB_BLOCK,
  65. VK_FORMAT_BC1_RGBA_UNORM_BLOCK,
  66. VK_FORMAT_BC1_RGB_SRGB_BLOCK,
  67. VK_FORMAT_BC1_RGB_UNORM_BLOCK,
  68. VK_FORMAT_BC3_SRGB_BLOCK,
  69. VK_FORMAT_BC3_UNORM_BLOCK,
  70. VK_FORMAT_BC4_SNORM_BLOCK,
  71. VK_FORMAT_BC4_UNORM_BLOCK,
  72. VK_FORMAT_BC5_SNORM_BLOCK,
  73. VK_FORMAT_BC5_UNORM_BLOCK,
  74. VK_FORMAT_BC7_SRGB_BLOCK,
  75. VK_FORMAT_BC7_UNORM_BLOCK,
  76. VK_FORMAT_ETC2_R8G8B8_SRGB_BLOCK,
  77. VK_FORMAT_ETC2_R8G8B8A8_SRGB_BLOCK,
  78. VK_FORMAT_EAC_R11_UNORM_BLOCK,
  79. VK_FORMAT_EAC_R11_SNORM_BLOCK,
  80. VK_FORMAT_EAC_R11G11_UNORM_BLOCK,
  81. VK_FORMAT_EAC_R11G11_SNORM_BLOCK,
  82. VK_FORMAT_PVRTC1_4BPP_SRGB_BLOCK_IMG,
  83. VK_FORMAT_PVRTC1_4BPP_UNORM_BLOCK_IMG,
  84. VK_FORMAT_PVRTC1_2BPP_SRGB_BLOCK_IMG,
  85. VK_FORMAT_PVRTC1_2BPP_UNORM_BLOCK_IMG,
  86. VK_FORMAT_R16G16B16A16_SFLOAT,
  87. VK_FORMAT_R16G16B16A16_UNORM,
  88. VK_FORMAT_R16G16_SFLOAT,
  89. VK_FORMAT_R16_SFLOAT,
  90. VK_FORMAT_R32G32B32A32_SFLOAT,
  91. VK_FORMAT_R32G32_SFLOAT,
  92. VK_FORMAT_R32_SFLOAT,
  93. VK_FORMAT_R8G8B8A8_SRGB,
  94. VK_FORMAT_R8G8B8A8_UNORM,
  95. VK_FORMAT_R8G8_SRGB,
  96. VK_FORMAT_R8G8_UNORM,
  97. VK_FORMAT_R8_SRGB,
  98. VK_FORMAT_R8_UNORM,
  99. VK_FORMAT_E5B9G9R9_UFLOAT_PACK32,
  100. VK_FORMAT_B10G11R11_UFLOAT_PACK32,
  101. VK_FORMAT_UNDEFINED
  102. } from '../libs/ktx-parse.module.js';
  103. import { ZSTDDecoder } from '../libs/zstddec.module.js';
  104. import { DisplayP3ColorSpace, LinearDisplayP3ColorSpace } from '../math/ColorSpaces.js';
  105. const _taskCache = new WeakMap();
  106. let _activeLoaders = 0;
  107. let _zstd;
  108. /**
  109. * A loader for KTX 2.0 GPU Texture containers.
  110. *
  111. * KTX 2.0 is a container format for various GPU texture formats. The loader supports Basis Universal GPU textures,
  112. * which can be quickly transcoded to a wide variety of GPU texture compression formats. While KTX 2.0 also allows
  113. * other hardware-specific formats, this loader does not yet parse them.
  114. *
  115. * This loader parses the KTX 2.0 container and transcodes to a supported GPU compressed texture format.
  116. * The required WASM transcoder and JS wrapper are available from the `examples/jsm/libs/basis` directory.
  117. *
  118. * This loader relies on Web Assembly which is not supported in older browsers.
  119. *
  120. * References:
  121. * - [KTX specification](http://github.khronos.org/KTX-Specification/)
  122. * - [DFD](https://www.khronos.org/registry/DataFormat/specs/1.3/dataformat.1.3.html#basicdescriptor)
  123. * - [BasisU HDR](https://github.com/BinomialLLC/basis_universal/wiki/UASTC-HDR-Texture-Specification-v1.0)
  124. *
  125. * ```js
  126. * const loader = new KTX2Loader();
  127. * loader.setTranscoderPath( 'examples/jsm/libs/basis/' );
  128. * loader.detectSupport( renderer );
  129. * const texture = loader.loadAsync( 'diffuse.ktx2' );
  130. * ```
  131. *
  132. * @augments Loader
  133. * @three_import import { KTX2Loader } from 'three/addons/loaders/KTX2Loader.js';
  134. */
  135. class KTX2Loader extends Loader {
  136. /**
  137. * Constructs a new KTX2 loader.
  138. *
  139. * @param {LoadingManager} [manager] - The loading manager.
  140. */
  141. constructor( manager ) {
  142. super( manager );
  143. this.transcoderPath = '';
  144. this.transcoderBinary = null;
  145. this.transcoderPending = null;
  146. this.workerPool = new WorkerPool();
  147. this.workerSourceURL = '';
  148. this.workerConfig = null;
  149. if ( typeof MSC_TRANSCODER !== 'undefined' ) {
  150. console.warn(
  151. 'THREE.KTX2Loader: Please update to latest "basis_transcoder".'
  152. + ' "msc_basis_transcoder" is no longer supported in three.js r125+.'
  153. );
  154. }
  155. }
  156. /**
  157. * Sets the transcoder path.
  158. *
  159. * The WASM transcoder and JS wrapper are available from the `examples/jsm/libs/basis` directory.
  160. *
  161. * @param {string} path - The transcoder path to set.
  162. * @return {KTX2Loader} A reference to this loader.
  163. */
  164. setTranscoderPath( path ) {
  165. this.transcoderPath = path;
  166. return this;
  167. }
  168. /**
  169. * Sets the maximum number of Web Workers to be allocated by this instance.
  170. *
  171. * @param {number} workerLimit - The worker limit.
  172. * @return {KTX2Loader} A reference to this loader.
  173. */
  174. setWorkerLimit( workerLimit ) {
  175. this.workerPool.setWorkerLimit( workerLimit );
  176. return this;
  177. }
  178. /**
  179. * Async version of {@link KTX2Loader#detectSupport}.
  180. *
  181. * @async
  182. * @deprecated
  183. * @param {WebGPURenderer} renderer - The renderer.
  184. * @return {Promise} A Promise that resolves when the support has been detected.
  185. */
  186. async detectSupportAsync( renderer ) {
  187. console.warn( 'KTX2Loader: "detectSupportAsync()" has been deprecated. Use "detectSupport()" and "await renderer.init();" when creating the renderer.' ); // @deprecated r181
  188. await renderer.init();
  189. return this.detectSupport( renderer );
  190. }
  191. /**
  192. * Detects hardware support for available compressed texture formats, to determine
  193. * the output format for the transcoder. Must be called before loading a texture.
  194. *
  195. * @param {WebGPURenderer|WebGLRenderer} renderer - The renderer.
  196. * @return {KTX2Loader} A reference to this loader.
  197. */
  198. detectSupport( renderer ) {
  199. if ( renderer.isWebGPURenderer === true ) {
  200. this.workerConfig = {
  201. astcSupported: renderer.hasFeature( 'texture-compression-astc' ),
  202. astcHDRSupported: false, // https://github.com/gpuweb/gpuweb/issues/3856
  203. etc1Supported: renderer.hasFeature( 'texture-compression-etc1' ),
  204. etc2Supported: renderer.hasFeature( 'texture-compression-etc2' ),
  205. dxtSupported: renderer.hasFeature( 'texture-compression-s3tc' ),
  206. bptcSupported: renderer.hasFeature( 'texture-compression-bc' ),
  207. pvrtcSupported: renderer.hasFeature( 'texture-compression-pvrtc' )
  208. };
  209. } else {
  210. this.workerConfig = {
  211. astcSupported: renderer.extensions.has( 'WEBGL_compressed_texture_astc' ),
  212. astcHDRSupported: renderer.extensions.has( 'WEBGL_compressed_texture_astc' )
  213. && renderer.extensions.get( 'WEBGL_compressed_texture_astc' ).getSupportedProfiles().includes( 'hdr' ),
  214. etc1Supported: renderer.extensions.has( 'WEBGL_compressed_texture_etc1' ),
  215. etc2Supported: renderer.extensions.has( 'WEBGL_compressed_texture_etc' ),
  216. dxtSupported: renderer.extensions.has( 'WEBGL_compressed_texture_s3tc' ),
  217. bptcSupported: renderer.extensions.has( 'EXT_texture_compression_bptc' ),
  218. pvrtcSupported: renderer.extensions.has( 'WEBGL_compressed_texture_pvrtc' )
  219. || renderer.extensions.has( 'WEBKIT_WEBGL_compressed_texture_pvrtc' )
  220. };
  221. if ( typeof navigator !== 'undefined' &&
  222. typeof navigator.platform !== 'undefined' && typeof navigator.userAgent !== 'undefined' &&
  223. navigator.platform.indexOf( 'Linux' ) >= 0 && navigator.userAgent.indexOf( 'Firefox' ) >= 0 &&
  224. this.workerConfig.astcSupported && this.workerConfig.etc2Supported &&
  225. this.workerConfig.bptcSupported && this.workerConfig.dxtSupported ) {
  226. // On Linux, Mesa drivers for AMD and Intel GPUs expose ETC2 and ASTC even though the hardware doesn't support these.
  227. // Using these extensions will result in expensive software decompression on the main thread inside the driver, causing performance issues.
  228. // When using ANGLE (e.g. via Chrome), these extensions are not exposed except for some specific Intel GPU models - however, Firefox doesn't perform this filtering.
  229. // Since a granular filter is a little too fragile and we can transcode into other GPU formats, disable formats that are likely to be emulated.
  230. this.workerConfig.astcSupported = false;
  231. this.workerConfig.etc2Supported = false;
  232. }
  233. }
  234. return this;
  235. }
  236. // TODO: Make this method private
  237. init() {
  238. if ( ! this.transcoderPending ) {
  239. // Load transcoder wrapper.
  240. const jsLoader = new FileLoader( this.manager );
  241. jsLoader.setPath( this.transcoderPath );
  242. jsLoader.setWithCredentials( this.withCredentials );
  243. const jsContent = jsLoader.loadAsync( 'basis_transcoder.js' );
  244. // Load transcoder WASM binary.
  245. const binaryLoader = new FileLoader( this.manager );
  246. binaryLoader.setPath( this.transcoderPath );
  247. binaryLoader.setResponseType( 'arraybuffer' );
  248. binaryLoader.setWithCredentials( this.withCredentials );
  249. const binaryContent = binaryLoader.loadAsync( 'basis_transcoder.wasm' );
  250. this.transcoderPending = Promise.all( [ jsContent, binaryContent ] )
  251. .then( ( [ jsContent, binaryContent ] ) => {
  252. const fn = KTX2Loader.BasisWorker.toString();
  253. const body = [
  254. '/* constants */',
  255. 'let _EngineFormat = ' + JSON.stringify( KTX2Loader.EngineFormat ),
  256. 'let _EngineType = ' + JSON.stringify( KTX2Loader.EngineType ),
  257. 'let _TranscoderFormat = ' + JSON.stringify( KTX2Loader.TranscoderFormat ),
  258. 'let _BasisFormat = ' + JSON.stringify( KTX2Loader.BasisFormat ),
  259. '/* basis_transcoder.js */',
  260. jsContent,
  261. '/* worker */',
  262. fn.substring( fn.indexOf( '{' ) + 1, fn.lastIndexOf( '}' ) )
  263. ].join( '\n' );
  264. this.workerSourceURL = URL.createObjectURL( new Blob( [ body ] ) );
  265. this.transcoderBinary = binaryContent;
  266. this.workerPool.setWorkerCreator( () => {
  267. const worker = new Worker( this.workerSourceURL );
  268. const transcoderBinary = this.transcoderBinary.slice( 0 );
  269. worker.postMessage( { type: 'init', config: this.workerConfig, transcoderBinary }, [ transcoderBinary ] );
  270. return worker;
  271. } );
  272. } );
  273. if ( _activeLoaders > 0 ) {
  274. // Each instance loads a transcoder and allocates workers, increasing network and memory cost.
  275. console.warn(
  276. 'THREE.KTX2Loader: Multiple active KTX2 loaders may cause performance issues.'
  277. + ' Use a single KTX2Loader instance, or call .dispose() on old instances.'
  278. );
  279. }
  280. _activeLoaders ++;
  281. }
  282. return this.transcoderPending;
  283. }
  284. /**
  285. * Starts loading from the given URL and passes the loaded KTX2 texture
  286. * to the `onLoad()` callback.
  287. *
  288. * @param {string} url - The path/URL of the file to be loaded. This can also be a data URI.
  289. * @param {function(CompressedTexture)} onLoad - Executed when the loading process has been finished.
  290. * @param {onProgressCallback} onProgress - Executed while the loading is in progress.
  291. * @param {onErrorCallback} onError - Executed when errors occur.
  292. */
  293. load( url, onLoad, onProgress, onError ) {
  294. if ( this.workerConfig === null ) {
  295. throw new Error( 'THREE.KTX2Loader: Missing initialization with `.detectSupport( renderer )`.' );
  296. }
  297. const loader = new FileLoader( this.manager );
  298. loader.setPath( this.path );
  299. loader.setCrossOrigin( this.crossOrigin );
  300. loader.setWithCredentials( this.withCredentials );
  301. loader.setRequestHeader( this.requestHeader );
  302. loader.setResponseType( 'arraybuffer' );
  303. loader.load( url, ( buffer ) => {
  304. this.parse( buffer, onLoad, onError );
  305. }, onProgress, onError );
  306. }
  307. /**
  308. * Parses the given KTX2 data.
  309. *
  310. * @param {ArrayBuffer} buffer - The raw KTX2 data as an array buffer.
  311. * @param {function(CompressedTexture)} onLoad - Executed when the loading/parsing process has been finished.
  312. * @param {onErrorCallback} onError - Executed when errors occur.
  313. * @returns {Promise} A Promise that resolves when the parsing has been finished.
  314. */
  315. parse( buffer, onLoad, onError ) {
  316. if ( this.workerConfig === null ) {
  317. throw new Error( 'THREE.KTX2Loader: Missing initialization with `.detectSupport( renderer )`.' );
  318. }
  319. // Check for an existing task using this buffer. A transferred buffer cannot be transferred
  320. // again from this thread.
  321. if ( _taskCache.has( buffer ) ) {
  322. const cachedTask = _taskCache.get( buffer );
  323. return cachedTask.promise.then( onLoad ).catch( onError );
  324. }
  325. this._createTexture( buffer )
  326. .then( ( texture ) => onLoad ? onLoad( texture ) : null )
  327. .catch( onError );
  328. }
  329. _createTextureFrom( transcodeResult, container ) {
  330. const { type: messageType, error, data: { faces, width, height, format, type, dfdFlags } } = transcodeResult;
  331. if ( messageType === 'error' ) return Promise.reject( error );
  332. let texture;
  333. if ( container.faceCount === 6 ) {
  334. texture = new CompressedCubeTexture( faces, format, type );
  335. } else {
  336. const mipmaps = faces[ 0 ].mipmaps;
  337. texture = container.layerCount > 1
  338. ? new CompressedArrayTexture( mipmaps, width, height, container.layerCount, format, type )
  339. : new CompressedTexture( mipmaps, width, height, format, type );
  340. }
  341. texture.minFilter = faces[ 0 ].mipmaps.length === 1 ? LinearFilter : LinearMipmapLinearFilter;
  342. texture.magFilter = LinearFilter;
  343. texture.generateMipmaps = false;
  344. texture.needsUpdate = true;
  345. texture.colorSpace = parseColorSpace( container );
  346. texture.premultiplyAlpha = !! ( dfdFlags & KHR_DF_FLAG_ALPHA_PREMULTIPLIED );
  347. return texture;
  348. }
  349. /**
  350. * @private
  351. * @param {ArrayBuffer} buffer
  352. * @param {?Object} config
  353. * @return {Promise<CompressedTexture|CompressedArrayTexture|DataTexture|Data3DTexture>}
  354. */
  355. async _createTexture( buffer, config = {} ) {
  356. const container = read( new Uint8Array( buffer ) );
  357. // Basis UASTC HDR is a subset of ASTC, which can be transcoded efficiently
  358. // to BC6H. To detect whether a KTX2 file uses Basis UASTC HDR, or default
  359. // ASTC, inspect the DFD color model.
  360. //
  361. // Source: https://github.com/BinomialLLC/basis_universal/issues/381
  362. const isBasisHDR = container.vkFormat === VK_FORMAT_ASTC_4x4_SFLOAT_BLOCK_EXT
  363. && container.dataFormatDescriptor[ 0 ].colorModel === 0xA7;
  364. // If the device supports ASTC, Basis UASTC HDR requires no transcoder.
  365. const needsTranscoder = container.vkFormat === VK_FORMAT_UNDEFINED
  366. || isBasisHDR && ! this.workerConfig.astcHDRSupported;
  367. if ( ! needsTranscoder ) {
  368. return createRawTexture( container );
  369. }
  370. //
  371. const taskConfig = config;
  372. const texturePending = this.init().then( () => {
  373. return this.workerPool.postMessage( { type: 'transcode', buffer, taskConfig: taskConfig }, [ buffer ] );
  374. } ).then( ( e ) => this._createTextureFrom( e.data, container ) );
  375. // Cache the task result.
  376. _taskCache.set( buffer, { promise: texturePending } );
  377. return texturePending;
  378. }
  379. /**
  380. * Frees internal resources. This method should be called
  381. * when the loader is no longer required.
  382. */
  383. dispose() {
  384. this.workerPool.dispose();
  385. if ( this.workerSourceURL ) URL.revokeObjectURL( this.workerSourceURL );
  386. _activeLoaders --;
  387. }
  388. }
  389. /* CONSTANTS */
  390. KTX2Loader.BasisFormat = {
  391. ETC1S: 0,
  392. UASTC: 1,
  393. UASTC_HDR: 2,
  394. };
  395. // Source: https://github.com/BinomialLLC/basis_universal/blob/master/webgl/texture_test/index.html
  396. KTX2Loader.TranscoderFormat = {
  397. ETC1: 0,
  398. ETC2: 1,
  399. BC1: 2,
  400. BC3: 3,
  401. BC4: 4,
  402. BC5: 5,
  403. BC7_M6_OPAQUE_ONLY: 6,
  404. BC7_M5: 7,
  405. PVRTC1_4_RGB: 8,
  406. PVRTC1_4_RGBA: 9,
  407. ASTC_4x4: 10,
  408. ATC_RGB: 11,
  409. ATC_RGBA_INTERPOLATED_ALPHA: 12,
  410. RGBA32: 13,
  411. RGB565: 14,
  412. BGR565: 15,
  413. RGBA4444: 16,
  414. BC6H: 22,
  415. RGB_HALF: 24,
  416. RGBA_HALF: 25,
  417. };
  418. KTX2Loader.EngineFormat = {
  419. RGBAFormat: RGBAFormat,
  420. RGBA_ASTC_4x4_Format: RGBA_ASTC_4x4_Format,
  421. RGB_BPTC_UNSIGNED_Format: RGB_BPTC_UNSIGNED_Format,
  422. RGBA_BPTC_Format: RGBA_BPTC_Format,
  423. RGBA_ETC2_EAC_Format: RGBA_ETC2_EAC_Format,
  424. RGBA_PVRTC_4BPPV1_Format: RGBA_PVRTC_4BPPV1_Format,
  425. RGBA_S3TC_DXT5_Format: RGBA_S3TC_DXT5_Format,
  426. RGB_ETC1_Format: RGB_ETC1_Format,
  427. RGB_ETC2_Format: RGB_ETC2_Format,
  428. RGB_PVRTC_4BPPV1_Format: RGB_PVRTC_4BPPV1_Format,
  429. RGBA_S3TC_DXT1_Format: RGBA_S3TC_DXT1_Format,
  430. };
  431. KTX2Loader.EngineType = {
  432. UnsignedByteType: UnsignedByteType,
  433. HalfFloatType: HalfFloatType,
  434. FloatType: FloatType,
  435. };
  436. /* WEB WORKER */
  437. KTX2Loader.BasisWorker = function () {
  438. let config;
  439. let transcoderPending;
  440. let BasisModule;
  441. const EngineFormat = _EngineFormat; // eslint-disable-line no-undef
  442. const EngineType = _EngineType; // eslint-disable-line no-undef
  443. const TranscoderFormat = _TranscoderFormat; // eslint-disable-line no-undef
  444. const BasisFormat = _BasisFormat; // eslint-disable-line no-undef
  445. self.addEventListener( 'message', function ( e ) {
  446. const message = e.data;
  447. switch ( message.type ) {
  448. case 'init':
  449. config = message.config;
  450. init( message.transcoderBinary );
  451. break;
  452. case 'transcode':
  453. transcoderPending.then( () => {
  454. try {
  455. const { faces, buffers, width, height, hasAlpha, format, type, dfdFlags } = transcode( message.buffer );
  456. self.postMessage( { type: 'transcode', id: message.id, data: { faces, width, height, hasAlpha, format, type, dfdFlags } }, buffers );
  457. } catch ( error ) {
  458. console.error( error );
  459. self.postMessage( { type: 'error', id: message.id, error: error.message } );
  460. }
  461. } );
  462. break;
  463. }
  464. } );
  465. function init( wasmBinary ) {
  466. transcoderPending = new Promise( ( resolve ) => {
  467. BasisModule = { wasmBinary, onRuntimeInitialized: resolve };
  468. BASIS( BasisModule ); // eslint-disable-line no-undef
  469. } ).then( () => {
  470. BasisModule.initializeBasis();
  471. if ( BasisModule.KTX2File === undefined ) {
  472. console.warn( 'THREE.KTX2Loader: Please update Basis Universal transcoder.' );
  473. }
  474. } );
  475. }
  476. function transcode( buffer ) {
  477. const ktx2File = new BasisModule.KTX2File( new Uint8Array( buffer ) );
  478. function cleanup() {
  479. ktx2File.close();
  480. ktx2File.delete();
  481. }
  482. if ( ! ktx2File.isValid() ) {
  483. cleanup();
  484. throw new Error( 'THREE.KTX2Loader: Invalid or unsupported .ktx2 file' );
  485. }
  486. let basisFormat;
  487. if ( ktx2File.isUASTC() ) {
  488. basisFormat = BasisFormat.UASTC;
  489. } else if ( ktx2File.isETC1S() ) {
  490. basisFormat = BasisFormat.ETC1S;
  491. } else if ( ktx2File.isHDR() ) {
  492. basisFormat = BasisFormat.UASTC_HDR;
  493. } else {
  494. throw new Error( 'THREE.KTX2Loader: Unknown Basis encoding' );
  495. }
  496. const width = ktx2File.getWidth();
  497. const height = ktx2File.getHeight();
  498. const layerCount = ktx2File.getLayers() || 1;
  499. const levelCount = ktx2File.getLevels();
  500. const faceCount = ktx2File.getFaces();
  501. const hasAlpha = ktx2File.getHasAlpha();
  502. const dfdFlags = ktx2File.getDFDFlags();
  503. const { transcoderFormat, engineFormat, engineType } = getTranscoderFormat( basisFormat, width, height, hasAlpha );
  504. if ( ! width || ! height || ! levelCount ) {
  505. cleanup();
  506. throw new Error( 'THREE.KTX2Loader: Invalid texture' );
  507. }
  508. if ( ! ktx2File.startTranscoding() ) {
  509. cleanup();
  510. throw new Error( 'THREE.KTX2Loader: .startTranscoding failed' );
  511. }
  512. const faces = [];
  513. const buffers = [];
  514. for ( let face = 0; face < faceCount; face ++ ) {
  515. const mipmaps = [];
  516. for ( let mip = 0; mip < levelCount; mip ++ ) {
  517. const layerMips = [];
  518. let mipWidth, mipHeight;
  519. for ( let layer = 0; layer < layerCount; layer ++ ) {
  520. const levelInfo = ktx2File.getImageLevelInfo( mip, layer, face );
  521. if ( face === 0 && mip === 0 && layer === 0 && ( levelInfo.origWidth % 4 !== 0 || levelInfo.origHeight % 4 !== 0 ) ) {
  522. console.warn( 'THREE.KTX2Loader: ETC1S and UASTC textures should use multiple-of-four dimensions.' );
  523. }
  524. if ( levelCount > 1 ) {
  525. mipWidth = levelInfo.origWidth;
  526. mipHeight = levelInfo.origHeight;
  527. } else {
  528. // Handles non-multiple-of-four dimensions in textures without mipmaps. Textures with
  529. // mipmaps must use multiple-of-four dimensions, for some texture formats and APIs.
  530. // See mrdoob/three.js#25908.
  531. mipWidth = levelInfo.width;
  532. mipHeight = levelInfo.height;
  533. }
  534. let dst = new Uint8Array( ktx2File.getImageTranscodedSizeInBytes( mip, layer, 0, transcoderFormat ) );
  535. const status = ktx2File.transcodeImage( dst, mip, layer, face, transcoderFormat, 0, - 1, - 1 );
  536. if ( engineType === EngineType.HalfFloatType ) {
  537. dst = new Uint16Array( dst.buffer, dst.byteOffset, dst.byteLength / Uint16Array.BYTES_PER_ELEMENT );
  538. }
  539. if ( ! status ) {
  540. cleanup();
  541. throw new Error( 'THREE.KTX2Loader: .transcodeImage failed.' );
  542. }
  543. layerMips.push( dst );
  544. }
  545. const mipData = concat( layerMips );
  546. mipmaps.push( { data: mipData, width: mipWidth, height: mipHeight } );
  547. buffers.push( mipData.buffer );
  548. }
  549. faces.push( { mipmaps, width, height, format: engineFormat, type: engineType } );
  550. }
  551. cleanup();
  552. return { faces, buffers, width, height, hasAlpha, dfdFlags, format: engineFormat, type: engineType };
  553. }
  554. //
  555. // Optimal choice of a transcoder target format depends on the Basis format (ETC1S, UASTC, or
  556. // UASTC HDR), device capabilities, and texture dimensions. The list below ranks the formats
  557. // separately for each format. Currently, priority is assigned based on:
  558. //
  559. // high quality > low quality > uncompressed
  560. //
  561. // Prioritization may be revisited, or exposed for configuration, in the future.
  562. //
  563. // Reference: https://github.com/KhronosGroup/3D-Formats-Guidelines/blob/main/KTXDeveloperGuide.md
  564. const FORMAT_OPTIONS = [
  565. {
  566. if: 'astcSupported',
  567. basisFormat: [ BasisFormat.UASTC ],
  568. transcoderFormat: [ TranscoderFormat.ASTC_4x4, TranscoderFormat.ASTC_4x4 ],
  569. engineFormat: [ EngineFormat.RGBA_ASTC_4x4_Format, EngineFormat.RGBA_ASTC_4x4_Format ],
  570. engineType: [ EngineType.UnsignedByteType ],
  571. priorityETC1S: Infinity,
  572. priorityUASTC: 1,
  573. needsPowerOfTwo: false,
  574. },
  575. {
  576. if: 'bptcSupported',
  577. basisFormat: [ BasisFormat.ETC1S, BasisFormat.UASTC ],
  578. transcoderFormat: [ TranscoderFormat.BC7_M5, TranscoderFormat.BC7_M5 ],
  579. engineFormat: [ EngineFormat.RGBA_BPTC_Format, EngineFormat.RGBA_BPTC_Format ],
  580. engineType: [ EngineType.UnsignedByteType ],
  581. priorityETC1S: 3,
  582. priorityUASTC: 2,
  583. needsPowerOfTwo: false,
  584. },
  585. {
  586. if: 'dxtSupported',
  587. basisFormat: [ BasisFormat.ETC1S, BasisFormat.UASTC ],
  588. transcoderFormat: [ TranscoderFormat.BC1, TranscoderFormat.BC3 ],
  589. engineFormat: [ EngineFormat.RGBA_S3TC_DXT1_Format, EngineFormat.RGBA_S3TC_DXT5_Format ],
  590. engineType: [ EngineType.UnsignedByteType ],
  591. priorityETC1S: 4,
  592. priorityUASTC: 5,
  593. needsPowerOfTwo: false,
  594. },
  595. {
  596. if: 'etc2Supported',
  597. basisFormat: [ BasisFormat.ETC1S, BasisFormat.UASTC ],
  598. transcoderFormat: [ TranscoderFormat.ETC1, TranscoderFormat.ETC2 ],
  599. engineFormat: [ EngineFormat.RGB_ETC2_Format, EngineFormat.RGBA_ETC2_EAC_Format ],
  600. engineType: [ EngineType.UnsignedByteType ],
  601. priorityETC1S: 1,
  602. priorityUASTC: 3,
  603. needsPowerOfTwo: false,
  604. },
  605. {
  606. if: 'etc1Supported',
  607. basisFormat: [ BasisFormat.ETC1S, BasisFormat.UASTC ],
  608. transcoderFormat: [ TranscoderFormat.ETC1 ],
  609. engineFormat: [ EngineFormat.RGB_ETC1_Format ],
  610. engineType: [ EngineType.UnsignedByteType ],
  611. priorityETC1S: 2,
  612. priorityUASTC: 4,
  613. needsPowerOfTwo: false,
  614. },
  615. {
  616. if: 'pvrtcSupported',
  617. basisFormat: [ BasisFormat.ETC1S, BasisFormat.UASTC ],
  618. transcoderFormat: [ TranscoderFormat.PVRTC1_4_RGB, TranscoderFormat.PVRTC1_4_RGBA ],
  619. engineFormat: [ EngineFormat.RGB_PVRTC_4BPPV1_Format, EngineFormat.RGBA_PVRTC_4BPPV1_Format ],
  620. engineType: [ EngineType.UnsignedByteType ],
  621. priorityETC1S: 5,
  622. priorityUASTC: 6,
  623. needsPowerOfTwo: true,
  624. },
  625. {
  626. if: 'bptcSupported',
  627. basisFormat: [ BasisFormat.UASTC_HDR ],
  628. transcoderFormat: [ TranscoderFormat.BC6H ],
  629. engineFormat: [ EngineFormat.RGB_BPTC_UNSIGNED_Format ],
  630. engineType: [ EngineType.HalfFloatType ],
  631. priorityHDR: 1,
  632. needsPowerOfTwo: false,
  633. },
  634. // Uncompressed fallbacks.
  635. {
  636. basisFormat: [ BasisFormat.ETC1S, BasisFormat.UASTC ],
  637. transcoderFormat: [ TranscoderFormat.RGBA32, TranscoderFormat.RGBA32 ],
  638. engineFormat: [ EngineFormat.RGBAFormat, EngineFormat.RGBAFormat ],
  639. engineType: [ EngineType.UnsignedByteType, EngineType.UnsignedByteType ],
  640. priorityETC1S: 100,
  641. priorityUASTC: 100,
  642. needsPowerOfTwo: false,
  643. },
  644. {
  645. basisFormat: [ BasisFormat.UASTC_HDR ],
  646. transcoderFormat: [ TranscoderFormat.RGBA_HALF ],
  647. engineFormat: [ EngineFormat.RGBAFormat ],
  648. engineType: [ EngineType.HalfFloatType ],
  649. priorityHDR: 100,
  650. needsPowerOfTwo: false,
  651. }
  652. ];
  653. const OPTIONS = {
  654. [ BasisFormat.ETC1S ]: FORMAT_OPTIONS
  655. .filter( ( opt ) => opt.basisFormat.includes( BasisFormat.ETC1S ) )
  656. .sort( ( a, b ) => a.priorityETC1S - b.priorityETC1S ),
  657. [ BasisFormat.UASTC ]: FORMAT_OPTIONS
  658. .filter( ( opt ) => opt.basisFormat.includes( BasisFormat.UASTC ) )
  659. .sort( ( a, b ) => a.priorityUASTC - b.priorityUASTC ),
  660. [ BasisFormat.UASTC_HDR ]: FORMAT_OPTIONS
  661. .filter( ( opt ) => opt.basisFormat.includes( BasisFormat.UASTC_HDR ) )
  662. .sort( ( a, b ) => a.priorityHDR - b.priorityHDR ),
  663. };
  664. function getTranscoderFormat( basisFormat, width, height, hasAlpha ) {
  665. const options = OPTIONS[ basisFormat ];
  666. for ( let i = 0; i < options.length; i ++ ) {
  667. const opt = options[ i ];
  668. if ( opt.if && ! config[ opt.if ] ) continue;
  669. if ( ! opt.basisFormat.includes( basisFormat ) ) continue;
  670. if ( hasAlpha && opt.transcoderFormat.length < 2 ) continue;
  671. if ( opt.needsPowerOfTwo && ! ( isPowerOfTwo( width ) && isPowerOfTwo( height ) ) ) continue;
  672. const transcoderFormat = opt.transcoderFormat[ hasAlpha ? 1 : 0 ];
  673. const engineFormat = opt.engineFormat[ hasAlpha ? 1 : 0 ];
  674. const engineType = opt.engineType[ 0 ];
  675. return { transcoderFormat, engineFormat, engineType };
  676. }
  677. throw new Error( 'THREE.KTX2Loader: Failed to identify transcoding target.' );
  678. }
  679. function isPowerOfTwo( value ) {
  680. if ( value <= 2 ) return true;
  681. return ( value & ( value - 1 ) ) === 0 && value !== 0;
  682. }
  683. /**
  684. * Concatenates N byte arrays.
  685. *
  686. * @param {Uint8Array[]} arrays
  687. * @return {Uint8Array}
  688. */
  689. function concat( arrays ) {
  690. if ( arrays.length === 1 ) return arrays[ 0 ];
  691. let totalByteLength = 0;
  692. for ( let i = 0; i < arrays.length; i ++ ) {
  693. const array = arrays[ i ];
  694. totalByteLength += array.byteLength;
  695. }
  696. const result = new Uint8Array( totalByteLength );
  697. let byteOffset = 0;
  698. for ( let i = 0; i < arrays.length; i ++ ) {
  699. const array = arrays[ i ];
  700. result.set( array, byteOffset );
  701. byteOffset += array.byteLength;
  702. }
  703. return result;
  704. }
  705. };
  706. // Parsing for non-Basis textures. These textures may have supercompression
  707. // like Zstd, but they do not require transcoding.
  708. const UNCOMPRESSED_FORMATS = new Set( [ RGBAFormat, RGBFormat, RGFormat, RedFormat ] );
  709. const FORMAT_MAP = {
  710. [ VK_FORMAT_R32G32B32A32_SFLOAT ]: RGBAFormat,
  711. [ VK_FORMAT_R32G32_SFLOAT ]: RGFormat,
  712. [ VK_FORMAT_R32_SFLOAT ]: RedFormat,
  713. [ VK_FORMAT_R16G16B16A16_SFLOAT ]: RGBAFormat,
  714. [ VK_FORMAT_R16G16_SFLOAT ]: RGFormat,
  715. [ VK_FORMAT_R16_SFLOAT ]: RedFormat,
  716. [ VK_FORMAT_R16G16B16A16_UNORM ]: RGBAFormat,
  717. [ VK_FORMAT_R8G8B8A8_SRGB ]: RGBAFormat,
  718. [ VK_FORMAT_R8G8B8A8_UNORM ]: RGBAFormat,
  719. [ VK_FORMAT_R8G8_SRGB ]: RGFormat,
  720. [ VK_FORMAT_R8G8_UNORM ]: RGFormat,
  721. [ VK_FORMAT_R8_SRGB ]: RedFormat,
  722. [ VK_FORMAT_R8_UNORM ]: RedFormat,
  723. [ VK_FORMAT_E5B9G9R9_UFLOAT_PACK32 ]: RGBFormat,
  724. [ VK_FORMAT_B10G11R11_UFLOAT_PACK32 ]: RGBFormat,
  725. [ VK_FORMAT_ETC2_R8G8B8A8_SRGB_BLOCK ]: RGBA_ETC2_EAC_Format,
  726. [ VK_FORMAT_ETC2_R8G8B8_SRGB_BLOCK ]: RGB_ETC2_Format,
  727. [ VK_FORMAT_EAC_R11_UNORM_BLOCK ]: R11_EAC_Format,
  728. [ VK_FORMAT_EAC_R11_SNORM_BLOCK ]: SIGNED_R11_EAC_Format,
  729. [ VK_FORMAT_EAC_R11G11_UNORM_BLOCK ]: RG11_EAC_Format,
  730. [ VK_FORMAT_EAC_R11G11_SNORM_BLOCK ]: SIGNED_RG11_EAC_Format,
  731. [ VK_FORMAT_ASTC_4x4_SFLOAT_BLOCK_EXT ]: RGBA_ASTC_4x4_Format,
  732. [ VK_FORMAT_ASTC_4x4_SRGB_BLOCK ]: RGBA_ASTC_4x4_Format,
  733. [ VK_FORMAT_ASTC_4x4_UNORM_BLOCK ]: RGBA_ASTC_4x4_Format,
  734. [ VK_FORMAT_ASTC_6x6_SFLOAT_BLOCK_EXT ]: RGBA_ASTC_6x6_Format,
  735. [ VK_FORMAT_ASTC_6x6_SRGB_BLOCK ]: RGBA_ASTC_6x6_Format,
  736. [ VK_FORMAT_ASTC_6x6_UNORM_BLOCK ]: RGBA_ASTC_6x6_Format,
  737. [ VK_FORMAT_BC1_RGBA_SRGB_BLOCK ]: RGBA_S3TC_DXT1_Format,
  738. [ VK_FORMAT_BC1_RGBA_UNORM_BLOCK ]: RGBA_S3TC_DXT1_Format,
  739. [ VK_FORMAT_BC1_RGB_SRGB_BLOCK ]: RGB_S3TC_DXT1_Format,
  740. [ VK_FORMAT_BC1_RGB_UNORM_BLOCK ]: RGB_S3TC_DXT1_Format,
  741. [ VK_FORMAT_BC3_SRGB_BLOCK ]: RGBA_S3TC_DXT5_Format,
  742. [ VK_FORMAT_BC3_UNORM_BLOCK ]: RGBA_S3TC_DXT5_Format,
  743. [ VK_FORMAT_BC4_SNORM_BLOCK ]: SIGNED_RED_RGTC1_Format,
  744. [ VK_FORMAT_BC4_UNORM_BLOCK ]: RED_RGTC1_Format,
  745. [ VK_FORMAT_BC5_SNORM_BLOCK ]: SIGNED_RED_GREEN_RGTC2_Format,
  746. [ VK_FORMAT_BC5_UNORM_BLOCK ]: RED_GREEN_RGTC2_Format,
  747. [ VK_FORMAT_BC7_SRGB_BLOCK ]: RGBA_BPTC_Format,
  748. [ VK_FORMAT_BC7_UNORM_BLOCK ]: RGBA_BPTC_Format,
  749. [ VK_FORMAT_PVRTC1_4BPP_SRGB_BLOCK_IMG ]: RGBA_PVRTC_4BPPV1_Format,
  750. [ VK_FORMAT_PVRTC1_4BPP_UNORM_BLOCK_IMG ]: RGBA_PVRTC_4BPPV1_Format,
  751. [ VK_FORMAT_PVRTC1_2BPP_SRGB_BLOCK_IMG ]: RGBA_PVRTC_2BPPV1_Format,
  752. [ VK_FORMAT_PVRTC1_2BPP_UNORM_BLOCK_IMG ]: RGBA_PVRTC_2BPPV1_Format,
  753. };
  754. const TYPE_MAP = {
  755. [ VK_FORMAT_R32G32B32A32_SFLOAT ]: FloatType,
  756. [ VK_FORMAT_R32G32_SFLOAT ]: FloatType,
  757. [ VK_FORMAT_R32_SFLOAT ]: FloatType,
  758. [ VK_FORMAT_R16G16B16A16_SFLOAT ]: HalfFloatType,
  759. [ VK_FORMAT_R16G16_SFLOAT ]: HalfFloatType,
  760. [ VK_FORMAT_R16_SFLOAT ]: HalfFloatType,
  761. [ VK_FORMAT_R16G16B16A16_UNORM ]: UnsignedShortType,
  762. [ VK_FORMAT_R8G8B8A8_SRGB ]: UnsignedByteType,
  763. [ VK_FORMAT_R8G8B8A8_UNORM ]: UnsignedByteType,
  764. [ VK_FORMAT_R8G8_SRGB ]: UnsignedByteType,
  765. [ VK_FORMAT_R8G8_UNORM ]: UnsignedByteType,
  766. [ VK_FORMAT_R8_SRGB ]: UnsignedByteType,
  767. [ VK_FORMAT_R8_UNORM ]: UnsignedByteType,
  768. [ VK_FORMAT_E5B9G9R9_UFLOAT_PACK32 ]: UnsignedInt5999Type,
  769. [ VK_FORMAT_B10G11R11_UFLOAT_PACK32 ]: UnsignedInt101111Type,
  770. [ VK_FORMAT_ETC2_R8G8B8A8_SRGB_BLOCK ]: UnsignedByteType,
  771. [ VK_FORMAT_ETC2_R8G8B8_SRGB_BLOCK ]: UnsignedByteType,
  772. [ VK_FORMAT_EAC_R11_UNORM_BLOCK ]: UnsignedByteType,
  773. [ VK_FORMAT_EAC_R11_SNORM_BLOCK ]: UnsignedByteType,
  774. [ VK_FORMAT_EAC_R11G11_UNORM_BLOCK ]: UnsignedByteType,
  775. [ VK_FORMAT_EAC_R11G11_SNORM_BLOCK ]: UnsignedByteType,
  776. [ VK_FORMAT_ASTC_4x4_SFLOAT_BLOCK_EXT ]: HalfFloatType,
  777. [ VK_FORMAT_ASTC_4x4_SRGB_BLOCK ]: UnsignedByteType,
  778. [ VK_FORMAT_ASTC_4x4_UNORM_BLOCK ]: UnsignedByteType,
  779. [ VK_FORMAT_ASTC_6x6_SFLOAT_BLOCK_EXT ]: HalfFloatType,
  780. [ VK_FORMAT_ASTC_6x6_SRGB_BLOCK ]: UnsignedByteType,
  781. [ VK_FORMAT_ASTC_6x6_UNORM_BLOCK ]: UnsignedByteType,
  782. [ VK_FORMAT_BC1_RGBA_SRGB_BLOCK ]: UnsignedByteType,
  783. [ VK_FORMAT_BC1_RGBA_UNORM_BLOCK ]: UnsignedByteType,
  784. [ VK_FORMAT_BC1_RGB_SRGB_BLOCK ]: UnsignedByteType,
  785. [ VK_FORMAT_BC1_RGB_UNORM_BLOCK ]: UnsignedByteType,
  786. [ VK_FORMAT_BC3_SRGB_BLOCK ]: UnsignedByteType,
  787. [ VK_FORMAT_BC3_UNORM_BLOCK ]: UnsignedByteType,
  788. [ VK_FORMAT_BC4_SNORM_BLOCK ]: UnsignedByteType,
  789. [ VK_FORMAT_BC4_UNORM_BLOCK ]: UnsignedByteType,
  790. [ VK_FORMAT_BC5_SNORM_BLOCK ]: UnsignedByteType,
  791. [ VK_FORMAT_BC5_UNORM_BLOCK ]: UnsignedByteType,
  792. [ VK_FORMAT_BC7_SRGB_BLOCK ]: UnsignedByteType,
  793. [ VK_FORMAT_BC7_UNORM_BLOCK ]: UnsignedByteType,
  794. [ VK_FORMAT_PVRTC1_4BPP_SRGB_BLOCK_IMG ]: UnsignedByteType,
  795. [ VK_FORMAT_PVRTC1_4BPP_UNORM_BLOCK_IMG ]: UnsignedByteType,
  796. [ VK_FORMAT_PVRTC1_2BPP_SRGB_BLOCK_IMG ]: UnsignedByteType,
  797. [ VK_FORMAT_PVRTC1_2BPP_UNORM_BLOCK_IMG ]: UnsignedByteType,
  798. };
  799. async function createRawTexture( container ) {
  800. const { vkFormat } = container;
  801. if ( FORMAT_MAP[ vkFormat ] === undefined ) {
  802. throw new Error( 'THREE.KTX2Loader: Unsupported vkFormat: ' + vkFormat );
  803. }
  804. // TODO: Merge the TYPE_MAP warning into the thrown error above, after r190.
  805. if ( TYPE_MAP[ vkFormat ] === undefined ) {
  806. console.warn( 'THREE.KTX2Loader: Missing ".type" for vkFormat: ' + vkFormat );
  807. }
  808. //
  809. let zstd;
  810. if ( container.supercompressionScheme === KHR_SUPERCOMPRESSION_ZSTD ) {
  811. if ( ! _zstd ) {
  812. _zstd = new Promise( async ( resolve ) => {
  813. const zstd = new ZSTDDecoder();
  814. await zstd.init();
  815. resolve( zstd );
  816. } );
  817. }
  818. zstd = await _zstd;
  819. }
  820. //
  821. const mipmaps = [];
  822. for ( let levelIndex = 0; levelIndex < container.levels.length; levelIndex ++ ) {
  823. const levelWidth = Math.max( 1, container.pixelWidth >> levelIndex );
  824. const levelHeight = Math.max( 1, container.pixelHeight >> levelIndex );
  825. const levelDepth = container.pixelDepth ? Math.max( 1, container.pixelDepth >> levelIndex ) : 0;
  826. const level = container.levels[ levelIndex ];
  827. let levelData;
  828. if ( container.supercompressionScheme === KHR_SUPERCOMPRESSION_NONE ) {
  829. levelData = level.levelData;
  830. } else if ( container.supercompressionScheme === KHR_SUPERCOMPRESSION_ZSTD ) {
  831. levelData = zstd.decode( level.levelData, level.uncompressedByteLength );
  832. } else {
  833. throw new Error( 'THREE.KTX2Loader: Unsupported supercompressionScheme.' );
  834. }
  835. let data;
  836. if ( TYPE_MAP[ vkFormat ] === FloatType ) {
  837. data = new Float32Array(
  838. levelData.buffer,
  839. levelData.byteOffset,
  840. levelData.byteLength / Float32Array.BYTES_PER_ELEMENT
  841. );
  842. } else if ( TYPE_MAP[ vkFormat ] === HalfFloatType || TYPE_MAP[ vkFormat ] === UnsignedShortType ) {
  843. data = new Uint16Array(
  844. levelData.buffer,
  845. levelData.byteOffset,
  846. levelData.byteLength / Uint16Array.BYTES_PER_ELEMENT
  847. );
  848. } else if ( TYPE_MAP[ vkFormat ] === UnsignedInt5999Type || TYPE_MAP[ vkFormat ] === UnsignedInt101111Type ) {
  849. data = new Uint32Array(
  850. levelData.buffer,
  851. levelData.byteOffset,
  852. levelData.byteLength / Uint32Array.BYTES_PER_ELEMENT
  853. );
  854. } else {
  855. data = levelData;
  856. }
  857. mipmaps.push( {
  858. data: data,
  859. width: levelWidth,
  860. height: levelHeight,
  861. depth: levelDepth,
  862. } );
  863. }
  864. // levelCount = 0 implies runtime-generated mipmaps.
  865. const useMipmaps = container.levelCount === 0 || mipmaps.length > 1;
  866. let texture;
  867. if ( UNCOMPRESSED_FORMATS.has( FORMAT_MAP[ vkFormat ] ) ) {
  868. texture = container.pixelDepth === 0
  869. ? new DataTexture( mipmaps[ 0 ].data, container.pixelWidth, container.pixelHeight )
  870. : new Data3DTexture( mipmaps[ 0 ].data, container.pixelWidth, container.pixelHeight, container.pixelDepth );
  871. texture.minFilter = useMipmaps ? NearestMipmapNearestFilter : NearestFilter;
  872. texture.magFilter = NearestFilter;
  873. texture.generateMipmaps = container.levelCount === 0;
  874. } else {
  875. if ( container.pixelDepth > 0 ) throw new Error( 'THREE.KTX2Loader: Unsupported pixelDepth.' );
  876. texture = new CompressedTexture( mipmaps, container.pixelWidth, container.pixelHeight );
  877. texture.minFilter = useMipmaps ? LinearMipmapLinearFilter : LinearFilter;
  878. texture.magFilter = LinearFilter;
  879. }
  880. texture.mipmaps = mipmaps;
  881. texture.type = TYPE_MAP[ vkFormat ];
  882. texture.format = FORMAT_MAP[ vkFormat ];
  883. texture.colorSpace = parseColorSpace( container );
  884. texture.needsUpdate = true;
  885. //
  886. return Promise.resolve( texture );
  887. }
  888. function parseColorSpace( container ) {
  889. const dfd = container.dataFormatDescriptor[ 0 ];
  890. if ( dfd.colorPrimaries === KHR_DF_PRIMARIES_BT709 ) {
  891. return dfd.transferFunction === KHR_DF_TRANSFER_SRGB ? SRGBColorSpace : LinearSRGBColorSpace;
  892. } else if ( dfd.colorPrimaries === KHR_DF_PRIMARIES_DISPLAYP3 ) {
  893. return dfd.transferFunction === KHR_DF_TRANSFER_SRGB ? DisplayP3ColorSpace : LinearDisplayP3ColorSpace;
  894. } else if ( dfd.colorPrimaries === KHR_DF_PRIMARIES_UNSPECIFIED ) {
  895. return NoColorSpace;
  896. } else {
  897. console.warn( `THREE.KTX2Loader: Unsupported color primaries, "${ dfd.colorPrimaries }"` );
  898. return NoColorSpace;
  899. }
  900. }
  901. export { KTX2Loader };
粤ICP备19079148号