mshtml: Use lazy allocation for connection points.
[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         return NULL;
1281
1282     ret->blit_targets = HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY,
1283             gl_info->limits.buffers * sizeof(*ret->blit_targets));
1284     if (!ret->blit_targets)
1285         goto out;
1286
1287     ret->draw_buffers = HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY,
1288             gl_info->limits.buffers * sizeof(*ret->draw_buffers));
1289     if (!ret->draw_buffers)
1290         goto out;
1291
1292     ret->free_occlusion_query_size = 4;
1293     ret->free_occlusion_queries = HeapAlloc(GetProcessHeap(), 0,
1294             ret->free_occlusion_query_size * sizeof(*ret->free_occlusion_queries));
1295     if (!ret->free_occlusion_queries)
1296         goto out;
1297
1298     list_init(&ret->occlusion_queries);
1299
1300     ret->free_event_query_size = 4;
1301     ret->free_event_queries = HeapAlloc(GetProcessHeap(), 0,
1302             ret->free_event_query_size * sizeof(*ret->free_event_queries));
1303     if (!ret->free_event_queries)
1304         goto out;
1305
1306     list_init(&ret->event_queries);
1307     list_init(&ret->fbo_list);
1308     list_init(&ret->fbo_destroy_list);
1309
1310     if (!(hdc = GetDC(swapchain->win_handle)))
1311     {
1312         WARN("Failed to retireve device context, trying swapchain backup.\n");
1313
1314         if (!(hdc = swapchain_get_backup_dc(swapchain)))
1315         {
1316             ERR("Failed to retrieve a device context.\n");
1317             goto out;
1318         }
1319     }
1320
1321     color_format = target->resource.format;
1322
1323     /* In case of ORM_BACKBUFFER, make sure to request an alpha component for
1324      * X4R4G4B4/X8R8G8B8 as we might need it for the backbuffer. */
1325     if (wined3d_settings.offscreen_rendering_mode == ORM_BACKBUFFER)
1326     {
1327         auxBuffers = TRUE;
1328
1329         if (color_format->id == WINED3DFMT_B4G4R4X4_UNORM)
1330             color_format = wined3d_get_format(gl_info, WINED3DFMT_B4G4R4A4_UNORM);
1331         else if (color_format->id == WINED3DFMT_B8G8R8X8_UNORM)
1332             color_format = wined3d_get_format(gl_info, WINED3DFMT_B8G8R8A8_UNORM);
1333     }
1334
1335     /* DirectDraw supports 8bit paletted render targets and these are used by
1336      * old games like StarCraft and C&C. Most modern hardware doesn't support
1337      * 8bit natively so we perform some form of 8bit -> 32bit conversion. The
1338      * conversion (ab)uses the alpha component for storing the palette index.
1339      * For this reason we require a format with 8bit alpha, so request
1340      * A8R8G8B8. */
1341     if (color_format->id == WINED3DFMT_P8_UINT)
1342         color_format = wined3d_get_format(gl_info, WINED3DFMT_B8G8R8A8_UNORM);
1343
1344     /* Try to find a pixel format which matches our requirements. */
1345     pixel_format = context_choose_pixel_format(device, hdc, color_format, ds_format, auxBuffers, FALSE);
1346
1347     /* Try to locate a compatible format if we weren't able to find anything. */
1348     if (!pixel_format)
1349     {
1350         TRACE("Trying to locate a compatible pixel format because an exact match failed.\n");
1351         pixel_format = context_choose_pixel_format(device, hdc, color_format, ds_format, auxBuffers, TRUE);
1352     }
1353
1354     /* If we still don't have a pixel format, something is very wrong as ChoosePixelFormat barely fails */
1355     if (!pixel_format)
1356     {
1357         ERR("Can't find a suitable pixel format.\n");
1358         goto out;
1359     }
1360
1361     context_enter(ret);
1362
1363     if (!context_set_pixel_format(gl_info, hdc, pixel_format))
1364     {
1365         ERR("Failed to set pixel format %d on device context %p.\n", pixel_format, hdc);
1366         context_release(ret);
1367         goto out;
1368     }
1369
1370     if (!(ctx = wglCreateContext(hdc)))
1371     {
1372         ERR("Failed to create a WGL context.\n");
1373         context_release(ret);
1374         goto out;
1375     }
1376
1377     if (device->context_count)
1378     {
1379         if (!wglShareLists(device->contexts[0]->glCtx, ctx))
1380         {
1381             ERR("wglShareLists(%p, %p) failed, last error %#x.\n",
1382                     device->contexts[0]->glCtx, ctx, GetLastError());
1383             context_release(ret);
1384             if (!wglDeleteContext(ctx))
1385                 ERR("wglDeleteContext(%p) failed, last error %#x.\n", ctx, GetLastError());
1386             goto out;
1387         }
1388     }
1389
1390     if (!device_context_add(device, ret))
1391     {
1392         ERR("Failed to add the newly created context to the context list\n");
1393         context_release(ret);
1394         if (!wglDeleteContext(ctx))
1395             ERR("wglDeleteContext(%p) failed, last error %#x.\n", ctx, GetLastError());
1396         goto out;
1397     }
1398
1399     ret->gl_info = gl_info;
1400     ret->state_table = device->StateTable;
1401
1402     /* Mark all states dirty to force a proper initialization of the states
1403      * on the first use of the context. */
1404     for (state = 0; state <= STATE_HIGHEST; ++state)
1405     {
1406         if (ret->state_table[state].representative)
1407             context_invalidate_state(ret, state);
1408     }
1409
1410     ret->swapchain = swapchain;
1411     ret->current_rt = target;
1412     ret->tid = GetCurrentThreadId();
1413
1414     ret->render_offscreen = surface_is_offscreen(target);
1415     ret->draw_buffers_mask = context_generate_rt_mask(GL_BACK);
1416     ret->valid = 1;
1417
1418     ret->glCtx = ctx;
1419     ret->win_handle = swapchain->win_handle;
1420     ret->hdc = hdc;
1421     ret->pixel_format = pixel_format;
1422
1423     /* Set up the context defaults */
1424     if (!context_set_current(ret))
1425     {
1426         ERR("Cannot activate context to set up defaults.\n");
1427         device_context_remove(device, ret);
1428         context_release(ret);
1429         if (!wglDeleteContext(ctx))
1430             ERR("wglDeleteContext(%p) failed, last error %#x.\n", ctx, GetLastError());
1431         goto out;
1432     }
1433
1434     switch (swapchain->desc.swap_interval)
1435     {
1436         case WINED3DPRESENT_INTERVAL_IMMEDIATE:
1437             swap_interval = 0;
1438             break;
1439         case WINED3DPRESENT_INTERVAL_DEFAULT:
1440         case WINED3DPRESENT_INTERVAL_ONE:
1441             swap_interval = 1;
1442             break;
1443         case WINED3DPRESENT_INTERVAL_TWO:
1444             swap_interval = 2;
1445             break;
1446         case WINED3DPRESENT_INTERVAL_THREE:
1447             swap_interval = 3;
1448             break;
1449         case WINED3DPRESENT_INTERVAL_FOUR:
1450             swap_interval = 4;
1451             break;
1452         default:
1453             FIXME("Unknown swap interval %#x.\n", swapchain->desc.swap_interval);
1454             swap_interval = 1;
1455     }
1456
1457     if (gl_info->supported[WGL_EXT_SWAP_CONTROL])
1458     {
1459         if (!GL_EXTCALL(wglSwapIntervalEXT(swap_interval)))
1460             ERR("wglSwapIntervalEXT failed to set swap interval %d for context %p, last error %#x\n",
1461                 swap_interval, ret, GetLastError());
1462     }
1463
1464     gl_info->gl_ops.gl.p_glGetIntegerv(GL_AUX_BUFFERS, &ret->aux_buffers);
1465
1466     TRACE("Setting up the screen\n");
1467     /* Clear the screen */
1468     gl_info->gl_ops.gl.p_glClearColor(1.0f, 0.0f, 0.0f, 0.0f);
1469     checkGLcall("glClearColor");
1470     gl_info->gl_ops.gl.p_glClearIndex(0);
1471     gl_info->gl_ops.gl.p_glClearDepth(1);
1472     gl_info->gl_ops.gl.p_glClearStencil(0xffff);
1473
1474     checkGLcall("glClear");
1475
1476     gl_info->gl_ops.gl.p_glLightModeli(GL_LIGHT_MODEL_LOCAL_VIEWER, GL_TRUE);
1477     checkGLcall("glLightModeli(GL_LIGHT_MODEL_LOCAL_VIEWER, GL_TRUE);");
1478
1479     gl_info->gl_ops.gl.p_glTexEnvf(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_COMBINE_EXT);
1480     checkGLcall("glTexEnvf(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_COMBINE_EXT);");
1481
1482     gl_info->gl_ops.gl.p_glLightModeli(GL_LIGHT_MODEL_COLOR_CONTROL, GL_SEPARATE_SPECULAR_COLOR);
1483     checkGLcall("glLightModeli(GL_LIGHT_MODEL_COLOR_CONTROL, GL_SEPARATE_SPECULAR_COLOR);");
1484
1485     gl_info->gl_ops.gl.p_glPixelStorei(GL_PACK_ALIGNMENT, device->surface_alignment);
1486     checkGLcall("glPixelStorei(GL_PACK_ALIGNMENT, device->surface_alignment);");
1487     gl_info->gl_ops.gl.p_glPixelStorei(GL_UNPACK_ALIGNMENT, device->surface_alignment);
1488     checkGLcall("glPixelStorei(GL_UNPACK_ALIGNMENT, device->surface_alignment);");
1489
1490     if (gl_info->supported[APPLE_CLIENT_STORAGE])
1491     {
1492         /* Most textures will use client storage if supported. Exceptions are
1493          * non-native power of 2 textures and textures in DIB sections. */
1494         gl_info->gl_ops.gl.p_glPixelStorei(GL_UNPACK_CLIENT_STORAGE_APPLE, GL_TRUE);
1495         checkGLcall("glPixelStorei(GL_UNPACK_CLIENT_STORAGE_APPLE, GL_TRUE)");
1496     }
1497     if (gl_info->supported[ARB_VERTEX_BLEND])
1498     {
1499         /* Direct3D always uses n-1 weights for n world matrices and uses
1500          * 1 - sum for the last one this is equal to GL_WEIGHT_SUM_UNITY_ARB.
1501          * Enabling it doesn't do anything unless GL_VERTEX_BLEND_ARB isn't
1502          * enabled as well. */
1503         gl_info->gl_ops.gl.p_glEnable(GL_WEIGHT_SUM_UNITY_ARB);
1504         checkGLcall("glEnable(GL_WEIGHT_SUM_UNITY_ARB)");
1505     }
1506     if (gl_info->supported[NV_TEXTURE_SHADER2])
1507     {
1508         /* Set up the previous texture input for all shader units. This applies to bump mapping, and in d3d
1509          * the previous texture where to source the offset from is always unit - 1.
1510          */
1511         for (s = 1; s < gl_info->limits.textures; ++s)
1512         {
1513             context_active_texture(ret, gl_info, s);
1514             gl_info->gl_ops.gl.p_glTexEnvi(GL_TEXTURE_SHADER_NV,
1515                     GL_PREVIOUS_TEXTURE_INPUT_NV, GL_TEXTURE0_ARB + s - 1);
1516             checkGLcall("glTexEnvi(GL_TEXTURE_SHADER_NV, GL_PREVIOUS_TEXTURE_INPUT_NV, ...");
1517         }
1518     }
1519     if (gl_info->supported[ARB_FRAGMENT_PROGRAM])
1520     {
1521         /* MacOS(radeon X1600 at least, but most likely others too) refuses to draw if GLSL and ARBFP are
1522          * enabled, but the currently bound arbfp program is 0. Enabling ARBFP with prog 0 is invalid, but
1523          * GLSL should bypass this. This causes problems in programs that never use the fixed function pipeline,
1524          * because the ARBFP extension is enabled by the ARBFP pipeline at context creation, but no program
1525          * is ever assigned.
1526          *
1527          * So make sure a program is assigned to each context. The first real ARBFP use will set a different
1528          * program and the dummy program is destroyed when the context is destroyed.
1529          */
1530         const char *dummy_program =
1531                 "!!ARBfp1.0\n"
1532                 "MOV result.color, fragment.color.primary;\n"
1533                 "END\n";
1534         GL_EXTCALL(glGenProgramsARB(1, &ret->dummy_arbfp_prog));
1535         GL_EXTCALL(glBindProgramARB(GL_FRAGMENT_PROGRAM_ARB, ret->dummy_arbfp_prog));
1536         GL_EXTCALL(glProgramStringARB(GL_FRAGMENT_PROGRAM_ARB, GL_PROGRAM_FORMAT_ASCII_ARB, strlen(dummy_program), dummy_program));
1537     }
1538
1539     if (gl_info->supported[ARB_POINT_SPRITE])
1540     {
1541         for (s = 0; s < gl_info->limits.textures; ++s)
1542         {
1543             context_active_texture(ret, gl_info, s);
1544             gl_info->gl_ops.gl.p_glTexEnvi(GL_POINT_SPRITE_ARB, GL_COORD_REPLACE_ARB, GL_TRUE);
1545             checkGLcall("glTexEnvi(GL_POINT_SPRITE_ARB, GL_COORD_REPLACE_ARB, GL_TRUE)");
1546         }
1547     }
1548
1549     if (gl_info->supported[ARB_PROVOKING_VERTEX])
1550     {
1551         GL_EXTCALL(glProvokingVertex(GL_FIRST_VERTEX_CONVENTION));
1552     }
1553     else if (gl_info->supported[EXT_PROVOKING_VERTEX])
1554     {
1555         GL_EXTCALL(glProvokingVertexEXT(GL_FIRST_VERTEX_CONVENTION_EXT));
1556     }
1557     ret->select_shader = 1;
1558
1559     /* If this happens to be the first context for the device, dummy textures
1560      * are not created yet. In that case, they will be created (and bound) by
1561      * create_dummy_textures right after this context is initialized. */
1562     if (device->dummy_texture_2d[0])
1563         bind_dummy_textures(device, ret);
1564
1565     TRACE("Created context %p.\n", ret);
1566
1567     return ret;
1568
1569 out:
1570     HeapFree(GetProcessHeap(), 0, ret->free_event_queries);
1571     HeapFree(GetProcessHeap(), 0, ret->free_occlusion_queries);
1572     HeapFree(GetProcessHeap(), 0, ret->draw_buffers);
1573     HeapFree(GetProcessHeap(), 0, ret->blit_targets);
1574     HeapFree(GetProcessHeap(), 0, ret);
1575     return NULL;
1576 }
1577
1578 /* Do not call while under the GL lock. */
1579 void context_destroy(struct wined3d_device *device, struct wined3d_context *context)
1580 {
1581     BOOL destroy;
1582
1583     TRACE("Destroying ctx %p\n", context);
1584
1585     if (context->tid == GetCurrentThreadId() || !context->current)
1586     {
1587         context_destroy_gl_resources(context);
1588         TlsSetValue(wined3d_context_tls_idx, NULL);
1589         destroy = TRUE;
1590     }
1591     else
1592     {
1593         /* Make a copy of gl_info for context_destroy_gl_resources use, the one
1594            in wined3d_adapter may go away in the meantime */
1595         struct wined3d_gl_info *gl_info = HeapAlloc(GetProcessHeap(), 0, sizeof(*gl_info));
1596         *gl_info = *context->gl_info;
1597         context->gl_info = gl_info;
1598         context->destroyed = 1;
1599         destroy = FALSE;
1600     }
1601
1602     HeapFree(GetProcessHeap(), 0, context->draw_buffers);
1603     HeapFree(GetProcessHeap(), 0, context->blit_targets);
1604     device_context_remove(device, context);
1605     if (destroy) HeapFree(GetProcessHeap(), 0, context);
1606 }
1607
1608 /* Context activation is done by the caller. */
1609 static void set_blit_dimension(const struct wined3d_gl_info *gl_info, UINT width, UINT height)
1610 {
1611     const GLdouble projection[] =
1612     {
1613         2.0 / width,          0.0,  0.0, 0.0,
1614                 0.0, 2.0 / height,  0.0, 0.0,
1615                 0.0,          0.0,  2.0, 0.0,
1616                -1.0,         -1.0, -1.0, 1.0,
1617     };
1618
1619     gl_info->gl_ops.gl.p_glMatrixMode(GL_PROJECTION);
1620     checkGLcall("glMatrixMode(GL_PROJECTION)");
1621     gl_info->gl_ops.gl.p_glLoadMatrixd(projection);
1622     checkGLcall("glLoadMatrixd");
1623     gl_info->gl_ops.gl.p_glViewport(0, 0, width, height);
1624     checkGLcall("glViewport");
1625 }
1626
1627 static void context_get_rt_size(const struct wined3d_context *context, SIZE *size)
1628 {
1629     const struct wined3d_surface *rt = context->current_rt;
1630
1631     if (rt->container.type == WINED3D_CONTAINER_SWAPCHAIN
1632             && rt->container.u.swapchain->front_buffer == rt)
1633     {
1634         RECT window_size;
1635
1636         GetClientRect(context->win_handle, &window_size);
1637         size->cx = window_size.right - window_size.left;
1638         size->cy = window_size.bottom - window_size.top;
1639
1640         return;
1641     }
1642
1643     size->cx = rt->resource.width;
1644     size->cy = rt->resource.height;
1645 }
1646
1647 /*****************************************************************************
1648  * SetupForBlit
1649  *
1650  * Sets up a context for DirectDraw blitting.
1651  * All texture units are disabled, texture unit 0 is set as current unit
1652  * fog, lighting, blending, alpha test, z test, scissor test, culling disabled
1653  * color writing enabled for all channels
1654  * register combiners disabled, shaders disabled
1655  * world matrix is set to identity, texture matrix 0 too
1656  * projection matrix is setup for drawing screen coordinates
1657  *
1658  * Params:
1659  *  This: Device to activate the context for
1660  *  context: Context to setup
1661  *
1662  *****************************************************************************/
1663 /* Context activation is done by the caller. */
1664 static void SetupForBlit(const struct wined3d_device *device, struct wined3d_context *context)
1665 {
1666     int i;
1667     const struct wined3d_gl_info *gl_info = context->gl_info;
1668     DWORD sampler;
1669     SIZE rt_size;
1670
1671     TRACE("Setting up context %p for blitting\n", context);
1672
1673     context_get_rt_size(context, &rt_size);
1674
1675     if (context->last_was_blit)
1676     {
1677         if (context->blit_w != rt_size.cx || context->blit_h != rt_size.cy)
1678         {
1679             set_blit_dimension(gl_info, rt_size.cx, rt_size.cy);
1680             context->blit_w = rt_size.cx;
1681             context->blit_h = rt_size.cy;
1682             /* No need to dirtify here, the states are still dirtified because
1683              * they weren't applied since the last SetupForBlit() call. */
1684         }
1685         TRACE("Context is already set up for blitting, nothing to do\n");
1686         return;
1687     }
1688     context->last_was_blit = TRUE;
1689
1690     /* Disable all textures. The caller can then bind a texture it wants to blit
1691      * from
1692      *
1693      * The blitting code uses (for now) the fixed function pipeline, so make sure to reset all fixed
1694      * function texture unit. No need to care for higher samplers
1695      */
1696     for (i = gl_info->limits.textures - 1; i > 0 ; --i)
1697     {
1698         sampler = device->rev_tex_unit_map[i];
1699         context_active_texture(context, gl_info, i);
1700
1701         if (gl_info->supported[ARB_TEXTURE_CUBE_MAP])
1702         {
1703             gl_info->gl_ops.gl.p_glDisable(GL_TEXTURE_CUBE_MAP_ARB);
1704             checkGLcall("glDisable GL_TEXTURE_CUBE_MAP_ARB");
1705         }
1706         gl_info->gl_ops.gl.p_glDisable(GL_TEXTURE_3D);
1707         checkGLcall("glDisable GL_TEXTURE_3D");
1708         if (gl_info->supported[ARB_TEXTURE_RECTANGLE])
1709         {
1710             gl_info->gl_ops.gl.p_glDisable(GL_TEXTURE_RECTANGLE_ARB);
1711             checkGLcall("glDisable GL_TEXTURE_RECTANGLE_ARB");
1712         }
1713         gl_info->gl_ops.gl.p_glDisable(GL_TEXTURE_2D);
1714         checkGLcall("glDisable GL_TEXTURE_2D");
1715
1716         gl_info->gl_ops.gl.p_glTexEnvi(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_REPLACE);
1717         checkGLcall("glTexEnvi(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_REPLACE);");
1718
1719         if (sampler != WINED3D_UNMAPPED_STAGE)
1720         {
1721             if (sampler < MAX_TEXTURES)
1722                 context_invalidate_state(context, STATE_TEXTURESTAGE(sampler, WINED3D_TSS_COLOR_OP));
1723             context_invalidate_state(context, STATE_SAMPLER(sampler));
1724         }
1725     }
1726     context_active_texture(context, gl_info, 0);
1727
1728     sampler = device->rev_tex_unit_map[0];
1729
1730     if (gl_info->supported[ARB_TEXTURE_CUBE_MAP])
1731     {
1732         gl_info->gl_ops.gl.p_glDisable(GL_TEXTURE_CUBE_MAP_ARB);
1733         checkGLcall("glDisable GL_TEXTURE_CUBE_MAP_ARB");
1734     }
1735     gl_info->gl_ops.gl.p_glDisable(GL_TEXTURE_3D);
1736     checkGLcall("glDisable GL_TEXTURE_3D");
1737     if (gl_info->supported[ARB_TEXTURE_RECTANGLE])
1738     {
1739         gl_info->gl_ops.gl.p_glDisable(GL_TEXTURE_RECTANGLE_ARB);
1740         checkGLcall("glDisable GL_TEXTURE_RECTANGLE_ARB");
1741     }
1742     gl_info->gl_ops.gl.p_glDisable(GL_TEXTURE_2D);
1743     checkGLcall("glDisable GL_TEXTURE_2D");
1744
1745     gl_info->gl_ops.gl.p_glTexEnvi(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_REPLACE);
1746
1747     gl_info->gl_ops.gl.p_glMatrixMode(GL_TEXTURE);
1748     checkGLcall("glMatrixMode(GL_TEXTURE)");
1749     gl_info->gl_ops.gl.p_glLoadIdentity();
1750     checkGLcall("glLoadIdentity()");
1751
1752     if (gl_info->supported[EXT_TEXTURE_LOD_BIAS])
1753     {
1754         gl_info->gl_ops.gl.p_glTexEnvf(GL_TEXTURE_FILTER_CONTROL_EXT,
1755                 GL_TEXTURE_LOD_BIAS_EXT, 0.0f);
1756         checkGLcall("glTexEnvf GL_TEXTURE_LOD_BIAS_EXT ...");
1757     }
1758
1759     if (sampler != WINED3D_UNMAPPED_STAGE)
1760     {
1761         if (sampler < MAX_TEXTURES)
1762         {
1763             context_invalidate_state(context, STATE_TRANSFORM(WINED3D_TS_TEXTURE0 + sampler));
1764             context_invalidate_state(context, STATE_TEXTURESTAGE(sampler, WINED3D_TSS_COLOR_OP));
1765         }
1766         context_invalidate_state(context, STATE_SAMPLER(sampler));
1767     }
1768
1769     /* Other misc states */
1770     gl_info->gl_ops.gl.p_glDisable(GL_ALPHA_TEST);
1771     checkGLcall("glDisable(GL_ALPHA_TEST)");
1772     context_invalidate_state(context, STATE_RENDER(WINED3D_RS_ALPHATESTENABLE));
1773     gl_info->gl_ops.gl.p_glDisable(GL_LIGHTING);
1774     checkGLcall("glDisable GL_LIGHTING");
1775     context_invalidate_state(context, STATE_RENDER(WINED3D_RS_LIGHTING));
1776     gl_info->gl_ops.gl.p_glDisable(GL_DEPTH_TEST);
1777     checkGLcall("glDisable GL_DEPTH_TEST");
1778     context_invalidate_state(context, STATE_RENDER(WINED3D_RS_ZENABLE));
1779     glDisableWINE(GL_FOG);
1780     checkGLcall("glDisable GL_FOG");
1781     context_invalidate_state(context, STATE_RENDER(WINED3D_RS_FOGENABLE));
1782     gl_info->gl_ops.gl.p_glDisable(GL_BLEND);
1783     checkGLcall("glDisable GL_BLEND");
1784     context_invalidate_state(context, STATE_RENDER(WINED3D_RS_ALPHABLENDENABLE));
1785     gl_info->gl_ops.gl.p_glDisable(GL_CULL_FACE);
1786     checkGLcall("glDisable GL_CULL_FACE");
1787     context_invalidate_state(context, STATE_RENDER(WINED3D_RS_CULLMODE));
1788     gl_info->gl_ops.gl.p_glDisable(GL_STENCIL_TEST);
1789     checkGLcall("glDisable GL_STENCIL_TEST");
1790     context_invalidate_state(context, STATE_RENDER(WINED3D_RS_STENCILENABLE));
1791     gl_info->gl_ops.gl.p_glDisable(GL_SCISSOR_TEST);
1792     checkGLcall("glDisable GL_SCISSOR_TEST");
1793     context_invalidate_state(context, STATE_RENDER(WINED3D_RS_SCISSORTESTENABLE));
1794     if (gl_info->supported[ARB_POINT_SPRITE])
1795     {
1796         gl_info->gl_ops.gl.p_glDisable(GL_POINT_SPRITE_ARB);
1797         checkGLcall("glDisable GL_POINT_SPRITE_ARB");
1798         context_invalidate_state(context, STATE_RENDER(WINED3D_RS_POINTSPRITEENABLE));
1799     }
1800     gl_info->gl_ops.gl.p_glColorMask(GL_TRUE, GL_TRUE,GL_TRUE,GL_TRUE);
1801     checkGLcall("glColorMask");
1802     context_invalidate_state(context, STATE_RENDER(WINED3D_RS_COLORWRITEENABLE));
1803     context_invalidate_state(context, STATE_RENDER(WINED3D_RS_COLORWRITEENABLE1));
1804     context_invalidate_state(context, STATE_RENDER(WINED3D_RS_COLORWRITEENABLE2));
1805     context_invalidate_state(context, STATE_RENDER(WINED3D_RS_COLORWRITEENABLE3));
1806     if (gl_info->supported[EXT_SECONDARY_COLOR])
1807     {
1808         gl_info->gl_ops.gl.p_glDisable(GL_COLOR_SUM_EXT);
1809         context_invalidate_state(context, STATE_RENDER(WINED3D_RS_SPECULARENABLE));
1810         checkGLcall("glDisable(GL_COLOR_SUM_EXT)");
1811     }
1812
1813     /* Setup transforms */
1814     gl_info->gl_ops.gl.p_glMatrixMode(GL_MODELVIEW);
1815     checkGLcall("glMatrixMode(GL_MODELVIEW)");
1816     gl_info->gl_ops.gl.p_glLoadIdentity();
1817     checkGLcall("glLoadIdentity()");
1818     context_invalidate_state(context, STATE_TRANSFORM(WINED3D_TS_WORLD_MATRIX(0)));
1819
1820     context->last_was_rhw = TRUE;
1821     context_invalidate_state(context, STATE_VDECL); /* because of last_was_rhw = TRUE */
1822
1823     gl_info->gl_ops.gl.p_glDisable(GL_CLIP_PLANE0); checkGLcall("glDisable(clip plane 0)");
1824     gl_info->gl_ops.gl.p_glDisable(GL_CLIP_PLANE1); checkGLcall("glDisable(clip plane 1)");
1825     gl_info->gl_ops.gl.p_glDisable(GL_CLIP_PLANE2); checkGLcall("glDisable(clip plane 2)");
1826     gl_info->gl_ops.gl.p_glDisable(GL_CLIP_PLANE3); checkGLcall("glDisable(clip plane 3)");
1827     gl_info->gl_ops.gl.p_glDisable(GL_CLIP_PLANE4); checkGLcall("glDisable(clip plane 4)");
1828     gl_info->gl_ops.gl.p_glDisable(GL_CLIP_PLANE5); checkGLcall("glDisable(clip plane 5)");
1829     context_invalidate_state(context, STATE_RENDER(WINED3D_RS_CLIPPING));
1830
1831     set_blit_dimension(gl_info, rt_size.cx, rt_size.cy);
1832
1833     /* Disable shaders */
1834     device->shader_backend->shader_select(context, WINED3D_SHADER_MODE_NONE, WINED3D_SHADER_MODE_NONE);
1835     context->select_shader = 1;
1836     context->load_constants = 1;
1837
1838     context->blit_w = rt_size.cx;
1839     context->blit_h = rt_size.cy;
1840     context_invalidate_state(context, STATE_VIEWPORT);
1841     context_invalidate_state(context, STATE_TRANSFORM(WINED3D_TS_PROJECTION));
1842 }
1843
1844 static inline BOOL is_rt_mask_onscreen(DWORD rt_mask)
1845 {
1846     return rt_mask & (1 << 31);
1847 }
1848
1849 static inline GLenum draw_buffer_from_rt_mask(DWORD rt_mask)
1850 {
1851     return rt_mask & ~(1 << 31);
1852 }
1853
1854 /* Context activation is done by the caller. */
1855 static void context_apply_draw_buffers(struct wined3d_context *context, DWORD rt_mask)
1856 {
1857     const struct wined3d_gl_info *gl_info = context->gl_info;
1858
1859     if (!rt_mask)
1860     {
1861         gl_info->gl_ops.gl.p_glDrawBuffer(GL_NONE);
1862         checkGLcall("glDrawBuffer()");
1863     }
1864     else if (is_rt_mask_onscreen(rt_mask))
1865     {
1866         gl_info->gl_ops.gl.p_glDrawBuffer(draw_buffer_from_rt_mask(rt_mask));
1867         checkGLcall("glDrawBuffer()");
1868     }
1869     else
1870     {
1871         if (wined3d_settings.offscreen_rendering_mode == ORM_FBO)
1872         {
1873             unsigned int i = 0;
1874
1875             while (rt_mask)
1876             {
1877                 if (rt_mask & 1)
1878                     context->draw_buffers[i] = GL_COLOR_ATTACHMENT0 + i;
1879                 else
1880                     context->draw_buffers[i] = GL_NONE;
1881
1882                 rt_mask >>= 1;
1883                 ++i;
1884             }
1885
1886             if (gl_info->supported[ARB_DRAW_BUFFERS])
1887             {
1888                 GL_EXTCALL(glDrawBuffersARB(i, context->draw_buffers));
1889                 checkGLcall("glDrawBuffers()");
1890             }
1891             else
1892             {
1893                 gl_info->gl_ops.gl.p_glDrawBuffer(context->draw_buffers[0]);
1894                 checkGLcall("glDrawBuffer()");
1895             }
1896         }
1897         else
1898         {
1899             ERR("Unexpected draw buffers mask with backbuffer ORM.\n");
1900         }
1901     }
1902 }
1903
1904 /* Context activation is done by the caller. */
1905 void context_set_draw_buffer(struct wined3d_context *context, GLenum buffer)
1906 {
1907     const struct wined3d_gl_info *gl_info = context->gl_info;
1908
1909     gl_info->gl_ops.gl.p_glDrawBuffer(buffer);
1910     checkGLcall("glDrawBuffer()");
1911     if (context->current_fbo)
1912         context->current_fbo->rt_mask = context_generate_rt_mask(buffer);
1913     else
1914         context->draw_buffers_mask = context_generate_rt_mask(buffer);
1915 }
1916
1917 /* Context activation is done by the caller. */
1918 void context_active_texture(struct wined3d_context *context, const struct wined3d_gl_info *gl_info, unsigned int unit)
1919 {
1920     GL_EXTCALL(glActiveTextureARB(GL_TEXTURE0 + unit));
1921     checkGLcall("glActiveTextureARB");
1922     context->active_texture = unit;
1923 }
1924
1925 void context_bind_texture(struct wined3d_context *context, GLenum target, GLuint name)
1926 {
1927     const struct wined3d_gl_info *gl_info = context->gl_info;
1928     DWORD unit = context->active_texture;
1929     DWORD old_texture_type = context->texture_type[unit];
1930
1931     if (name)
1932     {
1933         gl_info->gl_ops.gl.p_glBindTexture(target, name);
1934         checkGLcall("glBindTexture");
1935     }
1936     else
1937     {
1938         target = GL_NONE;
1939     }
1940
1941     if (old_texture_type != target)
1942     {
1943         const struct wined3d_device *device = context->swapchain->device;
1944
1945         switch (old_texture_type)
1946         {
1947             case GL_NONE:
1948                 /* nothing to do */
1949                 break;
1950             case GL_TEXTURE_2D:
1951                 gl_info->gl_ops.gl.p_glBindTexture(GL_TEXTURE_2D, device->dummy_texture_2d[unit]);
1952                 checkGLcall("glBindTexture");
1953                 break;
1954             case GL_TEXTURE_RECTANGLE_ARB:
1955                 gl_info->gl_ops.gl.p_glBindTexture(GL_TEXTURE_RECTANGLE_ARB, device->dummy_texture_rect[unit]);
1956                 checkGLcall("glBindTexture");
1957                 break;
1958             case GL_TEXTURE_CUBE_MAP:
1959                 gl_info->gl_ops.gl.p_glBindTexture(GL_TEXTURE_CUBE_MAP, device->dummy_texture_cube[unit]);
1960                 checkGLcall("glBindTexture");
1961                 break;
1962             case GL_TEXTURE_3D:
1963                 gl_info->gl_ops.gl.p_glBindTexture(GL_TEXTURE_3D, device->dummy_texture_3d[unit]);
1964                 checkGLcall("glBindTexture");
1965                 break;
1966             default:
1967                 ERR("Unexpected texture target %#x\n", old_texture_type);
1968         }
1969
1970         context->texture_type[unit] = target;
1971     }
1972 }
1973
1974 static void context_set_render_offscreen(struct wined3d_context *context, BOOL offscreen)
1975 {
1976     if (context->render_offscreen == offscreen) return;
1977
1978     context_invalidate_state(context, STATE_POINTSPRITECOORDORIGIN);
1979     context_invalidate_state(context, STATE_TRANSFORM(WINED3D_TS_PROJECTION));
1980     context_invalidate_state(context, STATE_VIEWPORT);
1981     context_invalidate_state(context, STATE_SCISSORRECT);
1982     context_invalidate_state(context, STATE_FRONTFACE);
1983     context->render_offscreen = offscreen;
1984 }
1985
1986 static BOOL match_depth_stencil_format(const struct wined3d_format *existing,
1987         const struct wined3d_format *required)
1988 {
1989     BYTE existing_depth, existing_stencil, required_depth, required_stencil;
1990
1991     if (existing == required) return TRUE;
1992     if ((existing->flags & WINED3DFMT_FLAG_FLOAT) != (required->flags & WINED3DFMT_FLAG_FLOAT)) return FALSE;
1993
1994     getDepthStencilBits(existing, &existing_depth, &existing_stencil);
1995     getDepthStencilBits(required, &required_depth, &required_stencil);
1996
1997     if(existing_depth < required_depth) return FALSE;
1998     /* If stencil bits are used the exact amount is required - otherwise wrapping
1999      * won't work correctly */
2000     if(required_stencil && required_stencil != existing_stencil) return FALSE;
2001     return TRUE;
2002 }
2003
2004 /* The caller provides a context */
2005 static void context_validate_onscreen_formats(struct wined3d_context *context,
2006         const struct wined3d_surface *depth_stencil)
2007 {
2008     /* Onscreen surfaces are always in a swapchain */
2009     struct wined3d_swapchain *swapchain = context->current_rt->container.u.swapchain;
2010
2011     if (context->render_offscreen || !depth_stencil) return;
2012     if (match_depth_stencil_format(swapchain->ds_format, depth_stencil->resource.format)) return;
2013
2014     /* TODO: If the requested format would satisfy the needs of the existing one(reverse match),
2015      * or no onscreen depth buffer was created, the OpenGL drawable could be changed to the new
2016      * format. */
2017     WARN("Depth stencil format is not supported by WGL, rendering the backbuffer in an FBO\n");
2018
2019     /* The currently active context is the necessary context to access the swapchain's onscreen buffers */
2020     surface_load_location(context->current_rt, SFLAG_INTEXTURE, NULL);
2021     swapchain->render_to_fbo = TRUE;
2022     swapchain_update_draw_bindings(swapchain);
2023     context_set_render_offscreen(context, TRUE);
2024 }
2025
2026 static DWORD context_generate_rt_mask_no_fbo(const struct wined3d_device *device, const struct wined3d_surface *rt)
2027 {
2028     if (!rt || rt->resource.format->id == WINED3DFMT_NULL)
2029         return 0;
2030     else if (rt->container.type == WINED3D_CONTAINER_SWAPCHAIN)
2031         return context_generate_rt_mask_from_surface(rt);
2032     else
2033         return context_generate_rt_mask(device->offscreenBuffer);
2034 }
2035
2036 /* Context activation is done by the caller. */
2037 void context_apply_blit_state(struct wined3d_context *context, const struct wined3d_device *device)
2038 {
2039     struct wined3d_surface *rt = context->current_rt;
2040     DWORD rt_mask, *cur_mask;
2041
2042     if (wined3d_settings.offscreen_rendering_mode == ORM_FBO)
2043     {
2044         context_validate_onscreen_formats(context, NULL);
2045
2046         if (context->render_offscreen)
2047         {
2048             surface_internal_preload(rt, SRGB_RGB);
2049
2050             context_apply_fbo_state_blit(context, GL_FRAMEBUFFER, rt, NULL, rt->draw_binding);
2051             if (rt->resource.format->id != WINED3DFMT_NULL)
2052                 rt_mask = 1;
2053             else
2054                 rt_mask = 0;
2055         }
2056         else
2057         {
2058             context_bind_fbo(context, GL_FRAMEBUFFER, NULL);
2059             rt_mask = context_generate_rt_mask_from_surface(rt);
2060         }
2061     }
2062     else
2063     {
2064         rt_mask = context_generate_rt_mask_no_fbo(device, rt);
2065     }
2066
2067     cur_mask = context->current_fbo ? &context->current_fbo->rt_mask : &context->draw_buffers_mask;
2068
2069     if (rt_mask != *cur_mask)
2070     {
2071         context_apply_draw_buffers(context, rt_mask);
2072         *cur_mask = rt_mask;
2073     }
2074
2075     if (wined3d_settings.offscreen_rendering_mode == ORM_FBO)
2076     {
2077         context_check_fbo_status(context, GL_FRAMEBUFFER);
2078     }
2079
2080     SetupForBlit(device, context);
2081     context_invalidate_state(context, STATE_FRAMEBUFFER);
2082 }
2083
2084 static BOOL context_validate_rt_config(UINT rt_count,
2085         struct wined3d_surface * const *rts, const struct wined3d_surface *ds)
2086 {
2087     unsigned int i;
2088
2089     if (ds) return TRUE;
2090
2091     for (i = 0; i < rt_count; ++i)
2092     {
2093         if (rts[i] && rts[i]->resource.format->id != WINED3DFMT_NULL)
2094             return TRUE;
2095     }
2096
2097     WARN("Invalid render target config, need at least one attachment.\n");
2098     return FALSE;
2099 }
2100
2101 /* Context activation is done by the caller. */
2102 BOOL context_apply_clear_state(struct wined3d_context *context, const struct wined3d_device *device,
2103         UINT rt_count, const struct wined3d_fb_state *fb)
2104 {
2105     const struct wined3d_gl_info *gl_info = context->gl_info;
2106     DWORD rt_mask = 0, *cur_mask;
2107     UINT i;
2108     struct wined3d_surface **rts = fb->render_targets;
2109
2110     if (isStateDirty(context, STATE_FRAMEBUFFER) || fb != &device->fb
2111             || rt_count != context->gl_info->limits.buffers)
2112     {
2113         if (!context_validate_rt_config(rt_count, rts, fb->depth_stencil))
2114             return FALSE;
2115
2116         if (wined3d_settings.offscreen_rendering_mode == ORM_FBO)
2117         {
2118             context_validate_onscreen_formats(context, fb->depth_stencil);
2119
2120             if (!rt_count || surface_is_offscreen(rts[0]))
2121             {
2122                 for (i = 0; i < rt_count; ++i)
2123                 {
2124                     context->blit_targets[i] = rts[i];
2125                     if (rts[i] && rts[i]->resource.format->id != WINED3DFMT_NULL)
2126                         rt_mask |= (1 << i);
2127                 }
2128                 while (i < context->gl_info->limits.buffers)
2129                 {
2130                     context->blit_targets[i] = NULL;
2131                     ++i;
2132                 }
2133                 context_apply_fbo_state(context, GL_FRAMEBUFFER, context->blit_targets, fb->depth_stencil,
2134                         rt_count ? rts[0]->draw_binding : SFLAG_INTEXTURE);
2135                 gl_info->gl_ops.gl.p_glReadBuffer(GL_NONE);
2136                 checkGLcall("glReadBuffer");
2137             }
2138             else
2139             {
2140                 context_apply_fbo_state(context, GL_FRAMEBUFFER, NULL, NULL, SFLAG_INDRAWABLE);
2141                 rt_mask = context_generate_rt_mask_from_surface(rts[0]);
2142             }
2143
2144             /* If the framebuffer is not the device's fb the device's fb has to be reapplied
2145              * next draw. Otherwise we could mark the framebuffer state clean here, once the
2146              * state management allows this */
2147             context_invalidate_state(context, STATE_FRAMEBUFFER);
2148         }
2149         else
2150         {
2151             rt_mask = context_generate_rt_mask_no_fbo(device, rt_count ? rts[0] : NULL);
2152         }
2153     }
2154     else if (wined3d_settings.offscreen_rendering_mode == ORM_FBO
2155             && (!rt_count || surface_is_offscreen(rts[0])))
2156     {
2157         for (i = 0; i < rt_count; ++i)
2158         {
2159             if (rts[i] && rts[i]->resource.format->id != WINED3DFMT_NULL) rt_mask |= (1 << i);
2160         }
2161     }
2162     else
2163     {
2164         rt_mask = context_generate_rt_mask_no_fbo(device, rt_count ? rts[0] : NULL);
2165     }
2166
2167     cur_mask = context->current_fbo ? &context->current_fbo->rt_mask : &context->draw_buffers_mask;
2168
2169     if (rt_mask != *cur_mask)
2170     {
2171         context_apply_draw_buffers(context, rt_mask);
2172         *cur_mask = rt_mask;
2173         context_invalidate_state(context, STATE_FRAMEBUFFER);
2174     }
2175
2176     if (wined3d_settings.offscreen_rendering_mode == ORM_FBO)
2177     {
2178         context_check_fbo_status(context, GL_FRAMEBUFFER);
2179     }
2180
2181     if (context->last_was_blit)
2182         context->last_was_blit = FALSE;
2183
2184     /* Blending and clearing should be orthogonal, but tests on the nvidia
2185      * driver show that disabling blending when clearing improves the clearing
2186      * performance incredibly. */
2187     gl_info->gl_ops.gl.p_glDisable(GL_BLEND);
2188     gl_info->gl_ops.gl.p_glEnable(GL_SCISSOR_TEST);
2189     checkGLcall("glEnable GL_SCISSOR_TEST");
2190
2191     context_invalidate_state(context, STATE_RENDER(WINED3D_RS_ALPHABLENDENABLE));
2192     context_invalidate_state(context, STATE_RENDER(WINED3D_RS_SCISSORTESTENABLE));
2193     context_invalidate_state(context, STATE_SCISSORRECT);
2194
2195     return TRUE;
2196 }
2197
2198 static DWORD find_draw_buffers_mask(const struct wined3d_context *context, const struct wined3d_device *device)
2199 {
2200     const struct wined3d_state *state = &device->stateBlock->state;
2201     struct wined3d_surface **rts = state->fb->render_targets;
2202     struct wined3d_shader *ps = state->pixel_shader;
2203     DWORD rt_mask, rt_mask_bits;
2204     unsigned int i;
2205
2206     if (wined3d_settings.offscreen_rendering_mode != ORM_FBO) return context_generate_rt_mask_no_fbo(device, rts[0]);
2207     else if (!context->render_offscreen) return context_generate_rt_mask_from_surface(rts[0]);
2208
2209     rt_mask = ps ? ps->reg_maps.rt_mask : 1;
2210     rt_mask &= device->valid_rt_mask;
2211     rt_mask_bits = rt_mask;
2212     i = 0;
2213     while (rt_mask_bits)
2214     {
2215         rt_mask_bits &= ~(1 << i);
2216         if (!rts[i] || rts[i]->resource.format->id == WINED3DFMT_NULL)
2217             rt_mask &= ~(1 << i);
2218
2219         i++;
2220     }
2221
2222     return rt_mask;
2223 }
2224
2225 /* Context activation is done by the caller. */
2226 void context_state_fb(struct wined3d_context *context, const struct wined3d_state *state, DWORD state_id)
2227 {
2228     const struct wined3d_device *device = context->swapchain->device;
2229     const struct wined3d_gl_info *gl_info = context->gl_info;
2230     const struct wined3d_fb_state *fb = state->fb;
2231     DWORD rt_mask = find_draw_buffers_mask(context, device);
2232     DWORD *cur_mask;
2233
2234     if (wined3d_settings.offscreen_rendering_mode == ORM_FBO)
2235     {
2236         if (!context->render_offscreen)
2237         {
2238             context_apply_fbo_state(context, GL_FRAMEBUFFER, NULL, NULL, SFLAG_INDRAWABLE);
2239         }
2240         else
2241         {
2242             context_apply_fbo_state(context, GL_FRAMEBUFFER, fb->render_targets, fb->depth_stencil,
2243                     fb->render_targets[0]->draw_binding);
2244             gl_info->gl_ops.gl.p_glReadBuffer(GL_NONE);
2245             checkGLcall("glReadBuffer");
2246         }
2247     }
2248
2249     cur_mask = context->current_fbo ? &context->current_fbo->rt_mask : &context->draw_buffers_mask;
2250     if (rt_mask != *cur_mask)
2251     {
2252         context_apply_draw_buffers(context, rt_mask);
2253         *cur_mask = rt_mask;
2254     }
2255 }
2256
2257 /* Context activation is done by the caller. */
2258 void context_state_drawbuf(struct wined3d_context *context, const struct wined3d_state *state, DWORD state_id)
2259 {
2260     const struct wined3d_device *device = context->swapchain->device;
2261     DWORD rt_mask, *cur_mask;
2262
2263     if (isStateDirty(context, STATE_FRAMEBUFFER)) return;
2264
2265     cur_mask = context->current_fbo ? &context->current_fbo->rt_mask : &context->draw_buffers_mask;
2266     rt_mask = find_draw_buffers_mask(context, device);
2267     if (rt_mask != *cur_mask)
2268     {
2269         context_apply_draw_buffers(context, rt_mask);
2270         *cur_mask = rt_mask;
2271     }
2272 }
2273
2274 /* Context activation is done by the caller. */
2275 BOOL context_apply_draw_state(struct wined3d_context *context, struct wined3d_device *device)
2276 {
2277     const struct wined3d_state *state = &device->stateBlock->state;
2278     const struct StateEntry *state_table = context->state_table;
2279     const struct wined3d_fb_state *fb = state->fb;
2280     unsigned int i;
2281
2282     if (!context_validate_rt_config(context->gl_info->limits.buffers,
2283             fb->render_targets, fb->depth_stencil))
2284         return FALSE;
2285
2286     if (wined3d_settings.offscreen_rendering_mode == ORM_FBO && isStateDirty(context, STATE_FRAMEBUFFER))
2287     {
2288         context_validate_onscreen_formats(context, fb->depth_stencil);
2289     }
2290
2291     /* Preload resources before FBO setup. Texture preload in particular may
2292      * result in changes to the current FBO, due to using e.g. FBO blits for
2293      * updating a resource location. */
2294     device_update_tex_unit_map(device);
2295     device_preload_textures(device);
2296     if (isStateDirty(context, STATE_VDECL) || isStateDirty(context, STATE_STREAMSRC))
2297         device_update_stream_info(device, context->gl_info);
2298     if (state->index_buffer)
2299     {
2300         if (device->strided_streams.all_vbo)
2301             wined3d_buffer_preload(state->index_buffer);
2302         else
2303             buffer_get_sysmem(state->index_buffer, context->gl_info);
2304     }
2305
2306     for (i = 0; i < context->numDirtyEntries; ++i)
2307     {
2308         DWORD rep = context->dirtyArray[i];
2309         DWORD idx = rep / (sizeof(*context->isStateDirty) * CHAR_BIT);
2310         BYTE shift = rep & ((sizeof(*context->isStateDirty) * CHAR_BIT) - 1);
2311         context->isStateDirty[idx] &= ~(1 << shift);
2312         state_table[rep].apply(context, state, rep);
2313     }
2314
2315     if (context->select_shader)
2316     {
2317         device->shader_backend->shader_select(context,
2318                 use_vs(state) ? WINED3D_SHADER_MODE_SHADER : WINED3D_SHADER_MODE_FFP,
2319                 use_ps(state) ? WINED3D_SHADER_MODE_SHADER : WINED3D_SHADER_MODE_FFP);
2320         context->select_shader = 0;
2321     }
2322
2323     if (context->load_constants)
2324     {
2325         device->shader_backend->shader_load_constants(context, use_ps(state), use_vs(state));
2326         context->load_constants = 0;
2327     }
2328
2329     if (wined3d_settings.offscreen_rendering_mode == ORM_FBO)
2330     {
2331         context_check_fbo_status(context, GL_FRAMEBUFFER);
2332     }
2333
2334     context->numDirtyEntries = 0; /* This makes the whole list clean */
2335     context->last_was_blit = FALSE;
2336
2337     return TRUE;
2338 }
2339
2340 static void context_setup_target(struct wined3d_context *context, struct wined3d_surface *target)
2341 {
2342     BOOL old_render_offscreen = context->render_offscreen, render_offscreen;
2343
2344     render_offscreen = surface_is_offscreen(target);
2345     if (context->current_rt == target && render_offscreen == old_render_offscreen) return;
2346
2347     /* To compensate the lack of format switching with some offscreen rendering methods and on onscreen buffers
2348      * the alpha blend state changes with different render target formats. */
2349     if (!context->current_rt)
2350     {
2351         context_invalidate_state(context, STATE_RENDER(WINED3D_RS_ALPHABLENDENABLE));
2352     }
2353     else
2354     {
2355         const struct wined3d_format *old = context->current_rt->resource.format;
2356         const struct wined3d_format *new = target->resource.format;
2357
2358         if (old->id != new->id)
2359         {
2360             /* Disable blending when the alpha mask has changed and when a format doesn't support blending. */
2361             if ((old->alpha_size && !new->alpha_size) || (!old->alpha_size && new->alpha_size)
2362                     || !(new->flags & WINED3DFMT_FLAG_POSTPIXELSHADER_BLENDING))
2363                 context_invalidate_state(context, STATE_RENDER(WINED3D_RS_ALPHABLENDENABLE));
2364
2365             /* Update sRGB writing when switching between formats that do/do not support sRGB writing */
2366             if ((old->flags & WINED3DFMT_FLAG_SRGB_WRITE) != (new->flags & WINED3DFMT_FLAG_SRGB_WRITE))
2367                 context_invalidate_state(context, STATE_RENDER(WINED3D_RS_SRGBWRITEENABLE));
2368         }
2369
2370         /* When switching away from an offscreen render target, and we're not
2371          * using FBOs, we have to read the drawable into the texture. This is
2372          * done via PreLoad (and SFLAG_INDRAWABLE set on the surface). There
2373          * are some things that need care though. PreLoad needs a GL context,
2374          * and FindContext is called before the context is activated. It also
2375          * has to be called with the old rendertarget active, otherwise a
2376          * wrong drawable is read. */
2377         if (wined3d_settings.offscreen_rendering_mode != ORM_FBO
2378                 && old_render_offscreen && context->current_rt != target)
2379         {
2380             /* Read the back buffer of the old drawable into the destination texture. */
2381             if (context->current_rt->texture_name_srgb)
2382                 surface_internal_preload(context->current_rt, SRGB_SRGB);
2383             surface_internal_preload(context->current_rt, SRGB_RGB);
2384             surface_modify_location(context->current_rt, SFLAG_INDRAWABLE, FALSE);
2385         }
2386     }
2387
2388     context->current_rt = target;
2389     context_set_render_offscreen(context, render_offscreen);
2390 }
2391
2392 /* Do not call while under the GL lock. */
2393 struct wined3d_context *context_acquire(const struct wined3d_device *device, struct wined3d_surface *target)
2394 {
2395     struct wined3d_context *current_context = context_get_current();
2396     struct wined3d_context *context;
2397
2398     TRACE("device %p, target %p.\n", device, target);
2399
2400     if (current_context && current_context->destroyed)
2401         current_context = NULL;
2402
2403     if (!target)
2404     {
2405         if (current_context
2406                 && current_context->current_rt
2407                 && current_context->swapchain->device == device)
2408         {
2409             target = current_context->current_rt;
2410         }
2411         else
2412         {
2413             struct wined3d_swapchain *swapchain = device->swapchains[0];
2414             if (swapchain->back_buffers)
2415                 target = swapchain->back_buffers[0];
2416             else
2417                 target = swapchain->front_buffer;
2418         }
2419     }
2420
2421     if (current_context && current_context->current_rt == target)
2422     {
2423         context = current_context;
2424     }
2425     else if (target->container.type == WINED3D_CONTAINER_SWAPCHAIN)
2426     {
2427         TRACE("Rendering onscreen.\n");
2428
2429         context = swapchain_get_context(target->container.u.swapchain);
2430     }
2431     else
2432     {
2433         TRACE("Rendering offscreen.\n");
2434
2435         /* Stay with the current context if possible. Otherwise use the
2436          * context for the primary swapchain. */
2437         if (current_context && current_context->swapchain->device == device)
2438             context = current_context;
2439         else
2440             context = swapchain_get_context(device->swapchains[0]);
2441     }
2442
2443     context_update_window(context);
2444     context_setup_target(context, target);
2445     context_enter(context);
2446     if (!context->valid) return context;
2447
2448     if (context != current_context)
2449     {
2450         if (!context_set_current(context))
2451             ERR("Failed to activate the new context.\n");
2452     }
2453     else if (context->restore_ctx)
2454     {
2455         context_set_gl_context(context);
2456     }
2457
2458     return context;
2459 }