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