1c4b219188cc97cde1bea1bbff3833e66534641b
[mesa.git] / src / mesa / main / imports.c
1 /**
2 * \file imports.c
3 * Standard C library function wrappers.
4 *
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,
8 * etc.
9 *
10 * Some drivers will want to override/replace this file with something
11 * specialized, but that'll be rare.
12 *
13 * Eventually, I want to move roll the glheader.h file into this.
14 *
15 * \todo Functions still needed:
16 * - scanf
17 * - qsort
18 * - rand and RAND_MAX
19 */
20
21 /*
22 * Mesa 3-D graphics library
23 * Version: 7.1
24 *
25 * Copyright (C) 1999-2007 Brian Paul All Rights Reserved.
26 *
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:
33 *
34 * The above copyright notice and this permission notice shall be included
35 * in all copies or substantial portions of the Software.
36 *
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.
43 */
44
45
46
47 #include "imports.h"
48 #include "context.h"
49 #include "version.h"
50
51 #ifdef _GNU_SOURCE
52 #include <locale.h>
53 #ifdef __APPLE__
54 #include <xlocale.h>
55 #endif
56 #endif
57
58
59 #define MAXSTRING 4000 /* for vsnprintf() */
60
61 #ifdef WIN32
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);
65 #ifdef __VMS
66 #include "vsnprintf.c"
67 #endif
68 #endif
69
70 /**********************************************************************/
71 /** \name Memory */
72 /*@{*/
73
74 /**
75 * Allocate aligned memory.
76 *
77 * \param bytes number of bytes to allocate.
78 * \param alignment alignment (must be greater than zero).
79 *
80 * Allocates extra memory to accommodate rounding up the address for
81 * alignment and to record the real malloc address.
82 *
83 * \sa _mesa_align_free().
84 */
85 void *
86 _mesa_align_malloc(size_t bytes, unsigned long alignment)
87 {
88 #if defined(HAVE_POSIX_MEMALIGN)
89 void *mem;
90 int err = posix_memalign(& mem, alignment, bytes);
91 (void) err;
92 return mem;
93 #elif defined(_WIN32) && defined(_MSC_VER)
94 return _aligned_malloc(bytes, alignment);
95 #else
96 uintptr_t ptr, buf;
97
98 ASSERT( alignment > 0 );
99
100 ptr = (uintptr_t) malloc(bytes + alignment + sizeof(void *));
101 if (!ptr)
102 return NULL;
103
104 buf = (ptr + alignment + sizeof(void *)) & ~(uintptr_t)(alignment - 1);
105 *(uintptr_t *)(buf - sizeof(void *)) = ptr;
106
107 #ifdef DEBUG
108 /* mark the non-aligned area */
109 while ( ptr < buf - sizeof(void *) ) {
110 *(unsigned long *)ptr = 0xcdcdcdcd;
111 ptr += sizeof(unsigned long);
112 }
113 #endif
114
115 return (void *) buf;
116 #endif /* defined(HAVE_POSIX_MEMALIGN) */
117 }
118
119 /**
120 * Same as _mesa_align_malloc(), but using calloc(1, ) instead of
121 * malloc()
122 */
123 void *
124 _mesa_align_calloc(size_t bytes, unsigned long alignment)
125 {
126 #if defined(HAVE_POSIX_MEMALIGN)
127 void *mem;
128
129 mem = _mesa_align_malloc(bytes, alignment);
130 if (mem != NULL) {
131 (void) memset(mem, 0, bytes);
132 }
133
134 return mem;
135 #elif defined(_WIN32) && defined(_MSC_VER)
136 void *mem;
137
138 mem = _aligned_malloc(bytes, alignment);
139 if (mem != NULL) {
140 (void) memset(mem, 0, bytes);
141 }
142
143 return mem;
144 #else
145 uintptr_t ptr, buf;
146
147 ASSERT( alignment > 0 );
148
149 ptr = (uintptr_t) calloc(1, bytes + alignment + sizeof(void *));
150 if (!ptr)
151 return NULL;
152
153 buf = (ptr + alignment + sizeof(void *)) & ~(uintptr_t)(alignment - 1);
154 *(uintptr_t *)(buf - sizeof(void *)) = ptr;
155
156 #ifdef DEBUG
157 /* mark the non-aligned area */
158 while ( ptr < buf - sizeof(void *) ) {
159 *(unsigned long *)ptr = 0xcdcdcdcd;
160 ptr += sizeof(unsigned long);
161 }
162 #endif
163
164 return (void *)buf;
165 #endif /* defined(HAVE_POSIX_MEMALIGN) */
166 }
167
168 /**
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.
174 */
175 void
176 _mesa_align_free(void *ptr)
177 {
178 #if defined(HAVE_POSIX_MEMALIGN)
179 free(ptr);
180 #elif defined(_WIN32) && defined(_MSC_VER)
181 _aligned_free(ptr);
182 #else
183 void **cubbyHole = (void **) ((char *) ptr - sizeof(void *));
184 void *realAddr = *cubbyHole;
185 free(realAddr);
186 #endif /* defined(HAVE_POSIX_MEMALIGN) */
187 }
188
189 /**
190 * Reallocate memory, with alignment.
191 */
192 void *
193 _mesa_align_realloc(void *oldBuffer, size_t oldSize, size_t newSize,
194 unsigned long alignment)
195 {
196 #if defined(_WIN32) && defined(_MSC_VER)
197 (void) oldSize;
198 return _aligned_realloc(oldBuffer, newSize, alignment);
199 #else
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);
204 }
205 if (oldBuffer)
206 _mesa_align_free(oldBuffer);
207 return newBuf;
208 #endif
209 }
210
211
212
213 /** Reallocate memory */
214 void *
215 _mesa_realloc(void *oldBuffer, size_t oldSize, size_t newSize)
216 {
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);
221 if (oldBuffer)
222 free(oldBuffer);
223 return newBuffer;
224 }
225
226 /**
227 * Fill memory with a constant 16bit word.
228 * \param dst destination pointer.
229 * \param val value.
230 * \param n number of words.
231 */
232 void
233 _mesa_memset16( unsigned short *dst, unsigned short val, size_t n )
234 {
235 while (n-- > 0)
236 *dst++ = val;
237 }
238
239 /*@}*/
240
241
242 /**********************************************************************/
243 /** \name Math */
244 /*@{*/
245
246 /** Wrapper around sin() */
247 double
248 _mesa_sin(double a)
249 {
250 return sin(a);
251 }
252
253 /** Single precision wrapper around sin() */
254 float
255 _mesa_sinf(float a)
256 {
257 return (float) sin((double) a);
258 }
259
260 /** Wrapper around cos() */
261 double
262 _mesa_cos(double a)
263 {
264 return cos(a);
265 }
266
267 /** Single precision wrapper around asin() */
268 float
269 _mesa_asinf(float x)
270 {
271 return (float) asin((double) x);
272 }
273
274 /** Single precision wrapper around atan() */
275 float
276 _mesa_atanf(float x)
277 {
278 return (float) atan((double) x);
279 }
280
281 /** Wrapper around sqrt() */
282 double
283 _mesa_sqrtd(double x)
284 {
285 return sqrt(x);
286 }
287
288
289 /*
290 * A High Speed, Low Precision Square Root
291 * by Paul Lalonde and Robert Dawson
292 * from "Graphics Gems", Academic Press, 1990
293 *
294 * SPARC implementation of a fast square root by table
295 * lookup.
296 * SPARC floating point format is as follows:
297 *
298 * BIT 31 30 23 22 0
299 * sign exponent mantissa
300 */
301 static short sqrttab[0x100]; /* declare table of square roots */
302
303 void
304 _mesa_init_sqrt_table(void)
305 {
306 #if defined(USE_IEEE) && !defined(DEBUG)
307 unsigned short i;
308 fi_type fi; /* to access the bits of a float in C quickly */
309 /* we use a union defined in glheader.h */
310
311 for(i=0; i<= 0x7f; i++) {
312 fi.i = 0;
313
314 /*
315 * Build a float with the bit pattern i as mantissa
316 * and an exponent of 0, stored as 127
317 */
318
319 fi.i = (i << 16) | (127 << 23);
320 fi.f = _mesa_sqrtd(fi.f);
321
322 /*
323 * Take the square root then strip the first 7 bits of
324 * the mantissa into the table
325 */
326
327 sqrttab[i] = (fi.i & 0x7fffff) >> 16;
328
329 /*
330 * Repeat the process, this time with an exponent of
331 * 1, stored as 128
332 */
333
334 fi.i = 0;
335 fi.i = (i << 16) | (128 << 23);
336 fi.f = sqrt(fi.f);
337 sqrttab[i+0x80] = (fi.i & 0x7fffff) >> 16;
338 }
339 #else
340 (void) sqrttab; /* silence compiler warnings */
341 #endif /*HAVE_FAST_MATH*/
342 }
343
344
345 /**
346 * Single precision square root.
347 */
348 float
349 _mesa_sqrtf( float x )
350 {
351 #if defined(USE_IEEE) && !defined(DEBUG)
352 fi_type num;
353 /* to access the bits of a float in C
354 * we use a union from glheader.h */
355
356 short e; /* the exponent */
357 if (x == 0.0F) return 0.0F; /* check for square root of 0 */
358 num.f = x;
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 */
366 /* high bit */
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
373 */
374 num.i = ((sqrttab[num.i >> 16]) << 16) | ((e + 127) << 23);
375
376 return num.f;
377 #else
378 return (float) _mesa_sqrtd((double) x);
379 #endif
380 }
381
382
383 /**
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
386 and Vesa Karvonen.
387 */
388 float
389 _mesa_inv_sqrtf(float n)
390 {
391 #if defined(USE_IEEE) && !defined(DEBUG)
392 float r0, x0, y0;
393 float r1, x1, y1;
394 float r2, x2, y2;
395 #if 0 /* not used, see below -BP */
396 float r3, x3, y3;
397 #endif
398 fi_type u;
399 unsigned int magic;
400
401 /*
402 Exponent part of the magic number -
403
404 We want to:
405 1. subtract the bias from the exponent,
406 2. negate it
407 3. divide by two (rounding towards -inf)
408 4. add the bias back
409
410 Which is the same as subtracting the exponent from 381 and dividing
411 by 2.
412
413 floor(-(x - 127) / 2) + 127 = floor((381 - x) / 2)
414 */
415
416 magic = 381 << 23;
417
418 /*
419 Significand part of magic number -
420
421 With the current magic number, "(magic - u.i) >> 1" will give you:
422
423 for 1 <= u.f <= 2: 1.25 - u.f / 4
424 for 2 <= u.f <= 4: 1.00 - u.f / 8
425
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...)
430
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:
434
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.)
439
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
444 is possible.
445
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
449
450 */
451
452 magic -= (int)(0.0332281 * (1 << 25));
453
454 u.f = n;
455 u.i = (magic - u.i) >> 1;
456
457 /*
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.
462 */
463 x0 = 1.0f;
464 y0 = 0.5f * n;
465 r0 = u.f;
466
467 x1 = x0 * r0;
468 y1 = y0 * r0 * r0;
469 r1 = 1.5f - y1;
470
471 x2 = x1 * r1;
472 y2 = y1 * r1 * r1;
473 r2 = 1.5f - y2;
474
475 #if 1
476 return x2 * r2; /* we can stop here, and be conformant -BP */
477 #else
478 x3 = x2 * r2;
479 y3 = y2 * r2 * r2;
480 r3 = 1.5f - y3;
481
482 return x3 * r3;
483 #endif
484 #else
485 return (float) (1.0 / sqrt(n));
486 #endif
487 }
488
489 /**
490 * Find the first bit set in a word.
491 */
492 int
493 _mesa_ffs(int32_t i)
494 {
495 #if (defined(_WIN32) ) || defined(__IBMC__) || defined(__IBMCPP__)
496 register int bit = 0;
497 if (i != 0) {
498 if ((i & 0xffff) == 0) {
499 bit += 16;
500 i >>= 16;
501 }
502 if ((i & 0xff) == 0) {
503 bit += 8;
504 i >>= 8;
505 }
506 if ((i & 0xf) == 0) {
507 bit += 4;
508 i >>= 4;
509 }
510 while ((i & 1) == 0) {
511 bit++;
512 i >>= 1;
513 }
514 bit++;
515 }
516 return bit;
517 #else
518 return ffs(i);
519 #endif
520 }
521
522
523 /**
524 * Find position of first bit set in given value.
525 * XXX Warning: this function can only be used on 64-bit systems!
526 * \return position of least-significant bit set, starting at 1, return zero
527 * if no bits set.
528 */
529 int
530 _mesa_ffsll(int64_t val)
531 {
532 #ifdef ffsll
533 return ffsll(val);
534 #else
535 int bit;
536
537 assert(sizeof(val) == 8);
538
539 bit = _mesa_ffs((int32_t)val);
540 if (bit != 0)
541 return bit;
542
543 bit = _mesa_ffs((int32_t)(val >> 32));
544 if (bit != 0)
545 return 32 + bit;
546
547 return 0;
548 #endif
549 }
550
551
552 /**
553 * Return number of bits set in given GLuint.
554 */
555 unsigned int
556 _mesa_bitcount(unsigned int n)
557 {
558 #if defined(__GNUC__) && \
559 ((_GNUC__ == 3 && __GNUC_MINOR__ >= 4) || __GNUC__ >= 4)
560 return __builtin_popcount(n);
561 #else
562 unsigned int bits;
563 for (bits = 0; n > 0; n = n >> 1) {
564 bits += (n & 1);
565 }
566 return bits;
567 #endif
568 }
569
570
571 /**
572 * Convert a 4-byte float to a 2-byte half float.
573 * Based on code from:
574 * http://www.opengl.org/discussion_boards/ubb/Forum3/HTML/008786.html
575 */
576 GLhalfARB
577 _mesa_float_to_half(float val)
578 {
579 const fi_type fi = {val};
580 const int flt_m = fi.i & 0x7fffff;
581 const int flt_e = (fi.i >> 23) & 0xff;
582 const int flt_s = (fi.i >> 31) & 0x1;
583 int s, e, m = 0;
584 GLhalfARB result;
585
586 /* sign bit */
587 s = flt_s;
588
589 /* handle special cases */
590 if ((flt_e == 0) && (flt_m == 0)) {
591 /* zero */
592 /* m = 0; - already set */
593 e = 0;
594 }
595 else if ((flt_e == 0) && (flt_m != 0)) {
596 /* denorm -- denorm float maps to 0 half */
597 /* m = 0; - already set */
598 e = 0;
599 }
600 else if ((flt_e == 0xff) && (flt_m == 0)) {
601 /* infinity */
602 /* m = 0; - already set */
603 e = 31;
604 }
605 else if ((flt_e == 0xff) && (flt_m != 0)) {
606 /* NaN */
607 m = 1;
608 e = 31;
609 }
610 else {
611 /* regular number */
612 const int new_exp = flt_e - 127;
613 if (new_exp < -24) {
614 /* this maps to 0 */
615 /* m = 0; - already set */
616 e = 0;
617 }
618 else if (new_exp < -14) {
619 /* this maps to a denorm */
620 unsigned int exp_val = (unsigned int) (-14 - new_exp); /* 2^-exp_val*/
621 e = 0;
622 switch (exp_val) {
623 case 0:
624 _mesa_warning(NULL,
625 "float_to_half: logical error in denorm creation!\n");
626 /* m = 0; - already set */
627 break;
628 case 1: m = 512 + (flt_m >> 14); break;
629 case 2: m = 256 + (flt_m >> 15); break;
630 case 3: m = 128 + (flt_m >> 16); break;
631 case 4: m = 64 + (flt_m >> 17); break;
632 case 5: m = 32 + (flt_m >> 18); break;
633 case 6: m = 16 + (flt_m >> 19); break;
634 case 7: m = 8 + (flt_m >> 20); break;
635 case 8: m = 4 + (flt_m >> 21); break;
636 case 9: m = 2 + (flt_m >> 22); break;
637 case 10: m = 1; break;
638 }
639 }
640 else if (new_exp > 15) {
641 /* map this value to infinity */
642 /* m = 0; - already set */
643 e = 31;
644 }
645 else {
646 /* regular */
647 e = new_exp + 15;
648 m = flt_m >> 13;
649 }
650 }
651
652 result = (s << 15) | (e << 10) | m;
653 return result;
654 }
655
656
657 /**
658 * Convert a 2-byte half float to a 4-byte float.
659 * Based on code from:
660 * http://www.opengl.org/discussion_boards/ubb/Forum3/HTML/008786.html
661 */
662 float
663 _mesa_half_to_float(GLhalfARB val)
664 {
665 /* XXX could also use a 64K-entry lookup table */
666 const int m = val & 0x3ff;
667 const int e = (val >> 10) & 0x1f;
668 const int s = (val >> 15) & 0x1;
669 int flt_m, flt_e, flt_s;
670 fi_type fi;
671 float result;
672
673 /* sign bit */
674 flt_s = s;
675
676 /* handle special cases */
677 if ((e == 0) && (m == 0)) {
678 /* zero */
679 flt_m = 0;
680 flt_e = 0;
681 }
682 else if ((e == 0) && (m != 0)) {
683 /* denorm -- denorm half will fit in non-denorm single */
684 const float half_denorm = 1.0f / 16384.0f; /* 2^-14 */
685 float mantissa = ((float) (m)) / 1024.0f;
686 float sign = s ? -1.0f : 1.0f;
687 return sign * mantissa * half_denorm;
688 }
689 else if ((e == 31) && (m == 0)) {
690 /* infinity */
691 flt_e = 0xff;
692 flt_m = 0;
693 }
694 else if ((e == 31) && (m != 0)) {
695 /* NaN */
696 flt_e = 0xff;
697 flt_m = 1;
698 }
699 else {
700 /* regular */
701 flt_e = e + 112;
702 flt_m = m << 13;
703 }
704
705 fi.i = (flt_s << 31) | (flt_e << 23) | flt_m;
706 result = fi.f;
707 return result;
708 }
709
710 /*@}*/
711
712
713 /**********************************************************************/
714 /** \name Sort & Search */
715 /*@{*/
716
717 /**
718 * Wrapper for bsearch().
719 */
720 void *
721 _mesa_bsearch( const void *key, const void *base, size_t nmemb, size_t size,
722 int (*compar)(const void *, const void *) )
723 {
724 #if defined(_WIN32_WCE)
725 void *mid;
726 int cmp;
727 while (nmemb) {
728 nmemb >>= 1;
729 mid = (char *)base + nmemb * size;
730 cmp = (*compar)(key, mid);
731 if (cmp == 0)
732 return mid;
733 if (cmp > 0) {
734 base = (char *)mid + size;
735 --nmemb;
736 }
737 }
738 return NULL;
739 #else
740 return bsearch(key, base, nmemb, size, compar);
741 #endif
742 }
743
744 /*@}*/
745
746
747 /**********************************************************************/
748 /** \name Environment vars */
749 /*@{*/
750
751 /**
752 * Wrapper for getenv().
753 */
754 char *
755 _mesa_getenv( const char *var )
756 {
757 #if defined(_XBOX) || defined(_WIN32_WCE)
758 return NULL;
759 #else
760 return getenv(var);
761 #endif
762 }
763
764 /*@}*/
765
766
767 /**********************************************************************/
768 /** \name String */
769 /*@{*/
770
771 /**
772 * Implemented using malloc() and strcpy.
773 * Note that NULL is handled accordingly.
774 */
775 char *
776 _mesa_strdup( const char *s )
777 {
778 if (s) {
779 size_t l = strlen(s);
780 char *s2 = (char *) malloc(l + 1);
781 if (s2)
782 strcpy(s2, s);
783 return s2;
784 }
785 else {
786 return NULL;
787 }
788 }
789
790 /** Wrapper around strtof() */
791 float
792 _mesa_strtof( const char *s, char **end )
793 {
794 #ifdef _GNU_SOURCE
795 static locale_t loc = NULL;
796 if (!loc) {
797 loc = newlocale(LC_CTYPE_MASK, "C", NULL);
798 }
799 return strtof_l(s, end, loc);
800 #elif defined(_ISOC99_SOURCE) || (defined(_XOPEN_SOURCE) && _XOPEN_SOURCE >= 600)
801 return strtof(s, end);
802 #else
803 return (float)strtod(s, end);
804 #endif
805 }
806
807 /** Compute simple checksum/hash for a string */
808 unsigned int
809 _mesa_str_checksum(const char *str)
810 {
811 /* This could probably be much better */
812 unsigned int sum, i;
813 const char *c;
814 sum = i = 1;
815 for (c = str; *c; c++, i++)
816 sum += *c * (i % 100);
817 return sum + i;
818 }
819
820
821 /*@}*/
822
823
824 /** Wrapper around vsnprintf() */
825 int
826 _mesa_snprintf( char *str, size_t size, const char *fmt, ... )
827 {
828 int r;
829 va_list args;
830 va_start( args, fmt );
831 r = vsnprintf( str, size, fmt, args );
832 va_end( args );
833 return r;
834 }
835
836
837 /**********************************************************************/
838 /** \name Diagnostics */
839 /*@{*/
840
841 static void
842 output_if_debug(const char *prefixString, const char *outputString,
843 GLboolean newline)
844 {
845 static int debug = -1;
846
847 /* Check the MESA_DEBUG environment variable if it hasn't
848 * been checked yet. We only have to check it once...
849 */
850 if (debug == -1) {
851 char *env = _mesa_getenv("MESA_DEBUG");
852
853 /* In a debug build, we print warning messages *unless*
854 * MESA_DEBUG is 0. In a non-debug build, we don't
855 * print warning messages *unless* MESA_DEBUG is
856 * set *to any value*.
857 */
858 #ifdef DEBUG
859 debug = (env != NULL && atoi(env) == 0) ? 0 : 1;
860 #else
861 debug = (env != NULL) ? 1 : 0;
862 #endif
863 }
864
865 /* Now only print the string if we're required to do so. */
866 if (debug) {
867 fprintf(stderr, "%s: %s", prefixString, outputString);
868 if (newline)
869 fprintf(stderr, "\n");
870
871 #if defined(_WIN32) && !defined(_WIN32_WCE)
872 /* stderr from windows applications without console is not usually
873 * visible, so communicate with the debugger instead */
874 {
875 char buf[4096];
876 _mesa_snprintf(buf, sizeof(buf), "%s: %s%s", prefixString, outputString, newline ? "\n" : "");
877 OutputDebugStringA(buf);
878 }
879 #endif
880 }
881 }
882
883
884 /**
885 * Return string version of GL error code.
886 */
887 static const char *
888 error_string( GLenum error )
889 {
890 switch (error) {
891 case GL_NO_ERROR:
892 return "GL_NO_ERROR";
893 case GL_INVALID_VALUE:
894 return "GL_INVALID_VALUE";
895 case GL_INVALID_ENUM:
896 return "GL_INVALID_ENUM";
897 case GL_INVALID_OPERATION:
898 return "GL_INVALID_OPERATION";
899 case GL_STACK_OVERFLOW:
900 return "GL_STACK_OVERFLOW";
901 case GL_STACK_UNDERFLOW:
902 return "GL_STACK_UNDERFLOW";
903 case GL_OUT_OF_MEMORY:
904 return "GL_OUT_OF_MEMORY";
905 case GL_TABLE_TOO_LARGE:
906 return "GL_TABLE_TOO_LARGE";
907 case GL_INVALID_FRAMEBUFFER_OPERATION_EXT:
908 return "GL_INVALID_FRAMEBUFFER_OPERATION";
909 default:
910 return "unknown";
911 }
912 }
913
914
915 /**
916 * When a new type of error is recorded, print a message describing
917 * previous errors which were accumulated.
918 */
919 static void
920 flush_delayed_errors( GLcontext *ctx )
921 {
922 char s[MAXSTRING];
923
924 if (ctx->ErrorDebugCount) {
925 _mesa_snprintf(s, MAXSTRING, "%d similar %s errors",
926 ctx->ErrorDebugCount,
927 error_string(ctx->ErrorValue));
928
929 output_if_debug("Mesa", s, GL_TRUE);
930
931 ctx->ErrorDebugCount = 0;
932 }
933 }
934
935
936 /**
937 * Report a warning (a recoverable error condition) to stderr if
938 * either DEBUG is defined or the MESA_DEBUG env var is set.
939 *
940 * \param ctx GL context.
941 * \param fmtString printf()-like format string.
942 */
943 void
944 _mesa_warning( GLcontext *ctx, const char *fmtString, ... )
945 {
946 char str[MAXSTRING];
947 va_list args;
948 va_start( args, fmtString );
949 (void) vsnprintf( str, MAXSTRING, fmtString, args );
950 va_end( args );
951
952 if (ctx)
953 flush_delayed_errors( ctx );
954
955 output_if_debug("Mesa warning", str, GL_TRUE);
956 }
957
958
959 /**
960 * Report an internal implementation problem.
961 * Prints the message to stderr via fprintf().
962 *
963 * \param ctx GL context.
964 * \param fmtString problem description string.
965 */
966 void
967 _mesa_problem( const GLcontext *ctx, const char *fmtString, ... )
968 {
969 va_list args;
970 char str[MAXSTRING];
971 (void) ctx;
972
973 va_start( args, fmtString );
974 vsnprintf( str, MAXSTRING, fmtString, args );
975 va_end( args );
976
977 fprintf(stderr, "Mesa %s implementation error: %s\n", MESA_VERSION_STRING, str);
978 fprintf(stderr, "Please report at bugzilla.freedesktop.org\n");
979 }
980
981
982 /**
983 * Record an OpenGL state error. These usually occur when the user
984 * passes invalid parameters to a GL function.
985 *
986 * If debugging is enabled (either at compile-time via the DEBUG macro, or
987 * run-time via the MESA_DEBUG environment variable), report the error with
988 * _mesa_debug().
989 *
990 * \param ctx the GL context.
991 * \param error the error value.
992 * \param fmtString printf() style format string, followed by optional args
993 */
994 void
995 _mesa_error( GLcontext *ctx, GLenum error, const char *fmtString, ... )
996 {
997 static GLint debug = -1;
998
999 /* Check debug environment variable only once:
1000 */
1001 if (debug == -1) {
1002 const char *debugEnv = _mesa_getenv("MESA_DEBUG");
1003
1004 #ifdef DEBUG
1005 if (debugEnv && strstr(debugEnv, "silent"))
1006 debug = GL_FALSE;
1007 else
1008 debug = GL_TRUE;
1009 #else
1010 if (debugEnv)
1011 debug = GL_TRUE;
1012 else
1013 debug = GL_FALSE;
1014 #endif
1015 }
1016
1017 if (debug) {
1018 if (ctx->ErrorValue == error &&
1019 ctx->ErrorDebugFmtString == fmtString) {
1020 ctx->ErrorDebugCount++;
1021 }
1022 else {
1023 char s[MAXSTRING], s2[MAXSTRING];
1024 va_list args;
1025
1026 flush_delayed_errors( ctx );
1027
1028 va_start(args, fmtString);
1029 vsnprintf(s, MAXSTRING, fmtString, args);
1030 va_end(args);
1031
1032 _mesa_snprintf(s2, MAXSTRING, "%s in %s", error_string(error), s);
1033 output_if_debug("Mesa: User error", s2, GL_TRUE);
1034
1035 ctx->ErrorDebugFmtString = fmtString;
1036 ctx->ErrorDebugCount = 0;
1037 }
1038 }
1039
1040 _mesa_record_error(ctx, error);
1041 }
1042
1043
1044 /**
1045 * Report debug information. Print error message to stderr via fprintf().
1046 * No-op if DEBUG mode not enabled.
1047 *
1048 * \param ctx GL context.
1049 * \param fmtString printf()-style format string, followed by optional args.
1050 */
1051 void
1052 _mesa_debug( const GLcontext *ctx, const char *fmtString, ... )
1053 {
1054 #ifdef DEBUG
1055 char s[MAXSTRING];
1056 va_list args;
1057 va_start(args, fmtString);
1058 vsnprintf(s, MAXSTRING, fmtString, args);
1059 va_end(args);
1060 output_if_debug("Mesa", s, GL_FALSE);
1061 #endif /* DEBUG */
1062 (void) ctx;
1063 (void) fmtString;
1064 }
1065
1066 /*@}*/