2
0

VTKLoader.js 27 KB

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