DRACOLoader.js 17 KB

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