RGBELoader.js 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545
  1. /**
  2. * @author Nikos M. / https://github.com/foo123/
  3. */
  4. import {
  5. DataTextureLoader,
  6. DefaultLoadingManager,
  7. FloatType,
  8. HalfFloatType,
  9. LinearEncoding,
  10. LinearFilter,
  11. NearestFilter,
  12. RGBEEncoding,
  13. RGBEFormat,
  14. RGBFormat,
  15. UnsignedByteType
  16. } from "../../../build/three.module.js";
  17. // https://github.com/mrdoob/three.js/issues/5552
  18. // http://en.wikipedia.org/wiki/RGBE_image_format
  19. var RGBELoader = function ( manager ) {
  20. this.manager = ( manager !== undefined ) ? manager : DefaultLoadingManager;
  21. this.type = UnsignedByteType;
  22. };
  23. // extend DataTextureLoader
  24. RGBELoader.prototype = Object.create( DataTextureLoader.prototype );
  25. // adapted from http://www.graphics.cornell.edu/~bjw/rgbe.html
  26. RGBELoader.prototype._parser = function ( buffer ) {
  27. var
  28. /* return codes for rgbe routines */
  29. //RGBE_RETURN_SUCCESS = 0,
  30. RGBE_RETURN_FAILURE = - 1,
  31. /* default error routine. change this to change error handling */
  32. rgbe_read_error = 1,
  33. rgbe_write_error = 2,
  34. rgbe_format_error = 3,
  35. rgbe_memory_error = 4,
  36. rgbe_error = function ( rgbe_error_code, msg ) {
  37. switch ( rgbe_error_code ) {
  38. case rgbe_read_error: console.error( "RGBELoader Read Error: " + ( msg || '' ) );
  39. break;
  40. case rgbe_write_error: console.error( "RGBELoader Write Error: " + ( msg || '' ) );
  41. break;
  42. case rgbe_format_error: console.error( "RGBELoader Bad File Format: " + ( msg || '' ) );
  43. break;
  44. default:
  45. case rgbe_memory_error: console.error( "RGBELoader: Error: " + ( msg || '' ) );
  46. }
  47. return RGBE_RETURN_FAILURE;
  48. },
  49. /* offsets to red, green, and blue components in a data (float) pixel */
  50. //RGBE_DATA_RED = 0,
  51. //RGBE_DATA_GREEN = 1,
  52. //RGBE_DATA_BLUE = 2,
  53. /* number of floats per pixel, use 4 since stored in rgba image format */
  54. //RGBE_DATA_SIZE = 4,
  55. /* flags indicating which fields in an rgbe_header_info are valid */
  56. RGBE_VALID_PROGRAMTYPE = 1,
  57. RGBE_VALID_FORMAT = 2,
  58. RGBE_VALID_DIMENSIONS = 4,
  59. NEWLINE = "\n",
  60. fgets = function ( buffer, lineLimit, consume ) {
  61. lineLimit = ! lineLimit ? 1024 : lineLimit;
  62. var p = buffer.pos,
  63. i = - 1, len = 0, s = '', chunkSize = 128,
  64. chunk = String.fromCharCode.apply( null, new Uint16Array( buffer.subarray( p, p + chunkSize ) ) )
  65. ;
  66. while ( ( 0 > ( i = chunk.indexOf( NEWLINE ) ) ) && ( len < lineLimit ) && ( p < buffer.byteLength ) ) {
  67. s += chunk; len += chunk.length;
  68. p += chunkSize;
  69. chunk += String.fromCharCode.apply( null, new Uint16Array( buffer.subarray( p, p + chunkSize ) ) );
  70. }
  71. if ( - 1 < i ) {
  72. /*for (i=l-1; i>=0; i--) {
  73. byteCode = m.charCodeAt(i);
  74. if (byteCode > 0x7f && byteCode <= 0x7ff) byteLen++;
  75. else if (byteCode > 0x7ff && byteCode <= 0xffff) byteLen += 2;
  76. if (byteCode >= 0xDC00 && byteCode <= 0xDFFF) i--; //trail surrogate
  77. }*/
  78. if ( false !== consume ) buffer.pos += len + i + 1;
  79. return s + chunk.slice( 0, i );
  80. }
  81. return false;
  82. },
  83. /* minimal header reading. modify if you want to parse more information */
  84. RGBE_ReadHeader = function ( buffer ) {
  85. var line, match,
  86. // regexes to parse header info fields
  87. magic_token_re = /^#\?(\S+)$/,
  88. gamma_re = /^\s*GAMMA\s*=\s*(\d+(\.\d+)?)\s*$/,
  89. exposure_re = /^\s*EXPOSURE\s*=\s*(\d+(\.\d+)?)\s*$/,
  90. format_re = /^\s*FORMAT=(\S+)\s*$/,
  91. dimensions_re = /^\s*\-Y\s+(\d+)\s+\+X\s+(\d+)\s*$/,
  92. // RGBE format header struct
  93. header = {
  94. valid: 0, /* indicate which fields are valid */
  95. string: '', /* the actual header string */
  96. comments: '', /* comments found in header */
  97. programtype: 'RGBE', /* listed at beginning of file to identify it after "#?". defaults to "RGBE" */
  98. format: '', /* RGBE format, default 32-bit_rle_rgbe */
  99. gamma: 1.0, /* image has already been gamma corrected with given gamma. defaults to 1.0 (no correction) */
  100. exposure: 1.0, /* a value of 1.0 in an image corresponds to <exposure> watts/steradian/m^2. defaults to 1.0 */
  101. width: 0, height: 0 /* image dimensions, width/height */
  102. };
  103. if ( buffer.pos >= buffer.byteLength || ! ( line = fgets( buffer ) ) ) {
  104. return rgbe_error( rgbe_read_error, "no header found" );
  105. }
  106. /* if you want to require the magic token then uncomment the next line */
  107. if ( ! ( match = line.match( magic_token_re ) ) ) {
  108. return rgbe_error( rgbe_format_error, "bad initial token" );
  109. }
  110. header.valid |= RGBE_VALID_PROGRAMTYPE;
  111. header.programtype = match[ 1 ];
  112. header.string += line + "\n";
  113. while ( true ) {
  114. line = fgets( buffer );
  115. if ( false === line ) break;
  116. header.string += line + "\n";
  117. if ( '#' === line.charAt( 0 ) ) {
  118. header.comments += line + "\n";
  119. continue; // comment line
  120. }
  121. if ( match = line.match( gamma_re ) ) {
  122. header.gamma = parseFloat( match[ 1 ], 10 );
  123. }
  124. if ( match = line.match( exposure_re ) ) {
  125. header.exposure = parseFloat( match[ 1 ], 10 );
  126. }
  127. if ( match = line.match( format_re ) ) {
  128. header.valid |= RGBE_VALID_FORMAT;
  129. header.format = match[ 1 ];//'32-bit_rle_rgbe';
  130. }
  131. if ( match = line.match( dimensions_re ) ) {
  132. header.valid |= RGBE_VALID_DIMENSIONS;
  133. header.height = parseInt( match[ 1 ], 10 );
  134. header.width = parseInt( match[ 2 ], 10 );
  135. }
  136. if ( ( header.valid & RGBE_VALID_FORMAT ) && ( header.valid & RGBE_VALID_DIMENSIONS ) ) break;
  137. }
  138. if ( ! ( header.valid & RGBE_VALID_FORMAT ) ) {
  139. return rgbe_error( rgbe_format_error, "missing format specifier" );
  140. }
  141. if ( ! ( header.valid & RGBE_VALID_DIMENSIONS ) ) {
  142. return rgbe_error( rgbe_format_error, "missing image size specifier" );
  143. }
  144. return header;
  145. },
  146. RGBE_ReadPixels_RLE = function ( buffer, w, h ) {
  147. var data_rgba, offset, pos, count, byteValue,
  148. scanline_buffer, ptr, ptr_end, i, l, off, isEncodedRun,
  149. scanline_width = w, num_scanlines = h, rgbeStart
  150. ;
  151. if (
  152. // run length encoding is not allowed so read flat
  153. ( ( scanline_width < 8 ) || ( scanline_width > 0x7fff ) ) ||
  154. // this file is not run length encoded
  155. ( ( 2 !== buffer[ 0 ] ) || ( 2 !== buffer[ 1 ] ) || ( buffer[ 2 ] & 0x80 ) )
  156. ) {
  157. // return the flat buffer
  158. return new Uint8Array( buffer );
  159. }
  160. if ( scanline_width !== ( ( buffer[ 2 ] << 8 ) | buffer[ 3 ] ) ) {
  161. return rgbe_error( rgbe_format_error, "wrong scanline width" );
  162. }
  163. data_rgba = new Uint8Array( 4 * w * h );
  164. if ( ! data_rgba || ! data_rgba.length ) {
  165. return rgbe_error( rgbe_memory_error, "unable to allocate buffer space" );
  166. }
  167. offset = 0; pos = 0; ptr_end = 4 * scanline_width;
  168. rgbeStart = new Uint8Array( 4 );
  169. scanline_buffer = new Uint8Array( ptr_end );
  170. // read in each successive scanline
  171. while ( ( num_scanlines > 0 ) && ( pos < buffer.byteLength ) ) {
  172. if ( pos + 4 > buffer.byteLength ) {
  173. return rgbe_error( rgbe_read_error );
  174. }
  175. rgbeStart[ 0 ] = buffer[ pos ++ ];
  176. rgbeStart[ 1 ] = buffer[ pos ++ ];
  177. rgbeStart[ 2 ] = buffer[ pos ++ ];
  178. rgbeStart[ 3 ] = buffer[ pos ++ ];
  179. if ( ( 2 != rgbeStart[ 0 ] ) || ( 2 != rgbeStart[ 1 ] ) || ( ( ( rgbeStart[ 2 ] << 8 ) | rgbeStart[ 3 ] ) != scanline_width ) ) {
  180. return rgbe_error( rgbe_format_error, "bad rgbe scanline format" );
  181. }
  182. // read each of the four channels for the scanline into the buffer
  183. // first red, then green, then blue, then exponent
  184. ptr = 0;
  185. while ( ( ptr < ptr_end ) && ( pos < buffer.byteLength ) ) {
  186. count = buffer[ pos ++ ];
  187. isEncodedRun = count > 128;
  188. if ( isEncodedRun ) count -= 128;
  189. if ( ( 0 === count ) || ( ptr + count > ptr_end ) ) {
  190. return rgbe_error( rgbe_format_error, "bad scanline data" );
  191. }
  192. if ( isEncodedRun ) {
  193. // a (encoded) run of the same value
  194. byteValue = buffer[ pos ++ ];
  195. for ( i = 0; i < count; i ++ ) {
  196. scanline_buffer[ ptr ++ ] = byteValue;
  197. }
  198. //ptr += count;
  199. } else {
  200. // a literal-run
  201. scanline_buffer.set( buffer.subarray( pos, pos + count ), ptr );
  202. ptr += count; pos += count;
  203. }
  204. }
  205. // now convert data from buffer into rgba
  206. // first red, then green, then blue, then exponent (alpha)
  207. l = scanline_width; //scanline_buffer.byteLength;
  208. for ( i = 0; i < l; i ++ ) {
  209. off = 0;
  210. data_rgba[ offset ] = scanline_buffer[ i + off ];
  211. off += scanline_width; //1;
  212. data_rgba[ offset + 1 ] = scanline_buffer[ i + off ];
  213. off += scanline_width; //1;
  214. data_rgba[ offset + 2 ] = scanline_buffer[ i + off ];
  215. off += scanline_width; //1;
  216. data_rgba[ offset + 3 ] = scanline_buffer[ i + off ];
  217. offset += 4;
  218. }
  219. num_scanlines --;
  220. }
  221. return data_rgba;
  222. };
  223. var RGBEByteToRGBFloat = function ( sourceArray, sourceOffset, destArray, destOffset ) {
  224. var e = sourceArray[ sourceOffset + 3 ];
  225. var scale = Math.pow( 2.0, e - 128.0 ) / 255.0;
  226. destArray[ destOffset + 0 ] = sourceArray[ sourceOffset + 0 ] * scale;
  227. destArray[ destOffset + 1 ] = sourceArray[ sourceOffset + 1 ] * scale;
  228. destArray[ destOffset + 2 ] = sourceArray[ sourceOffset + 2 ] * scale;
  229. };
  230. var RGBEByteToRGBHalf = ( function () {
  231. // Source: http://gamedev.stackexchange.com/questions/17326/conversion-of-a-number-from-single-precision-floating-point-representation-to-a/17410#17410
  232. var floatView = new Float32Array( 1 );
  233. var int32View = new Int32Array( floatView.buffer );
  234. /* This method is faster than the OpenEXR implementation (very often
  235. * used, eg. in Ogre), with the additional benefit of rounding, inspired
  236. * by James Tursa?s half-precision code. */
  237. function toHalf( val ) {
  238. floatView[ 0 ] = val;
  239. var x = int32View[ 0 ];
  240. var bits = ( x >> 16 ) & 0x8000; /* Get the sign */
  241. var m = ( x >> 12 ) & 0x07ff; /* Keep one extra bit for rounding */
  242. var e = ( x >> 23 ) & 0xff; /* Using int is faster here */
  243. /* If zero, or denormal, or exponent underflows too much for a denormal
  244. * half, return signed zero. */
  245. if ( e < 103 ) return bits;
  246. /* If NaN, return NaN. If Inf or exponent overflow, return Inf. */
  247. if ( e > 142 ) {
  248. bits |= 0x7c00;
  249. /* If exponent was 0xff and one mantissa bit was set, it means NaN,
  250. * not Inf, so make sure we set one mantissa bit too. */
  251. bits |= ( ( e == 255 ) ? 0 : 1 ) && ( x & 0x007fffff );
  252. return bits;
  253. }
  254. /* If exponent underflows but not too much, return a denormal */
  255. if ( e < 113 ) {
  256. m |= 0x0800;
  257. /* Extra rounding may overflow and set mantissa to 0 and exponent
  258. * to 1, which is OK. */
  259. bits |= ( m >> ( 114 - e ) ) + ( ( m >> ( 113 - e ) ) & 1 );
  260. return bits;
  261. }
  262. bits |= ( ( e - 112 ) << 10 ) | ( m >> 1 );
  263. /* Extra rounding. An overflow will set mantissa to 0 and increment
  264. * the exponent, which is OK. */
  265. bits += m & 1;
  266. return bits;
  267. }
  268. return function ( sourceArray, sourceOffset, destArray, destOffset ) {
  269. var e = sourceArray[ sourceOffset + 3 ];
  270. var scale = Math.pow( 2.0, e - 128.0 ) / 255.0;
  271. destArray[ destOffset + 0 ] = toHalf( sourceArray[ sourceOffset + 0 ] * scale );
  272. destArray[ destOffset + 1 ] = toHalf( sourceArray[ sourceOffset + 1 ] * scale );
  273. destArray[ destOffset + 2 ] = toHalf( sourceArray[ sourceOffset + 2 ] * scale );
  274. };
  275. } )();
  276. var byteArray = new Uint8Array( buffer );
  277. byteArray.pos = 0;
  278. var rgbe_header_info = RGBE_ReadHeader( byteArray );
  279. if ( RGBE_RETURN_FAILURE !== rgbe_header_info ) {
  280. var w = rgbe_header_info.width,
  281. h = rgbe_header_info.height,
  282. image_rgba_data = RGBE_ReadPixels_RLE( byteArray.subarray( byteArray.pos ), w, h );
  283. if ( RGBE_RETURN_FAILURE !== image_rgba_data ) {
  284. switch ( this.type ) {
  285. case UnsignedByteType:
  286. var data = image_rgba_data;
  287. var format = RGBEFormat; // handled as THREE.RGBAFormat in shaders
  288. var type = UnsignedByteType;
  289. break;
  290. case FloatType:
  291. var numElements = ( image_rgba_data.length / 4 ) * 3;
  292. var floatArray = new Float32Array( numElements );
  293. for ( var j = 0; j < numElements; j ++ ) {
  294. RGBEByteToRGBFloat( image_rgba_data, j * 4, floatArray, j * 3 );
  295. }
  296. var data = floatArray;
  297. var format = RGBFormat;
  298. var type = FloatType;
  299. break;
  300. case HalfFloatType:
  301. var numElements = ( image_rgba_data.length / 4 ) * 3;
  302. var halfArray = new Uint16Array( numElements );
  303. for ( var j = 0; j < numElements; j ++ ) {
  304. RGBEByteToRGBHalf( image_rgba_data, j * 4, halfArray, j * 3 );
  305. }
  306. var data = halfArray;
  307. var format = RGBFormat;
  308. var type = HalfFloatType;
  309. break;
  310. default:
  311. console.error( 'THREE.RGBELoader: unsupported type: ', this.type );
  312. break;
  313. }
  314. return {
  315. width: w, height: h,
  316. data: data,
  317. header: rgbe_header_info.string,
  318. gamma: rgbe_header_info.gamma,
  319. exposure: rgbe_header_info.exposure,
  320. format: format,
  321. type: type
  322. };
  323. }
  324. }
  325. return null;
  326. };
  327. RGBELoader.prototype.setDataType = function ( value ) {
  328. this.type = value;
  329. return this;
  330. };
  331. RGBELoader.prototype.setType = function ( value ) {
  332. console.warn( 'THREE.RGBELoader: .setType() has been renamed to .setDataType().' );
  333. return this.setDataType( value );
  334. };
  335. RGBELoader.prototype.load = function ( url, onLoad, onProgress, onError ) {
  336. function onLoadCallback( texture, texData ) {
  337. switch ( texture.type ) {
  338. case UnsignedByteType:
  339. texture.encoding = RGBEEncoding;
  340. texture.minFilter = NearestFilter;
  341. texture.magFilter = NearestFilter;
  342. texture.generateMipmaps = false;
  343. texture.flipY = true;
  344. break;
  345. case FloatType:
  346. texture.encoding = LinearEncoding;
  347. texture.minFilter = LinearFilter;
  348. texture.magFilter = LinearFilter;
  349. texture.generateMipmaps = false;
  350. texture.flipY = true;
  351. break;
  352. case HalfFloatType:
  353. texture.encoding = LinearEncoding;
  354. texture.minFilter = LinearFilter;
  355. texture.magFilter = LinearFilter;
  356. texture.generateMipmaps = false;
  357. texture.flipY = true;
  358. break;
  359. }
  360. if ( onLoad ) onLoad( texture, texData );
  361. }
  362. return DataTextureLoader.prototype.load.call( this, url, onLoadCallback, onProgress, onError );
  363. };
  364. export { RGBELoader };