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