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