NRRDLoader.js 13 KB

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