NRRDLoader.js 14 KB

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