winex11: Add window data structure locking to the SysCommand entry point.
[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  * Copyright 2012 Alexandre Julliard
10  *
11  * This library is free software; you can redistribute it and/or
12  * modify it under the terms of the GNU Lesser General Public
13  * License as published by the Free Software Foundation; either
14  * version 2.1 of the License, or (at your option) any later version.
15  *
16  * This library is distributed in the hope that it will be useful,
17  * but WITHOUT ANY WARRANTY; without even the implied warranty of
18  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
19  * Lesser General Public License for more details.
20  *
21  * You should have received a copy of the GNU Lesser General Public
22  * License along with this library; if not, write to the Free Software
23  * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA
24  */
25
26 #include "config.h"
27 #include "wine/port.h"
28
29 #include <assert.h>
30 #include <stdlib.h>
31 #include <string.h>
32
33 #ifdef HAVE_SYS_SOCKET_H
34 #include <sys/socket.h>
35 #endif
36 #ifdef HAVE_SYS_UN_H
37 #include <sys/un.h>
38 #endif
39 #ifdef HAVE_GL_GL_H
40 # include <GL/gl.h>
41 #endif
42 #ifdef HAVE_GL_GLX_H
43 # include <GL/glx.h>
44 #endif
45 #undef APIENTRY
46 #undef GLAPI
47 #undef WINGDIAPI
48
49 #include "x11drv.h"
50 #include "xcomposite.h"
51 #include "winternl.h"
52 #include "wine/library.h"
53 #include "wine/debug.h"
54
55 WINE_DEFAULT_DEBUG_CHANNEL(wgl);
56
57 #ifdef SONAME_LIBGL
58
59 WINE_DECLARE_DEBUG_CHANNEL(winediag);
60
61 #include "wine/wgl_driver.h"
62 #include "wine/wglext.h"
63
64 /* For compatibility with old Mesa headers */
65 #ifndef GLX_SAMPLE_BUFFERS_ARB
66 # define GLX_SAMPLE_BUFFERS_ARB           100000
67 #endif
68 #ifndef GLX_SAMPLES_ARB
69 # define GLX_SAMPLES_ARB                  100001
70 #endif
71 #ifndef GL_TEXTURE_CUBE_MAP
72 # define GL_TEXTURE_CUBE_MAP              0x8513
73 #endif
74 #ifndef GLX_FRAMEBUFFER_SRGB_CAPABLE_EXT
75 # define GLX_FRAMEBUFFER_SRGB_CAPABLE_EXT 0x20B2
76 #endif
77 #ifndef GLX_EXT_fbconfig_packed_float
78 # define GLX_RGBA_UNSIGNED_FLOAT_TYPE_EXT 0x20B1
79 # define GLX_RGBA_UNSIGNED_FLOAT_BIT_EXT  0x00000008
80 #endif
81 #ifndef GLX_ARB_create_context
82 # define GLX_CONTEXT_MAJOR_VERSION_ARB    0x2091
83 # define GLX_CONTEXT_MINOR_VERSION_ARB    0x2092
84 # define GLX_CONTEXT_FLAGS_ARB            0x2094
85 #endif
86 #ifndef GLX_ARB_create_context_profile
87 # define GLX_CONTEXT_PROFILE_MASK_ARB     0x9126
88 #endif
89 /** GLX_ATI_pixel_format_float */
90 #define GLX_RGBA_FLOAT_ATI_BIT            0x00000100
91 /** GLX_ARB_pixel_format_float */
92 #define GLX_RGBA_FLOAT_BIT                0x00000004
93 #define GLX_RGBA_FLOAT_TYPE               0x20B9
94 /** GL_NV_float_buffer */
95 #define GL_FLOAT_R_NV                     0x8880
96 #define GL_FLOAT_RG_NV                    0x8881
97 #define GL_FLOAT_RGB_NV                   0x8882
98 #define GL_FLOAT_RGBA_NV                  0x8883
99 #define GL_FLOAT_R16_NV                   0x8884
100 #define GL_FLOAT_R32_NV                   0x8885
101 #define GL_FLOAT_RG16_NV                  0x8886
102 #define GL_FLOAT_RG32_NV                  0x8887
103 #define GL_FLOAT_RGB16_NV                 0x8888
104 #define GL_FLOAT_RGB32_NV                 0x8889
105 #define GL_FLOAT_RGBA16_NV                0x888A
106 #define GL_FLOAT_RGBA32_NV                0x888B
107 #define GL_TEXTURE_FLOAT_COMPONENTS_NV    0x888C
108 #define GL_FLOAT_CLEAR_COLOR_VALUE_NV     0x888D
109 #define GL_FLOAT_RGBA_MODE_NV             0x888E
110 /** GLX_NV_float_buffer */
111 #define GLX_FLOAT_COMPONENTS_NV           0x20B0
112
113
114 struct WineGLInfo {
115     const char *glVersion;
116     char *glExtensions;
117
118     int glxVersion[2];
119
120     const char *glxServerVersion;
121     const char *glxServerVendor;
122     const char *glxServerExtensions;
123
124     const char *glxClientVersion;
125     const char *glxClientVendor;
126     const char *glxClientExtensions;
127
128     const char *glxExtensions;
129
130     BOOL glxDirect;
131     char wglExtensions[4096];
132 };
133
134 struct wgl_pixel_format
135 {
136     GLXFBConfig fbconfig;
137     int         fmt_id;
138     int         render_type;
139     DWORD       dwFlags; /* We store some PFD_* flags in here for emulated bitmap formats */
140 };
141
142 struct wgl_context
143 {
144     HDC hdc;
145     BOOL has_been_current;
146     BOOL sharing;
147     BOOL gl3_context;
148     XVisualInfo *vis;
149     const struct wgl_pixel_format *fmt;
150     int numAttribs; /* This is needed for delaying wglCreateContextAttribsARB */
151     int attribList[16]; /* This is needed for delaying wglCreateContextAttribsARB */
152     GLXContext ctx;
153     Drawable drawables[2];
154     BOOL refresh_drawables;
155     struct list entry;
156 };
157
158 struct wgl_pbuffer
159 {
160     Drawable   drawable;
161     const struct wgl_pixel_format* fmt;
162     int        width;
163     int        height;
164     int*       attribList;
165     int        use_render_texture; /* This is also the internal texture format */
166     int        texture_bind_target;
167     int        texture_bpp;
168     GLint      texture_format;
169     GLuint     texture_target;
170     GLenum     texture_type;
171     GLuint     texture;
172     int        texture_level;
173 };
174
175 enum dc_gl_type
176 {
177     DC_GL_NONE,       /* no GL support (pixel format not set yet) */
178     DC_GL_WINDOW,     /* normal top-level window */
179     DC_GL_CHILD_WIN,  /* child window using XComposite */
180     DC_GL_PIXMAP_WIN, /* child window using intermediate pixmap */
181     DC_GL_PBUFFER     /* pseudo memory DC using a PBuffer */
182 };
183
184 struct glx_physdev
185 {
186     struct gdi_physdev             dev;
187     X11DRV_PDEVICE                *x11dev;
188     enum dc_gl_type                type;          /* type of GL device context */
189     const struct wgl_pixel_format *format;
190     Drawable                       drawable;
191     Pixmap                         pixmap;        /* pixmap for a DL_GL_PIXMAP_WIN drawable */
192 };
193
194 struct gl_drawable
195 {
196     enum dc_gl_type                type;         /* type of GL surface */
197     Drawable                       drawable;     /* drawable for rendering to the client area */
198     Pixmap                         pixmap;       /* base pixmap if drawable is a GLXPixmap */
199     Colormap                       colormap;     /* colormap used for the drawable */
200     const struct wgl_pixel_format *format;       /* pixel format for the drawable */
201     XVisualInfo                   *visual;       /* information about the GL visual */
202     RECT                           rect;         /* drawable rect, relative to whole window drawable */
203 };
204
205 /* X context to associate a struct gl_drawable to an hwnd */
206 static XContext gl_hwnd_context;
207 /* X context to associate a struct gl_drawable to a pbuffer hdc */
208 static XContext gl_pbuffer_context;
209
210 static const struct gdi_dc_funcs glxdrv_funcs;
211
212 static inline struct glx_physdev *get_glxdrv_dev( PHYSDEV dev )
213 {
214     return (struct glx_physdev *)dev;
215 }
216
217 static struct list context_list = LIST_INIT( context_list );
218 static struct WineGLInfo WineGLInfo = { 0 };
219 static struct wgl_pixel_format *pixel_formats;
220 static int nb_pixel_formats, nb_onscreen_formats;
221 static int use_render_texture_emulation = 1;
222 static BOOL has_swap_control;
223 static int swap_interval = 1;
224
225 static CRITICAL_SECTION context_section;
226 static CRITICAL_SECTION_DEBUG critsect_debug =
227 {
228     0, 0, &context_section,
229     { &critsect_debug.ProcessLocksList, &critsect_debug.ProcessLocksList },
230       0, 0, { (DWORD_PTR)(__FILE__ ": context_section") }
231 };
232 static CRITICAL_SECTION context_section = { &critsect_debug, -1, 0, 0, 0, 0 };
233
234 static struct opengl_funcs opengl_funcs;
235
236 #define USE_GL_FUNC(name) #name,
237 static const char *opengl_func_names[] = { ALL_WGL_FUNCS };
238 #undef USE_GL_FUNC
239
240 static void X11DRV_WineGL_LoadExtensions(void);
241 static void init_pixel_formats( Display *display );
242 static BOOL glxRequireVersion(int requiredVersion);
243
244 static void dump_PIXELFORMATDESCRIPTOR(const PIXELFORMATDESCRIPTOR *ppfd) {
245   TRACE("  - size / version : %d / %d\n", ppfd->nSize, ppfd->nVersion);
246   TRACE("  - dwFlags : ");
247 #define TEST_AND_DUMP(t,tv) if ((t) & (tv)) TRACE(#tv " ")
248   TEST_AND_DUMP(ppfd->dwFlags, PFD_DEPTH_DONTCARE);
249   TEST_AND_DUMP(ppfd->dwFlags, PFD_DOUBLEBUFFER);
250   TEST_AND_DUMP(ppfd->dwFlags, PFD_DOUBLEBUFFER_DONTCARE);
251   TEST_AND_DUMP(ppfd->dwFlags, PFD_DRAW_TO_WINDOW);
252   TEST_AND_DUMP(ppfd->dwFlags, PFD_DRAW_TO_BITMAP);
253   TEST_AND_DUMP(ppfd->dwFlags, PFD_GENERIC_ACCELERATED);
254   TEST_AND_DUMP(ppfd->dwFlags, PFD_GENERIC_FORMAT);
255   TEST_AND_DUMP(ppfd->dwFlags, PFD_NEED_PALETTE);
256   TEST_AND_DUMP(ppfd->dwFlags, PFD_NEED_SYSTEM_PALETTE);
257   TEST_AND_DUMP(ppfd->dwFlags, PFD_STEREO);
258   TEST_AND_DUMP(ppfd->dwFlags, PFD_STEREO_DONTCARE);
259   TEST_AND_DUMP(ppfd->dwFlags, PFD_SUPPORT_GDI);
260   TEST_AND_DUMP(ppfd->dwFlags, PFD_SUPPORT_OPENGL);
261   TEST_AND_DUMP(ppfd->dwFlags, PFD_SWAP_COPY);
262   TEST_AND_DUMP(ppfd->dwFlags, PFD_SWAP_EXCHANGE);
263   TEST_AND_DUMP(ppfd->dwFlags, PFD_SWAP_LAYER_BUFFERS);
264   /* PFD_SUPPORT_COMPOSITION is new in Vista, it is similar to composition
265    * under X e.g. COMPOSITE + GLX_EXT_TEXTURE_FROM_PIXMAP. */
266   TEST_AND_DUMP(ppfd->dwFlags, PFD_SUPPORT_COMPOSITION);
267 #undef TEST_AND_DUMP
268   TRACE("\n");
269
270   TRACE("  - iPixelType : ");
271   switch (ppfd->iPixelType) {
272   case PFD_TYPE_RGBA: TRACE("PFD_TYPE_RGBA"); break;
273   case PFD_TYPE_COLORINDEX: TRACE("PFD_TYPE_COLORINDEX"); break;
274   }
275   TRACE("\n");
276
277   TRACE("  - Color   : %d\n", ppfd->cColorBits);
278   TRACE("  - Red     : %d\n", ppfd->cRedBits);
279   TRACE("  - Green   : %d\n", ppfd->cGreenBits);
280   TRACE("  - Blue    : %d\n", ppfd->cBlueBits);
281   TRACE("  - Alpha   : %d\n", ppfd->cAlphaBits);
282   TRACE("  - Accum   : %d\n", ppfd->cAccumBits);
283   TRACE("  - Depth   : %d\n", ppfd->cDepthBits);
284   TRACE("  - Stencil : %d\n", ppfd->cStencilBits);
285   TRACE("  - Aux     : %d\n", ppfd->cAuxBuffers);
286
287   TRACE("  - iLayerType : ");
288   switch (ppfd->iLayerType) {
289   case PFD_MAIN_PLANE: TRACE("PFD_MAIN_PLANE"); break;
290   case PFD_OVERLAY_PLANE: TRACE("PFD_OVERLAY_PLANE"); break;
291   case (BYTE)PFD_UNDERLAY_PLANE: TRACE("PFD_UNDERLAY_PLANE"); break;
292   }
293   TRACE("\n");
294 }
295
296 #define PUSH1(attribs,att)        do { attribs[nAttribs++] = (att); } while (0)
297 #define PUSH2(attribs,att,value)  do { attribs[nAttribs++] = (att); attribs[nAttribs++] = (value); } while(0)
298
299 #define MAKE_FUNCPTR(f) static typeof(f) * p##f;
300 /* GLX 1.0 */
301 MAKE_FUNCPTR(glXChooseVisual)
302 MAKE_FUNCPTR(glXCopyContext)
303 MAKE_FUNCPTR(glXCreateContext)
304 MAKE_FUNCPTR(glXCreateGLXPixmap)
305 MAKE_FUNCPTR(glXGetCurrentContext)
306 MAKE_FUNCPTR(glXGetCurrentDrawable)
307 MAKE_FUNCPTR(glXDestroyContext)
308 MAKE_FUNCPTR(glXDestroyGLXPixmap)
309 MAKE_FUNCPTR(glXGetConfig)
310 MAKE_FUNCPTR(glXIsDirect)
311 MAKE_FUNCPTR(glXMakeCurrent)
312 MAKE_FUNCPTR(glXSwapBuffers)
313 MAKE_FUNCPTR(glXQueryExtension)
314 MAKE_FUNCPTR(glXQueryVersion)
315
316 /* GLX 1.1 */
317 MAKE_FUNCPTR(glXGetClientString)
318 MAKE_FUNCPTR(glXQueryExtensionsString)
319 MAKE_FUNCPTR(glXQueryServerString)
320
321 /* GLX 1.3 */
322 MAKE_FUNCPTR(glXGetFBConfigs)
323 MAKE_FUNCPTR(glXChooseFBConfig)
324 MAKE_FUNCPTR(glXCreatePbuffer)
325 MAKE_FUNCPTR(glXCreateNewContext)
326 MAKE_FUNCPTR(glXDestroyPbuffer)
327 MAKE_FUNCPTR(glXGetFBConfigAttrib)
328 MAKE_FUNCPTR(glXGetVisualFromFBConfig)
329 MAKE_FUNCPTR(glXMakeContextCurrent)
330 MAKE_FUNCPTR(glXQueryDrawable)
331 MAKE_FUNCPTR(glXGetCurrentReadDrawable)
332 #undef MAKE_FUNCPTR
333
334 /* GLX Extensions */
335 static GLXContext (*pglXCreateContextAttribsARB)(Display *dpy, GLXFBConfig config, GLXContext share_context, Bool direct, const int *attrib_list);
336 static void* (*pglXGetProcAddressARB)(const GLubyte *);
337 static int   (*pglXSwapIntervalSGI)(int);
338
339 /* NV GLX Extension */
340 static void* (*pglXAllocateMemoryNV)(GLsizei size, GLfloat readfreq, GLfloat writefreq, GLfloat priority);
341 static void  (*pglXFreeMemoryNV)(GLvoid *pointer);
342
343 /* MESA GLX Extensions */
344 static void (*pglXCopySubBufferMESA)(Display *dpy, GLXDrawable drawable, int x, int y, int width, int height);
345
346 /* Standard OpenGL */
347 static void (*pglFinish)(void);
348 static void (*pglFlush)(void);
349
350 static void wglFinish(void);
351 static void wglFlush(void);
352
353 /* check if the extension is present in the list */
354 static BOOL has_extension( const char *list, const char *ext )
355 {
356     size_t len = strlen( ext );
357
358     while (list)
359     {
360         while (*list == ' ') list++;
361         if (!strncmp( list, ext, len ) && (!list[len] || list[len] == ' ')) return TRUE;
362         list = strchr( list, ' ' );
363     }
364     return FALSE;
365 }
366
367 static int GLXErrorHandler(Display *dpy, XErrorEvent *event, void *arg)
368 {
369     /* In the future we might want to find the exact X or GLX error to report back to the app */
370     return 1;
371 }
372
373 static BOOL X11DRV_WineGL_InitOpenglInfo(void)
374 {
375     int screen = DefaultScreen(gdi_display);
376     Window win = 0, root = 0;
377     const char *gl_renderer;
378     const char* str;
379     XVisualInfo *vis;
380     GLXContext ctx = NULL;
381     XSetWindowAttributes attr;
382     BOOL ret = FALSE;
383     int attribList[] = {GLX_RGBA, GLX_DOUBLEBUFFER, None};
384
385     attr.override_redirect = True;
386     attr.colormap = None;
387     attr.border_pixel = 0;
388
389     vis = pglXChooseVisual(gdi_display, screen, attribList);
390     if (vis) {
391 #ifdef __i386__
392         WORD old_fs = wine_get_fs();
393         /* Create a GLX Context. Without one we can't query GL information */
394         ctx = pglXCreateContext(gdi_display, vis, None, GL_TRUE);
395         if (wine_get_fs() != old_fs)
396         {
397             wine_set_fs( old_fs );
398             ERR( "%%fs register corrupted, probably broken ATI driver, disabling OpenGL.\n" );
399             ERR( "You need to set the \"UseFastTls\" option to \"2\" in your X config file.\n" );
400             goto done;
401         }
402 #else
403         ctx = pglXCreateContext(gdi_display, vis, None, GL_TRUE);
404 #endif
405     }
406     if (!ctx) goto done;
407
408     root = RootWindow( gdi_display, vis->screen );
409     if (vis->visual != DefaultVisual( gdi_display, vis->screen ))
410         attr.colormap = XCreateColormap( gdi_display, root, vis->visual, AllocNone );
411     if ((win = XCreateWindow( gdi_display, root, -1, -1, 1, 1, 0, vis->depth, InputOutput,
412                               vis->visual, CWBorderPixel | CWOverrideRedirect | CWColormap, &attr )))
413         XMapWindow( gdi_display, win );
414     else
415         win = root;
416
417     if(pglXMakeCurrent(gdi_display, win, ctx) == 0)
418     {
419         ERR_(winediag)( "Unable to activate OpenGL context, most likely your OpenGL drivers haven't been installed correctly\n" );
420         goto done;
421     }
422     gl_renderer = (const char *)opengl_funcs.gl.p_glGetString(GL_RENDERER);
423     WineGLInfo.glVersion = (const char *) opengl_funcs.gl.p_glGetString(GL_VERSION);
424     str = (const char *) opengl_funcs.gl.p_glGetString(GL_EXTENSIONS);
425     WineGLInfo.glExtensions = HeapAlloc(GetProcessHeap(), 0, strlen(str)+1);
426     strcpy(WineGLInfo.glExtensions, str);
427
428     /* Get the common GLX version supported by GLX client and server ( major/minor) */
429     pglXQueryVersion(gdi_display, &WineGLInfo.glxVersion[0], &WineGLInfo.glxVersion[1]);
430
431     WineGLInfo.glxServerVersion = pglXQueryServerString(gdi_display, screen, GLX_VERSION);
432     WineGLInfo.glxServerVendor = pglXQueryServerString(gdi_display, screen, GLX_VENDOR);
433     WineGLInfo.glxServerExtensions = pglXQueryServerString(gdi_display, screen, GLX_EXTENSIONS);
434
435     WineGLInfo.glxClientVersion = pglXGetClientString(gdi_display, GLX_VERSION);
436     WineGLInfo.glxClientVendor = pglXGetClientString(gdi_display, GLX_VENDOR);
437     WineGLInfo.glxClientExtensions = pglXGetClientString(gdi_display, GLX_EXTENSIONS);
438
439     WineGLInfo.glxExtensions = pglXQueryExtensionsString(gdi_display, screen);
440     WineGLInfo.glxDirect = pglXIsDirect(gdi_display, ctx);
441
442     TRACE("GL version             : %s.\n", WineGLInfo.glVersion);
443     TRACE("GL renderer            : %s.\n", gl_renderer);
444     TRACE("GLX version            : %d.%d.\n", WineGLInfo.glxVersion[0], WineGLInfo.glxVersion[1]);
445     TRACE("Server GLX version     : %s.\n", WineGLInfo.glxServerVersion);
446     TRACE("Server GLX vendor:     : %s.\n", WineGLInfo.glxServerVendor);
447     TRACE("Client GLX version     : %s.\n", WineGLInfo.glxClientVersion);
448     TRACE("Client GLX vendor:     : %s.\n", WineGLInfo.glxClientVendor);
449     TRACE("Direct rendering enabled: %s\n", WineGLInfo.glxDirect ? "True" : "False");
450
451     if(!WineGLInfo.glxDirect)
452     {
453         int fd = ConnectionNumber(gdi_display);
454         struct sockaddr_un uaddr;
455         unsigned int uaddrlen = sizeof(struct sockaddr_un);
456
457         /* In general indirect rendering on a local X11 server indicates a driver problem.
458          * Detect a local X11 server by checking whether the X11 socket is a Unix socket.
459          */
460         if(!getsockname(fd, (struct sockaddr *)&uaddr, &uaddrlen) && uaddr.sun_family == AF_UNIX)
461             ERR_(winediag)("Direct rendering is disabled, most likely your OpenGL drivers "
462                            "haven't been installed correctly (using GL renderer %s, version %s).\n",
463                            debugstr_a(gl_renderer), debugstr_a(WineGLInfo.glVersion));
464     }
465     else
466     {
467         /* In general you would expect that if direct rendering is returned, that you receive hardware
468          * accelerated OpenGL rendering. The definition of direct rendering is that rendering is performed
469          * client side without sending all GL commands to X using the GLX protocol. When Mesa falls back to
470          * software rendering, it shows direct rendering.
471          *
472          * Depending on the cause of software rendering a different rendering string is shown. In case Mesa fails
473          * to load a DRI module 'Software Rasterizer' is returned. When Mesa is compiled as a OpenGL reference driver
474          * it shows 'Mesa X11'.
475          */
476         if(!strcmp(gl_renderer, "Software Rasterizer") || !strcmp(gl_renderer, "Mesa X11"))
477             ERR_(winediag)("The Mesa OpenGL driver is using software rendering, most likely your OpenGL "
478                            "drivers haven't been installed correctly (using GL renderer %s, version %s).\n",
479                            debugstr_a(gl_renderer), debugstr_a(WineGLInfo.glVersion));
480     }
481     ret = TRUE;
482
483 done:
484     if(vis) XFree(vis);
485     if(ctx) {
486         pglXMakeCurrent(gdi_display, None, NULL);    
487         pglXDestroyContext(gdi_display, ctx);
488     }
489     if (win != root) XDestroyWindow( gdi_display, win );
490     if (attr.colormap) XFreeColormap( gdi_display, attr.colormap );
491     if (!ret) ERR(" couldn't initialize OpenGL, expect problems\n");
492     return ret;
493 }
494
495 static BOOL has_opengl(void)
496 {
497     static int init_done;
498     static void *opengl_handle;
499
500     char buffer[200];
501     int error_base, event_base;
502     unsigned int i;
503
504     if (init_done) return (opengl_handle != NULL);
505     init_done = 1;
506
507     /* No need to load any other libraries as according to the ABI, libGL should be self-sufficient
508        and include all dependencies */
509     opengl_handle = wine_dlopen(SONAME_LIBGL, RTLD_NOW|RTLD_GLOBAL, buffer, sizeof(buffer));
510     if (opengl_handle == NULL)
511     {
512         ERR( "Failed to load libGL: %s\n", buffer );
513         ERR( "OpenGL support is disabled.\n");
514         return FALSE;
515     }
516
517     for (i = 0; i < sizeof(opengl_func_names)/sizeof(opengl_func_names[0]); i++)
518     {
519         if (!(((void **)&opengl_funcs.gl)[i] = wine_dlsym( opengl_handle, opengl_func_names[i], NULL, 0 )))
520         {
521             ERR( "%s not found in libGL, disabling OpenGL.\n", opengl_func_names[i] );
522             goto failed;
523         }
524     }
525
526     /* redirect some standard OpenGL functions */
527 #define REDIRECT(func) \
528     do { p##func = opengl_funcs.gl.p_##func; opengl_funcs.gl.p_##func = w##func; } while(0)
529     REDIRECT( glFinish );
530     REDIRECT( glFlush );
531 #undef REDIRECT
532
533     pglXGetProcAddressARB = wine_dlsym(opengl_handle, "glXGetProcAddressARB", NULL, 0);
534     if (pglXGetProcAddressARB == NULL) {
535         ERR("Could not find glXGetProcAddressARB in libGL, disabling OpenGL.\n");
536         goto failed;
537     }
538
539 #define LOAD_FUNCPTR(f) do if((p##f = (void*)pglXGetProcAddressARB((const unsigned char*)#f)) == NULL) \
540     { \
541         ERR( "%s not found in libGL, disabling OpenGL.\n", #f ); \
542         goto failed; \
543     } while(0)
544
545     /* GLX 1.0 */
546     LOAD_FUNCPTR(glXChooseVisual);
547     LOAD_FUNCPTR(glXCopyContext);
548     LOAD_FUNCPTR(glXCreateContext);
549     LOAD_FUNCPTR(glXCreateGLXPixmap);
550     LOAD_FUNCPTR(glXGetCurrentContext);
551     LOAD_FUNCPTR(glXGetCurrentDrawable);
552     LOAD_FUNCPTR(glXDestroyContext);
553     LOAD_FUNCPTR(glXDestroyGLXPixmap);
554     LOAD_FUNCPTR(glXGetConfig);
555     LOAD_FUNCPTR(glXIsDirect);
556     LOAD_FUNCPTR(glXMakeCurrent);
557     LOAD_FUNCPTR(glXSwapBuffers);
558     LOAD_FUNCPTR(glXQueryExtension);
559     LOAD_FUNCPTR(glXQueryVersion);
560
561     /* GLX 1.1 */
562     LOAD_FUNCPTR(glXGetClientString);
563     LOAD_FUNCPTR(glXQueryExtensionsString);
564     LOAD_FUNCPTR(glXQueryServerString);
565
566     /* GLX 1.3 */
567     LOAD_FUNCPTR(glXCreatePbuffer);
568     LOAD_FUNCPTR(glXCreateNewContext);
569     LOAD_FUNCPTR(glXDestroyPbuffer);
570     LOAD_FUNCPTR(glXMakeContextCurrent);
571     LOAD_FUNCPTR(glXGetCurrentReadDrawable);
572     LOAD_FUNCPTR(glXGetFBConfigs);
573 #undef LOAD_FUNCPTR
574
575 /* It doesn't matter if these fail. They'll only be used if the driver reports
576    the associated extension is available (and if a driver reports the extension
577    is available but fails to provide the functions, it's quite broken) */
578 #define LOAD_FUNCPTR(f) p##f = pglXGetProcAddressARB((const GLubyte *)#f)
579     /* ARB GLX Extension */
580     LOAD_FUNCPTR(glXCreateContextAttribsARB);
581     /* SGI GLX Extension */
582     LOAD_FUNCPTR(glXSwapIntervalSGI);
583     /* NV GLX Extension */
584     LOAD_FUNCPTR(glXAllocateMemoryNV);
585     LOAD_FUNCPTR(glXFreeMemoryNV);
586 #undef LOAD_FUNCPTR
587
588     if(!X11DRV_WineGL_InitOpenglInfo()) goto failed;
589
590     if (pglXQueryExtension(gdi_display, &error_base, &event_base)) {
591         TRACE("GLX is up and running error_base = %d\n", error_base);
592     } else {
593         ERR( "GLX extension is missing, disabling OpenGL.\n" );
594         goto failed;
595     }
596     gl_hwnd_context = XUniqueContext();
597     gl_pbuffer_context = XUniqueContext();
598
599     /* In case of GLX you have direct and indirect rendering. Most of the time direct rendering is used
600      * as in general only that is hardware accelerated. In some cases like in case of remote X indirect
601      * rendering is used.
602      *
603      * The main problem for our OpenGL code is that we need certain GLX calls but their presence
604      * depends on the reported GLX client / server version and on the client / server extension list.
605      * Those don't have to be the same.
606      *
607      * In general the server GLX information lists the capabilities in case of indirect rendering.
608      * When direct rendering is used, the OpenGL client library is responsible for which GLX calls are
609      * available and in that case the client GLX informat can be used.
610      * OpenGL programs should use the 'intersection' of both sets of information which is advertised
611      * in the GLX version/extension list. When a program does this it works for certain for both
612      * direct and indirect rendering.
613      *
614      * The problem we are having in this area is that ATI's Linux drivers are broken. For some reason
615      * they haven't added some very important GLX extensions like GLX_SGIX_fbconfig to their client
616      * extension list which causes this extension not to be listed. (Wine requires this extension).
617      * ATI advertises a GLX client version of 1.3 which implies that this fbconfig extension among
618      * pbuffers is around.
619      *
620      * In order to provide users of Ati's proprietary drivers with OpenGL support, we need to detect
621      * the ATI drivers and from then on use GLX client information for them.
622      */
623
624     if(glxRequireVersion(3)) {
625         pglXChooseFBConfig = pglXGetProcAddressARB((const GLubyte *) "glXChooseFBConfig");
626         pglXGetFBConfigAttrib = pglXGetProcAddressARB((const GLubyte *) "glXGetFBConfigAttrib");
627         pglXGetVisualFromFBConfig = pglXGetProcAddressARB((const GLubyte *) "glXGetVisualFromFBConfig");
628         pglXQueryDrawable = pglXGetProcAddressARB((const GLubyte *) "glXQueryDrawable");
629     } else if (has_extension( WineGLInfo.glxExtensions, "GLX_SGIX_fbconfig")) {
630         pglXChooseFBConfig = pglXGetProcAddressARB((const GLubyte *) "glXChooseFBConfigSGIX");
631         pglXGetFBConfigAttrib = pglXGetProcAddressARB((const GLubyte *) "glXGetFBConfigAttribSGIX");
632         pglXGetVisualFromFBConfig = pglXGetProcAddressARB((const GLubyte *) "glXGetVisualFromFBConfigSGIX");
633
634         /* The mesa libGL client library seems to forward glXQueryDrawable to the Xserver, so only
635          * enable this function when the Xserver understand GLX 1.3 or newer
636          */
637         pglXQueryDrawable = NULL;
638      } else if(strcmp("ATI", WineGLInfo.glxClientVendor) == 0) {
639         TRACE("Overriding ATI GLX capabilities!\n");
640         pglXChooseFBConfig = pglXGetProcAddressARB((const GLubyte *) "glXChooseFBConfig");
641         pglXGetFBConfigAttrib = pglXGetProcAddressARB((const GLubyte *) "glXGetFBConfigAttrib");
642         pglXGetVisualFromFBConfig = pglXGetProcAddressARB((const GLubyte *) "glXGetVisualFromFBConfig");
643         pglXQueryDrawable = pglXGetProcAddressARB((const GLubyte *) "glXQueryDrawable");
644
645         /* Use client GLX information in case of the ATI drivers. We override the
646          * capabilities over here and not somewhere else as ATI might better their
647          * life in the future. In case they release proper drivers this block of
648          * code won't be called. */
649         WineGLInfo.glxExtensions = WineGLInfo.glxClientExtensions;
650     } else {
651          ERR(" glx_version is %s and GLX_SGIX_fbconfig extension is unsupported. Expect problems.\n", WineGLInfo.glxServerVersion);
652     }
653
654     if (has_extension( WineGLInfo.glxExtensions, "GLX_MESA_copy_sub_buffer")) {
655         pglXCopySubBufferMESA = pglXGetProcAddressARB((const GLubyte *) "glXCopySubBufferMESA");
656     }
657
658     X11DRV_WineGL_LoadExtensions();
659     init_pixel_formats( gdi_display );
660     return TRUE;
661
662 failed:
663     wine_dlclose(opengl_handle, NULL, 0);
664     opengl_handle = NULL;
665     return FALSE;
666 }
667
668 static int describeContext( struct wgl_context *ctx ) {
669     int tmp;
670     int ctx_vis_id;
671     TRACE(" Context %p have (vis:%p):\n", ctx, ctx->vis);
672     pglXGetFBConfigAttrib(gdi_display, ctx->fmt->fbconfig, GLX_FBCONFIG_ID, &tmp);
673     TRACE(" - FBCONFIG_ID 0x%x\n", tmp);
674     pglXGetFBConfigAttrib(gdi_display, ctx->fmt->fbconfig, GLX_VISUAL_ID, &tmp);
675     TRACE(" - VISUAL_ID 0x%x\n", tmp);
676     ctx_vis_id = tmp;
677     return ctx_vis_id;
678 }
679
680 static int ConvertAttribWGLtoGLX(const int* iWGLAttr, int* oGLXAttr, struct wgl_pbuffer* pbuf) {
681   int nAttribs = 0;
682   unsigned cur = 0; 
683   int pop;
684   int drawattrib = 0;
685   int nvfloatattrib = GLX_DONT_CARE;
686   int pixelattrib = GLX_DONT_CARE;
687
688   /* The list of WGL attributes is allowed to be NULL. We don't return here for NULL
689    * because we need to do fixups for GLX_DRAWABLE_TYPE/GLX_RENDER_TYPE/GLX_FLOAT_COMPONENTS_NV. */
690   while (iWGLAttr && 0 != iWGLAttr[cur]) {
691     TRACE("pAttr[%d] = %x\n", cur, iWGLAttr[cur]);
692
693     switch (iWGLAttr[cur]) {
694     case WGL_AUX_BUFFERS_ARB:
695       pop = iWGLAttr[++cur];
696       PUSH2(oGLXAttr, GLX_AUX_BUFFERS, pop);
697       TRACE("pAttr[%d] = GLX_AUX_BUFFERS: %d\n", cur, pop);
698       break;
699     case WGL_COLOR_BITS_ARB:
700       pop = iWGLAttr[++cur];
701       PUSH2(oGLXAttr, GLX_BUFFER_SIZE, pop);
702       TRACE("pAttr[%d] = GLX_BUFFER_SIZE: %d\n", cur, pop);
703       break;
704     case WGL_BLUE_BITS_ARB:
705       pop = iWGLAttr[++cur];
706       PUSH2(oGLXAttr, GLX_BLUE_SIZE, pop);
707       TRACE("pAttr[%d] = GLX_BLUE_SIZE: %d\n", cur, pop);
708       break;
709     case WGL_RED_BITS_ARB:
710       pop = iWGLAttr[++cur];
711       PUSH2(oGLXAttr, GLX_RED_SIZE, pop);
712       TRACE("pAttr[%d] = GLX_RED_SIZE: %d\n", cur, pop);
713       break;
714     case WGL_GREEN_BITS_ARB:
715       pop = iWGLAttr[++cur];
716       PUSH2(oGLXAttr, GLX_GREEN_SIZE, pop);
717       TRACE("pAttr[%d] = GLX_GREEN_SIZE: %d\n", cur, pop);
718       break;
719     case WGL_ALPHA_BITS_ARB:
720       pop = iWGLAttr[++cur];
721       PUSH2(oGLXAttr, GLX_ALPHA_SIZE, pop);
722       TRACE("pAttr[%d] = GLX_ALPHA_SIZE: %d\n", cur, pop);
723       break;
724     case WGL_DEPTH_BITS_ARB:
725       pop = iWGLAttr[++cur];
726       PUSH2(oGLXAttr, GLX_DEPTH_SIZE, pop);
727       TRACE("pAttr[%d] = GLX_DEPTH_SIZE: %d\n", cur, pop);
728       break;
729     case WGL_STENCIL_BITS_ARB:
730       pop = iWGLAttr[++cur];
731       PUSH2(oGLXAttr, GLX_STENCIL_SIZE, pop);
732       TRACE("pAttr[%d] = GLX_STENCIL_SIZE: %d\n", cur, pop);
733       break;
734     case WGL_DOUBLE_BUFFER_ARB:
735       pop = iWGLAttr[++cur];
736       PUSH2(oGLXAttr, GLX_DOUBLEBUFFER, pop);
737       TRACE("pAttr[%d] = GLX_DOUBLEBUFFER: %d\n", cur, pop);
738       break;
739     case WGL_STEREO_ARB:
740       pop = iWGLAttr[++cur];
741       PUSH2(oGLXAttr, GLX_STEREO, pop);
742       TRACE("pAttr[%d] = GLX_STEREO: %d\n", cur, pop);
743       break;
744
745     case WGL_PIXEL_TYPE_ARB:
746       pop = iWGLAttr[++cur];
747       TRACE("pAttr[%d] = WGL_PIXEL_TYPE_ARB: %d\n", cur, pop);
748       switch (pop) {
749       case WGL_TYPE_COLORINDEX_ARB: pixelattrib = GLX_COLOR_INDEX_BIT; break ;
750       case WGL_TYPE_RGBA_ARB: pixelattrib = GLX_RGBA_BIT; break ;
751       /* 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 */
752       case WGL_TYPE_RGBA_FLOAT_ATI: pixelattrib = GLX_RGBA_FLOAT_BIT; break ;
753       case WGL_TYPE_RGBA_UNSIGNED_FLOAT_EXT: pixelattrib = GLX_RGBA_UNSIGNED_FLOAT_BIT_EXT; break ;
754       default:
755         ERR("unexpected PixelType(%x)\n", pop); 
756         pop = 0;
757       }
758       break;
759
760     case WGL_SUPPORT_GDI_ARB:
761       /* This flag is set in a pixel format */
762       pop = iWGLAttr[++cur];
763       TRACE("pAttr[%d] = WGL_SUPPORT_GDI_ARB: %d\n", cur, pop);
764       break;
765
766     case WGL_DRAW_TO_BITMAP_ARB:
767       /* This flag is set in a pixel format */
768       pop = iWGLAttr[++cur];
769       TRACE("pAttr[%d] = WGL_DRAW_TO_BITMAP_ARB: %d\n", cur, pop);
770       break;
771
772     case WGL_DRAW_TO_WINDOW_ARB:
773       pop = iWGLAttr[++cur];
774       TRACE("pAttr[%d] = WGL_DRAW_TO_WINDOW_ARB: %d\n", cur, pop);
775       /* GLX_DRAWABLE_TYPE flags need to be OR'd together. See below. */
776       if (pop) {
777         drawattrib |= GLX_WINDOW_BIT;
778       }
779       break;
780
781     case WGL_DRAW_TO_PBUFFER_ARB:
782       pop = iWGLAttr[++cur];
783       TRACE("pAttr[%d] = WGL_DRAW_TO_PBUFFER_ARB: %d\n", cur, pop);
784       /* GLX_DRAWABLE_TYPE flags need to be OR'd together. See below. */
785       if (pop) {
786         drawattrib |= GLX_PBUFFER_BIT;
787       }
788       break;
789
790     case WGL_ACCELERATION_ARB:
791       /* This flag is set in a pixel format */
792       pop = iWGLAttr[++cur];
793       TRACE("pAttr[%d] = WGL_ACCELERATION_ARB: %d\n", cur, pop);
794       break;
795
796     case WGL_SUPPORT_OPENGL_ARB:
797       pop = iWGLAttr[++cur];
798       /** nothing to do, if we are here, supposing support Accelerated OpenGL */
799       TRACE("pAttr[%d] = WGL_SUPPORT_OPENGL_ARB: %d\n", cur, pop);
800       break;
801
802     case WGL_SWAP_METHOD_ARB:
803       pop = iWGLAttr[++cur];
804       /* For now we ignore this and just return SWAP_EXCHANGE */
805       TRACE("pAttr[%d] = WGL_SWAP_METHOD_ARB: %#x\n", cur, pop);
806       break;
807
808     case WGL_PBUFFER_LARGEST_ARB:
809       pop = iWGLAttr[++cur];
810       PUSH2(oGLXAttr, GLX_LARGEST_PBUFFER, pop);
811       TRACE("pAttr[%d] = GLX_LARGEST_PBUFFER: %x\n", cur, pop);
812       break;
813
814     case WGL_SAMPLE_BUFFERS_ARB:
815       pop = iWGLAttr[++cur];
816       PUSH2(oGLXAttr, GLX_SAMPLE_BUFFERS_ARB, pop);
817       TRACE("pAttr[%d] = GLX_SAMPLE_BUFFERS_ARB: %x\n", cur, pop);
818       break;
819
820     case WGL_SAMPLES_ARB:
821       pop = iWGLAttr[++cur];
822       PUSH2(oGLXAttr, GLX_SAMPLES_ARB, pop);
823       TRACE("pAttr[%d] = GLX_SAMPLES_ARB: %x\n", cur, pop);
824       break;
825
826     case WGL_TEXTURE_FORMAT_ARB:
827     case WGL_TEXTURE_TARGET_ARB:
828     case WGL_MIPMAP_TEXTURE_ARB:
829       TRACE("WGL_render_texture Attributes: %x as %x\n", iWGLAttr[cur], iWGLAttr[cur + 1]);
830       pop = iWGLAttr[++cur];
831       if (NULL == pbuf) {
832         ERR("trying to use GLX_Pbuffer Attributes without Pbuffer (was %x)\n", iWGLAttr[cur]);
833       }
834       if (!use_render_texture_emulation) {
835         if (WGL_NO_TEXTURE_ARB != pop) {
836           ERR("trying to use WGL_render_texture Attributes without support (was %x)\n", iWGLAttr[cur]);
837           return -1; /** error: don't support it */
838         } else {
839           drawattrib |= GLX_PBUFFER_BIT;
840         }
841       }
842       break ;
843     case WGL_FLOAT_COMPONENTS_NV:
844       nvfloatattrib = iWGLAttr[++cur];
845       TRACE("pAttr[%d] = WGL_FLOAT_COMPONENTS_NV: %x\n", cur, nvfloatattrib);
846       break ;
847     case WGL_BIND_TO_TEXTURE_DEPTH_NV:
848     case WGL_BIND_TO_TEXTURE_RGB_ARB:
849     case WGL_BIND_TO_TEXTURE_RGBA_ARB:
850     case WGL_BIND_TO_TEXTURE_RECTANGLE_FLOAT_R_NV:
851     case WGL_BIND_TO_TEXTURE_RECTANGLE_FLOAT_RG_NV:
852     case WGL_BIND_TO_TEXTURE_RECTANGLE_FLOAT_RGB_NV:
853     case WGL_BIND_TO_TEXTURE_RECTANGLE_FLOAT_RGBA_NV:
854       pop = iWGLAttr[++cur];
855       /** cannot be converted, see direct handling on 
856        *   - wglGetPixelFormatAttribivARB
857        *  TODO: wglChoosePixelFormat
858        */
859       break ;
860     case WGL_FRAMEBUFFER_SRGB_CAPABLE_EXT:
861       pop = iWGLAttr[++cur];
862       PUSH2(oGLXAttr, GLX_FRAMEBUFFER_SRGB_CAPABLE_EXT, pop);
863       TRACE("pAttr[%d] = GLX_FRAMEBUFFER_SRGB_CAPABLE_EXT: %x\n", cur, pop);
864       break ;
865
866     case WGL_TYPE_RGBA_UNSIGNED_FLOAT_EXT:
867       pop = iWGLAttr[++cur];
868       PUSH2(oGLXAttr, GLX_RGBA_UNSIGNED_FLOAT_TYPE_EXT, pop);
869       TRACE("pAttr[%d] = GLX_RGBA_UNSIGNED_FLOAT_TYPE_EXT: %x\n", cur, pop);
870       break ;
871     default:
872       FIXME("unsupported %x WGL Attribute\n", iWGLAttr[cur]);
873       break;
874     }
875     ++cur;
876   }
877
878   /* By default glXChooseFBConfig defaults to GLX_WINDOW_BIT. wglChoosePixelFormatARB searches through
879    * all formats. Unless drawattrib is set to a non-zero value override it with GLX_DONT_CARE, so that
880    * pixmap and pbuffer formats appear as well. */
881   if (!drawattrib) drawattrib = GLX_DONT_CARE;
882   PUSH2(oGLXAttr, GLX_DRAWABLE_TYPE, drawattrib);
883   TRACE("pAttr[?] = GLX_DRAWABLE_TYPE: %#x\n", drawattrib);
884
885   /* By default glXChooseFBConfig uses GLX_RGBA_BIT as the default value. Since wglChoosePixelFormatARB
886    * searches in all formats we have to do the same. For this reason we set GLX_RENDER_TYPE to
887    * GLX_DONT_CARE unless it is overridden. */
888   PUSH2(oGLXAttr, GLX_RENDER_TYPE, pixelattrib);
889   TRACE("pAttr[?] = GLX_RENDER_TYPE: %#x\n", pixelattrib);
890
891   /* Set GLX_FLOAT_COMPONENTS_NV all the time */
892   if (has_extension(WineGLInfo.glxExtensions, "GLX_NV_float_buffer")) {
893     PUSH2(oGLXAttr, GLX_FLOAT_COMPONENTS_NV, nvfloatattrib);
894     TRACE("pAttr[?] = GLX_FLOAT_COMPONENTS_NV: %#x\n", nvfloatattrib);
895   }
896
897   return nAttribs;
898 }
899
900 static int get_render_type_from_fbconfig(Display *display, GLXFBConfig fbconfig)
901 {
902     int render_type=0, render_type_bit;
903     pglXGetFBConfigAttrib(display, fbconfig, GLX_RENDER_TYPE, &render_type_bit);
904     switch(render_type_bit)
905     {
906         case GLX_RGBA_BIT:
907             render_type = GLX_RGBA_TYPE;
908             break;
909         case GLX_COLOR_INDEX_BIT:
910             render_type = GLX_COLOR_INDEX_TYPE;
911             break;
912         case GLX_RGBA_FLOAT_BIT:
913             render_type = GLX_RGBA_FLOAT_TYPE;
914             break;
915         case GLX_RGBA_UNSIGNED_FLOAT_BIT_EXT:
916             render_type = GLX_RGBA_UNSIGNED_FLOAT_TYPE_EXT;
917             break;
918         default:
919             ERR("Unknown render_type: %x\n", render_type_bit);
920     }
921     return render_type;
922 }
923
924 /* Check whether a fbconfig is suitable for Windows-style bitmap rendering */
925 static BOOL check_fbconfig_bitmap_capability(Display *display, GLXFBConfig fbconfig)
926 {
927     int dbuf, value;
928     pglXGetFBConfigAttrib(display, fbconfig, GLX_DOUBLEBUFFER, &dbuf);
929     pglXGetFBConfigAttrib(gdi_display, fbconfig, GLX_DRAWABLE_TYPE, &value);
930
931     /* Windows only supports bitmap rendering on single buffered formats, further the fbconfig needs to have
932      * the GLX_PIXMAP_BIT set. */
933     return !dbuf && (value & GLX_PIXMAP_BIT);
934 }
935
936 static void init_pixel_formats( Display *display )
937 {
938     struct wgl_pixel_format *list;
939     int size = 0, onscreen_size = 0;
940     int fmt_id, nCfgs, i, run, bmp_formats;
941     GLXFBConfig* cfgs;
942     XVisualInfo *visinfo;
943
944     cfgs = pglXGetFBConfigs(display, DefaultScreen(display), &nCfgs);
945     if (NULL == cfgs || 0 == nCfgs) {
946         if(cfgs != NULL) XFree(cfgs);
947         ERR("glXChooseFBConfig returns NULL\n");
948         return;
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(*list));
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].fbconfig = cfgs[i];
994                 list[size].fmt_id = fmt_id;
995                 list[size].render_type = get_render_type_from_fbconfig(display, cfgs[i]);
996                 list[size].dwFlags = 0;
997                 size++;
998                 onscreen_size++;
999
1000                 /* Clone a format if it is bitmap capable for indirect rendering to bitmaps */
1001                 if(check_fbconfig_bitmap_capability(display, cfgs[i]))
1002                 {
1003                     TRACE("Found bitmap capable format FBCONFIG_ID 0x%x corresponding to iPixelFormat %d at GLX index %d\n", fmt_id, size+1, i);
1004                     list[size].fbconfig = cfgs[i];
1005                     list[size].fmt_id = fmt_id;
1006                     list[size].render_type = get_render_type_from_fbconfig(display, cfgs[i]);
1007                     list[size].dwFlags = PFD_DRAW_TO_BITMAP | PFD_SUPPORT_GDI | PFD_GENERIC_FORMAT;
1008                     size++;
1009                     onscreen_size++;
1010                 }
1011             } else if(run && !visinfo) {
1012                 int window_drawable=0;
1013                 pglXGetFBConfigAttrib(gdi_display, cfgs[i], GLX_DRAWABLE_TYPE, &window_drawable);
1014
1015                 /* Recent Nvidia drivers and DRI drivers offer window drawable formats without a visual.
1016                  * This are formats like 16-bit rgb on a 24-bit desktop. In order to support these formats
1017                  * onscreen we would have to use glXCreateWindow instead of XCreateWindow. Further it will
1018                  * likely make our child window opengl rendering more complicated since likely you can't use
1019                  * XCopyArea on a GLX Window.
1020                  * For now ignore fbconfigs which are window drawable but lack a visual. */
1021                 if(window_drawable & GLX_WINDOW_BIT)
1022                 {
1023                     TRACE("Skipping FBCONFIG_ID 0x%x as an offscreen format because it is window_drawable\n", fmt_id);
1024                     continue;
1025                 }
1026
1027                 TRACE("Found offscreen format FBCONFIG_ID 0x%x corresponding to iPixelFormat %d at GLX index %d\n", fmt_id, size+1, i);
1028                 list[size].fbconfig = cfgs[i];
1029                 list[size].fmt_id = fmt_id;
1030                 list[size].render_type = get_render_type_from_fbconfig(display, cfgs[i]);
1031                 list[size].dwFlags = 0;
1032                 size++;
1033             }
1034
1035             if (visinfo) XFree(visinfo);
1036         }
1037     }
1038
1039     XFree(cfgs);
1040
1041     pixel_formats = list;
1042     nb_pixel_formats = size;
1043     nb_onscreen_formats = onscreen_size;
1044 }
1045
1046 static inline BOOL is_valid_pixel_format( int format )
1047 {
1048     return format > 0 && format <= nb_pixel_formats;
1049 }
1050
1051 static inline BOOL is_onscreen_pixel_format( int format )
1052 {
1053     return format > 0 && format <= nb_onscreen_formats;
1054 }
1055
1056 /* GLX can advertise dozens of different pixelformats including offscreen and onscreen ones.
1057  * In our WGL implementation we only support a subset of these formats namely the format of
1058  * Wine's main visual and offscreen formats (if they are available).
1059  * This function converts a WGL format to its corresponding GLX one.
1060  */
1061 static const struct wgl_pixel_format *get_pixel_format(Display *display, int iPixelFormat, BOOL AllowOffscreen)
1062 {
1063     /* Check if the pixelformat is valid. Note that it is legal to pass an invalid
1064      * iPixelFormat in case of probing the number of pixelformats.
1065      */
1066     if (is_valid_pixel_format( iPixelFormat ) &&
1067         (is_onscreen_pixel_format( iPixelFormat ) || AllowOffscreen)) {
1068         TRACE("Returning fmt_id=%#x for iPixelFormat=%d\n",
1069               pixel_formats[iPixelFormat-1].fmt_id, iPixelFormat);
1070         return &pixel_formats[iPixelFormat-1];
1071     }
1072     return NULL;
1073 }
1074
1075 static int pixelformat_from_fbconfig_id(XID fbconfig_id)
1076 {
1077     int i;
1078
1079     if (!fbconfig_id) return 0;
1080
1081     for (i = 0; i < nb_pixel_formats; i++)
1082         if (pixel_formats[i].fmt_id == fbconfig_id) return i + 1;
1083
1084     /* This will happen on hwnds without a pixel format set; it's ok */
1085     return 0;
1086 }
1087
1088
1089 /* Mark any allocated context using the glx drawable 'old' to use 'new' */
1090 static void mark_drawable_dirty(Drawable old, Drawable new)
1091 {
1092     struct wgl_context *ctx;
1093
1094     LIST_FOR_EACH_ENTRY( ctx, &context_list, struct wgl_context, entry )
1095     {
1096         if (old == ctx->drawables[0]) {
1097             ctx->drawables[0] = new;
1098             ctx->refresh_drawables = TRUE;
1099         }
1100         if (old == ctx->drawables[1]) {
1101             ctx->drawables[1] = new;
1102             ctx->refresh_drawables = TRUE;
1103         }
1104     }
1105 }
1106
1107 /* Given the current context, make sure its drawable is sync'd */
1108 static inline void sync_context(struct wgl_context *context)
1109 {
1110     EnterCriticalSection( &context_section );
1111     if (context->refresh_drawables) {
1112         if (glxRequireVersion(3))
1113             pglXMakeContextCurrent(gdi_display, context->drawables[0],
1114                                    context->drawables[1], context->ctx);
1115         else
1116             pglXMakeCurrent(gdi_display, context->drawables[0], context->ctx);
1117         context->refresh_drawables = FALSE;
1118     }
1119     LeaveCriticalSection( &context_section );
1120 }
1121
1122 static struct gl_drawable *get_gl_drawable( HWND hwnd, HDC hdc )
1123 {
1124     struct gl_drawable *gl;
1125
1126     EnterCriticalSection( &context_section );
1127     if (hwnd && !XFindContext( gdi_display, (XID)hwnd, gl_hwnd_context, (char **)&gl )) return gl;
1128     if (hdc && !XFindContext( gdi_display, (XID)hdc, gl_pbuffer_context, (char **)&gl )) return gl;
1129     LeaveCriticalSection( &context_section );
1130     return NULL;
1131 }
1132
1133 static void release_gl_drawable( struct gl_drawable *gl )
1134 {
1135     if (gl) LeaveCriticalSection( &context_section );
1136 }
1137
1138 BOOL has_gl_drawable( HWND hwnd )
1139 {
1140     struct gl_drawable *gl;
1141
1142     gl = get_gl_drawable( hwnd, 0 );
1143     release_gl_drawable( gl );
1144     return gl != NULL;
1145 }
1146
1147 static GLXContext create_glxcontext(Display *display, struct wgl_context *context, GLXContext shareList)
1148 {
1149     GLXContext ctx;
1150
1151     /* We use indirect rendering for rendering to bitmaps. See get_formats for a comment about this. */
1152     BOOL indirect = !(context->fmt->dwFlags & PFD_DRAW_TO_BITMAP);
1153
1154     if(context->gl3_context)
1155     {
1156         if(context->numAttribs)
1157             ctx = pglXCreateContextAttribsARB(gdi_display, context->fmt->fbconfig, shareList, indirect, context->attribList);
1158         else
1159             ctx = pglXCreateContextAttribsARB(gdi_display, context->fmt->fbconfig, shareList, indirect, NULL);
1160     }
1161     else if(context->vis)
1162         ctx = pglXCreateContext(gdi_display, context->vis, shareList, indirect);
1163     else /* Create a GLX Context for a pbuffer */
1164         ctx = pglXCreateNewContext(gdi_display, context->fmt->fbconfig, context->fmt->render_type, shareList, TRUE);
1165
1166     return ctx;
1167 }
1168
1169
1170 /***********************************************************************
1171  *              free_gl_drawable
1172  */
1173 static void free_gl_drawable( struct gl_drawable *gl )
1174 {
1175     switch (gl->type)
1176     {
1177     case DC_GL_WINDOW:
1178     case DC_GL_CHILD_WIN:
1179         XDestroyWindow( gdi_display, gl->drawable );
1180         XFreeColormap( gdi_display, gl->colormap );
1181         break;
1182     case DC_GL_PIXMAP_WIN:
1183         pglXDestroyGLXPixmap( gdi_display, gl->drawable );
1184         XFreePixmap( gdi_display, gl->pixmap );
1185         break;
1186     default:
1187         break;
1188     }
1189     if (gl->visual) XFree( gl->visual );
1190     HeapFree( GetProcessHeap(), 0, gl );
1191 }
1192
1193
1194 /***********************************************************************
1195  *              set_win_format
1196  */
1197 BOOL set_win_format( HWND hwnd, XID fbconfig_id )
1198 {
1199     XSetWindowAttributes attrib;
1200     struct gl_drawable *gl, *prev;
1201     int format;
1202
1203     if (!(format = pixelformat_from_fbconfig_id( fbconfig_id ))) return FALSE;
1204
1205     gl = HeapAlloc( GetProcessHeap(), HEAP_ZERO_MEMORY, sizeof(*gl) );
1206     gl->format = &pixel_formats[format - 1];
1207     gl->visual = pglXGetVisualFromFBConfig( gdi_display, gl->format->fbconfig );
1208     if (!gl->visual)
1209     {
1210         HeapFree( GetProcessHeap(), 0, gl );
1211         return FALSE;
1212     }
1213
1214     GetClientRect( hwnd, &gl->rect );
1215     gl->rect.right  = min( max( 1, gl->rect.right ), 65535 );
1216     gl->rect.bottom = min( max( 1, gl->rect.bottom ), 65535 );
1217
1218     if (GetAncestor( hwnd, GA_PARENT ) == GetDesktopWindow())  /* top-level window */
1219     {
1220         Window parent = X11DRV_get_whole_window( hwnd );
1221
1222         gl->type = DC_GL_WINDOW;
1223         gl->colormap = XCreateColormap( gdi_display, root_window, gl->visual->visual,
1224                                         (gl->visual->class == PseudoColor ||
1225                                          gl->visual->class == GrayScale ||
1226                                          gl->visual->class == DirectColor) ? AllocAll : AllocNone );
1227         attrib.colormap = gl->colormap;
1228         attrib.bit_gravity = NorthWestGravity;
1229         attrib.win_gravity = NorthWestGravity;
1230         attrib.backing_store = NotUseful;
1231         /* put the initial rect outside of the window, it will be moved into place by SetWindowPos */
1232         OffsetRect( &gl->rect, gl->rect.right, gl->rect.bottom );
1233         if (parent)
1234             gl->drawable = XCreateWindow( gdi_display, parent, gl->rect.left, gl->rect.top,
1235                                           gl->rect.right - gl->rect.left, gl->rect.bottom - gl->rect.top,
1236                                           0, screen_depth, InputOutput, gl->visual->visual,
1237                                           CWBitGravity | CWWinGravity | CWBackingStore | CWColormap,
1238                                           &attrib );
1239         if (gl->drawable)
1240             XMapWindow( gdi_display, gl->drawable );
1241         else
1242             XFreeColormap( gdi_display, gl->colormap );
1243     }
1244 #ifdef SONAME_LIBXCOMPOSITE
1245     else if(usexcomposite)
1246     {
1247         static Window dummy_parent;
1248
1249         attrib.override_redirect = True;
1250         if (!dummy_parent)
1251         {
1252             dummy_parent = XCreateWindow( gdi_display, root_window, -1, -1, 1, 1, 0, screen_depth,
1253                                          InputOutput, visual, CWOverrideRedirect, &attrib );
1254             XMapWindow( gdi_display, dummy_parent );
1255         }
1256         gl->colormap = XCreateColormap(gdi_display, dummy_parent, gl->visual->visual,
1257                                        (gl->visual->class == PseudoColor ||
1258                                         gl->visual->class == GrayScale ||
1259                                         gl->visual->class == DirectColor) ?
1260                                        AllocAll : AllocNone);
1261         attrib.colormap = gl->colormap;
1262         XInstallColormap(gdi_display, attrib.colormap);
1263
1264         gl->type = DC_GL_CHILD_WIN;
1265         gl->drawable = XCreateWindow( gdi_display, dummy_parent, 0, 0,
1266                                       gl->rect.right - gl->rect.left, gl->rect.bottom - gl->rect.top,
1267                                       0, gl->visual->depth, InputOutput, gl->visual->visual,
1268                                       CWColormap | CWOverrideRedirect, &attrib );
1269         if (gl->drawable)
1270         {
1271             pXCompositeRedirectWindow(gdi_display, gl->drawable, CompositeRedirectManual);
1272             XMapWindow(gdi_display, gl->drawable);
1273         }
1274         else XFreeColormap( gdi_display, gl->colormap );
1275     }
1276 #endif
1277     else
1278     {
1279         WARN("XComposite is not available, using GLXPixmap hack\n");
1280
1281         gl->type = DC_GL_PIXMAP_WIN;
1282         gl->pixmap = XCreatePixmap( gdi_display, root_window,
1283                                     gl->rect.right - gl->rect.left, gl->rect.bottom - gl->rect.top,
1284                                     gl->visual->depth );
1285         if (gl->pixmap)
1286         {
1287             gl->drawable = pglXCreateGLXPixmap( gdi_display, gl->visual, gl->pixmap );
1288             if (!gl->drawable) XFreePixmap( gdi_display, gl->pixmap );
1289         }
1290     }
1291
1292     if (!gl->drawable)
1293     {
1294         XFree( gl->visual );
1295         HeapFree( GetProcessHeap(), 0, gl );
1296         return FALSE;
1297     }
1298
1299     TRACE("Created GL drawable 0x%lx, using FBConfigID 0x%lx\n", gl->drawable, fbconfig_id);
1300
1301     XFlush( gdi_display );
1302
1303     EnterCriticalSection( &context_section );
1304     if (!XFindContext( gdi_display, (XID)hwnd, gl_hwnd_context, (char **)&prev ))
1305         free_gl_drawable( prev );
1306     XSaveContext( gdi_display, (XID)hwnd, gl_hwnd_context, (char *)gl );
1307     LeaveCriticalSection( &context_section );
1308
1309     /* force DCE invalidation */
1310     SetWindowPos( hwnd, 0, 0, 0, 0, 0,
1311                   SWP_NOACTIVATE | SWP_NOZORDER | SWP_NOSIZE | SWP_NOMOVE |
1312                   SWP_NOREDRAW | SWP_DEFERERASE | SWP_NOSENDCHANGING | SWP_STATECHANGED);
1313     return TRUE;
1314 }
1315
1316 /***********************************************************************
1317  *              sync_gl_drawable
1318  */
1319 void sync_gl_drawable( HWND hwnd, const RECT *visible_rect, const RECT *client_rect )
1320 {
1321     struct gl_drawable *gl;
1322     Drawable glxp;
1323     Pixmap pix;
1324     int mask = 0;
1325     XWindowChanges changes;
1326
1327     changes.x      = client_rect->left - visible_rect->left;
1328     changes.y      = client_rect->top - visible_rect->top;
1329     changes.width  = min( max( 1, client_rect->right - client_rect->left ), 65535 );
1330     changes.height = min( max( 1, client_rect->bottom - client_rect->top ), 65535 );
1331
1332     if (!(gl = get_gl_drawable( hwnd, 0 ))) return;
1333
1334     if (changes.width  != gl->rect.right - gl->rect.left) mask |= CWWidth;
1335     if (changes.height != gl->rect.bottom - gl->rect.top) mask |= CWHeight;
1336
1337     TRACE( "setting drawable %lx pos %d,%d,%dx%d\n",
1338            gl->drawable, changes.x, changes.y, changes.width, changes.height );
1339
1340     switch (gl->type)
1341     {
1342     case DC_GL_WINDOW:
1343         if (changes.x != gl->rect.left) mask |= CWX;
1344         if (changes.y != gl->rect.top)  mask |= CWY;
1345         /* fallthrough */
1346     case DC_GL_CHILD_WIN:
1347         if (mask) XConfigureWindow( gdi_display, gl->drawable, mask, &changes );
1348         break;
1349     case DC_GL_PIXMAP_WIN:
1350         if (!mask) break;
1351         pix = XCreatePixmap(gdi_display, root_window, changes.width, changes.height, gl->visual->depth);
1352         if (!pix) goto done;
1353         glxp = pglXCreateGLXPixmap(gdi_display, gl->visual, pix);
1354         if (!glxp)
1355         {
1356             XFreePixmap(gdi_display, pix);
1357             goto done;
1358         }
1359         mark_drawable_dirty(gl->drawable, glxp);
1360         XFlush( gdi_display );
1361
1362         XFreePixmap(gdi_display, gl->pixmap);
1363         pglXDestroyGLXPixmap(gdi_display, gl->drawable);
1364         TRACE( "Recreated GL drawable %lx to replace %lx\n", glxp, gl->drawable );
1365
1366         gl->pixmap = pix;
1367         gl->drawable = glxp;
1368         break;
1369     default:
1370         break;
1371     }
1372     SetRect( &gl->rect, changes.x, changes.y, changes.x + changes.width, changes.y + changes.height );
1373 done:
1374     release_gl_drawable( gl );
1375 }
1376
1377 /***********************************************************************
1378  *              destroy_gl_drawable
1379  */
1380 void destroy_gl_drawable( HWND hwnd )
1381 {
1382     struct gl_drawable *gl;
1383
1384     EnterCriticalSection( &context_section );
1385     if (!XFindContext( gdi_display, (XID)hwnd, gl_hwnd_context, (char **)&gl ))
1386     {
1387         XDeleteContext( gdi_display, (XID)hwnd, gl_hwnd_context );
1388         free_gl_drawable( gl );
1389     }
1390     LeaveCriticalSection( &context_section );
1391 }
1392
1393
1394 /**
1395  * glxdrv_DescribePixelFormat
1396  *
1397  * Get the pixel-format descriptor associated to the given id
1398  */
1399 static int glxdrv_wglDescribePixelFormat( HDC hdc, int iPixelFormat,
1400                                           UINT nBytes, PIXELFORMATDESCRIPTOR *ppfd)
1401 {
1402   /*XVisualInfo *vis;*/
1403   int value;
1404   int rb,gb,bb,ab;
1405   const struct wgl_pixel_format *fmt;
1406
1407   if (!has_opengl()) return 0;
1408
1409   TRACE("(%p,%d,%d,%p)\n", hdc, iPixelFormat, nBytes, ppfd);
1410
1411   if (!ppfd) return nb_onscreen_formats;
1412
1413   /* 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 */
1414   fmt = get_pixel_format(gdi_display, iPixelFormat, FALSE /* Offscreen */);
1415   if (!fmt) {
1416       WARN("unexpected format %d\n", iPixelFormat);
1417       return 0;
1418   }
1419
1420   if (nBytes < sizeof(PIXELFORMATDESCRIPTOR)) {
1421     ERR("Wrong structure size !\n");
1422     /* Should set error */
1423     return 0;
1424   }
1425
1426   memset(ppfd, 0, sizeof(PIXELFORMATDESCRIPTOR));
1427   ppfd->nSize = sizeof(PIXELFORMATDESCRIPTOR);
1428   ppfd->nVersion = 1;
1429
1430   /* These flags are always the same... */
1431   ppfd->dwFlags = PFD_SUPPORT_OPENGL;
1432   /* Now the flags extracted from the Visual */
1433
1434   pglXGetFBConfigAttrib(gdi_display, fmt->fbconfig, GLX_DRAWABLE_TYPE, &value);
1435   if(value & GLX_WINDOW_BIT)
1436       ppfd->dwFlags |= PFD_DRAW_TO_WINDOW;
1437
1438   /* On Windows bitmap rendering is only offered using the GDI Software renderer. We reserve some formats (see get_formats for more info)
1439    * for bitmap rendering since we require indirect rendering for this. Further pixel format logs of a GeforceFX, Geforce8800GT, Radeon HD3400 and a
1440    * 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
1441    * offered the GDI bit either. */
1442   ppfd->dwFlags |= fmt->dwFlags & (PFD_DRAW_TO_BITMAP | PFD_SUPPORT_GDI);
1443
1444   /* PFD_GENERIC_FORMAT - gdi software rendering
1445    * PFD_GENERIC_ACCELERATED - some parts are accelerated by a display driver (MCD e.g. 3dfx minigl)
1446    * none set - full hardware accelerated by a ICD
1447    *
1448    * We only set PFD_GENERIC_FORMAT on bitmap formats (see get_formats) as that's what ATI and Nvidia Windows drivers do  */
1449   ppfd->dwFlags |= fmt->dwFlags & (PFD_GENERIC_FORMAT | PFD_GENERIC_ACCELERATED);
1450
1451   pglXGetFBConfigAttrib(gdi_display, fmt->fbconfig, GLX_DOUBLEBUFFER, &value);
1452   if (value) {
1453       ppfd->dwFlags |= PFD_DOUBLEBUFFER;
1454       ppfd->dwFlags &= ~PFD_SUPPORT_GDI;
1455   }
1456   pglXGetFBConfigAttrib(gdi_display, fmt->fbconfig, GLX_STEREO, &value); if (value) ppfd->dwFlags |= PFD_STEREO;
1457
1458   /* Pixel type */
1459   pglXGetFBConfigAttrib(gdi_display, fmt->fbconfig, GLX_RENDER_TYPE, &value);
1460   if (value & GLX_RGBA_BIT)
1461     ppfd->iPixelType = PFD_TYPE_RGBA;
1462   else
1463     ppfd->iPixelType = PFD_TYPE_COLORINDEX;
1464
1465   /* Color bits */
1466   pglXGetFBConfigAttrib(gdi_display, fmt->fbconfig, GLX_BUFFER_SIZE, &value);
1467   ppfd->cColorBits = value;
1468
1469   /* Red, green, blue and alpha bits / shifts */
1470   if (ppfd->iPixelType == PFD_TYPE_RGBA) {
1471     pglXGetFBConfigAttrib(gdi_display, fmt->fbconfig, GLX_RED_SIZE, &rb);
1472     pglXGetFBConfigAttrib(gdi_display, fmt->fbconfig, GLX_GREEN_SIZE, &gb);
1473     pglXGetFBConfigAttrib(gdi_display, fmt->fbconfig, GLX_BLUE_SIZE, &bb);
1474     pglXGetFBConfigAttrib(gdi_display, fmt->fbconfig, GLX_ALPHA_SIZE, &ab);
1475
1476     ppfd->cRedBits = rb;
1477     ppfd->cRedShift = gb + bb + ab;
1478     ppfd->cBlueBits = bb;
1479     ppfd->cBlueShift = ab;
1480     ppfd->cGreenBits = gb;
1481     ppfd->cGreenShift = bb + ab;
1482     ppfd->cAlphaBits = ab;
1483     ppfd->cAlphaShift = 0;
1484   } else {
1485     ppfd->cRedBits = 0;
1486     ppfd->cRedShift = 0;
1487     ppfd->cBlueBits = 0;
1488     ppfd->cBlueShift = 0;
1489     ppfd->cGreenBits = 0;
1490     ppfd->cGreenShift = 0;
1491     ppfd->cAlphaBits = 0;
1492     ppfd->cAlphaShift = 0;
1493   }
1494
1495   /* Accum RGBA bits */
1496   pglXGetFBConfigAttrib(gdi_display, fmt->fbconfig, GLX_ACCUM_RED_SIZE, &rb);
1497   pglXGetFBConfigAttrib(gdi_display, fmt->fbconfig, GLX_ACCUM_GREEN_SIZE, &gb);
1498   pglXGetFBConfigAttrib(gdi_display, fmt->fbconfig, GLX_ACCUM_BLUE_SIZE, &bb);
1499   pglXGetFBConfigAttrib(gdi_display, fmt->fbconfig, GLX_ACCUM_ALPHA_SIZE, &ab);
1500
1501   ppfd->cAccumBits = rb+gb+bb+ab;
1502   ppfd->cAccumRedBits = rb;
1503   ppfd->cAccumGreenBits = gb;
1504   ppfd->cAccumBlueBits = bb;
1505   ppfd->cAccumAlphaBits = ab;
1506
1507   /* Aux bits */
1508   pglXGetFBConfigAttrib(gdi_display, fmt->fbconfig, GLX_AUX_BUFFERS, &value);
1509   ppfd->cAuxBuffers = value;
1510
1511   /* Depth bits */
1512   pglXGetFBConfigAttrib(gdi_display, fmt->fbconfig, GLX_DEPTH_SIZE, &value);
1513   ppfd->cDepthBits = value;
1514
1515   /* stencil bits */
1516   pglXGetFBConfigAttrib(gdi_display, fmt->fbconfig, GLX_STENCIL_SIZE, &value);
1517   ppfd->cStencilBits = value;
1518
1519   ppfd->iLayerType = PFD_MAIN_PLANE;
1520
1521   if (TRACE_ON(wgl)) {
1522     dump_PIXELFORMATDESCRIPTOR(ppfd);
1523   }
1524
1525   return nb_onscreen_formats;
1526 }
1527
1528 /***********************************************************************
1529  *              glxdrv_wglGetPixelFormat
1530  */
1531 static int glxdrv_wglGetPixelFormat( HDC hdc )
1532 {
1533     struct gl_drawable *gl;
1534     int ret = 0;
1535
1536     if ((gl = get_gl_drawable( WindowFromDC( hdc ), hdc )))
1537     {
1538         ret = gl->format - pixel_formats + 1;
1539         /* Offscreen formats can't be used with traditional WGL calls.
1540          * As has been verified on Windows GetPixelFormat doesn't fail but returns iPixelFormat=1. */
1541         if (!is_onscreen_pixel_format( ret )) ret = 1;
1542         release_gl_drawable( gl );
1543     }
1544     TRACE( "%p -> %d\n", hdc, ret );
1545     return ret;
1546 }
1547
1548 /***********************************************************************
1549  *              glxdrv_wglSetPixelFormat
1550  */
1551 static BOOL glxdrv_wglSetPixelFormat( HDC hdc, int iPixelFormat, const PIXELFORMATDESCRIPTOR *ppfd )
1552 {
1553     const struct wgl_pixel_format *fmt;
1554     int value;
1555     struct gl_drawable *gl;
1556     HWND hwnd = WindowFromDC( hdc );
1557
1558     TRACE("(%p,%d,%p)\n", hdc, iPixelFormat, ppfd);
1559
1560     if (!hwnd || hwnd == GetDesktopWindow())
1561     {
1562         WARN( "not a proper window DC %p/%p\n", hdc, hwnd );
1563         return FALSE;
1564     }
1565
1566     /* Check if iPixelFormat is in our list of supported formats to see if it is supported. */
1567     fmt = get_pixel_format(gdi_display, iPixelFormat, FALSE /* Offscreen */);
1568     if(!fmt) {
1569         ERR("Invalid iPixelFormat: %d\n", iPixelFormat);
1570         return FALSE;
1571     }
1572
1573     pglXGetFBConfigAttrib(gdi_display, fmt->fbconfig, GLX_DRAWABLE_TYPE, &value);
1574     if (!(value & GLX_WINDOW_BIT))
1575     {
1576         WARN("Pixel format %d is not compatible for window rendering\n", iPixelFormat);
1577         return FALSE;
1578     }
1579
1580     if ((gl = get_gl_drawable( hwnd, hdc )))
1581     {
1582         int prev = gl->format - pixel_formats + 1;
1583         release_gl_drawable( gl );
1584         return prev == iPixelFormat;  /* cannot change it if already set */
1585     }
1586
1587     if(!SendMessageW(hwnd, WM_X11DRV_SET_WIN_FORMAT, fmt->fmt_id, 0)) {
1588         ERR("Couldn't set format of the window, returning failure\n");
1589         return FALSE;
1590     }
1591     /* physDev->current_pf will be set by the DCE update */
1592
1593     if (TRACE_ON(wgl)) {
1594         int gl_test = 0;
1595
1596         gl_test = pglXGetFBConfigAttrib(gdi_display, fmt->fbconfig, GLX_FBCONFIG_ID, &value);
1597         if (gl_test) {
1598            ERR("Failed to retrieve FBCONFIG_ID from GLXFBConfig, expect problems.\n");
1599         } else {
1600             TRACE(" FBConfig have :\n");
1601             TRACE(" - FBCONFIG_ID   0x%x\n", value);
1602             pglXGetFBConfigAttrib(gdi_display, fmt->fbconfig, GLX_VISUAL_ID, &value);
1603             TRACE(" - VISUAL_ID     0x%x\n", value);
1604             pglXGetFBConfigAttrib(gdi_display, fmt->fbconfig, GLX_DRAWABLE_TYPE, &value);
1605             TRACE(" - DRAWABLE_TYPE 0x%x\n", value);
1606         }
1607     }
1608     return TRUE;
1609 }
1610
1611 /***********************************************************************
1612  *              glxdrv_wglCopyContext
1613  */
1614 static BOOL glxdrv_wglCopyContext(struct wgl_context *src, struct wgl_context *dst, UINT mask)
1615 {
1616     TRACE("%p -> %p mask %#x\n", src, dst, mask);
1617
1618     pglXCopyContext(gdi_display, src->ctx, dst->ctx, mask);
1619
1620     /* As opposed to wglCopyContext, glXCopyContext doesn't return anything, so hopefully we passed */
1621     return TRUE;
1622 }
1623
1624 /***********************************************************************
1625  *              glxdrv_wglCreateContext
1626  */
1627 static struct wgl_context *glxdrv_wglCreateContext( HDC hdc )
1628 {
1629     struct wgl_context *ret = NULL;
1630     struct gl_drawable *gl;
1631
1632     if (!(gl = get_gl_drawable( WindowFromDC( hdc ), hdc )))
1633     {
1634         SetLastError( ERROR_INVALID_PIXEL_FORMAT );
1635         return NULL;
1636     }
1637
1638     if ((ret = HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, sizeof(*ret))))
1639     {
1640         ret->hdc = hdc;
1641         ret->fmt = gl->format;
1642         ret->vis = pglXGetVisualFromFBConfig(gdi_display, gl->format->fbconfig);
1643         ret->ctx = create_glxcontext(gdi_display, ret, NULL);
1644         list_add_head( &context_list, &ret->entry );
1645     }
1646     release_gl_drawable( gl );
1647     TRACE( "%p -> %p\n", hdc, ret );
1648     return ret;
1649 }
1650
1651 /***********************************************************************
1652  *              glxdrv_wglDeleteContext
1653  */
1654 static void glxdrv_wglDeleteContext(struct wgl_context *ctx)
1655 {
1656     TRACE("(%p)\n", ctx);
1657
1658     EnterCriticalSection( &context_section );
1659     list_remove( &ctx->entry );
1660     LeaveCriticalSection( &context_section );
1661
1662     if (ctx->ctx) pglXDestroyContext( gdi_display, ctx->ctx );
1663     if (ctx->vis) XFree( ctx->vis );
1664     HeapFree( GetProcessHeap(), 0, ctx );
1665 }
1666
1667 /***********************************************************************
1668  *              glxdrv_wglGetProcAddress
1669  */
1670 static PROC glxdrv_wglGetProcAddress(LPCSTR lpszProc)
1671 {
1672     if (!strncmp(lpszProc, "wgl", 3)) return NULL;
1673     return pglXGetProcAddressARB((const GLubyte*)lpszProc);
1674 }
1675
1676 /***********************************************************************
1677  *              glxdrv_wglMakeCurrent
1678  */
1679 static BOOL glxdrv_wglMakeCurrent(HDC hdc, struct wgl_context *ctx)
1680 {
1681     BOOL ret = FALSE;
1682     struct gl_drawable *gl;
1683
1684     TRACE("(%p,%p)\n", hdc, ctx);
1685
1686     if (!ctx)
1687     {
1688         pglXMakeCurrent(gdi_display, None, NULL);
1689         NtCurrentTeb()->glContext = NULL;
1690         return TRUE;
1691     }
1692
1693     if ((gl = get_gl_drawable( WindowFromDC( hdc ), hdc )))
1694     {
1695         if (ctx->fmt != gl->format)
1696         {
1697             WARN( "mismatched pixel format hdc %p %p ctx %p %p\n", hdc, gl->format, ctx, ctx->fmt );
1698             SetLastError( ERROR_INVALID_PIXEL_FORMAT );
1699             goto done;
1700         }
1701
1702         if (TRACE_ON(wgl)) {
1703             describeContext(ctx);
1704             TRACE("hdc %p drawable %lx fmt %p ctx %p\n", hdc, gl->drawable, gl->format, ctx->ctx );
1705         }
1706
1707         ret = pglXMakeCurrent(gdi_display, gl->drawable, ctx->ctx);
1708         if (ret)
1709         {
1710             NtCurrentTeb()->glContext = ctx;
1711             ctx->has_been_current = TRUE;
1712             ctx->hdc = hdc;
1713             ctx->drawables[0] = gl->drawable;
1714             ctx->drawables[1] = gl->drawable;
1715             ctx->refresh_drawables = FALSE;
1716             goto done;
1717         }
1718     }
1719     SetLastError( ERROR_INVALID_HANDLE );
1720
1721 done:
1722     release_gl_drawable( gl );
1723     TRACE( "%p,%p returning %d\n", hdc, ctx, ret );
1724     return ret;
1725 }
1726
1727 /***********************************************************************
1728  *              X11DRV_wglMakeContextCurrentARB
1729  */
1730 static BOOL X11DRV_wglMakeContextCurrentARB( HDC draw_hdc, HDC read_hdc, struct wgl_context *ctx )
1731 {
1732     BOOL ret = FALSE;
1733     struct gl_drawable *draw_gl, *read_gl = NULL;
1734
1735     TRACE("(%p,%p,%p)\n", draw_hdc, read_hdc, ctx);
1736
1737     if (!ctx)
1738     {
1739         pglXMakeCurrent(gdi_display, None, NULL);
1740         NtCurrentTeb()->glContext = NULL;
1741         return TRUE;
1742     }
1743
1744     if (!pglXMakeContextCurrent) return FALSE;
1745
1746     if ((draw_gl = get_gl_drawable( WindowFromDC( draw_hdc ), draw_hdc )))
1747     {
1748         read_gl = get_gl_drawable( WindowFromDC( read_hdc ), read_hdc );
1749         ret = pglXMakeContextCurrent(gdi_display, draw_gl->drawable,
1750                                      read_gl ? read_gl->drawable : 0, ctx->ctx);
1751         if (ret)
1752         {
1753             ctx->has_been_current = TRUE;
1754             ctx->hdc = draw_hdc;
1755             ctx->drawables[0] = draw_gl->drawable;
1756             ctx->drawables[1] = read_gl ? read_gl->drawable : 0;
1757             ctx->refresh_drawables = FALSE;
1758             NtCurrentTeb()->glContext = ctx;
1759             goto done;
1760         }
1761     }
1762     SetLastError( ERROR_INVALID_HANDLE );
1763 done:
1764     release_gl_drawable( read_gl );
1765     release_gl_drawable( draw_gl );
1766     TRACE( "%p,%p,%p returning %d\n", draw_hdc, read_hdc, ctx, ret );
1767     return ret;
1768 }
1769
1770 /***********************************************************************
1771  *              glxdrv_wglShareLists
1772  */
1773 static BOOL glxdrv_wglShareLists(struct wgl_context *org, struct wgl_context *dest)
1774 {
1775     TRACE("(%p, %p)\n", org, dest);
1776
1777     /* Sharing of display lists works differently in GLX and WGL. In case of GLX it is done
1778      * at context creation time but in case of WGL it is done using wglShareLists.
1779      * In the past we tried to emulate wglShareLists by delaying GLX context creation until
1780      * either a wglMakeCurrent or wglShareLists. This worked fine for most apps but it causes
1781      * issues for OpenGL 3 because there wglCreateContextAttribsARB can fail in a lot of cases,
1782      * so there delaying context creation doesn't work.
1783      *
1784      * The new approach is to create a GLX context in wglCreateContext / wglCreateContextAttribsARB
1785      * and when a program requests sharing we recreate the destination context if it hasn't been made
1786      * current or when it hasn't shared display lists before.
1787      */
1788
1789     if((org->has_been_current && dest->has_been_current) || dest->has_been_current)
1790     {
1791         ERR("Could not share display lists, one of the contexts has been current already !\n");
1792         return FALSE;
1793     }
1794     else if(dest->sharing)
1795     {
1796         ERR("Could not share display lists because hglrc2 has already shared lists before\n");
1797         return FALSE;
1798     }
1799     else
1800     {
1801         describeContext(org);
1802         describeContext(dest);
1803
1804         /* Re-create the GLX context and share display lists */
1805         pglXDestroyContext(gdi_display, dest->ctx);
1806         dest->ctx = create_glxcontext(gdi_display, dest, org->ctx);
1807         TRACE(" re-created an OpenGL context (%p) for Wine context %p sharing lists with OpenGL ctx %p\n", dest->ctx, dest, org->ctx);
1808
1809         org->sharing = TRUE;
1810         dest->sharing = TRUE;
1811         return TRUE;
1812     }
1813     return FALSE;
1814 }
1815
1816 static void flush_gl_drawable( struct glx_physdev *physdev )
1817 {
1818     RECT rect;
1819     int w = physdev->x11dev->dc_rect.right - physdev->x11dev->dc_rect.left;
1820     int h = physdev->x11dev->dc_rect.bottom - physdev->x11dev->dc_rect.top;
1821     Drawable src = physdev->drawable;
1822
1823     if (w <= 0 || h <= 0) return;
1824
1825     switch (physdev->type)
1826     {
1827     case DC_GL_PIXMAP_WIN:
1828         src = physdev->pixmap;
1829         /* fall through */
1830     case DC_GL_CHILD_WIN:
1831         /* The GL drawable may be lagged behind if we don't flush first, so
1832          * flush the display make sure we copy up-to-date data */
1833         XFlush(gdi_display);
1834         XSetFunction(gdi_display, physdev->x11dev->gc, GXcopy);
1835         XCopyArea(gdi_display, src, physdev->x11dev->drawable, physdev->x11dev->gc, 0, 0, w, h,
1836                   physdev->x11dev->dc_rect.left, physdev->x11dev->dc_rect.top);
1837         SetRect( &rect, 0, 0, w, h );
1838         add_device_bounds( physdev->x11dev, &rect );
1839     default:
1840         break;
1841     }
1842 }
1843
1844
1845 static void wglFinish(void)
1846 {
1847     struct wgl_context *ctx = NtCurrentTeb()->glContext;
1848     enum x11drv_escape_codes code = X11DRV_FLUSH_GL_DRAWABLE;
1849
1850     sync_context(ctx);
1851     pglFinish();
1852     ExtEscape( ctx->hdc, X11DRV_ESCAPE, sizeof(code), (LPSTR)&code, 0, NULL );
1853 }
1854
1855 static void wglFlush(void)
1856 {
1857     struct wgl_context *ctx = NtCurrentTeb()->glContext;
1858     enum x11drv_escape_codes code = X11DRV_FLUSH_GL_DRAWABLE;
1859
1860     sync_context(ctx);
1861     pglFlush();
1862     ExtEscape( ctx->hdc, X11DRV_ESCAPE, sizeof(code), (LPSTR)&code, 0, NULL );
1863 }
1864
1865 /***********************************************************************
1866  *              X11DRV_wglCreateContextAttribsARB
1867  */
1868 static struct wgl_context *X11DRV_wglCreateContextAttribsARB( HDC hdc, struct wgl_context *hShareContext,
1869                                                               const int* attribList )
1870 {
1871     struct wgl_context *ret = NULL;
1872     struct gl_drawable *gl;
1873
1874     TRACE("(%p %p %p)\n", hdc, hShareContext, attribList);
1875
1876     if (!(gl = get_gl_drawable( WindowFromDC( hdc ), hdc )))
1877     {
1878         SetLastError( ERROR_INVALID_PIXEL_FORMAT );
1879         return NULL;
1880     }
1881
1882     if ((ret = HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, sizeof(*ret))))
1883     {
1884         ret->hdc = hdc;
1885         ret->fmt = gl->format;
1886         ret->vis = NULL; /* glXCreateContextAttribsARB requires a fbconfig instead of a visual */
1887         ret->gl3_context = TRUE;
1888         ret->numAttribs = 0;
1889         if (attribList)
1890         {
1891             int *pContextAttribList = &ret->attribList[0];
1892             /* attribList consists of pairs {token, value] terminated with 0 */
1893             while(attribList[0] != 0)
1894             {
1895                 TRACE("%#x %#x\n", attribList[0], attribList[1]);
1896                 switch(attribList[0])
1897                 {
1898                 case WGL_CONTEXT_MAJOR_VERSION_ARB:
1899                     pContextAttribList[0] = GLX_CONTEXT_MAJOR_VERSION_ARB;
1900                     pContextAttribList[1] = attribList[1];
1901                     break;
1902                 case WGL_CONTEXT_MINOR_VERSION_ARB:
1903                     pContextAttribList[0] = GLX_CONTEXT_MINOR_VERSION_ARB;
1904                     pContextAttribList[1] = attribList[1];
1905                     break;
1906                 case WGL_CONTEXT_LAYER_PLANE_ARB:
1907                     break;
1908                 case WGL_CONTEXT_FLAGS_ARB:
1909                     pContextAttribList[0] = GLX_CONTEXT_FLAGS_ARB;
1910                     pContextAttribList[1] = attribList[1];
1911                     break;
1912                 case WGL_CONTEXT_PROFILE_MASK_ARB:
1913                     pContextAttribList[0] = GLX_CONTEXT_PROFILE_MASK_ARB;
1914                     pContextAttribList[1] = attribList[1];
1915                     break;
1916                 default:
1917                     ERR("Unhandled attribList pair: %#x %#x\n", attribList[0], attribList[1]);
1918                 }
1919                 ret->numAttribs++;
1920                 attribList += 2;
1921                 pContextAttribList += 2;
1922             }
1923         }
1924
1925         X11DRV_expect_error(gdi_display, GLXErrorHandler, NULL);
1926         ret->ctx = create_glxcontext(gdi_display, ret, NULL);
1927         XSync(gdi_display, False);
1928         if (X11DRV_check_error() || !ret->ctx)
1929         {
1930             /* In the future we should convert the GLX error to a win32 one here if needed */
1931             ERR("Context creation failed\n");
1932             HeapFree( GetProcessHeap(), 0, ret );
1933             ret = NULL;
1934         }
1935         else list_add_head( &context_list, &ret->entry );
1936     }
1937
1938     release_gl_drawable( gl );
1939     TRACE( "%p -> %p\n", hdc, ret );
1940     return ret;
1941 }
1942
1943 /**
1944  * X11DRV_wglGetExtensionsStringARB
1945  *
1946  * WGL_ARB_extensions_string: wglGetExtensionsStringARB
1947  */
1948 static const GLubyte *X11DRV_wglGetExtensionsStringARB(HDC hdc)
1949 {
1950     TRACE("() returning \"%s\"\n", WineGLInfo.wglExtensions);
1951     return (const GLubyte *)WineGLInfo.wglExtensions;
1952 }
1953
1954 /**
1955  * X11DRV_wglCreatePbufferARB
1956  *
1957  * WGL_ARB_pbuffer: wglCreatePbufferARB
1958  */
1959 static struct wgl_pbuffer *X11DRV_wglCreatePbufferARB( HDC hdc, int iPixelFormat, int iWidth, int iHeight,
1960                                                        const int *piAttribList )
1961 {
1962     struct wgl_pbuffer* object = NULL;
1963     const struct wgl_pixel_format *fmt = NULL;
1964     int attribs[256];
1965     int nAttribs = 0;
1966
1967     TRACE("(%p, %d, %d, %d, %p)\n", hdc, iPixelFormat, iWidth, iHeight, piAttribList);
1968
1969     /* Convert the WGL pixelformat to a GLX format, if it fails then the format is invalid */
1970     fmt = get_pixel_format(gdi_display, iPixelFormat, TRUE /* Offscreen */);
1971     if(!fmt) {
1972         ERR("(%p): invalid pixel format %d\n", hdc, iPixelFormat);
1973         SetLastError(ERROR_INVALID_PIXEL_FORMAT);
1974         return NULL;
1975     }
1976
1977     object = HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, sizeof(*object));
1978     if (NULL == object) {
1979         SetLastError(ERROR_NO_SYSTEM_RESOURCES);
1980         return NULL;
1981     }
1982     object->width = iWidth;
1983     object->height = iHeight;
1984     object->fmt = fmt;
1985
1986     PUSH2(attribs, GLX_PBUFFER_WIDTH,  iWidth);
1987     PUSH2(attribs, GLX_PBUFFER_HEIGHT, iHeight); 
1988     while (piAttribList && 0 != *piAttribList) {
1989         int attr_v;
1990         switch (*piAttribList) {
1991             case WGL_PBUFFER_LARGEST_ARB: {
1992                 ++piAttribList;
1993                 attr_v = *piAttribList;
1994                 TRACE("WGL_LARGEST_PBUFFER_ARB = %d\n", attr_v);
1995                 PUSH2(attribs, GLX_LARGEST_PBUFFER, attr_v);
1996                 break;
1997             }
1998
1999             case WGL_TEXTURE_FORMAT_ARB: {
2000                 ++piAttribList;
2001                 attr_v = *piAttribList;
2002                 TRACE("WGL_render_texture Attribute: WGL_TEXTURE_FORMAT_ARB as %x\n", attr_v);
2003                 if (WGL_NO_TEXTURE_ARB == attr_v) {
2004                     object->use_render_texture = 0;
2005                 } else {
2006                     if (!use_render_texture_emulation) {
2007                         SetLastError(ERROR_INVALID_DATA);
2008                         goto create_failed;
2009                     }
2010                     switch (attr_v) {
2011                         case WGL_TEXTURE_RGB_ARB:
2012                             object->use_render_texture = GL_RGB;
2013                             object->texture_bpp = 3;
2014                             object->texture_format = GL_RGB;
2015                             object->texture_type = GL_UNSIGNED_BYTE;
2016                             break;
2017                         case WGL_TEXTURE_RGBA_ARB:
2018                             object->use_render_texture = GL_RGBA;
2019                             object->texture_bpp = 4;
2020                             object->texture_format = GL_RGBA;
2021                             object->texture_type = GL_UNSIGNED_BYTE;
2022                             break;
2023
2024                         /* WGL_FLOAT_COMPONENTS_NV */
2025                         case WGL_TEXTURE_FLOAT_R_NV:
2026                             object->use_render_texture = GL_FLOAT_R_NV;
2027                             object->texture_bpp = 4;
2028                             object->texture_format = GL_RED;
2029                             object->texture_type = GL_FLOAT;
2030                             break;
2031                         case WGL_TEXTURE_FLOAT_RG_NV:
2032                             object->use_render_texture = GL_FLOAT_RG_NV;
2033                             object->texture_bpp = 8;
2034                             object->texture_format = GL_LUMINANCE_ALPHA;
2035                             object->texture_type = GL_FLOAT;
2036                             break;
2037                         case WGL_TEXTURE_FLOAT_RGB_NV:
2038                             object->use_render_texture = GL_FLOAT_RGB_NV;
2039                             object->texture_bpp = 12;
2040                             object->texture_format = GL_RGB;
2041                             object->texture_type = GL_FLOAT;
2042                             break;
2043                         case WGL_TEXTURE_FLOAT_RGBA_NV:
2044                             object->use_render_texture = GL_FLOAT_RGBA_NV;
2045                             object->texture_bpp = 16;
2046                             object->texture_format = GL_RGBA;
2047                             object->texture_type = GL_FLOAT;
2048                             break;
2049                         default:
2050                             ERR("Unknown texture format: %x\n", attr_v);
2051                             SetLastError(ERROR_INVALID_DATA);
2052                             goto create_failed;
2053                     }
2054                 }
2055                 break;
2056             }
2057
2058             case WGL_TEXTURE_TARGET_ARB: {
2059                 ++piAttribList;
2060                 attr_v = *piAttribList;
2061                 TRACE("WGL_render_texture Attribute: WGL_TEXTURE_TARGET_ARB as %x\n", attr_v);
2062                 if (WGL_NO_TEXTURE_ARB == attr_v) {
2063                     object->texture_target = 0;
2064                 } else {
2065                     if (!use_render_texture_emulation) {
2066                         SetLastError(ERROR_INVALID_DATA);
2067                         goto create_failed;
2068                     }
2069                     switch (attr_v) {
2070                         case WGL_TEXTURE_CUBE_MAP_ARB: {
2071                             if (iWidth != iHeight) {
2072                                 SetLastError(ERROR_INVALID_DATA);
2073                                 goto create_failed;
2074                             }
2075                             object->texture_target = GL_TEXTURE_CUBE_MAP;
2076                             object->texture_bind_target = GL_TEXTURE_BINDING_CUBE_MAP;
2077                            break;
2078                         }
2079                         case WGL_TEXTURE_1D_ARB: {
2080                             if (1 != iHeight) {
2081                                 SetLastError(ERROR_INVALID_DATA);
2082                                 goto create_failed;
2083                             }
2084                             object->texture_target = GL_TEXTURE_1D;
2085                             object->texture_bind_target = GL_TEXTURE_BINDING_1D;
2086                             break;
2087                         }
2088                         case WGL_TEXTURE_2D_ARB: {
2089                             object->texture_target = GL_TEXTURE_2D;
2090                             object->texture_bind_target = GL_TEXTURE_BINDING_2D;
2091                             break;
2092                         }
2093                         case WGL_TEXTURE_RECTANGLE_NV: {
2094                             object->texture_target = GL_TEXTURE_RECTANGLE_NV;
2095                             object->texture_bind_target = GL_TEXTURE_BINDING_RECTANGLE_NV;
2096                             break;
2097                         }
2098                         default:
2099                             ERR("Unknown texture target: %x\n", attr_v);
2100                             SetLastError(ERROR_INVALID_DATA);
2101                             goto create_failed;
2102                     }
2103                 }
2104                 break;
2105             }
2106
2107             case WGL_MIPMAP_TEXTURE_ARB: {
2108                 ++piAttribList;
2109                 attr_v = *piAttribList;
2110                 TRACE("WGL_render_texture Attribute: WGL_MIPMAP_TEXTURE_ARB as %x\n", attr_v);
2111                 if (!use_render_texture_emulation) {
2112                     SetLastError(ERROR_INVALID_DATA);
2113                     goto create_failed;
2114                 }
2115                 break;
2116             }
2117         }
2118         ++piAttribList;
2119     }
2120
2121     PUSH1(attribs, None);
2122     object->drawable = pglXCreatePbuffer(gdi_display, fmt->fbconfig, attribs);
2123     TRACE("new Pbuffer drawable as %lx\n", object->drawable);
2124     if (!object->drawable) {
2125         SetLastError(ERROR_NO_SYSTEM_RESOURCES);
2126         goto create_failed; /* unexpected error */
2127     }
2128     TRACE("->(%p)\n", object);
2129     return object;
2130
2131 create_failed:
2132     HeapFree(GetProcessHeap(), 0, object);
2133     TRACE("->(FAILED)\n");
2134     return NULL;
2135 }
2136
2137 /**
2138  * X11DRV_wglDestroyPbufferARB
2139  *
2140  * WGL_ARB_pbuffer: wglDestroyPbufferARB
2141  */
2142 static BOOL X11DRV_wglDestroyPbufferARB( struct wgl_pbuffer *object )
2143 {
2144     TRACE("(%p)\n", object);
2145
2146     pglXDestroyPbuffer(gdi_display, object->drawable);
2147     HeapFree(GetProcessHeap(), 0, object);
2148     return GL_TRUE;
2149 }
2150
2151 /**
2152  * X11DRV_wglGetPbufferDCARB
2153  *
2154  * WGL_ARB_pbuffer: wglGetPbufferDCARB
2155  */
2156 static HDC X11DRV_wglGetPbufferDCARB( struct wgl_pbuffer *object )
2157 {
2158     struct x11drv_escape_set_drawable escape;
2159     struct gl_drawable *gl, *prev;
2160     HDC hdc;
2161
2162     hdc = CreateDCA( "DISPLAY", NULL, NULL, NULL );
2163     if (!hdc) return 0;
2164
2165     if (!(gl = HeapAlloc( GetProcessHeap(), HEAP_ZERO_MEMORY, sizeof(*gl) )))
2166     {
2167         DeleteDC( hdc );
2168         return 0;
2169     }
2170     gl->type = DC_GL_PBUFFER;
2171     gl->drawable = object->drawable;
2172     gl->format = object->fmt;
2173
2174     EnterCriticalSection( &context_section );
2175     if (!XFindContext( gdi_display, (XID)hdc, gl_pbuffer_context, (char **)&prev ))
2176         free_gl_drawable( prev );
2177     XSaveContext( gdi_display, (XID)hdc, gl_pbuffer_context, (char *)gl );
2178     LeaveCriticalSection( &context_section );
2179
2180     escape.code = X11DRV_SET_DRAWABLE;
2181     escape.hwnd = 0;
2182     escape.drawable = object->drawable;
2183     escape.mode = IncludeInferiors;
2184     SetRect( &escape.dc_rect, 0, 0, object->width, object->height );
2185     escape.fbconfig_id = object->fmt->fmt_id;
2186     ExtEscape( hdc, X11DRV_ESCAPE, sizeof(escape), (LPSTR)&escape, 0, NULL );
2187
2188     TRACE( "(%p)->(%p)\n", object, hdc );
2189     return hdc;
2190 }
2191
2192 /**
2193  * X11DRV_wglQueryPbufferARB
2194  *
2195  * WGL_ARB_pbuffer: wglQueryPbufferARB
2196  */
2197 static BOOL X11DRV_wglQueryPbufferARB( struct wgl_pbuffer *object, int iAttribute, int *piValue )
2198 {
2199     TRACE("(%p, 0x%x, %p)\n", object, iAttribute, piValue);
2200
2201     switch (iAttribute) {
2202         case WGL_PBUFFER_WIDTH_ARB:
2203             pglXQueryDrawable(gdi_display, object->drawable, GLX_WIDTH, (unsigned int*) piValue);
2204             break;
2205         case WGL_PBUFFER_HEIGHT_ARB:
2206             pglXQueryDrawable(gdi_display, object->drawable, GLX_HEIGHT, (unsigned int*) piValue);
2207             break;
2208
2209         case WGL_PBUFFER_LOST_ARB:
2210             /* GLX Pbuffers cannot be lost by default. We can support this by
2211              * setting GLX_PRESERVED_CONTENTS to False and using glXSelectEvent
2212              * to receive pixel buffer clobber events, however that may or may
2213              * not give any benefit */
2214             *piValue = GL_FALSE;
2215             break;
2216
2217         case WGL_TEXTURE_FORMAT_ARB:
2218             if (!object->use_render_texture) {
2219                 *piValue = WGL_NO_TEXTURE_ARB;
2220             } else {
2221                 if (!use_render_texture_emulation) {
2222                     SetLastError(ERROR_INVALID_HANDLE);
2223                     return GL_FALSE;
2224                 }
2225                 switch(object->use_render_texture) {
2226                     case GL_RGB:
2227                         *piValue = WGL_TEXTURE_RGB_ARB;
2228                         break;
2229                     case GL_RGBA:
2230                         *piValue = WGL_TEXTURE_RGBA_ARB;
2231                         break;
2232                     /* WGL_FLOAT_COMPONENTS_NV */
2233                     case GL_FLOAT_R_NV:
2234                         *piValue = WGL_TEXTURE_FLOAT_R_NV;
2235                         break;
2236                     case GL_FLOAT_RG_NV:
2237                         *piValue = WGL_TEXTURE_FLOAT_RG_NV;
2238                         break;
2239                     case GL_FLOAT_RGB_NV:
2240                         *piValue = WGL_TEXTURE_FLOAT_RGB_NV;
2241                         break;
2242                     case GL_FLOAT_RGBA_NV:
2243                         *piValue = WGL_TEXTURE_FLOAT_RGBA_NV;
2244                         break;
2245                     default:
2246                         ERR("Unknown texture format: %x\n", object->use_render_texture);
2247                 }
2248             }
2249             break;
2250
2251         case WGL_TEXTURE_TARGET_ARB:
2252             if (!object->texture_target){
2253                 *piValue = WGL_NO_TEXTURE_ARB;
2254             } else {
2255                 if (!use_render_texture_emulation) {
2256                     SetLastError(ERROR_INVALID_DATA);
2257                     return GL_FALSE;
2258                 }
2259                 switch (object->texture_target) {
2260                     case GL_TEXTURE_1D:       *piValue = WGL_TEXTURE_1D_ARB; break;
2261                     case GL_TEXTURE_2D:       *piValue = WGL_TEXTURE_2D_ARB; break;
2262                     case GL_TEXTURE_CUBE_MAP: *piValue = WGL_TEXTURE_CUBE_MAP_ARB; break;
2263                     case GL_TEXTURE_RECTANGLE_NV: *piValue = WGL_TEXTURE_RECTANGLE_NV; break;
2264                 }
2265             }
2266             break;
2267
2268         case WGL_MIPMAP_TEXTURE_ARB:
2269             *piValue = GL_FALSE; /** don't support that */
2270             FIXME("unsupported WGL_ARB_render_texture attribute query for 0x%x\n", iAttribute);
2271             break;
2272
2273         default:
2274             FIXME("unexpected attribute %x\n", iAttribute);
2275             break;
2276     }
2277
2278     return GL_TRUE;
2279 }
2280
2281 /**
2282  * X11DRV_wglReleasePbufferDCARB
2283  *
2284  * WGL_ARB_pbuffer: wglReleasePbufferDCARB
2285  */
2286 static int X11DRV_wglReleasePbufferDCARB( struct wgl_pbuffer *object, HDC hdc )
2287 {
2288     struct gl_drawable *gl;
2289
2290     TRACE("(%p, %p)\n", object, hdc);
2291
2292     EnterCriticalSection( &context_section );
2293     if (!XFindContext( gdi_display, (XID)hdc, gl_pbuffer_context, (char **)&gl ))
2294     {
2295         XDeleteContext( gdi_display, (XID)hdc, gl_pbuffer_context );
2296         free_gl_drawable( gl );
2297     }
2298     LeaveCriticalSection( &context_section );
2299
2300     return DeleteDC(hdc);
2301 }
2302
2303 /**
2304  * X11DRV_wglSetPbufferAttribARB
2305  *
2306  * WGL_ARB_pbuffer: wglSetPbufferAttribARB
2307  */
2308 static BOOL X11DRV_wglSetPbufferAttribARB( struct wgl_pbuffer *object, const int *piAttribList )
2309 {
2310     GLboolean ret = GL_FALSE;
2311
2312     WARN("(%p, %p): alpha-testing, report any problem\n", object, piAttribList);
2313
2314     if (!object->use_render_texture) {
2315         SetLastError(ERROR_INVALID_HANDLE);
2316         return GL_FALSE;
2317     }
2318     if (1 == use_render_texture_emulation) {
2319         return GL_TRUE;
2320     }
2321     return ret;
2322 }
2323
2324 /**
2325  * X11DRV_wglChoosePixelFormatARB
2326  *
2327  * WGL_ARB_pixel_format: wglChoosePixelFormatARB
2328  */
2329 static BOOL X11DRV_wglChoosePixelFormatARB( HDC hdc, const int *piAttribIList, const FLOAT *pfAttribFList,
2330                                             UINT nMaxFormats, int *piFormats, UINT *nNumFormats )
2331 {
2332     int attribs[256];
2333     int nAttribs = 0;
2334     GLXFBConfig* cfgs = NULL;
2335     int nCfgs = 0;
2336     int it;
2337     int fmt_id;
2338     int start, end;
2339     UINT pfmt_it = 0;
2340     int run;
2341     int i;
2342     DWORD dwFlags = 0;
2343
2344     TRACE("(%p, %p, %p, %d, %p, %p): hackish\n", hdc, piAttribIList, pfAttribFList, nMaxFormats, piFormats, nNumFormats);
2345     if (NULL != pfAttribFList) {
2346         FIXME("unused pfAttribFList\n");
2347     }
2348
2349     nAttribs = ConvertAttribWGLtoGLX(piAttribIList, attribs, NULL);
2350     if (-1 == nAttribs) {
2351         WARN("Cannot convert WGL to GLX attributes\n");
2352         return GL_FALSE;
2353     }
2354     PUSH1(attribs, None);
2355
2356     /* There is no 1:1 mapping between GLX and WGL formats because we duplicate some GLX formats for bitmap rendering (see get_formats).
2357      * Flags like PFD_SUPPORT_GDI, PFD_DRAW_TO_BITMAP and others are a property of the pixel format. We don't query these attributes
2358      * using glXChooseFBConfig but we filter the result of glXChooseFBConfig later on.
2359      */
2360     for(i=0; piAttribIList[i] != 0; i+=2)
2361     {
2362         switch(piAttribIList[i])
2363         {
2364             case WGL_DRAW_TO_BITMAP_ARB:
2365                 if(piAttribIList[i+1])
2366                     dwFlags |= PFD_DRAW_TO_BITMAP;
2367                 break;
2368             case WGL_ACCELERATION_ARB:
2369                 switch(piAttribIList[i+1])
2370                 {
2371                     case WGL_NO_ACCELERATION_ARB:
2372                         dwFlags |= PFD_GENERIC_FORMAT;
2373                         break;
2374                     case WGL_GENERIC_ACCELERATION_ARB:
2375                         dwFlags |= PFD_GENERIC_ACCELERATED;
2376                         break;
2377                     case WGL_FULL_ACCELERATION_ARB:
2378                         /* Nothing to do */
2379                         break;
2380                 }
2381                 break;
2382             case WGL_SUPPORT_GDI_ARB:
2383                 if(piAttribIList[i+1])
2384                     dwFlags |= PFD_SUPPORT_GDI;
2385                 break;
2386         }
2387     }
2388
2389     /* Search for FB configurations matching the requirements in attribs */
2390     cfgs = pglXChooseFBConfig(gdi_display, DefaultScreen(gdi_display), attribs, &nCfgs);
2391     if (NULL == cfgs) {
2392         WARN("Compatible Pixel Format not found\n");
2393         return GL_FALSE;
2394     }
2395
2396     /* Loop through all matching formats and check if they are suitable.
2397      * Note that this function should at max return nMaxFormats different formats */
2398     for(run=0; run < 2; run++)
2399     {
2400         for (it = 0; it < nCfgs && pfmt_it < nMaxFormats; ++it)
2401         {
2402             if (pglXGetFBConfigAttrib(gdi_display, cfgs[it], GLX_FBCONFIG_ID, &fmt_id))
2403             {
2404                 ERR("Failed to retrieve FBCONFIG_ID from GLXFBConfig, expect problems.\n");
2405                 continue;
2406             }
2407
2408             /* During the first run we only want onscreen formats and during the second only offscreen */
2409             start = run == 1 ? nb_onscreen_formats : 0;
2410             end = run == 1 ? nb_pixel_formats : nb_onscreen_formats;
2411
2412             for (i = start; i < end; i++)
2413             {
2414                 if (pixel_formats[i].fmt_id == fmt_id && (pixel_formats[i].dwFlags & dwFlags) == dwFlags)
2415                 {
2416                     piFormats[pfmt_it++] = i + 1;
2417                     TRACE("at %d/%d found FBCONFIG_ID 0x%x (%d)\n",
2418                           it + 1, nCfgs, fmt_id, piFormats[pfmt_it]);
2419                     break;
2420                 }
2421             }
2422         }
2423     }
2424
2425     *nNumFormats = pfmt_it;
2426     /** free list */
2427     XFree(cfgs);
2428     return GL_TRUE;
2429 }
2430
2431 /**
2432  * X11DRV_wglGetPixelFormatAttribivARB
2433  *
2434  * WGL_ARB_pixel_format: wglGetPixelFormatAttribivARB
2435  */
2436 static BOOL X11DRV_wglGetPixelFormatAttribivARB( HDC hdc, int iPixelFormat, int iLayerPlane,
2437                                                  UINT nAttributes, const int *piAttributes, int *piValues )
2438 {
2439     UINT i;
2440     const struct wgl_pixel_format *fmt = NULL;
2441     int hTest;
2442     int tmp;
2443     int curGLXAttr = 0;
2444
2445     TRACE("(%p, %d, %d, %d, %p, %p)\n", hdc, iPixelFormat, iLayerPlane, nAttributes, piAttributes, piValues);
2446
2447     if (0 < iLayerPlane) {
2448         FIXME("unsupported iLayerPlane(%d) > 0, returns FALSE\n", iLayerPlane);
2449         return GL_FALSE;
2450     }
2451
2452     /* Convert the WGL pixelformat to a GLX one, if this fails then most likely the iPixelFormat isn't supported.
2453     * We don't have to fail yet as a program can specify an invalid iPixelFormat (lets say 0) if it wants to query
2454     * the number of supported WGL formats. Whether the iPixelFormat is valid is handled in the for-loop below. */
2455     fmt = get_pixel_format(gdi_display, iPixelFormat, TRUE /* Offscreen */);
2456     if(!fmt) {
2457         WARN("Unable to convert iPixelFormat %d to a GLX one!\n", iPixelFormat);
2458     }
2459
2460     for (i = 0; i < nAttributes; ++i) {
2461         const int curWGLAttr = piAttributes[i];
2462         TRACE("pAttr[%d] = %x\n", i, curWGLAttr);
2463
2464         switch (curWGLAttr) {
2465             case WGL_NUMBER_PIXEL_FORMATS_ARB:
2466                 piValues[i] = nb_pixel_formats;
2467                 continue;
2468
2469             case WGL_SUPPORT_OPENGL_ARB:
2470                 piValues[i] = GL_TRUE; 
2471                 continue;
2472
2473             case WGL_ACCELERATION_ARB:
2474                 curGLXAttr = GLX_CONFIG_CAVEAT;
2475                 if (!fmt) goto pix_error;
2476                 if(fmt->dwFlags & PFD_GENERIC_FORMAT)
2477                     piValues[i] = WGL_NO_ACCELERATION_ARB;
2478                 else if(fmt->dwFlags & PFD_GENERIC_ACCELERATED)
2479                     piValues[i] = WGL_GENERIC_ACCELERATION_ARB;
2480                 else
2481                     piValues[i] = WGL_FULL_ACCELERATION_ARB;
2482                 continue;
2483
2484             case WGL_TRANSPARENT_ARB:
2485                 curGLXAttr = GLX_TRANSPARENT_TYPE;
2486                 if (!fmt) goto pix_error;
2487                 hTest = pglXGetFBConfigAttrib(gdi_display, fmt->fbconfig, curGLXAttr, &tmp);
2488                 if (hTest) goto get_error;
2489                     piValues[i] = GL_FALSE;
2490                 if (GLX_NONE != tmp) piValues[i] = GL_TRUE;
2491                     continue;
2492
2493             case WGL_PIXEL_TYPE_ARB:
2494                 curGLXAttr = GLX_RENDER_TYPE;
2495                 if (!fmt) goto pix_error;
2496                 hTest = pglXGetFBConfigAttrib(gdi_display, fmt->fbconfig, curGLXAttr, &tmp);
2497                 if (hTest) goto get_error;
2498                 TRACE("WGL_PIXEL_TYPE_ARB: GLX_RENDER_TYPE = 0x%x\n", tmp);
2499                 if      (tmp & GLX_RGBA_BIT)           { piValues[i] = WGL_TYPE_RGBA_ARB; }
2500                 else if (tmp & GLX_COLOR_INDEX_BIT)    { piValues[i] = WGL_TYPE_COLORINDEX_ARB; }
2501                 else if (tmp & GLX_RGBA_FLOAT_BIT)     { piValues[i] = WGL_TYPE_RGBA_FLOAT_ATI; }
2502                 else if (tmp & GLX_RGBA_FLOAT_ATI_BIT) { piValues[i] = WGL_TYPE_RGBA_FLOAT_ATI; }
2503                 else if (tmp & GLX_RGBA_UNSIGNED_FLOAT_BIT_EXT) { piValues[i] = WGL_TYPE_RGBA_UNSIGNED_FLOAT_EXT; }
2504                 else {
2505                     ERR("unexpected RenderType(%x)\n", tmp);
2506                     piValues[i] = WGL_TYPE_RGBA_ARB;
2507                 }
2508                 continue;
2509
2510             case WGL_COLOR_BITS_ARB:
2511                 curGLXAttr = GLX_BUFFER_SIZE;
2512                 break;
2513
2514             case WGL_BIND_TO_TEXTURE_RGB_ARB:
2515             case WGL_BIND_TO_TEXTURE_RGBA_ARB:
2516                 if (!use_render_texture_emulation) {
2517                     piValues[i] = GL_FALSE;
2518                     continue;   
2519                 }
2520                 curGLXAttr = GLX_RENDER_TYPE;
2521                 if (!fmt) goto pix_error;
2522                 hTest = pglXGetFBConfigAttrib(gdi_display, fmt->fbconfig, curGLXAttr, &tmp);
2523                 if (hTest) goto get_error;
2524                 if (GLX_COLOR_INDEX_BIT == tmp) {
2525                     piValues[i] = GL_FALSE;  
2526                     continue;
2527                 }
2528                 hTest = pglXGetFBConfigAttrib(gdi_display, fmt->fbconfig, GLX_DRAWABLE_TYPE, &tmp);
2529                 if (hTest) goto get_error;
2530                 piValues[i] = (tmp & GLX_PBUFFER_BIT) ? GL_TRUE : GL_FALSE;
2531                 continue;
2532
2533             case WGL_BLUE_BITS_ARB:
2534                 curGLXAttr = GLX_BLUE_SIZE;
2535                 break;
2536             case WGL_RED_BITS_ARB:
2537                 curGLXAttr = GLX_RED_SIZE;
2538                 break;
2539             case WGL_GREEN_BITS_ARB:
2540                 curGLXAttr = GLX_GREEN_SIZE;
2541                 break;
2542             case WGL_ALPHA_BITS_ARB:
2543                 curGLXAttr = GLX_ALPHA_SIZE;
2544                 break;
2545             case WGL_DEPTH_BITS_ARB:
2546                 curGLXAttr = GLX_DEPTH_SIZE;
2547                 break;
2548             case WGL_STENCIL_BITS_ARB:
2549                 curGLXAttr = GLX_STENCIL_SIZE;
2550                 break;
2551             case WGL_DOUBLE_BUFFER_ARB:
2552                 curGLXAttr = GLX_DOUBLEBUFFER;
2553                 break;
2554             case WGL_STEREO_ARB:
2555                 curGLXAttr = GLX_STEREO;
2556                 break;
2557             case WGL_AUX_BUFFERS_ARB:
2558                 curGLXAttr = GLX_AUX_BUFFERS;
2559                 break;
2560
2561             case WGL_SUPPORT_GDI_ARB:
2562                 if (!fmt) goto pix_error;
2563                 piValues[i] = (fmt->dwFlags & PFD_SUPPORT_GDI) != 0;
2564                 continue;
2565
2566             case WGL_DRAW_TO_BITMAP_ARB:
2567                 if (!fmt) goto pix_error;
2568                 piValues[i] = (fmt->dwFlags & PFD_DRAW_TO_BITMAP) != 0;
2569                 continue;
2570
2571             case WGL_DRAW_TO_WINDOW_ARB:
2572             case WGL_DRAW_TO_PBUFFER_ARB:
2573                 if (!fmt) goto pix_error;
2574                 hTest = pglXGetFBConfigAttrib(gdi_display, fmt->fbconfig, GLX_DRAWABLE_TYPE, &tmp);
2575                 if (hTest) goto get_error;
2576                 if((curWGLAttr == WGL_DRAW_TO_WINDOW_ARB && (tmp&GLX_WINDOW_BIT)) ||
2577                    (curWGLAttr == WGL_DRAW_TO_PBUFFER_ARB && (tmp&GLX_PBUFFER_BIT)))
2578                     piValues[i] = GL_TRUE;
2579                 else
2580                     piValues[i] = GL_FALSE;
2581                 continue;
2582
2583             case WGL_SWAP_METHOD_ARB:
2584                 /* For now return SWAP_EXCHANGE_ARB which is the best type of buffer switch available.
2585                  * Later on we can also use GLX_OML_swap_method on drivers which support this. At this
2586                  * point only ATI offers this.
2587                  */
2588                 piValues[i] = WGL_SWAP_EXCHANGE_ARB;
2589                 break;
2590
2591             case WGL_PBUFFER_LARGEST_ARB:
2592                 curGLXAttr = GLX_LARGEST_PBUFFER;
2593                 break;
2594
2595             case WGL_SAMPLE_BUFFERS_ARB:
2596                 curGLXAttr = GLX_SAMPLE_BUFFERS_ARB;
2597                 break;
2598
2599             case WGL_SAMPLES_ARB:
2600                 curGLXAttr = GLX_SAMPLES_ARB;
2601                 break;
2602
2603             case WGL_FLOAT_COMPONENTS_NV:
2604                 curGLXAttr = GLX_FLOAT_COMPONENTS_NV;
2605                 break;
2606
2607             case WGL_FRAMEBUFFER_SRGB_CAPABLE_EXT:
2608                 curGLXAttr = GLX_FRAMEBUFFER_SRGB_CAPABLE_EXT;
2609                 break;
2610
2611             case WGL_TYPE_RGBA_UNSIGNED_FLOAT_EXT:
2612                 curGLXAttr = GLX_RGBA_UNSIGNED_FLOAT_TYPE_EXT;
2613                 break;
2614
2615             case WGL_ACCUM_RED_BITS_ARB:
2616                 curGLXAttr = GLX_ACCUM_RED_SIZE;
2617                 break;
2618             case WGL_ACCUM_GREEN_BITS_ARB:
2619                 curGLXAttr = GLX_ACCUM_GREEN_SIZE;
2620                 break;
2621             case WGL_ACCUM_BLUE_BITS_ARB:
2622                 curGLXAttr = GLX_ACCUM_BLUE_SIZE;
2623                 break;
2624             case WGL_ACCUM_ALPHA_BITS_ARB:
2625                 curGLXAttr = GLX_ACCUM_ALPHA_SIZE;
2626                 break;
2627             case WGL_ACCUM_BITS_ARB:
2628                 if (!fmt) goto pix_error;
2629                 hTest = pglXGetFBConfigAttrib(gdi_display, fmt->fbconfig, GLX_ACCUM_RED_SIZE, &tmp);
2630                 if (hTest) goto get_error;
2631                 piValues[i] = tmp;
2632                 hTest = pglXGetFBConfigAttrib(gdi_display, fmt->fbconfig, GLX_ACCUM_GREEN_SIZE, &tmp);
2633                 if (hTest) goto get_error;
2634                 piValues[i] += tmp;
2635                 hTest = pglXGetFBConfigAttrib(gdi_display, fmt->fbconfig, GLX_ACCUM_BLUE_SIZE, &tmp);
2636                 if (hTest) goto get_error;
2637                 piValues[i] += tmp;
2638                 hTest = pglXGetFBConfigAttrib(gdi_display, fmt->fbconfig, GLX_ACCUM_ALPHA_SIZE, &tmp);
2639                 if (hTest) goto get_error;
2640                 piValues[i] += tmp;
2641                 continue;
2642
2643             default:
2644                 FIXME("unsupported %x WGL Attribute\n", curWGLAttr);
2645         }
2646
2647         /* Retrieve a GLX FBConfigAttrib when the attribute to query is valid and
2648          * iPixelFormat != 0. When iPixelFormat is 0 the only value which makes
2649          * sense to query is WGL_NUMBER_PIXEL_FORMATS_ARB.
2650          *
2651          * TODO: properly test the behavior of wglGetPixelFormatAttrib*v on Windows
2652          *       and check which options can work using iPixelFormat=0 and which not.
2653          *       A problem would be that this function is an extension. This would
2654          *       mean that the behavior could differ between different vendors (ATI, Nvidia, ..).
2655          */
2656         if (0 != curGLXAttr && iPixelFormat != 0) {
2657             if (!fmt) goto pix_error;
2658             hTest = pglXGetFBConfigAttrib(gdi_display, fmt->fbconfig, curGLXAttr, piValues + i);
2659             if (hTest) goto get_error;
2660             curGLXAttr = 0;
2661         } else { 
2662             piValues[i] = GL_FALSE; 
2663         }
2664     }
2665     return GL_TRUE;
2666
2667 get_error:
2668     ERR("(%p): unexpected failure on GetFBConfigAttrib(%x) returns FALSE\n", hdc, curGLXAttr);
2669     return GL_FALSE;
2670
2671 pix_error:
2672     ERR("(%p): unexpected iPixelFormat(%d) vs nFormats(%d), returns FALSE\n", hdc, iPixelFormat, nb_pixel_formats);
2673     return GL_FALSE;
2674 }
2675
2676 /**
2677  * X11DRV_wglGetPixelFormatAttribfvARB
2678  *
2679  * WGL_ARB_pixel_format: wglGetPixelFormatAttribfvARB
2680  */
2681 static BOOL X11DRV_wglGetPixelFormatAttribfvARB( HDC hdc, int iPixelFormat, int iLayerPlane,
2682                                                  UINT nAttributes, const int *piAttributes, FLOAT *pfValues )
2683 {
2684     int *attr;
2685     int ret;
2686     UINT i;
2687
2688     TRACE("(%p, %d, %d, %d, %p, %p)\n", hdc, iPixelFormat, iLayerPlane, nAttributes, piAttributes, pfValues);
2689
2690     /* Allocate a temporary array to store integer values */
2691     attr = HeapAlloc(GetProcessHeap(), 0, nAttributes * sizeof(int));
2692     if (!attr) {
2693         ERR("couldn't allocate %d array\n", nAttributes);
2694         return GL_FALSE;
2695     }
2696
2697     /* Piggy-back on wglGetPixelFormatAttribivARB */
2698     ret = X11DRV_wglGetPixelFormatAttribivARB(hdc, iPixelFormat, iLayerPlane, nAttributes, piAttributes, attr);
2699     if (ret) {
2700         /* Convert integer values to float. Should also check for attributes
2701            that can give decimal values here */
2702         for (i=0; i<nAttributes;i++) {
2703             pfValues[i] = attr[i];
2704         }
2705     }
2706
2707     HeapFree(GetProcessHeap(), 0, attr);
2708     return ret;
2709 }
2710
2711 /**
2712  * X11DRV_wglBindTexImageARB
2713  *
2714  * WGL_ARB_render_texture: wglBindTexImageARB
2715  */
2716 static BOOL X11DRV_wglBindTexImageARB( struct wgl_pbuffer *object, int iBuffer )
2717 {
2718     GLboolean ret = GL_FALSE;
2719
2720     TRACE("(%p, %d)\n", object, iBuffer);
2721
2722     if (!object->use_render_texture) {
2723         SetLastError(ERROR_INVALID_HANDLE);
2724         return GL_FALSE;
2725     }
2726
2727     if (1 == use_render_texture_emulation) {
2728         static int init = 0;
2729         int prev_binded_texture = 0;
2730         GLXContext prev_context;
2731         Drawable prev_drawable;
2732         GLXContext tmp_context;
2733
2734         prev_context = pglXGetCurrentContext();
2735         prev_drawable = pglXGetCurrentDrawable();
2736
2737         /* Our render_texture emulation is basic and lacks some features (1D/Cube support).
2738            This is mostly due to lack of demos/games using them. Further the use of glReadPixels
2739            isn't ideal performance wise but I wasn't able to get other ways working.
2740         */
2741         if(!init) {
2742             init = 1; /* Only show the FIXME once for performance reasons */
2743             FIXME("partial stub!\n");
2744         }
2745
2746         TRACE("drawable=%lx, context=%p\n", object->drawable, prev_context);
2747         tmp_context = pglXCreateNewContext(gdi_display, object->fmt->fbconfig, object->fmt->render_type, prev_context, True);
2748
2749         opengl_funcs.gl.p_glGetIntegerv(object->texture_bind_target, &prev_binded_texture);
2750
2751         /* Switch to our pbuffer */
2752         pglXMakeCurrent(gdi_display, object->drawable, tmp_context);
2753
2754         /* Make sure that the prev_binded_texture is set as the current texture state isn't shared between contexts.
2755          * After that upload the pbuffer texture data. */
2756         opengl_funcs.gl.p_glBindTexture(object->texture_target, prev_binded_texture);
2757         opengl_funcs.gl.p_glCopyTexImage2D(object->texture_target, 0, object->use_render_texture, 0, 0, object->width, object->height, 0);
2758
2759         /* Switch back to the original drawable and upload the pbuffer-texture */
2760         pglXMakeCurrent(gdi_display, prev_drawable, prev_context);
2761         pglXDestroyContext(gdi_display, tmp_context);
2762         return GL_TRUE;
2763     }
2764
2765     return ret;
2766 }
2767
2768 /**
2769  * X11DRV_wglReleaseTexImageARB
2770  *
2771  * WGL_ARB_render_texture: wglReleaseTexImageARB
2772  */
2773 static BOOL X11DRV_wglReleaseTexImageARB( struct wgl_pbuffer *object, int iBuffer )
2774 {
2775     GLboolean ret = GL_FALSE;
2776
2777     TRACE("(%p, %d)\n", object, iBuffer);
2778
2779     if (!object->use_render_texture) {
2780         SetLastError(ERROR_INVALID_HANDLE);
2781         return GL_FALSE;
2782     }
2783     if (1 == use_render_texture_emulation) {
2784         return GL_TRUE;
2785     }
2786     return ret;
2787 }
2788
2789 /**
2790  * X11DRV_wglGetExtensionsStringEXT
2791  *
2792  * WGL_EXT_extensions_string: wglGetExtensionsStringEXT
2793  */
2794 static const GLubyte *X11DRV_wglGetExtensionsStringEXT(void)
2795 {
2796     TRACE("() returning \"%s\"\n", WineGLInfo.wglExtensions);
2797     return (const GLubyte *)WineGLInfo.wglExtensions;
2798 }
2799
2800 /**
2801  * X11DRV_wglGetSwapIntervalEXT
2802  *
2803  * WGL_EXT_swap_control: wglGetSwapIntervalEXT
2804  */
2805 static int X11DRV_wglGetSwapIntervalEXT(void)
2806 {
2807     /* GLX_SGI_swap_control doesn't have any provisions for getting the swap
2808      * interval, so the swap interval has to be tracked. */
2809     TRACE("()\n");
2810     return swap_interval;
2811 }
2812
2813 /**
2814  * X11DRV_wglSwapIntervalEXT
2815  *
2816  * WGL_EXT_swap_control: wglSwapIntervalEXT
2817  */
2818 static BOOL X11DRV_wglSwapIntervalEXT(int interval)
2819 {
2820     BOOL ret = TRUE;
2821
2822     TRACE("(%d)\n", interval);
2823
2824     if (interval < 0)
2825     {
2826         SetLastError(ERROR_INVALID_DATA);
2827         return FALSE;
2828     }
2829     else if (!has_swap_control && interval == 0)
2830     {
2831         /* wglSwapIntervalEXT considers an interval value of zero to mean that
2832          * vsync should be disabled, but glXSwapIntervalSGI considers such a
2833          * value to be an error. Just silently ignore the request for now. */
2834         WARN("Request to disable vertical sync is not handled\n");
2835         swap_interval = 0;
2836     }
2837     else
2838     {
2839         if (pglXSwapIntervalSGI)
2840             ret = !pglXSwapIntervalSGI(interval);
2841         else
2842             WARN("GLX_SGI_swap_control extension is not available\n");
2843
2844         if (ret)
2845             swap_interval = interval;
2846         else
2847             SetLastError(ERROR_DC_NOT_FOUND);
2848     }
2849
2850     return ret;
2851 }
2852
2853 /**
2854  * X11DRV_wglSetPixelFormatWINE
2855  *
2856  * WGL_WINE_pixel_format_passthrough: wglSetPixelFormatWINE
2857  * This is a WINE-specific wglSetPixelFormat which can set the pixel format multiple times.
2858  */
2859 static BOOL X11DRV_wglSetPixelFormatWINE(HDC hdc, int format)
2860 {
2861     const struct wgl_pixel_format *fmt;
2862     int value;
2863     HWND hwnd;
2864
2865     TRACE("(%p,%d)\n", hdc, format);
2866
2867     fmt = get_pixel_format(gdi_display, format, FALSE /* Offscreen */);
2868     if (!fmt)
2869     {
2870         ERR( "Invalid format %d\n", format );
2871         return FALSE;
2872     }
2873
2874     hwnd = WindowFromDC( hdc );
2875     if (!hwnd || hwnd == GetDesktopWindow())
2876     {
2877         ERR( "not a valid window DC %p\n", hdc );
2878         return FALSE;
2879     }
2880
2881     pglXGetFBConfigAttrib(gdi_display, fmt->fbconfig, GLX_DRAWABLE_TYPE, &value);
2882     if (!(value & GLX_WINDOW_BIT))
2883     {
2884         WARN( "Pixel format %d is not compatible for window rendering\n", format );
2885         return FALSE;
2886     }
2887
2888     return SendMessageW(hwnd, WM_X11DRV_SET_WIN_FORMAT, fmt->fmt_id, 0);
2889     /* DC pixel format will be set by the DCE update */
2890 }
2891
2892 /**
2893  * glxRequireVersion (internal)
2894  *
2895  * Check if the supported GLX version matches requiredVersion.
2896  */
2897 static BOOL glxRequireVersion(int requiredVersion)
2898 {
2899     /* Both requiredVersion and glXVersion[1] contains the minor GLX version */
2900     if(requiredVersion <= WineGLInfo.glxVersion[1])
2901         return TRUE;
2902
2903     return FALSE;
2904 }
2905
2906 static void register_extension(const char *ext)
2907 {
2908     if (WineGLInfo.wglExtensions[0])
2909         strcat(WineGLInfo.wglExtensions, " ");
2910     strcat(WineGLInfo.wglExtensions, ext);
2911
2912     TRACE("'%s'\n", ext);
2913 }
2914
2915 /**
2916  * X11DRV_WineGL_LoadExtensions
2917  */
2918 static void X11DRV_WineGL_LoadExtensions(void)
2919 {
2920     WineGLInfo.wglExtensions[0] = 0;
2921
2922     /* ARB Extensions */
2923
2924     if (has_extension( WineGLInfo.glxExtensions, "GLX_ARB_create_context"))
2925     {
2926         register_extension( "WGL_ARB_create_context" );
2927         opengl_funcs.ext.p_wglCreateContextAttribsARB = X11DRV_wglCreateContextAttribsARB;
2928
2929         if (has_extension( WineGLInfo.glxExtensions, "GLX_ARB_create_context_profile"))
2930             register_extension("WGL_ARB_create_context_profile");
2931     }
2932
2933     if (has_extension( WineGLInfo.glxExtensions, "GLX_ARB_fbconfig_float"))
2934     {
2935         register_extension("WGL_ARB_pixel_format_float");
2936         register_extension("WGL_ATI_pixel_format_float");
2937     }
2938
2939     register_extension( "WGL_ARB_extensions_string" );
2940     opengl_funcs.ext.p_wglGetExtensionsStringARB = X11DRV_wglGetExtensionsStringARB;
2941
2942     if (glxRequireVersion(3))
2943     {
2944         register_extension( "WGL_ARB_make_current_read" );
2945         opengl_funcs.ext.p_wglGetCurrentReadDCARB   = (void *)1;  /* never called */
2946         opengl_funcs.ext.p_wglMakeContextCurrentARB = X11DRV_wglMakeContextCurrentARB;
2947     }
2948
2949     if (has_extension( WineGLInfo.glxExtensions, "GLX_ARB_multisample")) register_extension( "WGL_ARB_multisample" );
2950
2951     /* In general pbuffer functionality requires support in the X-server. The functionality is
2952      * available either when the GLX_SGIX_pbuffer is present or when the GLX server version is 1.3.
2953      */
2954     if ( glxRequireVersion(3) && has_extension( WineGLInfo.glxExtensions, "GLX_SGIX_pbuffer") )
2955     {
2956         register_extension( "WGL_ARB_pbuffer" );
2957         opengl_funcs.ext.p_wglCreatePbufferARB    = X11DRV_wglCreatePbufferARB;
2958         opengl_funcs.ext.p_wglDestroyPbufferARB   = X11DRV_wglDestroyPbufferARB;
2959         opengl_funcs.ext.p_wglGetPbufferDCARB     = X11DRV_wglGetPbufferDCARB;
2960         opengl_funcs.ext.p_wglQueryPbufferARB     = X11DRV_wglQueryPbufferARB;
2961         opengl_funcs.ext.p_wglReleasePbufferDCARB = X11DRV_wglReleasePbufferDCARB;
2962         opengl_funcs.ext.p_wglSetPbufferAttribARB = X11DRV_wglSetPbufferAttribARB;
2963     }
2964
2965     register_extension( "WGL_ARB_pixel_format" );
2966     opengl_funcs.ext.p_wglChoosePixelFormatARB      = X11DRV_wglChoosePixelFormatARB;
2967     opengl_funcs.ext.p_wglGetPixelFormatAttribfvARB = X11DRV_wglGetPixelFormatAttribfvARB;
2968     opengl_funcs.ext.p_wglGetPixelFormatAttribivARB = X11DRV_wglGetPixelFormatAttribivARB;
2969
2970     /* Support WGL_ARB_render_texture when there's support or pbuffer based emulation */
2971     if (has_extension( WineGLInfo.glxExtensions, "GLX_ARB_render_texture") ||
2972         (glxRequireVersion(3) && has_extension( WineGLInfo.glxExtensions, "GLX_SGIX_pbuffer") && use_render_texture_emulation))
2973     {
2974         register_extension( "WGL_ARB_render_texture" );
2975         opengl_funcs.ext.p_wglBindTexImageARB    = X11DRV_wglBindTexImageARB;
2976         opengl_funcs.ext.p_wglReleaseTexImageARB = X11DRV_wglReleaseTexImageARB;
2977
2978         /* The WGL version of GLX_NV_float_buffer requires render_texture */
2979         if (has_extension( WineGLInfo.glxExtensions, "GLX_NV_float_buffer"))
2980             register_extension("WGL_NV_float_buffer");
2981
2982         /* Again there's no GLX equivalent for this extension, so depend on the required GL extension */
2983         if (has_extension(WineGLInfo.glExtensions, "GL_NV_texture_rectangle"))
2984             register_extension("WGL_NV_texture_rectangle");
2985     }
2986
2987     /* EXT Extensions */
2988
2989     register_extension( "WGL_EXT_extensions_string" );
2990     opengl_funcs.ext.p_wglGetExtensionsStringEXT = X11DRV_wglGetExtensionsStringEXT;
2991
2992     /* Load this extension even when it isn't backed by a GLX extension because it is has been around for ages.
2993      * Games like Call of Duty and K.O.T.O.R. rely on it. Further our emulation is good enough. */
2994     register_extension( "WGL_EXT_swap_control" );
2995     opengl_funcs.ext.p_wglSwapIntervalEXT = X11DRV_wglSwapIntervalEXT;
2996     opengl_funcs.ext.p_wglGetSwapIntervalEXT = X11DRV_wglGetSwapIntervalEXT;
2997
2998     if (has_extension( WineGLInfo.glxExtensions, "GLX_EXT_framebuffer_sRGB"))
2999         register_extension("WGL_EXT_framebuffer_sRGB");
3000
3001     if (has_extension( WineGLInfo.glxExtensions, "GLX_EXT_fbconfig_packed_float"))
3002         register_extension("WGL_EXT_pixel_format_packed_float");
3003
3004     if (has_extension( WineGLInfo.glxExtensions, "GLX_EXT_swap_control"))
3005         has_swap_control = TRUE;
3006
3007     /* The OpenGL extension GL_NV_vertex_array_range adds wgl/glX functions which aren't exported as 'real' wgl/glX extensions. */
3008     if (has_extension(WineGLInfo.glExtensions, "GL_NV_vertex_array_range"))
3009     {
3010         register_extension( "WGL_NV_vertex_array_range" );
3011         opengl_funcs.ext.p_wglAllocateMemoryNV = pglXAllocateMemoryNV;
3012         opengl_funcs.ext.p_wglFreeMemoryNV = pglXFreeMemoryNV;
3013     }
3014
3015     /* WINE-specific WGL Extensions */
3016
3017     /* In WineD3D we need the ability to set the pixel format more than once (e.g. after a device reset).
3018      * The default wglSetPixelFormat doesn't allow this, so add our own which allows it.
3019      */
3020     register_extension( "WGL_WINE_pixel_format_passthrough" );
3021     opengl_funcs.ext.p_wglSetPixelFormatWINE = X11DRV_wglSetPixelFormatWINE;
3022 }
3023
3024
3025 /**
3026  * glxdrv_SwapBuffers
3027  *
3028  * Swap the buffers of this DC
3029  */
3030 static BOOL glxdrv_wglSwapBuffers( HDC hdc )
3031 {
3032     enum x11drv_escape_codes code = X11DRV_FLUSH_GL_DRAWABLE;
3033     struct gl_drawable *gl;
3034     struct wgl_context *ctx = NtCurrentTeb()->glContext;
3035
3036     TRACE("(%p)\n", hdc);
3037
3038     if (!(gl = get_gl_drawable( WindowFromDC( hdc ), hdc )))
3039     {
3040         SetLastError( ERROR_INVALID_HANDLE );
3041         return FALSE;
3042     }
3043
3044     switch (gl->type)
3045     {
3046     case DC_GL_PIXMAP_WIN:
3047         if (ctx) sync_context( ctx );
3048         if (pglXCopySubBufferMESA) {
3049             /* (glX)SwapBuffers has an implicit glFlush effect, however
3050              * GLX_MESA_copy_sub_buffer doesn't. Make sure GL is flushed before
3051              * copying */
3052             pglFlush();
3053             pglXCopySubBufferMESA( gdi_display, gl->drawable, 0, 0,
3054                                    gl->rect.right - gl->rect.left, gl->rect.bottom - gl->rect.top );
3055             break;
3056         }
3057         /* fall through */
3058     default:
3059         pglXSwapBuffers(gdi_display, gl->drawable);
3060         break;
3061     }
3062
3063     release_gl_drawable( gl );
3064
3065     ExtEscape( hdc, X11DRV_ESCAPE, sizeof(code), (LPSTR)&code, 0, NULL );
3066
3067     return TRUE;
3068 }
3069
3070 static BOOL create_glx_dc( PHYSDEV *pdev )
3071 {
3072     /* assume that only the main x11 device implements GetDeviceCaps */
3073     X11DRV_PDEVICE *x11dev = get_x11drv_dev( GET_NEXT_PHYSDEV( *pdev, pGetDeviceCaps ));
3074     struct glx_physdev *physdev = HeapAlloc( GetProcessHeap(), HEAP_ZERO_MEMORY, sizeof(*physdev) );
3075
3076     if (!physdev) return FALSE;
3077     physdev->x11dev = x11dev;
3078     push_dc_driver( pdev, &physdev->dev, &glxdrv_funcs );
3079     return TRUE;
3080 }
3081
3082 /**********************************************************************
3083  *           glxdrv_CreateDC
3084  */
3085 static BOOL glxdrv_CreateDC( PHYSDEV *pdev, LPCWSTR driver, LPCWSTR device,
3086                              LPCWSTR output, const DEVMODEW* initData )
3087 {
3088     return create_glx_dc( pdev );
3089 }
3090
3091 /**********************************************************************
3092  *           glxdrv_CreateCompatibleDC
3093  */
3094 static BOOL glxdrv_CreateCompatibleDC( PHYSDEV orig, PHYSDEV *pdev )
3095 {
3096     if (orig)  /* chain to next driver first */
3097     {
3098         orig = GET_NEXT_PHYSDEV( orig, pCreateCompatibleDC );
3099         if (!orig->funcs->pCreateCompatibleDC( orig, pdev )) return FALSE;
3100     }
3101     /* otherwise we have been called by x11drv */
3102     return create_glx_dc( pdev );
3103 }
3104
3105 /**********************************************************************
3106  *           glxdrv_DeleteDC
3107  */
3108 static BOOL glxdrv_DeleteDC( PHYSDEV dev )
3109 {
3110     struct glx_physdev *physdev = get_glxdrv_dev( dev );
3111     HeapFree( GetProcessHeap(), 0, physdev );
3112     return TRUE;
3113 }
3114
3115 /**********************************************************************
3116  *           glxdrv_ExtEscape
3117  */
3118 static INT glxdrv_ExtEscape( PHYSDEV dev, INT escape, INT in_count, LPCVOID in_data,
3119                              INT out_count, LPVOID out_data )
3120 {
3121     struct glx_physdev *physdev = get_glxdrv_dev( dev );
3122
3123     dev = GET_NEXT_PHYSDEV( dev, pExtEscape );
3124
3125     if (escape == X11DRV_ESCAPE && in_data && in_count >= sizeof(enum x11drv_escape_codes))
3126     {
3127         switch (*(const enum x11drv_escape_codes *)in_data)
3128         {
3129         case X11DRV_SET_DRAWABLE:
3130             if (in_count >= sizeof(struct x11drv_escape_set_drawable))
3131             {
3132                 struct gl_drawable *gl;
3133                 const struct x11drv_escape_set_drawable *data = in_data;
3134
3135                 if ((gl = get_gl_drawable( data->hwnd, dev->hdc )))
3136                 {
3137                     physdev->format       = gl->format;
3138                     physdev->type         = gl->type;
3139                     physdev->drawable     = gl->drawable;
3140                     physdev->pixmap       = gl->pixmap;
3141                     release_gl_drawable( gl );
3142                 }
3143                 else
3144                 {
3145                     physdev->format       = NULL;
3146                     physdev->type         = DC_GL_NONE;
3147                     physdev->drawable     = 0;
3148                     physdev->pixmap       = 0;
3149                 }
3150                 TRACE( "SET_DRAWABLE hdc %p drawable %lx pf %p type %u\n",
3151                        dev->hdc, physdev->drawable, physdev->format, physdev->type );
3152             }
3153             break;
3154         case X11DRV_GET_DRAWABLE:
3155             if (out_count >= sizeof(struct x11drv_escape_get_drawable))
3156             {
3157                 struct x11drv_escape_get_drawable *data = out_data;
3158                 data->pixel_format = physdev->format ? physdev->format - pixel_formats + 1 : 0;
3159                 data->gl_drawable  = physdev->drawable;
3160             }
3161             break;
3162         case X11DRV_FLUSH_GL_DRAWABLE:
3163             flush_gl_drawable( physdev );
3164             return TRUE;
3165         default:
3166             break;
3167         }
3168     }
3169     return dev->funcs->pExtEscape( dev, escape, in_count, in_data, out_count, out_data );
3170 }
3171
3172 /**********************************************************************
3173  *           glxdrv_wine_get_wgl_driver
3174  */
3175 static struct opengl_funcs * glxdrv_wine_get_wgl_driver( PHYSDEV dev, UINT version )
3176 {
3177     if (version != WINE_WGL_DRIVER_VERSION)
3178     {
3179         ERR( "version mismatch, opengl32 wants %u but driver has %u\n", version, WINE_WGL_DRIVER_VERSION );
3180         return NULL;
3181     }
3182
3183     if (has_opengl()) return &opengl_funcs;
3184
3185     dev = GET_NEXT_PHYSDEV( dev, wine_get_wgl_driver );
3186     return dev->funcs->wine_get_wgl_driver( dev, version );
3187 }
3188
3189 static const struct gdi_dc_funcs glxdrv_funcs =
3190 {
3191     NULL,                               /* pAbortDoc */
3192     NULL,                               /* pAbortPath */
3193     NULL,                               /* pAlphaBlend */
3194     NULL,                               /* pAngleArc */
3195     NULL,                               /* pArc */
3196     NULL,                               /* pArcTo */
3197     NULL,                               /* pBeginPath */
3198     NULL,                               /* pBlendImage */
3199     NULL,                               /* pChord */
3200     NULL,                               /* pCloseFigure */
3201     glxdrv_CreateCompatibleDC,          /* pCreateCompatibleDC */
3202     glxdrv_CreateDC,                    /* pCreateDC */
3203     glxdrv_DeleteDC,                    /* pDeleteDC */
3204     NULL,                               /* pDeleteObject */
3205     NULL,                               /* pDeviceCapabilities */
3206     NULL,                               /* pEllipse */
3207     NULL,                               /* pEndDoc */
3208     NULL,                               /* pEndPage */
3209     NULL,                               /* pEndPath */
3210     NULL,                               /* pEnumFonts */
3211     NULL,                               /* pEnumICMProfiles */
3212     NULL,                               /* pExcludeClipRect */
3213     NULL,                               /* pExtDeviceMode */
3214     glxdrv_ExtEscape,                   /* pExtEscape */
3215     NULL,                               /* pExtFloodFill */
3216     NULL,                               /* pExtSelectClipRgn */
3217     NULL,                               /* pExtTextOut */
3218     NULL,                               /* pFillPath */
3219     NULL,                               /* pFillRgn */
3220     NULL,                               /* pFlattenPath */
3221     NULL,                               /* pFontIsLinked */
3222     NULL,                               /* pFrameRgn */
3223     NULL,                               /* pGdiComment */
3224     NULL,                               /* pGdiRealizationInfo */
3225     NULL,                               /* pGetBoundsRect */
3226     NULL,                               /* pGetCharABCWidths */
3227     NULL,                               /* pGetCharABCWidthsI */
3228     NULL,                               /* pGetCharWidth */
3229     NULL,                               /* pGetDeviceCaps */
3230     NULL,                               /* pGetDeviceGammaRamp */
3231     NULL,                               /* pGetFontData */
3232     NULL,                               /* pGetFontUnicodeRanges */
3233     NULL,                               /* pGetGlyphIndices */
3234     NULL,                               /* pGetGlyphOutline */
3235     NULL,                               /* pGetICMProfile */
3236     NULL,                               /* pGetImage */
3237     NULL,                               /* pGetKerningPairs */
3238     NULL,                               /* pGetNearestColor */
3239     NULL,                               /* pGetOutlineTextMetrics */
3240     NULL,                               /* pGetPixel */
3241     NULL,                               /* pGetSystemPaletteEntries */
3242     NULL,                               /* pGetTextCharsetInfo */
3243     NULL,                               /* pGetTextExtentExPoint */
3244     NULL,                               /* pGetTextExtentExPointI */
3245     NULL,                               /* pGetTextFace */
3246     NULL,                               /* pGetTextMetrics */
3247     NULL,                               /* pGradientFill */
3248     NULL,                               /* pIntersectClipRect */
3249     NULL,                               /* pInvertRgn */
3250     NULL,                               /* pLineTo */
3251     NULL,                               /* pModifyWorldTransform */
3252     NULL,                               /* pMoveTo */
3253     NULL,                               /* pOffsetClipRgn */
3254     NULL,                               /* pOffsetViewportOrg */
3255     NULL,                               /* pOffsetWindowOrg */
3256     NULL,                               /* pPaintRgn */
3257     NULL,                               /* pPatBlt */
3258     NULL,                               /* pPie */
3259     NULL,                               /* pPolyBezier */
3260     NULL,                               /* pPolyBezierTo */
3261     NULL,                               /* pPolyDraw */
3262     NULL,                               /* pPolyPolygon */
3263     NULL,                               /* pPolyPolyline */
3264     NULL,                               /* pPolygon */
3265     NULL,                               /* pPolyline */
3266     NULL,                               /* pPolylineTo */
3267     NULL,                               /* pPutImage */
3268     NULL,                               /* pRealizeDefaultPalette */
3269     NULL,                               /* pRealizePalette */
3270     NULL,                               /* pRectangle */
3271     NULL,                               /* pResetDC */
3272     NULL,                               /* pRestoreDC */
3273     NULL,                               /* pRoundRect */
3274     NULL,                               /* pSaveDC */
3275     NULL,                               /* pScaleViewportExt */
3276     NULL,                               /* pScaleWindowExt */
3277     NULL,                               /* pSelectBitmap */
3278     NULL,                               /* pSelectBrush */
3279     NULL,                               /* pSelectClipPath */
3280     NULL,                               /* pSelectFont */
3281     NULL,                               /* pSelectPalette */
3282     NULL,                               /* pSelectPen */
3283     NULL,                               /* pSetArcDirection */
3284     NULL,                               /* pSetBkColor */
3285     NULL,                               /* pSetBkMode */
3286     NULL,                               /* pSetBoundsRect */
3287     NULL,                               /* pSetDCBrushColor */
3288     NULL,                               /* pSetDCPenColor */
3289     NULL,                               /* pSetDIBitsToDevice */
3290     NULL,                               /* pSetDeviceClipping */
3291     NULL,                               /* pSetDeviceGammaRamp */
3292     NULL,                               /* pSetLayout */
3293     NULL,                               /* pSetMapMode */
3294     NULL,                               /* pSetMapperFlags */
3295     NULL,                               /* pSetPixel */
3296     NULL,                               /* pSetPolyFillMode */
3297     NULL,                               /* pSetROP2 */
3298     NULL,                               /* pSetRelAbs */
3299     NULL,                               /* pSetStretchBltMode */
3300     NULL,                               /* pSetTextAlign */
3301     NULL,                               /* pSetTextCharacterExtra */
3302     NULL,                               /* pSetTextColor */
3303     NULL,                               /* pSetTextJustification */
3304     NULL,                               /* pSetViewportExt */
3305     NULL,                               /* pSetViewportOrg */
3306     NULL,                               /* pSetWindowExt */
3307     NULL,                               /* pSetWindowOrg */
3308     NULL,                               /* pSetWorldTransform */
3309     NULL,                               /* pStartDoc */
3310     NULL,                               /* pStartPage */
3311     NULL,                               /* pStretchBlt */
3312     NULL,                               /* pStretchDIBits */
3313     NULL,                               /* pStrokeAndFillPath */
3314     NULL,                               /* pStrokePath */
3315     NULL,                               /* pUnrealizePalette */
3316     NULL,                               /* pWidenPath */
3317     glxdrv_wine_get_wgl_driver,         /* wine_get_wgl_driver */
3318     GDI_PRIORITY_GRAPHICS_DRV + 20      /* priority */
3319 };
3320
3321 static struct opengl_funcs opengl_funcs =
3322 {
3323     {
3324         glxdrv_wglCopyContext,              /* p_wglCopyContext */
3325         glxdrv_wglCreateContext,            /* p_wglCreateContext */
3326         glxdrv_wglDeleteContext,            /* p_wglDeleteContext */
3327         glxdrv_wglDescribePixelFormat,      /* p_wglDescribePixelFormat */
3328         glxdrv_wglGetPixelFormat,           /* p_wglGetPixelFormat */
3329         glxdrv_wglGetProcAddress,           /* p_wglGetProcAddress */
3330         glxdrv_wglMakeCurrent,              /* p_wglMakeCurrent */
3331         glxdrv_wglSetPixelFormat,           /* p_wglSetPixelFormat */
3332         glxdrv_wglShareLists,               /* p_wglShareLists */
3333         glxdrv_wglSwapBuffers,              /* p_wglSwapBuffers */
3334     }
3335 };
3336
3337 const struct gdi_dc_funcs *get_glx_driver(void)
3338 {
3339     return &glxdrv_funcs;
3340 }
3341
3342 #else  /* no OpenGL includes */
3343
3344 const struct gdi_dc_funcs *get_glx_driver(void)
3345 {
3346     return NULL;
3347 }
3348
3349 BOOL set_win_format( HWND hwnd, XID fbconfig_id )
3350 {
3351     return FALSE;
3352 }
3353
3354 BOOL has_gl_drawable( HWND hwnd )
3355 {
3356     return FALSE;
3357 }
3358
3359 void sync_gl_drawable( HWND hwnd, const RECT *visible_rect, const RECT *client_rect )
3360 {
3361 }
3362
3363 void destroy_gl_drawable( HWND hwnd )
3364 {
3365 }
3366
3367 #endif /* defined(SONAME_LIBGL) */