xm_api.c revision 9bed64cbf193e87e0dba46edf5cfaec267b0d8e6
1/* $Id: xm_api.c,v 1.27 2001/08/31 04:30:14 brianp 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 "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   if (getenv("MESA_DEBUG"))
172      fprintf( stderr, "X/Mesa error: %s\n", msg );
173}
174
175
176/*
177 * Return the host's byte order as LSBFirst or MSBFirst ala X.
178 */
179#ifndef XFree86Server
180static int host_byte_order( void )
181{
182   int i = 1;
183   char *cptr = (char *) &i;
184   return (*cptr==1) ? LSBFirst : MSBFirst;
185}
186#endif
187
188
189/*
190 * Error handling.
191 */
192#ifndef XFree86Server
193static int mesaXErrorFlag = 0;
194
195static int mesaHandleXError( XMesaDisplay *dpy, XErrorEvent *event )
196{
197   (void) dpy;
198   (void) event;
199   mesaXErrorFlag = 1;
200   return 0;
201}
202#endif
203
204
205/*
206 * Check if the X Shared Memory extension is available.
207 * Return:  0 = not available
208 *          1 = shared XImage support available
209 *          2 = shared Pixmap support available also
210 */
211#ifndef XFree86Server
212static int check_for_xshm( XMesaDisplay *display )
213{
214#ifdef USE_XSHM
215   int major, minor, ignore;
216   Bool pixmaps;
217
218   if (XQueryExtension( display, "MIT-SHM", &ignore, &ignore, &ignore )) {
219      if (XShmQueryVersion( display, &major, &minor, &pixmaps )==True) {
220	 return (pixmaps==True) ? 2 : 1;
221      }
222      else {
223	 return 0;
224      }
225   }
226   else {
227      return 0;
228   }
229#else
230   /* Can't compile XSHM support */
231   return 0;
232#endif
233}
234#endif
235
236
237/*
238 * Return the width and height of the given drawable.
239 */
240static void get_drawable_size( XMesaDisplay *dpy, XMesaDrawable d,
241                               unsigned int *width, unsigned int *height)
242{
243#ifdef XFree86Server
244    (void) dpy;
245    *width = d->width;
246    *height = d->height;
247#else
248   Window root;
249   int x, y;
250   unsigned int bw, depth;
251
252   _glthread_LOCK_MUTEX(_xmesa_lock);
253   XGetGeometry( dpy, d, &root, &x, &y, width, height, &bw, &depth );
254   _glthread_UNLOCK_MUTEX(_xmesa_lock);
255#endif
256}
257
258
259/*
260 * Apply gamma correction to an intensity value in [0..max].  Return the
261 * new intensity value.
262 */
263static GLint gamma_adjust( GLfloat gamma, GLint value, GLint max )
264{
265   if (gamma == 1.0) {
266      return value;
267   }
268   else {
269      double x = (double) value / (double) max;
270      return IROUND_POS((GLfloat) max * pow(x, 1.0F/gamma));
271   }
272}
273
274
275
276/*
277 * Return the true number of bits per pixel for XImages.
278 * For example, if we request a 24-bit deep visual we may actually need/get
279 * 32bpp XImages.  This function returns the appropriate bpp.
280 * Input:  dpy - the X display
281 *         visinfo - desribes the visual to be used for XImages
282 * Return:  true number of bits per pixel for XImages
283 */
284#define GET_BITS_PER_PIXEL(xmv) bits_per_pixel(xmv)
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                             XMesaWindow window, XMesaColormap cmap )
1034{
1035   unsigned long rmask, gmask, bmask;
1036   (void) buffer;
1037   (void) window;
1038   (void) cmap;
1039
1040   /* Compute red multiplier (mask) and bit shift */
1041   v->rshift = 0;
1042   rmask = GET_REDMASK(v);
1043   while ((rmask & 1)==0) {
1044      v->rshift++;
1045      rmask = rmask >> 1;
1046   }
1047
1048   /* Compute green multiplier (mask) and bit shift */
1049   v->gshift = 0;
1050   gmask = GET_GREENMASK(v);
1051   while ((gmask & 1)==0) {
1052      v->gshift++;
1053      gmask = gmask >> 1;
1054   }
1055
1056   /* Compute blue multiplier (mask) and bit shift */
1057   v->bshift = 0;
1058   bmask = GET_BLUEMASK(v);
1059   while ((bmask & 1)==0) {
1060      v->bshift++;
1061      bmask = bmask >> 1;
1062   }
1063
1064   /*
1065    * Compute component-to-pixel lookup tables and dithering kernel
1066    */
1067   {
1068      static GLubyte kernel[16] = {
1069          0*16,  8*16,  2*16, 10*16,
1070         12*16,  4*16, 14*16,  6*16,
1071          3*16, 11*16,  1*16,  9*16,
1072         15*16,  7*16, 13*16,  5*16,
1073      };
1074      GLint rBits = bitcount(rmask);
1075      GLint gBits = bitcount(gmask);
1076      GLint bBits = bitcount(bmask);
1077      GLint maxBits;
1078      GLuint i;
1079
1080      /* convert pixel components in [0,_mask] to RGB values in [0,255] */
1081      for (i=0; i<=rmask; i++)
1082         v->PixelToR[i] = (unsigned char) ((i * 255) / rmask);
1083      for (i=0; i<=gmask; i++)
1084         v->PixelToG[i] = (unsigned char) ((i * 255) / gmask);
1085      for (i=0; i<=bmask; i++)
1086         v->PixelToB[i] = (unsigned char) ((i * 255) / bmask);
1087
1088      /* convert RGB values from [0,255] to pixel components */
1089
1090      for (i=0;i<256;i++) {
1091         GLint r = gamma_adjust(v->RedGamma,   i, 255);
1092         GLint g = gamma_adjust(v->GreenGamma, i, 255);
1093         GLint b = gamma_adjust(v->BlueGamma,  i, 255);
1094         v->RtoPixel[i] = (r >> (8-rBits)) << v->rshift;
1095         v->GtoPixel[i] = (g >> (8-gBits)) << v->gshift;
1096         v->BtoPixel[i] = (b >> (8-bBits)) << v->bshift;
1097      }
1098      /* overflow protection */
1099      for (i=256;i<512;i++) {
1100         v->RtoPixel[i] = v->RtoPixel[255];
1101         v->GtoPixel[i] = v->GtoPixel[255];
1102         v->BtoPixel[i] = v->BtoPixel[255];
1103      }
1104
1105      /* setup dithering kernel */
1106      maxBits = rBits;
1107      if (gBits > maxBits)  maxBits = gBits;
1108      if (bBits > maxBits)  maxBits = bBits;
1109      for (i=0;i<16;i++) {
1110         v->Kernel[i] = kernel[i] >> maxBits;
1111      }
1112
1113      v->undithered_pf = PF_TRUECOLOR;
1114      v->dithered_pf = (GET_VISUAL_DEPTH(v)<24) ? PF_TRUEDITHER : PF_TRUECOLOR;
1115   }
1116
1117   /*
1118    * Now check for TrueColor visuals which we can optimize.
1119    */
1120   if (   GET_REDMASK(v)  ==0x0000ff
1121       && GET_GREENMASK(v)==0x00ff00
1122       && GET_BLUEMASK(v) ==0xff0000
1123       && CHECK_BYTE_ORDER(v)
1124       && v->BitsPerPixel==32
1125       && sizeof(GLuint)==4
1126       && v->RedGamma==1.0 && v->GreenGamma==1.0 && v->BlueGamma==1.0) {
1127      /* common 32 bpp config used on SGI, Sun */
1128      v->undithered_pf = v->dithered_pf = PF_8A8B8G8R;
1129   }
1130   else if (GET_REDMASK(v)  ==0xff0000
1131       &&   GET_GREENMASK(v)==0x00ff00
1132       &&   GET_BLUEMASK(v) ==0x0000ff
1133       && CHECK_BYTE_ORDER(v)
1134       && v->BitsPerPixel==32
1135       && sizeof(GLuint)==4
1136       && v->RedGamma==1.0 && v->GreenGamma==1.0 && v->BlueGamma==1.0) {
1137      /* common 32 bpp config used on Linux, HP, IBM */
1138      v->undithered_pf = v->dithered_pf = PF_8R8G8B;
1139   }
1140   else if (GET_REDMASK(v)  ==0xff0000
1141       &&   GET_GREENMASK(v)==0x00ff00
1142       &&   GET_BLUEMASK(v) ==0x0000ff
1143       && CHECK_BYTE_ORDER(v)
1144       && v->BitsPerPixel==24
1145       && sizeof(GLuint)==4
1146       && v->RedGamma==1.0 && v->GreenGamma==1.0 && v->BlueGamma==1.0) {
1147      /* common packed 24 bpp config used on Linux */
1148      v->undithered_pf = v->dithered_pf = PF_8R8G8B24;
1149   }
1150   else if (GET_REDMASK(v)  ==0xf800
1151       &&   GET_GREENMASK(v)==0x07e0
1152       &&   GET_BLUEMASK(v) ==0x001f
1153       && CHECK_BYTE_ORDER(v)
1154       && v->BitsPerPixel==16
1155       && sizeof(GLushort)==2
1156       && v->RedGamma==1.0 && v->GreenGamma==1.0 && v->BlueGamma==1.0) {
1157      /* 5-6-5 color weight on common PC VGA boards */
1158      v->undithered_pf = PF_5R6G5B;
1159      v->dithered_pf = PF_DITHER_5R6G5B;
1160   }
1161   else if (GET_REDMASK(v)  ==0xe0
1162       &&   GET_GREENMASK(v)==0x1c
1163       &&   GET_BLUEMASK(v) ==0x03
1164       && CHECK_FOR_HPCR(v)) {
1165      setup_8bit_hpcr( v );
1166   }
1167}
1168
1169
1170
1171/*
1172 * Setup RGB rendering for a window with a monochrome visual.
1173 */
1174static void setup_monochrome( XMesaVisual v, XMesaBuffer b )
1175{
1176   (void) b;
1177   v->dithered_pf = v->undithered_pf = PF_1BIT;
1178   /* if black=1 then we must flip pixel values */
1179   v->bitFlip = (GET_BLACK_PIXEL(v) != 0);
1180}
1181
1182
1183
1184/*
1185 * When a context is "made current" for the first time, we can finally
1186 * finish initializing the context's visual and buffer information.
1187 * Input:  v - the XMesaVisual to initialize
1188 *         b - the XMesaBuffer to initialize (may be NULL)
1189 *         rgb_flag - TRUE = RGBA mode, FALSE = color index mode
1190 *         window - the window/pixmap we're rendering into
1191 *         cmap - the colormap associated with the window/pixmap
1192 * Return:  GL_TRUE=success, GL_FALSE=failure
1193 */
1194static GLboolean initialize_visual_and_buffer( int client,
1195                                               XMesaVisual v,
1196                                               XMesaBuffer b,
1197                                               GLboolean rgb_flag,
1198                                               XMesaDrawable window,
1199                                               XMesaColormap cmap
1200                                             )
1201{
1202#ifndef XFree86Server
1203   XGCValues gcvalues;
1204#endif
1205
1206   if (b) {
1207      assert(b->xm_visual == v);
1208   }
1209
1210   /* Save true bits/pixel */
1211   v->BitsPerPixel = GET_BITS_PER_PIXEL(v);
1212   assert(v->BitsPerPixel > 0);
1213
1214
1215   if (rgb_flag==GL_FALSE) {
1216      /* COLOR-INDEXED WINDOW:
1217       * Even if the visual is TrueColor or DirectColor we treat it as
1218       * being color indexed.  This is weird but might be useful to someone.
1219       */
1220      v->dithered_pf = v->undithered_pf = PF_INDEX;
1221      v->index_bits = GET_VISUAL_DEPTH(v);
1222   }
1223   else {
1224      /* RGB WINDOW:
1225       * We support RGB rendering into almost any kind of visual.
1226       */
1227      int xclass;
1228      xclass = GET_VISUAL_CLASS(v);
1229      if (xclass==TrueColor || xclass==DirectColor) {
1230	 setup_truecolor( v, b, (XMesaWindow)window, cmap );
1231      }
1232      else if (xclass==StaticGray && GET_VISUAL_DEPTH(v)==1) {
1233	 setup_monochrome( v, b );
1234      }
1235      else if (xclass==GrayScale || xclass==StaticGray) {
1236         if (!setup_grayscale( client, v, b, cmap )) {
1237            return GL_FALSE;
1238         }
1239      }
1240      else if ((xclass==PseudoColor || xclass==StaticColor)
1241               && GET_VISUAL_DEPTH(v)>=4 && GET_VISUAL_DEPTH(v)<=16) {
1242	 if (!setup_dithered_color( client, v, b, cmap )) {
1243            return GL_FALSE;
1244         }
1245      }
1246      else {
1247	 error("XMesa: RGB mode rendering not supported in given visual.");
1248	 return GL_FALSE;
1249      }
1250      v->index_bits = 0;
1251
1252      if (getenv("MESA_NO_DITHER")) {
1253	 v->dithered_pf = v->undithered_pf;
1254      }
1255   }
1256
1257
1258   /*
1259    * If MESA_INFO env var is set print out some debugging info
1260    * which can help Brian figure out what's going on when a user
1261    * reports bugs.
1262    */
1263   if (getenv("MESA_INFO")) {
1264      fprintf(stderr, "X/Mesa visual = %p\n", v);
1265      fprintf(stderr, "X/Mesa dithered pf = %u\n", v->dithered_pf);
1266      fprintf(stderr, "X/Mesa undithered pf = %u\n", v->undithered_pf);
1267      fprintf(stderr, "X/Mesa level = %d\n", v->level);
1268      fprintf(stderr, "X/Mesa depth = %d\n", GET_VISUAL_DEPTH(v));
1269      fprintf(stderr, "X/Mesa bits per pixel = %d\n", v->BitsPerPixel);
1270   }
1271
1272   if (b && window) {
1273      /* Do window-specific initializations */
1274
1275      /* Window dimensions */
1276      unsigned int w, h;
1277      get_drawable_size( v->display, window, &w, &h );
1278      b->width = w;
1279      b->height = h;
1280
1281      b->frontbuffer = window;
1282
1283      /* Setup for single/double buffering */
1284      if (v->mesa_visual.doubleBufferMode) {
1285         /* Double buffered */
1286#ifndef XFree86Server
1287         b->shm = check_for_xshm( v->display );
1288#endif
1289         xmesa_alloc_back_buffer( b );
1290         if (b->db_state==BACK_PIXMAP) {
1291            b->buffer = (XMesaDrawable)b->backpixmap;
1292         }
1293         else {
1294            b->buffer = XIMAGE;
1295         }
1296      }
1297      else {
1298         /* Single Buffered */
1299         b->buffer = b->frontbuffer;
1300      }
1301
1302      /* X11 graphics contexts */
1303#ifdef XFree86Server
1304      b->gc = CreateScratchGC(v->display, window->depth);
1305#else
1306      b->gc = XCreateGC( v->display, window, 0, NULL );
1307#endif
1308      XMesaSetFunction( v->display, b->gc, GXcopy );
1309
1310      /*
1311       * Don't generate Graphics Expose/NoExpose events in swapbuffers().
1312       * Patch contributed by Michael Pichler May 15, 1995.
1313       */
1314#ifdef XFree86Server
1315      b->cleargc = CreateScratchGC(v->display, window->depth);
1316      {
1317	  CARD32 v[1];
1318	  v[0] = FALSE;
1319	  dixChangeGC(NullClient, b->cleargc, GCGraphicsExposures, v, NULL);
1320      }
1321#else
1322      gcvalues.graphics_exposures = False;
1323      b->cleargc = XCreateGC( v->display, window,
1324                              GCGraphicsExposures, &gcvalues);
1325#endif
1326      XMesaSetFunction( v->display, b->cleargc, GXcopy );
1327      /*
1328       * Set fill style and tile pixmap once for all for HPCR stuff
1329       * (instead of doing it each time in clear_color_HPCR_pixmap())
1330       * Initialize whole stuff
1331       * Patch contributed by Jacques Leroy March 8, 1998.
1332       */
1333      if (v->hpcr_clear_flag && b->buffer!=XIMAGE) {
1334	int i;
1335	for (i=0; i<16; i++)
1336        {
1337	   XMesaPutPixel(v->hpcr_clear_ximage, i, 0, 0);
1338	   XMesaPutPixel(v->hpcr_clear_ximage, i, 1, 0);
1339        }
1340        XMesaPutImage(b->display, (XMesaDrawable)v->hpcr_clear_pixmap,
1341		      b->cleargc, v->hpcr_clear_ximage, 0, 0, 0, 0, 16, 2);
1342	XMesaSetFillStyle( v->display, b->cleargc, FillTiled);
1343	XMesaSetTile( v->display, b->cleargc, v->hpcr_clear_pixmap );
1344      }
1345
1346      /* Initialize the row buffer XImage for use in write_color_span() */
1347#ifdef XFree86Server
1348      b->rowimage = XMesaCreateImage(GET_VISUAL_DEPTH(v), MAX_WIDTH, 1,
1349				     (char *)MALLOC(MAX_WIDTH*4));
1350#else
1351      b->rowimage = XCreateImage( v->display,
1352                                  v->visinfo->visual,
1353                                  v->visinfo->depth,
1354                                  ZPixmap, 0,           /*format, offset*/
1355                                  (char*) MALLOC(MAX_WIDTH*4),  /*data*/
1356                                  MAX_WIDTH, 1,         /*width, height*/
1357                                  32,                   /*bitmap_pad*/
1358                                  0                     /*bytes_per_line*/ );
1359#endif
1360   }
1361
1362   return GL_TRUE;
1363}
1364
1365
1366
1367/*
1368 * Convert an RGBA color to a pixel value.
1369 */
1370unsigned long
1371xmesa_color_to_pixel( XMesaContext xmesa, GLubyte r, GLubyte g, GLubyte b, GLubyte a,
1372                      GLuint pixelFormat)
1373{
1374   switch (pixelFormat) {
1375      case PF_INDEX:
1376         return 0;
1377      case PF_TRUECOLOR:
1378         {
1379            unsigned long p;
1380            PACK_TRUECOLOR( p, r, g, b );
1381            return p;
1382         }
1383      case PF_8A8B8G8R:
1384         return PACK_8A8B8G8R( r, g, b, a );
1385      case PF_8R8G8B:
1386         /* fall through */
1387      case PF_8R8G8B24:
1388         return PACK_8R8G8B( r, g, b );
1389      case PF_5R6G5B:
1390         return PACK_5R6G5B( r, g, b );
1391      case PF_DITHER:
1392         {
1393            DITHER_SETUP;
1394            return DITHER( 1, 0, r, g, b );
1395         }
1396      case PF_1BIT:
1397         /* 382 = (3*255)/2 */
1398         return ((r+g+b) > 382) ^ xmesa->xm_visual->bitFlip;
1399      case PF_HPCR:
1400         return DITHER_HPCR(1, 1, r, g, b);
1401      case PF_LOOKUP:
1402         {
1403            LOOKUP_SETUP;
1404            return LOOKUP( r, g, b );
1405         }
1406      case PF_GRAYSCALE:
1407         return GRAY_RGB( r, g, b );
1408      case PF_TRUEDITHER:
1409         /* fall through */
1410      case PF_DITHER_5R6G5B:
1411         {
1412            unsigned long p;
1413            PACK_TRUEDITHER(p, 1, 0, r, g, b);
1414            return p;
1415         }
1416      default:
1417         _mesa_problem(NULL, "Bad pixel format in xmesa_color_to_pixel");
1418   }
1419   return 0;
1420}
1421
1422
1423/**********************************************************************/
1424/*****                       Public Functions                     *****/
1425/**********************************************************************/
1426
1427
1428/*
1429 * Create a new X/Mesa visual.
1430 * Input:  display - X11 display
1431 *         visinfo - an XVisualInfo pointer
1432 *         rgb_flag - GL_TRUE = RGB mode,
1433 *                    GL_FALSE = color index mode
1434 *         alpha_flag - alpha buffer requested?
1435 *         db_flag - GL_TRUE = double-buffered,
1436 *                   GL_FALSE = single buffered
1437 *         stereo_flag - stereo visual?
1438 *         ximage_flag - GL_TRUE = use an XImage for back buffer,
1439 *                       GL_FALSE = use an off-screen pixmap for back buffer
1440 *         depth_size - requested bits/depth values, or zero
1441 *         stencil_size - requested bits/stencil values, or zero
1442 *         accum_red_size - requested bits/red accum values, or zero
1443 *         accum_green_size - requested bits/green accum values, or zero
1444 *         accum_blue_size - requested bits/blue accum values, or zero
1445 *         accum_alpha_size - requested bits/alpha accum values, or zero
1446 *         num_samples - number of samples/pixel if multisampling, or zero
1447 *         level - visual level, usually 0
1448 *         visualCaveat - ala the GLX extension, usually GLX_NONE_EXT
1449 * Return;  a new XMesaVisual or 0 if error.
1450 */
1451XMesaVisual XMesaCreateVisual( XMesaDisplay *display,
1452                               XMesaVisualInfo visinfo,
1453                               GLboolean rgb_flag,
1454                               GLboolean alpha_flag,
1455                               GLboolean db_flag,
1456                               GLboolean stereo_flag,
1457                               GLboolean ximage_flag,
1458                               GLint depth_size,
1459                               GLint stencil_size,
1460                               GLint accum_red_size,
1461                               GLint accum_green_size,
1462                               GLint accum_blue_size,
1463                               GLint accum_alpha_size,
1464                               GLint num_samples,
1465                               GLint level,
1466                               GLint visualCaveat )
1467{
1468   char *gamma;
1469   XMesaVisual v;
1470   GLint red_bits, green_bits, blue_bits, alpha_bits;
1471
1472   /* For debugging only */
1473   if (getenv("MESA_XSYNC")) {
1474      /* This makes debugging X easier.
1475       * In your debugger, set a breakpoint on _XError to stop when an
1476       * X protocol error is generated.
1477       */
1478#ifdef XFree86Server
1479      /* NOT_NEEDED */
1480#else
1481      XSynchronize( display, 1 );
1482#endif
1483   }
1484
1485   v = (XMesaVisual) CALLOC_STRUCT(xmesa_visual);
1486   if (!v) {
1487      return NULL;
1488   }
1489
1490   /*
1491    * In the X server, NULL is passed in for the display.  It will have
1492    * to be set before using this visual.  See XMesaSetVisualDisplay()
1493    * below.
1494    */
1495   v->display = display;
1496
1497   /* Save a copy of the XVisualInfo struct because the user may XFREE()
1498    * the struct but we may need some of the information contained in it
1499    * at a later time.
1500    */
1501#ifdef XFree86Server
1502   v->visinfo = visinfo;
1503#else
1504   v->visinfo = (XVisualInfo *) MALLOC(sizeof(*visinfo));
1505   if(!v->visinfo) {
1506      FREE(v);
1507      return NULL;
1508   }
1509   MEMCPY(v->visinfo, visinfo, sizeof(*visinfo));
1510
1511   /* Save a copy of the pointer now so we can find this visual again
1512    * if we need to search for it in find_glx_visual().
1513    */
1514   v->vishandle = visinfo;
1515#endif
1516
1517#ifdef XFree86Server
1518   /* Initialize the depth of the screen */
1519   {
1520       PixmapFormatRec *format;
1521
1522       for (format = screenInfo.formats;
1523	    format->depth != display->rootDepth;
1524	    format++)
1525	   ;
1526       v->screen_depth = format->bitsPerPixel;
1527   }
1528#endif
1529
1530   /* check for MESA_GAMMA environment variable */
1531   gamma = getenv("MESA_GAMMA");
1532   if (gamma) {
1533      v->RedGamma = v->GreenGamma = v->BlueGamma = 0.0;
1534      sscanf( gamma, "%f %f %f", &v->RedGamma, &v->GreenGamma, &v->BlueGamma );
1535      if (v->RedGamma<=0.0)    v->RedGamma = 1.0;
1536      if (v->GreenGamma<=0.0)  v->GreenGamma = v->RedGamma;
1537      if (v->BlueGamma<=0.0)   v->BlueGamma = v->RedGamma;
1538   }
1539   else {
1540      v->RedGamma = v->GreenGamma = v->BlueGamma = 1.0;
1541   }
1542
1543   v->ximage_flag = ximage_flag;
1544   v->level = level;
1545   v->VisualCaveat = visualCaveat;
1546
1547   (void) initialize_visual_and_buffer( 0, v, NULL, rgb_flag, 0, 0 );
1548
1549   {
1550      int xclass;
1551      xclass = GET_VISUAL_CLASS(v);
1552      if (xclass==TrueColor || xclass==DirectColor) {
1553         red_bits   = bitcount(GET_REDMASK(v));
1554         green_bits = bitcount(GET_GREENMASK(v));
1555         blue_bits  = bitcount(GET_BLUEMASK(v));
1556         alpha_bits = 0;
1557      }
1558      else {
1559         /* this is an approximation */
1560         int depth;
1561         depth = GET_VISUAL_DEPTH(v);
1562         red_bits = depth / 3;
1563         depth -= red_bits;
1564         green_bits = depth / 2;
1565         depth -= green_bits;
1566         blue_bits = depth;
1567         alpha_bits = 0;
1568         assert( red_bits + green_bits + blue_bits == GET_VISUAL_DEPTH(v) );
1569      }
1570   }
1571
1572   if (alpha_flag && alpha_bits == 0)
1573      alpha_bits = 8;
1574
1575   _mesa_initialize_visual( &v->mesa_visual,
1576                            rgb_flag, db_flag, stereo_flag,
1577                            red_bits, green_bits,
1578                            blue_bits, alpha_bits,
1579                            v->index_bits,
1580                            depth_size,
1581                            stencil_size,
1582                            accum_red_size, accum_green_size,
1583                            accum_blue_size, accum_alpha_size,
1584                            0 );
1585   return v;
1586}
1587
1588
1589void XMesaSetVisualDisplay( XMesaDisplay *dpy, XMesaVisual v )
1590{
1591    v->display = dpy;
1592}
1593
1594
1595void XMesaDestroyVisual( XMesaVisual v )
1596{
1597#ifndef XFree86Server
1598   FREE(v->visinfo);
1599#endif
1600   FREE(v);
1601}
1602
1603
1604
1605/*
1606 * Create a new XMesaContext.
1607 * Input:  v - XMesaVisual
1608 *         share_list - another XMesaContext with which to share display
1609 *                      lists or NULL if no sharing is wanted.
1610 * Return:  an XMesaContext or NULL if error.
1611 */
1612XMesaContext XMesaCreateContext( XMesaVisual v, XMesaContext share_list )
1613{
1614   XMesaContext c;
1615   GLcontext *ctx;
1616   GLboolean direct = GL_TRUE; /* XXXX */
1617   /* NOT_DONE: should this be GL_FALSE??? */
1618   static GLboolean firstTime = GL_TRUE;
1619
1620   if (firstTime) {
1621      _glthread_INIT_MUTEX(_xmesa_lock);
1622      firstTime = GL_FALSE;
1623   }
1624
1625   c = (XMesaContext) CALLOC_STRUCT(xmesa_context);
1626   if (!c) {
1627      return NULL;
1628   }
1629
1630   ctx = c->gl_ctx = _mesa_create_context( &v->mesa_visual,
1631                      share_list ? share_list->gl_ctx : (GLcontext *) NULL,
1632                      (void *) c, direct );
1633   if (!c->gl_ctx) {
1634      FREE(c);
1635      return NULL;
1636   }
1637
1638   _mesa_enable_sw_extensions(ctx);
1639   _mesa_enable_1_3_extensions(ctx);
1640   ctx->Driver.BaseCompressedTexFormat = _mesa_base_compressed_texformat;
1641   ctx->Driver.CompressedTextureSize = _mesa_compressed_texture_size;
1642   ctx->Driver.GetCompressedTexImage = _mesa_get_compressed_teximage;
1643
1644   if (CHECK_BYTE_ORDER(v)) {
1645      c->swapbytes = GL_FALSE;
1646   }
1647   else {
1648      c->swapbytes = GL_TRUE;
1649   }
1650
1651   c->xm_visual = v;
1652   c->xm_buffer = NULL;   /* set later by XMesaMakeCurrent */
1653   c->display = v->display;
1654   c->pixelformat = v->dithered_pf;      /* Dithering is enabled by default */
1655
1656   ctx->Driver.UpdateState = xmesa_update_state;
1657
1658   /* Initialize the software rasterizer and helper modules.
1659    */
1660   _swrast_CreateContext( ctx );
1661   _ac_CreateContext( ctx );
1662   _tnl_CreateContext( ctx );
1663   _swsetup_CreateContext( ctx );
1664
1665   xmesa_register_swrast_functions( ctx );
1666
1667   /* Set up some constant pointers:
1668    */
1669   xmesa_init_pointers( ctx );
1670
1671
1672   /* Run the config file
1673    */
1674   _mesa_read_config_file( ctx );
1675
1676
1677   return c;
1678}
1679
1680
1681
1682
1683void XMesaDestroyContext( XMesaContext c )
1684{
1685#ifdef FX
1686   if (c->xm_buffer && c->xm_buffer->FXctx)
1687      fxMesaDestroyContext(c->xm_buffer->FXctx);
1688#endif
1689   if (c->gl_ctx) {
1690      _swsetup_DestroyContext( c->gl_ctx );
1691      _swrast_DestroyContext( c->gl_ctx );
1692      _tnl_DestroyContext( c->gl_ctx );
1693      _ac_DestroyContext( c->gl_ctx );
1694      _mesa_destroy_context( c->gl_ctx );
1695   }
1696
1697   /*
1698    * XXX This code should really go away because the ancilliary data
1699    * associated with a window/pixmap should not go away just because
1700    * a context is destroyed.
1701    */
1702#if 0
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#endif
1725
1726   FREE( c );
1727}
1728
1729
1730
1731/*
1732 * XXX this isn't a public function!  It's a hack for the 3Dfx driver.
1733 * Create a new XMesaBuffer from an X window.
1734 * Input:  v - the XMesaVisual
1735 *         w - the window
1736 *         c - the context
1737 * Return:  new XMesaBuffer or NULL if error
1738 */
1739XMesaBuffer XMesaCreateWindowBuffer2( XMesaVisual v, XMesaWindow w,
1740                                      XMesaContext c )
1741{
1742#ifndef XFree86Server
1743   XWindowAttributes attr;
1744#endif
1745#ifdef FX
1746   char *fxEnvVar;
1747#endif
1748   int client = 0;
1749
1750   XMesaBuffer b = alloc_xmesa_buffer();
1751   if (!b) {
1752      return NULL;
1753   }
1754
1755   (void) c;
1756
1757#ifdef XFree86Server
1758   client = CLIENT_ID(((XMesaDrawable)w)->id);
1759#endif
1760
1761   assert(v);
1762
1763#ifdef XFree86Server
1764   if (GET_VISUAL_DEPTH(v) != ((XMesaDrawable)w)->depth) {
1765#else
1766   XGetWindowAttributes( v->display, w, &attr );
1767
1768   if (GET_VISUAL_DEPTH(v) != attr.depth) {
1769#endif
1770      if (getenv("MESA_DEBUG")) {
1771         fprintf(stderr, "XMesaCreateWindowBuffer: depth mismatch between visual and window!\n");
1772      }
1773      return NULL;
1774   }
1775
1776   b->xm_context = NULL; /* Associate no context with this buffer */
1777
1778   b->xm_visual = v;
1779   b->pixmap_flag = GL_FALSE;
1780   b->display = v->display;
1781#ifdef XFree86Server
1782   b->cmap = (ColormapPtr)LookupIDByType(wColormap(w), RT_COLORMAP);
1783#else
1784   if (attr.colormap) {
1785      b->cmap = attr.colormap;
1786   }
1787   else {
1788      if (getenv("MESA_DEBUG")) {
1789         fprintf(stderr, "Window %u has no colormap!\n", (unsigned int) w);
1790      }
1791      /* this is weird, a window w/out a colormap!? */
1792      /* OK, let's just allocate a new one and hope for the best */
1793      b->cmap = XCreateColormap(v->display, w, attr.visual, AllocNone);
1794   }
1795#endif
1796
1797   /* determine back buffer implementation */
1798   if (v->mesa_visual.doubleBufferMode) {
1799      if (v->ximage_flag) {
1800	 b->db_state = BACK_XIMAGE;
1801      }
1802      else {
1803	 b->db_state = BACK_PIXMAP;
1804      }
1805   }
1806   else {
1807      b->db_state = 0;
1808   }
1809
1810   _mesa_initialize_framebuffer(&b->mesa_buffer,
1811                                &v->mesa_visual,
1812                                v->mesa_visual.depthBits > 0,
1813                                v->mesa_visual.stencilBits > 0,
1814                                v->mesa_visual.accumRedBits > 0,
1815                                v->mesa_visual.alphaBits > 0 );
1816
1817   if (!initialize_visual_and_buffer( client, v, b, v->mesa_visual.rgbMode,
1818                                      (XMesaDrawable)w, b->cmap )) {
1819      free_xmesa_buffer(client, b);
1820      return NULL;
1821   }
1822
1823#ifdef FX
1824   fxEnvVar = getenv("MESA_GLX_FX");
1825   if (fxEnvVar) {
1826     if (fxEnvVar[0]!='d') {
1827       int attribs[100];
1828       int numAttribs = 0;
1829       int hw;
1830       if (v->mesa_visual.depthBits > 0) {
1831	 attribs[numAttribs++] = FXMESA_DEPTH_SIZE;
1832	 attribs[numAttribs++] = 1;
1833       }
1834       if (v->mesa_visual.doubleBufferMode) {
1835	 attribs[numAttribs++] = FXMESA_DOUBLEBUFFER;
1836       }
1837       if (v->mesa_visual.accumRedBits > 0) {
1838	 attribs[numAttribs++] = FXMESA_ACCUM_SIZE;
1839	 attribs[numAttribs++] = v->mesa_visual.accumRedBits;
1840       }
1841       if (v->mesa_visual.stencilBits > 0) {
1842         attribs[numAttribs++] = FXMESA_STENCIL_SIZE;
1843         attribs[numAttribs++] = v->mesa_visual.stencilBits;
1844       }
1845       if (v->mesa_visual.alphaBits > 0) {
1846         attribs[numAttribs++] = FXMESA_ALPHA_SIZE;
1847         attribs[numAttribs++] = 1;
1848       }
1849       if (c->gl_ctx) {
1850#define FXMESA_SHARE_CONTEXT 990099  /* keep in sync with fxapi.c! */
1851         attribs[numAttribs++] = FXMESA_SHARE_CONTEXT;
1852         attribs[numAttribs++] = (int) c->gl_ctx;
1853       }
1854       attribs[numAttribs++] = FXMESA_NONE;
1855
1856       if ((hw = fxQueryHardware())==GR_SSTTYPE_VOODOO) {
1857         b->FXctx = fxMesaCreateBestContext(0, b->width, b->height, attribs);
1858         if ((v->undithered_pf!=PF_INDEX) && (b->backimage)) {
1859	   b->FXisHackUsable = b->FXctx ? GL_TRUE : GL_FALSE;
1860	   if (fxEnvVar[0]=='w' || fxEnvVar[0]=='W')
1861	     b->FXwindowHack = b->FXctx ? GL_TRUE : GL_FALSE;
1862	   else
1863	     b->FXwindowHack = GL_FALSE;
1864         }
1865       }
1866       else {
1867         if (fxEnvVar[0]=='w' || fxEnvVar[0]=='W')
1868	   b->FXctx = fxMesaCreateContext(w, GR_RESOLUTION_NONE,
1869					  GR_REFRESH_75Hz, attribs);
1870         else
1871	   b->FXctx = fxMesaCreateBestContext(0, b->width, b->height, attribs);
1872         b->FXisHackUsable = GL_FALSE;
1873         b->FXwindowHack = GL_FALSE;
1874       }
1875       /*
1876       fprintf(stderr,
1877               "voodoo %d, wid %d height %d hack: usable %d active %d\n",
1878               hw, b->width, b->height, b->FXisHackUsable, b->FXwindowHack);
1879       */
1880     }
1881   }
1882   else {
1883      fprintf(stderr,"WARNING: This Mesa Library includes the Glide driver but\n");
1884      fprintf(stderr,"         you have not defined the MESA_GLX_FX env. var.\n");
1885      fprintf(stderr,"         (check the README.3DFX file for more information).\n\n");
1886      fprintf(stderr,"         you can disable this message with a 'export MESA_GLX_FX=disable'.\n");
1887   }
1888#endif
1889
1890   return b;
1891}
1892
1893
1894XMesaBuffer XMesaCreateWindowBuffer( XMesaVisual v, XMesaWindow w )
1895{
1896   return XMesaCreateWindowBuffer2( v, w, NULL );
1897}
1898
1899
1900/*
1901 * Create a new XMesaBuffer from an X pixmap.
1902 * Input:  v - the XMesaVisual
1903 *         p - the pixmap
1904 *         cmap - the colormap, may be 0 if using a TrueColor or DirectColor
1905 *                visual for the pixmap
1906 * Return:  new XMesaBuffer or NULL if error
1907 */
1908XMesaBuffer XMesaCreatePixmapBuffer( XMesaVisual v,
1909				     XMesaPixmap p, XMesaColormap cmap )
1910{
1911   int client = 0;
1912   XMesaBuffer b = alloc_xmesa_buffer();
1913   if (!b) {
1914      return NULL;
1915   }
1916
1917
1918#ifdef XFree86Server
1919   client = CLIENT_ID(((XMesaDrawable)p)->id);
1920#endif
1921
1922   assert(v);
1923
1924   b->xm_context = NULL; /* Associate no context with this buffer */
1925
1926   b->xm_visual = v;
1927   b->pixmap_flag = GL_TRUE;
1928   b->display = v->display;
1929   b->cmap = cmap;
1930
1931   /* determine back buffer implementation */
1932   if (v->mesa_visual.doubleBufferMode) {
1933      if (v->ximage_flag) {
1934	 b->db_state = BACK_XIMAGE;
1935      }
1936      else {
1937	 b->db_state = BACK_PIXMAP;
1938      }
1939   }
1940   else {
1941      b->db_state = 0;
1942   }
1943
1944   _mesa_initialize_framebuffer(&b->mesa_buffer,
1945                                &v->mesa_visual,
1946                                v->mesa_visual.depthBits > 0,
1947                                v->mesa_visual.stencilBits > 0,
1948                                v->mesa_visual.accumRedBits +
1949                                v->mesa_visual.accumGreenBits +
1950                                v->mesa_visual.accumBlueBits > 0,
1951                                v->mesa_visual.alphaBits > 0 );
1952
1953   if (!initialize_visual_and_buffer(client, v, b, v->mesa_visual.rgbMode,
1954				     (XMesaDrawable)p, cmap)) {
1955      free_xmesa_buffer(client, b);
1956      return NULL;
1957   }
1958
1959   return b;
1960}
1961
1962
1963
1964/*
1965 * Deallocate an XMesaBuffer structure and all related info.
1966 */
1967void XMesaDestroyBuffer( XMesaBuffer b )
1968{
1969   int client = 0;
1970
1971#ifdef XFree86Server
1972   if (b->frontbuffer)
1973       client = CLIENT_ID(b->frontbuffer->id);
1974#endif
1975
1976   if (b->gc)  XMesaFreeGC( b->xm_visual->display, b->gc );
1977   if (b->cleargc)  XMesaFreeGC( b->xm_visual->display, b->cleargc );
1978
1979   if (b->backimage) {
1980#if defined(USE_XSHM) && !defined(XFree86Server)
1981       if (b->shm) {
1982	   XShmDetach( b->xm_visual->display, &b->shminfo );
1983	   XDestroyImage( b->backimage );
1984	   shmdt( b->shminfo.shmaddr );
1985       }
1986       else
1987#endif
1988	   XMesaDestroyImage( b->backimage );
1989   }
1990   if (b->backpixmap) {
1991      XMesaFreePixmap( b->xm_visual->display, b->backpixmap );
1992      if (b->xm_visual->hpcr_clear_flag) {
1993	XMesaFreePixmap( b->xm_visual->display,
1994			 b->xm_visual->hpcr_clear_pixmap );
1995	XMesaDestroyImage( b->xm_visual->hpcr_clear_ximage );
1996      }
1997   }
1998   if (b->rowimage) {
1999      FREE( b->rowimage->data );
2000      b->rowimage->data = NULL;
2001      XMesaDestroyImage( b->rowimage );
2002   }
2003
2004   if (b->xm_context)
2005      b->xm_context->xm_buffer = NULL;
2006
2007   free_xmesa_buffer(client, b);
2008}
2009
2010
2011
2012/*
2013 * Bind buffer b to context c and make c the current rendering context.
2014 */
2015GLboolean XMesaMakeCurrent( XMesaContext c, XMesaBuffer b )
2016{
2017   return XMesaMakeCurrent2( c, b, b );
2018}
2019
2020
2021/*
2022 * Bind buffer b to context c and make c the current rendering context.
2023 */
2024GLboolean XMesaMakeCurrent2( XMesaContext c, XMesaBuffer drawBuffer,
2025                             XMesaBuffer readBuffer )
2026{
2027   if (c) {
2028      if (!drawBuffer || !readBuffer)
2029         return GL_FALSE;  /* must specify buffers! */
2030
2031#ifdef FX
2032      if (drawBuffer->FXctx) {
2033         fxMesaMakeCurrent(drawBuffer->FXctx);
2034
2035         /* Disassociate drawBuffer's current context from drawBuffer */
2036         if (drawBuffer->xm_context)
2037            drawBuffer->xm_context->xm_buffer = NULL;
2038
2039         /* Disassociate old buffer from this context */
2040         if (c->xm_buffer)
2041            c->xm_buffer->xm_context = NULL;
2042
2043         /* Associate the context with this buffer */
2044         drawBuffer->xm_context = c;
2045
2046         c->xm_buffer = drawBuffer;
2047         c->xm_read_buffer = readBuffer;
2048         c->use_read_buffer = (drawBuffer != readBuffer);
2049
2050         return GL_TRUE;
2051      }
2052#endif
2053      if (c->gl_ctx == _mesa_get_current_context()
2054          && c->xm_buffer == drawBuffer
2055          && c->xm_read_buffer == readBuffer
2056          && c->xm_buffer->wasCurrent) {
2057         /* same context and buffer, do nothing */
2058         return GL_TRUE;
2059      }
2060
2061      /* Disassociate drawBuffer's current context from drawBuffer */
2062      if (drawBuffer->xm_context)
2063         drawBuffer->xm_context->xm_buffer = NULL;
2064
2065      /* Disassociate old buffer with this context */
2066      if (c->xm_buffer)
2067	  c->xm_buffer->xm_context = NULL;
2068
2069      drawBuffer->xm_context = c; /* Associate the context with this buffer */
2070
2071      c->xm_buffer = drawBuffer;
2072      c->xm_read_buffer = readBuffer;
2073      c->use_read_buffer = (drawBuffer != readBuffer);
2074
2075      _mesa_make_current2(c->gl_ctx,
2076                          &drawBuffer->mesa_buffer,
2077                          &readBuffer->mesa_buffer);
2078
2079      if (c->gl_ctx->Viewport.Width == 0) {
2080	 /* initialize viewport to window size */
2081	 _mesa_Viewport( 0, 0, drawBuffer->width, drawBuffer->height );
2082	 c->gl_ctx->Scissor.Width = drawBuffer->width;
2083	 c->gl_ctx->Scissor.Height = drawBuffer->height;
2084      }
2085
2086      if (c->xm_visual->mesa_visual.rgbMode) {
2087         /*
2088          * Must recompute and set these pixel values because colormap
2089          * can be different for different windows.
2090          */
2091         c->clearpixel = xmesa_color_to_pixel( c,
2092                                               c->clearcolor[0],
2093                                               c->clearcolor[1],
2094                                               c->clearcolor[2],
2095                                               c->clearcolor[3],
2096                                               c->xm_visual->undithered_pf);
2097         XMesaSetForeground(c->display, c->xm_buffer->cleargc, c->clearpixel);
2098      }
2099
2100      /* Solution to Stephane Rehel's problem with glXReleaseBuffersMESA(): */
2101      c->xm_buffer->wasCurrent = GL_TRUE;
2102   }
2103   else {
2104      /* Detach */
2105      _mesa_make_current2( NULL, NULL, NULL );
2106   }
2107   return GL_TRUE;
2108}
2109
2110
2111/*
2112 * Unbind the context c from its buffer.
2113 */
2114GLboolean XMesaUnbindContext( XMesaContext c )
2115{
2116   /* A no-op for XFree86 integration purposes */
2117   return GL_TRUE;
2118}
2119
2120
2121XMesaContext XMesaGetCurrentContext( void )
2122{
2123   GET_CURRENT_CONTEXT(ctx);
2124   if (ctx) {
2125      XMesaContext xmesa = (XMesaContext) ctx->DriverCtx;
2126      return xmesa;
2127   }
2128   else {
2129      return 0;
2130   }
2131}
2132
2133
2134XMesaBuffer XMesaGetCurrentBuffer( void )
2135{
2136   GET_CURRENT_CONTEXT(ctx);
2137   if (ctx) {
2138      XMesaContext xmesa = (XMesaContext) ctx->DriverCtx;
2139      return xmesa->xm_buffer;
2140   }
2141   else {
2142      return 0;
2143   }
2144}
2145
2146
2147/* New in Mesa 3.1 */
2148XMesaBuffer XMesaGetCurrentReadBuffer( void )
2149{
2150   GET_CURRENT_CONTEXT(ctx);
2151   if (ctx) {
2152      XMesaContext xmesa = (XMesaContext) ctx->DriverCtx;
2153      return xmesa->xm_buffer;
2154   }
2155   else {
2156      return 0;
2157   }
2158}
2159
2160
2161GLboolean XMesaForceCurrent(XMesaContext c)
2162{
2163   if (c) {
2164      if (c->gl_ctx != _mesa_get_current_context()) {
2165	 _mesa_make_current(c->gl_ctx, &c->xm_buffer->mesa_buffer);
2166      }
2167   }
2168   else {
2169      _mesa_make_current(NULL, NULL);
2170   }
2171   return GL_TRUE;
2172}
2173
2174
2175GLboolean XMesaLoseCurrent(XMesaContext c)
2176{
2177   (void) c;
2178   _mesa_make_current(NULL, NULL);
2179   return GL_TRUE;
2180}
2181
2182
2183/*
2184 * Switch 3Dfx support hack between window and full-screen mode.
2185 */
2186GLboolean XMesaSetFXmode( GLint mode )
2187{
2188#ifdef FX
2189   const char *fx = getenv("MESA_GLX_FX");
2190   if (fx && fx[0] != 'd') {
2191      GET_CURRENT_CONTEXT(ctx);
2192      GrHwConfiguration hw;
2193      if (!FX_grSstQueryHardware(&hw)) {
2194         /*fprintf(stderr, "!grSstQueryHardware\n");*/
2195         return GL_FALSE;
2196      }
2197      if (hw.num_sst < 1) {
2198         /*fprintf(stderr, "hw.num_sst < 1\n");*/
2199         return GL_FALSE;
2200      }
2201      if (ctx) {
2202         XMesaContext xmesa = (XMesaContext) ctx->DriverCtx;
2203         if (mode == XMESA_FX_WINDOW) {
2204	    if (xmesa->xm_buffer->FXisHackUsable) {
2205	       FX_grSstControl(GR_CONTROL_DEACTIVATE);
2206	       xmesa->xm_buffer->FXwindowHack = GL_TRUE;
2207	       return GL_TRUE;
2208	    }
2209	 }
2210	 else if (mode == XMESA_FX_FULLSCREEN) {
2211	    FX_grSstControl(GR_CONTROL_ACTIVATE);
2212	    xmesa->xm_buffer->FXwindowHack = GL_FALSE;
2213	    return GL_TRUE;
2214	 }
2215	 else {
2216	    /* Error: Bad mode value */
2217	 }
2218      }
2219   }
2220   /*fprintf(stderr, "fallthrough\n");*/
2221#else
2222   (void) mode;
2223#endif
2224   return GL_FALSE;
2225}
2226
2227
2228
2229#ifdef FX
2230/*
2231 * Read image from VooDoo frame buffer into X/Mesa's back XImage.
2232 */
2233static void FXgetImage( XMesaBuffer b )
2234{
2235   static unsigned short pixbuf[MAX_WIDTH];
2236   GLuint x, y;
2237   int xpos, ypos;
2238   XMesaWindow root;
2239   unsigned int bw, depth, width, height;
2240   XMesaContext xmesa = (XMesaContext) b->xm_context->gl_ctx->DriverCtx;
2241
2242   assert(xmesa->xm_buffer->FXctx);
2243
2244#ifdef XFree86Server
2245   x = b->frontbuffer->x;
2246   y = b->frontbuffer->y;
2247   width = b->frontbuffer->width;
2248   height = b->frontbuffer->height;
2249   depth = b->frontbuffer->depth;
2250#else
2251   XGetGeometry( xmesa->xm_visual->display, b->frontbuffer,
2252                 &root, &xpos, &ypos, &width, &height, &bw, &depth);
2253#endif
2254   if (b->width != width || b->height != height) {
2255      b->width = MIN2((int)width, xmesa->xm_buffer->FXctx->width);
2256      b->height = MIN2((int)height, xmesa->xm_buffer->FXctx->height);
2257      if (b->width & 1)
2258         b->width--;  /* prevent odd width */
2259      xmesa_alloc_back_buffer( b );
2260   }
2261
2262   grLfbWriteColorFormat(GR_COLORFORMAT_ARGB);
2263   if (xmesa->xm_visual->undithered_pf==PF_5R6G5B) {
2264      /* Special case: 16bpp RGB */
2265      grLfbReadRegion( GR_BUFFER_FRONTBUFFER,       /* src buffer */
2266                       0, xmesa->xm_buffer->FXctx->height - b->height,  /*pos*/
2267                       b->width, b->height,         /* size */
2268                       b->width * sizeof(GLushort), /* stride */
2269                       b->backimage->data);         /* dest buffer */
2270   }
2271   else if (xmesa->xm_visual->dithered_pf==PF_DITHER
2272	    && GET_VISUAL_DEPTH(xmesa->xm_visual)==8) {
2273      /* Special case: 8bpp RGB */
2274      for (y=0;y<b->height;y++) {
2275         GLubyte *ptr = (GLubyte*) xmesa->xm_buffer->backimage->data
2276                        + xmesa->xm_buffer->backimage->bytes_per_line * y;
2277         XDITHER_SETUP(y);
2278
2279         /* read row from 3Dfx frame buffer */
2280         grLfbReadRegion( GR_BUFFER_FRONTBUFFER,
2281                          0, xmesa->xm_buffer->FXctx->height-(b->height-y),
2282                          b->width, 1,
2283                          0,
2284                          pixbuf );
2285
2286         /* write to XImage back buffer */
2287         for (x=0;x<b->width;x++) {
2288            GLubyte r = (pixbuf[x] & 0xf800) >> 8;
2289            GLubyte g = (pixbuf[x] & 0x07e0) >> 3;
2290            GLubyte b = (pixbuf[x] & 0x001f) << 3;
2291            *ptr++ = XDITHER( x, r, g, b);
2292         }
2293      }
2294   }
2295   else {
2296      /* General case: slow! */
2297      for (y=0;y<b->height;y++) {
2298         /* read row from 3Dfx frame buffer */
2299         grLfbReadRegion( GR_BUFFER_FRONTBUFFER,
2300                          0, xmesa->xm_buffer->FXctx->height-(b->height-y),
2301                          b->width, 1,
2302                          0,
2303                          pixbuf );
2304
2305         /* write to XImage back buffer */
2306         for (x=0;x<b->width;x++) {
2307            XMesaPutPixel(b->backimage,x,y,
2308			  xmesa_color_to_pixel(xmesa,
2309					       (pixbuf[x] & 0xf800) >> 8,
2310					       (pixbuf[x] & 0x07e0) >> 3,
2311					       (pixbuf[x] & 0x001f) << 3,
2312					       0xff, xmesa->pixelformat));
2313         }
2314      }
2315   }
2316   grLfbWriteColorFormat(GR_COLORFORMAT_ABGR);
2317}
2318#endif
2319
2320
2321/*
2322 * Copy the back buffer to the front buffer.  If there's no back buffer
2323 * this is a no-op.
2324 */
2325void XMesaSwapBuffers( XMesaBuffer b )
2326{
2327   GET_CURRENT_CONTEXT(ctx);
2328
2329   /* If we're swapping the buffer associated with the current context
2330    * we have to flush any pending rendering commands first.
2331    */
2332   if (b->xm_context && b->xm_context->gl_ctx == ctx)
2333      _mesa_swapbuffers(ctx);
2334
2335   if (b->db_state) {
2336#ifdef FX
2337      if (b->FXctx) {
2338         fxMesaSwapBuffers();
2339
2340         if (b->FXwindowHack)
2341            FXgetImage(b);
2342         else
2343            return;
2344      }
2345#endif
2346     if (b->backimage) {
2347	 /* Copy Ximage from host's memory to server's window */
2348#if defined(USE_XSHM) && !defined(XFree86Server)
2349	 if (b->shm) {
2350            /*_glthread_LOCK_MUTEX(_xmesa_lock);*/
2351	    XShmPutImage( b->xm_visual->display, b->frontbuffer,
2352			  b->cleargc,
2353			  b->backimage, 0, 0,
2354			  0, 0, b->width, b->height, False );
2355            /*_glthread_UNLOCK_MUTEX(_xmesa_lock);*/
2356	 }
2357	 else
2358#endif
2359         {
2360            /*_glthread_LOCK_MUTEX(_xmesa_lock);*/
2361            XMesaPutImage( b->xm_visual->display, b->frontbuffer,
2362			   b->cleargc,
2363			   b->backimage, 0, 0,
2364			   0, 0, b->width, b->height );
2365            /*_glthread_UNLOCK_MUTEX(_xmesa_lock);*/
2366         }
2367      }
2368      else {
2369	 /* Copy pixmap to window on server */
2370         /*_glthread_LOCK_MUTEX(_xmesa_lock);*/
2371	 XMesaCopyArea( b->xm_visual->display,
2372			b->backpixmap,   /* source drawable */
2373			b->frontbuffer,  /* dest. drawable */
2374			b->cleargc,
2375			0, 0, b->width, b->height,  /* source region */
2376			0, 0                 /* dest region */
2377		      );
2378         /*_glthread_UNLOCK_MUTEX(_xmesa_lock);*/
2379      }
2380   }
2381#if !defined(XFree86Server)
2382   XSync( b->xm_visual->display, False );
2383#endif
2384}
2385
2386
2387
2388/*
2389 * Copy sub-region of back buffer to front buffer
2390 */
2391void XMesaCopySubBuffer( XMesaBuffer b, int x, int y, int width, int height )
2392{
2393   GET_CURRENT_CONTEXT(ctx);
2394
2395   /* If we're swapping the buffer associated with the current context
2396    * we have to flush any pending rendering commands first.
2397    */
2398   if (b->xm_context->gl_ctx == ctx)
2399      _mesa_swapbuffers(ctx);
2400
2401   if (b->db_state) {
2402      int yTop = b->height - y - height;
2403#ifdef FX
2404      if (b->FXctx) {
2405         fxMesaSwapBuffers();
2406         if (b->FXwindowHack)
2407            FXgetImage(b);
2408         else
2409            return;
2410      }
2411#endif
2412      if (b->backimage) {
2413         /* Copy Ximage from host's memory to server's window */
2414#if defined(USE_XSHM) && !defined(XFree86Server)
2415         if (b->shm) {
2416            /* XXX assuming width and height aren't too large! */
2417            XShmPutImage( b->xm_visual->display, b->frontbuffer,
2418                          b->cleargc,
2419                          b->backimage, x, yTop,
2420                          x, yTop, width, height, False );
2421            /* wait for finished event??? */
2422         }
2423         else
2424#endif
2425         {
2426            /* XXX assuming width and height aren't too large! */
2427            XMesaPutImage( b->xm_visual->display, b->frontbuffer,
2428			   b->cleargc,
2429			   b->backimage, x, yTop,
2430			   x, yTop, width, height );
2431         }
2432      }
2433      else {
2434         /* Copy pixmap to window on server */
2435         XMesaCopyArea( b->xm_visual->display,
2436			b->backpixmap,           /* source drawable */
2437			b->frontbuffer,          /* dest. drawable */
2438			b->cleargc,
2439			x, yTop, width, height,  /* source region */
2440			x, yTop                  /* dest region */
2441                      );
2442      }
2443   }
2444}
2445
2446
2447/*
2448 * Return a pointer to the XMesa backbuffer Pixmap or XImage.  This function
2449 * is a way to get "under the hood" of X/Mesa so one can manipulate the
2450 * back buffer directly.
2451 * Output:  pixmap - pointer to back buffer's Pixmap, or 0
2452 *          ximage - pointer to back buffer's XImage, or NULL
2453 * Return:  GL_TRUE = context is double buffered
2454 *          GL_FALSE = context is single buffered
2455 */
2456GLboolean XMesaGetBackBuffer( XMesaBuffer b,
2457                              XMesaPixmap *pixmap,
2458                              XMesaImage **ximage )
2459{
2460   if (b->db_state) {
2461      if (pixmap)  *pixmap = b->backpixmap;
2462      if (ximage)  *ximage = b->backimage;
2463      return GL_TRUE;
2464   }
2465   else {
2466      *pixmap = 0;
2467      *ximage = NULL;
2468      return GL_FALSE;
2469   }
2470}
2471
2472
2473/*
2474 * Return the depth buffer associated with an XMesaBuffer.
2475 * Input:  b - the XMesa buffer handle
2476 * Output:  width, height - size of buffer in pixels
2477 *          bytesPerValue - bytes per depth value (2 or 4)
2478 *          buffer - pointer to depth buffer values
2479 * Return:  GL_TRUE or GL_FALSE to indicate success or failure.
2480 */
2481GLboolean XMesaGetDepthBuffer( XMesaBuffer b, GLint *width, GLint *height,
2482                               GLint *bytesPerValue, void **buffer )
2483{
2484   if (!b->mesa_buffer.DepthBuffer) {
2485      *width = 0;
2486      *height = 0;
2487      *bytesPerValue = 0;
2488      *buffer = 0;
2489      return GL_FALSE;
2490   }
2491   else {
2492      *width = b->mesa_buffer.Width;
2493      *height = b->mesa_buffer.Height;
2494      *bytesPerValue = sizeof(GLdepth);
2495      *buffer = b->mesa_buffer.DepthBuffer;
2496      return GL_TRUE;
2497   }
2498}
2499
2500
2501void XMesaFlush( XMesaContext c )
2502{
2503   if (c && c->xm_visual) {
2504#ifdef XFree86Server
2505      /* NOT_NEEDED */
2506#else
2507      XSync( c->xm_visual->display, False );
2508#endif
2509   }
2510}
2511
2512
2513
2514const char *XMesaGetString( XMesaContext c, int name )
2515{
2516   (void) c;
2517   if (name==XMESA_VERSION) {
2518      return "3.5";
2519   }
2520   else if (name==XMESA_EXTENSIONS) {
2521      return "";
2522   }
2523   else {
2524      return NULL;
2525   }
2526}
2527
2528
2529
2530XMesaBuffer XMesaFindBuffer( XMesaDisplay *dpy, XMesaDrawable d )
2531{
2532   XMesaBuffer b;
2533   for (b=XMesaBufferList; b; b=b->Next) {
2534      if (b->frontbuffer==d && b->display==dpy) {
2535         return b;
2536      }
2537   }
2538   return NULL;
2539}
2540
2541
2542
2543/*
2544 * Look for XMesaBuffers whose X window has been destroyed.
2545 * Deallocate any such XMesaBuffers.
2546 */
2547void XMesaGarbageCollect( void )
2548{
2549   XMesaBuffer b, next;
2550   for (b=XMesaBufferList; b; b=next) {
2551      next = b->Next;
2552      if (!b->pixmap_flag) {
2553#ifdef XFree86Server
2554	 /* NOT_NEEDED */
2555#else
2556         XSync(b->display, False);
2557         if (!window_exists( b->display, b->frontbuffer )) {
2558            /* found a dead window, free the ancillary info */
2559            XMesaDestroyBuffer( b );
2560         }
2561#endif
2562      }
2563   }
2564}
2565
2566
2567void XMesaReset( void )
2568{
2569    while (XMesaBufferList)
2570	XMesaDestroyBuffer(XMesaBufferList);
2571
2572    XMesaBufferList = NULL;
2573}
2574
2575
2576unsigned long XMesaDitherColor( XMesaContext xmesa, GLint x, GLint y,
2577                                GLfloat red, GLfloat green,
2578                                GLfloat blue, GLfloat alpha )
2579{
2580   GLint r = (GLint) (red   * 255.0F);
2581   GLint g = (GLint) (green * 255.0F);
2582   GLint b = (GLint) (blue  * 255.0F);
2583   GLint a = (GLint) (alpha * 255.0F);
2584
2585   switch (xmesa->pixelformat) {
2586      case PF_INDEX:
2587         return 0;
2588      case PF_TRUECOLOR:
2589         {
2590            unsigned long p;
2591            PACK_TRUECOLOR( p, r, g, b );
2592            return p;
2593         }
2594      case PF_8A8B8G8R:
2595         return PACK_8A8B8G8R( r, g, b, a );
2596      case PF_8R8G8B:
2597         return PACK_8R8G8B( r, g, b );
2598      case PF_5R6G5B:
2599         return PACK_5R6G5B( r, g, b );
2600      case PF_DITHER:
2601         {
2602            DITHER_SETUP;
2603            return DITHER( x, y, r, g, b );
2604         }
2605      case PF_1BIT:
2606         /* 382 = (3*255)/2 */
2607         return ((r+g+b) > 382) ^ xmesa->xm_visual->bitFlip;
2608      case PF_HPCR:
2609         return DITHER_HPCR(x, y, r, g, b);
2610      case PF_LOOKUP:
2611         {
2612            LOOKUP_SETUP;
2613            return LOOKUP( r, g, b );
2614         }
2615      case PF_GRAYSCALE:
2616         return GRAY_RGB( r, g, b );
2617      case PF_DITHER_5R6G5B:
2618         /* fall through */
2619      case PF_TRUEDITHER:
2620         {
2621            unsigned long p;
2622            PACK_TRUEDITHER(p, x, y, r, g, b);
2623            return p;
2624         }
2625      default:
2626         _mesa_problem(NULL, "Bad pixel format in XMesaDitherColor");
2627   }
2628   return 0;
2629}
2630
2631
2632