KTX2Loader.js 35 KB

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