ddraw: Do not crash when Clipper is NULL.
[wine] / dlls / ddraw / main.c
1 /*        DirectDraw Base Functions
2  *
3  * Copyright 1997-1999 Marcus Meissner
4  * Copyright 1998 Lionel Ulmer
5  * Copyright 2000-2001 TransGaming Technologies Inc.
6  * Copyright 2006 Stefan Dösinger
7  *
8  * This file contains the (internal) driver registration functions,
9  * driver enumeration APIs and DirectDraw creation functions.
10  *
11  * This library is free software; you can redistribute it and/or
12  * modify it under the terms of the GNU Lesser General Public
13  * License as published by the Free Software Foundation; either
14  * version 2.1 of the License, or (at your option) any later version.
15  *
16  * This library is distributed in the hope that it will be useful,
17  * but WITHOUT ANY WARRANTY; without even the implied warranty of
18  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
19  * Lesser General Public License for more details.
20  *
21  * You should have received a copy of the GNU Lesser General Public
22  * License along with this library; if not, write to the Free Software
23  * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA
24  */
25
26 #include "config.h"
27 #include "wine/port.h"
28 #include "wine/debug.h"
29
30 #include <assert.h>
31 #include <stdarg.h>
32 #include <string.h>
33 #include <stdlib.h>
34
35 #define COBJMACROS
36
37 #include "windef.h"
38 #include "winbase.h"
39 #include "winerror.h"
40 #include "wingdi.h"
41 #include "wine/exception.h"
42 #include "winreg.h"
43
44 #include "ddraw.h"
45 #include "d3d.h"
46
47 #include "ddraw_private.h"
48
49 typedef IWineD3D* (WINAPI *fnWineDirect3DCreate)(UINT, UINT, IUnknown *);
50
51 static HMODULE hWineD3D = (HMODULE) -1;
52 static fnWineDirect3DCreate pWineDirect3DCreate;
53
54 WINE_DEFAULT_DEBUG_CHANNEL(ddraw);
55
56 /* The configured default surface */
57 WINED3DSURFTYPE DefaultSurfaceType = SURFACE_UNKNOWN;
58
59 /* DDraw list and critical section */
60 static struct list global_ddraw_list = LIST_INIT(global_ddraw_list);
61
62 static CRITICAL_SECTION_DEBUG ddraw_cs_debug =
63 {
64     0, 0, &ddraw_cs,
65     { &ddraw_cs_debug.ProcessLocksList,
66     &ddraw_cs_debug.ProcessLocksList },
67     0, 0, { (DWORD_PTR)(__FILE__ ": ddraw_cs") }
68 };
69 CRITICAL_SECTION ddraw_cs = { &ddraw_cs_debug, -1, 0, 0, 0, 0 };
70
71 /***********************************************************************
72  *
73  * Helper function for DirectDrawCreate and friends
74  * Creates a new DDraw interface with the given REFIID
75  *
76  * Interfaces that can be created:
77  *  IDirectDraw, IDirectDraw2, IDirectDraw4, IDirectDraw7
78  *  IDirect3D, IDirect3D2, IDirect3D3, IDirect3D7. (Does Windows return
79  *  IDirect3D interfaces?)
80  *
81  * Arguments:
82  *  guid: ID of the requested driver, NULL for the default driver.
83  *        The GUID can be queried with DirectDrawEnumerate(Ex)A/W
84  *  DD: Used to return the pointer to the created object
85  *  UnkOuter: For aggregation, which is unsupported. Must be NULL
86  *  iid: requested version ID.
87  *
88  * Returns:
89  *  DD_OK if the Interface was created successfully
90  *  CLASS_E_NOAGGREGATION if UnkOuter is not NULL
91  *  E_OUTOFMEMORY if some allocation failed
92  *
93  ***********************************************************************/
94 static HRESULT
95 DDRAW_Create(const GUID *guid,
96              void **DD,
97              IUnknown *UnkOuter,
98              REFIID iid)
99 {
100     IDirectDrawImpl *This = NULL;
101     HRESULT hr;
102     IWineD3D *wineD3D = NULL;
103     IWineD3DDevice *wineD3DDevice = NULL;
104     HDC hDC;
105     WINED3DDEVTYPE devicetype;
106
107     TRACE("(%s,%p,%p)\n", debugstr_guid(guid), DD, UnkOuter);
108
109     *DD = NULL;
110
111     /* We don't care about this guids. Well, there's no special guid anyway
112      * OK, we could
113      */
114     if (guid == (GUID *) DDCREATE_EMULATIONONLY)
115     {
116         /* Use the reference device id. This doesn't actually change anything,
117          * WineD3D always uses OpenGL for D3D rendering. One could make it request
118          * indirect rendering
119          */
120         devicetype = WINED3DDEVTYPE_REF;
121     }
122     else if(guid == (GUID *) DDCREATE_HARDWAREONLY)
123     {
124         devicetype = WINED3DDEVTYPE_HAL;
125     }
126     else
127     {
128         devicetype = 0;
129     }
130
131     /* DDraw doesn't support aggregation, according to msdn */
132     if (UnkOuter != NULL)
133         return CLASS_E_NOAGGREGATION;
134
135     /* DirectDraw creation comes here */
136     This = HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, sizeof(IDirectDrawImpl));
137     if(!This)
138     {
139         ERR("Out of memory when creating DirectDraw\n");
140         return E_OUTOFMEMORY;
141     }
142
143     /* The interfaces:
144      * IDirectDraw and IDirect3D are the same object,
145      * QueryInterface is used to get other interfaces.
146      */
147     ICOM_INIT_INTERFACE(This, IDirectDraw,  IDirectDraw1_Vtbl);
148     ICOM_INIT_INTERFACE(This, IDirectDraw2, IDirectDraw2_Vtbl);
149     ICOM_INIT_INTERFACE(This, IDirectDraw3, IDirectDraw3_Vtbl);
150     ICOM_INIT_INTERFACE(This, IDirectDraw4, IDirectDraw4_Vtbl);
151     ICOM_INIT_INTERFACE(This, IDirectDraw7, IDirectDraw7_Vtbl);
152     ICOM_INIT_INTERFACE(This, IDirect3D,  IDirect3D1_Vtbl);
153     ICOM_INIT_INTERFACE(This, IDirect3D2, IDirect3D2_Vtbl);
154     ICOM_INIT_INTERFACE(This, IDirect3D3, IDirect3D3_Vtbl);
155     ICOM_INIT_INTERFACE(This, IDirect3D7, IDirect3D7_Vtbl);
156
157     /* See comments in IDirectDrawImpl_CreateNewSurface for a description
158      * of this member.
159      * Read from a registry key, should add a winecfg option later
160      */
161     This->ImplType = DefaultSurfaceType;
162
163     /* Get the current screen settings */
164     hDC = GetDC(0);
165     This->orig_bpp = GetDeviceCaps(hDC, BITSPIXEL) * GetDeviceCaps(hDC, PLANES);
166     ReleaseDC(0, hDC);
167     This->orig_width = GetSystemMetrics(SM_CXSCREEN);
168     This->orig_height = GetSystemMetrics(SM_CYSCREEN);
169
170     if (hWineD3D == (HMODULE) -1)
171     {
172         hWineD3D = LoadLibraryA("wined3d");
173         if (hWineD3D)
174         {
175             pWineDirect3DCreate = (fnWineDirect3DCreate) GetProcAddress(hWineD3D, "WineDirect3DCreate");
176             pWineDirect3DCreateClipper = (fnWineDirect3DCreateClipper) GetProcAddress(hWineD3D, "WineDirect3DCreateClipper");
177         }
178     }
179
180     if (!hWineD3D)
181     {
182         ERR("Couldn't load WineD3D - OpenGL libs not present?\n");
183         hr = DDERR_NODIRECTDRAWSUPPORT;
184         goto err_out;
185     }
186
187     /* Initialize WineD3D
188      *
189      * All Rendering (2D and 3D) is relayed to WineD3D,
190      * but DirectDraw specific management, like DDSURFACEDESC and DDPIXELFORMAT
191      * structure handling is handled in this lib.
192      */
193     wineD3D = pWineDirect3DCreate(0 /* SDKVersion */, 7 /* DXVersion */, (IUnknown *) This /* Parent */);
194     if(!wineD3D)
195     {
196         ERR("Failed to initialise WineD3D\n");
197         hr = E_OUTOFMEMORY;
198         goto err_out;
199     }
200     This->wineD3D = wineD3D;
201     TRACE("WineD3D created at %p\n", wineD3D);
202
203     /* Initialized member...
204      *
205      * It is set to false at creation time, and set to true in
206      * IDirectDraw7::Initialize. Its sole purpose is to return DD_OK on
207      * initialize only once
208      */
209     This->initialized = FALSE;
210
211     /* Initialize WineD3DDevice
212      *
213      * It is used for screen setup, surface and palette creation
214      * When a Direct3DDevice7 is created, the D3D capabilities of WineD3D are
215      * initialized
216      */
217     hr = IWineD3D_CreateDevice(wineD3D,
218                                0 /*D3D_ADAPTER_DEFAULT*/,
219                                devicetype,
220                                NULL, /* FocusWindow, don't know yet */
221                                0, /* BehaviorFlags */
222                                &wineD3DDevice,
223                                (IUnknown *) ICOM_INTERFACE(This, IDirectDraw7));
224     if(FAILED(hr))
225     {
226         ERR("Failed to create a wineD3DDevice, result = %x\n", hr);
227         goto err_out;
228     }
229     This->wineD3DDevice = wineD3DDevice;
230     TRACE("wineD3DDevice created at %p\n", This->wineD3DDevice);
231
232     /* Register the window class
233      *
234      * It is used to create a hidden window for D3D
235      * rendering, if the application didn't pass one.
236      * It can also be used for Creating a device window
237      * from SetCooperativeLevel
238      *
239      * The name: DDRAW_<address>. The classname is
240      * 32 bit long, so a 64 bit address will fit nicely
241      * (Will this be compiled for 64 bit anyway?)
242      *
243      */
244     sprintf(This->classname, "DDRAW_%p", This);
245
246     memset(&This->wnd_class, 0, sizeof(This->wnd_class));
247     This->wnd_class.style = CS_HREDRAW | CS_VREDRAW;
248     This->wnd_class.lpfnWndProc = DefWindowProcA;
249     This->wnd_class.cbClsExtra = 0;
250     This->wnd_class.cbWndExtra = 0;
251     This->wnd_class.hInstance = GetModuleHandleA(0);
252     This->wnd_class.hIcon = 0;
253     This->wnd_class.hCursor = 0;
254     This->wnd_class.hbrBackground = (HBRUSH) GetStockObject(BLACK_BRUSH);
255     This->wnd_class.lpszMenuName = NULL;
256     This->wnd_class.lpszClassName = This->classname;
257     if(!RegisterClassA(&This->wnd_class))
258     {
259         ERR("RegisterClassA failed!\n");
260         goto err_out;
261     }
262
263     /* Get the amount of video memory */
264     This->total_vidmem = IWineD3DDevice_GetAvailableTextureMem(This->wineD3DDevice);
265
266     /* Initialize the caps */
267     This->caps.dwSize = sizeof(This->caps);
268 /* do not report DDCAPS_OVERLAY and friends since we don't support overlays */
269 #define BLIT_CAPS (DDCAPS_BLT | DDCAPS_BLTCOLORFILL | DDCAPS_BLTDEPTHFILL \
270           | DDCAPS_BLTSTRETCH | DDCAPS_CANBLTSYSMEM | DDCAPS_CANCLIP      \
271           | DDCAPS_CANCLIPSTRETCHED | DDCAPS_COLORKEY                     \
272           | DDCAPS_COLORKEYHWASSIST | DDCAPS_ALIGNBOUNDARYSRC )
273 #define CKEY_CAPS (DDCKEYCAPS_DESTBLT | DDCKEYCAPS_SRCBLT)
274 #define FX_CAPS (DDFXCAPS_BLTALPHA | DDFXCAPS_BLTMIRRORLEFTRIGHT        \
275                 | DDFXCAPS_BLTMIRRORUPDOWN | DDFXCAPS_BLTROTATION90     \
276                 | DDFXCAPS_BLTSHRINKX | DDFXCAPS_BLTSHRINKXN            \
277                 | DDFXCAPS_BLTSHRINKY | DDFXCAPS_BLTSHRINKXN            \
278                 | DDFXCAPS_BLTSTRETCHX | DDFXCAPS_BLTSTRETCHXN          \
279                 | DDFXCAPS_BLTSTRETCHY | DDFXCAPS_BLTSTRETCHYN)
280     This->caps.dwCaps |= DDCAPS_GDI | DDCAPS_PALETTE | BLIT_CAPS;
281
282     This->caps.dwCaps2 |= DDCAPS2_CERTIFIED | DDCAPS2_NOPAGELOCKREQUIRED |
283                           DDCAPS2_PRIMARYGAMMA | DDCAPS2_WIDESURFACES |
284                           DDCAPS2_CANRENDERWINDOWED;
285     This->caps.dwCKeyCaps |= CKEY_CAPS;
286     This->caps.dwFXCaps |= FX_CAPS;
287     This->caps.dwPalCaps |= DDPCAPS_8BIT | DDPCAPS_PRIMARYSURFACE;
288     This->caps.dwVidMemTotal = This->total_vidmem;
289     This->caps.dwVidMemFree = This->total_vidmem;
290     This->caps.dwSVBCaps |= BLIT_CAPS;
291     This->caps.dwSVBCKeyCaps |= CKEY_CAPS;
292     This->caps.dwSVBFXCaps |= FX_CAPS;
293     This->caps.dwVSBCaps |= BLIT_CAPS;
294     This->caps.dwVSBCKeyCaps |= CKEY_CAPS;
295     This->caps.dwVSBFXCaps |= FX_CAPS;
296     This->caps.dwSSBCaps |= BLIT_CAPS;
297     This->caps.dwSSBCKeyCaps |= CKEY_CAPS;
298     This->caps.dwSSBFXCaps |= FX_CAPS;
299     This->caps.ddsCaps.dwCaps |= DDSCAPS_ALPHA | DDSCAPS_BACKBUFFER |
300                                  DDSCAPS_FLIP | DDSCAPS_FRONTBUFFER |
301                                  DDSCAPS_OFFSCREENPLAIN | DDSCAPS_PALETTE |
302                                  DDSCAPS_PRIMARYSURFACE | DDSCAPS_SYSTEMMEMORY |
303                                  DDSCAPS_VIDEOMEMORY | DDSCAPS_VISIBLE;
304     /* Hacks for D3D code */
305     /* TODO: Check if WineD3D has 3D enabled
306        Need opengl surfaces or auto for 3D
307      */
308     if(This->ImplType == 0 || This->ImplType == SURFACE_OPENGL)
309     {
310         This->caps.dwCaps |= DDCAPS_3D;
311         This->caps.ddsCaps.dwCaps |= DDSCAPS_3DDEVICE | DDSCAPS_MIPMAP | DDSCAPS_TEXTURE | DDSCAPS_ZBUFFER;
312     }
313     This->caps.ddsOldCaps.dwCaps = This->caps.ddsCaps.dwCaps;
314
315 #undef BLIT_CAPS
316 #undef CKEY_CAPS
317 #undef FX_CAPS
318
319     list_init(&This->surface_list);
320     list_add_head(&global_ddraw_list, &This->ddraw_list_entry);
321
322     This->decls = HeapAlloc(GetProcessHeap(), 0, 0);
323     if(!This->decls)
324     {
325         ERR("Error allocating an empty array for the converted vertex decls\n");
326         goto err_out;
327     }
328
329     /* Call QueryInterface to get the pointer to the requested interface. This also initializes
330      * The required refcount
331      */
332     hr = IDirectDraw7_QueryInterface( ICOM_INTERFACE(This, IDirectDraw7), iid, DD);
333     if(SUCCEEDED(hr)) return DD_OK;
334
335 err_out:
336     /* Let's hope we never need this ;) */
337     if(wineD3DDevice) IWineD3DDevice_Release(wineD3DDevice);
338     if(wineD3D) IWineD3D_Release(wineD3D);
339     if(This) HeapFree(GetProcessHeap(), 0, This->decls);
340     HeapFree(GetProcessHeap(), 0, This);
341     return hr;
342 }
343
344 /***********************************************************************
345  * DirectDrawCreate (DDRAW.@)
346  *
347  * Creates legacy DirectDraw Interfaces. Can't create IDirectDraw7
348  * interfaces in theory
349  *
350  * Arguments, return values: See DDRAW_Create
351  *
352  ***********************************************************************/
353 HRESULT WINAPI
354 DirectDrawCreate(GUID *GUID,
355                  IDirectDraw **DD,
356                  IUnknown *UnkOuter)
357 {
358     HRESULT hr;
359     TRACE("(%s,%p,%p)\n", debugstr_guid(GUID), DD, UnkOuter);
360
361     EnterCriticalSection(&ddraw_cs);
362     hr = DDRAW_Create(GUID, (void **) DD, UnkOuter, &IID_IDirectDraw);
363     LeaveCriticalSection(&ddraw_cs);
364     return hr;
365 }
366
367 /***********************************************************************
368  * DirectDrawCreateEx (DDRAW.@)
369  *
370  * Only creates new IDirectDraw7 interfaces, supposed to fail if legacy
371  * interfaces are requested.
372  *
373  * Arguments, return values: See DDRAW_Create
374  *
375  ***********************************************************************/
376 HRESULT WINAPI
377 DirectDrawCreateEx(GUID *GUID,
378                    void **DD,
379                    REFIID iid,
380                    IUnknown *UnkOuter)
381 {
382     HRESULT hr;
383     TRACE("(%s,%p,%s,%p)\n", debugstr_guid(GUID), DD, debugstr_guid(iid), UnkOuter);
384
385     if (!IsEqualGUID(iid, &IID_IDirectDraw7))
386         return DDERR_INVALIDPARAMS;
387
388     EnterCriticalSection(&ddraw_cs);
389     hr = DDRAW_Create(GUID, DD, UnkOuter, iid);
390     LeaveCriticalSection(&ddraw_cs);
391     return hr;
392 }
393
394 /***********************************************************************
395  * DirectDrawEnumerateA (DDRAW.@)
396  *
397  * Enumerates legacy ddraw drivers, ascii version. We only have one
398  * driver, which relays to WineD3D. If we were sufficiently cool,
399  * we could offer various interfaces, which use a different default surface
400  * implementation, but I think it's better to offer this choice in
401  * winecfg, because some apps use the default driver, so we would need
402  * a winecfg option anyway, and there shouldn't be 2 ways to set one setting
403  *
404  * Arguments:
405  *  Callback: Callback function from the app
406  *  Context: Argument to the call back.
407  *
408  * Returns:
409  *  DD_OK on success
410  *  E_INVALIDARG if the Callback caused a page fault
411  *
412  *
413  ***********************************************************************/
414 HRESULT WINAPI
415 DirectDrawEnumerateA(LPDDENUMCALLBACKA Callback,
416                      void *Context)
417 {
418     BOOL stop = FALSE;
419
420     TRACE(" Enumerating default DirectDraw HAL interface\n");
421     /* We only have one driver */
422     __TRY
423     {
424         static CHAR driver_desc[] = "DirectDraw HAL",
425         driver_name[] = "display";
426
427         stop = !Callback(NULL, driver_desc, driver_name, Context);
428     }
429     __EXCEPT_PAGE_FAULT
430     {
431         return E_INVALIDARG;
432     }
433     __ENDTRY
434
435     TRACE(" End of enumeration\n");
436     return DD_OK;
437 }
438
439 /***********************************************************************
440  * DirectDrawEnumerateExA (DDRAW.@)
441  *
442  * Enumerates DirectDraw7 drivers, ascii version. See
443  * the comments above DirectDrawEnumerateA for more details.
444  *
445  * The Flag member is not supported right now.
446  *
447  ***********************************************************************/
448 HRESULT WINAPI
449 DirectDrawEnumerateExA(LPDDENUMCALLBACKEXA Callback,
450                        void *Context,
451                        DWORD Flags)
452 {
453     BOOL stop = FALSE;
454     TRACE("Enumerating default DirectDraw HAL interface\n");
455
456     /* We only have one driver by now */
457     __TRY
458     {
459         static CHAR driver_desc[] = "DirectDraw HAL",
460         driver_name[] = "display";
461
462         /* QuickTime expects the description "DirectDraw HAL" */
463         stop = !Callback(NULL, driver_desc, driver_name, Context, 0);
464     }
465     __EXCEPT_PAGE_FAULT
466     {
467         return E_INVALIDARG;
468     }
469     __ENDTRY;
470
471     TRACE("End of enumeration\n");
472     return DD_OK;
473 }
474
475 /***********************************************************************
476  * DirectDrawEnumerateW (DDRAW.@)
477  *
478  * Enumerates legacy drivers, unicode version. See
479  * the comments above DirectDrawEnumerateA for more details.
480  *
481  * The Flag member is not supported right now.
482  *
483  ***********************************************************************/
484
485 /***********************************************************************
486  * DirectDrawEnumerateExW (DDRAW.@)
487  *
488  * Enumerates DirectDraw7 drivers, unicode version. See
489  * the comments above DirectDrawEnumerateA for more details.
490  *
491  * The Flag member is not supported right now.
492  *
493  ***********************************************************************/
494
495 /***********************************************************************
496  * Classfactory implementation.
497  ***********************************************************************/
498
499 /***********************************************************************
500  * CF_CreateDirectDraw
501  *
502  * DDraw creation function for the class factory
503  *
504  * Params:
505  *  UnkOuter: Set to NULL
506  *  iid: ID of the wanted interface
507  *  obj: Address to pass the interface pointer back
508  *
509  * Returns
510  *  DD_OK / DDERR*, see DDRAW_Create
511  *
512  ***********************************************************************/
513 static HRESULT
514 CF_CreateDirectDraw(IUnknown* UnkOuter, REFIID iid,
515                     void **obj)
516 {
517     HRESULT hr;
518
519     TRACE("(%p,%s,%p)\n", UnkOuter, debugstr_guid(iid), obj);
520
521     EnterCriticalSection(&ddraw_cs);
522     hr = DDRAW_Create(NULL, obj, UnkOuter, iid);
523     LeaveCriticalSection(&ddraw_cs);
524     return hr;
525 }
526
527 /***********************************************************************
528  * CF_CreateDirectDraw
529  *
530  * Clipper creation function for the class factory
531  *
532  * Params:
533  *  UnkOuter: Set to NULL
534  *  iid: ID of the wanted interface
535  *  obj: Address to pass the interface pointer back
536  *
537  * Returns
538  *  DD_OK / DDERR*, see DDRAW_Create
539  *
540  ***********************************************************************/
541 static HRESULT
542 CF_CreateDirectDrawClipper(IUnknown* UnkOuter, REFIID riid,
543                               void **obj)
544 {
545     HRESULT hr;
546     IDirectDrawClipper *Clip;
547
548     EnterCriticalSection(&ddraw_cs);
549     hr = DirectDrawCreateClipper(0, &Clip, UnkOuter);
550     if (hr != DD_OK)
551     {
552         LeaveCriticalSection(&ddraw_cs);
553         return hr;
554     }
555
556     hr = IDirectDrawClipper_QueryInterface(Clip, riid, obj);
557     IDirectDrawClipper_Release(Clip);
558
559     LeaveCriticalSection(&ddraw_cs);
560     return hr;
561 }
562
563 static const struct object_creation_info object_creation[] =
564 {
565     { &CLSID_DirectDraw,        CF_CreateDirectDraw },
566     { &CLSID_DirectDraw7,       CF_CreateDirectDraw },
567     { &CLSID_DirectDrawClipper, CF_CreateDirectDrawClipper }
568 };
569
570 /*******************************************************************************
571  * IDirectDrawClassFactory::QueryInterface
572  *
573  * QueryInterface for the class factory
574  *
575  * PARAMS
576  *    riid   Reference to identifier of queried interface
577  *    ppv    Address to return the interface pointer at
578  *
579  * RETURNS
580  *    Success: S_OK
581  *    Failure: E_NOINTERFACE
582  *
583  *******************************************************************************/
584 static HRESULT WINAPI
585 IDirectDrawClassFactoryImpl_QueryInterface(IClassFactory *iface,
586                     REFIID riid,
587                     void **obj)
588 {
589     ICOM_THIS_FROM(IClassFactoryImpl, IClassFactory, iface);
590
591     TRACE("(%p)->(%s,%p)\n", This, debugstr_guid(riid), obj);
592
593     if (IsEqualGUID(riid, &IID_IUnknown)
594         || IsEqualGUID(riid, &IID_IClassFactory))
595     {
596         IClassFactory_AddRef(iface);
597         *obj = This;
598         return S_OK;
599     }
600
601     WARN("(%p)->(%s,%p),not found\n",This,debugstr_guid(riid),obj);
602     return E_NOINTERFACE;
603 }
604
605 /*******************************************************************************
606  * IDirectDrawClassFactory::AddRef
607  *
608  * AddRef for the class factory
609  *
610  * RETURNS
611  *  The new refcount
612  *
613  *******************************************************************************/
614 static ULONG WINAPI
615 IDirectDrawClassFactoryImpl_AddRef(IClassFactory *iface)
616 {
617     ICOM_THIS_FROM(IClassFactoryImpl, IClassFactory, iface);
618     ULONG ref = InterlockedIncrement(&This->ref);
619
620     TRACE("(%p)->() incrementing from %d.\n", This, ref - 1);
621
622     return ref;
623 }
624
625 /*******************************************************************************
626  * IDirectDrawClassFactory::Release
627  *
628  * Release for the class factory. If the refcount falls to 0, the object
629  * is destroyed
630  *
631  * RETURNS
632  *  The new refcount
633  *
634  *******************************************************************************/
635 static ULONG WINAPI
636 IDirectDrawClassFactoryImpl_Release(IClassFactory *iface)
637 {
638     ICOM_THIS_FROM(IClassFactoryImpl, IClassFactory, iface);
639     ULONG ref = InterlockedDecrement(&This->ref);
640     TRACE("(%p)->() decrementing from %d.\n", This, ref+1);
641
642     if (ref == 0)
643         HeapFree(GetProcessHeap(), 0, This);
644
645     return ref;
646 }
647
648
649 /*******************************************************************************
650  * IDirectDrawClassFactory::CreateInstance
651  *
652  * What is this? Seems to create DirectDraw objects...
653  *
654  * Params
655  *  The ususal things???
656  *
657  * RETURNS
658  *  ???
659  *
660  *******************************************************************************/
661 static HRESULT WINAPI
662 IDirectDrawClassFactoryImpl_CreateInstance(IClassFactory *iface,
663                                            IUnknown *UnkOuter,
664                                            REFIID riid,
665                                            void **obj)
666 {
667     ICOM_THIS_FROM(IClassFactoryImpl, IClassFactory, iface);
668
669     TRACE("(%p)->(%p,%s,%p)\n",This,UnkOuter,debugstr_guid(riid),obj);
670
671     return This->pfnCreateInstance(UnkOuter, riid, obj);
672 }
673
674 /*******************************************************************************
675  * IDirectDrawClassFactory::LockServer
676  *
677  * What is this?
678  *
679  * Params
680  *  ???
681  *
682  * RETURNS
683  *  S_OK, because it's a stub
684  *
685  *******************************************************************************/
686 static HRESULT WINAPI
687 IDirectDrawClassFactoryImpl_LockServer(IClassFactory *iface,BOOL dolock)
688 {
689     ICOM_THIS_FROM(IClassFactoryImpl, IClassFactory, iface);
690     FIXME("(%p)->(%d),stub!\n",This,dolock);
691     return S_OK;
692 }
693
694 /*******************************************************************************
695  * The class factory VTable
696  *******************************************************************************/
697 static const IClassFactoryVtbl IClassFactory_Vtbl =
698 {
699     IDirectDrawClassFactoryImpl_QueryInterface,
700     IDirectDrawClassFactoryImpl_AddRef,
701     IDirectDrawClassFactoryImpl_Release,
702     IDirectDrawClassFactoryImpl_CreateInstance,
703     IDirectDrawClassFactoryImpl_LockServer
704 };
705
706 /*******************************************************************************
707  * DllGetClassObject [DDRAW.@]
708  * Retrieves class object from a DLL object
709  *
710  * NOTES
711  *    Docs say returns STDAPI
712  *
713  * PARAMS
714  *    rclsid [I] CLSID for the class object
715  *    riid   [I] Reference to identifier of interface for class object
716  *    ppv    [O] Address of variable to receive interface pointer for riid
717  *
718  * RETURNS
719  *    Success: S_OK
720  *    Failure: CLASS_E_CLASSNOTAVAILABLE, E_OUTOFMEMORY, E_INVALIDARG,
721  *             E_UNEXPECTED
722  */
723 HRESULT WINAPI DllGetClassObject(REFCLSID rclsid, REFIID riid, LPVOID *ppv)
724 {
725     unsigned int i;
726     IClassFactoryImpl *factory;
727
728     TRACE("(%s,%s,%p)\n", debugstr_guid(rclsid), debugstr_guid(riid), ppv);
729
730     if ( !IsEqualGUID( &IID_IClassFactory, riid )
731          && ! IsEqualGUID( &IID_IUnknown, riid) )
732         return E_NOINTERFACE;
733
734     for (i=0; i < sizeof(object_creation)/sizeof(object_creation[0]); i++)
735     {
736         if (IsEqualGUID(object_creation[i].clsid, rclsid))
737             break;
738     }
739
740     if (i == sizeof(object_creation)/sizeof(object_creation[0]))
741     {
742         FIXME("%s: no class found.\n", debugstr_guid(rclsid));
743         return CLASS_E_CLASSNOTAVAILABLE;
744     }
745
746     factory = HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, sizeof(*factory));
747     if (factory == NULL) return E_OUTOFMEMORY;
748
749     ICOM_INIT_INTERFACE(factory, IClassFactory, IClassFactory_Vtbl);
750     factory->ref = 1;
751
752     factory->pfnCreateInstance = object_creation[i].pfnCreateInstance;
753
754     *ppv = ICOM_INTERFACE(factory, IClassFactory);
755     return S_OK;
756 }
757
758
759 /*******************************************************************************
760  * DllCanUnloadNow [DDRAW.@]  Determines whether the DLL is in use.
761  *
762  * RETURNS
763  *    Success: S_OK
764  *    Failure: S_FALSE
765  */
766 HRESULT WINAPI DllCanUnloadNow(void)
767 {
768     HRESULT hr;
769     FIXME("(void): stub\n");
770
771     EnterCriticalSection(&ddraw_cs);
772     hr = S_FALSE;
773     LeaveCriticalSection(&ddraw_cs);
774
775     return hr;
776 }
777
778 /*******************************************************************************
779  * DestroyCallback
780  *
781  * Callback function for the EnumSurfaces call in DllMain.
782  * Dumps some surface info and releases the surface
783  *
784  * Params:
785  *  surf: The enumerated surface
786  *  desc: it's description
787  *  context: Pointer to the ddraw impl
788  *
789  * Returns:
790  *  DDENUMRET_OK;
791  *******************************************************************************/
792 static HRESULT WINAPI
793 DestroyCallback(IDirectDrawSurface7 *surf,
794                 DDSURFACEDESC2 *desc,
795                 void *context)
796 {
797     IDirectDrawSurfaceImpl *Impl = ICOM_OBJECT(IDirectDrawSurfaceImpl, IDirectDrawSurface7, surf);
798     IDirectDrawImpl *ddraw = (IDirectDrawImpl *) context;
799     ULONG ref;
800
801     ref = IDirectDrawSurface7_Release(surf);  /* For the EnumSurfaces */
802     WARN("Surface %p has an reference count of %d\n", Impl, ref);
803
804     /* Skip surfaces which are attached somewhere or which are
805      * part of a complex compound. They will get released when destroying
806      * the root
807      */
808     if( (!Impl->is_complex_root) || (Impl->first_attached != Impl) )
809         return DDENUMRET_OK;
810     /* Skip our depth stencil surface, it will be released with the render target */
811     if( Impl == ddraw->DepthStencilBuffer)
812         return DDENUMRET_OK;
813
814     /* Destroy the surface */
815     while(ref) ref = IDirectDrawSurface7_Release(surf);
816
817     return DDENUMRET_OK;
818 }
819
820 /***********************************************************************
821  * get_config_key
822  *
823  * Reads a config key from the registry. Taken from WineD3D
824  *
825  ***********************************************************************/
826 static inline DWORD get_config_key(HKEY defkey, HKEY appkey, const char* name, char* buffer, DWORD size)
827 {
828     if (0 != appkey && !RegQueryValueExA( appkey, name, 0, NULL, (LPBYTE) buffer, &size )) return 0;
829     if (0 != defkey && !RegQueryValueExA( defkey, name, 0, NULL, (LPBYTE) buffer, &size )) return 0;
830     return ERROR_FILE_NOT_FOUND;
831 }
832
833 /***********************************************************************
834  * DllMain (DDRAW.0)
835  *
836  * Could be used to register DirectDraw drivers, if we have more than
837  * one. Also used to destroy any objects left at unload if the
838  * app didn't release them properly(Gothic 2, Diablo 2, Moto racer, ...)
839  *
840  ***********************************************************************/
841 BOOL WINAPI
842 DllMain(HINSTANCE hInstDLL,
843         DWORD Reason,
844         void *lpv)
845 {
846     TRACE("(%p,%x,%p)\n", hInstDLL, Reason, lpv);
847     if (Reason == DLL_PROCESS_ATTACH)
848     {
849         char buffer[MAX_PATH+10];
850         DWORD size = sizeof(buffer);
851         HKEY hkey = 0;
852         HKEY appkey = 0;
853         DWORD len;
854
855        /* @@ Wine registry key: HKCU\Software\Wine\Direct3D */
856        if ( RegOpenKeyA( HKEY_CURRENT_USER, "Software\\Wine\\Direct3D", &hkey ) ) hkey = 0;
857
858        len = GetModuleFileNameA( 0, buffer, MAX_PATH );
859        if (len && len < MAX_PATH)
860        {
861             HKEY tmpkey;
862             /* @@ Wine registry key: HKCU\Software\Wine\AppDefaults\app.exe\Direct3D */
863             if (!RegOpenKeyA( HKEY_CURRENT_USER, "Software\\Wine\\AppDefaults", &tmpkey ))
864             {
865                 char *p, *appname = buffer;
866                 if ((p = strrchr( appname, '/' ))) appname = p + 1;
867                 if ((p = strrchr( appname, '\\' ))) appname = p + 1;
868                 strcat( appname, "\\Direct3D" );
869                 TRACE("appname = [%s]\n", appname);
870                 if (RegOpenKeyA( tmpkey, appname, &appkey )) appkey = 0;
871                 RegCloseKey( tmpkey );
872             }
873        }
874
875        if ( 0 != hkey || 0 != appkey )
876        {
877             if ( !get_config_key( hkey, appkey, "DirectDrawRenderer", buffer, size) )
878             {
879                 if (!strcmp(buffer,"gdi"))
880                 {
881                     TRACE("Defaulting to GDI surfaces\n");
882                     DefaultSurfaceType = SURFACE_GDI;
883                 }
884                 else if (!strcmp(buffer,"opengl"))
885                 {
886                     TRACE("Defaulting to opengl surfaces\n");
887                     DefaultSurfaceType = SURFACE_OPENGL;
888                 }
889                 else
890                 {
891                     ERR("Unknown default surface type. Supported are:\n gdi, opengl\n");
892                 }
893             }
894         }
895
896         DisableThreadLibraryCalls(hInstDLL);
897     }
898     else if (Reason == DLL_PROCESS_DETACH)
899     {
900         if(!list_empty(&global_ddraw_list))
901         {
902             struct list *entry, *entry2;
903             WARN("There are still existing DirectDraw interfaces. Wine bug or buggy application?\n");
904
905             /* We remove elemets from this loop */
906             LIST_FOR_EACH_SAFE(entry, entry2, &global_ddraw_list)
907             {
908                 HRESULT hr;
909                 DDSURFACEDESC2 desc;
910                 int i;
911                 IDirectDrawImpl *ddraw = LIST_ENTRY(entry, IDirectDrawImpl, ddraw_list_entry);
912
913                 WARN("DDraw %p has a refcount of %d\n", ddraw, ddraw->ref7 + ddraw->ref4 + ddraw->ref3 + ddraw->ref2 + ddraw->ref1);
914
915                 /* Add references to each interface to avoid freeing them unexpectadely */
916                 IDirectDraw_AddRef(ICOM_INTERFACE(ddraw, IDirectDraw));
917                 IDirectDraw2_AddRef(ICOM_INTERFACE(ddraw, IDirectDraw2));
918                 IDirectDraw3_AddRef(ICOM_INTERFACE(ddraw, IDirectDraw3));
919                 IDirectDraw4_AddRef(ICOM_INTERFACE(ddraw, IDirectDraw4));
920                 IDirectDraw7_AddRef(ICOM_INTERFACE(ddraw, IDirectDraw7));
921
922                 /* Does a D3D device exist? Destroy it
923                     * TODO: Destroy all Vertex buffers, Lights, Materials
924                     * and execture buffers too
925                     */
926                 if(ddraw->d3ddevice)
927                 {
928                     WARN("DDraw %p has d3ddevice %p attached\n", ddraw, ddraw->d3ddevice);
929                     while(IDirect3DDevice7_Release(ICOM_INTERFACE(ddraw->d3ddevice, IDirect3DDevice7)));
930                 }
931
932                 /* Try to release the objects
933                     * Do an EnumSurfaces to find any hanging surfaces
934                     */
935                 memset(&desc, 0, sizeof(desc));
936                 desc.dwSize = sizeof(desc);
937                 for(i = 0; i <= 1; i++)
938                 {
939                     hr = IDirectDraw7_EnumSurfaces(ICOM_INTERFACE(ddraw, IDirectDraw7),
940                                                     DDENUMSURFACES_ALL,
941                                                     &desc,
942                                                     (void *) ddraw,
943                                                     DestroyCallback);
944                     if(hr != D3D_OK)
945                         ERR("(%p) EnumSurfaces failed, prepare for trouble\n", ddraw);
946                 }
947
948                 /* Check the surface count */
949                 if(ddraw->surfaces > 0)
950                     ERR("DDraw %p still has %d surfaces attached\n", ddraw, ddraw->surfaces);
951
952                 /* Release all hanging references to destroy the objects. This
953                     * restores the screen mode too
954                     */
955                 while(IDirectDraw_Release(ICOM_INTERFACE(ddraw, IDirectDraw)));
956                 while(IDirectDraw2_Release(ICOM_INTERFACE(ddraw, IDirectDraw2)));
957                 while(IDirectDraw3_Release(ICOM_INTERFACE(ddraw, IDirectDraw3)));
958                 while(IDirectDraw4_Release(ICOM_INTERFACE(ddraw, IDirectDraw4)));
959                 while(IDirectDraw7_Release(ICOM_INTERFACE(ddraw, IDirectDraw7)));
960             }
961         }
962     }
963
964     return TRUE;
965 }