VTKLoader.js 27 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093
  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 === '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 rawData = ele[ '#text' ];
  428. const byteData = Base64toByteArray( rawData );
  429. let blocks = byteData[ 0 ];
  430. for ( let i = 1; i < numBytes - 1; i ++ ) {
  431. blocks = blocks | byteData[ i ] << i * numBytes;
  432. }
  433. let headerSize = ( blocks + 3 ) * numBytes;
  434. const padding = headerSize % 3 > 0 ? 3 - headerSize % 3 : 0;
  435. headerSize = headerSize + padding;
  436. const dataOffsets = [];
  437. let currentOffset = headerSize;
  438. dataOffsets.push( currentOffset ); // Get the blocks sizes after the compression.
  439. // There are three blocks before c-size-i, so we skip 3*numBytes
  440. const cSizeStart = 3 * numBytes;
  441. for ( let i = 0; i < blocks; i ++ ) {
  442. let currentBlockSize = byteData[ i * numBytes + cSizeStart ];
  443. for ( let j = 1; j < numBytes - 1; j ++ ) {
  444. // Each data point consists of 8 bytes regardless of the header type
  445. currentBlockSize = currentBlockSize | byteData[ i * numBytes + cSizeStart + j ] << j * 8;
  446. }
  447. currentOffset = currentOffset + currentBlockSize;
  448. dataOffsets.push( currentOffset );
  449. }
  450. for ( let i = 0; i < dataOffsets.length - 1; i ++ ) {
  451. const data = fflate.unzlibSync( byteData.slice( dataOffsets[ i ], dataOffsets[ i + 1 ] ) ); // eslint-disable-line no-undef
  452. content = data.buffer;
  453. if ( ele.attributes.type === 'Float32' ) {
  454. content = new Float32Array( content );
  455. txt = Float32Concat( txt, content );
  456. } else if ( ele.attributes.type === 'Int64' ) {
  457. content = new Int32Array( content );
  458. txt = Int32Concat( txt, content );
  459. }
  460. }
  461. delete ele[ '#text' ];
  462. if ( ele.attributes.type === 'Int64' ) {
  463. if ( ele.attributes.format === 'binary' ) {
  464. txt = txt.filter( function ( el, idx ) {
  465. if ( idx % 2 !== 1 ) return true;
  466. } );
  467. }
  468. }
  469. } else {
  470. if ( ele.attributes.format === 'binary' && ! compressed ) {
  471. content = Base64toByteArray( ele[ '#text' ] ); // VTP data for the uncompressed case has the following structure:
  472. // [#bytes][DATA]
  473. // where "[#bytes]" is an integer value specifying the number of bytes in the block of data following it.
  474. content = content.slice( numBytes ).buffer;
  475. } else {
  476. if ( ele[ '#text' ] ) {
  477. content = ele[ '#text' ].split( /\s+/ ).filter( function ( el ) {
  478. if ( el !== '' ) return el;
  479. } );
  480. } else {
  481. content = new Int32Array( 0 ).buffer;
  482. }
  483. }
  484. delete ele[ '#text' ]; // Get the content and optimize it
  485. if ( ele.attributes.type === 'Float32' ) {
  486. txt = new Float32Array( content );
  487. } else if ( ele.attributes.type === 'Int32' ) {
  488. txt = new Int32Array( content );
  489. } else if ( ele.attributes.type === 'Int64' ) {
  490. txt = new Int32Array( content );
  491. if ( ele.attributes.format === 'binary' ) {
  492. txt = txt.filter( function ( el, idx ) {
  493. if ( idx % 2 !== 1 ) return true;
  494. } );
  495. }
  496. }
  497. } // endif ( ele.attributes.format === 'binary' && compressed )
  498. return txt;
  499. } // Main part
  500. // Get Dom
  501. const dom = new DOMParser().parseFromString( stringFile, 'application/xml' ); // Get the doc
  502. const doc = dom.documentElement; // Convert to json
  503. const json = xmlToJson( doc );
  504. let points = [];
  505. let normals = [];
  506. let indices = [];
  507. if ( json.PolyData ) {
  508. const piece = json.PolyData.Piece;
  509. const compressed = json.attributes.hasOwnProperty( 'compressor' ); // Can be optimized
  510. // Loop through the sections
  511. const sections = [ 'PointData', 'Points', 'Strips', 'Polys' ]; // +['CellData', 'Verts', 'Lines'];
  512. let sectionIndex = 0;
  513. const numberOfSections = sections.length;
  514. while ( sectionIndex < numberOfSections ) {
  515. const section = piece[ sections[ sectionIndex ] ]; // If it has a DataArray in it
  516. if ( section && section.DataArray ) {
  517. // Depending on the number of DataArrays
  518. let arr;
  519. if ( Object.prototype.toString.call( section.DataArray ) === '[object Array]' ) {
  520. arr = section.DataArray;
  521. } else {
  522. arr = [ section.DataArray ];
  523. }
  524. let dataArrayIndex = 0;
  525. const numberOfDataArrays = arr.length;
  526. while ( dataArrayIndex < numberOfDataArrays ) {
  527. // Parse the DataArray
  528. if ( '#text' in arr[ dataArrayIndex ] && arr[ dataArrayIndex ][ '#text' ].length > 0 ) {
  529. arr[ dataArrayIndex ].text = parseDataArray( arr[ dataArrayIndex ], compressed );
  530. }
  531. dataArrayIndex ++;
  532. }
  533. switch ( sections[ sectionIndex ] ) {
  534. // if iti is point data
  535. case 'PointData':
  536. {
  537. const numberOfPoints = parseInt( piece.attributes.NumberOfPoints );
  538. const normalsName = section.attributes.Normals;
  539. if ( numberOfPoints > 0 ) {
  540. for ( let i = 0, len = arr.length; i < len; i ++ ) {
  541. if ( normalsName === arr[ i ].attributes.Name ) {
  542. const components = arr[ i ].attributes.NumberOfComponents;
  543. normals = new Float32Array( numberOfPoints * components );
  544. normals.set( arr[ i ].text, 0 );
  545. }
  546. }
  547. }
  548. }
  549. break;
  550. // if it is points
  551. case 'Points':
  552. {
  553. const numberOfPoints = parseInt( piece.attributes.NumberOfPoints );
  554. if ( numberOfPoints > 0 ) {
  555. const components = section.DataArray.attributes.NumberOfComponents;
  556. points = new Float32Array( numberOfPoints * components );
  557. points.set( section.DataArray.text, 0 );
  558. }
  559. }
  560. break;
  561. // if it is strips
  562. case 'Strips':
  563. {
  564. const numberOfStrips = parseInt( piece.attributes.NumberOfStrips );
  565. if ( numberOfStrips > 0 ) {
  566. const connectivity = new Int32Array( section.DataArray[ 0 ].text.length );
  567. const offset = new Int32Array( section.DataArray[ 1 ].text.length );
  568. connectivity.set( section.DataArray[ 0 ].text, 0 );
  569. offset.set( section.DataArray[ 1 ].text, 0 );
  570. const size = numberOfStrips + connectivity.length;
  571. indices = new Uint32Array( 3 * size - 9 * numberOfStrips );
  572. let indicesIndex = 0;
  573. for ( let i = 0, len = numberOfStrips; i < len; i ++ ) {
  574. const strip = [];
  575. for ( let s = 0, len1 = offset[ i ], len0 = 0; s < len1 - len0; s ++ ) {
  576. strip.push( connectivity[ s ] );
  577. if ( i > 0 ) len0 = offset[ i - 1 ];
  578. }
  579. for ( let j = 0, len1 = offset[ i ], len0 = 0; j < len1 - len0 - 2; j ++ ) {
  580. if ( j % 2 ) {
  581. indices[ indicesIndex ++ ] = strip[ j ];
  582. indices[ indicesIndex ++ ] = strip[ j + 2 ];
  583. indices[ indicesIndex ++ ] = strip[ j + 1 ];
  584. } else {
  585. indices[ indicesIndex ++ ] = strip[ j ];
  586. indices[ indicesIndex ++ ] = strip[ j + 1 ];
  587. indices[ indicesIndex ++ ] = strip[ j + 2 ];
  588. }
  589. if ( i > 0 ) len0 = offset[ i - 1 ];
  590. }
  591. }
  592. }
  593. }
  594. break;
  595. // if it is polys
  596. case 'Polys':
  597. {
  598. const numberOfPolys = parseInt( piece.attributes.NumberOfPolys );
  599. if ( numberOfPolys > 0 ) {
  600. const connectivity = new Int32Array( section.DataArray[ 0 ].text.length );
  601. const offset = new Int32Array( section.DataArray[ 1 ].text.length );
  602. connectivity.set( section.DataArray[ 0 ].text, 0 );
  603. offset.set( section.DataArray[ 1 ].text, 0 );
  604. const size = numberOfPolys + connectivity.length;
  605. indices = new Uint32Array( 3 * size - 9 * numberOfPolys );
  606. let indicesIndex = 0,
  607. connectivityIndex = 0;
  608. let i = 0,
  609. len0 = 0;
  610. const len = numberOfPolys;
  611. while ( i < len ) {
  612. const poly = [];
  613. let s = 0;
  614. const len1 = offset[ i ];
  615. while ( s < len1 - len0 ) {
  616. poly.push( connectivity[ connectivityIndex ++ ] );
  617. s ++;
  618. }
  619. let j = 1;
  620. while ( j < len1 - len0 - 1 ) {
  621. indices[ indicesIndex ++ ] = poly[ 0 ];
  622. indices[ indicesIndex ++ ] = poly[ j ];
  623. indices[ indicesIndex ++ ] = poly[ j + 1 ];
  624. j ++;
  625. }
  626. i ++;
  627. len0 = offset[ i - 1 ];
  628. }
  629. }
  630. }
  631. break;
  632. default:
  633. break;
  634. }
  635. }
  636. sectionIndex ++;
  637. }
  638. const geometry = new THREE.BufferGeometry();
  639. geometry.setIndex( new THREE.BufferAttribute( indices, 1 ) );
  640. geometry.setAttribute( 'position', new THREE.BufferAttribute( points, 3 ) );
  641. if ( normals.length === points.length ) {
  642. geometry.setAttribute( 'normal', new THREE.BufferAttribute( normals, 3 ) );
  643. }
  644. return geometry;
  645. } else {
  646. throw new Error( 'Unsupported DATASET type' );
  647. }
  648. } // get the 5 first lines of the files to check if there is the key word binary
  649. const meta = THREE.LoaderUtils.decodeText( new Uint8Array( data, 0, 250 ) ).split( '\n' );
  650. if ( meta[ 0 ].indexOf( 'xml' ) !== - 1 ) {
  651. return parseXML( THREE.LoaderUtils.decodeText( data ) );
  652. } else if ( meta[ 2 ].includes( 'ASCII' ) ) {
  653. return parseASCII( THREE.LoaderUtils.decodeText( data ) );
  654. } else {
  655. return parseBinary( data );
  656. }
  657. }
  658. }
  659. THREE.VTKLoader = VTKLoader;
  660. } )();