OSDN Git Service

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