NRRDLoader.js 13 KB

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