DRACOLoader.js 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688
  1. import {
  2. BufferAttribute,
  3. BufferGeometry,
  4. Color,
  5. ColorManagement,
  6. FileLoader,
  7. Loader,
  8. LinearSRGBColorSpace,
  9. SRGBColorSpace
  10. } from 'three';
  11. const _taskCache = new WeakMap();
  12. /**
  13. * A loader for the Draco format.
  14. *
  15. * [Draco]{@link https://google.github.io/draco/} is an open source library for compressing
  16. * and decompressing 3D meshes and point clouds. Compressed geometry can be significantly smaller,
  17. * at the cost of additional decoding time on the client device.
  18. *
  19. * Standalone Draco files have a `.drc` extension, and contain vertex positions, normals, colors,
  20. * and other attributes. Draco files do not contain materials, textures, animation, or node hierarchies –
  21. * to use these features, embed Draco geometry inside of a glTF file. A normal glTF file can be converted
  22. * to a Draco-compressed glTF file using [glTF-Pipeline]{@link https://github.com/CesiumGS/gltf-pipeline}.
  23. * When using Draco with glTF, an instance of `DRACOLoader` will be used internally by {@link GLTFLoader}.
  24. *
  25. * It is recommended to create one DRACOLoader instance and reuse it to avoid loading and creating
  26. * multiple decoder instances.
  27. *
  28. * `DRACOLoader` will automatically use either the JS or the WASM decoding library, based on
  29. * browser capabilities.
  30. *
  31. * ```js
  32. * const loader = new DRACOLoader();
  33. * loader.setDecoderPath( '/examples/jsm/libs/draco/' );
  34. *
  35. * const geometry = await dracoLoader.loadAsync( 'models/draco/bunny.drc' );
  36. * geometry.computeVertexNormals(); // optional
  37. *
  38. * dracoLoader.dispose();
  39. * ```
  40. *
  41. * @augments Loader
  42. * @three_import import { DRACOLoader } from 'three/addons/loaders/DRACOLoader.js';
  43. */
  44. class DRACOLoader extends Loader {
  45. /**
  46. * Constructs a new Draco loader.
  47. *
  48. * @param {LoadingManager} [manager] - The loading manager.
  49. */
  50. constructor( manager ) {
  51. super( manager );
  52. this.decoderPath = '';
  53. this.decoderConfig = {};
  54. this.decoderBinary = null;
  55. this.decoderPending = null;
  56. this.workerLimit = 4;
  57. this.workerPool = [];
  58. this.workerNextTaskID = 1;
  59. this.workerSourceURL = '';
  60. this.defaultAttributeIDs = {
  61. position: 'POSITION',
  62. normal: 'NORMAL',
  63. color: 'COLOR',
  64. uv: 'TEX_COORD'
  65. };
  66. this.defaultAttributeTypes = {
  67. position: 'Float32Array',
  68. normal: 'Float32Array',
  69. color: 'Float32Array',
  70. uv: 'Float32Array'
  71. };
  72. }
  73. /**
  74. * Provides configuration for the decoder libraries. Configuration cannot be changed after decoding begins.
  75. *
  76. * @param {string} path - The decoder path.
  77. * @return {DRACOLoader} A reference to this loader.
  78. */
  79. setDecoderPath( path ) {
  80. this.decoderPath = path;
  81. return this;
  82. }
  83. /**
  84. * Provides configuration for the decoder libraries. Configuration cannot be changed after decoding begins.
  85. *
  86. * @param {{type:('js'|'wasm')}} config - The decoder config.
  87. * @return {DRACOLoader} A reference to this loader.
  88. */
  89. setDecoderConfig( config ) {
  90. this.decoderConfig = config;
  91. return this;
  92. }
  93. /**
  94. * Sets the maximum number of Web Workers to be used during decoding.
  95. * A lower limit may be preferable if workers are also for other tasks in the application.
  96. *
  97. * @param {number} workerLimit - The worker limit.
  98. * @return {DRACOLoader} A reference to this loader.
  99. */
  100. setWorkerLimit( workerLimit ) {
  101. this.workerLimit = workerLimit;
  102. return this;
  103. }
  104. /**
  105. * Starts loading from the given URL and passes the loaded Draco asset
  106. * to the `onLoad()` callback.
  107. *
  108. * @param {string} url - The path/URL of the file to be loaded. This can also be a data URI.
  109. * @param {function(BufferGeometry)} onLoad - Executed when the loading process has been finished.
  110. * @param {onProgressCallback} onProgress - Executed while the loading is in progress.
  111. * @param {onErrorCallback} onError - Executed when errors occur.
  112. */
  113. load( url, onLoad, onProgress, onError ) {
  114. const loader = new FileLoader( this.manager );
  115. loader.setPath( this.path );
  116. loader.setResponseType( 'arraybuffer' );
  117. loader.setRequestHeader( this.requestHeader );
  118. loader.setWithCredentials( this.withCredentials );
  119. loader.load( url, ( buffer ) => {
  120. this.parse( buffer, onLoad, onError );
  121. }, onProgress, onError );
  122. }
  123. /**
  124. * Parses the given Draco data.
  125. *
  126. * @param {ArrayBuffer} buffer - The raw Draco data as an array buffer.
  127. * @param {function(BufferGeometry)} onLoad - Executed when the loading/parsing process has been finished.
  128. * @param {onErrorCallback} onError - Executed when errors occur.
  129. */
  130. parse( buffer, onLoad, onError = ()=>{} ) {
  131. this.decodeDracoFile( buffer, onLoad, null, null, SRGBColorSpace, onError ).catch( onError );
  132. }
  133. //
  134. decodeDracoFile( buffer, callback, attributeIDs, attributeTypes, vertexColorSpace = LinearSRGBColorSpace, onError = () => {} ) {
  135. const taskConfig = {
  136. attributeIDs: attributeIDs || this.defaultAttributeIDs,
  137. attributeTypes: attributeTypes || this.defaultAttributeTypes,
  138. useUniqueIDs: !! attributeIDs,
  139. vertexColorSpace: vertexColorSpace,
  140. };
  141. return this.decodeGeometry( buffer, taskConfig ).then( callback ).catch( onError );
  142. }
  143. decodeGeometry( buffer, taskConfig ) {
  144. const taskKey = JSON.stringify( taskConfig );
  145. // Check for an existing task using this buffer. A transferred buffer cannot be transferred
  146. // again from this thread.
  147. if ( _taskCache.has( buffer ) ) {
  148. const cachedTask = _taskCache.get( buffer );
  149. if ( cachedTask.key === taskKey ) {
  150. return cachedTask.promise;
  151. } else if ( buffer.byteLength === 0 ) {
  152. // Technically, it would be possible to wait for the previous task to complete,
  153. // transfer the buffer back, and decode again with the second configuration. That
  154. // is complex, and I don't know of any reason to decode a Draco buffer twice in
  155. // different ways, so this is left unimplemented.
  156. throw new Error(
  157. 'THREE.DRACOLoader: Unable to re-decode a buffer with different ' +
  158. 'settings. Buffer has already been transferred.'
  159. );
  160. }
  161. }
  162. //
  163. let worker;
  164. const taskID = this.workerNextTaskID ++;
  165. const taskCost = buffer.byteLength;
  166. // Obtain a worker and assign a task, and construct a geometry instance
  167. // when the task completes.
  168. const geometryPending = this._getWorker( taskID, taskCost )
  169. .then( ( _worker ) => {
  170. worker = _worker;
  171. return new Promise( ( resolve, reject ) => {
  172. worker._callbacks[ taskID ] = { resolve, reject };
  173. worker.postMessage( { type: 'decode', id: taskID, taskConfig, buffer }, [ buffer ] );
  174. // this.debug();
  175. } );
  176. } )
  177. .then( ( message ) => this._createGeometry( message.geometry ) );
  178. // Remove task from the task list.
  179. // Note: replaced '.finally()' with '.catch().then()' block - iOS 11 support (#19416)
  180. geometryPending
  181. .catch( () => true )
  182. .then( () => {
  183. if ( worker && taskID ) {
  184. this._releaseTask( worker, taskID );
  185. // this.debug();
  186. }
  187. } );
  188. // Cache the task result.
  189. _taskCache.set( buffer, {
  190. key: taskKey,
  191. promise: geometryPending
  192. } );
  193. return geometryPending;
  194. }
  195. _createGeometry( geometryData ) {
  196. const geometry = new BufferGeometry();
  197. if ( geometryData.index ) {
  198. geometry.setIndex( new BufferAttribute( geometryData.index.array, 1 ) );
  199. }
  200. for ( let i = 0; i < geometryData.attributes.length; i ++ ) {
  201. const result = geometryData.attributes[ i ];
  202. const name = result.name;
  203. const array = result.array;
  204. const itemSize = result.itemSize;
  205. const attribute = new BufferAttribute( array, itemSize );
  206. if ( name === 'color' ) {
  207. this._assignVertexColorSpace( attribute, result.vertexColorSpace );
  208. attribute.normalized = ( array instanceof Float32Array ) === false;
  209. }
  210. geometry.setAttribute( name, attribute );
  211. }
  212. return geometry;
  213. }
  214. _assignVertexColorSpace( attribute, inputColorSpace ) {
  215. // While .drc files do not specify colorspace, the only 'official' tooling
  216. // is PLY and OBJ converters, which use sRGB. We'll assume sRGB when a .drc
  217. // file is passed into .load() or .parse(). GLTFLoader uses internal APIs
  218. // to decode geometry, and vertex colors are already Linear-sRGB in there.
  219. if ( inputColorSpace !== SRGBColorSpace ) return;
  220. const _color = new Color();
  221. for ( let i = 0, il = attribute.count; i < il; i ++ ) {
  222. _color.fromBufferAttribute( attribute, i );
  223. ColorManagement.toWorkingColorSpace( _color, SRGBColorSpace );
  224. attribute.setXYZ( i, _color.r, _color.g, _color.b );
  225. }
  226. }
  227. _loadLibrary( url, responseType ) {
  228. const loader = new FileLoader( this.manager );
  229. loader.setPath( this.decoderPath );
  230. loader.setResponseType( responseType );
  231. loader.setWithCredentials( this.withCredentials );
  232. return new Promise( ( resolve, reject ) => {
  233. loader.load( url, resolve, undefined, reject );
  234. } );
  235. }
  236. preload() {
  237. this._initDecoder();
  238. return this;
  239. }
  240. _initDecoder() {
  241. if ( this.decoderPending ) return this.decoderPending;
  242. const useJS = typeof WebAssembly !== 'object' || this.decoderConfig.type === 'js';
  243. const librariesPending = [];
  244. if ( useJS ) {
  245. librariesPending.push( this._loadLibrary( 'draco_decoder.js', 'text' ) );
  246. } else {
  247. librariesPending.push( this._loadLibrary( 'draco_wasm_wrapper.js', 'text' ) );
  248. librariesPending.push( this._loadLibrary( 'draco_decoder.wasm', 'arraybuffer' ) );
  249. }
  250. this.decoderPending = Promise.all( librariesPending )
  251. .then( ( libraries ) => {
  252. const jsContent = libraries[ 0 ];
  253. if ( ! useJS ) {
  254. this.decoderConfig.wasmBinary = libraries[ 1 ];
  255. }
  256. const fn = DRACOWorker.toString();
  257. const body = [
  258. '/* draco decoder */',
  259. jsContent,
  260. '',
  261. '/* worker */',
  262. fn.substring( fn.indexOf( '{' ) + 1, fn.lastIndexOf( '}' ) )
  263. ].join( '\n' );
  264. this.workerSourceURL = URL.createObjectURL( new Blob( [ body ] ) );
  265. } );
  266. return this.decoderPending;
  267. }
  268. _getWorker( taskID, taskCost ) {
  269. return this._initDecoder().then( () => {
  270. if ( this.workerPool.length < this.workerLimit ) {
  271. const worker = new Worker( this.workerSourceURL );
  272. worker._callbacks = {};
  273. worker._taskCosts = {};
  274. worker._taskLoad = 0;
  275. worker.postMessage( { type: 'init', decoderConfig: this.decoderConfig } );
  276. worker.onmessage = function ( e ) {
  277. const message = e.data;
  278. switch ( message.type ) {
  279. case 'decode':
  280. worker._callbacks[ message.id ].resolve( message );
  281. break;
  282. case 'error':
  283. worker._callbacks[ message.id ].reject( message );
  284. break;
  285. default:
  286. console.error( 'THREE.DRACOLoader: Unexpected message, "' + message.type + '"' );
  287. }
  288. };
  289. this.workerPool.push( worker );
  290. } else {
  291. this.workerPool.sort( function ( a, b ) {
  292. return a._taskLoad > b._taskLoad ? - 1 : 1;
  293. } );
  294. }
  295. const worker = this.workerPool[ this.workerPool.length - 1 ];
  296. worker._taskCosts[ taskID ] = taskCost;
  297. worker._taskLoad += taskCost;
  298. return worker;
  299. } );
  300. }
  301. _releaseTask( worker, taskID ) {
  302. worker._taskLoad -= worker._taskCosts[ taskID ];
  303. delete worker._callbacks[ taskID ];
  304. delete worker._taskCosts[ taskID ];
  305. }
  306. debug() {
  307. console.log( 'Task load: ', this.workerPool.map( ( worker ) => worker._taskLoad ) );
  308. }
  309. dispose() {
  310. for ( let i = 0; i < this.workerPool.length; ++ i ) {
  311. this.workerPool[ i ].terminate();
  312. }
  313. this.workerPool.length = 0;
  314. if ( this.workerSourceURL !== '' ) {
  315. URL.revokeObjectURL( this.workerSourceURL );
  316. }
  317. return this;
  318. }
  319. }
  320. /* WEB WORKER */
  321. function DRACOWorker() {
  322. let decoderConfig;
  323. let decoderPending;
  324. onmessage = function ( e ) {
  325. const message = e.data;
  326. switch ( message.type ) {
  327. case 'init':
  328. decoderConfig = message.decoderConfig;
  329. decoderPending = new Promise( function ( resolve/*, reject*/ ) {
  330. decoderConfig.onModuleLoaded = function ( draco ) {
  331. // Module is Promise-like. Wrap before resolving to avoid loop.
  332. resolve( { draco: draco } );
  333. };
  334. DracoDecoderModule( decoderConfig ); // eslint-disable-line no-undef
  335. } );
  336. break;
  337. case 'decode':
  338. const buffer = message.buffer;
  339. const taskConfig = message.taskConfig;
  340. decoderPending.then( ( module ) => {
  341. const draco = module.draco;
  342. const decoder = new draco.Decoder();
  343. try {
  344. const geometry = decodeGeometry( draco, decoder, new Int8Array( buffer ), taskConfig );
  345. const buffers = geometry.attributes.map( ( attr ) => attr.array.buffer );
  346. if ( geometry.index ) buffers.push( geometry.index.array.buffer );
  347. self.postMessage( { type: 'decode', id: message.id, geometry }, buffers );
  348. } catch ( error ) {
  349. console.error( error );
  350. self.postMessage( { type: 'error', id: message.id, error: error.message } );
  351. } finally {
  352. draco.destroy( decoder );
  353. }
  354. } );
  355. break;
  356. }
  357. };
  358. function decodeGeometry( draco, decoder, array, taskConfig ) {
  359. const attributeIDs = taskConfig.attributeIDs;
  360. const attributeTypes = taskConfig.attributeTypes;
  361. let dracoGeometry;
  362. let decodingStatus;
  363. const geometryType = decoder.GetEncodedGeometryType( array );
  364. if ( geometryType === draco.TRIANGULAR_MESH ) {
  365. dracoGeometry = new draco.Mesh();
  366. decodingStatus = decoder.DecodeArrayToMesh( array, array.byteLength, dracoGeometry );
  367. } else if ( geometryType === draco.POINT_CLOUD ) {
  368. dracoGeometry = new draco.PointCloud();
  369. decodingStatus = decoder.DecodeArrayToPointCloud( array, array.byteLength, dracoGeometry );
  370. } else {
  371. throw new Error( 'THREE.DRACOLoader: Unexpected geometry type.' );
  372. }
  373. if ( ! decodingStatus.ok() || dracoGeometry.ptr === 0 ) {
  374. throw new Error( 'THREE.DRACOLoader: Decoding failed: ' + decodingStatus.error_msg() );
  375. }
  376. const geometry = { index: null, attributes: [] };
  377. // Gather all vertex attributes.
  378. for ( const attributeName in attributeIDs ) {
  379. const attributeType = self[ attributeTypes[ attributeName ] ];
  380. let attribute;
  381. let attributeID;
  382. // A Draco file may be created with default vertex attributes, whose attribute IDs
  383. // are mapped 1:1 from their semantic name (POSITION, NORMAL, ...). Alternatively,
  384. // a Draco file may contain a custom set of attributes, identified by known unique
  385. // IDs. glTF files always do the latter, and `.drc` files typically do the former.
  386. if ( taskConfig.useUniqueIDs ) {
  387. attributeID = attributeIDs[ attributeName ];
  388. attribute = decoder.GetAttributeByUniqueId( dracoGeometry, attributeID );
  389. } else {
  390. attributeID = decoder.GetAttributeId( dracoGeometry, draco[ attributeIDs[ attributeName ] ] );
  391. if ( attributeID === - 1 ) continue;
  392. attribute = decoder.GetAttribute( dracoGeometry, attributeID );
  393. }
  394. const attributeResult = decodeAttribute( draco, decoder, dracoGeometry, attributeName, attributeType, attribute );
  395. if ( attributeName === 'color' ) {
  396. attributeResult.vertexColorSpace = taskConfig.vertexColorSpace;
  397. }
  398. geometry.attributes.push( attributeResult );
  399. }
  400. // Add index.
  401. if ( geometryType === draco.TRIANGULAR_MESH ) {
  402. geometry.index = decodeIndex( draco, decoder, dracoGeometry );
  403. }
  404. draco.destroy( dracoGeometry );
  405. return geometry;
  406. }
  407. function decodeIndex( draco, decoder, dracoGeometry ) {
  408. const numFaces = dracoGeometry.num_faces();
  409. const numIndices = numFaces * 3;
  410. const byteLength = numIndices * 4;
  411. const ptr = draco._malloc( byteLength );
  412. decoder.GetTrianglesUInt32Array( dracoGeometry, byteLength, ptr );
  413. const index = new Uint32Array( draco.HEAPF32.buffer, ptr, numIndices ).slice();
  414. draco._free( ptr );
  415. return { array: index, itemSize: 1 };
  416. }
  417. function decodeAttribute( draco, decoder, dracoGeometry, attributeName, attributeType, attribute ) {
  418. const numComponents = attribute.num_components();
  419. const numPoints = dracoGeometry.num_points();
  420. const numValues = numPoints * numComponents;
  421. const byteLength = numValues * attributeType.BYTES_PER_ELEMENT;
  422. const dataType = getDracoDataType( draco, attributeType );
  423. const ptr = draco._malloc( byteLength );
  424. decoder.GetAttributeDataArrayForAllPoints( dracoGeometry, attribute, dataType, byteLength, ptr );
  425. const array = new attributeType( draco.HEAPF32.buffer, ptr, numValues ).slice();
  426. draco._free( ptr );
  427. return {
  428. name: attributeName,
  429. array: array,
  430. itemSize: numComponents
  431. };
  432. }
  433. function getDracoDataType( draco, attributeType ) {
  434. switch ( attributeType ) {
  435. case Float32Array: return draco.DT_FLOAT32;
  436. case Int8Array: return draco.DT_INT8;
  437. case Int16Array: return draco.DT_INT16;
  438. case Int32Array: return draco.DT_INT32;
  439. case Uint8Array: return draco.DT_UINT8;
  440. case Uint16Array: return draco.DT_UINT16;
  441. case Uint32Array: return draco.DT_UINT32;
  442. }
  443. }
  444. }
  445. export { DRACOLoader };