BasisTextureLoader.js 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486
  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. this.manager = manager || THREE.DefaultLoadingManager;
  20. this.crossOrigin = 'anonymous';
  21. this.transcoderPath = '';
  22. this.transcoderBinary = null;
  23. this.transcoderPending = null;
  24. this.workerLimit = 4;
  25. this.workerPool = [];
  26. this.workerNextTaskID = 1;
  27. this.workerSourceURL = '';
  28. this.workerConfig = {
  29. format: null,
  30. etcSupported: false,
  31. dxtSupported: false,
  32. pvrtcSupported: false,
  33. };
  34. };
  35. THREE.BasisTextureLoader.prototype = {
  36. constructor: THREE.BasisTextureLoader,
  37. setCrossOrigin: function ( crossOrigin ) {
  38. this.crossOrigin = crossOrigin;
  39. return this;
  40. },
  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 context = renderer.context;
  51. var config = this.workerConfig;
  52. config.etcSupported = !! context.getExtension( 'WEBGL_compressed_texture_etc1' );
  53. config.dxtSupported = !! context.getExtension( 'WEBGL_compressed_texture_s3tc' );
  54. config.pvrtcSupported = !! context.getExtension( 'WEBGL_compressed_texture_pvrtc' )
  55. || !! context.getExtension( 'WEBKIT_WEBGL_compressed_texture_pvrtc' );
  56. if ( config.etcSupported ) {
  57. config.format = THREE.BasisTextureLoader.BASIS_FORMAT.cTFETC1;
  58. } else if ( config.dxtSupported ) {
  59. config.format = THREE.BasisTextureLoader.BASIS_FORMAT.cTFBC1;
  60. } else if ( config.pvrtcSupported ) {
  61. config.format = THREE.BasisTextureLoader.BASIS_FORMAT.cTFPVRTC1_4_OPAQUE_ONLY;
  62. } else {
  63. throw new Error( 'THREE.BasisTextureLoader: No suitable compressed texture format found.' );
  64. }
  65. return this;
  66. },
  67. load: function ( url, onLoad, onProgress, onError ) {
  68. var loader = new THREE.FileLoader( this.manager );
  69. loader.setResponseType( 'arraybuffer' );
  70. loader.load( url, ( buffer ) => {
  71. this._createTexture( buffer )
  72. .then( onLoad )
  73. .catch( onError );
  74. }, onProgress, onError );
  75. },
  76. /**
  77. * @param {ArrayBuffer} buffer
  78. * @return {Promise<THREE.CompressedTexture>}
  79. */
  80. _createTexture: function ( buffer ) {
  81. var worker;
  82. var taskID;
  83. var texturePending = this._getWorker()
  84. .then( ( _worker ) => {
  85. worker = _worker;
  86. taskID = this.workerNextTaskID ++;
  87. return new Promise( ( resolve, reject ) => {
  88. worker._callbacks[ taskID ] = { resolve, reject };
  89. worker._taskCosts[ taskID ] = buffer.byteLength;
  90. worker._taskLoad += worker._taskCosts[ taskID ];
  91. worker.postMessage( { type: 'transcode', id: taskID, buffer }, [ buffer ] );
  92. } );
  93. } )
  94. .then( ( message ) => {
  95. var config = this.workerConfig;
  96. var { width, height, mipmaps } = message;
  97. var texture;
  98. if ( config.etcSupported ) {
  99. texture = new THREE.CompressedTexture( mipmaps, width, height, THREE.RGB_ETC1_Format );
  100. } else if ( config.dxtSupported ) {
  101. texture = new THREE.CompressedTexture( mipmaps, width, height, THREE.BasisTextureLoader.DXT_FORMAT_MAP[ config.format ], THREE.UnsignedByteType );
  102. } else if ( config.pvrtcSupported ) {
  103. texture = new THREE.CompressedTexture( mipmaps, width, height, THREE.RGB_PVRTC_4BPPV1_Format );
  104. } else {
  105. throw new Error( 'THREE.BasisTextureLoader: No supported format available.' );
  106. }
  107. texture.minFilter = THREE.LinearMipMapLinearFilter;
  108. texture.magFilter = THREE.LinearFilter;
  109. texture.generateMipmaps = false;
  110. texture.needsUpdate = true;
  111. return texture;
  112. } );
  113. texturePending
  114. .finally( () => {
  115. if ( worker && taskID ) {
  116. worker._taskLoad -= worker._taskCosts[ taskID ];
  117. delete worker._callbacks[ taskID ];
  118. delete worker._taskCosts[ taskID ];
  119. }
  120. } );
  121. return texturePending;
  122. },
  123. _initTranscoder: function () {
  124. if ( ! this.transcoderBinary ) {
  125. // Load transcoder wrapper.
  126. var jsLoader = new THREE.FileLoader( this.manager );
  127. jsLoader.setPath( this.transcoderPath );
  128. var jsContent = new Promise( ( resolve, reject ) => {
  129. jsLoader.load( 'basis_transcoder.js', resolve, undefined, reject );
  130. } );
  131. // Load transcoder WASM binary.
  132. var binaryLoader = new THREE.FileLoader( this.manager );
  133. binaryLoader.setPath( this.transcoderPath );
  134. binaryLoader.setResponseType( 'arraybuffer' );
  135. var binaryContent = new Promise( ( resolve, reject ) => {
  136. binaryLoader.load( 'basis_transcoder.wasm', resolve, undefined, reject );
  137. } );
  138. this.transcoderPending = Promise.all( [ jsContent, binaryContent ] )
  139. .then( ( [ jsContent, binaryContent ] ) => {
  140. var fn = THREE.BasisTextureLoader.BasisWorker.toString();
  141. var body = [
  142. '/* basis_transcoder.js */',
  143. 'var Module;',
  144. 'function createBasisModule () {',
  145. ' ' + jsContent,
  146. ' return Module;',
  147. '}',
  148. '',
  149. '/* worker */',
  150. fn.substring( fn.indexOf( '{' ) + 1, fn.lastIndexOf( '}' ) )
  151. ].join( '\n' );
  152. this.workerSourceURL = URL.createObjectURL( new Blob( [ body ] ) );
  153. this.transcoderBinary = binaryContent;
  154. } );
  155. }
  156. return this.transcoderPending;
  157. },
  158. _getWorker: function () {
  159. return this._initTranscoder().then( () => {
  160. if ( this.workerPool.length < this.workerLimit ) {
  161. var worker = new Worker( this.workerSourceURL );
  162. worker._callbacks = {};
  163. worker._taskCosts = {};
  164. worker._taskLoad = 0;
  165. worker.postMessage( {
  166. type: 'init',
  167. config: this.workerConfig,
  168. transcoderBinary: this.transcoderBinary,
  169. } );
  170. worker.onmessage = function ( e ) {
  171. var message = e.data;
  172. switch ( message.type ) {
  173. case 'transcode':
  174. worker._callbacks[ message.id ].resolve( message );
  175. break;
  176. case 'error':
  177. worker._callbacks[ message.id ].reject( message );
  178. break;
  179. default:
  180. console.error( 'THREE.BasisTextureLoader: Unexpected message, "' + message.type + '"' );
  181. }
  182. };
  183. this.workerPool.push( worker );
  184. } else {
  185. this.workerPool.sort( function ( a, b ) {
  186. return a._taskLoad > b._taskLoad ? - 1 : 1;
  187. } );
  188. }
  189. return this.workerPool[ this.workerPool.length - 1 ];
  190. } );
  191. },
  192. dispose: function () {
  193. for ( var i = 0; i < this.workerPool.length; i ++ ) {
  194. this.workerPool[ i ].terminate();
  195. }
  196. this.workerPool.length = 0;
  197. return this;
  198. }
  199. };
  200. /* CONSTANTS */
  201. THREE.BasisTextureLoader.BASIS_FORMAT = {
  202. cTFETC1: 0,
  203. cTFBC1: 1,
  204. cTFBC4: 2,
  205. cTFPVRTC1_4_OPAQUE_ONLY: 3,
  206. cTFBC7_M6_OPAQUE_ONLY: 4,
  207. cTFETC2: 5,
  208. cTFBC3: 6,
  209. cTFBC5: 7,
  210. };
  211. // DXT formats, from:
  212. // http://www.khronos.org/registry/webgl/extensions/WEBGL_compressed_texture_s3tc/
  213. THREE.BasisTextureLoader.DXT_FORMAT = {
  214. COMPRESSED_RGB_S3TC_DXT1_EXT: 0x83F0,
  215. COMPRESSED_RGBA_S3TC_DXT1_EXT: 0x83F1,
  216. COMPRESSED_RGBA_S3TC_DXT3_EXT: 0x83F2,
  217. COMPRESSED_RGBA_S3TC_DXT5_EXT: 0x83F3,
  218. };
  219. THREE.BasisTextureLoader.DXT_FORMAT_MAP = {};
  220. THREE.BasisTextureLoader.DXT_FORMAT_MAP[ THREE.BasisTextureLoader.BASIS_FORMAT.cTFBC1 ] =
  221. THREE.BasisTextureLoader.DXT_FORMAT.COMPRESSED_RGB_S3TC_DXT1_EXT;
  222. THREE.BasisTextureLoader.DXT_FORMAT_MAP[ THREE.BasisTextureLoader.BASIS_FORMAT.cTFBC3 ] =
  223. THREE.BasisTextureLoader.DXT_FORMAT.COMPRESSED_RGBA_S3TC_DXT5_EXT;
  224. /* WEB WORKER */
  225. THREE.BasisTextureLoader.BasisWorker = function () {
  226. var config;
  227. var transcoderPending;
  228. var _BasisFile;
  229. onmessage = function ( e ) {
  230. var message = e.data;
  231. switch ( message.type ) {
  232. case 'init':
  233. config = message.config;
  234. init( message.transcoderBinary );
  235. break;
  236. case 'transcode':
  237. transcoderPending.then( () => {
  238. try {
  239. var { width, height, mipmaps } = transcode( message.buffer );
  240. var buffers = [];
  241. for ( var i = 0; i < mipmaps.length; ++ i ) {
  242. buffers.push( mipmaps[ i ].data.buffer );
  243. }
  244. self.postMessage( { type: 'transcode', id: message.id, width, height, mipmaps }, buffers );
  245. } catch ( error ) {
  246. console.error( error );
  247. self.postMessage( { type: 'error', id: message.id, error: error.message } );
  248. }
  249. } );
  250. break;
  251. }
  252. };
  253. function init( wasmBinary ) {
  254. transcoderPending = new Promise( ( resolve ) => {
  255. // The 'Module' global is used by the Basis wrapper, which will check for
  256. // the 'wasmBinary' property before trying to load the file itself.
  257. // TODO(donmccurdy): This only works with a modified version of the
  258. // emscripten-generated wrapper. The default seems to have a bug making it
  259. // impossible to override the WASM binary.
  260. Module = { wasmBinary, onRuntimeInitialized: resolve };
  261. } ).then( () => {
  262. var { BasisFile, initializeBasis } = Module;
  263. _BasisFile = BasisFile;
  264. initializeBasis();
  265. } );
  266. createBasisModule();
  267. }
  268. function transcode( buffer ) {
  269. var basisFile = new _BasisFile( new Uint8Array( buffer ) );
  270. var width = basisFile.getImageWidth( 0, 0 );
  271. var height = basisFile.getImageHeight( 0, 0 );
  272. var levels = basisFile.getNumLevels( 0 );
  273. function cleanup() {
  274. basisFile.close();
  275. basisFile.delete();
  276. }
  277. if ( ! width || ! height || ! levels ) {
  278. cleanup();
  279. throw new Error( 'THREE.BasisTextureLoader: Invalid .basis file' );
  280. }
  281. if ( ! basisFile.startTranscoding() ) {
  282. cleanup();
  283. throw new Error( 'THREE.BasisTextureLoader: .startTranscoding failed' );
  284. }
  285. var mipmaps = [];
  286. for ( var mip = 0; mip < levels; mip ++ ) {
  287. var mipWidth = basisFile.getImageWidth( 0, mip );
  288. var mipHeight = basisFile.getImageHeight( 0, mip );
  289. var dst = new Uint8Array( basisFile.getImageTranscodedSizeInBytes( 0, mip, config.format ) );
  290. var status = basisFile.transcodeImage(
  291. dst,
  292. 0,
  293. mip,
  294. config.format,
  295. config.etcSupported ? 0 : ( config.dxtSupported ? 1 : 0 ),
  296. 0
  297. );
  298. if ( ! status ) {
  299. cleanup();
  300. throw new Error( 'THREE.BasisTextureLoader: .transcodeImage failed.' );
  301. }
  302. mipmaps.push( { data: dst, width: mipWidth, height: mipHeight } );
  303. }
  304. cleanup();
  305. return { width, height, mipmaps };
  306. }
  307. };