DRACOLoader.js 13 KB

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