1
0

VTKLoader.js 28 KB

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