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