DRACOLoader.js 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740
  1. /** Copyright 2016 The Draco Authors.
  2. *
  3. * Licensed under the Apache License, Version 2.0 (the "License");
  4. * you may not use this file except in compliance with the License.
  5. * You may obtain a copy of the License at
  6. *
  7. * http://www.apache.org/licenses/LICENSE-2.0
  8. *
  9. * Unless required by applicable law or agreed to in writing, software
  10. * distributed under the License is distributed on an "AS IS" BASIS,
  11. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  12. * See the License for the specific language governing permissions and
  13. * limitations under the License.
  14. */
  15. import {
  16. BufferGeometry,
  17. DefaultLoadingManager,
  18. FileLoader,
  19. Float32BufferAttribute,
  20. Int16BufferAttribute,
  21. Int32BufferAttribute,
  22. Int8BufferAttribute,
  23. TriangleStripDrawMode,
  24. TrianglesDrawMode,
  25. Uint16BufferAttribute,
  26. Uint32BufferAttribute,
  27. Uint8BufferAttribute
  28. } from "../../../build/three.module.js";
  29. /**
  30. * @param {THREE.LoadingManager} manager
  31. */
  32. var DRACOLoader = function ( manager ) {
  33. this.timeLoaded = 0;
  34. this.manager = manager || DefaultLoadingManager;
  35. this.materials = null;
  36. this.verbosity = 0;
  37. this.attributeOptions = {};
  38. this.drawMode = TrianglesDrawMode;
  39. // Native Draco attribute type to Three.JS attribute type.
  40. this.nativeAttributeMap = {
  41. position: "POSITION",
  42. normal: "NORMAL",
  43. color: "COLOR",
  44. uv: "TEX_COORD"
  45. };
  46. };
  47. DRACOLoader.prototype = {
  48. constructor: DRACOLoader,
  49. load: function ( url, onLoad, onProgress, onError ) {
  50. var scope = this;
  51. var loader = new FileLoader( scope.manager );
  52. loader.setPath( this.path );
  53. loader.setResponseType( "arraybuffer" );
  54. loader.load(
  55. url,
  56. function ( blob ) {
  57. scope.decodeDracoFile( blob, onLoad );
  58. },
  59. onProgress,
  60. onError
  61. );
  62. },
  63. setPath: function ( value ) {
  64. this.path = value;
  65. return this;
  66. },
  67. setVerbosity: function ( level ) {
  68. this.verbosity = level;
  69. return this;
  70. },
  71. /**
  72. * Sets desired mode for generated geometry indices.
  73. * Can be either:
  74. * TrianglesDrawMode
  75. * TriangleStripDrawMode
  76. */
  77. setDrawMode: function ( drawMode ) {
  78. this.drawMode = drawMode;
  79. return this;
  80. },
  81. /**
  82. * Skips dequantization for a specific attribute.
  83. * |attributeName| is the js name of the given attribute type.
  84. * The only currently supported |attributeName| is 'position', more may be
  85. * added in future.
  86. */
  87. setSkipDequantization: function ( attributeName, skip ) {
  88. var skipDequantization = true;
  89. if ( typeof skip !== "undefined" ) skipDequantization = skip;
  90. this.getAttributeOptions(
  91. attributeName
  92. ).skipDequantization = skipDequantization;
  93. return this;
  94. },
  95. /**
  96. * Decompresses a Draco buffer. Names of attributes (for ID and type maps)
  97. * must be one of the supported three.js types, including: position, color,
  98. * normal, uv, uv2, skinIndex, skinWeight.
  99. *
  100. * @param {ArrayBuffer} rawBuffer
  101. * @param {Function} callback
  102. * @param {Object|undefined} attributeUniqueIdMap Provides a pre-defined ID
  103. * for each attribute in the geometry to be decoded. If given,
  104. * `attributeTypeMap` is required and `nativeAttributeMap` will be
  105. * ignored.
  106. * @param {Object|undefined} attributeTypeMap Provides a predefined data
  107. * type (as a typed array constructor) for each attribute in the
  108. * geometry to be decoded.
  109. */
  110. decodeDracoFile: function (
  111. rawBuffer,
  112. callback,
  113. attributeUniqueIdMap,
  114. attributeTypeMap
  115. ) {
  116. var scope = this;
  117. DRACOLoader.getDecoderModule().then( function ( module ) {
  118. scope.decodeDracoFileInternal(
  119. rawBuffer,
  120. module.decoder,
  121. callback,
  122. attributeUniqueIdMap,
  123. attributeTypeMap
  124. );
  125. } );
  126. },
  127. decodeDracoFileInternal: function (
  128. rawBuffer,
  129. dracoDecoder,
  130. callback,
  131. attributeUniqueIdMap,
  132. attributeTypeMap
  133. ) {
  134. /*
  135. * Here is how to use Draco Javascript decoder and get the geometry.
  136. */
  137. var buffer = new dracoDecoder.DecoderBuffer();
  138. buffer.Init( new Int8Array( rawBuffer ), rawBuffer.byteLength );
  139. var decoder = new dracoDecoder.Decoder();
  140. /*
  141. * Determine what type is this file: mesh or point cloud.
  142. */
  143. var geometryType = decoder.GetEncodedGeometryType( buffer );
  144. if ( geometryType == dracoDecoder.TRIANGULAR_MESH ) {
  145. if ( this.verbosity > 0 ) {
  146. console.log( "Loaded a mesh." );
  147. }
  148. } else if ( geometryType == dracoDecoder.POINT_CLOUD ) {
  149. if ( this.verbosity > 0 ) {
  150. console.log( "Loaded a point cloud." );
  151. }
  152. } else {
  153. var errorMsg = "DRACOLoader: Unknown geometry type.";
  154. console.error( errorMsg );
  155. throw new Error( errorMsg );
  156. }
  157. callback(
  158. this.convertDracoGeometryTo3JS(
  159. dracoDecoder,
  160. decoder,
  161. geometryType,
  162. buffer,
  163. attributeUniqueIdMap,
  164. attributeTypeMap
  165. )
  166. );
  167. },
  168. addAttributeToGeometry: function (
  169. dracoDecoder,
  170. decoder,
  171. dracoGeometry,
  172. attributeName,
  173. attributeType,
  174. attribute,
  175. geometry,
  176. geometryBuffer
  177. ) {
  178. if ( attribute.ptr === 0 ) {
  179. var errorMsg = "DRACOLoader: No attribute " + attributeName;
  180. console.error( errorMsg );
  181. throw new Error( errorMsg );
  182. }
  183. var numComponents = attribute.num_components();
  184. var numPoints = dracoGeometry.num_points();
  185. var numValues = numPoints * numComponents;
  186. var attributeData;
  187. var TypedBufferAttribute;
  188. switch ( attributeType ) {
  189. case Float32Array:
  190. attributeData = new dracoDecoder.DracoFloat32Array();
  191. decoder.GetAttributeFloatForAllPoints(
  192. dracoGeometry,
  193. attribute,
  194. attributeData
  195. );
  196. geometryBuffer[ attributeName ] = new Float32Array( numValues );
  197. TypedBufferAttribute = Float32BufferAttribute;
  198. break;
  199. case Int8Array:
  200. attributeData = new dracoDecoder.DracoInt8Array();
  201. decoder.GetAttributeInt8ForAllPoints(
  202. dracoGeometry,
  203. attribute,
  204. attributeData
  205. );
  206. geometryBuffer[ attributeName ] = new Int8Array( numValues );
  207. TypedBufferAttribute = Int8BufferAttribute;
  208. break;
  209. case Int16Array:
  210. attributeData = new dracoDecoder.DracoInt16Array();
  211. decoder.GetAttributeInt16ForAllPoints(
  212. dracoGeometry,
  213. attribute,
  214. attributeData
  215. );
  216. geometryBuffer[ attributeName ] = new Int16Array( numValues );
  217. TypedBufferAttribute = Int16BufferAttribute;
  218. break;
  219. case Int32Array:
  220. attributeData = new dracoDecoder.DracoInt32Array();
  221. decoder.GetAttributeInt32ForAllPoints(
  222. dracoGeometry,
  223. attribute,
  224. attributeData
  225. );
  226. geometryBuffer[ attributeName ] = new Int32Array( numValues );
  227. TypedBufferAttribute = Int32BufferAttribute;
  228. break;
  229. case Uint8Array:
  230. attributeData = new dracoDecoder.DracoUInt8Array();
  231. decoder.GetAttributeUInt8ForAllPoints(
  232. dracoGeometry,
  233. attribute,
  234. attributeData
  235. );
  236. geometryBuffer[ attributeName ] = new Uint8Array( numValues );
  237. TypedBufferAttribute = Uint8BufferAttribute;
  238. break;
  239. case Uint16Array:
  240. attributeData = new dracoDecoder.DracoUInt16Array();
  241. decoder.GetAttributeUInt16ForAllPoints(
  242. dracoGeometry,
  243. attribute,
  244. attributeData
  245. );
  246. geometryBuffer[ attributeName ] = new Uint16Array( numValues );
  247. TypedBufferAttribute = Uint16BufferAttribute;
  248. break;
  249. case Uint32Array:
  250. attributeData = new dracoDecoder.DracoUInt32Array();
  251. decoder.GetAttributeUInt32ForAllPoints(
  252. dracoGeometry,
  253. attribute,
  254. attributeData
  255. );
  256. geometryBuffer[ attributeName ] = new Uint32Array( numValues );
  257. TypedBufferAttribute = Uint32BufferAttribute;
  258. break;
  259. default:
  260. var errorMsg = "DRACOLoader: Unexpected attribute type.";
  261. console.error( errorMsg );
  262. throw new Error( errorMsg );
  263. }
  264. // Copy data from decoder.
  265. for ( var i = 0; i < numValues; i ++ ) {
  266. geometryBuffer[ attributeName ][ i ] = attributeData.GetValue( i );
  267. }
  268. // Add attribute to THREEJS geometry for rendering.
  269. geometry.addAttribute(
  270. attributeName,
  271. new TypedBufferAttribute( geometryBuffer[ attributeName ], numComponents )
  272. );
  273. dracoDecoder.destroy( attributeData );
  274. },
  275. convertDracoGeometryTo3JS: function (
  276. dracoDecoder,
  277. decoder,
  278. geometryType,
  279. buffer,
  280. attributeUniqueIdMap,
  281. attributeTypeMap
  282. ) {
  283. // TODO: Should not assume native Draco attribute IDs apply.
  284. if ( this.getAttributeOptions( "position" ).skipDequantization === true ) {
  285. decoder.SkipAttributeTransform( dracoDecoder.POSITION );
  286. }
  287. var dracoGeometry;
  288. var decodingStatus;
  289. var start_time = performance.now();
  290. if ( geometryType === dracoDecoder.TRIANGULAR_MESH ) {
  291. dracoGeometry = new dracoDecoder.Mesh();
  292. decodingStatus = decoder.DecodeBufferToMesh( buffer, dracoGeometry );
  293. } else {
  294. dracoGeometry = new dracoDecoder.PointCloud();
  295. decodingStatus = decoder.DecodeBufferToPointCloud( buffer, dracoGeometry );
  296. }
  297. if ( ! decodingStatus.ok() || dracoGeometry.ptr == 0 ) {
  298. var errorMsg = "DRACOLoader: Decoding failed: ";
  299. errorMsg += decodingStatus.error_msg();
  300. console.error( errorMsg );
  301. dracoDecoder.destroy( decoder );
  302. dracoDecoder.destroy( dracoGeometry );
  303. throw new Error( errorMsg );
  304. }
  305. var decode_end = performance.now();
  306. dracoDecoder.destroy( buffer );
  307. /*
  308. * Example on how to retrieve mesh and attributes.
  309. */
  310. var numFaces;
  311. if ( geometryType == dracoDecoder.TRIANGULAR_MESH ) {
  312. numFaces = dracoGeometry.num_faces();
  313. if ( this.verbosity > 0 ) {
  314. console.log( "Number of faces loaded: " + numFaces.toString() );
  315. }
  316. } else {
  317. numFaces = 0;
  318. }
  319. var numPoints = dracoGeometry.num_points();
  320. var numAttributes = dracoGeometry.num_attributes();
  321. if ( this.verbosity > 0 ) {
  322. console.log( "Number of points loaded: " + numPoints.toString() );
  323. console.log( "Number of attributes loaded: " + numAttributes.toString() );
  324. }
  325. // Verify if there is position attribute.
  326. // TODO: Should not assume native Draco attribute IDs apply.
  327. var posAttId = decoder.GetAttributeId( dracoGeometry, dracoDecoder.POSITION );
  328. if ( posAttId == - 1 ) {
  329. var errorMsg = "DRACOLoader: No position attribute found.";
  330. console.error( errorMsg );
  331. dracoDecoder.destroy( decoder );
  332. dracoDecoder.destroy( dracoGeometry );
  333. throw new Error( errorMsg );
  334. }
  335. var posAttribute = decoder.GetAttribute( dracoGeometry, posAttId );
  336. // Structure for converting to THREEJS geometry later.
  337. var geometryBuffer = {};
  338. // Import data to Three JS geometry.
  339. var geometry = new BufferGeometry();
  340. // Do not use both the native attribute map and a provided (e.g. glTF) map.
  341. if ( attributeUniqueIdMap ) {
  342. // Add attributes of user specified unique id. E.g. GLTF models.
  343. for ( var attributeName in attributeUniqueIdMap ) {
  344. var attributeType = attributeTypeMap[ attributeName ];
  345. var attributeId = attributeUniqueIdMap[ attributeName ];
  346. var attribute = decoder.GetAttributeByUniqueId(
  347. dracoGeometry,
  348. attributeId
  349. );
  350. this.addAttributeToGeometry(
  351. dracoDecoder,
  352. decoder,
  353. dracoGeometry,
  354. attributeName,
  355. attributeType,
  356. attribute,
  357. geometry,
  358. geometryBuffer
  359. );
  360. }
  361. } else {
  362. // Add native Draco attribute type to geometry.
  363. for ( var attributeName in this.nativeAttributeMap ) {
  364. var attId = decoder.GetAttributeId(
  365. dracoGeometry,
  366. dracoDecoder[ this.nativeAttributeMap[ attributeName ] ]
  367. );
  368. if ( attId !== - 1 ) {
  369. if ( this.verbosity > 0 ) {
  370. console.log( "Loaded " + attributeName + " attribute." );
  371. }
  372. var attribute = decoder.GetAttribute( dracoGeometry, attId );
  373. this.addAttributeToGeometry(
  374. dracoDecoder,
  375. decoder,
  376. dracoGeometry,
  377. attributeName,
  378. Float32Array,
  379. attribute,
  380. geometry,
  381. geometryBuffer
  382. );
  383. }
  384. }
  385. }
  386. // For mesh, we need to generate the faces.
  387. if ( geometryType == dracoDecoder.TRIANGULAR_MESH ) {
  388. if ( this.drawMode === TriangleStripDrawMode ) {
  389. var stripsArray = new dracoDecoder.DracoInt32Array();
  390. decoder.GetTriangleStripsFromMesh(
  391. dracoGeometry,
  392. stripsArray
  393. );
  394. geometryBuffer.indices = new Uint32Array( stripsArray.size() );
  395. for ( var i = 0; i < stripsArray.size(); ++ i ) {
  396. geometryBuffer.indices[ i ] = stripsArray.GetValue( i );
  397. }
  398. dracoDecoder.destroy( stripsArray );
  399. } else {
  400. var numIndices = numFaces * 3;
  401. geometryBuffer.indices = new Uint32Array( numIndices );
  402. var ia = new dracoDecoder.DracoInt32Array();
  403. for ( var i = 0; i < numFaces; ++ i ) {
  404. decoder.GetFaceFromMesh( dracoGeometry, i, ia );
  405. var index = i * 3;
  406. geometryBuffer.indices[ index ] = ia.GetValue( 0 );
  407. geometryBuffer.indices[ index + 1 ] = ia.GetValue( 1 );
  408. geometryBuffer.indices[ index + 2 ] = ia.GetValue( 2 );
  409. }
  410. dracoDecoder.destroy( ia );
  411. }
  412. }
  413. geometry.drawMode = this.drawMode;
  414. if ( geometryType == dracoDecoder.TRIANGULAR_MESH ) {
  415. geometry.setIndex(
  416. new ( geometryBuffer.indices.length > 65535
  417. ? Uint32BufferAttribute
  418. : Uint16BufferAttribute )( geometryBuffer.indices, 1 )
  419. );
  420. }
  421. // TODO: Should not assume native Draco attribute IDs apply.
  422. // TODO: Can other attribute types be quantized?
  423. var posTransform = new dracoDecoder.AttributeQuantizationTransform();
  424. if ( posTransform.InitFromAttribute( posAttribute ) ) {
  425. // Quantized attribute. Store the quantization parameters into the
  426. // js attribute.
  427. geometry.attributes[ "position" ].isQuantized = true;
  428. geometry.attributes[ "position" ].maxRange = posTransform.range();
  429. geometry.attributes[
  430. "position"
  431. ].numQuantizationBits = posTransform.quantization_bits();
  432. geometry.attributes[ "position" ].minValues = new Float32Array( 3 );
  433. for ( var i = 0; i < 3; ++ i ) {
  434. geometry.attributes[ "position" ].minValues[ i ] = posTransform.min_value(
  435. i
  436. );
  437. }
  438. }
  439. dracoDecoder.destroy( posTransform );
  440. dracoDecoder.destroy( decoder );
  441. dracoDecoder.destroy( dracoGeometry );
  442. this.decode_time = decode_end - start_time;
  443. this.import_time = performance.now() - decode_end;
  444. if ( this.verbosity > 0 ) {
  445. console.log( "Decode time: " + this.decode_time );
  446. console.log( "Import time: " + this.import_time );
  447. }
  448. return geometry;
  449. },
  450. isVersionSupported: function ( version, callback ) {
  451. DRACOLoader.getDecoderModule().then( function ( module ) {
  452. callback( module.decoder.isVersionSupported( version ) );
  453. } );
  454. },
  455. getAttributeOptions: function ( attributeName ) {
  456. if ( typeof this.attributeOptions[ attributeName ] === "undefined" )
  457. this.attributeOptions[ attributeName ] = {};
  458. return this.attributeOptions[ attributeName ];
  459. }
  460. };
  461. DRACOLoader.decoderPath = "./";
  462. DRACOLoader.decoderConfig = {};
  463. DRACOLoader.decoderModulePromise = null;
  464. /**
  465. * Sets the base path for decoder source files.
  466. * @param {string} path
  467. */
  468. DRACOLoader.setDecoderPath = function ( path ) {
  469. DRACOLoader.decoderPath = path;
  470. };
  471. /**
  472. * Sets decoder configuration and releases singleton decoder module. Module
  473. * will be recreated with the next decoding call.
  474. * @param {Object} config
  475. */
  476. DRACOLoader.setDecoderConfig = function ( config ) {
  477. var wasmBinary = DRACOLoader.decoderConfig.wasmBinary;
  478. DRACOLoader.decoderConfig = config || {};
  479. DRACOLoader.releaseDecoderModule();
  480. // Reuse WASM binary.
  481. if ( wasmBinary ) DRACOLoader.decoderConfig.wasmBinary = wasmBinary;
  482. };
  483. /**
  484. * Releases the singleton DracoDecoderModule instance. Module will be recreated
  485. * with the next decoding call.
  486. */
  487. DRACOLoader.releaseDecoderModule = function () {
  488. DRACOLoader.decoderModulePromise = null;
  489. };
  490. /**
  491. * Gets WebAssembly or asm.js singleton instance of DracoDecoderModule
  492. * after testing for browser support. Returns Promise that resolves when
  493. * module is available.
  494. * @return {Promise<{decoder: DracoDecoderModule}>}
  495. */
  496. DRACOLoader.getDecoderModule = function () {
  497. var scope = this;
  498. var path = DRACOLoader.decoderPath;
  499. var config = DRACOLoader.decoderConfig;
  500. var promise = DRACOLoader.decoderModulePromise;
  501. if ( promise ) return promise;
  502. // Load source files.
  503. if ( typeof DracoDecoderModule !== "undefined" ) {
  504. // Loaded externally.
  505. promise = Promise.resolve();
  506. } else if ( typeof WebAssembly !== "object" || config.type === "js" ) {
  507. // Load with asm.js.
  508. promise = DRACOLoader._loadScript( path + "draco_decoder.js" );
  509. } else {
  510. // Load with WebAssembly.
  511. config.wasmBinaryFile = path + "draco_decoder.wasm";
  512. promise = DRACOLoader._loadScript( path + "draco_wasm_wrapper.js" )
  513. .then( function () {
  514. return DRACOLoader._loadArrayBuffer( config.wasmBinaryFile );
  515. } )
  516. .then( function ( wasmBinary ) {
  517. config.wasmBinary = wasmBinary;
  518. } );
  519. }
  520. // Wait for source files, then create and return a decoder.
  521. promise = promise.then( function () {
  522. return new Promise( function ( resolve ) {
  523. config.onModuleLoaded = function ( decoder ) {
  524. scope.timeLoaded = performance.now();
  525. // Module is Promise-like. Wrap before resolving to avoid loop.
  526. resolve( { decoder: decoder } );
  527. };
  528. DracoDecoderModule( config );
  529. } );
  530. } );
  531. DRACOLoader.decoderModulePromise = promise;
  532. return promise;
  533. };
  534. /**
  535. * @param {string} src
  536. * @return {Promise}
  537. */
  538. DRACOLoader._loadScript = function ( src ) {
  539. var prevScript = document.getElementById( "decoder_script" );
  540. if ( prevScript !== null ) {
  541. prevScript.parentNode.removeChild( prevScript );
  542. }
  543. var head = document.getElementsByTagName( "head" )[ 0 ];
  544. var script = document.createElement( "script" );
  545. script.id = "decoder_script";
  546. script.type = "text/javascript";
  547. script.src = src;
  548. return new Promise( function ( resolve ) {
  549. script.onload = resolve;
  550. head.appendChild( script );
  551. } );
  552. };
  553. /**
  554. * @param {string} src
  555. * @return {Promise}
  556. */
  557. DRACOLoader._loadArrayBuffer = function ( src ) {
  558. var loader = new FileLoader();
  559. loader.setResponseType( "arraybuffer" );
  560. return new Promise( function ( resolve, reject ) {
  561. loader.load( src, resolve, undefined, reject );
  562. } );
  563. };
  564. export { DRACOLoader };