xm_api.c revision a078d75a27b99252ede6520e24b145106ab98aa2
1/* $Id: xm_api.c,v 1.36 2002/05/27 17:06:59 brianp Exp $ */
2
3/*
4 * Mesa 3-D graphics library
5 * Version:  4.0.2
6 *
7 * Copyright (C) 1999-2002  Brian Paul   All Rights Reserved.
8 *
9 * Permission is hereby granted, free of charge, to any person obtaining a
10 * copy of this software and associated documentation files (the "Software"),
11 * to deal in the Software without restriction, including without limitation
12 * the rights to use, copy, modify, merge, publish, distribute, sublicense,
13 * and/or sell copies of the Software, and to permit persons to whom the
14 * Software is furnished to do so, subject to the following conditions:
15 *
16 * The above copyright notice and this permission notice shall be included
17 * in all copies or substantial portions of the Software.
18 *
19 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
20 * OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
21 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.  IN NO EVENT SHALL
22 * BRIAN PAUL BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN
23 * AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
24 * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
25 */
26/* $XFree86: xc/extras/Mesa/src/X/xm_api.c,v 1.2 2002/02/26 23:37:31 tsi Exp $ */
27
28/*
29 * This file contains the implementations of all the XMesa* functions.
30 *
31 *
32 * NOTES:
33 *
34 * The window coordinate system origin (0,0) is in the lower-left corner
35 * of the window.  X11's window coordinate origin is in the upper-left
36 * corner of the window.  Therefore, most drawing functions in this
37 * file have to flip Y coordinates.
38 *
39 * Define USE_XSHM in the Makefile with -DUSE_XSHM if you want to compile
40 * in support for the MIT Shared Memory extension.  If enabled, when you
41 * use an Ximage for the back buffer in double buffered mode, the "swap"
42 * operation will be faster.  You must also link with -lXext.
43 *
44 * Byte swapping:  If the Mesa host and the X display use a different
45 * byte order then there's some trickiness to be aware of when using
46 * XImages.  The byte ordering used for the XImage is that of the X
47 * display, not the Mesa host.
48 * The color-to-pixel encoding for True/DirectColor must be done
49 * according to the display's visual red_mask, green_mask, and blue_mask.
50 * If XPutPixel is used to put a pixel into an XImage then XPutPixel will
51 * do byte swapping if needed.  If one wants to directly "poke" the pixel
52 * into the XImage's buffer then the pixel must be byte swapped first.  In
53 * Mesa, when byte swapping is needed we use the PF_TRUECOLOR pixel format
54 * and use XPutPixel everywhere except in the implementation of
55 * glClear(GL_COLOR_BUFFER_BIT).  We want this function to be fast so
56 * instead of using XPutPixel we "poke" our values after byte-swapping
57 * the clear pixel value if needed.
58 *
59 */
60
61#ifdef __CYGWIN__
62#undef WIN32
63#undef __WIN32__
64#endif
65
66#include "glxheader.h"
67#include "GL/xmesa.h"
68#include "xmesaP.h"
69#include "context.h"
70#include "extensions.h"
71#include "glthread.h"
72#include "matrix.h"
73#include "mem.h"
74#include "mmath.h"
75#include "mtypes.h"
76#ifdef HAVE_CONFIG_H
77#include "conf.h"
78#endif
79#include "macros.h"
80#include "texformat.h"
81#include "texstore.h"
82#include "swrast/swrast.h"
83#include "swrast_setup/swrast_setup.h"
84#include "array_cache/acache.h"
85#include "tnl/tnl.h"
86
87#ifndef GLX_NONE_EXT
88#define GLX_NONE_EXT 0x8000
89#endif
90
91
92/*
93 * Global X driver lock
94 */
95_glthread_Mutex _xmesa_lock;
96
97
98
99/*
100 * Lookup tables for HPCR pixel format:
101 */
102static short hpcr_rgbTbl[3][256] = {
103{
104 16,  16,  17,  17,  18,  18,  19,  19,  20,  20,  21,  21,  22,  22,  23,  23,
105 24,  24,  25,  25,  26,  26,  27,  27,  28,  28,  29,  29,  30,  30,  31,  31,
106 32,  32,  33,  33,  34,  34,  35,  35,  36,  36,  37,  37,  38,  38,  39,  39,
107 32,  33,  34,  35,  36,  37,  38,  39,  40,  41,  42,  43,  44,  45,  46,  47,
108 48,  49,  50,  51,  52,  53,  54,  55,  56,  57,  58,  59,  60,  61,  62,  63,
109 64,  65,  66,  67,  68,  69,  70,  71,  72,  73,  74,  75,  76,  77,  78,  79,
110 80,  81,  82,  83,  84,  85,  86,  87,  88,  89,  90,  91,  92,  93,  94,  95,
111 96,  97,  98,  99, 100, 101, 102, 103, 104, 105, 106, 107, 108, 109, 110, 111,
112112, 113, 114, 115, 116, 117, 118, 119, 120, 121, 122, 123, 124, 125, 126, 127,
113128, 129, 130, 131, 132, 133, 134, 135, 136, 137, 138, 139, 140, 141, 142, 143,
114144, 145, 146, 147, 148, 149, 150, 151, 152, 153, 154, 155, 156, 157, 158, 159,
115160, 161, 162, 163, 164, 165, 166, 167, 168, 169, 170, 171, 172, 173, 174, 175,
116176, 177, 178, 179, 180, 181, 182, 183, 184, 185, 186, 187, 188, 189, 190, 191,
117192, 193, 194, 195, 196, 197, 198, 199, 200, 201, 202, 203, 204, 205, 206, 207,
118208, 209, 210, 211, 212, 213, 214, 215, 216, 217, 218, 219, 220, 221, 222, 223,
119224, 225, 226, 227, 228, 229, 230, 231, 232, 233, 234, 235, 236, 237, 238, 239
120},
121{
122 16,  16,  17,  17,  18,  18,  19,  19,  20,  20,  21,  21,  22,  22,  23,  23,
123 24,  24,  25,  25,  26,  26,  27,  27,  28,  28,  29,  29,  30,  30,  31,  31,
124 32,  32,  33,  33,  34,  34,  35,  35,  36,  36,  37,  37,  38,  38,  39,  39,
125 32,  33,  34,  35,  36,  37,  38,  39,  40,  41,  42,  43,  44,  45,  46,  47,
126 48,  49,  50,  51,  52,  53,  54,  55,  56,  57,  58,  59,  60,  61,  62,  63,
127 64,  65,  66,  67,  68,  69,  70,  71,  72,  73,  74,  75,  76,  77,  78,  79,
128 80,  81,  82,  83,  84,  85,  86,  87,  88,  89,  90,  91,  92,  93,  94,  95,
129 96,  97,  98,  99, 100, 101, 102, 103, 104, 105, 106, 107, 108, 109, 110, 111,
130112, 113, 114, 115, 116, 117, 118, 119, 120, 121, 122, 123, 124, 125, 126, 127,
131128, 129, 130, 131, 132, 133, 134, 135, 136, 137, 138, 139, 140, 141, 142, 143,
132144, 145, 146, 147, 148, 149, 150, 151, 152, 153, 154, 155, 156, 157, 158, 159,
133160, 161, 162, 163, 164, 165, 166, 167, 168, 169, 170, 171, 172, 173, 174, 175,
134176, 177, 178, 179, 180, 181, 182, 183, 184, 185, 186, 187, 188, 189, 190, 191,
135192, 193, 194, 195, 196, 197, 198, 199, 200, 201, 202, 203, 204, 205, 206, 207,
136208, 209, 210, 211, 212, 213, 214, 215, 216, 217, 218, 219, 220, 221, 222, 223,
137224, 225, 226, 227, 228, 229, 230, 231, 232, 233, 234, 235, 236, 237, 238, 239
138},
139{
140 32,  32,  33,  33,  34,  34,  35,  35,  36,  36,  37,  37,  38,  38,  39,  39,
141 40,  40,  41,  41,  42,  42,  43,  43,  44,  44,  45,  45,  46,  46,  47,  47,
142 48,  48,  49,  49,  50,  50,  51,  51,  52,  52,  53,  53,  54,  54,  55,  55,
143 56,  56,  57,  57,  58,  58,  59,  59,  60,  60,  61,  61,  62,  62,  63,  63,
144 64,  64,  65,  65,  66,  66,  67,  67,  68,  68,  69,  69,  70,  70,  71,  71,
145 72,  72,  73,  73,  74,  74,  75,  75,  76,  76,  77,  77,  78,  78,  79,  79,
146 80,  80,  81,  81,  82,  82,  83,  83,  84,  84,  85,  85,  86,  86,  87,  87,
147 80,  81,  82,  83,  84,  85,  86,  87,  88,  89,  90,  91,  92,  93,  94,  95,
148 96,  97,  98,  99, 100, 101, 102, 103, 104, 105, 106, 107, 108, 109, 110, 111,
149112, 113, 114, 115, 116, 117, 118, 119, 120, 121, 122, 123, 124, 125, 126, 127,
150128, 129, 130, 131, 132, 133, 134, 135, 136, 137, 138, 139, 140, 141, 142, 143,
151144, 145, 146, 147, 148, 149, 150, 151, 152, 153, 154, 155, 156, 157, 158, 159,
152160, 161, 162, 163, 164, 165, 166, 167, 168, 169, 170, 171, 172, 173, 174, 175,
153176, 177, 178, 179, 180, 181, 182, 183, 184, 185, 186, 187, 188, 189, 190, 191,
154192, 193, 194, 195, 196, 197, 198, 199, 200, 201, 202, 203, 204, 205, 206, 207,
155208, 209, 210, 211, 212, 213, 214, 215, 216, 217, 218, 219, 220, 221, 222, 223
156}
157};
158
159
160
161/**********************************************************************/
162/*****                     X Utility Functions                    *****/
163/**********************************************************************/
164
165
166/*
167 * X/Mesa error reporting function:
168 */
169static void error( const char *msg )
170{
171   (void)DitherValues;		/* Muffle compiler */
172
173   if (getenv("MESA_DEBUG"))
174      fprintf( stderr, "X/Mesa error: %s\n", msg );
175}
176
177
178/*
179 * Return the host's byte order as LSBFirst or MSBFirst ala X.
180 */
181#ifndef XFree86Server
182static int host_byte_order( void )
183{
184   int i = 1;
185   char *cptr = (char *) &i;
186   return (*cptr==1) ? LSBFirst : MSBFirst;
187}
188#endif
189
190
191/*
192 * Error handling.
193 */
194#ifndef XFree86Server
195static int mesaXErrorFlag = 0;
196
197static int mesaHandleXError( XMesaDisplay *dpy, XErrorEvent *event )
198{
199   (void) dpy;
200   (void) event;
201   mesaXErrorFlag = 1;
202   return 0;
203}
204#endif
205
206
207/*
208 * Check if the X Shared Memory extension is available.
209 * Return:  0 = not available
210 *          1 = shared XImage support available
211 *          2 = shared Pixmap support available also
212 */
213#ifndef XFree86Server
214static int check_for_xshm( XMesaDisplay *display )
215{
216#ifdef USE_XSHM
217   int major, minor, ignore;
218   Bool pixmaps;
219
220   if (XQueryExtension( display, "MIT-SHM", &ignore, &ignore, &ignore )) {
221      if (XShmQueryVersion( display, &major, &minor, &pixmaps )==True) {
222	 return (pixmaps==True) ? 2 : 1;
223      }
224      else {
225	 return 0;
226      }
227   }
228   else {
229      return 0;
230   }
231#else
232   /* Can't compile XSHM support */
233   return 0;
234#endif
235}
236#endif
237
238
239/*
240 * Return the width and height of the given drawable.
241 */
242static void get_drawable_size( XMesaDisplay *dpy, XMesaDrawable d,
243                               unsigned int *width, unsigned int *height)
244{
245#ifdef XFree86Server
246    (void) dpy;
247    *width = d->width;
248    *height = d->height;
249#else
250   Window root;
251   int x, y;
252   unsigned int bw, depth;
253
254   _glthread_LOCK_MUTEX(_xmesa_lock);
255   XGetGeometry( dpy, d, &root, &x, &y, width, height, &bw, &depth );
256   _glthread_UNLOCK_MUTEX(_xmesa_lock);
257#endif
258}
259
260
261/*
262 * Apply gamma correction to an intensity value in [0..max].  Return the
263 * new intensity value.
264 */
265static GLint gamma_adjust( GLfloat gamma, GLint value, GLint max )
266{
267   if (gamma == 1.0) {
268      return value;
269   }
270   else {
271      double x = (double) value / (double) max;
272      return IROUND_POS((GLfloat) max * pow(x, 1.0F/gamma));
273   }
274}
275
276
277
278/*
279 * Return the true number of bits per pixel for XImages.
280 * For example, if we request a 24-bit deep visual we may actually need/get
281 * 32bpp XImages.  This function returns the appropriate bpp.
282 * Input:  dpy - the X display
283 *         visinfo - desribes the visual to be used for XImages
284 * Return:  true number of bits per pixel for XImages
285 */
286#ifdef XFree86Server
287
288static int bits_per_pixel( XMesaVisual xmv )
289{
290   XMesaVisualInfo visinfo = xmv->visinfo;
291   const int depth = visinfo->nplanes;
292   int i;
293   for (i = 0; i < screenInfo.numPixmapFormats; i++) {
294      if (screenInfo.formats[i].depth == depth)
295         return screenInfo.formats[i].bitsPerPixel;
296   }
297   return depth;  /* should never get here, but this should be safe */
298}
299
300#else
301
302static int bits_per_pixel( XMesaVisual xmv )
303{
304   XMesaDisplay *dpy = xmv->display;
305   XMesaVisualInfo visinfo = xmv->visinfo;
306   XMesaImage *img;
307   int bitsPerPixel;
308   /* Create a temporary XImage */
309   img = XCreateImage( dpy, visinfo->visual, visinfo->depth,
310		       ZPixmap, 0,           /*format, offset*/
311		       (char*) MALLOC(8),    /*data*/
312		       1, 1,                 /*width, height*/
313		       32,                   /*bitmap_pad*/
314		       0                     /*bytes_per_line*/
315                     );
316   assert(img);
317   /* grab the bits/pixel value */
318   bitsPerPixel = img->bits_per_pixel;
319   /* free the XImage */
320   FREE( img->data );
321   img->data = NULL;
322   XMesaDestroyImage( img );
323   return bitsPerPixel;
324}
325#endif
326
327
328
329/*
330 * Determine if a given X window ID is valid (window exists).
331 * Do this by calling XGetWindowAttributes() for the window and
332 * checking if we catch an X error.
333 * Input:  dpy - the display
334 *         win - the window to check for existance
335 * Return:  GL_TRUE - window exists
336 *          GL_FALSE - window doesn't exist
337 */
338#ifndef XFree86Server
339static GLboolean WindowExistsFlag;
340
341static int window_exists_err_handler( XMesaDisplay* dpy, XErrorEvent* xerr )
342{
343   (void) dpy;
344   if (xerr->error_code == BadWindow) {
345      WindowExistsFlag = GL_FALSE;
346   }
347   return 0;
348}
349
350static GLboolean window_exists( XMesaDisplay *dpy, Window win )
351{
352   XWindowAttributes wa;
353   int (*old_handler)( XMesaDisplay*, XErrorEvent* );
354   WindowExistsFlag = GL_TRUE;
355   old_handler = XSetErrorHandler(window_exists_err_handler);
356   XGetWindowAttributes( dpy, win, &wa ); /* dummy request */
357   XSetErrorHandler(old_handler);
358   return WindowExistsFlag;
359}
360#endif
361
362
363
364/**********************************************************************/
365/*****                Linked list of XMesaBuffers                 *****/
366/**********************************************************************/
367
368static XMesaBuffer XMesaBufferList = NULL;
369
370
371/* Allocate a new XMesaBuffer, add to linked list */
372static XMesaBuffer alloc_xmesa_buffer(void)
373{
374   XMesaBuffer b = (XMesaBuffer) CALLOC_STRUCT(xmesa_buffer);
375   if (b) {
376      b->Next = XMesaBufferList;
377      XMesaBufferList = b;
378   }
379   return b;
380}
381
382
383/*
384 * Find an XMesaBuffer by matching X display and colormap but NOT matching
385 * the notThis buffer.
386 */
387static XMesaBuffer find_xmesa_buffer(XMesaDisplay *dpy,
388                                     XMesaColormap cmap,
389                                     XMesaBuffer notThis)
390{
391   XMesaBuffer b;
392   for (b=XMesaBufferList; b; b=b->Next) {
393      if (b->display==dpy && b->cmap==cmap && b!=notThis) {
394         return b;
395      }
396   }
397   return NULL;
398}
399
400
401/*
402 * Free an XMesaBuffer, remove from linked list, perhaps free X colormap
403 * entries.
404 */
405static void free_xmesa_buffer(int client, XMesaBuffer buffer)
406{
407   XMesaBuffer prev = NULL, b;
408   (void) client;
409   for (b=XMesaBufferList; b; b=b->Next) {
410      if (b==buffer) {
411         /* unlink bufer from list */
412         if (prev)
413            prev->Next = buffer->Next;
414         else
415            XMesaBufferList = buffer->Next;
416         /* Check to free X colors */
417         if (buffer->num_alloced>0) {
418            /* If no other buffer uses this X colormap then free the colors. */
419            if (!find_xmesa_buffer(buffer->display, buffer->cmap, buffer)) {
420#ifdef XFree86Server
421               (void)FreeColors(buffer->cmap, client,
422				buffer->num_alloced, buffer->alloced_colors,
423				0);
424#else
425               XFreeColors(buffer->display, buffer->cmap,
426                           buffer->alloced_colors, buffer->num_alloced, 0);
427#endif
428            }
429         }
430
431         _mesa_free_framebuffer_data(&buffer->mesa_buffer);
432         FREE(buffer);
433
434         return;
435      }
436      /* continue search */
437      prev = b;
438   }
439   /* buffer not found in XMesaBufferList */
440   _mesa_problem(NULL,"free_xmesa_buffer() - buffer not found\n");
441}
442
443
444/* Copy X color table stuff from one XMesaBuffer to another. */
445static void copy_colortable_info(XMesaBuffer dst, const XMesaBuffer src)
446{
447   MEMCPY(dst->color_table, src->color_table, sizeof(src->color_table));
448   MEMCPY(dst->pixel_to_r, src->pixel_to_r, sizeof(src->pixel_to_r));
449   MEMCPY(dst->pixel_to_g, src->pixel_to_g, sizeof(src->pixel_to_g));
450   MEMCPY(dst->pixel_to_b, src->pixel_to_b, sizeof(src->pixel_to_b));
451   dst->num_alloced = src->num_alloced;
452   MEMCPY(dst->alloced_colors, src->alloced_colors,
453          sizeof(src->alloced_colors));
454}
455
456
457
458/**********************************************************************/
459/*****                   Misc Private Functions                   *****/
460/**********************************************************************/
461
462
463/*
464 * Return number of bits set in n.
465 */
466static int bitcount( unsigned long n )
467{
468   int bits;
469   for (bits=0; n>0; n=n>>1) {
470      if (n&1) {
471         bits++;
472      }
473   }
474   return bits;
475}
476
477
478
479/*
480 * Allocate a shared memory XImage back buffer for the given XMesaBuffer.
481 * Return:  GL_TRUE if success, GL_FALSE if error
482 */
483#ifndef XFree86Server
484static GLboolean alloc_shm_back_buffer( XMesaBuffer b )
485{
486#ifdef USE_XSHM
487   /*
488    * We have to do a _lot_ of error checking here to be sure we can
489    * really use the XSHM extension.  It seems different servers trigger
490    * errors at different points if the extension won't work.  Therefore
491    * we have to be very careful...
492    */
493   GC gc;
494   int (*old_handler)( XMesaDisplay *, XErrorEvent * );
495
496   b->backimage = XShmCreateImage( b->xm_visual->display,
497                                   b->xm_visual->visinfo->visual,
498                                   b->xm_visual->visinfo->depth,
499				   ZPixmap, NULL, &b->shminfo,
500				   b->width, b->height );
501   if (b->backimage == NULL) {
502      error("alloc_back_buffer: Shared memory error (XShmCreateImage), disabling.");
503      b->shm = 0;
504      return GL_FALSE;
505   }
506
507   b->shminfo.shmid = shmget( IPC_PRIVATE, b->backimage->bytes_per_line
508			     * b->backimage->height, IPC_CREAT|0777 );
509   if (b->shminfo.shmid < 0) {
510      if (getenv("MESA_DEBUG"))
511          perror("alloc_back_buffer");
512      XDestroyImage( b->backimage );
513      b->backimage = NULL;
514      error("alloc_back_buffer: Shared memory error (shmget), disabling.");
515      b->shm = 0;
516      return GL_FALSE;
517   }
518
519   b->shminfo.shmaddr = b->backimage->data
520                      = (char*)shmat( b->shminfo.shmid, 0, 0 );
521   if (b->shminfo.shmaddr == (char *) -1) {
522      if (getenv("MESA_DEBUG"))
523          perror("alloc_back_buffer");
524      XDestroyImage( b->backimage );
525      shmctl( b->shminfo.shmid, IPC_RMID, 0 );
526      b->backimage = NULL;
527      error("alloc_back_buffer: Shared memory error (shmat), disabling.");
528      b->shm = 0;
529      return GL_FALSE;
530   }
531
532   b->shminfo.readOnly = False;
533   mesaXErrorFlag = 0;
534   old_handler = XSetErrorHandler( mesaHandleXError );
535   /* This may trigger the X protocol error we're ready to catch: */
536   XShmAttach( b->xm_visual->display, &b->shminfo );
537   XSync( b->xm_visual->display, False );
538
539   if (mesaXErrorFlag) {
540      /* we are on a remote display, this error is normal, don't print it */
541      XFlush( b->xm_visual->display );
542      mesaXErrorFlag = 0;
543      XDestroyImage( b->backimage );
544      shmdt( b->shminfo.shmaddr );
545      shmctl( b->shminfo.shmid, IPC_RMID, 0 );
546      b->backimage = NULL;
547      b->shm = 0;
548      (void) XSetErrorHandler( old_handler );
549      return GL_FALSE;
550   }
551
552   shmctl( b->shminfo.shmid, IPC_RMID, 0 ); /* nobody else needs it */
553
554   /* Finally, try an XShmPutImage to be really sure the extension works */
555   gc = XCreateGC( b->xm_visual->display, b->frontbuffer, 0, NULL );
556   XShmPutImage( b->xm_visual->display, b->frontbuffer, gc,
557		 b->backimage, 0, 0, 0, 0, 1, 1 /*one pixel*/, False );
558   XSync( b->xm_visual->display, False );
559   XFreeGC( b->xm_visual->display, gc );
560   (void) XSetErrorHandler( old_handler );
561   if (mesaXErrorFlag) {
562      XFlush( b->xm_visual->display );
563      mesaXErrorFlag = 0;
564      XDestroyImage( b->backimage );
565      shmdt( b->shminfo.shmaddr );
566      shmctl( b->shminfo.shmid, IPC_RMID, 0 );
567      b->backimage = NULL;
568      b->shm = 0;
569      return GL_FALSE;
570   }
571
572   if (b->backimage) {
573      int height = b->backimage->height;
574      /* Needed by PIXELADDR1 macro */
575      b->ximage_width1 = b->backimage->bytes_per_line;
576      b->ximage_origin1 = (GLubyte *) b->backimage->data
577                        + b->ximage_width1 * (height-1);
578      /* Needed by PIXELADDR2 macro */
579      b->ximage_width2 = b->backimage->bytes_per_line / 2;
580      b->ximage_origin2 = (GLushort *) b->backimage->data
581                        + b->ximage_width2 * (height-1);
582      /* Needed by PIXELADDR3 macro */
583      b->ximage_width3 = b->backimage->bytes_per_line;
584      b->ximage_origin3 = (GLubyte *) b->backimage->data
585                        + b->ximage_width3 * (height-1);
586      /* Needed by PIXELADDR4 macro */
587      b->ximage_width4 = b->backimage->width;
588      b->ximage_origin4 = (GLuint *) b->backimage->data
589                        + b->ximage_width4 * (height-1);
590   }
591
592   return GL_TRUE;
593#else
594   /* Can't compile XSHM support */
595   return GL_FALSE;
596#endif
597}
598#endif
599
600
601
602/*
603 * Setup an off-screen pixmap or Ximage to use as the back buffer.
604 * Input:  b - the X/Mesa buffer
605 */
606void xmesa_alloc_back_buffer( XMesaBuffer b )
607{
608   if (b->db_state==BACK_XIMAGE) {
609      /* Deallocate the old backimage, if any */
610      if (b->backimage) {
611#if defined(USE_XSHM) && !defined(XFree86Server)
612	 if (b->shm) {
613	    XShmDetach( b->xm_visual->display, &b->shminfo );
614	    XDestroyImage( b->backimage );
615	    shmdt( b->shminfo.shmaddr );
616	 }
617	 else
618#endif
619	   XMesaDestroyImage( b->backimage );
620	 b->backimage = NULL;
621      }
622
623      /* Allocate new back buffer */
624#ifdef XFree86Server
625      {
626	 /* Allocate a regular XImage for the back buffer. */
627	 b->backimage = XMesaCreateImage(b->xm_visual->BitsPerPixel,
628					 b->width, b->height, NULL);
629#else
630      if (b->shm==0
631	  || alloc_shm_back_buffer(b)==GL_FALSE
632	  ) {
633	 /* Allocate a regular XImage for the back buffer. */
634	 b->backimage = XCreateImage( b->xm_visual->display,
635                                      b->xm_visual->visinfo->visual,
636                                      GET_VISUAL_DEPTH(b->xm_visual),
637				      ZPixmap, 0,   /* format, offset */
638				      NULL, b->width, b->height,
639				      8, 0 );  /* pad, bytes_per_line */
640#endif
641	 if (!b->backimage) {
642	    error("alloc_back_buffer: XCreateImage failed.");
643	 }
644         b->backimage->data = (char *) MALLOC( b->backimage->height
645                                             * b->backimage->bytes_per_line );
646         if (!b->backimage->data) {
647            error("alloc_back_buffer: MALLOC failed.");
648            XMesaDestroyImage( b->backimage );
649            b->backimage = NULL;
650         }
651      }
652      b->backpixmap = None;
653   }
654   else if (b->db_state==BACK_PIXMAP) {
655      XMesaPixmap old_pixmap = b->backpixmap;
656      /* Free the old back pixmap */
657      if (b->backpixmap) {
658	 XMesaFreePixmap( b->xm_visual->display, b->backpixmap );
659      }
660      /* Allocate new back pixmap */
661      b->backpixmap = XMesaCreatePixmap( b->xm_visual->display, b->frontbuffer,
662					 b->width, b->height,
663					 GET_VISUAL_DEPTH(b->xm_visual) );
664      b->backimage = NULL;
665      /* update other references to backpixmap */
666      if (b->buffer==(XMesaDrawable)old_pixmap) {
667	 b->buffer = (XMesaDrawable)b->backpixmap;
668      }
669   }
670}
671
672
673
674/*
675 * A replacement for XAllocColor.  This function should never
676 * fail to allocate a color.  When XAllocColor fails, we return
677 * the nearest matching color.  If we have to allocate many colors
678 * this function isn't too efficient; the XQueryColors() could be
679 * done just once.
680 * Written by Michael Pichler, Brian Paul, Mark Kilgard
681 * Input:  dpy - X display
682 *         cmap - X colormap
683 *         cmapSize - size of colormap
684 * In/Out: color - the XColor struct
685 * Output:  exact - 1=exact color match, 0=closest match
686 *          alloced - 1=XAlloc worked, 0=XAlloc failed
687 */
688static void
689noFaultXAllocColor( int client,
690                    XMesaDisplay *dpy,
691                    XMesaColormap cmap,
692                    int cmapSize,
693                    XMesaColor *color,
694                    int *exact, int *alloced )
695{
696#ifdef XFree86Server
697   Pixel *ppixIn;
698   xrgb *ctable;
699#else
700   /* we'll try to cache ctable for better remote display performance */
701   static Display *prevDisplay = NULL;
702   static XMesaColormap prevCmap = 0;
703   static int prevCmapSize = 0;
704   static XMesaColor *ctable = NULL;
705#endif
706   XMesaColor subColor;
707   int i, bestmatch;
708   double mindist;       /* 3*2^16^2 exceeds long int precision. */
709
710   (void) client;
711
712   /* First try just using XAllocColor. */
713#ifdef XFree86Server
714   if (AllocColor(cmap,
715		  &color->red, &color->green, &color->blue,
716		  &color->pixel,
717		  client) == Success) {
718#else
719   if (XAllocColor(dpy, cmap, color)) {
720#endif
721      *exact = 1;
722      *alloced = 1;
723      return;
724   }
725
726   /* Alloc failed, search for closest match */
727
728   /* Retrieve color table entries. */
729   /* XXX alloca candidate. */
730#ifdef XFree86Server
731   ppixIn = (Pixel *) MALLOC(cmapSize * sizeof(Pixel));
732   ctable = (xrgb *) MALLOC(cmapSize * sizeof(xrgb));
733   for (i = 0; i < cmapSize; i++) {
734      ppixIn[i] = i;
735   }
736   QueryColors(cmap, cmapSize, ppixIn, ctable);
737#else
738   if (prevDisplay != dpy || prevCmap != cmap
739       || prevCmapSize != cmapSize || !ctable) {
740      /* free previously cached color table */
741      if (ctable)
742         FREE(ctable);
743      /* Get the color table from X */
744      ctable = (XMesaColor *) MALLOC(cmapSize * sizeof(XMesaColor));
745      assert(ctable);
746      for (i = 0; i < cmapSize; i++) {
747         ctable[i].pixel = i;
748      }
749      XQueryColors(dpy, cmap, ctable, cmapSize);
750      prevDisplay = dpy;
751      prevCmap = cmap;
752      prevCmapSize = cmapSize;
753   }
754#endif
755
756   /* Find best match. */
757   bestmatch = -1;
758   mindist = 0.0;
759   for (i = 0; i < cmapSize; i++) {
760      double dr = 0.30 * ((double) color->red - (double) ctable[i].red);
761      double dg = 0.59 * ((double) color->green - (double) ctable[i].green);
762      double db = 0.11 * ((double) color->blue - (double) ctable[i].blue);
763      double dist = dr * dr + dg * dg + db * db;
764      if (bestmatch < 0 || dist < mindist) {
765         bestmatch = i;
766         mindist = dist;
767      }
768   }
769
770   /* Return result. */
771   subColor.red   = ctable[bestmatch].red;
772   subColor.green = ctable[bestmatch].green;
773   subColor.blue  = ctable[bestmatch].blue;
774   /* Try to allocate the closest match color.  This should only
775    * fail if the cell is read/write.  Otherwise, we're incrementing
776    * the cell's reference count.
777    */
778#ifdef XFree86Server
779   if (AllocColor(cmap,
780		  &subColor.red, &subColor.green, &subColor.blue,
781		  &subColor.pixel,
782		  client) == Success) {
783#else
784   if (XAllocColor(dpy, cmap, &subColor)) {
785#endif
786      *alloced = 1;
787   }
788   else {
789      /* do this to work around a problem reported by Frank Ortega */
790      subColor.pixel = (unsigned long) bestmatch;
791      subColor.red   = ctable[bestmatch].red;
792      subColor.green = ctable[bestmatch].green;
793      subColor.blue  = ctable[bestmatch].blue;
794      subColor.flags = DoRed | DoGreen | DoBlue;
795      *alloced = 0;
796   }
797#ifdef XFree86Server
798   FREE(ppixIn);
799   FREE(ctable);
800#else
801   /* don't free table, save it for next time */
802#endif
803
804   *color = subColor;
805   *exact = 0;
806}
807
808
809
810
811/*
812 * Do setup for PF_GRAYSCALE pixel format.
813 * Note that buffer may be NULL.
814 */
815static GLboolean setup_grayscale( int client, XMesaVisual v,
816                                  XMesaBuffer buffer, XMesaColormap cmap )
817{
818   if (GET_VISUAL_DEPTH(v)<4 || GET_VISUAL_DEPTH(v)>16) {
819      return GL_FALSE;
820   }
821
822   if (buffer) {
823      XMesaBuffer prevBuffer;
824
825      if (!cmap) {
826         return GL_FALSE;
827      }
828
829      prevBuffer = find_xmesa_buffer(v->display, cmap, buffer);
830      if (prevBuffer &&
831          (buffer->xm_visual->mesa_visual.rgbMode ==
832           prevBuffer->xm_visual->mesa_visual.rgbMode)) {
833         /* Copy colormap stuff from previous XMesaBuffer which uses same
834          * X colormap.  Do this to avoid time spent in noFaultXAllocColor.
835          */
836         copy_colortable_info(buffer, prevBuffer);
837      }
838      else {
839         /* Allocate 256 shades of gray */
840         int gray;
841         int colorsfailed = 0;
842         for (gray=0;gray<256;gray++) {
843            GLint r = gamma_adjust( v->RedGamma,   gray, 255 );
844            GLint g = gamma_adjust( v->GreenGamma, gray, 255 );
845            GLint b = gamma_adjust( v->BlueGamma,  gray, 255 );
846            int exact, alloced;
847            XMesaColor xcol;
848            xcol.red   = (r << 8) | r;
849            xcol.green = (g << 8) | g;
850            xcol.blue  = (b << 8) | b;
851            noFaultXAllocColor( client, v->display,
852                                cmap, GET_COLORMAP_SIZE(v),
853                                &xcol, &exact, &alloced );
854            if (!exact) {
855               colorsfailed++;
856            }
857            if (alloced) {
858               assert(buffer->num_alloced<256);
859               buffer->alloced_colors[buffer->num_alloced] = xcol.pixel;
860               buffer->num_alloced++;
861            }
862
863            /*OLD
864            assert(gray < 576);
865            buffer->color_table[gray*3+0] = xcol.pixel;
866            buffer->color_table[gray*3+1] = xcol.pixel;
867            buffer->color_table[gray*3+2] = xcol.pixel;
868            assert(xcol.pixel < 65536);
869            buffer->pixel_to_r[xcol.pixel] = gray * 30 / 100;
870            buffer->pixel_to_g[xcol.pixel] = gray * 59 / 100;
871            buffer->pixel_to_b[xcol.pixel] = gray * 11 / 100;
872            */
873            buffer->color_table[gray] = xcol.pixel;
874            assert(xcol.pixel < 65536);
875            buffer->pixel_to_r[xcol.pixel] = gray;
876            buffer->pixel_to_g[xcol.pixel] = gray;
877            buffer->pixel_to_b[xcol.pixel] = gray;
878         }
879
880         if (colorsfailed && getenv("MESA_DEBUG")) {
881            fprintf( stderr,
882                  "Note: %d out of 256 needed colors do not match exactly.\n",
883                  colorsfailed );
884         }
885      }
886   }
887
888   v->dithered_pf = PF_GRAYSCALE;
889   v->undithered_pf = PF_GRAYSCALE;
890   return GL_TRUE;
891}
892
893
894
895/*
896 * Setup RGB rendering for a window with a PseudoColor, StaticColor,
897 * or 8-bit TrueColor visual visual.  We try to allocate a palette of 225
898 * colors (5 red, 9 green, 5 blue) and dither to approximate a 24-bit RGB
899 * color.  While this function was originally designed just for 8-bit
900 * visuals, it has also proven to work from 4-bit up to 16-bit visuals.
901 * Dithering code contributed by Bob Mercier.
902 */
903static GLboolean setup_dithered_color( int client, XMesaVisual v,
904                                       XMesaBuffer buffer, XMesaColormap cmap )
905{
906   if (GET_VISUAL_DEPTH(v)<4 || GET_VISUAL_DEPTH(v)>16) {
907      return GL_FALSE;
908   }
909
910   if (buffer) {
911      XMesaBuffer prevBuffer;
912
913      if (!cmap) {
914         return GL_FALSE;
915      }
916
917      prevBuffer = find_xmesa_buffer(v->display, cmap, buffer);
918      if (prevBuffer &&
919          (buffer->xm_visual->mesa_visual.rgbMode ==
920           prevBuffer->xm_visual->mesa_visual.rgbMode)) {
921         /* Copy colormap stuff from previous, matching XMesaBuffer.
922          * Do this to avoid time spent in noFaultXAllocColor.
923          */
924         copy_colortable_info(buffer, prevBuffer);
925      }
926      else {
927         /* Allocate X colors and initialize color_table[], red_table[], etc */
928         int r, g, b, i;
929         int colorsfailed = 0;
930         for (r = 0; r < _R; r++) {
931            for (g = 0; g < _G; g++) {
932               for (b = 0; b < _B; b++) {
933                  XMesaColor xcol;
934                  int exact, alloced;
935                  xcol.red  =gamma_adjust(v->RedGamma,   r*65535/(_R-1),65535);
936                  xcol.green=gamma_adjust(v->GreenGamma, g*65535/(_G-1),65535);
937                  xcol.blue =gamma_adjust(v->BlueGamma,  b*65535/(_B-1),65535);
938                  noFaultXAllocColor( client, v->display,
939                                      cmap, GET_COLORMAP_SIZE(v),
940                                      &xcol, &exact, &alloced );
941                  if (!exact) {
942                     colorsfailed++;
943                  }
944                  if (alloced) {
945                     assert(buffer->num_alloced<256);
946                     buffer->alloced_colors[buffer->num_alloced] = xcol.pixel;
947                     buffer->num_alloced++;
948                  }
949                  i = _MIX( r, g, b );
950                  assert(i < 576);
951                  buffer->color_table[i] = xcol.pixel;
952                  assert(xcol.pixel < 65536);
953                  buffer->pixel_to_r[xcol.pixel] = r * 255 / (_R-1);
954                  buffer->pixel_to_g[xcol.pixel] = g * 255 / (_G-1);
955                  buffer->pixel_to_b[xcol.pixel] = b * 255 / (_B-1);
956               }
957            }
958         }
959
960         if (colorsfailed && getenv("MESA_DEBUG")) {
961            fprintf( stderr,
962                  "Note: %d out of %d needed colors do not match exactly.\n",
963                  colorsfailed, _R*_G*_B );
964         }
965      }
966   }
967
968   v->dithered_pf = PF_DITHER;
969   v->undithered_pf = PF_LOOKUP;
970   return GL_TRUE;
971}
972
973
974/*
975 * Setup for Hewlett Packard Color Recovery 8-bit TrueColor mode.
976 * HPCR simulates 24-bit color fidelity with an 8-bit frame buffer.
977 * Special dithering tables have to be initialized.
978 */
979static void setup_8bit_hpcr( XMesaVisual v )
980{
981   /* HP Color Recovery contributed by:  Alex De Bruyn (ad@lms.be)
982    * To work properly, the atom _HP_RGB_SMOOTH_MAP_LIST must be defined
983    * on the root window AND the colormap obtainable by XGetRGBColormaps
984    * for that atom must be set on the window.  (see also tkInitWindow)
985    * If that colormap is not set, the output will look stripy.
986    */
987
988   /* Setup color tables with gamma correction */
989   int i;
990   double g;
991
992   g = 1.0 / v->RedGamma;
993   for (i=0; i<256; i++) {
994      GLint red = IROUND_POS(255.0 * pow( hpcr_rgbTbl[0][i]/255.0, g ));
995      v->hpcr_rgbTbl[0][i] = CLAMP( red, 16, 239 );
996   }
997
998   g = 1.0 / v->GreenGamma;
999   for (i=0; i<256; i++) {
1000      GLint green = IROUND_POS(255.0 * pow( hpcr_rgbTbl[1][i]/255.0, g ));
1001      v->hpcr_rgbTbl[1][i] = CLAMP( green, 16, 239 );
1002   }
1003
1004   g = 1.0 / v->BlueGamma;
1005   for (i=0; i<256; i++) {
1006      GLint blue = IROUND_POS(255.0 * pow( hpcr_rgbTbl[2][i]/255.0, g ));
1007      v->hpcr_rgbTbl[2][i] = CLAMP( blue, 32, 223 );
1008   }
1009   v->undithered_pf = PF_HPCR;  /* can't really disable dithering for now */
1010   v->dithered_pf = PF_HPCR;
1011
1012   /* which method should I use to clear */
1013   /* GL_FALSE: keep the ordinary method  */
1014   /* GL_TRUE : clear with dither pattern */
1015   v->hpcr_clear_flag = getenv("MESA_HPCR_CLEAR") ? GL_TRUE : GL_FALSE;
1016
1017   if (v->hpcr_clear_flag) {
1018      v->hpcr_clear_pixmap = XMesaCreatePixmap(v->display,
1019                                               DefaultRootWindow(v->display),
1020                                               16, 2, 8);
1021#ifndef XFree86Server
1022      v->hpcr_clear_ximage = XGetImage(v->display, v->hpcr_clear_pixmap,
1023                                       0, 0, 16, 2, AllPlanes, ZPixmap);
1024#endif
1025   }
1026}
1027
1028
1029/*
1030 * Setup RGB rendering for a window with a True/DirectColor visual.
1031 */
1032static void setup_truecolor( XMesaVisual v, XMesaBuffer buffer,
1033                             XMesaColormap cmap )
1034{
1035   unsigned long rmask, gmask, bmask;
1036   (void) buffer;
1037   (void) cmap;
1038
1039   /* Compute red multiplier (mask) and bit shift */
1040   v->rshift = 0;
1041   rmask = GET_REDMASK(v);
1042   while ((rmask & 1)==0) {
1043      v->rshift++;
1044      rmask = rmask >> 1;
1045   }
1046
1047   /* Compute green multiplier (mask) and bit shift */
1048   v->gshift = 0;
1049   gmask = GET_GREENMASK(v);
1050   while ((gmask & 1)==0) {
1051      v->gshift++;
1052      gmask = gmask >> 1;
1053   }
1054
1055   /* Compute blue multiplier (mask) and bit shift */
1056   v->bshift = 0;
1057   bmask = GET_BLUEMASK(v);
1058   while ((bmask & 1)==0) {
1059      v->bshift++;
1060      bmask = bmask >> 1;
1061   }
1062
1063   /*
1064    * Compute component-to-pixel lookup tables and dithering kernel
1065    */
1066   {
1067      static GLubyte kernel[16] = {
1068          0*16,  8*16,  2*16, 10*16,
1069         12*16,  4*16, 14*16,  6*16,
1070          3*16, 11*16,  1*16,  9*16,
1071         15*16,  7*16, 13*16,  5*16,
1072      };
1073      GLint rBits = bitcount(rmask);
1074      GLint gBits = bitcount(gmask);
1075      GLint bBits = bitcount(bmask);
1076      GLint maxBits;
1077      GLuint i;
1078
1079      /* convert pixel components in [0,_mask] to RGB values in [0,255] */
1080      for (i=0; i<=rmask; i++)
1081         v->PixelToR[i] = (unsigned char) ((i * 255) / rmask);
1082      for (i=0; i<=gmask; i++)
1083         v->PixelToG[i] = (unsigned char) ((i * 255) / gmask);
1084      for (i=0; i<=bmask; i++)
1085         v->PixelToB[i] = (unsigned char) ((i * 255) / bmask);
1086
1087      /* convert RGB values from [0,255] to pixel components */
1088
1089      for (i=0;i<256;i++) {
1090         GLint r = gamma_adjust(v->RedGamma,   i, 255);
1091         GLint g = gamma_adjust(v->GreenGamma, i, 255);
1092         GLint b = gamma_adjust(v->BlueGamma,  i, 255);
1093         v->RtoPixel[i] = (r >> (8-rBits)) << v->rshift;
1094         v->GtoPixel[i] = (g >> (8-gBits)) << v->gshift;
1095         v->BtoPixel[i] = (b >> (8-bBits)) << v->bshift;
1096      }
1097      /* overflow protection */
1098      for (i=256;i<512;i++) {
1099         v->RtoPixel[i] = v->RtoPixel[255];
1100         v->GtoPixel[i] = v->GtoPixel[255];
1101         v->BtoPixel[i] = v->BtoPixel[255];
1102      }
1103
1104      /* setup dithering kernel */
1105      maxBits = rBits;
1106      if (gBits > maxBits)  maxBits = gBits;
1107      if (bBits > maxBits)  maxBits = bBits;
1108      for (i=0;i<16;i++) {
1109         v->Kernel[i] = kernel[i] >> maxBits;
1110      }
1111
1112      v->undithered_pf = PF_TRUECOLOR;
1113      v->dithered_pf = (GET_VISUAL_DEPTH(v)<24) ? PF_TRUEDITHER : PF_TRUECOLOR;
1114   }
1115
1116   /*
1117    * Now check for TrueColor visuals which we can optimize.
1118    */
1119   if (   GET_REDMASK(v)  ==0x0000ff
1120       && GET_GREENMASK(v)==0x00ff00
1121       && GET_BLUEMASK(v) ==0xff0000
1122       && CHECK_BYTE_ORDER(v)
1123       && v->BitsPerPixel==32
1124       && sizeof(GLuint)==4
1125       && v->RedGamma==1.0 && v->GreenGamma==1.0 && v->BlueGamma==1.0) {
1126      /* common 32 bpp config used on SGI, Sun */
1127      v->undithered_pf = v->dithered_pf = PF_8A8B8G8R;
1128   }
1129   else if (GET_REDMASK(v)  ==0xff0000
1130       &&   GET_GREENMASK(v)==0x00ff00
1131       &&   GET_BLUEMASK(v) ==0x0000ff
1132       && CHECK_BYTE_ORDER(v)
1133       && v->BitsPerPixel==32
1134       && sizeof(GLuint)==4
1135       && v->RedGamma==1.0 && v->GreenGamma==1.0 && v->BlueGamma==1.0) {
1136      /* common 32 bpp config used on Linux, HP, IBM */
1137      v->undithered_pf = v->dithered_pf = PF_8R8G8B;
1138   }
1139   else if (GET_REDMASK(v)  ==0xff0000
1140       &&   GET_GREENMASK(v)==0x00ff00
1141       &&   GET_BLUEMASK(v) ==0x0000ff
1142       && CHECK_BYTE_ORDER(v)
1143       && v->BitsPerPixel==24
1144       && sizeof(GLuint)==4
1145       && v->RedGamma==1.0 && v->GreenGamma==1.0 && v->BlueGamma==1.0) {
1146      /* common packed 24 bpp config used on Linux */
1147      v->undithered_pf = v->dithered_pf = PF_8R8G8B24;
1148   }
1149   else if (GET_REDMASK(v)  ==0xf800
1150       &&   GET_GREENMASK(v)==0x07e0
1151       &&   GET_BLUEMASK(v) ==0x001f
1152       && CHECK_BYTE_ORDER(v)
1153       && v->BitsPerPixel==16
1154       && sizeof(GLushort)==2
1155       && v->RedGamma==1.0 && v->GreenGamma==1.0 && v->BlueGamma==1.0) {
1156      /* 5-6-5 color weight on common PC VGA boards */
1157      v->undithered_pf = PF_5R6G5B;
1158      v->dithered_pf = PF_DITHER_5R6G5B;
1159   }
1160   else if (GET_REDMASK(v)  ==0xe0
1161       &&   GET_GREENMASK(v)==0x1c
1162       &&   GET_BLUEMASK(v) ==0x03
1163       && CHECK_FOR_HPCR(v)) {
1164      setup_8bit_hpcr( v );
1165   }
1166}
1167
1168
1169
1170/*
1171 * Setup RGB rendering for a window with a monochrome visual.
1172 */
1173static void setup_monochrome( XMesaVisual v, XMesaBuffer b )
1174{
1175   (void) b;
1176   v->dithered_pf = v->undithered_pf = PF_1BIT;
1177   /* if black=1 then we must flip pixel values */
1178   v->bitFlip = (GET_BLACK_PIXEL(v) != 0);
1179}
1180
1181
1182
1183/*
1184 * When a context is "made current" for the first time, we can finally
1185 * finish initializing the context's visual and buffer information.
1186 * Input:  v - the XMesaVisual to initialize
1187 *         b - the XMesaBuffer to initialize (may be NULL)
1188 *         rgb_flag - TRUE = RGBA mode, FALSE = color index mode
1189 *         window - the window/pixmap we're rendering into
1190 *         cmap - the colormap associated with the window/pixmap
1191 * Return:  GL_TRUE=success, GL_FALSE=failure
1192 */
1193static GLboolean initialize_visual_and_buffer( int client,
1194                                               XMesaVisual v,
1195                                               XMesaBuffer b,
1196                                               GLboolean rgb_flag,
1197                                               XMesaDrawable window,
1198                                               XMesaColormap cmap
1199                                             )
1200{
1201#ifndef XFree86Server
1202   XGCValues gcvalues;
1203#endif
1204
1205   if (b) {
1206      assert(b->xm_visual == v);
1207   }
1208
1209   /* Save true bits/pixel */
1210   v->BitsPerPixel = bits_per_pixel(v);
1211   assert(v->BitsPerPixel > 0);
1212
1213
1214   if (rgb_flag==GL_FALSE) {
1215      /* COLOR-INDEXED WINDOW:
1216       * Even if the visual is TrueColor or DirectColor we treat it as
1217       * being color indexed.  This is weird but might be useful to someone.
1218       */
1219      v->dithered_pf = v->undithered_pf = PF_INDEX;
1220      v->index_bits = GET_VISUAL_DEPTH(v);
1221   }
1222   else {
1223      /* RGB WINDOW:
1224       * We support RGB rendering into almost any kind of visual.
1225       */
1226      int xclass;
1227      xclass = GET_VISUAL_CLASS(v);
1228      if (xclass==TrueColor || xclass==DirectColor) {
1229	 setup_truecolor( v, b, cmap );
1230      }
1231      else if (xclass==StaticGray && GET_VISUAL_DEPTH(v)==1) {
1232	 setup_monochrome( v, b );
1233      }
1234      else if (xclass==GrayScale || xclass==StaticGray) {
1235         if (!setup_grayscale( client, v, b, cmap )) {
1236            return GL_FALSE;
1237         }
1238      }
1239      else if ((xclass==PseudoColor || xclass==StaticColor)
1240               && GET_VISUAL_DEPTH(v)>=4 && GET_VISUAL_DEPTH(v)<=16) {
1241	 if (!setup_dithered_color( client, v, b, cmap )) {
1242            return GL_FALSE;
1243         }
1244      }
1245      else {
1246	 error("XMesa: RGB mode rendering not supported in given visual.");
1247	 return GL_FALSE;
1248      }
1249      v->index_bits = 0;
1250
1251      if (getenv("MESA_NO_DITHER")) {
1252	 v->dithered_pf = v->undithered_pf;
1253      }
1254   }
1255
1256
1257   /*
1258    * If MESA_INFO env var is set print out some debugging info
1259    * which can help Brian figure out what's going on when a user
1260    * reports bugs.
1261    */
1262   if (getenv("MESA_INFO")) {
1263      fprintf(stderr, "X/Mesa visual = %p\n", (void *) v);
1264      fprintf(stderr, "X/Mesa dithered pf = %u\n", v->dithered_pf);
1265      fprintf(stderr, "X/Mesa undithered pf = %u\n", v->undithered_pf);
1266      fprintf(stderr, "X/Mesa level = %d\n", v->level);
1267      fprintf(stderr, "X/Mesa depth = %d\n", GET_VISUAL_DEPTH(v));
1268      fprintf(stderr, "X/Mesa bits per pixel = %d\n", v->BitsPerPixel);
1269   }
1270
1271   if (b && window) {
1272      /* Do window-specific initializations */
1273
1274      /* Window dimensions */
1275      unsigned int w, h;
1276      get_drawable_size( v->display, window, &w, &h );
1277      b->width = w;
1278      b->height = h;
1279
1280      b->frontbuffer = window;
1281
1282      /* Setup for single/double buffering */
1283      if (v->mesa_visual.doubleBufferMode) {
1284         /* Double buffered */
1285#ifndef XFree86Server
1286         b->shm = check_for_xshm( v->display );
1287#endif
1288         xmesa_alloc_back_buffer( b );
1289         if (b->db_state==BACK_PIXMAP) {
1290            b->buffer = (XMesaDrawable)b->backpixmap;
1291         }
1292         else {
1293            b->buffer = XIMAGE;
1294         }
1295      }
1296      else {
1297         /* Single Buffered */
1298         b->buffer = b->frontbuffer;
1299      }
1300
1301      /* X11 graphics contexts */
1302#ifdef XFree86Server
1303      b->gc = CreateScratchGC(v->display, window->depth);
1304#else
1305      b->gc = XCreateGC( v->display, window, 0, NULL );
1306#endif
1307      XMesaSetFunction( v->display, b->gc, GXcopy );
1308
1309      /* cleargc - for glClear() */
1310#ifdef XFree86Server
1311      b->cleargc = CreateScratchGC(v->display, window->depth);
1312#else
1313      b->cleargc = XCreateGC( v->display, window, 0, NULL );
1314#endif
1315      XMesaSetFunction( v->display, b->cleargc, GXcopy );
1316
1317      /*
1318       * Don't generate Graphics Expose/NoExpose events in swapbuffers().
1319       * Patch contributed by Michael Pichler May 15, 1995.
1320       */
1321#ifdef XFree86Server
1322      b->swapgc = CreateScratchGC(v->display, window->depth);
1323      {
1324	  CARD32 v[1];
1325	  v[0] = FALSE;
1326	  dixChangeGC(NullClient, b->swapgc, GCGraphicsExposures, v, NULL);
1327      }
1328#else
1329      gcvalues.graphics_exposures = False;
1330      b->swapgc = XCreateGC( v->display, window,
1331                              GCGraphicsExposures, &gcvalues);
1332#endif
1333      XMesaSetFunction( v->display, b->swapgc, GXcopy );
1334      /*
1335       * Set fill style and tile pixmap once for all for HPCR stuff
1336       * (instead of doing it each time in clear_color_HPCR_pixmap())
1337       * Initialize whole stuff
1338       * Patch contributed by Jacques Leroy March 8, 1998.
1339       */
1340      if (v->hpcr_clear_flag && b->buffer!=XIMAGE) {
1341	int i;
1342	for (i=0; i<16; i++)
1343        {
1344	   XMesaPutPixel(v->hpcr_clear_ximage, i, 0, 0);
1345	   XMesaPutPixel(v->hpcr_clear_ximage, i, 1, 0);
1346        }
1347        XMesaPutImage(b->display, (XMesaDrawable)v->hpcr_clear_pixmap,
1348		      b->cleargc, v->hpcr_clear_ximage, 0, 0, 0, 0, 16, 2);
1349	XMesaSetFillStyle( v->display, b->cleargc, FillTiled);
1350	XMesaSetTile( v->display, b->cleargc, v->hpcr_clear_pixmap );
1351      }
1352
1353      /* Initialize the row buffer XImage for use in write_color_span() */
1354#ifdef XFree86Server
1355      b->rowimage = XMesaCreateImage(GET_VISUAL_DEPTH(v), MAX_WIDTH, 1,
1356				     (char *)MALLOC(MAX_WIDTH*4));
1357#else
1358      b->rowimage = XCreateImage( v->display,
1359                                  v->visinfo->visual,
1360                                  v->visinfo->depth,
1361                                  ZPixmap, 0,           /*format, offset*/
1362                                  (char*) MALLOC(MAX_WIDTH*4),  /*data*/
1363                                  MAX_WIDTH, 1,         /*width, height*/
1364                                  32,                   /*bitmap_pad*/
1365                                  0                     /*bytes_per_line*/ );
1366#endif
1367   }
1368
1369   return GL_TRUE;
1370}
1371
1372
1373
1374/*
1375 * Convert an RGBA color to a pixel value.
1376 */
1377unsigned long
1378xmesa_color_to_pixel( XMesaContext xmesa, GLubyte r, GLubyte g, GLubyte b, GLubyte a,
1379                      GLuint pixelFormat)
1380{
1381   switch (pixelFormat) {
1382      case PF_INDEX:
1383         return 0;
1384      case PF_TRUECOLOR:
1385         {
1386            unsigned long p;
1387            PACK_TRUECOLOR( p, r, g, b );
1388            return p;
1389         }
1390      case PF_8A8B8G8R:
1391         return PACK_8A8B8G8R( r, g, b, a );
1392      case PF_8R8G8B:
1393         /* fall through */
1394      case PF_8R8G8B24:
1395         return PACK_8R8G8B( r, g, b );
1396      case PF_5R6G5B:
1397         return PACK_5R6G5B( r, g, b );
1398      case PF_DITHER:
1399         {
1400            DITHER_SETUP;
1401            return DITHER( 1, 0, r, g, b );
1402         }
1403      case PF_1BIT:
1404         /* 382 = (3*255)/2 */
1405         return ((r+g+b) > 382) ^ xmesa->xm_visual->bitFlip;
1406      case PF_HPCR:
1407         return DITHER_HPCR(1, 1, r, g, b);
1408      case PF_LOOKUP:
1409         {
1410            LOOKUP_SETUP;
1411            return LOOKUP( r, g, b );
1412         }
1413      case PF_GRAYSCALE:
1414         return GRAY_RGB( r, g, b );
1415      case PF_TRUEDITHER:
1416         /* fall through */
1417      case PF_DITHER_5R6G5B:
1418         {
1419            unsigned long p;
1420            PACK_TRUEDITHER(p, 1, 0, r, g, b);
1421            return p;
1422         }
1423      default:
1424         _mesa_problem(NULL, "Bad pixel format in xmesa_color_to_pixel");
1425   }
1426   return 0;
1427}
1428
1429
1430/**********************************************************************/
1431/*****                       Public Functions                     *****/
1432/**********************************************************************/
1433
1434
1435/*
1436 * Create a new X/Mesa visual.
1437 * Input:  display - X11 display
1438 *         visinfo - an XVisualInfo pointer
1439 *         rgb_flag - GL_TRUE = RGB mode,
1440 *                    GL_FALSE = color index mode
1441 *         alpha_flag - alpha buffer requested?
1442 *         db_flag - GL_TRUE = double-buffered,
1443 *                   GL_FALSE = single buffered
1444 *         stereo_flag - stereo visual?
1445 *         ximage_flag - GL_TRUE = use an XImage for back buffer,
1446 *                       GL_FALSE = use an off-screen pixmap for back buffer
1447 *         depth_size - requested bits/depth values, or zero
1448 *         stencil_size - requested bits/stencil values, or zero
1449 *         accum_red_size - requested bits/red accum values, or zero
1450 *         accum_green_size - requested bits/green accum values, or zero
1451 *         accum_blue_size - requested bits/blue accum values, or zero
1452 *         accum_alpha_size - requested bits/alpha accum values, or zero
1453 *         num_samples - number of samples/pixel if multisampling, or zero
1454 *         level - visual level, usually 0
1455 *         visualCaveat - ala the GLX extension, usually GLX_NONE_EXT
1456 * Return;  a new XMesaVisual or 0 if error.
1457 */
1458XMesaVisual XMesaCreateVisual( XMesaDisplay *display,
1459                               XMesaVisualInfo visinfo,
1460                               GLboolean rgb_flag,
1461                               GLboolean alpha_flag,
1462                               GLboolean db_flag,
1463                               GLboolean stereo_flag,
1464                               GLboolean ximage_flag,
1465                               GLint depth_size,
1466                               GLint stencil_size,
1467                               GLint accum_red_size,
1468                               GLint accum_green_size,
1469                               GLint accum_blue_size,
1470                               GLint accum_alpha_size,
1471                               GLint num_samples,
1472                               GLint level,
1473                               GLint visualCaveat )
1474{
1475   char *gamma;
1476   XMesaVisual v;
1477   GLint red_bits, green_bits, blue_bits, alpha_bits;
1478
1479   /* For debugging only */
1480   if (getenv("MESA_XSYNC")) {
1481      /* This makes debugging X easier.
1482       * In your debugger, set a breakpoint on _XError to stop when an
1483       * X protocol error is generated.
1484       */
1485#ifdef XFree86Server
1486      /* NOT_NEEDED */
1487#else
1488      XSynchronize( display, 1 );
1489#endif
1490   }
1491
1492   v = (XMesaVisual) CALLOC_STRUCT(xmesa_visual);
1493   if (!v) {
1494      return NULL;
1495   }
1496
1497   /*
1498    * In the X server, NULL is passed in for the display.  It will have
1499    * to be set before using this visual.  See XMesaSetVisualDisplay()
1500    * below.
1501    */
1502   v->display = display;
1503
1504   /* Save a copy of the XVisualInfo struct because the user may XFREE()
1505    * the struct but we may need some of the information contained in it
1506    * at a later time.
1507    */
1508#ifdef XFree86Server
1509   v->visinfo = visinfo;
1510#else
1511   v->visinfo = (XVisualInfo *) MALLOC(sizeof(*visinfo));
1512   if(!v->visinfo) {
1513      FREE(v);
1514      return NULL;
1515   }
1516   MEMCPY(v->visinfo, visinfo, sizeof(*visinfo));
1517
1518   /* Save a copy of the pointer now so we can find this visual again
1519    * if we need to search for it in find_glx_visual().
1520    */
1521   v->vishandle = visinfo;
1522#endif
1523
1524#ifdef XFree86Server
1525   /* Initialize the depth of the screen */
1526   {
1527       PixmapFormatRec *format;
1528
1529       for (format = screenInfo.formats;
1530	    format->depth != display->rootDepth;
1531	    format++)
1532	   ;
1533       v->screen_depth = format->bitsPerPixel;
1534   }
1535#endif
1536
1537   /* check for MESA_GAMMA environment variable */
1538   gamma = getenv("MESA_GAMMA");
1539   if (gamma) {
1540      v->RedGamma = v->GreenGamma = v->BlueGamma = 0.0;
1541      sscanf( gamma, "%f %f %f", &v->RedGamma, &v->GreenGamma, &v->BlueGamma );
1542      if (v->RedGamma<=0.0)    v->RedGamma = 1.0;
1543      if (v->GreenGamma<=0.0)  v->GreenGamma = v->RedGamma;
1544      if (v->BlueGamma<=0.0)   v->BlueGamma = v->RedGamma;
1545   }
1546   else {
1547      v->RedGamma = v->GreenGamma = v->BlueGamma = 1.0;
1548   }
1549
1550   v->ximage_flag = ximage_flag;
1551   v->level = level;
1552   v->VisualCaveat = visualCaveat;
1553
1554   (void) initialize_visual_and_buffer( 0, v, NULL, rgb_flag, 0, 0 );
1555
1556   {
1557      int xclass;
1558      xclass = GET_VISUAL_CLASS(v);
1559      if (xclass==TrueColor || xclass==DirectColor) {
1560         red_bits   = bitcount(GET_REDMASK(v));
1561         green_bits = bitcount(GET_GREENMASK(v));
1562         blue_bits  = bitcount(GET_BLUEMASK(v));
1563         alpha_bits = 0;
1564      }
1565      else {
1566         /* this is an approximation */
1567         int depth;
1568         depth = GET_VISUAL_DEPTH(v);
1569         red_bits = depth / 3;
1570         depth -= red_bits;
1571         green_bits = depth / 2;
1572         depth -= green_bits;
1573         blue_bits = depth;
1574         alpha_bits = 0;
1575         assert( red_bits + green_bits + blue_bits == GET_VISUAL_DEPTH(v) );
1576      }
1577   }
1578
1579   if (alpha_flag && alpha_bits == 0)
1580      alpha_bits = 8;
1581
1582   _mesa_initialize_visual( &v->mesa_visual,
1583                            rgb_flag, db_flag, stereo_flag,
1584                            red_bits, green_bits,
1585                            blue_bits, alpha_bits,
1586                            v->index_bits,
1587                            depth_size,
1588                            stencil_size,
1589                            accum_red_size, accum_green_size,
1590                            accum_blue_size, accum_alpha_size,
1591                            0 );
1592   return v;
1593}
1594
1595
1596void XMesaSetVisualDisplay( XMesaDisplay *dpy, XMesaVisual v )
1597{
1598    v->display = dpy;
1599}
1600
1601
1602void XMesaDestroyVisual( XMesaVisual v )
1603{
1604#ifndef XFree86Server
1605   FREE(v->visinfo);
1606#endif
1607   FREE(v);
1608}
1609
1610
1611
1612/*
1613 * Create a new XMesaContext.
1614 * Input:  v - XMesaVisual
1615 *         share_list - another XMesaContext with which to share display
1616 *                      lists or NULL if no sharing is wanted.
1617 * Return:  an XMesaContext or NULL if error.
1618 */
1619XMesaContext XMesaCreateContext( XMesaVisual v, XMesaContext share_list )
1620{
1621   XMesaContext c;
1622   GLcontext *ctx;
1623   GLboolean direct = GL_TRUE; /* XXXX */
1624   /* NOT_DONE: should this be GL_FALSE??? */
1625   static GLboolean firstTime = GL_TRUE;
1626
1627   if (firstTime) {
1628      _glthread_INIT_MUTEX(_xmesa_lock);
1629      firstTime = GL_FALSE;
1630   }
1631
1632   c = (XMesaContext) CALLOC_STRUCT(xmesa_context);
1633   if (!c) {
1634      return NULL;
1635   }
1636
1637   ctx = c->gl_ctx = _mesa_create_context( &v->mesa_visual,
1638                      share_list ? share_list->gl_ctx : (GLcontext *) NULL,
1639                      (void *) c, direct );
1640   if (!c->gl_ctx) {
1641      FREE(c);
1642      return NULL;
1643   }
1644
1645   _mesa_enable_sw_extensions(ctx);
1646   _mesa_enable_1_3_extensions(ctx);
1647
1648   if (CHECK_BYTE_ORDER(v)) {
1649      c->swapbytes = GL_FALSE;
1650   }
1651   else {
1652      c->swapbytes = GL_TRUE;
1653   }
1654
1655   c->xm_visual = v;
1656   c->xm_buffer = NULL;   /* set later by XMesaMakeCurrent */
1657   c->display = v->display;
1658   c->pixelformat = v->dithered_pf;      /* Dithering is enabled by default */
1659
1660   ctx->Driver.UpdateState = xmesa_update_state;
1661
1662   /* Initialize the software rasterizer and helper modules.
1663    */
1664   _swrast_CreateContext( ctx );
1665   _ac_CreateContext( ctx );
1666   _tnl_CreateContext( ctx );
1667   _swsetup_CreateContext( ctx );
1668
1669   xmesa_register_swrast_functions( ctx );
1670
1671   /* Set up some constant pointers:
1672    */
1673   xmesa_init_pointers( ctx );
1674
1675
1676   /* Run the config file
1677    */
1678   _mesa_read_config_file( ctx );
1679
1680
1681   return c;
1682}
1683
1684
1685
1686
1687void XMesaDestroyContext( XMesaContext c )
1688{
1689#ifdef FX
1690   if (c->xm_buffer && c->xm_buffer->FXctx)
1691      fxMesaDestroyContext(c->xm_buffer->FXctx);
1692#endif
1693   if (c->gl_ctx) {
1694      _swsetup_DestroyContext( c->gl_ctx );
1695      _swrast_DestroyContext( c->gl_ctx );
1696      _tnl_DestroyContext( c->gl_ctx );
1697      _ac_DestroyContext( c->gl_ctx );
1698      _mesa_destroy_context( c->gl_ctx );
1699   }
1700
1701   FREE( c );
1702}
1703
1704
1705
1706/*
1707 * XXX this isn't a public function!  It's a hack for the 3Dfx driver.
1708 * Create a new XMesaBuffer from an X window.
1709 * Input:  v - the XMesaVisual
1710 *         w - the window
1711 *         c - the context
1712 * Return:  new XMesaBuffer or NULL if error
1713 */
1714XMesaBuffer XMesaCreateWindowBuffer2( XMesaVisual v, XMesaWindow w,
1715                                      XMesaContext c )
1716{
1717#ifndef XFree86Server
1718   XWindowAttributes attr;
1719#endif
1720#ifdef FX
1721   char *fxEnvVar;
1722#endif
1723   int client = 0;
1724
1725   XMesaBuffer b = alloc_xmesa_buffer();
1726   if (!b) {
1727      return NULL;
1728   }
1729
1730   (void) c;
1731
1732#ifdef XFree86Server
1733   client = CLIENT_ID(((XMesaDrawable)w)->id);
1734#endif
1735
1736   assert(v);
1737
1738#ifdef XFree86Server
1739   if (GET_VISUAL_DEPTH(v) != ((XMesaDrawable)w)->depth) {
1740#else
1741   XGetWindowAttributes( v->display, w, &attr );
1742
1743   if (GET_VISUAL_DEPTH(v) != attr.depth) {
1744#endif
1745      if (getenv("MESA_DEBUG")) {
1746         fprintf(stderr, "XMesaCreateWindowBuffer: depth mismatch between visual and window!\n");
1747      }
1748      return NULL;
1749   }
1750
1751   b->xm_visual = v;
1752   b->type = WINDOW;
1753   b->display = v->display;
1754#ifdef XFree86Server
1755   b->cmap = (ColormapPtr)LookupIDByType(wColormap(w), RT_COLORMAP);
1756#else
1757   if (attr.colormap) {
1758      b->cmap = attr.colormap;
1759   }
1760   else {
1761      if (getenv("MESA_DEBUG")) {
1762         fprintf(stderr, "Window %u has no colormap!\n", (unsigned int) w);
1763      }
1764      /* this is weird, a window w/out a colormap!? */
1765      /* OK, let's just allocate a new one and hope for the best */
1766      b->cmap = XCreateColormap(v->display, w, attr.visual, AllocNone);
1767   }
1768#endif
1769
1770   /* determine back buffer implementation */
1771   if (v->mesa_visual.doubleBufferMode) {
1772      if (v->ximage_flag) {
1773	 b->db_state = BACK_XIMAGE;
1774      }
1775      else {
1776	 b->db_state = BACK_PIXMAP;
1777      }
1778   }
1779   else {
1780      b->db_state = 0;
1781   }
1782
1783   _mesa_initialize_framebuffer(&b->mesa_buffer,
1784                                &v->mesa_visual,
1785                                v->mesa_visual.depthBits > 0,
1786                                v->mesa_visual.stencilBits > 0,
1787                                v->mesa_visual.accumRedBits > 0,
1788                                v->mesa_visual.alphaBits > 0 );
1789
1790   if (!initialize_visual_and_buffer( client, v, b, v->mesa_visual.rgbMode,
1791                                      (XMesaDrawable)w, b->cmap )) {
1792      free_xmesa_buffer(client, b);
1793      return NULL;
1794   }
1795
1796#ifdef FX
1797   fxEnvVar = getenv("MESA_GLX_FX");
1798   if (fxEnvVar) {
1799     if (fxEnvVar[0]!='d') {
1800       int attribs[100];
1801       int numAttribs = 0;
1802       int hw;
1803       if (v->mesa_visual.depthBits > 0) {
1804	 attribs[numAttribs++] = FXMESA_DEPTH_SIZE;
1805	 attribs[numAttribs++] = 1;
1806       }
1807       if (v->mesa_visual.doubleBufferMode) {
1808	 attribs[numAttribs++] = FXMESA_DOUBLEBUFFER;
1809       }
1810       if (v->mesa_visual.accumRedBits > 0) {
1811	 attribs[numAttribs++] = FXMESA_ACCUM_SIZE;
1812	 attribs[numAttribs++] = v->mesa_visual.accumRedBits;
1813       }
1814       if (v->mesa_visual.stencilBits > 0) {
1815         attribs[numAttribs++] = FXMESA_STENCIL_SIZE;
1816         attribs[numAttribs++] = v->mesa_visual.stencilBits;
1817       }
1818       if (v->mesa_visual.alphaBits > 0) {
1819         attribs[numAttribs++] = FXMESA_ALPHA_SIZE;
1820         attribs[numAttribs++] = 1;
1821       }
1822       if (c->gl_ctx) {
1823#define FXMESA_SHARE_CONTEXT 990099  /* keep in sync with fxapi.c! */
1824         attribs[numAttribs++] = FXMESA_SHARE_CONTEXT;
1825         attribs[numAttribs++] = (int) c->gl_ctx;
1826       }
1827       attribs[numAttribs++] = FXMESA_NONE;
1828
1829       if ((hw = fxQueryHardware())==GR_SSTTYPE_VOODOO) {
1830         b->FXctx = fxMesaCreateBestContext(0, b->width, b->height, attribs);
1831         if ((v->undithered_pf!=PF_INDEX) && (b->backimage)) {
1832	   b->FXisHackUsable = b->FXctx ? GL_TRUE : GL_FALSE;
1833	   if (fxEnvVar[0]=='w' || fxEnvVar[0]=='W')
1834	     b->FXwindowHack = b->FXctx ? GL_TRUE : GL_FALSE;
1835	   else
1836	     b->FXwindowHack = GL_FALSE;
1837         }
1838       }
1839       else {
1840         if (fxEnvVar[0]=='w' || fxEnvVar[0]=='W')
1841	   b->FXctx = fxMesaCreateContext(w, GR_RESOLUTION_NONE,
1842					  GR_REFRESH_75Hz, attribs);
1843         else
1844	   b->FXctx = fxMesaCreateBestContext(0, b->width, b->height, attribs);
1845         b->FXisHackUsable = GL_FALSE;
1846         b->FXwindowHack = GL_FALSE;
1847       }
1848       /*
1849       fprintf(stderr,
1850               "voodoo %d, wid %d height %d hack: usable %d active %d\n",
1851               hw, b->width, b->height, b->FXisHackUsable, b->FXwindowHack);
1852       */
1853     }
1854   }
1855   else {
1856      fprintf(stderr,"WARNING: This Mesa Library includes the Glide driver but\n");
1857      fprintf(stderr,"         you have not defined the MESA_GLX_FX env. var.\n");
1858      fprintf(stderr,"         (check the README.3DFX file for more information).\n\n");
1859      fprintf(stderr,"         you can disable this message with a 'export MESA_GLX_FX=disable'.\n");
1860   }
1861#endif
1862
1863   return b;
1864}
1865
1866
1867XMesaBuffer XMesaCreateWindowBuffer( XMesaVisual v, XMesaWindow w )
1868{
1869   return XMesaCreateWindowBuffer2( v, w, NULL );
1870}
1871
1872
1873/*
1874 * Create a new XMesaBuffer from an X pixmap.
1875 * Input:  v - the XMesaVisual
1876 *         p - the pixmap
1877 *         cmap - the colormap, may be 0 if using a TrueColor or DirectColor
1878 *                visual for the pixmap
1879 * Return:  new XMesaBuffer or NULL if error
1880 */
1881XMesaBuffer XMesaCreatePixmapBuffer( XMesaVisual v,
1882				     XMesaPixmap p, XMesaColormap cmap )
1883{
1884   int client = 0;
1885   XMesaBuffer b = alloc_xmesa_buffer();
1886   if (!b) {
1887      return NULL;
1888   }
1889
1890
1891#ifdef XFree86Server
1892   client = CLIENT_ID(((XMesaDrawable)p)->id);
1893#endif
1894
1895   assert(v);
1896
1897   b->xm_visual = v;
1898   b->type = PIXMAP;
1899   b->display = v->display;
1900   b->cmap = cmap;
1901
1902   /* determine back buffer implementation */
1903   if (v->mesa_visual.doubleBufferMode) {
1904      if (v->ximage_flag) {
1905	 b->db_state = BACK_XIMAGE;
1906      }
1907      else {
1908	 b->db_state = BACK_PIXMAP;
1909      }
1910   }
1911   else {
1912      b->db_state = 0;
1913   }
1914
1915   _mesa_initialize_framebuffer(&b->mesa_buffer,
1916                                &v->mesa_visual,
1917                                v->mesa_visual.depthBits > 0,
1918                                v->mesa_visual.stencilBits > 0,
1919                                v->mesa_visual.accumRedBits +
1920                                v->mesa_visual.accumGreenBits +
1921                                v->mesa_visual.accumBlueBits > 0,
1922                                v->mesa_visual.alphaBits > 0 );
1923
1924   if (!initialize_visual_and_buffer(client, v, b, v->mesa_visual.rgbMode,
1925				     (XMesaDrawable)p, cmap)) {
1926      free_xmesa_buffer(client, b);
1927      return NULL;
1928   }
1929
1930   return b;
1931}
1932
1933
1934
1935#if 0 /* not done */
1936XMesaBuffer XMesaCreatePBuffer( XMesaVisual v, XMesaColormap cmap,
1937                                unsigned int width, unsigned int height )
1938{
1939   int client = 0;
1940   XMesaBuffer b = alloc_xmesa_buffer();
1941   if (!b) {
1942      return NULL;
1943   }
1944
1945   b->xm_visual = v;
1946   b->pbuffer_flag = GL_TRUE;
1947   b->display = v->display;
1948   b->cmap = cmap;
1949
1950   /* determine back buffer implementation */
1951   if (v->mesa_visual.doubleBufferMode) {
1952      if (v->ximage_flag) {
1953	 b->db_state = BACK_XIMAGE;
1954      }
1955      else {
1956	 b->db_state = BACK_PIXMAP;
1957      }
1958   }
1959   else {
1960      b->db_state = 0;
1961   }
1962
1963   _mesa_initialize_framebuffer(&b->mesa_buffer,
1964                                &v->mesa_visual,
1965                                v->mesa_visual.depthBits > 0,
1966                                v->mesa_visual.stencilBits > 0,
1967                                v->mesa_visual.accumRedBits +
1968                                v->mesa_visual.accumGreenBits +
1969                                v->mesa_visual.accumBlueBits > 0,
1970                                v->mesa_visual.alphaBits > 0 );
1971
1972   if (!initialize_visual_and_buffer(client, v, b, v->mesa_visual.rgbMode,
1973				     0, cmap)) {
1974      free_xmesa_buffer(client, b);
1975      return NULL;
1976   }
1977
1978   return b;
1979}
1980#endif
1981
1982
1983
1984/*
1985 * Deallocate an XMesaBuffer structure and all related info.
1986 */
1987void XMesaDestroyBuffer( XMesaBuffer b )
1988{
1989   int client = 0;
1990
1991#ifdef XFree86Server
1992   if (b->frontbuffer)
1993       client = CLIENT_ID(b->frontbuffer->id);
1994#endif
1995
1996   if (b->gc)  XMesaFreeGC( b->xm_visual->display, b->gc );
1997   if (b->cleargc)  XMesaFreeGC( b->xm_visual->display, b->cleargc );
1998   if (b->swapgc)  XMesaFreeGC( b->xm_visual->display, b->swapgc );
1999
2000   if (b->backimage) {
2001#if defined(USE_XSHM) && !defined(XFree86Server)
2002       if (b->shm) {
2003	   XShmDetach( b->xm_visual->display, &b->shminfo );
2004	   XDestroyImage( b->backimage );
2005	   shmdt( b->shminfo.shmaddr );
2006       }
2007       else
2008#endif
2009	   XMesaDestroyImage( b->backimage );
2010   }
2011   if (b->backpixmap) {
2012      XMesaFreePixmap( b->xm_visual->display, b->backpixmap );
2013      if (b->xm_visual->hpcr_clear_flag) {
2014	XMesaFreePixmap( b->xm_visual->display,
2015			 b->xm_visual->hpcr_clear_pixmap );
2016	XMesaDestroyImage( b->xm_visual->hpcr_clear_ximage );
2017      }
2018   }
2019   if (b->rowimage) {
2020      FREE( b->rowimage->data );
2021      b->rowimage->data = NULL;
2022      XMesaDestroyImage( b->rowimage );
2023   }
2024
2025   free_xmesa_buffer(client, b);
2026}
2027
2028
2029
2030/*
2031 * Bind buffer b to context c and make c the current rendering context.
2032 */
2033GLboolean XMesaMakeCurrent( XMesaContext c, XMesaBuffer b )
2034{
2035   return XMesaMakeCurrent2( c, b, b );
2036}
2037
2038
2039/*
2040 * Bind buffer b to context c and make c the current rendering context.
2041 */
2042GLboolean XMesaMakeCurrent2( XMesaContext c, XMesaBuffer drawBuffer,
2043                             XMesaBuffer readBuffer )
2044{
2045   if (c) {
2046      if (!drawBuffer || !readBuffer)
2047         return GL_FALSE;  /* must specify buffers! */
2048
2049#ifdef FX
2050      if (drawBuffer->FXctx) {
2051         fxMesaMakeCurrent(drawBuffer->FXctx);
2052
2053         c->xm_buffer = drawBuffer;
2054         c->xm_read_buffer = readBuffer;
2055         c->use_read_buffer = (drawBuffer != readBuffer);
2056
2057         return GL_TRUE;
2058      }
2059#endif
2060      if (c->gl_ctx == _mesa_get_current_context()
2061          && c->xm_buffer == drawBuffer
2062          && c->xm_read_buffer == readBuffer
2063          && c->xm_buffer->wasCurrent) {
2064         /* same context and buffer, do nothing */
2065         return GL_TRUE;
2066      }
2067
2068      c->xm_buffer = drawBuffer;
2069      c->xm_read_buffer = readBuffer;
2070      c->use_read_buffer = (drawBuffer != readBuffer);
2071
2072      _mesa_make_current2(c->gl_ctx,
2073                          &drawBuffer->mesa_buffer,
2074                          &readBuffer->mesa_buffer);
2075
2076      if (c->gl_ctx->Viewport.Width == 0) {
2077	 /* initialize viewport to window size */
2078	 _mesa_Viewport( 0, 0, drawBuffer->width, drawBuffer->height );
2079	 c->gl_ctx->Scissor.Width = drawBuffer->width;
2080	 c->gl_ctx->Scissor.Height = drawBuffer->height;
2081      }
2082
2083      if (c->xm_visual->mesa_visual.rgbMode) {
2084         /*
2085          * Must recompute and set these pixel values because colormap
2086          * can be different for different windows.
2087          */
2088         c->clearpixel = xmesa_color_to_pixel( c,
2089                                               c->clearcolor[0],
2090                                               c->clearcolor[1],
2091                                               c->clearcolor[2],
2092                                               c->clearcolor[3],
2093                                               c->xm_visual->undithered_pf);
2094         XMesaSetForeground(c->display, c->xm_buffer->cleargc, c->clearpixel);
2095      }
2096
2097      /* Solution to Stephane Rehel's problem with glXReleaseBuffersMESA(): */
2098      c->xm_buffer->wasCurrent = GL_TRUE;
2099   }
2100   else {
2101      /* Detach */
2102      _mesa_make_current2( NULL, NULL, NULL );
2103   }
2104   return GL_TRUE;
2105}
2106
2107
2108/*
2109 * Unbind the context c from its buffer.
2110 */
2111GLboolean XMesaUnbindContext( XMesaContext c )
2112{
2113   /* A no-op for XFree86 integration purposes */
2114   return GL_TRUE;
2115}
2116
2117
2118XMesaContext XMesaGetCurrentContext( void )
2119{
2120   GET_CURRENT_CONTEXT(ctx);
2121   if (ctx) {
2122      XMesaContext xmesa = (XMesaContext) ctx->DriverCtx;
2123      return xmesa;
2124   }
2125   else {
2126      return 0;
2127   }
2128}
2129
2130
2131XMesaBuffer XMesaGetCurrentBuffer( void )
2132{
2133   GET_CURRENT_CONTEXT(ctx);
2134   if (ctx) {
2135      XMesaContext xmesa = (XMesaContext) ctx->DriverCtx;
2136      return xmesa->xm_buffer;
2137   }
2138   else {
2139      return 0;
2140   }
2141}
2142
2143
2144/* New in Mesa 3.1 */
2145XMesaBuffer XMesaGetCurrentReadBuffer( void )
2146{
2147   GET_CURRENT_CONTEXT(ctx);
2148   if (ctx) {
2149      XMesaContext xmesa = (XMesaContext) ctx->DriverCtx;
2150      return xmesa->xm_buffer;
2151   }
2152   else {
2153      return 0;
2154   }
2155}
2156
2157
2158GLboolean XMesaForceCurrent(XMesaContext c)
2159{
2160   if (c) {
2161      if (c->gl_ctx != _mesa_get_current_context()) {
2162	 _mesa_make_current(c->gl_ctx, &c->xm_buffer->mesa_buffer);
2163      }
2164   }
2165   else {
2166      _mesa_make_current(NULL, NULL);
2167   }
2168   return GL_TRUE;
2169}
2170
2171
2172GLboolean XMesaLoseCurrent(XMesaContext c)
2173{
2174   (void) c;
2175   _mesa_make_current(NULL, NULL);
2176   return GL_TRUE;
2177}
2178
2179
2180/*
2181 * Switch 3Dfx support hack between window and full-screen mode.
2182 */
2183GLboolean XMesaSetFXmode( GLint mode )
2184{
2185#ifdef FX
2186   const char *fx = getenv("MESA_GLX_FX");
2187   if (fx && fx[0] != 'd') {
2188      GET_CURRENT_CONTEXT(ctx);
2189      GrHwConfiguration hw;
2190      if (!FX_grSstQueryHardware(&hw)) {
2191         /*fprintf(stderr, "!grSstQueryHardware\n");*/
2192         return GL_FALSE;
2193      }
2194      if (hw.num_sst < 1) {
2195         /*fprintf(stderr, "hw.num_sst < 1\n");*/
2196         return GL_FALSE;
2197      }
2198      if (ctx) {
2199         XMesaContext xmesa = (XMesaContext) ctx->DriverCtx;
2200         if (mode == XMESA_FX_WINDOW) {
2201	    if (xmesa->xm_buffer->FXisHackUsable) {
2202	       FX_grSstControl(GR_CONTROL_DEACTIVATE);
2203	       xmesa->xm_buffer->FXwindowHack = GL_TRUE;
2204	       return GL_TRUE;
2205	    }
2206	 }
2207	 else if (mode == XMESA_FX_FULLSCREEN) {
2208	    FX_grSstControl(GR_CONTROL_ACTIVATE);
2209	    xmesa->xm_buffer->FXwindowHack = GL_FALSE;
2210	    return GL_TRUE;
2211	 }
2212	 else {
2213	    /* Error: Bad mode value */
2214	 }
2215      }
2216   }
2217   /*fprintf(stderr, "fallthrough\n");*/
2218#else
2219   (void) mode;
2220#endif
2221   return GL_FALSE;
2222}
2223
2224
2225
2226#ifdef FX
2227/*
2228 * Read image from VooDoo frame buffer into X/Mesa's back XImage.
2229 */
2230static void FXgetImage( XMesaBuffer b )
2231{
2232   GET_CURRENT_CONTEXT(ctx);
2233   static unsigned short pixbuf[MAX_WIDTH];
2234   GLuint x, y;
2235   int xpos, ypos;
2236   XMesaWindow root;
2237   unsigned int bw, depth, width, height;
2238   XMesaContext xmesa = (XMesaContext) ctx->DriverCtx;
2239
2240   assert(xmesa->xm_buffer->FXctx);
2241
2242#ifdef XFree86Server
2243   x = b->frontbuffer->x;
2244   y = b->frontbuffer->y;
2245   width = b->frontbuffer->width;
2246   height = b->frontbuffer->height;
2247   depth = b->frontbuffer->depth;
2248#else
2249   XGetGeometry( xmesa->xm_visual->display, b->frontbuffer,
2250                 &root, &xpos, &ypos, &width, &height, &bw, &depth);
2251#endif
2252   if (b->width != width || b->height != height) {
2253      b->width = MIN2((int)width, xmesa->xm_buffer->FXctx->width);
2254      b->height = MIN2((int)height, xmesa->xm_buffer->FXctx->height);
2255      if (b->width & 1)
2256         b->width--;  /* prevent odd width */
2257      xmesa_alloc_back_buffer( b );
2258   }
2259
2260   grLfbWriteColorFormat(GR_COLORFORMAT_ARGB);
2261   if (xmesa->xm_visual->undithered_pf==PF_5R6G5B) {
2262      /* Special case: 16bpp RGB */
2263      grLfbReadRegion( GR_BUFFER_FRONTBUFFER,       /* src buffer */
2264                       0, xmesa->xm_buffer->FXctx->height - b->height,  /*pos*/
2265                       b->width, b->height,         /* size */
2266                       b->width * sizeof(GLushort), /* stride */
2267                       b->backimage->data);         /* dest buffer */
2268   }
2269   else if (xmesa->xm_visual->dithered_pf==PF_DITHER
2270	    && GET_VISUAL_DEPTH(xmesa->xm_visual)==8) {
2271      /* Special case: 8bpp RGB */
2272      for (y=0;y<b->height;y++) {
2273         GLubyte *ptr = (GLubyte*) xmesa->xm_buffer->backimage->data
2274                        + xmesa->xm_buffer->backimage->bytes_per_line * y;
2275         XDITHER_SETUP(y);
2276
2277         /* read row from 3Dfx frame buffer */
2278         grLfbReadRegion( GR_BUFFER_FRONTBUFFER,
2279                          0, xmesa->xm_buffer->FXctx->height-(b->height-y),
2280                          b->width, 1,
2281                          0,
2282                          pixbuf );
2283
2284         /* write to XImage back buffer */
2285         for (x=0;x<b->width;x++) {
2286            GLubyte r = (pixbuf[x] & 0xf800) >> 8;
2287            GLubyte g = (pixbuf[x] & 0x07e0) >> 3;
2288            GLubyte b = (pixbuf[x] & 0x001f) << 3;
2289            *ptr++ = XDITHER( x, r, g, b);
2290         }
2291      }
2292   }
2293   else {
2294      /* General case: slow! */
2295      for (y=0;y<b->height;y++) {
2296         /* read row from 3Dfx frame buffer */
2297         grLfbReadRegion( GR_BUFFER_FRONTBUFFER,
2298                          0, xmesa->xm_buffer->FXctx->height-(b->height-y),
2299                          b->width, 1,
2300                          0,
2301                          pixbuf );
2302
2303         /* write to XImage back buffer */
2304         for (x=0;x<b->width;x++) {
2305            XMesaPutPixel(b->backimage,x,y,
2306			  xmesa_color_to_pixel(xmesa,
2307					       (pixbuf[x] & 0xf800) >> 8,
2308					       (pixbuf[x] & 0x07e0) >> 3,
2309					       (pixbuf[x] & 0x001f) << 3,
2310					       0xff, xmesa->pixelformat));
2311         }
2312      }
2313   }
2314   grLfbWriteColorFormat(GR_COLORFORMAT_ABGR);
2315}
2316#endif
2317
2318
2319/*
2320 * Copy the back buffer to the front buffer.  If there's no back buffer
2321 * this is a no-op.
2322 */
2323void XMesaSwapBuffers( XMesaBuffer b )
2324{
2325   GET_CURRENT_CONTEXT(ctx);
2326
2327   /* If we're swapping the buffer associated with the current context
2328    * we have to flush any pending rendering commands first.
2329    */
2330   if (ctx && ctx->DrawBuffer == &(b->mesa_buffer))
2331      _mesa_swapbuffers(ctx);
2332
2333   if (b->db_state) {
2334#ifdef FX
2335      if (b->FXctx) {
2336         fxMesaSwapBuffers();
2337
2338         if (b->FXwindowHack)
2339            FXgetImage(b);
2340         else
2341            return;
2342      }
2343#endif
2344     if (b->backimage) {
2345	 /* Copy Ximage from host's memory to server's window */
2346#if defined(USE_XSHM) && !defined(XFree86Server)
2347	 if (b->shm) {
2348            /*_glthread_LOCK_MUTEX(_xmesa_lock);*/
2349	    XShmPutImage( b->xm_visual->display, b->frontbuffer,
2350			  b->swapgc,
2351			  b->backimage, 0, 0,
2352			  0, 0, b->width, b->height, False );
2353            /*_glthread_UNLOCK_MUTEX(_xmesa_lock);*/
2354	 }
2355	 else
2356#endif
2357         {
2358            /*_glthread_LOCK_MUTEX(_xmesa_lock);*/
2359            XMesaPutImage( b->xm_visual->display, b->frontbuffer,
2360			   b->swapgc,
2361			   b->backimage, 0, 0,
2362			   0, 0, b->width, b->height );
2363            /*_glthread_UNLOCK_MUTEX(_xmesa_lock);*/
2364         }
2365      }
2366      else {
2367	 /* Copy pixmap to window on server */
2368         /*_glthread_LOCK_MUTEX(_xmesa_lock);*/
2369	 XMesaCopyArea( b->xm_visual->display,
2370			b->backpixmap,   /* source drawable */
2371			b->frontbuffer,  /* dest. drawable */
2372			b->swapgc,
2373			0, 0, b->width, b->height,  /* source region */
2374			0, 0                 /* dest region */
2375		      );
2376         /*_glthread_UNLOCK_MUTEX(_xmesa_lock);*/
2377      }
2378   }
2379#if !defined(XFree86Server)
2380   XSync( b->xm_visual->display, False );
2381#endif
2382}
2383
2384
2385
2386/*
2387 * Copy sub-region of back buffer to front buffer
2388 */
2389void XMesaCopySubBuffer( XMesaBuffer b, int x, int y, int width, int height )
2390{
2391   GET_CURRENT_CONTEXT(ctx);
2392
2393   /* If we're swapping the buffer associated with the current context
2394    * we have to flush any pending rendering commands first.
2395    */
2396   if (ctx && ctx->DrawBuffer == &(b->mesa_buffer))
2397      _mesa_swapbuffers(ctx);
2398
2399   if (b->db_state) {
2400      int yTop = b->height - y - height;
2401#ifdef FX
2402      if (b->FXctx) {
2403         fxMesaSwapBuffers();
2404         if (b->FXwindowHack)
2405            FXgetImage(b);
2406         else
2407            return;
2408      }
2409#endif
2410      if (b->backimage) {
2411         /* Copy Ximage from host's memory to server's window */
2412#if defined(USE_XSHM) && !defined(XFree86Server)
2413         if (b->shm) {
2414            /* XXX assuming width and height aren't too large! */
2415            XShmPutImage( b->xm_visual->display, b->frontbuffer,
2416                          b->swapgc,
2417                          b->backimage, x, yTop,
2418                          x, yTop, width, height, False );
2419            /* wait for finished event??? */
2420         }
2421         else
2422#endif
2423         {
2424            /* XXX assuming width and height aren't too large! */
2425            XMesaPutImage( b->xm_visual->display, b->frontbuffer,
2426			   b->swapgc,
2427			   b->backimage, x, yTop,
2428			   x, yTop, width, height );
2429         }
2430      }
2431      else {
2432         /* Copy pixmap to window on server */
2433         XMesaCopyArea( b->xm_visual->display,
2434			b->backpixmap,           /* source drawable */
2435			b->frontbuffer,          /* dest. drawable */
2436			b->swapgc,
2437			x, yTop, width, height,  /* source region */
2438			x, yTop                  /* dest region */
2439                      );
2440      }
2441   }
2442}
2443
2444
2445/*
2446 * Return a pointer to the XMesa backbuffer Pixmap or XImage.  This function
2447 * is a way to get "under the hood" of X/Mesa so one can manipulate the
2448 * back buffer directly.
2449 * Output:  pixmap - pointer to back buffer's Pixmap, or 0
2450 *          ximage - pointer to back buffer's XImage, or NULL
2451 * Return:  GL_TRUE = context is double buffered
2452 *          GL_FALSE = context is single buffered
2453 */
2454GLboolean XMesaGetBackBuffer( XMesaBuffer b,
2455                              XMesaPixmap *pixmap,
2456                              XMesaImage **ximage )
2457{
2458   if (b->db_state) {
2459      if (pixmap)  *pixmap = b->backpixmap;
2460      if (ximage)  *ximage = b->backimage;
2461      return GL_TRUE;
2462   }
2463   else {
2464      *pixmap = 0;
2465      *ximage = NULL;
2466      return GL_FALSE;
2467   }
2468}
2469
2470
2471/*
2472 * Return the depth buffer associated with an XMesaBuffer.
2473 * Input:  b - the XMesa buffer handle
2474 * Output:  width, height - size of buffer in pixels
2475 *          bytesPerValue - bytes per depth value (2 or 4)
2476 *          buffer - pointer to depth buffer values
2477 * Return:  GL_TRUE or GL_FALSE to indicate success or failure.
2478 */
2479GLboolean XMesaGetDepthBuffer( XMesaBuffer b, GLint *width, GLint *height,
2480                               GLint *bytesPerValue, void **buffer )
2481{
2482   if (!b->mesa_buffer.DepthBuffer) {
2483      *width = 0;
2484      *height = 0;
2485      *bytesPerValue = 0;
2486      *buffer = 0;
2487      return GL_FALSE;
2488   }
2489   else {
2490      *width = b->mesa_buffer.Width;
2491      *height = b->mesa_buffer.Height;
2492      *bytesPerValue = sizeof(GLdepth);
2493      *buffer = b->mesa_buffer.DepthBuffer;
2494      return GL_TRUE;
2495   }
2496}
2497
2498
2499void XMesaFlush( XMesaContext c )
2500{
2501   if (c && c->xm_visual) {
2502#ifdef XFree86Server
2503      /* NOT_NEEDED */
2504#else
2505      XSync( c->xm_visual->display, False );
2506#endif
2507   }
2508}
2509
2510
2511
2512const char *XMesaGetString( XMesaContext c, int name )
2513{
2514   (void) c;
2515   if (name==XMESA_VERSION) {
2516      return "3.5";
2517   }
2518   else if (name==XMESA_EXTENSIONS) {
2519      return "";
2520   }
2521   else {
2522      return NULL;
2523   }
2524}
2525
2526
2527
2528XMesaBuffer XMesaFindBuffer( XMesaDisplay *dpy, XMesaDrawable d )
2529{
2530   XMesaBuffer b;
2531   for (b=XMesaBufferList; b; b=b->Next) {
2532      if (b->frontbuffer==d && b->display==dpy) {
2533         return b;
2534      }
2535   }
2536   return NULL;
2537}
2538
2539
2540
2541/*
2542 * Look for XMesaBuffers whose X window has been destroyed.
2543 * Deallocate any such XMesaBuffers.
2544 */
2545void XMesaGarbageCollect( void )
2546{
2547   XMesaBuffer b, next;
2548   for (b=XMesaBufferList; b; b=next) {
2549      next = b->Next;
2550      if (b->display && b->frontbuffer && b->type == WINDOW) {
2551#ifdef XFree86Server
2552	 /* NOT_NEEDED */
2553#else
2554         XSync(b->display, False);
2555         if (!window_exists( b->display, b->frontbuffer )) {
2556            /* found a dead window, free the ancillary info */
2557            XMesaDestroyBuffer( b );
2558         }
2559#endif
2560      }
2561   }
2562}
2563
2564
2565void XMesaReset( void )
2566{
2567    while (XMesaBufferList)
2568	XMesaDestroyBuffer(XMesaBufferList);
2569
2570    XMesaBufferList = NULL;
2571}
2572
2573
2574unsigned long XMesaDitherColor( XMesaContext xmesa, GLint x, GLint y,
2575                                GLfloat red, GLfloat green,
2576                                GLfloat blue, GLfloat alpha )
2577{
2578   GLint r = (GLint) (red   * 255.0F);
2579   GLint g = (GLint) (green * 255.0F);
2580   GLint b = (GLint) (blue  * 255.0F);
2581   GLint a = (GLint) (alpha * 255.0F);
2582
2583   switch (xmesa->pixelformat) {
2584      case PF_INDEX:
2585         return 0;
2586      case PF_TRUECOLOR:
2587         {
2588            unsigned long p;
2589            PACK_TRUECOLOR( p, r, g, b );
2590            return p;
2591         }
2592      case PF_8A8B8G8R:
2593         return PACK_8A8B8G8R( r, g, b, a );
2594      case PF_8R8G8B:
2595         return PACK_8R8G8B( r, g, b );
2596      case PF_5R6G5B:
2597         return PACK_5R6G5B( r, g, b );
2598      case PF_DITHER:
2599         {
2600            DITHER_SETUP;
2601            return DITHER( x, y, r, g, b );
2602         }
2603      case PF_1BIT:
2604         /* 382 = (3*255)/2 */
2605         return ((r+g+b) > 382) ^ xmesa->xm_visual->bitFlip;
2606      case PF_HPCR:
2607         return DITHER_HPCR(x, y, r, g, b);
2608      case PF_LOOKUP:
2609         {
2610            LOOKUP_SETUP;
2611            return LOOKUP( r, g, b );
2612         }
2613      case PF_GRAYSCALE:
2614         return GRAY_RGB( r, g, b );
2615      case PF_DITHER_5R6G5B:
2616         /* fall through */
2617      case PF_TRUEDITHER:
2618         {
2619            unsigned long p;
2620            PACK_TRUEDITHER(p, x, y, r, g, b);
2621            return p;
2622         }
2623      default:
2624         _mesa_problem(NULL, "Bad pixel format in XMesaDitherColor");
2625   }
2626   return 0;
2627}
2628
2629
2630/*
2631 * This is typically called when the window size changes and we need
2632 * to reallocate the buffer's back/depth/stencil/accum buffers.
2633 */
2634void XMesaResizeBuffers( XMesaBuffer b )
2635{
2636   xmesa_resize_buffers( &(b->mesa_buffer) );
2637
2638}
2639
2640