DRACOLoader.js 15 KB

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