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