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