glxcmds.c revision e157f381f21a1d5307f64b6ec3cc1b26d4ddf576
1/*
2 * SGI FREE SOFTWARE LICENSE B (Version 2.0, Sept. 18, 2008)
3 * Copyright (C) 1991-2000 Silicon Graphics, Inc. All Rights Reserved.
4 *
5 * Permission is hereby granted, free of charge, to any person obtaining a
6 * copy of this software and associated documentation files (the "Software"),
7 * to deal in the Software without restriction, including without limitation
8 * the rights to use, copy, modify, merge, publish, distribute, sublicense,
9 * and/or sell copies of the Software, and to permit persons to whom the
10 * Software is furnished to do so, subject to the following conditions:
11 *
12 * The above copyright notice including the dates of first publication and
13 * either this permission notice or a reference to
14 * http://oss.sgi.com/projects/FreeB/
15 * shall be included 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 * SILICON GRAPHICS, INC. BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
21 * WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF
22 * OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
23 * SOFTWARE.
24 *
25 * Except as contained in this notice, the name of Silicon Graphics, Inc.
26 * shall not be used in advertising or otherwise to promote the sale, use or
27 * other dealings in this Software without prior written authorization from
28 * Silicon Graphics, Inc.
29 */
30
31/**
32 * \file glxcmds.c
33 * Client-side GLX interface.
34 */
35
36#include "glxclient.h"
37#include "glapi.h"
38#include "glxextensions.h"
39#include "indirect.h"
40
41#ifdef GLX_DIRECT_RENDERING
42#ifdef GLX_USE_APPLEGL
43#include "apple_glx_context.h"
44#include "apple_glx.h"
45#include "glx_error.h"
46#else
47#include <sys/time.h>
48#ifdef XF86VIDMODE
49#include <X11/extensions/xf86vmode.h>
50#endif
51#include "xf86dri.h"
52#endif
53#else
54#endif
55
56#if defined(USE_XCB)
57#include <X11/Xlib-xcb.h>
58#include <xcb/xcb.h>
59#include <xcb/glx.h>
60#endif
61
62static const char __glXGLXClientVendorName[] = "Mesa Project and SGI";
63static const char __glXGLXClientVersion[] = "1.4";
64
65#if defined(GLX_DIRECT_RENDERING) && !defined(GLX_USE_APPLEGL)
66
67/**
68 * Get the __DRIdrawable for the drawable associated with a GLXContext
69 *
70 * \param dpy       The display associated with \c drawable.
71 * \param drawable  GLXDrawable whose __DRIdrawable part is to be retrieved.
72 * \param scrn_num  If non-NULL, the drawables screen is stored there
73 * \returns  A pointer to the context's __DRIdrawable on success, or NULL if
74 *           the drawable is not associated with a direct-rendering context.
75 */
76_X_HIDDEN __GLXDRIdrawable *
77GetGLXDRIDrawable(Display * dpy, GLXDrawable drawable)
78{
79   struct glx_display *priv = __glXInitialize(dpy);
80   __GLXDRIdrawable *pdraw;
81
82   if (priv == NULL)
83      return NULL;
84
85   if (__glxHashLookup(priv->drawHash, drawable, (void *) &pdraw) == 0)
86      return pdraw;
87
88   return NULL;
89}
90
91#endif
92
93
94/**
95 * Get the GLX per-screen data structure associated with a GLX context.
96 *
97 * \param dpy   Display for which the GLX per-screen information is to be
98 *              retrieved.
99 * \param scrn  Screen on \c dpy for which the GLX per-screen information is
100 *              to be retrieved.
101 * \returns A pointer to the GLX per-screen data if \c dpy and \c scrn
102 *          specify a valid GLX screen, or NULL otherwise.
103 *
104 * \todo Should this function validate that \c scrn is within the screen
105 *       number range for \c dpy?
106 */
107
108static struct glx_screen *
109GetGLXScreenConfigs(Display * dpy, int scrn)
110{
111   struct glx_display *const priv = __glXInitialize(dpy);
112
113   return (priv
114           && priv->screens !=
115           NULL) ? priv->screens[scrn] : NULL;
116}
117
118
119static int
120GetGLXPrivScreenConfig(Display * dpy, int scrn, struct glx_display ** ppriv,
121                       struct glx_screen ** ppsc)
122{
123   /* Initialize the extension, if needed .  This has the added value
124    * of initializing/allocating the display private
125    */
126
127   if (dpy == NULL) {
128      return GLX_NO_EXTENSION;
129   }
130
131   *ppriv = __glXInitialize(dpy);
132   if (*ppriv == NULL) {
133      return GLX_NO_EXTENSION;
134   }
135
136   /* Check screen number to see if its valid */
137   if ((scrn < 0) || (scrn >= ScreenCount(dpy))) {
138      return GLX_BAD_SCREEN;
139   }
140
141   /* Check to see if the GL is supported on this screen */
142   *ppsc = (*ppriv)->screens[scrn];
143   if ((*ppsc)->configs == NULL) {
144      /* No support for GL on this screen regardless of visual */
145      return GLX_BAD_VISUAL;
146   }
147
148   return Success;
149}
150
151
152/**
153 * Determine if a \c GLXFBConfig supplied by the application is valid.
154 *
155 * \param dpy     Application supplied \c Display pointer.
156 * \param config  Application supplied \c GLXFBConfig.
157 *
158 * \returns If the \c GLXFBConfig is valid, the a pointer to the matching
159 *          \c struct glx_config structure is returned.  Otherwise, \c NULL
160 *          is returned.
161 */
162static struct glx_config *
163ValidateGLXFBConfig(Display * dpy, GLXFBConfig fbconfig)
164{
165   struct glx_display *const priv = __glXInitialize(dpy);
166   int num_screens = ScreenCount(dpy);
167   unsigned i;
168   struct glx_config *config;
169
170   if (priv != NULL) {
171      for (i = 0; i < num_screens; i++) {
172	 for (config = priv->screens[i]->configs; config != NULL;
173	      config = config->next) {
174	    if (config == (struct glx_config *) fbconfig) {
175	       return config;
176	    }
177	 }
178      }
179   }
180
181   return NULL;
182}
183
184_X_HIDDEN Bool
185glx_context_init(struct glx_context *gc,
186		 struct glx_screen *psc, struct glx_config *config)
187{
188   gc->majorOpcode = __glXSetupForCommand(psc->display->dpy);
189   if (!gc->majorOpcode)
190      return GL_FALSE;
191
192   gc->screen = psc->scr;
193   gc->psc = psc;
194   gc->config = config;
195   gc->isDirect = GL_TRUE;
196   gc->currentContextTag = -1;
197
198   return GL_TRUE;
199}
200
201
202/**
203 * Create a new context.
204 *
205 * \param renderType   For FBConfigs, what is the rendering type?
206 */
207
208static GLXContext
209CreateContext(Display *dpy, int generic_id, struct glx_config *config,
210              GLXContext shareList_user, Bool allowDirect,
211	      unsigned code, int renderType, int screen)
212{
213   struct glx_context *gc;
214   struct glx_screen *psc;
215   struct glx_context *shareList = (struct glx_context *) shareList_user;
216   if (dpy == NULL)
217      return NULL;
218
219   psc = GetGLXScreenConfigs(dpy, screen);
220   if (psc == NULL)
221      return NULL;
222
223   if (generic_id == None)
224      return NULL;
225
226   gc = NULL;
227#ifdef GLX_USE_APPLEGL
228   gc = applegl_create_context(psc, config, shareList, renderType);
229#else
230   if (allowDirect && psc->vtable->create_context)
231      gc = psc->vtable->create_context(psc, config, shareList, renderType);
232   if (!gc)
233      gc = indirect_create_context(psc, config, shareList, renderType);
234#endif
235   if (!gc)
236      return NULL;
237
238   LockDisplay(dpy);
239   switch (code) {
240   case X_GLXCreateContext: {
241      xGLXCreateContextReq *req;
242
243      /* Send the glXCreateContext request */
244      GetReq(GLXCreateContext, req);
245      req->reqType = gc->majorOpcode;
246      req->glxCode = X_GLXCreateContext;
247      req->context = gc->xid = XAllocID(dpy);
248      req->visual = generic_id;
249      req->screen = screen;
250      req->shareList = shareList ? shareList->xid : None;
251      req->isDirect = gc->isDirect;
252      break;
253   }
254
255   case X_GLXCreateNewContext: {
256      xGLXCreateNewContextReq *req;
257
258      /* Send the glXCreateNewContext request */
259      GetReq(GLXCreateNewContext, req);
260      req->reqType = gc->majorOpcode;
261      req->glxCode = X_GLXCreateNewContext;
262      req->context = gc->xid = XAllocID(dpy);
263      req->fbconfig = generic_id;
264      req->screen = screen;
265      req->renderType = renderType;
266      req->shareList = shareList ? shareList->xid : None;
267      req->isDirect = gc->isDirect;
268      break;
269   }
270
271   case X_GLXvop_CreateContextWithConfigSGIX: {
272      xGLXVendorPrivateWithReplyReq *vpreq;
273      xGLXCreateContextWithConfigSGIXReq *req;
274
275      /* Send the glXCreateNewContext request */
276      GetReqExtra(GLXVendorPrivateWithReply,
277		  sz_xGLXCreateContextWithConfigSGIXReq -
278		  sz_xGLXVendorPrivateWithReplyReq, vpreq);
279      req = (xGLXCreateContextWithConfigSGIXReq *) vpreq;
280      req->reqType = gc->majorOpcode;
281      req->glxCode = X_GLXVendorPrivateWithReply;
282      req->vendorCode = X_GLXvop_CreateContextWithConfigSGIX;
283      req->context = gc->xid = XAllocID(dpy);
284      req->fbconfig = generic_id;
285      req->screen = screen;
286      req->renderType = renderType;
287      req->shareList = shareList ? shareList->xid : None;
288      req->isDirect = gc->isDirect;
289      break;
290   }
291
292   default:
293      /* What to do here?  This case is the sign of an internal error.  It
294       * should never be reachable.
295       */
296      break;
297   }
298
299   UnlockDisplay(dpy);
300   SyncHandle();
301
302   gc->imported = GL_FALSE;
303   gc->renderType = renderType;
304
305   return (GLXContext) gc;
306}
307
308_X_EXPORT GLXContext
309glXCreateContext(Display * dpy, XVisualInfo * vis,
310                 GLXContext shareList, Bool allowDirect)
311{
312   struct glx_config *config = NULL;
313   int renderType = 0;
314
315#if defined(GLX_DIRECT_RENDERING) || defined(GLX_USE_APPLEGL)
316   struct glx_screen *const psc = GetGLXScreenConfigs(dpy, vis->screen);
317
318   config = glx_config_find_visual(psc->visuals, vis->visualid);
319   if (config == NULL) {
320      xError error;
321
322      error.errorCode = BadValue;
323      error.resourceID = vis->visualid;
324      error.sequenceNumber = dpy->request;
325      error.type = X_Error;
326      error.majorCode = __glXSetupForCommand(dpy);
327      error.minorCode = X_GLXCreateContext;
328      _XError(dpy, &error);
329      return None;
330   }
331
332   renderType = config->rgbMode ? GLX_RGBA_TYPE : GLX_COLOR_INDEX_TYPE;
333#endif
334
335   return CreateContext(dpy, vis->visualid, config, shareList, allowDirect,
336                        X_GLXCreateContext, renderType, vis->screen);
337}
338
339_X_HIDDEN void
340glx_send_destroy_context(Display *dpy, XID xid)
341{
342   CARD8 opcode = __glXSetupForCommand(dpy);
343   xGLXDestroyContextReq *req;
344
345   LockDisplay(dpy);
346   GetReq(GLXDestroyContext, req);
347   req->reqType = opcode;
348   req->glxCode = X_GLXDestroyContext;
349   req->context = xid;
350   UnlockDisplay(dpy);
351   SyncHandle();
352}
353
354/*
355** Destroy the named context
356*/
357static void
358DestroyContext(Display * dpy, GLXContext ctx)
359{
360   struct glx_context *gc = (struct glx_context *) ctx;
361
362   if (!gc)
363      return;
364
365   __glXLock();
366   if (gc->currentDpy) {
367      /* This context is bound to some thread.  According to the man page,
368       * we should not actually delete the context until it's unbound.
369       * Note that we set gc->xid = None above.  In MakeContextCurrent()
370       * we check for that and delete the context there.
371       */
372      if (!gc->imported)
373	 glx_send_destroy_context(dpy, gc->xid);
374      gc->xid = None;
375      __glXUnlock();
376      return;
377   }
378   __glXUnlock();
379
380   if (gc->vtable->destroy)
381      gc->vtable->destroy(gc);
382}
383
384_X_EXPORT void
385glXDestroyContext(Display * dpy, GLXContext gc)
386{
387   DestroyContext(dpy, gc);
388}
389
390/*
391** Return the major and minor version #s for the GLX extension
392*/
393_X_EXPORT Bool
394glXQueryVersion(Display * dpy, int *major, int *minor)
395{
396   struct glx_display *priv;
397
398   /* Init the extension.  This fetches the major and minor version. */
399   priv = __glXInitialize(dpy);
400   if (!priv)
401      return GL_FALSE;
402
403   if (major)
404      *major = priv->majorVersion;
405   if (minor)
406      *minor = priv->minorVersion;
407   return GL_TRUE;
408}
409
410/*
411** Query the existance of the GLX extension
412*/
413_X_EXPORT Bool
414glXQueryExtension(Display * dpy, int *errorBase, int *eventBase)
415{
416   int major_op, erb, evb;
417   Bool rv;
418
419   rv = XQueryExtension(dpy, GLX_EXTENSION_NAME, &major_op, &evb, &erb);
420   if (rv) {
421      if (errorBase)
422         *errorBase = erb;
423      if (eventBase)
424         *eventBase = evb;
425   }
426   return rv;
427}
428
429/*
430** Put a barrier in the token stream that forces the GL to finish its
431** work before X can proceed.
432*/
433_X_EXPORT void
434glXWaitGL(void)
435{
436   struct glx_context *gc = __glXGetCurrentContext();
437
438   if (gc && gc->vtable->wait_gl)
439      gc->vtable->wait_gl(gc);
440}
441
442/*
443** Put a barrier in the token stream that forces X to finish its
444** work before GL can proceed.
445*/
446_X_EXPORT void
447glXWaitX(void)
448{
449   struct glx_context *gc = __glXGetCurrentContext();
450
451   if (gc && gc->vtable->wait_x)
452      gc->vtable->wait_x(gc);
453}
454
455_X_EXPORT void
456glXUseXFont(Font font, int first, int count, int listBase)
457{
458   struct glx_context *gc = __glXGetCurrentContext();
459
460   if (gc && gc->vtable->use_x_font)
461      gc->vtable->use_x_font(gc, font, first, count, listBase);
462}
463
464/************************************************************************/
465
466/*
467** Copy the source context to the destination context using the
468** attribute "mask".
469*/
470_X_EXPORT void
471glXCopyContext(Display * dpy, GLXContext source_user,
472	       GLXContext dest_user, unsigned long mask)
473{
474   struct glx_context *source = (struct glx_context *) source_user;
475   struct glx_context *dest = (struct glx_context *) dest_user;
476#ifdef GLX_USE_APPLEGL
477   struct glx_context *gc = __glXGetCurrentContext();
478   int errorcode;
479   bool x11error;
480
481   if(apple_glx_copy_context(gc->driContext, source->driContext, dest->driContext,
482                             mask, &errorcode, &x11error)) {
483      __glXSendError(dpy, errorcode, 0, X_GLXCopyContext, x11error);
484   }
485
486#else
487   xGLXCopyContextReq *req;
488   struct glx_context *gc = __glXGetCurrentContext();
489   GLXContextTag tag;
490   CARD8 opcode;
491
492   opcode = __glXSetupForCommand(dpy);
493   if (!opcode) {
494      return;
495   }
496
497#if defined(GLX_DIRECT_RENDERING) && !defined(GLX_USE_APPLEGL)
498   if (gc->isDirect) {
499      /* NOT_DONE: This does not work yet */
500   }
501#endif
502
503   /*
504    ** If the source is the current context, send its tag so that the context
505    ** can be flushed before the copy.
506    */
507   if (source == gc && dpy == gc->currentDpy) {
508      tag = gc->currentContextTag;
509   }
510   else {
511      tag = 0;
512   }
513
514   /* Send the glXCopyContext request */
515   LockDisplay(dpy);
516   GetReq(GLXCopyContext, req);
517   req->reqType = opcode;
518   req->glxCode = X_GLXCopyContext;
519   req->source = source ? source->xid : None;
520   req->dest = dest ? dest->xid : None;
521   req->mask = mask;
522   req->contextTag = tag;
523   UnlockDisplay(dpy);
524   SyncHandle();
525#endif /* GLX_USE_APPLEGL */
526}
527
528
529/**
530 * Determine if a context uses direct rendering.
531 *
532 * \param dpy        Display where the context was created.
533 * \param contextID  ID of the context to be tested.
534 *
535 * \returns \c GL_TRUE if the context is direct rendering or not.
536 */
537static Bool
538__glXIsDirect(Display * dpy, GLXContextID contextID)
539{
540#if !defined(USE_XCB)
541   xGLXIsDirectReq *req;
542   xGLXIsDirectReply reply;
543#endif
544   CARD8 opcode;
545
546   opcode = __glXSetupForCommand(dpy);
547   if (!opcode) {
548      return GL_FALSE;
549   }
550
551#ifdef USE_XCB
552   xcb_connection_t *c = XGetXCBConnection(dpy);
553   xcb_glx_is_direct_reply_t *reply = xcb_glx_is_direct_reply(c,
554                                                              xcb_glx_is_direct
555                                                              (c, contextID),
556                                                              NULL);
557
558   const Bool is_direct = reply->is_direct ? True : False;
559   free(reply);
560
561   return is_direct;
562#else
563   /* Send the glXIsDirect request */
564   LockDisplay(dpy);
565   GetReq(GLXIsDirect, req);
566   req->reqType = opcode;
567   req->glxCode = X_GLXIsDirect;
568   req->context = contextID;
569   _XReply(dpy, (xReply *) & reply, 0, False);
570   UnlockDisplay(dpy);
571   SyncHandle();
572
573   return reply.isDirect;
574#endif /* USE_XCB */
575}
576
577/**
578 * \todo
579 * Shouldn't this function \b always return \c GL_FALSE when
580 * \c GLX_DIRECT_RENDERING is not defined?  Do we really need to bother with
581 * the GLX protocol here at all?
582 */
583_X_EXPORT Bool
584glXIsDirect(Display * dpy, GLXContext gc_user)
585{
586   struct glx_context *gc = (struct glx_context *) gc_user;
587
588   if (!gc) {
589      return GL_FALSE;
590   }
591   else if (gc->isDirect) {
592      return GL_TRUE;
593   }
594#ifdef GLX_USE_APPLEGL  /* TODO: indirect on darwin */
595      return GL_FALSE;
596#else
597   return __glXIsDirect(dpy, gc->xid);
598#endif
599}
600
601_X_EXPORT GLXPixmap
602glXCreateGLXPixmap(Display * dpy, XVisualInfo * vis, Pixmap pixmap)
603{
604#ifdef GLX_USE_APPLEGL
605   int screen = vis->screen;
606   struct glx_screen *const psc = GetGLXScreenConfigs(dpy, screen);
607   const struct glx_config *config;
608
609   config = glx_config_find_visual(psc->visuals, vis->visualid);
610
611   if(apple_glx_pixmap_create(dpy, vis->screen, pixmap, config))
612      return None;
613
614   return pixmap;
615#else
616   xGLXCreateGLXPixmapReq *req;
617   GLXPixmap xid;
618   CARD8 opcode;
619
620   opcode = __glXSetupForCommand(dpy);
621   if (!opcode) {
622      return None;
623   }
624
625   /* Send the glXCreateGLXPixmap request */
626   LockDisplay(dpy);
627   GetReq(GLXCreateGLXPixmap, req);
628   req->reqType = opcode;
629   req->glxCode = X_GLXCreateGLXPixmap;
630   req->screen = vis->screen;
631   req->visual = vis->visualid;
632   req->pixmap = pixmap;
633   req->glxpixmap = xid = XAllocID(dpy);
634   UnlockDisplay(dpy);
635   SyncHandle();
636
637#if defined(GLX_DIRECT_RENDERING) && !defined(GLX_USE_APPLEGL)
638   do {
639      /* FIXME: Maybe delay __DRIdrawable creation until the drawable
640       * is actually bound to a context... */
641
642      struct glx_display *const priv = __glXInitialize(dpy);
643      __GLXDRIdrawable *pdraw;
644      struct glx_screen *psc;
645      struct glx_config *config;
646
647      psc = priv->screens[vis->screen];
648      if (psc->driScreen == NULL)
649         break;
650      config = glx_config_find_visual(psc->visuals, vis->visualid);
651      pdraw = psc->driScreen->createDrawable(psc, pixmap, xid, config);
652      if (pdraw == NULL) {
653         fprintf(stderr, "failed to create pixmap\n");
654         break;
655      }
656
657      if (__glxHashInsert(priv->drawHash, xid, pdraw)) {
658         (*pdraw->destroyDrawable) (pdraw);
659         return None;           /* FIXME: Check what we're supposed to do here... */
660      }
661   } while (0);
662#endif
663
664   return xid;
665#endif
666}
667
668/*
669** Destroy the named pixmap
670*/
671_X_EXPORT void
672glXDestroyGLXPixmap(Display * dpy, GLXPixmap glxpixmap)
673{
674#ifdef GLX_USE_APPLEGL
675   if(apple_glx_pixmap_destroy(dpy, glxpixmap))
676      __glXSendError(dpy, GLXBadPixmap, glxpixmap, X_GLXDestroyPixmap, false);
677#else
678   xGLXDestroyGLXPixmapReq *req;
679   CARD8 opcode;
680
681   opcode = __glXSetupForCommand(dpy);
682   if (!opcode) {
683      return;
684   }
685
686   /* Send the glXDestroyGLXPixmap request */
687   LockDisplay(dpy);
688   GetReq(GLXDestroyGLXPixmap, req);
689   req->reqType = opcode;
690   req->glxCode = X_GLXDestroyGLXPixmap;
691   req->glxpixmap = glxpixmap;
692   UnlockDisplay(dpy);
693   SyncHandle();
694
695#if defined(GLX_DIRECT_RENDERING) && !defined(GLX_USE_APPLEGL)
696   {
697      struct glx_display *const priv = __glXInitialize(dpy);
698      __GLXDRIdrawable *pdraw = GetGLXDRIDrawable(dpy, glxpixmap);
699
700      if (pdraw != NULL) {
701         (*pdraw->destroyDrawable) (pdraw);
702         __glxHashDelete(priv->drawHash, glxpixmap);
703      }
704   }
705#endif
706#endif /* GLX_USE_APPLEGL */
707}
708
709_X_EXPORT void
710glXSwapBuffers(Display * dpy, GLXDrawable drawable)
711{
712#ifdef GLX_USE_APPLEGL
713   struct glx_context * gc = __glXGetCurrentContext();
714   if(gc && apple_glx_is_current_drawable(dpy, gc->driContext, drawable)) {
715      apple_glx_swap_buffers(gc->driContext);
716   } else {
717      __glXSendError(dpy, GLXBadCurrentWindow, 0, X_GLXSwapBuffers, false);
718   }
719#else
720   struct glx_context *gc;
721   GLXContextTag tag;
722   CARD8 opcode;
723#ifdef USE_XCB
724   xcb_connection_t *c;
725#else
726   xGLXSwapBuffersReq *req;
727#endif
728
729   gc = __glXGetCurrentContext();
730
731#if defined(GLX_DIRECT_RENDERING) && !defined(GLX_USE_APPLEGL)
732   __GLXDRIdrawable *pdraw = GetGLXDRIDrawable(dpy, drawable);
733
734   if (pdraw != NULL) {
735      if (gc && drawable == gc->currentDrawable) {
736	 glFlush();
737      }
738
739      (*pdraw->psc->driScreen->swapBuffers)(pdraw, 0, 0, 0);
740      return;
741   }
742#endif
743
744   opcode = __glXSetupForCommand(dpy);
745   if (!opcode) {
746      return;
747   }
748
749   /*
750    ** The calling thread may or may not have a current context.  If it
751    ** does, send the context tag so the server can do a flush.
752    */
753   if ((gc != NULL) && (dpy == gc->currentDpy) &&
754       ((drawable == gc->currentDrawable)
755        || (drawable == gc->currentReadable))) {
756      tag = gc->currentContextTag;
757   }
758   else {
759      tag = 0;
760   }
761
762#ifdef USE_XCB
763   c = XGetXCBConnection(dpy);
764   xcb_glx_swap_buffers(c, tag, drawable);
765   xcb_flush(c);
766#else
767   /* Send the glXSwapBuffers request */
768   LockDisplay(dpy);
769   GetReq(GLXSwapBuffers, req);
770   req->reqType = opcode;
771   req->glxCode = X_GLXSwapBuffers;
772   req->drawable = drawable;
773   req->contextTag = tag;
774   UnlockDisplay(dpy);
775   SyncHandle();
776   XFlush(dpy);
777#endif /* USE_XCB */
778#endif /* GLX_USE_APPLEGL */
779}
780
781
782/*
783** Return configuration information for the given display, screen and
784** visual combination.
785*/
786_X_EXPORT int
787glXGetConfig(Display * dpy, XVisualInfo * vis, int attribute,
788             int *value_return)
789{
790   struct glx_display *priv;
791   struct glx_screen *psc;
792   struct glx_config *config;
793   int status;
794
795   status = GetGLXPrivScreenConfig(dpy, vis->screen, &priv, &psc);
796   if (status == Success) {
797      config = glx_config_find_visual(psc->visuals, vis->visualid);
798
799      /* Lookup attribute after first finding a match on the visual */
800      if (config != NULL) {
801	 return glx_config_get(config, attribute, value_return);
802      }
803
804      status = GLX_BAD_VISUAL;
805   }
806
807   /*
808    ** If we can't find the config for this visual, this visual is not
809    ** supported by the OpenGL implementation on the server.
810    */
811   if ((status == GLX_BAD_VISUAL) && (attribute == GLX_USE_GL)) {
812      *value_return = GL_FALSE;
813      status = Success;
814   }
815
816   return status;
817}
818
819/************************************************************************/
820
821static void
822init_fbconfig_for_chooser(struct glx_config * config,
823                          GLboolean fbconfig_style_tags)
824{
825   memset(config, 0, sizeof(struct glx_config));
826   config->visualID = (XID) GLX_DONT_CARE;
827   config->visualType = GLX_DONT_CARE;
828
829   /* glXChooseFBConfig specifies different defaults for these two than
830    * glXChooseVisual.
831    */
832   if (fbconfig_style_tags) {
833      config->rgbMode = GL_TRUE;
834      config->doubleBufferMode = GLX_DONT_CARE;
835   }
836
837   config->visualRating = GLX_DONT_CARE;
838   config->transparentPixel = GLX_NONE;
839   config->transparentRed = GLX_DONT_CARE;
840   config->transparentGreen = GLX_DONT_CARE;
841   config->transparentBlue = GLX_DONT_CARE;
842   config->transparentAlpha = GLX_DONT_CARE;
843   config->transparentIndex = GLX_DONT_CARE;
844
845   config->drawableType = GLX_WINDOW_BIT;
846   config->renderType =
847      (config->rgbMode) ? GLX_RGBA_BIT : GLX_COLOR_INDEX_BIT;
848   config->xRenderable = GLX_DONT_CARE;
849   config->fbconfigID = (GLXFBConfigID) (GLX_DONT_CARE);
850
851   config->swapMethod = GLX_DONT_CARE;
852}
853
854#define MATCH_DONT_CARE( param )        \
855  do {                                  \
856    if ( ((int) a-> param != (int) GLX_DONT_CARE)   \
857         && (a-> param != b-> param) ) {        \
858      return False;                             \
859    }                                           \
860  } while ( 0 )
861
862#define MATCH_MINIMUM( param )                  \
863  do {                                          \
864    if ( ((int) a-> param != (int) GLX_DONT_CARE)	\
865         && (a-> param > b-> param) ) {         \
866      return False;                             \
867    }                                           \
868  } while ( 0 )
869
870#define MATCH_EXACT( param )                    \
871  do {                                          \
872    if ( a-> param != b-> param) {              \
873      return False;                             \
874    }                                           \
875  } while ( 0 )
876
877/* Test that all bits from a are contained in b */
878#define MATCH_MASK(param)			\
879  do {						\
880    if ((a->param & ~b->param) != 0)		\
881      return False;				\
882  } while (0);
883
884/**
885 * Determine if two GLXFBConfigs are compatible.
886 *
887 * \param a  Application specified config to test.
888 * \param b  Server specified config to test against \c a.
889 */
890static Bool
891fbconfigs_compatible(const struct glx_config * const a,
892                     const struct glx_config * const b)
893{
894   MATCH_DONT_CARE(doubleBufferMode);
895   MATCH_DONT_CARE(visualType);
896   MATCH_DONT_CARE(visualRating);
897   MATCH_DONT_CARE(xRenderable);
898   MATCH_DONT_CARE(fbconfigID);
899   MATCH_DONT_CARE(swapMethod);
900
901   MATCH_MINIMUM(rgbBits);
902   MATCH_MINIMUM(numAuxBuffers);
903   MATCH_MINIMUM(redBits);
904   MATCH_MINIMUM(greenBits);
905   MATCH_MINIMUM(blueBits);
906   MATCH_MINIMUM(alphaBits);
907   MATCH_MINIMUM(depthBits);
908   MATCH_MINIMUM(stencilBits);
909   MATCH_MINIMUM(accumRedBits);
910   MATCH_MINIMUM(accumGreenBits);
911   MATCH_MINIMUM(accumBlueBits);
912   MATCH_MINIMUM(accumAlphaBits);
913   MATCH_MINIMUM(sampleBuffers);
914   MATCH_MINIMUM(maxPbufferWidth);
915   MATCH_MINIMUM(maxPbufferHeight);
916   MATCH_MINIMUM(maxPbufferPixels);
917   MATCH_MINIMUM(samples);
918
919   MATCH_DONT_CARE(stereoMode);
920   MATCH_EXACT(level);
921
922   MATCH_MASK(drawableType);
923   MATCH_MASK(renderType);
924
925   /* There is a bug in a few of the XFree86 DDX drivers.  They contain
926    * visuals with a "transparent type" of 0 when they really mean GLX_NONE.
927    * Technically speaking, it is a bug in the DDX driver, but there is
928    * enough of an installed base to work around the problem here.  In any
929    * case, 0 is not a valid value of the transparent type, so we'll treat 0
930    * from the app as GLX_DONT_CARE. We'll consider GLX_NONE from the app and
931    * 0 from the server to be a match to maintain backward compatibility with
932    * the (broken) drivers.
933    */
934
935   if (a->transparentPixel != (int) GLX_DONT_CARE && a->transparentPixel != 0) {
936      if (a->transparentPixel == GLX_NONE) {
937         if (b->transparentPixel != GLX_NONE && b->transparentPixel != 0)
938            return False;
939      }
940      else {
941         MATCH_EXACT(transparentPixel);
942      }
943
944      switch (a->transparentPixel) {
945      case GLX_TRANSPARENT_RGB:
946         MATCH_DONT_CARE(transparentRed);
947         MATCH_DONT_CARE(transparentGreen);
948         MATCH_DONT_CARE(transparentBlue);
949         MATCH_DONT_CARE(transparentAlpha);
950         break;
951
952      case GLX_TRANSPARENT_INDEX:
953         MATCH_DONT_CARE(transparentIndex);
954         break;
955
956      default:
957         break;
958      }
959   }
960
961   return True;
962}
963
964
965/* There's some trickly language in the GLX spec about how this is supposed
966 * to work.  Basically, if a given component size is either not specified
967 * or the requested size is zero, it is supposed to act like PERFER_SMALLER.
968 * Well, that's really hard to do with the code as-is.  This behavior is
969 * closer to correct, but still not technically right.
970 */
971#define PREFER_LARGER_OR_ZERO(comp)             \
972  do {                                          \
973    if ( ((*a)-> comp) != ((*b)-> comp) ) {     \
974      if ( ((*a)-> comp) == 0 ) {               \
975        return -1;                              \
976      }                                         \
977      else if ( ((*b)-> comp) == 0 ) {          \
978        return 1;                               \
979      }                                         \
980      else {                                    \
981        return ((*b)-> comp) - ((*a)-> comp) ;  \
982      }                                         \
983    }                                           \
984  } while( 0 )
985
986#define PREFER_LARGER(comp)                     \
987  do {                                          \
988    if ( ((*a)-> comp) != ((*b)-> comp) ) {     \
989      return ((*b)-> comp) - ((*a)-> comp) ;    \
990    }                                           \
991  } while( 0 )
992
993#define PREFER_SMALLER(comp)                    \
994  do {                                          \
995    if ( ((*a)-> comp) != ((*b)-> comp) ) {     \
996      return ((*a)-> comp) - ((*b)-> comp) ;    \
997    }                                           \
998  } while( 0 )
999
1000/**
1001 * Compare two GLXFBConfigs.  This function is intended to be used as the
1002 * compare function passed in to qsort.
1003 *
1004 * \returns If \c a is a "better" config, according to the specification of
1005 *          SGIX_fbconfig, a number less than zero is returned.  If \c b is
1006 *          better, then a number greater than zero is return.  If both are
1007 *          equal, zero is returned.
1008 * \sa qsort, glXChooseVisual, glXChooseFBConfig, glXChooseFBConfigSGIX
1009 */
1010static int
1011fbconfig_compare(struct glx_config **a, struct glx_config **b)
1012{
1013   /* The order of these comparisons must NOT change.  It is defined by
1014    * the GLX 1.3 spec and ARB_multisample.
1015    */
1016
1017   PREFER_SMALLER(visualSelectGroup);
1018
1019   /* The sort order for the visualRating is GLX_NONE, GLX_SLOW, and
1020    * GLX_NON_CONFORMANT_CONFIG.  It just so happens that this is the
1021    * numerical sort order of the enums (0x8000, 0x8001, and 0x800D).
1022    */
1023   PREFER_SMALLER(visualRating);
1024
1025   /* This isn't quite right.  It is supposed to compare the sum of the
1026    * components the user specifically set minimums for.
1027    */
1028   PREFER_LARGER_OR_ZERO(redBits);
1029   PREFER_LARGER_OR_ZERO(greenBits);
1030   PREFER_LARGER_OR_ZERO(blueBits);
1031   PREFER_LARGER_OR_ZERO(alphaBits);
1032
1033   PREFER_SMALLER(rgbBits);
1034
1035   if (((*a)->doubleBufferMode != (*b)->doubleBufferMode)) {
1036      /* Prefer single-buffer.
1037       */
1038      return (!(*a)->doubleBufferMode) ? -1 : 1;
1039   }
1040
1041   PREFER_SMALLER(numAuxBuffers);
1042
1043   PREFER_LARGER_OR_ZERO(depthBits);
1044   PREFER_SMALLER(stencilBits);
1045
1046   /* This isn't quite right.  It is supposed to compare the sum of the
1047    * components the user specifically set minimums for.
1048    */
1049   PREFER_LARGER_OR_ZERO(accumRedBits);
1050   PREFER_LARGER_OR_ZERO(accumGreenBits);
1051   PREFER_LARGER_OR_ZERO(accumBlueBits);
1052   PREFER_LARGER_OR_ZERO(accumAlphaBits);
1053
1054   PREFER_SMALLER(visualType);
1055
1056   /* None of the multisample specs say where this comparison should happen,
1057    * so I put it near the end.
1058    */
1059   PREFER_SMALLER(sampleBuffers);
1060   PREFER_SMALLER(samples);
1061
1062   /* None of the pbuffer or fbconfig specs say that this comparison needs
1063    * to happen at all, but it seems like it should.
1064    */
1065   PREFER_LARGER(maxPbufferWidth);
1066   PREFER_LARGER(maxPbufferHeight);
1067   PREFER_LARGER(maxPbufferPixels);
1068
1069   return 0;
1070}
1071
1072
1073/**
1074 * Selects and sorts a subset of the supplied configs based on the attributes.
1075 * This function forms to basis of \c glXChooseVisual, \c glXChooseFBConfig,
1076 * and \c glXChooseFBConfigSGIX.
1077 *
1078 * \param configs   Array of pointers to possible configs.  The elements of
1079 *                  this array that do not meet the criteria will be set to
1080 *                  NULL.  The remaining elements will be sorted according to
1081 *                  the various visual / FBConfig selection rules.
1082 * \param num_configs  Number of elements in the \c configs array.
1083 * \param attribList   Attributes used select from \c configs.  This array is
1084 *                     terminated by a \c None tag.  The array can either take
1085 *                     the form expected by \c glXChooseVisual (where boolean
1086 *                     tags do not have a value) or by \c glXChooseFBConfig
1087 *                     (where every tag has a value).
1088 * \param fbconfig_style_tags  Selects whether \c attribList is in
1089 *                             \c glXChooseVisual style or
1090 *                             \c glXChooseFBConfig style.
1091 * \returns The number of valid elements left in \c configs.
1092 *
1093 * \sa glXChooseVisual, glXChooseFBConfig, glXChooseFBConfigSGIX
1094 */
1095static int
1096choose_visual(struct glx_config ** configs, int num_configs,
1097              const int *attribList, GLboolean fbconfig_style_tags)
1098{
1099   struct glx_config test_config;
1100   int base;
1101   int i;
1102
1103   /* This is a fairly direct implementation of the selection method
1104    * described by GLX_SGIX_fbconfig.  Start by culling out all the
1105    * configs that are not compatible with the selected parameter
1106    * list.
1107    */
1108
1109   init_fbconfig_for_chooser(&test_config, fbconfig_style_tags);
1110   __glXInitializeVisualConfigFromTags(&test_config, 512,
1111                                       (const INT32 *) attribList,
1112                                       GL_TRUE, fbconfig_style_tags);
1113
1114   base = 0;
1115   for (i = 0; i < num_configs; i++) {
1116      if (fbconfigs_compatible(&test_config, configs[i])) {
1117         configs[base] = configs[i];
1118         base++;
1119      }
1120   }
1121
1122   if (base == 0) {
1123      return 0;
1124   }
1125
1126   if (base < num_configs) {
1127      (void) memset(&configs[base], 0, sizeof(void *) * (num_configs - base));
1128   }
1129
1130   /* After the incompatible configs are removed, the resulting
1131    * list is sorted according to the rules set out in the various
1132    * specifications.
1133    */
1134
1135   qsort(configs, base, sizeof(struct glx_config *),
1136         (int (*)(const void *, const void *)) fbconfig_compare);
1137   return base;
1138}
1139
1140
1141
1142
1143/*
1144** Return the visual that best matches the template.  Return None if no
1145** visual matches the template.
1146*/
1147_X_EXPORT XVisualInfo *
1148glXChooseVisual(Display * dpy, int screen, int *attribList)
1149{
1150   XVisualInfo *visualList = NULL;
1151   struct glx_display *priv;
1152   struct glx_screen *psc;
1153   struct glx_config test_config;
1154   struct glx_config *config;
1155   struct glx_config *best_config = NULL;
1156
1157   /*
1158    ** Get a list of all visuals, return if list is empty
1159    */
1160   if (GetGLXPrivScreenConfig(dpy, screen, &priv, &psc) != Success) {
1161      return None;
1162   }
1163
1164
1165   /*
1166    ** Build a template from the defaults and the attribute list
1167    ** Free visual list and return if an unexpected token is encountered
1168    */
1169   init_fbconfig_for_chooser(&test_config, GL_FALSE);
1170   __glXInitializeVisualConfigFromTags(&test_config, 512,
1171                                       (const INT32 *) attribList,
1172                                       GL_TRUE, GL_FALSE);
1173
1174   /*
1175    ** Eliminate visuals that don't meet minimum requirements
1176    ** Compute a score for those that do
1177    ** Remember which visual, if any, got the highest score
1178    ** If no visual is acceptable, return None
1179    ** Otherwise, create an XVisualInfo list with just the selected X visual
1180    ** and return this.
1181    */
1182   for (config = psc->visuals; config != NULL; config = config->next) {
1183      if (fbconfigs_compatible(&test_config, config)
1184          && ((best_config == NULL) ||
1185              (fbconfig_compare (&config, &best_config) < 0))) {
1186         XVisualInfo visualTemplate;
1187         XVisualInfo *newList;
1188         int i;
1189
1190         visualTemplate.screen = screen;
1191         visualTemplate.visualid = config->visualID;
1192         newList = XGetVisualInfo(dpy, VisualScreenMask | VisualIDMask,
1193                                  &visualTemplate, &i);
1194
1195         if (newList) {
1196            Xfree(visualList);
1197            visualList = newList;
1198            best_config = config;
1199         }
1200      }
1201   }
1202
1203#ifdef GLX_USE_APPLEGL
1204   if(visualList && getenv("LIBGL_DUMP_VISUALID")) {
1205      printf("visualid 0x%lx\n", visualList[0].visualid);
1206   }
1207#endif
1208
1209   return visualList;
1210}
1211
1212
1213_X_EXPORT const char *
1214glXQueryExtensionsString(Display * dpy, int screen)
1215{
1216   struct glx_screen *psc;
1217   struct glx_display *priv;
1218
1219   if (GetGLXPrivScreenConfig(dpy, screen, &priv, &psc) != Success) {
1220      return NULL;
1221   }
1222
1223   if (!psc->effectiveGLXexts) {
1224      if (!psc->serverGLXexts) {
1225         psc->serverGLXexts =
1226            __glXQueryServerString(dpy, priv->majorOpcode, screen,
1227                                   GLX_EXTENSIONS);
1228      }
1229
1230      __glXCalculateUsableExtensions(psc,
1231#if defined(GLX_DIRECT_RENDERING) && !defined(GLX_USE_APPLEGL)
1232                                     (psc->driScreen != NULL),
1233#else
1234                                     GL_FALSE,
1235#endif
1236                                     priv->minorVersion);
1237   }
1238
1239   return psc->effectiveGLXexts;
1240}
1241
1242_X_EXPORT const char *
1243glXGetClientString(Display * dpy, int name)
1244{
1245   (void) dpy;
1246
1247   switch (name) {
1248   case GLX_VENDOR:
1249      return (__glXGLXClientVendorName);
1250   case GLX_VERSION:
1251      return (__glXGLXClientVersion);
1252   case GLX_EXTENSIONS:
1253      return (__glXGetClientExtensions());
1254   default:
1255      return NULL;
1256   }
1257}
1258
1259_X_EXPORT const char *
1260glXQueryServerString(Display * dpy, int screen, int name)
1261{
1262   struct glx_screen *psc;
1263   struct glx_display *priv;
1264   const char **str;
1265
1266
1267   if (GetGLXPrivScreenConfig(dpy, screen, &priv, &psc) != Success) {
1268      return NULL;
1269   }
1270
1271   switch (name) {
1272   case GLX_VENDOR:
1273      str = &priv->serverGLXvendor;
1274      break;
1275   case GLX_VERSION:
1276      str = &priv->serverGLXversion;
1277      break;
1278   case GLX_EXTENSIONS:
1279      str = &psc->serverGLXexts;
1280      break;
1281   default:
1282      return NULL;
1283   }
1284
1285   if (*str == NULL) {
1286      *str = __glXQueryServerString(dpy, priv->majorOpcode, screen, name);
1287   }
1288
1289   return *str;
1290}
1291
1292void
1293__glXClientInfo(Display * dpy, int opcode)
1294{
1295   char *ext_str = __glXGetClientGLExtensionString();
1296   int size = strlen(ext_str) + 1;
1297
1298#ifdef USE_XCB
1299   xcb_connection_t *c = XGetXCBConnection(dpy);
1300   xcb_glx_client_info(c,
1301                       GLX_MAJOR_VERSION, GLX_MINOR_VERSION, size, ext_str);
1302#else
1303   xGLXClientInfoReq *req;
1304
1305   /* Send the glXClientInfo request */
1306   LockDisplay(dpy);
1307   GetReq(GLXClientInfo, req);
1308   req->reqType = opcode;
1309   req->glxCode = X_GLXClientInfo;
1310   req->major = GLX_MAJOR_VERSION;
1311   req->minor = GLX_MINOR_VERSION;
1312
1313   req->length += (size + 3) >> 2;
1314   req->numbytes = size;
1315   Data(dpy, ext_str, size);
1316
1317   UnlockDisplay(dpy);
1318   SyncHandle();
1319#endif /* USE_XCB */
1320
1321   Xfree(ext_str);
1322}
1323
1324
1325/*
1326** EXT_import_context
1327*/
1328
1329_X_EXPORT Display *
1330glXGetCurrentDisplay(void)
1331{
1332   struct glx_context *gc = __glXGetCurrentContext();
1333   if (NULL == gc)
1334      return NULL;
1335   return gc->currentDpy;
1336}
1337
1338_X_EXPORT
1339GLX_ALIAS(Display *, glXGetCurrentDisplayEXT, (void), (),
1340          glXGetCurrentDisplay)
1341
1342#ifndef GLX_USE_APPLEGL
1343_X_EXPORT GLXContext
1344glXImportContextEXT(Display *dpy, GLXContextID contextID)
1345{
1346   struct glx_display *priv = __glXInitialize(dpy);
1347   struct glx_screen *psc;
1348   xGLXQueryContextReply reply;
1349   CARD8 opcode;
1350   struct glx_context *ctx;
1351   int propList[__GLX_MAX_CONTEXT_PROPS * 2], *pProp, nPropListBytes;
1352   int i, renderType;
1353   XID share;
1354   struct glx_config *mode;
1355
1356   if (contextID == None || __glXIsDirect(dpy, contextID))
1357      return NULL;
1358
1359   opcode = __glXSetupForCommand(dpy);
1360   if (!opcode)
1361      return 0;
1362
1363   /* Send the glXQueryContextInfoEXT request */
1364   LockDisplay(dpy);
1365
1366   if (priv->majorVersion > 1 || priv->minorVersion >= 3) {
1367      xGLXQueryContextReq *req;
1368
1369      GetReq(GLXQueryContext, req);
1370
1371      req->reqType = opcode;
1372      req->glxCode = X_GLXQueryContext;
1373      req->context = contextID;
1374   }
1375   else {
1376      xGLXVendorPrivateReq *vpreq;
1377      xGLXQueryContextInfoEXTReq *req;
1378
1379      GetReqExtra(GLXVendorPrivate,
1380		  sz_xGLXQueryContextInfoEXTReq - sz_xGLXVendorPrivateReq,
1381		  vpreq);
1382      req = (xGLXQueryContextInfoEXTReq *) vpreq;
1383      req->reqType = opcode;
1384      req->glxCode = X_GLXVendorPrivateWithReply;
1385      req->vendorCode = X_GLXvop_QueryContextInfoEXT;
1386      req->context = contextID;
1387   }
1388
1389   _XReply(dpy, (xReply *) & reply, 0, False);
1390
1391   if (reply.n <= __GLX_MAX_CONTEXT_PROPS)
1392      nPropListBytes = reply.n * 2 * sizeof propList[0];
1393   else
1394      nPropListBytes = 0;
1395   _XRead(dpy, (char *) propList, nPropListBytes);
1396   UnlockDisplay(dpy);
1397   SyncHandle();
1398
1399   /* Look up screen first so we can look up visuals/fbconfigs later */
1400   psc = NULL;
1401   for (i = 0, pProp = propList; i < reply.n; i++, pProp += 2)
1402      if (pProp[0] == GLX_SCREEN)
1403	 psc = GetGLXScreenConfigs(dpy, pProp[1]);
1404   if (psc == NULL)
1405      return NULL;
1406
1407   share = None;
1408   mode = NULL;
1409   renderType = 0;
1410   pProp = propList;
1411
1412   for (i = 0, pProp = propList; i < reply.n; i++, pProp += 2)
1413      switch (pProp[0]) {
1414      case GLX_SHARE_CONTEXT_EXT:
1415	 share = pProp[1];
1416	 break;
1417      case GLX_VISUAL_ID_EXT:
1418	 mode = glx_config_find_visual(psc->visuals, pProp[1]);
1419	 break;
1420      case GLX_FBCONFIG_ID:
1421	 mode = glx_config_find_fbconfig(psc->configs, pProp[1]);
1422	 break;
1423      case GLX_RENDER_TYPE:
1424	 renderType = pProp[1];
1425	 break;
1426      }
1427
1428   if (mode == NULL)
1429      return NULL;
1430
1431   ctx = indirect_create_context(psc, mode, NULL, renderType);
1432   if (ctx == NULL)
1433      return NULL;
1434
1435   ctx->xid = contextID;
1436   ctx->imported = GL_TRUE;
1437   ctx->share_xid = share;
1438
1439   return (GLXContext) ctx;
1440}
1441
1442#endif
1443
1444_X_EXPORT int
1445glXQueryContext(Display * dpy, GLXContext ctx_user, int attribute, int *value)
1446{
1447   struct glx_context *ctx = (struct glx_context *) ctx_user;
1448
1449   switch (attribute) {
1450      case GLX_SHARE_CONTEXT_EXT:
1451      *value = ctx->share_xid;
1452      break;
1453   case GLX_VISUAL_ID_EXT:
1454      *value = ctx->config ? ctx->config->visualID : None;
1455      break;
1456   case GLX_SCREEN:
1457      *value = ctx->screen;
1458      break;
1459   case GLX_FBCONFIG_ID:
1460      *value = ctx->config ? ctx->config->fbconfigID : None;
1461      break;
1462   case GLX_RENDER_TYPE:
1463      *value = ctx->renderType;
1464      break;
1465   default:
1466      return GLX_BAD_ATTRIBUTE;
1467   }
1468   return Success;
1469}
1470
1471_X_EXPORT
1472GLX_ALIAS(int, glXQueryContextInfoEXT,
1473          (Display * dpy, GLXContext ctx, int attribute, int *value),
1474          (dpy, ctx, attribute, value), glXQueryContext)
1475
1476_X_EXPORT GLXContextID glXGetContextIDEXT(const GLXContext ctx_user)
1477{
1478   struct glx_context *ctx = (struct glx_context *) ctx_user;
1479
1480   return ctx->xid;
1481}
1482
1483_X_EXPORT void
1484glXFreeContextEXT(Display * dpy, GLXContext ctx)
1485{
1486   DestroyContext(dpy, ctx);
1487}
1488
1489
1490_X_EXPORT GLXFBConfig *
1491glXChooseFBConfig(Display * dpy, int screen,
1492                  const int *attribList, int *nitems)
1493{
1494   struct glx_config **config_list;
1495   int list_size;
1496
1497
1498   config_list = (struct glx_config **)
1499      glXGetFBConfigs(dpy, screen, &list_size);
1500
1501   if ((config_list != NULL) && (list_size > 0) && (attribList != NULL)) {
1502      list_size = choose_visual(config_list, list_size, attribList, GL_TRUE);
1503      if (list_size == 0) {
1504         XFree(config_list);
1505         config_list = NULL;
1506      }
1507   }
1508
1509   *nitems = list_size;
1510   return (GLXFBConfig *) config_list;
1511}
1512
1513
1514_X_EXPORT GLXContext
1515glXCreateNewContext(Display * dpy, GLXFBConfig fbconfig,
1516                    int renderType, GLXContext shareList, Bool allowDirect)
1517{
1518   struct glx_config *config = (struct glx_config *) fbconfig;
1519
1520   return CreateContext(dpy, config->fbconfigID, config, shareList,
1521			allowDirect, X_GLXCreateNewContext, renderType,
1522			config->screen);
1523}
1524
1525
1526_X_EXPORT GLXDrawable
1527glXGetCurrentReadDrawable(void)
1528{
1529   struct glx_context *gc = __glXGetCurrentContext();
1530
1531   return gc->currentReadable;
1532}
1533
1534
1535_X_EXPORT GLXFBConfig *
1536glXGetFBConfigs(Display * dpy, int screen, int *nelements)
1537{
1538   struct glx_display *priv = __glXInitialize(dpy);
1539   struct glx_config **config_list = NULL;
1540   struct glx_config *config;
1541   unsigned num_configs = 0;
1542   int i;
1543
1544   *nelements = 0;
1545   if (priv && (priv->screens != NULL)
1546       && (screen >= 0) && (screen <= ScreenCount(dpy))
1547       && (priv->screens[screen]->configs != NULL)
1548       && (priv->screens[screen]->configs->fbconfigID
1549	   != (int) GLX_DONT_CARE)) {
1550
1551      for (config = priv->screens[screen]->configs; config != NULL;
1552           config = config->next) {
1553         if (config->fbconfigID != (int) GLX_DONT_CARE) {
1554            num_configs++;
1555         }
1556      }
1557
1558      config_list = Xmalloc(num_configs * sizeof *config_list);
1559      if (config_list != NULL) {
1560         *nelements = num_configs;
1561         i = 0;
1562         for (config = priv->screens[screen]->configs; config != NULL;
1563              config = config->next) {
1564            if (config->fbconfigID != (int) GLX_DONT_CARE) {
1565               config_list[i] = config;
1566               i++;
1567            }
1568         }
1569      }
1570   }
1571
1572   return (GLXFBConfig *) config_list;
1573}
1574
1575
1576_X_EXPORT int
1577glXGetFBConfigAttrib(Display * dpy, GLXFBConfig fbconfig,
1578                     int attribute, int *value)
1579{
1580   struct glx_config *config = ValidateGLXFBConfig(dpy, fbconfig);
1581
1582   if (config == NULL)
1583      return GLXBadFBConfig;
1584
1585   return glx_config_get(config, attribute, value);
1586}
1587
1588
1589_X_EXPORT XVisualInfo *
1590glXGetVisualFromFBConfig(Display * dpy, GLXFBConfig fbconfig)
1591{
1592   XVisualInfo visualTemplate;
1593   struct glx_config *config = (struct glx_config *) fbconfig;
1594   int count;
1595
1596   /*
1597    ** Get a list of all visuals, return if list is empty
1598    */
1599   visualTemplate.visualid = config->visualID;
1600   return XGetVisualInfo(dpy, VisualIDMask, &visualTemplate, &count);
1601}
1602
1603#ifndef GLX_USE_APPLEGL
1604/*
1605** GLX_SGI_swap_control
1606*/
1607static int
1608__glXSwapIntervalSGI(int interval)
1609{
1610   xGLXVendorPrivateReq *req;
1611   struct glx_context *gc = __glXGetCurrentContext();
1612   struct glx_screen *psc;
1613   Display *dpy;
1614   CARD32 *interval_ptr;
1615   CARD8 opcode;
1616
1617   if (gc == NULL) {
1618      return GLX_BAD_CONTEXT;
1619   }
1620
1621   if (interval <= 0) {
1622      return GLX_BAD_VALUE;
1623   }
1624
1625   psc = GetGLXScreenConfigs( gc->currentDpy, gc->screen);
1626
1627#ifdef GLX_DIRECT_RENDERING
1628   if (gc->isDirect && psc->driScreen && psc->driScreen->setSwapInterval) {
1629      __GLXDRIdrawable *pdraw =
1630	 GetGLXDRIDrawable(gc->currentDpy, gc->currentDrawable);
1631      psc->driScreen->setSwapInterval(pdraw, interval);
1632      return 0;
1633   }
1634#endif
1635
1636   dpy = gc->currentDpy;
1637   opcode = __glXSetupForCommand(dpy);
1638   if (!opcode) {
1639      return 0;
1640   }
1641
1642   /* Send the glXSwapIntervalSGI request */
1643   LockDisplay(dpy);
1644   GetReqExtra(GLXVendorPrivate, sizeof(CARD32), req);
1645   req->reqType = opcode;
1646   req->glxCode = X_GLXVendorPrivate;
1647   req->vendorCode = X_GLXvop_SwapIntervalSGI;
1648   req->contextTag = gc->currentContextTag;
1649
1650   interval_ptr = (CARD32 *) (req + 1);
1651   *interval_ptr = interval;
1652
1653   UnlockDisplay(dpy);
1654   SyncHandle();
1655   XFlush(dpy);
1656
1657   return 0;
1658}
1659
1660
1661/*
1662** GLX_MESA_swap_control
1663*/
1664static int
1665__glXSwapIntervalMESA(unsigned int interval)
1666{
1667#ifdef GLX_DIRECT_RENDERING
1668   struct glx_context *gc = __glXGetCurrentContext();
1669
1670   if (gc != NULL && gc->isDirect) {
1671      struct glx_screen *psc;
1672
1673      psc = GetGLXScreenConfigs( gc->currentDpy, gc->screen);
1674      if (psc->driScreen && psc->driScreen->setSwapInterval) {
1675         __GLXDRIdrawable *pdraw =
1676	    GetGLXDRIDrawable(gc->currentDpy, gc->currentDrawable);
1677	 return psc->driScreen->setSwapInterval(pdraw, interval);
1678      }
1679   }
1680#endif
1681
1682   return GLX_BAD_CONTEXT;
1683}
1684
1685
1686static int
1687__glXGetSwapIntervalMESA(void)
1688{
1689#ifdef GLX_DIRECT_RENDERING
1690   struct glx_context *gc = __glXGetCurrentContext();
1691
1692   if (gc != NULL && gc->isDirect) {
1693      struct glx_screen *psc;
1694
1695      psc = GetGLXScreenConfigs( gc->currentDpy, gc->screen);
1696      if (psc->driScreen && psc->driScreen->getSwapInterval) {
1697         __GLXDRIdrawable *pdraw =
1698	    GetGLXDRIDrawable(gc->currentDpy, gc->currentDrawable);
1699	 return psc->driScreen->getSwapInterval(pdraw);
1700      }
1701   }
1702#endif
1703
1704   return 0;
1705}
1706
1707
1708/*
1709** GLX_SGI_video_sync
1710*/
1711static int
1712__glXGetVideoSyncSGI(unsigned int *count)
1713{
1714   int64_t ust, msc, sbc;
1715   int ret;
1716   struct glx_context *gc = __glXGetCurrentContext();
1717   struct glx_screen *psc;
1718#ifdef GLX_DIRECT_RENDERING
1719   __GLXDRIdrawable *pdraw;
1720#endif
1721
1722   if (!gc)
1723      return GLX_BAD_CONTEXT;
1724
1725#ifdef GLX_DIRECT_RENDERING
1726   if (!gc->isDirect)
1727      return GLX_BAD_CONTEXT;
1728#endif
1729
1730   psc = GetGLXScreenConfigs(gc->currentDpy, gc->screen);
1731#ifdef GLX_DIRECT_RENDERING
1732   pdraw = GetGLXDRIDrawable(gc->currentDpy, gc->currentDrawable);
1733#endif
1734
1735   /* FIXME: Looking at the GLX_SGI_video_sync spec in the extension registry,
1736    * FIXME: there should be a GLX encoding for this call.  I can find no
1737    * FIXME: documentation for the GLX encoding.
1738    */
1739#ifdef GLX_DIRECT_RENDERING
1740   if (psc->driScreen && psc->driScreen->getDrawableMSC) {
1741      ret = psc->driScreen->getDrawableMSC(psc, pdraw, &ust, &msc, &sbc);
1742      *count = (unsigned) msc;
1743      return (ret == True) ? 0 : GLX_BAD_CONTEXT;
1744   }
1745#endif
1746
1747   return GLX_BAD_CONTEXT;
1748}
1749
1750static int
1751__glXWaitVideoSyncSGI(int divisor, int remainder, unsigned int *count)
1752{
1753   struct glx_context *gc = __glXGetCurrentContext();
1754   struct glx_screen *psc;
1755#ifdef GLX_DIRECT_RENDERING
1756   __GLXDRIdrawable *pdraw;
1757#endif
1758   int64_t ust, msc, sbc;
1759   int ret;
1760
1761   if (divisor <= 0 || remainder < 0)
1762      return GLX_BAD_VALUE;
1763
1764   if (!gc)
1765      return GLX_BAD_CONTEXT;
1766
1767#ifdef GLX_DIRECT_RENDERING
1768   if (!gc->isDirect)
1769      return GLX_BAD_CONTEXT;
1770#endif
1771
1772   psc = GetGLXScreenConfigs( gc->currentDpy, gc->screen);
1773#ifdef GLX_DIRECT_RENDERING
1774   pdraw = GetGLXDRIDrawable(gc->currentDpy, gc->currentDrawable);
1775#endif
1776
1777#ifdef GLX_DIRECT_RENDERING
1778   if (psc->driScreen && psc->driScreen->waitForMSC) {
1779      ret = psc->driScreen->waitForMSC(pdraw, 0, divisor, remainder, &ust, &msc,
1780				       &sbc);
1781      *count = (unsigned) msc;
1782      return (ret == True) ? 0 : GLX_BAD_CONTEXT;
1783   }
1784#endif
1785
1786   return GLX_BAD_CONTEXT;
1787}
1788
1789#endif /* GLX_USE_APPLEGL */
1790
1791/*
1792** GLX_SGIX_fbconfig
1793** Many of these functions are aliased to GLX 1.3 entry points in the
1794** GLX_functions table.
1795*/
1796
1797_X_EXPORT
1798GLX_ALIAS(int, glXGetFBConfigAttribSGIX,
1799          (Display * dpy, GLXFBConfigSGIX config, int attribute, int *value),
1800          (dpy, config, attribute, value), glXGetFBConfigAttrib)
1801
1802_X_EXPORT GLX_ALIAS(GLXFBConfigSGIX *, glXChooseFBConfigSGIX,
1803                 (Display * dpy, int screen, int *attrib_list,
1804                  int *nelements), (dpy, screen, attrib_list, nelements),
1805                 glXChooseFBConfig)
1806
1807_X_EXPORT GLX_ALIAS(XVisualInfo *, glXGetVisualFromFBConfigSGIX,
1808                 (Display * dpy, GLXFBConfigSGIX config),
1809                 (dpy, config), glXGetVisualFromFBConfig)
1810
1811_X_EXPORT GLXPixmap
1812glXCreateGLXPixmapWithConfigSGIX(Display * dpy,
1813                                 GLXFBConfigSGIX fbconfig,
1814                                 Pixmap pixmap)
1815{
1816#ifndef GLX_USE_APPLEGL
1817   xGLXVendorPrivateWithReplyReq *vpreq;
1818   xGLXCreateGLXPixmapWithConfigSGIXReq *req;
1819   GLXPixmap xid = None;
1820   CARD8 opcode;
1821   struct glx_screen *psc;
1822#endif
1823   struct glx_config *config = (struct glx_config *) fbconfig;
1824
1825
1826   if ((dpy == NULL) || (config == NULL)) {
1827      return None;
1828   }
1829#ifdef GLX_USE_APPLEGL
1830   if(apple_glx_pixmap_create(dpy, config->screen, pixmap, config))
1831      return None;
1832   return pixmap;
1833#else
1834
1835   psc = GetGLXScreenConfigs(dpy, config->screen);
1836   if ((psc != NULL)
1837       && __glXExtensionBitIsEnabled(psc, SGIX_fbconfig_bit)) {
1838      opcode = __glXSetupForCommand(dpy);
1839      if (!opcode) {
1840         return None;
1841      }
1842
1843      /* Send the glXCreateGLXPixmapWithConfigSGIX request */
1844      LockDisplay(dpy);
1845      GetReqExtra(GLXVendorPrivateWithReply,
1846                  sz_xGLXCreateGLXPixmapWithConfigSGIXReq -
1847                  sz_xGLXVendorPrivateWithReplyReq, vpreq);
1848      req = (xGLXCreateGLXPixmapWithConfigSGIXReq *) vpreq;
1849      req->reqType = opcode;
1850      req->glxCode = X_GLXVendorPrivateWithReply;
1851      req->vendorCode = X_GLXvop_CreateGLXPixmapWithConfigSGIX;
1852      req->screen = config->screen;
1853      req->fbconfig = config->fbconfigID;
1854      req->pixmap = pixmap;
1855      req->glxpixmap = xid = XAllocID(dpy);
1856      UnlockDisplay(dpy);
1857      SyncHandle();
1858   }
1859
1860   return xid;
1861#endif
1862}
1863
1864_X_EXPORT GLXContext
1865glXCreateContextWithConfigSGIX(Display * dpy,
1866                               GLXFBConfigSGIX fbconfig, int renderType,
1867                               GLXContext shareList, Bool allowDirect)
1868{
1869   GLXContext gc = NULL;
1870   struct glx_config *config = (struct glx_config *) fbconfig;
1871   struct glx_screen *psc;
1872
1873
1874   if ((dpy == NULL) || (config == NULL)) {
1875      return None;
1876   }
1877
1878   psc = GetGLXScreenConfigs(dpy, config->screen);
1879   if ((psc != NULL)
1880       && __glXExtensionBitIsEnabled(psc, SGIX_fbconfig_bit)) {
1881      gc = CreateContext(dpy, config->fbconfigID, config, shareList,
1882                         allowDirect,
1883			 X_GLXvop_CreateContextWithConfigSGIX, renderType,
1884			 config->screen);
1885   }
1886
1887   return gc;
1888}
1889
1890
1891_X_EXPORT GLXFBConfigSGIX
1892glXGetFBConfigFromVisualSGIX(Display * dpy, XVisualInfo * vis)
1893{
1894   struct glx_display *priv;
1895   struct glx_screen *psc = NULL;
1896
1897   if ((GetGLXPrivScreenConfig(dpy, vis->screen, &priv, &psc) == Success)
1898       && __glXExtensionBitIsEnabled(psc, SGIX_fbconfig_bit)
1899       && (psc->configs->fbconfigID != (int) GLX_DONT_CARE)) {
1900      return (GLXFBConfigSGIX) glx_config_find_visual(psc->configs,
1901						      vis->visualid);
1902   }
1903
1904   return NULL;
1905}
1906
1907#ifndef GLX_USE_APPLEGL
1908/*
1909** GLX_SGIX_swap_group
1910*/
1911static void
1912__glXJoinSwapGroupSGIX(Display * dpy, GLXDrawable drawable,
1913                       GLXDrawable member)
1914{
1915   (void) dpy;
1916   (void) drawable;
1917   (void) member;
1918}
1919
1920
1921/*
1922** GLX_SGIX_swap_barrier
1923*/
1924static void
1925__glXBindSwapBarrierSGIX(Display * dpy, GLXDrawable drawable, int barrier)
1926{
1927   (void) dpy;
1928   (void) drawable;
1929   (void) barrier;
1930}
1931
1932static Bool
1933__glXQueryMaxSwapBarriersSGIX(Display * dpy, int screen, int *max)
1934{
1935   (void) dpy;
1936   (void) screen;
1937   (void) max;
1938   return False;
1939}
1940
1941
1942/*
1943** GLX_OML_sync_control
1944*/
1945static Bool
1946__glXGetSyncValuesOML(Display * dpy, GLXDrawable drawable,
1947                      int64_t * ust, int64_t * msc, int64_t * sbc)
1948{
1949   struct glx_display * const priv = __glXInitialize(dpy);
1950   int ret;
1951#ifdef GLX_DIRECT_RENDERING
1952   __GLXDRIdrawable *pdraw;
1953#endif
1954   struct glx_screen *psc;
1955
1956   if (!priv)
1957      return False;
1958
1959#ifdef GLX_DIRECT_RENDERING
1960   pdraw = GetGLXDRIDrawable(dpy, drawable);
1961   psc = pdraw ? pdraw->psc : NULL;
1962   if (pdraw && psc->driScreen->getDrawableMSC) {
1963      ret = psc->driScreen->getDrawableMSC(psc, pdraw, ust, msc, sbc);
1964      return ret;
1965   }
1966#endif
1967
1968   return False;
1969}
1970
1971#if defined(GLX_DIRECT_RENDERING) && !defined(GLX_USE_APPLEGL)
1972_X_HIDDEN GLboolean
1973__glxGetMscRate(__GLXDRIdrawable *glxDraw,
1974		int32_t * numerator, int32_t * denominator)
1975{
1976#ifdef XF86VIDMODE
1977   struct glx_screen *psc;
1978   XF86VidModeModeLine mode_line;
1979   int dot_clock;
1980   int i;
1981
1982   psc = glxDraw->psc;
1983   if (XF86VidModeQueryVersion(psc->dpy, &i, &i) &&
1984       XF86VidModeGetModeLine(psc->dpy, psc->scr, &dot_clock, &mode_line)) {
1985      unsigned n = dot_clock * 1000;
1986      unsigned d = mode_line.vtotal * mode_line.htotal;
1987
1988# define V_INTERLACE 0x010
1989# define V_DBLSCAN   0x020
1990
1991      if (mode_line.flags & V_INTERLACE)
1992         n *= 2;
1993      else if (mode_line.flags & V_DBLSCAN)
1994         d *= 2;
1995
1996      /* The OML_sync_control spec requires that if the refresh rate is a
1997       * whole number, that the returned numerator be equal to the refresh
1998       * rate and the denominator be 1.
1999       */
2000
2001      if (n % d == 0) {
2002         n /= d;
2003         d = 1;
2004      }
2005      else {
2006         static const unsigned f[] = { 13, 11, 7, 5, 3, 2, 0 };
2007
2008         /* This is a poor man's way to reduce a fraction.  It's far from
2009          * perfect, but it will work well enough for this situation.
2010          */
2011
2012         for (i = 0; f[i] != 0; i++) {
2013            while (n % f[i] == 0 && d % f[i] == 0) {
2014               d /= f[i];
2015               n /= f[i];
2016            }
2017         }
2018      }
2019
2020      *numerator = n;
2021      *denominator = d;
2022
2023      return True;
2024   }
2025   else
2026#endif
2027
2028   return False;
2029}
2030#endif
2031
2032/**
2033 * Determine the refresh rate of the specified drawable and display.
2034 *
2035 * \param dpy          Display whose refresh rate is to be determined.
2036 * \param drawable     Drawable whose refresh rate is to be determined.
2037 * \param numerator    Numerator of the refresh rate.
2038 * \param demoninator  Denominator of the refresh rate.
2039 * \return  If the refresh rate for the specified display and drawable could
2040 *          be calculated, True is returned.  Otherwise False is returned.
2041 *
2042 * \note This function is implemented entirely client-side.  A lot of other
2043 *       functionality is required to export GLX_OML_sync_control, so on
2044 *       XFree86 this function can be called for direct-rendering contexts
2045 *       when GLX_OML_sync_control appears in the client extension string.
2046 */
2047
2048_X_HIDDEN GLboolean
2049__glXGetMscRateOML(Display * dpy, GLXDrawable drawable,
2050                   int32_t * numerator, int32_t * denominator)
2051{
2052#if defined( GLX_DIRECT_RENDERING ) && defined( XF86VIDMODE )
2053   __GLXDRIdrawable *draw = GetGLXDRIDrawable(dpy, drawable);
2054
2055   if (draw == NULL)
2056      return False;
2057
2058   return __glxGetMscRate(draw, numerator, denominator);
2059#else
2060   (void) dpy;
2061   (void) drawable;
2062   (void) numerator;
2063   (void) denominator;
2064#endif
2065   return False;
2066}
2067
2068
2069static int64_t
2070__glXSwapBuffersMscOML(Display * dpy, GLXDrawable drawable,
2071                       int64_t target_msc, int64_t divisor, int64_t remainder)
2072{
2073   struct glx_context *gc = __glXGetCurrentContext();
2074#ifdef GLX_DIRECT_RENDERING
2075   __GLXDRIdrawable *pdraw = GetGLXDRIDrawable(dpy, drawable);
2076   struct glx_screen *psc = pdraw ? pdraw->psc : NULL;
2077#endif
2078
2079   if (!gc) /* no GLX for this */
2080      return -1;
2081
2082#ifdef GLX_DIRECT_RENDERING
2083   if (!pdraw || !gc->isDirect)
2084      return -1;
2085#endif
2086
2087   /* The OML_sync_control spec says these should "generate a GLX_BAD_VALUE
2088    * error", but it also says "It [glXSwapBuffersMscOML] will return a value
2089    * of -1 if the function failed because of errors detected in the input
2090    * parameters"
2091    */
2092   if (divisor < 0 || remainder < 0 || target_msc < 0)
2093      return -1;
2094   if (divisor > 0 && remainder >= divisor)
2095      return -1;
2096
2097   if (target_msc == 0 && divisor == 0 && remainder == 0)
2098      remainder = 1;
2099
2100#ifdef GLX_DIRECT_RENDERING
2101   if (psc->driScreen && psc->driScreen->swapBuffers)
2102      return (*psc->driScreen->swapBuffers)(pdraw, target_msc, divisor,
2103					    remainder);
2104#endif
2105
2106   return -1;
2107}
2108
2109
2110static Bool
2111__glXWaitForMscOML(Display * dpy, GLXDrawable drawable,
2112                   int64_t target_msc, int64_t divisor,
2113                   int64_t remainder, int64_t * ust,
2114                   int64_t * msc, int64_t * sbc)
2115{
2116#ifdef GLX_DIRECT_RENDERING
2117   __GLXDRIdrawable *pdraw = GetGLXDRIDrawable(dpy, drawable);
2118   struct glx_screen *psc = pdraw ? pdraw->psc : NULL;
2119   int ret;
2120#endif
2121
2122
2123   /* The OML_sync_control spec says these should "generate a GLX_BAD_VALUE
2124    * error", but the return type in the spec is Bool.
2125    */
2126   if (divisor < 0 || remainder < 0 || target_msc < 0)
2127      return False;
2128   if (divisor > 0 && remainder >= divisor)
2129      return False;
2130
2131#ifdef GLX_DIRECT_RENDERING
2132   if (pdraw && psc->driScreen && psc->driScreen->waitForMSC) {
2133      ret = psc->driScreen->waitForMSC(pdraw, target_msc, divisor, remainder,
2134				       ust, msc, sbc);
2135      return ret;
2136   }
2137#endif
2138
2139   return False;
2140}
2141
2142
2143static Bool
2144__glXWaitForSbcOML(Display * dpy, GLXDrawable drawable,
2145                   int64_t target_sbc, int64_t * ust,
2146                   int64_t * msc, int64_t * sbc)
2147{
2148#ifdef GLX_DIRECT_RENDERING
2149   __GLXDRIdrawable *pdraw = GetGLXDRIDrawable(dpy, drawable);
2150   struct glx_screen *psc = pdraw ? pdraw->psc : NULL;
2151   int ret;
2152#endif
2153
2154   /* The OML_sync_control spec says this should "generate a GLX_BAD_VALUE
2155    * error", but the return type in the spec is Bool.
2156    */
2157   if (target_sbc < 0)
2158      return False;
2159
2160#ifdef GLX_DIRECT_RENDERING
2161   if (pdraw && psc->driScreen && psc->driScreen->waitForSBC) {
2162      ret = psc->driScreen->waitForSBC(pdraw, target_sbc, ust, msc, sbc);
2163      return ret;
2164   }
2165#endif
2166
2167   return False;
2168}
2169
2170/*@}*/
2171
2172
2173/**
2174 * Mesa extension stubs.  These will help reduce portability problems.
2175 */
2176/*@{*/
2177
2178/**
2179 * Release all buffers associated with the specified GLX drawable.
2180 *
2181 * \todo
2182 * This function was intended for stand-alone Mesa.  The issue there is that
2183 * the library doesn't get any notification when a window is closed.  In
2184 * DRI there is a similar but slightly different issue.  When GLX 1.3 is
2185 * supported, there are 3 different functions to destroy a drawable.  It
2186 * should be possible to create GLX protocol (or have it determine which
2187 * protocol to use based on the type of the drawable) to have one function
2188 * do the work of 3.  For the direct-rendering case, this function could
2189 * just call the driver's \c __DRIdrawableRec::destroyDrawable function.
2190 * This would reduce the frequency with which \c __driGarbageCollectDrawables
2191 * would need to be used.  This really should be done as part of the new DRI
2192 * interface work.
2193 *
2194 * \sa http://oss.sgi.com/projects/ogl-sample/registry/MESA/release_buffers.txt
2195 *     __driGarbageCollectDrawables
2196 *     glXDestroyGLXPixmap
2197 *     glXDestroyPbuffer glXDestroyPixmap glXDestroyWindow
2198 *     glXDestroyGLXPbufferSGIX glXDestroyGLXVideoSourceSGIX
2199 */
2200static Bool
2201__glXReleaseBuffersMESA(Display * dpy, GLXDrawable d)
2202{
2203   (void) dpy;
2204   (void) d;
2205   return False;
2206}
2207
2208
2209_X_EXPORT GLXPixmap
2210glXCreateGLXPixmapMESA(Display * dpy, XVisualInfo * visual,
2211                       Pixmap pixmap, Colormap cmap)
2212{
2213   (void) dpy;
2214   (void) visual;
2215   (void) pixmap;
2216   (void) cmap;
2217   return 0;
2218}
2219
2220/*@}*/
2221
2222
2223/**
2224 * GLX_MESA_copy_sub_buffer
2225 */
2226#define X_GLXvop_CopySubBufferMESA 5154 /* temporary */
2227static void
2228__glXCopySubBufferMESA(Display * dpy, GLXDrawable drawable,
2229                       int x, int y, int width, int height)
2230{
2231   xGLXVendorPrivateReq *req;
2232   struct glx_context *gc;
2233   GLXContextTag tag;
2234   CARD32 *drawable_ptr;
2235   INT32 *x_ptr, *y_ptr, *w_ptr, *h_ptr;
2236   CARD8 opcode;
2237
2238#if defined(GLX_DIRECT_RENDERING) && !defined(GLX_USE_APPLEGL)
2239   __GLXDRIdrawable *pdraw = GetGLXDRIDrawable(dpy, drawable);
2240   if (pdraw != NULL) {
2241      struct glx_screen *psc = pdraw->psc;
2242      if (psc->driScreen->copySubBuffer != NULL) {
2243         glFlush();
2244         (*psc->driScreen->copySubBuffer) (pdraw, x, y, width, height);
2245      }
2246
2247      return;
2248   }
2249#endif
2250
2251   opcode = __glXSetupForCommand(dpy);
2252   if (!opcode)
2253      return;
2254
2255   /*
2256    ** The calling thread may or may not have a current context.  If it
2257    ** does, send the context tag so the server can do a flush.
2258    */
2259   gc = __glXGetCurrentContext();
2260   if ((gc != NULL) && (dpy == gc->currentDpy) &&
2261       ((drawable == gc->currentDrawable) ||
2262        (drawable == gc->currentReadable))) {
2263      tag = gc->currentContextTag;
2264   }
2265   else {
2266      tag = 0;
2267   }
2268
2269   LockDisplay(dpy);
2270   GetReqExtra(GLXVendorPrivate, sizeof(CARD32) + sizeof(INT32) * 4, req);
2271   req->reqType = opcode;
2272   req->glxCode = X_GLXVendorPrivate;
2273   req->vendorCode = X_GLXvop_CopySubBufferMESA;
2274   req->contextTag = tag;
2275
2276   drawable_ptr = (CARD32 *) (req + 1);
2277   x_ptr = (INT32 *) (drawable_ptr + 1);
2278   y_ptr = (INT32 *) (drawable_ptr + 2);
2279   w_ptr = (INT32 *) (drawable_ptr + 3);
2280   h_ptr = (INT32 *) (drawable_ptr + 4);
2281
2282   *drawable_ptr = drawable;
2283   *x_ptr = x;
2284   *y_ptr = y;
2285   *w_ptr = width;
2286   *h_ptr = height;
2287
2288   UnlockDisplay(dpy);
2289   SyncHandle();
2290}
2291
2292/*@{*/
2293static void
2294__glXBindTexImageEXT(Display * dpy,
2295                     GLXDrawable drawable, int buffer, const int *attrib_list)
2296{
2297   struct glx_context *gc = __glXGetCurrentContext();
2298
2299   if (gc == NULL || gc->vtable->bind_tex_image == NULL)
2300      return;
2301
2302   gc->vtable->bind_tex_image(dpy, drawable, buffer, attrib_list);
2303}
2304
2305static void
2306__glXReleaseTexImageEXT(Display * dpy, GLXDrawable drawable, int buffer)
2307{
2308   struct glx_context *gc = __glXGetCurrentContext();
2309
2310   if (gc == NULL || gc->vtable->release_tex_image == NULL)
2311      return;
2312
2313   gc->vtable->release_tex_image(dpy, drawable, buffer);
2314}
2315
2316/*@}*/
2317
2318#endif /* GLX_USE_APPLEGL */
2319
2320/**
2321 * \c strdup is actually not a standard ANSI C or POSIX routine.
2322 * Irix will not define it if ANSI mode is in effect.
2323 *
2324 * \sa strdup
2325 */
2326_X_HIDDEN char *
2327__glXstrdup(const char *str)
2328{
2329   char *copy;
2330   copy = (char *) Xmalloc(strlen(str) + 1);
2331   if (!copy)
2332      return NULL;
2333   strcpy(copy, str);
2334   return copy;
2335}
2336
2337/*
2338** glXGetProcAddress support
2339*/
2340
2341struct name_address_pair
2342{
2343   const char *Name;
2344   GLvoid *Address;
2345};
2346
2347#define GLX_FUNCTION(f) { # f, (GLvoid *) f }
2348#define GLX_FUNCTION2(n,f) { # n, (GLvoid *) f }
2349
2350static const struct name_address_pair GLX_functions[] = {
2351   /*** GLX_VERSION_1_0 ***/
2352   GLX_FUNCTION(glXChooseVisual),
2353   GLX_FUNCTION(glXCopyContext),
2354   GLX_FUNCTION(glXCreateContext),
2355   GLX_FUNCTION(glXCreateGLXPixmap),
2356   GLX_FUNCTION(glXDestroyContext),
2357   GLX_FUNCTION(glXDestroyGLXPixmap),
2358   GLX_FUNCTION(glXGetConfig),
2359   GLX_FUNCTION(glXGetCurrentContext),
2360   GLX_FUNCTION(glXGetCurrentDrawable),
2361   GLX_FUNCTION(glXIsDirect),
2362   GLX_FUNCTION(glXMakeCurrent),
2363   GLX_FUNCTION(glXQueryExtension),
2364   GLX_FUNCTION(glXQueryVersion),
2365   GLX_FUNCTION(glXSwapBuffers),
2366   GLX_FUNCTION(glXUseXFont),
2367   GLX_FUNCTION(glXWaitGL),
2368   GLX_FUNCTION(glXWaitX),
2369
2370   /*** GLX_VERSION_1_1 ***/
2371   GLX_FUNCTION(glXGetClientString),
2372   GLX_FUNCTION(glXQueryExtensionsString),
2373   GLX_FUNCTION(glXQueryServerString),
2374
2375   /*** GLX_VERSION_1_2 ***/
2376   GLX_FUNCTION(glXGetCurrentDisplay),
2377
2378   /*** GLX_VERSION_1_3 ***/
2379   GLX_FUNCTION(glXChooseFBConfig),
2380   GLX_FUNCTION(glXCreateNewContext),
2381   GLX_FUNCTION(glXCreatePbuffer),
2382   GLX_FUNCTION(glXCreatePixmap),
2383   GLX_FUNCTION(glXCreateWindow),
2384   GLX_FUNCTION(glXDestroyPbuffer),
2385   GLX_FUNCTION(glXDestroyPixmap),
2386   GLX_FUNCTION(glXDestroyWindow),
2387   GLX_FUNCTION(glXGetCurrentReadDrawable),
2388   GLX_FUNCTION(glXGetFBConfigAttrib),
2389   GLX_FUNCTION(glXGetFBConfigs),
2390   GLX_FUNCTION(glXGetSelectedEvent),
2391   GLX_FUNCTION(glXGetVisualFromFBConfig),
2392   GLX_FUNCTION(glXMakeContextCurrent),
2393   GLX_FUNCTION(glXQueryContext),
2394   GLX_FUNCTION(glXQueryDrawable),
2395   GLX_FUNCTION(glXSelectEvent),
2396
2397#ifndef GLX_USE_APPLEGL
2398   /*** GLX_SGI_swap_control ***/
2399   GLX_FUNCTION2(glXSwapIntervalSGI, __glXSwapIntervalSGI),
2400
2401   /*** GLX_SGI_video_sync ***/
2402   GLX_FUNCTION2(glXGetVideoSyncSGI, __glXGetVideoSyncSGI),
2403   GLX_FUNCTION2(glXWaitVideoSyncSGI, __glXWaitVideoSyncSGI),
2404
2405   /*** GLX_SGI_make_current_read ***/
2406   GLX_FUNCTION2(glXMakeCurrentReadSGI, glXMakeContextCurrent),
2407   GLX_FUNCTION2(glXGetCurrentReadDrawableSGI, glXGetCurrentReadDrawable),
2408
2409   /*** GLX_EXT_import_context ***/
2410   GLX_FUNCTION(glXFreeContextEXT),
2411   GLX_FUNCTION(glXGetContextIDEXT),
2412   GLX_FUNCTION2(glXGetCurrentDisplayEXT, glXGetCurrentDisplay),
2413   GLX_FUNCTION(glXImportContextEXT),
2414   GLX_FUNCTION2(glXQueryContextInfoEXT, glXQueryContext),
2415#endif
2416
2417   /*** GLX_SGIX_fbconfig ***/
2418   GLX_FUNCTION2(glXGetFBConfigAttribSGIX, glXGetFBConfigAttrib),
2419   GLX_FUNCTION2(glXChooseFBConfigSGIX, glXChooseFBConfig),
2420   GLX_FUNCTION(glXCreateGLXPixmapWithConfigSGIX),
2421   GLX_FUNCTION(glXCreateContextWithConfigSGIX),
2422   GLX_FUNCTION2(glXGetVisualFromFBConfigSGIX, glXGetVisualFromFBConfig),
2423   GLX_FUNCTION(glXGetFBConfigFromVisualSGIX),
2424
2425#ifndef GLX_USE_APPLEGL
2426   /*** GLX_SGIX_pbuffer ***/
2427   GLX_FUNCTION(glXCreateGLXPbufferSGIX),
2428   GLX_FUNCTION(glXDestroyGLXPbufferSGIX),
2429   GLX_FUNCTION(glXQueryGLXPbufferSGIX),
2430   GLX_FUNCTION(glXSelectEventSGIX),
2431   GLX_FUNCTION(glXGetSelectedEventSGIX),
2432
2433   /*** GLX_SGIX_swap_group ***/
2434   GLX_FUNCTION2(glXJoinSwapGroupSGIX, __glXJoinSwapGroupSGIX),
2435
2436   /*** GLX_SGIX_swap_barrier ***/
2437   GLX_FUNCTION2(glXBindSwapBarrierSGIX, __glXBindSwapBarrierSGIX),
2438   GLX_FUNCTION2(glXQueryMaxSwapBarriersSGIX, __glXQueryMaxSwapBarriersSGIX),
2439
2440   /*** GLX_MESA_copy_sub_buffer ***/
2441   GLX_FUNCTION2(glXCopySubBufferMESA, __glXCopySubBufferMESA),
2442
2443   /*** GLX_MESA_pixmap_colormap ***/
2444   GLX_FUNCTION(glXCreateGLXPixmapMESA),
2445
2446   /*** GLX_MESA_release_buffers ***/
2447   GLX_FUNCTION2(glXReleaseBuffersMESA, __glXReleaseBuffersMESA),
2448
2449   /*** GLX_MESA_swap_control ***/
2450   GLX_FUNCTION2(glXSwapIntervalMESA, __glXSwapIntervalMESA),
2451   GLX_FUNCTION2(glXGetSwapIntervalMESA, __glXGetSwapIntervalMESA),
2452#endif
2453
2454   /*** GLX_ARB_get_proc_address ***/
2455   GLX_FUNCTION(glXGetProcAddressARB),
2456
2457   /*** GLX 1.4 ***/
2458   GLX_FUNCTION2(glXGetProcAddress, glXGetProcAddressARB),
2459
2460#ifndef GLX_USE_APPLEGL
2461   /*** GLX_OML_sync_control ***/
2462   GLX_FUNCTION2(glXWaitForSbcOML, __glXWaitForSbcOML),
2463   GLX_FUNCTION2(glXWaitForMscOML, __glXWaitForMscOML),
2464   GLX_FUNCTION2(glXSwapBuffersMscOML, __glXSwapBuffersMscOML),
2465   GLX_FUNCTION2(glXGetMscRateOML, __glXGetMscRateOML),
2466   GLX_FUNCTION2(glXGetSyncValuesOML, __glXGetSyncValuesOML),
2467
2468   /*** GLX_EXT_texture_from_pixmap ***/
2469   GLX_FUNCTION2(glXBindTexImageEXT, __glXBindTexImageEXT),
2470   GLX_FUNCTION2(glXReleaseTexImageEXT, __glXReleaseTexImageEXT),
2471#endif
2472
2473#if defined(GLX_DIRECT_RENDERING) && !defined(GLX_USE_APPLEGL)
2474   /*** DRI configuration ***/
2475   GLX_FUNCTION(glXGetScreenDriver),
2476   GLX_FUNCTION(glXGetDriverConfig),
2477#endif
2478
2479   {NULL, NULL}                 /* end of list */
2480};
2481
2482static const GLvoid *
2483get_glx_proc_address(const char *funcName)
2484{
2485   GLuint i;
2486
2487   /* try static functions */
2488   for (i = 0; GLX_functions[i].Name; i++) {
2489      if (strcmp(GLX_functions[i].Name, funcName) == 0)
2490         return GLX_functions[i].Address;
2491   }
2492
2493   return NULL;
2494}
2495
2496/**
2497 * Get the address of a named GL function.  This is the pre-GLX 1.4 name for
2498 * \c glXGetProcAddress.
2499 *
2500 * \param procName  Name of a GL or GLX function.
2501 * \returns         A pointer to the named function
2502 *
2503 * \sa glXGetProcAddress
2504 */
2505_X_EXPORT void (*glXGetProcAddressARB(const GLubyte * procName)) (void)
2506{
2507   typedef void (*gl_function) (void);
2508   gl_function f;
2509
2510
2511   /* Search the table of GLX and internal functions first.  If that
2512    * fails and the supplied name could be a valid core GL name, try
2513    * searching the core GL function table.  This check is done to prevent
2514    * DRI based drivers from searching the core GL function table for
2515    * internal API functions.
2516    */
2517   f = (gl_function) get_glx_proc_address((const char *) procName);
2518   if ((f == NULL) && (procName[0] == 'g') && (procName[1] == 'l')
2519       && (procName[2] != 'X')) {
2520#ifdef GLX_SHARED_GLAPI
2521      f = (gl_function) __indirect_get_proc_address((const char *) procName);
2522#endif
2523      if (!f)
2524         f = (gl_function) _glapi_get_proc_address((const char *) procName);
2525   }
2526   return f;
2527}
2528
2529/**
2530 * Get the address of a named GL function.  This is the GLX 1.4 name for
2531 * \c glXGetProcAddressARB.
2532 *
2533 * \param procName  Name of a GL or GLX function.
2534 * \returns         A pointer to the named function
2535 *
2536 * \sa glXGetProcAddressARB
2537 */
2538_X_EXPORT void (*glXGetProcAddress(const GLubyte * procName)) (void)
2539#if defined(__GNUC__) && !defined(GLX_ALIAS_UNSUPPORTED)
2540   __attribute__ ((alias("glXGetProcAddressARB")));
2541#else
2542{
2543   return glXGetProcAddressARB(procName);
2544}
2545#endif /* __GNUC__ */
2546
2547
2548#if defined(GLX_DIRECT_RENDERING) && !defined(GLX_USE_APPLEGL)
2549/**
2550 * Get the unadjusted system time (UST).  Currently, the UST is measured in
2551 * microseconds since Epoc.  The actual resolution of the UST may vary from
2552 * system to system, and the units may vary from release to release.
2553 * Drivers should not call this function directly.  They should instead use
2554 * \c glXGetProcAddress to obtain a pointer to the function.
2555 *
2556 * \param ust Location to store the 64-bit UST
2557 * \returns Zero on success or a negative errno value on failure.
2558 *
2559 * \sa glXGetProcAddress, PFNGLXGETUSTPROC
2560 *
2561 * \since Internal API version 20030317.
2562 */
2563_X_HIDDEN int
2564__glXGetUST(int64_t * ust)
2565{
2566   struct timeval tv;
2567
2568   if (ust == NULL) {
2569      return -EFAULT;
2570   }
2571
2572   if (gettimeofday(&tv, NULL) == 0) {
2573      ust[0] = (tv.tv_sec * 1000000) + tv.tv_usec;
2574      return 0;
2575   }
2576   else {
2577      return -errno;
2578   }
2579}
2580#endif /* GLX_DIRECT_RENDERING */
2581