BasisTextureLoader.js 11 KB

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