NRRDLoader.js 13 KB

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