DRACOLoader2.js 14 KB

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