3 * Standard C library function wrappers.
5 * Imports are services which the device driver or window system or
6 * operating system provides to the core renderer. The core renderer (Mesa)
7 * will call these functions in order to do memory allocation, simple I/O,
10 * Some drivers will want to override/replace this file with something
11 * specialized, but that'll be rare.
13 * Eventually, I want to move roll the glheader.h file into this.
15 * \todo Functions still needed:
22 * Mesa 3-D graphics library
25 * Copyright (C) 1999-2007 Brian Paul All Rights Reserved.
27 * Permission is hereby granted, free of charge, to any person obtaining a
28 * copy of this software and associated documentation files (the "Software"),
29 * to deal in the Software without restriction, including without limitation
30 * the rights to use, copy, modify, merge, publish, distribute, sublicense,
31 * and/or sell copies of the Software, and to permit persons to whom the
32 * Software is furnished to do so, subject to the following conditions:
34 * The above copyright notice and this permission notice shall be included
35 * in all copies or substantial portions of the Software.
37 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
38 * OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
39 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
40 * BRIAN PAUL BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN
41 * AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
42 * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
59 #define MAXSTRING 4000 /* for vsnprintf() */
62 #define vsnprintf _vsnprintf
63 #elif defined(__IBMC__) || defined(__IBMCPP__) || ( defined(__VMS) && __CRTL_VER < 70312000 )
64 extern int vsnprintf(char *str
, size_t count
, const char *fmt
, va_list arg
);
66 #include "vsnprintf.c"
70 /**********************************************************************/
75 * Allocate aligned memory.
77 * \param bytes number of bytes to allocate.
78 * \param alignment alignment (must be greater than zero).
80 * Allocates extra memory to accommodate rounding up the address for
81 * alignment and to record the real malloc address.
83 * \sa _mesa_align_free().
86 _mesa_align_malloc(size_t bytes
, unsigned long alignment
)
88 #if defined(HAVE_POSIX_MEMALIGN)
90 int err
= posix_memalign(& mem
, alignment
, bytes
);
93 #elif defined(_WIN32) && defined(_MSC_VER)
94 return _aligned_malloc(bytes
, alignment
);
98 ASSERT( alignment
> 0 );
100 ptr
= (uintptr_t) malloc(bytes
+ alignment
+ sizeof(void *));
104 buf
= (ptr
+ alignment
+ sizeof(void *)) & ~(uintptr_t)(alignment
- 1);
105 *(uintptr_t *)(buf
- sizeof(void *)) = ptr
;
108 /* mark the non-aligned area */
109 while ( ptr
< buf
- sizeof(void *) ) {
110 *(unsigned long *)ptr
= 0xcdcdcdcd;
111 ptr
+= sizeof(unsigned long);
116 #endif /* defined(HAVE_POSIX_MEMALIGN) */
120 * Same as _mesa_align_malloc(), but using calloc(1, ) instead of
124 _mesa_align_calloc(size_t bytes
, unsigned long alignment
)
126 #if defined(HAVE_POSIX_MEMALIGN)
129 mem
= _mesa_align_malloc(bytes
, alignment
);
131 (void) memset(mem
, 0, bytes
);
135 #elif defined(_WIN32) && defined(_MSC_VER)
138 mem
= _aligned_malloc(bytes
, alignment
);
140 (void) memset(mem
, 0, bytes
);
147 ASSERT( alignment
> 0 );
149 ptr
= (uintptr_t) calloc(1, bytes
+ alignment
+ sizeof(void *));
153 buf
= (ptr
+ alignment
+ sizeof(void *)) & ~(uintptr_t)(alignment
- 1);
154 *(uintptr_t *)(buf
- sizeof(void *)) = ptr
;
157 /* mark the non-aligned area */
158 while ( ptr
< buf
- sizeof(void *) ) {
159 *(unsigned long *)ptr
= 0xcdcdcdcd;
160 ptr
+= sizeof(unsigned long);
165 #endif /* defined(HAVE_POSIX_MEMALIGN) */
169 * Free memory which was allocated with either _mesa_align_malloc()
170 * or _mesa_align_calloc().
171 * \param ptr pointer to the memory to be freed.
172 * The actual address to free is stored in the word immediately before the
173 * address the client sees.
176 _mesa_align_free(void *ptr
)
178 #if defined(HAVE_POSIX_MEMALIGN)
180 #elif defined(_WIN32) && defined(_MSC_VER)
183 void **cubbyHole
= (void **) ((char *) ptr
- sizeof(void *));
184 void *realAddr
= *cubbyHole
;
186 #endif /* defined(HAVE_POSIX_MEMALIGN) */
190 * Reallocate memory, with alignment.
193 _mesa_align_realloc(void *oldBuffer
, size_t oldSize
, size_t newSize
,
194 unsigned long alignment
)
196 #if defined(_WIN32) && defined(_MSC_VER)
198 return _aligned_realloc(oldBuffer
, newSize
, alignment
);
200 const size_t copySize
= (oldSize
< newSize
) ? oldSize
: newSize
;
201 void *newBuf
= _mesa_align_malloc(newSize
, alignment
);
202 if (newBuf
&& oldBuffer
&& copySize
> 0) {
203 memcpy(newBuf
, oldBuffer
, copySize
);
206 _mesa_align_free(oldBuffer
);
213 /** Reallocate memory */
215 _mesa_realloc(void *oldBuffer
, size_t oldSize
, size_t newSize
)
217 const size_t copySize
= (oldSize
< newSize
) ? oldSize
: newSize
;
218 void *newBuffer
= malloc(newSize
);
219 if (newBuffer
&& oldBuffer
&& copySize
> 0)
220 memcpy(newBuffer
, oldBuffer
, copySize
);
227 * Fill memory with a constant 16bit word.
228 * \param dst destination pointer.
230 * \param n number of words.
233 _mesa_memset16( unsigned short *dst
, unsigned short val
, size_t n
)
242 /**********************************************************************/
246 /** Wrapper around sin() */
253 /** Single precision wrapper around sin() */
257 return (float) sin((double) a
);
260 /** Wrapper around cos() */
267 /** Single precision wrapper around asin() */
271 return (float) asin((double) x
);
274 /** Single precision wrapper around atan() */
278 return (float) atan((double) x
);
281 /** Wrapper around sqrt() */
283 _mesa_sqrtd(double x
)
290 * A High Speed, Low Precision Square Root
291 * by Paul Lalonde and Robert Dawson
292 * from "Graphics Gems", Academic Press, 1990
294 * SPARC implementation of a fast square root by table
296 * SPARC floating point format is as follows:
299 * sign exponent mantissa
301 static short sqrttab
[0x100]; /* declare table of square roots */
304 _mesa_init_sqrt_table(void)
306 #if defined(USE_IEEE) && !defined(DEBUG)
308 fi_type fi
; /* to access the bits of a float in C quickly */
309 /* we use a union defined in glheader.h */
311 for(i
=0; i
<= 0x7f; i
++) {
315 * Build a float with the bit pattern i as mantissa
316 * and an exponent of 0, stored as 127
319 fi
.i
= (i
<< 16) | (127 << 23);
320 fi
.f
= _mesa_sqrtd(fi
.f
);
323 * Take the square root then strip the first 7 bits of
324 * the mantissa into the table
327 sqrttab
[i
] = (fi
.i
& 0x7fffff) >> 16;
330 * Repeat the process, this time with an exponent of
335 fi
.i
= (i
<< 16) | (128 << 23);
337 sqrttab
[i
+0x80] = (fi
.i
& 0x7fffff) >> 16;
340 (void) sqrttab
; /* silence compiler warnings */
341 #endif /*HAVE_FAST_MATH*/
346 * Single precision square root.
349 _mesa_sqrtf( float x
)
351 #if defined(USE_IEEE) && !defined(DEBUG)
353 /* to access the bits of a float in C
354 * we use a union from glheader.h */
356 short e
; /* the exponent */
357 if (x
== 0.0F
) return 0.0F
; /* check for square root of 0 */
359 e
= (num
.i
>> 23) - 127; /* get the exponent - on a SPARC the */
360 /* exponent is stored with 127 added */
361 num
.i
&= 0x7fffff; /* leave only the mantissa */
362 if (e
& 0x01) num
.i
|= 0x800000;
363 /* the exponent is odd so we have to */
364 /* look it up in the second half of */
365 /* the lookup table, so we set the */
367 e
>>= 1; /* divide the exponent by two */
368 /* note that in C the shift */
369 /* operators are sign preserving */
370 /* for signed operands */
371 /* Do the table lookup, based on the quaternary mantissa,
372 * then reconstruct the result back into a float
374 num
.i
= ((sqrttab
[num
.i
>> 16]) << 16) | ((e
+ 127) << 23);
378 return (float) _mesa_sqrtd((double) x
);
384 inv_sqrt - A single precision 1/sqrt routine for IEEE format floats.
385 written by Josh Vanderhoof, based on newsgroup posts by James Van Buskirk
389 _mesa_inv_sqrtf(float n
)
391 #if defined(USE_IEEE) && !defined(DEBUG)
395 #if 0 /* not used, see below -BP */
402 Exponent part of the magic number -
405 1. subtract the bias from the exponent,
407 3. divide by two (rounding towards -inf)
410 Which is the same as subtracting the exponent from 381 and dividing
413 floor(-(x - 127) / 2) + 127 = floor((381 - x) / 2)
419 Significand part of magic number -
421 With the current magic number, "(magic - u.i) >> 1" will give you:
423 for 1 <= u.f <= 2: 1.25 - u.f / 4
424 for 2 <= u.f <= 4: 1.00 - u.f / 8
426 This isn't a bad approximation of 1/sqrt. The maximum difference from
427 1/sqrt will be around .06. After three Newton-Raphson iterations, the
428 maximum difference is less than 4.5e-8. (Which is actually close
429 enough to make the following bias academic...)
431 To get a better approximation you can add a bias to the magic
432 number. For example, if you subtract 1/2 of the maximum difference in
433 the first approximation (.03), you will get the following function:
435 for 1 <= u.f <= 2: 1.22 - u.f / 4
436 for 2 <= u.f <= 3.76: 0.97 - u.f / 8
437 for 3.76 <= u.f <= 4: 0.72 - u.f / 16
438 (The 3.76 to 4 range is where the result is < .5.)
440 This is the closest possible initial approximation, but with a maximum
441 error of 8e-11 after three NR iterations, it is still not perfect. If
442 you subtract 0.0332281 instead of .03, the maximum error will be
443 2.5e-11 after three NR iterations, which should be about as close as
446 for 1 <= u.f <= 2: 1.2167719 - u.f / 4
447 for 2 <= u.f <= 3.73: 0.9667719 - u.f / 8
448 for 3.73 <= u.f <= 4: 0.7167719 - u.f / 16
452 magic
-= (int)(0.0332281 * (1 << 25));
455 u
.i
= (magic
- u
.i
) >> 1;
458 Instead of Newton-Raphson, we use Goldschmidt's algorithm, which
459 allows more parallelism. From what I understand, the parallelism
460 comes at the cost of less precision, because it lets error
461 accumulate across iterations.
476 return x2
* r2
; /* we can stop here, and be conformant -BP */
485 return (float) (1.0 / sqrt(n
));
490 /** Wrapper around pow() */
492 _mesa_pow(double x
, double y
)
499 * Find the first bit set in a word.
504 #if (defined(_WIN32) ) || defined(__IBMC__) || defined(__IBMCPP__)
505 register int bit
= 0;
507 if ((i
& 0xffff) == 0) {
511 if ((i
& 0xff) == 0) {
515 if ((i
& 0xf) == 0) {
519 while ((i
& 1) == 0) {
533 * Find position of first bit set in given value.
534 * XXX Warning: this function can only be used on 64-bit systems!
535 * \return position of least-significant bit set, starting at 1, return zero
539 _mesa_ffsll(int64_t val
)
546 assert(sizeof(val
) == 8);
548 bit
= _mesa_ffs((int32_t)val
);
552 bit
= _mesa_ffs((int32_t)(val
>> 32));
562 * Return number of bits set in given GLuint.
565 _mesa_bitcount(unsigned int n
)
567 #if defined(__GNUC__)
568 return __builtin_popcount(n
);
571 for (bits
= 0; n
> 0; n
= n
>> 1) {
580 * Convert a 4-byte float to a 2-byte half float.
581 * Based on code from:
582 * http://www.opengl.org/discussion_boards/ubb/Forum3/HTML/008786.html
585 _mesa_float_to_half(float val
)
587 const fi_type fi
= {val
};
588 const int flt_m
= fi
.i
& 0x7fffff;
589 const int flt_e
= (fi
.i
>> 23) & 0xff;
590 const int flt_s
= (fi
.i
>> 31) & 0x1;
597 /* handle special cases */
598 if ((flt_e
== 0) && (flt_m
== 0)) {
600 /* m = 0; - already set */
603 else if ((flt_e
== 0) && (flt_m
!= 0)) {
604 /* denorm -- denorm float maps to 0 half */
605 /* m = 0; - already set */
608 else if ((flt_e
== 0xff) && (flt_m
== 0)) {
610 /* m = 0; - already set */
613 else if ((flt_e
== 0xff) && (flt_m
!= 0)) {
620 const int new_exp
= flt_e
- 127;
623 /* m = 0; - already set */
626 else if (new_exp
< -14) {
627 /* this maps to a denorm */
628 unsigned int exp_val
= (unsigned int) (-14 - new_exp
); /* 2^-exp_val*/
633 "float_to_half: logical error in denorm creation!\n");
634 /* m = 0; - already set */
636 case 1: m
= 512 + (flt_m
>> 14); break;
637 case 2: m
= 256 + (flt_m
>> 15); break;
638 case 3: m
= 128 + (flt_m
>> 16); break;
639 case 4: m
= 64 + (flt_m
>> 17); break;
640 case 5: m
= 32 + (flt_m
>> 18); break;
641 case 6: m
= 16 + (flt_m
>> 19); break;
642 case 7: m
= 8 + (flt_m
>> 20); break;
643 case 8: m
= 4 + (flt_m
>> 21); break;
644 case 9: m
= 2 + (flt_m
>> 22); break;
645 case 10: m
= 1; break;
648 else if (new_exp
> 15) {
649 /* map this value to infinity */
650 /* m = 0; - already set */
660 result
= (s
<< 15) | (e
<< 10) | m
;
666 * Convert a 2-byte half float to a 4-byte float.
667 * Based on code from:
668 * http://www.opengl.org/discussion_boards/ubb/Forum3/HTML/008786.html
671 _mesa_half_to_float(GLhalfARB val
)
673 /* XXX could also use a 64K-entry lookup table */
674 const int m
= val
& 0x3ff;
675 const int e
= (val
>> 10) & 0x1f;
676 const int s
= (val
>> 15) & 0x1;
677 int flt_m
, flt_e
, flt_s
;
684 /* handle special cases */
685 if ((e
== 0) && (m
== 0)) {
690 else if ((e
== 0) && (m
!= 0)) {
691 /* denorm -- denorm half will fit in non-denorm single */
692 const float half_denorm
= 1.0f
/ 16384.0f
; /* 2^-14 */
693 float mantissa
= ((float) (m
)) / 1024.0f
;
694 float sign
= s
? -1.0f
: 1.0f
;
695 return sign
* mantissa
* half_denorm
;
697 else if ((e
== 31) && (m
== 0)) {
702 else if ((e
== 31) && (m
!= 0)) {
713 fi
.i
= (flt_s
<< 31) | (flt_e
<< 23) | flt_m
;
721 /**********************************************************************/
722 /** \name Sort & Search */
726 * Wrapper for bsearch().
729 _mesa_bsearch( const void *key
, const void *base
, size_t nmemb
, size_t size
,
730 int (*compar
)(const void *, const void *) )
732 #if defined(_WIN32_WCE)
737 mid
= (char *)base
+ nmemb
* size
;
738 cmp
= (*compar
)(key
, mid
);
742 base
= (char *)mid
+ size
;
748 return bsearch(key
, base
, nmemb
, size
, compar
);
755 /**********************************************************************/
756 /** \name Environment vars */
760 * Wrapper for getenv().
763 _mesa_getenv( const char *var
)
765 #if defined(_XBOX) || defined(_WIN32_WCE)
775 /**********************************************************************/
780 * Implemented using malloc() and strcpy.
781 * Note that NULL is handled accordingly.
784 _mesa_strdup( const char *s
)
787 size_t l
= strlen(s
);
788 char *s2
= (char *) malloc(l
+ 1);
798 /** Wrapper around strtof() */
800 _mesa_strtof( const char *s
, char **end
)
803 static locale_t loc
= NULL
;
805 loc
= newlocale(LC_CTYPE_MASK
, "C", NULL
);
807 return strtof_l(s
, end
, loc
);
808 #elif defined(_ISOC99_SOURCE) || (defined(_XOPEN_SOURCE) && _XOPEN_SOURCE >= 600)
809 return strtof(s
, end
);
811 return (float)strtod(s
, end
);
815 /** Compute simple checksum/hash for a string */
817 _mesa_str_checksum(const char *str
)
819 /* This could probably be much better */
823 for (c
= str
; *c
; c
++, i
++)
824 sum
+= *c
* (i
% 100);
832 /** Wrapper around vsnprintf() */
834 _mesa_snprintf( char *str
, size_t size
, const char *fmt
, ... )
838 va_start( args
, fmt
);
839 r
= vsnprintf( str
, size
, fmt
, args
);
845 /**********************************************************************/
846 /** \name Diagnostics */
850 output_if_debug(const char *prefixString
, const char *outputString
,
853 static int debug
= -1;
855 /* Check the MESA_DEBUG environment variable if it hasn't
856 * been checked yet. We only have to check it once...
859 char *env
= _mesa_getenv("MESA_DEBUG");
861 /* In a debug build, we print warning messages *unless*
862 * MESA_DEBUG is 0. In a non-debug build, we don't
863 * print warning messages *unless* MESA_DEBUG is
864 * set *to any value*.
867 debug
= (env
!= NULL
&& atoi(env
) == 0) ? 0 : 1;
869 debug
= (env
!= NULL
) ? 1 : 0;
873 /* Now only print the string if we're required to do so. */
875 fprintf(stderr
, "%s: %s", prefixString
, outputString
);
877 fprintf(stderr
, "\n");
879 #if defined(_WIN32) && !defined(_WIN32_WCE)
880 /* stderr from windows applications without console is not usually
881 * visible, so communicate with the debugger instead */
884 _mesa_snprintf(buf
, sizeof(buf
), "%s: %s%s", prefixString
, outputString
, newline
? "\n" : "");
885 OutputDebugStringA(buf
);
893 * Return string version of GL error code.
896 error_string( GLenum error
)
900 return "GL_NO_ERROR";
901 case GL_INVALID_VALUE
:
902 return "GL_INVALID_VALUE";
903 case GL_INVALID_ENUM
:
904 return "GL_INVALID_ENUM";
905 case GL_INVALID_OPERATION
:
906 return "GL_INVALID_OPERATION";
907 case GL_STACK_OVERFLOW
:
908 return "GL_STACK_OVERFLOW";
909 case GL_STACK_UNDERFLOW
:
910 return "GL_STACK_UNDERFLOW";
911 case GL_OUT_OF_MEMORY
:
912 return "GL_OUT_OF_MEMORY";
913 case GL_TABLE_TOO_LARGE
:
914 return "GL_TABLE_TOO_LARGE";
915 case GL_INVALID_FRAMEBUFFER_OPERATION_EXT
:
916 return "GL_INVALID_FRAMEBUFFER_OPERATION";
924 * When a new type of error is recorded, print a message describing
925 * previous errors which were accumulated.
928 flush_delayed_errors( GLcontext
*ctx
)
932 if (ctx
->ErrorDebugCount
) {
933 _mesa_snprintf(s
, MAXSTRING
, "%d similar %s errors",
934 ctx
->ErrorDebugCount
,
935 error_string(ctx
->ErrorValue
));
937 output_if_debug("Mesa", s
, GL_TRUE
);
939 ctx
->ErrorDebugCount
= 0;
945 * Report a warning (a recoverable error condition) to stderr if
946 * either DEBUG is defined or the MESA_DEBUG env var is set.
948 * \param ctx GL context.
949 * \param fmtString printf()-like format string.
952 _mesa_warning( GLcontext
*ctx
, const char *fmtString
, ... )
956 va_start( args
, fmtString
);
957 (void) vsnprintf( str
, MAXSTRING
, fmtString
, args
);
961 flush_delayed_errors( ctx
);
963 output_if_debug("Mesa warning", str
, GL_TRUE
);
968 * Report an internal implementation problem.
969 * Prints the message to stderr via fprintf().
971 * \param ctx GL context.
972 * \param fmtString problem description string.
975 _mesa_problem( const GLcontext
*ctx
, const char *fmtString
, ... )
981 va_start( args
, fmtString
);
982 vsnprintf( str
, MAXSTRING
, fmtString
, args
);
985 fprintf(stderr
, "Mesa %s implementation error: %s\n", MESA_VERSION_STRING
, str
);
986 fprintf(stderr
, "Please report at bugzilla.freedesktop.org\n");
991 * Record an OpenGL state error. These usually occur when the user
992 * passes invalid parameters to a GL function.
994 * If debugging is enabled (either at compile-time via the DEBUG macro, or
995 * run-time via the MESA_DEBUG environment variable), report the error with
998 * \param ctx the GL context.
999 * \param error the error value.
1000 * \param fmtString printf() style format string, followed by optional args
1003 _mesa_error( GLcontext
*ctx
, GLenum error
, const char *fmtString
, ... )
1005 static GLint debug
= -1;
1007 /* Check debug environment variable only once:
1010 const char *debugEnv
= _mesa_getenv("MESA_DEBUG");
1013 if (debugEnv
&& strstr(debugEnv
, "silent"))
1026 if (ctx
->ErrorValue
== error
&&
1027 ctx
->ErrorDebugFmtString
== fmtString
) {
1028 ctx
->ErrorDebugCount
++;
1031 char s
[MAXSTRING
], s2
[MAXSTRING
];
1034 flush_delayed_errors( ctx
);
1036 va_start(args
, fmtString
);
1037 vsnprintf(s
, MAXSTRING
, fmtString
, args
);
1040 _mesa_snprintf(s2
, MAXSTRING
, "%s in %s", error_string(error
), s
);
1041 output_if_debug("Mesa: User error", s2
, GL_TRUE
);
1043 ctx
->ErrorDebugFmtString
= fmtString
;
1044 ctx
->ErrorDebugCount
= 0;
1048 _mesa_record_error(ctx
, error
);
1053 * Report debug information. Print error message to stderr via fprintf().
1054 * No-op if DEBUG mode not enabled.
1056 * \param ctx GL context.
1057 * \param fmtString printf()-style format string, followed by optional args.
1060 _mesa_debug( const GLcontext
*ctx
, const char *fmtString
, ... )
1065 va_start(args
, fmtString
);
1066 vsnprintf(s
, MAXSTRING
, fmtString
, args
);
1068 output_if_debug("Mesa", s
, GL_FALSE
);