VTKLoader.js 30 KB

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