VTKLoader.js 27 KB

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