DRACOLoader.js 13 KB

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