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