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