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