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