KTX2Loader.js 36 KB

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