DRACOLoader.js 15 KB

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