ddraw: Failing surface creation is not an internal error.
[wine] / dlls / ddraw / ddraw.c
1 /*
2  * Copyright 1997-2000 Marcus Meissner
3  * Copyright 1998-2000 Lionel Ulmer
4  * Copyright 2000-2001 TransGaming Technologies Inc.
5  * Copyright 2006 Stefan Dösinger
6  * Copyright 2008 Denver Gingerich
7  *
8  * This library is free software; you can redistribute it and/or
9  * modify it under the terms of the GNU Lesser General Public
10  * License as published by the Free Software Foundation; either
11  * version 2.1 of the License, or (at your option) any later version.
12  *
13  * This library is distributed in the hope that it will be useful,
14  * but WITHOUT ANY WARRANTY; without even the implied warranty of
15  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
16  * Lesser General Public License for more details.
17  *
18  * You should have received a copy of the GNU Lesser General Public
19  * License along with this library; if not, write to the Free Software
20  * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA
21  */
22
23 #include "config.h"
24 #include "wine/port.h"
25
26 #include "ddraw_private.h"
27
28 WINE_DEFAULT_DEBUG_CHANNEL(ddraw);
29
30 /* Device identifier. Don't relay it to WineD3D */
31 static const DDDEVICEIDENTIFIER2 deviceidentifier =
32 {
33     "display",
34     "DirectDraw HAL",
35     { { 0x00010001, 0x00010001 } },
36     0, 0, 0, 0,
37     /* a8373c10-7ac4-4deb-849a-009844d08b2d */
38     {0xa8373c10,0x7ac4,0x4deb, {0x84,0x9a,0x00,0x98,0x44,0xd0,0x8b,0x2d}},
39     0
40 };
41
42 static void STDMETHODCALLTYPE ddraw_null_wined3d_object_destroyed(void *parent) {}
43
44 const struct wined3d_parent_ops ddraw_null_wined3d_parent_ops =
45 {
46     ddraw_null_wined3d_object_destroyed,
47 };
48
49 static inline IDirectDrawImpl *ddraw_from_ddraw1(IDirectDraw *iface)
50 {
51     return (IDirectDrawImpl *)((char*)iface - FIELD_OFFSET(IDirectDrawImpl, IDirectDraw_vtbl));
52 }
53
54 static inline IDirectDrawImpl *ddraw_from_ddraw2(IDirectDraw2 *iface)
55 {
56     return (IDirectDrawImpl *)((char*)iface - FIELD_OFFSET(IDirectDrawImpl, IDirectDraw2_vtbl));
57 }
58
59 static inline IDirectDrawImpl *ddraw_from_ddraw3(IDirectDraw3 *iface)
60 {
61     return (IDirectDrawImpl *)((char*)iface - FIELD_OFFSET(IDirectDrawImpl, IDirectDraw3_vtbl));
62 }
63
64 static inline IDirectDrawImpl *ddraw_from_ddraw4(IDirectDraw4 *iface)
65 {
66     return (IDirectDrawImpl *)((char*)iface - FIELD_OFFSET(IDirectDrawImpl, IDirectDraw4_vtbl));
67 }
68
69 /*****************************************************************************
70  * IUnknown Methods
71  *****************************************************************************/
72
73 /*****************************************************************************
74  * IDirectDraw7::QueryInterface
75  *
76  * Queries different interfaces of the DirectDraw object. It can return
77  * IDirectDraw interfaces in version 1, 2, 4 and 7, and IDirect3D interfaces
78  * in version 1, 2, 3 and 7. An IDirect3DDevice can be created with this
79  * method.
80  * The returned interface is AddRef()-ed before it's returned
81  *
82  * Used for version 1, 2, 4 and 7
83  *
84  * Params:
85  *  refiid: Interface ID asked for
86  *  obj: Used to return the interface pointer
87  *
88  * Returns:
89  *  S_OK if an interface was found
90  *  E_NOINTERFACE if the requested interface wasn't found
91  *
92  *****************************************************************************/
93 static HRESULT WINAPI ddraw7_QueryInterface(IDirectDraw7 *iface, REFIID refiid, void **obj)
94 {
95     IDirectDrawImpl *This = (IDirectDrawImpl *)iface;
96
97     TRACE("iface %p, riid %s, object %p.\n", iface, debugstr_guid(refiid), obj);
98
99     /* Can change surface impl type */
100     EnterCriticalSection(&ddraw_cs);
101
102     /* According to COM docs, if the QueryInterface fails, obj should be set to NULL */
103     *obj = NULL;
104
105     if(!refiid)
106     {
107         LeaveCriticalSection(&ddraw_cs);
108         return DDERR_INVALIDPARAMS;
109     }
110
111     /* Check DirectDraw Interfaces */
112     if ( IsEqualGUID( &IID_IUnknown, refiid ) ||
113          IsEqualGUID( &IID_IDirectDraw7, refiid ) )
114     {
115         *obj = This;
116         TRACE("(%p) Returning IDirectDraw7 interface at %p\n", This, *obj);
117     }
118     else if ( IsEqualGUID( &IID_IDirectDraw4, refiid ) )
119     {
120         *obj = &This->IDirectDraw4_vtbl;
121         TRACE("(%p) Returning IDirectDraw4 interface at %p\n", This, *obj);
122     }
123     else if ( IsEqualGUID( &IID_IDirectDraw3, refiid ) )
124     {
125         /* This Interface exists in ddrawex.dll, it is implemented in a wrapper */
126         WARN("IDirectDraw3 is not valid in ddraw.dll\n");
127         *obj = NULL;
128         LeaveCriticalSection(&ddraw_cs);
129         return E_NOINTERFACE;
130     }
131     else if ( IsEqualGUID( &IID_IDirectDraw2, refiid ) )
132     {
133         *obj = &This->IDirectDraw2_vtbl;
134         TRACE("(%p) Returning IDirectDraw2 interface at %p\n", This, *obj);
135     }
136     else if ( IsEqualGUID( &IID_IDirectDraw, refiid ) )
137     {
138         *obj = &This->IDirectDraw_vtbl;
139         TRACE("(%p) Returning IDirectDraw interface at %p\n", This, *obj);
140     }
141
142     /* Direct3D
143      * The refcount unit test revealed that an IDirect3D7 interface can only be queried
144      * from a DirectDraw object that was created as an IDirectDraw7 interface. No idea
145      * who had this idea and why. The older interfaces can query and IDirect3D version
146      * because they are all created as IDirectDraw(1). This isn't really crucial behavior,
147      * and messy to implement with the common creation function, so it has been left out here.
148      */
149     else if ( IsEqualGUID( &IID_IDirect3D  , refiid ) ||
150               IsEqualGUID( &IID_IDirect3D2 , refiid ) ||
151               IsEqualGUID( &IID_IDirect3D3 , refiid ) ||
152               IsEqualGUID( &IID_IDirect3D7 , refiid ) )
153     {
154         /* Check the surface implementation */
155         if(This->ImplType == SURFACE_UNKNOWN)
156         {
157             /* Apps may create the IDirect3D Interface before the primary surface.
158              * set the surface implementation */
159             This->ImplType = SURFACE_OPENGL;
160             TRACE("(%p) Choosing OpenGL surfaces because a Direct3D interface was requested\n", This);
161         }
162         else if(This->ImplType != SURFACE_OPENGL && DefaultSurfaceType == SURFACE_UNKNOWN)
163         {
164             ERR("(%p) The App is requesting a D3D device, but a non-OpenGL surface type was choosen. Prepare for trouble!\n", This);
165             ERR(" (%p) You may want to contact wine-devel for help\n", This);
166             /* Should I assert(0) here??? */
167         }
168         else if(This->ImplType != SURFACE_OPENGL)
169         {
170             WARN("The app requests a Direct3D interface, but non-opengl surfaces where set in winecfg\n");
171             /* Do not abort here, only reject 3D Device creation */
172         }
173
174         if ( IsEqualGUID( &IID_IDirect3D  , refiid ) )
175         {
176             This->d3dversion = 1;
177             *obj = &This->IDirect3D_vtbl;
178             TRACE(" returning Direct3D interface at %p.\n", *obj);
179         }
180         else if ( IsEqualGUID( &IID_IDirect3D2  , refiid ) )
181         {
182             This->d3dversion = 2;
183             *obj = &This->IDirect3D2_vtbl;
184             TRACE(" returning Direct3D2 interface at %p.\n", *obj);
185         }
186         else if ( IsEqualGUID( &IID_IDirect3D3  , refiid ) )
187         {
188             This->d3dversion = 3;
189             *obj = &This->IDirect3D3_vtbl;
190             TRACE(" returning Direct3D3 interface at %p.\n", *obj);
191         }
192         else if(IsEqualGUID( &IID_IDirect3D7  , refiid ))
193         {
194             This->d3dversion = 7;
195             *obj = &This->IDirect3D7_vtbl;
196             TRACE(" returning Direct3D7 interface at %p.\n", *obj);
197         }
198     }
199     else if (IsEqualGUID(refiid, &IID_IWineD3DDeviceParent))
200     {
201         *obj = &This->device_parent_vtbl;
202     }
203
204     /* Unknown interface */
205     else
206     {
207         ERR("(%p)->(%s, %p): No interface found\n", This, debugstr_guid(refiid), obj);
208         LeaveCriticalSection(&ddraw_cs);
209         return E_NOINTERFACE;
210     }
211
212     IUnknown_AddRef( (IUnknown *) *obj );
213     LeaveCriticalSection(&ddraw_cs);
214     return S_OK;
215 }
216
217 static HRESULT WINAPI ddraw4_QueryInterface(IDirectDraw4 *iface, REFIID riid, void **object)
218 {
219     TRACE("iface %p, riid %s, object %p.\n", iface, debugstr_guid(riid), object);
220
221     return ddraw7_QueryInterface((IDirectDraw7 *)ddraw_from_ddraw4(iface), riid, object);
222 }
223
224 static HRESULT WINAPI ddraw3_QueryInterface(IDirectDraw3 *iface, REFIID riid, void **object)
225 {
226     TRACE("iface %p, riid %s, object %p.\n", iface, debugstr_guid(riid), object);
227
228     return ddraw7_QueryInterface((IDirectDraw7 *)ddraw_from_ddraw3(iface), riid, object);
229 }
230
231 static HRESULT WINAPI ddraw2_QueryInterface(IDirectDraw2 *iface, REFIID riid, void **object)
232 {
233     TRACE("iface %p, riid %s, object %p.\n", iface, debugstr_guid(riid), object);
234
235     return ddraw7_QueryInterface((IDirectDraw7 *)ddraw_from_ddraw2(iface), riid, object);
236 }
237
238 static HRESULT WINAPI ddraw1_QueryInterface(IDirectDraw *iface, REFIID riid, void **object)
239 {
240     TRACE("iface %p, riid %s, object %p.\n", iface, debugstr_guid(riid), object);
241
242     return ddraw7_QueryInterface((IDirectDraw7 *)ddraw_from_ddraw1(iface), riid, object);
243 }
244
245 static HRESULT WINAPI d3d7_QueryInterface(IDirect3D7 *iface, REFIID riid, void **object)
246 {
247     TRACE("iface %p, riid %s, object %p.\n", iface, debugstr_guid(riid), object);
248
249     return ddraw7_QueryInterface((IDirectDraw7 *)ddraw_from_d3d7(iface), riid, object);
250 }
251
252 static HRESULT WINAPI d3d3_QueryInterface(IDirect3D3 *iface, REFIID riid, void **object)
253 {
254     TRACE("iface %p, riid %s, object %p.\n", iface, debugstr_guid(riid), object);
255
256     return ddraw7_QueryInterface((IDirectDraw7 *)ddraw_from_d3d3(iface), riid, object);
257 }
258
259 static HRESULT WINAPI d3d2_QueryInterface(IDirect3D2 *iface, REFIID riid, void **object)
260 {
261     TRACE("iface %p, riid %s, object %p.\n", iface, debugstr_guid(riid), object);
262
263     return ddraw7_QueryInterface((IDirectDraw7 *)ddraw_from_d3d2(iface), riid, object);
264 }
265
266 static HRESULT WINAPI d3d1_QueryInterface(IDirect3D *iface, REFIID riid, void **object)
267 {
268     TRACE("iface %p, riid %s, object %p.\n", iface, debugstr_guid(riid), object);
269
270     return ddraw7_QueryInterface((IDirectDraw7 *)ddraw_from_d3d1(iface), riid, object);
271 }
272
273 /*****************************************************************************
274  * IDirectDraw7::AddRef
275  *
276  * Increases the interfaces refcount, basically
277  *
278  * DDraw refcounting is a bit tricky. The different DirectDraw interface
279  * versions have individual refcounts, but the IDirect3D interfaces do not.
280  * All interfaces are from one object, that means calling QueryInterface on an
281  * IDirectDraw7 interface for an IDirectDraw4 interface does not create a new
282  * IDirectDrawImpl object.
283  *
284  * That means all AddRef and Release implementations of IDirectDrawX work
285  * with their own counter, and IDirect3DX::AddRef thunk to IDirectDraw (1),
286  * except of IDirect3D7 which thunks to IDirectDraw7
287  *
288  * Returns: The new refcount
289  *
290  *****************************************************************************/
291 static ULONG WINAPI ddraw7_AddRef(IDirectDraw7 *iface)
292 {
293     IDirectDrawImpl *This = (IDirectDrawImpl *)iface;
294     ULONG ref = InterlockedIncrement(&This->ref7);
295
296     TRACE("%p increasing refcount to %u.\n", This, ref);
297
298     if(ref == 1) InterlockedIncrement(&This->numIfaces);
299
300     return ref;
301 }
302
303 static ULONG WINAPI ddraw4_AddRef(IDirectDraw4 *iface)
304 {
305     IDirectDrawImpl *ddraw = ddraw_from_ddraw4(iface);
306     ULONG ref = InterlockedIncrement(&ddraw->ref4);
307
308     TRACE("%p increasing refcount to %u.\n", ddraw, ref);
309
310     if (ref == 1) InterlockedIncrement(&ddraw->numIfaces);
311
312     return ref;
313 }
314
315 static ULONG WINAPI ddraw3_AddRef(IDirectDraw3 *iface)
316 {
317     IDirectDrawImpl *ddraw = ddraw_from_ddraw3(iface);
318     ULONG ref = InterlockedIncrement(&ddraw->ref3);
319
320     TRACE("%p increasing refcount to %u.\n", ddraw, ref);
321
322     if (ref == 1) InterlockedIncrement(&ddraw->numIfaces);
323
324     return ref;
325 }
326
327 static ULONG WINAPI ddraw2_AddRef(IDirectDraw2 *iface)
328 {
329     IDirectDrawImpl *ddraw = ddraw_from_ddraw2(iface);
330     ULONG ref = InterlockedIncrement(&ddraw->ref2);
331
332     TRACE("%p increasing refcount to %u.\n", ddraw, ref);
333
334     if (ref == 1) InterlockedIncrement(&ddraw->numIfaces);
335
336     return ref;
337 }
338
339 static ULONG WINAPI ddraw1_AddRef(IDirectDraw *iface)
340 {
341     IDirectDrawImpl *ddraw = ddraw_from_ddraw1(iface);
342     ULONG ref = InterlockedIncrement(&ddraw->ref1);
343
344     TRACE("%p increasing refcount to %u.\n", ddraw, ref);
345
346     if (ref == 1) InterlockedIncrement(&ddraw->numIfaces);
347
348     return ref;
349 }
350
351 static ULONG WINAPI d3d7_AddRef(IDirect3D7 *iface)
352 {
353     TRACE("iface %p.\n", iface);
354
355     return ddraw7_AddRef((IDirectDraw7 *)ddraw_from_d3d7(iface));
356 }
357
358 static ULONG WINAPI d3d3_AddRef(IDirect3D3 *iface)
359 {
360     TRACE("iface %p.\n", iface);
361
362     return ddraw1_AddRef((IDirectDraw *)&ddraw_from_d3d3(iface)->IDirectDraw_vtbl);
363 }
364
365 static ULONG WINAPI d3d2_AddRef(IDirect3D2 *iface)
366 {
367     TRACE("iface %p.\n", iface);
368
369     return ddraw1_AddRef((IDirectDraw *)&ddraw_from_d3d2(iface)->IDirectDraw_vtbl);
370 }
371
372 static ULONG WINAPI d3d1_AddRef(IDirect3D *iface)
373 {
374     TRACE("iface %p.\n", iface);
375
376     return ddraw1_AddRef((IDirectDraw *)&ddraw_from_d3d1(iface)->IDirectDraw_vtbl);
377 }
378
379 /*****************************************************************************
380  * ddraw_destroy
381  *
382  * Destroys a ddraw object if all refcounts are 0. This is to share code
383  * between the IDirectDrawX::Release functions
384  *
385  * Params:
386  *  This: DirectDraw object to destroy
387  *
388  *****************************************************************************/
389 static void ddraw_destroy(IDirectDrawImpl *This)
390 {
391     IDirectDraw7_SetCooperativeLevel((IDirectDraw7 *)This, NULL, DDSCL_NORMAL);
392     IDirectDraw7_RestoreDisplayMode((IDirectDraw7 *)This);
393
394     /* Destroy the device window if we created one */
395     if(This->devicewindow != 0)
396     {
397         TRACE(" (%p) Destroying the device window %p\n", This, This->devicewindow);
398         DestroyWindow(This->devicewindow);
399         This->devicewindow = 0;
400     }
401
402     EnterCriticalSection(&ddraw_cs);
403     list_remove(&This->ddraw_list_entry);
404     LeaveCriticalSection(&ddraw_cs);
405
406     /* Release the attached WineD3D stuff */
407     IWineD3DDevice_Release(This->wineD3DDevice);
408     IWineD3D_Release(This->wineD3D);
409
410     /* Now free the object */
411     HeapFree(GetProcessHeap(), 0, This);
412 }
413
414 /*****************************************************************************
415  * IDirectDraw7::Release
416  *
417  * Decreases the refcount. If the refcount falls to 0, the object is destroyed
418  *
419  * Returns: The new refcount
420  *****************************************************************************/
421 static ULONG WINAPI ddraw7_Release(IDirectDraw7 *iface)
422 {
423     IDirectDrawImpl *This = (IDirectDrawImpl *)iface;
424     ULONG ref = InterlockedDecrement(&This->ref7);
425
426     TRACE("%p decreasing refcount to %u.\n", This, ref);
427
428     if (!ref && !InterlockedDecrement(&This->numIfaces))
429         ddraw_destroy(This);
430
431     return ref;
432 }
433
434 static ULONG WINAPI ddraw4_Release(IDirectDraw4 *iface)
435 {
436     IDirectDrawImpl *ddraw = ddraw_from_ddraw4(iface);
437     ULONG ref = InterlockedDecrement(&ddraw->ref4);
438
439     TRACE("%p decreasing refcount to %u.\n", ddraw, ref);
440
441     if (!ref && !InterlockedDecrement(&ddraw->numIfaces))
442         ddraw_destroy(ddraw);
443
444     return ref;
445 }
446
447 static ULONG WINAPI ddraw3_Release(IDirectDraw3 *iface)
448 {
449     IDirectDrawImpl *ddraw = ddraw_from_ddraw3(iface);
450     ULONG ref = InterlockedDecrement(&ddraw->ref3);
451
452     TRACE("%p decreasing refcount to %u.\n", ddraw, ref);
453
454     if (!ref && !InterlockedDecrement(&ddraw->numIfaces))
455         ddraw_destroy(ddraw);
456
457     return ref;
458 }
459
460 static ULONG WINAPI ddraw2_Release(IDirectDraw2 *iface)
461 {
462     IDirectDrawImpl *ddraw = ddraw_from_ddraw2(iface);
463     ULONG ref = InterlockedDecrement(&ddraw->ref2);
464
465     TRACE("%p decreasing refcount to %u.\n", ddraw, ref);
466
467     if (!ref && !InterlockedDecrement(&ddraw->numIfaces))
468         ddraw_destroy(ddraw);
469
470     return ref;
471 }
472
473 static ULONG WINAPI ddraw1_Release(IDirectDraw *iface)
474 {
475     IDirectDrawImpl *ddraw = ddraw_from_ddraw1(iface);
476     ULONG ref = InterlockedDecrement(&ddraw->ref1);
477
478     TRACE("%p decreasing refcount to %u.\n", ddraw, ref);
479
480     if (!ref && !InterlockedDecrement(&ddraw->numIfaces))
481         ddraw_destroy(ddraw);
482
483     return ref;
484 }
485
486 static ULONG WINAPI d3d7_Release(IDirect3D7 *iface)
487 {
488     TRACE("iface %p.\n", iface);
489
490     return ddraw7_Release((IDirectDraw7 *)ddraw_from_d3d7(iface));
491 }
492
493 static ULONG WINAPI d3d3_Release(IDirect3D3 *iface)
494 {
495     TRACE("iface %p.\n", iface);
496
497     return ddraw1_Release((IDirectDraw *)&ddraw_from_d3d3(iface)->IDirectDraw_vtbl);
498 }
499
500 static ULONG WINAPI d3d2_Release(IDirect3D2 *iface)
501 {
502     TRACE("iface %p.\n", iface);
503
504     return ddraw1_Release((IDirectDraw *)&ddraw_from_d3d2(iface)->IDirectDraw_vtbl);
505 }
506
507 static ULONG WINAPI d3d1_Release(IDirect3D *iface)
508 {
509     TRACE("iface %p.\n", iface);
510
511     return ddraw1_Release((IDirectDraw *)&ddraw_from_d3d1(iface)->IDirectDraw_vtbl);
512 }
513
514 /*****************************************************************************
515  * IDirectDraw methods
516  *****************************************************************************/
517
518 /*****************************************************************************
519  * IDirectDraw7::SetCooperativeLevel
520  *
521  * Sets the cooperative level for the DirectDraw object, and the window
522  * assigned to it. The cooperative level determines the general behavior
523  * of the DirectDraw application
524  *
525  * Warning: This is quite tricky, as it's not really documented which
526  * cooperative levels can be combined with each other. If a game fails
527  * after this function, try to check the cooperative levels passed on
528  * Windows, and if it returns something different.
529  *
530  * If you think that this function caused the failure because it writes a
531  * fixme, be sure to run again with a +ddraw trace.
532  *
533  * What is known about cooperative levels (See the ddraw modes test):
534  * DDSCL_EXCLUSIVE and DDSCL_FULLSCREEN must be used with each other
535  * DDSCL_NORMAL is not compatible with DDSCL_EXCLUSIVE or DDSCL_FULLSCREEN
536  * DDSCL_SETFOCUSWINDOW can be passed only in DDSCL_NORMAL mode, but after that
537  * DDSCL_FULLSCREEN can be activated
538  * DDSCL_SETFOCUSWINDOW may only be used with DDSCL_NOWINDOWCHANGES
539  *
540  * Handled flags: DDSCL_NORMAL, DDSCL_FULLSCREEN, DDSCL_EXCLUSIVE,
541  *                DDSCL_SETFOCUSWINDOW (partially),
542  *                DDSCL_MULTITHREADED (work in progress)
543  *
544  * Unhandled flags, which should be implemented
545  *  DDSCL_SETDEVICEWINDOW: Sets a window specially used for rendering (I don't
546  *  expect any difference to a normal window for wine)
547  *  DDSCL_CREATEDEVICEWINDOW: Tells ddraw to create its own window for
548  *  rendering (Possible test case: Half-Life)
549  *
550  * Unsure about these: DDSCL_FPUSETUP DDSCL_FPURESERVE
551  *
552  * These don't seem very important for wine:
553  *  DDSCL_ALLOWREBOOT, DDSCL_NOWINDOWCHANGES, DDSCL_ALLOWMODEX
554  *
555  * Returns:
556  *  DD_OK if the cooperative level was set successfully
557  *  DDERR_INVALIDPARAMS if the passed cooperative level combination is invalid
558  *  DDERR_HWNDALREADYSET if DDSCL_SETFOCUSWINDOW is passed in exclusive mode
559  *   (Probably others too, have to investigate)
560  *
561  *****************************************************************************/
562 static HRESULT WINAPI ddraw7_SetCooperativeLevel(IDirectDraw7 *iface, HWND hwnd, DWORD cooplevel)
563 {
564     IDirectDrawImpl *This = (IDirectDrawImpl *)iface;
565     HWND window;
566
567     TRACE("iface %p, window %p, flags %#x.\n", iface, hwnd, cooplevel);
568     DDRAW_dump_cooperativelevel(cooplevel);
569
570     EnterCriticalSection(&ddraw_cs);
571
572     /* Get the old window */
573     window = This->dest_window;
574
575     /* Tests suggest that we need one of them: */
576     if(!(cooplevel & (DDSCL_SETFOCUSWINDOW |
577                       DDSCL_NORMAL         |
578                       DDSCL_EXCLUSIVE      )))
579     {
580         TRACE("Incorrect cooplevel flags, returning DDERR_INVALIDPARAMS\n");
581         LeaveCriticalSection(&ddraw_cs);
582         return DDERR_INVALIDPARAMS;
583     }
584
585     /* Handle those levels first which set various hwnds */
586     if(cooplevel & DDSCL_SETFOCUSWINDOW)
587     {
588         /* This isn't compatible with a lot of flags */
589         if(cooplevel & ( DDSCL_MULTITHREADED   |
590                          DDSCL_FPUSETUP        |
591                          DDSCL_FPUPRESERVE     |
592                          DDSCL_ALLOWREBOOT     |
593                          DDSCL_ALLOWMODEX      |
594                          DDSCL_SETDEVICEWINDOW |
595                          DDSCL_NORMAL          |
596                          DDSCL_EXCLUSIVE       |
597                          DDSCL_FULLSCREEN      ) )
598         {
599             TRACE("Called with incompatible flags, returning DDERR_INVALIDPARAMS\n");
600             LeaveCriticalSection(&ddraw_cs);
601             return DDERR_INVALIDPARAMS;
602         }
603         else if( (This->cooperative_level & DDSCL_FULLSCREEN) && window)
604         {
605             TRACE("Setting DDSCL_SETFOCUSWINDOW with an already set window, returning DDERR_HWNDALREADYSET\n");
606             LeaveCriticalSection(&ddraw_cs);
607             return DDERR_HWNDALREADYSET;
608         }
609
610         This->focuswindow = hwnd;
611         /* Won't use the hwnd param for anything else */
612         hwnd = NULL;
613
614         /* Use the focus window for drawing too */
615         This->dest_window = This->focuswindow;
616
617         /* Destroy the device window, if we have one */
618         if(This->devicewindow)
619         {
620             DestroyWindow(This->devicewindow);
621             This->devicewindow = NULL;
622         }
623     }
624     /* DDSCL_NORMAL or DDSCL_FULLSCREEN | DDSCL_EXCLUSIVE */
625     if(cooplevel & DDSCL_NORMAL)
626     {
627         /* Can't coexist with fullscreen or exclusive */
628         if(cooplevel & (DDSCL_FULLSCREEN | DDSCL_EXCLUSIVE) )
629         {
630             TRACE("(%p) DDSCL_NORMAL is not compative with DDSCL_FULLSCREEN or DDSCL_EXCLUSIVE\n", This);
631             LeaveCriticalSection(&ddraw_cs);
632             return DDERR_INVALIDPARAMS;
633         }
634
635         /* Switching from fullscreen? */
636         if(This->cooperative_level & DDSCL_FULLSCREEN)
637         {
638             This->cooperative_level &= ~DDSCL_FULLSCREEN;
639             This->cooperative_level &= ~DDSCL_EXCLUSIVE;
640             This->cooperative_level &= ~DDSCL_ALLOWMODEX;
641
642             IWineD3DDevice_ReleaseFocusWindow(This->wineD3DDevice);
643         }
644
645         /* Don't override focus windows or private device windows */
646         if( hwnd &&
647             !(This->focuswindow) &&
648             !(This->devicewindow) &&
649             (hwnd != window) )
650         {
651             This->dest_window = hwnd;
652         }
653     }
654     else if(cooplevel & DDSCL_FULLSCREEN)
655     {
656         /* Needs DDSCL_EXCLUSIVE */
657         if(!(cooplevel & DDSCL_EXCLUSIVE) )
658         {
659             TRACE("(%p) DDSCL_FULLSCREEN needs DDSCL_EXCLUSIVE\n", This);
660             LeaveCriticalSection(&ddraw_cs);
661             return DDERR_INVALIDPARAMS;
662         }
663         /* Need a HWND
664         if(hwnd == 0)
665         {
666             TRACE("(%p) DDSCL_FULLSCREEN needs a HWND\n", This);
667             return DDERR_INVALIDPARAMS;
668         }
669         */
670
671         This->cooperative_level &= ~DDSCL_NORMAL;
672
673         /* Don't override focus windows or private device windows */
674         if( hwnd &&
675             !(This->focuswindow) &&
676             !(This->devicewindow) &&
677             (hwnd != window) )
678         {
679             HRESULT hr = IWineD3DDevice_AcquireFocusWindow(This->wineD3DDevice, hwnd);
680             if (FAILED(hr))
681             {
682                 ERR("Failed to acquire focus window, hr %#x.\n", hr);
683                 LeaveCriticalSection(&ddraw_cs);
684                 return hr;
685             }
686             This->dest_window = hwnd;
687         }
688     }
689     else if(cooplevel & DDSCL_EXCLUSIVE)
690     {
691         TRACE("(%p) DDSCL_EXCLUSIVE needs DDSCL_FULLSCREEN\n", This);
692         LeaveCriticalSection(&ddraw_cs);
693         return DDERR_INVALIDPARAMS;
694     }
695
696     if(cooplevel & DDSCL_CREATEDEVICEWINDOW)
697     {
698         /* Don't create a device window if a focus window is set */
699         if( !(This->focuswindow) )
700         {
701             HWND devicewindow = CreateWindowExA(0, DDRAW_WINDOW_CLASS_NAME, "DDraw device window",
702                     WS_POPUP, 0, 0, GetSystemMetrics(SM_CXSCREEN), GetSystemMetrics(SM_CYSCREEN),
703                     NULL, NULL, NULL, NULL);
704             if (!devicewindow)
705             {
706                 ERR("Failed to create window, last error %#x.\n", GetLastError());
707                 LeaveCriticalSection(&ddraw_cs);
708                 return E_FAIL;
709             }
710
711             ShowWindow(devicewindow, SW_SHOW);   /* Just to be sure */
712             TRACE("(%p) Created a DDraw device window. HWND=%p\n", This, devicewindow);
713
714             This->devicewindow = devicewindow;
715             This->dest_window = devicewindow;
716         }
717     }
718
719     if(cooplevel & DDSCL_MULTITHREADED && !(This->cooperative_level & DDSCL_MULTITHREADED))
720     {
721         /* Enable thread safety in wined3d */
722         IWineD3DDevice_SetMultithreaded(This->wineD3DDevice);
723     }
724
725     /* Unhandled flags */
726     if(cooplevel & DDSCL_ALLOWREBOOT)
727         WARN("(%p) Unhandled flag DDSCL_ALLOWREBOOT, harmless\n", This);
728     if(cooplevel & DDSCL_ALLOWMODEX)
729         WARN("(%p) Unhandled flag DDSCL_ALLOWMODEX, harmless\n", This);
730     if(cooplevel & DDSCL_FPUSETUP)
731         WARN("(%p) Unhandled flag DDSCL_FPUSETUP, harmless\n", This);
732
733     /* Store the cooperative_level */
734     This->cooperative_level |= cooplevel;
735     TRACE("SetCooperativeLevel retuning DD_OK\n");
736     LeaveCriticalSection(&ddraw_cs);
737     return DD_OK;
738 }
739
740 static HRESULT WINAPI ddraw4_SetCooperativeLevel(IDirectDraw4 *iface, HWND window, DWORD flags)
741 {
742     TRACE("iface %p, window %p, flags %#x.\n", iface, window, flags);
743
744     return ddraw7_SetCooperativeLevel((IDirectDraw7 *)ddraw_from_ddraw4(iface), window, flags);
745 }
746
747 static HRESULT WINAPI ddraw3_SetCooperativeLevel(IDirectDraw3 *iface, HWND window, DWORD flags)
748 {
749     TRACE("iface %p, window %p, flags %#x.\n", iface, window, flags);
750
751     return ddraw7_SetCooperativeLevel((IDirectDraw7 *)ddraw_from_ddraw3(iface), window, flags);
752 }
753
754 static HRESULT WINAPI ddraw2_SetCooperativeLevel(IDirectDraw2 *iface, HWND window, DWORD flags)
755 {
756     TRACE("iface %p, window %p, flags %#x.\n", iface, window, flags);
757
758     return ddraw7_SetCooperativeLevel((IDirectDraw7 *)ddraw_from_ddraw2(iface), window, flags);
759 }
760
761 static HRESULT WINAPI ddraw1_SetCooperativeLevel(IDirectDraw *iface, HWND window, DWORD flags)
762 {
763     TRACE("iface %p, window %p, flags %#x.\n", iface, window, flags);
764
765     return ddraw7_SetCooperativeLevel((IDirectDraw7 *)ddraw_from_ddraw1(iface), window, flags);
766 }
767
768 /*****************************************************************************
769  *
770  * Helper function for SetDisplayMode and RestoreDisplayMode
771  *
772  * Implements DirectDraw's SetDisplayMode, but ignores the value of
773  * ForceRefreshRate, since it is already handled by
774  * ddraw7_SetDisplayMode.  RestoreDisplayMode can use this function
775  * without worrying that ForceRefreshRate will override the refresh rate.  For
776  * argument and return value documentation, see
777  * ddraw7_SetDisplayMode.
778  *
779  *****************************************************************************/
780 static HRESULT ddraw_set_display_mode(IDirectDraw7 *iface, DWORD Width, DWORD Height,
781         DWORD BPP, DWORD RefreshRate, DWORD Flags)
782 {
783     IDirectDrawImpl *This = (IDirectDrawImpl *)iface;
784     WINED3DDISPLAYMODE Mode;
785     HRESULT hr;
786
787     TRACE("iface %p, width %u, height %u, bpp %u, refresh_rate %u, flags %#x.\n",
788             iface, Width, Height, BPP, RefreshRate, Flags);
789
790     EnterCriticalSection(&ddraw_cs);
791     if( !Width || !Height )
792     {
793         ERR("Width %u, Height %u, what to do?\n", Width, Height);
794         /* It looks like Need for Speed Porsche Unleashed expects DD_OK here */
795         LeaveCriticalSection(&ddraw_cs);
796         return DD_OK;
797     }
798
799     /* Check the exclusive mode
800     if(!(This->cooperative_level & DDSCL_EXCLUSIVE))
801         return DDERR_NOEXCLUSIVEMODE;
802      * This is WRONG. Don't know if the SDK is completely
803      * wrong and if there are any conditions when DDERR_NOEXCLUSIVE
804      * is returned, but Half-Life 1.1.1.1 (Steam version)
805      * depends on this
806      */
807
808     Mode.Width = Width;
809     Mode.Height = Height;
810     Mode.RefreshRate = RefreshRate;
811     switch(BPP)
812     {
813         case 8:  Mode.Format = WINED3DFMT_P8_UINT;          break;
814         case 15: Mode.Format = WINED3DFMT_B5G5R5X1_UNORM;   break;
815         case 16: Mode.Format = WINED3DFMT_B5G6R5_UNORM;     break;
816         case 24: Mode.Format = WINED3DFMT_B8G8R8_UNORM;     break;
817         case 32: Mode.Format = WINED3DFMT_B8G8R8X8_UNORM;   break;
818     }
819
820     /* TODO: The possible return values from msdn suggest that
821      * the screen mode can't be changed if a surface is locked
822      * or some drawing is in progress
823      */
824
825     /* TODO: Lose the primary surface */
826     hr = IWineD3DDevice_SetDisplayMode(This->wineD3DDevice,
827                                        0, /* First swapchain */
828                                        &Mode);
829     LeaveCriticalSection(&ddraw_cs);
830     switch(hr)
831     {
832         case WINED3DERR_NOTAVAILABLE:       return DDERR_UNSUPPORTED;
833         default:                            return hr;
834     }
835 }
836
837 /*****************************************************************************
838  * IDirectDraw7::SetDisplayMode
839  *
840  * Sets the display screen resolution, color depth and refresh frequency
841  * when in fullscreen mode (in theory).
842  * Possible return values listed in the SDK suggest that this method fails
843  * when not in fullscreen mode, but this is wrong. Windows 2000 happily sets
844  * the display mode in DDSCL_NORMAL mode without an hwnd specified.
845  * It seems to be valid to pass 0 for With and Height, this has to be tested
846  * It could mean that the current video mode should be left as-is. (But why
847  * call it then?)
848  *
849  * Params:
850  *  Height, Width: Screen dimension
851  *  BPP: Color depth in Bits per pixel
852  *  Refreshrate: Screen refresh rate
853  *  Flags: Other stuff
854  *
855  * Returns
856  *  DD_OK on success
857  *
858  *****************************************************************************/
859 static HRESULT WINAPI ddraw7_SetDisplayMode(IDirectDraw7 *iface, DWORD Width, DWORD Height,
860         DWORD BPP, DWORD RefreshRate, DWORD Flags)
861 {
862     TRACE("iface %p, width %u, height %u, bpp %u, refresh_rate %u, flags %#x.\n",
863             iface, Width, Height, BPP, RefreshRate, Flags);
864
865     if (force_refresh_rate != 0)
866     {
867         TRACE("ForceRefreshRate overriding passed-in refresh rate (%u Hz) to %u Hz\n",
868                 RefreshRate, force_refresh_rate);
869         RefreshRate = force_refresh_rate;
870     }
871
872     return ddraw_set_display_mode(iface, Width, Height, BPP, RefreshRate, Flags);
873 }
874
875 static HRESULT WINAPI ddraw4_SetDisplayMode(IDirectDraw4 *iface,
876         DWORD width, DWORD height, DWORD bpp, DWORD refresh_rate, DWORD flags)
877 {
878     TRACE("iface %p, width %u, height %u, bpp %u, refresh_rate %u, flags %#x.\n",
879             iface, width, height, bpp, refresh_rate, flags);
880
881     return ddraw7_SetDisplayMode((IDirectDraw7 *)ddraw_from_ddraw4(iface),
882             width, height, bpp, refresh_rate, flags);
883 }
884
885 static HRESULT WINAPI ddraw3_SetDisplayMode(IDirectDraw3 *iface,
886         DWORD width, DWORD height, DWORD bpp, DWORD refresh_rate, DWORD flags)
887 {
888     TRACE("iface %p, width %u, height %u, bpp %u, refresh_rate %u, flags %#x.\n",
889             iface, width, height, bpp, refresh_rate, flags);
890
891     return ddraw7_SetDisplayMode((IDirectDraw7 *)ddraw_from_ddraw3(iface),
892             width, height, bpp, refresh_rate, flags);
893 }
894
895 static HRESULT WINAPI ddraw2_SetDisplayMode(IDirectDraw2 *iface,
896         DWORD width, DWORD height, DWORD bpp, DWORD refresh_rate, DWORD flags)
897 {
898     TRACE("iface %p, width %u, height %u, bpp %u, refresh_rate %u, flags %#x.\n",
899             iface, width, height, bpp, refresh_rate, flags);
900
901     return ddraw7_SetDisplayMode((IDirectDraw7 *)ddraw_from_ddraw2(iface),
902             width, height, bpp, refresh_rate, flags);
903 }
904
905 static HRESULT WINAPI ddraw1_SetDisplayMode(IDirectDraw *iface, DWORD width, DWORD height, DWORD bpp)
906 {
907     TRACE("iface %p, width %u, height %u, bpp %u.\n", iface, width, height, bpp);
908
909     return ddraw7_SetDisplayMode((IDirectDraw7 *)ddraw_from_ddraw1(iface), width, height, bpp, 0, 0);
910 }
911
912 /*****************************************************************************
913  * IDirectDraw7::RestoreDisplayMode
914  *
915  * Restores the display mode to what it was at creation time. Basically.
916  *
917  * A problem arises when there are 2 DirectDraw objects using the same hwnd:
918  *  -> DD_1 finds the screen at 1400x1050x32 when created, sets it to 640x480x16
919  *  -> DD_2 is created, finds the screen at 640x480x16, sets it to 1024x768x32
920  *  -> DD_1 is released. The screen should be left at 1024x768x32.
921  *  -> DD_2 is released. The screen should be set to 1400x1050x32
922  * This case is unhandled right now, but Empire Earth does it this way.
923  * (But perhaps there is something in SetCooperativeLevel to prevent this)
924  *
925  * The msdn says that this method resets the display mode to what it was before
926  * SetDisplayMode was called. What if SetDisplayModes is called 2 times??
927  *
928  * Returns
929  *  DD_OK on success
930  *  DDERR_NOEXCLUSIVE mode if the device isn't in fullscreen mode
931  *
932  *****************************************************************************/
933 static HRESULT WINAPI ddraw7_RestoreDisplayMode(IDirectDraw7 *iface)
934 {
935     IDirectDrawImpl *This = (IDirectDrawImpl *)iface;
936
937     TRACE("iface %p.\n", iface);
938
939     return ddraw_set_display_mode(iface, This->orig_width, This->orig_height, This->orig_bpp, 0, 0);
940 }
941
942 static HRESULT WINAPI ddraw4_RestoreDisplayMode(IDirectDraw4 *iface)
943 {
944     TRACE("iface %p.\n", iface);
945
946     return ddraw7_RestoreDisplayMode((IDirectDraw7 *)ddraw_from_ddraw4(iface));
947 }
948
949 static HRESULT WINAPI ddraw3_RestoreDisplayMode(IDirectDraw3 *iface)
950 {
951     TRACE("iface %p.\n", iface);
952
953     return ddraw7_RestoreDisplayMode((IDirectDraw7 *)ddraw_from_ddraw3(iface));
954 }
955
956 static HRESULT WINAPI ddraw2_RestoreDisplayMode(IDirectDraw2 *iface)
957 {
958     TRACE("iface %p.\n", iface);
959
960     return ddraw7_RestoreDisplayMode((IDirectDraw7 *)ddraw_from_ddraw2(iface));
961 }
962
963 static HRESULT WINAPI ddraw1_RestoreDisplayMode(IDirectDraw *iface)
964 {
965     TRACE("iface %p.\n", iface);
966
967     return ddraw7_RestoreDisplayMode((IDirectDraw7 *)ddraw_from_ddraw1(iface));
968 }
969
970 /*****************************************************************************
971  * IDirectDraw7::GetCaps
972  *
973  * Returns the drives capabilities
974  *
975  * Used for version 1, 2, 4 and 7
976  *
977  * Params:
978  *  DriverCaps: Structure to write the Hardware accelerated caps to
979  *  HelCaps: Structure to write the emulation caps to
980  *
981  * Returns
982  *  This implementation returns DD_OK only
983  *
984  *****************************************************************************/
985 static HRESULT WINAPI ddraw7_GetCaps(IDirectDraw7 *iface, DDCAPS *DriverCaps, DDCAPS *HELCaps)
986 {
987     IDirectDrawImpl *This = (IDirectDrawImpl *)iface;
988     DDCAPS caps;
989     WINED3DCAPS winecaps;
990     HRESULT hr;
991     DDSCAPS2 ddscaps = {0, 0, 0, 0};
992
993     TRACE("iface %p, driver_caps %p, hel_caps %p.\n", iface, DriverCaps, HELCaps);
994
995     /* One structure must be != NULL */
996     if( (!DriverCaps) && (!HELCaps) )
997     {
998         ERR("(%p) Invalid params to ddraw7_GetCaps\n", This);
999         return DDERR_INVALIDPARAMS;
1000     }
1001
1002     memset(&caps, 0, sizeof(caps));
1003     memset(&winecaps, 0, sizeof(winecaps));
1004     caps.dwSize = sizeof(caps);
1005     EnterCriticalSection(&ddraw_cs);
1006     hr = IWineD3DDevice_GetDeviceCaps(This->wineD3DDevice, &winecaps);
1007     if(FAILED(hr)) {
1008         WARN("IWineD3DDevice::GetDeviceCaps failed\n");
1009         LeaveCriticalSection(&ddraw_cs);
1010         return hr;
1011     }
1012
1013     hr = IDirectDraw7_GetAvailableVidMem(iface, &ddscaps, &caps.dwVidMemTotal, &caps.dwVidMemFree);
1014     LeaveCriticalSection(&ddraw_cs);
1015     if(FAILED(hr)) {
1016         WARN("IDirectDraw7::GetAvailableVidMem failed\n");
1017         return hr;
1018     }
1019
1020     caps.dwCaps = winecaps.DirectDrawCaps.Caps;
1021     caps.dwCaps2 = winecaps.DirectDrawCaps.Caps2;
1022     caps.dwCKeyCaps = winecaps.DirectDrawCaps.CKeyCaps;
1023     caps.dwFXCaps = winecaps.DirectDrawCaps.FXCaps;
1024     caps.dwPalCaps = winecaps.DirectDrawCaps.PalCaps;
1025     caps.ddsCaps.dwCaps = winecaps.DirectDrawCaps.ddsCaps;
1026     caps.dwSVBCaps = winecaps.DirectDrawCaps.SVBCaps;
1027     caps.dwSVBCKeyCaps = winecaps.DirectDrawCaps.SVBCKeyCaps;
1028     caps.dwSVBFXCaps = winecaps.DirectDrawCaps.SVBFXCaps;
1029     caps.dwVSBCaps = winecaps.DirectDrawCaps.VSBCaps;
1030     caps.dwVSBCKeyCaps = winecaps.DirectDrawCaps.VSBCKeyCaps;
1031     caps.dwVSBFXCaps = winecaps.DirectDrawCaps.VSBFXCaps;
1032     caps.dwSSBCaps = winecaps.DirectDrawCaps.SSBCaps;
1033     caps.dwSSBCKeyCaps = winecaps.DirectDrawCaps.SSBCKeyCaps;
1034     caps.dwSSBFXCaps = winecaps.DirectDrawCaps.SSBFXCaps;
1035
1036     /* Even if WineD3D supports 3D rendering, remove the cap if ddraw is configured
1037      * not to use it
1038      */
1039     if(DefaultSurfaceType == SURFACE_GDI) {
1040         caps.dwCaps &= ~DDCAPS_3D;
1041         caps.ddsCaps.dwCaps &= ~(DDSCAPS_3DDEVICE | DDSCAPS_MIPMAP | DDSCAPS_TEXTURE | DDSCAPS_ZBUFFER);
1042     }
1043     if(winecaps.DirectDrawCaps.StrideAlign != 0) {
1044         caps.dwCaps |= DDCAPS_ALIGNSTRIDE;
1045         caps.dwAlignStrideAlign = winecaps.DirectDrawCaps.StrideAlign;
1046     }
1047
1048     if(DriverCaps)
1049     {
1050         DD_STRUCT_COPY_BYSIZE(DriverCaps, &caps);
1051         if (TRACE_ON(ddraw))
1052         {
1053             TRACE("Driver Caps :\n");
1054             DDRAW_dump_DDCAPS(DriverCaps);
1055         }
1056
1057     }
1058     if(HELCaps)
1059     {
1060         DD_STRUCT_COPY_BYSIZE(HELCaps, &caps);
1061         if (TRACE_ON(ddraw))
1062         {
1063             TRACE("HEL Caps :\n");
1064             DDRAW_dump_DDCAPS(HELCaps);
1065         }
1066     }
1067
1068     return DD_OK;
1069 }
1070
1071 static HRESULT WINAPI ddraw4_GetCaps(IDirectDraw4 *iface, DDCAPS *driver_caps, DDCAPS *hel_caps)
1072 {
1073     TRACE("iface %p, driver_caps %p, hel_caps %p.\n", iface, driver_caps, hel_caps);
1074
1075     return ddraw7_GetCaps((IDirectDraw7 *)ddraw_from_ddraw4(iface), driver_caps, hel_caps);
1076 }
1077
1078 static HRESULT WINAPI ddraw3_GetCaps(IDirectDraw3 *iface, DDCAPS *driver_caps, DDCAPS *hel_caps)
1079 {
1080     TRACE("iface %p, driver_caps %p, hel_caps %p.\n", iface, driver_caps, hel_caps);
1081
1082     return ddraw7_GetCaps((IDirectDraw7 *)ddraw_from_ddraw3(iface), driver_caps, hel_caps);
1083 }
1084
1085 static HRESULT WINAPI ddraw2_GetCaps(IDirectDraw2 *iface, DDCAPS *driver_caps, DDCAPS *hel_caps)
1086 {
1087     TRACE("iface %p, driver_caps %p, hel_caps %p.\n", iface, driver_caps, hel_caps);
1088
1089     return ddraw7_GetCaps((IDirectDraw7 *)ddraw_from_ddraw2(iface), driver_caps, hel_caps);
1090 }
1091
1092 static HRESULT WINAPI ddraw1_GetCaps(IDirectDraw *iface, DDCAPS *driver_caps, DDCAPS *hel_caps)
1093 {
1094     TRACE("iface %p, driver_caps %p, hel_caps %p.\n", iface, driver_caps, hel_caps);
1095
1096     return ddraw7_GetCaps((IDirectDraw7 *)ddraw_from_ddraw1(iface), driver_caps, hel_caps);
1097 }
1098
1099 /*****************************************************************************
1100  * IDirectDraw7::Compact
1101  *
1102  * No idea what it does, MSDN says it's not implemented.
1103  *
1104  * Returns
1105  *  DD_OK, but this is unchecked
1106  *
1107  *****************************************************************************/
1108 static HRESULT WINAPI ddraw7_Compact(IDirectDraw7 *iface)
1109 {
1110     TRACE("iface %p.\n", iface);
1111
1112     return DD_OK;
1113 }
1114
1115 static HRESULT WINAPI ddraw4_Compact(IDirectDraw4 *iface)
1116 {
1117     TRACE("iface %p.\n", iface);
1118
1119     return ddraw7_Compact((IDirectDraw7 *)ddraw_from_ddraw4(iface));
1120 }
1121
1122 static HRESULT WINAPI ddraw3_Compact(IDirectDraw3 *iface)
1123 {
1124     TRACE("iface %p.\n", iface);
1125
1126     return ddraw7_Compact((IDirectDraw7 *)ddraw_from_ddraw3(iface));
1127 }
1128
1129 static HRESULT WINAPI ddraw2_Compact(IDirectDraw2 *iface)
1130 {
1131     TRACE("iface %p.\n", iface);
1132
1133     return ddraw7_Compact((IDirectDraw7 *)ddraw_from_ddraw2(iface));
1134 }
1135
1136 static HRESULT WINAPI ddraw1_Compact(IDirectDraw *iface)
1137 {
1138     TRACE("iface %p.\n", iface);
1139
1140     return ddraw7_Compact((IDirectDraw7 *)ddraw_from_ddraw1(iface));
1141 }
1142
1143 /*****************************************************************************
1144  * IDirectDraw7::GetDisplayMode
1145  *
1146  * Returns information about the current display mode
1147  *
1148  * Exists in Version 1, 2, 4 and 7
1149  *
1150  * Params:
1151  *  DDSD: Address of a surface description structure to write the info to
1152  *
1153  * Returns
1154  *  DD_OK
1155  *
1156  *****************************************************************************/
1157 static HRESULT WINAPI ddraw7_GetDisplayMode(IDirectDraw7 *iface, DDSURFACEDESC2 *DDSD)
1158 {
1159     IDirectDrawImpl *This = (IDirectDrawImpl *)iface;
1160     HRESULT hr;
1161     WINED3DDISPLAYMODE Mode;
1162     DWORD Size;
1163
1164     TRACE("iface %p, surface_desc %p.\n", iface, DDSD);
1165
1166     EnterCriticalSection(&ddraw_cs);
1167     /* This seems sane */
1168     if (!DDSD)
1169     {
1170         LeaveCriticalSection(&ddraw_cs);
1171         return DDERR_INVALIDPARAMS;
1172     }
1173
1174     /* The necessary members of LPDDSURFACEDESC and LPDDSURFACEDESC2 are equal,
1175      * so one method can be used for all versions (Hopefully)
1176      */
1177     hr = IWineD3DDevice_GetDisplayMode(This->wineD3DDevice,
1178                                       0 /* swapchain 0 */,
1179                                       &Mode);
1180     if( hr != D3D_OK )
1181     {
1182         ERR(" (%p) IWineD3DDevice::GetDisplayMode returned %08x\n", This, hr);
1183         LeaveCriticalSection(&ddraw_cs);
1184         return hr;
1185     }
1186
1187     Size = DDSD->dwSize;
1188     memset(DDSD, 0, Size);
1189
1190     DDSD->dwSize = Size;
1191     DDSD->dwFlags |= DDSD_HEIGHT | DDSD_WIDTH | DDSD_PIXELFORMAT | DDSD_PITCH | DDSD_REFRESHRATE;
1192     DDSD->dwWidth = Mode.Width;
1193     DDSD->dwHeight = Mode.Height;
1194     DDSD->u2.dwRefreshRate = 60;
1195     DDSD->ddsCaps.dwCaps = 0;
1196     DDSD->u4.ddpfPixelFormat.dwSize = sizeof(DDSD->u4.ddpfPixelFormat);
1197     PixelFormat_WineD3DtoDD(&DDSD->u4.ddpfPixelFormat, Mode.Format);
1198     DDSD->u1.lPitch = Mode.Width * DDSD->u4.ddpfPixelFormat.u1.dwRGBBitCount / 8;
1199
1200     if(TRACE_ON(ddraw))
1201     {
1202         TRACE("Returning surface desc :\n");
1203         DDRAW_dump_surface_desc(DDSD);
1204     }
1205
1206     LeaveCriticalSection(&ddraw_cs);
1207     return DD_OK;
1208 }
1209
1210 static HRESULT WINAPI ddraw4_GetDisplayMode(IDirectDraw4 *iface, DDSURFACEDESC2 *surface_desc)
1211 {
1212     TRACE("iface %p, surface_desc %p.\n", iface, surface_desc);
1213
1214     return ddraw7_GetDisplayMode((IDirectDraw7 *)ddraw_from_ddraw4(iface), surface_desc);
1215 }
1216
1217 static HRESULT WINAPI ddraw3_GetDisplayMode(IDirectDraw3 *iface, DDSURFACEDESC *surface_desc)
1218 {
1219     TRACE("iface %p, surface_desc %p.\n", iface, surface_desc);
1220
1221     return ddraw7_GetDisplayMode((IDirectDraw7 *)ddraw_from_ddraw3(iface), (DDSURFACEDESC2 *)surface_desc);
1222 }
1223
1224 static HRESULT WINAPI ddraw2_GetDisplayMode(IDirectDraw2 *iface, DDSURFACEDESC *surface_desc)
1225 {
1226     TRACE("iface %p, surface_desc %p.\n", iface, surface_desc);
1227
1228     return ddraw7_GetDisplayMode((IDirectDraw7 *)ddraw_from_ddraw2(iface), (DDSURFACEDESC2 *)surface_desc);
1229 }
1230
1231 static HRESULT WINAPI ddraw1_GetDisplayMode(IDirectDraw *iface, DDSURFACEDESC *surface_desc)
1232 {
1233     TRACE("iface %p, surface_desc %p.\n", iface, surface_desc);
1234
1235     return ddraw7_GetDisplayMode((IDirectDraw7 *)ddraw_from_ddraw1(iface), (DDSURFACEDESC2 *)surface_desc);
1236 }
1237
1238 /*****************************************************************************
1239  * IDirectDraw7::GetFourCCCodes
1240  *
1241  * Returns an array of supported FourCC codes.
1242  *
1243  * Exists in Version 1, 2, 4 and 7
1244  *
1245  * Params:
1246  *  NumCodes: Contains the number of Codes that Codes can carry. Returns the number
1247  *            of enumerated codes
1248  *  Codes: Pointer to an array of DWORDs where the supported codes are written
1249  *         to
1250  *
1251  * Returns
1252  *  Always returns DD_OK, as it's a stub for now
1253  *
1254  *****************************************************************************/
1255 static HRESULT WINAPI ddraw7_GetFourCCCodes(IDirectDraw7 *iface, DWORD *NumCodes, DWORD *Codes)
1256 {
1257     IDirectDrawImpl *This = (IDirectDrawImpl *)iface;
1258     static const WINED3DFORMAT formats[] =
1259     {
1260         WINED3DFMT_YUY2, WINED3DFMT_UYVY, WINED3DFMT_YV12,
1261         WINED3DFMT_DXT1, WINED3DFMT_DXT2, WINED3DFMT_DXT3, WINED3DFMT_DXT4, WINED3DFMT_DXT5,
1262         WINED3DFMT_ATI2N, WINED3DFMT_NVHU, WINED3DFMT_NVHS
1263     };
1264     DWORD count = 0, i, outsize;
1265     HRESULT hr;
1266     WINED3DDISPLAYMODE d3ddm;
1267     WINED3DSURFTYPE type = This->ImplType;
1268
1269     TRACE("iface %p, codes_count %p, codes %p.\n", iface, NumCodes, Codes);
1270
1271     IWineD3DDevice_GetDisplayMode(This->wineD3DDevice,
1272                                   0 /* swapchain 0 */,
1273                                   &d3ddm);
1274
1275     outsize = NumCodes && Codes ? *NumCodes : 0;
1276
1277     if(type == SURFACE_UNKNOWN) type = SURFACE_GDI;
1278
1279     for(i = 0; i < (sizeof(formats) / sizeof(formats[0])); i++) {
1280         hr = IWineD3D_CheckDeviceFormat(This->wineD3D,
1281                                         WINED3DADAPTER_DEFAULT,
1282                                         WINED3DDEVTYPE_HAL,
1283                                         d3ddm.Format /* AdapterFormat */,
1284                                         0 /* usage */,
1285                                         WINED3DRTYPE_SURFACE,
1286                                         formats[i],
1287                                         type);
1288         if(SUCCEEDED(hr)) {
1289             if(count < outsize) {
1290                 Codes[count] = formats[i];
1291             }
1292             count++;
1293         }
1294     }
1295     if(NumCodes) {
1296         TRACE("Returning %u FourCC codes\n", count);
1297         *NumCodes = count;
1298     }
1299
1300     return DD_OK;
1301 }
1302
1303 static HRESULT WINAPI ddraw4_GetFourCCCodes(IDirectDraw4 *iface, DWORD *codes_count, DWORD *codes)
1304 {
1305     TRACE("iface %p, codes_count %p, codes %p.\n", iface, codes_count, codes);
1306
1307     return ddraw7_GetFourCCCodes((IDirectDraw7 *)ddraw_from_ddraw4(iface), codes_count, codes);
1308 }
1309
1310 static HRESULT WINAPI ddraw3_GetFourCCCodes(IDirectDraw3 *iface, DWORD *codes_count, DWORD *codes)
1311 {
1312     TRACE("iface %p, codes_count %p, codes %p.\n", iface, codes_count, codes);
1313
1314     return ddraw7_GetFourCCCodes((IDirectDraw7 *)ddraw_from_ddraw3(iface), codes_count, codes);
1315 }
1316
1317 static HRESULT WINAPI ddraw2_GetFourCCCodes(IDirectDraw2 *iface, DWORD *codes_count, DWORD *codes)
1318 {
1319     TRACE("iface %p, codes_count %p, codes %p.\n", iface, codes_count, codes);
1320
1321     return ddraw7_GetFourCCCodes((IDirectDraw7 *)ddraw_from_ddraw2(iface), codes_count, codes);
1322 }
1323
1324 static HRESULT WINAPI ddraw1_GetFourCCCodes(IDirectDraw *iface, DWORD *codes_count, DWORD *codes)
1325 {
1326     TRACE("iface %p, codes_count %p, codes %p.\n", iface, codes_count, codes);
1327
1328     return ddraw7_GetFourCCCodes((IDirectDraw7 *)ddraw_from_ddraw1(iface), codes_count, codes);
1329 }
1330
1331 /*****************************************************************************
1332  * IDirectDraw7::GetMonitorFrequency
1333  *
1334  * Returns the monitor's frequency
1335  *
1336  * Exists in Version 1, 2, 4 and 7
1337  *
1338  * Params:
1339  *  Freq: Pointer to a DWORD to write the frequency to
1340  *
1341  * Returns
1342  *  Always returns DD_OK
1343  *
1344  *****************************************************************************/
1345 static HRESULT WINAPI ddraw7_GetMonitorFrequency(IDirectDraw7 *iface, DWORD *Freq)
1346 {
1347     FIXME("iface %p, frequency %p stub!\n", iface, Freq);
1348
1349     /* Ideally this should be in WineD3D, as it concerns the screen setup,
1350      * but for now this should make the games happy
1351      */
1352     *Freq = 60;
1353     return DD_OK;
1354 }
1355
1356 static HRESULT WINAPI ddraw4_GetMonitorFrequency(IDirectDraw4 *iface, DWORD *frequency)
1357 {
1358     TRACE("iface %p, frequency %p.\n", iface, frequency);
1359
1360     return ddraw7_GetMonitorFrequency((IDirectDraw7 *)ddraw_from_ddraw4(iface), frequency);
1361 }
1362
1363 static HRESULT WINAPI ddraw3_GetMonitorFrequency(IDirectDraw3 *iface, DWORD *frequency)
1364 {
1365     TRACE("iface %p, frequency %p.\n", iface, frequency);
1366
1367     return ddraw7_GetMonitorFrequency((IDirectDraw7 *)ddraw_from_ddraw3(iface), frequency);
1368 }
1369
1370 static HRESULT WINAPI ddraw2_GetMonitorFrequency(IDirectDraw2 *iface, DWORD *frequency)
1371 {
1372     TRACE("iface %p, frequency %p.\n", iface, frequency);
1373
1374     return ddraw7_GetMonitorFrequency((IDirectDraw7 *)ddraw_from_ddraw2(iface), frequency);
1375 }
1376
1377 static HRESULT WINAPI ddraw1_GetMonitorFrequency(IDirectDraw *iface, DWORD *frequency)
1378 {
1379     TRACE("iface %p, frequency %p.\n", iface, frequency);
1380
1381     return ddraw7_GetMonitorFrequency((IDirectDraw7 *)ddraw_from_ddraw1(iface), frequency);
1382 }
1383
1384 /*****************************************************************************
1385  * IDirectDraw7::GetVerticalBlankStatus
1386  *
1387  * Returns the Vertical blank status of the monitor. This should be in WineD3D
1388  * too basically, but as it's a semi stub, I didn't create a function there
1389  *
1390  * Params:
1391  *  status: Pointer to a BOOL to be filled with the vertical blank status
1392  *
1393  * Returns
1394  *  DD_OK on success
1395  *  DDERR_INVALIDPARAMS if status is NULL
1396  *
1397  *****************************************************************************/
1398 static HRESULT WINAPI ddraw7_GetVerticalBlankStatus(IDirectDraw7 *iface, BOOL *status)
1399 {
1400     IDirectDrawImpl *This = (IDirectDrawImpl *)iface;
1401
1402     TRACE("iface %p, status %p.\n", iface, status);
1403
1404     /* This looks sane, the MSDN suggests it too */
1405     EnterCriticalSection(&ddraw_cs);
1406     if(!status)
1407     {
1408         LeaveCriticalSection(&ddraw_cs);
1409         return DDERR_INVALIDPARAMS;
1410     }
1411
1412     *status = This->fake_vblank;
1413     This->fake_vblank = !This->fake_vblank;
1414     LeaveCriticalSection(&ddraw_cs);
1415     return DD_OK;
1416 }
1417
1418 static HRESULT WINAPI ddraw4_GetVerticalBlankStatus(IDirectDraw4 *iface, BOOL *status)
1419 {
1420     TRACE("iface %p, status %p.\n", iface, status);
1421
1422     return ddraw7_GetVerticalBlankStatus((IDirectDraw7 *)ddraw_from_ddraw4(iface), status);
1423 }
1424
1425 static HRESULT WINAPI ddraw3_GetVerticalBlankStatus(IDirectDraw3 *iface, BOOL *status)
1426 {
1427     TRACE("iface %p, status %p.\n", iface, status);
1428
1429     return ddraw7_GetVerticalBlankStatus((IDirectDraw7 *)ddraw_from_ddraw3(iface), status);
1430 }
1431
1432 static HRESULT WINAPI ddraw2_GetVerticalBlankStatus(IDirectDraw2 *iface, BOOL *status)
1433 {
1434     TRACE("iface %p, status %p.\n", iface, status);
1435
1436     return ddraw7_GetVerticalBlankStatus((IDirectDraw7 *)ddraw_from_ddraw2(iface), status);
1437 }
1438
1439 static HRESULT WINAPI ddraw1_GetVerticalBlankStatus(IDirectDraw *iface, BOOL *status)
1440 {
1441     TRACE("iface %p, status %p.\n", iface, status);
1442
1443     return ddraw7_GetVerticalBlankStatus((IDirectDraw7 *)ddraw_from_ddraw1(iface), status);
1444 }
1445
1446 /*****************************************************************************
1447  * IDirectDraw7::GetAvailableVidMem
1448  *
1449  * Returns the total and free video memory
1450  *
1451  * Params:
1452  *  Caps: Specifies the memory type asked for
1453  *  total: Pointer to a DWORD to be filled with the total memory
1454  *  free: Pointer to a DWORD to be filled with the free memory
1455  *
1456  * Returns
1457  *  DD_OK on success
1458  *  DDERR_INVALIDPARAMS of free and total are NULL
1459  *
1460  *****************************************************************************/
1461 static HRESULT WINAPI ddraw7_GetAvailableVidMem(IDirectDraw7 *iface, DDSCAPS2 *Caps, DWORD *total, DWORD *free)
1462 {
1463     IDirectDrawImpl *This = (IDirectDrawImpl *)iface;
1464
1465     TRACE("iface %p, caps %p, total %p, free %p.\n", iface, Caps, total, free);
1466
1467     if(TRACE_ON(ddraw))
1468     {
1469         TRACE("(%p) Asked for memory with description: ", This);
1470         DDRAW_dump_DDSCAPS2(Caps);
1471     }
1472     EnterCriticalSection(&ddraw_cs);
1473
1474     /* Todo: System memory vs local video memory vs non-local video memory
1475      * The MSDN also mentions differences between texture memory and other
1476      * resources, but that's not important
1477      */
1478
1479     if( (!total) && (!free) )
1480     {
1481         LeaveCriticalSection(&ddraw_cs);
1482         return DDERR_INVALIDPARAMS;
1483     }
1484
1485     if(total) *total = This->total_vidmem;
1486     if(free) *free = IWineD3DDevice_GetAvailableTextureMem(This->wineD3DDevice);
1487
1488     LeaveCriticalSection(&ddraw_cs);
1489     return DD_OK;
1490 }
1491
1492 static HRESULT WINAPI ddraw4_GetAvailableVidMem(IDirectDraw4 *iface,
1493         DDSCAPS2 *caps, DWORD *total, DWORD *free)
1494 {
1495     TRACE("iface %p, caps %p, total %p, free %p.\n", iface, caps, total, free);
1496
1497     return ddraw7_GetAvailableVidMem((IDirectDraw7 *)ddraw_from_ddraw4(iface), caps, total, free);
1498 }
1499
1500 static HRESULT WINAPI ddraw3_GetAvailableVidMem(IDirectDraw3 *iface,
1501         DDSCAPS *caps, DWORD *total, DWORD *free)
1502 {
1503     DDSCAPS2 caps2;
1504
1505     TRACE("iface %p, caps %p, total %p, free %p.\n", iface, caps, total, free);
1506
1507     DDRAW_Convert_DDSCAPS_1_To_2(caps, &caps2);
1508     return ddraw7_GetAvailableVidMem((IDirectDraw7 *)ddraw_from_ddraw3(iface), &caps2, total, free);
1509 }
1510
1511 static HRESULT WINAPI ddraw2_GetAvailableVidMem(IDirectDraw2 *iface,
1512         DDSCAPS *caps, DWORD *total, DWORD *free)
1513 {
1514     DDSCAPS2 caps2;
1515
1516     TRACE("iface %p, caps %p, total %p, free %p.\n", iface, caps, total, free);
1517
1518     DDRAW_Convert_DDSCAPS_1_To_2(caps, &caps2);
1519     return ddraw7_GetAvailableVidMem((IDirectDraw7 *)ddraw_from_ddraw2(iface), &caps2, total, free);
1520 }
1521
1522 /*****************************************************************************
1523  * IDirectDraw7::Initialize
1524  *
1525  * Initializes a DirectDraw interface.
1526  *
1527  * Params:
1528  *  GUID: Interface identifier. Well, don't know what this is really good
1529  *   for
1530  *
1531  * Returns
1532  *  Returns DD_OK on the first call,
1533  *  DDERR_ALREADYINITIALIZED on repeated calls
1534  *
1535  *****************************************************************************/
1536 static HRESULT WINAPI ddraw7_Initialize(IDirectDraw7 *iface, GUID *Guid)
1537 {
1538     IDirectDrawImpl *This = (IDirectDrawImpl *)iface;
1539
1540     TRACE("iface %p, guid %s.\n", iface, debugstr_guid(Guid));
1541
1542     if(This->initialized)
1543     {
1544         return DDERR_ALREADYINITIALIZED;
1545     }
1546     else
1547     {
1548         return DD_OK;
1549     }
1550 }
1551
1552 static HRESULT WINAPI ddraw4_Initialize(IDirectDraw4 *iface, GUID *guid)
1553 {
1554     TRACE("iface %p, guid %s.\n", iface, debugstr_guid(guid));
1555
1556     return ddraw7_Initialize((IDirectDraw7 *)ddraw_from_ddraw4(iface), guid);
1557 }
1558
1559 static HRESULT WINAPI ddraw3_Initialize(IDirectDraw3 *iface, GUID *guid)
1560 {
1561     TRACE("iface %p, guid %s.\n", iface, debugstr_guid(guid));
1562
1563     return ddraw7_Initialize((IDirectDraw7 *)ddraw_from_ddraw3(iface), guid);
1564 }
1565
1566 static HRESULT WINAPI ddraw2_Initialize(IDirectDraw2 *iface, GUID *guid)
1567 {
1568     TRACE("iface %p, guid %s.\n", iface, debugstr_guid(guid));
1569
1570     return ddraw7_Initialize((IDirectDraw7 *)ddraw_from_ddraw2(iface), guid);
1571 }
1572
1573 static HRESULT WINAPI ddraw1_Initialize(IDirectDraw *iface, GUID *guid)
1574 {
1575     TRACE("iface %p, guid %s.\n", iface, debugstr_guid(guid));
1576
1577     return ddraw7_Initialize((IDirectDraw7 *)ddraw_from_ddraw1(iface), guid);
1578 }
1579
1580 static HRESULT WINAPI d3d1_Initialize(IDirect3D *iface, REFIID riid)
1581 {
1582     TRACE("iface %p, riid %s.\n", iface, debugstr_guid(riid));
1583
1584     return D3D_OK;
1585 }
1586
1587 /*****************************************************************************
1588  * IDirectDraw7::FlipToGDISurface
1589  *
1590  * "Makes the surface that the GDI writes to the primary surface"
1591  * Looks like some windows specific thing we don't have to care about.
1592  * According to MSDN it permits GDI dialog boxes in FULLSCREEN mode. Good to
1593  * show error boxes ;)
1594  * Well, just return DD_OK.
1595  *
1596  * Returns:
1597  *  Always returns DD_OK
1598  *
1599  *****************************************************************************/
1600 static HRESULT WINAPI ddraw7_FlipToGDISurface(IDirectDraw7 *iface)
1601 {
1602     FIXME("iface %p stub!\n", iface);
1603
1604     return DD_OK;
1605 }
1606
1607 static HRESULT WINAPI ddraw4_FlipToGDISurface(IDirectDraw4 *iface)
1608 {
1609     TRACE("iface %p.\n", iface);
1610
1611     return ddraw7_FlipToGDISurface((IDirectDraw7 *)ddraw_from_ddraw4(iface));
1612 }
1613
1614 static HRESULT WINAPI ddraw3_FlipToGDISurface(IDirectDraw3 *iface)
1615 {
1616     TRACE("iface %p.\n", iface);
1617
1618     return ddraw7_FlipToGDISurface((IDirectDraw7 *)ddraw_from_ddraw3(iface));
1619 }
1620
1621 static HRESULT WINAPI ddraw2_FlipToGDISurface(IDirectDraw2 *iface)
1622 {
1623     TRACE("iface %p.\n", iface);
1624
1625     return ddraw7_FlipToGDISurface((IDirectDraw7 *)ddraw_from_ddraw2(iface));
1626 }
1627
1628 static HRESULT WINAPI ddraw1_FlipToGDISurface(IDirectDraw *iface)
1629 {
1630     TRACE("iface %p.\n", iface);
1631
1632     return ddraw7_FlipToGDISurface((IDirectDraw7 *)ddraw_from_ddraw1(iface));
1633 }
1634
1635 /*****************************************************************************
1636  * IDirectDraw7::WaitForVerticalBlank
1637  *
1638  * This method allows applications to get in sync with the vertical blank
1639  * interval.
1640  * The wormhole demo in the DirectX 7 sdk uses this call, and it doesn't
1641  * redraw the screen, most likely because of this stub
1642  *
1643  * Parameters:
1644  *  Flags: one of DDWAITVB_BLOCKBEGIN, DDWAITVB_BLOCKBEGINEVENT
1645  *         or DDWAITVB_BLOCKEND
1646  *  h: Not used, according to MSDN
1647  *
1648  * Returns:
1649  *  Always returns DD_OK
1650  *
1651  *****************************************************************************/
1652 static HRESULT WINAPI ddraw7_WaitForVerticalBlank(IDirectDraw7 *iface, DWORD Flags, HANDLE event)
1653 {
1654     static BOOL hide;
1655
1656     TRACE("iface %p, flags %#x, event %p.\n", iface, Flags, event);
1657
1658     /* This function is called often, so print the fixme only once */
1659     if(!hide)
1660     {
1661         FIXME("iface %p, flags %#x, event %p stub!\n", iface, Flags, event);
1662         hide = TRUE;
1663     }
1664
1665     /* MSDN says DDWAITVB_BLOCKBEGINEVENT is not supported */
1666     if(Flags & DDWAITVB_BLOCKBEGINEVENT)
1667         return DDERR_UNSUPPORTED; /* unchecked */
1668
1669     return DD_OK;
1670 }
1671
1672 static HRESULT WINAPI ddraw4_WaitForVerticalBlank(IDirectDraw4 *iface, DWORD flags, HANDLE event)
1673 {
1674     TRACE("iface %p, flags %#x, event %p.\n", iface, flags, event);
1675
1676     return ddraw7_WaitForVerticalBlank((IDirectDraw7 *)ddraw_from_ddraw4(iface), flags, event);
1677 }
1678
1679 static HRESULT WINAPI ddraw3_WaitForVerticalBlank(IDirectDraw3 *iface, DWORD flags, HANDLE event)
1680 {
1681     TRACE("iface %p, flags %#x, event %p.\n", iface, flags, event);
1682
1683     return ddraw7_WaitForVerticalBlank((IDirectDraw7 *)ddraw_from_ddraw3(iface), flags, event);
1684 }
1685
1686 static HRESULT WINAPI ddraw2_WaitForVerticalBlank(IDirectDraw2 *iface, DWORD flags, HANDLE event)
1687 {
1688     TRACE("iface %p, flags %#x, event %p.\n", iface, flags, event);
1689
1690     return ddraw7_WaitForVerticalBlank((IDirectDraw7 *)ddraw_from_ddraw2(iface), flags, event);
1691 }
1692
1693 static HRESULT WINAPI ddraw1_WaitForVerticalBlank(IDirectDraw *iface, DWORD flags, HANDLE event)
1694 {
1695     TRACE("iface %p, flags %#x, event %p.\n", iface, flags, event);
1696
1697     return ddraw7_WaitForVerticalBlank((IDirectDraw7 *)ddraw_from_ddraw1(iface), flags, event);
1698 }
1699
1700 /*****************************************************************************
1701  * IDirectDraw7::GetScanLine
1702  *
1703  * Returns the scan line that is being drawn on the monitor
1704  *
1705  * Parameters:
1706  *  Scanline: Address to write the scan line value to
1707  *
1708  * Returns:
1709  *  Always returns DD_OK
1710  *
1711  *****************************************************************************/
1712 static HRESULT WINAPI ddraw7_GetScanLine(IDirectDraw7 *iface, DWORD *Scanline)
1713 {
1714     IDirectDrawImpl *This = (IDirectDrawImpl *)iface;
1715     static BOOL hide = FALSE;
1716     WINED3DDISPLAYMODE Mode;
1717
1718     TRACE("iface %p, line %p.\n", iface, Scanline);
1719
1720     /* This function is called often, so print the fixme only once */
1721     EnterCriticalSection(&ddraw_cs);
1722     if(!hide)
1723     {
1724         FIXME("iface %p, line %p partial stub!\n", iface, Scanline);
1725         hide = TRUE;
1726     }
1727
1728     IWineD3DDevice_GetDisplayMode(This->wineD3DDevice,
1729                                   0,
1730                                   &Mode);
1731
1732     /* Fake the line sweeping of the monitor */
1733     /* FIXME: We should synchronize with a source to keep the refresh rate */
1734     *Scanline = This->cur_scanline++;
1735     /* Assume 20 scan lines in the vertical blank */
1736     if (This->cur_scanline >= Mode.Height + 20)
1737         This->cur_scanline = 0;
1738
1739     LeaveCriticalSection(&ddraw_cs);
1740     return DD_OK;
1741 }
1742
1743 static HRESULT WINAPI ddraw4_GetScanLine(IDirectDraw4 *iface, DWORD *line)
1744 {
1745     TRACE("iface %p, line %p.\n", iface, line);
1746
1747     return ddraw7_GetScanLine((IDirectDraw7 *)ddraw_from_ddraw4(iface), line);
1748 }
1749
1750 static HRESULT WINAPI ddraw3_GetScanLine(IDirectDraw3 *iface, DWORD *line)
1751 {
1752     TRACE("iface %p, line %p.\n", iface, line);
1753
1754     return ddraw7_GetScanLine((IDirectDraw7 *)ddraw_from_ddraw3(iface), line);
1755 }
1756
1757 static HRESULT WINAPI ddraw2_GetScanLine(IDirectDraw2 *iface, DWORD *line)
1758 {
1759     TRACE("iface %p, line %p.\n", iface, line);
1760
1761     return ddraw7_GetScanLine((IDirectDraw7 *)ddraw_from_ddraw2(iface), line);
1762 }
1763
1764 static HRESULT WINAPI ddraw1_GetScanLine(IDirectDraw *iface, DWORD *line)
1765 {
1766     TRACE("iface %p, line %p.\n", iface, line);
1767
1768     return ddraw7_GetScanLine((IDirectDraw7 *)ddraw_from_ddraw1(iface), line);
1769 }
1770
1771 /*****************************************************************************
1772  * IDirectDraw7::TestCooperativeLevel
1773  *
1774  * Informs the application about the state of the video adapter, depending
1775  * on the cooperative level
1776  *
1777  * Returns:
1778  *  DD_OK if the device is in a sane state
1779  *  DDERR_NOEXCLUSIVEMODE or DDERR_EXCLUSIVEMODEALREADYSET
1780  *  if the state is not correct(See below)
1781  *
1782  *****************************************************************************/
1783 static HRESULT WINAPI ddraw7_TestCooperativeLevel(IDirectDraw7 *iface)
1784 {
1785     TRACE("iface %p.\n", iface);
1786
1787     return DD_OK;
1788 }
1789
1790 static HRESULT WINAPI ddraw4_TestCooperativeLevel(IDirectDraw4 *iface)
1791 {
1792     TRACE("iface %p.\n", iface);
1793
1794     return ddraw7_TestCooperativeLevel((IDirectDraw7 *)ddraw_from_ddraw4(iface));
1795 }
1796
1797 /*****************************************************************************
1798  * IDirectDraw7::GetGDISurface
1799  *
1800  * Returns the surface that GDI is treating as the primary surface.
1801  * For Wine this is the front buffer
1802  *
1803  * Params:
1804  *  GDISurface: Address to write the surface pointer to
1805  *
1806  * Returns:
1807  *  DD_OK if the surface was found
1808  *  DDERR_NOTFOUND if the GDI surface wasn't found
1809  *
1810  *****************************************************************************/
1811 static HRESULT WINAPI ddraw7_GetGDISurface(IDirectDraw7 *iface, IDirectDrawSurface7 **GDISurface)
1812 {
1813     IDirectDrawImpl *This = (IDirectDrawImpl *)iface;
1814     IWineD3DSurface *Surf;
1815     IDirectDrawSurface7 *ddsurf;
1816     HRESULT hr;
1817     DDSCAPS2 ddsCaps;
1818
1819     TRACE("iface %p, surface %p.\n", iface, GDISurface);
1820
1821     /* Get the back buffer from the wineD3DDevice and search its
1822      * attached surfaces for the front buffer
1823      */
1824     EnterCriticalSection(&ddraw_cs);
1825     hr = IWineD3DDevice_GetBackBuffer(This->wineD3DDevice,
1826                                       0, /* SwapChain */
1827                                       0, /* first back buffer*/
1828                                       WINED3DBACKBUFFER_TYPE_MONO,
1829                                       &Surf);
1830
1831     if( (hr != D3D_OK) ||
1832         (!Surf) )
1833     {
1834         ERR("IWineD3DDevice::GetBackBuffer failed\n");
1835         LeaveCriticalSection(&ddraw_cs);
1836         return DDERR_NOTFOUND;
1837     }
1838
1839     /* GetBackBuffer AddRef()ed the surface, release it */
1840     IWineD3DSurface_Release(Surf);
1841
1842     IWineD3DSurface_GetParent(Surf,
1843                               (IUnknown **) &ddsurf);
1844     IDirectDrawSurface7_Release(ddsurf);  /* For the GetParent */
1845
1846     /* Find the front buffer */
1847     ddsCaps.dwCaps = DDSCAPS_FRONTBUFFER;
1848     hr = IDirectDrawSurface7_GetAttachedSurface(ddsurf,
1849                                                 &ddsCaps,
1850                                                 GDISurface);
1851     if(hr != DD_OK)
1852     {
1853         ERR("IDirectDrawSurface7::GetAttachedSurface failed, hr = %x\n", hr);
1854     }
1855
1856     /* The AddRef is OK this time */
1857     LeaveCriticalSection(&ddraw_cs);
1858     return hr;
1859 }
1860
1861 static HRESULT WINAPI ddraw4_GetGDISurface(IDirectDraw4 *iface, IDirectDrawSurface4 **surface)
1862 {
1863     TRACE("iface %p, surface %p.\n", iface, surface);
1864
1865     return ddraw7_GetGDISurface((IDirectDraw7 *)ddraw_from_ddraw4(iface), (IDirectDrawSurface7 **)surface);
1866 }
1867
1868 static HRESULT WINAPI ddraw3_GetGDISurface(IDirectDraw3 *iface, IDirectDrawSurface **surface)
1869 {
1870     IDirectDrawSurface7 *surface7;
1871     HRESULT hr;
1872
1873     TRACE("iface %p, surface %p.\n", iface, surface);
1874
1875     hr = ddraw7_GetGDISurface((IDirectDraw7 *)ddraw_from_ddraw3(iface), &surface7);
1876     *surface = surface7 ? (IDirectDrawSurface *)&((IDirectDrawSurfaceImpl *)surface7)->IDirectDrawSurface3_vtbl : NULL;
1877
1878     return hr;
1879 }
1880
1881 static HRESULT WINAPI ddraw2_GetGDISurface(IDirectDraw2 *iface, IDirectDrawSurface **surface)
1882 {
1883     IDirectDrawSurface7 *surface7;
1884     HRESULT hr;
1885
1886     TRACE("iface %p, surface %p.\n", iface, surface);
1887
1888     hr = ddraw7_GetGDISurface((IDirectDraw7 *)ddraw_from_ddraw2(iface), &surface7);
1889     *surface = surface7 ? (IDirectDrawSurface *)&((IDirectDrawSurfaceImpl *)surface7)->IDirectDrawSurface3_vtbl : NULL;
1890
1891     return hr;
1892 }
1893
1894 static HRESULT WINAPI ddraw1_GetGDISurface(IDirectDraw *iface, IDirectDrawSurface **surface)
1895 {
1896     IDirectDrawSurface7 *surface7;
1897     HRESULT hr;
1898
1899     TRACE("iface %p, surface %p.\n", iface, surface);
1900
1901     hr = ddraw7_GetGDISurface((IDirectDraw7 *)ddraw_from_ddraw1(iface), &surface7);
1902     *surface = surface7 ? (IDirectDrawSurface *)&((IDirectDrawSurfaceImpl *)surface7)->IDirectDrawSurface3_vtbl : NULL;
1903
1904     return hr;
1905 }
1906
1907 struct displaymodescallback_context
1908 {
1909     LPDDENUMMODESCALLBACK func;
1910     void *context;
1911 };
1912
1913 static HRESULT CALLBACK EnumDisplayModesCallbackThunk(DDSURFACEDESC2 *surface_desc, void *context)
1914 {
1915     struct displaymodescallback_context *cbcontext = context;
1916     DDSURFACEDESC desc;
1917
1918     memcpy(&desc, surface_desc, sizeof(desc));
1919     desc.dwSize = sizeof(desc);
1920
1921     return cbcontext->func(&desc, cbcontext->context);
1922 }
1923
1924 /*****************************************************************************
1925  * IDirectDraw7::EnumDisplayModes
1926  *
1927  * Enumerates the supported Display modes. The modes can be filtered with
1928  * the DDSD parameter.
1929  *
1930  * Params:
1931  *  Flags: can be DDEDM_REFRESHRATES and DDEDM_STANDARDVGAMODES
1932  *  DDSD: Surface description to filter the modes
1933  *  Context: Pointer passed back to the callback function
1934  *  cb: Application-provided callback function
1935  *
1936  * Returns:
1937  *  DD_OK on success
1938  *  DDERR_INVALIDPARAMS if the callback wasn't set
1939  *
1940  *****************************************************************************/
1941 static HRESULT WINAPI ddraw7_EnumDisplayModes(IDirectDraw7 *iface, DWORD Flags,
1942         DDSURFACEDESC2 *DDSD, void *Context, LPDDENUMMODESCALLBACK2 cb)
1943 {
1944     IDirectDrawImpl *This = (IDirectDrawImpl *)iface;
1945     unsigned int modenum, fmt;
1946     WINED3DFORMAT pixelformat = WINED3DFMT_UNKNOWN;
1947     WINED3DDISPLAYMODE mode;
1948     DDSURFACEDESC2 callback_sd;
1949     WINED3DDISPLAYMODE *enum_modes = NULL;
1950     unsigned enum_mode_count = 0, enum_mode_array_size = 0;
1951
1952     static const WINED3DFORMAT checkFormatList[] =
1953     {
1954         WINED3DFMT_B8G8R8X8_UNORM,
1955         WINED3DFMT_B5G6R5_UNORM,
1956         WINED3DFMT_P8_UINT,
1957     };
1958
1959     TRACE("iface %p, flags %#x, surface_desc %p, context %p, callback %p.\n",
1960             iface, Flags, DDSD, Context, cb);
1961
1962     EnterCriticalSection(&ddraw_cs);
1963     /* This looks sane */
1964     if(!cb)
1965     {
1966         LeaveCriticalSection(&ddraw_cs);
1967         return DDERR_INVALIDPARAMS;
1968     }
1969
1970     if(DDSD)
1971     {
1972         if ((DDSD->dwFlags & DDSD_PIXELFORMAT) && (DDSD->u4.ddpfPixelFormat.dwFlags & DDPF_RGB) )
1973             pixelformat = PixelFormat_DD2WineD3D(&DDSD->u4.ddpfPixelFormat);
1974     }
1975
1976     if(!(Flags & DDEDM_REFRESHRATES))
1977     {
1978         enum_mode_array_size = 16;
1979         enum_modes = HeapAlloc(GetProcessHeap(), 0, sizeof(WINED3DDISPLAYMODE) * enum_mode_array_size);
1980         if (!enum_modes)
1981         {
1982             ERR("Out of memory\n");
1983             LeaveCriticalSection(&ddraw_cs);
1984             return DDERR_OUTOFMEMORY;
1985         }
1986     }
1987
1988     for(fmt = 0; fmt < (sizeof(checkFormatList) / sizeof(checkFormatList[0])); fmt++)
1989     {
1990         if(pixelformat != WINED3DFMT_UNKNOWN && checkFormatList[fmt] != pixelformat)
1991         {
1992             continue;
1993         }
1994
1995         modenum = 0;
1996         while(IWineD3D_EnumAdapterModes(This->wineD3D,
1997                                         WINED3DADAPTER_DEFAULT,
1998                                         checkFormatList[fmt],
1999                                         modenum++,
2000                                         &mode) == WINED3D_OK)
2001         {
2002             if(DDSD)
2003             {
2004                 if(DDSD->dwFlags & DDSD_WIDTH && mode.Width != DDSD->dwWidth) continue;
2005                 if(DDSD->dwFlags & DDSD_HEIGHT && mode.Height != DDSD->dwHeight) continue;
2006             }
2007
2008             if(!(Flags & DDEDM_REFRESHRATES))
2009             {
2010                 /* DX docs state EnumDisplayMode should return only unique modes. If DDEDM_REFRESHRATES is not set, refresh
2011                  * rate doesn't matter when determining if the mode is unique. So modes only differing in refresh rate have
2012                  * to be reduced to a single unique result in such case.
2013                  */
2014                 BOOL found = FALSE;
2015                 unsigned i;
2016
2017                 for (i = 0; i < enum_mode_count; i++)
2018                 {
2019                     if(enum_modes[i].Width == mode.Width && enum_modes[i].Height == mode.Height &&
2020                        enum_modes[i].Format == mode.Format)
2021                     {
2022                         found = TRUE;
2023                         break;
2024                     }
2025                 }
2026
2027                 if(found) continue;
2028             }
2029
2030             memset(&callback_sd, 0, sizeof(callback_sd));
2031             callback_sd.dwSize = sizeof(callback_sd);
2032             callback_sd.u4.ddpfPixelFormat.dwSize = sizeof(DDPIXELFORMAT);
2033
2034             callback_sd.dwFlags = DDSD_HEIGHT|DDSD_WIDTH|DDSD_PIXELFORMAT|DDSD_PITCH;
2035             if(Flags & DDEDM_REFRESHRATES)
2036             {
2037                 callback_sd.dwFlags |= DDSD_REFRESHRATE;
2038                 callback_sd.u2.dwRefreshRate = mode.RefreshRate;
2039             }
2040
2041             callback_sd.dwWidth = mode.Width;
2042             callback_sd.dwHeight = mode.Height;
2043
2044             PixelFormat_WineD3DtoDD(&callback_sd.u4.ddpfPixelFormat, mode.Format);
2045
2046             /* Calc pitch and DWORD align like MSDN says */
2047             callback_sd.u1.lPitch = (callback_sd.u4.ddpfPixelFormat.u1.dwRGBBitCount / 8) * mode.Width;
2048             callback_sd.u1.lPitch = (callback_sd.u1.lPitch + 3) & ~3;
2049
2050             TRACE("Enumerating %dx%dx%d @%d\n", callback_sd.dwWidth, callback_sd.dwHeight, callback_sd.u4.ddpfPixelFormat.u1.dwRGBBitCount,
2051               callback_sd.u2.dwRefreshRate);
2052
2053             if(cb(&callback_sd, Context) == DDENUMRET_CANCEL)
2054             {
2055                 TRACE("Application asked to terminate the enumeration\n");
2056                 HeapFree(GetProcessHeap(), 0, enum_modes);
2057                 LeaveCriticalSection(&ddraw_cs);
2058                 return DD_OK;
2059             }
2060
2061             if(!(Flags & DDEDM_REFRESHRATES))
2062             {
2063                 if (enum_mode_count == enum_mode_array_size)
2064                 {
2065                     WINED3DDISPLAYMODE *new_enum_modes;
2066
2067                     enum_mode_array_size *= 2;
2068                     new_enum_modes = HeapReAlloc(GetProcessHeap(), 0, enum_modes, sizeof(WINED3DDISPLAYMODE) * enum_mode_array_size);
2069
2070                     if (!new_enum_modes)
2071                     {
2072                         ERR("Out of memory\n");
2073                         HeapFree(GetProcessHeap(), 0, enum_modes);
2074                         LeaveCriticalSection(&ddraw_cs);
2075                         return DDERR_OUTOFMEMORY;
2076                     }
2077
2078                     enum_modes = new_enum_modes;
2079                 }
2080
2081                 enum_modes[enum_mode_count++] = mode;
2082             }
2083         }
2084     }
2085
2086     TRACE("End of enumeration\n");
2087     HeapFree(GetProcessHeap(), 0, enum_modes);
2088     LeaveCriticalSection(&ddraw_cs);
2089     return DD_OK;
2090 }
2091
2092 static HRESULT WINAPI ddraw4_EnumDisplayModes(IDirectDraw4 *iface, DWORD flags,
2093         DDSURFACEDESC2 *surface_desc, void *context, LPDDENUMMODESCALLBACK2 callback)
2094 {
2095     TRACE("iface %p, flags %#x, surface_desc %p, context %p, callback %p.\n",
2096             iface, flags, surface_desc, context, callback);
2097
2098     return ddraw7_EnumDisplayModes((IDirectDraw7 *)ddraw_from_ddraw4(iface), flags,
2099             surface_desc, context, callback);
2100 }
2101
2102 static HRESULT WINAPI ddraw3_EnumDisplayModes(IDirectDraw3 *iface, DWORD flags,
2103         DDSURFACEDESC *surface_desc, void *context, LPDDENUMMODESCALLBACK callback)
2104 {
2105     struct displaymodescallback_context cbcontext;
2106
2107     TRACE("iface %p, flags %#x, surface_desc %p, context %p, callback %p.\n",
2108             iface, flags, surface_desc, context, callback);
2109
2110     cbcontext.func = callback;
2111     cbcontext.context = context;
2112
2113     return ddraw7_EnumDisplayModes((IDirectDraw7 *)ddraw_from_ddraw3(iface), flags,
2114             (DDSURFACEDESC2 *)surface_desc, &cbcontext, EnumDisplayModesCallbackThunk);
2115 }
2116
2117 static HRESULT WINAPI ddraw2_EnumDisplayModes(IDirectDraw2 *iface, DWORD flags,
2118         DDSURFACEDESC *surface_desc, void *context, LPDDENUMMODESCALLBACK callback)
2119 {
2120     struct displaymodescallback_context cbcontext;
2121
2122     TRACE("iface %p, flags %#x, surface_desc %p, context %p, callback %p.\n",
2123             iface, flags, surface_desc, context, callback);
2124
2125     cbcontext.func = callback;
2126     cbcontext.context = context;
2127
2128     return ddraw7_EnumDisplayModes((IDirectDraw7 *)ddraw_from_ddraw2(iface), flags,
2129             (DDSURFACEDESC2 *)surface_desc, &cbcontext, EnumDisplayModesCallbackThunk);
2130 }
2131
2132 static HRESULT WINAPI ddraw1_EnumDisplayModes(IDirectDraw *iface, DWORD flags,
2133         DDSURFACEDESC *surface_desc, void *context, LPDDENUMMODESCALLBACK callback)
2134 {
2135     struct displaymodescallback_context cbcontext;
2136
2137     TRACE("iface %p, flags %#x, surface_desc %p, context %p, callback %p.\n",
2138             iface, flags, surface_desc, context, callback);
2139
2140     cbcontext.func = callback;
2141     cbcontext.context = context;
2142
2143     return ddraw7_EnumDisplayModes((IDirectDraw7 *)ddraw_from_ddraw1(iface), flags,
2144             (DDSURFACEDESC2 *)surface_desc, &cbcontext, EnumDisplayModesCallbackThunk);
2145 }
2146
2147 /*****************************************************************************
2148  * IDirectDraw7::EvaluateMode
2149  *
2150  * Used with IDirectDraw7::StartModeTest to test video modes.
2151  * EvaluateMode is used to pass or fail a mode, and continue with the next
2152  * mode
2153  *
2154  * Params:
2155  *  Flags: DDEM_MODEPASSED or DDEM_MODEFAILED
2156  *  Timeout: Returns the amount of seconds left before the mode would have
2157  *           been failed automatically
2158  *
2159  * Returns:
2160  *  This implementation always DD_OK, because it's a stub
2161  *
2162  *****************************************************************************/
2163 static HRESULT WINAPI ddraw7_EvaluateMode(IDirectDraw7 *iface, DWORD Flags, DWORD *Timeout)
2164 {
2165     FIXME("iface %p, flags %#x, timeout %p stub!\n", iface, Flags, Timeout);
2166
2167     /* When implementing this, implement it in WineD3D */
2168
2169     return DD_OK;
2170 }
2171
2172 /*****************************************************************************
2173  * IDirectDraw7::GetDeviceIdentifier
2174  *
2175  * Returns the device identifier, which gives information about the driver
2176  * Our device identifier is defined at the beginning of this file.
2177  *
2178  * Params:
2179  *  DDDI: Address for the returned structure
2180  *  Flags: Can be DDGDI_GETHOSTIDENTIFIER
2181  *
2182  * Returns:
2183  *  On success it returns DD_OK
2184  *  DDERR_INVALIDPARAMS if DDDI is NULL
2185  *
2186  *****************************************************************************/
2187 static HRESULT WINAPI ddraw7_GetDeviceIdentifier(IDirectDraw7 *iface,
2188         DDDEVICEIDENTIFIER2 *DDDI, DWORD Flags)
2189 {
2190     TRACE("iface %p, device_identifier %p, flags %#x.\n", iface, DDDI, Flags);
2191
2192     if(!DDDI)
2193         return DDERR_INVALIDPARAMS;
2194
2195     /* The DDGDI_GETHOSTIDENTIFIER returns the information about the 2D
2196      * host adapter, if there's a secondary 3D adapter. This doesn't apply
2197      * to any modern hardware, nor is it interesting for Wine, so ignore it.
2198      * Size of DDDEVICEIDENTIFIER2 may be aligned to 8 bytes and thus 4
2199      * bytes too long. So only copy the relevant part of the structure
2200      */
2201
2202     memcpy(DDDI, &deviceidentifier, FIELD_OFFSET(DDDEVICEIDENTIFIER2, dwWHQLLevel) + sizeof(DWORD));
2203     return DD_OK;
2204 }
2205
2206 static HRESULT WINAPI ddraw4_GetDeviceIdentifier(IDirectDraw4 *iface,
2207         DDDEVICEIDENTIFIER *identifier, DWORD flags)
2208 {
2209     DDDEVICEIDENTIFIER2 identifier2;
2210     HRESULT hr;
2211
2212     TRACE("iface %p, identifier %p, flags %#x.\n", iface, identifier, flags);
2213
2214     hr = ddraw7_GetDeviceIdentifier((IDirectDraw7 *)ddraw_from_ddraw4(iface), &identifier2, flags);
2215     DDRAW_Convert_DDDEVICEIDENTIFIER_2_To_1(&identifier2, identifier);
2216
2217     return hr;
2218 }
2219
2220 /*****************************************************************************
2221  * IDirectDraw7::GetSurfaceFromDC
2222  *
2223  * Returns the Surface for a GDI device context handle.
2224  * Is this related to IDirectDrawSurface::GetDC ???
2225  *
2226  * Params:
2227  *  hdc: hdc to return the surface for
2228  *  Surface: Address to write the surface pointer to
2229  *
2230  * Returns:
2231  *  Always returns DD_OK because it's a stub
2232  *
2233  *****************************************************************************/
2234 static HRESULT WINAPI ddraw7_GetSurfaceFromDC(IDirectDraw7 *iface, HDC hdc, IDirectDrawSurface7 **Surface)
2235 {
2236     IDirectDrawImpl *This = (IDirectDrawImpl *)iface;
2237     IWineD3DSurface *wined3d_surface;
2238     HRESULT hr;
2239
2240     TRACE("iface %p, dc %p, surface %p.\n", iface, hdc, Surface);
2241
2242     if (!Surface) return E_INVALIDARG;
2243
2244     hr = IWineD3DDevice_GetSurfaceFromDC(This->wineD3DDevice, hdc, &wined3d_surface);
2245     if (FAILED(hr))
2246     {
2247         TRACE("No surface found for dc %p.\n", hdc);
2248         *Surface = NULL;
2249         return DDERR_NOTFOUND;
2250     }
2251
2252     IWineD3DSurface_GetParent(wined3d_surface, (IUnknown **)Surface);
2253     TRACE("Returning surface %p.\n", Surface);
2254     return DD_OK;
2255 }
2256
2257 static HRESULT WINAPI ddraw4_GetSurfaceFromDC(IDirectDraw4 *iface, HDC dc, IDirectDrawSurface4 **surface)
2258 {
2259     IDirectDrawSurface7 *surface7;
2260     HRESULT hr;
2261
2262     TRACE("iface %p, dc %p, surface %p.\n", iface, dc, surface);
2263
2264     if (!surface) return E_INVALIDARG;
2265
2266     hr = ddraw7_GetSurfaceFromDC((IDirectDraw7 *)ddraw_from_ddraw4(iface), dc, &surface7);
2267     *surface = surface7 ? (IDirectDrawSurface4 *)&((IDirectDrawSurfaceImpl *)surface7)->IDirectDrawSurface3_vtbl : NULL;
2268
2269     return hr;
2270 }
2271
2272 static HRESULT WINAPI ddraw3_GetSurfaceFromDC(IDirectDraw3 *iface, HDC dc, IDirectDrawSurface **surface)
2273 {
2274     TRACE("iface %p, dc %p, surface %p.\n", iface, dc, surface);
2275
2276     return ddraw7_GetSurfaceFromDC((IDirectDraw7 *)ddraw_from_ddraw3(iface),
2277             dc, (IDirectDrawSurface7 **)surface);
2278 }
2279
2280 /*****************************************************************************
2281  * IDirectDraw7::RestoreAllSurfaces
2282  *
2283  * Calls the restore method of all surfaces
2284  *
2285  * Params:
2286  *
2287  * Returns:
2288  *  Always returns DD_OK because it's a stub
2289  *
2290  *****************************************************************************/
2291 static HRESULT WINAPI ddraw7_RestoreAllSurfaces(IDirectDraw7 *iface)
2292 {
2293     FIXME("iface %p stub!\n", iface);
2294
2295     /* This isn't hard to implement: Enumerate all WineD3D surfaces,
2296      * get their parent and call their restore method. Do not implement
2297      * it in WineD3D, as restoring a surface means re-creating the
2298      * WineD3DDSurface
2299      */
2300     return DD_OK;
2301 }
2302
2303 static HRESULT WINAPI ddraw4_RestoreAllSurfaces(IDirectDraw4 *iface)
2304 {
2305     TRACE("iface %p.\n", iface);
2306
2307     return ddraw7_RestoreAllSurfaces((IDirectDraw7 *)ddraw_from_ddraw4(iface));
2308 }
2309
2310 /*****************************************************************************
2311  * IDirectDraw7::StartModeTest
2312  *
2313  * Tests the specified video modes to update the system registry with
2314  * refresh rate information. StartModeTest starts the mode test,
2315  * EvaluateMode is used to fail or pass a mode. If EvaluateMode
2316  * isn't called within 15 seconds, the mode is failed automatically
2317  *
2318  * As refresh rates are handled by the X server, I don't think this
2319  * Method is important
2320  *
2321  * Params:
2322  *  Modes: An array of mode specifications
2323  *  NumModes: The number of modes in Modes
2324  *  Flags: Some flags...
2325  *
2326  * Returns:
2327  *  Returns DDERR_TESTFINISHED if flags contains DDSMT_ISTESTREQUIRED,
2328  *  if no modes are passed, DDERR_INVALIDPARAMS is returned,
2329  *  otherwise DD_OK
2330  *
2331  *****************************************************************************/
2332 static HRESULT WINAPI ddraw7_StartModeTest(IDirectDraw7 *iface, SIZE *Modes, DWORD NumModes, DWORD Flags)
2333 {
2334     FIXME("iface %p, modes %p, mode_count %u, flags %#x partial stub!\n",
2335             iface, Modes, NumModes, Flags);
2336
2337     /* This looks sane */
2338     if( (!Modes) || (NumModes == 0) ) return DDERR_INVALIDPARAMS;
2339
2340     /* DDSMT_ISTESTREQUIRED asks if a mode test is necessary.
2341      * As it is not, DDERR_TESTFINISHED is returned
2342      * (hopefully that's correct
2343      *
2344     if(Flags & DDSMT_ISTESTREQUIRED) return DDERR_TESTFINISHED;
2345      * well, that value doesn't (yet) exist in the wine headers, so ignore it
2346      */
2347
2348     return DD_OK;
2349 }
2350
2351 /*****************************************************************************
2352  * ddraw_recreate_surfaces_cb
2353  *
2354  * Enumeration callback for ddraw_recreate_surface.
2355  * It re-recreates the WineD3DSurface. It's pretty straightforward
2356  *
2357  *****************************************************************************/
2358 HRESULT WINAPI ddraw_recreate_surfaces_cb(IDirectDrawSurface7 *surf, DDSURFACEDESC2 *desc, void *Context)
2359 {
2360     IDirectDrawSurfaceImpl *surfImpl = (IDirectDrawSurfaceImpl *)surf;
2361     IDirectDrawImpl *This = surfImpl->ddraw;
2362     IUnknown *Parent;
2363     IWineD3DSurface *wineD3DSurface;
2364     IWineD3DSwapChain *swapchain;
2365     HRESULT hr;
2366     IWineD3DClipper *clipper = NULL;
2367
2368     WINED3DSURFACE_DESC     Desc;
2369     WINED3DFORMAT           Format;
2370     DWORD                   Usage;
2371     WINED3DPOOL             Pool;
2372
2373     WINED3DMULTISAMPLE_TYPE MultiSampleType;
2374     DWORD                   MultiSampleQuality;
2375     UINT                    Width;
2376     UINT                    Height;
2377
2378     TRACE("surface %p, surface_desc %p, context %p.\n",
2379             surf, desc, Context);
2380
2381     /* For the enumeration */
2382     IDirectDrawSurface7_Release(surf);
2383
2384     if(surfImpl->ImplType == This->ImplType) return DDENUMRET_OK; /* Continue */
2385
2386     /* Get the objects */
2387     swapchain = surfImpl->wineD3DSwapChain;
2388     surfImpl->wineD3DSwapChain = NULL;
2389     wineD3DSurface = surfImpl->WineD3DSurface;
2390
2391     /* get the clipper */
2392     IWineD3DSurface_GetClipper(wineD3DSurface, &clipper);
2393
2394     /* Get the surface properties */
2395     hr = IWineD3DSurface_GetDesc(wineD3DSurface, &Desc);
2396     if(hr != D3D_OK) return hr;
2397
2398     Format = Desc.format;
2399     Usage = Desc.usage;
2400     Pool = Desc.pool;
2401     MultiSampleType = Desc.multisample_type;
2402     MultiSampleQuality = Desc.multisample_quality;
2403     Width = Desc.width;
2404     Height = Desc.height;
2405
2406     IWineD3DSurface_GetParent(wineD3DSurface, &Parent);
2407
2408     /* Create the new surface */
2409     hr = IWineD3DDevice_CreateSurface(This->wineD3DDevice, Width, Height, Format,
2410             TRUE /* Lockable */, FALSE /* Discard */, surfImpl->mipmap_level, &surfImpl->WineD3DSurface, Usage, Pool,
2411             MultiSampleType, MultiSampleQuality, This->ImplType, Parent, &ddraw_null_wined3d_parent_ops);
2412     IUnknown_Release(Parent);
2413     if (FAILED(hr))
2414     {
2415         surfImpl->WineD3DSurface = wineD3DSurface;
2416         return hr;
2417     }
2418
2419     IWineD3DSurface_SetClipper(surfImpl->WineD3DSurface, clipper);
2420
2421     /* TODO: Copy the surface content, except for render targets */
2422
2423     /* If there's a swapchain, it owns the wined3d surfaces. So Destroy
2424      * the swapchain
2425      */
2426     if(swapchain) {
2427         /* The backbuffers have the swapchain set as well, but the primary
2428          * owns it and destroys it
2429          */
2430         if(surfImpl->surface_desc.ddsCaps.dwCaps & DDSCAPS_PRIMARYSURFACE) {
2431             IWineD3DDevice_UninitGDI(This->wineD3DDevice, D3D7CB_DestroySwapChain);
2432         }
2433         surfImpl->isRenderTarget = FALSE;
2434     } else {
2435         if(IWineD3DSurface_Release(wineD3DSurface) == 0)
2436             TRACE("Surface released successful, next surface\n");
2437         else
2438             ERR("Something's still holding the old WineD3DSurface\n");
2439     }
2440
2441     surfImpl->ImplType = This->ImplType;
2442
2443     if(clipper)
2444     {
2445         IWineD3DClipper_Release(clipper);
2446     }
2447     return DDENUMRET_OK;
2448 }
2449
2450 /*****************************************************************************
2451  * ddraw_recreate_surfaces
2452  *
2453  * A function, that converts all wineD3DSurfaces to the new implementation type
2454  * It enumerates all surfaces with IWineD3DDevice::EnumSurfaces, creates a
2455  * new WineD3DSurface, copies the content and releases the old surface
2456  *
2457  *****************************************************************************/
2458 static HRESULT ddraw_recreate_surfaces(IDirectDrawImpl *This)
2459 {
2460     DDSURFACEDESC2 desc;
2461     TRACE("(%p): Switch to implementation %d\n", This, This->ImplType);
2462
2463     if(This->ImplType != SURFACE_OPENGL && This->d3d_initialized)
2464     {
2465         /* Should happen almost never */
2466         FIXME("(%p) Switching to non-opengl surfaces with d3d started. Is this a bug?\n", This);
2467         /* Shutdown d3d */
2468         IWineD3DDevice_Uninit3D(This->wineD3DDevice, D3D7CB_DestroySwapChain);
2469     }
2470     /* Contrary: D3D starting is handled by the caller, because it knows the render target */
2471
2472     memset(&desc, 0, sizeof(desc));
2473     desc.dwSize = sizeof(desc);
2474
2475     return IDirectDraw7_EnumSurfaces((IDirectDraw7 *)This, 0, &desc, This, ddraw_recreate_surfaces_cb);
2476 }
2477
2478 ULONG WINAPI D3D7CB_DestroySwapChain(IWineD3DSwapChain *pSwapChain) {
2479     IUnknown* swapChainParent;
2480
2481     TRACE("swapchain %p.\n", pSwapChain);
2482
2483     IWineD3DSwapChain_GetParent(pSwapChain, &swapChainParent);
2484     IUnknown_Release(swapChainParent);
2485     return IUnknown_Release(swapChainParent);
2486 }
2487
2488 /*****************************************************************************
2489  * ddraw_create_surface
2490  *
2491  * A helper function for IDirectDraw7::CreateSurface. It creates a new surface
2492  * with the passed parameters.
2493  *
2494  * Params:
2495  *  DDSD: Description of the surface to create
2496  *  Surf: Address to store the interface pointer at
2497  *
2498  * Returns:
2499  *  DD_OK on success
2500  *
2501  *****************************************************************************/
2502 static HRESULT ddraw_create_surface(IDirectDrawImpl *This, DDSURFACEDESC2 *pDDSD,
2503         IDirectDrawSurfaceImpl **ppSurf, UINT level)
2504 {
2505     WINED3DSURFTYPE ImplType = This->ImplType;
2506     HRESULT hr;
2507
2508     TRACE("ddraw %p, surface_desc %p, surface %p, level %u.\n",
2509             This, pDDSD, ppSurf, level);
2510
2511     if (TRACE_ON(ddraw))
2512     {
2513         TRACE(" (%p) Requesting surface desc :\n", This);
2514         DDRAW_dump_surface_desc(pDDSD);
2515     }
2516
2517     /* Select the surface type, if it wasn't choosen yet */
2518     if(ImplType == SURFACE_UNKNOWN)
2519     {
2520         /* Use GL Surfaces if a D3DDEVICE Surface is requested */
2521         if(pDDSD->ddsCaps.dwCaps & DDSCAPS_3DDEVICE)
2522         {
2523             TRACE("(%p) Choosing GL surfaces because a 3DDEVICE Surface was requested\n", This);
2524             ImplType = SURFACE_OPENGL;
2525         }
2526
2527         /* Otherwise use GDI surfaces for now */
2528         else
2529         {
2530             TRACE("(%p) Choosing GDI surfaces for 2D rendering\n", This);
2531             ImplType = SURFACE_GDI;
2532         }
2533
2534         /* Policy if all surface implementations are available:
2535          * First, check if a default type was set with winecfg. If not,
2536          * try Xrender surfaces, and use them if they work. Next, check if
2537          * accelerated OpenGL is available, and use GL surfaces in this
2538          * case. If all else fails, use GDI surfaces. If a 3DDEVICE surface
2539          * was created, always use OpenGL surfaces.
2540          *
2541          * (Note: Xrender surfaces are not implemented for now, the
2542          * unaccelerated implementation uses GDI to render in Software)
2543          */
2544
2545         /* Store the type. If it needs to be changed, all WineD3DSurfaces have to
2546          * be re-created. This could be done with IDirectDrawSurface7::Restore
2547          */
2548         This->ImplType = ImplType;
2549     }
2550     else
2551     {
2552         if ((pDDSD->ddsCaps.dwCaps & DDSCAPS_3DDEVICE)
2553                 && (This->ImplType != SURFACE_OPENGL)
2554                 && DefaultSurfaceType == SURFACE_UNKNOWN)
2555         {
2556             /* We have to change to OpenGL,
2557              * and re-create all WineD3DSurfaces
2558              */
2559             ImplType = SURFACE_OPENGL;
2560             This->ImplType = ImplType;
2561             TRACE("(%p) Re-creating all surfaces\n", This);
2562             ddraw_recreate_surfaces(This);
2563             TRACE("(%p) Done recreating all surfaces\n", This);
2564         }
2565         else if(This->ImplType != SURFACE_OPENGL && pDDSD->ddsCaps.dwCaps & DDSCAPS_3DDEVICE)
2566         {
2567             WARN("The application requests a 3D capable surface, but a non-opengl surface was set in the registry\n");
2568             /* Do not fail surface creation, only fail 3D device creation */
2569         }
2570     }
2571
2572     /* Create the Surface object */
2573     *ppSurf = HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, sizeof(IDirectDrawSurfaceImpl));
2574     if(!*ppSurf)
2575     {
2576         ERR("(%p) Error allocating memory for a surface\n", This);
2577         return DDERR_OUTOFVIDEOMEMORY;
2578     }
2579
2580     hr = ddraw_surface_init(*ppSurf, This, pDDSD, level, ImplType);
2581     if (FAILED(hr))
2582     {
2583         WARN("Failed to initialize surface, hr %#x.\n", hr);
2584         HeapFree(GetProcessHeap(), 0, *ppSurf);
2585         return hr;
2586     }
2587
2588     /* Increase the surface counter, and attach the surface */
2589     InterlockedIncrement(&This->surfaces);
2590     list_add_head(&This->surface_list, &(*ppSurf)->surface_list_entry);
2591
2592     TRACE("Created surface %p.\n", *ppSurf);
2593
2594     return DD_OK;
2595 }
2596 /*****************************************************************************
2597  * CreateAdditionalSurfaces
2598  *
2599  * Creates a new mipmap chain.
2600  *
2601  * Params:
2602  *  root: Root surface to attach the newly created chain to
2603  *  count: number of surfaces to create
2604  *  DDSD: Description of the surface. Intentionally not a pointer to avoid side
2605  *        effects on the caller
2606  *  CubeFaceRoot: Whether the new surface is a root of a cube map face. This
2607  *                creates an additional surface without the mipmapping flags
2608  *
2609  *****************************************************************************/
2610 static HRESULT
2611 CreateAdditionalSurfaces(IDirectDrawImpl *This,
2612                          IDirectDrawSurfaceImpl *root,
2613                          UINT count,
2614                          DDSURFACEDESC2 DDSD,
2615                          BOOL CubeFaceRoot)
2616 {
2617     UINT i, j, level = 0;
2618     HRESULT hr;
2619     IDirectDrawSurfaceImpl *last = root;
2620
2621     for(i = 0; i < count; i++)
2622     {
2623         IDirectDrawSurfaceImpl *object2 = NULL;
2624
2625         /* increase the mipmap level, but only if a mipmap is created
2626          * In this case, also halve the size
2627          */
2628         if(DDSD.ddsCaps.dwCaps & DDSCAPS_MIPMAP && !CubeFaceRoot)
2629         {
2630             level++;
2631             if(DDSD.dwWidth > 1) DDSD.dwWidth /= 2;
2632             if(DDSD.dwHeight > 1) DDSD.dwHeight /= 2;
2633             /* Set the mipmap sublevel flag according to msdn */
2634             DDSD.ddsCaps.dwCaps2 |= DDSCAPS2_MIPMAPSUBLEVEL;
2635         }
2636         else
2637         {
2638             DDSD.ddsCaps.dwCaps2 &= ~DDSCAPS2_MIPMAPSUBLEVEL;
2639         }
2640         CubeFaceRoot = FALSE;
2641
2642         hr = ddraw_create_surface(This, &DDSD, &object2, level);
2643         if(hr != DD_OK)
2644         {
2645             return hr;
2646         }
2647
2648         /* Add the new surface to the complex attachment array */
2649         for(j = 0; j < MAX_COMPLEX_ATTACHED; j++)
2650         {
2651             if(last->complex_array[j]) continue;
2652             last->complex_array[j] = object2;
2653             break;
2654         }
2655         last = object2;
2656
2657         /* Remove the (possible) back buffer cap from the new surface description,
2658          * because only one surface in the flipping chain is a back buffer, one
2659          * is a front buffer, the others are just primary surfaces.
2660          */
2661         DDSD.ddsCaps.dwCaps &= ~DDSCAPS_BACKBUFFER;
2662     }
2663     return DD_OK;
2664 }
2665
2666 /* Must set all attached surfaces (e.g. mipmaps) versions as well */
2667 static void ddraw_set_surface_version(IDirectDrawSurfaceImpl *surface, UINT version)
2668 {
2669     unsigned int i;
2670
2671     TRACE("surface %p, version %u -> %u.\n", surface, surface->version, version);
2672
2673     surface->version = version;
2674     for (i = 0; i < MAX_COMPLEX_ATTACHED; ++i)
2675     {
2676         if (!surface->complex_array[i]) break;
2677         ddraw_set_surface_version(surface->complex_array[i], version);
2678     }
2679     while ((surface = surface->next_attached))
2680     {
2681         ddraw_set_surface_version(surface, version);
2682     }
2683 }
2684
2685 /*****************************************************************************
2686  * ddraw_attach_d3d_device
2687  *
2688  * Initializes the D3D capabilities of WineD3D
2689  *
2690  * Params:
2691  *  primary: The primary surface for D3D
2692  *
2693  * Returns
2694  *  DD_OK on success,
2695  *  DDERR_* otherwise
2696  *
2697  *****************************************************************************/
2698 static HRESULT ddraw_attach_d3d_device(IDirectDrawImpl *ddraw, IDirectDrawSurfaceImpl *primary)
2699 {
2700     WINED3DPRESENT_PARAMETERS localParameters;
2701     HWND window = ddraw->dest_window;
2702     HRESULT hr;
2703
2704     TRACE("ddraw %p, primary %p.\n", ddraw, primary);
2705
2706     if (!window || window == GetDesktopWindow())
2707     {
2708         window = CreateWindowExA(0, DDRAW_WINDOW_CLASS_NAME, "Hidden D3D Window",
2709                 WS_DISABLED, 0, 0, GetSystemMetrics(SM_CXSCREEN), GetSystemMetrics(SM_CYSCREEN),
2710                 NULL, NULL, NULL, NULL);
2711         if (!window)
2712         {
2713             ERR("Failed to create window, last error %#x.\n", GetLastError());
2714             return E_FAIL;
2715         }
2716
2717         ShowWindow(window, SW_HIDE);   /* Just to be sure */
2718         WARN("No window for the Direct3DDevice, created hidden window %p.\n", window);
2719     }
2720     else
2721     {
2722         TRACE("Using existing window %p for Direct3D rendering.\n", window);
2723     }
2724     ddraw->d3d_window = window;
2725
2726     /* Store the future Render Target surface */
2727     ddraw->d3d_target = primary;
2728
2729     /* Use the surface description for the device parameters, not the device
2730      * settings. The application might render to an offscreen surface. */
2731     localParameters.BackBufferWidth = primary->surface_desc.dwWidth;
2732     localParameters.BackBufferHeight = primary->surface_desc.dwHeight;
2733     localParameters.BackBufferFormat = PixelFormat_DD2WineD3D(&primary->surface_desc.u4.ddpfPixelFormat);
2734     localParameters.BackBufferCount = (primary->surface_desc.dwFlags & DDSD_BACKBUFFERCOUNT)
2735             ? primary->surface_desc.dwBackBufferCount : 0;
2736     localParameters.MultiSampleType = WINED3DMULTISAMPLE_NONE;
2737     localParameters.MultiSampleQuality = 0;
2738     localParameters.SwapEffect = WINED3DSWAPEFFECT_COPY;
2739     localParameters.hDeviceWindow = window;
2740     localParameters.Windowed = !(ddraw->cooperative_level & DDSCL_FULLSCREEN);
2741     localParameters.EnableAutoDepthStencil = TRUE;
2742     localParameters.AutoDepthStencilFormat = WINED3DFMT_D16_UNORM;
2743     localParameters.Flags = 0;
2744     localParameters.FullScreen_RefreshRateInHz = WINED3DPRESENT_RATE_DEFAULT;
2745     localParameters.PresentationInterval = WINED3DPRESENT_INTERVAL_DEFAULT;
2746
2747     /* Set this NOW, otherwise creating the depth stencil surface will cause a
2748      * recursive loop until ram or emulated video memory is full. */
2749     ddraw->d3d_initialized = TRUE;
2750     hr = IWineD3DDevice_Init3D(ddraw->wineD3DDevice, &localParameters);
2751     if (FAILED(hr))
2752     {
2753         ddraw->d3d_target = NULL;
2754         ddraw->d3d_initialized = FALSE;
2755         return hr;
2756     }
2757
2758     ddraw->declArraySize = 2;
2759     ddraw->decls = HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, sizeof(*ddraw->decls) * ddraw->declArraySize);
2760     if (!ddraw->decls)
2761     {
2762         ERR("Error allocating an array for the converted vertex decls.\n");
2763         ddraw->declArraySize = 0;
2764         hr = IWineD3DDevice_Uninit3D(ddraw->wineD3DDevice, D3D7CB_DestroySwapChain);
2765         return E_OUTOFMEMORY;
2766     }
2767
2768     TRACE("Successfully initialized 3D.\n");
2769
2770     return DD_OK;
2771 }
2772
2773 static HRESULT ddraw_create_gdi_swapchain(IDirectDrawImpl *ddraw, IDirectDrawSurfaceImpl *primary)
2774 {
2775     WINED3DPRESENT_PARAMETERS presentation_parameters;
2776     HWND window;
2777     HRESULT hr;
2778
2779     window = ddraw->dest_window;
2780
2781     memset(&presentation_parameters, 0, sizeof(presentation_parameters));
2782
2783     /* Use the surface description for the device parameters, not the device
2784      * settings. The application might render to an offscreen surface. */
2785     presentation_parameters.BackBufferWidth = primary->surface_desc.dwWidth;
2786     presentation_parameters.BackBufferHeight = primary->surface_desc.dwHeight;
2787     presentation_parameters.BackBufferFormat = PixelFormat_DD2WineD3D(&primary->surface_desc.u4.ddpfPixelFormat);
2788     presentation_parameters.BackBufferCount = (primary->surface_desc.dwFlags & DDSD_BACKBUFFERCOUNT)
2789             ? primary->surface_desc.dwBackBufferCount : 0;
2790     presentation_parameters.MultiSampleType = WINED3DMULTISAMPLE_NONE;
2791     presentation_parameters.MultiSampleQuality = 0;
2792     presentation_parameters.SwapEffect = WINED3DSWAPEFFECT_FLIP;
2793     presentation_parameters.hDeviceWindow = window;
2794     presentation_parameters.Windowed = !(ddraw->cooperative_level & DDSCL_FULLSCREEN);
2795     presentation_parameters.EnableAutoDepthStencil = FALSE; /* Not on GDI swapchains */
2796     presentation_parameters.AutoDepthStencilFormat = 0;
2797     presentation_parameters.Flags = 0;
2798     presentation_parameters.FullScreen_RefreshRateInHz = WINED3DPRESENT_RATE_DEFAULT;
2799     presentation_parameters.PresentationInterval = WINED3DPRESENT_INTERVAL_DEFAULT;
2800
2801     ddraw->d3d_target = primary;
2802     hr = IWineD3DDevice_InitGDI(ddraw->wineD3DDevice, &presentation_parameters);
2803     ddraw->d3d_target = NULL;
2804     if (FAILED(hr))
2805     {
2806         WARN("Failed to initialize GDI ddraw implementation, hr %#x.\n", hr);
2807         primary->wineD3DSwapChain = NULL;
2808     }
2809
2810     return hr;
2811 }
2812
2813 /*****************************************************************************
2814  * IDirectDraw7::CreateSurface
2815  *
2816  * Creates a new IDirectDrawSurface object and returns its interface.
2817  *
2818  * The surface connections with wined3d are a bit tricky. Basically it works
2819  * like this:
2820  *
2821  * |------------------------|               |-----------------|
2822  * | DDraw surface          |               | WineD3DSurface  |
2823  * |                        |               |                 |
2824  * |        WineD3DSurface  |-------------->|                 |
2825  * |        Child           |<------------->| Parent          |
2826  * |------------------------|               |-----------------|
2827  *
2828  * The DDraw surface is the parent of the wined3d surface, and it releases
2829  * the WineD3DSurface when the ddraw surface is destroyed.
2830  *
2831  * However, for all surfaces which can be in a container in WineD3D,
2832  * we have to do this. These surfaces are usually complex surfaces,
2833  * so this concerns primary surfaces with a front and a back buffer,
2834  * and textures.
2835  *
2836  * |------------------------|               |-----------------|
2837  * | DDraw surface          |               | Container       |
2838  * |                        |               |                 |
2839  * |                  Child |<------------->| Parent          |
2840  * |                Texture |<------------->|                 |
2841  * |         WineD3DSurface |<----|         |          Levels |<--|
2842  * | Complex connection     |     |         |                 |   |
2843  * |------------------------|     |         |-----------------|   |
2844  *  ^                             |                               |
2845  *  |                             |                               |
2846  *  |                             |                               |
2847  *  |    |------------------|     |         |-----------------|   |
2848  *  |    | IParent          |     |-------->| WineD3DSurface  |   |
2849  *  |    |                  |               |                 |   |
2850  *  |    |            Child |<------------->| Parent          |   |
2851  *  |    |                  |               |       Container |<--|
2852  *  |    |------------------|               |-----------------|   |
2853  *  |                                                             |
2854  *  |   |----------------------|                                  |
2855  *  |   | DDraw surface 2      |                                  |
2856  *  |   |                      |                                  |
2857  *  |<->| Complex root   Child |                                  |
2858  *  |   |              Texture |                                  |
2859  *  |   |       WineD3DSurface |<----|                            |
2860  *  |   |----------------------|     |                            |
2861  *  |                                |                            |
2862  *  |    |---------------------|     |      |-----------------|   |
2863  *  |    | IParent             |     |----->| WineD3DSurface  |   |
2864  *  |    |                     |            |                 |   |
2865  *  |    |               Child |<---------->| Parent          |   |
2866  *  |    |---------------------|            |       Container |<--|
2867  *  |                                       |-----------------|   |
2868  *  |                                                             |
2869  *  |             ---More surfaces can follow---                  |
2870  *
2871  * The reason is that the IWineD3DSwapchain(render target container)
2872  * and the IWineD3DTexure(Texture container) release the parents
2873  * of their surface's children, but by releasing the complex root
2874  * the surfaces which are complexly attached to it are destroyed
2875  * too. See IDirectDrawSurface::Release for a more detailed
2876  * explanation.
2877  *
2878  * Params:
2879  *  DDSD: Description of the surface to create
2880  *  Surf: Address to store the interface pointer at
2881  *  UnkOuter: Basically for aggregation support, but ddraw doesn't support
2882  *            aggregation, so it has to be NULL
2883  *
2884  * Returns:
2885  *  DD_OK on success
2886  *  CLASS_E_NOAGGREGATION if UnkOuter != NULL
2887  *  DDERR_* if an error occurs
2888  *
2889  *****************************************************************************/
2890 static HRESULT WINAPI ddraw7_CreateSurface(IDirectDraw7 *iface,
2891         DDSURFACEDESC2 *DDSD, IDirectDrawSurface7 **Surf, IUnknown *UnkOuter)
2892 {
2893     IDirectDrawImpl *This = (IDirectDrawImpl *)iface;
2894     IDirectDrawSurfaceImpl *object = NULL;
2895     HRESULT hr;
2896     LONG extra_surfaces = 0;
2897     DDSURFACEDESC2 desc2;
2898     WINED3DDISPLAYMODE Mode;
2899     const DWORD sysvidmem = DDSCAPS_VIDEOMEMORY | DDSCAPS_SYSTEMMEMORY;
2900
2901     TRACE("iface %p, surface_desc %p, surface %p, outer_unknown %p.\n",
2902             iface, DDSD, Surf, UnkOuter);
2903
2904     /* Some checks before we start */
2905     if (TRACE_ON(ddraw))
2906     {
2907         TRACE(" (%p) Requesting surface desc :\n", This);
2908         DDRAW_dump_surface_desc(DDSD);
2909     }
2910     EnterCriticalSection(&ddraw_cs);
2911
2912     if (UnkOuter != NULL)
2913     {
2914         FIXME("(%p) : outer != NULL?\n", This);
2915         LeaveCriticalSection(&ddraw_cs);
2916         return CLASS_E_NOAGGREGATION; /* unchecked */
2917     }
2918
2919     if (Surf == NULL)
2920     {
2921         FIXME("(%p) You want to get back a surface? Don't give NULL ptrs!\n", This);
2922         LeaveCriticalSection(&ddraw_cs);
2923         return E_POINTER; /* unchecked */
2924     }
2925
2926     if (!(DDSD->dwFlags & DDSD_CAPS))
2927     {
2928         /* DVIDEO.DLL does forget the DDSD_CAPS flag ... *sigh* */
2929         DDSD->dwFlags |= DDSD_CAPS;
2930     }
2931
2932     if (DDSD->ddsCaps.dwCaps & DDSCAPS_ALLOCONLOAD)
2933     {
2934         /* If the surface is of the 'alloconload' type, ignore the LPSURFACE field */
2935         DDSD->dwFlags &= ~DDSD_LPSURFACE;
2936     }
2937
2938     if ((DDSD->dwFlags & DDSD_LPSURFACE) && (DDSD->lpSurface == NULL))
2939     {
2940         /* Frank Herbert's Dune specifies a null pointer for the surface, ignore the LPSURFACE field */
2941         WARN("(%p) Null surface pointer specified, ignore it!\n", This);
2942         DDSD->dwFlags &= ~DDSD_LPSURFACE;
2943     }
2944
2945     if((DDSD->ddsCaps.dwCaps & (DDSCAPS_FLIP | DDSCAPS_PRIMARYSURFACE)) == (DDSCAPS_FLIP | DDSCAPS_PRIMARYSURFACE) &&
2946        !(This->cooperative_level & DDSCL_EXCLUSIVE))
2947     {
2948         TRACE("(%p): Attempt to create a flipable primary surface without DDSCL_EXCLUSIVE set\n", This);
2949         *Surf = NULL;
2950         LeaveCriticalSection(&ddraw_cs);
2951         return DDERR_NOEXCLUSIVEMODE;
2952     }
2953
2954     if(DDSD->ddsCaps.dwCaps & (DDSCAPS_FRONTBUFFER | DDSCAPS_BACKBUFFER)) {
2955         WARN("Application tried to create an explicit front or back buffer\n");
2956         LeaveCriticalSection(&ddraw_cs);
2957         return DDERR_INVALIDCAPS;
2958     }
2959
2960     if((DDSD->ddsCaps.dwCaps & sysvidmem) == sysvidmem)
2961     {
2962         /* This is a special switch in ddrawex.dll, but not allowed in ddraw.dll */
2963         WARN("Application tries to put the surface in both system and video memory\n");
2964         LeaveCriticalSection(&ddraw_cs);
2965         *Surf = NULL;
2966         return DDERR_INVALIDCAPS;
2967     }
2968
2969     /* Check cube maps but only if the size includes them */
2970     if (DDSD->dwSize >= sizeof(DDSURFACEDESC2))
2971     {
2972         if(DDSD->ddsCaps.dwCaps2 & DDSCAPS2_CUBEMAP_ALLFACES &&
2973            !(DDSD->ddsCaps.dwCaps2 & DDSCAPS2_CUBEMAP))
2974         {
2975             WARN("Cube map faces requested without cube map flag\n");
2976             LeaveCriticalSection(&ddraw_cs);
2977             return DDERR_INVALIDCAPS;
2978         }
2979         if(DDSD->ddsCaps.dwCaps2 & DDSCAPS2_CUBEMAP &&
2980            (DDSD->ddsCaps.dwCaps2 & DDSCAPS2_CUBEMAP_ALLFACES) == 0)
2981         {
2982             WARN("Cube map without faces requested\n");
2983             LeaveCriticalSection(&ddraw_cs);
2984             return DDERR_INVALIDPARAMS;
2985         }
2986
2987         /* Quick tests confirm those can be created, but we don't do that yet */
2988         if(DDSD->ddsCaps.dwCaps2 & DDSCAPS2_CUBEMAP &&
2989            (DDSD->ddsCaps.dwCaps2 & DDSCAPS2_CUBEMAP_ALLFACES) != DDSCAPS2_CUBEMAP_ALLFACES)
2990         {
2991             FIXME("Partial cube maps not supported yet\n");
2992         }
2993     }
2994
2995     /* According to the msdn this flag is ignored by CreateSurface */
2996     if (DDSD->dwSize >= sizeof(DDSURFACEDESC2))
2997         DDSD->ddsCaps.dwCaps2 &= ~DDSCAPS2_MIPMAPSUBLEVEL;
2998
2999     /* Modify some flags */
3000     memset(&desc2, 0, sizeof(desc2));
3001     desc2.dwSize = sizeof(desc2);   /* For the struct copy */
3002     DD_STRUCT_COPY_BYSIZE(&desc2, DDSD);
3003     desc2.dwSize = sizeof(desc2);   /* To override a possibly smaller size */
3004     desc2.u4.ddpfPixelFormat.dwSize=sizeof(DDPIXELFORMAT); /* Just to be sure */
3005
3006     /* Get the video mode from WineD3D - we will need it */
3007     hr = IWineD3DDevice_GetDisplayMode(This->wineD3DDevice,
3008                                        0, /* Swapchain 0 */
3009                                        &Mode);
3010     if(FAILED(hr))
3011     {
3012         ERR("Failed to read display mode from wined3d\n");
3013         switch(This->orig_bpp)
3014         {
3015             case 8:
3016                 Mode.Format = WINED3DFMT_P8_UINT;
3017                 break;
3018
3019             case 15:
3020                 Mode.Format = WINED3DFMT_B5G5R5X1_UNORM;
3021                 break;
3022
3023             case 16:
3024                 Mode.Format = WINED3DFMT_B5G6R5_UNORM;
3025                 break;
3026
3027             case 24:
3028                 Mode.Format = WINED3DFMT_B8G8R8_UNORM;
3029                 break;
3030
3031             case 32:
3032                 Mode.Format = WINED3DFMT_B8G8R8X8_UNORM;
3033                 break;
3034         }
3035         Mode.Width = This->orig_width;
3036         Mode.Height = This->orig_height;
3037     }
3038
3039     /* No pixelformat given? Use the current screen format */
3040     if(!(desc2.dwFlags & DDSD_PIXELFORMAT))
3041     {
3042         desc2.dwFlags |= DDSD_PIXELFORMAT;
3043         desc2.u4.ddpfPixelFormat.dwSize=sizeof(DDPIXELFORMAT);
3044
3045         /* Wait: It could be a Z buffer */
3046         if(desc2.ddsCaps.dwCaps & DDSCAPS_ZBUFFER)
3047         {
3048             switch(desc2.u2.dwMipMapCount) /* Who had this glorious idea? */
3049             {
3050                 case 15:
3051                     PixelFormat_WineD3DtoDD(&desc2.u4.ddpfPixelFormat, WINED3DFMT_S1_UINT_D15_UNORM);
3052                     break;
3053                 case 16:
3054                     PixelFormat_WineD3DtoDD(&desc2.u4.ddpfPixelFormat, WINED3DFMT_D16_UNORM);
3055                     break;
3056                 case 24:
3057                     PixelFormat_WineD3DtoDD(&desc2.u4.ddpfPixelFormat, WINED3DFMT_X8D24_UNORM);
3058                     break;
3059                 case 32:
3060                     PixelFormat_WineD3DtoDD(&desc2.u4.ddpfPixelFormat, WINED3DFMT_D32_UNORM);
3061                     break;
3062                 default:
3063                     ERR("Unknown Z buffer bit depth\n");
3064             }
3065         }
3066         else
3067         {
3068             PixelFormat_WineD3DtoDD(&desc2.u4.ddpfPixelFormat, Mode.Format);
3069         }
3070     }
3071
3072     /* No Width or no Height? Use the original screen size
3073      */
3074     if(!(desc2.dwFlags & DDSD_WIDTH) ||
3075        !(desc2.dwFlags & DDSD_HEIGHT) )
3076     {
3077         /* Invalid for non-render targets */
3078         if(!(desc2.ddsCaps.dwCaps & DDSCAPS_PRIMARYSURFACE))
3079         {
3080             WARN("Creating a non-Primary surface without Width or Height info, returning DDERR_INVALIDPARAMS\n");
3081             *Surf = NULL;
3082             LeaveCriticalSection(&ddraw_cs);
3083             return DDERR_INVALIDPARAMS;
3084         }
3085
3086         desc2.dwFlags |= DDSD_WIDTH | DDSD_HEIGHT;
3087         desc2.dwWidth = Mode.Width;
3088         desc2.dwHeight = Mode.Height;
3089     }
3090
3091     /* Mipmap count fixes */
3092     if(desc2.ddsCaps.dwCaps & DDSCAPS_MIPMAP)
3093     {
3094         if(desc2.ddsCaps.dwCaps & DDSCAPS_COMPLEX)
3095         {
3096             if(desc2.dwFlags & DDSD_MIPMAPCOUNT)
3097             {
3098                 /* Mipmap count is given, should not be 0 */
3099                 if( desc2.u2.dwMipMapCount == 0 )
3100                 {
3101                     LeaveCriticalSection(&ddraw_cs);
3102                     return DDERR_INVALIDPARAMS;
3103                 }
3104             }
3105             else
3106             {
3107                 /* Undocumented feature: Create sublevels until
3108                  * either the width or the height is 1
3109                  */
3110                 DWORD min = desc2.dwWidth < desc2.dwHeight ?
3111                             desc2.dwWidth : desc2.dwHeight;
3112                 desc2.u2.dwMipMapCount = 0;
3113                 while( min )
3114                 {
3115                     desc2.u2.dwMipMapCount += 1;
3116                     min >>= 1;
3117                 }
3118             }
3119         }
3120         else
3121         {
3122             /* Not-complex mipmap -> Mipmapcount = 1 */
3123             desc2.u2.dwMipMapCount = 1;
3124         }
3125         extra_surfaces = desc2.u2.dwMipMapCount - 1;
3126
3127         /* There's a mipmap count in the created surface in any case */
3128         desc2.dwFlags |= DDSD_MIPMAPCOUNT;
3129     }
3130     /* If no mipmap is given, the texture has only one level */
3131
3132     /* The first surface is a front buffer, the back buffer is created afterwards */
3133     if( (desc2.dwFlags & DDSD_CAPS) && (desc2.ddsCaps.dwCaps & DDSCAPS_PRIMARYSURFACE) )
3134     {
3135         desc2.ddsCaps.dwCaps |= DDSCAPS_FRONTBUFFER;
3136     }
3137
3138     /* The root surface in a cube map is positive x */
3139     if(desc2.ddsCaps.dwCaps2 & DDSCAPS2_CUBEMAP)
3140     {
3141         desc2.ddsCaps.dwCaps2 &= ~DDSCAPS2_CUBEMAP_ALLFACES;
3142         desc2.ddsCaps.dwCaps2 |=  DDSCAPS2_CUBEMAP_POSITIVEX;
3143     }
3144
3145     /* Create the first surface */
3146     hr = ddraw_create_surface(This, &desc2, &object, 0);
3147     if (FAILED(hr))
3148     {
3149         WARN("ddraw_create_surface failed, hr %#x.\n", hr);
3150         LeaveCriticalSection(&ddraw_cs);
3151         return hr;
3152     }
3153     object->is_complex_root = TRUE;
3154
3155     *Surf = (IDirectDrawSurface7 *)object;
3156
3157     /* Create Additional surfaces if necessary
3158      * This applies to Primary surfaces which have a back buffer count
3159      * set, but not to mipmap textures. In case of Mipmap textures,
3160      * wineD3D takes care of the creation of additional surfaces
3161      */
3162     if(DDSD->dwFlags & DDSD_BACKBUFFERCOUNT)
3163     {
3164         extra_surfaces = DDSD->dwBackBufferCount;
3165         desc2.ddsCaps.dwCaps &= ~DDSCAPS_FRONTBUFFER; /* It's not a front buffer */
3166         desc2.ddsCaps.dwCaps |= DDSCAPS_BACKBUFFER;
3167         desc2.dwBackBufferCount = 0;
3168     }
3169
3170     hr = DD_OK;
3171     if(desc2.ddsCaps.dwCaps2 & DDSCAPS2_CUBEMAP)
3172     {
3173         desc2.ddsCaps.dwCaps2 &= ~DDSCAPS2_CUBEMAP_ALLFACES;
3174         desc2.ddsCaps.dwCaps2 |=  DDSCAPS2_CUBEMAP_NEGATIVEZ;
3175         hr |= CreateAdditionalSurfaces(This, object, extra_surfaces + 1, desc2, TRUE);
3176         desc2.ddsCaps.dwCaps2 &= ~DDSCAPS2_CUBEMAP_NEGATIVEZ;
3177         desc2.ddsCaps.dwCaps2 |=  DDSCAPS2_CUBEMAP_POSITIVEZ;
3178         hr |= CreateAdditionalSurfaces(This, object, extra_surfaces + 1, desc2, TRUE);
3179         desc2.ddsCaps.dwCaps2 &= ~DDSCAPS2_CUBEMAP_POSITIVEZ;
3180         desc2.ddsCaps.dwCaps2 |=  DDSCAPS2_CUBEMAP_NEGATIVEY;
3181         hr |= CreateAdditionalSurfaces(This, object, extra_surfaces + 1, desc2, TRUE);
3182         desc2.ddsCaps.dwCaps2 &= ~DDSCAPS2_CUBEMAP_NEGATIVEY;
3183         desc2.ddsCaps.dwCaps2 |=  DDSCAPS2_CUBEMAP_POSITIVEY;
3184         hr |= CreateAdditionalSurfaces(This, object, extra_surfaces + 1, desc2, TRUE);
3185         desc2.ddsCaps.dwCaps2 &= ~DDSCAPS2_CUBEMAP_POSITIVEY;
3186         desc2.ddsCaps.dwCaps2 |=  DDSCAPS2_CUBEMAP_NEGATIVEX;
3187         hr |= CreateAdditionalSurfaces(This, object, extra_surfaces + 1, desc2, TRUE);
3188         desc2.ddsCaps.dwCaps2 &= ~DDSCAPS2_CUBEMAP_NEGATIVEX;
3189         desc2.ddsCaps.dwCaps2 |=  DDSCAPS2_CUBEMAP_POSITIVEX;
3190     }
3191
3192     hr |= CreateAdditionalSurfaces(This, object, extra_surfaces, desc2, FALSE);
3193     if(hr != DD_OK)
3194     {
3195         /* This destroys and possibly created surfaces too */
3196         IDirectDrawSurface_Release((IDirectDrawSurface7 *)object);
3197         LeaveCriticalSection(&ddraw_cs);
3198         return hr;
3199     }
3200
3201     /* If the implementation is OpenGL and there's no d3ddevice, attach a d3ddevice
3202      * But attach the d3ddevice only if the currently created surface was
3203      * a primary surface (2D app in 3D mode) or a 3DDEVICE surface (3D app)
3204      * The only case I can think of where this doesn't apply is when a
3205      * 2D app was configured by the user to run with OpenGL and it didn't create
3206      * the render target as first surface. In this case the render target creation
3207      * will cause the 3D init.
3208      */
3209     if( (This->ImplType == SURFACE_OPENGL) && !(This->d3d_initialized) &&
3210         desc2.ddsCaps.dwCaps & (DDSCAPS_PRIMARYSURFACE | DDSCAPS_3DDEVICE) )
3211     {
3212         IDirectDrawSurfaceImpl *target = object, *surface;
3213         struct list *entry;
3214
3215         /* Search for the primary to use as render target */
3216         LIST_FOR_EACH(entry, &This->surface_list)
3217         {
3218             surface = LIST_ENTRY(entry, IDirectDrawSurfaceImpl, surface_list_entry);
3219             if((surface->surface_desc.ddsCaps.dwCaps & (DDSCAPS_PRIMARYSURFACE | DDSCAPS_FRONTBUFFER)) ==
3220                (DDSCAPS_PRIMARYSURFACE | DDSCAPS_FRONTBUFFER))
3221             {
3222                 /* found */
3223                 target = surface;
3224                 TRACE("Using primary %p as render target\n", target);
3225                 break;
3226             }
3227         }
3228
3229         TRACE("(%p) Attaching a D3DDevice, rendertarget = %p\n", This, target);
3230         hr = ddraw_attach_d3d_device(This, target);
3231         if (hr != D3D_OK)
3232         {
3233             IDirectDrawSurfaceImpl *release_surf;
3234             ERR("ddraw_attach_d3d_device failed, hr %#x\n", hr);
3235             *Surf = NULL;
3236
3237             /* The before created surface structures are in an incomplete state here.
3238              * WineD3D holds the reference on the IParents, and it released them on the failure
3239              * already. So the regular release method implementation would fail on the attempt
3240              * to destroy either the IParents or the swapchain. So free the surface here.
3241              * The surface structure here is a list, not a tree, because onscreen targets
3242              * cannot be cube textures
3243              */
3244             while(object)
3245             {
3246                 release_surf = object;
3247                 object = object->complex_array[0];
3248                 ddraw_surface_destroy(release_surf);
3249             }
3250             LeaveCriticalSection(&ddraw_cs);
3251             return hr;
3252         }
3253     }
3254     else if(!(This->d3d_initialized) && desc2.ddsCaps.dwCaps & DDSCAPS_PRIMARYSURFACE)
3255     {
3256         ddraw_create_gdi_swapchain(This, object);
3257     }
3258
3259     /* Addref the ddraw interface to keep an reference for each surface */
3260     IDirectDraw7_AddRef(iface);
3261     object->ifaceToRelease = (IUnknown *) iface;
3262
3263     /* Create a WineD3DTexture if a texture was requested */
3264     if(desc2.ddsCaps.dwCaps & DDSCAPS_TEXTURE)
3265     {
3266         UINT levels;
3267         WINED3DFORMAT Format;
3268         WINED3DPOOL Pool = WINED3DPOOL_DEFAULT;
3269
3270         This->tex_root = object;
3271
3272         if(desc2.ddsCaps.dwCaps & DDSCAPS_MIPMAP)
3273         {
3274             /* a mipmap is created, create enough levels */
3275             levels = desc2.u2.dwMipMapCount;
3276         }
3277         else
3278         {
3279             /* No mipmap is created, create one level */
3280             levels = 1;
3281         }
3282
3283         /* DDSCAPS_SYSTEMMEMORY textures are in WINED3DPOOL_SYSTEMMEM */
3284         if(DDSD->ddsCaps.dwCaps & DDSCAPS_SYSTEMMEMORY)
3285         {
3286             Pool = WINED3DPOOL_SYSTEMMEM;
3287         }
3288         /* Should I forward the MANAGED cap to the managed pool ? */
3289
3290         /* Get the format. It's set already by CreateNewSurface */
3291         Format = PixelFormat_DD2WineD3D(&object->surface_desc.u4.ddpfPixelFormat);
3292
3293         /* The surfaces are already created, the callback only
3294          * passes the IWineD3DSurface to WineD3D
3295          */
3296         if(desc2.ddsCaps.dwCaps2 & DDSCAPS2_CUBEMAP)
3297         {
3298             hr = IWineD3DDevice_CreateCubeTexture(This->wineD3DDevice, DDSD->dwWidth /* Edgelength */,
3299                     levels, 0 /* usage */, Format, Pool, (IWineD3DCubeTexture **)&object->wineD3DTexture,
3300                     (IUnknown *)object, &ddraw_null_wined3d_parent_ops);
3301         }
3302         else
3303         {
3304             hr = IWineD3DDevice_CreateTexture(This->wineD3DDevice, DDSD->dwWidth, DDSD->dwHeight, levels,
3305                     0 /* usage */, Format, Pool, (IWineD3DTexture **)&object->wineD3DTexture,
3306                     (IUnknown *)object, &ddraw_null_wined3d_parent_ops);
3307         }
3308         This->tex_root = NULL;
3309     }
3310
3311     LeaveCriticalSection(&ddraw_cs);
3312     return hr;
3313 }
3314
3315 static HRESULT WINAPI ddraw4_CreateSurface(IDirectDraw4 *iface,
3316         DDSURFACEDESC2 *surface_desc, IDirectDrawSurface4 **surface, IUnknown *outer_unknown)
3317 {
3318     IDirectDrawImpl *ddraw = ddraw_from_ddraw4(iface);
3319     IDirectDrawSurfaceImpl *impl;
3320     HRESULT hr;
3321
3322     TRACE("iface %p, surface_desc %p, surface %p, outer_unknown %p.\n",
3323             iface, surface_desc, surface, outer_unknown);
3324
3325     hr = ddraw7_CreateSurface((IDirectDraw7 *)ddraw, surface_desc, (IDirectDrawSurface7 **)surface, outer_unknown);
3326     impl = (IDirectDrawSurfaceImpl *)*surface;
3327     if (SUCCEEDED(hr) && impl)
3328     {
3329         ddraw_set_surface_version(impl, 4);
3330         IDirectDraw7_Release((IDirectDraw7 *)ddraw);
3331         IDirectDraw4_AddRef(iface);
3332         impl->ifaceToRelease = (IUnknown *)iface;
3333     }
3334
3335     return hr;
3336 }
3337
3338 static HRESULT WINAPI ddraw3_CreateSurface(IDirectDraw3 *iface,
3339         DDSURFACEDESC *surface_desc, IDirectDrawSurface **surface, IUnknown *outer_unknown)
3340 {
3341     IDirectDrawImpl *ddraw = ddraw_from_ddraw3(iface);
3342     IDirectDrawSurface7 *surface7;
3343     IDirectDrawSurfaceImpl *impl;
3344     HRESULT hr;
3345
3346     TRACE("iface %p, surface_desc %p, surface %p, outer_unknown %p.\n",
3347             iface, surface_desc, surface, outer_unknown);
3348
3349     hr = ddraw7_CreateSurface((IDirectDraw7 *)ddraw, (DDSURFACEDESC2 *)surface_desc, &surface7, outer_unknown);
3350     if (FAILED(hr))
3351     {
3352         *surface = NULL;
3353         return hr;
3354     }
3355
3356     impl = (IDirectDrawSurfaceImpl *)surface7;
3357     *surface = (IDirectDrawSurface *)&impl->IDirectDrawSurface3_vtbl;
3358     ddraw_set_surface_version(impl, 3);
3359     IDirectDraw7_Release((IDirectDraw7 *)ddraw);
3360     IDirectDraw3_AddRef(iface);
3361     impl->ifaceToRelease = (IUnknown *)iface;
3362
3363     return hr;
3364 }
3365
3366 static HRESULT WINAPI ddraw2_CreateSurface(IDirectDraw2 *iface,
3367         DDSURFACEDESC *surface_desc, IDirectDrawSurface **surface, IUnknown *outer_unknown)
3368 {
3369     IDirectDrawImpl *ddraw = ddraw_from_ddraw2(iface);
3370     IDirectDrawSurface7 *surface7;
3371     IDirectDrawSurfaceImpl *impl;
3372     HRESULT hr;
3373
3374     TRACE("iface %p, surface_desc %p, surface %p, outer_unknown %p.\n",
3375             iface, surface_desc, surface, outer_unknown);
3376
3377     hr = ddraw7_CreateSurface((IDirectDraw7 *)ddraw, (DDSURFACEDESC2 *)surface_desc, &surface7, outer_unknown);
3378     if (FAILED(hr))
3379     {
3380         *surface = NULL;
3381         return hr;
3382     }
3383
3384     impl = (IDirectDrawSurfaceImpl *)surface7;
3385     *surface = (IDirectDrawSurface *)&impl->IDirectDrawSurface3_vtbl;
3386     ddraw_set_surface_version(impl, 2);
3387     IDirectDraw7_Release((IDirectDraw7 *)ddraw);
3388     impl->ifaceToRelease = NULL;
3389
3390     return hr;
3391 }
3392
3393 static HRESULT WINAPI ddraw1_CreateSurface(IDirectDraw *iface,
3394         DDSURFACEDESC *surface_desc, IDirectDrawSurface **surface, IUnknown *outer_unknown)
3395 {
3396     IDirectDrawImpl *ddraw = ddraw_from_ddraw1(iface);
3397     IDirectDrawSurface7 *surface7;
3398     IDirectDrawSurfaceImpl *impl;
3399     HRESULT hr;
3400
3401     TRACE("iface %p, surface_desc %p, surface %p, outer_unknown %p.\n",
3402             iface, surface_desc, surface, outer_unknown);
3403
3404     /* Remove front buffer flag, this causes failure in v7, and its added to normal
3405      * primaries anyway. */
3406     surface_desc->ddsCaps.dwCaps &= ~DDSCAPS_FRONTBUFFER;
3407     hr = ddraw7_CreateSurface((IDirectDraw7 *)ddraw, (DDSURFACEDESC2 *)surface_desc, &surface7, outer_unknown);
3408     if (FAILED(hr))
3409     {
3410         *surface = NULL;
3411         return hr;
3412     }
3413
3414     impl = (IDirectDrawSurfaceImpl *)surface7;
3415     *surface = (IDirectDrawSurface *)&impl->IDirectDrawSurface3_vtbl;
3416     ddraw_set_surface_version(impl, 1);
3417     IDirectDraw7_Release((IDirectDraw7 *)ddraw);
3418     impl->ifaceToRelease = NULL;
3419
3420     return hr;
3421 }
3422
3423 #define DDENUMSURFACES_SEARCHTYPE (DDENUMSURFACES_CANBECREATED|DDENUMSURFACES_DOESEXIST)
3424 #define DDENUMSURFACES_MATCHTYPE (DDENUMSURFACES_ALL|DDENUMSURFACES_MATCH|DDENUMSURFACES_NOMATCH)
3425
3426 static BOOL
3427 Main_DirectDraw_DDPIXELFORMAT_Match(const DDPIXELFORMAT *requested,
3428                                     const DDPIXELFORMAT *provided)
3429 {
3430     /* Some flags must be present in both or neither for a match. */
3431     static const DWORD must_match = DDPF_PALETTEINDEXED1 | DDPF_PALETTEINDEXED2
3432         | DDPF_PALETTEINDEXED4 | DDPF_PALETTEINDEXED8 | DDPF_FOURCC
3433         | DDPF_ZBUFFER | DDPF_STENCILBUFFER;
3434
3435     if ((requested->dwFlags & provided->dwFlags) != requested->dwFlags)
3436         return FALSE;
3437
3438     if ((requested->dwFlags & must_match) != (provided->dwFlags & must_match))
3439         return FALSE;
3440
3441     if (requested->dwFlags & DDPF_FOURCC)
3442         if (requested->dwFourCC != provided->dwFourCC)
3443             return FALSE;
3444
3445     if (requested->dwFlags & (DDPF_RGB|DDPF_YUV|DDPF_ZBUFFER|DDPF_ALPHA
3446                               |DDPF_LUMINANCE|DDPF_BUMPDUDV))
3447         if (requested->u1.dwRGBBitCount != provided->u1.dwRGBBitCount)
3448             return FALSE;
3449
3450     if (requested->dwFlags & (DDPF_RGB|DDPF_YUV|DDPF_STENCILBUFFER
3451                               |DDPF_LUMINANCE|DDPF_BUMPDUDV))
3452         if (requested->u2.dwRBitMask != provided->u2.dwRBitMask)
3453             return FALSE;
3454
3455     if (requested->dwFlags & (DDPF_RGB|DDPF_YUV|DDPF_ZBUFFER|DDPF_BUMPDUDV))
3456         if (requested->u3.dwGBitMask != provided->u3.dwGBitMask)
3457             return FALSE;
3458
3459     /* I could be wrong about the bumpmapping. MSDN docs are vague. */
3460     if (requested->dwFlags & (DDPF_RGB|DDPF_YUV|DDPF_STENCILBUFFER
3461                               |DDPF_BUMPDUDV))
3462         if (requested->u4.dwBBitMask != provided->u4.dwBBitMask)
3463             return FALSE;
3464
3465     if (requested->dwFlags & (DDPF_ALPHAPIXELS|DDPF_ZPIXELS))
3466         if (requested->u5.dwRGBAlphaBitMask != provided->u5.dwRGBAlphaBitMask)
3467             return FALSE;
3468
3469     return TRUE;
3470 }
3471
3472 static BOOL ddraw_match_surface_desc(const DDSURFACEDESC2 *requested, const DDSURFACEDESC2 *provided)
3473 {
3474     struct compare_info
3475     {
3476         DWORD flag;
3477         ptrdiff_t offset;
3478         size_t size;
3479     };
3480
3481 #define CMP(FLAG, FIELD)                                \
3482         { DDSD_##FLAG, offsetof(DDSURFACEDESC2, FIELD), \
3483           sizeof(((DDSURFACEDESC2 *)(NULL))->FIELD) }
3484
3485     static const struct compare_info compare[] =
3486     {
3487         CMP(ALPHABITDEPTH, dwAlphaBitDepth),
3488         CMP(BACKBUFFERCOUNT, dwBackBufferCount),
3489         CMP(CAPS, ddsCaps),
3490         CMP(CKDESTBLT, ddckCKDestBlt),
3491         CMP(CKDESTOVERLAY, u3 /* ddckCKDestOverlay */),
3492         CMP(CKSRCBLT, ddckCKSrcBlt),
3493         CMP(CKSRCOVERLAY, ddckCKSrcOverlay),
3494         CMP(HEIGHT, dwHeight),
3495         CMP(LINEARSIZE, u1 /* dwLinearSize */),
3496         CMP(LPSURFACE, lpSurface),
3497         CMP(MIPMAPCOUNT, u2 /* dwMipMapCount */),
3498         CMP(PITCH, u1 /* lPitch */),
3499         /* PIXELFORMAT: manual */
3500         CMP(REFRESHRATE, u2 /* dwRefreshRate */),
3501         CMP(TEXTURESTAGE, dwTextureStage),
3502         CMP(WIDTH, dwWidth),
3503         /* ZBUFFERBITDEPTH: "obsolete" */
3504     };
3505
3506 #undef CMP
3507
3508     unsigned int i;
3509
3510     if ((requested->dwFlags & provided->dwFlags) != requested->dwFlags)
3511         return FALSE;
3512
3513     for (i=0; i < sizeof(compare)/sizeof(compare[0]); i++)
3514     {
3515         if (requested->dwFlags & compare[i].flag
3516             && memcmp((const char *)provided + compare[i].offset,
3517                       (const char *)requested + compare[i].offset,
3518                       compare[i].size) != 0)
3519             return FALSE;
3520     }
3521
3522     if (requested->dwFlags & DDSD_PIXELFORMAT)
3523     {
3524         if (!Main_DirectDraw_DDPIXELFORMAT_Match(&requested->u4.ddpfPixelFormat,
3525                                                 &provided->u4.ddpfPixelFormat))
3526             return FALSE;
3527     }
3528
3529     return TRUE;
3530 }
3531
3532 #undef DDENUMSURFACES_SEARCHTYPE
3533 #undef DDENUMSURFACES_MATCHTYPE
3534
3535 struct surfacescallback_context
3536 {
3537     LPDDENUMSURFACESCALLBACK func;
3538     void *context;
3539 };
3540
3541 static HRESULT CALLBACK EnumSurfacesCallbackThunk(IDirectDrawSurface7 *surface,
3542         DDSURFACEDESC2 *surface_desc, void *context)
3543 {
3544     struct surfacescallback_context *cbcontext = context;
3545
3546     return cbcontext->func((IDirectDrawSurface *)&((IDirectDrawSurfaceImpl *)surface)->IDirectDrawSurface3_vtbl,
3547             (DDSURFACEDESC *)surface_desc, cbcontext->context);
3548 }
3549
3550 /*****************************************************************************
3551  * IDirectDraw7::EnumSurfaces
3552  *
3553  * Loops through all surfaces attached to this device and calls the
3554  * application callback. This can't be relayed to WineD3DDevice,
3555  * because some WineD3DSurfaces' parents are IParent objects
3556  *
3557  * Params:
3558  *  Flags: Some filtering flags. See IDirectDrawImpl_EnumSurfacesCallback
3559  *  DDSD: Description to filter for
3560  *  Context: Application-provided pointer, it's passed unmodified to the
3561  *           Callback function
3562  *  Callback: Address to call for each surface
3563  *
3564  * Returns:
3565  *  DDERR_INVALIDPARAMS if the callback is NULL
3566  *  DD_OK on success
3567  *
3568  *****************************************************************************/
3569 static HRESULT WINAPI ddraw7_EnumSurfaces(IDirectDraw7 *iface, DWORD Flags,
3570         DDSURFACEDESC2 *DDSD, void *Context, LPDDENUMSURFACESCALLBACK7 Callback)
3571 {
3572     /* The surface enumeration is handled by WineDDraw,
3573      * because it keeps track of all surfaces attached to
3574      * it. The filtering is done by our callback function,
3575      * because WineDDraw doesn't handle ddraw-like surface
3576      * caps structures
3577      */
3578     IDirectDrawImpl *This = (IDirectDrawImpl *)iface;
3579     IDirectDrawSurfaceImpl *surf;
3580     BOOL all, nomatch;
3581     DDSURFACEDESC2 desc;
3582     struct list *entry, *entry2;
3583
3584     TRACE("iface %p, flags %#x, surface_desc %p, context %p, callback %p.\n",
3585             iface, Flags, DDSD, Context, Callback);
3586
3587     all = Flags & DDENUMSURFACES_ALL;
3588     nomatch = Flags & DDENUMSURFACES_NOMATCH;
3589
3590     EnterCriticalSection(&ddraw_cs);
3591
3592     if(!Callback)
3593     {
3594         LeaveCriticalSection(&ddraw_cs);
3595         return DDERR_INVALIDPARAMS;
3596     }
3597
3598     /* Use the _SAFE enumeration, the app may destroy enumerated surfaces */
3599     LIST_FOR_EACH_SAFE(entry, entry2, &This->surface_list)
3600     {
3601         surf = LIST_ENTRY(entry, IDirectDrawSurfaceImpl, surface_list_entry);
3602         if (all || (nomatch != ddraw_match_surface_desc(DDSD, &surf->surface_desc)))
3603         {
3604             desc = surf->surface_desc;
3605             IDirectDrawSurface7_AddRef((IDirectDrawSurface7 *)surf);
3606             if (Callback((IDirectDrawSurface7 *)surf, &desc, Context) != DDENUMRET_OK)
3607             {
3608                 LeaveCriticalSection(&ddraw_cs);
3609                 return DD_OK;
3610             }
3611         }
3612     }
3613     LeaveCriticalSection(&ddraw_cs);
3614     return DD_OK;
3615 }
3616
3617 static HRESULT WINAPI ddraw4_EnumSurfaces(IDirectDraw4 *iface, DWORD flags,
3618         DDSURFACEDESC2 *surface_desc, void *context, LPDDENUMSURFACESCALLBACK2 callback)
3619 {
3620     TRACE("iface %p, flags %#x, surface_desc %p, context %p, callback %p.\n",
3621             iface, flags, surface_desc, context, callback);
3622
3623     return ddraw7_EnumSurfaces((IDirectDraw7 *)ddraw_from_ddraw4(iface),
3624             flags, surface_desc, context, (LPDDENUMSURFACESCALLBACK7)callback);
3625 }
3626
3627 static HRESULT WINAPI ddraw3_EnumSurfaces(IDirectDraw3 *iface, DWORD flags,
3628         DDSURFACEDESC *surface_desc, void *context, LPDDENUMSURFACESCALLBACK callback)
3629 {
3630     struct surfacescallback_context cbcontext;
3631
3632     TRACE("iface %p, flags %#x, surface_desc %p, context %p, callback %p.\n",
3633             iface, flags, surface_desc, context, callback);
3634
3635     cbcontext.func = callback;
3636     cbcontext.context = context;
3637
3638     return ddraw7_EnumSurfaces((IDirectDraw7 *)ddraw_from_ddraw3(iface), flags,
3639             (DDSURFACEDESC2 *)surface_desc, &cbcontext, EnumSurfacesCallbackThunk);
3640 }
3641
3642 static HRESULT WINAPI ddraw2_EnumSurfaces(IDirectDraw2 *iface, DWORD flags,
3643         DDSURFACEDESC *surface_desc, void *context, LPDDENUMSURFACESCALLBACK callback)
3644 {
3645     struct surfacescallback_context cbcontext;
3646
3647     TRACE("iface %p, flags %#x, surface_desc %p, context %p, callback %p.\n",
3648             iface, flags, surface_desc, context, callback);
3649
3650     cbcontext.func = callback;
3651     cbcontext.context = context;
3652
3653     return ddraw7_EnumSurfaces((IDirectDraw7 *)ddraw_from_ddraw2(iface), flags,
3654             (DDSURFACEDESC2 *)surface_desc, &cbcontext, EnumSurfacesCallbackThunk);
3655 }
3656
3657 static HRESULT WINAPI ddraw1_EnumSurfaces(IDirectDraw *iface, DWORD flags,
3658         DDSURFACEDESC *surface_desc, void *context, LPDDENUMSURFACESCALLBACK callback)
3659 {
3660     struct surfacescallback_context cbcontext;
3661
3662     TRACE("iface %p, flags %#x, surface_desc %p, context %p, callback %p.\n",
3663             iface, flags, surface_desc, context, callback);
3664
3665     cbcontext.func = callback;
3666     cbcontext.context = context;
3667
3668     return ddraw7_EnumSurfaces((IDirectDraw7 *)ddraw_from_ddraw1(iface), flags,
3669             (DDSURFACEDESC2 *)surface_desc, &cbcontext, EnumSurfacesCallbackThunk);
3670 }
3671
3672 /*****************************************************************************
3673  * DirectDrawCreateClipper (DDRAW.@)
3674  *
3675  * Creates a new IDirectDrawClipper object.
3676  *
3677  * Params:
3678  *  Clipper: Address to write the interface pointer to
3679  *  UnkOuter: For aggregation support, which ddraw doesn't have. Has to be
3680  *            NULL
3681  *
3682  * Returns:
3683  *  CLASS_E_NOAGGREGATION if UnkOuter != NULL
3684  *  E_OUTOFMEMORY if allocating the object failed
3685  *
3686  *****************************************************************************/
3687 HRESULT WINAPI
3688 DirectDrawCreateClipper(DWORD Flags,
3689                         LPDIRECTDRAWCLIPPER *Clipper,
3690                         IUnknown *UnkOuter)
3691 {
3692     IDirectDrawClipperImpl* object;
3693     HRESULT hr;
3694
3695     TRACE("flags %#x, clipper %p, outer_unknown %p.\n",
3696             Flags, Clipper, UnkOuter);
3697
3698     EnterCriticalSection(&ddraw_cs);
3699     if (UnkOuter != NULL)
3700     {
3701         LeaveCriticalSection(&ddraw_cs);
3702         return CLASS_E_NOAGGREGATION;
3703     }
3704
3705     if (!LoadWineD3D())
3706     {
3707         LeaveCriticalSection(&ddraw_cs);
3708         return DDERR_NODIRECTDRAWSUPPORT;
3709     }
3710
3711     object = HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY,
3712                      sizeof(IDirectDrawClipperImpl));
3713     if (object == NULL)
3714     {
3715         LeaveCriticalSection(&ddraw_cs);
3716         return E_OUTOFMEMORY;
3717     }
3718
3719     hr = ddraw_clipper_init(object);
3720     if (FAILED(hr))
3721     {
3722         WARN("Failed to initialize clipper, hr %#x.\n", hr);
3723         HeapFree(GetProcessHeap(), 0, object);
3724         LeaveCriticalSection(&ddraw_cs);
3725         return hr;
3726     }
3727
3728     TRACE("Created clipper %p.\n", object);
3729     *Clipper = (IDirectDrawClipper *) object;
3730     LeaveCriticalSection(&ddraw_cs);
3731     return DD_OK;
3732 }
3733
3734 /*****************************************************************************
3735  * IDirectDraw7::CreateClipper
3736  *
3737  * Creates a DDraw clipper. See DirectDrawCreateClipper for details
3738  *
3739  *****************************************************************************/
3740 static HRESULT WINAPI ddraw7_CreateClipper(IDirectDraw7 *iface, DWORD Flags,
3741         IDirectDrawClipper **Clipper, IUnknown *UnkOuter)
3742 {
3743     TRACE("iface %p, flags %#x, clipper %p, outer_unknown %p.\n",
3744             iface, Flags, Clipper, UnkOuter);
3745
3746     return DirectDrawCreateClipper(Flags, Clipper, UnkOuter);
3747 }
3748
3749 static HRESULT WINAPI ddraw4_CreateClipper(IDirectDraw4 *iface,
3750         DWORD flags, IDirectDrawClipper **clipper, IUnknown *outer_unknown)
3751 {
3752     TRACE("iface %p, flags %#x, clipper %p, outer_unknown %p.\n",
3753             iface, flags, clipper, outer_unknown);
3754
3755     return ddraw7_CreateClipper((IDirectDraw7 *)ddraw_from_ddraw4(iface), flags, clipper, outer_unknown);
3756 }
3757
3758 static HRESULT WINAPI ddraw3_CreateClipper(IDirectDraw3 *iface,
3759         DWORD flags, IDirectDrawClipper **clipper, IUnknown *outer_unknown)
3760 {
3761     TRACE("iface %p, flags %#x, clipper %p, outer_unknown %p.\n",
3762             iface, flags, clipper, outer_unknown);
3763
3764     return ddraw7_CreateClipper((IDirectDraw7 *)ddraw_from_ddraw3(iface), flags, clipper, outer_unknown);
3765 }
3766
3767 static HRESULT WINAPI ddraw2_CreateClipper(IDirectDraw2 *iface,
3768         DWORD flags, IDirectDrawClipper **clipper, IUnknown *outer_unknown)
3769 {
3770     TRACE("iface %p, flags %#x, clipper %p, outer_unknown %p.\n",
3771             iface, flags, clipper, outer_unknown);
3772
3773     return ddraw7_CreateClipper((IDirectDraw7 *)ddraw_from_ddraw2(iface), flags, clipper, outer_unknown);
3774 }
3775
3776 static HRESULT WINAPI ddraw1_CreateClipper(IDirectDraw *iface,
3777         DWORD flags, IDirectDrawClipper **clipper, IUnknown *outer_unknown)
3778 {
3779     TRACE("iface %p, flags %#x, clipper %p, outer_unknown %p.\n",
3780             iface, flags, clipper, outer_unknown);
3781
3782     return ddraw7_CreateClipper((IDirectDraw7 *)ddraw_from_ddraw1(iface), flags, clipper, outer_unknown);
3783 }
3784
3785 /*****************************************************************************
3786  * IDirectDraw7::CreatePalette
3787  *
3788  * Creates a new IDirectDrawPalette object
3789  *
3790  * Params:
3791  *  Flags: The flags for the new clipper
3792  *  ColorTable: Color table to assign to the new clipper
3793  *  Palette: Address to write the interface pointer to
3794  *  UnkOuter: For aggregation support, which ddraw doesn't have. Has to be
3795  *            NULL
3796  *
3797  * Returns:
3798  *  CLASS_E_NOAGGREGATION if UnkOuter != NULL
3799  *  E_OUTOFMEMORY if allocating the object failed
3800  *
3801  *****************************************************************************/
3802 static HRESULT WINAPI ddraw7_CreatePalette(IDirectDraw7 *iface, DWORD Flags,
3803         PALETTEENTRY *ColorTable, IDirectDrawPalette **Palette, IUnknown *pUnkOuter)
3804 {
3805     IDirectDrawImpl *This = (IDirectDrawImpl *)iface;
3806     IDirectDrawPaletteImpl *object;
3807     HRESULT hr;
3808
3809     TRACE("iface %p, flags %#x, color_table %p, palette %p, outer_unknown %p.\n",
3810             iface, Flags, ColorTable, Palette, pUnkOuter);
3811
3812     EnterCriticalSection(&ddraw_cs);
3813     if(pUnkOuter != NULL)
3814     {
3815         WARN("pUnkOuter is %p, returning CLASS_E_NOAGGREGATION\n", pUnkOuter);
3816         LeaveCriticalSection(&ddraw_cs);
3817         return CLASS_E_NOAGGREGATION;
3818     }
3819
3820     /* The refcount test shows that a cooplevel is required for this */
3821     if(!This->cooperative_level)
3822     {
3823         WARN("No cooperative level set, returning DDERR_NOCOOPERATIVELEVELSET\n");
3824         LeaveCriticalSection(&ddraw_cs);
3825         return DDERR_NOCOOPERATIVELEVELSET;
3826     }
3827
3828     object = HeapAlloc(GetProcessHeap(), 0, sizeof(IDirectDrawPaletteImpl));
3829     if(!object)
3830     {
3831         ERR("Out of memory when allocating memory for a palette implementation\n");
3832         LeaveCriticalSection(&ddraw_cs);
3833         return E_OUTOFMEMORY;
3834     }
3835
3836     hr = ddraw_palette_init(object, This, Flags, ColorTable);
3837     if (FAILED(hr))
3838     {
3839         WARN("Failed to initialize palette, hr %#x.\n", hr);
3840         HeapFree(GetProcessHeap(), 0, object);
3841         LeaveCriticalSection(&ddraw_cs);
3842         return hr;
3843     }
3844
3845     TRACE("Created palette %p.\n", object);
3846     *Palette = (IDirectDrawPalette *)object;
3847     LeaveCriticalSection(&ddraw_cs);
3848     return DD_OK;
3849 }
3850
3851 static HRESULT WINAPI ddraw4_CreatePalette(IDirectDraw4 *iface, DWORD flags,
3852         PALETTEENTRY *entries, IDirectDrawPalette **palette, IUnknown *outer_unknown)
3853 {
3854     IDirectDrawImpl *ddraw = ddraw_from_ddraw4(iface);
3855     HRESULT hr;
3856
3857     TRACE("iface %p, flags %#x, entries %p, palette %p, outer_unknown %p.\n",
3858             iface, flags, entries, palette, outer_unknown);
3859
3860     hr = ddraw7_CreatePalette((IDirectDraw7 *)ddraw, flags, entries, palette, outer_unknown);
3861     if (SUCCEEDED(hr) && *palette)
3862     {
3863         IDirectDrawPaletteImpl *impl = (IDirectDrawPaletteImpl *)*palette;
3864         IDirectDraw7_Release((IDirectDraw7 *)ddraw);
3865         IDirectDraw4_AddRef(iface);
3866         impl->ifaceToRelease = (IUnknown *)iface;
3867     }
3868     return hr;
3869 }
3870
3871 static HRESULT WINAPI ddraw3_CreatePalette(IDirectDraw3 *iface, DWORD flags,
3872         PALETTEENTRY *entries, IDirectDrawPalette **palette, IUnknown *outer_unknown)
3873 {
3874     IDirectDrawImpl *ddraw = ddraw_from_ddraw3(iface);
3875     HRESULT hr;
3876
3877     TRACE("iface %p, flags %#x, entries %p, palette %p, outer_unknown %p.\n",
3878             iface, flags, entries, palette, outer_unknown);
3879
3880     hr = ddraw7_CreatePalette((IDirectDraw7 *)ddraw, flags, entries, palette, outer_unknown);
3881     if (SUCCEEDED(hr) && *palette)
3882     {
3883         IDirectDrawPaletteImpl *impl = (IDirectDrawPaletteImpl *)*palette;
3884         IDirectDraw7_Release((IDirectDraw7 *)ddraw);
3885         IDirectDraw4_AddRef(iface);
3886         impl->ifaceToRelease = (IUnknown *)iface;
3887     }
3888
3889     return hr;
3890 }
3891
3892 static HRESULT WINAPI ddraw2_CreatePalette(IDirectDraw2 *iface, DWORD flags,
3893         PALETTEENTRY *entries, IDirectDrawPalette **palette, IUnknown *outer_unknown)
3894 {
3895     IDirectDrawImpl *ddraw = ddraw_from_ddraw2(iface);
3896     HRESULT hr;
3897
3898     TRACE("iface %p, flags %#x, entries %p, palette %p, outer_unknown %p.\n",
3899             iface, flags, entries, palette, outer_unknown);
3900
3901     hr = ddraw7_CreatePalette((IDirectDraw7 *)ddraw, flags, entries, palette, outer_unknown);
3902     if (SUCCEEDED(hr) && *palette)
3903     {
3904         IDirectDrawPaletteImpl *impl = (IDirectDrawPaletteImpl *)*palette;
3905         IDirectDraw7_Release((IDirectDraw7 *)ddraw);
3906         impl->ifaceToRelease = NULL;
3907     }
3908
3909     return hr;
3910 }
3911
3912 static HRESULT WINAPI ddraw1_CreatePalette(IDirectDraw *iface, DWORD flags,
3913         PALETTEENTRY *entries, IDirectDrawPalette **palette, IUnknown *outer_unknown)
3914 {
3915     IDirectDrawImpl *ddraw = ddraw_from_ddraw1(iface);
3916     HRESULT hr;
3917
3918     TRACE("iface %p, flags %#x, entries %p, palette %p, outer_unknown %p.\n",
3919             iface, flags, entries, palette, outer_unknown);
3920
3921     hr = ddraw7_CreatePalette((IDirectDraw7 *)ddraw, flags, entries, palette, outer_unknown);
3922     if (SUCCEEDED(hr) && *palette)
3923     {
3924         IDirectDrawPaletteImpl *impl = (IDirectDrawPaletteImpl *)*palette;
3925         IDirectDraw7_Release((IDirectDraw7 *)ddraw);
3926         impl->ifaceToRelease = NULL;
3927     }
3928
3929     return hr;
3930 }
3931
3932 /*****************************************************************************
3933  * IDirectDraw7::DuplicateSurface
3934  *
3935  * Duplicates a surface. The surface memory points to the same memory as
3936  * the original surface, and it's released when the last surface referencing
3937  * it is released. I guess that's beyond Wine's surface management right now
3938  * (Idea: create a new DDraw surface with the same WineD3DSurface. I need a
3939  * test application to implement this)
3940  *
3941  * Params:
3942  *  Src: Address of the source surface
3943  *  Dest: Address to write the new surface pointer to
3944  *
3945  * Returns:
3946  *  See IDirectDraw7::CreateSurface
3947  *
3948  *****************************************************************************/
3949 static HRESULT WINAPI ddraw7_DuplicateSurface(IDirectDraw7 *iface,
3950         IDirectDrawSurface7 *Src, IDirectDrawSurface7 **Dest)
3951 {
3952     IDirectDrawSurfaceImpl *Surf = (IDirectDrawSurfaceImpl *)Src;
3953
3954     FIXME("iface %p, src %p, dst %p partial stub!\n", iface, Src, Dest);
3955
3956     /* For now, simply create a new, independent surface */
3957     return IDirectDraw7_CreateSurface(iface,
3958                                       &Surf->surface_desc,
3959                                       Dest,
3960                                       NULL);
3961 }
3962
3963 static HRESULT WINAPI ddraw4_DuplicateSurface(IDirectDraw4 *iface,
3964         IDirectDrawSurface4 *src, IDirectDrawSurface4 **dst)
3965 {
3966     TRACE("iface %p, src %p, dst %p.\n", iface, src, dst);
3967
3968     return ddraw7_DuplicateSurface((IDirectDraw7 *)ddraw_from_ddraw4(iface),
3969             (IDirectDrawSurface7 *)src, (IDirectDrawSurface7 **)dst);
3970 }
3971
3972 static HRESULT WINAPI ddraw3_DuplicateSurface(IDirectDraw3 *iface,
3973         IDirectDrawSurface *src, IDirectDrawSurface **dst)
3974 {
3975     IDirectDrawSurface7 *src7, *dst7;
3976     HRESULT hr;
3977
3978     TRACE("iface %p, src %p, dst %p.\n", iface, src, dst);
3979     src7 = (IDirectDrawSurface7 *)surface_from_surface3((IDirectDrawSurface3 *)src);
3980     hr = ddraw7_DuplicateSurface((IDirectDraw7 *)ddraw_from_ddraw3(iface), src7, &dst7);
3981     if (FAILED(hr))
3982         return hr;
3983     *dst = (IDirectDrawSurface *)&((IDirectDrawSurfaceImpl *)dst7)->IDirectDrawSurface3_vtbl;
3984     return hr;
3985 }
3986
3987 static HRESULT WINAPI ddraw2_DuplicateSurface(IDirectDraw2 *iface,
3988         IDirectDrawSurface *src, IDirectDrawSurface **dst)
3989 {
3990     IDirectDrawSurface7 *src7, *dst7;
3991     HRESULT hr;
3992
3993     TRACE("iface %p, src %p, dst %p.\n", iface, src, dst);
3994     src7 = (IDirectDrawSurface7 *)surface_from_surface3((IDirectDrawSurface3 *)src);
3995     hr = ddraw7_DuplicateSurface((IDirectDraw7 *)ddraw_from_ddraw2(iface), src7, &dst7);
3996     if (FAILED(hr))
3997         return hr;
3998     *dst = (IDirectDrawSurface *)&((IDirectDrawSurfaceImpl *)dst7)->IDirectDrawSurface3_vtbl;
3999     return hr;
4000 }
4001
4002 static HRESULT WINAPI ddraw1_DuplicateSurface(IDirectDraw *iface,
4003         IDirectDrawSurface *src, IDirectDrawSurface **dst)
4004 {
4005     IDirectDrawSurface7 *src7, *dst7;
4006     HRESULT hr;
4007
4008     TRACE("iface %p, src %p, dst %p.\n", iface, src, dst);
4009     src7 = (IDirectDrawSurface7 *)surface_from_surface3((IDirectDrawSurface3 *)src);
4010     hr = ddraw7_DuplicateSurface((IDirectDraw7 *)ddraw_from_ddraw1(iface), src7, &dst7);
4011     if (FAILED(hr))
4012         return hr;
4013     *dst = (IDirectDrawSurface *)&((IDirectDrawSurfaceImpl *)dst7)->IDirectDrawSurface3_vtbl;
4014     return hr;
4015 }
4016
4017 /*****************************************************************************
4018  * IDirect3D7::EnumDevices
4019  *
4020  * The EnumDevices method for IDirect3D7. It enumerates all supported
4021  * D3D7 devices. Currently the T&L, HAL and RGB devices are enumerated.
4022  *
4023  * Params:
4024  *  callback: Function to call for each enumerated device
4025  *  context: Pointer to pass back to the app
4026  *
4027  * Returns:
4028  *  D3D_OK, or the return value of the GetCaps call
4029  *
4030  *****************************************************************************/
4031 static HRESULT WINAPI d3d7_EnumDevices(IDirect3D7 *iface, LPD3DENUMDEVICESCALLBACK7 callback, void *context)
4032 {
4033     char interface_name_tnl[] = "WINE Direct3D7 Hardware Transform and Lighting acceleration using WineD3D";
4034     char device_name_tnl[] = "Wine D3D7 T&L HAL";
4035     char interface_name_hal[] = "WINE Direct3D7 Hardware acceleration using WineD3D";
4036     char device_name_hal[] = "Wine D3D7 HAL";
4037     char interface_name_rgb[] = "WINE Direct3D7 RGB Software Emulation using WineD3D";
4038     char device_name_rgb[] = "Wine D3D7 RGB";
4039
4040     IDirectDrawImpl *ddraw = ddraw_from_d3d7(iface);
4041     D3DDEVICEDESC7 device_desc7;
4042     D3DDEVICEDESC device_desc1;
4043     HRESULT hr;
4044
4045     TRACE("iface %p, callback %p, context %p.\n", iface, callback, context);
4046
4047     EnterCriticalSection(&ddraw_cs);
4048
4049     hr = IDirect3DImpl_GetCaps(ddraw->wineD3D, &device_desc1, &device_desc7);
4050     if (hr != D3D_OK)
4051     {
4052         LeaveCriticalSection(&ddraw_cs);
4053         return hr;
4054     }
4055     callback(interface_name_tnl, device_name_tnl, &device_desc7, context);
4056
4057     device_desc7.deviceGUID = IID_IDirect3DHALDevice;
4058     callback(interface_name_hal, device_name_hal, &device_desc7, context);
4059
4060     device_desc7.deviceGUID = IID_IDirect3DRGBDevice;
4061     callback(interface_name_rgb, device_name_rgb, &device_desc7, context);
4062
4063     TRACE("End of enumeration.\n");
4064
4065     LeaveCriticalSection(&ddraw_cs);
4066
4067     return D3D_OK;
4068 }
4069
4070 /*****************************************************************************
4071  * IDirect3D3::EnumDevices
4072  *
4073  * Enumerates all supported Direct3DDevice interfaces. This is the
4074  * implementation for Direct3D 1 to Direc3D 3, Version 7 has its own.
4075  *
4076  * Version 1, 2 and 3
4077  *
4078  * Params:
4079  *  callback: Application-provided routine to call for each enumerated device
4080  *  Context: Pointer to pass to the callback
4081  *
4082  * Returns:
4083  *  D3D_OK on success,
4084  *  The result of IDirect3DImpl_GetCaps if it failed
4085  *
4086  *****************************************************************************/
4087 static HRESULT WINAPI d3d3_EnumDevices(IDirect3D3 *iface, LPD3DENUMDEVICESCALLBACK callback, void *context)
4088 {
4089     static CHAR wined3d_description[] = "Wine D3DDevice using WineD3D and OpenGL";
4090
4091     IDirectDrawImpl *ddraw = ddraw_from_d3d3(iface);
4092     D3DDEVICEDESC device_desc1, hal_desc, hel_desc;
4093     D3DDEVICEDESC7 device_desc7;
4094     HRESULT hr;
4095
4096     /* Some games (Motoracer 2 demo) have the bad idea to modify the device
4097      * name string. Let's put the string in a sufficiently sized array in
4098      * writable memory. */
4099     char device_name[50];
4100     strcpy(device_name,"Direct3D HEL");
4101
4102     TRACE("iface %p, callback %p, context %p.\n", iface, callback, context);
4103
4104     EnterCriticalSection(&ddraw_cs);
4105
4106     hr = IDirect3DImpl_GetCaps(ddraw->wineD3D, &device_desc1, &device_desc7);
4107     if (hr != D3D_OK)
4108     {
4109         LeaveCriticalSection(&ddraw_cs);
4110         return hr;
4111     }
4112
4113     /* Do I have to enumerate the reference id? Note from old d3d7:
4114      * "It seems that enumerating the reference IID on Direct3D 1 games
4115      * (AvP / Motoracer2) breaks them". So do not enumerate this iid in V1
4116      *
4117      * There's a registry key HKLM\Software\Microsoft\Direct3D\Drivers,
4118      * EnumReference which enables / disables enumerating the reference
4119      * rasterizer. It's a DWORD, 0 means disabled, 2 means enabled. The
4120      * enablerefrast.reg and disablerefrast.reg files in the DirectX 7.0 sdk
4121      * demo directory suggest this.
4122      *
4123      * Some games(GTA 2) seem to use the second enumerated device, so I have
4124      * to enumerate at least 2 devices. So enumerate the reference device to
4125      * have 2 devices.
4126      *
4127      * Other games (Rollcage) tell emulation and hal device apart by certain
4128      * flags. Rollcage expects D3DPTEXTURECAPS_POW2 to be set (yeah, it is a
4129      * limitation flag), and it refuses all devices that have the perspective
4130      * flag set. This way it refuses the emulation device, and HAL devices
4131      * never have POW2 unset in d3d7 on windows. */
4132     if (ddraw->d3dversion != 1)
4133     {
4134         static CHAR reference_description[] = "RGB Direct3D emulation";
4135
4136         TRACE("Enumerating WineD3D D3DDevice interface.\n");
4137         hal_desc = device_desc1;
4138         hel_desc = device_desc1;
4139         /* The rgb device has the pow2 flag set in the hel caps, but not in the hal caps. */
4140         hal_desc.dpcLineCaps.dwTextureCaps &= ~(D3DPTEXTURECAPS_POW2
4141                 | D3DPTEXTURECAPS_NONPOW2CONDITIONAL | D3DPTEXTURECAPS_PERSPECTIVE);
4142         hal_desc.dpcTriCaps.dwTextureCaps &= ~(D3DPTEXTURECAPS_POW2
4143                 | D3DPTEXTURECAPS_NONPOW2CONDITIONAL | D3DPTEXTURECAPS_PERSPECTIVE);
4144         hr = callback((GUID *)&IID_IDirect3DRGBDevice, reference_description,
4145                 device_name, &hal_desc, &hel_desc, context);
4146         if (hr != D3DENUMRET_OK)
4147         {
4148             TRACE("Application cancelled the enumeration.\n");
4149             LeaveCriticalSection(&ddraw_cs);
4150             return D3D_OK;
4151         }
4152     }
4153
4154     strcpy(device_name,"Direct3D HAL");
4155
4156     TRACE("Enumerating HAL Direct3D device.\n");
4157     hal_desc = device_desc1;
4158     hel_desc = device_desc1;
4159     /* The hal device does not have the pow2 flag set in hel, but in hal. */
4160     hel_desc.dpcLineCaps.dwTextureCaps &= ~(D3DPTEXTURECAPS_POW2
4161             | D3DPTEXTURECAPS_NONPOW2CONDITIONAL | D3DPTEXTURECAPS_PERSPECTIVE);
4162     hel_desc.dpcTriCaps.dwTextureCaps &= ~(D3DPTEXTURECAPS_POW2
4163             | D3DPTEXTURECAPS_NONPOW2CONDITIONAL | D3DPTEXTURECAPS_PERSPECTIVE);
4164     hr = callback((GUID *)&IID_IDirect3DHALDevice, wined3d_description,
4165             device_name, &hal_desc, &hel_desc, context);
4166     if (hr != D3DENUMRET_OK)
4167     {
4168         TRACE("Application cancelled the enumeration.\n");
4169         LeaveCriticalSection(&ddraw_cs);
4170         return D3D_OK;
4171     }
4172
4173     TRACE("End of enumeration.\n");
4174
4175     LeaveCriticalSection(&ddraw_cs);
4176     return D3D_OK;
4177 }
4178
4179 static HRESULT WINAPI d3d2_EnumDevices(IDirect3D2 *iface, LPD3DENUMDEVICESCALLBACK callback, void *context)
4180 {
4181     TRACE("iface %p, callback %p, context %p.\n", iface, callback, context);
4182
4183     return d3d3_EnumDevices((IDirect3D3 *)&ddraw_from_d3d2(iface)->IDirect3D3_vtbl, callback, context);
4184 }
4185
4186 static HRESULT WINAPI d3d1_EnumDevices(IDirect3D *iface, LPD3DENUMDEVICESCALLBACK callback, void *context)
4187 {
4188     TRACE("iface %p, callback %p, context %p.\n", iface, callback, context);
4189
4190     return d3d3_EnumDevices((IDirect3D3 *)&ddraw_from_d3d1(iface)->IDirect3D3_vtbl, callback, context);
4191 }
4192
4193 /*****************************************************************************
4194  * IDirect3D3::CreateLight
4195  *
4196  * Creates an IDirect3DLight interface. This interface is used in
4197  * Direct3D3 or earlier for lighting. In Direct3D7 it has been replaced
4198  * by the DIRECT3DLIGHT7 structure. Wine's Direct3DLight implementation
4199  * uses the IDirect3DDevice7 interface with D3D7 lights.
4200  *
4201  * Version 1, 2 and 3
4202  *
4203  * Params:
4204  *  light: Address to store the new interface pointer
4205  *  outer_unknown: Basically for aggregation, but ddraw doesn't support it.
4206  *                 Must be NULL
4207  *
4208  * Returns:
4209  *  D3D_OK on success
4210  *  DDERR_OUTOFMEMORY if memory allocation failed
4211  *  CLASS_E_NOAGGREGATION if outer_unknown != NULL
4212  *
4213  *****************************************************************************/
4214 static HRESULT WINAPI d3d3_CreateLight(IDirect3D3 *iface, IDirect3DLight **light, IUnknown *outer_unknown)
4215 {
4216     IDirect3DLightImpl *object;
4217
4218     TRACE("iface %p, light %p, outer_unknown %p.\n", iface, light, outer_unknown);
4219
4220     if (outer_unknown) return CLASS_E_NOAGGREGATION;
4221
4222     object = HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, sizeof(*object));
4223     if (!object)
4224     {
4225         ERR("Failed to allocate light memory.\n");
4226         return DDERR_OUTOFMEMORY;
4227     }
4228
4229     d3d_light_init(object, ddraw_from_d3d3(iface));
4230
4231     TRACE("Created light %p.\n", object);
4232     *light = (IDirect3DLight *)object;
4233
4234     return D3D_OK;
4235 }
4236
4237 static HRESULT WINAPI d3d2_CreateLight(IDirect3D2 *iface, IDirect3DLight **light, IUnknown *outer_unknown)
4238 {
4239     TRACE("iface %p, light %p, outer_unknown %p.\n", iface, light, outer_unknown);
4240
4241     return d3d3_CreateLight((IDirect3D3 *)&ddraw_from_d3d2(iface)->IDirect3D3_vtbl, light, outer_unknown);
4242 }
4243
4244 static HRESULT WINAPI d3d1_CreateLight(IDirect3D *iface, IDirect3DLight **light, IUnknown *outer_unknown)
4245 {
4246     TRACE("iface %p, light %p, outer_unknown %p.\n", iface, light, outer_unknown);
4247
4248     return d3d3_CreateLight((IDirect3D3 *)&ddraw_from_d3d1(iface)->IDirect3D3_vtbl, light, outer_unknown);
4249 }
4250
4251 /*****************************************************************************
4252  * IDirect3D3::CreateMaterial
4253  *
4254  * Creates an IDirect3DMaterial interface. This interface is used by Direct3D3
4255  * and older versions. The IDirect3DMaterial implementation wraps its
4256  * functionality to IDirect3DDevice7::SetMaterial and friends.
4257  *
4258  * Version 1, 2 and 3
4259  *
4260  * Params:
4261  *  material: Address to store the new interface's pointer to
4262  *  outer_unknown: Basically for aggregation, but ddraw doesn't support it.
4263  *                 Must be NULL
4264  *
4265  * Returns:
4266  *  D3D_OK on success
4267  *  DDERR_OUTOFMEMORY if memory allocation failed
4268  *  CLASS_E_NOAGGREGATION if outer_unknown != NULL
4269  *
4270  *****************************************************************************/
4271 static HRESULT WINAPI d3d3_CreateMaterial(IDirect3D3 *iface, IDirect3DMaterial3 **material, IUnknown *outer_unknown)
4272 {
4273     IDirect3DMaterialImpl *object;
4274
4275     TRACE("iface %p, material %p, outer_unknown %p.\n", iface, material, outer_unknown);
4276
4277     if (outer_unknown) return CLASS_E_NOAGGREGATION;
4278
4279     object = HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, sizeof(*object));
4280     if (!object)
4281     {
4282         ERR("Failed to allocate material memory.\n");
4283         return DDERR_OUTOFMEMORY;
4284     }
4285
4286     d3d_material_init(object, ddraw_from_d3d3(iface));
4287
4288     TRACE("Created material %p.\n", object);
4289     *material = (IDirect3DMaterial3 *)object;
4290
4291     return D3D_OK;
4292 }
4293
4294 static HRESULT WINAPI d3d2_CreateMaterial(IDirect3D2 *iface, IDirect3DMaterial2 **material, IUnknown *outer_unknown)
4295 {
4296     IDirect3DMaterial3 *material3;
4297     HRESULT hr;
4298
4299     TRACE("iface %p, material %p, outer_unknown %p.\n", iface, material, outer_unknown);
4300
4301     hr = d3d3_CreateMaterial((IDirect3D3 *)&ddraw_from_d3d2(iface)->IDirect3D3_vtbl, &material3, outer_unknown);
4302     *material = material3 ? (IDirect3DMaterial2 *)&((IDirect3DMaterialImpl *)material3)->IDirect3DMaterial2_vtbl : NULL;
4303
4304     TRACE("Returning material %p.\n", *material);
4305
4306     return hr;
4307 }
4308
4309 static HRESULT WINAPI d3d1_CreateMaterial(IDirect3D *iface, IDirect3DMaterial **material, IUnknown *outer_unknown)
4310 {
4311     IDirect3DMaterial3 *material3;
4312     HRESULT hr;
4313
4314     TRACE("iface %p, material %p, outer_unknown %p.\n", iface, material, outer_unknown);
4315
4316     hr = d3d3_CreateMaterial((IDirect3D3 *)&ddraw_from_d3d1(iface)->IDirect3D3_vtbl, &material3, outer_unknown);
4317     *material = material3 ? (IDirect3DMaterial *)&((IDirect3DMaterialImpl *)material3)->IDirect3DMaterial_vtbl : NULL;
4318
4319     TRACE("Returning material %p.\n", *material);
4320
4321     return hr;
4322 }
4323
4324 /*****************************************************************************
4325  * IDirect3D3::CreateViewport
4326  *
4327  * Creates an IDirect3DViewport interface. This interface is used
4328  * by Direct3D and earlier versions for Viewport management. In Direct3D7
4329  * it has been replaced by a viewport structure and
4330  * IDirect3DDevice7::*Viewport. Wine's IDirect3DViewport implementation
4331  * uses the IDirect3DDevice7 methods for its functionality
4332  *
4333  * Params:
4334  *  Viewport: Address to store the new interface pointer
4335  *  outer_unknown: Basically for aggregation, but ddraw doesn't support it.
4336  *                 Must be NULL
4337  *
4338  * Returns:
4339  *  D3D_OK on success
4340  *  DDERR_OUTOFMEMORY if memory allocation failed
4341  *  CLASS_E_NOAGGREGATION if outer_unknown != NULL
4342  *
4343  *****************************************************************************/
4344 static HRESULT WINAPI d3d3_CreateViewport(IDirect3D3 *iface, IDirect3DViewport3 **viewport, IUnknown *outer_unknown)
4345 {
4346     IDirect3DViewportImpl *object;
4347
4348     TRACE("iface %p, viewport %p, outer_unknown %p.\n", iface, viewport, outer_unknown);
4349
4350     if (outer_unknown) return CLASS_E_NOAGGREGATION;
4351
4352     object = HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, sizeof(*object));
4353     if (!object)
4354     {
4355         ERR("Failed to allocate viewport memory.\n");
4356         return DDERR_OUTOFMEMORY;
4357     }
4358
4359     d3d_viewport_init(object, ddraw_from_d3d3(iface));
4360
4361     TRACE("Created viewport %p.\n", object);
4362     *viewport = (IDirect3DViewport3 *)object;
4363
4364     return D3D_OK;
4365 }
4366
4367 static HRESULT WINAPI d3d2_CreateViewport(IDirect3D2 *iface, IDirect3DViewport2 **viewport, IUnknown *outer_unknown)
4368 {
4369     TRACE("iface %p, viewport %p, outer_unknown %p.\n", iface, viewport, outer_unknown);
4370
4371     return d3d3_CreateViewport((IDirect3D3 *)&ddraw_from_d3d2(iface)->IDirect3D3_vtbl,
4372             (IDirect3DViewport3 **)viewport, outer_unknown);
4373 }
4374
4375 static HRESULT WINAPI d3d1_CreateViewport(IDirect3D *iface, IDirect3DViewport **viewport, IUnknown *outer_unknown)
4376 {
4377     TRACE("iface %p, viewport %p, outer_unknown %p.\n", iface, viewport, outer_unknown);
4378
4379     return d3d3_CreateViewport((IDirect3D3 *)&ddraw_from_d3d1(iface)->IDirect3D3_vtbl,
4380             (IDirect3DViewport3 **)viewport, outer_unknown);
4381 }
4382
4383 /*****************************************************************************
4384  * IDirect3D3::FindDevice
4385  *
4386  * This method finds a device with the requested properties and returns a
4387  * device description
4388  *
4389  * Verion 1, 2 and 3
4390  * Params:
4391  *  fds: Describes the requested device characteristics
4392  *  fdr: Returns the device description
4393  *
4394  * Returns:
4395  *  D3D_OK on success
4396  *  DDERR_INVALIDPARAMS if no device was found
4397  *
4398  *****************************************************************************/
4399 static HRESULT WINAPI d3d3_FindDevice(IDirect3D3 *iface, D3DFINDDEVICESEARCH *fds, D3DFINDDEVICERESULT *fdr)
4400 {
4401     IDirectDrawImpl *ddraw = ddraw_from_d3d3(iface);
4402     D3DDEVICEDESC7 desc7;
4403     D3DDEVICEDESC desc1;
4404     HRESULT hr;
4405
4406     TRACE("iface %p, fds %p, fdr %p.\n", iface, fds, fdr);
4407
4408     if (!fds || !fdr) return DDERR_INVALIDPARAMS;
4409
4410     if (fds->dwSize != sizeof(D3DFINDDEVICESEARCH)
4411             || fdr->dwSize != sizeof(D3DFINDDEVICERESULT))
4412         return DDERR_INVALIDPARAMS;
4413
4414     if ((fds->dwFlags & D3DFDS_COLORMODEL)
4415             && fds->dcmColorModel != D3DCOLOR_RGB)
4416     {
4417         WARN("Trying to request a non-RGB D3D color model. Not supported.\n");
4418         return DDERR_INVALIDPARAMS; /* No real idea what to return here :-) */
4419     }
4420
4421     if (fds->dwFlags & D3DFDS_GUID)
4422     {
4423         TRACE("Trying to match guid %s.\n", debugstr_guid(&(fds->guid)));
4424         if (!IsEqualGUID(&IID_D3DDEVICE_WineD3D, &fds->guid)
4425                 && !IsEqualGUID(&IID_IDirect3DHALDevice, &fds->guid)
4426                 && !IsEqualGUID(&IID_IDirect3DRGBDevice, &fds->guid))
4427         {
4428             WARN("No match for this GUID.\n");
4429             return DDERR_NOTFOUND;
4430         }
4431     }
4432
4433     /* Get the caps */
4434     hr = IDirect3DImpl_GetCaps(ddraw->wineD3D, &desc1, &desc7);
4435     if (hr != D3D_OK) return hr;
4436
4437     /* Now return our own GUID */
4438     fdr->guid = IID_D3DDEVICE_WineD3D;
4439     fdr->ddHwDesc = desc1;
4440     fdr->ddSwDesc = desc1;
4441
4442     TRACE("Returning Wine's wined3d device with (undumped) capabilities.\n");
4443
4444     return D3D_OK;
4445 }
4446
4447 static HRESULT WINAPI d3d2_FindDevice(IDirect3D2 *iface, D3DFINDDEVICESEARCH *fds, D3DFINDDEVICERESULT *fdr)
4448 {
4449     TRACE("iface %p, fds %p, fdr %p.\n", iface, fds, fdr);
4450
4451     return d3d3_FindDevice((IDirect3D3 *)&ddraw_from_d3d2(iface)->IDirect3D3_vtbl, fds, fdr);
4452 }
4453
4454 static HRESULT WINAPI d3d1_FindDevice(IDirect3D *iface, D3DFINDDEVICESEARCH *fds, D3DFINDDEVICERESULT *fdr)
4455 {
4456     TRACE("iface %p, fds %p, fdr %p.\n", iface, fds, fdr);
4457
4458     return d3d3_FindDevice((IDirect3D3 *)&ddraw_from_d3d1(iface)->IDirect3D3_vtbl, fds, fdr);
4459 }
4460
4461 /*****************************************************************************
4462  * IDirect3D7::CreateDevice
4463  *
4464  * Creates an IDirect3DDevice7 interface.
4465  *
4466  * Version 2, 3 and 7. IDirect3DDevice 1 interfaces are interfaces to
4467  * DirectDraw surfaces and are created with
4468  * IDirectDrawSurface::QueryInterface. This method uses CreateDevice to
4469  * create the device object and QueryInterfaces for IDirect3DDevice
4470  *
4471  * Params:
4472  *  refiid: IID of the device to create
4473  *  Surface: Initial rendertarget
4474  *  Device: Address to return the interface pointer
4475  *
4476  * Returns:
4477  *  D3D_OK on success
4478  *  DDERR_OUTOFMEMORY if memory allocation failed
4479  *  DDERR_INVALIDPARAMS if a device exists already
4480  *
4481  *****************************************************************************/
4482 static HRESULT WINAPI d3d7_CreateDevice(IDirect3D7 *iface, REFCLSID riid,
4483         IDirectDrawSurface7 *surface, IDirect3DDevice7 **device)
4484 {
4485     IDirectDrawSurfaceImpl *target = (IDirectDrawSurfaceImpl *)surface;
4486     IDirectDrawImpl *ddraw = ddraw_from_d3d7(iface);
4487     IDirect3DDeviceImpl *object;
4488     HRESULT hr;
4489
4490     TRACE("iface %p, riid %s, surface %p, device %p.\n", iface, debugstr_guid(riid), surface, device);
4491
4492     EnterCriticalSection(&ddraw_cs);
4493     *device = NULL;
4494
4495     /* Fail device creation if non-opengl surfaces are used. */
4496     if (ddraw->ImplType != SURFACE_OPENGL)
4497     {
4498         ERR("The application wants to create a Direct3D device, but non-opengl surfaces are set in the registry.\n");
4499         ERR("Please set the surface implementation to opengl or autodetection to allow 3D rendering.\n");
4500
4501         /* We only hit this path if a default surface is set in the registry. Incorrect autodetection
4502          * is caught in CreateSurface or QueryInterface. */
4503         LeaveCriticalSection(&ddraw_cs);
4504         return DDERR_NO3D;
4505     }
4506
4507     if (ddraw->d3ddevice)
4508     {
4509         FIXME("Only one Direct3D device per DirectDraw object supported.\n");
4510         LeaveCriticalSection(&ddraw_cs);
4511         return DDERR_INVALIDPARAMS;
4512     }
4513
4514     object = HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, sizeof(*object));
4515     if (!object)
4516     {
4517         ERR("Failed to allocate device memory.\n");
4518         LeaveCriticalSection(&ddraw_cs);
4519         return DDERR_OUTOFMEMORY;
4520     }
4521
4522     hr = d3d_device_init(object, ddraw, target);
4523     if (FAILED(hr))
4524     {
4525         WARN("Failed to initialize device, hr %#x.\n", hr);
4526         HeapFree(GetProcessHeap(), 0, object);
4527         LeaveCriticalSection(&ddraw_cs);
4528         return hr;
4529     }
4530
4531     TRACE("Created device %p.\n", object);
4532     *device = (IDirect3DDevice7 *)object;
4533
4534     LeaveCriticalSection(&ddraw_cs);
4535     return D3D_OK;
4536 }
4537
4538 static HRESULT WINAPI d3d3_CreateDevice(IDirect3D3 *iface, REFCLSID riid,
4539         IDirectDrawSurface4 *surface, IDirect3DDevice3 **device, IUnknown *outer_unknown)
4540 {
4541     HRESULT hr;
4542
4543     TRACE("iface %p, riid %s, surface %p, device %p, outer_unknown %p.\n",
4544             iface, debugstr_guid(riid), surface, device, outer_unknown);
4545
4546     if (outer_unknown) return CLASS_E_NOAGGREGATION;
4547
4548     hr = d3d7_CreateDevice((IDirect3D7 *)&ddraw_from_d3d3(iface)->IDirect3D7_vtbl, riid,
4549             (IDirectDrawSurface7 *)surface, (IDirect3DDevice7 **)device);
4550     if (*device) *device = (IDirect3DDevice3 *)&((IDirect3DDeviceImpl *)*device)->IDirect3DDevice3_vtbl;
4551
4552     return hr;
4553 }
4554
4555 static HRESULT WINAPI d3d2_CreateDevice(IDirect3D2 *iface, REFCLSID riid,
4556         IDirectDrawSurface *surface, IDirect3DDevice2 **device)
4557 {
4558     HRESULT hr;
4559
4560     TRACE("iface %p, riid %s, surface %p, device %p.\n",
4561             iface, debugstr_guid(riid), surface, device);
4562
4563     hr = d3d7_CreateDevice((IDirect3D7 *)&ddraw_from_d3d2(iface)->IDirect3D7_vtbl, riid,
4564             surface ? (IDirectDrawSurface7 *)surface_from_surface3((IDirectDrawSurface3 *)surface) : NULL,
4565             (IDirect3DDevice7 **)device);
4566     if (*device) *device = (IDirect3DDevice2 *)&((IDirect3DDeviceImpl *)*device)->IDirect3DDevice2_vtbl;
4567
4568     return hr;
4569 }
4570
4571 /*****************************************************************************
4572  * IDirect3D7::CreateVertexBuffer
4573  *
4574  * Creates a new vertex buffer object and returns a IDirect3DVertexBuffer7
4575  * interface.
4576  *
4577  * Version 3 and 7
4578  *
4579  * Params:
4580  *  desc: Requested Vertex buffer properties
4581  *  vertex_buffer: Address to return the interface pointer at
4582  *  flags: Some flags, should be 0
4583  *
4584  * Returns
4585  *  D3D_OK on success
4586  *  DDERR_OUTOFMEMORY if memory allocation failed
4587  *  The return value of IWineD3DDevice::CreateVertexBuffer if this call fails
4588  *  DDERR_INVALIDPARAMS if desc or vertex_buffer are NULL
4589  *
4590  *****************************************************************************/
4591 static HRESULT WINAPI d3d7_CreateVertexBuffer(IDirect3D7 *iface, D3DVERTEXBUFFERDESC *desc,
4592         IDirect3DVertexBuffer7 **vertex_buffer, DWORD flags)
4593 {
4594     IDirect3DVertexBufferImpl *object;
4595     HRESULT hr;
4596
4597     TRACE("iface %p, desc %p, vertex_buffer %p, flags %#x.\n",
4598             iface, desc, vertex_buffer, flags);
4599
4600     if (!vertex_buffer || !desc) return DDERR_INVALIDPARAMS;
4601
4602     TRACE("Vertex buffer description:\n");
4603     TRACE("    dwSize %u\n", desc->dwSize);
4604     TRACE("    dwCaps %#x\n", desc->dwCaps);
4605     TRACE("    FVF %#x\n", desc->dwFVF);
4606     TRACE("    dwNumVertices %u\n", desc->dwNumVertices);
4607
4608     /* Now create the vertex buffer */
4609     object = HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, sizeof(*object));
4610     if (!object)
4611     {
4612         ERR("Failed to allocate vertex buffer memory.\n");
4613         return DDERR_OUTOFMEMORY;
4614     }
4615
4616     hr = d3d_vertex_buffer_init(object, ddraw_from_d3d7(iface), desc);
4617     if (FAILED(hr))
4618     {
4619         WARN("Failed to initialize vertex buffer, hr %#x.\n", hr);
4620         HeapFree(GetProcessHeap(), 0, object);
4621         return hr;
4622     }
4623
4624     TRACE("Created vertex buffer %p.\n", object);
4625     *vertex_buffer = (IDirect3DVertexBuffer7 *)object;
4626
4627     return D3D_OK;
4628 }
4629
4630 static HRESULT WINAPI d3d3_CreateVertexBuffer(IDirect3D3 *iface, D3DVERTEXBUFFERDESC *desc,
4631         IDirect3DVertexBuffer **vertex_buffer, DWORD flags, IUnknown *outer_unknown)
4632 {
4633     IDirectDrawImpl *This = ddraw_from_d3d3(iface);
4634     HRESULT hr;
4635
4636     TRACE("iface %p, desc %p, vertex_buffer %p, flags %#x, outer_unknown %p.\n",
4637             iface, desc, vertex_buffer, flags, outer_unknown);
4638
4639     if (outer_unknown) return CLASS_E_NOAGGREGATION;
4640
4641     hr = d3d7_CreateVertexBuffer((IDirect3D7 *)&This->IDirect3D7_vtbl,
4642             desc, (IDirect3DVertexBuffer7 **)vertex_buffer, flags);
4643     if (*vertex_buffer)
4644         *vertex_buffer = (IDirect3DVertexBuffer *)&((IDirect3DVertexBufferImpl *)*vertex_buffer)->IDirect3DVertexBuffer_vtbl;
4645
4646     return hr;
4647 }
4648
4649 /*****************************************************************************
4650  * IDirect3D7::EnumZBufferFormats
4651  *
4652  * Enumerates all supported Z buffer pixel formats
4653  *
4654  * Version 3 and 7
4655  *
4656  * Params:
4657  *  device_iid:
4658  *  callback: callback to call for each pixel format
4659  *  context: Pointer to pass back to the callback
4660  *
4661  * Returns:
4662  *  D3D_OK on success
4663  *  DDERR_INVALIDPARAMS if callback is NULL
4664  *  For details, see IWineD3DDevice::EnumZBufferFormats
4665  *
4666  *****************************************************************************/
4667 static HRESULT WINAPI d3d7_EnumZBufferFormats(IDirect3D7 *iface, REFCLSID device_iid,
4668         LPD3DENUMPIXELFORMATSCALLBACK callback, void *context)
4669 {
4670     IDirectDrawImpl *ddraw = ddraw_from_d3d7(iface);
4671     WINED3DDISPLAYMODE d3ddm;
4672     WINED3DDEVTYPE type;
4673     unsigned int i;
4674     HRESULT hr;
4675
4676     /* Order matters. Specifically, BattleZone II (full version) expects the
4677      * 16-bit depth formats to be listed before the 24 and 32 ones. */
4678     static const WINED3DFORMAT formats[] =
4679     {
4680         WINED3DFMT_S1_UINT_D15_UNORM,
4681         WINED3DFMT_D16_UNORM,
4682         WINED3DFMT_X8D24_UNORM,
4683         WINED3DFMT_S4X4_UINT_D24_UNORM,
4684         WINED3DFMT_D24_UNORM_S8_UINT,
4685         WINED3DFMT_D32_UNORM,
4686     };
4687
4688     TRACE("iface %p, device_iid %s, callback %p, context %p.\n",
4689             iface, debugstr_guid(device_iid), callback, context);
4690
4691     if (!callback) return DDERR_INVALIDPARAMS;
4692
4693     if (IsEqualGUID(device_iid, &IID_IDirect3DHALDevice)
4694             || IsEqualGUID(device_iid, &IID_IDirect3DTnLHalDevice)
4695             || IsEqualGUID(device_iid, &IID_D3DDEVICE_WineD3D))
4696     {
4697         TRACE("Asked for HAL device.\n");
4698         type = WINED3DDEVTYPE_HAL;
4699     }
4700     else if (IsEqualGUID(device_iid, &IID_IDirect3DRGBDevice)
4701             || IsEqualGUID(device_iid, &IID_IDirect3DMMXDevice))
4702     {
4703         TRACE("Asked for SW device.\n");
4704         type = WINED3DDEVTYPE_SW;
4705     }
4706     else if (IsEqualGUID(device_iid, &IID_IDirect3DRefDevice))
4707     {
4708         TRACE("Asked for REF device.\n");
4709         type = WINED3DDEVTYPE_REF;
4710     }
4711     else if (IsEqualGUID(device_iid, &IID_IDirect3DNullDevice))
4712     {
4713         TRACE("Asked for NULLREF device.\n");
4714         type = WINED3DDEVTYPE_NULLREF;
4715     }
4716     else
4717     {
4718         FIXME("Unexpected device GUID %s.\n", debugstr_guid(device_iid));
4719         type = WINED3DDEVTYPE_HAL;
4720     }
4721
4722     EnterCriticalSection(&ddraw_cs);
4723     /* We need an adapter format from somewhere to please wined3d and WGL.
4724      * Use the current display mode. So far all cards offer the same depth
4725      * stencil format for all modes, but if some do not and applications do
4726      * not like that we'll have to find some workaround, like iterating over
4727      * all imaginable formats and collecting all the depth stencil formats we
4728      * can get. */
4729     hr = IWineD3DDevice_GetDisplayMode(ddraw->wineD3DDevice, 0, &d3ddm);
4730
4731     for (i = 0; i < (sizeof(formats) / sizeof(*formats)); ++i)
4732     {
4733         hr = IWineD3D_CheckDeviceFormat(ddraw->wineD3D, WINED3DADAPTER_DEFAULT, type, d3ddm.Format,
4734                 WINED3DUSAGE_DEPTHSTENCIL, WINED3DRTYPE_SURFACE, formats[i], SURFACE_OPENGL);
4735         if (SUCCEEDED(hr))
4736         {
4737             DDPIXELFORMAT pformat;
4738
4739             memset(&pformat, 0, sizeof(pformat));
4740             pformat.dwSize = sizeof(pformat);
4741             PixelFormat_WineD3DtoDD(&pformat, formats[i]);
4742
4743             TRACE("Enumerating wined3d format %#x.\n", formats[i]);
4744             hr = callback(&pformat, context);
4745             if (hr != DDENUMRET_OK)
4746             {
4747                 TRACE("Format enumeration cancelled by application.\n");
4748                 LeaveCriticalSection(&ddraw_cs);
4749                 return D3D_OK;
4750             }
4751         }
4752     }
4753     TRACE("End of enumeration.\n");
4754
4755     LeaveCriticalSection(&ddraw_cs);
4756     return D3D_OK;
4757 }
4758
4759 static HRESULT WINAPI d3d3_EnumZBufferFormats(IDirect3D3 *iface, REFCLSID device_iid,
4760         LPD3DENUMPIXELFORMATSCALLBACK callback, void *context)
4761 {
4762     TRACE("iface %p, device_iid %s, callback %p, context %p.\n",
4763             iface, debugstr_guid(device_iid), callback, context);
4764
4765     return d3d7_EnumZBufferFormats((IDirect3D7 *)&ddraw_from_d3d3(iface)->IDirect3D7_vtbl,
4766             device_iid, callback, context);
4767 }
4768
4769 /*****************************************************************************
4770  * IDirect3D7::EvictManagedTextures
4771  *
4772  * Removes all managed textures (=surfaces with DDSCAPS2_TEXTUREMANAGE or
4773  * DDSCAPS2_D3DTEXTUREMANAGE caps) to be removed from video memory.
4774  *
4775  * Version 3 and 7
4776  *
4777  * Returns:
4778  *  D3D_OK, because it's a stub
4779  *
4780  *****************************************************************************/
4781 static HRESULT WINAPI d3d7_EvictManagedTextures(IDirect3D7 *iface)
4782 {
4783     FIXME("iface %p stub!\n", iface);
4784
4785     /* TODO: Just enumerate resources using IWineD3DDevice_EnumResources(),
4786      * then unload surfaces / textures. */
4787
4788     return D3D_OK;
4789 }
4790
4791 static HRESULT WINAPI d3d3_EvictManagedTextures(IDirect3D3 *iface)
4792 {
4793     TRACE("iface %p.\n", iface);
4794
4795     return d3d7_EvictManagedTextures((IDirect3D7 *)&ddraw_from_d3d3(iface)->IDirect3D7_vtbl);
4796 }
4797
4798 /*****************************************************************************
4799  * IDirect3DImpl_GetCaps
4800  *
4801  * This function retrieves the device caps from wined3d
4802  * and converts it into a D3D7 and D3D - D3D3 structure
4803  * This is a helper function called from various places in ddraw
4804  *
4805  * Params:
4806  *  wined3d: The interface to get the caps from
4807  *  desc1: Old D3D <3 structure to fill (needed)
4808  *  desc7: D3D7 device desc structure to fill (needed)
4809  *
4810  * Returns
4811  *  D3D_OK on success, or the return value of IWineD3D::GetCaps
4812  *
4813  *****************************************************************************/
4814 HRESULT IDirect3DImpl_GetCaps(IWineD3D *wined3d, D3DDEVICEDESC *desc1, D3DDEVICEDESC7 *desc7)
4815 {
4816     WINED3DCAPS wined3d_caps;
4817     HRESULT hr;
4818
4819     TRACE("wined3d %p, desc1 %p, desc7 %p.\n", wined3d, desc1, desc7);
4820
4821     memset(&wined3d_caps, 0, sizeof(wined3d_caps));
4822
4823     EnterCriticalSection(&ddraw_cs);
4824     hr = IWineD3D_GetDeviceCaps(wined3d, 0, WINED3DDEVTYPE_HAL, &wined3d_caps);
4825     LeaveCriticalSection(&ddraw_cs);
4826     if (FAILED(hr))
4827     {
4828         WARN("Failed to get device caps, hr %#x.\n", hr);
4829         return hr;
4830     }
4831
4832     /* Copy the results into the d3d7 and d3d3 structures */
4833     desc7->dwDevCaps = wined3d_caps.DevCaps;
4834     desc7->dpcLineCaps.dwMiscCaps = wined3d_caps.PrimitiveMiscCaps;
4835     desc7->dpcLineCaps.dwRasterCaps = wined3d_caps.RasterCaps;
4836     desc7->dpcLineCaps.dwZCmpCaps = wined3d_caps.ZCmpCaps;
4837     desc7->dpcLineCaps.dwSrcBlendCaps = wined3d_caps.SrcBlendCaps;
4838     desc7->dpcLineCaps.dwDestBlendCaps = wined3d_caps.DestBlendCaps;
4839     desc7->dpcLineCaps.dwAlphaCmpCaps = wined3d_caps.AlphaCmpCaps;
4840     desc7->dpcLineCaps.dwShadeCaps = wined3d_caps.ShadeCaps;
4841     desc7->dpcLineCaps.dwTextureCaps = wined3d_caps.TextureCaps;
4842     desc7->dpcLineCaps.dwTextureFilterCaps = wined3d_caps.TextureFilterCaps;
4843     desc7->dpcLineCaps.dwTextureAddressCaps = wined3d_caps.TextureAddressCaps;
4844
4845     desc7->dwMaxTextureWidth = wined3d_caps.MaxTextureWidth;
4846     desc7->dwMaxTextureHeight = wined3d_caps.MaxTextureHeight;
4847
4848     desc7->dwMaxTextureRepeat = wined3d_caps.MaxTextureRepeat;
4849     desc7->dwMaxTextureAspectRatio = wined3d_caps.MaxTextureAspectRatio;
4850     desc7->dwMaxAnisotropy = wined3d_caps.MaxAnisotropy;
4851     desc7->dvMaxVertexW = wined3d_caps.MaxVertexW;
4852
4853     desc7->dvGuardBandLeft = wined3d_caps.GuardBandLeft;
4854     desc7->dvGuardBandTop = wined3d_caps.GuardBandTop;
4855     desc7->dvGuardBandRight = wined3d_caps.GuardBandRight;
4856     desc7->dvGuardBandBottom = wined3d_caps.GuardBandBottom;
4857
4858     desc7->dvExtentsAdjust = wined3d_caps.ExtentsAdjust;
4859     desc7->dwStencilCaps = wined3d_caps.StencilCaps;
4860
4861     desc7->dwFVFCaps = wined3d_caps.FVFCaps;
4862     desc7->dwTextureOpCaps = wined3d_caps.TextureOpCaps;
4863
4864     desc7->dwVertexProcessingCaps = wined3d_caps.VertexProcessingCaps;
4865     desc7->dwMaxActiveLights = wined3d_caps.MaxActiveLights;
4866
4867     /* Remove all non-d3d7 caps */
4868     desc7->dwDevCaps &= (
4869         D3DDEVCAPS_FLOATTLVERTEX         | D3DDEVCAPS_SORTINCREASINGZ          | D3DDEVCAPS_SORTDECREASINGZ          |
4870         D3DDEVCAPS_SORTEXACT             | D3DDEVCAPS_EXECUTESYSTEMMEMORY      | D3DDEVCAPS_EXECUTEVIDEOMEMORY       |
4871         D3DDEVCAPS_TLVERTEXSYSTEMMEMORY  | D3DDEVCAPS_TLVERTEXVIDEOMEMORY      | D3DDEVCAPS_TEXTURESYSTEMMEMORY      |
4872         D3DDEVCAPS_TEXTUREVIDEOMEMORY    | D3DDEVCAPS_DRAWPRIMTLVERTEX         | D3DDEVCAPS_CANRENDERAFTERFLIP       |
4873         D3DDEVCAPS_TEXTURENONLOCALVIDMEM | D3DDEVCAPS_DRAWPRIMITIVES2          | D3DDEVCAPS_SEPARATETEXTUREMEMORIES  |
4874         D3DDEVCAPS_DRAWPRIMITIVES2EX     | D3DDEVCAPS_HWTRANSFORMANDLIGHT      | D3DDEVCAPS_CANBLTSYSTONONLOCAL      |
4875         D3DDEVCAPS_HWRASTERIZATION);
4876
4877     desc7->dwStencilCaps &= (
4878         D3DSTENCILCAPS_KEEP              | D3DSTENCILCAPS_ZERO                 | D3DSTENCILCAPS_REPLACE              |
4879         D3DSTENCILCAPS_INCRSAT           | D3DSTENCILCAPS_DECRSAT              | D3DSTENCILCAPS_INVERT               |
4880         D3DSTENCILCAPS_INCR              | D3DSTENCILCAPS_DECR);
4881
4882     /* FVF caps ?*/
4883
4884     desc7->dwTextureOpCaps &= (
4885         D3DTEXOPCAPS_DISABLE             | D3DTEXOPCAPS_SELECTARG1             | D3DTEXOPCAPS_SELECTARG2             |
4886         D3DTEXOPCAPS_MODULATE            | D3DTEXOPCAPS_MODULATE2X             | D3DTEXOPCAPS_MODULATE4X             |
4887         D3DTEXOPCAPS_ADD                 | D3DTEXOPCAPS_ADDSIGNED              | D3DTEXOPCAPS_ADDSIGNED2X            |
4888         D3DTEXOPCAPS_SUBTRACT            | D3DTEXOPCAPS_ADDSMOOTH              | D3DTEXOPCAPS_BLENDTEXTUREALPHA      |
4889         D3DTEXOPCAPS_BLENDFACTORALPHA    | D3DTEXOPCAPS_BLENDTEXTUREALPHAPM    | D3DTEXOPCAPS_BLENDCURRENTALPHA      |
4890         D3DTEXOPCAPS_PREMODULATE         | D3DTEXOPCAPS_MODULATEALPHA_ADDCOLOR | D3DTEXOPCAPS_MODULATECOLOR_ADDALPHA |
4891         D3DTEXOPCAPS_MODULATEINVALPHA_ADDCOLOR | D3DTEXOPCAPS_MODULATEINVCOLOR_ADDALPHA | D3DTEXOPCAPS_BUMPENVMAP    |
4892         D3DTEXOPCAPS_BUMPENVMAPLUMINANCE | D3DTEXOPCAPS_DOTPRODUCT3);
4893
4894     desc7->dwVertexProcessingCaps &= (
4895         D3DVTXPCAPS_TEXGEN               | D3DVTXPCAPS_MATERIALSOURCE7         | D3DVTXPCAPS_VERTEXFOG               |
4896         D3DVTXPCAPS_DIRECTIONALLIGHTS    | D3DVTXPCAPS_POSITIONALLIGHTS        | D3DVTXPCAPS_LOCALVIEWER);
4897
4898     desc7->dpcLineCaps.dwMiscCaps &= (
4899         D3DPMISCCAPS_MASKPLANES          | D3DPMISCCAPS_MASKZ                  | D3DPMISCCAPS_LINEPATTERNREP         |
4900         D3DPMISCCAPS_CONFORMANT          | D3DPMISCCAPS_CULLNONE               | D3DPMISCCAPS_CULLCW                 |
4901         D3DPMISCCAPS_CULLCCW);
4902
4903     desc7->dpcLineCaps.dwRasterCaps &= (
4904         D3DPRASTERCAPS_DITHER            | D3DPRASTERCAPS_ROP2                 | D3DPRASTERCAPS_XOR                  |
4905         D3DPRASTERCAPS_PAT               | D3DPRASTERCAPS_ZTEST                | D3DPRASTERCAPS_SUBPIXEL             |
4906         D3DPRASTERCAPS_SUBPIXELX         | D3DPRASTERCAPS_FOGVERTEX            | D3DPRASTERCAPS_FOGTABLE             |
4907         D3DPRASTERCAPS_STIPPLE           | D3DPRASTERCAPS_ANTIALIASSORTDEPENDENT | D3DPRASTERCAPS_ANTIALIASSORTINDEPENDENT |
4908         D3DPRASTERCAPS_ANTIALIASEDGES    | D3DPRASTERCAPS_MIPMAPLODBIAS        | D3DPRASTERCAPS_ZBIAS                |
4909         D3DPRASTERCAPS_ZBUFFERLESSHSR    | D3DPRASTERCAPS_FOGRANGE             | D3DPRASTERCAPS_ANISOTROPY           |
4910         D3DPRASTERCAPS_WBUFFER           | D3DPRASTERCAPS_TRANSLUCENTSORTINDEPENDENT | D3DPRASTERCAPS_WFOG           |
4911         D3DPRASTERCAPS_ZFOG);
4912
4913     desc7->dpcLineCaps.dwZCmpCaps &= (
4914         D3DPCMPCAPS_NEVER                | D3DPCMPCAPS_LESS                    | D3DPCMPCAPS_EQUAL                   |
4915         D3DPCMPCAPS_LESSEQUAL            | D3DPCMPCAPS_GREATER                 | D3DPCMPCAPS_NOTEQUAL                |
4916         D3DPCMPCAPS_GREATEREQUAL         | D3DPCMPCAPS_ALWAYS);
4917
4918     desc7->dpcLineCaps.dwSrcBlendCaps &= (
4919         D3DPBLENDCAPS_ZERO               | D3DPBLENDCAPS_ONE                   | D3DPBLENDCAPS_SRCCOLOR              |
4920         D3DPBLENDCAPS_INVSRCCOLOR        | D3DPBLENDCAPS_SRCALPHA              | D3DPBLENDCAPS_INVSRCALPHA           |
4921         D3DPBLENDCAPS_DESTALPHA          | D3DPBLENDCAPS_INVDESTALPHA          | D3DPBLENDCAPS_DESTCOLOR             |
4922         D3DPBLENDCAPS_INVDESTCOLOR       | D3DPBLENDCAPS_SRCALPHASAT           | D3DPBLENDCAPS_BOTHSRCALPHA          |
4923         D3DPBLENDCAPS_BOTHINVSRCALPHA);
4924
4925     desc7->dpcLineCaps.dwDestBlendCaps &= (
4926         D3DPBLENDCAPS_ZERO               | D3DPBLENDCAPS_ONE                   | D3DPBLENDCAPS_SRCCOLOR              |
4927         D3DPBLENDCAPS_INVSRCCOLOR        | D3DPBLENDCAPS_SRCALPHA              | D3DPBLENDCAPS_INVSRCALPHA           |
4928         D3DPBLENDCAPS_DESTALPHA          | D3DPBLENDCAPS_INVDESTALPHA          | D3DPBLENDCAPS_DESTCOLOR             |
4929         D3DPBLENDCAPS_INVDESTCOLOR       | D3DPBLENDCAPS_SRCALPHASAT           | D3DPBLENDCAPS_BOTHSRCALPHA          |
4930         D3DPBLENDCAPS_BOTHINVSRCALPHA);
4931
4932     desc7->dpcLineCaps.dwAlphaCmpCaps &= (
4933         D3DPCMPCAPS_NEVER                | D3DPCMPCAPS_LESS                    | D3DPCMPCAPS_EQUAL                   |
4934         D3DPCMPCAPS_LESSEQUAL            | D3DPCMPCAPS_GREATER                 | D3DPCMPCAPS_NOTEQUAL                |
4935         D3DPCMPCAPS_GREATEREQUAL         | D3DPCMPCAPS_ALWAYS);
4936
4937     desc7->dpcLineCaps.dwShadeCaps &= (
4938         D3DPSHADECAPS_COLORFLATMONO      | D3DPSHADECAPS_COLORFLATRGB          | D3DPSHADECAPS_COLORGOURAUDMONO      |
4939         D3DPSHADECAPS_COLORGOURAUDRGB    | D3DPSHADECAPS_COLORPHONGMONO        | D3DPSHADECAPS_COLORPHONGRGB         |
4940         D3DPSHADECAPS_SPECULARFLATMONO   | D3DPSHADECAPS_SPECULARFLATRGB       | D3DPSHADECAPS_SPECULARGOURAUDMONO   |
4941         D3DPSHADECAPS_SPECULARGOURAUDRGB | D3DPSHADECAPS_SPECULARPHONGMONO     | D3DPSHADECAPS_SPECULARPHONGRGB      |
4942         D3DPSHADECAPS_ALPHAFLATBLEND     | D3DPSHADECAPS_ALPHAFLATSTIPPLED     | D3DPSHADECAPS_ALPHAGOURAUDBLEND     |
4943         D3DPSHADECAPS_ALPHAGOURAUDSTIPPLED | D3DPSHADECAPS_ALPHAPHONGBLEND     | D3DPSHADECAPS_ALPHAPHONGSTIPPLED    |
4944         D3DPSHADECAPS_FOGFLAT            | D3DPSHADECAPS_FOGGOURAUD            | D3DPSHADECAPS_FOGPHONG);
4945
4946     desc7->dpcLineCaps.dwTextureCaps &= (
4947         D3DPTEXTURECAPS_PERSPECTIVE      | D3DPTEXTURECAPS_POW2                | D3DPTEXTURECAPS_ALPHA               |
4948         D3DPTEXTURECAPS_TRANSPARENCY     | D3DPTEXTURECAPS_BORDER              | D3DPTEXTURECAPS_SQUAREONLY          |
4949         D3DPTEXTURECAPS_TEXREPEATNOTSCALEDBYSIZE | D3DPTEXTURECAPS_ALPHAPALETTE| D3DPTEXTURECAPS_NONPOW2CONDITIONAL  |
4950         D3DPTEXTURECAPS_PROJECTED        | D3DPTEXTURECAPS_CUBEMAP             | D3DPTEXTURECAPS_COLORKEYBLEND);
4951
4952     desc7->dpcLineCaps.dwTextureFilterCaps &= (
4953         D3DPTFILTERCAPS_NEAREST          | D3DPTFILTERCAPS_LINEAR              | D3DPTFILTERCAPS_MIPNEAREST          |
4954         D3DPTFILTERCAPS_MIPLINEAR        | D3DPTFILTERCAPS_LINEARMIPNEAREST    | D3DPTFILTERCAPS_LINEARMIPLINEAR     |
4955         D3DPTFILTERCAPS_MINFPOINT        | D3DPTFILTERCAPS_MINFLINEAR          | D3DPTFILTERCAPS_MINFANISOTROPIC     |
4956         D3DPTFILTERCAPS_MIPFPOINT        | D3DPTFILTERCAPS_MIPFLINEAR          | D3DPTFILTERCAPS_MAGFPOINT           |
4957         D3DPTFILTERCAPS_MAGFLINEAR       | D3DPTFILTERCAPS_MAGFANISOTROPIC     | D3DPTFILTERCAPS_MAGFAFLATCUBIC      |
4958         D3DPTFILTERCAPS_MAGFGAUSSIANCUBIC);
4959
4960     desc7->dpcLineCaps.dwTextureBlendCaps &= (
4961         D3DPTBLENDCAPS_DECAL             | D3DPTBLENDCAPS_MODULATE             | D3DPTBLENDCAPS_DECALALPHA           |
4962         D3DPTBLENDCAPS_MODULATEALPHA     | D3DPTBLENDCAPS_DECALMASK            | D3DPTBLENDCAPS_MODULATEMASK         |
4963         D3DPTBLENDCAPS_COPY              | D3DPTBLENDCAPS_ADD);
4964
4965     desc7->dpcLineCaps.dwTextureAddressCaps &= (
4966         D3DPTADDRESSCAPS_WRAP            | D3DPTADDRESSCAPS_MIRROR             | D3DPTADDRESSCAPS_CLAMP              |
4967         D3DPTADDRESSCAPS_BORDER          | D3DPTADDRESSCAPS_INDEPENDENTUV);
4968
4969     if (!(desc7->dpcLineCaps.dwTextureCaps & D3DPTEXTURECAPS_POW2))
4970     {
4971         /* DirectX7 always has the np2 flag set, no matter what the card
4972          * supports. Some old games (Rollcage) check the caps incorrectly.
4973          * If wined3d supports nonpow2 textures it also has np2 conditional
4974          * support. */
4975         desc7->dpcLineCaps.dwTextureCaps |= D3DPTEXTURECAPS_POW2 | D3DPTEXTURECAPS_NONPOW2CONDITIONAL;
4976     }
4977
4978     /* Fill the missing members, and do some fixup */
4979     desc7->dpcLineCaps.dwSize = sizeof(desc7->dpcLineCaps);
4980     desc7->dpcLineCaps.dwTextureBlendCaps = D3DPTBLENDCAPS_ADD | D3DPTBLENDCAPS_MODULATEMASK |
4981                                             D3DPTBLENDCAPS_COPY | D3DPTBLENDCAPS_DECAL |
4982                                             D3DPTBLENDCAPS_DECALALPHA | D3DPTBLENDCAPS_DECALMASK |
4983                                             D3DPTBLENDCAPS_MODULATE | D3DPTBLENDCAPS_MODULATEALPHA;
4984     desc7->dpcLineCaps.dwStippleWidth = 32;
4985     desc7->dpcLineCaps.dwStippleHeight = 32;
4986     /* Use the same for the TriCaps */
4987     desc7->dpcTriCaps = desc7->dpcLineCaps;
4988
4989     desc7->dwDeviceRenderBitDepth = DDBD_16 | DDBD_24 | DDBD_32;
4990     desc7->dwDeviceZBufferBitDepth = DDBD_16 | DDBD_24;
4991     desc7->dwMinTextureWidth = 1;
4992     desc7->dwMinTextureHeight = 1;
4993
4994     /* Convert DWORDs safely to WORDs */
4995     if (wined3d_caps.MaxTextureBlendStages > 0xffff) desc7->wMaxTextureBlendStages = 0xffff;
4996     else desc7->wMaxTextureBlendStages = (WORD)wined3d_caps.MaxTextureBlendStages;
4997     if (wined3d_caps.MaxSimultaneousTextures > 0xffff) desc7->wMaxSimultaneousTextures = 0xffff;
4998     else desc7->wMaxSimultaneousTextures = (WORD)wined3d_caps.MaxSimultaneousTextures;
4999
5000     if (wined3d_caps.MaxUserClipPlanes > 0xffff) desc7->wMaxUserClipPlanes = 0xffff;
5001     else desc7->wMaxUserClipPlanes = (WORD)wined3d_caps.MaxUserClipPlanes;
5002     if (wined3d_caps.MaxVertexBlendMatrices > 0xffff) desc7->wMaxVertexBlendMatrices = 0xffff;
5003     else desc7->wMaxVertexBlendMatrices = (WORD)wined3d_caps.MaxVertexBlendMatrices;
5004
5005     desc7->deviceGUID = IID_IDirect3DTnLHalDevice;
5006
5007     desc7->dwReserved1 = 0;
5008     desc7->dwReserved2 = 0;
5009     desc7->dwReserved3 = 0;
5010     desc7->dwReserved4 = 0;
5011
5012     /* Fill the old structure */
5013     memset(desc1, 0, sizeof(desc1));
5014     desc1->dwSize = sizeof(D3DDEVICEDESC);
5015     desc1->dwFlags = D3DDD_COLORMODEL
5016             | D3DDD_DEVCAPS
5017             | D3DDD_TRANSFORMCAPS
5018             | D3DDD_BCLIPPING
5019             | D3DDD_LIGHTINGCAPS
5020             | D3DDD_LINECAPS
5021             | D3DDD_TRICAPS
5022             | D3DDD_DEVICERENDERBITDEPTH
5023             | D3DDD_DEVICEZBUFFERBITDEPTH
5024             | D3DDD_MAXBUFFERSIZE
5025             | D3DDD_MAXVERTEXCOUNT;
5026
5027     desc1->dcmColorModel = D3DCOLOR_RGB;
5028     desc1->dwDevCaps = desc7->dwDevCaps;
5029     desc1->dtcTransformCaps.dwSize = sizeof(D3DTRANSFORMCAPS);
5030     desc1->dtcTransformCaps.dwCaps = D3DTRANSFORMCAPS_CLIP;
5031     desc1->bClipping = TRUE;
5032     desc1->dlcLightingCaps.dwSize = sizeof(D3DLIGHTINGCAPS);
5033     desc1->dlcLightingCaps.dwCaps = D3DLIGHTCAPS_DIRECTIONAL
5034             | D3DLIGHTCAPS_PARALLELPOINT
5035             | D3DLIGHTCAPS_POINT
5036             | D3DLIGHTCAPS_SPOT;
5037
5038     desc1->dlcLightingCaps.dwLightingModel = D3DLIGHTINGMODEL_RGB;
5039     desc1->dlcLightingCaps.dwNumLights = desc7->dwMaxActiveLights;
5040
5041     desc1->dpcLineCaps.dwSize = sizeof(D3DPRIMCAPS);
5042     desc1->dpcLineCaps.dwMiscCaps = desc7->dpcLineCaps.dwMiscCaps;
5043     desc1->dpcLineCaps.dwRasterCaps = desc7->dpcLineCaps.dwRasterCaps;
5044     desc1->dpcLineCaps.dwZCmpCaps = desc7->dpcLineCaps.dwZCmpCaps;
5045     desc1->dpcLineCaps.dwSrcBlendCaps = desc7->dpcLineCaps.dwSrcBlendCaps;
5046     desc1->dpcLineCaps.dwDestBlendCaps = desc7->dpcLineCaps.dwDestBlendCaps;
5047     desc1->dpcLineCaps.dwShadeCaps = desc7->dpcLineCaps.dwShadeCaps;
5048     desc1->dpcLineCaps.dwTextureCaps = desc7->dpcLineCaps.dwTextureCaps;
5049     desc1->dpcLineCaps.dwTextureFilterCaps = desc7->dpcLineCaps.dwTextureFilterCaps;
5050     desc1->dpcLineCaps.dwTextureBlendCaps = desc7->dpcLineCaps.dwTextureBlendCaps;
5051     desc1->dpcLineCaps.dwTextureAddressCaps = desc7->dpcLineCaps.dwTextureAddressCaps;
5052     desc1->dpcLineCaps.dwStippleWidth = desc7->dpcLineCaps.dwStippleWidth;
5053     desc1->dpcLineCaps.dwAlphaCmpCaps = desc7->dpcLineCaps.dwAlphaCmpCaps;
5054
5055     desc1->dpcTriCaps.dwSize = sizeof(D3DPRIMCAPS);
5056     desc1->dpcTriCaps.dwMiscCaps = desc7->dpcTriCaps.dwMiscCaps;
5057     desc1->dpcTriCaps.dwRasterCaps = desc7->dpcTriCaps.dwRasterCaps;
5058     desc1->dpcTriCaps.dwZCmpCaps = desc7->dpcTriCaps.dwZCmpCaps;
5059     desc1->dpcTriCaps.dwSrcBlendCaps = desc7->dpcTriCaps.dwSrcBlendCaps;
5060     desc1->dpcTriCaps.dwDestBlendCaps = desc7->dpcTriCaps.dwDestBlendCaps;
5061     desc1->dpcTriCaps.dwShadeCaps = desc7->dpcTriCaps.dwShadeCaps;
5062     desc1->dpcTriCaps.dwTextureCaps = desc7->dpcTriCaps.dwTextureCaps;
5063     desc1->dpcTriCaps.dwTextureFilterCaps = desc7->dpcTriCaps.dwTextureFilterCaps;
5064     desc1->dpcTriCaps.dwTextureBlendCaps = desc7->dpcTriCaps.dwTextureBlendCaps;
5065     desc1->dpcTriCaps.dwTextureAddressCaps = desc7->dpcTriCaps.dwTextureAddressCaps;
5066     desc1->dpcTriCaps.dwStippleWidth = desc7->dpcTriCaps.dwStippleWidth;
5067     desc1->dpcTriCaps.dwAlphaCmpCaps = desc7->dpcTriCaps.dwAlphaCmpCaps;
5068
5069     desc1->dwDeviceRenderBitDepth = desc7->dwDeviceRenderBitDepth;
5070     desc1->dwDeviceZBufferBitDepth = desc7->dwDeviceZBufferBitDepth;
5071     desc1->dwMaxBufferSize = 0;
5072     desc1->dwMaxVertexCount = 65536;
5073     desc1->dwMinTextureWidth  = desc7->dwMinTextureWidth;
5074     desc1->dwMinTextureHeight = desc7->dwMinTextureHeight;
5075     desc1->dwMaxTextureWidth  = desc7->dwMaxTextureWidth;
5076     desc1->dwMaxTextureHeight = desc7->dwMaxTextureHeight;
5077     desc1->dwMinStippleWidth  = 1;
5078     desc1->dwMinStippleHeight = 1;
5079     desc1->dwMaxStippleWidth  = 32;
5080     desc1->dwMaxStippleHeight = 32;
5081     desc1->dwMaxTextureRepeat = desc7->dwMaxTextureRepeat;
5082     desc1->dwMaxTextureAspectRatio = desc7->dwMaxTextureAspectRatio;
5083     desc1->dwMaxAnisotropy = desc7->dwMaxAnisotropy;
5084     desc1->dvGuardBandLeft = desc7->dvGuardBandLeft;
5085     desc1->dvGuardBandRight = desc7->dvGuardBandRight;
5086     desc1->dvGuardBandTop = desc7->dvGuardBandTop;
5087     desc1->dvGuardBandBottom = desc7->dvGuardBandBottom;
5088     desc1->dvExtentsAdjust = desc7->dvExtentsAdjust;
5089     desc1->dwStencilCaps = desc7->dwStencilCaps;
5090     desc1->dwFVFCaps = desc7->dwFVFCaps;
5091     desc1->dwTextureOpCaps = desc7->dwTextureOpCaps;
5092     desc1->wMaxTextureBlendStages = desc7->wMaxTextureBlendStages;
5093     desc1->wMaxSimultaneousTextures = desc7->wMaxSimultaneousTextures;
5094
5095     return DD_OK;
5096 }
5097
5098 /*****************************************************************************
5099  * IDirectDraw7 VTable
5100  *****************************************************************************/
5101 static const struct IDirectDraw7Vtbl ddraw7_vtbl =
5102 {
5103     /* IUnknown */
5104     ddraw7_QueryInterface,
5105     ddraw7_AddRef,
5106     ddraw7_Release,
5107     /* IDirectDraw */
5108     ddraw7_Compact,
5109     ddraw7_CreateClipper,
5110     ddraw7_CreatePalette,
5111     ddraw7_CreateSurface,
5112     ddraw7_DuplicateSurface,
5113     ddraw7_EnumDisplayModes,
5114     ddraw7_EnumSurfaces,
5115     ddraw7_FlipToGDISurface,
5116     ddraw7_GetCaps,
5117     ddraw7_GetDisplayMode,
5118     ddraw7_GetFourCCCodes,
5119     ddraw7_GetGDISurface,
5120     ddraw7_GetMonitorFrequency,
5121     ddraw7_GetScanLine,
5122     ddraw7_GetVerticalBlankStatus,
5123     ddraw7_Initialize,
5124     ddraw7_RestoreDisplayMode,
5125     ddraw7_SetCooperativeLevel,
5126     ddraw7_SetDisplayMode,
5127     ddraw7_WaitForVerticalBlank,
5128     /* IDirectDraw2 */
5129     ddraw7_GetAvailableVidMem,
5130     /* IDirectDraw3 */
5131     ddraw7_GetSurfaceFromDC,
5132     /* IDirectDraw4 */
5133     ddraw7_RestoreAllSurfaces,
5134     ddraw7_TestCooperativeLevel,
5135     ddraw7_GetDeviceIdentifier,
5136     /* IDirectDraw7 */
5137     ddraw7_StartModeTest,
5138     ddraw7_EvaluateMode
5139 };
5140
5141 static const struct IDirectDraw4Vtbl ddraw4_vtbl =
5142 {
5143     /* IUnknown */
5144     ddraw4_QueryInterface,
5145     ddraw4_AddRef,
5146     ddraw4_Release,
5147     /* IDirectDraw */
5148     ddraw4_Compact,
5149     ddraw4_CreateClipper,
5150     ddraw4_CreatePalette,
5151     ddraw4_CreateSurface,
5152     ddraw4_DuplicateSurface,
5153     ddraw4_EnumDisplayModes,
5154     ddraw4_EnumSurfaces,
5155     ddraw4_FlipToGDISurface,
5156     ddraw4_GetCaps,
5157     ddraw4_GetDisplayMode,
5158     ddraw4_GetFourCCCodes,
5159     ddraw4_GetGDISurface,
5160     ddraw4_GetMonitorFrequency,
5161     ddraw4_GetScanLine,
5162     ddraw4_GetVerticalBlankStatus,
5163     ddraw4_Initialize,
5164     ddraw4_RestoreDisplayMode,
5165     ddraw4_SetCooperativeLevel,
5166     ddraw4_SetDisplayMode,
5167     ddraw4_WaitForVerticalBlank,
5168     /* IDirectDraw2 */
5169     ddraw4_GetAvailableVidMem,
5170     /* IDirectDraw3 */
5171     ddraw4_GetSurfaceFromDC,
5172     /* IDirectDraw4 */
5173     ddraw4_RestoreAllSurfaces,
5174     ddraw4_TestCooperativeLevel,
5175     ddraw4_GetDeviceIdentifier,
5176 };
5177
5178 static const struct IDirectDraw3Vtbl ddraw3_vtbl =
5179 {
5180     /* IUnknown */
5181     ddraw3_QueryInterface,
5182     ddraw3_AddRef,
5183     ddraw3_Release,
5184     /* IDirectDraw */
5185     ddraw3_Compact,
5186     ddraw3_CreateClipper,
5187     ddraw3_CreatePalette,
5188     ddraw3_CreateSurface,
5189     ddraw3_DuplicateSurface,
5190     ddraw3_EnumDisplayModes,
5191     ddraw3_EnumSurfaces,
5192     ddraw3_FlipToGDISurface,
5193     ddraw3_GetCaps,
5194     ddraw3_GetDisplayMode,
5195     ddraw3_GetFourCCCodes,
5196     ddraw3_GetGDISurface,
5197     ddraw3_GetMonitorFrequency,
5198     ddraw3_GetScanLine,
5199     ddraw3_GetVerticalBlankStatus,
5200     ddraw3_Initialize,
5201     ddraw3_RestoreDisplayMode,
5202     ddraw3_SetCooperativeLevel,
5203     ddraw3_SetDisplayMode,
5204     ddraw3_WaitForVerticalBlank,
5205     /* IDirectDraw2 */
5206     ddraw3_GetAvailableVidMem,
5207     /* IDirectDraw3 */
5208     ddraw3_GetSurfaceFromDC,
5209 };
5210
5211 static const struct IDirectDraw2Vtbl ddraw2_vtbl =
5212 {
5213     /* IUnknown */
5214     ddraw2_QueryInterface,
5215     ddraw2_AddRef,
5216     ddraw2_Release,
5217     /* IDirectDraw */
5218     ddraw2_Compact,
5219     ddraw2_CreateClipper,
5220     ddraw2_CreatePalette,
5221     ddraw2_CreateSurface,
5222     ddraw2_DuplicateSurface,
5223     ddraw2_EnumDisplayModes,
5224     ddraw2_EnumSurfaces,
5225     ddraw2_FlipToGDISurface,
5226     ddraw2_GetCaps,
5227     ddraw2_GetDisplayMode,
5228     ddraw2_GetFourCCCodes,
5229     ddraw2_GetGDISurface,
5230     ddraw2_GetMonitorFrequency,
5231     ddraw2_GetScanLine,
5232     ddraw2_GetVerticalBlankStatus,
5233     ddraw2_Initialize,
5234     ddraw2_RestoreDisplayMode,
5235     ddraw2_SetCooperativeLevel,
5236     ddraw2_SetDisplayMode,
5237     ddraw2_WaitForVerticalBlank,
5238     /* IDirectDraw2 */
5239     ddraw2_GetAvailableVidMem,
5240 };
5241
5242 static const struct IDirectDrawVtbl ddraw1_vtbl =
5243 {
5244     /* IUnknown */
5245     ddraw1_QueryInterface,
5246     ddraw1_AddRef,
5247     ddraw1_Release,
5248     /* IDirectDraw */
5249     ddraw1_Compact,
5250     ddraw1_CreateClipper,
5251     ddraw1_CreatePalette,
5252     ddraw1_CreateSurface,
5253     ddraw1_DuplicateSurface,
5254     ddraw1_EnumDisplayModes,
5255     ddraw1_EnumSurfaces,
5256     ddraw1_FlipToGDISurface,
5257     ddraw1_GetCaps,
5258     ddraw1_GetDisplayMode,
5259     ddraw1_GetFourCCCodes,
5260     ddraw1_GetGDISurface,
5261     ddraw1_GetMonitorFrequency,
5262     ddraw1_GetScanLine,
5263     ddraw1_GetVerticalBlankStatus,
5264     ddraw1_Initialize,
5265     ddraw1_RestoreDisplayMode,
5266     ddraw1_SetCooperativeLevel,
5267     ddraw1_SetDisplayMode,
5268     ddraw1_WaitForVerticalBlank,
5269 };
5270
5271 static const struct IDirect3D7Vtbl d3d7_vtbl =
5272 {
5273     /* IUnknown methods */
5274     d3d7_QueryInterface,
5275     d3d7_AddRef,
5276     d3d7_Release,
5277     /* IDirect3D7 methods */
5278     d3d7_EnumDevices,
5279     d3d7_CreateDevice,
5280     d3d7_CreateVertexBuffer,
5281     d3d7_EnumZBufferFormats,
5282     d3d7_EvictManagedTextures
5283 };
5284
5285 static const struct IDirect3D3Vtbl d3d3_vtbl =
5286 {
5287     /* IUnknown methods */
5288     d3d3_QueryInterface,
5289     d3d3_AddRef,
5290     d3d3_Release,
5291     /* IDirect3D3 methods */
5292     d3d3_EnumDevices,
5293     d3d3_CreateLight,
5294     d3d3_CreateMaterial,
5295     d3d3_CreateViewport,
5296     d3d3_FindDevice,
5297     d3d3_CreateDevice,
5298     d3d3_CreateVertexBuffer,
5299     d3d3_EnumZBufferFormats,
5300     d3d3_EvictManagedTextures
5301 };
5302
5303 static const struct IDirect3D2Vtbl d3d2_vtbl =
5304 {
5305     /* IUnknown methods */
5306     d3d2_QueryInterface,
5307     d3d2_AddRef,
5308     d3d2_Release,
5309     /* IDirect3D2 methods */
5310     d3d2_EnumDevices,
5311     d3d2_CreateLight,
5312     d3d2_CreateMaterial,
5313     d3d2_CreateViewport,
5314     d3d2_FindDevice,
5315     d3d2_CreateDevice
5316 };
5317
5318 static const struct IDirect3DVtbl d3d1_vtbl =
5319 {
5320     /* IUnknown methods */
5321     d3d1_QueryInterface,
5322     d3d1_AddRef,
5323     d3d1_Release,
5324     /* IDirect3D methods */
5325     d3d1_Initialize,
5326     d3d1_EnumDevices,
5327     d3d1_CreateLight,
5328     d3d1_CreateMaterial,
5329     d3d1_CreateViewport,
5330     d3d1_FindDevice
5331 };
5332
5333 /*****************************************************************************
5334  * ddraw_find_decl
5335  *
5336  * Finds the WineD3D vertex declaration for a specific fvf, and creates one
5337  * if none was found.
5338  *
5339  * This function is in ddraw.c and the DDraw object space because D3D7
5340  * vertex buffers are created using the IDirect3D interface to the ddraw
5341  * object, so they can be valid across D3D devices(theoretically. The ddraw
5342  * object also owns the wined3d device
5343  *
5344  * Parameters:
5345  *  This: Device
5346  *  fvf: Fvf to find the decl for
5347  *
5348  * Returns:
5349  *  NULL in case of an error, the IWineD3DVertexDeclaration interface for the
5350  *  fvf otherwise.
5351  *
5352  *****************************************************************************/
5353 IWineD3DVertexDeclaration *ddraw_find_decl(IDirectDrawImpl *This, DWORD fvf)
5354 {
5355     HRESULT hr;
5356     IWineD3DVertexDeclaration* pDecl = NULL;
5357     int p, low, high; /* deliberately signed */
5358     struct FvfToDecl *convertedDecls = This->decls;
5359
5360     TRACE("Searching for declaration for fvf %08x... ", fvf);
5361
5362     low = 0;
5363     high = This->numConvertedDecls - 1;
5364     while(low <= high) {
5365         p = (low + high) >> 1;
5366         TRACE("%d ", p);
5367         if(convertedDecls[p].fvf == fvf) {
5368             TRACE("found %p\n", convertedDecls[p].decl);
5369             return convertedDecls[p].decl;
5370         } else if(convertedDecls[p].fvf < fvf) {
5371             low = p + 1;
5372         } else {
5373             high = p - 1;
5374         }
5375     }
5376     TRACE("not found. Creating and inserting at position %d.\n", low);
5377
5378     hr = IWineD3DDevice_CreateVertexDeclarationFromFVF(This->wineD3DDevice, &pDecl,
5379             (IUnknown *)This, &ddraw_null_wined3d_parent_ops, fvf);
5380     if (hr != S_OK) return NULL;
5381
5382     if(This->declArraySize == This->numConvertedDecls) {
5383         int grow = max(This->declArraySize / 2, 8);
5384         convertedDecls = HeapReAlloc(GetProcessHeap(), 0, convertedDecls,
5385                                      sizeof(convertedDecls[0]) * (This->numConvertedDecls + grow));
5386         if(!convertedDecls) {
5387             /* This will destroy it */
5388             IWineD3DVertexDeclaration_Release(pDecl);
5389             return NULL;
5390         }
5391         This->decls = convertedDecls;
5392         This->declArraySize += grow;
5393     }
5394
5395     memmove(convertedDecls + low + 1, convertedDecls + low, sizeof(convertedDecls[0]) * (This->numConvertedDecls - low));
5396     convertedDecls[low].decl = pDecl;
5397     convertedDecls[low].fvf = fvf;
5398     This->numConvertedDecls++;
5399
5400     TRACE("Returning %p. %d decls in array\n", pDecl, This->numConvertedDecls);
5401     return pDecl;
5402 }
5403
5404 /* IWineD3DDeviceParent IUnknown methods */
5405
5406 static inline struct IDirectDrawImpl *ddraw_from_device_parent(IWineD3DDeviceParent *iface)
5407 {
5408     return (struct IDirectDrawImpl *)((char*)iface - FIELD_OFFSET(struct IDirectDrawImpl, device_parent_vtbl));
5409 }
5410
5411 static HRESULT STDMETHODCALLTYPE device_parent_QueryInterface(IWineD3DDeviceParent *iface, REFIID riid, void **object)
5412 {
5413     struct IDirectDrawImpl *This = ddraw_from_device_parent(iface);
5414     return ddraw7_QueryInterface((IDirectDraw7 *)This, riid, object);
5415 }
5416
5417 static ULONG STDMETHODCALLTYPE device_parent_AddRef(IWineD3DDeviceParent *iface)
5418 {
5419     struct IDirectDrawImpl *This = ddraw_from_device_parent(iface);
5420     return ddraw7_AddRef((IDirectDraw7 *)This);
5421 }
5422
5423 static ULONG STDMETHODCALLTYPE device_parent_Release(IWineD3DDeviceParent *iface)
5424 {
5425     struct IDirectDrawImpl *This = ddraw_from_device_parent(iface);
5426     return ddraw7_Release((IDirectDraw7 *)This);
5427 }
5428
5429 /* IWineD3DDeviceParent methods */
5430
5431 static void STDMETHODCALLTYPE device_parent_WineD3DDeviceCreated(IWineD3DDeviceParent *iface, IWineD3DDevice *device)
5432 {
5433     TRACE("iface %p, device %p\n", iface, device);
5434 }
5435
5436 static HRESULT STDMETHODCALLTYPE device_parent_CreateSurface(IWineD3DDeviceParent *iface,
5437         IUnknown *superior, UINT width, UINT height, WINED3DFORMAT format, DWORD usage,
5438         WINED3DPOOL pool, UINT level, WINED3DCUBEMAP_FACES face, IWineD3DSurface **surface)
5439 {
5440     struct IDirectDrawImpl *This = ddraw_from_device_parent(iface);
5441     IDirectDrawSurfaceImpl *surf = NULL;
5442     UINT i = 0;
5443     DDSCAPS2 searchcaps = This->tex_root->surface_desc.ddsCaps;
5444
5445     TRACE("iface %p, superior %p, width %u, height %u, format %#x, usage %#x,\n"
5446             "\tpool %#x, level %u, face %u, surface %p\n",
5447             iface, superior, width, height, format, usage, pool, level, face, surface);
5448
5449     searchcaps.dwCaps2 &= ~DDSCAPS2_CUBEMAP_ALLFACES;
5450     switch(face)
5451     {
5452         case WINED3DCUBEMAP_FACE_POSITIVE_X:
5453             TRACE("Asked for positive x\n");
5454             if (searchcaps.dwCaps2 & DDSCAPS2_CUBEMAP)
5455             {
5456                 searchcaps.dwCaps2 |= DDSCAPS2_CUBEMAP_POSITIVEX;
5457             }
5458             surf = This->tex_root; break;
5459         case WINED3DCUBEMAP_FACE_NEGATIVE_X:
5460             TRACE("Asked for negative x\n");
5461             searchcaps.dwCaps2 |= DDSCAPS2_CUBEMAP_NEGATIVEX; break;
5462         case WINED3DCUBEMAP_FACE_POSITIVE_Y:
5463             TRACE("Asked for positive y\n");
5464             searchcaps.dwCaps2 |= DDSCAPS2_CUBEMAP_POSITIVEY; break;
5465         case WINED3DCUBEMAP_FACE_NEGATIVE_Y:
5466             TRACE("Asked for negative y\n");
5467             searchcaps.dwCaps2 |= DDSCAPS2_CUBEMAP_NEGATIVEY; break;
5468         case WINED3DCUBEMAP_FACE_POSITIVE_Z:
5469             TRACE("Asked for positive z\n");
5470             searchcaps.dwCaps2 |= DDSCAPS2_CUBEMAP_POSITIVEZ; break;
5471         case WINED3DCUBEMAP_FACE_NEGATIVE_Z:
5472             TRACE("Asked for negative z\n");
5473             searchcaps.dwCaps2 |= DDSCAPS2_CUBEMAP_NEGATIVEZ; break;
5474         default: {ERR("Unexpected cube face\n");} /* Stupid compiler */
5475     }
5476
5477     if (!surf)
5478     {
5479         IDirectDrawSurface7 *attached;
5480         IDirectDrawSurface7_GetAttachedSurface((IDirectDrawSurface7 *)This->tex_root, &searchcaps, &attached);
5481         surf = (IDirectDrawSurfaceImpl *)attached;
5482         IDirectDrawSurface7_Release(attached);
5483     }
5484     if (!surf) ERR("root search surface not found\n");
5485
5486     /* Find the wanted mipmap. There are enough mipmaps in the chain */
5487     while (i < level)
5488     {
5489         IDirectDrawSurface7 *attached;
5490         IDirectDrawSurface7_GetAttachedSurface((IDirectDrawSurface7 *)surf, &searchcaps, &attached);
5491         if(!attached) ERR("Surface not found\n");
5492         surf = (IDirectDrawSurfaceImpl *)attached;
5493         IDirectDrawSurface7_Release(attached);
5494         ++i;
5495     }
5496
5497     /* Return the surface */
5498     *surface = surf->WineD3DSurface;
5499     IWineD3DSurface_AddRef(*surface);
5500
5501     TRACE("Returning wineD3DSurface %p, it belongs to surface %p\n", *surface, surf);
5502
5503     return D3D_OK;
5504 }
5505
5506 static HRESULT WINAPI findRenderTarget(IDirectDrawSurface7 *surface, DDSURFACEDESC2 *surface_desc, void *ctx)
5507 {
5508     IDirectDrawSurfaceImpl *s = (IDirectDrawSurfaceImpl *)surface;
5509     IDirectDrawSurfaceImpl **target = ctx;
5510
5511     if (!s->isRenderTarget)
5512     {
5513         *target = s;
5514         IDirectDrawSurface7_Release(surface);
5515         return DDENUMRET_CANCEL;
5516     }
5517
5518     /* Recurse into the surface tree */
5519     IDirectDrawSurface7_EnumAttachedSurfaces(surface, ctx, findRenderTarget);
5520
5521     IDirectDrawSurface7_Release(surface);
5522     if (*target) return DDENUMRET_CANCEL;
5523
5524     return DDENUMRET_OK;
5525 }
5526
5527 static HRESULT STDMETHODCALLTYPE device_parent_CreateRenderTarget(IWineD3DDeviceParent *iface,
5528         IUnknown *superior, UINT width, UINT height, WINED3DFORMAT format, WINED3DMULTISAMPLE_TYPE multisample_type,
5529         DWORD multisample_quality, BOOL lockable, IWineD3DSurface **surface)
5530 {
5531     struct IDirectDrawImpl *This = ddraw_from_device_parent(iface);
5532     IDirectDrawSurfaceImpl *d3d_surface = This->d3d_target;
5533     IDirectDrawSurfaceImpl *target = NULL;
5534
5535     TRACE("iface %p, superior %p, width %u, height %u, format %#x, multisample_type %#x,\n"
5536             "\tmultisample_quality %u, lockable %u, surface %p\n",
5537             iface, superior, width, height, format, multisample_type, multisample_quality, lockable, surface);
5538
5539     if (d3d_surface->isRenderTarget)
5540     {
5541         IDirectDrawSurface7_EnumAttachedSurfaces((IDirectDrawSurface7 *)d3d_surface, &target, findRenderTarget);
5542     }
5543     else
5544     {
5545         target = d3d_surface;
5546     }
5547
5548     if (!target)
5549     {
5550         target = This->d3d_target;
5551         ERR(" (%p) : No DirectDrawSurface found to create the back buffer. Using the front buffer as back buffer. Uncertain consequences\n", This);
5552     }
5553
5554     /* TODO: Return failure if the dimensions do not match, but this shouldn't happen */
5555
5556     *surface = target->WineD3DSurface;
5557     IWineD3DSurface_AddRef(*surface);
5558     target->isRenderTarget = TRUE;
5559
5560     TRACE("Returning wineD3DSurface %p, it belongs to surface %p\n", *surface, d3d_surface);
5561
5562     return D3D_OK;
5563 }
5564
5565 static HRESULT STDMETHODCALLTYPE device_parent_CreateDepthStencilSurface(IWineD3DDeviceParent *iface,
5566         IUnknown *superior, UINT width, UINT height, WINED3DFORMAT format, WINED3DMULTISAMPLE_TYPE multisample_type,
5567         DWORD multisample_quality, BOOL discard, IWineD3DSurface **surface)
5568 {
5569     struct IDirectDrawImpl *This = ddraw_from_device_parent(iface);
5570     IDirectDrawSurfaceImpl *ddraw_surface;
5571     DDSURFACEDESC2 ddsd;
5572     HRESULT hr;
5573
5574     TRACE("iface %p, superior %p, width %u, height %u, format %#x, multisample_type %#x,\n"
5575             "\tmultisample_quality %u, discard %u, surface %p\n",
5576             iface, superior, width, height, format, multisample_type, multisample_quality, discard, surface);
5577
5578     *surface = NULL;
5579
5580     /* Create a DirectDraw surface */
5581     memset(&ddsd, 0, sizeof(ddsd));
5582     ddsd.dwSize = sizeof(ddsd);
5583     ddsd.u4.ddpfPixelFormat.dwSize = sizeof(DDPIXELFORMAT);
5584     ddsd.dwFlags = DDSD_PIXELFORMAT | DDSD_WIDTH | DDSD_HEIGHT | DDSD_CAPS;
5585     ddsd.ddsCaps.dwCaps = DDSCAPS_OFFSCREENPLAIN;
5586     ddsd.dwHeight = height;
5587     ddsd.dwWidth = width;
5588     if (format)
5589     {
5590         PixelFormat_WineD3DtoDD(&ddsd.u4.ddpfPixelFormat, format);
5591     }
5592     else
5593     {
5594         ddsd.dwFlags ^= DDSD_PIXELFORMAT;
5595     }
5596
5597     This->depthstencil = TRUE;
5598     hr = IDirectDraw7_CreateSurface((IDirectDraw7 *)This, &ddsd, (IDirectDrawSurface7 **)&ddraw_surface, NULL);
5599     This->depthstencil = FALSE;
5600     if(FAILED(hr))
5601     {
5602         ERR(" (%p) Creating a DepthStencil Surface failed, result = %x\n", This, hr);
5603         return hr;
5604     }
5605
5606     *surface = ddraw_surface->WineD3DSurface;
5607     IWineD3DSurface_AddRef(*surface);
5608     IDirectDrawSurface7_Release((IDirectDrawSurface7 *)ddraw_surface);
5609
5610     return D3D_OK;
5611 }
5612
5613 static HRESULT STDMETHODCALLTYPE device_parent_CreateVolume(IWineD3DDeviceParent *iface,
5614         IUnknown *superior, UINT width, UINT height, UINT depth, WINED3DFORMAT format,
5615         WINED3DPOOL pool, DWORD usage, IWineD3DVolume **volume)
5616 {
5617     TRACE("iface %p, superior %p, width %u, height %u, depth %u, format %#x, pool %#x, usage %#x, volume %p\n",
5618                 iface, superior, width, height, depth, format, pool, usage, volume);
5619
5620     ERR("Not implemented!\n");
5621
5622     return E_NOTIMPL;
5623 }
5624
5625 static HRESULT STDMETHODCALLTYPE device_parent_CreateSwapChain(IWineD3DDeviceParent *iface,
5626         WINED3DPRESENT_PARAMETERS *present_parameters, IWineD3DSwapChain **swapchain)
5627 {
5628     struct IDirectDrawImpl *This = ddraw_from_device_parent(iface);
5629     IDirectDrawSurfaceImpl *iterator;
5630     IParentImpl *object;
5631     HRESULT hr;
5632
5633     TRACE("iface %p, present_parameters %p, swapchain %p\n", iface, present_parameters, swapchain);
5634
5635     object = HeapAlloc(GetProcessHeap(),  HEAP_ZERO_MEMORY, sizeof(IParentImpl));
5636     if (!object)
5637     {
5638         FIXME("Allocation of memory failed\n");
5639         *swapchain = NULL;
5640         return DDERR_OUTOFVIDEOMEMORY;
5641     }
5642
5643     ddraw_parent_init(object);
5644
5645     hr = IWineD3DDevice_CreateSwapChain(This->wineD3DDevice, present_parameters,
5646             swapchain, (IUnknown *)object, This->ImplType);
5647     if (FAILED(hr))
5648     {
5649         FIXME("(%p) CreateSwapChain failed, returning %#x\n", iface, hr);
5650         HeapFree(GetProcessHeap(), 0 , object);
5651         *swapchain = NULL;
5652         return hr;
5653     }
5654
5655     object->child = (IUnknown *)*swapchain;
5656     This->d3d_target->wineD3DSwapChain = *swapchain;
5657     iterator = This->d3d_target->complex_array[0];
5658     while (iterator)
5659     {
5660         iterator->wineD3DSwapChain = *swapchain;
5661         iterator = iterator->complex_array[0];
5662     }
5663
5664     return hr;
5665 }
5666
5667 static const IWineD3DDeviceParentVtbl ddraw_wined3d_device_parent_vtbl =
5668 {
5669     /* IUnknown methods */
5670     device_parent_QueryInterface,
5671     device_parent_AddRef,
5672     device_parent_Release,
5673     /* IWineD3DDeviceParent methods */
5674     device_parent_WineD3DDeviceCreated,
5675     device_parent_CreateSurface,
5676     device_parent_CreateRenderTarget,
5677     device_parent_CreateDepthStencilSurface,
5678     device_parent_CreateVolume,
5679     device_parent_CreateSwapChain,
5680 };
5681
5682 HRESULT ddraw_init(IDirectDrawImpl *ddraw, WINED3DDEVTYPE device_type)
5683 {
5684     HRESULT hr;
5685     HDC hDC;
5686
5687     ddraw->lpVtbl = &ddraw7_vtbl;
5688     ddraw->IDirectDraw_vtbl = &ddraw1_vtbl;
5689     ddraw->IDirectDraw2_vtbl = &ddraw2_vtbl;
5690     ddraw->IDirectDraw3_vtbl = &ddraw3_vtbl;
5691     ddraw->IDirectDraw4_vtbl = &ddraw4_vtbl;
5692     ddraw->IDirect3D_vtbl = &d3d1_vtbl;
5693     ddraw->IDirect3D2_vtbl = &d3d2_vtbl;
5694     ddraw->IDirect3D3_vtbl = &d3d3_vtbl;
5695     ddraw->IDirect3D7_vtbl = &d3d7_vtbl;
5696     ddraw->device_parent_vtbl = &ddraw_wined3d_device_parent_vtbl;
5697     ddraw->numIfaces = 1;
5698     ddraw->ref7 = 1;
5699
5700     /* See comments in IDirectDrawImpl_CreateNewSurface for a description of
5701      * this field. */
5702     ddraw->ImplType = DefaultSurfaceType;
5703
5704     /* Get the current screen settings. */
5705     hDC = GetDC(0);
5706     ddraw->orig_bpp = GetDeviceCaps(hDC, BITSPIXEL) * GetDeviceCaps(hDC, PLANES);
5707     ReleaseDC(0, hDC);
5708     ddraw->orig_width = GetSystemMetrics(SM_CXSCREEN);
5709     ddraw->orig_height = GetSystemMetrics(SM_CYSCREEN);
5710
5711     if (!LoadWineD3D())
5712     {
5713         ERR("Failed to load wined3d - broken OpenGL setup?\n");
5714         return DDERR_NODIRECTDRAWSUPPORT;
5715     }
5716
5717     ddraw->wineD3D = pWineDirect3DCreate(7, (IUnknown *)ddraw);
5718     if (!ddraw->wineD3D)
5719     {
5720         WARN("Failed to create a wined3d object.\n");
5721         return E_OUTOFMEMORY;
5722     }
5723
5724     hr = IWineD3D_CreateDevice(ddraw->wineD3D, WINED3DADAPTER_DEFAULT, device_type, NULL, 0, (IUnknown *)ddraw,
5725             (IWineD3DDeviceParent *)&ddraw->device_parent_vtbl, &ddraw->wineD3DDevice);
5726     if (FAILED(hr))
5727     {
5728         WARN("Failed to create a wined3d device, hr %#x.\n", hr);
5729         IWineD3D_Release(ddraw->wineD3D);
5730         return hr;
5731     }
5732
5733     /* Get the amount of video memory */
5734     ddraw->total_vidmem = IWineD3DDevice_GetAvailableTextureMem(ddraw->wineD3DDevice);
5735
5736     list_init(&ddraw->surface_list);
5737
5738     return DD_OK;
5739 }