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