VTKLoader.js 30 KB

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