strmbase: Add support for rendering algorithms to quality control.
[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  * Copyright 2008 Denver Gingerich
7  *
8  * This library is free software; you can redistribute it and/or
9  * modify it under the terms of the GNU Lesser General Public
10  * License as published by the Free Software Foundation; either
11  * version 2.1 of the License, or (at your option) any later version.
12  *
13  * This library is distributed in the hope that it will be useful,
14  * but WITHOUT ANY WARRANTY; without even the implied warranty of
15  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
16  * Lesser General Public License for more details.
17  *
18  * You should have received a copy of the GNU Lesser General Public
19  * License along with this library; if not, write to the Free Software
20  * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA
21  */
22
23 #include "config.h"
24 #include "wine/port.h"
25
26 #include "ddraw_private.h"
27
28 WINE_DEFAULT_DEBUG_CHANNEL(ddraw);
29
30 /* Device identifier. Don't relay it to WineD3D */
31 static const DDDEVICEIDENTIFIER2 deviceidentifier =
32 {
33     "display",
34     "DirectDraw HAL",
35     { { 0x00010001, 0x00010001 } },
36     0, 0, 0, 0,
37     /* a8373c10-7ac4-4deb-849a-009844d08b2d */
38     {0xa8373c10,0x7ac4,0x4deb, {0x84,0x9a,0x00,0x98,0x44,0xd0,0x8b,0x2d}},
39     0
40 };
41
42 static void STDMETHODCALLTYPE ddraw_null_wined3d_object_destroyed(void *parent) {}
43
44 const struct wined3d_parent_ops ddraw_null_wined3d_parent_ops =
45 {
46     ddraw_null_wined3d_object_destroyed,
47 };
48
49 static inline IDirectDrawImpl *ddraw_from_ddraw1(IDirectDraw *iface)
50 {
51     return (IDirectDrawImpl *)((char*)iface - FIELD_OFFSET(IDirectDrawImpl, IDirectDraw_vtbl));
52 }
53
54 static inline IDirectDrawImpl *ddraw_from_ddraw2(IDirectDraw2 *iface)
55 {
56     return (IDirectDrawImpl *)((char*)iface - FIELD_OFFSET(IDirectDrawImpl, IDirectDraw2_vtbl));
57 }
58
59 static inline IDirectDrawImpl *ddraw_from_ddraw3(IDirectDraw3 *iface)
60 {
61     return (IDirectDrawImpl *)((char*)iface - FIELD_OFFSET(IDirectDrawImpl, IDirectDraw3_vtbl));
62 }
63
64 static inline IDirectDrawImpl *ddraw_from_ddraw4(IDirectDraw4 *iface)
65 {
66     return (IDirectDrawImpl *)((char*)iface - FIELD_OFFSET(IDirectDrawImpl, IDirectDraw4_vtbl));
67 }
68
69 /*****************************************************************************
70  * IUnknown Methods
71  *****************************************************************************/
72
73 /*****************************************************************************
74  * IDirectDraw7::QueryInterface
75  *
76  * Queries different interfaces of the DirectDraw object. It can return
77  * IDirectDraw interfaces in version 1, 2, 4 and 7, and IDirect3D interfaces
78  * in version 1, 2, 3 and 7. An IDirect3DDevice can be created with this
79  * method.
80  * The returned interface is AddRef()-ed before it's returned
81  *
82  * Used for version 1, 2, 4 and 7
83  *
84  * Params:
85  *  refiid: Interface ID asked for
86  *  obj: Used to return the interface pointer
87  *
88  * Returns:
89  *  S_OK if an interface was found
90  *  E_NOINTERFACE if the requested interface wasn't found
91  *
92  *****************************************************************************/
93 static HRESULT WINAPI ddraw7_QueryInterface(IDirectDraw7 *iface, REFIID refiid, void **obj)
94 {
95     IDirectDrawImpl *This = (IDirectDrawImpl *)iface;
96
97     TRACE("iface %p, riid %s, object %p.\n", iface, debugstr_guid(refiid), obj);
98
99     /* Can change surface impl type */
100     EnterCriticalSection(&ddraw_cs);
101
102     /* According to COM docs, if the QueryInterface fails, obj should be set to NULL */
103     *obj = NULL;
104
105     if(!refiid)
106     {
107         LeaveCriticalSection(&ddraw_cs);
108         return DDERR_INVALIDPARAMS;
109     }
110
111     /* Check DirectDraw Interfaces */
112     if ( IsEqualGUID( &IID_IUnknown, refiid ) ||
113          IsEqualGUID( &IID_IDirectDraw7, refiid ) )
114     {
115         *obj = This;
116         TRACE("(%p) Returning IDirectDraw7 interface at %p\n", This, *obj);
117     }
118     else if ( IsEqualGUID( &IID_IDirectDraw4, refiid ) )
119     {
120         *obj = &This->IDirectDraw4_vtbl;
121         TRACE("(%p) Returning IDirectDraw4 interface at %p\n", This, *obj);
122     }
123     else if ( IsEqualGUID( &IID_IDirectDraw3, refiid ) )
124     {
125         /* This Interface exists in ddrawex.dll, it is implemented in a wrapper */
126         WARN("IDirectDraw3 is not valid in ddraw.dll\n");
127         *obj = NULL;
128         LeaveCriticalSection(&ddraw_cs);
129         return E_NOINTERFACE;
130     }
131     else if ( IsEqualGUID( &IID_IDirectDraw2, refiid ) )
132     {
133         *obj = &This->IDirectDraw2_vtbl;
134         TRACE("(%p) Returning IDirectDraw2 interface at %p\n", This, *obj);
135     }
136     else if ( IsEqualGUID( &IID_IDirectDraw, refiid ) )
137     {
138         *obj = &This->IDirectDraw_vtbl;
139         TRACE("(%p) Returning IDirectDraw interface at %p\n", This, *obj);
140     }
141
142     /* Direct3D
143      * The refcount unit test revealed that an IDirect3D7 interface can only be queried
144      * from a DirectDraw object that was created as an IDirectDraw7 interface. No idea
145      * who had this idea and why. The older interfaces can query and IDirect3D version
146      * because they are all created as IDirectDraw(1). This isn't really crucial behavior,
147      * and messy to implement with the common creation function, so it has been left out here.
148      */
149     else if ( IsEqualGUID( &IID_IDirect3D  , refiid ) ||
150               IsEqualGUID( &IID_IDirect3D2 , refiid ) ||
151               IsEqualGUID( &IID_IDirect3D3 , refiid ) ||
152               IsEqualGUID( &IID_IDirect3D7 , refiid ) )
153     {
154         /* Check the surface implementation */
155         if(This->ImplType == SURFACE_UNKNOWN)
156         {
157             /* Apps may create the IDirect3D Interface before the primary surface.
158              * set the surface implementation */
159             This->ImplType = SURFACE_OPENGL;
160             TRACE("(%p) Choosing OpenGL surfaces because a Direct3D interface was requested\n", This);
161         }
162         else if(This->ImplType != SURFACE_OPENGL && DefaultSurfaceType == SURFACE_UNKNOWN)
163         {
164             ERR("(%p) The App is requesting a D3D device, but a non-OpenGL surface type was choosen. Prepare for trouble!\n", This);
165             ERR(" (%p) You may want to contact wine-devel for help\n", This);
166             /* Should I assert(0) here??? */
167         }
168         else if(This->ImplType != SURFACE_OPENGL)
169         {
170             WARN("The app requests a Direct3D interface, but non-opengl surfaces where set in winecfg\n");
171             /* Do not abort here, only reject 3D Device creation */
172         }
173
174         if ( IsEqualGUID( &IID_IDirect3D  , refiid ) )
175         {
176             This->d3dversion = 1;
177             *obj = &This->IDirect3D_vtbl;
178             TRACE(" returning Direct3D interface at %p.\n", *obj);
179         }
180         else if ( IsEqualGUID( &IID_IDirect3D2  , refiid ) )
181         {
182             This->d3dversion = 2;
183             *obj = &This->IDirect3D2_vtbl;
184             TRACE(" returning Direct3D2 interface at %p.\n", *obj);
185         }
186         else if ( IsEqualGUID( &IID_IDirect3D3  , refiid ) )
187         {
188             This->d3dversion = 3;
189             *obj = &This->IDirect3D3_vtbl;
190             TRACE(" returning Direct3D3 interface at %p.\n", *obj);
191         }
192         else if(IsEqualGUID( &IID_IDirect3D7  , refiid ))
193         {
194             This->d3dversion = 7;
195             *obj = &This->IDirect3D7_vtbl;
196             TRACE(" returning Direct3D7 interface at %p.\n", *obj);
197         }
198     }
199     else if (IsEqualGUID(refiid, &IID_IWineD3DDeviceParent))
200     {
201         *obj = &This->device_parent_vtbl;
202     }
203
204     /* Unknown interface */
205     else
206     {
207         ERR("(%p)->(%s, %p): No interface found\n", This, debugstr_guid(refiid), obj);
208         LeaveCriticalSection(&ddraw_cs);
209         return E_NOINTERFACE;
210     }
211
212     IUnknown_AddRef( (IUnknown *) *obj );
213     LeaveCriticalSection(&ddraw_cs);
214     return S_OK;
215 }
216
217 static HRESULT WINAPI ddraw4_QueryInterface(IDirectDraw4 *iface, REFIID riid, void **object)
218 {
219     TRACE("iface %p, riid %s, object %p.\n", iface, debugstr_guid(riid), object);
220
221     return ddraw7_QueryInterface((IDirectDraw7 *)ddraw_from_ddraw4(iface), riid, object);
222 }
223
224 static HRESULT WINAPI ddraw3_QueryInterface(IDirectDraw3 *iface, REFIID riid, void **object)
225 {
226     TRACE("iface %p, riid %s, object %p.\n", iface, debugstr_guid(riid), object);
227
228     return ddraw7_QueryInterface((IDirectDraw7 *)ddraw_from_ddraw3(iface), riid, object);
229 }
230
231 static HRESULT WINAPI ddraw2_QueryInterface(IDirectDraw2 *iface, REFIID riid, void **object)
232 {
233     TRACE("iface %p, riid %s, object %p.\n", iface, debugstr_guid(riid), object);
234
235     return ddraw7_QueryInterface((IDirectDraw7 *)ddraw_from_ddraw2(iface), riid, object);
236 }
237
238 static HRESULT WINAPI ddraw1_QueryInterface(IDirectDraw *iface, REFIID riid, void **object)
239 {
240     TRACE("iface %p, riid %s, object %p.\n", iface, debugstr_guid(riid), object);
241
242     return ddraw7_QueryInterface((IDirectDraw7 *)ddraw_from_ddraw1(iface), riid, object);
243 }
244
245 static HRESULT WINAPI d3d7_QueryInterface(IDirect3D7 *iface, REFIID riid, void **object)
246 {
247     TRACE("iface %p, riid %s, object %p.\n", iface, debugstr_guid(riid), object);
248
249     return ddraw7_QueryInterface((IDirectDraw7 *)ddraw_from_d3d7(iface), riid, object);
250 }
251
252 static HRESULT WINAPI d3d3_QueryInterface(IDirect3D3 *iface, REFIID riid, void **object)
253 {
254     TRACE("iface %p, riid %s, object %p.\n", iface, debugstr_guid(riid), object);
255
256     return ddraw7_QueryInterface((IDirectDraw7 *)ddraw_from_d3d3(iface), riid, object);
257 }
258
259 static HRESULT WINAPI d3d2_QueryInterface(IDirect3D2 *iface, REFIID riid, void **object)
260 {
261     TRACE("iface %p, riid %s, object %p.\n", iface, debugstr_guid(riid), object);
262
263     return ddraw7_QueryInterface((IDirectDraw7 *)ddraw_from_d3d2(iface), riid, object);
264 }
265
266 static HRESULT WINAPI d3d1_QueryInterface(IDirect3D *iface, REFIID riid, void **object)
267 {
268     TRACE("iface %p, riid %s, object %p.\n", iface, debugstr_guid(riid), object);
269
270     return ddraw7_QueryInterface((IDirectDraw7 *)ddraw_from_d3d1(iface), riid, object);
271 }
272
273 /*****************************************************************************
274  * IDirectDraw7::AddRef
275  *
276  * Increases the interfaces refcount, basically
277  *
278  * DDraw refcounting is a bit tricky. The different DirectDraw interface
279  * versions have individual refcounts, but the IDirect3D interfaces do not.
280  * All interfaces are from one object, that means calling QueryInterface on an
281  * IDirectDraw7 interface for an IDirectDraw4 interface does not create a new
282  * IDirectDrawImpl object.
283  *
284  * That means all AddRef and Release implementations of IDirectDrawX work
285  * with their own counter, and IDirect3DX::AddRef thunk to IDirectDraw (1),
286  * except of IDirect3D7 which thunks to IDirectDraw7
287  *
288  * Returns: The new refcount
289  *
290  *****************************************************************************/
291 static ULONG WINAPI ddraw7_AddRef(IDirectDraw7 *iface)
292 {
293     IDirectDrawImpl *This = (IDirectDrawImpl *)iface;
294     ULONG ref = InterlockedIncrement(&This->ref7);
295
296     TRACE("%p increasing refcount to %u.\n", This, ref);
297
298     if(ref == 1) InterlockedIncrement(&This->numIfaces);
299
300     return ref;
301 }
302
303 static ULONG WINAPI ddraw4_AddRef(IDirectDraw4 *iface)
304 {
305     IDirectDrawImpl *ddraw = ddraw_from_ddraw4(iface);
306     ULONG ref = InterlockedIncrement(&ddraw->ref4);
307
308     TRACE("%p increasing refcount to %u.\n", ddraw, ref);
309
310     if (ref == 1) InterlockedIncrement(&ddraw->numIfaces);
311
312     return ref;
313 }
314
315 static ULONG WINAPI ddraw3_AddRef(IDirectDraw3 *iface)
316 {
317     IDirectDrawImpl *ddraw = ddraw_from_ddraw3(iface);
318     ULONG ref = InterlockedIncrement(&ddraw->ref3);
319
320     TRACE("%p increasing refcount to %u.\n", ddraw, ref);
321
322     if (ref == 1) InterlockedIncrement(&ddraw->numIfaces);
323
324     return ref;
325 }
326
327 static ULONG WINAPI ddraw2_AddRef(IDirectDraw2 *iface)
328 {
329     IDirectDrawImpl *ddraw = ddraw_from_ddraw2(iface);
330     ULONG ref = InterlockedIncrement(&ddraw->ref2);
331
332     TRACE("%p increasing refcount to %u.\n", ddraw, ref);
333
334     if (ref == 1) InterlockedIncrement(&ddraw->numIfaces);
335
336     return ref;
337 }
338
339 static ULONG WINAPI ddraw1_AddRef(IDirectDraw *iface)
340 {
341     IDirectDrawImpl *ddraw = ddraw_from_ddraw1(iface);
342     ULONG ref = InterlockedIncrement(&ddraw->ref1);
343
344     TRACE("%p increasing refcount to %u.\n", ddraw, ref);
345
346     if (ref == 1) InterlockedIncrement(&ddraw->numIfaces);
347
348     return ref;
349 }
350
351 static ULONG WINAPI d3d7_AddRef(IDirect3D7 *iface)
352 {
353     TRACE("iface %p.\n", iface);
354
355     return ddraw7_AddRef((IDirectDraw7 *)ddraw_from_d3d7(iface));
356 }
357
358 static ULONG WINAPI d3d3_AddRef(IDirect3D3 *iface)
359 {
360     TRACE("iface %p.\n", iface);
361
362     return ddraw1_AddRef((IDirectDraw *)&ddraw_from_d3d3(iface)->IDirectDraw_vtbl);
363 }
364
365 static ULONG WINAPI d3d2_AddRef(IDirect3D2 *iface)
366 {
367     TRACE("iface %p.\n", iface);
368
369     return ddraw1_AddRef((IDirectDraw *)&ddraw_from_d3d2(iface)->IDirectDraw_vtbl);
370 }
371
372 static ULONG WINAPI d3d1_AddRef(IDirect3D *iface)
373 {
374     TRACE("iface %p.\n", iface);
375
376     return ddraw1_AddRef((IDirectDraw *)&ddraw_from_d3d1(iface)->IDirectDraw_vtbl);
377 }
378
379 /*****************************************************************************
380  * ddraw_destroy
381  *
382  * Destroys a ddraw object if all refcounts are 0. This is to share code
383  * between the IDirectDrawX::Release functions
384  *
385  * Params:
386  *  This: DirectDraw object to destroy
387  *
388  *****************************************************************************/
389 static void ddraw_destroy(IDirectDrawImpl *This)
390 {
391     IDirectDraw7_SetCooperativeLevel((IDirectDraw7 *)This, NULL, DDSCL_NORMAL);
392     IDirectDraw7_RestoreDisplayMode((IDirectDraw7 *)This);
393
394     /* Destroy the device window if we created one */
395     if(This->devicewindow != 0)
396     {
397         TRACE(" (%p) Destroying the device window %p\n", This, This->devicewindow);
398         DestroyWindow(This->devicewindow);
399         This->devicewindow = 0;
400     }
401
402     EnterCriticalSection(&ddraw_cs);
403     list_remove(&This->ddraw_list_entry);
404     LeaveCriticalSection(&ddraw_cs);
405
406     /* Release the attached WineD3D stuff */
407     IWineD3DDevice_Release(This->wineD3DDevice);
408     IWineD3D_Release(This->wineD3D);
409
410     /* Now free the object */
411     HeapFree(GetProcessHeap(), 0, This);
412 }
413
414 /*****************************************************************************
415  * IDirectDraw7::Release
416  *
417  * Decreases the refcount. If the refcount falls to 0, the object is destroyed
418  *
419  * Returns: The new refcount
420  *****************************************************************************/
421 static ULONG WINAPI ddraw7_Release(IDirectDraw7 *iface)
422 {
423     IDirectDrawImpl *This = (IDirectDrawImpl *)iface;
424     ULONG ref = InterlockedDecrement(&This->ref7);
425
426     TRACE("%p decreasing refcount to %u.\n", This, ref);
427
428     if (!ref && !InterlockedDecrement(&This->numIfaces))
429         ddraw_destroy(This);
430
431     return ref;
432 }
433
434 static ULONG WINAPI ddraw4_Release(IDirectDraw4 *iface)
435 {
436     IDirectDrawImpl *ddraw = ddraw_from_ddraw4(iface);
437     ULONG ref = InterlockedDecrement(&ddraw->ref4);
438
439     TRACE("%p decreasing refcount to %u.\n", ddraw, ref);
440
441     if (!ref && !InterlockedDecrement(&ddraw->numIfaces))
442         ddraw_destroy(ddraw);
443
444     return ref;
445 }
446
447 static ULONG WINAPI ddraw3_Release(IDirectDraw3 *iface)
448 {
449     IDirectDrawImpl *ddraw = ddraw_from_ddraw3(iface);
450     ULONG ref = InterlockedDecrement(&ddraw->ref3);
451
452     TRACE("%p decreasing refcount to %u.\n", ddraw, ref);
453
454     if (!ref && !InterlockedDecrement(&ddraw->numIfaces))
455         ddraw_destroy(ddraw);
456
457     return ref;
458 }
459
460 static ULONG WINAPI ddraw2_Release(IDirectDraw2 *iface)
461 {
462     IDirectDrawImpl *ddraw = ddraw_from_ddraw2(iface);
463     ULONG ref = InterlockedDecrement(&ddraw->ref2);
464
465     TRACE("%p decreasing refcount to %u.\n", ddraw, ref);
466
467     if (!ref && !InterlockedDecrement(&ddraw->numIfaces))
468         ddraw_destroy(ddraw);
469
470     return ref;
471 }
472
473 static ULONG WINAPI ddraw1_Release(IDirectDraw *iface)
474 {
475     IDirectDrawImpl *ddraw = ddraw_from_ddraw1(iface);
476     ULONG ref = InterlockedDecrement(&ddraw->ref1);
477
478     TRACE("%p decreasing refcount to %u.\n", ddraw, ref);
479
480     if (!ref && !InterlockedDecrement(&ddraw->numIfaces))
481         ddraw_destroy(ddraw);
482
483     return ref;
484 }
485
486 static ULONG WINAPI d3d7_Release(IDirect3D7 *iface)
487 {
488     TRACE("iface %p.\n", iface);
489
490     return ddraw7_Release((IDirectDraw7 *)ddraw_from_d3d7(iface));
491 }
492
493 static ULONG WINAPI d3d3_Release(IDirect3D3 *iface)
494 {
495     TRACE("iface %p.\n", iface);
496
497     return ddraw1_Release((IDirectDraw *)&ddraw_from_d3d3(iface)->IDirectDraw_vtbl);
498 }
499
500 static ULONG WINAPI d3d2_Release(IDirect3D2 *iface)
501 {
502     TRACE("iface %p.\n", iface);
503
504     return ddraw1_Release((IDirectDraw *)&ddraw_from_d3d2(iface)->IDirectDraw_vtbl);
505 }
506
507 static ULONG WINAPI d3d1_Release(IDirect3D *iface)
508 {
509     TRACE("iface %p.\n", iface);
510
511     return ddraw1_Release((IDirectDraw *)&ddraw_from_d3d1(iface)->IDirectDraw_vtbl);
512 }
513
514 /*****************************************************************************
515  * IDirectDraw methods
516  *****************************************************************************/
517
518 /*****************************************************************************
519  * IDirectDraw7::SetCooperativeLevel
520  *
521  * Sets the cooperative level for the DirectDraw object, and the window
522  * assigned to it. The cooperative level determines the general behavior
523  * of the DirectDraw application
524  *
525  * Warning: This is quite tricky, as it's not really documented which
526  * cooperative levels can be combined with each other. If a game fails
527  * after this function, try to check the cooperative levels passed on
528  * Windows, and if it returns something different.
529  *
530  * If you think that this function caused the failure because it writes a
531  * fixme, be sure to run again with a +ddraw trace.
532  *
533  * What is known about cooperative levels (See the ddraw modes test):
534  * DDSCL_EXCLUSIVE and DDSCL_FULLSCREEN must be used with each other
535  * DDSCL_NORMAL is not compatible with DDSCL_EXCLUSIVE or DDSCL_FULLSCREEN
536  * DDSCL_SETFOCUSWINDOW can be passed only in DDSCL_NORMAL mode, but after that
537  * DDSCL_FULLSCREEN can be activated
538  * DDSCL_SETFOCUSWINDOW may only be used with DDSCL_NOWINDOWCHANGES
539  *
540  * Handled flags: DDSCL_NORMAL, DDSCL_FULLSCREEN, DDSCL_EXCLUSIVE,
541  *                DDSCL_SETFOCUSWINDOW (partially),
542  *                DDSCL_MULTITHREADED (work in progress)
543  *
544  * Unhandled flags, which should be implemented
545  *  DDSCL_SETDEVICEWINDOW: Sets a window specially used for rendering (I don't
546  *  expect any difference to a normal window for wine)
547  *  DDSCL_CREATEDEVICEWINDOW: Tells ddraw to create its own window for
548  *  rendering (Possible test case: Half-Life)
549  *
550  * Unsure about these: DDSCL_FPUSETUP DDSCL_FPURESERVE
551  *
552  * These don't seem very important for wine:
553  *  DDSCL_ALLOWREBOOT, DDSCL_NOWINDOWCHANGES, DDSCL_ALLOWMODEX
554  *
555  * Returns:
556  *  DD_OK if the cooperative level was set successfully
557  *  DDERR_INVALIDPARAMS if the passed cooperative level combination is invalid
558  *  DDERR_HWNDALREADYSET if DDSCL_SETFOCUSWINDOW is passed in exclusive mode
559  *   (Probably others too, have to investigate)
560  *
561  *****************************************************************************/
562 static HRESULT WINAPI ddraw7_SetCooperativeLevel(IDirectDraw7 *iface, HWND hwnd, DWORD cooplevel)
563 {
564     IDirectDrawImpl *This = (IDirectDrawImpl *)iface;
565     HWND window;
566
567     TRACE("iface %p, window %p, flags %#x.\n", iface, hwnd, cooplevel);
568     DDRAW_dump_cooperativelevel(cooplevel);
569
570     EnterCriticalSection(&ddraw_cs);
571
572     /* Get the old window */
573     window = This->dest_window;
574
575     /* Tests suggest that we need one of them: */
576     if(!(cooplevel & (DDSCL_SETFOCUSWINDOW |
577                       DDSCL_NORMAL         |
578                       DDSCL_EXCLUSIVE      )))
579     {
580         TRACE("Incorrect cooplevel flags, returning DDERR_INVALIDPARAMS\n");
581         LeaveCriticalSection(&ddraw_cs);
582         return DDERR_INVALIDPARAMS;
583     }
584
585     /* Handle those levels first which set various hwnds */
586     if(cooplevel & DDSCL_SETFOCUSWINDOW)
587     {
588         /* This isn't compatible with a lot of flags */
589         if(cooplevel & ( DDSCL_MULTITHREADED      |
590                          DDSCL_CREATEDEVICEWINDOW |
591                          DDSCL_FPUSETUP           |
592                          DDSCL_FPUPRESERVE        |
593                          DDSCL_ALLOWREBOOT        |
594                          DDSCL_ALLOWMODEX         |
595                          DDSCL_SETDEVICEWINDOW    |
596                          DDSCL_NORMAL             |
597                          DDSCL_EXCLUSIVE          |
598                          DDSCL_FULLSCREEN         ) )
599         {
600             TRACE("Called with incompatible flags, returning DDERR_INVALIDPARAMS\n");
601             LeaveCriticalSection(&ddraw_cs);
602             return DDERR_INVALIDPARAMS;
603         }
604
605         if( (This->cooperative_level & DDSCL_EXCLUSIVE) && window )
606         {
607             TRACE("Setting DDSCL_SETFOCUSWINDOW with an already set window, returning DDERR_HWNDALREADYSET\n");
608             LeaveCriticalSection(&ddraw_cs);
609             return DDERR_HWNDALREADYSET;
610         }
611
612         This->focuswindow = hwnd;
613         /* Won't use the hwnd param for anything else */
614         hwnd = NULL;
615
616         /* Use the focus window for drawing too */
617         This->dest_window = This->focuswindow;
618
619         /* Destroy the device window, if we have one */
620         if(This->devicewindow)
621         {
622             DestroyWindow(This->devicewindow);
623             This->devicewindow = NULL;
624         }
625
626         LeaveCriticalSection(&ddraw_cs);
627         return DD_OK;
628     }
629
630     if(cooplevel & DDSCL_EXCLUSIVE)
631     {
632         if( !(cooplevel & DDSCL_FULLSCREEN) || !hwnd )
633         {
634             TRACE("(%p) DDSCL_EXCLUSIVE needs DDSCL_FULLSCREEN and a window\n", This);
635             LeaveCriticalSection(&ddraw_cs);
636             return DDERR_INVALIDPARAMS;
637         }
638     }
639     else if( !(cooplevel & DDSCL_NORMAL) )
640     {
641         TRACE("(%p) SetCooperativeLevel needs at least SetFocusWindow or Exclusive or Normal mode\n", This);
642         LeaveCriticalSection(&ddraw_cs);
643         return DDERR_INVALIDPARAMS;
644      }
645
646     /* Do we switch from fullscreen to non-fullscreen ? */
647     if (!(cooplevel & DDSCL_FULLSCREEN) && (This->cooperative_level & DDSCL_FULLSCREEN))
648     {
649         IWineD3DDevice_ReleaseFocusWindow(This->wineD3DDevice);
650         IWineD3DDevice_RestoreFullscreenWindow(This->wineD3DDevice, This->dest_window);
651     }
652
653     /* Don't override focus windows or private device windows */
654     if (hwnd && !This->focuswindow && !This->devicewindow && (hwnd != window))
655     {
656         if (cooplevel & DDSCL_FULLSCREEN)
657         {
658             WINED3DDISPLAYMODE display_mode;
659             HRESULT hr;
660
661             IWineD3D_GetAdapterDisplayMode(This->wineD3D, WINED3DADAPTER_DEFAULT, &display_mode);
662             IWineD3DDevice_SetupFullscreenWindow(This->wineD3DDevice, hwnd, display_mode.Width, display_mode.Height);
663             hr = IWineD3DDevice_AcquireFocusWindow(This->wineD3DDevice, hwnd);
664             if (FAILED(hr))
665             {
666                 ERR("Failed to acquire focus window, hr %#x.\n", hr);
667                 LeaveCriticalSection(&ddraw_cs);
668                 return hr;
669             }
670         }
671         This->dest_window = hwnd;
672     }
673
674     if(cooplevel & DDSCL_CREATEDEVICEWINDOW)
675     {
676         /* Don't create a device window if a focus window is set */
677         if( !(This->focuswindow) )
678         {
679             HWND devicewindow = CreateWindowExA(0, DDRAW_WINDOW_CLASS_NAME, "DDraw device window",
680                     WS_POPUP, 0, 0, GetSystemMetrics(SM_CXSCREEN), GetSystemMetrics(SM_CYSCREEN),
681                     NULL, NULL, NULL, NULL);
682             if (!devicewindow)
683             {
684                 ERR("Failed to create window, last error %#x.\n", GetLastError());
685                 LeaveCriticalSection(&ddraw_cs);
686                 return E_FAIL;
687             }
688
689             ShowWindow(devicewindow, SW_SHOW);   /* Just to be sure */
690             TRACE("(%p) Created a DDraw device window. HWND=%p\n", This, devicewindow);
691
692             This->devicewindow = devicewindow;
693             This->dest_window = devicewindow;
694         }
695     }
696
697     if(cooplevel & DDSCL_MULTITHREADED && !(This->cooperative_level & DDSCL_MULTITHREADED))
698     {
699         /* Enable thread safety in wined3d */
700         IWineD3DDevice_SetMultithreaded(This->wineD3DDevice);
701     }
702
703     /* Unhandled flags */
704     if(cooplevel & DDSCL_ALLOWREBOOT)
705         WARN("(%p) Unhandled flag DDSCL_ALLOWREBOOT, harmless\n", This);
706     if(cooplevel & DDSCL_ALLOWMODEX)
707         WARN("(%p) Unhandled flag DDSCL_ALLOWMODEX, harmless\n", This);
708     if(cooplevel & DDSCL_FPUSETUP)
709         WARN("(%p) Unhandled flag DDSCL_FPUSETUP, harmless\n", This);
710
711     /* Store the cooperative_level */
712     This->cooperative_level = cooplevel;
713     TRACE("SetCooperativeLevel retuning DD_OK\n");
714     LeaveCriticalSection(&ddraw_cs);
715     return DD_OK;
716 }
717
718 static HRESULT WINAPI ddraw4_SetCooperativeLevel(IDirectDraw4 *iface, HWND window, DWORD flags)
719 {
720     TRACE("iface %p, window %p, flags %#x.\n", iface, window, flags);
721
722     return ddraw7_SetCooperativeLevel((IDirectDraw7 *)ddraw_from_ddraw4(iface), window, flags);
723 }
724
725 static HRESULT WINAPI ddraw3_SetCooperativeLevel(IDirectDraw3 *iface, HWND window, DWORD flags)
726 {
727     TRACE("iface %p, window %p, flags %#x.\n", iface, window, flags);
728
729     return ddraw7_SetCooperativeLevel((IDirectDraw7 *)ddraw_from_ddraw3(iface), window, flags);
730 }
731
732 static HRESULT WINAPI ddraw2_SetCooperativeLevel(IDirectDraw2 *iface, HWND window, DWORD flags)
733 {
734     TRACE("iface %p, window %p, flags %#x.\n", iface, window, flags);
735
736     return ddraw7_SetCooperativeLevel((IDirectDraw7 *)ddraw_from_ddraw2(iface), window, flags);
737 }
738
739 static HRESULT WINAPI ddraw1_SetCooperativeLevel(IDirectDraw *iface, HWND window, DWORD flags)
740 {
741     TRACE("iface %p, window %p, flags %#x.\n", iface, window, flags);
742
743     return ddraw7_SetCooperativeLevel((IDirectDraw7 *)ddraw_from_ddraw1(iface), window, flags);
744 }
745
746 /*****************************************************************************
747  *
748  * Helper function for SetDisplayMode and RestoreDisplayMode
749  *
750  * Implements DirectDraw's SetDisplayMode, but ignores the value of
751  * ForceRefreshRate, since it is already handled by
752  * ddraw7_SetDisplayMode.  RestoreDisplayMode can use this function
753  * without worrying that ForceRefreshRate will override the refresh rate.  For
754  * argument and return value documentation, see
755  * ddraw7_SetDisplayMode.
756  *
757  *****************************************************************************/
758 static HRESULT ddraw_set_display_mode(IDirectDraw7 *iface, DWORD Width, DWORD Height,
759         DWORD BPP, DWORD RefreshRate, DWORD Flags)
760 {
761     IDirectDrawImpl *This = (IDirectDrawImpl *)iface;
762     WINED3DDISPLAYMODE Mode;
763     HRESULT hr;
764
765     TRACE("iface %p, width %u, height %u, bpp %u, refresh_rate %u, flags %#x.\n",
766             iface, Width, Height, BPP, RefreshRate, Flags);
767
768     EnterCriticalSection(&ddraw_cs);
769     if( !Width || !Height )
770     {
771         ERR("Width %u, Height %u, what to do?\n", Width, Height);
772         /* It looks like Need for Speed Porsche Unleashed expects DD_OK here */
773         LeaveCriticalSection(&ddraw_cs);
774         return DD_OK;
775     }
776
777     /* Check the exclusive mode
778     if(!(This->cooperative_level & DDSCL_EXCLUSIVE))
779         return DDERR_NOEXCLUSIVEMODE;
780      * This is WRONG. Don't know if the SDK is completely
781      * wrong and if there are any conditions when DDERR_NOEXCLUSIVE
782      * is returned, but Half-Life 1.1.1.1 (Steam version)
783      * depends on this
784      */
785
786     Mode.Width = Width;
787     Mode.Height = Height;
788     Mode.RefreshRate = RefreshRate;
789     switch(BPP)
790     {
791         case 8:  Mode.Format = WINED3DFMT_P8_UINT;          break;
792         case 15: Mode.Format = WINED3DFMT_B5G5R5X1_UNORM;   break;
793         case 16: Mode.Format = WINED3DFMT_B5G6R5_UNORM;     break;
794         case 24: Mode.Format = WINED3DFMT_B8G8R8_UNORM;     break;
795         case 32: Mode.Format = WINED3DFMT_B8G8R8X8_UNORM;   break;
796     }
797
798     /* TODO: The possible return values from msdn suggest that
799      * the screen mode can't be changed if a surface is locked
800      * or some drawing is in progress
801      */
802
803     /* TODO: Lose the primary surface */
804     hr = IWineD3DDevice_SetDisplayMode(This->wineD3DDevice,
805                                        0, /* First swapchain */
806                                        &Mode);
807     IWineD3DDevice_RestoreFullscreenWindow(This->wineD3DDevice, This->dest_window);
808     IWineD3DDevice_SetupFullscreenWindow(This->wineD3DDevice, This->dest_window, Width, Height);
809     LeaveCriticalSection(&ddraw_cs);
810     switch(hr)
811     {
812         case WINED3DERR_NOTAVAILABLE:       return DDERR_UNSUPPORTED;
813         default:                            return hr;
814     }
815 }
816
817 /*****************************************************************************
818  * IDirectDraw7::SetDisplayMode
819  *
820  * Sets the display screen resolution, color depth and refresh frequency
821  * when in fullscreen mode (in theory).
822  * Possible return values listed in the SDK suggest that this method fails
823  * when not in fullscreen mode, but this is wrong. Windows 2000 happily sets
824  * the display mode in DDSCL_NORMAL mode without an hwnd specified.
825  * It seems to be valid to pass 0 for With and Height, this has to be tested
826  * It could mean that the current video mode should be left as-is. (But why
827  * call it then?)
828  *
829  * Params:
830  *  Height, Width: Screen dimension
831  *  BPP: Color depth in Bits per pixel
832  *  Refreshrate: Screen refresh rate
833  *  Flags: Other stuff
834  *
835  * Returns
836  *  DD_OK on success
837  *
838  *****************************************************************************/
839 static HRESULT WINAPI ddraw7_SetDisplayMode(IDirectDraw7 *iface, DWORD Width, DWORD Height,
840         DWORD BPP, DWORD RefreshRate, DWORD Flags)
841 {
842     TRACE("iface %p, width %u, height %u, bpp %u, refresh_rate %u, flags %#x.\n",
843             iface, Width, Height, BPP, RefreshRate, Flags);
844
845     if (force_refresh_rate != 0)
846     {
847         TRACE("ForceRefreshRate overriding passed-in refresh rate (%u Hz) to %u Hz\n",
848                 RefreshRate, force_refresh_rate);
849         RefreshRate = force_refresh_rate;
850     }
851
852     return ddraw_set_display_mode(iface, Width, Height, BPP, RefreshRate, Flags);
853 }
854
855 static HRESULT WINAPI ddraw4_SetDisplayMode(IDirectDraw4 *iface,
856         DWORD width, DWORD height, DWORD bpp, DWORD refresh_rate, DWORD flags)
857 {
858     TRACE("iface %p, width %u, height %u, bpp %u, refresh_rate %u, flags %#x.\n",
859             iface, width, height, bpp, refresh_rate, flags);
860
861     return ddraw7_SetDisplayMode((IDirectDraw7 *)ddraw_from_ddraw4(iface),
862             width, height, bpp, refresh_rate, flags);
863 }
864
865 static HRESULT WINAPI ddraw3_SetDisplayMode(IDirectDraw3 *iface,
866         DWORD width, DWORD height, DWORD bpp, DWORD refresh_rate, DWORD flags)
867 {
868     TRACE("iface %p, width %u, height %u, bpp %u, refresh_rate %u, flags %#x.\n",
869             iface, width, height, bpp, refresh_rate, flags);
870
871     return ddraw7_SetDisplayMode((IDirectDraw7 *)ddraw_from_ddraw3(iface),
872             width, height, bpp, refresh_rate, flags);
873 }
874
875 static HRESULT WINAPI ddraw2_SetDisplayMode(IDirectDraw2 *iface,
876         DWORD width, DWORD height, DWORD bpp, DWORD refresh_rate, DWORD flags)
877 {
878     TRACE("iface %p, width %u, height %u, bpp %u, refresh_rate %u, flags %#x.\n",
879             iface, width, height, bpp, refresh_rate, flags);
880
881     return ddraw7_SetDisplayMode((IDirectDraw7 *)ddraw_from_ddraw2(iface),
882             width, height, bpp, refresh_rate, flags);
883 }
884
885 static HRESULT WINAPI ddraw1_SetDisplayMode(IDirectDraw *iface, DWORD width, DWORD height, DWORD bpp)
886 {
887     TRACE("iface %p, width %u, height %u, bpp %u.\n", iface, width, height, bpp);
888
889     return ddraw7_SetDisplayMode((IDirectDraw7 *)ddraw_from_ddraw1(iface), width, height, bpp, 0, 0);
890 }
891
892 /*****************************************************************************
893  * IDirectDraw7::RestoreDisplayMode
894  *
895  * Restores the display mode to what it was at creation time. Basically.
896  *
897  * A problem arises when there are 2 DirectDraw objects using the same hwnd:
898  *  -> DD_1 finds the screen at 1400x1050x32 when created, sets it to 640x480x16
899  *  -> DD_2 is created, finds the screen at 640x480x16, sets it to 1024x768x32
900  *  -> DD_1 is released. The screen should be left at 1024x768x32.
901  *  -> DD_2 is released. The screen should be set to 1400x1050x32
902  * This case is unhandled right now, but Empire Earth does it this way.
903  * (But perhaps there is something in SetCooperativeLevel to prevent this)
904  *
905  * The msdn says that this method resets the display mode to what it was before
906  * SetDisplayMode was called. What if SetDisplayModes is called 2 times??
907  *
908  * Returns
909  *  DD_OK on success
910  *  DDERR_NOEXCLUSIVE mode if the device isn't in fullscreen mode
911  *
912  *****************************************************************************/
913 static HRESULT WINAPI ddraw7_RestoreDisplayMode(IDirectDraw7 *iface)
914 {
915     IDirectDrawImpl *This = (IDirectDrawImpl *)iface;
916
917     TRACE("iface %p.\n", iface);
918
919     return ddraw_set_display_mode(iface, This->orig_width, This->orig_height, This->orig_bpp, 0, 0);
920 }
921
922 static HRESULT WINAPI ddraw4_RestoreDisplayMode(IDirectDraw4 *iface)
923 {
924     TRACE("iface %p.\n", iface);
925
926     return ddraw7_RestoreDisplayMode((IDirectDraw7 *)ddraw_from_ddraw4(iface));
927 }
928
929 static HRESULT WINAPI ddraw3_RestoreDisplayMode(IDirectDraw3 *iface)
930 {
931     TRACE("iface %p.\n", iface);
932
933     return ddraw7_RestoreDisplayMode((IDirectDraw7 *)ddraw_from_ddraw3(iface));
934 }
935
936 static HRESULT WINAPI ddraw2_RestoreDisplayMode(IDirectDraw2 *iface)
937 {
938     TRACE("iface %p.\n", iface);
939
940     return ddraw7_RestoreDisplayMode((IDirectDraw7 *)ddraw_from_ddraw2(iface));
941 }
942
943 static HRESULT WINAPI ddraw1_RestoreDisplayMode(IDirectDraw *iface)
944 {
945     TRACE("iface %p.\n", iface);
946
947     return ddraw7_RestoreDisplayMode((IDirectDraw7 *)ddraw_from_ddraw1(iface));
948 }
949
950 /*****************************************************************************
951  * IDirectDraw7::GetCaps
952  *
953  * Returns the drives capabilities
954  *
955  * Used for version 1, 2, 4 and 7
956  *
957  * Params:
958  *  DriverCaps: Structure to write the Hardware accelerated caps to
959  *  HelCaps: Structure to write the emulation caps to
960  *
961  * Returns
962  *  This implementation returns DD_OK only
963  *
964  *****************************************************************************/
965 static HRESULT WINAPI ddraw7_GetCaps(IDirectDraw7 *iface, DDCAPS *DriverCaps, DDCAPS *HELCaps)
966 {
967     IDirectDrawImpl *This = (IDirectDrawImpl *)iface;
968     DDCAPS caps;
969     WINED3DCAPS winecaps;
970     HRESULT hr;
971     DDSCAPS2 ddscaps = {0, 0, 0, 0};
972
973     TRACE("iface %p, driver_caps %p, hel_caps %p.\n", iface, DriverCaps, HELCaps);
974
975     /* One structure must be != NULL */
976     if( (!DriverCaps) && (!HELCaps) )
977     {
978         ERR("(%p) Invalid params to ddraw7_GetCaps\n", This);
979         return DDERR_INVALIDPARAMS;
980     }
981
982     memset(&caps, 0, sizeof(caps));
983     memset(&winecaps, 0, sizeof(winecaps));
984     caps.dwSize = sizeof(caps);
985     EnterCriticalSection(&ddraw_cs);
986     hr = IWineD3DDevice_GetDeviceCaps(This->wineD3DDevice, &winecaps);
987     if(FAILED(hr)) {
988         WARN("IWineD3DDevice::GetDeviceCaps failed\n");
989         LeaveCriticalSection(&ddraw_cs);
990         return hr;
991     }
992
993     hr = IDirectDraw7_GetAvailableVidMem(iface, &ddscaps, &caps.dwVidMemTotal, &caps.dwVidMemFree);
994     LeaveCriticalSection(&ddraw_cs);
995     if(FAILED(hr)) {
996         WARN("IDirectDraw7::GetAvailableVidMem failed\n");
997         return hr;
998     }
999
1000     caps.dwCaps = winecaps.DirectDrawCaps.Caps;
1001     caps.dwCaps2 = winecaps.DirectDrawCaps.Caps2;
1002     caps.dwCKeyCaps = winecaps.DirectDrawCaps.CKeyCaps;
1003     caps.dwFXCaps = winecaps.DirectDrawCaps.FXCaps;
1004     caps.dwPalCaps = winecaps.DirectDrawCaps.PalCaps;
1005     caps.ddsCaps.dwCaps = winecaps.DirectDrawCaps.ddsCaps;
1006     caps.dwSVBCaps = winecaps.DirectDrawCaps.SVBCaps;
1007     caps.dwSVBCKeyCaps = winecaps.DirectDrawCaps.SVBCKeyCaps;
1008     caps.dwSVBFXCaps = winecaps.DirectDrawCaps.SVBFXCaps;
1009     caps.dwVSBCaps = winecaps.DirectDrawCaps.VSBCaps;
1010     caps.dwVSBCKeyCaps = winecaps.DirectDrawCaps.VSBCKeyCaps;
1011     caps.dwVSBFXCaps = winecaps.DirectDrawCaps.VSBFXCaps;
1012     caps.dwSSBCaps = winecaps.DirectDrawCaps.SSBCaps;
1013     caps.dwSSBCKeyCaps = winecaps.DirectDrawCaps.SSBCKeyCaps;
1014     caps.dwSSBFXCaps = winecaps.DirectDrawCaps.SSBFXCaps;
1015
1016     /* Even if WineD3D supports 3D rendering, remove the cap if ddraw is configured
1017      * not to use it
1018      */
1019     if(DefaultSurfaceType == SURFACE_GDI) {
1020         caps.dwCaps &= ~DDCAPS_3D;
1021         caps.ddsCaps.dwCaps &= ~(DDSCAPS_3DDEVICE | DDSCAPS_MIPMAP | DDSCAPS_TEXTURE | DDSCAPS_ZBUFFER);
1022     }
1023     if(winecaps.DirectDrawCaps.StrideAlign != 0) {
1024         caps.dwCaps |= DDCAPS_ALIGNSTRIDE;
1025         caps.dwAlignStrideAlign = winecaps.DirectDrawCaps.StrideAlign;
1026     }
1027
1028     if(DriverCaps)
1029     {
1030         DD_STRUCT_COPY_BYSIZE(DriverCaps, &caps);
1031         if (TRACE_ON(ddraw))
1032         {
1033             TRACE("Driver Caps :\n");
1034             DDRAW_dump_DDCAPS(DriverCaps);
1035         }
1036
1037     }
1038     if(HELCaps)
1039     {
1040         DD_STRUCT_COPY_BYSIZE(HELCaps, &caps);
1041         if (TRACE_ON(ddraw))
1042         {
1043             TRACE("HEL Caps :\n");
1044             DDRAW_dump_DDCAPS(HELCaps);
1045         }
1046     }
1047
1048     return DD_OK;
1049 }
1050
1051 static HRESULT WINAPI ddraw4_GetCaps(IDirectDraw4 *iface, DDCAPS *driver_caps, DDCAPS *hel_caps)
1052 {
1053     TRACE("iface %p, driver_caps %p, hel_caps %p.\n", iface, driver_caps, hel_caps);
1054
1055     return ddraw7_GetCaps((IDirectDraw7 *)ddraw_from_ddraw4(iface), driver_caps, hel_caps);
1056 }
1057
1058 static HRESULT WINAPI ddraw3_GetCaps(IDirectDraw3 *iface, DDCAPS *driver_caps, DDCAPS *hel_caps)
1059 {
1060     TRACE("iface %p, driver_caps %p, hel_caps %p.\n", iface, driver_caps, hel_caps);
1061
1062     return ddraw7_GetCaps((IDirectDraw7 *)ddraw_from_ddraw3(iface), driver_caps, hel_caps);
1063 }
1064
1065 static HRESULT WINAPI ddraw2_GetCaps(IDirectDraw2 *iface, DDCAPS *driver_caps, DDCAPS *hel_caps)
1066 {
1067     TRACE("iface %p, driver_caps %p, hel_caps %p.\n", iface, driver_caps, hel_caps);
1068
1069     return ddraw7_GetCaps((IDirectDraw7 *)ddraw_from_ddraw2(iface), driver_caps, hel_caps);
1070 }
1071
1072 static HRESULT WINAPI ddraw1_GetCaps(IDirectDraw *iface, DDCAPS *driver_caps, DDCAPS *hel_caps)
1073 {
1074     TRACE("iface %p, driver_caps %p, hel_caps %p.\n", iface, driver_caps, hel_caps);
1075
1076     return ddraw7_GetCaps((IDirectDraw7 *)ddraw_from_ddraw1(iface), driver_caps, hel_caps);
1077 }
1078
1079 /*****************************************************************************
1080  * IDirectDraw7::Compact
1081  *
1082  * No idea what it does, MSDN says it's not implemented.
1083  *
1084  * Returns
1085  *  DD_OK, but this is unchecked
1086  *
1087  *****************************************************************************/
1088 static HRESULT WINAPI ddraw7_Compact(IDirectDraw7 *iface)
1089 {
1090     TRACE("iface %p.\n", iface);
1091
1092     return DD_OK;
1093 }
1094
1095 static HRESULT WINAPI ddraw4_Compact(IDirectDraw4 *iface)
1096 {
1097     TRACE("iface %p.\n", iface);
1098
1099     return ddraw7_Compact((IDirectDraw7 *)ddraw_from_ddraw4(iface));
1100 }
1101
1102 static HRESULT WINAPI ddraw3_Compact(IDirectDraw3 *iface)
1103 {
1104     TRACE("iface %p.\n", iface);
1105
1106     return ddraw7_Compact((IDirectDraw7 *)ddraw_from_ddraw3(iface));
1107 }
1108
1109 static HRESULT WINAPI ddraw2_Compact(IDirectDraw2 *iface)
1110 {
1111     TRACE("iface %p.\n", iface);
1112
1113     return ddraw7_Compact((IDirectDraw7 *)ddraw_from_ddraw2(iface));
1114 }
1115
1116 static HRESULT WINAPI ddraw1_Compact(IDirectDraw *iface)
1117 {
1118     TRACE("iface %p.\n", iface);
1119
1120     return ddraw7_Compact((IDirectDraw7 *)ddraw_from_ddraw1(iface));
1121 }
1122
1123 /*****************************************************************************
1124  * IDirectDraw7::GetDisplayMode
1125  *
1126  * Returns information about the current display mode
1127  *
1128  * Exists in Version 1, 2, 4 and 7
1129  *
1130  * Params:
1131  *  DDSD: Address of a surface description structure to write the info to
1132  *
1133  * Returns
1134  *  DD_OK
1135  *
1136  *****************************************************************************/
1137 static HRESULT WINAPI ddraw7_GetDisplayMode(IDirectDraw7 *iface, DDSURFACEDESC2 *DDSD)
1138 {
1139     IDirectDrawImpl *This = (IDirectDrawImpl *)iface;
1140     HRESULT hr;
1141     WINED3DDISPLAYMODE Mode;
1142     DWORD Size;
1143
1144     TRACE("iface %p, surface_desc %p.\n", iface, DDSD);
1145
1146     EnterCriticalSection(&ddraw_cs);
1147     /* This seems sane */
1148     if (!DDSD)
1149     {
1150         LeaveCriticalSection(&ddraw_cs);
1151         return DDERR_INVALIDPARAMS;
1152     }
1153
1154     /* The necessary members of LPDDSURFACEDESC and LPDDSURFACEDESC2 are equal,
1155      * so one method can be used for all versions (Hopefully)
1156      */
1157     hr = IWineD3DDevice_GetDisplayMode(This->wineD3DDevice,
1158                                       0 /* swapchain 0 */,
1159                                       &Mode);
1160     if( hr != D3D_OK )
1161     {
1162         ERR(" (%p) IWineD3DDevice::GetDisplayMode returned %08x\n", This, hr);
1163         LeaveCriticalSection(&ddraw_cs);
1164         return hr;
1165     }
1166
1167     Size = DDSD->dwSize;
1168     memset(DDSD, 0, Size);
1169
1170     DDSD->dwSize = Size;
1171     DDSD->dwFlags |= DDSD_HEIGHT | DDSD_WIDTH | DDSD_PIXELFORMAT | DDSD_PITCH | DDSD_REFRESHRATE;
1172     DDSD->dwWidth = Mode.Width;
1173     DDSD->dwHeight = Mode.Height;
1174     DDSD->u2.dwRefreshRate = 60;
1175     DDSD->ddsCaps.dwCaps = 0;
1176     DDSD->u4.ddpfPixelFormat.dwSize = sizeof(DDSD->u4.ddpfPixelFormat);
1177     PixelFormat_WineD3DtoDD(&DDSD->u4.ddpfPixelFormat, Mode.Format);
1178     DDSD->u1.lPitch = Mode.Width * DDSD->u4.ddpfPixelFormat.u1.dwRGBBitCount / 8;
1179
1180     if(TRACE_ON(ddraw))
1181     {
1182         TRACE("Returning surface desc :\n");
1183         DDRAW_dump_surface_desc(DDSD);
1184     }
1185
1186     LeaveCriticalSection(&ddraw_cs);
1187     return DD_OK;
1188 }
1189
1190 static HRESULT WINAPI ddraw4_GetDisplayMode(IDirectDraw4 *iface, DDSURFACEDESC2 *surface_desc)
1191 {
1192     TRACE("iface %p, surface_desc %p.\n", iface, surface_desc);
1193
1194     return ddraw7_GetDisplayMode((IDirectDraw7 *)ddraw_from_ddraw4(iface), surface_desc);
1195 }
1196
1197 static HRESULT WINAPI ddraw3_GetDisplayMode(IDirectDraw3 *iface, DDSURFACEDESC *surface_desc)
1198 {
1199     TRACE("iface %p, surface_desc %p.\n", iface, surface_desc);
1200
1201     return ddraw7_GetDisplayMode((IDirectDraw7 *)ddraw_from_ddraw3(iface), (DDSURFACEDESC2 *)surface_desc);
1202 }
1203
1204 static HRESULT WINAPI ddraw2_GetDisplayMode(IDirectDraw2 *iface, DDSURFACEDESC *surface_desc)
1205 {
1206     TRACE("iface %p, surface_desc %p.\n", iface, surface_desc);
1207
1208     return ddraw7_GetDisplayMode((IDirectDraw7 *)ddraw_from_ddraw2(iface), (DDSURFACEDESC2 *)surface_desc);
1209 }
1210
1211 static HRESULT WINAPI ddraw1_GetDisplayMode(IDirectDraw *iface, DDSURFACEDESC *surface_desc)
1212 {
1213     TRACE("iface %p, surface_desc %p.\n", iface, surface_desc);
1214
1215     return ddraw7_GetDisplayMode((IDirectDraw7 *)ddraw_from_ddraw1(iface), (DDSURFACEDESC2 *)surface_desc);
1216 }
1217
1218 /*****************************************************************************
1219  * IDirectDraw7::GetFourCCCodes
1220  *
1221  * Returns an array of supported FourCC codes.
1222  *
1223  * Exists in Version 1, 2, 4 and 7
1224  *
1225  * Params:
1226  *  NumCodes: Contains the number of Codes that Codes can carry. Returns the number
1227  *            of enumerated codes
1228  *  Codes: Pointer to an array of DWORDs where the supported codes are written
1229  *         to
1230  *
1231  * Returns
1232  *  Always returns DD_OK, as it's a stub for now
1233  *
1234  *****************************************************************************/
1235 static HRESULT WINAPI ddraw7_GetFourCCCodes(IDirectDraw7 *iface, DWORD *NumCodes, DWORD *Codes)
1236 {
1237     IDirectDrawImpl *This = (IDirectDrawImpl *)iface;
1238     static const enum wined3d_format_id formats[] =
1239     {
1240         WINED3DFMT_YUY2, WINED3DFMT_UYVY, WINED3DFMT_YV12,
1241         WINED3DFMT_DXT1, WINED3DFMT_DXT2, WINED3DFMT_DXT3, WINED3DFMT_DXT4, WINED3DFMT_DXT5,
1242         WINED3DFMT_ATI2N, WINED3DFMT_NVHU, WINED3DFMT_NVHS
1243     };
1244     DWORD count = 0, i, outsize;
1245     HRESULT hr;
1246     WINED3DDISPLAYMODE d3ddm;
1247     WINED3DSURFTYPE type = This->ImplType;
1248
1249     TRACE("iface %p, codes_count %p, codes %p.\n", iface, NumCodes, Codes);
1250
1251     IWineD3DDevice_GetDisplayMode(This->wineD3DDevice,
1252                                   0 /* swapchain 0 */,
1253                                   &d3ddm);
1254
1255     outsize = NumCodes && Codes ? *NumCodes : 0;
1256
1257     if(type == SURFACE_UNKNOWN) type = SURFACE_GDI;
1258
1259     for(i = 0; i < (sizeof(formats) / sizeof(formats[0])); i++) {
1260         hr = IWineD3D_CheckDeviceFormat(This->wineD3D,
1261                                         WINED3DADAPTER_DEFAULT,
1262                                         WINED3DDEVTYPE_HAL,
1263                                         d3ddm.Format /* AdapterFormat */,
1264                                         0 /* usage */,
1265                                         WINED3DRTYPE_SURFACE,
1266                                         formats[i],
1267                                         type);
1268         if(SUCCEEDED(hr)) {
1269             if(count < outsize) {
1270                 Codes[count] = formats[i];
1271             }
1272             count++;
1273         }
1274     }
1275     if(NumCodes) {
1276         TRACE("Returning %u FourCC codes\n", count);
1277         *NumCodes = count;
1278     }
1279
1280     return DD_OK;
1281 }
1282
1283 static HRESULT WINAPI ddraw4_GetFourCCCodes(IDirectDraw4 *iface, DWORD *codes_count, DWORD *codes)
1284 {
1285     TRACE("iface %p, codes_count %p, codes %p.\n", iface, codes_count, codes);
1286
1287     return ddraw7_GetFourCCCodes((IDirectDraw7 *)ddraw_from_ddraw4(iface), codes_count, codes);
1288 }
1289
1290 static HRESULT WINAPI ddraw3_GetFourCCCodes(IDirectDraw3 *iface, DWORD *codes_count, DWORD *codes)
1291 {
1292     TRACE("iface %p, codes_count %p, codes %p.\n", iface, codes_count, codes);
1293
1294     return ddraw7_GetFourCCCodes((IDirectDraw7 *)ddraw_from_ddraw3(iface), codes_count, codes);
1295 }
1296
1297 static HRESULT WINAPI ddraw2_GetFourCCCodes(IDirectDraw2 *iface, DWORD *codes_count, DWORD *codes)
1298 {
1299     TRACE("iface %p, codes_count %p, codes %p.\n", iface, codes_count, codes);
1300
1301     return ddraw7_GetFourCCCodes((IDirectDraw7 *)ddraw_from_ddraw2(iface), codes_count, codes);
1302 }
1303
1304 static HRESULT WINAPI ddraw1_GetFourCCCodes(IDirectDraw *iface, DWORD *codes_count, DWORD *codes)
1305 {
1306     TRACE("iface %p, codes_count %p, codes %p.\n", iface, codes_count, codes);
1307
1308     return ddraw7_GetFourCCCodes((IDirectDraw7 *)ddraw_from_ddraw1(iface), codes_count, codes);
1309 }
1310
1311 /*****************************************************************************
1312  * IDirectDraw7::GetMonitorFrequency
1313  *
1314  * Returns the monitor's frequency
1315  *
1316  * Exists in Version 1, 2, 4 and 7
1317  *
1318  * Params:
1319  *  Freq: Pointer to a DWORD to write the frequency to
1320  *
1321  * Returns
1322  *  Always returns DD_OK
1323  *
1324  *****************************************************************************/
1325 static HRESULT WINAPI ddraw7_GetMonitorFrequency(IDirectDraw7 *iface, DWORD *Freq)
1326 {
1327     FIXME("iface %p, frequency %p stub!\n", iface, Freq);
1328
1329     /* Ideally this should be in WineD3D, as it concerns the screen setup,
1330      * but for now this should make the games happy
1331      */
1332     *Freq = 60;
1333     return DD_OK;
1334 }
1335
1336 static HRESULT WINAPI ddraw4_GetMonitorFrequency(IDirectDraw4 *iface, DWORD *frequency)
1337 {
1338     TRACE("iface %p, frequency %p.\n", iface, frequency);
1339
1340     return ddraw7_GetMonitorFrequency((IDirectDraw7 *)ddraw_from_ddraw4(iface), frequency);
1341 }
1342
1343 static HRESULT WINAPI ddraw3_GetMonitorFrequency(IDirectDraw3 *iface, DWORD *frequency)
1344 {
1345     TRACE("iface %p, frequency %p.\n", iface, frequency);
1346
1347     return ddraw7_GetMonitorFrequency((IDirectDraw7 *)ddraw_from_ddraw3(iface), frequency);
1348 }
1349
1350 static HRESULT WINAPI ddraw2_GetMonitorFrequency(IDirectDraw2 *iface, DWORD *frequency)
1351 {
1352     TRACE("iface %p, frequency %p.\n", iface, frequency);
1353
1354     return ddraw7_GetMonitorFrequency((IDirectDraw7 *)ddraw_from_ddraw2(iface), frequency);
1355 }
1356
1357 static HRESULT WINAPI ddraw1_GetMonitorFrequency(IDirectDraw *iface, DWORD *frequency)
1358 {
1359     TRACE("iface %p, frequency %p.\n", iface, frequency);
1360
1361     return ddraw7_GetMonitorFrequency((IDirectDraw7 *)ddraw_from_ddraw1(iface), frequency);
1362 }
1363
1364 /*****************************************************************************
1365  * IDirectDraw7::GetVerticalBlankStatus
1366  *
1367  * Returns the Vertical blank status of the monitor. This should be in WineD3D
1368  * too basically, but as it's a semi stub, I didn't create a function there
1369  *
1370  * Params:
1371  *  status: Pointer to a BOOL to be filled with the vertical blank status
1372  *
1373  * Returns
1374  *  DD_OK on success
1375  *  DDERR_INVALIDPARAMS if status is NULL
1376  *
1377  *****************************************************************************/
1378 static HRESULT WINAPI ddraw7_GetVerticalBlankStatus(IDirectDraw7 *iface, BOOL *status)
1379 {
1380     IDirectDrawImpl *This = (IDirectDrawImpl *)iface;
1381
1382     TRACE("iface %p, status %p.\n", iface, status);
1383
1384     /* This looks sane, the MSDN suggests it too */
1385     EnterCriticalSection(&ddraw_cs);
1386     if(!status)
1387     {
1388         LeaveCriticalSection(&ddraw_cs);
1389         return DDERR_INVALIDPARAMS;
1390     }
1391
1392     *status = This->fake_vblank;
1393     This->fake_vblank = !This->fake_vblank;
1394     LeaveCriticalSection(&ddraw_cs);
1395     return DD_OK;
1396 }
1397
1398 static HRESULT WINAPI ddraw4_GetVerticalBlankStatus(IDirectDraw4 *iface, BOOL *status)
1399 {
1400     TRACE("iface %p, status %p.\n", iface, status);
1401
1402     return ddraw7_GetVerticalBlankStatus((IDirectDraw7 *)ddraw_from_ddraw4(iface), status);
1403 }
1404
1405 static HRESULT WINAPI ddraw3_GetVerticalBlankStatus(IDirectDraw3 *iface, BOOL *status)
1406 {
1407     TRACE("iface %p, status %p.\n", iface, status);
1408
1409     return ddraw7_GetVerticalBlankStatus((IDirectDraw7 *)ddraw_from_ddraw3(iface), status);
1410 }
1411
1412 static HRESULT WINAPI ddraw2_GetVerticalBlankStatus(IDirectDraw2 *iface, BOOL *status)
1413 {
1414     TRACE("iface %p, status %p.\n", iface, status);
1415
1416     return ddraw7_GetVerticalBlankStatus((IDirectDraw7 *)ddraw_from_ddraw2(iface), status);
1417 }
1418
1419 static HRESULT WINAPI ddraw1_GetVerticalBlankStatus(IDirectDraw *iface, BOOL *status)
1420 {
1421     TRACE("iface %p, status %p.\n", iface, status);
1422
1423     return ddraw7_GetVerticalBlankStatus((IDirectDraw7 *)ddraw_from_ddraw1(iface), status);
1424 }
1425
1426 /*****************************************************************************
1427  * IDirectDraw7::GetAvailableVidMem
1428  *
1429  * Returns the total and free video memory
1430  *
1431  * Params:
1432  *  Caps: Specifies the memory type asked for
1433  *  total: Pointer to a DWORD to be filled with the total memory
1434  *  free: Pointer to a DWORD to be filled with the free memory
1435  *
1436  * Returns
1437  *  DD_OK on success
1438  *  DDERR_INVALIDPARAMS of free and total are NULL
1439  *
1440  *****************************************************************************/
1441 static HRESULT WINAPI ddraw7_GetAvailableVidMem(IDirectDraw7 *iface, DDSCAPS2 *Caps, DWORD *total, DWORD *free)
1442 {
1443     IDirectDrawImpl *This = (IDirectDrawImpl *)iface;
1444
1445     TRACE("iface %p, caps %p, total %p, free %p.\n", iface, Caps, total, free);
1446
1447     if(TRACE_ON(ddraw))
1448     {
1449         TRACE("(%p) Asked for memory with description: ", This);
1450         DDRAW_dump_DDSCAPS2(Caps);
1451     }
1452     EnterCriticalSection(&ddraw_cs);
1453
1454     /* Todo: System memory vs local video memory vs non-local video memory
1455      * The MSDN also mentions differences between texture memory and other
1456      * resources, but that's not important
1457      */
1458
1459     if( (!total) && (!free) )
1460     {
1461         LeaveCriticalSection(&ddraw_cs);
1462         return DDERR_INVALIDPARAMS;
1463     }
1464
1465     if(total) *total = This->total_vidmem;
1466     if(free) *free = IWineD3DDevice_GetAvailableTextureMem(This->wineD3DDevice);
1467
1468     LeaveCriticalSection(&ddraw_cs);
1469     return DD_OK;
1470 }
1471
1472 static HRESULT WINAPI ddraw4_GetAvailableVidMem(IDirectDraw4 *iface,
1473         DDSCAPS2 *caps, DWORD *total, DWORD *free)
1474 {
1475     TRACE("iface %p, caps %p, total %p, free %p.\n", iface, caps, total, free);
1476
1477     return ddraw7_GetAvailableVidMem((IDirectDraw7 *)ddraw_from_ddraw4(iface), caps, total, free);
1478 }
1479
1480 static HRESULT WINAPI ddraw3_GetAvailableVidMem(IDirectDraw3 *iface,
1481         DDSCAPS *caps, DWORD *total, DWORD *free)
1482 {
1483     DDSCAPS2 caps2;
1484
1485     TRACE("iface %p, caps %p, total %p, free %p.\n", iface, caps, total, free);
1486
1487     DDRAW_Convert_DDSCAPS_1_To_2(caps, &caps2);
1488     return ddraw7_GetAvailableVidMem((IDirectDraw7 *)ddraw_from_ddraw3(iface), &caps2, total, free);
1489 }
1490
1491 static HRESULT WINAPI ddraw2_GetAvailableVidMem(IDirectDraw2 *iface,
1492         DDSCAPS *caps, DWORD *total, DWORD *free)
1493 {
1494     DDSCAPS2 caps2;
1495
1496     TRACE("iface %p, caps %p, total %p, free %p.\n", iface, caps, total, free);
1497
1498     DDRAW_Convert_DDSCAPS_1_To_2(caps, &caps2);
1499     return ddraw7_GetAvailableVidMem((IDirectDraw7 *)ddraw_from_ddraw2(iface), &caps2, total, free);
1500 }
1501
1502 /*****************************************************************************
1503  * IDirectDraw7::Initialize
1504  *
1505  * Initializes a DirectDraw interface.
1506  *
1507  * Params:
1508  *  GUID: Interface identifier. Well, don't know what this is really good
1509  *   for
1510  *
1511  * Returns
1512  *  Returns DD_OK on the first call,
1513  *  DDERR_ALREADYINITIALIZED on repeated calls
1514  *
1515  *****************************************************************************/
1516 static HRESULT WINAPI ddraw7_Initialize(IDirectDraw7 *iface, GUID *Guid)
1517 {
1518     IDirectDrawImpl *This = (IDirectDrawImpl *)iface;
1519
1520     TRACE("iface %p, guid %s.\n", iface, debugstr_guid(Guid));
1521
1522     if(This->initialized)
1523     {
1524         return DDERR_ALREADYINITIALIZED;
1525     }
1526     else
1527     {
1528         return DD_OK;
1529     }
1530 }
1531
1532 static HRESULT WINAPI ddraw4_Initialize(IDirectDraw4 *iface, GUID *guid)
1533 {
1534     TRACE("iface %p, guid %s.\n", iface, debugstr_guid(guid));
1535
1536     return ddraw7_Initialize((IDirectDraw7 *)ddraw_from_ddraw4(iface), guid);
1537 }
1538
1539 static HRESULT WINAPI ddraw3_Initialize(IDirectDraw3 *iface, GUID *guid)
1540 {
1541     TRACE("iface %p, guid %s.\n", iface, debugstr_guid(guid));
1542
1543     return ddraw7_Initialize((IDirectDraw7 *)ddraw_from_ddraw3(iface), guid);
1544 }
1545
1546 static HRESULT WINAPI ddraw2_Initialize(IDirectDraw2 *iface, GUID *guid)
1547 {
1548     TRACE("iface %p, guid %s.\n", iface, debugstr_guid(guid));
1549
1550     return ddraw7_Initialize((IDirectDraw7 *)ddraw_from_ddraw2(iface), guid);
1551 }
1552
1553 static HRESULT WINAPI ddraw1_Initialize(IDirectDraw *iface, GUID *guid)
1554 {
1555     TRACE("iface %p, guid %s.\n", iface, debugstr_guid(guid));
1556
1557     return ddraw7_Initialize((IDirectDraw7 *)ddraw_from_ddraw1(iface), guid);
1558 }
1559
1560 static HRESULT WINAPI d3d1_Initialize(IDirect3D *iface, REFIID riid)
1561 {
1562     TRACE("iface %p, riid %s.\n", iface, debugstr_guid(riid));
1563
1564     return D3D_OK;
1565 }
1566
1567 /*****************************************************************************
1568  * IDirectDraw7::FlipToGDISurface
1569  *
1570  * "Makes the surface that the GDI writes to the primary surface"
1571  * Looks like some windows specific thing we don't have to care about.
1572  * According to MSDN it permits GDI dialog boxes in FULLSCREEN mode. Good to
1573  * show error boxes ;)
1574  * Well, just return DD_OK.
1575  *
1576  * Returns:
1577  *  Always returns DD_OK
1578  *
1579  *****************************************************************************/
1580 static HRESULT WINAPI ddraw7_FlipToGDISurface(IDirectDraw7 *iface)
1581 {
1582     FIXME("iface %p stub!\n", iface);
1583
1584     return DD_OK;
1585 }
1586
1587 static HRESULT WINAPI ddraw4_FlipToGDISurface(IDirectDraw4 *iface)
1588 {
1589     TRACE("iface %p.\n", iface);
1590
1591     return ddraw7_FlipToGDISurface((IDirectDraw7 *)ddraw_from_ddraw4(iface));
1592 }
1593
1594 static HRESULT WINAPI ddraw3_FlipToGDISurface(IDirectDraw3 *iface)
1595 {
1596     TRACE("iface %p.\n", iface);
1597
1598     return ddraw7_FlipToGDISurface((IDirectDraw7 *)ddraw_from_ddraw3(iface));
1599 }
1600
1601 static HRESULT WINAPI ddraw2_FlipToGDISurface(IDirectDraw2 *iface)
1602 {
1603     TRACE("iface %p.\n", iface);
1604
1605     return ddraw7_FlipToGDISurface((IDirectDraw7 *)ddraw_from_ddraw2(iface));
1606 }
1607
1608 static HRESULT WINAPI ddraw1_FlipToGDISurface(IDirectDraw *iface)
1609 {
1610     TRACE("iface %p.\n", iface);
1611
1612     return ddraw7_FlipToGDISurface((IDirectDraw7 *)ddraw_from_ddraw1(iface));
1613 }
1614
1615 /*****************************************************************************
1616  * IDirectDraw7::WaitForVerticalBlank
1617  *
1618  * This method allows applications to get in sync with the vertical blank
1619  * interval.
1620  * The wormhole demo in the DirectX 7 sdk uses this call, and it doesn't
1621  * redraw the screen, most likely because of this stub
1622  *
1623  * Parameters:
1624  *  Flags: one of DDWAITVB_BLOCKBEGIN, DDWAITVB_BLOCKBEGINEVENT
1625  *         or DDWAITVB_BLOCKEND
1626  *  h: Not used, according to MSDN
1627  *
1628  * Returns:
1629  *  Always returns DD_OK
1630  *
1631  *****************************************************************************/
1632 static HRESULT WINAPI ddraw7_WaitForVerticalBlank(IDirectDraw7 *iface, DWORD Flags, HANDLE event)
1633 {
1634     static BOOL hide;
1635
1636     TRACE("iface %p, flags %#x, event %p.\n", iface, Flags, event);
1637
1638     /* This function is called often, so print the fixme only once */
1639     if(!hide)
1640     {
1641         FIXME("iface %p, flags %#x, event %p stub!\n", iface, Flags, event);
1642         hide = TRUE;
1643     }
1644
1645     /* MSDN says DDWAITVB_BLOCKBEGINEVENT is not supported */
1646     if(Flags & DDWAITVB_BLOCKBEGINEVENT)
1647         return DDERR_UNSUPPORTED; /* unchecked */
1648
1649     return DD_OK;
1650 }
1651
1652 static HRESULT WINAPI ddraw4_WaitForVerticalBlank(IDirectDraw4 *iface, DWORD flags, HANDLE event)
1653 {
1654     TRACE("iface %p, flags %#x, event %p.\n", iface, flags, event);
1655
1656     return ddraw7_WaitForVerticalBlank((IDirectDraw7 *)ddraw_from_ddraw4(iface), flags, event);
1657 }
1658
1659 static HRESULT WINAPI ddraw3_WaitForVerticalBlank(IDirectDraw3 *iface, DWORD flags, HANDLE event)
1660 {
1661     TRACE("iface %p, flags %#x, event %p.\n", iface, flags, event);
1662
1663     return ddraw7_WaitForVerticalBlank((IDirectDraw7 *)ddraw_from_ddraw3(iface), flags, event);
1664 }
1665
1666 static HRESULT WINAPI ddraw2_WaitForVerticalBlank(IDirectDraw2 *iface, DWORD flags, HANDLE event)
1667 {
1668     TRACE("iface %p, flags %#x, event %p.\n", iface, flags, event);
1669
1670     return ddraw7_WaitForVerticalBlank((IDirectDraw7 *)ddraw_from_ddraw2(iface), flags, event);
1671 }
1672
1673 static HRESULT WINAPI ddraw1_WaitForVerticalBlank(IDirectDraw *iface, DWORD flags, HANDLE event)
1674 {
1675     TRACE("iface %p, flags %#x, event %p.\n", iface, flags, event);
1676
1677     return ddraw7_WaitForVerticalBlank((IDirectDraw7 *)ddraw_from_ddraw1(iface), flags, event);
1678 }
1679
1680 /*****************************************************************************
1681  * IDirectDraw7::GetScanLine
1682  *
1683  * Returns the scan line that is being drawn on the monitor
1684  *
1685  * Parameters:
1686  *  Scanline: Address to write the scan line value to
1687  *
1688  * Returns:
1689  *  Always returns DD_OK
1690  *
1691  *****************************************************************************/
1692 static HRESULT WINAPI ddraw7_GetScanLine(IDirectDraw7 *iface, DWORD *Scanline)
1693 {
1694     IDirectDrawImpl *This = (IDirectDrawImpl *)iface;
1695     static BOOL hide = FALSE;
1696     WINED3DDISPLAYMODE Mode;
1697
1698     TRACE("iface %p, line %p.\n", iface, Scanline);
1699
1700     /* This function is called often, so print the fixme only once */
1701     EnterCriticalSection(&ddraw_cs);
1702     if(!hide)
1703     {
1704         FIXME("iface %p, line %p partial stub!\n", iface, Scanline);
1705         hide = TRUE;
1706     }
1707
1708     IWineD3DDevice_GetDisplayMode(This->wineD3DDevice,
1709                                   0,
1710                                   &Mode);
1711
1712     /* Fake the line sweeping of the monitor */
1713     /* FIXME: We should synchronize with a source to keep the refresh rate */
1714     *Scanline = This->cur_scanline++;
1715     /* Assume 20 scan lines in the vertical blank */
1716     if (This->cur_scanline >= Mode.Height + 20)
1717         This->cur_scanline = 0;
1718
1719     LeaveCriticalSection(&ddraw_cs);
1720     return DD_OK;
1721 }
1722
1723 static HRESULT WINAPI ddraw4_GetScanLine(IDirectDraw4 *iface, DWORD *line)
1724 {
1725     TRACE("iface %p, line %p.\n", iface, line);
1726
1727     return ddraw7_GetScanLine((IDirectDraw7 *)ddraw_from_ddraw4(iface), line);
1728 }
1729
1730 static HRESULT WINAPI ddraw3_GetScanLine(IDirectDraw3 *iface, DWORD *line)
1731 {
1732     TRACE("iface %p, line %p.\n", iface, line);
1733
1734     return ddraw7_GetScanLine((IDirectDraw7 *)ddraw_from_ddraw3(iface), line);
1735 }
1736
1737 static HRESULT WINAPI ddraw2_GetScanLine(IDirectDraw2 *iface, DWORD *line)
1738 {
1739     TRACE("iface %p, line %p.\n", iface, line);
1740
1741     return ddraw7_GetScanLine((IDirectDraw7 *)ddraw_from_ddraw2(iface), line);
1742 }
1743
1744 static HRESULT WINAPI ddraw1_GetScanLine(IDirectDraw *iface, DWORD *line)
1745 {
1746     TRACE("iface %p, line %p.\n", iface, line);
1747
1748     return ddraw7_GetScanLine((IDirectDraw7 *)ddraw_from_ddraw1(iface), line);
1749 }
1750
1751 /*****************************************************************************
1752  * IDirectDraw7::TestCooperativeLevel
1753  *
1754  * Informs the application about the state of the video adapter, depending
1755  * on the cooperative level
1756  *
1757  * Returns:
1758  *  DD_OK if the device is in a sane state
1759  *  DDERR_NOEXCLUSIVEMODE or DDERR_EXCLUSIVEMODEALREADYSET
1760  *  if the state is not correct(See below)
1761  *
1762  *****************************************************************************/
1763 static HRESULT WINAPI ddraw7_TestCooperativeLevel(IDirectDraw7 *iface)
1764 {
1765     TRACE("iface %p.\n", iface);
1766
1767     return DD_OK;
1768 }
1769
1770 static HRESULT WINAPI ddraw4_TestCooperativeLevel(IDirectDraw4 *iface)
1771 {
1772     TRACE("iface %p.\n", iface);
1773
1774     return ddraw7_TestCooperativeLevel((IDirectDraw7 *)ddraw_from_ddraw4(iface));
1775 }
1776
1777 /*****************************************************************************
1778  * IDirectDraw7::GetGDISurface
1779  *
1780  * Returns the surface that GDI is treating as the primary surface.
1781  * For Wine this is the front buffer
1782  *
1783  * Params:
1784  *  GDISurface: Address to write the surface pointer to
1785  *
1786  * Returns:
1787  *  DD_OK if the surface was found
1788  *  DDERR_NOTFOUND if the GDI surface wasn't found
1789  *
1790  *****************************************************************************/
1791 static HRESULT WINAPI ddraw7_GetGDISurface(IDirectDraw7 *iface, IDirectDrawSurface7 **GDISurface)
1792 {
1793     IDirectDrawImpl *This = (IDirectDrawImpl *)iface;
1794     IWineD3DSurface *Surf;
1795     IDirectDrawSurface7 *ddsurf;
1796     HRESULT hr;
1797     DDSCAPS2 ddsCaps;
1798
1799     TRACE("iface %p, surface %p.\n", iface, GDISurface);
1800
1801     /* Get the back buffer from the wineD3DDevice and search its
1802      * attached surfaces for the front buffer
1803      */
1804     EnterCriticalSection(&ddraw_cs);
1805     hr = IWineD3DDevice_GetBackBuffer(This->wineD3DDevice,
1806                                       0, /* SwapChain */
1807                                       0, /* first back buffer*/
1808                                       WINED3DBACKBUFFER_TYPE_MONO,
1809                                       &Surf);
1810
1811     if( (hr != D3D_OK) ||
1812         (!Surf) )
1813     {
1814         ERR("IWineD3DDevice::GetBackBuffer failed\n");
1815         LeaveCriticalSection(&ddraw_cs);
1816         return DDERR_NOTFOUND;
1817     }
1818
1819     ddsurf = IWineD3DSurface_GetParent(Surf);
1820     IWineD3DSurface_Release(Surf);
1821
1822     /* Find the front buffer */
1823     ddsCaps.dwCaps = DDSCAPS_FRONTBUFFER;
1824     hr = IDirectDrawSurface7_GetAttachedSurface(ddsurf,
1825                                                 &ddsCaps,
1826                                                 GDISurface);
1827     if(hr != DD_OK)
1828     {
1829         ERR("IDirectDrawSurface7::GetAttachedSurface failed, hr = %x\n", hr);
1830     }
1831
1832     /* The AddRef is OK this time */
1833     LeaveCriticalSection(&ddraw_cs);
1834     return hr;
1835 }
1836
1837 static HRESULT WINAPI ddraw4_GetGDISurface(IDirectDraw4 *iface, IDirectDrawSurface4 **surface)
1838 {
1839     TRACE("iface %p, surface %p.\n", iface, surface);
1840
1841     return ddraw7_GetGDISurface((IDirectDraw7 *)ddraw_from_ddraw4(iface), (IDirectDrawSurface7 **)surface);
1842 }
1843
1844 static HRESULT WINAPI ddraw3_GetGDISurface(IDirectDraw3 *iface, IDirectDrawSurface **surface)
1845 {
1846     IDirectDrawSurface7 *surface7;
1847     HRESULT hr;
1848
1849     TRACE("iface %p, surface %p.\n", iface, surface);
1850
1851     hr = ddraw7_GetGDISurface((IDirectDraw7 *)ddraw_from_ddraw3(iface), &surface7);
1852     *surface = surface7 ? (IDirectDrawSurface *)&((IDirectDrawSurfaceImpl *)surface7)->IDirectDrawSurface3_vtbl : NULL;
1853
1854     return hr;
1855 }
1856
1857 static HRESULT WINAPI ddraw2_GetGDISurface(IDirectDraw2 *iface, IDirectDrawSurface **surface)
1858 {
1859     IDirectDrawSurface7 *surface7;
1860     HRESULT hr;
1861
1862     TRACE("iface %p, surface %p.\n", iface, surface);
1863
1864     hr = ddraw7_GetGDISurface((IDirectDraw7 *)ddraw_from_ddraw2(iface), &surface7);
1865     *surface = surface7 ? (IDirectDrawSurface *)&((IDirectDrawSurfaceImpl *)surface7)->IDirectDrawSurface3_vtbl : NULL;
1866
1867     return hr;
1868 }
1869
1870 static HRESULT WINAPI ddraw1_GetGDISurface(IDirectDraw *iface, IDirectDrawSurface **surface)
1871 {
1872     IDirectDrawSurface7 *surface7;
1873     HRESULT hr;
1874
1875     TRACE("iface %p, surface %p.\n", iface, surface);
1876
1877     hr = ddraw7_GetGDISurface((IDirectDraw7 *)ddraw_from_ddraw1(iface), &surface7);
1878     *surface = surface7 ? (IDirectDrawSurface *)&((IDirectDrawSurfaceImpl *)surface7)->IDirectDrawSurface3_vtbl : NULL;
1879
1880     return hr;
1881 }
1882
1883 struct displaymodescallback_context
1884 {
1885     LPDDENUMMODESCALLBACK func;
1886     void *context;
1887 };
1888
1889 static HRESULT CALLBACK EnumDisplayModesCallbackThunk(DDSURFACEDESC2 *surface_desc, void *context)
1890 {
1891     struct displaymodescallback_context *cbcontext = context;
1892     DDSURFACEDESC desc;
1893
1894     memcpy(&desc, surface_desc, sizeof(desc));
1895     desc.dwSize = sizeof(desc);
1896
1897     return cbcontext->func(&desc, cbcontext->context);
1898 }
1899
1900 /*****************************************************************************
1901  * IDirectDraw7::EnumDisplayModes
1902  *
1903  * Enumerates the supported Display modes. The modes can be filtered with
1904  * the DDSD parameter.
1905  *
1906  * Params:
1907  *  Flags: can be DDEDM_REFRESHRATES and DDEDM_STANDARDVGAMODES
1908  *  DDSD: Surface description to filter the modes
1909  *  Context: Pointer passed back to the callback function
1910  *  cb: Application-provided callback function
1911  *
1912  * Returns:
1913  *  DD_OK on success
1914  *  DDERR_INVALIDPARAMS if the callback wasn't set
1915  *
1916  *****************************************************************************/
1917 static HRESULT WINAPI ddraw7_EnumDisplayModes(IDirectDraw7 *iface, DWORD Flags,
1918         DDSURFACEDESC2 *DDSD, void *Context, LPDDENUMMODESCALLBACK2 cb)
1919 {
1920     IDirectDrawImpl *This = (IDirectDrawImpl *)iface;
1921     unsigned int modenum, fmt;
1922     enum wined3d_format_id pixelformat = WINED3DFMT_UNKNOWN;
1923     WINED3DDISPLAYMODE mode;
1924     DDSURFACEDESC2 callback_sd;
1925     WINED3DDISPLAYMODE *enum_modes = NULL;
1926     unsigned enum_mode_count = 0, enum_mode_array_size = 0;
1927
1928     static const enum wined3d_format_id checkFormatList[] =
1929     {
1930         WINED3DFMT_B8G8R8X8_UNORM,
1931         WINED3DFMT_B5G6R5_UNORM,
1932         WINED3DFMT_P8_UINT,
1933     };
1934
1935     TRACE("iface %p, flags %#x, surface_desc %p, context %p, callback %p.\n",
1936             iface, Flags, DDSD, Context, cb);
1937
1938     EnterCriticalSection(&ddraw_cs);
1939     /* This looks sane */
1940     if(!cb)
1941     {
1942         LeaveCriticalSection(&ddraw_cs);
1943         return DDERR_INVALIDPARAMS;
1944     }
1945
1946     if(DDSD)
1947     {
1948         if ((DDSD->dwFlags & DDSD_PIXELFORMAT) && (DDSD->u4.ddpfPixelFormat.dwFlags & DDPF_RGB) )
1949             pixelformat = PixelFormat_DD2WineD3D(&DDSD->u4.ddpfPixelFormat);
1950     }
1951
1952     if(!(Flags & DDEDM_REFRESHRATES))
1953     {
1954         enum_mode_array_size = 16;
1955         enum_modes = HeapAlloc(GetProcessHeap(), 0, sizeof(WINED3DDISPLAYMODE) * enum_mode_array_size);
1956         if (!enum_modes)
1957         {
1958             ERR("Out of memory\n");
1959             LeaveCriticalSection(&ddraw_cs);
1960             return DDERR_OUTOFMEMORY;
1961         }
1962     }
1963
1964     for(fmt = 0; fmt < (sizeof(checkFormatList) / sizeof(checkFormatList[0])); fmt++)
1965     {
1966         if(pixelformat != WINED3DFMT_UNKNOWN && checkFormatList[fmt] != pixelformat)
1967         {
1968             continue;
1969         }
1970
1971         modenum = 0;
1972         while(IWineD3D_EnumAdapterModes(This->wineD3D,
1973                                         WINED3DADAPTER_DEFAULT,
1974                                         checkFormatList[fmt],
1975                                         modenum++,
1976                                         &mode) == WINED3D_OK)
1977         {
1978             if(DDSD)
1979             {
1980                 if(DDSD->dwFlags & DDSD_WIDTH && mode.Width != DDSD->dwWidth) continue;
1981                 if(DDSD->dwFlags & DDSD_HEIGHT && mode.Height != DDSD->dwHeight) continue;
1982             }
1983
1984             if(!(Flags & DDEDM_REFRESHRATES))
1985             {
1986                 /* DX docs state EnumDisplayMode should return only unique modes. If DDEDM_REFRESHRATES is not set, refresh
1987                  * rate doesn't matter when determining if the mode is unique. So modes only differing in refresh rate have
1988                  * to be reduced to a single unique result in such case.
1989                  */
1990                 BOOL found = FALSE;
1991                 unsigned i;
1992
1993                 for (i = 0; i < enum_mode_count; i++)
1994                 {
1995                     if(enum_modes[i].Width == mode.Width && enum_modes[i].Height == mode.Height &&
1996                        enum_modes[i].Format == mode.Format)
1997                     {
1998                         found = TRUE;
1999                         break;
2000                     }
2001                 }
2002
2003                 if(found) continue;
2004             }
2005
2006             memset(&callback_sd, 0, sizeof(callback_sd));
2007             callback_sd.dwSize = sizeof(callback_sd);
2008             callback_sd.u4.ddpfPixelFormat.dwSize = sizeof(DDPIXELFORMAT);
2009
2010             callback_sd.dwFlags = DDSD_HEIGHT|DDSD_WIDTH|DDSD_PIXELFORMAT|DDSD_PITCH;
2011             if(Flags & DDEDM_REFRESHRATES)
2012             {
2013                 callback_sd.dwFlags |= DDSD_REFRESHRATE;
2014                 callback_sd.u2.dwRefreshRate = mode.RefreshRate;
2015             }
2016
2017             callback_sd.dwWidth = mode.Width;
2018             callback_sd.dwHeight = mode.Height;
2019
2020             PixelFormat_WineD3DtoDD(&callback_sd.u4.ddpfPixelFormat, mode.Format);
2021
2022             /* Calc pitch and DWORD align like MSDN says */
2023             callback_sd.u1.lPitch = (callback_sd.u4.ddpfPixelFormat.u1.dwRGBBitCount / 8) * mode.Width;
2024             callback_sd.u1.lPitch = (callback_sd.u1.lPitch + 3) & ~3;
2025
2026             TRACE("Enumerating %dx%dx%d @%d\n", callback_sd.dwWidth, callback_sd.dwHeight, callback_sd.u4.ddpfPixelFormat.u1.dwRGBBitCount,
2027               callback_sd.u2.dwRefreshRate);
2028
2029             if(cb(&callback_sd, Context) == DDENUMRET_CANCEL)
2030             {
2031                 TRACE("Application asked to terminate the enumeration\n");
2032                 HeapFree(GetProcessHeap(), 0, enum_modes);
2033                 LeaveCriticalSection(&ddraw_cs);
2034                 return DD_OK;
2035             }
2036
2037             if(!(Flags & DDEDM_REFRESHRATES))
2038             {
2039                 if (enum_mode_count == enum_mode_array_size)
2040                 {
2041                     WINED3DDISPLAYMODE *new_enum_modes;
2042
2043                     enum_mode_array_size *= 2;
2044                     new_enum_modes = HeapReAlloc(GetProcessHeap(), 0, enum_modes, sizeof(WINED3DDISPLAYMODE) * enum_mode_array_size);
2045
2046                     if (!new_enum_modes)
2047                     {
2048                         ERR("Out of memory\n");
2049                         HeapFree(GetProcessHeap(), 0, enum_modes);
2050                         LeaveCriticalSection(&ddraw_cs);
2051                         return DDERR_OUTOFMEMORY;
2052                     }
2053
2054                     enum_modes = new_enum_modes;
2055                 }
2056
2057                 enum_modes[enum_mode_count++] = mode;
2058             }
2059         }
2060     }
2061
2062     TRACE("End of enumeration\n");
2063     HeapFree(GetProcessHeap(), 0, enum_modes);
2064     LeaveCriticalSection(&ddraw_cs);
2065     return DD_OK;
2066 }
2067
2068 static HRESULT WINAPI ddraw4_EnumDisplayModes(IDirectDraw4 *iface, DWORD flags,
2069         DDSURFACEDESC2 *surface_desc, void *context, LPDDENUMMODESCALLBACK2 callback)
2070 {
2071     TRACE("iface %p, flags %#x, surface_desc %p, context %p, callback %p.\n",
2072             iface, flags, surface_desc, context, callback);
2073
2074     return ddraw7_EnumDisplayModes((IDirectDraw7 *)ddraw_from_ddraw4(iface), flags,
2075             surface_desc, context, callback);
2076 }
2077
2078 static HRESULT WINAPI ddraw3_EnumDisplayModes(IDirectDraw3 *iface, DWORD flags,
2079         DDSURFACEDESC *surface_desc, void *context, LPDDENUMMODESCALLBACK callback)
2080 {
2081     struct displaymodescallback_context cbcontext;
2082
2083     TRACE("iface %p, flags %#x, surface_desc %p, context %p, callback %p.\n",
2084             iface, flags, surface_desc, context, callback);
2085
2086     cbcontext.func = callback;
2087     cbcontext.context = context;
2088
2089     return ddraw7_EnumDisplayModes((IDirectDraw7 *)ddraw_from_ddraw3(iface), flags,
2090             (DDSURFACEDESC2 *)surface_desc, &cbcontext, EnumDisplayModesCallbackThunk);
2091 }
2092
2093 static HRESULT WINAPI ddraw2_EnumDisplayModes(IDirectDraw2 *iface, DWORD flags,
2094         DDSURFACEDESC *surface_desc, void *context, LPDDENUMMODESCALLBACK callback)
2095 {
2096     struct displaymodescallback_context cbcontext;
2097
2098     TRACE("iface %p, flags %#x, surface_desc %p, context %p, callback %p.\n",
2099             iface, flags, surface_desc, context, callback);
2100
2101     cbcontext.func = callback;
2102     cbcontext.context = context;
2103
2104     return ddraw7_EnumDisplayModes((IDirectDraw7 *)ddraw_from_ddraw2(iface), flags,
2105             (DDSURFACEDESC2 *)surface_desc, &cbcontext, EnumDisplayModesCallbackThunk);
2106 }
2107
2108 static HRESULT WINAPI ddraw1_EnumDisplayModes(IDirectDraw *iface, DWORD flags,
2109         DDSURFACEDESC *surface_desc, void *context, LPDDENUMMODESCALLBACK callback)
2110 {
2111     struct displaymodescallback_context cbcontext;
2112
2113     TRACE("iface %p, flags %#x, surface_desc %p, context %p, callback %p.\n",
2114             iface, flags, surface_desc, context, callback);
2115
2116     cbcontext.func = callback;
2117     cbcontext.context = context;
2118
2119     return ddraw7_EnumDisplayModes((IDirectDraw7 *)ddraw_from_ddraw1(iface), flags,
2120             (DDSURFACEDESC2 *)surface_desc, &cbcontext, EnumDisplayModesCallbackThunk);
2121 }
2122
2123 /*****************************************************************************
2124  * IDirectDraw7::EvaluateMode
2125  *
2126  * Used with IDirectDraw7::StartModeTest to test video modes.
2127  * EvaluateMode is used to pass or fail a mode, and continue with the next
2128  * mode
2129  *
2130  * Params:
2131  *  Flags: DDEM_MODEPASSED or DDEM_MODEFAILED
2132  *  Timeout: Returns the amount of seconds left before the mode would have
2133  *           been failed automatically
2134  *
2135  * Returns:
2136  *  This implementation always DD_OK, because it's a stub
2137  *
2138  *****************************************************************************/
2139 static HRESULT WINAPI ddraw7_EvaluateMode(IDirectDraw7 *iface, DWORD Flags, DWORD *Timeout)
2140 {
2141     FIXME("iface %p, flags %#x, timeout %p stub!\n", iface, Flags, Timeout);
2142
2143     /* When implementing this, implement it in WineD3D */
2144
2145     return DD_OK;
2146 }
2147
2148 /*****************************************************************************
2149  * IDirectDraw7::GetDeviceIdentifier
2150  *
2151  * Returns the device identifier, which gives information about the driver
2152  * Our device identifier is defined at the beginning of this file.
2153  *
2154  * Params:
2155  *  DDDI: Address for the returned structure
2156  *  Flags: Can be DDGDI_GETHOSTIDENTIFIER
2157  *
2158  * Returns:
2159  *  On success it returns DD_OK
2160  *  DDERR_INVALIDPARAMS if DDDI is NULL
2161  *
2162  *****************************************************************************/
2163 static HRESULT WINAPI ddraw7_GetDeviceIdentifier(IDirectDraw7 *iface,
2164         DDDEVICEIDENTIFIER2 *DDDI, DWORD Flags)
2165 {
2166     TRACE("iface %p, device_identifier %p, flags %#x.\n", iface, DDDI, Flags);
2167
2168     if(!DDDI)
2169         return DDERR_INVALIDPARAMS;
2170
2171     /* The DDGDI_GETHOSTIDENTIFIER returns the information about the 2D
2172      * host adapter, if there's a secondary 3D adapter. This doesn't apply
2173      * to any modern hardware, nor is it interesting for Wine, so ignore it.
2174      * Size of DDDEVICEIDENTIFIER2 may be aligned to 8 bytes and thus 4
2175      * bytes too long. So only copy the relevant part of the structure
2176      */
2177
2178     memcpy(DDDI, &deviceidentifier, FIELD_OFFSET(DDDEVICEIDENTIFIER2, dwWHQLLevel) + sizeof(DWORD));
2179     return DD_OK;
2180 }
2181
2182 static HRESULT WINAPI ddraw4_GetDeviceIdentifier(IDirectDraw4 *iface,
2183         DDDEVICEIDENTIFIER *identifier, DWORD flags)
2184 {
2185     DDDEVICEIDENTIFIER2 identifier2;
2186     HRESULT hr;
2187
2188     TRACE("iface %p, identifier %p, flags %#x.\n", iface, identifier, flags);
2189
2190     hr = ddraw7_GetDeviceIdentifier((IDirectDraw7 *)ddraw_from_ddraw4(iface), &identifier2, flags);
2191     DDRAW_Convert_DDDEVICEIDENTIFIER_2_To_1(&identifier2, identifier);
2192
2193     return hr;
2194 }
2195
2196 /*****************************************************************************
2197  * IDirectDraw7::GetSurfaceFromDC
2198  *
2199  * Returns the Surface for a GDI device context handle.
2200  * Is this related to IDirectDrawSurface::GetDC ???
2201  *
2202  * Params:
2203  *  hdc: hdc to return the surface for
2204  *  Surface: Address to write the surface pointer to
2205  *
2206  * Returns:
2207  *  Always returns DD_OK because it's a stub
2208  *
2209  *****************************************************************************/
2210 static HRESULT WINAPI ddraw7_GetSurfaceFromDC(IDirectDraw7 *iface, HDC hdc, IDirectDrawSurface7 **Surface)
2211 {
2212     IDirectDrawImpl *This = (IDirectDrawImpl *)iface;
2213     IWineD3DSurface *wined3d_surface;
2214     HRESULT hr;
2215
2216     TRACE("iface %p, dc %p, surface %p.\n", iface, hdc, Surface);
2217
2218     if (!Surface) return E_INVALIDARG;
2219
2220     hr = IWineD3DDevice_GetSurfaceFromDC(This->wineD3DDevice, hdc, &wined3d_surface);
2221     if (FAILED(hr))
2222     {
2223         TRACE("No surface found for dc %p.\n", hdc);
2224         *Surface = NULL;
2225         return DDERR_NOTFOUND;
2226     }
2227
2228     *Surface = IWineD3DSurface_GetParent(wined3d_surface);
2229     IDirectDrawSurface7_AddRef(*Surface);
2230     TRACE("Returning surface %p.\n", Surface);
2231     return DD_OK;
2232 }
2233
2234 static HRESULT WINAPI ddraw4_GetSurfaceFromDC(IDirectDraw4 *iface, HDC dc, IDirectDrawSurface4 **surface)
2235 {
2236     IDirectDrawSurface7 *surface7;
2237     HRESULT hr;
2238
2239     TRACE("iface %p, dc %p, surface %p.\n", iface, dc, surface);
2240
2241     if (!surface) return E_INVALIDARG;
2242
2243     hr = ddraw7_GetSurfaceFromDC((IDirectDraw7 *)ddraw_from_ddraw4(iface), dc, &surface7);
2244     *surface = surface7 ? (IDirectDrawSurface4 *)&((IDirectDrawSurfaceImpl *)surface7)->IDirectDrawSurface3_vtbl : NULL;
2245
2246     return hr;
2247 }
2248
2249 static HRESULT WINAPI ddraw3_GetSurfaceFromDC(IDirectDraw3 *iface, HDC dc, IDirectDrawSurface **surface)
2250 {
2251     TRACE("iface %p, dc %p, surface %p.\n", iface, dc, surface);
2252
2253     return ddraw7_GetSurfaceFromDC((IDirectDraw7 *)ddraw_from_ddraw3(iface),
2254             dc, (IDirectDrawSurface7 **)surface);
2255 }
2256
2257 /*****************************************************************************
2258  * IDirectDraw7::RestoreAllSurfaces
2259  *
2260  * Calls the restore method of all surfaces
2261  *
2262  * Params:
2263  *
2264  * Returns:
2265  *  Always returns DD_OK because it's a stub
2266  *
2267  *****************************************************************************/
2268 static HRESULT WINAPI ddraw7_RestoreAllSurfaces(IDirectDraw7 *iface)
2269 {
2270     FIXME("iface %p stub!\n", iface);
2271
2272     /* This isn't hard to implement: Enumerate all WineD3D surfaces,
2273      * get their parent and call their restore method. Do not implement
2274      * it in WineD3D, as restoring a surface means re-creating the
2275      * WineD3DDSurface
2276      */
2277     return DD_OK;
2278 }
2279
2280 static HRESULT WINAPI ddraw4_RestoreAllSurfaces(IDirectDraw4 *iface)
2281 {
2282     TRACE("iface %p.\n", iface);
2283
2284     return ddraw7_RestoreAllSurfaces((IDirectDraw7 *)ddraw_from_ddraw4(iface));
2285 }
2286
2287 /*****************************************************************************
2288  * IDirectDraw7::StartModeTest
2289  *
2290  * Tests the specified video modes to update the system registry with
2291  * refresh rate information. StartModeTest starts the mode test,
2292  * EvaluateMode is used to fail or pass a mode. If EvaluateMode
2293  * isn't called within 15 seconds, the mode is failed automatically
2294  *
2295  * As refresh rates are handled by the X server, I don't think this
2296  * Method is important
2297  *
2298  * Params:
2299  *  Modes: An array of mode specifications
2300  *  NumModes: The number of modes in Modes
2301  *  Flags: Some flags...
2302  *
2303  * Returns:
2304  *  Returns DDERR_TESTFINISHED if flags contains DDSMT_ISTESTREQUIRED,
2305  *  if no modes are passed, DDERR_INVALIDPARAMS is returned,
2306  *  otherwise DD_OK
2307  *
2308  *****************************************************************************/
2309 static HRESULT WINAPI ddraw7_StartModeTest(IDirectDraw7 *iface, SIZE *Modes, DWORD NumModes, DWORD Flags)
2310 {
2311     FIXME("iface %p, modes %p, mode_count %u, flags %#x partial stub!\n",
2312             iface, Modes, NumModes, Flags);
2313
2314     /* This looks sane */
2315     if( (!Modes) || (NumModes == 0) ) return DDERR_INVALIDPARAMS;
2316
2317     /* DDSMT_ISTESTREQUIRED asks if a mode test is necessary.
2318      * As it is not, DDERR_TESTFINISHED is returned
2319      * (hopefully that's correct
2320      *
2321     if(Flags & DDSMT_ISTESTREQUIRED) return DDERR_TESTFINISHED;
2322      * well, that value doesn't (yet) exist in the wine headers, so ignore it
2323      */
2324
2325     return DD_OK;
2326 }
2327
2328 /*****************************************************************************
2329  * ddraw_recreate_surfaces_cb
2330  *
2331  * Enumeration callback for ddraw_recreate_surface.
2332  * It re-recreates the WineD3DSurface. It's pretty straightforward
2333  *
2334  *****************************************************************************/
2335 HRESULT WINAPI ddraw_recreate_surfaces_cb(IDirectDrawSurface7 *surf, DDSURFACEDESC2 *desc, void *Context)
2336 {
2337     IDirectDrawSurfaceImpl *surfImpl = (IDirectDrawSurfaceImpl *)surf;
2338     IDirectDrawImpl *This = surfImpl->ddraw;
2339     IWineD3DSurface *wineD3DSurface;
2340     IWineD3DSwapChain *swapchain;
2341     void *parent;
2342     HRESULT hr;
2343     IWineD3DClipper *clipper = NULL;
2344
2345     WINED3DSURFACE_DESC     Desc;
2346     enum wined3d_format_id Format;
2347     DWORD                   Usage;
2348     WINED3DPOOL             Pool;
2349
2350     WINED3DMULTISAMPLE_TYPE MultiSampleType;
2351     DWORD                   MultiSampleQuality;
2352     UINT                    Width;
2353     UINT                    Height;
2354
2355     TRACE("surface %p, surface_desc %p, context %p.\n",
2356             surf, desc, Context);
2357
2358     /* For the enumeration */
2359     IDirectDrawSurface7_Release(surf);
2360
2361     if(surfImpl->ImplType == This->ImplType) return DDENUMRET_OK; /* Continue */
2362
2363     /* Get the objects */
2364     swapchain = surfImpl->wineD3DSwapChain;
2365     surfImpl->wineD3DSwapChain = NULL;
2366     wineD3DSurface = surfImpl->WineD3DSurface;
2367
2368     /* get the clipper */
2369     IWineD3DSurface_GetClipper(wineD3DSurface, &clipper);
2370
2371     /* Get the surface properties */
2372     IWineD3DSurface_GetDesc(wineD3DSurface, &Desc);
2373
2374     Format = Desc.format;
2375     Usage = Desc.usage;
2376     Pool = Desc.pool;
2377     MultiSampleType = Desc.multisample_type;
2378     MultiSampleQuality = Desc.multisample_quality;
2379     Width = Desc.width;
2380     Height = Desc.height;
2381
2382     parent = IWineD3DSurface_GetParent(wineD3DSurface);
2383     hr = IWineD3DDevice_CreateSurface(This->wineD3DDevice, Width, Height, Format, TRUE /* Lockable */,
2384             FALSE /* Discard */, surfImpl->mipmap_level, Usage, Pool, MultiSampleType, MultiSampleQuality,
2385             This->ImplType, parent, &ddraw_null_wined3d_parent_ops, &surfImpl->WineD3DSurface);
2386     if (FAILED(hr))
2387     {
2388         surfImpl->WineD3DSurface = wineD3DSurface;
2389         return hr;
2390     }
2391
2392     IWineD3DSurface_SetClipper(surfImpl->WineD3DSurface, clipper);
2393
2394     /* TODO: Copy the surface content, except for render targets */
2395
2396     /* If there's a swapchain, it owns the wined3d surfaces. So Destroy
2397      * the swapchain
2398      */
2399     if(swapchain) {
2400         /* The backbuffers have the swapchain set as well, but the primary
2401          * owns it and destroys it
2402          */
2403         if(surfImpl->surface_desc.ddsCaps.dwCaps & DDSCAPS_PRIMARYSURFACE) {
2404             IWineD3DDevice_UninitGDI(This->wineD3DDevice, D3D7CB_DestroySwapChain);
2405         }
2406         surfImpl->isRenderTarget = FALSE;
2407     } else {
2408         if(IWineD3DSurface_Release(wineD3DSurface) == 0)
2409             TRACE("Surface released successful, next surface\n");
2410         else
2411             ERR("Something's still holding the old WineD3DSurface\n");
2412     }
2413
2414     surfImpl->ImplType = This->ImplType;
2415
2416     if(clipper)
2417     {
2418         IWineD3DClipper_Release(clipper);
2419     }
2420     return DDENUMRET_OK;
2421 }
2422
2423 /*****************************************************************************
2424  * ddraw_recreate_surfaces
2425  *
2426  * A function, that converts all wineD3DSurfaces to the new implementation type
2427  * It enumerates all surfaces with IWineD3DDevice::EnumSurfaces, creates a
2428  * new WineD3DSurface, copies the content and releases the old surface
2429  *
2430  *****************************************************************************/
2431 static HRESULT ddraw_recreate_surfaces(IDirectDrawImpl *This)
2432 {
2433     DDSURFACEDESC2 desc;
2434     TRACE("(%p): Switch to implementation %d\n", This, This->ImplType);
2435
2436     if(This->ImplType != SURFACE_OPENGL && This->d3d_initialized)
2437     {
2438         /* Should happen almost never */
2439         FIXME("(%p) Switching to non-opengl surfaces with d3d started. Is this a bug?\n", This);
2440         /* Shutdown d3d */
2441         IWineD3DDevice_Uninit3D(This->wineD3DDevice, D3D7CB_DestroySwapChain);
2442     }
2443     /* Contrary: D3D starting is handled by the caller, because it knows the render target */
2444
2445     memset(&desc, 0, sizeof(desc));
2446     desc.dwSize = sizeof(desc);
2447
2448     return IDirectDraw7_EnumSurfaces((IDirectDraw7 *)This, 0, &desc, This, ddraw_recreate_surfaces_cb);
2449 }
2450
2451 ULONG WINAPI D3D7CB_DestroySwapChain(IWineD3DSwapChain *pSwapChain)
2452 {
2453     IUnknown *swapChainParent;
2454
2455     TRACE("swapchain %p.\n", pSwapChain);
2456
2457     swapChainParent = IWineD3DSwapChain_GetParent(pSwapChain);
2458     return IUnknown_Release(swapChainParent);
2459 }
2460
2461 /*****************************************************************************
2462  * ddraw_create_surface
2463  *
2464  * A helper function for IDirectDraw7::CreateSurface. It creates a new surface
2465  * with the passed parameters.
2466  *
2467  * Params:
2468  *  DDSD: Description of the surface to create
2469  *  Surf: Address to store the interface pointer at
2470  *
2471  * Returns:
2472  *  DD_OK on success
2473  *
2474  *****************************************************************************/
2475 static HRESULT ddraw_create_surface(IDirectDrawImpl *This, DDSURFACEDESC2 *pDDSD,
2476         IDirectDrawSurfaceImpl **ppSurf, UINT level)
2477 {
2478     WINED3DSURFTYPE ImplType = This->ImplType;
2479     HRESULT hr;
2480
2481     TRACE("ddraw %p, surface_desc %p, surface %p, level %u.\n",
2482             This, pDDSD, ppSurf, level);
2483
2484     if (TRACE_ON(ddraw))
2485     {
2486         TRACE(" (%p) Requesting surface desc :\n", This);
2487         DDRAW_dump_surface_desc(pDDSD);
2488     }
2489
2490     /* Select the surface type, if it wasn't choosen yet */
2491     if(ImplType == SURFACE_UNKNOWN)
2492     {
2493         /* Use GL Surfaces if a D3DDEVICE Surface is requested */
2494         if(pDDSD->ddsCaps.dwCaps & DDSCAPS_3DDEVICE)
2495         {
2496             TRACE("(%p) Choosing GL surfaces because a 3DDEVICE Surface was requested\n", This);
2497             ImplType = SURFACE_OPENGL;
2498         }
2499
2500         /* Otherwise use GDI surfaces for now */
2501         else
2502         {
2503             TRACE("(%p) Choosing GDI surfaces for 2D rendering\n", This);
2504             ImplType = SURFACE_GDI;
2505         }
2506
2507         /* Policy if all surface implementations are available:
2508          * First, check if a default type was set with winecfg. If not,
2509          * try Xrender surfaces, and use them if they work. Next, check if
2510          * accelerated OpenGL is available, and use GL surfaces in this
2511          * case. If all else fails, use GDI surfaces. If a 3DDEVICE surface
2512          * was created, always use OpenGL surfaces.
2513          *
2514          * (Note: Xrender surfaces are not implemented for now, the
2515          * unaccelerated implementation uses GDI to render in Software)
2516          */
2517
2518         /* Store the type. If it needs to be changed, all WineD3DSurfaces have to
2519          * be re-created. This could be done with IDirectDrawSurface7::Restore
2520          */
2521         This->ImplType = ImplType;
2522     }
2523     else
2524     {
2525         if ((pDDSD->ddsCaps.dwCaps & DDSCAPS_3DDEVICE)
2526                 && (This->ImplType != SURFACE_OPENGL)
2527                 && DefaultSurfaceType == SURFACE_UNKNOWN)
2528         {
2529             /* We have to change to OpenGL,
2530              * and re-create all WineD3DSurfaces
2531              */
2532             ImplType = SURFACE_OPENGL;
2533             This->ImplType = ImplType;
2534             TRACE("(%p) Re-creating all surfaces\n", This);
2535             ddraw_recreate_surfaces(This);
2536             TRACE("(%p) Done recreating all surfaces\n", This);
2537         }
2538         else if(This->ImplType != SURFACE_OPENGL && pDDSD->ddsCaps.dwCaps & DDSCAPS_3DDEVICE)
2539         {
2540             WARN("The application requests a 3D capable surface, but a non-opengl surface was set in the registry\n");
2541             /* Do not fail surface creation, only fail 3D device creation */
2542         }
2543     }
2544
2545     /* Create the Surface object */
2546     *ppSurf = HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, sizeof(IDirectDrawSurfaceImpl));
2547     if(!*ppSurf)
2548     {
2549         ERR("(%p) Error allocating memory for a surface\n", This);
2550         return DDERR_OUTOFVIDEOMEMORY;
2551     }
2552
2553     hr = ddraw_surface_init(*ppSurf, This, pDDSD, level, ImplType);
2554     if (FAILED(hr))
2555     {
2556         WARN("Failed to initialize surface, hr %#x.\n", hr);
2557         HeapFree(GetProcessHeap(), 0, *ppSurf);
2558         return hr;
2559     }
2560
2561     /* Increase the surface counter, and attach the surface */
2562     InterlockedIncrement(&This->surfaces);
2563     list_add_head(&This->surface_list, &(*ppSurf)->surface_list_entry);
2564
2565     TRACE("Created surface %p.\n", *ppSurf);
2566
2567     return DD_OK;
2568 }
2569 /*****************************************************************************
2570  * CreateAdditionalSurfaces
2571  *
2572  * Creates a new mipmap chain.
2573  *
2574  * Params:
2575  *  root: Root surface to attach the newly created chain to
2576  *  count: number of surfaces to create
2577  *  DDSD: Description of the surface. Intentionally not a pointer to avoid side
2578  *        effects on the caller
2579  *  CubeFaceRoot: Whether the new surface is a root of a cube map face. This
2580  *                creates an additional surface without the mipmapping flags
2581  *
2582  *****************************************************************************/
2583 static HRESULT
2584 CreateAdditionalSurfaces(IDirectDrawImpl *This,
2585                          IDirectDrawSurfaceImpl *root,
2586                          UINT count,
2587                          DDSURFACEDESC2 DDSD,
2588                          BOOL CubeFaceRoot)
2589 {
2590     UINT i, j, level = 0;
2591     HRESULT hr;
2592     IDirectDrawSurfaceImpl *last = root;
2593
2594     for(i = 0; i < count; i++)
2595     {
2596         IDirectDrawSurfaceImpl *object2 = NULL;
2597
2598         /* increase the mipmap level, but only if a mipmap is created
2599          * In this case, also halve the size
2600          */
2601         if(DDSD.ddsCaps.dwCaps & DDSCAPS_MIPMAP && !CubeFaceRoot)
2602         {
2603             level++;
2604             if(DDSD.dwWidth > 1) DDSD.dwWidth /= 2;
2605             if(DDSD.dwHeight > 1) DDSD.dwHeight /= 2;
2606             /* Set the mipmap sublevel flag according to msdn */
2607             DDSD.ddsCaps.dwCaps2 |= DDSCAPS2_MIPMAPSUBLEVEL;
2608         }
2609         else
2610         {
2611             DDSD.ddsCaps.dwCaps2 &= ~DDSCAPS2_MIPMAPSUBLEVEL;
2612         }
2613         CubeFaceRoot = FALSE;
2614
2615         hr = ddraw_create_surface(This, &DDSD, &object2, level);
2616         if(hr != DD_OK)
2617         {
2618             return hr;
2619         }
2620
2621         /* Add the new surface to the complex attachment array */
2622         for(j = 0; j < MAX_COMPLEX_ATTACHED; j++)
2623         {
2624             if(last->complex_array[j]) continue;
2625             last->complex_array[j] = object2;
2626             break;
2627         }
2628         last = object2;
2629
2630         /* Remove the (possible) back buffer cap from the new surface description,
2631          * because only one surface in the flipping chain is a back buffer, one
2632          * is a front buffer, the others are just primary surfaces.
2633          */
2634         DDSD.ddsCaps.dwCaps &= ~DDSCAPS_BACKBUFFER;
2635     }
2636     return DD_OK;
2637 }
2638
2639 /* Must set all attached surfaces (e.g. mipmaps) versions as well */
2640 static void ddraw_set_surface_version(IDirectDrawSurfaceImpl *surface, UINT version)
2641 {
2642     unsigned int i;
2643
2644     TRACE("surface %p, version %u -> %u.\n", surface, surface->version, version);
2645
2646     surface->version = version;
2647     for (i = 0; i < MAX_COMPLEX_ATTACHED; ++i)
2648     {
2649         if (!surface->complex_array[i]) break;
2650         ddraw_set_surface_version(surface->complex_array[i], version);
2651     }
2652     while ((surface = surface->next_attached))
2653     {
2654         ddraw_set_surface_version(surface, version);
2655     }
2656 }
2657
2658 /*****************************************************************************
2659  * ddraw_attach_d3d_device
2660  *
2661  * Initializes the D3D capabilities of WineD3D
2662  *
2663  * Params:
2664  *  primary: The primary surface for D3D
2665  *
2666  * Returns
2667  *  DD_OK on success,
2668  *  DDERR_* otherwise
2669  *
2670  *****************************************************************************/
2671 static HRESULT ddraw_attach_d3d_device(IDirectDrawImpl *ddraw, IDirectDrawSurfaceImpl *primary)
2672 {
2673     WINED3DPRESENT_PARAMETERS localParameters;
2674     HWND window = ddraw->dest_window;
2675     HRESULT hr;
2676
2677     TRACE("ddraw %p, primary %p.\n", ddraw, primary);
2678
2679     if (!window || window == GetDesktopWindow())
2680     {
2681         window = CreateWindowExA(0, DDRAW_WINDOW_CLASS_NAME, "Hidden D3D Window",
2682                 WS_DISABLED, 0, 0, GetSystemMetrics(SM_CXSCREEN), GetSystemMetrics(SM_CYSCREEN),
2683                 NULL, NULL, NULL, NULL);
2684         if (!window)
2685         {
2686             ERR("Failed to create window, last error %#x.\n", GetLastError());
2687             return E_FAIL;
2688         }
2689
2690         ShowWindow(window, SW_HIDE);   /* Just to be sure */
2691         WARN("No window for the Direct3DDevice, created hidden window %p.\n", window);
2692     }
2693     else
2694     {
2695         TRACE("Using existing window %p for Direct3D rendering.\n", window);
2696     }
2697     ddraw->d3d_window = window;
2698
2699     /* Store the future Render Target surface */
2700     ddraw->d3d_target = primary;
2701
2702     /* Use the surface description for the device parameters, not the device
2703      * settings. The application might render to an offscreen surface. */
2704     localParameters.BackBufferWidth = primary->surface_desc.dwWidth;
2705     localParameters.BackBufferHeight = primary->surface_desc.dwHeight;
2706     localParameters.BackBufferFormat = PixelFormat_DD2WineD3D(&primary->surface_desc.u4.ddpfPixelFormat);
2707     localParameters.BackBufferCount = (primary->surface_desc.dwFlags & DDSD_BACKBUFFERCOUNT)
2708             ? primary->surface_desc.dwBackBufferCount : 0;
2709     localParameters.MultiSampleType = WINED3DMULTISAMPLE_NONE;
2710     localParameters.MultiSampleQuality = 0;
2711     localParameters.SwapEffect = WINED3DSWAPEFFECT_COPY;
2712     localParameters.hDeviceWindow = window;
2713     localParameters.Windowed = !(ddraw->cooperative_level & DDSCL_FULLSCREEN);
2714     localParameters.EnableAutoDepthStencil = TRUE;
2715     localParameters.AutoDepthStencilFormat = WINED3DFMT_D16_UNORM;
2716     localParameters.Flags = 0;
2717     localParameters.FullScreen_RefreshRateInHz = WINED3DPRESENT_RATE_DEFAULT;
2718     localParameters.PresentationInterval = WINED3DPRESENT_INTERVAL_DEFAULT;
2719
2720     /* Set this NOW, otherwise creating the depth stencil surface will cause a
2721      * recursive loop until ram or emulated video memory is full. */
2722     ddraw->d3d_initialized = TRUE;
2723     hr = IWineD3DDevice_Init3D(ddraw->wineD3DDevice, &localParameters);
2724     if (FAILED(hr))
2725     {
2726         ddraw->d3d_target = NULL;
2727         ddraw->d3d_initialized = FALSE;
2728         return hr;
2729     }
2730
2731     ddraw->declArraySize = 2;
2732     ddraw->decls = HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, sizeof(*ddraw->decls) * ddraw->declArraySize);
2733     if (!ddraw->decls)
2734     {
2735         ERR("Error allocating an array for the converted vertex decls.\n");
2736         ddraw->declArraySize = 0;
2737         hr = IWineD3DDevice_Uninit3D(ddraw->wineD3DDevice, D3D7CB_DestroySwapChain);
2738         return E_OUTOFMEMORY;
2739     }
2740
2741     TRACE("Successfully initialized 3D.\n");
2742
2743     return DD_OK;
2744 }
2745
2746 static HRESULT ddraw_create_gdi_swapchain(IDirectDrawImpl *ddraw, IDirectDrawSurfaceImpl *primary)
2747 {
2748     WINED3DPRESENT_PARAMETERS presentation_parameters;
2749     HWND window;
2750     HRESULT hr;
2751
2752     window = ddraw->dest_window;
2753
2754     memset(&presentation_parameters, 0, sizeof(presentation_parameters));
2755
2756     /* Use the surface description for the device parameters, not the device
2757      * settings. The application might render to an offscreen surface. */
2758     presentation_parameters.BackBufferWidth = primary->surface_desc.dwWidth;
2759     presentation_parameters.BackBufferHeight = primary->surface_desc.dwHeight;
2760     presentation_parameters.BackBufferFormat = PixelFormat_DD2WineD3D(&primary->surface_desc.u4.ddpfPixelFormat);
2761     presentation_parameters.BackBufferCount = (primary->surface_desc.dwFlags & DDSD_BACKBUFFERCOUNT)
2762             ? primary->surface_desc.dwBackBufferCount : 0;
2763     presentation_parameters.MultiSampleType = WINED3DMULTISAMPLE_NONE;
2764     presentation_parameters.MultiSampleQuality = 0;
2765     presentation_parameters.SwapEffect = WINED3DSWAPEFFECT_FLIP;
2766     presentation_parameters.hDeviceWindow = window;
2767     presentation_parameters.Windowed = !(ddraw->cooperative_level & DDSCL_FULLSCREEN);
2768     presentation_parameters.EnableAutoDepthStencil = FALSE; /* Not on GDI swapchains */
2769     presentation_parameters.AutoDepthStencilFormat = 0;
2770     presentation_parameters.Flags = 0;
2771     presentation_parameters.FullScreen_RefreshRateInHz = WINED3DPRESENT_RATE_DEFAULT;
2772     presentation_parameters.PresentationInterval = WINED3DPRESENT_INTERVAL_DEFAULT;
2773
2774     ddraw->d3d_target = primary;
2775     hr = IWineD3DDevice_InitGDI(ddraw->wineD3DDevice, &presentation_parameters);
2776     ddraw->d3d_target = NULL;
2777     if (FAILED(hr))
2778     {
2779         WARN("Failed to initialize GDI ddraw implementation, hr %#x.\n", hr);
2780         primary->wineD3DSwapChain = NULL;
2781     }
2782
2783     return hr;
2784 }
2785
2786 /*****************************************************************************
2787  * IDirectDraw7::CreateSurface
2788  *
2789  * Creates a new IDirectDrawSurface object and returns its interface.
2790  *
2791  * The surface connections with wined3d are a bit tricky. Basically it works
2792  * like this:
2793  *
2794  * |------------------------|               |-----------------|
2795  * | DDraw surface          |               | WineD3DSurface  |
2796  * |                        |               |                 |
2797  * |        WineD3DSurface  |-------------->|                 |
2798  * |        Child           |<------------->| Parent          |
2799  * |------------------------|               |-----------------|
2800  *
2801  * The DDraw surface is the parent of the wined3d surface, and it releases
2802  * the WineD3DSurface when the ddraw surface is destroyed.
2803  *
2804  * However, for all surfaces which can be in a container in WineD3D,
2805  * we have to do this. These surfaces are usually complex surfaces,
2806  * so this concerns primary surfaces with a front and a back buffer,
2807  * and textures.
2808  *
2809  * |------------------------|               |-----------------|
2810  * | DDraw surface          |               | Container       |
2811  * |                        |               |                 |
2812  * |                  Child |<------------->| Parent          |
2813  * |                Texture |<------------->|                 |
2814  * |         WineD3DSurface |<----|         |          Levels |<--|
2815  * | Complex connection     |     |         |                 |   |
2816  * |------------------------|     |         |-----------------|   |
2817  *  ^                             |                               |
2818  *  |                             |                               |
2819  *  |                             |                               |
2820  *  |    |------------------|     |         |-----------------|   |
2821  *  |    | IParent          |     |-------->| WineD3DSurface  |   |
2822  *  |    |                  |               |                 |   |
2823  *  |    |            Child |<------------->| Parent          |   |
2824  *  |    |                  |               |       Container |<--|
2825  *  |    |------------------|               |-----------------|   |
2826  *  |                                                             |
2827  *  |   |----------------------|                                  |
2828  *  |   | DDraw surface 2      |                                  |
2829  *  |   |                      |                                  |
2830  *  |<->| Complex root   Child |                                  |
2831  *  |   |              Texture |                                  |
2832  *  |   |       WineD3DSurface |<----|                            |
2833  *  |   |----------------------|     |                            |
2834  *  |                                |                            |
2835  *  |    |---------------------|     |      |-----------------|   |
2836  *  |    | IParent             |     |----->| WineD3DSurface  |   |
2837  *  |    |                     |            |                 |   |
2838  *  |    |               Child |<---------->| Parent          |   |
2839  *  |    |---------------------|            |       Container |<--|
2840  *  |                                       |-----------------|   |
2841  *  |                                                             |
2842  *  |             ---More surfaces can follow---                  |
2843  *
2844  * The reason is that the IWineD3DSwapchain(render target container)
2845  * and the IWineD3DTexure(Texture container) release the parents
2846  * of their surface's children, but by releasing the complex root
2847  * the surfaces which are complexly attached to it are destroyed
2848  * too. See IDirectDrawSurface::Release for a more detailed
2849  * explanation.
2850  *
2851  * Params:
2852  *  DDSD: Description of the surface to create
2853  *  Surf: Address to store the interface pointer at
2854  *  UnkOuter: Basically for aggregation support, but ddraw doesn't support
2855  *            aggregation, so it has to be NULL
2856  *
2857  * Returns:
2858  *  DD_OK on success
2859  *  CLASS_E_NOAGGREGATION if UnkOuter != NULL
2860  *  DDERR_* if an error occurs
2861  *
2862  *****************************************************************************/
2863 static HRESULT CreateSurface(IDirectDraw7 *iface,
2864         DDSURFACEDESC2 *DDSD, IDirectDrawSurface7 **Surf, IUnknown *UnkOuter)
2865 {
2866     IDirectDrawImpl *This = (IDirectDrawImpl *)iface;
2867     IDirectDrawSurfaceImpl *object = NULL;
2868     HRESULT hr;
2869     LONG extra_surfaces = 0;
2870     DDSURFACEDESC2 desc2;
2871     WINED3DDISPLAYMODE Mode;
2872     const DWORD sysvidmem = DDSCAPS_VIDEOMEMORY | DDSCAPS_SYSTEMMEMORY;
2873
2874     TRACE("iface %p, surface_desc %p, surface %p, outer_unknown %p.\n",
2875             iface, DDSD, Surf, UnkOuter);
2876
2877     /* Some checks before we start */
2878     if (TRACE_ON(ddraw))
2879     {
2880         TRACE(" (%p) Requesting surface desc :\n", This);
2881         DDRAW_dump_surface_desc(DDSD);
2882     }
2883     EnterCriticalSection(&ddraw_cs);
2884
2885     if (UnkOuter != NULL)
2886     {
2887         FIXME("(%p) : outer != NULL?\n", This);
2888         LeaveCriticalSection(&ddraw_cs);
2889         return CLASS_E_NOAGGREGATION; /* unchecked */
2890     }
2891
2892     if (Surf == NULL)
2893     {
2894         FIXME("(%p) You want to get back a surface? Don't give NULL ptrs!\n", This);
2895         LeaveCriticalSection(&ddraw_cs);
2896         return E_POINTER; /* unchecked */
2897     }
2898
2899     if (!(DDSD->dwFlags & DDSD_CAPS))
2900     {
2901         /* DVIDEO.DLL does forget the DDSD_CAPS flag ... *sigh* */
2902         DDSD->dwFlags |= DDSD_CAPS;
2903     }
2904
2905     if (DDSD->ddsCaps.dwCaps & DDSCAPS_ALLOCONLOAD)
2906     {
2907         /* If the surface is of the 'alloconload' type, ignore the LPSURFACE field */
2908         DDSD->dwFlags &= ~DDSD_LPSURFACE;
2909     }
2910
2911     if ((DDSD->dwFlags & DDSD_LPSURFACE) && (DDSD->lpSurface == NULL))
2912     {
2913         /* Frank Herbert's Dune specifies a null pointer for the surface, ignore the LPSURFACE field */
2914         WARN("(%p) Null surface pointer specified, ignore it!\n", This);
2915         DDSD->dwFlags &= ~DDSD_LPSURFACE;
2916     }
2917
2918     if((DDSD->ddsCaps.dwCaps & (DDSCAPS_FLIP | DDSCAPS_PRIMARYSURFACE)) == (DDSCAPS_FLIP | DDSCAPS_PRIMARYSURFACE) &&
2919        !(This->cooperative_level & DDSCL_EXCLUSIVE))
2920     {
2921         TRACE("(%p): Attempt to create a flipable primary surface without DDSCL_EXCLUSIVE set\n", This);
2922         *Surf = NULL;
2923         LeaveCriticalSection(&ddraw_cs);
2924         return DDERR_NOEXCLUSIVEMODE;
2925     }
2926
2927     if((DDSD->ddsCaps.dwCaps & (DDSCAPS_BACKBUFFER | DDSCAPS_PRIMARYSURFACE)) == (DDSCAPS_BACKBUFFER | DDSCAPS_PRIMARYSURFACE))
2928     {
2929         WARN("Application wanted to create back buffer primary surface\n");
2930         LeaveCriticalSection(&ddraw_cs);
2931         return DDERR_INVALIDCAPS;
2932     }
2933
2934     if((DDSD->ddsCaps.dwCaps & sysvidmem) == sysvidmem)
2935     {
2936         /* This is a special switch in ddrawex.dll, but not allowed in ddraw.dll */
2937         WARN("Application tries to put the surface in both system and video memory\n");
2938         LeaveCriticalSection(&ddraw_cs);
2939         *Surf = NULL;
2940         return DDERR_INVALIDCAPS;
2941     }
2942
2943     /* Check cube maps but only if the size includes them */
2944     if (DDSD->dwSize >= sizeof(DDSURFACEDESC2))
2945     {
2946         if(DDSD->ddsCaps.dwCaps2 & DDSCAPS2_CUBEMAP_ALLFACES &&
2947            !(DDSD->ddsCaps.dwCaps2 & DDSCAPS2_CUBEMAP))
2948         {
2949             WARN("Cube map faces requested without cube map flag\n");
2950             LeaveCriticalSection(&ddraw_cs);
2951             return DDERR_INVALIDCAPS;
2952         }
2953         if(DDSD->ddsCaps.dwCaps2 & DDSCAPS2_CUBEMAP &&
2954            (DDSD->ddsCaps.dwCaps2 & DDSCAPS2_CUBEMAP_ALLFACES) == 0)
2955         {
2956             WARN("Cube map without faces requested\n");
2957             LeaveCriticalSection(&ddraw_cs);
2958             return DDERR_INVALIDPARAMS;
2959         }
2960
2961         /* Quick tests confirm those can be created, but we don't do that yet */
2962         if(DDSD->ddsCaps.dwCaps2 & DDSCAPS2_CUBEMAP &&
2963            (DDSD->ddsCaps.dwCaps2 & DDSCAPS2_CUBEMAP_ALLFACES) != DDSCAPS2_CUBEMAP_ALLFACES)
2964         {
2965             FIXME("Partial cube maps not supported yet\n");
2966         }
2967     }
2968
2969     /* According to the msdn this flag is ignored by CreateSurface */
2970     if (DDSD->dwSize >= sizeof(DDSURFACEDESC2))
2971         DDSD->ddsCaps.dwCaps2 &= ~DDSCAPS2_MIPMAPSUBLEVEL;
2972
2973     /* Modify some flags */
2974     memset(&desc2, 0, sizeof(desc2));
2975     desc2.dwSize = sizeof(desc2);   /* For the struct copy */
2976     DD_STRUCT_COPY_BYSIZE(&desc2, DDSD);
2977     desc2.dwSize = sizeof(desc2);   /* To override a possibly smaller size */
2978     desc2.u4.ddpfPixelFormat.dwSize=sizeof(DDPIXELFORMAT); /* Just to be sure */
2979
2980     /* Get the video mode from WineD3D - we will need it */
2981     hr = IWineD3DDevice_GetDisplayMode(This->wineD3DDevice,
2982                                        0, /* Swapchain 0 */
2983                                        &Mode);
2984     if(FAILED(hr))
2985     {
2986         ERR("Failed to read display mode from wined3d\n");
2987         switch(This->orig_bpp)
2988         {
2989             case 8:
2990                 Mode.Format = WINED3DFMT_P8_UINT;
2991                 break;
2992
2993             case 15:
2994                 Mode.Format = WINED3DFMT_B5G5R5X1_UNORM;
2995                 break;
2996
2997             case 16:
2998                 Mode.Format = WINED3DFMT_B5G6R5_UNORM;
2999                 break;
3000
3001             case 24:
3002                 Mode.Format = WINED3DFMT_B8G8R8_UNORM;
3003                 break;
3004
3005             case 32:
3006                 Mode.Format = WINED3DFMT_B8G8R8X8_UNORM;
3007                 break;
3008         }
3009         Mode.Width = This->orig_width;
3010         Mode.Height = This->orig_height;
3011     }
3012
3013     /* No pixelformat given? Use the current screen format */
3014     if(!(desc2.dwFlags & DDSD_PIXELFORMAT))
3015     {
3016         desc2.dwFlags |= DDSD_PIXELFORMAT;
3017         desc2.u4.ddpfPixelFormat.dwSize=sizeof(DDPIXELFORMAT);
3018
3019         /* Wait: It could be a Z buffer */
3020         if(desc2.ddsCaps.dwCaps & DDSCAPS_ZBUFFER)
3021         {
3022             switch(desc2.u2.dwMipMapCount) /* Who had this glorious idea? */
3023             {
3024                 case 15:
3025                     PixelFormat_WineD3DtoDD(&desc2.u4.ddpfPixelFormat, WINED3DFMT_S1_UINT_D15_UNORM);
3026                     break;
3027                 case 16:
3028                     PixelFormat_WineD3DtoDD(&desc2.u4.ddpfPixelFormat, WINED3DFMT_D16_UNORM);
3029                     break;
3030                 case 24:
3031                     PixelFormat_WineD3DtoDD(&desc2.u4.ddpfPixelFormat, WINED3DFMT_X8D24_UNORM);
3032                     break;
3033                 case 32:
3034                     PixelFormat_WineD3DtoDD(&desc2.u4.ddpfPixelFormat, WINED3DFMT_D32_UNORM);
3035                     break;
3036                 default:
3037                     ERR("Unknown Z buffer bit depth\n");
3038             }
3039         }
3040         else
3041         {
3042             PixelFormat_WineD3DtoDD(&desc2.u4.ddpfPixelFormat, Mode.Format);
3043         }
3044     }
3045
3046     /* No Width or no Height? Use the original screen size
3047      */
3048     if(!(desc2.dwFlags & DDSD_WIDTH) ||
3049        !(desc2.dwFlags & DDSD_HEIGHT) )
3050     {
3051         /* Invalid for non-render targets */
3052         if(!(desc2.ddsCaps.dwCaps & DDSCAPS_PRIMARYSURFACE))
3053         {
3054             WARN("Creating a non-Primary surface without Width or Height info, returning DDERR_INVALIDPARAMS\n");
3055             *Surf = NULL;
3056             LeaveCriticalSection(&ddraw_cs);
3057             return DDERR_INVALIDPARAMS;
3058         }
3059
3060         desc2.dwFlags |= DDSD_WIDTH | DDSD_HEIGHT;
3061         desc2.dwWidth = Mode.Width;
3062         desc2.dwHeight = Mode.Height;
3063     }
3064
3065     /* Mipmap count fixes */
3066     if(desc2.ddsCaps.dwCaps & DDSCAPS_MIPMAP)
3067     {
3068         if(desc2.ddsCaps.dwCaps & DDSCAPS_COMPLEX)
3069         {
3070             if(desc2.dwFlags & DDSD_MIPMAPCOUNT)
3071             {
3072                 /* Mipmap count is given, should not be 0 */
3073                 if( desc2.u2.dwMipMapCount == 0 )
3074                 {
3075                     LeaveCriticalSection(&ddraw_cs);
3076                     return DDERR_INVALIDPARAMS;
3077                 }
3078             }
3079             else
3080             {
3081                 /* Undocumented feature: Create sublevels until
3082                  * either the width or the height is 1
3083                  */
3084                 DWORD min = desc2.dwWidth < desc2.dwHeight ?
3085                             desc2.dwWidth : desc2.dwHeight;
3086                 desc2.u2.dwMipMapCount = 0;
3087                 while( min )
3088                 {
3089                     desc2.u2.dwMipMapCount += 1;
3090                     min >>= 1;
3091                 }
3092             }
3093         }
3094         else
3095         {
3096             /* Not-complex mipmap -> Mipmapcount = 1 */
3097             desc2.u2.dwMipMapCount = 1;
3098         }
3099         extra_surfaces = desc2.u2.dwMipMapCount - 1;
3100
3101         /* There's a mipmap count in the created surface in any case */
3102         desc2.dwFlags |= DDSD_MIPMAPCOUNT;
3103     }
3104     /* If no mipmap is given, the texture has only one level */
3105
3106     /* The first surface is a front buffer, the back buffer is created afterwards */
3107     if( (desc2.dwFlags & DDSD_CAPS) && (desc2.ddsCaps.dwCaps & DDSCAPS_PRIMARYSURFACE) )
3108     {
3109         desc2.ddsCaps.dwCaps |= DDSCAPS_FRONTBUFFER;
3110     }
3111
3112     /* The root surface in a cube map is positive x */
3113     if(desc2.ddsCaps.dwCaps2 & DDSCAPS2_CUBEMAP)
3114     {
3115         desc2.ddsCaps.dwCaps2 &= ~DDSCAPS2_CUBEMAP_ALLFACES;
3116         desc2.ddsCaps.dwCaps2 |=  DDSCAPS2_CUBEMAP_POSITIVEX;
3117     }
3118
3119     /* Create the first surface */
3120     hr = ddraw_create_surface(This, &desc2, &object, 0);
3121     if (FAILED(hr))
3122     {
3123         WARN("ddraw_create_surface failed, hr %#x.\n", hr);
3124         LeaveCriticalSection(&ddraw_cs);
3125         return hr;
3126     }
3127     object->is_complex_root = TRUE;
3128
3129     *Surf = (IDirectDrawSurface7 *)object;
3130
3131     /* Create Additional surfaces if necessary
3132      * This applies to Primary surfaces which have a back buffer count
3133      * set, but not to mipmap textures. In case of Mipmap textures,
3134      * wineD3D takes care of the creation of additional surfaces
3135      */
3136     if(DDSD->dwFlags & DDSD_BACKBUFFERCOUNT)
3137     {
3138         extra_surfaces = DDSD->dwBackBufferCount;
3139         desc2.ddsCaps.dwCaps &= ~DDSCAPS_FRONTBUFFER; /* It's not a front buffer */
3140         desc2.ddsCaps.dwCaps |= DDSCAPS_BACKBUFFER;
3141         desc2.dwBackBufferCount = 0;
3142     }
3143
3144     hr = DD_OK;
3145     if(desc2.ddsCaps.dwCaps2 & DDSCAPS2_CUBEMAP)
3146     {
3147         desc2.ddsCaps.dwCaps2 &= ~DDSCAPS2_CUBEMAP_ALLFACES;
3148         desc2.ddsCaps.dwCaps2 |=  DDSCAPS2_CUBEMAP_NEGATIVEZ;
3149         hr |= CreateAdditionalSurfaces(This, object, extra_surfaces + 1, desc2, TRUE);
3150         desc2.ddsCaps.dwCaps2 &= ~DDSCAPS2_CUBEMAP_NEGATIVEZ;
3151         desc2.ddsCaps.dwCaps2 |=  DDSCAPS2_CUBEMAP_POSITIVEZ;
3152         hr |= CreateAdditionalSurfaces(This, object, extra_surfaces + 1, desc2, TRUE);
3153         desc2.ddsCaps.dwCaps2 &= ~DDSCAPS2_CUBEMAP_POSITIVEZ;
3154         desc2.ddsCaps.dwCaps2 |=  DDSCAPS2_CUBEMAP_NEGATIVEY;
3155         hr |= CreateAdditionalSurfaces(This, object, extra_surfaces + 1, desc2, TRUE);
3156         desc2.ddsCaps.dwCaps2 &= ~DDSCAPS2_CUBEMAP_NEGATIVEY;
3157         desc2.ddsCaps.dwCaps2 |=  DDSCAPS2_CUBEMAP_POSITIVEY;
3158         hr |= CreateAdditionalSurfaces(This, object, extra_surfaces + 1, desc2, TRUE);
3159         desc2.ddsCaps.dwCaps2 &= ~DDSCAPS2_CUBEMAP_POSITIVEY;
3160         desc2.ddsCaps.dwCaps2 |=  DDSCAPS2_CUBEMAP_NEGATIVEX;
3161         hr |= CreateAdditionalSurfaces(This, object, extra_surfaces + 1, desc2, TRUE);
3162         desc2.ddsCaps.dwCaps2 &= ~DDSCAPS2_CUBEMAP_NEGATIVEX;
3163         desc2.ddsCaps.dwCaps2 |=  DDSCAPS2_CUBEMAP_POSITIVEX;
3164     }
3165
3166     hr |= CreateAdditionalSurfaces(This, object, extra_surfaces, desc2, FALSE);
3167     if(hr != DD_OK)
3168     {
3169         /* This destroys and possibly created surfaces too */
3170         IDirectDrawSurface_Release((IDirectDrawSurface7 *)object);
3171         LeaveCriticalSection(&ddraw_cs);
3172         return hr;
3173     }
3174
3175     /* If the implementation is OpenGL and there's no d3ddevice, attach a d3ddevice
3176      * But attach the d3ddevice only if the currently created surface was
3177      * a primary surface (2D app in 3D mode) or a 3DDEVICE surface (3D app)
3178      * The only case I can think of where this doesn't apply is when a
3179      * 2D app was configured by the user to run with OpenGL and it didn't create
3180      * the render target as first surface. In this case the render target creation
3181      * will cause the 3D init.
3182      */
3183     if( (This->ImplType == SURFACE_OPENGL) && !(This->d3d_initialized) &&
3184         desc2.ddsCaps.dwCaps & (DDSCAPS_PRIMARYSURFACE | DDSCAPS_3DDEVICE) )
3185     {
3186         IDirectDrawSurfaceImpl *target = object, *surface;
3187         struct list *entry;
3188
3189         /* Search for the primary to use as render target */
3190         LIST_FOR_EACH(entry, &This->surface_list)
3191         {
3192             surface = LIST_ENTRY(entry, IDirectDrawSurfaceImpl, surface_list_entry);
3193             if((surface->surface_desc.ddsCaps.dwCaps & (DDSCAPS_PRIMARYSURFACE | DDSCAPS_FRONTBUFFER)) ==
3194                (DDSCAPS_PRIMARYSURFACE | DDSCAPS_FRONTBUFFER))
3195             {
3196                 /* found */
3197                 target = surface;
3198                 TRACE("Using primary %p as render target\n", target);
3199                 break;
3200             }
3201         }
3202
3203         TRACE("(%p) Attaching a D3DDevice, rendertarget = %p\n", This, target);
3204         hr = ddraw_attach_d3d_device(This, target);
3205         if (hr != D3D_OK)
3206         {
3207             IDirectDrawSurfaceImpl *release_surf;
3208             ERR("ddraw_attach_d3d_device failed, hr %#x\n", hr);
3209             *Surf = NULL;
3210
3211             /* The before created surface structures are in an incomplete state here.
3212              * WineD3D holds the reference on the IParents, and it released them on the failure
3213              * already. So the regular release method implementation would fail on the attempt
3214              * to destroy either the IParents or the swapchain. So free the surface here.
3215              * The surface structure here is a list, not a tree, because onscreen targets
3216              * cannot be cube textures
3217              */
3218             while(object)
3219             {
3220                 release_surf = object;
3221                 object = object->complex_array[0];
3222                 ddraw_surface_destroy(release_surf);
3223             }
3224             LeaveCriticalSection(&ddraw_cs);
3225             return hr;
3226         }
3227     }
3228     else if(!(This->d3d_initialized) && desc2.ddsCaps.dwCaps & DDSCAPS_PRIMARYSURFACE)
3229     {
3230         ddraw_create_gdi_swapchain(This, object);
3231     }
3232
3233     /* Addref the ddraw interface to keep an reference for each surface */
3234     IDirectDraw7_AddRef(iface);
3235     object->ifaceToRelease = (IUnknown *) iface;
3236
3237     /* Create a WineD3DTexture if a texture was requested */
3238     if(desc2.ddsCaps.dwCaps & DDSCAPS_TEXTURE)
3239     {
3240         enum wined3d_format_id Format;
3241         UINT levels;
3242         WINED3DPOOL Pool = WINED3DPOOL_DEFAULT;
3243
3244         This->tex_root = object;
3245
3246         if(desc2.ddsCaps.dwCaps & DDSCAPS_MIPMAP)
3247         {
3248             /* a mipmap is created, create enough levels */
3249             levels = desc2.u2.dwMipMapCount;
3250         }
3251         else
3252         {
3253             /* No mipmap is created, create one level */
3254             levels = 1;
3255         }
3256
3257         /* DDSCAPS_SYSTEMMEMORY textures are in WINED3DPOOL_SYSTEMMEM */
3258         if(DDSD->ddsCaps.dwCaps & DDSCAPS_SYSTEMMEMORY)
3259         {
3260             Pool = WINED3DPOOL_SYSTEMMEM;
3261         }
3262         /* Should I forward the MANAGED cap to the managed pool ? */
3263
3264         /* Get the format. It's set already by CreateNewSurface */
3265         Format = PixelFormat_DD2WineD3D(&object->surface_desc.u4.ddpfPixelFormat);
3266
3267         /* The surfaces are already created, the callback only
3268          * passes the IWineD3DSurface to WineD3D
3269          */
3270         if(desc2.ddsCaps.dwCaps2 & DDSCAPS2_CUBEMAP)
3271         {
3272             hr = IWineD3DDevice_CreateCubeTexture(This->wineD3DDevice, DDSD->dwWidth /* Edgelength */, levels,
3273                     0 /* usage */, Format, Pool, object, &ddraw_null_wined3d_parent_ops,
3274                     (IWineD3DCubeTexture **)&object->wineD3DTexture);
3275         }
3276         else
3277         {
3278             hr = IWineD3DDevice_CreateTexture(This->wineD3DDevice, DDSD->dwWidth, DDSD->dwHeight, levels,
3279                     0 /* usage */, Format, Pool, object, &ddraw_null_wined3d_parent_ops,
3280                     (IWineD3DTexture **)&object->wineD3DTexture);
3281         }
3282         This->tex_root = NULL;
3283     }
3284
3285     LeaveCriticalSection(&ddraw_cs);
3286     return hr;
3287 }
3288
3289 static HRESULT WINAPI ddraw7_CreateSurface(IDirectDraw7 *iface,
3290         DDSURFACEDESC2 *surface_desc, IDirectDrawSurface7 **surface, IUnknown *outer_unknown)
3291 {
3292     TRACE("iface %p, surface_desc %p, surface %p, outer_unknown %p.\n",
3293             iface, surface_desc, surface, outer_unknown);
3294
3295     if(surface_desc == NULL || surface_desc->dwSize != sizeof(DDSURFACEDESC2))
3296     {
3297         WARN("Application supplied invalid surface descriptor\n");
3298         return DDERR_INVALIDPARAMS;
3299     }
3300
3301     if(surface_desc->ddsCaps.dwCaps & (DDSCAPS_FRONTBUFFER | DDSCAPS_BACKBUFFER))
3302     {
3303         if (TRACE_ON(ddraw))
3304         {
3305             TRACE(" (%p) Requesting surface desc :\n", iface);
3306             DDRAW_dump_surface_desc(surface_desc);
3307         }
3308
3309         WARN("Application tried to create an explicit front or back buffer\n");
3310         return DDERR_INVALIDCAPS;
3311     }
3312
3313     return CreateSurface(iface, surface_desc, surface, outer_unknown);
3314 }
3315
3316 static HRESULT WINAPI ddraw4_CreateSurface(IDirectDraw4 *iface,
3317         DDSURFACEDESC2 *surface_desc, IDirectDrawSurface4 **surface, IUnknown *outer_unknown)
3318 {
3319     IDirectDrawImpl *ddraw = ddraw_from_ddraw4(iface);
3320     IDirectDrawSurfaceImpl *impl;
3321     HRESULT hr;
3322
3323     TRACE("iface %p, surface_desc %p, surface %p, outer_unknown %p.\n",
3324             iface, surface_desc, surface, outer_unknown);
3325
3326     if(surface_desc == NULL || surface_desc->dwSize != sizeof(DDSURFACEDESC2))
3327     {
3328         WARN("Application supplied invalid surface descriptor\n");
3329         return DDERR_INVALIDPARAMS;
3330     }
3331
3332     if(surface_desc->ddsCaps.dwCaps & (DDSCAPS_FRONTBUFFER | DDSCAPS_BACKBUFFER))
3333     {
3334         if (TRACE_ON(ddraw))
3335         {
3336             TRACE(" (%p) Requesting surface desc :\n", iface);
3337             DDRAW_dump_surface_desc(surface_desc);
3338         }
3339
3340         WARN("Application tried to create an explicit front or back buffer\n");
3341         return DDERR_INVALIDCAPS;
3342     }
3343
3344     hr = CreateSurface((IDirectDraw7 *)ddraw, surface_desc, (IDirectDrawSurface7 **)surface, outer_unknown);
3345     impl = (IDirectDrawSurfaceImpl *)*surface;
3346     if (SUCCEEDED(hr) && impl)
3347     {
3348         ddraw_set_surface_version(impl, 4);
3349         IDirectDraw7_Release((IDirectDraw7 *)ddraw);
3350         IDirectDraw4_AddRef(iface);
3351         impl->ifaceToRelease = (IUnknown *)iface;
3352     }
3353
3354     return hr;
3355 }
3356
3357 static HRESULT WINAPI ddraw3_CreateSurface(IDirectDraw3 *iface,
3358         DDSURFACEDESC *surface_desc, IDirectDrawSurface **surface, IUnknown *outer_unknown)
3359 {
3360     IDirectDrawImpl *ddraw = ddraw_from_ddraw3(iface);
3361     IDirectDrawSurface7 *surface7;
3362     IDirectDrawSurfaceImpl *impl;
3363     HRESULT hr;
3364
3365     TRACE("iface %p, surface_desc %p, surface %p, outer_unknown %p.\n",
3366             iface, surface_desc, surface, outer_unknown);
3367
3368     if(surface_desc == NULL || surface_desc->dwSize != sizeof(DDSURFACEDESC))
3369     {
3370         WARN("Application supplied invalid surface descriptor\n");
3371         return DDERR_INVALIDPARAMS;
3372     }
3373
3374     if(surface_desc->ddsCaps.dwCaps & (DDSCAPS_FRONTBUFFER | DDSCAPS_BACKBUFFER))
3375     {
3376         if (TRACE_ON(ddraw))
3377         {
3378             TRACE(" (%p) Requesting surface desc :\n", iface);
3379             DDRAW_dump_surface_desc((LPDDSURFACEDESC2)surface_desc);
3380         }
3381
3382         WARN("Application tried to create an explicit front or back buffer\n");
3383         return DDERR_INVALIDCAPS;
3384     }
3385
3386     hr = CreateSurface((IDirectDraw7 *)ddraw, (DDSURFACEDESC2 *)surface_desc, &surface7, outer_unknown);
3387     if (FAILED(hr))
3388     {
3389         *surface = NULL;
3390         return hr;
3391     }
3392
3393     impl = (IDirectDrawSurfaceImpl *)surface7;
3394     *surface = (IDirectDrawSurface *)&impl->IDirectDrawSurface3_vtbl;
3395     ddraw_set_surface_version(impl, 3);
3396     IDirectDraw7_Release((IDirectDraw7 *)ddraw);
3397     IDirectDraw3_AddRef(iface);
3398     impl->ifaceToRelease = (IUnknown *)iface;
3399
3400     return hr;
3401 }
3402
3403 static HRESULT WINAPI ddraw2_CreateSurface(IDirectDraw2 *iface,
3404         DDSURFACEDESC *surface_desc, IDirectDrawSurface **surface, IUnknown *outer_unknown)
3405 {
3406     IDirectDrawImpl *ddraw = ddraw_from_ddraw2(iface);
3407     IDirectDrawSurface7 *surface7;
3408     IDirectDrawSurfaceImpl *impl;
3409     HRESULT hr;
3410
3411     TRACE("iface %p, surface_desc %p, surface %p, outer_unknown %p.\n",
3412             iface, surface_desc, surface, outer_unknown);
3413
3414     if(surface_desc == NULL || surface_desc->dwSize != sizeof(DDSURFACEDESC))
3415     {
3416         WARN("Application supplied invalid surface descriptor\n");
3417         return DDERR_INVALIDPARAMS;
3418     }
3419
3420     if(surface_desc->ddsCaps.dwCaps & (DDSCAPS_FRONTBUFFER | DDSCAPS_BACKBUFFER))
3421     {
3422         if (TRACE_ON(ddraw))
3423         {
3424             TRACE(" (%p) Requesting surface desc :\n", iface);
3425             DDRAW_dump_surface_desc((LPDDSURFACEDESC2)surface_desc);
3426         }
3427
3428         WARN("Application tried to create an explicit front or back buffer\n");
3429         return DDERR_INVALIDCAPS;
3430     }
3431
3432     hr = CreateSurface((IDirectDraw7 *)ddraw, (DDSURFACEDESC2 *)surface_desc, &surface7, outer_unknown);
3433     if (FAILED(hr))
3434     {
3435         *surface = NULL;
3436         return hr;
3437     }
3438
3439     impl = (IDirectDrawSurfaceImpl *)surface7;
3440     *surface = (IDirectDrawSurface *)&impl->IDirectDrawSurface3_vtbl;
3441     ddraw_set_surface_version(impl, 2);
3442     IDirectDraw7_Release((IDirectDraw7 *)ddraw);
3443     impl->ifaceToRelease = NULL;
3444
3445     return hr;
3446 }
3447
3448 static HRESULT WINAPI ddraw1_CreateSurface(IDirectDraw *iface,
3449         DDSURFACEDESC *surface_desc, IDirectDrawSurface **surface, IUnknown *outer_unknown)
3450 {
3451     IDirectDrawImpl *ddraw = ddraw_from_ddraw1(iface);
3452     IDirectDrawSurface7 *surface7;
3453     IDirectDrawSurfaceImpl *impl;
3454     HRESULT hr;
3455
3456     TRACE("iface %p, surface_desc %p, surface %p, outer_unknown %p.\n",
3457             iface, surface_desc, surface, outer_unknown);
3458
3459     if(surface_desc == NULL || surface_desc->dwSize != sizeof(DDSURFACEDESC))
3460     {
3461         WARN("Application supplied invalid surface descriptor\n");
3462         return DDERR_INVALIDPARAMS;
3463     }
3464
3465     /* Remove front buffer flag, this causes failure in v7, and its added to normal
3466      * primaries anyway. */
3467     surface_desc->ddsCaps.dwCaps &= ~DDSCAPS_FRONTBUFFER;
3468     hr = CreateSurface((IDirectDraw7 *)ddraw, (DDSURFACEDESC2 *)surface_desc, &surface7, outer_unknown);
3469     if (FAILED(hr))
3470     {
3471         *surface = NULL;
3472         return hr;
3473     }
3474
3475     impl = (IDirectDrawSurfaceImpl *)surface7;
3476     *surface = (IDirectDrawSurface *)&impl->IDirectDrawSurface3_vtbl;
3477     ddraw_set_surface_version(impl, 1);
3478     IDirectDraw7_Release((IDirectDraw7 *)ddraw);
3479     impl->ifaceToRelease = NULL;
3480
3481     return hr;
3482 }
3483
3484 #define DDENUMSURFACES_SEARCHTYPE (DDENUMSURFACES_CANBECREATED|DDENUMSURFACES_DOESEXIST)
3485 #define DDENUMSURFACES_MATCHTYPE (DDENUMSURFACES_ALL|DDENUMSURFACES_MATCH|DDENUMSURFACES_NOMATCH)
3486
3487 static BOOL
3488 Main_DirectDraw_DDPIXELFORMAT_Match(const DDPIXELFORMAT *requested,
3489                                     const DDPIXELFORMAT *provided)
3490 {
3491     /* Some flags must be present in both or neither for a match. */
3492     static const DWORD must_match = DDPF_PALETTEINDEXED1 | DDPF_PALETTEINDEXED2
3493         | DDPF_PALETTEINDEXED4 | DDPF_PALETTEINDEXED8 | DDPF_FOURCC
3494         | DDPF_ZBUFFER | DDPF_STENCILBUFFER;
3495
3496     if ((requested->dwFlags & provided->dwFlags) != requested->dwFlags)
3497         return FALSE;
3498
3499     if ((requested->dwFlags & must_match) != (provided->dwFlags & must_match))
3500         return FALSE;
3501
3502     if (requested->dwFlags & DDPF_FOURCC)
3503         if (requested->dwFourCC != provided->dwFourCC)
3504             return FALSE;
3505
3506     if (requested->dwFlags & (DDPF_RGB|DDPF_YUV|DDPF_ZBUFFER|DDPF_ALPHA
3507                               |DDPF_LUMINANCE|DDPF_BUMPDUDV))
3508         if (requested->u1.dwRGBBitCount != provided->u1.dwRGBBitCount)
3509             return FALSE;
3510
3511     if (requested->dwFlags & (DDPF_RGB|DDPF_YUV|DDPF_STENCILBUFFER
3512                               |DDPF_LUMINANCE|DDPF_BUMPDUDV))
3513         if (requested->u2.dwRBitMask != provided->u2.dwRBitMask)
3514             return FALSE;
3515
3516     if (requested->dwFlags & (DDPF_RGB|DDPF_YUV|DDPF_ZBUFFER|DDPF_BUMPDUDV))
3517         if (requested->u3.dwGBitMask != provided->u3.dwGBitMask)
3518             return FALSE;
3519
3520     /* I could be wrong about the bumpmapping. MSDN docs are vague. */
3521     if (requested->dwFlags & (DDPF_RGB|DDPF_YUV|DDPF_STENCILBUFFER
3522                               |DDPF_BUMPDUDV))
3523         if (requested->u4.dwBBitMask != provided->u4.dwBBitMask)
3524             return FALSE;
3525
3526     if (requested->dwFlags & (DDPF_ALPHAPIXELS|DDPF_ZPIXELS))
3527         if (requested->u5.dwRGBAlphaBitMask != provided->u5.dwRGBAlphaBitMask)
3528             return FALSE;
3529
3530     return TRUE;
3531 }
3532
3533 static BOOL ddraw_match_surface_desc(const DDSURFACEDESC2 *requested, const DDSURFACEDESC2 *provided)
3534 {
3535     struct compare_info
3536     {
3537         DWORD flag;
3538         ptrdiff_t offset;
3539         size_t size;
3540     };
3541
3542 #define CMP(FLAG, FIELD)                                \
3543         { DDSD_##FLAG, offsetof(DDSURFACEDESC2, FIELD), \
3544           sizeof(((DDSURFACEDESC2 *)(NULL))->FIELD) }
3545
3546     static const struct compare_info compare[] =
3547     {
3548         CMP(ALPHABITDEPTH, dwAlphaBitDepth),
3549         CMP(BACKBUFFERCOUNT, dwBackBufferCount),
3550         CMP(CAPS, ddsCaps),
3551         CMP(CKDESTBLT, ddckCKDestBlt),
3552         CMP(CKDESTOVERLAY, u3 /* ddckCKDestOverlay */),
3553         CMP(CKSRCBLT, ddckCKSrcBlt),
3554         CMP(CKSRCOVERLAY, ddckCKSrcOverlay),
3555         CMP(HEIGHT, dwHeight),
3556         CMP(LINEARSIZE, u1 /* dwLinearSize */),
3557         CMP(LPSURFACE, lpSurface),
3558         CMP(MIPMAPCOUNT, u2 /* dwMipMapCount */),
3559         CMP(PITCH, u1 /* lPitch */),
3560         /* PIXELFORMAT: manual */
3561         CMP(REFRESHRATE, u2 /* dwRefreshRate */),
3562         CMP(TEXTURESTAGE, dwTextureStage),
3563         CMP(WIDTH, dwWidth),
3564         /* ZBUFFERBITDEPTH: "obsolete" */
3565     };
3566
3567 #undef CMP
3568
3569     unsigned int i;
3570
3571     if ((requested->dwFlags & provided->dwFlags) != requested->dwFlags)
3572         return FALSE;
3573
3574     for (i=0; i < sizeof(compare)/sizeof(compare[0]); i++)
3575     {
3576         if (requested->dwFlags & compare[i].flag
3577             && memcmp((const char *)provided + compare[i].offset,
3578                       (const char *)requested + compare[i].offset,
3579                       compare[i].size) != 0)
3580             return FALSE;
3581     }
3582
3583     if (requested->dwFlags & DDSD_PIXELFORMAT)
3584     {
3585         if (!Main_DirectDraw_DDPIXELFORMAT_Match(&requested->u4.ddpfPixelFormat,
3586                                                 &provided->u4.ddpfPixelFormat))
3587             return FALSE;
3588     }
3589
3590     return TRUE;
3591 }
3592
3593 #undef DDENUMSURFACES_SEARCHTYPE
3594 #undef DDENUMSURFACES_MATCHTYPE
3595
3596 struct surfacescallback_context
3597 {
3598     LPDDENUMSURFACESCALLBACK func;
3599     void *context;
3600 };
3601
3602 static HRESULT CALLBACK EnumSurfacesCallbackThunk(IDirectDrawSurface7 *surface,
3603         DDSURFACEDESC2 *surface_desc, void *context)
3604 {
3605     struct surfacescallback_context *cbcontext = context;
3606
3607     return cbcontext->func((IDirectDrawSurface *)&((IDirectDrawSurfaceImpl *)surface)->IDirectDrawSurface3_vtbl,
3608             (DDSURFACEDESC *)surface_desc, cbcontext->context);
3609 }
3610
3611 /*****************************************************************************
3612  * IDirectDraw7::EnumSurfaces
3613  *
3614  * Loops through all surfaces attached to this device and calls the
3615  * application callback. This can't be relayed to WineD3DDevice,
3616  * because some WineD3DSurfaces' parents are IParent objects
3617  *
3618  * Params:
3619  *  Flags: Some filtering flags. See IDirectDrawImpl_EnumSurfacesCallback
3620  *  DDSD: Description to filter for
3621  *  Context: Application-provided pointer, it's passed unmodified to the
3622  *           Callback function
3623  *  Callback: Address to call for each surface
3624  *
3625  * Returns:
3626  *  DDERR_INVALIDPARAMS if the callback is NULL
3627  *  DD_OK on success
3628  *
3629  *****************************************************************************/
3630 static HRESULT WINAPI ddraw7_EnumSurfaces(IDirectDraw7 *iface, DWORD Flags,
3631         DDSURFACEDESC2 *DDSD, void *Context, LPDDENUMSURFACESCALLBACK7 Callback)
3632 {
3633     /* The surface enumeration is handled by WineDDraw,
3634      * because it keeps track of all surfaces attached to
3635      * it. The filtering is done by our callback function,
3636      * because WineDDraw doesn't handle ddraw-like surface
3637      * caps structures
3638      */
3639     IDirectDrawImpl *This = (IDirectDrawImpl *)iface;
3640     IDirectDrawSurfaceImpl *surf;
3641     BOOL all, nomatch;
3642     DDSURFACEDESC2 desc;
3643     struct list *entry, *entry2;
3644
3645     TRACE("iface %p, flags %#x, surface_desc %p, context %p, callback %p.\n",
3646             iface, Flags, DDSD, Context, Callback);
3647
3648     all = Flags & DDENUMSURFACES_ALL;
3649     nomatch = Flags & DDENUMSURFACES_NOMATCH;
3650
3651     EnterCriticalSection(&ddraw_cs);
3652
3653     if(!Callback)
3654     {
3655         LeaveCriticalSection(&ddraw_cs);
3656         return DDERR_INVALIDPARAMS;
3657     }
3658
3659     /* Use the _SAFE enumeration, the app may destroy enumerated surfaces */
3660     LIST_FOR_EACH_SAFE(entry, entry2, &This->surface_list)
3661     {
3662         surf = LIST_ENTRY(entry, IDirectDrawSurfaceImpl, surface_list_entry);
3663         if (all || (nomatch != ddraw_match_surface_desc(DDSD, &surf->surface_desc)))
3664         {
3665             desc = surf->surface_desc;
3666             IDirectDrawSurface7_AddRef((IDirectDrawSurface7 *)surf);
3667             if (Callback((IDirectDrawSurface7 *)surf, &desc, Context) != DDENUMRET_OK)
3668             {
3669                 LeaveCriticalSection(&ddraw_cs);
3670                 return DD_OK;
3671             }
3672         }
3673     }
3674     LeaveCriticalSection(&ddraw_cs);
3675     return DD_OK;
3676 }
3677
3678 static HRESULT WINAPI ddraw4_EnumSurfaces(IDirectDraw4 *iface, DWORD flags,
3679         DDSURFACEDESC2 *surface_desc, void *context, LPDDENUMSURFACESCALLBACK2 callback)
3680 {
3681     TRACE("iface %p, flags %#x, surface_desc %p, context %p, callback %p.\n",
3682             iface, flags, surface_desc, context, callback);
3683
3684     return ddraw7_EnumSurfaces((IDirectDraw7 *)ddraw_from_ddraw4(iface),
3685             flags, surface_desc, context, (LPDDENUMSURFACESCALLBACK7)callback);
3686 }
3687
3688 static HRESULT WINAPI ddraw3_EnumSurfaces(IDirectDraw3 *iface, DWORD flags,
3689         DDSURFACEDESC *surface_desc, void *context, LPDDENUMSURFACESCALLBACK callback)
3690 {
3691     struct surfacescallback_context cbcontext;
3692
3693     TRACE("iface %p, flags %#x, surface_desc %p, context %p, callback %p.\n",
3694             iface, flags, surface_desc, context, callback);
3695
3696     cbcontext.func = callback;
3697     cbcontext.context = context;
3698
3699     return ddraw7_EnumSurfaces((IDirectDraw7 *)ddraw_from_ddraw3(iface), flags,
3700             (DDSURFACEDESC2 *)surface_desc, &cbcontext, EnumSurfacesCallbackThunk);
3701 }
3702
3703 static HRESULT WINAPI ddraw2_EnumSurfaces(IDirectDraw2 *iface, DWORD flags,
3704         DDSURFACEDESC *surface_desc, void *context, LPDDENUMSURFACESCALLBACK callback)
3705 {
3706     struct surfacescallback_context cbcontext;
3707
3708     TRACE("iface %p, flags %#x, surface_desc %p, context %p, callback %p.\n",
3709             iface, flags, surface_desc, context, callback);
3710
3711     cbcontext.func = callback;
3712     cbcontext.context = context;
3713
3714     return ddraw7_EnumSurfaces((IDirectDraw7 *)ddraw_from_ddraw2(iface), flags,
3715             (DDSURFACEDESC2 *)surface_desc, &cbcontext, EnumSurfacesCallbackThunk);
3716 }
3717
3718 static HRESULT WINAPI ddraw1_EnumSurfaces(IDirectDraw *iface, DWORD flags,
3719         DDSURFACEDESC *surface_desc, void *context, LPDDENUMSURFACESCALLBACK callback)
3720 {
3721     struct surfacescallback_context cbcontext;
3722
3723     TRACE("iface %p, flags %#x, surface_desc %p, context %p, callback %p.\n",
3724             iface, flags, surface_desc, context, callback);
3725
3726     cbcontext.func = callback;
3727     cbcontext.context = context;
3728
3729     return ddraw7_EnumSurfaces((IDirectDraw7 *)ddraw_from_ddraw1(iface), flags,
3730             (DDSURFACEDESC2 *)surface_desc, &cbcontext, EnumSurfacesCallbackThunk);
3731 }
3732
3733 /*****************************************************************************
3734  * DirectDrawCreateClipper (DDRAW.@)
3735  *
3736  * Creates a new IDirectDrawClipper object.
3737  *
3738  * Params:
3739  *  Clipper: Address to write the interface pointer to
3740  *  UnkOuter: For aggregation support, which ddraw doesn't have. Has to be
3741  *            NULL
3742  *
3743  * Returns:
3744  *  CLASS_E_NOAGGREGATION if UnkOuter != NULL
3745  *  E_OUTOFMEMORY if allocating the object failed
3746  *
3747  *****************************************************************************/
3748 HRESULT WINAPI
3749 DirectDrawCreateClipper(DWORD Flags,
3750                         LPDIRECTDRAWCLIPPER *Clipper,
3751                         IUnknown *UnkOuter)
3752 {
3753     IDirectDrawClipperImpl* object;
3754     HRESULT hr;
3755
3756     TRACE("flags %#x, clipper %p, outer_unknown %p.\n",
3757             Flags, Clipper, UnkOuter);
3758
3759     EnterCriticalSection(&ddraw_cs);
3760     if (UnkOuter != NULL)
3761     {
3762         LeaveCriticalSection(&ddraw_cs);
3763         return CLASS_E_NOAGGREGATION;
3764     }
3765
3766     if (!LoadWineD3D())
3767     {
3768         LeaveCriticalSection(&ddraw_cs);
3769         return DDERR_NODIRECTDRAWSUPPORT;
3770     }
3771
3772     object = HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY,
3773                      sizeof(IDirectDrawClipperImpl));
3774     if (object == NULL)
3775     {
3776         LeaveCriticalSection(&ddraw_cs);
3777         return E_OUTOFMEMORY;
3778     }
3779
3780     hr = ddraw_clipper_init(object);
3781     if (FAILED(hr))
3782     {
3783         WARN("Failed to initialize clipper, hr %#x.\n", hr);
3784         HeapFree(GetProcessHeap(), 0, object);
3785         LeaveCriticalSection(&ddraw_cs);
3786         return hr;
3787     }
3788
3789     TRACE("Created clipper %p.\n", object);
3790     *Clipper = (IDirectDrawClipper *) object;
3791     LeaveCriticalSection(&ddraw_cs);
3792     return DD_OK;
3793 }
3794
3795 /*****************************************************************************
3796  * IDirectDraw7::CreateClipper
3797  *
3798  * Creates a DDraw clipper. See DirectDrawCreateClipper for details
3799  *
3800  *****************************************************************************/
3801 static HRESULT WINAPI ddraw7_CreateClipper(IDirectDraw7 *iface, DWORD Flags,
3802         IDirectDrawClipper **Clipper, IUnknown *UnkOuter)
3803 {
3804     TRACE("iface %p, flags %#x, clipper %p, outer_unknown %p.\n",
3805             iface, Flags, Clipper, UnkOuter);
3806
3807     return DirectDrawCreateClipper(Flags, Clipper, UnkOuter);
3808 }
3809
3810 static HRESULT WINAPI ddraw4_CreateClipper(IDirectDraw4 *iface,
3811         DWORD flags, IDirectDrawClipper **clipper, IUnknown *outer_unknown)
3812 {
3813     TRACE("iface %p, flags %#x, clipper %p, outer_unknown %p.\n",
3814             iface, flags, clipper, outer_unknown);
3815
3816     return ddraw7_CreateClipper((IDirectDraw7 *)ddraw_from_ddraw4(iface), flags, clipper, outer_unknown);
3817 }
3818
3819 static HRESULT WINAPI ddraw3_CreateClipper(IDirectDraw3 *iface,
3820         DWORD flags, IDirectDrawClipper **clipper, IUnknown *outer_unknown)
3821 {
3822     TRACE("iface %p, flags %#x, clipper %p, outer_unknown %p.\n",
3823             iface, flags, clipper, outer_unknown);
3824
3825     return ddraw7_CreateClipper((IDirectDraw7 *)ddraw_from_ddraw3(iface), flags, clipper, outer_unknown);
3826 }
3827
3828 static HRESULT WINAPI ddraw2_CreateClipper(IDirectDraw2 *iface,
3829         DWORD flags, IDirectDrawClipper **clipper, IUnknown *outer_unknown)
3830 {
3831     TRACE("iface %p, flags %#x, clipper %p, outer_unknown %p.\n",
3832             iface, flags, clipper, outer_unknown);
3833
3834     return ddraw7_CreateClipper((IDirectDraw7 *)ddraw_from_ddraw2(iface), flags, clipper, outer_unknown);
3835 }
3836
3837 static HRESULT WINAPI ddraw1_CreateClipper(IDirectDraw *iface,
3838         DWORD flags, IDirectDrawClipper **clipper, IUnknown *outer_unknown)
3839 {
3840     TRACE("iface %p, flags %#x, clipper %p, outer_unknown %p.\n",
3841             iface, flags, clipper, outer_unknown);
3842
3843     return ddraw7_CreateClipper((IDirectDraw7 *)ddraw_from_ddraw1(iface), flags, clipper, outer_unknown);
3844 }
3845
3846 /*****************************************************************************
3847  * IDirectDraw7::CreatePalette
3848  *
3849  * Creates a new IDirectDrawPalette object
3850  *
3851  * Params:
3852  *  Flags: The flags for the new clipper
3853  *  ColorTable: Color table to assign to the new clipper
3854  *  Palette: Address to write the interface pointer to
3855  *  UnkOuter: For aggregation support, which ddraw doesn't have. Has to be
3856  *            NULL
3857  *
3858  * Returns:
3859  *  CLASS_E_NOAGGREGATION if UnkOuter != NULL
3860  *  E_OUTOFMEMORY if allocating the object failed
3861  *
3862  *****************************************************************************/
3863 static HRESULT WINAPI ddraw7_CreatePalette(IDirectDraw7 *iface, DWORD Flags,
3864         PALETTEENTRY *ColorTable, IDirectDrawPalette **Palette, IUnknown *pUnkOuter)
3865 {
3866     IDirectDrawImpl *This = (IDirectDrawImpl *)iface;
3867     IDirectDrawPaletteImpl *object;
3868     HRESULT hr;
3869
3870     TRACE("iface %p, flags %#x, color_table %p, palette %p, outer_unknown %p.\n",
3871             iface, Flags, ColorTable, Palette, pUnkOuter);
3872
3873     EnterCriticalSection(&ddraw_cs);
3874     if(pUnkOuter != NULL)
3875     {
3876         WARN("pUnkOuter is %p, returning CLASS_E_NOAGGREGATION\n", pUnkOuter);
3877         LeaveCriticalSection(&ddraw_cs);
3878         return CLASS_E_NOAGGREGATION;
3879     }
3880
3881     /* The refcount test shows that a cooplevel is required for this */
3882     if(!This->cooperative_level)
3883     {
3884         WARN("No cooperative level set, returning DDERR_NOCOOPERATIVELEVELSET\n");
3885         LeaveCriticalSection(&ddraw_cs);
3886         return DDERR_NOCOOPERATIVELEVELSET;
3887     }
3888
3889     object = HeapAlloc(GetProcessHeap(), 0, sizeof(IDirectDrawPaletteImpl));
3890     if(!object)
3891     {
3892         ERR("Out of memory when allocating memory for a palette implementation\n");
3893         LeaveCriticalSection(&ddraw_cs);
3894         return E_OUTOFMEMORY;
3895     }
3896
3897     hr = ddraw_palette_init(object, This, Flags, ColorTable);
3898     if (FAILED(hr))
3899     {
3900         WARN("Failed to initialize palette, hr %#x.\n", hr);
3901         HeapFree(GetProcessHeap(), 0, object);
3902         LeaveCriticalSection(&ddraw_cs);
3903         return hr;
3904     }
3905
3906     TRACE("Created palette %p.\n", object);
3907     *Palette = (IDirectDrawPalette *)object;
3908     LeaveCriticalSection(&ddraw_cs);
3909     return DD_OK;
3910 }
3911
3912 static HRESULT WINAPI ddraw4_CreatePalette(IDirectDraw4 *iface, DWORD flags,
3913         PALETTEENTRY *entries, IDirectDrawPalette **palette, IUnknown *outer_unknown)
3914 {
3915     IDirectDrawImpl *ddraw = ddraw_from_ddraw4(iface);
3916     HRESULT hr;
3917
3918     TRACE("iface %p, flags %#x, entries %p, palette %p, outer_unknown %p.\n",
3919             iface, flags, entries, palette, outer_unknown);
3920
3921     hr = ddraw7_CreatePalette((IDirectDraw7 *)ddraw, flags, entries, palette, outer_unknown);
3922     if (SUCCEEDED(hr) && *palette)
3923     {
3924         IDirectDrawPaletteImpl *impl = (IDirectDrawPaletteImpl *)*palette;
3925         IDirectDraw7_Release((IDirectDraw7 *)ddraw);
3926         IDirectDraw4_AddRef(iface);
3927         impl->ifaceToRelease = (IUnknown *)iface;
3928     }
3929     return hr;
3930 }
3931
3932 static HRESULT WINAPI ddraw3_CreatePalette(IDirectDraw3 *iface, DWORD flags,
3933         PALETTEENTRY *entries, IDirectDrawPalette **palette, IUnknown *outer_unknown)
3934 {
3935     IDirectDrawImpl *ddraw = ddraw_from_ddraw3(iface);
3936     HRESULT hr;
3937
3938     TRACE("iface %p, flags %#x, entries %p, palette %p, outer_unknown %p.\n",
3939             iface, flags, entries, palette, outer_unknown);
3940
3941     hr = ddraw7_CreatePalette((IDirectDraw7 *)ddraw, flags, entries, palette, outer_unknown);
3942     if (SUCCEEDED(hr) && *palette)
3943     {
3944         IDirectDrawPaletteImpl *impl = (IDirectDrawPaletteImpl *)*palette;
3945         IDirectDraw7_Release((IDirectDraw7 *)ddraw);
3946         IDirectDraw4_AddRef(iface);
3947         impl->ifaceToRelease = (IUnknown *)iface;
3948     }
3949
3950     return hr;
3951 }
3952
3953 static HRESULT WINAPI ddraw2_CreatePalette(IDirectDraw2 *iface, DWORD flags,
3954         PALETTEENTRY *entries, IDirectDrawPalette **palette, IUnknown *outer_unknown)
3955 {
3956     IDirectDrawImpl *ddraw = ddraw_from_ddraw2(iface);
3957     HRESULT hr;
3958
3959     TRACE("iface %p, flags %#x, entries %p, palette %p, outer_unknown %p.\n",
3960             iface, flags, entries, palette, outer_unknown);
3961
3962     hr = ddraw7_CreatePalette((IDirectDraw7 *)ddraw, flags, entries, palette, outer_unknown);
3963     if (SUCCEEDED(hr) && *palette)
3964     {
3965         IDirectDrawPaletteImpl *impl = (IDirectDrawPaletteImpl *)*palette;
3966         IDirectDraw7_Release((IDirectDraw7 *)ddraw);
3967         impl->ifaceToRelease = NULL;
3968     }
3969
3970     return hr;
3971 }
3972
3973 static HRESULT WINAPI ddraw1_CreatePalette(IDirectDraw *iface, DWORD flags,
3974         PALETTEENTRY *entries, IDirectDrawPalette **palette, IUnknown *outer_unknown)
3975 {
3976     IDirectDrawImpl *ddraw = ddraw_from_ddraw1(iface);
3977     HRESULT hr;
3978
3979     TRACE("iface %p, flags %#x, entries %p, palette %p, outer_unknown %p.\n",
3980             iface, flags, entries, palette, outer_unknown);
3981
3982     hr = ddraw7_CreatePalette((IDirectDraw7 *)ddraw, flags, entries, palette, outer_unknown);
3983     if (SUCCEEDED(hr) && *palette)
3984     {
3985         IDirectDrawPaletteImpl *impl = (IDirectDrawPaletteImpl *)*palette;
3986         IDirectDraw7_Release((IDirectDraw7 *)ddraw);
3987         impl->ifaceToRelease = NULL;
3988     }
3989
3990     return hr;
3991 }
3992
3993 /*****************************************************************************
3994  * IDirectDraw7::DuplicateSurface
3995  *
3996  * Duplicates a surface. The surface memory points to the same memory as
3997  * the original surface, and it's released when the last surface referencing
3998  * it is released. I guess that's beyond Wine's surface management right now
3999  * (Idea: create a new DDraw surface with the same WineD3DSurface. I need a
4000  * test application to implement this)
4001  *
4002  * Params:
4003  *  Src: Address of the source surface
4004  *  Dest: Address to write the new surface pointer to
4005  *
4006  * Returns:
4007  *  See IDirectDraw7::CreateSurface
4008  *
4009  *****************************************************************************/
4010 static HRESULT WINAPI ddraw7_DuplicateSurface(IDirectDraw7 *iface,
4011         IDirectDrawSurface7 *Src, IDirectDrawSurface7 **Dest)
4012 {
4013     IDirectDrawSurfaceImpl *Surf = (IDirectDrawSurfaceImpl *)Src;
4014
4015     FIXME("iface %p, src %p, dst %p partial stub!\n", iface, Src, Dest);
4016
4017     /* For now, simply create a new, independent surface */
4018     return IDirectDraw7_CreateSurface(iface,
4019                                       &Surf->surface_desc,
4020                                       Dest,
4021                                       NULL);
4022 }
4023
4024 static HRESULT WINAPI ddraw4_DuplicateSurface(IDirectDraw4 *iface,
4025         IDirectDrawSurface4 *src, IDirectDrawSurface4 **dst)
4026 {
4027     TRACE("iface %p, src %p, dst %p.\n", iface, src, dst);
4028
4029     return ddraw7_DuplicateSurface((IDirectDraw7 *)ddraw_from_ddraw4(iface),
4030             (IDirectDrawSurface7 *)src, (IDirectDrawSurface7 **)dst);
4031 }
4032
4033 static HRESULT WINAPI ddraw3_DuplicateSurface(IDirectDraw3 *iface,
4034         IDirectDrawSurface *src, IDirectDrawSurface **dst)
4035 {
4036     IDirectDrawSurface7 *src7, *dst7;
4037     HRESULT hr;
4038
4039     TRACE("iface %p, src %p, dst %p.\n", iface, src, dst);
4040     src7 = (IDirectDrawSurface7 *)surface_from_surface3((IDirectDrawSurface3 *)src);
4041     hr = ddraw7_DuplicateSurface((IDirectDraw7 *)ddraw_from_ddraw3(iface), src7, &dst7);
4042     if (FAILED(hr))
4043         return hr;
4044     *dst = (IDirectDrawSurface *)&((IDirectDrawSurfaceImpl *)dst7)->IDirectDrawSurface3_vtbl;
4045     return hr;
4046 }
4047
4048 static HRESULT WINAPI ddraw2_DuplicateSurface(IDirectDraw2 *iface,
4049         IDirectDrawSurface *src, IDirectDrawSurface **dst)
4050 {
4051     IDirectDrawSurface7 *src7, *dst7;
4052     HRESULT hr;
4053
4054     TRACE("iface %p, src %p, dst %p.\n", iface, src, dst);
4055     src7 = (IDirectDrawSurface7 *)surface_from_surface3((IDirectDrawSurface3 *)src);
4056     hr = ddraw7_DuplicateSurface((IDirectDraw7 *)ddraw_from_ddraw2(iface), src7, &dst7);
4057     if (FAILED(hr))
4058         return hr;
4059     *dst = (IDirectDrawSurface *)&((IDirectDrawSurfaceImpl *)dst7)->IDirectDrawSurface3_vtbl;
4060     return hr;
4061 }
4062
4063 static HRESULT WINAPI ddraw1_DuplicateSurface(IDirectDraw *iface,
4064         IDirectDrawSurface *src, IDirectDrawSurface **dst)
4065 {
4066     IDirectDrawSurface7 *src7, *dst7;
4067     HRESULT hr;
4068
4069     TRACE("iface %p, src %p, dst %p.\n", iface, src, dst);
4070     src7 = (IDirectDrawSurface7 *)surface_from_surface3((IDirectDrawSurface3 *)src);
4071     hr = ddraw7_DuplicateSurface((IDirectDraw7 *)ddraw_from_ddraw1(iface), src7, &dst7);
4072     if (FAILED(hr))
4073         return hr;
4074     *dst = (IDirectDrawSurface *)&((IDirectDrawSurfaceImpl *)dst7)->IDirectDrawSurface3_vtbl;
4075     return hr;
4076 }
4077
4078 /*****************************************************************************
4079  * IDirect3D7::EnumDevices
4080  *
4081  * The EnumDevices method for IDirect3D7. It enumerates all supported
4082  * D3D7 devices. Currently the T&L, HAL and RGB devices are enumerated.
4083  *
4084  * Params:
4085  *  callback: Function to call for each enumerated device
4086  *  context: Pointer to pass back to the app
4087  *
4088  * Returns:
4089  *  D3D_OK, or the return value of the GetCaps call
4090  *
4091  *****************************************************************************/
4092 static HRESULT WINAPI d3d7_EnumDevices(IDirect3D7 *iface, LPD3DENUMDEVICESCALLBACK7 callback, void *context)
4093 {
4094     char interface_name_tnl[] = "WINE Direct3D7 Hardware Transform and Lighting acceleration using WineD3D";
4095     char device_name_tnl[] = "Wine D3D7 T&L HAL";
4096     char interface_name_hal[] = "WINE Direct3D7 Hardware acceleration using WineD3D";
4097     char device_name_hal[] = "Wine D3D7 HAL";
4098     char interface_name_rgb[] = "WINE Direct3D7 RGB Software Emulation using WineD3D";
4099     char device_name_rgb[] = "Wine D3D7 RGB";
4100
4101     IDirectDrawImpl *ddraw = ddraw_from_d3d7(iface);
4102     D3DDEVICEDESC7 device_desc7;
4103     D3DDEVICEDESC device_desc1;
4104     HRESULT hr;
4105
4106     TRACE("iface %p, callback %p, context %p.\n", iface, callback, context);
4107
4108     EnterCriticalSection(&ddraw_cs);
4109
4110     hr = IDirect3DImpl_GetCaps(ddraw->wineD3D, &device_desc1, &device_desc7);
4111     if (hr != D3D_OK)
4112     {
4113         LeaveCriticalSection(&ddraw_cs);
4114         return hr;
4115     }
4116     callback(interface_name_tnl, device_name_tnl, &device_desc7, context);
4117
4118     device_desc7.deviceGUID = IID_IDirect3DHALDevice;
4119     callback(interface_name_hal, device_name_hal, &device_desc7, context);
4120
4121     device_desc7.deviceGUID = IID_IDirect3DRGBDevice;
4122     callback(interface_name_rgb, device_name_rgb, &device_desc7, context);
4123
4124     TRACE("End of enumeration.\n");
4125
4126     LeaveCriticalSection(&ddraw_cs);
4127
4128     return D3D_OK;
4129 }
4130
4131 /*****************************************************************************
4132  * IDirect3D3::EnumDevices
4133  *
4134  * Enumerates all supported Direct3DDevice interfaces. This is the
4135  * implementation for Direct3D 1 to Direc3D 3, Version 7 has its own.
4136  *
4137  * Version 1, 2 and 3
4138  *
4139  * Params:
4140  *  callback: Application-provided routine to call for each enumerated device
4141  *  Context: Pointer to pass to the callback
4142  *
4143  * Returns:
4144  *  D3D_OK on success,
4145  *  The result of IDirect3DImpl_GetCaps if it failed
4146  *
4147  *****************************************************************************/
4148 static HRESULT WINAPI d3d3_EnumDevices(IDirect3D3 *iface, LPD3DENUMDEVICESCALLBACK callback, void *context)
4149 {
4150     static CHAR wined3d_description[] = "Wine D3DDevice using WineD3D and OpenGL";
4151
4152     IDirectDrawImpl *ddraw = ddraw_from_d3d3(iface);
4153     D3DDEVICEDESC device_desc1, hal_desc, hel_desc;
4154     D3DDEVICEDESC7 device_desc7;
4155     HRESULT hr;
4156
4157     /* Some games (Motoracer 2 demo) have the bad idea to modify the device
4158      * name string. Let's put the string in a sufficiently sized array in
4159      * writable memory. */
4160     char device_name[50];
4161     strcpy(device_name,"Direct3D HEL");
4162
4163     TRACE("iface %p, callback %p, context %p.\n", iface, callback, context);
4164
4165     EnterCriticalSection(&ddraw_cs);
4166
4167     hr = IDirect3DImpl_GetCaps(ddraw->wineD3D, &device_desc1, &device_desc7);
4168     if (hr != D3D_OK)
4169     {
4170         LeaveCriticalSection(&ddraw_cs);
4171         return hr;
4172     }
4173
4174     /* Do I have to enumerate the reference id? Note from old d3d7:
4175      * "It seems that enumerating the reference IID on Direct3D 1 games
4176      * (AvP / Motoracer2) breaks them". So do not enumerate this iid in V1
4177      *
4178      * There's a registry key HKLM\Software\Microsoft\Direct3D\Drivers,
4179      * EnumReference which enables / disables enumerating the reference
4180      * rasterizer. It's a DWORD, 0 means disabled, 2 means enabled. The
4181      * enablerefrast.reg and disablerefrast.reg files in the DirectX 7.0 sdk
4182      * demo directory suggest this.
4183      *
4184      * Some games(GTA 2) seem to use the second enumerated device, so I have
4185      * to enumerate at least 2 devices. So enumerate the reference device to
4186      * have 2 devices.
4187      *
4188      * Other games (Rollcage) tell emulation and hal device apart by certain
4189      * flags. Rollcage expects D3DPTEXTURECAPS_POW2 to be set (yeah, it is a
4190      * limitation flag), and it refuses all devices that have the perspective
4191      * flag set. This way it refuses the emulation device, and HAL devices
4192      * never have POW2 unset in d3d7 on windows. */
4193     if (ddraw->d3dversion != 1)
4194     {
4195         static CHAR reference_description[] = "RGB Direct3D emulation";
4196
4197         TRACE("Enumerating WineD3D D3DDevice interface.\n");
4198         hal_desc = device_desc1;
4199         hel_desc = device_desc1;
4200         /* The rgb device has the pow2 flag set in the hel caps, but not in the hal caps. */
4201         hal_desc.dpcLineCaps.dwTextureCaps &= ~(D3DPTEXTURECAPS_POW2
4202                 | D3DPTEXTURECAPS_NONPOW2CONDITIONAL | D3DPTEXTURECAPS_PERSPECTIVE);
4203         hal_desc.dpcTriCaps.dwTextureCaps &= ~(D3DPTEXTURECAPS_POW2
4204                 | D3DPTEXTURECAPS_NONPOW2CONDITIONAL | D3DPTEXTURECAPS_PERSPECTIVE);
4205         hr = callback((GUID *)&IID_IDirect3DRGBDevice, reference_description,
4206                 device_name, &hal_desc, &hel_desc, context);
4207         if (hr != D3DENUMRET_OK)
4208         {
4209             TRACE("Application cancelled the enumeration.\n");
4210             LeaveCriticalSection(&ddraw_cs);
4211             return D3D_OK;
4212         }
4213     }
4214
4215     strcpy(device_name,"Direct3D HAL");
4216
4217     TRACE("Enumerating HAL Direct3D device.\n");
4218     hal_desc = device_desc1;
4219     hel_desc = device_desc1;
4220     /* The hal device does not have the pow2 flag set in hel, but in hal. */
4221     hel_desc.dpcLineCaps.dwTextureCaps &= ~(D3DPTEXTURECAPS_POW2
4222             | D3DPTEXTURECAPS_NONPOW2CONDITIONAL | D3DPTEXTURECAPS_PERSPECTIVE);
4223     hel_desc.dpcTriCaps.dwTextureCaps &= ~(D3DPTEXTURECAPS_POW2
4224             | D3DPTEXTURECAPS_NONPOW2CONDITIONAL | D3DPTEXTURECAPS_PERSPECTIVE);
4225     hr = callback((GUID *)&IID_IDirect3DHALDevice, wined3d_description,
4226             device_name, &hal_desc, &hel_desc, context);
4227     if (hr != D3DENUMRET_OK)
4228     {
4229         TRACE("Application cancelled the enumeration.\n");
4230         LeaveCriticalSection(&ddraw_cs);
4231         return D3D_OK;
4232     }
4233
4234     TRACE("End of enumeration.\n");
4235
4236     LeaveCriticalSection(&ddraw_cs);
4237     return D3D_OK;
4238 }
4239
4240 static HRESULT WINAPI d3d2_EnumDevices(IDirect3D2 *iface, LPD3DENUMDEVICESCALLBACK callback, void *context)
4241 {
4242     TRACE("iface %p, callback %p, context %p.\n", iface, callback, context);
4243
4244     return d3d3_EnumDevices((IDirect3D3 *)&ddraw_from_d3d2(iface)->IDirect3D3_vtbl, callback, context);
4245 }
4246
4247 static HRESULT WINAPI d3d1_EnumDevices(IDirect3D *iface, LPD3DENUMDEVICESCALLBACK callback, void *context)
4248 {
4249     TRACE("iface %p, callback %p, context %p.\n", iface, callback, context);
4250
4251     return d3d3_EnumDevices((IDirect3D3 *)&ddraw_from_d3d1(iface)->IDirect3D3_vtbl, callback, context);
4252 }
4253
4254 /*****************************************************************************
4255  * IDirect3D3::CreateLight
4256  *
4257  * Creates an IDirect3DLight interface. This interface is used in
4258  * Direct3D3 or earlier for lighting. In Direct3D7 it has been replaced
4259  * by the DIRECT3DLIGHT7 structure. Wine's Direct3DLight implementation
4260  * uses the IDirect3DDevice7 interface with D3D7 lights.
4261  *
4262  * Version 1, 2 and 3
4263  *
4264  * Params:
4265  *  light: Address to store the new interface pointer
4266  *  outer_unknown: Basically for aggregation, but ddraw doesn't support it.
4267  *                 Must be NULL
4268  *
4269  * Returns:
4270  *  D3D_OK on success
4271  *  DDERR_OUTOFMEMORY if memory allocation failed
4272  *  CLASS_E_NOAGGREGATION if outer_unknown != NULL
4273  *
4274  *****************************************************************************/
4275 static HRESULT WINAPI d3d3_CreateLight(IDirect3D3 *iface, IDirect3DLight **light, IUnknown *outer_unknown)
4276 {
4277     IDirect3DLightImpl *object;
4278
4279     TRACE("iface %p, light %p, outer_unknown %p.\n", iface, light, outer_unknown);
4280
4281     if (outer_unknown) return CLASS_E_NOAGGREGATION;
4282
4283     object = HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, sizeof(*object));
4284     if (!object)
4285     {
4286         ERR("Failed to allocate light memory.\n");
4287         return DDERR_OUTOFMEMORY;
4288     }
4289
4290     d3d_light_init(object, ddraw_from_d3d3(iface));
4291
4292     TRACE("Created light %p.\n", object);
4293     *light = (IDirect3DLight *)object;
4294
4295     return D3D_OK;
4296 }
4297
4298 static HRESULT WINAPI d3d2_CreateLight(IDirect3D2 *iface, IDirect3DLight **light, IUnknown *outer_unknown)
4299 {
4300     TRACE("iface %p, light %p, outer_unknown %p.\n", iface, light, outer_unknown);
4301
4302     return d3d3_CreateLight((IDirect3D3 *)&ddraw_from_d3d2(iface)->IDirect3D3_vtbl, light, outer_unknown);
4303 }
4304
4305 static HRESULT WINAPI d3d1_CreateLight(IDirect3D *iface, IDirect3DLight **light, IUnknown *outer_unknown)
4306 {
4307     TRACE("iface %p, light %p, outer_unknown %p.\n", iface, light, outer_unknown);
4308
4309     return d3d3_CreateLight((IDirect3D3 *)&ddraw_from_d3d1(iface)->IDirect3D3_vtbl, light, outer_unknown);
4310 }
4311
4312 /*****************************************************************************
4313  * IDirect3D3::CreateMaterial
4314  *
4315  * Creates an IDirect3DMaterial interface. This interface is used by Direct3D3
4316  * and older versions. The IDirect3DMaterial implementation wraps its
4317  * functionality to IDirect3DDevice7::SetMaterial and friends.
4318  *
4319  * Version 1, 2 and 3
4320  *
4321  * Params:
4322  *  material: Address to store the new interface's pointer to
4323  *  outer_unknown: Basically for aggregation, but ddraw doesn't support it.
4324  *                 Must be NULL
4325  *
4326  * Returns:
4327  *  D3D_OK on success
4328  *  DDERR_OUTOFMEMORY if memory allocation failed
4329  *  CLASS_E_NOAGGREGATION if outer_unknown != NULL
4330  *
4331  *****************************************************************************/
4332 static HRESULT WINAPI d3d3_CreateMaterial(IDirect3D3 *iface, IDirect3DMaterial3 **material, IUnknown *outer_unknown)
4333 {
4334     IDirect3DMaterialImpl *object;
4335
4336     TRACE("iface %p, material %p, outer_unknown %p.\n", iface, material, outer_unknown);
4337
4338     if (outer_unknown) return CLASS_E_NOAGGREGATION;
4339
4340     object = HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, sizeof(*object));
4341     if (!object)
4342     {
4343         ERR("Failed to allocate material memory.\n");
4344         return DDERR_OUTOFMEMORY;
4345     }
4346
4347     d3d_material_init(object, ddraw_from_d3d3(iface));
4348
4349     TRACE("Created material %p.\n", object);
4350     *material = (IDirect3DMaterial3 *)object;
4351
4352     return D3D_OK;
4353 }
4354
4355 static HRESULT WINAPI d3d2_CreateMaterial(IDirect3D2 *iface, IDirect3DMaterial2 **material, IUnknown *outer_unknown)
4356 {
4357     IDirect3DMaterial3 *material3;
4358     HRESULT hr;
4359
4360     TRACE("iface %p, material %p, outer_unknown %p.\n", iface, material, outer_unknown);
4361
4362     hr = d3d3_CreateMaterial((IDirect3D3 *)&ddraw_from_d3d2(iface)->IDirect3D3_vtbl, &material3, outer_unknown);
4363     *material = material3 ? (IDirect3DMaterial2 *)&((IDirect3DMaterialImpl *)material3)->IDirect3DMaterial2_vtbl : NULL;
4364
4365     TRACE("Returning material %p.\n", *material);
4366
4367     return hr;
4368 }
4369
4370 static HRESULT WINAPI d3d1_CreateMaterial(IDirect3D *iface, IDirect3DMaterial **material, IUnknown *outer_unknown)
4371 {
4372     IDirect3DMaterial3 *material3;
4373     HRESULT hr;
4374
4375     TRACE("iface %p, material %p, outer_unknown %p.\n", iface, material, outer_unknown);
4376
4377     hr = d3d3_CreateMaterial((IDirect3D3 *)&ddraw_from_d3d1(iface)->IDirect3D3_vtbl, &material3, outer_unknown);
4378     *material = material3 ? (IDirect3DMaterial *)&((IDirect3DMaterialImpl *)material3)->IDirect3DMaterial_vtbl : NULL;
4379
4380     TRACE("Returning material %p.\n", *material);
4381
4382     return hr;
4383 }
4384
4385 /*****************************************************************************
4386  * IDirect3D3::CreateViewport
4387  *
4388  * Creates an IDirect3DViewport interface. This interface is used
4389  * by Direct3D and earlier versions for Viewport management. In Direct3D7
4390  * it has been replaced by a viewport structure and
4391  * IDirect3DDevice7::*Viewport. Wine's IDirect3DViewport implementation
4392  * uses the IDirect3DDevice7 methods for its functionality
4393  *
4394  * Params:
4395  *  Viewport: Address to store the new interface pointer
4396  *  outer_unknown: Basically for aggregation, but ddraw doesn't support it.
4397  *                 Must be NULL
4398  *
4399  * Returns:
4400  *  D3D_OK on success
4401  *  DDERR_OUTOFMEMORY if memory allocation failed
4402  *  CLASS_E_NOAGGREGATION if outer_unknown != NULL
4403  *
4404  *****************************************************************************/
4405 static HRESULT WINAPI d3d3_CreateViewport(IDirect3D3 *iface, IDirect3DViewport3 **viewport, IUnknown *outer_unknown)
4406 {
4407     IDirect3DViewportImpl *object;
4408
4409     TRACE("iface %p, viewport %p, outer_unknown %p.\n", iface, viewport, outer_unknown);
4410
4411     if (outer_unknown) return CLASS_E_NOAGGREGATION;
4412
4413     object = HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, sizeof(*object));
4414     if (!object)
4415     {
4416         ERR("Failed to allocate viewport memory.\n");
4417         return DDERR_OUTOFMEMORY;
4418     }
4419
4420     d3d_viewport_init(object, ddraw_from_d3d3(iface));
4421
4422     TRACE("Created viewport %p.\n", object);
4423     *viewport = (IDirect3DViewport3 *)object;
4424
4425     return D3D_OK;
4426 }
4427
4428 static HRESULT WINAPI d3d2_CreateViewport(IDirect3D2 *iface, IDirect3DViewport2 **viewport, IUnknown *outer_unknown)
4429 {
4430     TRACE("iface %p, viewport %p, outer_unknown %p.\n", iface, viewport, outer_unknown);
4431
4432     return d3d3_CreateViewport((IDirect3D3 *)&ddraw_from_d3d2(iface)->IDirect3D3_vtbl,
4433             (IDirect3DViewport3 **)viewport, outer_unknown);
4434 }
4435
4436 static HRESULT WINAPI d3d1_CreateViewport(IDirect3D *iface, IDirect3DViewport **viewport, IUnknown *outer_unknown)
4437 {
4438     TRACE("iface %p, viewport %p, outer_unknown %p.\n", iface, viewport, outer_unknown);
4439
4440     return d3d3_CreateViewport((IDirect3D3 *)&ddraw_from_d3d1(iface)->IDirect3D3_vtbl,
4441             (IDirect3DViewport3 **)viewport, outer_unknown);
4442 }
4443
4444 /*****************************************************************************
4445  * IDirect3D3::FindDevice
4446  *
4447  * This method finds a device with the requested properties and returns a
4448  * device description
4449  *
4450  * Verion 1, 2 and 3
4451  * Params:
4452  *  fds: Describes the requested device characteristics
4453  *  fdr: Returns the device description
4454  *
4455  * Returns:
4456  *  D3D_OK on success
4457  *  DDERR_INVALIDPARAMS if no device was found
4458  *
4459  *****************************************************************************/
4460 static HRESULT WINAPI d3d3_FindDevice(IDirect3D3 *iface, D3DFINDDEVICESEARCH *fds, D3DFINDDEVICERESULT *fdr)
4461 {
4462     IDirectDrawImpl *ddraw = ddraw_from_d3d3(iface);
4463     D3DDEVICEDESC7 desc7;
4464     D3DDEVICEDESC desc1;
4465     HRESULT hr;
4466
4467     TRACE("iface %p, fds %p, fdr %p.\n", iface, fds, fdr);
4468
4469     if (!fds || !fdr) return DDERR_INVALIDPARAMS;
4470
4471     if (fds->dwSize != sizeof(D3DFINDDEVICESEARCH)
4472             || fdr->dwSize != sizeof(D3DFINDDEVICERESULT))
4473         return DDERR_INVALIDPARAMS;
4474
4475     if ((fds->dwFlags & D3DFDS_COLORMODEL)
4476             && fds->dcmColorModel != D3DCOLOR_RGB)
4477     {
4478         WARN("Trying to request a non-RGB D3D color model. Not supported.\n");
4479         return DDERR_INVALIDPARAMS; /* No real idea what to return here :-) */
4480     }
4481
4482     if (fds->dwFlags & D3DFDS_GUID)
4483     {
4484         TRACE("Trying to match guid %s.\n", debugstr_guid(&(fds->guid)));
4485         if (!IsEqualGUID(&IID_D3DDEVICE_WineD3D, &fds->guid)
4486                 && !IsEqualGUID(&IID_IDirect3DHALDevice, &fds->guid)
4487                 && !IsEqualGUID(&IID_IDirect3DRGBDevice, &fds->guid))
4488         {
4489             WARN("No match for this GUID.\n");
4490             return DDERR_NOTFOUND;
4491         }
4492     }
4493
4494     /* Get the caps */
4495     hr = IDirect3DImpl_GetCaps(ddraw->wineD3D, &desc1, &desc7);
4496     if (hr != D3D_OK) return hr;
4497
4498     /* Now return our own GUID */
4499     fdr->guid = IID_D3DDEVICE_WineD3D;
4500     fdr->ddHwDesc = desc1;
4501     fdr->ddSwDesc = desc1;
4502
4503     TRACE("Returning Wine's wined3d device with (undumped) capabilities.\n");
4504
4505     return D3D_OK;
4506 }
4507
4508 static HRESULT WINAPI d3d2_FindDevice(IDirect3D2 *iface, D3DFINDDEVICESEARCH *fds, D3DFINDDEVICERESULT *fdr)
4509 {
4510     TRACE("iface %p, fds %p, fdr %p.\n", iface, fds, fdr);
4511
4512     return d3d3_FindDevice((IDirect3D3 *)&ddraw_from_d3d2(iface)->IDirect3D3_vtbl, fds, fdr);
4513 }
4514
4515 static HRESULT WINAPI d3d1_FindDevice(IDirect3D *iface, D3DFINDDEVICESEARCH *fds, D3DFINDDEVICERESULT *fdr)
4516 {
4517     TRACE("iface %p, fds %p, fdr %p.\n", iface, fds, fdr);
4518
4519     return d3d3_FindDevice((IDirect3D3 *)&ddraw_from_d3d1(iface)->IDirect3D3_vtbl, fds, fdr);
4520 }
4521
4522 /*****************************************************************************
4523  * IDirect3D7::CreateDevice
4524  *
4525  * Creates an IDirect3DDevice7 interface.
4526  *
4527  * Version 2, 3 and 7. IDirect3DDevice 1 interfaces are interfaces to
4528  * DirectDraw surfaces and are created with
4529  * IDirectDrawSurface::QueryInterface. This method uses CreateDevice to
4530  * create the device object and QueryInterfaces for IDirect3DDevice
4531  *
4532  * Params:
4533  *  refiid: IID of the device to create
4534  *  Surface: Initial rendertarget
4535  *  Device: Address to return the interface pointer
4536  *
4537  * Returns:
4538  *  D3D_OK on success
4539  *  DDERR_OUTOFMEMORY if memory allocation failed
4540  *  DDERR_INVALIDPARAMS if a device exists already
4541  *
4542  *****************************************************************************/
4543 static HRESULT WINAPI d3d7_CreateDevice(IDirect3D7 *iface, REFCLSID riid,
4544         IDirectDrawSurface7 *surface, IDirect3DDevice7 **device)
4545 {
4546     IDirectDrawSurfaceImpl *target = (IDirectDrawSurfaceImpl *)surface;
4547     IDirectDrawImpl *ddraw = ddraw_from_d3d7(iface);
4548     IDirect3DDeviceImpl *object;
4549     HRESULT hr;
4550
4551     TRACE("iface %p, riid %s, surface %p, device %p.\n", iface, debugstr_guid(riid), surface, device);
4552
4553     EnterCriticalSection(&ddraw_cs);
4554     *device = NULL;
4555
4556     /* Fail device creation if non-opengl surfaces are used. */
4557     if (ddraw->ImplType != SURFACE_OPENGL)
4558     {
4559         ERR("The application wants to create a Direct3D device, but non-opengl surfaces are set in the registry.\n");
4560         ERR("Please set the surface implementation to opengl or autodetection to allow 3D rendering.\n");
4561
4562         /* We only hit this path if a default surface is set in the registry. Incorrect autodetection
4563          * is caught in CreateSurface or QueryInterface. */
4564         LeaveCriticalSection(&ddraw_cs);
4565         return DDERR_NO3D;
4566     }
4567
4568     if (ddraw->d3ddevice)
4569     {
4570         FIXME("Only one Direct3D device per DirectDraw object supported.\n");
4571         LeaveCriticalSection(&ddraw_cs);
4572         return DDERR_INVALIDPARAMS;
4573     }
4574
4575     object = HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, sizeof(*object));
4576     if (!object)
4577     {
4578         ERR("Failed to allocate device memory.\n");
4579         LeaveCriticalSection(&ddraw_cs);
4580         return DDERR_OUTOFMEMORY;
4581     }
4582
4583     hr = d3d_device_init(object, ddraw, target);
4584     if (FAILED(hr))
4585     {
4586         WARN("Failed to initialize device, hr %#x.\n", hr);
4587         HeapFree(GetProcessHeap(), 0, object);
4588         LeaveCriticalSection(&ddraw_cs);
4589         return hr;
4590     }
4591
4592     TRACE("Created device %p.\n", object);
4593     *device = (IDirect3DDevice7 *)object;
4594
4595     LeaveCriticalSection(&ddraw_cs);
4596     return D3D_OK;
4597 }
4598
4599 static HRESULT WINAPI d3d3_CreateDevice(IDirect3D3 *iface, REFCLSID riid,
4600         IDirectDrawSurface4 *surface, IDirect3DDevice3 **device, IUnknown *outer_unknown)
4601 {
4602     HRESULT hr;
4603
4604     TRACE("iface %p, riid %s, surface %p, device %p, outer_unknown %p.\n",
4605             iface, debugstr_guid(riid), surface, device, outer_unknown);
4606
4607     if (outer_unknown) return CLASS_E_NOAGGREGATION;
4608
4609     hr = d3d7_CreateDevice((IDirect3D7 *)&ddraw_from_d3d3(iface)->IDirect3D7_vtbl, riid,
4610             (IDirectDrawSurface7 *)surface, (IDirect3DDevice7 **)device);
4611     if (*device) *device = (IDirect3DDevice3 *)&((IDirect3DDeviceImpl *)*device)->IDirect3DDevice3_vtbl;
4612
4613     return hr;
4614 }
4615
4616 static HRESULT WINAPI d3d2_CreateDevice(IDirect3D2 *iface, REFCLSID riid,
4617         IDirectDrawSurface *surface, IDirect3DDevice2 **device)
4618 {
4619     HRESULT hr;
4620
4621     TRACE("iface %p, riid %s, surface %p, device %p.\n",
4622             iface, debugstr_guid(riid), surface, device);
4623
4624     hr = d3d7_CreateDevice((IDirect3D7 *)&ddraw_from_d3d2(iface)->IDirect3D7_vtbl, riid,
4625             surface ? (IDirectDrawSurface7 *)surface_from_surface3((IDirectDrawSurface3 *)surface) : NULL,
4626             (IDirect3DDevice7 **)device);
4627     if (*device) *device = (IDirect3DDevice2 *)&((IDirect3DDeviceImpl *)*device)->IDirect3DDevice2_vtbl;
4628
4629     return hr;
4630 }
4631
4632 /*****************************************************************************
4633  * IDirect3D7::CreateVertexBuffer
4634  *
4635  * Creates a new vertex buffer object and returns a IDirect3DVertexBuffer7
4636  * interface.
4637  *
4638  * Version 3 and 7
4639  *
4640  * Params:
4641  *  desc: Requested Vertex buffer properties
4642  *  vertex_buffer: Address to return the interface pointer at
4643  *  flags: Some flags, should be 0
4644  *
4645  * Returns
4646  *  D3D_OK on success
4647  *  DDERR_OUTOFMEMORY if memory allocation failed
4648  *  The return value of IWineD3DDevice::CreateVertexBuffer if this call fails
4649  *  DDERR_INVALIDPARAMS if desc or vertex_buffer are NULL
4650  *
4651  *****************************************************************************/
4652 static HRESULT WINAPI d3d7_CreateVertexBuffer(IDirect3D7 *iface, D3DVERTEXBUFFERDESC *desc,
4653         IDirect3DVertexBuffer7 **vertex_buffer, DWORD flags)
4654 {
4655     IDirect3DVertexBufferImpl *object;
4656     HRESULT hr;
4657
4658     TRACE("iface %p, desc %p, vertex_buffer %p, flags %#x.\n",
4659             iface, desc, vertex_buffer, flags);
4660
4661     if (!vertex_buffer || !desc) return DDERR_INVALIDPARAMS;
4662
4663     TRACE("Vertex buffer description:\n");
4664     TRACE("    dwSize %u\n", desc->dwSize);
4665     TRACE("    dwCaps %#x\n", desc->dwCaps);
4666     TRACE("    FVF %#x\n", desc->dwFVF);
4667     TRACE("    dwNumVertices %u\n", desc->dwNumVertices);
4668
4669     /* Now create the vertex buffer */
4670     object = HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, sizeof(*object));
4671     if (!object)
4672     {
4673         ERR("Failed to allocate vertex buffer memory.\n");
4674         return DDERR_OUTOFMEMORY;
4675     }
4676
4677     hr = d3d_vertex_buffer_init(object, ddraw_from_d3d7(iface), desc);
4678     if (FAILED(hr))
4679     {
4680         WARN("Failed to initialize vertex buffer, hr %#x.\n", hr);
4681         HeapFree(GetProcessHeap(), 0, object);
4682         return hr;
4683     }
4684
4685     TRACE("Created vertex buffer %p.\n", object);
4686     *vertex_buffer = (IDirect3DVertexBuffer7 *)object;
4687
4688     return D3D_OK;
4689 }
4690
4691 static HRESULT WINAPI d3d3_CreateVertexBuffer(IDirect3D3 *iface, D3DVERTEXBUFFERDESC *desc,
4692         IDirect3DVertexBuffer **vertex_buffer, DWORD flags, IUnknown *outer_unknown)
4693 {
4694     IDirectDrawImpl *This = ddraw_from_d3d3(iface);
4695     HRESULT hr;
4696
4697     TRACE("iface %p, desc %p, vertex_buffer %p, flags %#x, outer_unknown %p.\n",
4698             iface, desc, vertex_buffer, flags, outer_unknown);
4699
4700     if (outer_unknown) return CLASS_E_NOAGGREGATION;
4701
4702     hr = d3d7_CreateVertexBuffer((IDirect3D7 *)&This->IDirect3D7_vtbl,
4703             desc, (IDirect3DVertexBuffer7 **)vertex_buffer, flags);
4704     if (*vertex_buffer)
4705         *vertex_buffer = (IDirect3DVertexBuffer *)&((IDirect3DVertexBufferImpl *)*vertex_buffer)->IDirect3DVertexBuffer_vtbl;
4706
4707     return hr;
4708 }
4709
4710 /*****************************************************************************
4711  * IDirect3D7::EnumZBufferFormats
4712  *
4713  * Enumerates all supported Z buffer pixel formats
4714  *
4715  * Version 3 and 7
4716  *
4717  * Params:
4718  *  device_iid:
4719  *  callback: callback to call for each pixel format
4720  *  context: Pointer to pass back to the callback
4721  *
4722  * Returns:
4723  *  D3D_OK on success
4724  *  DDERR_INVALIDPARAMS if callback is NULL
4725  *  For details, see IWineD3DDevice::EnumZBufferFormats
4726  *
4727  *****************************************************************************/
4728 static HRESULT WINAPI d3d7_EnumZBufferFormats(IDirect3D7 *iface, REFCLSID device_iid,
4729         LPD3DENUMPIXELFORMATSCALLBACK callback, void *context)
4730 {
4731     IDirectDrawImpl *ddraw = ddraw_from_d3d7(iface);
4732     WINED3DDISPLAYMODE d3ddm;
4733     WINED3DDEVTYPE type;
4734     unsigned int i;
4735     HRESULT hr;
4736
4737     /* Order matters. Specifically, BattleZone II (full version) expects the
4738      * 16-bit depth formats to be listed before the 24 and 32 ones. */
4739     static const enum wined3d_format_id formats[] =
4740     {
4741         WINED3DFMT_S1_UINT_D15_UNORM,
4742         WINED3DFMT_D16_UNORM,
4743         WINED3DFMT_X8D24_UNORM,
4744         WINED3DFMT_S4X4_UINT_D24_UNORM,
4745         WINED3DFMT_D24_UNORM_S8_UINT,
4746         WINED3DFMT_D32_UNORM,
4747     };
4748
4749     TRACE("iface %p, device_iid %s, callback %p, context %p.\n",
4750             iface, debugstr_guid(device_iid), callback, context);
4751
4752     if (!callback) return DDERR_INVALIDPARAMS;
4753
4754     if (IsEqualGUID(device_iid, &IID_IDirect3DHALDevice)
4755             || IsEqualGUID(device_iid, &IID_IDirect3DTnLHalDevice)
4756             || IsEqualGUID(device_iid, &IID_D3DDEVICE_WineD3D))
4757     {
4758         TRACE("Asked for HAL device.\n");
4759         type = WINED3DDEVTYPE_HAL;
4760     }
4761     else if (IsEqualGUID(device_iid, &IID_IDirect3DRGBDevice)
4762             || IsEqualGUID(device_iid, &IID_IDirect3DMMXDevice))
4763     {
4764         TRACE("Asked for SW device.\n");
4765         type = WINED3DDEVTYPE_SW;
4766     }
4767     else if (IsEqualGUID(device_iid, &IID_IDirect3DRefDevice))
4768     {
4769         TRACE("Asked for REF device.\n");
4770         type = WINED3DDEVTYPE_REF;
4771     }
4772     else if (IsEqualGUID(device_iid, &IID_IDirect3DNullDevice))
4773     {
4774         TRACE("Asked for NULLREF device.\n");
4775         type = WINED3DDEVTYPE_NULLREF;
4776     }
4777     else
4778     {
4779         FIXME("Unexpected device GUID %s.\n", debugstr_guid(device_iid));
4780         type = WINED3DDEVTYPE_HAL;
4781     }
4782
4783     EnterCriticalSection(&ddraw_cs);
4784     /* We need an adapter format from somewhere to please wined3d and WGL.
4785      * Use the current display mode. So far all cards offer the same depth
4786      * stencil format for all modes, but if some do not and applications do
4787      * not like that we'll have to find some workaround, like iterating over
4788      * all imaginable formats and collecting all the depth stencil formats we
4789      * can get. */
4790     hr = IWineD3DDevice_GetDisplayMode(ddraw->wineD3DDevice, 0, &d3ddm);
4791
4792     for (i = 0; i < (sizeof(formats) / sizeof(*formats)); ++i)
4793     {
4794         hr = IWineD3D_CheckDeviceFormat(ddraw->wineD3D, WINED3DADAPTER_DEFAULT, type, d3ddm.Format,
4795                 WINED3DUSAGE_DEPTHSTENCIL, WINED3DRTYPE_SURFACE, formats[i], SURFACE_OPENGL);
4796         if (SUCCEEDED(hr))
4797         {
4798             DDPIXELFORMAT pformat;
4799
4800             memset(&pformat, 0, sizeof(pformat));
4801             pformat.dwSize = sizeof(pformat);
4802             PixelFormat_WineD3DtoDD(&pformat, formats[i]);
4803
4804             TRACE("Enumerating wined3d format %#x.\n", formats[i]);
4805             hr = callback(&pformat, context);
4806             if (hr != DDENUMRET_OK)
4807             {
4808                 TRACE("Format enumeration cancelled by application.\n");
4809                 LeaveCriticalSection(&ddraw_cs);
4810                 return D3D_OK;
4811             }
4812         }
4813     }
4814     TRACE("End of enumeration.\n");
4815
4816     LeaveCriticalSection(&ddraw_cs);
4817     return D3D_OK;
4818 }
4819
4820 static HRESULT WINAPI d3d3_EnumZBufferFormats(IDirect3D3 *iface, REFCLSID device_iid,
4821         LPD3DENUMPIXELFORMATSCALLBACK callback, void *context)
4822 {
4823     TRACE("iface %p, device_iid %s, callback %p, context %p.\n",
4824             iface, debugstr_guid(device_iid), callback, context);
4825
4826     return d3d7_EnumZBufferFormats((IDirect3D7 *)&ddraw_from_d3d3(iface)->IDirect3D7_vtbl,
4827             device_iid, callback, context);
4828 }
4829
4830 /*****************************************************************************
4831  * IDirect3D7::EvictManagedTextures
4832  *
4833  * Removes all managed textures (=surfaces with DDSCAPS2_TEXTUREMANAGE or
4834  * DDSCAPS2_D3DTEXTUREMANAGE caps) to be removed from video memory.
4835  *
4836  * Version 3 and 7
4837  *
4838  * Returns:
4839  *  D3D_OK, because it's a stub
4840  *
4841  *****************************************************************************/
4842 static HRESULT WINAPI d3d7_EvictManagedTextures(IDirect3D7 *iface)
4843 {
4844     FIXME("iface %p stub!\n", iface);
4845
4846     /* TODO: Just enumerate resources using IWineD3DDevice_EnumResources(),
4847      * then unload surfaces / textures. */
4848
4849     return D3D_OK;
4850 }
4851
4852 static HRESULT WINAPI d3d3_EvictManagedTextures(IDirect3D3 *iface)
4853 {
4854     TRACE("iface %p.\n", iface);
4855
4856     return d3d7_EvictManagedTextures((IDirect3D7 *)&ddraw_from_d3d3(iface)->IDirect3D7_vtbl);
4857 }
4858
4859 /*****************************************************************************
4860  * IDirect3DImpl_GetCaps
4861  *
4862  * This function retrieves the device caps from wined3d
4863  * and converts it into a D3D7 and D3D - D3D3 structure
4864  * This is a helper function called from various places in ddraw
4865  *
4866  * Params:
4867  *  wined3d: The interface to get the caps from
4868  *  desc1: Old D3D <3 structure to fill (needed)
4869  *  desc7: D3D7 device desc structure to fill (needed)
4870  *
4871  * Returns
4872  *  D3D_OK on success, or the return value of IWineD3D::GetCaps
4873  *
4874  *****************************************************************************/
4875 HRESULT IDirect3DImpl_GetCaps(IWineD3D *wined3d, D3DDEVICEDESC *desc1, D3DDEVICEDESC7 *desc7)
4876 {
4877     WINED3DCAPS wined3d_caps;
4878     HRESULT hr;
4879
4880     TRACE("wined3d %p, desc1 %p, desc7 %p.\n", wined3d, desc1, desc7);
4881
4882     memset(&wined3d_caps, 0, sizeof(wined3d_caps));
4883
4884     EnterCriticalSection(&ddraw_cs);
4885     hr = IWineD3D_GetDeviceCaps(wined3d, 0, WINED3DDEVTYPE_HAL, &wined3d_caps);
4886     LeaveCriticalSection(&ddraw_cs);
4887     if (FAILED(hr))
4888     {
4889         WARN("Failed to get device caps, hr %#x.\n", hr);
4890         return hr;
4891     }
4892
4893     /* Copy the results into the d3d7 and d3d3 structures */
4894     desc7->dwDevCaps = wined3d_caps.DevCaps;
4895     desc7->dpcLineCaps.dwMiscCaps = wined3d_caps.PrimitiveMiscCaps;
4896     desc7->dpcLineCaps.dwRasterCaps = wined3d_caps.RasterCaps;
4897     desc7->dpcLineCaps.dwZCmpCaps = wined3d_caps.ZCmpCaps;
4898     desc7->dpcLineCaps.dwSrcBlendCaps = wined3d_caps.SrcBlendCaps;
4899     desc7->dpcLineCaps.dwDestBlendCaps = wined3d_caps.DestBlendCaps;
4900     desc7->dpcLineCaps.dwAlphaCmpCaps = wined3d_caps.AlphaCmpCaps;
4901     desc7->dpcLineCaps.dwShadeCaps = wined3d_caps.ShadeCaps;
4902     desc7->dpcLineCaps.dwTextureCaps = wined3d_caps.TextureCaps;
4903     desc7->dpcLineCaps.dwTextureFilterCaps = wined3d_caps.TextureFilterCaps;
4904     desc7->dpcLineCaps.dwTextureAddressCaps = wined3d_caps.TextureAddressCaps;
4905
4906     desc7->dwMaxTextureWidth = wined3d_caps.MaxTextureWidth;
4907     desc7->dwMaxTextureHeight = wined3d_caps.MaxTextureHeight;
4908
4909     desc7->dwMaxTextureRepeat = wined3d_caps.MaxTextureRepeat;
4910     desc7->dwMaxTextureAspectRatio = wined3d_caps.MaxTextureAspectRatio;
4911     desc7->dwMaxAnisotropy = wined3d_caps.MaxAnisotropy;
4912     desc7->dvMaxVertexW = wined3d_caps.MaxVertexW;
4913
4914     desc7->dvGuardBandLeft = wined3d_caps.GuardBandLeft;
4915     desc7->dvGuardBandTop = wined3d_caps.GuardBandTop;
4916     desc7->dvGuardBandRight = wined3d_caps.GuardBandRight;
4917     desc7->dvGuardBandBottom = wined3d_caps.GuardBandBottom;
4918
4919     desc7->dvExtentsAdjust = wined3d_caps.ExtentsAdjust;
4920     desc7->dwStencilCaps = wined3d_caps.StencilCaps;
4921
4922     desc7->dwFVFCaps = wined3d_caps.FVFCaps;
4923     desc7->dwTextureOpCaps = wined3d_caps.TextureOpCaps;
4924
4925     desc7->dwVertexProcessingCaps = wined3d_caps.VertexProcessingCaps;
4926     desc7->dwMaxActiveLights = wined3d_caps.MaxActiveLights;
4927
4928     /* Remove all non-d3d7 caps */
4929     desc7->dwDevCaps &= (
4930         D3DDEVCAPS_FLOATTLVERTEX         | D3DDEVCAPS_SORTINCREASINGZ          | D3DDEVCAPS_SORTDECREASINGZ          |
4931         D3DDEVCAPS_SORTEXACT             | D3DDEVCAPS_EXECUTESYSTEMMEMORY      | D3DDEVCAPS_EXECUTEVIDEOMEMORY       |
4932         D3DDEVCAPS_TLVERTEXSYSTEMMEMORY  | D3DDEVCAPS_TLVERTEXVIDEOMEMORY      | D3DDEVCAPS_TEXTURESYSTEMMEMORY      |
4933         D3DDEVCAPS_TEXTUREVIDEOMEMORY    | D3DDEVCAPS_DRAWPRIMTLVERTEX         | D3DDEVCAPS_CANRENDERAFTERFLIP       |
4934         D3DDEVCAPS_TEXTURENONLOCALVIDMEM | D3DDEVCAPS_DRAWPRIMITIVES2          | D3DDEVCAPS_SEPARATETEXTUREMEMORIES  |
4935         D3DDEVCAPS_DRAWPRIMITIVES2EX     | D3DDEVCAPS_HWTRANSFORMANDLIGHT      | D3DDEVCAPS_CANBLTSYSTONONLOCAL      |
4936         D3DDEVCAPS_HWRASTERIZATION);
4937
4938     desc7->dwStencilCaps &= (
4939         D3DSTENCILCAPS_KEEP              | D3DSTENCILCAPS_ZERO                 | D3DSTENCILCAPS_REPLACE              |
4940         D3DSTENCILCAPS_INCRSAT           | D3DSTENCILCAPS_DECRSAT              | D3DSTENCILCAPS_INVERT               |
4941         D3DSTENCILCAPS_INCR              | D3DSTENCILCAPS_DECR);
4942
4943     /* FVF caps ?*/
4944
4945     desc7->dwTextureOpCaps &= (
4946         D3DTEXOPCAPS_DISABLE             | D3DTEXOPCAPS_SELECTARG1             | D3DTEXOPCAPS_SELECTARG2             |
4947         D3DTEXOPCAPS_MODULATE            | D3DTEXOPCAPS_MODULATE2X             | D3DTEXOPCAPS_MODULATE4X             |
4948         D3DTEXOPCAPS_ADD                 | D3DTEXOPCAPS_ADDSIGNED              | D3DTEXOPCAPS_ADDSIGNED2X            |
4949         D3DTEXOPCAPS_SUBTRACT            | D3DTEXOPCAPS_ADDSMOOTH              | D3DTEXOPCAPS_BLENDTEXTUREALPHA      |
4950         D3DTEXOPCAPS_BLENDFACTORALPHA    | D3DTEXOPCAPS_BLENDTEXTUREALPHAPM    | D3DTEXOPCAPS_BLENDCURRENTALPHA      |
4951         D3DTEXOPCAPS_PREMODULATE         | D3DTEXOPCAPS_MODULATEALPHA_ADDCOLOR | D3DTEXOPCAPS_MODULATECOLOR_ADDALPHA |
4952         D3DTEXOPCAPS_MODULATEINVALPHA_ADDCOLOR | D3DTEXOPCAPS_MODULATEINVCOLOR_ADDALPHA | D3DTEXOPCAPS_BUMPENVMAP    |
4953         D3DTEXOPCAPS_BUMPENVMAPLUMINANCE | D3DTEXOPCAPS_DOTPRODUCT3);
4954
4955     desc7->dwVertexProcessingCaps &= (
4956         D3DVTXPCAPS_TEXGEN               | D3DVTXPCAPS_MATERIALSOURCE7         | D3DVTXPCAPS_VERTEXFOG               |
4957         D3DVTXPCAPS_DIRECTIONALLIGHTS    | D3DVTXPCAPS_POSITIONALLIGHTS        | D3DVTXPCAPS_LOCALVIEWER);
4958
4959     desc7->dpcLineCaps.dwMiscCaps &= (
4960         D3DPMISCCAPS_MASKPLANES          | D3DPMISCCAPS_MASKZ                  | D3DPMISCCAPS_LINEPATTERNREP         |
4961         D3DPMISCCAPS_CONFORMANT          | D3DPMISCCAPS_CULLNONE               | D3DPMISCCAPS_CULLCW                 |
4962         D3DPMISCCAPS_CULLCCW);
4963
4964     desc7->dpcLineCaps.dwRasterCaps &= (
4965         D3DPRASTERCAPS_DITHER            | D3DPRASTERCAPS_ROP2                 | D3DPRASTERCAPS_XOR                  |
4966         D3DPRASTERCAPS_PAT               | D3DPRASTERCAPS_ZTEST                | D3DPRASTERCAPS_SUBPIXEL             |
4967         D3DPRASTERCAPS_SUBPIXELX         | D3DPRASTERCAPS_FOGVERTEX            | D3DPRASTERCAPS_FOGTABLE             |
4968         D3DPRASTERCAPS_STIPPLE           | D3DPRASTERCAPS_ANTIALIASSORTDEPENDENT | D3DPRASTERCAPS_ANTIALIASSORTINDEPENDENT |
4969         D3DPRASTERCAPS_ANTIALIASEDGES    | D3DPRASTERCAPS_MIPMAPLODBIAS        | D3DPRASTERCAPS_ZBIAS                |
4970         D3DPRASTERCAPS_ZBUFFERLESSHSR    | D3DPRASTERCAPS_FOGRANGE             | D3DPRASTERCAPS_ANISOTROPY           |
4971         D3DPRASTERCAPS_WBUFFER           | D3DPRASTERCAPS_TRANSLUCENTSORTINDEPENDENT | D3DPRASTERCAPS_WFOG           |
4972         D3DPRASTERCAPS_ZFOG);
4973
4974     desc7->dpcLineCaps.dwZCmpCaps &= (
4975         D3DPCMPCAPS_NEVER                | D3DPCMPCAPS_LESS                    | D3DPCMPCAPS_EQUAL                   |
4976         D3DPCMPCAPS_LESSEQUAL            | D3DPCMPCAPS_GREATER                 | D3DPCMPCAPS_NOTEQUAL                |
4977         D3DPCMPCAPS_GREATEREQUAL         | D3DPCMPCAPS_ALWAYS);
4978
4979     desc7->dpcLineCaps.dwSrcBlendCaps &= (
4980         D3DPBLENDCAPS_ZERO               | D3DPBLENDCAPS_ONE                   | D3DPBLENDCAPS_SRCCOLOR              |
4981         D3DPBLENDCAPS_INVSRCCOLOR        | D3DPBLENDCAPS_SRCALPHA              | D3DPBLENDCAPS_INVSRCALPHA           |
4982         D3DPBLENDCAPS_DESTALPHA          | D3DPBLENDCAPS_INVDESTALPHA          | D3DPBLENDCAPS_DESTCOLOR             |
4983         D3DPBLENDCAPS_INVDESTCOLOR       | D3DPBLENDCAPS_SRCALPHASAT           | D3DPBLENDCAPS_BOTHSRCALPHA          |
4984         D3DPBLENDCAPS_BOTHINVSRCALPHA);
4985
4986     desc7->dpcLineCaps.dwDestBlendCaps &= (
4987         D3DPBLENDCAPS_ZERO               | D3DPBLENDCAPS_ONE                   | D3DPBLENDCAPS_SRCCOLOR              |
4988         D3DPBLENDCAPS_INVSRCCOLOR        | D3DPBLENDCAPS_SRCALPHA              | D3DPBLENDCAPS_INVSRCALPHA           |
4989         D3DPBLENDCAPS_DESTALPHA          | D3DPBLENDCAPS_INVDESTALPHA          | D3DPBLENDCAPS_DESTCOLOR             |
4990         D3DPBLENDCAPS_INVDESTCOLOR       | D3DPBLENDCAPS_SRCALPHASAT           | D3DPBLENDCAPS_BOTHSRCALPHA          |
4991         D3DPBLENDCAPS_BOTHINVSRCALPHA);
4992
4993     desc7->dpcLineCaps.dwAlphaCmpCaps &= (
4994         D3DPCMPCAPS_NEVER                | D3DPCMPCAPS_LESS                    | D3DPCMPCAPS_EQUAL                   |
4995         D3DPCMPCAPS_LESSEQUAL            | D3DPCMPCAPS_GREATER                 | D3DPCMPCAPS_NOTEQUAL                |
4996         D3DPCMPCAPS_GREATEREQUAL         | D3DPCMPCAPS_ALWAYS);
4997
4998     desc7->dpcLineCaps.dwShadeCaps &= (
4999         D3DPSHADECAPS_COLORFLATMONO      | D3DPSHADECAPS_COLORFLATRGB          | D3DPSHADECAPS_COLORGOURAUDMONO      |
5000         D3DPSHADECAPS_COLORGOURAUDRGB    | D3DPSHADECAPS_COLORPHONGMONO        | D3DPSHADECAPS_COLORPHONGRGB         |
5001         D3DPSHADECAPS_SPECULARFLATMONO   | D3DPSHADECAPS_SPECULARFLATRGB       | D3DPSHADECAPS_SPECULARGOURAUDMONO   |
5002         D3DPSHADECAPS_SPECULARGOURAUDRGB | D3DPSHADECAPS_SPECULARPHONGMONO     | D3DPSHADECAPS_SPECULARPHONGRGB      |
5003         D3DPSHADECAPS_ALPHAFLATBLEND     | D3DPSHADECAPS_ALPHAFLATSTIPPLED     | D3DPSHADECAPS_ALPHAGOURAUDBLEND     |
5004         D3DPSHADECAPS_ALPHAGOURAUDSTIPPLED | D3DPSHADECAPS_ALPHAPHONGBLEND     | D3DPSHADECAPS_ALPHAPHONGSTIPPLED    |
5005         D3DPSHADECAPS_FOGFLAT            | D3DPSHADECAPS_FOGGOURAUD            | D3DPSHADECAPS_FOGPHONG);
5006
5007     desc7->dpcLineCaps.dwTextureCaps &= (
5008         D3DPTEXTURECAPS_PERSPECTIVE      | D3DPTEXTURECAPS_POW2                | D3DPTEXTURECAPS_ALPHA               |
5009         D3DPTEXTURECAPS_TRANSPARENCY     | D3DPTEXTURECAPS_BORDER              | D3DPTEXTURECAPS_SQUAREONLY          |
5010         D3DPTEXTURECAPS_TEXREPEATNOTSCALEDBYSIZE | D3DPTEXTURECAPS_ALPHAPALETTE| D3DPTEXTURECAPS_NONPOW2CONDITIONAL  |
5011         D3DPTEXTURECAPS_PROJECTED        | D3DPTEXTURECAPS_CUBEMAP             | D3DPTEXTURECAPS_COLORKEYBLEND);
5012
5013     desc7->dpcLineCaps.dwTextureFilterCaps &= (
5014         D3DPTFILTERCAPS_NEAREST          | D3DPTFILTERCAPS_LINEAR              | D3DPTFILTERCAPS_MIPNEAREST          |
5015         D3DPTFILTERCAPS_MIPLINEAR        | D3DPTFILTERCAPS_LINEARMIPNEAREST    | D3DPTFILTERCAPS_LINEARMIPLINEAR     |
5016         D3DPTFILTERCAPS_MINFPOINT        | D3DPTFILTERCAPS_MINFLINEAR          | D3DPTFILTERCAPS_MINFANISOTROPIC     |
5017         D3DPTFILTERCAPS_MIPFPOINT        | D3DPTFILTERCAPS_MIPFLINEAR          | D3DPTFILTERCAPS_MAGFPOINT           |
5018         D3DPTFILTERCAPS_MAGFLINEAR       | D3DPTFILTERCAPS_MAGFANISOTROPIC     | D3DPTFILTERCAPS_MAGFAFLATCUBIC      |
5019         D3DPTFILTERCAPS_MAGFGAUSSIANCUBIC);
5020
5021     desc7->dpcLineCaps.dwTextureBlendCaps &= (
5022         D3DPTBLENDCAPS_DECAL             | D3DPTBLENDCAPS_MODULATE             | D3DPTBLENDCAPS_DECALALPHA           |
5023         D3DPTBLENDCAPS_MODULATEALPHA     | D3DPTBLENDCAPS_DECALMASK            | D3DPTBLENDCAPS_MODULATEMASK         |
5024         D3DPTBLENDCAPS_COPY              | D3DPTBLENDCAPS_ADD);
5025
5026     desc7->dpcLineCaps.dwTextureAddressCaps &= (
5027         D3DPTADDRESSCAPS_WRAP            | D3DPTADDRESSCAPS_MIRROR             | D3DPTADDRESSCAPS_CLAMP              |
5028         D3DPTADDRESSCAPS_BORDER          | D3DPTADDRESSCAPS_INDEPENDENTUV);
5029
5030     if (!(desc7->dpcLineCaps.dwTextureCaps & D3DPTEXTURECAPS_POW2))
5031     {
5032         /* DirectX7 always has the np2 flag set, no matter what the card
5033          * supports. Some old games (Rollcage) check the caps incorrectly.
5034          * If wined3d supports nonpow2 textures it also has np2 conditional
5035          * support. */
5036         desc7->dpcLineCaps.dwTextureCaps |= D3DPTEXTURECAPS_POW2 | D3DPTEXTURECAPS_NONPOW2CONDITIONAL;
5037     }
5038
5039     /* Fill the missing members, and do some fixup */
5040     desc7->dpcLineCaps.dwSize = sizeof(desc7->dpcLineCaps);
5041     desc7->dpcLineCaps.dwTextureBlendCaps = D3DPTBLENDCAPS_ADD | D3DPTBLENDCAPS_MODULATEMASK |
5042                                             D3DPTBLENDCAPS_COPY | D3DPTBLENDCAPS_DECAL |
5043                                             D3DPTBLENDCAPS_DECALALPHA | D3DPTBLENDCAPS_DECALMASK |
5044                                             D3DPTBLENDCAPS_MODULATE | D3DPTBLENDCAPS_MODULATEALPHA;
5045     desc7->dpcLineCaps.dwStippleWidth = 32;
5046     desc7->dpcLineCaps.dwStippleHeight = 32;
5047     /* Use the same for the TriCaps */
5048     desc7->dpcTriCaps = desc7->dpcLineCaps;
5049
5050     desc7->dwDeviceRenderBitDepth = DDBD_16 | DDBD_24 | DDBD_32;
5051     desc7->dwDeviceZBufferBitDepth = DDBD_16 | DDBD_24;
5052     desc7->dwMinTextureWidth = 1;
5053     desc7->dwMinTextureHeight = 1;
5054
5055     /* Convert DWORDs safely to WORDs */
5056     if (wined3d_caps.MaxTextureBlendStages > 0xffff) desc7->wMaxTextureBlendStages = 0xffff;
5057     else desc7->wMaxTextureBlendStages = (WORD)wined3d_caps.MaxTextureBlendStages;
5058     if (wined3d_caps.MaxSimultaneousTextures > 0xffff) desc7->wMaxSimultaneousTextures = 0xffff;
5059     else desc7->wMaxSimultaneousTextures = (WORD)wined3d_caps.MaxSimultaneousTextures;
5060
5061     if (wined3d_caps.MaxUserClipPlanes > 0xffff) desc7->wMaxUserClipPlanes = 0xffff;
5062     else desc7->wMaxUserClipPlanes = (WORD)wined3d_caps.MaxUserClipPlanes;
5063     if (wined3d_caps.MaxVertexBlendMatrices > 0xffff) desc7->wMaxVertexBlendMatrices = 0xffff;
5064     else desc7->wMaxVertexBlendMatrices = (WORD)wined3d_caps.MaxVertexBlendMatrices;
5065
5066     desc7->deviceGUID = IID_IDirect3DTnLHalDevice;
5067
5068     desc7->dwReserved1 = 0;
5069     desc7->dwReserved2 = 0;
5070     desc7->dwReserved3 = 0;
5071     desc7->dwReserved4 = 0;
5072
5073     /* Fill the old structure */
5074     memset(desc1, 0, sizeof(*desc1));
5075     desc1->dwSize = sizeof(D3DDEVICEDESC);
5076     desc1->dwFlags = D3DDD_COLORMODEL
5077             | D3DDD_DEVCAPS
5078             | D3DDD_TRANSFORMCAPS
5079             | D3DDD_BCLIPPING
5080             | D3DDD_LIGHTINGCAPS
5081             | D3DDD_LINECAPS
5082             | D3DDD_TRICAPS
5083             | D3DDD_DEVICERENDERBITDEPTH
5084             | D3DDD_DEVICEZBUFFERBITDEPTH
5085             | D3DDD_MAXBUFFERSIZE
5086             | D3DDD_MAXVERTEXCOUNT;
5087
5088     desc1->dcmColorModel = D3DCOLOR_RGB;
5089     desc1->dwDevCaps = desc7->dwDevCaps;
5090     desc1->dtcTransformCaps.dwSize = sizeof(D3DTRANSFORMCAPS);
5091     desc1->dtcTransformCaps.dwCaps = D3DTRANSFORMCAPS_CLIP;
5092     desc1->bClipping = TRUE;
5093     desc1->dlcLightingCaps.dwSize = sizeof(D3DLIGHTINGCAPS);
5094     desc1->dlcLightingCaps.dwCaps = D3DLIGHTCAPS_DIRECTIONAL
5095             | D3DLIGHTCAPS_PARALLELPOINT
5096             | D3DLIGHTCAPS_POINT
5097             | D3DLIGHTCAPS_SPOT;
5098
5099     desc1->dlcLightingCaps.dwLightingModel = D3DLIGHTINGMODEL_RGB;
5100     desc1->dlcLightingCaps.dwNumLights = desc7->dwMaxActiveLights;
5101
5102     desc1->dpcLineCaps.dwSize = sizeof(D3DPRIMCAPS);
5103     desc1->dpcLineCaps.dwMiscCaps = desc7->dpcLineCaps.dwMiscCaps;
5104     desc1->dpcLineCaps.dwRasterCaps = desc7->dpcLineCaps.dwRasterCaps;
5105     desc1->dpcLineCaps.dwZCmpCaps = desc7->dpcLineCaps.dwZCmpCaps;
5106     desc1->dpcLineCaps.dwSrcBlendCaps = desc7->dpcLineCaps.dwSrcBlendCaps;
5107     desc1->dpcLineCaps.dwDestBlendCaps = desc7->dpcLineCaps.dwDestBlendCaps;
5108     desc1->dpcLineCaps.dwShadeCaps = desc7->dpcLineCaps.dwShadeCaps;
5109     desc1->dpcLineCaps.dwTextureCaps = desc7->dpcLineCaps.dwTextureCaps;
5110     desc1->dpcLineCaps.dwTextureFilterCaps = desc7->dpcLineCaps.dwTextureFilterCaps;
5111     desc1->dpcLineCaps.dwTextureBlendCaps = desc7->dpcLineCaps.dwTextureBlendCaps;
5112     desc1->dpcLineCaps.dwTextureAddressCaps = desc7->dpcLineCaps.dwTextureAddressCaps;
5113     desc1->dpcLineCaps.dwStippleWidth = desc7->dpcLineCaps.dwStippleWidth;
5114     desc1->dpcLineCaps.dwAlphaCmpCaps = desc7->dpcLineCaps.dwAlphaCmpCaps;
5115
5116     desc1->dpcTriCaps.dwSize = sizeof(D3DPRIMCAPS);
5117     desc1->dpcTriCaps.dwMiscCaps = desc7->dpcTriCaps.dwMiscCaps;
5118     desc1->dpcTriCaps.dwRasterCaps = desc7->dpcTriCaps.dwRasterCaps;
5119     desc1->dpcTriCaps.dwZCmpCaps = desc7->dpcTriCaps.dwZCmpCaps;
5120     desc1->dpcTriCaps.dwSrcBlendCaps = desc7->dpcTriCaps.dwSrcBlendCaps;
5121     desc1->dpcTriCaps.dwDestBlendCaps = desc7->dpcTriCaps.dwDestBlendCaps;
5122     desc1->dpcTriCaps.dwShadeCaps = desc7->dpcTriCaps.dwShadeCaps;
5123     desc1->dpcTriCaps.dwTextureCaps = desc7->dpcTriCaps.dwTextureCaps;
5124     desc1->dpcTriCaps.dwTextureFilterCaps = desc7->dpcTriCaps.dwTextureFilterCaps;
5125     desc1->dpcTriCaps.dwTextureBlendCaps = desc7->dpcTriCaps.dwTextureBlendCaps;
5126     desc1->dpcTriCaps.dwTextureAddressCaps = desc7->dpcTriCaps.dwTextureAddressCaps;
5127     desc1->dpcTriCaps.dwStippleWidth = desc7->dpcTriCaps.dwStippleWidth;
5128     desc1->dpcTriCaps.dwAlphaCmpCaps = desc7->dpcTriCaps.dwAlphaCmpCaps;
5129
5130     desc1->dwDeviceRenderBitDepth = desc7->dwDeviceRenderBitDepth;
5131     desc1->dwDeviceZBufferBitDepth = desc7->dwDeviceZBufferBitDepth;
5132     desc1->dwMaxBufferSize = 0;
5133     desc1->dwMaxVertexCount = 65536;
5134     desc1->dwMinTextureWidth  = desc7->dwMinTextureWidth;
5135     desc1->dwMinTextureHeight = desc7->dwMinTextureHeight;
5136     desc1->dwMaxTextureWidth  = desc7->dwMaxTextureWidth;
5137     desc1->dwMaxTextureHeight = desc7->dwMaxTextureHeight;
5138     desc1->dwMinStippleWidth  = 1;
5139     desc1->dwMinStippleHeight = 1;
5140     desc1->dwMaxStippleWidth  = 32;
5141     desc1->dwMaxStippleHeight = 32;
5142     desc1->dwMaxTextureRepeat = desc7->dwMaxTextureRepeat;
5143     desc1->dwMaxTextureAspectRatio = desc7->dwMaxTextureAspectRatio;
5144     desc1->dwMaxAnisotropy = desc7->dwMaxAnisotropy;
5145     desc1->dvGuardBandLeft = desc7->dvGuardBandLeft;
5146     desc1->dvGuardBandRight = desc7->dvGuardBandRight;
5147     desc1->dvGuardBandTop = desc7->dvGuardBandTop;
5148     desc1->dvGuardBandBottom = desc7->dvGuardBandBottom;
5149     desc1->dvExtentsAdjust = desc7->dvExtentsAdjust;
5150     desc1->dwStencilCaps = desc7->dwStencilCaps;
5151     desc1->dwFVFCaps = desc7->dwFVFCaps;
5152     desc1->dwTextureOpCaps = desc7->dwTextureOpCaps;
5153     desc1->wMaxTextureBlendStages = desc7->wMaxTextureBlendStages;
5154     desc1->wMaxSimultaneousTextures = desc7->wMaxSimultaneousTextures;
5155
5156     return DD_OK;
5157 }
5158
5159 /*****************************************************************************
5160  * IDirectDraw7 VTable
5161  *****************************************************************************/
5162 static const struct IDirectDraw7Vtbl ddraw7_vtbl =
5163 {
5164     /* IUnknown */
5165     ddraw7_QueryInterface,
5166     ddraw7_AddRef,
5167     ddraw7_Release,
5168     /* IDirectDraw */
5169     ddraw7_Compact,
5170     ddraw7_CreateClipper,
5171     ddraw7_CreatePalette,
5172     ddraw7_CreateSurface,
5173     ddraw7_DuplicateSurface,
5174     ddraw7_EnumDisplayModes,
5175     ddraw7_EnumSurfaces,
5176     ddraw7_FlipToGDISurface,
5177     ddraw7_GetCaps,
5178     ddraw7_GetDisplayMode,
5179     ddraw7_GetFourCCCodes,
5180     ddraw7_GetGDISurface,
5181     ddraw7_GetMonitorFrequency,
5182     ddraw7_GetScanLine,
5183     ddraw7_GetVerticalBlankStatus,
5184     ddraw7_Initialize,
5185     ddraw7_RestoreDisplayMode,
5186     ddraw7_SetCooperativeLevel,
5187     ddraw7_SetDisplayMode,
5188     ddraw7_WaitForVerticalBlank,
5189     /* IDirectDraw2 */
5190     ddraw7_GetAvailableVidMem,
5191     /* IDirectDraw3 */
5192     ddraw7_GetSurfaceFromDC,
5193     /* IDirectDraw4 */
5194     ddraw7_RestoreAllSurfaces,
5195     ddraw7_TestCooperativeLevel,
5196     ddraw7_GetDeviceIdentifier,
5197     /* IDirectDraw7 */
5198     ddraw7_StartModeTest,
5199     ddraw7_EvaluateMode
5200 };
5201
5202 static const struct IDirectDraw4Vtbl ddraw4_vtbl =
5203 {
5204     /* IUnknown */
5205     ddraw4_QueryInterface,
5206     ddraw4_AddRef,
5207     ddraw4_Release,
5208     /* IDirectDraw */
5209     ddraw4_Compact,
5210     ddraw4_CreateClipper,
5211     ddraw4_CreatePalette,
5212     ddraw4_CreateSurface,
5213     ddraw4_DuplicateSurface,
5214     ddraw4_EnumDisplayModes,
5215     ddraw4_EnumSurfaces,
5216     ddraw4_FlipToGDISurface,
5217     ddraw4_GetCaps,
5218     ddraw4_GetDisplayMode,
5219     ddraw4_GetFourCCCodes,
5220     ddraw4_GetGDISurface,
5221     ddraw4_GetMonitorFrequency,
5222     ddraw4_GetScanLine,
5223     ddraw4_GetVerticalBlankStatus,
5224     ddraw4_Initialize,
5225     ddraw4_RestoreDisplayMode,
5226     ddraw4_SetCooperativeLevel,
5227     ddraw4_SetDisplayMode,
5228     ddraw4_WaitForVerticalBlank,
5229     /* IDirectDraw2 */
5230     ddraw4_GetAvailableVidMem,
5231     /* IDirectDraw3 */
5232     ddraw4_GetSurfaceFromDC,
5233     /* IDirectDraw4 */
5234     ddraw4_RestoreAllSurfaces,
5235     ddraw4_TestCooperativeLevel,
5236     ddraw4_GetDeviceIdentifier,
5237 };
5238
5239 static const struct IDirectDraw3Vtbl ddraw3_vtbl =
5240 {
5241     /* IUnknown */
5242     ddraw3_QueryInterface,
5243     ddraw3_AddRef,
5244     ddraw3_Release,
5245     /* IDirectDraw */
5246     ddraw3_Compact,
5247     ddraw3_CreateClipper,
5248     ddraw3_CreatePalette,
5249     ddraw3_CreateSurface,
5250     ddraw3_DuplicateSurface,
5251     ddraw3_EnumDisplayModes,
5252     ddraw3_EnumSurfaces,
5253     ddraw3_FlipToGDISurface,
5254     ddraw3_GetCaps,
5255     ddraw3_GetDisplayMode,
5256     ddraw3_GetFourCCCodes,
5257     ddraw3_GetGDISurface,
5258     ddraw3_GetMonitorFrequency,
5259     ddraw3_GetScanLine,
5260     ddraw3_GetVerticalBlankStatus,
5261     ddraw3_Initialize,
5262     ddraw3_RestoreDisplayMode,
5263     ddraw3_SetCooperativeLevel,
5264     ddraw3_SetDisplayMode,
5265     ddraw3_WaitForVerticalBlank,
5266     /* IDirectDraw2 */
5267     ddraw3_GetAvailableVidMem,
5268     /* IDirectDraw3 */
5269     ddraw3_GetSurfaceFromDC,
5270 };
5271
5272 static const struct IDirectDraw2Vtbl ddraw2_vtbl =
5273 {
5274     /* IUnknown */
5275     ddraw2_QueryInterface,
5276     ddraw2_AddRef,
5277     ddraw2_Release,
5278     /* IDirectDraw */
5279     ddraw2_Compact,
5280     ddraw2_CreateClipper,
5281     ddraw2_CreatePalette,
5282     ddraw2_CreateSurface,
5283     ddraw2_DuplicateSurface,
5284     ddraw2_EnumDisplayModes,
5285     ddraw2_EnumSurfaces,
5286     ddraw2_FlipToGDISurface,
5287     ddraw2_GetCaps,
5288     ddraw2_GetDisplayMode,
5289     ddraw2_GetFourCCCodes,
5290     ddraw2_GetGDISurface,
5291     ddraw2_GetMonitorFrequency,
5292     ddraw2_GetScanLine,
5293     ddraw2_GetVerticalBlankStatus,
5294     ddraw2_Initialize,
5295     ddraw2_RestoreDisplayMode,
5296     ddraw2_SetCooperativeLevel,
5297     ddraw2_SetDisplayMode,
5298     ddraw2_WaitForVerticalBlank,
5299     /* IDirectDraw2 */
5300     ddraw2_GetAvailableVidMem,
5301 };
5302
5303 static const struct IDirectDrawVtbl ddraw1_vtbl =
5304 {
5305     /* IUnknown */
5306     ddraw1_QueryInterface,
5307     ddraw1_AddRef,
5308     ddraw1_Release,
5309     /* IDirectDraw */
5310     ddraw1_Compact,
5311     ddraw1_CreateClipper,
5312     ddraw1_CreatePalette,
5313     ddraw1_CreateSurface,
5314     ddraw1_DuplicateSurface,
5315     ddraw1_EnumDisplayModes,
5316     ddraw1_EnumSurfaces,
5317     ddraw1_FlipToGDISurface,
5318     ddraw1_GetCaps,
5319     ddraw1_GetDisplayMode,
5320     ddraw1_GetFourCCCodes,
5321     ddraw1_GetGDISurface,
5322     ddraw1_GetMonitorFrequency,
5323     ddraw1_GetScanLine,
5324     ddraw1_GetVerticalBlankStatus,
5325     ddraw1_Initialize,
5326     ddraw1_RestoreDisplayMode,
5327     ddraw1_SetCooperativeLevel,
5328     ddraw1_SetDisplayMode,
5329     ddraw1_WaitForVerticalBlank,
5330 };
5331
5332 static const struct IDirect3D7Vtbl d3d7_vtbl =
5333 {
5334     /* IUnknown methods */
5335     d3d7_QueryInterface,
5336     d3d7_AddRef,
5337     d3d7_Release,
5338     /* IDirect3D7 methods */
5339     d3d7_EnumDevices,
5340     d3d7_CreateDevice,
5341     d3d7_CreateVertexBuffer,
5342     d3d7_EnumZBufferFormats,
5343     d3d7_EvictManagedTextures
5344 };
5345
5346 static const struct IDirect3D3Vtbl d3d3_vtbl =
5347 {
5348     /* IUnknown methods */
5349     d3d3_QueryInterface,
5350     d3d3_AddRef,
5351     d3d3_Release,
5352     /* IDirect3D3 methods */
5353     d3d3_EnumDevices,
5354     d3d3_CreateLight,
5355     d3d3_CreateMaterial,
5356     d3d3_CreateViewport,
5357     d3d3_FindDevice,
5358     d3d3_CreateDevice,
5359     d3d3_CreateVertexBuffer,
5360     d3d3_EnumZBufferFormats,
5361     d3d3_EvictManagedTextures
5362 };
5363
5364 static const struct IDirect3D2Vtbl d3d2_vtbl =
5365 {
5366     /* IUnknown methods */
5367     d3d2_QueryInterface,
5368     d3d2_AddRef,
5369     d3d2_Release,
5370     /* IDirect3D2 methods */
5371     d3d2_EnumDevices,
5372     d3d2_CreateLight,
5373     d3d2_CreateMaterial,
5374     d3d2_CreateViewport,
5375     d3d2_FindDevice,
5376     d3d2_CreateDevice
5377 };
5378
5379 static const struct IDirect3DVtbl d3d1_vtbl =
5380 {
5381     /* IUnknown methods */
5382     d3d1_QueryInterface,
5383     d3d1_AddRef,
5384     d3d1_Release,
5385     /* IDirect3D methods */
5386     d3d1_Initialize,
5387     d3d1_EnumDevices,
5388     d3d1_CreateLight,
5389     d3d1_CreateMaterial,
5390     d3d1_CreateViewport,
5391     d3d1_FindDevice
5392 };
5393
5394 /*****************************************************************************
5395  * ddraw_find_decl
5396  *
5397  * Finds the WineD3D vertex declaration for a specific fvf, and creates one
5398  * if none was found.
5399  *
5400  * This function is in ddraw.c and the DDraw object space because D3D7
5401  * vertex buffers are created using the IDirect3D interface to the ddraw
5402  * object, so they can be valid across D3D devices(theoretically. The ddraw
5403  * object also owns the wined3d device
5404  *
5405  * Parameters:
5406  *  This: Device
5407  *  fvf: Fvf to find the decl for
5408  *
5409  * Returns:
5410  *  NULL in case of an error, the IWineD3DVertexDeclaration interface for the
5411  *  fvf otherwise.
5412  *
5413  *****************************************************************************/
5414 IWineD3DVertexDeclaration *ddraw_find_decl(IDirectDrawImpl *This, DWORD fvf)
5415 {
5416     HRESULT hr;
5417     IWineD3DVertexDeclaration* pDecl = NULL;
5418     int p, low, high; /* deliberately signed */
5419     struct FvfToDecl *convertedDecls = This->decls;
5420
5421     TRACE("Searching for declaration for fvf %08x... ", fvf);
5422
5423     low = 0;
5424     high = This->numConvertedDecls - 1;
5425     while(low <= high) {
5426         p = (low + high) >> 1;
5427         TRACE("%d ", p);
5428         if(convertedDecls[p].fvf == fvf) {
5429             TRACE("found %p\n", convertedDecls[p].decl);
5430             return convertedDecls[p].decl;
5431         } else if(convertedDecls[p].fvf < fvf) {
5432             low = p + 1;
5433         } else {
5434             high = p - 1;
5435         }
5436     }
5437     TRACE("not found. Creating and inserting at position %d.\n", low);
5438
5439     hr = IWineD3DDevice_CreateVertexDeclarationFromFVF(This->wineD3DDevice,
5440             fvf, This, &ddraw_null_wined3d_parent_ops, &pDecl);
5441     if (hr != S_OK) return NULL;
5442
5443     if(This->declArraySize == This->numConvertedDecls) {
5444         int grow = max(This->declArraySize / 2, 8);
5445         convertedDecls = HeapReAlloc(GetProcessHeap(), 0, convertedDecls,
5446                                      sizeof(convertedDecls[0]) * (This->numConvertedDecls + grow));
5447         if(!convertedDecls) {
5448             /* This will destroy it */
5449             IWineD3DVertexDeclaration_Release(pDecl);
5450             return NULL;
5451         }
5452         This->decls = convertedDecls;
5453         This->declArraySize += grow;
5454     }
5455
5456     memmove(convertedDecls + low + 1, convertedDecls + low, sizeof(convertedDecls[0]) * (This->numConvertedDecls - low));
5457     convertedDecls[low].decl = pDecl;
5458     convertedDecls[low].fvf = fvf;
5459     This->numConvertedDecls++;
5460
5461     TRACE("Returning %p. %d decls in array\n", pDecl, This->numConvertedDecls);
5462     return pDecl;
5463 }
5464
5465 /* IWineD3DDeviceParent IUnknown methods */
5466
5467 static inline struct IDirectDrawImpl *ddraw_from_device_parent(IWineD3DDeviceParent *iface)
5468 {
5469     return (struct IDirectDrawImpl *)((char*)iface - FIELD_OFFSET(struct IDirectDrawImpl, device_parent_vtbl));
5470 }
5471
5472 static HRESULT STDMETHODCALLTYPE device_parent_QueryInterface(IWineD3DDeviceParent *iface, REFIID riid, void **object)
5473 {
5474     struct IDirectDrawImpl *This = ddraw_from_device_parent(iface);
5475     return ddraw7_QueryInterface((IDirectDraw7 *)This, riid, object);
5476 }
5477
5478 static ULONG STDMETHODCALLTYPE device_parent_AddRef(IWineD3DDeviceParent *iface)
5479 {
5480     struct IDirectDrawImpl *This = ddraw_from_device_parent(iface);
5481     return ddraw7_AddRef((IDirectDraw7 *)This);
5482 }
5483
5484 static ULONG STDMETHODCALLTYPE device_parent_Release(IWineD3DDeviceParent *iface)
5485 {
5486     struct IDirectDrawImpl *This = ddraw_from_device_parent(iface);
5487     return ddraw7_Release((IDirectDraw7 *)This);
5488 }
5489
5490 /* IWineD3DDeviceParent methods */
5491
5492 static void STDMETHODCALLTYPE device_parent_WineD3DDeviceCreated(IWineD3DDeviceParent *iface, IWineD3DDevice *device)
5493 {
5494     TRACE("iface %p, device %p\n", iface, device);
5495 }
5496
5497 static HRESULT STDMETHODCALLTYPE device_parent_CreateSurface(IWineD3DDeviceParent *iface,
5498         IUnknown *superior, UINT width, UINT height, enum wined3d_format_id format, DWORD usage,
5499         WINED3DPOOL pool, UINT level, WINED3DCUBEMAP_FACES face, IWineD3DSurface **surface)
5500 {
5501     struct IDirectDrawImpl *This = ddraw_from_device_parent(iface);
5502     IDirectDrawSurfaceImpl *surf = NULL;
5503     UINT i = 0;
5504     DDSCAPS2 searchcaps = This->tex_root->surface_desc.ddsCaps;
5505
5506     TRACE("iface %p, superior %p, width %u, height %u, format %#x, usage %#x,\n"
5507             "\tpool %#x, level %u, face %u, surface %p\n",
5508             iface, superior, width, height, format, usage, pool, level, face, surface);
5509
5510     searchcaps.dwCaps2 &= ~DDSCAPS2_CUBEMAP_ALLFACES;
5511     switch(face)
5512     {
5513         case WINED3DCUBEMAP_FACE_POSITIVE_X:
5514             TRACE("Asked for positive x\n");
5515             if (searchcaps.dwCaps2 & DDSCAPS2_CUBEMAP)
5516             {
5517                 searchcaps.dwCaps2 |= DDSCAPS2_CUBEMAP_POSITIVEX;
5518             }
5519             surf = This->tex_root; break;
5520         case WINED3DCUBEMAP_FACE_NEGATIVE_X:
5521             TRACE("Asked for negative x\n");
5522             searchcaps.dwCaps2 |= DDSCAPS2_CUBEMAP_NEGATIVEX; break;
5523         case WINED3DCUBEMAP_FACE_POSITIVE_Y:
5524             TRACE("Asked for positive y\n");
5525             searchcaps.dwCaps2 |= DDSCAPS2_CUBEMAP_POSITIVEY; break;
5526         case WINED3DCUBEMAP_FACE_NEGATIVE_Y:
5527             TRACE("Asked for negative y\n");
5528             searchcaps.dwCaps2 |= DDSCAPS2_CUBEMAP_NEGATIVEY; break;
5529         case WINED3DCUBEMAP_FACE_POSITIVE_Z:
5530             TRACE("Asked for positive z\n");
5531             searchcaps.dwCaps2 |= DDSCAPS2_CUBEMAP_POSITIVEZ; break;
5532         case WINED3DCUBEMAP_FACE_NEGATIVE_Z:
5533             TRACE("Asked for negative z\n");
5534             searchcaps.dwCaps2 |= DDSCAPS2_CUBEMAP_NEGATIVEZ; break;
5535         default: {ERR("Unexpected cube face\n");} /* Stupid compiler */
5536     }
5537
5538     if (!surf)
5539     {
5540         IDirectDrawSurface7 *attached;
5541         IDirectDrawSurface7_GetAttachedSurface((IDirectDrawSurface7 *)This->tex_root, &searchcaps, &attached);
5542         surf = (IDirectDrawSurfaceImpl *)attached;
5543         IDirectDrawSurface7_Release(attached);
5544     }
5545     if (!surf) ERR("root search surface not found\n");
5546
5547     /* Find the wanted mipmap. There are enough mipmaps in the chain */
5548     while (i < level)
5549     {
5550         IDirectDrawSurface7 *attached;
5551         IDirectDrawSurface7_GetAttachedSurface((IDirectDrawSurface7 *)surf, &searchcaps, &attached);
5552         if(!attached) ERR("Surface not found\n");
5553         surf = (IDirectDrawSurfaceImpl *)attached;
5554         IDirectDrawSurface7_Release(attached);
5555         ++i;
5556     }
5557
5558     /* Return the surface */
5559     *surface = surf->WineD3DSurface;
5560     IWineD3DSurface_AddRef(*surface);
5561
5562     TRACE("Returning wineD3DSurface %p, it belongs to surface %p\n", *surface, surf);
5563
5564     return D3D_OK;
5565 }
5566
5567 static HRESULT WINAPI findRenderTarget(IDirectDrawSurface7 *surface, DDSURFACEDESC2 *surface_desc, void *ctx)
5568 {
5569     IDirectDrawSurfaceImpl *s = (IDirectDrawSurfaceImpl *)surface;
5570     IDirectDrawSurfaceImpl **target = ctx;
5571
5572     if (!s->isRenderTarget)
5573     {
5574         *target = s;
5575         IDirectDrawSurface7_Release(surface);
5576         return DDENUMRET_CANCEL;
5577     }
5578
5579     /* Recurse into the surface tree */
5580     IDirectDrawSurface7_EnumAttachedSurfaces(surface, ctx, findRenderTarget);
5581
5582     IDirectDrawSurface7_Release(surface);
5583     if (*target) return DDENUMRET_CANCEL;
5584
5585     return DDENUMRET_OK;
5586 }
5587
5588 static HRESULT STDMETHODCALLTYPE device_parent_CreateRenderTarget(IWineD3DDeviceParent *iface,
5589         IUnknown *superior, UINT width, UINT height, enum wined3d_format_id format,
5590         WINED3DMULTISAMPLE_TYPE multisample_type, DWORD multisample_quality, BOOL lockable,
5591         IWineD3DSurface **surface)
5592 {
5593     struct IDirectDrawImpl *This = ddraw_from_device_parent(iface);
5594     IDirectDrawSurfaceImpl *d3d_surface = This->d3d_target;
5595     IDirectDrawSurfaceImpl *target = NULL;
5596
5597     TRACE("iface %p, superior %p, width %u, height %u, format %#x, multisample_type %#x,\n"
5598             "\tmultisample_quality %u, lockable %u, surface %p\n",
5599             iface, superior, width, height, format, multisample_type, multisample_quality, lockable, surface);
5600
5601     if (d3d_surface->isRenderTarget)
5602     {
5603         IDirectDrawSurface7_EnumAttachedSurfaces((IDirectDrawSurface7 *)d3d_surface, &target, findRenderTarget);
5604     }
5605     else
5606     {
5607         target = d3d_surface;
5608     }
5609
5610     if (!target)
5611     {
5612         target = This->d3d_target;
5613         ERR(" (%p) : No DirectDrawSurface found to create the back buffer. Using the front buffer as back buffer. Uncertain consequences\n", This);
5614     }
5615
5616     /* TODO: Return failure if the dimensions do not match, but this shouldn't happen */
5617
5618     *surface = target->WineD3DSurface;
5619     IWineD3DSurface_AddRef(*surface);
5620     target->isRenderTarget = TRUE;
5621
5622     TRACE("Returning wineD3DSurface %p, it belongs to surface %p\n", *surface, d3d_surface);
5623
5624     return D3D_OK;
5625 }
5626
5627 static HRESULT STDMETHODCALLTYPE device_parent_CreateDepthStencilSurface(IWineD3DDeviceParent *iface,
5628         UINT width, UINT height, enum wined3d_format_id format, WINED3DMULTISAMPLE_TYPE multisample_type,
5629         DWORD multisample_quality, BOOL discard, IWineD3DSurface **surface)
5630 {
5631     struct IDirectDrawImpl *This = ddraw_from_device_parent(iface);
5632     IDirectDrawSurfaceImpl *ddraw_surface;
5633     DDSURFACEDESC2 ddsd;
5634     HRESULT hr;
5635
5636     TRACE("iface %p, width %u, height %u, format %#x, multisample_type %#x,\n"
5637             "\tmultisample_quality %u, discard %u, surface %p\n",
5638             iface, width, height, format, multisample_type, multisample_quality, discard, surface);
5639
5640     *surface = NULL;
5641
5642     /* Create a DirectDraw surface */
5643     memset(&ddsd, 0, sizeof(ddsd));
5644     ddsd.dwSize = sizeof(ddsd);
5645     ddsd.u4.ddpfPixelFormat.dwSize = sizeof(DDPIXELFORMAT);
5646     ddsd.dwFlags = DDSD_PIXELFORMAT | DDSD_WIDTH | DDSD_HEIGHT | DDSD_CAPS;
5647     ddsd.ddsCaps.dwCaps = DDSCAPS_OFFSCREENPLAIN;
5648     ddsd.dwHeight = height;
5649     ddsd.dwWidth = width;
5650     if (format)
5651     {
5652         PixelFormat_WineD3DtoDD(&ddsd.u4.ddpfPixelFormat, format);
5653     }
5654     else
5655     {
5656         ddsd.dwFlags ^= DDSD_PIXELFORMAT;
5657     }
5658
5659     This->depthstencil = TRUE;
5660     hr = IDirectDraw7_CreateSurface((IDirectDraw7 *)This, &ddsd, (IDirectDrawSurface7 **)&ddraw_surface, NULL);
5661     This->depthstencil = FALSE;
5662     if(FAILED(hr))
5663     {
5664         ERR(" (%p) Creating a DepthStencil Surface failed, result = %x\n", This, hr);
5665         return hr;
5666     }
5667
5668     *surface = ddraw_surface->WineD3DSurface;
5669     IWineD3DSurface_AddRef(*surface);
5670     IDirectDrawSurface7_Release((IDirectDrawSurface7 *)ddraw_surface);
5671
5672     return D3D_OK;
5673 }
5674
5675 static HRESULT STDMETHODCALLTYPE device_parent_CreateVolume(IWineD3DDeviceParent *iface,
5676         IUnknown *superior, UINT width, UINT height, UINT depth, enum wined3d_format_id format,
5677         WINED3DPOOL pool, DWORD usage, IWineD3DVolume **volume)
5678 {
5679     TRACE("iface %p, superior %p, width %u, height %u, depth %u, format %#x, pool %#x, usage %#x, volume %p\n",
5680                 iface, superior, width, height, depth, format, pool, usage, volume);
5681
5682     ERR("Not implemented!\n");
5683
5684     return E_NOTIMPL;
5685 }
5686
5687 static HRESULT STDMETHODCALLTYPE device_parent_CreateSwapChain(IWineD3DDeviceParent *iface,
5688         WINED3DPRESENT_PARAMETERS *present_parameters, IWineD3DSwapChain **swapchain)
5689 {
5690     struct IDirectDrawImpl *This = ddraw_from_device_parent(iface);
5691     IDirectDrawSurfaceImpl *iterator;
5692     IParentImpl *object;
5693     HRESULT hr;
5694
5695     TRACE("iface %p, present_parameters %p, swapchain %p\n", iface, present_parameters, swapchain);
5696
5697     object = HeapAlloc(GetProcessHeap(),  HEAP_ZERO_MEMORY, sizeof(IParentImpl));
5698     if (!object)
5699     {
5700         FIXME("Allocation of memory failed\n");
5701         *swapchain = NULL;
5702         return DDERR_OUTOFVIDEOMEMORY;
5703     }
5704
5705     ddraw_parent_init(object);
5706
5707     hr = IWineD3DDevice_CreateSwapChain(This->wineD3DDevice, present_parameters,
5708             This->ImplType, object, swapchain);
5709     if (FAILED(hr))
5710     {
5711         FIXME("(%p) CreateSwapChain failed, returning %#x\n", iface, hr);
5712         HeapFree(GetProcessHeap(), 0 , object);
5713         *swapchain = NULL;
5714         return hr;
5715     }
5716
5717     object->child = (IUnknown *)*swapchain;
5718     This->d3d_target->wineD3DSwapChain = *swapchain;
5719     iterator = This->d3d_target->complex_array[0];
5720     while (iterator)
5721     {
5722         iterator->wineD3DSwapChain = *swapchain;
5723         iterator = iterator->complex_array[0];
5724     }
5725
5726     return hr;
5727 }
5728
5729 static const IWineD3DDeviceParentVtbl ddraw_wined3d_device_parent_vtbl =
5730 {
5731     /* IUnknown methods */
5732     device_parent_QueryInterface,
5733     device_parent_AddRef,
5734     device_parent_Release,
5735     /* IWineD3DDeviceParent methods */
5736     device_parent_WineD3DDeviceCreated,
5737     device_parent_CreateSurface,
5738     device_parent_CreateRenderTarget,
5739     device_parent_CreateDepthStencilSurface,
5740     device_parent_CreateVolume,
5741     device_parent_CreateSwapChain,
5742 };
5743
5744 HRESULT ddraw_init(IDirectDrawImpl *ddraw, WINED3DDEVTYPE device_type)
5745 {
5746     HRESULT hr;
5747     HDC hDC;
5748
5749     ddraw->lpVtbl = &ddraw7_vtbl;
5750     ddraw->IDirectDraw_vtbl = &ddraw1_vtbl;
5751     ddraw->IDirectDraw2_vtbl = &ddraw2_vtbl;
5752     ddraw->IDirectDraw3_vtbl = &ddraw3_vtbl;
5753     ddraw->IDirectDraw4_vtbl = &ddraw4_vtbl;
5754     ddraw->IDirect3D_vtbl = &d3d1_vtbl;
5755     ddraw->IDirect3D2_vtbl = &d3d2_vtbl;
5756     ddraw->IDirect3D3_vtbl = &d3d3_vtbl;
5757     ddraw->IDirect3D7_vtbl = &d3d7_vtbl;
5758     ddraw->device_parent_vtbl = &ddraw_wined3d_device_parent_vtbl;
5759     ddraw->numIfaces = 1;
5760     ddraw->ref7 = 1;
5761
5762     /* See comments in IDirectDrawImpl_CreateNewSurface for a description of
5763      * this field. */
5764     ddraw->ImplType = DefaultSurfaceType;
5765
5766     /* Get the current screen settings. */
5767     hDC = GetDC(0);
5768     ddraw->orig_bpp = GetDeviceCaps(hDC, BITSPIXEL) * GetDeviceCaps(hDC, PLANES);
5769     ReleaseDC(0, hDC);
5770     ddraw->orig_width = GetSystemMetrics(SM_CXSCREEN);
5771     ddraw->orig_height = GetSystemMetrics(SM_CYSCREEN);
5772
5773     if (!LoadWineD3D())
5774     {
5775         ERR("Failed to load wined3d - broken OpenGL setup?\n");
5776         return DDERR_NODIRECTDRAWSUPPORT;
5777     }
5778
5779     ddraw->wineD3D = pWineDirect3DCreate(7, (IUnknown *)ddraw);
5780     if (!ddraw->wineD3D)
5781     {
5782         WARN("Failed to create a wined3d object.\n");
5783         return E_OUTOFMEMORY;
5784     }
5785
5786     hr = IWineD3D_CreateDevice(ddraw->wineD3D, WINED3DADAPTER_DEFAULT, device_type, NULL, 0,
5787             (IWineD3DDeviceParent *)&ddraw->device_parent_vtbl, &ddraw->wineD3DDevice);
5788     if (FAILED(hr))
5789     {
5790         WARN("Failed to create a wined3d device, hr %#x.\n", hr);
5791         IWineD3D_Release(ddraw->wineD3D);
5792         return hr;
5793     }
5794
5795     /* Get the amount of video memory */
5796     ddraw->total_vidmem = IWineD3DDevice_GetAvailableTextureMem(ddraw->wineD3DDevice);
5797
5798     list_init(&ddraw->surface_list);
5799
5800     return DD_OK;
5801 }