VTKLoader.js 27 KB

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