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