DRACOLoader.js 14 KB

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