VTKLoader.js 28 KB

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