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