DRACOLoader.js 19 KB

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