BasisTextureLoader.js 9.2 KB

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