ddraw: Make directdraw create functions hookable.
[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 <assert.h>
27 #include <stdarg.h>
28 #include <string.h>
29 #include <stdlib.h>
30
31 #define COBJMACROS
32 #define NONAMELESSUNION
33
34 #include "windef.h"
35 #include "winbase.h"
36 #include "winerror.h"
37 #include "wingdi.h"
38 #include "wine/exception.h"
39
40 #include "ddraw.h"
41 #include "d3d.h"
42
43 #include "ddraw_private.h"
44 #include "wine/debug.h"
45
46 WINE_DEFAULT_DEBUG_CHANNEL(ddraw);
47
48 static BOOL IDirectDrawImpl_DDSD_Match(const DDSURFACEDESC2* requested, const DDSURFACEDESC2* provided);
49 static HRESULT IDirectDrawImpl_AttachD3DDevice(IDirectDrawImpl *This, IDirectDrawSurfaceImpl *primary);
50 static HRESULT IDirectDrawImpl_CreateNewSurface(IDirectDrawImpl *This, DDSURFACEDESC2 *pDDSD, IDirectDrawSurfaceImpl **ppSurf, UINT level);
51 static HRESULT IDirectDrawImpl_CreateGDISwapChain(IDirectDrawImpl *This, IDirectDrawSurfaceImpl *primary);
52
53 /* Device identifier. Don't relay it to WineD3D */
54 static const DDDEVICEIDENTIFIER2 deviceidentifier =
55 {
56     "display",
57     "DirectDraw HAL",
58     { { 0x00010001, 0x00010001 } },
59     0, 0, 0, 0,
60     /* a8373c10-7ac4-4deb-849a-009844d08b2d */
61     {0xa8373c10,0x7ac4,0x4deb, {0x84,0x9a,0x00,0x98,0x44,0xd0,0x8b,0x2d}},
62     0
63 };
64
65 static void STDMETHODCALLTYPE ddraw_null_wined3d_object_destroyed(void *parent) {}
66
67 const struct wined3d_parent_ops ddraw_null_wined3d_parent_ops =
68 {
69     ddraw_null_wined3d_object_destroyed,
70 };
71
72 /*****************************************************************************
73  * IUnknown Methods
74  *****************************************************************************/
75
76 /*****************************************************************************
77  * IDirectDraw7::QueryInterface
78  *
79  * Queries different interfaces of the DirectDraw object. It can return
80  * IDirectDraw interfaces in version 1, 2, 4 and 7, and IDirect3D interfaces
81  * in version 1, 2, 3 and 7. An IDirect3DDevice can be created with this
82  * method.
83  * The returned interface is AddRef()-ed before it's returned
84  *
85  * Used for version 1, 2, 4 and 7
86  *
87  * Params:
88  *  refiid: Interface ID asked for
89  *  obj: Used to return the interface pointer
90  *
91  * Returns:
92  *  S_OK if an interface was found
93  *  E_NOINTERFACE if the requested interface wasn't found
94  *
95  *****************************************************************************/
96 static HRESULT WINAPI
97 IDirectDrawImpl_QueryInterface(IDirectDraw7 *iface,
98                                REFIID refiid,
99                                void **obj)
100 {
101     IDirectDrawImpl *This = (IDirectDrawImpl *)iface;
102
103     TRACE("(%p)->(%s,%p)\n", This, debugstr_guid(refiid), obj);
104
105     /* Can change surface impl type */
106     EnterCriticalSection(&ddraw_cs);
107
108     /* According to COM docs, if the QueryInterface fails, obj should be set to NULL */
109     *obj = NULL;
110
111     if(!refiid)
112     {
113         LeaveCriticalSection(&ddraw_cs);
114         return DDERR_INVALIDPARAMS;
115     }
116
117     /* Check DirectDraw Interfaces */
118     if ( IsEqualGUID( &IID_IUnknown, refiid ) ||
119          IsEqualGUID( &IID_IDirectDraw7, refiid ) )
120     {
121         *obj = This;
122         TRACE("(%p) Returning IDirectDraw7 interface at %p\n", This, *obj);
123     }
124     else if ( IsEqualGUID( &IID_IDirectDraw4, refiid ) )
125     {
126         *obj = &This->IDirectDraw4_vtbl;
127         TRACE("(%p) Returning IDirectDraw4 interface at %p\n", This, *obj);
128     }
129     else if ( IsEqualGUID( &IID_IDirectDraw3, refiid ) )
130     {
131         /* This Interface exists in ddrawex.dll, it is implemented in a wrapper */
132         WARN("IDirectDraw3 is not valid in ddraw.dll\n");
133         *obj = NULL;
134         LeaveCriticalSection(&ddraw_cs);
135         return E_NOINTERFACE;
136     }
137     else if ( IsEqualGUID( &IID_IDirectDraw2, refiid ) )
138     {
139         *obj = &This->IDirectDraw2_vtbl;
140         TRACE("(%p) Returning IDirectDraw2 interface at %p\n", This, *obj);
141     }
142     else if ( IsEqualGUID( &IID_IDirectDraw, refiid ) )
143     {
144         *obj = &This->IDirectDraw_vtbl;
145         TRACE("(%p) Returning IDirectDraw interface at %p\n", This, *obj);
146     }
147
148     /* Direct3D
149      * The refcount unit test revealed that an IDirect3D7 interface can only be queried
150      * from a DirectDraw object that was created as an IDirectDraw7 interface. No idea
151      * who had this idea and why. The older interfaces can query and IDirect3D version
152      * because they are all created as IDirectDraw(1). This isn't really crucial behavior,
153      * and messy to implement with the common creation function, so it has been left out here.
154      */
155     else if ( IsEqualGUID( &IID_IDirect3D  , refiid ) ||
156               IsEqualGUID( &IID_IDirect3D2 , refiid ) ||
157               IsEqualGUID( &IID_IDirect3D3 , refiid ) ||
158               IsEqualGUID( &IID_IDirect3D7 , refiid ) )
159     {
160         /* Check the surface implementation */
161         if(This->ImplType == SURFACE_UNKNOWN)
162         {
163             /* Apps may create the IDirect3D Interface before the primary surface.
164              * set the surface implementation */
165             This->ImplType = SURFACE_OPENGL;
166             TRACE("(%p) Choosing OpenGL surfaces because a Direct3D interface was requested\n", This);
167         }
168         else if(This->ImplType != SURFACE_OPENGL && DefaultSurfaceType == SURFACE_UNKNOWN)
169         {
170             ERR("(%p) The App is requesting a D3D device, but a non-OpenGL surface type was choosen. Prepare for trouble!\n", This);
171             ERR(" (%p) You may want to contact wine-devel for help\n", This);
172             /* Should I assert(0) here??? */
173         }
174         else if(This->ImplType != SURFACE_OPENGL)
175         {
176             WARN("The app requests a Direct3D interface, but non-opengl surfaces where set in winecfg\n");
177             /* Do not abort here, only reject 3D Device creation */
178         }
179
180         if ( IsEqualGUID( &IID_IDirect3D  , refiid ) )
181         {
182             This->d3dversion = 1;
183             *obj = &This->IDirect3D_vtbl;
184             TRACE(" returning Direct3D interface at %p.\n", *obj);
185         }
186         else if ( IsEqualGUID( &IID_IDirect3D2  , refiid ) )
187         {
188             This->d3dversion = 2;
189             *obj = &This->IDirect3D2_vtbl;
190             TRACE(" returning Direct3D2 interface at %p.\n", *obj);
191         }
192         else if ( IsEqualGUID( &IID_IDirect3D3  , refiid ) )
193         {
194             This->d3dversion = 3;
195             *obj = &This->IDirect3D3_vtbl;
196             TRACE(" returning Direct3D3 interface at %p.\n", *obj);
197         }
198         else if(IsEqualGUID( &IID_IDirect3D7  , refiid ))
199         {
200             This->d3dversion = 7;
201             *obj = &This->IDirect3D7_vtbl;
202             TRACE(" returning Direct3D7 interface at %p.\n", *obj);
203         }
204     }
205     else if (IsEqualGUID(refiid, &IID_IWineD3DDeviceParent))
206     {
207         *obj = &This->device_parent_vtbl;
208     }
209
210     /* Unknown interface */
211     else
212     {
213         ERR("(%p)->(%s, %p): No interface found\n", This, debugstr_guid(refiid), obj);
214         LeaveCriticalSection(&ddraw_cs);
215         return E_NOINTERFACE;
216     }
217
218     IUnknown_AddRef( (IUnknown *) *obj );
219     LeaveCriticalSection(&ddraw_cs);
220     return S_OK;
221 }
222
223 /*****************************************************************************
224  * IDirectDraw7::AddRef
225  *
226  * Increases the interfaces refcount, basically
227  *
228  * DDraw refcounting is a bit tricky. The different DirectDraw interface
229  * versions have individual refcounts, but the IDirect3D interfaces do not.
230  * All interfaces are from one object, that means calling QueryInterface on an
231  * IDirectDraw7 interface for an IDirectDraw4 interface does not create a new
232  * IDirectDrawImpl object.
233  *
234  * That means all AddRef and Release implementations of IDirectDrawX work
235  * with their own counter, and IDirect3DX::AddRef thunk to IDirectDraw (1),
236  * except of IDirect3D7 which thunks to IDirectDraw7
237  *
238  * Returns: The new refcount
239  *
240  *****************************************************************************/
241 static ULONG WINAPI
242 IDirectDrawImpl_AddRef(IDirectDraw7 *iface)
243 {
244     IDirectDrawImpl *This = (IDirectDrawImpl *)iface;
245     ULONG ref = InterlockedIncrement(&This->ref7);
246
247     TRACE("(%p) : incrementing IDirectDraw7 refcount from %u.\n", This, ref -1);
248
249     if(ref == 1) InterlockedIncrement(&This->numIfaces);
250
251     return ref;
252 }
253
254 /*****************************************************************************
255  * IDirectDrawImpl_Destroy
256  *
257  * Destroys a ddraw object if all refcounts are 0. This is to share code
258  * between the IDirectDrawX::Release functions
259  *
260  * Params:
261  *  This: DirectDraw object to destroy
262  *
263  *****************************************************************************/
264 void
265 IDirectDrawImpl_Destroy(IDirectDrawImpl *This)
266 {
267     /* Clear the cooplevel to restore window and display mode */
268     IDirectDraw7_SetCooperativeLevel((IDirectDraw7 *)This, NULL, DDSCL_NORMAL);
269
270     /* Destroy the device window if we created one */
271     if(This->devicewindow != 0)
272     {
273         TRACE(" (%p) Destroying the device window %p\n", This, This->devicewindow);
274         DestroyWindow(This->devicewindow);
275         This->devicewindow = 0;
276     }
277
278     /* Unregister the window class */
279     UnregisterClassA(This->classname, 0);
280
281     EnterCriticalSection(&ddraw_cs);
282     list_remove(&This->ddraw_list_entry);
283     LeaveCriticalSection(&ddraw_cs);
284
285     /* Release the attached WineD3D stuff */
286     IWineD3DDevice_Release(This->wineD3DDevice);
287     IWineD3D_Release(This->wineD3D);
288
289     /* Now free the object */
290     HeapFree(GetProcessHeap(), 0, This);
291 }
292
293 /*****************************************************************************
294  * IDirectDraw7::Release
295  *
296  * Decreases the refcount. If the refcount falls to 0, the object is destroyed
297  *
298  * Returns: The new refcount
299  *****************************************************************************/
300 static ULONG WINAPI
301 IDirectDrawImpl_Release(IDirectDraw7 *iface)
302 {
303     IDirectDrawImpl *This = (IDirectDrawImpl *)iface;
304     ULONG ref = InterlockedDecrement(&This->ref7);
305
306     TRACE("(%p)->() decrementing IDirectDraw7 refcount from %u.\n", This, ref +1);
307
308     if(ref == 0)
309     {
310         ULONG ifacecount = InterlockedDecrement(&This->numIfaces);
311         if(ifacecount == 0) IDirectDrawImpl_Destroy(This);
312     }
313
314     return ref;
315 }
316
317 /*****************************************************************************
318  * IDirectDraw methods
319  *****************************************************************************/
320
321 /*****************************************************************************
322  * IDirectDraw7::SetCooperativeLevel
323  *
324  * Sets the cooperative level for the DirectDraw object, and the window
325  * assigned to it. The cooperative level determines the general behavior
326  * of the DirectDraw application
327  *
328  * Warning: This is quite tricky, as it's not really documented which
329  * cooperative levels can be combined with each other. If a game fails
330  * after this function, try to check the cooperative levels passed on
331  * Windows, and if it returns something different.
332  *
333  * If you think that this function caused the failure because it writes a
334  * fixme, be sure to run again with a +ddraw trace.
335  *
336  * What is known about cooperative levels (See the ddraw modes test):
337  * DDSCL_EXCLUSIVE and DDSCL_FULLSCREEN must be used with each other
338  * DDSCL_NORMAL is not compatible with DDSCL_EXCLUSIVE or DDSCL_FULLSCREEN
339  * DDSCL_SETFOCUSWINDOW can be passed only in DDSCL_NORMAL mode, but after that
340  * DDSCL_FULLSCREEN can be activated
341  * DDSCL_SETFOCUSWINDOW may only be used with DDSCL_NOWINDOWCHANGES
342  *
343  * Handled flags: DDSCL_NORMAL, DDSCL_FULLSCREEN, DDSCL_EXCLUSIVE,
344  *                DDSCL_SETFOCUSWINDOW (partially),
345  *                DDSCL_MULTITHREADED (work in progress)
346  *
347  * Unhandled flags, which should be implemented
348  *  DDSCL_SETDEVICEWINDOW: Sets a window specially used for rendering (I don't
349  *  expect any difference to a normal window for wine)
350  *  DDSCL_CREATEDEVICEWINDOW: Tells ddraw to create its own window for
351  *  rendering (Possible test case: Half-life)
352  *
353  * Unsure about these: DDSCL_FPUSETUP DDSCL_FPURESERVE
354  *
355  * These don't seem very important for wine:
356  *  DDSCL_ALLOWREBOOT, DDSCL_NOWINDOWCHANGES, DDSCL_ALLOWMODEX
357  *
358  * Returns:
359  *  DD_OK if the cooperative level was set successfully
360  *  DDERR_INVALIDPARAMS if the passed cooperative level combination is invalid
361  *  DDERR_HWNDALREADYSET if DDSCL_SETFOCUSWINDOW is passed in exclusive mode
362  *   (Probably others too, have to investigate)
363  *
364  *****************************************************************************/
365 static HRESULT WINAPI
366 IDirectDrawImpl_SetCooperativeLevel(IDirectDraw7 *iface,
367                                     HWND hwnd,
368                                     DWORD cooplevel)
369 {
370     IDirectDrawImpl *This = (IDirectDrawImpl *)iface;
371     HWND window;
372
373     TRACE("(%p)->(%p,%08x)\n",This,hwnd,cooplevel);
374     DDRAW_dump_cooperativelevel(cooplevel);
375
376     EnterCriticalSection(&ddraw_cs);
377
378     /* Get the old window */
379     window = This->dest_window;
380
381     /* Tests suggest that we need one of them: */
382     if(!(cooplevel & (DDSCL_SETFOCUSWINDOW |
383                       DDSCL_NORMAL         |
384                       DDSCL_EXCLUSIVE      )))
385     {
386         TRACE("Incorrect cooplevel flags, returning DDERR_INVALIDPARAMS\n");
387         LeaveCriticalSection(&ddraw_cs);
388         return DDERR_INVALIDPARAMS;
389     }
390
391     /* Handle those levels first which set various hwnds */
392     if(cooplevel & DDSCL_SETFOCUSWINDOW)
393     {
394         /* This isn't compatible with a lot of flags */
395         if(cooplevel & ( DDSCL_MULTITHREADED   |
396                          DDSCL_FPUSETUP        |
397                          DDSCL_FPUPRESERVE     |
398                          DDSCL_ALLOWREBOOT     |
399                          DDSCL_ALLOWMODEX      |
400                          DDSCL_SETDEVICEWINDOW |
401                          DDSCL_NORMAL          |
402                          DDSCL_EXCLUSIVE       |
403                          DDSCL_FULLSCREEN      ) )
404         {
405             TRACE("Called with incompatible flags, returning DDERR_INVALIDPARAMS\n");
406             LeaveCriticalSection(&ddraw_cs);
407             return DDERR_INVALIDPARAMS;
408         }
409         else if( (This->cooperative_level & DDSCL_FULLSCREEN) && window)
410         {
411             TRACE("Setting DDSCL_SETFOCUSWINDOW with an already set window, returning DDERR_HWNDALREADYSET\n");
412             LeaveCriticalSection(&ddraw_cs);
413             return DDERR_HWNDALREADYSET;
414         }
415
416         This->focuswindow = hwnd;
417         /* Won't use the hwnd param for anything else */
418         hwnd = NULL;
419
420         /* Use the focus window for drawing too */
421         This->dest_window = This->focuswindow;
422
423         /* Destroy the device window, if we have one */
424         if(This->devicewindow)
425         {
426             DestroyWindow(This->devicewindow);
427             This->devicewindow = NULL;
428         }
429     }
430     /* DDSCL_NORMAL or DDSCL_FULLSCREEN | DDSCL_EXCLUSIVE */
431     if(cooplevel & DDSCL_NORMAL)
432     {
433         /* Can't coexist with fullscreen or exclusive */
434         if(cooplevel & (DDSCL_FULLSCREEN | DDSCL_EXCLUSIVE) )
435         {
436             TRACE("(%p) DDSCL_NORMAL is not compative with DDSCL_FULLSCREEN or DDSCL_EXCLUSIVE\n", This);
437             LeaveCriticalSection(&ddraw_cs);
438             return DDERR_INVALIDPARAMS;
439         }
440
441         /* Switching from fullscreen? */
442         if(This->cooperative_level & DDSCL_FULLSCREEN)
443         {
444             /* Restore the display mode */
445             IDirectDraw7_RestoreDisplayMode(iface);
446
447             This->cooperative_level &= ~DDSCL_FULLSCREEN;
448             This->cooperative_level &= ~DDSCL_EXCLUSIVE;
449             This->cooperative_level &= ~DDSCL_ALLOWMODEX;
450         }
451
452         /* Don't override focus windows or private device windows */
453         if( hwnd &&
454             !(This->focuswindow) &&
455             !(This->devicewindow) &&
456             (hwnd != window) )
457         {
458             This->dest_window = hwnd;
459         }
460     }
461     else if(cooplevel & DDSCL_FULLSCREEN)
462     {
463         /* Needs DDSCL_EXCLUSIVE */
464         if(!(cooplevel & DDSCL_EXCLUSIVE) )
465         {
466             TRACE("(%p) DDSCL_FULLSCREEN needs DDSCL_EXCLUSIVE\n", This);
467             LeaveCriticalSection(&ddraw_cs);
468             return DDERR_INVALIDPARAMS;
469         }
470         /* Need a HWND
471         if(hwnd == 0)
472         {
473             TRACE("(%p) DDSCL_FULLSCREEN needs a HWND\n", This);
474             return DDERR_INVALIDPARAMS;
475         }
476         */
477
478         This->cooperative_level &= ~DDSCL_NORMAL;
479
480         /* Don't override focus windows or private device windows */
481         if( hwnd &&
482             !(This->focuswindow) &&
483             !(This->devicewindow) &&
484             (hwnd != window) )
485         {
486             This->dest_window = hwnd;
487         }
488     }
489     else if(cooplevel & DDSCL_EXCLUSIVE)
490     {
491         TRACE("(%p) DDSCL_EXCLUSIVE needs DDSCL_FULLSCREEN\n", This);
492         LeaveCriticalSection(&ddraw_cs);
493         return DDERR_INVALIDPARAMS;
494     }
495
496     if(cooplevel & DDSCL_CREATEDEVICEWINDOW)
497     {
498         /* Don't create a device window if a focus window is set */
499         if( !(This->focuswindow) )
500         {
501             HWND devicewindow = CreateWindowExA(0, This->classname, "DDraw device window",
502                                                 WS_POPUP, 0, 0,
503                                                 GetSystemMetrics(SM_CXSCREEN),
504                                                 GetSystemMetrics(SM_CYSCREEN),
505                                                 NULL, NULL, GetModuleHandleA(0), NULL);
506
507             ShowWindow(devicewindow, SW_SHOW);   /* Just to be sure */
508             TRACE("(%p) Created a DDraw device window. HWND=%p\n", This, devicewindow);
509
510             This->devicewindow = devicewindow;
511             This->dest_window = devicewindow;
512         }
513     }
514
515     if(cooplevel & DDSCL_MULTITHREADED && !(This->cooperative_level & DDSCL_MULTITHREADED))
516     {
517         /* Enable thread safety in wined3d */
518         IWineD3DDevice_SetMultithreaded(This->wineD3DDevice);
519     }
520
521     /* Unhandled flags */
522     if(cooplevel & DDSCL_ALLOWREBOOT)
523         WARN("(%p) Unhandled flag DDSCL_ALLOWREBOOT, harmless\n", This);
524     if(cooplevel & DDSCL_ALLOWMODEX)
525         WARN("(%p) Unhandled flag DDSCL_ALLOWMODEX, harmless\n", This);
526     if(cooplevel & DDSCL_FPUSETUP)
527         WARN("(%p) Unhandled flag DDSCL_FPUSETUP, harmless\n", This);
528
529     /* Store the cooperative_level */
530     This->cooperative_level |= cooplevel;
531     TRACE("SetCooperativeLevel retuning DD_OK\n");
532     LeaveCriticalSection(&ddraw_cs);
533     return DD_OK;
534 }
535
536 /*****************************************************************************
537  *
538  * Helper function for SetDisplayMode and RestoreDisplayMode
539  *
540  * Implements DirectDraw's SetDisplayMode, but ignores the value of
541  * ForceRefreshRate, since it is already handled by
542  * IDirectDrawImpl_SetDisplayMode.  RestoreDisplayMode can use this function
543  * without worrying that ForceRefreshRate will override the refresh rate.  For
544  * argument and return value documentation, see
545  * IDirectDrawImpl_SetDisplayMode.
546  *
547  *****************************************************************************/
548 static HRESULT
549 IDirectDrawImpl_SetDisplayModeNoOverride(IDirectDraw7 *iface,
550                                          DWORD Width,
551                                          DWORD Height,
552                                          DWORD BPP,
553                                          DWORD RefreshRate,
554                                          DWORD Flags)
555 {
556     IDirectDrawImpl *This = (IDirectDrawImpl *)iface;
557     WINED3DDISPLAYMODE Mode;
558     HRESULT hr;
559     TRACE("(%p)->(%d,%d,%d,%d,%x): Relay!\n", This, Width, Height, BPP, RefreshRate, Flags);
560
561     EnterCriticalSection(&ddraw_cs);
562     if( !Width || !Height )
563     {
564         ERR("Width=%d, Height=%d, what to do?\n", Width, Height);
565         /* It looks like Need for Speed Porsche Unleashed expects DD_OK here */
566         LeaveCriticalSection(&ddraw_cs);
567         return DD_OK;
568     }
569
570     /* Check the exclusive mode
571     if(!(This->cooperative_level & DDSCL_EXCLUSIVE))
572         return DDERR_NOEXCLUSIVEMODE;
573      * This is WRONG. Don't know if the SDK is completely
574      * wrong and if there are any conditions when DDERR_NOEXCLUSIVE
575      * is returned, but Half-Life 1.1.1.1 (Steam version)
576      * depends on this
577      */
578
579     Mode.Width = Width;
580     Mode.Height = Height;
581     Mode.RefreshRate = RefreshRate;
582     switch(BPP)
583     {
584         case 8:  Mode.Format = WINED3DFMT_P8_UINT;          break;
585         case 15: Mode.Format = WINED3DFMT_B5G5R5X1_UNORM;   break;
586         case 16: Mode.Format = WINED3DFMT_B5G6R5_UNORM;     break;
587         case 24: Mode.Format = WINED3DFMT_B8G8R8_UNORM;     break;
588         case 32: Mode.Format = WINED3DFMT_B8G8R8X8_UNORM;   break;
589     }
590
591     /* TODO: The possible return values from msdn suggest that
592      * the screen mode can't be changed if a surface is locked
593      * or some drawing is in progress
594      */
595
596     /* TODO: Lose the primary surface */
597     hr = IWineD3DDevice_SetDisplayMode(This->wineD3DDevice,
598                                        0, /* First swapchain */
599                                        &Mode);
600     LeaveCriticalSection(&ddraw_cs);
601     switch(hr)
602     {
603         case WINED3DERR_NOTAVAILABLE:       return DDERR_UNSUPPORTED;
604         default:                            return hr;
605     }
606 }
607
608 /*****************************************************************************
609  * IDirectDraw7::SetDisplayMode
610  *
611  * Sets the display screen resolution, color depth and refresh frequency
612  * when in fullscreen mode (in theory).
613  * Possible return values listed in the SDK suggest that this method fails
614  * when not in fullscreen mode, but this is wrong. Windows 2000 happily sets
615  * the display mode in DDSCL_NORMAL mode without an hwnd specified.
616  * It seems to be valid to pass 0 for With and Height, this has to be tested
617  * It could mean that the current video mode should be left as-is. (But why
618  * call it then?)
619  *
620  * Params:
621  *  Height, Width: Screen dimension
622  *  BPP: Color depth in Bits per pixel
623  *  Refreshrate: Screen refresh rate
624  *  Flags: Other stuff
625  *
626  * Returns
627  *  DD_OK on success
628  *
629  *****************************************************************************/
630 static HRESULT WINAPI
631 IDirectDrawImpl_SetDisplayMode(IDirectDraw7 *iface,
632                                DWORD Width,
633                                DWORD Height,
634                                DWORD BPP,
635                                DWORD RefreshRate,
636                                DWORD Flags)
637 {
638     if (force_refresh_rate != 0)
639     {
640         TRACE("ForceRefreshRate overriding passed-in refresh rate (%d Hz) to %d Hz\n", RefreshRate, force_refresh_rate);
641         RefreshRate = force_refresh_rate;
642     }
643
644     return IDirectDrawImpl_SetDisplayModeNoOverride(iface, Width, Height, BPP,
645                                                     RefreshRate, Flags);
646 }
647
648 /*****************************************************************************
649  * IDirectDraw7::RestoreDisplayMode
650  *
651  * Restores the display mode to what it was at creation time. Basically.
652  *
653  * A problem arises when there are 2 DirectDraw objects using the same hwnd:
654  *  -> DD_1 finds the screen at 1400x1050x32 when created, sets it to 640x480x16
655  *  -> DD_2 is created, finds the screen at 640x480x16, sets it to 1024x768x32
656  *  -> DD_1 is released. The screen should be left at 1024x768x32.
657  *  -> DD_2 is released. The screen should be set to 1400x1050x32
658  * This case is unhandled right now, but Empire Earth does it this way.
659  * (But perhaps there is something in SetCooperativeLevel to prevent this)
660  *
661  * The msdn says that this method resets the display mode to what it was before
662  * SetDisplayMode was called. What if SetDisplayModes is called 2 times??
663  *
664  * Returns
665  *  DD_OK on success
666  *  DDERR_NOEXCLUSIVE mode if the device isn't in fullscreen mode
667  *
668  *****************************************************************************/
669 static HRESULT WINAPI
670 IDirectDrawImpl_RestoreDisplayMode(IDirectDraw7 *iface)
671 {
672     IDirectDrawImpl *This = (IDirectDrawImpl *)iface;
673     TRACE("(%p)\n", This);
674
675     return IDirectDrawImpl_SetDisplayModeNoOverride(iface,
676             This->orig_width, This->orig_height, This->orig_bpp, 0, 0);
677 }
678
679 /*****************************************************************************
680  * IDirectDraw7::GetCaps
681  *
682  * Returns the drives capabilities
683  *
684  * Used for version 1, 2, 4 and 7
685  *
686  * Params:
687  *  DriverCaps: Structure to write the Hardware accelerated caps to
688  *  HelCaps: Structure to write the emulation caps to
689  *
690  * Returns
691  *  This implementation returns DD_OK only
692  *
693  *****************************************************************************/
694 static HRESULT WINAPI
695 IDirectDrawImpl_GetCaps(IDirectDraw7 *iface,
696                         DDCAPS *DriverCaps,
697                         DDCAPS *HELCaps)
698 {
699     IDirectDrawImpl *This = (IDirectDrawImpl *)iface;
700     DDCAPS caps;
701     WINED3DCAPS winecaps;
702     HRESULT hr;
703     DDSCAPS2 ddscaps = {0, 0, 0, 0};
704     TRACE("(%p)->(%p,%p)\n", This, DriverCaps, HELCaps);
705
706     /* One structure must be != NULL */
707     if( (!DriverCaps) && (!HELCaps) )
708     {
709         ERR("(%p) Invalid params to IDirectDrawImpl_GetCaps\n", This);
710         return DDERR_INVALIDPARAMS;
711     }
712
713     memset(&caps, 0, sizeof(caps));
714     memset(&winecaps, 0, sizeof(winecaps));
715     caps.dwSize = sizeof(caps);
716     EnterCriticalSection(&ddraw_cs);
717     hr = IWineD3DDevice_GetDeviceCaps(This->wineD3DDevice, &winecaps);
718     if(FAILED(hr)) {
719         WARN("IWineD3DDevice::GetDeviceCaps failed\n");
720         LeaveCriticalSection(&ddraw_cs);
721         return hr;
722     }
723
724     hr = IDirectDraw7_GetAvailableVidMem(iface, &ddscaps, &caps.dwVidMemTotal, &caps.dwVidMemFree);
725     LeaveCriticalSection(&ddraw_cs);
726     if(FAILED(hr)) {
727         WARN("IDirectDraw7::GetAvailableVidMem failed\n");
728         return hr;
729     }
730
731     caps.dwCaps = winecaps.DirectDrawCaps.Caps;
732     caps.dwCaps2 = winecaps.DirectDrawCaps.Caps2;
733     caps.dwCKeyCaps = winecaps.DirectDrawCaps.CKeyCaps;
734     caps.dwFXCaps = winecaps.DirectDrawCaps.FXCaps;
735     caps.dwPalCaps = winecaps.DirectDrawCaps.PalCaps;
736     caps.ddsCaps.dwCaps = winecaps.DirectDrawCaps.ddsCaps;
737     caps.dwSVBCaps = winecaps.DirectDrawCaps.SVBCaps;
738     caps.dwSVBCKeyCaps = winecaps.DirectDrawCaps.SVBCKeyCaps;
739     caps.dwSVBFXCaps = winecaps.DirectDrawCaps.SVBFXCaps;
740     caps.dwVSBCaps = winecaps.DirectDrawCaps.VSBCaps;
741     caps.dwVSBCKeyCaps = winecaps.DirectDrawCaps.VSBCKeyCaps;
742     caps.dwVSBFXCaps = winecaps.DirectDrawCaps.VSBFXCaps;
743     caps.dwSSBCaps = winecaps.DirectDrawCaps.SSBCaps;
744     caps.dwSSBCKeyCaps = winecaps.DirectDrawCaps.SSBCKeyCaps;
745     caps.dwSSBFXCaps = winecaps.DirectDrawCaps.SSBFXCaps;
746
747     /* Even if WineD3D supports 3D rendering, remove the cap if ddraw is configured
748      * not to use it
749      */
750     if(DefaultSurfaceType == SURFACE_GDI) {
751         caps.dwCaps &= ~DDCAPS_3D;
752         caps.ddsCaps.dwCaps &= ~(DDSCAPS_3DDEVICE | DDSCAPS_MIPMAP | DDSCAPS_TEXTURE | DDSCAPS_ZBUFFER);
753     }
754     if(winecaps.DirectDrawCaps.StrideAlign != 0) {
755         caps.dwCaps |= DDCAPS_ALIGNSTRIDE;
756         caps.dwAlignStrideAlign = winecaps.DirectDrawCaps.StrideAlign;
757     }
758
759     if(DriverCaps)
760     {
761         DD_STRUCT_COPY_BYSIZE(DriverCaps, &caps);
762         if (TRACE_ON(ddraw))
763         {
764             TRACE("Driver Caps :\n");
765             DDRAW_dump_DDCAPS(DriverCaps);
766         }
767
768     }
769     if(HELCaps)
770     {
771         DD_STRUCT_COPY_BYSIZE(HELCaps, &caps);
772         if (TRACE_ON(ddraw))
773         {
774             TRACE("HEL Caps :\n");
775             DDRAW_dump_DDCAPS(HELCaps);
776         }
777     }
778
779     return DD_OK;
780 }
781
782 /*****************************************************************************
783  * IDirectDraw7::Compact
784  *
785  * No idea what it does, MSDN says it's not implemented.
786  *
787  * Returns
788  *  DD_OK, but this is unchecked
789  *
790  *****************************************************************************/
791 static HRESULT WINAPI
792 IDirectDrawImpl_Compact(IDirectDraw7 *iface)
793 {
794     IDirectDrawImpl *This = (IDirectDrawImpl *)iface;
795     TRACE("(%p)\n", This);
796
797     return DD_OK;
798 }
799
800 /*****************************************************************************
801  * IDirectDraw7::GetDisplayMode
802  *
803  * Returns information about the current display mode
804  *
805  * Exists in Version 1, 2, 4 and 7
806  *
807  * Params:
808  *  DDSD: Address of a surface description structure to write the info to
809  *
810  * Returns
811  *  DD_OK
812  *
813  *****************************************************************************/
814 static HRESULT WINAPI
815 IDirectDrawImpl_GetDisplayMode(IDirectDraw7 *iface,
816                                DDSURFACEDESC2 *DDSD)
817 {
818     IDirectDrawImpl *This = (IDirectDrawImpl *)iface;
819     HRESULT hr;
820     WINED3DDISPLAYMODE Mode;
821     DWORD Size;
822     TRACE("(%p)->(%p): Relay\n", This, DDSD);
823
824     EnterCriticalSection(&ddraw_cs);
825     /* This seems sane */
826     if (!DDSD)
827     {
828         LeaveCriticalSection(&ddraw_cs);
829         return DDERR_INVALIDPARAMS;
830     }
831
832     /* The necessary members of LPDDSURFACEDESC and LPDDSURFACEDESC2 are equal,
833      * so one method can be used for all versions (Hopefully)
834      */
835     hr = IWineD3DDevice_GetDisplayMode(This->wineD3DDevice,
836                                       0 /* swapchain 0 */,
837                                       &Mode);
838     if( hr != D3D_OK )
839     {
840         ERR(" (%p) IWineD3DDevice::GetDisplayMode returned %08x\n", This, hr);
841         LeaveCriticalSection(&ddraw_cs);
842         return hr;
843     }
844
845     Size = DDSD->dwSize;
846     memset(DDSD, 0, Size);
847
848     DDSD->dwSize = Size;
849     DDSD->dwFlags |= DDSD_HEIGHT | DDSD_WIDTH | DDSD_PIXELFORMAT | DDSD_PITCH | DDSD_REFRESHRATE;
850     DDSD->dwWidth = Mode.Width;
851     DDSD->dwHeight = Mode.Height;
852     DDSD->u2.dwRefreshRate = 60;
853     DDSD->ddsCaps.dwCaps = 0;
854     DDSD->u4.ddpfPixelFormat.dwSize = sizeof(DDSD->u4.ddpfPixelFormat);
855     PixelFormat_WineD3DtoDD(&DDSD->u4.ddpfPixelFormat, Mode.Format);
856     DDSD->u1.lPitch = Mode.Width * DDSD->u4.ddpfPixelFormat.u1.dwRGBBitCount / 8;
857
858     if(TRACE_ON(ddraw))
859     {
860         TRACE("Returning surface desc :\n");
861         DDRAW_dump_surface_desc(DDSD);
862     }
863
864     LeaveCriticalSection(&ddraw_cs);
865     return DD_OK;
866 }
867
868 /*****************************************************************************
869  * IDirectDraw7::GetFourCCCodes
870  *
871  * Returns an array of supported FourCC codes.
872  *
873  * Exists in Version 1, 2, 4 and 7
874  *
875  * Params:
876  *  NumCodes: Contains the number of Codes that Codes can carry. Returns the number
877  *            of enumerated codes
878  *  Codes: Pointer to an array of DWORDs where the supported codes are written
879  *         to
880  *
881  * Returns
882  *  Always returns DD_OK, as it's a stub for now
883  *
884  *****************************************************************************/
885 static HRESULT WINAPI
886 IDirectDrawImpl_GetFourCCCodes(IDirectDraw7 *iface,
887                                DWORD *NumCodes, DWORD *Codes)
888 {
889     IDirectDrawImpl *This = (IDirectDrawImpl *)iface;
890     WINED3DFORMAT formats[] = {
891         WINED3DFMT_YUY2, WINED3DFMT_UYVY, WINED3DFMT_YV12,
892         WINED3DFMT_DXT1, WINED3DFMT_DXT2, WINED3DFMT_DXT3, WINED3DFMT_DXT4, WINED3DFMT_DXT5,
893         WINED3DFMT_ATI2N, WINED3DFMT_NVHU, WINED3DFMT_NVHS
894     };
895     DWORD count = 0, i, outsize;
896     HRESULT hr;
897     WINED3DDISPLAYMODE d3ddm;
898     WINED3DSURFTYPE type = This->ImplType;
899     TRACE("(%p)->(%p, %p)\n", This, NumCodes, Codes);
900
901     IWineD3DDevice_GetDisplayMode(This->wineD3DDevice,
902                                   0 /* swapchain 0 */,
903                                   &d3ddm);
904
905     outsize = NumCodes && Codes ? *NumCodes : 0;
906
907     if(type == SURFACE_UNKNOWN) type = SURFACE_GDI;
908
909     for(i = 0; i < (sizeof(formats) / sizeof(formats[0])); i++) {
910         hr = IWineD3D_CheckDeviceFormat(This->wineD3D,
911                                         WINED3DADAPTER_DEFAULT,
912                                         WINED3DDEVTYPE_HAL,
913                                         d3ddm.Format /* AdapterFormat */,
914                                         0 /* usage */,
915                                         WINED3DRTYPE_SURFACE,
916                                         formats[i],
917                                         type);
918         if(SUCCEEDED(hr)) {
919             if(count < outsize) {
920                 Codes[count] = formats[i];
921             }
922             count++;
923         }
924     }
925     if(NumCodes) {
926         TRACE("Returning %u FourCC codes\n", count);
927         *NumCodes = count;
928     }
929
930     return DD_OK;
931 }
932
933 /*****************************************************************************
934  * IDirectDraw7::GetMonitorFrequency
935  *
936  * Returns the monitor's frequency
937  *
938  * Exists in Version 1, 2, 4 and 7
939  *
940  * Params:
941  *  Freq: Pointer to a DWORD to write the frequency to
942  *
943  * Returns
944  *  Always returns DD_OK
945  *
946  *****************************************************************************/
947 static HRESULT WINAPI
948 IDirectDrawImpl_GetMonitorFrequency(IDirectDraw7 *iface,
949                                     DWORD *Freq)
950 {
951     IDirectDrawImpl *This = (IDirectDrawImpl *)iface;
952     TRACE("(%p)->(%p)\n", This, Freq);
953
954     /* Ideally this should be in WineD3D, as it concerns the screen setup,
955      * but for now this should make the games happy
956      */
957     *Freq = 60;
958     return DD_OK;
959 }
960
961 /*****************************************************************************
962  * IDirectDraw7::GetVerticalBlankStatus
963  *
964  * Returns the Vertical blank status of the monitor. This should be in WineD3D
965  * too basically, but as it's a semi stub, I didn't create a function there
966  *
967  * Params:
968  *  status: Pointer to a BOOL to be filled with the vertical blank status
969  *
970  * Returns
971  *  DD_OK on success
972  *  DDERR_INVALIDPARAMS if status is NULL
973  *
974  *****************************************************************************/
975 static HRESULT WINAPI
976 IDirectDrawImpl_GetVerticalBlankStatus(IDirectDraw7 *iface,
977                                        BOOL *status)
978 {
979     IDirectDrawImpl *This = (IDirectDrawImpl *)iface;
980     TRACE("(%p)->(%p)\n", This, status);
981
982     /* This looks sane, the MSDN suggests it too */
983     EnterCriticalSection(&ddraw_cs);
984     if(!status)
985     {
986         LeaveCriticalSection(&ddraw_cs);
987         return DDERR_INVALIDPARAMS;
988     }
989
990     *status = This->fake_vblank;
991     This->fake_vblank = !This->fake_vblank;
992     LeaveCriticalSection(&ddraw_cs);
993     return DD_OK;
994 }
995
996 /*****************************************************************************
997  * IDirectDraw7::GetAvailableVidMem
998  *
999  * Returns the total and free video memory
1000  *
1001  * Params:
1002  *  Caps: Specifies the memory type asked for
1003  *  total: Pointer to a DWORD to be filled with the total memory
1004  *  free: Pointer to a DWORD to be filled with the free memory
1005  *
1006  * Returns
1007  *  DD_OK on success
1008  *  DDERR_INVALIDPARAMS of free and total are NULL
1009  *
1010  *****************************************************************************/
1011 static HRESULT WINAPI
1012 IDirectDrawImpl_GetAvailableVidMem(IDirectDraw7 *iface, DDSCAPS2 *Caps, DWORD *total, DWORD *free)
1013 {
1014     IDirectDrawImpl *This = (IDirectDrawImpl *)iface;
1015     TRACE("(%p)->(%p, %p, %p)\n", This, Caps, total, free);
1016
1017     if(TRACE_ON(ddraw))
1018     {
1019         TRACE("(%p) Asked for memory with description: ", This);
1020         DDRAW_dump_DDSCAPS2(Caps);
1021     }
1022     EnterCriticalSection(&ddraw_cs);
1023
1024     /* Todo: System memory vs local video memory vs non-local video memory
1025      * The MSDN also mentions differences between texture memory and other
1026      * resources, but that's not important
1027      */
1028
1029     if( (!total) && (!free) )
1030     {
1031         LeaveCriticalSection(&ddraw_cs);
1032         return DDERR_INVALIDPARAMS;
1033     }
1034
1035     if(total) *total = This->total_vidmem;
1036     if(free) *free = IWineD3DDevice_GetAvailableTextureMem(This->wineD3DDevice);
1037
1038     LeaveCriticalSection(&ddraw_cs);
1039     return DD_OK;
1040 }
1041
1042 /*****************************************************************************
1043  * IDirectDraw7::Initialize
1044  *
1045  * Initializes a DirectDraw interface.
1046  *
1047  * Params:
1048  *  GUID: Interface identifier. Well, don't know what this is really good
1049  *   for
1050  *
1051  * Returns
1052  *  Returns DD_OK on the first call,
1053  *  DDERR_ALREADYINITIALIZED on repeated calls
1054  *
1055  *****************************************************************************/
1056 static HRESULT WINAPI
1057 IDirectDrawImpl_Initialize(IDirectDraw7 *iface,
1058                            GUID *Guid)
1059 {
1060     IDirectDrawImpl *This = (IDirectDrawImpl *)iface;
1061     TRACE("(%p)->(%s): No-op\n", This, debugstr_guid(Guid));
1062
1063     if(This->initialized)
1064     {
1065         return DDERR_ALREADYINITIALIZED;
1066     }
1067     else
1068     {
1069         return DD_OK;
1070     }
1071 }
1072
1073 /*****************************************************************************
1074  * IDirectDraw7::FlipToGDISurface
1075  *
1076  * "Makes the surface that the GDI writes to the primary surface"
1077  * Looks like some windows specific thing we don't have to care about.
1078  * According to MSDN it permits GDI dialog boxes in FULLSCREEN mode. Good to
1079  * show error boxes ;)
1080  * Well, just return DD_OK.
1081  *
1082  * Returns:
1083  *  Always returns DD_OK
1084  *
1085  *****************************************************************************/
1086 static HRESULT WINAPI
1087 IDirectDrawImpl_FlipToGDISurface(IDirectDraw7 *iface)
1088 {
1089     IDirectDrawImpl *This = (IDirectDrawImpl *)iface;
1090     TRACE("(%p)\n", This);
1091
1092     return DD_OK;
1093 }
1094
1095 /*****************************************************************************
1096  * IDirectDraw7::WaitForVerticalBlank
1097  *
1098  * This method allows applications to get in sync with the vertical blank
1099  * interval.
1100  * The wormhole demo in the DirectX 7 sdk uses this call, and it doesn't
1101  * redraw the screen, most likely because of this stub
1102  *
1103  * Parameters:
1104  *  Flags: one of DDWAITVB_BLOCKBEGIN, DDWAITVB_BLOCKBEGINEVENT
1105  *         or DDWAITVB_BLOCKEND
1106  *  h: Not used, according to MSDN
1107  *
1108  * Returns:
1109  *  Always returns DD_OK
1110  *
1111  *****************************************************************************/
1112 static HRESULT WINAPI
1113 IDirectDrawImpl_WaitForVerticalBlank(IDirectDraw7 *iface,
1114                                      DWORD Flags,
1115                                      HANDLE h)
1116 {
1117     IDirectDrawImpl *This = (IDirectDrawImpl *)iface;
1118     static BOOL hide = FALSE;
1119
1120     /* This function is called often, so print the fixme only once */
1121     if(!hide)
1122     {
1123         FIXME("(%p)->(%x,%p): Stub\n", This, Flags, h);
1124         hide = TRUE;
1125     }
1126
1127     /* MSDN says DDWAITVB_BLOCKBEGINEVENT is not supported */
1128     if(Flags & DDWAITVB_BLOCKBEGINEVENT)
1129         return DDERR_UNSUPPORTED; /* unchecked */
1130
1131     return DD_OK;
1132 }
1133
1134 /*****************************************************************************
1135  * IDirectDraw7::GetScanLine
1136  *
1137  * Returns the scan line that is being drawn on the monitor
1138  *
1139  * Parameters:
1140  *  Scanline: Address to write the scan line value to
1141  *
1142  * Returns:
1143  *  Always returns DD_OK
1144  *
1145  *****************************************************************************/
1146 static HRESULT WINAPI IDirectDrawImpl_GetScanLine(IDirectDraw7 *iface, DWORD *Scanline)
1147 {
1148     IDirectDrawImpl *This = (IDirectDrawImpl *)iface;
1149     static BOOL hide = FALSE;
1150     WINED3DDISPLAYMODE Mode;
1151
1152     /* This function is called often, so print the fixme only once */
1153     EnterCriticalSection(&ddraw_cs);
1154     if(!hide)
1155     {
1156         FIXME("(%p)->(%p): Semi-Stub\n", This, Scanline);
1157         hide = TRUE;
1158     }
1159
1160     IWineD3DDevice_GetDisplayMode(This->wineD3DDevice,
1161                                   0,
1162                                   &Mode);
1163
1164     /* Fake the line sweeping of the monitor */
1165     /* FIXME: We should synchronize with a source to keep the refresh rate */
1166     *Scanline = This->cur_scanline++;
1167     /* Assume 20 scan lines in the vertical blank */
1168     if (This->cur_scanline >= Mode.Height + 20)
1169         This->cur_scanline = 0;
1170
1171     LeaveCriticalSection(&ddraw_cs);
1172     return DD_OK;
1173 }
1174
1175 /*****************************************************************************
1176  * IDirectDraw7::TestCooperativeLevel
1177  *
1178  * Informs the application about the state of the video adapter, depending
1179  * on the cooperative level
1180  *
1181  * Returns:
1182  *  DD_OK if the device is in a sane state
1183  *  DDERR_NOEXCLUSIVEMODE or DDERR_EXCLUSIVEMODEALREADYSET
1184  *  if the state is not correct(See below)
1185  *
1186  *****************************************************************************/
1187 static HRESULT WINAPI
1188 IDirectDrawImpl_TestCooperativeLevel(IDirectDraw7 *iface)
1189 {
1190     IDirectDrawImpl *This = (IDirectDrawImpl *)iface;
1191     HRESULT hr;
1192     TRACE("(%p)\n", This);
1193
1194     EnterCriticalSection(&ddraw_cs);
1195     /* Description from MSDN:
1196      * For fullscreen apps return DDERR_NOEXCLUSIVEMODE if the user switched
1197      * away from the app with e.g. alt-tab. Windowed apps receive
1198      * DDERR_EXCLUSIVEMODEALREADYSET if another application created a
1199      * DirectDraw object in exclusive mode. DDERR_WRONGMODE is returned,
1200      * when the video mode has changed
1201      */
1202
1203     hr =  IWineD3DDevice_TestCooperativeLevel(This->wineD3DDevice);
1204
1205     /* Fix the result value. These values are mapped from their
1206      * d3d9 counterpart.
1207      */
1208     switch(hr)
1209     {
1210         case WINED3DERR_DEVICELOST:
1211             if(This->cooperative_level & DDSCL_EXCLUSIVE)
1212             {
1213                 LeaveCriticalSection(&ddraw_cs);
1214                 return DDERR_NOEXCLUSIVEMODE;
1215             }
1216             else
1217             {
1218                 LeaveCriticalSection(&ddraw_cs);
1219                 return DDERR_EXCLUSIVEMODEALREADYSET;
1220             }
1221
1222         case WINED3DERR_DEVICENOTRESET:
1223             LeaveCriticalSection(&ddraw_cs);
1224             return DD_OK;
1225
1226         case WINED3D_OK:
1227             LeaveCriticalSection(&ddraw_cs);
1228             return DD_OK;
1229
1230         case WINED3DERR_DRIVERINTERNALERROR:
1231         default:
1232             ERR("(%p) Unexpected return value %08x from wineD3D, "
1233                 " returning DD_OK\n", This, hr);
1234     }
1235
1236     LeaveCriticalSection(&ddraw_cs);
1237     return DD_OK;
1238 }
1239
1240 /*****************************************************************************
1241  * IDirectDraw7::GetGDISurface
1242  *
1243  * Returns the surface that GDI is treating as the primary surface.
1244  * For Wine this is the front buffer
1245  *
1246  * Params:
1247  *  GDISurface: Address to write the surface pointer to
1248  *
1249  * Returns:
1250  *  DD_OK if the surface was found
1251  *  DDERR_NOTFOUND if the GDI surface wasn't found
1252  *
1253  *****************************************************************************/
1254 static HRESULT WINAPI
1255 IDirectDrawImpl_GetGDISurface(IDirectDraw7 *iface,
1256                               IDirectDrawSurface7 **GDISurface)
1257 {
1258     IDirectDrawImpl *This = (IDirectDrawImpl *)iface;
1259     IWineD3DSurface *Surf;
1260     IDirectDrawSurface7 *ddsurf;
1261     HRESULT hr;
1262     DDSCAPS2 ddsCaps;
1263     TRACE("(%p)->(%p)\n", This, GDISurface);
1264
1265     /* Get the back buffer from the wineD3DDevice and search its
1266      * attached surfaces for the front buffer
1267      */
1268     EnterCriticalSection(&ddraw_cs);
1269     hr = IWineD3DDevice_GetBackBuffer(This->wineD3DDevice,
1270                                       0, /* SwapChain */
1271                                       0, /* first back buffer*/
1272                                       WINED3DBACKBUFFER_TYPE_MONO,
1273                                       &Surf);
1274
1275     if( (hr != D3D_OK) ||
1276         (!Surf) )
1277     {
1278         ERR("IWineD3DDevice::GetBackBuffer failed\n");
1279         LeaveCriticalSection(&ddraw_cs);
1280         return DDERR_NOTFOUND;
1281     }
1282
1283     /* GetBackBuffer AddRef()ed the surface, release it */
1284     IWineD3DSurface_Release(Surf);
1285
1286     IWineD3DSurface_GetParent(Surf,
1287                               (IUnknown **) &ddsurf);
1288     IDirectDrawSurface7_Release(ddsurf);  /* For the GetParent */
1289
1290     /* Find the front buffer */
1291     ddsCaps.dwCaps = DDSCAPS_FRONTBUFFER;
1292     hr = IDirectDrawSurface7_GetAttachedSurface(ddsurf,
1293                                                 &ddsCaps,
1294                                                 GDISurface);
1295     if(hr != DD_OK)
1296     {
1297         ERR("IDirectDrawSurface7::GetAttachedSurface failed, hr = %x\n", hr);
1298     }
1299
1300     /* The AddRef is OK this time */
1301     LeaveCriticalSection(&ddraw_cs);
1302     return hr;
1303 }
1304
1305 /*****************************************************************************
1306  * IDirectDraw7::EnumDisplayModes
1307  *
1308  * Enumerates the supported Display modes. The modes can be filtered with
1309  * the DDSD parameter.
1310  *
1311  * Params:
1312  *  Flags: can be DDEDM_REFRESHRATES and DDEDM_STANDARDVGAMODES
1313  *  DDSD: Surface description to filter the modes
1314  *  Context: Pointer passed back to the callback function
1315  *  cb: Application-provided callback function
1316  *
1317  * Returns:
1318  *  DD_OK on success
1319  *  DDERR_INVALIDPARAMS if the callback wasn't set
1320  *
1321  *****************************************************************************/
1322 static HRESULT WINAPI
1323 IDirectDrawImpl_EnumDisplayModes(IDirectDraw7 *iface,
1324                                  DWORD Flags,
1325                                  DDSURFACEDESC2 *DDSD,
1326                                  void *Context,
1327                                  LPDDENUMMODESCALLBACK2 cb)
1328 {
1329     IDirectDrawImpl *This = (IDirectDrawImpl *)iface;
1330     unsigned int modenum, fmt;
1331     WINED3DFORMAT pixelformat = WINED3DFMT_UNKNOWN;
1332     WINED3DDISPLAYMODE mode;
1333     DDSURFACEDESC2 callback_sd;
1334     WINED3DDISPLAYMODE *enum_modes = NULL;
1335     unsigned enum_mode_count = 0, enum_mode_array_size = 0;
1336
1337     WINED3DFORMAT checkFormatList[] =
1338     {
1339         WINED3DFMT_B8G8R8_UNORM,
1340         WINED3DFMT_B8G8R8A8_UNORM,
1341         WINED3DFMT_B8G8R8X8_UNORM,
1342         WINED3DFMT_B5G6R5_UNORM,
1343         WINED3DFMT_B5G5R5X1_UNORM,
1344         WINED3DFMT_B5G5R5A1_UNORM,
1345         WINED3DFMT_B4G4R4A4_UNORM,
1346         WINED3DFMT_B2G3R3_UNORM,
1347         WINED3DFMT_B2G3R3A8_UNORM,
1348         WINED3DFMT_B4G4R4X4_UNORM,
1349         WINED3DFMT_R10G10B10A2_UNORM,
1350         WINED3DFMT_R8G8B8A8_UNORM,
1351         WINED3DFMT_R8G8B8X8_UNORM,
1352         WINED3DFMT_B10G10R10A2_UNORM,
1353         WINED3DFMT_P8_UINT_A8_UNORM,
1354         WINED3DFMT_P8_UINT,
1355     };
1356
1357     TRACE("(%p)->(%p,%p,%p): Relay\n", This, DDSD, Context, cb);
1358
1359     EnterCriticalSection(&ddraw_cs);
1360     /* This looks sane */
1361     if(!cb)
1362     {
1363         LeaveCriticalSection(&ddraw_cs);
1364         return DDERR_INVALIDPARAMS;
1365     }
1366
1367     if(DDSD)
1368     {
1369         if ((DDSD->dwFlags & DDSD_PIXELFORMAT) && (DDSD->u4.ddpfPixelFormat.dwFlags & DDPF_RGB) )
1370             pixelformat = PixelFormat_DD2WineD3D(&DDSD->u4.ddpfPixelFormat);
1371     }
1372
1373     if(!(Flags & DDEDM_REFRESHRATES))
1374     {
1375         enum_mode_array_size = 16;
1376         enum_modes = HeapAlloc(GetProcessHeap(), 0, sizeof(WINED3DDISPLAYMODE) * enum_mode_array_size);
1377         if (!enum_modes)
1378         {
1379             ERR("Out of memory\n");
1380             LeaveCriticalSection(&ddraw_cs);
1381             return DDERR_OUTOFMEMORY;
1382         }
1383     }
1384
1385     for(fmt = 0; fmt < (sizeof(checkFormatList) / sizeof(checkFormatList[0])); fmt++)
1386     {
1387         if(pixelformat != WINED3DFMT_UNKNOWN && checkFormatList[fmt] != pixelformat)
1388         {
1389             continue;
1390         }
1391
1392         modenum = 0;
1393         while(IWineD3D_EnumAdapterModes(This->wineD3D,
1394                                         WINED3DADAPTER_DEFAULT,
1395                                         checkFormatList[fmt],
1396                                         modenum++,
1397                                         &mode) == WINED3D_OK)
1398         {
1399             if(DDSD)
1400             {
1401                 if(DDSD->dwFlags & DDSD_WIDTH && mode.Width != DDSD->dwWidth) continue;
1402                 if(DDSD->dwFlags & DDSD_HEIGHT && mode.Height != DDSD->dwHeight) continue;
1403             }
1404
1405             if(!(Flags & DDEDM_REFRESHRATES))
1406             {
1407                 /* DX docs state EnumDisplayMode should return only unique modes. If DDEDM_REFRESHRATES is not set, refresh
1408                  * rate doesn't matter when determining if the mode is unique. So modes only differing in refresh rate have
1409                  * to be reduced to a single unique result in such case.
1410                  */
1411                 BOOL found = FALSE;
1412                 unsigned i;
1413
1414                 for (i = 0; i < enum_mode_count; i++)
1415                 {
1416                     if(enum_modes[i].Width == mode.Width && enum_modes[i].Height == mode.Height &&
1417                        enum_modes[i].Format == mode.Format)
1418                     {
1419                         found = TRUE;
1420                         break;
1421                     }
1422                 }
1423
1424                 if(found) continue;
1425             }
1426
1427             memset(&callback_sd, 0, sizeof(callback_sd));
1428             callback_sd.dwSize = sizeof(callback_sd);
1429             callback_sd.u4.ddpfPixelFormat.dwSize = sizeof(DDPIXELFORMAT);
1430
1431             callback_sd.dwFlags = DDSD_HEIGHT|DDSD_WIDTH|DDSD_PIXELFORMAT|DDSD_PITCH;
1432             if(Flags & DDEDM_REFRESHRATES)
1433             {
1434                 callback_sd.dwFlags |= DDSD_REFRESHRATE;
1435                 callback_sd.u2.dwRefreshRate = mode.RefreshRate;
1436             }
1437
1438             callback_sd.dwWidth = mode.Width;
1439             callback_sd.dwHeight = mode.Height;
1440
1441             PixelFormat_WineD3DtoDD(&callback_sd.u4.ddpfPixelFormat, mode.Format);
1442
1443             /* Calc pitch and DWORD align like MSDN says */
1444             callback_sd.u1.lPitch = (callback_sd.u4.ddpfPixelFormat.u1.dwRGBBitCount / 8) * mode.Width;
1445             callback_sd.u1.lPitch = (callback_sd.u1.lPitch + 3) & ~3;
1446
1447             TRACE("Enumerating %dx%dx%d @%d\n", callback_sd.dwWidth, callback_sd.dwHeight, callback_sd.u4.ddpfPixelFormat.u1.dwRGBBitCount,
1448               callback_sd.u2.dwRefreshRate);
1449
1450             if(cb(&callback_sd, Context) == DDENUMRET_CANCEL)
1451             {
1452                 TRACE("Application asked to terminate the enumeration\n");
1453                 HeapFree(GetProcessHeap(), 0, enum_modes);
1454                 LeaveCriticalSection(&ddraw_cs);
1455                 return DD_OK;
1456             }
1457
1458             if(!(Flags & DDEDM_REFRESHRATES))
1459             {
1460                 if (enum_mode_count == enum_mode_array_size)
1461                 {
1462                     WINED3DDISPLAYMODE *new_enum_modes;
1463
1464                     enum_mode_array_size *= 2;
1465                     new_enum_modes = HeapReAlloc(GetProcessHeap(), 0, enum_modes, sizeof(WINED3DDISPLAYMODE) * enum_mode_array_size);
1466
1467                     if (!new_enum_modes)
1468                     {
1469                         ERR("Out of memory\n");
1470                         HeapFree(GetProcessHeap(), 0, enum_modes);
1471                         LeaveCriticalSection(&ddraw_cs);
1472                         return DDERR_OUTOFMEMORY;
1473                     }
1474
1475                     enum_modes = new_enum_modes;
1476                 }
1477
1478                 enum_modes[enum_mode_count++] = mode;
1479             }
1480         }
1481     }
1482
1483     TRACE("End of enumeration\n");
1484     HeapFree(GetProcessHeap(), 0, enum_modes);
1485     LeaveCriticalSection(&ddraw_cs);
1486     return DD_OK;
1487 }
1488
1489 /*****************************************************************************
1490  * IDirectDraw7::EvaluateMode
1491  *
1492  * Used with IDirectDraw7::StartModeTest to test video modes.
1493  * EvaluateMode is used to pass or fail a mode, and continue with the next
1494  * mode
1495  *
1496  * Params:
1497  *  Flags: DDEM_MODEPASSED or DDEM_MODEFAILED
1498  *  Timeout: Returns the amount of seconds left before the mode would have
1499  *           been failed automatically
1500  *
1501  * Returns:
1502  *  This implementation always DD_OK, because it's a stub
1503  *
1504  *****************************************************************************/
1505 static HRESULT WINAPI
1506 IDirectDrawImpl_EvaluateMode(IDirectDraw7 *iface,
1507                              DWORD Flags,
1508                              DWORD *Timeout)
1509 {
1510     IDirectDrawImpl *This = (IDirectDrawImpl *)iface;
1511     FIXME("(%p)->(%d,%p): Stub!\n", This, Flags, Timeout);
1512
1513     /* When implementing this, implement it in WineD3D */
1514
1515     return DD_OK;
1516 }
1517
1518 /*****************************************************************************
1519  * IDirectDraw7::GetDeviceIdentifier
1520  *
1521  * Returns the device identifier, which gives information about the driver
1522  * Our device identifier is defined at the beginning of this file.
1523  *
1524  * Params:
1525  *  DDDI: Address for the returned structure
1526  *  Flags: Can be DDGDI_GETHOSTIDENTIFIER
1527  *
1528  * Returns:
1529  *  On success it returns DD_OK
1530  *  DDERR_INVALIDPARAMS if DDDI is NULL
1531  *
1532  *****************************************************************************/
1533 static HRESULT WINAPI
1534 IDirectDrawImpl_GetDeviceIdentifier(IDirectDraw7 *iface,
1535                                     DDDEVICEIDENTIFIER2 *DDDI,
1536                                     DWORD Flags)
1537 {
1538     IDirectDrawImpl *This = (IDirectDrawImpl *)iface;
1539     TRACE("(%p)->(%p,%08x)\n", This, DDDI, Flags);
1540
1541     if(!DDDI)
1542         return DDERR_INVALIDPARAMS;
1543
1544     /* The DDGDI_GETHOSTIDENTIFIER returns the information about the 2D
1545      * host adapter, if there's a secondary 3D adapter. This doesn't apply
1546      * to any modern hardware, nor is it interesting for Wine, so ignore it
1547      */
1548
1549     *DDDI = deviceidentifier;
1550     return DD_OK;
1551 }
1552
1553 /*****************************************************************************
1554  * IDirectDraw7::GetSurfaceFromDC
1555  *
1556  * Returns the Surface for a GDI device context handle.
1557  * Is this related to IDirectDrawSurface::GetDC ???
1558  *
1559  * Params:
1560  *  hdc: hdc to return the surface for
1561  *  Surface: Address to write the surface pointer to
1562  *
1563  * Returns:
1564  *  Always returns DD_OK because it's a stub
1565  *
1566  *****************************************************************************/
1567 static HRESULT WINAPI
1568 IDirectDrawImpl_GetSurfaceFromDC(IDirectDraw7 *iface,
1569                                  HDC hdc,
1570                                  IDirectDrawSurface7 **Surface)
1571 {
1572     IDirectDrawImpl *This = (IDirectDrawImpl *)iface;
1573     FIXME("(%p)->(%p,%p): Stub!\n", This, hdc, Surface);
1574
1575     /* Implementation idea if needed: Loop through all surfaces and compare
1576      * their hdc with hdc. Implement it in WineD3D! */
1577     return DDERR_NOTFOUND;
1578 }
1579
1580 /*****************************************************************************
1581  * IDirectDraw7::RestoreAllSurfaces
1582  *
1583  * Calls the restore method of all surfaces
1584  *
1585  * Params:
1586  *
1587  * Returns:
1588  *  Always returns DD_OK because it's a stub
1589  *
1590  *****************************************************************************/
1591 static HRESULT WINAPI
1592 IDirectDrawImpl_RestoreAllSurfaces(IDirectDraw7 *iface)
1593 {
1594     IDirectDrawImpl *This = (IDirectDrawImpl *)iface;
1595     FIXME("(%p): Stub\n", This);
1596
1597     /* This isn't hard to implement: Enumerate all WineD3D surfaces,
1598      * get their parent and call their restore method. Do not implement
1599      * it in WineD3D, as restoring a surface means re-creating the
1600      * WineD3DDSurface
1601      */
1602     return DD_OK;
1603 }
1604
1605 /*****************************************************************************
1606  * IDirectDraw7::StartModeTest
1607  *
1608  * Tests the specified video modes to update the system registry with
1609  * refresh rate information. StartModeTest starts the mode test,
1610  * EvaluateMode is used to fail or pass a mode. If EvaluateMode
1611  * isn't called within 15 seconds, the mode is failed automatically
1612  *
1613  * As refresh rates are handled by the X server, I don't think this
1614  * Method is important
1615  *
1616  * Params:
1617  *  Modes: An array of mode specifications
1618  *  NumModes: The number of modes in Modes
1619  *  Flags: Some flags...
1620  *
1621  * Returns:
1622  *  Returns DDERR_TESTFINISHED if flags contains DDSMT_ISTESTREQUIRED,
1623  *  if no modes are passed, DDERR_INVALIDPARAMS is returned,
1624  *  otherwise DD_OK
1625  *
1626  *****************************************************************************/
1627 static HRESULT WINAPI
1628 IDirectDrawImpl_StartModeTest(IDirectDraw7 *iface,
1629                               SIZE *Modes,
1630                               DWORD NumModes,
1631                               DWORD Flags)
1632 {
1633     IDirectDrawImpl *This = (IDirectDrawImpl *)iface;
1634     WARN("(%p)->(%p, %d, %x): Semi-Stub, most likely harmless\n", This, Modes, NumModes, Flags);
1635
1636     /* This looks sane */
1637     if( (!Modes) || (NumModes == 0) ) return DDERR_INVALIDPARAMS;
1638
1639     /* DDSMT_ISTESTREQUIRED asks if a mode test is necessary.
1640      * As it is not, DDERR_TESTFINISHED is returned
1641      * (hopefully that's correct
1642      *
1643     if(Flags & DDSMT_ISTESTREQUIRED) return DDERR_TESTFINISHED;
1644      * well, that value doesn't (yet) exist in the wine headers, so ignore it
1645      */
1646
1647     return DD_OK;
1648 }
1649
1650 /*****************************************************************************
1651  * IDirectDrawImpl_RecreateSurfacesCallback
1652  *
1653  * Enumeration callback for IDirectDrawImpl_RecreateAllSurfaces.
1654  * It re-recreates the WineD3DSurface. It's pretty straightforward
1655  *
1656  *****************************************************************************/
1657 HRESULT WINAPI
1658 IDirectDrawImpl_RecreateSurfacesCallback(IDirectDrawSurface7 *surf,
1659                                          DDSURFACEDESC2 *desc,
1660                                          void *Context)
1661 {
1662     IDirectDrawSurfaceImpl *surfImpl = (IDirectDrawSurfaceImpl *)surf;
1663     IDirectDrawImpl *This = surfImpl->ddraw;
1664     IUnknown *Parent;
1665     IWineD3DSurface *wineD3DSurface;
1666     IWineD3DSwapChain *swapchain;
1667     HRESULT hr;
1668     IWineD3DClipper *clipper = NULL;
1669
1670     WINED3DSURFACE_DESC     Desc;
1671     WINED3DFORMAT           Format;
1672     DWORD                   Usage;
1673     WINED3DPOOL             Pool;
1674
1675     WINED3DMULTISAMPLE_TYPE MultiSampleType;
1676     DWORD                   MultiSampleQuality;
1677     UINT                    Width;
1678     UINT                    Height;
1679
1680     TRACE("(%p): Enumerated Surface %p\n", This, surfImpl);
1681
1682     /* For the enumeration */
1683     IDirectDrawSurface7_Release(surf);
1684
1685     if(surfImpl->ImplType == This->ImplType) return DDENUMRET_OK; /* Continue */
1686
1687     /* Get the objects */
1688     swapchain = surfImpl->wineD3DSwapChain;
1689     surfImpl->wineD3DSwapChain = NULL;
1690     wineD3DSurface = surfImpl->WineD3DSurface;
1691
1692     /* get the clipper */
1693     IWineD3DSurface_GetClipper(wineD3DSurface, &clipper);
1694
1695     /* Get the surface properties */
1696     hr = IWineD3DSurface_GetDesc(wineD3DSurface, &Desc);
1697     if(hr != D3D_OK) return hr;
1698
1699     Format = Desc.format;
1700     Usage = Desc.usage;
1701     Pool = Desc.pool;
1702     MultiSampleType = Desc.multisample_type;
1703     MultiSampleQuality = Desc.multisample_quality;
1704     Width = Desc.width;
1705     Height = Desc.height;
1706
1707     IWineD3DSurface_GetParent(wineD3DSurface, &Parent);
1708
1709     /* Create the new surface */
1710     hr = IWineD3DDevice_CreateSurface(This->wineD3DDevice, Width, Height, Format,
1711             TRUE /* Lockable */, FALSE /* Discard */, surfImpl->mipmap_level, &surfImpl->WineD3DSurface, Usage, Pool,
1712             MultiSampleType, MultiSampleQuality, This->ImplType, Parent, &ddraw_null_wined3d_parent_ops);
1713     IUnknown_Release(Parent);
1714
1715     if(hr != D3D_OK)
1716         return hr;
1717
1718     IWineD3DSurface_SetClipper(surfImpl->WineD3DSurface, clipper);
1719
1720     /* TODO: Copy the surface content, except for render targets */
1721
1722     /* If there's a swapchain, it owns the wined3d surfaces. So Destroy
1723      * the swapchain
1724      */
1725     if(swapchain) {
1726         /* The backbuffers have the swapchain set as well, but the primary
1727          * owns it and destroys it
1728          */
1729         if(surfImpl->surface_desc.ddsCaps.dwCaps & DDSCAPS_PRIMARYSURFACE) {
1730             IWineD3DDevice_UninitGDI(This->wineD3DDevice, D3D7CB_DestroySwapChain);
1731         }
1732         surfImpl->isRenderTarget = FALSE;
1733     } else {
1734         if(IWineD3DSurface_Release(wineD3DSurface) == 0)
1735             TRACE("Surface released successful, next surface\n");
1736         else
1737             ERR("Something's still holding the old WineD3DSurface\n");
1738     }
1739
1740     surfImpl->ImplType = This->ImplType;
1741
1742     if(clipper)
1743     {
1744         IWineD3DClipper_Release(clipper);
1745     }
1746     return DDENUMRET_OK;
1747 }
1748
1749 /*****************************************************************************
1750  * IDirectDrawImpl_RecreateAllSurfaces
1751  *
1752  * A function, that converts all wineD3DSurfaces to the new implementation type
1753  * It enumerates all surfaces with IWineD3DDevice::EnumSurfaces, creates a
1754  * new WineD3DSurface, copies the content and releases the old surface
1755  *
1756  *****************************************************************************/
1757 static HRESULT
1758 IDirectDrawImpl_RecreateAllSurfaces(IDirectDrawImpl *This)
1759 {
1760     DDSURFACEDESC2 desc;
1761     TRACE("(%p): Switch to implementation %d\n", This, This->ImplType);
1762
1763     if(This->ImplType != SURFACE_OPENGL && This->d3d_initialized)
1764     {
1765         /* Should happen almost never */
1766         FIXME("(%p) Switching to non-opengl surfaces with d3d started. Is this a bug?\n", This);
1767         /* Shutdown d3d */
1768         IWineD3DDevice_Uninit3D(This->wineD3DDevice, D3D7CB_DestroySwapChain);
1769     }
1770     /* Contrary: D3D starting is handled by the caller, because it knows the render target */
1771
1772     memset(&desc, 0, sizeof(desc));
1773     desc.dwSize = sizeof(desc);
1774
1775     return IDirectDraw7_EnumSurfaces((IDirectDraw7 *)This, 0, &desc, This, IDirectDrawImpl_RecreateSurfacesCallback);
1776 }
1777
1778 ULONG WINAPI D3D7CB_DestroySwapChain(IWineD3DSwapChain *pSwapChain) {
1779     IUnknown* swapChainParent;
1780     TRACE("(%p) call back\n", pSwapChain);
1781
1782     IWineD3DSwapChain_GetParent(pSwapChain, &swapChainParent);
1783     IUnknown_Release(swapChainParent);
1784     return IUnknown_Release(swapChainParent);
1785 }
1786
1787 /*****************************************************************************
1788  * IDirectDrawImpl_CreateNewSurface
1789  *
1790  * A helper function for IDirectDraw7::CreateSurface. It creates a new surface
1791  * with the passed parameters.
1792  *
1793  * Params:
1794  *  DDSD: Description of the surface to create
1795  *  Surf: Address to store the interface pointer at
1796  *
1797  * Returns:
1798  *  DD_OK on success
1799  *
1800  *****************************************************************************/
1801 static HRESULT
1802 IDirectDrawImpl_CreateNewSurface(IDirectDrawImpl *This,
1803                                  DDSURFACEDESC2 *pDDSD,
1804                                  IDirectDrawSurfaceImpl **ppSurf,
1805                                  UINT level)
1806 {
1807     HRESULT hr;
1808     UINT Width, Height;
1809     WINED3DFORMAT Format = WINED3DFMT_UNKNOWN;
1810     DWORD Usage = 0;
1811     WINED3DSURFTYPE ImplType = This->ImplType;
1812     WINED3DSURFACE_DESC Desc;
1813     WINED3DPOOL Pool = WINED3DPOOL_DEFAULT;
1814
1815     if (TRACE_ON(ddraw))
1816     {
1817         TRACE(" (%p) Requesting surface desc :\n", This);
1818         DDRAW_dump_surface_desc(pDDSD);
1819     }
1820
1821     /* Select the surface type, if it wasn't choosen yet */
1822     if(ImplType == SURFACE_UNKNOWN)
1823     {
1824         /* Use GL Surfaces if a D3DDEVICE Surface is requested */
1825         if(pDDSD->ddsCaps.dwCaps & DDSCAPS_3DDEVICE)
1826         {
1827             TRACE("(%p) Choosing GL surfaces because a 3DDEVICE Surface was requested\n", This);
1828             ImplType = SURFACE_OPENGL;
1829         }
1830
1831         /* Otherwise use GDI surfaces for now */
1832         else
1833         {
1834             TRACE("(%p) Choosing GDI surfaces for 2D rendering\n", This);
1835             ImplType = SURFACE_GDI;
1836         }
1837
1838         /* Policy if all surface implementations are available:
1839          * First, check if a default type was set with winecfg. If not,
1840          * try Xrender surfaces, and use them if they work. Next, check if
1841          * accelerated OpenGL is available, and use GL surfaces in this
1842          * case. If all else fails, use GDI surfaces. If a 3DDEVICE surface
1843          * was created, always use OpenGL surfaces.
1844          *
1845          * (Note: Xrender surfaces are not implemented for now, the
1846          * unaccelerated implementation uses GDI to render in Software)
1847          */
1848
1849         /* Store the type. If it needs to be changed, all WineD3DSurfaces have to
1850          * be re-created. This could be done with IDirectDrawSurface7::Restore
1851          */
1852         This->ImplType = ImplType;
1853     }
1854     else
1855     {
1856         if ((pDDSD->ddsCaps.dwCaps & DDSCAPS_3DDEVICE)
1857                 && (This->ImplType != SURFACE_OPENGL)
1858                 && DefaultSurfaceType == SURFACE_UNKNOWN)
1859         {
1860             /* We have to change to OpenGL,
1861              * and re-create all WineD3DSurfaces
1862              */
1863             ImplType = SURFACE_OPENGL;
1864             This->ImplType = ImplType;
1865             TRACE("(%p) Re-creating all surfaces\n", This);
1866             IDirectDrawImpl_RecreateAllSurfaces(This);
1867             TRACE("(%p) Done recreating all surfaces\n", This);
1868         }
1869         else if(This->ImplType != SURFACE_OPENGL && pDDSD->ddsCaps.dwCaps & DDSCAPS_3DDEVICE)
1870         {
1871             WARN("The application requests a 3D capable surface, but a non-opengl surface was set in the registry\n");
1872             /* Do not fail surface creation, only fail 3D device creation */
1873         }
1874     }
1875
1876     if (!(pDDSD->ddsCaps.dwCaps & (DDSCAPS_VIDEOMEMORY | DDSCAPS_SYSTEMMEMORY)) &&
1877         !((pDDSD->ddsCaps.dwCaps & DDSCAPS_TEXTURE) && (pDDSD->ddsCaps.dwCaps2 & DDSCAPS2_TEXTUREMANAGE)) )
1878     {
1879         /* Tests show surfaces without memory flags get these flags added right after creation. */
1880         pDDSD->ddsCaps.dwCaps |= DDSCAPS_LOCALVIDMEM | DDSCAPS_VIDEOMEMORY;
1881     }
1882     /* Get the correct wined3d usage */
1883     if (pDDSD->ddsCaps.dwCaps & (DDSCAPS_PRIMARYSURFACE |
1884                                  DDSCAPS_3DDEVICE       ) )
1885     {
1886         Usage |= WINED3DUSAGE_RENDERTARGET;
1887
1888         pDDSD->ddsCaps.dwCaps |= DDSCAPS_VISIBLE;
1889     }
1890     if (pDDSD->ddsCaps.dwCaps & (DDSCAPS_OVERLAY))
1891     {
1892         Usage |= WINED3DUSAGE_OVERLAY;
1893     }
1894     if(This->depthstencil || (pDDSD->ddsCaps.dwCaps & DDSCAPS_ZBUFFER) )
1895     {
1896         /* The depth stencil creation callback sets this flag.
1897          * Set the WineD3D usage to let it know that it's a depth
1898          * Stencil surface.
1899          */
1900         Usage |= WINED3DUSAGE_DEPTHSTENCIL;
1901     }
1902     if(pDDSD->ddsCaps.dwCaps & DDSCAPS_SYSTEMMEMORY)
1903     {
1904         Pool = WINED3DPOOL_SYSTEMMEM;
1905     }
1906     else if(pDDSD->ddsCaps.dwCaps2 & DDSCAPS2_TEXTUREMANAGE)
1907     {
1908         Pool = WINED3DPOOL_MANAGED;
1909         /* Managed textures have the system memory flag set */
1910         pDDSD->ddsCaps.dwCaps |= DDSCAPS_SYSTEMMEMORY;
1911     }
1912     else if(pDDSD->ddsCaps.dwCaps & DDSCAPS_VIDEOMEMORY)
1913     {
1914         /* Videomemory adds localvidmem, this is mutually exclusive with systemmemory
1915          * and texturemanage
1916          */
1917         pDDSD->ddsCaps.dwCaps |= DDSCAPS_LOCALVIDMEM;
1918     }
1919
1920     Format = PixelFormat_DD2WineD3D(&pDDSD->u4.ddpfPixelFormat);
1921     if(Format == WINED3DFMT_UNKNOWN)
1922     {
1923         ERR("Unsupported / Unknown pixelformat\n");
1924         return DDERR_INVALIDPIXELFORMAT;
1925     }
1926
1927     /* Create the Surface object */
1928     *ppSurf = HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, sizeof(IDirectDrawSurfaceImpl));
1929     if(!*ppSurf)
1930     {
1931         ERR("(%p) Error allocating memory for a surface\n", This);
1932         return DDERR_OUTOFVIDEOMEMORY;
1933     }
1934     (*ppSurf)->lpVtbl = &IDirectDrawSurface7_Vtbl;
1935     (*ppSurf)->IDirectDrawSurface3_vtbl = &IDirectDrawSurface3_Vtbl;
1936     (*ppSurf)->IDirectDrawGammaControl_vtbl = &IDirectDrawGammaControl_Vtbl;
1937     (*ppSurf)->IDirect3DTexture2_vtbl = &IDirect3DTexture2_Vtbl;
1938     (*ppSurf)->IDirect3DTexture_vtbl = &IDirect3DTexture1_Vtbl;
1939     (*ppSurf)->ref = 1;
1940     (*ppSurf)->version = 7;
1941     TRACE("%p->version = %d\n", (*ppSurf), (*ppSurf)->version);
1942     (*ppSurf)->ddraw = This;
1943     (*ppSurf)->surface_desc.dwSize = sizeof(DDSURFACEDESC2);
1944     (*ppSurf)->surface_desc.u4.ddpfPixelFormat.dwSize = sizeof(DDPIXELFORMAT);
1945     DD_STRUCT_COPY_BYSIZE(&(*ppSurf)->surface_desc, pDDSD);
1946
1947     /* Surface attachments */
1948     (*ppSurf)->next_attached = NULL;
1949     (*ppSurf)->first_attached = *ppSurf;
1950
1951     /* Needed to re-create the surface on an implementation change */
1952     (*ppSurf)->ImplType = ImplType;
1953
1954     /* For D3DDevice creation */
1955     (*ppSurf)->isRenderTarget = FALSE;
1956
1957     /* A trace message for debugging */
1958     TRACE("(%p) Created IDirectDrawSurface implementation structure at %p\n", This, *ppSurf);
1959
1960     /* Now create the WineD3D Surface */
1961     hr = IWineD3DDevice_CreateSurface(This->wineD3DDevice, pDDSD->dwWidth, pDDSD->dwHeight, Format,
1962             TRUE /* Lockable */, FALSE /* Discard */, level, &(*ppSurf)->WineD3DSurface,
1963             Usage, Pool, WINED3DMULTISAMPLE_NONE, 0 /* MultiSampleQuality */, ImplType,
1964             (IUnknown *)*ppSurf, &ddraw_null_wined3d_parent_ops);
1965
1966     if(hr != D3D_OK)
1967     {
1968         ERR("IWineD3DDevice::CreateSurface failed. hr = %08x\n", hr);
1969         return hr;
1970     }
1971
1972     /* Increase the surface counter, and attach the surface */
1973     InterlockedIncrement(&This->surfaces);
1974     list_add_head(&This->surface_list, &(*ppSurf)->surface_list_entry);
1975
1976     /* Here we could store all created surfaces in the DirectDrawImpl structure,
1977      * But this could also be delegated to WineDDraw, as it keeps track of all its
1978      * resources. Not implemented for now, as there are more important things ;)
1979      */
1980
1981     /* Get the pixel format of the WineD3DSurface and store it.
1982      * Don't use the Format choosen above, WineD3D might have
1983      * changed it
1984      */
1985     (*ppSurf)->surface_desc.dwFlags |= DDSD_PIXELFORMAT;
1986     hr = IWineD3DSurface_GetDesc((*ppSurf)->WineD3DSurface, &Desc);
1987     if(hr != D3D_OK)
1988     {
1989         ERR("IWineD3DSurface::GetDesc failed\n");
1990         IDirectDrawSurface7_Release( (IDirectDrawSurface7 *) *ppSurf);
1991         return hr;
1992     }
1993
1994     Format = Desc.format;
1995     Width = Desc.width;
1996     Height = Desc.height;
1997
1998     if(Format == WINED3DFMT_UNKNOWN)
1999     {
2000         FIXME("IWineD3DSurface::GetDesc returned WINED3DFMT_UNKNOWN\n");
2001     }
2002     PixelFormat_WineD3DtoDD( &(*ppSurf)->surface_desc.u4.ddpfPixelFormat, Format);
2003
2004     /* Anno 1602 stores the pitch right after surface creation, so make sure it's there.
2005      * I can't LockRect() the surface here because if OpenGL surfaces are in use, the
2006      * WineD3DDevice might not be usable for 3D yet, so an extra method was created.
2007      * TODO: Test other fourcc formats
2008      */
2009     if(Format == WINED3DFMT_DXT1 || Format == WINED3DFMT_DXT2 || Format == WINED3DFMT_DXT3 ||
2010        Format == WINED3DFMT_DXT4 || Format == WINED3DFMT_DXT5)
2011     {
2012         (*ppSurf)->surface_desc.dwFlags |= DDSD_LINEARSIZE;
2013         if(Format == WINED3DFMT_DXT1)
2014         {
2015             (*ppSurf)->surface_desc.u1.dwLinearSize = max(4, Width) * max(4, Height) / 2;
2016         }
2017         else
2018         {
2019             (*ppSurf)->surface_desc.u1.dwLinearSize = max(4, Width) * max(4, Height);
2020         }
2021     }
2022     else
2023     {
2024         (*ppSurf)->surface_desc.dwFlags |= DDSD_PITCH;
2025         (*ppSurf)->surface_desc.u1.lPitch = IWineD3DSurface_GetPitch((*ppSurf)->WineD3DSurface);
2026     }
2027
2028     /* Application passed a color key? Set it! */
2029     if(pDDSD->dwFlags & DDSD_CKDESTOVERLAY)
2030     {
2031         IWineD3DSurface_SetColorKey((*ppSurf)->WineD3DSurface,
2032                                     DDCKEY_DESTOVERLAY,
2033                                     (WINEDDCOLORKEY *) &pDDSD->u3.ddckCKDestOverlay);
2034     }
2035     if(pDDSD->dwFlags & DDSD_CKDESTBLT)
2036     {
2037         IWineD3DSurface_SetColorKey((*ppSurf)->WineD3DSurface,
2038                                     DDCKEY_DESTBLT,
2039                                     (WINEDDCOLORKEY *) &pDDSD->ddckCKDestBlt);
2040     }
2041     if(pDDSD->dwFlags & DDSD_CKSRCOVERLAY)
2042     {
2043         IWineD3DSurface_SetColorKey((*ppSurf)->WineD3DSurface,
2044                                     DDCKEY_SRCOVERLAY,
2045                                     (WINEDDCOLORKEY *) &pDDSD->ddckCKSrcOverlay);
2046     }
2047     if(pDDSD->dwFlags & DDSD_CKSRCBLT)
2048     {
2049         IWineD3DSurface_SetColorKey((*ppSurf)->WineD3DSurface,
2050                                     DDCKEY_SRCBLT,
2051                                     (WINEDDCOLORKEY *) &pDDSD->ddckCKSrcBlt);
2052     }
2053     if ( pDDSD->dwFlags & DDSD_LPSURFACE)
2054     {
2055         hr = IWineD3DSurface_SetMem((*ppSurf)->WineD3DSurface, pDDSD->lpSurface);
2056         if(hr != WINED3D_OK)
2057         {
2058             /* No need for a trace here, wined3d does that for us */
2059             IDirectDrawSurface7_Release((IDirectDrawSurface7 *)*ppSurf);
2060             return hr;
2061         }
2062     }
2063
2064     return DD_OK;
2065 }
2066 /*****************************************************************************
2067  * CreateAdditionalSurfaces
2068  *
2069  * Creates a new mipmap chain.
2070  *
2071  * Params:
2072  *  root: Root surface to attach the newly created chain to
2073  *  count: number of surfaces to create
2074  *  DDSD: Description of the surface. Intentionally not a pointer to avoid side
2075  *        effects on the caller
2076  *  CubeFaceRoot: Whether the new surface is a root of a cube map face. This
2077  *                creates an additional surface without the mipmapping flags
2078  *
2079  *****************************************************************************/
2080 static HRESULT
2081 CreateAdditionalSurfaces(IDirectDrawImpl *This,
2082                          IDirectDrawSurfaceImpl *root,
2083                          UINT count,
2084                          DDSURFACEDESC2 DDSD,
2085                          BOOL CubeFaceRoot)
2086 {
2087     UINT i, j, level = 0;
2088     HRESULT hr;
2089     IDirectDrawSurfaceImpl *last = root;
2090
2091     for(i = 0; i < count; i++)
2092     {
2093         IDirectDrawSurfaceImpl *object2 = NULL;
2094
2095         /* increase the mipmap level, but only if a mipmap is created
2096          * In this case, also halve the size
2097          */
2098         if(DDSD.ddsCaps.dwCaps & DDSCAPS_MIPMAP && !CubeFaceRoot)
2099         {
2100             level++;
2101             if(DDSD.dwWidth > 1) DDSD.dwWidth /= 2;
2102             if(DDSD.dwHeight > 1) DDSD.dwHeight /= 2;
2103             /* Set the mipmap sublevel flag according to msdn */
2104             DDSD.ddsCaps.dwCaps2 |= DDSCAPS2_MIPMAPSUBLEVEL;
2105         }
2106         else
2107         {
2108             DDSD.ddsCaps.dwCaps2 &= ~DDSCAPS2_MIPMAPSUBLEVEL;
2109         }
2110         CubeFaceRoot = FALSE;
2111
2112         hr = IDirectDrawImpl_CreateNewSurface(This,
2113                                               &DDSD,
2114                                               &object2,
2115                                               level);
2116         if(hr != DD_OK)
2117         {
2118             return hr;
2119         }
2120
2121         /* Add the new surface to the complex attachment array */
2122         for(j = 0; j < MAX_COMPLEX_ATTACHED; j++)
2123         {
2124             if(last->complex_array[j]) continue;
2125             last->complex_array[j] = object2;
2126             break;
2127         }
2128         last = object2;
2129
2130         /* Remove the (possible) back buffer cap from the new surface description,
2131          * because only one surface in the flipping chain is a back buffer, one
2132          * is a front buffer, the others are just primary surfaces.
2133          */
2134         DDSD.ddsCaps.dwCaps &= ~DDSCAPS_BACKBUFFER;
2135     }
2136     return DD_OK;
2137 }
2138
2139 /*****************************************************************************
2140  * IDirectDraw7::CreateSurface
2141  *
2142  * Creates a new IDirectDrawSurface object and returns its interface.
2143  *
2144  * The surface connections with wined3d are a bit tricky. Basically it works
2145  * like this:
2146  *
2147  * |------------------------|               |-----------------|
2148  * | DDraw surface          |               | WineD3DSurface  |
2149  * |                        |               |                 |
2150  * |        WineD3DSurface  |-------------->|                 |
2151  * |        Child           |<------------->| Parent          |
2152  * |------------------------|               |-----------------|
2153  *
2154  * The DDraw surface is the parent of the wined3d surface, and it releases
2155  * the WineD3DSurface when the ddraw surface is destroyed.
2156  *
2157  * However, for all surfaces which can be in a container in WineD3D,
2158  * we have to do this. These surfaces are usually complex surfaces,
2159  * so this concerns primary surfaces with a front and a back buffer,
2160  * and textures.
2161  *
2162  * |------------------------|               |-----------------|
2163  * | DDraw surface          |               | Container       |
2164  * |                        |               |                 |
2165  * |                  Child |<------------->| Parent          |
2166  * |                Texture |<------------->|                 |
2167  * |         WineD3DSurface |<----|         |          Levels |<--|
2168  * | Complex connection     |     |         |                 |   |
2169  * |------------------------|     |         |-----------------|   |
2170  *  ^                             |                               |
2171  *  |                             |                               |
2172  *  |                             |                               |
2173  *  |    |------------------|     |         |-----------------|   |
2174  *  |    | IParent          |     |-------->| WineD3DSurface  |   |
2175  *  |    |                  |               |                 |   |
2176  *  |    |            Child |<------------->| Parent          |   |
2177  *  |    |                  |               |       Container |<--|
2178  *  |    |------------------|               |-----------------|   |
2179  *  |                                                             |
2180  *  |   |----------------------|                                  |
2181  *  |   | DDraw surface 2      |                                  |
2182  *  |   |                      |                                  |
2183  *  |<->| Complex root   Child |                                  |
2184  *  |   |              Texture |                                  |
2185  *  |   |       WineD3DSurface |<----|                            |
2186  *  |   |----------------------|     |                            |
2187  *  |                                |                            |
2188  *  |    |---------------------|     |      |-----------------|   |
2189  *  |    | IParent             |     |----->| WineD3DSurface  |   |
2190  *  |    |                     |            |                 |   |
2191  *  |    |               Child |<---------->| Parent          |   |
2192  *  |    |---------------------|            |       Container |<--|
2193  *  |                                       |-----------------|   |
2194  *  |                                                             |
2195  *  |             ---More surfaces can follow---                  |
2196  *
2197  * The reason is that the IWineD3DSwapchain(render target container)
2198  * and the IWineD3DTexure(Texture container) release the parents
2199  * of their surface's children, but by releasing the complex root
2200  * the surfaces which are complexly attached to it are destroyed
2201  * too. See IDirectDrawSurface::Release for a more detailed
2202  * explanation.
2203  *
2204  * Params:
2205  *  DDSD: Description of the surface to create
2206  *  Surf: Address to store the interface pointer at
2207  *  UnkOuter: Basically for aggregation support, but ddraw doesn't support
2208  *            aggregation, so it has to be NULL
2209  *
2210  * Returns:
2211  *  DD_OK on success
2212  *  CLASS_E_NOAGGREGATION if UnkOuter != NULL
2213  *  DDERR_* if an error occurs
2214  *
2215  *****************************************************************************/
2216 static HRESULT WINAPI
2217 IDirectDrawImpl_CreateSurface(IDirectDraw7 *iface,
2218                               DDSURFACEDESC2 *DDSD,
2219                               IDirectDrawSurface7 **Surf,
2220                               IUnknown *UnkOuter)
2221 {
2222     IDirectDrawImpl *This = (IDirectDrawImpl *)iface;
2223     IDirectDrawSurfaceImpl *object = NULL;
2224     HRESULT hr;
2225     LONG extra_surfaces = 0;
2226     DDSURFACEDESC2 desc2;
2227     WINED3DDISPLAYMODE Mode;
2228     const DWORD sysvidmem = DDSCAPS_VIDEOMEMORY | DDSCAPS_SYSTEMMEMORY;
2229
2230     TRACE("(%p)->(%p,%p,%p)\n", This, DDSD, Surf, UnkOuter);
2231
2232     /* Some checks before we start */
2233     if (TRACE_ON(ddraw))
2234     {
2235         TRACE(" (%p) Requesting surface desc :\n", This);
2236         DDRAW_dump_surface_desc(DDSD);
2237     }
2238     EnterCriticalSection(&ddraw_cs);
2239
2240     if (UnkOuter != NULL)
2241     {
2242         FIXME("(%p) : outer != NULL?\n", This);
2243         LeaveCriticalSection(&ddraw_cs);
2244         return CLASS_E_NOAGGREGATION; /* unchecked */
2245     }
2246
2247     if (Surf == NULL)
2248     {
2249         FIXME("(%p) You want to get back a surface? Don't give NULL ptrs!\n", This);
2250         LeaveCriticalSection(&ddraw_cs);
2251         return E_POINTER; /* unchecked */
2252     }
2253
2254     if (!(DDSD->dwFlags & DDSD_CAPS))
2255     {
2256         /* DVIDEO.DLL does forget the DDSD_CAPS flag ... *sigh* */
2257         DDSD->dwFlags |= DDSD_CAPS;
2258     }
2259
2260     if (DDSD->ddsCaps.dwCaps & DDSCAPS_ALLOCONLOAD)
2261     {
2262         /* If the surface is of the 'alloconload' type, ignore the LPSURFACE field */
2263         DDSD->dwFlags &= ~DDSD_LPSURFACE;
2264     }
2265
2266     if ((DDSD->dwFlags & DDSD_LPSURFACE) && (DDSD->lpSurface == NULL))
2267     {
2268         /* Frank Herbert's Dune specifies a null pointer for the surface, ignore the LPSURFACE field */
2269         WARN("(%p) Null surface pointer specified, ignore it!\n", This);
2270         DDSD->dwFlags &= ~DDSD_LPSURFACE;
2271     }
2272
2273     if((DDSD->ddsCaps.dwCaps & (DDSCAPS_FLIP | DDSCAPS_PRIMARYSURFACE)) == (DDSCAPS_FLIP | DDSCAPS_PRIMARYSURFACE) &&
2274        !(This->cooperative_level & DDSCL_EXCLUSIVE))
2275     {
2276         TRACE("(%p): Attempt to create a flipable primary surface without DDSCL_EXCLUSIVE set\n", This);
2277         *Surf = NULL;
2278         LeaveCriticalSection(&ddraw_cs);
2279         return DDERR_NOEXCLUSIVEMODE;
2280     }
2281
2282     if(DDSD->ddsCaps.dwCaps & (DDSCAPS_FRONTBUFFER | DDSCAPS_BACKBUFFER)) {
2283         WARN("Application tried to create an explicit front or back buffer\n");
2284         LeaveCriticalSection(&ddraw_cs);
2285         return DDERR_INVALIDCAPS;
2286     }
2287
2288     if((DDSD->ddsCaps.dwCaps & sysvidmem) == sysvidmem)
2289     {
2290         /* This is a special switch in ddrawex.dll, but not allowed in ddraw.dll */
2291         WARN("Application tries to put the surface in both system and video memory\n");
2292         LeaveCriticalSection(&ddraw_cs);
2293         *Surf = NULL;
2294         return DDERR_INVALIDCAPS;
2295     }
2296
2297     /* Check cube maps but only if the size includes them */
2298     if (DDSD->dwSize >= sizeof(DDSURFACEDESC2))
2299     {
2300         if(DDSD->ddsCaps.dwCaps2 & DDSCAPS2_CUBEMAP_ALLFACES &&
2301            !(DDSD->ddsCaps.dwCaps2 & DDSCAPS2_CUBEMAP))
2302         {
2303             WARN("Cube map faces requested without cube map flag\n");
2304             LeaveCriticalSection(&ddraw_cs);
2305             return DDERR_INVALIDCAPS;
2306         }
2307         if(DDSD->ddsCaps.dwCaps2 & DDSCAPS2_CUBEMAP &&
2308            (DDSD->ddsCaps.dwCaps2 & DDSCAPS2_CUBEMAP_ALLFACES) == 0)
2309         {
2310             WARN("Cube map without faces requested\n");
2311             LeaveCriticalSection(&ddraw_cs);
2312             return DDERR_INVALIDPARAMS;
2313         }
2314
2315         /* Quick tests confirm those can be created, but we don't do that yet */
2316         if(DDSD->ddsCaps.dwCaps2 & DDSCAPS2_CUBEMAP &&
2317            (DDSD->ddsCaps.dwCaps2 & DDSCAPS2_CUBEMAP_ALLFACES) != DDSCAPS2_CUBEMAP_ALLFACES)
2318         {
2319             FIXME("Partial cube maps not supported yet\n");
2320         }
2321     }
2322
2323     /* According to the msdn this flag is ignored by CreateSurface */
2324     if (DDSD->dwSize >= sizeof(DDSURFACEDESC2))
2325         DDSD->ddsCaps.dwCaps2 &= ~DDSCAPS2_MIPMAPSUBLEVEL;
2326
2327     /* Modify some flags */
2328     memset(&desc2, 0, sizeof(desc2));
2329     desc2.dwSize = sizeof(desc2);   /* For the struct copy */
2330     DD_STRUCT_COPY_BYSIZE(&desc2, DDSD);
2331     desc2.dwSize = sizeof(desc2);   /* To override a possibly smaller size */
2332     desc2.u4.ddpfPixelFormat.dwSize=sizeof(DDPIXELFORMAT); /* Just to be sure */
2333
2334     /* Get the video mode from WineD3D - we will need it */
2335     hr = IWineD3DDevice_GetDisplayMode(This->wineD3DDevice,
2336                                        0, /* Swapchain 0 */
2337                                        &Mode);
2338     if(FAILED(hr))
2339     {
2340         ERR("Failed to read display mode from wined3d\n");
2341         switch(This->orig_bpp)
2342         {
2343             case 8:
2344                 Mode.Format = WINED3DFMT_P8_UINT;
2345                 break;
2346
2347             case 15:
2348                 Mode.Format = WINED3DFMT_B5G5R5X1_UNORM;
2349                 break;
2350
2351             case 16:
2352                 Mode.Format = WINED3DFMT_B5G6R5_UNORM;
2353                 break;
2354
2355             case 24:
2356                 Mode.Format = WINED3DFMT_B8G8R8_UNORM;
2357                 break;
2358
2359             case 32:
2360                 Mode.Format = WINED3DFMT_B8G8R8X8_UNORM;
2361                 break;
2362         }
2363         Mode.Width = This->orig_width;
2364         Mode.Height = This->orig_height;
2365     }
2366
2367     /* No pixelformat given? Use the current screen format */
2368     if(!(desc2.dwFlags & DDSD_PIXELFORMAT))
2369     {
2370         desc2.dwFlags |= DDSD_PIXELFORMAT;
2371         desc2.u4.ddpfPixelFormat.dwSize=sizeof(DDPIXELFORMAT);
2372
2373         /* Wait: It could be a Z buffer */
2374         if(desc2.ddsCaps.dwCaps & DDSCAPS_ZBUFFER)
2375         {
2376             switch(desc2.u2.dwMipMapCount) /* Who had this glorious idea? */
2377             {
2378                 case 15:
2379                     PixelFormat_WineD3DtoDD(&desc2.u4.ddpfPixelFormat, WINED3DFMT_S1_UINT_D15_UNORM);
2380                     break;
2381                 case 16:
2382                     PixelFormat_WineD3DtoDD(&desc2.u4.ddpfPixelFormat, WINED3DFMT_D16_UNORM);
2383                     break;
2384                 case 24:
2385                     PixelFormat_WineD3DtoDD(&desc2.u4.ddpfPixelFormat, WINED3DFMT_X8D24_UNORM);
2386                     break;
2387                 case 32:
2388                     PixelFormat_WineD3DtoDD(&desc2.u4.ddpfPixelFormat, WINED3DFMT_D32_UNORM);
2389                     break;
2390                 default:
2391                     ERR("Unknown Z buffer bit depth\n");
2392             }
2393         }
2394         else
2395         {
2396             PixelFormat_WineD3DtoDD(&desc2.u4.ddpfPixelFormat, Mode.Format);
2397         }
2398     }
2399
2400     /* No Width or no Height? Use the original screen size
2401      */
2402     if(!(desc2.dwFlags & DDSD_WIDTH) ||
2403        !(desc2.dwFlags & DDSD_HEIGHT) )
2404     {
2405         /* Invalid for non-render targets */
2406         if(!(desc2.ddsCaps.dwCaps & DDSCAPS_PRIMARYSURFACE))
2407         {
2408             WARN("Creating a non-Primary surface without Width or Height info, returning DDERR_INVALIDPARAMS\n");
2409             *Surf = NULL;
2410             LeaveCriticalSection(&ddraw_cs);
2411             return DDERR_INVALIDPARAMS;
2412         }
2413
2414         desc2.dwFlags |= DDSD_WIDTH | DDSD_HEIGHT;
2415         desc2.dwWidth = Mode.Width;
2416         desc2.dwHeight = Mode.Height;
2417     }
2418
2419     /* Mipmap count fixes */
2420     if(desc2.ddsCaps.dwCaps & DDSCAPS_MIPMAP)
2421     {
2422         if(desc2.ddsCaps.dwCaps & DDSCAPS_COMPLEX)
2423         {
2424             if(desc2.dwFlags & DDSD_MIPMAPCOUNT)
2425             {
2426                 /* Mipmap count is given, should not be 0 */
2427                 if( desc2.u2.dwMipMapCount == 0 )
2428                 {
2429                     LeaveCriticalSection(&ddraw_cs);
2430                     return DDERR_INVALIDPARAMS;
2431                 }
2432             }
2433             else
2434             {
2435                 /* Undocumented feature: Create sublevels until
2436                  * either the width or the height is 1
2437                  */
2438                 DWORD min = desc2.dwWidth < desc2.dwHeight ?
2439                             desc2.dwWidth : desc2.dwHeight;
2440                 desc2.u2.dwMipMapCount = 0;
2441                 while( min )
2442                 {
2443                     desc2.u2.dwMipMapCount += 1;
2444                     min >>= 1;
2445                 }
2446             }
2447         }
2448         else
2449         {
2450             /* Not-complex mipmap -> Mipmapcount = 1 */
2451             desc2.u2.dwMipMapCount = 1;
2452         }
2453         extra_surfaces = desc2.u2.dwMipMapCount - 1;
2454
2455         /* There's a mipmap count in the created surface in any case */
2456         desc2.dwFlags |= DDSD_MIPMAPCOUNT;
2457     }
2458     /* If no mipmap is given, the texture has only one level */
2459
2460     /* The first surface is a front buffer, the back buffer is created afterwards */
2461     if( (desc2.dwFlags & DDSD_CAPS) && (desc2.ddsCaps.dwCaps & DDSCAPS_PRIMARYSURFACE) )
2462     {
2463         desc2.ddsCaps.dwCaps |= DDSCAPS_FRONTBUFFER;
2464     }
2465
2466     /* The root surface in a cube map is positive x */
2467     if(desc2.ddsCaps.dwCaps2 & DDSCAPS2_CUBEMAP)
2468     {
2469         desc2.ddsCaps.dwCaps2 &= ~DDSCAPS2_CUBEMAP_ALLFACES;
2470         desc2.ddsCaps.dwCaps2 |=  DDSCAPS2_CUBEMAP_POSITIVEX;
2471     }
2472
2473     /* Create the first surface */
2474     hr = IDirectDrawImpl_CreateNewSurface(This, &desc2, &object, 0);
2475     if( hr != DD_OK)
2476     {
2477         ERR("IDirectDrawImpl_CreateNewSurface failed with %08x\n", hr);
2478         LeaveCriticalSection(&ddraw_cs);
2479         return hr;
2480     }
2481     object->is_complex_root = TRUE;
2482
2483     *Surf = (IDirectDrawSurface7 *)object;
2484
2485     /* Create Additional surfaces if necessary
2486      * This applies to Primary surfaces which have a back buffer count
2487      * set, but not to mipmap textures. In case of Mipmap textures,
2488      * wineD3D takes care of the creation of additional surfaces
2489      */
2490     if(DDSD->dwFlags & DDSD_BACKBUFFERCOUNT)
2491     {
2492         extra_surfaces = DDSD->dwBackBufferCount;
2493         desc2.ddsCaps.dwCaps &= ~DDSCAPS_FRONTBUFFER; /* It's not a front buffer */
2494         desc2.ddsCaps.dwCaps |= DDSCAPS_BACKBUFFER;
2495         desc2.dwBackBufferCount = 0;
2496     }
2497
2498     hr = DD_OK;
2499     if(desc2.ddsCaps.dwCaps2 & DDSCAPS2_CUBEMAP)
2500     {
2501         desc2.ddsCaps.dwCaps2 &= ~DDSCAPS2_CUBEMAP_ALLFACES;
2502         desc2.ddsCaps.dwCaps2 |=  DDSCAPS2_CUBEMAP_NEGATIVEZ;
2503         hr |= CreateAdditionalSurfaces(This, object, extra_surfaces + 1, desc2, TRUE);
2504         desc2.ddsCaps.dwCaps2 &= ~DDSCAPS2_CUBEMAP_NEGATIVEZ;
2505         desc2.ddsCaps.dwCaps2 |=  DDSCAPS2_CUBEMAP_POSITIVEZ;
2506         hr |= CreateAdditionalSurfaces(This, object, extra_surfaces + 1, desc2, TRUE);
2507         desc2.ddsCaps.dwCaps2 &= ~DDSCAPS2_CUBEMAP_POSITIVEZ;
2508         desc2.ddsCaps.dwCaps2 |=  DDSCAPS2_CUBEMAP_NEGATIVEY;
2509         hr |= CreateAdditionalSurfaces(This, object, extra_surfaces + 1, desc2, TRUE);
2510         desc2.ddsCaps.dwCaps2 &= ~DDSCAPS2_CUBEMAP_NEGATIVEY;
2511         desc2.ddsCaps.dwCaps2 |=  DDSCAPS2_CUBEMAP_POSITIVEY;
2512         hr |= CreateAdditionalSurfaces(This, object, extra_surfaces + 1, desc2, TRUE);
2513         desc2.ddsCaps.dwCaps2 &= ~DDSCAPS2_CUBEMAP_POSITIVEY;
2514         desc2.ddsCaps.dwCaps2 |=  DDSCAPS2_CUBEMAP_NEGATIVEX;
2515         hr |= CreateAdditionalSurfaces(This, object, extra_surfaces + 1, desc2, TRUE);
2516         desc2.ddsCaps.dwCaps2 &= ~DDSCAPS2_CUBEMAP_NEGATIVEX;
2517         desc2.ddsCaps.dwCaps2 |=  DDSCAPS2_CUBEMAP_POSITIVEX;
2518     }
2519
2520     hr |= CreateAdditionalSurfaces(This, object, extra_surfaces, desc2, FALSE);
2521     if(hr != DD_OK)
2522     {
2523         /* This destroys and possibly created surfaces too */
2524         IDirectDrawSurface_Release((IDirectDrawSurface7 *)object);
2525         LeaveCriticalSection(&ddraw_cs);
2526         return hr;
2527     }
2528
2529     /* If the implementation is OpenGL and there's no d3ddevice, attach a d3ddevice
2530      * But attach the d3ddevice only if the currently created surface was
2531      * a primary surface (2D app in 3D mode) or a 3DDEVICE surface (3D app)
2532      * The only case I can think of where this doesn't apply is when a
2533      * 2D app was configured by the user to run with OpenGL and it didn't create
2534      * the render target as first surface. In this case the render target creation
2535      * will cause the 3D init.
2536      */
2537     if( (This->ImplType == SURFACE_OPENGL) && !(This->d3d_initialized) &&
2538         desc2.ddsCaps.dwCaps & (DDSCAPS_PRIMARYSURFACE | DDSCAPS_3DDEVICE) )
2539     {
2540         IDirectDrawSurfaceImpl *target = object, *surface;
2541         struct list *entry;
2542
2543         /* Search for the primary to use as render target */
2544         LIST_FOR_EACH(entry, &This->surface_list)
2545         {
2546             surface = LIST_ENTRY(entry, IDirectDrawSurfaceImpl, surface_list_entry);
2547             if((surface->surface_desc.ddsCaps.dwCaps & (DDSCAPS_PRIMARYSURFACE | DDSCAPS_FRONTBUFFER)) ==
2548                (DDSCAPS_PRIMARYSURFACE | DDSCAPS_FRONTBUFFER))
2549             {
2550                 /* found */
2551                 target = surface;
2552                 TRACE("Using primary %p as render target\n", target);
2553                 break;
2554             }
2555         }
2556
2557         TRACE("(%p) Attaching a D3DDevice, rendertarget = %p\n", This, target);
2558         hr = IDirectDrawImpl_AttachD3DDevice(This, target);
2559         if(hr != D3D_OK)
2560         {
2561             IDirectDrawSurfaceImpl *release_surf;
2562             ERR("IDirectDrawImpl_AttachD3DDevice failed, hr = %x\n", hr);
2563             *Surf = NULL;
2564
2565             /* The before created surface structures are in an incomplete state here.
2566              * WineD3D holds the reference on the IParents, and it released them on the failure
2567              * already. So the regular release method implementation would fail on the attempt
2568              * to destroy either the IParents or the swapchain. So free the surface here.
2569              * The surface structure here is a list, not a tree, because onscreen targets
2570              * cannot be cube textures
2571              */
2572             while(object)
2573             {
2574                 release_surf = object;
2575                 object = object->complex_array[0];
2576                 IDirectDrawSurfaceImpl_Destroy(release_surf);
2577             }
2578             LeaveCriticalSection(&ddraw_cs);
2579             return hr;
2580         }
2581     } else if(!(This->d3d_initialized) && desc2.ddsCaps.dwCaps & DDSCAPS_PRIMARYSURFACE) {
2582         IDirectDrawImpl_CreateGDISwapChain(This, object);
2583     }
2584
2585     /* Addref the ddraw interface to keep an reference for each surface */
2586     IDirectDraw7_AddRef(iface);
2587     object->ifaceToRelease = (IUnknown *) iface;
2588
2589     /* Create a WineD3DTexture if a texture was requested */
2590     if(desc2.ddsCaps.dwCaps & DDSCAPS_TEXTURE)
2591     {
2592         UINT levels;
2593         WINED3DFORMAT Format;
2594         WINED3DPOOL Pool = WINED3DPOOL_DEFAULT;
2595
2596         This->tex_root = object;
2597
2598         if(desc2.ddsCaps.dwCaps & DDSCAPS_MIPMAP)
2599         {
2600             /* a mipmap is created, create enough levels */
2601             levels = desc2.u2.dwMipMapCount;
2602         }
2603         else
2604         {
2605             /* No mipmap is created, create one level */
2606             levels = 1;
2607         }
2608
2609         /* DDSCAPS_SYSTEMMEMORY textures are in WINED3DPOOL_SYSTEMMEM */
2610         if(DDSD->ddsCaps.dwCaps & DDSCAPS_SYSTEMMEMORY)
2611         {
2612             Pool = WINED3DPOOL_SYSTEMMEM;
2613         }
2614         /* Should I forward the MANAGED cap to the managed pool ? */
2615
2616         /* Get the format. It's set already by CreateNewSurface */
2617         Format = PixelFormat_DD2WineD3D(&object->surface_desc.u4.ddpfPixelFormat);
2618
2619         /* The surfaces are already created, the callback only
2620          * passes the IWineD3DSurface to WineD3D
2621          */
2622         if(desc2.ddsCaps.dwCaps2 & DDSCAPS2_CUBEMAP)
2623         {
2624             hr = IWineD3DDevice_CreateCubeTexture(This->wineD3DDevice, DDSD->dwWidth /* Edgelength */,
2625                     levels, 0 /* usage */, Format, Pool, (IWineD3DCubeTexture **)&object->wineD3DTexture,
2626                     (IUnknown *)object, &ddraw_null_wined3d_parent_ops);
2627         }
2628         else
2629         {
2630             hr = IWineD3DDevice_CreateTexture(This->wineD3DDevice, DDSD->dwWidth, DDSD->dwHeight, levels,
2631                     0 /* usage */, Format, Pool, (IWineD3DTexture **)&object->wineD3DTexture,
2632                     (IUnknown *)object, &ddraw_null_wined3d_parent_ops);
2633         }
2634         This->tex_root = NULL;
2635     }
2636
2637     LeaveCriticalSection(&ddraw_cs);
2638     return hr;
2639 }
2640
2641 #define DDENUMSURFACES_SEARCHTYPE (DDENUMSURFACES_CANBECREATED|DDENUMSURFACES_DOESEXIST)
2642 #define DDENUMSURFACES_MATCHTYPE (DDENUMSURFACES_ALL|DDENUMSURFACES_MATCH|DDENUMSURFACES_NOMATCH)
2643
2644 static BOOL
2645 Main_DirectDraw_DDPIXELFORMAT_Match(const DDPIXELFORMAT *requested,
2646                                     const DDPIXELFORMAT *provided)
2647 {
2648     /* Some flags must be present in both or neither for a match. */
2649     static const DWORD must_match = DDPF_PALETTEINDEXED1 | DDPF_PALETTEINDEXED2
2650         | DDPF_PALETTEINDEXED4 | DDPF_PALETTEINDEXED8 | DDPF_FOURCC
2651         | DDPF_ZBUFFER | DDPF_STENCILBUFFER;
2652
2653     if ((requested->dwFlags & provided->dwFlags) != requested->dwFlags)
2654         return FALSE;
2655
2656     if ((requested->dwFlags & must_match) != (provided->dwFlags & must_match))
2657         return FALSE;
2658
2659     if (requested->dwFlags & DDPF_FOURCC)
2660         if (requested->dwFourCC != provided->dwFourCC)
2661             return FALSE;
2662
2663     if (requested->dwFlags & (DDPF_RGB|DDPF_YUV|DDPF_ZBUFFER|DDPF_ALPHA
2664                               |DDPF_LUMINANCE|DDPF_BUMPDUDV))
2665         if (requested->u1.dwRGBBitCount != provided->u1.dwRGBBitCount)
2666             return FALSE;
2667
2668     if (requested->dwFlags & (DDPF_RGB|DDPF_YUV|DDPF_STENCILBUFFER
2669                               |DDPF_LUMINANCE|DDPF_BUMPDUDV))
2670         if (requested->u2.dwRBitMask != provided->u2.dwRBitMask)
2671             return FALSE;
2672
2673     if (requested->dwFlags & (DDPF_RGB|DDPF_YUV|DDPF_ZBUFFER|DDPF_BUMPDUDV))
2674         if (requested->u3.dwGBitMask != provided->u3.dwGBitMask)
2675             return FALSE;
2676
2677     /* I could be wrong about the bumpmapping. MSDN docs are vague. */
2678     if (requested->dwFlags & (DDPF_RGB|DDPF_YUV|DDPF_STENCILBUFFER
2679                               |DDPF_BUMPDUDV))
2680         if (requested->u4.dwBBitMask != provided->u4.dwBBitMask)
2681             return FALSE;
2682
2683     if (requested->dwFlags & (DDPF_ALPHAPIXELS|DDPF_ZPIXELS))
2684         if (requested->u5.dwRGBAlphaBitMask != provided->u5.dwRGBAlphaBitMask)
2685             return FALSE;
2686
2687     return TRUE;
2688 }
2689
2690 static BOOL
2691 IDirectDrawImpl_DDSD_Match(const DDSURFACEDESC2* requested,
2692                            const DDSURFACEDESC2* provided)
2693 {
2694     struct compare_info
2695     {
2696         DWORD flag;
2697         ptrdiff_t offset;
2698         size_t size;
2699     };
2700
2701 #define CMP(FLAG, FIELD)                                \
2702         { DDSD_##FLAG, offsetof(DDSURFACEDESC2, FIELD), \
2703           sizeof(((DDSURFACEDESC2 *)(NULL))->FIELD) }
2704
2705     static const struct compare_info compare[] =
2706     {
2707         CMP(ALPHABITDEPTH, dwAlphaBitDepth),
2708         CMP(BACKBUFFERCOUNT, dwBackBufferCount),
2709         CMP(CAPS, ddsCaps),
2710         CMP(CKDESTBLT, ddckCKDestBlt),
2711         CMP(CKDESTOVERLAY, u3 /* ddckCKDestOverlay */),
2712         CMP(CKSRCBLT, ddckCKSrcBlt),
2713         CMP(CKSRCOVERLAY, ddckCKSrcOverlay),
2714         CMP(HEIGHT, dwHeight),
2715         CMP(LINEARSIZE, u1 /* dwLinearSize */),
2716         CMP(LPSURFACE, lpSurface),
2717         CMP(MIPMAPCOUNT, u2 /* dwMipMapCount */),
2718         CMP(PITCH, u1 /* lPitch */),
2719         /* PIXELFORMAT: manual */
2720         CMP(REFRESHRATE, u2 /* dwRefreshRate */),
2721         CMP(TEXTURESTAGE, dwTextureStage),
2722         CMP(WIDTH, dwWidth),
2723         /* ZBUFFERBITDEPTH: "obsolete" */
2724     };
2725
2726 #undef CMP
2727
2728     unsigned int i;
2729
2730     if ((requested->dwFlags & provided->dwFlags) != requested->dwFlags)
2731         return FALSE;
2732
2733     for (i=0; i < sizeof(compare)/sizeof(compare[0]); i++)
2734     {
2735         if (requested->dwFlags & compare[i].flag
2736             && memcmp((const char *)provided + compare[i].offset,
2737                       (const char *)requested + compare[i].offset,
2738                       compare[i].size) != 0)
2739             return FALSE;
2740     }
2741
2742     if (requested->dwFlags & DDSD_PIXELFORMAT)
2743     {
2744         if (!Main_DirectDraw_DDPIXELFORMAT_Match(&requested->u4.ddpfPixelFormat,
2745                                                 &provided->u4.ddpfPixelFormat))
2746             return FALSE;
2747     }
2748
2749     return TRUE;
2750 }
2751
2752 #undef DDENUMSURFACES_SEARCHTYPE
2753 #undef DDENUMSURFACES_MATCHTYPE
2754
2755 /*****************************************************************************
2756  * IDirectDraw7::EnumSurfaces
2757  *
2758  * Loops through all surfaces attached to this device and calls the
2759  * application callback. This can't be relayed to WineD3DDevice,
2760  * because some WineD3DSurfaces' parents are IParent objects
2761  *
2762  * Params:
2763  *  Flags: Some filtering flags. See IDirectDrawImpl_EnumSurfacesCallback
2764  *  DDSD: Description to filter for
2765  *  Context: Application-provided pointer, it's passed unmodified to the
2766  *           Callback function
2767  *  Callback: Address to call for each surface
2768  *
2769  * Returns:
2770  *  DDERR_INVALIDPARAMS if the callback is NULL
2771  *  DD_OK on success
2772  *
2773  *****************************************************************************/
2774 static HRESULT WINAPI
2775 IDirectDrawImpl_EnumSurfaces(IDirectDraw7 *iface,
2776                              DWORD Flags,
2777                              DDSURFACEDESC2 *DDSD,
2778                              void *Context,
2779                              LPDDENUMSURFACESCALLBACK7 Callback)
2780 {
2781     /* The surface enumeration is handled by WineDDraw,
2782      * because it keeps track of all surfaces attached to
2783      * it. The filtering is done by our callback function,
2784      * because WineDDraw doesn't handle ddraw-like surface
2785      * caps structures
2786      */
2787     IDirectDrawImpl *This = (IDirectDrawImpl *)iface;
2788     IDirectDrawSurfaceImpl *surf;
2789     BOOL all, nomatch;
2790     DDSURFACEDESC2 desc;
2791     struct list *entry, *entry2;
2792
2793     all = Flags & DDENUMSURFACES_ALL;
2794     nomatch = Flags & DDENUMSURFACES_NOMATCH;
2795
2796     TRACE("(%p)->(%x,%p,%p,%p)\n", This, Flags, DDSD, Context, Callback);
2797     EnterCriticalSection(&ddraw_cs);
2798
2799     if(!Callback)
2800     {
2801         LeaveCriticalSection(&ddraw_cs);
2802         return DDERR_INVALIDPARAMS;
2803     }
2804
2805     /* Use the _SAFE enumeration, the app may destroy enumerated surfaces */
2806     LIST_FOR_EACH_SAFE(entry, entry2, &This->surface_list)
2807     {
2808         surf = LIST_ENTRY(entry, IDirectDrawSurfaceImpl, surface_list_entry);
2809         if (all || (nomatch != IDirectDrawImpl_DDSD_Match(DDSD, &surf->surface_desc)))
2810         {
2811             desc = surf->surface_desc;
2812             IDirectDrawSurface7_AddRef((IDirectDrawSurface7 *)surf);
2813             if (Callback((IDirectDrawSurface7 *)surf, &desc, Context) != DDENUMRET_OK)
2814             {
2815                 LeaveCriticalSection(&ddraw_cs);
2816                 return DD_OK;
2817             }
2818         }
2819     }
2820     LeaveCriticalSection(&ddraw_cs);
2821     return DD_OK;
2822 }
2823
2824 static HRESULT WINAPI
2825 findRenderTarget(IDirectDrawSurface7 *surface,
2826                  DDSURFACEDESC2 *desc,
2827                  void *ctx)
2828 {
2829     IDirectDrawSurfaceImpl *surf = (IDirectDrawSurfaceImpl *)surface;
2830     IDirectDrawSurfaceImpl **target = ctx;
2831
2832     if(!surf->isRenderTarget) {
2833         *target = surf;
2834         IDirectDrawSurface7_Release(surface);
2835         return DDENUMRET_CANCEL;
2836     }
2837
2838     /* Recurse into the surface tree */
2839     IDirectDrawSurface7_EnumAttachedSurfaces(surface, ctx, findRenderTarget);
2840
2841     IDirectDrawSurface7_Release(surface);
2842     if(*target) return DDENUMRET_CANCEL;
2843     else return DDENUMRET_OK; /* Continue with the next neighbor surface */
2844 }
2845
2846 static HRESULT IDirectDrawImpl_CreateGDISwapChain(IDirectDrawImpl *This,
2847                                                          IDirectDrawSurfaceImpl *primary) {
2848     HRESULT hr;
2849     WINED3DPRESENT_PARAMETERS presentation_parameters;
2850     HWND window;
2851
2852     window = This->dest_window;
2853
2854     memset(&presentation_parameters, 0, sizeof(presentation_parameters));
2855
2856     /* Use the surface description for the device parameters, not the
2857      * Device settings. The app might render to an offscreen surface
2858      */
2859     presentation_parameters.BackBufferWidth                 = primary->surface_desc.dwWidth;
2860     presentation_parameters.BackBufferHeight                = primary->surface_desc.dwHeight;
2861     presentation_parameters.BackBufferFormat                = PixelFormat_DD2WineD3D(&primary->surface_desc.u4.ddpfPixelFormat);
2862     presentation_parameters.BackBufferCount                 = (primary->surface_desc.dwFlags & DDSD_BACKBUFFERCOUNT) ? primary->surface_desc.dwBackBufferCount : 0;
2863     presentation_parameters.MultiSampleType                 = WINED3DMULTISAMPLE_NONE;
2864     presentation_parameters.MultiSampleQuality              = 0;
2865     presentation_parameters.SwapEffect                      = WINED3DSWAPEFFECT_FLIP;
2866     presentation_parameters.hDeviceWindow                   = window;
2867     presentation_parameters.Windowed                        = !(This->cooperative_level & DDSCL_FULLSCREEN);
2868     presentation_parameters.EnableAutoDepthStencil          = FALSE; /* Not on GDI swapchains */
2869     presentation_parameters.AutoDepthStencilFormat          = 0;
2870     presentation_parameters.Flags                           = 0;
2871     presentation_parameters.FullScreen_RefreshRateInHz      = WINED3DPRESENT_RATE_DEFAULT; /* Default rate: It's already set */
2872     presentation_parameters.PresentationInterval            = WINED3DPRESENT_INTERVAL_DEFAULT;
2873
2874     This->d3d_target = primary;
2875     hr = IWineD3DDevice_InitGDI(This->wineD3DDevice, &presentation_parameters);
2876     This->d3d_target = NULL;
2877
2878     if (hr != D3D_OK)
2879     {
2880         FIXME("(%p) call to IWineD3DDevice_InitGDI failed\n", This);
2881         primary->wineD3DSwapChain = NULL;
2882     }
2883     return hr;
2884 }
2885
2886 /*****************************************************************************
2887  * IDirectDrawImpl_AttachD3DDevice
2888  *
2889  * Initializes the D3D capabilities of WineD3D
2890  *
2891  * Params:
2892  *  primary: The primary surface for D3D
2893  *
2894  * Returns
2895  *  DD_OK on success,
2896  *  DDERR_* otherwise
2897  *
2898  *****************************************************************************/
2899 static HRESULT
2900 IDirectDrawImpl_AttachD3DDevice(IDirectDrawImpl *This,
2901                                 IDirectDrawSurfaceImpl *primary)
2902 {
2903     HRESULT hr;
2904     HWND                  window = This->dest_window;
2905
2906     WINED3DPRESENT_PARAMETERS localParameters;
2907
2908     TRACE("(%p)->(%p)\n", This, primary);
2909
2910     /* If there's no window, create a hidden window. WineD3D needs it */
2911     if(window == 0 || window == GetDesktopWindow())
2912     {
2913         window = CreateWindowExA(0, This->classname, "Hidden D3D Window",
2914                                  WS_DISABLED, 0, 0,
2915                                  GetSystemMetrics(SM_CXSCREEN),
2916                                  GetSystemMetrics(SM_CYSCREEN),
2917                                  NULL, NULL, GetModuleHandleA(0), NULL);
2918
2919         ShowWindow(window, SW_HIDE);   /* Just to be sure */
2920         WARN("(%p) No window for the Direct3DDevice, created a hidden window. HWND=%p\n", This, window);
2921     }
2922     else
2923     {
2924         TRACE("(%p) Using existing window %p for Direct3D rendering\n", This, window);
2925     }
2926     This->d3d_window = window;
2927
2928     /* Store the future Render Target surface */
2929     This->d3d_target = primary;
2930
2931     /* Use the surface description for the device parameters, not the
2932      * Device settings. The app might render to an offscreen surface
2933      */
2934     localParameters.BackBufferWidth                 = primary->surface_desc.dwWidth;
2935     localParameters.BackBufferHeight                = primary->surface_desc.dwHeight;
2936     localParameters.BackBufferFormat                = PixelFormat_DD2WineD3D(&primary->surface_desc.u4.ddpfPixelFormat);
2937     localParameters.BackBufferCount                 = (primary->surface_desc.dwFlags & DDSD_BACKBUFFERCOUNT) ? primary->surface_desc.dwBackBufferCount : 0;
2938     localParameters.MultiSampleType                 = WINED3DMULTISAMPLE_NONE;
2939     localParameters.MultiSampleQuality              = 0;
2940     localParameters.SwapEffect                      = WINED3DSWAPEFFECT_COPY;
2941     localParameters.hDeviceWindow                   = window;
2942     localParameters.Windowed                        = !(This->cooperative_level & DDSCL_FULLSCREEN);
2943     localParameters.EnableAutoDepthStencil          = TRUE;
2944     localParameters.AutoDepthStencilFormat          = WINED3DFMT_D16_UNORM;
2945     localParameters.Flags                           = 0;
2946     localParameters.FullScreen_RefreshRateInHz      = WINED3DPRESENT_RATE_DEFAULT; /* Default rate: It's already set */
2947     localParameters.PresentationInterval            = WINED3DPRESENT_INTERVAL_DEFAULT;
2948
2949     TRACE("Passing mode %d\n", localParameters.BackBufferFormat);
2950
2951     /* Set this NOW, otherwise creating the depth stencil surface will cause a
2952      * recursive loop until ram or emulated video memory is full
2953      */
2954     This->d3d_initialized = TRUE;
2955
2956     hr = IWineD3DDevice_Init3D(This->wineD3DDevice, &localParameters);
2957     if(FAILED(hr))
2958     {
2959         This->d3d_target = NULL;
2960         This->d3d_initialized = FALSE;
2961         return hr;
2962     }
2963
2964     This->declArraySize = 2;
2965     This->decls = HeapAlloc(GetProcessHeap(),
2966                             HEAP_ZERO_MEMORY,
2967                             sizeof(*This->decls) * This->declArraySize);
2968     if(!This->decls)
2969     {
2970         ERR("Error allocating an array for the converted vertex decls\n");
2971         This->declArraySize = 0;
2972         hr = IWineD3DDevice_Uninit3D(This->wineD3DDevice, D3D7CB_DestroySwapChain);
2973         return E_OUTOFMEMORY;
2974     }
2975
2976     /* Create an Index Buffer parent */
2977     TRACE("(%p) Successfully initialized 3D\n", This);
2978     return DD_OK;
2979 }
2980
2981 /*****************************************************************************
2982  * DirectDrawCreateClipper (DDRAW.@)
2983  *
2984  * Creates a new IDirectDrawClipper object.
2985  *
2986  * Params:
2987  *  Clipper: Address to write the interface pointer to
2988  *  UnkOuter: For aggregation support, which ddraw doesn't have. Has to be
2989  *            NULL
2990  *
2991  * Returns:
2992  *  CLASS_E_NOAGGREGATION if UnkOuter != NULL
2993  *  E_OUTOFMEMORY if allocating the object failed
2994  *
2995  *****************************************************************************/
2996 HRESULT WINAPI
2997 DirectDrawCreateClipper(DWORD Flags,
2998                         LPDIRECTDRAWCLIPPER *Clipper,
2999                         IUnknown *UnkOuter)
3000 {
3001     IDirectDrawClipperImpl* object;
3002     TRACE("(%08x,%p,%p)\n", Flags, Clipper, UnkOuter);
3003
3004     EnterCriticalSection(&ddraw_cs);
3005     if (UnkOuter != NULL)
3006     {
3007         LeaveCriticalSection(&ddraw_cs);
3008         return CLASS_E_NOAGGREGATION;
3009     }
3010
3011     if (!LoadWineD3D())
3012     {
3013         LeaveCriticalSection(&ddraw_cs);
3014         return DDERR_NODIRECTDRAWSUPPORT;
3015     }
3016
3017     object = HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY,
3018                      sizeof(IDirectDrawClipperImpl));
3019     if (object == NULL)
3020     {
3021         LeaveCriticalSection(&ddraw_cs);
3022         return E_OUTOFMEMORY;
3023     }
3024
3025     object->lpVtbl = &IDirectDrawClipper_Vtbl;
3026     object->ref = 1;
3027     object->wineD3DClipper = pWineDirect3DCreateClipper((IUnknown *) object);
3028     if(!object->wineD3DClipper)
3029     {
3030         HeapFree(GetProcessHeap(), 0, object);
3031         LeaveCriticalSection(&ddraw_cs);
3032         return E_OUTOFMEMORY;
3033     }
3034
3035     *Clipper = (IDirectDrawClipper *) object;
3036     LeaveCriticalSection(&ddraw_cs);
3037     return DD_OK;
3038 }
3039
3040 /*****************************************************************************
3041  * IDirectDraw7::CreateClipper
3042  *
3043  * Creates a DDraw clipper. See DirectDrawCreateClipper for details
3044  *
3045  *****************************************************************************/
3046 static HRESULT WINAPI
3047 IDirectDrawImpl_CreateClipper(IDirectDraw7 *iface,
3048                               DWORD Flags,
3049                               IDirectDrawClipper **Clipper,
3050                               IUnknown *UnkOuter)
3051 {
3052     IDirectDrawImpl *This = (IDirectDrawImpl *)iface;
3053     TRACE("(%p)->(%x,%p,%p)\n", This, Flags, Clipper, UnkOuter);
3054     return DirectDrawCreateClipper(Flags, Clipper, UnkOuter);
3055 }
3056
3057 /*****************************************************************************
3058  * IDirectDraw7::CreatePalette
3059  *
3060  * Creates a new IDirectDrawPalette object
3061  *
3062  * Params:
3063  *  Flags: The flags for the new clipper
3064  *  ColorTable: Color table to assign to the new clipper
3065  *  Palette: Address to write the interface pointer to
3066  *  UnkOuter: For aggregation support, which ddraw doesn't have. Has to be
3067  *            NULL
3068  *
3069  * Returns:
3070  *  CLASS_E_NOAGGREGATION if UnkOuter != NULL
3071  *  E_OUTOFMEMORY if allocating the object failed
3072  *
3073  *****************************************************************************/
3074 static HRESULT WINAPI
3075 IDirectDrawImpl_CreatePalette(IDirectDraw7 *iface,
3076                               DWORD Flags,
3077                               PALETTEENTRY *ColorTable,
3078                               IDirectDrawPalette **Palette,
3079                               IUnknown *pUnkOuter)
3080 {
3081     IDirectDrawImpl *This = (IDirectDrawImpl *)iface;
3082     IDirectDrawPaletteImpl *object;
3083     HRESULT hr = DDERR_GENERIC;
3084     TRACE("(%p)->(%x,%p,%p,%p)\n", This, Flags, ColorTable, Palette, pUnkOuter);
3085
3086     EnterCriticalSection(&ddraw_cs);
3087     if(pUnkOuter != NULL)
3088     {
3089         WARN("pUnkOuter is %p, returning CLASS_E_NOAGGREGATION\n", pUnkOuter);
3090         LeaveCriticalSection(&ddraw_cs);
3091         return CLASS_E_NOAGGREGATION;
3092     }
3093
3094     /* The refcount test shows that a cooplevel is required for this */
3095     if(!This->cooperative_level)
3096     {
3097         WARN("No cooperative level set, returning DDERR_NOCOOPERATIVELEVELSET\n");
3098         LeaveCriticalSection(&ddraw_cs);
3099         return DDERR_NOCOOPERATIVELEVELSET;
3100     }
3101
3102     object = HeapAlloc(GetProcessHeap(), 0, sizeof(IDirectDrawPaletteImpl));
3103     if(!object)
3104     {
3105         ERR("Out of memory when allocating memory for a palette implementation\n");
3106         LeaveCriticalSection(&ddraw_cs);
3107         return E_OUTOFMEMORY;
3108     }
3109
3110     object->lpVtbl = &IDirectDrawPalette_Vtbl;
3111     object->ref = 1;
3112     object->ddraw_owner = This;
3113
3114     hr = IWineD3DDevice_CreatePalette(This->wineD3DDevice, Flags,
3115             ColorTable, &object->wineD3DPalette, (IUnknown *)object);
3116     if(hr != DD_OK)
3117     {
3118         HeapFree(GetProcessHeap(), 0, object);
3119         LeaveCriticalSection(&ddraw_cs);
3120         return hr;
3121     }
3122
3123     IDirectDraw7_AddRef(iface);
3124     object->ifaceToRelease = (IUnknown *) iface;
3125     *Palette = (IDirectDrawPalette *)object;
3126     LeaveCriticalSection(&ddraw_cs);
3127     return DD_OK;
3128 }
3129
3130 /*****************************************************************************
3131  * IDirectDraw7::DuplicateSurface
3132  *
3133  * Duplicates a surface. The surface memory points to the same memory as
3134  * the original surface, and it's released when the last surface referencing
3135  * it is released. I guess that's beyond Wine's surface management right now
3136  * (Idea: create a new DDraw surface with the same WineD3DSurface. I need a
3137  * test application to implement this)
3138  *
3139  * Params:
3140  *  Src: Address of the source surface
3141  *  Dest: Address to write the new surface pointer to
3142  *
3143  * Returns:
3144  *  See IDirectDraw7::CreateSurface
3145  *
3146  *****************************************************************************/
3147 static HRESULT WINAPI
3148 IDirectDrawImpl_DuplicateSurface(IDirectDraw7 *iface,
3149                                  IDirectDrawSurface7 *Src,
3150                                  IDirectDrawSurface7 **Dest)
3151 {
3152     IDirectDrawImpl *This = (IDirectDrawImpl *)iface;
3153     IDirectDrawSurfaceImpl *Surf = (IDirectDrawSurfaceImpl *)Src;
3154
3155     FIXME("(%p)->(%p,%p)\n", This, Surf, Dest);
3156
3157     /* For now, simply create a new, independent surface */
3158     return IDirectDraw7_CreateSurface(iface,
3159                                       &Surf->surface_desc,
3160                                       Dest,
3161                                       NULL);
3162 }
3163
3164 /*****************************************************************************
3165  * IDirectDraw7 VTable
3166  *****************************************************************************/
3167 const IDirectDraw7Vtbl IDirectDraw7_Vtbl =
3168 {
3169     /*** IUnknown ***/
3170     IDirectDrawImpl_QueryInterface,
3171     IDirectDrawImpl_AddRef,
3172     IDirectDrawImpl_Release,
3173     /*** IDirectDraw ***/
3174     IDirectDrawImpl_Compact,
3175     IDirectDrawImpl_CreateClipper,
3176     IDirectDrawImpl_CreatePalette,
3177     IDirectDrawImpl_CreateSurface,
3178     IDirectDrawImpl_DuplicateSurface,
3179     IDirectDrawImpl_EnumDisplayModes,
3180     IDirectDrawImpl_EnumSurfaces,
3181     IDirectDrawImpl_FlipToGDISurface,
3182     IDirectDrawImpl_GetCaps,
3183     IDirectDrawImpl_GetDisplayMode,
3184     IDirectDrawImpl_GetFourCCCodes,
3185     IDirectDrawImpl_GetGDISurface,
3186     IDirectDrawImpl_GetMonitorFrequency,
3187     IDirectDrawImpl_GetScanLine,
3188     IDirectDrawImpl_GetVerticalBlankStatus,
3189     IDirectDrawImpl_Initialize,
3190     IDirectDrawImpl_RestoreDisplayMode,
3191     IDirectDrawImpl_SetCooperativeLevel,
3192     IDirectDrawImpl_SetDisplayMode,
3193     IDirectDrawImpl_WaitForVerticalBlank,
3194     /*** IDirectDraw2 ***/
3195     IDirectDrawImpl_GetAvailableVidMem,
3196     /*** IDirectDraw3 ***/
3197     IDirectDrawImpl_GetSurfaceFromDC,
3198     /*** IDirectDraw4 ***/
3199     IDirectDrawImpl_RestoreAllSurfaces,
3200     IDirectDrawImpl_TestCooperativeLevel,
3201     IDirectDrawImpl_GetDeviceIdentifier,
3202     /*** IDirectDraw7 ***/
3203     IDirectDrawImpl_StartModeTest,
3204     IDirectDrawImpl_EvaluateMode
3205 };
3206
3207 /*****************************************************************************
3208  * IDirectDrawImpl_FindDecl
3209  *
3210  * Finds the WineD3D vertex declaration for a specific fvf, and creates one
3211  * if none was found.
3212  *
3213  * This function is in ddraw.c and the DDraw object space because D3D7
3214  * vertex buffers are created using the IDirect3D interface to the ddraw
3215  * object, so they can be valid across D3D devices(theoretically. The ddraw
3216  * object also owns the wined3d device
3217  *
3218  * Parameters:
3219  *  This: Device
3220  *  fvf: Fvf to find the decl for
3221  *
3222  * Returns:
3223  *  NULL in case of an error, the IWineD3DVertexDeclaration interface for the
3224  *  fvf otherwise.
3225  *
3226  *****************************************************************************/
3227 IWineD3DVertexDeclaration *
3228 IDirectDrawImpl_FindDecl(IDirectDrawImpl *This,
3229                          DWORD fvf)
3230 {
3231     HRESULT hr;
3232     IWineD3DVertexDeclaration* pDecl = NULL;
3233     int p, low, high; /* deliberately signed */
3234     struct FvfToDecl *convertedDecls = This->decls;
3235
3236     TRACE("Searching for declaration for fvf %08x... ", fvf);
3237
3238     low = 0;
3239     high = This->numConvertedDecls - 1;
3240     while(low <= high) {
3241         p = (low + high) >> 1;
3242         TRACE("%d ", p);
3243         if(convertedDecls[p].fvf == fvf) {
3244             TRACE("found %p\n", convertedDecls[p].decl);
3245             return convertedDecls[p].decl;
3246         } else if(convertedDecls[p].fvf < fvf) {
3247             low = p + 1;
3248         } else {
3249             high = p - 1;
3250         }
3251     }
3252     TRACE("not found. Creating and inserting at position %d.\n", low);
3253
3254     hr = IWineD3DDevice_CreateVertexDeclarationFromFVF(This->wineD3DDevice, &pDecl,
3255             (IUnknown *)This, &ddraw_null_wined3d_parent_ops, fvf);
3256     if (hr != S_OK) return NULL;
3257
3258     if(This->declArraySize == This->numConvertedDecls) {
3259         int grow = max(This->declArraySize / 2, 8);
3260         convertedDecls = HeapReAlloc(GetProcessHeap(), 0, convertedDecls,
3261                                      sizeof(convertedDecls[0]) * (This->numConvertedDecls + grow));
3262         if(!convertedDecls) {
3263             /* This will destroy it */
3264             IWineD3DVertexDeclaration_Release(pDecl);
3265             return NULL;
3266         }
3267         This->decls = convertedDecls;
3268         This->declArraySize += grow;
3269     }
3270
3271     memmove(convertedDecls + low + 1, convertedDecls + low, sizeof(convertedDecls[0]) * (This->numConvertedDecls - low));
3272     convertedDecls[low].decl = pDecl;
3273     convertedDecls[low].fvf = fvf;
3274     This->numConvertedDecls++;
3275
3276     TRACE("Returning %p. %d decls in array\n", pDecl, This->numConvertedDecls);
3277     return pDecl;
3278 }
3279
3280 /* IWineD3DDeviceParent IUnknown methods */
3281
3282 static inline struct IDirectDrawImpl *ddraw_from_device_parent(IWineD3DDeviceParent *iface)
3283 {
3284     return (struct IDirectDrawImpl *)((char*)iface - FIELD_OFFSET(struct IDirectDrawImpl, device_parent_vtbl));
3285 }
3286
3287 static HRESULT STDMETHODCALLTYPE device_parent_QueryInterface(IWineD3DDeviceParent *iface, REFIID riid, void **object)
3288 {
3289     struct IDirectDrawImpl *This = ddraw_from_device_parent(iface);
3290     return IDirectDrawImpl_QueryInterface((IDirectDraw7 *)This, riid, object);
3291 }
3292
3293 static ULONG STDMETHODCALLTYPE device_parent_AddRef(IWineD3DDeviceParent *iface)
3294 {
3295     struct IDirectDrawImpl *This = ddraw_from_device_parent(iface);
3296     return IDirectDrawImpl_AddRef((IDirectDraw7 *)This);
3297 }
3298
3299 static ULONG STDMETHODCALLTYPE device_parent_Release(IWineD3DDeviceParent *iface)
3300 {
3301     struct IDirectDrawImpl *This = ddraw_from_device_parent(iface);
3302     return IDirectDrawImpl_Release((IDirectDraw7 *)This);
3303 }
3304
3305 /* IWineD3DDeviceParent methods */
3306
3307 static void STDMETHODCALLTYPE device_parent_WineD3DDeviceCreated(IWineD3DDeviceParent *iface, IWineD3DDevice *device)
3308 {
3309     TRACE("iface %p, device %p\n", iface, device);
3310 }
3311
3312 static HRESULT STDMETHODCALLTYPE device_parent_CreateSurface(IWineD3DDeviceParent *iface,
3313         IUnknown *superior, UINT width, UINT height, WINED3DFORMAT format, DWORD usage,
3314         WINED3DPOOL pool, UINT level, WINED3DCUBEMAP_FACES face, IWineD3DSurface **surface)
3315 {
3316     struct IDirectDrawImpl *This = ddraw_from_device_parent(iface);
3317     IDirectDrawSurfaceImpl *surf = NULL;
3318     UINT i = 0;
3319     DDSCAPS2 searchcaps = This->tex_root->surface_desc.ddsCaps;
3320
3321     TRACE("iface %p, superior %p, width %u, height %u, format %#x, usage %#x,\n"
3322             "\tpool %#x, level %u, face %u, surface %p\n",
3323             iface, superior, width, height, format, usage, pool, level, face, surface);
3324
3325     searchcaps.dwCaps2 &= ~DDSCAPS2_CUBEMAP_ALLFACES;
3326     switch(face)
3327     {
3328         case WINED3DCUBEMAP_FACE_POSITIVE_X:
3329             TRACE("Asked for positive x\n");
3330             if (searchcaps.dwCaps2 & DDSCAPS2_CUBEMAP)
3331             {
3332                 searchcaps.dwCaps2 |= DDSCAPS2_CUBEMAP_POSITIVEX;
3333             }
3334             surf = This->tex_root; break;
3335         case WINED3DCUBEMAP_FACE_NEGATIVE_X:
3336             TRACE("Asked for negative x\n");
3337             searchcaps.dwCaps2 |= DDSCAPS2_CUBEMAP_NEGATIVEX; break;
3338         case WINED3DCUBEMAP_FACE_POSITIVE_Y:
3339             TRACE("Asked for positive y\n");
3340             searchcaps.dwCaps2 |= DDSCAPS2_CUBEMAP_POSITIVEY; break;
3341         case WINED3DCUBEMAP_FACE_NEGATIVE_Y:
3342             TRACE("Asked for negative y\n");
3343             searchcaps.dwCaps2 |= DDSCAPS2_CUBEMAP_NEGATIVEY; break;
3344         case WINED3DCUBEMAP_FACE_POSITIVE_Z:
3345             TRACE("Asked for positive z\n");
3346             searchcaps.dwCaps2 |= DDSCAPS2_CUBEMAP_POSITIVEZ; break;
3347         case WINED3DCUBEMAP_FACE_NEGATIVE_Z:
3348             TRACE("Asked for negative z\n");
3349             searchcaps.dwCaps2 |= DDSCAPS2_CUBEMAP_NEGATIVEZ; break;
3350         default: {ERR("Unexpected cube face\n");} /* Stupid compiler */
3351     }
3352
3353     if (!surf)
3354     {
3355         IDirectDrawSurface7 *attached;
3356         IDirectDrawSurface7_GetAttachedSurface((IDirectDrawSurface7 *)This->tex_root, &searchcaps, &attached);
3357         surf = (IDirectDrawSurfaceImpl *)attached;
3358         IDirectDrawSurface7_Release(attached);
3359     }
3360     if (!surf) ERR("root search surface not found\n");
3361
3362     /* Find the wanted mipmap. There are enough mipmaps in the chain */
3363     while (i < level)
3364     {
3365         IDirectDrawSurface7 *attached;
3366         IDirectDrawSurface7_GetAttachedSurface((IDirectDrawSurface7 *)surf, &searchcaps, &attached);
3367         if(!attached) ERR("Surface not found\n");
3368         surf = (IDirectDrawSurfaceImpl *)attached;
3369         IDirectDrawSurface7_Release(attached);
3370         ++i;
3371     }
3372
3373     /* Return the surface */
3374     *surface = surf->WineD3DSurface;
3375     IWineD3DSurface_AddRef(*surface);
3376
3377     TRACE("Returning wineD3DSurface %p, it belongs to surface %p\n", *surface, surf);
3378
3379     return D3D_OK;
3380 }
3381
3382 static HRESULT STDMETHODCALLTYPE device_parent_CreateRenderTarget(IWineD3DDeviceParent *iface,
3383         IUnknown *superior, UINT width, UINT height, WINED3DFORMAT format, WINED3DMULTISAMPLE_TYPE multisample_type,
3384         DWORD multisample_quality, BOOL lockable, IWineD3DSurface **surface)
3385 {
3386     struct IDirectDrawImpl *This = ddraw_from_device_parent(iface);
3387     IDirectDrawSurfaceImpl *d3d_surface = This->d3d_target;
3388     IDirectDrawSurfaceImpl *target = NULL;
3389
3390     TRACE("iface %p, superior %p, width %u, height %u, format %#x, multisample_type %#x,\n"
3391             "\tmultisample_quality %u, lockable %u, surface %p\n",
3392             iface, superior, width, height, format, multisample_type, multisample_quality, lockable, surface);
3393
3394     if (d3d_surface->isRenderTarget)
3395     {
3396         IDirectDrawSurface7_EnumAttachedSurfaces((IDirectDrawSurface7 *)d3d_surface, &target, findRenderTarget);
3397     }
3398     else
3399     {
3400         target = d3d_surface;
3401     }
3402
3403     if (!target)
3404     {
3405         target = This->d3d_target;
3406         ERR(" (%p) : No DirectDrawSurface found to create the back buffer. Using the front buffer as back buffer. Uncertain consequences\n", This);
3407     }
3408
3409     /* TODO: Return failure if the dimensions do not match, but this shouldn't happen */
3410
3411     *surface = target->WineD3DSurface;
3412     IWineD3DSurface_AddRef(*surface);
3413     target->isRenderTarget = TRUE;
3414
3415     TRACE("Returning wineD3DSurface %p, it belongs to surface %p\n", *surface, d3d_surface);
3416
3417     return D3D_OK;
3418 }
3419
3420 static HRESULT STDMETHODCALLTYPE device_parent_CreateDepthStencilSurface(IWineD3DDeviceParent *iface,
3421         IUnknown *superior, UINT width, UINT height, WINED3DFORMAT format, WINED3DMULTISAMPLE_TYPE multisample_type,
3422         DWORD multisample_quality, BOOL discard, IWineD3DSurface **surface)
3423 {
3424     struct IDirectDrawImpl *This = ddraw_from_device_parent(iface);
3425     IDirectDrawSurfaceImpl *ddraw_surface;
3426     DDSURFACEDESC2 ddsd;
3427     HRESULT hr;
3428
3429     TRACE("iface %p, superior %p, width %u, height %u, format %#x, multisample_type %#x,\n"
3430             "\tmultisample_quality %u, discard %u, surface %p\n",
3431             iface, superior, width, height, format, multisample_type, multisample_quality, discard, surface);
3432
3433     *surface = NULL;
3434
3435     /* Create a DirectDraw surface */
3436     memset(&ddsd, 0, sizeof(ddsd));
3437     ddsd.dwSize = sizeof(ddsd);
3438     ddsd.u4.ddpfPixelFormat.dwSize = sizeof(DDPIXELFORMAT);
3439     ddsd.dwFlags = DDSD_PIXELFORMAT | DDSD_WIDTH | DDSD_HEIGHT | DDSD_CAPS;
3440     ddsd.ddsCaps.dwCaps = DDSCAPS_OFFSCREENPLAIN;
3441     ddsd.dwHeight = height;
3442     ddsd.dwWidth = width;
3443     if (format)
3444     {
3445         PixelFormat_WineD3DtoDD(&ddsd.u4.ddpfPixelFormat, format);
3446     }
3447     else
3448     {
3449         ddsd.dwFlags ^= DDSD_PIXELFORMAT;
3450     }
3451
3452     This->depthstencil = TRUE;
3453     hr = IDirectDraw7_CreateSurface((IDirectDraw7 *)This, &ddsd, (IDirectDrawSurface7 **)&ddraw_surface, NULL);
3454     This->depthstencil = FALSE;
3455     if(FAILED(hr))
3456     {
3457         ERR(" (%p) Creating a DepthStencil Surface failed, result = %x\n", This, hr);
3458         return hr;
3459     }
3460
3461     *surface = ddraw_surface->WineD3DSurface;
3462     IWineD3DSurface_AddRef(*surface);
3463     IDirectDrawSurface7_Release((IDirectDrawSurface7 *)ddraw_surface);
3464
3465     return D3D_OK;
3466 }
3467
3468 static HRESULT STDMETHODCALLTYPE device_parent_CreateVolume(IWineD3DDeviceParent *iface,
3469         IUnknown *superior, UINT width, UINT height, UINT depth, WINED3DFORMAT format,
3470         WINED3DPOOL pool, DWORD usage, IWineD3DVolume **volume)
3471 {
3472     TRACE("iface %p, superior %p, width %u, height %u, depth %u, format %#x, pool %#x, usage %#x, volume %p\n",
3473                 iface, superior, width, height, depth, format, pool, usage, volume);
3474
3475     ERR("Not implemented!\n");
3476
3477     return E_NOTIMPL;
3478 }
3479
3480 static HRESULT STDMETHODCALLTYPE device_parent_CreateSwapChain(IWineD3DDeviceParent *iface,
3481         WINED3DPRESENT_PARAMETERS *present_parameters, IWineD3DSwapChain **swapchain)
3482 {
3483     struct IDirectDrawImpl *This = ddraw_from_device_parent(iface);
3484     IDirectDrawSurfaceImpl *iterator;
3485     IParentImpl *object;
3486     HRESULT hr;
3487
3488     TRACE("iface %p, present_parameters %p, swapchain %p\n", iface, present_parameters, swapchain);
3489
3490     object = HeapAlloc(GetProcessHeap(),  HEAP_ZERO_MEMORY, sizeof(IParentImpl));
3491     if (!object)
3492     {
3493         FIXME("Allocation of memory failed\n");
3494         *swapchain = NULL;
3495         return DDERR_OUTOFVIDEOMEMORY;
3496     }
3497
3498     object->lpVtbl = &IParent_Vtbl;
3499     object->ref = 1;
3500
3501     hr = IWineD3DDevice_CreateSwapChain(This->wineD3DDevice, present_parameters,
3502             swapchain, (IUnknown *)object, This->ImplType);
3503     if (FAILED(hr))
3504     {
3505         FIXME("(%p) CreateSwapChain failed, returning %#x\n", iface, hr);
3506         HeapFree(GetProcessHeap(), 0 , object);
3507         *swapchain = NULL;
3508         return hr;
3509     }
3510
3511     object->child = (IUnknown *)*swapchain;
3512     This->d3d_target->wineD3DSwapChain = *swapchain;
3513     iterator = This->d3d_target->complex_array[0];
3514     while (iterator)
3515     {
3516         iterator->wineD3DSwapChain = *swapchain;
3517         iterator = iterator->complex_array[0];
3518     }
3519
3520     return hr;
3521 }
3522
3523 const IWineD3DDeviceParentVtbl ddraw_wined3d_device_parent_vtbl =
3524 {
3525     /* IUnknown methods */
3526     device_parent_QueryInterface,
3527     device_parent_AddRef,
3528     device_parent_Release,
3529     /* IWineD3DDeviceParent methods */
3530     device_parent_WineD3DDeviceCreated,
3531     device_parent_CreateSurface,
3532     device_parent_CreateRenderTarget,
3533     device_parent_CreateDepthStencilSurface,
3534     device_parent_CreateVolume,
3535     device_parent_CreateSwapChain,
3536 };