NRRDLoader.js 13 KB

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