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