fe65216c41154df3e3032228ab29d7199c8df199
[profile/ivi/mesa.git] / src / glx / x11 / glxext.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 glxext.c
33  * GLX protocol interface boot-strap code.
34  *
35  * Direct rendering support added by Precision Insight, Inc.
36  *
37  * \author Kevin E. Martin <kevin@precisioninsight.com>
38  */
39
40 #include <assert.h>
41 #include "glxclient.h"
42 #include <X11/extensions/Xext.h>
43 #include <X11/extensions/extutil.h>
44 #include "glapi.h"
45 #include "glxextensions.h"
46 #include "glcontextmodes.h"
47
48 #ifdef USE_XCB
49 #include <X11/Xlib-xcb.h>
50 #include <xcb/xcb.h>
51 #include <xcb/glx.h>
52 #endif
53
54
55 #ifdef DEBUG
56 void __glXDumpDrawBuffer(__GLXcontext * ctx);
57 #endif
58
59 /*
60 ** You can set this cell to 1 to force the gl drawing stuff to be
61 ** one command per packet
62 */
63 _X_HIDDEN int __glXDebug = 0;
64
65 /* Extension required boiler plate */
66
67 static char *__glXExtensionName = GLX_EXTENSION_NAME;
68 XExtensionInfo *__glXExtensionInfo = NULL;
69
70 static /* const */ char *error_list[] = {
71    "GLXBadContext",
72    "GLXBadContextState",
73    "GLXBadDrawable",
74    "GLXBadPixmap",
75    "GLXBadContextTag",
76    "GLXBadCurrentWindow",
77    "GLXBadRenderRequest",
78    "GLXBadLargeRequest",
79    "GLXUnsupportedPrivateRequest",
80    "GLXBadFBConfig",
81    "GLXBadPbuffer",
82    "GLXBadCurrentDrawable",
83    "GLXBadWindow",
84 };
85
86 static int
87 __glXCloseDisplay(Display * dpy, XExtCodes * codes)
88 {
89    GLXContext gc;
90
91    gc = __glXGetCurrentContext();
92    if (dpy == gc->currentDpy) {
93       __glXSetCurrentContextNull();
94       __glXFreeContext(gc);
95    }
96
97    return XextRemoveDisplay(__glXExtensionInfo, dpy);
98 }
99
100
101 static
102 XEXT_GENERATE_ERROR_STRING(__glXErrorString, __glXExtensionName,
103                            __GLX_NUMBER_ERRORS, error_list)
104 static Bool
105 __glXWireToEvent(Display *dpy, XEvent *event, xEvent *wire);
106 static Status
107 __glXEventToWire(Display *dpy, XEvent *event, xEvent *wire);
108
109 static /* const */ XExtensionHooks __glXExtensionHooks = {
110   NULL,                   /* create_gc */
111   NULL,                   /* copy_gc */
112   NULL,                   /* flush_gc */
113   NULL,                   /* free_gc */
114   NULL,                   /* create_font */
115   NULL,                   /* free_font */
116   __glXCloseDisplay,      /* close_display */
117   __glXWireToEvent,       /* wire_to_event */
118   __glXEventToWire,       /* event_to_wire */
119   NULL,                   /* error */
120   __glXErrorString,       /* error_string */
121 };
122
123 static
124 XEXT_GENERATE_FIND_DISPLAY(__glXFindDisplay, __glXExtensionInfo,
125                            __glXExtensionName, &__glXExtensionHooks,
126                            __GLX_NUMBER_EVENTS, NULL)
127
128 /*
129  * GLX events are a bit funky.  We don't stuff the X event code into
130  * our user exposed (via XNextEvent) structure.  Instead we use the GLX
131  * private event code namespace (and hope it doesn't conflict).  Clients
132  * have to know that bit 15 in the event type field means they're getting
133  * a GLX event, and then handle the various sub-event types there, rather
134  * than simply checking the event code and handling it directly.
135  */
136
137 static Bool
138 __glXWireToEvent(Display *dpy, XEvent *event, xEvent *wire)
139 {
140    XExtDisplayInfo *info = __glXFindDisplay(dpy);
141
142    XextCheckExtension(dpy, info, __glXExtensionName, False);
143
144    switch ((wire->u.u.type & 0x7f) - info->codes->first_event) {
145    case GLX_PbufferClobber:
146    {
147       GLXPbufferClobberEvent *aevent = (GLXPbufferClobberEvent *)event;
148       xGLXPbufferClobberEvent *awire = (xGLXPbufferClobberEvent *)wire;
149       aevent->event_type = awire->type;
150       aevent->serial = awire->sequenceNumber;
151       aevent->event_type = awire->event_type;
152       aevent->draw_type = awire->draw_type;
153       aevent->drawable = awire->drawable;
154       aevent->buffer_mask = awire->buffer_mask;
155       aevent->aux_buffer = awire->aux_buffer;
156       aevent->x = awire->x;
157       aevent->y = awire->y;
158       aevent->width = awire->width;
159       aevent->height = awire->height;
160       aevent->count = awire->count;
161       return True;
162    }
163    case GLX_BufferSwapComplete:
164    {
165       GLXBufferSwapComplete *aevent = (GLXBufferSwapComplete *)event;
166       xGLXBufferSwapComplete *awire = (xGLXBufferSwapComplete *)wire;
167       aevent->event_type = awire->event_type;
168       aevent->drawable = awire->drawable;
169       aevent->ust = ((CARD64)awire->ust_hi << 32) | awire->ust_lo;
170       aevent->msc = ((CARD64)awire->msc_hi << 32) | awire->msc_lo;
171       aevent->sbc = ((CARD64)awire->sbc_hi << 32) | awire->sbc_lo;
172       return True;
173    }
174    default:
175       /* client doesn't support server event */
176       break;
177    }
178
179    return False;
180 }
181
182 /* We don't actually support this.  It doesn't make sense for clients to
183  * send each other GLX events.
184  */
185 static Status
186 __glXEventToWire(Display *dpy, XEvent *event, xEvent *wire)
187 {
188    XExtDisplayInfo *info = __glXFindDisplay(dpy);
189
190    XextCheckExtension(dpy, info, __glXExtensionName, False);
191
192    switch (event->type) {
193    case GLX_DAMAGED:
194       break;
195    case GLX_SAVED:
196       break;
197    case GLX_EXCHANGE_COMPLETE:
198       break;
199    case GLX_BLIT_COMPLETE:
200       break;
201    case GLX_FLIP_COMPLETE:
202       break;
203    default:
204       /* client doesn't support server event */
205       break;
206    }
207
208    return Success;
209 }
210
211 /************************************************************************/
212 /*
213 ** Free the per screen configs data as well as the array of
214 ** __glXScreenConfigs.
215 */
216 static void
217 FreeScreenConfigs(__GLXdisplayPrivate * priv)
218 {
219    __GLXscreenConfigs *psc;
220    GLint i, screens;
221
222    /* Free screen configuration information */
223    psc = priv->screenConfigs;
224    screens = ScreenCount(priv->dpy);
225    for (i = 0; i < screens; i++, psc++) {
226       if (psc->configs) {
227          _gl_context_modes_destroy(psc->configs);
228          if (psc->effectiveGLXexts)
229             Xfree(psc->effectiveGLXexts);
230          psc->configs = NULL;   /* NOTE: just for paranoia */
231       }
232       if (psc->visuals) {
233          _gl_context_modes_destroy(psc->visuals);
234          psc->visuals = NULL;   /* NOTE: just for paranoia */
235       }
236       Xfree((char *) psc->serverGLXexts);
237
238 #ifdef GLX_DIRECT_RENDERING
239       if (psc->driver_configs) {
240          unsigned int j;
241          for (j = 0; psc->driver_configs[j]; j++)
242             free((__DRIconfig *) psc->driver_configs[j]);
243          free(psc->driver_configs);
244          psc->driver_configs = NULL;
245       }
246       if (psc->driScreen) {
247          psc->driScreen->destroyScreen(psc);
248          __glxHashDestroy(psc->drawHash);
249          XFree(psc->driScreen);
250          psc->driScreen = NULL;
251       }
252 #endif
253    }
254    XFree((char *) priv->screenConfigs);
255    priv->screenConfigs = NULL;
256 }
257
258 /*
259 ** Release the private memory referred to in a display private
260 ** structure.  The caller will free the extension structure.
261 */
262 static int
263 __glXFreeDisplayPrivate(XExtData * extension)
264 {
265    __GLXdisplayPrivate *priv;
266
267    priv = (__GLXdisplayPrivate *) extension->private_data;
268    FreeScreenConfigs(priv);
269    if (priv->serverGLXvendor) {
270       Xfree((char *) priv->serverGLXvendor);
271       priv->serverGLXvendor = 0x0;      /* to protect against double free's */
272    }
273    if (priv->serverGLXversion) {
274       Xfree((char *) priv->serverGLXversion);
275       priv->serverGLXversion = 0x0;     /* to protect against double free's */
276    }
277
278 #ifdef GLX_DIRECT_RENDERING
279    /* Free the direct rendering per display data */
280    if (priv->driswDisplay)
281       (*priv->driswDisplay->destroyDisplay) (priv->driswDisplay);
282    priv->driswDisplay = NULL;
283
284    if (priv->driDisplay)
285       (*priv->driDisplay->destroyDisplay) (priv->driDisplay);
286    priv->driDisplay = NULL;
287
288    if (priv->dri2Display)
289       (*priv->dri2Display->destroyDisplay) (priv->dri2Display);
290    priv->dri2Display = NULL;
291 #endif
292
293    Xfree((char *) priv);
294    return 0;
295 }
296
297 /************************************************************************/
298
299 /*
300 ** Query the version of the GLX extension.  This procedure works even if
301 ** the client extension is not completely set up.
302 */
303 static Bool
304 QueryVersion(Display * dpy, int opcode, int *major, int *minor)
305 {
306 #ifdef USE_XCB
307    xcb_connection_t *c = XGetXCBConnection(dpy);
308    xcb_glx_query_version_reply_t *reply = xcb_glx_query_version_reply(c,
309                                                                       xcb_glx_query_version
310                                                                       (c,
311                                                                        GLX_MAJOR_VERSION,
312                                                                        GLX_MINOR_VERSION),
313                                                                       NULL);
314
315    if (reply->major_version != GLX_MAJOR_VERSION) {
316       free(reply);
317       return GL_FALSE;
318    }
319    *major = reply->major_version;
320    *minor = min(reply->minor_version, GLX_MINOR_VERSION);
321    free(reply);
322    return GL_TRUE;
323 #else
324    xGLXQueryVersionReq *req;
325    xGLXQueryVersionReply reply;
326
327    /* Send the glXQueryVersion request */
328    LockDisplay(dpy);
329    GetReq(GLXQueryVersion, req);
330    req->reqType = opcode;
331    req->glxCode = X_GLXQueryVersion;
332    req->majorVersion = GLX_MAJOR_VERSION;
333    req->minorVersion = GLX_MINOR_VERSION;
334    _XReply(dpy, (xReply *) & reply, 0, False);
335    UnlockDisplay(dpy);
336    SyncHandle();
337
338    if (reply.majorVersion != GLX_MAJOR_VERSION) {
339       /*
340        ** The server does not support the same major release as this
341        ** client.
342        */
343       return GL_FALSE;
344    }
345    *major = reply.majorVersion;
346    *minor = min(reply.minorVersion, GLX_MINOR_VERSION);
347    return GL_TRUE;
348 #endif /* USE_XCB */
349 }
350
351
352 _X_HIDDEN void
353 __glXInitializeVisualConfigFromTags(__GLcontextModes * config, int count,
354                                     const INT32 * bp, Bool tagged_only,
355                                     Bool fbconfig_style_tags)
356 {
357    int i;
358
359    if (!tagged_only) {
360       /* Copy in the first set of properties */
361       config->visualID = *bp++;
362
363       config->visualType = _gl_convert_from_x_visual_type(*bp++);
364
365       config->rgbMode = *bp++;
366
367       config->redBits = *bp++;
368       config->greenBits = *bp++;
369       config->blueBits = *bp++;
370       config->alphaBits = *bp++;
371       config->accumRedBits = *bp++;
372       config->accumGreenBits = *bp++;
373       config->accumBlueBits = *bp++;
374       config->accumAlphaBits = *bp++;
375
376       config->doubleBufferMode = *bp++;
377       config->stereoMode = *bp++;
378
379       config->rgbBits = *bp++;
380       config->depthBits = *bp++;
381       config->stencilBits = *bp++;
382       config->numAuxBuffers = *bp++;
383       config->level = *bp++;
384
385       count -= __GLX_MIN_CONFIG_PROPS;
386    }
387
388    /*
389     ** Additional properties may be in a list at the end
390     ** of the reply.  They are in pairs of property type
391     ** and property value.
392     */
393
394 #define FETCH_OR_SET(tag) \
395     config-> tag = ( fbconfig_style_tags ) ? *bp++ : 1
396
397    for (i = 0; i < count; i += 2) {
398       switch (*bp++) {
399       case GLX_RGBA:
400          FETCH_OR_SET(rgbMode);
401          break;
402       case GLX_BUFFER_SIZE:
403          config->rgbBits = *bp++;
404          break;
405       case GLX_LEVEL:
406          config->level = *bp++;
407          break;
408       case GLX_DOUBLEBUFFER:
409          FETCH_OR_SET(doubleBufferMode);
410          break;
411       case GLX_STEREO:
412          FETCH_OR_SET(stereoMode);
413          break;
414       case GLX_AUX_BUFFERS:
415          config->numAuxBuffers = *bp++;
416          break;
417       case GLX_RED_SIZE:
418          config->redBits = *bp++;
419          break;
420       case GLX_GREEN_SIZE:
421          config->greenBits = *bp++;
422          break;
423       case GLX_BLUE_SIZE:
424          config->blueBits = *bp++;
425          break;
426       case GLX_ALPHA_SIZE:
427          config->alphaBits = *bp++;
428          break;
429       case GLX_DEPTH_SIZE:
430          config->depthBits = *bp++;
431          break;
432       case GLX_STENCIL_SIZE:
433          config->stencilBits = *bp++;
434          break;
435       case GLX_ACCUM_RED_SIZE:
436          config->accumRedBits = *bp++;
437          break;
438       case GLX_ACCUM_GREEN_SIZE:
439          config->accumGreenBits = *bp++;
440          break;
441       case GLX_ACCUM_BLUE_SIZE:
442          config->accumBlueBits = *bp++;
443          break;
444       case GLX_ACCUM_ALPHA_SIZE:
445          config->accumAlphaBits = *bp++;
446          break;
447       case GLX_VISUAL_CAVEAT_EXT:
448          config->visualRating = *bp++;
449          break;
450       case GLX_X_VISUAL_TYPE:
451          config->visualType = *bp++;
452          break;
453       case GLX_TRANSPARENT_TYPE:
454          config->transparentPixel = *bp++;
455          break;
456       case GLX_TRANSPARENT_INDEX_VALUE:
457          config->transparentIndex = *bp++;
458          break;
459       case GLX_TRANSPARENT_RED_VALUE:
460          config->transparentRed = *bp++;
461          break;
462       case GLX_TRANSPARENT_GREEN_VALUE:
463          config->transparentGreen = *bp++;
464          break;
465       case GLX_TRANSPARENT_BLUE_VALUE:
466          config->transparentBlue = *bp++;
467          break;
468       case GLX_TRANSPARENT_ALPHA_VALUE:
469          config->transparentAlpha = *bp++;
470          break;
471       case GLX_VISUAL_ID:
472          config->visualID = *bp++;
473          break;
474       case GLX_DRAWABLE_TYPE:
475          config->drawableType = *bp++;
476          break;
477       case GLX_RENDER_TYPE:
478          config->renderType = *bp++;
479          break;
480       case GLX_X_RENDERABLE:
481          config->xRenderable = *bp++;
482          break;
483       case GLX_FBCONFIG_ID:
484          config->fbconfigID = *bp++;
485          break;
486       case GLX_MAX_PBUFFER_WIDTH:
487          config->maxPbufferWidth = *bp++;
488          break;
489       case GLX_MAX_PBUFFER_HEIGHT:
490          config->maxPbufferHeight = *bp++;
491          break;
492       case GLX_MAX_PBUFFER_PIXELS:
493          config->maxPbufferPixels = *bp++;
494          break;
495       case GLX_OPTIMAL_PBUFFER_WIDTH_SGIX:
496          config->optimalPbufferWidth = *bp++;
497          break;
498       case GLX_OPTIMAL_PBUFFER_HEIGHT_SGIX:
499          config->optimalPbufferHeight = *bp++;
500          break;
501       case GLX_VISUAL_SELECT_GROUP_SGIX:
502          config->visualSelectGroup = *bp++;
503          break;
504       case GLX_SWAP_METHOD_OML:
505          config->swapMethod = *bp++;
506          break;
507       case GLX_SAMPLE_BUFFERS_SGIS:
508          config->sampleBuffers = *bp++;
509          break;
510       case GLX_SAMPLES_SGIS:
511          config->samples = *bp++;
512          break;
513       case GLX_BIND_TO_TEXTURE_RGB_EXT:
514          config->bindToTextureRgb = *bp++;
515          break;
516       case GLX_BIND_TO_TEXTURE_RGBA_EXT:
517          config->bindToTextureRgba = *bp++;
518          break;
519       case GLX_BIND_TO_MIPMAP_TEXTURE_EXT:
520          config->bindToMipmapTexture = *bp++;
521          break;
522       case GLX_BIND_TO_TEXTURE_TARGETS_EXT:
523          config->bindToTextureTargets = *bp++;
524          break;
525       case GLX_Y_INVERTED_EXT:
526          config->yInverted = *bp++;
527          break;
528       case None:
529          i = count;
530          break;
531       default:
532          break;
533       }
534    }
535
536    config->renderType =
537       (config->rgbMode) ? GLX_RGBA_BIT : GLX_COLOR_INDEX_BIT;
538
539    config->haveAccumBuffer = ((config->accumRedBits +
540                                config->accumGreenBits +
541                                config->accumBlueBits +
542                                config->accumAlphaBits) > 0);
543    config->haveDepthBuffer = (config->depthBits > 0);
544    config->haveStencilBuffer = (config->stencilBits > 0);
545 }
546
547 static __GLcontextModes *
548 createConfigsFromProperties(Display * dpy, int nvisuals, int nprops,
549                             int screen, GLboolean tagged_only)
550 {
551    INT32 buf[__GLX_TOTAL_CONFIG], *props;
552    unsigned prop_size;
553    __GLcontextModes *modes, *m;
554    int i;
555
556    if (nprops == 0)
557       return NULL;
558
559    /* FIXME: Is the __GLX_MIN_CONFIG_PROPS test correct for FBconfigs? */
560
561    /* Check number of properties */
562    if (nprops < __GLX_MIN_CONFIG_PROPS || nprops > __GLX_MAX_CONFIG_PROPS)
563       return NULL;
564
565    /* Allocate memory for our config structure */
566    modes = _gl_context_modes_create(nvisuals, sizeof(__GLcontextModes));
567    if (!modes)
568       return NULL;
569
570    prop_size = nprops * __GLX_SIZE_INT32;
571    if (prop_size <= sizeof(buf))
572       props = buf;
573    else
574       props = Xmalloc(prop_size);
575
576    /* Read each config structure and convert it into our format */
577    m = modes;
578    for (i = 0; i < nvisuals; i++) {
579       _XRead(dpy, (char *) props, prop_size);
580       /* Older X servers don't send this so we default it here. */
581       m->drawableType = GLX_WINDOW_BIT;
582       __glXInitializeVisualConfigFromTags(m, nprops, props,
583                                           tagged_only, GL_TRUE);
584       m->screen = screen;
585       m = m->next;
586    }
587
588    if (props != buf)
589       Xfree(props);
590
591    return modes;
592 }
593
594 static GLboolean
595 getVisualConfigs(Display * dpy, __GLXdisplayPrivate * priv, int screen)
596 {
597    xGLXGetVisualConfigsReq *req;
598    __GLXscreenConfigs *psc;
599    xGLXGetVisualConfigsReply reply;
600
601    LockDisplay(dpy);
602
603    psc = priv->screenConfigs + screen;
604    psc->visuals = NULL;
605    GetReq(GLXGetVisualConfigs, req);
606    req->reqType = priv->majorOpcode;
607    req->glxCode = X_GLXGetVisualConfigs;
608    req->screen = screen;
609
610    if (!_XReply(dpy, (xReply *) & reply, 0, False))
611       goto out;
612
613    psc->visuals = createConfigsFromProperties(dpy,
614                                               reply.numVisuals,
615                                               reply.numProps,
616                                               screen, GL_FALSE);
617
618  out:
619    UnlockDisplay(dpy);
620    return psc->visuals != NULL;
621 }
622
623 static GLboolean
624 getFBConfigs(Display * dpy, __GLXdisplayPrivate * priv, int screen)
625 {
626    xGLXGetFBConfigsReq *fb_req;
627    xGLXGetFBConfigsSGIXReq *sgi_req;
628    xGLXVendorPrivateWithReplyReq *vpreq;
629    xGLXGetFBConfigsReply reply;
630    __GLXscreenConfigs *psc;
631
632    psc = priv->screenConfigs + screen;
633    psc->serverGLXexts =
634       __glXQueryServerString(dpy, priv->majorOpcode, screen, GLX_EXTENSIONS);
635
636    LockDisplay(dpy);
637
638    psc->configs = NULL;
639    if (atof(priv->serverGLXversion) >= 1.3) {
640       GetReq(GLXGetFBConfigs, fb_req);
641       fb_req->reqType = priv->majorOpcode;
642       fb_req->glxCode = X_GLXGetFBConfigs;
643       fb_req->screen = screen;
644    }
645    else if (strstr(psc->serverGLXexts, "GLX_SGIX_fbconfig") != NULL) {
646       GetReqExtra(GLXVendorPrivateWithReply,
647                   sz_xGLXGetFBConfigsSGIXReq +
648                   sz_xGLXVendorPrivateWithReplyReq, vpreq);
649       sgi_req = (xGLXGetFBConfigsSGIXReq *) vpreq;
650       sgi_req->reqType = priv->majorOpcode;
651       sgi_req->glxCode = X_GLXVendorPrivateWithReply;
652       sgi_req->vendorCode = X_GLXvop_GetFBConfigsSGIX;
653       sgi_req->screen = screen;
654    }
655    else
656       goto out;
657
658    if (!_XReply(dpy, (xReply *) & reply, 0, False))
659       goto out;
660
661    psc->configs = createConfigsFromProperties(dpy,
662                                               reply.numFBConfigs,
663                                               reply.numAttribs * 2,
664                                               screen, GL_TRUE);
665
666  out:
667    UnlockDisplay(dpy);
668    return psc->configs != NULL;
669 }
670
671 /*
672 ** Allocate the memory for the per screen configs for each screen.
673 ** If that works then fetch the per screen configs data.
674 */
675 static Bool
676 AllocAndFetchScreenConfigs(Display * dpy, __GLXdisplayPrivate * priv)
677 {
678    __GLXscreenConfigs *psc;
679    GLint i, screens;
680
681    /*
682     ** First allocate memory for the array of per screen configs.
683     */
684    screens = ScreenCount(dpy);
685    psc = (__GLXscreenConfigs *) Xmalloc(screens * sizeof(__GLXscreenConfigs));
686    if (!psc) {
687       return GL_FALSE;
688    }
689    memset(psc, 0, screens * sizeof(__GLXscreenConfigs));
690    priv->screenConfigs = psc;
691
692    priv->serverGLXversion =
693       __glXQueryServerString(dpy, priv->majorOpcode, 0, GLX_VERSION);
694    if (priv->serverGLXversion == NULL) {
695       FreeScreenConfigs(priv);
696       return GL_FALSE;
697    }
698
699    for (i = 0; i < screens; i++, psc++) {
700       getVisualConfigs(dpy, priv, i);
701       getFBConfigs(dpy, priv, i);
702
703 #ifdef GLX_DIRECT_RENDERING
704       psc->scr = i;
705       psc->dpy = dpy;
706       psc->drawHash = __glxHashCreate();
707       if (psc->drawHash == NULL)
708          continue;
709
710       if (priv->dri2Display)
711          psc->driScreen = (*priv->dri2Display->createScreen) (psc, i, priv);
712
713       if (psc->driScreen == NULL && priv->driDisplay)
714          psc->driScreen = (*priv->driDisplay->createScreen) (psc, i, priv);
715
716       if (psc->driScreen == NULL && priv->driswDisplay)
717          psc->driScreen = (*priv->driswDisplay->createScreen) (psc, i, priv);
718
719       if (psc->driScreen == NULL) {
720          __glxHashDestroy(psc->drawHash);
721          psc->drawHash = NULL;
722       }
723 #endif
724    }
725    SyncHandle();
726    return GL_TRUE;
727 }
728
729 /*
730 ** Initialize the client side extension code.
731 */
732 _X_HIDDEN __GLXdisplayPrivate *
733 __glXInitialize(Display * dpy)
734 {
735    XExtDisplayInfo *info = __glXFindDisplay(dpy);
736    XExtData **privList, *private, *found;
737    __GLXdisplayPrivate *dpyPriv;
738    XEDataObject dataObj;
739    int major, minor;
740 #ifdef GLX_DIRECT_RENDERING
741    Bool glx_direct, glx_accel;
742 #endif
743
744    /* The one and only long long lock */
745    __glXLock();
746
747    if (!XextHasExtension(info)) {
748       /* No GLX extension supported by this server. Oh well. */
749       __glXUnlock();
750       XMissingExtension(dpy, __glXExtensionName);
751       return 0;
752    }
753
754    /* See if a display private already exists.  If so, return it */
755    dataObj.display = dpy;
756    privList = XEHeadOfExtensionList(dataObj);
757    found = XFindOnExtensionList(privList, info->codes->extension);
758    if (found) {
759       __glXUnlock();
760       return (__GLXdisplayPrivate *) found->private_data;
761    }
762
763    /* See if the versions are compatible */
764    if (!QueryVersion(dpy, info->codes->major_opcode, &major, &minor)) {
765       /* The client and server do not agree on versions.  Punt. */
766       __glXUnlock();
767       return 0;
768    }
769
770    /*
771     ** Allocate memory for all the pieces needed for this buffer.
772     */
773    private = (XExtData *) Xmalloc(sizeof(XExtData));
774    if (!private) {
775       __glXUnlock();
776       return 0;
777    }
778    dpyPriv = (__GLXdisplayPrivate *) Xcalloc(1, sizeof(__GLXdisplayPrivate));
779    if (!dpyPriv) {
780       __glXUnlock();
781       Xfree((char *) private);
782       return 0;
783    }
784
785    /*
786     ** Init the display private and then read in the screen config
787     ** structures from the server.
788     */
789    dpyPriv->majorOpcode = info->codes->major_opcode;
790    dpyPriv->majorVersion = major;
791    dpyPriv->minorVersion = minor;
792    dpyPriv->dpy = dpy;
793
794    dpyPriv->serverGLXvendor = 0x0;
795    dpyPriv->serverGLXversion = 0x0;
796
797 #ifdef GLX_DIRECT_RENDERING
798    glx_direct = (getenv("LIBGL_ALWAYS_INDIRECT") == NULL);
799    glx_accel = (getenv("LIBGL_ALWAYS_SOFTWARE") == NULL);
800
801    /*
802     ** Initialize the direct rendering per display data and functions.
803     ** Note: This _must_ be done before calling any other DRI routines
804     ** (e.g., those called in AllocAndFetchScreenConfigs).
805     */
806    if (glx_direct && glx_accel) {
807       dpyPriv->dri2Display = dri2CreateDisplay(dpy);
808       dpyPriv->driDisplay = driCreateDisplay(dpy);
809    }
810    if (glx_direct)
811       dpyPriv->driswDisplay = driswCreateDisplay(dpy);
812 #endif
813
814    if (!AllocAndFetchScreenConfigs(dpy, dpyPriv)) {
815       __glXUnlock();
816       Xfree((char *) dpyPriv);
817       Xfree((char *) private);
818       return 0;
819    }
820
821    /*
822     ** Fill in the private structure.  This is the actual structure that
823     ** hangs off of the Display structure.  Our private structure is
824     ** referred to by this structure.  Got that?
825     */
826    private->number = info->codes->extension;
827    private->next = 0;
828    private->free_private = __glXFreeDisplayPrivate;
829    private->private_data = (char *) dpyPriv;
830    XAddToExtensionList(privList, private);
831
832    if (dpyPriv->majorVersion == 1 && dpyPriv->minorVersion >= 1) {
833       __glXClientInfo(dpy, dpyPriv->majorOpcode);
834    }
835    __glXUnlock();
836
837    return dpyPriv;
838 }
839
840 /*
841 ** Setup for sending a GLX command on dpy.  Make sure the extension is
842 ** initialized.  Try to avoid calling __glXInitialize as its kinda slow.
843 */
844 _X_HIDDEN CARD8
845 __glXSetupForCommand(Display * dpy)
846 {
847    GLXContext gc;
848    __GLXdisplayPrivate *priv;
849
850    /* If this thread has a current context, flush its rendering commands */
851    gc = __glXGetCurrentContext();
852    if (gc->currentDpy) {
853       /* Flush rendering buffer of the current context, if any */
854       (void) __glXFlushRenderBuffer(gc, gc->pc);
855
856       if (gc->currentDpy == dpy) {
857          /* Use opcode from gc because its right */
858          return gc->majorOpcode;
859       }
860       else {
861          /*
862           ** Have to get info about argument dpy because it might be to
863           ** a different server
864           */
865       }
866    }
867
868    /* Forced to lookup extension via the slow initialize route */
869    priv = __glXInitialize(dpy);
870    if (!priv) {
871       return 0;
872    }
873    return priv->majorOpcode;
874 }
875
876 /**
877  * Flush the drawing command transport buffer.
878  *
879  * \param ctx  Context whose transport buffer is to be flushed.
880  * \param pc   Pointer to first unused buffer location.
881  *
882  * \todo
883  * Modify this function to use \c ctx->pc instead of the explicit
884  * \c pc parameter.
885  */
886 _X_HIDDEN GLubyte *
887 __glXFlushRenderBuffer(__GLXcontext * ctx, GLubyte * pc)
888 {
889    Display *const dpy = ctx->currentDpy;
890 #ifdef USE_XCB
891    xcb_connection_t *c = XGetXCBConnection(dpy);
892 #else
893    xGLXRenderReq *req;
894 #endif /* USE_XCB */
895    const GLint size = pc - ctx->buf;
896
897    if ((dpy != NULL) && (size > 0)) {
898 #ifdef USE_XCB
899       xcb_glx_render(c, ctx->currentContextTag, size,
900                      (const uint8_t *) ctx->buf);
901 #else
902       /* Send the entire buffer as an X request */
903       LockDisplay(dpy);
904       GetReq(GLXRender, req);
905       req->reqType = ctx->majorOpcode;
906       req->glxCode = X_GLXRender;
907       req->contextTag = ctx->currentContextTag;
908       req->length += (size + 3) >> 2;
909       _XSend(dpy, (char *) ctx->buf, size);
910       UnlockDisplay(dpy);
911       SyncHandle();
912 #endif
913    }
914
915    /* Reset pointer and return it */
916    ctx->pc = ctx->buf;
917    return ctx->pc;
918 }
919
920
921 /**
922  * Send a portion of a GLXRenderLarge command to the server.  The advantage of
923  * this function over \c __glXSendLargeCommand is that callers can use the
924  * data buffer in the GLX context and may be able to avoid allocating an
925  * extra buffer.  The disadvantage is the clients will have to do more
926  * GLX protocol work (i.e., calculating \c totalRequests, etc.).
927  *
928  * \sa __glXSendLargeCommand
929  *
930  * \param gc             GLX context
931  * \param requestNumber  Which part of the whole command is this?  The first
932  *                       request is 1.
933  * \param totalRequests  How many requests will there be?
934  * \param data           Command data.
935  * \param dataLen        Size, in bytes, of the command data.
936  */
937 _X_HIDDEN void
938 __glXSendLargeChunk(__GLXcontext * gc, GLint requestNumber,
939                     GLint totalRequests, const GLvoid * data, GLint dataLen)
940 {
941    Display *dpy = gc->currentDpy;
942 #ifdef USE_XCB
943    xcb_connection_t *c = XGetXCBConnection(dpy);
944    xcb_glx_render_large(c, gc->currentContextTag, requestNumber,
945                         totalRequests, dataLen, data);
946 #else
947    xGLXRenderLargeReq *req;
948
949    if (requestNumber == 1) {
950       LockDisplay(dpy);
951    }
952
953    GetReq(GLXRenderLarge, req);
954    req->reqType = gc->majorOpcode;
955    req->glxCode = X_GLXRenderLarge;
956    req->contextTag = gc->currentContextTag;
957    req->length += (dataLen + 3) >> 2;
958    req->requestNumber = requestNumber;
959    req->requestTotal = totalRequests;
960    req->dataBytes = dataLen;
961    Data(dpy, data, dataLen);
962
963    if (requestNumber == totalRequests) {
964       UnlockDisplay(dpy);
965       SyncHandle();
966    }
967 #endif /* USE_XCB */
968 }
969
970
971 /**
972  * Send a command that is too large for the GLXRender protocol request.
973  *
974  * Send a large command, one that is too large for some reason to
975  * send using the GLXRender protocol request.  One reason to send
976  * a large command is to avoid copying the data.
977  *
978  * \param ctx        GLX context
979  * \param header     Header data.
980  * \param headerLen  Size, in bytes, of the header data.  It is assumed that
981  *                   the header data will always be small enough to fit in
982  *                   a single X protocol packet.
983  * \param data       Command data.
984  * \param dataLen    Size, in bytes, of the command data.
985  */
986 _X_HIDDEN void
987 __glXSendLargeCommand(__GLXcontext * ctx,
988                       const GLvoid * header, GLint headerLen,
989                       const GLvoid * data, GLint dataLen)
990 {
991    GLint maxSize;
992    GLint totalRequests, requestNumber;
993
994    /*
995     ** Calculate the maximum amount of data can be stuffed into a single
996     ** packet.  sz_xGLXRenderReq is added because bufSize is the maximum
997     ** packet size minus sz_xGLXRenderReq.
998     */
999    maxSize = (ctx->bufSize + sz_xGLXRenderReq) - sz_xGLXRenderLargeReq;
1000    totalRequests = 1 + (dataLen / maxSize);
1001    if (dataLen % maxSize)
1002       totalRequests++;
1003
1004    /*
1005     ** Send all of the command, except the large array, as one request.
1006     */
1007    assert(headerLen <= maxSize);
1008    __glXSendLargeChunk(ctx, 1, totalRequests, header, headerLen);
1009
1010    /*
1011     ** Send enough requests until the whole array is sent.
1012     */
1013    for (requestNumber = 2; requestNumber <= (totalRequests - 1);
1014         requestNumber++) {
1015       __glXSendLargeChunk(ctx, requestNumber, totalRequests, data, maxSize);
1016       data = (const GLvoid *) (((const GLubyte *) data) + maxSize);
1017       dataLen -= maxSize;
1018       assert(dataLen > 0);
1019    }
1020
1021    assert(dataLen <= maxSize);
1022    __glXSendLargeChunk(ctx, requestNumber, totalRequests, data, dataLen);
1023 }
1024
1025 /************************************************************************/
1026
1027 #ifdef DEBUG
1028 _X_HIDDEN void
1029 __glXDumpDrawBuffer(__GLXcontext * ctx)
1030 {
1031    GLubyte *p = ctx->buf;
1032    GLubyte *end = ctx->pc;
1033    GLushort opcode, length;
1034
1035    while (p < end) {
1036       /* Fetch opcode */
1037       opcode = *((GLushort *) p);
1038       length = *((GLushort *) (p + 2));
1039       printf("%2x: %5d: ", opcode, length);
1040       length -= 4;
1041       p += 4;
1042       while (length > 0) {
1043          printf("%08x ", *((unsigned *) p));
1044          p += 4;
1045          length -= 4;
1046       }
1047       printf("\n");
1048    }
1049 }
1050 #endif