BasisTextureLoader.js 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557
  1. console.warn( "THREE.BasisTextureLoader: As part of the transition to ES6 Modules, the files in 'examples/js' were deprecated in May 2020 (r117) and will be deleted in December 2020 (r124). You can find more information about developing using ES6 Modules in https://threejs.org/docs/index.html#manual/en/introduction/Import-via-modules." );
  2. /**
  3. * @author Don McCurdy / https://www.donmccurdy.com
  4. * @author Austin Eng / https://github.com/austinEng
  5. * @author Shrek Shao / https://github.com/shrekshao
  6. * @author Senya Pugach / https://upisfr.ee
  7. */
  8. /**
  9. * Loader for Basis Universal GPU Texture Codec.
  10. *
  11. * Basis Universal is a "supercompressed" GPU texture and texture video
  12. * compression system that outputs a highly compressed intermediate file format
  13. * (.basis) that can be quickly transcoded to a wide variety of GPU texture
  14. * compression formats.
  15. *
  16. * This loader parallelizes the transcoding process across a configurable number
  17. * of web workers, before transferring the transcoded compressed texture back
  18. * to the main thread.
  19. */
  20. THREE.BasisTextureLoader = function ( manager ) {
  21. THREE.Loader.call( this, manager );
  22. this.transcoderPath = '';
  23. this.transcoderBinary = null;
  24. this.transcoderPending = null;
  25. this.workerLimit = 4;
  26. this.workerPool = [];
  27. this.workerNextTaskID = 1;
  28. this.workerSourceURL = '';
  29. this.workerConfig = {
  30. format: null,
  31. astcSupported: false,
  32. bptcSupported: false,
  33. etcSupported: false,
  34. dxtSupported: false,
  35. pvrtcSupported: false,
  36. };
  37. };
  38. THREE.BasisTextureLoader.taskCache = new WeakMap();
  39. THREE.BasisTextureLoader.prototype = Object.assign( Object.create( THREE.Loader.prototype ), {
  40. constructor: THREE.BasisTextureLoader,
  41. setTranscoderPath: function ( path ) {
  42. this.transcoderPath = path;
  43. return this;
  44. },
  45. setWorkerLimit: function ( workerLimit ) {
  46. this.workerLimit = workerLimit;
  47. return this;
  48. },
  49. detectSupport: function ( renderer ) {
  50. var config = this.workerConfig;
  51. config.astcSupported = !! renderer.extensions.get( 'WEBGL_compressed_texture_astc' );
  52. config.bptcSupported = !! renderer.extensions.get( 'EXT_texture_compression_bptc' );
  53. config.etcSupported = !! renderer.extensions.get( 'WEBGL_compressed_texture_etc1' );
  54. config.dxtSupported = !! renderer.extensions.get( 'WEBGL_compressed_texture_s3tc' );
  55. config.pvrtcSupported = !! renderer.extensions.get( 'WEBGL_compressed_texture_pvrtc' )
  56. || !! renderer.extensions.get( 'WEBKIT_WEBGL_compressed_texture_pvrtc' );
  57. if ( config.astcSupported ) {
  58. config.format = THREE.BasisTextureLoader.BASIS_FORMAT.cTFASTC_4x4;
  59. } else if ( config.bptcSupported ) {
  60. config.format = THREE.BasisTextureLoader.BASIS_FORMAT.cTFBC7_M5;
  61. } else if ( config.dxtSupported ) {
  62. config.format = THREE.BasisTextureLoader.BASIS_FORMAT.cTFBC3;
  63. } else if ( config.pvrtcSupported ) {
  64. config.format = THREE.BasisTextureLoader.BASIS_FORMAT.cTFPVRTC1_4_RGBA;
  65. } else if ( config.etcSupported ) {
  66. config.format = THREE.BasisTextureLoader.BASIS_FORMAT.cTFETC1;
  67. } else {
  68. throw new Error( 'THREE.BasisTextureLoader: No suitable compressed texture format found.' );
  69. }
  70. return this;
  71. },
  72. load: function ( url, onLoad, onProgress, onError ) {
  73. var loader = new THREE.FileLoader( this.manager );
  74. loader.setResponseType( 'arraybuffer' );
  75. loader.load( url, ( buffer ) => {
  76. var taskKey = JSON.stringify( url );
  77. // Check for an existing task using this buffer. A transferred buffer cannot be transferred
  78. // again from this thread.
  79. if ( THREE.BasisTextureLoader.taskCache.has( buffer ) ) {
  80. var cachedTask = THREE.BasisTextureLoader.taskCache.get( buffer );
  81. if ( cachedTask.key === taskKey ) {
  82. return cachedTask.promise.then( onLoad ).catch( onError );
  83. } else if ( buffer.byteLength === 0 ) {
  84. // Technically, it would be possible to wait for the previous task to complete,
  85. // transfer the buffer back, and decode again with the second configuration. That
  86. // is complex, and I don't know of any reason to decode a Basis buffer twice in
  87. // different ways, so this is left unimplemented.
  88. throw new Error(
  89. 'THREE.BasisTextureLoader: Unable to re-decode a buffer with different ' +
  90. 'settings. Buffer has already been transferred.'
  91. );
  92. }
  93. }
  94. this._createTexture( buffer, url )
  95. .then( onLoad )
  96. .catch( onError );
  97. }, onProgress, onError );
  98. },
  99. /**
  100. * @param {ArrayBuffer} buffer
  101. * @param {string} url
  102. * @return {Promise<THREE.CompressedTexture>}
  103. */
  104. _createTexture: function ( buffer, url ) {
  105. var worker;
  106. var taskID;
  107. var taskCost = buffer.byteLength;
  108. var texturePending = this._allocateWorker( taskCost )
  109. .then( ( _worker ) => {
  110. worker = _worker;
  111. taskID = this.workerNextTaskID ++;
  112. return new Promise( ( resolve, reject ) => {
  113. worker._callbacks[ taskID ] = { resolve, reject };
  114. worker.postMessage( { type: 'transcode', id: taskID, buffer }, [ buffer ] );
  115. } );
  116. } )
  117. .then( ( message ) => {
  118. var config = this.workerConfig;
  119. var { width, height, mipmaps, format } = message;
  120. var texture;
  121. switch ( format ) {
  122. case THREE.BasisTextureLoader.BASIS_FORMAT.cTFASTC_4x4:
  123. texture = new THREE.CompressedTexture( mipmaps, width, height, THREE.RGBA_ASTC_4x4_Format );
  124. break;
  125. case THREE.BasisTextureLoader.BASIS_FORMAT.cTFBC7_M5:
  126. texture = new THREE.CompressedTexture( mipmaps, width, height, THREE.RGBA_BPTC_Format );
  127. break;
  128. case THREE.BasisTextureLoader.BASIS_FORMAT.cTFBC1:
  129. case THREE.BasisTextureLoader.BASIS_FORMAT.cTFBC3:
  130. texture = new THREE.CompressedTexture( mipmaps, width, height, THREE.BasisTextureLoader.DXT_FORMAT_MAP[ config.format ], THREE.UnsignedByteType );
  131. break;
  132. case THREE.BasisTextureLoader.BASIS_FORMAT.cTFETC1:
  133. texture = new THREE.CompressedTexture( mipmaps, width, height, THREE.RGB_ETC1_Format );
  134. break;
  135. case THREE.BasisTextureLoader.BASIS_FORMAT.cTFPVRTC1_4_RGB:
  136. texture = new THREE.CompressedTexture( mipmaps, width, height, THREE.RGB_PVRTC_4BPPV1_Format );
  137. break;
  138. case THREE.BasisTextureLoader.BASIS_FORMAT.cTFPVRTC1_4_RGBA:
  139. texture = new THREE.CompressedTexture( mipmaps, width, height, THREE.RGBA_PVRTC_4BPPV1_Format );
  140. break;
  141. default:
  142. throw new Error( 'THREE.BasisTextureLoader: No supported format available.' );
  143. }
  144. texture.minFilter = mipmaps.length === 1 ? THREE.LinearFilter : THREE.LinearMipmapLinearFilter;
  145. texture.magFilter = THREE.LinearFilter;
  146. texture.generateMipmaps = false;
  147. texture.needsUpdate = true;
  148. return texture;
  149. } );
  150. // Note: replaced '.finally()' with '.catch().then()' block - iOS 11 support (#19416)
  151. texturePending
  152. .catch( () => true )
  153. .then( () => {
  154. if ( worker && taskID ) {
  155. worker._taskLoad -= taskCost;
  156. delete worker._callbacks[ taskID ];
  157. }
  158. } );
  159. var taskKey = JSON.stringify( url );
  160. // Cache the task result.
  161. THREE.BasisTextureLoader.taskCache.set( buffer, {
  162. key: taskKey,
  163. promise: texturePending
  164. } );
  165. return texturePending;
  166. },
  167. _initTranscoder: function () {
  168. if ( ! this.transcoderPending ) {
  169. // Load transcoder wrapper.
  170. var jsLoader = new THREE.FileLoader( this.manager );
  171. jsLoader.setPath( this.transcoderPath );
  172. var jsContent = new Promise( ( resolve, reject ) => {
  173. jsLoader.load( 'basis_transcoder.js', resolve, undefined, reject );
  174. } );
  175. // Load transcoder WASM binary.
  176. var binaryLoader = new THREE.FileLoader( this.manager );
  177. binaryLoader.setPath( this.transcoderPath );
  178. binaryLoader.setResponseType( 'arraybuffer' );
  179. var binaryContent = new Promise( ( resolve, reject ) => {
  180. binaryLoader.load( 'basis_transcoder.wasm', resolve, undefined, reject );
  181. } );
  182. this.transcoderPending = Promise.all( [ jsContent, binaryContent ] )
  183. .then( ( [ jsContent, binaryContent ] ) => {
  184. var fn = THREE.BasisTextureLoader.BasisWorker.toString();
  185. var body = [
  186. '/* basis_transcoder.js */',
  187. jsContent,
  188. '/* worker */',
  189. fn.substring( fn.indexOf( '{' ) + 1, fn.lastIndexOf( '}' ) )
  190. ].join( '\n' );
  191. this.workerSourceURL = URL.createObjectURL( new Blob( [ body ] ) );
  192. this.transcoderBinary = binaryContent;
  193. } );
  194. }
  195. return this.transcoderPending;
  196. },
  197. _allocateWorker: function ( taskCost ) {
  198. return this._initTranscoder().then( () => {
  199. if ( this.workerPool.length < this.workerLimit ) {
  200. var worker = new Worker( this.workerSourceURL );
  201. worker._callbacks = {};
  202. worker._taskLoad = 0;
  203. worker.postMessage( {
  204. type: 'init',
  205. config: this.workerConfig,
  206. transcoderBinary: this.transcoderBinary,
  207. } );
  208. worker.onmessage = function ( e ) {
  209. var message = e.data;
  210. switch ( message.type ) {
  211. case 'transcode':
  212. worker._callbacks[ message.id ].resolve( message );
  213. break;
  214. case 'error':
  215. worker._callbacks[ message.id ].reject( message );
  216. break;
  217. default:
  218. console.error( 'THREE.BasisTextureLoader: Unexpected message, "' + message.type + '"' );
  219. }
  220. };
  221. this.workerPool.push( worker );
  222. } else {
  223. this.workerPool.sort( function ( a, b ) {
  224. return a._taskLoad > b._taskLoad ? - 1 : 1;
  225. } );
  226. }
  227. var worker = this.workerPool[ this.workerPool.length - 1 ];
  228. worker._taskLoad += taskCost;
  229. return worker;
  230. } );
  231. },
  232. dispose: function () {
  233. for ( var i = 0; i < this.workerPool.length; i ++ ) {
  234. this.workerPool[ i ].terminate();
  235. }
  236. this.workerPool.length = 0;
  237. return this;
  238. }
  239. } );
  240. /* CONSTANTS */
  241. THREE.BasisTextureLoader.BASIS_FORMAT = {
  242. cTFETC1: 0,
  243. cTFETC2: 1,
  244. cTFBC1: 2,
  245. cTFBC3: 3,
  246. cTFBC4: 4,
  247. cTFBC5: 5,
  248. cTFBC7_M6_OPAQUE_ONLY: 6,
  249. cTFBC7_M5: 7,
  250. cTFPVRTC1_4_RGB: 8,
  251. cTFPVRTC1_4_RGBA: 9,
  252. cTFASTC_4x4: 10,
  253. cTFATC_RGB: 11,
  254. cTFATC_RGBA_INTERPOLATED_ALPHA: 12,
  255. cTFRGBA32: 13,
  256. cTFRGB565: 14,
  257. cTFBGR565: 15,
  258. cTFRGBA4444: 16,
  259. };
  260. // DXT formats, from:
  261. // http://www.khronos.org/registry/webgl/extensions/WEBGL_compressed_texture_s3tc/
  262. THREE.BasisTextureLoader.DXT_FORMAT = {
  263. COMPRESSED_RGB_S3TC_DXT1_EXT: 0x83F0,
  264. COMPRESSED_RGBA_S3TC_DXT1_EXT: 0x83F1,
  265. COMPRESSED_RGBA_S3TC_DXT3_EXT: 0x83F2,
  266. COMPRESSED_RGBA_S3TC_DXT5_EXT: 0x83F3,
  267. };
  268. THREE.BasisTextureLoader.DXT_FORMAT_MAP = {};
  269. THREE.BasisTextureLoader.DXT_FORMAT_MAP[ THREE.BasisTextureLoader.BASIS_FORMAT.cTFBC1 ] =
  270. THREE.BasisTextureLoader.DXT_FORMAT.COMPRESSED_RGB_S3TC_DXT1_EXT;
  271. THREE.BasisTextureLoader.DXT_FORMAT_MAP[ THREE.BasisTextureLoader.BASIS_FORMAT.cTFBC3 ] =
  272. THREE.BasisTextureLoader.DXT_FORMAT.COMPRESSED_RGBA_S3TC_DXT5_EXT;
  273. /* WEB WORKER */
  274. THREE.BasisTextureLoader.BasisWorker = function () {
  275. var config;
  276. var transcoderPending;
  277. var _BasisFile;
  278. onmessage = function ( e ) {
  279. var message = e.data;
  280. switch ( message.type ) {
  281. case 'init':
  282. config = message.config;
  283. init( message.transcoderBinary );
  284. break;
  285. case 'transcode':
  286. transcoderPending.then( () => {
  287. try {
  288. var { width, height, hasAlpha, mipmaps, format } = transcode( message.buffer );
  289. var buffers = [];
  290. for ( var i = 0; i < mipmaps.length; ++ i ) {
  291. buffers.push( mipmaps[ i ].data.buffer );
  292. }
  293. self.postMessage( { type: 'transcode', id: message.id, width, height, hasAlpha, mipmaps, format }, buffers );
  294. } catch ( error ) {
  295. console.error( error );
  296. self.postMessage( { type: 'error', id: message.id, error: error.message } );
  297. }
  298. } );
  299. break;
  300. }
  301. };
  302. function init( wasmBinary ) {
  303. var BasisModule;
  304. transcoderPending = new Promise( ( resolve ) => {
  305. BasisModule = { wasmBinary, onRuntimeInitialized: resolve };
  306. BASIS( BasisModule );
  307. } ).then( () => {
  308. var { BasisFile, initializeBasis } = BasisModule;
  309. _BasisFile = BasisFile;
  310. initializeBasis();
  311. } );
  312. }
  313. function transcode( buffer ) {
  314. var basisFile = new _BasisFile( new Uint8Array( buffer ) );
  315. var width = basisFile.getImageWidth( 0, 0 );
  316. var height = basisFile.getImageHeight( 0, 0 );
  317. var levels = basisFile.getNumLevels( 0 );
  318. var hasAlpha = basisFile.getHasAlpha();
  319. function cleanup() {
  320. basisFile.close();
  321. basisFile.delete();
  322. }
  323. if ( ! hasAlpha ) {
  324. switch ( config.format ) {
  325. case 9: // Hardcoded: THREE.BasisTextureLoader.BASIS_FORMAT.cTFPVRTC1_4_RGBA
  326. config.format = 8; // Hardcoded: THREE.BasisTextureLoader.BASIS_FORMAT.cTFPVRTC1_4_RGB;
  327. break;
  328. default:
  329. break;
  330. }
  331. }
  332. if ( ! width || ! height || ! levels ) {
  333. cleanup();
  334. throw new Error( 'THREE.BasisTextureLoader: Invalid .basis file' );
  335. }
  336. if ( ! basisFile.startTranscoding() ) {
  337. cleanup();
  338. throw new Error( 'THREE.BasisTextureLoader: .startTranscoding failed' );
  339. }
  340. var mipmaps = [];
  341. for ( var mip = 0; mip < levels; mip ++ ) {
  342. var mipWidth = basisFile.getImageWidth( 0, mip );
  343. var mipHeight = basisFile.getImageHeight( 0, mip );
  344. var dst = new Uint8Array( basisFile.getImageTranscodedSizeInBytes( 0, mip, config.format ) );
  345. var status = basisFile.transcodeImage(
  346. dst,
  347. 0,
  348. mip,
  349. config.format,
  350. 0,
  351. hasAlpha
  352. );
  353. if ( ! status ) {
  354. cleanup();
  355. throw new Error( 'THREE.BasisTextureLoader: .transcodeImage failed.' );
  356. }
  357. mipmaps.push( { data: dst, width: mipWidth, height: mipHeight } );
  358. }
  359. cleanup();
  360. return { width, height, hasAlpha, mipmaps, format: config.format };
  361. }
  362. };