DRACOLoader.js 19 KB

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