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