BasisTextureLoader.js 9.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401
  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 { data, width, height } = message;
  85. var mipmaps = [ { data, width, height } ];
  86. var texture;
  87. if ( config.etcSupported ) {
  88. texture = new THREE.CompressedTexture( mipmaps, width, height, THREE.RGB_ETC1_Format );
  89. } else if ( config.dxtSupported ) {
  90. texture = new THREE.CompressedTexture( mipmaps, width, height, THREE.BasisTextureLoader.DXT_FORMAT_MAP[ config.format ], THREE.UnsignedByteType );
  91. } else if ( config.pvrtcSupported ) {
  92. texture = new THREE.CompressedTexture( mipmaps, width, height, THREE.RGB_PVRTC_4BPPV1_Format );
  93. } else {
  94. throw new Error( 'THREE.BasisTextureLoader: No supported format available.' );
  95. }
  96. texture.minFilter = THREE.LinearMipMapLinearFilter;
  97. texture.magFilter = THREE.LinearFilter;
  98. texture.encoding = THREE.sRGBEncoding;
  99. texture.generateMipmaps = false;
  100. texture.needsUpdate = true;
  101. return texture;
  102. });
  103. }
  104. _initTranscoder () {
  105. if ( ! this.transcoderBinary ) {
  106. // TODO(donmccurdy): Use THREE.FileLoader.
  107. var jsContent = fetch( this.transcoderPath + 'basis_transcoder.js' )
  108. .then( ( response ) => response.text() );
  109. var binaryContent = fetch( this.transcoderPath + 'basis_transcoder.wasm' )
  110. .then( ( response ) => response.arrayBuffer() );
  111. this.transcoderPending = Promise.all( [ jsContent, binaryContent ] )
  112. .then( ( [ jsContent, binaryContent ] ) => {
  113. var fn = THREE.BasisTextureLoader.BasisWorker.toString();
  114. var body = [
  115. '/* basis_transcoder.js */',
  116. 'var Module;',
  117. 'function createBasisModule () {',
  118. ' ' + jsContent,
  119. ' return Module;',
  120. '}',
  121. '',
  122. '/* worker */',
  123. fn.substring( fn.indexOf( '{' ) + 1, fn.lastIndexOf( '}' ) )
  124. ].join( '\n' );
  125. this.workerSourceURL = URL.createObjectURL( new Blob( [ body ] ) );
  126. this.transcoderBinary = binaryContent;
  127. } );
  128. }
  129. return this.transcoderPending;
  130. }
  131. getWorker () {
  132. return this._initTranscoder().then( () => {
  133. if ( this.workerPool.length < this.workerLimit ) {
  134. var worker = new Worker( this.workerSourceURL );
  135. worker._callbacks = {};
  136. worker._taskCosts = {};
  137. worker._taskLoad = 0;
  138. worker._taskCount = 0;
  139. worker.postMessage( {
  140. type: 'init',
  141. config: this.workerConfig,
  142. transcoderBinary: this.transcoderBinary,
  143. } );
  144. worker.onmessage = function ( e ) {
  145. var message = e.data;
  146. switch ( message.type ) {
  147. case 'transcode':
  148. worker._callbacks[ message.id ]( message );
  149. worker._taskLoad -= worker._taskCosts[ message.id ];
  150. delete worker._callbacks[ message.id ];
  151. delete worker._taskCosts[ message.id ];
  152. break;
  153. default:
  154. throw new Error( 'THREE.BasisTextureLoader: Unexpected message, "' + message.type + '"' );
  155. }
  156. }
  157. this.workerPool.push( worker );
  158. } else {
  159. this.workerPool.sort( function ( a, b ) { return a._taskLoad > b._taskLoad ? -1 : 1; } );
  160. }
  161. return this.workerPool[ this.workerPool.length - 1 ];
  162. } );
  163. }
  164. dispose () {
  165. for ( var i = 0; i < this.workerPool.length; i++ ) {
  166. this.workerPool[ i ].terminate();
  167. }
  168. this.workerPool.length = 0;
  169. }
  170. }
  171. /* CONSTANTS */
  172. THREE.BasisTextureLoader.BASIS_FORMAT = {
  173. cTFETC1: 0,
  174. cTFBC1: 1,
  175. cTFBC4: 2,
  176. cTFPVRTC1_4_OPAQUE_ONLY: 3,
  177. cTFBC7_M6_OPAQUE_ONLY: 4,
  178. cTFETC2: 5,
  179. cTFBC3: 6,
  180. cTFBC5: 7,
  181. };
  182. // DXT formats, from:
  183. // http://www.khronos.org/registry/webgl/extensions/WEBGL_compressed_texture_s3tc/
  184. THREE.BasisTextureLoader.DXT_FORMAT = {
  185. COMPRESSED_RGB_S3TC_DXT1_EXT: 0x83F0,
  186. COMPRESSED_RGBA_S3TC_DXT1_EXT: 0x83F1,
  187. COMPRESSED_RGBA_S3TC_DXT3_EXT: 0x83F2,
  188. COMPRESSED_RGBA_S3TC_DXT5_EXT: 0x83F3,
  189. };
  190. THREE.BasisTextureLoader.DXT_FORMAT_MAP = {};
  191. THREE.BasisTextureLoader.DXT_FORMAT_MAP[ THREE.BasisTextureLoader.BASIS_FORMAT.cTFBC1 ] =
  192. THREE.BasisTextureLoader.DXT_FORMAT.COMPRESSED_RGB_S3TC_DXT1_EXT;
  193. THREE.BasisTextureLoader.DXT_FORMAT_MAP[ THREE.BasisTextureLoader.BASIS_FORMAT.cTFBC3 ] =
  194. THREE.BasisTextureLoader.DXT_FORMAT.COMPRESSED_RGBA_S3TC_DXT5_EXT;
  195. /* WEB WORKER */
  196. THREE.BasisTextureLoader.BasisWorker = function () {
  197. var config;
  198. var transcoderPending;
  199. var _BasisFile;
  200. onmessage = function ( e ) {
  201. var message = e.data;
  202. switch ( message.type ) {
  203. case 'init':
  204. config = message.config;
  205. init( message.transcoderBinary );
  206. break;
  207. case 'transcode':
  208. transcoderPending.then( () => {
  209. var { data, width, height } = transcode( message.buffer );
  210. self.postMessage( { type: 'transcode', id: message.id, data, width, height }, [ data.buffer ] );
  211. } );
  212. break;
  213. }
  214. };
  215. function init ( wasmBinary ) {
  216. transcoderPending = new Promise( ( resolve ) => {
  217. // The 'Module' global is used by the Basis wrapper, which will check for
  218. // the 'wasmBinary' property before trying to load the file itself.
  219. // TODO(donmccurdy): This only works with a modified version of the
  220. // emscripten-generated wrapper. The default seems to have a bug making it
  221. // impossible to override the WASM binary.
  222. Module = { wasmBinary, onRuntimeInitialized: resolve };
  223. } ).then( () => {
  224. var { BasisFile, initializeBasis } = Module;
  225. _BasisFile = BasisFile;
  226. initializeBasis();
  227. } );
  228. createBasisModule();
  229. }
  230. function transcode ( buffer ) {
  231. var basisFile = new _BasisFile( new Uint8Array( buffer ) );
  232. var width = basisFile.getImageWidth( 0, 0 );
  233. var height = basisFile.getImageHeight( 0, 0 );
  234. var images = basisFile.getNumImages();
  235. var levels = basisFile.getNumLevels( 0 );
  236. function cleanup () {
  237. basisFile.close();
  238. basisFile.delete();
  239. }
  240. if ( ! width || ! height || ! images || ! levels ) {
  241. cleanup();
  242. throw new Error( 'THREE.BasisTextureLoader: Invalid .basis file' );
  243. }
  244. if ( ! basisFile.startTranscoding() ) {
  245. cleanup();
  246. throw new Error( 'THREE.BasisTextureLoader: .startTranscoding failed' );
  247. }
  248. var dst = new Uint8Array( basisFile.getImageTranscodedSizeInBytes( 0, 0, config.format ) );
  249. var startTime = performance.now();
  250. var status = basisFile.transcodeImage(
  251. dst,
  252. 0,
  253. 0,
  254. config.format,
  255. config.etcSupported ? 0 : ( config.dxtSupported ? 1 : 0 ),
  256. 0
  257. );
  258. cleanup();
  259. if ( ! status ) {
  260. throw new Error( 'THREE.BasisTextureLoader: .transcodeImage failed.' );
  261. }
  262. return { data: dst, width, height };
  263. }
  264. };