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