DRACOLoader.js 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615
  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. class DRACOLoader extends Loader {
  13. constructor( manager ) {
  14. super( manager );
  15. this.decoderPath = '';
  16. this.decoderConfig = {};
  17. this.decoderBinary = null;
  18. this.decoderPending = null;
  19. this.workerLimit = 4;
  20. this.workerPool = [];
  21. this.workerNextTaskID = 1;
  22. this.workerSourceURL = '';
  23. this.defaultAttributeIDs = {
  24. position: 'POSITION',
  25. normal: 'NORMAL',
  26. color: 'COLOR',
  27. uv: 'TEX_COORD'
  28. };
  29. this.defaultAttributeTypes = {
  30. position: 'Float32Array',
  31. normal: 'Float32Array',
  32. color: 'Float32Array',
  33. uv: 'Float32Array'
  34. };
  35. }
  36. setDecoderPath( path ) {
  37. this.decoderPath = path;
  38. return this;
  39. }
  40. setDecoderConfig( config ) {
  41. this.decoderConfig = config;
  42. return this;
  43. }
  44. setWorkerLimit( workerLimit ) {
  45. this.workerLimit = workerLimit;
  46. return this;
  47. }
  48. load( url, onLoad, onProgress, onError ) {
  49. const loader = new FileLoader( this.manager );
  50. loader.setPath( this.path );
  51. loader.setResponseType( 'arraybuffer' );
  52. loader.setRequestHeader( this.requestHeader );
  53. loader.setWithCredentials( this.withCredentials );
  54. loader.load( url, ( buffer ) => {
  55. this.parse( buffer, onLoad, onError );
  56. }, onProgress, onError );
  57. }
  58. parse( buffer, onLoad, onError = ()=>{} ) {
  59. this.decodeDracoFile( buffer, onLoad, null, null, SRGBColorSpace, onError ).catch( onError );
  60. }
  61. decodeDracoFile( buffer, callback, attributeIDs, attributeTypes, vertexColorSpace = LinearSRGBColorSpace, onError = () => {} ) {
  62. const taskConfig = {
  63. attributeIDs: attributeIDs || this.defaultAttributeIDs,
  64. attributeTypes: attributeTypes || this.defaultAttributeTypes,
  65. useUniqueIDs: !! attributeIDs,
  66. vertexColorSpace: vertexColorSpace,
  67. };
  68. return this.decodeGeometry( buffer, taskConfig ).then( callback ).catch( onError );
  69. }
  70. decodeGeometry( buffer, taskConfig ) {
  71. const taskKey = JSON.stringify( taskConfig );
  72. // Check for an existing task using this buffer. A transferred buffer cannot be transferred
  73. // again from this thread.
  74. if ( _taskCache.has( buffer ) ) {
  75. const cachedTask = _taskCache.get( buffer );
  76. if ( cachedTask.key === taskKey ) {
  77. return cachedTask.promise;
  78. } else if ( buffer.byteLength === 0 ) {
  79. // Technically, it would be possible to wait for the previous task to complete,
  80. // transfer the buffer back, and decode again with the second configuration. That
  81. // is complex, and I don't know of any reason to decode a Draco buffer twice in
  82. // different ways, so this is left unimplemented.
  83. throw new Error(
  84. 'THREE.DRACOLoader: Unable to re-decode a buffer with different ' +
  85. 'settings. Buffer has already been transferred.'
  86. );
  87. }
  88. }
  89. //
  90. let worker;
  91. const taskID = this.workerNextTaskID ++;
  92. const taskCost = buffer.byteLength;
  93. // Obtain a worker and assign a task, and construct a geometry instance
  94. // when the task completes.
  95. const geometryPending = this._getWorker( taskID, taskCost )
  96. .then( ( _worker ) => {
  97. worker = _worker;
  98. return new Promise( ( resolve, reject ) => {
  99. worker._callbacks[ taskID ] = { resolve, reject };
  100. worker.postMessage( { type: 'decode', id: taskID, taskConfig, buffer }, [ buffer ] );
  101. // this.debug();
  102. } );
  103. } )
  104. .then( ( message ) => this._createGeometry( message.geometry ) );
  105. // Remove task from the task list.
  106. // Note: replaced '.finally()' with '.catch().then()' block - iOS 11 support (#19416)
  107. geometryPending
  108. .catch( () => true )
  109. .then( () => {
  110. if ( worker && taskID ) {
  111. this._releaseTask( worker, taskID );
  112. // this.debug();
  113. }
  114. } );
  115. // Cache the task result.
  116. _taskCache.set( buffer, {
  117. key: taskKey,
  118. promise: geometryPending
  119. } );
  120. return geometryPending;
  121. }
  122. _createGeometry( geometryData ) {
  123. const geometry = new BufferGeometry();
  124. if ( geometryData.index ) {
  125. geometry.setIndex( new BufferAttribute( geometryData.index.array, 1 ) );
  126. }
  127. for ( let i = 0; i < geometryData.attributes.length; i ++ ) {
  128. const result = geometryData.attributes[ i ];
  129. const name = result.name;
  130. const array = result.array;
  131. const itemSize = result.itemSize;
  132. const attribute = new BufferAttribute( array, itemSize );
  133. if ( name === 'color' ) {
  134. this._assignVertexColorSpace( attribute, result.vertexColorSpace );
  135. attribute.normalized = ( array instanceof Float32Array ) === false;
  136. }
  137. geometry.setAttribute( name, attribute );
  138. }
  139. return geometry;
  140. }
  141. _assignVertexColorSpace( attribute, inputColorSpace ) {
  142. // While .drc files do not specify colorspace, the only 'official' tooling
  143. // is PLY and OBJ converters, which use sRGB. We'll assume sRGB when a .drc
  144. // file is passed into .load() or .parse(). GLTFLoader uses internal APIs
  145. // to decode geometry, and vertex colors are already Linear-sRGB in there.
  146. if ( inputColorSpace !== SRGBColorSpace ) return;
  147. const _color = new Color();
  148. for ( let i = 0, il = attribute.count; i < il; i ++ ) {
  149. _color.fromBufferAttribute( attribute, i );
  150. ColorManagement.toWorkingColorSpace( _color, SRGBColorSpace );
  151. attribute.setXYZ( i, _color.r, _color.g, _color.b );
  152. }
  153. }
  154. _loadLibrary( url, responseType ) {
  155. const loader = new FileLoader( this.manager );
  156. loader.setPath( this.decoderPath );
  157. loader.setResponseType( responseType );
  158. loader.setWithCredentials( this.withCredentials );
  159. return new Promise( ( resolve, reject ) => {
  160. loader.load( url, resolve, undefined, reject );
  161. } );
  162. }
  163. preload() {
  164. this._initDecoder();
  165. return this;
  166. }
  167. _initDecoder() {
  168. if ( this.decoderPending ) return this.decoderPending;
  169. const useJS = typeof WebAssembly !== 'object' || this.decoderConfig.type === 'js';
  170. const librariesPending = [];
  171. if ( useJS ) {
  172. librariesPending.push( this._loadLibrary( 'draco_decoder.js', 'text' ) );
  173. } else {
  174. librariesPending.push( this._loadLibrary( 'draco_wasm_wrapper.js', 'text' ) );
  175. librariesPending.push( this._loadLibrary( 'draco_decoder.wasm', 'arraybuffer' ) );
  176. }
  177. this.decoderPending = Promise.all( librariesPending )
  178. .then( ( libraries ) => {
  179. const jsContent = libraries[ 0 ];
  180. if ( ! useJS ) {
  181. this.decoderConfig.wasmBinary = libraries[ 1 ];
  182. }
  183. const fn = DRACOWorker.toString();
  184. const body = [
  185. '/* draco decoder */',
  186. jsContent,
  187. '',
  188. '/* worker */',
  189. fn.substring( fn.indexOf( '{' ) + 1, fn.lastIndexOf( '}' ) )
  190. ].join( '\n' );
  191. this.workerSourceURL = URL.createObjectURL( new Blob( [ body ] ) );
  192. } );
  193. return this.decoderPending;
  194. }
  195. _getWorker( taskID, taskCost ) {
  196. return this._initDecoder().then( () => {
  197. if ( this.workerPool.length < this.workerLimit ) {
  198. const worker = new Worker( this.workerSourceURL );
  199. worker._callbacks = {};
  200. worker._taskCosts = {};
  201. worker._taskLoad = 0;
  202. worker.postMessage( { type: 'init', decoderConfig: this.decoderConfig } );
  203. worker.onmessage = function ( e ) {
  204. const message = e.data;
  205. switch ( message.type ) {
  206. case 'decode':
  207. worker._callbacks[ message.id ].resolve( message );
  208. break;
  209. case 'error':
  210. worker._callbacks[ message.id ].reject( message );
  211. break;
  212. default:
  213. console.error( 'THREE.DRACOLoader: Unexpected message, "' + message.type + '"' );
  214. }
  215. };
  216. this.workerPool.push( worker );
  217. } else {
  218. this.workerPool.sort( function ( a, b ) {
  219. return a._taskLoad > b._taskLoad ? - 1 : 1;
  220. } );
  221. }
  222. const worker = this.workerPool[ this.workerPool.length - 1 ];
  223. worker._taskCosts[ taskID ] = taskCost;
  224. worker._taskLoad += taskCost;
  225. return worker;
  226. } );
  227. }
  228. _releaseTask( worker, taskID ) {
  229. worker._taskLoad -= worker._taskCosts[ taskID ];
  230. delete worker._callbacks[ taskID ];
  231. delete worker._taskCosts[ taskID ];
  232. }
  233. debug() {
  234. console.log( 'Task load: ', this.workerPool.map( ( worker ) => worker._taskLoad ) );
  235. }
  236. dispose() {
  237. for ( let i = 0; i < this.workerPool.length; ++ i ) {
  238. this.workerPool[ i ].terminate();
  239. }
  240. this.workerPool.length = 0;
  241. if ( this.workerSourceURL !== '' ) {
  242. URL.revokeObjectURL( this.workerSourceURL );
  243. }
  244. return this;
  245. }
  246. }
  247. /* WEB WORKER */
  248. function DRACOWorker() {
  249. let decoderConfig;
  250. let decoderPending;
  251. onmessage = function ( e ) {
  252. const message = e.data;
  253. switch ( message.type ) {
  254. case 'init':
  255. decoderConfig = message.decoderConfig;
  256. decoderPending = new Promise( function ( resolve/*, reject*/ ) {
  257. decoderConfig.onModuleLoaded = function ( draco ) {
  258. // Module is Promise-like. Wrap before resolving to avoid loop.
  259. resolve( { draco: draco } );
  260. };
  261. DracoDecoderModule( decoderConfig ); // eslint-disable-line no-undef
  262. } );
  263. break;
  264. case 'decode':
  265. const buffer = message.buffer;
  266. const taskConfig = message.taskConfig;
  267. decoderPending.then( ( module ) => {
  268. const draco = module.draco;
  269. const decoder = new draco.Decoder();
  270. try {
  271. const geometry = decodeGeometry( draco, decoder, new Int8Array( buffer ), taskConfig );
  272. const buffers = geometry.attributes.map( ( attr ) => attr.array.buffer );
  273. if ( geometry.index ) buffers.push( geometry.index.array.buffer );
  274. self.postMessage( { type: 'decode', id: message.id, geometry }, buffers );
  275. } catch ( error ) {
  276. console.error( error );
  277. self.postMessage( { type: 'error', id: message.id, error: error.message } );
  278. } finally {
  279. draco.destroy( decoder );
  280. }
  281. } );
  282. break;
  283. }
  284. };
  285. function decodeGeometry( draco, decoder, array, taskConfig ) {
  286. const attributeIDs = taskConfig.attributeIDs;
  287. const attributeTypes = taskConfig.attributeTypes;
  288. let dracoGeometry;
  289. let decodingStatus;
  290. const geometryType = decoder.GetEncodedGeometryType( array );
  291. if ( geometryType === draco.TRIANGULAR_MESH ) {
  292. dracoGeometry = new draco.Mesh();
  293. decodingStatus = decoder.DecodeArrayToMesh( array, array.byteLength, dracoGeometry );
  294. } else if ( geometryType === draco.POINT_CLOUD ) {
  295. dracoGeometry = new draco.PointCloud();
  296. decodingStatus = decoder.DecodeArrayToPointCloud( array, array.byteLength, dracoGeometry );
  297. } else {
  298. throw new Error( 'THREE.DRACOLoader: Unexpected geometry type.' );
  299. }
  300. if ( ! decodingStatus.ok() || dracoGeometry.ptr === 0 ) {
  301. throw new Error( 'THREE.DRACOLoader: Decoding failed: ' + decodingStatus.error_msg() );
  302. }
  303. const geometry = { index: null, attributes: [] };
  304. // Gather all vertex attributes.
  305. for ( const attributeName in attributeIDs ) {
  306. const attributeType = self[ attributeTypes[ attributeName ] ];
  307. let attribute;
  308. let attributeID;
  309. // A Draco file may be created with default vertex attributes, whose attribute IDs
  310. // are mapped 1:1 from their semantic name (POSITION, NORMAL, ...). Alternatively,
  311. // a Draco file may contain a custom set of attributes, identified by known unique
  312. // IDs. glTF files always do the latter, and `.drc` files typically do the former.
  313. if ( taskConfig.useUniqueIDs ) {
  314. attributeID = attributeIDs[ attributeName ];
  315. attribute = decoder.GetAttributeByUniqueId( dracoGeometry, attributeID );
  316. } else {
  317. attributeID = decoder.GetAttributeId( dracoGeometry, draco[ attributeIDs[ attributeName ] ] );
  318. if ( attributeID === - 1 ) continue;
  319. attribute = decoder.GetAttribute( dracoGeometry, attributeID );
  320. }
  321. const attributeResult = decodeAttribute( draco, decoder, dracoGeometry, attributeName, attributeType, attribute );
  322. if ( attributeName === 'color' ) {
  323. attributeResult.vertexColorSpace = taskConfig.vertexColorSpace;
  324. }
  325. geometry.attributes.push( attributeResult );
  326. }
  327. // Add index.
  328. if ( geometryType === draco.TRIANGULAR_MESH ) {
  329. geometry.index = decodeIndex( draco, decoder, dracoGeometry );
  330. }
  331. draco.destroy( dracoGeometry );
  332. return geometry;
  333. }
  334. function decodeIndex( draco, decoder, dracoGeometry ) {
  335. const numFaces = dracoGeometry.num_faces();
  336. const numIndices = numFaces * 3;
  337. const byteLength = numIndices * 4;
  338. const ptr = draco._malloc( byteLength );
  339. decoder.GetTrianglesUInt32Array( dracoGeometry, byteLength, ptr );
  340. const index = new Uint32Array( draco.HEAPF32.buffer, ptr, numIndices ).slice();
  341. draco._free( ptr );
  342. return { array: index, itemSize: 1 };
  343. }
  344. function decodeAttribute( draco, decoder, dracoGeometry, attributeName, attributeType, attribute ) {
  345. const numComponents = attribute.num_components();
  346. const numPoints = dracoGeometry.num_points();
  347. const numValues = numPoints * numComponents;
  348. const byteLength = numValues * attributeType.BYTES_PER_ELEMENT;
  349. const dataType = getDracoDataType( draco, attributeType );
  350. const ptr = draco._malloc( byteLength );
  351. decoder.GetAttributeDataArrayForAllPoints( dracoGeometry, attribute, dataType, byteLength, ptr );
  352. const array = new attributeType( draco.HEAPF32.buffer, ptr, numValues ).slice();
  353. draco._free( ptr );
  354. return {
  355. name: attributeName,
  356. array: array,
  357. itemSize: numComponents
  358. };
  359. }
  360. function getDracoDataType( draco, attributeType ) {
  361. switch ( attributeType ) {
  362. case Float32Array: return draco.DT_FLOAT32;
  363. case Int8Array: return draco.DT_INT8;
  364. case Int16Array: return draco.DT_INT16;
  365. case Int32Array: return draco.DT_INT32;
  366. case Uint8Array: return draco.DT_UINT8;
  367. case Uint16Array: return draco.DT_UINT16;
  368. case Uint32Array: return draco.DT_UINT32;
  369. }
  370. }
  371. }
  372. export { DRACOLoader };