wined3d: Fall back to backbuffer offscreen rendering if FBOs are unavailable.
[wine] / dlls / wined3d / directx.c
1 /*
2  * IWineD3D implementation
3  *
4  * Copyright 2002-2004 Jason Edmeades
5  * Copyright 2003-2004 Raphael Junqueira
6  * Copyright 2004 Christian Costa
7  * Copyright 2005 Oliver Stieber
8  * Copyright 2007-2008 Stefan Dösinger for CodeWeavers
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 /* Compile time diagnostics: */
26
27 #ifndef DEBUG_SINGLE_MODE
28 /* Set to 1 to force only a single display mode to be exposed: */
29 #define DEBUG_SINGLE_MODE 0
30 #endif
31
32 #include "config.h"
33 #include <assert.h>
34 #include "wined3d_private.h"
35
36 WINE_DEFAULT_DEBUG_CHANNEL(d3d);
37 WINE_DECLARE_DEBUG_CHANNEL(d3d_caps);
38
39 #define GLINFO_LOCATION (*gl_info)
40
41 /* The d3d device ID */
42 static const GUID IID_D3DDEVICE_D3DUID = { 0xaeb2cdd4, 0x6e41, 0x43ea, { 0x94,0x1c,0x83,0x61,0xcc,0x76,0x07,0x81 } };
43
44 /* Extension detection */
45 static const struct {
46     const char *extension_string;
47     GL_SupportedExt extension;
48     DWORD version;
49 } EXTENSION_MAP[] = {
50     /* APPLE */
51     {"GL_APPLE_client_storage",             APPLE_CLIENT_STORAGE,           0                           },
52     {"GL_APPLE_fence",                      APPLE_FENCE,                    0                           },
53     {"GL_APPLE_flush_render",               APPLE_FLUSH_RENDER,             0                           },
54     {"GL_APPLE_ycbcr_422",                  APPLE_YCBCR_422,                0                           },
55     {"GL_APPLE_float_pixels",               APPLE_FLOAT_PIXELS,             0                           },
56
57     /* ATI */
58     {"GL_ATI_separate_stencil",             ATI_SEPARATE_STENCIL,           0                           },
59     {"GL_ATI_texture_env_combine3",         ATI_TEXTURE_ENV_COMBINE3,       0                           },
60     {"GL_ATI_texture_mirror_once",          ATI_TEXTURE_MIRROR_ONCE,        0                           },
61     {"GL_ATI_fragment_shader",              ATI_FRAGMENT_SHADER,            0                           },
62     {"GL_ATI_texture_compression_3dc",      ATI_TEXTURE_COMPRESSION_3DC,    0                           },
63
64     /* ARB */
65     {"GL_ARB_color_buffer_float",           ARB_COLOR_BUFFER_FLOAT,         0                           },
66     {"GL_ARB_depth_buffer_float",           ARB_DEPTH_BUFFER_FLOAT,         0                           },
67     {"GL_ARB_depth_texture",                ARB_DEPTH_TEXTURE,              0                           },
68     {"GL_ARB_draw_buffers",                 ARB_DRAW_BUFFERS,               0                           },
69     {"GL_ARB_fragment_program",             ARB_FRAGMENT_PROGRAM,           0                           },
70     {"GL_ARB_fragment_shader",              ARB_FRAGMENT_SHADER,            0                           },
71     {"GL_ARB_geometry_shader4",             ARB_GEOMETRY_SHADER4,           0                           },
72     {"GL_ARB_half_float_pixel",             ARB_HALF_FLOAT_PIXEL,           0                           },
73     {"GL_ARB_imaging",                      ARB_IMAGING,                    0                           },
74     {"GL_ARB_multisample",                  ARB_MULTISAMPLE,                0                           }, /* needs GLX_ARB_MULTISAMPLE as well */
75     {"GL_ARB_multitexture",                 ARB_MULTITEXTURE,               0                           },
76     {"GL_ARB_occlusion_query",              ARB_OCCLUSION_QUERY,            0                           },
77     {"GL_ARB_pixel_buffer_object",          ARB_PIXEL_BUFFER_OBJECT,        0                           },
78     {"GL_ARB_point_parameters",             ARB_POINT_PARAMETERS,           0                           },
79     {"GL_ARB_point_sprite",                 ARB_POINT_SPRITE,               0                           },
80     {"GL_ARB_texture_border_clamp",         ARB_TEXTURE_BORDER_CLAMP,       0                           },
81     {"GL_ARB_texture_compression",          ARB_TEXTURE_COMPRESSION,        0                           },
82     {"GL_ARB_texture_cube_map",             ARB_TEXTURE_CUBE_MAP,           0                           },
83     {"GL_ARB_texture_env_add",              ARB_TEXTURE_ENV_ADD,            0                           },
84     {"GL_ARB_texture_env_combine",          ARB_TEXTURE_ENV_COMBINE,        0                           },
85     {"GL_ARB_texture_env_dot3",             ARB_TEXTURE_ENV_DOT3,           0                           },
86     {"GL_ARB_texture_float",                ARB_TEXTURE_FLOAT,              0                           },
87     {"GL_ARB_texture_mirrored_repeat",      ARB_TEXTURE_MIRRORED_REPEAT,    0                           },
88     {"GL_ARB_texture_non_power_of_two",     ARB_TEXTURE_NON_POWER_OF_TWO,   MAKEDWORD_VERSION(2, 0)     },
89     {"GL_ARB_texture_rectangle",            ARB_TEXTURE_RECTANGLE,          0                           },
90     {"GL_ARB_texture_rg",                   ARB_TEXTURE_RG,                 0                           },
91     {"GL_ARB_vertex_blend",                 ARB_VERTEX_BLEND,               0                           },
92     {"GL_ARB_vertex_buffer_object",         ARB_VERTEX_BUFFER_OBJECT,       0                           },
93     {"GL_ARB_vertex_program",               ARB_VERTEX_PROGRAM,             0                           },
94     {"GL_ARB_vertex_shader",                ARB_VERTEX_SHADER,              0                           },
95     {"GL_ARB_shader_objects",               ARB_SHADER_OBJECTS,             0                           },
96     {"GL_ARB_shader_texture_lod",           ARB_SHADER_TEXTURE_LOD,         0                           },
97     {"GL_ARB_half_float_vertex",            ARB_HALF_FLOAT_VERTEX,          0                           },
98
99     /* EXT */
100     {"GL_EXT_blend_color",                  EXT_BLEND_COLOR,                0                           },
101     {"GL_EXT_blend_minmax",                 EXT_BLEND_MINMAX,               0                           },
102     {"GL_EXT_blend_equation_separate",      EXT_BLEND_EQUATION_SEPARATE,    0                           },
103     {"GL_EXT_blend_func_separate",          EXT_BLEND_FUNC_SEPARATE,        0                           },
104     {"GL_EXT_fog_coord",                    EXT_FOG_COORD,                  0                           },
105     {"GL_EXT_framebuffer_blit",             EXT_FRAMEBUFFER_BLIT,           0                           },
106     {"GL_EXT_framebuffer_multisample",      EXT_FRAMEBUFFER_MULTISAMPLE,    0                           },
107     {"GL_EXT_framebuffer_object",           EXT_FRAMEBUFFER_OBJECT,         0                           },
108     {"GL_EXT_packed_depth_stencil",         EXT_PACKED_DEPTH_STENCIL,       0                           },
109     {"GL_EXT_paletted_texture",             EXT_PALETTED_TEXTURE,           0                           },
110     {"GL_EXT_point_parameters",             EXT_POINT_PARAMETERS,           0                           },
111     {"GL_EXT_secondary_color",              EXT_SECONDARY_COLOR,            0                           },
112     {"GL_EXT_stencil_two_side",             EXT_STENCIL_TWO_SIDE,           0                           },
113     {"GL_EXT_stencil_wrap",                 EXT_STENCIL_WRAP,               0                           },
114     {"GL_EXT_texture3D",                    EXT_TEXTURE3D,                  MAKEDWORD_VERSION(1, 2)     },
115     {"GL_EXT_texture_compression_s3tc",     EXT_TEXTURE_COMPRESSION_S3TC,   0                           },
116     {"GL_EXT_texture_compression_rgtc",     EXT_TEXTURE_COMPRESSION_RGTC,   0                           },
117     {"GL_EXT_texture_env_add",              EXT_TEXTURE_ENV_ADD,            0                           },
118     {"GL_EXT_texture_env_combine",          EXT_TEXTURE_ENV_COMBINE,        0                           },
119     {"GL_EXT_texture_env_dot3",             EXT_TEXTURE_ENV_DOT3,           0                           },
120     {"GL_EXT_texture_sRGB",                 EXT_TEXTURE_SRGB,               0                           },
121     {"GL_EXT_texture_swizzle",              EXT_TEXTURE_SWIZZLE,            0                           },
122     {"GL_EXT_texture_filter_anisotropic",   EXT_TEXTURE_FILTER_ANISOTROPIC, 0                           },
123     {"GL_EXT_texture_lod",                  EXT_TEXTURE_LOD,                0                           },
124     {"GL_EXT_texture_lod_bias",             EXT_TEXTURE_LOD_BIAS,           0                           },
125     {"GL_EXT_vertex_array_bgra",            EXT_VERTEX_ARRAY_BGRA,          0                           },
126     {"GL_EXT_vertex_shader",                EXT_VERTEX_SHADER,              0                           },
127     {"GL_EXT_gpu_program_parameters",       EXT_GPU_PROGRAM_PARAMETERS,     0                           },
128
129     /* NV */
130     {"GL_NV_half_float",                    NV_HALF_FLOAT,                  0                           },
131     {"GL_NV_fence",                         NV_FENCE,                       0                           },
132     {"GL_NV_fog_distance",                  NV_FOG_DISTANCE,                0                           },
133     {"GL_NV_fragment_program",              NV_FRAGMENT_PROGRAM,            0                           },
134     {"GL_NV_fragment_program2",             NV_FRAGMENT_PROGRAM2,           0                           },
135     {"GL_NV_register_combiners",            NV_REGISTER_COMBINERS,          0                           },
136     {"GL_NV_register_combiners2",           NV_REGISTER_COMBINERS2,         0                           },
137     {"GL_NV_texgen_reflection",             NV_TEXGEN_REFLECTION,           0                           },
138     {"GL_NV_texture_env_combine4",          NV_TEXTURE_ENV_COMBINE4,        0                           },
139     {"GL_NV_texture_shader",                NV_TEXTURE_SHADER,              0                           },
140     {"GL_NV_texture_shader2",               NV_TEXTURE_SHADER2,             0                           },
141     {"GL_NV_texture_shader3",               NV_TEXTURE_SHADER3,             0                           },
142     {"GL_NV_occlusion_query",               NV_OCCLUSION_QUERY,             0                           },
143     {"GL_NV_vertex_program",                NV_VERTEX_PROGRAM,              0                           },
144     {"GL_NV_vertex_program1_1",             NV_VERTEX_PROGRAM1_1,           0                           },
145     {"GL_NV_vertex_program2",               NV_VERTEX_PROGRAM2,             0                           },
146     {"GL_NV_vertex_program2_option",        NV_VERTEX_PROGRAM2_OPTION,      0                           },
147     {"GL_NV_vertex_program3",               NV_VERTEX_PROGRAM3,             0                           },
148     {"GL_NV_fragment_program_option",       NV_FRAGMENT_PROGRAM_OPTION,     0                           },
149     {"GL_NV_depth_clamp",                   NV_DEPTH_CLAMP,                 0                           },
150     {"GL_NV_light_max_exponent",            NV_LIGHT_MAX_EXPONENT,          0                           },
151
152     /* SGI */
153     {"GL_SGIS_generate_mipmap",             SGIS_GENERATE_MIPMAP,           0                           },
154 };
155
156 /**********************************************************
157  * Utility functions follow
158  **********************************************************/
159
160 static HRESULT WINAPI IWineD3DImpl_CheckDeviceFormat(IWineD3D *iface, UINT Adapter, WINED3DDEVTYPE DeviceType, WINED3DFORMAT AdapterFormat, DWORD Usage, WINED3DRESOURCETYPE RType, WINED3DFORMAT CheckFormat, WINED3DSURFTYPE SurfaceType);
161 static const struct fragment_pipeline *select_fragment_implementation(struct WineD3DAdapter *adapter,
162         WINED3DDEVTYPE DeviceType);
163 static const shader_backend_t *select_shader_backend(struct WineD3DAdapter *adapter, WINED3DDEVTYPE DeviceType);
164 static const struct blit_shader *select_blit_implementation(struct WineD3DAdapter *adapter, WINED3DDEVTYPE DeviceType);
165
166 /* lookup tables */
167 const int minLookup[MAX_LOOKUPS] =
168 {
169     WINED3DTADDRESS_WRAP, /* WINELOOKUP_WARPPARAM */
170 };
171
172 const int maxLookup[MAX_LOOKUPS] =
173 {
174     WINED3DTADDRESS_MIRRORONCE, /* WINELOOKUP_WARPPARAM */
175 };
176
177 DWORD *stateLookup[MAX_LOOKUPS];
178
179 struct min_lookup minMipLookup[WINED3DTEXF_ANISOTROPIC + 1];
180 const struct min_lookup minMipLookup_noFilter[WINED3DTEXF_ANISOTROPIC + 1] =
181 {
182     {{GL_NEAREST, GL_NEAREST, GL_NEAREST}},
183     {{GL_NEAREST, GL_NEAREST, GL_NEAREST}},
184     {{GL_NEAREST, GL_NEAREST, GL_NEAREST}},
185     {{GL_NEAREST, GL_NEAREST, GL_NEAREST}},
186 };
187
188 GLenum magLookup[WINED3DTEXF_ANISOTROPIC + 1];
189 const GLenum magLookup_noFilter[WINED3DTEXF_ANISOTROPIC + 1] =
190 {
191     GL_NEAREST, GL_NEAREST, GL_NEAREST, GL_NEAREST
192 };
193
194 /* drawStridedSlow attributes */
195 glAttribFunc position_funcs[WINED3D_FFP_EMIT_COUNT];
196 glAttribFunc diffuse_funcs[WINED3D_FFP_EMIT_COUNT];
197 glAttribFunc specular_func_3ubv;
198 glAttribFunc specular_funcs[WINED3D_FFP_EMIT_COUNT];
199 glAttribFunc normal_funcs[WINED3D_FFP_EMIT_COUNT];
200 glMultiTexCoordFunc multi_texcoord_funcs[WINED3D_FFP_EMIT_COUNT];
201
202 /**
203  * Note: GL seems to trap if GetDeviceCaps is called before any HWND's created,
204  * i.e., there is no GL Context - Get a default rendering context to enable the
205  * function query some info from GL.
206  */
207
208 static int             wined3d_fake_gl_context_ref = 0;
209 static BOOL            wined3d_fake_gl_context_foreign;
210 static BOOL            wined3d_fake_gl_context_available = FALSE;
211 static HDC             wined3d_fake_gl_context_hdc = NULL;
212 static HWND            wined3d_fake_gl_context_hwnd = NULL;
213
214 static CRITICAL_SECTION wined3d_fake_gl_context_cs;
215 static CRITICAL_SECTION_DEBUG wined3d_fake_gl_context_cs_debug =
216 {
217     0, 0, &wined3d_fake_gl_context_cs,
218     { &wined3d_fake_gl_context_cs_debug.ProcessLocksList,
219       &wined3d_fake_gl_context_cs_debug.ProcessLocksList },
220     0, 0, { (DWORD_PTR)(__FILE__ ": wined3d_fake_gl_context_cs") }
221 };
222 static CRITICAL_SECTION wined3d_fake_gl_context_cs = { &wined3d_fake_gl_context_cs_debug, -1, 0, 0, 0, 0 };
223
224 static void WineD3D_ReleaseFakeGLContext(void) {
225     HGLRC glCtx;
226
227     EnterCriticalSection(&wined3d_fake_gl_context_cs);
228
229     if(!wined3d_fake_gl_context_available) {
230         TRACE_(d3d_caps)("context not available\n");
231         LeaveCriticalSection(&wined3d_fake_gl_context_cs);
232         return;
233     }
234
235     glCtx = pwglGetCurrentContext();
236
237     TRACE_(d3d_caps)("decrementing ref from %i\n", wined3d_fake_gl_context_ref);
238     if (0 == (--wined3d_fake_gl_context_ref) ) {
239         if(!wined3d_fake_gl_context_foreign && glCtx) {
240             TRACE_(d3d_caps)("destroying fake GL context\n");
241             pwglMakeCurrent(NULL, NULL);
242             pwglDeleteContext(glCtx);
243         }
244         if(wined3d_fake_gl_context_hdc)
245             ReleaseDC(wined3d_fake_gl_context_hwnd, wined3d_fake_gl_context_hdc);
246         wined3d_fake_gl_context_hdc = NULL; /* Make sure we don't think that it is still around */
247         if(wined3d_fake_gl_context_hwnd)
248             DestroyWindow(wined3d_fake_gl_context_hwnd);
249         wined3d_fake_gl_context_hwnd = NULL;
250         wined3d_fake_gl_context_available = FALSE;
251     }
252     assert(wined3d_fake_gl_context_ref >= 0);
253
254     LeaveCriticalSection(&wined3d_fake_gl_context_cs);
255 }
256
257 static BOOL WineD3D_CreateFakeGLContext(void) {
258     HGLRC glCtx = NULL;
259
260     EnterCriticalSection(&wined3d_fake_gl_context_cs);
261
262     TRACE("getting context...\n");
263     if(wined3d_fake_gl_context_ref > 0) goto ret;
264     assert(0 == wined3d_fake_gl_context_ref);
265
266     wined3d_fake_gl_context_foreign = TRUE;
267
268     glCtx = pwglGetCurrentContext();
269     if (!glCtx) {
270         PIXELFORMATDESCRIPTOR pfd;
271         int iPixelFormat;
272
273         wined3d_fake_gl_context_foreign = FALSE;
274
275         /* We need a fake window as a hdc retrieved using GetDC(0) can't be used for much GL purposes */
276         wined3d_fake_gl_context_hwnd = CreateWindowA(WINED3D_OPENGL_WINDOW_CLASS_NAME, "WineD3D fake window", WS_OVERLAPPEDWINDOW, 10, 10, 10, 10, NULL, NULL, NULL, NULL);
277         if(!wined3d_fake_gl_context_hwnd) {
278             ERR("HWND creation failed!\n");
279             goto fail;
280         }
281         wined3d_fake_gl_context_hdc = GetDC(wined3d_fake_gl_context_hwnd);
282         if(!wined3d_fake_gl_context_hdc) {
283             ERR("GetDC failed!\n");
284             goto fail;
285         }
286
287         /* PixelFormat selection */
288         ZeroMemory(&pfd, sizeof(pfd));
289         pfd.nSize      = sizeof(pfd);
290         pfd.nVersion   = 1;
291         pfd.dwFlags    = PFD_SUPPORT_OPENGL | PFD_DOUBLEBUFFER | PFD_DRAW_TO_WINDOW;/*PFD_GENERIC_ACCELERATED*/
292         pfd.iPixelType = PFD_TYPE_RGBA;
293         pfd.cColorBits = 32;
294         pfd.iLayerType = PFD_MAIN_PLANE;
295
296         iPixelFormat = ChoosePixelFormat(wined3d_fake_gl_context_hdc, &pfd);
297         if(!iPixelFormat) {
298             /* If this happens something is very wrong as ChoosePixelFormat barely fails */
299             ERR("Can't find a suitable iPixelFormat\n");
300             goto fail;
301         }
302         DescribePixelFormat(wined3d_fake_gl_context_hdc, iPixelFormat, sizeof(pfd), &pfd);
303         SetPixelFormat(wined3d_fake_gl_context_hdc, iPixelFormat, &pfd);
304
305         /* Create a GL context */
306         glCtx = pwglCreateContext(wined3d_fake_gl_context_hdc);
307         if (!glCtx) {
308             WARN_(d3d_caps)("Error creating default context for capabilities initialization\n");
309             goto fail;
310         }
311
312         /* Make it the current GL context */
313         if (!pwglMakeCurrent(wined3d_fake_gl_context_hdc, glCtx)) {
314             WARN_(d3d_caps)("Error setting default context as current for capabilities initialization\n");
315             goto fail;
316         }
317     }
318
319   ret:
320     TRACE("incrementing ref from %i\n", wined3d_fake_gl_context_ref);
321     wined3d_fake_gl_context_ref++;
322     wined3d_fake_gl_context_available = TRUE;
323     LeaveCriticalSection(&wined3d_fake_gl_context_cs);
324     return TRUE;
325   fail:
326     if(wined3d_fake_gl_context_hdc)
327         ReleaseDC(wined3d_fake_gl_context_hwnd, wined3d_fake_gl_context_hdc);
328     wined3d_fake_gl_context_hdc = NULL;
329     if(wined3d_fake_gl_context_hwnd)
330         DestroyWindow(wined3d_fake_gl_context_hwnd);
331     wined3d_fake_gl_context_hwnd = NULL;
332     if(glCtx) pwglDeleteContext(glCtx);
333     LeaveCriticalSection(&wined3d_fake_gl_context_cs);
334     return FALSE;
335 }
336
337 /* Adjust the amount of used texture memory */
338 long WineD3DAdapterChangeGLRam(IWineD3DDeviceImpl *D3DDevice, long glram){
339     struct WineD3DAdapter *adapter = D3DDevice->adapter;
340
341     adapter->UsedTextureRam += glram;
342     TRACE("Adjusted gl ram by %ld to %d\n", glram, adapter->UsedTextureRam);
343     return adapter->UsedTextureRam;
344 }
345
346 /**********************************************************
347  * IUnknown parts follows
348  **********************************************************/
349
350 static HRESULT WINAPI IWineD3DImpl_QueryInterface(IWineD3D *iface,REFIID riid,LPVOID *ppobj)
351 {
352     IWineD3DDeviceImpl *This = (IWineD3DDeviceImpl *)iface;
353
354     TRACE("(%p)->(%s,%p)\n",This,debugstr_guid(riid),ppobj);
355     if (IsEqualGUID(riid, &IID_IUnknown)
356         || IsEqualGUID(riid, &IID_IWineD3DBase)
357         || IsEqualGUID(riid, &IID_IWineD3DDevice)) {
358         IUnknown_AddRef(iface);
359         *ppobj = This;
360         return S_OK;
361     }
362     *ppobj = NULL;
363     return E_NOINTERFACE;
364 }
365
366 static ULONG WINAPI IWineD3DImpl_AddRef(IWineD3D *iface) {
367     IWineD3DImpl *This = (IWineD3DImpl *)iface;
368     ULONG refCount = InterlockedIncrement(&This->ref);
369
370     TRACE("(%p) : AddRef increasing from %d\n", This, refCount - 1);
371     return refCount;
372 }
373
374 static ULONG WINAPI IWineD3DImpl_Release(IWineD3D *iface) {
375     IWineD3DImpl *This = (IWineD3DImpl *)iface;
376     ULONG ref;
377     TRACE("(%p) : Releasing from %d\n", This, This->ref);
378     ref = InterlockedDecrement(&This->ref);
379     if (ref == 0) {
380         unsigned int i;
381
382         for (i = 0; i < This->adapter_count; ++i)
383         {
384             HeapFree(GetProcessHeap(), 0, This->adapters[i].cfgs);
385         }
386         HeapFree(GetProcessHeap(), 0, This);
387     }
388
389     return ref;
390 }
391
392 /* Set the shader type for this device, depending on the given capabilities,
393  * the device type, and the user preferences in wined3d_settings */
394
395 static void select_shader_mode(const WineD3D_GL_Info *gl_info, WINED3DDEVTYPE DeviceType, int *ps_selected, int *vs_selected)
396 {
397     if (wined3d_settings.vs_mode == VS_NONE) {
398         *vs_selected = SHADER_NONE;
399     } else if (gl_info->supported[ARB_VERTEX_SHADER] && wined3d_settings.glslRequested) {
400         /* Geforce4 cards support GLSL but for vertex shaders only. Further its reported GLSL caps are
401          * wrong. This combined with the fact that glsl won't offer more features or performance, use ARB
402          * shaders only on this card. */
403         if(gl_info->vs_nv_version && gl_info->vs_nv_version < VS_VERSION_20)
404             *vs_selected = SHADER_ARB;
405         else
406             *vs_selected = SHADER_GLSL;
407     } else if (gl_info->supported[ARB_VERTEX_PROGRAM]) {
408         *vs_selected = SHADER_ARB;
409     } else {
410         *vs_selected = SHADER_NONE;
411     }
412
413     if (wined3d_settings.ps_mode == PS_NONE) {
414         *ps_selected = SHADER_NONE;
415     } else if (gl_info->supported[ARB_FRAGMENT_SHADER] && wined3d_settings.glslRequested) {
416         *ps_selected = SHADER_GLSL;
417     } else if (gl_info->supported[ARB_FRAGMENT_PROGRAM]) {
418         *ps_selected = SHADER_ARB;
419     } else if (gl_info->supported[ATI_FRAGMENT_SHADER]) {
420         *ps_selected = SHADER_ATI;
421     } else {
422         *ps_selected = SHADER_NONE;
423     }
424 }
425
426 /** Select the number of report maximum shader constants based on the selected shader modes */
427 static void select_shader_max_constants(
428     int ps_selected_mode,
429     int vs_selected_mode,
430     WineD3D_GL_Info *gl_info) {
431
432     switch (vs_selected_mode) {
433         case SHADER_GLSL:
434             gl_info->max_vshader_constantsF = gl_info->vs_glsl_constantsF;
435             break;
436         case SHADER_ARB:
437             gl_info->max_vshader_constantsF = gl_info->vs_arb_constantsF;
438             break;
439         default:
440             gl_info->max_vshader_constantsF = 0;
441             break;
442     }
443
444     switch (ps_selected_mode) {
445         case SHADER_GLSL:
446             gl_info->max_pshader_constantsF = gl_info->ps_glsl_constantsF;
447             break;
448         case SHADER_ARB:
449             gl_info->max_pshader_constantsF = gl_info->ps_arb_constantsF;
450             break;
451         default:
452             gl_info->max_pshader_constantsF = 0;
453             break;
454     }
455 }
456
457 /**********************************************************
458  * IWineD3D parts follows
459  **********************************************************/
460
461 /* GL locking is done by the caller */
462 static inline BOOL test_arb_vs_offset_limit(const WineD3D_GL_Info *gl_info)
463 {
464     GLuint prog;
465     BOOL ret = FALSE;
466     const char *testcode =
467         "!!ARBvp1.0\n"
468         "PARAM C[66] = { program.env[0..65] };\n"
469         "ADDRESS A0;"
470         "PARAM zero = {0.0, 0.0, 0.0, 0.0};\n"
471         "ARL A0.x, zero.x;\n"
472         "MOV result.position, C[A0.x + 65];\n"
473         "END\n";
474
475     while(glGetError());
476     GL_EXTCALL(glGenProgramsARB(1, &prog));
477     if(!prog) {
478         ERR("Failed to create an ARB offset limit test program\n");
479     }
480     GL_EXTCALL(glBindProgramARB(GL_VERTEX_PROGRAM_ARB, prog));
481     GL_EXTCALL(glProgramStringARB(GL_VERTEX_PROGRAM_ARB, GL_PROGRAM_FORMAT_ASCII_ARB,
482                                   strlen(testcode), testcode));
483     if(glGetError() != 0) {
484         TRACE("OpenGL implementation does not allow indirect addressing offsets > 63\n");
485         TRACE("error: %s\n", debugstr_a((const char *)glGetString(GL_PROGRAM_ERROR_STRING_ARB)));
486         ret = TRUE;
487     } else TRACE("OpenGL implementation allows offsets > 63\n");
488
489     GL_EXTCALL(glBindProgramARB(GL_VERTEX_PROGRAM_ARB, 0));
490     GL_EXTCALL(glDeleteProgramsARB(1, &prog));
491     checkGLcall("ARB vp offset limit test cleanup\n");
492
493     return ret;
494 }
495
496 static DWORD ver_for_ext(GL_SupportedExt ext)
497 {
498     unsigned int i;
499     for (i = 0; i < (sizeof(EXTENSION_MAP) / sizeof(*EXTENSION_MAP)); ++i) {
500         if(EXTENSION_MAP[i].extension == ext) {
501             return EXTENSION_MAP[i].version;
502         }
503     }
504     return 0;
505 }
506
507 static BOOL IWineD3DImpl_FillGLCaps(WineD3D_GL_Info *gl_info) {
508     const char *GL_Extensions    = NULL;
509     const char *WGL_Extensions   = NULL;
510     const char *gl_string        = NULL;
511     const char *gl_string_cursor = NULL;
512     GLint       gl_max;
513     GLfloat     gl_floatv[2];
514     int         major = 1, minor = 0;
515     BOOL        return_value = TRUE;
516     unsigned    i;
517     HDC         hdc;
518     unsigned int vidmem=0;
519
520     TRACE_(d3d_caps)("(%p)\n", gl_info);
521
522     ENTER_GL();
523
524     gl_string = (const char *) glGetString(GL_RENDERER);
525     if (!gl_string) gl_string = "None";
526     strcpy(gl_info->gl_renderer, gl_string);
527
528     gl_string = (const char *) glGetString(GL_VENDOR);
529     TRACE_(d3d_caps)("Filling vendor string %s\n", gl_string);
530     if (gl_string != NULL) {
531         /* Fill in the GL vendor */
532         if (strstr(gl_string, "NVIDIA")) {
533             gl_info->gl_vendor = VENDOR_NVIDIA;
534         } else if (strstr(gl_string, "ATI")) {
535             gl_info->gl_vendor = VENDOR_ATI;
536         } else if (strstr(gl_string, "Intel(R)") ||
537                    strstr(gl_info->gl_renderer, "Intel(R)") ||
538                    strstr(gl_string, "Intel Inc.")) {
539             gl_info->gl_vendor = VENDOR_INTEL;
540         } else if (strstr(gl_string, "Mesa")) {
541             gl_info->gl_vendor = VENDOR_MESA;
542         } else {
543             gl_info->gl_vendor = VENDOR_WINE;
544         }
545     } else {
546         gl_info->gl_vendor = VENDOR_WINE;
547     }
548
549
550     TRACE_(d3d_caps)("found GL_VENDOR (%s)->(0x%04x)\n", debugstr_a(gl_string), gl_info->gl_vendor);
551
552     /* Parse the GL_VERSION field into major and minor information */
553     gl_string = (const char *) glGetString(GL_VERSION);
554     if (gl_string != NULL) {
555
556         /* First, parse the generic opengl version. This is supposed not to be convoluted with
557          * driver specific information
558          */
559         gl_string_cursor = gl_string;
560         major = atoi(gl_string_cursor);
561         if(major <= 0) {
562             ERR("Invalid opengl major version: %d\n", major);
563         }
564         while (*gl_string_cursor <= '9' && *gl_string_cursor >= '0') {
565             ++gl_string_cursor;
566         }
567         if (*gl_string_cursor++ != '.') {
568             ERR_(d3d_caps)("Invalid opengl version string: %s\n", debugstr_a(gl_string));
569         }
570         minor = atoi(gl_string_cursor);
571         TRACE_(d3d_caps)("Found OpenGL version: %d.%d\n", major, minor);
572         gl_info->gl_version = MAKEDWORD_VERSION(major, minor);
573
574         /* Now parse the driver specific string which we'll report to the app */
575         switch (gl_info->gl_vendor) {
576         case VENDOR_NVIDIA:
577             gl_string_cursor = strstr(gl_string, "NVIDIA");
578             if (!gl_string_cursor) {
579                 ERR_(d3d_caps)("Invalid nVidia version string: %s\n", debugstr_a(gl_string));
580                 break;
581             }
582
583             gl_string_cursor = strstr(gl_string_cursor, " ");
584             if (!gl_string_cursor) {
585                 ERR_(d3d_caps)("Invalid nVidia version string: %s\n", debugstr_a(gl_string));
586                 break;
587             }
588
589             while (*gl_string_cursor == ' ') {
590                 ++gl_string_cursor;
591             }
592
593             if (!*gl_string_cursor) {
594                 ERR_(d3d_caps)("Invalid nVidia version string: %s\n", debugstr_a(gl_string));
595                 break;
596             }
597
598             major = atoi(gl_string_cursor);
599             while (*gl_string_cursor <= '9' && *gl_string_cursor >= '0') {
600                 ++gl_string_cursor;
601             }
602
603             if (*gl_string_cursor++ != '.') {
604                 ERR_(d3d_caps)("Invalid nVidia version string: %s\n", debugstr_a(gl_string));
605                 break;
606             }
607
608             minor = atoi(gl_string_cursor);
609             minor = major*100+minor;
610             major = 10;
611
612             break;
613
614         case VENDOR_ATI:
615             major = minor = 0;
616             gl_string_cursor = strchr(gl_string, '-');
617             if (gl_string_cursor) {
618                 gl_string_cursor++;
619
620                 /* Check if version number is of the form x.y.z */
621                 if ( *gl_string_cursor < '0' || *gl_string_cursor > '9'
622                      || *(gl_string_cursor+1) != '.'
623                      || *(gl_string_cursor+2) < '0' || *(gl_string_cursor+2) > '9'
624                      || *(gl_string_cursor+3) != '.'
625                      || *(gl_string_cursor+4) < '0' || *(gl_string_cursor+4) > '9' )
626                     /* Mark version number as malformed */
627                     gl_string_cursor = 0;
628             }
629
630             if (!gl_string_cursor)
631                 WARN_(d3d_caps)("malformed GL_VERSION (%s)\n", debugstr_a(gl_string));
632             else {
633                 major = *gl_string_cursor - '0';
634                 minor = (*(gl_string_cursor+2) - '0') * 256 + (*(gl_string_cursor+4) - '0');
635             }
636             break;
637
638         case VENDOR_INTEL:
639             /* Apple and Mesa version strings look differently, but both provide intel drivers */
640             if(strstr(gl_string, "APPLE")) {
641                 /* [0-9]+.[0-9]+ APPLE-[0-9]+.[0.9]+.[0.9]+
642                  * We only need the first part, and use the APPLE as identification
643                  * "1.2 APPLE-1.4.56"
644                  */
645                 gl_string_cursor = gl_string;
646                 major = atoi(gl_string_cursor);
647                 while (*gl_string_cursor <= '9' && *gl_string_cursor >= '0') {
648                     ++gl_string_cursor;
649                 }
650
651                 if (*gl_string_cursor++ != '.') {
652                     ERR_(d3d_caps)("Invalid MacOS-Intel version string: %s\n", debugstr_a(gl_string));
653                     break;
654                 }
655
656                 minor = atoi(gl_string_cursor);
657                 break;
658             }
659
660         case VENDOR_MESA:
661             gl_string_cursor = strstr(gl_string, "Mesa");
662             gl_string_cursor = strstr(gl_string_cursor, " ");
663             while (*gl_string_cursor && ' ' == *gl_string_cursor) ++gl_string_cursor;
664             if (*gl_string_cursor) {
665                 char tmp[16];
666                 int cursor = 0;
667
668                 while (*gl_string_cursor <= '9' && *gl_string_cursor >= '0') {
669                     tmp[cursor++] = *gl_string_cursor;
670                     ++gl_string_cursor;
671                 }
672                 tmp[cursor] = 0;
673                 major = atoi(tmp);
674
675                 if (*gl_string_cursor != '.') WARN_(d3d_caps)("malformed GL_VERSION (%s)\n", debugstr_a(gl_string));
676                 ++gl_string_cursor;
677
678                 cursor = 0;
679                 while (*gl_string_cursor <= '9' && *gl_string_cursor >= '0') {
680                     tmp[cursor++] = *gl_string_cursor;
681                     ++gl_string_cursor;
682                 }
683                 tmp[cursor] = 0;
684                 minor = atoi(tmp);
685             }
686             break;
687
688         default:
689             major = 0;
690             minor = 9;
691         }
692         gl_info->driver_version = MAKEDWORD_VERSION(major, minor);
693         TRACE_(d3d_caps)("found driver version (%s)->%i.%i->(0x%08x)\n", debugstr_a(gl_string), major, minor, gl_info->driver_version);
694         /* Current Windows drivers have versions like 6.14.... (some older have an earlier version) */
695         gl_info->driver_version_hipart = MAKEDWORD_VERSION(6, 14);
696     } else {
697         FIXME("OpenGL driver did not return version information\n");
698         gl_info->driver_version = MAKEDWORD_VERSION(0, 0);
699         gl_info->driver_version_hipart = MAKEDWORD_VERSION(6, 14);
700     }
701
702     TRACE_(d3d_caps)("found GL_RENDERER (%s)->(0x%04x)\n", debugstr_a(gl_info->gl_renderer), gl_info->gl_card);
703
704     /*
705      * Initialize openGL extension related variables
706      *  with Default values
707      */
708     memset(gl_info->supported, 0, sizeof(gl_info->supported));
709     gl_info->max_buffers        = 1;
710     gl_info->max_textures       = 1;
711     gl_info->max_texture_stages = 1;
712     gl_info->max_fragment_samplers = 1;
713     gl_info->max_vertex_samplers = 0;
714     gl_info->max_combined_samplers = gl_info->max_fragment_samplers + gl_info->max_vertex_samplers;
715     gl_info->max_sampler_stages = 1;
716     gl_info->ps_arb_version = PS_VERSION_NOT_SUPPORTED;
717     gl_info->ps_arb_max_temps = 0;
718     gl_info->ps_arb_max_instructions = 0;
719     gl_info->vs_arb_version = VS_VERSION_NOT_SUPPORTED;
720     gl_info->vs_arb_max_temps = 0;
721     gl_info->vs_arb_max_instructions = 0;
722     gl_info->vs_nv_version  = VS_VERSION_NOT_SUPPORTED;
723     gl_info->vs_ati_version = VS_VERSION_NOT_SUPPORTED;
724     gl_info->vs_glsl_constantsF = 0;
725     gl_info->ps_glsl_constantsF = 0;
726     gl_info->vs_arb_constantsF = 0;
727     gl_info->ps_arb_constantsF = 0;
728
729     /* Retrieve opengl defaults */
730     glGetIntegerv(GL_MAX_CLIP_PLANES, &gl_max);
731     gl_info->max_clipplanes = min(WINED3DMAXUSERCLIPPLANES, gl_max);
732     TRACE_(d3d_caps)("ClipPlanes support - num Planes=%d\n", gl_max);
733
734     glGetIntegerv(GL_MAX_LIGHTS, &gl_max);
735     gl_info->max_lights = gl_max;
736     TRACE_(d3d_caps)("Lights support - max lights=%d\n", gl_max);
737
738     glGetIntegerv(GL_MAX_TEXTURE_SIZE, &gl_max);
739     gl_info->max_texture_size = gl_max;
740     TRACE_(d3d_caps)("Maximum texture size support - max texture size=%d\n", gl_max);
741
742     glGetFloatv(GL_ALIASED_POINT_SIZE_RANGE, gl_floatv);
743     gl_info->max_pointsizemin = gl_floatv[0];
744     gl_info->max_pointsize = gl_floatv[1];
745     TRACE_(d3d_caps)("Maximum point size support - max point size=%f\n", gl_floatv[1]);
746
747     /* Parse the gl supported features, in theory enabling parts of our code appropriately */
748     GL_Extensions = (const char *) glGetString(GL_EXTENSIONS);
749     TRACE_(d3d_caps)("GL_Extensions reported:\n");
750
751     if (NULL == GL_Extensions) {
752         ERR("   GL_Extensions returns NULL\n");
753     } else {
754         gl_info->supported[WINED3D_GL_EXT_NONE] = TRUE;
755
756         while (*GL_Extensions != 0x00) {
757             const char *Start;
758             char        ThisExtn[256];
759             size_t      len;
760
761             while (isspace(*GL_Extensions)) GL_Extensions++;
762             Start = GL_Extensions;
763             while (!isspace(*GL_Extensions) && *GL_Extensions != 0x00) {
764                 GL_Extensions++;
765             }
766
767             len = GL_Extensions - Start;
768             if (len == 0 || len >= sizeof(ThisExtn))
769                 continue;
770
771             memcpy(ThisExtn, Start, len);
772             ThisExtn[len] = '\0';
773             TRACE_(d3d_caps)("- %s\n", ThisExtn);
774
775             for (i = 0; i < (sizeof(EXTENSION_MAP) / sizeof(*EXTENSION_MAP)); ++i) {
776                 if (!strcmp(ThisExtn, EXTENSION_MAP[i].extension_string)) {
777                     TRACE_(d3d_caps)(" FOUND: %s support\n", EXTENSION_MAP[i].extension_string);
778                     gl_info->supported[EXTENSION_MAP[i].extension] = TRUE;
779                     break;
780                 }
781             }
782         }
783
784         LEAVE_GL();
785
786         /* Now work out what GL support this card really has */
787 #define USE_GL_FUNC(type, pfn, ext, replace) { \
788             DWORD ver = ver_for_ext(ext); \
789             if(gl_info->supported[ext]) gl_info->pfn = (type) pwglGetProcAddress(#pfn); \
790             else if(ver && ver <= gl_info->gl_version) gl_info->pfn = (type) pwglGetProcAddress(#replace); \
791             else gl_info->pfn = NULL; \
792         }
793         GL_EXT_FUNCS_GEN;
794 #undef USE_GL_FUNC
795
796 #define USE_GL_FUNC(type, pfn, ext, replace) gl_info->pfn = (type) pwglGetProcAddress(#pfn);
797         WGL_EXT_FUNCS_GEN;
798 #undef USE_GL_FUNC
799
800         ENTER_GL();
801         /* Now mark all the extensions supported which are included in the opengl core version. Do this *after*
802          * loading the functions, otherwise the code above will load the extension entry points instead of the
803          * core functions, which may not work
804          */
805         for (i = 0; i < (sizeof(EXTENSION_MAP) / sizeof(*EXTENSION_MAP)); ++i) {
806             if (gl_info->supported[EXTENSION_MAP[i].extension] == FALSE &&
807                 EXTENSION_MAP[i].version <= gl_info->gl_version && EXTENSION_MAP[i].version) {
808                 TRACE_(d3d_caps)(" GL CORE: %s support\n", EXTENSION_MAP[i].extension_string);
809                 gl_info->supported[EXTENSION_MAP[i].extension] = TRUE;
810             }
811         }
812
813         if (gl_info->supported[APPLE_FENCE]) {
814             /* GL_NV_fence and GL_APPLE_fence provide the same functionality basically.
815              * The apple extension interacts with some other apple exts. Disable the NV
816              * extension if the apple one is support to prevent confusion in other parts
817              * of the code
818              */
819             gl_info->supported[NV_FENCE] = FALSE;
820         }
821         if (gl_info->supported[APPLE_FLOAT_PIXELS]) {
822             /* GL_APPLE_float_pixels == GL_ARB_texture_float + GL_ARB_half_float_pixel
823              *
824              * The enums are the same:
825              * GL_RGBA16F_ARB     = GL_RGBA_FLOAT16_APPLE = 0x881A
826              * GL_RGB16F_ARB      = GL_RGB_FLOAT16_APPLE  = 0x881B
827              * GL_RGBA32F_ARB     = GL_RGBA_FLOAT32_APPLE = 0x8814
828              * GL_RGB32F_ARB      = GL_RGB_FLOAT32_APPLE  = 0x8815
829              * GL_HALF_FLOAT_ARB  = GL_HALF_APPLE         =  0x140B
830              */
831             if(!gl_info->supported[ARB_TEXTURE_FLOAT]) {
832                 TRACE_(d3d_caps)(" IMPLIED: GL_ARB_texture_float support(from GL_APPLE_float_pixels\n");
833                 gl_info->supported[ARB_TEXTURE_FLOAT] = TRUE;
834             }
835             if(!gl_info->supported[ARB_HALF_FLOAT_PIXEL]) {
836                 TRACE_(d3d_caps)(" IMPLIED: GL_ARB_half_float_pixel support(from GL_APPLE_float_pixels\n");
837                 gl_info->supported[ARB_HALF_FLOAT_PIXEL] = TRUE;
838             }
839         }
840         if (gl_info->supported[ARB_TEXTURE_CUBE_MAP]) {
841             TRACE_(d3d_caps)(" IMPLIED: NVIDIA (NV) Texture Gen Reflection support\n");
842             gl_info->supported[NV_TEXGEN_REFLECTION] = TRUE;
843         }
844         if (gl_info->supported[NV_TEXTURE_SHADER2]) {
845             if(gl_info->supported[NV_REGISTER_COMBINERS]) {
846                 /* Also disable ATI_FRAGMENT_SHADER if register combiners and texture_shader2
847                  * are supported. The nv extensions provide the same functionality as the
848                  * ATI one, and a bit more(signed pixelformats)
849                  */
850                 gl_info->supported[ATI_FRAGMENT_SHADER] = FALSE;
851             }
852         }
853         if (gl_info->supported[ARB_DRAW_BUFFERS]) {
854             glGetIntegerv(GL_MAX_DRAW_BUFFERS_ARB, &gl_max);
855             gl_info->max_buffers = gl_max;
856             TRACE_(d3d_caps)("Max draw buffers: %u\n", gl_max);
857         }
858         if (gl_info->supported[ARB_MULTITEXTURE]) {
859             glGetIntegerv(GL_MAX_TEXTURE_UNITS_ARB, &gl_max);
860             gl_info->max_textures = min(MAX_TEXTURES, gl_max);
861             TRACE_(d3d_caps)("Max textures: %d\n", gl_info->max_textures);
862
863             if (gl_info->supported[NV_REGISTER_COMBINERS]) {
864                 GLint tmp;
865                 glGetIntegerv(GL_MAX_GENERAL_COMBINERS_NV, &tmp);
866                 gl_info->max_texture_stages = min(MAX_TEXTURES, tmp);
867             } else {
868                 gl_info->max_texture_stages = min(MAX_TEXTURES, gl_max);
869             }
870             TRACE_(d3d_caps)("Max texture stages: %d\n", gl_info->max_texture_stages);
871
872             if (gl_info->supported[ARB_FRAGMENT_PROGRAM]) {
873                 GLint tmp;
874                 glGetIntegerv(GL_MAX_TEXTURE_IMAGE_UNITS_ARB, &tmp);
875                 gl_info->max_fragment_samplers = min(MAX_FRAGMENT_SAMPLERS, tmp);
876             } else {
877                 gl_info->max_fragment_samplers = max(gl_info->max_fragment_samplers, gl_max);
878             }
879             TRACE_(d3d_caps)("Max fragment samplers: %d\n", gl_info->max_fragment_samplers);
880
881             if (gl_info->supported[ARB_VERTEX_SHADER]) {
882                 GLint tmp;
883                 glGetIntegerv(GL_MAX_VERTEX_TEXTURE_IMAGE_UNITS_ARB, &tmp);
884                 gl_info->max_vertex_samplers = tmp;
885                 glGetIntegerv(GL_MAX_COMBINED_TEXTURE_IMAGE_UNITS_ARB, &tmp);
886                 gl_info->max_combined_samplers = tmp;
887
888                 /* Loading GLSL sampler uniforms is much simpler if we can assume that the sampler setup
889                  * is known at shader link time. In a vertex shader + pixel shader combination this isn't
890                  * an issue because then the sampler setup only depends on the two shaders. If a pixel
891                  * shader is used with fixed function vertex processing we're fine too because fixed function
892                  * vertex processing doesn't use any samplers. If fixed function fragment processing is
893                  * used we have to make sure that all vertex sampler setups are valid together with all
894                  * possible fixed function fragment processing setups. This is true if vsamplers + MAX_TEXTURES
895                  * <= max_samplers. This is true on all d3d9 cards that support vtf(gf 6 and gf7 cards).
896                  * dx9 radeon cards do not support vertex texture fetch. DX10 cards have 128 samplers, and
897                  * dx9 is limited to 8 fixed function texture stages and 4 vertex samplers. DX10 does not have
898                  * a fixed function pipeline anymore.
899                  *
900                  * So this is just a check to check that our assumption holds true. If not, write a warning
901                  * and reduce the number of vertex samplers or probably disable vertex texture fetch.
902                  */
903                 if(gl_info->max_vertex_samplers && gl_info->max_combined_samplers < 12 &&
904                    MAX_TEXTURES + gl_info->max_vertex_samplers > gl_info->max_combined_samplers) {
905                     FIXME("OpenGL implementation supports %u vertex samplers and %u total samplers\n",
906                           gl_info->max_vertex_samplers, gl_info->max_combined_samplers);
907                     FIXME("Expected vertex samplers + MAX_TEXTURES(=8) > combined_samplers\n");
908                     if( gl_info->max_combined_samplers > MAX_TEXTURES )
909                         gl_info->max_vertex_samplers =
910                             gl_info->max_combined_samplers - MAX_TEXTURES;
911                     else
912                         gl_info->max_vertex_samplers = 0;
913                 }
914             } else {
915                 gl_info->max_combined_samplers = gl_info->max_fragment_samplers;
916             }
917             TRACE_(d3d_caps)("Max vertex samplers: %u\n", gl_info->max_vertex_samplers);
918             TRACE_(d3d_caps)("Max combined samplers: %u\n", gl_info->max_combined_samplers);
919         }
920         if (gl_info->supported[ARB_VERTEX_BLEND]) {
921             glGetIntegerv(GL_MAX_VERTEX_UNITS_ARB, &gl_max);
922             gl_info->max_blends = gl_max;
923             TRACE_(d3d_caps)("Max blends: %u\n", gl_info->max_blends);
924         }
925         if (gl_info->supported[EXT_TEXTURE3D]) {
926             glGetIntegerv(GL_MAX_3D_TEXTURE_SIZE_EXT, &gl_max);
927             gl_info->max_texture3d_size = gl_max;
928             TRACE_(d3d_caps)("Max texture3D size: %d\n", gl_info->max_texture3d_size);
929         }
930         if (gl_info->supported[EXT_TEXTURE_FILTER_ANISOTROPIC]) {
931             glGetIntegerv(GL_MAX_TEXTURE_MAX_ANISOTROPY_EXT, &gl_max);
932             gl_info->max_anisotropy = gl_max;
933             TRACE_(d3d_caps)("Max anisotropy: %d\n", gl_info->max_anisotropy);
934         }
935         if (gl_info->supported[ARB_FRAGMENT_PROGRAM]) {
936             gl_info->ps_arb_version = PS_VERSION_11;
937             GL_EXTCALL(glGetProgramivARB(GL_FRAGMENT_PROGRAM_ARB, GL_MAX_PROGRAM_ENV_PARAMETERS_ARB, &gl_max));
938             gl_info->ps_arb_constantsF = gl_max;
939             TRACE_(d3d_caps)("Max ARB_FRAGMENT_PROGRAM float constants: %d\n", gl_info->ps_arb_constantsF);
940             GL_EXTCALL(glGetProgramivARB(GL_FRAGMENT_PROGRAM_ARB, GL_MAX_PROGRAM_NATIVE_TEMPORARIES_ARB, &gl_max));
941             gl_info->ps_arb_max_temps = gl_max;
942             TRACE_(d3d_caps)("Max ARB_FRAGMENT_PROGRAM native temporaries: %d\n", gl_info->ps_arb_max_temps);
943             GL_EXTCALL(glGetProgramivARB(GL_FRAGMENT_PROGRAM_ARB, GL_MAX_PROGRAM_NATIVE_INSTRUCTIONS_ARB, &gl_max));
944             gl_info->ps_arb_max_instructions = gl_max;
945             TRACE_(d3d_caps)("Max ARB_FRAGMENT_PROGRAM native instructions: %d\n", gl_info->ps_arb_max_instructions);
946         }
947         if (gl_info->supported[ARB_VERTEX_PROGRAM]) {
948             gl_info->vs_arb_version = VS_VERSION_11;
949             GL_EXTCALL(glGetProgramivARB(GL_VERTEX_PROGRAM_ARB, GL_MAX_PROGRAM_ENV_PARAMETERS_ARB, &gl_max));
950             gl_info->vs_arb_constantsF = gl_max;
951             TRACE_(d3d_caps)("Max ARB_VERTEX_PROGRAM float constants: %d\n", gl_info->vs_arb_constantsF);
952             GL_EXTCALL(glGetProgramivARB(GL_VERTEX_PROGRAM_ARB, GL_MAX_PROGRAM_NATIVE_TEMPORARIES_ARB, &gl_max));
953             gl_info->vs_arb_max_temps = gl_max;
954             TRACE_(d3d_caps)("Max ARB_VERTEX_PROGRAM native temporaries: %d\n", gl_info->vs_arb_max_temps);
955             GL_EXTCALL(glGetProgramivARB(GL_VERTEX_PROGRAM_ARB, GL_MAX_PROGRAM_NATIVE_INSTRUCTIONS_ARB, &gl_max));
956             gl_info->vs_arb_max_instructions = gl_max;
957             TRACE_(d3d_caps)("Max ARB_VERTEX_PROGRAM native instructions: %d\n", gl_info->vs_arb_max_instructions);
958
959             gl_info->arb_vs_offset_limit = test_arb_vs_offset_limit(gl_info);
960         }
961         if (gl_info->supported[ARB_VERTEX_SHADER]) {
962             glGetIntegerv(GL_MAX_VERTEX_UNIFORM_COMPONENTS_ARB, &gl_max);
963             gl_info->vs_glsl_constantsF = gl_max / 4;
964             TRACE_(d3d_caps)("Max ARB_VERTEX_SHADER float constants: %u\n", gl_info->vs_glsl_constantsF);
965         }
966         if (gl_info->supported[ARB_FRAGMENT_SHADER]) {
967             glGetIntegerv(GL_MAX_FRAGMENT_UNIFORM_COMPONENTS_ARB, &gl_max);
968             gl_info->ps_glsl_constantsF = gl_max / 4;
969             TRACE_(d3d_caps)("Max ARB_FRAGMENT_SHADER float constants: %u\n", gl_info->ps_glsl_constantsF);
970             glGetIntegerv(GL_MAX_VARYING_FLOATS_ARB, &gl_max);
971             gl_info->max_glsl_varyings = gl_max;
972             TRACE_(d3d_caps)("Max GLSL varyings: %u (%u 4 component varyings)\n", gl_max, gl_max / 4);
973         }
974         if (gl_info->supported[EXT_VERTEX_SHADER]) {
975             gl_info->vs_ati_version = VS_VERSION_11;
976         }
977         if (gl_info->supported[NV_VERTEX_PROGRAM3]) {
978             gl_info->vs_nv_version = VS_VERSION_30;
979         } else if (gl_info->supported[NV_VERTEX_PROGRAM2]) {
980             gl_info->vs_nv_version = VS_VERSION_20;
981         } else if (gl_info->supported[NV_VERTEX_PROGRAM1_1]) {
982             gl_info->vs_nv_version = VS_VERSION_11;
983         } else if (gl_info->supported[NV_VERTEX_PROGRAM]) {
984             gl_info->vs_nv_version = VS_VERSION_10;
985         }
986         if (gl_info->supported[NV_FRAGMENT_PROGRAM2]) {
987             gl_info->ps_nv_version = PS_VERSION_30;
988         } else if (gl_info->supported[NV_FRAGMENT_PROGRAM]) {
989             gl_info->ps_nv_version = PS_VERSION_20;
990         }
991         if (gl_info->supported[NV_LIGHT_MAX_EXPONENT]) {
992             glGetFloatv(GL_MAX_SHININESS_NV, &gl_info->max_shininess);
993         } else {
994             gl_info->max_shininess = 128.0;
995         }
996         if (gl_info->supported[ARB_TEXTURE_NON_POWER_OF_TWO]) {
997             /* If we have full NP2 texture support, disable GL_ARB_texture_rectangle because we will never use it.
998              * This saves a few redundant glDisable calls
999              */
1000             gl_info->supported[ARB_TEXTURE_RECTANGLE] = FALSE;
1001         }
1002         if(gl_info->supported[ATI_FRAGMENT_SHADER]) {
1003             /* Disable NV_register_combiners and fragment shader if this is supported.
1004              * generally the NV extensions are preferred over the ATI ones, and this
1005              * extension is disabled if register_combiners and texture_shader2 are both
1006              * supported. So we reach this place only if we have incomplete NV dxlevel 8
1007              * fragment processing support
1008              */
1009             gl_info->supported[NV_REGISTER_COMBINERS] = FALSE;
1010             gl_info->supported[NV_REGISTER_COMBINERS2] = FALSE;
1011             gl_info->supported[NV_TEXTURE_SHADER] = FALSE;
1012             gl_info->supported[NV_TEXTURE_SHADER2] = FALSE;
1013             gl_info->supported[NV_TEXTURE_SHADER3] = FALSE;
1014         }
1015         if(gl_info->supported[NV_HALF_FLOAT]) {
1016             /* GL_ARB_half_float_vertex is a subset of GL_NV_half_float */
1017             gl_info->supported[ARB_HALF_FLOAT_VERTEX] = TRUE;
1018         }
1019         if(gl_info->supported[ARB_POINT_SPRITE]) {
1020             gl_info->max_point_sprite_units = gl_info->max_textures;
1021         } else {
1022             gl_info->max_point_sprite_units = 0;
1023         }
1024     }
1025     checkGLcall("extension detection\n");
1026
1027     /* In some cases the number of texture stages can be larger than the number
1028      * of samplers. The GF4 for example can use only 2 samplers (no fragment
1029      * shaders), but 8 texture stages (register combiners). */
1030     gl_info->max_sampler_stages = max(gl_info->max_fragment_samplers, gl_info->max_texture_stages);
1031
1032     /* We can only use ORM_FBO when the hardware supports it. */
1033     if (wined3d_settings.offscreen_rendering_mode == ORM_FBO && !gl_info->supported[EXT_FRAMEBUFFER_OBJECT]) {
1034         WARN_(d3d_caps)("GL_EXT_framebuffer_object not supported, falling back to backbuffer offscreen rendering mode.\n");
1035         wined3d_settings.offscreen_rendering_mode = ORM_BACKBUFFER;
1036     }
1037
1038     /* MRTs are currently only supported when FBOs are used. */
1039     if (wined3d_settings.offscreen_rendering_mode != ORM_FBO) {
1040         gl_info->max_buffers = 1;
1041     }
1042
1043     /* Below is a list of Nvidia and ATI GPUs. Both vendors have dozens of different GPUs with roughly the same
1044      * features. In most cases GPUs from a certain family differ in clockspeeds, the amount of video memory and
1045      * in case of the latest videocards in the number of pixel/vertex pipelines.
1046      *
1047      * A Direct3D device object contains the PCI id (vendor + device) of the videocard which is used for
1048      * rendering. Various games use this information to get a rough estimation of the features of the card
1049      * and some might use it for enabling 3d effects only on certain types of videocards. In some cases
1050      * games might even use it to work around bugs which happen on certain videocards/driver combinations.
1051      * The problem is that OpenGL only exposes a rendering string containing the name of the videocard and
1052      * not the PCI id.
1053      *
1054      * Various games depend on the PCI id, so somehow we need to provide one. A simple option is to parse
1055      * the renderer string and translate this to the right PCI id. This is a lot of work because there are more
1056      * than 200 GPUs just for Nvidia. Various cards share the same renderer string, so the amount of code might
1057      * be 'small' but there are quite a number of exceptions which would make this a pain to maintain.
1058      * Another way would be to query the PCI id from the operating system (assuming this is the videocard which
1059      * is used for rendering which is not always the case). This would work but it is not very portable. Second
1060      * it would not work well in, let's say, a remote X situation in which the amount of 3d features which can be used
1061      * is limited.
1062      *
1063      * As said most games only use the PCI id to get an indication of the capabilities of the card.
1064      * It doesn't really matter if the given id is the correct one if we return the id of a card with
1065      * similar 3d features.
1066      *
1067      * The code below checks the OpenGL capabilities of a videocard and matches that to a certain level of
1068      * Direct3D functionality. Once a card passes the Direct3D9 check, we know that the card (in case of Nvidia)
1069      * is at least a GeforceFX. To give a better estimate we do a basic check on the renderer string but if that
1070      * won't pass we return a default card. This way is better than maintaining a full card database as even
1071      * without a full database we can return a card with similar features. Second the size of the database
1072      * can be made quite small because when you know what type of 3d functionality a card has, you know to which
1073      * GPU family the GPU must belong. Because of this you only have to check a small part of the renderer string
1074      * to distinguishes between different models from that family.
1075      *
1076      * The code also selects a default amount of video memory which we will use for an estimation of the amount
1077      * of free texture memory. In case of real D3D the amount of texture memory includes video memory and system
1078      * memory (to be specific AGP memory or in case of PCIE TurboCache/HyperMemory). We don't know how much
1079      * system memory can be addressed by the system but we can make a reasonable estimation about the amount of
1080      * video memory. If the value is slightly wrong it doesn't matter as we didn't include AGP-like memory which
1081      * makes the amount of addressable memory higher and second OpenGL isn't that critical it moves to system
1082      * memory behind our backs if really needed.
1083      * Note that the amount of video memory can be overruled using a registry setting.
1084      */
1085     switch (gl_info->gl_vendor) {
1086         case VENDOR_NVIDIA:
1087             /* Both the GeforceFX, 6xxx and 7xxx series support D3D9. The last two types have more
1088              * shader capabilities, so we use the shader capabilities to distinguish between FX and 6xxx/7xxx.
1089              */
1090             if(WINE_D3D9_CAPABLE(gl_info) && (gl_info->vs_nv_version == VS_VERSION_30)) {
1091                 /* Geforce 200 - highend */
1092                 if(strstr(gl_info->gl_renderer, "GTX 280") ||
1093                    strstr(gl_info->gl_renderer, "GTX 285") ||
1094                    strstr(gl_info->gl_renderer, "GTX 295"))
1095                 {
1096                     gl_info->gl_card = CARD_NVIDIA_GEFORCE_GTX280;
1097                     vidmem = 1024;
1098                 }
1099                 /* Geforce 200 - midend high */
1100                 if(strstr(gl_info->gl_renderer, "GTX 275")) {
1101                     gl_info->gl_card = CARD_NVIDIA_GEFORCE_GTX275;
1102                     vidmem = 896;
1103                 }
1104                 /* Geforce 200 - midend */
1105                 if(strstr(gl_info->gl_renderer, "GTX 260")) {
1106                     gl_info->gl_card = CARD_NVIDIA_GEFORCE_GTX260;
1107                     vidmem = 1024;
1108                 }
1109                 /* Geforce9 - highend / Geforce 200 - midend (GTS 150/250 are based on the same core) */
1110                 else if(strstr(gl_info->gl_renderer, "9800") ||
1111                         strstr(gl_info->gl_renderer, "GTS 150") ||
1112                         strstr(gl_info->gl_renderer, "GTS 250"))
1113                 {
1114                     gl_info->gl_card = CARD_NVIDIA_GEFORCE_9800GT;
1115                     vidmem = 512;
1116                 }
1117                 /* Geforce9 - midend */
1118                 else if(strstr(gl_info->gl_renderer, "9600")) {
1119                     gl_info->gl_card = CARD_NVIDIA_GEFORCE_9600GT;
1120                     vidmem = 384; /* The 9600GSO has 384MB, the 9600GT has 512-1024MB */
1121                 }
1122                 /* Geforce9 - midend low / Geforce 200 - low*/
1123                 else if(strstr(gl_info->gl_renderer, "9500") ||
1124                         strstr(gl_info->gl_renderer, "GT 120") ||
1125                         strstr(gl_info->gl_renderer, "GT 130"))
1126                 {
1127                     gl_info->gl_card = CARD_NVIDIA_GEFORCE_9500GT;
1128                     vidmem = 256; /* The 9500GT has 256-1024MB */
1129                 }
1130                 /* Geforce9 - lowend */
1131                 else if(strstr(gl_info->gl_renderer, "9400")) {
1132                     gl_info->gl_card = CARD_NVIDIA_GEFORCE_9400GT;
1133                     vidmem = 256; /* The 9400GT has 256-1024MB */
1134                 }
1135                 /* Geforce9 - lowend low */
1136                 else if(strstr(gl_info->gl_renderer, "9100") ||
1137                         strstr(gl_info->gl_renderer, "9200") ||
1138                         strstr(gl_info->gl_renderer, "9300") ||
1139                         strstr(gl_info->gl_renderer, "G 100"))
1140                 {
1141                     gl_info->gl_card = CARD_NVIDIA_GEFORCE_9200;
1142                     vidmem = 256; /* The 9100-9300 cards have 256MB */
1143                 }
1144                 /* Geforce8 - highend */
1145                 else if (strstr(gl_info->gl_renderer, "8800")) {
1146                     gl_info->gl_card = CARD_NVIDIA_GEFORCE_8800GTS;
1147                     vidmem = 320; /* The 8800GTS uses 320MB, a 8800GTX can have 768MB */
1148                 }
1149                 /* Geforce8 - midend mobile */
1150                 else if(strstr(gl_info->gl_renderer, "8600 M")) {
1151                     gl_info->gl_card = CARD_NVIDIA_GEFORCE_8600MGT;
1152                     vidmem = 512;
1153                 }
1154                 /* Geforce8 - midend */
1155                 else if(strstr(gl_info->gl_renderer, "8600") ||
1156                         strstr(gl_info->gl_renderer, "8700"))
1157                 {
1158                     gl_info->gl_card = CARD_NVIDIA_GEFORCE_8600GT;
1159                     vidmem = 256;
1160                 }
1161                 /* Geforce8 - lowend */
1162                 else if(strstr(gl_info->gl_renderer, "8300") ||
1163                         strstr(gl_info->gl_renderer, "8400") ||
1164                         strstr(gl_info->gl_renderer, "8500"))
1165                 {
1166                     gl_info->gl_card = CARD_NVIDIA_GEFORCE_8300GS;
1167                     vidmem = 128; /* 128-256MB for a 8300, 256-512MB for a 8400 */
1168                 }
1169                 /* Geforce7 - highend */
1170                 else if(strstr(gl_info->gl_renderer, "7800") ||
1171                         strstr(gl_info->gl_renderer, "7900") ||
1172                         strstr(gl_info->gl_renderer, "7950") ||
1173                         strstr(gl_info->gl_renderer, "Quadro FX 4") ||
1174                         strstr(gl_info->gl_renderer, "Quadro FX 5"))
1175                 {
1176                     gl_info->gl_card = CARD_NVIDIA_GEFORCE_7800GT;
1177                     vidmem = 256; /* A 7800GT uses 256MB while highend 7900 cards can use 512MB */
1178                 }
1179                 /* Geforce7 midend */
1180                 else if(strstr(gl_info->gl_renderer, "7600") ||
1181                         strstr(gl_info->gl_renderer, "7700")) {
1182                     gl_info->gl_card = CARD_NVIDIA_GEFORCE_7600;
1183                     vidmem = 256; /* The 7600 uses 256-512MB */
1184                 /* Geforce7 lower medium */
1185                 } else if(strstr(gl_info->gl_renderer, "7400")) {
1186                     gl_info->gl_card = CARD_NVIDIA_GEFORCE_7400;
1187                     vidmem = 256; /* The 7400 uses 256-512MB */
1188                 }
1189                 /* Geforce7 lowend */
1190                 else if(strstr(gl_info->gl_renderer, "7300")) {
1191                     gl_info->gl_card = CARD_NVIDIA_GEFORCE_7300;
1192                     vidmem = 256; /* Mac Pros with this card have 256 MB */
1193                 }
1194                 /* Geforce6 highend */
1195                 else if(strstr(gl_info->gl_renderer, "6800"))
1196                 {
1197                     gl_info->gl_card = CARD_NVIDIA_GEFORCE_6800;
1198                     vidmem = 128; /* The 6800 uses 128-256MB, the 7600 uses 256-512MB */
1199                 }
1200                 /* Geforce6 - midend */
1201                 else if(strstr(gl_info->gl_renderer, "6600") ||
1202                         strstr(gl_info->gl_renderer, "6610") ||
1203                         strstr(gl_info->gl_renderer, "6700"))
1204                 {
1205                     gl_info->gl_card = CARD_NVIDIA_GEFORCE_6600GT;
1206                     vidmem = 128; /* A 6600GT has 128-256MB */
1207                 }
1208                 /* Geforce6/7 lowend */
1209                 else {
1210                     gl_info->gl_card = CARD_NVIDIA_GEFORCE_6200; /* Geforce 6100/6150/6200/7300/7400/7500 */
1211                     vidmem = 64; /* */
1212                 }
1213             } else if(WINE_D3D9_CAPABLE(gl_info)) {
1214                 /* GeforceFX - highend */
1215                 if (strstr(gl_info->gl_renderer, "5800") ||
1216                     strstr(gl_info->gl_renderer, "5900") ||
1217                     strstr(gl_info->gl_renderer, "5950") ||
1218                     strstr(gl_info->gl_renderer, "Quadro FX"))
1219                 {
1220                     gl_info->gl_card = CARD_NVIDIA_GEFORCEFX_5800;
1221                     vidmem = 256; /* 5800-5900 cards use 256MB */
1222                 }
1223                 /* GeforceFX - midend */
1224                 else if(strstr(gl_info->gl_renderer, "5600") ||
1225                         strstr(gl_info->gl_renderer, "5650") ||
1226                         strstr(gl_info->gl_renderer, "5700") ||
1227                         strstr(gl_info->gl_renderer, "5750"))
1228                 {
1229                     gl_info->gl_card = CARD_NVIDIA_GEFORCEFX_5600;
1230                     vidmem = 128; /* A 5600 uses 128-256MB */
1231                 }
1232                 /* GeforceFX - lowend */
1233                 else {
1234                     gl_info->gl_card = CARD_NVIDIA_GEFORCEFX_5200; /* GeforceFX 5100/5200/5250/5300/5500 */
1235                     vidmem = 64; /* Normal FX5200 cards use 64-256MB; laptop (non-standard) can have less */
1236                 }
1237             } else if(WINE_D3D8_CAPABLE(gl_info)) {
1238                 if (strstr(gl_info->gl_renderer, "GeForce4 Ti") || strstr(gl_info->gl_renderer, "Quadro4")) {
1239                     gl_info->gl_card = CARD_NVIDIA_GEFORCE4_TI4200; /* Geforce4 Ti4200/Ti4400/Ti4600/Ti4800, Quadro4 */
1240                     vidmem = 64; /* Geforce4 Ti cards have 64-128MB */
1241                 }
1242                 else {
1243                     gl_info->gl_card = CARD_NVIDIA_GEFORCE3; /* Geforce3 standard/Ti200/Ti500, Quadro DCC */
1244                     vidmem = 64; /* Geforce3 cards have 64-128MB */
1245                 }
1246             } else if(WINE_D3D7_CAPABLE(gl_info)) {
1247                 if (strstr(gl_info->gl_renderer, "GeForce4 MX")) {
1248                     gl_info->gl_card = CARD_NVIDIA_GEFORCE4_MX; /* MX420/MX440/MX460/MX4000 */
1249                     vidmem = 64; /* Most Geforce4MX GPUs have at least 64MB of memory, some early models had 32MB but most have 64MB or even 128MB */
1250                 }
1251                 else if(strstr(gl_info->gl_renderer, "GeForce2 MX") || strstr(gl_info->gl_renderer, "Quadro2 MXR")) {
1252                     gl_info->gl_card = CARD_NVIDIA_GEFORCE2_MX; /* Geforce2 standard/MX100/MX200/MX400, Quadro2 MXR */
1253                     vidmem = 32; /* Geforce2MX GPUs have 32-64MB of video memory */
1254                 }
1255                 else if(strstr(gl_info->gl_renderer, "GeForce2") || strstr(gl_info->gl_renderer, "Quadro2")) {
1256                     gl_info->gl_card = CARD_NVIDIA_GEFORCE2; /* Geforce2 GTS/Pro/Ti/Ultra, Quadro2 */
1257                     vidmem = 32; /* Geforce2 GPUs have 32-64MB of video memory */
1258                 }
1259                 else {
1260                     gl_info->gl_card = CARD_NVIDIA_GEFORCE; /* Geforce 256/DDR, Quadro */
1261                     vidmem = 32; /* Most Geforce1 cards have 32MB, there are also some rare 16 and 64MB (Dell) models */
1262                 }
1263             } else {
1264                 if (strstr(gl_info->gl_renderer, "TNT2")) {
1265                     gl_info->gl_card = CARD_NVIDIA_RIVA_TNT2; /* Riva TNT2 standard/M64/Pro/Ultra */
1266                     vidmem = 32; /* Most TNT2 boards have 32MB, though there are 16MB boards too */
1267                 }
1268                 else {
1269                     gl_info->gl_card = CARD_NVIDIA_RIVA_TNT; /* Riva TNT, Vanta */
1270                     vidmem = 16; /* Most TNT boards have 16MB, some rare models have 8MB */
1271                 }
1272             }
1273             break;
1274         case VENDOR_ATI:
1275             if(WINE_D3D9_CAPABLE(gl_info)) {
1276                 /* Radeon R7xx HD4800 - highend */
1277                 if (strstr(gl_info->gl_renderer, "HD 4800") ||
1278                     strstr(gl_info->gl_renderer, "HD 4830") ||
1279                     strstr(gl_info->gl_renderer, "HD 4850") ||
1280                     strstr(gl_info->gl_renderer, "HD 4870") ||
1281                     strstr(gl_info->gl_renderer, "HD 4890"))
1282                 {
1283                     gl_info->gl_card = CARD_ATI_RADEON_HD4800;
1284                     vidmem = 512; /* HD4800 cards use 512-1024MB */
1285                 }
1286                 /* Radeon R6xx HD2900/HD3800 - highend */
1287                 else if (strstr(gl_info->gl_renderer, "HD 2900") ||
1288                          strstr(gl_info->gl_renderer, "HD 3870") ||
1289                          strstr(gl_info->gl_renderer, "HD 3850"))
1290                 {
1291                     gl_info->gl_card = CARD_ATI_RADEON_HD2900;
1292                     vidmem = 512; /* HD2900/HD3800 uses 256-1024MB */
1293                 }
1294                 /* Radeon R6xx HD2600/HD3600 - midend; HD3830 is China-only midend */
1295                 else if (strstr(gl_info->gl_renderer, "HD 2600") ||
1296                          strstr(gl_info->gl_renderer, "HD 3830") ||
1297                          strstr(gl_info->gl_renderer, "HD 3690") ||
1298                          strstr(gl_info->gl_renderer, "HD 3650"))
1299                 {
1300                     gl_info->gl_card = CARD_ATI_RADEON_HD2600;
1301                     vidmem = 256; /* HD2600/HD3600 uses 256-512MB */
1302                 }
1303                 /* Radeon R6xx HD2300/HD2400/HD3400 - lowend */
1304                 else if (strstr(gl_info->gl_renderer, "HD 2300") ||
1305                          strstr(gl_info->gl_renderer, "HD 2400") ||
1306                          strstr(gl_info->gl_renderer, "HD 3470") ||
1307                          strstr(gl_info->gl_renderer, "HD 3450") ||
1308                          strstr(gl_info->gl_renderer, "HD 3430"))
1309                 {
1310                     gl_info->gl_card = CARD_ATI_RADEON_HD2300;
1311                     vidmem = 128; /* HD2300 uses at least 128MB, HD2400 uses 256MB */
1312                 }
1313                 /* Radeon R6xx/R7xx integrated */
1314                 else if (strstr(gl_info->gl_renderer, "HD 3100") ||
1315                          strstr(gl_info->gl_renderer, "HD 3200") ||
1316                          strstr(gl_info->gl_renderer, "HD 3300"))
1317                 {
1318                     gl_info->gl_card = CARD_ATI_RADEON_HD3200;
1319                     vidmem = 128; /* 128MB */
1320                 }
1321                 /* Radeon R5xx */
1322                 else if (strstr(gl_info->gl_renderer, "X1600") ||
1323                          strstr(gl_info->gl_renderer, "X1650") ||
1324                          strstr(gl_info->gl_renderer, "X1800") ||
1325                          strstr(gl_info->gl_renderer, "X1900") ||
1326                          strstr(gl_info->gl_renderer, "X1950"))
1327                 {
1328                     gl_info->gl_card = CARD_ATI_RADEON_X1600;
1329                     vidmem = 128; /* X1600 uses 128-256MB, >=X1800 uses 256MB */
1330                 }
1331                 /* Radeon R4xx + X1300/X1400/X1450/X1550/X2300 (lowend R5xx) */
1332                 else if(strstr(gl_info->gl_renderer, "X700") ||
1333                         strstr(gl_info->gl_renderer, "X800") ||
1334                         strstr(gl_info->gl_renderer, "X850") ||
1335                         strstr(gl_info->gl_renderer, "X1300") ||
1336                         strstr(gl_info->gl_renderer, "X1400") ||
1337                         strstr(gl_info->gl_renderer, "X1450") ||
1338                         strstr(gl_info->gl_renderer, "X1550"))
1339                 {
1340                     gl_info->gl_card = CARD_ATI_RADEON_X700;
1341                     vidmem = 128; /* x700/x8*0 use 128-256MB, >=x1300 128-512MB */
1342                 }
1343                 /* Radeon Xpress Series - onboard, DX9b, Shader 2.0, 300-400MHz */
1344                 else if(strstr(gl_info->gl_renderer, "Radeon Xpress"))
1345                 {
1346                     gl_info->gl_card = CARD_ATI_RADEON_XPRESS_200M;
1347                     vidmem = 64; /* Shared RAM, BIOS configurable, 64-256M */
1348                 }
1349                 /* Radeon R3xx */ 
1350                 else {
1351                     gl_info->gl_card = CARD_ATI_RADEON_9500; /* Radeon 9500/9550/9600/9700/9800/X300/X550/X600 */
1352                     vidmem = 64; /* Radeon 9500 uses 64MB, higher models use up to 256MB */
1353                 }
1354             } else if(WINE_D3D8_CAPABLE(gl_info)) {
1355                 gl_info->gl_card = CARD_ATI_RADEON_8500; /* Radeon 8500/9000/9100/9200/9300 */
1356                 vidmem = 64; /* 8500/9000 cards use mostly 64MB, though there are 32MB and 128MB models */
1357             } else if(WINE_D3D7_CAPABLE(gl_info)) {
1358                 gl_info->gl_card = CARD_ATI_RADEON_7200; /* Radeon 7000/7100/7200/7500 */
1359                 vidmem = 32; /* There are models with up to 64MB */
1360             } else {
1361                 gl_info->gl_card = CARD_ATI_RAGE_128PRO;
1362                 vidmem = 16; /* There are 16-32MB models */
1363             }
1364             break;
1365         case VENDOR_INTEL:
1366             if (strstr(gl_info->gl_renderer, "GMA 950") ||
1367                 strstr(gl_info->gl_renderer, "945GM")) {
1368                 /* MacOS calls the card GMA 950, but everywhere else the PCI ID is named 945GM */
1369                 gl_info->gl_card = CARD_INTEL_I945GM;
1370                 vidmem = 64;
1371             } else if (strstr(gl_info->gl_renderer, "915GM")) {
1372                 gl_info->gl_card = CARD_INTEL_I915GM;
1373             } else if (strstr(gl_info->gl_renderer, "915G")) {
1374                 gl_info->gl_card = CARD_INTEL_I915G;
1375             } else if (strstr(gl_info->gl_renderer, "865G")) {
1376                 gl_info->gl_card = CARD_INTEL_I865G;
1377             } else if (strstr(gl_info->gl_renderer, "855G")) {
1378                 gl_info->gl_card = CARD_INTEL_I855G;
1379             } else if (strstr(gl_info->gl_renderer, "830G")) {
1380                 gl_info->gl_card = CARD_INTEL_I830G;
1381             } else {
1382                 gl_info->gl_card = CARD_INTEL_I915G;
1383             }
1384             break;
1385         case VENDOR_MESA:
1386         case VENDOR_WINE:
1387         default:
1388             /* Default to generic Nvidia hardware based on the supported OpenGL extensions. The choice 
1389              * for Nvidia was because the hardware and drivers they make are of good quality. This makes
1390              * them a good generic choice.
1391              */
1392             gl_info->gl_vendor = VENDOR_NVIDIA;
1393             if(WINE_D3D9_CAPABLE(gl_info))
1394                 gl_info->gl_card = CARD_NVIDIA_GEFORCEFX_5600;
1395             else if(WINE_D3D8_CAPABLE(gl_info))
1396                 gl_info->gl_card = CARD_NVIDIA_GEFORCE3;
1397             else if(WINE_D3D7_CAPABLE(gl_info))
1398                 gl_info->gl_card = CARD_NVIDIA_GEFORCE;
1399             else if(WINE_D3D6_CAPABLE(gl_info))
1400                 gl_info->gl_card = CARD_NVIDIA_RIVA_TNT;
1401             else
1402                 gl_info->gl_card = CARD_NVIDIA_RIVA_128;
1403     }
1404     TRACE_(d3d_caps)("FOUND (fake) card: 0x%x (vendor id), 0x%x (device id)\n", gl_info->gl_vendor, gl_info->gl_card);
1405
1406     /* If we have an estimate use it, else default to 64MB;  */
1407     if(vidmem)
1408         gl_info->vidmem = vidmem*1024*1024; /* convert from MBs to bytes */
1409     else
1410         gl_info->vidmem = WINE_DEFAULT_VIDMEM;
1411
1412     /* Load all the lookup tables */
1413     for (i = 0; i < MAX_LOOKUPS; i++) {
1414         stateLookup[i] = HeapAlloc(GetProcessHeap(), 0, sizeof(*stateLookup[i]) * (1 + maxLookup[i] - minLookup[i]) );
1415     }
1416
1417     stateLookup[WINELOOKUP_WARPPARAM][WINED3DTADDRESS_WRAP   - minLookup[WINELOOKUP_WARPPARAM]] = GL_REPEAT;
1418     stateLookup[WINELOOKUP_WARPPARAM][WINED3DTADDRESS_CLAMP  - minLookup[WINELOOKUP_WARPPARAM]] = GL_CLAMP_TO_EDGE;
1419     stateLookup[WINELOOKUP_WARPPARAM][WINED3DTADDRESS_BORDER - minLookup[WINELOOKUP_WARPPARAM]] =
1420              gl_info->supported[ARB_TEXTURE_BORDER_CLAMP] ? GL_CLAMP_TO_BORDER_ARB : GL_REPEAT;
1421     stateLookup[WINELOOKUP_WARPPARAM][WINED3DTADDRESS_BORDER - minLookup[WINELOOKUP_WARPPARAM]] =
1422              gl_info->supported[ARB_TEXTURE_BORDER_CLAMP] ? GL_CLAMP_TO_BORDER_ARB : GL_REPEAT;
1423     stateLookup[WINELOOKUP_WARPPARAM][WINED3DTADDRESS_MIRROR - minLookup[WINELOOKUP_WARPPARAM]] =
1424              gl_info->supported[ARB_TEXTURE_MIRRORED_REPEAT] ? GL_MIRRORED_REPEAT_ARB : GL_REPEAT;
1425     stateLookup[WINELOOKUP_WARPPARAM][WINED3DTADDRESS_MIRRORONCE - minLookup[WINELOOKUP_WARPPARAM]] =
1426              gl_info->supported[ATI_TEXTURE_MIRROR_ONCE] ? GL_MIRROR_CLAMP_TO_EDGE_ATI : GL_REPEAT;
1427
1428     magLookup[WINED3DTEXF_NONE        - WINED3DTEXF_NONE]  = GL_NEAREST;
1429     magLookup[WINED3DTEXF_POINT       - WINED3DTEXF_NONE] = GL_NEAREST;
1430     magLookup[WINED3DTEXF_LINEAR      - WINED3DTEXF_NONE] = GL_LINEAR;
1431     magLookup[WINED3DTEXF_ANISOTROPIC - WINED3DTEXF_NONE] =
1432              gl_info->supported[EXT_TEXTURE_FILTER_ANISOTROPIC] ? GL_LINEAR : GL_NEAREST;
1433
1434
1435     minMipLookup[WINED3DTEXF_NONE].mip[WINED3DTEXF_NONE]     = GL_LINEAR;
1436     minMipLookup[WINED3DTEXF_NONE].mip[WINED3DTEXF_POINT]    = GL_LINEAR;
1437     minMipLookup[WINED3DTEXF_NONE].mip[WINED3DTEXF_LINEAR]   = GL_LINEAR;
1438     minMipLookup[WINED3DTEXF_POINT].mip[WINED3DTEXF_NONE]    = GL_NEAREST;
1439     minMipLookup[WINED3DTEXF_POINT].mip[WINED3DTEXF_POINT]   = GL_NEAREST_MIPMAP_NEAREST;
1440     minMipLookup[WINED3DTEXF_POINT].mip[WINED3DTEXF_LINEAR]  = GL_NEAREST_MIPMAP_LINEAR;
1441     minMipLookup[WINED3DTEXF_LINEAR].mip[WINED3DTEXF_NONE]   = GL_LINEAR;
1442     minMipLookup[WINED3DTEXF_LINEAR].mip[WINED3DTEXF_POINT]  = GL_LINEAR_MIPMAP_NEAREST;
1443     minMipLookup[WINED3DTEXF_LINEAR].mip[WINED3DTEXF_LINEAR] = GL_LINEAR_MIPMAP_LINEAR;
1444     minMipLookup[WINED3DTEXF_ANISOTROPIC].mip[WINED3DTEXF_NONE]
1445             = gl_info->supported[EXT_TEXTURE_FILTER_ANISOTROPIC] ? GL_LINEAR_MIPMAP_LINEAR : GL_LINEAR;
1446     minMipLookup[WINED3DTEXF_ANISOTROPIC].mip[WINED3DTEXF_POINT]
1447             = gl_info->supported[EXT_TEXTURE_FILTER_ANISOTROPIC] ? GL_LINEAR_MIPMAP_NEAREST : GL_LINEAR;
1448     minMipLookup[WINED3DTEXF_ANISOTROPIC].mip[WINED3DTEXF_LINEAR]
1449             = gl_info->supported[EXT_TEXTURE_FILTER_ANISOTROPIC] ? GL_LINEAR_MIPMAP_LINEAR : GL_LINEAR;
1450
1451 /* TODO: config lookups */
1452
1453     /* Make sure there's an active HDC else the WGL extensions will fail */
1454     hdc = pwglGetCurrentDC();
1455     if (hdc) {
1456         /* Not all GL drivers might offer WGL extensions e.g. VirtualBox */
1457         if(GL_EXTCALL(wglGetExtensionsStringARB))
1458             WGL_Extensions = GL_EXTCALL(wglGetExtensionsStringARB(hdc));
1459
1460         if (NULL == WGL_Extensions) {
1461             ERR("   WGL_Extensions returns NULL\n");
1462         } else {
1463             TRACE_(d3d_caps)("WGL_Extensions reported:\n");
1464             while (*WGL_Extensions != 0x00) {
1465                 const char *Start;
1466                 char ThisExtn[256];
1467                 size_t len;
1468
1469                 while (isspace(*WGL_Extensions)) WGL_Extensions++;
1470                 Start = WGL_Extensions;
1471                 while (!isspace(*WGL_Extensions) && *WGL_Extensions != 0x00) {
1472                     WGL_Extensions++;
1473                 }
1474
1475                 len = WGL_Extensions - Start;
1476                 if (len == 0 || len >= sizeof(ThisExtn))
1477                     continue;
1478
1479                 memcpy(ThisExtn, Start, len);
1480                 ThisExtn[len] = '\0';
1481                 TRACE_(d3d_caps)("- %s\n", ThisExtn);
1482
1483                 if (!strcmp(ThisExtn, "WGL_ARB_pbuffer")) {
1484                     gl_info->supported[WGL_ARB_PBUFFER] = TRUE;
1485                     TRACE_(d3d_caps)("FOUND: WGL_ARB_pbuffer support\n");
1486                 }
1487                 if (!strcmp(ThisExtn, "WGL_ARB_pixel_format")) {
1488                     gl_info->supported[WGL_ARB_PIXEL_FORMAT] = TRUE;
1489                     TRACE_(d3d_caps)("FOUND: WGL_ARB_pixel_format support\n");
1490                 }
1491                 if (!strcmp(ThisExtn, "WGL_WINE_pixel_format_passthrough")) {
1492                     gl_info->supported[WGL_WINE_PIXEL_FORMAT_PASSTHROUGH] = TRUE;
1493                     TRACE_(d3d_caps)("FOUND: WGL_WINE_pixel_format_passthrough support\n");
1494                 }
1495             }
1496         }
1497     }
1498     LEAVE_GL();
1499
1500     return return_value;
1501 }
1502
1503 /**********************************************************
1504  * IWineD3D implementation follows
1505  **********************************************************/
1506
1507 static UINT     WINAPI IWineD3DImpl_GetAdapterCount (IWineD3D *iface) {
1508     IWineD3DImpl *This = (IWineD3DImpl *)iface;
1509
1510     TRACE_(d3d_caps)("(%p): Reporting %u adapters\n", This, This->adapter_count);
1511
1512     return This->adapter_count;
1513 }
1514
1515 static HRESULT  WINAPI IWineD3DImpl_RegisterSoftwareDevice(IWineD3D *iface, void* pInitializeFunction) {
1516     IWineD3DImpl *This = (IWineD3DImpl *)iface;
1517     FIXME("(%p)->(%p): stub\n", This, pInitializeFunction);
1518     return WINED3D_OK;
1519 }
1520
1521 static HMONITOR WINAPI IWineD3DImpl_GetAdapterMonitor(IWineD3D *iface, UINT Adapter) {
1522     IWineD3DImpl *This = (IWineD3DImpl *)iface;
1523
1524     TRACE_(d3d_caps)("(%p)->(%d)\n", This, Adapter);
1525
1526     if (Adapter >= IWineD3DImpl_GetAdapterCount(iface)) {
1527         return NULL;
1528     }
1529
1530     return MonitorFromPoint(This->adapters[Adapter].monitorPoint, MONITOR_DEFAULTTOPRIMARY);
1531 }
1532
1533 /* FIXME: GetAdapterModeCount and EnumAdapterModes currently only returns modes
1534      of the same bpp but different resolutions                                  */
1535
1536 /* Note: dx9 supplies a format. Calls from d3d8 supply WINED3DFMT_UNKNOWN */
1537 static UINT     WINAPI IWineD3DImpl_GetAdapterModeCount(IWineD3D *iface, UINT Adapter, WINED3DFORMAT Format) {
1538     IWineD3DImpl *This = (IWineD3DImpl *)iface;
1539     TRACE_(d3d_caps)("(%p}->(Adapter: %d, Format: %s)\n", This, Adapter, debug_d3dformat(Format));
1540
1541     if (Adapter >= IWineD3D_GetAdapterCount(iface)) {
1542         return 0;
1543     }
1544
1545     /* TODO: Store modes per adapter and read it from the adapter structure */
1546     if (Adapter == 0) { /* Display */
1547         int i = 0;
1548         int j = 0;
1549
1550         if (!DEBUG_SINGLE_MODE) {
1551             DEVMODEW DevModeW;
1552
1553             ZeroMemory(&DevModeW, sizeof(DevModeW));
1554             DevModeW.dmSize = sizeof(DevModeW);
1555             while (EnumDisplaySettingsExW(NULL, j, &DevModeW, 0)) {
1556                 j++;
1557                 switch (Format)
1558                 {
1559                     case WINED3DFMT_UNKNOWN:
1560                         /* This is for D3D8, do not enumerate P8 here */
1561                         if (DevModeW.dmBitsPerPel == 32 ||
1562                             DevModeW.dmBitsPerPel == 16) i++;
1563                         break;
1564                     case WINED3DFMT_X8R8G8B8:
1565                         if (DevModeW.dmBitsPerPel == 32) i++;
1566                         break;
1567                     case WINED3DFMT_R5G6B5:
1568                         if (DevModeW.dmBitsPerPel == 16) i++;
1569                         break;
1570                     case WINED3DFMT_P8:
1571                         if (DevModeW.dmBitsPerPel == 8) i++;
1572                         break;
1573                     default:
1574                         /* Skip other modes as they do not match the requested format */
1575                         break;
1576                 }
1577             }
1578         } else {
1579             i = 1;
1580             j = 1;
1581         }
1582
1583         TRACE_(d3d_caps)("(%p}->(Adapter: %d) => %d (out of %d)\n", This, Adapter, i, j);
1584         return i;
1585     } else {
1586         FIXME_(d3d_caps)("Adapter not primary display\n");
1587     }
1588     return 0;
1589 }
1590
1591 /* Note: dx9 supplies a format. Calls from d3d8 supply WINED3DFMT_UNKNOWN */
1592 static HRESULT WINAPI IWineD3DImpl_EnumAdapterModes(IWineD3D *iface, UINT Adapter, WINED3DFORMAT Format, UINT Mode, WINED3DDISPLAYMODE* pMode) {
1593     IWineD3DImpl *This = (IWineD3DImpl *)iface;
1594     TRACE_(d3d_caps)("(%p}->(Adapter:%d, mode:%d, pMode:%p, format:%s)\n", This, Adapter, Mode, pMode, debug_d3dformat(Format));
1595
1596     /* Validate the parameters as much as possible */
1597     if (NULL == pMode ||
1598         Adapter >= IWineD3DImpl_GetAdapterCount(iface) ||
1599         Mode    >= IWineD3DImpl_GetAdapterModeCount(iface, Adapter, Format)) {
1600         return WINED3DERR_INVALIDCALL;
1601     }
1602
1603     /* TODO: Store modes per adapter and read it from the adapter structure */
1604     if (Adapter == 0 && !DEBUG_SINGLE_MODE) { /* Display */
1605         DEVMODEW DevModeW;
1606         int ModeIdx = 0;
1607         UINT i = 0;
1608         int j = 0;
1609
1610         ZeroMemory(&DevModeW, sizeof(DevModeW));
1611         DevModeW.dmSize = sizeof(DevModeW);
1612
1613         /* If we are filtering to a specific format (D3D9), then need to skip
1614            all unrelated modes, but if mode is irrelevant (D3D8), then we can
1615            just count through the ones with valid bit depths */
1616         while ((i<=Mode) && EnumDisplaySettingsExW(NULL, j++, &DevModeW, 0)) {
1617             switch (Format)
1618             {
1619                 case WINED3DFMT_UNKNOWN:
1620                     /* This is D3D8. Do not enumerate P8 here */
1621                     if (DevModeW.dmBitsPerPel == 32 ||
1622                         DevModeW.dmBitsPerPel == 16) i++;
1623                     break;
1624                 case WINED3DFMT_X8R8G8B8:
1625                     if (DevModeW.dmBitsPerPel == 32) i++;
1626                     break;
1627                 case WINED3DFMT_R5G6B5:
1628                     if (DevModeW.dmBitsPerPel == 16) i++;
1629                     break;
1630                 case WINED3DFMT_P8:
1631                     if (DevModeW.dmBitsPerPel == 8) i++;
1632                     break;
1633                 default:
1634                     /* Modes that don't match what we support can get an early-out */
1635                     TRACE_(d3d_caps)("Searching for %s, returning D3DERR_INVALIDCALL\n", debug_d3dformat(Format));
1636                     return WINED3DERR_INVALIDCALL;
1637             }
1638         }
1639
1640         if (i == 0) {
1641             TRACE_(d3d_caps)("No modes found for format (%x - %s)\n", Format, debug_d3dformat(Format));
1642             return WINED3DERR_INVALIDCALL;
1643         }
1644         ModeIdx = j - 1;
1645
1646         /* Now get the display mode via the calculated index */
1647         if (EnumDisplaySettingsExW(NULL, ModeIdx, &DevModeW, 0)) {
1648             pMode->Width        = DevModeW.dmPelsWidth;
1649             pMode->Height       = DevModeW.dmPelsHeight;
1650             pMode->RefreshRate  = WINED3DADAPTER_DEFAULT;
1651             if (DevModeW.dmFields & DM_DISPLAYFREQUENCY)
1652                 pMode->RefreshRate = DevModeW.dmDisplayFrequency;
1653
1654             if (Format == WINED3DFMT_UNKNOWN) {
1655                 pMode->Format = pixelformat_for_depth(DevModeW.dmBitsPerPel);
1656             } else {
1657                 pMode->Format = Format;
1658             }
1659         } else {
1660             TRACE_(d3d_caps)("Requested mode out of range %d\n", Mode);
1661             return WINED3DERR_INVALIDCALL;
1662         }
1663
1664         TRACE_(d3d_caps)("W %d H %d rr %d fmt (%x - %s) bpp %u\n", pMode->Width, pMode->Height,
1665                 pMode->RefreshRate, pMode->Format, debug_d3dformat(pMode->Format),
1666                 DevModeW.dmBitsPerPel);
1667
1668     } else if (DEBUG_SINGLE_MODE) {
1669         /* Return one setting of the format requested */
1670         if (Mode > 0) return WINED3DERR_INVALIDCALL;
1671         pMode->Width        = 800;
1672         pMode->Height       = 600;
1673         pMode->RefreshRate  = 60;
1674         pMode->Format       = (Format == WINED3DFMT_UNKNOWN) ? WINED3DFMT_X8R8G8B8 : Format;
1675     } else {
1676         FIXME_(d3d_caps)("Adapter not primary display\n");
1677     }
1678
1679     return WINED3D_OK;
1680 }
1681
1682 static HRESULT WINAPI IWineD3DImpl_GetAdapterDisplayMode(IWineD3D *iface, UINT Adapter, WINED3DDISPLAYMODE* pMode) {
1683     IWineD3DImpl *This = (IWineD3DImpl *)iface;
1684     TRACE_(d3d_caps)("(%p}->(Adapter: %d, pMode: %p)\n", This, Adapter, pMode);
1685
1686     if (NULL == pMode ||
1687         Adapter >= IWineD3D_GetAdapterCount(iface)) {
1688         return WINED3DERR_INVALIDCALL;
1689     }
1690
1691     if (Adapter == 0) { /* Display */
1692         int bpp = 0;
1693         DEVMODEW DevModeW;
1694
1695         ZeroMemory(&DevModeW, sizeof(DevModeW));
1696         DevModeW.dmSize = sizeof(DevModeW);
1697
1698         EnumDisplaySettingsExW(NULL, ENUM_CURRENT_SETTINGS, &DevModeW, 0);
1699         pMode->Width        = DevModeW.dmPelsWidth;
1700         pMode->Height       = DevModeW.dmPelsHeight;
1701         bpp                 = DevModeW.dmBitsPerPel;
1702         pMode->RefreshRate  = WINED3DADAPTER_DEFAULT;
1703         if (DevModeW.dmFields&DM_DISPLAYFREQUENCY)
1704         {
1705             pMode->RefreshRate = DevModeW.dmDisplayFrequency;
1706         }
1707
1708         pMode->Format = pixelformat_for_depth(bpp);
1709     } else {
1710         FIXME_(d3d_caps)("Adapter not primary display\n");
1711     }
1712
1713     TRACE_(d3d_caps)("returning w:%d, h:%d, ref:%d, fmt:%s\n", pMode->Width,
1714           pMode->Height, pMode->RefreshRate, debug_d3dformat(pMode->Format));
1715     return WINED3D_OK;
1716 }
1717
1718 /* NOTE: due to structure differences between dx8 and dx9 D3DADAPTER_IDENTIFIER,
1719    and fields being inserted in the middle, a new structure is used in place    */
1720 static HRESULT WINAPI IWineD3DImpl_GetAdapterIdentifier(IWineD3D *iface, UINT Adapter, DWORD Flags,
1721                                                    WINED3DADAPTER_IDENTIFIER* pIdentifier) {
1722     IWineD3DImpl *This = (IWineD3DImpl *)iface;
1723
1724     TRACE_(d3d_caps)("(%p}->(Adapter: %d, Flags: %x, pId=%p)\n", This, Adapter, Flags, pIdentifier);
1725
1726     if (Adapter >= IWineD3D_GetAdapterCount(iface)) {
1727         return WINED3DERR_INVALIDCALL;
1728     }
1729
1730     /* Return the information requested */
1731     TRACE_(d3d_caps)("device/Vendor Name and Version detection using FillGLCaps\n");
1732     strcpy(pIdentifier->Driver, This->adapters[Adapter].driver);
1733     if(This->adapters[Adapter].gl_info.driver_description)
1734         strcpy(pIdentifier->Description, This->adapters[Adapter].gl_info.driver_description);
1735     else /* Copy default description "Direct3D HAL" */
1736         strcpy(pIdentifier->Description, This->adapters[Adapter].description);
1737
1738     /* Note dx8 doesn't supply a DeviceName */
1739     if (NULL != pIdentifier->DeviceName) strcpy(pIdentifier->DeviceName, "\\\\.\\DISPLAY1"); /* FIXME: May depend on desktop? */
1740     pIdentifier->DriverVersion->u.HighPart = This->adapters[Adapter].gl_info.driver_version_hipart;
1741     pIdentifier->DriverVersion->u.LowPart = This->adapters[Adapter].gl_info.driver_version;
1742     *(pIdentifier->VendorId) = This->adapters[Adapter].gl_info.gl_vendor;
1743     *(pIdentifier->DeviceId) = This->adapters[Adapter].gl_info.gl_card;
1744     *(pIdentifier->SubSysId) = 0;
1745     *(pIdentifier->Revision) = 0;
1746     *pIdentifier->DeviceIdentifier = IID_D3DDEVICE_D3DUID;
1747
1748     if(wined3d_settings.pci_device_id != PCI_DEVICE_NONE)
1749     {
1750         TRACE_(d3d_caps)("Overriding pci device id with: %x\n", wined3d_settings.pci_device_id);
1751         *(pIdentifier->DeviceId) = wined3d_settings.pci_device_id;
1752     }
1753
1754     if(wined3d_settings.pci_vendor_id != PCI_VENDOR_NONE)
1755     {
1756         TRACE_(d3d_caps)("Overriding pci vendor id with: %x\n", wined3d_settings.pci_vendor_id);
1757         *(pIdentifier->VendorId) = wined3d_settings.pci_vendor_id;
1758     }
1759
1760     if (Flags & WINED3DENUM_NO_WHQL_LEVEL) {
1761         *(pIdentifier->WHQLLevel) = 0;
1762     } else {
1763         *(pIdentifier->WHQLLevel) = 1;
1764     }
1765
1766     return WINED3D_OK;
1767 }
1768
1769 static BOOL IWineD3DImpl_IsPixelFormatCompatibleWithRenderFmt(const WineD3D_GL_Info *gl_info,
1770         const WineD3D_PixelFormat *cfg, const struct GlPixelFormatDesc *format_desc)
1771 {
1772     short redSize, greenSize, blueSize, alphaSize, colorBits;
1773
1774     if(!cfg)
1775         return FALSE;
1776
1777     if(cfg->iPixelType == WGL_TYPE_RGBA_ARB) { /* Integer RGBA formats */
1778         if (!getColorBits(format_desc, &redSize, &greenSize, &blueSize, &alphaSize, &colorBits))
1779         {
1780             ERR("Unable to check compatibility for Format=%s\n", debug_d3dformat(format_desc->format));
1781             return FALSE;
1782         }
1783
1784         if(cfg->redSize < redSize)
1785             return FALSE;
1786
1787         if(cfg->greenSize < greenSize)
1788             return FALSE;
1789
1790         if(cfg->blueSize < blueSize)
1791             return FALSE;
1792
1793         if(cfg->alphaSize < alphaSize)
1794             return FALSE;
1795
1796         return TRUE;
1797     } else if(cfg->iPixelType == WGL_TYPE_RGBA_FLOAT_ARB) { /* Float RGBA formats; TODO: WGL_NV_float_buffer */
1798         if (format_desc->format == WINED3DFMT_R16_FLOAT)
1799             return (cfg->redSize == 16 && cfg->greenSize == 0 && cfg->blueSize == 0 && cfg->alphaSize == 0);
1800         if (format_desc->format == WINED3DFMT_R16G16_FLOAT)
1801             return (cfg->redSize == 16 && cfg->greenSize == 16 && cfg->blueSize == 0 && cfg->alphaSize == 0);
1802         if (format_desc->format == WINED3DFMT_R16G16B16A16_FLOAT)
1803             return (cfg->redSize == 16 && cfg->greenSize == 16 && cfg->blueSize == 16 && cfg->alphaSize == 16);
1804         if (format_desc->format == WINED3DFMT_R32_FLOAT)
1805             return (cfg->redSize == 32 && cfg->greenSize == 0 && cfg->blueSize == 0 && cfg->alphaSize == 0);
1806         if (format_desc->format == WINED3DFMT_R32G32_FLOAT)
1807             return (cfg->redSize == 32 && cfg->greenSize == 32 && cfg->blueSize == 0 && cfg->alphaSize == 0);
1808         if (format_desc->format == WINED3DFMT_R32G32B32A32_FLOAT)
1809             return (cfg->redSize == 32 && cfg->greenSize == 32 && cfg->blueSize == 32 && cfg->alphaSize == 32);
1810     } else {
1811         /* Probably a color index mode */
1812         return FALSE;
1813     }
1814
1815     return FALSE;
1816 }
1817
1818 static BOOL IWineD3DImpl_IsPixelFormatCompatibleWithDepthFmt(const WineD3D_GL_Info *gl_info,
1819         const WineD3D_PixelFormat *cfg, const struct GlPixelFormatDesc *format_desc)
1820 {
1821     short depthSize, stencilSize;
1822     BOOL lockable = FALSE;
1823
1824     if(!cfg)
1825         return FALSE;
1826
1827     if (!getDepthStencilBits(format_desc, &depthSize, &stencilSize))
1828     {
1829         ERR("Unable to check compatibility for Format=%s\n", debug_d3dformat(format_desc->format));
1830         return FALSE;
1831     }
1832
1833     if ((format_desc->format == WINED3DFMT_D16_LOCKABLE) || (format_desc->format == WINED3DFMT_D32F_LOCKABLE))
1834         lockable = TRUE;
1835
1836     /* On some modern cards like the Geforce8/9 GLX doesn't offer some dephthstencil formats which D3D9 reports.
1837      * We can safely report 'compatible' formats (e.g. D24 can be used for D16) as long as we aren't dealing with
1838      * a lockable format. This also helps D3D <= 7 as they expect D16 which isn't offered without this on Geforce8 cards. */
1839     if(!(cfg->depthSize == depthSize || (!lockable && cfg->depthSize > depthSize)))
1840         return FALSE;
1841
1842     /* Some cards like Intel i915 ones only offer D24S8 but lots of games also need a format without stencil, so
1843      * allow more stencil bits than requested. */
1844     if(cfg->stencilSize < stencilSize)
1845         return FALSE;
1846
1847     return TRUE;
1848 }
1849
1850 static HRESULT WINAPI IWineD3DImpl_CheckDepthStencilMatch(IWineD3D *iface, UINT Adapter, WINED3DDEVTYPE DeviceType,
1851                                                    WINED3DFORMAT AdapterFormat,
1852                                                    WINED3DFORMAT RenderTargetFormat,
1853                                                    WINED3DFORMAT DepthStencilFormat) {
1854     IWineD3DImpl *This = (IWineD3DImpl *)iface;
1855     int nCfgs;
1856     const WineD3D_PixelFormat *cfgs;
1857     const struct WineD3DAdapter *adapter;
1858     const struct GlPixelFormatDesc *rt_format_desc;
1859     const struct GlPixelFormatDesc *ds_format_desc;
1860     int it;
1861
1862     WARN_(d3d_caps)("(%p)-> (STUB) (Adptr:%d, DevType:(%x,%s), AdptFmt:(%x,%s), RendrTgtFmt:(%x,%s), DepthStencilFmt:(%x,%s))\n",
1863            This, Adapter,
1864            DeviceType, debug_d3ddevicetype(DeviceType),
1865            AdapterFormat, debug_d3dformat(AdapterFormat),
1866            RenderTargetFormat, debug_d3dformat(RenderTargetFormat),
1867            DepthStencilFormat, debug_d3dformat(DepthStencilFormat));
1868
1869     if (Adapter >= IWineD3D_GetAdapterCount(iface)) {
1870         TRACE("(%p) Failed: Atapter (%u) higher than supported adapters (%u) returning WINED3DERR_INVALIDCALL\n", This, Adapter, IWineD3D_GetAdapterCount(iface));
1871         return WINED3DERR_INVALIDCALL;
1872     }
1873
1874     adapter = &This->adapters[Adapter];
1875     rt_format_desc = getFormatDescEntry(RenderTargetFormat, &adapter->gl_info);
1876     ds_format_desc = getFormatDescEntry(DepthStencilFormat, &adapter->gl_info);
1877     cfgs = adapter->cfgs;
1878     nCfgs = adapter->nCfgs;
1879     for (it = 0; it < nCfgs; ++it) {
1880         if (IWineD3DImpl_IsPixelFormatCompatibleWithRenderFmt(&adapter->gl_info, &cfgs[it], rt_format_desc))
1881         {
1882             if (IWineD3DImpl_IsPixelFormatCompatibleWithDepthFmt(&adapter->gl_info, &cfgs[it], ds_format_desc))
1883             {
1884                 TRACE_(d3d_caps)("(%p) : Formats matched\n", This);
1885                 return WINED3D_OK;
1886             }
1887         }
1888     }
1889     WARN_(d3d_caps)("unsupported format pair: %s and %s\n", debug_d3dformat(RenderTargetFormat), debug_d3dformat(DepthStencilFormat));
1890
1891     return WINED3DERR_NOTAVAILABLE;
1892 }
1893
1894 static HRESULT WINAPI IWineD3DImpl_CheckDeviceMultiSampleType(IWineD3D *iface, UINT Adapter, WINED3DDEVTYPE DeviceType, 
1895                                                        WINED3DFORMAT SurfaceFormat,
1896                                                        BOOL Windowed, WINED3DMULTISAMPLE_TYPE MultiSampleType, DWORD*   pQualityLevels) {
1897
1898     IWineD3DImpl *This = (IWineD3DImpl *)iface;
1899     const struct GlPixelFormatDesc *glDesc;
1900     const struct WineD3DAdapter *adapter;
1901
1902     TRACE_(d3d_caps)("(%p)-> (Adptr:%d, DevType:(%x,%s), SurfFmt:(%x,%s), Win?%d, MultiSamp:%x, pQual:%p)\n",
1903           This,
1904           Adapter,
1905           DeviceType, debug_d3ddevicetype(DeviceType),
1906           SurfaceFormat, debug_d3dformat(SurfaceFormat),
1907           Windowed,
1908           MultiSampleType,
1909           pQualityLevels);
1910
1911     if (Adapter >= IWineD3D_GetAdapterCount(iface)) {
1912         return WINED3DERR_INVALIDCALL;
1913     }
1914
1915     /* TODO: handle Windowed, add more quality levels */
1916
1917     if (WINED3DMULTISAMPLE_NONE == MultiSampleType) {
1918         if(pQualityLevels) *pQualityLevels = 1;
1919         return WINED3D_OK;
1920     }
1921
1922     /* By default multisampling is disabled right now as it causes issues
1923      * on some Nvidia driver versions and it doesn't work well in combination
1924      * with FBOs yet. */
1925     if(!wined3d_settings.allow_multisampling)
1926         return WINED3DERR_NOTAVAILABLE;
1927
1928     adapter = &This->adapters[Adapter];
1929     glDesc = getFormatDescEntry(SurfaceFormat, &adapter->gl_info);
1930     if (!glDesc) return WINED3DERR_INVALIDCALL;
1931
1932     if(glDesc->Flags & (WINED3DFMT_FLAG_DEPTH | WINED3DFMT_FLAG_STENCIL)) {
1933         int i, nCfgs;
1934         const WineD3D_PixelFormat *cfgs;
1935
1936         cfgs = adapter->cfgs;
1937         nCfgs = adapter->nCfgs;
1938         for(i=0; i<nCfgs; i++) {
1939             if(cfgs[i].numSamples != MultiSampleType)
1940                 continue;
1941
1942             if (!IWineD3DImpl_IsPixelFormatCompatibleWithDepthFmt(&adapter->gl_info, &cfgs[i], glDesc))
1943                 continue;
1944
1945             TRACE("Found iPixelFormat=%d to support MultiSampleType=%d for format %s\n", cfgs[i].iPixelFormat, MultiSampleType, debug_d3dformat(SurfaceFormat));
1946
1947             if(pQualityLevels)
1948                 *pQualityLevels = 1; /* Guess at a value! */
1949             return WINED3D_OK;
1950         }
1951     }
1952     else if(glDesc->Flags & WINED3DFMT_FLAG_RENDERTARGET) {
1953         short redSize, greenSize, blueSize, alphaSize, colorBits;
1954         int i, nCfgs;
1955         const WineD3D_PixelFormat *cfgs;
1956
1957         if (!getColorBits(glDesc, &redSize, &greenSize, &blueSize, &alphaSize, &colorBits))
1958         {
1959             ERR("Unable to color bits for format %#x, can't check multisampling capability!\n", SurfaceFormat);
1960             return WINED3DERR_NOTAVAILABLE;
1961         }
1962
1963         cfgs = adapter->cfgs;
1964         nCfgs = adapter->nCfgs;
1965         for(i=0; i<nCfgs; i++) {
1966             if(cfgs[i].numSamples != MultiSampleType)
1967                 continue;
1968             if(cfgs[i].redSize != redSize)
1969                 continue;
1970             if(cfgs[i].greenSize != greenSize)
1971                 continue;
1972             if(cfgs[i].blueSize != blueSize)
1973                 continue;
1974             if(cfgs[i].alphaSize != alphaSize)
1975                 continue;
1976
1977             TRACE("Found iPixelFormat=%d to support MultiSampleType=%d for format %s\n", cfgs[i].iPixelFormat, MultiSampleType, debug_d3dformat(SurfaceFormat));
1978
1979             if(pQualityLevels)
1980                 *pQualityLevels = 1; /* Guess at a value! */
1981             return WINED3D_OK;
1982         }
1983     }
1984     return WINED3DERR_NOTAVAILABLE;
1985 }
1986
1987 static HRESULT WINAPI IWineD3DImpl_CheckDeviceType(IWineD3D *iface, UINT Adapter, WINED3DDEVTYPE DeviceType,
1988                                             WINED3DFORMAT DisplayFormat, WINED3DFORMAT BackBufferFormat, BOOL Windowed) {
1989
1990     IWineD3DImpl *This = (IWineD3DImpl *)iface;
1991     HRESULT hr = WINED3DERR_NOTAVAILABLE;
1992     UINT nmodes;
1993
1994     TRACE_(d3d_caps)("(%p)-> (STUB) (Adptr:%d, CheckType:(%x,%s), DispFmt:(%x,%s), BackBuf:(%x,%s), Win?%d): stub\n",
1995           This,
1996           Adapter,
1997           DeviceType, debug_d3ddevicetype(DeviceType),
1998           DisplayFormat, debug_d3dformat(DisplayFormat),
1999           BackBufferFormat, debug_d3dformat(BackBufferFormat),
2000           Windowed);
2001
2002     if (Adapter >= IWineD3D_GetAdapterCount(iface)) {
2003         WARN_(d3d_caps)("Adapter >= IWineD3D_GetAdapterCount(iface), returning WINED3DERR_INVALIDCALL\n");
2004         return WINED3DERR_INVALIDCALL;
2005     }
2006
2007     /* The task of this function is to check whether a certain display / backbuffer format
2008      * combination is available on the given adapter. In fullscreen mode microsoft specified
2009      * that the display format shouldn't provide alpha and that ignoring alpha the backbuffer
2010      * and display format should match exactly.
2011      * In windowed mode format conversion can occur and this depends on the driver. When format
2012      * conversion is done, this function should nevertheless fail and applications need to use
2013      * CheckDeviceFormatConversion.
2014      * At the moment we assume that fullscreen and windowed have the same capabilities */
2015
2016     /* There are only 4 display formats */
2017     if(!((DisplayFormat == WINED3DFMT_R5G6B5) ||
2018          (DisplayFormat == WINED3DFMT_X1R5G5B5) ||
2019          (DisplayFormat == WINED3DFMT_X8R8G8B8) ||
2020          (DisplayFormat == WINED3DFMT_A2R10G10B10)))
2021     {
2022         TRACE_(d3d_caps)("Format %s unsupported as display format\n", debug_d3dformat(DisplayFormat));
2023         return WINED3DERR_NOTAVAILABLE;
2024     }
2025
2026     /* If the requested DisplayFormat is not available, don't continue */
2027     nmodes = IWineD3DImpl_GetAdapterModeCount(iface, Adapter, DisplayFormat);
2028     if(!nmodes) {
2029         TRACE_(d3d_caps)("No available modes for display format %s\n", debug_d3dformat(DisplayFormat));
2030         return WINED3DERR_NOTAVAILABLE;
2031     }
2032
2033     /* Windowed mode allows you to specify WINED3DFMT_UNKNOWN for the backbufferformat, it means 'reuse' the display format for the backbuffer */
2034     if(!Windowed && BackBufferFormat == WINED3DFMT_UNKNOWN) {
2035         TRACE_(d3d_caps)("BackBufferFormat WINED3FMT_UNKNOWN not available in Windowed mode\n");
2036         return WINED3DERR_NOTAVAILABLE;
2037     }
2038
2039     /* In FULLSCREEN mode R5G6B5 can only be mixed with backbuffer format R5G6B5 */
2040     if( (DisplayFormat == WINED3DFMT_R5G6B5) && (BackBufferFormat != WINED3DFMT_R5G6B5) ) {
2041         TRACE_(d3d_caps)("Unsupported display/backbuffer format combination %s/%s\n", debug_d3dformat(DisplayFormat), debug_d3dformat(BackBufferFormat));
2042         return WINED3DERR_NOTAVAILABLE;
2043     }
2044
2045     /* In FULLSCREEN mode X1R5G5B5 can only be mixed with backbuffer format *1R5G5B5 */
2046     if( (DisplayFormat == WINED3DFMT_X1R5G5B5) && !((BackBufferFormat == WINED3DFMT_X1R5G5B5) || (BackBufferFormat == WINED3DFMT_A1R5G5B5)) ) {
2047         TRACE_(d3d_caps)("Unsupported display/backbuffer format combination %s/%s\n", debug_d3dformat(DisplayFormat), debug_d3dformat(BackBufferFormat));
2048         return WINED3DERR_NOTAVAILABLE;
2049     }
2050
2051     /* In FULLSCREEN mode X8R8G8B8 can only be mixed with backbuffer format *8R8G8B8 */
2052     if( (DisplayFormat == WINED3DFMT_X8R8G8B8) && !((BackBufferFormat == WINED3DFMT_X8R8G8B8) || (BackBufferFormat == WINED3DFMT_A8R8G8B8)) ) {
2053         TRACE_(d3d_caps)("Unsupported display/backbuffer format combination %s/%s\n", debug_d3dformat(DisplayFormat), debug_d3dformat(BackBufferFormat));
2054         return WINED3DERR_NOTAVAILABLE;
2055     }
2056
2057     /* A2R10G10B10 is only allowed in fullscreen mode and it can only be mixed with backbuffer format A2R10G10B10 */
2058     if( (DisplayFormat == WINED3DFMT_A2R10G10B10) && ((BackBufferFormat != WINED3DFMT_A2R10G10B10) || Windowed)) {
2059         TRACE_(d3d_caps)("Unsupported display/backbuffer format combination %s/%s\n", debug_d3dformat(DisplayFormat), debug_d3dformat(BackBufferFormat));
2060         return WINED3DERR_NOTAVAILABLE;
2061     }
2062
2063     /* Use CheckDeviceFormat to see if the BackBufferFormat is usable with the given DisplayFormat */
2064     hr = IWineD3DImpl_CheckDeviceFormat(iface, Adapter, DeviceType, DisplayFormat, WINED3DUSAGE_RENDERTARGET, WINED3DRTYPE_SURFACE, BackBufferFormat, SURFACE_OPENGL);
2065     if(FAILED(hr))
2066         TRACE_(d3d_caps)("Unsupported display/backbuffer format combination %s/%s\n", debug_d3dformat(DisplayFormat), debug_d3dformat(BackBufferFormat));
2067
2068     return hr;
2069 }
2070
2071
2072 /* Check if we support bumpmapping for a format */
2073 static BOOL CheckBumpMapCapability(struct WineD3DAdapter *adapter,
2074         WINED3DDEVTYPE DeviceType, const struct GlPixelFormatDesc *format_desc)
2075 {
2076     const struct fragment_pipeline *fp;
2077
2078     switch(format_desc->format)
2079     {
2080         case WINED3DFMT_R8G8_SNORM:
2081         case WINED3DFMT_R16G16_SNORM:
2082         case WINED3DFMT_L6V5U5:
2083         case WINED3DFMT_X8L8V8U8:
2084         case WINED3DFMT_R8G8B8A8_SNORM:
2085             /* Ask the fixed function pipeline implementation if it can deal
2086              * with the conversion. If we've got a GL extension giving native
2087              * support this will be an identity conversion. */
2088             fp = select_fragment_implementation(adapter, DeviceType);
2089             if (fp->color_fixup_supported(format_desc->color_fixup))
2090             {
2091                 TRACE_(d3d_caps)("[OK]\n");
2092                 return TRUE;
2093             }
2094             TRACE_(d3d_caps)("[FAILED]\n");
2095             return FALSE;
2096
2097         default:
2098             TRACE_(d3d_caps)("[FAILED]\n");
2099             return FALSE;
2100     }
2101 }
2102
2103 /* Check if the given DisplayFormat + DepthStencilFormat combination is valid for the Adapter */
2104 static BOOL CheckDepthStencilCapability(struct WineD3DAdapter *adapter,
2105         const struct GlPixelFormatDesc *display_format_desc, const struct GlPixelFormatDesc *ds_format_desc)
2106 {
2107     int it=0;
2108
2109     /* Only allow depth/stencil formats */
2110     if (!(ds_format_desc->Flags & (WINED3DFMT_FLAG_DEPTH | WINED3DFMT_FLAG_STENCIL))) return FALSE;
2111
2112     /* Walk through all WGL pixel formats to find a match */
2113     for (it = 0; it < adapter->nCfgs; ++it)
2114     {
2115         WineD3D_PixelFormat *cfg = &adapter->cfgs[it];
2116         if (IWineD3DImpl_IsPixelFormatCompatibleWithRenderFmt(&adapter->gl_info, cfg, display_format_desc))
2117         {
2118             if (IWineD3DImpl_IsPixelFormatCompatibleWithDepthFmt(&adapter->gl_info, cfg, ds_format_desc))
2119             {
2120                 return TRUE;
2121             }
2122         }
2123     }
2124
2125     return FALSE;
2126 }
2127
2128 static BOOL CheckFilterCapability(struct WineD3DAdapter *adapter, const struct GlPixelFormatDesc *format_desc)
2129 {
2130     /* The flags entry of a format contains the filtering capability */
2131     if (format_desc->Flags & WINED3DFMT_FLAG_FILTERING) return TRUE;
2132
2133     return FALSE;
2134 }
2135
2136 /* Check the render target capabilities of a format */
2137 static BOOL CheckRenderTargetCapability(struct WineD3DAdapter *adapter,
2138         const struct GlPixelFormatDesc *adapter_format_desc, const struct GlPixelFormatDesc *check_format_desc)
2139 {
2140     /* Filter out non-RT formats */
2141     if (!(check_format_desc->Flags & WINED3DFMT_FLAG_RENDERTARGET)) return FALSE;
2142
2143     if(wined3d_settings.offscreen_rendering_mode == ORM_BACKBUFFER) {
2144         WineD3D_PixelFormat *cfgs = adapter->cfgs;
2145         int it;
2146         short AdapterRed, AdapterGreen, AdapterBlue, AdapterAlpha, AdapterTotalSize;
2147         short CheckRed, CheckGreen, CheckBlue, CheckAlpha, CheckTotalSize;
2148
2149         getColorBits(adapter_format_desc, &AdapterRed, &AdapterGreen, &AdapterBlue, &AdapterAlpha, &AdapterTotalSize);
2150         getColorBits(check_format_desc, &CheckRed, &CheckGreen, &CheckBlue, &CheckAlpha, &CheckTotalSize);
2151
2152         /* In backbuffer mode the front and backbuffer share the same WGL pixelformat.
2153          * The format must match in RGB, alpha is allowed to be different. (Only the backbuffer can have alpha) */
2154         if(!((AdapterRed == CheckRed) && (AdapterGreen == CheckGreen) && (AdapterBlue == CheckBlue))) {
2155             TRACE_(d3d_caps)("[FAILED]\n");
2156             return FALSE;
2157         }
2158
2159         /* Check if there is a WGL pixel format matching the requirements, the format should also be window
2160          * drawable (not offscreen; e.g. Nvidia offers R5G6B5 for pbuffers even when X is running at 24bit) */
2161         for (it = 0; it < adapter->nCfgs; ++it)
2162         {
2163             if (cfgs[it].windowDrawable && IWineD3DImpl_IsPixelFormatCompatibleWithRenderFmt(&adapter->gl_info,
2164                     &cfgs[it], check_format_desc))
2165             {
2166                 TRACE_(d3d_caps)("iPixelFormat=%d is compatible with CheckFormat=%s\n",
2167                         cfgs[it].iPixelFormat, debug_d3dformat(check_format_desc->format));
2168                 return TRUE;
2169             }
2170         }
2171     } else if(wined3d_settings.offscreen_rendering_mode == ORM_PBUFFER) {
2172         /* We can probably use this function in FBO mode too on some drivers to get some basic indication of the capabilities. */
2173         WineD3D_PixelFormat *cfgs = adapter->cfgs;
2174         int it;
2175
2176         /* Check if there is a WGL pixel format matching the requirements, the pixel format should also be usable with pbuffers */
2177         for (it = 0; it < adapter->nCfgs; ++it)
2178         {
2179             if (cfgs[it].pbufferDrawable && IWineD3DImpl_IsPixelFormatCompatibleWithRenderFmt(&adapter->gl_info,
2180                     &cfgs[it], check_format_desc))
2181             {
2182                 TRACE_(d3d_caps)("iPixelFormat=%d is compatible with CheckFormat=%s\n",
2183                         cfgs[it].iPixelFormat, debug_d3dformat(check_format_desc->format));
2184                 return TRUE;
2185             }
2186         }
2187     } else if(wined3d_settings.offscreen_rendering_mode == ORM_FBO){
2188         /* For now return TRUE for FBOs until we have some proper checks.
2189          * Note that this function will only be called when the format is around for texturing. */
2190         return TRUE;
2191     }
2192     return FALSE;
2193 }
2194
2195 static BOOL CheckSrgbReadCapability(struct WineD3DAdapter *adapter, const struct GlPixelFormatDesc *format_desc)
2196 {
2197     const WineD3D_GL_Info *gl_info = &adapter->gl_info;
2198
2199     /* Check for supported sRGB formats (Texture loading and framebuffer) */
2200     if(!GL_SUPPORT(EXT_TEXTURE_SRGB)) {
2201         TRACE_(d3d_caps)("[FAILED] GL_EXT_texture_sRGB not supported\n");
2202         return FALSE;
2203     }
2204
2205     switch (format_desc->format)
2206     {
2207         case WINED3DFMT_A8R8G8B8:
2208         case WINED3DFMT_X8R8G8B8:
2209         case WINED3DFMT_A4R4G4B4:
2210         case WINED3DFMT_L8:
2211         case WINED3DFMT_A8L8:
2212         case WINED3DFMT_DXT1:
2213         case WINED3DFMT_DXT2:
2214         case WINED3DFMT_DXT3:
2215         case WINED3DFMT_DXT4:
2216         case WINED3DFMT_DXT5:
2217             TRACE_(d3d_caps)("[OK]\n");
2218             return TRUE;
2219
2220         default:
2221             TRACE_(d3d_caps)("[FAILED] Gamma texture format %s not supported.\n", debug_d3dformat(format_desc->format));
2222             return FALSE;
2223     }
2224     return FALSE;
2225 }
2226
2227 static BOOL CheckSrgbWriteCapability(struct WineD3DAdapter *adapter,
2228         WINED3DDEVTYPE DeviceType, const struct GlPixelFormatDesc *format_desc)
2229 {
2230     /* Only offer SRGB writing on X8R8G8B8/A8R8G8B8 when we use ARB or GLSL shaders as we are
2231      * doing the color fixup in shaders.
2232      * Note Windows drivers (at least on the Geforce 8800) also offer this on R5G6B5. */
2233     if ((format_desc->format == WINED3DFMT_X8R8G8B8) || (format_desc->format == WINED3DFMT_A8R8G8B8))
2234     {
2235         int vs_selected_mode;
2236         int ps_selected_mode;
2237         select_shader_mode(&adapter->gl_info, DeviceType, &ps_selected_mode, &vs_selected_mode);
2238
2239         if((ps_selected_mode == SHADER_ARB) || (ps_selected_mode == SHADER_GLSL)) {
2240             TRACE_(d3d_caps)("[OK]\n");
2241             return TRUE;
2242         }
2243     }
2244
2245     TRACE_(d3d_caps)("[FAILED] - no SRGB writing support on format=%s\n", debug_d3dformat(format_desc->format));
2246     return FALSE;
2247 }
2248
2249 /* Check if a format support blending in combination with pixel shaders */
2250 static BOOL CheckPostPixelShaderBlendingCapability(struct WineD3DAdapter *adapter,
2251         const struct GlPixelFormatDesc *format_desc)
2252 {
2253     /* The flags entry of a format contains the post pixel shader blending capability */
2254     if (format_desc->Flags & WINED3DFMT_FLAG_POSTPIXELSHADER_BLENDING) return TRUE;
2255
2256     return FALSE;
2257 }
2258
2259 static BOOL CheckWrapAndMipCapability(struct WineD3DAdapter *adapter, const struct GlPixelFormatDesc *format_desc)
2260 {
2261     /* OpenGL supports mipmapping on all formats basically. Wrapping is unsupported,
2262      * but we have to report mipmapping so we cannot reject this flag. Tests show that
2263      * windows reports WRAPANDMIP on unfilterable surfaces as well, apparently to show
2264      * that wrapping is supported. The lack of filtering will sort out the mipmapping
2265      * capability anyway.
2266      *
2267      * For now lets report this on all formats, but in the future we may want to
2268      * restrict it to some should games need that
2269      */
2270     return TRUE;
2271 }
2272
2273 /* Check if a texture format is supported on the given adapter */
2274 static BOOL CheckTextureCapability(struct WineD3DAdapter *adapter,
2275         WINED3DDEVTYPE DeviceType, const struct GlPixelFormatDesc *format_desc)
2276 {
2277     const WineD3D_GL_Info *gl_info = &adapter->gl_info;
2278     const shader_backend_t *shader_backend;
2279     const struct fragment_pipeline *fp;
2280
2281     switch (format_desc->format)
2282     {
2283         /*****
2284          *  supported: RGB(A) formats
2285          */
2286         case WINED3DFMT_R8G8B8: /* Enable for dx7, blacklisted for 8 and 9 above */
2287         case WINED3DFMT_A8R8G8B8:
2288         case WINED3DFMT_X8R8G8B8:
2289         case WINED3DFMT_R5G6B5:
2290         case WINED3DFMT_X1R5G5B5:
2291         case WINED3DFMT_A1R5G5B5:
2292         case WINED3DFMT_A4R4G4B4:
2293         case WINED3DFMT_A8_UNORM:
2294         case WINED3DFMT_X4R4G4B4:
2295         case WINED3DFMT_R8G8B8A8_UNORM:
2296         case WINED3DFMT_X8B8G8R8:
2297         case WINED3DFMT_A2R10G10B10:
2298         case WINED3DFMT_R10G10B10A2_UNORM:
2299         case WINED3DFMT_R16G16_UNORM:
2300             TRACE_(d3d_caps)("[OK]\n");
2301             return TRUE;
2302
2303         case WINED3DFMT_R3G3B2:
2304             TRACE_(d3d_caps)("[FAILED] - Not supported on Windows\n");
2305             return FALSE;
2306
2307         /*****
2308          *  supported: Palettized
2309          */
2310         case WINED3DFMT_P8:
2311             TRACE_(d3d_caps)("[OK]\n");
2312             return TRUE;
2313         /* No Windows driver offers A8P8, so don't offer it either */
2314         case WINED3DFMT_A8P8:
2315             return FALSE;
2316
2317         /*****
2318          *  Supported: (Alpha)-Luminance
2319          */
2320         case WINED3DFMT_L8:
2321         case WINED3DFMT_A8L8:
2322         case WINED3DFMT_L16:
2323             TRACE_(d3d_caps)("[OK]\n");
2324             return TRUE;
2325
2326         /* Not supported on Windows, thus disabled */
2327         case WINED3DFMT_A4L4:
2328             TRACE_(d3d_caps)("[FAILED] - not supported on windows\n");
2329             return FALSE;
2330
2331         /*****
2332          *  Supported: Depth/Stencil formats
2333          */
2334         case WINED3DFMT_D16_LOCKABLE:
2335         case WINED3DFMT_D16_UNORM:
2336         case WINED3DFMT_D15S1:
2337         case WINED3DFMT_D24X8:
2338         case WINED3DFMT_D24X4S4:
2339         case WINED3DFMT_D24S8:
2340         case WINED3DFMT_D24FS8:
2341         case WINED3DFMT_D32:
2342         case WINED3DFMT_D32F_LOCKABLE:
2343             return TRUE;
2344
2345         /*****
2346          *  Not supported everywhere(depends on GL_ATI_envmap_bumpmap or
2347          *  GL_NV_texture_shader). Emulated by shaders
2348          */
2349         case WINED3DFMT_R8G8_SNORM:
2350         case WINED3DFMT_X8L8V8U8:
2351         case WINED3DFMT_L6V5U5:
2352         case WINED3DFMT_R8G8B8A8_SNORM:
2353         case WINED3DFMT_R16G16_SNORM:
2354             /* Ask the shader backend if it can deal with the conversion. If
2355              * we've got a GL extension giving native support this will be an
2356              * identity conversion. */
2357             shader_backend = select_shader_backend(adapter, DeviceType);
2358             if (shader_backend->shader_color_fixup_supported(format_desc->color_fixup))
2359             {
2360                 TRACE_(d3d_caps)("[OK]\n");
2361                 return TRUE;
2362             }
2363             TRACE_(d3d_caps)("[FAILED]\n");
2364             return FALSE;
2365
2366         case WINED3DFMT_DXT1:
2367         case WINED3DFMT_DXT2:
2368         case WINED3DFMT_DXT3:
2369         case WINED3DFMT_DXT4:
2370         case WINED3DFMT_DXT5:
2371             if (GL_SUPPORT(EXT_TEXTURE_COMPRESSION_S3TC)) {
2372                 TRACE_(d3d_caps)("[OK]\n");
2373                 return TRUE;
2374             }
2375             TRACE_(d3d_caps)("[FAILED]\n");
2376             return FALSE;
2377
2378
2379         /*****
2380          *  Odd formats - not supported
2381          */
2382         case WINED3DFMT_VERTEXDATA:
2383         case WINED3DFMT_R16_UINT:
2384         case WINED3DFMT_R32_UINT:
2385         case WINED3DFMT_R16G16B16A16_SNORM:
2386         case WINED3DFMT_A2W10V10U10:
2387         case WINED3DFMT_W11V11U10:
2388             TRACE_(d3d_caps)("[FAILED]\n"); /* Enable when implemented */
2389             return FALSE;
2390
2391         /*****
2392          *  WINED3DFMT_CxV8U8: Not supported right now
2393          */
2394         case WINED3DFMT_CxV8U8:
2395             TRACE_(d3d_caps)("[FAILED]\n"); /* Enable when implemented */
2396             return FALSE;
2397
2398         /* YUV formats */
2399         case WINED3DFMT_UYVY:
2400         case WINED3DFMT_YUY2:
2401             if(GL_SUPPORT(APPLE_YCBCR_422)) {
2402                 TRACE_(d3d_caps)("[OK]\n");
2403                 return TRUE;
2404             }
2405             TRACE_(d3d_caps)("[FAILED]\n");
2406             return FALSE;
2407         case WINED3DFMT_YV12:
2408             TRACE_(d3d_caps)("[FAILED]\n");
2409             return FALSE;
2410
2411             /* Not supported */
2412         case WINED3DFMT_R16G16B16A16_UNORM:
2413         case WINED3DFMT_A8R3G3B2:
2414             TRACE_(d3d_caps)("[FAILED]\n"); /* Enable when implemented */
2415             return FALSE;
2416
2417             /* Floating point formats */
2418         case WINED3DFMT_R16_FLOAT:
2419         case WINED3DFMT_R16G16_FLOAT:
2420         case WINED3DFMT_R16G16B16A16_FLOAT:
2421             if(GL_SUPPORT(ARB_TEXTURE_FLOAT) && GL_SUPPORT(ARB_HALF_FLOAT_PIXEL)) {
2422                 TRACE_(d3d_caps)("[OK]\n");
2423                 return TRUE;
2424             }
2425             TRACE_(d3d_caps)("[FAILED]\n");
2426             return FALSE;
2427
2428         case WINED3DFMT_R32_FLOAT:
2429         case WINED3DFMT_R32G32_FLOAT:
2430         case WINED3DFMT_R32G32B32A32_FLOAT:
2431             if (GL_SUPPORT(ARB_TEXTURE_FLOAT)) {
2432                 TRACE_(d3d_caps)("[OK]\n");
2433                 return TRUE;
2434             }
2435             TRACE_(d3d_caps)("[FAILED]\n");
2436             return FALSE;
2437
2438         /* ATI instancing hack: Although ATI cards do not support Shader Model 3.0, they support
2439          * instancing. To query if the card supports instancing CheckDeviceFormat with the special format
2440          * MAKEFOURCC('I','N','S','T') is used. Should a (broken) app check for this provide a proper return value.
2441          * We can do instancing with all shader versions, but we need vertex shaders.
2442          *
2443          * Additionally applications have to set the D3DRS_POINTSIZE render state to MAKEFOURCC('I','N','S','T') once
2444          * to enable instancing. WineD3D doesn't need that and just ignores it.
2445          *
2446          * With Shader Model 3.0 capable cards Instancing 'just works' in Windows.
2447          */
2448         case WINEMAKEFOURCC('I','N','S','T'):
2449             TRACE("ATI Instancing check hack\n");
2450             if(GL_SUPPORT(ARB_VERTEX_PROGRAM) || GL_SUPPORT(ARB_VERTEX_SHADER)) {
2451                 TRACE_(d3d_caps)("[OK]\n");
2452                 return TRUE;
2453             }
2454             TRACE_(d3d_caps)("[FAILED]\n");
2455             return FALSE;
2456
2457         /* Some weird FOURCC formats */
2458         case WINED3DFMT_R8G8_B8G8:
2459         case WINED3DFMT_G8R8_G8B8:
2460         case WINED3DFMT_MULTI2_ARGB8:
2461             TRACE_(d3d_caps)("[FAILED]\n");
2462             return FALSE;
2463
2464         /* Vendor specific formats */
2465         case WINED3DFMT_ATI2N:
2466             if(GL_SUPPORT(ATI_TEXTURE_COMPRESSION_3DC) || GL_SUPPORT(EXT_TEXTURE_COMPRESSION_RGTC)) {
2467                 shader_backend = select_shader_backend(adapter, DeviceType);
2468                 fp = select_fragment_implementation(adapter, DeviceType);
2469                 if (shader_backend->shader_color_fixup_supported(format_desc->color_fixup)
2470                         && fp->color_fixup_supported(format_desc->color_fixup))
2471                 {
2472                     TRACE_(d3d_caps)("[OK]\n");
2473                     return TRUE;
2474                 }
2475
2476                 TRACE_(d3d_caps)("[OK]\n");
2477                 return TRUE;
2478             }
2479             TRACE_(d3d_caps)("[FAILED]\n");
2480             return FALSE;
2481
2482         case WINED3DFMT_NVHU:
2483         case WINED3DFMT_NVHS:
2484             /* These formats seem to be similar to the HILO formats in GL_NV_texture_shader. NVHU
2485              * is said to be GL_UNSIGNED_HILO16, NVHS GL_SIGNED_HILO16. Rumours say that d3d computes
2486              * a 3rd channel similarly to D3DFMT_CxV8U8(So NVHS could be called D3DFMT_CxV16U16).
2487              * ATI refused to support formats which can easilly be emulated with pixel shaders, so
2488              * Applications have to deal with not having NVHS and NVHU.
2489              */
2490             TRACE_(d3d_caps)("[FAILED]\n");
2491             return FALSE;
2492
2493         case WINED3DFMT_UNKNOWN:
2494             return FALSE;
2495
2496         default:
2497             ERR("Unhandled format=%s\n", debug_d3dformat(format_desc->format));
2498             break;
2499     }
2500     return FALSE;
2501 }
2502
2503 static BOOL CheckSurfaceCapability(struct WineD3DAdapter *adapter, const struct GlPixelFormatDesc *adapter_format_desc,
2504         WINED3DDEVTYPE DeviceType, const struct GlPixelFormatDesc *check_format_desc, WINED3DSURFTYPE SurfaceType)
2505 {
2506     const struct blit_shader *blitter;
2507
2508     if(SurfaceType == SURFACE_GDI) {
2509         switch(check_format_desc->format)
2510         {
2511             case WINED3DFMT_R8G8B8:
2512             case WINED3DFMT_A8R8G8B8:
2513             case WINED3DFMT_X8R8G8B8:
2514             case WINED3DFMT_R5G6B5:
2515             case WINED3DFMT_X1R5G5B5:
2516             case WINED3DFMT_A1R5G5B5:
2517             case WINED3DFMT_A4R4G4B4:
2518             case WINED3DFMT_R3G3B2:
2519             case WINED3DFMT_A8_UNORM:
2520             case WINED3DFMT_A8R3G3B2:
2521             case WINED3DFMT_X4R4G4B4:
2522             case WINED3DFMT_R10G10B10A2_UNORM:
2523             case WINED3DFMT_R8G8B8A8_UNORM:
2524             case WINED3DFMT_X8B8G8R8:
2525             case WINED3DFMT_R16G16_UNORM:
2526             case WINED3DFMT_A2R10G10B10:
2527             case WINED3DFMT_R16G16B16A16_UNORM:
2528             case WINED3DFMT_P8:
2529                 TRACE_(d3d_caps)("[OK]\n");
2530                 return TRUE;
2531             default:
2532                 TRACE_(d3d_caps)("[FAILED] - not available on GDI surfaces\n");
2533                 return FALSE;
2534         }
2535     }
2536
2537     /* All format that are supported for textures are supported for surfaces as well */
2538     if (CheckTextureCapability(adapter, DeviceType, check_format_desc)) return TRUE;
2539     /* All depth stencil formats are supported on surfaces */
2540     if (CheckDepthStencilCapability(adapter, adapter_format_desc, check_format_desc)) return TRUE;
2541
2542     /* If opengl can't process the format natively, the blitter may be able to convert it */
2543     blitter = select_blit_implementation(adapter, DeviceType);
2544     if (blitter->color_fixup_supported(check_format_desc->color_fixup))
2545     {
2546         TRACE_(d3d_caps)("[OK]\n");
2547         return TRUE;
2548     }
2549
2550     /* Reject other formats */
2551     TRACE_(d3d_caps)("[FAILED]\n");
2552     return FALSE;
2553 }
2554
2555 static BOOL CheckVertexTextureCapability(struct WineD3DAdapter *adapter, const struct GlPixelFormatDesc *format_desc)
2556 {
2557     const WineD3D_GL_Info *gl_info = &adapter->gl_info;
2558
2559     if (!GL_LIMITS(vertex_samplers)) {
2560         TRACE_(d3d_caps)("[FAILED]\n");
2561         return FALSE;
2562     }
2563
2564     switch (format_desc->format)
2565     {
2566         case WINED3DFMT_R32G32B32A32_FLOAT:
2567             if (!GL_SUPPORT(ARB_TEXTURE_FLOAT)) {
2568                 TRACE_(d3d_caps)("[FAILED]\n");
2569                 return FALSE;
2570             }
2571             TRACE_(d3d_caps)("[OK]\n");
2572             return TRUE;
2573
2574         default:
2575             TRACE_(d3d_caps)("[FAILED]\n");
2576             return FALSE;
2577     }
2578     return FALSE;
2579 }
2580
2581 static HRESULT WINAPI IWineD3DImpl_CheckDeviceFormat(IWineD3D *iface, UINT Adapter, WINED3DDEVTYPE DeviceType, 
2582         WINED3DFORMAT AdapterFormat, DWORD Usage, WINED3DRESOURCETYPE RType, WINED3DFORMAT CheckFormat,
2583         WINED3DSURFTYPE SurfaceType) {
2584     IWineD3DImpl *This = (IWineD3DImpl *)iface;
2585     struct WineD3DAdapter *adapter = &This->adapters[Adapter];
2586     const WineD3D_GL_Info *gl_info = &adapter->gl_info;
2587     const struct GlPixelFormatDesc *format_desc = getFormatDescEntry(CheckFormat, gl_info);
2588     const struct GlPixelFormatDesc *adapter_format_desc = getFormatDescEntry(AdapterFormat, gl_info);
2589     DWORD UsageCaps = 0;
2590
2591     TRACE_(d3d_caps)("(%p)-> (STUB) (Adptr:%d, DevType:(%u,%s), AdptFmt:(%u,%s), Use:(%u,%s,%s), ResTyp:(%x,%s), CheckFmt:(%u,%s))\n",
2592           This,
2593           Adapter,
2594           DeviceType, debug_d3ddevicetype(DeviceType),
2595           AdapterFormat, debug_d3dformat(AdapterFormat),
2596           Usage, debug_d3dusage(Usage), debug_d3dusagequery(Usage),
2597           RType, debug_d3dresourcetype(RType),
2598           CheckFormat, debug_d3dformat(CheckFormat));
2599
2600     if (Adapter >= IWineD3D_GetAdapterCount(iface)) {
2601         return WINED3DERR_INVALIDCALL;
2602     }
2603
2604     if(RType == WINED3DRTYPE_CUBETEXTURE) {
2605
2606         if(SurfaceType != SURFACE_OPENGL) {
2607             TRACE("[FAILED]\n");
2608             return WINED3DERR_NOTAVAILABLE;
2609         }
2610
2611         /* Cubetexture allows:
2612          *                    - D3DUSAGE_AUTOGENMIPMAP
2613          *                    - D3DUSAGE_DEPTHSTENCIL
2614          *                    - D3DUSAGE_DYNAMIC
2615          *                    - D3DUSAGE_NONSECURE (d3d9ex)
2616          *                    - D3DUSAGE_RENDERTARGET
2617          *                    - D3DUSAGE_SOFTWAREPROCESSING
2618          *                    - D3DUSAGE_QUERY_WRAPANDMIP
2619          */
2620         if(GL_SUPPORT(ARB_TEXTURE_CUBE_MAP)) {
2621             /* Check if the texture format is around */
2622             if (CheckTextureCapability(adapter, DeviceType, format_desc))
2623             {
2624                 if(Usage & WINED3DUSAGE_AUTOGENMIPMAP) {
2625                     /* Check for automatic mipmap generation support */
2626                     if(GL_SUPPORT(SGIS_GENERATE_MIPMAP)) {
2627                         UsageCaps |= WINED3DUSAGE_AUTOGENMIPMAP;
2628                     } else {
2629                         /* When autogenmipmap isn't around continue and return WINED3DOK_NOAUTOGEN instead of D3D_OK */
2630                         TRACE_(d3d_caps)("[FAILED] - No autogenmipmap support, but continuing\n");
2631                     }
2632                 }
2633
2634                 /* Always report dynamic locking */
2635                 if(Usage & WINED3DUSAGE_DYNAMIC)
2636                     UsageCaps |= WINED3DUSAGE_DYNAMIC;
2637
2638                 if(Usage & WINED3DUSAGE_RENDERTARGET) {
2639                     if(CheckRenderTargetCapability(adapter, adapter_format_desc, format_desc))
2640                     {
2641                         UsageCaps |= WINED3DUSAGE_RENDERTARGET;
2642                     } else {
2643                         TRACE_(d3d_caps)("[FAILED] - No rendertarget support\n");
2644                         return WINED3DERR_NOTAVAILABLE;
2645                     }
2646                 }
2647
2648                 /* Always report software processing */
2649                 if(Usage & WINED3DUSAGE_SOFTWAREPROCESSING)
2650                     UsageCaps |= WINED3DUSAGE_SOFTWAREPROCESSING;
2651
2652                 /* Check QUERY_FILTER support */
2653                 if(Usage & WINED3DUSAGE_QUERY_FILTER) {
2654                     if (CheckFilterCapability(adapter, format_desc))
2655                     {
2656                         UsageCaps |= WINED3DUSAGE_QUERY_FILTER;
2657                     } else {
2658                         TRACE_(d3d_caps)("[FAILED] - No query filter support\n");
2659                         return WINED3DERR_NOTAVAILABLE;
2660                     }
2661                 }
2662
2663                 /* Check QUERY_POSTPIXELSHADER_BLENDING support */
2664                 if(Usage & WINED3DUSAGE_QUERY_POSTPIXELSHADER_BLENDING) {
2665                     if (CheckPostPixelShaderBlendingCapability(adapter, format_desc))
2666                     {
2667                         UsageCaps |= WINED3DUSAGE_QUERY_POSTPIXELSHADER_BLENDING;
2668                     } else {
2669                         TRACE_(d3d_caps)("[FAILED] - No query post pixelshader blending support\n");
2670                         return WINED3DERR_NOTAVAILABLE;
2671                     }
2672                 }
2673
2674                 /* Check QUERY_SRGBREAD support */
2675                 if(Usage & WINED3DUSAGE_QUERY_SRGBREAD) {
2676                     if (CheckSrgbReadCapability(adapter, format_desc))
2677                     {
2678                         UsageCaps |= WINED3DUSAGE_QUERY_SRGBREAD;
2679                     } else {
2680                         TRACE_(d3d_caps)("[FAILED] - No query srgbread support\n");
2681                         return WINED3DERR_NOTAVAILABLE;
2682                     }
2683                 }
2684
2685                 /* Check QUERY_SRGBWRITE support */
2686                 if(Usage & WINED3DUSAGE_QUERY_SRGBWRITE) {
2687                     if (CheckSrgbWriteCapability(adapter, DeviceType, format_desc))
2688                     {
2689                         UsageCaps |= WINED3DUSAGE_QUERY_SRGBWRITE;
2690                     } else {
2691                         TRACE_(d3d_caps)("[FAILED] - No query srgbwrite support\n");
2692                         return WINED3DERR_NOTAVAILABLE;
2693                     }
2694                 }
2695
2696                 /* Check QUERY_VERTEXTEXTURE support */
2697                 if(Usage & WINED3DUSAGE_QUERY_VERTEXTEXTURE) {
2698                     if (CheckVertexTextureCapability(adapter, format_desc))
2699                     {
2700                         UsageCaps |= WINED3DUSAGE_QUERY_VERTEXTEXTURE;
2701                     } else {
2702                         TRACE_(d3d_caps)("[FAILED] - No query vertextexture support\n");
2703                         return WINED3DERR_NOTAVAILABLE;
2704                     }
2705                 }
2706
2707                 /* Check QUERY_WRAPANDMIP support */
2708                 if(Usage & WINED3DUSAGE_QUERY_WRAPANDMIP) {
2709                     if (CheckWrapAndMipCapability(adapter, format_desc))
2710                     {
2711                         UsageCaps |= WINED3DUSAGE_QUERY_WRAPANDMIP;
2712                     } else {
2713                         TRACE_(d3d_caps)("[FAILED] - No wrapping and mipmapping support\n");
2714                         return WINED3DERR_NOTAVAILABLE;
2715                     }
2716                 }
2717             } else {
2718                 TRACE_(d3d_caps)("[FAILED] - Cube texture format not supported\n");
2719                 return WINED3DERR_NOTAVAILABLE;
2720             }
2721         } else {
2722             TRACE_(d3d_caps)("[FAILED] - No cube texture support\n");
2723             return WINED3DERR_NOTAVAILABLE;
2724         }
2725     } else if(RType == WINED3DRTYPE_SURFACE) {
2726         /* Surface allows:
2727          *                - D3DUSAGE_DEPTHSTENCIL
2728          *                - D3DUSAGE_NONSECURE (d3d9ex)
2729          *                - D3DUSAGE_RENDERTARGET
2730          */
2731
2732         if (CheckSurfaceCapability(adapter, adapter_format_desc, DeviceType, format_desc, SurfaceType))
2733         {
2734             if(Usage & WINED3DUSAGE_DEPTHSTENCIL) {
2735                 if (CheckDepthStencilCapability(adapter, adapter_format_desc, format_desc))
2736                 {
2737                     UsageCaps |= WINED3DUSAGE_DEPTHSTENCIL;
2738                 } else {
2739                     TRACE_(d3d_caps)("[FAILED] - No depthstencil support\n");
2740                     return WINED3DERR_NOTAVAILABLE;
2741                 }
2742             }
2743
2744             if(Usage & WINED3DUSAGE_RENDERTARGET) {
2745                 if (CheckRenderTargetCapability(adapter, adapter_format_desc, format_desc))
2746                 {
2747                     UsageCaps |= WINED3DUSAGE_RENDERTARGET;
2748                 } else {
2749                     TRACE_(d3d_caps)("[FAILED] - No rendertarget support\n");
2750                     return WINED3DERR_NOTAVAILABLE;
2751                 }
2752             }
2753
2754             /* Check QUERY_POSTPIXELSHADER_BLENDING support */
2755             if(Usage & WINED3DUSAGE_QUERY_POSTPIXELSHADER_BLENDING) {
2756                 if (CheckPostPixelShaderBlendingCapability(adapter, format_desc))
2757                 {
2758                     UsageCaps |= WINED3DUSAGE_QUERY_POSTPIXELSHADER_BLENDING;
2759                 } else {
2760                     TRACE_(d3d_caps)("[FAILED] - No query post pixelshader blending support\n");
2761                     return WINED3DERR_NOTAVAILABLE;
2762                 }
2763             }
2764         } else {
2765             TRACE_(d3d_caps)("[FAILED] - Not supported for plain surfaces\n");
2766             return WINED3DERR_NOTAVAILABLE;
2767         }
2768
2769     } else if(RType == WINED3DRTYPE_TEXTURE) {
2770         /* Texture allows:
2771          *                - D3DUSAGE_AUTOGENMIPMAP
2772          *                - D3DUSAGE_DEPTHSTENCIL
2773          *                - D3DUSAGE_DMAP
2774          *                - D3DUSAGE_DYNAMIC
2775          *                - D3DUSAGE_NONSECURE (d3d9ex)
2776          *                - D3DUSAGE_RENDERTARGET
2777          *                - D3DUSAGE_SOFTWAREPROCESSING
2778          *                - D3DUSAGE_TEXTAPI (d3d9ex)
2779          *                - D3DUSAGE_QUERY_WRAPANDMIP
2780          */
2781
2782         if(SurfaceType != SURFACE_OPENGL) {
2783             TRACE("[FAILED]\n");
2784             return WINED3DERR_NOTAVAILABLE;
2785         }
2786
2787         /* Check if the texture format is around */
2788         if (CheckTextureCapability(adapter, DeviceType, format_desc))
2789         {
2790             if(Usage & WINED3DUSAGE_AUTOGENMIPMAP) {
2791                 /* Check for automatic mipmap generation support */
2792                 if(GL_SUPPORT(SGIS_GENERATE_MIPMAP)) {
2793                     UsageCaps |= WINED3DUSAGE_AUTOGENMIPMAP;
2794                 } else {
2795                     /* When autogenmipmap isn't around continue and return WINED3DOK_NOAUTOGEN instead of D3D_OK */
2796                     TRACE_(d3d_caps)("[FAILED] - No autogenmipmap support, but continuing\n");
2797                 }
2798             }
2799
2800             /* Always report dynamic locking */
2801             if(Usage & WINED3DUSAGE_DYNAMIC)
2802                 UsageCaps |= WINED3DUSAGE_DYNAMIC;
2803
2804             if(Usage & WINED3DUSAGE_RENDERTARGET) {
2805                 if (CheckRenderTargetCapability(adapter, adapter_format_desc, format_desc))
2806                 {
2807                     UsageCaps |= WINED3DUSAGE_RENDERTARGET;
2808                 } else {
2809                     TRACE_(d3d_caps)("[FAILED] - No rendertarget support\n");
2810                      return WINED3DERR_NOTAVAILABLE;
2811                  }
2812             }
2813
2814             /* Always report software processing */
2815             if(Usage & WINED3DUSAGE_SOFTWAREPROCESSING)
2816                 UsageCaps |= WINED3DUSAGE_SOFTWAREPROCESSING;
2817
2818             /* Check QUERY_FILTER support */
2819             if(Usage & WINED3DUSAGE_QUERY_FILTER) {
2820                 if (CheckFilterCapability(adapter, format_desc))
2821                 {
2822                     UsageCaps |= WINED3DUSAGE_QUERY_FILTER;
2823                 } else {
2824                     TRACE_(d3d_caps)("[FAILED] - No query filter support\n");
2825                     return WINED3DERR_NOTAVAILABLE;
2826                 }
2827             }
2828
2829             /* Check QUERY_LEGACYBUMPMAP support */
2830             if(Usage & WINED3DUSAGE_QUERY_LEGACYBUMPMAP) {
2831                 if (CheckBumpMapCapability(adapter, DeviceType, format_desc))
2832                 {
2833                     UsageCaps |= WINED3DUSAGE_QUERY_LEGACYBUMPMAP;
2834                 } else {
2835                     TRACE_(d3d_caps)("[FAILED] - No legacy bumpmap support\n");
2836                     return WINED3DERR_NOTAVAILABLE;
2837                 }
2838             }
2839
2840             /* Check QUERY_POSTPIXELSHADER_BLENDING support */
2841             if(Usage & WINED3DUSAGE_QUERY_POSTPIXELSHADER_BLENDING) {
2842                 if (CheckPostPixelShaderBlendingCapability(adapter, format_desc))
2843                 {
2844                     UsageCaps |= WINED3DUSAGE_QUERY_POSTPIXELSHADER_BLENDING;
2845                 } else {
2846                     TRACE_(d3d_caps)("[FAILED] - No query post pixelshader blending support\n");
2847                     return WINED3DERR_NOTAVAILABLE;
2848                 }
2849             }
2850
2851             /* Check QUERY_SRGBREAD support */
2852             if(Usage & WINED3DUSAGE_QUERY_SRGBREAD) {
2853                 if (CheckSrgbReadCapability(adapter, format_desc))
2854                 {
2855                     UsageCaps |= WINED3DUSAGE_QUERY_SRGBREAD;
2856                 } else {
2857                     TRACE_(d3d_caps)("[FAILED] - No query srgbread support\n");
2858                     return WINED3DERR_NOTAVAILABLE;
2859                 }
2860             }
2861
2862             /* Check QUERY_SRGBWRITE support */
2863             if(Usage & WINED3DUSAGE_QUERY_SRGBWRITE) {
2864                 if (CheckSrgbWriteCapability(adapter, DeviceType, format_desc))
2865                 {
2866                     UsageCaps |= WINED3DUSAGE_QUERY_SRGBWRITE;
2867                 } else {
2868                     TRACE_(d3d_caps)("[FAILED] - No query srgbwrite support\n");
2869                     return WINED3DERR_NOTAVAILABLE;
2870                 }
2871             }
2872
2873             /* Check QUERY_VERTEXTEXTURE support */
2874             if(Usage & WINED3DUSAGE_QUERY_VERTEXTEXTURE) {
2875                 if (CheckVertexTextureCapability(adapter, format_desc))
2876                 {
2877                     UsageCaps |= WINED3DUSAGE_QUERY_VERTEXTEXTURE;
2878                 } else {
2879                     TRACE_(d3d_caps)("[FAILED] - No query vertextexture support\n");
2880                     return WINED3DERR_NOTAVAILABLE;
2881                 }
2882             }
2883
2884             /* Check QUERY_WRAPANDMIP support */
2885             if(Usage & WINED3DUSAGE_QUERY_WRAPANDMIP) {
2886                 if (CheckWrapAndMipCapability(adapter, format_desc))
2887                 {
2888                     UsageCaps |= WINED3DUSAGE_QUERY_WRAPANDMIP;
2889                 } else {
2890                     TRACE_(d3d_caps)("[FAILED] - No wrapping and mipmapping support\n");
2891                     return WINED3DERR_NOTAVAILABLE;
2892                 }
2893             }
2894
2895             if(Usage & WINED3DUSAGE_DEPTHSTENCIL) {
2896                 if (CheckDepthStencilCapability(adapter, adapter_format_desc, format_desc))
2897                 {
2898                     UsageCaps |= WINED3DUSAGE_DEPTHSTENCIL;
2899                 } else {
2900                     TRACE_(d3d_caps)("[FAILED] - No depth stencil support\n");
2901                     return WINED3DERR_NOTAVAILABLE;
2902                 }
2903             }
2904         } else {
2905             TRACE_(d3d_caps)("[FAILED] - Texture format not supported\n");
2906             return WINED3DERR_NOTAVAILABLE;
2907         }
2908     } else if((RType == WINED3DRTYPE_VOLUME) || (RType == WINED3DRTYPE_VOLUMETEXTURE)) {
2909         /* Volume is to VolumeTexture what Surface is to Texture but its usage caps are not documented.
2910          * Most driver seem to offer (nearly) the same on Volume and VolumeTexture, so do that too.
2911          *
2912          * Volumetexture allows:
2913          *                      - D3DUSAGE_DYNAMIC
2914          *                      - D3DUSAGE_NONSECURE (d3d9ex)
2915          *                      - D3DUSAGE_SOFTWAREPROCESSING
2916          *                      - D3DUSAGE_QUERY_WRAPANDMIP
2917          */
2918
2919         if(SurfaceType != SURFACE_OPENGL) {
2920             TRACE("[FAILED]\n");
2921             return WINED3DERR_NOTAVAILABLE;
2922         }
2923
2924         /* Check volume texture and volume usage caps */
2925         if(GL_SUPPORT(EXT_TEXTURE3D)) {
2926             if (!CheckTextureCapability(adapter, DeviceType, format_desc))
2927             {
2928                 TRACE_(d3d_caps)("[FAILED] - Format not supported\n");
2929                 return WINED3DERR_NOTAVAILABLE;
2930             }
2931
2932             /* Always report dynamic locking */
2933             if(Usage & WINED3DUSAGE_DYNAMIC)
2934                 UsageCaps |= WINED3DUSAGE_DYNAMIC;
2935
2936             /* Always report software processing */
2937             if(Usage & WINED3DUSAGE_SOFTWAREPROCESSING)
2938                 UsageCaps |= WINED3DUSAGE_SOFTWAREPROCESSING;
2939
2940             /* Check QUERY_FILTER support */
2941             if(Usage & WINED3DUSAGE_QUERY_FILTER) {
2942                 if (CheckFilterCapability(adapter, format_desc))
2943                 {
2944                     UsageCaps |= WINED3DUSAGE_QUERY_FILTER;
2945                 } else {
2946                     TRACE_(d3d_caps)("[FAILED] - No query filter support\n");
2947                     return WINED3DERR_NOTAVAILABLE;
2948                 }
2949             }
2950
2951             /* Check QUERY_POSTPIXELSHADER_BLENDING support */
2952             if(Usage & WINED3DUSAGE_QUERY_POSTPIXELSHADER_BLENDING) {
2953                 if (CheckPostPixelShaderBlendingCapability(adapter, format_desc))
2954                 {
2955                     UsageCaps |= WINED3DUSAGE_QUERY_POSTPIXELSHADER_BLENDING;
2956                 } else {
2957                     TRACE_(d3d_caps)("[FAILED] - No query post pixelshader blending support\n");
2958                     return WINED3DERR_NOTAVAILABLE;
2959                 }
2960             }
2961
2962             /* Check QUERY_SRGBREAD support */
2963             if(Usage & WINED3DUSAGE_QUERY_SRGBREAD) {
2964                 if (CheckSrgbReadCapability(adapter, format_desc))
2965                 {
2966                     UsageCaps |= WINED3DUSAGE_QUERY_SRGBREAD;
2967                 } else {
2968                     TRACE_(d3d_caps)("[FAILED] - No query srgbread support\n");
2969                     return WINED3DERR_NOTAVAILABLE;
2970                 }
2971             }
2972
2973             /* Check QUERY_SRGBWRITE support */
2974             if(Usage & WINED3DUSAGE_QUERY_SRGBWRITE) {
2975                 if (CheckSrgbWriteCapability(adapter, DeviceType, format_desc))
2976                 {
2977                     UsageCaps |= WINED3DUSAGE_QUERY_SRGBWRITE;
2978                 } else {
2979                     TRACE_(d3d_caps)("[FAILED] - No query srgbwrite support\n");
2980                     return WINED3DERR_NOTAVAILABLE;
2981                 }
2982             }
2983
2984             /* Check QUERY_VERTEXTEXTURE support */
2985             if(Usage & WINED3DUSAGE_QUERY_VERTEXTEXTURE) {
2986                 if (CheckVertexTextureCapability(adapter, format_desc))
2987                 {
2988                     UsageCaps |= WINED3DUSAGE_QUERY_VERTEXTEXTURE;
2989                 } else {
2990                     TRACE_(d3d_caps)("[FAILED] - No query vertextexture support\n");
2991                     return WINED3DERR_NOTAVAILABLE;
2992                 }
2993             }
2994
2995             /* Check QUERY_WRAPANDMIP support */
2996             if(Usage & WINED3DUSAGE_QUERY_WRAPANDMIP) {
2997                 if (CheckWrapAndMipCapability(adapter, format_desc))
2998                 {
2999                     UsageCaps |= WINED3DUSAGE_QUERY_WRAPANDMIP;
3000                 } else {
3001                     TRACE_(d3d_caps)("[FAILED] - No wrapping and mipmapping support\n");
3002                     return WINED3DERR_NOTAVAILABLE;
3003                 }
3004             }
3005         } else {
3006             TRACE_(d3d_caps)("[FAILED] - No volume texture support\n");
3007             return WINED3DERR_NOTAVAILABLE;
3008         }
3009
3010         /* Filter formats that need conversion; For one part, this conversion is unimplemented,
3011          * and volume textures are huge, so it would be a big performance hit. Unless we hit an
3012          * app needing one of those formats, don't advertize them to avoid leading apps into
3013          * temptation. The windows drivers don't support most of those formats on volumes anyway,
3014          * except of R32F.
3015          */
3016         switch(CheckFormat) {
3017             case WINED3DFMT_P8:
3018             case WINED3DFMT_A4L4:
3019             case WINED3DFMT_R32_FLOAT:
3020             case WINED3DFMT_R16_FLOAT:
3021             case WINED3DFMT_X8L8V8U8:
3022             case WINED3DFMT_L6V5U5:
3023             case WINED3DFMT_R16G16_UNORM:
3024                 TRACE_(d3d_caps)("[FAILED] - No converted formats on volumes\n");
3025                 return WINED3DERR_NOTAVAILABLE;
3026
3027             case WINED3DFMT_R8G8B8A8_SNORM:
3028             case WINED3DFMT_R16G16_SNORM:
3029             if(!GL_SUPPORT(NV_TEXTURE_SHADER)) {
3030                 TRACE_(d3d_caps)("[FAILED] - No converted formats on volumes\n");
3031                 return WINED3DERR_NOTAVAILABLE;
3032             }
3033             break;
3034
3035             case WINED3DFMT_R8G8_SNORM:
3036             if(!GL_SUPPORT(NV_TEXTURE_SHADER)) {
3037                 TRACE_(d3d_caps)("[FAILED] - No converted formats on volumes\n");
3038                 return WINED3DERR_NOTAVAILABLE;
3039             }
3040             break;
3041
3042             case WINED3DFMT_DXT1:
3043             case WINED3DFMT_DXT2:
3044             case WINED3DFMT_DXT3:
3045             case WINED3DFMT_DXT4:
3046             case WINED3DFMT_DXT5:
3047                 /* The GL_EXT_texture_compression_s3tc spec requires that loading an s3tc
3048                  * compressed texture results in an error. While the D3D refrast does
3049                  * support s3tc volumes, at least the nvidia windows driver does not, so
3050                  * we're free not to support this format.
3051                  */
3052                 TRACE_(d3d_caps)("[FAILED] - DXTn does not support 3D textures\n");
3053                 return WINED3DERR_NOTAVAILABLE;
3054
3055             default:
3056                 /* Do nothing, continue with checking the format below */
3057                 break;
3058         }
3059     } else if(RType == WINED3DRTYPE_BUFFER){
3060         /* For instance vertexbuffer/indexbuffer aren't supported yet because no Windows drivers seem to offer it */
3061         TRACE_(d3d_caps)("Unhandled resource type D3DRTYPE_INDEXBUFFER / D3DRTYPE_VERTEXBUFFER\n");
3062         return WINED3DERR_NOTAVAILABLE;
3063     }
3064
3065     /* This format is nothing special and it is supported perfectly.
3066      * However, ati and nvidia driver on windows do not mark this format as
3067      * supported (tested with the dxCapsViewer) and pretending to
3068      * support this format uncovers a bug in Battlefield 1942 (fonts are missing)
3069      * So do the same as Windows drivers and pretend not to support it on dx8 and 9
3070      * Enable it on dx7. It will need additional checking on dx10 when we support it.
3071      */
3072     if(This->dxVersion > 7 && CheckFormat == WINED3DFMT_R8G8B8) {
3073         TRACE_(d3d_caps)("[FAILED]\n");
3074         return WINED3DERR_NOTAVAILABLE;
3075     }
3076
3077     /* When the UsageCaps exactly matches Usage return WINED3D_OK except for the situation in which
3078      * WINED3DUSAGE_AUTOGENMIPMAP isn't around, then WINED3DOK_NOAUTOGEN is returned if all the other
3079      * usage flags match. */
3080     if(UsageCaps == Usage) {
3081         return WINED3D_OK;
3082     } else if((UsageCaps == (Usage & ~WINED3DUSAGE_AUTOGENMIPMAP)) && (Usage & WINED3DUSAGE_AUTOGENMIPMAP)){
3083         return WINED3DOK_NOAUTOGEN;
3084     } else {
3085         TRACE_(d3d_caps)("[FAILED] - Usage=%#08x requested for CheckFormat=%s and RType=%d but only %#08x is available\n", Usage, debug_d3dformat(CheckFormat), RType, UsageCaps);
3086         return WINED3DERR_NOTAVAILABLE;
3087     }
3088 }
3089
3090 static HRESULT  WINAPI IWineD3DImpl_CheckDeviceFormatConversion(IWineD3D *iface, UINT Adapter, WINED3DDEVTYPE DeviceType,
3091                                                           WINED3DFORMAT SourceFormat, WINED3DFORMAT TargetFormat) {
3092     IWineD3DImpl *This = (IWineD3DImpl *)iface;
3093
3094     FIXME_(d3d_caps)("(%p)-> (STUB) (Adptr:%d, DevType:(%u,%s), SrcFmt:(%u,%s), TgtFmt:(%u,%s))\n",
3095           This,
3096           Adapter,
3097           DeviceType, debug_d3ddevicetype(DeviceType),
3098           SourceFormat, debug_d3dformat(SourceFormat),
3099           TargetFormat, debug_d3dformat(TargetFormat));
3100     return WINED3D_OK;
3101 }
3102
3103 static const shader_backend_t *select_shader_backend(struct WineD3DAdapter *adapter, WINED3DDEVTYPE DeviceType)
3104 {
3105     const shader_backend_t *ret;
3106     int vs_selected_mode;
3107     int ps_selected_mode;
3108
3109     select_shader_mode(&adapter->gl_info, DeviceType, &ps_selected_mode, &vs_selected_mode);
3110     if (vs_selected_mode == SHADER_GLSL || ps_selected_mode == SHADER_GLSL) {
3111         ret = &glsl_shader_backend;
3112     } else if (vs_selected_mode == SHADER_ARB || ps_selected_mode == SHADER_ARB) {
3113         ret = &arb_program_shader_backend;
3114     } else {
3115         ret = &none_shader_backend;
3116     }
3117     return ret;
3118 }
3119
3120 static const struct fragment_pipeline *select_fragment_implementation(struct WineD3DAdapter *adapter,
3121         WINED3DDEVTYPE DeviceType)
3122 {
3123     const WineD3D_GL_Info *gl_info = &adapter->gl_info;
3124     int vs_selected_mode;
3125     int ps_selected_mode;
3126
3127     select_shader_mode(&adapter->gl_info, DeviceType, &ps_selected_mode, &vs_selected_mode);
3128     if((ps_selected_mode == SHADER_ARB || ps_selected_mode == SHADER_GLSL) && GL_SUPPORT(ARB_FRAGMENT_PROGRAM)) {
3129         return &arbfp_fragment_pipeline;
3130     } else if(ps_selected_mode == SHADER_ATI) {
3131         return &atifs_fragment_pipeline;
3132     } else if(GL_SUPPORT(NV_REGISTER_COMBINERS) && GL_SUPPORT(NV_TEXTURE_SHADER2)) {
3133         return &nvts_fragment_pipeline;
3134     } else if(GL_SUPPORT(NV_REGISTER_COMBINERS)) {
3135         return &nvrc_fragment_pipeline;
3136     } else {
3137         return &ffp_fragment_pipeline;
3138     }
3139 }
3140
3141 static const struct blit_shader *select_blit_implementation(struct WineD3DAdapter *adapter, WINED3DDEVTYPE DeviceType)
3142 {
3143     const WineD3D_GL_Info *gl_info = &adapter->gl_info;
3144     int vs_selected_mode;
3145     int ps_selected_mode;
3146
3147     select_shader_mode(&adapter->gl_info, DeviceType, &ps_selected_mode, &vs_selected_mode);
3148     if((ps_selected_mode == SHADER_ARB || ps_selected_mode == SHADER_GLSL) && GL_SUPPORT(ARB_FRAGMENT_PROGRAM)) {
3149         return &arbfp_blit;
3150     } else {
3151         return &ffp_blit;
3152     }
3153 }
3154
3155 /* Note: d3d8 passes in a pointer to a D3DCAPS8 structure, which is a true
3156       subset of a D3DCAPS9 structure. However, it has to come via a void *
3157       as the d3d8 interface cannot import the d3d9 header                  */
3158 static HRESULT WINAPI IWineD3DImpl_GetDeviceCaps(IWineD3D *iface, UINT Adapter, WINED3DDEVTYPE DeviceType, WINED3DCAPS* pCaps) {
3159
3160     IWineD3DImpl    *This = (IWineD3DImpl *)iface;
3161     struct WineD3DAdapter *adapter = &This->adapters[Adapter];
3162     const WineD3D_GL_Info *gl_info = &adapter->gl_info;
3163     int vs_selected_mode;
3164     int ps_selected_mode;
3165     struct shader_caps shader_caps;
3166     struct fragment_caps fragment_caps;
3167     const shader_backend_t *shader_backend;
3168     const struct fragment_pipeline *frag_pipeline = NULL;
3169     DWORD ckey_caps, blit_caps, fx_caps;
3170
3171     TRACE_(d3d_caps)("(%p)->(Adptr:%d, DevType: %x, pCaps: %p)\n", This, Adapter, DeviceType, pCaps);
3172
3173     if (Adapter >= IWineD3D_GetAdapterCount(iface)) {
3174         return WINED3DERR_INVALIDCALL;
3175     }
3176
3177     select_shader_mode(&adapter->gl_info, DeviceType, &ps_selected_mode, &vs_selected_mode);
3178
3179     /* This function should *not* be modifying GL caps
3180      * TODO: move the functionality where it belongs */
3181     select_shader_max_constants(ps_selected_mode, vs_selected_mode, &adapter->gl_info);
3182
3183     /* ------------------------------------------------
3184        The following fields apply to both d3d8 and d3d9
3185        ------------------------------------------------ */
3186     pCaps->DeviceType              = (DeviceType == WINED3DDEVTYPE_HAL) ? WINED3DDEVTYPE_HAL : WINED3DDEVTYPE_REF;  /* Not quite true, but use h/w supported by opengl I suppose */
3187     pCaps->AdapterOrdinal          = Adapter;
3188
3189     pCaps->Caps                    = 0;
3190     pCaps->Caps2                   = WINED3DCAPS2_CANRENDERWINDOWED |
3191                                      WINED3DCAPS2_FULLSCREENGAMMA |
3192                                      WINED3DCAPS2_DYNAMICTEXTURES;
3193     if(GL_SUPPORT(SGIS_GENERATE_MIPMAP)) {
3194         pCaps->Caps2 |= WINED3DCAPS2_CANAUTOGENMIPMAP;
3195     }
3196
3197     pCaps->Caps3                   = WINED3DCAPS3_ALPHA_FULLSCREEN_FLIP_OR_DISCARD |
3198                                      WINED3DCAPS3_COPY_TO_VIDMEM                   |
3199                                      WINED3DCAPS3_COPY_TO_SYSTEMMEM;
3200
3201     pCaps->PresentationIntervals   = WINED3DPRESENT_INTERVAL_IMMEDIATE  |
3202                                      WINED3DPRESENT_INTERVAL_ONE;
3203
3204     pCaps->CursorCaps              = WINED3DCURSORCAPS_COLOR            |
3205                                      WINED3DCURSORCAPS_LOWRES;
3206
3207     pCaps->DevCaps                 = WINED3DDEVCAPS_FLOATTLVERTEX       |
3208                                      WINED3DDEVCAPS_EXECUTESYSTEMMEMORY |
3209                                      WINED3DDEVCAPS_TLVERTEXSYSTEMMEMORY|
3210                                      WINED3DDEVCAPS_TLVERTEXVIDEOMEMORY |
3211                                      WINED3DDEVCAPS_DRAWPRIMTLVERTEX    |
3212                                      WINED3DDEVCAPS_HWTRANSFORMANDLIGHT |
3213                                      WINED3DDEVCAPS_EXECUTEVIDEOMEMORY  |
3214                                      WINED3DDEVCAPS_PUREDEVICE          |
3215                                      WINED3DDEVCAPS_HWRASTERIZATION     |
3216                                      WINED3DDEVCAPS_TEXTUREVIDEOMEMORY  |
3217                                      WINED3DDEVCAPS_TEXTURESYSTEMMEMORY |
3218                                      WINED3DDEVCAPS_CANRENDERAFTERFLIP  |
3219                                      WINED3DDEVCAPS_DRAWPRIMITIVES2     |
3220                                      WINED3DDEVCAPS_DRAWPRIMITIVES2EX   |
3221                                      WINED3DDEVCAPS_RTPATCHES;
3222
3223     pCaps->PrimitiveMiscCaps       = WINED3DPMISCCAPS_CULLNONE              |
3224                                      WINED3DPMISCCAPS_CULLCCW               |
3225                                      WINED3DPMISCCAPS_CULLCW                |
3226                                      WINED3DPMISCCAPS_COLORWRITEENABLE      |
3227                                      WINED3DPMISCCAPS_CLIPTLVERTS           |
3228                                      WINED3DPMISCCAPS_CLIPPLANESCALEDPOINTS |
3229                                      WINED3DPMISCCAPS_MASKZ                 |
3230                                      WINED3DPMISCCAPS_BLENDOP               |
3231                                      WINED3DPMISCCAPS_MRTPOSTPIXELSHADERBLENDING;
3232                                     /* TODO:
3233                                         WINED3DPMISCCAPS_NULLREFERENCE
3234                                         WINED3DPMISCCAPS_INDEPENDENTWRITEMASKS
3235                                         WINED3DPMISCCAPS_FOGANDSPECULARALPHA
3236                                         WINED3DPMISCCAPS_MRTINDEPENDENTBITDEPTHS
3237                                         WINED3DPMISCCAPS_FOGVERTEXCLAMPED */
3238
3239     if(GL_SUPPORT(EXT_BLEND_EQUATION_SEPARATE) && GL_SUPPORT(EXT_BLEND_FUNC_SEPARATE))
3240         pCaps->PrimitiveMiscCaps |= WINED3DPMISCCAPS_SEPARATEALPHABLEND;
3241
3242     pCaps->RasterCaps              = WINED3DPRASTERCAPS_DITHER    |
3243                                      WINED3DPRASTERCAPS_PAT       |
3244                                      WINED3DPRASTERCAPS_WFOG      |
3245                                      WINED3DPRASTERCAPS_ZFOG      |
3246                                      WINED3DPRASTERCAPS_FOGVERTEX |
3247                                      WINED3DPRASTERCAPS_FOGTABLE  |
3248                                      WINED3DPRASTERCAPS_STIPPLE   |
3249                                      WINED3DPRASTERCAPS_SUBPIXEL  |
3250                                      WINED3DPRASTERCAPS_ZTEST     |
3251                                      WINED3DPRASTERCAPS_SCISSORTEST   |
3252                                      WINED3DPRASTERCAPS_SLOPESCALEDEPTHBIAS |
3253                                      WINED3DPRASTERCAPS_DEPTHBIAS;
3254
3255     if (GL_SUPPORT(EXT_TEXTURE_FILTER_ANISOTROPIC)) {
3256         pCaps->RasterCaps |= WINED3DPRASTERCAPS_ANISOTROPY    |
3257                              WINED3DPRASTERCAPS_ZBIAS         |
3258                              WINED3DPRASTERCAPS_MIPMAPLODBIAS;
3259     }
3260     if(GL_SUPPORT(NV_FOG_DISTANCE)) {
3261         pCaps->RasterCaps         |= WINED3DPRASTERCAPS_FOGRANGE;
3262     }
3263                         /* FIXME Add:
3264                            WINED3DPRASTERCAPS_COLORPERSPECTIVE
3265                            WINED3DPRASTERCAPS_STRETCHBLTMULTISAMPLE
3266                            WINED3DPRASTERCAPS_ANTIALIASEDGES
3267                            WINED3DPRASTERCAPS_ZBUFFERLESSHSR
3268                            WINED3DPRASTERCAPS_WBUFFER */
3269
3270     pCaps->ZCmpCaps = WINED3DPCMPCAPS_ALWAYS       |
3271                       WINED3DPCMPCAPS_EQUAL        |
3272                       WINED3DPCMPCAPS_GREATER      |
3273                       WINED3DPCMPCAPS_GREATEREQUAL |
3274                       WINED3DPCMPCAPS_LESS         |
3275                       WINED3DPCMPCAPS_LESSEQUAL    |
3276                       WINED3DPCMPCAPS_NEVER        |
3277                       WINED3DPCMPCAPS_NOTEQUAL;
3278
3279     pCaps->SrcBlendCaps  = WINED3DPBLENDCAPS_BOTHINVSRCALPHA |
3280                            WINED3DPBLENDCAPS_BOTHSRCALPHA    |
3281                            WINED3DPBLENDCAPS_DESTALPHA       |
3282                            WINED3DPBLENDCAPS_DESTCOLOR       |
3283                            WINED3DPBLENDCAPS_INVDESTALPHA    |
3284                            WINED3DPBLENDCAPS_INVDESTCOLOR    |
3285                            WINED3DPBLENDCAPS_INVSRCALPHA     |
3286                            WINED3DPBLENDCAPS_INVSRCCOLOR     |
3287                            WINED3DPBLENDCAPS_ONE             |
3288                            WINED3DPBLENDCAPS_SRCALPHA        |
3289                            WINED3DPBLENDCAPS_SRCALPHASAT     |
3290                            WINED3DPBLENDCAPS_SRCCOLOR        |
3291                            WINED3DPBLENDCAPS_ZERO;
3292
3293     pCaps->DestBlendCaps = WINED3DPBLENDCAPS_DESTALPHA       |
3294                            WINED3DPBLENDCAPS_DESTCOLOR       |
3295                            WINED3DPBLENDCAPS_INVDESTALPHA    |
3296                            WINED3DPBLENDCAPS_INVDESTCOLOR    |
3297                            WINED3DPBLENDCAPS_INVSRCALPHA     |
3298                            WINED3DPBLENDCAPS_INVSRCCOLOR     |
3299                            WINED3DPBLENDCAPS_ONE             |
3300                            WINED3DPBLENDCAPS_SRCALPHA        |
3301                            WINED3DPBLENDCAPS_SRCCOLOR        |
3302                            WINED3DPBLENDCAPS_ZERO;
3303     /* NOTE: WINED3DPBLENDCAPS_SRCALPHASAT is not supported as dest blend factor,
3304      * according to the glBlendFunc manpage
3305      *
3306      * WINED3DPBLENDCAPS_BOTHINVSRCALPHA and WINED3DPBLENDCAPS_BOTHSRCALPHA are
3307      * legacy settings for srcblend only
3308      */
3309
3310     if( GL_SUPPORT(EXT_BLEND_COLOR)) {
3311         pCaps->SrcBlendCaps |= WINED3DPBLENDCAPS_BLENDFACTOR;
3312         pCaps->DestBlendCaps |= WINED3DPBLENDCAPS_BLENDFACTOR;
3313     }
3314
3315
3316     pCaps->AlphaCmpCaps = WINED3DPCMPCAPS_ALWAYS       |
3317                           WINED3DPCMPCAPS_EQUAL        |
3318                           WINED3DPCMPCAPS_GREATER      |
3319                           WINED3DPCMPCAPS_GREATEREQUAL |
3320                           WINED3DPCMPCAPS_LESS         |
3321                           WINED3DPCMPCAPS_LESSEQUAL    |
3322                           WINED3DPCMPCAPS_NEVER        |
3323                           WINED3DPCMPCAPS_NOTEQUAL;
3324
3325     pCaps->ShadeCaps     = WINED3DPSHADECAPS_SPECULARGOURAUDRGB |
3326                            WINED3DPSHADECAPS_COLORGOURAUDRGB    |
3327                            WINED3DPSHADECAPS_ALPHAFLATBLEND     |
3328                            WINED3DPSHADECAPS_ALPHAGOURAUDBLEND  |
3329                            WINED3DPSHADECAPS_COLORFLATRGB       |
3330                            WINED3DPSHADECAPS_FOGFLAT            |
3331                            WINED3DPSHADECAPS_FOGGOURAUD         |
3332                            WINED3DPSHADECAPS_SPECULARFLATRGB;
3333
3334     pCaps->TextureCaps =  WINED3DPTEXTURECAPS_ALPHA              |
3335                           WINED3DPTEXTURECAPS_ALPHAPALETTE       |
3336                           WINED3DPTEXTURECAPS_TRANSPARENCY       |
3337                           WINED3DPTEXTURECAPS_BORDER             |
3338                           WINED3DPTEXTURECAPS_MIPMAP             |
3339                           WINED3DPTEXTURECAPS_PROJECTED          |
3340                           WINED3DPTEXTURECAPS_PERSPECTIVE;
3341
3342     if( !GL_SUPPORT(ARB_TEXTURE_NON_POWER_OF_TWO)) {
3343         pCaps->TextureCaps |= WINED3DPTEXTURECAPS_POW2 |
3344                               WINED3DPTEXTURECAPS_NONPOW2CONDITIONAL;
3345     }
3346
3347     if( GL_SUPPORT(EXT_TEXTURE3D)) {
3348         pCaps->TextureCaps |=  WINED3DPTEXTURECAPS_VOLUMEMAP      |
3349                                WINED3DPTEXTURECAPS_MIPVOLUMEMAP   |
3350                                WINED3DPTEXTURECAPS_VOLUMEMAP_POW2;
3351     }
3352
3353     if (GL_SUPPORT(ARB_TEXTURE_CUBE_MAP)) {
3354         pCaps->TextureCaps |= WINED3DPTEXTURECAPS_CUBEMAP     |
3355                               WINED3DPTEXTURECAPS_MIPCUBEMAP    |
3356                               WINED3DPTEXTURECAPS_CUBEMAP_POW2;
3357
3358     }
3359
3360     pCaps->TextureFilterCaps = WINED3DPTFILTERCAPS_MAGFLINEAR       |
3361                                WINED3DPTFILTERCAPS_MAGFPOINT        |
3362                                WINED3DPTFILTERCAPS_MINFLINEAR       |
3363                                WINED3DPTFILTERCAPS_MINFPOINT        |
3364                                WINED3DPTFILTERCAPS_MIPFLINEAR       |
3365                                WINED3DPTFILTERCAPS_MIPFPOINT        |
3366                                WINED3DPTFILTERCAPS_LINEAR           |
3367                                WINED3DPTFILTERCAPS_LINEARMIPLINEAR  |
3368                                WINED3DPTFILTERCAPS_LINEARMIPNEAREST |
3369                                WINED3DPTFILTERCAPS_MIPLINEAR        |
3370                                WINED3DPTFILTERCAPS_MIPNEAREST       |
3371                                WINED3DPTFILTERCAPS_NEAREST;
3372
3373     if (GL_SUPPORT(EXT_TEXTURE_FILTER_ANISOTROPIC)) {
3374         pCaps->TextureFilterCaps |= WINED3DPTFILTERCAPS_MAGFANISOTROPIC |
3375                                     WINED3DPTFILTERCAPS_MINFANISOTROPIC;
3376     }
3377
3378     if (GL_SUPPORT(ARB_TEXTURE_CUBE_MAP)) {
3379         pCaps->CubeTextureFilterCaps = WINED3DPTFILTERCAPS_MAGFLINEAR       |
3380                                        WINED3DPTFILTERCAPS_MAGFPOINT        |
3381                                        WINED3DPTFILTERCAPS_MINFLINEAR       |
3382                                        WINED3DPTFILTERCAPS_MINFPOINT        |
3383                                        WINED3DPTFILTERCAPS_MIPFLINEAR       |
3384                                        WINED3DPTFILTERCAPS_MIPFPOINT        |
3385                                        WINED3DPTFILTERCAPS_LINEAR           |
3386                                        WINED3DPTFILTERCAPS_LINEARMIPLINEAR  |
3387                                        WINED3DPTFILTERCAPS_LINEARMIPNEAREST |
3388                                        WINED3DPTFILTERCAPS_MIPLINEAR        |
3389                                        WINED3DPTFILTERCAPS_MIPNEAREST       |
3390                                        WINED3DPTFILTERCAPS_NEAREST;
3391
3392         if (GL_SUPPORT(EXT_TEXTURE_FILTER_ANISOTROPIC)) {
3393             pCaps->CubeTextureFilterCaps |= WINED3DPTFILTERCAPS_MAGFANISOTROPIC |
3394                                             WINED3DPTFILTERCAPS_MINFANISOTROPIC;
3395         }
3396     } else
3397         pCaps->CubeTextureFilterCaps = 0;
3398
3399     if (GL_SUPPORT(EXT_TEXTURE3D)) {
3400         pCaps->VolumeTextureFilterCaps = WINED3DPTFILTERCAPS_MAGFLINEAR       |
3401                                          WINED3DPTFILTERCAPS_MAGFPOINT        |
3402                                          WINED3DPTFILTERCAPS_MINFLINEAR       |
3403                                          WINED3DPTFILTERCAPS_MINFPOINT        |
3404                                          WINED3DPTFILTERCAPS_MIPFLINEAR       |
3405                                          WINED3DPTFILTERCAPS_MIPFPOINT        |
3406                                          WINED3DPTFILTERCAPS_LINEAR           |
3407                                          WINED3DPTFILTERCAPS_LINEARMIPLINEAR  |
3408                                          WINED3DPTFILTERCAPS_LINEARMIPNEAREST |
3409                                          WINED3DPTFILTERCAPS_MIPLINEAR        |
3410                                          WINED3DPTFILTERCAPS_MIPNEAREST       |
3411                                          WINED3DPTFILTERCAPS_NEAREST;
3412     } else
3413         pCaps->VolumeTextureFilterCaps = 0;
3414
3415     pCaps->TextureAddressCaps =  WINED3DPTADDRESSCAPS_INDEPENDENTUV |
3416                                  WINED3DPTADDRESSCAPS_CLAMP  |
3417                                  WINED3DPTADDRESSCAPS_WRAP;
3418
3419     if (GL_SUPPORT(ARB_TEXTURE_BORDER_CLAMP)) {
3420         pCaps->TextureAddressCaps |= WINED3DPTADDRESSCAPS_BORDER;
3421     }
3422     if (GL_SUPPORT(ARB_TEXTURE_MIRRORED_REPEAT)) {
3423         pCaps->TextureAddressCaps |= WINED3DPTADDRESSCAPS_MIRROR;
3424     }
3425     if (GL_SUPPORT(ATI_TEXTURE_MIRROR_ONCE)) {
3426         pCaps->TextureAddressCaps |= WINED3DPTADDRESSCAPS_MIRRORONCE;
3427     }
3428
3429     if (GL_SUPPORT(EXT_TEXTURE3D)) {
3430         pCaps->VolumeTextureAddressCaps =  WINED3DPTADDRESSCAPS_INDEPENDENTUV |
3431                                            WINED3DPTADDRESSCAPS_CLAMP  |
3432                                            WINED3DPTADDRESSCAPS_WRAP;
3433         if (GL_SUPPORT(ARB_TEXTURE_BORDER_CLAMP)) {
3434             pCaps->VolumeTextureAddressCaps |= WINED3DPTADDRESSCAPS_BORDER;
3435         }
3436         if (GL_SUPPORT(ARB_TEXTURE_MIRRORED_REPEAT)) {
3437             pCaps->VolumeTextureAddressCaps |= WINED3DPTADDRESSCAPS_MIRROR;
3438         }
3439         if (GL_SUPPORT(ATI_TEXTURE_MIRROR_ONCE)) {
3440             pCaps->VolumeTextureAddressCaps |= WINED3DPTADDRESSCAPS_MIRRORONCE;
3441         }
3442     } else
3443         pCaps->VolumeTextureAddressCaps = 0;
3444
3445     pCaps->LineCaps = WINED3DLINECAPS_TEXTURE       |
3446                       WINED3DLINECAPS_ZTEST         |
3447                       WINED3DLINECAPS_BLEND         |
3448                       WINED3DLINECAPS_ALPHACMP      |
3449                       WINED3DLINECAPS_FOG;
3450     /* WINED3DLINECAPS_ANTIALIAS is not supported on Windows, and dx and gl seem to have a different
3451      * idea how generating the smoothing alpha values works; the result is different
3452      */
3453
3454     pCaps->MaxTextureWidth  = GL_LIMITS(texture_size);
3455     pCaps->MaxTextureHeight = GL_LIMITS(texture_size);
3456
3457     if(GL_SUPPORT(EXT_TEXTURE3D))
3458         pCaps->MaxVolumeExtent = GL_LIMITS(texture3d_size);
3459     else
3460         pCaps->MaxVolumeExtent = 0;
3461
3462     pCaps->MaxTextureRepeat = 32768;
3463     pCaps->MaxTextureAspectRatio = GL_LIMITS(texture_size);
3464     pCaps->MaxVertexW = 1.0;
3465
3466     pCaps->GuardBandLeft = 0;
3467     pCaps->GuardBandTop = 0;
3468     pCaps->GuardBandRight = 0;
3469     pCaps->GuardBandBottom = 0;
3470
3471     pCaps->ExtentsAdjust = 0;
3472
3473     pCaps->StencilCaps =  WINED3DSTENCILCAPS_DECRSAT |
3474                           WINED3DSTENCILCAPS_INCRSAT |
3475                           WINED3DSTENCILCAPS_INVERT  |
3476                           WINED3DSTENCILCAPS_KEEP    |
3477                           WINED3DSTENCILCAPS_REPLACE |
3478                           WINED3DSTENCILCAPS_ZERO;
3479     if (GL_SUPPORT(EXT_STENCIL_WRAP)) {
3480         pCaps->StencilCaps |= WINED3DSTENCILCAPS_DECR  |
3481                               WINED3DSTENCILCAPS_INCR;
3482     }
3483     if ( This->dxVersion > 8 &&
3484         ( GL_SUPPORT(EXT_STENCIL_TWO_SIDE) ||
3485             GL_SUPPORT(ATI_SEPARATE_STENCIL) ) ) {
3486         pCaps->StencilCaps |= WINED3DSTENCILCAPS_TWOSIDED;
3487     }
3488
3489     pCaps->FVFCaps = WINED3DFVFCAPS_PSIZE | 0x0008; /* 8 texture coords */
3490
3491     pCaps->MaxUserClipPlanes       = GL_LIMITS(clipplanes);
3492     pCaps->MaxActiveLights         = GL_LIMITS(lights);
3493
3494     pCaps->MaxVertexBlendMatrices      = GL_LIMITS(blends);
3495     pCaps->MaxVertexBlendMatrixIndex   = 0;
3496
3497     pCaps->MaxAnisotropy   = GL_LIMITS(anisotropy);
3498     pCaps->MaxPointSize    = GL_LIMITS(pointsize);
3499
3500
3501     pCaps->VertexProcessingCaps = WINED3DVTXPCAPS_DIRECTIONALLIGHTS |
3502                                   WINED3DVTXPCAPS_MATERIALSOURCE7   |
3503                                   WINED3DVTXPCAPS_POSITIONALLIGHTS  |
3504                                   WINED3DVTXPCAPS_LOCALVIEWER       |
3505                                   WINED3DVTXPCAPS_VERTEXFOG         |
3506                                   WINED3DVTXPCAPS_TEXGEN;
3507                                   /* FIXME: Add 
3508                                      D3DVTXPCAPS_TWEENING, D3DVTXPCAPS_TEXGEN_SPHEREMAP */
3509
3510     pCaps->MaxPrimitiveCount   = 0xFFFFF; /* For now set 2^20-1 which is used by most >=Geforce3/Radeon8500 cards */
3511     pCaps->MaxVertexIndex      = 0xFFFFF;
3512     pCaps->MaxStreams          = MAX_STREAMS;
3513     pCaps->MaxStreamStride     = 1024;
3514
3515     /* d3d9.dll sets D3DDEVCAPS2_CAN_STRETCHRECT_FROM_TEXTURES here because StretchRects is implemented in d3d9 */
3516     pCaps->DevCaps2                          = WINED3DDEVCAPS2_STREAMOFFSET |
3517                                                WINED3DDEVCAPS2_VERTEXELEMENTSCANSHARESTREAMOFFSET;
3518     pCaps->MaxNpatchTessellationLevel        = 0;
3519     pCaps->MasterAdapterOrdinal              = 0;
3520     pCaps->AdapterOrdinalInGroup             = 0;
3521     pCaps->NumberOfAdaptersInGroup           = 1;
3522
3523     pCaps->NumSimultaneousRTs = GL_LIMITS(buffers);
3524
3525     pCaps->StretchRectFilterCaps             = WINED3DPTFILTERCAPS_MINFPOINT  |
3526                                                 WINED3DPTFILTERCAPS_MAGFPOINT  |
3527                                                 WINED3DPTFILTERCAPS_MINFLINEAR |
3528                                                 WINED3DPTFILTERCAPS_MAGFLINEAR;
3529     pCaps->VertexTextureFilterCaps           = 0;
3530
3531     memset(&shader_caps, 0, sizeof(shader_caps));
3532     shader_backend = select_shader_backend(adapter, DeviceType);
3533     shader_backend->shader_get_caps(DeviceType, &adapter->gl_info, &shader_caps);
3534
3535     memset(&fragment_caps, 0, sizeof(fragment_caps));
3536     frag_pipeline = select_fragment_implementation(adapter, DeviceType);
3537     frag_pipeline->get_caps(DeviceType, &adapter->gl_info, &fragment_caps);
3538
3539     /* Add shader misc caps. Only some of them belong to the shader parts of the pipeline */
3540     pCaps->PrimitiveMiscCaps |= fragment_caps.PrimitiveMiscCaps;
3541
3542     /* This takes care for disabling vertex shader or pixel shader caps while leaving the other one enabled.
3543      * Ignore shader model capabilities if disabled in config
3544      */
3545     if(vs_selected_mode == SHADER_NONE) {
3546         TRACE_(d3d_caps)("Vertex shader disabled in config, reporting version 0.0\n");
3547         pCaps->VertexShaderVersion          = WINED3DVS_VERSION(0,0);
3548         pCaps->MaxVertexShaderConst         = 0;
3549     } else {
3550         pCaps->VertexShaderVersion          = shader_caps.VertexShaderVersion;
3551         pCaps->MaxVertexShaderConst         = shader_caps.MaxVertexShaderConst;
3552     }
3553
3554     if(ps_selected_mode == SHADER_NONE) {
3555         TRACE_(d3d_caps)("Pixel shader disabled in config, reporting version 0.0\n");
3556         pCaps->PixelShaderVersion           = WINED3DPS_VERSION(0,0);
3557         pCaps->PixelShader1xMaxValue        = 0.0;
3558     } else {
3559         pCaps->PixelShaderVersion           = shader_caps.PixelShaderVersion;
3560         pCaps->PixelShader1xMaxValue        = shader_caps.PixelShader1xMaxValue;
3561     }
3562
3563     pCaps->TextureOpCaps                    = fragment_caps.TextureOpCaps;
3564     pCaps->MaxTextureBlendStages            = fragment_caps.MaxTextureBlendStages;
3565     pCaps->MaxSimultaneousTextures          = fragment_caps.MaxSimultaneousTextures;
3566
3567     pCaps->VS20Caps                         = shader_caps.VS20Caps;
3568     pCaps->MaxVShaderInstructionsExecuted   = shader_caps.MaxVShaderInstructionsExecuted;
3569     pCaps->MaxVertexShader30InstructionSlots= shader_caps.MaxVertexShader30InstructionSlots;
3570     pCaps->PS20Caps                         = shader_caps.PS20Caps;
3571     pCaps->MaxPShaderInstructionsExecuted   = shader_caps.MaxPShaderInstructionsExecuted;
3572     pCaps->MaxPixelShader30InstructionSlots = shader_caps.MaxPixelShader30InstructionSlots;
3573
3574     /* The following caps are shader specific, but they are things we cannot detect, or which
3575      * are the same among all shader models. So to avoid code duplication set the shader version
3576      * specific, but otherwise constant caps here
3577      */
3578     if(pCaps->VertexShaderVersion == WINED3DVS_VERSION(3,0)) {
3579         /* Where possible set the caps based on OpenGL extensions and if they aren't set (in case of software rendering)
3580         use the VS 3.0 from MSDN or else if there's OpenGL spec use a hardcoded value minimum VS3.0 value. */
3581         pCaps->VS20Caps.Caps                     = WINED3DVS20CAPS_PREDICATION;
3582         pCaps->VS20Caps.DynamicFlowControlDepth  = WINED3DVS20_MAX_DYNAMICFLOWCONTROLDEPTH; /* VS 3.0 requires MAX_DYNAMICFLOWCONTROLDEPTH (24) */
3583         pCaps->VS20Caps.NumTemps                 = max(32, adapter->gl_info.vs_arb_max_temps);
3584         pCaps->VS20Caps.StaticFlowControlDepth   = WINED3DVS20_MAX_STATICFLOWCONTROLDEPTH ; /* level of nesting in loops / if-statements; VS 3.0 requires MAX (4) */
3585
3586         pCaps->MaxVShaderInstructionsExecuted    = 65535; /* VS 3.0 needs at least 65535, some cards even use 2^32-1 */
3587         pCaps->MaxVertexShader30InstructionSlots = max(512, adapter->gl_info.vs_arb_max_instructions);
3588     } else if(pCaps->VertexShaderVersion == WINED3DVS_VERSION(2,0)) {
3589         pCaps->VS20Caps.Caps                     = 0;
3590         pCaps->VS20Caps.DynamicFlowControlDepth  = WINED3DVS20_MIN_DYNAMICFLOWCONTROLDEPTH;
3591         pCaps->VS20Caps.NumTemps                 = max(12, adapter->gl_info.vs_arb_max_temps);
3592         pCaps->VS20Caps.StaticFlowControlDepth   = 1;
3593
3594         pCaps->MaxVShaderInstructionsExecuted    = 65535;
3595         pCaps->MaxVertexShader30InstructionSlots = 0;
3596     } else { /* VS 1.x */
3597         pCaps->VS20Caps.Caps                     = 0;
3598         pCaps->VS20Caps.DynamicFlowControlDepth  = 0;
3599         pCaps->VS20Caps.NumTemps                 = 0;
3600         pCaps->VS20Caps.StaticFlowControlDepth   = 0;
3601
3602         pCaps->MaxVShaderInstructionsExecuted    = 0;
3603         pCaps->MaxVertexShader30InstructionSlots = 0;
3604     }
3605
3606     if(pCaps->PixelShaderVersion == WINED3DPS_VERSION(3,0)) {
3607         /* Where possible set the caps based on OpenGL extensions and if they aren't set (in case of software rendering)
3608         use the PS 3.0 from MSDN or else if there's OpenGL spec use a hardcoded value minimum PS 3.0 value. */
3609
3610         /* Caps is more or less undocumented on MSDN but it appears to be used for PS20Caps based on results from R9600/FX5900/Geforce6800 cards from Windows */
3611         pCaps->PS20Caps.Caps                     = WINED3DPS20CAPS_ARBITRARYSWIZZLE     |
3612                 WINED3DPS20CAPS_GRADIENTINSTRUCTIONS |
3613                 WINED3DPS20CAPS_PREDICATION          |
3614                 WINED3DPS20CAPS_NODEPENDENTREADLIMIT |
3615                 WINED3DPS20CAPS_NOTEXINSTRUCTIONLIMIT;
3616         pCaps->PS20Caps.DynamicFlowControlDepth  = WINED3DPS20_MAX_DYNAMICFLOWCONTROLDEPTH; /* PS 3.0 requires MAX_DYNAMICFLOWCONTROLDEPTH (24) */
3617         pCaps->PS20Caps.NumTemps                 = max(32, adapter->gl_info.ps_arb_max_temps);
3618         pCaps->PS20Caps.StaticFlowControlDepth   = WINED3DPS20_MAX_STATICFLOWCONTROLDEPTH; /* PS 3.0 requires MAX_STATICFLOWCONTROLDEPTH (4) */
3619         pCaps->PS20Caps.NumInstructionSlots      = WINED3DPS20_MAX_NUMINSTRUCTIONSLOTS; /* PS 3.0 requires MAX_NUMINSTRUCTIONSLOTS (512) */
3620
3621         pCaps->MaxPShaderInstructionsExecuted    = 65535;
3622         pCaps->MaxPixelShader30InstructionSlots  = max(WINED3DMIN30SHADERINSTRUCTIONS, adapter->gl_info.ps_arb_max_instructions);
3623     } else if(pCaps->PixelShaderVersion == WINED3DPS_VERSION(2,0)) {
3624         /* Below we assume PS2.0 specs, not extended 2.0a(GeforceFX)/2.0b(Radeon R3xx) ones */
3625         pCaps->PS20Caps.Caps                     = 0;
3626         pCaps->PS20Caps.DynamicFlowControlDepth  = 0; /* WINED3DVS20_MIN_DYNAMICFLOWCONTROLDEPTH = 0 */
3627         pCaps->PS20Caps.NumTemps                 = max(12, adapter->gl_info.ps_arb_max_temps);
3628         pCaps->PS20Caps.StaticFlowControlDepth   = WINED3DPS20_MIN_STATICFLOWCONTROLDEPTH; /* Minimum: 1 */
3629         pCaps->PS20Caps.NumInstructionSlots      = WINED3DPS20_MIN_NUMINSTRUCTIONSLOTS; /* Minimum number (64 ALU + 32 Texture), a GeforceFX uses 512 */
3630
3631         pCaps->MaxPShaderInstructionsExecuted    = 512; /* Minimum value, a GeforceFX uses 1024 */
3632         pCaps->MaxPixelShader30InstructionSlots  = 0;
3633     } else { /* PS 1.x */
3634         pCaps->PS20Caps.Caps                     = 0;
3635         pCaps->PS20Caps.DynamicFlowControlDepth  = 0;
3636         pCaps->PS20Caps.NumTemps                 = 0;
3637         pCaps->PS20Caps.StaticFlowControlDepth   = 0;
3638         pCaps->PS20Caps.NumInstructionSlots      = 0;
3639
3640         pCaps->MaxPShaderInstructionsExecuted    = 0;
3641         pCaps->MaxPixelShader30InstructionSlots  = 0;
3642     }
3643
3644     if(pCaps->VertexShaderVersion >= WINED3DVS_VERSION(2,0)) {
3645         /* OpenGL supports all the formats below, perhaps not always
3646          * without conversion, but it supports them.
3647          * Further GLSL doesn't seem to have an official unsigned type so
3648          * don't advertise it yet as I'm not sure how we handle it.
3649          * We might need to add some clamping in the shader engine to
3650          * support it.
3651          * TODO: WINED3DDTCAPS_USHORT2N, WINED3DDTCAPS_USHORT4N, WINED3DDTCAPS_UDEC3, WINED3DDTCAPS_DEC3N */
3652         pCaps->DeclTypes = WINED3DDTCAPS_UBYTE4    |
3653                            WINED3DDTCAPS_UBYTE4N   |
3654                            WINED3DDTCAPS_SHORT2N   |
3655                            WINED3DDTCAPS_SHORT4N;
3656         if (GL_SUPPORT(ARB_HALF_FLOAT_VERTEX)) {
3657             pCaps->DeclTypes |= WINED3DDTCAPS_FLOAT16_2 |
3658                                 WINED3DDTCAPS_FLOAT16_4;
3659         }
3660     } else
3661         pCaps->DeclTypes                         = 0;
3662
3663     /* Set DirectDraw helper Caps */
3664     ckey_caps =                         WINEDDCKEYCAPS_DESTBLT              |
3665                                         WINEDDCKEYCAPS_SRCBLT;
3666     fx_caps =                           WINEDDFXCAPS_BLTALPHA               |
3667                                         WINEDDFXCAPS_BLTMIRRORLEFTRIGHT     |
3668                                         WINEDDFXCAPS_BLTMIRRORUPDOWN        |
3669                                         WINEDDFXCAPS_BLTROTATION90          |
3670                                         WINEDDFXCAPS_BLTSHRINKX             |
3671                                         WINEDDFXCAPS_BLTSHRINKXN            |
3672                                         WINEDDFXCAPS_BLTSHRINKY             |
3673                                         WINEDDFXCAPS_BLTSHRINKXN            |
3674                                         WINEDDFXCAPS_BLTSTRETCHX            |
3675                                         WINEDDFXCAPS_BLTSTRETCHXN           |
3676                                         WINEDDFXCAPS_BLTSTRETCHY            |
3677                                         WINEDDFXCAPS_BLTSTRETCHYN;
3678     blit_caps =                         WINEDDCAPS_BLT                      |
3679                                         WINEDDCAPS_BLTCOLORFILL             |
3680                                         WINEDDCAPS_BLTDEPTHFILL             |
3681                                         WINEDDCAPS_BLTSTRETCH               |
3682                                         WINEDDCAPS_CANBLTSYSMEM             |
3683                                         WINEDDCAPS_CANCLIP                  |
3684                                         WINEDDCAPS_CANCLIPSTRETCHED         |
3685                                         WINEDDCAPS_COLORKEY                 |
3686                                         WINEDDCAPS_COLORKEYHWASSIST         |
3687                                         WINEDDCAPS_ALIGNBOUNDARYSRC;
3688
3689     /* Fill the ddraw caps structure */
3690     pCaps->DirectDrawCaps.Caps =        WINEDDCAPS_GDI                      |
3691                                         WINEDDCAPS_PALETTE                  |
3692                                         blit_caps;
3693     pCaps->DirectDrawCaps.Caps2 =       WINEDDCAPS2_CERTIFIED                |
3694                                         WINEDDCAPS2_NOPAGELOCKREQUIRED       |
3695                                         WINEDDCAPS2_PRIMARYGAMMA             |
3696                                         WINEDDCAPS2_WIDESURFACES             |
3697                                         WINEDDCAPS2_CANRENDERWINDOWED;
3698     pCaps->DirectDrawCaps.SVBCaps =     blit_caps;
3699     pCaps->DirectDrawCaps.SVBCKeyCaps = ckey_caps;
3700     pCaps->DirectDrawCaps.SVBFXCaps =   fx_caps;
3701     pCaps->DirectDrawCaps.VSBCaps =     blit_caps;
3702     pCaps->DirectDrawCaps.VSBCKeyCaps = ckey_caps;
3703     pCaps->DirectDrawCaps.VSBFXCaps =   fx_caps;
3704     pCaps->DirectDrawCaps.SSBCaps =     blit_caps;
3705     pCaps->DirectDrawCaps.SSBCKeyCaps = ckey_caps;
3706     pCaps->DirectDrawCaps.SSBFXCaps =   fx_caps;
3707
3708     pCaps->DirectDrawCaps.ddsCaps =     WINEDDSCAPS_ALPHA                   |
3709                                         WINEDDSCAPS_BACKBUFFER              |
3710                                         WINEDDSCAPS_FLIP                    |
3711                                         WINEDDSCAPS_FRONTBUFFER             |
3712                                         WINEDDSCAPS_OFFSCREENPLAIN          |
3713                                         WINEDDSCAPS_PALETTE                 |
3714                                         WINEDDSCAPS_PRIMARYSURFACE          |
3715                                         WINEDDSCAPS_SYSTEMMEMORY            |
3716                                         WINEDDSCAPS_VIDEOMEMORY             |
3717                                         WINEDDSCAPS_VISIBLE;
3718     pCaps->DirectDrawCaps.StrideAlign = DDRAW_PITCH_ALIGNMENT;
3719
3720     /* Set D3D caps if OpenGL is available. */
3721     if (adapter->opengl)
3722     {
3723         pCaps->DirectDrawCaps.ddsCaps |=WINEDDSCAPS_3DDEVICE                |
3724                                         WINEDDSCAPS_MIPMAP                  |
3725                                         WINEDDSCAPS_TEXTURE                 |
3726                                         WINEDDSCAPS_ZBUFFER;
3727         pCaps->DirectDrawCaps.Caps |=   WINEDDCAPS_3D;
3728     }
3729
3730     return WINED3D_OK;
3731 }
3732
3733 /* Note due to structure differences between dx8 and dx9 D3DPRESENT_PARAMETERS,
3734    and fields being inserted in the middle, a new structure is used in place    */
3735 static HRESULT WINAPI IWineD3DImpl_CreateDevice(IWineD3D *iface, UINT Adapter,
3736         WINED3DDEVTYPE DeviceType, HWND hFocusWindow, DWORD BehaviourFlags, IUnknown *parent,
3737         IWineD3DDeviceParent *device_parent, IWineD3DDevice **ppReturnedDeviceInterface)
3738 {
3739     IWineD3DDeviceImpl *object  = NULL;
3740     IWineD3DImpl       *This    = (IWineD3DImpl *)iface;
3741     struct WineD3DAdapter *adapter = &This->adapters[Adapter];
3742     WINED3DDISPLAYMODE  mode;
3743     const struct fragment_pipeline *frag_pipeline = NULL;
3744     int i;
3745     struct fragment_caps ffp_caps;
3746     struct shader_caps shader_caps;
3747     HRESULT hr;
3748
3749     /* Validate the adapter number. If no adapters are available(no GL), ignore the adapter
3750      * number and create a device without a 3D adapter for 2D only operation.
3751      */
3752     if (IWineD3D_GetAdapterCount(iface) && Adapter >= IWineD3D_GetAdapterCount(iface)) {
3753         return WINED3DERR_INVALIDCALL;
3754     }
3755
3756     /* Create a WineD3DDevice object */
3757     object = HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, sizeof(IWineD3DDeviceImpl));
3758     *ppReturnedDeviceInterface = (IWineD3DDevice *)object;
3759     TRACE("Created WineD3DDevice object @ %p\n", object);
3760     if (NULL == object) {
3761       return WINED3DERR_OUTOFVIDEOMEMORY;
3762     }
3763
3764     /* Set up initial COM information */
3765     object->lpVtbl  = &IWineD3DDevice_Vtbl;
3766     object->ref     = 1;
3767     object->wineD3D = iface;
3768     object->adapter = This->adapter_count ? adapter : NULL;
3769     IWineD3D_AddRef(object->wineD3D);
3770     object->parent  = parent;
3771     object->device_parent = device_parent;
3772     list_init(&object->resources);
3773     list_init(&object->shaders);
3774
3775     if(This->dxVersion == 7) {
3776         object->surface_alignment = DDRAW_PITCH_ALIGNMENT;
3777     } else {
3778         object->surface_alignment = D3D8_PITCH_ALIGNMENT;
3779     }
3780     object->posFixup[0] = 1.0; /* This is needed to get the x coord unmodified through a MAD */
3781
3782     /* Set the state up as invalid until the device is fully created */
3783     object->state   = WINED3DERR_DRIVERINTERNALERROR;
3784
3785     TRACE("(%p)->(Adptr:%d, DevType: %x, FocusHwnd: %p, BehFlags: %x, RetDevInt: %p)\n", This, Adapter, DeviceType,
3786           hFocusWindow, BehaviourFlags, ppReturnedDeviceInterface);
3787
3788     /* Save the creation parameters */
3789     object->createParms.AdapterOrdinal = Adapter;
3790     object->createParms.DeviceType     = DeviceType;
3791     object->createParms.hFocusWindow   = hFocusWindow;
3792     object->createParms.BehaviorFlags  = BehaviourFlags;
3793
3794     /* Initialize other useful values */
3795     object->adapterNo                    = Adapter;
3796     object->devType                      = DeviceType;
3797
3798     select_shader_mode(&adapter->gl_info, DeviceType,
3799             &object->ps_selected_mode, &object->vs_selected_mode);
3800     object->shader_backend = select_shader_backend(adapter, DeviceType);
3801
3802     memset(&shader_caps, 0, sizeof(shader_caps));
3803     object->shader_backend->shader_get_caps(DeviceType, &adapter->gl_info, &shader_caps);
3804     object->d3d_vshader_constantF = shader_caps.MaxVertexShaderConst;
3805     object->d3d_pshader_constantF = shader_caps.MaxPixelShaderConst;
3806     object->vs_clipping = shader_caps.VSClipping;
3807
3808     memset(&ffp_caps, 0, sizeof(ffp_caps));
3809     frag_pipeline = select_fragment_implementation(adapter, DeviceType);
3810     object->frag_pipe = frag_pipeline;
3811     frag_pipeline->get_caps(DeviceType, &adapter->gl_info, &ffp_caps);
3812     object->max_ffp_textures = ffp_caps.MaxSimultaneousTextures;
3813     object->max_ffp_texture_stages = ffp_caps.MaxTextureBlendStages;
3814     hr = compile_state_table(object->StateTable, object->multistate_funcs, &adapter->gl_info,
3815                         ffp_vertexstate_template, frag_pipeline, misc_state_template);
3816
3817     if (FAILED(hr)) {
3818         IWineD3D_Release(object->wineD3D);
3819         HeapFree(GetProcessHeap(), 0, object);
3820
3821         return hr;
3822     }
3823
3824     object->blitter = select_blit_implementation(adapter, DeviceType);
3825
3826     /* set the state of the device to valid */
3827     object->state = WINED3D_OK;
3828
3829     /* Get the initial screen setup for ddraw */
3830     IWineD3DImpl_GetAdapterDisplayMode(iface, Adapter, &mode);
3831
3832     object->ddraw_width = mode.Width;
3833     object->ddraw_height = mode.Height;
3834     object->ddraw_format = mode.Format;
3835
3836     for(i = 0; i < PATCHMAP_SIZE; i++) {
3837         list_init(&object->patches[i]);
3838     }
3839
3840     IWineD3DDeviceParent_WineD3DDeviceCreated(device_parent, *ppReturnedDeviceInterface);
3841
3842     return WINED3D_OK;
3843 }
3844
3845 static HRESULT WINAPI IWineD3DImpl_GetParent(IWineD3D *iface, IUnknown **pParent) {
3846     IWineD3DImpl *This = (IWineD3DImpl *)iface;
3847     IUnknown_AddRef(This->parent);
3848     *pParent = This->parent;
3849     return WINED3D_OK;
3850 }
3851
3852 ULONG WINAPI D3DCB_DefaultDestroySurface(IWineD3DSurface *pSurface) {
3853     IUnknown* surfaceParent;
3854     TRACE("(%p) call back\n", pSurface);
3855
3856     /* Now, release the parent, which will take care of cleaning up the surface for us */
3857     IWineD3DSurface_GetParent(pSurface, &surfaceParent);
3858     IUnknown_Release(surfaceParent);
3859     return IUnknown_Release(surfaceParent);
3860 }
3861
3862 ULONG WINAPI D3DCB_DefaultDestroyVolume(IWineD3DVolume *pVolume) {
3863     IUnknown* volumeParent;
3864     TRACE("(%p) call back\n", pVolume);
3865
3866     /* Now, release the parent, which will take care of cleaning up the volume for us */
3867     IWineD3DVolume_GetParent(pVolume, &volumeParent);
3868     IUnknown_Release(volumeParent);
3869     return IUnknown_Release(volumeParent);
3870 }
3871
3872 static BOOL match_apple(const WineD3D_GL_Info *gl_info)
3873 {
3874     /* MacOS has various specialities in the extensions it advertises. Some have to be loaded from
3875      * the opengl 1.2+ core, while other extensions are advertised, but software emulated. So try to
3876      * detect the Apple OpenGL implementation to apply some extension fixups afterwards.
3877      *
3878      * Detecting this isn't really easy. The vendor string doesn't mention Apple. Compile-time checks
3879      * aren't sufficient either because a Linux binary may display on a macos X server via remote X11.
3880      * So try to detect the GL implementation by looking at certain Apple extensions. Some extensions
3881      * like client storage might be supported on other implementations too, but GL_APPLE_flush_render
3882      * is specific to the Mac OS X window management, and GL_APPLE_ycbcr_422 is QuickTime specific. So
3883      * the chance that other implementations support them is rather small since Win32 QuickTime uses
3884      * DirectDraw, not OpenGL.
3885      */
3886     if(gl_info->supported[APPLE_FENCE] &&
3887        gl_info->supported[APPLE_CLIENT_STORAGE] &&
3888        gl_info->supported[APPLE_FLUSH_RENDER] &&
3889        gl_info->supported[APPLE_YCBCR_422]) {
3890         TRACE_(d3d_caps)("GL_APPLE_fence, GL_APPLE_client_storage, GL_APPLE_flush_render and GL_ycbcr_422 are supported\n");
3891         TRACE_(d3d_caps)("Activating MacOS fixups\n");
3892         return TRUE;
3893     } else {
3894         TRACE_(d3d_caps)("Apple extensions are not supported\n");
3895         TRACE_(d3d_caps)("Not activating MacOS fixups\n");
3896         return FALSE;
3897     }
3898 }
3899
3900 static void test_pbo_functionality(WineD3D_GL_Info *gl_info) {
3901     /* Some OpenGL implementations, namely Apple's Geforce 8 driver, advertises PBOs,
3902      * but glTexSubImage from a PBO fails miserably, with the first line repeated over
3903      * all the texture. This function detects this bug by its symptom and disables PBOs
3904      * if the test fails.
3905      *
3906      * The test uploads a 4x4 texture via the PBO in the "native" format GL_BGRA,
3907      * GL_UNSIGNED_INT_8_8_8_8_REV. This format triggers the bug, and it is what we use
3908      * for D3DFMT_A8R8G8B8. Then the texture is read back without any PBO and the data
3909      * read back is compared to the original. If they are equal PBOs are assumed to work,
3910      * otherwise the PBO extension is disabled.
3911      */
3912     GLuint texture, pbo;
3913     static const unsigned int pattern[] = {
3914         0x00000000, 0x000000ff, 0x0000ff00, 0x40ff0000,
3915         0x80ffffff, 0x40ffff00, 0x00ff00ff, 0x0000ffff,
3916         0x00ffff00, 0x00ff00ff, 0x0000ffff, 0x000000ff,
3917         0x80ff00ff, 0x0000ffff, 0x00ff00ff, 0x40ff00ff
3918     };
3919     unsigned int check[sizeof(pattern) / sizeof(pattern[0])];
3920
3921     if(!gl_info->supported[ARB_PIXEL_BUFFER_OBJECT]) {
3922         /* No PBO -> No point in testing them */
3923         return;
3924     }
3925
3926     ENTER_GL();
3927
3928     while(glGetError());
3929     glGenTextures(1, &texture);
3930     glBindTexture(GL_TEXTURE_2D, texture);
3931
3932     glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAX_LEVEL, 0);
3933     glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA8, 4, 4, 0, GL_BGRA, GL_UNSIGNED_INT_8_8_8_8_REV, 0);
3934     checkGLcall("Specifying the PBO test texture\n");
3935
3936     GL_EXTCALL(glGenBuffersARB(1, &pbo));
3937     GL_EXTCALL(glBindBufferARB(GL_PIXEL_UNPACK_BUFFER_ARB, pbo));
3938     GL_EXTCALL(glBufferDataARB(GL_PIXEL_UNPACK_BUFFER_ARB, sizeof(pattern), pattern, GL_STREAM_DRAW_ARB));
3939     checkGLcall("Specifying the PBO test pbo\n");
3940
3941     glTexSubImage2D(GL_TEXTURE_2D, 0, 0, 0, 4, 4, GL_BGRA, GL_UNSIGNED_INT_8_8_8_8_REV, NULL);
3942     checkGLcall("Loading the PBO test texture\n");
3943
3944     GL_EXTCALL(glBindBufferARB(GL_PIXEL_UNPACK_BUFFER_ARB, 0));
3945     glFinish(); /* just to be sure */
3946
3947     memset(check, 0, sizeof(check));
3948     glGetTexImage(GL_TEXTURE_2D, 0, GL_BGRA, GL_UNSIGNED_INT_8_8_8_8_REV, check);
3949     checkGLcall("Reading back the PBO test texture\n");
3950
3951     glDeleteTextures(1, &texture);
3952     GL_EXTCALL(glDeleteBuffersARB(1, &pbo));
3953     checkGLcall("PBO test cleanup\n");
3954
3955     LEAVE_GL();
3956
3957     if(memcmp(check, pattern, sizeof(check)) != 0) {
3958         WARN_(d3d_caps)("PBO test failed, read back data doesn't match original\n");
3959         WARN_(d3d_caps)("Disabling PBOs. This may result in slower performance\n");
3960         gl_info->supported[ARB_PIXEL_BUFFER_OBJECT] = FALSE;
3961     } else {
3962         TRACE_(d3d_caps)("PBO test successful\n");
3963     }
3964 }
3965
3966 /* Certain applications(Steam) complain if we report an outdated driver version. In general,
3967  * reporting a driver version is moot because we are not the Windows driver, and we have different
3968  * bugs, features, etc.
3969  *
3970  * If a card is not found in this table, the gl driver version is reported
3971  */
3972 struct driver_version_information {
3973     WORD vendor;                        /* reported PCI card vendor ID  */
3974     WORD card;                          /* reported PCI card device ID  */
3975     const char *description;                  /* Description of the card e.g. NVIDIA RIVA TNT */
3976     WORD hipart_hi, hipart_lo;          /* driver hiword to report      */
3977     WORD lopart_hi, lopart_lo;          /* driver loword to report      */
3978 };
3979
3980 static const struct driver_version_information driver_version_table[] = {
3981     /* Nvidia drivers. Geforce6 and newer cards are supported by the current driver (180.x)
3982      * GeforceFX support is up to 173.x, - driver uses numbering x.y.11.7341 for 173.41 where x is the windows revision (6=2000/xp, 7=vista), y is unknown
3983      * Geforce2MX/3/4 up to 96.x - driver uses numbering 9.6.8.9 for 96.89
3984      * TNT/Geforce1/2 up to 71.x - driver uses numbering 7.1.8.6 for 71.86
3985      *
3986      * All version numbers used below are from the Linux nvidia drivers.
3987      */
3988     {VENDOR_NVIDIA,     CARD_NVIDIA_RIVA_TNT,           "NVIDIA RIVA TNT",                  7,  1,  8,  6      },
3989     {VENDOR_NVIDIA,     CARD_NVIDIA_RIVA_TNT2,          "NVIDIA RIVA TNT2/TNT2 Pro",        7,  1,  8,  6      },
3990     {VENDOR_NVIDIA,     CARD_NVIDIA_GEFORCE,            "NVIDIA GeForce 256",               7,  1,  8,  6      },
3991     {VENDOR_NVIDIA,     CARD_NVIDIA_GEFORCE2_MX,        "NVIDIA GeForce2 MX/MX 400",        9,  6,  4,  3      },
3992     {VENDOR_NVIDIA,     CARD_NVIDIA_GEFORCE2,           "NVIDIA GeForce2 GTS/GeForce2 Pro", 7,  1,  8,  6      },
3993     {VENDOR_NVIDIA,     CARD_NVIDIA_GEFORCE3,           "NVIDIA GeForce3",                  9,  6,  4,  3      },
3994     {VENDOR_NVIDIA,     CARD_NVIDIA_GEFORCE4_MX,        "NVIDIA GeForce4 MX 460",           9,  6,  4,  3      },
3995     {VENDOR_NVIDIA,     CARD_NVIDIA_GEFORCE4_TI4200,    "NVIDIA GeForce4 Ti 4200",          9,  6,  4,  3      },
3996     {VENDOR_NVIDIA,     CARD_NVIDIA_GEFORCEFX_5200,     "NVIDIA GeForce FX 5200",           7,  15, 11, 7341   },
3997     {VENDOR_NVIDIA,     CARD_NVIDIA_GEFORCEFX_5600,     "NVIDIA GeForce FX 5600",           7,  15, 11, 7341   },
3998     {VENDOR_NVIDIA,     CARD_NVIDIA_GEFORCEFX_5800,     "NVIDIA GeForce FX 5800",           7,  15, 11, 7341   },
3999     {VENDOR_NVIDIA,     CARD_NVIDIA_GEFORCE_6200,       "NVIDIA GeForce 6200",              7,  15, 11, 8044   },
4000     {VENDOR_NVIDIA,     CARD_NVIDIA_GEFORCE_6600GT,     "NVIDIA GeForce 6600 GT",           7,  15, 11, 8044   },
4001     {VENDOR_NVIDIA,     CARD_NVIDIA_GEFORCE_6800,       "NVIDIA GeForce 6800",              7,  15, 11, 8044   },
4002     {VENDOR_NVIDIA,     CARD_NVIDIA_GEFORCE_7300,       "NVIDIA GeForce Go 7300",           7,  15, 11, 8044   },
4003     {VENDOR_NVIDIA,     CARD_NVIDIA_GEFORCE_7400,       "NVIDIA GeForce Go 7400",           7,  15, 11, 8044   },
4004     {VENDOR_NVIDIA,     CARD_NVIDIA_GEFORCE_7600,       "NVIDIA GeForce 7600 GT",           7,  15, 11, 8044   },
4005     {VENDOR_NVIDIA,     CARD_NVIDIA_GEFORCE_7800GT,     "NVIDIA GeForce 7800 GT",           7,  15, 11, 8044   },
4006     {VENDOR_NVIDIA,     CARD_NVIDIA_GEFORCE_8300GS,     "NVIDIA GeForce 8300 GS",           7,  15, 11, 8044   },
4007     {VENDOR_NVIDIA,     CARD_NVIDIA_GEFORCE_8600GT,     "NVIDIA GeForce 8600 GT",           7,  15, 11, 8044   },
4008     {VENDOR_NVIDIA,     CARD_NVIDIA_GEFORCE_8600MGT,    "NVIDIA GeForce 8600M GT",          7,  15, 11, 8044   },
4009     {VENDOR_NVIDIA,     CARD_NVIDIA_GEFORCE_8800GTS,    "NVIDIA GeForce 8800 GTS",          7,  15, 11, 8044   },
4010     {VENDOR_NVIDIA,     CARD_NVIDIA_GEFORCE_9200,       "NVIDIA GeForce 9200",              7,  15, 11, 8044   },
4011     {VENDOR_NVIDIA,     CARD_NVIDIA_GEFORCE_9400GT,     "NVIDIA GeForce 9400 GT",           7,  15, 11, 8044   },
4012     {VENDOR_NVIDIA,     CARD_NVIDIA_GEFORCE_9500GT,     "NVIDIA GeForce 9500 GT",           7,  15, 11, 8044   },
4013     {VENDOR_NVIDIA,     CARD_NVIDIA_GEFORCE_9600GT,     "NVIDIA GeForce 9600 GT",           7,  15, 11, 8044   },
4014     {VENDOR_NVIDIA,     CARD_NVIDIA_GEFORCE_9800GT,     "NVIDIA GeForce 9800 GT",           7,  15, 11, 8044   },
4015     {VENDOR_NVIDIA,     CARD_NVIDIA_GEFORCE_GTX260,     "NVIDIA GeForce GTX 260",           7,  15, 11, 8044   },
4016     {VENDOR_NVIDIA,     CARD_NVIDIA_GEFORCE_GTX275,     "NVIDIA GeForce GTX 275",           7,  15, 11, 8044   },
4017     {VENDOR_NVIDIA,     CARD_NVIDIA_GEFORCE_GTX280,     "NVIDIA GeForce GTX 280",           7,  15, 11, 8044   },
4018
4019     /* ATI cards. The driver versions are somewhat similar, but not quite the same. Let's hardcode */
4020     {VENDOR_ATI,        CARD_ATI_RADEON_9500,           "ATI Radeon 9500",                  6,  14, 10, 6764    },
4021     {VENDOR_ATI,        CARD_ATI_RADEON_X700,           "ATI Radeon X700 SE",               6,  14, 10, 6764    },
4022     {VENDOR_ATI,        CARD_ATI_RADEON_X1600,          "ATI Radeon X1600 Series",          6,  14, 10, 6764    },
4023     {VENDOR_ATI,        CARD_ATI_RADEON_HD2300,         "ATI Mobility Radeon HD 2300",      6,  14, 10, 6764    },
4024     {VENDOR_ATI,        CARD_ATI_RADEON_HD2600,         "ATI Mobility Radeon HD 2600",      6,  14, 10, 6764    },
4025     {VENDOR_ATI,        CARD_ATI_RADEON_HD2900,         "ATI Radeon HD 2900 XT",            6,  14, 10, 6764    },
4026     {VENDOR_ATI,        CARD_ATI_RADEON_HD4800,         "ATI Radeon HD 4800 Series",        6,  14, 10, 6764    },
4027
4028     /* TODO: Add information about legacy ATI hardware, Intel and other cards */
4029 };
4030
4031 static BOOL match_ati_r300_to_500(const WineD3D_GL_Info *gl_info) {
4032     if(gl_info->gl_vendor != VENDOR_ATI) return FALSE;
4033     if(gl_info->gl_card == CARD_ATI_RADEON_9500) return TRUE;
4034     if(gl_info->gl_card == CARD_ATI_RADEON_X700) return TRUE;
4035     if(gl_info->gl_card == CARD_ATI_RADEON_X1600) return TRUE;
4036     return FALSE;
4037 }
4038
4039 static BOOL match_geforce5(const WineD3D_GL_Info *gl_info) {
4040     if(gl_info->gl_vendor == VENDOR_NVIDIA) {
4041         if(gl_info->gl_card == CARD_NVIDIA_GEFORCEFX_5800 || gl_info->gl_card == CARD_NVIDIA_GEFORCEFX_5600) {
4042             return TRUE;
4043         }
4044     }
4045     return FALSE;
4046 }
4047
4048 static BOOL match_apple_intel(const WineD3D_GL_Info *gl_info) {
4049     return gl_info->gl_vendor == VENDOR_INTEL && match_apple(gl_info);
4050 }
4051
4052 static BOOL match_apple_nonr500ati(const WineD3D_GL_Info *gl_info) {
4053     if(!match_apple(gl_info)) return FALSE;
4054     if(gl_info->gl_vendor != VENDOR_ATI) return FALSE;
4055     if(gl_info->gl_card == CARD_ATI_RADEON_X1600) return FALSE;
4056     return TRUE;
4057 }
4058
4059 static BOOL match_fglrx(const WineD3D_GL_Info *gl_info) {
4060     if(gl_info->gl_vendor != VENDOR_ATI) return FALSE;
4061     if(match_apple(gl_info)) return FALSE;
4062     if(strstr(gl_info->gl_renderer, "DRI")) return FALSE; /* Filter out Mesa DRI drivers */
4063     return TRUE;
4064 }
4065
4066 static BOOL match_dx10_capable(const WineD3D_GL_Info *gl_info) {
4067     /* DX9 cards support 40 single float varyings in hardware, most drivers report 32. ATI misreports
4068      * 44 varyings. So assume that if we have more than 44 varyings we have a dx10 card.
4069      * This detection is for the gl_ClipPos varying quirk. If a d3d9 card really supports more than 44
4070      * varyings and we subtract one in dx9 shaders its not going to hurt us because the dx9 limit is
4071      * hardcoded
4072      *
4073      * dx10 cards usually have 64 varyings
4074      */
4075     return gl_info->max_glsl_varyings > 44;
4076 }
4077
4078 static void quirk_arb_constants(WineD3D_GL_Info *gl_info) {
4079     TRACE_(d3d_caps)("Using ARB vs constant limit(=%u) for GLSL\n", gl_info->vs_arb_constantsF);
4080     gl_info->vs_glsl_constantsF = gl_info->vs_arb_constantsF;
4081     TRACE_(d3d_caps)("Using ARB ps constant limit(=%u) for GLSL\n", gl_info->ps_arb_constantsF);
4082     gl_info->ps_glsl_constantsF = gl_info->ps_arb_constantsF;
4083 }
4084
4085 static void quirk_apple_glsl_constants(WineD3D_GL_Info *gl_info) {
4086     quirk_arb_constants(gl_info);
4087     /* MacOS needs uniforms for relative addressing offsets. This can accumulate to quite a few uniforms.
4088      * Beyond that the general uniform isn't optimal, so reserve a number of uniforms. 12 vec4's should
4089      * allow 48 different offsets or other helper immediate values
4090      */
4091     TRACE_(d3d_caps)("Reserving 12 GLSL constants for compiler private use\n");
4092     gl_info->reserved_glsl_constants = max(gl_info->reserved_glsl_constants, 12);
4093 }
4094
4095 /* fglrx crashes with a very bad kernel panic if GL_POINT_SPRITE_ARB is set to GL_COORD_REPLACE_ARB
4096  * on more than one texture unit. This means that the d3d9 visual point size test will cause a
4097  * kernel panic on any machine running fglrx 9.3(latest that supports r300 to r500 cards). This
4098  * quirk only enables point sprites on the first texture unit. This keeps point sprites working in
4099  * most games, but avoids the crash
4100  *
4101  * A more sophisticated way would be to find all units that need texture coordinates and enable
4102  * point sprites for one if only one is found, and software emulate point sprites in drawStridedSlow
4103  * if more than one unit needs texture coordinates(This requires software ffp and vertex shaders though)
4104  *
4105  * Note that disabling the extension entirely does not gain predictability because there is no point
4106  * sprite capability flag in d3d, so the potential rendering bugs are the same if we disable the extension.
4107  */
4108 static void quirk_one_point_sprite(WineD3D_GL_Info *gl_info) {
4109     if(gl_info->supported[ARB_POINT_SPRITE]) {
4110         TRACE("Limiting point sprites to one texture unit\n");
4111         gl_info->max_point_sprite_units = 1;
4112     }
4113 }
4114
4115 static void quirk_ati_dx9(WineD3D_GL_Info *gl_info) {
4116     quirk_arb_constants(gl_info);
4117
4118     /* MacOS advertises GL_ARB_texture_non_power_of_two on ATI r500 and earlier cards, although
4119      * these cards only support GL_ARB_texture_rectangle(D3DPTEXTURECAPS_NONPOW2CONDITIONAL).
4120      * If real NP2 textures are used, the driver falls back to software. We could just remove the
4121      * extension and use GL_ARB_texture_rectangle instead, but texture_rectangle is inconventient
4122      * due to the non-normalized texture coordinates. Thus set an internal extension flag,
4123      * GL_WINE_normalized_texrect, which signals the code that it can use non power of two textures
4124      * as per GL_ARB_texture_non_power_of_two, but has to stick to the texture_rectangle limits.
4125      *
4126      * fglrx doesn't advertise GL_ARB_texture_non_power_of_two, but it advertises opengl 2.0 which
4127      * has this extension promoted to core. The extension loading code sets this extension supported
4128      * due to that, so this code works on fglrx as well.
4129      */
4130     TRACE("GL_ARB_texture_non_power_of_two advertised on R500 or earlier card, removing\n");
4131     gl_info->supported[ARB_TEXTURE_NON_POWER_OF_TWO] = FALSE;
4132     gl_info->supported[WINE_NORMALIZED_TEXRECT] = TRUE;
4133
4134     /* fglrx has the same structural issues as the one described in quirk_apple_glsl_constants, although
4135      * it is generally more efficient. Reserve just 8 constants
4136      */
4137     TRACE_(d3d_caps)("Reserving 8 GLSL constants for compiler private use\n");
4138     gl_info->reserved_glsl_constants = max(gl_info->reserved_glsl_constants, 8);
4139 }
4140
4141 static void quirk_no_np2(WineD3D_GL_Info *gl_info) {
4142     /*  The nVidia GeForceFX series reports OpenGL 2.0 capabilities with the latest drivers versions, but
4143      *  doesn't explicitly advertise the ARB_tex_npot extension in the GL extension string.
4144      *  This usually means that ARB_tex_npot is supported in hardware as long as the application is staying
4145      *  within the limits enforced by the ARB_texture_rectangle extension. This however is not true for the
4146      *  FX series, which instantly falls back to a slower software path as soon as ARB_tex_npot is used.
4147      *  We therefore completely remove ARB_tex_npot from the list of supported extensions.
4148      *
4149      *  Note that wine_normalized_texrect can't be used in this case because internally it uses ARB_tex_npot,
4150      *  triggering the software fallback. There is not much we can do here apart from disabling the
4151      *  software-emulated extension and reenable ARB_tex_rect (which was previously disabled
4152      *  in IWineD3DImpl_FillGLCaps).
4153      *  This fixup removes performance problems on both the FX 5900 and FX 5700 (e.g. for framebuffer
4154      *  post-processing effects in the game "Max Payne 2").
4155      *  The behaviour can be verified through a simple test app attached in bugreport #14724.
4156      */
4157     TRACE("GL_ARB_texture_non_power_of_two advertised through OpenGL 2.0 on NV FX card, removing\n");
4158     gl_info->supported[ARB_TEXTURE_NON_POWER_OF_TWO] = FALSE;
4159     gl_info->supported[ARB_TEXTURE_RECTANGLE] = TRUE;
4160 }
4161
4162 static void quirk_texcoord_w(WineD3D_GL_Info *gl_info) {
4163     /* The Intel GPUs on MacOS set the .w register of texcoords to 0.0 by default, which causes problems
4164      * with fixed function fragment processing. Ideally this flag should be detected with a test shader
4165      * and OpenGL feedback mode, but some GL implementations (MacOS ATI at least, probably all MacOS ones)
4166      * do not like vertex shaders in feedback mode and return an error, even though it should be valid
4167      * according to the spec.
4168      *
4169      * We don't want to enable this on all cards, as it adds an extra instruction per texcoord used. This
4170      * makes the shader slower and eats instruction slots which should be available to the d3d app.
4171      *
4172      * ATI Radeon HD 2xxx cards on MacOS have the issue. Instead of checking for the buggy cards, blacklist
4173      * all radeon cards on Macs and whitelist the good ones. That way we're prepared for the future. If
4174      * this workaround is activated on cards that do not need it, it won't break things, just affect
4175      * performance negatively.
4176      */
4177     TRACE("Enabling vertex texture coord fixes in vertex shaders\n");
4178     gl_info->set_texcoord_w = TRUE;
4179 }
4180
4181 static void quirk_clip_varying(WineD3D_GL_Info *gl_info) {
4182     gl_info->glsl_clip_varying = TRUE;
4183 }
4184
4185 struct driver_quirk quirk_table[] = {
4186     {
4187         match_ati_r300_to_500,
4188         quirk_ati_dx9,
4189         "ATI GLSL constant and normalized texrect quirk"
4190     },
4191     /* MacOS advertises more GLSL vertex shader uniforms than supported by the hardware, and if more are
4192      * used it falls back to software. While the compiler can detect if the shader uses all declared
4193      * uniforms, the optimization fails if the shader uses relative addressing. So any GLSL shader
4194      * using relative addressing falls back to software.
4195      *
4196      * ARB vp gives the correct amount of uniforms, so use it instead of GLSL
4197      */
4198     {
4199         match_apple,
4200         quirk_apple_glsl_constants,
4201         "Apple GLSL uniform override"
4202     },
4203     {
4204         match_geforce5,
4205         quirk_no_np2,
4206         "Geforce 5 NP2 disable"
4207     },
4208     {
4209         match_apple_intel,
4210         quirk_texcoord_w,
4211         "Init texcoord .w for Apple Intel GPU driver"
4212     },
4213     {
4214         match_apple_nonr500ati,
4215         quirk_texcoord_w,
4216         "Init texcoord .w for Apple ATI >= r600 GPU driver"
4217     },
4218     {
4219         match_fglrx,
4220         quirk_one_point_sprite,
4221         "Fglrx point sprite crash workaround"
4222     },
4223     {
4224         match_dx10_capable,
4225         quirk_clip_varying,
4226         "Reserved varying for gl_ClipPos"
4227     }
4228 };
4229
4230 static void fixup_extensions(WineD3D_GL_Info *gl_info) {
4231     unsigned int i;
4232
4233     for(i = 0; i < (sizeof(quirk_table) / sizeof(*quirk_table)); i++) {
4234         if(!quirk_table[i].match(gl_info)) continue;
4235         TRACE_(d3d_caps)("Applying driver quirk \"%s\"\n", quirk_table[i].description);
4236         quirk_table[i].apply(gl_info);
4237     }
4238
4239     /* Find out if PBOs work as they are supposed to */
4240     test_pbo_functionality(gl_info);
4241
4242     /* Fixup the driver version */
4243     for(i = 0; i < (sizeof(driver_version_table) / sizeof(driver_version_table[0])); i++) {
4244         if(gl_info->gl_vendor == driver_version_table[i].vendor &&
4245            gl_info->gl_card   == driver_version_table[i].card) {
4246             TRACE_(d3d_caps)("Found card 0x%04x, 0x%04x in driver version DB\n", gl_info->gl_vendor, gl_info->gl_card);
4247
4248             gl_info->driver_version        = MAKEDWORD_VERSION(driver_version_table[i].lopart_hi,
4249                                                                driver_version_table[i].lopart_lo);
4250             gl_info->driver_version_hipart = MAKEDWORD_VERSION(driver_version_table[i].hipart_hi,
4251                                                                driver_version_table[i].hipart_lo);
4252             strcpy(gl_info->driver_description, driver_version_table[i].description);
4253             break;
4254         }
4255     }
4256 }
4257
4258 static void WINE_GLAPI invalid_func(const void *data)
4259 {
4260     ERR("Invalid vertex attribute function called\n");
4261     DebugBreak();
4262 }
4263
4264 static void WINE_GLAPI invalid_texcoord_func(GLenum unit, const void *data)
4265 {
4266     ERR("Invalid texcoord function called\n");
4267     DebugBreak();
4268 }
4269
4270 /* Helper functions for providing vertex data to opengl. The arrays are initialized based on
4271  * the extension detection and are used in drawStridedSlow
4272  */
4273 static void WINE_GLAPI position_d3dcolor(const void *data)
4274 {
4275     DWORD pos = *((const DWORD *)data);
4276
4277     FIXME("Add a test for fixed function position from d3dcolor type\n");
4278     glVertex4s(D3DCOLOR_B_R(pos),
4279                D3DCOLOR_B_G(pos),
4280                D3DCOLOR_B_B(pos),
4281                D3DCOLOR_B_A(pos));
4282 }
4283
4284 static void WINE_GLAPI position_float4(const void *data)
4285 {
4286     const GLfloat *pos = data;
4287
4288     if (pos[3] < eps && pos[3] > -eps)
4289         glVertex3fv(pos);
4290     else {
4291         float w = 1.0 / pos[3];
4292
4293         glVertex4f(pos[0] * w, pos[1] * w, pos[2] * w, w);
4294     }
4295 }
4296
4297 static void WINE_GLAPI diffuse_d3dcolor(const void *data)
4298 {
4299     DWORD diffuseColor = *((const DWORD *)data);
4300
4301     glColor4ub(D3DCOLOR_B_R(diffuseColor),
4302                D3DCOLOR_B_G(diffuseColor),
4303                D3DCOLOR_B_B(diffuseColor),
4304                D3DCOLOR_B_A(diffuseColor));
4305 }
4306
4307 static void WINE_GLAPI specular_d3dcolor(const void *data)
4308 {
4309     DWORD specularColor = *((const DWORD *)data);
4310     GLbyte d[] = {D3DCOLOR_B_R(specularColor),
4311             D3DCOLOR_B_G(specularColor),
4312             D3DCOLOR_B_B(specularColor)};
4313
4314     specular_func_3ubv(d);
4315 }
4316
4317 static void WINE_GLAPI warn_no_specular_func(const void *data)
4318 {
4319     WARN("GL_EXT_secondary_color not supported\n");
4320 }
4321
4322 static void fillGLAttribFuncs(const WineD3D_GL_Info *gl_info)
4323 {
4324     position_funcs[WINED3D_FFP_EMIT_FLOAT1]      = invalid_func;
4325     position_funcs[WINED3D_FFP_EMIT_FLOAT2]      = invalid_func;
4326     position_funcs[WINED3D_FFP_EMIT_FLOAT3]      = (glAttribFunc)glVertex3fv;
4327     position_funcs[WINED3D_FFP_EMIT_FLOAT4]      = position_float4;
4328     position_funcs[WINED3D_FFP_EMIT_D3DCOLOR]    = position_d3dcolor;
4329     position_funcs[WINED3D_FFP_EMIT_UBYTE4]      = invalid_func;
4330     position_funcs[WINED3D_FFP_EMIT_SHORT2]      = invalid_func;
4331     position_funcs[WINED3D_FFP_EMIT_SHORT4]      = (glAttribFunc)glVertex2sv;
4332     position_funcs[WINED3D_FFP_EMIT_UBYTE4N]     = invalid_func;
4333     position_funcs[WINED3D_FFP_EMIT_SHORT2N]     = invalid_func;
4334     position_funcs[WINED3D_FFP_EMIT_SHORT4N]     = invalid_func;
4335     position_funcs[WINED3D_FFP_EMIT_USHORT2N]    = invalid_func;
4336     position_funcs[WINED3D_FFP_EMIT_USHORT4N]    = invalid_func;
4337     position_funcs[WINED3D_FFP_EMIT_UDEC3]       = invalid_func;
4338     position_funcs[WINED3D_FFP_EMIT_DEC3N]       = invalid_func;
4339     position_funcs[WINED3D_FFP_EMIT_FLOAT16_2]   = invalid_func;
4340     position_funcs[WINED3D_FFP_EMIT_FLOAT16_4]   = invalid_func;
4341
4342     diffuse_funcs[WINED3D_FFP_EMIT_FLOAT1]       = invalid_func;
4343     diffuse_funcs[WINED3D_FFP_EMIT_FLOAT2]       = invalid_func;
4344     diffuse_funcs[WINED3D_FFP_EMIT_FLOAT3]       = (glAttribFunc)glColor3fv;
4345     diffuse_funcs[WINED3D_FFP_EMIT_FLOAT4]       = (glAttribFunc)glColor4fv;
4346     diffuse_funcs[WINED3D_FFP_EMIT_D3DCOLOR]     = diffuse_d3dcolor;
4347     diffuse_funcs[WINED3D_FFP_EMIT_UBYTE4]       = invalid_func;
4348     diffuse_funcs[WINED3D_FFP_EMIT_SHORT2]       = invalid_func;
4349     diffuse_funcs[WINED3D_FFP_EMIT_SHORT4]       = invalid_func;
4350     diffuse_funcs[WINED3D_FFP_EMIT_UBYTE4N]      = (glAttribFunc)glColor4ubv;
4351     diffuse_funcs[WINED3D_FFP_EMIT_SHORT2N]      = invalid_func;
4352     diffuse_funcs[WINED3D_FFP_EMIT_SHORT4N]      = (glAttribFunc)glColor4sv;
4353     diffuse_funcs[WINED3D_FFP_EMIT_USHORT2N]     = invalid_func;
4354     diffuse_funcs[WINED3D_FFP_EMIT_USHORT4N]     = (glAttribFunc)glColor4usv;
4355     diffuse_funcs[WINED3D_FFP_EMIT_UDEC3]        = invalid_func;
4356     diffuse_funcs[WINED3D_FFP_EMIT_DEC3N]        = invalid_func;
4357     diffuse_funcs[WINED3D_FFP_EMIT_FLOAT16_2]    = invalid_func;
4358     diffuse_funcs[WINED3D_FFP_EMIT_FLOAT16_4]    = invalid_func;
4359
4360     /* No 4 component entry points here */
4361     specular_funcs[WINED3D_FFP_EMIT_FLOAT1]      = invalid_func;
4362     specular_funcs[WINED3D_FFP_EMIT_FLOAT2]      = invalid_func;
4363     if(GL_SUPPORT(EXT_SECONDARY_COLOR)) {
4364         specular_funcs[WINED3D_FFP_EMIT_FLOAT3]  = (glAttribFunc)GL_EXTCALL(glSecondaryColor3fvEXT);
4365     } else {
4366         specular_funcs[WINED3D_FFP_EMIT_FLOAT3]  = warn_no_specular_func;
4367     }
4368     specular_funcs[WINED3D_FFP_EMIT_FLOAT4]      = invalid_func;
4369     if(GL_SUPPORT(EXT_SECONDARY_COLOR)) {
4370         specular_func_3ubv = (glAttribFunc)GL_EXTCALL(glSecondaryColor3ubvEXT);
4371         specular_funcs[WINED3D_FFP_EMIT_D3DCOLOR] = specular_d3dcolor;
4372     } else {
4373         specular_funcs[WINED3D_FFP_EMIT_D3DCOLOR] = warn_no_specular_func;
4374     }
4375     specular_funcs[WINED3D_FFP_EMIT_UBYTE4]      = invalid_func;
4376     specular_funcs[WINED3D_FFP_EMIT_SHORT2]      = invalid_func;
4377     specular_funcs[WINED3D_FFP_EMIT_SHORT4]      = invalid_func;
4378     specular_funcs[WINED3D_FFP_EMIT_UBYTE4N]     = invalid_func;
4379     specular_funcs[WINED3D_FFP_EMIT_SHORT2N]     = invalid_func;
4380     specular_funcs[WINED3D_FFP_EMIT_SHORT4N]     = invalid_func;
4381     specular_funcs[WINED3D_FFP_EMIT_USHORT2N]    = invalid_func;
4382     specular_funcs[WINED3D_FFP_EMIT_USHORT4N]    = invalid_func;
4383     specular_funcs[WINED3D_FFP_EMIT_UDEC3]       = invalid_func;
4384     specular_funcs[WINED3D_FFP_EMIT_DEC3N]       = invalid_func;
4385     specular_funcs[WINED3D_FFP_EMIT_FLOAT16_2]   = invalid_func;
4386     specular_funcs[WINED3D_FFP_EMIT_FLOAT16_4]   = invalid_func;
4387
4388     /* Only 3 component entry points here. Test how others behave. Float4 normals are used
4389      * by one of our tests, trying to pass it to the pixel shader, which fails on Windows.
4390      */
4391     normal_funcs[WINED3D_FFP_EMIT_FLOAT1]         = invalid_func;
4392     normal_funcs[WINED3D_FFP_EMIT_FLOAT2]         = invalid_func;
4393     normal_funcs[WINED3D_FFP_EMIT_FLOAT3]         = (glAttribFunc)glNormal3fv;
4394     normal_funcs[WINED3D_FFP_EMIT_FLOAT4]         = (glAttribFunc)glNormal3fv; /* Just ignore the 4th value */
4395     normal_funcs[WINED3D_FFP_EMIT_D3DCOLOR]       = invalid_func;
4396     normal_funcs[WINED3D_FFP_EMIT_UBYTE4]         = invalid_func;
4397     normal_funcs[WINED3D_FFP_EMIT_SHORT2]         = invalid_func;
4398     normal_funcs[WINED3D_FFP_EMIT_SHORT4]         = invalid_func;
4399     normal_funcs[WINED3D_FFP_EMIT_UBYTE4N]        = invalid_func;
4400     normal_funcs[WINED3D_FFP_EMIT_SHORT2N]        = invalid_func;
4401     normal_funcs[WINED3D_FFP_EMIT_SHORT4N]        = invalid_func;
4402     normal_funcs[WINED3D_FFP_EMIT_USHORT2N]       = invalid_func;
4403     normal_funcs[WINED3D_FFP_EMIT_USHORT4N]       = invalid_func;
4404     normal_funcs[WINED3D_FFP_EMIT_UDEC3]          = invalid_func;
4405     normal_funcs[WINED3D_FFP_EMIT_DEC3N]          = invalid_func;
4406     normal_funcs[WINED3D_FFP_EMIT_FLOAT16_2]      = invalid_func;
4407     normal_funcs[WINED3D_FFP_EMIT_FLOAT16_4]      = invalid_func;
4408
4409     multi_texcoord_funcs[WINED3D_FFP_EMIT_FLOAT1]    = (glMultiTexCoordFunc)GL_EXTCALL(glMultiTexCoord1fvARB);
4410     multi_texcoord_funcs[WINED3D_FFP_EMIT_FLOAT2]    = (glMultiTexCoordFunc)GL_EXTCALL(glMultiTexCoord2fvARB);
4411     multi_texcoord_funcs[WINED3D_FFP_EMIT_FLOAT3]    = (glMultiTexCoordFunc)GL_EXTCALL(glMultiTexCoord3fvARB);
4412     multi_texcoord_funcs[WINED3D_FFP_EMIT_FLOAT4]    = (glMultiTexCoordFunc)GL_EXTCALL(glMultiTexCoord4fvARB);
4413     multi_texcoord_funcs[WINED3D_FFP_EMIT_D3DCOLOR]  = invalid_texcoord_func;
4414     multi_texcoord_funcs[WINED3D_FFP_EMIT_UBYTE4]    = invalid_texcoord_func;
4415     multi_texcoord_funcs[WINED3D_FFP_EMIT_SHORT2]    = (glMultiTexCoordFunc)GL_EXTCALL(glMultiTexCoord2svARB);
4416     multi_texcoord_funcs[WINED3D_FFP_EMIT_SHORT4]    = (glMultiTexCoordFunc)GL_EXTCALL(glMultiTexCoord4svARB);
4417     multi_texcoord_funcs[WINED3D_FFP_EMIT_UBYTE4N]   = invalid_texcoord_func;
4418     multi_texcoord_funcs[WINED3D_FFP_EMIT_SHORT2N]   = invalid_texcoord_func;
4419     multi_texcoord_funcs[WINED3D_FFP_EMIT_SHORT4N]   = invalid_texcoord_func;
4420     multi_texcoord_funcs[WINED3D_FFP_EMIT_USHORT2N]  = invalid_texcoord_func;
4421     multi_texcoord_funcs[WINED3D_FFP_EMIT_USHORT4N]  = invalid_texcoord_func;
4422     multi_texcoord_funcs[WINED3D_FFP_EMIT_UDEC3]     = invalid_texcoord_func;
4423     multi_texcoord_funcs[WINED3D_FFP_EMIT_DEC3N]     = invalid_texcoord_func;
4424     if (GL_SUPPORT(NV_HALF_FLOAT))
4425     {
4426         /* Not supported by ARB_HALF_FLOAT_VERTEX, so check for NV_HALF_FLOAT */
4427         multi_texcoord_funcs[WINED3D_FFP_EMIT_FLOAT16_2] = (glMultiTexCoordFunc)GL_EXTCALL(glMultiTexCoord2hvNV);
4428         multi_texcoord_funcs[WINED3D_FFP_EMIT_FLOAT16_4] = (glMultiTexCoordFunc)GL_EXTCALL(glMultiTexCoord4hvNV);
4429     } else {
4430         multi_texcoord_funcs[WINED3D_FFP_EMIT_FLOAT16_2] = invalid_texcoord_func;
4431         multi_texcoord_funcs[WINED3D_FFP_EMIT_FLOAT16_4] = invalid_texcoord_func;
4432     }
4433 }
4434
4435 BOOL InitAdapters(IWineD3DImpl *This)
4436 {
4437     static HMODULE mod_gl;
4438     BOOL ret;
4439     int ps_selected_mode, vs_selected_mode;
4440
4441     /* No need to hold any lock. The calling library makes sure only one thread calls
4442      * wined3d simultaneously
4443      */
4444
4445     TRACE("Initializing adapters\n");
4446
4447     if(!mod_gl) {
4448 #ifdef USE_WIN32_OPENGL
4449 #define USE_GL_FUNC(pfn) pfn = (void*)GetProcAddress(mod_gl, #pfn);
4450         mod_gl = LoadLibraryA("opengl32.dll");
4451         if(!mod_gl) {
4452             ERR("Can't load opengl32.dll!\n");
4453             goto nogl_adapter;
4454         }
4455 #else
4456 #define USE_GL_FUNC(pfn) pfn = (void*)pwglGetProcAddress(#pfn);
4457         /* To bypass the opengl32 thunks load wglGetProcAddress from gdi32 (glXGetProcAddress wrapper) instead of opengl32's */
4458         mod_gl = GetModuleHandleA("gdi32.dll");
4459 #endif
4460     }
4461
4462 /* Load WGL core functions from opengl32.dll */
4463 #define USE_WGL_FUNC(pfn) p##pfn = (void*)GetProcAddress(mod_gl, #pfn);
4464     WGL_FUNCS_GEN;
4465 #undef USE_WGL_FUNC
4466
4467     if(!pwglGetProcAddress) {
4468         ERR("Unable to load wglGetProcAddress!\n");
4469         goto nogl_adapter;
4470     }
4471
4472 /* Dynamically load all GL core functions */
4473     GL_FUNCS_GEN;
4474 #undef USE_GL_FUNC
4475
4476     /* Load glFinish and glFlush from opengl32.dll even if we're not using WIN32 opengl
4477      * otherwise because we have to use winex11.drv's override
4478      */
4479 #ifdef USE_WIN32_OPENGL
4480     glFinish = (void*)GetProcAddress(mod_gl, "glFinish");
4481     glFlush = (void*)GetProcAddress(mod_gl, "glFlush");
4482 #else
4483     glFinish = (void*)pwglGetProcAddress("wglFinish");
4484     glFlush = (void*)pwglGetProcAddress("wglFlush");
4485 #endif
4486
4487     glEnableWINE = glEnable;
4488     glDisableWINE = glDisable;
4489
4490     /* For now only one default adapter */
4491     {
4492         struct WineD3DAdapter *adapter = &This->adapters[0];
4493         const WineD3D_GL_Info *gl_info = &adapter->gl_info;
4494         int iPixelFormat;
4495         int res;
4496         int i;
4497         WineD3D_PixelFormat *cfgs;
4498         DISPLAY_DEVICEW DisplayDevice;
4499         HDC hdc;
4500
4501         TRACE("Initializing default adapter\n");
4502         adapter->num = 0;
4503         adapter->monitorPoint.x = -1;
4504         adapter->monitorPoint.y = -1;
4505
4506         if (!WineD3D_CreateFakeGLContext()) {
4507             ERR("Failed to get a gl context for default adapter\n");
4508             WineD3D_ReleaseFakeGLContext();
4509             goto nogl_adapter;
4510         }
4511
4512         ret = IWineD3DImpl_FillGLCaps(&adapter->gl_info);
4513         if(!ret) {
4514             ERR("Failed to initialize gl caps for default adapter\n");
4515             WineD3D_ReleaseFakeGLContext();
4516             goto nogl_adapter;
4517         }
4518         ret = initPixelFormats(&adapter->gl_info);
4519         if(!ret) {
4520             ERR("Failed to init gl formats\n");
4521             WineD3D_ReleaseFakeGLContext();
4522             goto nogl_adapter;
4523         }
4524
4525         hdc = pwglGetCurrentDC();
4526         if(!hdc) {
4527             ERR("Failed to get gl HDC\n");
4528             WineD3D_ReleaseFakeGLContext();
4529             goto nogl_adapter;
4530         }
4531
4532         adapter->driver = "Display";
4533         adapter->description = "Direct3D HAL";
4534
4535         /* Use the VideoRamSize registry setting when set */
4536         if(wined3d_settings.emulated_textureram)
4537             adapter->TextureRam = wined3d_settings.emulated_textureram;
4538         else
4539             adapter->TextureRam = adapter->gl_info.vidmem;
4540         adapter->UsedTextureRam = 0;
4541         TRACE("Emulating %dMB of texture ram\n", adapter->TextureRam/(1024*1024));
4542
4543         /* Initialize the Adapter's DeviceName which is required for ChangeDisplaySettings and friends */
4544         DisplayDevice.cb = sizeof(DisplayDevice);
4545         EnumDisplayDevicesW(NULL, 0 /* Adapter 0 = iDevNum 0 */, &DisplayDevice, 0);
4546         TRACE("DeviceName: %s\n", debugstr_w(DisplayDevice.DeviceName));
4547         strcpyW(adapter->DeviceName, DisplayDevice.DeviceName);
4548
4549         if(GL_SUPPORT(WGL_ARB_PIXEL_FORMAT))
4550         {
4551             int attribute;
4552             int attribs[10];
4553             int values[10];
4554             int nAttribs = 0;
4555
4556             attribute = WGL_NUMBER_PIXEL_FORMATS_ARB;
4557             GL_EXTCALL(wglGetPixelFormatAttribivARB(hdc, 0, 0, 1, &attribute, &adapter->nCfgs));
4558
4559             adapter->cfgs = HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, adapter->nCfgs *sizeof(WineD3D_PixelFormat));
4560             cfgs = adapter->cfgs;
4561             attribs[nAttribs++] = WGL_RED_BITS_ARB;
4562             attribs[nAttribs++] = WGL_GREEN_BITS_ARB;
4563             attribs[nAttribs++] = WGL_BLUE_BITS_ARB;
4564             attribs[nAttribs++] = WGL_ALPHA_BITS_ARB;
4565             attribs[nAttribs++] = WGL_DEPTH_BITS_ARB;
4566             attribs[nAttribs++] = WGL_STENCIL_BITS_ARB;
4567             attribs[nAttribs++] = WGL_DRAW_TO_WINDOW_ARB;
4568             attribs[nAttribs++] = WGL_PIXEL_TYPE_ARB;
4569             attribs[nAttribs++] = WGL_DOUBLE_BUFFER_ARB;
4570             attribs[nAttribs++] = WGL_AUX_BUFFERS_ARB;
4571
4572             for (iPixelFormat=1; iPixelFormat <= adapter->nCfgs; ++iPixelFormat)
4573             {
4574                 res = GL_EXTCALL(wglGetPixelFormatAttribivARB(hdc, iPixelFormat, 0, nAttribs, attribs, values));
4575
4576                 if(!res)
4577                     continue;
4578
4579                 /* Cache the pixel format */
4580                 cfgs->iPixelFormat = iPixelFormat;
4581                 cfgs->redSize = values[0];
4582                 cfgs->greenSize = values[1];
4583                 cfgs->blueSize = values[2];
4584                 cfgs->alphaSize = values[3];
4585                 cfgs->depthSize = values[4];
4586                 cfgs->stencilSize = values[5];
4587                 cfgs->windowDrawable = values[6];
4588                 cfgs->iPixelType = values[7];
4589                 cfgs->doubleBuffer = values[8];
4590                 cfgs->auxBuffers = values[9];
4591
4592                 cfgs->pbufferDrawable = FALSE;
4593                 /* Check for pbuffer support when it is around as wglGetPixelFormatAttribiv fails for unknown attributes. */
4594                 if(GL_SUPPORT(WGL_ARB_PBUFFER)) {
4595                     int attrib = WGL_DRAW_TO_PBUFFER_ARB;
4596                     int value;
4597                     if(GL_EXTCALL(wglGetPixelFormatAttribivARB(hdc, iPixelFormat, 0, 1, &attrib, &value)))
4598                         cfgs->pbufferDrawable = value;
4599                 }
4600
4601                 cfgs->numSamples = 0;
4602                 /* Check multisample support */
4603                 if(GL_SUPPORT(ARB_MULTISAMPLE)) {
4604                     int attrib[2] = {WGL_SAMPLE_BUFFERS_ARB, WGL_SAMPLES_ARB};
4605                     int value[2];
4606                     if(GL_EXTCALL(wglGetPixelFormatAttribivARB(hdc, iPixelFormat, 0, 2, attrib, value))) {
4607                         /* value[0] = WGL_SAMPLE_BUFFERS_ARB which tells whether multisampling is supported.
4608                         * value[1] = number of multi sample buffers*/
4609                         if(value[0])
4610                             cfgs->numSamples = value[1];
4611                     }
4612                 }
4613
4614                 TRACE("iPixelFormat=%d, iPixelType=%#x, doubleBuffer=%d, RGBA=%d/%d/%d/%d, depth=%d, stencil=%d, windowDrawable=%d, pbufferDrawable=%d\n", cfgs->iPixelFormat, cfgs->iPixelType, cfgs->doubleBuffer, cfgs->redSize, cfgs->greenSize, cfgs->blueSize, cfgs->alphaSize, cfgs->depthSize, cfgs->stencilSize, cfgs->windowDrawable, cfgs->pbufferDrawable);
4615                 cfgs++;
4616             }
4617         }
4618         else
4619         {
4620             int nCfgs = DescribePixelFormat(hdc, 0, 0, 0);
4621             adapter->cfgs = HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, nCfgs*sizeof(WineD3D_PixelFormat));
4622             adapter->nCfgs = 0; /* We won't accept all formats e.g. software accelerated ones will be skipped */
4623
4624             cfgs = adapter->cfgs;
4625             for(iPixelFormat=1; iPixelFormat<=nCfgs; iPixelFormat++)
4626             {
4627                 PIXELFORMATDESCRIPTOR ppfd;
4628
4629                 res = DescribePixelFormat(hdc, iPixelFormat, sizeof(PIXELFORMATDESCRIPTOR), &ppfd);
4630                 if(!res)
4631                     continue;
4632
4633                 /* We only want HW acceleration using an OpenGL ICD driver.
4634                  * PFD_GENERIC_FORMAT = slow opengl 1.1 gdi software rendering
4635                  * PFD_GENERIC_ACCELERATED = partial hw acceleration using a MCD driver (e.g. 3dfx minigl)
4636                  */
4637                 if(ppfd.dwFlags & (PFD_GENERIC_FORMAT | PFD_GENERIC_ACCELERATED))
4638                 {
4639                     TRACE("Skipping iPixelFormat=%d because it isn't ICD accelerated\n", iPixelFormat);
4640                     continue;
4641                 }
4642
4643                 cfgs->iPixelFormat = iPixelFormat;
4644                 cfgs->redSize = ppfd.cRedBits;
4645                 cfgs->greenSize = ppfd.cGreenBits;
4646                 cfgs->blueSize = ppfd.cBlueBits;
4647                 cfgs->alphaSize = ppfd.cAlphaBits;
4648                 cfgs->depthSize = ppfd.cDepthBits;
4649                 cfgs->stencilSize = ppfd.cStencilBits;
4650                 cfgs->pbufferDrawable = 0;
4651                 cfgs->windowDrawable = (ppfd.dwFlags & PFD_DRAW_TO_WINDOW) ? 1 : 0;
4652                 cfgs->iPixelType = (ppfd.iPixelType == PFD_TYPE_RGBA) ? WGL_TYPE_RGBA_ARB : WGL_TYPE_COLORINDEX_ARB;
4653                 cfgs->doubleBuffer = (ppfd.dwFlags & PFD_DOUBLEBUFFER) ? 1 : 0;
4654                 cfgs->auxBuffers = ppfd.cAuxBuffers;
4655                 cfgs->numSamples = 0;
4656
4657                 TRACE("iPixelFormat=%d, iPixelType=%#x, doubleBuffer=%d, RGBA=%d/%d/%d/%d, depth=%d, stencil=%d, windowDrawable=%d, pbufferDrawable=%d\n", cfgs->iPixelFormat, cfgs->iPixelType, cfgs->doubleBuffer, cfgs->redSize, cfgs->greenSize, cfgs->blueSize, cfgs->alphaSize, cfgs->depthSize, cfgs->stencilSize, cfgs->windowDrawable, cfgs->pbufferDrawable);
4658                 cfgs++;
4659                 adapter->nCfgs++;
4660             }
4661
4662             /* Yikes we haven't found any suitable formats. This should only happen in case of GDI software rendering which we can't use anyway as its 3D functionality is very, very limited */
4663             if(!adapter->nCfgs)
4664             {
4665                 ERR("Disabling Direct3D because no hardware accelerated pixel formats have been found!\n");
4666
4667                 WineD3D_ReleaseFakeGLContext();
4668                 HeapFree(GetProcessHeap(), 0, adapter->cfgs);
4669                 goto nogl_adapter;
4670             }
4671         }
4672
4673         /* D16, D24X8 and D24S8 are common depth / depth+stencil formats. All drivers support them though this doesn't
4674          * mean that the format is offered in hardware. For instance Geforce8 cards don't have offer D16 in hardware
4675          * but just fake it using D24(X8?) which is fine. D3D also allows that.
4676          * Some display drivers (i915 on Linux) only report mixed depth+stencil formats like D24S8. MSDN clearly mentions
4677          * that only on lockable formats (e.g. D16_locked) the bit order is guaranteed and that on other formats the
4678          * driver is allowed to consume more bits EXCEPT for stencil bits.
4679          *
4680          * Mark an adapter with this broken stencil behavior.
4681          */
4682         adapter->brokenStencil = TRUE;
4683         for (i = 0, cfgs = adapter->cfgs; i < adapter->nCfgs; ++i)
4684         {
4685             /* Nearly all drivers offer depth formats without stencil, only on i915 this if-statement won't be entered. */
4686             if(cfgs[i].depthSize && !cfgs[i].stencilSize) {
4687                 adapter->brokenStencil = FALSE;
4688                 break;
4689             }
4690         }
4691
4692         fixup_extensions(&adapter->gl_info);
4693         add_gl_compat_wrappers(&adapter->gl_info);
4694
4695         WineD3D_ReleaseFakeGLContext();
4696
4697         select_shader_mode(&adapter->gl_info, WINED3DDEVTYPE_HAL, &ps_selected_mode, &vs_selected_mode);
4698         select_shader_max_constants(ps_selected_mode, vs_selected_mode, &adapter->gl_info);
4699         fillGLAttribFuncs(&adapter->gl_info);
4700         adapter->opengl = TRUE;
4701     }
4702     This->adapter_count = 1;
4703     TRACE("%u adapters successfully initialized\n", This->adapter_count);
4704
4705     return TRUE;
4706
4707 nogl_adapter:
4708     /* Initialize an adapter for ddraw-only memory counting */
4709     memset(This->adapters, 0, sizeof(This->adapters));
4710     This->adapters[0].num = 0;
4711     This->adapters[0].opengl = FALSE;
4712     This->adapters[0].monitorPoint.x = -1;
4713     This->adapters[0].monitorPoint.y = -1;
4714
4715     This->adapters[0].driver = "Display";
4716     This->adapters[0].description = "WineD3D DirectDraw Emulation";
4717     if(wined3d_settings.emulated_textureram) {
4718         This->adapters[0].TextureRam = wined3d_settings.emulated_textureram;
4719     } else {
4720         This->adapters[0].TextureRam = 8 * 1024 * 1024; /* This is plenty for a DDraw-only card */
4721     }
4722
4723     initPixelFormatsNoGL(&This->adapters[0].gl_info);
4724
4725     This->adapter_count = 1;
4726     return FALSE;
4727 }
4728
4729 /**********************************************************
4730  * IWineD3D VTbl follows
4731  **********************************************************/
4732
4733 const IWineD3DVtbl IWineD3D_Vtbl =
4734 {
4735     /* IUnknown */
4736     IWineD3DImpl_QueryInterface,
4737     IWineD3DImpl_AddRef,
4738     IWineD3DImpl_Release,
4739     /* IWineD3D */
4740     IWineD3DImpl_GetParent,
4741     IWineD3DImpl_GetAdapterCount,
4742     IWineD3DImpl_RegisterSoftwareDevice,
4743     IWineD3DImpl_GetAdapterMonitor,
4744     IWineD3DImpl_GetAdapterModeCount,
4745     IWineD3DImpl_EnumAdapterModes,
4746     IWineD3DImpl_GetAdapterDisplayMode,
4747     IWineD3DImpl_GetAdapterIdentifier,
4748     IWineD3DImpl_CheckDeviceMultiSampleType,
4749     IWineD3DImpl_CheckDepthStencilMatch,
4750     IWineD3DImpl_CheckDeviceType,
4751     IWineD3DImpl_CheckDeviceFormat,
4752     IWineD3DImpl_CheckDeviceFormatConversion,
4753     IWineD3DImpl_GetDeviceCaps,
4754     IWineD3DImpl_CreateDevice
4755 };