1 /* 2 * Copyright (C) 2013 The Android Open Source Project 3 * 4 * Licensed under the Apache License, Version 2.0 (the "License"); 5 * you may not use this file except in compliance with the License. 6 * You may obtain a copy of the License at 7 * 8 * http://www.apache.org/licenses/LICENSE-2.0 9 * 10 * Unless required by applicable law or agreed to in writing, software 11 * distributed under the License is distributed on an "AS IS" BASIS, 12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 * See the License for the specific language governing permissions and 14 * limitations under the License. 15 */ 16 17 #ifndef LE_FX_ENGINE_COMMON_CORE_MATH_H_ 18 #define LE_FX_ENGINE_COMMON_CORE_MATH_H_ 19 20 #include <math.h> 21 #include <algorithm> 22 using ::std::min; 23 using ::std::max; 24 using ::std::fill; 25 using ::std::fill_n;using ::std::lower_bound; 26 #include <cmath> 27 #include <math.h> 28 //using ::std::fpclassify; 29 30 #include "common/core/os.h" 31 #include "common/core/types.h" 32 33 namespace le_fx { 34 namespace math { 35 36 // A fast approximation to log2(.) fast_log2(float val)37inline float fast_log2(float val) { 38 int* const exp_ptr = reinterpret_cast <int *> (&val); 39 int x = *exp_ptr; 40 const int log_2 = ((x >> 23) & 255) - 128; 41 x &= ~(255 << 23); 42 x += 127 << 23; 43 *exp_ptr = x; 44 val = ((-1.0f / 3) * val + 2) * val - 2.0f / 3; 45 return static_cast<float>(val + log_2); 46 } 47 48 // A fast approximation to log(.) fast_log(float val)49inline float fast_log(float val) { 50 return fast_log2(val) * 51 0.693147180559945286226763982995180413126945495605468750f; 52 } 53 54 // An approximation of the exp(.) function using a 5-th order Taylor expansion. 55 // It's pretty accurate between +-0.1 and accurate to 10e-3 between +-1 56 template <typename T> ExpApproximationViaTaylorExpansionOrder5(T x)57inline T ExpApproximationViaTaylorExpansionOrder5(T x) { 58 const T x2 = x * x; 59 const T x3 = x2 * x; 60 const T x4 = x2 * x2; 61 const T x5 = x3 * x2; 62 return 1.0f + x + 0.5f * x2 + 63 0.16666666666666665741480812812369549646973609924316406250f * x3 + 64 0.0416666666666666643537020320309238741174340248107910156250f * x4 + 65 0.008333333333333333217685101601546193705871701240539550781250f * x5; 66 } 67 68 } // namespace math 69 } // namespace le_fx 70 71 // Math functions missing in Android NDK: 72 #if defined(LE_FX_OS_ANDROID) 73 74 namespace std { 75 76 // 77 // Round to the nearest integer: We need this implementation 78 // since std::round is missing on android. 79 // 80 template <typename T> round(const T & x)81inline T round(const T &x) { 82 return static_cast<T>(std::floor(static_cast<double>(x) + 0.5)); 83 } 84 85 } // namespace std 86 87 #endif // LE_FX_OS_ANDROID 88 89 #endif // LE_FX_ENGINE_COMMON_CORE_MATH_H_ 90