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