HalfFloat.h 7.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208
  1. // Jolt Physics Library (https://github.com/jrouwe/JoltPhysics)
  2. // SPDX-FileCopyrightText: 2021 Jorrit Rouwe
  3. // SPDX-License-Identifier: MIT
  4. #pragma once
  5. #include <Jolt/Math/Vec4.h>
  6. #include <Jolt/Core/FPException.h>
  7. JPH_NAMESPACE_BEGIN
  8. using HalfFloat = uint16;
  9. // Define half float constant values
  10. static constexpr HalfFloat HALF_FLT_MAX = 0x7bff;
  11. static constexpr HalfFloat HALF_FLT_MAX_NEGATIVE = 0xfbff;
  12. static constexpr HalfFloat HALF_FLT_INF = 0x7c00;
  13. static constexpr HalfFloat HALF_FLT_INF_NEGATIVE = 0xfc00;
  14. static constexpr HalfFloat HALF_FLT_NANQ = 0x7e00;
  15. static constexpr HalfFloat HALF_FLT_NANQ_NEGATIVE = 0xfe00;
  16. namespace HalfFloatConversion {
  17. // Layout of a float
  18. static constexpr int FLOAT_SIGN_POS = 31;
  19. static constexpr int FLOAT_EXPONENT_POS = 23;
  20. static constexpr int FLOAT_EXPONENT_BITS = 8;
  21. static constexpr int FLOAT_EXPONENT_MASK = (1 << FLOAT_EXPONENT_BITS) - 1;
  22. static constexpr int FLOAT_EXPONENT_BIAS = 127;
  23. static constexpr int FLOAT_MANTISSA_BITS = 23;
  24. static constexpr int FLOAT_MANTISSA_MASK = (1 << FLOAT_MANTISSA_BITS) - 1;
  25. static constexpr int FLOAT_EXPONENT_AND_MANTISSA_MASK = FLOAT_MANTISSA_MASK + (FLOAT_EXPONENT_MASK << FLOAT_EXPONENT_POS);
  26. // Layout of half float
  27. static constexpr int HALF_FLT_SIGN_POS = 15;
  28. static constexpr int HALF_FLT_EXPONENT_POS = 10;
  29. static constexpr int HALF_FLT_EXPONENT_BITS = 5;
  30. static constexpr int HALF_FLT_EXPONENT_MASK = (1 << HALF_FLT_EXPONENT_BITS) - 1;
  31. static constexpr int HALF_FLT_EXPONENT_BIAS = 15;
  32. static constexpr int HALF_FLT_MANTISSA_BITS = 10;
  33. static constexpr int HALF_FLT_MANTISSA_MASK = (1 << HALF_FLT_MANTISSA_BITS) - 1;
  34. static constexpr int HALF_FLT_EXPONENT_AND_MANTISSA_MASK = HALF_FLT_MANTISSA_MASK + (HALF_FLT_EXPONENT_MASK << HALF_FLT_EXPONENT_POS);
  35. /// Define half-float rounding modes
  36. enum ERoundingMode
  37. {
  38. ROUND_TO_NEG_INF, ///< Round to negative infinity
  39. ROUND_TO_POS_INF, ///< Round to positive infinity
  40. ROUND_TO_NEAREST, ///< Round to nearest value
  41. };
  42. /// Convert a float (32-bits) to a half float (16-bits), fallback version when no intrinsics available
  43. template <int RoundingMode>
  44. inline HalfFloat FromFloatFallback(float inV)
  45. {
  46. // Reinterpret the float as an uint32
  47. uint32 value = BitCast<uint32>(inV);
  48. // Extract exponent
  49. uint32 exponent = (value >> FLOAT_EXPONENT_POS) & FLOAT_EXPONENT_MASK;
  50. // Extract mantissa
  51. uint32 mantissa = value & FLOAT_MANTISSA_MASK;
  52. // Extract the sign and move it into the right spot for the half float (so we can just or it in at the end)
  53. HalfFloat hf_sign = HalfFloat(value >> (FLOAT_SIGN_POS - HALF_FLT_SIGN_POS)) & (1 << HALF_FLT_SIGN_POS);
  54. // Check NaN or INF
  55. if (exponent == FLOAT_EXPONENT_MASK) // NaN or INF
  56. return hf_sign | (mantissa == 0? HALF_FLT_INF : HALF_FLT_NANQ);
  57. // Rebias the exponent for half floats
  58. int rebiased_exponent = int(exponent) - FLOAT_EXPONENT_BIAS + HALF_FLT_EXPONENT_BIAS;
  59. // Check overflow to infinity
  60. if (rebiased_exponent >= HALF_FLT_EXPONENT_MASK)
  61. {
  62. bool round_up = RoundingMode == ROUND_TO_NEAREST || (hf_sign == 0) == (RoundingMode == ROUND_TO_POS_INF);
  63. return hf_sign | (round_up? HALF_FLT_INF : HALF_FLT_MAX);
  64. }
  65. // Check underflow to zero
  66. if (rebiased_exponent < -HALF_FLT_MANTISSA_BITS)
  67. {
  68. bool round_up = RoundingMode != ROUND_TO_NEAREST && (hf_sign == 0) == (RoundingMode == ROUND_TO_POS_INF) && (value & FLOAT_EXPONENT_AND_MANTISSA_MASK) != 0;
  69. return hf_sign | (round_up? 1 : 0);
  70. }
  71. HalfFloat hf_exponent;
  72. int shift;
  73. if (rebiased_exponent <= 0)
  74. {
  75. // Underflow to denormalized number
  76. hf_exponent = 0;
  77. mantissa |= 1 << FLOAT_MANTISSA_BITS; // Add the implicit 1 bit to the mantissa
  78. shift = FLOAT_MANTISSA_BITS - HALF_FLT_MANTISSA_BITS + 1 - rebiased_exponent;
  79. }
  80. else
  81. {
  82. // Normal half float
  83. hf_exponent = HalfFloat(rebiased_exponent << HALF_FLT_EXPONENT_POS);
  84. shift = FLOAT_MANTISSA_BITS - HALF_FLT_MANTISSA_BITS;
  85. }
  86. // Compose the half float
  87. HalfFloat hf_mantissa = HalfFloat(mantissa >> shift);
  88. HalfFloat hf = hf_sign | hf_exponent | hf_mantissa;
  89. // Calculate the remaining bits that we're discarding
  90. uint remainder = mantissa & ((1 << shift) - 1);
  91. if constexpr (RoundingMode == ROUND_TO_NEAREST)
  92. {
  93. // Round to nearest
  94. uint round_threshold = 1 << (shift - 1);
  95. if (remainder > round_threshold // Above threshold, we must always round
  96. || (remainder == round_threshold && (hf_mantissa & 1))) // When equal, round to nearest even
  97. hf++; // May overflow to infinity
  98. }
  99. else
  100. {
  101. // Round up or down (truncate) depending on the rounding mode
  102. bool round_up = (hf_sign == 0) == (RoundingMode == ROUND_TO_POS_INF) && remainder != 0;
  103. if (round_up)
  104. hf++; // May overflow to infinity
  105. }
  106. return hf;
  107. }
  108. /// Convert a float (32-bits) to a half float (16-bits)
  109. template <int RoundingMode>
  110. JPH_INLINE HalfFloat FromFloat(float inV)
  111. {
  112. #ifdef JPH_USE_F16C
  113. FPExceptionDisableOverflow disable_overflow;
  114. JPH_UNUSED(disable_overflow);
  115. union
  116. {
  117. __m128i u128;
  118. HalfFloat u16[8];
  119. } hf;
  120. __m128 val = _mm_load_ss(&inV);
  121. switch (RoundingMode)
  122. {
  123. case ROUND_TO_NEG_INF:
  124. hf.u128 = _mm_cvtps_ph(val, _MM_FROUND_TO_NEG_INF);
  125. break;
  126. case ROUND_TO_POS_INF:
  127. hf.u128 = _mm_cvtps_ph(val, _MM_FROUND_TO_POS_INF);
  128. break;
  129. case ROUND_TO_NEAREST:
  130. hf.u128 = _mm_cvtps_ph(val, _MM_FROUND_TO_NEAREST_INT);
  131. break;
  132. }
  133. return hf.u16[0];
  134. #else
  135. return FromFloatFallback<RoundingMode>(inV);
  136. #endif
  137. }
  138. /// Convert 4 half floats (lower 64 bits) to floats, fallback version when no intrinsics available
  139. inline Vec4 ToFloatFallback(UVec4Arg inValue)
  140. {
  141. // Unpack half floats to 4 uint32's
  142. UVec4 value = inValue.Expand4Uint16Lo();
  143. // Normal half float path, extract the exponent and mantissa, shift them into place and update the exponent bias
  144. UVec4 exponent_mantissa = UVec4::sAnd(value, UVec4::sReplicate(HALF_FLT_EXPONENT_AND_MANTISSA_MASK)).LogicalShiftLeft<FLOAT_EXPONENT_POS - HALF_FLT_EXPONENT_POS>() + UVec4::sReplicate((FLOAT_EXPONENT_BIAS - HALF_FLT_EXPONENT_BIAS) << FLOAT_EXPONENT_POS);
  145. // Denormalized half float path, renormalize the float
  146. UVec4 exponent_mantissa_denormalized = ((exponent_mantissa + UVec4::sReplicate(1 << FLOAT_EXPONENT_POS)).ReinterpretAsFloat() - UVec4::sReplicate((FLOAT_EXPONENT_BIAS - HALF_FLT_EXPONENT_BIAS + 1) << FLOAT_EXPONENT_POS).ReinterpretAsFloat()).ReinterpretAsInt();
  147. // NaN / INF path, set all exponent bits
  148. UVec4 exponent_mantissa_nan_inf = UVec4::sOr(exponent_mantissa, UVec4::sReplicate(FLOAT_EXPONENT_MASK << FLOAT_EXPONENT_POS));
  149. // Get the exponent to determine which of the paths we should take
  150. UVec4 exponent_mask = UVec4::sReplicate(HALF_FLT_EXPONENT_MASK << HALF_FLT_EXPONENT_POS);
  151. UVec4 exponent = UVec4::sAnd(value, exponent_mask);
  152. UVec4 is_denormalized = UVec4::sEquals(exponent, UVec4::sZero());
  153. UVec4 is_nan_inf = UVec4::sEquals(exponent, exponent_mask);
  154. // Select the correct result
  155. UVec4 result_exponent_mantissa = UVec4::sSelect(UVec4::sSelect(exponent_mantissa, exponent_mantissa_nan_inf, is_nan_inf), exponent_mantissa_denormalized, is_denormalized);
  156. // Extract the sign bit and shift it to the left
  157. UVec4 sign = UVec4::sAnd(value, UVec4::sReplicate(1 << HALF_FLT_SIGN_POS)).LogicalShiftLeft<FLOAT_SIGN_POS - HALF_FLT_SIGN_POS>();
  158. // Construct the float
  159. return UVec4::sOr(sign, result_exponent_mantissa).ReinterpretAsFloat();
  160. }
  161. /// Convert 4 half floats (lower 64 bits) to floats
  162. JPH_INLINE Vec4 ToFloat(UVec4Arg inValue)
  163. {
  164. #if defined(JPH_USE_F16C)
  165. return _mm_cvtph_ps(inValue.mValue);
  166. #elif defined(JPH_USE_NEON)
  167. return vcvt_f32_f16(vreinterpret_f16_u32(vget_low_u32(inValue.mValue)));
  168. #else
  169. return ToFloatFallback(inValue);
  170. #endif
  171. }
  172. } // HalfFloatConversion
  173. JPH_NAMESPACE_END