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