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