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