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