BasisTextureLoader.js 9.4 KB

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