Merge branch 'draw-instanced'
[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 /**
457 * Find the first bit set in a word.
458 */
459 int
460 _mesa_ffs(int32_t i)
461 {
462 #if (defined(_WIN32) ) || defined(__IBMC__) || defined(__IBMCPP__)
463 register int bit = 0;
464 if (i != 0) {
465 if ((i & 0xffff) == 0) {
466 bit += 16;
467 i >>= 16;
468 }
469 if ((i & 0xff) == 0) {
470 bit += 8;
471 i >>= 8;
472 }
473 if ((i & 0xf) == 0) {
474 bit += 4;
475 i >>= 4;
476 }
477 while ((i & 1) == 0) {
478 bit++;
479 i >>= 1;
480 }
481 bit++;
482 }
483 return bit;
484 #else
485 return ffs(i);
486 #endif
487 }
488
489
490 /**
491 * Find position of first bit set in given value.
492 * XXX Warning: this function can only be used on 64-bit systems!
493 * \return position of least-significant bit set, starting at 1, return zero
494 * if no bits set.
495 */
496 int
497 _mesa_ffsll(int64_t val)
498 {
499 #ifdef ffsll
500 return ffsll(val);
501 #else
502 int bit;
503
504 assert(sizeof(val) == 8);
505
506 bit = _mesa_ffs((int32_t)val);
507 if (bit != 0)
508 return bit;
509
510 bit = _mesa_ffs((int32_t)(val >> 32));
511 if (bit != 0)
512 return 32 + bit;
513
514 return 0;
515 #endif
516 }
517
518
519 /**
520 * Return number of bits set in given GLuint.
521 */
522 unsigned int
523 _mesa_bitcount(unsigned int n)
524 {
525 #if defined(__GNUC__) && \
526 ((_GNUC__ == 3 && __GNUC_MINOR__ >= 4) || __GNUC__ >= 4)
527 return __builtin_popcount(n);
528 #else
529 unsigned int bits;
530 for (bits = 0; n > 0; n = n >> 1) {
531 bits += (n & 1);
532 }
533 return bits;
534 #endif
535 }
536
537
538 /**
539 * Convert a 4-byte float to a 2-byte half float.
540 * Based on code from:
541 * http://www.opengl.org/discussion_boards/ubb/Forum3/HTML/008786.html
542 */
543 GLhalfARB
544 _mesa_float_to_half(float val)
545 {
546 const fi_type fi = {val};
547 const int flt_m = fi.i & 0x7fffff;
548 const int flt_e = (fi.i >> 23) & 0xff;
549 const int flt_s = (fi.i >> 31) & 0x1;
550 int s, e, m = 0;
551 GLhalfARB result;
552
553 /* sign bit */
554 s = flt_s;
555
556 /* handle special cases */
557 if ((flt_e == 0) && (flt_m == 0)) {
558 /* zero */
559 /* m = 0; - already set */
560 e = 0;
561 }
562 else if ((flt_e == 0) && (flt_m != 0)) {
563 /* denorm -- denorm float maps to 0 half */
564 /* m = 0; - already set */
565 e = 0;
566 }
567 else if ((flt_e == 0xff) && (flt_m == 0)) {
568 /* infinity */
569 /* m = 0; - already set */
570 e = 31;
571 }
572 else if ((flt_e == 0xff) && (flt_m != 0)) {
573 /* NaN */
574 m = 1;
575 e = 31;
576 }
577 else {
578 /* regular number */
579 const int new_exp = flt_e - 127;
580 if (new_exp < -24) {
581 /* this maps to 0 */
582 /* m = 0; - already set */
583 e = 0;
584 }
585 else if (new_exp < -14) {
586 /* this maps to a denorm */
587 unsigned int exp_val = (unsigned int) (-14 - new_exp); /* 2^-exp_val*/
588 e = 0;
589 switch (exp_val) {
590 case 0:
591 _mesa_warning(NULL,
592 "float_to_half: logical error in denorm creation!\n");
593 /* m = 0; - already set */
594 break;
595 case 1: m = 512 + (flt_m >> 14); break;
596 case 2: m = 256 + (flt_m >> 15); break;
597 case 3: m = 128 + (flt_m >> 16); break;
598 case 4: m = 64 + (flt_m >> 17); break;
599 case 5: m = 32 + (flt_m >> 18); break;
600 case 6: m = 16 + (flt_m >> 19); break;
601 case 7: m = 8 + (flt_m >> 20); break;
602 case 8: m = 4 + (flt_m >> 21); break;
603 case 9: m = 2 + (flt_m >> 22); break;
604 case 10: m = 1; break;
605 }
606 }
607 else if (new_exp > 15) {
608 /* map this value to infinity */
609 /* m = 0; - already set */
610 e = 31;
611 }
612 else {
613 /* regular */
614 e = new_exp + 15;
615 m = flt_m >> 13;
616 }
617 }
618
619 result = (s << 15) | (e << 10) | m;
620 return result;
621 }
622
623
624 /**
625 * Convert a 2-byte half float to a 4-byte float.
626 * Based on code from:
627 * http://www.opengl.org/discussion_boards/ubb/Forum3/HTML/008786.html
628 */
629 float
630 _mesa_half_to_float(GLhalfARB val)
631 {
632 /* XXX could also use a 64K-entry lookup table */
633 const int m = val & 0x3ff;
634 const int e = (val >> 10) & 0x1f;
635 const int s = (val >> 15) & 0x1;
636 int flt_m, flt_e, flt_s;
637 fi_type fi;
638 float result;
639
640 /* sign bit */
641 flt_s = s;
642
643 /* handle special cases */
644 if ((e == 0) && (m == 0)) {
645 /* zero */
646 flt_m = 0;
647 flt_e = 0;
648 }
649 else if ((e == 0) && (m != 0)) {
650 /* denorm -- denorm half will fit in non-denorm single */
651 const float half_denorm = 1.0f / 16384.0f; /* 2^-14 */
652 float mantissa = ((float) (m)) / 1024.0f;
653 float sign = s ? -1.0f : 1.0f;
654 return sign * mantissa * half_denorm;
655 }
656 else if ((e == 31) && (m == 0)) {
657 /* infinity */
658 flt_e = 0xff;
659 flt_m = 0;
660 }
661 else if ((e == 31) && (m != 0)) {
662 /* NaN */
663 flt_e = 0xff;
664 flt_m = 1;
665 }
666 else {
667 /* regular */
668 flt_e = e + 112;
669 flt_m = m << 13;
670 }
671
672 fi.i = (flt_s << 31) | (flt_e << 23) | flt_m;
673 result = fi.f;
674 return result;
675 }
676
677 /*@}*/
678
679
680 /**********************************************************************/
681 /** \name Sort & Search */
682 /*@{*/
683
684 /**
685 * Wrapper for bsearch().
686 */
687 void *
688 _mesa_bsearch( const void *key, const void *base, size_t nmemb, size_t size,
689 int (*compar)(const void *, const void *) )
690 {
691 #if defined(_WIN32_WCE)
692 void *mid;
693 int cmp;
694 while (nmemb) {
695 nmemb >>= 1;
696 mid = (char *)base + nmemb * size;
697 cmp = (*compar)(key, mid);
698 if (cmp == 0)
699 return mid;
700 if (cmp > 0) {
701 base = (char *)mid + size;
702 --nmemb;
703 }
704 }
705 return NULL;
706 #else
707 return bsearch(key, base, nmemb, size, compar);
708 #endif
709 }
710
711 /*@}*/
712
713
714 /**********************************************************************/
715 /** \name Environment vars */
716 /*@{*/
717
718 /**
719 * Wrapper for getenv().
720 */
721 char *
722 _mesa_getenv( const char *var )
723 {
724 #if defined(_XBOX) || defined(_WIN32_WCE)
725 return NULL;
726 #else
727 return getenv(var);
728 #endif
729 }
730
731 /*@}*/
732
733
734 /**********************************************************************/
735 /** \name String */
736 /*@{*/
737
738 /**
739 * Implemented using malloc() and strcpy.
740 * Note that NULL is handled accordingly.
741 */
742 char *
743 _mesa_strdup( const char *s )
744 {
745 if (s) {
746 size_t l = strlen(s);
747 char *s2 = (char *) malloc(l + 1);
748 if (s2)
749 strcpy(s2, s);
750 return s2;
751 }
752 else {
753 return NULL;
754 }
755 }
756
757 /** Wrapper around strtof() */
758 float
759 _mesa_strtof( const char *s, char **end )
760 {
761 #if defined(_GNU_SOURCE) && !defined(__CYGWIN__) && !defined(__FreeBSD__)
762 static locale_t loc = NULL;
763 if (!loc) {
764 loc = newlocale(LC_CTYPE_MASK, "C", NULL);
765 }
766 return strtof_l(s, end, loc);
767 #elif defined(_ISOC99_SOURCE) || (defined(_XOPEN_SOURCE) && _XOPEN_SOURCE >= 600)
768 return strtof(s, end);
769 #else
770 return (float)strtod(s, end);
771 #endif
772 }
773
774 /** Compute simple checksum/hash for a string */
775 unsigned int
776 _mesa_str_checksum(const char *str)
777 {
778 /* This could probably be much better */
779 unsigned int sum, i;
780 const char *c;
781 sum = i = 1;
782 for (c = str; *c; c++, i++)
783 sum += *c * (i % 100);
784 return sum + i;
785 }
786
787
788 /*@}*/
789
790
791 /** Wrapper around vsnprintf() */
792 int
793 _mesa_snprintf( char *str, size_t size, const char *fmt, ... )
794 {
795 int r;
796 va_list args;
797 va_start( args, fmt );
798 r = vsnprintf( str, size, fmt, args );
799 va_end( args );
800 return r;
801 }
802
803
804 /**********************************************************************/
805 /** \name Diagnostics */
806 /*@{*/
807
808 static void
809 output_if_debug(const char *prefixString, const char *outputString,
810 GLboolean newline)
811 {
812 static int debug = -1;
813
814 /* Check the MESA_DEBUG environment variable if it hasn't
815 * been checked yet. We only have to check it once...
816 */
817 if (debug == -1) {
818 char *env = _mesa_getenv("MESA_DEBUG");
819
820 /* In a debug build, we print warning messages *unless*
821 * MESA_DEBUG is 0. In a non-debug build, we don't
822 * print warning messages *unless* MESA_DEBUG is
823 * set *to any value*.
824 */
825 #ifdef DEBUG
826 debug = (env != NULL && atoi(env) == 0) ? 0 : 1;
827 #else
828 debug = (env != NULL) ? 1 : 0;
829 #endif
830 }
831
832 /* Now only print the string if we're required to do so. */
833 if (debug) {
834 fprintf(stderr, "%s: %s", prefixString, outputString);
835 if (newline)
836 fprintf(stderr, "\n");
837
838 #if defined(_WIN32) && !defined(_WIN32_WCE)
839 /* stderr from windows applications without console is not usually
840 * visible, so communicate with the debugger instead */
841 {
842 char buf[4096];
843 _mesa_snprintf(buf, sizeof(buf), "%s: %s%s", prefixString, outputString, newline ? "\n" : "");
844 OutputDebugStringA(buf);
845 }
846 #endif
847 }
848 }
849
850
851 /**
852 * Return string version of GL error code.
853 */
854 static const char *
855 error_string( GLenum error )
856 {
857 switch (error) {
858 case GL_NO_ERROR:
859 return "GL_NO_ERROR";
860 case GL_INVALID_VALUE:
861 return "GL_INVALID_VALUE";
862 case GL_INVALID_ENUM:
863 return "GL_INVALID_ENUM";
864 case GL_INVALID_OPERATION:
865 return "GL_INVALID_OPERATION";
866 case GL_STACK_OVERFLOW:
867 return "GL_STACK_OVERFLOW";
868 case GL_STACK_UNDERFLOW:
869 return "GL_STACK_UNDERFLOW";
870 case GL_OUT_OF_MEMORY:
871 return "GL_OUT_OF_MEMORY";
872 case GL_TABLE_TOO_LARGE:
873 return "GL_TABLE_TOO_LARGE";
874 case GL_INVALID_FRAMEBUFFER_OPERATION_EXT:
875 return "GL_INVALID_FRAMEBUFFER_OPERATION";
876 default:
877 return "unknown";
878 }
879 }
880
881
882 /**
883 * When a new type of error is recorded, print a message describing
884 * previous errors which were accumulated.
885 */
886 static void
887 flush_delayed_errors( struct gl_context *ctx )
888 {
889 char s[MAXSTRING];
890
891 if (ctx->ErrorDebugCount) {
892 _mesa_snprintf(s, MAXSTRING, "%d similar %s errors",
893 ctx->ErrorDebugCount,
894 error_string(ctx->ErrorValue));
895
896 output_if_debug("Mesa", s, GL_TRUE);
897
898 ctx->ErrorDebugCount = 0;
899 }
900 }
901
902
903 /**
904 * Report a warning (a recoverable error condition) to stderr if
905 * either DEBUG is defined or the MESA_DEBUG env var is set.
906 *
907 * \param ctx GL context.
908 * \param fmtString printf()-like format string.
909 */
910 void
911 _mesa_warning( struct gl_context *ctx, const char *fmtString, ... )
912 {
913 char str[MAXSTRING];
914 va_list args;
915 va_start( args, fmtString );
916 (void) vsnprintf( str, MAXSTRING, fmtString, args );
917 va_end( args );
918
919 if (ctx)
920 flush_delayed_errors( ctx );
921
922 output_if_debug("Mesa warning", str, GL_TRUE);
923 }
924
925
926 /**
927 * Report an internal implementation problem.
928 * Prints the message to stderr via fprintf().
929 *
930 * \param ctx GL context.
931 * \param fmtString problem description string.
932 */
933 void
934 _mesa_problem( const struct gl_context *ctx, const char *fmtString, ... )
935 {
936 va_list args;
937 char str[MAXSTRING];
938 (void) ctx;
939
940 va_start( args, fmtString );
941 vsnprintf( str, MAXSTRING, fmtString, args );
942 va_end( args );
943
944 fprintf(stderr, "Mesa %s implementation error: %s\n", MESA_VERSION_STRING, str);
945 fprintf(stderr, "Please report at bugzilla.freedesktop.org\n");
946 }
947
948
949 /**
950 * Record an OpenGL state error. These usually occur when the user
951 * passes invalid parameters to a GL function.
952 *
953 * If debugging is enabled (either at compile-time via the DEBUG macro, or
954 * run-time via the MESA_DEBUG environment variable), report the error with
955 * _mesa_debug().
956 *
957 * \param ctx the GL context.
958 * \param error the error value.
959 * \param fmtString printf() style format string, followed by optional args
960 */
961 void
962 _mesa_error( struct gl_context *ctx, GLenum error, const char *fmtString, ... )
963 {
964 static GLint debug = -1;
965
966 /* Check debug environment variable only once:
967 */
968 if (debug == -1) {
969 const char *debugEnv = _mesa_getenv("MESA_DEBUG");
970
971 #ifdef DEBUG
972 if (debugEnv && strstr(debugEnv, "silent"))
973 debug = GL_FALSE;
974 else
975 debug = GL_TRUE;
976 #else
977 if (debugEnv)
978 debug = GL_TRUE;
979 else
980 debug = GL_FALSE;
981 #endif
982 }
983
984 if (debug) {
985 if (ctx->ErrorValue == error &&
986 ctx->ErrorDebugFmtString == fmtString) {
987 ctx->ErrorDebugCount++;
988 }
989 else {
990 char s[MAXSTRING], s2[MAXSTRING];
991 va_list args;
992
993 flush_delayed_errors( ctx );
994
995 va_start(args, fmtString);
996 vsnprintf(s, MAXSTRING, fmtString, args);
997 va_end(args);
998
999 _mesa_snprintf(s2, MAXSTRING, "%s in %s", error_string(error), s);
1000 output_if_debug("Mesa: User error", s2, GL_TRUE);
1001
1002 ctx->ErrorDebugFmtString = fmtString;
1003 ctx->ErrorDebugCount = 0;
1004 }
1005 }
1006
1007 _mesa_record_error(ctx, error);
1008 }
1009
1010
1011 /**
1012 * Report debug information. Print error message to stderr via fprintf().
1013 * No-op if DEBUG mode not enabled.
1014 *
1015 * \param ctx GL context.
1016 * \param fmtString printf()-style format string, followed by optional args.
1017 */
1018 void
1019 _mesa_debug( const struct gl_context *ctx, const char *fmtString, ... )
1020 {
1021 #ifdef DEBUG
1022 char s[MAXSTRING];
1023 va_list args;
1024 va_start(args, fmtString);
1025 vsnprintf(s, MAXSTRING, fmtString, args);
1026 va_end(args);
1027 output_if_debug("Mesa", s, GL_FALSE);
1028 #endif /* DEBUG */
1029 (void) ctx;
1030 (void) fmtString;
1031 }
1032
1033 /*@}*/