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