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