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