KTX2Loader.js 14 KB

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