openTRI 0.1
triMath.h
1/*
2Copyright (C) 2000-2006 Tomas Jakobsson.
3
4triMath.h
5*/
6
7#ifndef __TRIMATH_H__
8#define __TRIMATH_H__
9
10#include <math.h>
11#include <time.h>
12#include "triTypes.h"
13
14#define TRI_PI 3.1415926535897932384626433832795028841971693993751058209749445923f
15#define TRI_RAD_TO_DEG(X) ((X) * (180.0f / TRI_PI))
16#define TRI_DEG_TO_RAD(X) ((X) * (TRI_PI / 180.0f))
17#define TRI_EPSILON 0.03125f
18#define TRI_RAND_MAX RAND_MAX
19#define TRI_RAND_MAX_HALF RAND_MAX / 2.0f
20#define TRI_NANMASK (255<<23)
21#define TRI_IS_NAN(X) (((*(triS32*)&X)&BASE_MATH_NANMASK)==BASE_MATH_NANMASK)
22
23/*
24===========
25triMathInit
26===========
27*/
28static inline triBool triMathInit (void)
29{
30 srand (time (NULL));
31 return TRUE;
32}
33
34/*
35============
36triMathBound
37============
38*/
39static inline triFloat triMathBound (const triFloat Min, const triFloat Num, const triFloat Max)
40{
41 if ((Min) < (Max))
42 {
43 if ((Num) < (Min)) return (Min);
44 else if ((Num) > (Max)) return (Max);
45 else return (Num);
46 }
47 else
48 {
49 if ((Num) < (Max)) return (Max);
50 else if ((Num) > (Min)) return (Min);
51 else return (Num);
52 }
53}
54
55/*
56=============
57triMathRandom
58=============
59*/
60static inline triFloat triMathRandom (const triFloat Min, const triFloat Max)
61{
62 return (rand () * (((Max) - (Min)) * (1.0f / (triFloat)TRI_RAND_MAX)) + (Min));
63}
64
65/*
66===========
67triMathRInt
68===========
69*/
70static inline triS32 triMathRInt (const triFloat X)
71{
72 return (triS32)((X) >= 0 ? (X) + 0.5 : (X) - 0.5);
73}
74
75/*
76===========
77triMathWrap
78===========
79*/
80static inline triFloat triMathWrap (const triFloat Min, triFloat Num, const triFloat Max)
81{
82 triFloat Diff;
83
84 if ((Min) < (Max))
85 {
86 Diff = (Max) - (Min);
87
88 while ((Num) < (Min)) (Num) += Diff;
89 while ((Num) > (Max)) (Num) -= Diff;
90 }
91 else
92 {
93 Diff = (Min) - (Max);
94
95 while ((Num) < (Max)) (Num) += Diff;
96 while ((Num) > (Min)) (Num) -= Diff;
97 }
98
99 return (Num);
100}
101
102/*
103==============
104triMathBetween
105==============
106*/
107static inline triBool triMathBetween (const triFloat Min, const triFloat Num, const triFloat Max)
108{
109 if ((Min) < (Max))
110 {
111 if ((Num) < (Min)) return FALSE;
112 else if ((Num) > (Max)) return FALSE;
113 else return TRUE;
114 }
115 else
116 {
117 if ((Num) > (Min)) return FALSE;
118 else if ((Num) < (Max)) return FALSE;
119 else return TRUE;
120 }
121}
122
123/*
124============
125triMathShift
126============
127*/
128static inline void triMathShift (triFloat Num1, triFloat Num2)
129{
130 triFloat Temp;
131
132 Temp = Num1;
133 Num1 = Num2;
134 Num2 = Temp;
135}
136
137/*
138===============
139triMathNextPow2
140===============
141*/
142static inline triU32 triMathNextPow2 (triU32 In)
143{
144 triU32 Out;
145
146 for (Out=2; Out<In; Out<<=1);
147
148 return Out;
149}
150
151#endif // __TRI_MATH__