KTX2Loader.js 34 KB

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