xm_api.c revision 685bb6941681f89f71a9169594d87c8e314b94d0
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 "main/context.h"
60#include "pipe/p_defines.h"
61#include "pipe/p_screen.h"
62#include "pipe/p_context.h"
63
64#include "xm_public.h"
65#include <GL/glx.h>
66
67
68/* Driver interface routines, set up by xlib backend on library
69 * _init().  These are global in the same way that function names are
70 * global.
71 */
72static struct xm_driver driver;
73static struct st_api *stapi;
74
75void xmesa_set_driver( const struct xm_driver *templ )
76{
77   driver = *templ;
78   stapi = driver.create_st_api();
79}
80
81
82/*
83 * XXX replace this with a linked list, or better yet, try to attach the
84 * gallium/mesa extra bits to the X Display object with XAddExtension().
85 */
86#define MAX_DISPLAYS 10
87static struct xmesa_display Displays[MAX_DISPLAYS];
88static int NumDisplays = 0;
89
90
91static XMesaDisplay
92xmesa_init_display( Display *display )
93{
94   pipe_static_mutex(init_mutex);
95   XMesaDisplay xmdpy;
96   int i;
97
98   pipe_mutex_lock(init_mutex);
99
100   /* Look for XMesaDisplay which corresponds to 'display' */
101   for (i = 0; i < NumDisplays; i++) {
102      if (Displays[i].display == display) {
103         /* Found it */
104         pipe_mutex_unlock(init_mutex);
105         return &Displays[i];
106      }
107   }
108
109   /* Create new XMesaDisplay */
110
111   assert(NumDisplays < MAX_DISPLAYS);
112   xmdpy = &Displays[NumDisplays];
113   NumDisplays++;
114
115   if (!xmdpy->display && display) {
116      xmdpy->display = display;
117      xmdpy->screen = driver.create_pipe_screen(display);
118      xmdpy->smapi = CALLOC_STRUCT(st_manager);
119      if (xmdpy->smapi)
120         xmdpy->smapi->screen = xmdpy->screen;
121
122      if (xmdpy->screen && xmdpy->smapi) {
123         pipe_mutex_init(xmdpy->mutex);
124      }
125      else {
126         if (xmdpy->screen) {
127            xmdpy->screen->destroy(xmdpy->screen);
128            xmdpy->screen = NULL;
129         }
130         if (xmdpy->smapi) {
131            FREE(xmdpy->smapi);
132            xmdpy->smapi = NULL;
133         }
134
135         xmdpy->display = NULL;
136      }
137   }
138   if (!xmdpy->display || xmdpy->display != display)
139      xmdpy = NULL;
140
141   pipe_mutex_unlock(init_mutex);
142
143   return xmdpy;
144}
145
146/**********************************************************************/
147/*****                     X Utility Functions                    *****/
148/**********************************************************************/
149
150
151/**
152 * Return the host's byte order as LSBFirst or MSBFirst ala X.
153 */
154static int host_byte_order( void )
155{
156   int i = 1;
157   char *cptr = (char *) &i;
158   return (*cptr==1) ? LSBFirst : MSBFirst;
159}
160
161
162
163
164/**
165 * Return the true number of bits per pixel for XImages.
166 * For example, if we request a 24-bit deep visual we may actually need/get
167 * 32bpp XImages.  This function returns the appropriate bpp.
168 * Input:  dpy - the X display
169 *         visinfo - desribes the visual to be used for XImages
170 * Return:  true number of bits per pixel for XImages
171 */
172static int
173bits_per_pixel( XMesaVisual xmv )
174{
175   Display *dpy = xmv->display;
176   XVisualInfo * visinfo = xmv->visinfo;
177   XImage *img;
178   int bitsPerPixel;
179   /* Create a temporary XImage */
180   img = XCreateImage( dpy, visinfo->visual, visinfo->depth,
181		       ZPixmap, 0,           /*format, offset*/
182		       (char*) MALLOC(8),    /*data*/
183		       1, 1,                 /*width, height*/
184		       32,                   /*bitmap_pad*/
185		       0                     /*bytes_per_line*/
186                     );
187   assert(img);
188   /* grab the bits/pixel value */
189   bitsPerPixel = img->bits_per_pixel;
190   /* free the XImage */
191   free( img->data );
192   img->data = NULL;
193   XDestroyImage( img );
194   return bitsPerPixel;
195}
196
197
198
199/*
200 * Determine if a given X window ID is valid (window exists).
201 * Do this by calling XGetWindowAttributes() for the window and
202 * checking if we catch an X error.
203 * Input:  dpy - the display
204 *         win - the window to check for existance
205 * Return:  GL_TRUE - window exists
206 *          GL_FALSE - window doesn't exist
207 */
208static GLboolean WindowExistsFlag;
209
210static int window_exists_err_handler( Display* dpy, XErrorEvent* xerr )
211{
212   (void) dpy;
213   if (xerr->error_code == BadWindow) {
214      WindowExistsFlag = GL_FALSE;
215   }
216   return 0;
217}
218
219static GLboolean window_exists( Display *dpy, Window win )
220{
221   XWindowAttributes wa;
222   int (*old_handler)( Display*, XErrorEvent* );
223   WindowExistsFlag = GL_TRUE;
224   old_handler = XSetErrorHandler(window_exists_err_handler);
225   XGetWindowAttributes( dpy, win, &wa ); /* dummy request */
226   XSetErrorHandler(old_handler);
227   return WindowExistsFlag;
228}
229
230static Status
231get_drawable_size( Display *dpy, Drawable d, uint *width, uint *height )
232{
233   Window root;
234   Status stat;
235   int xpos, ypos;
236   unsigned int w, h, bw, depth;
237   stat = XGetGeometry(dpy, d, &root, &xpos, &ypos, &w, &h, &bw, &depth);
238   *width = w;
239   *height = h;
240   return stat;
241}
242
243
244/**
245 * Return the size of the window (or pixmap) that corresponds to the
246 * given XMesaBuffer.
247 * \param width  returns width in pixels
248 * \param height  returns height in pixels
249 */
250void
251xmesa_get_window_size(Display *dpy, XMesaBuffer b,
252                      GLuint *width, GLuint *height)
253{
254   XMesaDisplay xmdpy = xmesa_init_display(dpy);
255   Status stat;
256
257   pipe_mutex_lock(xmdpy->mutex);
258   XSync(b->xm_visual->display, 0); /* added for Chromium */
259   stat = get_drawable_size(dpy, b->ws.drawable, width, height);
260   pipe_mutex_unlock(xmdpy->mutex);
261
262   if (!stat) {
263      /* probably querying a window that's recently been destroyed */
264      _mesa_warning(NULL, "XGetGeometry failed!\n");
265      *width = *height = 1;
266   }
267}
268
269#define GET_REDMASK(__v)        __v->mesa_visual.redMask
270#define GET_GREENMASK(__v)      __v->mesa_visual.greenMask
271#define GET_BLUEMASK(__v)       __v->mesa_visual.blueMask
272
273
274/**
275 * Choose the pixel format for the given visual.
276 * This will tell the gallium driver how to pack pixel data into
277 * drawing surfaces.
278 */
279static GLuint
280choose_pixel_format(XMesaVisual v)
281{
282   boolean native_byte_order = (host_byte_order() ==
283                                ImageByteOrder(v->display));
284
285   if (   GET_REDMASK(v)   == 0x0000ff
286       && GET_GREENMASK(v) == 0x00ff00
287       && GET_BLUEMASK(v)  == 0xff0000
288       && v->BitsPerPixel == 32) {
289      if (native_byte_order) {
290         /* no byteswapping needed */
291         return PIPE_FORMAT_R8G8B8A8_UNORM;
292      }
293      else {
294         return PIPE_FORMAT_A8B8G8R8_UNORM;
295      }
296   }
297   else if (   GET_REDMASK(v)   == 0xff0000
298            && GET_GREENMASK(v) == 0x00ff00
299            && GET_BLUEMASK(v)  == 0x0000ff
300            && v->BitsPerPixel == 32) {
301      if (native_byte_order) {
302         /* no byteswapping needed */
303         return PIPE_FORMAT_B8G8R8A8_UNORM;
304      }
305      else {
306         return PIPE_FORMAT_A8R8G8B8_UNORM;
307      }
308   }
309   else if (   GET_REDMASK(v)   == 0x0000ff00
310            && GET_GREENMASK(v) == 0x00ff0000
311            && GET_BLUEMASK(v)  == 0xff000000
312            && v->BitsPerPixel == 32) {
313      if (native_byte_order) {
314         /* no byteswapping needed */
315         return PIPE_FORMAT_A8R8G8B8_UNORM;
316      }
317      else {
318         return PIPE_FORMAT_B8G8R8A8_UNORM;
319      }
320   }
321   else if (   GET_REDMASK(v)   == 0xf800
322            && GET_GREENMASK(v) == 0x07e0
323            && GET_BLUEMASK(v)  == 0x001f
324            && native_byte_order
325            && v->BitsPerPixel == 16) {
326      /* 5-6-5 RGB */
327      return PIPE_FORMAT_B5G6R5_UNORM;
328   }
329
330   return PIPE_FORMAT_NONE;
331}
332
333
334/**
335 * Choose a depth/stencil format that satisfies the given depth and
336 * stencil sizes.
337 */
338static enum pipe_format
339choose_depth_stencil_format(XMesaDisplay xmdpy, int depth, int stencil)
340{
341   const enum pipe_texture_target target = PIPE_TEXTURE_2D;
342   const unsigned tex_usage = PIPE_BIND_DEPTH_STENCIL;
343   const unsigned geom_flags = (PIPE_TEXTURE_GEOM_NON_SQUARE |
344                                PIPE_TEXTURE_GEOM_NON_POWER_OF_TWO);
345   const unsigned sample_count = 0;
346   enum pipe_format formats[8], fmt;
347   int count, i;
348
349   count = 0;
350
351   if (depth <= 16 && stencil == 0) {
352      formats[count++] = PIPE_FORMAT_Z16_UNORM;
353   }
354   if (depth <= 24 && stencil == 0) {
355      formats[count++] = PIPE_FORMAT_X8Z24_UNORM;
356      formats[count++] = PIPE_FORMAT_Z24X8_UNORM;
357   }
358   if (depth <= 24 && stencil <= 8) {
359      formats[count++] = PIPE_FORMAT_S8_USCALED_Z24_UNORM;
360      formats[count++] = PIPE_FORMAT_Z24_UNORM_S8_USCALED;
361   }
362   if (depth <= 32 && stencil == 0) {
363      formats[count++] = PIPE_FORMAT_Z32_UNORM;
364   }
365
366   fmt = PIPE_FORMAT_NONE;
367   for (i = 0; i < count; i++) {
368      if (xmdpy->screen->is_format_supported(xmdpy->screen, formats[i],
369                                             target, sample_count,
370                                             tex_usage, geom_flags)) {
371         fmt = formats[i];
372         break;
373      }
374   }
375
376   return fmt;
377}
378
379
380
381/**********************************************************************/
382/*****                Linked list of XMesaBuffers                 *****/
383/**********************************************************************/
384
385static XMesaBuffer XMesaBufferList = NULL;
386
387
388/**
389 * Allocate a new XMesaBuffer object which corresponds to the given drawable.
390 * Note that XMesaBuffer is derived from GLframebuffer.
391 * The new XMesaBuffer will not have any size (Width=Height=0).
392 *
393 * \param d  the corresponding X drawable (window or pixmap)
394 * \param type  either WINDOW, PIXMAP or PBUFFER, describing d
395 * \param vis  the buffer's visual
396 * \param cmap  the window's colormap, if known.
397 * \return new XMesaBuffer or NULL if any problem
398 */
399static XMesaBuffer
400create_xmesa_buffer(Drawable d, BufferType type,
401                    XMesaVisual vis, Colormap cmap)
402{
403   XMesaDisplay xmdpy = xmesa_init_display(vis->display);
404   XMesaBuffer b;
405   uint width, height;
406
407   ASSERT(type == WINDOW || type == PIXMAP || type == PBUFFER);
408
409   if (!xmdpy)
410      return NULL;
411
412   b = (XMesaBuffer) CALLOC_STRUCT(xmesa_buffer);
413   if (!b)
414      return NULL;
415
416   b->ws.drawable = d;
417   b->ws.visual = vis->visinfo->visual;
418   b->ws.depth = vis->visinfo->depth;
419
420   b->xm_visual = vis;
421   b->type = type;
422   b->cmap = cmap;
423
424   get_drawable_size(vis->display, d, &width, &height);
425
426   /*
427    * Create framebuffer, but we'll plug in our own renderbuffers below.
428    */
429   b->stfb = xmesa_create_st_framebuffer(xmdpy, b);
430
431   /* GLX_EXT_texture_from_pixmap */
432   b->TextureTarget = 0;
433   b->TextureFormat = GLX_TEXTURE_FORMAT_NONE_EXT;
434   b->TextureMipmap = 0;
435
436   /* insert buffer into linked list */
437   b->Next = XMesaBufferList;
438   XMesaBufferList = b;
439
440   return b;
441}
442
443
444/**
445 * Find an XMesaBuffer by matching X display and colormap but NOT matching
446 * the notThis buffer.
447 */
448XMesaBuffer
449xmesa_find_buffer(Display *dpy, Colormap cmap, XMesaBuffer notThis)
450{
451   XMesaBuffer b;
452   for (b = XMesaBufferList; b; b = b->Next) {
453      if (b->xm_visual->display == dpy &&
454          b->cmap == cmap &&
455          b != notThis) {
456         return b;
457      }
458   }
459   return NULL;
460}
461
462
463/**
464 * Remove buffer from linked list, delete if no longer referenced.
465 */
466static void
467xmesa_free_buffer(XMesaBuffer buffer)
468{
469   XMesaBuffer prev = NULL, b;
470
471   for (b = XMesaBufferList; b; b = b->Next) {
472      if (b == buffer) {
473         /* unlink buffer from list */
474         if (prev)
475            prev->Next = buffer->Next;
476         else
477            XMesaBufferList = buffer->Next;
478
479         /* Since the X window for the XMesaBuffer is going away, we don't
480          * want to dereference this pointer in the future.
481          */
482         b->ws.drawable = 0;
483
484         /* XXX we should move the buffer to a delete-pending list and destroy
485          * the buffer until it is no longer current.
486          */
487         xmesa_destroy_st_framebuffer(buffer->stfb);
488
489         free(buffer);
490
491         return;
492      }
493      /* continue search */
494      prev = b;
495   }
496   /* buffer not found in XMesaBufferList */
497   _mesa_problem(NULL,"xmesa_free_buffer() - buffer not found\n");
498}
499
500
501
502/**********************************************************************/
503/*****                   Misc Private Functions                   *****/
504/**********************************************************************/
505
506
507/**
508 * When a context is bound for the first time, we can finally finish
509 * initializing the context's visual and buffer information.
510 * \param v  the XMesaVisual to initialize
511 * \param b  the XMesaBuffer to initialize (may be NULL)
512 * \param rgb_flag  TRUE = RGBA mode, FALSE = color index mode
513 * \param window  the window/pixmap we're rendering into
514 * \param cmap  the colormap associated with the window/pixmap
515 * \return GL_TRUE=success, GL_FALSE=failure
516 */
517static GLboolean
518initialize_visual_and_buffer(XMesaVisual v, XMesaBuffer b,
519                             GLboolean rgb_flag, Drawable window,
520                             Colormap cmap)
521{
522   ASSERT(!b || b->xm_visual == v);
523
524   /* Save true bits/pixel */
525   v->BitsPerPixel = bits_per_pixel(v);
526   assert(v->BitsPerPixel > 0);
527
528   if (rgb_flag == GL_FALSE) {
529      /* COLOR-INDEXED WINDOW: not supported*/
530      return GL_FALSE;
531   }
532   else {
533      /* RGB WINDOW:
534       * We support RGB rendering into almost any kind of visual.
535       */
536      const int xclass = v->mesa_visual.visualType;
537      if (xclass != GLX_TRUE_COLOR && xclass == !GLX_DIRECT_COLOR) {
538	 _mesa_warning(NULL,
539            "XMesa: RGB mode rendering not supported in given visual.\n");
540	 return GL_FALSE;
541      }
542      v->mesa_visual.indexBits = 0;
543
544      if (v->BitsPerPixel == 32) {
545         /* We use XImages for all front/back buffers.  If an X Window or
546          * X Pixmap is 32bpp, there's no guarantee that the alpha channel
547          * will be preserved.  For XImages we're in luck.
548          */
549         v->mesa_visual.alphaBits = 8;
550      }
551   }
552
553   /*
554    * If MESA_INFO env var is set print out some debugging info
555    * which can help Brian figure out what's going on when a user
556    * reports bugs.
557    */
558   if (_mesa_getenv("MESA_INFO")) {
559      printf("X/Mesa visual = %p\n", (void *) v);
560      printf("X/Mesa level = %d\n", v->mesa_visual.level);
561      printf("X/Mesa depth = %d\n", v->visinfo->depth);
562      printf("X/Mesa bits per pixel = %d\n", v->BitsPerPixel);
563   }
564
565   return GL_TRUE;
566}
567
568
569
570#define NUM_VISUAL_TYPES   6
571
572/**
573 * Convert an X visual type to a GLX visual type.
574 *
575 * \param visualType X visual type (i.e., \c TrueColor, \c StaticGray, etc.)
576 *        to be converted.
577 * \return If \c visualType is a valid X visual type, a GLX visual type will
578 *         be returned.  Otherwise \c GLX_NONE will be returned.
579 *
580 * \note
581 * This code was lifted directly from lib/GL/glx/glcontextmodes.c in the
582 * DRI CVS tree.
583 */
584static GLint
585xmesa_convert_from_x_visual_type( int visualType )
586{
587    static const int glx_visual_types[ NUM_VISUAL_TYPES ] = {
588	GLX_STATIC_GRAY,  GLX_GRAY_SCALE,
589	GLX_STATIC_COLOR, GLX_PSEUDO_COLOR,
590	GLX_TRUE_COLOR,   GLX_DIRECT_COLOR
591    };
592
593    return ( (unsigned) visualType < NUM_VISUAL_TYPES )
594	? glx_visual_types[ visualType ] : GLX_NONE;
595}
596
597
598/**********************************************************************/
599/*****                       Public Functions                     *****/
600/**********************************************************************/
601
602
603/*
604 * Create a new X/Mesa visual.
605 * Input:  display - X11 display
606 *         visinfo - an XVisualInfo pointer
607 *         rgb_flag - GL_TRUE = RGB mode,
608 *                    GL_FALSE = color index mode
609 *         alpha_flag - alpha buffer requested?
610 *         db_flag - GL_TRUE = double-buffered,
611 *                   GL_FALSE = single buffered
612 *         stereo_flag - stereo visual?
613 *         ximage_flag - GL_TRUE = use an XImage for back buffer,
614 *                       GL_FALSE = use an off-screen pixmap for back buffer
615 *         depth_size - requested bits/depth values, or zero
616 *         stencil_size - requested bits/stencil values, or zero
617 *         accum_red_size - requested bits/red accum values, or zero
618 *         accum_green_size - requested bits/green accum values, or zero
619 *         accum_blue_size - requested bits/blue accum values, or zero
620 *         accum_alpha_size - requested bits/alpha accum values, or zero
621 *         num_samples - number of samples/pixel if multisampling, or zero
622 *         level - visual level, usually 0
623 *         visualCaveat - ala the GLX extension, usually GLX_NONE
624 * Return;  a new XMesaVisual or 0 if error.
625 */
626PUBLIC
627XMesaVisual XMesaCreateVisual( Display *display,
628                               XVisualInfo * visinfo,
629                               GLboolean rgb_flag,
630                               GLboolean alpha_flag,
631                               GLboolean db_flag,
632                               GLboolean stereo_flag,
633                               GLboolean ximage_flag,
634                               GLint depth_size,
635                               GLint stencil_size,
636                               GLint accum_red_size,
637                               GLint accum_green_size,
638                               GLint accum_blue_size,
639                               GLint accum_alpha_size,
640                               GLint num_samples,
641                               GLint level,
642                               GLint visualCaveat )
643{
644   XMesaDisplay xmdpy = xmesa_init_display(display);
645   XMesaVisual v;
646   GLint red_bits, green_bits, blue_bits, alpha_bits;
647
648   if (!xmdpy)
649      return NULL;
650
651   /* For debugging only */
652   if (_mesa_getenv("MESA_XSYNC")) {
653      /* This makes debugging X easier.
654       * In your debugger, set a breakpoint on _XError to stop when an
655       * X protocol error is generated.
656       */
657      XSynchronize( display, 1 );
658   }
659
660   v = (XMesaVisual) CALLOC_STRUCT(xmesa_visual);
661   if (!v) {
662      return NULL;
663   }
664
665   v->display = display;
666
667   /* Save a copy of the XVisualInfo struct because the user may Xfree()
668    * the struct but we may need some of the information contained in it
669    * at a later time.
670    */
671   v->visinfo = (XVisualInfo *) MALLOC(sizeof(*visinfo));
672   if (!v->visinfo) {
673      free(v);
674      return NULL;
675   }
676   memcpy(v->visinfo, visinfo, sizeof(*visinfo));
677
678   v->ximage_flag = ximage_flag;
679
680   v->mesa_visual.redMask = visinfo->red_mask;
681   v->mesa_visual.greenMask = visinfo->green_mask;
682   v->mesa_visual.blueMask = visinfo->blue_mask;
683   v->mesa_visual.visualID = visinfo->visualid;
684   v->mesa_visual.screen = visinfo->screen;
685
686#if !(defined(__cplusplus) || defined(c_plusplus))
687   v->mesa_visual.visualType = xmesa_convert_from_x_visual_type(visinfo->class);
688#else
689   v->mesa_visual.visualType = xmesa_convert_from_x_visual_type(visinfo->c_class);
690#endif
691
692   v->mesa_visual.visualRating = visualCaveat;
693
694   if (alpha_flag)
695      v->mesa_visual.alphaBits = 8;
696
697   (void) initialize_visual_and_buffer( v, NULL, rgb_flag, 0, 0 );
698
699   {
700      const int xclass = v->mesa_visual.visualType;
701      if (xclass == GLX_TRUE_COLOR || xclass == GLX_DIRECT_COLOR) {
702         red_bits   = _mesa_bitcount(GET_REDMASK(v));
703         green_bits = _mesa_bitcount(GET_GREENMASK(v));
704         blue_bits  = _mesa_bitcount(GET_BLUEMASK(v));
705      }
706      else {
707         /* this is an approximation */
708         int depth;
709         depth = v->visinfo->depth;
710         red_bits = depth / 3;
711         depth -= red_bits;
712         green_bits = depth / 2;
713         depth -= green_bits;
714         blue_bits = depth;
715         alpha_bits = 0;
716         assert( red_bits + green_bits + blue_bits == v->visinfo->depth );
717      }
718      alpha_bits = v->mesa_visual.alphaBits;
719   }
720
721   _mesa_initialize_visual( &v->mesa_visual,
722                            db_flag, stereo_flag,
723                            red_bits, green_bits,
724                            blue_bits, alpha_bits,
725                            depth_size,
726                            stencil_size,
727                            accum_red_size, accum_green_size,
728                            accum_blue_size, accum_alpha_size,
729                            0 );
730
731   v->stvis.buffer_mask = ST_ATTACHMENT_FRONT_LEFT_MASK;
732   if (db_flag)
733      v->stvis.buffer_mask |= ST_ATTACHMENT_BACK_LEFT_MASK;
734   if (stereo_flag) {
735      v->stvis.buffer_mask |= ST_ATTACHMENT_FRONT_RIGHT_MASK;
736      if (db_flag)
737         v->stvis.buffer_mask |= ST_ATTACHMENT_BACK_RIGHT_MASK;
738   }
739
740   v->stvis.color_format = choose_pixel_format(v);
741   if (v->stvis.color_format == PIPE_FORMAT_NONE) {
742      FREE(v->visinfo);
743      FREE(v);
744      return NULL;
745   }
746
747   v->stvis.depth_stencil_format =
748      choose_depth_stencil_format(xmdpy, depth_size, stencil_size);
749
750   v->stvis.accum_format = (accum_red_size +
751         accum_green_size + accum_blue_size + accum_alpha_size) ?
752      PIPE_FORMAT_R16G16B16A16_SNORM : PIPE_FORMAT_NONE;
753
754   v->stvis.samples = num_samples;
755   v->stvis.render_buffer = ST_ATTACHMENT_INVALID;
756
757   /* XXX minor hack */
758   v->mesa_visual.level = level;
759   return v;
760}
761
762
763PUBLIC
764void XMesaDestroyVisual( XMesaVisual v )
765{
766   free(v->visinfo);
767   free(v);
768}
769
770
771/**
772 * Do per-display initializations.
773 */
774void
775xmesa_init( Display *display )
776{
777   xmesa_init_display(display);
778}
779
780
781/**
782 * Create a new XMesaContext.
783 * \param v  the XMesaVisual
784 * \param share_list  another XMesaContext with which to share display
785 *                    lists or NULL if no sharing is wanted.
786 * \return an XMesaContext or NULL if error.
787 */
788PUBLIC
789XMesaContext XMesaCreateContext( XMesaVisual v, XMesaContext share_list )
790{
791   XMesaDisplay xmdpy = xmesa_init_display(v->display);
792   XMesaContext c;
793
794   if (!xmdpy)
795      return NULL;
796
797   /* Note: the XMesaContext contains a Mesa GLcontext struct (inheritance) */
798   c = (XMesaContext) CALLOC_STRUCT(xmesa_context);
799   if (!c)
800      return NULL;
801
802   c->xm_visual = v;
803   c->xm_buffer = NULL;   /* set later by XMesaMakeCurrent */
804   c->xm_read_buffer = NULL;
805
806   c->st = stapi->create_context(stapi, xmdpy->smapi,
807         &v->stvis, (share_list) ? share_list->st : NULL);
808   if (c->st == NULL)
809      goto fail;
810
811   c->st->st_manager_private = (void *) c;
812
813   return c;
814
815fail:
816   if (c->st)
817      c->st->destroy(c->st);
818
819   free(c);
820   return NULL;
821}
822
823
824
825PUBLIC
826void XMesaDestroyContext( XMesaContext c )
827{
828   c->st->destroy(c->st);
829
830   /* FIXME: We should destroy the screen here, but if we do so, surfaces may
831    * outlive it, causing segfaults
832   struct pipe_screen *screen = c->st->pipe->screen;
833   screen->destroy(screen);
834   */
835
836   free(c);
837}
838
839
840
841/**
842 * Private function for creating an XMesaBuffer which corresponds to an
843 * X window or pixmap.
844 * \param v  the window's XMesaVisual
845 * \param w  the window we're wrapping
846 * \return  new XMesaBuffer or NULL if error
847 */
848PUBLIC XMesaBuffer
849XMesaCreateWindowBuffer(XMesaVisual v, Window w)
850{
851   XWindowAttributes attr;
852   XMesaBuffer b;
853   Colormap cmap;
854   int depth;
855
856   assert(v);
857   assert(w);
858
859   /* Check that window depth matches visual depth */
860   XGetWindowAttributes( v->display, w, &attr );
861   depth = attr.depth;
862   if (v->visinfo->depth != depth) {
863      _mesa_warning(NULL, "XMesaCreateWindowBuffer: depth mismatch between visual (%d) and window (%d)!\n",
864                    v->visinfo->depth, depth);
865      return NULL;
866   }
867
868   /* Find colormap */
869   if (attr.colormap) {
870      cmap = attr.colormap;
871   }
872   else {
873      _mesa_warning(NULL, "Window %u has no colormap!\n", (unsigned int) w);
874      /* this is weird, a window w/out a colormap!? */
875      /* OK, let's just allocate a new one and hope for the best */
876      cmap = XCreateColormap(v->display, w, attr.visual, AllocNone);
877   }
878
879   b = create_xmesa_buffer((Drawable) w, WINDOW, v, cmap);
880   if (!b)
881      return NULL;
882
883   if (!initialize_visual_and_buffer( v, b, v->mesa_visual.rgbMode,
884                                      (Drawable) w, cmap )) {
885      xmesa_free_buffer(b);
886      return NULL;
887   }
888
889   return b;
890}
891
892
893
894/**
895 * Create a new XMesaBuffer from an X pixmap.
896 *
897 * \param v    the XMesaVisual
898 * \param p    the pixmap
899 * \param cmap the colormap, may be 0 if using a \c GLX_TRUE_COLOR or
900 *             \c GLX_DIRECT_COLOR visual for the pixmap
901 * \returns new XMesaBuffer or NULL if error
902 */
903PUBLIC XMesaBuffer
904XMesaCreatePixmapBuffer(XMesaVisual v, Pixmap p, Colormap cmap)
905{
906   XMesaBuffer b;
907
908   assert(v);
909
910   b = create_xmesa_buffer((Drawable) p, PIXMAP, v, cmap);
911   if (!b)
912      return NULL;
913
914   if (!initialize_visual_and_buffer(v, b, v->mesa_visual.rgbMode,
915				     (Drawable) p, cmap)) {
916      xmesa_free_buffer(b);
917      return NULL;
918   }
919
920   return b;
921}
922
923
924/**
925 * For GLX_EXT_texture_from_pixmap
926 */
927XMesaBuffer
928XMesaCreatePixmapTextureBuffer(XMesaVisual v, Pixmap p,
929                               Colormap cmap,
930                               int format, int target, int mipmap)
931{
932   GET_CURRENT_CONTEXT(ctx);
933   XMesaBuffer b;
934
935   assert(v);
936
937   b = create_xmesa_buffer((Drawable) p, PIXMAP, v, cmap);
938   if (!b)
939      return NULL;
940
941   /* get pixmap size */
942   xmesa_get_window_size(v->display, b, &b->width, &b->height);
943
944   if (target == 0) {
945      /* examine dims */
946      if (ctx->Extensions.ARB_texture_non_power_of_two) {
947         target = GLX_TEXTURE_2D_EXT;
948      }
949      else if (   _mesa_bitcount(b->width)  == 1
950               && _mesa_bitcount(b->height) == 1) {
951         /* power of two size */
952         if (b->height == 1) {
953            target = GLX_TEXTURE_1D_EXT;
954         }
955         else {
956            target = GLX_TEXTURE_2D_EXT;
957         }
958      }
959      else if (ctx->Extensions.NV_texture_rectangle) {
960         target = GLX_TEXTURE_RECTANGLE_EXT;
961      }
962      else {
963         /* non power of two textures not supported */
964         XMesaDestroyBuffer(b);
965         return 0;
966      }
967   }
968
969   b->TextureTarget = target;
970   b->TextureFormat = format;
971   b->TextureMipmap = mipmap;
972
973   if (!initialize_visual_and_buffer(v, b, v->mesa_visual.rgbMode,
974				     (Drawable) p, cmap)) {
975      xmesa_free_buffer(b);
976      return NULL;
977   }
978
979   return b;
980}
981
982
983
984XMesaBuffer
985XMesaCreatePBuffer(XMesaVisual v, Colormap cmap,
986                   unsigned int width, unsigned int height)
987{
988   Window root;
989   Drawable drawable;  /* X Pixmap Drawable */
990   XMesaBuffer b;
991
992   /* allocate pixmap for front buffer */
993   root = RootWindow( v->display, v->visinfo->screen );
994   drawable = XCreatePixmap(v->display, root, width, height,
995                            v->visinfo->depth);
996   if (!drawable)
997      return NULL;
998
999   b = create_xmesa_buffer(drawable, PBUFFER, v, cmap);
1000   if (!b)
1001      return NULL;
1002
1003   if (!initialize_visual_and_buffer(v, b, v->mesa_visual.rgbMode,
1004				     drawable, cmap)) {
1005      xmesa_free_buffer(b);
1006      return NULL;
1007   }
1008
1009   return b;
1010}
1011
1012
1013
1014/*
1015 * Deallocate an XMesaBuffer structure and all related info.
1016 */
1017PUBLIC void
1018XMesaDestroyBuffer(XMesaBuffer b)
1019{
1020   xmesa_free_buffer(b);
1021}
1022
1023
1024/**
1025 * Query the current drawable size and notify the binding context.
1026 */
1027void
1028xmesa_check_buffer_size(XMesaBuffer b)
1029{
1030   XMesaContext xmctx = XMesaGetCurrentContext();
1031
1032   if (b->type == PBUFFER)
1033      return;
1034
1035   xmesa_get_window_size(b->xm_visual->display, b, &b->width, &b->height);
1036   if (xmctx && xmctx->xm_buffer == b)
1037      xmctx->st->notify_invalid_framebuffer(xmctx->st, b->stfb);
1038}
1039
1040
1041/*
1042 * Bind buffer b to context c and make c the current rendering context.
1043 */
1044PUBLIC
1045GLboolean XMesaMakeCurrent2( XMesaContext c, XMesaBuffer drawBuffer,
1046                             XMesaBuffer readBuffer )
1047{
1048   XMesaContext old_ctx = XMesaGetCurrentContext();
1049
1050   if (old_ctx && old_ctx != c) {
1051      XMesaFlush(old_ctx);
1052      old_ctx->xm_buffer = NULL;
1053      old_ctx->xm_read_buffer = NULL;
1054   }
1055
1056   if (c) {
1057      if (!drawBuffer || !readBuffer)
1058         return GL_FALSE;  /* must specify buffers! */
1059
1060      if (c == old_ctx &&
1061	  c->xm_buffer == drawBuffer &&
1062	  c->xm_read_buffer == readBuffer)
1063	 return GL_TRUE;
1064
1065      xmesa_check_buffer_size(drawBuffer);
1066      if (readBuffer != drawBuffer)
1067         xmesa_check_buffer_size(readBuffer);
1068
1069      c->xm_buffer = drawBuffer;
1070      c->xm_read_buffer = readBuffer;
1071
1072      stapi->make_current(stapi, c->st, drawBuffer->stfb, readBuffer->stfb);
1073
1074      /* Solution to Stephane Rehel's problem with glXReleaseBuffersMESA(): */
1075      drawBuffer->wasCurrent = GL_TRUE;
1076   }
1077   else {
1078      /* Detach */
1079      stapi->make_current(stapi, NULL, NULL, NULL);
1080
1081   }
1082   return GL_TRUE;
1083}
1084
1085
1086/*
1087 * Unbind the context c from its buffer.
1088 */
1089GLboolean XMesaUnbindContext( XMesaContext c )
1090{
1091   /* A no-op for XFree86 integration purposes */
1092   return GL_TRUE;
1093}
1094
1095
1096XMesaContext XMesaGetCurrentContext( void )
1097{
1098   struct st_context_iface *st = stapi->get_current(stapi);
1099   return (XMesaContext) (st) ? st->st_manager_private : NULL;
1100}
1101
1102
1103
1104/**
1105 * Swap front and back color buffers and have winsys display front buffer.
1106 * If there's no front color buffer no swap actually occurs.
1107 */
1108PUBLIC
1109void XMesaSwapBuffers( XMesaBuffer b )
1110{
1111   XMesaContext xmctx = XMesaGetCurrentContext();
1112
1113   if (xmctx && xmctx->xm_buffer == b) {
1114      xmctx->st->flush( xmctx->st,
1115            PIPE_FLUSH_RENDER_CACHE |
1116            PIPE_FLUSH_SWAPBUFFERS |
1117            PIPE_FLUSH_FRAME,
1118            NULL);
1119   }
1120
1121   xmesa_swap_st_framebuffer(b->stfb);
1122}
1123
1124
1125
1126/*
1127 * Copy sub-region of back buffer to front buffer
1128 */
1129void XMesaCopySubBuffer( XMesaBuffer b, int x, int y, int width, int height )
1130{
1131   xmesa_copy_st_framebuffer(b->stfb,
1132         ST_ATTACHMENT_BACK_LEFT, ST_ATTACHMENT_FRONT_LEFT,
1133         x, y, width, height);
1134}
1135
1136
1137
1138void XMesaFlush( XMesaContext c )
1139{
1140   if (c && c->xm_visual->display) {
1141      XMesaDisplay xmdpy = xmesa_init_display(c->xm_visual->display);
1142      struct pipe_fence_handle *fence = NULL;
1143
1144      c->st->flush(c->st, PIPE_FLUSH_RENDER_CACHE | PIPE_FLUSH_FRAME, &fence);
1145      if (fence) {
1146         xmdpy->screen->fence_finish(xmdpy->screen, fence, 0);
1147         xmdpy->screen->fence_reference(xmdpy->screen, &fence, NULL);
1148      }
1149      XSync( c->xm_visual->display, False );
1150   }
1151}
1152
1153
1154
1155
1156
1157XMesaBuffer XMesaFindBuffer( Display *dpy, Drawable d )
1158{
1159   XMesaBuffer b;
1160   for (b = XMesaBufferList; b; b = b->Next) {
1161      if (b->ws.drawable == d && b->xm_visual->display == dpy) {
1162         return b;
1163      }
1164   }
1165   return NULL;
1166}
1167
1168
1169/**
1170 * Free/destroy all XMesaBuffers associated with given display.
1171 */
1172void xmesa_destroy_buffers_on_display(Display *dpy)
1173{
1174   XMesaBuffer b, next;
1175   for (b = XMesaBufferList; b; b = next) {
1176      next = b->Next;
1177      if (b->xm_visual->display == dpy) {
1178         xmesa_free_buffer(b);
1179      }
1180   }
1181}
1182
1183
1184/*
1185 * Look for XMesaBuffers whose X window has been destroyed.
1186 * Deallocate any such XMesaBuffers.
1187 */
1188void XMesaGarbageCollect( void )
1189{
1190   XMesaBuffer b, next;
1191   for (b=XMesaBufferList; b; b=next) {
1192      next = b->Next;
1193      if (b->xm_visual &&
1194          b->xm_visual->display &&
1195          b->ws.drawable &&
1196          b->type == WINDOW) {
1197         XSync(b->xm_visual->display, False);
1198         if (!window_exists( b->xm_visual->display, b->ws.drawable )) {
1199            /* found a dead window, free the ancillary info */
1200            XMesaDestroyBuffer( b );
1201         }
1202      }
1203   }
1204}
1205
1206
1207
1208
1209PUBLIC void
1210XMesaBindTexImage(Display *dpy, XMesaBuffer drawable, int buffer,
1211                  const int *attrib_list)
1212{
1213}
1214
1215
1216
1217PUBLIC void
1218XMesaReleaseTexImage(Display *dpy, XMesaBuffer drawable, int buffer)
1219{
1220}
1221
1222
1223void
1224XMesaCopyContext(XMesaContext src, XMesaContext dst, unsigned long mask)
1225{
1226   if (dst->st->copy)
1227      dst->st->copy(dst->st, src->st, mask);
1228}
1229