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