Add and use a method for fast float rounding

Unlike fastf2i, this keeps the result as a float instead of converting to
integer.
This commit is contained in:
Chris Robinson 2018-05-12 00:52:09 -07:00
parent 3867cad94d
commit e787a241c0
3 changed files with 56 additions and 1 deletions

View File

@ -1663,7 +1663,7 @@ static void ApplyDither(ALfloat (*restrict Samples)[BUFFERSIZE], ALuint *dither_
ALuint rng0 = dither_rng(&seed);
ALuint rng1 = dither_rng(&seed);
val += (ALfloat)(rng0*(1.0/UINT_MAX) - rng1*(1.0/UINT_MAX));
samples[i] = fastf2i(val) * invscale;
samples[i] = fast_roundf(val) * invscale;
}
}
*dither_seed = seed;

View File

@ -125,6 +125,7 @@ extern inline ALuint NextPowerOf2(ALuint value);
extern inline size_t RoundUp(size_t value, size_t r);
extern inline ALint fastf2i(ALfloat f);
extern inline int float2int(float f);
extern inline float fast_roundf(float f);
#ifndef __GNUC__
#if defined(HAVE_BITSCANFORWARD64_INTRINSIC)
extern inline int msvc64_ctz64(ALuint64 v);

View File

@ -275,6 +275,60 @@ inline int float2int(float f)
return (ALint)f;
}
/* Rounds a float to the nearest integral value, according to the current
* rounding mode. This is essentially an inlined version of rintf, although
* makes fewer promises (e.g. -0 or -0.25 rounded to 0 may result in +0).
*/
inline float fast_roundf(float f)
{
#if (defined(__GNUC__) || defined(__clang__)) && (defined(__i386__) || defined(__x86_64__)) && \
!defined(__SSE_MATH__)
float out;
__asm__ __volatile__("frndint" : "=t"(out) : "0"(f));
return out;
#else
/* Integral limit, where sub-integral precision is not available for
* floats.
*/
static const float ilim[2] = {
8388608.0f /* 0x1.0p+23 */,
-8388608.0f /* -0x1.0p+23 */
};
uint32_t sign, expo;
union {
float f;
uint32_t i;
} conv;
conv.f = f;
sign = (conv.i>>31)&0x01;
expo = (conv.i>>23)&0xff;
if(UNLIKELY(expo >= 150/*+23*/))
{
/* An exponent (base-2) of 23 or higher is incapable of sub-integral
* precision, so it's already an integral value. We don't need to worry
* about infinity or NaN here.
*/
return f;
}
/* Adding the integral limit to the value (with a matching sign) forces a
* result that has no sub-integral precision, and is consequently forced to
* round to an integral value. Removing the integral limit then restores
* the initial value rounded to the integral. The compiler should not
* optimize this out because of non-associative rules on floating-point
* math (as long as you don't use -fassociative-math,
* -funsafe-math-optimizations, -ffast-math, or -Ofast, in which case this
* may break).
*/
f += ilim[sign];
return f - ilim[sign];
#endif
}
enum DevProbe {
ALL_DEVICE_PROBE,