DRACOLoader.js 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571
  1. ( function () {
  2. const _taskCache = new WeakMap();
  3. class DRACOLoader extends THREE.Loader {
  4. constructor( manager ) {
  5. super( manager );
  6. this.decoderPath = '';
  7. this.decoderConfig = {};
  8. this.decoderBinary = null;
  9. this.decoderPending = null;
  10. this.workerLimit = 4;
  11. this.workerPool = [];
  12. this.workerNextTaskID = 1;
  13. this.workerSourceURL = '';
  14. this.defaultAttributeIDs = {
  15. position: 'POSITION',
  16. normal: 'NORMAL',
  17. color: 'COLOR',
  18. uv: 'TEX_COORD'
  19. };
  20. this.defaultAttributeTypes = {
  21. position: 'Float32Array',
  22. normal: 'Float32Array',
  23. color: 'Float32Array',
  24. uv: 'Float32Array'
  25. };
  26. }
  27. setDecoderPath( path ) {
  28. this.decoderPath = path;
  29. return this;
  30. }
  31. setDecoderConfig( config ) {
  32. this.decoderConfig = config;
  33. return this;
  34. }
  35. setWorkerLimit( workerLimit ) {
  36. this.workerLimit = workerLimit;
  37. return this;
  38. }
  39. load( url, onLoad, onProgress, onError ) {
  40. const loader = new THREE.FileLoader( this.manager );
  41. loader.setPath( this.path );
  42. loader.setResponseType( 'arraybuffer' );
  43. loader.setRequestHeader( this.requestHeader );
  44. loader.setWithCredentials( this.withCredentials );
  45. loader.load( url, buffer => {
  46. const taskConfig = {
  47. attributeIDs: this.defaultAttributeIDs,
  48. attributeTypes: this.defaultAttributeTypes,
  49. useUniqueIDs: false
  50. };
  51. this.decodeGeometry( buffer, taskConfig ).then( onLoad ).catch( onError );
  52. }, onProgress, onError );
  53. }
  54. /** @deprecated Kept for backward-compatibility with previous DRACOLoader versions. */
  55. decodeDracoFile( buffer, callback, attributeIDs, attributeTypes ) {
  56. const taskConfig = {
  57. attributeIDs: attributeIDs || this.defaultAttributeIDs,
  58. attributeTypes: attributeTypes || this.defaultAttributeTypes,
  59. useUniqueIDs: !! attributeIDs
  60. };
  61. this.decodeGeometry( buffer, taskConfig ).then( callback );
  62. }
  63. decodeGeometry( buffer, taskConfig ) {
  64. // TODO: For backward-compatibility, support 'attributeTypes' objects containing
  65. // references (rather than names) to typed array constructors. These must be
  66. // serialized before sending them to the worker.
  67. for ( const attribute in taskConfig.attributeTypes ) {
  68. const type = taskConfig.attributeTypes[ attribute ];
  69. if ( type.BYTES_PER_ELEMENT !== undefined ) {
  70. taskConfig.attributeTypes[ attribute ] = type.name;
  71. }
  72. } //
  73. const taskKey = JSON.stringify( taskConfig ); // Check for an existing task using this buffer. A transferred buffer cannot be transferred
  74. // again from this thread.
  75. if ( _taskCache.has( buffer ) ) {
  76. const cachedTask = _taskCache.get( buffer );
  77. if ( cachedTask.key === taskKey ) {
  78. return cachedTask.promise;
  79. } else if ( buffer.byteLength === 0 ) {
  80. // Technically, it would be possible to wait for the previous task to complete,
  81. // transfer the buffer back, and decode again with the second configuration. That
  82. // is complex, and I don't know of any reason to decode a Draco buffer twice in
  83. // different ways, so this is left unimplemented.
  84. throw new Error( 'THREE.DRACOLoader: Unable to re-decode a buffer with different ' + 'settings. Buffer has already been transferred.' );
  85. }
  86. } //
  87. let worker;
  88. const taskID = this.workerNextTaskID ++;
  89. const taskCost = buffer.byteLength; // Obtain a worker and assign a task, and construct a geometry instance
  90. // when the task completes.
  91. const geometryPending = this._getWorker( taskID, taskCost ).then( _worker => {
  92. worker = _worker;
  93. return new Promise( ( resolve, reject ) => {
  94. worker._callbacks[ taskID ] = {
  95. resolve,
  96. reject
  97. };
  98. worker.postMessage( {
  99. type: 'decode',
  100. id: taskID,
  101. taskConfig,
  102. buffer
  103. }, [ buffer ] ); // this.debug();
  104. } );
  105. } ).then( message => this._createGeometry( message.geometry ) ); // Remove task from the task list.
  106. // Note: replaced '.finally()' with '.catch().then()' block - iOS 11 support (#19416)
  107. geometryPending.catch( () => true ).then( () => {
  108. if ( worker && taskID ) {
  109. this._releaseTask( worker, taskID ); // this.debug();
  110. }
  111. } ); // Cache the task result.
  112. _taskCache.set( buffer, {
  113. key: taskKey,
  114. promise: geometryPending
  115. } );
  116. return geometryPending;
  117. }
  118. _createGeometry( geometryData ) {
  119. const geometry = new THREE.BufferGeometry();
  120. if ( geometryData.index ) {
  121. geometry.setIndex( new THREE.BufferAttribute( geometryData.index.array, 1 ) );
  122. }
  123. for ( let i = 0; i < geometryData.attributes.length; i ++ ) {
  124. const attribute = geometryData.attributes[ i ];
  125. const name = attribute.name;
  126. const array = attribute.array;
  127. const itemSize = attribute.itemSize;
  128. geometry.setAttribute( name, new THREE.BufferAttribute( array, itemSize ) );
  129. }
  130. return geometry;
  131. }
  132. _loadLibrary( url, responseType ) {
  133. const loader = new THREE.FileLoader( this.manager );
  134. loader.setPath( this.decoderPath );
  135. loader.setResponseType( responseType );
  136. loader.setWithCredentials( this.withCredentials );
  137. return new Promise( ( resolve, reject ) => {
  138. loader.load( url, resolve, undefined, reject );
  139. } );
  140. }
  141. preload() {
  142. this._initDecoder();
  143. return this;
  144. }
  145. _initDecoder() {
  146. if ( this.decoderPending ) return this.decoderPending;
  147. const useJS = typeof WebAssembly !== 'object' || this.decoderConfig.type === 'js';
  148. const librariesPending = [];
  149. if ( useJS ) {
  150. librariesPending.push( this._loadLibrary( 'draco_decoder.js', 'text' ) );
  151. } else {
  152. librariesPending.push( this._loadLibrary( 'draco_wasm_wrapper.js', 'text' ) );
  153. librariesPending.push( this._loadLibrary( 'draco_decoder.wasm', 'arraybuffer' ) );
  154. }
  155. this.decoderPending = Promise.all( librariesPending ).then( libraries => {
  156. const jsContent = libraries[ 0 ];
  157. if ( ! useJS ) {
  158. this.decoderConfig.wasmBinary = libraries[ 1 ];
  159. }
  160. const fn = DRACOWorker.toString();
  161. const body = [ '/* draco decoder */', jsContent, '', '/* worker */', fn.substring( fn.indexOf( '{' ) + 1, fn.lastIndexOf( '}' ) ) ].join( '\n' );
  162. this.workerSourceURL = URL.createObjectURL( new Blob( [ body ] ) );
  163. } );
  164. return this.decoderPending;
  165. }
  166. _getWorker( taskID, taskCost ) {
  167. return this._initDecoder().then( () => {
  168. if ( this.workerPool.length < this.workerLimit ) {
  169. const worker = new Worker( this.workerSourceURL );
  170. worker._callbacks = {};
  171. worker._taskCosts = {};
  172. worker._taskLoad = 0;
  173. worker.postMessage( {
  174. type: 'init',
  175. decoderConfig: this.decoderConfig
  176. } );
  177. worker.onmessage = function ( e ) {
  178. const message = e.data;
  179. switch ( message.type ) {
  180. case 'decode':
  181. worker._callbacks[ message.id ].resolve( message );
  182. break;
  183. case 'error':
  184. worker._callbacks[ message.id ].reject( message );
  185. break;
  186. default:
  187. console.error( 'THREE.DRACOLoader: Unexpected message, "' + message.type + '"' );
  188. }
  189. };
  190. this.workerPool.push( worker );
  191. } else {
  192. this.workerPool.sort( function ( a, b ) {
  193. return a._taskLoad > b._taskLoad ? - 1 : 1;
  194. } );
  195. }
  196. const worker = this.workerPool[ this.workerPool.length - 1 ];
  197. worker._taskCosts[ taskID ] = taskCost;
  198. worker._taskLoad += taskCost;
  199. return worker;
  200. } );
  201. }
  202. _releaseTask( worker, taskID ) {
  203. worker._taskLoad -= worker._taskCosts[ taskID ];
  204. delete worker._callbacks[ taskID ];
  205. delete worker._taskCosts[ taskID ];
  206. }
  207. debug() {
  208. console.log( 'Task load: ', this.workerPool.map( worker => worker._taskLoad ) );
  209. }
  210. dispose() {
  211. for ( let i = 0; i < this.workerPool.length; ++ i ) {
  212. this.workerPool[ i ].terminate();
  213. }
  214. this.workerPool.length = 0;
  215. return this;
  216. }
  217. }
  218. /* WEB WORKER */
  219. function DRACOWorker() {
  220. let decoderConfig;
  221. let decoderPending;
  222. onmessage = function ( e ) {
  223. const message = e.data;
  224. switch ( message.type ) {
  225. case 'init':
  226. decoderConfig = message.decoderConfig;
  227. decoderPending = new Promise( function ( resolve
  228. /*, reject*/
  229. ) {
  230. decoderConfig.onModuleLoaded = function ( draco ) {
  231. // Module is Promise-like. Wrap before resolving to avoid loop.
  232. resolve( {
  233. draco: draco
  234. } );
  235. };
  236. DracoDecoderModule( decoderConfig ); // eslint-disable-line no-undef
  237. } );
  238. break;
  239. case 'decode':
  240. const buffer = message.buffer;
  241. const taskConfig = message.taskConfig;
  242. decoderPending.then( module => {
  243. const draco = module.draco;
  244. const decoder = new draco.Decoder();
  245. const decoderBuffer = new draco.DecoderBuffer();
  246. decoderBuffer.Init( new Int8Array( buffer ), buffer.byteLength );
  247. try {
  248. const geometry = decodeGeometry( draco, decoder, decoderBuffer, taskConfig );
  249. const buffers = geometry.attributes.map( attr => attr.array.buffer );
  250. if ( geometry.index ) buffers.push( geometry.index.array.buffer );
  251. self.postMessage( {
  252. type: 'decode',
  253. id: message.id,
  254. geometry
  255. }, buffers );
  256. } catch ( error ) {
  257. console.error( error );
  258. self.postMessage( {
  259. type: 'error',
  260. id: message.id,
  261. error: error.message
  262. } );
  263. } finally {
  264. draco.destroy( decoderBuffer );
  265. draco.destroy( decoder );
  266. }
  267. } );
  268. break;
  269. }
  270. };
  271. function decodeGeometry( draco, decoder, decoderBuffer, taskConfig ) {
  272. const attributeIDs = taskConfig.attributeIDs;
  273. const attributeTypes = taskConfig.attributeTypes;
  274. let dracoGeometry;
  275. let decodingStatus;
  276. const geometryType = decoder.GetEncodedGeometryType( decoderBuffer );
  277. if ( geometryType === draco.TRIANGULAR_MESH ) {
  278. dracoGeometry = new draco.Mesh();
  279. decodingStatus = decoder.DecodeBufferToMesh( decoderBuffer, dracoGeometry );
  280. } else if ( geometryType === draco.POINT_CLOUD ) {
  281. dracoGeometry = new draco.PointCloud();
  282. decodingStatus = decoder.DecodeBufferToPointCloud( decoderBuffer, dracoGeometry );
  283. } else {
  284. throw new Error( 'THREE.DRACOLoader: Unexpected geometry type.' );
  285. }
  286. if ( ! decodingStatus.ok() || dracoGeometry.ptr === 0 ) {
  287. throw new Error( 'THREE.DRACOLoader: Decoding failed: ' + decodingStatus.error_msg() );
  288. }
  289. const geometry = {
  290. index: null,
  291. attributes: []
  292. }; // Gather all vertex attributes.
  293. for ( const attributeName in attributeIDs ) {
  294. const attributeType = self[ attributeTypes[ attributeName ] ];
  295. let attribute;
  296. let attributeID; // A Draco file may be created with default vertex attributes, whose attribute IDs
  297. // are mapped 1:1 from their semantic name (POSITION, NORMAL, ...). Alternatively,
  298. // a Draco file may contain a custom set of attributes, identified by known unique
  299. // IDs. glTF files always do the latter, and `.drc` files typically do the former.
  300. if ( taskConfig.useUniqueIDs ) {
  301. attributeID = attributeIDs[ attributeName ];
  302. attribute = decoder.GetAttributeByUniqueId( dracoGeometry, attributeID );
  303. } else {
  304. attributeID = decoder.GetAttributeId( dracoGeometry, draco[ attributeIDs[ attributeName ] ] );
  305. if ( attributeID === - 1 ) continue;
  306. attribute = decoder.GetAttribute( dracoGeometry, attributeID );
  307. }
  308. geometry.attributes.push( decodeAttribute( draco, decoder, dracoGeometry, attributeName, attributeType, attribute ) );
  309. } // Add index.
  310. if ( geometryType === draco.TRIANGULAR_MESH ) {
  311. geometry.index = decodeIndex( draco, decoder, dracoGeometry );
  312. }
  313. draco.destroy( dracoGeometry );
  314. return geometry;
  315. }
  316. function decodeIndex( draco, decoder, dracoGeometry ) {
  317. const numFaces = dracoGeometry.num_faces();
  318. const numIndices = numFaces * 3;
  319. const byteLength = numIndices * 4;
  320. const ptr = draco._malloc( byteLength );
  321. decoder.GetTrianglesUInt32Array( dracoGeometry, byteLength, ptr );
  322. const index = new Uint32Array( draco.HEAPF32.buffer, ptr, numIndices ).slice();
  323. draco._free( ptr );
  324. return {
  325. array: index,
  326. itemSize: 1
  327. };
  328. }
  329. function decodeAttribute( draco, decoder, dracoGeometry, attributeName, attributeType, attribute ) {
  330. const numComponents = attribute.num_components();
  331. const numPoints = dracoGeometry.num_points();
  332. const numValues = numPoints * numComponents;
  333. const byteLength = numValues * attributeType.BYTES_PER_ELEMENT;
  334. const dataType = getDracoDataType( draco, attributeType );
  335. const ptr = draco._malloc( byteLength );
  336. decoder.GetAttributeDataArrayForAllPoints( dracoGeometry, attribute, dataType, byteLength, ptr );
  337. const array = new attributeType( draco.HEAPF32.buffer, ptr, numValues ).slice();
  338. draco._free( ptr );
  339. return {
  340. name: attributeName,
  341. array: array,
  342. itemSize: numComponents
  343. };
  344. }
  345. function getDracoDataType( draco, attributeType ) {
  346. switch ( attributeType ) {
  347. case Float32Array:
  348. return draco.DT_FLOAT32;
  349. case Int8Array:
  350. return draco.DT_INT8;
  351. case Int16Array:
  352. return draco.DT_INT16;
  353. case Int32Array:
  354. return draco.DT_INT32;
  355. case Uint8Array:
  356. return draco.DT_UINT8;
  357. case Uint16Array:
  358. return draco.DT_UINT16;
  359. case Uint32Array:
  360. return draco.DT_UINT32;
  361. }
  362. }
  363. }
  364. THREE.DRACOLoader = DRACOLoader;
  365. } )();