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