00001 /* 00002 * The Mana World 00003 * Copyright (C) 2009 The Mana World Development Team 00004 * 00005 * This file is part of The Mana World. 00006 * 00007 * This program is free software; you can redistribute it and/or modify 00008 * it under the terms of the GNU General Public License as published by 00009 * the Free Software Foundation; either version 2 of the License, or 00010 * any later version. 00011 * 00012 * This program is distributed in the hope that it will be useful, 00013 * but WITHOUT ANY WARRANTY; without even the implied warranty of 00014 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 00015 * GNU General Public License for more details. 00016 * 00017 * You should have received a copy of the GNU General Public License 00018 * along with this program; if not, write to the Free Software 00019 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA 00020 */ 00021 00022 #ifndef UTILS_MATHUTILS_H 00023 #define UTILS_MATHUTILS_H 00024 00025 /* A very fast function to calculate the approximate inverse square root of a 00026 * floating point value and a helper function that uses it for getting the 00027 * normal squareroot. For an explanation of the inverse squareroot function 00028 * read: 00029 * http://www.math.purdue.edu/~clomont/Math/Papers/2003/InvSqrt.pdf 00030 * 00031 * Unfortunately the original creator of this function seems to be unknown. 00032 */ 00033 00034 inline float fastInvSqrt(float x) 00035 { 00036 union { int i; float x; } tmp; 00037 float xhalf = 0.5f * x; 00038 tmp.x = x; 00039 tmp.i = 0x5f375a86 - (tmp.i >> 1); 00040 x = tmp.x; 00041 x = x * (1.5f - xhalf * x * x); 00042 return x; 00043 } 00044 00045 inline float fastSqrt(float x) 00046 { 00047 return 1.0f / fastInvSqrt(x); 00048 } 00049 00050 inline float weightedAverage(float n1, float n2, float w) 00051 { 00052 if (w < 0.0f) 00053 return n1; 00054 00055 if (w > 1.0f) 00056 return n2; 00057 00058 return w * n2 + (1.0f - w) * n1; 00059 } 00060 00061 #endif // UTILS_MATHUTILS_H