NRRDLoader.js 13 KB

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