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