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