KTX2Loader.js 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721
  1. /**
  2. * Loader for KTX 2.0 GPU Texture containers.
  3. *
  4. * KTX 2.0 is a container format for various GPU texture formats. The loader
  5. * supports Basis Universal GPU textures, which can be quickly transcoded to
  6. * a wide variety of GPU texture compression formats, as well as some
  7. * uncompressed DataTexture and Data3DTexture formats.
  8. *
  9. * References:
  10. * - KTX: http://github.khronos.org/KTX-Specification/
  11. * - DFD: https://www.khronos.org/registry/DataFormat/specs/1.3/dataformat.1.3.html#basicdescriptor
  12. */
  13. import {
  14. CompressedTexture,
  15. Data3DTexture,
  16. DataTexture,
  17. FileLoader,
  18. FloatType,
  19. HalfFloatType,
  20. LinearEncoding,
  21. LinearFilter,
  22. LinearMipmapLinearFilter,
  23. Loader,
  24. RedFormat,
  25. RGB_ETC1_Format,
  26. RGB_ETC2_Format,
  27. RGB_PVRTC_4BPPV1_Format,
  28. RGB_S3TC_DXT1_Format,
  29. RGBA_ASTC_4x4_Format,
  30. RGBA_BPTC_Format,
  31. RGBA_ETC2_EAC_Format,
  32. RGBA_PVRTC_4BPPV1_Format,
  33. RGBA_S3TC_DXT5_Format,
  34. RGBAFormat,
  35. RGFormat,
  36. sRGBEncoding,
  37. UnsignedByteType
  38. } from 'three';
  39. import { WorkerPool } from '../utils/WorkerPool.js';
  40. import {
  41. read,
  42. VK_FORMAT_UNDEFINED,
  43. VK_FORMAT_R16_SFLOAT,
  44. VK_FORMAT_R16G16_SFLOAT,
  45. VK_FORMAT_R16G16B16A16_SFLOAT,
  46. VK_FORMAT_R32_SFLOAT,
  47. VK_FORMAT_R32G32_SFLOAT,
  48. VK_FORMAT_R32G32B32A32_SFLOAT,
  49. VK_FORMAT_R8_SRGB,
  50. VK_FORMAT_R8_UNORM,
  51. VK_FORMAT_R8G8_SRGB,
  52. VK_FORMAT_R8G8_UNORM,
  53. VK_FORMAT_R8G8B8A8_SRGB,
  54. VK_FORMAT_R8G8B8A8_UNORM,
  55. } from '../libs/ktx-parse.module.js';
  56. const KTX2TransferSRGB = 2;
  57. const KTX2_ALPHA_PREMULTIPLIED = 1;
  58. const _taskCache = new WeakMap();
  59. let _activeLoaders = 0;
  60. class KTX2Loader extends Loader {
  61. constructor( manager ) {
  62. super( manager );
  63. this.transcoderPath = '';
  64. this.transcoderBinary = null;
  65. this.transcoderPending = null;
  66. this.workerPool = new WorkerPool();
  67. this.workerSourceURL = '';
  68. this.workerConfig = null;
  69. if ( typeof MSC_TRANSCODER !== 'undefined' ) {
  70. console.warn(
  71. 'THREE.KTX2Loader: Please update to latest "basis_transcoder".'
  72. + ' "msc_basis_transcoder" is no longer supported in three.js r125+.'
  73. );
  74. }
  75. }
  76. setTranscoderPath( path ) {
  77. this.transcoderPath = path;
  78. return this;
  79. }
  80. setWorkerLimit( num ) {
  81. this.workerPool.setWorkerLimit( num );
  82. return this;
  83. }
  84. detectSupport( renderer ) {
  85. this.workerConfig = {
  86. astcSupported: renderer.extensions.has( 'WEBGL_compressed_texture_astc' ),
  87. etc1Supported: renderer.extensions.has( 'WEBGL_compressed_texture_etc1' ),
  88. etc2Supported: renderer.extensions.has( 'WEBGL_compressed_texture_etc' ),
  89. dxtSupported: renderer.extensions.has( 'WEBGL_compressed_texture_s3tc' ),
  90. bptcSupported: renderer.extensions.has( 'EXT_texture_compression_bptc' ),
  91. pvrtcSupported: renderer.extensions.has( 'WEBGL_compressed_texture_pvrtc' )
  92. || renderer.extensions.has( 'WEBKIT_WEBGL_compressed_texture_pvrtc' )
  93. };
  94. if ( renderer.capabilities.isWebGL2 ) {
  95. // https://github.com/mrdoob/three.js/pull/22928
  96. this.workerConfig.etc1Supported = false;
  97. }
  98. return this;
  99. }
  100. init() {
  101. if ( ! this.transcoderPending ) {
  102. // Load transcoder wrapper.
  103. const jsLoader = new FileLoader( this.manager );
  104. jsLoader.setPath( this.transcoderPath );
  105. jsLoader.setWithCredentials( this.withCredentials );
  106. const jsContent = jsLoader.loadAsync( 'basis_transcoder.js' );
  107. // Load transcoder WASM binary.
  108. const binaryLoader = new FileLoader( this.manager );
  109. binaryLoader.setPath( this.transcoderPath );
  110. binaryLoader.setResponseType( 'arraybuffer' );
  111. binaryLoader.setWithCredentials( this.withCredentials );
  112. const binaryContent = binaryLoader.loadAsync( 'basis_transcoder.wasm' );
  113. this.transcoderPending = Promise.all( [ jsContent, binaryContent ] )
  114. .then( ( [ jsContent, binaryContent ] ) => {
  115. const fn = KTX2Loader.BasisWorker.toString();
  116. const body = [
  117. '/* constants */',
  118. 'let _EngineFormat = ' + JSON.stringify( KTX2Loader.EngineFormat ),
  119. 'let _TranscoderFormat = ' + JSON.stringify( KTX2Loader.TranscoderFormat ),
  120. 'let _BasisFormat = ' + JSON.stringify( KTX2Loader.BasisFormat ),
  121. '/* basis_transcoder.js */',
  122. jsContent,
  123. '/* worker */',
  124. fn.substring( fn.indexOf( '{' ) + 1, fn.lastIndexOf( '}' ) )
  125. ].join( '\n' );
  126. this.workerSourceURL = URL.createObjectURL( new Blob( [ body ] ) );
  127. this.transcoderBinary = binaryContent;
  128. this.workerPool.setWorkerCreator( () => {
  129. const worker = new Worker( this.workerSourceURL );
  130. const transcoderBinary = this.transcoderBinary.slice( 0 );
  131. worker.postMessage( { type: 'init', config: this.workerConfig, transcoderBinary }, [ transcoderBinary ] );
  132. return worker;
  133. } );
  134. } );
  135. if ( _activeLoaders > 0 ) {
  136. // Each instance loads a transcoder and allocates workers, increasing network and memory cost.
  137. console.warn(
  138. 'THREE.KTX2Loader: Multiple active KTX2 loaders may cause performance issues.'
  139. + ' Use a single KTX2Loader instance, or call .dispose() on old instances.'
  140. );
  141. }
  142. _activeLoaders ++;
  143. }
  144. return this.transcoderPending;
  145. }
  146. load( url, onLoad, onProgress, onError ) {
  147. if ( this.workerConfig === null ) {
  148. throw new Error( 'THREE.KTX2Loader: Missing initialization with `.detectSupport( renderer )`.' );
  149. }
  150. const loader = new FileLoader( this.manager );
  151. loader.setResponseType( 'arraybuffer' );
  152. loader.setWithCredentials( this.withCredentials );
  153. loader.load( url, ( buffer ) => {
  154. // Check for an existing task using this buffer. A transferred buffer cannot be transferred
  155. // again from this thread.
  156. if ( _taskCache.has( buffer ) ) {
  157. const cachedTask = _taskCache.get( buffer );
  158. return cachedTask.promise.then( onLoad ).catch( onError );
  159. }
  160. this._createTexture( buffer )
  161. .then( ( texture ) => onLoad ? onLoad( texture ) : null )
  162. .catch( onError );
  163. }, onProgress, onError );
  164. }
  165. _createTextureFrom( transcodeResult ) {
  166. const { mipmaps, width, height, format, type, error, dfdTransferFn, dfdFlags } = transcodeResult;
  167. if ( type === 'error' ) return Promise.reject( error );
  168. const texture = new CompressedTexture( mipmaps, width, height, format, UnsignedByteType );
  169. texture.minFilter = mipmaps.length === 1 ? LinearFilter : LinearMipmapLinearFilter;
  170. texture.magFilter = LinearFilter;
  171. texture.generateMipmaps = false;
  172. texture.needsUpdate = true;
  173. texture.encoding = dfdTransferFn === KTX2TransferSRGB ? sRGBEncoding : LinearEncoding;
  174. texture.premultiplyAlpha = !! ( dfdFlags & KTX2_ALPHA_PREMULTIPLIED );
  175. return texture;
  176. }
  177. /**
  178. * @param {ArrayBuffer} buffer
  179. * @param {object?} config
  180. * @return {Promise<CompressedTexture|DataTexture|Data3DTexture>}
  181. */
  182. _createTexture( buffer, config = {} ) {
  183. const container = read( new Uint8Array( buffer ) );
  184. if ( container.vkFormat !== VK_FORMAT_UNDEFINED ) {
  185. return createDataTexture( container );
  186. }
  187. //
  188. const taskConfig = config;
  189. const texturePending = this.init().then( () => {
  190. return this.workerPool.postMessage( { type: 'transcode', buffer, taskConfig: taskConfig }, [ buffer ] );
  191. } ).then( ( e ) => this._createTextureFrom( e.data ) );
  192. // Cache the task result.
  193. _taskCache.set( buffer, { promise: texturePending } );
  194. return texturePending;
  195. }
  196. dispose() {
  197. this.workerPool.dispose();
  198. if ( this.workerSourceURL ) URL.revokeObjectURL( this.workerSourceURL );
  199. _activeLoaders --;
  200. return this;
  201. }
  202. }
  203. /* CONSTANTS */
  204. KTX2Loader.BasisFormat = {
  205. ETC1S: 0,
  206. UASTC_4x4: 1,
  207. };
  208. KTX2Loader.TranscoderFormat = {
  209. ETC1: 0,
  210. ETC2: 1,
  211. BC1: 2,
  212. BC3: 3,
  213. BC4: 4,
  214. BC5: 5,
  215. BC7_M6_OPAQUE_ONLY: 6,
  216. BC7_M5: 7,
  217. PVRTC1_4_RGB: 8,
  218. PVRTC1_4_RGBA: 9,
  219. ASTC_4x4: 10,
  220. ATC_RGB: 11,
  221. ATC_RGBA_INTERPOLATED_ALPHA: 12,
  222. RGBA32: 13,
  223. RGB565: 14,
  224. BGR565: 15,
  225. RGBA4444: 16,
  226. };
  227. KTX2Loader.EngineFormat = {
  228. RGBAFormat: RGBAFormat,
  229. RGBA_ASTC_4x4_Format: RGBA_ASTC_4x4_Format,
  230. RGBA_BPTC_Format: RGBA_BPTC_Format,
  231. RGBA_ETC2_EAC_Format: RGBA_ETC2_EAC_Format,
  232. RGBA_PVRTC_4BPPV1_Format: RGBA_PVRTC_4BPPV1_Format,
  233. RGBA_S3TC_DXT5_Format: RGBA_S3TC_DXT5_Format,
  234. RGB_ETC1_Format: RGB_ETC1_Format,
  235. RGB_ETC2_Format: RGB_ETC2_Format,
  236. RGB_PVRTC_4BPPV1_Format: RGB_PVRTC_4BPPV1_Format,
  237. RGB_S3TC_DXT1_Format: RGB_S3TC_DXT1_Format,
  238. };
  239. /* WEB WORKER */
  240. KTX2Loader.BasisWorker = function () {
  241. let config;
  242. let transcoderPending;
  243. let BasisModule;
  244. const EngineFormat = _EngineFormat; // eslint-disable-line no-undef
  245. const TranscoderFormat = _TranscoderFormat; // eslint-disable-line no-undef
  246. const BasisFormat = _BasisFormat; // eslint-disable-line no-undef
  247. self.addEventListener( 'message', function ( e ) {
  248. const message = e.data;
  249. switch ( message.type ) {
  250. case 'init':
  251. config = message.config;
  252. init( message.transcoderBinary );
  253. break;
  254. case 'transcode':
  255. transcoderPending.then( () => {
  256. try {
  257. const { width, height, hasAlpha, mipmaps, format, dfdTransferFn, dfdFlags } = transcode( message.buffer );
  258. const buffers = [];
  259. for ( let i = 0; i < mipmaps.length; ++ i ) {
  260. buffers.push( mipmaps[ i ].data.buffer );
  261. }
  262. self.postMessage( { type: 'transcode', id: message.id, width, height, hasAlpha, mipmaps, format, dfdTransferFn, dfdFlags }, buffers );
  263. } catch ( error ) {
  264. console.error( error );
  265. self.postMessage( { type: 'error', id: message.id, error: error.message } );
  266. }
  267. } );
  268. break;
  269. }
  270. } );
  271. function init( wasmBinary ) {
  272. transcoderPending = new Promise( ( resolve ) => {
  273. BasisModule = { wasmBinary, onRuntimeInitialized: resolve };
  274. BASIS( BasisModule ); // eslint-disable-line no-undef
  275. } ).then( () => {
  276. BasisModule.initializeBasis();
  277. if ( BasisModule.KTX2File === undefined ) {
  278. console.warn( 'THREE.KTX2Loader: Please update Basis Universal transcoder.' );
  279. }
  280. } );
  281. }
  282. function transcode( buffer ) {
  283. const ktx2File = new BasisModule.KTX2File( new Uint8Array( buffer ) );
  284. function cleanup() {
  285. ktx2File.close();
  286. ktx2File.delete();
  287. }
  288. if ( ! ktx2File.isValid() ) {
  289. cleanup();
  290. throw new Error( 'THREE.KTX2Loader: Invalid or unsupported .ktx2 file' );
  291. }
  292. const basisFormat = ktx2File.isUASTC() ? BasisFormat.UASTC_4x4 : BasisFormat.ETC1S;
  293. const width = ktx2File.getWidth();
  294. const height = ktx2File.getHeight();
  295. const levels = ktx2File.getLevels();
  296. const hasAlpha = ktx2File.getHasAlpha();
  297. const dfdTransferFn = ktx2File.getDFDTransferFunc();
  298. const dfdFlags = ktx2File.getDFDFlags();
  299. const { transcoderFormat, engineFormat } = getTranscoderFormat( basisFormat, width, height, hasAlpha );
  300. if ( ! width || ! height || ! levels ) {
  301. cleanup();
  302. throw new Error( 'THREE.KTX2Loader: Invalid texture' );
  303. }
  304. if ( ! ktx2File.startTranscoding() ) {
  305. cleanup();
  306. throw new Error( 'THREE.KTX2Loader: .startTranscoding failed' );
  307. }
  308. const mipmaps = [];
  309. for ( let mip = 0; mip < levels; mip ++ ) {
  310. const levelInfo = ktx2File.getImageLevelInfo( mip, 0, 0 );
  311. const mipWidth = levelInfo.origWidth;
  312. const mipHeight = levelInfo.origHeight;
  313. const dst = new Uint8Array( ktx2File.getImageTranscodedSizeInBytes( mip, 0, 0, transcoderFormat ) );
  314. const status = ktx2File.transcodeImage(
  315. dst,
  316. mip,
  317. 0,
  318. 0,
  319. transcoderFormat,
  320. 0,
  321. - 1,
  322. - 1,
  323. );
  324. if ( ! status ) {
  325. cleanup();
  326. throw new Error( 'THREE.KTX2Loader: .transcodeImage failed.' );
  327. }
  328. mipmaps.push( { data: dst, width: mipWidth, height: mipHeight } );
  329. }
  330. cleanup();
  331. return { width, height, hasAlpha, mipmaps, format: engineFormat, dfdTransferFn, dfdFlags };
  332. }
  333. //
  334. // Optimal choice of a transcoder target format depends on the Basis format (ETC1S or UASTC),
  335. // device capabilities, and texture dimensions. The list below ranks the formats separately
  336. // for ETC1S and UASTC.
  337. //
  338. // In some cases, transcoding UASTC to RGBA32 might be preferred for higher quality (at
  339. // significant memory cost) compared to ETC1/2, BC1/3, and PVRTC. The transcoder currently
  340. // chooses RGBA32 only as a last resort and does not expose that option to the caller.
  341. const FORMAT_OPTIONS = [
  342. {
  343. if: 'astcSupported',
  344. basisFormat: [ BasisFormat.UASTC_4x4 ],
  345. transcoderFormat: [ TranscoderFormat.ASTC_4x4, TranscoderFormat.ASTC_4x4 ],
  346. engineFormat: [ EngineFormat.RGBA_ASTC_4x4_Format, EngineFormat.RGBA_ASTC_4x4_Format ],
  347. priorityETC1S: Infinity,
  348. priorityUASTC: 1,
  349. needsPowerOfTwo: false,
  350. },
  351. {
  352. if: 'bptcSupported',
  353. basisFormat: [ BasisFormat.ETC1S, BasisFormat.UASTC_4x4 ],
  354. transcoderFormat: [ TranscoderFormat.BC7_M5, TranscoderFormat.BC7_M5 ],
  355. engineFormat: [ EngineFormat.RGBA_BPTC_Format, EngineFormat.RGBA_BPTC_Format ],
  356. priorityETC1S: 3,
  357. priorityUASTC: 2,
  358. needsPowerOfTwo: false,
  359. },
  360. {
  361. if: 'dxtSupported',
  362. basisFormat: [ BasisFormat.ETC1S, BasisFormat.UASTC_4x4 ],
  363. transcoderFormat: [ TranscoderFormat.BC1, TranscoderFormat.BC3 ],
  364. engineFormat: [ EngineFormat.RGB_S3TC_DXT1_Format, EngineFormat.RGBA_S3TC_DXT5_Format ],
  365. priorityETC1S: 4,
  366. priorityUASTC: 5,
  367. needsPowerOfTwo: false,
  368. },
  369. {
  370. if: 'etc2Supported',
  371. basisFormat: [ BasisFormat.ETC1S, BasisFormat.UASTC_4x4 ],
  372. transcoderFormat: [ TranscoderFormat.ETC1, TranscoderFormat.ETC2 ],
  373. engineFormat: [ EngineFormat.RGB_ETC2_Format, EngineFormat.RGBA_ETC2_EAC_Format ],
  374. priorityETC1S: 1,
  375. priorityUASTC: 3,
  376. needsPowerOfTwo: false,
  377. },
  378. {
  379. if: 'etc1Supported',
  380. basisFormat: [ BasisFormat.ETC1S, BasisFormat.UASTC_4x4 ],
  381. transcoderFormat: [ TranscoderFormat.ETC1 ],
  382. engineFormat: [ EngineFormat.RGB_ETC1_Format ],
  383. priorityETC1S: 2,
  384. priorityUASTC: 4,
  385. needsPowerOfTwo: false,
  386. },
  387. {
  388. if: 'pvrtcSupported',
  389. basisFormat: [ BasisFormat.ETC1S, BasisFormat.UASTC_4x4 ],
  390. transcoderFormat: [ TranscoderFormat.PVRTC1_4_RGB, TranscoderFormat.PVRTC1_4_RGBA ],
  391. engineFormat: [ EngineFormat.RGB_PVRTC_4BPPV1_Format, EngineFormat.RGBA_PVRTC_4BPPV1_Format ],
  392. priorityETC1S: 5,
  393. priorityUASTC: 6,
  394. needsPowerOfTwo: true,
  395. },
  396. ];
  397. const ETC1S_OPTIONS = FORMAT_OPTIONS.sort( function ( a, b ) {
  398. return a.priorityETC1S - b.priorityETC1S;
  399. } );
  400. const UASTC_OPTIONS = FORMAT_OPTIONS.sort( function ( a, b ) {
  401. return a.priorityUASTC - b.priorityUASTC;
  402. } );
  403. function getTranscoderFormat( basisFormat, width, height, hasAlpha ) {
  404. let transcoderFormat;
  405. let engineFormat;
  406. const options = basisFormat === BasisFormat.ETC1S ? ETC1S_OPTIONS : UASTC_OPTIONS;
  407. for ( let i = 0; i < options.length; i ++ ) {
  408. const opt = options[ i ];
  409. if ( ! config[ opt.if ] ) continue;
  410. if ( ! opt.basisFormat.includes( basisFormat ) ) continue;
  411. if ( hasAlpha && opt.transcoderFormat.length < 2 ) continue;
  412. if ( opt.needsPowerOfTwo && ! ( isPowerOfTwo( width ) && isPowerOfTwo( height ) ) ) continue;
  413. transcoderFormat = opt.transcoderFormat[ hasAlpha ? 1 : 0 ];
  414. engineFormat = opt.engineFormat[ hasAlpha ? 1 : 0 ];
  415. return { transcoderFormat, engineFormat };
  416. }
  417. console.warn( 'THREE.KTX2Loader: No suitable compressed texture format found. Decoding to RGBA32.' );
  418. transcoderFormat = TranscoderFormat.RGBA32;
  419. engineFormat = EngineFormat.RGBAFormat;
  420. return { transcoderFormat, engineFormat };
  421. }
  422. function isPowerOfTwo( value ) {
  423. if ( value <= 2 ) return true;
  424. return ( value & ( value - 1 ) ) === 0 && value !== 0;
  425. }
  426. };
  427. //
  428. // DataTexture and Data3DTexture parsing.
  429. const FORMAT_MAP = {
  430. [VK_FORMAT_R32G32B32A32_SFLOAT]: RGBAFormat,
  431. [VK_FORMAT_R16G16B16A16_SFLOAT]: RGBAFormat,
  432. [VK_FORMAT_R8G8B8A8_UNORM]: RGBAFormat,
  433. [VK_FORMAT_R8G8B8A8_SRGB]: RGBAFormat,
  434. [VK_FORMAT_R32G32_SFLOAT]: RGFormat,
  435. [VK_FORMAT_R16G16_SFLOAT]: RGFormat,
  436. [VK_FORMAT_R8G8_UNORM]: RGFormat,
  437. [VK_FORMAT_R8G8_SRGB]: RGFormat,
  438. [VK_FORMAT_R32_SFLOAT]: RedFormat,
  439. [VK_FORMAT_R16_SFLOAT]: RedFormat,
  440. [VK_FORMAT_R8_SRGB]: RedFormat,
  441. [VK_FORMAT_R8_UNORM]: RedFormat,
  442. };
  443. const TYPE_MAP = {
  444. [VK_FORMAT_R32G32B32A32_SFLOAT]: FloatType,
  445. [VK_FORMAT_R16G16B16A16_SFLOAT]: HalfFloatType,
  446. [VK_FORMAT_R8G8B8A8_UNORM]: UnsignedByteType,
  447. [VK_FORMAT_R8G8B8A8_SRGB]: UnsignedByteType,
  448. [VK_FORMAT_R32G32_SFLOAT]: FloatType,
  449. [VK_FORMAT_R16G16_SFLOAT]: HalfFloatType,
  450. [VK_FORMAT_R8G8_UNORM]: UnsignedByteType,
  451. [VK_FORMAT_R8G8_SRGB]: UnsignedByteType,
  452. [VK_FORMAT_R32_SFLOAT]: FloatType,
  453. [VK_FORMAT_R16_SFLOAT]: HalfFloatType,
  454. [VK_FORMAT_R8_SRGB]: UnsignedByteType,
  455. [VK_FORMAT_R8_UNORM]: UnsignedByteType,
  456. };
  457. const ENCODING_MAP = {
  458. [VK_FORMAT_R8G8B8A8_SRGB]: sRGBEncoding,
  459. [VK_FORMAT_R8G8_SRGB]: sRGBEncoding,
  460. [VK_FORMAT_R8_SRGB]: sRGBEncoding,
  461. };
  462. function createDataTexture( container ) {
  463. const { vkFormat, pixelWidth, pixelHeight, pixelDepth } = container;
  464. if ( FORMAT_MAP[ vkFormat ] === undefined ) {
  465. throw new Error( 'THREE.KTX2Loader: Unsupported vkFormat.' );
  466. }
  467. //
  468. let view;
  469. const levelData = container.levels[ 0 ].levelData;
  470. if ( TYPE_MAP[ vkFormat ] === FloatType ) {
  471. view = new Float32Array(
  472. levelData.buffer,
  473. levelData.byteOffset,
  474. levelData.byteLength / Float32Array.BYTES_PER_ELEMENT
  475. );
  476. } else if ( TYPE_MAP[ vkFormat ] === HalfFloatType ) {
  477. view = new Uint16Array(
  478. levelData.buffer,
  479. levelData.byteOffset,
  480. levelData.byteLength / Uint16Array.BYTES_PER_ELEMENT
  481. );
  482. } else {
  483. view = levelData;
  484. }
  485. //
  486. const texture = pixelDepth === 0
  487. ? new DataTexture( view, pixelWidth, pixelHeight )
  488. : new Data3DTexture( view, pixelWidth, pixelHeight, pixelDepth );
  489. texture.type = TYPE_MAP[ vkFormat ];
  490. texture.format = FORMAT_MAP[ vkFormat ];
  491. texture.encoding = ENCODING_MAP[ vkFormat ] || LinearEncoding;
  492. texture.needsUpdate = true;
  493. //
  494. return Promise.resolve( texture );
  495. }
  496. export { KTX2Loader };