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