NRRDLoader.js 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718
  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. /**
  10. * A loader for the NRRD format.
  11. *
  12. * ```js
  13. * const loader = new NRRDLoader();
  14. * const volume = await loader.loadAsync( 'models/nrrd/I.nrrd' );
  15. * ```
  16. *
  17. * @augments Loader
  18. * @three_import import { NRRDLoader } from 'three/addons/loaders/NRRDLoader.js';
  19. */
  20. class NRRDLoader extends Loader {
  21. /**
  22. * Constructs a new NRRD loader.
  23. *
  24. * @param {LoadingManager} [manager] - The loading manager.
  25. */
  26. constructor( manager ) {
  27. super( manager );
  28. }
  29. /**
  30. * Starts loading from the given URL and passes the loaded NRRD asset
  31. * to the `onLoad()` callback.
  32. *
  33. * @param {string} url - The path/URL of the file to be loaded. This can also be a data URI.
  34. * @param {function(Volume)} onLoad - Executed when the loading process has been finished.
  35. * @param {onProgressCallback} onProgress - Executed while the loading is in progress.
  36. * @param {onErrorCallback} onError - Executed when errors occur.
  37. */
  38. load( url, onLoad, onProgress, onError ) {
  39. const scope = this;
  40. const loader = new FileLoader( scope.manager );
  41. loader.setPath( scope.path );
  42. loader.setResponseType( 'arraybuffer' );
  43. loader.setRequestHeader( scope.requestHeader );
  44. loader.setWithCredentials( scope.withCredentials );
  45. loader.load( url, function ( data ) {
  46. try {
  47. onLoad( scope.parse( data ) );
  48. } catch ( e ) {
  49. if ( onError ) {
  50. onError( e );
  51. } else {
  52. console.error( e );
  53. }
  54. scope.manager.itemError( url );
  55. }
  56. }, onProgress, onError );
  57. }
  58. /**
  59. * Toggles the segmentation mode.
  60. *
  61. * @param {boolean} segmentation - Whether to use segmentation mode or not.
  62. */
  63. setSegmentation( segmentation ) {
  64. this.segmentation = segmentation;
  65. }
  66. /**
  67. * Parses the given NRRD data and returns the resulting volume data.
  68. *
  69. * @param {ArrayBuffer} data - The raw NRRD data as an array buffer.
  70. * @return {Volume} The parsed volume.
  71. */
  72. parse( data ) {
  73. // this parser is largely inspired from the XTK NRRD parser : https://github.com/xtk/X
  74. let _data = data;
  75. let _dataPointer = 0;
  76. const _nativeLittleEndian = new Int8Array( new Int16Array( [ 1 ] ).buffer )[ 0 ] > 0;
  77. const _littleEndian = true;
  78. const headerObject = {};
  79. function scan( type, chunks ) {
  80. let _chunkSize = 1;
  81. let _array_type = Uint8Array;
  82. switch ( type ) {
  83. // 1 byte data types
  84. case 'uchar':
  85. break;
  86. case 'schar':
  87. _array_type = Int8Array;
  88. break;
  89. // 2 byte data types
  90. case 'ushort':
  91. _array_type = Uint16Array;
  92. _chunkSize = 2;
  93. break;
  94. case 'sshort':
  95. _array_type = Int16Array;
  96. _chunkSize = 2;
  97. break;
  98. // 4 byte data types
  99. case 'uint':
  100. _array_type = Uint32Array;
  101. _chunkSize = 4;
  102. break;
  103. case 'sint':
  104. _array_type = Int32Array;
  105. _chunkSize = 4;
  106. break;
  107. case 'float':
  108. _array_type = Float32Array;
  109. _chunkSize = 4;
  110. break;
  111. case 'complex':
  112. _array_type = Float64Array;
  113. _chunkSize = 8;
  114. break;
  115. case 'double':
  116. _array_type = Float64Array;
  117. _chunkSize = 8;
  118. break;
  119. }
  120. // increase the data pointer in-place
  121. let _bytes = new _array_type( _data.slice( _dataPointer,
  122. _dataPointer += chunks * _chunkSize ) );
  123. // if required, flip the endianness of the bytes
  124. if ( _nativeLittleEndian != _littleEndian ) {
  125. // we need to flip here since the format doesn't match the native endianness
  126. _bytes = flipEndianness( _bytes, _chunkSize );
  127. }
  128. // return the byte array
  129. return _bytes;
  130. }
  131. //Flips typed array endianness in-place. Based on https://github.com/kig/DataStream.js/blob/master/DataStream.js.
  132. function flipEndianness( array, chunkSize ) {
  133. const u8 = new Uint8Array( array.buffer, array.byteOffset, array.byteLength );
  134. for ( let i = 0; i < array.byteLength; i += chunkSize ) {
  135. for ( let j = i + chunkSize - 1, k = i; j > k; j --, k ++ ) {
  136. const tmp = u8[ k ];
  137. u8[ k ] = u8[ j ];
  138. u8[ j ] = tmp;
  139. }
  140. }
  141. return array;
  142. }
  143. //parse the header
  144. function parseHeader( header ) {
  145. let data, field, fn, i, l, m, _i, _len;
  146. const lines = header.split( /\r?\n/ );
  147. for ( _i = 0, _len = lines.length; _i < _len; _i ++ ) {
  148. l = lines[ _i ];
  149. if ( l.match( /NRRD\d+/ ) ) {
  150. headerObject.isNrrd = true;
  151. } else if ( ! l.match( /^#/ ) && ( m = l.match( /(.*):(.*)/ ) ) ) {
  152. field = m[ 1 ].trim();
  153. data = m[ 2 ].trim();
  154. fn = _fieldFunctions[ field ];
  155. if ( fn ) {
  156. fn.call( headerObject, data );
  157. } else {
  158. headerObject[ field ] = data;
  159. }
  160. }
  161. }
  162. if ( ! headerObject.isNrrd ) {
  163. throw new Error( 'Not an NRRD file' );
  164. }
  165. if ( headerObject.encoding === 'bz2' || headerObject.encoding === 'bzip2' ) {
  166. throw new Error( 'Bzip is not supported' );
  167. }
  168. if ( ! headerObject.vectors ) {
  169. //if no space direction is set, let's use the identity
  170. headerObject.vectors = [ ];
  171. headerObject.vectors.push( [ 1, 0, 0 ] );
  172. headerObject.vectors.push( [ 0, 1, 0 ] );
  173. headerObject.vectors.push( [ 0, 0, 1 ] );
  174. //apply spacing if defined
  175. if ( headerObject.spacings ) {
  176. for ( i = 0; i <= 2; i ++ ) {
  177. if ( ! isNaN( headerObject.spacings[ i ] ) ) {
  178. for ( let j = 0; j <= 2; j ++ ) {
  179. headerObject.vectors[ i ][ j ] *= headerObject.spacings[ i ];
  180. }
  181. }
  182. }
  183. }
  184. }
  185. }
  186. //parse the data when registered as one of this type : 'text', 'ascii', 'txt'
  187. function parseDataAsText( data, start, end ) {
  188. let number = '';
  189. start = start || 0;
  190. end = end || data.length;
  191. let value;
  192. //length of the result is the product of the sizes
  193. const lengthOfTheResult = headerObject.sizes.reduce( function ( previous, current ) {
  194. return previous * current;
  195. }, 1 );
  196. let base = 10;
  197. if ( headerObject.encoding === 'hex' ) {
  198. base = 16;
  199. }
  200. const result = new headerObject.__array( lengthOfTheResult );
  201. let resultIndex = 0;
  202. let parsingFunction = parseInt;
  203. if ( headerObject.__array === Float32Array || headerObject.__array === Float64Array ) {
  204. parsingFunction = parseFloat;
  205. }
  206. for ( let i = start; i < end; i ++ ) {
  207. value = data[ i ];
  208. //if value is not a space
  209. if ( ( value < 9 || value > 13 ) && value !== 32 ) {
  210. number += String.fromCharCode( value );
  211. } else {
  212. if ( number !== '' ) {
  213. result[ resultIndex ] = parsingFunction( number, base );
  214. resultIndex ++;
  215. }
  216. number = '';
  217. }
  218. }
  219. if ( number !== '' ) {
  220. result[ resultIndex ] = parsingFunction( number, base );
  221. resultIndex ++;
  222. }
  223. return result;
  224. }
  225. const _bytes = scan( 'uchar', data.byteLength );
  226. const _length = _bytes.length;
  227. let _header = null;
  228. let _data_start = 0;
  229. let i;
  230. for ( i = 1; i < _length; i ++ ) {
  231. if ( _bytes[ i - 1 ] == 10 && _bytes[ i ] == 10 ) {
  232. // we found two line breaks in a row
  233. // now we know what the header is
  234. _header = this._parseChars( _bytes, 0, i - 2 );
  235. // this is were the data starts
  236. _data_start = i + 1;
  237. break;
  238. }
  239. }
  240. // parse the header
  241. parseHeader( _header );
  242. _data = _bytes.subarray( _data_start ); // the data without header
  243. if ( headerObject.encoding.substring( 0, 2 ) === 'gz' ) {
  244. // we need to decompress the datastream
  245. // here we start the unzipping and get a typed Uint8Array back
  246. _data = fflate.gunzipSync( new Uint8Array( _data ) );
  247. } else if ( headerObject.encoding === 'ascii' || headerObject.encoding === 'text' || headerObject.encoding === 'txt' || headerObject.encoding === 'hex' ) {
  248. _data = parseDataAsText( _data );
  249. } else if ( headerObject.encoding === 'raw' ) {
  250. //we need to copy the array to create a new array buffer, else we retrieve the original arraybuffer with the header
  251. const _copy = new Uint8Array( _data.length );
  252. for ( let i = 0; i < _data.length; i ++ ) {
  253. _copy[ i ] = _data[ i ];
  254. }
  255. _data = _copy;
  256. }
  257. // .. let's use the underlying array buffer
  258. _data = _data.buffer;
  259. const volume = new Volume();
  260. volume.header = headerObject;
  261. volume.segmentation = this.segmentation;
  262. //
  263. // parse the (unzipped) data to a datastream of the correct type
  264. //
  265. volume.data = new headerObject.__array( _data );
  266. // get the min and max intensities
  267. const min_max = volume.computeMinMax();
  268. const min = min_max[ 0 ];
  269. const max = min_max[ 1 ];
  270. // attach the scalar range to the volume
  271. volume.windowLow = min;
  272. volume.windowHigh = max;
  273. // get the image dimensions
  274. volume.dimensions = [ headerObject.sizes[ 0 ], headerObject.sizes[ 1 ], headerObject.sizes[ 2 ] ];
  275. volume.xLength = volume.dimensions[ 0 ];
  276. volume.yLength = volume.dimensions[ 1 ];
  277. volume.zLength = volume.dimensions[ 2 ];
  278. // Identify axis order in the space-directions matrix from the header if possible.
  279. if ( headerObject.vectors ) {
  280. const xIndex = headerObject.vectors.findIndex( vector => vector[ 0 ] !== 0 );
  281. const yIndex = headerObject.vectors.findIndex( vector => vector[ 1 ] !== 0 );
  282. const zIndex = headerObject.vectors.findIndex( vector => vector[ 2 ] !== 0 );
  283. const axisOrder = [];
  284. if ( xIndex !== yIndex && xIndex !== zIndex && yIndex !== zIndex ) {
  285. axisOrder[ xIndex ] = 'x';
  286. axisOrder[ yIndex ] = 'y';
  287. axisOrder[ zIndex ] = 'z';
  288. } else {
  289. axisOrder[ 0 ] = 'x';
  290. axisOrder[ 1 ] = 'y';
  291. axisOrder[ 2 ] = 'z';
  292. }
  293. volume.axisOrder = axisOrder;
  294. } else {
  295. volume.axisOrder = [ 'x', 'y', 'z' ];
  296. }
  297. // spacing
  298. const spacingX = new Vector3().fromArray( headerObject.vectors[ 0 ] ).length();
  299. const spacingY = new Vector3().fromArray( headerObject.vectors[ 1 ] ).length();
  300. const spacingZ = new Vector3().fromArray( headerObject.vectors[ 2 ] ).length();
  301. volume.spacing = [ spacingX, spacingY, spacingZ ];
  302. // Create IJKtoRAS matrix
  303. volume.matrix = new Matrix4();
  304. const transitionMatrix = new Matrix4();
  305. if ( headerObject.space === 'left-posterior-superior' ) {
  306. transitionMatrix.set(
  307. - 1, 0, 0, 0,
  308. 0, - 1, 0, 0,
  309. 0, 0, 1, 0,
  310. 0, 0, 0, 1
  311. );
  312. } else if ( headerObject.space === 'left-anterior-superior' ) {
  313. transitionMatrix.set(
  314. 1, 0, 0, 0,
  315. 0, 1, 0, 0,
  316. 0, 0, - 1, 0,
  317. 0, 0, 0, 1
  318. );
  319. }
  320. if ( ! headerObject.vectors ) {
  321. volume.matrix.set(
  322. 1, 0, 0, 0,
  323. 0, 1, 0, 0,
  324. 0, 0, 1, 0,
  325. 0, 0, 0, 1 );
  326. } else {
  327. const v = headerObject.vectors;
  328. const ijk_to_transition = new Matrix4().set(
  329. v[ 0 ][ 0 ], v[ 1 ][ 0 ], v[ 2 ][ 0 ], 0,
  330. v[ 0 ][ 1 ], v[ 1 ][ 1 ], v[ 2 ][ 1 ], 0,
  331. v[ 0 ][ 2 ], v[ 1 ][ 2 ], v[ 2 ][ 2 ], 0,
  332. 0, 0, 0, 1
  333. );
  334. const transition_to_ras = new Matrix4().multiplyMatrices( ijk_to_transition, transitionMatrix );
  335. volume.matrix = transition_to_ras;
  336. }
  337. volume.inverseMatrix = new Matrix4();
  338. volume.inverseMatrix.copy( volume.matrix ).invert();
  339. volume.RASDimensions = [
  340. Math.floor( volume.xLength * spacingX ),
  341. Math.floor( volume.yLength * spacingY ),
  342. Math.floor( volume.zLength * spacingZ )
  343. ];
  344. // .. and set the default threshold
  345. // only if the threshold was not already set
  346. if ( volume.lowerThreshold === - Infinity ) {
  347. volume.lowerThreshold = min;
  348. }
  349. if ( volume.upperThreshold === Infinity ) {
  350. volume.upperThreshold = max;
  351. }
  352. return volume;
  353. }
  354. _parseChars( array, start, end ) {
  355. // without borders, use the whole array
  356. if ( start === undefined ) {
  357. start = 0;
  358. }
  359. if ( end === undefined ) {
  360. end = array.length;
  361. }
  362. let output = '';
  363. // create and append the chars
  364. let i = 0;
  365. for ( i = start; i < end; ++ i ) {
  366. output += String.fromCharCode( array[ i ] );
  367. }
  368. return output;
  369. }
  370. }
  371. const _fieldFunctions = {
  372. type: function ( data ) {
  373. switch ( data ) {
  374. case 'uchar':
  375. case 'unsigned char':
  376. case 'uint8':
  377. case 'uint8_t':
  378. this.__array = Uint8Array;
  379. break;
  380. case 'signed char':
  381. case 'int8':
  382. case 'int8_t':
  383. this.__array = Int8Array;
  384. break;
  385. case 'short':
  386. case 'short int':
  387. case 'signed short':
  388. case 'signed short int':
  389. case 'int16':
  390. case 'int16_t':
  391. this.__array = Int16Array;
  392. break;
  393. case 'ushort':
  394. case 'unsigned short':
  395. case 'unsigned short int':
  396. case 'uint16':
  397. case 'uint16_t':
  398. this.__array = Uint16Array;
  399. break;
  400. case 'int':
  401. case 'signed int':
  402. case 'int32':
  403. case 'int32_t':
  404. this.__array = Int32Array;
  405. break;
  406. case 'uint':
  407. case 'unsigned int':
  408. case 'uint32':
  409. case 'uint32_t':
  410. this.__array = Uint32Array;
  411. break;
  412. case 'float':
  413. this.__array = Float32Array;
  414. break;
  415. case 'double':
  416. this.__array = Float64Array;
  417. break;
  418. default:
  419. throw new Error( 'Unsupported NRRD data type: ' + data );
  420. }
  421. return this.type = data;
  422. },
  423. endian: function ( data ) {
  424. return this.endian = data;
  425. },
  426. encoding: function ( data ) {
  427. return this.encoding = data;
  428. },
  429. dimension: function ( data ) {
  430. return this.dim = parseInt( data, 10 );
  431. },
  432. sizes: function ( data ) {
  433. let i;
  434. return this.sizes = ( function () {
  435. const _ref = data.split( /\s+/ );
  436. const _results = [];
  437. for ( let _i = 0, _len = _ref.length; _i < _len; _i ++ ) {
  438. i = _ref[ _i ];
  439. _results.push( parseInt( i, 10 ) );
  440. }
  441. return _results;
  442. } )();
  443. },
  444. space: function ( data ) {
  445. return this.space = data;
  446. },
  447. 'space origin': function ( data ) {
  448. return this.space_origin = data.split( '(' )[ 1 ].split( ')' )[ 0 ].split( ',' );
  449. },
  450. 'space directions': function ( data ) {
  451. let f, v;
  452. const parts = data.match( /\(.*?\)/g );
  453. return this.vectors = ( function () {
  454. const _results = [];
  455. for ( let _i = 0, _len = parts.length; _i < _len; _i ++ ) {
  456. v = parts[ _i ];
  457. _results.push( ( function () {
  458. const _ref = v.slice( 1, - 1 ).split( /,/ );
  459. const _results2 = [];
  460. for ( let _j = 0, _len2 = _ref.length; _j < _len2; _j ++ ) {
  461. f = _ref[ _j ];
  462. _results2.push( parseFloat( f ) );
  463. }
  464. return _results2;
  465. } )() );
  466. }
  467. return _results;
  468. } )();
  469. },
  470. spacings: function ( data ) {
  471. let f;
  472. const parts = data.split( /\s+/ );
  473. return this.spacings = ( function () {
  474. const _results = [];
  475. for ( let _i = 0, _len = parts.length; _i < _len; _i ++ ) {
  476. f = parts[ _i ];
  477. _results.push( parseFloat( f ) );
  478. }
  479. return _results;
  480. } )();
  481. }
  482. };
  483. export { NRRDLoader };