wined3d: Add UnregisterClass() on DLL_PROCESS_DETACH.
[wine] / dlls / wined3d / context.c
1 /*
2  * Context and render target management in wined3d
3  *
4  * Copyright 2007-2008 Stefan Dösinger for CodeWeavers
5  *
6  * This library is free software; you can redistribute it and/or
7  * modify it under the terms of the GNU Lesser General Public
8  * License as published by the Free Software Foundation; either
9  * version 2.1 of the License, or (at your option) any later version.
10  *
11  * This library is distributed in the hope that it will be useful,
12  * but WITHOUT ANY WARRANTY; without even the implied warranty of
13  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
14  * Lesser General Public License for more details.
15  *
16  * You should have received a copy of the GNU Lesser General Public
17  * License along with this library; if not, write to the Free Software
18  * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA
19  */
20
21 #include "config.h"
22 #include <stdio.h>
23 #ifdef HAVE_FLOAT_H
24 # include <float.h>
25 #endif
26 #include "wined3d_private.h"
27
28 WINE_DEFAULT_DEBUG_CHANNEL(d3d);
29
30 #define GLINFO_LOCATION This->adapter->gl_info
31
32 /* The last used device.
33  *
34  * If the application creates multiple devices and switches between them, ActivateContext has to
35  * change the opengl context. This flag allows to keep track which device is active
36  */
37 static IWineD3DDeviceImpl *last_device;
38
39 /* FBO helper functions */
40
41 void context_bind_fbo(IWineD3DDevice *iface, GLenum target, GLuint *fbo)
42 {
43     const IWineD3DDeviceImpl *This = (IWineD3DDeviceImpl *)iface;
44
45     if (!*fbo)
46     {
47         GL_EXTCALL(glGenFramebuffersEXT(1, fbo));
48         checkGLcall("glGenFramebuffersEXT()");
49         TRACE("Created FBO %d\n", *fbo);
50     }
51
52     GL_EXTCALL(glBindFramebufferEXT(target, *fbo));
53     checkGLcall("glBindFramebuffer()");
54 }
55
56 static void context_clean_fbo_attachments(IWineD3DDeviceImpl *This)
57 {
58     unsigned int i;
59
60     for (i = 0; i < GL_LIMITS(buffers); ++i)
61     {
62         GL_EXTCALL(glFramebufferTexture2DEXT(GL_FRAMEBUFFER_EXT, GL_COLOR_ATTACHMENT0_EXT + i, GL_TEXTURE_2D, 0, 0));
63         checkGLcall("glFramebufferTexture2D()");
64     }
65     GL_EXTCALL(glFramebufferTexture2DEXT(GL_FRAMEBUFFER_EXT, GL_DEPTH_ATTACHMENT_EXT, GL_TEXTURE_2D, 0, 0));
66     checkGLcall("glFramebufferTexture2D()");
67 }
68
69 static void context_destroy_fbo(IWineD3DDeviceImpl *This, const GLuint *fbo)
70 {
71     GL_EXTCALL(glBindFramebufferEXT(GL_FRAMEBUFFER_EXT, *fbo));
72     checkGLcall("glBindFramebuffer()");
73
74     context_clean_fbo_attachments(This);
75
76     GL_EXTCALL(glBindFramebufferEXT(GL_FRAMEBUFFER_EXT, 0));
77     checkGLcall("glBindFramebuffer()");
78     GL_EXTCALL(glDeleteFramebuffersEXT(1, fbo));
79     checkGLcall("glDeleteFramebuffers()");
80 }
81
82 static void context_apply_attachment_filter_states(IWineD3DDevice *iface, IWineD3DSurface *surface, BOOL force_preload)
83 {
84     IWineD3DDeviceImpl *This = (IWineD3DDeviceImpl *)iface;
85     const IWineD3DSurfaceImpl *surface_impl = (IWineD3DSurfaceImpl *)surface;
86     IWineD3DBaseTextureImpl *texture_impl;
87     BOOL update_minfilter = FALSE;
88     BOOL update_magfilter = FALSE;
89
90     /* Update base texture states array */
91     if (SUCCEEDED(IWineD3DSurface_GetContainer(surface, &IID_IWineD3DBaseTexture, (void **)&texture_impl)))
92     {
93         if (texture_impl->baseTexture.states[WINED3DTEXSTA_MINFILTER] != WINED3DTEXF_POINT
94             || texture_impl->baseTexture.states[WINED3DTEXSTA_MIPFILTER] != WINED3DTEXF_NONE)
95         {
96             texture_impl->baseTexture.states[WINED3DTEXSTA_MINFILTER] = WINED3DTEXF_POINT;
97             texture_impl->baseTexture.states[WINED3DTEXSTA_MIPFILTER] = WINED3DTEXF_NONE;
98             update_minfilter = TRUE;
99         }
100
101         if (texture_impl->baseTexture.states[WINED3DTEXSTA_MAGFILTER] != WINED3DTEXF_POINT)
102         {
103             texture_impl->baseTexture.states[WINED3DTEXSTA_MAGFILTER] = WINED3DTEXF_POINT;
104             update_magfilter = TRUE;
105         }
106
107         if (texture_impl->baseTexture.bindCount)
108         {
109             WARN("Render targets should not be bound to a sampler\n");
110             IWineD3DDeviceImpl_MarkStateDirty(This, STATE_SAMPLER(texture_impl->baseTexture.sampler));
111         }
112
113         IWineD3DBaseTexture_Release((IWineD3DBaseTexture *)texture_impl);
114     }
115
116     if (update_minfilter || update_magfilter || force_preload)
117     {
118         GLenum target, bind_target;
119         GLint old_binding;
120
121         target = surface_impl->glDescription.target;
122         if (target == GL_TEXTURE_2D)
123         {
124             bind_target = GL_TEXTURE_2D;
125             glGetIntegerv(GL_TEXTURE_BINDING_2D, &old_binding);
126         } else if (target == GL_TEXTURE_RECTANGLE_ARB) {
127             bind_target = GL_TEXTURE_RECTANGLE_ARB;
128             glGetIntegerv(GL_TEXTURE_BINDING_RECTANGLE_ARB, &old_binding);
129         } else {
130             bind_target = GL_TEXTURE_CUBE_MAP_ARB;
131             glGetIntegerv(GL_TEXTURE_BINDING_CUBE_MAP_ARB, &old_binding);
132         }
133
134         surface_internal_preload(surface, SRGB_RGB);
135
136         glBindTexture(bind_target, surface_impl->glDescription.textureName);
137         if (update_minfilter) glTexParameteri(bind_target, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
138         if (update_magfilter) glTexParameteri(bind_target, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
139         glBindTexture(bind_target, old_binding);
140     }
141
142     checkGLcall("apply_attachment_filter_states()");
143 }
144
145 /* TODO: Handle stencil attachments */
146 void context_attach_depth_stencil_fbo(IWineD3DDeviceImpl *This, GLenum fbo_target, IWineD3DSurface *depth_stencil, BOOL use_render_buffer)
147 {
148     IWineD3DSurfaceImpl *depth_stencil_impl = (IWineD3DSurfaceImpl *)depth_stencil;
149
150     TRACE("Attach depth stencil %p\n", depth_stencil);
151
152     if (depth_stencil)
153     {
154         if (use_render_buffer && depth_stencil_impl->current_renderbuffer)
155         {
156             GL_EXTCALL(glFramebufferRenderbufferEXT(fbo_target, GL_DEPTH_ATTACHMENT_EXT, GL_RENDERBUFFER_EXT, depth_stencil_impl->current_renderbuffer->id));
157             checkGLcall("glFramebufferRenderbufferEXT()");
158         } else {
159             context_apply_attachment_filter_states((IWineD3DDevice *)This, depth_stencil, TRUE);
160
161             GL_EXTCALL(glFramebufferTexture2DEXT(fbo_target, GL_DEPTH_ATTACHMENT_EXT, depth_stencil_impl->glDescription.target,
162                         depth_stencil_impl->glDescription.textureName, depth_stencil_impl->glDescription.level));
163             checkGLcall("glFramebufferTexture2DEXT()");
164         }
165     } else {
166         GL_EXTCALL(glFramebufferTexture2DEXT(fbo_target, GL_DEPTH_ATTACHMENT_EXT, GL_TEXTURE_2D, 0, 0));
167         checkGLcall("glFramebufferTexture2DEXT()");
168     }
169 }
170
171 void context_attach_surface_fbo(IWineD3DDeviceImpl *This, GLenum fbo_target, DWORD idx, IWineD3DSurface *surface)
172 {
173     const IWineD3DSurfaceImpl *surface_impl = (IWineD3DSurfaceImpl *)surface;
174
175     TRACE("Attach surface %p to %u\n", surface, idx);
176
177     if (surface)
178     {
179         context_apply_attachment_filter_states((IWineD3DDevice *)This, surface, TRUE);
180
181         GL_EXTCALL(glFramebufferTexture2DEXT(fbo_target, GL_COLOR_ATTACHMENT0_EXT + idx, surface_impl->glDescription.target,
182                 surface_impl->glDescription.textureName, surface_impl->glDescription.level));
183         checkGLcall("glFramebufferTexture2DEXT()");
184     } else {
185         GL_EXTCALL(glFramebufferTexture2DEXT(fbo_target, GL_COLOR_ATTACHMENT0_EXT + idx, GL_TEXTURE_2D, 0, 0));
186         checkGLcall("glFramebufferTexture2DEXT()");
187     }
188 }
189
190 static void context_check_fbo_status(IWineD3DDevice *iface)
191 {
192     IWineD3DDeviceImpl *This = (IWineD3DDeviceImpl *)iface;
193     GLenum status;
194
195     status = GL_EXTCALL(glCheckFramebufferStatusEXT(GL_FRAMEBUFFER_EXT));
196     if (status == GL_FRAMEBUFFER_COMPLETE_EXT)
197     {
198         TRACE("FBO complete\n");
199     } else {
200         IWineD3DSurfaceImpl *attachment;
201         unsigned int i;
202         FIXME("FBO status %s (%#x)\n", debug_fbostatus(status), status);
203
204         /* Dump the FBO attachments */
205         for (i = 0; i < GL_LIMITS(buffers); ++i)
206         {
207             attachment = (IWineD3DSurfaceImpl *)This->activeContext->current_fbo->render_targets[i];
208             if (attachment)
209             {
210                 FIXME("\tColor attachment %d: (%p) %s %ux%u\n",
211                         i, attachment, debug_d3dformat(attachment->resource.format_desc->format),
212                         attachment->pow2Width, attachment->pow2Height);
213             }
214         }
215         attachment = (IWineD3DSurfaceImpl *)This->activeContext->current_fbo->depth_stencil;
216         if (attachment)
217         {
218             FIXME("\tDepth attachment: (%p) %s %ux%u\n",
219                     attachment, debug_d3dformat(attachment->resource.format_desc->format),
220                     attachment->pow2Width, attachment->pow2Height);
221         }
222     }
223 }
224
225 static struct fbo_entry *context_create_fbo_entry(IWineD3DDevice *iface)
226 {
227     IWineD3DDeviceImpl *This = (IWineD3DDeviceImpl *)iface;
228     struct fbo_entry *entry;
229
230     entry = HeapAlloc(GetProcessHeap(), 0, sizeof(*entry));
231     entry->render_targets = HeapAlloc(GetProcessHeap(), 0, GL_LIMITS(buffers) * sizeof(*entry->render_targets));
232     memcpy(entry->render_targets, This->render_targets, GL_LIMITS(buffers) * sizeof(*entry->render_targets));
233     entry->depth_stencil = This->stencilBufferTarget;
234     entry->attached = FALSE;
235     entry->id = 0;
236
237     return entry;
238 }
239
240 static void context_reuse_fbo_entry(IWineD3DDevice *iface, struct fbo_entry *entry)
241 {
242     IWineD3DDeviceImpl *This = (IWineD3DDeviceImpl *)iface;
243
244     GL_EXTCALL(glBindFramebufferEXT(GL_FRAMEBUFFER_EXT, entry->id));
245     checkGLcall("glBindFramebuffer()");
246     context_clean_fbo_attachments(This);
247
248     memcpy(entry->render_targets, This->render_targets, GL_LIMITS(buffers) * sizeof(*entry->render_targets));
249     entry->depth_stencil = This->stencilBufferTarget;
250     entry->attached = FALSE;
251 }
252
253 static void context_destroy_fbo_entry(IWineD3DDeviceImpl *This, struct fbo_entry *entry)
254 {
255     if (entry->id)
256     {
257         TRACE("Destroy FBO %d\n", entry->id);
258         context_destroy_fbo(This, &entry->id);
259     }
260     list_remove(&entry->entry);
261     HeapFree(GetProcessHeap(), 0, entry->render_targets);
262     HeapFree(GetProcessHeap(), 0, entry);
263 }
264
265
266 static struct fbo_entry *context_find_fbo_entry(IWineD3DDevice *iface, WineD3DContext *context)
267 {
268     IWineD3DDeviceImpl *This = (IWineD3DDeviceImpl *)iface;
269     struct fbo_entry *entry;
270
271     LIST_FOR_EACH_ENTRY(entry, &context->fbo_list, struct fbo_entry, entry)
272     {
273         if (!memcmp(entry->render_targets, This->render_targets, GL_LIMITS(buffers) * sizeof(*entry->render_targets))
274                 && entry->depth_stencil == This->stencilBufferTarget)
275         {
276             list_remove(&entry->entry);
277             list_add_head(&context->fbo_list, &entry->entry);
278             return entry;
279         }
280     }
281
282     if (context->fbo_entry_count < WINED3D_MAX_FBO_ENTRIES)
283     {
284         entry = context_create_fbo_entry(iface);
285         list_add_head(&context->fbo_list, &entry->entry);
286         ++context->fbo_entry_count;
287     }
288     else
289     {
290         entry = LIST_ENTRY(list_tail(&context->fbo_list), struct fbo_entry, entry);
291         context_reuse_fbo_entry(iface, entry);
292         list_remove(&entry->entry);
293         list_add_head(&context->fbo_list, &entry->entry);
294     }
295
296     return entry;
297 }
298
299 static void context_apply_fbo_entry(IWineD3DDevice *iface, struct fbo_entry *entry)
300 {
301     IWineD3DDeviceImpl *This = (IWineD3DDeviceImpl *)iface;
302     unsigned int i;
303
304     context_bind_fbo(iface, GL_FRAMEBUFFER_EXT, &entry->id);
305
306     if (!entry->attached)
307     {
308         /* Apply render targets */
309         for (i = 0; i < GL_LIMITS(buffers); ++i)
310         {
311             IWineD3DSurface *render_target = This->render_targets[i];
312             context_attach_surface_fbo(This, GL_FRAMEBUFFER_EXT, i, render_target);
313         }
314
315         /* Apply depth targets */
316         if (This->stencilBufferTarget) {
317             unsigned int w = ((IWineD3DSurfaceImpl *)This->render_targets[0])->pow2Width;
318             unsigned int h = ((IWineD3DSurfaceImpl *)This->render_targets[0])->pow2Height;
319
320             surface_set_compatible_renderbuffer(This->stencilBufferTarget, w, h);
321         }
322         context_attach_depth_stencil_fbo(This, GL_FRAMEBUFFER_EXT, This->stencilBufferTarget, TRUE);
323
324         entry->attached = TRUE;
325     } else {
326         for (i = 0; i < GL_LIMITS(buffers); ++i)
327         {
328             if (This->render_targets[i])
329                 context_apply_attachment_filter_states(iface, This->render_targets[i], FALSE);
330         }
331         if (This->stencilBufferTarget)
332             context_apply_attachment_filter_states(iface, This->stencilBufferTarget, FALSE);
333     }
334
335     for (i = 0; i < GL_LIMITS(buffers); ++i)
336     {
337         if (This->render_targets[i])
338             This->draw_buffers[i] = GL_COLOR_ATTACHMENT0_EXT + i;
339         else
340             This->draw_buffers[i] = GL_NONE;
341     }
342 }
343
344 static void context_apply_fbo_state(IWineD3DDevice *iface)
345 {
346     IWineD3DDeviceImpl *This = (IWineD3DDeviceImpl *)iface;
347     WineD3DContext *context = This->activeContext;
348
349     if (This->render_offscreen)
350     {
351         context->current_fbo = context_find_fbo_entry(iface, context);
352         context_apply_fbo_entry(iface, context->current_fbo);
353     } else {
354         context->current_fbo = NULL;
355         GL_EXTCALL(glBindFramebufferEXT(GL_FRAMEBUFFER_EXT, 0));
356     }
357
358     context_check_fbo_status(iface);
359 }
360
361 void context_resource_released(IWineD3DDevice *iface, IWineD3DResource *resource, WINED3DRESOURCETYPE type)
362 {
363     IWineD3DDeviceImpl *This = (IWineD3DDeviceImpl *)iface;
364     UINT i;
365
366     switch(type)
367     {
368         case WINED3DRTYPE_SURFACE:
369         {
370             for (i = 0; i < This->numContexts; ++i)
371             {
372                 struct fbo_entry *entry, *entry2;
373
374                 LIST_FOR_EACH_ENTRY_SAFE(entry, entry2, &This->contexts[i]->fbo_list, struct fbo_entry, entry)
375                 {
376                     BOOL destroyed = FALSE;
377                     UINT j;
378
379                     for (j = 0; !destroyed && j < GL_LIMITS(buffers); ++j)
380                     {
381                         if (entry->render_targets[j] == (IWineD3DSurface *)resource)
382                         {
383                             context_destroy_fbo_entry(This, entry);
384                             destroyed = TRUE;
385                         }
386                     }
387
388                     if (!destroyed && entry->depth_stencil == (IWineD3DSurface *)resource)
389                         context_destroy_fbo_entry(This, entry);
390                 }
391             }
392
393             break;
394         }
395
396         default:
397             break;
398     }
399 }
400
401 /*****************************************************************************
402  * Context_MarkStateDirty
403  *
404  * Marks a state in a context dirty. Only one context, opposed to
405  * IWineD3DDeviceImpl_MarkStateDirty, which marks the state dirty in all
406  * contexts
407  *
408  * Params:
409  *  context: Context to mark the state dirty in
410  *  state: State to mark dirty
411  *  StateTable: Pointer to the state table in use(for state grouping)
412  *
413  *****************************************************************************/
414 static void Context_MarkStateDirty(WineD3DContext *context, DWORD state, const struct StateEntry *StateTable) {
415     DWORD rep = StateTable[state].representative;
416     DWORD idx;
417     BYTE shift;
418
419     if(!rep || isStateDirty(context, rep)) return;
420
421     context->dirtyArray[context->numDirtyEntries++] = rep;
422     idx = rep >> 5;
423     shift = rep & 0x1f;
424     context->isStateDirty[idx] |= (1 << shift);
425 }
426
427 /*****************************************************************************
428  * AddContextToArray
429  *
430  * Adds a context to the context array. Helper function for CreateContext
431  *
432  * This method is not called in performance-critical code paths, only when a
433  * new render target or swapchain is created. Thus performance is not an issue
434  * here.
435  *
436  * Params:
437  *  This: Device to add the context for
438  *  hdc: device context
439  *  glCtx: WGL context to add
440  *  pbuffer: optional pbuffer used with this context
441  *
442  *****************************************************************************/
443 static WineD3DContext *AddContextToArray(IWineD3DDeviceImpl *This, HWND win_handle, HDC hdc, HGLRC glCtx, HPBUFFERARB pbuffer) {
444     WineD3DContext **oldArray = This->contexts;
445     DWORD state;
446
447     This->contexts = HeapAlloc(GetProcessHeap(), 0, sizeof(*This->contexts) * (This->numContexts + 1));
448     if(This->contexts == NULL) {
449         ERR("Unable to grow the context array\n");
450         This->contexts = oldArray;
451         return NULL;
452     }
453     if(oldArray) {
454         memcpy(This->contexts, oldArray, sizeof(*This->contexts) * This->numContexts);
455     }
456
457     This->contexts[This->numContexts] = HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, sizeof(WineD3DContext));
458     if(This->contexts[This->numContexts] == NULL) {
459         ERR("Unable to allocate a new context\n");
460         HeapFree(GetProcessHeap(), 0, This->contexts);
461         This->contexts = oldArray;
462         return NULL;
463     }
464
465     This->contexts[This->numContexts]->hdc = hdc;
466     This->contexts[This->numContexts]->glCtx = glCtx;
467     This->contexts[This->numContexts]->pbuffer = pbuffer;
468     This->contexts[This->numContexts]->win_handle = win_handle;
469     HeapFree(GetProcessHeap(), 0, oldArray);
470
471     /* Mark all states dirty to force a proper initialization of the states on the first use of the context
472      */
473     for(state = 0; state <= STATE_HIGHEST; state++) {
474         Context_MarkStateDirty(This->contexts[This->numContexts], state, This->StateTable);
475     }
476
477     This->numContexts++;
478     TRACE("Created context %p\n", This->contexts[This->numContexts - 1]);
479     return This->contexts[This->numContexts - 1];
480 }
481
482 /* This function takes care of WineD3D pixel format selection. */
483 static int WineD3D_ChoosePixelFormat(IWineD3DDeviceImpl *This, HDC hdc,
484         const struct GlPixelFormatDesc *color_format_desc, const struct GlPixelFormatDesc *ds_format_desc,
485         BOOL auxBuffers, int numSamples, BOOL pbuffer, BOOL findCompatible)
486 {
487     int iPixelFormat=0;
488     unsigned int matchtry;
489     short redBits, greenBits, blueBits, alphaBits, colorBits;
490     short depthBits=0, stencilBits=0;
491
492     struct match_type {
493         BOOL require_aux;
494         BOOL exact_alpha;
495         BOOL exact_color;
496     } matches[] = {
497         /* First, try without alpha match buffers. MacOS supports aux buffers only
498          * on A8R8G8B8, and we prefer better offscreen rendering over an alpha match.
499          * Then try without aux buffers - this is the most common cause for not
500          * finding a pixel format. Also some drivers(the open source ones)
501          * only offer 32 bit ARB pixel formats. First try without an exact alpha
502          * match, then try without an exact alpha and color match.
503          */
504         { TRUE,  TRUE,  TRUE  },
505         { TRUE,  FALSE, TRUE  },
506         { FALSE, TRUE,  TRUE  },
507         { FALSE, FALSE, TRUE  },
508         { TRUE,  FALSE, FALSE },
509         { FALSE, FALSE, FALSE },
510     };
511
512     int i = 0;
513     int nCfgs = This->adapter->nCfgs;
514
515     TRACE("ColorFormat=%s, DepthStencilFormat=%s, auxBuffers=%d, numSamples=%d, pbuffer=%d, findCompatible=%d\n",
516           debug_d3dformat(color_format_desc->format), debug_d3dformat(ds_format_desc->format),
517           auxBuffers, numSamples, pbuffer, findCompatible);
518
519     if (!getColorBits(color_format_desc, &redBits, &greenBits, &blueBits, &alphaBits, &colorBits))
520     {
521         ERR("Unable to get color bits for format %s (%#x)!\n",
522                 debug_d3dformat(color_format_desc->format), color_format_desc->format);
523         return 0;
524     }
525
526     /* In WGL both color, depth and stencil are features of a pixel format. In case of D3D they are separate.
527      * You are able to add a depth + stencil surface at a later stage when you need it.
528      * In order to support this properly in WineD3D we need the ability to recreate the opengl context and
529      * drawable when this is required. This is very tricky as we need to reapply ALL opengl states for the new
530      * context, need torecreate shaders, textures and other resources.
531      *
532      * The context manager already takes care of the state problem and for the other tasks code from Reset
533      * can be used. These changes are way to risky during the 1.0 code freeze which is taking place right now.
534      * Likely a lot of other new bugs will be exposed. For that reason request a depth stencil surface all the
535      * time. It can cause a slight performance hit but fixes a lot of regressions. A fixme reminds of that this
536      * issue needs to be fixed. */
537     if (ds_format_desc->format != WINED3DFMT_D24S8)
538     {
539         FIXME("Add OpenGL context recreation support to SetDepthStencilSurface\n");
540         ds_format_desc = getFormatDescEntry(WINED3DFMT_D24S8, &This->adapter->gl_info);
541     }
542
543     getDepthStencilBits(ds_format_desc, &depthBits, &stencilBits);
544
545     for(matchtry = 0; matchtry < (sizeof(matches) / sizeof(matches[0])) && !iPixelFormat; matchtry++) {
546         for(i=0; i<nCfgs; i++) {
547             BOOL exactDepthMatch = TRUE;
548             WineD3D_PixelFormat *cfg = &This->adapter->cfgs[i];
549
550             /* For now only accept RGBA formats. Perhaps some day we will
551              * allow floating point formats for pbuffers. */
552             if(cfg->iPixelType != WGL_TYPE_RGBA_ARB)
553                 continue;
554
555             /* In window mode (!pbuffer) we need a window drawable format and double buffering. */
556             if(!pbuffer && !(cfg->windowDrawable && cfg->doubleBuffer))
557                 continue;
558
559             /* We like to have aux buffers in backbuffer mode */
560             if(auxBuffers && !cfg->auxBuffers && matches[matchtry].require_aux)
561                 continue;
562
563             /* In pbuffer-mode we need a pbuffer-capable format but we don't want double buffering */
564             if(pbuffer && (!cfg->pbufferDrawable || cfg->doubleBuffer))
565                 continue;
566
567             if(matches[matchtry].exact_color) {
568                 if(cfg->redSize != redBits)
569                     continue;
570                 if(cfg->greenSize != greenBits)
571                     continue;
572                 if(cfg->blueSize != blueBits)
573                     continue;
574             } else {
575                 if(cfg->redSize < redBits)
576                     continue;
577                 if(cfg->greenSize < greenBits)
578                     continue;
579                 if(cfg->blueSize < blueBits)
580                     continue;
581             }
582             if(matches[matchtry].exact_alpha) {
583                 if(cfg->alphaSize != alphaBits)
584                     continue;
585             } else {
586                 if(cfg->alphaSize < alphaBits)
587                     continue;
588             }
589
590             /* We try to locate a format which matches our requirements exactly. In case of
591              * depth it is no problem to emulate 16-bit using e.g. 24-bit, so accept that. */
592             if(cfg->depthSize < depthBits)
593                 continue;
594             else if(cfg->depthSize > depthBits)
595                 exactDepthMatch = FALSE;
596
597             /* In all cases make sure the number of stencil bits matches our requirements
598              * even when we don't need stencil because it could affect performance EXCEPT
599              * on cards which don't offer depth formats without stencil like the i915 drivers
600              * on Linux. */
601             if(stencilBits != cfg->stencilSize && !(This->adapter->brokenStencil && stencilBits <= cfg->stencilSize))
602                 continue;
603
604             /* Check multisampling support */
605             if(cfg->numSamples != numSamples)
606                 continue;
607
608             /* When we have passed all the checks then we have found a format which matches our
609              * requirements. Note that we only check for a limit number of capabilities right now,
610              * so there can easily be a dozen of pixel formats which appear to be the 'same' but
611              * can still differ in things like multisampling, stereo, SRGB and other flags.
612              */
613
614             /* Exit the loop as we have found a format :) */
615             if(exactDepthMatch) {
616                 iPixelFormat = cfg->iPixelFormat;
617                 break;
618             } else if(!iPixelFormat) {
619                 /* In the end we might end up with a format which doesn't exactly match our depth
620                  * requirements. Accept the first format we found because formats with higher iPixelFormat
621                  * values tend to have more extended capabilities (e.g. multisampling) which we don't need. */
622                 iPixelFormat = cfg->iPixelFormat;
623             }
624         }
625     }
626
627     /* When findCompatible is set and no suitable format was found, let ChoosePixelFormat choose a pixel format in order not to crash. */
628     if(!iPixelFormat && !findCompatible) {
629         ERR("Can't find a suitable iPixelFormat\n");
630         return FALSE;
631     } else if(!iPixelFormat) {
632         PIXELFORMATDESCRIPTOR pfd;
633
634         TRACE("Falling back to ChoosePixelFormat as we weren't able to find an exactly matching pixel format\n");
635         /* PixelFormat selection */
636         ZeroMemory(&pfd, sizeof(pfd));
637         pfd.nSize      = sizeof(pfd);
638         pfd.nVersion   = 1;
639         pfd.dwFlags    = PFD_SUPPORT_OPENGL | PFD_DOUBLEBUFFER | PFD_DRAW_TO_WINDOW;/*PFD_GENERIC_ACCELERATED*/
640         pfd.iPixelType = PFD_TYPE_RGBA;
641         pfd.cAlphaBits = alphaBits;
642         pfd.cColorBits = colorBits;
643         pfd.cDepthBits = depthBits;
644         pfd.cStencilBits = stencilBits;
645         pfd.iLayerType = PFD_MAIN_PLANE;
646
647         iPixelFormat = ChoosePixelFormat(hdc, &pfd);
648         if(!iPixelFormat) {
649             /* If this happens something is very wrong as ChoosePixelFormat barely fails */
650             ERR("Can't find a suitable iPixelFormat\n");
651             return FALSE;
652         }
653     }
654
655     TRACE("Found iPixelFormat=%d for ColorFormat=%s, DepthStencilFormat=%s\n",
656             iPixelFormat, debug_d3dformat(color_format_desc->format), debug_d3dformat(ds_format_desc->format));
657     return iPixelFormat;
658 }
659
660 /*****************************************************************************
661  * CreateContext
662  *
663  * Creates a new context for a window, or a pbuffer context.
664  *
665  * * Params:
666  *  This: Device to activate the context for
667  *  target: Surface this context will render to
668  *  win_handle: handle to the window which we are drawing to
669  *  create_pbuffer: tells whether to create a pbuffer or not
670  *  pPresentParameters: contains the pixelformats to use for onscreen rendering
671  *
672  *****************************************************************************/
673 WineD3DContext *CreateContext(IWineD3DDeviceImpl *This, IWineD3DSurfaceImpl *target, HWND win_handle, BOOL create_pbuffer, const WINED3DPRESENT_PARAMETERS *pPresentParms) {
674     HDC oldDrawable, hdc;
675     HPBUFFERARB pbuffer = NULL;
676     HGLRC ctx = NULL, oldCtx;
677     WineD3DContext *ret = NULL;
678     unsigned int s;
679
680     TRACE("(%p): Creating a %s context for render target %p\n", This, create_pbuffer ? "offscreen" : "onscreen", target);
681
682     if(create_pbuffer) {
683         HDC hdc_parent = GetDC(win_handle);
684         int iPixelFormat = 0;
685
686         IWineD3DSurface *StencilSurface = This->stencilBufferTarget;
687         const struct GlPixelFormatDesc *ds_format_desc = StencilSurface
688                 ? ((IWineD3DSurfaceImpl *)StencilSurface)->resource.format_desc
689                 : getFormatDescEntry(WINED3DFMT_UNKNOWN, &This->adapter->gl_info);
690
691         /* Try to find a pixel format with pbuffer support. */
692         iPixelFormat = WineD3D_ChoosePixelFormat(This, hdc_parent, target->resource.format_desc,
693                 ds_format_desc, FALSE /* auxBuffers */, 0 /* numSamples */, TRUE /* PBUFFER */,
694                 FALSE /* findCompatible */);
695         if(!iPixelFormat) {
696             TRACE("Trying to locate a compatible pixel format because an exact match failed.\n");
697
698             /* For some reason we weren't able to find a format, try to find something instead of crashing.
699              * A reason for failure could have been wglChoosePixelFormatARB strictness. */
700             iPixelFormat = WineD3D_ChoosePixelFormat(This, hdc_parent, target->resource.format_desc,
701                     ds_format_desc, FALSE /* auxBuffer */, 0 /* numSamples */, TRUE /* PBUFFER */,
702                     TRUE /* findCompatible */);
703         }
704
705         /* This shouldn't happen as ChoosePixelFormat always returns something */
706         if(!iPixelFormat) {
707             ERR("Unable to locate a pixel format for a pbuffer\n");
708             ReleaseDC(win_handle, hdc_parent);
709             goto out;
710         }
711
712         TRACE("Creating a pBuffer drawable for the new context\n");
713         pbuffer = GL_EXTCALL(wglCreatePbufferARB(hdc_parent, iPixelFormat, target->currentDesc.Width, target->currentDesc.Height, 0));
714         if(!pbuffer) {
715             ERR("Cannot create a pbuffer\n");
716             ReleaseDC(win_handle, hdc_parent);
717             goto out;
718         }
719
720         /* In WGL a pbuffer is 'wrapped' inside a HDC to 'fool' wglMakeCurrent */
721         hdc = GL_EXTCALL(wglGetPbufferDCARB(pbuffer));
722         if(!hdc) {
723             ERR("Cannot get a HDC for pbuffer (%p)\n", pbuffer);
724             GL_EXTCALL(wglDestroyPbufferARB(pbuffer));
725             ReleaseDC(win_handle, hdc_parent);
726             goto out;
727         }
728         ReleaseDC(win_handle, hdc_parent);
729     } else {
730         PIXELFORMATDESCRIPTOR pfd;
731         int iPixelFormat;
732         int res;
733         const struct GlPixelFormatDesc *color_format_desc = target->resource.format_desc;
734         const struct GlPixelFormatDesc *ds_format_desc = getFormatDescEntry(WINED3DFMT_UNKNOWN,
735                 &This->adapter->gl_info);
736         BOOL auxBuffers = FALSE;
737         int numSamples = 0;
738
739         hdc = GetDC(win_handle);
740         if(hdc == NULL) {
741             ERR("Cannot retrieve a device context!\n");
742             goto out;
743         }
744
745         /* In case of ORM_BACKBUFFER, make sure to request an alpha component for X4R4G4B4/X8R8G8B8 as we might need it for the backbuffer. */
746         if(wined3d_settings.offscreen_rendering_mode == ORM_BACKBUFFER) {
747             auxBuffers = TRUE;
748
749             if (color_format_desc->format == WINED3DFMT_X4R4G4B4)
750                 color_format_desc = getFormatDescEntry(WINED3DFMT_A4R4G4B4, &This->adapter->gl_info);
751             else if (color_format_desc->format == WINED3DFMT_X8R8G8B8)
752                 color_format_desc = getFormatDescEntry(WINED3DFMT_A8R8G8B8, &This->adapter->gl_info);
753         }
754
755         /* DirectDraw supports 8bit paletted render targets and these are used by old games like Starcraft and C&C.
756          * Most modern hardware doesn't support 8bit natively so we perform some form of 8bit -> 32bit conversion.
757          * The conversion (ab)uses the alpha component for storing the palette index. For this reason we require
758          * a format with 8bit alpha, so request A8R8G8B8. */
759         if (color_format_desc->format == WINED3DFMT_P8)
760             color_format_desc = getFormatDescEntry(WINED3DFMT_A8R8G8B8, &This->adapter->gl_info);
761
762         /* Retrieve the depth stencil format from the present parameters.
763          * The choice of the proper format can give a nice performance boost
764          * in case of GPU limited programs. */
765         if(pPresentParms->EnableAutoDepthStencil) {
766             TRACE("pPresentParms->EnableAutoDepthStencil=enabled; using AutoDepthStencilFormat=%s\n", debug_d3dformat(pPresentParms->AutoDepthStencilFormat));
767             ds_format_desc = getFormatDescEntry(pPresentParms->AutoDepthStencilFormat, &This->adapter->gl_info);
768         }
769
770         /* D3D only allows multisampling when SwapEffect is set to WINED3DSWAPEFFECT_DISCARD */
771         if(pPresentParms->MultiSampleType && (pPresentParms->SwapEffect == WINED3DSWAPEFFECT_DISCARD)) {
772             if(!GL_SUPPORT(ARB_MULTISAMPLE))
773                 ERR("The program is requesting multisampling without support!\n");
774             else {
775                 ERR("Requesting MultiSampleType=%d\n", pPresentParms->MultiSampleType);
776                 numSamples = pPresentParms->MultiSampleType;
777             }
778         }
779
780         /* Try to find a pixel format which matches our requirements */
781         iPixelFormat = WineD3D_ChoosePixelFormat(This, hdc, color_format_desc, ds_format_desc,
782                 auxBuffers, numSamples, FALSE /* PBUFFER */, FALSE /* findCompatible */);
783
784         /* Try to locate a compatible format if we weren't able to find anything */
785         if(!iPixelFormat) {
786             TRACE("Trying to locate a compatible pixel format because an exact match failed.\n");
787             iPixelFormat = WineD3D_ChoosePixelFormat(This, hdc, color_format_desc, ds_format_desc,
788                     auxBuffers, 0 /* numSamples */, FALSE /* PBUFFER */, TRUE /* findCompatible */ );
789         }
790
791         /* If we still don't have a pixel format, something is very wrong as ChoosePixelFormat barely fails */
792         if(!iPixelFormat) {
793             ERR("Can't find a suitable iPixelFormat\n");
794             return FALSE;
795         }
796
797         DescribePixelFormat(hdc, iPixelFormat, sizeof(pfd), &pfd);
798         res = SetPixelFormat(hdc, iPixelFormat, NULL);
799         if(!res) {
800             int oldPixelFormat = GetPixelFormat(hdc);
801
802             /* By default WGL doesn't allow pixel format adjustments but we need it here.
803              * For this reason there is a WINE-specific wglSetPixelFormat which allows you to
804              * set the pixel format multiple times. Only use it when it is really needed. */
805
806             if(oldPixelFormat == iPixelFormat) {
807                 /* We don't have to do anything as the formats are the same :) */
808             } else if(oldPixelFormat && GL_SUPPORT(WGL_WINE_PIXEL_FORMAT_PASSTHROUGH)) {
809                 res = GL_EXTCALL(wglSetPixelFormatWINE(hdc, iPixelFormat, NULL));
810
811                 if(!res) {
812                     ERR("wglSetPixelFormatWINE failed on HDC=%p for iPixelFormat=%d\n", hdc, iPixelFormat);
813                     return FALSE;
814                 }
815             } else if(oldPixelFormat) {
816                 /* OpenGL doesn't allow pixel format adjustments. Print an error and continue using the old format.
817                  * There's a big chance that the old format works although with a performance hit and perhaps rendering errors. */
818                 ERR("HDC=%p is already set to iPixelFormat=%d and OpenGL doesn't allow changes!\n", hdc, oldPixelFormat);
819             } else {
820                 ERR("SetPixelFormat failed on HDC=%p for iPixelFormat=%d\n", hdc, iPixelFormat);
821                 return FALSE;
822             }
823         }
824     }
825
826     ctx = pwglCreateContext(hdc);
827     if(This->numContexts) pwglShareLists(This->contexts[0]->glCtx, ctx);
828
829     if(!ctx) {
830         ERR("Failed to create a WGL context\n");
831         if(create_pbuffer) {
832             GL_EXTCALL(wglReleasePbufferDCARB(pbuffer, hdc));
833             GL_EXTCALL(wglDestroyPbufferARB(pbuffer));
834         }
835         goto out;
836     }
837     ret = AddContextToArray(This, win_handle, hdc, ctx, pbuffer);
838     if(!ret) {
839         ERR("Failed to add the newly created context to the context list\n");
840         pwglDeleteContext(ctx);
841         if(create_pbuffer) {
842             GL_EXTCALL(wglReleasePbufferDCARB(pbuffer, hdc));
843             GL_EXTCALL(wglDestroyPbufferARB(pbuffer));
844         }
845         goto out;
846     }
847     ret->surface = (IWineD3DSurface *) target;
848     ret->isPBuffer = create_pbuffer;
849     ret->tid = GetCurrentThreadId();
850     if(This->shader_backend->shader_dirtifyable_constants((IWineD3DDevice *) This)) {
851         /* Create the dirty constants array and initialize them to dirty */
852         ret->vshader_const_dirty = HeapAlloc(GetProcessHeap(), 0,
853                 sizeof(*ret->vshader_const_dirty) * GL_LIMITS(vshader_constantsF));
854         ret->pshader_const_dirty = HeapAlloc(GetProcessHeap(), 0,
855                 sizeof(*ret->pshader_const_dirty) * GL_LIMITS(pshader_constantsF));
856         memset(ret->vshader_const_dirty, 1,
857                sizeof(*ret->vshader_const_dirty) * GL_LIMITS(vshader_constantsF));
858         memset(ret->pshader_const_dirty, 1,
859                 sizeof(*ret->pshader_const_dirty) * GL_LIMITS(pshader_constantsF));
860     }
861
862     TRACE("Successfully created new context %p\n", ret);
863
864     list_init(&ret->fbo_list);
865
866     /* Set up the context defaults */
867     oldCtx  = pwglGetCurrentContext();
868     oldDrawable = pwglGetCurrentDC();
869     if(oldCtx && oldDrawable) {
870         /* See comment in ActivateContext context switching */
871         This->frag_pipe->enable_extension((IWineD3DDevice *) This, FALSE);
872     }
873     if(pwglMakeCurrent(hdc, ctx) == FALSE) {
874         ERR("Cannot activate context to set up defaults\n");
875         goto out;
876     }
877
878     ENTER_GL();
879
880     glGetIntegerv(GL_AUX_BUFFERS, &ret->aux_buffers);
881
882     TRACE("Setting up the screen\n");
883     /* Clear the screen */
884     glClearColor(1.0, 0.0, 0.0, 0.0);
885     checkGLcall("glClearColor");
886     glClearIndex(0);
887     glClearDepth(1);
888     glClearStencil(0xffff);
889
890     checkGLcall("glClear");
891
892     glLightModeli(GL_LIGHT_MODEL_LOCAL_VIEWER, GL_TRUE);
893     checkGLcall("glLightModeli(GL_LIGHT_MODEL_LOCAL_VIEWER, GL_TRUE);");
894
895     glTexEnvf(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_COMBINE_EXT);
896     checkGLcall("glTexEnvf(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_COMBINE_EXT);");
897
898     glLightModeli(GL_LIGHT_MODEL_COLOR_CONTROL, GL_SEPARATE_SPECULAR_COLOR);
899     checkGLcall("glLightModeli(GL_LIGHT_MODEL_COLOR_CONTROL, GL_SEPARATE_SPECULAR_COLOR);");
900
901     glPixelStorei(GL_PACK_ALIGNMENT, This->surface_alignment);
902     checkGLcall("glPixelStorei(GL_PACK_ALIGNMENT, This->surface_alignment);");
903     glPixelStorei(GL_UNPACK_ALIGNMENT, This->surface_alignment);
904     checkGLcall("glPixelStorei(GL_UNPACK_ALIGNMENT, This->surface_alignment);");
905
906     if(GL_SUPPORT(APPLE_CLIENT_STORAGE)) {
907         /* Most textures will use client storage if supported. Exceptions are non-native power of 2 textures
908          * and textures in DIB sections(due to the memory protection).
909          */
910         glPixelStorei(GL_UNPACK_CLIENT_STORAGE_APPLE, GL_TRUE);
911         checkGLcall("glPixelStorei(GL_UNPACK_CLIENT_STORAGE_APPLE, GL_TRUE)");
912     }
913     if(GL_SUPPORT(ARB_VERTEX_BLEND)) {
914         /* Direct3D always uses n-1 weights for n world matrices and uses 1 - sum for the last one
915          * this is equal to GL_WEIGHT_SUM_UNITY_ARB. Enabling it doesn't do anything unless
916          * GL_VERTEX_BLEND_ARB isn't enabled too
917          */
918         glEnable(GL_WEIGHT_SUM_UNITY_ARB);
919         checkGLcall("glEnable(GL_WEIGHT_SUM_UNITY_ARB)");
920     }
921     if(GL_SUPPORT(NV_TEXTURE_SHADER2)) {
922         /* Set up the previous texture input for all shader units. This applies to bump mapping, and in d3d
923          * the previous texture where to source the offset from is always unit - 1.
924          */
925         for(s = 1; s < GL_LIMITS(textures); s++) {
926             GL_EXTCALL(glActiveTextureARB(GL_TEXTURE0_ARB + s));
927             glTexEnvi(GL_TEXTURE_SHADER_NV, GL_PREVIOUS_TEXTURE_INPUT_NV, GL_TEXTURE0_ARB + s - 1);
928             checkGLcall("glTexEnvi(GL_TEXTURE_SHADER_NV, GL_PREVIOUS_TEXTURE_INPUT_NV, ...\n");
929         }
930     }
931
932     for(s = 0; s < GL_LIMITS(point_sprite_units); s++) {
933         GL_EXTCALL(glActiveTextureARB(GL_TEXTURE0_ARB + s));
934         glTexEnvi(GL_POINT_SPRITE_ARB, GL_COORD_REPLACE_ARB, GL_TRUE);
935         checkGLcall("glTexEnvi(GL_POINT_SPRITE_ARB, GL_COORD_REPLACE_ARB, GL_TRUE)\n");
936     }
937     LEAVE_GL();
938
939     /* Never keep GL_FRAGMENT_SHADER_ATI enabled on a context that we switch away from,
940      * but enable it for the first context we create, and reenable it on the old context
941      */
942     if(oldDrawable && oldCtx) {
943         pwglMakeCurrent(oldDrawable, oldCtx);
944     } else {
945         last_device = This;
946     }
947     This->frag_pipe->enable_extension((IWineD3DDevice *) This, TRUE);
948
949     return ret;
950
951 out:
952     return NULL;
953 }
954
955 /*****************************************************************************
956  * RemoveContextFromArray
957  *
958  * Removes a context from the context manager. The opengl context is not
959  * destroyed or unset. context is not a valid pointer after that call.
960  *
961  * Similar to the former call this isn't a performance critical function. A
962  * helper function for DestroyContext.
963  *
964  * Params:
965  *  This: Device to activate the context for
966  *  context: Context to remove
967  *
968  *****************************************************************************/
969 static void RemoveContextFromArray(IWineD3DDeviceImpl *This, WineD3DContext *context) {
970     WineD3DContext **new_array;
971     BOOL found = FALSE;
972     UINT i;
973
974     TRACE("Removing ctx %p\n", context);
975
976     for (i = 0; i < This->numContexts; ++i)
977     {
978         if (This->contexts[i] == context)
979         {
980             HeapFree(GetProcessHeap(), 0, context);
981             found = TRUE;
982             break;
983         }
984     }
985
986     if (!found)
987     {
988         ERR("Context %p doesn't exist in context array\n", context);
989         return;
990     }
991
992     while (i < This->numContexts - 1)
993     {
994         This->contexts[i] = This->contexts[i + 1];
995         ++i;
996     }
997
998     --This->numContexts;
999     if (!This->numContexts)
1000     {
1001         HeapFree(GetProcessHeap(), 0, This->contexts);
1002         This->contexts = NULL;
1003         return;
1004     }
1005
1006     new_array = HeapReAlloc(GetProcessHeap(), 0, This->contexts, This->numContexts * sizeof(*This->contexts));
1007     if (!new_array)
1008     {
1009         ERR("Failed to shrink context array. Oh well.\n");
1010         return;
1011     }
1012
1013     This->contexts = new_array;
1014 }
1015
1016 /*****************************************************************************
1017  * DestroyContext
1018  *
1019  * Destroys a wineD3DContext
1020  *
1021  * Params:
1022  *  This: Device to activate the context for
1023  *  context: Context to destroy
1024  *
1025  *****************************************************************************/
1026 void DestroyContext(IWineD3DDeviceImpl *This, WineD3DContext *context) {
1027     struct fbo_entry *entry, *entry2;
1028
1029     TRACE("Destroying ctx %p\n", context);
1030
1031     /* The correct GL context needs to be active to cleanup the GL resources below */
1032     if(pwglGetCurrentContext() != context->glCtx){
1033         pwglMakeCurrent(context->hdc, context->glCtx);
1034         last_device = NULL;
1035     }
1036
1037     ENTER_GL();
1038
1039     LIST_FOR_EACH_ENTRY_SAFE(entry, entry2, &context->fbo_list, struct fbo_entry, entry) {
1040         context_destroy_fbo_entry(This, entry);
1041     }
1042     if (context->src_fbo) {
1043         TRACE("Destroy src FBO %d\n", context->src_fbo);
1044         context_destroy_fbo(This, &context->src_fbo);
1045     }
1046     if (context->dst_fbo) {
1047         TRACE("Destroy dst FBO %d\n", context->dst_fbo);
1048         context_destroy_fbo(This, &context->dst_fbo);
1049     }
1050
1051     LEAVE_GL();
1052
1053     if (This->activeContext == context)
1054     {
1055         This->activeContext = NULL;
1056         TRACE("Destroying the active context.\n");
1057     }
1058
1059     /* Cleanup the GL context */
1060     pwglMakeCurrent(NULL, NULL);
1061     if(context->isPBuffer) {
1062         GL_EXTCALL(wglReleasePbufferDCARB(context->pbuffer, context->hdc));
1063         GL_EXTCALL(wglDestroyPbufferARB(context->pbuffer));
1064     } else ReleaseDC(context->win_handle, context->hdc);
1065     pwglDeleteContext(context->glCtx);
1066
1067     HeapFree(GetProcessHeap(), 0, context->vshader_const_dirty);
1068     HeapFree(GetProcessHeap(), 0, context->pshader_const_dirty);
1069     RemoveContextFromArray(This, context);
1070 }
1071
1072 static inline void set_blit_dimension(UINT width, UINT height) {
1073     glMatrixMode(GL_PROJECTION);
1074     checkGLcall("glMatrixMode(GL_PROJECTION)");
1075     glLoadIdentity();
1076     checkGLcall("glLoadIdentity()");
1077     glOrtho(0, width, height, 0, 0.0, -1.0);
1078     checkGLcall("glOrtho");
1079     glViewport(0, 0, width, height);
1080     checkGLcall("glViewport");
1081 }
1082
1083 /*****************************************************************************
1084  * SetupForBlit
1085  *
1086  * Sets up a context for DirectDraw blitting.
1087  * All texture units are disabled, texture unit 0 is set as current unit
1088  * fog, lighting, blending, alpha test, z test, scissor test, culling disabled
1089  * color writing enabled for all channels
1090  * register combiners disabled, shaders disabled
1091  * world matrix is set to identity, texture matrix 0 too
1092  * projection matrix is setup for drawing screen coordinates
1093  *
1094  * Params:
1095  *  This: Device to activate the context for
1096  *  context: Context to setup
1097  *  width: render target width
1098  *  height: render target height
1099  *
1100  *****************************************************************************/
1101 static inline void SetupForBlit(IWineD3DDeviceImpl *This, WineD3DContext *context, UINT width, UINT height) {
1102     int i, sampler;
1103     const struct StateEntry *StateTable = This->StateTable;
1104
1105     TRACE("Setting up context %p for blitting\n", context);
1106     if(context->last_was_blit) {
1107         if(context->blit_w != width || context->blit_h != height) {
1108             set_blit_dimension(width, height);
1109             context->blit_w = width; context->blit_h = height;
1110             /* No need to dirtify here, the states are still dirtified because they weren't
1111              * applied since the last SetupForBlit call. Otherwise last_was_blit would not
1112              * be set
1113              */
1114         }
1115         TRACE("Context is already set up for blitting, nothing to do\n");
1116         return;
1117     }
1118     context->last_was_blit = TRUE;
1119
1120     /* TODO: Use a display list */
1121
1122     /* Disable shaders */
1123     This->shader_backend->shader_select((IWineD3DDevice *)This, FALSE, FALSE);
1124     Context_MarkStateDirty(context, STATE_VSHADER, StateTable);
1125     Context_MarkStateDirty(context, STATE_PIXELSHADER, StateTable);
1126
1127     /* Call ENTER_GL() once for all gl calls below. In theory we should not call
1128      * helper functions in between gl calls. This function is full of Context_MarkStateDirty
1129      * which can safely be called from here, we only lock once instead locking/unlocking
1130      * after each GL call.
1131      */
1132     ENTER_GL();
1133
1134     /* Disable all textures. The caller can then bind a texture it wants to blit
1135      * from
1136      *
1137      * The blitting code uses (for now) the fixed function pipeline, so make sure to reset all fixed
1138      * function texture unit. No need to care for higher samplers
1139      */
1140     for(i = GL_LIMITS(textures) - 1; i > 0 ; i--) {
1141         sampler = This->rev_tex_unit_map[i];
1142         GL_EXTCALL(glActiveTextureARB(GL_TEXTURE0_ARB + i));
1143         checkGLcall("glActiveTextureARB");
1144
1145         if(GL_SUPPORT(ARB_TEXTURE_CUBE_MAP)) {
1146             glDisable(GL_TEXTURE_CUBE_MAP_ARB);
1147             checkGLcall("glDisable GL_TEXTURE_CUBE_MAP_ARB");
1148         }
1149         glDisable(GL_TEXTURE_3D);
1150         checkGLcall("glDisable GL_TEXTURE_3D");
1151         if(GL_SUPPORT(ARB_TEXTURE_RECTANGLE)) {
1152             glDisable(GL_TEXTURE_RECTANGLE_ARB);
1153             checkGLcall("glDisable GL_TEXTURE_RECTANGLE_ARB");
1154         }
1155         glDisable(GL_TEXTURE_2D);
1156         checkGLcall("glDisable GL_TEXTURE_2D");
1157
1158         glTexEnvi(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_REPLACE);
1159         checkGLcall("glTexEnvi(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_REPLACE);");
1160
1161         if (sampler != -1) {
1162             if (sampler < MAX_TEXTURES) {
1163                 Context_MarkStateDirty(context, STATE_TEXTURESTAGE(sampler, WINED3DTSS_COLOROP), StateTable);
1164             }
1165             Context_MarkStateDirty(context, STATE_SAMPLER(sampler), StateTable);
1166         }
1167     }
1168     GL_EXTCALL(glActiveTextureARB(GL_TEXTURE0_ARB));
1169     checkGLcall("glActiveTextureARB");
1170
1171     sampler = This->rev_tex_unit_map[0];
1172
1173     if(GL_SUPPORT(ARB_TEXTURE_CUBE_MAP)) {
1174         glDisable(GL_TEXTURE_CUBE_MAP_ARB);
1175         checkGLcall("glDisable GL_TEXTURE_CUBE_MAP_ARB");
1176     }
1177     glDisable(GL_TEXTURE_3D);
1178     checkGLcall("glDisable GL_TEXTURE_3D");
1179     if(GL_SUPPORT(ARB_TEXTURE_RECTANGLE)) {
1180         glDisable(GL_TEXTURE_RECTANGLE_ARB);
1181         checkGLcall("glDisable GL_TEXTURE_RECTANGLE_ARB");
1182     }
1183     glDisable(GL_TEXTURE_2D);
1184     checkGLcall("glDisable GL_TEXTURE_2D");
1185
1186     glTexEnvi(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_REPLACE);
1187
1188     glMatrixMode(GL_TEXTURE);
1189     checkGLcall("glMatrixMode(GL_TEXTURE)");
1190     glLoadIdentity();
1191     checkGLcall("glLoadIdentity()");
1192
1193     if (GL_SUPPORT(EXT_TEXTURE_LOD_BIAS)) {
1194         glTexEnvf(GL_TEXTURE_FILTER_CONTROL_EXT,
1195                   GL_TEXTURE_LOD_BIAS_EXT,
1196                   0.0);
1197         checkGLcall("glTexEnvi GL_TEXTURE_LOD_BIAS_EXT ...");
1198     }
1199
1200     if (sampler != -1) {
1201         if (sampler < MAX_TEXTURES) {
1202             Context_MarkStateDirty(context, STATE_TRANSFORM(WINED3DTS_TEXTURE0 + sampler), StateTable);
1203             Context_MarkStateDirty(context, STATE_TEXTURESTAGE(sampler, WINED3DTSS_COLOROP), StateTable);
1204         }
1205         Context_MarkStateDirty(context, STATE_SAMPLER(sampler), StateTable);
1206     }
1207
1208     /* Other misc states */
1209     glDisable(GL_ALPHA_TEST);
1210     checkGLcall("glDisable(GL_ALPHA_TEST)");
1211     Context_MarkStateDirty(context, STATE_RENDER(WINED3DRS_ALPHATESTENABLE), StateTable);
1212     glDisable(GL_LIGHTING);
1213     checkGLcall("glDisable GL_LIGHTING");
1214     Context_MarkStateDirty(context, STATE_RENDER(WINED3DRS_LIGHTING), StateTable);
1215     glDisable(GL_DEPTH_TEST);
1216     checkGLcall("glDisable GL_DEPTH_TEST");
1217     Context_MarkStateDirty(context, STATE_RENDER(WINED3DRS_ZENABLE), StateTable);
1218     glDisableWINE(GL_FOG);
1219     checkGLcall("glDisable GL_FOG");
1220     Context_MarkStateDirty(context, STATE_RENDER(WINED3DRS_FOGENABLE), StateTable);
1221     glDisable(GL_BLEND);
1222     checkGLcall("glDisable GL_BLEND");
1223     Context_MarkStateDirty(context, STATE_RENDER(WINED3DRS_ALPHABLENDENABLE), StateTable);
1224     glDisable(GL_CULL_FACE);
1225     checkGLcall("glDisable GL_CULL_FACE");
1226     Context_MarkStateDirty(context, STATE_RENDER(WINED3DRS_CULLMODE), StateTable);
1227     glDisable(GL_STENCIL_TEST);
1228     checkGLcall("glDisable GL_STENCIL_TEST");
1229     Context_MarkStateDirty(context, STATE_RENDER(WINED3DRS_STENCILENABLE), StateTable);
1230     glDisable(GL_SCISSOR_TEST);
1231     checkGLcall("glDisable GL_SCISSOR_TEST");
1232     Context_MarkStateDirty(context, STATE_RENDER(WINED3DRS_SCISSORTESTENABLE), StateTable);
1233     if(GL_SUPPORT(ARB_POINT_SPRITE)) {
1234         glDisable(GL_POINT_SPRITE_ARB);
1235         checkGLcall("glDisable GL_POINT_SPRITE_ARB");
1236         Context_MarkStateDirty(context, STATE_RENDER(WINED3DRS_POINTSPRITEENABLE), StateTable);
1237     }
1238     glColorMask(GL_TRUE, GL_TRUE,GL_TRUE,GL_TRUE);
1239     checkGLcall("glColorMask");
1240     Context_MarkStateDirty(context, STATE_RENDER(WINED3DRS_CLIPPING), StateTable);
1241     if (GL_SUPPORT(EXT_SECONDARY_COLOR)) {
1242         glDisable(GL_COLOR_SUM_EXT);
1243         Context_MarkStateDirty(context, STATE_RENDER(WINED3DRS_SPECULARENABLE), StateTable);
1244         checkGLcall("glDisable(GL_COLOR_SUM_EXT)");
1245     }
1246
1247     /* Setup transforms */
1248     glMatrixMode(GL_MODELVIEW);
1249     checkGLcall("glMatrixMode(GL_MODELVIEW)");
1250     glLoadIdentity();
1251     checkGLcall("glLoadIdentity()");
1252     Context_MarkStateDirty(context, STATE_TRANSFORM(WINED3DTS_WORLDMATRIX(0)), StateTable);
1253
1254     context->last_was_rhw = TRUE;
1255     Context_MarkStateDirty(context, STATE_VDECL, StateTable); /* because of last_was_rhw = TRUE */
1256
1257     glDisable(GL_CLIP_PLANE0); checkGLcall("glDisable(clip plane 0)");
1258     glDisable(GL_CLIP_PLANE1); checkGLcall("glDisable(clip plane 1)");
1259     glDisable(GL_CLIP_PLANE2); checkGLcall("glDisable(clip plane 2)");
1260     glDisable(GL_CLIP_PLANE3); checkGLcall("glDisable(clip plane 3)");
1261     glDisable(GL_CLIP_PLANE4); checkGLcall("glDisable(clip plane 4)");
1262     glDisable(GL_CLIP_PLANE5); checkGLcall("glDisable(clip plane 5)");
1263     Context_MarkStateDirty(context, STATE_RENDER(WINED3DRS_CLIPPING), StateTable);
1264     LEAVE_GL();
1265
1266     set_blit_dimension(width, height);
1267     context->blit_w = width; context->blit_h = height;
1268     Context_MarkStateDirty(context, STATE_VIEWPORT, StateTable);
1269     Context_MarkStateDirty(context, STATE_TRANSFORM(WINED3DTS_PROJECTION), StateTable);
1270
1271
1272     This->frag_pipe->enable_extension((IWineD3DDevice *) This, FALSE);
1273 }
1274
1275 /*****************************************************************************
1276  * findThreadContextForSwapChain
1277  *
1278  * Searches a swapchain for all contexts and picks one for the thread tid.
1279  * If none can be found the swapchain is requested to create a new context
1280  *
1281  *****************************************************************************/
1282 static WineD3DContext *findThreadContextForSwapChain(IWineD3DSwapChain *swapchain, DWORD tid) {
1283     unsigned int i;
1284
1285     for(i = 0; i < ((IWineD3DSwapChainImpl *) swapchain)->num_contexts; i++) {
1286         if(((IWineD3DSwapChainImpl *) swapchain)->context[i]->tid == tid) {
1287             return ((IWineD3DSwapChainImpl *) swapchain)->context[i];
1288         }
1289
1290     }
1291
1292     /* Create a new context for the thread */
1293     return IWineD3DSwapChainImpl_CreateContextForThread(swapchain);
1294 }
1295
1296 /*****************************************************************************
1297  * FindContext
1298  *
1299  * Finds a context for the current render target and thread
1300  *
1301  * Parameters:
1302  *  target: Render target to find the context for
1303  *  tid: Thread to activate the context for
1304  *
1305  * Returns: The needed context
1306  *
1307  *****************************************************************************/
1308 static inline WineD3DContext *FindContext(IWineD3DDeviceImpl *This, IWineD3DSurface *target, DWORD tid) {
1309     IWineD3DSwapChain *swapchain = NULL;
1310     BOOL readTexture = wined3d_settings.offscreen_rendering_mode != ORM_FBO && This->render_offscreen;
1311     WineD3DContext *context = This->activeContext;
1312     BOOL oldRenderOffscreen = This->render_offscreen;
1313     const struct GlPixelFormatDesc *old = ((IWineD3DSurfaceImpl *)This->lastActiveRenderTarget)->resource.format_desc;
1314     const struct GlPixelFormatDesc *new = ((IWineD3DSurfaceImpl *)target)->resource.format_desc;
1315     const struct StateEntry *StateTable = This->StateTable;
1316
1317     /* To compensate the lack of format switching with some offscreen rendering methods and on onscreen buffers
1318      * the alpha blend state changes with different render target formats
1319      */
1320     if (old->format != new->format)
1321     {
1322         /* Disable blending when the alpha mask has changed and when a format doesn't support blending */
1323         if ((old->alpha_mask && !new->alpha_mask) || (!old->alpha_mask && new->alpha_mask)
1324                 || !(new->Flags & WINED3DFMT_FLAG_POSTPIXELSHADER_BLENDING))
1325         {
1326             Context_MarkStateDirty(context, STATE_RENDER(WINED3DRS_ALPHABLENDENABLE), StateTable);
1327         }
1328     }
1329
1330     if (SUCCEEDED(IWineD3DSurface_GetContainer(target, &IID_IWineD3DSwapChain, (void **)&swapchain))) {
1331         TRACE("Rendering onscreen\n");
1332
1333         context = findThreadContextForSwapChain(swapchain, tid);
1334
1335         This->render_offscreen = FALSE;
1336         /* The context != This->activeContext will catch a NOP context change. This can occur
1337          * if we are switching back to swapchain rendering in case of FBO or Back Buffer offscreen
1338          * rendering. No context change is needed in that case
1339          */
1340
1341         if(wined3d_settings.offscreen_rendering_mode == ORM_PBUFFER) {
1342             if(This->pbufferContext && tid == This->pbufferContext->tid) {
1343                 This->pbufferContext->tid = 0;
1344             }
1345         }
1346         IWineD3DSwapChain_Release(swapchain);
1347
1348         if(oldRenderOffscreen) {
1349             Context_MarkStateDirty(context, WINED3DTS_PROJECTION, StateTable);
1350             Context_MarkStateDirty(context, STATE_VDECL, StateTable);
1351             Context_MarkStateDirty(context, STATE_VIEWPORT, StateTable);
1352             Context_MarkStateDirty(context, STATE_SCISSORRECT, StateTable);
1353             Context_MarkStateDirty(context, STATE_FRONTFACE, StateTable);
1354         }
1355
1356     } else {
1357         TRACE("Rendering offscreen\n");
1358         This->render_offscreen = TRUE;
1359
1360         switch(wined3d_settings.offscreen_rendering_mode) {
1361             case ORM_FBO:
1362                 /* FBOs do not need a different context. Stay with whatever context is active at the moment */
1363                 if(This->activeContext && tid == This->lastThread) {
1364                     context = This->activeContext;
1365                 } else {
1366                     /* This may happen if the app jumps straight into offscreen rendering
1367                      * Start using the context of the primary swapchain. tid == 0 is no problem
1368                      * for findThreadContextForSwapChain.
1369                      *
1370                      * Can also happen on thread switches - in that case findThreadContextForSwapChain
1371                      * is perfect to call.
1372                      */
1373                     context = findThreadContextForSwapChain(This->swapchains[0], tid);
1374                 }
1375                 break;
1376
1377             case ORM_PBUFFER:
1378             {
1379                 IWineD3DSurfaceImpl *targetimpl = (IWineD3DSurfaceImpl *) target;
1380                 if(This->pbufferContext == NULL ||
1381                    This->pbufferWidth < targetimpl->currentDesc.Width ||
1382                    This->pbufferHeight < targetimpl->currentDesc.Height) {
1383                     if(This->pbufferContext) {
1384                         DestroyContext(This, This->pbufferContext);
1385                     }
1386
1387                     /* The display is irrelevant here, the window is 0. But CreateContext needs a valid X connection.
1388                      * Create the context on the same server as the primary swapchain. The primary swapchain is exists at this point.
1389                      */
1390                     This->pbufferContext = CreateContext(This, targetimpl,
1391                             ((IWineD3DSwapChainImpl *) This->swapchains[0])->context[0]->win_handle,
1392                             TRUE /* pbuffer */, &((IWineD3DSwapChainImpl *)This->swapchains[0])->presentParms);
1393                     This->pbufferWidth = targetimpl->currentDesc.Width;
1394                     This->pbufferHeight = targetimpl->currentDesc.Height;
1395                    }
1396
1397                    if(This->pbufferContext) {
1398                        if(This->pbufferContext->tid != 0 && This->pbufferContext->tid != tid) {
1399                            FIXME("The PBuffr context is only supported for one thread for now!\n");
1400                        }
1401                        This->pbufferContext->tid = tid;
1402                        context = This->pbufferContext;
1403                        break;
1404                    } else {
1405                        ERR("Failed to create a buffer context and drawable, falling back to back buffer offscreen rendering\n");
1406                        wined3d_settings.offscreen_rendering_mode = ORM_BACKBUFFER;
1407                    }
1408             }
1409
1410             case ORM_BACKBUFFER:
1411                 /* Stay with the currently active context for back buffer rendering */
1412                 if(This->activeContext && tid == This->lastThread) {
1413                     context = This->activeContext;
1414                 } else {
1415                     /* This may happen if the app jumps straight into offscreen rendering
1416                      * Start using the context of the primary swapchain. tid == 0 is no problem
1417                      * for findThreadContextForSwapChain.
1418                      *
1419                      * Can also happen on thread switches - in that case findThreadContextForSwapChain
1420                      * is perfect to call.
1421                      */
1422                     context = findThreadContextForSwapChain(This->swapchains[0], tid);
1423                 }
1424                 break;
1425         }
1426
1427         if(!oldRenderOffscreen) {
1428             Context_MarkStateDirty(context, WINED3DTS_PROJECTION, StateTable);
1429             Context_MarkStateDirty(context, STATE_VDECL, StateTable);
1430             Context_MarkStateDirty(context, STATE_VIEWPORT, StateTable);
1431             Context_MarkStateDirty(context, STATE_SCISSORRECT, StateTable);
1432             Context_MarkStateDirty(context, STATE_FRONTFACE, StateTable);
1433         }
1434     }
1435
1436     /* When switching away from an offscreen render target, and we're not using FBOs,
1437      * we have to read the drawable into the texture. This is done via PreLoad(and
1438      * SFLAG_INDRAWABLE set on the surface). There are some things that need care though.
1439      * PreLoad needs a GL context, and FindContext is called before the context is activated.
1440      * It also has to be called with the old rendertarget active, otherwise a wrong drawable
1441      * is read. This leads to these possible situations:
1442      *
1443      * 0) lastActiveRenderTarget == target && oldTid == newTid:
1444      *    Nothing to do, we don't even reach this code in this case...
1445      *
1446      * 1) lastActiveRenderTarget != target && oldTid == newTid:
1447      *    The currently active context is OK for readback. Call PreLoad, and it
1448      *    performs the read
1449      *
1450      * 2) lastActiveRenderTarget == target && oldTid != newTid:
1451      *    Nothing to do - the drawable is unchanged
1452      *
1453      * 3) lastActiveRenderTarget != target && oldTid != newTid:
1454      *    This is tricky. We have to get a context with the old drawable from somewhere
1455      *    before we can switch to the new context. In this case, PreLoad calls
1456      *    ActivateContext(lastActiveRenderTarget) from the new(current) thread. This
1457      *    is case (2) then. The old drawable is activated for the new thread, and the
1458      *    readback can be done. The recursed ActivateContext does *not* call PreLoad again.
1459      *    After that, the outer ActivateContext(which calls PreLoad) can activate the new
1460      *    target for the new thread
1461      */
1462     if (readTexture && This->lastActiveRenderTarget != target) {
1463         BOOL oldInDraw = This->isInDraw;
1464
1465         /* PreLoad requires a context to load the texture, thus it will call ActivateContext.
1466          * Set the isInDraw to true to signal PreLoad that it has a context. Will be tricky
1467          * when using offscreen rendering with multithreading
1468          */
1469         This->isInDraw = TRUE;
1470
1471         /* Do that before switching the context:
1472          * Read the back buffer of the old drawable into the destination texture
1473          */
1474         if(((IWineD3DSurfaceImpl *)This->lastActiveRenderTarget)->glDescription.srgbTextureName) {
1475             surface_internal_preload(This->lastActiveRenderTarget, SRGB_BOTH);
1476         } else {
1477             surface_internal_preload(This->lastActiveRenderTarget, SRGB_RGB);
1478         }
1479
1480         /* Assume that the drawable will be modified by some other things now */
1481         IWineD3DSurface_ModifyLocation(This->lastActiveRenderTarget, SFLAG_INDRAWABLE, FALSE);
1482
1483         This->isInDraw = oldInDraw;
1484     }
1485
1486     return context;
1487 }
1488
1489 static void apply_draw_buffer(IWineD3DDeviceImpl *This, IWineD3DSurface *target, BOOL blit)
1490 {
1491     IWineD3DSwapChain *swapchain;
1492
1493     if (SUCCEEDED(IWineD3DSurface_GetContainer(target, &IID_IWineD3DSwapChain, (void **)&swapchain)))
1494     {
1495         IWineD3DSwapChain_Release((IUnknown *)swapchain);
1496         ENTER_GL();
1497         glDrawBuffer(surface_get_gl_buffer(target, swapchain));
1498         checkGLcall("glDrawBuffers()");
1499         LEAVE_GL();
1500     }
1501     else
1502     {
1503         ENTER_GL();
1504         if (wined3d_settings.offscreen_rendering_mode == ORM_FBO)
1505         {
1506             if (!blit)
1507             {
1508                 if (GL_SUPPORT(ARB_DRAW_BUFFERS))
1509                 {
1510                     GL_EXTCALL(glDrawBuffersARB(GL_LIMITS(buffers), This->draw_buffers));
1511                     checkGLcall("glDrawBuffers()");
1512                 }
1513                 else
1514                 {
1515                     glDrawBuffer(This->draw_buffers[0]);
1516                     checkGLcall("glDrawBuffer()");
1517                 }
1518             } else {
1519                 glDrawBuffer(GL_COLOR_ATTACHMENT0_EXT);
1520                 checkGLcall("glDrawBuffer()");
1521             }
1522         }
1523         else
1524         {
1525             glDrawBuffer(This->offscreenBuffer);
1526             checkGLcall("glDrawBuffer()");
1527         }
1528         LEAVE_GL();
1529     }
1530 }
1531
1532 /*****************************************************************************
1533  * ActivateContext
1534  *
1535  * Finds a rendering context and drawable matching the device and render
1536  * target for the current thread, activates them and puts them into the
1537  * requested state.
1538  *
1539  * Params:
1540  *  This: Device to activate the context for
1541  *  target: Requested render target
1542  *  usage: Prepares the context for blitting, drawing or other actions
1543  *
1544  *****************************************************************************/
1545 void ActivateContext(IWineD3DDeviceImpl *This, IWineD3DSurface *target, ContextUsage usage) {
1546     DWORD                         tid = GetCurrentThreadId();
1547     DWORD                         i, dirtyState, idx;
1548     BYTE                          shift;
1549     WineD3DContext                *context;
1550     const struct StateEntry       *StateTable = This->StateTable;
1551
1552     TRACE("(%p): Selecting context for render target %p, thread %d\n", This, target, tid);
1553     if(This->lastActiveRenderTarget != target || tid != This->lastThread) {
1554         context = FindContext(This, target, tid);
1555         context->draw_buffer_dirty = TRUE;
1556         This->lastActiveRenderTarget = target;
1557         This->lastThread = tid;
1558     } else {
1559         /* Stick to the old context */
1560         context = This->activeContext;
1561     }
1562
1563     /* Activate the opengl context */
1564     if(last_device != This || context != This->activeContext) {
1565         BOOL ret;
1566
1567         /* Prevent an unneeded context switch as those are expensive */
1568         if(context->glCtx && (context->glCtx == pwglGetCurrentContext())) {
1569             TRACE("Already using gl context %p\n", context->glCtx);
1570         }
1571         else {
1572             TRACE("Switching gl ctx to %p, hdc=%p ctx=%p\n", context, context->hdc, context->glCtx);
1573
1574             ret = pwglMakeCurrent(context->hdc, context->glCtx);
1575             if(ret == FALSE) {
1576                 ERR("Failed to activate the new context\n");
1577             } else if(!context->last_was_blit) {
1578                 This->frag_pipe->enable_extension((IWineD3DDevice *) This, TRUE);
1579             } else {
1580                 This->frag_pipe->enable_extension((IWineD3DDevice *) This, FALSE);
1581             }
1582         }
1583         if(This->activeContext->vshader_const_dirty) {
1584             memset(This->activeContext->vshader_const_dirty, 1,
1585                    sizeof(*This->activeContext->vshader_const_dirty) * GL_LIMITS(vshader_constantsF));
1586         }
1587         if(This->activeContext->pshader_const_dirty) {
1588             memset(This->activeContext->pshader_const_dirty, 1,
1589                    sizeof(*This->activeContext->pshader_const_dirty) * GL_LIMITS(pshader_constantsF));
1590         }
1591         This->activeContext = context;
1592         last_device = This;
1593     }
1594
1595     switch (usage) {
1596         case CTXUSAGE_CLEAR:
1597         case CTXUSAGE_DRAWPRIM:
1598             if (wined3d_settings.offscreen_rendering_mode == ORM_FBO) {
1599                 context_apply_fbo_state((IWineD3DDevice *)This);
1600             }
1601             if (context->draw_buffer_dirty) {
1602                 apply_draw_buffer(This, target, FALSE);
1603                 context->draw_buffer_dirty = FALSE;
1604             }
1605             break;
1606
1607         case CTXUSAGE_BLIT:
1608             if (wined3d_settings.offscreen_rendering_mode == ORM_FBO) {
1609                 if (This->render_offscreen) {
1610                     FIXME("Activating for CTXUSAGE_BLIT for an offscreen target with ORM_FBO. This should be avoided.\n");
1611                     context_bind_fbo((IWineD3DDevice *)This, GL_FRAMEBUFFER_EXT, &context->dst_fbo);
1612                     context_attach_surface_fbo(This, GL_FRAMEBUFFER_EXT, 0, target);
1613
1614                     ENTER_GL();
1615                     GL_EXTCALL(glFramebufferRenderbufferEXT(GL_FRAMEBUFFER_EXT, GL_DEPTH_ATTACHMENT_EXT, GL_RENDERBUFFER_EXT, 0));
1616                     checkGLcall("glFramebufferRenderbufferEXT");
1617                     LEAVE_GL();
1618                 } else {
1619                     ENTER_GL();
1620                     GL_EXTCALL(glBindFramebufferEXT(GL_FRAMEBUFFER_EXT, 0));
1621                     checkGLcall("glFramebufferRenderbufferEXT");
1622                     LEAVE_GL();
1623                 }
1624                 context->draw_buffer_dirty = TRUE;
1625             }
1626             if (context->draw_buffer_dirty) {
1627                 apply_draw_buffer(This, target, TRUE);
1628                 if (wined3d_settings.offscreen_rendering_mode != ORM_FBO) {
1629                     context->draw_buffer_dirty = FALSE;
1630                 }
1631             }
1632             break;
1633
1634         default:
1635             break;
1636     }
1637
1638     switch(usage) {
1639         case CTXUSAGE_RESOURCELOAD:
1640             /* This does not require any special states to be set up */
1641             break;
1642
1643         case CTXUSAGE_CLEAR:
1644             if(context->last_was_blit) {
1645                 This->frag_pipe->enable_extension((IWineD3DDevice *) This, TRUE);
1646             }
1647
1648             /* Blending and clearing should be orthogonal, but tests on the nvidia driver show that disabling
1649              * blending when clearing improves the clearing performance incredibly.
1650              */
1651             ENTER_GL();
1652             glDisable(GL_BLEND);
1653             LEAVE_GL();
1654             Context_MarkStateDirty(context, STATE_RENDER(WINED3DRS_ALPHABLENDENABLE), StateTable);
1655
1656             ENTER_GL();
1657             glEnable(GL_SCISSOR_TEST);
1658             checkGLcall("glEnable GL_SCISSOR_TEST");
1659             LEAVE_GL();
1660             context->last_was_blit = FALSE;
1661             Context_MarkStateDirty(context, STATE_RENDER(WINED3DRS_SCISSORTESTENABLE), StateTable);
1662             Context_MarkStateDirty(context, STATE_SCISSORRECT, StateTable);
1663             break;
1664
1665         case CTXUSAGE_DRAWPRIM:
1666             /* This needs all dirty states applied */
1667             if(context->last_was_blit) {
1668                 This->frag_pipe->enable_extension((IWineD3DDevice *) This, TRUE);
1669             }
1670
1671             IWineD3DDeviceImpl_FindTexUnitMap(This);
1672
1673             for(i=0; i < context->numDirtyEntries; i++) {
1674                 dirtyState = context->dirtyArray[i];
1675                 idx = dirtyState >> 5;
1676                 shift = dirtyState & 0x1f;
1677                 context->isStateDirty[idx] &= ~(1 << shift);
1678                 StateTable[dirtyState].apply(dirtyState, This->stateBlock, context);
1679             }
1680             context->numDirtyEntries = 0; /* This makes the whole list clean */
1681             context->last_was_blit = FALSE;
1682             break;
1683
1684         case CTXUSAGE_BLIT:
1685             SetupForBlit(This, context,
1686                          ((IWineD3DSurfaceImpl *)target)->currentDesc.Width,
1687                          ((IWineD3DSurfaceImpl *)target)->currentDesc.Height);
1688             break;
1689
1690         default:
1691             FIXME("Unexpected context usage requested\n");
1692     }
1693 }
1694
1695 WineD3DContext *getActiveContext(void) {
1696     return last_device->activeContext;
1697 }