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