NRRDLoader.js 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643
  1. /*
  2. * three.js NRRD file loader
  3. */
  4. import {
  5. FileLoader,
  6. Loader,
  7. Matrix4,
  8. Vector3
  9. } from "../../../build/three.module.js";
  10. import { Zlib } from "../libs/gunzip.module.min.js";
  11. import { Volume } from "../misc/Volume.js";
  12. var NRRDLoader = function ( manager ) {
  13. Loader.call( this, manager );
  14. };
  15. NRRDLoader.prototype = Object.assign( Object.create( Loader.prototype ), {
  16. constructor: NRRDLoader,
  17. load: function ( url, onLoad, onProgress, onError ) {
  18. var scope = this;
  19. var loader = new FileLoader( scope.manager );
  20. loader.setPath( scope.path );
  21. loader.setResponseType( 'arraybuffer' );
  22. loader.setRequestHeader( scope.requestHeader );
  23. loader.load( url, function ( data ) {
  24. try {
  25. onLoad( scope.parse( data ) );
  26. } catch ( e ) {
  27. if ( onError ) {
  28. onError( e );
  29. } else {
  30. console.error( e );
  31. }
  32. scope.manager.itemError( url );
  33. }
  34. }, onProgress, onError );
  35. },
  36. parse: function ( data ) {
  37. // this parser is largely inspired from the XTK NRRD parser : https://github.com/xtk/X
  38. var _data = data;
  39. var _dataPointer = 0;
  40. var _nativeLittleEndian = new Int8Array( new Int16Array( [ 1 ] ).buffer )[ 0 ] > 0;
  41. var _littleEndian = true;
  42. var headerObject = {};
  43. function scan( type, chunks ) {
  44. if ( chunks === undefined || chunks === null ) {
  45. chunks = 1;
  46. }
  47. var _chunkSize = 1;
  48. var _array_type = Uint8Array;
  49. switch ( type ) {
  50. // 1 byte data types
  51. case 'uchar':
  52. break;
  53. case 'schar':
  54. _array_type = Int8Array;
  55. break;
  56. // 2 byte data types
  57. case 'ushort':
  58. _array_type = Uint16Array;
  59. _chunkSize = 2;
  60. break;
  61. case 'sshort':
  62. _array_type = Int16Array;
  63. _chunkSize = 2;
  64. break;
  65. // 4 byte data types
  66. case 'uint':
  67. _array_type = Uint32Array;
  68. _chunkSize = 4;
  69. break;
  70. case 'sint':
  71. _array_type = Int32Array;
  72. _chunkSize = 4;
  73. break;
  74. case 'float':
  75. _array_type = Float32Array;
  76. _chunkSize = 4;
  77. break;
  78. case 'complex':
  79. _array_type = Float64Array;
  80. _chunkSize = 8;
  81. break;
  82. case 'double':
  83. _array_type = Float64Array;
  84. _chunkSize = 8;
  85. break;
  86. }
  87. // increase the data pointer in-place
  88. var _bytes = new _array_type( _data.slice( _dataPointer,
  89. _dataPointer += chunks * _chunkSize ) );
  90. // if required, flip the endianness of the bytes
  91. if ( _nativeLittleEndian != _littleEndian ) {
  92. // we need to flip here since the format doesn't match the native endianness
  93. _bytes = flipEndianness( _bytes, _chunkSize );
  94. }
  95. if ( chunks == 1 ) {
  96. // if only one chunk was requested, just return one value
  97. return _bytes[ 0 ];
  98. }
  99. // return the byte array
  100. return _bytes;
  101. }
  102. //Flips typed array endianness in-place. Based on https://github.com/kig/DataStream.js/blob/master/DataStream.js.
  103. function flipEndianness( array, chunkSize ) {
  104. var u8 = new Uint8Array( array.buffer, array.byteOffset, array.byteLength );
  105. for ( var i = 0; i < array.byteLength; i += chunkSize ) {
  106. for ( var j = i + chunkSize - 1, k = i; j > k; j --, k ++ ) {
  107. var tmp = u8[ k ];
  108. u8[ k ] = u8[ j ];
  109. u8[ j ] = tmp;
  110. }
  111. }
  112. return array;
  113. }
  114. //parse the header
  115. function parseHeader( header ) {
  116. var data, field, fn, i, l, lines, m, _i, _len;
  117. lines = header.split( /\r?\n/ );
  118. for ( _i = 0, _len = lines.length; _i < _len; _i ++ ) {
  119. l = lines[ _i ];
  120. if ( l.match( /NRRD\d+/ ) ) {
  121. headerObject.isNrrd = true;
  122. } else if ( l.match( /^#/ ) ) {
  123. } else if ( m = l.match( /(.*):(.*)/ ) ) {
  124. field = m[ 1 ].trim();
  125. data = m[ 2 ].trim();
  126. fn = NRRDLoader.prototype.fieldFunctions[ field ];
  127. if ( fn ) {
  128. fn.call( headerObject, data );
  129. } else {
  130. headerObject[ field ] = data;
  131. }
  132. }
  133. }
  134. if ( ! headerObject.isNrrd ) {
  135. throw new Error( 'Not an NRRD file' );
  136. }
  137. if ( headerObject.encoding === 'bz2' || headerObject.encoding === 'bzip2' ) {
  138. throw new Error( 'Bzip is not supported' );
  139. }
  140. if ( ! headerObject.vectors ) {
  141. //if no space direction is set, let's use the identity
  142. headerObject.vectors = [ new Vector3( 1, 0, 0 ), new Vector3( 0, 1, 0 ), new Vector3( 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. headerObject.vectors[ i ].multiplyScalar( headerObject.spacings[ i ] );
  148. }
  149. }
  150. }
  151. }
  152. }
  153. //parse the data when registred as one of this type : 'text', 'ascii', 'txt'
  154. function parseDataAsText( data, start, end ) {
  155. var number = '';
  156. start = start || 0;
  157. end = end || data.length;
  158. var value;
  159. //length of the result is the product of the sizes
  160. var lengthOfTheResult = headerObject.sizes.reduce( function ( previous, current ) {
  161. return previous * current;
  162. }, 1 );
  163. var base = 10;
  164. if ( headerObject.encoding === 'hex' ) {
  165. base = 16;
  166. }
  167. var result = new headerObject.__array( lengthOfTheResult );
  168. var resultIndex = 0;
  169. var parsingFunction = parseInt;
  170. if ( headerObject.__array === Float32Array || headerObject.__array === Float64Array ) {
  171. parsingFunction = parseFloat;
  172. }
  173. for ( var i = start; i < end; i ++ ) {
  174. value = data[ i ];
  175. //if value is not a space
  176. if ( ( value < 9 || value > 13 ) && value !== 32 ) {
  177. number += String.fromCharCode( value );
  178. } else {
  179. if ( number !== '' ) {
  180. result[ resultIndex ] = parsingFunction( number, base );
  181. resultIndex ++;
  182. }
  183. number = '';
  184. }
  185. }
  186. if ( number !== '' ) {
  187. result[ resultIndex ] = parsingFunction( number, base );
  188. resultIndex ++;
  189. }
  190. return result;
  191. }
  192. var _bytes = scan( 'uchar', data.byteLength );
  193. var _length = _bytes.length;
  194. var _header = null;
  195. var _data_start = 0;
  196. var i;
  197. for ( i = 1; i < _length; i ++ ) {
  198. if ( _bytes[ i - 1 ] == 10 && _bytes[ i ] == 10 ) {
  199. // we found two line breaks in a row
  200. // now we know what the header is
  201. _header = this.parseChars( _bytes, 0, i - 2 );
  202. // this is were the data starts
  203. _data_start = i + 1;
  204. break;
  205. }
  206. }
  207. // parse the header
  208. parseHeader( _header );
  209. var _data = _bytes.subarray( _data_start ); // the data without header
  210. if ( headerObject.encoding === 'gzip' || headerObject.encoding === 'gz' ) {
  211. // we need to decompress the datastream
  212. // here we start the unzipping and get a typed Uint8Array back
  213. var inflate = new Zlib.Gunzip( new Uint8Array( _data ) ); // eslint-disable-line no-undef
  214. _data = inflate.decompress();
  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. var _copy = new Uint8Array( _data.length );
  220. for ( var 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. var 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. var min_max = volume.computeMinMax();
  235. var min = min_max[ 0 ];
  236. var 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. // spacing
  246. var spacingX = ( new Vector3( headerObject.vectors[ 0 ][ 0 ], headerObject.vectors[ 0 ][ 1 ],
  247. headerObject.vectors[ 0 ][ 2 ] ) ).length();
  248. var spacingY = ( new Vector3( headerObject.vectors[ 1 ][ 0 ], headerObject.vectors[ 1 ][ 1 ],
  249. headerObject.vectors[ 1 ][ 2 ] ) ).length();
  250. var spacingZ = ( new Vector3( headerObject.vectors[ 2 ][ 0 ], headerObject.vectors[ 2 ][ 1 ],
  251. headerObject.vectors[ 2 ][ 2 ] ) ).length();
  252. volume.spacing = [ spacingX, spacingY, spacingZ ];
  253. // Create IJKtoRAS matrix
  254. volume.matrix = new Matrix4();
  255. var _spaceX = 1;
  256. var _spaceY = 1;
  257. var _spaceZ = 1;
  258. if ( headerObject.space == "left-posterior-superior" ) {
  259. _spaceX = - 1;
  260. _spaceY = - 1;
  261. } else if ( headerObject.space === 'left-anterior-superior' ) {
  262. _spaceX = - 1;
  263. }
  264. if ( ! headerObject.vectors ) {
  265. volume.matrix.set(
  266. _spaceX, 0, 0, 0,
  267. 0, _spaceY, 0, 0,
  268. 0, 0, _spaceZ, 0,
  269. 0, 0, 0, 1 );
  270. } else {
  271. var v = headerObject.vectors;
  272. volume.matrix.set(
  273. _spaceX * v[ 0 ][ 0 ], _spaceX * v[ 1 ][ 0 ], _spaceX * v[ 2 ][ 0 ], 0,
  274. _spaceY * v[ 0 ][ 1 ], _spaceY * v[ 1 ][ 1 ], _spaceY * v[ 2 ][ 1 ], 0,
  275. _spaceZ * v[ 0 ][ 2 ], _spaceZ * v[ 1 ][ 2 ], _spaceZ * v[ 2 ][ 2 ], 0,
  276. 0, 0, 0, 1 );
  277. }
  278. volume.inverseMatrix = new Matrix4();
  279. volume.inverseMatrix.getInverse( volume.matrix );
  280. volume.RASDimensions = ( new Vector3( volume.xLength, volume.yLength, volume.zLength ) ).applyMatrix4( volume.matrix ).round().toArray().map( Math.abs );
  281. // .. and set the default threshold
  282. // only if the threshold was not already set
  283. if ( volume.lowerThreshold === - Infinity ) {
  284. volume.lowerThreshold = min;
  285. }
  286. if ( volume.upperThreshold === Infinity ) {
  287. volume.upperThreshold = max;
  288. }
  289. return volume;
  290. },
  291. parseChars: function ( array, start, end ) {
  292. // without borders, use the whole array
  293. if ( start === undefined ) {
  294. start = 0;
  295. }
  296. if ( end === undefined ) {
  297. end = array.length;
  298. }
  299. var output = '';
  300. // create and append the chars
  301. var i = 0;
  302. for ( i = start; i < end; ++ i ) {
  303. output += String.fromCharCode( array[ i ] );
  304. }
  305. return output;
  306. },
  307. fieldFunctions: {
  308. type: function ( data ) {
  309. switch ( data ) {
  310. case 'uchar':
  311. case 'unsigned char':
  312. case 'uint8':
  313. case 'uint8_t':
  314. this.__array = Uint8Array;
  315. break;
  316. case 'signed char':
  317. case 'int8':
  318. case 'int8_t':
  319. this.__array = Int8Array;
  320. break;
  321. case 'short':
  322. case 'short int':
  323. case 'signed short':
  324. case 'signed short int':
  325. case 'int16':
  326. case 'int16_t':
  327. this.__array = Int16Array;
  328. break;
  329. case 'ushort':
  330. case 'unsigned short':
  331. case 'unsigned short int':
  332. case 'uint16':
  333. case 'uint16_t':
  334. this.__array = Uint16Array;
  335. break;
  336. case 'int':
  337. case 'signed int':
  338. case 'int32':
  339. case 'int32_t':
  340. this.__array = Int32Array;
  341. break;
  342. case 'uint':
  343. case 'unsigned int':
  344. case 'uint32':
  345. case 'uint32_t':
  346. this.__array = Uint32Array;
  347. break;
  348. case 'float':
  349. this.__array = Float32Array;
  350. break;
  351. case 'double':
  352. this.__array = Float64Array;
  353. break;
  354. default:
  355. throw new Error( 'Unsupported NRRD data type: ' + data );
  356. }
  357. return this.type = data;
  358. },
  359. endian: function ( data ) {
  360. return this.endian = data;
  361. },
  362. encoding: function ( data ) {
  363. return this.encoding = data;
  364. },
  365. dimension: function ( data ) {
  366. return this.dim = parseInt( data, 10 );
  367. },
  368. sizes: function ( data ) {
  369. var i;
  370. return this.sizes = ( function () {
  371. var _i, _len, _ref, _results;
  372. _ref = data.split( /\s+/ );
  373. _results = [];
  374. for ( _i = 0, _len = _ref.length; _i < _len; _i ++ ) {
  375. i = _ref[ _i ];
  376. _results.push( parseInt( i, 10 ) );
  377. }
  378. return _results;
  379. } )();
  380. },
  381. space: function ( data ) {
  382. return this.space = data;
  383. },
  384. 'space origin': function ( data ) {
  385. return this.space_origin = data.split( "(" )[ 1 ].split( ")" )[ 0 ].split( "," );
  386. },
  387. 'space directions': function ( data ) {
  388. var f, parts, v;
  389. parts = data.match( /\(.*?\)/g );
  390. return this.vectors = ( function () {
  391. var _i, _len, _results;
  392. _results = [];
  393. for ( _i = 0, _len = parts.length; _i < _len; _i ++ ) {
  394. v = parts[ _i ];
  395. _results.push( ( function () {
  396. var _j, _len2, _ref, _results2;
  397. _ref = v.slice( 1, - 1 ).split( /,/ );
  398. _results2 = [];
  399. for ( _j = 0, _len2 = _ref.length; _j < _len2; _j ++ ) {
  400. f = _ref[ _j ];
  401. _results2.push( parseFloat( f ) );
  402. }
  403. return _results2;
  404. } )() );
  405. }
  406. return _results;
  407. } )();
  408. },
  409. spacings: function ( data ) {
  410. var f, parts;
  411. parts = data.split( /\s+/ );
  412. return this.spacings = ( function () {
  413. var _i, _len, _results = [];
  414. for ( _i = 0, _len = parts.length; _i < _len; _i ++ ) {
  415. f = parts[ _i ];
  416. _results.push( parseFloat( f ) );
  417. }
  418. return _results;
  419. } )();
  420. }
  421. }
  422. } );
  423. export { NRRDLoader };
粤ICP备19079148号