VTKLoader.js 28 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142
  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. var firstLength = first.length,
  356. result = new Float32Array(firstLength + second.length);
  357. result.set(first);
  358. result.set(second, firstLength);
  359. return result;
  360. }
  361. function Int32Concat(first, second) {
  362. var firstLength = first.length,
  363. result = new Int32Array(firstLength + second.length);
  364. result.set(first);
  365. result.set(second, firstLength);
  366. return result;
  367. }
  368. function parseXML( stringFile ) {
  369. // Changes XML to JSON, based on https://davidwalsh.name/convert-xml-json
  370. function xmlToJson( xml ) {
  371. // Create the return object
  372. var obj = {};
  373. if ( xml.nodeType == 1 ) { // element
  374. // do attributes
  375. if ( xml.attributes ) {
  376. if ( xml.attributes.length > 0 ) {
  377. obj[ 'attributes' ] = {};
  378. for ( var j = 0; j < xml.attributes.length; j ++ ) {
  379. var attribute = xml.attributes.item( j );
  380. obj[ 'attributes' ][ attribute.nodeName ] = attribute.nodeValue.trim();
  381. }
  382. }
  383. }
  384. } else if ( xml.nodeType == 3 ) { // text
  385. obj = xml.nodeValue.trim();
  386. }
  387. // do children
  388. if ( xml.hasChildNodes() ) {
  389. for ( var i = 0; i < xml.childNodes.length; i ++ ) {
  390. var item = xml.childNodes.item( i );
  391. var nodeName = item.nodeName;
  392. if ( typeof( obj[ nodeName ] ) === 'undefined' ) {
  393. var tmp = xmlToJson( item );
  394. if ( tmp !== '' ) obj[ nodeName ] = tmp;
  395. } else {
  396. if ( typeof( obj[ nodeName ].push ) === 'undefined' ) {
  397. var old = obj[ nodeName ];
  398. obj[ nodeName ] = [ old ];
  399. }
  400. var tmp = xmlToJson( item );
  401. if ( tmp !== '' ) obj[ nodeName ].push( tmp );
  402. }
  403. }
  404. }
  405. return obj;
  406. }
  407. // Taken from Base64-js
  408. function Base64toByteArray( b64 ) {
  409. var Arr = typeof Uint8Array !== 'undefined' ? Uint8Array : Array;
  410. var i;
  411. var lookup = [];
  412. var revLookup = [];
  413. var code = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/';
  414. var len = code.length;
  415. for ( i = 0; i < len; i ++ ) {
  416. lookup[ i ] = code[ i ];
  417. }
  418. for ( i = 0; i < len; ++ i ) {
  419. revLookup[ code.charCodeAt( i ) ] = i;
  420. }
  421. revLookup[ '-'.charCodeAt( 0 ) ] = 62;
  422. revLookup[ '_'.charCodeAt( 0 ) ] = 63;
  423. var j, l, tmp, placeHolders, arr;
  424. var len = b64.length;
  425. if ( len % 4 > 0 ) {
  426. throw new Error( 'Invalid string. Length must be a multiple of 4' );
  427. }
  428. placeHolders = b64[ len - 2 ] === '=' ? 2 : b64[ len - 1 ] === '=' ? 1 : 0;
  429. arr = new Arr( len * 3 / 4 - placeHolders );
  430. l = placeHolders > 0 ? len - 4 : len;
  431. var L = 0;
  432. for ( i = 0, j = 0; i < l; i += 4, j += 3 ) {
  433. tmp = ( revLookup[ b64.charCodeAt( i ) ] << 18 ) | ( revLookup[ b64.charCodeAt( i + 1 ) ] << 12 ) | ( revLookup[ b64.charCodeAt( i + 2 ) ] << 6 ) | revLookup[ b64.charCodeAt( i + 3 ) ];
  434. arr[ L ++ ] = ( tmp & 0xFF0000 ) >> 16;
  435. arr[ L ++ ] = ( tmp & 0xFF00 ) >> 8;
  436. arr[ L ++ ] = tmp & 0xFF;
  437. }
  438. if ( placeHolders === 2 ) {
  439. tmp = ( revLookup[ b64.charCodeAt( i ) ] << 2 ) | ( revLookup[ b64.charCodeAt( i + 1 ) ] >> 4 );
  440. arr[ L ++ ] = tmp & 0xFF;
  441. } else if ( placeHolders === 1 ) {
  442. tmp = ( revLookup[ b64.charCodeAt( i ) ] << 10 ) | ( revLookup[ b64.charCodeAt( i + 1 ) ] << 4 ) | ( revLookup[ b64.charCodeAt( i + 2 ) ] >> 2 );
  443. arr[ L ++ ] = ( tmp >> 8 ) & 0xFF;
  444. arr[ L ++ ] = tmp & 0xFF;
  445. }
  446. return arr;
  447. }
  448. function parseDataArray( ele, compressed ) {
  449. var numBytes = 0;
  450. if ( json.attributes.header_type == 'UInt64' )
  451. numBytes = 8;
  452. else if( json.attributes.header_type == 'UInt32' )
  453. numBytes = 4;
  454. // Check the format
  455. if ( ele.attributes.format == 'binary' && compressed ) {
  456. var rawData, content, byteData, blocks, cSizeStart, headerSize, padding, dataOffsets, currentOffset;
  457. if ( ele.attributes.type == 'Float32' ) {
  458. var txt = new Float32Array( );
  459. } else if ( ele.attributes.type === 'Int64' ) {
  460. var txt = new Int32Array( );
  461. }
  462. // VTP data with the header has the following structure:
  463. // [#blocks][#u-size][#p-size][#c-size-1][#c-size-2]...[#c-size-#blocks][DATA]
  464. //
  465. // 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:
  466. // [#blocks] = Number of blocks
  467. // [#u-size] = Block size before compression
  468. // [#p-size] = Size of last partial block (zero if it not needed)
  469. // [#c-size-i] = Size in bytes of block i after compression
  470. //
  471. // 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
  472. // computed by summing the compressed block sizes from preceding blocks according to the header.
  473. rawData = ele[ '#text' ];
  474. byteData = Base64toByteArray( rawData );
  475. blocks = byteData[0]
  476. for ( var i = 1; i<numBytes-1; i++ ) {
  477. blocks = blocks | ( byteData[i] << (i*numBytes) );
  478. }
  479. headerSize = (blocks + 3) * numBytes;
  480. padding = ( (headerSize % 3) > 0 ) ? 3 - (headerSize % 3) : 0;
  481. headerSize = headerSize + padding;
  482. dataOffsets = [];
  483. currentOffset = headerSize;
  484. dataOffsets.push( currentOffset );
  485. // Get the blocks sizes after the compression.
  486. // There are three blocks before c-size-i, so we skip 3*numBytes
  487. cSizeStart = 3*numBytes;
  488. for ( var i = 0; i<blocks; i++ ) {
  489. var currentBlockSize = byteData[i*numBytes + cSizeStart];
  490. for ( var j = 1; j<numBytes-1; j++ ) {
  491. // Each data point consists of 8 bytes regardless of the header type
  492. currentBlockSize = currentBlockSize | ( byteData[i*numBytes + cSizeStart + j] << (j*8) );
  493. }
  494. currentOffset = currentOffset + currentBlockSize;
  495. dataOffsets.push( currentOffset );
  496. }
  497. for ( var i=0; i<dataOffsets.length-1; i++ ) {
  498. var inflate = new Zlib.Inflate( byteData.slice( dataOffsets[i], dataOffsets[i+1] ), { resize: true, verify: true } );
  499. content = inflate.decompress();
  500. content = content.buffer;
  501. if ( ele.attributes.type == 'Float32' ) {
  502. content = new Float32Array( content );
  503. txt = Float32Concat(txt, content);
  504. } else if ( ele.attributes.type === 'Int64' ) {
  505. content = new Int32Array( content );
  506. txt = Int32Concat(txt, content);
  507. }
  508. }
  509. delete ele[ '#text' ];
  510. // Get the content and optimize it
  511. if ( ele.attributes.type == 'Float32' ) {
  512. if ( ele.attributes.format == 'binary' ) {
  513. if ( ! compressed ) {
  514. txt = txt.filter( function( el, idx, arr ) {
  515. if ( idx !== 0 ) return true;
  516. } );
  517. }
  518. }
  519. } else if ( ele.attributes.type === 'Int64' ) {
  520. if ( ele.attributes.format == 'binary' ) {
  521. if ( ! compressed ) {
  522. txt = txt.filter( function ( el, idx, arr ) {
  523. if ( idx !== 0 ) return true;
  524. } );
  525. }
  526. txt = txt.filter( function ( el, idx, arr ) {
  527. if ( idx % 2 !== 1 ) return true;
  528. } );
  529. }
  530. }
  531. } else {
  532. if ( ele.attributes.format == 'binary' && ! compressed ) {
  533. var content = Base64toByteArray( ele[ '#text' ] );
  534. // VTP data for the uncompressed case has the following structure:
  535. // [#bytes][DATA]
  536. // where "[#bytes]" is an integer value specifying the number of bytes in the block of data following it.
  537. content = content.slice(numBytes).buffer;
  538. } else {
  539. if ( ele[ '#text' ] ) {
  540. var content = ele[ '#text' ].replace( /\n/g, ' ' ).split( ' ' ).filter( function ( el, idx, arr ) {
  541. if ( el !== '' ) return el;
  542. } );
  543. } else {
  544. var content = new Int32Array( 0 ).buffer;
  545. }
  546. }
  547. delete ele[ '#text' ];
  548. // Get the content and optimize it
  549. if ( ele.attributes.type == 'Float32' ) {
  550. var txt = new Float32Array( content );
  551. } else if ( ele.attributes.type === 'Int64' ) {
  552. var txt = new Int32Array( content );
  553. if ( ele.attributes.format == 'binary' ) {
  554. txt = txt.filter( function ( el, idx, arr ) {
  555. if ( idx % 2 !== 1 ) return true;
  556. } );
  557. }
  558. }
  559. } // endif ( ele.attributes.format == 'binary' && compressed )
  560. return txt;
  561. }
  562. // Main part
  563. // Get Dom
  564. var dom = null;
  565. if ( window.DOMParser ) {
  566. try {
  567. dom = ( new DOMParser() ).parseFromString( stringFile, 'text/xml' );
  568. } catch ( e ) {
  569. dom = null;
  570. }
  571. } else if ( window.ActiveXObject ) {
  572. try {
  573. dom = new ActiveXObject( 'Microsoft.XMLDOM' );
  574. dom.async = false;
  575. if ( ! dom.loadXML( xml ) ) {
  576. throw new Error( dom.parseError.reason + dom.parseError.srcText );
  577. }
  578. } catch ( e ) {
  579. dom = null;
  580. }
  581. } else {
  582. throw new Error( 'Cannot parse xml string!' );
  583. }
  584. // Get the doc
  585. var doc = dom.documentElement;
  586. // Convert to json
  587. var json = xmlToJson( doc );
  588. var points = [];
  589. var normals = [];
  590. var indices = [];
  591. if ( json.PolyData ) {
  592. var piece = json.PolyData.Piece;
  593. var compressed = json.attributes.hasOwnProperty( 'compressor' );
  594. // Can be optimized
  595. // Loop through the sections
  596. var sections = [ 'PointData', 'Points', 'Strips', 'Polys' ];// +['CellData', 'Verts', 'Lines'];
  597. var sectionIndex = 0, numberOfSections = sections.length;
  598. while ( sectionIndex < numberOfSections ) {
  599. var section = piece[ sections[ sectionIndex ] ];
  600. // If it has a DataArray in it
  601. if ( section.DataArray ) {
  602. // Depending on the number of DataArrays
  603. if ( Object.prototype.toString.call( section.DataArray ) === '[object Array]' ) {
  604. var arr = section.DataArray;
  605. } else {
  606. var arr = [ section.DataArray ];
  607. }
  608. var dataArrayIndex = 0, numberOfDataArrays = arr.length;
  609. while ( dataArrayIndex < numberOfDataArrays ) {
  610. // Parse the DataArray
  611. if ( ('#text' in arr[ dataArrayIndex ]) && (arr[ dataArrayIndex ][ '#text' ].length > 0) ) {
  612. arr[ dataArrayIndex ].text = parseDataArray( arr[ dataArrayIndex ], compressed );
  613. }
  614. dataArrayIndex ++;
  615. }
  616. switch ( sections[ sectionIndex ] ) {
  617. // if iti is point data
  618. case 'PointData':
  619. var numberOfPoints = parseInt( piece.attributes.NumberOfPoints );
  620. var normalsName = section.attributes.Normals;
  621. if ( numberOfPoints > 0 ) {
  622. for ( var i = 0, len = arr.length; i < len; i ++ ) {
  623. if ( normalsName == arr[ i ].attributes.Name ) {
  624. var components = arr[ i ].attributes.NumberOfComponents;
  625. normals = new Float32Array( numberOfPoints * components );
  626. normals.set( arr[ i ].text, 0 );
  627. }
  628. }
  629. }
  630. break;
  631. // if it is points
  632. case 'Points':
  633. var numberOfPoints = parseInt( piece.attributes.NumberOfPoints );
  634. if ( numberOfPoints > 0 ) {
  635. var components = section.DataArray.attributes.NumberOfComponents;
  636. points = new Float32Array( numberOfPoints * components );
  637. points.set( section.DataArray.text, 0 );
  638. }
  639. break;
  640. // if it is strips
  641. case 'Strips':
  642. var numberOfStrips = parseInt( piece.attributes.NumberOfStrips );
  643. if ( numberOfStrips > 0 ) {
  644. var connectivity = new Int32Array( section.DataArray[ 0 ].text.length );
  645. var offset = new Int32Array( section.DataArray[ 1 ].text.length );
  646. connectivity.set( section.DataArray[ 0 ].text, 0 );
  647. offset.set( section.DataArray[ 1 ].text, 0 );
  648. var size = numberOfStrips + connectivity.length;
  649. indices = new Uint32Array( 3 * size - 9 * numberOfStrips );
  650. var indicesIndex = 0;
  651. for ( var i = 0,len = numberOfStrips; i < len; i ++ ) {
  652. var strip = [];
  653. for ( var s = 0, len1 = offset[ i ], len0 = 0; s < len1 - len0; s ++ ) {
  654. strip.push ( connectivity[ s ] );
  655. if ( i > 0 ) len0 = offset[ i - 1 ];
  656. }
  657. for ( var j = 0, len1 = offset[ i ], len0 = 0; j < len1 - len0 - 2; j ++ ) {
  658. if ( j % 2 ) {
  659. indices[ indicesIndex ++ ] = strip[ j ];
  660. indices[ indicesIndex ++ ] = strip[ j + 2 ];
  661. indices[ indicesIndex ++ ] = strip[ j + 1 ];
  662. } else {
  663. indices[ indicesIndex ++ ] = strip[ j ];
  664. indices[ indicesIndex ++ ] = strip[ j + 1 ];
  665. indices[ indicesIndex ++ ] = strip[ j + 2 ];
  666. }
  667. if ( i > 0 ) len0 = offset[ i - 1 ];
  668. }
  669. }
  670. }
  671. break;
  672. // if it is polys
  673. case 'Polys':
  674. var numberOfPolys = parseInt( piece.attributes.NumberOfPolys );
  675. if ( numberOfPolys > 0 ) {
  676. var connectivity = new Int32Array( section.DataArray[ 0 ].text.length );
  677. var offset = new Int32Array( section.DataArray[ 1 ].text.length );
  678. connectivity.set( section.DataArray[ 0 ].text, 0 );
  679. offset.set( section.DataArray[ 1 ].text, 0 );
  680. var size = numberOfPolys + connectivity.length;
  681. indices = new Uint32Array( 3 * size - 9 * numberOfPolys );
  682. var indicesIndex = 0, connectivityIndex = 0;
  683. var i = 0,len = numberOfPolys, len0 = 0;
  684. while ( i < len ) {
  685. var poly = [];
  686. var s = 0, len1 = offset[ i ];
  687. while ( s < len1 - len0 ) {
  688. poly.push( connectivity[ connectivityIndex ++ ] );
  689. s ++;
  690. }
  691. var j = 1;
  692. while ( j < len1 - len0 - 1 ) {
  693. indices[ indicesIndex ++ ] = poly[ 0 ];
  694. indices[ indicesIndex ++ ] = poly[ j ];
  695. indices[ indicesIndex ++ ] = poly[ j + 1 ];
  696. j ++;
  697. }
  698. i ++;
  699. len0 = offset[ i - 1 ];
  700. }
  701. }
  702. break;
  703. default:
  704. break;
  705. }
  706. }
  707. sectionIndex ++;
  708. }
  709. var geometry = new THREE.BufferGeometry();
  710. geometry.setIndex( new THREE.BufferAttribute( indices, 1 ) );
  711. geometry.addAttribute( 'position', new THREE.BufferAttribute( points, 3 ) );
  712. if ( normals.length == points.length ) {
  713. geometry.addAttribute( 'normal', new THREE.BufferAttribute( normals, 3 ) );
  714. }
  715. return geometry;
  716. } else {
  717. // TODO for vtu,vti,and other xml formats
  718. }
  719. }
  720. function getStringFile( data ) {
  721. var stringFile = '';
  722. var charArray = new Uint8Array( data );
  723. var i = 0;
  724. var len = charArray.length;
  725. while ( len -- ) {
  726. stringFile += String.fromCharCode( charArray[ i ++ ] );
  727. }
  728. return stringFile;
  729. }
  730. // get the 5 first lines of the files to check if there is the key word binary
  731. var meta = String.fromCharCode.apply( null, new Uint8Array( data, 0, 250 ) ).split( '\n' );
  732. if ( meta[ 0 ].indexOf( 'xml' ) !== - 1 ) {
  733. return parseXML( getStringFile( data ) );
  734. } else if ( meta[ 2 ].includes( 'ASCII' ) ) {
  735. return parseASCII( getStringFile( data ) );
  736. } else {
  737. return parseBinary( data );
  738. }
  739. }
  740. } );