DRACOLoader.js 12 KB

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