NRRDLoader.js 13 KB

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