NRRDLoader.js 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671
  1. import {
  2. FileLoader,
  3. Loader,
  4. Matrix4,
  5. Vector3
  6. } from 'three';
  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( /^#/ ) && ( m = l.match( /(.*):(.*)/ ) ) ) {
  120. field = m[ 1 ].trim();
  121. data = m[ 2 ].trim();
  122. fn = _fieldFunctions[ field ];
  123. if ( fn ) {
  124. fn.call( headerObject, data );
  125. } else {
  126. headerObject[ field ] = data;
  127. }
  128. }
  129. }
  130. if ( ! headerObject.isNrrd ) {
  131. throw new Error( 'Not an NRRD file' );
  132. }
  133. if ( headerObject.encoding === 'bz2' || headerObject.encoding === 'bzip2' ) {
  134. throw new Error( 'Bzip is not supported' );
  135. }
  136. if ( ! headerObject.vectors ) {
  137. //if no space direction is set, let's use the identity
  138. headerObject.vectors = [ ];
  139. headerObject.vectors.push( [ 1, 0, 0 ] );
  140. headerObject.vectors.push( [ 0, 1, 0 ] );
  141. headerObject.vectors.push( [ 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. for ( let j = 0; j <= 2; j ++ ) {
  147. headerObject.vectors[ i ][ j ] *= headerObject.spacings[ i ];
  148. }
  149. }
  150. }
  151. }
  152. }
  153. }
  154. //parse the data when registred as one of this type : 'text', 'ascii', 'txt'
  155. function parseDataAsText( data, start, end ) {
  156. let number = '';
  157. start = start || 0;
  158. end = end || data.length;
  159. let value;
  160. //length of the result is the product of the sizes
  161. const lengthOfTheResult = headerObject.sizes.reduce( function ( previous, current ) {
  162. return previous * current;
  163. }, 1 );
  164. let base = 10;
  165. if ( headerObject.encoding === 'hex' ) {
  166. base = 16;
  167. }
  168. const result = new headerObject.__array( lengthOfTheResult );
  169. let resultIndex = 0;
  170. let parsingFunction = parseInt;
  171. if ( headerObject.__array === Float32Array || headerObject.__array === Float64Array ) {
  172. parsingFunction = parseFloat;
  173. }
  174. for ( let i = start; i < end; i ++ ) {
  175. value = data[ i ];
  176. //if value is not a space
  177. if ( ( value < 9 || value > 13 ) && value !== 32 ) {
  178. number += String.fromCharCode( value );
  179. } else {
  180. if ( number !== '' ) {
  181. result[ resultIndex ] = parsingFunction( number, base );
  182. resultIndex ++;
  183. }
  184. number = '';
  185. }
  186. }
  187. if ( number !== '' ) {
  188. result[ resultIndex ] = parsingFunction( number, base );
  189. resultIndex ++;
  190. }
  191. return result;
  192. }
  193. const _bytes = scan( 'uchar', data.byteLength );
  194. const _length = _bytes.length;
  195. let _header = null;
  196. let _data_start = 0;
  197. let i;
  198. for ( i = 1; i < _length; i ++ ) {
  199. if ( _bytes[ i - 1 ] == 10 && _bytes[ i ] == 10 ) {
  200. // we found two line breaks in a row
  201. // now we know what the header is
  202. _header = this.parseChars( _bytes, 0, i - 2 );
  203. // this is were the data starts
  204. _data_start = i + 1;
  205. break;
  206. }
  207. }
  208. // parse the header
  209. parseHeader( _header );
  210. _data = _bytes.subarray( _data_start ); // the data without header
  211. if ( headerObject.encoding.substring( 0, 2 ) === 'gz' ) {
  212. // we need to decompress the datastream
  213. // here we start the unzipping and get a typed Uint8Array back
  214. _data = fflate.gunzipSync( new Uint8Array( _data ) );// eslint-disable-line no-undef
  215. } else if ( headerObject.encoding === 'ascii' || headerObject.encoding === 'text' || headerObject.encoding === 'txt' || headerObject.encoding === 'hex' ) {
  216. _data = parseDataAsText( _data );
  217. } else if ( headerObject.encoding === 'raw' ) {
  218. //we need to copy the array to create a new array buffer, else we retrieve the original arraybuffer with the header
  219. const _copy = new Uint8Array( _data.length );
  220. for ( let i = 0; i < _data.length; i ++ ) {
  221. _copy[ i ] = _data[ i ];
  222. }
  223. _data = _copy;
  224. }
  225. // .. let's use the underlying array buffer
  226. _data = _data.buffer;
  227. const volume = new Volume();
  228. volume.header = headerObject;
  229. //
  230. // parse the (unzipped) data to a datastream of the correct type
  231. //
  232. volume.data = new headerObject.__array( _data );
  233. // get the min and max intensities
  234. const min_max = volume.computeMinMax();
  235. const min = min_max[ 0 ];
  236. const max = min_max[ 1 ];
  237. // attach the scalar range to the volume
  238. volume.windowLow = min;
  239. volume.windowHigh = max;
  240. // get the image dimensions
  241. volume.dimensions = [ headerObject.sizes[ 0 ], headerObject.sizes[ 1 ], headerObject.sizes[ 2 ] ];
  242. volume.xLength = volume.dimensions[ 0 ];
  243. volume.yLength = volume.dimensions[ 1 ];
  244. volume.zLength = volume.dimensions[ 2 ];
  245. // Identify axis order in the space-directions matrix from the header if possible.
  246. if ( headerObject.vectors ) {
  247. const xIndex = headerObject.vectors.findIndex( vector => vector[ 0 ] !== 0 );
  248. const yIndex = headerObject.vectors.findIndex( vector => vector[ 1 ] !== 0 );
  249. const zIndex = headerObject.vectors.findIndex( vector => vector[ 2 ] !== 0 );
  250. const axisOrder = [];
  251. axisOrder[ xIndex ] = 'x';
  252. axisOrder[ yIndex ] = 'y';
  253. axisOrder[ zIndex ] = 'z';
  254. volume.axisOrder = axisOrder;
  255. } else {
  256. volume.axisOrder = [ 'x', 'y', 'z' ];
  257. }
  258. // spacing
  259. const spacingX = new Vector3().fromArray( headerObject.vectors[ 0 ] ).length();
  260. const spacingY = new Vector3().fromArray( headerObject.vectors[ 1 ] ).length();
  261. const spacingZ = new Vector3().fromArray( headerObject.vectors[ 2 ] ).length();
  262. volume.spacing = [ spacingX, spacingY, spacingZ ];
  263. // Create IJKtoRAS matrix
  264. volume.matrix = new Matrix4();
  265. const transitionMatrix = new Matrix4();
  266. if ( headerObject.space === 'left-posterior-superior' ) {
  267. transitionMatrix.set(
  268. - 1, 0, 0, 0,
  269. 0, - 1, 0, 0,
  270. 0, 0, 1, 0,
  271. 0, 0, 0, 1
  272. );
  273. } else if ( headerObject.space === 'left-anterior-superior' ) {
  274. transitionMatrix.set(
  275. 1, 0, 0, 0,
  276. 0, 1, 0, 0,
  277. 0, 0, - 1, 0,
  278. 0, 0, 0, 1
  279. );
  280. }
  281. if ( ! headerObject.vectors ) {
  282. volume.matrix.set(
  283. 1, 0, 0, 0,
  284. 0, 1, 0, 0,
  285. 0, 0, 1, 0,
  286. 0, 0, 0, 1 );
  287. } else {
  288. const v = headerObject.vectors;
  289. const ijk_to_transition = new Matrix4().set(
  290. v[ 0 ][ 0 ], v[ 1 ][ 0 ], v[ 2 ][ 0 ], 0,
  291. v[ 0 ][ 1 ], v[ 1 ][ 1 ], v[ 2 ][ 1 ], 0,
  292. v[ 0 ][ 2 ], v[ 1 ][ 2 ], v[ 2 ][ 2 ], 0,
  293. 0, 0, 0, 1
  294. );
  295. const transition_to_ras = new Matrix4().multiplyMatrices( ijk_to_transition, transitionMatrix );
  296. volume.matrix = transition_to_ras;
  297. }
  298. volume.inverseMatrix = new Matrix4();
  299. volume.inverseMatrix.copy( volume.matrix ).invert();
  300. volume.RASDimensions = new Vector3( volume.xLength, volume.yLength, volume.zLength ).applyMatrix4( volume.matrix ).round().toArray().map( Math.abs );
  301. // .. and set the default threshold
  302. // only if the threshold was not already set
  303. if ( volume.lowerThreshold === - Infinity ) {
  304. volume.lowerThreshold = min;
  305. }
  306. if ( volume.upperThreshold === Infinity ) {
  307. volume.upperThreshold = max;
  308. }
  309. return volume;
  310. }
  311. parseChars( array, start, end ) {
  312. // without borders, use the whole array
  313. if ( start === undefined ) {
  314. start = 0;
  315. }
  316. if ( end === undefined ) {
  317. end = array.length;
  318. }
  319. let output = '';
  320. // create and append the chars
  321. let i = 0;
  322. for ( i = start; i < end; ++ i ) {
  323. output += String.fromCharCode( array[ i ] );
  324. }
  325. return output;
  326. }
  327. }
  328. const _fieldFunctions = {
  329. type: function ( data ) {
  330. switch ( data ) {
  331. case 'uchar':
  332. case 'unsigned char':
  333. case 'uint8':
  334. case 'uint8_t':
  335. this.__array = Uint8Array;
  336. break;
  337. case 'signed char':
  338. case 'int8':
  339. case 'int8_t':
  340. this.__array = Int8Array;
  341. break;
  342. case 'short':
  343. case 'short int':
  344. case 'signed short':
  345. case 'signed short int':
  346. case 'int16':
  347. case 'int16_t':
  348. this.__array = Int16Array;
  349. break;
  350. case 'ushort':
  351. case 'unsigned short':
  352. case 'unsigned short int':
  353. case 'uint16':
  354. case 'uint16_t':
  355. this.__array = Uint16Array;
  356. break;
  357. case 'int':
  358. case 'signed int':
  359. case 'int32':
  360. case 'int32_t':
  361. this.__array = Int32Array;
  362. break;
  363. case 'uint':
  364. case 'unsigned int':
  365. case 'uint32':
  366. case 'uint32_t':
  367. this.__array = Uint32Array;
  368. break;
  369. case 'float':
  370. this.__array = Float32Array;
  371. break;
  372. case 'double':
  373. this.__array = Float64Array;
  374. break;
  375. default:
  376. throw new Error( 'Unsupported NRRD data type: ' + data );
  377. }
  378. return this.type = data;
  379. },
  380. endian: function ( data ) {
  381. return this.endian = data;
  382. },
  383. encoding: function ( data ) {
  384. return this.encoding = data;
  385. },
  386. dimension: function ( data ) {
  387. return this.dim = parseInt( data, 10 );
  388. },
  389. sizes: function ( data ) {
  390. let i;
  391. return this.sizes = ( function () {
  392. const _ref = data.split( /\s+/ );
  393. const _results = [];
  394. for ( let _i = 0, _len = _ref.length; _i < _len; _i ++ ) {
  395. i = _ref[ _i ];
  396. _results.push( parseInt( i, 10 ) );
  397. }
  398. return _results;
  399. } )();
  400. },
  401. space: function ( data ) {
  402. return this.space = data;
  403. },
  404. 'space origin': function ( data ) {
  405. return this.space_origin = data.split( '(' )[ 1 ].split( ')' )[ 0 ].split( ',' );
  406. },
  407. 'space directions': function ( data ) {
  408. let f, v;
  409. const parts = data.match( /\(.*?\)/g );
  410. return this.vectors = ( function () {
  411. const _results = [];
  412. for ( let _i = 0, _len = parts.length; _i < _len; _i ++ ) {
  413. v = parts[ _i ];
  414. _results.push( ( function () {
  415. const _ref = v.slice( 1, - 1 ).split( /,/ );
  416. const _results2 = [];
  417. for ( let _j = 0, _len2 = _ref.length; _j < _len2; _j ++ ) {
  418. f = _ref[ _j ];
  419. _results2.push( parseFloat( f ) );
  420. }
  421. return _results2;
  422. } )() );
  423. }
  424. return _results;
  425. } )();
  426. },
  427. spacings: function ( data ) {
  428. let f;
  429. const parts = data.split( /\s+/ );
  430. return this.spacings = ( function () {
  431. const _results = [];
  432. for ( let _i = 0, _len = parts.length; _i < _len; _i ++ ) {
  433. f = parts[ _i ];
  434. _results.push( parseFloat( f ) );
  435. }
  436. return _results;
  437. } )();
  438. }
  439. };
  440. export { NRRDLoader };