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