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
);
94 #elif defined(_WIN32) && defined(_MSC_VER)
95 return _aligned_malloc(bytes
, alignment
);
99 ASSERT( alignment
> 0 );
101 ptr
= (uintptr_t) malloc(bytes
+ alignment
+ sizeof(void *));
105 buf
= (ptr
+ alignment
+ sizeof(void *)) & ~(uintptr_t)(alignment
- 1);
106 *(uintptr_t *)(buf
- sizeof(void *)) = ptr
;
109 /* mark the non-aligned area */
110 while ( ptr
< buf
- sizeof(void *) ) {
111 *(unsigned long *)ptr
= 0xcdcdcdcd;
112 ptr
+= sizeof(unsigned long);
117 #endif /* defined(HAVE_POSIX_MEMALIGN) */
121 * Same as _mesa_align_malloc(), but using calloc(1, ) instead of
125 _mesa_align_calloc(size_t bytes
, unsigned long alignment
)
127 #if defined(HAVE_POSIX_MEMALIGN)
130 mem
= _mesa_align_malloc(bytes
, alignment
);
132 (void) memset(mem
, 0, bytes
);
136 #elif defined(_WIN32) && defined(_MSC_VER)
139 mem
= _aligned_malloc(bytes
, alignment
);
141 (void) memset(mem
, 0, bytes
);
148 ASSERT( alignment
> 0 );
150 ptr
= (uintptr_t) calloc(1, bytes
+ alignment
+ sizeof(void *));
154 buf
= (ptr
+ alignment
+ sizeof(void *)) & ~(uintptr_t)(alignment
- 1);
155 *(uintptr_t *)(buf
- sizeof(void *)) = ptr
;
158 /* mark the non-aligned area */
159 while ( ptr
< buf
- sizeof(void *) ) {
160 *(unsigned long *)ptr
= 0xcdcdcdcd;
161 ptr
+= sizeof(unsigned long);
166 #endif /* defined(HAVE_POSIX_MEMALIGN) */
170 * Free memory which was allocated with either _mesa_align_malloc()
171 * or _mesa_align_calloc().
172 * \param ptr pointer to the memory to be freed.
173 * The actual address to free is stored in the word immediately before the
174 * address the client sees.
177 _mesa_align_free(void *ptr
)
179 #if defined(HAVE_POSIX_MEMALIGN)
181 #elif defined(_WIN32) && defined(_MSC_VER)
184 void **cubbyHole
= (void **) ((char *) ptr
- sizeof(void *));
185 void *realAddr
= *cubbyHole
;
187 #endif /* defined(HAVE_POSIX_MEMALIGN) */
191 * Reallocate memory, with alignment.
194 _mesa_align_realloc(void *oldBuffer
, size_t oldSize
, size_t newSize
,
195 unsigned long alignment
)
197 #if defined(_WIN32) && defined(_MSC_VER)
199 return _aligned_realloc(oldBuffer
, newSize
, alignment
);
201 const size_t copySize
= (oldSize
< newSize
) ? oldSize
: newSize
;
202 void *newBuf
= _mesa_align_malloc(newSize
, alignment
);
203 if (newBuf
&& oldBuffer
&& copySize
> 0) {
204 memcpy(newBuf
, oldBuffer
, copySize
);
207 _mesa_align_free(oldBuffer
);
214 /** Reallocate memory */
216 _mesa_realloc(void *oldBuffer
, size_t oldSize
, size_t newSize
)
218 const size_t copySize
= (oldSize
< newSize
) ? oldSize
: newSize
;
219 void *newBuffer
= malloc(newSize
);
220 if (newBuffer
&& oldBuffer
&& copySize
> 0)
221 memcpy(newBuffer
, oldBuffer
, copySize
);
228 * Fill memory with a constant 16bit word.
229 * \param dst destination pointer.
231 * \param n number of words.
234 _mesa_memset16( unsigned short *dst
, unsigned short val
, size_t n
)
243 /**********************************************************************/
247 /** Wrapper around sqrt() */
249 _mesa_sqrtd(double x
)
256 * A High Speed, Low Precision Square Root
257 * by Paul Lalonde and Robert Dawson
258 * from "Graphics Gems", Academic Press, 1990
260 * SPARC implementation of a fast square root by table
262 * SPARC floating point format is as follows:
265 * sign exponent mantissa
267 static short sqrttab
[0x100]; /* declare table of square roots */
270 _mesa_init_sqrt_table(void)
272 #if defined(USE_IEEE) && !defined(DEBUG)
274 fi_type fi
; /* to access the bits of a float in C quickly */
275 /* we use a union defined in glheader.h */
277 for(i
=0; i
<= 0x7f; i
++) {
281 * Build a float with the bit pattern i as mantissa
282 * and an exponent of 0, stored as 127
285 fi
.i
= (i
<< 16) | (127 << 23);
286 fi
.f
= _mesa_sqrtd(fi
.f
);
289 * Take the square root then strip the first 7 bits of
290 * the mantissa into the table
293 sqrttab
[i
] = (fi
.i
& 0x7fffff) >> 16;
296 * Repeat the process, this time with an exponent of
301 fi
.i
= (i
<< 16) | (128 << 23);
303 sqrttab
[i
+0x80] = (fi
.i
& 0x7fffff) >> 16;
306 (void) sqrttab
; /* silence compiler warnings */
307 #endif /*HAVE_FAST_MATH*/
312 * Single precision square root.
315 _mesa_sqrtf( float x
)
317 #if defined(USE_IEEE) && !defined(DEBUG)
319 /* to access the bits of a float in C
320 * we use a union from glheader.h */
322 short e
; /* the exponent */
323 if (x
== 0.0F
) return 0.0F
; /* check for square root of 0 */
325 e
= (num
.i
>> 23) - 127; /* get the exponent - on a SPARC the */
326 /* exponent is stored with 127 added */
327 num
.i
&= 0x7fffff; /* leave only the mantissa */
328 if (e
& 0x01) num
.i
|= 0x800000;
329 /* the exponent is odd so we have to */
330 /* look it up in the second half of */
331 /* the lookup table, so we set the */
333 e
>>= 1; /* divide the exponent by two */
334 /* note that in C the shift */
335 /* operators are sign preserving */
336 /* for signed operands */
337 /* Do the table lookup, based on the quaternary mantissa,
338 * then reconstruct the result back into a float
340 num
.i
= ((sqrttab
[num
.i
>> 16]) << 16) | ((e
+ 127) << 23);
344 return (float) _mesa_sqrtd((double) x
);
350 inv_sqrt - A single precision 1/sqrt routine for IEEE format floats.
351 written by Josh Vanderhoof, based on newsgroup posts by James Van Buskirk
355 _mesa_inv_sqrtf(float n
)
357 #if defined(USE_IEEE) && !defined(DEBUG)
361 #if 0 /* not used, see below -BP */
368 Exponent part of the magic number -
371 1. subtract the bias from the exponent,
373 3. divide by two (rounding towards -inf)
376 Which is the same as subtracting the exponent from 381 and dividing
379 floor(-(x - 127) / 2) + 127 = floor((381 - x) / 2)
385 Significand part of magic number -
387 With the current magic number, "(magic - u.i) >> 1" will give you:
389 for 1 <= u.f <= 2: 1.25 - u.f / 4
390 for 2 <= u.f <= 4: 1.00 - u.f / 8
392 This isn't a bad approximation of 1/sqrt. The maximum difference from
393 1/sqrt will be around .06. After three Newton-Raphson iterations, the
394 maximum difference is less than 4.5e-8. (Which is actually close
395 enough to make the following bias academic...)
397 To get a better approximation you can add a bias to the magic
398 number. For example, if you subtract 1/2 of the maximum difference in
399 the first approximation (.03), you will get the following function:
401 for 1 <= u.f <= 2: 1.22 - u.f / 4
402 for 2 <= u.f <= 3.76: 0.97 - u.f / 8
403 for 3.76 <= u.f <= 4: 0.72 - u.f / 16
404 (The 3.76 to 4 range is where the result is < .5.)
406 This is the closest possible initial approximation, but with a maximum
407 error of 8e-11 after three NR iterations, it is still not perfect. If
408 you subtract 0.0332281 instead of .03, the maximum error will be
409 2.5e-11 after three NR iterations, which should be about as close as
412 for 1 <= u.f <= 2: 1.2167719 - u.f / 4
413 for 2 <= u.f <= 3.73: 0.9667719 - u.f / 8
414 for 3.73 <= u.f <= 4: 0.7167719 - u.f / 16
418 magic
-= (int)(0.0332281 * (1 << 25));
421 u
.i
= (magic
- u
.i
) >> 1;
424 Instead of Newton-Raphson, we use Goldschmidt's algorithm, which
425 allows more parallelism. From what I understand, the parallelism
426 comes at the cost of less precision, because it lets error
427 accumulate across iterations.
442 return x2
* r2
; /* we can stop here, and be conformant -BP */
451 return (float) (1.0 / sqrt(n
));
456 * Find the first bit set in a word.
461 #if (defined(_WIN32) ) || defined(__IBMC__) || defined(__IBMCPP__)
462 register int bit
= 0;
464 if ((i
& 0xffff) == 0) {
468 if ((i
& 0xff) == 0) {
472 if ((i
& 0xf) == 0) {
476 while ((i
& 1) == 0) {
490 * Find position of first bit set in given value.
491 * XXX Warning: this function can only be used on 64-bit systems!
492 * \return position of least-significant bit set, starting at 1, return zero
496 _mesa_ffsll(int64_t val
)
503 assert(sizeof(val
) == 8);
505 bit
= _mesa_ffs((int32_t)val
);
509 bit
= _mesa_ffs((int32_t)(val
>> 32));
519 * Return number of bits set in given GLuint.
522 _mesa_bitcount(unsigned int n
)
524 #if defined(__GNUC__) && \
525 ((_GNUC__ == 3 && __GNUC_MINOR__ >= 4) || __GNUC__ >= 4)
526 return __builtin_popcount(n
);
529 for (bits
= 0; n
> 0; n
= n
>> 1) {
538 * Convert a 4-byte float to a 2-byte half float.
539 * Based on code from:
540 * http://www.opengl.org/discussion_boards/ubb/Forum3/HTML/008786.html
543 _mesa_float_to_half(float val
)
545 const fi_type fi
= {val
};
546 const int flt_m
= fi
.i
& 0x7fffff;
547 const int flt_e
= (fi
.i
>> 23) & 0xff;
548 const int flt_s
= (fi
.i
>> 31) & 0x1;
555 /* handle special cases */
556 if ((flt_e
== 0) && (flt_m
== 0)) {
558 /* m = 0; - already set */
561 else if ((flt_e
== 0) && (flt_m
!= 0)) {
562 /* denorm -- denorm float maps to 0 half */
563 /* m = 0; - already set */
566 else if ((flt_e
== 0xff) && (flt_m
== 0)) {
568 /* m = 0; - already set */
571 else if ((flt_e
== 0xff) && (flt_m
!= 0)) {
578 const int new_exp
= flt_e
- 127;
581 /* m = 0; - already set */
584 else if (new_exp
< -14) {
585 /* this maps to a denorm */
586 unsigned int exp_val
= (unsigned int) (-14 - new_exp
); /* 2^-exp_val*/
591 "float_to_half: logical error in denorm creation!\n");
592 /* m = 0; - already set */
594 case 1: m
= 512 + (flt_m
>> 14); break;
595 case 2: m
= 256 + (flt_m
>> 15); break;
596 case 3: m
= 128 + (flt_m
>> 16); break;
597 case 4: m
= 64 + (flt_m
>> 17); break;
598 case 5: m
= 32 + (flt_m
>> 18); break;
599 case 6: m
= 16 + (flt_m
>> 19); break;
600 case 7: m
= 8 + (flt_m
>> 20); break;
601 case 8: m
= 4 + (flt_m
>> 21); break;
602 case 9: m
= 2 + (flt_m
>> 22); break;
603 case 10: m
= 1; break;
606 else if (new_exp
> 15) {
607 /* map this value to infinity */
608 /* m = 0; - already set */
618 result
= (s
<< 15) | (e
<< 10) | m
;
624 * Convert a 2-byte half float to a 4-byte float.
625 * Based on code from:
626 * http://www.opengl.org/discussion_boards/ubb/Forum3/HTML/008786.html
629 _mesa_half_to_float(GLhalfARB val
)
631 /* XXX could also use a 64K-entry lookup table */
632 const int m
= val
& 0x3ff;
633 const int e
= (val
>> 10) & 0x1f;
634 const int s
= (val
>> 15) & 0x1;
635 int flt_m
, flt_e
, flt_s
;
642 /* handle special cases */
643 if ((e
== 0) && (m
== 0)) {
648 else if ((e
== 0) && (m
!= 0)) {
649 /* denorm -- denorm half will fit in non-denorm single */
650 const float half_denorm
= 1.0f
/ 16384.0f
; /* 2^-14 */
651 float mantissa
= ((float) (m
)) / 1024.0f
;
652 float sign
= s
? -1.0f
: 1.0f
;
653 return sign
* mantissa
* half_denorm
;
655 else if ((e
== 31) && (m
== 0)) {
660 else if ((e
== 31) && (m
!= 0)) {
671 fi
.i
= (flt_s
<< 31) | (flt_e
<< 23) | flt_m
;
679 /**********************************************************************/
680 /** \name Sort & Search */
684 * Wrapper for bsearch().
687 _mesa_bsearch( const void *key
, const void *base
, size_t nmemb
, size_t size
,
688 int (*compar
)(const void *, const void *) )
690 #if defined(_WIN32_WCE)
695 mid
= (char *)base
+ nmemb
* size
;
696 cmp
= (*compar
)(key
, mid
);
700 base
= (char *)mid
+ size
;
706 return bsearch(key
, base
, nmemb
, size
, compar
);
713 /**********************************************************************/
714 /** \name Environment vars */
718 * Wrapper for getenv().
721 _mesa_getenv( const char *var
)
723 #if defined(_XBOX) || defined(_WIN32_WCE)
733 /**********************************************************************/
738 * Implemented using malloc() and strcpy.
739 * Note that NULL is handled accordingly.
742 _mesa_strdup( const char *s
)
745 size_t l
= strlen(s
);
746 char *s2
= (char *) malloc(l
+ 1);
756 /** Wrapper around strtof() */
758 _mesa_strtof( const char *s
, char **end
)
760 #if defined(_GNU_SOURCE) && !defined(__CYGWIN__) && !defined(__FreeBSD__)
761 static locale_t loc
= NULL
;
763 loc
= newlocale(LC_CTYPE_MASK
, "C", NULL
);
765 return strtof_l(s
, end
, loc
);
766 #elif defined(_ISOC99_SOURCE) || (defined(_XOPEN_SOURCE) && _XOPEN_SOURCE >= 600)
767 return strtof(s
, end
);
769 return (float)strtod(s
, end
);
773 /** Compute simple checksum/hash for a string */
775 _mesa_str_checksum(const char *str
)
777 /* This could probably be much better */
781 for (c
= str
; *c
; c
++, i
++)
782 sum
+= *c
* (i
% 100);
790 /** Wrapper around vsnprintf() */
792 _mesa_snprintf( char *str
, size_t size
, const char *fmt
, ... )
796 va_start( args
, fmt
);
797 r
= vsnprintf( str
, size
, fmt
, args
);
803 /**********************************************************************/
804 /** \name Diagnostics */
808 output_if_debug(const char *prefixString
, const char *outputString
,
811 static int debug
= -1;
813 /* Check the MESA_DEBUG environment variable if it hasn't
814 * been checked yet. We only have to check it once...
817 char *env
= _mesa_getenv("MESA_DEBUG");
819 /* In a debug build, we print warning messages *unless*
820 * MESA_DEBUG is 0. In a non-debug build, we don't
821 * print warning messages *unless* MESA_DEBUG is
822 * set *to any value*.
825 debug
= (env
!= NULL
&& atoi(env
) == 0) ? 0 : 1;
827 debug
= (env
!= NULL
) ? 1 : 0;
831 /* Now only print the string if we're required to do so. */
833 fprintf(stderr
, "%s: %s", prefixString
, outputString
);
835 fprintf(stderr
, "\n");
837 #if defined(_WIN32) && !defined(_WIN32_WCE)
838 /* stderr from windows applications without console is not usually
839 * visible, so communicate with the debugger instead */
842 _mesa_snprintf(buf
, sizeof(buf
), "%s: %s%s", prefixString
, outputString
, newline
? "\n" : "");
843 OutputDebugStringA(buf
);
851 * Return string version of GL error code.
854 error_string( GLenum error
)
858 return "GL_NO_ERROR";
859 case GL_INVALID_VALUE
:
860 return "GL_INVALID_VALUE";
861 case GL_INVALID_ENUM
:
862 return "GL_INVALID_ENUM";
863 case GL_INVALID_OPERATION
:
864 return "GL_INVALID_OPERATION";
865 case GL_STACK_OVERFLOW
:
866 return "GL_STACK_OVERFLOW";
867 case GL_STACK_UNDERFLOW
:
868 return "GL_STACK_UNDERFLOW";
869 case GL_OUT_OF_MEMORY
:
870 return "GL_OUT_OF_MEMORY";
871 case GL_TABLE_TOO_LARGE
:
872 return "GL_TABLE_TOO_LARGE";
873 case GL_INVALID_FRAMEBUFFER_OPERATION_EXT
:
874 return "GL_INVALID_FRAMEBUFFER_OPERATION";
882 * When a new type of error is recorded, print a message describing
883 * previous errors which were accumulated.
886 flush_delayed_errors( struct gl_context
*ctx
)
890 if (ctx
->ErrorDebugCount
) {
891 _mesa_snprintf(s
, MAXSTRING
, "%d similar %s errors",
892 ctx
->ErrorDebugCount
,
893 error_string(ctx
->ErrorValue
));
895 output_if_debug("Mesa", s
, GL_TRUE
);
897 ctx
->ErrorDebugCount
= 0;
903 * Report a warning (a recoverable error condition) to stderr if
904 * either DEBUG is defined or the MESA_DEBUG env var is set.
906 * \param ctx GL context.
907 * \param fmtString printf()-like format string.
910 _mesa_warning( struct gl_context
*ctx
, const char *fmtString
, ... )
914 va_start( args
, fmtString
);
915 (void) vsnprintf( str
, MAXSTRING
, fmtString
, args
);
919 flush_delayed_errors( ctx
);
921 output_if_debug("Mesa warning", str
, GL_TRUE
);
926 * Report an internal implementation problem.
927 * Prints the message to stderr via fprintf().
929 * \param ctx GL context.
930 * \param fmtString problem description string.
933 _mesa_problem( const struct gl_context
*ctx
, const char *fmtString
, ... )
939 va_start( args
, fmtString
);
940 vsnprintf( str
, MAXSTRING
, fmtString
, args
);
943 fprintf(stderr
, "Mesa %s implementation error: %s\n", MESA_VERSION_STRING
, str
);
944 fprintf(stderr
, "Please report at bugzilla.freedesktop.org\n");
949 * Record an OpenGL state error. These usually occur when the user
950 * passes invalid parameters to a GL function.
952 * If debugging is enabled (either at compile-time via the DEBUG macro, or
953 * run-time via the MESA_DEBUG environment variable), report the error with
956 * \param ctx the GL context.
957 * \param error the error value.
958 * \param fmtString printf() style format string, followed by optional args
961 _mesa_error( struct gl_context
*ctx
, GLenum error
, const char *fmtString
, ... )
963 static GLint debug
= -1;
965 /* Check debug environment variable only once:
968 const char *debugEnv
= _mesa_getenv("MESA_DEBUG");
971 if (debugEnv
&& strstr(debugEnv
, "silent"))
984 if (ctx
->ErrorValue
== error
&&
985 ctx
->ErrorDebugFmtString
== fmtString
) {
986 ctx
->ErrorDebugCount
++;
989 char s
[MAXSTRING
], s2
[MAXSTRING
];
992 flush_delayed_errors( ctx
);
994 va_start(args
, fmtString
);
995 vsnprintf(s
, MAXSTRING
, fmtString
, args
);
998 _mesa_snprintf(s2
, MAXSTRING
, "%s in %s", error_string(error
), s
);
999 output_if_debug("Mesa: User error", s2
, GL_TRUE
);
1001 ctx
->ErrorDebugFmtString
= fmtString
;
1002 ctx
->ErrorDebugCount
= 0;
1006 _mesa_record_error(ctx
, error
);
1011 * Report debug information. Print error message to stderr via fprintf().
1012 * No-op if DEBUG mode not enabled.
1014 * \param ctx GL context.
1015 * \param fmtString printf()-style format string, followed by optional args.
1018 _mesa_debug( const struct gl_context
*ctx
, const char *fmtString
, ... )
1023 va_start(args
, fmtString
);
1024 vsnprintf(s
, MAXSTRING
, fmtString
, args
);
1026 output_if_debug("Mesa", s
, GL_FALSE
);