DRACOLoader.js 18 KB

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