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