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