VTKLoader.js 27 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174
  1. /**
  2. * @author mrdoob / http://mrdoob.com/
  3. * @author Alex Pletzer
  4. *
  5. * Updated on 22.03.2017
  6. * VTK header is now parsed and used to extract all the compressed data
  7. * @author Andrii Iudin https://github.com/andreyyudin
  8. * @author Paul Kibet Korir https://github.com/polarise
  9. * @author Sriram Somasundharam https://github.com/raamssundar
  10. */
  11. THREE.VTKLoader = function ( manager ) {
  12. this.manager = ( manager !== undefined ) ? manager : THREE.DefaultLoadingManager;
  13. };
  14. Object.assign( THREE.VTKLoader.prototype, THREE.EventDispatcher.prototype, {
  15. load: function ( url, onLoad, onProgress, onError ) {
  16. var scope = this;
  17. var loader = new THREE.FileLoader( scope.manager );
  18. loader.setPath( scope.path );
  19. loader.setResponseType( 'arraybuffer' );
  20. loader.load( url, function ( text ) {
  21. onLoad( scope.parse( text ) );
  22. }, onProgress, onError );
  23. },
  24. setPath: function ( value ) {
  25. this.path = value;
  26. return this;
  27. },
  28. parse: function ( data ) {
  29. function parseASCII( data ) {
  30. // connectivity of the triangles
  31. var indices = [];
  32. // triangles vertices
  33. var positions = [];
  34. // red, green, blue colors in the range 0 to 1
  35. var colors = [];
  36. // normal vector, one per vertex
  37. var normals = [];
  38. var result;
  39. // pattern for reading vertices, 3 floats or integers
  40. var pat3Floats = /(\-?\d+\.?[\d\-\+e]*)\s+(\-?\d+\.?[\d\-\+e]*)\s+(\-?\d+\.?[\d\-\+e]*)/g;
  41. // pattern for connectivity, an integer followed by any number of ints
  42. // the first integer is the number of polygon nodes
  43. var patConnectivity = /^(\d+)\s+([\s\d]*)/;
  44. // indicates start of vertex data section
  45. var patPOINTS = /^POINTS /;
  46. // indicates start of polygon connectivity section
  47. var patPOLYGONS = /^POLYGONS /;
  48. // indicates start of triangle strips section
  49. var patTRIANGLE_STRIPS = /^TRIANGLE_STRIPS /;
  50. // POINT_DATA number_of_values
  51. var patPOINT_DATA = /^POINT_DATA[ ]+(\d+)/;
  52. // CELL_DATA number_of_polys
  53. var patCELL_DATA = /^CELL_DATA[ ]+(\d+)/;
  54. // Start of color section
  55. var patCOLOR_SCALARS = /^COLOR_SCALARS[ ]+(\w+)[ ]+3/;
  56. // NORMALS Normals float
  57. var patNORMALS = /^NORMALS[ ]+(\w+)[ ]+(\w+)/;
  58. var inPointsSection = false;
  59. var inPolygonsSection = false;
  60. var inTriangleStripSection = false;
  61. var inPointDataSection = false;
  62. var inCellDataSection = false;
  63. var inColorSection = false;
  64. var inNormalsSection = false;
  65. var lines = data.split( '\n' );
  66. for ( var i in lines ) {
  67. var line = lines[ i ];
  68. if ( line.indexOf( 'DATASET' ) === 0 ) {
  69. var dataset = line.split( ' ' )[ 1 ];
  70. if ( dataset !== 'POLYDATA' ) throw new Error( 'Unsupported DATASET type: ' + dataset );
  71. } else if ( inPointsSection ) {
  72. // get the vertices
  73. while ( ( result = pat3Floats.exec( line ) ) !== null ) {
  74. var x = parseFloat( result[ 1 ] );
  75. var y = parseFloat( result[ 2 ] );
  76. var z = parseFloat( result[ 3 ] );
  77. positions.push( x, y, z );
  78. }
  79. } else if ( inPolygonsSection ) {
  80. if ( ( result = patConnectivity.exec( line ) ) !== null ) {
  81. // numVertices i0 i1 i2 ...
  82. var numVertices = parseInt( result[ 1 ] );
  83. var inds = result[ 2 ].split( /\s+/ );
  84. if ( numVertices >= 3 ) {
  85. var i0 = parseInt( inds[ 0 ] );
  86. var i1, i2;
  87. var k = 1;
  88. // split the polygon in numVertices - 2 triangles
  89. for ( var j = 0; j < numVertices - 2; ++ j ) {
  90. i1 = parseInt( inds[ k ] );
  91. i2 = parseInt( inds[ k + 1 ] );
  92. indices.push( i0, i1, i2 );
  93. k ++;
  94. }
  95. }
  96. }
  97. } else if ( inTriangleStripSection ) {
  98. if ( ( result = patConnectivity.exec( line ) ) !== null ) {
  99. // numVertices i0 i1 i2 ...
  100. var numVertices = parseInt( result[ 1 ] );
  101. var inds = result[ 2 ].split( /\s+/ );
  102. if ( numVertices >= 3 ) {
  103. var i0, i1, i2;
  104. // split the polygon in numVertices - 2 triangles
  105. for ( var j = 0; j < numVertices - 2; j ++ ) {
  106. if ( j % 2 === 1 ) {
  107. i0 = parseInt( inds[ j ] );
  108. i1 = parseInt( inds[ j + 2 ] );
  109. i2 = parseInt( inds[ j + 1 ] );
  110. indices.push( i0, i1, i2 );
  111. } else {
  112. i0 = parseInt( inds[ j ] );
  113. i1 = parseInt( inds[ j + 1 ] );
  114. i2 = parseInt( inds[ j + 2 ] );
  115. indices.push( i0, i1, i2 );
  116. }
  117. }
  118. }
  119. }
  120. } else if ( inPointDataSection || inCellDataSection ) {
  121. if ( inColorSection ) {
  122. // Get the colors
  123. while ( ( result = pat3Floats.exec( line ) ) !== null ) {
  124. var r = parseFloat( result[ 1 ] );
  125. var g = parseFloat( result[ 2 ] );
  126. var b = parseFloat( result[ 3 ] );
  127. colors.push( r, g, b );
  128. }
  129. } else if ( inNormalsSection ) {
  130. // Get the normal vectors
  131. while ( ( result = pat3Floats.exec( line ) ) !== null ) {
  132. var nx = parseFloat( result[ 1 ] );
  133. var ny = parseFloat( result[ 2 ] );
  134. var nz = parseFloat( result[ 3 ] );
  135. normals.push( nx, ny, nz );
  136. }
  137. }
  138. }
  139. if ( patPOLYGONS.exec( line ) !== null ) {
  140. inPolygonsSection = true;
  141. inPointsSection = false;
  142. inTriangleStripSection = false;
  143. } else if ( patPOINTS.exec( line ) !== null ) {
  144. inPolygonsSection = false;
  145. inPointsSection = true;
  146. inTriangleStripSection = false;
  147. } else if ( patTRIANGLE_STRIPS.exec( line ) !== null ) {
  148. inPolygonsSection = false;
  149. inPointsSection = false;
  150. inTriangleStripSection = true;
  151. } else if ( patPOINT_DATA.exec( line ) !== null ) {
  152. inPointDataSection = true;
  153. inPointsSection = false;
  154. inPolygonsSection = false;
  155. inTriangleStripSection = false;
  156. } else if ( patCELL_DATA.exec( line ) !== null ) {
  157. inCellDataSection = true;
  158. inPointsSection = false;
  159. inPolygonsSection = false;
  160. inTriangleStripSection = false;
  161. } else if ( patCOLOR_SCALARS.exec( line ) !== null ) {
  162. inColorSection = true;
  163. inNormalsSection = false;
  164. inPointsSection = false;
  165. inPolygonsSection = false;
  166. inTriangleStripSection = false;
  167. } else if ( patNORMALS.exec( line ) !== null ) {
  168. inNormalsSection = true;
  169. inColorSection = false;
  170. inPointsSection = false;
  171. inPolygonsSection = false;
  172. inTriangleStripSection = false;
  173. }
  174. }
  175. var geometry = new THREE.BufferGeometry();
  176. geometry.setIndex( indices );
  177. geometry.addAttribute( 'position', new THREE.Float32BufferAttribute( positions, 3 ) );
  178. if ( normals.length === positions.length ) {
  179. geometry.addAttribute( 'normal', new THREE.Float32BufferAttribute( normals, 3 ) );
  180. }
  181. if ( colors.length !== indices.length ) {
  182. // stagger
  183. if ( colors.length === positions.length ) {
  184. geometry.addAttribute( 'color', new THREE.Float32BufferAttribute( colors, 3 ) );
  185. }
  186. } else {
  187. // cell
  188. geometry = geometry.toNonIndexed();
  189. var numTriangles = geometry.attributes.position.count / 3;
  190. if ( colors.length === ( numTriangles * 3 ) ) {
  191. var newColors = [];
  192. for ( var i = 0; i < numTriangles; i ++ ) {
  193. var r = colors[ 3 * i + 0 ];
  194. var g = colors[ 3 * i + 1 ];
  195. var b = colors[ 3 * i + 2 ];
  196. newColors.push( r, g, b );
  197. newColors.push( r, g, b );
  198. newColors.push( r, g, b );
  199. }
  200. geometry.addAttribute( 'color', new THREE.Float32BufferAttribute( newColors, 3 ) );
  201. }
  202. }
  203. return geometry;
  204. }
  205. function parseBinary( data ) {
  206. var count, pointIndex, i, numberOfPoints, s;
  207. var buffer = new Uint8Array( data );
  208. var dataView = new DataView( data );
  209. // Points and normals, by default, are empty
  210. var points = [];
  211. var normals = [];
  212. var indices = [];
  213. // Going to make a big array of strings
  214. var vtk = [];
  215. var index = 0;
  216. function findString( buffer, start ) {
  217. var index = start;
  218. var c = buffer[ index ];
  219. var s = [];
  220. while ( c !== 10 ) {
  221. s.push( String.fromCharCode( c ) );
  222. index ++;
  223. c = buffer[ index ];
  224. }
  225. return { start: start,
  226. end: index,
  227. next: index + 1,
  228. parsedString: s.join( '' ) };
  229. }
  230. var state, line;
  231. while ( true ) {
  232. // Get a string
  233. state = findString( buffer, index );
  234. line = state.parsedString;
  235. if ( line.indexOf( 'DATASET' ) === 0 ) {
  236. var dataset = line.split( ' ' )[ 1 ];
  237. if ( dataset !== 'POLYDATA' ) throw new Error( 'Unsupported DATASET type: ' + dataset );
  238. } else if ( line.indexOf( 'POINTS' ) === 0 ) {
  239. vtk.push( line );
  240. // Add the points
  241. numberOfPoints = parseInt( line.split( ' ' )[ 1 ], 10 );
  242. // Each point is 3 4-byte floats
  243. count = numberOfPoints * 4 * 3;
  244. points = new Float32Array( numberOfPoints * 3 );
  245. pointIndex = state.next;
  246. for ( i = 0; i < numberOfPoints; i ++ ) {
  247. points[ 3 * i ] = dataView.getFloat32( pointIndex, false );
  248. points[ 3 * i + 1 ] = dataView.getFloat32( pointIndex + 4, false );
  249. points[ 3 * i + 2 ] = dataView.getFloat32( pointIndex + 8, false );
  250. pointIndex = pointIndex + 12;
  251. }
  252. // increment our next pointer
  253. state.next = state.next + count + 1;
  254. } else if ( line.indexOf( 'TRIANGLE_STRIPS' ) === 0 ) {
  255. var numberOfStrips = parseInt( line.split( ' ' )[ 1 ], 10 );
  256. var size = parseInt( line.split( ' ' )[ 2 ], 10 );
  257. // 4 byte integers
  258. count = size * 4;
  259. indices = new Uint32Array( 3 * size - 9 * numberOfStrips );
  260. var indicesIndex = 0;
  261. pointIndex = state.next;
  262. for ( i = 0; i < numberOfStrips; i ++ ) {
  263. // For each strip, read the first value, then record that many more points
  264. var indexCount = dataView.getInt32( pointIndex, false );
  265. var strip = [];
  266. pointIndex += 4;
  267. for ( s = 0; s < indexCount; s ++ ) {
  268. strip.push( dataView.getInt32( pointIndex, false ) );
  269. pointIndex += 4;
  270. }
  271. // retrieves the n-2 triangles from the triangle strip
  272. for ( var j = 0; j < indexCount - 2; j ++ ) {
  273. if ( j % 2 ) {
  274. indices[ indicesIndex ++ ] = strip[ j ];
  275. indices[ indicesIndex ++ ] = strip[ j + 2 ];
  276. indices[ indicesIndex ++ ] = strip[ j + 1 ];
  277. } else {
  278. indices[ indicesIndex ++ ] = strip[ j ];
  279. indices[ indicesIndex ++ ] = strip[ j + 1 ];
  280. indices[ indicesIndex ++ ] = strip[ j + 2 ];
  281. }
  282. }
  283. }
  284. // increment our next pointer
  285. state.next = state.next + count + 1;
  286. } else if ( line.indexOf( 'POLYGONS' ) === 0 ) {
  287. var numberOfStrips = parseInt( line.split( ' ' )[ 1 ], 10 );
  288. var size = parseInt( line.split( ' ' )[ 2 ], 10 );
  289. // 4 byte integers
  290. count = size * 4;
  291. indices = new Uint32Array( 3 * size - 9 * numberOfStrips );
  292. var indicesIndex = 0;
  293. pointIndex = state.next;
  294. for ( i = 0; i < numberOfStrips; i ++ ) {
  295. // For each strip, read the first value, then record that many more points
  296. var indexCount = dataView.getInt32( pointIndex, false );
  297. var strip = [];
  298. pointIndex += 4;
  299. for ( s = 0; s < indexCount; s ++ ) {
  300. strip.push( dataView.getInt32( pointIndex, false ) );
  301. pointIndex += 4;
  302. }
  303. // divide the polygon in n-2 triangle
  304. for ( var j = 1; j < indexCount - 1; j ++ ) {
  305. indices[ indicesIndex ++ ] = strip[ 0 ];
  306. indices[ indicesIndex ++ ] = strip[ j ];
  307. indices[ indicesIndex ++ ] = strip[ j + 1 ];
  308. }
  309. }
  310. // increment our next pointer
  311. state.next = state.next + count + 1;
  312. } else if ( line.indexOf( 'POINT_DATA' ) === 0 ) {
  313. numberOfPoints = parseInt( line.split( ' ' )[ 1 ], 10 );
  314. // Grab the next line
  315. state = findString( buffer, state.next );
  316. // Now grab the binary data
  317. count = numberOfPoints * 4 * 3;
  318. normals = new Float32Array( numberOfPoints * 3 );
  319. pointIndex = state.next;
  320. for ( i = 0; i < numberOfPoints; i ++ ) {
  321. normals[ 3 * i ] = dataView.getFloat32( pointIndex, false );
  322. normals[ 3 * i + 1 ] = dataView.getFloat32( pointIndex + 4, false );
  323. normals[ 3 * i + 2 ] = dataView.getFloat32( pointIndex + 8, false );
  324. pointIndex += 12;
  325. }
  326. // Increment past our data
  327. state.next = state.next + count;
  328. }
  329. // Increment index
  330. index = state.next;
  331. if ( index >= buffer.byteLength ) {
  332. break;
  333. }
  334. }
  335. var geometry = new THREE.BufferGeometry();
  336. geometry.setIndex( new THREE.BufferAttribute( indices, 1 ) );
  337. geometry.addAttribute( 'position', new THREE.BufferAttribute( points, 3 ) );
  338. if ( normals.length === points.length ) {
  339. geometry.addAttribute( 'normal', new THREE.BufferAttribute( normals, 3 ) );
  340. }
  341. return geometry;
  342. }
  343. function Float32Concat( first, second ) {
  344. var firstLength = first.length, result = new Float32Array( firstLength + second.length );
  345. result.set( first );
  346. result.set( second, firstLength );
  347. return result;
  348. }
  349. function Int32Concat( first, second ) {
  350. var firstLength = first.length, result = new Int32Array( firstLength + second.length );
  351. result.set( first );
  352. result.set( second, firstLength );
  353. return result;
  354. }
  355. function parseXML( stringFile ) {
  356. // Changes XML to JSON, based on https://davidwalsh.name/convert-xml-json
  357. function xmlToJson( xml ) {
  358. // Create the return object
  359. var obj = {};
  360. if ( xml.nodeType === 1 ) { // element
  361. // do attributes
  362. if ( xml.attributes ) {
  363. if ( xml.attributes.length > 0 ) {
  364. obj[ 'attributes' ] = {};
  365. for ( var j = 0; j < xml.attributes.length; j ++ ) {
  366. var attribute = xml.attributes.item( j );
  367. obj[ 'attributes' ][ attribute.nodeName ] = attribute.nodeValue.trim();
  368. }
  369. }
  370. }
  371. } else if ( xml.nodeType === 3 ) { // text
  372. obj = xml.nodeValue.trim();
  373. }
  374. // do children
  375. if ( xml.hasChildNodes() ) {
  376. for ( var i = 0; i < xml.childNodes.length; i ++ ) {
  377. var item = xml.childNodes.item( i );
  378. var nodeName = item.nodeName;
  379. if ( typeof obj[ nodeName ] === 'undefined' ) {
  380. var tmp = xmlToJson( item );
  381. if ( tmp !== '' ) obj[ nodeName ] = tmp;
  382. } else {
  383. if ( typeof obj[ nodeName ].push === 'undefined' ) {
  384. var old = obj[ nodeName ];
  385. obj[ nodeName ] = [ old ];
  386. }
  387. var tmp = xmlToJson( item );
  388. if ( tmp !== '' ) obj[ nodeName ].push( tmp );
  389. }
  390. }
  391. }
  392. return obj;
  393. }
  394. // Taken from Base64-js
  395. function Base64toByteArray( b64 ) {
  396. var Arr = typeof Uint8Array !== 'undefined' ? Uint8Array : Array;
  397. var i;
  398. var lookup = [];
  399. var revLookup = [];
  400. var code = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/';
  401. var len = code.length;
  402. for ( i = 0; i < len; i ++ ) {
  403. lookup[ i ] = code[ i ];
  404. }
  405. for ( i = 0; i < len; ++ i ) {
  406. revLookup[ code.charCodeAt( i ) ] = i;
  407. }
  408. revLookup[ '-'.charCodeAt( 0 ) ] = 62;
  409. revLookup[ '_'.charCodeAt( 0 ) ] = 63;
  410. var j, l, tmp, placeHolders, arr;
  411. var len = b64.length;
  412. if ( len % 4 > 0 ) {
  413. throw new Error( 'Invalid string. Length must be a multiple of 4' );
  414. }
  415. placeHolders = b64[ len - 2 ] === '=' ? 2 : b64[ len - 1 ] === '=' ? 1 : 0;
  416. arr = new Arr( len * 3 / 4 - placeHolders );
  417. l = placeHolders > 0 ? len - 4 : len;
  418. var L = 0;
  419. for ( i = 0, j = 0; i < l; i += 4, j += 3 ) {
  420. tmp = ( revLookup[ b64.charCodeAt( i ) ] << 18 ) | ( revLookup[ b64.charCodeAt( i + 1 ) ] << 12 ) | ( revLookup[ b64.charCodeAt( i + 2 ) ] << 6 ) | revLookup[ b64.charCodeAt( i + 3 ) ];
  421. arr[ L ++ ] = ( tmp & 0xFF0000 ) >> 16;
  422. arr[ L ++ ] = ( tmp & 0xFF00 ) >> 8;
  423. arr[ L ++ ] = tmp & 0xFF;
  424. }
  425. if ( placeHolders === 2 ) {
  426. tmp = ( revLookup[ b64.charCodeAt( i ) ] << 2 ) | ( revLookup[ b64.charCodeAt( i + 1 ) ] >> 4 );
  427. arr[ L ++ ] = tmp & 0xFF;
  428. } else if ( placeHolders === 1 ) {
  429. tmp = ( revLookup[ b64.charCodeAt( i ) ] << 10 ) | ( revLookup[ b64.charCodeAt( i + 1 ) ] << 4 ) | ( revLookup[ b64.charCodeAt( i + 2 ) ] >> 2 );
  430. arr[ L ++ ] = ( tmp >> 8 ) & 0xFF;
  431. arr[ L ++ ] = tmp & 0xFF;
  432. }
  433. return arr;
  434. }
  435. function parseDataArray( ele, compressed ) {
  436. var numBytes = 0;
  437. if ( json.attributes.header_type === 'UInt64' ) {
  438. numBytes = 8;
  439. } else if ( json.attributes.header_type === 'UInt32' ) {
  440. numBytes = 4;
  441. }
  442. // Check the format
  443. if ( ele.attributes.format === 'binary' && compressed ) {
  444. var rawData, content, byteData, blocks, cSizeStart, headerSize, padding, dataOffsets, currentOffset;
  445. if ( ele.attributes.type === 'Float32' ) {
  446. var txt = new Float32Array( );
  447. } else if ( ele.attributes.type === 'Int64' ) {
  448. var txt = new Int32Array( );
  449. }
  450. // VTP data with the header has the following structure:
  451. // [#blocks][#u-size][#p-size][#c-size-1][#c-size-2]...[#c-size-#blocks][DATA]
  452. //
  453. // Each token is an integer value whose type is specified by "header_type" at the top of the file (UInt32 if no type specified). The token meanings are:
  454. // [#blocks] = Number of blocks
  455. // [#u-size] = Block size before compression
  456. // [#p-size] = Size of last partial block (zero if it not needed)
  457. // [#c-size-i] = Size in bytes of block i after compression
  458. //
  459. // The [DATA] portion stores contiguously every block appended together. The offset from the beginning of the data section to the beginning of a block is
  460. // computed by summing the compressed block sizes from preceding blocks according to the header.
  461. rawData = ele[ '#text' ];
  462. byteData = Base64toByteArray( rawData );
  463. blocks = byteData[ 0 ];
  464. for ( var i = 1; i < numBytes - 1; i ++ ) {
  465. blocks = blocks | ( byteData[ i ] << ( i * numBytes ) );
  466. }
  467. headerSize = ( blocks + 3 ) * numBytes;
  468. padding = ( ( headerSize % 3 ) > 0 ) ? 3 - ( headerSize % 3 ) : 0;
  469. headerSize = headerSize + padding;
  470. dataOffsets = [];
  471. currentOffset = headerSize;
  472. dataOffsets.push( currentOffset );
  473. // Get the blocks sizes after the compression.
  474. // There are three blocks before c-size-i, so we skip 3*numBytes
  475. cSizeStart = 3 * numBytes;
  476. for ( var i = 0; i < blocks; i ++ ) {
  477. var currentBlockSize = byteData[ i * numBytes + cSizeStart ];
  478. for ( var j = 1; j < numBytes - 1; j ++ ) {
  479. // Each data point consists of 8 bytes regardless of the header type
  480. currentBlockSize = currentBlockSize | ( byteData[ i * numBytes + cSizeStart + j ] << ( j * 8 ) );
  481. }
  482. currentOffset = currentOffset + currentBlockSize;
  483. dataOffsets.push( currentOffset );
  484. }
  485. for ( var i = 0; i < dataOffsets.length - 1; i ++ ) {
  486. var inflate = new Zlib.Inflate( byteData.slice( dataOffsets[ i ], dataOffsets[ i + 1 ] ), { resize: true, verify: true } ); // eslint-disable-line no-undef
  487. content = inflate.decompress();
  488. content = content.buffer;
  489. if ( ele.attributes.type === 'Float32' ) {
  490. content = new Float32Array( content );
  491. txt = Float32Concat( txt, content );
  492. } else if ( ele.attributes.type === 'Int64' ) {
  493. content = new Int32Array( content );
  494. txt = Int32Concat( txt, content );
  495. }
  496. }
  497. delete ele[ '#text' ];
  498. if ( ele.attributes.type === 'Int64' ) {
  499. if ( ele.attributes.format === 'binary' ) {
  500. txt = txt.filter( function ( el, idx ) {
  501. if ( idx % 2 !== 1 ) return true;
  502. } );
  503. }
  504. }
  505. } else {
  506. if ( ele.attributes.format === 'binary' && ! compressed ) {
  507. var content = Base64toByteArray( ele[ '#text' ] );
  508. // VTP data for the uncompressed case has the following structure:
  509. // [#bytes][DATA]
  510. // where "[#bytes]" is an integer value specifying the number of bytes in the block of data following it.
  511. content = content.slice( numBytes ).buffer;
  512. } else {
  513. if ( ele[ '#text' ] ) {
  514. var content = ele[ '#text' ].split( /\s+/ ).filter( function ( el ) {
  515. if ( el !== '' ) return el;
  516. } );
  517. } else {
  518. var content = new Int32Array( 0 ).buffer;
  519. }
  520. }
  521. delete ele[ '#text' ];
  522. // Get the content and optimize it
  523. if ( ele.attributes.type === 'Float32' ) {
  524. var txt = new Float32Array( content );
  525. } else if ( ele.attributes.type === 'Int32' ) {
  526. var txt = new Int32Array( content );
  527. } else if ( ele.attributes.type === 'Int64' ) {
  528. var txt = new Int32Array( content );
  529. if ( ele.attributes.format === 'binary' ) {
  530. txt = txt.filter( function ( el, idx ) {
  531. if ( idx % 2 !== 1 ) return true;
  532. } );
  533. }
  534. }
  535. } // endif ( ele.attributes.format === 'binary' && compressed )
  536. return txt;
  537. }
  538. // Main part
  539. // Get Dom
  540. var dom = null;
  541. if ( window.DOMParser ) {
  542. try {
  543. dom = ( new DOMParser() ).parseFromString( stringFile, 'text/xml' );
  544. } catch ( e ) {
  545. dom = null;
  546. }
  547. } else if ( window.ActiveXObject ) {
  548. try {
  549. dom = new ActiveXObject( 'Microsoft.XMLDOM' ); // eslint-disable-line no-undef
  550. dom.async = false;
  551. if ( ! dom.loadXML( /* xml */ ) ) {
  552. throw new Error( dom.parseError.reason + dom.parseError.srcText );
  553. }
  554. } catch ( e ) {
  555. dom = null;
  556. }
  557. } else {
  558. throw new Error( 'Cannot parse xml string!' );
  559. }
  560. // Get the doc
  561. var doc = dom.documentElement;
  562. // Convert to json
  563. var json = xmlToJson( doc );
  564. var points = [];
  565. var normals = [];
  566. var indices = [];
  567. if ( json.PolyData ) {
  568. var piece = json.PolyData.Piece;
  569. var compressed = json.attributes.hasOwnProperty( 'compressor' );
  570. // Can be optimized
  571. // Loop through the sections
  572. var sections = [ 'PointData', 'Points', 'Strips', 'Polys' ];// +['CellData', 'Verts', 'Lines'];
  573. var sectionIndex = 0, numberOfSections = sections.length;
  574. while ( sectionIndex < numberOfSections ) {
  575. var section = piece[ sections[ sectionIndex ] ];
  576. // If it has a DataArray in it
  577. if ( section && section.DataArray ) {
  578. // Depending on the number of DataArrays
  579. if ( Object.prototype.toString.call( section.DataArray ) === '[object Array]' ) {
  580. var arr = section.DataArray;
  581. } else {
  582. var arr = [ section.DataArray ];
  583. }
  584. var dataArrayIndex = 0, numberOfDataArrays = arr.length;
  585. while ( dataArrayIndex < numberOfDataArrays ) {
  586. // Parse the DataArray
  587. if ( ( '#text' in arr[ dataArrayIndex ] ) && ( arr[ dataArrayIndex ][ '#text' ].length > 0 ) ) {
  588. arr[ dataArrayIndex ].text = parseDataArray( arr[ dataArrayIndex ], compressed );
  589. }
  590. dataArrayIndex ++;
  591. }
  592. switch ( sections[ sectionIndex ] ) {
  593. // if iti is point data
  594. case 'PointData':
  595. var numberOfPoints = parseInt( piece.attributes.NumberOfPoints );
  596. var normalsName = section.attributes.Normals;
  597. if ( numberOfPoints > 0 ) {
  598. for ( var i = 0, len = arr.length; i < len; i ++ ) {
  599. if ( normalsName === arr[ i ].attributes.Name ) {
  600. var components = arr[ i ].attributes.NumberOfComponents;
  601. normals = new Float32Array( numberOfPoints * components );
  602. normals.set( arr[ i ].text, 0 );
  603. }
  604. }
  605. }
  606. break;
  607. // if it is points
  608. case 'Points':
  609. var numberOfPoints = parseInt( piece.attributes.NumberOfPoints );
  610. if ( numberOfPoints > 0 ) {
  611. var components = section.DataArray.attributes.NumberOfComponents;
  612. points = new Float32Array( numberOfPoints * components );
  613. points.set( section.DataArray.text, 0 );
  614. }
  615. break;
  616. // if it is strips
  617. case 'Strips':
  618. var numberOfStrips = parseInt( piece.attributes.NumberOfStrips );
  619. if ( numberOfStrips > 0 ) {
  620. var connectivity = new Int32Array( section.DataArray[ 0 ].text.length );
  621. var offset = new Int32Array( section.DataArray[ 1 ].text.length );
  622. connectivity.set( section.DataArray[ 0 ].text, 0 );
  623. offset.set( section.DataArray[ 1 ].text, 0 );
  624. var size = numberOfStrips + connectivity.length;
  625. indices = new Uint32Array( 3 * size - 9 * numberOfStrips );
  626. var indicesIndex = 0;
  627. for ( var i = 0, len = numberOfStrips; i < len; i ++ ) {
  628. var strip = [];
  629. for ( var s = 0, len1 = offset[ i ], len0 = 0; s < len1 - len0; s ++ ) {
  630. strip.push( connectivity[ s ] );
  631. if ( i > 0 ) len0 = offset[ i - 1 ];
  632. }
  633. for ( var j = 0, len1 = offset[ i ], len0 = 0; j < len1 - len0 - 2; j ++ ) {
  634. if ( j % 2 ) {
  635. indices[ indicesIndex ++ ] = strip[ j ];
  636. indices[ indicesIndex ++ ] = strip[ j + 2 ];
  637. indices[ indicesIndex ++ ] = strip[ j + 1 ];
  638. } else {
  639. indices[ indicesIndex ++ ] = strip[ j ];
  640. indices[ indicesIndex ++ ] = strip[ j + 1 ];
  641. indices[ indicesIndex ++ ] = strip[ j + 2 ];
  642. }
  643. if ( i > 0 ) len0 = offset[ i - 1 ];
  644. }
  645. }
  646. }
  647. break;
  648. // if it is polys
  649. case 'Polys':
  650. var numberOfPolys = parseInt( piece.attributes.NumberOfPolys );
  651. if ( numberOfPolys > 0 ) {
  652. var connectivity = new Int32Array( section.DataArray[ 0 ].text.length );
  653. var offset = new Int32Array( section.DataArray[ 1 ].text.length );
  654. connectivity.set( section.DataArray[ 0 ].text, 0 );
  655. offset.set( section.DataArray[ 1 ].text, 0 );
  656. var size = numberOfPolys + connectivity.length;
  657. indices = new Uint32Array( 3 * size - 9 * numberOfPolys );
  658. var indicesIndex = 0, connectivityIndex = 0;
  659. var i = 0, len = numberOfPolys, len0 = 0;
  660. while ( i < len ) {
  661. var poly = [];
  662. var s = 0, len1 = offset[ i ];
  663. while ( s < len1 - len0 ) {
  664. poly.push( connectivity[ connectivityIndex ++ ] );
  665. s ++;
  666. }
  667. var j = 1;
  668. while ( j < len1 - len0 - 1 ) {
  669. indices[ indicesIndex ++ ] = poly[ 0 ];
  670. indices[ indicesIndex ++ ] = poly[ j ];
  671. indices[ indicesIndex ++ ] = poly[ j + 1 ];
  672. j ++;
  673. }
  674. i ++;
  675. len0 = offset[ i - 1 ];
  676. }
  677. }
  678. break;
  679. default:
  680. break;
  681. }
  682. }
  683. sectionIndex ++;
  684. }
  685. var geometry = new THREE.BufferGeometry();
  686. geometry.setIndex( new THREE.BufferAttribute( indices, 1 ) );
  687. geometry.addAttribute( 'position', new THREE.BufferAttribute( points, 3 ) );
  688. if ( normals.length === points.length ) {
  689. geometry.addAttribute( 'normal', new THREE.BufferAttribute( normals, 3 ) );
  690. }
  691. return geometry;
  692. } else {
  693. throw new Error( 'Unsupported DATASET type' );
  694. }
  695. }
  696. function getStringFile( data ) {
  697. var stringFile = '';
  698. var charArray = new Uint8Array( data );
  699. var i = 0;
  700. var len = charArray.length;
  701. while ( len -- ) {
  702. stringFile += String.fromCharCode( charArray[ i ++ ] );
  703. }
  704. return stringFile;
  705. }
  706. // get the 5 first lines of the files to check if there is the key word binary
  707. var meta = THREE.LoaderUtils.decodeText( new Uint8Array( data, 0, 250 ) ).split( '\n' );
  708. if ( meta[ 0 ].indexOf( 'xml' ) !== - 1 ) {
  709. return parseXML( getStringFile( data ) );
  710. } else if ( meta[ 2 ].includes( 'ASCII' ) ) {
  711. return parseASCII( getStringFile( data ) );
  712. } else {
  713. return parseBinary( data );
  714. }
  715. }
  716. } );