mshtml: Return referenced object in get_node_obj.
[wine] / dlls / opengl32 / wgl.c
1 /* Window-specific OpenGL functions implementation.
2  *
3  * Copyright (c) 1999 Lionel Ulmer
4  * Copyright (c) 2005 Raphael Junqueira
5  *
6  * This library is free software; you can redistribute it and/or
7  * modify it under the terms of the GNU Lesser General Public
8  * License as published by the Free Software Foundation; either
9  * version 2.1 of the License, or (at your option) any later version.
10  *
11  * This library is distributed in the hope that it will be useful,
12  * but WITHOUT ANY WARRANTY; without even the implied warranty of
13  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
14  * Lesser General Public License for more details.
15  *
16  * You should have received a copy of the GNU Lesser General Public
17  * License along with this library; if not, write to the Free Software
18  * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA
19  */
20
21 #include "config.h"
22 #include "wine/port.h"
23
24 #include <stdarg.h>
25 #include <stdlib.h>
26 #include <string.h>
27
28 #include "windef.h"
29 #include "winbase.h"
30 #include "winuser.h"
31 #include "winreg.h"
32 #include "wingdi.h"
33 #include "winternl.h"
34 #include "winnt.h"
35
36 #include "opengl_ext.h"
37 #ifdef HAVE_GL_GLU_H
38 #undef far
39 #undef near
40 #include <GL/glu.h>
41 #endif
42 #include "wine/gdi_driver.h"
43 #include "wine/library.h"
44 #include "wine/debug.h"
45
46 WINE_DEFAULT_DEBUG_CHANNEL(wgl);
47 WINE_DECLARE_DEBUG_CHANNEL(opengl);
48
49 static struct
50 {
51     /* internal WGL functions */
52     void  (WINAPI *p_wglFinish)(void);
53     void  (WINAPI *p_wglFlush)(void);
54     void  (WINAPI *p_wglGetIntegerv)(GLenum pname, GLint* params);
55 } wine_wgl;
56
57 static const struct wgl_funcs *wgl_driver;
58
59 #ifdef SONAME_LIBGLU
60 #define MAKE_FUNCPTR(f) static typeof(f) * p##f;
61 MAKE_FUNCPTR(gluNewTess)
62 MAKE_FUNCPTR(gluDeleteTess)
63 MAKE_FUNCPTR(gluTessBeginContour)
64 MAKE_FUNCPTR(gluTessBeginPolygon)
65 MAKE_FUNCPTR(gluTessCallback)
66 MAKE_FUNCPTR(gluTessEndContour)
67 MAKE_FUNCPTR(gluTessEndPolygon)
68 MAKE_FUNCPTR(gluTessVertex)
69 #undef MAKE_FUNCPTR
70 #endif /* SONAME_LIBGLU */
71
72 static HMODULE opengl32_handle;
73 static void* libglu_handle = NULL;
74
75 const GLubyte * WINAPI wine_glGetString( GLenum name );
76
77 /* internal GDI functions */
78 extern INT WINAPI GdiDescribePixelFormat( HDC hdc, INT fmt, UINT size, PIXELFORMATDESCRIPTOR *pfd );
79 extern BOOL WINAPI GdiSetPixelFormat( HDC hdc, INT fmt, const PIXELFORMATDESCRIPTOR *pfd );
80 extern BOOL WINAPI GdiSwapBuffers( HDC hdc );
81
82 /***********************************************************************
83  *               wglSetPixelFormat(OPENGL32.@)
84  */
85 BOOL WINAPI wglSetPixelFormat( HDC hdc, INT iPixelFormat,
86                                const PIXELFORMATDESCRIPTOR *ppfd)
87 {
88     return GdiSetPixelFormat(hdc, iPixelFormat, ppfd);
89 }
90
91 /***********************************************************************
92  *              wglCopyContext (OPENGL32.@)
93  */
94 BOOL WINAPI wglCopyContext(HGLRC hglrcSrc, HGLRC hglrcDst, UINT mask)
95 {
96     if (!hglrcSrc || !hglrcDst)
97     {
98         SetLastError(ERROR_INVALID_HANDLE);
99         return FALSE;
100     }
101     return wgl_driver->p_wglCopyContext(hglrcSrc, hglrcDst, mask);
102 }
103
104 /***********************************************************************
105  *              wglDeleteContext (OPENGL32.@)
106  */
107 BOOL WINAPI wglDeleteContext(HGLRC hglrc)
108 {
109     if (!hglrc)
110     {
111         SetLastError(ERROR_INVALID_HANDLE);
112         return FALSE;
113     }
114     return wgl_driver->p_wglDeleteContext(hglrc);
115 }
116
117 /***********************************************************************
118  *              wglMakeCurrent (OPENGL32.@)
119  */
120 BOOL WINAPI wglMakeCurrent(HDC hdc, HGLRC hglrc)
121 {
122     if (!hglrc && !hdc && !NtCurrentTeb()->glContext)
123     {
124         SetLastError( ERROR_INVALID_HANDLE );
125         return FALSE;
126     }
127     return wgl_driver->p_wglMakeCurrent(hdc, hglrc);
128 }
129
130 /***********************************************************************
131  *              wglCreateContextAttribsARB  (wrapper for the extension function returned by the driver)
132  */
133 static HGLRC WINAPI wglCreateContextAttribsARB( HDC hdc, HGLRC share, const int *attribs )
134 {
135     return wgl_driver->p_wglCreateContextAttribsARB( hdc, share, attribs );
136 }
137
138 /***********************************************************************
139  *              wglMakeContextCurrentARB  (wrapper for the extension function returned by the driver)
140  */
141 static BOOL WINAPI wglMakeContextCurrentARB( HDC draw_hdc, HDC read_hdc, HGLRC hglrc )
142 {
143     return wgl_driver->p_wglMakeContextCurrentARB( draw_hdc, read_hdc, hglrc );
144 }
145
146 /***********************************************************************
147  *              wglShareLists (OPENGL32.@)
148  */
149 BOOL WINAPI wglShareLists(HGLRC hglrc1, HGLRC hglrc2)
150 {
151     if (!hglrc1 || !hglrc2)
152     {
153         SetLastError(ERROR_INVALID_HANDLE);
154         return FALSE;
155     }
156     return wgl_driver->p_wglShareLists(hglrc1, hglrc2);
157 }
158
159 /***********************************************************************
160  *              wglGetCurrentDC (OPENGL32.@)
161  */
162 HDC WINAPI wglGetCurrentDC(void)
163 {
164   return wgl_driver->p_wglGetCurrentDC();
165 }
166
167 /***********************************************************************
168  *              wglCreateContext (OPENGL32.@)
169  */
170 HGLRC WINAPI wglCreateContext(HDC hdc)
171 {
172     return wgl_driver->p_wglCreateContext(hdc);
173 }
174
175 /***********************************************************************
176  *              wglGetCurrentContext (OPENGL32.@)
177  */
178 HGLRC WINAPI wglGetCurrentContext(void)
179 {
180     return NtCurrentTeb()->glContext;
181 }
182
183 /***********************************************************************
184  *              wglChoosePixelFormat (OPENGL32.@)
185  */
186 INT WINAPI wglChoosePixelFormat(HDC hdc, const PIXELFORMATDESCRIPTOR* ppfd)
187 {
188     PIXELFORMATDESCRIPTOR format, best;
189     int i, count, best_format;
190     int bestDBuffer = -1, bestStereo = -1;
191
192     TRACE_(wgl)( "%p %p: size %u version %u flags %u type %u color %u %u,%u,%u,%u "
193                  "accum %u depth %u stencil %u aux %u\n",
194                  hdc, ppfd, ppfd->nSize, ppfd->nVersion, ppfd->dwFlags, ppfd->iPixelType,
195                  ppfd->cColorBits, ppfd->cRedBits, ppfd->cGreenBits, ppfd->cBlueBits, ppfd->cAlphaBits,
196                  ppfd->cAccumBits, ppfd->cDepthBits, ppfd->cStencilBits, ppfd->cAuxBuffers );
197
198     count = GdiDescribePixelFormat( hdc, 0, 0, NULL );
199     if (!count) return 0;
200
201     best_format = 0;
202     best.dwFlags = 0;
203     best.cAlphaBits = -1;
204     best.cColorBits = -1;
205     best.cDepthBits = -1;
206     best.cStencilBits = -1;
207     best.cAuxBuffers = -1;
208
209     for (i = 1; i <= count; i++)
210     {
211         if (!GdiDescribePixelFormat( hdc, i, sizeof(format), &format )) continue;
212
213         if (ppfd->iPixelType != format.iPixelType)
214         {
215             TRACE( "pixel type mismatch for iPixelFormat=%d\n", i );
216             continue;
217         }
218
219         /* only use bitmap capable for formats for bitmap rendering */
220         if( (ppfd->dwFlags & PFD_DRAW_TO_BITMAP) != (format.dwFlags & PFD_DRAW_TO_BITMAP))
221         {
222             TRACE( "PFD_DRAW_TO_BITMAP mismatch for iPixelFormat=%d\n", i );
223             continue;
224         }
225
226         /* The behavior of PDF_STEREO/PFD_STEREO_DONTCARE and PFD_DOUBLEBUFFER / PFD_DOUBLEBUFFER_DONTCARE
227          * is not very clear on MSDN. They specify that ChoosePixelFormat tries to match pixel formats
228          * with the flag (PFD_STEREO / PFD_DOUBLEBUFFERING) set. Otherwise it says that it tries to match
229          * formats without the given flag set.
230          * A test on Windows using a Radeon 9500pro on WinXP (the driver doesn't support Stereo)
231          * has indicated that a format without stereo is returned when stereo is unavailable.
232          * So in case PFD_STEREO is set, formats that support it should have priority above formats
233          * without. In case PFD_STEREO_DONTCARE is set, stereo is ignored.
234          *
235          * To summarize the following is most likely the correct behavior:
236          * stereo not set -> prefer non-stereo formats, but also accept stereo formats
237          * stereo set -> prefer stereo formats, but also accept non-stereo formats
238          * stereo don't care -> it doesn't matter whether we get stereo or not
239          *
240          * In Wine we will treat non-stereo the same way as don't care because it makes
241          * format selection even more complicated and second drivers with Stereo advertise
242          * each format twice anyway.
243          */
244
245         /* Doublebuffer, see the comments above */
246         if (!(ppfd->dwFlags & PFD_DOUBLEBUFFER_DONTCARE))
247         {
248             if (((ppfd->dwFlags & PFD_DOUBLEBUFFER) != bestDBuffer) &&
249                 ((format.dwFlags & PFD_DOUBLEBUFFER) == (ppfd->dwFlags & PFD_DOUBLEBUFFER)))
250                 goto found;
251
252             if (bestDBuffer != -1 && (format.dwFlags & PFD_DOUBLEBUFFER) != bestDBuffer) continue;
253         }
254
255         /* Stereo, see the comments above. */
256         if (!(ppfd->dwFlags & PFD_STEREO_DONTCARE))
257         {
258             if (((ppfd->dwFlags & PFD_STEREO) != bestStereo) &&
259                 ((format.dwFlags & PFD_STEREO) == (ppfd->dwFlags & PFD_STEREO)))
260                 goto found;
261
262             if (bestStereo != -1 && (format.dwFlags & PFD_STEREO) != bestStereo) continue;
263         }
264
265         /* Below we will do a number of checks to select the 'best' pixelformat.
266          * We assume the precedence cColorBits > cAlphaBits > cDepthBits > cStencilBits -> cAuxBuffers.
267          * The code works by trying to match the most important options as close as possible.
268          * When a reasonable format is found, we will try to match more options.
269          * It appears (see the opengl32 test) that Windows opengl drivers ignore options
270          * like cColorBits, cAlphaBits and friends if they are set to 0, so they are considered
271          * as DONTCARE. At least Serious Sam TSE relies on this behavior. */
272
273         if (ppfd->cColorBits)
274         {
275             if (((ppfd->cColorBits > best.cColorBits) && (format.cColorBits > best.cColorBits)) ||
276                 ((format.cColorBits >= ppfd->cColorBits) && (format.cColorBits < best.cColorBits)))
277                 goto found;
278
279             if (best.cColorBits != format.cColorBits)  /* Do further checks if the format is compatible */
280             {
281                 TRACE( "color mismatch for iPixelFormat=%d\n", i );
282                 continue;
283             }
284         }
285         if (ppfd->cAlphaBits)
286         {
287             if (((ppfd->cAlphaBits > best.cAlphaBits) && (format.cAlphaBits > best.cAlphaBits)) ||
288                 ((format.cAlphaBits >= ppfd->cAlphaBits) && (format.cAlphaBits < best.cAlphaBits)))
289                 goto found;
290
291             if (best.cAlphaBits != format.cAlphaBits)
292             {
293                 TRACE( "alpha mismatch for iPixelFormat=%d\n", i );
294                 continue;
295             }
296         }
297         if (ppfd->cDepthBits)
298         {
299             if (((ppfd->cDepthBits > best.cDepthBits) && (format.cDepthBits > best.cDepthBits)) ||
300                 ((format.cDepthBits >= ppfd->cDepthBits) && (format.cDepthBits < best.cDepthBits)))
301                 goto found;
302
303             if (best.cDepthBits != format.cDepthBits)
304             {
305                 TRACE( "depth mismatch for iPixelFormat=%d\n", i );
306                 continue;
307             }
308         }
309         if (ppfd->cStencilBits)
310         {
311             if (((ppfd->cStencilBits > best.cStencilBits) && (format.cStencilBits > best.cStencilBits)) ||
312                 ((format.cStencilBits >= ppfd->cStencilBits) && (format.cStencilBits < best.cStencilBits)))
313                 goto found;
314
315             if (best.cStencilBits != format.cStencilBits)
316             {
317                 TRACE( "stencil mismatch for iPixelFormat=%d\n", i );
318                 continue;
319             }
320         }
321         if (ppfd->cAuxBuffers)
322         {
323             if (((ppfd->cAuxBuffers > best.cAuxBuffers) && (format.cAuxBuffers > best.cAuxBuffers)) ||
324                 ((format.cAuxBuffers >= ppfd->cAuxBuffers) && (format.cAuxBuffers < best.cAuxBuffers)))
325                 goto found;
326
327             if (best.cAuxBuffers != format.cAuxBuffers)
328             {
329                 TRACE( "aux mismatch for iPixelFormat=%d\n", i );
330                 continue;
331             }
332         }
333         continue;
334
335     found:
336         best_format = i;
337         best = format;
338         bestDBuffer = format.dwFlags & PFD_DOUBLEBUFFER;
339         bestStereo = format.dwFlags & PFD_STEREO;
340     }
341
342     TRACE( "returning %u\n", best_format );
343     return best_format;
344 }
345
346 /***********************************************************************
347  *              wglDescribePixelFormat (OPENGL32.@)
348  */
349 INT WINAPI wglDescribePixelFormat(HDC hdc, INT iPixelFormat, UINT nBytes,
350                                 LPPIXELFORMATDESCRIPTOR ppfd)
351 {
352   return GdiDescribePixelFormat(hdc, iPixelFormat, nBytes, ppfd);
353 }
354
355 /***********************************************************************
356  *              wglGetPixelFormat (OPENGL32.@)
357  */
358 INT WINAPI wglGetPixelFormat(HDC hdc)
359 {
360     return wgl_driver->p_GetPixelFormat( hdc );
361 }
362
363 /***********************************************************************
364  *              wglCreateLayerContext (OPENGL32.@)
365  */
366 HGLRC WINAPI wglCreateLayerContext(HDC hdc,
367                                    int iLayerPlane) {
368   TRACE("(%p,%d)\n", hdc, iLayerPlane);
369
370   if (iLayerPlane == 0) {
371       return wglCreateContext(hdc);
372   }
373   FIXME("no handler for layer %d\n", iLayerPlane);
374
375   return NULL;
376 }
377
378 /***********************************************************************
379  *              wglDescribeLayerPlane (OPENGL32.@)
380  */
381 BOOL WINAPI wglDescribeLayerPlane(HDC hdc,
382                                   int iPixelFormat,
383                                   int iLayerPlane,
384                                   UINT nBytes,
385                                   LPLAYERPLANEDESCRIPTOR plpd) {
386   FIXME("(%p,%d,%d,%d,%p)\n", hdc, iPixelFormat, iLayerPlane, nBytes, plpd);
387
388   return FALSE;
389 }
390
391 /***********************************************************************
392  *              wglGetLayerPaletteEntries (OPENGL32.@)
393  */
394 int WINAPI wglGetLayerPaletteEntries(HDC hdc,
395                                      int iLayerPlane,
396                                      int iStart,
397                                      int cEntries,
398                                      const COLORREF *pcr) {
399   FIXME("(): stub!\n");
400
401   return 0;
402 }
403
404 /* check if the extension is present in the list */
405 static BOOL has_extension( const char *list, const char *ext )
406 {
407     size_t len = strlen( ext );
408
409     while (list)
410     {
411         while (*list == ' ') list++;
412         if (!strncmp( list, ext, len ) && (!list[len] || list[len] == ' ')) return TRUE;
413         list = strchr( list, ' ' );
414     }
415     return FALSE;
416 }
417
418 static int compar(const void *elt_a, const void *elt_b) {
419   return strcmp(((const OpenGL_extension *) elt_a)->name,
420                 ((const OpenGL_extension *) elt_b)->name);
421 }
422
423 /* Check if a GL extension is supported */
424 static BOOL is_extension_supported(const char* extension)
425 {
426     const char *gl_ext_string = (const char*)wine_glGetString(GL_EXTENSIONS);
427
428     TRACE("Checking for extension '%s'\n", extension);
429
430     if(!gl_ext_string) {
431         ERR("No OpenGL extensions found, check if your OpenGL setup is correct!\n");
432         return FALSE;
433     }
434
435     /* We use the GetProcAddress function from the display driver to retrieve function pointers
436      * for OpenGL and WGL extensions. In case of winex11.drv the OpenGL extension lookup is done
437      * using glXGetProcAddress. This function is quite unreliable in the sense that its specs don't
438      * require the function to return NULL when an extension isn't found. For this reason we check
439      * if the OpenGL extension required for the function we are looking up is supported. */
440
441     /* Check if the extension is part of the GL extension string to see if it is supported. */
442     if (has_extension(gl_ext_string, extension))
443         return TRUE;
444
445     /* In general an OpenGL function starts as an ARB/EXT extension and at some stage
446      * it becomes part of the core OpenGL library and can be reached without the ARB/EXT
447      * suffix as well. In the extension table, these functions contain GL_VERSION_major_minor.
448      * Check if we are searching for a core GL function */
449     if(strncmp(extension, "GL_VERSION_", 11) == 0)
450     {
451         const GLubyte *gl_version = glGetString(GL_VERSION);
452         const char *version = extension + 11; /* Move past 'GL_VERSION_' */
453
454         if(!gl_version) {
455             ERR("No OpenGL version found!\n");
456             return FALSE;
457         }
458
459         /* Compare the major/minor version numbers of the native OpenGL library and what is required by the function.
460          * The gl_version string is guaranteed to have at least a major/minor and sometimes it has a release number as well. */
461         if( (gl_version[0] >= version[0]) || ((gl_version[0] == version[0]) && (gl_version[2] >= version[2])) ) {
462             return TRUE;
463         }
464         WARN("The function requires OpenGL version '%c.%c' while your drivers only provide '%c.%c'\n", version[0], version[2], gl_version[0], gl_version[2]);
465     }
466
467     return FALSE;
468 }
469
470 static const OpenGL_extension wgl_extensions[] =
471 {
472     { "wglCreateContextAttribsARB", "WGL_ARB_create_context", wglCreateContextAttribsARB },
473     { "wglMakeContextCurrentARB", "WGL_ARB_make_current_read", wglMakeContextCurrentARB },
474 };
475
476 /***********************************************************************
477  *              wglGetProcAddress (OPENGL32.@)
478  */
479 PROC WINAPI wglGetProcAddress(LPCSTR  lpszProc) {
480   void *local_func;
481   OpenGL_extension  ext;
482   const OpenGL_extension *ext_ret;
483
484   TRACE("(%s)\n", lpszProc);
485
486   if (lpszProc == NULL)
487     return NULL;
488
489   /* Without an active context opengl32 doesn't know to what
490    * driver it has to dispatch wglGetProcAddress.
491    */
492   if (wglGetCurrentContext() == NULL)
493   {
494     WARN("No active WGL context found\n");
495     return NULL;
496   }
497
498   /* Search in the thunks to find the real name of the extension */
499   ext.name = lpszProc;
500   ext_ret = bsearch(&ext, extension_registry, extension_registry_size,
501                     sizeof(OpenGL_extension), compar);
502
503   /* If nothing was found, we are looking for a WGL extension or an unknown GL extension. */
504   if (ext_ret == NULL) {
505     /* If the function name starts with a 'w', it is a WGL extension */
506     if(lpszProc[0] == 'w')
507     {
508         local_func = wgl_driver->p_wglGetProcAddress( lpszProc );
509         if (local_func == (void *)1)  /* special function that needs a wrapper */
510         {
511             ext_ret = bsearch( &ext, wgl_extensions, sizeof(wgl_extensions)/sizeof(wgl_extensions[0]),
512                                sizeof(OpenGL_extension), compar );
513             if (ext_ret) return ext_ret->func;
514
515             FIXME( "wrapper missing for %s\n", lpszProc );
516             return NULL;
517         }
518         return local_func;
519     }
520
521     /* We are dealing with an unknown GL extension */
522     WARN("Extension '%s' not defined in opengl32.dll's function table!\n", lpszProc);
523     return NULL;
524   } else { /* We are looking for an OpenGL extension */
525
526     /* Check if the GL extension required by the function is available */
527     if(!is_extension_supported(ext_ret->extension)) {
528         WARN("Extension '%s' required by function '%s' not supported!\n", ext_ret->extension, lpszProc);
529     }
530
531     local_func = wgl_driver->p_wglGetProcAddress(ext_ret->name);
532
533     /* After that, look at the extensions defined in the Linux OpenGL library */
534     if (local_func == NULL) {
535       char buf[256];
536       void *ret = NULL;
537
538       /* Remove the last 3 letters (EXT, ARB, ...).
539
540          I know that some extensions have more than 3 letters (MESA, NV,
541          INTEL, ...), but this is only a stop-gap measure to fix buggy
542          OpenGL drivers (moreover, it is only useful for old 1.0 apps
543          that query the glBindTextureEXT extension).
544       */
545       memcpy(buf, ext_ret->name, strlen(ext_ret->name) - 3);
546       buf[strlen(ext_ret->name) - 3] = '\0';
547       TRACE("Extension not found in the Linux OpenGL library, checking against libGL bug with %s..\n", buf);
548
549       ret = GetProcAddress(opengl32_handle, buf);
550       if (ret != NULL) {
551         TRACE("Found function in main OpenGL library (%p)!\n", ret);
552       } else {
553         WARN("Did not find function %s (%s) in your OpenGL library!\n", lpszProc, ext_ret->name);
554       }
555
556       return ret;
557     } else {
558       TRACE("returning function (%p)\n", ext_ret->func);
559       extension_funcs[ext_ret - extension_registry] = local_func;
560
561       return ext_ret->func;
562     }
563   }
564 }
565
566 /***********************************************************************
567  *              wglRealizeLayerPalette (OPENGL32.@)
568  */
569 BOOL WINAPI wglRealizeLayerPalette(HDC hdc,
570                                    int iLayerPlane,
571                                    BOOL bRealize) {
572   FIXME("()\n");
573
574   return FALSE;
575 }
576
577 /***********************************************************************
578  *              wglSetLayerPaletteEntries (OPENGL32.@)
579  */
580 int WINAPI wglSetLayerPaletteEntries(HDC hdc,
581                                      int iLayerPlane,
582                                      int iStart,
583                                      int cEntries,
584                                      const COLORREF *pcr) {
585   FIXME("(): stub!\n");
586
587   return 0;
588 }
589
590 /***********************************************************************
591  *              wglSwapLayerBuffers (OPENGL32.@)
592  */
593 BOOL WINAPI wglSwapLayerBuffers(HDC hdc,
594                                 UINT fuPlanes) {
595   TRACE_(opengl)("(%p, %08x)\n", hdc, fuPlanes);
596
597   if (fuPlanes & WGL_SWAP_MAIN_PLANE) {
598     if (!GdiSwapBuffers(hdc)) return FALSE;
599     fuPlanes &= ~WGL_SWAP_MAIN_PLANE;
600   }
601
602   if (fuPlanes) {
603     WARN("Following layers unhandled: %08x\n", fuPlanes);
604   }
605
606   return TRUE;
607 }
608
609 /***********************************************************************
610  *              wglUseFontBitmaps_common
611  */
612 static BOOL wglUseFontBitmaps_common( HDC hdc, DWORD first, DWORD count, DWORD listBase, BOOL unicode )
613 {
614      GLYPHMETRICS gm;
615      unsigned int glyph, size = 0;
616      void *bitmap = NULL, *gl_bitmap = NULL;
617      int org_alignment;
618      BOOL ret = TRUE;
619
620      glGetIntegerv(GL_UNPACK_ALIGNMENT, &org_alignment);
621      glPixelStorei(GL_UNPACK_ALIGNMENT, 4);
622
623      for (glyph = first; glyph < first + count; glyph++) {
624          static const MAT2 identity = { {0,1},{0,0},{0,0},{0,1} };
625          unsigned int needed_size, height, width, width_int;
626
627          if (unicode)
628              needed_size = GetGlyphOutlineW(hdc, glyph, GGO_BITMAP, &gm, 0, NULL, &identity);
629          else
630              needed_size = GetGlyphOutlineA(hdc, glyph, GGO_BITMAP, &gm, 0, NULL, &identity);
631
632          TRACE("Glyph: %3d / List: %d size %d\n", glyph, listBase, needed_size);
633          if (needed_size == GDI_ERROR) {
634              ret = FALSE;
635              break;
636          }
637
638          if (needed_size > size) {
639              size = needed_size;
640              HeapFree(GetProcessHeap(), 0, bitmap);
641              HeapFree(GetProcessHeap(), 0, gl_bitmap);
642              bitmap = HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, size);
643              gl_bitmap = HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, size);
644          }
645          if (unicode)
646              ret = (GetGlyphOutlineW(hdc, glyph, GGO_BITMAP, &gm, size, bitmap, &identity) != GDI_ERROR);
647          else
648              ret = (GetGlyphOutlineA(hdc, glyph, GGO_BITMAP, &gm, size, bitmap, &identity) != GDI_ERROR);
649          if (!ret) break;
650
651          if (TRACE_ON(wgl)) {
652              unsigned int bitmask;
653              unsigned char *bitmap_ = bitmap;
654
655              TRACE("  - bbox: %d x %d\n", gm.gmBlackBoxX, gm.gmBlackBoxY);
656              TRACE("  - origin: (%d, %d)\n", gm.gmptGlyphOrigin.x, gm.gmptGlyphOrigin.y);
657              TRACE("  - increment: %d - %d\n", gm.gmCellIncX, gm.gmCellIncY);
658              if (needed_size != 0) {
659                  TRACE("  - bitmap:\n");
660                  for (height = 0; height < gm.gmBlackBoxY; height++) {
661                      TRACE("      ");
662                      for (width = 0, bitmask = 0x80; width < gm.gmBlackBoxX; width++, bitmask >>= 1) {
663                          if (bitmask == 0) {
664                              bitmap_ += 1;
665                              bitmask = 0x80;
666                          }
667                          if (*bitmap_ & bitmask)
668                              TRACE("*");
669                          else
670                              TRACE(" ");
671                      }
672                      bitmap_ += (4 - ((UINT_PTR)bitmap_ & 0x03));
673                      TRACE("\n");
674                  }
675              }
676          }
677
678          /* In OpenGL, the bitmap is drawn from the bottom to the top... So we need to invert the
679          * glyph for it to be drawn properly.
680          */
681          if (needed_size != 0) {
682              width_int = (gm.gmBlackBoxX + 31) / 32;
683              for (height = 0; height < gm.gmBlackBoxY; height++) {
684                  for (width = 0; width < width_int; width++) {
685                      ((int *) gl_bitmap)[(gm.gmBlackBoxY - height - 1) * width_int + width] =
686                      ((int *) bitmap)[height * width_int + width];
687                  }
688              }
689          }
690
691          glNewList(listBase++, GL_COMPILE);
692          if (needed_size != 0) {
693              glBitmap(gm.gmBlackBoxX, gm.gmBlackBoxY,
694                      0 - gm.gmptGlyphOrigin.x, (int) gm.gmBlackBoxY - gm.gmptGlyphOrigin.y,
695                      gm.gmCellIncX, gm.gmCellIncY,
696                      gl_bitmap);
697          } else {
698              /* This is the case of 'empty' glyphs like the space character */
699              glBitmap(0, 0, 0, 0, gm.gmCellIncX, gm.gmCellIncY, NULL);
700          }
701          glEndList();
702      }
703
704      glPixelStorei(GL_UNPACK_ALIGNMENT, org_alignment);
705      HeapFree(GetProcessHeap(), 0, bitmap);
706      HeapFree(GetProcessHeap(), 0, gl_bitmap);
707      return ret;
708 }
709
710 /***********************************************************************
711  *              wglUseFontBitmapsA (OPENGL32.@)
712  */
713 BOOL WINAPI wglUseFontBitmapsA(HDC hdc, DWORD first, DWORD count, DWORD listBase)
714 {
715     return wglUseFontBitmaps_common( hdc, first, count, listBase, FALSE );
716 }
717
718 /***********************************************************************
719  *              wglUseFontBitmapsW (OPENGL32.@)
720  */
721 BOOL WINAPI wglUseFontBitmapsW(HDC hdc, DWORD first, DWORD count, DWORD listBase)
722 {
723     return wglUseFontBitmaps_common( hdc, first, count, listBase, TRUE );
724 }
725
726 #ifdef SONAME_LIBGLU
727
728 static void *load_libglu(void)
729 {
730     static int already_loaded;
731     void *handle;
732
733     if (already_loaded) return libglu_handle;
734     already_loaded = 1;
735
736     TRACE("Trying to load GLU library: %s\n", SONAME_LIBGLU);
737     handle = wine_dlopen(SONAME_LIBGLU, RTLD_NOW, NULL, 0);
738     if (!handle)
739     {
740         WARN("Failed to load %s\n", SONAME_LIBGLU);
741         return NULL;
742     }
743
744 #define LOAD_FUNCPTR(f) if((p##f = wine_dlsym(handle, #f, NULL, 0)) == NULL) goto sym_not_found;
745 LOAD_FUNCPTR(gluNewTess)
746 LOAD_FUNCPTR(gluDeleteTess)
747 LOAD_FUNCPTR(gluTessBeginContour)
748 LOAD_FUNCPTR(gluTessBeginPolygon)
749 LOAD_FUNCPTR(gluTessCallback)
750 LOAD_FUNCPTR(gluTessEndContour)
751 LOAD_FUNCPTR(gluTessEndPolygon)
752 LOAD_FUNCPTR(gluTessVertex)
753 #undef LOAD_FUNCPTR
754     libglu_handle = handle;
755     return handle;
756
757 sym_not_found:
758     WARN("Unable to load function ptrs from libGLU\n");
759     /* Close the library as we won't use it */
760     wine_dlclose(handle, NULL, 0);
761     return NULL;
762 }
763
764 static void fixed_to_double(POINTFX fixed, UINT em_size, GLdouble vertex[3])
765 {
766     vertex[0] = (fixed.x.value + (GLdouble)fixed.x.fract / (1 << 16)) / em_size;  
767     vertex[1] = (fixed.y.value + (GLdouble)fixed.y.fract / (1 << 16)) / em_size;  
768     vertex[2] = 0.0;
769 }
770
771 static void tess_callback_vertex(GLvoid *vertex)
772 {
773     GLdouble *dbl = vertex;
774     TRACE("%f, %f, %f\n", dbl[0], dbl[1], dbl[2]);
775     glVertex3dv(vertex);
776 }
777
778 static void tess_callback_begin(GLenum which)
779 {
780     TRACE("%d\n", which);
781     glBegin(which);
782 }
783
784 static void tess_callback_end(void)
785 {
786     TRACE("\n");
787     glEnd();
788 }
789
790 /***********************************************************************
791  *              wglUseFontOutlines_common
792  */
793 static BOOL wglUseFontOutlines_common(HDC hdc,
794                                       DWORD first,
795                                       DWORD count,
796                                       DWORD listBase,
797                                       FLOAT deviation,
798                                       FLOAT extrusion,
799                                       int format,
800                                       LPGLYPHMETRICSFLOAT lpgmf,
801                                       BOOL unicode)
802 {
803     UINT glyph;
804     const MAT2 identity = {{0,1},{0,0},{0,0},{0,1}};
805     GLUtesselator *tess;
806     LOGFONTW lf;
807     HFONT old_font, unscaled_font;
808     UINT em_size = 1024;
809     RECT rc;
810
811     TRACE("(%p, %d, %d, %d, %f, %f, %d, %p, %s)\n", hdc, first, count,
812           listBase, deviation, extrusion, format, lpgmf, unicode ? "W" : "A");
813
814     if (!load_libglu())
815     {
816         ERR("libGLU is required for this function but isn't loaded\n");
817         return FALSE;
818     }
819
820     tess = pgluNewTess();
821     if(!tess) return FALSE;
822     pgluTessCallback(tess, GLU_TESS_VERTEX, (_GLUfuncptr)tess_callback_vertex);
823     pgluTessCallback(tess, GLU_TESS_BEGIN, (_GLUfuncptr)tess_callback_begin);
824     pgluTessCallback(tess, GLU_TESS_END, tess_callback_end);
825
826     GetObjectW(GetCurrentObject(hdc, OBJ_FONT), sizeof(lf), &lf);
827     rc.left = rc.right = rc.bottom = 0;
828     rc.top = em_size;
829     DPtoLP(hdc, (POINT*)&rc, 2);
830     lf.lfHeight = -abs(rc.top - rc.bottom);
831     lf.lfOrientation = lf.lfEscapement = 0;
832     unscaled_font = CreateFontIndirectW(&lf);
833     old_font = SelectObject(hdc, unscaled_font);
834
835     for (glyph = first; glyph < first + count; glyph++)
836     {
837         DWORD needed;
838         GLYPHMETRICS gm;
839         BYTE *buf;
840         TTPOLYGONHEADER *pph;
841         TTPOLYCURVE *ppc;
842         GLdouble *vertices;
843
844         if(unicode)
845             needed = GetGlyphOutlineW(hdc, glyph, GGO_NATIVE, &gm, 0, NULL, &identity);
846         else
847             needed = GetGlyphOutlineA(hdc, glyph, GGO_NATIVE, &gm, 0, NULL, &identity);
848
849         if(needed == GDI_ERROR)
850             goto error;
851
852         buf = HeapAlloc(GetProcessHeap(), 0, needed);
853         vertices = HeapAlloc(GetProcessHeap(), 0, needed / sizeof(POINTFX) * 3 * sizeof(GLdouble));
854
855         if(unicode)
856             GetGlyphOutlineW(hdc, glyph, GGO_NATIVE, &gm, needed, buf, &identity);
857         else
858             GetGlyphOutlineA(hdc, glyph, GGO_NATIVE, &gm, needed, buf, &identity);
859
860         TRACE("glyph %d\n", glyph);
861
862         if(lpgmf)
863         {
864             lpgmf->gmfBlackBoxX = (float)gm.gmBlackBoxX / em_size;
865             lpgmf->gmfBlackBoxY = (float)gm.gmBlackBoxY / em_size;
866             lpgmf->gmfptGlyphOrigin.x = (float)gm.gmptGlyphOrigin.x / em_size;
867             lpgmf->gmfptGlyphOrigin.y = (float)gm.gmptGlyphOrigin.y / em_size;
868             lpgmf->gmfCellIncX = (float)gm.gmCellIncX / em_size;
869             lpgmf->gmfCellIncY = (float)gm.gmCellIncY / em_size;
870
871             TRACE("%fx%f at %f,%f inc %f,%f\n", lpgmf->gmfBlackBoxX, lpgmf->gmfBlackBoxY,
872                   lpgmf->gmfptGlyphOrigin.x, lpgmf->gmfptGlyphOrigin.y, lpgmf->gmfCellIncX, lpgmf->gmfCellIncY); 
873             lpgmf++;
874         }
875
876         glNewList(listBase++, GL_COMPILE);
877         pgluTessBeginPolygon(tess, NULL);
878
879         pph = (TTPOLYGONHEADER*)buf;
880         while((BYTE*)pph < buf + needed)
881         {
882             TRACE("\tstart %d, %d\n", pph->pfxStart.x.value, pph->pfxStart.y.value);
883
884             pgluTessBeginContour(tess);
885
886             fixed_to_double(pph->pfxStart, em_size, vertices);
887             pgluTessVertex(tess, vertices, vertices);
888             vertices += 3;
889
890             ppc = (TTPOLYCURVE*)((char*)pph + sizeof(*pph));
891             while((char*)ppc < (char*)pph + pph->cb)
892             {
893                 int i;
894
895                 switch(ppc->wType) {
896                 case TT_PRIM_LINE:
897                     for(i = 0; i < ppc->cpfx; i++)
898                     {
899                         TRACE("\t\tline to %d, %d\n", ppc->apfx[i].x.value, ppc->apfx[i].y.value);
900                         fixed_to_double(ppc->apfx[i], em_size, vertices); 
901                         pgluTessVertex(tess, vertices, vertices);
902                         vertices += 3;
903                     }
904                     break;
905
906                 case TT_PRIM_QSPLINE:
907                     for(i = 0; i < ppc->cpfx/2; i++)
908                     {
909                         /* FIXME: just connecting the control points for now */
910                         TRACE("\t\tcurve  %d,%d %d,%d\n",
911                               ppc->apfx[i * 2].x.value,     ppc->apfx[i * 3].y.value,
912                               ppc->apfx[i * 2 + 1].x.value, ppc->apfx[i * 3 + 1].y.value);
913                         fixed_to_double(ppc->apfx[i * 2], em_size, vertices); 
914                         pgluTessVertex(tess, vertices, vertices);
915                         vertices += 3;
916                         fixed_to_double(ppc->apfx[i * 2 + 1], em_size, vertices); 
917                         pgluTessVertex(tess, vertices, vertices);
918                         vertices += 3;
919                     }
920                     break;
921                 default:
922                     ERR("\t\tcurve type = %d\n", ppc->wType);
923                     pgluTessEndContour(tess);
924                     goto error_in_list;
925                 }
926
927                 ppc = (TTPOLYCURVE*)((char*)ppc + sizeof(*ppc) +
928                                      (ppc->cpfx - 1) * sizeof(POINTFX));
929             }
930             pgluTessEndContour(tess);
931             pph = (TTPOLYGONHEADER*)((char*)pph + pph->cb);
932         }
933
934 error_in_list:
935         pgluTessEndPolygon(tess);
936         glTranslated((GLdouble)gm.gmCellIncX / em_size, (GLdouble)gm.gmCellIncY / em_size, 0.0);
937         glEndList();
938         HeapFree(GetProcessHeap(), 0, buf);
939         HeapFree(GetProcessHeap(), 0, vertices);
940     }
941
942  error:
943     DeleteObject(SelectObject(hdc, old_font));
944     pgluDeleteTess(tess);
945     return TRUE;
946
947 }
948
949 #else /* SONAME_LIBGLU */
950
951 static BOOL wglUseFontOutlines_common(HDC hdc,
952                                       DWORD first,
953                                       DWORD count,
954                                       DWORD listBase,
955                                       FLOAT deviation,
956                                       FLOAT extrusion,
957                                       int format,
958                                       LPGLYPHMETRICSFLOAT lpgmf,
959                                       BOOL unicode)
960 {
961     FIXME("Unable to compile in wglUseFontOutlines support without GL/glu.h\n");
962     return FALSE;
963 }
964
965 #endif /* SONAME_LIBGLU */
966
967 /***********************************************************************
968  *              wglUseFontOutlinesA (OPENGL32.@)
969  */
970 BOOL WINAPI wglUseFontOutlinesA(HDC hdc,
971                                 DWORD first,
972                                 DWORD count,
973                                 DWORD listBase,
974                                 FLOAT deviation,
975                                 FLOAT extrusion,
976                                 int format,
977                                 LPGLYPHMETRICSFLOAT lpgmf)
978 {
979     return wglUseFontOutlines_common(hdc, first, count, listBase, deviation, extrusion, format, lpgmf, FALSE);
980 }
981
982 /***********************************************************************
983  *              wglUseFontOutlinesW (OPENGL32.@)
984  */
985 BOOL WINAPI wglUseFontOutlinesW(HDC hdc,
986                                 DWORD first,
987                                 DWORD count,
988                                 DWORD listBase,
989                                 FLOAT deviation,
990                                 FLOAT extrusion,
991                                 int format,
992                                 LPGLYPHMETRICSFLOAT lpgmf)
993 {
994     return wglUseFontOutlines_common(hdc, first, count, listBase, deviation, extrusion, format, lpgmf, TRUE);
995 }
996
997 /***********************************************************************
998  *              glDebugEntry (OPENGL32.@)
999  */
1000 GLint WINAPI wine_glDebugEntry( GLint unknown1, GLint unknown2 )
1001 {
1002     return 0;
1003 }
1004
1005 /***********************************************************************
1006  *              glFinish (OPENGL32.@)
1007  */
1008 void WINAPI wine_glFinish( void )
1009 {
1010     TRACE("()\n");
1011     wine_wgl.p_wglFinish();
1012 }
1013
1014 /***********************************************************************
1015  *              glFlush (OPENGL32.@)
1016  */
1017 void WINAPI wine_glFlush( void )
1018 {
1019     TRACE("()\n");
1020     wine_wgl.p_wglFlush();
1021 }
1022
1023 /* build the extension string by filtering out the disabled extensions */
1024 static char *build_gl_extensions( const char *extensions )
1025 {
1026     char *p, *str, *disabled = NULL;
1027     const char *end;
1028     HKEY hkey;
1029
1030     TRACE( "GL_EXTENSIONS:\n" );
1031
1032     if (!extensions) extensions = "";
1033
1034     /* @@ Wine registry key: HKCU\Software\Wine\OpenGL */
1035     if (!RegOpenKeyA( HKEY_CURRENT_USER, "Software\\Wine\\OpenGL", &hkey ))
1036     {
1037         DWORD size, ret = RegQueryValueExA( hkey, "DisabledExtensions", 0, NULL, NULL, &size );
1038         if (!ret && (disabled = HeapAlloc( GetProcessHeap(), 0, size )))
1039             ret = RegQueryValueExA( hkey, "DisabledExtensions", 0, NULL, (BYTE *)disabled, &size );
1040         RegCloseKey( hkey );
1041         if (ret) *disabled = 0;
1042     }
1043
1044     if ((str = HeapAlloc( GetProcessHeap(), 0, strlen(extensions) + 2 )))
1045     {
1046         p = str;
1047         for (;;)
1048         {
1049             while (*extensions == ' ') extensions++;
1050             if (!*extensions) break;
1051             if (!(end = strchr( extensions, ' ' ))) end = extensions + strlen( extensions );
1052             memcpy( p, extensions, end - extensions );
1053             p[end - extensions] = 0;
1054             if (!has_extension( disabled, p ))
1055             {
1056                 TRACE("++ %s\n", p );
1057                 p += end - extensions;
1058                 *p++ = ' ';
1059             }
1060             else TRACE("-- %s (disabled by config)\n", p );
1061             extensions = end;
1062         }
1063         *p = 0;
1064     }
1065     HeapFree( GetProcessHeap(), 0, disabled );
1066     return str;
1067 }
1068
1069 /***********************************************************************
1070  *              glGetString (OPENGL32.@)
1071  */
1072 const GLubyte * WINAPI wine_glGetString( GLenum name )
1073 {
1074   static const GLubyte *gl_extensions;
1075
1076   /* this is for buggy nvidia driver, crashing if called from a different
1077      thread with no context */
1078   if(wglGetCurrentContext() == NULL)
1079     return NULL;
1080
1081   if (name != GL_EXTENSIONS) return glGetString(name);
1082
1083   if (!gl_extensions)
1084   {
1085       const char *orig_ext = (const char *)glGetString(GL_EXTENSIONS);
1086       char *new_ext = build_gl_extensions( orig_ext );
1087       if (InterlockedCompareExchangePointer( (void **)&gl_extensions, new_ext, NULL ))
1088           HeapFree( GetProcessHeap(), 0, new_ext );
1089   }
1090   return gl_extensions;
1091 }
1092
1093 /***********************************************************************
1094  *              glGetIntegerv (OPENGL32.@)
1095  */
1096 void WINAPI wine_glGetIntegerv( GLenum pname, GLint* params )
1097 {
1098     wine_wgl.p_wglGetIntegerv(pname, params);
1099 }
1100
1101 /***********************************************************************
1102  *              wglSwapBuffers (OPENGL32.@)
1103  */
1104 BOOL WINAPI DECLSPEC_HOTPATCH wglSwapBuffers( HDC hdc )
1105 {
1106     return GdiSwapBuffers(hdc);
1107 }
1108
1109 /* This is for brain-dead applications that use OpenGL functions before even
1110    creating a rendering context.... */
1111 static BOOL process_attach(void)
1112 {
1113   HDC hdc = GetDC( 0 );
1114
1115   wgl_driver = __wine_get_wgl_driver( hdc, WINE_GDI_DRIVER_VERSION );
1116   ReleaseDC( 0, hdc );
1117
1118   /* internal WGL functions */
1119   wine_wgl.p_wglFinish = (void *)wgl_driver->p_wglGetProcAddress("wglFinish");
1120   wine_wgl.p_wglFlush = (void *)wgl_driver->p_wglGetProcAddress("wglFlush");
1121   wine_wgl.p_wglGetIntegerv = (void *)wgl_driver->p_wglGetProcAddress("wglGetIntegerv");
1122   return TRUE;
1123 }
1124
1125
1126 /**********************************************************************/
1127
1128 static void process_detach(void)
1129 {
1130   if (libglu_handle) wine_dlclose(libglu_handle, NULL, 0);
1131 }
1132
1133 /***********************************************************************
1134  *           OpenGL initialisation routine
1135  */
1136 BOOL WINAPI DllMain( HINSTANCE hinst, DWORD reason, LPVOID reserved )
1137 {
1138     switch(reason)
1139     {
1140     case DLL_PROCESS_ATTACH:
1141         opengl32_handle = hinst;
1142         DisableThreadLibraryCalls(hinst);
1143         return process_attach();
1144     case DLL_PROCESS_DETACH:
1145         process_detach();
1146         break;
1147     }
1148     return TRUE;
1149 }