BasisTextureLoader.js 19 KB

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