DRACOLoader.js 15 KB

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