VTKLoader.js 28 KB

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