2
0

DRACOLoader2.js 13 KB

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