NRRDLoader.js 13 KB

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