DRACOLoader.js 15 KB

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