1 /*
2  * Mesa 3-D graphics library
3  * Version:  7.1
4  *
5  * Copyright (C) 1999-2007  Brian Paul   All Rights Reserved.
6  *
7  * Permission is hereby granted, free of charge, to any person obtaining a
8  * copy of this software and associated documentation files (the "Software"),
9  * to deal in the Software without restriction, including without limitation
10  * the rights to use, copy, modify, merge, publish, distribute, sublicense,
11  * and/or sell copies of the Software, and to permit persons to whom the
12  * Software is furnished to do so, subject to the following conditions:
13  *
14  * The above copyright notice and this permission notice shall be included
15  * in all copies or substantial portions of the Software.
16  *
17  * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
18  * OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
19  * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.  IN NO EVENT SHALL
20  * BRIAN PAUL BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN
21  * AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
22  * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
23  */
24 
25 /**
26  * \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  *
39  * Byte swapping:  If the Mesa host and the X display use a different
40  * byte order then there's some trickiness to be aware of when using
41  * XImages.  The byte ordering used for the XImage is that of the X
42  * display, not the Mesa host.
43  * The color-to-pixel encoding for True/DirectColor must be done
44  * according to the display's visual red_mask, green_mask, and blue_mask.
45  * If XPutPixel is used to put a pixel into an XImage then XPutPixel will
46  * do byte swapping if needed.  If one wants to directly "poke" the pixel
47  * into the XImage's buffer then the pixel must be byte swapped first.
48  *
49  */
50 
51 #ifdef __CYGWIN__
52 #undef WIN32
53 #undef __WIN32__
54 #endif
55 
56 #include "xm_api.h"
57 #include "xm_st.h"
58 
59 #include "pipe/p_context.h"
60 #include "pipe/p_defines.h"
61 #include "pipe/p_screen.h"
62 #include "pipe/p_state.h"
63 
64 #include "util/u_atomic.h"
65 #include "util/u_inlines.h"
66 
67 #include "xm_public.h"
68 #include <GL/glx.h>
69 
70 
71 /* Driver interface routines, set up by xlib backend on library
72  * _init().  These are global in the same way that function names are
73  * global.
74  */
75 static struct xm_driver driver;
76 static struct st_api *stapi;
77 
78 /* Default strict invalidate to false.  This means we will not call
79  * XGetGeometry after every swapbuffers, which allows swapbuffers to
80  * remain asynchronous.  For apps running at 100fps with synchronous
81  * swapping, a 10% boost is typical.  For gears, I see closer to 20%
82  * speedup.
83  *
84  * Note that the work of copying data on swapbuffers doesn't disappear
85  * - this change just allows the X server to execute the PutImage
86  * asynchronously without us effectively blocked until its completion.
87  *
88  * This speeds up even llvmpipe's threaded rasterization as the
89  * swapbuffers operation was a large part of the serial component of
90  * an llvmpipe frame.
91  *
92  * The downside of this is correctness - applications which don't call
93  * glViewport on window resizes will get incorrect rendering.  A
94  * better solution would be to have per-frame but asynchronous
95  * invalidation.  Xcb almost looks as if it could provide this, but
96  * the API doesn't seem to quite be there.
97  */
98 boolean xmesa_strict_invalidate = FALSE;
99 
xmesa_set_driver(const struct xm_driver * templ)100 void xmesa_set_driver( const struct xm_driver *templ )
101 {
102    driver = *templ;
103    stapi = driver.create_st_api();
104 
105    xmesa_strict_invalidate =
106       debug_get_bool_option("XMESA_STRICT_INVALIDATE", FALSE);
107 }
108 
109 
110 /*
111  * XXX replace this with a linked list, or better yet, try to attach the
112  * gallium/mesa extra bits to the X Display object with XAddExtension().
113  */
114 #define MAX_DISPLAYS 10
115 static struct xmesa_display Displays[MAX_DISPLAYS];
116 static int NumDisplays = 0;
117 
118 static int
xmesa_get_param(struct st_manager * smapi,enum st_manager_param param)119 xmesa_get_param(struct st_manager *smapi,
120                 enum st_manager_param param)
121 {
122    switch(param) {
123    case ST_MANAGER_BROKEN_INVALIDATE:
124       return !xmesa_strict_invalidate;
125    default:
126       return 0;
127    }
128 }
129 
130 static XMesaDisplay
xmesa_init_display(Display * display)131 xmesa_init_display( Display *display )
132 {
133    pipe_static_mutex(init_mutex);
134    XMesaDisplay xmdpy;
135    int i;
136 
137    pipe_mutex_lock(init_mutex);
138 
139    /* Look for XMesaDisplay which corresponds to 'display' */
140    for (i = 0; i < NumDisplays; i++) {
141       if (Displays[i].display == display) {
142          /* Found it */
143          pipe_mutex_unlock(init_mutex);
144          return &Displays[i];
145       }
146    }
147 
148    /* Create new XMesaDisplay */
149 
150    assert(NumDisplays < MAX_DISPLAYS);
151    xmdpy = &Displays[NumDisplays];
152    NumDisplays++;
153 
154    if (!xmdpy->display && display) {
155       xmdpy->display = display;
156       xmdpy->screen = driver.create_pipe_screen(display);
157       xmdpy->smapi = CALLOC_STRUCT(st_manager);
158       if (xmdpy->smapi) {
159          xmdpy->smapi->screen = xmdpy->screen;
160          xmdpy->smapi->get_param = xmesa_get_param;
161       }
162 
163       if (xmdpy->screen && xmdpy->smapi) {
164          pipe_mutex_init(xmdpy->mutex);
165       }
166       else {
167          if (xmdpy->screen) {
168             xmdpy->screen->destroy(xmdpy->screen);
169             xmdpy->screen = NULL;
170          }
171          if (xmdpy->smapi) {
172             FREE(xmdpy->smapi);
173             xmdpy->smapi = NULL;
174          }
175 
176          xmdpy->display = NULL;
177       }
178    }
179    if (!xmdpy->display || xmdpy->display != display)
180       xmdpy = NULL;
181 
182    pipe_mutex_unlock(init_mutex);
183 
184    return xmdpy;
185 }
186 
187 /**********************************************************************/
188 /*****                     X Utility Functions                    *****/
189 /**********************************************************************/
190 
191 
192 /**
193  * Return the host's byte order as LSBFirst or MSBFirst ala X.
194  */
host_byte_order(void)195 static int host_byte_order( void )
196 {
197    int i = 1;
198    char *cptr = (char *) &i;
199    return (*cptr==1) ? LSBFirst : MSBFirst;
200 }
201 
202 
203 
204 
205 /**
206  * Return the true number of bits per pixel for XImages.
207  * For example, if we request a 24-bit deep visual we may actually need/get
208  * 32bpp XImages.  This function returns the appropriate bpp.
209  * Input:  dpy - the X display
210  *         visinfo - desribes the visual to be used for XImages
211  * Return:  true number of bits per pixel for XImages
212  */
213 static int
bits_per_pixel(XMesaVisual xmv)214 bits_per_pixel( XMesaVisual xmv )
215 {
216    Display *dpy = xmv->display;
217    XVisualInfo * visinfo = xmv->visinfo;
218    XImage *img;
219    int bitsPerPixel;
220    /* Create a temporary XImage */
221    img = XCreateImage( dpy, visinfo->visual, visinfo->depth,
222 		       ZPixmap, 0,           /*format, offset*/
223 		       (char*) MALLOC(8),    /*data*/
224 		       1, 1,                 /*width, height*/
225 		       32,                   /*bitmap_pad*/
226 		       0                     /*bytes_per_line*/
227                      );
228    assert(img);
229    /* grab the bits/pixel value */
230    bitsPerPixel = img->bits_per_pixel;
231    /* free the XImage */
232    free( img->data );
233    img->data = NULL;
234    XDestroyImage( img );
235    return bitsPerPixel;
236 }
237 
238 
239 
240 /*
241  * Determine if a given X window ID is valid (window exists).
242  * Do this by calling XGetWindowAttributes() for the window and
243  * checking if we catch an X error.
244  * Input:  dpy - the display
245  *         win - the window to check for existance
246  * Return:  GL_TRUE - window exists
247  *          GL_FALSE - window doesn't exist
248  */
249 static GLboolean WindowExistsFlag;
250 
window_exists_err_handler(Display * dpy,XErrorEvent * xerr)251 static int window_exists_err_handler( Display* dpy, XErrorEvent* xerr )
252 {
253    (void) dpy;
254    if (xerr->error_code == BadWindow) {
255       WindowExistsFlag = GL_FALSE;
256    }
257    return 0;
258 }
259 
window_exists(Display * dpy,Window win)260 static GLboolean window_exists( Display *dpy, Window win )
261 {
262    XWindowAttributes wa;
263    int (*old_handler)( Display*, XErrorEvent* );
264    WindowExistsFlag = GL_TRUE;
265    old_handler = XSetErrorHandler(window_exists_err_handler);
266    XGetWindowAttributes( dpy, win, &wa ); /* dummy request */
267    XSetErrorHandler(old_handler);
268    return WindowExistsFlag;
269 }
270 
271 static Status
get_drawable_size(Display * dpy,Drawable d,uint * width,uint * height)272 get_drawable_size( Display *dpy, Drawable d, uint *width, uint *height )
273 {
274    Window root;
275    Status stat;
276    int xpos, ypos;
277    unsigned int w, h, bw, depth;
278    stat = XGetGeometry(dpy, d, &root, &xpos, &ypos, &w, &h, &bw, &depth);
279    *width = w;
280    *height = h;
281    return stat;
282 }
283 
284 
285 /**
286  * Return the size of the window (or pixmap) that corresponds to the
287  * given XMesaBuffer.
288  * \param width  returns width in pixels
289  * \param height  returns height in pixels
290  */
291 void
xmesa_get_window_size(Display * dpy,XMesaBuffer b,GLuint * width,GLuint * height)292 xmesa_get_window_size(Display *dpy, XMesaBuffer b,
293                       GLuint *width, GLuint *height)
294 {
295    XMesaDisplay xmdpy = xmesa_init_display(dpy);
296    Status stat;
297 
298    pipe_mutex_lock(xmdpy->mutex);
299    stat = get_drawable_size(dpy, b->ws.drawable, width, height);
300    pipe_mutex_unlock(xmdpy->mutex);
301 
302    if (!stat) {
303       /* probably querying a window that's recently been destroyed */
304       _mesa_warning(NULL, "XGetGeometry failed!\n");
305       *width = *height = 1;
306    }
307 }
308 
309 #define GET_REDMASK(__v)        __v->mesa_visual.redMask
310 #define GET_GREENMASK(__v)      __v->mesa_visual.greenMask
311 #define GET_BLUEMASK(__v)       __v->mesa_visual.blueMask
312 
313 
314 /**
315  * Choose the pixel format for the given visual.
316  * This will tell the gallium driver how to pack pixel data into
317  * drawing surfaces.
318  */
319 static GLuint
choose_pixel_format(XMesaVisual v)320 choose_pixel_format(XMesaVisual v)
321 {
322    boolean native_byte_order = (host_byte_order() ==
323                                 ImageByteOrder(v->display));
324 
325    if (   GET_REDMASK(v)   == 0x0000ff
326        && GET_GREENMASK(v) == 0x00ff00
327        && GET_BLUEMASK(v)  == 0xff0000
328        && v->BitsPerPixel == 32) {
329       if (native_byte_order) {
330          /* no byteswapping needed */
331          return PIPE_FORMAT_R8G8B8A8_UNORM;
332       }
333       else {
334          return PIPE_FORMAT_A8B8G8R8_UNORM;
335       }
336    }
337    else if (   GET_REDMASK(v)   == 0xff0000
338             && GET_GREENMASK(v) == 0x00ff00
339             && GET_BLUEMASK(v)  == 0x0000ff
340             && v->BitsPerPixel == 32) {
341       if (native_byte_order) {
342          /* no byteswapping needed */
343          return PIPE_FORMAT_B8G8R8A8_UNORM;
344       }
345       else {
346          return PIPE_FORMAT_A8R8G8B8_UNORM;
347       }
348    }
349    else if (   GET_REDMASK(v)   == 0x0000ff00
350             && GET_GREENMASK(v) == 0x00ff0000
351             && GET_BLUEMASK(v)  == 0xff000000
352             && v->BitsPerPixel == 32) {
353       if (native_byte_order) {
354          /* no byteswapping needed */
355          return PIPE_FORMAT_A8R8G8B8_UNORM;
356       }
357       else {
358          return PIPE_FORMAT_B8G8R8A8_UNORM;
359       }
360    }
361    else if (   GET_REDMASK(v)   == 0xf800
362             && GET_GREENMASK(v) == 0x07e0
363             && GET_BLUEMASK(v)  == 0x001f
364             && native_byte_order
365             && v->BitsPerPixel == 16) {
366       /* 5-6-5 RGB */
367       return PIPE_FORMAT_B5G6R5_UNORM;
368    }
369 
370    return PIPE_FORMAT_NONE;
371 }
372 
373 
374 /**
375  * Choose a depth/stencil format that satisfies the given depth and
376  * stencil sizes.
377  */
378 static enum pipe_format
choose_depth_stencil_format(XMesaDisplay xmdpy,int depth,int stencil)379 choose_depth_stencil_format(XMesaDisplay xmdpy, int depth, int stencil)
380 {
381    const enum pipe_texture_target target = PIPE_TEXTURE_2D;
382    const unsigned tex_usage = PIPE_BIND_DEPTH_STENCIL;
383    const unsigned sample_count = 0;
384    enum pipe_format formats[8], fmt;
385    int count, i;
386 
387    count = 0;
388 
389    if (depth <= 16 && stencil == 0) {
390       formats[count++] = PIPE_FORMAT_Z16_UNORM;
391    }
392    if (depth <= 24 && stencil == 0) {
393       formats[count++] = PIPE_FORMAT_X8Z24_UNORM;
394       formats[count++] = PIPE_FORMAT_Z24X8_UNORM;
395    }
396    if (depth <= 24 && stencil <= 8) {
397       formats[count++] = PIPE_FORMAT_S8_UINT_Z24_UNORM;
398       formats[count++] = PIPE_FORMAT_Z24_UNORM_S8_UINT;
399    }
400    if (depth <= 32 && stencil == 0) {
401       formats[count++] = PIPE_FORMAT_Z32_UNORM;
402    }
403 
404    fmt = PIPE_FORMAT_NONE;
405    for (i = 0; i < count; i++) {
406       if (xmdpy->screen->is_format_supported(xmdpy->screen, formats[i],
407                                              target, sample_count,
408                                              tex_usage)) {
409          fmt = formats[i];
410          break;
411       }
412    }
413 
414    return fmt;
415 }
416 
417 
418 
419 /**********************************************************************/
420 /*****                Linked list of XMesaBuffers                 *****/
421 /**********************************************************************/
422 
423 static XMesaBuffer XMesaBufferList = NULL;
424 
425 
426 /**
427  * Allocate a new XMesaBuffer object which corresponds to the given drawable.
428  * Note that XMesaBuffer is derived from struct gl_framebuffer.
429  * The new XMesaBuffer will not have any size (Width=Height=0).
430  *
431  * \param d  the corresponding X drawable (window or pixmap)
432  * \param type  either WINDOW, PIXMAP or PBUFFER, describing d
433  * \param vis  the buffer's visual
434  * \param cmap  the window's colormap, if known.
435  * \return new XMesaBuffer or NULL if any problem
436  */
437 static XMesaBuffer
create_xmesa_buffer(Drawable d,BufferType type,XMesaVisual vis,Colormap cmap)438 create_xmesa_buffer(Drawable d, BufferType type,
439                     XMesaVisual vis, Colormap cmap)
440 {
441    XMesaDisplay xmdpy = xmesa_init_display(vis->display);
442    XMesaBuffer b;
443    uint width, height;
444 
445    ASSERT(type == WINDOW || type == PIXMAP || type == PBUFFER);
446 
447    if (!xmdpy)
448       return NULL;
449 
450    b = (XMesaBuffer) CALLOC_STRUCT(xmesa_buffer);
451    if (!b)
452       return NULL;
453 
454    b->ws.drawable = d;
455    b->ws.visual = vis->visinfo->visual;
456    b->ws.depth = vis->visinfo->depth;
457 
458    b->xm_visual = vis;
459    b->type = type;
460    b->cmap = cmap;
461 
462    get_drawable_size(vis->display, d, &width, &height);
463 
464    /*
465     * Create framebuffer, but we'll plug in our own renderbuffers below.
466     */
467    b->stfb = xmesa_create_st_framebuffer(xmdpy, b);
468 
469    /* GLX_EXT_texture_from_pixmap */
470    b->TextureTarget = 0;
471    b->TextureFormat = GLX_TEXTURE_FORMAT_NONE_EXT;
472    b->TextureMipmap = 0;
473 
474    /* insert buffer into linked list */
475    b->Next = XMesaBufferList;
476    XMesaBufferList = b;
477 
478    return b;
479 }
480 
481 
482 /**
483  * Find an XMesaBuffer by matching X display and colormap but NOT matching
484  * the notThis buffer.
485  */
486 XMesaBuffer
xmesa_find_buffer(Display * dpy,Colormap cmap,XMesaBuffer notThis)487 xmesa_find_buffer(Display *dpy, Colormap cmap, XMesaBuffer notThis)
488 {
489    XMesaBuffer b;
490    for (b = XMesaBufferList; b; b = b->Next) {
491       if (b->xm_visual->display == dpy &&
492           b->cmap == cmap &&
493           b != notThis) {
494          return b;
495       }
496    }
497    return NULL;
498 }
499 
500 
501 /**
502  * Remove buffer from linked list, delete if no longer referenced.
503  */
504 static void
xmesa_free_buffer(XMesaBuffer buffer)505 xmesa_free_buffer(XMesaBuffer buffer)
506 {
507    XMesaBuffer prev = NULL, b;
508 
509    for (b = XMesaBufferList; b; b = b->Next) {
510       if (b == buffer) {
511          /* unlink buffer from list */
512          if (prev)
513             prev->Next = buffer->Next;
514          else
515             XMesaBufferList = buffer->Next;
516 
517          /* Since the X window for the XMesaBuffer is going away, we don't
518           * want to dereference this pointer in the future.
519           */
520          b->ws.drawable = 0;
521 
522          /* XXX we should move the buffer to a delete-pending list and destroy
523           * the buffer until it is no longer current.
524           */
525          xmesa_destroy_st_framebuffer(buffer->stfb);
526 
527          free(buffer);
528 
529          return;
530       }
531       /* continue search */
532       prev = b;
533    }
534    /* buffer not found in XMesaBufferList */
535    _mesa_problem(NULL,"xmesa_free_buffer() - buffer not found\n");
536 }
537 
538 
539 
540 /**********************************************************************/
541 /*****                   Misc Private Functions                   *****/
542 /**********************************************************************/
543 
544 
545 /**
546  * When a context is bound for the first time, we can finally finish
547  * initializing the context's visual and buffer information.
548  * \param v  the XMesaVisual to initialize
549  * \param b  the XMesaBuffer to initialize (may be NULL)
550  * \param rgb_flag  TRUE = RGBA mode, FALSE = color index mode
551  * \param window  the window/pixmap we're rendering into
552  * \param cmap  the colormap associated with the window/pixmap
553  * \return GL_TRUE=success, GL_FALSE=failure
554  */
555 static GLboolean
initialize_visual_and_buffer(XMesaVisual v,XMesaBuffer b,GLboolean rgb_flag,Drawable window,Colormap cmap)556 initialize_visual_and_buffer(XMesaVisual v, XMesaBuffer b,
557                              GLboolean rgb_flag, Drawable window,
558                              Colormap cmap)
559 {
560    ASSERT(!b || b->xm_visual == v);
561 
562    /* Save true bits/pixel */
563    v->BitsPerPixel = bits_per_pixel(v);
564    assert(v->BitsPerPixel > 0);
565 
566    if (rgb_flag == GL_FALSE) {
567       /* COLOR-INDEXED WINDOW: not supported*/
568       return GL_FALSE;
569    }
570    else {
571       /* RGB WINDOW:
572        * We support RGB rendering into almost any kind of visual.
573        */
574       const int xclass = v->visualType;
575       if (xclass != GLX_TRUE_COLOR && xclass == !GLX_DIRECT_COLOR) {
576 	 _mesa_warning(NULL,
577             "XMesa: RGB mode rendering not supported in given visual.\n");
578 	 return GL_FALSE;
579       }
580       v->mesa_visual.indexBits = 0;
581 
582       if (v->BitsPerPixel == 32) {
583          /* We use XImages for all front/back buffers.  If an X Window or
584           * X Pixmap is 32bpp, there's no guarantee that the alpha channel
585           * will be preserved.  For XImages we're in luck.
586           */
587          v->mesa_visual.alphaBits = 8;
588       }
589    }
590 
591    /*
592     * If MESA_INFO env var is set print out some debugging info
593     * which can help Brian figure out what's going on when a user
594     * reports bugs.
595     */
596    if (_mesa_getenv("MESA_INFO")) {
597       printf("X/Mesa visual = %p\n", (void *) v);
598       printf("X/Mesa level = %d\n", v->mesa_visual.level);
599       printf("X/Mesa depth = %d\n", v->visinfo->depth);
600       printf("X/Mesa bits per pixel = %d\n", v->BitsPerPixel);
601    }
602 
603    return GL_TRUE;
604 }
605 
606 
607 
608 #define NUM_VISUAL_TYPES   6
609 
610 /**
611  * Convert an X visual type to a GLX visual type.
612  *
613  * \param visualType X visual type (i.e., \c TrueColor, \c StaticGray, etc.)
614  *        to be converted.
615  * \return If \c visualType is a valid X visual type, a GLX visual type will
616  *         be returned.  Otherwise \c GLX_NONE will be returned.
617  *
618  * \note
619  * This code was lifted directly from lib/GL/glx/glcontextmodes.c in the
620  * DRI CVS tree.
621  */
622 static GLint
xmesa_convert_from_x_visual_type(int visualType)623 xmesa_convert_from_x_visual_type( int visualType )
624 {
625     static const int glx_visual_types[ NUM_VISUAL_TYPES ] = {
626 	GLX_STATIC_GRAY,  GLX_GRAY_SCALE,
627 	GLX_STATIC_COLOR, GLX_PSEUDO_COLOR,
628 	GLX_TRUE_COLOR,   GLX_DIRECT_COLOR
629     };
630 
631     return ( (unsigned) visualType < NUM_VISUAL_TYPES )
632 	? glx_visual_types[ visualType ] : GLX_NONE;
633 }
634 
635 
636 /**********************************************************************/
637 /*****                       Public Functions                     *****/
638 /**********************************************************************/
639 
640 
641 /*
642  * Create a new X/Mesa visual.
643  * Input:  display - X11 display
644  *         visinfo - an XVisualInfo pointer
645  *         rgb_flag - GL_TRUE = RGB mode,
646  *                    GL_FALSE = color index mode
647  *         alpha_flag - alpha buffer requested?
648  *         db_flag - GL_TRUE = double-buffered,
649  *                   GL_FALSE = single buffered
650  *         stereo_flag - stereo visual?
651  *         ximage_flag - GL_TRUE = use an XImage for back buffer,
652  *                       GL_FALSE = use an off-screen pixmap for back buffer
653  *         depth_size - requested bits/depth values, or zero
654  *         stencil_size - requested bits/stencil values, or zero
655  *         accum_red_size - requested bits/red accum values, or zero
656  *         accum_green_size - requested bits/green accum values, or zero
657  *         accum_blue_size - requested bits/blue accum values, or zero
658  *         accum_alpha_size - requested bits/alpha accum values, or zero
659  *         num_samples - number of samples/pixel if multisampling, or zero
660  *         level - visual level, usually 0
661  *         visualCaveat - ala the GLX extension, usually GLX_NONE
662  * Return;  a new XMesaVisual or 0 if error.
663  */
664 PUBLIC
XMesaCreateVisual(Display * display,XVisualInfo * 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)665 XMesaVisual XMesaCreateVisual( Display *display,
666                                XVisualInfo * visinfo,
667                                GLboolean rgb_flag,
668                                GLboolean alpha_flag,
669                                GLboolean db_flag,
670                                GLboolean stereo_flag,
671                                GLboolean ximage_flag,
672                                GLint depth_size,
673                                GLint stencil_size,
674                                GLint accum_red_size,
675                                GLint accum_green_size,
676                                GLint accum_blue_size,
677                                GLint accum_alpha_size,
678                                GLint num_samples,
679                                GLint level,
680                                GLint visualCaveat )
681 {
682    XMesaDisplay xmdpy = xmesa_init_display(display);
683    XMesaVisual v;
684    GLint red_bits, green_bits, blue_bits, alpha_bits;
685 
686    if (!xmdpy)
687       return NULL;
688 
689    /* For debugging only */
690    if (_mesa_getenv("MESA_XSYNC")) {
691       /* This makes debugging X easier.
692        * In your debugger, set a breakpoint on _XError to stop when an
693        * X protocol error is generated.
694        */
695       XSynchronize( display, 1 );
696    }
697 
698    v = (XMesaVisual) CALLOC_STRUCT(xmesa_visual);
699    if (!v) {
700       return NULL;
701    }
702 
703    v->display = display;
704 
705    /* Save a copy of the XVisualInfo struct because the user may Xfree()
706     * the struct but we may need some of the information contained in it
707     * at a later time.
708     */
709    v->visinfo = (XVisualInfo *) MALLOC(sizeof(*visinfo));
710    if (!v->visinfo) {
711       free(v);
712       return NULL;
713    }
714    memcpy(v->visinfo, visinfo, sizeof(*visinfo));
715 
716    v->ximage_flag = ximage_flag;
717 
718    v->mesa_visual.redMask = visinfo->red_mask;
719    v->mesa_visual.greenMask = visinfo->green_mask;
720    v->mesa_visual.blueMask = visinfo->blue_mask;
721    v->visualID = visinfo->visualid;
722    v->screen = visinfo->screen;
723 
724 #if !(defined(__cplusplus) || defined(c_plusplus))
725    v->visualType = xmesa_convert_from_x_visual_type(visinfo->class);
726 #else
727    v->visualType = xmesa_convert_from_x_visual_type(visinfo->c_class);
728 #endif
729 
730    v->mesa_visual.visualRating = visualCaveat;
731 
732    if (alpha_flag)
733       v->mesa_visual.alphaBits = 8;
734 
735    (void) initialize_visual_and_buffer( v, NULL, rgb_flag, 0, 0 );
736 
737    {
738       const int xclass = v->visualType;
739       if (xclass == GLX_TRUE_COLOR || xclass == GLX_DIRECT_COLOR) {
740          red_bits   = _mesa_bitcount(GET_REDMASK(v));
741          green_bits = _mesa_bitcount(GET_GREENMASK(v));
742          blue_bits  = _mesa_bitcount(GET_BLUEMASK(v));
743       }
744       else {
745          /* this is an approximation */
746          int depth;
747          depth = v->visinfo->depth;
748          red_bits = depth / 3;
749          depth -= red_bits;
750          green_bits = depth / 2;
751          depth -= green_bits;
752          blue_bits = depth;
753          alpha_bits = 0;
754          assert( red_bits + green_bits + blue_bits == v->visinfo->depth );
755       }
756       alpha_bits = v->mesa_visual.alphaBits;
757    }
758 
759    /* initialize visual */
760    {
761       struct gl_config *vis = &v->mesa_visual;
762 
763       vis->rgbMode          = GL_TRUE;
764       vis->doubleBufferMode = db_flag;
765       vis->stereoMode       = stereo_flag;
766 
767       vis->redBits          = red_bits;
768       vis->greenBits        = green_bits;
769       vis->blueBits         = blue_bits;
770       vis->alphaBits        = alpha_bits;
771       vis->rgbBits          = red_bits + green_bits + blue_bits;
772 
773       vis->indexBits      = 0;
774       vis->depthBits      = depth_size;
775       vis->stencilBits    = stencil_size;
776 
777       vis->accumRedBits   = accum_red_size;
778       vis->accumGreenBits = accum_green_size;
779       vis->accumBlueBits  = accum_blue_size;
780       vis->accumAlphaBits = accum_alpha_size;
781 
782       vis->haveAccumBuffer   = accum_red_size > 0;
783       vis->haveDepthBuffer   = depth_size > 0;
784       vis->haveStencilBuffer = stencil_size > 0;
785 
786       vis->numAuxBuffers = 0;
787       vis->level = 0;
788       vis->sampleBuffers = 0;
789       vis->samples = 0;
790    }
791 
792    v->stvis.buffer_mask = ST_ATTACHMENT_FRONT_LEFT_MASK;
793    if (db_flag)
794       v->stvis.buffer_mask |= ST_ATTACHMENT_BACK_LEFT_MASK;
795    if (stereo_flag) {
796       v->stvis.buffer_mask |= ST_ATTACHMENT_FRONT_RIGHT_MASK;
797       if (db_flag)
798          v->stvis.buffer_mask |= ST_ATTACHMENT_BACK_RIGHT_MASK;
799    }
800 
801    v->stvis.color_format = choose_pixel_format(v);
802    if (v->stvis.color_format == PIPE_FORMAT_NONE) {
803       FREE(v->visinfo);
804       FREE(v);
805       return NULL;
806    }
807 
808    v->stvis.depth_stencil_format =
809       choose_depth_stencil_format(xmdpy, depth_size, stencil_size);
810 
811    v->stvis.accum_format = (accum_red_size +
812          accum_green_size + accum_blue_size + accum_alpha_size) ?
813       PIPE_FORMAT_R16G16B16A16_SNORM : PIPE_FORMAT_NONE;
814 
815    v->stvis.samples = num_samples;
816    v->stvis.render_buffer = ST_ATTACHMENT_INVALID;
817 
818    /* XXX minor hack */
819    v->mesa_visual.level = level;
820    return v;
821 }
822 
823 
824 PUBLIC
XMesaDestroyVisual(XMesaVisual v)825 void XMesaDestroyVisual( XMesaVisual v )
826 {
827    free(v->visinfo);
828    free(v);
829 }
830 
831 
832 /**
833  * Return the informative name.
834  */
835 const char *
xmesa_get_name(void)836 xmesa_get_name(void)
837 {
838    return stapi->name;
839 }
840 
841 
842 /**
843  * Do per-display initializations.
844  */
845 void
xmesa_init(Display * display)846 xmesa_init( Display *display )
847 {
848    xmesa_init_display(display);
849 }
850 
851 
852 /**
853  * Create a new XMesaContext.
854  * \param v  the XMesaVisual
855  * \param share_list  another XMesaContext with which to share display
856  *                    lists or NULL if no sharing is wanted.
857  * \return an XMesaContext or NULL if error.
858  */
859 PUBLIC
XMesaCreateContext(XMesaVisual v,XMesaContext share_list,GLuint major,GLuint minor,GLuint profileMask,GLuint contextFlags)860 XMesaContext XMesaCreateContext( XMesaVisual v, XMesaContext share_list,
861                                  GLuint major, GLuint minor,
862                                  GLuint profileMask, GLuint contextFlags)
863 {
864    XMesaDisplay xmdpy = xmesa_init_display(v->display);
865    struct st_context_attribs attribs;
866    enum st_context_error ctx_err = 0;
867    XMesaContext c;
868 
869    if (!xmdpy)
870       return NULL;
871 
872    /* Note: the XMesaContext contains a Mesa struct gl_context struct (inheritance) */
873    c = (XMesaContext) CALLOC_STRUCT(xmesa_context);
874    if (!c)
875       return NULL;
876 
877    c->xm_visual = v;
878    c->xm_buffer = NULL;   /* set later by XMesaMakeCurrent */
879    c->xm_read_buffer = NULL;
880 
881    memset(&attribs, 0, sizeof(attribs));
882    attribs.visual = v->stvis;
883    attribs.major = major;
884    attribs.minor = minor;
885    if (contextFlags & GLX_CONTEXT_FORWARD_COMPATIBLE_BIT_ARB)
886       attribs.flags |= ST_CONTEXT_FLAG_FORWARD_COMPATIBLE;
887    if (contextFlags & GLX_CONTEXT_DEBUG_BIT_ARB)
888       attribs.flags |= ST_CONTEXT_FLAG_DEBUG;
889    if (contextFlags & GLX_CONTEXT_ROBUST_ACCESS_BIT_ARB)
890       attribs.flags |= ST_CONTEXT_FLAG_ROBUST_ACCESS;
891 
892    /* There are no profiles before OpenGL 3.2.  The
893     * GLX_ARB_create_context_profile spec says:
894     *
895     *     "If the requested OpenGL version is less than 3.2,
896     *     GLX_CONTEXT_PROFILE_MASK_ARB is ignored and the functionality of the
897     *     context is determined solely by the requested version."
898     *
899     * The spec also says:
900     *
901     *     "The default value for GLX_CONTEXT_PROFILE_MASK_ARB is
902     *     GLX_CONTEXT_CORE_PROFILE_BIT_ARB."
903     */
904    attribs.profile = ST_PROFILE_DEFAULT;
905    if ((major > 3 || (major == 3 && minor >= 2))
906        && ((profileMask & GLX_CONTEXT_COMPATIBILITY_PROFILE_BIT_ARB) == 0))
907       attribs.profile = ST_PROFILE_OPENGL_CORE;
908 
909    c->st = stapi->create_context(stapi, xmdpy->smapi, &attribs,
910          &ctx_err, (share_list) ? share_list->st : NULL);
911    if (c->st == NULL)
912       goto fail;
913 
914    c->st->st_manager_private = (void *) c;
915 
916    return c;
917 
918 fail:
919    if (c->st)
920       c->st->destroy(c->st);
921 
922    free(c);
923    return NULL;
924 }
925 
926 
927 
928 PUBLIC
XMesaDestroyContext(XMesaContext c)929 void XMesaDestroyContext( XMesaContext c )
930 {
931    c->st->destroy(c->st);
932 
933    /* FIXME: We should destroy the screen here, but if we do so, surfaces may
934     * outlive it, causing segfaults
935    struct pipe_screen *screen = c->st->pipe->screen;
936    screen->destroy(screen);
937    */
938 
939    free(c);
940 }
941 
942 
943 
944 /**
945  * Private function for creating an XMesaBuffer which corresponds to an
946  * X window or pixmap.
947  * \param v  the window's XMesaVisual
948  * \param w  the window we're wrapping
949  * \return  new XMesaBuffer or NULL if error
950  */
951 PUBLIC XMesaBuffer
XMesaCreateWindowBuffer(XMesaVisual v,Window w)952 XMesaCreateWindowBuffer(XMesaVisual v, Window w)
953 {
954    XWindowAttributes attr;
955    XMesaBuffer b;
956    Colormap cmap;
957    int depth;
958 
959    assert(v);
960    assert(w);
961 
962    /* Check that window depth matches visual depth */
963    XGetWindowAttributes( v->display, w, &attr );
964    depth = attr.depth;
965    if (v->visinfo->depth != depth) {
966       _mesa_warning(NULL, "XMesaCreateWindowBuffer: depth mismatch between visual (%d) and window (%d)!\n",
967                     v->visinfo->depth, depth);
968       return NULL;
969    }
970 
971    /* Find colormap */
972    if (attr.colormap) {
973       cmap = attr.colormap;
974    }
975    else {
976       _mesa_warning(NULL, "Window %u has no colormap!\n", (unsigned int) w);
977       /* this is weird, a window w/out a colormap!? */
978       /* OK, let's just allocate a new one and hope for the best */
979       cmap = XCreateColormap(v->display, w, attr.visual, AllocNone);
980    }
981 
982    b = create_xmesa_buffer((Drawable) w, WINDOW, v, cmap);
983    if (!b)
984       return NULL;
985 
986    if (!initialize_visual_and_buffer( v, b, v->mesa_visual.rgbMode,
987                                       (Drawable) w, cmap )) {
988       xmesa_free_buffer(b);
989       return NULL;
990    }
991 
992    return b;
993 }
994 
995 
996 
997 /**
998  * Create a new XMesaBuffer from an X pixmap.
999  *
1000  * \param v    the XMesaVisual
1001  * \param p    the pixmap
1002  * \param cmap the colormap, may be 0 if using a \c GLX_TRUE_COLOR or
1003  *             \c GLX_DIRECT_COLOR visual for the pixmap
1004  * \returns new XMesaBuffer or NULL if error
1005  */
1006 PUBLIC XMesaBuffer
XMesaCreatePixmapBuffer(XMesaVisual v,Pixmap p,Colormap cmap)1007 XMesaCreatePixmapBuffer(XMesaVisual v, Pixmap p, Colormap cmap)
1008 {
1009    XMesaBuffer b;
1010 
1011    assert(v);
1012 
1013    b = create_xmesa_buffer((Drawable) p, PIXMAP, v, cmap);
1014    if (!b)
1015       return NULL;
1016 
1017    if (!initialize_visual_and_buffer(v, b, v->mesa_visual.rgbMode,
1018 				     (Drawable) p, cmap)) {
1019       xmesa_free_buffer(b);
1020       return NULL;
1021    }
1022 
1023    return b;
1024 }
1025 
1026 
1027 /**
1028  * For GLX_EXT_texture_from_pixmap
1029  */
1030 XMesaBuffer
XMesaCreatePixmapTextureBuffer(XMesaVisual v,Pixmap p,Colormap cmap,int format,int target,int mipmap)1031 XMesaCreatePixmapTextureBuffer(XMesaVisual v, Pixmap p,
1032                                Colormap cmap,
1033                                int format, int target, int mipmap)
1034 {
1035    GET_CURRENT_CONTEXT(ctx);
1036    XMesaBuffer b;
1037 
1038    assert(v);
1039 
1040    b = create_xmesa_buffer((Drawable) p, PIXMAP, v, cmap);
1041    if (!b)
1042       return NULL;
1043 
1044    /* get pixmap size */
1045    xmesa_get_window_size(v->display, b, &b->width, &b->height);
1046 
1047    if (target == 0) {
1048       /* examine dims */
1049       if (ctx->Extensions.ARB_texture_non_power_of_two) {
1050          target = GLX_TEXTURE_2D_EXT;
1051       }
1052       else if (   _mesa_bitcount(b->width)  == 1
1053                && _mesa_bitcount(b->height) == 1) {
1054          /* power of two size */
1055          if (b->height == 1) {
1056             target = GLX_TEXTURE_1D_EXT;
1057          }
1058          else {
1059             target = GLX_TEXTURE_2D_EXT;
1060          }
1061       }
1062       else if (ctx->Extensions.NV_texture_rectangle) {
1063          target = GLX_TEXTURE_RECTANGLE_EXT;
1064       }
1065       else {
1066          /* non power of two textures not supported */
1067          XMesaDestroyBuffer(b);
1068          return 0;
1069       }
1070    }
1071 
1072    b->TextureTarget = target;
1073    b->TextureFormat = format;
1074    b->TextureMipmap = mipmap;
1075 
1076    if (!initialize_visual_and_buffer(v, b, v->mesa_visual.rgbMode,
1077 				     (Drawable) p, cmap)) {
1078       xmesa_free_buffer(b);
1079       return NULL;
1080    }
1081 
1082    return b;
1083 }
1084 
1085 
1086 
1087 XMesaBuffer
XMesaCreatePBuffer(XMesaVisual v,Colormap cmap,unsigned int width,unsigned int height)1088 XMesaCreatePBuffer(XMesaVisual v, Colormap cmap,
1089                    unsigned int width, unsigned int height)
1090 {
1091    Window root;
1092    Drawable drawable;  /* X Pixmap Drawable */
1093    XMesaBuffer b;
1094 
1095    /* allocate pixmap for front buffer */
1096    root = RootWindow( v->display, v->visinfo->screen );
1097    drawable = XCreatePixmap(v->display, root, width, height,
1098                             v->visinfo->depth);
1099    if (!drawable)
1100       return NULL;
1101 
1102    b = create_xmesa_buffer(drawable, PBUFFER, v, cmap);
1103    if (!b)
1104       return NULL;
1105 
1106    if (!initialize_visual_and_buffer(v, b, v->mesa_visual.rgbMode,
1107 				     drawable, cmap)) {
1108       xmesa_free_buffer(b);
1109       return NULL;
1110    }
1111 
1112    return b;
1113 }
1114 
1115 
1116 
1117 /*
1118  * Deallocate an XMesaBuffer structure and all related info.
1119  */
1120 PUBLIC void
XMesaDestroyBuffer(XMesaBuffer b)1121 XMesaDestroyBuffer(XMesaBuffer b)
1122 {
1123    xmesa_free_buffer(b);
1124 }
1125 
1126 
1127 /**
1128  * Notify the binding context to validate the buffer.
1129  */
1130 void
xmesa_notify_invalid_buffer(XMesaBuffer b)1131 xmesa_notify_invalid_buffer(XMesaBuffer b)
1132 {
1133    p_atomic_inc(&b->stfb->stamp);
1134 }
1135 
1136 
1137 /**
1138  * Query the current drawable size and notify the binding context.
1139  */
1140 void
xmesa_check_buffer_size(XMesaBuffer b)1141 xmesa_check_buffer_size(XMesaBuffer b)
1142 {
1143    GLuint old_width, old_height;
1144 
1145    if (b->type == PBUFFER)
1146       return;
1147 
1148    old_width = b->width;
1149    old_height = b->height;
1150 
1151    xmesa_get_window_size(b->xm_visual->display, b, &b->width, &b->height);
1152 
1153    if (b->width != old_width || b->height != old_height)
1154       xmesa_notify_invalid_buffer(b);
1155 }
1156 
1157 
1158 /*
1159  * Bind buffer b to context c and make c the current rendering context.
1160  */
1161 PUBLIC
XMesaMakeCurrent2(XMesaContext c,XMesaBuffer drawBuffer,XMesaBuffer readBuffer)1162 GLboolean XMesaMakeCurrent2( XMesaContext c, XMesaBuffer drawBuffer,
1163                              XMesaBuffer readBuffer )
1164 {
1165    XMesaContext old_ctx = XMesaGetCurrentContext();
1166 
1167    if (old_ctx && old_ctx != c) {
1168       XMesaFlush(old_ctx);
1169       old_ctx->xm_buffer = NULL;
1170       old_ctx->xm_read_buffer = NULL;
1171    }
1172 
1173    if (c) {
1174       if (!drawBuffer || !readBuffer)
1175          return GL_FALSE;  /* must specify buffers! */
1176 
1177       if (c == old_ctx &&
1178 	  c->xm_buffer == drawBuffer &&
1179 	  c->xm_read_buffer == readBuffer)
1180 	 return GL_TRUE;
1181 
1182       xmesa_check_buffer_size(drawBuffer);
1183       if (readBuffer != drawBuffer)
1184          xmesa_check_buffer_size(readBuffer);
1185 
1186       c->xm_buffer = drawBuffer;
1187       c->xm_read_buffer = readBuffer;
1188 
1189       stapi->make_current(stapi, c->st, drawBuffer->stfb, readBuffer->stfb);
1190 
1191       /* Solution to Stephane Rehel's problem with glXReleaseBuffersMESA(): */
1192       drawBuffer->wasCurrent = GL_TRUE;
1193    }
1194    else {
1195       /* Detach */
1196       stapi->make_current(stapi, NULL, NULL, NULL);
1197 
1198    }
1199    return GL_TRUE;
1200 }
1201 
1202 
1203 /*
1204  * Unbind the context c from its buffer.
1205  */
XMesaUnbindContext(XMesaContext c)1206 GLboolean XMesaUnbindContext( XMesaContext c )
1207 {
1208    /* A no-op for XFree86 integration purposes */
1209    return GL_TRUE;
1210 }
1211 
1212 
XMesaGetCurrentContext(void)1213 XMesaContext XMesaGetCurrentContext( void )
1214 {
1215    struct st_context_iface *st = stapi->get_current(stapi);
1216    return (XMesaContext) (st) ? st->st_manager_private : NULL;
1217 }
1218 
1219 
1220 
1221 /**
1222  * Swap front and back color buffers and have winsys display front buffer.
1223  * If there's no front color buffer no swap actually occurs.
1224  */
1225 PUBLIC
XMesaSwapBuffers(XMesaBuffer b)1226 void XMesaSwapBuffers( XMesaBuffer b )
1227 {
1228    XMesaContext xmctx = XMesaGetCurrentContext();
1229 
1230    if (xmctx && xmctx->xm_buffer == b) {
1231       xmctx->st->flush( xmctx->st, ST_FLUSH_FRONT, NULL);
1232    }
1233 
1234    xmesa_swap_st_framebuffer(b->stfb);
1235 }
1236 
1237 
1238 
1239 /*
1240  * Copy sub-region of back buffer to front buffer
1241  */
XMesaCopySubBuffer(XMesaBuffer b,int x,int y,int width,int height)1242 void XMesaCopySubBuffer( XMesaBuffer b, int x, int y, int width, int height )
1243 {
1244    xmesa_copy_st_framebuffer(b->stfb,
1245          ST_ATTACHMENT_BACK_LEFT, ST_ATTACHMENT_FRONT_LEFT,
1246          x, y, width, height);
1247 }
1248 
1249 
1250 
XMesaFlush(XMesaContext c)1251 void XMesaFlush( XMesaContext c )
1252 {
1253    if (c && c->xm_visual->display) {
1254       XMesaDisplay xmdpy = xmesa_init_display(c->xm_visual->display);
1255       struct pipe_fence_handle *fence = NULL;
1256 
1257       c->st->flush(c->st, ST_FLUSH_FRONT, &fence);
1258       if (fence) {
1259          xmdpy->screen->fence_finish(xmdpy->screen, fence,
1260                                      PIPE_TIMEOUT_INFINITE);
1261          xmdpy->screen->fence_reference(xmdpy->screen, &fence, NULL);
1262       }
1263       XFlush( c->xm_visual->display );
1264    }
1265 }
1266 
1267 
1268 
1269 
1270 
XMesaFindBuffer(Display * dpy,Drawable d)1271 XMesaBuffer XMesaFindBuffer( Display *dpy, Drawable d )
1272 {
1273    XMesaBuffer b;
1274    for (b = XMesaBufferList; b; b = b->Next) {
1275       if (b->ws.drawable == d && b->xm_visual->display == dpy) {
1276          return b;
1277       }
1278    }
1279    return NULL;
1280 }
1281 
1282 
1283 /**
1284  * Free/destroy all XMesaBuffers associated with given display.
1285  */
xmesa_destroy_buffers_on_display(Display * dpy)1286 void xmesa_destroy_buffers_on_display(Display *dpy)
1287 {
1288    XMesaBuffer b, next;
1289    for (b = XMesaBufferList; b; b = next) {
1290       next = b->Next;
1291       if (b->xm_visual->display == dpy) {
1292          xmesa_free_buffer(b);
1293          /* delete head of list? */
1294          if (XMesaBufferList == b) {
1295             XMesaBufferList = next;
1296          }
1297       }
1298    }
1299 }
1300 
1301 
1302 /*
1303  * Look for XMesaBuffers whose X window has been destroyed.
1304  * Deallocate any such XMesaBuffers.
1305  */
XMesaGarbageCollect(void)1306 void XMesaGarbageCollect( void )
1307 {
1308    XMesaBuffer b, next;
1309    for (b=XMesaBufferList; b; b=next) {
1310       next = b->Next;
1311       if (b->xm_visual &&
1312           b->xm_visual->display &&
1313           b->ws.drawable &&
1314           b->type == WINDOW) {
1315          XSync(b->xm_visual->display, False);
1316          if (!window_exists( b->xm_visual->display, b->ws.drawable )) {
1317             /* found a dead window, free the ancillary info */
1318             XMesaDestroyBuffer( b );
1319          }
1320       }
1321    }
1322 }
1323 
1324 
xmesa_attachment_type(int glx_attachment)1325 static enum st_attachment_type xmesa_attachment_type(int glx_attachment)
1326 {
1327    switch(glx_attachment) {
1328       case GLX_FRONT_LEFT_EXT:
1329          return ST_ATTACHMENT_FRONT_LEFT;
1330       case GLX_FRONT_RIGHT_EXT:
1331          return ST_ATTACHMENT_FRONT_RIGHT;
1332       case GLX_BACK_LEFT_EXT:
1333          return ST_ATTACHMENT_BACK_LEFT;
1334       case GLX_BACK_RIGHT_EXT:
1335          return ST_ATTACHMENT_BACK_RIGHT;
1336       default:
1337          assert(0);
1338          return ST_ATTACHMENT_FRONT_LEFT;
1339    }
1340 }
1341 
1342 
1343 PUBLIC void
XMesaBindTexImage(Display * dpy,XMesaBuffer drawable,int buffer,const int * attrib_list)1344 XMesaBindTexImage(Display *dpy, XMesaBuffer drawable, int buffer,
1345                   const int *attrib_list)
1346 {
1347    struct st_context_iface *st = stapi->get_current(stapi);
1348    struct st_framebuffer_iface* stfbi = drawable->stfb;
1349    struct pipe_resource *res;
1350    int x, y, w, h;
1351    enum st_attachment_type st_attachment = xmesa_attachment_type(buffer);
1352 
1353    x = 0;
1354    y = 0;
1355    w = drawable->width;
1356    h = drawable->height;
1357 
1358    /* We need to validate our attachments before using them,
1359     * in case the texture doesn't exist yet. */
1360    xmesa_st_framebuffer_validate_textures(stfbi, w, h, 1 << st_attachment);
1361    res = xmesa_get_attachment(stfbi, st_attachment);
1362 
1363    if (res) {
1364       struct pipe_context* pipe = xmesa_get_context(stfbi);
1365       enum pipe_format internal_format = res->format;
1366       struct pipe_transfer *tex_xfer;
1367       char *map;
1368       int line, ximage_stride;
1369       XImage *img;
1370 
1371       internal_format = choose_pixel_format(drawable->xm_visual);
1372 
1373       tex_xfer = pipe_get_transfer(pipe, res,
1374                                    0, 0,    /* level, layer */
1375                                    PIPE_TRANSFER_WRITE,
1376                                    x, y,
1377                                    w, h);
1378       if (!tex_xfer)
1379          return;
1380 
1381       /* Grab the XImage that we want to turn into a texture. */
1382       img = XGetImage(dpy,
1383                       drawable->ws.drawable,
1384                       x, y,
1385                       w, h,
1386                       AllPlanes,
1387                       ZPixmap);
1388 
1389       if (!img) {
1390          pipe_transfer_destroy(pipe, tex_xfer);
1391          return;
1392       }
1393 
1394       map = pipe_transfer_map(pipe, tex_xfer);
1395 
1396       if (!map) {
1397          pipe_transfer_destroy(pipe, tex_xfer);
1398          return;
1399       }
1400 
1401       /* The pipe transfer has a pitch rounded up to the nearest 64 pixels.
1402          We assume 32 bit pixels. */
1403       ximage_stride = w * 4;
1404 
1405       for (line = 0; line < h; line++)
1406          memcpy(&map[line * tex_xfer->stride],
1407                 &img->data[line * ximage_stride],
1408                 ximage_stride);
1409 
1410       pipe_transfer_unmap(pipe, tex_xfer);
1411 
1412       pipe_transfer_destroy(pipe, tex_xfer);
1413 
1414       st->teximage(st,
1415                    ST_TEXTURE_2D,
1416                    0,    /* level */
1417                    internal_format,
1418                    res,
1419                    FALSE /* no mipmap */);
1420 
1421    }
1422 }
1423 
1424 
1425 
1426 PUBLIC void
XMesaReleaseTexImage(Display * dpy,XMesaBuffer drawable,int buffer)1427 XMesaReleaseTexImage(Display *dpy, XMesaBuffer drawable, int buffer)
1428 {
1429 }
1430 
1431 
1432 void
XMesaCopyContext(XMesaContext src,XMesaContext dst,unsigned long mask)1433 XMesaCopyContext(XMesaContext src, XMesaContext dst, unsigned long mask)
1434 {
1435    if (dst->st->copy)
1436       dst->st->copy(dst->st, src->st, mask);
1437 }
1438