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