NRRDLoader.js 13 KB

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