DRACOLoader2.js 13 KB

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