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