VTKLoader.js 27 KB

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