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