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