user32: Use more meaningful variable names.
[wine] / dlls / winex11.drv / opengl.c
1 /*
2  * X11DRV OpenGL functions
3  *
4  * Copyright 2000 Lionel Ulmer
5  * Copyright 2005 Alex Woods
6  * Copyright 2005 Raphael Junqueira
7  * Copyright 2006-2009 Roderick Colenbrander
8  * Copyright 2006 Tomas Carnecky
9  *
10  * This library is free software; you can redistribute it and/or
11  * modify it under the terms of the GNU Lesser General Public
12  * License as published by the Free Software Foundation; either
13  * version 2.1 of the License, or (at your option) any later version.
14  *
15  * This library is distributed in the hope that it will be useful,
16  * but WITHOUT ANY WARRANTY; without even the implied warranty of
17  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
18  * Lesser General Public License for more details.
19  *
20  * You should have received a copy of the GNU Lesser General Public
21  * License along with this library; if not, write to the Free Software
22  * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA
23  */
24
25 #include "config.h"
26 #include "wine/port.h"
27
28 #include <assert.h>
29 #include <stdlib.h>
30 #include <string.h>
31
32 #ifdef HAVE_SYS_SOCKET_H
33 #include <sys/socket.h>
34 #endif
35 #ifdef HAVE_SYS_UN_H
36 #include <sys/un.h>
37 #endif
38
39 #include "x11drv.h"
40 #include "winternl.h"
41 #include "wine/library.h"
42 #include "wine/debug.h"
43
44 WINE_DEFAULT_DEBUG_CHANNEL(wgl);
45 WINE_DECLARE_DEBUG_CHANNEL(winediag);
46
47 #ifdef SONAME_LIBGL
48
49 #undef APIENTRY
50 #undef CALLBACK
51 #undef WINAPI
52
53 #ifdef HAVE_GL_GL_H
54 # include <GL/gl.h>
55 #endif
56 #ifdef HAVE_GL_GLX_H
57 # include <GL/glx.h>
58 #endif
59
60 #include "wine/wgl.h"
61
62 #undef APIENTRY
63 #undef CALLBACK
64 #undef WINAPI
65
66 /* Redefines the constants */
67 #define CALLBACK    __stdcall
68 #define WINAPI      __stdcall
69 #define APIENTRY    WINAPI
70
71
72 WINE_DECLARE_DEBUG_CHANNEL(fps);
73
74 typedef struct wine_glextension {
75     const char *extName;
76     struct {
77         const char *funcName;
78         void *funcAddress;
79     } extEntryPoints[9];
80 } WineGLExtension;
81
82 struct WineGLInfo {
83     const char *glVersion;
84     char *glExtensions;
85
86     int glxVersion[2];
87
88     const char *glxServerVersion;
89     const char *glxServerVendor;
90     const char *glxServerExtensions;
91
92     const char *glxClientVersion;
93     const char *glxClientVendor;
94     const char *glxClientExtensions;
95
96     const char *glxExtensions;
97
98     BOOL glxDirect;
99     char wglExtensions[4096];
100 };
101
102 typedef struct wine_glpixelformat {
103     int         iPixelFormat;
104     GLXFBConfig fbconfig;
105     int         fmt_id;
106     int         render_type;
107     BOOL        offscreenOnly;
108     DWORD       dwFlags; /* We store some PFD_* flags in here for emulated bitmap formats */
109 } WineGLPixelFormat;
110
111 typedef struct wine_glcontext {
112     HDC hdc;
113     BOOL do_escape;
114     BOOL has_been_current;
115     BOOL sharing;
116     DWORD tid;
117     BOOL gl3_context;
118     XVisualInfo *vis;
119     WineGLPixelFormat *fmt;
120     int numAttribs; /* This is needed for delaying wglCreateContextAttribsARB */
121     int attribList[16]; /* This is needed for delaying wglCreateContextAttribsARB */
122     GLXContext ctx;
123     HDC read_hdc;
124     Drawable drawables[2];
125     BOOL refresh_drawables;
126     struct wine_glcontext *next;
127     struct wine_glcontext *prev;
128 } Wine_GLContext;
129
130 typedef struct wine_glpbuffer {
131     Drawable   drawable;
132     Display*   display;
133     WineGLPixelFormat* fmt;
134     int        width;
135     int        height;
136     int*       attribList;
137     HDC        hdc;
138
139     int        use_render_texture; /* This is also the internal texture format */
140     int        texture_bind_target;
141     int        texture_bpp;
142     GLint      texture_format;
143     GLuint     texture_target;
144     GLenum     texture_type;
145     GLuint     texture;
146     int        texture_level;
147 } Wine_GLPBuffer;
148
149 static Wine_GLContext *context_list;
150 static struct WineGLInfo WineGLInfo = { 0 };
151 static int use_render_texture_emulation = 1;
152 static int use_render_texture_ati = 0;
153 static BOOL has_swap_control;
154 static int swap_interval = 1;
155
156 #define MAX_EXTENSIONS 16
157 static const WineGLExtension *WineGLExtensionList[MAX_EXTENSIONS];
158 static int WineGLExtensionListSize;
159
160 static void X11DRV_WineGL_LoadExtensions(void);
161 static WineGLPixelFormat* ConvertPixelFormatWGLtoGLX(Display *display, int iPixelFormat, BOOL AllowOffscreen, int *fmt_count);
162 static BOOL glxRequireVersion(int requiredVersion);
163 static BOOL glxRequireExtension(const char *requiredExtension);
164
165 static void dump_PIXELFORMATDESCRIPTOR(const PIXELFORMATDESCRIPTOR *ppfd) {
166   TRACE("  - size / version : %d / %d\n", ppfd->nSize, ppfd->nVersion);
167   TRACE("  - dwFlags : ");
168 #define TEST_AND_DUMP(t,tv) if ((t) & (tv)) TRACE(#tv " ")
169   TEST_AND_DUMP(ppfd->dwFlags, PFD_DEPTH_DONTCARE);
170   TEST_AND_DUMP(ppfd->dwFlags, PFD_DOUBLEBUFFER);
171   TEST_AND_DUMP(ppfd->dwFlags, PFD_DOUBLEBUFFER_DONTCARE);
172   TEST_AND_DUMP(ppfd->dwFlags, PFD_DRAW_TO_WINDOW);
173   TEST_AND_DUMP(ppfd->dwFlags, PFD_DRAW_TO_BITMAP);
174   TEST_AND_DUMP(ppfd->dwFlags, PFD_GENERIC_ACCELERATED);
175   TEST_AND_DUMP(ppfd->dwFlags, PFD_GENERIC_FORMAT);
176   TEST_AND_DUMP(ppfd->dwFlags, PFD_NEED_PALETTE);
177   TEST_AND_DUMP(ppfd->dwFlags, PFD_NEED_SYSTEM_PALETTE);
178   TEST_AND_DUMP(ppfd->dwFlags, PFD_STEREO);
179   TEST_AND_DUMP(ppfd->dwFlags, PFD_STEREO_DONTCARE);
180   TEST_AND_DUMP(ppfd->dwFlags, PFD_SUPPORT_GDI);
181   TEST_AND_DUMP(ppfd->dwFlags, PFD_SUPPORT_OPENGL);
182   TEST_AND_DUMP(ppfd->dwFlags, PFD_SWAP_COPY);
183   TEST_AND_DUMP(ppfd->dwFlags, PFD_SWAP_EXCHANGE);
184   TEST_AND_DUMP(ppfd->dwFlags, PFD_SWAP_LAYER_BUFFERS);
185   /* PFD_SUPPORT_COMPOSITION is new in Vista, it is similar to composition
186    * under X e.g. COMPOSITE + GLX_EXT_TEXTURE_FROM_PIXMAP. */
187   TEST_AND_DUMP(ppfd->dwFlags, PFD_SUPPORT_COMPOSITION);
188 #undef TEST_AND_DUMP
189   TRACE("\n");
190
191   TRACE("  - iPixelType : ");
192   switch (ppfd->iPixelType) {
193   case PFD_TYPE_RGBA: TRACE("PFD_TYPE_RGBA"); break;
194   case PFD_TYPE_COLORINDEX: TRACE("PFD_TYPE_COLORINDEX"); break;
195   }
196   TRACE("\n");
197
198   TRACE("  - Color   : %d\n", ppfd->cColorBits);
199   TRACE("  - Red     : %d\n", ppfd->cRedBits);
200   TRACE("  - Green   : %d\n", ppfd->cGreenBits);
201   TRACE("  - Blue    : %d\n", ppfd->cBlueBits);
202   TRACE("  - Alpha   : %d\n", ppfd->cAlphaBits);
203   TRACE("  - Accum   : %d\n", ppfd->cAccumBits);
204   TRACE("  - Depth   : %d\n", ppfd->cDepthBits);
205   TRACE("  - Stencil : %d\n", ppfd->cStencilBits);
206   TRACE("  - Aux     : %d\n", ppfd->cAuxBuffers);
207
208   TRACE("  - iLayerType : ");
209   switch (ppfd->iLayerType) {
210   case PFD_MAIN_PLANE: TRACE("PFD_MAIN_PLANE"); break;
211   case PFD_OVERLAY_PLANE: TRACE("PFD_OVERLAY_PLANE"); break;
212   case (BYTE)PFD_UNDERLAY_PLANE: TRACE("PFD_UNDERLAY_PLANE"); break;
213   }
214   TRACE("\n");
215 }
216
217 #define PUSH1(attribs,att)        do { attribs[nAttribs++] = (att); } while (0)
218 #define PUSH2(attribs,att,value)  do { attribs[nAttribs++] = (att); attribs[nAttribs++] = (value); } while(0)
219
220 #define MAKE_FUNCPTR(f) static typeof(f) * p##f;
221 /* GLX 1.0 */
222 MAKE_FUNCPTR(glXChooseVisual)
223 MAKE_FUNCPTR(glXCopyContext)
224 MAKE_FUNCPTR(glXCreateContext)
225 MAKE_FUNCPTR(glXCreateGLXPixmap)
226 MAKE_FUNCPTR(glXGetCurrentContext)
227 MAKE_FUNCPTR(glXGetCurrentDrawable)
228 MAKE_FUNCPTR(glXDestroyContext)
229 MAKE_FUNCPTR(glXDestroyGLXPixmap)
230 MAKE_FUNCPTR(glXGetConfig)
231 MAKE_FUNCPTR(glXIsDirect)
232 MAKE_FUNCPTR(glXMakeCurrent)
233 MAKE_FUNCPTR(glXSwapBuffers)
234 MAKE_FUNCPTR(glXQueryExtension)
235 MAKE_FUNCPTR(glXQueryVersion)
236 MAKE_FUNCPTR(glXUseXFont)
237
238 /* GLX 1.1 */
239 MAKE_FUNCPTR(glXGetClientString)
240 MAKE_FUNCPTR(glXQueryExtensionsString)
241 MAKE_FUNCPTR(glXQueryServerString)
242
243 /* GLX 1.3 */
244 MAKE_FUNCPTR(glXGetFBConfigs)
245 MAKE_FUNCPTR(glXChooseFBConfig)
246 MAKE_FUNCPTR(glXCreatePbuffer)
247 MAKE_FUNCPTR(glXCreateNewContext)
248 MAKE_FUNCPTR(glXDestroyPbuffer)
249 MAKE_FUNCPTR(glXGetFBConfigAttrib)
250 MAKE_FUNCPTR(glXGetVisualFromFBConfig)
251 MAKE_FUNCPTR(glXMakeContextCurrent)
252 MAKE_FUNCPTR(glXQueryDrawable)
253 MAKE_FUNCPTR(glXGetCurrentReadDrawable)
254
255 /* GLX Extensions */
256 static GLXContext (*pglXCreateContextAttribsARB)(Display *dpy, GLXFBConfig config, GLXContext share_context, Bool direct, const int *attrib_list);
257 static void* (*pglXGetProcAddressARB)(const GLubyte *);
258 static int   (*pglXSwapIntervalSGI)(int);
259
260 /* ATI GLX Extensions */
261 static BOOL  (*pglXBindTexImageATI)(Display *dpy, GLXPbuffer pbuffer, int buffer);
262 static BOOL  (*pglXReleaseTexImageATI)(Display *dpy, GLXPbuffer pbuffer, int buffer);
263 static BOOL  (*pglXDrawableAttribATI)(Display *dpy, GLXDrawable draw, const int *attribList);
264
265 /* NV GLX Extension */
266 static void* (*pglXAllocateMemoryNV)(GLsizei size, GLfloat readfreq, GLfloat writefreq, GLfloat priority);
267 static void  (*pglXFreeMemoryNV)(GLvoid *pointer);
268
269 /* MESA GLX Extensions */
270 static void (*pglXCopySubBufferMESA)(Display *dpy, GLXDrawable drawable, int x, int y, int width, int height);
271
272 /* Standard OpenGL */
273 MAKE_FUNCPTR(glBindTexture)
274 MAKE_FUNCPTR(glBitmap)
275 MAKE_FUNCPTR(glCopyTexSubImage1D)
276 MAKE_FUNCPTR(glCopyTexImage2D)
277 MAKE_FUNCPTR(glCopyTexSubImage2D)
278 MAKE_FUNCPTR(glDrawBuffer)
279 MAKE_FUNCPTR(glEndList)
280 MAKE_FUNCPTR(glGetError)
281 MAKE_FUNCPTR(glGetIntegerv)
282 MAKE_FUNCPTR(glGetString)
283 MAKE_FUNCPTR(glNewList)
284 MAKE_FUNCPTR(glPixelStorei)
285 MAKE_FUNCPTR(glReadPixels)
286 MAKE_FUNCPTR(glTexImage2D)
287 MAKE_FUNCPTR(glFinish)
288 MAKE_FUNCPTR(glFlush)
289 #undef MAKE_FUNCPTR
290
291 static int GLXErrorHandler(Display *dpy, XErrorEvent *event, void *arg)
292 {
293     /* In the future we might want to find the exact X or GLX error to report back to the app */
294     return 1;
295 }
296
297 static BOOL infoInitialized = FALSE;
298 static BOOL X11DRV_WineGL_InitOpenglInfo(void)
299 {
300     int screen = DefaultScreen(gdi_display);
301     Window win = 0, root = 0;
302     const char* str;
303     XVisualInfo *vis;
304     GLXContext ctx = NULL;
305     XSetWindowAttributes attr;
306     BOOL ret = FALSE;
307     int attribList[] = {GLX_RGBA, GLX_DOUBLEBUFFER, None};
308
309     if (infoInitialized)
310         return TRUE;
311     infoInitialized = TRUE;
312
313     attr.override_redirect = True;
314     attr.colormap = None;
315     attr.border_pixel = 0;
316
317     wine_tsx11_lock();
318
319     vis = pglXChooseVisual(gdi_display, screen, attribList);
320     if (vis) {
321 #ifdef __i386__
322         WORD old_fs = wine_get_fs();
323         /* Create a GLX Context. Without one we can't query GL information */
324         ctx = pglXCreateContext(gdi_display, vis, None, GL_TRUE);
325         if (wine_get_fs() != old_fs)
326         {
327             wine_set_fs( old_fs );
328             ERR( "%%fs register corrupted, probably broken ATI driver, disabling OpenGL.\n" );
329             ERR( "You need to set the \"UseFastTls\" option to \"2\" in your X config file.\n" );
330             goto done;
331         }
332 #else
333         ctx = pglXCreateContext(gdi_display, vis, None, GL_TRUE);
334 #endif
335     }
336     if (!ctx) goto done;
337
338     root = RootWindow( gdi_display, vis->screen );
339     if (vis->visual != DefaultVisual( gdi_display, vis->screen ))
340         attr.colormap = XCreateColormap( gdi_display, root, vis->visual, AllocNone );
341     if ((win = XCreateWindow( gdi_display, root, -1, -1, 1, 1, 0, vis->depth, InputOutput,
342                               vis->visual, CWBorderPixel | CWOverrideRedirect | CWColormap, &attr )))
343         XMapWindow( gdi_display, win );
344     else
345         win = root;
346
347     if(pglXMakeCurrent(gdi_display, win, ctx) == 0)
348     {
349         ERR_(winediag)( "Unable to activate OpenGL context, most likely your OpenGL drivers haven't been installed correctly\n" );
350         goto done;
351     }
352     WineGLInfo.glVersion = (const char *) pglGetString(GL_VERSION);
353     str = (const char *) pglGetString(GL_EXTENSIONS);
354     WineGLInfo.glExtensions = HeapAlloc(GetProcessHeap(), 0, strlen(str)+1);
355     strcpy(WineGLInfo.glExtensions, str);
356
357     /* Get the common GLX version supported by GLX client and server ( major/minor) */
358     pglXQueryVersion(gdi_display, &WineGLInfo.glxVersion[0], &WineGLInfo.glxVersion[1]);
359
360     WineGLInfo.glxServerVersion = pglXQueryServerString(gdi_display, screen, GLX_VERSION);
361     WineGLInfo.glxServerVendor = pglXQueryServerString(gdi_display, screen, GLX_VENDOR);
362     WineGLInfo.glxServerExtensions = pglXQueryServerString(gdi_display, screen, GLX_EXTENSIONS);
363
364     WineGLInfo.glxClientVersion = pglXGetClientString(gdi_display, GLX_VERSION);
365     WineGLInfo.glxClientVendor = pglXGetClientString(gdi_display, GLX_VENDOR);
366     WineGLInfo.glxClientExtensions = pglXGetClientString(gdi_display, GLX_EXTENSIONS);
367
368     WineGLInfo.glxExtensions = pglXQueryExtensionsString(gdi_display, screen);
369     WineGLInfo.glxDirect = pglXIsDirect(gdi_display, ctx);
370
371     TRACE("GL version             : %s.\n", WineGLInfo.glVersion);
372     TRACE("GL renderer            : %s.\n", pglGetString(GL_RENDERER));
373     TRACE("GLX version            : %d.%d.\n", WineGLInfo.glxVersion[0], WineGLInfo.glxVersion[1]);
374     TRACE("Server GLX version     : %s.\n", WineGLInfo.glxServerVersion);
375     TRACE("Server GLX vendor:     : %s.\n", WineGLInfo.glxServerVendor);
376     TRACE("Client GLX version     : %s.\n", WineGLInfo.glxClientVersion);
377     TRACE("Client GLX vendor:     : %s.\n", WineGLInfo.glxClientVendor);
378     TRACE("Direct rendering enabled: %s\n", WineGLInfo.glxDirect ? "True" : "False");
379
380     if(!WineGLInfo.glxDirect)
381     {
382         int fd = ConnectionNumber(gdi_display);
383         struct sockaddr_un uaddr;
384         unsigned int uaddrlen = sizeof(struct sockaddr_un);
385
386         /* In general indirect rendering on a local X11 server indicates a driver problem.
387          * Detect a local X11 server by checking whether the X11 socket is a Unix socket.
388          */
389         if(!getsockname(fd, (struct sockaddr *)&uaddr, &uaddrlen) && uaddr.sun_family == AF_UNIX)
390             ERR_(winediag)("Direct rendering is disabled, most likely your OpenGL drivers haven't been installed correctly\n");
391     }
392     else
393     {
394         /* In general you would expect that if direct rendering is returned, that you receive hardware
395          * accelerated OpenGL rendering. The definition of direct rendering is that rendering is performed
396          * client side without sending all GL commands to X using the GLX protocol. When Mesa falls back to
397          * software rendering, it shows direct rendering.
398          *
399          * Depending on the cause of software rendering a different rendering string is shown. In case Mesa fails
400          * to load a DRI module 'Software Rasterizer' is returned. When Mesa is compiled as a OpenGL reference driver
401          * it shows 'Mesa X11'.
402          */
403         const char *gl_renderer = (const char *)pglGetString(GL_RENDERER);
404         if(!strcmp(gl_renderer, "Software Rasterizer") || !strcmp(gl_renderer, "Mesa X11"))
405             ERR_(winediag)("The Mesa OpenGL driver is using software rendering, most likely your OpenGL drivers haven't been installed correctly\n");
406     }
407     ret = TRUE;
408
409 done:
410     if(vis) XFree(vis);
411     if(ctx) {
412         pglXMakeCurrent(gdi_display, None, NULL);    
413         pglXDestroyContext(gdi_display, ctx);
414     }
415     if (win != root) XDestroyWindow( gdi_display, win );
416     if (attr.colormap) XFreeColormap( gdi_display, attr.colormap );
417     wine_tsx11_unlock();
418     if (!ret) ERR(" couldn't initialize OpenGL, expect problems\n");
419     return ret;
420 }
421
422 void X11DRV_OpenGL_Cleanup(void)
423 {
424     HeapFree(GetProcessHeap(), 0, WineGLInfo.glExtensions);
425     infoInitialized = FALSE;
426 }
427
428 static BOOL has_opengl(void)
429 {
430     static int init_done;
431     static void *opengl_handle;
432
433     char buffer[200];
434     int error_base, event_base;
435
436     if (init_done) return (opengl_handle != NULL);
437     init_done = 1;
438
439     /* No need to load any other libraries as according to the ABI, libGL should be self-sufficient
440        and include all dependencies */
441     opengl_handle = wine_dlopen(SONAME_LIBGL, RTLD_NOW|RTLD_GLOBAL, buffer, sizeof(buffer));
442     if (opengl_handle == NULL)
443     {
444         ERR( "Failed to load libGL: %s\n", buffer );
445         ERR( "OpenGL support is disabled.\n");
446         return FALSE;
447     }
448
449     pglXGetProcAddressARB = wine_dlsym(opengl_handle, "glXGetProcAddressARB", NULL, 0);
450     if (pglXGetProcAddressARB == NULL) {
451         ERR("Could not find glXGetProcAddressARB in libGL, disabling OpenGL.\n");
452         goto failed;
453     }
454
455 #define LOAD_FUNCPTR(f) do if((p##f = (void*)pglXGetProcAddressARB((const unsigned char*)#f)) == NULL) \
456     { \
457         ERR( "%s not found in libGL, disabling OpenGL.\n", #f ); \
458         goto failed; \
459     } while(0)
460
461     /* GLX 1.0 */
462     LOAD_FUNCPTR(glXChooseVisual);
463     LOAD_FUNCPTR(glXCopyContext);
464     LOAD_FUNCPTR(glXCreateContext);
465     LOAD_FUNCPTR(glXCreateGLXPixmap);
466     LOAD_FUNCPTR(glXGetCurrentContext);
467     LOAD_FUNCPTR(glXGetCurrentDrawable);
468     LOAD_FUNCPTR(glXDestroyContext);
469     LOAD_FUNCPTR(glXDestroyGLXPixmap);
470     LOAD_FUNCPTR(glXGetConfig);
471     LOAD_FUNCPTR(glXIsDirect);
472     LOAD_FUNCPTR(glXMakeCurrent);
473     LOAD_FUNCPTR(glXSwapBuffers);
474     LOAD_FUNCPTR(glXQueryExtension);
475     LOAD_FUNCPTR(glXQueryVersion);
476     LOAD_FUNCPTR(glXUseXFont);
477
478     /* GLX 1.1 */
479     LOAD_FUNCPTR(glXGetClientString);
480     LOAD_FUNCPTR(glXQueryExtensionsString);
481     LOAD_FUNCPTR(glXQueryServerString);
482
483     /* GLX 1.3 */
484     LOAD_FUNCPTR(glXCreatePbuffer);
485     LOAD_FUNCPTR(glXCreateNewContext);
486     LOAD_FUNCPTR(glXDestroyPbuffer);
487     LOAD_FUNCPTR(glXMakeContextCurrent);
488     LOAD_FUNCPTR(glXGetCurrentReadDrawable);
489     LOAD_FUNCPTR(glXGetFBConfigs);
490
491     /* Standard OpenGL calls */
492     LOAD_FUNCPTR(glBindTexture);
493     LOAD_FUNCPTR(glBitmap);
494     LOAD_FUNCPTR(glCopyTexSubImage1D);
495     LOAD_FUNCPTR(glCopyTexImage2D);
496     LOAD_FUNCPTR(glCopyTexSubImage2D);
497     LOAD_FUNCPTR(glDrawBuffer);
498     LOAD_FUNCPTR(glEndList);
499     LOAD_FUNCPTR(glGetError);
500     LOAD_FUNCPTR(glGetIntegerv);
501     LOAD_FUNCPTR(glGetString);
502     LOAD_FUNCPTR(glNewList);
503     LOAD_FUNCPTR(glPixelStorei);
504     LOAD_FUNCPTR(glReadPixels);
505     LOAD_FUNCPTR(glTexImage2D);
506     LOAD_FUNCPTR(glFinish);
507     LOAD_FUNCPTR(glFlush);
508 #undef LOAD_FUNCPTR
509
510 /* It doesn't matter if these fail. They'll only be used if the driver reports
511    the associated extension is available (and if a driver reports the extension
512    is available but fails to provide the functions, it's quite broken) */
513 #define LOAD_FUNCPTR(f) p##f = pglXGetProcAddressARB((const GLubyte *)#f)
514     /* ARB GLX Extension */
515     LOAD_FUNCPTR(glXCreateContextAttribsARB);
516     /* SGI GLX Extension */
517     LOAD_FUNCPTR(glXSwapIntervalSGI);
518     /* NV GLX Extension */
519     LOAD_FUNCPTR(glXAllocateMemoryNV);
520     LOAD_FUNCPTR(glXFreeMemoryNV);
521 #undef LOAD_FUNCPTR
522
523     if(!X11DRV_WineGL_InitOpenglInfo()) goto failed;
524
525     wine_tsx11_lock();
526     if (pglXQueryExtension(gdi_display, &error_base, &event_base)) {
527         TRACE("GLX is up and running error_base = %d\n", error_base);
528     } else {
529         wine_tsx11_unlock();
530         ERR( "GLX extension is missing, disabling OpenGL.\n" );
531         goto failed;
532     }
533
534     /* In case of GLX you have direct and indirect rendering. Most of the time direct rendering is used
535      * as in general only that is hardware accelerated. In some cases like in case of remote X indirect
536      * rendering is used.
537      *
538      * The main problem for our OpenGL code is that we need certain GLX calls but their presence
539      * depends on the reported GLX client / server version and on the client / server extension list.
540      * Those don't have to be the same.
541      *
542      * In general the server GLX information lists the capabilities in case of indirect rendering.
543      * When direct rendering is used, the OpenGL client library is responsible for which GLX calls are
544      * available and in that case the client GLX informat can be used.
545      * OpenGL programs should use the 'intersection' of both sets of information which is advertised
546      * in the GLX version/extension list. When a program does this it works for certain for both
547      * direct and indirect rendering.
548      *
549      * The problem we are having in this area is that ATI's Linux drivers are broken. For some reason
550      * they haven't added some very important GLX extensions like GLX_SGIX_fbconfig to their client
551      * extension list which causes this extension not to be listed. (Wine requires this extension).
552      * ATI advertises a GLX client version of 1.3 which implies that this fbconfig extension among
553      * pbuffers is around.
554      *
555      * In order to provide users of Ati's proprietary drivers with OpenGL support, we need to detect
556      * the ATI drivers and from then on use GLX client information for them.
557      */
558
559     if(glxRequireVersion(3)) {
560         pglXChooseFBConfig = pglXGetProcAddressARB((const GLubyte *) "glXChooseFBConfig");
561         pglXGetFBConfigAttrib = pglXGetProcAddressARB((const GLubyte *) "glXGetFBConfigAttrib");
562         pglXGetVisualFromFBConfig = pglXGetProcAddressARB((const GLubyte *) "glXGetVisualFromFBConfig");
563         pglXQueryDrawable = pglXGetProcAddressARB((const GLubyte *) "glXQueryDrawable");
564     } else if(glxRequireExtension("GLX_SGIX_fbconfig")) {
565         pglXChooseFBConfig = pglXGetProcAddressARB((const GLubyte *) "glXChooseFBConfigSGIX");
566         pglXGetFBConfigAttrib = pglXGetProcAddressARB((const GLubyte *) "glXGetFBConfigAttribSGIX");
567         pglXGetVisualFromFBConfig = pglXGetProcAddressARB((const GLubyte *) "glXGetVisualFromFBConfigSGIX");
568
569         /* The mesa libGL client library seems to forward glXQueryDrawable to the Xserver, so only
570          * enable this function when the Xserver understand GLX 1.3 or newer
571          */
572         pglXQueryDrawable = NULL;
573      } else if(strcmp("ATI", WineGLInfo.glxClientVendor) == 0) {
574         TRACE("Overriding ATI GLX capabilities!\n");
575         pglXChooseFBConfig = pglXGetProcAddressARB((const GLubyte *) "glXChooseFBConfig");
576         pglXGetFBConfigAttrib = pglXGetProcAddressARB((const GLubyte *) "glXGetFBConfigAttrib");
577         pglXGetVisualFromFBConfig = pglXGetProcAddressARB((const GLubyte *) "glXGetVisualFromFBConfig");
578         pglXQueryDrawable = pglXGetProcAddressARB((const GLubyte *) "glXQueryDrawable");
579
580         /* Use client GLX information in case of the ATI drivers. We override the
581          * capabilities over here and not somewhere else as ATI might better their
582          * life in the future. In case they release proper drivers this block of
583          * code won't be called. */
584         WineGLInfo.glxExtensions = WineGLInfo.glxClientExtensions;
585     } else {
586          ERR(" glx_version is %s and GLX_SGIX_fbconfig extension is unsupported. Expect problems.\n", WineGLInfo.glxServerVersion);
587     }
588
589     if(glxRequireExtension("GLX_ATI_render_texture")) {
590         use_render_texture_ati = 1;
591         pglXBindTexImageATI = pglXGetProcAddressARB((const GLubyte *) "glXBindTexImageATI");
592         pglXReleaseTexImageATI = pglXGetProcAddressARB((const GLubyte *) "glXReleaseTexImageATI");
593         pglXDrawableAttribATI = pglXGetProcAddressARB((const GLubyte *) "glXDrawableAttribATI");
594     }
595
596     if(glxRequireExtension("GLX_MESA_copy_sub_buffer")) {
597         pglXCopySubBufferMESA = pglXGetProcAddressARB((const GLubyte *) "glXCopySubBufferMESA");
598     }
599
600     X11DRV_WineGL_LoadExtensions();
601
602     wine_tsx11_unlock();
603     return TRUE;
604
605 failed:
606     wine_dlclose(opengl_handle, NULL, 0);
607     opengl_handle = NULL;
608     return FALSE;
609 }
610
611 static inline Wine_GLContext *alloc_context(void)
612 {
613     Wine_GLContext *ret;
614
615     if ((ret = HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, sizeof(Wine_GLContext))))
616     {
617         ret->next = context_list;
618         if (context_list) context_list->prev = ret;
619         context_list = ret;
620     }
621     return ret;
622 }
623
624 static inline void free_context(Wine_GLContext *context)
625 {
626     if (context->next != NULL) context->next->prev = context->prev;
627     if (context->prev != NULL) context->prev->next = context->next;
628     else context_list = context->next;
629
630     if (context->vis) XFree(context->vis);
631     HeapFree(GetProcessHeap(), 0, context);
632 }
633
634 static inline BOOL is_valid_context( Wine_GLContext *ctx )
635 {
636     Wine_GLContext *ptr;
637     for (ptr = context_list; ptr; ptr = ptr->next) if (ptr == ctx) break;
638     return (ptr != NULL);
639 }
640
641 static int describeContext(Wine_GLContext* ctx) {
642     int tmp;
643     int ctx_vis_id;
644     TRACE(" Context %p have (vis:%p):\n", ctx, ctx->vis);
645     pglXGetFBConfigAttrib(gdi_display, ctx->fmt->fbconfig, GLX_FBCONFIG_ID, &tmp);
646     TRACE(" - FBCONFIG_ID 0x%x\n", tmp);
647     pglXGetFBConfigAttrib(gdi_display, ctx->fmt->fbconfig, GLX_VISUAL_ID, &tmp);
648     TRACE(" - VISUAL_ID 0x%x\n", tmp);
649     ctx_vis_id = tmp;
650     return ctx_vis_id;
651 }
652
653 static BOOL describeDrawable(X11DRV_PDEVICE *physDev) {
654     int tmp;
655     WineGLPixelFormat *fmt;
656     int fmt_count = 0;
657
658     fmt = ConvertPixelFormatWGLtoGLX(gdi_display, physDev->current_pf, TRUE /* Offscreen */, &fmt_count);
659     if(!fmt) return FALSE;
660
661     TRACE(" HDC %p has:\n", physDev->hdc);
662     TRACE(" - iPixelFormat %d\n", fmt->iPixelFormat);
663     TRACE(" - Drawable %p\n", (void*) get_glxdrawable(physDev));
664     TRACE(" - FBCONFIG_ID 0x%x\n", fmt->fmt_id);
665
666     pglXGetFBConfigAttrib(gdi_display, fmt->fbconfig, GLX_VISUAL_ID, &tmp);
667     TRACE(" - VISUAL_ID 0x%x\n", tmp);
668
669     return TRUE;
670 }
671
672 static int ConvertAttribWGLtoGLX(const int* iWGLAttr, int* oGLXAttr, Wine_GLPBuffer* pbuf) {
673   int nAttribs = 0;
674   unsigned cur = 0; 
675   int pop;
676   int drawattrib = 0;
677   int nvfloatattrib = GLX_DONT_CARE;
678   int pixelattrib = ~0;
679
680   /* The list of WGL attributes is allowed to be NULL. We don't return here for NULL
681    * because we need to do fixups for GLX_DRAWABLE_TYPE/GLX_RENDER_TYPE/GLX_FLOAT_COMPONENTS_NV. */
682   while (iWGLAttr && 0 != iWGLAttr[cur]) {
683     TRACE("pAttr[%d] = %x\n", cur, iWGLAttr[cur]);
684
685     switch (iWGLAttr[cur]) {
686     case WGL_AUX_BUFFERS_ARB:
687       pop = iWGLAttr[++cur];
688       PUSH2(oGLXAttr, GLX_AUX_BUFFERS, pop);
689       TRACE("pAttr[%d] = GLX_AUX_BUFFERS: %d\n", cur, pop);
690       break;
691     case WGL_COLOR_BITS_ARB:
692       pop = iWGLAttr[++cur];
693       PUSH2(oGLXAttr, GLX_BUFFER_SIZE, pop);
694       TRACE("pAttr[%d] = GLX_BUFFER_SIZE: %d\n", cur, pop);
695       break;
696     case WGL_BLUE_BITS_ARB:
697       pop = iWGLAttr[++cur];
698       PUSH2(oGLXAttr, GLX_BLUE_SIZE, pop);
699       TRACE("pAttr[%d] = GLX_BLUE_SIZE: %d\n", cur, pop);
700       break;
701     case WGL_RED_BITS_ARB:
702       pop = iWGLAttr[++cur];
703       PUSH2(oGLXAttr, GLX_RED_SIZE, pop);
704       TRACE("pAttr[%d] = GLX_RED_SIZE: %d\n", cur, pop);
705       break;
706     case WGL_GREEN_BITS_ARB:
707       pop = iWGLAttr[++cur];
708       PUSH2(oGLXAttr, GLX_GREEN_SIZE, pop);
709       TRACE("pAttr[%d] = GLX_GREEN_SIZE: %d\n", cur, pop);
710       break;
711     case WGL_ALPHA_BITS_ARB:
712       pop = iWGLAttr[++cur];
713       PUSH2(oGLXAttr, GLX_ALPHA_SIZE, pop);
714       TRACE("pAttr[%d] = GLX_ALPHA_SIZE: %d\n", cur, pop);
715       break;
716     case WGL_DEPTH_BITS_ARB:
717       pop = iWGLAttr[++cur];
718       PUSH2(oGLXAttr, GLX_DEPTH_SIZE, pop);
719       TRACE("pAttr[%d] = GLX_DEPTH_SIZE: %d\n", cur, pop);
720       break;
721     case WGL_STENCIL_BITS_ARB:
722       pop = iWGLAttr[++cur];
723       PUSH2(oGLXAttr, GLX_STENCIL_SIZE, pop);
724       TRACE("pAttr[%d] = GLX_STENCIL_SIZE: %d\n", cur, pop);
725       break;
726     case WGL_DOUBLE_BUFFER_ARB:
727       pop = iWGLAttr[++cur];
728       PUSH2(oGLXAttr, GLX_DOUBLEBUFFER, pop);
729       TRACE("pAttr[%d] = GLX_DOUBLEBUFFER: %d\n", cur, pop);
730       break;
731     case WGL_STEREO_ARB:
732       pop = iWGLAttr[++cur];
733       PUSH2(oGLXAttr, GLX_STEREO, pop);
734       TRACE("pAttr[%d] = GLX_STEREO: %d\n", cur, pop);
735       break;
736
737     case WGL_PIXEL_TYPE_ARB:
738       pop = iWGLAttr[++cur];
739       TRACE("pAttr[%d] = WGL_PIXEL_TYPE_ARB: %d\n", cur, pop);
740       switch (pop) {
741       case WGL_TYPE_COLORINDEX_ARB: pixelattrib = GLX_COLOR_INDEX_BIT; break ;
742       case WGL_TYPE_RGBA_ARB: pixelattrib = GLX_RGBA_BIT; break ;
743       /* This is the same as WGL_TYPE_RGBA_FLOAT_ATI but the GLX constants differ, only the ARB GLX one is widely supported so use that */
744       case WGL_TYPE_RGBA_FLOAT_ATI: pixelattrib = GLX_RGBA_FLOAT_BIT; break ;
745       case WGL_TYPE_RGBA_UNSIGNED_FLOAT_EXT: pixelattrib = GLX_RGBA_UNSIGNED_FLOAT_BIT_EXT; break ;
746       default:
747         ERR("unexpected PixelType(%x)\n", pop); 
748         pop = 0;
749       }
750       break;
751
752     case WGL_SUPPORT_GDI_ARB:
753       /* This flag is set in a WineGLPixelFormat */
754       pop = iWGLAttr[++cur];
755       TRACE("pAttr[%d] = WGL_SUPPORT_GDI_ARB: %d\n", cur, pop);
756       break;
757
758     case WGL_DRAW_TO_BITMAP_ARB:
759       /* This flag is set in a WineGLPixelFormat */
760       pop = iWGLAttr[++cur];
761       TRACE("pAttr[%d] = WGL_DRAW_TO_BITMAP_ARB: %d\n", cur, pop);
762       break;
763
764     case WGL_DRAW_TO_WINDOW_ARB:
765       pop = iWGLAttr[++cur];
766       TRACE("pAttr[%d] = WGL_DRAW_TO_WINDOW_ARB: %d\n", cur, pop);
767       /* GLX_DRAWABLE_TYPE flags need to be OR'd together. See below. */
768       if (pop) {
769         drawattrib |= GLX_WINDOW_BIT;
770       }
771       break;
772
773     case WGL_DRAW_TO_PBUFFER_ARB:
774       pop = iWGLAttr[++cur];
775       TRACE("pAttr[%d] = WGL_DRAW_TO_PBUFFER_ARB: %d\n", cur, pop);
776       /* GLX_DRAWABLE_TYPE flags need to be OR'd together. See below. */
777       if (pop) {
778         drawattrib |= GLX_PBUFFER_BIT;
779       }
780       break;
781
782     case WGL_ACCELERATION_ARB:
783       /* This flag is set in a WineGLPixelFormat */
784       pop = iWGLAttr[++cur];
785       TRACE("pAttr[%d] = WGL_ACCELERATION_ARB: %d\n", cur, pop);
786       break;
787
788     case WGL_SUPPORT_OPENGL_ARB:
789       pop = iWGLAttr[++cur];
790       /** nothing to do, if we are here, supposing support Accelerated OpenGL */
791       TRACE("pAttr[%d] = WGL_SUPPORT_OPENGL_ARB: %d\n", cur, pop);
792       break;
793
794     case WGL_SWAP_METHOD_ARB:
795       pop = iWGLAttr[++cur];
796       /* For now we ignore this and just return SWAP_EXCHANGE */
797       TRACE("pAttr[%d] = WGL_SWAP_METHOD_ARB: %#x\n", cur, pop);
798       break;
799
800     case WGL_PBUFFER_LARGEST_ARB:
801       pop = iWGLAttr[++cur];
802       PUSH2(oGLXAttr, GLX_LARGEST_PBUFFER, pop);
803       TRACE("pAttr[%d] = GLX_LARGEST_PBUFFER: %x\n", cur, pop);
804       break;
805
806     case WGL_SAMPLE_BUFFERS_ARB:
807       pop = iWGLAttr[++cur];
808       PUSH2(oGLXAttr, GLX_SAMPLE_BUFFERS_ARB, pop);
809       TRACE("pAttr[%d] = GLX_SAMPLE_BUFFERS_ARB: %x\n", cur, pop);
810       break;
811
812     case WGL_SAMPLES_ARB:
813       pop = iWGLAttr[++cur];
814       PUSH2(oGLXAttr, GLX_SAMPLES_ARB, pop);
815       TRACE("pAttr[%d] = GLX_SAMPLES_ARB: %x\n", cur, pop);
816       break;
817
818     case WGL_TEXTURE_FORMAT_ARB:
819     case WGL_TEXTURE_TARGET_ARB:
820     case WGL_MIPMAP_TEXTURE_ARB:
821       TRACE("WGL_render_texture Attributes: %x as %x\n", iWGLAttr[cur], iWGLAttr[cur + 1]);
822       pop = iWGLAttr[++cur];
823       if (NULL == pbuf) {
824         ERR("trying to use GLX_Pbuffer Attributes without Pbuffer (was %x)\n", iWGLAttr[cur]);
825       }
826       if (use_render_texture_ati) {
827         /** nothing to do here */
828       }
829       else if (!use_render_texture_emulation) {
830         if (WGL_NO_TEXTURE_ARB != pop) {
831           ERR("trying to use WGL_render_texture Attributes without support (was %x)\n", iWGLAttr[cur]);
832           return -1; /** error: don't support it */
833         } else {
834           drawattrib |= GLX_PBUFFER_BIT;
835         }
836       }
837       break ;
838     case WGL_FLOAT_COMPONENTS_NV:
839       nvfloatattrib = iWGLAttr[++cur];
840       TRACE("pAttr[%d] = WGL_FLOAT_COMPONENTS_NV: %x\n", cur, nvfloatattrib);
841       break ;
842     case WGL_BIND_TO_TEXTURE_DEPTH_NV:
843     case WGL_BIND_TO_TEXTURE_RGB_ARB:
844     case WGL_BIND_TO_TEXTURE_RGBA_ARB:
845     case WGL_BIND_TO_TEXTURE_RECTANGLE_FLOAT_R_NV:
846     case WGL_BIND_TO_TEXTURE_RECTANGLE_FLOAT_RG_NV:
847     case WGL_BIND_TO_TEXTURE_RECTANGLE_FLOAT_RGB_NV:
848     case WGL_BIND_TO_TEXTURE_RECTANGLE_FLOAT_RGBA_NV:
849       pop = iWGLAttr[++cur];
850       /** cannot be converted, see direct handling on 
851        *   - wglGetPixelFormatAttribivARB
852        *  TODO: wglChoosePixelFormat
853        */
854       break ;
855     case WGL_FRAMEBUFFER_SRGB_CAPABLE_EXT:
856       pop = iWGLAttr[++cur];
857       PUSH2(oGLXAttr, GLX_FRAMEBUFFER_SRGB_CAPABLE_EXT, pop);
858       TRACE("pAttr[%d] = GLX_FRAMEBUFFER_SRGB_CAPABLE_EXT: %x\n", cur, pop);
859       break ;
860
861     case WGL_TYPE_RGBA_UNSIGNED_FLOAT_EXT:
862       pop = iWGLAttr[++cur];
863       PUSH2(oGLXAttr, GLX_RGBA_UNSIGNED_FLOAT_TYPE_EXT, pop);
864       TRACE("pAttr[%d] = GLX_RGBA_UNSIGNED_FLOAT_TYPE_EXT: %x\n", cur, pop);
865       break ;
866     default:
867       FIXME("unsupported %x WGL Attribute\n", iWGLAttr[cur]);
868       break;
869     }
870     ++cur;
871   }
872
873   /* By default glXChooseFBConfig defaults to GLX_WINDOW_BIT. wglChoosePixelFormatARB searches through
874    * all formats. Unless drawattrib is set to a non-zero value override it with ~0, so that pixmap and pbuffer
875    * formats appear as well. */
876   if(!drawattrib) drawattrib = ~0;
877   PUSH2(oGLXAttr, GLX_DRAWABLE_TYPE, drawattrib);
878   TRACE("pAttr[?] = GLX_DRAWABLE_TYPE: %#x\n", drawattrib);
879
880   /* By default glXChooseFBConfig uses GLX_RGBA_BIT as the default value. Since wglChoosePixelFormatARB
881    * searches in all formats we have to do the same. For this reason we set GLX_RENDER_TYPE to ~0 unless
882    * it is overridden. */
883   PUSH2(oGLXAttr, GLX_RENDER_TYPE, pixelattrib);
884   TRACE("pAttr[?] = GLX_RENDER_TYPE: %#x\n", pixelattrib);
885
886   /* Set GLX_FLOAT_COMPONENTS_NV all the time */
887   if(strstr(WineGLInfo.glxExtensions, "GLX_NV_float_buffer")) {
888     PUSH2(oGLXAttr, GLX_FLOAT_COMPONENTS_NV, nvfloatattrib);
889     TRACE("pAttr[?] = GLX_FLOAT_COMPONENTS_NV: %#x\n", nvfloatattrib);
890   }
891
892   return nAttribs;
893 }
894
895 static int get_render_type_from_fbconfig(Display *display, GLXFBConfig fbconfig)
896 {
897     int render_type=0, render_type_bit;
898     pglXGetFBConfigAttrib(display, fbconfig, GLX_RENDER_TYPE, &render_type_bit);
899     switch(render_type_bit)
900     {
901         case GLX_RGBA_BIT:
902             render_type = GLX_RGBA_TYPE;
903             break;
904         case GLX_COLOR_INDEX_BIT:
905             render_type = GLX_COLOR_INDEX_TYPE;
906             break;
907         case GLX_RGBA_FLOAT_BIT:
908             render_type = GLX_RGBA_FLOAT_TYPE;
909             break;
910         case GLX_RGBA_UNSIGNED_FLOAT_BIT_EXT:
911             render_type = GLX_RGBA_UNSIGNED_FLOAT_TYPE_EXT;
912             break;
913         default:
914             ERR("Unknown render_type: %x\n", render_type_bit);
915     }
916     return render_type;
917 }
918
919 /* Check whether a fbconfig is suitable for Windows-style bitmap rendering */
920 static BOOL check_fbconfig_bitmap_capability(Display *display, GLXFBConfig fbconfig)
921 {
922     int dbuf, value;
923     pglXGetFBConfigAttrib(display, fbconfig, GLX_DOUBLEBUFFER, &dbuf);
924     pglXGetFBConfigAttrib(gdi_display, fbconfig, GLX_DRAWABLE_TYPE, &value);
925
926     /* Windows only supports bitmap rendering on single buffered formats, further the fbconfig needs to have
927      * the GLX_PIXMAP_BIT set. */
928     return !dbuf && (value & GLX_PIXMAP_BIT);
929 }
930
931 static WineGLPixelFormat *get_formats(Display *display, int *size_ret, int *onscreen_size_ret)
932 {
933     static WineGLPixelFormat *list;
934     static int size, onscreen_size;
935
936     int fmt_id, nCfgs, i, run, bmp_formats;
937     GLXFBConfig* cfgs;
938     XVisualInfo *visinfo;
939
940     wine_tsx11_lock();
941     if (list) goto done;
942
943     cfgs = pglXGetFBConfigs(display, DefaultScreen(display), &nCfgs);
944     if (NULL == cfgs || 0 == nCfgs) {
945         if(cfgs != NULL) XFree(cfgs);
946         wine_tsx11_unlock();
947         ERR("glXChooseFBConfig returns NULL\n");
948         return NULL;
949     }
950
951     /* Bitmap rendering on Windows implies the use of the Microsoft GDI software renderer.
952      * Further most GLX drivers only offer pixmap rendering using indirect rendering (except for modern drivers which support 'AIGLX' / composite).
953      * Indirect rendering can indicate software rendering (on Nvidia it is hw accelerated)
954      * Since bitmap rendering implies the use of software rendering we can safely use indirect rendering for bitmaps.
955      *
956      * Below we count the number of formats which are suitable for bitmap rendering. Windows restricts bitmap rendering to single buffered formats.
957      */
958     for(i=0, bmp_formats=0; i<nCfgs; i++)
959     {
960         if(check_fbconfig_bitmap_capability(display, cfgs[i]))
961             bmp_formats++;
962     }
963     TRACE("Found %d bitmap capable fbconfigs\n", bmp_formats);
964
965     list = HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, (nCfgs + bmp_formats)*sizeof(WineGLPixelFormat));
966
967     /* Fill the pixel format list. Put onscreen formats at the top and offscreen ones at the bottom.
968      * Do this as GLX doesn't guarantee that the list is sorted */
969     for(run=0; run < 2; run++)
970     {
971         for(i=0; i<nCfgs; i++) {
972             pglXGetFBConfigAttrib(display, cfgs[i], GLX_FBCONFIG_ID, &fmt_id);
973             visinfo = pglXGetVisualFromFBConfig(display, cfgs[i]);
974
975             /* The first run we only add onscreen formats (ones which have an associated X Visual).
976              * The second run we only set offscreen formats. */
977             if(!run && visinfo)
978             {
979                 /* We implement child window rendering using offscreen buffers (using composite or an XPixmap).
980                  * The contents is copied to the destination using XCopyArea. For the copying to work
981                  * the depth of the source and destination window should be the same. In general this should
982                  * not be a problem for OpenGL as drivers only advertise formats with a similar depth (or no depth).
983                  * As of the introduction of composition managers at least Nvidia now also offers ARGB visuals
984                  * with a depth of 32 in addition to the default 24 bit. In order to prevent BadMatch errors we only
985                  * list formats with the same depth. */
986                 if(visinfo->depth != screen_depth)
987                 {
988                     XFree(visinfo);
989                     continue;
990                 }
991
992                 TRACE("Found onscreen format FBCONFIG_ID 0x%x corresponding to iPixelFormat %d at GLX index %d\n", fmt_id, size+1, i);
993                 list[size].iPixelFormat = size+1; /* The index starts at 1 */
994                 list[size].fbconfig = cfgs[i];
995                 list[size].fmt_id = fmt_id;
996                 list[size].render_type = get_render_type_from_fbconfig(display, cfgs[i]);
997                 list[size].offscreenOnly = FALSE;
998                 list[size].dwFlags = 0;
999                 size++;
1000                 onscreen_size++;
1001
1002                 /* Clone a format if it is bitmap capable for indirect rendering to bitmaps */
1003                 if(check_fbconfig_bitmap_capability(display, cfgs[i]))
1004                 {
1005                     TRACE("Found bitmap capable format FBCONFIG_ID 0x%x corresponding to iPixelFormat %d at GLX index %d\n", fmt_id, size+1, i);
1006                     list[size].iPixelFormat = size+1; /* The index starts at 1 */
1007                     list[size].fbconfig = cfgs[i];
1008                     list[size].fmt_id = fmt_id;
1009                     list[size].render_type = get_render_type_from_fbconfig(display, cfgs[i]);
1010                     list[size].offscreenOnly = FALSE;
1011                     list[size].dwFlags = PFD_DRAW_TO_BITMAP | PFD_SUPPORT_GDI | PFD_GENERIC_FORMAT;
1012                     size++;
1013                     onscreen_size++;
1014                 }
1015             } else if(run && !visinfo) {
1016                 int window_drawable=0;
1017                 pglXGetFBConfigAttrib(gdi_display, cfgs[i], GLX_DRAWABLE_TYPE, &window_drawable);
1018
1019                 /* Recent Nvidia drivers and DRI drivers offer window drawable formats without a visual.
1020                  * This are formats like 16-bit rgb on a 24-bit desktop. In order to support these formats
1021                  * onscreen we would have to use glXCreateWindow instead of XCreateWindow. Further it will
1022                  * likely make our child window opengl rendering more complicated since likely you can't use
1023                  * XCopyArea on a GLX Window.
1024                  * For now ignore fbconfigs which are window drawable but lack a visual. */
1025                 if(window_drawable & GLX_WINDOW_BIT)
1026                 {
1027                     TRACE("Skipping FBCONFIG_ID 0x%x as an offscreen format because it is window_drawable\n", fmt_id);
1028                     continue;
1029                 }
1030
1031                 TRACE("Found offscreen format FBCONFIG_ID 0x%x corresponding to iPixelFormat %d at GLX index %d\n", fmt_id, size+1, i);
1032                 list[size].iPixelFormat = size+1; /* The index starts at 1 */
1033                 list[size].fbconfig = cfgs[i];
1034                 list[size].fmt_id = fmt_id;
1035                 list[size].render_type = get_render_type_from_fbconfig(display, cfgs[i]);
1036                 list[size].offscreenOnly = TRUE;
1037                 list[size].dwFlags = 0;
1038                 size++;
1039             }
1040
1041             if (visinfo) XFree(visinfo);
1042         }
1043     }
1044
1045     XFree(cfgs);
1046
1047 done:
1048     if (size_ret) *size_ret = size;
1049     if (onscreen_size_ret) *onscreen_size_ret = onscreen_size;
1050     wine_tsx11_unlock();
1051     return list;
1052 }
1053
1054 /* GLX can advertise dozens of different pixelformats including offscreen and onscreen ones.
1055  * In our WGL implementation we only support a subset of these formats namely the format of
1056  * Wine's main visual and offscreen formats (if they are available).
1057  * This function converts a WGL format to its corresponding GLX one. It returns a WineGLPixelFormat
1058  * and it returns the number of supported WGL formats in fmt_count.
1059  */
1060 static WineGLPixelFormat* ConvertPixelFormatWGLtoGLX(Display *display, int iPixelFormat, BOOL AllowOffscreen, int *fmt_count)
1061 {
1062     WineGLPixelFormat *list, *res = NULL;
1063     int size, onscreen_size;
1064
1065     if (!(list = get_formats(display, &size, &onscreen_size ))) return NULL;
1066
1067     /* Check if the pixelformat is valid. Note that it is legal to pass an invalid
1068      * iPixelFormat in case of probing the number of pixelformats.
1069      */
1070     if((iPixelFormat > 0) && (iPixelFormat <= size) &&
1071        (!list[iPixelFormat-1].offscreenOnly || AllowOffscreen)) {
1072         res = &list[iPixelFormat-1];
1073         TRACE("Returning fmt_id=%#x for iPixelFormat=%d\n", res->fmt_id, iPixelFormat);
1074     }
1075
1076     if(AllowOffscreen)
1077         *fmt_count = size;
1078     else
1079         *fmt_count = onscreen_size;
1080
1081     TRACE("Number of returned pixelformats=%d\n", *fmt_count);
1082
1083     return res;
1084 }
1085
1086 /* Search our internal pixelformat list for the WGL format corresponding to the given fbconfig */
1087 static WineGLPixelFormat* ConvertPixelFormatGLXtoWGL(Display *display, int fmt_id, DWORD dwFlags)
1088 {
1089     WineGLPixelFormat *list;
1090     int i, size;
1091
1092     if (!(list = get_formats(display, &size, NULL ))) return NULL;
1093
1094     for(i=0; i<size; i++) {
1095         /* A GLX format can appear multiple times in the pixel format list due to fake formats for bitmap rendering.
1096          * Fake formats might get selected when the user passes the proper flags using the dwFlags parameter. */
1097         if( (list[i].fmt_id == fmt_id) && ((list[i].dwFlags & dwFlags) == dwFlags) ) {
1098             TRACE("Returning iPixelFormat %d for fmt_id 0x%x\n", list[i].iPixelFormat, fmt_id);
1099             return &list[i];
1100         }
1101     }
1102     TRACE("No compatible format found for fmt_id 0x%x\n", fmt_id);
1103     return NULL;
1104 }
1105
1106 int pixelformat_from_fbconfig_id(XID fbconfig_id)
1107 {
1108     WineGLPixelFormat *fmt;
1109
1110     if (!fbconfig_id) return 0;
1111
1112     fmt = ConvertPixelFormatGLXtoWGL(gdi_display, fbconfig_id, 0 /* no flags */);
1113     if(fmt)
1114         return fmt->iPixelFormat;
1115     /* This will happen on hwnds without a pixel format set; it's ok */
1116     return 0;
1117 }
1118
1119
1120 /* Mark any allocated context using the glx drawable 'old' to use 'new' */
1121 void mark_drawable_dirty(Drawable old, Drawable new)
1122 {
1123     Wine_GLContext *ctx;
1124     for (ctx = context_list; ctx; ctx = ctx->next) {
1125         if (old == ctx->drawables[0]) {
1126             ctx->drawables[0] = new;
1127             ctx->refresh_drawables = TRUE;
1128         }
1129         if (old == ctx->drawables[1]) {
1130             ctx->drawables[1] = new;
1131             ctx->refresh_drawables = TRUE;
1132         }
1133     }
1134 }
1135
1136 /* Given the current context, make sure its drawable is sync'd */
1137 static inline void sync_context(Wine_GLContext *context)
1138 {
1139     if(context && context->refresh_drawables) {
1140         if (glxRequireVersion(3))
1141             pglXMakeContextCurrent(gdi_display, context->drawables[0],
1142                                    context->drawables[1], context->ctx);
1143         else
1144             pglXMakeCurrent(gdi_display, context->drawables[0], context->ctx);
1145         context->refresh_drawables = FALSE;
1146     }
1147 }
1148
1149
1150 static GLXContext create_glxcontext(Display *display, Wine_GLContext *context, GLXContext shareList)
1151 {
1152     GLXContext ctx;
1153
1154     /* We use indirect rendering for rendering to bitmaps. See get_formats for a comment about this. */
1155     BOOL indirect = (context->fmt->dwFlags & PFD_DRAW_TO_BITMAP) ? FALSE : TRUE;
1156
1157     if(context->gl3_context)
1158     {
1159         if(context->numAttribs)
1160             ctx = pglXCreateContextAttribsARB(gdi_display, context->fmt->fbconfig, shareList, indirect, context->attribList);
1161         else
1162             ctx = pglXCreateContextAttribsARB(gdi_display, context->fmt->fbconfig, shareList, indirect, NULL);
1163     }
1164     else if(context->vis)
1165         ctx = pglXCreateContext(gdi_display, context->vis, shareList, indirect);
1166     else /* Create a GLX Context for a pbuffer */
1167         ctx = pglXCreateNewContext(gdi_display, context->fmt->fbconfig, context->fmt->render_type, shareList, TRUE);
1168
1169     return ctx;
1170 }
1171
1172
1173 Drawable create_glxpixmap(Display *display, XVisualInfo *vis, Pixmap parent)
1174 {
1175     return pglXCreateGLXPixmap(display, vis, parent);
1176 }
1177
1178
1179 static XID create_bitmap_glxpixmap(X11DRV_PDEVICE *physDev, WineGLPixelFormat *fmt)
1180 {
1181     GLXPixmap ret = 0;
1182     XVisualInfo *vis;
1183
1184     wine_tsx11_lock();
1185
1186     vis = pglXGetVisualFromFBConfig(gdi_display, fmt->fbconfig);
1187     if(vis) {
1188         if(vis->depth == physDev->bitmap->pixmap_depth)
1189             ret = pglXCreateGLXPixmap(gdi_display, vis, physDev->bitmap->pixmap);
1190         XFree(vis);
1191     }
1192     wine_tsx11_unlock();
1193     TRACE("return %lx\n", ret);
1194     return ret;
1195 }
1196
1197 /**
1198  * X11DRV_ChoosePixelFormat
1199  *
1200  * Equivalent to glXChooseVisual.
1201  */
1202 int CDECL X11DRV_ChoosePixelFormat(X11DRV_PDEVICE *physDev,
1203                              const PIXELFORMATDESCRIPTOR *ppfd) {
1204     WineGLPixelFormat *list;
1205     int onscreen_size;
1206     int ret = 0;
1207     int value = 0;
1208     int i = 0;
1209     int bestFormat = -1;
1210     int bestDBuffer = -1;
1211     int bestStereo = -1;
1212     int bestColor = -1;
1213     int bestAlpha = -1;
1214     int bestDepth = -1;
1215     int bestStencil = -1;
1216     int bestAux = -1;
1217
1218     if (!has_opengl()) return 0;
1219
1220     if (TRACE_ON(wgl)) {
1221         TRACE("(%p,%p)\n", physDev, ppfd);
1222
1223         dump_PIXELFORMATDESCRIPTOR(ppfd);
1224     }
1225
1226     if (!(list = get_formats(gdi_display, NULL, &onscreen_size ))) return 0;
1227
1228     wine_tsx11_lock();
1229     for(i=0; i<onscreen_size; i++)
1230     {
1231         int dwFlags = 0;
1232         int iPixelType = 0;
1233         int alpha=0, color=0, depth=0, stencil=0, aux=0;
1234         WineGLPixelFormat *fmt = &list[i];
1235
1236         /* Pixel type */
1237         pglXGetFBConfigAttrib(gdi_display, fmt->fbconfig, GLX_RENDER_TYPE, &value);
1238         if (value & GLX_RGBA_BIT)
1239             iPixelType = PFD_TYPE_RGBA;
1240         else
1241             iPixelType = PFD_TYPE_COLORINDEX;
1242
1243         if (ppfd->iPixelType != iPixelType)
1244         {
1245             TRACE("pixel type mismatch for iPixelFormat=%d\n", i+1);
1246             continue;
1247         }
1248
1249         /* Only use bitmap capable for formats for bitmap rendering.
1250          * See get_formats for more info. */
1251         if( (ppfd->dwFlags & PFD_DRAW_TO_BITMAP) != (fmt->dwFlags & PFD_DRAW_TO_BITMAP))
1252         {
1253             TRACE("PFD_DRAW_TO_BITMAP mismatch for iPixelFormat=%d\n", i+1);
1254             continue;
1255         }
1256
1257         pglXGetFBConfigAttrib(gdi_display, fmt->fbconfig, GLX_DOUBLEBUFFER, &value);
1258         if (value) dwFlags |= PFD_DOUBLEBUFFER;
1259         pglXGetFBConfigAttrib(gdi_display, fmt->fbconfig, GLX_STEREO, &value);
1260         if (value) dwFlags |= PFD_STEREO;
1261         pglXGetFBConfigAttrib(gdi_display, fmt->fbconfig, GLX_BUFFER_SIZE, &color); /* cColorBits */
1262         pglXGetFBConfigAttrib(gdi_display, fmt->fbconfig, GLX_ALPHA_SIZE, &alpha); /* cAlphaBits */
1263         pglXGetFBConfigAttrib(gdi_display, fmt->fbconfig, GLX_DEPTH_SIZE, &depth); /* cDepthBits */
1264         pglXGetFBConfigAttrib(gdi_display, fmt->fbconfig, GLX_STENCIL_SIZE, &stencil); /* cStencilBits */
1265         pglXGetFBConfigAttrib(gdi_display, fmt->fbconfig, GLX_AUX_BUFFERS, &aux); /* cAuxBuffers */
1266
1267         /* The behavior of PDF_STEREO/PFD_STEREO_DONTCARE and PFD_DOUBLEBUFFER / PFD_DOUBLEBUFFER_DONTCARE
1268          * is not very clear on MSDN. They specify that ChoosePixelFormat tries to match pixel formats
1269          * with the flag (PFD_STEREO / PFD_DOUBLEBUFFERING) set. Otherwise it says that it tries to match
1270          * formats without the given flag set.
1271          * A test on Windows using a Radeon 9500pro on WinXP (the driver doesn't support Stereo)
1272          * has indicated that a format without stereo is returned when stereo is unavailable.
1273          * So in case PFD_STEREO is set, formats that support it should have priority above formats
1274          * without. In case PFD_STEREO_DONTCARE is set, stereo is ignored.
1275          *
1276          * To summarize the following is most likely the correct behavior:
1277          * stereo not set -> prefer no-stereo formats, else also accept stereo formats
1278          * stereo set -> prefer stereo formats, else also accept no-stereo formats
1279          * stereo don't care -> it doesn't matter whether we get stereo or not
1280          *
1281          * In Wine we will treat no-stereo the same way as don't care because it makes
1282          * format selection even more complicated and second drivers with Stereo advertise
1283          * each format twice anyway.
1284          */
1285
1286         /* Doublebuffer, see the comments above */
1287         if( !(ppfd->dwFlags & PFD_DOUBLEBUFFER_DONTCARE) ) {
1288             if( ((ppfd->dwFlags & PFD_DOUBLEBUFFER) != bestDBuffer) &&
1289                 ((dwFlags & PFD_DOUBLEBUFFER) == (ppfd->dwFlags & PFD_DOUBLEBUFFER)) )
1290             {
1291                 bestDBuffer = dwFlags & PFD_DOUBLEBUFFER;
1292                 bestStereo = dwFlags & PFD_STEREO;
1293                 bestAlpha = alpha;
1294                 bestColor = color;
1295                 bestDepth = depth;
1296                 bestStencil = stencil;
1297                 bestAux = aux;
1298                 bestFormat = i;
1299                 continue;
1300             }
1301             if(bestDBuffer != -1 && (dwFlags & PFD_DOUBLEBUFFER) != bestDBuffer)
1302                 continue;
1303         }
1304
1305         /* Stereo, see the comments above. */
1306         if( !(ppfd->dwFlags & PFD_STEREO_DONTCARE) ) {
1307             if( ((ppfd->dwFlags & PFD_STEREO) != bestStereo) &&
1308                 ((dwFlags & PFD_STEREO) == (ppfd->dwFlags & PFD_STEREO)) )
1309             {
1310                 bestDBuffer = dwFlags & PFD_DOUBLEBUFFER;
1311                 bestStereo = dwFlags & PFD_STEREO;
1312                 bestAlpha = alpha;
1313                 bestColor = color;
1314                 bestDepth = depth;
1315                 bestStencil = stencil;
1316                 bestAux = aux;
1317                 bestFormat = i;
1318                 continue;
1319             }
1320             if(bestStereo != -1 && (dwFlags & PFD_STEREO) != bestStereo)
1321                 continue;
1322         }
1323
1324         /* Below we will do a number of checks to select the 'best' pixelformat.
1325          * We assume the precedence cColorBits > cAlphaBits > cDepthBits > cStencilBits -> cAuxBuffers.
1326          * The code works by trying to match the most important options as close as possible.
1327          * When a reasonable format is found, we will try to match more options.
1328          * It appears (see the opengl32 test) that Windows opengl drivers ignore options
1329          * like cColorBits, cAlphaBits and friends if they are set to 0, so they are considered
1330          * as DONTCARE. At least Serious Sam TSE relies on this behavior. */
1331
1332         /* Color bits */
1333         if(ppfd->cColorBits) {
1334             if( ((ppfd->cColorBits > bestColor) && (color > bestColor)) ||
1335                 ((color >= ppfd->cColorBits) && (color < bestColor)) )
1336             {
1337                 bestDBuffer = dwFlags & PFD_DOUBLEBUFFER;
1338                 bestStereo = dwFlags & PFD_STEREO;
1339                 bestAlpha = alpha;
1340                 bestColor = color;
1341                 bestDepth = depth;
1342                 bestStencil = stencil;
1343                 bestAux = aux;
1344                 bestFormat = i;
1345                 continue;
1346             } else if(bestColor != color) {  /* Do further checks if the format is compatible */
1347                 TRACE("color mismatch for iPixelFormat=%d\n", i+1);
1348                 continue;
1349             }
1350         }
1351
1352         /* Alpha bits */
1353         if(ppfd->cAlphaBits) {
1354             if( ((ppfd->cAlphaBits > bestAlpha) && (alpha > bestAlpha)) ||
1355                 ((alpha >= ppfd->cAlphaBits) && (alpha < bestAlpha)) )
1356             {
1357                 bestDBuffer = dwFlags & PFD_DOUBLEBUFFER;
1358                 bestStereo = dwFlags & PFD_STEREO;
1359                 bestAlpha = alpha;
1360                 bestColor = color;
1361                 bestDepth = depth;
1362                 bestStencil = stencil;
1363                 bestAux = aux;
1364                 bestFormat = i;
1365                 continue;
1366             } else if(bestAlpha != alpha) {
1367                 TRACE("alpha mismatch for iPixelFormat=%d\n", i+1);
1368                 continue;
1369             }
1370         }
1371
1372         /* Depth bits */
1373         if(ppfd->cDepthBits) {
1374             if( ((ppfd->cDepthBits > bestDepth) && (depth > bestDepth)) ||
1375                 ((depth >= ppfd->cDepthBits) && (depth < bestDepth)) )
1376             {
1377                 bestDBuffer = dwFlags & PFD_DOUBLEBUFFER;
1378                 bestStereo = dwFlags & PFD_STEREO;
1379                 bestAlpha = alpha;
1380                 bestColor = color;
1381                 bestDepth = depth;
1382                 bestStencil = stencil;
1383                 bestAux = aux;
1384                 bestFormat = i;
1385                 continue;
1386             } else if(bestDepth != depth) {
1387                 TRACE("depth mismatch for iPixelFormat=%d\n", i+1);
1388                 continue;
1389             }
1390         }
1391
1392         /* Stencil bits */
1393         if(ppfd->cStencilBits) {
1394             if( ((ppfd->cStencilBits > bestStencil) && (stencil > bestStencil)) ||
1395                 ((stencil >= ppfd->cStencilBits) && (stencil < bestStencil)) )
1396             {
1397                 bestDBuffer = dwFlags & PFD_DOUBLEBUFFER;
1398                 bestStereo = dwFlags & PFD_STEREO;
1399                 bestAlpha = alpha;
1400                 bestColor = color;
1401                 bestDepth = depth;
1402                 bestStencil = stencil;
1403                 bestAux = aux;
1404                 bestFormat = i;
1405                 continue;
1406             } else if(bestStencil != stencil) {
1407                 TRACE("stencil mismatch for iPixelFormat=%d\n", i+1);
1408                 continue;
1409             }
1410         }
1411
1412         /* Aux buffers */
1413         if(ppfd->cAuxBuffers) {
1414             if( ((ppfd->cAuxBuffers > bestAux) && (aux > bestAux)) ||
1415                 ((aux >= ppfd->cAuxBuffers) && (aux < bestAux)) )
1416             {
1417                 bestDBuffer = dwFlags & PFD_DOUBLEBUFFER;
1418                 bestStereo = dwFlags & PFD_STEREO;
1419                 bestAlpha = alpha;
1420                 bestColor = color;
1421                 bestDepth = depth;
1422                 bestStencil = stencil;
1423                 bestAux = aux;
1424                 bestFormat = i;
1425                 continue;
1426             } else if(bestAux != aux) {
1427                 TRACE("aux mismatch for iPixelFormat=%d\n", i+1);
1428                 continue;
1429             }
1430         }
1431     }
1432
1433     if(bestFormat == -1) {
1434         TRACE("No matching mode was found returning 0\n");
1435         ret = 0;
1436     }
1437     else {
1438         ret = bestFormat+1; /* the return value should be a 1-based index */
1439         TRACE("Successfully found a matching mode, returning index: %d %x\n", ret, list[bestFormat].fmt_id);
1440     }
1441
1442     wine_tsx11_unlock();
1443
1444     return ret;
1445 }
1446 /**
1447  * X11DRV_DescribePixelFormat
1448  *
1449  * Get the pixel-format descriptor associated to the given id
1450  */
1451 int CDECL X11DRV_DescribePixelFormat(X11DRV_PDEVICE *physDev,
1452                                int iPixelFormat,
1453                                UINT nBytes,
1454                                PIXELFORMATDESCRIPTOR *ppfd) {
1455   /*XVisualInfo *vis;*/
1456   int value;
1457   int rb,gb,bb,ab;
1458   WineGLPixelFormat *fmt;
1459   int ret = 0;
1460   int fmt_count = 0;
1461
1462   if (!has_opengl()) return 0;
1463
1464   TRACE("(%p,%d,%d,%p)\n", physDev, iPixelFormat, nBytes, ppfd);
1465
1466   /* Look for the iPixelFormat in our list of supported formats. If it is supported we get the index in the FBConfig table and the number of supported formats back */
1467   fmt = ConvertPixelFormatWGLtoGLX(gdi_display, iPixelFormat, FALSE /* Offscreen */, &fmt_count);
1468   if (ppfd == NULL) {
1469       /* The application is only querying the number of pixelformats */
1470       return fmt_count;
1471   } else if(fmt == NULL) {
1472       WARN("unexpected iPixelFormat(%d): not >=1 and <=nFormats(%d), returning NULL!\n", iPixelFormat, fmt_count);
1473       return 0;
1474   }
1475
1476   if (nBytes < sizeof(PIXELFORMATDESCRIPTOR)) {
1477     ERR("Wrong structure size !\n");
1478     /* Should set error */
1479     return 0;
1480   }
1481
1482   ret = fmt_count;
1483
1484   memset(ppfd, 0, sizeof(PIXELFORMATDESCRIPTOR));
1485   ppfd->nSize = sizeof(PIXELFORMATDESCRIPTOR);
1486   ppfd->nVersion = 1;
1487
1488   /* These flags are always the same... */
1489   ppfd->dwFlags = PFD_SUPPORT_OPENGL;
1490   /* Now the flags extracted from the Visual */
1491
1492   wine_tsx11_lock();
1493
1494   pglXGetFBConfigAttrib(gdi_display, fmt->fbconfig, GLX_DRAWABLE_TYPE, &value);
1495   if(value & GLX_WINDOW_BIT)
1496       ppfd->dwFlags |= PFD_DRAW_TO_WINDOW;
1497
1498   /* On Windows bitmap rendering is only offered using the GDI Software renderer. We reserve some formats (see get_formats for more info)
1499    * for bitmap rendering since we require indirect rendering for this. Further pixel format logs of a GeforceFX, Geforce8800GT, Radeon HD3400 and a
1500    * Radeon 9000 indicated that all bitmap formats have PFD_SUPPORT_GDI. Except for 2 formats on the Radeon 9000 none of the hw accelerated formats
1501    * offered the GDI bit either. */
1502   ppfd->dwFlags |= fmt->dwFlags & (PFD_DRAW_TO_BITMAP | PFD_SUPPORT_GDI);
1503
1504   /* PFD_GENERIC_FORMAT - gdi software rendering
1505    * PFD_GENERIC_ACCELERATED - some parts are accelerated by a display driver (MCD e.g. 3dfx minigl)
1506    * none set - full hardware accelerated by a ICD
1507    *
1508    * We only set PFD_GENERIC_FORMAT on bitmap formats (see get_formats) as that's what ATI and Nvidia Windows drivers do  */
1509   ppfd->dwFlags |= fmt->dwFlags & (PFD_GENERIC_FORMAT | PFD_GENERIC_ACCELERATED);
1510
1511   pglXGetFBConfigAttrib(gdi_display, fmt->fbconfig, GLX_DOUBLEBUFFER, &value);
1512   if (value) {
1513       ppfd->dwFlags |= PFD_DOUBLEBUFFER;
1514       ppfd->dwFlags &= ~PFD_SUPPORT_GDI;
1515   }
1516   pglXGetFBConfigAttrib(gdi_display, fmt->fbconfig, GLX_STEREO, &value); if (value) ppfd->dwFlags |= PFD_STEREO;
1517
1518   /* Pixel type */
1519   pglXGetFBConfigAttrib(gdi_display, fmt->fbconfig, GLX_RENDER_TYPE, &value);
1520   if (value & GLX_RGBA_BIT)
1521     ppfd->iPixelType = PFD_TYPE_RGBA;
1522   else
1523     ppfd->iPixelType = PFD_TYPE_COLORINDEX;
1524
1525   /* Color bits */
1526   pglXGetFBConfigAttrib(gdi_display, fmt->fbconfig, GLX_BUFFER_SIZE, &value);
1527   ppfd->cColorBits = value;
1528
1529   /* Red, green, blue and alpha bits / shifts */
1530   if (ppfd->iPixelType == PFD_TYPE_RGBA) {
1531     pglXGetFBConfigAttrib(gdi_display, fmt->fbconfig, GLX_RED_SIZE, &rb);
1532     pglXGetFBConfigAttrib(gdi_display, fmt->fbconfig, GLX_GREEN_SIZE, &gb);
1533     pglXGetFBConfigAttrib(gdi_display, fmt->fbconfig, GLX_BLUE_SIZE, &bb);
1534     pglXGetFBConfigAttrib(gdi_display, fmt->fbconfig, GLX_ALPHA_SIZE, &ab);
1535
1536     ppfd->cRedBits = rb;
1537     ppfd->cRedShift = gb + bb + ab;
1538     ppfd->cBlueBits = bb;
1539     ppfd->cBlueShift = ab;
1540     ppfd->cGreenBits = gb;
1541     ppfd->cGreenShift = bb + ab;
1542     ppfd->cAlphaBits = ab;
1543     ppfd->cAlphaShift = 0;
1544   } else {
1545     ppfd->cRedBits = 0;
1546     ppfd->cRedShift = 0;
1547     ppfd->cBlueBits = 0;
1548     ppfd->cBlueShift = 0;
1549     ppfd->cGreenBits = 0;
1550     ppfd->cGreenShift = 0;
1551     ppfd->cAlphaBits = 0;
1552     ppfd->cAlphaShift = 0;
1553   }
1554
1555   /* Accum RGBA bits */
1556   pglXGetFBConfigAttrib(gdi_display, fmt->fbconfig, GLX_ACCUM_RED_SIZE, &rb);
1557   pglXGetFBConfigAttrib(gdi_display, fmt->fbconfig, GLX_ACCUM_GREEN_SIZE, &gb);
1558   pglXGetFBConfigAttrib(gdi_display, fmt->fbconfig, GLX_ACCUM_BLUE_SIZE, &bb);
1559   pglXGetFBConfigAttrib(gdi_display, fmt->fbconfig, GLX_ACCUM_ALPHA_SIZE, &ab);
1560
1561   ppfd->cAccumBits = rb+gb+bb+ab;
1562   ppfd->cAccumRedBits = rb;
1563   ppfd->cAccumGreenBits = gb;
1564   ppfd->cAccumBlueBits = bb;
1565   ppfd->cAccumAlphaBits = ab;
1566
1567   /* Aux bits */
1568   pglXGetFBConfigAttrib(gdi_display, fmt->fbconfig, GLX_AUX_BUFFERS, &value);
1569   ppfd->cAuxBuffers = value;
1570
1571   /* Depth bits */
1572   pglXGetFBConfigAttrib(gdi_display, fmt->fbconfig, GLX_DEPTH_SIZE, &value);
1573   ppfd->cDepthBits = value;
1574
1575   /* stencil bits */
1576   pglXGetFBConfigAttrib(gdi_display, fmt->fbconfig, GLX_STENCIL_SIZE, &value);
1577   ppfd->cStencilBits = value;
1578
1579   wine_tsx11_unlock();
1580
1581   ppfd->iLayerType = PFD_MAIN_PLANE;
1582
1583   if (TRACE_ON(wgl)) {
1584     dump_PIXELFORMATDESCRIPTOR(ppfd);
1585   }
1586
1587   return ret;
1588 }
1589
1590 /**
1591  * X11DRV_GetPixelFormat
1592  *
1593  * Get the pixel-format id used by this DC
1594  */
1595 int CDECL X11DRV_GetPixelFormat(X11DRV_PDEVICE *physDev) {
1596   WineGLPixelFormat *fmt;
1597   int tmp;
1598   TRACE("(%p)\n", physDev);
1599
1600   if (!physDev->current_pf) return 0;  /* not set yet */
1601
1602   fmt = ConvertPixelFormatWGLtoGLX(gdi_display, physDev->current_pf, TRUE, &tmp);
1603   if(!fmt)
1604   {
1605     ERR("Unable to find a WineGLPixelFormat for iPixelFormat=%d\n", physDev->current_pf);
1606     return 0;
1607   }
1608   else if(fmt->offscreenOnly)
1609   {
1610     /* Offscreen formats can't be used with traditional WGL calls.
1611      * As has been verified on Windows GetPixelFormat doesn't fail but returns iPixelFormat=1. */
1612      TRACE("Returning iPixelFormat=1 for offscreen format: %d\n", fmt->iPixelFormat);
1613     return 1;
1614   }
1615
1616   TRACE("(%p): returns %d\n", physDev, physDev->current_pf);
1617   return physDev->current_pf;
1618 }
1619
1620 /* This function is the core of X11DRV_SetPixelFormat and X11DRV_SetPixelFormatWINE.
1621  * Both functions are the same except that X11DRV_SetPixelFormatWINE allows you to
1622  * set the pixel format multiple times. */
1623 static BOOL internal_SetPixelFormat(X11DRV_PDEVICE *physDev,
1624                            int iPixelFormat,
1625                            const PIXELFORMATDESCRIPTOR *ppfd) {
1626     WineGLPixelFormat *fmt;
1627     int value;
1628     HWND hwnd;
1629
1630     /* SetPixelFormat is not allowed on the X root_window e.g. GetDC(0) */
1631     if(get_glxdrawable(physDev) == root_window)
1632     {
1633         ERR("Invalid operation on root_window\n");
1634         return FALSE;
1635     }
1636
1637     /* Check if iPixelFormat is in our list of supported formats to see if it is supported. */
1638     fmt = ConvertPixelFormatWGLtoGLX(gdi_display, iPixelFormat, FALSE /* Offscreen */, &value);
1639     if(!fmt) {
1640         ERR("Invalid iPixelFormat: %d\n", iPixelFormat);
1641         return FALSE;
1642     }
1643
1644     wine_tsx11_lock();
1645     pglXGetFBConfigAttrib(gdi_display, fmt->fbconfig, GLX_DRAWABLE_TYPE, &value);
1646     wine_tsx11_unlock();
1647
1648     hwnd = WindowFromDC(physDev->hdc);
1649     if(hwnd) {
1650         if(!(value&GLX_WINDOW_BIT)) {
1651             WARN("Pixel format %d is not compatible for window rendering\n", iPixelFormat);
1652             return FALSE;
1653         }
1654
1655         if(!SendMessageW(hwnd, WM_X11DRV_SET_WIN_FORMAT, fmt->fmt_id, 0)) {
1656             ERR("Couldn't set format of the window, returning failure\n");
1657             return FALSE;
1658         }
1659     }
1660     else if(physDev->bitmap) {
1661         if(!(value&GLX_PIXMAP_BIT)) {
1662             WARN("Pixel format %d is not compatible for bitmap rendering\n", iPixelFormat);
1663             return FALSE;
1664         }
1665
1666         physDev->bitmap->glxpixmap = create_bitmap_glxpixmap(physDev, fmt);
1667         if(!physDev->bitmap->glxpixmap) {
1668             WARN("Couldn't create glxpixmap for pixel format %d\n", iPixelFormat);
1669             return FALSE;
1670         }
1671     }
1672     else {
1673         FIXME("called on a non-window, non-bitmap object?\n");
1674     }
1675
1676     physDev->current_pf = iPixelFormat;
1677
1678     if (TRACE_ON(wgl)) {
1679         int gl_test = 0;
1680
1681         wine_tsx11_lock();
1682         gl_test = pglXGetFBConfigAttrib(gdi_display, fmt->fbconfig, GLX_FBCONFIG_ID, &value);
1683         if (gl_test) {
1684            ERR("Failed to retrieve FBCONFIG_ID from GLXFBConfig, expect problems.\n");
1685         } else {
1686             TRACE(" FBConfig have :\n");
1687             TRACE(" - FBCONFIG_ID   0x%x\n", value);
1688             pglXGetFBConfigAttrib(gdi_display, fmt->fbconfig, GLX_VISUAL_ID, &value);
1689             TRACE(" - VISUAL_ID     0x%x\n", value);
1690             pglXGetFBConfigAttrib(gdi_display, fmt->fbconfig, GLX_DRAWABLE_TYPE, &value);
1691             TRACE(" - DRAWABLE_TYPE 0x%x\n", value);
1692         }
1693         wine_tsx11_unlock();
1694     }
1695     return TRUE;
1696 }
1697
1698
1699 /**
1700  * X11DRV_SetPixelFormat
1701  *
1702  * Set the pixel-format id used by this DC
1703  */
1704 BOOL CDECL X11DRV_SetPixelFormat(X11DRV_PDEVICE *physDev,
1705                            int iPixelFormat,
1706                            const PIXELFORMATDESCRIPTOR *ppfd) {
1707     TRACE("(%p,%d,%p)\n", physDev, iPixelFormat, ppfd);
1708
1709     if (!has_opengl()) return FALSE;
1710
1711     if(physDev->current_pf)  /* cannot change it if already set */
1712         return (physDev->current_pf == iPixelFormat);
1713
1714     return internal_SetPixelFormat(physDev, iPixelFormat, ppfd);
1715 }
1716
1717 /**
1718  * X11DRV_wglCopyContext
1719  *
1720  * For OpenGL32 wglCopyContext.
1721  */
1722 BOOL CDECL X11DRV_wglCopyContext(HGLRC hglrcSrc, HGLRC hglrcDst, UINT mask) {
1723     Wine_GLContext *src = (Wine_GLContext*)hglrcSrc;
1724     Wine_GLContext *dst = (Wine_GLContext*)hglrcDst;
1725
1726     TRACE("hglrcSrc: (%p), hglrcDst: (%p), mask: %#x\n", hglrcSrc, hglrcDst, mask);
1727
1728     wine_tsx11_lock();
1729     pglXCopyContext(gdi_display, src->ctx, dst->ctx, mask);
1730     wine_tsx11_unlock();
1731
1732     /* As opposed to wglCopyContext, glXCopyContext doesn't return anything, so hopefully we passed */
1733     return TRUE;
1734 }
1735
1736 /**
1737  * X11DRV_wglCreateContext
1738  *
1739  * For OpenGL32 wglCreateContext.
1740  */
1741 HGLRC CDECL X11DRV_wglCreateContext(X11DRV_PDEVICE *physDev)
1742 {
1743     Wine_GLContext *ret;
1744     WineGLPixelFormat *fmt;
1745     int hdcPF = physDev->current_pf;
1746     int fmt_count = 0;
1747     HDC hdc = physDev->hdc;
1748
1749     TRACE("(%p)->(PF:%d)\n", hdc, hdcPF);
1750
1751     if (!has_opengl()) return 0;
1752
1753     fmt = ConvertPixelFormatWGLtoGLX(gdi_display, hdcPF, TRUE /* Offscreen */, &fmt_count);
1754     /* We can render using the iPixelFormat (1) of Wine's Main visual AND using some offscreen formats.
1755      * Note that standard WGL-calls don't recognize offscreen-only formats. For that reason pbuffers
1756      * use a sort of 'proxy' HDC (wglGetPbufferDCARB).
1757      * If this fails something is very wrong on the system. */
1758     if(!fmt) {
1759         ERR("Cannot get FB Config for iPixelFormat %d, expect problems!\n", hdcPF);
1760         SetLastError(ERROR_INVALID_PIXEL_FORMAT);
1761         return NULL;
1762     }
1763
1764     wine_tsx11_lock();
1765     ret = alloc_context();
1766     ret->hdc = hdc;
1767     ret->fmt = fmt;
1768     ret->has_been_current = FALSE;
1769     ret->sharing = FALSE;
1770
1771     ret->vis = pglXGetVisualFromFBConfig(gdi_display, fmt->fbconfig);
1772     ret->ctx = create_glxcontext(gdi_display, ret, NULL);
1773     wine_tsx11_unlock();
1774
1775     TRACE(" creating context %p (GL context creation delayed)\n", ret);
1776     return (HGLRC) ret;
1777 }
1778
1779 /**
1780  * X11DRV_wglDeleteContext
1781  *
1782  * For OpenGL32 wglDeleteContext.
1783  */
1784 BOOL CDECL X11DRV_wglDeleteContext(HGLRC hglrc)
1785 {
1786     Wine_GLContext *ctx = (Wine_GLContext *) hglrc;
1787
1788     TRACE("(%p)\n", hglrc);
1789
1790     if (!has_opengl()) return 0;
1791
1792     if (!is_valid_context(ctx))
1793     {
1794         WARN("Error deleting context !\n");
1795         SetLastError(ERROR_INVALID_HANDLE);
1796         return FALSE;
1797     }
1798
1799     /* WGL doesn't allow deletion of a context which is current in another thread */
1800     if (ctx->tid != 0 && ctx->tid != GetCurrentThreadId())
1801     {
1802         TRACE("Cannot delete context=%p because it is current in another thread.\n", ctx);
1803         SetLastError(ERROR_BUSY);
1804         return FALSE;
1805     }
1806
1807     /* WGL makes a context not current if it is active before deletion. GLX waits until the context is not current. */
1808     if (ctx == NtCurrentTeb()->glContext)
1809         wglMakeCurrent(ctx->hdc, NULL);
1810
1811     if (ctx->ctx)
1812     {
1813         wine_tsx11_lock();
1814         pglXDestroyContext(gdi_display, ctx->ctx);
1815         wine_tsx11_unlock();
1816     }
1817
1818     free_context(ctx);
1819     return TRUE;
1820 }
1821
1822 /**
1823  * X11DRV_wglGetCurrentReadDCARB
1824  *
1825  * For OpenGL32 wglGetCurrentReadDCARB.
1826  */
1827 static HDC WINAPI X11DRV_wglGetCurrentReadDCARB(void) 
1828 {
1829     HDC ret = 0;
1830     Wine_GLContext *ctx = NtCurrentTeb()->glContext;
1831
1832     if (ctx) ret = ctx->read_hdc;
1833
1834     TRACE(" returning %p (GL drawable %lu)\n", ret, ctx ? ctx->drawables[1] : 0);
1835     return ret;
1836 }
1837
1838 /**
1839  * X11DRV_wglGetProcAddress
1840  *
1841  * For OpenGL32 wglGetProcAddress.
1842  */
1843 PROC CDECL X11DRV_wglGetProcAddress(LPCSTR lpszProc)
1844 {
1845     int i, j;
1846     const WineGLExtension *ext;
1847
1848     int padding = 32 - strlen(lpszProc);
1849     if (padding < 0)
1850         padding = 0;
1851
1852     if (!has_opengl()) return NULL;
1853
1854     /* Check the table of WGL extensions to see if we need to return a WGL extension
1855      * or a function pointer to a native OpenGL function. */
1856     if(strncmp(lpszProc, "wgl", 3) != 0) {
1857         return pglXGetProcAddressARB((const GLubyte*)lpszProc);
1858     } else {
1859         TRACE("('%s'):%*s", lpszProc, padding, " ");
1860         for (i = 0; i < WineGLExtensionListSize; ++i) {
1861             ext = WineGLExtensionList[i];
1862             for (j = 0; ext->extEntryPoints[j].funcName; ++j) {
1863                 if (strcmp(ext->extEntryPoints[j].funcName, lpszProc) == 0) {
1864                     TRACE("(%p) - WineGL\n", ext->extEntryPoints[j].funcAddress);
1865                     return ext->extEntryPoints[j].funcAddress;
1866                 }
1867             }
1868         }
1869     }
1870
1871     WARN("(%s) - not found\n", lpszProc);
1872     return NULL;
1873 }
1874
1875 /**
1876  * X11DRV_wglMakeCurrent
1877  *
1878  * For OpenGL32 wglMakeCurrent.
1879  */
1880 BOOL CDECL X11DRV_wglMakeCurrent(X11DRV_PDEVICE *physDev, HGLRC hglrc) {
1881     BOOL ret;
1882     HDC hdc = physDev->hdc;
1883     DWORD type = GetObjectType(hdc);
1884     Wine_GLContext *ctx = (Wine_GLContext *) hglrc;
1885
1886     TRACE("(%p,%p)\n", hdc, hglrc);
1887
1888     if (!has_opengl()) return FALSE;
1889
1890     wine_tsx11_lock();
1891     if (hglrc == NULL)
1892     {
1893         Wine_GLContext *prev_ctx = NtCurrentTeb()->glContext;
1894         if (prev_ctx) prev_ctx->tid = 0;
1895
1896         ret = pglXMakeCurrent(gdi_display, None, NULL);
1897         NtCurrentTeb()->glContext = NULL;
1898     }
1899     else if (!physDev->current_pf)
1900     {
1901         WARN("Trying to use an invalid drawable\n");
1902         SetLastError(ERROR_INVALID_HANDLE);
1903         ret = FALSE;
1904     }
1905     else if (ctx->fmt->iPixelFormat != physDev->current_pf)
1906     {
1907         WARN( "mismatched pixel format hdc %p %u ctx %p %u\n",
1908               hdc, physDev->current_pf, ctx, ctx->fmt->iPixelFormat );
1909         SetLastError( ERROR_INVALID_PIXEL_FORMAT );
1910         ret = FALSE;
1911     }
1912     else
1913     {
1914         Drawable drawable = get_glxdrawable(physDev);
1915         Wine_GLContext *prev_ctx = NtCurrentTeb()->glContext;
1916
1917         /* The describe lines below are for debugging purposes only */
1918         if (TRACE_ON(wgl)) {
1919             describeDrawable(physDev);
1920             describeContext(ctx);
1921         }
1922
1923         TRACE(" make current for dis %p, drawable %p, ctx %p\n", gdi_display, (void*) drawable, ctx->ctx);
1924         ret = pglXMakeCurrent(gdi_display, drawable, ctx->ctx);
1925
1926         if (ret)
1927         {
1928             if (prev_ctx) prev_ctx->tid = 0;
1929             NtCurrentTeb()->glContext = ctx;
1930
1931             ctx->has_been_current = TRUE;
1932             ctx->tid = GetCurrentThreadId();
1933             ctx->hdc = hdc;
1934             ctx->read_hdc = hdc;
1935             ctx->drawables[0] = drawable;
1936             ctx->drawables[1] = drawable;
1937             ctx->refresh_drawables = FALSE;
1938
1939             if (type == OBJ_MEMDC)
1940             {
1941                 ctx->do_escape = TRUE;
1942                 pglDrawBuffer(GL_FRONT_LEFT);
1943             }
1944         }
1945         else
1946             SetLastError(ERROR_INVALID_HANDLE);
1947     }
1948     wine_tsx11_unlock();
1949     TRACE(" returning %s\n", (ret ? "True" : "False"));
1950     return ret;
1951 }
1952
1953 /**
1954  * X11DRV_wglMakeContextCurrentARB
1955  *
1956  * For OpenGL32 wglMakeContextCurrentARB
1957  */
1958 BOOL CDECL X11DRV_wglMakeContextCurrentARB(X11DRV_PDEVICE* pDrawDev, X11DRV_PDEVICE* pReadDev, HGLRC hglrc)
1959 {
1960     BOOL ret;
1961
1962     TRACE("(%p,%p,%p)\n", pDrawDev, pReadDev, hglrc);
1963
1964     if (!has_opengl()) return 0;
1965
1966     wine_tsx11_lock();
1967     if (hglrc == NULL)
1968     {
1969         Wine_GLContext *prev_ctx = NtCurrentTeb()->glContext;
1970         if (prev_ctx) prev_ctx->tid = 0;
1971
1972         ret = pglXMakeCurrent(gdi_display, None, NULL);
1973         NtCurrentTeb()->glContext = NULL;
1974     }
1975     else if (!pDrawDev->current_pf)
1976     {
1977         WARN("Trying to use an invalid drawable\n");
1978         SetLastError(ERROR_INVALID_HANDLE);
1979         ret = FALSE;
1980     }
1981     else
1982     {
1983         if (NULL == pglXMakeContextCurrent) {
1984             ret = FALSE;
1985         } else {
1986             Wine_GLContext *ctx = (Wine_GLContext *) hglrc;
1987             Drawable d_draw = get_glxdrawable(pDrawDev);
1988             Drawable d_read = get_glxdrawable(pReadDev);
1989
1990             ret = pglXMakeContextCurrent(gdi_display, d_draw, d_read, ctx->ctx);
1991             if (ret)
1992             {
1993                 Wine_GLContext *prev_ctx = NtCurrentTeb()->glContext;
1994                 if (prev_ctx) prev_ctx->tid = 0;
1995
1996                 ctx->has_been_current = TRUE;
1997                 ctx->tid = GetCurrentThreadId();
1998                 ctx->hdc = pDrawDev->hdc;
1999                 ctx->read_hdc = pReadDev->hdc;
2000                 ctx->drawables[0] = d_draw;
2001                 ctx->drawables[1] = d_read;
2002                 ctx->refresh_drawables = FALSE;
2003                 NtCurrentTeb()->glContext = ctx;
2004             }
2005             else
2006                 SetLastError(ERROR_INVALID_HANDLE);
2007         }
2008     }
2009     wine_tsx11_unlock();
2010
2011     TRACE(" returning %s\n", (ret ? "True" : "False"));
2012     return ret;
2013 }
2014
2015 /**
2016  * X11DRV_wglShareLists
2017  *
2018  * For OpenGL32 wglShareLists.
2019  */
2020 BOOL CDECL X11DRV_wglShareLists(HGLRC hglrc1, HGLRC hglrc2) {
2021     Wine_GLContext *org  = (Wine_GLContext *) hglrc1;
2022     Wine_GLContext *dest = (Wine_GLContext *) hglrc2;
2023
2024     TRACE("(%p, %p)\n", org, dest);
2025
2026     if (!has_opengl()) return FALSE;
2027
2028     /* Sharing of display lists works differently in GLX and WGL. In case of GLX it is done
2029      * at context creation time but in case of WGL it is done using wglShareLists.
2030      * In the past we tried to emulate wglShareLists by delaying GLX context creation until
2031      * either a wglMakeCurrent or wglShareLists. This worked fine for most apps but it causes
2032      * issues for OpenGL 3 because there wglCreateContextAttribsARB can fail in a lot of cases,
2033      * so there delaying context creation doesn't work.
2034      *
2035      * The new approach is to create a GLX context in wglCreateContext / wglCreateContextAttribsARB
2036      * and when a program requests sharing we recreate the destination context if it hasn't been made
2037      * current or when it hasn't shared display lists before.
2038      */
2039
2040     if((org->has_been_current && dest->has_been_current) || dest->has_been_current)
2041     {
2042         ERR("Could not share display lists, one of the contexts has been current already !\n");
2043         return FALSE;
2044     }
2045     else if(dest->sharing)
2046     {
2047         ERR("Could not share display lists because hglrc2 has already shared lists before\n");
2048         return FALSE;
2049     }
2050     else
2051     {
2052         if((GetObjectType(org->hdc) == OBJ_MEMDC) ^ (GetObjectType(dest->hdc) == OBJ_MEMDC))
2053         {
2054             WARN("Attempting to share a context between a direct and indirect rendering context, expect issues!\n");
2055         }
2056
2057         wine_tsx11_lock();
2058         describeContext(org);
2059         describeContext(dest);
2060
2061         /* Re-create the GLX context and share display lists */
2062         pglXDestroyContext(gdi_display, dest->ctx);
2063         dest->ctx = create_glxcontext(gdi_display, dest, org->ctx);
2064         wine_tsx11_unlock();
2065         TRACE(" re-created an OpenGL context (%p) for Wine context %p sharing lists with OpenGL ctx %p\n", dest->ctx, dest, org->ctx);
2066
2067         org->sharing = TRUE;
2068         dest->sharing = TRUE;
2069         return TRUE;
2070     }
2071     return FALSE;
2072 }
2073
2074 static BOOL internal_wglUseFontBitmaps(HDC hdc, DWORD first, DWORD count, DWORD listBase, DWORD (WINAPI *GetGlyphOutline_ptr)(HDC,UINT,UINT,LPGLYPHMETRICS,DWORD,LPVOID,const MAT2*))
2075 {
2076      /* We are running using client-side rendering fonts... */
2077      GLYPHMETRICS gm;
2078      unsigned int glyph, size = 0;
2079      void *bitmap = NULL, *gl_bitmap = NULL;
2080      int org_alignment;
2081
2082      wine_tsx11_lock();
2083      pglGetIntegerv(GL_UNPACK_ALIGNMENT, &org_alignment);
2084      pglPixelStorei(GL_UNPACK_ALIGNMENT, 4);
2085      wine_tsx11_unlock();
2086
2087      for (glyph = first; glyph < first + count; glyph++) {
2088          static const MAT2 identity = { {0,1},{0,0},{0,0},{0,1} };
2089          unsigned int needed_size = GetGlyphOutline_ptr(hdc, glyph, GGO_BITMAP, &gm, 0, NULL, &identity);
2090          unsigned int height, width_int;
2091
2092          TRACE("Glyph : %3d / List : %d\n", glyph, listBase);
2093          if (needed_size == GDI_ERROR) {
2094              TRACE("  - needed size : %d (GDI_ERROR)\n", needed_size);
2095              goto error;
2096          } else {
2097              TRACE("  - needed size : %d\n", needed_size);
2098          }
2099
2100          if (needed_size > size) {
2101              size = needed_size;
2102              HeapFree(GetProcessHeap(), 0, bitmap);
2103              HeapFree(GetProcessHeap(), 0, gl_bitmap);
2104              bitmap = HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, size);
2105              gl_bitmap = HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, size);
2106          }
2107          if (GetGlyphOutline_ptr(hdc, glyph, GGO_BITMAP, &gm, size, bitmap, &identity) == GDI_ERROR)
2108              goto error;
2109          if (TRACE_ON(wgl)) {
2110              unsigned int height, width, bitmask;
2111              unsigned char *bitmap_ = bitmap;
2112
2113              TRACE("  - bbox : %d x %d\n", gm.gmBlackBoxX, gm.gmBlackBoxY);
2114              TRACE("  - origin : (%d , %d)\n", gm.gmptGlyphOrigin.x, gm.gmptGlyphOrigin.y);
2115              TRACE("  - increment : %d - %d\n", gm.gmCellIncX, gm.gmCellIncY);
2116              if (needed_size != 0) {
2117                  TRACE("  - bitmap :\n");
2118                  for (height = 0; height < gm.gmBlackBoxY; height++) {
2119                      TRACE("      ");
2120                      for (width = 0, bitmask = 0x80; width < gm.gmBlackBoxX; width++, bitmask >>= 1) {
2121                          if (bitmask == 0) {
2122                              bitmap_ += 1;
2123                              bitmask = 0x80;
2124                          }
2125                          if (*bitmap_ & bitmask)
2126                              TRACE("*");
2127                          else
2128                              TRACE(" ");
2129                      }
2130                      bitmap_ += (4 - ((UINT_PTR)bitmap_ & 0x03));
2131                      TRACE("\n");
2132                  }
2133              }
2134          }
2135
2136          /* In OpenGL, the bitmap is drawn from the bottom to the top... So we need to invert the
2137          * glyph for it to be drawn properly.
2138          */
2139          if (needed_size != 0) {
2140              width_int = (gm.gmBlackBoxX + 31) / 32;
2141              for (height = 0; height < gm.gmBlackBoxY; height++) {
2142                  unsigned int width;
2143                  for (width = 0; width < width_int; width++) {
2144                      ((int *) gl_bitmap)[(gm.gmBlackBoxY - height - 1) * width_int + width] =
2145                      ((int *) bitmap)[height * width_int + width];
2146                  }
2147              }
2148          }
2149
2150          wine_tsx11_lock();
2151          pglNewList(listBase++, GL_COMPILE);
2152          if (needed_size != 0) {
2153              pglBitmap(gm.gmBlackBoxX, gm.gmBlackBoxY,
2154                      0 - gm.gmptGlyphOrigin.x, (int) gm.gmBlackBoxY - gm.gmptGlyphOrigin.y,
2155                      gm.gmCellIncX, gm.gmCellIncY,
2156                      gl_bitmap);
2157          } else {
2158              /* This is the case of 'empty' glyphs like the space character */
2159              pglBitmap(0, 0, 0, 0, gm.gmCellIncX, gm.gmCellIncY, NULL);
2160          }
2161          pglEndList();
2162          wine_tsx11_unlock();
2163      }
2164
2165      wine_tsx11_lock();
2166      pglPixelStorei(GL_UNPACK_ALIGNMENT, org_alignment);
2167      wine_tsx11_unlock();
2168
2169      HeapFree(GetProcessHeap(), 0, bitmap);
2170      HeapFree(GetProcessHeap(), 0, gl_bitmap);
2171      return TRUE;
2172
2173   error:
2174      wine_tsx11_lock();
2175      pglPixelStorei(GL_UNPACK_ALIGNMENT, org_alignment);
2176      wine_tsx11_unlock();
2177
2178      HeapFree(GetProcessHeap(), 0, bitmap);
2179      HeapFree(GetProcessHeap(), 0, gl_bitmap);
2180      return FALSE;
2181 }
2182
2183 /**
2184  * X11DRV_wglUseFontBitmapsA
2185  *
2186  * For OpenGL32 wglUseFontBitmapsA.
2187  */
2188 BOOL CDECL X11DRV_wglUseFontBitmapsA(X11DRV_PDEVICE *physDev, DWORD first, DWORD count, DWORD listBase)
2189 {
2190      Font fid = physDev->font;
2191
2192      TRACE("(%p, %d, %d, %d) using font %ld\n", physDev->hdc, first, count, listBase, fid);
2193
2194      if (!has_opengl()) return FALSE;
2195
2196      if (fid == 0) {
2197          return internal_wglUseFontBitmaps(physDev->hdc, first, count, listBase, GetGlyphOutlineA);
2198      }
2199
2200      wine_tsx11_lock();
2201      /* I assume that the glyphs are at the same position for X and for Windows */
2202      pglXUseXFont(fid, first, count, listBase);
2203      wine_tsx11_unlock();
2204      return TRUE;
2205 }
2206
2207 /**
2208  * X11DRV_wglUseFontBitmapsW
2209  *
2210  * For OpenGL32 wglUseFontBitmapsW.
2211  */
2212 BOOL CDECL X11DRV_wglUseFontBitmapsW(X11DRV_PDEVICE *physDev, DWORD first, DWORD count, DWORD listBase)
2213 {
2214      Font fid = physDev->font;
2215
2216      TRACE("(%p, %d, %d, %d) using font %ld\n", physDev->hdc, first, count, listBase, fid);
2217
2218      if (!has_opengl()) return FALSE;
2219
2220      if (fid == 0) {
2221          return internal_wglUseFontBitmaps(physDev->hdc, first, count, listBase, GetGlyphOutlineW);
2222      }
2223
2224      WARN("Using the glX API for the WCHAR variant - some characters may come out incorrectly !\n");
2225
2226      wine_tsx11_lock();
2227      /* I assume that the glyphs are at the same position for X and for Windows */
2228      pglXUseXFont(fid, first, count, listBase);
2229      wine_tsx11_unlock();
2230      return TRUE;
2231 }
2232
2233 /* WGL helper function which handles differences in glGetIntegerv from WGL and GLX */
2234 static void WINAPI X11DRV_wglGetIntegerv(GLenum pname, GLint* params)
2235 {
2236     wine_tsx11_lock();
2237     switch(pname)
2238     {
2239     case GL_DEPTH_BITS:
2240         {
2241             Wine_GLContext *ctx = NtCurrentTeb()->glContext;
2242
2243             pglGetIntegerv(pname, params);
2244             /**
2245              * if we cannot find a Wine Context
2246              * we only have the default wine desktop context,
2247              * so if we have only a 24 depth say we have 32
2248              */
2249             if (!ctx && *params == 24) {
2250                 *params = 32;
2251             }
2252             TRACE("returns GL_DEPTH_BITS as '%d'\n", *params);
2253             break;
2254         }
2255     case GL_ALPHA_BITS:
2256         {
2257             Wine_GLContext *ctx = NtCurrentTeb()->glContext;
2258
2259             pglXGetFBConfigAttrib(gdi_display, ctx->fmt->fbconfig, GLX_ALPHA_SIZE, params);
2260             TRACE("returns GL_ALPHA_BITS as '%d'\n", *params);
2261             break;
2262         }
2263     default:
2264         pglGetIntegerv(pname, params);
2265         break;
2266     }
2267     wine_tsx11_unlock();
2268 }
2269
2270 void flush_gl_drawable(X11DRV_PDEVICE *physDev)
2271 {
2272     int w, h;
2273
2274     if (!physDev->gl_copy || !physDev->current_pf)
2275         return;
2276
2277     w = physDev->dc_rect.right - physDev->dc_rect.left;
2278     h = physDev->dc_rect.bottom - physDev->dc_rect.top;
2279
2280     if(w > 0 && h > 0) {
2281         Drawable src = physDev->pixmap;
2282         if(!src) src = physDev->gl_drawable;
2283
2284         /* The GL drawable may be lagged behind if we don't flush first, so
2285          * flush the display make sure we copy up-to-date data */
2286         wine_tsx11_lock();
2287         XFlush(gdi_display);
2288         XSetFunction(gdi_display, physDev->gc, GXcopy);
2289         XCopyArea(gdi_display, src, physDev->drawable, physDev->gc, 0, 0, w, h,
2290                   physDev->dc_rect.left, physDev->dc_rect.top);
2291         wine_tsx11_unlock();
2292     }
2293 }
2294
2295
2296 static void WINAPI X11DRV_wglFinish(void)
2297 {
2298     Wine_GLContext *ctx = NtCurrentTeb()->glContext;
2299     enum x11drv_escape_codes code = X11DRV_FLUSH_GL_DRAWABLE;
2300
2301     wine_tsx11_lock();
2302     sync_context(ctx);
2303     pglFinish();
2304     wine_tsx11_unlock();
2305     if (ctx) ExtEscape(ctx->hdc, X11DRV_ESCAPE, sizeof(code), (LPSTR)&code, 0, NULL );
2306 }
2307
2308 static void WINAPI X11DRV_wglFlush(void)
2309 {
2310     Wine_GLContext *ctx = NtCurrentTeb()->glContext;
2311     enum x11drv_escape_codes code = X11DRV_FLUSH_GL_DRAWABLE;
2312
2313     wine_tsx11_lock();
2314     sync_context(ctx);
2315     pglFlush();
2316     wine_tsx11_unlock();
2317     if (ctx) ExtEscape(ctx->hdc, X11DRV_ESCAPE, sizeof(code), (LPSTR)&code, 0, NULL );
2318 }
2319
2320 /**
2321  * X11DRV_wglCreateContextAttribsARB
2322  *
2323  * WGL_ARB_create_context: wglCreateContextAttribsARB
2324  */
2325 HGLRC CDECL X11DRV_wglCreateContextAttribsARB(X11DRV_PDEVICE *physDev, HGLRC hShareContext, const int* attribList)
2326 {
2327     Wine_GLContext *ret;
2328     WineGLPixelFormat *fmt;
2329     int hdcPF = physDev->current_pf;
2330     int fmt_count = 0;
2331
2332     TRACE("(%p %p %p)\n", physDev, hShareContext, attribList);
2333
2334     if (!has_opengl()) return 0;
2335
2336     fmt = ConvertPixelFormatWGLtoGLX(gdi_display, hdcPF, TRUE /* Offscreen */, &fmt_count);
2337     /* wglCreateContextAttribsARB supports ALL pixel formats, so also offscreen ones.
2338      * If this fails something is very wrong on the system. */
2339     if(!fmt)
2340     {
2341         ERR("Cannot get FB Config for iPixelFormat %d, expect problems!\n", hdcPF);
2342         SetLastError(ERROR_INVALID_PIXEL_FORMAT);
2343         return NULL;
2344     }
2345
2346     wine_tsx11_lock();
2347     ret = alloc_context();
2348     wine_tsx11_unlock();
2349     ret->hdc = physDev->hdc;
2350     ret->fmt = fmt;
2351     ret->vis = NULL; /* glXCreateContextAttribsARB requires a fbconfig instead of a visual */
2352     ret->gl3_context = TRUE;
2353
2354     ret->numAttribs = 0;
2355     if(attribList)
2356     {
2357         int *pAttribList = (int*)attribList;
2358         int *pContextAttribList = &ret->attribList[0];
2359         /* attribList consists of pairs {token, value] terminated with 0 */
2360         while(pAttribList[0] != 0)
2361         {
2362             TRACE("%#x %#x\n", pAttribList[0], pAttribList[1]);
2363             switch(pAttribList[0])
2364             {
2365                 case WGL_CONTEXT_MAJOR_VERSION_ARB:
2366                     pContextAttribList[0] = GLX_CONTEXT_MAJOR_VERSION_ARB;
2367                     pContextAttribList[1] = pAttribList[1];
2368                     break;
2369                 case WGL_CONTEXT_MINOR_VERSION_ARB:
2370                     pContextAttribList[0] = GLX_CONTEXT_MINOR_VERSION_ARB;
2371                     pContextAttribList[1] = pAttribList[1];
2372                     break;
2373                 case WGL_CONTEXT_LAYER_PLANE_ARB:
2374                     break;
2375                 case WGL_CONTEXT_FLAGS_ARB:
2376                     pContextAttribList[0] = GLX_CONTEXT_FLAGS_ARB;
2377                     pContextAttribList[1] = pAttribList[1];
2378                     break;
2379                 case WGL_CONTEXT_PROFILE_MASK_ARB:
2380                     pContextAttribList[0] = GLX_CONTEXT_PROFILE_MASK_ARB;
2381                     pContextAttribList[1] = pAttribList[1];
2382                     break;
2383                 default:
2384                     ERR("Unhandled attribList pair: %#x %#x\n", pAttribList[0], pAttribList[1]);
2385             }
2386
2387             ret->numAttribs++;
2388             pAttribList += 2;
2389             pContextAttribList += 2;
2390         }
2391     }
2392
2393     wine_tsx11_lock();
2394     X11DRV_expect_error(gdi_display, GLXErrorHandler, NULL);
2395     ret->ctx = create_glxcontext(gdi_display, ret, NULL);
2396
2397     XSync(gdi_display, False);
2398     if(X11DRV_check_error() || !ret->ctx)
2399     {
2400         /* In the future we should convert the GLX error to a win32 one here if needed */
2401         ERR("Context creation failed\n");
2402         free_context(ret);
2403         wine_tsx11_unlock();
2404         return NULL;
2405     }
2406
2407     wine_tsx11_unlock();
2408     TRACE(" creating context %p\n", ret);
2409     return (HGLRC) ret;
2410 }
2411
2412 /**
2413  * X11DRV_wglGetExtensionsStringARB
2414  *
2415  * WGL_ARB_extensions_string: wglGetExtensionsStringARB
2416  */
2417 static const char * WINAPI X11DRV_wglGetExtensionsStringARB(HDC hdc) {
2418     TRACE("() returning \"%s\"\n", WineGLInfo.wglExtensions);
2419     return WineGLInfo.wglExtensions;
2420 }
2421
2422 /**
2423  * X11DRV_wglCreatePbufferARB
2424  *
2425  * WGL_ARB_pbuffer: wglCreatePbufferARB
2426  */
2427 static HPBUFFERARB WINAPI X11DRV_wglCreatePbufferARB(HDC hdc, int iPixelFormat, int iWidth, int iHeight, const int *piAttribList)
2428 {
2429     Wine_GLPBuffer* object = NULL;
2430     WineGLPixelFormat *fmt = NULL;
2431     int nCfgs = 0;
2432     int attribs[256];
2433     int nAttribs = 0;
2434
2435     TRACE("(%p, %d, %d, %d, %p)\n", hdc, iPixelFormat, iWidth, iHeight, piAttribList);
2436
2437     if (0 >= iPixelFormat) {
2438         ERR("(%p): unexpected iPixelFormat(%d) <= 0, returns NULL\n", hdc, iPixelFormat);
2439         SetLastError(ERROR_INVALID_PIXEL_FORMAT);
2440         return NULL; /* unexpected error */
2441     }
2442
2443     /* Convert the WGL pixelformat to a GLX format, if it fails then the format is invalid */
2444     fmt = ConvertPixelFormatWGLtoGLX(gdi_display, iPixelFormat, TRUE /* Offscreen */, &nCfgs);
2445     if(!fmt) {
2446         ERR("(%p): unexpected iPixelFormat(%d) > nFormats(%d), returns NULL\n", hdc, iPixelFormat, nCfgs);
2447         SetLastError(ERROR_INVALID_PIXEL_FORMAT);
2448         goto create_failed; /* unexpected error */
2449     }
2450
2451     object = HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, sizeof(Wine_GLPBuffer));
2452     if (NULL == object) {
2453         SetLastError(ERROR_NO_SYSTEM_RESOURCES);
2454         goto create_failed; /* unexpected error */
2455     }
2456     object->hdc = hdc;
2457     object->display = gdi_display;
2458     object->width = iWidth;
2459     object->height = iHeight;
2460     object->fmt = fmt;
2461
2462     PUSH2(attribs, GLX_PBUFFER_WIDTH,  iWidth);
2463     PUSH2(attribs, GLX_PBUFFER_HEIGHT, iHeight); 
2464     while (piAttribList && 0 != *piAttribList) {
2465         int attr_v;
2466         switch (*piAttribList) {
2467             case WGL_PBUFFER_LARGEST_ARB: {
2468                 ++piAttribList;
2469                 attr_v = *piAttribList;
2470                 TRACE("WGL_LARGEST_PBUFFER_ARB = %d\n", attr_v);
2471                 PUSH2(attribs, GLX_LARGEST_PBUFFER, attr_v);
2472                 break;
2473             }
2474
2475             case WGL_TEXTURE_FORMAT_ARB: {
2476                 ++piAttribList;
2477                 attr_v = *piAttribList;
2478                 TRACE("WGL_render_texture Attribute: WGL_TEXTURE_FORMAT_ARB as %x\n", attr_v);
2479                 if (use_render_texture_ati) {
2480                     int type = 0;
2481                     switch (attr_v) {
2482                         case WGL_NO_TEXTURE_ARB: type = GLX_NO_TEXTURE_ATI; break ;
2483                         case WGL_TEXTURE_RGB_ARB: type = GLX_TEXTURE_RGB_ATI; break ;
2484                         case WGL_TEXTURE_RGBA_ARB: type = GLX_TEXTURE_RGBA_ATI; break ;
2485                         default:
2486                             SetLastError(ERROR_INVALID_DATA);
2487                             goto create_failed;
2488                     }
2489                     object->use_render_texture = 1;
2490                     PUSH2(attribs, GLX_TEXTURE_FORMAT_ATI, type);
2491                 } else {
2492                     if (WGL_NO_TEXTURE_ARB == attr_v) {
2493                         object->use_render_texture = 0;
2494                     } else {
2495                         if (!use_render_texture_emulation) {
2496                             SetLastError(ERROR_INVALID_DATA);
2497                             goto create_failed;
2498                         }
2499                         switch (attr_v) {
2500                             case WGL_TEXTURE_RGB_ARB:
2501                                 object->use_render_texture = GL_RGB;
2502                                 object->texture_bpp = 3;
2503                                 object->texture_format = GL_RGB;
2504                                 object->texture_type = GL_UNSIGNED_BYTE;
2505                                 break;
2506                             case WGL_TEXTURE_RGBA_ARB:
2507                                 object->use_render_texture = GL_RGBA;
2508                                 object->texture_bpp = 4;
2509                                 object->texture_format = GL_RGBA;
2510                                 object->texture_type = GL_UNSIGNED_BYTE;
2511                                 break;
2512
2513                             /* WGL_FLOAT_COMPONENTS_NV */
2514                             case WGL_TEXTURE_FLOAT_R_NV:
2515                                 object->use_render_texture = GL_FLOAT_R_NV;
2516                                 object->texture_bpp = 4;
2517                                 object->texture_format = GL_RED;
2518                                 object->texture_type = GL_FLOAT;
2519                                 break;
2520                             case WGL_TEXTURE_FLOAT_RG_NV:
2521                                 object->use_render_texture = GL_FLOAT_RG_NV;
2522                                 object->texture_bpp = 8;
2523                                 object->texture_format = GL_LUMINANCE_ALPHA;
2524                                 object->texture_type = GL_FLOAT;
2525                                 break;
2526                             case WGL_TEXTURE_FLOAT_RGB_NV:
2527                                 object->use_render_texture = GL_FLOAT_RGB_NV;
2528                                 object->texture_bpp = 12;
2529                                 object->texture_format = GL_RGB;
2530                                 object->texture_type = GL_FLOAT;
2531                                 break;
2532                             case WGL_TEXTURE_FLOAT_RGBA_NV:
2533                                 object->use_render_texture = GL_FLOAT_RGBA_NV;
2534                                 object->texture_bpp = 16;
2535                                 object->texture_format = GL_RGBA;
2536                                 object->texture_type = GL_FLOAT;
2537                                 break;
2538                             default:
2539                                 ERR("Unknown texture format: %x\n", attr_v);
2540                                 SetLastError(ERROR_INVALID_DATA);
2541                                 goto create_failed;
2542                         }
2543                     }
2544                 }
2545                 break;
2546             }
2547
2548             case WGL_TEXTURE_TARGET_ARB: {
2549                 ++piAttribList;
2550                 attr_v = *piAttribList;
2551                 TRACE("WGL_render_texture Attribute: WGL_TEXTURE_TARGET_ARB as %x\n", attr_v);
2552                 if (use_render_texture_ati) {
2553                     int type = 0;
2554                     switch (attr_v) {
2555                         case WGL_NO_TEXTURE_ARB: type = GLX_NO_TEXTURE_ATI; break ;
2556                         case WGL_TEXTURE_CUBE_MAP_ARB: type = GLX_TEXTURE_CUBE_MAP_ATI; break ;
2557                         case WGL_TEXTURE_1D_ARB: type = GLX_TEXTURE_1D_ATI; break ;
2558                         case WGL_TEXTURE_2D_ARB: type = GLX_TEXTURE_2D_ATI; break ;
2559                         default:
2560                             SetLastError(ERROR_INVALID_DATA);
2561                             goto create_failed;
2562                     }
2563                     PUSH2(attribs, GLX_TEXTURE_TARGET_ATI, type);
2564                 } else {
2565                     if (WGL_NO_TEXTURE_ARB == attr_v) {
2566                         object->texture_target = 0;
2567                     } else {
2568                         if (!use_render_texture_emulation) {
2569                             SetLastError(ERROR_INVALID_DATA);
2570                             goto create_failed;
2571                         }
2572                         switch (attr_v) {
2573                             case WGL_TEXTURE_CUBE_MAP_ARB: {
2574                                 if (iWidth != iHeight) {
2575                                     SetLastError(ERROR_INVALID_DATA);
2576                                     goto create_failed;
2577                                 }
2578                                 object->texture_target = GL_TEXTURE_CUBE_MAP;
2579                                 object->texture_bind_target = GL_TEXTURE_BINDING_CUBE_MAP;
2580                                break;
2581                             }
2582                             case WGL_TEXTURE_1D_ARB: {
2583                                 if (1 != iHeight) {
2584                                     SetLastError(ERROR_INVALID_DATA);
2585                                     goto create_failed;
2586                                 }
2587                                 object->texture_target = GL_TEXTURE_1D;
2588                                 object->texture_bind_target = GL_TEXTURE_BINDING_1D;
2589                                 break;
2590                             }
2591                             case WGL_TEXTURE_2D_ARB: {
2592                                 object->texture_target = GL_TEXTURE_2D;
2593                                 object->texture_bind_target = GL_TEXTURE_BINDING_2D;
2594                                 break;
2595                             }
2596                             case WGL_TEXTURE_RECTANGLE_NV: {
2597                                 object->texture_target = GL_TEXTURE_RECTANGLE_NV;
2598                                 object->texture_bind_target = GL_TEXTURE_BINDING_RECTANGLE_NV;
2599                                 break;
2600                             }
2601                             default:
2602                                 ERR("Unknown texture target: %x\n", attr_v);
2603                                 SetLastError(ERROR_INVALID_DATA);
2604                                 goto create_failed;
2605                         }
2606                     }
2607                 }
2608                 break;
2609             }
2610
2611             case WGL_MIPMAP_TEXTURE_ARB: {
2612                 ++piAttribList;
2613                 attr_v = *piAttribList;
2614                 TRACE("WGL_render_texture Attribute: WGL_MIPMAP_TEXTURE_ARB as %x\n", attr_v);
2615                 if (use_render_texture_ati) {
2616                     PUSH2(attribs, GLX_MIPMAP_TEXTURE_ATI, attr_v);
2617                 } else {
2618                     if (!use_render_texture_emulation) {
2619                         SetLastError(ERROR_INVALID_DATA);
2620                         goto create_failed;
2621                     }
2622                 }
2623                 break;
2624             }
2625         }
2626         ++piAttribList;
2627     }
2628
2629     PUSH1(attribs, None);
2630     wine_tsx11_lock();
2631     object->drawable = pglXCreatePbuffer(gdi_display, fmt->fbconfig, attribs);
2632     wine_tsx11_unlock();
2633     TRACE("new Pbuffer drawable as %p\n", (void*) object->drawable);
2634     if (!object->drawable) {
2635         SetLastError(ERROR_NO_SYSTEM_RESOURCES);
2636         goto create_failed; /* unexpected error */
2637     }
2638     TRACE("->(%p)\n", object);
2639     return object;
2640
2641 create_failed:
2642     HeapFree(GetProcessHeap(), 0, object);
2643     TRACE("->(FAILED)\n");
2644     return NULL;
2645 }
2646
2647 /**
2648  * X11DRV_wglDestroyPbufferARB
2649  *
2650  * WGL_ARB_pbuffer: wglDestroyPbufferARB
2651  */
2652 static GLboolean WINAPI X11DRV_wglDestroyPbufferARB(HPBUFFERARB hPbuffer)
2653 {
2654     Wine_GLPBuffer* object = hPbuffer;
2655     TRACE("(%p)\n", hPbuffer);
2656     if (NULL == object) {
2657         SetLastError(ERROR_INVALID_HANDLE);
2658         return GL_FALSE;
2659     }
2660     wine_tsx11_lock();
2661     pglXDestroyPbuffer(object->display, object->drawable);
2662     wine_tsx11_unlock();
2663     HeapFree(GetProcessHeap(), 0, object);
2664     return GL_TRUE;
2665 }
2666
2667 /**
2668  * X11DRV_wglGetPbufferDCARB
2669  *
2670  * WGL_ARB_pbuffer: wglGetPbufferDCARB
2671  * The function wglGetPbufferDCARB returns a device context for a pbuffer.
2672  * Gdi32 implements the part of this function which creates a device context.
2673  * This part associates the physDev with the X drawable of the pbuffer.
2674  */
2675 HDC CDECL X11DRV_wglGetPbufferDCARB(X11DRV_PDEVICE *physDev, HPBUFFERARB hPbuffer)
2676 {
2677     Wine_GLPBuffer* object = hPbuffer;
2678     if (NULL == object) {
2679         SetLastError(ERROR_INVALID_HANDLE);
2680         return NULL;
2681     }
2682
2683     /* The function wglGetPbufferDCARB returns a DC to which the pbuffer can be connected.
2684      * All formats in our pixelformat list are compatible with each other and the main drawable. */
2685     physDev->current_pf = object->fmt->iPixelFormat;
2686     physDev->drawable = object->drawable;
2687     SetRect( &physDev->drawable_rect, 0, 0, object->width, object->height );
2688     physDev->dc_rect = physDev->drawable_rect;
2689
2690     TRACE("(%p)->(%p)\n", hPbuffer, physDev->hdc);
2691     return physDev->hdc;
2692 }
2693
2694 /**
2695  * X11DRV_wglQueryPbufferARB
2696  *
2697  * WGL_ARB_pbuffer: wglQueryPbufferARB
2698  */
2699 static GLboolean WINAPI X11DRV_wglQueryPbufferARB(HPBUFFERARB hPbuffer, int iAttribute, int *piValue)
2700 {
2701     Wine_GLPBuffer* object = hPbuffer;
2702     TRACE("(%p, 0x%x, %p)\n", hPbuffer, iAttribute, piValue);
2703     if (NULL == object) {
2704         SetLastError(ERROR_INVALID_HANDLE);
2705         return GL_FALSE;
2706     }
2707     switch (iAttribute) {
2708         case WGL_PBUFFER_WIDTH_ARB:
2709             wine_tsx11_lock();
2710             pglXQueryDrawable(object->display, object->drawable, GLX_WIDTH, (unsigned int*) piValue);
2711             wine_tsx11_unlock();
2712             break;
2713         case WGL_PBUFFER_HEIGHT_ARB:
2714             wine_tsx11_lock();
2715             pglXQueryDrawable(object->display, object->drawable, GLX_HEIGHT, (unsigned int*) piValue);
2716             wine_tsx11_unlock();
2717             break;
2718
2719         case WGL_PBUFFER_LOST_ARB:
2720             /* GLX Pbuffers cannot be lost by default. We can support this by
2721              * setting GLX_PRESERVED_CONTENTS to False and using glXSelectEvent
2722              * to receive pixel buffer clobber events, however that may or may
2723              * not give any benefit */
2724             *piValue = GL_FALSE;
2725             break;
2726
2727         case WGL_TEXTURE_FORMAT_ARB:
2728             if (use_render_texture_ati) {
2729                 unsigned int tmp;
2730                 int type = WGL_NO_TEXTURE_ARB;
2731                 wine_tsx11_lock();
2732                 pglXQueryDrawable(object->display, object->drawable, GLX_TEXTURE_FORMAT_ATI, &tmp);
2733                 wine_tsx11_unlock();
2734                 switch (tmp) {
2735                     case GLX_NO_TEXTURE_ATI: type = WGL_NO_TEXTURE_ARB; break ;
2736                     case GLX_TEXTURE_RGB_ATI: type = WGL_TEXTURE_RGB_ARB; break ;
2737                     case GLX_TEXTURE_RGBA_ATI: type = WGL_TEXTURE_RGBA_ARB; break ;
2738                 }
2739                 *piValue = type;
2740             } else {
2741                 if (!object->use_render_texture) {
2742                     *piValue = WGL_NO_TEXTURE_ARB;
2743                 } else {
2744                     if (!use_render_texture_emulation) {
2745                         SetLastError(ERROR_INVALID_HANDLE);
2746                         return GL_FALSE;
2747                     }
2748                     switch(object->use_render_texture) {
2749                         case GL_RGB:
2750                             *piValue = WGL_TEXTURE_RGB_ARB;
2751                             break;
2752                         case GL_RGBA:
2753                             *piValue = WGL_TEXTURE_RGBA_ARB;
2754                             break;
2755                         /* WGL_FLOAT_COMPONENTS_NV */
2756                         case GL_FLOAT_R_NV:
2757                             *piValue = WGL_TEXTURE_FLOAT_R_NV;
2758                             break;
2759                         case GL_FLOAT_RG_NV:
2760                             *piValue = WGL_TEXTURE_FLOAT_RG_NV;
2761                             break;
2762                         case GL_FLOAT_RGB_NV:
2763                             *piValue = WGL_TEXTURE_FLOAT_RGB_NV;
2764                             break;
2765                         case GL_FLOAT_RGBA_NV:
2766                             *piValue = WGL_TEXTURE_FLOAT_RGBA_NV;
2767                             break;
2768                         default:
2769                             ERR("Unknown texture format: %x\n", object->use_render_texture);
2770                     }
2771                 }
2772             }
2773             break;
2774
2775         case WGL_TEXTURE_TARGET_ARB:
2776             if (use_render_texture_ati) {
2777                 unsigned int tmp;
2778                 int type = WGL_NO_TEXTURE_ARB;
2779                 wine_tsx11_lock();
2780                 pglXQueryDrawable(object->display, object->drawable, GLX_TEXTURE_TARGET_ATI, &tmp);
2781                 wine_tsx11_unlock();
2782                 switch (tmp) {
2783                     case GLX_NO_TEXTURE_ATI: type = WGL_NO_TEXTURE_ARB; break ;
2784                     case GLX_TEXTURE_CUBE_MAP_ATI: type = WGL_TEXTURE_CUBE_MAP_ARB; break ;
2785                     case GLX_TEXTURE_1D_ATI: type = WGL_TEXTURE_1D_ARB; break ;
2786                     case GLX_TEXTURE_2D_ATI: type = WGL_TEXTURE_2D_ARB; break ;
2787                 }
2788                 *piValue = type;
2789             } else {
2790             if (!object->texture_target) {
2791                 *piValue = WGL_NO_TEXTURE_ARB;
2792             } else {
2793                 if (!use_render_texture_emulation) {
2794                     SetLastError(ERROR_INVALID_DATA);      
2795                     return GL_FALSE;
2796                 }
2797                 switch (object->texture_target) {
2798                     case GL_TEXTURE_1D:       *piValue = WGL_TEXTURE_1D_ARB; break;
2799                     case GL_TEXTURE_2D:       *piValue = WGL_TEXTURE_2D_ARB; break;
2800                     case GL_TEXTURE_CUBE_MAP: *piValue = WGL_TEXTURE_CUBE_MAP_ARB; break;
2801                     case GL_TEXTURE_RECTANGLE_NV: *piValue = WGL_TEXTURE_RECTANGLE_NV; break;
2802                 }
2803             }
2804         }
2805         break;
2806
2807     case WGL_MIPMAP_TEXTURE_ARB:
2808         if (use_render_texture_ati) {
2809             wine_tsx11_lock();
2810             pglXQueryDrawable(object->display, object->drawable, GLX_MIPMAP_TEXTURE_ATI, (unsigned int*) piValue);
2811             wine_tsx11_unlock();
2812         } else {
2813             *piValue = GL_FALSE; /** don't support that */
2814             FIXME("unsupported WGL_ARB_render_texture attribute query for 0x%x\n", iAttribute);
2815         }
2816         break;
2817
2818     default:
2819         FIXME("unexpected attribute %x\n", iAttribute);
2820         break;
2821     }
2822
2823     return GL_TRUE;
2824 }
2825
2826 /**
2827  * X11DRV_wglReleasePbufferDCARB
2828  *
2829  * WGL_ARB_pbuffer: wglReleasePbufferDCARB
2830  */
2831 static int WINAPI X11DRV_wglReleasePbufferDCARB(HPBUFFERARB hPbuffer, HDC hdc)
2832 {
2833     TRACE("(%p, %p)\n", hPbuffer, hdc);
2834     return DeleteDC(hdc);
2835 }
2836
2837 /**
2838  * X11DRV_wglSetPbufferAttribARB
2839  *
2840  * WGL_ARB_pbuffer: wglSetPbufferAttribARB
2841  */
2842 static GLboolean WINAPI X11DRV_wglSetPbufferAttribARB(HPBUFFERARB hPbuffer, const int *piAttribList)
2843 {
2844     Wine_GLPBuffer* object = hPbuffer;
2845     GLboolean ret = GL_FALSE;
2846
2847     WARN("(%p, %p): alpha-testing, report any problem\n", hPbuffer, piAttribList);
2848     if (NULL == object) {
2849         SetLastError(ERROR_INVALID_HANDLE);
2850         return GL_FALSE;
2851     }
2852     if (!object->use_render_texture) {
2853         SetLastError(ERROR_INVALID_HANDLE);
2854         return GL_FALSE;
2855     }
2856     if (!use_render_texture_ati && 1 == use_render_texture_emulation) {
2857         return GL_TRUE;
2858     }
2859     if (NULL != pglXDrawableAttribATI) {
2860         if (use_render_texture_ati) {
2861             FIXME("Need conversion for GLX_ATI_render_texture\n");
2862         }
2863         wine_tsx11_lock();
2864         ret = pglXDrawableAttribATI(object->display, object->drawable, piAttribList);
2865         wine_tsx11_unlock();
2866     }
2867     return ret;
2868 }
2869
2870 /**
2871  * X11DRV_wglChoosePixelFormatARB
2872  *
2873  * WGL_ARB_pixel_format: wglChoosePixelFormatARB
2874  */
2875 static GLboolean WINAPI X11DRV_wglChoosePixelFormatARB(HDC hdc, const int *piAttribIList, const FLOAT *pfAttribFList, UINT nMaxFormats, int *piFormats, UINT *nNumFormats)
2876 {
2877     int gl_test = 0;
2878     int attribs[256];
2879     int nAttribs = 0;
2880     GLXFBConfig* cfgs = NULL;
2881     int nCfgs = 0;
2882     int it;
2883     int fmt_id;
2884     WineGLPixelFormat *fmt;
2885     UINT pfmt_it = 0;
2886     int run;
2887     int i;
2888     DWORD dwFlags = 0;
2889
2890     TRACE("(%p, %p, %p, %d, %p, %p): hackish\n", hdc, piAttribIList, pfAttribFList, nMaxFormats, piFormats, nNumFormats);
2891     if (NULL != pfAttribFList) {
2892         FIXME("unused pfAttribFList\n");
2893     }
2894
2895     nAttribs = ConvertAttribWGLtoGLX(piAttribIList, attribs, NULL);
2896     if (-1 == nAttribs) {
2897         WARN("Cannot convert WGL to GLX attributes\n");
2898         return GL_FALSE;
2899     }
2900     PUSH1(attribs, None);
2901
2902     /* There is no 1:1 mapping between GLX and WGL formats because we duplicate some GLX formats for bitmap rendering (see get_formats).
2903      * Flags like PFD_SUPPORT_GDI, PFD_DRAW_TO_BITMAP and others are a property of the WineGLPixelFormat. We don't query these attributes
2904      * using glXChooseFBConfig but we filter the result of glXChooseFBConfig later on by passing a dwFlags to 'ConvertPixelFormatGLXtoWGL'. */
2905     for(i=0; piAttribIList[i] != 0; i+=2)
2906     {
2907         switch(piAttribIList[i])
2908         {
2909             case WGL_DRAW_TO_BITMAP_ARB:
2910                 if(piAttribIList[i+1])
2911                     dwFlags |= PFD_DRAW_TO_BITMAP;
2912                 break;
2913             case WGL_ACCELERATION_ARB:
2914                 switch(piAttribIList[i+1])
2915                 {
2916                     case WGL_NO_ACCELERATION_ARB:
2917                         dwFlags |= PFD_GENERIC_FORMAT;
2918                         break;
2919                     case WGL_GENERIC_ACCELERATION_ARB:
2920                         dwFlags |= PFD_GENERIC_ACCELERATED;
2921                         break;
2922                     case WGL_FULL_ACCELERATION_ARB:
2923                         /* Nothing to do */
2924                         break;
2925                 }
2926                 break;
2927             case WGL_SUPPORT_GDI_ARB:
2928                 if(piAttribIList[i+1])
2929                     dwFlags |= PFD_SUPPORT_GDI;
2930                 break;
2931         }
2932     }
2933
2934     /* Search for FB configurations matching the requirements in attribs */
2935     wine_tsx11_lock();
2936     cfgs = pglXChooseFBConfig(gdi_display, DefaultScreen(gdi_display), attribs, &nCfgs);
2937     if (NULL == cfgs) {
2938         wine_tsx11_unlock();
2939         WARN("Compatible Pixel Format not found\n");
2940         return GL_FALSE;
2941     }
2942
2943     /* Loop through all matching formats and check if they are suitable.
2944     * Note that this function should at max return nMaxFormats different formats */
2945     for(run=0; run < 2; run++)
2946     {
2947         for (it = 0; it < nCfgs; ++it) {
2948             gl_test = pglXGetFBConfigAttrib(gdi_display, cfgs[it], GLX_FBCONFIG_ID, &fmt_id);
2949             if (gl_test) {
2950                 ERR("Failed to retrieve FBCONFIG_ID from GLXFBConfig, expect problems.\n");
2951                 continue;
2952             }
2953
2954             /* Search for the format in our list of compatible formats */
2955             fmt = ConvertPixelFormatGLXtoWGL(gdi_display, fmt_id, dwFlags);
2956             if(!fmt)
2957                 continue;
2958
2959             /* During the first run we only want onscreen formats and during the second only offscreen 'XOR' */
2960             if( ((run == 0) && fmt->offscreenOnly) || ((run == 1) && !fmt->offscreenOnly) )
2961                 continue;
2962
2963             if(pfmt_it < nMaxFormats) {
2964                 piFormats[pfmt_it] = fmt->iPixelFormat;
2965                 TRACE("at %d/%d found FBCONFIG_ID 0x%x (%d)\n", it + 1, nCfgs, fmt_id, piFormats[pfmt_it]);
2966             }
2967             pfmt_it++;
2968         }
2969     }
2970
2971     *nNumFormats = pfmt_it;
2972     /** free list */
2973     XFree(cfgs);
2974     wine_tsx11_unlock();
2975     return GL_TRUE;
2976 }
2977
2978 /**
2979  * X11DRV_wglGetPixelFormatAttribivARB
2980  *
2981  * WGL_ARB_pixel_format: wglGetPixelFormatAttribivARB
2982  */
2983 static GLboolean WINAPI X11DRV_wglGetPixelFormatAttribivARB(HDC hdc, int iPixelFormat, int iLayerPlane, UINT nAttributes, const int *piAttributes, int *piValues)
2984 {
2985     UINT i;
2986     WineGLPixelFormat *fmt = NULL;
2987     int hTest;
2988     int tmp;
2989     int curGLXAttr = 0;
2990     int nWGLFormats = 0;
2991
2992     TRACE("(%p, %d, %d, %d, %p, %p)\n", hdc, iPixelFormat, iLayerPlane, nAttributes, piAttributes, piValues);
2993
2994     if (0 < iLayerPlane) {
2995         FIXME("unsupported iLayerPlane(%d) > 0, returns FALSE\n", iLayerPlane);
2996         return GL_FALSE;
2997     }
2998
2999     /* Convert the WGL pixelformat to a GLX one, if this fails then most likely the iPixelFormat isn't supported.
3000     * We don't have to fail yet as a program can specify an invalid iPixelFormat (lets say 0) if it wants to query
3001     * the number of supported WGL formats. Whether the iPixelFormat is valid is handled in the for-loop below. */
3002     fmt = ConvertPixelFormatWGLtoGLX(gdi_display, iPixelFormat, TRUE /* Offscreen */, &nWGLFormats);
3003     if(!fmt) {
3004         WARN("Unable to convert iPixelFormat %d to a GLX one!\n", iPixelFormat);
3005     }
3006
3007     wine_tsx11_lock();
3008     for (i = 0; i < nAttributes; ++i) {
3009         const int curWGLAttr = piAttributes[i];
3010         TRACE("pAttr[%d] = %x\n", i, curWGLAttr);
3011
3012         switch (curWGLAttr) {
3013             case WGL_NUMBER_PIXEL_FORMATS_ARB:
3014                 piValues[i] = nWGLFormats; 
3015                 continue;
3016
3017             case WGL_SUPPORT_OPENGL_ARB:
3018                 piValues[i] = GL_TRUE; 
3019                 continue;
3020
3021             case WGL_ACCELERATION_ARB:
3022                 curGLXAttr = GLX_CONFIG_CAVEAT;
3023                 if (!fmt) goto pix_error;
3024                 if(fmt->dwFlags & PFD_GENERIC_FORMAT)
3025                     piValues[i] = WGL_NO_ACCELERATION_ARB;
3026                 else if(fmt->dwFlags & PFD_GENERIC_ACCELERATED)
3027                     piValues[i] = WGL_GENERIC_ACCELERATION_ARB;
3028                 else
3029                     piValues[i] = WGL_FULL_ACCELERATION_ARB;
3030                 continue;
3031
3032             case WGL_TRANSPARENT_ARB:
3033                 curGLXAttr = GLX_TRANSPARENT_TYPE;
3034                 if (!fmt) goto pix_error;
3035                 hTest = pglXGetFBConfigAttrib(gdi_display, fmt->fbconfig, curGLXAttr, &tmp);
3036                 if (hTest) goto get_error;
3037                     piValues[i] = GL_FALSE;
3038                 if (GLX_NONE != tmp) piValues[i] = GL_TRUE;
3039                     continue;
3040
3041             case WGL_PIXEL_TYPE_ARB:
3042                 curGLXAttr = GLX_RENDER_TYPE;
3043                 if (!fmt) goto pix_error;
3044                 hTest = pglXGetFBConfigAttrib(gdi_display, fmt->fbconfig, curGLXAttr, &tmp);
3045                 if (hTest) goto get_error;
3046                 TRACE("WGL_PIXEL_TYPE_ARB: GLX_RENDER_TYPE = 0x%x\n", tmp);
3047                 if      (tmp & GLX_RGBA_BIT)           { piValues[i] = WGL_TYPE_RGBA_ARB; }
3048                 else if (tmp & GLX_COLOR_INDEX_BIT)    { piValues[i] = WGL_TYPE_COLORINDEX_ARB; }
3049                 else if (tmp & GLX_RGBA_FLOAT_BIT)     { piValues[i] = WGL_TYPE_RGBA_FLOAT_ATI; }
3050                 else if (tmp & GLX_RGBA_FLOAT_ATI_BIT) { piValues[i] = WGL_TYPE_RGBA_FLOAT_ATI; }
3051                 else if (tmp & GLX_RGBA_UNSIGNED_FLOAT_BIT_EXT) { piValues[i] = WGL_TYPE_RGBA_UNSIGNED_FLOAT_EXT; }
3052                 else {
3053                     ERR("unexpected RenderType(%x)\n", tmp);
3054                     piValues[i] = WGL_TYPE_RGBA_ARB;
3055                 }
3056                 continue;
3057
3058             case WGL_COLOR_BITS_ARB:
3059                 curGLXAttr = GLX_BUFFER_SIZE;
3060                 break;
3061
3062             case WGL_BIND_TO_TEXTURE_RGB_ARB:
3063                 if (use_render_texture_ati) {
3064                     curGLXAttr = GLX_BIND_TO_TEXTURE_RGB_ATI;
3065                     break;
3066                 }
3067             case WGL_BIND_TO_TEXTURE_RGBA_ARB:
3068                 if (use_render_texture_ati) {
3069                     curGLXAttr = GLX_BIND_TO_TEXTURE_RGBA_ATI;
3070                     break;
3071                 }
3072                 if (!use_render_texture_emulation) {
3073                     piValues[i] = GL_FALSE;
3074                     continue;   
3075                 }
3076                 curGLXAttr = GLX_RENDER_TYPE;
3077                 if (!fmt) goto pix_error;
3078                 hTest = pglXGetFBConfigAttrib(gdi_display, fmt->fbconfig, curGLXAttr, &tmp);
3079                 if (hTest) goto get_error;
3080                 if (GLX_COLOR_INDEX_BIT == tmp) {
3081                     piValues[i] = GL_FALSE;  
3082                     continue;
3083                 }
3084                 hTest = pglXGetFBConfigAttrib(gdi_display, fmt->fbconfig, GLX_DRAWABLE_TYPE, &tmp);
3085                 if (hTest) goto get_error;
3086                 piValues[i] = (tmp & GLX_PBUFFER_BIT) ? GL_TRUE : GL_FALSE;
3087                 continue;
3088
3089             case WGL_BLUE_BITS_ARB:
3090                 curGLXAttr = GLX_BLUE_SIZE;
3091                 break;
3092             case WGL_RED_BITS_ARB:
3093                 curGLXAttr = GLX_RED_SIZE;
3094                 break;
3095             case WGL_GREEN_BITS_ARB:
3096                 curGLXAttr = GLX_GREEN_SIZE;
3097                 break;
3098             case WGL_ALPHA_BITS_ARB:
3099                 curGLXAttr = GLX_ALPHA_SIZE;
3100                 break;
3101             case WGL_DEPTH_BITS_ARB:
3102                 curGLXAttr = GLX_DEPTH_SIZE;
3103                 break;
3104             case WGL_STENCIL_BITS_ARB:
3105                 curGLXAttr = GLX_STENCIL_SIZE;
3106                 break;
3107             case WGL_DOUBLE_BUFFER_ARB:
3108                 curGLXAttr = GLX_DOUBLEBUFFER;
3109                 break;
3110             case WGL_STEREO_ARB:
3111                 curGLXAttr = GLX_STEREO;
3112                 break;
3113             case WGL_AUX_BUFFERS_ARB:
3114                 curGLXAttr = GLX_AUX_BUFFERS;
3115                 break;
3116
3117             case WGL_SUPPORT_GDI_ARB:
3118                 if (!fmt) goto pix_error;
3119                 piValues[i] = (fmt->dwFlags & PFD_SUPPORT_GDI) ? TRUE : FALSE;
3120                 continue;
3121
3122             case WGL_DRAW_TO_BITMAP_ARB:
3123                 if (!fmt) goto pix_error;
3124                 piValues[i] = (fmt->dwFlags & PFD_DRAW_TO_BITMAP) ? TRUE : FALSE;
3125                 continue;
3126
3127             case WGL_DRAW_TO_WINDOW_ARB:
3128             case WGL_DRAW_TO_PBUFFER_ARB:
3129                 if (!fmt) goto pix_error;
3130                 hTest = pglXGetFBConfigAttrib(gdi_display, fmt->fbconfig, GLX_DRAWABLE_TYPE, &tmp);
3131                 if (hTest) goto get_error;
3132                 if((curWGLAttr == WGL_DRAW_TO_WINDOW_ARB && (tmp&GLX_WINDOW_BIT)) ||
3133                    (curWGLAttr == WGL_DRAW_TO_PBUFFER_ARB && (tmp&GLX_PBUFFER_BIT)))
3134                     piValues[i] = GL_TRUE;
3135                 else
3136                     piValues[i] = GL_FALSE;
3137                 continue;
3138
3139             case WGL_SWAP_METHOD_ARB:
3140                 /* For now return SWAP_EXCHANGE_ARB which is the best type of buffer switch available.
3141                  * Later on we can also use GLX_OML_swap_method on drivers which support this. At this
3142                  * point only ATI offers this.
3143                  */
3144                 piValues[i] = WGL_SWAP_EXCHANGE_ARB;
3145                 break;
3146
3147             case WGL_PBUFFER_LARGEST_ARB:
3148                 curGLXAttr = GLX_LARGEST_PBUFFER;
3149                 break;
3150
3151             case WGL_SAMPLE_BUFFERS_ARB:
3152                 curGLXAttr = GLX_SAMPLE_BUFFERS_ARB;
3153                 break;
3154
3155             case WGL_SAMPLES_ARB:
3156                 curGLXAttr = GLX_SAMPLES_ARB;
3157                 break;
3158
3159             case WGL_FLOAT_COMPONENTS_NV:
3160                 curGLXAttr = GLX_FLOAT_COMPONENTS_NV;
3161                 break;
3162
3163             case WGL_FRAMEBUFFER_SRGB_CAPABLE_EXT:
3164                 curGLXAttr = GLX_FRAMEBUFFER_SRGB_CAPABLE_EXT;
3165                 break;
3166
3167             case WGL_TYPE_RGBA_UNSIGNED_FLOAT_EXT:
3168                 curGLXAttr = GLX_RGBA_UNSIGNED_FLOAT_TYPE_EXT;
3169                 break;
3170
3171             case WGL_ACCUM_RED_BITS_ARB:
3172                 curGLXAttr = GLX_ACCUM_RED_SIZE;
3173                 break;
3174             case WGL_ACCUM_GREEN_BITS_ARB:
3175                 curGLXAttr = GLX_ACCUM_GREEN_SIZE;
3176                 break;
3177             case WGL_ACCUM_BLUE_BITS_ARB:
3178                 curGLXAttr = GLX_ACCUM_BLUE_SIZE;
3179                 break;
3180             case WGL_ACCUM_ALPHA_BITS_ARB:
3181                 curGLXAttr = GLX_ACCUM_ALPHA_SIZE;
3182                 break;
3183             case WGL_ACCUM_BITS_ARB:
3184                 if (!fmt) goto pix_error;
3185                 hTest = pglXGetFBConfigAttrib(gdi_display, fmt->fbconfig, GLX_ACCUM_RED_SIZE, &tmp);
3186                 if (hTest) goto get_error;
3187                 piValues[i] = tmp;
3188                 hTest = pglXGetFBConfigAttrib(gdi_display, fmt->fbconfig, GLX_ACCUM_GREEN_SIZE, &tmp);
3189                 if (hTest) goto get_error;
3190                 piValues[i] += tmp;
3191                 hTest = pglXGetFBConfigAttrib(gdi_display, fmt->fbconfig, GLX_ACCUM_BLUE_SIZE, &tmp);
3192                 if (hTest) goto get_error;
3193                 piValues[i] += tmp;
3194                 hTest = pglXGetFBConfigAttrib(gdi_display, fmt->fbconfig, GLX_ACCUM_ALPHA_SIZE, &tmp);
3195                 if (hTest) goto get_error;
3196                 piValues[i] += tmp;
3197                 continue;
3198
3199             default:
3200                 FIXME("unsupported %x WGL Attribute\n", curWGLAttr);
3201         }
3202
3203         /* Retrieve a GLX FBConfigAttrib when the attribute to query is valid and
3204          * iPixelFormat != 0. When iPixelFormat is 0 the only value which makes
3205          * sense to query is WGL_NUMBER_PIXEL_FORMATS_ARB.
3206          *
3207          * TODO: properly test the behavior of wglGetPixelFormatAttrib*v on Windows
3208          *       and check which options can work using iPixelFormat=0 and which not.
3209          *       A problem would be that this function is an extension. This would
3210          *       mean that the behavior could differ between different vendors (ATI, Nvidia, ..).
3211          */
3212         if (0 != curGLXAttr && iPixelFormat != 0) {
3213             if (!fmt) goto pix_error;
3214             hTest = pglXGetFBConfigAttrib(gdi_display, fmt->fbconfig, curGLXAttr, piValues + i);
3215             if (hTest) goto get_error;
3216             curGLXAttr = 0;
3217         } else { 
3218             piValues[i] = GL_FALSE; 
3219         }
3220     }
3221     wine_tsx11_unlock();
3222     return GL_TRUE;
3223
3224 get_error:
3225     wine_tsx11_unlock();
3226     ERR("(%p): unexpected failure on GetFBConfigAttrib(%x) returns FALSE\n", hdc, curGLXAttr);
3227     return GL_FALSE;
3228
3229 pix_error:
3230     wine_tsx11_unlock();
3231     ERR("(%p): unexpected iPixelFormat(%d) vs nFormats(%d), returns FALSE\n", hdc, iPixelFormat, nWGLFormats);
3232     return GL_FALSE;
3233 }
3234
3235 /**
3236  * X11DRV_wglGetPixelFormatAttribfvARB
3237  *
3238  * WGL_ARB_pixel_format: wglGetPixelFormatAttribfvARB
3239  */
3240 static GLboolean WINAPI X11DRV_wglGetPixelFormatAttribfvARB(HDC hdc, int iPixelFormat, int iLayerPlane, UINT nAttributes, const int *piAttributes, FLOAT *pfValues)
3241 {
3242     int *attr;
3243     int ret;
3244     UINT i;
3245
3246     TRACE("(%p, %d, %d, %d, %p, %p)\n", hdc, iPixelFormat, iLayerPlane, nAttributes, piAttributes, pfValues);
3247
3248     /* Allocate a temporary array to store integer values */
3249     attr = HeapAlloc(GetProcessHeap(), 0, nAttributes * sizeof(int));
3250     if (!attr) {
3251         ERR("couldn't allocate %d array\n", nAttributes);
3252         return GL_FALSE;
3253     }
3254
3255     /* Piggy-back on wglGetPixelFormatAttribivARB */
3256     ret = X11DRV_wglGetPixelFormatAttribivARB(hdc, iPixelFormat, iLayerPlane, nAttributes, piAttributes, attr);
3257     if (ret) {
3258         /* Convert integer values to float. Should also check for attributes
3259            that can give decimal values here */
3260         for (i=0; i<nAttributes;i++) {
3261             pfValues[i] = attr[i];
3262         }
3263     }
3264
3265     HeapFree(GetProcessHeap(), 0, attr);
3266     return ret;
3267 }
3268
3269 /**
3270  * X11DRV_wglBindTexImageARB
3271  *
3272  * WGL_ARB_render_texture: wglBindTexImageARB
3273  */
3274 static GLboolean WINAPI X11DRV_wglBindTexImageARB(HPBUFFERARB hPbuffer, int iBuffer)
3275 {
3276     Wine_GLPBuffer* object = hPbuffer;
3277     GLboolean ret = GL_FALSE;
3278
3279     TRACE("(%p, %d)\n", hPbuffer, iBuffer);
3280     if (NULL == object) {
3281         SetLastError(ERROR_INVALID_HANDLE);
3282         return GL_FALSE;
3283     }
3284     if (!object->use_render_texture) {
3285         SetLastError(ERROR_INVALID_HANDLE);
3286         return GL_FALSE;
3287     }
3288
3289     if (!use_render_texture_ati && 1 == use_render_texture_emulation) {
3290         static int init = 0;
3291         int prev_binded_texture = 0;
3292         GLXContext prev_context;
3293         Drawable prev_drawable;
3294         GLXContext tmp_context;
3295
3296         wine_tsx11_lock();
3297         prev_context = pglXGetCurrentContext();
3298         prev_drawable = pglXGetCurrentDrawable();
3299
3300         /* Our render_texture emulation is basic and lacks some features (1D/Cube support).
3301            This is mostly due to lack of demos/games using them. Further the use of glReadPixels
3302            isn't ideal performance wise but I wasn't able to get other ways working.
3303         */
3304         if(!init) {
3305             init = 1; /* Only show the FIXME once for performance reasons */
3306             FIXME("partial stub!\n");
3307         }
3308
3309         TRACE("drawable=%p, context=%p\n", (void*)object->drawable, prev_context);
3310         tmp_context = pglXCreateNewContext(gdi_display, object->fmt->fbconfig, object->fmt->render_type, prev_context, True);
3311
3312         pglGetIntegerv(object->texture_bind_target, &prev_binded_texture);
3313
3314         /* Switch to our pbuffer */
3315         pglXMakeCurrent(gdi_display, object->drawable, tmp_context);
3316
3317         /* Make sure that the prev_binded_texture is set as the current texture state isn't shared between contexts.
3318          * After that upload the pbuffer texture data. */
3319         pglBindTexture(object->texture_target, prev_binded_texture);
3320         pglCopyTexImage2D(object->texture_target, 0, object->use_render_texture, 0, 0, object->width, object->height, 0);
3321
3322         /* Switch back to the original drawable and upload the pbuffer-texture */
3323         pglXMakeCurrent(object->display, prev_drawable, prev_context);
3324         pglXDestroyContext(gdi_display, tmp_context);
3325         wine_tsx11_unlock();
3326         return GL_TRUE;
3327     }
3328
3329     if (NULL != pglXBindTexImageATI) {
3330         int buffer;
3331
3332         switch(iBuffer)
3333         {
3334             case WGL_FRONT_LEFT_ARB:
3335                 buffer = GLX_FRONT_LEFT_ATI;
3336                 break;
3337             case WGL_FRONT_RIGHT_ARB:
3338                 buffer = GLX_FRONT_RIGHT_ATI;
3339                 break;
3340             case WGL_BACK_LEFT_ARB:
3341                 buffer = GLX_BACK_LEFT_ATI;
3342                 break;
3343             case WGL_BACK_RIGHT_ARB:
3344                 buffer = GLX_BACK_RIGHT_ATI;
3345                 break;
3346             default:
3347                 ERR("Unknown iBuffer=%#x\n", iBuffer);
3348                 return FALSE;
3349         }
3350
3351         /* In the sample 'ogl_offscreen_rendering_3' from codesampler.net I get garbage on the screen.
3352          * I'm not sure if that's a bug in the ATI extension or in the program. I think that the program
3353          * expected a single buffering format since it didn't ask for double buffering. A buffer swap
3354          * fixed the program. I don't know what the correct behavior is. On the other hand that demo
3355          * works fine using our pbuffer emulation path.
3356          */
3357         wine_tsx11_lock();
3358         ret = pglXBindTexImageATI(object->display, object->drawable, buffer);
3359         wine_tsx11_unlock();
3360     }
3361     return ret;
3362 }
3363
3364 /**
3365  * X11DRV_wglReleaseTexImageARB
3366  *
3367  * WGL_ARB_render_texture: wglReleaseTexImageARB
3368  */
3369 static GLboolean WINAPI X11DRV_wglReleaseTexImageARB(HPBUFFERARB hPbuffer, int iBuffer)
3370 {
3371     Wine_GLPBuffer* object = hPbuffer;
3372     GLboolean ret = GL_FALSE;
3373
3374     TRACE("(%p, %d)\n", hPbuffer, iBuffer);
3375     if (NULL == object) {
3376         SetLastError(ERROR_INVALID_HANDLE);
3377         return GL_FALSE;
3378     }
3379     if (!object->use_render_texture) {
3380         SetLastError(ERROR_INVALID_HANDLE);
3381         return GL_FALSE;
3382     }
3383     if (!use_render_texture_ati && 1 == use_render_texture_emulation) {
3384         return GL_TRUE;
3385     }
3386     if (NULL != pglXReleaseTexImageATI) {
3387         int buffer;
3388
3389         switch(iBuffer)
3390         {
3391             case WGL_FRONT_LEFT_ARB:
3392                 buffer = GLX_FRONT_LEFT_ATI;
3393                 break;
3394             case WGL_FRONT_RIGHT_ARB:
3395                 buffer = GLX_FRONT_RIGHT_ATI;
3396                 break;
3397             case WGL_BACK_LEFT_ARB:
3398                 buffer = GLX_BACK_LEFT_ATI;
3399                 break;
3400             case WGL_BACK_RIGHT_ARB:
3401                 buffer = GLX_BACK_RIGHT_ATI;
3402                 break;
3403             default:
3404                 ERR("Unknown iBuffer=%#x\n", iBuffer);
3405                 return FALSE;
3406         }
3407         wine_tsx11_lock();
3408         ret = pglXReleaseTexImageATI(object->display, object->drawable, buffer);
3409         wine_tsx11_unlock();
3410     }
3411     return ret;
3412 }
3413
3414 /**
3415  * X11DRV_wglGetExtensionsStringEXT
3416  *
3417  * WGL_EXT_extensions_string: wglGetExtensionsStringEXT
3418  */
3419 static const char * WINAPI X11DRV_wglGetExtensionsStringEXT(void) {
3420     TRACE("() returning \"%s\"\n", WineGLInfo.wglExtensions);
3421     return WineGLInfo.wglExtensions;
3422 }
3423
3424 /**
3425  * X11DRV_wglGetSwapIntervalEXT
3426  *
3427  * WGL_EXT_swap_control: wglGetSwapIntervalEXT
3428  */
3429 static int WINAPI X11DRV_wglGetSwapIntervalEXT(VOID) {
3430     /* GLX_SGI_swap_control doesn't have any provisions for getting the swap
3431      * interval, so the swap interval has to be tracked. */
3432     TRACE("()\n");
3433     return swap_interval;
3434 }
3435
3436 /**
3437  * X11DRV_wglSwapIntervalEXT
3438  *
3439  * WGL_EXT_swap_control: wglSwapIntervalEXT
3440  */
3441 static BOOL WINAPI X11DRV_wglSwapIntervalEXT(int interval) {
3442     BOOL ret = TRUE;
3443
3444     TRACE("(%d)\n", interval);
3445
3446     if (interval < 0)
3447     {
3448         SetLastError(ERROR_INVALID_DATA);
3449         return FALSE;
3450     }
3451     else if (!has_swap_control && interval == 0)
3452     {
3453         /* wglSwapIntervalEXT considers an interval value of zero to mean that
3454          * vsync should be disabled, but glXSwapIntervalSGI considers such a
3455          * value to be an error. Just silently ignore the request for now. */
3456         WARN("Request to disable vertical sync is not handled\n");
3457         swap_interval = 0;
3458     }
3459     else
3460     {
3461         if (pglXSwapIntervalSGI)
3462         {
3463             wine_tsx11_lock();
3464             ret = !pglXSwapIntervalSGI(interval);
3465             wine_tsx11_unlock();
3466         }
3467         else
3468             WARN("GLX_SGI_swap_control extension is not available\n");
3469
3470         if (ret)
3471             swap_interval = interval;
3472         else
3473             SetLastError(ERROR_DC_NOT_FOUND);
3474     }
3475
3476     return ret;
3477 }
3478
3479 /**
3480  * X11DRV_wglAllocateMemoryNV
3481  *
3482  * WGL_NV_vertex_array_range: wglAllocateMemoryNV
3483  */
3484 static void* WINAPI X11DRV_wglAllocateMemoryNV(GLsizei size, GLfloat readfreq, GLfloat writefreq, GLfloat priority) {
3485     void *ret = NULL;
3486     TRACE("(%d, %f, %f, %f)\n", size, readfreq, writefreq, priority );
3487
3488     if (pglXAllocateMemoryNV)
3489     {
3490         wine_tsx11_lock();
3491         ret = pglXAllocateMemoryNV(size, readfreq, writefreq, priority);
3492         wine_tsx11_unlock();
3493     }
3494     return ret;
3495 }
3496
3497 /**
3498  * X11DRV_wglFreeMemoryNV
3499  *
3500  * WGL_NV_vertex_array_range: wglFreeMemoryNV
3501  */
3502 static void WINAPI X11DRV_wglFreeMemoryNV(GLvoid* pointer) {
3503     TRACE("(%p)\n", pointer);
3504     if (pglXFreeMemoryNV == NULL)
3505         return;
3506
3507     wine_tsx11_lock();
3508     pglXFreeMemoryNV(pointer);
3509     wine_tsx11_unlock();
3510 }
3511
3512 /**
3513  * X11DRV_wglSetPixelFormatWINE
3514  *
3515  * WGL_WINE_pixel_format_passthrough: wglSetPixelFormatWINE
3516  * This is a WINE-specific wglSetPixelFormat which can set the pixel format multiple times.
3517  */
3518 BOOL CDECL X11DRV_wglSetPixelFormatWINE(X11DRV_PDEVICE *physDev, int iPixelFormat, const PIXELFORMATDESCRIPTOR *ppfd)
3519 {
3520     TRACE("(%p,%d,%p)\n", physDev, iPixelFormat, ppfd);
3521
3522     if (!has_opengl()) return FALSE;
3523
3524     if (physDev->current_pf == iPixelFormat) return TRUE;
3525
3526     /* Relay to the core SetPixelFormat */
3527     TRACE("Changing iPixelFormat from %d to %d\n", physDev->current_pf, iPixelFormat);
3528     return internal_SetPixelFormat(physDev, iPixelFormat, ppfd);
3529 }
3530
3531 /**
3532  * glxRequireVersion (internal)
3533  *
3534  * Check if the supported GLX version matches requiredVersion.
3535  */
3536 static BOOL glxRequireVersion(int requiredVersion)
3537 {
3538     /* Both requiredVersion and glXVersion[1] contains the minor GLX version */
3539     if(requiredVersion <= WineGLInfo.glxVersion[1])
3540         return TRUE;
3541
3542     return FALSE;
3543 }
3544
3545 static BOOL glxRequireExtension(const char *requiredExtension)
3546 {
3547     if (strstr(WineGLInfo.glxExtensions, requiredExtension) == NULL) {
3548         return FALSE;
3549     }
3550
3551     return TRUE;
3552 }
3553
3554 static void register_extension_string(const char *ext)
3555 {
3556     if (WineGLInfo.wglExtensions[0])
3557         strcat(WineGLInfo.wglExtensions, " ");
3558     strcat(WineGLInfo.wglExtensions, ext);
3559
3560     TRACE("'%s'\n", ext);
3561 }
3562
3563 static BOOL register_extension(const WineGLExtension * ext)
3564 {
3565     int i;
3566
3567     assert( WineGLExtensionListSize < MAX_EXTENSIONS );
3568     WineGLExtensionList[WineGLExtensionListSize++] = ext;
3569
3570     register_extension_string(ext->extName);
3571
3572     for (i = 0; ext->extEntryPoints[i].funcName; ++i)
3573         TRACE("    - '%s'\n", ext->extEntryPoints[i].funcName);
3574
3575     return TRUE;
3576 }
3577
3578 static const WineGLExtension WGL_internal_functions =
3579 {
3580   "",
3581   {
3582     { "wglGetIntegerv", X11DRV_wglGetIntegerv },
3583     { "wglFinish", X11DRV_wglFinish },
3584     { "wglFlush", X11DRV_wglFlush },
3585   }
3586 };
3587
3588
3589 static const WineGLExtension WGL_ARB_create_context =
3590 {
3591   "WGL_ARB_create_context",
3592   {
3593     { "wglCreateContextAttribsARB", X11DRV_wglCreateContextAttribsARB },
3594   }
3595 };
3596
3597 static const WineGLExtension WGL_ARB_extensions_string =
3598 {
3599   "WGL_ARB_extensions_string",
3600   {
3601     { "wglGetExtensionsStringARB", X11DRV_wglGetExtensionsStringARB },
3602   }
3603 };
3604
3605 static const WineGLExtension WGL_ARB_make_current_read =
3606 {
3607   "WGL_ARB_make_current_read",
3608   {
3609     { "wglGetCurrentReadDCARB", X11DRV_wglGetCurrentReadDCARB },
3610     { "wglMakeContextCurrentARB", X11DRV_wglMakeContextCurrentARB },
3611   }
3612 };
3613
3614 static const WineGLExtension WGL_ARB_multisample =
3615 {
3616   "WGL_ARB_multisample",
3617 };
3618
3619 static const WineGLExtension WGL_ARB_pbuffer =
3620 {
3621   "WGL_ARB_pbuffer",
3622   {
3623     { "wglCreatePbufferARB", X11DRV_wglCreatePbufferARB },
3624     { "wglDestroyPbufferARB", X11DRV_wglDestroyPbufferARB },
3625     { "wglGetPbufferDCARB", X11DRV_wglGetPbufferDCARB },
3626     { "wglQueryPbufferARB", X11DRV_wglQueryPbufferARB },
3627     { "wglReleasePbufferDCARB", X11DRV_wglReleasePbufferDCARB },
3628     { "wglSetPbufferAttribARB", X11DRV_wglSetPbufferAttribARB },
3629   }
3630 };
3631
3632 static const WineGLExtension WGL_ARB_pixel_format =
3633 {
3634   "WGL_ARB_pixel_format",
3635   {
3636     { "wglChoosePixelFormatARB", X11DRV_wglChoosePixelFormatARB },
3637     { "wglGetPixelFormatAttribfvARB", X11DRV_wglGetPixelFormatAttribfvARB },
3638     { "wglGetPixelFormatAttribivARB", X11DRV_wglGetPixelFormatAttribivARB },
3639   }
3640 };
3641
3642 static const WineGLExtension WGL_ARB_render_texture =
3643 {
3644   "WGL_ARB_render_texture",
3645   {
3646     { "wglBindTexImageARB", X11DRV_wglBindTexImageARB },
3647     { "wglReleaseTexImageARB", X11DRV_wglReleaseTexImageARB },
3648   }
3649 };
3650
3651 static const WineGLExtension WGL_EXT_extensions_string =
3652 {
3653   "WGL_EXT_extensions_string",
3654   {
3655     { "wglGetExtensionsStringEXT", X11DRV_wglGetExtensionsStringEXT },
3656   }
3657 };
3658
3659 static const WineGLExtension WGL_EXT_swap_control =
3660 {
3661   "WGL_EXT_swap_control",
3662   {
3663     { "wglSwapIntervalEXT", X11DRV_wglSwapIntervalEXT },
3664     { "wglGetSwapIntervalEXT", X11DRV_wglGetSwapIntervalEXT },
3665   }
3666 };
3667
3668 static const WineGLExtension WGL_NV_vertex_array_range =
3669 {
3670   "WGL_NV_vertex_array_range",
3671   {
3672     { "wglAllocateMemoryNV", X11DRV_wglAllocateMemoryNV },
3673     { "wglFreeMemoryNV", X11DRV_wglFreeMemoryNV },
3674   }
3675 };
3676
3677 static const WineGLExtension WGL_WINE_pixel_format_passthrough =
3678 {
3679   "WGL_WINE_pixel_format_passthrough",
3680   {
3681     { "wglSetPixelFormatWINE", X11DRV_wglSetPixelFormatWINE },
3682   }
3683 };
3684
3685 /**
3686  * X11DRV_WineGL_LoadExtensions
3687  */
3688 static void X11DRV_WineGL_LoadExtensions(void)
3689 {
3690     WineGLInfo.wglExtensions[0] = 0;
3691
3692     /* Load Wine internal functions */
3693     register_extension(&WGL_internal_functions);
3694
3695     /* ARB Extensions */
3696
3697     if(glxRequireExtension("GLX_ARB_create_context"))
3698     {
3699         register_extension(&WGL_ARB_create_context);
3700
3701         if(glxRequireExtension("GLX_ARB_create_context_profile"))
3702             register_extension_string("WGL_ARB_create_context_profile");
3703     }
3704
3705     if(glxRequireExtension("GLX_ARB_fbconfig_float"))
3706     {
3707         register_extension_string("WGL_ARB_pixel_format_float");
3708         register_extension_string("WGL_ATI_pixel_format_float");
3709     }
3710
3711     register_extension(&WGL_ARB_extensions_string);
3712
3713     if (glxRequireVersion(3))
3714         register_extension(&WGL_ARB_make_current_read);
3715
3716     if (glxRequireExtension("GLX_ARB_multisample"))
3717         register_extension(&WGL_ARB_multisample);
3718
3719     /* In general pbuffer functionality requires support in the X-server. The functionality is
3720      * available either when the GLX_SGIX_pbuffer is present or when the GLX server version is 1.3.
3721      * All display drivers except for Nvidia's use the GLX module from Xfree86/Xorg which only
3722      * supports GLX 1.2. The endresult is that only Nvidia's drivers support pbuffers.
3723      *
3724      * The only other drive which has pbuffer support is Ati's FGLRX driver. They provide clientside GLX 1.3 support
3725      * without support in the X-server (which other Mesa based drivers require).
3726      *
3727      * Support pbuffers when the GLX version is 1.3 and GLX_SGIX_pbuffer is available. Further pbuffers can
3728      * also be supported when GLX_ATI_render_texture is available. This extension depends on pbuffers, so when it
3729      * is available pbuffers must be available too. */
3730     if ( (glxRequireVersion(3) && glxRequireExtension("GLX_SGIX_pbuffer")) || glxRequireExtension("GLX_ATI_render_texture"))
3731         register_extension(&WGL_ARB_pbuffer);
3732
3733     register_extension(&WGL_ARB_pixel_format);
3734
3735     /* Support WGL_ARB_render_texture when there's support or pbuffer based emulation */
3736     if (glxRequireExtension("GLX_ATI_render_texture") ||
3737         glxRequireExtension("GLX_ARB_render_texture") ||
3738         (glxRequireVersion(3) && glxRequireExtension("GLX_SGIX_pbuffer") && use_render_texture_emulation))
3739     {
3740         register_extension(&WGL_ARB_render_texture);
3741
3742         /* The WGL version of GLX_NV_float_buffer requires render_texture */
3743         if(glxRequireExtension("GLX_NV_float_buffer"))
3744             register_extension_string("WGL_NV_float_buffer");
3745
3746         /* Again there's no GLX equivalent for this extension, so depend on the required GL extension */
3747         if(strstr(WineGLInfo.glExtensions, "GL_NV_texture_rectangle") != NULL)
3748             register_extension_string("WGL_NV_texture_rectangle");
3749     }
3750
3751     /* EXT Extensions */
3752
3753     register_extension(&WGL_EXT_extensions_string);
3754
3755     /* Load this extension even when it isn't backed by a GLX extension because it is has been around for ages.
3756      * Games like Call of Duty and K.O.T.O.R. rely on it. Further our emulation is good enough. */
3757     register_extension(&WGL_EXT_swap_control);
3758
3759     if(glxRequireExtension("GLX_EXT_framebuffer_sRGB"))
3760         register_extension_string("WGL_EXT_framebuffer_sRGB");
3761
3762     if(glxRequireExtension("GLX_EXT_fbconfig_packed_float"))
3763         register_extension_string("WGL_EXT_pixel_format_packed_float");
3764
3765     if (glxRequireExtension("GLX_EXT_swap_control"))
3766         has_swap_control = TRUE;
3767
3768     /* The OpenGL extension GL_NV_vertex_array_range adds wgl/glX functions which aren't exported as 'real' wgl/glX extensions. */
3769     if(strstr(WineGLInfo.glExtensions, "GL_NV_vertex_array_range") != NULL)
3770         register_extension(&WGL_NV_vertex_array_range);
3771
3772     /* WINE-specific WGL Extensions */
3773
3774     /* In WineD3D we need the ability to set the pixel format more than once (e.g. after a device reset).
3775      * The default wglSetPixelFormat doesn't allow this, so add our own which allows it.
3776      */
3777     register_extension(&WGL_WINE_pixel_format_passthrough);
3778 }
3779
3780
3781 Drawable get_glxdrawable(X11DRV_PDEVICE *physDev)
3782 {
3783     Drawable ret;
3784
3785     if(physDev->bitmap)
3786     {
3787         if (physDev->bitmap->hbitmap == BITMAP_stock_phys_bitmap.hbitmap)
3788             ret = physDev->drawable; /* PBuffer */
3789         else
3790             ret = physDev->bitmap->glxpixmap;
3791     }
3792     else if(physDev->gl_drawable)
3793         ret = physDev->gl_drawable;
3794     else
3795         ret = physDev->drawable;
3796     return ret;
3797 }
3798
3799 BOOL destroy_glxpixmap(Display *display, XID glxpixmap)
3800 {
3801     wine_tsx11_lock(); 
3802     pglXDestroyGLXPixmap(display, glxpixmap);
3803     wine_tsx11_unlock(); 
3804     return TRUE;
3805 }
3806
3807 /**
3808  * X11DRV_SwapBuffers
3809  *
3810  * Swap the buffers of this DC
3811  */
3812 BOOL CDECL X11DRV_SwapBuffers(X11DRV_PDEVICE *physDev)
3813 {
3814   GLXDrawable drawable;
3815   Wine_GLContext *ctx = NtCurrentTeb()->glContext;
3816
3817   if (!has_opengl()) return FALSE;
3818
3819   TRACE("(%p)\n", physDev);
3820
3821   if (!ctx)
3822   {
3823       WARN("Using a NULL context, skipping\n");
3824       SetLastError(ERROR_INVALID_HANDLE);
3825       return FALSE;
3826   }
3827
3828   if (!physDev->current_pf)
3829   {
3830       WARN("Using an invalid drawable, skipping\n");
3831       SetLastError(ERROR_INVALID_HANDLE);
3832       return FALSE;
3833   }
3834
3835   drawable = get_glxdrawable(physDev);
3836
3837   wine_tsx11_lock();
3838   sync_context(ctx);
3839   if(physDev->pixmap) {
3840       if(pglXCopySubBufferMESA) {
3841           int w = physDev->dc_rect.right - physDev->dc_rect.left;
3842           int h = physDev->dc_rect.bottom - physDev->dc_rect.top;
3843
3844           /* (glX)SwapBuffers has an implicit glFlush effect, however
3845            * GLX_MESA_copy_sub_buffer doesn't. Make sure GL is flushed before
3846            * copying */
3847           pglFlush();
3848           if(w > 0 && h > 0)
3849               pglXCopySubBufferMESA(gdi_display, drawable, 0, 0, w, h);
3850       }
3851       else
3852           pglXSwapBuffers(gdi_display, drawable);
3853   }
3854   else
3855       pglXSwapBuffers(gdi_display, drawable);
3856
3857   flush_gl_drawable(physDev);
3858   wine_tsx11_unlock();
3859
3860   /* FPS support */
3861   if (TRACE_ON(fps))
3862   {
3863       static long prev_time, start_time;
3864       static unsigned long frames, frames_total;
3865
3866       DWORD time = GetTickCount();
3867       frames++;
3868       frames_total++;
3869       /* every 1.5 seconds */
3870       if (time - prev_time > 1500) {
3871           TRACE_(fps)("@ approx %.2ffps, total %.2ffps\n",
3872                       1000.0*frames/(time - prev_time), 1000.0*frames_total/(time - start_time));
3873           prev_time = time;
3874           frames = 0;
3875           if(start_time == 0) start_time = time;
3876       }
3877   }
3878
3879   return TRUE;
3880 }
3881
3882 XVisualInfo *visual_from_fbconfig_id( XID fbconfig_id )
3883 {
3884     WineGLPixelFormat *fmt;
3885     XVisualInfo *ret;
3886
3887     fmt = ConvertPixelFormatGLXtoWGL(gdi_display, fbconfig_id, 0 /* no flags */);
3888     if(fmt == NULL)
3889         return NULL;
3890
3891     wine_tsx11_lock();
3892     ret = pglXGetVisualFromFBConfig(gdi_display, fmt->fbconfig);
3893     wine_tsx11_unlock();
3894     return ret;
3895 }
3896
3897 #else  /* no OpenGL includes */
3898
3899 void X11DRV_OpenGL_Cleanup(void)
3900 {
3901 }
3902
3903 static inline void opengl_error(void)
3904 {
3905     static int warned;
3906     if (!warned++) ERR("No OpenGL support compiled in.\n");
3907 }
3908
3909 int pixelformat_from_fbconfig_id(XID fbconfig_id)
3910 {
3911     return 0;
3912 }
3913
3914 void mark_drawable_dirty(Drawable old, Drawable new)
3915 {
3916 }
3917
3918 void flush_gl_drawable(X11DRV_PDEVICE *physDev)
3919 {
3920 }
3921
3922 Drawable create_glxpixmap(Display *display, XVisualInfo *vis, Pixmap parent)
3923 {
3924     return 0;
3925 }
3926
3927 /***********************************************************************
3928  *              ChoosePixelFormat (X11DRV.@)
3929  */
3930 int CDECL X11DRV_ChoosePixelFormat(X11DRV_PDEVICE *physDev,
3931                                      const PIXELFORMATDESCRIPTOR *ppfd) {
3932   opengl_error();
3933   return 0;
3934 }
3935
3936 /***********************************************************************
3937  *              DescribePixelFormat (X11DRV.@)
3938  */
3939 int CDECL X11DRV_DescribePixelFormat(X11DRV_PDEVICE *physDev,
3940                                      int iPixelFormat,
3941                                      UINT nBytes,
3942                                      PIXELFORMATDESCRIPTOR *ppfd) {
3943   opengl_error();
3944   return 0;
3945 }
3946
3947 /***********************************************************************
3948  *              GetPixelFormat (X11DRV.@)
3949  */
3950 int CDECL X11DRV_GetPixelFormat(X11DRV_PDEVICE *physDev) {
3951   opengl_error();
3952   return 0;
3953 }
3954
3955 /***********************************************************************
3956  *              SetPixelFormat (X11DRV.@)
3957  */
3958 BOOL CDECL X11DRV_SetPixelFormat(X11DRV_PDEVICE *physDev,
3959                                    int iPixelFormat,
3960                                    const PIXELFORMATDESCRIPTOR *ppfd) {
3961   opengl_error();
3962   return FALSE;
3963 }
3964
3965 /***********************************************************************
3966  *              SwapBuffers (X11DRV.@)
3967  */
3968 BOOL CDECL X11DRV_SwapBuffers(X11DRV_PDEVICE *physDev) {
3969   opengl_error();
3970   return FALSE;
3971 }
3972
3973 /**
3974  * X11DRV_wglCopyContext
3975  *
3976  * For OpenGL32 wglCopyContext.
3977  */
3978 BOOL CDECL X11DRV_wglCopyContext(HGLRC hglrcSrc, HGLRC hglrcDst, UINT mask) {
3979     opengl_error();
3980     return FALSE;
3981 }
3982
3983 /**
3984  * X11DRV_wglCreateContext
3985  *
3986  * For OpenGL32 wglCreateContext.
3987  */
3988 HGLRC CDECL X11DRV_wglCreateContext(X11DRV_PDEVICE *physDev) {
3989     opengl_error();
3990     return NULL;
3991 }
3992
3993 /**
3994  * X11DRV_wglCreateContextAttribsARB
3995  *
3996  * WGL_ARB_create_context: wglCreateContextAttribsARB
3997  */
3998 HGLRC CDECL X11DRV_wglCreateContextAttribsARB(X11DRV_PDEVICE *physDev, HGLRC hShareContext, const int* attribList)
3999 {
4000     opengl_error();
4001     return NULL;
4002 }
4003
4004 /**
4005  * X11DRV_wglDeleteContext
4006  *
4007  * For OpenGL32 wglDeleteContext.
4008  */
4009 BOOL CDECL X11DRV_wglDeleteContext(HGLRC hglrc) {
4010     opengl_error();
4011     return FALSE;
4012 }
4013
4014 /**
4015  * X11DRV_wglGetProcAddress
4016  *
4017  * For OpenGL32 wglGetProcAddress.
4018  */
4019 PROC CDECL X11DRV_wglGetProcAddress(LPCSTR lpszProc) {
4020     opengl_error();
4021     return NULL;
4022 }
4023
4024 HDC CDECL X11DRV_wglGetPbufferDCARB(X11DRV_PDEVICE *hDevice, void *hPbuffer)
4025 {
4026     opengl_error();
4027     return NULL;
4028 }
4029
4030 BOOL CDECL X11DRV_wglMakeContextCurrentARB(X11DRV_PDEVICE* hDrawDev, X11DRV_PDEVICE* hReadDev, HGLRC hglrc) {
4031     opengl_error();
4032     return FALSE;
4033 }
4034
4035 /**
4036  * X11DRV_wglMakeCurrent
4037  *
4038  * For OpenGL32 wglMakeCurrent.
4039  */
4040 BOOL CDECL X11DRV_wglMakeCurrent(X11DRV_PDEVICE *physDev, HGLRC hglrc) {
4041     opengl_error();
4042     return FALSE;
4043 }
4044
4045 /**
4046  * X11DRV_wglShareLists
4047  *
4048  * For OpenGL32 wglShareLists.
4049  */
4050 BOOL CDECL X11DRV_wglShareLists(HGLRC hglrc1, HGLRC hglrc2) {
4051     opengl_error();
4052     return FALSE;
4053 }
4054
4055 /**
4056  * X11DRV_wglUseFontBitmapsA
4057  *
4058  * For OpenGL32 wglUseFontBitmapsA.
4059  */
4060 BOOL CDECL X11DRV_wglUseFontBitmapsA(X11DRV_PDEVICE *physDev, DWORD first, DWORD count, DWORD listBase)
4061 {
4062     opengl_error();
4063     return FALSE;
4064 }
4065
4066 /**
4067  * X11DRV_wglUseFontBitmapsW
4068  *
4069  * For OpenGL32 wglUseFontBitmapsW.
4070  */
4071 BOOL CDECL X11DRV_wglUseFontBitmapsW(X11DRV_PDEVICE *physDev, DWORD first, DWORD count, DWORD listBase)
4072 {
4073     opengl_error();
4074     return FALSE;
4075 }
4076
4077 /**
4078  * X11DRV_wglSetPixelFormatWINE
4079  *
4080  * WGL_WINE_pixel_format_passthrough: wglSetPixelFormatWINE
4081  * This is a WINE-specific wglSetPixelFormat which can set the pixel format multiple times.
4082  */
4083 BOOL CDECL X11DRV_wglSetPixelFormatWINE(X11DRV_PDEVICE *physDev, int iPixelFormat, const PIXELFORMATDESCRIPTOR *ppfd)
4084 {
4085     opengl_error();
4086     return FALSE;
4087 }
4088
4089 Drawable get_glxdrawable(X11DRV_PDEVICE *physDev)
4090 {
4091     return 0;
4092 }
4093
4094 BOOL destroy_glxpixmap(Display *display, XID glxpixmap)
4095 {
4096     return FALSE;
4097 }
4098
4099 XVisualInfo *visual_from_fbconfig_id( XID fbconfig_id )
4100 {
4101     return NULL;
4102 }
4103
4104 #endif /* defined(SONAME_LIBGL) */