2
0

BasisTextureLoader.js 11 KB

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