OSDN Git Service

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