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