KTX2Loader.js 14 KB

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