wined3d: Split context_apply_state() into separate functions for each usage.
[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
27 #include "initguid.h"
28 #include "wined3d_private.h"
29
30 WINE_DEFAULT_DEBUG_CHANNEL(d3d);
31
32 struct wined3d_wndproc
33 {
34     HWND window;
35     WNDPROC proc;
36     IWineD3DDeviceImpl *device;
37 };
38
39 struct wined3d_wndproc_table
40 {
41     struct wined3d_wndproc *entries;
42     unsigned int count;
43     unsigned int size;
44 };
45
46 static struct wined3d_wndproc_table wndproc_table;
47
48 int num_lock = 0;
49 void (*CDECL wine_tsx11_lock_ptr)(void) = NULL;
50 void (*CDECL wine_tsx11_unlock_ptr)(void) = NULL;
51
52 static CRITICAL_SECTION wined3d_cs;
53 static CRITICAL_SECTION_DEBUG wined3d_cs_debug =
54 {
55     0, 0, &wined3d_cs,
56     {&wined3d_cs_debug.ProcessLocksList,
57     &wined3d_cs_debug.ProcessLocksList},
58     0, 0, {(DWORD_PTR)(__FILE__ ": wined3d_cs")}
59 };
60 static CRITICAL_SECTION wined3d_cs = {&wined3d_cs_debug, -1, 0, 0, 0, 0};
61
62 /* When updating default value here, make sure to update winecfg as well,
63  * where appropriate. */
64 wined3d_settings_t wined3d_settings =
65 {
66     VS_HW,          /* Hardware by default */
67     PS_HW,          /* Hardware by default */
68     TRUE,           /* Use of GLSL enabled by default */
69     ORM_FBO,        /* Use FBOs to do offscreen rendering */
70     RTL_READTEX,    /* Default render target locking method */
71     PCI_VENDOR_NONE,/* PCI Vendor ID */
72     PCI_DEVICE_NONE,/* PCI Device ID */
73     0,              /* The default of memory is set in FillGLCaps */
74     NULL,           /* No wine logo by default */
75     FALSE,          /* Disable multisampling for now due to Nvidia driver bugs which happens for some users */
76     FALSE,          /* No strict draw ordering. */
77 };
78
79 IWineD3D * WINAPI WineDirect3DCreate(UINT version, IUnknown *parent)
80 {
81     IWineD3DImpl *object;
82     HRESULT hr;
83
84     object = HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, sizeof(*object));
85     if (!object)
86     {
87         ERR("Failed to allocate wined3d object memory.\n");
88         return NULL;
89     }
90
91     hr = wined3d_init(object, version, parent);
92     if (FAILED(hr))
93     {
94         WARN("Failed to initialize wined3d object, hr %#x.\n", hr);
95         HeapFree(GetProcessHeap(), 0, object);
96         return NULL;
97     }
98
99     TRACE("Created wined3d object %p for d3d%d support.\n", object, version);
100
101     return (IWineD3D *)object;
102 }
103
104 static inline DWORD get_config_key(HKEY defkey, HKEY appkey, const char* name, char* buffer, DWORD size)
105 {
106     if (0 != appkey && !RegQueryValueExA( appkey, name, 0, NULL, (LPBYTE) buffer, &size )) return 0;
107     if (0 != defkey && !RegQueryValueExA( defkey, name, 0, NULL, (LPBYTE) buffer, &size )) return 0;
108     return ERROR_FILE_NOT_FOUND;
109 }
110
111 static inline DWORD get_config_key_dword(HKEY defkey, HKEY appkey, const char* name, DWORD *data)
112 {
113     DWORD type;
114     DWORD size = sizeof(DWORD);
115     if (0 != appkey && !RegQueryValueExA( appkey, name, 0, &type, (LPBYTE) data, &size ) && (type == REG_DWORD)) return 0;
116     if (0 != defkey && !RegQueryValueExA( defkey, name, 0, &type, (LPBYTE) data, &size ) && (type == REG_DWORD)) return 0;
117     return ERROR_FILE_NOT_FOUND;
118 }
119
120 static void CDECL wined3d_do_nothing(void)
121 {
122 }
123
124 static BOOL wined3d_dll_init(HINSTANCE hInstDLL)
125 {
126     DWORD wined3d_context_tls_idx;
127     HMODULE mod;
128     char buffer[MAX_PATH+10];
129     DWORD size = sizeof(buffer);
130     HKEY hkey = 0;
131     HKEY appkey = 0;
132     DWORD len, tmpvalue;
133     WNDCLASSA wc;
134
135     wined3d_context_tls_idx = TlsAlloc();
136     if (wined3d_context_tls_idx == TLS_OUT_OF_INDEXES)
137     {
138         DWORD err = GetLastError();
139         ERR("Failed to allocate context TLS index, err %#x.\n", err);
140         return FALSE;
141     }
142     context_set_tls_idx(wined3d_context_tls_idx);
143
144     /* We need our own window class for a fake window which we use to retrieve GL capabilities */
145     /* We might need CS_OWNDC in the future if we notice strange things on Windows.
146      * Various articles/posts about OpenGL problems on Windows recommend this. */
147     wc.style                = CS_HREDRAW | CS_VREDRAW;
148     wc.lpfnWndProc          = DefWindowProcA;
149     wc.cbClsExtra           = 0;
150     wc.cbWndExtra           = 0;
151     wc.hInstance            = hInstDLL;
152     wc.hIcon                = LoadIconA(NULL, (LPCSTR)IDI_WINLOGO);
153     wc.hCursor              = LoadCursorA(NULL, (LPCSTR)IDC_ARROW);
154     wc.hbrBackground        = NULL;
155     wc.lpszMenuName         = NULL;
156     wc.lpszClassName        = WINED3D_OPENGL_WINDOW_CLASS_NAME;
157
158     if (!RegisterClassA(&wc))
159     {
160         ERR("Failed to register window class 'WineD3D_OpenGL'!\n");
161         if (!TlsFree(wined3d_context_tls_idx))
162         {
163             DWORD err = GetLastError();
164             ERR("Failed to free context TLS index, err %#x.\n", err);
165         }
166         return FALSE;
167     }
168
169     DisableThreadLibraryCalls(hInstDLL);
170
171     mod = GetModuleHandleA( "winex11.drv" );
172     if (mod)
173     {
174         wine_tsx11_lock_ptr   = (void *)GetProcAddress( mod, "wine_tsx11_lock" );
175         wine_tsx11_unlock_ptr = (void *)GetProcAddress( mod, "wine_tsx11_unlock" );
176     }
177     else /* We are most likely on Windows */
178     {
179         wine_tsx11_lock_ptr   = wined3d_do_nothing;
180         wine_tsx11_unlock_ptr = wined3d_do_nothing;
181     }
182     /* @@ Wine registry key: HKCU\Software\Wine\Direct3D */
183     if ( RegOpenKeyA( HKEY_CURRENT_USER, "Software\\Wine\\Direct3D", &hkey ) ) hkey = 0;
184
185     len = GetModuleFileNameA( 0, buffer, MAX_PATH );
186     if (len && len < MAX_PATH)
187     {
188         HKEY tmpkey;
189         /* @@ Wine registry key: HKCU\Software\Wine\AppDefaults\app.exe\Direct3D */
190         if (!RegOpenKeyA( HKEY_CURRENT_USER, "Software\\Wine\\AppDefaults", &tmpkey ))
191         {
192             char *p, *appname = buffer;
193             if ((p = strrchr( appname, '/' ))) appname = p + 1;
194             if ((p = strrchr( appname, '\\' ))) appname = p + 1;
195             strcat( appname, "\\Direct3D" );
196             TRACE("appname = [%s]\n", appname);
197             if (RegOpenKeyA( tmpkey, appname, &appkey )) appkey = 0;
198             RegCloseKey( tmpkey );
199         }
200     }
201
202     if ( 0 != hkey || 0 != appkey )
203     {
204         if ( !get_config_key( hkey, appkey, "VertexShaderMode", buffer, size) )
205         {
206             if (!strcmp(buffer,"none"))
207             {
208                 TRACE("Disable vertex shaders\n");
209                 wined3d_settings.vs_mode = VS_NONE;
210             }
211         }
212         if ( !get_config_key( hkey, appkey, "PixelShaderMode", buffer, size) )
213         {
214             if (!strcmp(buffer,"enabled"))
215             {
216                 TRACE("Allow pixel shaders\n");
217                 wined3d_settings.ps_mode = PS_HW;
218             }
219             if (!strcmp(buffer,"disabled"))
220             {
221                 TRACE("Disable pixel shaders\n");
222                 wined3d_settings.ps_mode = PS_NONE;
223             }
224         }
225         if ( !get_config_key( hkey, appkey, "UseGLSL", buffer, size) )
226         {
227             if (!strcmp(buffer,"disabled"))
228             {
229                 TRACE("Use of GL Shading Language disabled\n");
230                 wined3d_settings.glslRequested = FALSE;
231             }
232         }
233         if ( !get_config_key( hkey, appkey, "OffscreenRenderingMode", buffer, size) )
234         {
235             if (!strcmp(buffer,"backbuffer"))
236             {
237                 TRACE("Using the backbuffer for offscreen rendering\n");
238                 wined3d_settings.offscreen_rendering_mode = ORM_BACKBUFFER;
239             }
240             else if (!strcmp(buffer,"fbo"))
241             {
242                 TRACE("Using FBOs for offscreen rendering\n");
243                 wined3d_settings.offscreen_rendering_mode = ORM_FBO;
244             }
245         }
246         if ( !get_config_key( hkey, appkey, "RenderTargetLockMode", buffer, size) )
247         {
248             if (!strcmp(buffer,"disabled"))
249             {
250                 TRACE("Disabling render target locking\n");
251                 wined3d_settings.rendertargetlock_mode = RTL_DISABLE;
252             }
253             else if (!strcmp(buffer,"readdraw"))
254             {
255                 TRACE("Using glReadPixels for render target reading and glDrawPixels for writing\n");
256                 wined3d_settings.rendertargetlock_mode = RTL_READDRAW;
257             }
258             else if (!strcmp(buffer,"readtex"))
259             {
260                 TRACE("Using glReadPixels for render target reading and textures for writing\n");
261                 wined3d_settings.rendertargetlock_mode = RTL_READTEX;
262             }
263         }
264         if ( !get_config_key_dword( hkey, appkey, "VideoPciDeviceID", &tmpvalue) )
265         {
266             int pci_device_id = tmpvalue;
267
268             /* A pci device id is 16-bit */
269             if(pci_device_id > 0xffff)
270             {
271                 ERR("Invalid value for VideoPciDeviceID. The value should be smaller or equal to 65535 or 0xffff\n");
272             }
273             else
274             {
275                 TRACE("Using PCI Device ID %04x\n", pci_device_id);
276                 wined3d_settings.pci_device_id = pci_device_id;
277             }
278         }
279         if ( !get_config_key_dword( hkey, appkey, "VideoPciVendorID", &tmpvalue) )
280         {
281             int pci_vendor_id = tmpvalue;
282
283             /* A pci device id is 16-bit */
284             if(pci_vendor_id > 0xffff)
285             {
286                 ERR("Invalid value for VideoPciVendorID. The value should be smaller or equal to 65535 or 0xffff\n");
287             }
288             else
289             {
290                 TRACE("Using PCI Vendor ID %04x\n", pci_vendor_id);
291                 wined3d_settings.pci_vendor_id = pci_vendor_id;
292             }
293         }
294         if ( !get_config_key( hkey, appkey, "VideoMemorySize", buffer, size) )
295         {
296             int TmpVideoMemorySize = atoi(buffer);
297             if(TmpVideoMemorySize > 0)
298             {
299                 wined3d_settings.emulated_textureram = TmpVideoMemorySize *1024*1024;
300                 TRACE("Use %iMB = %d byte for emulated_textureram\n",
301                         TmpVideoMemorySize,
302                         wined3d_settings.emulated_textureram);
303             }
304             else
305                 ERR("VideoMemorySize is %i but must be >0\n", TmpVideoMemorySize);
306         }
307         if ( !get_config_key( hkey, appkey, "WineLogo", buffer, size) )
308         {
309             size_t len = strlen(buffer) + 1;
310
311             wined3d_settings.logo = HeapAlloc(GetProcessHeap(), 0, len);
312             if (!wined3d_settings.logo) ERR("Failed to allocate logo path memory.\n");
313             else memcpy(wined3d_settings.logo, buffer, len);
314         }
315         if ( !get_config_key( hkey, appkey, "Multisampling", buffer, size) )
316         {
317             if (!strcmp(buffer,"enabled"))
318             {
319                 TRACE("Allow multisampling\n");
320                 wined3d_settings.allow_multisampling = TRUE;
321             }
322         }
323         if (!get_config_key(hkey, appkey, "StrictDrawOrdering", buffer, size)
324                 && !strcmp(buffer,"enabled"))
325         {
326             TRACE("Enforcing strict draw ordering.\n");
327             wined3d_settings.strict_draw_ordering = TRUE;
328         }
329     }
330     if (wined3d_settings.vs_mode == VS_HW)
331         TRACE("Allow HW vertex shaders\n");
332     if (wined3d_settings.ps_mode == PS_NONE)
333         TRACE("Disable pixel shaders\n");
334     if (wined3d_settings.glslRequested)
335         TRACE("If supported by your system, GL Shading Language will be used\n");
336
337     if (appkey) RegCloseKey( appkey );
338     if (hkey) RegCloseKey( hkey );
339
340     return TRUE;
341 }
342
343 static BOOL wined3d_dll_destroy(HINSTANCE hInstDLL)
344 {
345     DWORD wined3d_context_tls_idx = context_get_tls_idx();
346     unsigned int i;
347
348     if (!TlsFree(wined3d_context_tls_idx))
349     {
350         DWORD err = GetLastError();
351         ERR("Failed to free context TLS index, err %#x.\n", err);
352     }
353
354     for (i = 0; i < wndproc_table.count; ++i)
355     {
356         struct wined3d_wndproc *entry = &wndproc_table.entries[i];
357         SetWindowLongPtrW(entry->window, GWLP_WNDPROC, (LONG_PTR)entry->proc);
358     }
359     HeapFree(GetProcessHeap(), 0, wndproc_table.entries);
360
361     HeapFree(GetProcessHeap(), 0, wined3d_settings.logo);
362     UnregisterClassA(WINED3D_OPENGL_WINDOW_CLASS_NAME, hInstDLL);
363
364     return TRUE;
365 }
366
367 void WINAPI wined3d_mutex_lock(void)
368 {
369     EnterCriticalSection(&wined3d_cs);
370 }
371
372 void WINAPI wined3d_mutex_unlock(void)
373 {
374     LeaveCriticalSection(&wined3d_cs);
375 }
376
377 static struct wined3d_wndproc *wined3d_find_wndproc(HWND window)
378 {
379     unsigned int i;
380
381     for (i = 0; i < wndproc_table.count; ++i)
382     {
383         if (wndproc_table.entries[i].window == window)
384         {
385             return &wndproc_table.entries[i];
386         }
387     }
388
389     return NULL;
390 }
391
392 static LRESULT CALLBACK wined3d_wndproc(HWND window, UINT message, WPARAM wparam, LPARAM lparam)
393 {
394     struct wined3d_wndproc *entry;
395     IWineD3DDeviceImpl *device;
396     WNDPROC proc;
397
398     wined3d_mutex_lock();
399     entry = wined3d_find_wndproc(window);
400
401     if (!entry)
402     {
403         wined3d_mutex_unlock();
404         ERR("Window %p is not registered with wined3d.\n", window);
405         return DefWindowProcW(window, message, wparam, lparam);
406     }
407
408     device = entry->device;
409     proc = entry->proc;
410     wined3d_mutex_unlock();
411
412     return device_process_message(device, window, message, wparam, lparam, proc);
413 }
414
415 BOOL wined3d_register_window(HWND window, IWineD3DDeviceImpl *device)
416 {
417     struct wined3d_wndproc *entry;
418
419     wined3d_mutex_lock();
420
421     if (wndproc_table.size == wndproc_table.count)
422     {
423         unsigned int new_size = max(1, wndproc_table.size * 2);
424         struct wined3d_wndproc *new_entries;
425
426         if (!wndproc_table.entries) new_entries = HeapAlloc(GetProcessHeap(), 0, new_size * sizeof(*new_entries));
427         else new_entries = HeapReAlloc(GetProcessHeap(), 0, wndproc_table.entries, new_size * sizeof(*new_entries));
428
429         if (!new_entries)
430         {
431             wined3d_mutex_unlock();
432             ERR("Failed to grow table.\n");
433             return FALSE;
434         }
435
436         wndproc_table.entries = new_entries;
437         wndproc_table.size = new_size;
438     }
439
440     entry = &wndproc_table.entries[wndproc_table.count++];
441     entry->window = window;
442     entry->proc = (WNDPROC)SetWindowLongPtrW(window, GWLP_WNDPROC, (LONG_PTR)wined3d_wndproc);
443     entry->device = device;
444
445     wined3d_mutex_unlock();
446
447     return TRUE;
448 }
449
450 void wined3d_unregister_window(HWND window)
451 {
452     unsigned int i;
453
454     wined3d_mutex_lock();
455     for (i = 0; i < wndproc_table.count; ++i)
456     {
457         if (wndproc_table.entries[i].window == window)
458         {
459             struct wined3d_wndproc *entry = &wndproc_table.entries[i];
460             struct wined3d_wndproc *last = &wndproc_table.entries[--wndproc_table.count];
461
462             if (GetWindowLongPtrW(window, GWLP_WNDPROC) == (LONG_PTR)wined3d_wndproc)
463                 SetWindowLongPtrW(window, GWLP_WNDPROC, (LONG_PTR)entry->proc);
464             if (entry != last) *entry = *last;
465             wined3d_mutex_unlock();
466
467             return;
468         }
469     }
470     wined3d_mutex_unlock();
471
472     ERR("Window %p is not registered with wined3d.\n", window);
473 }
474
475 /* At process attach */
476 BOOL WINAPI DllMain(HINSTANCE hInstDLL, DWORD fdwReason, LPVOID lpv)
477 {
478     TRACE("WineD3D DLLMain Reason=%u\n", fdwReason);
479
480     switch (fdwReason)
481     {
482         case DLL_PROCESS_ATTACH:
483             return wined3d_dll_init(hInstDLL);
484
485         case DLL_PROCESS_DETACH:
486             return wined3d_dll_destroy(hInstDLL);
487
488         case DLL_THREAD_DETACH:
489         {
490             if (!context_set_current(NULL))
491             {
492                 ERR("Failed to clear current context.\n");
493             }
494             return TRUE;
495         }
496
497         default:
498             return TRUE;
499     }
500 }