KTX2Loader.js 15 KB

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