VTKLoader.js 27 KB

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