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