DRACOLoader.js 12 KB

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