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