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