BasisTextureLoader.js 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784
  1. import {
  2. CompressedTexture,
  3. FileLoader,
  4. LinearFilter,
  5. LinearMipmapLinearFilter,
  6. Loader,
  7. RGBAFormat,
  8. RGBA_ASTC_4x4_Format,
  9. RGBA_BPTC_Format,
  10. RGBA_ETC2_EAC_Format,
  11. RGBA_PVRTC_4BPPV1_Format,
  12. RGBA_S3TC_DXT5_Format,
  13. RGB_ETC1_Format,
  14. RGB_ETC2_Format,
  15. RGB_PVRTC_4BPPV1_Format,
  16. RGB_S3TC_DXT1_Format,
  17. UnsignedByteType
  18. } from '../../../build/three.module.js';
  19. /**
  20. * Loader for Basis Universal GPU Texture Codec.
  21. *
  22. * Basis Universal is a "supercompressed" GPU texture and texture video
  23. * compression system that outputs a highly compressed intermediate file format
  24. * (.basis) that can be quickly transcoded to a wide variety of GPU texture
  25. * compression formats.
  26. *
  27. * This loader parallelizes the transcoding process across a configurable number
  28. * of web workers, before transferring the transcoded compressed texture back
  29. * to the main thread.
  30. */
  31. var BasisTextureLoader = function ( manager ) {
  32. Loader.call( this, manager );
  33. this.transcoderPath = '';
  34. this.transcoderBinary = null;
  35. this.transcoderPending = null;
  36. this.workerLimit = 4;
  37. this.workerPool = [];
  38. this.workerNextTaskID = 1;
  39. this.workerSourceURL = '';
  40. this.workerConfig = null;
  41. };
  42. BasisTextureLoader.taskCache = new WeakMap();
  43. BasisTextureLoader.prototype = Object.assign( Object.create( Loader.prototype ), {
  44. constructor: BasisTextureLoader,
  45. setTranscoderPath: function ( path ) {
  46. this.transcoderPath = path;
  47. return this;
  48. },
  49. setWorkerLimit: function ( workerLimit ) {
  50. this.workerLimit = workerLimit;
  51. return this;
  52. },
  53. detectSupport: function ( renderer ) {
  54. this.workerConfig = {
  55. astcSupported: renderer.extensions.has( 'WEBGL_compressed_texture_astc' ),
  56. etc1Supported: renderer.extensions.has( 'WEBGL_compressed_texture_etc1' ),
  57. etc2Supported: renderer.extensions.has( 'WEBGL_compressed_texture_etc' ),
  58. dxtSupported: renderer.extensions.has( 'WEBGL_compressed_texture_s3tc' ),
  59. bptcSupported: renderer.extensions.has( 'EXT_texture_compression_bptc' ),
  60. pvrtcSupported: renderer.extensions.has( 'WEBGL_compressed_texture_pvrtc' )
  61. || renderer.extensions.has( 'WEBKIT_WEBGL_compressed_texture_pvrtc' )
  62. };
  63. return this;
  64. },
  65. load: function ( url, onLoad, onProgress, onError ) {
  66. var loader = new FileLoader( this.manager );
  67. loader.setResponseType( 'arraybuffer' );
  68. loader.setWithCredentials( this.withCredentials );
  69. var texture = new CompressedTexture();
  70. loader.load( url, ( buffer ) => {
  71. // Check for an existing task using this buffer. A transferred buffer cannot be transferred
  72. // again from this thread.
  73. if ( BasisTextureLoader.taskCache.has( buffer ) ) {
  74. var cachedTask = BasisTextureLoader.taskCache.get( buffer );
  75. return cachedTask.promise.then( onLoad ).catch( onError );
  76. }
  77. this._createTexture( [ buffer ] )
  78. .then( function ( _texture ) {
  79. texture.copy( _texture );
  80. texture.needsUpdate = true;
  81. if ( onLoad ) onLoad( texture );
  82. } )
  83. .catch( onError );
  84. }, onProgress, onError );
  85. return texture;
  86. },
  87. /** Low-level transcoding API, exposed for use by KTX2Loader. */
  88. parseInternalAsync: function ( options ) {
  89. var { levels } = options;
  90. var buffers = new Set();
  91. for ( var i = 0; i < levels.length; i ++ ) {
  92. buffers.add( levels[ i ].data.buffer );
  93. }
  94. return this._createTexture( Array.from( buffers ), { ...options, lowLevel: true } );
  95. },
  96. /**
  97. * @param {ArrayBuffer[]} buffers
  98. * @param {object?} config
  99. * @return {Promise<CompressedTexture>}
  100. */
  101. _createTexture: function ( buffers, config ) {
  102. var worker;
  103. var taskID;
  104. var taskConfig = config || {};
  105. var taskCost = 0;
  106. for ( var i = 0; i < buffers.length; i ++ ) {
  107. taskCost += buffers[ i ].byteLength;
  108. }
  109. var texturePending = this._allocateWorker( taskCost )
  110. .then( ( _worker ) => {
  111. worker = _worker;
  112. taskID = this.workerNextTaskID ++;
  113. return new Promise( ( resolve, reject ) => {
  114. worker._callbacks[ taskID ] = { resolve, reject };
  115. worker.postMessage( { type: 'transcode', id: taskID, buffers: buffers, taskConfig: taskConfig }, buffers );
  116. } );
  117. } )
  118. .then( ( message ) => {
  119. var { mipmaps, width, height, format } = message;
  120. var texture = new CompressedTexture( mipmaps, width, height, format, UnsignedByteType );
  121. texture.minFilter = mipmaps.length === 1 ? LinearFilter : LinearMipmapLinearFilter;
  122. texture.magFilter = LinearFilter;
  123. texture.generateMipmaps = false;
  124. texture.needsUpdate = true;
  125. return texture;
  126. } );
  127. // Note: replaced '.finally()' with '.catch().then()' block - iOS 11 support (#19416)
  128. texturePending
  129. .catch( () => true )
  130. .then( () => {
  131. if ( worker && taskID ) {
  132. worker._taskLoad -= taskCost;
  133. delete worker._callbacks[ taskID ];
  134. }
  135. } );
  136. // Cache the task result.
  137. BasisTextureLoader.taskCache.set( buffers[ 0 ], { promise: texturePending } );
  138. return texturePending;
  139. },
  140. _initTranscoder: function () {
  141. if ( ! this.transcoderPending ) {
  142. // Load transcoder wrapper.
  143. var jsLoader = new FileLoader( this.manager );
  144. jsLoader.setPath( this.transcoderPath );
  145. jsLoader.setWithCredentials( this.withCredentials );
  146. var jsContent = new Promise( ( resolve, reject ) => {
  147. jsLoader.load( 'basis_transcoder.js', resolve, undefined, reject );
  148. } );
  149. // Load transcoder WASM binary.
  150. var binaryLoader = new FileLoader( this.manager );
  151. binaryLoader.setPath( this.transcoderPath );
  152. binaryLoader.setResponseType( 'arraybuffer' );
  153. binaryLoader.setWithCredentials( this.withCredentials );
  154. var binaryContent = new Promise( ( resolve, reject ) => {
  155. binaryLoader.load( 'basis_transcoder.wasm', resolve, undefined, reject );
  156. } );
  157. this.transcoderPending = Promise.all( [ jsContent, binaryContent ] )
  158. .then( ( [ jsContent, binaryContent ] ) => {
  159. var fn = BasisTextureLoader.BasisWorker.toString();
  160. var body = [
  161. '/* constants */',
  162. 'var _EngineFormat = ' + JSON.stringify( BasisTextureLoader.EngineFormat ),
  163. 'var _TranscoderFormat = ' + JSON.stringify( BasisTextureLoader.TranscoderFormat ),
  164. 'var _BasisFormat = ' + JSON.stringify( BasisTextureLoader.BasisFormat ),
  165. '/* basis_transcoder.js */',
  166. jsContent,
  167. '/* worker */',
  168. fn.substring( fn.indexOf( '{' ) + 1, fn.lastIndexOf( '}' ) )
  169. ].join( '\n' );
  170. this.workerSourceURL = URL.createObjectURL( new Blob( [ body ] ) );
  171. this.transcoderBinary = binaryContent;
  172. } );
  173. }
  174. return this.transcoderPending;
  175. },
  176. _allocateWorker: function ( taskCost ) {
  177. return this._initTranscoder().then( () => {
  178. if ( this.workerPool.length < this.workerLimit ) {
  179. var worker = new Worker( this.workerSourceURL );
  180. worker._callbacks = {};
  181. worker._taskLoad = 0;
  182. worker.postMessage( {
  183. type: 'init',
  184. config: this.workerConfig,
  185. transcoderBinary: this.transcoderBinary,
  186. } );
  187. worker.onmessage = function ( e ) {
  188. var message = e.data;
  189. switch ( message.type ) {
  190. case 'transcode':
  191. worker._callbacks[ message.id ].resolve( message );
  192. break;
  193. case 'error':
  194. worker._callbacks[ message.id ].reject( message );
  195. break;
  196. default:
  197. console.error( 'THREE.BasisTextureLoader: Unexpected message, "' + message.type + '"' );
  198. }
  199. };
  200. this.workerPool.push( worker );
  201. } else {
  202. this.workerPool.sort( function ( a, b ) {
  203. return a._taskLoad > b._taskLoad ? - 1 : 1;
  204. } );
  205. }
  206. var worker = this.workerPool[ this.workerPool.length - 1 ];
  207. worker._taskLoad += taskCost;
  208. return worker;
  209. } );
  210. },
  211. dispose: function () {
  212. for ( var i = 0; i < this.workerPool.length; i ++ ) {
  213. this.workerPool[ i ].terminate();
  214. }
  215. this.workerPool.length = 0;
  216. return this;
  217. }
  218. } );
  219. /* CONSTANTS */
  220. BasisTextureLoader.BasisFormat = {
  221. ETC1S: 0,
  222. UASTC_4x4: 1,
  223. };
  224. BasisTextureLoader.TranscoderFormat = {
  225. ETC1: 0,
  226. ETC2: 1,
  227. BC1: 2,
  228. BC3: 3,
  229. BC4: 4,
  230. BC5: 5,
  231. BC7_M6_OPAQUE_ONLY: 6,
  232. BC7_M5: 7,
  233. PVRTC1_4_RGB: 8,
  234. PVRTC1_4_RGBA: 9,
  235. ASTC_4x4: 10,
  236. ATC_RGB: 11,
  237. ATC_RGBA_INTERPOLATED_ALPHA: 12,
  238. RGBA32: 13,
  239. RGB565: 14,
  240. BGR565: 15,
  241. RGBA4444: 16,
  242. };
  243. BasisTextureLoader.EngineFormat = {
  244. RGBAFormat: RGBAFormat,
  245. RGBA_ASTC_4x4_Format: RGBA_ASTC_4x4_Format,
  246. RGBA_BPTC_Format: RGBA_BPTC_Format,
  247. RGBA_ETC2_EAC_Format: RGBA_ETC2_EAC_Format,
  248. RGBA_PVRTC_4BPPV1_Format: RGBA_PVRTC_4BPPV1_Format,
  249. RGBA_S3TC_DXT5_Format: RGBA_S3TC_DXT5_Format,
  250. RGB_ETC1_Format: RGB_ETC1_Format,
  251. RGB_ETC2_Format: RGB_ETC2_Format,
  252. RGB_PVRTC_4BPPV1_Format: RGB_PVRTC_4BPPV1_Format,
  253. RGB_S3TC_DXT1_Format: RGB_S3TC_DXT1_Format,
  254. };
  255. /* WEB WORKER */
  256. BasisTextureLoader.BasisWorker = function () {
  257. var config;
  258. var transcoderPending;
  259. var BasisModule;
  260. var EngineFormat = _EngineFormat; // eslint-disable-line no-undef
  261. var TranscoderFormat = _TranscoderFormat; // eslint-disable-line no-undef
  262. var BasisFormat = _BasisFormat; // eslint-disable-line no-undef
  263. onmessage = function ( e ) {
  264. var message = e.data;
  265. switch ( message.type ) {
  266. case 'init':
  267. config = message.config;
  268. init( message.transcoderBinary );
  269. break;
  270. case 'transcode':
  271. transcoderPending.then( () => {
  272. try {
  273. var { width, height, hasAlpha, mipmaps, format } = message.taskConfig.lowLevel
  274. ? transcodeLowLevel( message.taskConfig )
  275. : transcode( message.buffers[ 0 ] );
  276. var buffers = [];
  277. for ( var i = 0; i < mipmaps.length; ++ i ) {
  278. buffers.push( mipmaps[ i ].data.buffer );
  279. }
  280. self.postMessage( { type: 'transcode', id: message.id, width, height, hasAlpha, mipmaps, format }, buffers );
  281. } catch ( error ) {
  282. console.error( error );
  283. self.postMessage( { type: 'error', id: message.id, error: error.message } );
  284. }
  285. } );
  286. break;
  287. }
  288. };
  289. function init( wasmBinary ) {
  290. transcoderPending = new Promise( ( resolve ) => {
  291. BasisModule = { wasmBinary, onRuntimeInitialized: resolve };
  292. BASIS( BasisModule ); // eslint-disable-line no-undef
  293. } ).then( () => {
  294. BasisModule.initializeBasis();
  295. } );
  296. }
  297. function transcodeLowLevel( taskConfig ) {
  298. var { basisFormat, width, height, hasAlpha } = taskConfig;
  299. var { transcoderFormat, engineFormat } = getTranscoderFormat( basisFormat, width, height, hasAlpha );
  300. var blockByteLength = BasisModule.getBytesPerBlockOrPixel( transcoderFormat );
  301. assert( BasisModule.isFormatSupported( transcoderFormat ), 'THREE.BasisTextureLoader: Unsupported format.' );
  302. var mipmaps = [];
  303. if ( basisFormat === BasisFormat.ETC1S ) {
  304. var transcoder = new BasisModule.LowLevelETC1SImageTranscoder();
  305. var { endpointCount, endpointsData, selectorCount, selectorsData, tablesData } = taskConfig.globalData;
  306. try {
  307. var ok;
  308. ok = transcoder.decodePalettes( endpointCount, endpointsData, selectorCount, selectorsData );
  309. assert( ok, 'THREE.BasisTextureLoader: decodePalettes() failed.' );
  310. ok = transcoder.decodeTables( tablesData );
  311. assert( ok, 'THREE.BasisTextureLoader: decodeTables() failed.' );
  312. for ( var i = 0; i < taskConfig.levels.length; i ++ ) {
  313. var level = taskConfig.levels[ i ];
  314. var imageDesc = taskConfig.globalData.imageDescs[ i ];
  315. var dstByteLength = getTranscodedImageByteLength( transcoderFormat, level.width, level.height );
  316. var dst = new Uint8Array( dstByteLength );
  317. ok = transcoder.transcodeImage(
  318. transcoderFormat,
  319. dst, dstByteLength / blockByteLength,
  320. level.data,
  321. getWidthInBlocks( transcoderFormat, level.width ),
  322. getHeightInBlocks( transcoderFormat, level.height ),
  323. level.width, level.height, level.index,
  324. imageDesc.rgbSliceByteOffset, imageDesc.rgbSliceByteLength,
  325. imageDesc.alphaSliceByteOffset, imageDesc.alphaSliceByteLength,
  326. imageDesc.imageFlags,
  327. hasAlpha,
  328. false,
  329. 0, 0
  330. );
  331. assert( ok, 'THREE.BasisTextureLoader: transcodeImage() failed for level ' + level.index + '.' );
  332. mipmaps.push( { data: dst, width: level.width, height: level.height } );
  333. }
  334. } finally {
  335. transcoder.delete();
  336. }
  337. } else {
  338. for ( var i = 0; i < taskConfig.levels.length; i ++ ) {
  339. var level = taskConfig.levels[ i ];
  340. var dstByteLength = getTranscodedImageByteLength( transcoderFormat, level.width, level.height );
  341. var dst = new Uint8Array( dstByteLength );
  342. var ok = BasisModule.transcodeUASTCImage(
  343. transcoderFormat,
  344. dst, dstByteLength / blockByteLength,
  345. level.data,
  346. getWidthInBlocks( transcoderFormat, level.width ),
  347. getHeightInBlocks( transcoderFormat, level.height ),
  348. level.width, level.height, level.index,
  349. 0,
  350. level.data.byteLength,
  351. 0,
  352. hasAlpha,
  353. false,
  354. 0, 0,
  355. - 1, - 1
  356. );
  357. assert( ok, 'THREE.BasisTextureLoader: transcodeUASTCImage() failed for level ' + level.index + '.' );
  358. mipmaps.push( { data: dst, width: level.width, height: level.height } );
  359. }
  360. }
  361. return { width, height, hasAlpha, mipmaps, format: engineFormat };
  362. }
  363. function transcode( buffer ) {
  364. var basisFile = new BasisModule.BasisFile( new Uint8Array( buffer ) );
  365. var basisFormat = basisFile.isUASTC() ? BasisFormat.UASTC_4x4 : BasisFormat.ETC1S;
  366. var width = basisFile.getImageWidth( 0, 0 );
  367. var height = basisFile.getImageHeight( 0, 0 );
  368. var levels = basisFile.getNumLevels( 0 );
  369. var hasAlpha = basisFile.getHasAlpha();
  370. function cleanup() {
  371. basisFile.close();
  372. basisFile.delete();
  373. }
  374. var { transcoderFormat, engineFormat } = getTranscoderFormat( basisFormat, width, height, hasAlpha );
  375. if ( ! width || ! height || ! levels ) {
  376. cleanup();
  377. throw new Error( 'THREE.BasisTextureLoader: Invalid texture' );
  378. }
  379. if ( ! basisFile.startTranscoding() ) {
  380. cleanup();
  381. throw new Error( 'THREE.BasisTextureLoader: .startTranscoding failed' );
  382. }
  383. var mipmaps = [];
  384. for ( var mip = 0; mip < levels; mip ++ ) {
  385. var mipWidth = basisFile.getImageWidth( 0, mip );
  386. var mipHeight = basisFile.getImageHeight( 0, mip );
  387. var dst = new Uint8Array( basisFile.getImageTranscodedSizeInBytes( 0, mip, transcoderFormat ) );
  388. var status = basisFile.transcodeImage(
  389. dst,
  390. 0,
  391. mip,
  392. transcoderFormat,
  393. 0,
  394. hasAlpha
  395. );
  396. if ( ! status ) {
  397. cleanup();
  398. throw new Error( 'THREE.BasisTextureLoader: .transcodeImage failed.' );
  399. }
  400. mipmaps.push( { data: dst, width: mipWidth, height: mipHeight } );
  401. }
  402. cleanup();
  403. return { width, height, hasAlpha, mipmaps, format: engineFormat };
  404. }
  405. //
  406. // Optimal choice of a transcoder target format depends on the Basis format (ETC1S or UASTC),
  407. // device capabilities, and texture dimensions. The list below ranks the formats separately
  408. // for ETC1S and UASTC.
  409. //
  410. // In some cases, transcoding UASTC to RGBA32 might be preferred for higher quality (at
  411. // significant memory cost) compared to ETC1/2, BC1/3, and PVRTC. The transcoder currently
  412. // chooses RGBA32 only as a last resort and does not expose that option to the caller.
  413. var FORMAT_OPTIONS = [
  414. {
  415. if: 'astcSupported',
  416. basisFormat: [ BasisFormat.UASTC_4x4 ],
  417. transcoderFormat: [ TranscoderFormat.ASTC_4x4, TranscoderFormat.ASTC_4x4 ],
  418. engineFormat: [ EngineFormat.RGBA_ASTC_4x4_Format, EngineFormat.RGBA_ASTC_4x4_Format ],
  419. priorityETC1S: Infinity,
  420. priorityUASTC: 1,
  421. needsPowerOfTwo: false,
  422. },
  423. {
  424. if: 'bptcSupported',
  425. basisFormat: [ BasisFormat.ETC1S, BasisFormat.UASTC_4x4 ],
  426. transcoderFormat: [ TranscoderFormat.BC7_M5, TranscoderFormat.BC7_M5 ],
  427. engineFormat: [ EngineFormat.RGBA_BPTC_Format, EngineFormat.RGBA_BPTC_Format ],
  428. priorityETC1S: 3,
  429. priorityUASTC: 2,
  430. needsPowerOfTwo: false,
  431. },
  432. {
  433. if: 'dxtSupported',
  434. basisFormat: [ BasisFormat.ETC1S, BasisFormat.UASTC_4x4 ],
  435. transcoderFormat: [ TranscoderFormat.BC1, TranscoderFormat.BC3 ],
  436. engineFormat: [ EngineFormat.RGB_S3TC_DXT1_Format, EngineFormat.RGBA_S3TC_DXT5_Format ],
  437. priorityETC1S: 4,
  438. priorityUASTC: 5,
  439. needsPowerOfTwo: false,
  440. },
  441. {
  442. if: 'etc2Supported',
  443. basisFormat: [ BasisFormat.ETC1S, BasisFormat.UASTC_4x4 ],
  444. transcoderFormat: [ TranscoderFormat.ETC1, TranscoderFormat.ETC2 ],
  445. engineFormat: [ EngineFormat.RGB_ETC2_Format, EngineFormat.RGBA_ETC2_EAC_Format ],
  446. priorityETC1S: 1,
  447. priorityUASTC: 3,
  448. needsPowerOfTwo: false,
  449. },
  450. {
  451. if: 'etc1Supported',
  452. basisFormat: [ BasisFormat.ETC1S, BasisFormat.UASTC_4x4 ],
  453. transcoderFormat: [ TranscoderFormat.ETC1, TranscoderFormat.ETC1 ],
  454. engineFormat: [ EngineFormat.RGB_ETC1_Format, EngineFormat.RGB_ETC1_Format ],
  455. priorityETC1S: 2,
  456. priorityUASTC: 4,
  457. needsPowerOfTwo: false,
  458. },
  459. {
  460. if: 'pvrtcSupported',
  461. basisFormat: [ BasisFormat.ETC1S, BasisFormat.UASTC_4x4 ],
  462. transcoderFormat: [ TranscoderFormat.PVRTC1_4_RGB, TranscoderFormat.PVRTC1_4_RGBA ],
  463. engineFormat: [ EngineFormat.RGB_PVRTC_4BPPV1_Format, EngineFormat.RGBA_PVRTC_4BPPV1_Format ],
  464. priorityETC1S: 5,
  465. priorityUASTC: 6,
  466. needsPowerOfTwo: true,
  467. },
  468. ];
  469. var ETC1S_OPTIONS = FORMAT_OPTIONS.sort( function ( a, b ) {
  470. return a.priorityETC1S - b.priorityETC1S;
  471. } );
  472. var UASTC_OPTIONS = FORMAT_OPTIONS.sort( function ( a, b ) {
  473. return a.priorityUASTC - b.priorityUASTC;
  474. } );
  475. function getTranscoderFormat( basisFormat, width, height, hasAlpha ) {
  476. var transcoderFormat;
  477. var engineFormat;
  478. var options = basisFormat === BasisFormat.ETC1S ? ETC1S_OPTIONS : UASTC_OPTIONS;
  479. for ( var i = 0; i < options.length; i ++ ) {
  480. var opt = options[ i ];
  481. if ( ! config[ opt.if ] ) continue;
  482. if ( ! opt.basisFormat.includes( basisFormat ) ) continue;
  483. if ( opt.needsPowerOfTwo && ! ( isPowerOfTwo( width ) && isPowerOfTwo( height ) ) ) continue;
  484. transcoderFormat = opt.transcoderFormat[ hasAlpha ? 1 : 0 ];
  485. engineFormat = opt.engineFormat[ hasAlpha ? 1 : 0 ];
  486. return { transcoderFormat, engineFormat };
  487. }
  488. console.warn( 'THREE.BasisTextureLoader: No suitable compressed texture format found. Decoding to RGBA32.' );
  489. transcoderFormat = TranscoderFormat.RGBA32;
  490. engineFormat = EngineFormat.RGBAFormat;
  491. return { transcoderFormat, engineFormat };
  492. }
  493. function assert( ok, message ) {
  494. if ( ! ok ) throw new Error( message );
  495. }
  496. function getWidthInBlocks( transcoderFormat, width ) {
  497. return Math.ceil( width / BasisModule.getFormatBlockWidth( transcoderFormat ) );
  498. }
  499. function getHeightInBlocks( transcoderFormat, height ) {
  500. return Math.ceil( height / BasisModule.getFormatBlockHeight( transcoderFormat ) );
  501. }
  502. function getTranscodedImageByteLength( transcoderFormat, width, height ) {
  503. var blockByteLength = BasisModule.getBytesPerBlockOrPixel( transcoderFormat );
  504. if ( BasisModule.formatIsUncompressed( transcoderFormat ) ) {
  505. return width * height * blockByteLength;
  506. }
  507. if ( transcoderFormat === TranscoderFormat.PVRTC1_4_RGB
  508. || transcoderFormat === TranscoderFormat.PVRTC1_4_RGBA ) {
  509. // GL requires extra padding for very small textures:
  510. // https://www.khronos.org/registry/OpenGL/extensions/IMG/IMG_texture_compression_pvrtc.txt
  511. var paddedWidth = ( width + 3 ) & ~ 3;
  512. var paddedHeight = ( height + 3 ) & ~ 3;
  513. return ( Math.max( 8, paddedWidth ) * Math.max( 8, paddedHeight ) * 4 + 7 ) / 8;
  514. }
  515. return ( getWidthInBlocks( transcoderFormat, width )
  516. * getHeightInBlocks( transcoderFormat, height )
  517. * blockByteLength );
  518. }
  519. function isPowerOfTwo( value ) {
  520. if ( value <= 2 ) return true;
  521. return ( value & ( value - 1 ) ) === 0 && value !== 0;
  522. }
  523. };
  524. export { BasisTextureLoader };