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