VTKLoader.js 30 KB

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