Release 1.5.29.
[wine] / dlls / wined3d / wined3d_main.c
1 /*
2  * Direct3D wine internal interface main
3  *
4  * Copyright 2002-2003 The wine-d3d team
5  * Copyright 2002-2003 Raphael Junqueira
6  * Copyright 2004      Jason Edmeades
7  * Copyright 2007-2008 Stefan Dösinger for CodeWeavers
8  * Copyright 2009 Henri Verbeet for CodeWeavers
9  *
10  * This library is free software; you can redistribute it and/or
11  * modify it under the terms of the GNU Lesser General Public
12  * License as published by the Free Software Foundation; either
13  * version 2.1 of the License, or (at your option) any later version.
14  *
15  * This library is distributed in the hope that it will be useful,
16  * but WITHOUT ANY WARRANTY; without even the implied warranty of
17  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
18  * Lesser General Public License for more details.
19  *
20  * You should have received a copy of the GNU Lesser General Public
21  * License along with this library; if not, write to the Free Software
22  * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA
23  */
24
25 #include "config.h"
26 #include "wine/port.h"
27
28 #include "initguid.h"
29 #include "wined3d_private.h"
30
31 WINE_DEFAULT_DEBUG_CHANNEL(d3d);
32 WINE_DECLARE_DEBUG_CHANNEL(winediag);
33
34 struct wined3d_wndproc
35 {
36     HWND window;
37     BOOL unicode;
38     WNDPROC proc;
39     struct wined3d_device *device;
40 };
41
42 struct wined3d_wndproc_table
43 {
44     struct wined3d_wndproc *entries;
45     unsigned int count;
46     unsigned int size;
47 };
48
49 static struct wined3d_wndproc_table wndproc_table;
50
51 static CRITICAL_SECTION wined3d_cs;
52 static CRITICAL_SECTION_DEBUG wined3d_cs_debug =
53 {
54     0, 0, &wined3d_cs,
55     {&wined3d_cs_debug.ProcessLocksList,
56     &wined3d_cs_debug.ProcessLocksList},
57     0, 0, {(DWORD_PTR)(__FILE__ ": wined3d_cs")}
58 };
59 static CRITICAL_SECTION wined3d_cs = {&wined3d_cs_debug, -1, 0, 0, 0, 0};
60
61 static CRITICAL_SECTION wined3d_wndproc_cs;
62 static CRITICAL_SECTION_DEBUG wined3d_wndproc_cs_debug =
63 {
64     0, 0, &wined3d_wndproc_cs,
65     {&wined3d_wndproc_cs_debug.ProcessLocksList,
66     &wined3d_wndproc_cs_debug.ProcessLocksList},
67     0, 0, {(DWORD_PTR)(__FILE__ ": wined3d_wndproc_cs")}
68 };
69 static CRITICAL_SECTION wined3d_wndproc_cs = {&wined3d_wndproc_cs_debug, -1, 0, 0, 0, 0};
70
71 /* When updating default value here, make sure to update winecfg as well,
72  * where appropriate. */
73 struct wined3d_settings wined3d_settings =
74 {
75     TRUE,           /* Use of GLSL enabled by default */
76     ORM_FBO,        /* Use FBOs to do offscreen rendering */
77     RTL_READTEX,    /* Default render target locking method */
78     PCI_VENDOR_NONE,/* PCI Vendor ID */
79     PCI_DEVICE_NONE,/* PCI Device ID */
80     0,              /* The default of memory is set in init_driver_info */
81     NULL,           /* No wine logo by default */
82     TRUE,           /* Multisampling enabled by default. */
83     FALSE,          /* No strict draw ordering. */
84     TRUE,           /* Don't try to render onscreen by default. */
85     ~0U,            /* No VS shader model limit by default. */
86     ~0U,            /* No GS shader model limit by default. */
87     ~0U,            /* No PS shader model limit by default. */
88 };
89
90 /* Do not call while under the GL lock. */
91 struct wined3d * CDECL wined3d_create(UINT version, DWORD flags)
92 {
93     struct wined3d *object;
94     HRESULT hr;
95
96     object = HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, FIELD_OFFSET(struct wined3d, adapters[1]));
97     if (!object)
98     {
99         ERR("Failed to allocate wined3d object memory.\n");
100         return NULL;
101     }
102
103     hr = wined3d_init(object, version, flags);
104     if (FAILED(hr))
105     {
106         WARN("Failed to initialize wined3d object, hr %#x.\n", hr);
107         HeapFree(GetProcessHeap(), 0, object);
108         return NULL;
109     }
110
111     TRACE("Created wined3d object %p for d3d%d support.\n", object, version);
112
113     return object;
114 }
115
116 static DWORD get_config_key(HKEY defkey, HKEY appkey, const char *name, char *buffer, DWORD size)
117 {
118     if (appkey && !RegQueryValueExA(appkey, name, 0, NULL, (BYTE *)buffer, &size)) return 0;
119     if (defkey && !RegQueryValueExA(defkey, name, 0, NULL, (BYTE *)buffer, &size)) return 0;
120     return ERROR_FILE_NOT_FOUND;
121 }
122
123 static DWORD get_config_key_dword(HKEY defkey, HKEY appkey, const char *name, DWORD *data)
124 {
125     DWORD type;
126     DWORD size = sizeof(DWORD);
127     if (appkey && !RegQueryValueExA(appkey, name, 0, &type, (BYTE *)data, &size) && (type == REG_DWORD)) return 0;
128     if (defkey && !RegQueryValueExA(defkey, name, 0, &type, (BYTE *)data, &size) && (type == REG_DWORD)) return 0;
129     return ERROR_FILE_NOT_FOUND;
130 }
131
132 static BOOL wined3d_dll_init(HINSTANCE hInstDLL)
133 {
134     DWORD wined3d_context_tls_idx;
135     char buffer[MAX_PATH+10];
136     DWORD size = sizeof(buffer);
137     HKEY hkey = 0;
138     HKEY appkey = 0;
139     DWORD len, tmpvalue;
140     WNDCLASSA wc;
141
142     wined3d_context_tls_idx = TlsAlloc();
143     if (wined3d_context_tls_idx == TLS_OUT_OF_INDEXES)
144     {
145         DWORD err = GetLastError();
146         ERR("Failed to allocate context TLS index, err %#x.\n", err);
147         return FALSE;
148     }
149     context_set_tls_idx(wined3d_context_tls_idx);
150
151     /* We need our own window class for a fake window which we use to retrieve GL capabilities */
152     /* We might need CS_OWNDC in the future if we notice strange things on Windows.
153      * Various articles/posts about OpenGL problems on Windows recommend this. */
154     wc.style                = CS_HREDRAW | CS_VREDRAW;
155     wc.lpfnWndProc          = DefWindowProcA;
156     wc.cbClsExtra           = 0;
157     wc.cbWndExtra           = 0;
158     wc.hInstance            = hInstDLL;
159     wc.hIcon                = LoadIconA(NULL, (LPCSTR)IDI_WINLOGO);
160     wc.hCursor              = LoadCursorA(NULL, (LPCSTR)IDC_ARROW);
161     wc.hbrBackground        = NULL;
162     wc.lpszMenuName         = NULL;
163     wc.lpszClassName        = WINED3D_OPENGL_WINDOW_CLASS_NAME;
164
165     if (!RegisterClassA(&wc))
166     {
167         ERR("Failed to register window class 'WineD3D_OpenGL'!\n");
168         if (!TlsFree(wined3d_context_tls_idx))
169         {
170             DWORD err = GetLastError();
171             ERR("Failed to free context TLS index, err %#x.\n", err);
172         }
173         return FALSE;
174     }
175
176     DisableThreadLibraryCalls(hInstDLL);
177
178     /* @@ Wine registry key: HKCU\Software\Wine\Direct3D */
179     if ( RegOpenKeyA( HKEY_CURRENT_USER, "Software\\Wine\\Direct3D", &hkey ) ) hkey = 0;
180
181     len = GetModuleFileNameA( 0, buffer, MAX_PATH );
182     if (len && len < MAX_PATH)
183     {
184         HKEY tmpkey;
185         /* @@ Wine registry key: HKCU\Software\Wine\AppDefaults\app.exe\Direct3D */
186         if (!RegOpenKeyA( HKEY_CURRENT_USER, "Software\\Wine\\AppDefaults", &tmpkey ))
187         {
188             char *p, *appname = buffer;
189             if ((p = strrchr( appname, '/' ))) appname = p + 1;
190             if ((p = strrchr( appname, '\\' ))) appname = p + 1;
191             strcat( appname, "\\Direct3D" );
192             TRACE("appname = [%s]\n", appname);
193             if (RegOpenKeyA( tmpkey, appname, &appkey )) appkey = 0;
194             RegCloseKey( tmpkey );
195         }
196     }
197
198     if (hkey || appkey)
199     {
200         if ( !get_config_key( hkey, appkey, "UseGLSL", buffer, size) )
201         {
202             if (!strcmp(buffer,"disabled"))
203             {
204                 ERR_(winediag)("The GLSL shader backend has been disabled. You get to keep all the pieces if it breaks.\n");
205                 TRACE("Use of GL Shading Language disabled\n");
206                 wined3d_settings.glslRequested = FALSE;
207             }
208         }
209         if ( !get_config_key( hkey, appkey, "OffscreenRenderingMode", buffer, size) )
210         {
211             if (!strcmp(buffer,"backbuffer"))
212             {
213                 TRACE("Using the backbuffer for offscreen rendering\n");
214                 wined3d_settings.offscreen_rendering_mode = ORM_BACKBUFFER;
215             }
216             else if (!strcmp(buffer,"fbo"))
217             {
218                 TRACE("Using FBOs for offscreen rendering\n");
219                 wined3d_settings.offscreen_rendering_mode = ORM_FBO;
220             }
221         }
222         if ( !get_config_key( hkey, appkey, "RenderTargetLockMode", buffer, size) )
223         {
224             if (!strcmp(buffer,"readdraw"))
225             {
226                 TRACE("Using glReadPixels for render target reading and glDrawPixels for writing\n");
227                 wined3d_settings.rendertargetlock_mode = RTL_READDRAW;
228             }
229             else if (!strcmp(buffer,"readtex"))
230             {
231                 TRACE("Using glReadPixels for render target reading and textures for writing\n");
232                 wined3d_settings.rendertargetlock_mode = RTL_READTEX;
233             }
234         }
235         if ( !get_config_key_dword( hkey, appkey, "VideoPciDeviceID", &tmpvalue) )
236         {
237             int pci_device_id = tmpvalue;
238
239             /* A pci device id is 16-bit */
240             if(pci_device_id > 0xffff)
241             {
242                 ERR("Invalid value for VideoPciDeviceID. The value should be smaller or equal to 65535 or 0xffff\n");
243             }
244             else
245             {
246                 TRACE("Using PCI Device ID %04x\n", pci_device_id);
247                 wined3d_settings.pci_device_id = pci_device_id;
248             }
249         }
250         if ( !get_config_key_dword( hkey, appkey, "VideoPciVendorID", &tmpvalue) )
251         {
252             int pci_vendor_id = tmpvalue;
253
254             /* A pci device id is 16-bit */
255             if(pci_vendor_id > 0xffff)
256             {
257                 ERR("Invalid value for VideoPciVendorID. The value should be smaller or equal to 65535 or 0xffff\n");
258             }
259             else
260             {
261                 TRACE("Using PCI Vendor ID %04x\n", pci_vendor_id);
262                 wined3d_settings.pci_vendor_id = pci_vendor_id;
263             }
264         }
265         if ( !get_config_key( hkey, appkey, "VideoMemorySize", buffer, size) )
266         {
267             int TmpVideoMemorySize = atoi(buffer);
268             if(TmpVideoMemorySize > 0)
269             {
270                 wined3d_settings.emulated_textureram = TmpVideoMemorySize *1024*1024;
271                 TRACE("Use %iMB = %d byte for emulated_textureram\n",
272                         TmpVideoMemorySize,
273                         wined3d_settings.emulated_textureram);
274             }
275             else
276                 ERR("VideoMemorySize is %i but must be >0\n", TmpVideoMemorySize);
277         }
278         if ( !get_config_key( hkey, appkey, "WineLogo", buffer, size) )
279         {
280             size_t len = strlen(buffer) + 1;
281
282             wined3d_settings.logo = HeapAlloc(GetProcessHeap(), 0, len);
283             if (!wined3d_settings.logo) ERR("Failed to allocate logo path memory.\n");
284             else memcpy(wined3d_settings.logo, buffer, len);
285         }
286         if ( !get_config_key( hkey, appkey, "Multisampling", buffer, size) )
287         {
288             if (!strcmp(buffer, "disabled"))
289             {
290                 TRACE("Multisampling disabled.\n");
291                 wined3d_settings.allow_multisampling = FALSE;
292             }
293         }
294         if (!get_config_key(hkey, appkey, "StrictDrawOrdering", buffer, size)
295                 && !strcmp(buffer,"enabled"))
296         {
297             TRACE("Enforcing strict draw ordering.\n");
298             wined3d_settings.strict_draw_ordering = TRUE;
299         }
300         if (!get_config_key(hkey, appkey, "AlwaysOffscreen", buffer, size)
301                 && !strcmp(buffer,"disabled"))
302         {
303             TRACE("Not always rendering backbuffers offscreen.\n");
304             wined3d_settings.always_offscreen = FALSE;
305         }
306         if (!get_config_key_dword(hkey, appkey, "MaxShaderModelVS", &wined3d_settings.max_sm_vs))
307             TRACE("Limiting VS shader model to %u.\n", wined3d_settings.max_sm_vs);
308         if (!get_config_key_dword(hkey, appkey, "MaxShaderModelGS", &wined3d_settings.max_sm_gs))
309             TRACE("Limiting GS shader model to %u.\n", wined3d_settings.max_sm_gs);
310         if (!get_config_key_dword(hkey, appkey, "MaxShaderModelPS", &wined3d_settings.max_sm_ps))
311             TRACE("Limiting PS shader model to %u.\n", wined3d_settings.max_sm_ps);
312     }
313
314     if (appkey) RegCloseKey( appkey );
315     if (hkey) RegCloseKey( hkey );
316
317     return TRUE;
318 }
319
320 static BOOL wined3d_dll_destroy(HINSTANCE hInstDLL)
321 {
322     DWORD wined3d_context_tls_idx = context_get_tls_idx();
323     unsigned int i;
324
325     if (!TlsFree(wined3d_context_tls_idx))
326     {
327         DWORD err = GetLastError();
328         ERR("Failed to free context TLS index, err %#x.\n", err);
329     }
330
331     for (i = 0; i < wndproc_table.count; ++i)
332     {
333         /* Trying to unregister these would be futile. These entries can only
334          * exist if either we skipped them in wined3d_unregister_window() due
335          * to the application replacing the wndproc after the entry was
336          * registered, or if the application still has an active wined3d
337          * device. In the latter case the application has bigger problems than
338          * these entries. */
339         WARN("Leftover wndproc table entry %p.\n", &wndproc_table.entries[i]);
340     }
341     HeapFree(GetProcessHeap(), 0, wndproc_table.entries);
342
343     HeapFree(GetProcessHeap(), 0, wined3d_settings.logo);
344     UnregisterClassA(WINED3D_OPENGL_WINDOW_CLASS_NAME, hInstDLL);
345
346     DeleteCriticalSection(&wined3d_wndproc_cs);
347     DeleteCriticalSection(&wined3d_cs);
348     return TRUE;
349 }
350
351 void WINAPI wined3d_mutex_lock(void)
352 {
353     EnterCriticalSection(&wined3d_cs);
354 }
355
356 void WINAPI wined3d_mutex_unlock(void)
357 {
358     LeaveCriticalSection(&wined3d_cs);
359 }
360
361 static void wined3d_wndproc_mutex_lock(void)
362 {
363     EnterCriticalSection(&wined3d_wndproc_cs);
364 }
365
366 static void wined3d_wndproc_mutex_unlock(void)
367 {
368     LeaveCriticalSection(&wined3d_wndproc_cs);
369 }
370
371 static struct wined3d_wndproc *wined3d_find_wndproc(HWND window)
372 {
373     unsigned int i;
374
375     for (i = 0; i < wndproc_table.count; ++i)
376     {
377         if (wndproc_table.entries[i].window == window)
378         {
379             return &wndproc_table.entries[i];
380         }
381     }
382
383     return NULL;
384 }
385
386 static LRESULT CALLBACK wined3d_wndproc(HWND window, UINT message, WPARAM wparam, LPARAM lparam)
387 {
388     struct wined3d_wndproc *entry;
389     struct wined3d_device *device;
390     BOOL unicode;
391     WNDPROC proc;
392
393     wined3d_wndproc_mutex_lock();
394     entry = wined3d_find_wndproc(window);
395
396     if (!entry)
397     {
398         wined3d_wndproc_mutex_unlock();
399         ERR("Window %p is not registered with wined3d.\n", window);
400         return DefWindowProcW(window, message, wparam, lparam);
401     }
402
403     device = entry->device;
404     unicode = entry->unicode;
405     proc = entry->proc;
406     wined3d_wndproc_mutex_unlock();
407
408     if (device)
409         return device_process_message(device, window, unicode, message, wparam, lparam, proc);
410     if (unicode)
411         return CallWindowProcW(proc, window, message, wparam, lparam);
412     return CallWindowProcA(proc, window, message, wparam, lparam);
413 }
414
415 BOOL wined3d_register_window(HWND window, struct wined3d_device *device)
416 {
417     struct wined3d_wndproc *entry;
418
419     wined3d_wndproc_mutex_lock();
420
421     if (wined3d_find_wndproc(window))
422     {
423         wined3d_wndproc_mutex_unlock();
424         WARN("Window %p is already registered with wined3d.\n", window);
425         return TRUE;
426     }
427
428     if (wndproc_table.size == wndproc_table.count)
429     {
430         unsigned int new_size = max(1, wndproc_table.size * 2);
431         struct wined3d_wndproc *new_entries;
432
433         if (!wndproc_table.entries) new_entries = HeapAlloc(GetProcessHeap(), 0, new_size * sizeof(*new_entries));
434         else new_entries = HeapReAlloc(GetProcessHeap(), 0, wndproc_table.entries, new_size * sizeof(*new_entries));
435
436         if (!new_entries)
437         {
438             wined3d_wndproc_mutex_unlock();
439             ERR("Failed to grow table.\n");
440             return FALSE;
441         }
442
443         wndproc_table.entries = new_entries;
444         wndproc_table.size = new_size;
445     }
446
447     entry = &wndproc_table.entries[wndproc_table.count++];
448     entry->window = window;
449     entry->unicode = IsWindowUnicode(window);
450     /* Set a window proc that matches the window. Some applications (e.g. NoX)
451      * replace the window proc after we've set ours, and expect to be able to
452      * call the previous one (ours) directly, without using CallWindowProc(). */
453     if (entry->unicode)
454         entry->proc = (WNDPROC)SetWindowLongPtrW(window, GWLP_WNDPROC, (LONG_PTR)wined3d_wndproc);
455     else
456         entry->proc = (WNDPROC)SetWindowLongPtrA(window, GWLP_WNDPROC, (LONG_PTR)wined3d_wndproc);
457     entry->device = device;
458
459     wined3d_wndproc_mutex_unlock();
460
461     return TRUE;
462 }
463
464 void wined3d_unregister_window(HWND window)
465 {
466     struct wined3d_wndproc *entry, *last;
467     LONG_PTR proc;
468
469     wined3d_wndproc_mutex_lock();
470
471     if (!(entry = wined3d_find_wndproc(window)))
472     {
473         wined3d_wndproc_mutex_unlock();
474         ERR("Window %p is not registered with wined3d.\n", window);
475         return;
476     }
477
478     if (entry->unicode)
479     {
480         proc = GetWindowLongPtrW(window, GWLP_WNDPROC);
481         if (proc != (LONG_PTR)wined3d_wndproc)
482         {
483             entry->device = NULL;
484             wined3d_wndproc_mutex_unlock();
485             WARN("Not unregistering window %p, window proc %#lx doesn't match wined3d window proc %p.\n",
486                     window, proc, wined3d_wndproc);
487             return;
488         }
489
490         SetWindowLongPtrW(window, GWLP_WNDPROC, (LONG_PTR)entry->proc);
491     }
492     else
493     {
494         proc = GetWindowLongPtrA(window, GWLP_WNDPROC);
495         if (proc != (LONG_PTR)wined3d_wndproc)
496         {
497             entry->device = NULL;
498             wined3d_wndproc_mutex_unlock();
499             WARN("Not unregistering window %p, window proc %#lx doesn't match wined3d window proc %p.\n",
500                     window, proc, wined3d_wndproc);
501             return;
502         }
503
504         SetWindowLongPtrA(window, GWLP_WNDPROC, (LONG_PTR)entry->proc);
505     }
506
507     last = &wndproc_table.entries[--wndproc_table.count];
508     if (entry != last) *entry = *last;
509
510     wined3d_wndproc_mutex_unlock();
511 }
512
513 /* At process attach */
514 BOOL WINAPI DllMain(HINSTANCE hInstDLL, DWORD fdwReason, LPVOID lpv)
515 {
516     TRACE("WineD3D DLLMain Reason=%u\n", fdwReason);
517
518     switch (fdwReason)
519     {
520         case DLL_PROCESS_ATTACH:
521             return wined3d_dll_init(hInstDLL);
522
523         case DLL_PROCESS_DETACH:
524             return wined3d_dll_destroy(hInstDLL);
525
526         case DLL_THREAD_DETACH:
527         {
528             if (!context_set_current(NULL))
529             {
530                 ERR("Failed to clear current context.\n");
531             }
532             return TRUE;
533         }
534
535         default:
536             return TRUE;
537     }
538 }