NRRDLoader.js 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609
  1. ( function () {
  2. class NRRDLoader extends THREE.Loader {
  3. constructor( manager ) {
  4. super( manager );
  5. }
  6. load( url, onLoad, onProgress, onError ) {
  7. const scope = this;
  8. const 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 ( data ) {
  14. try {
  15. onLoad( scope.parse( data ) );
  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( data ) {
  27. // this parser is largely inspired from the XTK NRRD parser : https://github.com/xtk/X
  28. let _data = data;
  29. let _dataPointer = 0;
  30. const _nativeLittleEndian = new Int8Array( new Int16Array( [ 1 ] ).buffer )[ 0 ] > 0;
  31. const _littleEndian = true;
  32. const headerObject = {};
  33. function scan( type, chunks ) {
  34. if ( chunks === undefined || chunks === null ) {
  35. chunks = 1;
  36. }
  37. let _chunkSize = 1;
  38. let _array_type = Uint8Array;
  39. switch ( type ) {
  40. // 1 byte data types
  41. case 'uchar':
  42. break;
  43. case 'schar':
  44. _array_type = Int8Array;
  45. break;
  46. // 2 byte data types
  47. case 'ushort':
  48. _array_type = Uint16Array;
  49. _chunkSize = 2;
  50. break;
  51. case 'sshort':
  52. _array_type = Int16Array;
  53. _chunkSize = 2;
  54. break;
  55. // 4 byte data types
  56. case 'uint':
  57. _array_type = Uint32Array;
  58. _chunkSize = 4;
  59. break;
  60. case 'sint':
  61. _array_type = Int32Array;
  62. _chunkSize = 4;
  63. break;
  64. case 'float':
  65. _array_type = Float32Array;
  66. _chunkSize = 4;
  67. break;
  68. case 'complex':
  69. _array_type = Float64Array;
  70. _chunkSize = 8;
  71. break;
  72. case 'double':
  73. _array_type = Float64Array;
  74. _chunkSize = 8;
  75. break;
  76. }
  77. // increase the data pointer in-place
  78. let _bytes = new _array_type( _data.slice( _dataPointer, _dataPointer += chunks * _chunkSize ) );
  79. // if required, flip the endianness of the bytes
  80. if ( _nativeLittleEndian != _littleEndian ) {
  81. // we need to flip here since the format doesn't match the native endianness
  82. _bytes = flipEndianness( _bytes, _chunkSize );
  83. }
  84. if ( chunks == 1 ) {
  85. // if only one chunk was requested, just return one value
  86. return _bytes[ 0 ];
  87. }
  88. // return the byte array
  89. return _bytes;
  90. }
  91. //Flips typed array endianness in-place. Based on https://github.com/kig/DataStream.js/blob/master/DataStream.js.
  92. function flipEndianness( array, chunkSize ) {
  93. const u8 = new Uint8Array( array.buffer, array.byteOffset, array.byteLength );
  94. for ( let i = 0; i < array.byteLength; i += chunkSize ) {
  95. for ( let j = i + chunkSize - 1, k = i; j > k; j --, k ++ ) {
  96. const tmp = u8[ k ];
  97. u8[ k ] = u8[ j ];
  98. u8[ j ] = tmp;
  99. }
  100. }
  101. return array;
  102. }
  103. //parse the header
  104. function parseHeader( header ) {
  105. let data, field, fn, i, l, m, _i, _len;
  106. const lines = header.split( /\r?\n/ );
  107. for ( _i = 0, _len = lines.length; _i < _len; _i ++ ) {
  108. l = lines[ _i ];
  109. if ( l.match( /NRRD\d+/ ) ) {
  110. headerObject.isNrrd = true;
  111. } else if ( ! l.match( /^#/ ) && ( m = l.match( /(.*):(.*)/ ) ) ) {
  112. field = m[ 1 ].trim();
  113. data = m[ 2 ].trim();
  114. fn = _fieldFunctions[ field ];
  115. if ( fn ) {
  116. fn.call( headerObject, data );
  117. } else {
  118. headerObject[ field ] = data;
  119. }
  120. }
  121. }
  122. if ( ! headerObject.isNrrd ) {
  123. throw new Error( 'Not an NRRD file' );
  124. }
  125. if ( headerObject.encoding === 'bz2' || headerObject.encoding === 'bzip2' ) {
  126. throw new Error( 'Bzip is not supported' );
  127. }
  128. if ( ! headerObject.vectors ) {
  129. //if no space direction is set, let's use the identity
  130. headerObject.vectors = [];
  131. headerObject.vectors.push( [ 1, 0, 0 ] );
  132. headerObject.vectors.push( [ 0, 1, 0 ] );
  133. headerObject.vectors.push( [ 0, 0, 1 ] );
  134. //apply spacing if defined
  135. if ( headerObject.spacings ) {
  136. for ( i = 0; i <= 2; i ++ ) {
  137. if ( ! isNaN( headerObject.spacings[ i ] ) ) {
  138. for ( let j = 0; j <= 2; j ++ ) {
  139. headerObject.vectors[ i ][ j ] *= headerObject.spacings[ i ];
  140. }
  141. }
  142. }
  143. }
  144. }
  145. }
  146. //parse the data when registred as one of this type : 'text', 'ascii', 'txt'
  147. function parseDataAsText( data, start, end ) {
  148. let number = '';
  149. start = start || 0;
  150. end = end || data.length;
  151. let value;
  152. //length of the result is the product of the sizes
  153. const lengthOfTheResult = headerObject.sizes.reduce( function ( previous, current ) {
  154. return previous * current;
  155. }, 1 );
  156. let base = 10;
  157. if ( headerObject.encoding === 'hex' ) {
  158. base = 16;
  159. }
  160. const result = new headerObject.__array( lengthOfTheResult );
  161. let resultIndex = 0;
  162. let parsingFunction = parseInt;
  163. if ( headerObject.__array === Float32Array || headerObject.__array === Float64Array ) {
  164. parsingFunction = parseFloat;
  165. }
  166. for ( let i = start; i < end; i ++ ) {
  167. value = data[ i ];
  168. //if value is not a space
  169. if ( ( value < 9 || value > 13 ) && value !== 32 ) {
  170. number += String.fromCharCode( value );
  171. } else {
  172. if ( number !== '' ) {
  173. result[ resultIndex ] = parsingFunction( number, base );
  174. resultIndex ++;
  175. }
  176. number = '';
  177. }
  178. }
  179. if ( number !== '' ) {
  180. result[ resultIndex ] = parsingFunction( number, base );
  181. resultIndex ++;
  182. }
  183. return result;
  184. }
  185. const _bytes = scan( 'uchar', data.byteLength );
  186. const _length = _bytes.length;
  187. let _header = null;
  188. let _data_start = 0;
  189. let i;
  190. for ( i = 1; i < _length; i ++ ) {
  191. if ( _bytes[ i - 1 ] == 10 && _bytes[ i ] == 10 ) {
  192. // we found two line breaks in a row
  193. // now we know what the header is
  194. _header = this.parseChars( _bytes, 0, i - 2 );
  195. // this is were the data starts
  196. _data_start = i + 1;
  197. break;
  198. }
  199. }
  200. // parse the header
  201. parseHeader( _header );
  202. _data = _bytes.subarray( _data_start ); // the data without header
  203. if ( headerObject.encoding.substring( 0, 2 ) === 'gz' ) {
  204. // we need to decompress the datastream
  205. // here we start the unzipping and get a typed Uint8Array back
  206. _data = fflate.gunzipSync( new Uint8Array( _data ) ); // eslint-disable-line no-undef
  207. } else if ( headerObject.encoding === 'ascii' || headerObject.encoding === 'text' || headerObject.encoding === 'txt' || headerObject.encoding === 'hex' ) {
  208. _data = parseDataAsText( _data );
  209. } else if ( headerObject.encoding === 'raw' ) {
  210. //we need to copy the array to create a new array buffer, else we retrieve the original arraybuffer with the header
  211. const _copy = new Uint8Array( _data.length );
  212. for ( let i = 0; i < _data.length; i ++ ) {
  213. _copy[ i ] = _data[ i ];
  214. }
  215. _data = _copy;
  216. }
  217. // .. let's use the underlying array buffer
  218. _data = _data.buffer;
  219. const volume = new THREE.Volume();
  220. volume.header = headerObject;
  221. //
  222. // parse the (unzipped) data to a datastream of the correct type
  223. //
  224. volume.data = new headerObject.__array( _data );
  225. // get the min and max intensities
  226. const min_max = volume.computeMinMax();
  227. const min = min_max[ 0 ];
  228. const max = min_max[ 1 ];
  229. // attach the scalar range to the volume
  230. volume.windowLow = min;
  231. volume.windowHigh = max;
  232. // get the image dimensions
  233. volume.dimensions = [ headerObject.sizes[ 0 ], headerObject.sizes[ 1 ], headerObject.sizes[ 2 ] ];
  234. volume.xLength = volume.dimensions[ 0 ];
  235. volume.yLength = volume.dimensions[ 1 ];
  236. volume.zLength = volume.dimensions[ 2 ];
  237. // Identify axis order in the space-directions matrix from the header if possible.
  238. if ( headerObject.vectors ) {
  239. const xIndex = headerObject.vectors.findIndex( vector => vector[ 0 ] !== 0 );
  240. const yIndex = headerObject.vectors.findIndex( vector => vector[ 1 ] !== 0 );
  241. const zIndex = headerObject.vectors.findIndex( vector => vector[ 2 ] !== 0 );
  242. const axisOrder = [];
  243. axisOrder[ xIndex ] = 'x';
  244. axisOrder[ yIndex ] = 'y';
  245. axisOrder[ zIndex ] = 'z';
  246. volume.axisOrder = axisOrder;
  247. } else {
  248. volume.axisOrder = [ 'x', 'y', 'z' ];
  249. }
  250. // spacing
  251. const spacingX = new THREE.Vector3().fromArray( headerObject.vectors[ 0 ] ).length();
  252. const spacingY = new THREE.Vector3().fromArray( headerObject.vectors[ 1 ] ).length();
  253. const spacingZ = new THREE.Vector3().fromArray( headerObject.vectors[ 2 ] ).length();
  254. volume.spacing = [ spacingX, spacingY, spacingZ ];
  255. // Create IJKtoRAS matrix
  256. volume.matrix = new THREE.Matrix4();
  257. const transitionMatrix = new THREE.Matrix4();
  258. if ( headerObject.space === 'left-posterior-superior' ) {
  259. transitionMatrix.set( - 1, 0, 0, 0, 0, - 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1 );
  260. } else if ( headerObject.space === 'left-anterior-superior' ) {
  261. transitionMatrix.set( 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, - 1, 0, 0, 0, 0, 1 );
  262. }
  263. if ( ! headerObject.vectors ) {
  264. volume.matrix.set( 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1 );
  265. } else {
  266. const v = headerObject.vectors;
  267. const ijk_to_transition = new THREE.Matrix4().set( v[ 0 ][ 0 ], v[ 1 ][ 0 ], v[ 2 ][ 0 ], 0, v[ 0 ][ 1 ], v[ 1 ][ 1 ], v[ 2 ][ 1 ], 0, v[ 0 ][ 2 ], v[ 1 ][ 2 ], v[ 2 ][ 2 ], 0, 0, 0, 0, 1 );
  268. const transition_to_ras = new THREE.Matrix4().multiplyMatrices( ijk_to_transition, transitionMatrix );
  269. volume.matrix = transition_to_ras;
  270. }
  271. volume.inverseMatrix = new THREE.Matrix4();
  272. volume.inverseMatrix.copy( volume.matrix ).invert();
  273. volume.RASDimensions = new THREE.Vector3( volume.xLength, volume.yLength, volume.zLength ).applyMatrix4( volume.matrix ).round().toArray().map( Math.abs );
  274. // .. and set the default threshold
  275. // only if the threshold was not already set
  276. if ( volume.lowerThreshold === - Infinity ) {
  277. volume.lowerThreshold = min;
  278. }
  279. if ( volume.upperThreshold === Infinity ) {
  280. volume.upperThreshold = max;
  281. }
  282. return volume;
  283. }
  284. parseChars( array, start, end ) {
  285. // without borders, use the whole array
  286. if ( start === undefined ) {
  287. start = 0;
  288. }
  289. if ( end === undefined ) {
  290. end = array.length;
  291. }
  292. let output = '';
  293. // create and append the chars
  294. let i = 0;
  295. for ( i = start; i < end; ++ i ) {
  296. output += String.fromCharCode( array[ i ] );
  297. }
  298. return output;
  299. }
  300. }
  301. const _fieldFunctions = {
  302. type: function ( data ) {
  303. switch ( data ) {
  304. case 'uchar':
  305. case 'unsigned char':
  306. case 'uint8':
  307. case 'uint8_t':
  308. this.__array = Uint8Array;
  309. break;
  310. case 'signed char':
  311. case 'int8':
  312. case 'int8_t':
  313. this.__array = Int8Array;
  314. break;
  315. case 'short':
  316. case 'short int':
  317. case 'signed short':
  318. case 'signed short int':
  319. case 'int16':
  320. case 'int16_t':
  321. this.__array = Int16Array;
  322. break;
  323. case 'ushort':
  324. case 'unsigned short':
  325. case 'unsigned short int':
  326. case 'uint16':
  327. case 'uint16_t':
  328. this.__array = Uint16Array;
  329. break;
  330. case 'int':
  331. case 'signed int':
  332. case 'int32':
  333. case 'int32_t':
  334. this.__array = Int32Array;
  335. break;
  336. case 'uint':
  337. case 'unsigned int':
  338. case 'uint32':
  339. case 'uint32_t':
  340. this.__array = Uint32Array;
  341. break;
  342. case 'float':
  343. this.__array = Float32Array;
  344. break;
  345. case 'double':
  346. this.__array = Float64Array;
  347. break;
  348. default:
  349. throw new Error( 'Unsupported NRRD data type: ' + data );
  350. }
  351. return this.type = data;
  352. },
  353. endian: function ( data ) {
  354. return this.endian = data;
  355. },
  356. encoding: function ( data ) {
  357. return this.encoding = data;
  358. },
  359. dimension: function ( data ) {
  360. return this.dim = parseInt( data, 10 );
  361. },
  362. sizes: function ( data ) {
  363. let i;
  364. return this.sizes = function () {
  365. const _ref = data.split( /\s+/ );
  366. const _results = [];
  367. for ( let _i = 0, _len = _ref.length; _i < _len; _i ++ ) {
  368. i = _ref[ _i ];
  369. _results.push( parseInt( i, 10 ) );
  370. }
  371. return _results;
  372. }();
  373. },
  374. space: function ( data ) {
  375. return this.space = data;
  376. },
  377. 'space origin': function ( data ) {
  378. return this.space_origin = data.split( '(' )[ 1 ].split( ')' )[ 0 ].split( ',' );
  379. },
  380. 'space directions': function ( data ) {
  381. let f, v;
  382. const parts = data.match( /\(.*?\)/g );
  383. return this.vectors = function () {
  384. const _results = [];
  385. for ( let _i = 0, _len = parts.length; _i < _len; _i ++ ) {
  386. v = parts[ _i ];
  387. _results.push( function () {
  388. const _ref = v.slice( 1, - 1 ).split( /,/ );
  389. const _results2 = [];
  390. for ( let _j = 0, _len2 = _ref.length; _j < _len2; _j ++ ) {
  391. f = _ref[ _j ];
  392. _results2.push( parseFloat( f ) );
  393. }
  394. return _results2;
  395. }() );
  396. }
  397. return _results;
  398. }();
  399. },
  400. spacings: function ( data ) {
  401. let f;
  402. const parts = data.split( /\s+/ );
  403. return this.spacings = function () {
  404. const _results = [];
  405. for ( let _i = 0, _len = parts.length; _i < _len; _i ++ ) {
  406. f = parts[ _i ];
  407. _results.push( parseFloat( f ) );
  408. }
  409. return _results;
  410. }();
  411. }
  412. };
  413. THREE.NRRDLoader = NRRDLoader;
  414. } )();