DRACOLoader.js 15 KB

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