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