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