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