DRACOLoader.js 19 KB

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