DRACOLoader2.js 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588
  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 ( rawBuffer, 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;
  92. var geometryPending = this._getWorker()
  93. .then( ( _worker ) => {
  94. worker = _worker;
  95. taskID = this.workerNextTaskID ++;
  96. return new Promise( ( resolve, reject ) => {
  97. worker._callbacks[ taskID ] = { resolve, reject };
  98. worker._taskCosts[ taskID ] = buffer.byteLength;
  99. worker._taskLoad += worker._taskCosts[ taskID ];
  100. worker.postMessage( { type: 'decode', id: taskID, taskConfig, buffer }, [ buffer ] );
  101. } );
  102. } )
  103. .then( ( message ) => {
  104. var geometryData = message.geometry;
  105. var geometry = new THREE.BufferGeometry();
  106. if ( geometryData.index ) {
  107. geometry.setIndex( new THREE.BufferAttribute( geometryData.index.array, 1 ) );
  108. }
  109. for ( var i = 0; i < geometryData.attributes.length; i++ ) {
  110. var attribute = geometryData.attributes[ i ];
  111. var name = attribute.name;
  112. var array = attribute.array;
  113. var itemSize = attribute.itemSize;
  114. geometry.addAttribute( name, new THREE.BufferAttribute( array, itemSize ) );
  115. }
  116. return geometry;
  117. } );
  118. geometryPending
  119. .finally( () => {
  120. if ( worker && taskID ) {
  121. worker._taskLoad -= worker._taskCosts[ taskID ];
  122. delete worker._callbacks[ taskID ];
  123. delete worker._taskCosts[ taskID ];
  124. }
  125. } );
  126. return geometryPending;
  127. },
  128. _loadLibrary: function ( url, responseType ) {
  129. var loader = new THREE.FileLoader( this.manager );
  130. loader.setPath( this.decoderPath );
  131. loader.setResponseType( responseType );
  132. return new Promise( ( resolve, reject ) => {
  133. loader.load( url, resolve, undefined, reject );
  134. } );
  135. },
  136. _initDecoder: function () {
  137. if ( this.decoderPending ) return this.decoderPending;
  138. var useJS = typeof WebAssembly !== 'object' || this.decoderConfig.type === 'js';
  139. var librariesPending = [];
  140. if ( useJS ) {
  141. librariesPending.push( this._loadLibrary( 'draco_decoder.js', 'text' ) );
  142. } else {
  143. librariesPending.push( this._loadLibrary( 'draco_wasm_wrapper.js', 'text' ) );
  144. librariesPending.push( this._loadLibrary( 'draco_decoder.wasm', 'arraybuffer' ) );
  145. }
  146. this.decoderPending = Promise.all( librariesPending )
  147. .then( ( libraries ) => {
  148. var jsContent = libraries[ 0 ];
  149. if ( ! useJS ) {
  150. this.decoderConfig.wasmBinary = libraries[ 1 ];
  151. }
  152. var fn = THREE.DRACOLoader.DRACOWorker.toString();
  153. var body = [
  154. '/* draco decoder */',
  155. jsContent,
  156. '',
  157. '/* worker */',
  158. fn.substring( fn.indexOf( '{' ) + 1, fn.lastIndexOf( '}' ) )
  159. ].join( '\n' );
  160. this.workerSourceURL = URL.createObjectURL( new Blob( [ body ] ) );
  161. } );
  162. return this.decoderPending;
  163. },
  164. _getWorker: function () {
  165. return this._initDecoder().then( () => {
  166. if ( this.workerPool.length < this.workerLimit ) {
  167. var worker = new Worker( this.workerSourceURL );
  168. worker._callbacks = {};
  169. worker._taskCosts = {};
  170. worker._taskLoad = 0;
  171. worker.postMessage( { type: 'init', decoderConfig: this.decoderConfig } );
  172. worker.onmessage = function ( e ) {
  173. var message = e.data;
  174. switch ( message.type ) {
  175. case 'decode':
  176. worker._callbacks[ message.id ].resolve( message );
  177. break;
  178. case 'error':
  179. worker._callbacks[ message.id ].reject( message );
  180. break;
  181. default:
  182. console.error( 'THREE.DRACOLoader: Unexpected message, "' + message.type + '"' );
  183. }
  184. };
  185. this.workerPool.push( worker );
  186. } else {
  187. this.workerPool.sort( function ( a, b ) {
  188. return a._taskLoad > b._taskLoad ? - 1 : 1;
  189. } );
  190. }
  191. return this.workerPool[ this.workerPool.length - 1 ];
  192. } );
  193. },
  194. dispose: function () {
  195. for ( var i = 0; i < this.workerPool.length; ++ i ) {
  196. this.workerPool[ i ].terminate();
  197. }
  198. this.workerPool.length = 0;
  199. return this;
  200. }
  201. };
  202. /* WEB WORKER */
  203. THREE.DRACOLoader.DRACOWorker = function () {
  204. var decoderConfig;
  205. var decoderPending;
  206. onmessage = function ( e ) {
  207. var message = e.data;
  208. switch ( message.type ) {
  209. case 'init':
  210. decoderConfig = message.decoderConfig;
  211. decoderPending = new Promise( function ( resolve, reject ) {
  212. decoderConfig.onModuleLoaded = function ( draco ) {
  213. // Module is Promise-like. Wrap before resolving to avoid loop.
  214. resolve( { draco: draco } );
  215. };
  216. DracoDecoderModule( decoderConfig );
  217. } );
  218. break;
  219. case 'decode':
  220. var buffer = message.buffer;
  221. var taskConfig = message.taskConfig;
  222. decoderPending.then( ( module ) => {
  223. var draco = module.draco;
  224. var decoder = new draco.Decoder();
  225. var decoderBuffer = new draco.DecoderBuffer();
  226. decoderBuffer.Init( new Int8Array( buffer ), buffer.byteLength );
  227. try {
  228. var geometry = decodeGeometry( draco, decoder, decoderBuffer, taskConfig );
  229. var buffers = geometry.attributes.map( ( attr ) => attr.array.buffer );
  230. if ( geometry.index ) buffers.push( geometry.index.array.buffer );
  231. self.postMessage( { type: 'decode', id: message.id, geometry }, buffers );
  232. } catch ( error ) {
  233. console.error( error );
  234. self.postMessage( { type: 'error', id: message.id, error: error.message } );
  235. } finally {
  236. draco.destroy( decoderBuffer );
  237. draco.destroy( decoder );
  238. }
  239. } );
  240. break;
  241. }
  242. };
  243. function decodeGeometry( draco, decoder, decoderBuffer, taskConfig ) {
  244. var attributeIDs = taskConfig.attributeIDs;
  245. var attributeTypes = taskConfig.attributeTypes;
  246. var dracoGeometry;
  247. var decodingStatus;
  248. var geometryType = decoder.GetEncodedGeometryType( decoderBuffer );
  249. if ( geometryType === draco.TRIANGULAR_MESH ) {
  250. dracoGeometry = new draco.Mesh();
  251. decodingStatus = decoder.DecodeBufferToMesh( decoderBuffer, dracoGeometry );
  252. } else if ( geometryType === draco.POINT_CLOUD ) {
  253. dracoGeometry = new draco.PointCloud();
  254. decodingStatus = decoder.DecodeBufferToPointCloud( decoderBuffer, dracoGeometry );
  255. } else {
  256. throw new Error( 'THREE.DRACOLoader: Unexpected geometry type.' );
  257. }
  258. if ( ! decodingStatus.ok() || dracoGeometry.ptr === 0 ) {
  259. throw new Error( 'THREE.DRACOLoader: Decoding failed: ' + decodingStatus.error_msg() );
  260. }
  261. var geometry = { index: null, attributes: [] };
  262. var numPoints = dracoGeometry.num_points();
  263. var numAttributes = dracoGeometry.num_attributes();
  264. // Add attributes of user specified unique id.
  265. for (var attributeName in attributeIDs) {
  266. var attributeType = self[ attributeTypes[ attributeName ] ];
  267. var attributeId = attributeIDs[ attributeName ];
  268. var attribute = decoder.GetAttributeByUniqueId( dracoGeometry, attributeId );
  269. geometry.attributes.push( this.decodeAttribute( draco, decoder, dracoGeometry, attributeName, attributeType, attribute ) );
  270. }
  271. // Add index.
  272. if ( geometryType === draco.TRIANGULAR_MESH ) {
  273. // Generate mesh faces.
  274. var numFaces = dracoGeometry.num_faces();
  275. var numIndices = numFaces * 3;
  276. var index = new Uint32Array( numIndices );
  277. var indexArray = new draco.DracoInt32Array();
  278. for ( var i = 0; i < numFaces; ++ i ) {
  279. decoder.GetFaceFromMesh( dracoGeometry, i, indexArray );
  280. for ( var j = 0; j < 3; ++ j ) {
  281. index[ i * 3 + j ] = indexArray.GetValue( j );
  282. }
  283. }
  284. geometry.index = { array: index, itemSize: 1 };
  285. draco.destroy( indexArray );
  286. }
  287. draco.destroy( dracoGeometry );
  288. return geometry;
  289. };
  290. function decodeAttribute ( draco, decoder, dracoGeometry, attributeName, attributeType, attribute ) {
  291. var numComponents = attribute.num_components();
  292. var numPoints = dracoGeometry.num_points();
  293. var numValues = numPoints * numComponents;
  294. var dracoArray;
  295. var array;
  296. switch ( attributeType ) {
  297. case Float32Array:
  298. dracoArray = new draco.DracoFloat32Array();
  299. decoder.GetAttributeFloatForAllPoints( dracoGeometry, attribute, dracoArray );
  300. array = new Float32Array( numValues );
  301. break;
  302. case Int8Array:
  303. dracoArray = new draco.DracoInt8Array();
  304. decoder.GetAttributeInt8ForAllPoints( dracoGeometry, attribute, dracoArray );
  305. array = new Int8Array( numValues );
  306. break;
  307. case Int16Array:
  308. dracoArray = new draco.DracoInt16Array();
  309. decoder.GetAttributeInt16ForAllPoints( dracoGeometry, attribute, dracoArray );
  310. array = new Int16Array( numValues );
  311. break;
  312. case Int32Array:
  313. dracoArray = new draco.DracoInt32Array();
  314. decoder.GetAttributeInt32ForAllPoints( dracoGeometry, attribute, dracoArray );
  315. array = new Int32Array( numValues );
  316. break;
  317. case Uint8Array:
  318. dracoArray = new draco.DracoUInt8Array();
  319. decoder.GetAttributeUInt8ForAllPoints( dracoGeometry, attribute, dracoArray );
  320. array = new Uint8Array( numValues );
  321. break;
  322. case Uint16Array:
  323. dracoArray = new draco.DracoUInt16Array();
  324. decoder.GetAttributeUInt16ForAllPoints( dracoGeometry, attribute, dracoArray );
  325. array = new Uint16Array( numValues );
  326. break;
  327. case Uint32Array:
  328. dracoArray = new draco.DracoUInt32Array();
  329. decoder.GetAttributeUInt32ForAllPoints( dracoGeometry, attribute, dracoArray );
  330. array = new Uint32Array( numValues );
  331. break;
  332. default:
  333. throw new Error( 'THREE.DRACOLoader: Unexpected attribute type.' );
  334. }
  335. for ( var i = 0; i < numValues; i++ ) {
  336. array[ i ] = dracoArray.GetValue( i );
  337. }
  338. draco.destroy( dracoArray );
  339. return {
  340. name: attributeName,
  341. array: array,
  342. itemSize: numComponents
  343. };
  344. };
  345. };
  346. /** Deprecated static methods */
  347. /** @deprecated */
  348. THREE.DRACOLoader.setDecoderPath = function () {
  349. console.warn( 'THREE.DRACOLoader: The .setDecoderPath() method has been removed. Use instance methods.' );
  350. };
  351. /** @deprecated */
  352. THREE.DRACOLoader.setDecoderConfig = function () {
  353. console.warn( 'THREE.DRACOLoader: The .setDecoderConfig() method has been removed. Use instance methods.' );
  354. };
  355. /** @deprecated */
  356. THREE.DRACOLoader.releaseDecoderModule = function () {
  357. console.warn( 'THREE.DRACOLoader: The .releaseDecoderModule() method has been removed. Use instance methods.' );
  358. };
  359. /** @deprecated */
  360. THREE.DRACOLoader.getDecoderModule = function () {
  361. console.warn( 'THREE.DRACOLoader: The .getDecoderModule() method has been removed. Use instance methods.' );
  362. };