• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 /*
2  * Mesa 3-D graphics library
3  *
4  * Copyright (C) 1999-2007  Brian Paul   All Rights Reserved.
5  *
6  * Permission is hereby granted, free of charge, to any person obtaining a
7  * copy of this software and associated documentation files (the "Software"),
8  * to deal in the Software without restriction, including without limitation
9  * the rights to use, copy, modify, merge, publish, distribute, sublicense,
10  * and/or sell copies of the Software, and to permit persons to whom the
11  * Software is furnished to do so, subject to the following conditions:
12  *
13  * The above copyright notice and this permission notice shall be included
14  * in all copies or substantial portions of the Software.
15  *
16  * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
17  * OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
18  * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.  IN NO EVENT SHALL
19  * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR
20  * OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,
21  * ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
22  * OTHER DEALINGS IN THE SOFTWARE.
23  */
24 
25 /**
26  * \file xm_api.c
27  *
28  * All the XMesa* API functions.
29  *
30  *
31  * NOTES:
32  *
33  * The window coordinate system origin (0,0) is in the lower-left corner
34  * of the window.  X11's window coordinate origin is in the upper-left
35  * corner of the window.  Therefore, most drawing functions in this
36  * file have to flip Y coordinates.
37  *
38  * Define USE_XSHM in the Makefile with -DUSE_XSHM if you want to compile
39  * in support for the MIT Shared Memory extension.  If enabled, when you
40  * use an Ximage for the back buffer in double buffered mode, the "swap"
41  * operation will be faster.  You must also link with -lXext.
42  *
43  * Byte swapping:  If the Mesa host and the X display use a different
44  * byte order then there's some trickiness to be aware of when using
45  * XImages.  The byte ordering used for the XImage is that of the X
46  * display, not the Mesa host.
47  * The color-to-pixel encoding for True/DirectColor must be done
48  * according to the display's visual red_mask, green_mask, and blue_mask.
49  * If XPutPixel is used to put a pixel into an XImage then XPutPixel will
50  * do byte swapping if needed.  If one wants to directly "poke" the pixel
51  * into the XImage's buffer then the pixel must be byte swapped first.  In
52  * Mesa, when byte swapping is needed we use the PF_TRUECOLOR pixel format
53  * and use XPutPixel everywhere except in the implementation of
54  * glClear(GL_COLOR_BUFFER_BIT).  We want this function to be fast so
55  * instead of using XPutPixel we "poke" our values after byte-swapping
56  * the clear pixel value if needed.
57  *
58  */
59 
60 #ifdef __CYGWIN__
61 #undef WIN32
62 #undef __WIN32__
63 #endif
64 
65 #include <stdio.h>
66 #include "glxheader.h"
67 #include "xmesaP.h"
68 #include "main/api_exec.h"
69 #include "main/context.h"
70 #include "main/extensions.h"
71 #include "main/framebuffer.h"
72 #include "main/macros.h"
73 #include "main/renderbuffer.h"
74 #include "main/state.h"
75 #include "main/teximage.h"
76 #include "main/version.h"
77 #include "main/vtxfmt.h"
78 #include "swrast/swrast.h"
79 #include "swrast/s_renderbuffer.h"
80 #include "swrast_setup/swrast_setup.h"
81 #include "vbo/vbo.h"
82 #include "tnl/tnl.h"
83 #include "tnl/t_context.h"
84 #include "tnl/t_pipeline.h"
85 #include "drivers/common/driverfuncs.h"
86 #include "drivers/common/meta.h"
87 #include "util/u_memory.h"
88 
89 /**
90  * Global X driver lock
91  */
92 mtx_t _xmesa_lock;
93 
94 
95 
96 /**********************************************************************/
97 /*****                     X Utility Functions                    *****/
98 /**********************************************************************/
99 
100 
101 /**
102  * Return the host's byte order as LSBFirst or MSBFirst ala X.
103  */
host_byte_order(void)104 static int host_byte_order( void )
105 {
106    int i = 1;
107    char *cptr = (char *) &i;
108    return (*cptr==1) ? LSBFirst : MSBFirst;
109 }
110 
111 
112 /**
113  * Check if the X Shared Memory extension is available.
114  * Return:  0 = not available
115  *          1 = shared XImage support available
116  *          2 = shared Pixmap support available also
117  */
check_for_xshm(XMesaDisplay * display)118 static int check_for_xshm( XMesaDisplay *display )
119 {
120 #if defined(USE_XSHM)
121    int ignore;
122 
123    if (XQueryExtension( display, "MIT-SHM", &ignore, &ignore, &ignore )) {
124       /* Note: we're no longer calling XShmQueryVersion() here.  It seems
125        * to be flakey (triggers a spurious X protocol error when we close
126        * one display connection and start using a new one.  XShm has been
127        * around a long time and hasn't changed so if MIT_SHM is supported
128        * we assume we're good to go.
129        */
130       return 2;
131    }
132    else {
133       return 0;
134    }
135 #else
136    /* No  XSHM support */
137    return 0;
138 #endif
139 }
140 
141 
142 /**
143  * Apply gamma correction to an intensity value in [0..max].  Return the
144  * new intensity value.
145  */
146 static GLint
gamma_adjust(GLfloat gamma,GLint value,GLint max)147 gamma_adjust( GLfloat gamma, GLint value, GLint max )
148 {
149    if (gamma == 1.0) {
150       return value;
151    }
152    else {
153       double x = (double) value / (double) max;
154       return lroundf((GLfloat) max * pow(x, 1.0F/gamma));
155    }
156 }
157 
158 
159 
160 /**
161  * Return the true number of bits per pixel for XImages.
162  * For example, if we request a 24-bit deep visual we may actually need/get
163  * 32bpp XImages.  This function returns the appropriate bpp.
164  * Input:  dpy - the X display
165  *         visinfo - desribes the visual to be used for XImages
166  * Return:  true number of bits per pixel for XImages
167  */
168 static int
bits_per_pixel(XMesaVisual xmv)169 bits_per_pixel( XMesaVisual xmv )
170 {
171    XMesaDisplay *dpy = xmv->display;
172    XMesaVisualInfo visinfo = xmv->visinfo;
173    XMesaImage *img;
174    int bitsPerPixel;
175    /* Create a temporary XImage */
176    img = XCreateImage( dpy, visinfo->visual, visinfo->depth,
177 		       ZPixmap, 0,           /*format, offset*/
178 		       malloc(8),    /*data*/
179 		       1, 1,                 /*width, height*/
180 		       32,                   /*bitmap_pad*/
181 		       0                     /*bytes_per_line*/
182                      );
183    assert(img);
184    /* grab the bits/pixel value */
185    bitsPerPixel = img->bits_per_pixel;
186    /* free the XImage */
187    free( img->data );
188    img->data = NULL;
189    XMesaDestroyImage( img );
190    return bitsPerPixel;
191 }
192 
193 
194 
195 /*
196  * Determine if a given X window ID is valid (window exists).
197  * Do this by calling XGetWindowAttributes() for the window and
198  * checking if we catch an X error.
199  * Input:  dpy - the display
200  *         win - the window to check for existence
201  * Return:  GL_TRUE - window exists
202  *          GL_FALSE - window doesn't exist
203  */
204 static GLboolean WindowExistsFlag;
205 
window_exists_err_handler(XMesaDisplay * dpy,XErrorEvent * xerr)206 static int window_exists_err_handler( XMesaDisplay* dpy, XErrorEvent* xerr )
207 {
208    (void) dpy;
209    if (xerr->error_code == BadWindow) {
210       WindowExistsFlag = GL_FALSE;
211    }
212    return 0;
213 }
214 
window_exists(XMesaDisplay * dpy,Window win)215 static GLboolean window_exists( XMesaDisplay *dpy, Window win )
216 {
217    XWindowAttributes wa;
218    int (*old_handler)( XMesaDisplay*, XErrorEvent* );
219    WindowExistsFlag = GL_TRUE;
220    old_handler = XSetErrorHandler(window_exists_err_handler);
221    XGetWindowAttributes( dpy, win, &wa ); /* dummy request */
222    XSetErrorHandler(old_handler);
223    return WindowExistsFlag;
224 }
225 
226 static Status
get_drawable_size(XMesaDisplay * dpy,Drawable d,GLuint * width,GLuint * height)227 get_drawable_size( XMesaDisplay *dpy, Drawable d, GLuint *width, GLuint *height )
228 {
229    Window root;
230    Status stat;
231    int xpos, ypos;
232    unsigned int w, h, bw, depth;
233    stat = XGetGeometry(dpy, d, &root, &xpos, &ypos, &w, &h, &bw, &depth);
234    *width = w;
235    *height = h;
236    return stat;
237 }
238 
239 
240 /**
241  * Return the size of the window (or pixmap) that corresponds to the
242  * given XMesaBuffer.
243  * \param width  returns width in pixels
244  * \param height  returns height in pixels
245  */
246 void
xmesa_get_window_size(XMesaDisplay * dpy,XMesaBuffer b,GLuint * width,GLuint * height)247 xmesa_get_window_size(XMesaDisplay *dpy, XMesaBuffer b,
248                       GLuint *width, GLuint *height)
249 {
250    Status stat;
251 
252    mtx_lock(&_xmesa_lock);
253    XSync(b->xm_visual->display, 0); /* added for Chromium */
254    stat = get_drawable_size(dpy, b->frontxrb->pixmap, width, height);
255    mtx_unlock(&_xmesa_lock);
256 
257    if (!stat) {
258       /* probably querying a window that's recently been destroyed */
259       _mesa_warning(NULL, "XGetGeometry failed!\n");
260       *width = *height = 1;
261    }
262 }
263 
264 
265 
266 /**********************************************************************/
267 /*****                Linked list of XMesaBuffers                 *****/
268 /**********************************************************************/
269 
270 XMesaBuffer XMesaBufferList = NULL;
271 
272 
273 /**
274  * Allocate a new XMesaBuffer object which corresponds to the given drawable.
275  * Note that XMesaBuffer is derived from struct gl_framebuffer.
276  * The new XMesaBuffer will not have any size (Width=Height=0).
277  *
278  * \param d  the corresponding X drawable (window or pixmap)
279  * \param type  either WINDOW, PIXMAP or PBUFFER, describing d
280  * \param vis  the buffer's visual
281  * \param cmap  the window's colormap, if known.
282  * \return new XMesaBuffer or NULL if any problem
283  */
284 static XMesaBuffer
create_xmesa_buffer(XMesaDrawable d,BufferType type,XMesaVisual vis,XMesaColormap cmap)285 create_xmesa_buffer(XMesaDrawable d, BufferType type,
286                     XMesaVisual vis, XMesaColormap cmap)
287 {
288    XMesaBuffer b;
289 
290    assert(type == WINDOW || type == PIXMAP || type == PBUFFER);
291 
292    b = (XMesaBuffer) CALLOC_STRUCT(xmesa_buffer);
293    if (!b)
294       return NULL;
295 
296    b->display = vis->display;
297    b->xm_visual = vis;
298    b->type = type;
299    b->cmap = cmap;
300 
301    _mesa_initialize_window_framebuffer(&b->mesa_buffer, &vis->mesa_visual);
302    b->mesa_buffer.Delete = xmesa_delete_framebuffer;
303 
304    /*
305     * Front renderbuffer
306     */
307    b->frontxrb = xmesa_new_renderbuffer(NULL, 0, vis, GL_FALSE);
308    if (!b->frontxrb) {
309       free(b);
310       return NULL;
311    }
312    b->frontxrb->Parent = b;
313    b->frontxrb->drawable = d;
314    b->frontxrb->pixmap = (XMesaPixmap) d;
315    _mesa_attach_and_own_rb(&b->mesa_buffer, BUFFER_FRONT_LEFT,
316                            &b->frontxrb->Base.Base);
317 
318    /*
319     * Back renderbuffer
320     */
321    if (vis->mesa_visual.doubleBufferMode) {
322       b->backxrb = xmesa_new_renderbuffer(NULL, 0, vis, GL_TRUE);
323       if (!b->backxrb) {
324          /* XXX free front xrb too */
325          free(b);
326          return NULL;
327       }
328       b->backxrb->Parent = b;
329       /* determine back buffer implementation */
330       b->db_mode = vis->ximage_flag ? BACK_XIMAGE : BACK_PIXMAP;
331 
332       _mesa_attach_and_own_rb(&b->mesa_buffer, BUFFER_BACK_LEFT,
333                               &b->backxrb->Base.Base);
334    }
335 
336    /*
337     * Other renderbuffer (depth, stencil, etc)
338     */
339    _swrast_add_soft_renderbuffers(&b->mesa_buffer,
340                                   GL_FALSE,  /* color */
341                                   vis->mesa_visual.depthBits > 0,
342                                   vis->mesa_visual.stencilBits > 0,
343                                   vis->mesa_visual.accumRedBits > 0,
344                                   GL_FALSE  /* software alpha buffer */ );
345 
346    /* GLX_EXT_texture_from_pixmap */
347    b->TextureTarget = 0;
348    b->TextureFormat = GLX_TEXTURE_FORMAT_NONE_EXT;
349    b->TextureMipmap = 0;
350 
351    /* insert buffer into linked list */
352    b->Next = XMesaBufferList;
353    XMesaBufferList = b;
354 
355    return b;
356 }
357 
358 
359 /**
360  * Find an XMesaBuffer by matching X display and colormap but NOT matching
361  * the notThis buffer.
362  */
363 XMesaBuffer
xmesa_find_buffer(XMesaDisplay * dpy,XMesaColormap cmap,XMesaBuffer notThis)364 xmesa_find_buffer(XMesaDisplay *dpy, XMesaColormap cmap, XMesaBuffer notThis)
365 {
366    XMesaBuffer b;
367    for (b=XMesaBufferList; b; b=b->Next) {
368       if (b->display==dpy && b->cmap==cmap && b!=notThis) {
369          return b;
370       }
371    }
372    return NULL;
373 }
374 
375 
376 /**
377  * Remove buffer from linked list, delete if no longer referenced.
378  */
379 static void
xmesa_free_buffer(XMesaBuffer buffer)380 xmesa_free_buffer(XMesaBuffer buffer)
381 {
382    XMesaBuffer prev = NULL, b;
383 
384    for (b = XMesaBufferList; b; b = b->Next) {
385       if (b == buffer) {
386          struct gl_framebuffer *fb = &buffer->mesa_buffer;
387 
388          /* unlink buffer from list */
389          if (prev)
390             prev->Next = buffer->Next;
391          else
392             XMesaBufferList = buffer->Next;
393 
394          /* mark as delete pending */
395          fb->DeletePending = GL_TRUE;
396 
397          /* Since the X window for the XMesaBuffer is going away, we don't
398           * want to dereference this pointer in the future.
399           */
400          b->frontxrb->drawable = 0;
401 
402          /* Unreference.  If count = zero we'll really delete the buffer */
403          _mesa_reference_framebuffer(&fb, NULL);
404 
405          return;
406       }
407       /* continue search */
408       prev = b;
409    }
410    /* buffer not found in XMesaBufferList */
411    _mesa_problem(NULL,"xmesa_free_buffer() - buffer not found\n");
412 }
413 
414 
415 
416 
417 /**********************************************************************/
418 /*****                   Misc Private Functions                   *****/
419 /**********************************************************************/
420 
421 
422 /**
423  * Setup RGB rendering for a window with a True/DirectColor visual.
424  */
425 static void
setup_truecolor(XMesaVisual v,XMesaBuffer buffer,XMesaColormap cmap)426 setup_truecolor(XMesaVisual v, XMesaBuffer buffer, XMesaColormap cmap)
427 {
428    unsigned long rmask, gmask, bmask;
429    (void) buffer;
430    (void) cmap;
431 
432    /* Compute red multiplier (mask) and bit shift */
433    v->rshift = 0;
434    rmask = GET_REDMASK(v);
435    while ((rmask & 1)==0) {
436       v->rshift++;
437       rmask = rmask >> 1;
438    }
439 
440    /* Compute green multiplier (mask) and bit shift */
441    v->gshift = 0;
442    gmask = GET_GREENMASK(v);
443    while ((gmask & 1)==0) {
444       v->gshift++;
445       gmask = gmask >> 1;
446    }
447 
448    /* Compute blue multiplier (mask) and bit shift */
449    v->bshift = 0;
450    bmask = GET_BLUEMASK(v);
451    while ((bmask & 1)==0) {
452       v->bshift++;
453       bmask = bmask >> 1;
454    }
455 
456    /*
457     * Compute component-to-pixel lookup tables and dithering kernel
458     */
459    {
460       static GLubyte kernel[16] = {
461           0*16,  8*16,  2*16, 10*16,
462          12*16,  4*16, 14*16,  6*16,
463           3*16, 11*16,  1*16,  9*16,
464          15*16,  7*16, 13*16,  5*16,
465       };
466       GLint rBits = util_bitcount(rmask);
467       GLint gBits = util_bitcount(gmask);
468       GLint bBits = util_bitcount(bmask);
469       GLint maxBits;
470       GLuint i;
471 
472       /* convert pixel components in [0,_mask] to RGB values in [0,255] */
473       for (i=0; i<=rmask; i++)
474          v->PixelToR[i] = (unsigned char) ((i * 255) / rmask);
475       for (i=0; i<=gmask; i++)
476          v->PixelToG[i] = (unsigned char) ((i * 255) / gmask);
477       for (i=0; i<=bmask; i++)
478          v->PixelToB[i] = (unsigned char) ((i * 255) / bmask);
479 
480       /* convert RGB values from [0,255] to pixel components */
481 
482       for (i=0;i<256;i++) {
483          GLint r = gamma_adjust(v->RedGamma,   i, 255);
484          GLint g = gamma_adjust(v->GreenGamma, i, 255);
485          GLint b = gamma_adjust(v->BlueGamma,  i, 255);
486          v->RtoPixel[i] = (r >> (8-rBits)) << v->rshift;
487          v->GtoPixel[i] = (g >> (8-gBits)) << v->gshift;
488          v->BtoPixel[i] = (b >> (8-bBits)) << v->bshift;
489       }
490       /* overflow protection */
491       for (i=256;i<512;i++) {
492          v->RtoPixel[i] = v->RtoPixel[255];
493          v->GtoPixel[i] = v->GtoPixel[255];
494          v->BtoPixel[i] = v->BtoPixel[255];
495       }
496 
497       /* setup dithering kernel */
498       maxBits = rBits;
499       if (gBits > maxBits)  maxBits = gBits;
500       if (bBits > maxBits)  maxBits = bBits;
501       for (i=0;i<16;i++) {
502          v->Kernel[i] = kernel[i] >> maxBits;
503       }
504 
505       v->undithered_pf = PF_Truecolor;
506       v->dithered_pf = (GET_VISUAL_DEPTH(v)<24) ? PF_Dither_True : PF_Truecolor;
507    }
508 
509    /*
510     * Now check for TrueColor visuals which we can optimize.
511     */
512    if (   GET_REDMASK(v)  ==0x0000ff
513        && GET_GREENMASK(v)==0x00ff00
514        && GET_BLUEMASK(v) ==0xff0000
515        && CHECK_BYTE_ORDER(v)
516        && v->BitsPerPixel==32
517        && v->RedGamma==1.0 && v->GreenGamma==1.0 && v->BlueGamma==1.0) {
518       /* common 32 bpp config used on SGI, Sun */
519       v->undithered_pf = v->dithered_pf = PF_8A8B8G8R; /* ABGR */
520    }
521    else if (GET_REDMASK(v)  == 0xff0000
522          && GET_GREENMASK(v)== 0x00ff00
523          && GET_BLUEMASK(v) == 0x0000ff
524          && CHECK_BYTE_ORDER(v)
525          && v->RedGamma == 1.0 && v->GreenGamma == 1.0 && v->BlueGamma == 1.0){
526       if (v->BitsPerPixel==32) {
527          /* if 32 bpp, and visual indicates 8 bpp alpha channel */
528          if (GET_VISUAL_DEPTH(v) == 32 && v->mesa_visual.alphaBits == 8)
529             v->undithered_pf = v->dithered_pf = PF_8A8R8G8B; /* ARGB */
530          else
531             v->undithered_pf = v->dithered_pf = PF_8R8G8B; /* xRGB */
532       }
533       else if (v->BitsPerPixel == 24) {
534          v->undithered_pf = v->dithered_pf = PF_8R8G8B24; /* RGB */
535       }
536    }
537    else if (GET_REDMASK(v)  ==0xf800
538        &&   GET_GREENMASK(v)==0x07e0
539        &&   GET_BLUEMASK(v) ==0x001f
540        && CHECK_BYTE_ORDER(v)
541        && v->BitsPerPixel==16
542        && v->RedGamma==1.0 && v->GreenGamma==1.0 && v->BlueGamma==1.0) {
543       /* 5-6-5 RGB */
544       v->undithered_pf = PF_5R6G5B;
545       v->dithered_pf = PF_Dither_5R6G5B;
546    }
547 }
548 
549 
550 /**
551  * When a context is bound for the first time, we can finally finish
552  * initializing the context's visual and buffer information.
553  * \param v  the XMesaVisual to initialize
554  * \param b  the XMesaBuffer to initialize (may be NULL)
555  * \param rgb_flag  TRUE = RGBA mode, FALSE = color index mode
556  * \param window  the window/pixmap we're rendering into
557  * \param cmap  the colormap associated with the window/pixmap
558  * \return GL_TRUE=success, GL_FALSE=failure
559  */
560 static GLboolean
initialize_visual_and_buffer(XMesaVisual v,XMesaBuffer b,XMesaDrawable window,XMesaColormap cmap)561 initialize_visual_and_buffer(XMesaVisual v, XMesaBuffer b,
562                              XMesaDrawable window,
563                              XMesaColormap cmap)
564 {
565    const int xclass = v->visualType;
566 
567 
568    assert(!b || b->xm_visual == v);
569 
570    /* Save true bits/pixel */
571    v->BitsPerPixel = bits_per_pixel(v);
572    assert(v->BitsPerPixel > 0);
573 
574    /* RGB WINDOW:
575     * We support RGB rendering into almost any kind of visual.
576     */
577    if (xclass == GLX_TRUE_COLOR || xclass == GLX_DIRECT_COLOR) {
578       setup_truecolor( v, b, cmap );
579    }
580    else {
581       _mesa_warning(NULL, "XMesa: RGB mode rendering not supported in given visual.\n");
582       return GL_FALSE;
583    }
584 
585    if (getenv("MESA_NO_DITHER")) {
586       v->dithered_pf = v->undithered_pf;
587    }
588 
589 
590    /*
591     * If MESA_INFO env var is set print out some debugging info
592     * which can help Brian figure out what's going on when a user
593     * reports bugs.
594     */
595    if (getenv("MESA_INFO")) {
596       printf("X/Mesa visual = %p\n", (void *) v);
597       printf("X/Mesa dithered pf = %u\n", v->dithered_pf);
598       printf("X/Mesa undithered pf = %u\n", v->undithered_pf);
599       printf("X/Mesa depth = %d\n", GET_VISUAL_DEPTH(v));
600       printf("X/Mesa bits per pixel = %d\n", v->BitsPerPixel);
601    }
602 
603    if (b && window) {
604       /* Do window-specific initializations */
605 
606       /* these should have been set in create_xmesa_buffer */
607       assert(b->frontxrb->drawable == window);
608       assert(b->frontxrb->pixmap == (XMesaPixmap) window);
609 
610       /* Setup for single/double buffering */
611       if (v->mesa_visual.doubleBufferMode) {
612          /* Double buffered */
613          b->shm = check_for_xshm( v->display );
614       }
615 
616       /* X11 graphics contexts */
617       b->gc = XCreateGC( v->display, window, 0, NULL );
618       XMesaSetFunction( v->display, b->gc, GXcopy );
619 
620       /* cleargc - for glClear() */
621       b->cleargc = XCreateGC( v->display, window, 0, NULL );
622       XMesaSetFunction( v->display, b->cleargc, GXcopy );
623 
624       /*
625        * Don't generate Graphics Expose/NoExpose events in swapbuffers().
626        * Patch contributed by Michael Pichler May 15, 1995.
627        */
628       {
629          XGCValues gcvalues;
630          gcvalues.graphics_exposures = False;
631          b->swapgc = XCreateGC(v->display, window,
632                                GCGraphicsExposures, &gcvalues);
633       }
634       XMesaSetFunction( v->display, b->swapgc, GXcopy );
635    }
636 
637    return GL_TRUE;
638 }
639 
640 
641 
642 /*
643  * Convert an RGBA color to a pixel value.
644  */
645 unsigned long
xmesa_color_to_pixel(struct gl_context * ctx,GLubyte r,GLubyte g,GLubyte b,GLubyte a,GLuint pixelFormat)646 xmesa_color_to_pixel(struct gl_context *ctx,
647                      GLubyte r, GLubyte g, GLubyte b, GLubyte a,
648                      GLuint pixelFormat)
649 {
650    XMesaContext xmesa = XMESA_CONTEXT(ctx);
651    switch (pixelFormat) {
652       case PF_Truecolor:
653          {
654             unsigned long p;
655             PACK_TRUECOLOR( p, r, g, b );
656             return p;
657          }
658       case PF_8A8B8G8R:
659          return PACK_8A8B8G8R( r, g, b, a );
660       case PF_8A8R8G8B:
661          return PACK_8A8R8G8B( r, g, b, a );
662       case PF_8R8G8B:
663          FALLTHROUGH;
664       case PF_8R8G8B24:
665          return PACK_8R8G8B( r, g, b );
666       case PF_5R6G5B:
667          return PACK_5R6G5B( r, g, b );
668       case PF_Dither_True:
669          FALLTHROUGH;
670       case PF_Dither_5R6G5B:
671          {
672             unsigned long p;
673             PACK_TRUEDITHER(p, 1, 0, r, g, b);
674             return p;
675          }
676       default:
677          _mesa_problem(ctx, "Bad pixel format in xmesa_color_to_pixel");
678    }
679    return 0;
680 }
681 
682 
683 #define NUM_VISUAL_TYPES   6
684 
685 /**
686  * Convert an X visual type to a GLX visual type.
687  *
688  * \param visualType X visual type (i.e., \c TrueColor, \c StaticGray, etc.)
689  *        to be converted.
690  * \return If \c visualType is a valid X visual type, a GLX visual type will
691  *         be returned.  Otherwise \c GLX_NONE will be returned.
692  *
693  * \note
694  * This code was lifted directly from lib/GL/glx/glcontextmodes.c in the
695  * DRI CVS tree.
696  */
697 static GLint
xmesa_convert_from_x_visual_type(int visualType)698 xmesa_convert_from_x_visual_type( int visualType )
699 {
700     static const int glx_visual_types[ NUM_VISUAL_TYPES ] = {
701 	GLX_STATIC_GRAY,  GLX_GRAY_SCALE,
702 	GLX_STATIC_COLOR, GLX_PSEUDO_COLOR,
703 	GLX_TRUE_COLOR,   GLX_DIRECT_COLOR
704     };
705 
706     return ( (unsigned) visualType < NUM_VISUAL_TYPES )
707 	? glx_visual_types[ visualType ] : GLX_NONE;
708 }
709 
710 
711 /**********************************************************************/
712 /*****                       Public Functions                     *****/
713 /**********************************************************************/
714 
715 
716 /*
717  * Create a new X/Mesa visual.
718  * Input:  display - X11 display
719  *         visinfo - an XVisualInfo pointer
720  *         rgb_flag - GL_TRUE = RGB mode,
721  *                    GL_FALSE = color index mode
722  *         alpha_flag - alpha buffer requested?
723  *         db_flag - GL_TRUE = double-buffered,
724  *                   GL_FALSE = single buffered
725  *         stereo_flag - stereo visual?
726  *         ximage_flag - GL_TRUE = use an XImage for back buffer,
727  *                       GL_FALSE = use an off-screen pixmap for back buffer
728  *         depth_size - requested bits/depth values, or zero
729  *         stencil_size - requested bits/stencil values, or zero
730  *         accum_red_size - requested bits/red accum values, or zero
731  *         accum_green_size - requested bits/green accum values, or zero
732  *         accum_blue_size - requested bits/blue accum values, or zero
733  *         accum_alpha_size - requested bits/alpha accum values, or zero
734  *         num_samples - number of samples/pixel if multisampling, or zero
735  *         level - visual level, usually 0
736  *         visualCaveat - ala the GLX extension, usually GLX_NONE
737  * Return;  a new XMesaVisual or 0 if error.
738  */
739 PUBLIC
XMesaCreateVisual(XMesaDisplay * display,XMesaVisualInfo visinfo,GLboolean rgb_flag,GLboolean alpha_flag,GLboolean db_flag,GLboolean stereo_flag,GLboolean ximage_flag,GLint depth_size,GLint stencil_size,GLint accum_red_size,GLint accum_green_size,GLint accum_blue_size,GLint accum_alpha_size,GLint num_samples,GLint level,GLint visualCaveat)740 XMesaVisual XMesaCreateVisual( XMesaDisplay *display,
741                                XMesaVisualInfo visinfo,
742                                GLboolean rgb_flag,
743                                GLboolean alpha_flag,
744                                GLboolean db_flag,
745                                GLboolean stereo_flag,
746                                GLboolean ximage_flag,
747                                GLint depth_size,
748                                GLint stencil_size,
749                                GLint accum_red_size,
750                                GLint accum_green_size,
751                                GLint accum_blue_size,
752                                GLint accum_alpha_size,
753                                GLint num_samples,
754                                GLint level,
755                                GLint visualCaveat )
756 {
757    char *gamma;
758    XMesaVisual v;
759    GLint red_bits, green_bits, blue_bits, alpha_bits;
760 
761    /* For debugging only */
762    if (getenv("MESA_XSYNC")) {
763       /* This makes debugging X easier.
764        * In your debugger, set a breakpoint on _XError to stop when an
765        * X protocol error is generated.
766        */
767       XSynchronize( display, 1 );
768    }
769 
770    /* Color-index rendering not supported. */
771    if (!rgb_flag)
772       return NULL;
773 
774    v = (XMesaVisual) CALLOC_STRUCT(xmesa_visual);
775    if (!v) {
776       return NULL;
777    }
778 
779    v->display = display;
780 
781    /* Save a copy of the XVisualInfo struct because the user may Xfree()
782     * the struct but we may need some of the information contained in it
783     * at a later time.
784     */
785    v->visinfo = malloc(sizeof(*visinfo));
786    if(!v->visinfo) {
787       free(v);
788       return NULL;
789    }
790    memcpy(v->visinfo, visinfo, sizeof(*visinfo));
791 
792    /* check for MESA_GAMMA environment variable */
793    gamma = getenv("MESA_GAMMA");
794    if (gamma) {
795       v->RedGamma = v->GreenGamma = v->BlueGamma = 0.0;
796       sscanf( gamma, "%f %f %f", &v->RedGamma, &v->GreenGamma, &v->BlueGamma );
797       if (v->RedGamma<=0.0)    v->RedGamma = 1.0;
798       if (v->GreenGamma<=0.0)  v->GreenGamma = v->RedGamma;
799       if (v->BlueGamma<=0.0)   v->BlueGamma = v->RedGamma;
800    }
801    else {
802       v->RedGamma = v->GreenGamma = v->BlueGamma = 1.0;
803    }
804 
805    v->ximage_flag = ximage_flag;
806 
807    v->mesa_visual.redMask = visinfo->red_mask;
808    v->mesa_visual.greenMask = visinfo->green_mask;
809    v->mesa_visual.blueMask = visinfo->blue_mask;
810    v->visualID = visinfo->visualid;
811    v->screen = visinfo->screen;
812 
813 #if !(defined(__cplusplus) || defined(c_plusplus))
814    v->visualType = xmesa_convert_from_x_visual_type(visinfo->class);
815 #else
816    v->visualType = xmesa_convert_from_x_visual_type(visinfo->c_class);
817 #endif
818 
819    if (alpha_flag)
820       v->mesa_visual.alphaBits = 8;
821 
822    (void) initialize_visual_and_buffer( v, NULL, 0, 0 );
823 
824    {
825       const int xclass = v->visualType;
826       if (xclass == GLX_TRUE_COLOR || xclass == GLX_DIRECT_COLOR) {
827          red_bits   = util_bitcount(GET_REDMASK(v));
828          green_bits = util_bitcount(GET_GREENMASK(v));
829          blue_bits  = util_bitcount(GET_BLUEMASK(v));
830       }
831       else {
832          /* this is an approximation */
833          int depth;
834          depth = GET_VISUAL_DEPTH(v);
835          red_bits = depth / 3;
836          depth -= red_bits;
837          green_bits = depth / 2;
838          depth -= green_bits;
839          blue_bits = depth;
840          alpha_bits = 0;
841          assert( red_bits + green_bits + blue_bits == GET_VISUAL_DEPTH(v) );
842       }
843       alpha_bits = v->mesa_visual.alphaBits;
844    }
845 
846    _mesa_initialize_visual(&v->mesa_visual,
847                            db_flag, stereo_flag,
848                            red_bits, green_bits,
849                            blue_bits, alpha_bits,
850                            depth_size,
851                            stencil_size,
852                            accum_red_size, accum_green_size,
853                            accum_blue_size, accum_alpha_size,
854                            0);
855 
856    return v;
857 }
858 
859 
860 PUBLIC
XMesaDestroyVisual(XMesaVisual v)861 void XMesaDestroyVisual( XMesaVisual v )
862 {
863    free(v->visinfo);
864    free(v);
865 }
866 
867 
868 
869 /**
870  * Create a new XMesaContext.
871  * \param v  the XMesaVisual
872  * \param share_list  another XMesaContext with which to share display
873  *                    lists or NULL if no sharing is wanted.
874  * \return an XMesaContext or NULL if error.
875  */
876 PUBLIC
XMesaCreateContext(XMesaVisual v,XMesaContext share_list)877 XMesaContext XMesaCreateContext( XMesaVisual v, XMesaContext share_list )
878 {
879    static GLboolean firstTime = GL_TRUE;
880    XMesaContext c;
881    struct gl_context *mesaCtx;
882    struct dd_function_table functions;
883    TNLcontext *tnl;
884 
885    if (firstTime) {
886       mtx_init(&_xmesa_lock, mtx_plain);
887       firstTime = GL_FALSE;
888    }
889 
890    /* Note: the XMesaContext contains a Mesa struct gl_context struct (inheritance) */
891    c = (XMesaContext) CALLOC_STRUCT(xmesa_context);
892    if (!c)
893       return NULL;
894 
895    mesaCtx = &(c->mesa);
896 
897    /* initialize with default driver functions, then plug in XMesa funcs */
898    _mesa_init_driver_functions(&functions);
899    _tnl_init_driver_draw_function(&functions);
900    xmesa_init_driver_functions(v, &functions);
901    if (!_mesa_initialize_context(mesaCtx, API_OPENGL_COMPAT, &v->mesa_visual,
902                       share_list ? &(share_list->mesa) : (struct gl_context *) NULL,
903                       &functions)) {
904       free(c);
905       return NULL;
906    }
907 
908    /* Enable this to exercise fixed function -> shader translation
909     * with software rendering.
910     */
911    if (0) {
912       mesaCtx->VertexProgram._MaintainTnlProgram = GL_TRUE;
913       mesaCtx->FragmentProgram._MaintainTexEnvProgram = GL_TRUE;
914       _mesa_reset_vertex_processing_mode(mesaCtx);
915    }
916 
917    _mesa_enable_sw_extensions(mesaCtx);
918 
919 #if ENABLE_EXT_timer_query
920     mesaCtx->Extensions.EXT_timer_query = GL_TRUE;
921 #endif
922 
923 
924    /* finish up xmesa context initializations */
925    c->direct = GL_TRUE;
926    c->swapbytes = CHECK_BYTE_ORDER(v) ? GL_FALSE : GL_TRUE;
927    c->xm_visual = v;
928    c->xm_buffer = NULL;   /* set later by XMesaMakeCurrent */
929    c->display = v->display;
930    c->pixelformat = v->dithered_pf;      /* Dithering is enabled by default */
931 
932    /* Initialize the software rasterizer and helper modules.
933     */
934    if (!_swrast_CreateContext( mesaCtx ) ||
935        !_vbo_CreateContext( mesaCtx, false ) ||
936        !_tnl_CreateContext( mesaCtx ) ||
937        !_swsetup_CreateContext( mesaCtx )) {
938       _mesa_free_context_data(&c->mesa, true);
939       free(c);
940       return NULL;
941    }
942 
943    /* tnl setup */
944    tnl = TNL_CONTEXT(mesaCtx);
945    tnl->Driver.RunPipeline = _tnl_run_pipeline;
946    /* swrast setup */
947    xmesa_register_swrast_functions( mesaCtx );
948    _swsetup_Wakeup(mesaCtx);
949 
950    _mesa_meta_init(mesaCtx);
951 
952    _mesa_override_extensions(mesaCtx);
953    _mesa_compute_version(mesaCtx);
954 
955     /* Exec table initialization requires the version to be computed */
956    _mesa_initialize_dispatch_tables(mesaCtx);
957    _mesa_initialize_vbo_vtxfmt(mesaCtx);
958 
959    return c;
960 }
961 
962 
963 
964 PUBLIC
XMesaDestroyContext(XMesaContext c)965 void XMesaDestroyContext( XMesaContext c )
966 {
967    struct gl_context *mesaCtx = &c->mesa;
968 
969    _mesa_meta_free( mesaCtx );
970 
971    _swsetup_DestroyContext( mesaCtx );
972    _swrast_DestroyContext( mesaCtx );
973    _tnl_DestroyContext( mesaCtx );
974    _vbo_DestroyContext( mesaCtx );
975    _mesa_free_context_data(mesaCtx, true);
976    free( c );
977 }
978 
979 
980 
981 /**
982  * Private function for creating an XMesaBuffer which corresponds to an
983  * X window or pixmap.
984  * \param v  the window's XMesaVisual
985  * \param w  the window we're wrapping
986  * \return  new XMesaBuffer or NULL if error
987  */
988 PUBLIC XMesaBuffer
XMesaCreateWindowBuffer(XMesaVisual v,XMesaWindow w)989 XMesaCreateWindowBuffer(XMesaVisual v, XMesaWindow w)
990 {
991    XWindowAttributes attr;
992    XMesaBuffer b;
993    XMesaColormap cmap;
994    int depth;
995 
996    assert(v);
997    assert(w);
998 
999    /* Check that window depth matches visual depth */
1000    XGetWindowAttributes( v->display, w, &attr );
1001    depth = attr.depth;
1002    if (GET_VISUAL_DEPTH(v) != depth) {
1003       _mesa_warning(NULL, "XMesaCreateWindowBuffer: depth mismatch between visual (%d) and window (%d)!\n",
1004                     GET_VISUAL_DEPTH(v), depth);
1005       return NULL;
1006    }
1007 
1008    /* Find colormap */
1009    if (attr.colormap) {
1010       cmap = attr.colormap;
1011    }
1012    else {
1013       _mesa_warning(NULL, "Window %u has no colormap!\n", (unsigned int) w);
1014       /* this is weird, a window w/out a colormap!? */
1015       /* OK, let's just allocate a new one and hope for the best */
1016       cmap = XCreateColormap(v->display, w, attr.visual, AllocNone);
1017    }
1018 
1019    b = create_xmesa_buffer((XMesaDrawable) w, WINDOW, v, cmap);
1020    if (!b)
1021       return NULL;
1022 
1023    if (!initialize_visual_and_buffer( v, b, (XMesaDrawable) w, cmap )) {
1024       xmesa_free_buffer(b);
1025       return NULL;
1026    }
1027 
1028    return b;
1029 }
1030 
1031 
1032 
1033 /**
1034  * Create a new XMesaBuffer from an X pixmap.
1035  *
1036  * \param v    the XMesaVisual
1037  * \param p    the pixmap
1038  * \param cmap the colormap, may be 0 if using a \c GLX_TRUE_COLOR or
1039  *             \c GLX_DIRECT_COLOR visual for the pixmap
1040  * \returns new XMesaBuffer or NULL if error
1041  */
1042 PUBLIC XMesaBuffer
XMesaCreatePixmapBuffer(XMesaVisual v,XMesaPixmap p,XMesaColormap cmap)1043 XMesaCreatePixmapBuffer(XMesaVisual v, XMesaPixmap p, XMesaColormap cmap)
1044 {
1045    XMesaBuffer b;
1046 
1047    assert(v);
1048 
1049    b = create_xmesa_buffer((XMesaDrawable) p, PIXMAP, v, cmap);
1050    if (!b)
1051       return NULL;
1052 
1053    if (!initialize_visual_and_buffer(v, b, (XMesaDrawable) p, cmap)) {
1054       xmesa_free_buffer(b);
1055       return NULL;
1056    }
1057 
1058    return b;
1059 }
1060 
1061 
1062 /**
1063  * For GLX_EXT_texture_from_pixmap
1064  */
1065 XMesaBuffer
XMesaCreatePixmapTextureBuffer(XMesaVisual v,XMesaPixmap p,XMesaColormap cmap,int format,int target,int mipmap)1066 XMesaCreatePixmapTextureBuffer(XMesaVisual v, XMesaPixmap p,
1067                                XMesaColormap cmap,
1068                                int format, int target, int mipmap)
1069 {
1070    GET_CURRENT_CONTEXT(ctx);
1071    XMesaBuffer b;
1072    GLuint width, height;
1073 
1074    assert(v);
1075 
1076    b = create_xmesa_buffer((XMesaDrawable) p, PIXMAP, v, cmap);
1077    if (!b)
1078       return NULL;
1079 
1080    /* get pixmap size, update framebuffer/renderbuffer dims */
1081    xmesa_get_window_size(v->display, b, &width, &height);
1082    _mesa_resize_framebuffer(NULL, &(b->mesa_buffer), width, height);
1083 
1084    if (target == 0) {
1085       /* examine dims */
1086       if (ctx->Extensions.ARB_texture_non_power_of_two) {
1087          target = GLX_TEXTURE_2D_EXT;
1088       }
1089       else if (   util_bitcount(width)  == 1
1090                && util_bitcount(height) == 1) {
1091          /* power of two size */
1092          if (height == 1) {
1093             target = GLX_TEXTURE_1D_EXT;
1094          }
1095          else {
1096             target = GLX_TEXTURE_2D_EXT;
1097          }
1098       }
1099       else if (ctx->Extensions.NV_texture_rectangle) {
1100          target = GLX_TEXTURE_RECTANGLE_EXT;
1101       }
1102       else {
1103          /* non power of two textures not supported */
1104          XMesaDestroyBuffer(b);
1105          return 0;
1106       }
1107    }
1108 
1109    b->TextureTarget = target;
1110    b->TextureFormat = format;
1111    b->TextureMipmap = mipmap;
1112 
1113    if (!initialize_visual_and_buffer(v, b, (XMesaDrawable) p, cmap)) {
1114       xmesa_free_buffer(b);
1115       return NULL;
1116    }
1117 
1118    return b;
1119 }
1120 
1121 
1122 
1123 XMesaBuffer
XMesaCreatePBuffer(XMesaVisual v,XMesaColormap cmap,unsigned int width,unsigned int height)1124 XMesaCreatePBuffer(XMesaVisual v, XMesaColormap cmap,
1125                    unsigned int width, unsigned int height)
1126 {
1127    XMesaWindow root;
1128    XMesaDrawable drawable;  /* X Pixmap Drawable */
1129    XMesaBuffer b;
1130 
1131    /* allocate pixmap for front buffer */
1132    root = RootWindow( v->display, v->visinfo->screen );
1133    drawable = XCreatePixmap(v->display, root, width, height,
1134                             v->visinfo->depth);
1135    if (!drawable)
1136       return NULL;
1137 
1138    b = create_xmesa_buffer(drawable, PBUFFER, v, cmap);
1139    if (!b)
1140       return NULL;
1141 
1142    if (!initialize_visual_and_buffer(v, b, drawable, cmap)) {
1143       xmesa_free_buffer(b);
1144       return NULL;
1145    }
1146 
1147    return b;
1148 }
1149 
1150 
1151 
1152 /*
1153  * Deallocate an XMesaBuffer structure and all related info.
1154  */
1155 PUBLIC void
XMesaDestroyBuffer(XMesaBuffer b)1156 XMesaDestroyBuffer(XMesaBuffer b)
1157 {
1158    xmesa_free_buffer(b);
1159 }
1160 
1161 
1162 /**
1163  * Query the current window size and update the corresponding struct gl_framebuffer
1164  * and all attached renderbuffers.
1165  * Called when:
1166  *  1. the first time a buffer is bound to a context.
1167  *  2. from glViewport to poll for window size changes
1168  *  3. from the XMesaResizeBuffers() API function.
1169  * Note: it's possible (and legal) for xmctx to be NULL.  That can happen
1170  * when resizing a buffer when no rendering context is bound.
1171  */
1172 void
xmesa_check_and_update_buffer_size(XMesaContext xmctx,XMesaBuffer drawBuffer)1173 xmesa_check_and_update_buffer_size(XMesaContext xmctx, XMesaBuffer drawBuffer)
1174 {
1175    GLuint width, height;
1176    xmesa_get_window_size(drawBuffer->display, drawBuffer, &width, &height);
1177    if (drawBuffer->mesa_buffer.Width != width ||
1178        drawBuffer->mesa_buffer.Height != height) {
1179       struct gl_context *ctx = xmctx ? &xmctx->mesa : NULL;
1180       _mesa_resize_framebuffer(ctx, &(drawBuffer->mesa_buffer), width, height);
1181    }
1182 }
1183 
1184 
1185 /*
1186  * Bind buffer b to context c and make c the current rendering context.
1187  */
XMesaMakeCurrent(XMesaContext c,XMesaBuffer b)1188 GLboolean XMesaMakeCurrent( XMesaContext c, XMesaBuffer b )
1189 {
1190    return XMesaMakeCurrent2( c, b, b );
1191 }
1192 
1193 
1194 /*
1195  * Bind buffer b to context c and make c the current rendering context.
1196  */
1197 PUBLIC
XMesaMakeCurrent2(XMesaContext c,XMesaBuffer drawBuffer,XMesaBuffer readBuffer)1198 GLboolean XMesaMakeCurrent2( XMesaContext c, XMesaBuffer drawBuffer,
1199                              XMesaBuffer readBuffer )
1200 {
1201    if (c) {
1202       if (!drawBuffer || !readBuffer)
1203          return GL_FALSE;  /* must specify buffers! */
1204 
1205       if (&(c->mesa) == _mesa_get_current_context()
1206           && c->mesa.DrawBuffer == &drawBuffer->mesa_buffer
1207           && c->mesa.ReadBuffer == &readBuffer->mesa_buffer
1208           && XMESA_BUFFER(c->mesa.DrawBuffer)->wasCurrent) {
1209          /* same context and buffer, do nothing */
1210          return GL_TRUE;
1211       }
1212 
1213       c->xm_buffer = drawBuffer;
1214 
1215       xmesa_check_and_update_buffer_size(c, drawBuffer);
1216       if (readBuffer != drawBuffer)
1217          xmesa_check_and_update_buffer_size(c, readBuffer);
1218 
1219       _mesa_make_current(&(c->mesa),
1220                          &drawBuffer->mesa_buffer,
1221                          &readBuffer->mesa_buffer);
1222 
1223       /*
1224        * Must recompute and set these pixel values because colormap
1225        * can be different for different windows.
1226        */
1227       c->clearpixel = xmesa_color_to_pixel( &c->mesa,
1228 					    c->clearcolor[0],
1229 					    c->clearcolor[1],
1230 					    c->clearcolor[2],
1231 					    c->clearcolor[3],
1232 					    c->xm_visual->undithered_pf);
1233       XMesaSetForeground(c->display, drawBuffer->cleargc, c->clearpixel);
1234 
1235       /* Solution to Stephane Rehel's problem with glXReleaseBuffersMESA(): */
1236       drawBuffer->wasCurrent = GL_TRUE;
1237    }
1238    else {
1239       /* Detach */
1240       _mesa_make_current( NULL, NULL, NULL );
1241    }
1242    return GL_TRUE;
1243 }
1244 
1245 
1246 /*
1247  * Unbind the context c from its buffer.
1248  */
XMesaUnbindContext(XMesaContext c)1249 GLboolean XMesaUnbindContext( XMesaContext c )
1250 {
1251    /* A no-op for XFree86 integration purposes */
1252    return GL_TRUE;
1253 }
1254 
1255 
XMesaGetCurrentContext(void)1256 XMesaContext XMesaGetCurrentContext( void )
1257 {
1258    GET_CURRENT_CONTEXT(ctx);
1259    if (ctx) {
1260       XMesaContext xmesa = XMESA_CONTEXT(ctx);
1261       return xmesa;
1262    }
1263    else {
1264       return 0;
1265    }
1266 }
1267 
1268 
XMesaGetCurrentBuffer(void)1269 XMesaBuffer XMesaGetCurrentBuffer( void )
1270 {
1271    GET_CURRENT_CONTEXT(ctx);
1272    if (ctx) {
1273       XMesaBuffer xmbuf = XMESA_BUFFER(ctx->DrawBuffer);
1274       return xmbuf;
1275    }
1276    else {
1277       return 0;
1278    }
1279 }
1280 
1281 
1282 /* New in Mesa 3.1 */
XMesaGetCurrentReadBuffer(void)1283 XMesaBuffer XMesaGetCurrentReadBuffer( void )
1284 {
1285    GET_CURRENT_CONTEXT(ctx);
1286    if (ctx) {
1287       return XMESA_BUFFER(ctx->ReadBuffer);
1288    }
1289    else {
1290       return 0;
1291    }
1292 }
1293 
1294 
XMesaGetCurrentDisplay(void)1295 Display *XMesaGetCurrentDisplay(void)
1296 {
1297    GET_CURRENT_CONTEXT(ctx);
1298    XMesaContext xmctx = XMESA_CONTEXT(ctx);
1299    return xmctx ? xmctx->display : NULL;
1300 }
1301 
1302 
1303 /**
1304  * Swap buffers notification callback.
1305  *
1306  * \param ctx GL context.
1307  *
1308  * Called by window system just before swapping buffers.
1309  * We have to finish any pending rendering.
1310  */
1311 static void
XMesaNotifySwapBuffers(struct gl_context * ctx)1312 XMesaNotifySwapBuffers(struct gl_context *ctx)
1313 {
1314    if (MESA_VERBOSE & VERBOSE_SWAPBUFFERS)
1315       _mesa_debug(ctx, "SwapBuffers\n");
1316 
1317    FLUSH_VERTICES(ctx, 0, 0);
1318    if (ctx->Driver.Flush) {
1319       ctx->Driver.Flush(ctx, 0);
1320    }
1321 }
1322 
1323 
1324 /*
1325  * Copy the back buffer to the front buffer.  If there's no back buffer
1326  * this is a no-op.
1327  */
1328 PUBLIC
XMesaSwapBuffers(XMesaBuffer b)1329 void XMesaSwapBuffers( XMesaBuffer b )
1330 {
1331    GET_CURRENT_CONTEXT(ctx);
1332 
1333    if (!b->backxrb) {
1334       /* single buffered */
1335       return;
1336    }
1337 
1338    /* If we're swapping the buffer associated with the current context
1339     * we have to flush any pending rendering commands first.
1340     */
1341    if (ctx && ctx->DrawBuffer == &(b->mesa_buffer))
1342       XMesaNotifySwapBuffers(ctx);
1343 
1344    if (b->db_mode) {
1345       if (b->backxrb->ximage) {
1346 	 /* Copy Ximage (back buf) from client memory to server window */
1347 #if defined(USE_XSHM)
1348 	 if (b->shm) {
1349             /*mtx_lock(&_xmesa_lock);*/
1350 	    XShmPutImage( b->xm_visual->display, b->frontxrb->drawable,
1351 			  b->swapgc,
1352 			  b->backxrb->ximage, 0, 0,
1353 			  0, 0, b->mesa_buffer.Width, b->mesa_buffer.Height,
1354                           False );
1355             /*mtx_unlock(&_xmesa_lock);*/
1356 	 }
1357 	 else
1358 #endif
1359          {
1360             /*mtx_lock(&_xmesa_lock);*/
1361             XMesaPutImage( b->xm_visual->display, b->frontxrb->drawable,
1362 			   b->swapgc,
1363 			   b->backxrb->ximage, 0, 0,
1364 			   0, 0, b->mesa_buffer.Width, b->mesa_buffer.Height );
1365             /*mtx_unlock(&_xmesa_lock);*/
1366          }
1367       }
1368       else if (b->backxrb->pixmap) {
1369 	 /* Copy pixmap (back buf) to window (front buf) on server */
1370          /*mtx_lock(&_xmesa_lock);*/
1371 	 XMesaCopyArea( b->xm_visual->display,
1372 			b->backxrb->pixmap,   /* source drawable */
1373 			b->frontxrb->drawable,  /* dest. drawable */
1374 			b->swapgc,
1375 			0, 0, b->mesa_buffer.Width, b->mesa_buffer.Height,
1376 			0, 0                 /* dest region */
1377 		      );
1378          /*mtx_unlock(&_xmesa_lock);*/
1379       }
1380    }
1381    XSync( b->xm_visual->display, False );
1382 }
1383 
1384 
1385 
1386 /*
1387  * Copy sub-region of back buffer to front buffer
1388  */
XMesaCopySubBuffer(XMesaBuffer b,int x,int y,int width,int height)1389 void XMesaCopySubBuffer( XMesaBuffer b, int x, int y, int width, int height )
1390 {
1391    GET_CURRENT_CONTEXT(ctx);
1392 
1393    /* If we're swapping the buffer associated with the current context
1394     * we have to flush any pending rendering commands first.
1395     */
1396    if (ctx && ctx->DrawBuffer == &(b->mesa_buffer))
1397       XMesaNotifySwapBuffers(ctx);
1398 
1399    if (!b->backxrb) {
1400       /* single buffered */
1401       return;
1402    }
1403 
1404    if (b->db_mode) {
1405       int yTop = b->mesa_buffer.Height - y - height;
1406       if (b->backxrb->ximage) {
1407          /* Copy Ximage from host's memory to server's window */
1408 #if defined(USE_XSHM)
1409          if (b->shm) {
1410             /* XXX assuming width and height aren't too large! */
1411             XShmPutImage( b->xm_visual->display, b->frontxrb->drawable,
1412                           b->swapgc,
1413                           b->backxrb->ximage, x, yTop,
1414                           x, yTop, width, height, False );
1415             /* wait for finished event??? */
1416          }
1417          else
1418 #endif
1419          {
1420             /* XXX assuming width and height aren't too large! */
1421             XMesaPutImage( b->xm_visual->display, b->frontxrb->drawable,
1422 			   b->swapgc,
1423 			   b->backxrb->ximage, x, yTop,
1424 			   x, yTop, width, height );
1425          }
1426       }
1427       else {
1428          /* Copy pixmap to window on server */
1429          XMesaCopyArea( b->xm_visual->display,
1430 			b->backxrb->pixmap,           /* source drawable */
1431 			b->frontxrb->drawable,        /* dest. drawable */
1432 			b->swapgc,
1433 			x, yTop, width, height,  /* source region */
1434 			x, yTop                  /* dest region */
1435                       );
1436       }
1437    }
1438 }
1439 
1440 
1441 /*
1442  * Return a pointer to the XMesa backbuffer Pixmap or XImage.  This function
1443  * is a way to get "under the hood" of X/Mesa so one can manipulate the
1444  * back buffer directly.
1445  * Output:  pixmap - pointer to back buffer's Pixmap, or 0
1446  *          ximage - pointer to back buffer's XImage, or NULL
1447  * Return:  GL_TRUE = context is double buffered
1448  *          GL_FALSE = context is single buffered
1449  */
XMesaGetBackBuffer(XMesaBuffer b,XMesaPixmap * pixmap,XMesaImage ** ximage)1450 GLboolean XMesaGetBackBuffer( XMesaBuffer b,
1451                               XMesaPixmap *pixmap,
1452                               XMesaImage **ximage )
1453 {
1454    if (b->db_mode) {
1455       if (pixmap)
1456          *pixmap = b->backxrb->pixmap;
1457       if (ximage)
1458          *ximage = b->backxrb->ximage;
1459       return GL_TRUE;
1460    }
1461    else {
1462       *pixmap = 0;
1463       *ximage = NULL;
1464       return GL_FALSE;
1465    }
1466 }
1467 
1468 
1469 /*
1470  * Return the depth buffer associated with an XMesaBuffer.
1471  * Input:  b - the XMesa buffer handle
1472  * Output:  width, height - size of buffer in pixels
1473  *          bytesPerValue - bytes per depth value (2 or 4)
1474  *          buffer - pointer to depth buffer values
1475  * Return:  GL_TRUE or GL_FALSE to indicate success or failure.
1476  */
XMesaGetDepthBuffer(XMesaBuffer b,GLint * width,GLint * height,GLint * bytesPerValue,void ** buffer)1477 GLboolean XMesaGetDepthBuffer( XMesaBuffer b, GLint *width, GLint *height,
1478                                GLint *bytesPerValue, void **buffer )
1479 {
1480    struct gl_renderbuffer *rb
1481       = b->mesa_buffer.Attachment[BUFFER_DEPTH].Renderbuffer;
1482    struct xmesa_renderbuffer *xrb = xmesa_renderbuffer(rb);
1483 
1484    if (!xrb || !xrb->Base.Buffer) {
1485       *width = 0;
1486       *height = 0;
1487       *bytesPerValue = 0;
1488       *buffer = 0;
1489       return GL_FALSE;
1490    }
1491    else {
1492       *width = b->mesa_buffer.Width;
1493       *height = b->mesa_buffer.Height;
1494       *bytesPerValue = b->mesa_buffer.Visual.depthBits <= 16
1495          ? sizeof(GLushort) : sizeof(GLuint);
1496       *buffer = (void *) xrb->Base.Buffer;
1497       return GL_TRUE;
1498    }
1499 }
1500 
1501 
XMesaFlush(XMesaContext c)1502 void XMesaFlush( XMesaContext c )
1503 {
1504    if (c && c->xm_visual) {
1505       XSync( c->xm_visual->display, False );
1506    }
1507 }
1508 
1509 
1510 
XMesaGetString(XMesaContext c,int name)1511 const char *XMesaGetString( XMesaContext c, int name )
1512 {
1513    (void) c;
1514    if (name==XMESA_VERSION) {
1515       return "5.0";
1516    }
1517    else if (name==XMESA_EXTENSIONS) {
1518       return "";
1519    }
1520    else {
1521       return NULL;
1522    }
1523 }
1524 
1525 
1526 
XMesaFindBuffer(XMesaDisplay * dpy,XMesaDrawable d)1527 XMesaBuffer XMesaFindBuffer( XMesaDisplay *dpy, XMesaDrawable d )
1528 {
1529    XMesaBuffer b;
1530    for (b=XMesaBufferList; b; b=b->Next) {
1531       if (b->frontxrb->drawable == d && b->display == dpy) {
1532          return b;
1533       }
1534    }
1535    return NULL;
1536 }
1537 
1538 
1539 /**
1540  * Free/destroy all XMesaBuffers associated with given display.
1541  */
xmesa_destroy_buffers_on_display(XMesaDisplay * dpy)1542 void xmesa_destroy_buffers_on_display(XMesaDisplay *dpy)
1543 {
1544    XMesaBuffer b, next;
1545    for (b = XMesaBufferList; b; b = next) {
1546       next = b->Next;
1547       if (b->display == dpy) {
1548          xmesa_free_buffer(b);
1549       }
1550    }
1551 }
1552 
1553 
1554 /*
1555  * Look for XMesaBuffers whose X window has been destroyed.
1556  * Deallocate any such XMesaBuffers.
1557  */
XMesaGarbageCollect(XMesaDisplay * dpy)1558 void XMesaGarbageCollect( XMesaDisplay* dpy )
1559 {
1560    XMesaBuffer b, next;
1561    for (b=XMesaBufferList; b; b=next) {
1562       next = b->Next;
1563       if (b->display && b->display == dpy && b->frontxrb->drawable && b->type == WINDOW) {
1564          XSync(b->display, False);
1565          if (!window_exists( b->display, b->frontxrb->drawable )) {
1566             /* found a dead window, free the ancillary info */
1567             XMesaDestroyBuffer( b );
1568          }
1569       }
1570    }
1571 }
1572 
1573 
XMesaDitherColor(XMesaContext xmesa,GLint x,GLint y,GLfloat red,GLfloat green,GLfloat blue,GLfloat alpha)1574 unsigned long XMesaDitherColor( XMesaContext xmesa, GLint x, GLint y,
1575                                 GLfloat red, GLfloat green,
1576                                 GLfloat blue, GLfloat alpha )
1577 {
1578    GLint r = (GLint) (red   * 255.0F);
1579    GLint g = (GLint) (green * 255.0F);
1580    GLint b = (GLint) (blue  * 255.0F);
1581    GLint a = (GLint) (alpha * 255.0F);
1582 
1583    switch (xmesa->pixelformat) {
1584       case PF_Truecolor:
1585          {
1586             unsigned long p;
1587             PACK_TRUECOLOR( p, r, g, b );
1588             return p;
1589          }
1590       case PF_8A8B8G8R:
1591          return PACK_8A8B8G8R( r, g, b, a );
1592       case PF_8A8R8G8B:
1593          return PACK_8A8R8G8B( r, g, b, a );
1594       case PF_8R8G8B:
1595          return PACK_8R8G8B( r, g, b );
1596       case PF_5R6G5B:
1597          return PACK_5R6G5B( r, g, b );
1598       case PF_Dither_5R6G5B:
1599          FALLTHROUGH;
1600       case PF_Dither_True:
1601          {
1602             unsigned long p;
1603             PACK_TRUEDITHER(p, x, y, r, g, b);
1604             return p;
1605          }
1606       default:
1607          _mesa_problem(NULL, "Bad pixel format in XMesaDitherColor");
1608    }
1609    return 0;
1610 }
1611 
1612 
1613 /*
1614  * This is typically called when the window size changes and we need
1615  * to reallocate the buffer's back/depth/stencil/accum buffers.
1616  */
1617 PUBLIC void
XMesaResizeBuffers(XMesaBuffer b)1618 XMesaResizeBuffers( XMesaBuffer b )
1619 {
1620    GET_CURRENT_CONTEXT(ctx);
1621    XMesaContext xmctx = XMESA_CONTEXT(ctx);
1622    if (!xmctx)
1623       return;
1624    xmesa_check_and_update_buffer_size(xmctx, b);
1625 }
1626 
1627 
1628 static GLint
xbuffer_to_renderbuffer(int buffer)1629 xbuffer_to_renderbuffer(int buffer)
1630 {
1631    assert(MAX_AUX_BUFFERS <= 4);
1632 
1633    switch (buffer) {
1634    case GLX_FRONT_LEFT_EXT:
1635       return BUFFER_FRONT_LEFT;
1636    case GLX_FRONT_RIGHT_EXT:
1637       return BUFFER_FRONT_RIGHT;
1638    case GLX_BACK_LEFT_EXT:
1639       return BUFFER_BACK_LEFT;
1640    case GLX_BACK_RIGHT_EXT:
1641       return BUFFER_BACK_RIGHT;
1642    case GLX_AUX0_EXT:
1643    case GLX_AUX1_EXT:
1644    case GLX_AUX2_EXT:
1645    case GLX_AUX3_EXT:
1646    case GLX_AUX4_EXT:
1647    case GLX_AUX5_EXT:
1648    case GLX_AUX6_EXT:
1649    case GLX_AUX7_EXT:
1650    case GLX_AUX8_EXT:
1651    case GLX_AUX9_EXT:
1652    default:
1653       /* BadValue error */
1654       return -1;
1655    }
1656 }
1657 
1658 
1659 PUBLIC void
XMesaBindTexImage(XMesaDisplay * dpy,XMesaBuffer drawable,int buffer,const int * attrib_list)1660 XMesaBindTexImage(XMesaDisplay *dpy, XMesaBuffer drawable, int buffer,
1661                   const int *attrib_list)
1662 {
1663 #if 0
1664    GET_CURRENT_CONTEXT(ctx);
1665    const GLuint unit = ctx->Texture.CurrentUnit;
1666    struct gl_texture_unit *texUnit = &ctx->Texture.Unit[unit];
1667    struct gl_texture_object *texObj;
1668 #endif
1669    struct gl_renderbuffer *rb;
1670    struct xmesa_renderbuffer *xrb;
1671    GLint b;
1672    XMesaImage *img = NULL;
1673    GLboolean freeImg = GL_FALSE;
1674 
1675    b = xbuffer_to_renderbuffer(buffer);
1676    if (b < 0)
1677       return;
1678 
1679    if (drawable->TextureFormat == GLX_TEXTURE_FORMAT_NONE_EXT)
1680       return; /* BadMatch error */
1681 
1682    rb = drawable->mesa_buffer.Attachment[b].Renderbuffer;
1683    if (!rb) {
1684       /* invalid buffer */
1685       return;
1686    }
1687    xrb = xmesa_renderbuffer(rb);
1688 
1689 #if 0
1690    switch (drawable->TextureTarget) {
1691    case GLX_TEXTURE_1D_EXT:
1692       texObj = texUnit->CurrentTex[TEXTURE_1D_INDEX];
1693       break;
1694    case GLX_TEXTURE_2D_EXT:
1695       texObj = texUnit->CurrentTex[TEXTURE_2D_INDEX];
1696       break;
1697    case GLX_TEXTURE_RECTANGLE_EXT:
1698       texObj = texUnit->CurrentTex[TEXTURE_RECT_INDEX];
1699       break;
1700    default:
1701       return; /* BadMatch error */
1702    }
1703 #endif
1704 
1705    /*
1706     * The following is a quick and simple way to implement
1707     * BindTexImage.  The better way is to write some new FetchTexel()
1708     * functions which would extract texels from XImages.  We'd still
1709     * need to use GetImage when texturing from a Pixmap (front buffer)
1710     * but texturing from a back buffer (XImage) would avoid an image
1711     * copy.
1712     */
1713 
1714    /* get XImage */
1715    if (xrb->pixmap) {
1716       img = XMesaGetImage(dpy, xrb->pixmap, 0, 0, rb->Width, rb->Height, ~0L,
1717 			  ZPixmap);
1718       freeImg = GL_TRUE;
1719    }
1720    else if (xrb->ximage) {
1721       img = xrb->ximage;
1722    }
1723 
1724    /* store the XImage as a new texture image */
1725    if (img) {
1726       GLenum format, type, intFormat;
1727       if (img->bits_per_pixel == 32) {
1728          format = GL_BGRA;
1729          type = GL_UNSIGNED_BYTE;
1730          intFormat = GL_RGBA;
1731       }
1732       else if (img->bits_per_pixel == 24) {
1733          format = GL_BGR;
1734          type = GL_UNSIGNED_BYTE;
1735          intFormat = GL_RGB;
1736       }
1737       else if (img->bits_per_pixel == 16) {
1738          format = GL_BGR;
1739          type = GL_UNSIGNED_SHORT_5_6_5;
1740          intFormat = GL_RGB;
1741       }
1742       else {
1743          _mesa_problem(NULL, "Unexpected XImage format in XMesaBindTexImage");
1744          return;
1745       }
1746       if (drawable->TextureFormat == GLX_TEXTURE_FORMAT_RGBA_EXT) {
1747          intFormat = GL_RGBA;
1748       }
1749       else if (drawable->TextureFormat == GLX_TEXTURE_FORMAT_RGB_EXT) {
1750          intFormat = GL_RGB;
1751       }
1752 
1753       _mesa_TexImage2D(GL_TEXTURE_2D, 0, intFormat, rb->Width, rb->Height, 0,
1754                        format, type, img->data);
1755 
1756       if (freeImg) {
1757 	 XMesaDestroyImage(img);
1758       }
1759    }
1760 }
1761 
1762 
1763 
1764 PUBLIC void
XMesaReleaseTexImage(XMesaDisplay * dpy,XMesaBuffer drawable,int buffer)1765 XMesaReleaseTexImage(XMesaDisplay *dpy, XMesaBuffer drawable, int buffer)
1766 {
1767    const GLint b = xbuffer_to_renderbuffer(buffer);
1768    if (b < 0)
1769       return;
1770 
1771    /* no-op for now */
1772 }
1773 
1774