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