KTX2Loader.js 34 KB

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