u_math.h revision 48a0a096f878d1e627226eae520847063473b17f
1/**************************************************************************
2 *
3 * Copyright 2008 Tungsten Graphics, Inc., Cedar Park, Texas.
4 * All Rights Reserved.
5 *
6 * Permission is hereby granted, free of charge, to any person obtaining a
7 * copy of this software and associated documentation files (the
8 * "Software"), to deal in the Software without restriction, including
9 * without limitation the rights to use, copy, modify, merge, publish,
10 * distribute, sub license, and/or sell copies of the Software, and to
11 * permit persons to whom the Software is furnished to do so, subject to
12 * the following conditions:
13 *
14 * The above copyright notice and this permission notice (including the
15 * next paragraph) shall be included in all copies or substantial portions
16 * of the Software.
17 *
18 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
19 * OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
20 * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT.
21 * IN NO EVENT SHALL TUNGSTEN GRAPHICS AND/OR ITS SUPPLIERS BE LIABLE FOR
22 * ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
23 * TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
24 * SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
25 *
26 **************************************************************************/
27
28
29/**
30 * Math utilities and approximations for common math functions.
31 * Reduced precision is usually acceptable in shaders...
32 *
33 * "fast" is used in the names of functions which are low-precision,
34 * or at least lower-precision than the normal C lib functions.
35 */
36
37
38#ifndef U_MATH_H
39#define U_MATH_H
40
41
42#include "pipe/p_compiler.h"
43#include "util/u_debug.h"
44
45
46#ifdef __cplusplus
47extern "C" {
48#endif
49
50
51#if defined(PIPE_SUBSYSTEM_WINDOWS_MINIPORT)
52__inline double ceil(double val)
53{
54   double ceil_val;
55
56   if ((val - (long) val) == 0) {
57      ceil_val = val;
58   }
59   else {
60      if (val > 0) {
61         ceil_val = (long) val + 1;
62      }
63      else {
64         ceil_val = (long) val;
65      }
66   }
67
68   return ceil_val;
69}
70
71#ifndef PIPE_SUBSYSTEM_WINDOWS_CE_OGL
72__inline double floor(double val)
73{
74   double floor_val;
75
76   if ((val - (long) val) == 0) {
77      floor_val = val;
78   }
79   else {
80      if (val > 0) {
81         floor_val = (long) val;
82      }
83      else {
84         floor_val = (long) val - 1;
85      }
86   }
87
88   return floor_val;
89}
90#endif
91
92#pragma function(pow)
93__inline double __cdecl pow(double val, double exponent)
94{
95   /* XXX */
96   assert(0);
97   return 0;
98}
99
100#pragma function(log)
101__inline double __cdecl log(double val)
102{
103   /* XXX */
104   assert(0);
105   return 0;
106}
107
108#pragma function(atan2)
109__inline double __cdecl atan2(double val)
110{
111   /* XXX */
112   assert(0);
113   return 0;
114}
115#else
116#include <math.h>
117#include <stdarg.h>
118#endif
119
120
121#ifndef M_SQRT2
122#define M_SQRT2 1.41421356237309504880
123#endif
124
125
126#if defined(_MSC_VER)
127
128#if _MSC_VER < 1400 && !defined(__cplusplus) || defined(PIPE_SUBSYSTEM_WINDOWS_CE)
129
130static INLINE float cosf( float f )
131{
132   return (float) cos( (double) f );
133}
134
135static INLINE float sinf( float f )
136{
137   return (float) sin( (double) f );
138}
139
140static INLINE float ceilf( float f )
141{
142   return (float) ceil( (double) f );
143}
144
145static INLINE float floorf( float f )
146{
147   return (float) floor( (double) f );
148}
149
150static INLINE float powf( float f, float g )
151{
152   return (float) pow( (double) f, (double) g );
153}
154
155static INLINE float sqrtf( float f )
156{
157   return (float) sqrt( (double) f );
158}
159
160static INLINE float fabsf( float f )
161{
162   return (float) fabs( (double) f );
163}
164
165static INLINE float logf( float f )
166{
167   return (float) log( (double) f );
168}
169
170#else
171/* Work-around an extra semi-colon in VS 2005 logf definition */
172#ifdef logf
173#undef logf
174#define logf(x) ((float)log((double)(x)))
175#endif /* logf */
176
177#define isfinite(x) _finite((double)(x))
178#define isnan(x) _isnan((double)(x))
179#endif /* _MSC_VER < 1400 && !defined(__cplusplus) */
180
181static INLINE double log2( double x )
182{
183   const double invln2 = 1.442695041;
184   return log( x ) * invln2;
185}
186
187static INLINE double
188round(double x)
189{
190   return x >= 0.0 ? floor(x + 0.5) : ceil(x - 0.5);
191}
192
193static INLINE float
194roundf(float x)
195{
196   return x >= 0.0f ? floorf(x + 0.5f) : ceilf(x - 0.5f);
197}
198
199#endif /* _MSC_VER */
200
201
202
203
204
205#define POW2_TABLE_SIZE_LOG2 9
206#define POW2_TABLE_SIZE (1 << POW2_TABLE_SIZE_LOG2)
207#define POW2_TABLE_OFFSET (POW2_TABLE_SIZE/2)
208#define POW2_TABLE_SCALE ((float)(POW2_TABLE_SIZE/2))
209extern float pow2_table[POW2_TABLE_SIZE];
210
211
212/**
213 * Initialize math module.  This should be called before using any
214 * other functions in this module.
215 */
216extern void
217util_init_math(void);
218
219
220union fi {
221   float f;
222   int32_t i;
223   uint32_t ui;
224};
225
226
227/**
228 * Fast version of 2^x
229 * Identity: exp2(a + b) = exp2(a) * exp2(b)
230 * Let ipart = int(x)
231 * Let fpart = x - ipart;
232 * So, exp2(x) = exp2(ipart) * exp2(fpart)
233 * Compute exp2(ipart) with i << ipart
234 * Compute exp2(fpart) with lookup table.
235 */
236static INLINE float
237util_fast_exp2(float x)
238{
239   int32_t ipart;
240   float fpart, mpart;
241   union fi epart;
242
243   if(x > 129.00000f)
244      return 3.402823466e+38f;
245
246   if (x < -126.99999f)
247      return 0.0f;
248
249   ipart = (int32_t) x;
250   fpart = x - (float) ipart;
251
252   /* same as
253    *   epart.f = (float) (1 << ipart)
254    * but faster and without integer overflow for ipart > 31
255    */
256   epart.i = (ipart + 127 ) << 23;
257
258   mpart = pow2_table[POW2_TABLE_OFFSET + (int)(fpart * POW2_TABLE_SCALE)];
259
260   return epart.f * mpart;
261}
262
263
264/**
265 * Fast approximation to exp(x).
266 */
267static INLINE float
268util_fast_exp(float x)
269{
270   const float k = 1.44269f; /* = log2(e) */
271   return util_fast_exp2(k * x);
272}
273
274
275#define LOG2_TABLE_SIZE_LOG2 16
276#define LOG2_TABLE_SCALE (1 << LOG2_TABLE_SIZE_LOG2)
277#define LOG2_TABLE_SIZE (LOG2_TABLE_SCALE + 1)
278extern float log2_table[LOG2_TABLE_SIZE];
279
280
281/**
282 * Fast approximation to log2(x).
283 */
284static INLINE float
285util_fast_log2(float x)
286{
287   union fi num;
288   float epart, mpart;
289   num.f = x;
290   epart = (float)(((num.i & 0x7f800000) >> 23) - 127);
291   /* mpart = log2_table[mantissa*LOG2_TABLE_SCALE + 0.5] */
292   mpart = log2_table[((num.i & 0x007fffff) + (1 << (22 - LOG2_TABLE_SIZE_LOG2))) >> (23 - LOG2_TABLE_SIZE_LOG2)];
293   return epart + mpart;
294}
295
296
297/**
298 * Fast approximation to x^y.
299 */
300static INLINE float
301util_fast_pow(float x, float y)
302{
303   return util_fast_exp2(util_fast_log2(x) * y);
304}
305
306/* Note that this counts zero as a power of two.
307 */
308static INLINE boolean
309util_is_power_of_two( unsigned v )
310{
311   return (v & (v-1)) == 0;
312}
313
314
315/**
316 * Floor(x), returned as int.
317 */
318static INLINE int
319util_ifloor(float f)
320{
321   int ai, bi;
322   double af, bf;
323   union fi u;
324   af = (3 << 22) + 0.5 + (double) f;
325   bf = (3 << 22) + 0.5 - (double) f;
326   u.f = (float) af;  ai = u.i;
327   u.f = (float) bf;  bi = u.i;
328   return (ai - bi) >> 1;
329}
330
331
332/**
333 * Round float to nearest int.
334 */
335static INLINE int
336util_iround(float f)
337{
338#if defined(PIPE_CC_GCC) && defined(PIPE_ARCH_X86)
339   int r;
340   __asm__ ("fistpl %0" : "=m" (r) : "t" (f) : "st");
341   return r;
342#elif defined(PIPE_CC_MSVC) && defined(PIPE_ARCH_X86)
343   int r;
344   _asm {
345      fld f
346      fistp r
347   }
348   return r;
349#else
350   if (f >= 0.0f)
351      return (int) (f + 0.5f);
352   else
353      return (int) (f - 0.5f);
354#endif
355}
356
357
358/**
359 * Approximate floating point comparison
360 */
361static INLINE boolean
362util_is_approx(float a, float b, float tol)
363{
364   return fabs(b - a) <= tol;
365}
366
367
368/**
369 * Test if x is NaN or +/- infinity.
370 */
371static INLINE boolean
372util_is_inf_or_nan(float x)
373{
374   union fi tmp;
375   tmp.f = x;
376   return !(int)((unsigned int)((tmp.i & 0x7fffffff)-0x7f800000) >> 31);
377}
378
379
380/**
381 * Find first bit set in word.  Least significant bit is 1.
382 * Return 0 if no bits set.
383 */
384#if defined(_MSC_VER) && _MSC_VER >= 1300 && (_M_IX86 || _M_AMD64 || _M_IA64)
385unsigned char _BitScanForward(unsigned long* Index, unsigned long Mask);
386#pragma intrinsic(_BitScanForward)
387static INLINE
388unsigned long ffs( unsigned long u )
389{
390   unsigned long i;
391   if (_BitScanForward(&i, u))
392      return i + 1;
393   else
394      return 0;
395}
396#elif defined(PIPE_CC_MSVC) && defined(PIPE_ARCH_X86)
397static INLINE
398unsigned ffs( unsigned u )
399{
400   unsigned i;
401
402   if (u == 0) {
403      return 0;
404   }
405
406   __asm bsf eax, [u]
407   __asm inc eax
408   __asm mov [i], eax
409
410   return i;
411}
412#elif defined(__MINGW32__)
413#define ffs __builtin_ffs
414#endif
415
416
417/* Could also binary search for the highest bit.
418 */
419static INLINE unsigned
420util_unsigned_logbase2(unsigned n)
421{
422   unsigned log2 = 0;
423   while (n >>= 1)
424      ++log2;
425   return log2;
426}
427
428
429/**
430 * Return float bits.
431 */
432static INLINE unsigned
433fui( float f )
434{
435   union fi fi;
436   fi.f = f;
437   return fi.ui;
438}
439
440
441/**
442 * Convert ubyte to float in [0, 1].
443 * XXX a 256-entry lookup table would be slightly faster.
444 */
445static INLINE float
446ubyte_to_float(ubyte ub)
447{
448   return (float) ub * (1.0f / 255.0f);
449}
450
451
452/**
453 * Convert float in [0,1] to ubyte in [0,255] with clamping.
454 */
455static INLINE ubyte
456float_to_ubyte(float f)
457{
458   const int ieee_0996 = 0x3f7f0000;   /* 0.996 or so */
459   union fi tmp;
460
461   tmp.f = f;
462   if (tmp.i < 0) {
463      return (ubyte) 0;
464   }
465   else if (tmp.i >= ieee_0996) {
466      return (ubyte) 255;
467   }
468   else {
469      tmp.f = tmp.f * (255.0f/256.0f) + 32768.0f;
470      return (ubyte) tmp.i;
471   }
472}
473
474static INLINE float
475byte_to_float_tex(int8_t b)
476{
477   return (b == -128) ? -1.0F : b * 1.0F / 127.0F;
478}
479
480static INLINE int8_t
481float_to_byte_tex(float f)
482{
483   return (int8_t) (127.0F * f);
484}
485
486/**
487 * Calc log base 2
488 */
489static INLINE unsigned
490util_logbase2(unsigned n)
491{
492   unsigned log2 = 0;
493   while (n >>= 1)
494      ++log2;
495   return log2;
496}
497
498
499/**
500 * Returns the smallest power of two >= x
501 */
502static INLINE unsigned
503util_next_power_of_two(unsigned x)
504{
505   unsigned i;
506
507   if (x == 0)
508      return 1;
509
510   --x;
511
512   for (i = 1; i < sizeof(unsigned) * 8; i <<= 1)
513      x |= x >> i;
514
515   return x + 1;
516}
517
518
519/**
520 * Return number of bits set in n.
521 */
522static INLINE unsigned
523util_bitcount(unsigned n)
524{
525#if defined(PIPE_CC_GCC)
526   return __builtin_popcount(n);
527#else
528   /* K&R classic bitcount.
529    *
530    * For each iteration, clear the LSB from the bitfield.
531    * Requires only one iteration per set bit, instead of
532    * one iteration per bit less than highest set bit.
533    */
534   unsigned bits = 0;
535   for (bits; n; bits++) {
536      n &= n - 1;
537   }
538   return bits;
539#endif
540}
541
542
543/**
544 * Reverse byte order of a 32 bit word.
545 */
546static INLINE uint32_t
547util_bswap32(uint32_t n)
548{
549#if defined(PIPE_CC_GCC) && (PIPE_CC_GCC_VERSION >= 403)
550   return __builtin_bswap32(n);
551#else
552   return (n >> 24) |
553          ((n >> 8) & 0x0000ff00) |
554          ((n << 8) & 0x00ff0000) |
555          (n << 24);
556#endif
557}
558
559
560/**
561 * Reverse byte order of a 16 bit word.
562 */
563static INLINE uint16_t
564util_bswap16(uint16_t n)
565{
566   return (n >> 8) |
567          (n << 8);
568}
569
570
571/**
572 * Clamp X to [MIN, MAX].
573 * This is a macro to allow float, int, uint, etc. types.
574 */
575#define CLAMP( X, MIN, MAX )  ( (X)<(MIN) ? (MIN) : ((X)>(MAX) ? (MAX) : (X)) )
576
577#define MIN2( A, B )   ( (A)<(B) ? (A) : (B) )
578#define MAX2( A, B )   ( (A)>(B) ? (A) : (B) )
579
580#define MIN3( A, B, C ) ((A) < (B) ? MIN2(A, C) : MIN2(B, C))
581#define MAX3( A, B, C ) ((A) > (B) ? MAX2(A, C) : MAX2(B, C))
582
583#define MIN4( A, B, C, D ) ((A) < (B) ? MIN3(A, C, D) : MIN3(B, C, D))
584#define MAX4( A, B, C, D ) ((A) > (B) ? MAX3(A, C, D) : MAX3(B, C, D))
585
586
587/**
588 * Align a value, only works pot alignemnts.
589 */
590static INLINE int
591align(int value, int alignment)
592{
593   return (value + alignment - 1) & ~(alignment - 1);
594}
595
596/**
597 * Works like align but on npot alignments.
598 */
599static INLINE size_t
600util_align_npot(size_t value, size_t alignment)
601{
602   if (value % alignment)
603      return value + (alignment - (value % alignment));
604   return value;
605}
606
607static INLINE unsigned
608u_minify(unsigned value, unsigned levels)
609{
610    return MAX2(1, value >> levels);
611}
612
613#ifndef COPY_4V
614#define COPY_4V( DST, SRC )         \
615do {                                \
616   (DST)[0] = (SRC)[0];             \
617   (DST)[1] = (SRC)[1];             \
618   (DST)[2] = (SRC)[2];             \
619   (DST)[3] = (SRC)[3];             \
620} while (0)
621#endif
622
623
624#ifndef COPY_4FV
625#define COPY_4FV( DST, SRC )  COPY_4V(DST, SRC)
626#endif
627
628
629#ifndef ASSIGN_4V
630#define ASSIGN_4V( DST, V0, V1, V2, V3 ) \
631do {                                     \
632   (DST)[0] = (V0);                      \
633   (DST)[1] = (V1);                      \
634   (DST)[2] = (V2);                      \
635   (DST)[3] = (V3);                      \
636} while (0)
637#endif
638
639
640static INLINE uint32_t util_unsigned_fixed(float value, unsigned frac_bits)
641{
642   return value < 0 ? 0 : (uint32_t)(value * (1<<frac_bits));
643}
644
645static INLINE int32_t util_signed_fixed(float value, unsigned frac_bits)
646{
647   return (int32_t)(value * (1<<frac_bits));
648}
649
650
651
652#ifdef __cplusplus
653}
654#endif
655
656#endif /* U_MATH_H */
657