DRACOLoader.js 18 KB

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