NRRDLoader.js 13 KB

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