VTKLoader.js 28 KB

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