1 /*
2 * Copyright 2006 The Android Open Source Project
3 *
4 * Use of this source code is governed by a BSD-style license that can be
5 * found in the LICENSE file.
6 */
7
8 #ifndef SkFloatingPoint_DEFINED
9 #define SkFloatingPoint_DEFINED
10
11 #include "include/core/SkTypes.h"
12 #include "include/private/SkFloatBits.h"
13 #include "include/private/SkSafe_math.h"
14 #include <float.h>
15 #include <math.h>
16 #include <cmath>
17 #include <cstring>
18 #include <limits>
19
20
21 #if defined(SK_LEGACY_FLOAT_RSQRT)
22 #if SK_CPU_SSE_LEVEL >= SK_CPU_SSE_LEVEL_SSE1
23 #include <xmmintrin.h>
24 #elif defined(SK_ARM_HAS_NEON)
25 #include <arm_neon.h>
26 #endif
27 #endif
28
29 constexpr float SK_FloatSqrt2 = 1.41421356f;
30 constexpr float SK_FloatPI = 3.14159265f;
31 constexpr double SK_DoublePI = 3.14159265358979323846264338327950288;
32
33 // C++98 cmath std::pow seems to be the earliest portable way to get float pow.
34 // However, on Linux including cmath undefines isfinite.
35 // http://gcc.gnu.org/bugzilla/show_bug.cgi?id=14608
sk_float_pow(float base,float exp)36 static inline float sk_float_pow(float base, float exp) {
37 return powf(base, exp);
38 }
39
40 #define sk_float_sqrt(x) sqrtf(x)
41 #define sk_float_sin(x) sinf(x)
42 #define sk_float_cos(x) cosf(x)
43 #define sk_float_tan(x) tanf(x)
44 #define sk_float_floor(x) floorf(x)
45 #define sk_float_ceil(x) ceilf(x)
46 #define sk_float_trunc(x) truncf(x)
47 #ifdef SK_BUILD_FOR_MAC
48 # define sk_float_acos(x) static_cast<float>(acos(x))
49 # define sk_float_asin(x) static_cast<float>(asin(x))
50 #else
51 # define sk_float_acos(x) acosf(x)
52 # define sk_float_asin(x) asinf(x)
53 #endif
54 #define sk_float_atan2(y,x) atan2f(y,x)
55 #define sk_float_abs(x) fabsf(x)
56 #define sk_float_copysign(x, y) copysignf(x, y)
57 #define sk_float_mod(x,y) fmodf(x,y)
58 #define sk_float_exp(x) expf(x)
59 #define sk_float_log(x) logf(x)
60
sk_float_degrees_to_radians(float degrees)61 constexpr float sk_float_degrees_to_radians(float degrees) {
62 return degrees * (SK_FloatPI / 180);
63 }
64
sk_float_radians_to_degrees(float radians)65 constexpr float sk_float_radians_to_degrees(float radians) {
66 return radians * (180 / SK_FloatPI);
67 }
68
69 #define sk_float_round(x) sk_float_floor((x) + 0.5f)
70
71 // can't find log2f on android, but maybe that just a tool bug?
72 #ifdef SK_BUILD_FOR_ANDROID
sk_float_log2(float x)73 static inline float sk_float_log2(float x) {
74 const double inv_ln_2 = 1.44269504088896;
75 return (float)(log(x) * inv_ln_2);
76 }
77 #else
78 #define sk_float_log2(x) log2f(x)
79 #endif
80
sk_float_isfinite(float x)81 static inline bool sk_float_isfinite(float x) {
82 return SkFloatBits_IsFinite(SkFloat2Bits(x));
83 }
84
sk_floats_are_finite(float a,float b)85 static inline bool sk_floats_are_finite(float a, float b) {
86 return sk_float_isfinite(a) && sk_float_isfinite(b);
87 }
88
sk_floats_are_finite(const float array[],int count)89 static inline bool sk_floats_are_finite(const float array[], int count) {
90 float prod = 0;
91 for (int i = 0; i < count; ++i) {
92 prod *= array[i];
93 }
94 // At this point, prod will either be NaN or 0
95 return prod == 0; // if prod is NaN, this check will return false
96 }
97
sk_float_isinf(float x)98 static inline bool sk_float_isinf(float x) {
99 return SkFloatBits_IsInf(SkFloat2Bits(x));
100 }
101
sk_float_isnan(float x)102 static inline bool sk_float_isnan(float x) {
103 return !(x == x);
104 }
105
106 #define sk_double_isnan(a) sk_float_isnan(a)
107
108 #define SK_MaxS32FitsInFloat 2147483520
109 #define SK_MinS32FitsInFloat -SK_MaxS32FitsInFloat
110
111 #define SK_MaxS64FitsInFloat (SK_MaxS64 >> (63-24) << (63-24)) // 0x7fffff8000000000
112 #define SK_MinS64FitsInFloat -SK_MaxS64FitsInFloat
113
114 /**
115 * Return the closest int for the given float. Returns SK_MaxS32FitsInFloat for NaN.
116 */
sk_float_saturate2int(float x)117 static inline int sk_float_saturate2int(float x) {
118 x = x < SK_MaxS32FitsInFloat ? x : SK_MaxS32FitsInFloat;
119 x = x > SK_MinS32FitsInFloat ? x : SK_MinS32FitsInFloat;
120 return (int)x;
121 }
122
123 /**
124 * Return the closest int for the given double. Returns SK_MaxS32 for NaN.
125 */
sk_double_saturate2int(double x)126 static inline int sk_double_saturate2int(double x) {
127 x = x < SK_MaxS32 ? x : SK_MaxS32;
128 x = x > SK_MinS32 ? x : SK_MinS32;
129 return (int)x;
130 }
131
132 /**
133 * Return the closest int64_t for the given float. Returns SK_MaxS64FitsInFloat for NaN.
134 */
sk_float_saturate2int64(float x)135 static inline int64_t sk_float_saturate2int64(float x) {
136 x = x < SK_MaxS64FitsInFloat ? x : SK_MaxS64FitsInFloat;
137 x = x > SK_MinS64FitsInFloat ? x : SK_MinS64FitsInFloat;
138 return (int64_t)x;
139 }
140
141 #define sk_float_floor2int(x) sk_float_saturate2int(sk_float_floor(x))
142 #define sk_float_round2int(x) sk_float_saturate2int(sk_float_floor((x) + 0.5f))
143 #define sk_float_ceil2int(x) sk_float_saturate2int(sk_float_ceil(x))
144
145 #define sk_float_floor2int_no_saturate(x) (int)sk_float_floor(x)
146 #define sk_float_round2int_no_saturate(x) (int)sk_float_floor((x) + 0.5f)
147 #define sk_float_ceil2int_no_saturate(x) (int)sk_float_ceil(x)
148
149 #define sk_double_floor(x) floor(x)
150 #define sk_double_round(x) floor((x) + 0.5)
151 #define sk_double_ceil(x) ceil(x)
152 #define sk_double_floor2int(x) (int)floor(x)
153 #define sk_double_round2int(x) (int)floor((x) + 0.5)
154 #define sk_double_ceil2int(x) (int)ceil(x)
155
156 // Cast double to float, ignoring any warning about too-large finite values being cast to float.
157 // Clang thinks this is undefined, but it's actually implementation defined to return either
158 // the largest float or infinity (one of the two bracketing representable floats). Good enough!
159 SK_ATTRIBUTE(no_sanitize("float-cast-overflow"))
sk_double_to_float(double x)160 static inline float sk_double_to_float(double x) {
161 return static_cast<float>(x);
162 }
163
164 #define SK_FloatNaN std::numeric_limits<float>::quiet_NaN()
165 #define SK_FloatInfinity (+std::numeric_limits<float>::infinity())
166 #define SK_FloatNegativeInfinity (-std::numeric_limits<float>::infinity())
167
168 #define SK_DoubleNaN std::numeric_limits<double>::quiet_NaN()
169
170 // Returns false if any of the floats are outside of [0...1]
171 // Returns true if count is 0
172 bool sk_floats_are_unit(const float array[], size_t count);
173
174 #if defined(SK_LEGACY_FLOAT_RSQRT)
sk_float_rsqrt_portable(float x)175 static inline float sk_float_rsqrt_portable(float x) {
176 // Get initial estimate.
177 int i;
178 memcpy(&i, &x, 4);
179 i = 0x5F1FFFF9 - (i>>1);
180 float estimate;
181 memcpy(&estimate, &i, 4);
182
183 // One step of Newton's method to refine.
184 const float estimate_sq = estimate*estimate;
185 estimate *= 0.703952253f*(2.38924456f-x*estimate_sq);
186 return estimate;
187 }
188
189 // Fast, approximate inverse square root.
190 // Compare to name-brand "1.0f / sk_float_sqrt(x)". Should be around 10x faster on SSE, 2x on NEON.
sk_float_rsqrt(float x)191 static inline float sk_float_rsqrt(float x) {
192 // We want all this inlined, so we'll inline SIMD and just take the hit when we don't know we've got
193 // it at compile time. This is going to be too fast to productively hide behind a function pointer.
194 //
195 // We do one step of Newton's method to refine the estimates in the NEON and portable paths. No
196 // refinement is faster, but very innacurate. Two steps is more accurate, but slower than 1/sqrt.
197 //
198 // Optimized constants in the portable path courtesy of http://rrrola.wz.cz/inv_sqrt.html
199 #if SK_CPU_SSE_LEVEL >= SK_CPU_SSE_LEVEL_SSE1
200 return _mm_cvtss_f32(_mm_rsqrt_ss(_mm_set_ss(x)));
201 #elif defined(SK_ARM_HAS_NEON)
202 // Get initial estimate.
203 const float32x2_t xx = vdup_n_f32(x); // Clever readers will note we're doing everything 2x.
204 float32x2_t estimate = vrsqrte_f32(xx);
205
206 // One step of Newton's method to refine.
207 const float32x2_t estimate_sq = vmul_f32(estimate, estimate);
208 estimate = vmul_f32(estimate, vrsqrts_f32(xx, estimate_sq));
209 return vget_lane_f32(estimate, 0); // 1 will work fine too; the answer's in both places.
210 #else
211 return sk_float_rsqrt_portable(x);
212 #endif
213 }
214 #else
215
sk_float_rsqrt_portable(float x)216 static inline float sk_float_rsqrt_portable(float x) { return 1.0f / sk_float_sqrt(x); }
sk_float_rsqrt(float x)217 static inline float sk_float_rsqrt (float x) { return 1.0f / sk_float_sqrt(x); }
218
219 #endif
220
221 // Returns the log2 of the provided value, were that value to be rounded up to the next power of 2.
222 // Returns 0 if value <= 0:
223 // Never returns a negative number, even if value is NaN.
224 //
225 // sk_float_nextlog2((-inf..1]) -> 0
226 // sk_float_nextlog2((1..2]) -> 1
227 // sk_float_nextlog2((2..4]) -> 2
228 // sk_float_nextlog2((4..8]) -> 3
229 // ...
sk_float_nextlog2(float x)230 static inline int sk_float_nextlog2(float x) {
231 uint32_t bits = (uint32_t)SkFloat2Bits(x);
232 bits += (1u << 23) - 1u; // Increment the exponent for non-powers-of-2.
233 int exp = ((int32_t)bits >> 23) - 127;
234 return exp & ~(exp >> 31); // Return 0 for negative or denormalized floats, and exponents < 0.
235 }
236
237 // This is the number of significant digits we can print in a string such that when we read that
238 // string back we get the floating point number we expect. The minimum value C requires is 6, but
239 // most compilers support 9
240 #ifdef FLT_DECIMAL_DIG
241 #define SK_FLT_DECIMAL_DIG FLT_DECIMAL_DIG
242 #else
243 #define SK_FLT_DECIMAL_DIG 9
244 #endif
245
246 // IEEE defines how float divide behaves for non-finite values and zero-denoms, but C does not
247 // so we have a helper that suppresses the possible undefined-behavior warnings.
248
249 SK_ATTRIBUTE(no_sanitize("float-divide-by-zero"))
sk_ieee_float_divide(float numer,float denom)250 static inline float sk_ieee_float_divide(float numer, float denom) {
251 return numer / denom;
252 }
253
254 SK_ATTRIBUTE(no_sanitize("float-divide-by-zero"))
sk_ieee_double_divide(double numer,double denom)255 static inline double sk_ieee_double_divide(double numer, double denom) {
256 return numer / denom;
257 }
258
259 // While we clean up divide by zero, we'll replace places that do divide by zero with this TODO.
sk_ieee_float_divide_TODO_IS_DIVIDE_BY_ZERO_SAFE_HERE(float n,float d)260 static inline float sk_ieee_float_divide_TODO_IS_DIVIDE_BY_ZERO_SAFE_HERE(float n, float d) {
261 return sk_ieee_float_divide(n,d);
262 }
263
sk_fmaf(float f,float m,float a)264 static inline float sk_fmaf(float f, float m, float a) {
265 #if defined(FP_FAST_FMA)
266 return std::fmaf(f,m,a);
267 #else
268 return f*m+a;
269 #endif
270 }
271
272 #endif
273