BasisTextureLoader.js 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536
  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. // Check for an existing task using this buffer. A transferred buffer cannot be transferred
  77. // again from this thread.
  78. if ( THREE.BasisTextureLoader.taskCache.has( buffer ) ) {
  79. var cachedTask = THREE.BasisTextureLoader.taskCache.get( buffer );
  80. return cachedTask.promise.then( onLoad ).catch( onError );
  81. }
  82. this._createTexture( buffer, url )
  83. .then( onLoad )
  84. .catch( onError );
  85. }, onProgress, onError );
  86. },
  87. /**
  88. * @param {ArrayBuffer} buffer
  89. * @param {string} url
  90. * @return {Promise<THREE.CompressedTexture>}
  91. */
  92. _createTexture: function ( buffer, url ) {
  93. var worker;
  94. var taskID;
  95. var taskCost = buffer.byteLength;
  96. var texturePending = this._allocateWorker( taskCost )
  97. .then( ( _worker ) => {
  98. worker = _worker;
  99. taskID = this.workerNextTaskID ++;
  100. return new Promise( ( resolve, reject ) => {
  101. worker._callbacks[ taskID ] = { resolve, reject };
  102. worker.postMessage( { type: 'transcode', id: taskID, buffer }, [ buffer ] );
  103. } );
  104. } )
  105. .then( ( message ) => {
  106. var config = this.workerConfig;
  107. var { width, height, mipmaps, format } = message;
  108. var texture;
  109. switch ( format ) {
  110. case THREE.BasisTextureLoader.BASIS_FORMAT.cTFASTC_4x4:
  111. texture = new THREE.CompressedTexture( mipmaps, width, height, THREE.RGBA_ASTC_4x4_Format );
  112. break;
  113. case THREE.BasisTextureLoader.BASIS_FORMAT.cTFBC7_M5:
  114. texture = new THREE.CompressedTexture( mipmaps, width, height, THREE.RGBA_BPTC_Format );
  115. break;
  116. case THREE.BasisTextureLoader.BASIS_FORMAT.cTFBC1:
  117. case THREE.BasisTextureLoader.BASIS_FORMAT.cTFBC3:
  118. texture = new THREE.CompressedTexture( mipmaps, width, height, THREE.BasisTextureLoader.DXT_FORMAT_MAP[ config.format ], THREE.UnsignedByteType );
  119. break;
  120. case THREE.BasisTextureLoader.BASIS_FORMAT.cTFETC1:
  121. texture = new THREE.CompressedTexture( mipmaps, width, height, THREE.RGB_ETC1_Format );
  122. break;
  123. case THREE.BasisTextureLoader.BASIS_FORMAT.cTFPVRTC1_4_RGB:
  124. texture = new THREE.CompressedTexture( mipmaps, width, height, THREE.RGB_PVRTC_4BPPV1_Format );
  125. break;
  126. case THREE.BasisTextureLoader.BASIS_FORMAT.cTFPVRTC1_4_RGBA:
  127. texture = new THREE.CompressedTexture( mipmaps, width, height, THREE.RGBA_PVRTC_4BPPV1_Format );
  128. break;
  129. default:
  130. throw new Error( 'THREE.BasisTextureLoader: No supported format available.' );
  131. }
  132. texture.minFilter = mipmaps.length === 1 ? THREE.LinearFilter : THREE.LinearMipmapLinearFilter;
  133. texture.magFilter = THREE.LinearFilter;
  134. texture.generateMipmaps = false;
  135. texture.needsUpdate = true;
  136. return texture;
  137. } );
  138. // Note: replaced '.finally()' with '.catch().then()' block - iOS 11 support (#19416)
  139. texturePending
  140. .catch( () => true )
  141. .then( () => {
  142. if ( worker && taskID ) {
  143. worker._taskLoad -= taskCost;
  144. delete worker._callbacks[ taskID ];
  145. }
  146. } );
  147. // Cache the task result.
  148. THREE.BasisTextureLoader.taskCache.set( buffer, {
  149. url: url,
  150. promise: texturePending
  151. } );
  152. return texturePending;
  153. },
  154. _initTranscoder: function () {
  155. if ( ! this.transcoderPending ) {
  156. // Load transcoder wrapper.
  157. var jsLoader = new THREE.FileLoader( this.manager );
  158. jsLoader.setPath( this.transcoderPath );
  159. var jsContent = new Promise( ( resolve, reject ) => {
  160. jsLoader.load( 'basis_transcoder.js', resolve, undefined, reject );
  161. } );
  162. // Load transcoder WASM binary.
  163. var binaryLoader = new THREE.FileLoader( this.manager );
  164. binaryLoader.setPath( this.transcoderPath );
  165. binaryLoader.setResponseType( 'arraybuffer' );
  166. var binaryContent = new Promise( ( resolve, reject ) => {
  167. binaryLoader.load( 'basis_transcoder.wasm', resolve, undefined, reject );
  168. } );
  169. this.transcoderPending = Promise.all( [ jsContent, binaryContent ] )
  170. .then( ( [ jsContent, binaryContent ] ) => {
  171. var fn = THREE.BasisTextureLoader.BasisWorker.toString();
  172. var body = [
  173. '/* basis_transcoder.js */',
  174. jsContent,
  175. '/* worker */',
  176. fn.substring( fn.indexOf( '{' ) + 1, fn.lastIndexOf( '}' ) )
  177. ].join( '\n' );
  178. this.workerSourceURL = URL.createObjectURL( new Blob( [ body ] ) );
  179. this.transcoderBinary = binaryContent;
  180. } );
  181. }
  182. return this.transcoderPending;
  183. },
  184. _allocateWorker: function ( taskCost ) {
  185. return this._initTranscoder().then( () => {
  186. if ( this.workerPool.length < this.workerLimit ) {
  187. var worker = new Worker( this.workerSourceURL );
  188. worker._callbacks = {};
  189. worker._taskLoad = 0;
  190. worker.postMessage( {
  191. type: 'init',
  192. config: this.workerConfig,
  193. transcoderBinary: this.transcoderBinary,
  194. } );
  195. worker.onmessage = function ( e ) {
  196. var message = e.data;
  197. switch ( message.type ) {
  198. case 'transcode':
  199. worker._callbacks[ message.id ].resolve( message );
  200. break;
  201. case 'error':
  202. worker._callbacks[ message.id ].reject( message );
  203. break;
  204. default:
  205. console.error( 'THREE.BasisTextureLoader: Unexpected message, "' + message.type + '"' );
  206. }
  207. };
  208. this.workerPool.push( worker );
  209. } else {
  210. this.workerPool.sort( function ( a, b ) {
  211. return a._taskLoad > b._taskLoad ? - 1 : 1;
  212. } );
  213. }
  214. var worker = this.workerPool[ this.workerPool.length - 1 ];
  215. worker._taskLoad += taskCost;
  216. return worker;
  217. } );
  218. },
  219. dispose: function () {
  220. for ( var i = 0; i < this.workerPool.length; i ++ ) {
  221. this.workerPool[ i ].terminate();
  222. }
  223. this.workerPool.length = 0;
  224. return this;
  225. }
  226. } );
  227. /* CONSTANTS */
  228. THREE.BasisTextureLoader.BASIS_FORMAT = {
  229. cTFETC1: 0,
  230. cTFETC2: 1,
  231. cTFBC1: 2,
  232. cTFBC3: 3,
  233. cTFBC4: 4,
  234. cTFBC5: 5,
  235. cTFBC7_M6_OPAQUE_ONLY: 6,
  236. cTFBC7_M5: 7,
  237. cTFPVRTC1_4_RGB: 8,
  238. cTFPVRTC1_4_RGBA: 9,
  239. cTFASTC_4x4: 10,
  240. cTFATC_RGB: 11,
  241. cTFATC_RGBA_INTERPOLATED_ALPHA: 12,
  242. cTFRGBA32: 13,
  243. cTFRGB565: 14,
  244. cTFBGR565: 15,
  245. cTFRGBA4444: 16,
  246. };
  247. // DXT formats, from:
  248. // http://www.khronos.org/registry/webgl/extensions/WEBGL_compressed_texture_s3tc/
  249. THREE.BasisTextureLoader.DXT_FORMAT = {
  250. COMPRESSED_RGB_S3TC_DXT1_EXT: 0x83F0,
  251. COMPRESSED_RGBA_S3TC_DXT1_EXT: 0x83F1,
  252. COMPRESSED_RGBA_S3TC_DXT3_EXT: 0x83F2,
  253. COMPRESSED_RGBA_S3TC_DXT5_EXT: 0x83F3,
  254. };
  255. THREE.BasisTextureLoader.DXT_FORMAT_MAP = {};
  256. THREE.BasisTextureLoader.DXT_FORMAT_MAP[ THREE.BasisTextureLoader.BASIS_FORMAT.cTFBC1 ] =
  257. THREE.BasisTextureLoader.DXT_FORMAT.COMPRESSED_RGB_S3TC_DXT1_EXT;
  258. THREE.BasisTextureLoader.DXT_FORMAT_MAP[ THREE.BasisTextureLoader.BASIS_FORMAT.cTFBC3 ] =
  259. THREE.BasisTextureLoader.DXT_FORMAT.COMPRESSED_RGBA_S3TC_DXT5_EXT;
  260. /* WEB WORKER */
  261. THREE.BasisTextureLoader.BasisWorker = function () {
  262. var config;
  263. var transcoderPending;
  264. var _BasisFile;
  265. onmessage = function ( e ) {
  266. var message = e.data;
  267. switch ( message.type ) {
  268. case 'init':
  269. config = message.config;
  270. init( message.transcoderBinary );
  271. break;
  272. case 'transcode':
  273. transcoderPending.then( () => {
  274. try {
  275. var { width, height, hasAlpha, mipmaps, format } = transcode( message.buffer );
  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. var BasisModule;
  291. transcoderPending = new Promise( ( resolve ) => {
  292. BasisModule = { wasmBinary, onRuntimeInitialized: resolve };
  293. BASIS( BasisModule );
  294. } ).then( () => {
  295. var { BasisFile, initializeBasis } = BasisModule;
  296. _BasisFile = BasisFile;
  297. initializeBasis();
  298. } );
  299. }
  300. function transcode( buffer ) {
  301. var basisFile = new _BasisFile( new Uint8Array( buffer ) );
  302. var width = basisFile.getImageWidth( 0, 0 );
  303. var height = basisFile.getImageHeight( 0, 0 );
  304. var levels = basisFile.getNumLevels( 0 );
  305. var hasAlpha = basisFile.getHasAlpha();
  306. function cleanup() {
  307. basisFile.close();
  308. basisFile.delete();
  309. }
  310. if ( ! hasAlpha ) {
  311. switch ( config.format ) {
  312. case 9: // Hardcoded: THREE.BasisTextureLoader.BASIS_FORMAT.cTFPVRTC1_4_RGBA
  313. config.format = 8; // Hardcoded: THREE.BasisTextureLoader.BASIS_FORMAT.cTFPVRTC1_4_RGB;
  314. break;
  315. default:
  316. break;
  317. }
  318. }
  319. if ( ! width || ! height || ! levels ) {
  320. cleanup();
  321. throw new Error( 'THREE.BasisTextureLoader: Invalid .basis file' );
  322. }
  323. if ( ! basisFile.startTranscoding() ) {
  324. cleanup();
  325. throw new Error( 'THREE.BasisTextureLoader: .startTranscoding failed' );
  326. }
  327. var mipmaps = [];
  328. for ( var mip = 0; mip < levels; mip ++ ) {
  329. var mipWidth = basisFile.getImageWidth( 0, mip );
  330. var mipHeight = basisFile.getImageHeight( 0, mip );
  331. var dst = new Uint8Array( basisFile.getImageTranscodedSizeInBytes( 0, mip, config.format ) );
  332. var status = basisFile.transcodeImage(
  333. dst,
  334. 0,
  335. mip,
  336. config.format,
  337. 0,
  338. hasAlpha
  339. );
  340. if ( ! status ) {
  341. cleanup();
  342. throw new Error( 'THREE.BasisTextureLoader: .transcodeImage failed.' );
  343. }
  344. mipmaps.push( { data: dst, width: mipWidth, height: mipHeight } );
  345. }
  346. cleanup();
  347. return { width, height, hasAlpha, mipmaps, format: config.format };
  348. }
  349. };