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