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