NRRDLoader.js 12 KB

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