usp10: Move the application of pair values to a helper function.
[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-2011 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 "wine/port.h"
24
25 #include <stdio.h>
26 #ifdef HAVE_FLOAT_H
27 # include <float.h>
28 #endif
29
30 #include "wined3d_private.h"
31
32 WINE_DEFAULT_DEBUG_CHANNEL(d3d);
33
34 static DWORD wined3d_context_tls_idx;
35
36 /* FBO helper functions */
37
38 /* Context activation is done by the caller. */
39 static void context_bind_fbo(struct wined3d_context *context, GLenum target, GLuint *fbo)
40 {
41     const struct wined3d_gl_info *gl_info = context->gl_info;
42     GLuint f;
43
44     if (!fbo)
45     {
46         f = 0;
47     }
48     else
49     {
50         if (!*fbo)
51         {
52             gl_info->fbo_ops.glGenFramebuffers(1, fbo);
53             checkGLcall("glGenFramebuffers()");
54             TRACE("Created FBO %u.\n", *fbo);
55         }
56         f = *fbo;
57     }
58
59     switch (target)
60     {
61         case GL_READ_FRAMEBUFFER:
62             if (context->fbo_read_binding == f) return;
63             context->fbo_read_binding = f;
64             break;
65
66         case GL_DRAW_FRAMEBUFFER:
67             if (context->fbo_draw_binding == f) return;
68             context->fbo_draw_binding = f;
69             break;
70
71         case GL_FRAMEBUFFER:
72             if (context->fbo_read_binding == f
73                     && context->fbo_draw_binding == f) return;
74             context->fbo_read_binding = f;
75             context->fbo_draw_binding = f;
76             break;
77
78         default:
79             FIXME("Unhandled target %#x.\n", target);
80             break;
81     }
82
83     gl_info->fbo_ops.glBindFramebuffer(target, f);
84     checkGLcall("glBindFramebuffer()");
85 }
86
87 /* Context activation is done by the caller. */
88 static void context_clean_fbo_attachments(const struct wined3d_gl_info *gl_info, GLenum target)
89 {
90     unsigned int i;
91
92     for (i = 0; i < gl_info->limits.buffers; ++i)
93     {
94         gl_info->fbo_ops.glFramebufferTexture2D(target, GL_COLOR_ATTACHMENT0 + i, GL_TEXTURE_2D, 0, 0);
95         checkGLcall("glFramebufferTexture2D()");
96     }
97     gl_info->fbo_ops.glFramebufferTexture2D(target, GL_DEPTH_ATTACHMENT, GL_TEXTURE_2D, 0, 0);
98     checkGLcall("glFramebufferTexture2D()");
99
100     gl_info->fbo_ops.glFramebufferTexture2D(target, GL_STENCIL_ATTACHMENT, GL_TEXTURE_2D, 0, 0);
101     checkGLcall("glFramebufferTexture2D()");
102 }
103
104 /* Context activation is done by the caller. */
105 static void context_destroy_fbo(struct wined3d_context *context, GLuint *fbo)
106 {
107     const struct wined3d_gl_info *gl_info = context->gl_info;
108
109     context_bind_fbo(context, GL_FRAMEBUFFER, fbo);
110     context_clean_fbo_attachments(gl_info, GL_FRAMEBUFFER);
111     context_bind_fbo(context, GL_FRAMEBUFFER, NULL);
112
113     gl_info->fbo_ops.glDeleteFramebuffers(1, fbo);
114     checkGLcall("glDeleteFramebuffers()");
115 }
116
117 static void context_attach_depth_stencil_rb(const struct wined3d_gl_info *gl_info,
118         GLenum fbo_target, DWORD format_flags, GLuint rb)
119 {
120     if (format_flags & WINED3DFMT_FLAG_DEPTH)
121     {
122         gl_info->fbo_ops.glFramebufferRenderbuffer(fbo_target, GL_DEPTH_ATTACHMENT, GL_RENDERBUFFER, rb);
123         checkGLcall("glFramebufferRenderbuffer()");
124     }
125
126     if (format_flags & WINED3DFMT_FLAG_STENCIL)
127     {
128         gl_info->fbo_ops.glFramebufferRenderbuffer(fbo_target, GL_STENCIL_ATTACHMENT, GL_RENDERBUFFER, rb);
129         checkGLcall("glFramebufferRenderbuffer()");
130     }
131 }
132
133 /* Context activation is done by the caller. */
134 static void context_attach_depth_stencil_fbo(struct wined3d_context *context,
135         GLenum fbo_target, struct wined3d_surface *depth_stencil, DWORD location)
136 {
137     const struct wined3d_gl_info *gl_info = context->gl_info;
138
139     TRACE("Attach depth stencil %p\n", depth_stencil);
140
141     if (depth_stencil)
142     {
143         DWORD format_flags = depth_stencil->resource.format->flags;
144
145         if (depth_stencil->current_renderbuffer)
146         {
147             context_attach_depth_stencil_rb(gl_info, fbo_target,
148                     format_flags, depth_stencil->current_renderbuffer->id);
149         }
150         else
151         {
152             switch (location)
153             {
154                 case SFLAG_INTEXTURE:
155                 case SFLAG_INSRGBTEX:
156                     surface_prepare_texture(depth_stencil, context, FALSE);
157
158                     if (format_flags & WINED3DFMT_FLAG_DEPTH)
159                     {
160                         gl_info->fbo_ops.glFramebufferTexture2D(fbo_target, GL_DEPTH_ATTACHMENT,
161                                 depth_stencil->texture_target, depth_stencil->texture_name,
162                                 depth_stencil->texture_level);
163                         checkGLcall("glFramebufferTexture2D()");
164                     }
165
166                     if (format_flags & WINED3DFMT_FLAG_STENCIL)
167                     {
168                         gl_info->fbo_ops.glFramebufferTexture2D(fbo_target, GL_STENCIL_ATTACHMENT,
169                                 depth_stencil->texture_target, depth_stencil->texture_name,
170                                 depth_stencil->texture_level);
171                         checkGLcall("glFramebufferTexture2D()");
172                     }
173                     break;
174
175                 case SFLAG_INRB_MULTISAMPLE:
176                     surface_prepare_rb(depth_stencil, gl_info, TRUE);
177                     context_attach_depth_stencil_rb(gl_info, fbo_target,
178                             format_flags, depth_stencil->rb_multisample);
179                     break;
180
181                 case SFLAG_INRB_RESOLVED:
182                     surface_prepare_rb(depth_stencil, gl_info, FALSE);
183                     context_attach_depth_stencil_rb(gl_info, fbo_target,
184                             format_flags, depth_stencil->rb_resolved);
185                     break;
186
187                 default:
188                     ERR("Unsupported location %s (%#x).\n", debug_surflocation(location), location);
189                     break;
190             }
191         }
192
193         if (!(format_flags & WINED3DFMT_FLAG_DEPTH))
194         {
195             gl_info->fbo_ops.glFramebufferTexture2D(fbo_target, GL_DEPTH_ATTACHMENT, GL_TEXTURE_2D, 0, 0);
196             checkGLcall("glFramebufferTexture2D()");
197         }
198
199         if (!(format_flags & WINED3DFMT_FLAG_STENCIL))
200         {
201             gl_info->fbo_ops.glFramebufferTexture2D(fbo_target, GL_STENCIL_ATTACHMENT, GL_TEXTURE_2D, 0, 0);
202             checkGLcall("glFramebufferTexture2D()");
203         }
204     }
205     else
206     {
207         gl_info->fbo_ops.glFramebufferTexture2D(fbo_target, GL_DEPTH_ATTACHMENT, GL_TEXTURE_2D, 0, 0);
208         checkGLcall("glFramebufferTexture2D()");
209
210         gl_info->fbo_ops.glFramebufferTexture2D(fbo_target, GL_STENCIL_ATTACHMENT, GL_TEXTURE_2D, 0, 0);
211         checkGLcall("glFramebufferTexture2D()");
212     }
213 }
214
215 /* Context activation is done by the caller. */
216 static void context_attach_surface_fbo(struct wined3d_context *context,
217         GLenum fbo_target, DWORD idx, struct wined3d_surface *surface, DWORD location)
218 {
219     const struct wined3d_gl_info *gl_info = context->gl_info;
220
221     TRACE("Attach surface %p to %u\n", surface, idx);
222
223     if (surface && surface->resource.format->id != WINED3DFMT_NULL)
224     {
225         BOOL srgb;
226
227         switch (location)
228         {
229             case SFLAG_INTEXTURE:
230             case SFLAG_INSRGBTEX:
231                 srgb = location == SFLAG_INSRGBTEX;
232                 surface_prepare_texture(surface, context, srgb);
233                 gl_info->fbo_ops.glFramebufferTexture2D(fbo_target, GL_COLOR_ATTACHMENT0 + idx,
234                         surface->texture_target, surface_get_texture_name(surface, gl_info, srgb),
235                         surface->texture_level);
236                 checkGLcall("glFramebufferTexture2D()");
237                 break;
238
239             case SFLAG_INRB_MULTISAMPLE:
240                 surface_prepare_rb(surface, gl_info, TRUE);
241                 gl_info->fbo_ops.glFramebufferRenderbuffer(fbo_target, GL_COLOR_ATTACHMENT0 + idx,
242                         GL_RENDERBUFFER, surface->rb_multisample);
243                 checkGLcall("glFramebufferRenderbuffer()");
244                 break;
245
246             case SFLAG_INRB_RESOLVED:
247                 surface_prepare_rb(surface, gl_info, FALSE);
248                 gl_info->fbo_ops.glFramebufferRenderbuffer(fbo_target, GL_COLOR_ATTACHMENT0 + idx,
249                         GL_RENDERBUFFER, surface->rb_resolved);
250                 checkGLcall("glFramebufferRenderbuffer()");
251                 break;
252
253             default:
254                 ERR("Unsupported location %s (%#x).\n", debug_surflocation(location), location);
255                 break;
256         }
257     }
258     else
259     {
260         gl_info->fbo_ops.glFramebufferTexture2D(fbo_target, GL_COLOR_ATTACHMENT0 + idx, GL_TEXTURE_2D, 0, 0);
261         checkGLcall("glFramebufferTexture2D()");
262     }
263 }
264
265 /* Context activation is done by the caller. */
266 void context_check_fbo_status(const struct wined3d_context *context, GLenum target)
267 {
268     const struct wined3d_gl_info *gl_info = context->gl_info;
269     GLenum status;
270
271     if (!FIXME_ON(d3d)) return;
272
273     status = gl_info->fbo_ops.glCheckFramebufferStatus(target);
274     if (status == GL_FRAMEBUFFER_COMPLETE)
275     {
276         TRACE("FBO complete\n");
277     }
278     else
279     {
280         const struct wined3d_surface *attachment;
281         unsigned int i;
282
283         FIXME("FBO status %s (%#x)\n", debug_fbostatus(status), status);
284
285         if (!context->current_fbo)
286         {
287             ERR("FBO 0 is incomplete, driver bug?\n");
288             return;
289         }
290
291         FIXME("\tLocation %s (%#x).\n", debug_surflocation(context->current_fbo->location),
292                 context->current_fbo->location);
293
294         /* Dump the FBO attachments */
295         for (i = 0; i < gl_info->limits.buffers; ++i)
296         {
297             attachment = context->current_fbo->render_targets[i];
298             if (attachment)
299             {
300                 FIXME("\tColor attachment %d: (%p) %s %ux%u %u samples.\n",
301                         i, attachment, debug_d3dformat(attachment->resource.format->id),
302                         attachment->pow2Width, attachment->pow2Height, attachment->resource.multisample_type);
303             }
304         }
305         attachment = context->current_fbo->depth_stencil;
306         if (attachment)
307         {
308             FIXME("\tDepth attachment: (%p) %s %ux%u %u samples.\n",
309                     attachment, debug_d3dformat(attachment->resource.format->id),
310                     attachment->pow2Width, attachment->pow2Height, attachment->resource.multisample_type);
311         }
312     }
313 }
314
315 static inline DWORD context_generate_rt_mask(GLenum buffer)
316 {
317     /* Should take care of all the GL_FRONT/GL_BACK/GL_AUXi/GL_NONE... cases */
318     return buffer ? (1 << 31) | buffer : 0;
319 }
320
321 static inline DWORD context_generate_rt_mask_from_surface(const struct wined3d_surface *target)
322 {
323     return (1 << 31) | surface_get_gl_buffer(target);
324 }
325
326 static struct fbo_entry *context_create_fbo_entry(const struct wined3d_context *context,
327         struct wined3d_surface **render_targets, struct wined3d_surface *depth_stencil, DWORD location)
328 {
329     const struct wined3d_gl_info *gl_info = context->gl_info;
330     struct fbo_entry *entry;
331
332     entry = HeapAlloc(GetProcessHeap(), 0, sizeof(*entry));
333     entry->render_targets = HeapAlloc(GetProcessHeap(), 0, gl_info->limits.buffers * sizeof(*entry->render_targets));
334     memcpy(entry->render_targets, render_targets, gl_info->limits.buffers * sizeof(*entry->render_targets));
335     entry->depth_stencil = depth_stencil;
336     entry->location = location;
337     entry->rt_mask = context_generate_rt_mask(GL_COLOR_ATTACHMENT0);
338     entry->attached = FALSE;
339     entry->id = 0;
340
341     return entry;
342 }
343
344 /* Context activation is done by the caller. */
345 static void context_reuse_fbo_entry(struct wined3d_context *context, GLenum target,
346         struct wined3d_surface **render_targets, struct wined3d_surface *depth_stencil,
347         DWORD location, struct fbo_entry *entry)
348 {
349     const struct wined3d_gl_info *gl_info = context->gl_info;
350
351     context_bind_fbo(context, target, &entry->id);
352     context_clean_fbo_attachments(gl_info, target);
353
354     memcpy(entry->render_targets, render_targets, gl_info->limits.buffers * sizeof(*entry->render_targets));
355     entry->depth_stencil = depth_stencil;
356     entry->location = location;
357     entry->attached = FALSE;
358 }
359
360 /* Context activation is done by the caller. */
361 static void context_destroy_fbo_entry(struct wined3d_context *context, struct fbo_entry *entry)
362 {
363     if (entry->id)
364     {
365         TRACE("Destroy FBO %d\n", entry->id);
366         context_destroy_fbo(context, &entry->id);
367     }
368     --context->fbo_entry_count;
369     list_remove(&entry->entry);
370     HeapFree(GetProcessHeap(), 0, entry->render_targets);
371     HeapFree(GetProcessHeap(), 0, entry);
372 }
373
374 /* Context activation is done by the caller. */
375 static struct fbo_entry *context_find_fbo_entry(struct wined3d_context *context, GLenum target,
376         struct wined3d_surface **render_targets, struct wined3d_surface *depth_stencil, DWORD location)
377 {
378     const struct wined3d_gl_info *gl_info = context->gl_info;
379     struct fbo_entry *entry;
380
381     if (depth_stencil && render_targets && render_targets[0])
382     {
383         if (depth_stencil->resource.width < render_targets[0]->resource.width ||
384             depth_stencil->resource.height < render_targets[0]->resource.height)
385         {
386             WARN("Depth stencil is smaller than the primary color buffer, disabling\n");
387             depth_stencil = NULL;
388         }
389     }
390
391     LIST_FOR_EACH_ENTRY(entry, &context->fbo_list, struct fbo_entry, entry)
392     {
393         if (!memcmp(entry->render_targets,
394                 render_targets, gl_info->limits.buffers * sizeof(*entry->render_targets))
395                 && entry->depth_stencil == depth_stencil && entry->location == location)
396         {
397             list_remove(&entry->entry);
398             list_add_head(&context->fbo_list, &entry->entry);
399             return entry;
400         }
401     }
402
403     if (context->fbo_entry_count < WINED3D_MAX_FBO_ENTRIES)
404     {
405         entry = context_create_fbo_entry(context, render_targets, depth_stencil, location);
406         list_add_head(&context->fbo_list, &entry->entry);
407         ++context->fbo_entry_count;
408     }
409     else
410     {
411         entry = LIST_ENTRY(list_tail(&context->fbo_list), struct fbo_entry, entry);
412         context_reuse_fbo_entry(context, target, render_targets, depth_stencil, location, entry);
413         list_remove(&entry->entry);
414         list_add_head(&context->fbo_list, &entry->entry);
415     }
416
417     return entry;
418 }
419
420 /* Context activation is done by the caller. */
421 static void context_apply_fbo_entry(struct wined3d_context *context, GLenum target, struct fbo_entry *entry)
422 {
423     const struct wined3d_gl_info *gl_info = context->gl_info;
424     unsigned int i;
425
426     context_bind_fbo(context, target, &entry->id);
427
428     if (entry->attached) return;
429
430     /* Apply render targets */
431     for (i = 0; i < gl_info->limits.buffers; ++i)
432     {
433         context_attach_surface_fbo(context, target, i, entry->render_targets[i], entry->location);
434     }
435
436     /* Apply depth targets */
437     if (entry->depth_stencil)
438         surface_set_compatible_renderbuffer(entry->depth_stencil, entry->render_targets[0]);
439     context_attach_depth_stencil_fbo(context, target, entry->depth_stencil, entry->location);
440
441     entry->attached = TRUE;
442 }
443
444 /* Context activation is done by the caller. */
445 static void context_apply_fbo_state(struct wined3d_context *context, GLenum target,
446         struct wined3d_surface **render_targets, struct wined3d_surface *depth_stencil, DWORD location)
447 {
448     struct fbo_entry *entry, *entry2;
449
450     LIST_FOR_EACH_ENTRY_SAFE(entry, entry2, &context->fbo_destroy_list, struct fbo_entry, entry)
451     {
452         context_destroy_fbo_entry(context, entry);
453     }
454
455     if (context->rebind_fbo)
456     {
457         context_bind_fbo(context, GL_FRAMEBUFFER, NULL);
458         context->rebind_fbo = FALSE;
459     }
460
461     if (location == SFLAG_INDRAWABLE)
462     {
463         context->current_fbo = NULL;
464         context_bind_fbo(context, target, NULL);
465     }
466     else
467     {
468         context->current_fbo = context_find_fbo_entry(context, target, render_targets, depth_stencil, location);
469         context_apply_fbo_entry(context, target, context->current_fbo);
470     }
471 }
472
473 /* Context activation is done by the caller. */
474 void context_apply_fbo_state_blit(struct wined3d_context *context, GLenum target,
475         struct wined3d_surface *render_target, struct wined3d_surface *depth_stencil, DWORD location)
476 {
477     UINT clear_size = (context->gl_info->limits.buffers - 1) * sizeof(*context->blit_targets);
478
479     context->blit_targets[0] = render_target;
480     if (clear_size)
481         memset(&context->blit_targets[1], 0, clear_size);
482     context_apply_fbo_state(context, target, context->blit_targets, depth_stencil, location);
483 }
484
485 /* Context activation is done by the caller. */
486 void context_alloc_occlusion_query(struct wined3d_context *context, struct wined3d_occlusion_query *query)
487 {
488     const struct wined3d_gl_info *gl_info = context->gl_info;
489
490     if (context->free_occlusion_query_count)
491     {
492         query->id = context->free_occlusion_queries[--context->free_occlusion_query_count];
493     }
494     else
495     {
496         if (gl_info->supported[ARB_OCCLUSION_QUERY])
497         {
498             GL_EXTCALL(glGenQueriesARB(1, &query->id));
499             checkGLcall("glGenQueriesARB");
500
501             TRACE("Allocated occlusion query %u in context %p.\n", query->id, context);
502         }
503         else
504         {
505             WARN("Occlusion queries not supported, not allocating query id.\n");
506             query->id = 0;
507         }
508     }
509
510     query->context = context;
511     list_add_head(&context->occlusion_queries, &query->entry);
512 }
513
514 void context_free_occlusion_query(struct wined3d_occlusion_query *query)
515 {
516     struct wined3d_context *context = query->context;
517
518     list_remove(&query->entry);
519     query->context = NULL;
520
521     if (context->free_occlusion_query_count >= context->free_occlusion_query_size - 1)
522     {
523         UINT new_size = context->free_occlusion_query_size << 1;
524         GLuint *new_data = HeapReAlloc(GetProcessHeap(), 0, context->free_occlusion_queries,
525                 new_size * sizeof(*context->free_occlusion_queries));
526
527         if (!new_data)
528         {
529             ERR("Failed to grow free list, leaking query %u in context %p.\n", query->id, context);
530             return;
531         }
532
533         context->free_occlusion_query_size = new_size;
534         context->free_occlusion_queries = new_data;
535     }
536
537     context->free_occlusion_queries[context->free_occlusion_query_count++] = query->id;
538 }
539
540 /* Context activation is done by the caller. */
541 void context_alloc_event_query(struct wined3d_context *context, struct wined3d_event_query *query)
542 {
543     const struct wined3d_gl_info *gl_info = context->gl_info;
544
545     if (context->free_event_query_count)
546     {
547         query->object = context->free_event_queries[--context->free_event_query_count];
548     }
549     else
550     {
551         if (gl_info->supported[ARB_SYNC])
552         {
553             /* Using ARB_sync, not much to do here. */
554             query->object.sync = NULL;
555             TRACE("Allocated event query %p in context %p.\n", query->object.sync, context);
556         }
557         else if (gl_info->supported[APPLE_FENCE])
558         {
559             GL_EXTCALL(glGenFencesAPPLE(1, &query->object.id));
560             checkGLcall("glGenFencesAPPLE");
561
562             TRACE("Allocated event query %u in context %p.\n", query->object.id, context);
563         }
564         else if(gl_info->supported[NV_FENCE])
565         {
566             GL_EXTCALL(glGenFencesNV(1, &query->object.id));
567             checkGLcall("glGenFencesNV");
568
569             TRACE("Allocated event query %u in context %p.\n", query->object.id, context);
570         }
571         else
572         {
573             WARN("Event queries not supported, not allocating query id.\n");
574             query->object.id = 0;
575         }
576     }
577
578     query->context = context;
579     list_add_head(&context->event_queries, &query->entry);
580 }
581
582 void context_free_event_query(struct wined3d_event_query *query)
583 {
584     struct wined3d_context *context = query->context;
585
586     list_remove(&query->entry);
587     query->context = NULL;
588
589     if (context->free_event_query_count >= context->free_event_query_size - 1)
590     {
591         UINT new_size = context->free_event_query_size << 1;
592         union wined3d_gl_query_object *new_data = HeapReAlloc(GetProcessHeap(), 0, context->free_event_queries,
593                 new_size * sizeof(*context->free_event_queries));
594
595         if (!new_data)
596         {
597             ERR("Failed to grow free list, leaking query %u in context %p.\n", query->object.id, context);
598             return;
599         }
600
601         context->free_event_query_size = new_size;
602         context->free_event_queries = new_data;
603     }
604
605     context->free_event_queries[context->free_event_query_count++] = query->object;
606 }
607
608 typedef void (context_fbo_entry_func_t)(struct wined3d_context *context, struct fbo_entry *entry);
609
610 static void context_enum_surface_fbo_entries(const struct wined3d_device *device,
611         const struct wined3d_surface *surface, context_fbo_entry_func_t *callback)
612 {
613     UINT i;
614
615     for (i = 0; i < device->context_count; ++i)
616     {
617         struct wined3d_context *context = device->contexts[i];
618         const struct wined3d_gl_info *gl_info = context->gl_info;
619         struct fbo_entry *entry, *entry2;
620
621         if (context->current_rt == surface) context->current_rt = NULL;
622
623         LIST_FOR_EACH_ENTRY_SAFE(entry, entry2, &context->fbo_list, struct fbo_entry, entry)
624         {
625             UINT j;
626
627             if (entry->depth_stencil == surface)
628             {
629                 callback(context, entry);
630                 continue;
631             }
632
633             for (j = 0; j < gl_info->limits.buffers; ++j)
634             {
635                 if (entry->render_targets[j] == surface)
636                 {
637                     callback(context, entry);
638                     break;
639                 }
640             }
641         }
642     }
643 }
644
645 static void context_queue_fbo_entry_destruction(struct wined3d_context *context, struct fbo_entry *entry)
646 {
647     list_remove(&entry->entry);
648     list_add_head(&context->fbo_destroy_list, &entry->entry);
649 }
650
651 void context_resource_released(const struct wined3d_device *device,
652         struct wined3d_resource *resource, enum wined3d_resource_type type)
653 {
654     if (!device->d3d_initialized) return;
655
656     switch (type)
657     {
658         case WINED3D_RTYPE_SURFACE:
659             context_enum_surface_fbo_entries(device, surface_from_resource(resource),
660                     context_queue_fbo_entry_destruction);
661             break;
662
663         default:
664             break;
665     }
666 }
667
668 static void context_detach_fbo_entry(struct wined3d_context *context, struct fbo_entry *entry)
669 {
670     entry->attached = FALSE;
671 }
672
673 void context_resource_unloaded(const struct wined3d_device *device,
674         struct wined3d_resource *resource, enum wined3d_resource_type type)
675 {
676     switch (type)
677     {
678         case WINED3D_RTYPE_SURFACE:
679             context_enum_surface_fbo_entries(device, surface_from_resource(resource),
680                     context_detach_fbo_entry);
681             break;
682
683         default:
684             break;
685     }
686 }
687
688 void context_surface_update(struct wined3d_context *context, const struct wined3d_surface *surface)
689 {
690     const struct wined3d_gl_info *gl_info = context->gl_info;
691     struct fbo_entry *entry = context->current_fbo;
692     unsigned int i;
693
694     if (!entry || context->rebind_fbo) return;
695
696     for (i = 0; i < gl_info->limits.buffers; ++i)
697     {
698         if (surface == entry->render_targets[i])
699         {
700             TRACE("Updated surface %p is bound as color attachment %u to the current FBO.\n", surface, i);
701             context->rebind_fbo = TRUE;
702             return;
703         }
704     }
705
706     if (surface == entry->depth_stencil)
707     {
708         TRACE("Updated surface %p is bound as depth attachment to the current FBO.\n", surface);
709         context->rebind_fbo = TRUE;
710     }
711 }
712
713 static BOOL context_set_pixel_format(const struct wined3d_gl_info *gl_info, HDC dc, int format)
714 {
715     int current = GetPixelFormat(dc);
716
717     if (current == format) return TRUE;
718
719     if (!current)
720     {
721         if (!SetPixelFormat(dc, format, NULL))
722         {
723             /* This may also happen if the dc belongs to a destroyed window. */
724             WARN("Failed to set pixel format %d on device context %p, last error %#x.\n",
725                     format, dc, GetLastError());
726             return FALSE;
727         }
728         return TRUE;
729     }
730
731     /* By default WGL doesn't allow pixel format adjustments but we need it
732      * here. For this reason there's a Wine specific wglSetPixelFormat()
733      * which allows us to set the pixel format multiple times. Only use it
734      * when really needed. */
735     if (gl_info->supported[WGL_WINE_PIXEL_FORMAT_PASSTHROUGH])
736     {
737         if (!GL_EXTCALL(wglSetPixelFormatWINE(dc, format)))
738         {
739             ERR("wglSetPixelFormatWINE failed to set pixel format %d on device context %p.\n",
740                     format, dc);
741             return FALSE;
742         }
743         return TRUE;
744     }
745
746     /* OpenGL doesn't allow pixel format adjustments. Print an error and
747      * continue using the old format. There's a big chance that the old
748      * format works although with a performance hit and perhaps rendering
749      * errors. */
750     ERR("Unable to set pixel format %d on device context %p. Already using format %d.\n",
751             format, dc, current);
752     return TRUE;
753 }
754
755 static BOOL context_set_gl_context(struct wined3d_context *ctx)
756 {
757     struct wined3d_swapchain *swapchain = ctx->swapchain;
758     BOOL backup = FALSE;
759
760     if (!context_set_pixel_format(ctx->gl_info, ctx->hdc, ctx->pixel_format))
761     {
762         WARN("Failed to set pixel format %d on device context %p.\n",
763                 ctx->pixel_format, ctx->hdc);
764         backup = TRUE;
765     }
766
767     if (backup || !wglMakeCurrent(ctx->hdc, ctx->glCtx))
768     {
769         HDC dc;
770
771         WARN("Failed to make GL context %p current on device context %p, last error %#x.\n",
772                 ctx->glCtx, ctx->hdc, GetLastError());
773         ctx->valid = 0;
774         WARN("Trying fallback to the backup window.\n");
775
776         /* FIXME: If the context is destroyed it's no longer associated with
777          * a swapchain, so we can't use the swapchain to get a backup dc. To
778          * make this work windowless contexts would need to be handled by the
779          * device. */
780         if (ctx->destroyed)
781         {
782             FIXME("Unable to get backup dc for destroyed context %p.\n", ctx);
783             context_set_current(NULL);
784             return FALSE;
785         }
786
787         if (!(dc = swapchain_get_backup_dc(swapchain)))
788         {
789             context_set_current(NULL);
790             return FALSE;
791         }
792
793         if (!context_set_pixel_format(ctx->gl_info, dc, ctx->pixel_format))
794         {
795             ERR("Failed to set pixel format %d on device context %p.\n",
796                     ctx->pixel_format, dc);
797             context_set_current(NULL);
798             return FALSE;
799         }
800
801         if (!wglMakeCurrent(dc, ctx->glCtx))
802         {
803             ERR("Fallback to backup window (dc %p) failed too, last error %#x.\n",
804                     dc, GetLastError());
805             context_set_current(NULL);
806             return FALSE;
807         }
808     }
809     return TRUE;
810 }
811
812 static void context_restore_gl_context(const struct wined3d_gl_info *gl_info, HDC dc, HGLRC gl_ctx, int pf)
813 {
814     if (!context_set_pixel_format(gl_info, dc, pf))
815     {
816         ERR("Failed to restore pixel format %d on device context %p.\n", pf, dc);
817         context_set_current(NULL);
818         return;
819     }
820
821     if (!wglMakeCurrent(dc, gl_ctx))
822     {
823         ERR("Failed to restore GL context %p on device context %p, last error %#x.\n",
824                 gl_ctx, dc, GetLastError());
825         context_set_current(NULL);
826     }
827 }
828
829 static void context_update_window(struct wined3d_context *context)
830 {
831     if (context->win_handle == context->swapchain->win_handle)
832         return;
833
834     TRACE("Updating context %p window from %p to %p.\n",
835             context, context->win_handle, context->swapchain->win_handle);
836
837     if (context->valid)
838     {
839         /* You'd figure ReleaseDC() would fail if the DC doesn't match the
840          * window. However, that's not what actually happens, and there are
841          * user32 tests that confirm ReleaseDC() with the wrong window is
842          * supposed to succeed. So explicitly check that the DC belongs to
843          * the window, since we want to avoid releasing a DC that belongs to
844          * some other window if the original window was already destroyed. */
845         if (WindowFromDC(context->hdc) != context->win_handle)
846         {
847             WARN("DC %p does not belong to window %p.\n",
848                     context->hdc, context->win_handle);
849         }
850         else if (!ReleaseDC(context->win_handle, context->hdc))
851         {
852             ERR("Failed to release device context %p, last error %#x.\n",
853                     context->hdc, GetLastError());
854         }
855     }
856     else context->valid = 1;
857
858     context->win_handle = context->swapchain->win_handle;
859
860     if (!(context->hdc = GetDC(context->win_handle)))
861     {
862         ERR("Failed to get a device context for window %p.\n", context->win_handle);
863         goto err;
864     }
865
866     if (!context_set_pixel_format(context->gl_info, context->hdc, context->pixel_format))
867     {
868         ERR("Failed to set pixel format %d on device context %p.\n",
869                 context->pixel_format, context->hdc);
870         goto err;
871     }
872
873     context_set_gl_context(context);
874
875     return;
876
877 err:
878     context->valid = 0;
879 }
880
881 /* Do not call while under the GL lock. */
882 static void context_destroy_gl_resources(struct wined3d_context *context)
883 {
884     const struct wined3d_gl_info *gl_info = context->gl_info;
885     struct wined3d_occlusion_query *occlusion_query;
886     struct wined3d_event_query *event_query;
887     struct fbo_entry *entry, *entry2;
888     HGLRC restore_ctx;
889     HDC restore_dc;
890     unsigned int i;
891     int restore_pf;
892
893     restore_ctx = wglGetCurrentContext();
894     restore_dc = wglGetCurrentDC();
895     restore_pf = GetPixelFormat(restore_dc);
896
897     if (context->valid && restore_ctx != context->glCtx)
898         context_set_gl_context(context);
899     else
900         restore_ctx = NULL;
901
902     LIST_FOR_EACH_ENTRY(occlusion_query, &context->occlusion_queries, struct wined3d_occlusion_query, entry)
903     {
904         if (context->valid && gl_info->supported[ARB_OCCLUSION_QUERY])
905             GL_EXTCALL(glDeleteQueriesARB(1, &occlusion_query->id));
906         occlusion_query->context = NULL;
907     }
908
909     LIST_FOR_EACH_ENTRY(event_query, &context->event_queries, struct wined3d_event_query, entry)
910     {
911         if (context->valid)
912         {
913             if (gl_info->supported[ARB_SYNC])
914             {
915                 if (event_query->object.sync) GL_EXTCALL(glDeleteSync(event_query->object.sync));
916             }
917             else if (gl_info->supported[APPLE_FENCE]) GL_EXTCALL(glDeleteFencesAPPLE(1, &event_query->object.id));
918             else if (gl_info->supported[NV_FENCE]) GL_EXTCALL(glDeleteFencesNV(1, &event_query->object.id));
919         }
920         event_query->context = NULL;
921     }
922
923     LIST_FOR_EACH_ENTRY_SAFE(entry, entry2, &context->fbo_destroy_list, struct fbo_entry, entry)
924     {
925         if (!context->valid) entry->id = 0;
926         context_destroy_fbo_entry(context, entry);
927     }
928
929     LIST_FOR_EACH_ENTRY_SAFE(entry, entry2, &context->fbo_list, struct fbo_entry, entry)
930     {
931         if (!context->valid) entry->id = 0;
932         context_destroy_fbo_entry(context, entry);
933     }
934
935     if (context->valid)
936     {
937         if (context->dummy_arbfp_prog)
938         {
939             GL_EXTCALL(glDeleteProgramsARB(1, &context->dummy_arbfp_prog));
940         }
941
942         if (gl_info->supported[ARB_OCCLUSION_QUERY])
943             GL_EXTCALL(glDeleteQueriesARB(context->free_occlusion_query_count, context->free_occlusion_queries));
944
945         if (gl_info->supported[ARB_SYNC])
946         {
947             for (i = 0; i < context->free_event_query_count; ++i)
948             {
949                 GL_EXTCALL(glDeleteSync(context->free_event_queries[i].sync));
950             }
951         }
952         else if (gl_info->supported[APPLE_FENCE])
953         {
954             for (i = 0; i < context->free_event_query_count; ++i)
955             {
956                 GL_EXTCALL(glDeleteFencesAPPLE(1, &context->free_event_queries[i].id));
957             }
958         }
959         else if (gl_info->supported[NV_FENCE])
960         {
961             for (i = 0; i < context->free_event_query_count; ++i)
962             {
963                 GL_EXTCALL(glDeleteFencesNV(1, &context->free_event_queries[i].id));
964             }
965         }
966
967         checkGLcall("context cleanup");
968     }
969
970     HeapFree(GetProcessHeap(), 0, context->free_occlusion_queries);
971     HeapFree(GetProcessHeap(), 0, context->free_event_queries);
972
973     if (restore_ctx)
974     {
975         context_restore_gl_context(gl_info, restore_dc, restore_ctx, restore_pf);
976     }
977     else if (wglGetCurrentContext() && !wglMakeCurrent(NULL, NULL))
978     {
979         ERR("Failed to disable GL context.\n");
980     }
981
982     ReleaseDC(context->win_handle, context->hdc);
983
984     if (!wglDeleteContext(context->glCtx))
985     {
986         DWORD err = GetLastError();
987         ERR("wglDeleteContext(%p) failed, last error %#x.\n", context->glCtx, err);
988     }
989 }
990
991 DWORD context_get_tls_idx(void)
992 {
993     return wined3d_context_tls_idx;
994 }
995
996 void context_set_tls_idx(DWORD idx)
997 {
998     wined3d_context_tls_idx = idx;
999 }
1000
1001 struct wined3d_context *context_get_current(void)
1002 {
1003     return TlsGetValue(wined3d_context_tls_idx);
1004 }
1005
1006 /* Do not call while under the GL lock. */
1007 BOOL context_set_current(struct wined3d_context *ctx)
1008 {
1009     struct wined3d_context *old = context_get_current();
1010
1011     if (old == ctx)
1012     {
1013         TRACE("Already using D3D context %p.\n", ctx);
1014         return TRUE;
1015     }
1016
1017     if (old)
1018     {
1019         if (old->destroyed)
1020         {
1021             TRACE("Switching away from destroyed context %p.\n", old);
1022             context_destroy_gl_resources(old);
1023             HeapFree(GetProcessHeap(), 0, (void *)old->gl_info);
1024             HeapFree(GetProcessHeap(), 0, old);
1025         }
1026         else
1027         {
1028             old->current = 0;
1029         }
1030     }
1031
1032     if (ctx)
1033     {
1034         if (!ctx->valid)
1035         {
1036             ERR("Trying to make invalid context %p current\n", ctx);
1037             return FALSE;
1038         }
1039
1040         TRACE("Switching to D3D context %p, GL context %p, device context %p.\n", ctx, ctx->glCtx, ctx->hdc);
1041         if (!context_set_gl_context(ctx))
1042             return FALSE;
1043         ctx->current = 1;
1044     }
1045     else if(wglGetCurrentContext())
1046     {
1047         TRACE("Clearing current D3D context.\n");
1048         if (!wglMakeCurrent(NULL, NULL))
1049         {
1050             DWORD err = GetLastError();
1051             ERR("Failed to clear current GL context, last error %#x.\n", err);
1052             TlsSetValue(wined3d_context_tls_idx, NULL);
1053             return FALSE;
1054         }
1055     }
1056
1057     return TlsSetValue(wined3d_context_tls_idx, ctx);
1058 }
1059
1060 void context_release(struct wined3d_context *context)
1061 {
1062     TRACE("Releasing context %p, level %u.\n", context, context->level);
1063
1064     if (WARN_ON(d3d))
1065     {
1066         if (!context->level)
1067             WARN("Context %p is not active.\n", context);
1068         else if (context != context_get_current())
1069             WARN("Context %p is not the current context.\n", context);
1070     }
1071
1072     if (!--context->level && context->restore_ctx)
1073     {
1074         TRACE("Restoring GL context %p on device context %p.\n", context->restore_ctx, context->restore_dc);
1075         context_restore_gl_context(context->gl_info, context->restore_dc, context->restore_ctx, context->restore_pf);
1076         context->restore_ctx = NULL;
1077         context->restore_dc = NULL;
1078     }
1079 }
1080
1081 static void context_enter(struct wined3d_context *context)
1082 {
1083     TRACE("Entering context %p, level %u.\n", context, context->level + 1);
1084
1085     if (!context->level++)
1086     {
1087         const struct wined3d_context *current_context = context_get_current();
1088         HGLRC current_gl = wglGetCurrentContext();
1089
1090         if (current_gl && (!current_context || current_context->glCtx != current_gl))
1091         {
1092             TRACE("Another GL context (%p on device context %p) is already current.\n",
1093                     current_gl, wglGetCurrentDC());
1094             context->restore_ctx = current_gl;
1095             context->restore_dc = wglGetCurrentDC();
1096             context->restore_pf = GetPixelFormat(context->restore_dc);
1097         }
1098     }
1099 }
1100
1101 void context_invalidate_state(struct wined3d_context *context, DWORD state)
1102 {
1103     DWORD rep = context->state_table[state].representative;
1104     DWORD idx;
1105     BYTE shift;
1106
1107     if (isStateDirty(context, rep)) return;
1108
1109     context->dirtyArray[context->numDirtyEntries++] = rep;
1110     idx = rep / (sizeof(*context->isStateDirty) * CHAR_BIT);
1111     shift = rep & ((sizeof(*context->isStateDirty) * CHAR_BIT) - 1);
1112     context->isStateDirty[idx] |= (1 << shift);
1113 }
1114
1115 /* This function takes care of wined3d pixel format selection. */
1116 static int context_choose_pixel_format(const struct wined3d_device *device, HDC hdc,
1117         const struct wined3d_format *color_format, const struct wined3d_format *ds_format,
1118         BOOL auxBuffers, BOOL findCompatible)
1119 {
1120     int iPixelFormat=0;
1121     BYTE redBits, greenBits, blueBits, alphaBits, colorBits;
1122     BYTE depthBits=0, stencilBits=0;
1123     unsigned int current_value;
1124     unsigned int cfg_count = device->adapter->cfg_count;
1125     unsigned int i;
1126
1127     TRACE("device %p, dc %p, color_format %s, ds_format %s, aux_buffers %#x, find_compatible %#x.\n",
1128             device, hdc, debug_d3dformat(color_format->id), debug_d3dformat(ds_format->id),
1129             auxBuffers, findCompatible);
1130
1131     if (!getColorBits(color_format, &redBits, &greenBits, &blueBits, &alphaBits, &colorBits))
1132     {
1133         ERR("Unable to get color bits for format %s (%#x)!\n",
1134                 debug_d3dformat(color_format->id), color_format->id);
1135         return 0;
1136     }
1137
1138     getDepthStencilBits(ds_format, &depthBits, &stencilBits);
1139
1140     current_value = 0;
1141     for (i = 0; i < cfg_count; ++i)
1142     {
1143         const struct wined3d_pixel_format *cfg = &device->adapter->cfgs[i];
1144         unsigned int value;
1145
1146         /* For now only accept RGBA formats. Perhaps some day we will
1147          * allow floating point formats for pbuffers. */
1148         if (cfg->iPixelType != WGL_TYPE_RGBA_ARB)
1149             continue;
1150         /* In window mode we need a window drawable format and double buffering. */
1151         if (!(cfg->windowDrawable && cfg->doubleBuffer))
1152             continue;
1153         if (cfg->redSize < redBits)
1154             continue;
1155         if (cfg->greenSize < greenBits)
1156             continue;
1157         if (cfg->blueSize < blueBits)
1158             continue;
1159         if (cfg->alphaSize < alphaBits)
1160             continue;
1161         if (cfg->depthSize < depthBits)
1162             continue;
1163         if (stencilBits && cfg->stencilSize != stencilBits)
1164             continue;
1165         /* Check multisampling support. */
1166         if (cfg->numSamples)
1167             continue;
1168
1169         value = 1;
1170         /* We try to locate a format which matches our requirements exactly. In case of
1171          * depth it is no problem to emulate 16-bit using e.g. 24-bit, so accept that. */
1172         if (cfg->depthSize == depthBits)
1173             value += 1;
1174         if (cfg->stencilSize == stencilBits)
1175             value += 2;
1176         if (cfg->alphaSize == alphaBits)
1177             value += 4;
1178         /* We like to have aux buffers in backbuffer mode */
1179         if (auxBuffers && cfg->auxBuffers)
1180             value += 8;
1181         if (cfg->redSize == redBits
1182                 && cfg->greenSize == greenBits
1183                 && cfg->blueSize == blueBits)
1184             value += 16;
1185
1186         if (value > current_value)
1187         {
1188             iPixelFormat = cfg->iPixelFormat;
1189             current_value = value;
1190         }
1191     }
1192
1193     /* When findCompatible is set and no suitable format was found, let ChoosePixelFormat choose a pixel format in order not to crash. */
1194     if(!iPixelFormat && !findCompatible) {
1195         ERR("Can't find a suitable iPixelFormat\n");
1196         return FALSE;
1197     } else if(!iPixelFormat) {
1198         PIXELFORMATDESCRIPTOR pfd;
1199
1200         TRACE("Falling back to ChoosePixelFormat as we weren't able to find an exactly matching pixel format\n");
1201         /* PixelFormat selection */
1202         ZeroMemory(&pfd, sizeof(pfd));
1203         pfd.nSize      = sizeof(pfd);
1204         pfd.nVersion   = 1;
1205         pfd.dwFlags    = PFD_SUPPORT_OPENGL | PFD_DOUBLEBUFFER | PFD_DRAW_TO_WINDOW;/*PFD_GENERIC_ACCELERATED*/
1206         pfd.iPixelType = PFD_TYPE_RGBA;
1207         pfd.cAlphaBits = alphaBits;
1208         pfd.cColorBits = colorBits;
1209         pfd.cDepthBits = depthBits;
1210         pfd.cStencilBits = stencilBits;
1211         pfd.iLayerType = PFD_MAIN_PLANE;
1212
1213         iPixelFormat = ChoosePixelFormat(hdc, &pfd);
1214         if(!iPixelFormat) {
1215             /* If this happens something is very wrong as ChoosePixelFormat barely fails */
1216             ERR("Can't find a suitable iPixelFormat\n");
1217             return FALSE;
1218         }
1219     }
1220
1221     TRACE("Found iPixelFormat=%d for ColorFormat=%s, DepthStencilFormat=%s\n",
1222             iPixelFormat, debug_d3dformat(color_format->id), debug_d3dformat(ds_format->id));
1223     return iPixelFormat;
1224 }
1225
1226 /* Context activation is done by the caller. */
1227 static void bind_dummy_textures(const struct wined3d_device *device, const struct wined3d_context *context)
1228 {
1229     const struct wined3d_gl_info *gl_info = context->gl_info;
1230     unsigned int i, count = min(MAX_COMBINED_SAMPLERS, gl_info->limits.combined_samplers);
1231
1232     for (i = 0; i < count; ++i)
1233     {
1234         GL_EXTCALL(glActiveTextureARB(GL_TEXTURE0_ARB + i));
1235         checkGLcall("glActiveTextureARB");
1236
1237         gl_info->gl_ops.gl.p_glBindTexture(GL_TEXTURE_2D, device->dummy_texture_2d[i]);
1238         checkGLcall("glBindTexture");
1239
1240         if (gl_info->supported[ARB_TEXTURE_RECTANGLE])
1241         {
1242             gl_info->gl_ops.gl.p_glBindTexture(GL_TEXTURE_RECTANGLE_ARB, device->dummy_texture_rect[i]);
1243             checkGLcall("glBindTexture");
1244         }
1245
1246         if (gl_info->supported[EXT_TEXTURE3D])
1247         {
1248             gl_info->gl_ops.gl.p_glBindTexture(GL_TEXTURE_3D, device->dummy_texture_3d[i]);
1249             checkGLcall("glBindTexture");
1250         }
1251
1252         if (gl_info->supported[ARB_TEXTURE_CUBE_MAP])
1253         {
1254             gl_info->gl_ops.gl.p_glBindTexture(GL_TEXTURE_CUBE_MAP, device->dummy_texture_cube[i]);
1255             checkGLcall("glBindTexture");
1256         }
1257     }
1258 }
1259
1260 /* Do not call while under the GL lock. */
1261 struct wined3d_context *context_create(struct wined3d_swapchain *swapchain,
1262         struct wined3d_surface *target, const struct wined3d_format *ds_format)
1263 {
1264     struct wined3d_device *device = swapchain->device;
1265     const struct wined3d_gl_info *gl_info = &device->adapter->gl_info;
1266     const struct wined3d_format *color_format;
1267     struct wined3d_context *ret;
1268     BOOL auxBuffers = FALSE;
1269     int pixel_format;
1270     unsigned int s;
1271     int swap_interval;
1272     DWORD state;
1273     HGLRC ctx;
1274     HDC hdc;
1275
1276     TRACE("swapchain %p, target %p, window %p.\n", swapchain, target, swapchain->win_handle);
1277
1278     ret = HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, sizeof(*ret));
1279     if (!ret)
1280     {
1281         ERR("Failed to allocate context memory.\n");
1282         return NULL;
1283     }
1284
1285     ret->blit_targets = HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY,
1286             gl_info->limits.buffers * sizeof(*ret->blit_targets));
1287     if (!ret->blit_targets)
1288         goto out;
1289
1290     ret->draw_buffers = HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY,
1291             gl_info->limits.buffers * sizeof(*ret->draw_buffers));
1292     if (!ret->draw_buffers)
1293         goto out;
1294
1295     ret->free_occlusion_query_size = 4;
1296     ret->free_occlusion_queries = HeapAlloc(GetProcessHeap(), 0,
1297             ret->free_occlusion_query_size * sizeof(*ret->free_occlusion_queries));
1298     if (!ret->free_occlusion_queries)
1299         goto out;
1300
1301     list_init(&ret->occlusion_queries);
1302
1303     ret->free_event_query_size = 4;
1304     ret->free_event_queries = HeapAlloc(GetProcessHeap(), 0,
1305             ret->free_event_query_size * sizeof(*ret->free_event_queries));
1306     if (!ret->free_event_queries)
1307         goto out;
1308
1309     list_init(&ret->event_queries);
1310     list_init(&ret->fbo_list);
1311     list_init(&ret->fbo_destroy_list);
1312
1313     if (!(hdc = GetDC(swapchain->win_handle)))
1314     {
1315         WARN("Failed to retireve device context, trying swapchain backup.\n");
1316
1317         if (!(hdc = swapchain_get_backup_dc(swapchain)))
1318         {
1319             ERR("Failed to retrieve a device context.\n");
1320             goto out;
1321         }
1322     }
1323
1324     color_format = target->resource.format;
1325
1326     /* In case of ORM_BACKBUFFER, make sure to request an alpha component for
1327      * X4R4G4B4/X8R8G8B8 as we might need it for the backbuffer. */
1328     if (wined3d_settings.offscreen_rendering_mode == ORM_BACKBUFFER)
1329     {
1330         auxBuffers = TRUE;
1331
1332         if (color_format->id == WINED3DFMT_B4G4R4X4_UNORM)
1333             color_format = wined3d_get_format(gl_info, WINED3DFMT_B4G4R4A4_UNORM);
1334         else if (color_format->id == WINED3DFMT_B8G8R8X8_UNORM)
1335             color_format = wined3d_get_format(gl_info, WINED3DFMT_B8G8R8A8_UNORM);
1336     }
1337
1338     /* DirectDraw supports 8bit paletted render targets and these are used by
1339      * old games like StarCraft and C&C. Most modern hardware doesn't support
1340      * 8bit natively so we perform some form of 8bit -> 32bit conversion. The
1341      * conversion (ab)uses the alpha component for storing the palette index.
1342      * For this reason we require a format with 8bit alpha, so request
1343      * A8R8G8B8. */
1344     if (color_format->id == WINED3DFMT_P8_UINT)
1345         color_format = wined3d_get_format(gl_info, WINED3DFMT_B8G8R8A8_UNORM);
1346
1347     /* Try to find a pixel format which matches our requirements. */
1348     pixel_format = context_choose_pixel_format(device, hdc, color_format, ds_format, auxBuffers, FALSE);
1349
1350     /* Try to locate a compatible format if we weren't able to find anything. */
1351     if (!pixel_format)
1352     {
1353         TRACE("Trying to locate a compatible pixel format because an exact match failed.\n");
1354         pixel_format = context_choose_pixel_format(device, hdc, color_format, ds_format, auxBuffers, TRUE);
1355     }
1356
1357     /* If we still don't have a pixel format, something is very wrong as ChoosePixelFormat barely fails */
1358     if (!pixel_format)
1359     {
1360         ERR("Can't find a suitable pixel format.\n");
1361         goto out;
1362     }
1363
1364     context_enter(ret);
1365
1366     if (!context_set_pixel_format(gl_info, hdc, pixel_format))
1367     {
1368         ERR("Failed to set pixel format %d on device context %p.\n", pixel_format, hdc);
1369         context_release(ret);
1370         goto out;
1371     }
1372
1373     if (!(ctx = wglCreateContext(hdc)))
1374     {
1375         ERR("Failed to create a WGL context.\n");
1376         context_release(ret);
1377         goto out;
1378     }
1379
1380     if (device->context_count)
1381     {
1382         if (!wglShareLists(device->contexts[0]->glCtx, ctx))
1383         {
1384             ERR("wglShareLists(%p, %p) failed, last error %#x.\n",
1385                     device->contexts[0]->glCtx, ctx, GetLastError());
1386             context_release(ret);
1387             if (!wglDeleteContext(ctx))
1388                 ERR("wglDeleteContext(%p) failed, last error %#x.\n", ctx, GetLastError());
1389             goto out;
1390         }
1391     }
1392
1393     if (!device_context_add(device, ret))
1394     {
1395         ERR("Failed to add the newly created context to the context list\n");
1396         context_release(ret);
1397         if (!wglDeleteContext(ctx))
1398             ERR("wglDeleteContext(%p) failed, last error %#x.\n", ctx, GetLastError());
1399         goto out;
1400     }
1401
1402     ret->gl_info = gl_info;
1403     ret->state_table = device->StateTable;
1404
1405     /* Mark all states dirty to force a proper initialization of the states
1406      * on the first use of the context. */
1407     for (state = 0; state <= STATE_HIGHEST; ++state)
1408     {
1409         if (ret->state_table[state].representative)
1410             context_invalidate_state(ret, state);
1411     }
1412
1413     ret->swapchain = swapchain;
1414     ret->current_rt = target;
1415     ret->tid = GetCurrentThreadId();
1416
1417     ret->render_offscreen = surface_is_offscreen(target);
1418     ret->draw_buffers_mask = context_generate_rt_mask(GL_BACK);
1419     ret->valid = 1;
1420
1421     ret->glCtx = ctx;
1422     ret->win_handle = swapchain->win_handle;
1423     ret->hdc = hdc;
1424     ret->pixel_format = pixel_format;
1425
1426     /* Set up the context defaults */
1427     if (!context_set_current(ret))
1428     {
1429         ERR("Cannot activate context to set up defaults.\n");
1430         device_context_remove(device, ret);
1431         context_release(ret);
1432         if (!wglDeleteContext(ctx))
1433             ERR("wglDeleteContext(%p) failed, last error %#x.\n", ctx, GetLastError());
1434         goto out;
1435     }
1436
1437     switch (swapchain->desc.swap_interval)
1438     {
1439         case WINED3DPRESENT_INTERVAL_IMMEDIATE:
1440             swap_interval = 0;
1441             break;
1442         case WINED3DPRESENT_INTERVAL_DEFAULT:
1443         case WINED3DPRESENT_INTERVAL_ONE:
1444             swap_interval = 1;
1445             break;
1446         case WINED3DPRESENT_INTERVAL_TWO:
1447             swap_interval = 2;
1448             break;
1449         case WINED3DPRESENT_INTERVAL_THREE:
1450             swap_interval = 3;
1451             break;
1452         case WINED3DPRESENT_INTERVAL_FOUR:
1453             swap_interval = 4;
1454             break;
1455         default:
1456             FIXME("Unknown swap interval %#x.\n", swapchain->desc.swap_interval);
1457             swap_interval = 1;
1458     }
1459
1460     if (gl_info->supported[WGL_EXT_SWAP_CONTROL])
1461     {
1462         if (!GL_EXTCALL(wglSwapIntervalEXT(swap_interval)))
1463             ERR("wglSwapIntervalEXT failed to set swap interval %d for context %p, last error %#x\n",
1464                 swap_interval, ret, GetLastError());
1465     }
1466
1467     gl_info->gl_ops.gl.p_glGetIntegerv(GL_AUX_BUFFERS, &ret->aux_buffers);
1468
1469     TRACE("Setting up the screen\n");
1470     /* Clear the screen */
1471     gl_info->gl_ops.gl.p_glClearColor(1.0f, 0.0f, 0.0f, 0.0f);
1472     checkGLcall("glClearColor");
1473     gl_info->gl_ops.gl.p_glClearIndex(0);
1474     gl_info->gl_ops.gl.p_glClearDepth(1);
1475     gl_info->gl_ops.gl.p_glClearStencil(0xffff);
1476
1477     checkGLcall("glClear");
1478
1479     gl_info->gl_ops.gl.p_glLightModeli(GL_LIGHT_MODEL_LOCAL_VIEWER, GL_TRUE);
1480     checkGLcall("glLightModeli(GL_LIGHT_MODEL_LOCAL_VIEWER, GL_TRUE);");
1481
1482     gl_info->gl_ops.gl.p_glTexEnvf(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_COMBINE_EXT);
1483     checkGLcall("glTexEnvf(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_COMBINE_EXT);");
1484
1485     gl_info->gl_ops.gl.p_glLightModeli(GL_LIGHT_MODEL_COLOR_CONTROL, GL_SEPARATE_SPECULAR_COLOR);
1486     checkGLcall("glLightModeli(GL_LIGHT_MODEL_COLOR_CONTROL, GL_SEPARATE_SPECULAR_COLOR);");
1487
1488     gl_info->gl_ops.gl.p_glPixelStorei(GL_PACK_ALIGNMENT, device->surface_alignment);
1489     checkGLcall("glPixelStorei(GL_PACK_ALIGNMENT, device->surface_alignment);");
1490     gl_info->gl_ops.gl.p_glPixelStorei(GL_UNPACK_ALIGNMENT, device->surface_alignment);
1491     checkGLcall("glPixelStorei(GL_UNPACK_ALIGNMENT, device->surface_alignment);");
1492
1493     if (gl_info->supported[APPLE_CLIENT_STORAGE])
1494     {
1495         /* Most textures will use client storage if supported. Exceptions are
1496          * non-native power of 2 textures and textures in DIB sections. */
1497         gl_info->gl_ops.gl.p_glPixelStorei(GL_UNPACK_CLIENT_STORAGE_APPLE, GL_TRUE);
1498         checkGLcall("glPixelStorei(GL_UNPACK_CLIENT_STORAGE_APPLE, GL_TRUE)");
1499     }
1500     if (gl_info->supported[ARB_VERTEX_BLEND])
1501     {
1502         /* Direct3D always uses n-1 weights for n world matrices and uses
1503          * 1 - sum for the last one this is equal to GL_WEIGHT_SUM_UNITY_ARB.
1504          * Enabling it doesn't do anything unless GL_VERTEX_BLEND_ARB isn't
1505          * enabled as well. */
1506         gl_info->gl_ops.gl.p_glEnable(GL_WEIGHT_SUM_UNITY_ARB);
1507         checkGLcall("glEnable(GL_WEIGHT_SUM_UNITY_ARB)");
1508     }
1509     if (gl_info->supported[NV_TEXTURE_SHADER2])
1510     {
1511         /* Set up the previous texture input for all shader units. This applies to bump mapping, and in d3d
1512          * the previous texture where to source the offset from is always unit - 1.
1513          */
1514         for (s = 1; s < gl_info->limits.textures; ++s)
1515         {
1516             context_active_texture(ret, gl_info, s);
1517             gl_info->gl_ops.gl.p_glTexEnvi(GL_TEXTURE_SHADER_NV,
1518                     GL_PREVIOUS_TEXTURE_INPUT_NV, GL_TEXTURE0_ARB + s - 1);
1519             checkGLcall("glTexEnvi(GL_TEXTURE_SHADER_NV, GL_PREVIOUS_TEXTURE_INPUT_NV, ...");
1520         }
1521     }
1522     if (gl_info->supported[ARB_FRAGMENT_PROGRAM])
1523     {
1524         /* MacOS(radeon X1600 at least, but most likely others too) refuses to draw if GLSL and ARBFP are
1525          * enabled, but the currently bound arbfp program is 0. Enabling ARBFP with prog 0 is invalid, but
1526          * GLSL should bypass this. This causes problems in programs that never use the fixed function pipeline,
1527          * because the ARBFP extension is enabled by the ARBFP pipeline at context creation, but no program
1528          * is ever assigned.
1529          *
1530          * So make sure a program is assigned to each context. The first real ARBFP use will set a different
1531          * program and the dummy program is destroyed when the context is destroyed.
1532          */
1533         const char *dummy_program =
1534                 "!!ARBfp1.0\n"
1535                 "MOV result.color, fragment.color.primary;\n"
1536                 "END\n";
1537         GL_EXTCALL(glGenProgramsARB(1, &ret->dummy_arbfp_prog));
1538         GL_EXTCALL(glBindProgramARB(GL_FRAGMENT_PROGRAM_ARB, ret->dummy_arbfp_prog));
1539         GL_EXTCALL(glProgramStringARB(GL_FRAGMENT_PROGRAM_ARB, GL_PROGRAM_FORMAT_ASCII_ARB, strlen(dummy_program), dummy_program));
1540     }
1541
1542     if (gl_info->supported[ARB_POINT_SPRITE])
1543     {
1544         for (s = 0; s < gl_info->limits.textures; ++s)
1545         {
1546             context_active_texture(ret, gl_info, s);
1547             gl_info->gl_ops.gl.p_glTexEnvi(GL_POINT_SPRITE_ARB, GL_COORD_REPLACE_ARB, GL_TRUE);
1548             checkGLcall("glTexEnvi(GL_POINT_SPRITE_ARB, GL_COORD_REPLACE_ARB, GL_TRUE)");
1549         }
1550     }
1551
1552     if (gl_info->supported[ARB_PROVOKING_VERTEX])
1553     {
1554         GL_EXTCALL(glProvokingVertex(GL_FIRST_VERTEX_CONVENTION));
1555     }
1556     else if (gl_info->supported[EXT_PROVOKING_VERTEX])
1557     {
1558         GL_EXTCALL(glProvokingVertexEXT(GL_FIRST_VERTEX_CONVENTION_EXT));
1559     }
1560     ret->select_shader = 1;
1561
1562     /* If this happens to be the first context for the device, dummy textures
1563      * are not created yet. In that case, they will be created (and bound) by
1564      * create_dummy_textures right after this context is initialized. */
1565     if (device->dummy_texture_2d[0])
1566         bind_dummy_textures(device, ret);
1567
1568     TRACE("Created context %p.\n", ret);
1569
1570     return ret;
1571
1572 out:
1573     HeapFree(GetProcessHeap(), 0, ret->free_event_queries);
1574     HeapFree(GetProcessHeap(), 0, ret->free_occlusion_queries);
1575     HeapFree(GetProcessHeap(), 0, ret->draw_buffers);
1576     HeapFree(GetProcessHeap(), 0, ret->blit_targets);
1577     HeapFree(GetProcessHeap(), 0, ret);
1578     return NULL;
1579 }
1580
1581 /* Do not call while under the GL lock. */
1582 void context_destroy(struct wined3d_device *device, struct wined3d_context *context)
1583 {
1584     BOOL destroy;
1585
1586     TRACE("Destroying ctx %p\n", context);
1587
1588     if (context->tid == GetCurrentThreadId() || !context->current)
1589     {
1590         context_destroy_gl_resources(context);
1591         TlsSetValue(wined3d_context_tls_idx, NULL);
1592         destroy = TRUE;
1593     }
1594     else
1595     {
1596         /* Make a copy of gl_info for context_destroy_gl_resources use, the one
1597            in wined3d_adapter may go away in the meantime */
1598         struct wined3d_gl_info *gl_info = HeapAlloc(GetProcessHeap(), 0, sizeof(*gl_info));
1599         *gl_info = *context->gl_info;
1600         context->gl_info = gl_info;
1601         context->destroyed = 1;
1602         destroy = FALSE;
1603     }
1604
1605     HeapFree(GetProcessHeap(), 0, context->draw_buffers);
1606     HeapFree(GetProcessHeap(), 0, context->blit_targets);
1607     device_context_remove(device, context);
1608     if (destroy) HeapFree(GetProcessHeap(), 0, context);
1609 }
1610
1611 /* Context activation is done by the caller. */
1612 static void set_blit_dimension(const struct wined3d_gl_info *gl_info, UINT width, UINT height)
1613 {
1614     const GLdouble projection[] =
1615     {
1616         2.0 / width,          0.0,  0.0, 0.0,
1617                 0.0, 2.0 / height,  0.0, 0.0,
1618                 0.0,          0.0,  2.0, 0.0,
1619                -1.0,         -1.0, -1.0, 1.0,
1620     };
1621
1622     gl_info->gl_ops.gl.p_glMatrixMode(GL_PROJECTION);
1623     checkGLcall("glMatrixMode(GL_PROJECTION)");
1624     gl_info->gl_ops.gl.p_glLoadMatrixd(projection);
1625     checkGLcall("glLoadMatrixd");
1626     gl_info->gl_ops.gl.p_glViewport(0, 0, width, height);
1627     checkGLcall("glViewport");
1628 }
1629
1630 static void context_get_rt_size(const struct wined3d_context *context, SIZE *size)
1631 {
1632     const struct wined3d_surface *rt = context->current_rt;
1633
1634     if (rt->container.type == WINED3D_CONTAINER_SWAPCHAIN
1635             && rt->container.u.swapchain->front_buffer == rt)
1636     {
1637         RECT window_size;
1638
1639         GetClientRect(context->win_handle, &window_size);
1640         size->cx = window_size.right - window_size.left;
1641         size->cy = window_size.bottom - window_size.top;
1642
1643         return;
1644     }
1645
1646     size->cx = rt->resource.width;
1647     size->cy = rt->resource.height;
1648 }
1649
1650 /*****************************************************************************
1651  * SetupForBlit
1652  *
1653  * Sets up a context for DirectDraw blitting.
1654  * All texture units are disabled, texture unit 0 is set as current unit
1655  * fog, lighting, blending, alpha test, z test, scissor test, culling disabled
1656  * color writing enabled for all channels
1657  * register combiners disabled, shaders disabled
1658  * world matrix is set to identity, texture matrix 0 too
1659  * projection matrix is setup for drawing screen coordinates
1660  *
1661  * Params:
1662  *  This: Device to activate the context for
1663  *  context: Context to setup
1664  *
1665  *****************************************************************************/
1666 /* Context activation is done by the caller. */
1667 static void SetupForBlit(const struct wined3d_device *device, struct wined3d_context *context)
1668 {
1669     int i;
1670     const struct wined3d_gl_info *gl_info = context->gl_info;
1671     DWORD sampler;
1672     SIZE rt_size;
1673
1674     TRACE("Setting up context %p for blitting\n", context);
1675
1676     context_get_rt_size(context, &rt_size);
1677
1678     if (context->last_was_blit)
1679     {
1680         if (context->blit_w != rt_size.cx || context->blit_h != rt_size.cy)
1681         {
1682             set_blit_dimension(gl_info, rt_size.cx, rt_size.cy);
1683             context->blit_w = rt_size.cx;
1684             context->blit_h = rt_size.cy;
1685             /* No need to dirtify here, the states are still dirtified because
1686              * they weren't applied since the last SetupForBlit() call. */
1687         }
1688         TRACE("Context is already set up for blitting, nothing to do\n");
1689         return;
1690     }
1691     context->last_was_blit = TRUE;
1692
1693     /* Disable all textures. The caller can then bind a texture it wants to blit
1694      * from
1695      *
1696      * The blitting code uses (for now) the fixed function pipeline, so make sure to reset all fixed
1697      * function texture unit. No need to care for higher samplers
1698      */
1699     for (i = gl_info->limits.textures - 1; i > 0 ; --i)
1700     {
1701         sampler = device->rev_tex_unit_map[i];
1702         context_active_texture(context, gl_info, i);
1703
1704         if (gl_info->supported[ARB_TEXTURE_CUBE_MAP])
1705         {
1706             gl_info->gl_ops.gl.p_glDisable(GL_TEXTURE_CUBE_MAP_ARB);
1707             checkGLcall("glDisable GL_TEXTURE_CUBE_MAP_ARB");
1708         }
1709         gl_info->gl_ops.gl.p_glDisable(GL_TEXTURE_3D);
1710         checkGLcall("glDisable GL_TEXTURE_3D");
1711         if (gl_info->supported[ARB_TEXTURE_RECTANGLE])
1712         {
1713             gl_info->gl_ops.gl.p_glDisable(GL_TEXTURE_RECTANGLE_ARB);
1714             checkGLcall("glDisable GL_TEXTURE_RECTANGLE_ARB");
1715         }
1716         gl_info->gl_ops.gl.p_glDisable(GL_TEXTURE_2D);
1717         checkGLcall("glDisable GL_TEXTURE_2D");
1718
1719         gl_info->gl_ops.gl.p_glTexEnvi(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_REPLACE);
1720         checkGLcall("glTexEnvi(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_REPLACE);");
1721
1722         if (sampler != WINED3D_UNMAPPED_STAGE)
1723         {
1724             if (sampler < MAX_TEXTURES)
1725                 context_invalidate_state(context, STATE_TEXTURESTAGE(sampler, WINED3D_TSS_COLOR_OP));
1726             context_invalidate_state(context, STATE_SAMPLER(sampler));
1727         }
1728     }
1729     context_active_texture(context, gl_info, 0);
1730
1731     sampler = device->rev_tex_unit_map[0];
1732
1733     if (gl_info->supported[ARB_TEXTURE_CUBE_MAP])
1734     {
1735         gl_info->gl_ops.gl.p_glDisable(GL_TEXTURE_CUBE_MAP_ARB);
1736         checkGLcall("glDisable GL_TEXTURE_CUBE_MAP_ARB");
1737     }
1738     gl_info->gl_ops.gl.p_glDisable(GL_TEXTURE_3D);
1739     checkGLcall("glDisable GL_TEXTURE_3D");
1740     if (gl_info->supported[ARB_TEXTURE_RECTANGLE])
1741     {
1742         gl_info->gl_ops.gl.p_glDisable(GL_TEXTURE_RECTANGLE_ARB);
1743         checkGLcall("glDisable GL_TEXTURE_RECTANGLE_ARB");
1744     }
1745     gl_info->gl_ops.gl.p_glDisable(GL_TEXTURE_2D);
1746     checkGLcall("glDisable GL_TEXTURE_2D");
1747
1748     gl_info->gl_ops.gl.p_glTexEnvi(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_REPLACE);
1749
1750     gl_info->gl_ops.gl.p_glMatrixMode(GL_TEXTURE);
1751     checkGLcall("glMatrixMode(GL_TEXTURE)");
1752     gl_info->gl_ops.gl.p_glLoadIdentity();
1753     checkGLcall("glLoadIdentity()");
1754
1755     if (gl_info->supported[EXT_TEXTURE_LOD_BIAS])
1756     {
1757         gl_info->gl_ops.gl.p_glTexEnvf(GL_TEXTURE_FILTER_CONTROL_EXT,
1758                 GL_TEXTURE_LOD_BIAS_EXT, 0.0f);
1759         checkGLcall("glTexEnvf GL_TEXTURE_LOD_BIAS_EXT ...");
1760     }
1761
1762     if (sampler != WINED3D_UNMAPPED_STAGE)
1763     {
1764         if (sampler < MAX_TEXTURES)
1765         {
1766             context_invalidate_state(context, STATE_TRANSFORM(WINED3D_TS_TEXTURE0 + sampler));
1767             context_invalidate_state(context, STATE_TEXTURESTAGE(sampler, WINED3D_TSS_COLOR_OP));
1768         }
1769         context_invalidate_state(context, STATE_SAMPLER(sampler));
1770     }
1771
1772     /* Other misc states */
1773     gl_info->gl_ops.gl.p_glDisable(GL_ALPHA_TEST);
1774     checkGLcall("glDisable(GL_ALPHA_TEST)");
1775     context_invalidate_state(context, STATE_RENDER(WINED3D_RS_ALPHATESTENABLE));
1776     gl_info->gl_ops.gl.p_glDisable(GL_LIGHTING);
1777     checkGLcall("glDisable GL_LIGHTING");
1778     context_invalidate_state(context, STATE_RENDER(WINED3D_RS_LIGHTING));
1779     gl_info->gl_ops.gl.p_glDisable(GL_DEPTH_TEST);
1780     checkGLcall("glDisable GL_DEPTH_TEST");
1781     context_invalidate_state(context, STATE_RENDER(WINED3D_RS_ZENABLE));
1782     glDisableWINE(GL_FOG);
1783     checkGLcall("glDisable GL_FOG");
1784     context_invalidate_state(context, STATE_RENDER(WINED3D_RS_FOGENABLE));
1785     gl_info->gl_ops.gl.p_glDisable(GL_BLEND);
1786     checkGLcall("glDisable GL_BLEND");
1787     context_invalidate_state(context, STATE_RENDER(WINED3D_RS_ALPHABLENDENABLE));
1788     gl_info->gl_ops.gl.p_glDisable(GL_CULL_FACE);
1789     checkGLcall("glDisable GL_CULL_FACE");
1790     context_invalidate_state(context, STATE_RENDER(WINED3D_RS_CULLMODE));
1791     gl_info->gl_ops.gl.p_glDisable(GL_STENCIL_TEST);
1792     checkGLcall("glDisable GL_STENCIL_TEST");
1793     context_invalidate_state(context, STATE_RENDER(WINED3D_RS_STENCILENABLE));
1794     gl_info->gl_ops.gl.p_glDisable(GL_SCISSOR_TEST);
1795     checkGLcall("glDisable GL_SCISSOR_TEST");
1796     context_invalidate_state(context, STATE_RENDER(WINED3D_RS_SCISSORTESTENABLE));
1797     if (gl_info->supported[ARB_POINT_SPRITE])
1798     {
1799         gl_info->gl_ops.gl.p_glDisable(GL_POINT_SPRITE_ARB);
1800         checkGLcall("glDisable GL_POINT_SPRITE_ARB");
1801         context_invalidate_state(context, STATE_RENDER(WINED3D_RS_POINTSPRITEENABLE));
1802     }
1803     gl_info->gl_ops.gl.p_glColorMask(GL_TRUE, GL_TRUE,GL_TRUE,GL_TRUE);
1804     checkGLcall("glColorMask");
1805     context_invalidate_state(context, STATE_RENDER(WINED3D_RS_COLORWRITEENABLE));
1806     context_invalidate_state(context, STATE_RENDER(WINED3D_RS_COLORWRITEENABLE1));
1807     context_invalidate_state(context, STATE_RENDER(WINED3D_RS_COLORWRITEENABLE2));
1808     context_invalidate_state(context, STATE_RENDER(WINED3D_RS_COLORWRITEENABLE3));
1809     if (gl_info->supported[EXT_SECONDARY_COLOR])
1810     {
1811         gl_info->gl_ops.gl.p_glDisable(GL_COLOR_SUM_EXT);
1812         context_invalidate_state(context, STATE_RENDER(WINED3D_RS_SPECULARENABLE));
1813         checkGLcall("glDisable(GL_COLOR_SUM_EXT)");
1814     }
1815
1816     /* Setup transforms */
1817     gl_info->gl_ops.gl.p_glMatrixMode(GL_MODELVIEW);
1818     checkGLcall("glMatrixMode(GL_MODELVIEW)");
1819     gl_info->gl_ops.gl.p_glLoadIdentity();
1820     checkGLcall("glLoadIdentity()");
1821     context_invalidate_state(context, STATE_TRANSFORM(WINED3D_TS_WORLD_MATRIX(0)));
1822
1823     context->last_was_rhw = TRUE;
1824     context_invalidate_state(context, STATE_VDECL); /* because of last_was_rhw = TRUE */
1825
1826     gl_info->gl_ops.gl.p_glDisable(GL_CLIP_PLANE0); checkGLcall("glDisable(clip plane 0)");
1827     gl_info->gl_ops.gl.p_glDisable(GL_CLIP_PLANE1); checkGLcall("glDisable(clip plane 1)");
1828     gl_info->gl_ops.gl.p_glDisable(GL_CLIP_PLANE2); checkGLcall("glDisable(clip plane 2)");
1829     gl_info->gl_ops.gl.p_glDisable(GL_CLIP_PLANE3); checkGLcall("glDisable(clip plane 3)");
1830     gl_info->gl_ops.gl.p_glDisable(GL_CLIP_PLANE4); checkGLcall("glDisable(clip plane 4)");
1831     gl_info->gl_ops.gl.p_glDisable(GL_CLIP_PLANE5); checkGLcall("glDisable(clip plane 5)");
1832     context_invalidate_state(context, STATE_RENDER(WINED3D_RS_CLIPPING));
1833
1834     set_blit_dimension(gl_info, rt_size.cx, rt_size.cy);
1835
1836     /* Disable shaders */
1837     device->shader_backend->shader_select(context, WINED3D_SHADER_MODE_NONE, WINED3D_SHADER_MODE_NONE);
1838     context->select_shader = 1;
1839     context->load_constants = 1;
1840
1841     context->blit_w = rt_size.cx;
1842     context->blit_h = rt_size.cy;
1843     context_invalidate_state(context, STATE_VIEWPORT);
1844     context_invalidate_state(context, STATE_TRANSFORM(WINED3D_TS_PROJECTION));
1845 }
1846
1847 static inline BOOL is_rt_mask_onscreen(DWORD rt_mask)
1848 {
1849     return rt_mask & (1 << 31);
1850 }
1851
1852 static inline GLenum draw_buffer_from_rt_mask(DWORD rt_mask)
1853 {
1854     return rt_mask & ~(1 << 31);
1855 }
1856
1857 /* Context activation is done by the caller. */
1858 static void context_apply_draw_buffers(struct wined3d_context *context, DWORD rt_mask)
1859 {
1860     const struct wined3d_gl_info *gl_info = context->gl_info;
1861
1862     if (!rt_mask)
1863     {
1864         gl_info->gl_ops.gl.p_glDrawBuffer(GL_NONE);
1865         checkGLcall("glDrawBuffer()");
1866     }
1867     else if (is_rt_mask_onscreen(rt_mask))
1868     {
1869         gl_info->gl_ops.gl.p_glDrawBuffer(draw_buffer_from_rt_mask(rt_mask));
1870         checkGLcall("glDrawBuffer()");
1871     }
1872     else
1873     {
1874         if (wined3d_settings.offscreen_rendering_mode == ORM_FBO)
1875         {
1876             unsigned int i = 0;
1877
1878             while (rt_mask)
1879             {
1880                 if (rt_mask & 1)
1881                     context->draw_buffers[i] = GL_COLOR_ATTACHMENT0 + i;
1882                 else
1883                     context->draw_buffers[i] = GL_NONE;
1884
1885                 rt_mask >>= 1;
1886                 ++i;
1887             }
1888
1889             if (gl_info->supported[ARB_DRAW_BUFFERS])
1890             {
1891                 GL_EXTCALL(glDrawBuffersARB(i, context->draw_buffers));
1892                 checkGLcall("glDrawBuffers()");
1893             }
1894             else
1895             {
1896                 gl_info->gl_ops.gl.p_glDrawBuffer(context->draw_buffers[0]);
1897                 checkGLcall("glDrawBuffer()");
1898             }
1899         }
1900         else
1901         {
1902             ERR("Unexpected draw buffers mask with backbuffer ORM.\n");
1903         }
1904     }
1905 }
1906
1907 /* Context activation is done by the caller. */
1908 void context_set_draw_buffer(struct wined3d_context *context, GLenum buffer)
1909 {
1910     const struct wined3d_gl_info *gl_info = context->gl_info;
1911
1912     gl_info->gl_ops.gl.p_glDrawBuffer(buffer);
1913     checkGLcall("glDrawBuffer()");
1914     if (context->current_fbo)
1915         context->current_fbo->rt_mask = context_generate_rt_mask(buffer);
1916     else
1917         context->draw_buffers_mask = context_generate_rt_mask(buffer);
1918 }
1919
1920 /* Context activation is done by the caller. */
1921 void context_active_texture(struct wined3d_context *context, const struct wined3d_gl_info *gl_info, unsigned int unit)
1922 {
1923     GL_EXTCALL(glActiveTextureARB(GL_TEXTURE0 + unit));
1924     checkGLcall("glActiveTextureARB");
1925     context->active_texture = unit;
1926 }
1927
1928 void context_bind_texture(struct wined3d_context *context, GLenum target, GLuint name)
1929 {
1930     const struct wined3d_gl_info *gl_info = context->gl_info;
1931     DWORD unit = context->active_texture;
1932     DWORD old_texture_type = context->texture_type[unit];
1933
1934     if (name)
1935     {
1936         gl_info->gl_ops.gl.p_glBindTexture(target, name);
1937         checkGLcall("glBindTexture");
1938     }
1939     else
1940     {
1941         target = GL_NONE;
1942     }
1943
1944     if (old_texture_type != target)
1945     {
1946         const struct wined3d_device *device = context->swapchain->device;
1947
1948         switch (old_texture_type)
1949         {
1950             case GL_NONE:
1951                 /* nothing to do */
1952                 break;
1953             case GL_TEXTURE_2D:
1954                 gl_info->gl_ops.gl.p_glBindTexture(GL_TEXTURE_2D, device->dummy_texture_2d[unit]);
1955                 checkGLcall("glBindTexture");
1956                 break;
1957             case GL_TEXTURE_RECTANGLE_ARB:
1958                 gl_info->gl_ops.gl.p_glBindTexture(GL_TEXTURE_RECTANGLE_ARB, device->dummy_texture_rect[unit]);
1959                 checkGLcall("glBindTexture");
1960                 break;
1961             case GL_TEXTURE_CUBE_MAP:
1962                 gl_info->gl_ops.gl.p_glBindTexture(GL_TEXTURE_CUBE_MAP, device->dummy_texture_cube[unit]);
1963                 checkGLcall("glBindTexture");
1964                 break;
1965             case GL_TEXTURE_3D:
1966                 gl_info->gl_ops.gl.p_glBindTexture(GL_TEXTURE_3D, device->dummy_texture_3d[unit]);
1967                 checkGLcall("glBindTexture");
1968                 break;
1969             default:
1970                 ERR("Unexpected texture target %#x\n", old_texture_type);
1971         }
1972
1973         context->texture_type[unit] = target;
1974     }
1975 }
1976
1977 static void context_set_render_offscreen(struct wined3d_context *context, BOOL offscreen)
1978 {
1979     if (context->render_offscreen == offscreen) return;
1980
1981     context_invalidate_state(context, STATE_POINTSPRITECOORDORIGIN);
1982     context_invalidate_state(context, STATE_TRANSFORM(WINED3D_TS_PROJECTION));
1983     context_invalidate_state(context, STATE_VIEWPORT);
1984     context_invalidate_state(context, STATE_SCISSORRECT);
1985     context_invalidate_state(context, STATE_FRONTFACE);
1986     context->render_offscreen = offscreen;
1987 }
1988
1989 static BOOL match_depth_stencil_format(const struct wined3d_format *existing,
1990         const struct wined3d_format *required)
1991 {
1992     BYTE existing_depth, existing_stencil, required_depth, required_stencil;
1993
1994     if (existing == required) return TRUE;
1995     if ((existing->flags & WINED3DFMT_FLAG_FLOAT) != (required->flags & WINED3DFMT_FLAG_FLOAT)) return FALSE;
1996
1997     getDepthStencilBits(existing, &existing_depth, &existing_stencil);
1998     getDepthStencilBits(required, &required_depth, &required_stencil);
1999
2000     if(existing_depth < required_depth) return FALSE;
2001     /* If stencil bits are used the exact amount is required - otherwise wrapping
2002      * won't work correctly */
2003     if(required_stencil && required_stencil != existing_stencil) return FALSE;
2004     return TRUE;
2005 }
2006
2007 /* The caller provides a context */
2008 static void context_validate_onscreen_formats(struct wined3d_context *context,
2009         const struct wined3d_surface *depth_stencil)
2010 {
2011     /* Onscreen surfaces are always in a swapchain */
2012     struct wined3d_swapchain *swapchain = context->current_rt->container.u.swapchain;
2013
2014     if (context->render_offscreen || !depth_stencil) return;
2015     if (match_depth_stencil_format(swapchain->ds_format, depth_stencil->resource.format)) return;
2016
2017     /* TODO: If the requested format would satisfy the needs of the existing one(reverse match),
2018      * or no onscreen depth buffer was created, the OpenGL drawable could be changed to the new
2019      * format. */
2020     WARN("Depth stencil format is not supported by WGL, rendering the backbuffer in an FBO\n");
2021
2022     /* The currently active context is the necessary context to access the swapchain's onscreen buffers */
2023     surface_load_location(context->current_rt, SFLAG_INTEXTURE, NULL);
2024     swapchain->render_to_fbo = TRUE;
2025     swapchain_update_draw_bindings(swapchain);
2026     context_set_render_offscreen(context, TRUE);
2027 }
2028
2029 static DWORD context_generate_rt_mask_no_fbo(const struct wined3d_device *device, const struct wined3d_surface *rt)
2030 {
2031     if (!rt || rt->resource.format->id == WINED3DFMT_NULL)
2032         return 0;
2033     else if (rt->container.type == WINED3D_CONTAINER_SWAPCHAIN)
2034         return context_generate_rt_mask_from_surface(rt);
2035     else
2036         return context_generate_rt_mask(device->offscreenBuffer);
2037 }
2038
2039 /* Context activation is done by the caller. */
2040 void context_apply_blit_state(struct wined3d_context *context, const struct wined3d_device *device)
2041 {
2042     struct wined3d_surface *rt = context->current_rt;
2043     DWORD rt_mask, *cur_mask;
2044
2045     if (wined3d_settings.offscreen_rendering_mode == ORM_FBO)
2046     {
2047         context_validate_onscreen_formats(context, NULL);
2048
2049         if (context->render_offscreen)
2050         {
2051             surface_internal_preload(rt, SRGB_RGB);
2052
2053             context_apply_fbo_state_blit(context, GL_FRAMEBUFFER, rt, NULL, rt->draw_binding);
2054             if (rt->resource.format->id != WINED3DFMT_NULL)
2055                 rt_mask = 1;
2056             else
2057                 rt_mask = 0;
2058         }
2059         else
2060         {
2061             context_bind_fbo(context, GL_FRAMEBUFFER, NULL);
2062             rt_mask = context_generate_rt_mask_from_surface(rt);
2063         }
2064     }
2065     else
2066     {
2067         rt_mask = context_generate_rt_mask_no_fbo(device, rt);
2068     }
2069
2070     cur_mask = context->current_fbo ? &context->current_fbo->rt_mask : &context->draw_buffers_mask;
2071
2072     if (rt_mask != *cur_mask)
2073     {
2074         context_apply_draw_buffers(context, rt_mask);
2075         *cur_mask = rt_mask;
2076     }
2077
2078     if (wined3d_settings.offscreen_rendering_mode == ORM_FBO)
2079     {
2080         context_check_fbo_status(context, GL_FRAMEBUFFER);
2081     }
2082
2083     SetupForBlit(device, context);
2084     context_invalidate_state(context, STATE_FRAMEBUFFER);
2085 }
2086
2087 static BOOL context_validate_rt_config(UINT rt_count,
2088         struct wined3d_surface * const *rts, const struct wined3d_surface *ds)
2089 {
2090     unsigned int i;
2091
2092     if (ds) return TRUE;
2093
2094     for (i = 0; i < rt_count; ++i)
2095     {
2096         if (rts[i] && rts[i]->resource.format->id != WINED3DFMT_NULL)
2097             return TRUE;
2098     }
2099
2100     WARN("Invalid render target config, need at least one attachment.\n");
2101     return FALSE;
2102 }
2103
2104 /* Context activation is done by the caller. */
2105 BOOL context_apply_clear_state(struct wined3d_context *context, const struct wined3d_device *device,
2106         UINT rt_count, const struct wined3d_fb_state *fb)
2107 {
2108     const struct wined3d_gl_info *gl_info = context->gl_info;
2109     DWORD rt_mask = 0, *cur_mask;
2110     UINT i;
2111     struct wined3d_surface **rts = fb->render_targets;
2112
2113     if (isStateDirty(context, STATE_FRAMEBUFFER) || fb != &device->fb
2114             || rt_count != context->gl_info->limits.buffers)
2115     {
2116         if (!context_validate_rt_config(rt_count, rts, fb->depth_stencil))
2117             return FALSE;
2118
2119         if (wined3d_settings.offscreen_rendering_mode == ORM_FBO)
2120         {
2121             context_validate_onscreen_formats(context, fb->depth_stencil);
2122
2123             if (!rt_count || surface_is_offscreen(rts[0]))
2124             {
2125                 for (i = 0; i < rt_count; ++i)
2126                 {
2127                     context->blit_targets[i] = rts[i];
2128                     if (rts[i] && rts[i]->resource.format->id != WINED3DFMT_NULL)
2129                         rt_mask |= (1 << i);
2130                 }
2131                 while (i < context->gl_info->limits.buffers)
2132                 {
2133                     context->blit_targets[i] = NULL;
2134                     ++i;
2135                 }
2136                 context_apply_fbo_state(context, GL_FRAMEBUFFER, context->blit_targets, fb->depth_stencil,
2137                         rt_count ? rts[0]->draw_binding : SFLAG_INTEXTURE);
2138                 gl_info->gl_ops.gl.p_glReadBuffer(GL_NONE);
2139                 checkGLcall("glReadBuffer");
2140             }
2141             else
2142             {
2143                 context_apply_fbo_state(context, GL_FRAMEBUFFER, NULL, NULL, SFLAG_INDRAWABLE);
2144                 rt_mask = context_generate_rt_mask_from_surface(rts[0]);
2145             }
2146
2147             /* If the framebuffer is not the device's fb the device's fb has to be reapplied
2148              * next draw. Otherwise we could mark the framebuffer state clean here, once the
2149              * state management allows this */
2150             context_invalidate_state(context, STATE_FRAMEBUFFER);
2151         }
2152         else
2153         {
2154             rt_mask = context_generate_rt_mask_no_fbo(device, rt_count ? rts[0] : NULL);
2155         }
2156     }
2157     else if (wined3d_settings.offscreen_rendering_mode == ORM_FBO
2158             && (!rt_count || surface_is_offscreen(rts[0])))
2159     {
2160         for (i = 0; i < rt_count; ++i)
2161         {
2162             if (rts[i] && rts[i]->resource.format->id != WINED3DFMT_NULL) rt_mask |= (1 << i);
2163         }
2164     }
2165     else
2166     {
2167         rt_mask = context_generate_rt_mask_no_fbo(device, rt_count ? rts[0] : NULL);
2168     }
2169
2170     cur_mask = context->current_fbo ? &context->current_fbo->rt_mask : &context->draw_buffers_mask;
2171
2172     if (rt_mask != *cur_mask)
2173     {
2174         context_apply_draw_buffers(context, rt_mask);
2175         *cur_mask = rt_mask;
2176         context_invalidate_state(context, STATE_FRAMEBUFFER);
2177     }
2178
2179     if (wined3d_settings.offscreen_rendering_mode == ORM_FBO)
2180     {
2181         context_check_fbo_status(context, GL_FRAMEBUFFER);
2182     }
2183
2184     if (context->last_was_blit)
2185         context->last_was_blit = FALSE;
2186
2187     /* Blending and clearing should be orthogonal, but tests on the nvidia
2188      * driver show that disabling blending when clearing improves the clearing
2189      * performance incredibly. */
2190     gl_info->gl_ops.gl.p_glDisable(GL_BLEND);
2191     gl_info->gl_ops.gl.p_glEnable(GL_SCISSOR_TEST);
2192     checkGLcall("glEnable GL_SCISSOR_TEST");
2193
2194     context_invalidate_state(context, STATE_RENDER(WINED3D_RS_ALPHABLENDENABLE));
2195     context_invalidate_state(context, STATE_RENDER(WINED3D_RS_SCISSORTESTENABLE));
2196     context_invalidate_state(context, STATE_SCISSORRECT);
2197
2198     return TRUE;
2199 }
2200
2201 static DWORD find_draw_buffers_mask(const struct wined3d_context *context, const struct wined3d_device *device)
2202 {
2203     const struct wined3d_state *state = &device->stateBlock->state;
2204     struct wined3d_surface **rts = state->fb->render_targets;
2205     struct wined3d_shader *ps = state->pixel_shader;
2206     DWORD rt_mask, rt_mask_bits;
2207     unsigned int i;
2208
2209     if (wined3d_settings.offscreen_rendering_mode != ORM_FBO) return context_generate_rt_mask_no_fbo(device, rts[0]);
2210     else if (!context->render_offscreen) return context_generate_rt_mask_from_surface(rts[0]);
2211
2212     rt_mask = ps ? ps->reg_maps.rt_mask : 1;
2213     rt_mask &= device->valid_rt_mask;
2214     rt_mask_bits = rt_mask;
2215     i = 0;
2216     while (rt_mask_bits)
2217     {
2218         rt_mask_bits &= ~(1 << i);
2219         if (!rts[i] || rts[i]->resource.format->id == WINED3DFMT_NULL)
2220             rt_mask &= ~(1 << i);
2221
2222         i++;
2223     }
2224
2225     return rt_mask;
2226 }
2227
2228 /* Context activation is done by the caller. */
2229 void context_state_fb(struct wined3d_context *context, const struct wined3d_state *state, DWORD state_id)
2230 {
2231     const struct wined3d_device *device = context->swapchain->device;
2232     const struct wined3d_gl_info *gl_info = context->gl_info;
2233     const struct wined3d_fb_state *fb = state->fb;
2234     DWORD rt_mask = find_draw_buffers_mask(context, device);
2235     DWORD *cur_mask;
2236
2237     if (wined3d_settings.offscreen_rendering_mode == ORM_FBO)
2238     {
2239         if (!context->render_offscreen)
2240         {
2241             context_apply_fbo_state(context, GL_FRAMEBUFFER, NULL, NULL, SFLAG_INDRAWABLE);
2242         }
2243         else
2244         {
2245             context_apply_fbo_state(context, GL_FRAMEBUFFER, fb->render_targets, fb->depth_stencil,
2246                     fb->render_targets[0]->draw_binding);
2247             gl_info->gl_ops.gl.p_glReadBuffer(GL_NONE);
2248             checkGLcall("glReadBuffer");
2249         }
2250     }
2251
2252     cur_mask = context->current_fbo ? &context->current_fbo->rt_mask : &context->draw_buffers_mask;
2253     if (rt_mask != *cur_mask)
2254     {
2255         context_apply_draw_buffers(context, rt_mask);
2256         *cur_mask = rt_mask;
2257     }
2258 }
2259
2260 /* Context activation is done by the caller. */
2261 void context_state_drawbuf(struct wined3d_context *context, const struct wined3d_state *state, DWORD state_id)
2262 {
2263     const struct wined3d_device *device = context->swapchain->device;
2264     DWORD rt_mask, *cur_mask;
2265
2266     if (isStateDirty(context, STATE_FRAMEBUFFER)) return;
2267
2268     cur_mask = context->current_fbo ? &context->current_fbo->rt_mask : &context->draw_buffers_mask;
2269     rt_mask = find_draw_buffers_mask(context, device);
2270     if (rt_mask != *cur_mask)
2271     {
2272         context_apply_draw_buffers(context, rt_mask);
2273         *cur_mask = rt_mask;
2274     }
2275 }
2276
2277 /* Context activation is done by the caller. */
2278 BOOL context_apply_draw_state(struct wined3d_context *context, struct wined3d_device *device)
2279 {
2280     const struct wined3d_state *state = &device->stateBlock->state;
2281     const struct StateEntry *state_table = context->state_table;
2282     const struct wined3d_fb_state *fb = state->fb;
2283     unsigned int i;
2284
2285     if (!context_validate_rt_config(context->gl_info->limits.buffers,
2286             fb->render_targets, fb->depth_stencil))
2287         return FALSE;
2288
2289     if (wined3d_settings.offscreen_rendering_mode == ORM_FBO && isStateDirty(context, STATE_FRAMEBUFFER))
2290     {
2291         context_validate_onscreen_formats(context, fb->depth_stencil);
2292     }
2293
2294     /* Preload resources before FBO setup. Texture preload in particular may
2295      * result in changes to the current FBO, due to using e.g. FBO blits for
2296      * updating a resource location. */
2297     device_update_tex_unit_map(device);
2298     device_preload_textures(device);
2299     if (isStateDirty(context, STATE_VDECL) || isStateDirty(context, STATE_STREAMSRC))
2300         device_update_stream_info(device, context->gl_info);
2301     if (state->index_buffer && !state->user_stream)
2302     {
2303         if (device->strided_streams.all_vbo)
2304             wined3d_buffer_preload(state->index_buffer);
2305         else
2306             buffer_get_sysmem(state->index_buffer, context->gl_info);
2307     }
2308
2309     for (i = 0; i < context->numDirtyEntries; ++i)
2310     {
2311         DWORD rep = context->dirtyArray[i];
2312         DWORD idx = rep / (sizeof(*context->isStateDirty) * CHAR_BIT);
2313         BYTE shift = rep & ((sizeof(*context->isStateDirty) * CHAR_BIT) - 1);
2314         context->isStateDirty[idx] &= ~(1 << shift);
2315         state_table[rep].apply(context, state, rep);
2316     }
2317
2318     if (context->select_shader)
2319     {
2320         device->shader_backend->shader_select(context,
2321                 use_vs(state) ? WINED3D_SHADER_MODE_SHADER : WINED3D_SHADER_MODE_FFP,
2322                 use_ps(state) ? WINED3D_SHADER_MODE_SHADER : WINED3D_SHADER_MODE_FFP);
2323         context->select_shader = 0;
2324     }
2325
2326     if (context->load_constants)
2327     {
2328         device->shader_backend->shader_load_constants(context, use_ps(state), use_vs(state));
2329         context->load_constants = 0;
2330     }
2331
2332     if (wined3d_settings.offscreen_rendering_mode == ORM_FBO)
2333     {
2334         context_check_fbo_status(context, GL_FRAMEBUFFER);
2335     }
2336
2337     context->numDirtyEntries = 0; /* This makes the whole list clean */
2338     context->last_was_blit = FALSE;
2339
2340     return TRUE;
2341 }
2342
2343 static void context_setup_target(struct wined3d_context *context, struct wined3d_surface *target)
2344 {
2345     BOOL old_render_offscreen = context->render_offscreen, render_offscreen;
2346
2347     render_offscreen = surface_is_offscreen(target);
2348     if (context->current_rt == target && render_offscreen == old_render_offscreen) return;
2349
2350     /* To compensate the lack of format switching with some offscreen rendering methods and on onscreen buffers
2351      * the alpha blend state changes with different render target formats. */
2352     if (!context->current_rt)
2353     {
2354         context_invalidate_state(context, STATE_RENDER(WINED3D_RS_ALPHABLENDENABLE));
2355     }
2356     else
2357     {
2358         const struct wined3d_format *old = context->current_rt->resource.format;
2359         const struct wined3d_format *new = target->resource.format;
2360
2361         if (old->id != new->id)
2362         {
2363             /* Disable blending when the alpha mask has changed and when a format doesn't support blending. */
2364             if ((old->alpha_size && !new->alpha_size) || (!old->alpha_size && new->alpha_size)
2365                     || !(new->flags & WINED3DFMT_FLAG_POSTPIXELSHADER_BLENDING))
2366                 context_invalidate_state(context, STATE_RENDER(WINED3D_RS_ALPHABLENDENABLE));
2367
2368             /* Update sRGB writing when switching between formats that do/do not support sRGB writing */
2369             if ((old->flags & WINED3DFMT_FLAG_SRGB_WRITE) != (new->flags & WINED3DFMT_FLAG_SRGB_WRITE))
2370                 context_invalidate_state(context, STATE_RENDER(WINED3D_RS_SRGBWRITEENABLE));
2371         }
2372
2373         /* When switching away from an offscreen render target, and we're not
2374          * using FBOs, we have to read the drawable into the texture. This is
2375          * done via PreLoad (and SFLAG_INDRAWABLE set on the surface). There
2376          * are some things that need care though. PreLoad needs a GL context,
2377          * and FindContext is called before the context is activated. It also
2378          * has to be called with the old rendertarget active, otherwise a
2379          * wrong drawable is read. */
2380         if (wined3d_settings.offscreen_rendering_mode != ORM_FBO
2381                 && old_render_offscreen && context->current_rt != target)
2382         {
2383             /* Read the back buffer of the old drawable into the destination texture. */
2384             if (context->current_rt->texture_name_srgb)
2385                 surface_internal_preload(context->current_rt, SRGB_SRGB);
2386             surface_internal_preload(context->current_rt, SRGB_RGB);
2387             surface_modify_location(context->current_rt, SFLAG_INDRAWABLE, FALSE);
2388         }
2389     }
2390
2391     context->current_rt = target;
2392     context_set_render_offscreen(context, render_offscreen);
2393 }
2394
2395 /* Do not call while under the GL lock. */
2396 struct wined3d_context *context_acquire(const struct wined3d_device *device, struct wined3d_surface *target)
2397 {
2398     struct wined3d_context *current_context = context_get_current();
2399     struct wined3d_context *context;
2400
2401     TRACE("device %p, target %p.\n", device, target);
2402
2403     if (current_context && current_context->destroyed)
2404         current_context = NULL;
2405
2406     if (!target)
2407     {
2408         if (current_context
2409                 && current_context->current_rt
2410                 && current_context->swapchain->device == device)
2411         {
2412             target = current_context->current_rt;
2413         }
2414         else
2415         {
2416             struct wined3d_swapchain *swapchain = device->swapchains[0];
2417             if (swapchain->back_buffers)
2418                 target = swapchain->back_buffers[0];
2419             else
2420                 target = swapchain->front_buffer;
2421         }
2422     }
2423
2424     if (current_context && current_context->current_rt == target)
2425     {
2426         context = current_context;
2427     }
2428     else if (target->container.type == WINED3D_CONTAINER_SWAPCHAIN)
2429     {
2430         TRACE("Rendering onscreen.\n");
2431
2432         context = swapchain_get_context(target->container.u.swapchain);
2433     }
2434     else
2435     {
2436         TRACE("Rendering offscreen.\n");
2437
2438         /* Stay with the current context if possible. Otherwise use the
2439          * context for the primary swapchain. */
2440         if (current_context && current_context->swapchain->device == device)
2441             context = current_context;
2442         else
2443             context = swapchain_get_context(device->swapchains[0]);
2444     }
2445
2446     context_update_window(context);
2447     context_setup_target(context, target);
2448     context_enter(context);
2449     if (!context->valid) return context;
2450
2451     if (context != current_context)
2452     {
2453         if (!context_set_current(context))
2454             ERR("Failed to activate the new context.\n");
2455     }
2456     else if (context->restore_ctx)
2457     {
2458         context_set_gl_context(context);
2459     }
2460
2461     return context;
2462 }