NRRDLoader.js 13 KB

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