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