VTKLoader.js 27 KB

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