RGBELoader.js 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442
  1. ( function () {
  2. // https://github.com/mrdoob/three.js/issues/5552
  3. // http://en.wikipedia.org/wiki/RGBE_image_format
  4. class RGBELoader extends THREE.DataTextureLoader {
  5. constructor( manager ) {
  6. super( manager );
  7. this.type = THREE.HalfFloatType;
  8. }
  9. // adapted from http://www.graphics.cornell.edu/~bjw/rgbe.html
  10. parse( buffer ) {
  11. const /* return codes for rgbe routines */
  12. //RGBE_RETURN_SUCCESS = 0,
  13. RGBE_RETURN_FAILURE = - 1,
  14. /* default error routine. change this to change error handling */
  15. rgbe_read_error = 1,
  16. rgbe_write_error = 2,
  17. rgbe_format_error = 3,
  18. rgbe_memory_error = 4,
  19. rgbe_error = function ( rgbe_error_code, msg ) {
  20. switch ( rgbe_error_code ) {
  21. case rgbe_read_error:
  22. console.error( 'THREE.RGBELoader Read Error: ' + ( msg || '' ) );
  23. break;
  24. case rgbe_write_error:
  25. console.error( 'THREE.RGBELoader Write Error: ' + ( msg || '' ) );
  26. break;
  27. case rgbe_format_error:
  28. console.error( 'THREE.RGBELoader Bad File Format: ' + ( msg || '' ) );
  29. break;
  30. default:
  31. case rgbe_memory_error:
  32. console.error( 'THREE.RGBELoader: Error: ' + ( msg || '' ) );
  33. }
  34. return RGBE_RETURN_FAILURE;
  35. },
  36. /* offsets to red, green, and blue components in a data (float) pixel */
  37. //RGBE_DATA_RED = 0,
  38. //RGBE_DATA_GREEN = 1,
  39. //RGBE_DATA_BLUE = 2,
  40. /* number of floats per pixel, use 4 since stored in rgba image format */
  41. //RGBE_DATA_SIZE = 4,
  42. /* flags indicating which fields in an rgbe_header_info are valid */
  43. RGBE_VALID_PROGRAMTYPE = 1,
  44. RGBE_VALID_FORMAT = 2,
  45. RGBE_VALID_DIMENSIONS = 4,
  46. NEWLINE = '\n',
  47. fgets = function ( buffer, lineLimit, consume ) {
  48. const chunkSize = 128;
  49. lineLimit = ! lineLimit ? 1024 : lineLimit;
  50. let p = buffer.pos,
  51. i = - 1,
  52. len = 0,
  53. s = '',
  54. chunk = String.fromCharCode.apply( null, new Uint16Array( buffer.subarray( p, p + chunkSize ) ) );
  55. while ( 0 > ( i = chunk.indexOf( NEWLINE ) ) && len < lineLimit && p < buffer.byteLength ) {
  56. s += chunk;
  57. len += chunk.length;
  58. p += chunkSize;
  59. chunk += String.fromCharCode.apply( null, new Uint16Array( buffer.subarray( p, p + chunkSize ) ) );
  60. }
  61. if ( - 1 < i ) {
  62. /*for (i=l-1; i>=0; i--) {
  63. byteCode = m.charCodeAt(i);
  64. if (byteCode > 0x7f && byteCode <= 0x7ff) byteLen++;
  65. else if (byteCode > 0x7ff && byteCode <= 0xffff) byteLen += 2;
  66. if (byteCode >= 0xDC00 && byteCode <= 0xDFFF) i--; //trail surrogate
  67. }*/
  68. if ( false !== consume ) buffer.pos += len + i + 1;
  69. return s + chunk.slice( 0, i );
  70. }
  71. return false;
  72. },
  73. /* minimal header reading. modify if you want to parse more information */
  74. RGBE_ReadHeader = function ( buffer ) {
  75. // regexes to parse header info fields
  76. const magic_token_re = /^#\?(\S+)/,
  77. gamma_re = /^\s*GAMMA\s*=\s*(\d+(\.\d+)?)\s*$/,
  78. exposure_re = /^\s*EXPOSURE\s*=\s*(\d+(\.\d+)?)\s*$/,
  79. format_re = /^\s*FORMAT=(\S+)\s*$/,
  80. dimensions_re = /^\s*\-Y\s+(\d+)\s+\+X\s+(\d+)\s*$/,
  81. // RGBE format header struct
  82. header = {
  83. valid: 0,
  84. /* indicate which fields are valid */
  85. string: '',
  86. /* the actual header string */
  87. comments: '',
  88. /* comments found in header */
  89. programtype: 'RGBE',
  90. /* listed at beginning of file to identify it after "#?". defaults to "RGBE" */
  91. format: '',
  92. /* RGBE format, default 32-bit_rle_rgbe */
  93. gamma: 1.0,
  94. /* image has already been gamma corrected with given gamma. defaults to 1.0 (no correction) */
  95. exposure: 1.0,
  96. /* a value of 1.0 in an image corresponds to <exposure> watts/steradian/m^2. defaults to 1.0 */
  97. width: 0,
  98. height: 0 /* image dimensions, width/height */
  99. };
  100. let line, match;
  101. if ( buffer.pos >= buffer.byteLength || ! ( line = fgets( buffer ) ) ) {
  102. return rgbe_error( rgbe_read_error, 'no header found' );
  103. }
  104. /* if you want to require the magic token then uncomment the next line */
  105. if ( ! ( match = line.match( magic_token_re ) ) ) {
  106. return rgbe_error( rgbe_format_error, 'bad initial token' );
  107. }
  108. header.valid |= RGBE_VALID_PROGRAMTYPE;
  109. header.programtype = match[ 1 ];
  110. header.string += line + '\n';
  111. while ( true ) {
  112. line = fgets( buffer );
  113. if ( false === line ) break;
  114. header.string += line + '\n';
  115. if ( '#' === line.charAt( 0 ) ) {
  116. header.comments += line + '\n';
  117. continue; // comment line
  118. }
  119. if ( match = line.match( gamma_re ) ) {
  120. header.gamma = parseFloat( match[ 1 ] );
  121. }
  122. if ( match = line.match( exposure_re ) ) {
  123. header.exposure = parseFloat( match[ 1 ] );
  124. }
  125. if ( match = line.match( format_re ) ) {
  126. header.valid |= RGBE_VALID_FORMAT;
  127. header.format = match[ 1 ]; //'32-bit_rle_rgbe';
  128. }
  129. if ( match = line.match( dimensions_re ) ) {
  130. header.valid |= RGBE_VALID_DIMENSIONS;
  131. header.height = parseInt( match[ 1 ], 10 );
  132. header.width = parseInt( match[ 2 ], 10 );
  133. }
  134. if ( header.valid & RGBE_VALID_FORMAT && header.valid & RGBE_VALID_DIMENSIONS ) break;
  135. }
  136. if ( ! ( header.valid & RGBE_VALID_FORMAT ) ) {
  137. return rgbe_error( rgbe_format_error, 'missing format specifier' );
  138. }
  139. if ( ! ( header.valid & RGBE_VALID_DIMENSIONS ) ) {
  140. return rgbe_error( rgbe_format_error, 'missing image size specifier' );
  141. }
  142. return header;
  143. },
  144. RGBE_ReadPixels_RLE = function ( buffer, w, h ) {
  145. const scanline_width = w;
  146. if (
  147. // run length encoding is not allowed so read flat
  148. scanline_width < 8 || scanline_width > 0x7fff ||
  149. // this file is not run length encoded
  150. 2 !== buffer[ 0 ] || 2 !== buffer[ 1 ] || buffer[ 2 ] & 0x80 ) {
  151. // return the flat buffer
  152. return new Uint8Array( buffer );
  153. }
  154. if ( scanline_width !== ( buffer[ 2 ] << 8 | buffer[ 3 ] ) ) {
  155. return rgbe_error( rgbe_format_error, 'wrong scanline width' );
  156. }
  157. const data_rgba = new Uint8Array( 4 * w * h );
  158. if ( ! data_rgba.length ) {
  159. return rgbe_error( rgbe_memory_error, 'unable to allocate buffer space' );
  160. }
  161. let offset = 0,
  162. pos = 0;
  163. const ptr_end = 4 * scanline_width;
  164. const rgbeStart = new Uint8Array( 4 );
  165. const scanline_buffer = new Uint8Array( ptr_end );
  166. let num_scanlines = h;
  167. // read in each successive scanline
  168. while ( num_scanlines > 0 && pos < buffer.byteLength ) {
  169. if ( pos + 4 > buffer.byteLength ) {
  170. return rgbe_error( rgbe_read_error );
  171. }
  172. rgbeStart[ 0 ] = buffer[ pos ++ ];
  173. rgbeStart[ 1 ] = buffer[ pos ++ ];
  174. rgbeStart[ 2 ] = buffer[ pos ++ ];
  175. rgbeStart[ 3 ] = buffer[ pos ++ ];
  176. if ( 2 != rgbeStart[ 0 ] || 2 != rgbeStart[ 1 ] || ( rgbeStart[ 2 ] << 8 | rgbeStart[ 3 ] ) != scanline_width ) {
  177. return rgbe_error( rgbe_format_error, 'bad rgbe scanline format' );
  178. }
  179. // read each of the four channels for the scanline into the buffer
  180. // first red, then green, then blue, then exponent
  181. let ptr = 0,
  182. count;
  183. while ( ptr < ptr_end && pos < buffer.byteLength ) {
  184. count = buffer[ pos ++ ];
  185. const isEncodedRun = count > 128;
  186. if ( isEncodedRun ) count -= 128;
  187. if ( 0 === count || ptr + count > ptr_end ) {
  188. return rgbe_error( rgbe_format_error, 'bad scanline data' );
  189. }
  190. if ( isEncodedRun ) {
  191. // a (encoded) run of the same value
  192. const byteValue = buffer[ pos ++ ];
  193. for ( let i = 0; i < count; i ++ ) {
  194. scanline_buffer[ ptr ++ ] = byteValue;
  195. }
  196. //ptr += count;
  197. } else {
  198. // a literal-run
  199. scanline_buffer.set( buffer.subarray( pos, pos + count ), ptr );
  200. ptr += count;
  201. pos += count;
  202. }
  203. }
  204. // now convert data from buffer into rgba
  205. // first red, then green, then blue, then exponent (alpha)
  206. const l = scanline_width; //scanline_buffer.byteLength;
  207. for ( let i = 0; i < l; i ++ ) {
  208. let off = 0;
  209. data_rgba[ offset ] = scanline_buffer[ i + off ];
  210. off += scanline_width; //1;
  211. data_rgba[ offset + 1 ] = scanline_buffer[ i + off ];
  212. off += scanline_width; //1;
  213. data_rgba[ offset + 2 ] = scanline_buffer[ i + off ];
  214. off += scanline_width; //1;
  215. data_rgba[ offset + 3 ] = scanline_buffer[ i + off ];
  216. offset += 4;
  217. }
  218. num_scanlines --;
  219. }
  220. return data_rgba;
  221. };
  222. const RGBEByteToRGBFloat = function ( sourceArray, sourceOffset, destArray, destOffset ) {
  223. const e = sourceArray[ sourceOffset + 3 ];
  224. const scale = Math.pow( 2.0, e - 128.0 ) / 255.0;
  225. destArray[ destOffset + 0 ] = sourceArray[ sourceOffset + 0 ] * scale;
  226. destArray[ destOffset + 1 ] = sourceArray[ sourceOffset + 1 ] * scale;
  227. destArray[ destOffset + 2 ] = sourceArray[ sourceOffset + 2 ] * scale;
  228. destArray[ destOffset + 3 ] = 1;
  229. };
  230. const RGBEByteToRGBHalf = function ( sourceArray, sourceOffset, destArray, destOffset ) {
  231. const e = sourceArray[ sourceOffset + 3 ];
  232. const scale = Math.pow( 2.0, e - 128.0 ) / 255.0;
  233. // clamping to 65504, the maximum representable value in float16
  234. destArray[ destOffset + 0 ] = THREE.DataUtils.toHalfFloat( Math.min( sourceArray[ sourceOffset + 0 ] * scale, 65504 ) );
  235. destArray[ destOffset + 1 ] = THREE.DataUtils.toHalfFloat( Math.min( sourceArray[ sourceOffset + 1 ] * scale, 65504 ) );
  236. destArray[ destOffset + 2 ] = THREE.DataUtils.toHalfFloat( Math.min( sourceArray[ sourceOffset + 2 ] * scale, 65504 ) );
  237. destArray[ destOffset + 3 ] = THREE.DataUtils.toHalfFloat( 1 );
  238. };
  239. const byteArray = new Uint8Array( buffer );
  240. byteArray.pos = 0;
  241. const rgbe_header_info = RGBE_ReadHeader( byteArray );
  242. if ( RGBE_RETURN_FAILURE !== rgbe_header_info ) {
  243. const w = rgbe_header_info.width,
  244. h = rgbe_header_info.height,
  245. image_rgba_data = RGBE_ReadPixels_RLE( byteArray.subarray( byteArray.pos ), w, h );
  246. if ( RGBE_RETURN_FAILURE !== image_rgba_data ) {
  247. let data, type;
  248. let numElements;
  249. switch ( this.type ) {
  250. case THREE.FloatType:
  251. numElements = image_rgba_data.length / 4;
  252. const floatArray = new Float32Array( numElements * 4 );
  253. for ( let j = 0; j < numElements; j ++ ) {
  254. RGBEByteToRGBFloat( image_rgba_data, j * 4, floatArray, j * 4 );
  255. }
  256. data = floatArray;
  257. type = THREE.FloatType;
  258. break;
  259. case THREE.HalfFloatType:
  260. numElements = image_rgba_data.length / 4;
  261. const halfArray = new Uint16Array( numElements * 4 );
  262. for ( let j = 0; j < numElements; j ++ ) {
  263. RGBEByteToRGBHalf( image_rgba_data, j * 4, halfArray, j * 4 );
  264. }
  265. data = halfArray;
  266. type = THREE.HalfFloatType;
  267. break;
  268. default:
  269. console.error( 'THREE.RGBELoader: unsupported type: ', this.type );
  270. break;
  271. }
  272. return {
  273. width: w,
  274. height: h,
  275. data: data,
  276. header: rgbe_header_info.string,
  277. gamma: rgbe_header_info.gamma,
  278. exposure: rgbe_header_info.exposure,
  279. type: type
  280. };
  281. }
  282. }
  283. return null;
  284. }
  285. setDataType( value ) {
  286. this.type = value;
  287. return this;
  288. }
  289. load( url, onLoad, onProgress, onError ) {
  290. function onLoadCallback( texture, texData ) {
  291. switch ( texture.type ) {
  292. case THREE.FloatType:
  293. case THREE.HalfFloatType:
  294. texture.encoding = THREE.LinearEncoding;
  295. texture.minFilter = THREE.LinearFilter;
  296. texture.magFilter = THREE.LinearFilter;
  297. texture.generateMipmaps = false;
  298. texture.flipY = true;
  299. break;
  300. }
  301. if ( onLoad ) onLoad( texture, texData );
  302. }
  303. return super.load( url, onLoadCallback, onProgress, onError );
  304. }
  305. }
  306. THREE.RGBELoader = RGBELoader;
  307. } )();