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