gdi32: Check the region handle in GetClipRgn later.
[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     IWineD3DDeviceImpl *device = ((IWineD3DSurfaceImpl *)context->surface)->resource.device;
321     const struct wined3d_gl_info *gl_info = context->gl_info;
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     IWineD3DDeviceImpl *device = ((IWineD3DSurfaceImpl *)context->surface)->resource.device;
338     const struct wined3d_gl_info *gl_info = context->gl_info;
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     IWineD3DDeviceImpl *device = ((IWineD3DSurfaceImpl *)context->surface)->resource.device;
367     const struct wined3d_gl_info *gl_info = context->gl_info;
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     IWineD3DDeviceImpl *device = ((IWineD3DSurfaceImpl *)context->surface)->resource.device;
403     const struct wined3d_gl_info *gl_info = context->gl_info;
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 void context_validate(struct wined3d_context *context)
651 {
652     HWND wnd = WindowFromDC(context->hdc);
653
654     if (wnd != context->win_handle)
655     {
656         WARN("DC %p belongs to window %p instead of %p.\n",
657                 context->hdc, wnd, context->win_handle);
658         context->valid = 0;
659     }
660 }
661
662 static void context_destroy_gl_resources(struct wined3d_context *context)
663 {
664     const struct wined3d_gl_info *gl_info = context->gl_info;
665     struct wined3d_occlusion_query *occlusion_query;
666     struct wined3d_event_query *event_query;
667     struct fbo_entry *entry, *entry2;
668     HGLRC restore_ctx;
669     HDC restore_dc;
670     unsigned int i;
671
672     restore_ctx = pwglGetCurrentContext();
673     restore_dc = pwglGetCurrentDC();
674
675     context_validate(context);
676     if (context->valid && restore_ctx != context->glCtx) pwglMakeCurrent(context->hdc, context->glCtx);
677     else restore_ctx = NULL;
678
679     ENTER_GL();
680
681     LIST_FOR_EACH_ENTRY(occlusion_query, &context->occlusion_queries, struct wined3d_occlusion_query, entry)
682     {
683         if (context->valid && gl_info->supported[ARB_OCCLUSION_QUERY])
684             GL_EXTCALL(glDeleteQueriesARB(1, &occlusion_query->id));
685         occlusion_query->context = NULL;
686     }
687
688     LIST_FOR_EACH_ENTRY(event_query, &context->event_queries, struct wined3d_event_query, entry)
689     {
690         if (context->valid)
691         {
692             if (gl_info->supported[ARB_SYNC])
693             {
694                 if (event_query->object.sync) GL_EXTCALL(glDeleteSync(event_query->object.sync));
695             }
696             else if (gl_info->supported[APPLE_FENCE]) GL_EXTCALL(glDeleteFencesAPPLE(1, &event_query->object.id));
697             else if (gl_info->supported[NV_FENCE]) GL_EXTCALL(glDeleteFencesNV(1, &event_query->object.id));
698         }
699         event_query->context = NULL;
700     }
701
702     LIST_FOR_EACH_ENTRY_SAFE(entry, entry2, &context->fbo_destroy_list, struct fbo_entry, entry)
703     {
704         if (!context->valid) entry->id = 0;
705         context_destroy_fbo_entry(context, entry);
706     }
707
708     LIST_FOR_EACH_ENTRY_SAFE(entry, entry2, &context->fbo_list, struct fbo_entry, entry)
709     {
710         if (!context->valid) entry->id = 0;
711         context_destroy_fbo_entry(context, entry);
712     }
713
714     if (context->valid)
715     {
716         if (context->src_fbo)
717         {
718             TRACE("Destroy src FBO %d\n", context->src_fbo);
719             context_destroy_fbo(context, &context->src_fbo);
720         }
721         if (context->dst_fbo)
722         {
723             TRACE("Destroy dst FBO %d\n", context->dst_fbo);
724             context_destroy_fbo(context, &context->dst_fbo);
725         }
726         if (context->dummy_arbfp_prog)
727         {
728             GL_EXTCALL(glDeleteProgramsARB(1, &context->dummy_arbfp_prog));
729         }
730
731         if (gl_info->supported[ARB_OCCLUSION_QUERY])
732             GL_EXTCALL(glDeleteQueriesARB(context->free_occlusion_query_count, context->free_occlusion_queries));
733
734         if (gl_info->supported[ARB_SYNC])
735         {
736             if (event_query->object.sync) GL_EXTCALL(glDeleteSync(event_query->object.sync));
737         }
738         else if (gl_info->supported[APPLE_FENCE])
739         {
740             for (i = 0; i < context->free_event_query_count; ++i)
741             {
742                 GL_EXTCALL(glDeleteFencesAPPLE(1, &context->free_event_queries[i].id));
743             }
744         }
745         else if (gl_info->supported[NV_FENCE])
746         {
747             for (i = 0; i < context->free_event_query_count; ++i)
748             {
749                 GL_EXTCALL(glDeleteFencesNV(1, &context->free_event_queries[i].id));
750             }
751         }
752
753         checkGLcall("context cleanup");
754     }
755
756     LEAVE_GL();
757
758     HeapFree(GetProcessHeap(), 0, context->free_occlusion_queries);
759     HeapFree(GetProcessHeap(), 0, context->free_event_queries);
760
761     if (restore_ctx)
762     {
763         if (!pwglMakeCurrent(restore_dc, restore_ctx))
764         {
765             DWORD err = GetLastError();
766             ERR("Failed to restore GL context %p on device context %p, last error %#x.\n",
767                     restore_ctx, restore_dc, err);
768         }
769     }
770     else if (pwglGetCurrentContext() && !pwglMakeCurrent(NULL, NULL))
771     {
772         ERR("Failed to disable GL context.\n");
773     }
774
775     if (context->pbuffer)
776     {
777         GL_EXTCALL(wglReleasePbufferDCARB(context->pbuffer, context->hdc));
778         GL_EXTCALL(wglDestroyPbufferARB(context->pbuffer));
779     }
780     else
781     {
782         ReleaseDC(context->win_handle, context->hdc);
783     }
784
785     if (!pwglDeleteContext(context->glCtx))
786     {
787         DWORD err = GetLastError();
788         ERR("wglDeleteContext(%p) failed, last error %#x.\n", context->glCtx, err);
789     }
790 }
791
792 DWORD context_get_tls_idx(void)
793 {
794     return wined3d_context_tls_idx;
795 }
796
797 void context_set_tls_idx(DWORD idx)
798 {
799     wined3d_context_tls_idx = idx;
800 }
801
802 struct wined3d_context *context_get_current(void)
803 {
804     return TlsGetValue(wined3d_context_tls_idx);
805 }
806
807 BOOL context_set_current(struct wined3d_context *ctx)
808 {
809     struct wined3d_context *old = context_get_current();
810
811     if (old == ctx)
812     {
813         TRACE("Already using D3D context %p.\n", ctx);
814         return TRUE;
815     }
816
817     if (old)
818     {
819         if (old->destroyed)
820         {
821             TRACE("Switching away from destroyed context %p.\n", old);
822             context_destroy_gl_resources(old);
823             HeapFree(GetProcessHeap(), 0, old);
824         }
825         else
826         {
827             old->current = 0;
828         }
829     }
830
831     if (ctx)
832     {
833         TRACE("Switching to D3D context %p, GL context %p, device context %p.\n", ctx, ctx->glCtx, ctx->hdc);
834         if (!pwglMakeCurrent(ctx->hdc, ctx->glCtx))
835         {
836             DWORD err = GetLastError();
837             ERR("Failed to make GL context %p current on device context %p, last error %#x.\n",
838                     ctx->glCtx, ctx->hdc, err);
839             TlsSetValue(wined3d_context_tls_idx, NULL);
840             return FALSE;
841         }
842         ctx->current = 1;
843     }
844     else if(pwglGetCurrentContext())
845     {
846         TRACE("Clearing current D3D context.\n");
847         if (!pwglMakeCurrent(NULL, NULL))
848         {
849             DWORD err = GetLastError();
850             ERR("Failed to clear current GL context, last error %#x.\n", err);
851             TlsSetValue(wined3d_context_tls_idx, NULL);
852             return FALSE;
853         }
854     }
855
856     return TlsSetValue(wined3d_context_tls_idx, ctx);
857 }
858
859 void context_release(struct wined3d_context *context)
860 {
861     TRACE("Releasing context %p, level %u.\n", context, context->level);
862
863     if (WARN_ON(d3d))
864     {
865         if (!context->level)
866             WARN("Context %p is not active.\n", context);
867         else if (context != context_get_current())
868             WARN("Context %p is not the current context.\n", context);
869     }
870
871     if (!--context->level && context->restore_ctx)
872     {
873         TRACE("Restoring GL context %p on device context %p.\n", context->restore_ctx, context->restore_dc);
874         if (!pwglMakeCurrent(context->restore_dc, context->restore_ctx))
875         {
876             DWORD err = GetLastError();
877             ERR("Failed to restore GL context %p on device context %p, last error %#x.\n",
878                     context->restore_ctx, context->restore_dc, err);
879         }
880         context->restore_ctx = NULL;
881         context->restore_dc = NULL;
882     }
883 }
884
885 static void context_enter(struct wined3d_context *context)
886 {
887     TRACE("Entering context %p, level %u.\n", context, context->level + 1);
888
889     if (!context->level++)
890     {
891         const struct wined3d_context *current_context = context_get_current();
892         HGLRC current_gl = pwglGetCurrentContext();
893
894         if (current_gl && (!current_context || current_context->glCtx != current_gl))
895         {
896             TRACE("Another GL context (%p on device context %p) is already current.\n",
897                     current_gl, pwglGetCurrentDC());
898             context->restore_ctx = current_gl;
899             context->restore_dc = pwglGetCurrentDC();
900         }
901     }
902 }
903
904 /*****************************************************************************
905  * Context_MarkStateDirty
906  *
907  * Marks a state in a context dirty. Only one context, opposed to
908  * IWineD3DDeviceImpl_MarkStateDirty, which marks the state dirty in all
909  * contexts
910  *
911  * Params:
912  *  context: Context to mark the state dirty in
913  *  state: State to mark dirty
914  *  StateTable: Pointer to the state table in use(for state grouping)
915  *
916  *****************************************************************************/
917 static void Context_MarkStateDirty(struct wined3d_context *context, DWORD state, const struct StateEntry *StateTable)
918 {
919     DWORD rep = StateTable[state].representative;
920     DWORD idx;
921     BYTE shift;
922
923     if (isStateDirty(context, rep)) return;
924
925     context->dirtyArray[context->numDirtyEntries++] = rep;
926     idx = rep / (sizeof(*context->isStateDirty) * CHAR_BIT);
927     shift = rep & ((sizeof(*context->isStateDirty) * CHAR_BIT) - 1);
928     context->isStateDirty[idx] |= (1 << shift);
929 }
930
931 /*****************************************************************************
932  * AddContextToArray
933  *
934  * Adds a context to the context array. Helper function for context_create().
935  *
936  * This method is not called in performance-critical code paths, only when a
937  * new render target or swapchain is created. Thus performance is not an issue
938  * here.
939  *
940  * Params:
941  *  This: Device to add the context for
942  *  hdc: device context
943  *  glCtx: WGL context to add
944  *  pbuffer: optional pbuffer used with this context
945  *
946  *****************************************************************************/
947 static struct wined3d_context *AddContextToArray(IWineD3DDeviceImpl *This,
948         HWND win_handle, HDC hdc, HGLRC glCtx, HPBUFFERARB pbuffer)
949 {
950     struct wined3d_context **oldArray = This->contexts;
951     DWORD state;
952
953     This->contexts = HeapAlloc(GetProcessHeap(), 0, sizeof(*This->contexts) * (This->numContexts + 1));
954     if(This->contexts == NULL) {
955         ERR("Unable to grow the context array\n");
956         This->contexts = oldArray;
957         return NULL;
958     }
959     if(oldArray) {
960         memcpy(This->contexts, oldArray, sizeof(*This->contexts) * This->numContexts);
961     }
962
963     This->contexts[This->numContexts] = HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, sizeof(**This->contexts));
964     if(This->contexts[This->numContexts] == NULL) {
965         ERR("Unable to allocate a new context\n");
966         HeapFree(GetProcessHeap(), 0, This->contexts);
967         This->contexts = oldArray;
968         return NULL;
969     }
970
971     This->contexts[This->numContexts]->hdc = hdc;
972     This->contexts[This->numContexts]->glCtx = glCtx;
973     This->contexts[This->numContexts]->pbuffer = pbuffer;
974     This->contexts[This->numContexts]->win_handle = win_handle;
975     HeapFree(GetProcessHeap(), 0, oldArray);
976
977     /* Mark all states dirty to force a proper initialization of the states on the first use of the context
978      */
979     for(state = 0; state <= STATE_HIGHEST; state++) {
980         if (This->StateTable[state].representative)
981             Context_MarkStateDirty(This->contexts[This->numContexts], state, This->StateTable);
982     }
983
984     This->numContexts++;
985     TRACE("Created context %p\n", This->contexts[This->numContexts - 1]);
986     return This->contexts[This->numContexts - 1];
987 }
988
989 /* This function takes care of WineD3D pixel format selection. */
990 static int WineD3D_ChoosePixelFormat(IWineD3DDeviceImpl *This, HDC hdc,
991         const struct GlPixelFormatDesc *color_format_desc, const struct GlPixelFormatDesc *ds_format_desc,
992         BOOL auxBuffers, int numSamples, BOOL pbuffer, BOOL findCompatible)
993 {
994     int iPixelFormat=0;
995     unsigned int matchtry;
996     short redBits, greenBits, blueBits, alphaBits, colorBits;
997     short depthBits=0, stencilBits=0;
998
999     struct match_type {
1000         BOOL require_aux;
1001         BOOL exact_alpha;
1002         BOOL exact_color;
1003     } matches[] = {
1004         /* First, try without alpha match buffers. MacOS supports aux buffers only
1005          * on A8R8G8B8, and we prefer better offscreen rendering over an alpha match.
1006          * Then try without aux buffers - this is the most common cause for not
1007          * finding a pixel format. Also some drivers(the open source ones)
1008          * only offer 32 bit ARB pixel formats. First try without an exact alpha
1009          * match, then try without an exact alpha and color match.
1010          */
1011         { TRUE,  TRUE,  TRUE  },
1012         { TRUE,  FALSE, TRUE  },
1013         { FALSE, TRUE,  TRUE  },
1014         { FALSE, FALSE, TRUE  },
1015         { TRUE,  FALSE, FALSE },
1016         { FALSE, FALSE, FALSE },
1017     };
1018
1019     int i = 0;
1020     int nCfgs = This->adapter->nCfgs;
1021
1022     TRACE("ColorFormat=%s, DepthStencilFormat=%s, auxBuffers=%d, numSamples=%d, pbuffer=%d, findCompatible=%d\n",
1023           debug_d3dformat(color_format_desc->format), debug_d3dformat(ds_format_desc->format),
1024           auxBuffers, numSamples, pbuffer, findCompatible);
1025
1026     if (!getColorBits(color_format_desc, &redBits, &greenBits, &blueBits, &alphaBits, &colorBits))
1027     {
1028         ERR("Unable to get color bits for format %s (%#x)!\n",
1029                 debug_d3dformat(color_format_desc->format), color_format_desc->format);
1030         return 0;
1031     }
1032
1033     /* In WGL both color, depth and stencil are features of a pixel format. In case of D3D they are separate.
1034      * You are able to add a depth + stencil surface at a later stage when you need it.
1035      * In order to support this properly in WineD3D we need the ability to recreate the opengl context and
1036      * drawable when this is required. This is very tricky as we need to reapply ALL opengl states for the new
1037      * context, need torecreate shaders, textures and other resources.
1038      *
1039      * The context manager already takes care of the state problem and for the other tasks code from Reset
1040      * can be used. These changes are way to risky during the 1.0 code freeze which is taking place right now.
1041      * Likely a lot of other new bugs will be exposed. For that reason request a depth stencil surface all the
1042      * time. It can cause a slight performance hit but fixes a lot of regressions. A fixme reminds of that this
1043      * issue needs to be fixed. */
1044     if (ds_format_desc->format != WINED3DFMT_D24_UNORM_S8_UINT)
1045     {
1046         FIXME("Add OpenGL context recreation support to SetDepthStencilSurface\n");
1047         ds_format_desc = getFormatDescEntry(WINED3DFMT_D24_UNORM_S8_UINT, &This->adapter->gl_info);
1048     }
1049
1050     getDepthStencilBits(ds_format_desc, &depthBits, &stencilBits);
1051
1052     for(matchtry = 0; matchtry < (sizeof(matches) / sizeof(matches[0])) && !iPixelFormat; matchtry++) {
1053         for(i=0; i<nCfgs; i++) {
1054             BOOL exactDepthMatch = TRUE;
1055             WineD3D_PixelFormat *cfg = &This->adapter->cfgs[i];
1056
1057             /* For now only accept RGBA formats. Perhaps some day we will
1058              * allow floating point formats for pbuffers. */
1059             if(cfg->iPixelType != WGL_TYPE_RGBA_ARB)
1060                 continue;
1061
1062             /* In window mode (!pbuffer) we need a window drawable format and double buffering. */
1063             if(!pbuffer && !(cfg->windowDrawable && cfg->doubleBuffer))
1064                 continue;
1065
1066             /* We like to have aux buffers in backbuffer mode */
1067             if(auxBuffers && !cfg->auxBuffers && matches[matchtry].require_aux)
1068                 continue;
1069
1070             /* In pbuffer-mode we need a pbuffer-capable format but we don't want double buffering */
1071             if(pbuffer && (!cfg->pbufferDrawable || cfg->doubleBuffer))
1072                 continue;
1073
1074             if(matches[matchtry].exact_color) {
1075                 if(cfg->redSize != redBits)
1076                     continue;
1077                 if(cfg->greenSize != greenBits)
1078                     continue;
1079                 if(cfg->blueSize != blueBits)
1080                     continue;
1081             } else {
1082                 if(cfg->redSize < redBits)
1083                     continue;
1084                 if(cfg->greenSize < greenBits)
1085                     continue;
1086                 if(cfg->blueSize < blueBits)
1087                     continue;
1088             }
1089             if(matches[matchtry].exact_alpha) {
1090                 if(cfg->alphaSize != alphaBits)
1091                     continue;
1092             } else {
1093                 if(cfg->alphaSize < alphaBits)
1094                     continue;
1095             }
1096
1097             /* We try to locate a format which matches our requirements exactly. In case of
1098              * depth it is no problem to emulate 16-bit using e.g. 24-bit, so accept that. */
1099             if(cfg->depthSize < depthBits)
1100                 continue;
1101             else if(cfg->depthSize > depthBits)
1102                 exactDepthMatch = FALSE;
1103
1104             /* In all cases make sure the number of stencil bits matches our requirements
1105              * even when we don't need stencil because it could affect performance EXCEPT
1106              * on cards which don't offer depth formats without stencil like the i915 drivers
1107              * on Linux. */
1108             if(stencilBits != cfg->stencilSize && !(This->adapter->brokenStencil && stencilBits <= cfg->stencilSize))
1109                 continue;
1110
1111             /* Check multisampling support */
1112             if(cfg->numSamples != numSamples)
1113                 continue;
1114
1115             /* When we have passed all the checks then we have found a format which matches our
1116              * requirements. Note that we only check for a limit number of capabilities right now,
1117              * so there can easily be a dozen of pixel formats which appear to be the 'same' but
1118              * can still differ in things like multisampling, stereo, SRGB and other flags.
1119              */
1120
1121             /* Exit the loop as we have found a format :) */
1122             if(exactDepthMatch) {
1123                 iPixelFormat = cfg->iPixelFormat;
1124                 break;
1125             } else if(!iPixelFormat) {
1126                 /* In the end we might end up with a format which doesn't exactly match our depth
1127                  * requirements. Accept the first format we found because formats with higher iPixelFormat
1128                  * values tend to have more extended capabilities (e.g. multisampling) which we don't need. */
1129                 iPixelFormat = cfg->iPixelFormat;
1130             }
1131         }
1132     }
1133
1134     /* When findCompatible is set and no suitable format was found, let ChoosePixelFormat choose a pixel format in order not to crash. */
1135     if(!iPixelFormat && !findCompatible) {
1136         ERR("Can't find a suitable iPixelFormat\n");
1137         return FALSE;
1138     } else if(!iPixelFormat) {
1139         PIXELFORMATDESCRIPTOR pfd;
1140
1141         TRACE("Falling back to ChoosePixelFormat as we weren't able to find an exactly matching pixel format\n");
1142         /* PixelFormat selection */
1143         ZeroMemory(&pfd, sizeof(pfd));
1144         pfd.nSize      = sizeof(pfd);
1145         pfd.nVersion   = 1;
1146         pfd.dwFlags    = PFD_SUPPORT_OPENGL | PFD_DOUBLEBUFFER | PFD_DRAW_TO_WINDOW;/*PFD_GENERIC_ACCELERATED*/
1147         pfd.iPixelType = PFD_TYPE_RGBA;
1148         pfd.cAlphaBits = alphaBits;
1149         pfd.cColorBits = colorBits;
1150         pfd.cDepthBits = depthBits;
1151         pfd.cStencilBits = stencilBits;
1152         pfd.iLayerType = PFD_MAIN_PLANE;
1153
1154         iPixelFormat = ChoosePixelFormat(hdc, &pfd);
1155         if(!iPixelFormat) {
1156             /* If this happens something is very wrong as ChoosePixelFormat barely fails */
1157             ERR("Can't find a suitable iPixelFormat\n");
1158             return FALSE;
1159         }
1160     }
1161
1162     TRACE("Found iPixelFormat=%d for ColorFormat=%s, DepthStencilFormat=%s\n",
1163             iPixelFormat, debug_d3dformat(color_format_desc->format), debug_d3dformat(ds_format_desc->format));
1164     return iPixelFormat;
1165 }
1166
1167 /*****************************************************************************
1168  * context_create
1169  *
1170  * Creates a new context for a window, or a pbuffer context.
1171  *
1172  * * Params:
1173  *  This: Device to activate the context for
1174  *  target: Surface this context will render to
1175  *  win_handle: handle to the window which we are drawing to
1176  *  create_pbuffer: tells whether to create a pbuffer or not
1177  *  pPresentParameters: contains the pixelformats to use for onscreen rendering
1178  *
1179  *****************************************************************************/
1180 struct wined3d_context *context_create(IWineD3DDeviceImpl *This, IWineD3DSurfaceImpl *target,
1181         HWND win_handle, BOOL create_pbuffer, const WINED3DPRESENT_PARAMETERS *pPresentParms)
1182 {
1183     const struct wined3d_gl_info *gl_info = &This->adapter->gl_info;
1184     struct wined3d_context *ret = NULL;
1185     HPBUFFERARB pbuffer = NULL;
1186     unsigned int s;
1187     HGLRC ctx;
1188     HDC hdc;
1189
1190     TRACE("(%p): Creating a %s context for render target %p\n", This, create_pbuffer ? "offscreen" : "onscreen", target);
1191
1192     if(create_pbuffer) {
1193         HDC hdc_parent = GetDC(win_handle);
1194         int iPixelFormat = 0;
1195
1196         IWineD3DSurface *StencilSurface = This->stencilBufferTarget;
1197         const struct GlPixelFormatDesc *ds_format_desc = StencilSurface
1198                 ? ((IWineD3DSurfaceImpl *)StencilSurface)->resource.format_desc
1199                 : getFormatDescEntry(WINED3DFMT_UNKNOWN, &This->adapter->gl_info);
1200
1201         /* Try to find a pixel format with pbuffer support. */
1202         iPixelFormat = WineD3D_ChoosePixelFormat(This, hdc_parent, target->resource.format_desc,
1203                 ds_format_desc, FALSE /* auxBuffers */, 0 /* numSamples */, TRUE /* PBUFFER */,
1204                 FALSE /* findCompatible */);
1205         if(!iPixelFormat) {
1206             TRACE("Trying to locate a compatible pixel format because an exact match failed.\n");
1207
1208             /* For some reason we weren't able to find a format, try to find something instead of crashing.
1209              * A reason for failure could have been wglChoosePixelFormatARB strictness. */
1210             iPixelFormat = WineD3D_ChoosePixelFormat(This, hdc_parent, target->resource.format_desc,
1211                     ds_format_desc, FALSE /* auxBuffer */, 0 /* numSamples */, TRUE /* PBUFFER */,
1212                     TRUE /* findCompatible */);
1213         }
1214
1215         /* This shouldn't happen as ChoosePixelFormat always returns something */
1216         if(!iPixelFormat) {
1217             ERR("Unable to locate a pixel format for a pbuffer\n");
1218             ReleaseDC(win_handle, hdc_parent);
1219             goto out;
1220         }
1221
1222         TRACE("Creating a pBuffer drawable for the new context\n");
1223         pbuffer = GL_EXTCALL(wglCreatePbufferARB(hdc_parent, iPixelFormat, target->currentDesc.Width, target->currentDesc.Height, 0));
1224         if(!pbuffer) {
1225             ERR("Cannot create a pbuffer\n");
1226             ReleaseDC(win_handle, hdc_parent);
1227             goto out;
1228         }
1229
1230         /* In WGL a pbuffer is 'wrapped' inside a HDC to 'fool' wglMakeCurrent */
1231         hdc = GL_EXTCALL(wglGetPbufferDCARB(pbuffer));
1232         if(!hdc) {
1233             ERR("Cannot get a HDC for pbuffer (%p)\n", pbuffer);
1234             GL_EXTCALL(wglDestroyPbufferARB(pbuffer));
1235             ReleaseDC(win_handle, hdc_parent);
1236             goto out;
1237         }
1238         ReleaseDC(win_handle, hdc_parent);
1239     } else {
1240         PIXELFORMATDESCRIPTOR pfd;
1241         int iPixelFormat;
1242         int res;
1243         const struct GlPixelFormatDesc *color_format_desc = target->resource.format_desc;
1244         const struct GlPixelFormatDesc *ds_format_desc = getFormatDescEntry(WINED3DFMT_UNKNOWN,
1245                 &This->adapter->gl_info);
1246         BOOL auxBuffers = FALSE;
1247         int numSamples = 0;
1248
1249         hdc = GetDC(win_handle);
1250         if(hdc == NULL) {
1251             ERR("Cannot retrieve a device context!\n");
1252             goto out;
1253         }
1254
1255         /* In case of ORM_BACKBUFFER, make sure to request an alpha component for X4R4G4B4/X8R8G8B8 as we might need it for the backbuffer. */
1256         if(wined3d_settings.offscreen_rendering_mode == ORM_BACKBUFFER) {
1257             auxBuffers = TRUE;
1258
1259             if (color_format_desc->format == WINED3DFMT_B4G4R4X4_UNORM)
1260                 color_format_desc = getFormatDescEntry(WINED3DFMT_B4G4R4A4_UNORM, &This->adapter->gl_info);
1261             else if (color_format_desc->format == WINED3DFMT_B8G8R8X8_UNORM)
1262                 color_format_desc = getFormatDescEntry(WINED3DFMT_B8G8R8A8_UNORM, &This->adapter->gl_info);
1263         }
1264
1265         /* DirectDraw supports 8bit paletted render targets and these are used by old games like Starcraft and C&C.
1266          * Most modern hardware doesn't support 8bit natively so we perform some form of 8bit -> 32bit conversion.
1267          * The conversion (ab)uses the alpha component for storing the palette index. For this reason we require
1268          * a format with 8bit alpha, so request A8R8G8B8. */
1269         if (color_format_desc->format == WINED3DFMT_P8_UINT)
1270             color_format_desc = getFormatDescEntry(WINED3DFMT_B8G8R8A8_UNORM, &This->adapter->gl_info);
1271
1272         /* Retrieve the depth stencil format from the present parameters.
1273          * The choice of the proper format can give a nice performance boost
1274          * in case of GPU limited programs. */
1275         if(pPresentParms->EnableAutoDepthStencil) {
1276             TRACE("pPresentParms->EnableAutoDepthStencil=enabled; using AutoDepthStencilFormat=%s\n", debug_d3dformat(pPresentParms->AutoDepthStencilFormat));
1277             ds_format_desc = getFormatDescEntry(pPresentParms->AutoDepthStencilFormat, &This->adapter->gl_info);
1278         }
1279
1280         /* D3D only allows multisampling when SwapEffect is set to WINED3DSWAPEFFECT_DISCARD */
1281         if(pPresentParms->MultiSampleType && (pPresentParms->SwapEffect == WINED3DSWAPEFFECT_DISCARD)) {
1282             if (!gl_info->supported[ARB_MULTISAMPLE])
1283                 ERR("The program is requesting multisampling without support!\n");
1284             else
1285             {
1286                 TRACE("Requesting multisample type %#x.\n", pPresentParms->MultiSampleType);
1287                 numSamples = pPresentParms->MultiSampleType;
1288             }
1289         }
1290
1291         /* Try to find a pixel format which matches our requirements */
1292         iPixelFormat = WineD3D_ChoosePixelFormat(This, hdc, color_format_desc, ds_format_desc,
1293                 auxBuffers, numSamples, FALSE /* PBUFFER */, FALSE /* findCompatible */);
1294
1295         /* Try to locate a compatible format if we weren't able to find anything */
1296         if(!iPixelFormat) {
1297             TRACE("Trying to locate a compatible pixel format because an exact match failed.\n");
1298             iPixelFormat = WineD3D_ChoosePixelFormat(This, hdc, color_format_desc, ds_format_desc,
1299                     auxBuffers, 0 /* numSamples */, FALSE /* PBUFFER */, TRUE /* findCompatible */ );
1300         }
1301
1302         /* If we still don't have a pixel format, something is very wrong as ChoosePixelFormat barely fails */
1303         if(!iPixelFormat) {
1304             ERR("Can't find a suitable iPixelFormat\n");
1305             return NULL;
1306         }
1307
1308         DescribePixelFormat(hdc, iPixelFormat, sizeof(pfd), &pfd);
1309         res = SetPixelFormat(hdc, iPixelFormat, NULL);
1310         if(!res) {
1311             int oldPixelFormat = GetPixelFormat(hdc);
1312
1313             /* By default WGL doesn't allow pixel format adjustments but we need it here.
1314              * For this reason there is a WINE-specific wglSetPixelFormat which allows you to
1315              * set the pixel format multiple times. Only use it when it is really needed. */
1316
1317             if(oldPixelFormat == iPixelFormat) {
1318                 /* We don't have to do anything as the formats are the same :) */
1319             }
1320             else if (oldPixelFormat && gl_info->supported[WGL_WINE_PIXEL_FORMAT_PASSTHROUGH])
1321             {
1322                 res = GL_EXTCALL(wglSetPixelFormatWINE(hdc, iPixelFormat, NULL));
1323
1324                 if(!res) {
1325                     ERR("wglSetPixelFormatWINE failed on HDC=%p for iPixelFormat=%d\n", hdc, iPixelFormat);
1326                     return NULL;
1327                 }
1328             } else if(oldPixelFormat) {
1329                 /* OpenGL doesn't allow pixel format adjustments. Print an error and continue using the old format.
1330                  * There's a big chance that the old format works although with a performance hit and perhaps rendering errors. */
1331                 ERR("HDC=%p is already set to iPixelFormat=%d and OpenGL doesn't allow changes!\n", hdc, oldPixelFormat);
1332             } else {
1333                 ERR("SetPixelFormat failed on HDC=%p for iPixelFormat=%d\n", hdc, iPixelFormat);
1334                 return NULL;
1335             }
1336         }
1337     }
1338
1339     ctx = pwglCreateContext(hdc);
1340     if (This->numContexts)
1341     {
1342         if (!pwglShareLists(This->contexts[0]->glCtx, ctx))
1343         {
1344             DWORD err = GetLastError();
1345             ERR("wglShareLists(%p, %p) failed, last error %#x.\n",
1346                     This->contexts[0]->glCtx, ctx, err);
1347         }
1348     }
1349
1350     if(!ctx) {
1351         ERR("Failed to create a WGL context\n");
1352         if(create_pbuffer) {
1353             GL_EXTCALL(wglReleasePbufferDCARB(pbuffer, hdc));
1354             GL_EXTCALL(wglDestroyPbufferARB(pbuffer));
1355         }
1356         goto out;
1357     }
1358     ret = AddContextToArray(This, win_handle, hdc, ctx, pbuffer);
1359     if(!ret) {
1360         ERR("Failed to add the newly created context to the context list\n");
1361         if (!pwglDeleteContext(ctx))
1362         {
1363             DWORD err = GetLastError();
1364             ERR("wglDeleteContext(%p) failed, last error %#x.\n", ctx, err);
1365         }
1366         if(create_pbuffer) {
1367             GL_EXTCALL(wglReleasePbufferDCARB(pbuffer, hdc));
1368             GL_EXTCALL(wglDestroyPbufferARB(pbuffer));
1369         }
1370         goto out;
1371     }
1372     ret->valid = 1;
1373     ret->gl_info = &This->adapter->gl_info;
1374     ret->surface = (IWineD3DSurface *) target;
1375     ret->current_rt = (IWineD3DSurface *)target;
1376     ret->render_offscreen = surface_is_offscreen((IWineD3DSurface *) target);
1377     ret->draw_buffer_dirty = TRUE;
1378     ret->tid = GetCurrentThreadId();
1379     if(This->shader_backend->shader_dirtifyable_constants((IWineD3DDevice *) This)) {
1380         /* Create the dirty constants array and initialize them to dirty */
1381         ret->vshader_const_dirty = HeapAlloc(GetProcessHeap(), 0,
1382                 sizeof(*ret->vshader_const_dirty) * This->d3d_vshader_constantF);
1383         ret->pshader_const_dirty = HeapAlloc(GetProcessHeap(), 0,
1384                 sizeof(*ret->pshader_const_dirty) * This->d3d_pshader_constantF);
1385         memset(ret->vshader_const_dirty, 1,
1386                sizeof(*ret->vshader_const_dirty) * This->d3d_vshader_constantF);
1387         memset(ret->pshader_const_dirty, 1,
1388                 sizeof(*ret->pshader_const_dirty) * This->d3d_pshader_constantF);
1389     }
1390
1391     ret->free_occlusion_query_size = 4;
1392     ret->free_occlusion_queries = HeapAlloc(GetProcessHeap(), 0,
1393             ret->free_occlusion_query_size * sizeof(*ret->free_occlusion_queries));
1394     if (!ret->free_occlusion_queries) goto out;
1395
1396     list_init(&ret->occlusion_queries);
1397
1398     ret->free_event_query_size = 4;
1399     ret->free_event_queries = HeapAlloc(GetProcessHeap(), 0,
1400             ret->free_event_query_size * sizeof(*ret->free_event_queries));
1401     if (!ret->free_event_queries) goto out;
1402
1403     list_init(&ret->event_queries);
1404
1405     TRACE("Successfully created new context %p\n", ret);
1406
1407     list_init(&ret->fbo_list);
1408     list_init(&ret->fbo_destroy_list);
1409
1410     context_enter(ret);
1411
1412     /* Set up the context defaults */
1413     if (!context_set_current(ret))
1414     {
1415         ERR("Cannot activate context to set up defaults\n");
1416         context_release(ret);
1417         goto out;
1418     }
1419
1420     ENTER_GL();
1421
1422     glGetIntegerv(GL_AUX_BUFFERS, &ret->aux_buffers);
1423
1424     TRACE("Setting up the screen\n");
1425     /* Clear the screen */
1426     glClearColor(1.0f, 0.0f, 0.0f, 0.0f);
1427     checkGLcall("glClearColor");
1428     glClearIndex(0);
1429     glClearDepth(1);
1430     glClearStencil(0xffff);
1431
1432     checkGLcall("glClear");
1433
1434     glLightModeli(GL_LIGHT_MODEL_LOCAL_VIEWER, GL_TRUE);
1435     checkGLcall("glLightModeli(GL_LIGHT_MODEL_LOCAL_VIEWER, GL_TRUE);");
1436
1437     glTexEnvf(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_COMBINE_EXT);
1438     checkGLcall("glTexEnvf(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_COMBINE_EXT);");
1439
1440     glLightModeli(GL_LIGHT_MODEL_COLOR_CONTROL, GL_SEPARATE_SPECULAR_COLOR);
1441     checkGLcall("glLightModeli(GL_LIGHT_MODEL_COLOR_CONTROL, GL_SEPARATE_SPECULAR_COLOR);");
1442
1443     glPixelStorei(GL_PACK_ALIGNMENT, This->surface_alignment);
1444     checkGLcall("glPixelStorei(GL_PACK_ALIGNMENT, This->surface_alignment);");
1445     glPixelStorei(GL_UNPACK_ALIGNMENT, This->surface_alignment);
1446     checkGLcall("glPixelStorei(GL_UNPACK_ALIGNMENT, This->surface_alignment);");
1447
1448     if (gl_info->supported[APPLE_CLIENT_STORAGE])
1449     {
1450         /* Most textures will use client storage if supported. Exceptions are non-native power of 2 textures
1451          * and textures in DIB sections(due to the memory protection).
1452          */
1453         glPixelStorei(GL_UNPACK_CLIENT_STORAGE_APPLE, GL_TRUE);
1454         checkGLcall("glPixelStorei(GL_UNPACK_CLIENT_STORAGE_APPLE, GL_TRUE)");
1455     }
1456     if (gl_info->supported[ARB_VERTEX_BLEND])
1457     {
1458         /* Direct3D always uses n-1 weights for n world matrices and uses 1 - sum for the last one
1459          * this is equal to GL_WEIGHT_SUM_UNITY_ARB. Enabling it doesn't do anything unless
1460          * GL_VERTEX_BLEND_ARB isn't enabled too
1461          */
1462         glEnable(GL_WEIGHT_SUM_UNITY_ARB);
1463         checkGLcall("glEnable(GL_WEIGHT_SUM_UNITY_ARB)");
1464     }
1465     if (gl_info->supported[NV_TEXTURE_SHADER2])
1466     {
1467         /* Set up the previous texture input for all shader units. This applies to bump mapping, and in d3d
1468          * the previous texture where to source the offset from is always unit - 1.
1469          */
1470         for (s = 1; s < gl_info->limits.textures; ++s)
1471         {
1472             GL_EXTCALL(glActiveTextureARB(GL_TEXTURE0_ARB + s));
1473             glTexEnvi(GL_TEXTURE_SHADER_NV, GL_PREVIOUS_TEXTURE_INPUT_NV, GL_TEXTURE0_ARB + s - 1);
1474             checkGLcall("glTexEnvi(GL_TEXTURE_SHADER_NV, GL_PREVIOUS_TEXTURE_INPUT_NV, ...");
1475         }
1476     }
1477     if (gl_info->supported[ARB_FRAGMENT_PROGRAM])
1478     {
1479         /* MacOS(radeon X1600 at least, but most likely others too) refuses to draw if GLSL and ARBFP are
1480          * enabled, but the currently bound arbfp program is 0. Enabling ARBFP with prog 0 is invalid, but
1481          * GLSL should bypass this. This causes problems in programs that never use the fixed function pipeline,
1482          * because the ARBFP extension is enabled by the ARBFP pipeline at context creation, but no program
1483          * is ever assigned.
1484          *
1485          * So make sure a program is assigned to each context. The first real ARBFP use will set a different
1486          * program and the dummy program is destroyed when the context is destroyed.
1487          */
1488         const char *dummy_program =
1489                 "!!ARBfp1.0\n"
1490                 "MOV result.color, fragment.color.primary;\n"
1491                 "END\n";
1492         GL_EXTCALL(glGenProgramsARB(1, &ret->dummy_arbfp_prog));
1493         GL_EXTCALL(glBindProgramARB(GL_FRAGMENT_PROGRAM_ARB, ret->dummy_arbfp_prog));
1494         GL_EXTCALL(glProgramStringARB(GL_FRAGMENT_PROGRAM_ARB, GL_PROGRAM_FORMAT_ASCII_ARB, strlen(dummy_program), dummy_program));
1495     }
1496
1497     for (s = 0; s < gl_info->limits.point_sprite_units; ++s)
1498     {
1499         GL_EXTCALL(glActiveTextureARB(GL_TEXTURE0_ARB + s));
1500         glTexEnvi(GL_POINT_SPRITE_ARB, GL_COORD_REPLACE_ARB, GL_TRUE);
1501         checkGLcall("glTexEnvi(GL_POINT_SPRITE_ARB, GL_COORD_REPLACE_ARB, GL_TRUE)");
1502     }
1503
1504     if (gl_info->supported[ARB_PROVOKING_VERTEX])
1505     {
1506         GL_EXTCALL(glProvokingVertex(GL_FIRST_VERTEX_CONVENTION));
1507     }
1508     else if (gl_info->supported[EXT_PROVOKING_VERTEX])
1509     {
1510         GL_EXTCALL(glProvokingVertexEXT(GL_FIRST_VERTEX_CONVENTION_EXT));
1511     }
1512
1513     LEAVE_GL();
1514
1515     This->frag_pipe->enable_extension((IWineD3DDevice *) This, TRUE);
1516
1517     return ret;
1518
1519 out:
1520     if (ret)
1521     {
1522         HeapFree(GetProcessHeap(), 0, ret->free_event_queries);
1523         HeapFree(GetProcessHeap(), 0, ret->free_occlusion_queries);
1524         HeapFree(GetProcessHeap(), 0, ret->pshader_const_dirty);
1525         HeapFree(GetProcessHeap(), 0, ret->vshader_const_dirty);
1526         HeapFree(GetProcessHeap(), 0, ret);
1527     }
1528     return NULL;
1529 }
1530
1531 /*****************************************************************************
1532  * RemoveContextFromArray
1533  *
1534  * Removes a context from the context manager. The opengl context is not
1535  * destroyed or unset. context is not a valid pointer after that call.
1536  *
1537  * Similar to the former call this isn't a performance critical function. A
1538  * helper function for context_destroy().
1539  *
1540  * Params:
1541  *  This: Device to activate the context for
1542  *  context: Context to remove
1543  *
1544  *****************************************************************************/
1545 static void RemoveContextFromArray(IWineD3DDeviceImpl *This, struct wined3d_context *context)
1546 {
1547     struct wined3d_context **new_array;
1548     BOOL found = FALSE;
1549     UINT i;
1550
1551     TRACE("Removing ctx %p\n", context);
1552
1553     for (i = 0; i < This->numContexts; ++i)
1554     {
1555         if (This->contexts[i] == context)
1556         {
1557             found = TRUE;
1558             break;
1559         }
1560     }
1561
1562     if (!found)
1563     {
1564         ERR("Context %p doesn't exist in context array\n", context);
1565         return;
1566     }
1567
1568     while (i < This->numContexts - 1)
1569     {
1570         This->contexts[i] = This->contexts[i + 1];
1571         ++i;
1572     }
1573
1574     --This->numContexts;
1575     if (!This->numContexts)
1576     {
1577         HeapFree(GetProcessHeap(), 0, This->contexts);
1578         This->contexts = NULL;
1579         return;
1580     }
1581
1582     new_array = HeapReAlloc(GetProcessHeap(), 0, This->contexts, This->numContexts * sizeof(*This->contexts));
1583     if (!new_array)
1584     {
1585         ERR("Failed to shrink context array. Oh well.\n");
1586         return;
1587     }
1588
1589     This->contexts = new_array;
1590 }
1591
1592 /*****************************************************************************
1593  * context_destroy
1594  *
1595  * Destroys a wined3d context
1596  *
1597  * Params:
1598  *  This: Device to activate the context for
1599  *  context: Context to destroy
1600  *
1601  *****************************************************************************/
1602 void context_destroy(IWineD3DDeviceImpl *This, struct wined3d_context *context)
1603 {
1604     BOOL destroy;
1605
1606     TRACE("Destroying ctx %p\n", context);
1607
1608     if (context->tid == GetCurrentThreadId() || !context->current)
1609     {
1610         context_destroy_gl_resources(context);
1611         TlsSetValue(wined3d_context_tls_idx, NULL);
1612         destroy = TRUE;
1613     }
1614     else
1615     {
1616         context->destroyed = 1;
1617         destroy = FALSE;
1618     }
1619
1620     HeapFree(GetProcessHeap(), 0, context->vshader_const_dirty);
1621     HeapFree(GetProcessHeap(), 0, context->pshader_const_dirty);
1622     RemoveContextFromArray(This, context);
1623     if (destroy) HeapFree(GetProcessHeap(), 0, context);
1624 }
1625
1626 /* GL locking is done by the caller */
1627 static inline void set_blit_dimension(UINT width, UINT height) {
1628     glMatrixMode(GL_PROJECTION);
1629     checkGLcall("glMatrixMode(GL_PROJECTION)");
1630     glLoadIdentity();
1631     checkGLcall("glLoadIdentity()");
1632     glOrtho(0, width, height, 0, 0.0, -1.0);
1633     checkGLcall("glOrtho");
1634     glViewport(0, 0, width, height);
1635     checkGLcall("glViewport");
1636 }
1637
1638 /*****************************************************************************
1639  * SetupForBlit
1640  *
1641  * Sets up a context for DirectDraw blitting.
1642  * All texture units are disabled, texture unit 0 is set as current unit
1643  * fog, lighting, blending, alpha test, z test, scissor test, culling disabled
1644  * color writing enabled for all channels
1645  * register combiners disabled, shaders disabled
1646  * world matrix is set to identity, texture matrix 0 too
1647  * projection matrix is setup for drawing screen coordinates
1648  *
1649  * Params:
1650  *  This: Device to activate the context for
1651  *  context: Context to setup
1652  *
1653  *****************************************************************************/
1654 /* Context activation is done by the caller. */
1655 static void SetupForBlit(IWineD3DDeviceImpl *This, struct wined3d_context *context)
1656 {
1657     int i;
1658     const struct StateEntry *StateTable = This->StateTable;
1659     const struct wined3d_gl_info *gl_info = context->gl_info;
1660     UINT width = ((IWineD3DSurfaceImpl *)context->current_rt)->currentDesc.Width;
1661     UINT height = ((IWineD3DSurfaceImpl *)context->current_rt)->currentDesc.Height;
1662     DWORD sampler;
1663
1664     TRACE("Setting up context %p for blitting\n", context);
1665     if(context->last_was_blit) {
1666         if(context->blit_w != width || context->blit_h != height) {
1667             ENTER_GL();
1668             set_blit_dimension(width, height);
1669             LEAVE_GL();
1670             context->blit_w = width; context->blit_h = height;
1671             /* No need to dirtify here, the states are still dirtified because they weren't
1672              * applied since the last SetupForBlit call. Otherwise last_was_blit would not
1673              * be set
1674              */
1675         }
1676         TRACE("Context is already set up for blitting, nothing to do\n");
1677         return;
1678     }
1679     context->last_was_blit = TRUE;
1680
1681     /* TODO: Use a display list */
1682
1683     /* Disable shaders */
1684     ENTER_GL();
1685     This->shader_backend->shader_select(context, FALSE, FALSE);
1686     LEAVE_GL();
1687
1688     Context_MarkStateDirty(context, STATE_VSHADER, StateTable);
1689     Context_MarkStateDirty(context, STATE_PIXELSHADER, StateTable);
1690
1691     /* Call ENTER_GL() once for all gl calls below. In theory we should not call
1692      * helper functions in between gl calls. This function is full of Context_MarkStateDirty
1693      * which can safely be called from here, we only lock once instead locking/unlocking
1694      * after each GL call.
1695      */
1696     ENTER_GL();
1697
1698     /* Disable all textures. The caller can then bind a texture it wants to blit
1699      * from
1700      *
1701      * The blitting code uses (for now) the fixed function pipeline, so make sure to reset all fixed
1702      * function texture unit. No need to care for higher samplers
1703      */
1704     for (i = gl_info->limits.textures - 1; i > 0 ; --i)
1705     {
1706         sampler = This->rev_tex_unit_map[i];
1707         GL_EXTCALL(glActiveTextureARB(GL_TEXTURE0_ARB + i));
1708         checkGLcall("glActiveTextureARB");
1709
1710         if (gl_info->supported[ARB_TEXTURE_CUBE_MAP])
1711         {
1712             glDisable(GL_TEXTURE_CUBE_MAP_ARB);
1713             checkGLcall("glDisable GL_TEXTURE_CUBE_MAP_ARB");
1714         }
1715         glDisable(GL_TEXTURE_3D);
1716         checkGLcall("glDisable GL_TEXTURE_3D");
1717         if (gl_info->supported[ARB_TEXTURE_RECTANGLE])
1718         {
1719             glDisable(GL_TEXTURE_RECTANGLE_ARB);
1720             checkGLcall("glDisable GL_TEXTURE_RECTANGLE_ARB");
1721         }
1722         glDisable(GL_TEXTURE_2D);
1723         checkGLcall("glDisable GL_TEXTURE_2D");
1724
1725         glTexEnvi(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_REPLACE);
1726         checkGLcall("glTexEnvi(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_REPLACE);");
1727
1728         if (sampler != WINED3D_UNMAPPED_STAGE)
1729         {
1730             if (sampler < MAX_TEXTURES) {
1731                 Context_MarkStateDirty(context, STATE_TEXTURESTAGE(sampler, WINED3DTSS_COLOROP), StateTable);
1732             }
1733             Context_MarkStateDirty(context, STATE_SAMPLER(sampler), StateTable);
1734         }
1735     }
1736     GL_EXTCALL(glActiveTextureARB(GL_TEXTURE0_ARB));
1737     checkGLcall("glActiveTextureARB");
1738
1739     sampler = This->rev_tex_unit_map[0];
1740
1741     if (gl_info->supported[ARB_TEXTURE_CUBE_MAP])
1742     {
1743         glDisable(GL_TEXTURE_CUBE_MAP_ARB);
1744         checkGLcall("glDisable GL_TEXTURE_CUBE_MAP_ARB");
1745     }
1746     glDisable(GL_TEXTURE_3D);
1747     checkGLcall("glDisable GL_TEXTURE_3D");
1748     if (gl_info->supported[ARB_TEXTURE_RECTANGLE])
1749     {
1750         glDisable(GL_TEXTURE_RECTANGLE_ARB);
1751         checkGLcall("glDisable GL_TEXTURE_RECTANGLE_ARB");
1752     }
1753     glDisable(GL_TEXTURE_2D);
1754     checkGLcall("glDisable GL_TEXTURE_2D");
1755
1756     glTexEnvi(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_REPLACE);
1757
1758     glMatrixMode(GL_TEXTURE);
1759     checkGLcall("glMatrixMode(GL_TEXTURE)");
1760     glLoadIdentity();
1761     checkGLcall("glLoadIdentity()");
1762
1763     if (gl_info->supported[EXT_TEXTURE_LOD_BIAS])
1764     {
1765         glTexEnvf(GL_TEXTURE_FILTER_CONTROL_EXT,
1766                   GL_TEXTURE_LOD_BIAS_EXT,
1767                   0.0f);
1768         checkGLcall("glTexEnvi GL_TEXTURE_LOD_BIAS_EXT ...");
1769     }
1770
1771     if (sampler != WINED3D_UNMAPPED_STAGE)
1772     {
1773         if (sampler < MAX_TEXTURES) {
1774             Context_MarkStateDirty(context, STATE_TRANSFORM(WINED3DTS_TEXTURE0 + sampler), StateTable);
1775             Context_MarkStateDirty(context, STATE_TEXTURESTAGE(sampler, WINED3DTSS_COLOROP), StateTable);
1776         }
1777         Context_MarkStateDirty(context, STATE_SAMPLER(sampler), StateTable);
1778     }
1779
1780     /* Other misc states */
1781     glDisable(GL_ALPHA_TEST);
1782     checkGLcall("glDisable(GL_ALPHA_TEST)");
1783     Context_MarkStateDirty(context, STATE_RENDER(WINED3DRS_ALPHATESTENABLE), StateTable);
1784     glDisable(GL_LIGHTING);
1785     checkGLcall("glDisable GL_LIGHTING");
1786     Context_MarkStateDirty(context, STATE_RENDER(WINED3DRS_LIGHTING), StateTable);
1787     glDisable(GL_DEPTH_TEST);
1788     checkGLcall("glDisable GL_DEPTH_TEST");
1789     Context_MarkStateDirty(context, STATE_RENDER(WINED3DRS_ZENABLE), StateTable);
1790     glDisableWINE(GL_FOG);
1791     checkGLcall("glDisable GL_FOG");
1792     Context_MarkStateDirty(context, STATE_RENDER(WINED3DRS_FOGENABLE), StateTable);
1793     glDisable(GL_BLEND);
1794     checkGLcall("glDisable GL_BLEND");
1795     Context_MarkStateDirty(context, STATE_RENDER(WINED3DRS_ALPHABLENDENABLE), StateTable);
1796     glDisable(GL_CULL_FACE);
1797     checkGLcall("glDisable GL_CULL_FACE");
1798     Context_MarkStateDirty(context, STATE_RENDER(WINED3DRS_CULLMODE), StateTable);
1799     glDisable(GL_STENCIL_TEST);
1800     checkGLcall("glDisable GL_STENCIL_TEST");
1801     Context_MarkStateDirty(context, STATE_RENDER(WINED3DRS_STENCILENABLE), StateTable);
1802     glDisable(GL_SCISSOR_TEST);
1803     checkGLcall("glDisable GL_SCISSOR_TEST");
1804     Context_MarkStateDirty(context, STATE_RENDER(WINED3DRS_SCISSORTESTENABLE), StateTable);
1805     if (gl_info->supported[ARB_POINT_SPRITE])
1806     {
1807         glDisable(GL_POINT_SPRITE_ARB);
1808         checkGLcall("glDisable GL_POINT_SPRITE_ARB");
1809         Context_MarkStateDirty(context, STATE_RENDER(WINED3DRS_POINTSPRITEENABLE), StateTable);
1810     }
1811     glColorMask(GL_TRUE, GL_TRUE,GL_TRUE,GL_TRUE);
1812     checkGLcall("glColorMask");
1813     Context_MarkStateDirty(context, STATE_RENDER(WINED3DRS_COLORWRITEENABLE), StateTable);
1814     if (gl_info->supported[EXT_SECONDARY_COLOR])
1815     {
1816         glDisable(GL_COLOR_SUM_EXT);
1817         Context_MarkStateDirty(context, STATE_RENDER(WINED3DRS_SPECULARENABLE), StateTable);
1818         checkGLcall("glDisable(GL_COLOR_SUM_EXT)");
1819     }
1820
1821     /* Setup transforms */
1822     glMatrixMode(GL_MODELVIEW);
1823     checkGLcall("glMatrixMode(GL_MODELVIEW)");
1824     glLoadIdentity();
1825     checkGLcall("glLoadIdentity()");
1826     Context_MarkStateDirty(context, STATE_TRANSFORM(WINED3DTS_WORLDMATRIX(0)), StateTable);
1827
1828     context->last_was_rhw = TRUE;
1829     Context_MarkStateDirty(context, STATE_VDECL, StateTable); /* because of last_was_rhw = TRUE */
1830
1831     glDisable(GL_CLIP_PLANE0); checkGLcall("glDisable(clip plane 0)");
1832     glDisable(GL_CLIP_PLANE1); checkGLcall("glDisable(clip plane 1)");
1833     glDisable(GL_CLIP_PLANE2); checkGLcall("glDisable(clip plane 2)");
1834     glDisable(GL_CLIP_PLANE3); checkGLcall("glDisable(clip plane 3)");
1835     glDisable(GL_CLIP_PLANE4); checkGLcall("glDisable(clip plane 4)");
1836     glDisable(GL_CLIP_PLANE5); checkGLcall("glDisable(clip plane 5)");
1837     Context_MarkStateDirty(context, STATE_RENDER(WINED3DRS_CLIPPING), StateTable);
1838
1839     set_blit_dimension(width, height);
1840
1841     LEAVE_GL();
1842
1843     context->blit_w = width; context->blit_h = height;
1844     Context_MarkStateDirty(context, STATE_VIEWPORT, StateTable);
1845     Context_MarkStateDirty(context, STATE_TRANSFORM(WINED3DTS_PROJECTION), StateTable);
1846
1847
1848     This->frag_pipe->enable_extension((IWineD3DDevice *) This, FALSE);
1849 }
1850
1851 /*****************************************************************************
1852  * findThreadContextForSwapChain
1853  *
1854  * Searches a swapchain for all contexts and picks one for the thread tid.
1855  * If none can be found the swapchain is requested to create a new context
1856  *
1857  *****************************************************************************/
1858 static struct wined3d_context *findThreadContextForSwapChain(IWineD3DSwapChain *swapchain, DWORD tid)
1859 {
1860     unsigned int i;
1861
1862     for(i = 0; i < ((IWineD3DSwapChainImpl *) swapchain)->num_contexts; i++) {
1863         if(((IWineD3DSwapChainImpl *) swapchain)->context[i]->tid == tid) {
1864             return ((IWineD3DSwapChainImpl *) swapchain)->context[i];
1865         }
1866
1867     }
1868
1869     /* Create a new context for the thread */
1870     return swapchain_create_context_for_thread(swapchain);
1871 }
1872
1873 /*****************************************************************************
1874  * FindContext
1875  *
1876  * Finds a context for the current render target and thread
1877  *
1878  * Parameters:
1879  *  target: Render target to find the context for
1880  *  tid: Thread to activate the context for
1881  *
1882  * Returns: The needed context
1883  *
1884  *****************************************************************************/
1885 static struct wined3d_context *FindContext(IWineD3DDeviceImpl *This, IWineD3DSurface *target)
1886 {
1887     IWineD3DSwapChain *swapchain = NULL;
1888     struct wined3d_context *current_context = context_get_current();
1889     const struct StateEntry *StateTable = This->StateTable;
1890     DWORD tid = GetCurrentThreadId();
1891     struct wined3d_context *context;
1892     BOOL old_render_offscreen;
1893
1894     if (current_context && current_context->destroyed) current_context = NULL;
1895
1896     if (!target)
1897     {
1898         if (current_context
1899                 && current_context->current_rt
1900                 && ((IWineD3DSurfaceImpl *)current_context->surface)->resource.device == This)
1901         {
1902             target = current_context->current_rt;
1903         }
1904         else
1905         {
1906             IWineD3DSwapChainImpl *swapchain = (IWineD3DSwapChainImpl *)This->swapchains[0];
1907             if (swapchain->backBuffer) target = swapchain->backBuffer[0];
1908             else target = swapchain->frontBuffer;
1909         }
1910     }
1911
1912     if (current_context && current_context->current_rt == target)
1913     {
1914         context_validate(current_context);
1915         return current_context;
1916     }
1917
1918     if (SUCCEEDED(IWineD3DSurface_GetContainer(target, &IID_IWineD3DSwapChain, (void **)&swapchain))) {
1919         TRACE("Rendering onscreen\n");
1920
1921         context = findThreadContextForSwapChain(swapchain, tid);
1922
1923         old_render_offscreen = context->render_offscreen;
1924         context->render_offscreen = surface_is_offscreen(target);
1925         /* The context != This->activeContext will catch a NOP context change. This can occur
1926          * if we are switching back to swapchain rendering in case of FBO or Back Buffer offscreen
1927          * rendering. No context change is needed in that case
1928          */
1929
1930         if(wined3d_settings.offscreen_rendering_mode == ORM_PBUFFER) {
1931             if(This->pbufferContext && tid == This->pbufferContext->tid) {
1932                 This->pbufferContext->tid = 0;
1933             }
1934         }
1935         IWineD3DSwapChain_Release(swapchain);
1936     }
1937     else
1938     {
1939         TRACE("Rendering offscreen\n");
1940
1941 retry:
1942         if (wined3d_settings.offscreen_rendering_mode == ORM_PBUFFER)
1943         {
1944             IWineD3DSurfaceImpl *targetimpl = (IWineD3DSurfaceImpl *)target;
1945             if (!This->pbufferContext
1946                     || This->pbufferWidth < targetimpl->currentDesc.Width
1947                     || This->pbufferHeight < targetimpl->currentDesc.Height)
1948             {
1949                 if (This->pbufferContext) context_destroy(This, This->pbufferContext);
1950
1951                 /* The display is irrelevant here, the window is 0. But
1952                  * context_create() needs a valid X connection. Create the context
1953                  * on the same server as the primary swapchain. The primary
1954                  * swapchain is exists at this point. */
1955                 This->pbufferContext = context_create(This, targetimpl,
1956                         ((IWineD3DSwapChainImpl *)This->swapchains[0])->context[0]->win_handle,
1957                         TRUE /* pbuffer */, &((IWineD3DSwapChainImpl *)This->swapchains[0])->presentParms);
1958                 This->pbufferWidth = targetimpl->currentDesc.Width;
1959                 This->pbufferHeight = targetimpl->currentDesc.Height;
1960                 if (This->pbufferContext) context_release(This->pbufferContext);
1961             }
1962
1963             if (This->pbufferContext)
1964             {
1965                 if (This->pbufferContext->tid && This->pbufferContext->tid != tid)
1966                 {
1967                     FIXME("The PBuffer context is only supported for one thread for now!\n");
1968                 }
1969                 This->pbufferContext->tid = tid;
1970                 context = This->pbufferContext;
1971             }
1972             else
1973             {
1974                 ERR("Failed to create a buffer context and drawable, falling back to back buffer offscreen rendering.\n");
1975                 wined3d_settings.offscreen_rendering_mode = ORM_BACKBUFFER;
1976                 goto retry;
1977             }
1978         }
1979         else
1980         {
1981             /* Stay with the currently active context. */
1982             if (current_context
1983                     && ((IWineD3DSurfaceImpl *)current_context->surface)->resource.device == This)
1984             {
1985                 context = current_context;
1986             }
1987             else
1988             {
1989                 /* This may happen if the app jumps straight into offscreen rendering
1990                  * Start using the context of the primary swapchain. tid == 0 is no problem
1991                  * for findThreadContextForSwapChain.
1992                  *
1993                  * Can also happen on thread switches - in that case findThreadContextForSwapChain
1994                  * is perfect to call. */
1995                 context = findThreadContextForSwapChain(This->swapchains[0], tid);
1996             }
1997         }
1998
1999         old_render_offscreen = context->render_offscreen;
2000         context->render_offscreen = TRUE;
2001     }
2002
2003     context_validate(context);
2004
2005     if (context->render_offscreen != old_render_offscreen)
2006     {
2007         Context_MarkStateDirty(context, STATE_TRANSFORM(WINED3DTS_PROJECTION), StateTable);
2008         Context_MarkStateDirty(context, STATE_VDECL, StateTable);
2009         Context_MarkStateDirty(context, STATE_VIEWPORT, StateTable);
2010         Context_MarkStateDirty(context, STATE_SCISSORRECT, StateTable);
2011         Context_MarkStateDirty(context, STATE_FRONTFACE, StateTable);
2012     }
2013
2014     /* To compensate the lack of format switching with some offscreen rendering methods and on onscreen buffers
2015      * the alpha blend state changes with different render target formats. */
2016     if (!context->current_rt)
2017     {
2018         Context_MarkStateDirty(context, STATE_RENDER(WINED3DRS_ALPHABLENDENABLE), StateTable);
2019     }
2020     else
2021     {
2022         const struct GlPixelFormatDesc *old = ((IWineD3DSurfaceImpl *)context->current_rt)->resource.format_desc;
2023         const struct GlPixelFormatDesc *new = ((IWineD3DSurfaceImpl *)target)->resource.format_desc;
2024
2025         if (old->format != new->format)
2026         {
2027             /* Disable blending when the alpha mask has changed and when a format doesn't support blending. */
2028             if ((old->alpha_mask && !new->alpha_mask) || (!old->alpha_mask && new->alpha_mask)
2029                     || !(new->Flags & WINED3DFMT_FLAG_POSTPIXELSHADER_BLENDING))
2030             {
2031                 Context_MarkStateDirty(context, STATE_RENDER(WINED3DRS_ALPHABLENDENABLE), StateTable);
2032             }
2033         }
2034
2035         /* When switching away from an offscreen render target, and we're not
2036          * using FBOs, we have to read the drawable into the texture. This is
2037          * done via PreLoad (and SFLAG_INDRAWABLE set on the surface). There
2038          * are some things that need care though. PreLoad needs a GL context,
2039          * and FindContext is called before the context is activated. It also
2040          * has to be called with the old rendertarget active, otherwise a
2041          * wrong drawable is read. */
2042         if (wined3d_settings.offscreen_rendering_mode != ORM_FBO
2043                 && old_render_offscreen && context->current_rt != target)
2044         {
2045             BOOL oldInDraw = This->isInDraw;
2046
2047             /* surface_internal_preload() requires a context to load the
2048              * texture, so it will call context_acquire(). Set isInDraw to true
2049              * to signal surface_internal_preload() that it has a context. */
2050
2051             /* FIXME: This is just broken. There's no guarantee whatsoever
2052              * that the currently active context, if any, is appropriate for
2053              * reading back the render target. We should probably call
2054              * context_set_current(context) here and then rely on
2055              * context_acquire() doing the right thing. */
2056             This->isInDraw = TRUE;
2057
2058             /* Read the back buffer of the old drawable into the destination texture. */
2059             if (((IWineD3DSurfaceImpl *)context->current_rt)->texture_name_srgb)
2060             {
2061                 surface_internal_preload(context->current_rt, SRGB_BOTH);
2062             }
2063             else
2064             {
2065                 surface_internal_preload(context->current_rt, SRGB_RGB);
2066             }
2067
2068             IWineD3DSurface_ModifyLocation(context->current_rt, SFLAG_INDRAWABLE, FALSE);
2069
2070             This->isInDraw = oldInDraw;
2071         }
2072     }
2073
2074     context->draw_buffer_dirty = TRUE;
2075     context->current_rt = target;
2076
2077     return context;
2078 }
2079
2080 /* Context activation is done by the caller. */
2081 static void context_apply_draw_buffer(struct wined3d_context *context, BOOL blit)
2082 {
2083     const struct wined3d_gl_info *gl_info = context->gl_info;
2084     IWineD3DSurface *rt = context->current_rt;
2085     IWineD3DDeviceImpl *device;
2086
2087     device = ((IWineD3DSurfaceImpl *)rt)->resource.device;
2088     if (!surface_is_offscreen(rt))
2089     {
2090         ENTER_GL();
2091         glDrawBuffer(surface_get_gl_buffer(rt));
2092         checkGLcall("glDrawBuffers()");
2093         LEAVE_GL();
2094     }
2095     else
2096     {
2097         ENTER_GL();
2098         if (wined3d_settings.offscreen_rendering_mode == ORM_FBO)
2099         {
2100             if (!blit)
2101             {
2102                 if (gl_info->supported[ARB_DRAW_BUFFERS])
2103                 {
2104                     GL_EXTCALL(glDrawBuffersARB(gl_info->limits.buffers, device->draw_buffers));
2105                     checkGLcall("glDrawBuffers()");
2106                 }
2107                 else
2108                 {
2109                     glDrawBuffer(device->draw_buffers[0]);
2110                     checkGLcall("glDrawBuffer()");
2111                 }
2112             } else {
2113                 glDrawBuffer(GL_COLOR_ATTACHMENT0);
2114                 checkGLcall("glDrawBuffer()");
2115             }
2116         }
2117         else
2118         {
2119             glDrawBuffer(device->offscreenBuffer);
2120             checkGLcall("glDrawBuffer()");
2121         }
2122         LEAVE_GL();
2123     }
2124 }
2125
2126 /* GL locking is done by the caller. */
2127 void context_set_draw_buffer(struct wined3d_context *context, GLenum buffer)
2128 {
2129     glDrawBuffer(buffer);
2130     checkGLcall("glDrawBuffer()");
2131     context->draw_buffer_dirty = TRUE;
2132 }
2133
2134 /* Context activation is done by the caller. */
2135 static void context_apply_state(struct wined3d_context *context, IWineD3DDeviceImpl *device, enum ContextUsage usage)
2136 {
2137     const struct StateEntry *state_table = device->StateTable;
2138     unsigned int i;
2139
2140     switch (usage) {
2141         case CTXUSAGE_CLEAR:
2142         case CTXUSAGE_DRAWPRIM:
2143             if (wined3d_settings.offscreen_rendering_mode == ORM_FBO) {
2144                 ENTER_GL();
2145                 context_apply_fbo_state(context);
2146                 LEAVE_GL();
2147             }
2148             if (context->draw_buffer_dirty) {
2149                 context_apply_draw_buffer(context, FALSE);
2150                 context->draw_buffer_dirty = FALSE;
2151             }
2152             break;
2153
2154         case CTXUSAGE_BLIT:
2155             if (wined3d_settings.offscreen_rendering_mode == ORM_FBO) {
2156                 if (context->render_offscreen)
2157                 {
2158                     FIXME("Activating for CTXUSAGE_BLIT for an offscreen target with ORM_FBO. This should be avoided.\n");
2159                     surface_internal_preload(context->current_rt, SRGB_RGB);
2160
2161                     ENTER_GL();
2162                     context_bind_fbo(context, GL_FRAMEBUFFER, &context->dst_fbo);
2163                     context_attach_surface_fbo(context, GL_FRAMEBUFFER, 0, context->current_rt);
2164                     context_attach_depth_stencil_fbo(context, GL_FRAMEBUFFER, NULL, FALSE);
2165                     LEAVE_GL();
2166                 } else {
2167                     ENTER_GL();
2168                     context_bind_fbo(context, GL_FRAMEBUFFER, NULL);
2169                     LEAVE_GL();
2170                 }
2171                 context->draw_buffer_dirty = TRUE;
2172             }
2173             if (context->draw_buffer_dirty) {
2174                 context_apply_draw_buffer(context, TRUE);
2175                 if (wined3d_settings.offscreen_rendering_mode != ORM_FBO) {
2176                     context->draw_buffer_dirty = FALSE;
2177                 }
2178             }
2179             break;
2180
2181         default:
2182             break;
2183     }
2184
2185     switch(usage) {
2186         case CTXUSAGE_RESOURCELOAD:
2187             /* This does not require any special states to be set up */
2188             break;
2189
2190         case CTXUSAGE_CLEAR:
2191             if(context->last_was_blit) {
2192                 device->frag_pipe->enable_extension((IWineD3DDevice *)device, TRUE);
2193             }
2194
2195             /* Blending and clearing should be orthogonal, but tests on the nvidia driver show that disabling
2196              * blending when clearing improves the clearing performance incredibly.
2197              */
2198             ENTER_GL();
2199             glDisable(GL_BLEND);
2200             LEAVE_GL();
2201             Context_MarkStateDirty(context, STATE_RENDER(WINED3DRS_ALPHABLENDENABLE), state_table);
2202
2203             ENTER_GL();
2204             glEnable(GL_SCISSOR_TEST);
2205             checkGLcall("glEnable GL_SCISSOR_TEST");
2206             LEAVE_GL();
2207             context->last_was_blit = FALSE;
2208             Context_MarkStateDirty(context, STATE_RENDER(WINED3DRS_SCISSORTESTENABLE), state_table);
2209             Context_MarkStateDirty(context, STATE_SCISSORRECT, state_table);
2210             break;
2211
2212         case CTXUSAGE_DRAWPRIM:
2213             /* This needs all dirty states applied */
2214             if(context->last_was_blit) {
2215                 device->frag_pipe->enable_extension((IWineD3DDevice *)device, TRUE);
2216             }
2217
2218             IWineD3DDeviceImpl_FindTexUnitMap(device);
2219             device_preload_textures(device);
2220             if (isStateDirty(context, STATE_VDECL))
2221                 device_update_stream_info(device, context->gl_info);
2222
2223             ENTER_GL();
2224             for (i = 0; i < context->numDirtyEntries; ++i)
2225             {
2226                 DWORD rep = context->dirtyArray[i];
2227                 DWORD idx = rep / (sizeof(*context->isStateDirty) * CHAR_BIT);
2228                 BYTE shift = rep & ((sizeof(*context->isStateDirty) * CHAR_BIT) - 1);
2229                 context->isStateDirty[idx] &= ~(1 << shift);
2230                 state_table[rep].apply(rep, device->stateBlock, context);
2231             }
2232             LEAVE_GL();
2233             context->numDirtyEntries = 0; /* This makes the whole list clean */
2234             context->last_was_blit = FALSE;
2235             break;
2236
2237         case CTXUSAGE_BLIT:
2238             SetupForBlit(device, context);
2239             break;
2240
2241         default:
2242             FIXME("Unexpected context usage requested\n");
2243     }
2244 }
2245
2246 /*****************************************************************************
2247  * context_acquire
2248  *
2249  * Finds a rendering context and drawable matching the device and render
2250  * target for the current thread, activates them and puts them into the
2251  * requested state.
2252  *
2253  * Params:
2254  *  This: Device to activate the context for
2255  *  target: Requested render target
2256  *  usage: Prepares the context for blitting, drawing or other actions
2257  *
2258  *****************************************************************************/
2259 struct wined3d_context *context_acquire(IWineD3DDeviceImpl *device, IWineD3DSurface *target, enum ContextUsage usage)
2260 {
2261     struct wined3d_context *current_context = context_get_current();
2262     struct wined3d_context *context;
2263
2264     TRACE("device %p, target %p, usage %#x.\n", device, target, usage);
2265
2266     context = FindContext(device, target);
2267     context_enter(context);
2268     if (!context->valid) return context;
2269
2270     if (context != current_context)
2271     {
2272         if (!context_set_current(context)) ERR("Failed to activate the new context.\n");
2273         else device->frag_pipe->enable_extension((IWineD3DDevice *)device, !context->last_was_blit);
2274
2275         if (context->vshader_const_dirty)
2276         {
2277             memset(context->vshader_const_dirty, 1,
2278                     sizeof(*context->vshader_const_dirty) * device->d3d_vshader_constantF);
2279             device->highest_dirty_vs_const = device->d3d_vshader_constantF;
2280         }
2281         if (context->pshader_const_dirty)
2282         {
2283             memset(context->pshader_const_dirty, 1,
2284                    sizeof(*context->pshader_const_dirty) * device->d3d_pshader_constantF);
2285             device->highest_dirty_ps_const = device->d3d_pshader_constantF;
2286         }
2287     }
2288     else if (context->restore_ctx)
2289     {
2290         if (!pwglMakeCurrent(context->hdc, context->glCtx))
2291         {
2292             DWORD err = GetLastError();
2293             ERR("Failed to make GL context %p current on device context %p, last error %#x.\n",
2294                     context->hdc, context->glCtx, err);
2295         }
2296     }
2297
2298     context_apply_state(context, device, usage);
2299
2300     return context;
2301 }