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