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