NRRDLoader.js 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635
  1. import {
  2. FileLoader,
  3. Loader,
  4. Matrix4,
  5. Vector3
  6. } from '../../../build/three.module.js';
  7. import * as fflate from '../libs/fflate.module.js';
  8. import { Volume } from '../misc/Volume.js';
  9. class NRRDLoader extends Loader {
  10. constructor( manager ) {
  11. super( manager );
  12. }
  13. load( url, onLoad, onProgress, onError ) {
  14. const scope = this;
  15. const loader = new FileLoader( scope.manager );
  16. loader.setPath( scope.path );
  17. loader.setResponseType( 'arraybuffer' );
  18. loader.setRequestHeader( scope.requestHeader );
  19. loader.setWithCredentials( scope.withCredentials );
  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( data ) {
  34. // this parser is largely inspired from the XTK NRRD parser : https://github.com/xtk/X
  35. let _data = data;
  36. let _dataPointer = 0;
  37. const _nativeLittleEndian = new Int8Array( new Int16Array( [ 1 ] ).buffer )[ 0 ] > 0;
  38. const _littleEndian = true;
  39. const headerObject = {};
  40. function scan( type, chunks ) {
  41. if ( chunks === undefined || chunks === null ) {
  42. chunks = 1;
  43. }
  44. let _chunkSize = 1;
  45. let _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. let _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. const u8 = new Uint8Array( array.buffer, array.byteOffset, array.byteLength );
  102. for ( let i = 0; i < array.byteLength; i += chunkSize ) {
  103. for ( let j = i + chunkSize - 1, k = i; j > k; j --, k ++ ) {
  104. const 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. let data, field, fn, i, l, m, _i, _len;
  114. const 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 = _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. let number = '';
  153. start = start || 0;
  154. end = end || data.length;
  155. let value;
  156. //length of the result is the product of the sizes
  157. const lengthOfTheResult = headerObject.sizes.reduce( function ( previous, current ) {
  158. return previous * current;
  159. }, 1 );
  160. let base = 10;
  161. if ( headerObject.encoding === 'hex' ) {
  162. base = 16;
  163. }
  164. const result = new headerObject.__array( lengthOfTheResult );
  165. let resultIndex = 0;
  166. let parsingFunction = parseInt;
  167. if ( headerObject.__array === Float32Array || headerObject.__array === Float64Array ) {
  168. parsingFunction = parseFloat;
  169. }
  170. for ( let 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. const _bytes = scan( 'uchar', data.byteLength );
  190. const _length = _bytes.length;
  191. let _header = null;
  192. let _data_start = 0;
  193. let 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. _data = _bytes.subarray( _data_start ); // the data without header
  207. if ( headerObject.encoding.substring( 0, 2 ) === 'gz' ) {
  208. // we need to decompress the datastream
  209. // here we start the unzipping and get a typed Uint8Array back
  210. _data = fflate.gunzipSync( new Uint8Array( _data ) );// eslint-disable-line no-undef
  211. } else if ( headerObject.encoding === 'ascii' || headerObject.encoding === 'text' || headerObject.encoding === 'txt' || headerObject.encoding === 'hex' ) {
  212. _data = parseDataAsText( _data );
  213. } else if ( headerObject.encoding === 'raw' ) {
  214. //we need to copy the array to create a new array buffer, else we retrieve the original arraybuffer with the header
  215. const _copy = new Uint8Array( _data.length );
  216. for ( let i = 0; i < _data.length; i ++ ) {
  217. _copy[ i ] = _data[ i ];
  218. }
  219. _data = _copy;
  220. }
  221. // .. let's use the underlying array buffer
  222. _data = _data.buffer;
  223. const volume = new Volume();
  224. volume.header = headerObject;
  225. //
  226. // parse the (unzipped) data to a datastream of the correct type
  227. //
  228. volume.data = new headerObject.__array( _data );
  229. // get the min and max intensities
  230. const min_max = volume.computeMinMax();
  231. const min = min_max[ 0 ];
  232. const max = min_max[ 1 ];
  233. // attach the scalar range to the volume
  234. volume.windowLow = min;
  235. volume.windowHigh = max;
  236. // get the image dimensions
  237. volume.dimensions = [ headerObject.sizes[ 0 ], headerObject.sizes[ 1 ], headerObject.sizes[ 2 ] ];
  238. volume.xLength = volume.dimensions[ 0 ];
  239. volume.yLength = volume.dimensions[ 1 ];
  240. volume.zLength = volume.dimensions[ 2 ];
  241. // spacing
  242. const spacingX = ( new Vector3( headerObject.vectors[ 0 ][ 0 ], headerObject.vectors[ 0 ][ 1 ],
  243. headerObject.vectors[ 0 ][ 2 ] ) ).length();
  244. const spacingY = ( new Vector3( headerObject.vectors[ 1 ][ 0 ], headerObject.vectors[ 1 ][ 1 ],
  245. headerObject.vectors[ 1 ][ 2 ] ) ).length();
  246. const spacingZ = ( new Vector3( headerObject.vectors[ 2 ][ 0 ], headerObject.vectors[ 2 ][ 1 ],
  247. headerObject.vectors[ 2 ][ 2 ] ) ).length();
  248. volume.spacing = [ spacingX, spacingY, spacingZ ];
  249. // Create IJKtoRAS matrix
  250. volume.matrix = new Matrix4();
  251. let _spaceX = 1;
  252. let _spaceY = 1;
  253. const _spaceZ = 1;
  254. if ( headerObject.space == 'left-posterior-superior' ) {
  255. _spaceX = - 1;
  256. _spaceY = - 1;
  257. } else if ( headerObject.space === 'left-anterior-superior' ) {
  258. _spaceX = - 1;
  259. }
  260. if ( ! headerObject.vectors ) {
  261. volume.matrix.set(
  262. _spaceX, 0, 0, 0,
  263. 0, _spaceY, 0, 0,
  264. 0, 0, _spaceZ, 0,
  265. 0, 0, 0, 1 );
  266. } else {
  267. const v = headerObject.vectors;
  268. volume.matrix.set(
  269. _spaceX * v[ 0 ][ 0 ], _spaceX * v[ 1 ][ 0 ], _spaceX * v[ 2 ][ 0 ], 0,
  270. _spaceY * v[ 0 ][ 1 ], _spaceY * v[ 1 ][ 1 ], _spaceY * v[ 2 ][ 1 ], 0,
  271. _spaceZ * v[ 0 ][ 2 ], _spaceZ * v[ 1 ][ 2 ], _spaceZ * v[ 2 ][ 2 ], 0,
  272. 0, 0, 0, 1 );
  273. }
  274. volume.inverseMatrix = new Matrix4();
  275. volume.inverseMatrix.copy( volume.matrix ).invert();
  276. volume.RASDimensions = ( new Vector3( volume.xLength, volume.yLength, volume.zLength ) ).applyMatrix4( volume.matrix ).round().toArray().map( Math.abs );
  277. // .. and set the default threshold
  278. // only if the threshold was not already set
  279. if ( volume.lowerThreshold === - Infinity ) {
  280. volume.lowerThreshold = min;
  281. }
  282. if ( volume.upperThreshold === Infinity ) {
  283. volume.upperThreshold = max;
  284. }
  285. return volume;
  286. }
  287. parseChars( array, start, end ) {
  288. // without borders, use the whole array
  289. if ( start === undefined ) {
  290. start = 0;
  291. }
  292. if ( end === undefined ) {
  293. end = array.length;
  294. }
  295. let output = '';
  296. // create and append the chars
  297. let i = 0;
  298. for ( i = start; i < end; ++ i ) {
  299. output += String.fromCharCode( array[ i ] );
  300. }
  301. return output;
  302. }
  303. }
  304. const _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. let i;
  367. return this.sizes = ( function () {
  368. const _ref = data.split( /\s+/ );
  369. const _results = [];
  370. for ( let _i = 0, _len = _ref.length; _i < _len; _i ++ ) {
  371. i = _ref[ _i ];
  372. _results.push( parseInt( i, 10 ) );
  373. }
  374. return _results;
  375. } )();
  376. },
  377. space: function ( data ) {
  378. return this.space = data;
  379. },
  380. 'space origin': function ( data ) {
  381. return this.space_origin = data.split( '(' )[ 1 ].split( ')' )[ 0 ].split( ',' );
  382. },
  383. 'space directions': function ( data ) {
  384. let f, v;
  385. const parts = data.match( /\(.*?\)/g );
  386. return this.vectors = ( function () {
  387. const _results = [];
  388. for ( let _i = 0, _len = parts.length; _i < _len; _i ++ ) {
  389. v = parts[ _i ];
  390. _results.push( ( function () {
  391. const _ref = v.slice( 1, - 1 ).split( /,/ );
  392. const _results2 = [];
  393. for ( let _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. let f;
  405. const parts = data.split( /\s+/ );
  406. return this.spacings = ( function () {
  407. const _results = [];
  408. for ( let _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. export { NRRDLoader };