DRACOLoader.js 15 KB

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