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