DRACOLoader.js 14 KB

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