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