VTKLoader.js 27 KB

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