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