2 * Context and render target management in wined3d
4 * Copyright 2007-2008 Stefan Dösinger for CodeWeavers
5 * Copyright 2009-2011 Henri Verbeet for CodeWeavers
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.
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.
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
23 #include "wine/port.h"
30 #include "wined3d_private.h"
32 WINE_DEFAULT_DEBUG_CHANNEL(d3d);
34 static DWORD wined3d_context_tls_idx;
36 /* FBO helper functions */
38 /* Context activation is done by the caller. */
39 static void context_bind_fbo(struct wined3d_context *context, GLenum target, GLuint *fbo)
41 const struct wined3d_gl_info *gl_info = context->gl_info;
52 gl_info->fbo_ops.glGenFramebuffers(1, fbo);
53 checkGLcall("glGenFramebuffers()");
54 TRACE("Created FBO %u.\n", *fbo);
61 case GL_READ_FRAMEBUFFER:
62 if (context->fbo_read_binding == f) return;
63 context->fbo_read_binding = f;
66 case GL_DRAW_FRAMEBUFFER:
67 if (context->fbo_draw_binding == f) return;
68 context->fbo_draw_binding = f;
72 if (context->fbo_read_binding == f
73 && context->fbo_draw_binding == f) return;
74 context->fbo_read_binding = f;
75 context->fbo_draw_binding = f;
79 FIXME("Unhandled target %#x.\n", target);
83 gl_info->fbo_ops.glBindFramebuffer(target, f);
84 checkGLcall("glBindFramebuffer()");
87 /* Context activation is done by the caller. */
88 static void context_clean_fbo_attachments(const struct wined3d_gl_info *gl_info, GLenum target)
92 for (i = 0; i < gl_info->limits.buffers; ++i)
94 gl_info->fbo_ops.glFramebufferTexture2D(target, GL_COLOR_ATTACHMENT0 + i, GL_TEXTURE_2D, 0, 0);
95 checkGLcall("glFramebufferTexture2D()");
97 gl_info->fbo_ops.glFramebufferTexture2D(target, GL_DEPTH_ATTACHMENT, GL_TEXTURE_2D, 0, 0);
98 checkGLcall("glFramebufferTexture2D()");
100 gl_info->fbo_ops.glFramebufferTexture2D(target, GL_STENCIL_ATTACHMENT, GL_TEXTURE_2D, 0, 0);
101 checkGLcall("glFramebufferTexture2D()");
104 /* Context activation is done by the caller. */
105 static void context_destroy_fbo(struct wined3d_context *context, GLuint *fbo)
107 const struct wined3d_gl_info *gl_info = context->gl_info;
109 context_bind_fbo(context, GL_FRAMEBUFFER, fbo);
110 context_clean_fbo_attachments(gl_info, GL_FRAMEBUFFER);
111 context_bind_fbo(context, GL_FRAMEBUFFER, NULL);
113 gl_info->fbo_ops.glDeleteFramebuffers(1, fbo);
114 checkGLcall("glDeleteFramebuffers()");
117 static void context_attach_depth_stencil_rb(const struct wined3d_gl_info *gl_info,
118 GLenum fbo_target, DWORD format_flags, GLuint rb)
120 if (format_flags & WINED3DFMT_FLAG_DEPTH)
122 gl_info->fbo_ops.glFramebufferRenderbuffer(fbo_target, GL_DEPTH_ATTACHMENT, GL_RENDERBUFFER, rb);
123 checkGLcall("glFramebufferRenderbuffer()");
126 if (format_flags & WINED3DFMT_FLAG_STENCIL)
128 gl_info->fbo_ops.glFramebufferRenderbuffer(fbo_target, GL_STENCIL_ATTACHMENT, GL_RENDERBUFFER, rb);
129 checkGLcall("glFramebufferRenderbuffer()");
133 /* Context activation is done by the caller. */
134 static void context_attach_depth_stencil_fbo(struct wined3d_context *context,
135 GLenum fbo_target, struct wined3d_surface *depth_stencil, DWORD location)
137 const struct wined3d_gl_info *gl_info = context->gl_info;
139 TRACE("Attach depth stencil %p\n", depth_stencil);
143 DWORD format_flags = depth_stencil->resource.format->flags;
145 if (depth_stencil->current_renderbuffer)
147 context_attach_depth_stencil_rb(gl_info, fbo_target,
148 format_flags, depth_stencil->current_renderbuffer->id);
154 case SFLAG_INTEXTURE:
155 case SFLAG_INSRGBTEX:
156 surface_prepare_texture(depth_stencil, context, FALSE);
158 if (format_flags & WINED3DFMT_FLAG_DEPTH)
160 gl_info->fbo_ops.glFramebufferTexture2D(fbo_target, GL_DEPTH_ATTACHMENT,
161 depth_stencil->texture_target, depth_stencil->texture_name,
162 depth_stencil->texture_level);
163 checkGLcall("glFramebufferTexture2D()");
166 if (format_flags & WINED3DFMT_FLAG_STENCIL)
168 gl_info->fbo_ops.glFramebufferTexture2D(fbo_target, GL_STENCIL_ATTACHMENT,
169 depth_stencil->texture_target, depth_stencil->texture_name,
170 depth_stencil->texture_level);
171 checkGLcall("glFramebufferTexture2D()");
175 case SFLAG_INRB_MULTISAMPLE:
176 surface_prepare_rb(depth_stencil, gl_info, TRUE);
177 context_attach_depth_stencil_rb(gl_info, fbo_target,
178 format_flags, depth_stencil->rb_multisample);
181 case SFLAG_INRB_RESOLVED:
182 surface_prepare_rb(depth_stencil, gl_info, FALSE);
183 context_attach_depth_stencil_rb(gl_info, fbo_target,
184 format_flags, depth_stencil->rb_resolved);
188 ERR("Unsupported location %s (%#x).\n", debug_surflocation(location), location);
193 if (!(format_flags & WINED3DFMT_FLAG_DEPTH))
195 gl_info->fbo_ops.glFramebufferTexture2D(fbo_target, GL_DEPTH_ATTACHMENT, GL_TEXTURE_2D, 0, 0);
196 checkGLcall("glFramebufferTexture2D()");
199 if (!(format_flags & WINED3DFMT_FLAG_STENCIL))
201 gl_info->fbo_ops.glFramebufferTexture2D(fbo_target, GL_STENCIL_ATTACHMENT, GL_TEXTURE_2D, 0, 0);
202 checkGLcall("glFramebufferTexture2D()");
207 gl_info->fbo_ops.glFramebufferTexture2D(fbo_target, GL_DEPTH_ATTACHMENT, GL_TEXTURE_2D, 0, 0);
208 checkGLcall("glFramebufferTexture2D()");
210 gl_info->fbo_ops.glFramebufferTexture2D(fbo_target, GL_STENCIL_ATTACHMENT, GL_TEXTURE_2D, 0, 0);
211 checkGLcall("glFramebufferTexture2D()");
215 /* Context activation is done by the caller. */
216 static void context_attach_surface_fbo(struct wined3d_context *context,
217 GLenum fbo_target, DWORD idx, struct wined3d_surface *surface, DWORD location)
219 const struct wined3d_gl_info *gl_info = context->gl_info;
221 TRACE("Attach surface %p to %u\n", surface, idx);
223 if (surface && surface->resource.format->id != WINED3DFMT_NULL)
229 case SFLAG_INTEXTURE:
230 case SFLAG_INSRGBTEX:
231 srgb = location == SFLAG_INSRGBTEX;
232 surface_prepare_texture(surface, context, srgb);
233 gl_info->fbo_ops.glFramebufferTexture2D(fbo_target, GL_COLOR_ATTACHMENT0 + idx,
234 surface->texture_target, surface_get_texture_name(surface, gl_info, srgb),
235 surface->texture_level);
236 checkGLcall("glFramebufferTexture2D()");
239 case SFLAG_INRB_MULTISAMPLE:
240 surface_prepare_rb(surface, gl_info, TRUE);
241 gl_info->fbo_ops.glFramebufferRenderbuffer(fbo_target, GL_COLOR_ATTACHMENT0 + idx,
242 GL_RENDERBUFFER, surface->rb_multisample);
243 checkGLcall("glFramebufferRenderbuffer()");
246 case SFLAG_INRB_RESOLVED:
247 surface_prepare_rb(surface, gl_info, FALSE);
248 gl_info->fbo_ops.glFramebufferRenderbuffer(fbo_target, GL_COLOR_ATTACHMENT0 + idx,
249 GL_RENDERBUFFER, surface->rb_resolved);
250 checkGLcall("glFramebufferRenderbuffer()");
254 ERR("Unsupported location %s (%#x).\n", debug_surflocation(location), location);
260 gl_info->fbo_ops.glFramebufferTexture2D(fbo_target, GL_COLOR_ATTACHMENT0 + idx, GL_TEXTURE_2D, 0, 0);
261 checkGLcall("glFramebufferTexture2D()");
265 /* Context activation is done by the caller. */
266 void context_check_fbo_status(const struct wined3d_context *context, GLenum target)
268 const struct wined3d_gl_info *gl_info = context->gl_info;
271 if (!FIXME_ON(d3d)) return;
273 status = gl_info->fbo_ops.glCheckFramebufferStatus(target);
274 if (status == GL_FRAMEBUFFER_COMPLETE)
276 TRACE("FBO complete\n");
280 const struct wined3d_surface *attachment;
283 FIXME("FBO status %s (%#x)\n", debug_fbostatus(status), status);
285 if (!context->current_fbo)
287 ERR("FBO 0 is incomplete, driver bug?\n");
291 FIXME("\tLocation %s (%#x).\n", debug_surflocation(context->current_fbo->location),
292 context->current_fbo->location);
294 /* Dump the FBO attachments */
295 for (i = 0; i < gl_info->limits.buffers; ++i)
297 attachment = context->current_fbo->render_targets[i];
300 FIXME("\tColor attachment %d: (%p) %s %ux%u %u samples.\n",
301 i, attachment, debug_d3dformat(attachment->resource.format->id),
302 attachment->pow2Width, attachment->pow2Height, attachment->resource.multisample_type);
305 attachment = context->current_fbo->depth_stencil;
308 FIXME("\tDepth attachment: (%p) %s %ux%u %u samples.\n",
309 attachment, debug_d3dformat(attachment->resource.format->id),
310 attachment->pow2Width, attachment->pow2Height, attachment->resource.multisample_type);
315 static inline DWORD context_generate_rt_mask(GLenum buffer)
317 /* Should take care of all the GL_FRONT/GL_BACK/GL_AUXi/GL_NONE... cases */
318 return buffer ? (1 << 31) | buffer : 0;
321 static inline DWORD context_generate_rt_mask_from_surface(const struct wined3d_surface *target)
323 return (1 << 31) | surface_get_gl_buffer(target);
326 static struct fbo_entry *context_create_fbo_entry(const struct wined3d_context *context,
327 struct wined3d_surface **render_targets, struct wined3d_surface *depth_stencil, DWORD location)
329 const struct wined3d_gl_info *gl_info = context->gl_info;
330 struct fbo_entry *entry;
332 entry = HeapAlloc(GetProcessHeap(), 0, sizeof(*entry));
333 entry->render_targets = HeapAlloc(GetProcessHeap(), 0, gl_info->limits.buffers * sizeof(*entry->render_targets));
334 memcpy(entry->render_targets, render_targets, gl_info->limits.buffers * sizeof(*entry->render_targets));
335 entry->depth_stencil = depth_stencil;
336 entry->location = location;
337 entry->rt_mask = context_generate_rt_mask(GL_COLOR_ATTACHMENT0);
338 entry->attached = FALSE;
344 /* Context activation is done by the caller. */
345 static void context_reuse_fbo_entry(struct wined3d_context *context, GLenum target,
346 struct wined3d_surface **render_targets, struct wined3d_surface *depth_stencil,
347 DWORD location, struct fbo_entry *entry)
349 const struct wined3d_gl_info *gl_info = context->gl_info;
351 context_bind_fbo(context, target, &entry->id);
352 context_clean_fbo_attachments(gl_info, target);
354 memcpy(entry->render_targets, render_targets, gl_info->limits.buffers * sizeof(*entry->render_targets));
355 entry->depth_stencil = depth_stencil;
356 entry->location = location;
357 entry->attached = FALSE;
360 /* Context activation is done by the caller. */
361 static void context_destroy_fbo_entry(struct wined3d_context *context, struct fbo_entry *entry)
365 TRACE("Destroy FBO %d\n", entry->id);
366 context_destroy_fbo(context, &entry->id);
368 --context->fbo_entry_count;
369 list_remove(&entry->entry);
370 HeapFree(GetProcessHeap(), 0, entry->render_targets);
371 HeapFree(GetProcessHeap(), 0, entry);
374 /* Context activation is done by the caller. */
375 static struct fbo_entry *context_find_fbo_entry(struct wined3d_context *context, GLenum target,
376 struct wined3d_surface **render_targets, struct wined3d_surface *depth_stencil, DWORD location)
378 const struct wined3d_gl_info *gl_info = context->gl_info;
379 struct fbo_entry *entry;
381 if (depth_stencil && render_targets && render_targets[0])
383 if (depth_stencil->resource.width < render_targets[0]->resource.width ||
384 depth_stencil->resource.height < render_targets[0]->resource.height)
386 WARN("Depth stencil is smaller than the primary color buffer, disabling\n");
387 depth_stencil = NULL;
391 LIST_FOR_EACH_ENTRY(entry, &context->fbo_list, struct fbo_entry, entry)
393 if (!memcmp(entry->render_targets,
394 render_targets, gl_info->limits.buffers * sizeof(*entry->render_targets))
395 && entry->depth_stencil == depth_stencil && entry->location == location)
397 list_remove(&entry->entry);
398 list_add_head(&context->fbo_list, &entry->entry);
403 if (context->fbo_entry_count < WINED3D_MAX_FBO_ENTRIES)
405 entry = context_create_fbo_entry(context, render_targets, depth_stencil, location);
406 list_add_head(&context->fbo_list, &entry->entry);
407 ++context->fbo_entry_count;
411 entry = LIST_ENTRY(list_tail(&context->fbo_list), struct fbo_entry, entry);
412 context_reuse_fbo_entry(context, target, render_targets, depth_stencil, location, entry);
413 list_remove(&entry->entry);
414 list_add_head(&context->fbo_list, &entry->entry);
420 /* Context activation is done by the caller. */
421 static void context_apply_fbo_entry(struct wined3d_context *context, GLenum target, struct fbo_entry *entry)
423 const struct wined3d_gl_info *gl_info = context->gl_info;
426 context_bind_fbo(context, target, &entry->id);
428 if (entry->attached) return;
430 /* Apply render targets */
431 for (i = 0; i < gl_info->limits.buffers; ++i)
433 context_attach_surface_fbo(context, target, i, entry->render_targets[i], entry->location);
436 /* Apply depth targets */
437 if (entry->depth_stencil)
438 surface_set_compatible_renderbuffer(entry->depth_stencil, entry->render_targets[0]);
439 context_attach_depth_stencil_fbo(context, target, entry->depth_stencil, entry->location);
441 entry->attached = TRUE;
444 /* Context activation is done by the caller. */
445 static void context_apply_fbo_state(struct wined3d_context *context, GLenum target,
446 struct wined3d_surface **render_targets, struct wined3d_surface *depth_stencil, DWORD location)
448 struct fbo_entry *entry, *entry2;
450 LIST_FOR_EACH_ENTRY_SAFE(entry, entry2, &context->fbo_destroy_list, struct fbo_entry, entry)
452 context_destroy_fbo_entry(context, entry);
455 if (context->rebind_fbo)
457 context_bind_fbo(context, GL_FRAMEBUFFER, NULL);
458 context->rebind_fbo = FALSE;
461 if (location == SFLAG_INDRAWABLE)
463 context->current_fbo = NULL;
464 context_bind_fbo(context, target, NULL);
468 context->current_fbo = context_find_fbo_entry(context, target, render_targets, depth_stencil, location);
469 context_apply_fbo_entry(context, target, context->current_fbo);
473 /* Context activation is done by the caller. */
474 void context_apply_fbo_state_blit(struct wined3d_context *context, GLenum target,
475 struct wined3d_surface *render_target, struct wined3d_surface *depth_stencil, DWORD location)
477 UINT clear_size = (context->gl_info->limits.buffers - 1) * sizeof(*context->blit_targets);
479 context->blit_targets[0] = render_target;
481 memset(&context->blit_targets[1], 0, clear_size);
482 context_apply_fbo_state(context, target, context->blit_targets, depth_stencil, location);
485 /* Context activation is done by the caller. */
486 void context_alloc_occlusion_query(struct wined3d_context *context, struct wined3d_occlusion_query *query)
488 const struct wined3d_gl_info *gl_info = context->gl_info;
490 if (context->free_occlusion_query_count)
492 query->id = context->free_occlusion_queries[--context->free_occlusion_query_count];
496 if (gl_info->supported[ARB_OCCLUSION_QUERY])
498 GL_EXTCALL(glGenQueriesARB(1, &query->id));
499 checkGLcall("glGenQueriesARB");
501 TRACE("Allocated occlusion query %u in context %p.\n", query->id, context);
505 WARN("Occlusion queries not supported, not allocating query id.\n");
510 query->context = context;
511 list_add_head(&context->occlusion_queries, &query->entry);
514 void context_free_occlusion_query(struct wined3d_occlusion_query *query)
516 struct wined3d_context *context = query->context;
518 list_remove(&query->entry);
519 query->context = NULL;
521 if (context->free_occlusion_query_count >= context->free_occlusion_query_size - 1)
523 UINT new_size = context->free_occlusion_query_size << 1;
524 GLuint *new_data = HeapReAlloc(GetProcessHeap(), 0, context->free_occlusion_queries,
525 new_size * sizeof(*context->free_occlusion_queries));
529 ERR("Failed to grow free list, leaking query %u in context %p.\n", query->id, context);
533 context->free_occlusion_query_size = new_size;
534 context->free_occlusion_queries = new_data;
537 context->free_occlusion_queries[context->free_occlusion_query_count++] = query->id;
540 /* Context activation is done by the caller. */
541 void context_alloc_event_query(struct wined3d_context *context, struct wined3d_event_query *query)
543 const struct wined3d_gl_info *gl_info = context->gl_info;
545 if (context->free_event_query_count)
547 query->object = context->free_event_queries[--context->free_event_query_count];
551 if (gl_info->supported[ARB_SYNC])
553 /* Using ARB_sync, not much to do here. */
554 query->object.sync = NULL;
555 TRACE("Allocated event query %p in context %p.\n", query->object.sync, context);
557 else if (gl_info->supported[APPLE_FENCE])
559 GL_EXTCALL(glGenFencesAPPLE(1, &query->object.id));
560 checkGLcall("glGenFencesAPPLE");
562 TRACE("Allocated event query %u in context %p.\n", query->object.id, context);
564 else if(gl_info->supported[NV_FENCE])
566 GL_EXTCALL(glGenFencesNV(1, &query->object.id));
567 checkGLcall("glGenFencesNV");
569 TRACE("Allocated event query %u in context %p.\n", query->object.id, context);
573 WARN("Event queries not supported, not allocating query id.\n");
574 query->object.id = 0;
578 query->context = context;
579 list_add_head(&context->event_queries, &query->entry);
582 void context_free_event_query(struct wined3d_event_query *query)
584 struct wined3d_context *context = query->context;
586 list_remove(&query->entry);
587 query->context = NULL;
589 if (context->free_event_query_count >= context->free_event_query_size - 1)
591 UINT new_size = context->free_event_query_size << 1;
592 union wined3d_gl_query_object *new_data = HeapReAlloc(GetProcessHeap(), 0, context->free_event_queries,
593 new_size * sizeof(*context->free_event_queries));
597 ERR("Failed to grow free list, leaking query %u in context %p.\n", query->object.id, context);
601 context->free_event_query_size = new_size;
602 context->free_event_queries = new_data;
605 context->free_event_queries[context->free_event_query_count++] = query->object;
608 typedef void (context_fbo_entry_func_t)(struct wined3d_context *context, struct fbo_entry *entry);
610 static void context_enum_surface_fbo_entries(const struct wined3d_device *device,
611 const struct wined3d_surface *surface, context_fbo_entry_func_t *callback)
615 for (i = 0; i < device->context_count; ++i)
617 struct wined3d_context *context = device->contexts[i];
618 const struct wined3d_gl_info *gl_info = context->gl_info;
619 struct fbo_entry *entry, *entry2;
621 if (context->current_rt == surface) context->current_rt = NULL;
623 LIST_FOR_EACH_ENTRY_SAFE(entry, entry2, &context->fbo_list, struct fbo_entry, entry)
627 if (entry->depth_stencil == surface)
629 callback(context, entry);
633 for (j = 0; j < gl_info->limits.buffers; ++j)
635 if (entry->render_targets[j] == surface)
637 callback(context, entry);
645 static void context_queue_fbo_entry_destruction(struct wined3d_context *context, struct fbo_entry *entry)
647 list_remove(&entry->entry);
648 list_add_head(&context->fbo_destroy_list, &entry->entry);
651 void context_resource_released(const struct wined3d_device *device,
652 struct wined3d_resource *resource, enum wined3d_resource_type type)
654 if (!device->d3d_initialized) return;
658 case WINED3D_RTYPE_SURFACE:
659 context_enum_surface_fbo_entries(device, surface_from_resource(resource),
660 context_queue_fbo_entry_destruction);
668 static void context_detach_fbo_entry(struct wined3d_context *context, struct fbo_entry *entry)
670 entry->attached = FALSE;
673 void context_resource_unloaded(const struct wined3d_device *device,
674 struct wined3d_resource *resource, enum wined3d_resource_type type)
678 case WINED3D_RTYPE_SURFACE:
679 context_enum_surface_fbo_entries(device, surface_from_resource(resource),
680 context_detach_fbo_entry);
688 void context_surface_update(struct wined3d_context *context, const struct wined3d_surface *surface)
690 const struct wined3d_gl_info *gl_info = context->gl_info;
691 struct fbo_entry *entry = context->current_fbo;
694 if (!entry || context->rebind_fbo) return;
696 for (i = 0; i < gl_info->limits.buffers; ++i)
698 if (surface == entry->render_targets[i])
700 TRACE("Updated surface %p is bound as color attachment %u to the current FBO.\n", surface, i);
701 context->rebind_fbo = TRUE;
706 if (surface == entry->depth_stencil)
708 TRACE("Updated surface %p is bound as depth attachment to the current FBO.\n", surface);
709 context->rebind_fbo = TRUE;
713 static BOOL context_set_pixel_format(const struct wined3d_gl_info *gl_info, HDC dc, int format)
715 int current = GetPixelFormat(dc);
717 if (current == format) return TRUE;
721 if (!SetPixelFormat(dc, format, NULL))
723 /* This may also happen if the dc belongs to a destroyed window. */
724 WARN("Failed to set pixel format %d on device context %p, last error %#x.\n",
725 format, dc, GetLastError());
731 /* By default WGL doesn't allow pixel format adjustments but we need it
732 * here. For this reason there's a Wine specific wglSetPixelFormat()
733 * which allows us to set the pixel format multiple times. Only use it
734 * when really needed. */
735 if (gl_info->supported[WGL_WINE_PIXEL_FORMAT_PASSTHROUGH])
737 if (!GL_EXTCALL(wglSetPixelFormatWINE(dc, format)))
739 ERR("wglSetPixelFormatWINE failed to set pixel format %d on device context %p.\n",
746 /* OpenGL doesn't allow pixel format adjustments. Print an error and
747 * continue using the old format. There's a big chance that the old
748 * format works although with a performance hit and perhaps rendering
750 ERR("Unable to set pixel format %d on device context %p. Already using format %d.\n",
751 format, dc, current);
755 static BOOL context_set_gl_context(struct wined3d_context *ctx)
757 struct wined3d_swapchain *swapchain = ctx->swapchain;
760 if (!context_set_pixel_format(ctx->gl_info, ctx->hdc, ctx->pixel_format))
762 WARN("Failed to set pixel format %d on device context %p.\n",
763 ctx->pixel_format, ctx->hdc);
767 if (backup || !wglMakeCurrent(ctx->hdc, ctx->glCtx))
771 WARN("Failed to make GL context %p current on device context %p, last error %#x.\n",
772 ctx->glCtx, ctx->hdc, GetLastError());
774 WARN("Trying fallback to the backup window.\n");
776 /* FIXME: If the context is destroyed it's no longer associated with
777 * a swapchain, so we can't use the swapchain to get a backup dc. To
778 * make this work windowless contexts would need to be handled by the
782 FIXME("Unable to get backup dc for destroyed context %p.\n", ctx);
783 context_set_current(NULL);
787 if (!(dc = swapchain_get_backup_dc(swapchain)))
789 context_set_current(NULL);
793 if (!context_set_pixel_format(ctx->gl_info, dc, ctx->pixel_format))
795 ERR("Failed to set pixel format %d on device context %p.\n",
796 ctx->pixel_format, dc);
797 context_set_current(NULL);
801 if (!wglMakeCurrent(dc, ctx->glCtx))
803 ERR("Fallback to backup window (dc %p) failed too, last error %#x.\n",
805 context_set_current(NULL);
812 static void context_restore_gl_context(const struct wined3d_gl_info *gl_info, HDC dc, HGLRC gl_ctx, int pf)
814 if (!context_set_pixel_format(gl_info, dc, pf))
816 ERR("Failed to restore pixel format %d on device context %p.\n", pf, dc);
817 context_set_current(NULL);
821 if (!wglMakeCurrent(dc, gl_ctx))
823 ERR("Failed to restore GL context %p on device context %p, last error %#x.\n",
824 gl_ctx, dc, GetLastError());
825 context_set_current(NULL);
829 static void context_update_window(struct wined3d_context *context)
831 if (context->win_handle == context->swapchain->win_handle)
834 TRACE("Updating context %p window from %p to %p.\n",
835 context, context->win_handle, context->swapchain->win_handle);
839 /* You'd figure ReleaseDC() would fail if the DC doesn't match the
840 * window. However, that's not what actually happens, and there are
841 * user32 tests that confirm ReleaseDC() with the wrong window is
842 * supposed to succeed. So explicitly check that the DC belongs to
843 * the window, since we want to avoid releasing a DC that belongs to
844 * some other window if the original window was already destroyed. */
845 if (WindowFromDC(context->hdc) != context->win_handle)
847 WARN("DC %p does not belong to window %p.\n",
848 context->hdc, context->win_handle);
850 else if (!ReleaseDC(context->win_handle, context->hdc))
852 ERR("Failed to release device context %p, last error %#x.\n",
853 context->hdc, GetLastError());
856 else context->valid = 1;
858 context->win_handle = context->swapchain->win_handle;
860 if (!(context->hdc = GetDC(context->win_handle)))
862 ERR("Failed to get a device context for window %p.\n", context->win_handle);
866 if (!context_set_pixel_format(context->gl_info, context->hdc, context->pixel_format))
868 ERR("Failed to set pixel format %d on device context %p.\n",
869 context->pixel_format, context->hdc);
873 context_set_gl_context(context);
881 /* Do not call while under the GL lock. */
882 static void context_destroy_gl_resources(struct wined3d_context *context)
884 const struct wined3d_gl_info *gl_info = context->gl_info;
885 struct wined3d_occlusion_query *occlusion_query;
886 struct wined3d_event_query *event_query;
887 struct fbo_entry *entry, *entry2;
893 restore_ctx = wglGetCurrentContext();
894 restore_dc = wglGetCurrentDC();
895 restore_pf = GetPixelFormat(restore_dc);
897 if (context->valid && restore_ctx != context->glCtx)
898 context_set_gl_context(context);
902 LIST_FOR_EACH_ENTRY(occlusion_query, &context->occlusion_queries, struct wined3d_occlusion_query, entry)
904 if (context->valid && gl_info->supported[ARB_OCCLUSION_QUERY])
905 GL_EXTCALL(glDeleteQueriesARB(1, &occlusion_query->id));
906 occlusion_query->context = NULL;
909 LIST_FOR_EACH_ENTRY(event_query, &context->event_queries, struct wined3d_event_query, entry)
913 if (gl_info->supported[ARB_SYNC])
915 if (event_query->object.sync) GL_EXTCALL(glDeleteSync(event_query->object.sync));
917 else if (gl_info->supported[APPLE_FENCE]) GL_EXTCALL(glDeleteFencesAPPLE(1, &event_query->object.id));
918 else if (gl_info->supported[NV_FENCE]) GL_EXTCALL(glDeleteFencesNV(1, &event_query->object.id));
920 event_query->context = NULL;
923 LIST_FOR_EACH_ENTRY_SAFE(entry, entry2, &context->fbo_destroy_list, struct fbo_entry, entry)
925 if (!context->valid) entry->id = 0;
926 context_destroy_fbo_entry(context, entry);
929 LIST_FOR_EACH_ENTRY_SAFE(entry, entry2, &context->fbo_list, struct fbo_entry, entry)
931 if (!context->valid) entry->id = 0;
932 context_destroy_fbo_entry(context, entry);
937 if (context->dummy_arbfp_prog)
939 GL_EXTCALL(glDeleteProgramsARB(1, &context->dummy_arbfp_prog));
942 if (gl_info->supported[ARB_OCCLUSION_QUERY])
943 GL_EXTCALL(glDeleteQueriesARB(context->free_occlusion_query_count, context->free_occlusion_queries));
945 if (gl_info->supported[ARB_SYNC])
947 for (i = 0; i < context->free_event_query_count; ++i)
949 GL_EXTCALL(glDeleteSync(context->free_event_queries[i].sync));
952 else if (gl_info->supported[APPLE_FENCE])
954 for (i = 0; i < context->free_event_query_count; ++i)
956 GL_EXTCALL(glDeleteFencesAPPLE(1, &context->free_event_queries[i].id));
959 else if (gl_info->supported[NV_FENCE])
961 for (i = 0; i < context->free_event_query_count; ++i)
963 GL_EXTCALL(glDeleteFencesNV(1, &context->free_event_queries[i].id));
967 checkGLcall("context cleanup");
970 HeapFree(GetProcessHeap(), 0, context->free_occlusion_queries);
971 HeapFree(GetProcessHeap(), 0, context->free_event_queries);
975 context_restore_gl_context(gl_info, restore_dc, restore_ctx, restore_pf);
977 else if (wglGetCurrentContext() && !wglMakeCurrent(NULL, NULL))
979 ERR("Failed to disable GL context.\n");
982 ReleaseDC(context->win_handle, context->hdc);
984 if (!wglDeleteContext(context->glCtx))
986 DWORD err = GetLastError();
987 ERR("wglDeleteContext(%p) failed, last error %#x.\n", context->glCtx, err);
991 DWORD context_get_tls_idx(void)
993 return wined3d_context_tls_idx;
996 void context_set_tls_idx(DWORD idx)
998 wined3d_context_tls_idx = idx;
1001 struct wined3d_context *context_get_current(void)
1003 return TlsGetValue(wined3d_context_tls_idx);
1006 /* Do not call while under the GL lock. */
1007 BOOL context_set_current(struct wined3d_context *ctx)
1009 struct wined3d_context *old = context_get_current();
1013 TRACE("Already using D3D context %p.\n", ctx);
1021 TRACE("Switching away from destroyed context %p.\n", old);
1022 context_destroy_gl_resources(old);
1023 HeapFree(GetProcessHeap(), 0, (void *)old->gl_info);
1024 HeapFree(GetProcessHeap(), 0, old);
1036 ERR("Trying to make invalid context %p current\n", ctx);
1040 TRACE("Switching to D3D context %p, GL context %p, device context %p.\n", ctx, ctx->glCtx, ctx->hdc);
1041 if (!context_set_gl_context(ctx))
1045 else if(wglGetCurrentContext())
1047 TRACE("Clearing current D3D context.\n");
1048 if (!wglMakeCurrent(NULL, NULL))
1050 DWORD err = GetLastError();
1051 ERR("Failed to clear current GL context, last error %#x.\n", err);
1052 TlsSetValue(wined3d_context_tls_idx, NULL);
1057 return TlsSetValue(wined3d_context_tls_idx, ctx);
1060 void context_release(struct wined3d_context *context)
1062 TRACE("Releasing context %p, level %u.\n", context, context->level);
1066 if (!context->level)
1067 WARN("Context %p is not active.\n", context);
1068 else if (context != context_get_current())
1069 WARN("Context %p is not the current context.\n", context);
1072 if (!--context->level && context->restore_ctx)
1074 TRACE("Restoring GL context %p on device context %p.\n", context->restore_ctx, context->restore_dc);
1075 context_restore_gl_context(context->gl_info, context->restore_dc, context->restore_ctx, context->restore_pf);
1076 context->restore_ctx = NULL;
1077 context->restore_dc = NULL;
1081 static void context_enter(struct wined3d_context *context)
1083 TRACE("Entering context %p, level %u.\n", context, context->level + 1);
1085 if (!context->level++)
1087 const struct wined3d_context *current_context = context_get_current();
1088 HGLRC current_gl = wglGetCurrentContext();
1090 if (current_gl && (!current_context || current_context->glCtx != current_gl))
1092 TRACE("Another GL context (%p on device context %p) is already current.\n",
1093 current_gl, wglGetCurrentDC());
1094 context->restore_ctx = current_gl;
1095 context->restore_dc = wglGetCurrentDC();
1096 context->restore_pf = GetPixelFormat(context->restore_dc);
1101 void context_invalidate_state(struct wined3d_context *context, DWORD state)
1103 DWORD rep = context->state_table[state].representative;
1107 if (isStateDirty(context, rep)) return;
1109 context->dirtyArray[context->numDirtyEntries++] = rep;
1110 idx = rep / (sizeof(*context->isStateDirty) * CHAR_BIT);
1111 shift = rep & ((sizeof(*context->isStateDirty) * CHAR_BIT) - 1);
1112 context->isStateDirty[idx] |= (1 << shift);
1115 /* This function takes care of wined3d pixel format selection. */
1116 static int context_choose_pixel_format(const struct wined3d_device *device, HDC hdc,
1117 const struct wined3d_format *color_format, const struct wined3d_format *ds_format,
1118 BOOL auxBuffers, BOOL findCompatible)
1121 BYTE redBits, greenBits, blueBits, alphaBits, colorBits;
1122 BYTE depthBits=0, stencilBits=0;
1123 unsigned int current_value;
1124 unsigned int cfg_count = device->adapter->cfg_count;
1127 TRACE("device %p, dc %p, color_format %s, ds_format %s, aux_buffers %#x, find_compatible %#x.\n",
1128 device, hdc, debug_d3dformat(color_format->id), debug_d3dformat(ds_format->id),
1129 auxBuffers, findCompatible);
1131 if (!getColorBits(color_format, &redBits, &greenBits, &blueBits, &alphaBits, &colorBits))
1133 ERR("Unable to get color bits for format %s (%#x)!\n",
1134 debug_d3dformat(color_format->id), color_format->id);
1138 getDepthStencilBits(ds_format, &depthBits, &stencilBits);
1141 for (i = 0; i < cfg_count; ++i)
1143 const struct wined3d_pixel_format *cfg = &device->adapter->cfgs[i];
1146 /* For now only accept RGBA formats. Perhaps some day we will
1147 * allow floating point formats for pbuffers. */
1148 if (cfg->iPixelType != WGL_TYPE_RGBA_ARB)
1150 /* In window mode we need a window drawable format and double buffering. */
1151 if (!(cfg->windowDrawable && cfg->doubleBuffer))
1153 if (cfg->redSize < redBits)
1155 if (cfg->greenSize < greenBits)
1157 if (cfg->blueSize < blueBits)
1159 if (cfg->alphaSize < alphaBits)
1161 if (cfg->depthSize < depthBits)
1163 if (stencilBits && cfg->stencilSize != stencilBits)
1165 /* Check multisampling support. */
1166 if (cfg->numSamples)
1170 /* We try to locate a format which matches our requirements exactly. In case of
1171 * depth it is no problem to emulate 16-bit using e.g. 24-bit, so accept that. */
1172 if (cfg->depthSize == depthBits)
1174 if (cfg->stencilSize == stencilBits)
1176 if (cfg->alphaSize == alphaBits)
1178 /* We like to have aux buffers in backbuffer mode */
1179 if (auxBuffers && cfg->auxBuffers)
1181 if (cfg->redSize == redBits
1182 && cfg->greenSize == greenBits
1183 && cfg->blueSize == blueBits)
1186 if (value > current_value)
1188 iPixelFormat = cfg->iPixelFormat;
1189 current_value = value;
1193 /* When findCompatible is set and no suitable format was found, let ChoosePixelFormat choose a pixel format in order not to crash. */
1194 if(!iPixelFormat && !findCompatible) {
1195 ERR("Can't find a suitable iPixelFormat\n");
1197 } else if(!iPixelFormat) {
1198 PIXELFORMATDESCRIPTOR pfd;
1200 TRACE("Falling back to ChoosePixelFormat as we weren't able to find an exactly matching pixel format\n");
1201 /* PixelFormat selection */
1202 ZeroMemory(&pfd, sizeof(pfd));
1203 pfd.nSize = sizeof(pfd);
1205 pfd.dwFlags = PFD_SUPPORT_OPENGL | PFD_DOUBLEBUFFER | PFD_DRAW_TO_WINDOW;/*PFD_GENERIC_ACCELERATED*/
1206 pfd.iPixelType = PFD_TYPE_RGBA;
1207 pfd.cAlphaBits = alphaBits;
1208 pfd.cColorBits = colorBits;
1209 pfd.cDepthBits = depthBits;
1210 pfd.cStencilBits = stencilBits;
1211 pfd.iLayerType = PFD_MAIN_PLANE;
1213 iPixelFormat = ChoosePixelFormat(hdc, &pfd);
1215 /* If this happens something is very wrong as ChoosePixelFormat barely fails */
1216 ERR("Can't find a suitable iPixelFormat\n");
1221 TRACE("Found iPixelFormat=%d for ColorFormat=%s, DepthStencilFormat=%s\n",
1222 iPixelFormat, debug_d3dformat(color_format->id), debug_d3dformat(ds_format->id));
1223 return iPixelFormat;
1226 /* Context activation is done by the caller. */
1227 static void bind_dummy_textures(const struct wined3d_device *device, const struct wined3d_context *context)
1229 const struct wined3d_gl_info *gl_info = context->gl_info;
1230 unsigned int i, count = min(MAX_COMBINED_SAMPLERS, gl_info->limits.combined_samplers);
1232 for (i = 0; i < count; ++i)
1234 GL_EXTCALL(glActiveTextureARB(GL_TEXTURE0_ARB + i));
1235 checkGLcall("glActiveTextureARB");
1237 gl_info->gl_ops.gl.p_glBindTexture(GL_TEXTURE_2D, device->dummy_texture_2d[i]);
1238 checkGLcall("glBindTexture");
1240 if (gl_info->supported[ARB_TEXTURE_RECTANGLE])
1242 gl_info->gl_ops.gl.p_glBindTexture(GL_TEXTURE_RECTANGLE_ARB, device->dummy_texture_rect[i]);
1243 checkGLcall("glBindTexture");
1246 if (gl_info->supported[EXT_TEXTURE3D])
1248 gl_info->gl_ops.gl.p_glBindTexture(GL_TEXTURE_3D, device->dummy_texture_3d[i]);
1249 checkGLcall("glBindTexture");
1252 if (gl_info->supported[ARB_TEXTURE_CUBE_MAP])
1254 gl_info->gl_ops.gl.p_glBindTexture(GL_TEXTURE_CUBE_MAP, device->dummy_texture_cube[i]);
1255 checkGLcall("glBindTexture");
1260 /* Do not call while under the GL lock. */
1261 struct wined3d_context *context_create(struct wined3d_swapchain *swapchain,
1262 struct wined3d_surface *target, const struct wined3d_format *ds_format)
1264 struct wined3d_device *device = swapchain->device;
1265 const struct wined3d_gl_info *gl_info = &device->adapter->gl_info;
1266 const struct wined3d_format *color_format;
1267 struct wined3d_context *ret;
1268 BOOL auxBuffers = FALSE;
1276 TRACE("swapchain %p, target %p, window %p.\n", swapchain, target, swapchain->win_handle);
1278 ret = HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, sizeof(*ret));
1281 ERR("Failed to allocate context memory.\n");
1285 ret->blit_targets = HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY,
1286 gl_info->limits.buffers * sizeof(*ret->blit_targets));
1287 if (!ret->blit_targets)
1290 ret->draw_buffers = HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY,
1291 gl_info->limits.buffers * sizeof(*ret->draw_buffers));
1292 if (!ret->draw_buffers)
1295 ret->free_occlusion_query_size = 4;
1296 ret->free_occlusion_queries = HeapAlloc(GetProcessHeap(), 0,
1297 ret->free_occlusion_query_size * sizeof(*ret->free_occlusion_queries));
1298 if (!ret->free_occlusion_queries)
1301 list_init(&ret->occlusion_queries);
1303 ret->free_event_query_size = 4;
1304 ret->free_event_queries = HeapAlloc(GetProcessHeap(), 0,
1305 ret->free_event_query_size * sizeof(*ret->free_event_queries));
1306 if (!ret->free_event_queries)
1309 list_init(&ret->event_queries);
1310 list_init(&ret->fbo_list);
1311 list_init(&ret->fbo_destroy_list);
1313 if (!(hdc = GetDC(swapchain->win_handle)))
1315 WARN("Failed to retireve device context, trying swapchain backup.\n");
1317 if (!(hdc = swapchain_get_backup_dc(swapchain)))
1319 ERR("Failed to retrieve a device context.\n");
1324 color_format = target->resource.format;
1326 /* In case of ORM_BACKBUFFER, make sure to request an alpha component for
1327 * X4R4G4B4/X8R8G8B8 as we might need it for the backbuffer. */
1328 if (wined3d_settings.offscreen_rendering_mode == ORM_BACKBUFFER)
1332 if (color_format->id == WINED3DFMT_B4G4R4X4_UNORM)
1333 color_format = wined3d_get_format(gl_info, WINED3DFMT_B4G4R4A4_UNORM);
1334 else if (color_format->id == WINED3DFMT_B8G8R8X8_UNORM)
1335 color_format = wined3d_get_format(gl_info, WINED3DFMT_B8G8R8A8_UNORM);
1338 /* DirectDraw supports 8bit paletted render targets and these are used by
1339 * old games like StarCraft and C&C. Most modern hardware doesn't support
1340 * 8bit natively so we perform some form of 8bit -> 32bit conversion. The
1341 * conversion (ab)uses the alpha component for storing the palette index.
1342 * For this reason we require a format with 8bit alpha, so request
1344 if (color_format->id == WINED3DFMT_P8_UINT)
1345 color_format = wined3d_get_format(gl_info, WINED3DFMT_B8G8R8A8_UNORM);
1347 /* Try to find a pixel format which matches our requirements. */
1348 pixel_format = context_choose_pixel_format(device, hdc, color_format, ds_format, auxBuffers, FALSE);
1350 /* Try to locate a compatible format if we weren't able to find anything. */
1353 TRACE("Trying to locate a compatible pixel format because an exact match failed.\n");
1354 pixel_format = context_choose_pixel_format(device, hdc, color_format, ds_format, auxBuffers, TRUE);
1357 /* If we still don't have a pixel format, something is very wrong as ChoosePixelFormat barely fails */
1360 ERR("Can't find a suitable pixel format.\n");
1366 if (!context_set_pixel_format(gl_info, hdc, pixel_format))
1368 ERR("Failed to set pixel format %d on device context %p.\n", pixel_format, hdc);
1369 context_release(ret);
1373 if (!(ctx = wglCreateContext(hdc)))
1375 ERR("Failed to create a WGL context.\n");
1376 context_release(ret);
1380 if (device->context_count)
1382 if (!wglShareLists(device->contexts[0]->glCtx, ctx))
1384 ERR("wglShareLists(%p, %p) failed, last error %#x.\n",
1385 device->contexts[0]->glCtx, ctx, GetLastError());
1386 context_release(ret);
1387 if (!wglDeleteContext(ctx))
1388 ERR("wglDeleteContext(%p) failed, last error %#x.\n", ctx, GetLastError());
1393 if (!device_context_add(device, ret))
1395 ERR("Failed to add the newly created context to the context list\n");
1396 context_release(ret);
1397 if (!wglDeleteContext(ctx))
1398 ERR("wglDeleteContext(%p) failed, last error %#x.\n", ctx, GetLastError());
1402 ret->gl_info = gl_info;
1403 ret->state_table = device->StateTable;
1405 /* Mark all states dirty to force a proper initialization of the states
1406 * on the first use of the context. */
1407 for (state = 0; state <= STATE_HIGHEST; ++state)
1409 if (ret->state_table[state].representative)
1410 context_invalidate_state(ret, state);
1413 ret->swapchain = swapchain;
1414 ret->current_rt = target;
1415 ret->tid = GetCurrentThreadId();
1417 ret->render_offscreen = surface_is_offscreen(target);
1418 ret->draw_buffers_mask = context_generate_rt_mask(GL_BACK);
1422 ret->win_handle = swapchain->win_handle;
1424 ret->pixel_format = pixel_format;
1426 /* Set up the context defaults */
1427 if (!context_set_current(ret))
1429 ERR("Cannot activate context to set up defaults.\n");
1430 device_context_remove(device, ret);
1431 context_release(ret);
1432 if (!wglDeleteContext(ctx))
1433 ERR("wglDeleteContext(%p) failed, last error %#x.\n", ctx, GetLastError());
1437 switch (swapchain->desc.swap_interval)
1439 case WINED3DPRESENT_INTERVAL_IMMEDIATE:
1442 case WINED3DPRESENT_INTERVAL_DEFAULT:
1443 case WINED3DPRESENT_INTERVAL_ONE:
1446 case WINED3DPRESENT_INTERVAL_TWO:
1449 case WINED3DPRESENT_INTERVAL_THREE:
1452 case WINED3DPRESENT_INTERVAL_FOUR:
1456 FIXME("Unknown swap interval %#x.\n", swapchain->desc.swap_interval);
1460 if (gl_info->supported[WGL_EXT_SWAP_CONTROL])
1462 if (!GL_EXTCALL(wglSwapIntervalEXT(swap_interval)))
1463 ERR("wglSwapIntervalEXT failed to set swap interval %d for context %p, last error %#x\n",
1464 swap_interval, ret, GetLastError());
1467 gl_info->gl_ops.gl.p_glGetIntegerv(GL_AUX_BUFFERS, &ret->aux_buffers);
1469 TRACE("Setting up the screen\n");
1470 /* Clear the screen */
1471 gl_info->gl_ops.gl.p_glClearColor(1.0f, 0.0f, 0.0f, 0.0f);
1472 checkGLcall("glClearColor");
1473 gl_info->gl_ops.gl.p_glClearIndex(0);
1474 gl_info->gl_ops.gl.p_glClearDepth(1);
1475 gl_info->gl_ops.gl.p_glClearStencil(0xffff);
1477 checkGLcall("glClear");
1479 gl_info->gl_ops.gl.p_glLightModeli(GL_LIGHT_MODEL_LOCAL_VIEWER, GL_TRUE);
1480 checkGLcall("glLightModeli(GL_LIGHT_MODEL_LOCAL_VIEWER, GL_TRUE);");
1482 gl_info->gl_ops.gl.p_glTexEnvf(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_COMBINE_EXT);
1483 checkGLcall("glTexEnvf(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_COMBINE_EXT);");
1485 gl_info->gl_ops.gl.p_glLightModeli(GL_LIGHT_MODEL_COLOR_CONTROL, GL_SEPARATE_SPECULAR_COLOR);
1486 checkGLcall("glLightModeli(GL_LIGHT_MODEL_COLOR_CONTROL, GL_SEPARATE_SPECULAR_COLOR);");
1488 gl_info->gl_ops.gl.p_glPixelStorei(GL_PACK_ALIGNMENT, device->surface_alignment);
1489 checkGLcall("glPixelStorei(GL_PACK_ALIGNMENT, device->surface_alignment);");
1490 gl_info->gl_ops.gl.p_glPixelStorei(GL_UNPACK_ALIGNMENT, device->surface_alignment);
1491 checkGLcall("glPixelStorei(GL_UNPACK_ALIGNMENT, device->surface_alignment);");
1493 if (gl_info->supported[APPLE_CLIENT_STORAGE])
1495 /* Most textures will use client storage if supported. Exceptions are
1496 * non-native power of 2 textures and textures in DIB sections. */
1497 gl_info->gl_ops.gl.p_glPixelStorei(GL_UNPACK_CLIENT_STORAGE_APPLE, GL_TRUE);
1498 checkGLcall("glPixelStorei(GL_UNPACK_CLIENT_STORAGE_APPLE, GL_TRUE)");
1500 if (gl_info->supported[ARB_VERTEX_BLEND])
1502 /* Direct3D always uses n-1 weights for n world matrices and uses
1503 * 1 - sum for the last one this is equal to GL_WEIGHT_SUM_UNITY_ARB.
1504 * Enabling it doesn't do anything unless GL_VERTEX_BLEND_ARB isn't
1505 * enabled as well. */
1506 gl_info->gl_ops.gl.p_glEnable(GL_WEIGHT_SUM_UNITY_ARB);
1507 checkGLcall("glEnable(GL_WEIGHT_SUM_UNITY_ARB)");
1509 if (gl_info->supported[NV_TEXTURE_SHADER2])
1511 /* Set up the previous texture input for all shader units. This applies to bump mapping, and in d3d
1512 * the previous texture where to source the offset from is always unit - 1.
1514 for (s = 1; s < gl_info->limits.textures; ++s)
1516 context_active_texture(ret, gl_info, s);
1517 gl_info->gl_ops.gl.p_glTexEnvi(GL_TEXTURE_SHADER_NV,
1518 GL_PREVIOUS_TEXTURE_INPUT_NV, GL_TEXTURE0_ARB + s - 1);
1519 checkGLcall("glTexEnvi(GL_TEXTURE_SHADER_NV, GL_PREVIOUS_TEXTURE_INPUT_NV, ...");
1522 if (gl_info->supported[ARB_FRAGMENT_PROGRAM])
1524 /* MacOS(radeon X1600 at least, but most likely others too) refuses to draw if GLSL and ARBFP are
1525 * enabled, but the currently bound arbfp program is 0. Enabling ARBFP with prog 0 is invalid, but
1526 * GLSL should bypass this. This causes problems in programs that never use the fixed function pipeline,
1527 * because the ARBFP extension is enabled by the ARBFP pipeline at context creation, but no program
1530 * So make sure a program is assigned to each context. The first real ARBFP use will set a different
1531 * program and the dummy program is destroyed when the context is destroyed.
1533 const char *dummy_program =
1535 "MOV result.color, fragment.color.primary;\n"
1537 GL_EXTCALL(glGenProgramsARB(1, &ret->dummy_arbfp_prog));
1538 GL_EXTCALL(glBindProgramARB(GL_FRAGMENT_PROGRAM_ARB, ret->dummy_arbfp_prog));
1539 GL_EXTCALL(glProgramStringARB(GL_FRAGMENT_PROGRAM_ARB, GL_PROGRAM_FORMAT_ASCII_ARB, strlen(dummy_program), dummy_program));
1542 if (gl_info->supported[ARB_POINT_SPRITE])
1544 for (s = 0; s < gl_info->limits.textures; ++s)
1546 context_active_texture(ret, gl_info, s);
1547 gl_info->gl_ops.gl.p_glTexEnvi(GL_POINT_SPRITE_ARB, GL_COORD_REPLACE_ARB, GL_TRUE);
1548 checkGLcall("glTexEnvi(GL_POINT_SPRITE_ARB, GL_COORD_REPLACE_ARB, GL_TRUE)");
1552 if (gl_info->supported[ARB_PROVOKING_VERTEX])
1554 GL_EXTCALL(glProvokingVertex(GL_FIRST_VERTEX_CONVENTION));
1556 else if (gl_info->supported[EXT_PROVOKING_VERTEX])
1558 GL_EXTCALL(glProvokingVertexEXT(GL_FIRST_VERTEX_CONVENTION_EXT));
1560 ret->select_shader = 1;
1562 /* If this happens to be the first context for the device, dummy textures
1563 * are not created yet. In that case, they will be created (and bound) by
1564 * create_dummy_textures right after this context is initialized. */
1565 if (device->dummy_texture_2d[0])
1566 bind_dummy_textures(device, ret);
1568 TRACE("Created context %p.\n", ret);
1573 HeapFree(GetProcessHeap(), 0, ret->free_event_queries);
1574 HeapFree(GetProcessHeap(), 0, ret->free_occlusion_queries);
1575 HeapFree(GetProcessHeap(), 0, ret->draw_buffers);
1576 HeapFree(GetProcessHeap(), 0, ret->blit_targets);
1577 HeapFree(GetProcessHeap(), 0, ret);
1581 /* Do not call while under the GL lock. */
1582 void context_destroy(struct wined3d_device *device, struct wined3d_context *context)
1586 TRACE("Destroying ctx %p\n", context);
1588 if (context->tid == GetCurrentThreadId() || !context->current)
1590 context_destroy_gl_resources(context);
1591 TlsSetValue(wined3d_context_tls_idx, NULL);
1596 /* Make a copy of gl_info for context_destroy_gl_resources use, the one
1597 in wined3d_adapter may go away in the meantime */
1598 struct wined3d_gl_info *gl_info = HeapAlloc(GetProcessHeap(), 0, sizeof(*gl_info));
1599 *gl_info = *context->gl_info;
1600 context->gl_info = gl_info;
1601 context->destroyed = 1;
1605 HeapFree(GetProcessHeap(), 0, context->draw_buffers);
1606 HeapFree(GetProcessHeap(), 0, context->blit_targets);
1607 device_context_remove(device, context);
1608 if (destroy) HeapFree(GetProcessHeap(), 0, context);
1611 /* Context activation is done by the caller. */
1612 static void set_blit_dimension(const struct wined3d_gl_info *gl_info, UINT width, UINT height)
1614 const GLdouble projection[] =
1616 2.0 / width, 0.0, 0.0, 0.0,
1617 0.0, 2.0 / height, 0.0, 0.0,
1619 -1.0, -1.0, -1.0, 1.0,
1622 gl_info->gl_ops.gl.p_glMatrixMode(GL_PROJECTION);
1623 checkGLcall("glMatrixMode(GL_PROJECTION)");
1624 gl_info->gl_ops.gl.p_glLoadMatrixd(projection);
1625 checkGLcall("glLoadMatrixd");
1626 gl_info->gl_ops.gl.p_glViewport(0, 0, width, height);
1627 checkGLcall("glViewport");
1630 static void context_get_rt_size(const struct wined3d_context *context, SIZE *size)
1632 const struct wined3d_surface *rt = context->current_rt;
1634 if (rt->container.type == WINED3D_CONTAINER_SWAPCHAIN
1635 && rt->container.u.swapchain->front_buffer == rt)
1639 GetClientRect(context->win_handle, &window_size);
1640 size->cx = window_size.right - window_size.left;
1641 size->cy = window_size.bottom - window_size.top;
1646 size->cx = rt->resource.width;
1647 size->cy = rt->resource.height;
1650 /*****************************************************************************
1653 * Sets up a context for DirectDraw blitting.
1654 * All texture units are disabled, texture unit 0 is set as current unit
1655 * fog, lighting, blending, alpha test, z test, scissor test, culling disabled
1656 * color writing enabled for all channels
1657 * register combiners disabled, shaders disabled
1658 * world matrix is set to identity, texture matrix 0 too
1659 * projection matrix is setup for drawing screen coordinates
1662 * This: Device to activate the context for
1663 * context: Context to setup
1665 *****************************************************************************/
1666 /* Context activation is done by the caller. */
1667 static void SetupForBlit(const struct wined3d_device *device, struct wined3d_context *context)
1670 const struct wined3d_gl_info *gl_info = context->gl_info;
1674 TRACE("Setting up context %p for blitting\n", context);
1676 context_get_rt_size(context, &rt_size);
1678 if (context->last_was_blit)
1680 if (context->blit_w != rt_size.cx || context->blit_h != rt_size.cy)
1682 set_blit_dimension(gl_info, rt_size.cx, rt_size.cy);
1683 context->blit_w = rt_size.cx;
1684 context->blit_h = rt_size.cy;
1685 /* No need to dirtify here, the states are still dirtified because
1686 * they weren't applied since the last SetupForBlit() call. */
1688 TRACE("Context is already set up for blitting, nothing to do\n");
1691 context->last_was_blit = TRUE;
1693 /* Disable all textures. The caller can then bind a texture it wants to blit
1696 * The blitting code uses (for now) the fixed function pipeline, so make sure to reset all fixed
1697 * function texture unit. No need to care for higher samplers
1699 for (i = gl_info->limits.textures - 1; i > 0 ; --i)
1701 sampler = device->rev_tex_unit_map[i];
1702 context_active_texture(context, gl_info, i);
1704 if (gl_info->supported[ARB_TEXTURE_CUBE_MAP])
1706 gl_info->gl_ops.gl.p_glDisable(GL_TEXTURE_CUBE_MAP_ARB);
1707 checkGLcall("glDisable GL_TEXTURE_CUBE_MAP_ARB");
1709 gl_info->gl_ops.gl.p_glDisable(GL_TEXTURE_3D);
1710 checkGLcall("glDisable GL_TEXTURE_3D");
1711 if (gl_info->supported[ARB_TEXTURE_RECTANGLE])
1713 gl_info->gl_ops.gl.p_glDisable(GL_TEXTURE_RECTANGLE_ARB);
1714 checkGLcall("glDisable GL_TEXTURE_RECTANGLE_ARB");
1716 gl_info->gl_ops.gl.p_glDisable(GL_TEXTURE_2D);
1717 checkGLcall("glDisable GL_TEXTURE_2D");
1719 gl_info->gl_ops.gl.p_glTexEnvi(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_REPLACE);
1720 checkGLcall("glTexEnvi(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_REPLACE);");
1722 if (sampler != WINED3D_UNMAPPED_STAGE)
1724 if (sampler < MAX_TEXTURES)
1725 context_invalidate_state(context, STATE_TEXTURESTAGE(sampler, WINED3D_TSS_COLOR_OP));
1726 context_invalidate_state(context, STATE_SAMPLER(sampler));
1729 context_active_texture(context, gl_info, 0);
1731 sampler = device->rev_tex_unit_map[0];
1733 if (gl_info->supported[ARB_TEXTURE_CUBE_MAP])
1735 gl_info->gl_ops.gl.p_glDisable(GL_TEXTURE_CUBE_MAP_ARB);
1736 checkGLcall("glDisable GL_TEXTURE_CUBE_MAP_ARB");
1738 gl_info->gl_ops.gl.p_glDisable(GL_TEXTURE_3D);
1739 checkGLcall("glDisable GL_TEXTURE_3D");
1740 if (gl_info->supported[ARB_TEXTURE_RECTANGLE])
1742 gl_info->gl_ops.gl.p_glDisable(GL_TEXTURE_RECTANGLE_ARB);
1743 checkGLcall("glDisable GL_TEXTURE_RECTANGLE_ARB");
1745 gl_info->gl_ops.gl.p_glDisable(GL_TEXTURE_2D);
1746 checkGLcall("glDisable GL_TEXTURE_2D");
1748 gl_info->gl_ops.gl.p_glTexEnvi(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_REPLACE);
1750 gl_info->gl_ops.gl.p_glMatrixMode(GL_TEXTURE);
1751 checkGLcall("glMatrixMode(GL_TEXTURE)");
1752 gl_info->gl_ops.gl.p_glLoadIdentity();
1753 checkGLcall("glLoadIdentity()");
1755 if (gl_info->supported[EXT_TEXTURE_LOD_BIAS])
1757 gl_info->gl_ops.gl.p_glTexEnvf(GL_TEXTURE_FILTER_CONTROL_EXT,
1758 GL_TEXTURE_LOD_BIAS_EXT, 0.0f);
1759 checkGLcall("glTexEnvf GL_TEXTURE_LOD_BIAS_EXT ...");
1762 if (sampler != WINED3D_UNMAPPED_STAGE)
1764 if (sampler < MAX_TEXTURES)
1766 context_invalidate_state(context, STATE_TRANSFORM(WINED3D_TS_TEXTURE0 + sampler));
1767 context_invalidate_state(context, STATE_TEXTURESTAGE(sampler, WINED3D_TSS_COLOR_OP));
1769 context_invalidate_state(context, STATE_SAMPLER(sampler));
1772 /* Other misc states */
1773 gl_info->gl_ops.gl.p_glDisable(GL_ALPHA_TEST);
1774 checkGLcall("glDisable(GL_ALPHA_TEST)");
1775 context_invalidate_state(context, STATE_RENDER(WINED3D_RS_ALPHATESTENABLE));
1776 gl_info->gl_ops.gl.p_glDisable(GL_LIGHTING);
1777 checkGLcall("glDisable GL_LIGHTING");
1778 context_invalidate_state(context, STATE_RENDER(WINED3D_RS_LIGHTING));
1779 gl_info->gl_ops.gl.p_glDisable(GL_DEPTH_TEST);
1780 checkGLcall("glDisable GL_DEPTH_TEST");
1781 context_invalidate_state(context, STATE_RENDER(WINED3D_RS_ZENABLE));
1782 glDisableWINE(GL_FOG);
1783 checkGLcall("glDisable GL_FOG");
1784 context_invalidate_state(context, STATE_RENDER(WINED3D_RS_FOGENABLE));
1785 gl_info->gl_ops.gl.p_glDisable(GL_BLEND);
1786 checkGLcall("glDisable GL_BLEND");
1787 context_invalidate_state(context, STATE_RENDER(WINED3D_RS_ALPHABLENDENABLE));
1788 gl_info->gl_ops.gl.p_glDisable(GL_CULL_FACE);
1789 checkGLcall("glDisable GL_CULL_FACE");
1790 context_invalidate_state(context, STATE_RENDER(WINED3D_RS_CULLMODE));
1791 gl_info->gl_ops.gl.p_glDisable(GL_STENCIL_TEST);
1792 checkGLcall("glDisable GL_STENCIL_TEST");
1793 context_invalidate_state(context, STATE_RENDER(WINED3D_RS_STENCILENABLE));
1794 gl_info->gl_ops.gl.p_glDisable(GL_SCISSOR_TEST);
1795 checkGLcall("glDisable GL_SCISSOR_TEST");
1796 context_invalidate_state(context, STATE_RENDER(WINED3D_RS_SCISSORTESTENABLE));
1797 if (gl_info->supported[ARB_POINT_SPRITE])
1799 gl_info->gl_ops.gl.p_glDisable(GL_POINT_SPRITE_ARB);
1800 checkGLcall("glDisable GL_POINT_SPRITE_ARB");
1801 context_invalidate_state(context, STATE_RENDER(WINED3D_RS_POINTSPRITEENABLE));
1803 gl_info->gl_ops.gl.p_glColorMask(GL_TRUE, GL_TRUE,GL_TRUE,GL_TRUE);
1804 checkGLcall("glColorMask");
1805 context_invalidate_state(context, STATE_RENDER(WINED3D_RS_COLORWRITEENABLE));
1806 context_invalidate_state(context, STATE_RENDER(WINED3D_RS_COLORWRITEENABLE1));
1807 context_invalidate_state(context, STATE_RENDER(WINED3D_RS_COLORWRITEENABLE2));
1808 context_invalidate_state(context, STATE_RENDER(WINED3D_RS_COLORWRITEENABLE3));
1809 if (gl_info->supported[EXT_SECONDARY_COLOR])
1811 gl_info->gl_ops.gl.p_glDisable(GL_COLOR_SUM_EXT);
1812 context_invalidate_state(context, STATE_RENDER(WINED3D_RS_SPECULARENABLE));
1813 checkGLcall("glDisable(GL_COLOR_SUM_EXT)");
1816 /* Setup transforms */
1817 gl_info->gl_ops.gl.p_glMatrixMode(GL_MODELVIEW);
1818 checkGLcall("glMatrixMode(GL_MODELVIEW)");
1819 gl_info->gl_ops.gl.p_glLoadIdentity();
1820 checkGLcall("glLoadIdentity()");
1821 context_invalidate_state(context, STATE_TRANSFORM(WINED3D_TS_WORLD_MATRIX(0)));
1823 context->last_was_rhw = TRUE;
1824 context_invalidate_state(context, STATE_VDECL); /* because of last_was_rhw = TRUE */
1826 gl_info->gl_ops.gl.p_glDisable(GL_CLIP_PLANE0); checkGLcall("glDisable(clip plane 0)");
1827 gl_info->gl_ops.gl.p_glDisable(GL_CLIP_PLANE1); checkGLcall("glDisable(clip plane 1)");
1828 gl_info->gl_ops.gl.p_glDisable(GL_CLIP_PLANE2); checkGLcall("glDisable(clip plane 2)");
1829 gl_info->gl_ops.gl.p_glDisable(GL_CLIP_PLANE3); checkGLcall("glDisable(clip plane 3)");
1830 gl_info->gl_ops.gl.p_glDisable(GL_CLIP_PLANE4); checkGLcall("glDisable(clip plane 4)");
1831 gl_info->gl_ops.gl.p_glDisable(GL_CLIP_PLANE5); checkGLcall("glDisable(clip plane 5)");
1832 context_invalidate_state(context, STATE_RENDER(WINED3D_RS_CLIPPING));
1834 set_blit_dimension(gl_info, rt_size.cx, rt_size.cy);
1836 /* Disable shaders */
1837 device->shader_backend->shader_select(context, WINED3D_SHADER_MODE_NONE, WINED3D_SHADER_MODE_NONE);
1838 context->select_shader = 1;
1839 context->load_constants = 1;
1841 context->blit_w = rt_size.cx;
1842 context->blit_h = rt_size.cy;
1843 context_invalidate_state(context, STATE_VIEWPORT);
1844 context_invalidate_state(context, STATE_TRANSFORM(WINED3D_TS_PROJECTION));
1847 static inline BOOL is_rt_mask_onscreen(DWORD rt_mask)
1849 return rt_mask & (1 << 31);
1852 static inline GLenum draw_buffer_from_rt_mask(DWORD rt_mask)
1854 return rt_mask & ~(1 << 31);
1857 /* Context activation is done by the caller. */
1858 static void context_apply_draw_buffers(struct wined3d_context *context, DWORD rt_mask)
1860 const struct wined3d_gl_info *gl_info = context->gl_info;
1864 gl_info->gl_ops.gl.p_glDrawBuffer(GL_NONE);
1865 checkGLcall("glDrawBuffer()");
1867 else if (is_rt_mask_onscreen(rt_mask))
1869 gl_info->gl_ops.gl.p_glDrawBuffer(draw_buffer_from_rt_mask(rt_mask));
1870 checkGLcall("glDrawBuffer()");
1874 if (wined3d_settings.offscreen_rendering_mode == ORM_FBO)
1881 context->draw_buffers[i] = GL_COLOR_ATTACHMENT0 + i;
1883 context->draw_buffers[i] = GL_NONE;
1889 if (gl_info->supported[ARB_DRAW_BUFFERS])
1891 GL_EXTCALL(glDrawBuffersARB(i, context->draw_buffers));
1892 checkGLcall("glDrawBuffers()");
1896 gl_info->gl_ops.gl.p_glDrawBuffer(context->draw_buffers[0]);
1897 checkGLcall("glDrawBuffer()");
1902 ERR("Unexpected draw buffers mask with backbuffer ORM.\n");
1907 /* Context activation is done by the caller. */
1908 void context_set_draw_buffer(struct wined3d_context *context, GLenum buffer)
1910 const struct wined3d_gl_info *gl_info = context->gl_info;
1912 gl_info->gl_ops.gl.p_glDrawBuffer(buffer);
1913 checkGLcall("glDrawBuffer()");
1914 if (context->current_fbo)
1915 context->current_fbo->rt_mask = context_generate_rt_mask(buffer);
1917 context->draw_buffers_mask = context_generate_rt_mask(buffer);
1920 /* Context activation is done by the caller. */
1921 void context_active_texture(struct wined3d_context *context, const struct wined3d_gl_info *gl_info, unsigned int unit)
1923 GL_EXTCALL(glActiveTextureARB(GL_TEXTURE0 + unit));
1924 checkGLcall("glActiveTextureARB");
1925 context->active_texture = unit;
1928 void context_bind_texture(struct wined3d_context *context, GLenum target, GLuint name)
1930 const struct wined3d_gl_info *gl_info = context->gl_info;
1931 DWORD unit = context->active_texture;
1932 DWORD old_texture_type = context->texture_type[unit];
1936 gl_info->gl_ops.gl.p_glBindTexture(target, name);
1937 checkGLcall("glBindTexture");
1944 if (old_texture_type != target)
1946 const struct wined3d_device *device = context->swapchain->device;
1948 switch (old_texture_type)
1954 gl_info->gl_ops.gl.p_glBindTexture(GL_TEXTURE_2D, device->dummy_texture_2d[unit]);
1955 checkGLcall("glBindTexture");
1957 case GL_TEXTURE_RECTANGLE_ARB:
1958 gl_info->gl_ops.gl.p_glBindTexture(GL_TEXTURE_RECTANGLE_ARB, device->dummy_texture_rect[unit]);
1959 checkGLcall("glBindTexture");
1961 case GL_TEXTURE_CUBE_MAP:
1962 gl_info->gl_ops.gl.p_glBindTexture(GL_TEXTURE_CUBE_MAP, device->dummy_texture_cube[unit]);
1963 checkGLcall("glBindTexture");
1966 gl_info->gl_ops.gl.p_glBindTexture(GL_TEXTURE_3D, device->dummy_texture_3d[unit]);
1967 checkGLcall("glBindTexture");
1970 ERR("Unexpected texture target %#x\n", old_texture_type);
1973 context->texture_type[unit] = target;
1977 static void context_set_render_offscreen(struct wined3d_context *context, BOOL offscreen)
1979 if (context->render_offscreen == offscreen) return;
1981 context_invalidate_state(context, STATE_POINTSPRITECOORDORIGIN);
1982 context_invalidate_state(context, STATE_TRANSFORM(WINED3D_TS_PROJECTION));
1983 context_invalidate_state(context, STATE_VIEWPORT);
1984 context_invalidate_state(context, STATE_SCISSORRECT);
1985 context_invalidate_state(context, STATE_FRONTFACE);
1986 context->render_offscreen = offscreen;
1989 static BOOL match_depth_stencil_format(const struct wined3d_format *existing,
1990 const struct wined3d_format *required)
1992 BYTE existing_depth, existing_stencil, required_depth, required_stencil;
1994 if (existing == required) return TRUE;
1995 if ((existing->flags & WINED3DFMT_FLAG_FLOAT) != (required->flags & WINED3DFMT_FLAG_FLOAT)) return FALSE;
1997 getDepthStencilBits(existing, &existing_depth, &existing_stencil);
1998 getDepthStencilBits(required, &required_depth, &required_stencil);
2000 if(existing_depth < required_depth) return FALSE;
2001 /* If stencil bits are used the exact amount is required - otherwise wrapping
2002 * won't work correctly */
2003 if(required_stencil && required_stencil != existing_stencil) return FALSE;
2007 /* The caller provides a context */
2008 static void context_validate_onscreen_formats(struct wined3d_context *context,
2009 const struct wined3d_surface *depth_stencil)
2011 /* Onscreen surfaces are always in a swapchain */
2012 struct wined3d_swapchain *swapchain = context->current_rt->container.u.swapchain;
2014 if (context->render_offscreen || !depth_stencil) return;
2015 if (match_depth_stencil_format(swapchain->ds_format, depth_stencil->resource.format)) return;
2017 /* TODO: If the requested format would satisfy the needs of the existing one(reverse match),
2018 * or no onscreen depth buffer was created, the OpenGL drawable could be changed to the new
2020 WARN("Depth stencil format is not supported by WGL, rendering the backbuffer in an FBO\n");
2022 /* The currently active context is the necessary context to access the swapchain's onscreen buffers */
2023 surface_load_location(context->current_rt, SFLAG_INTEXTURE, NULL);
2024 swapchain->render_to_fbo = TRUE;
2025 swapchain_update_draw_bindings(swapchain);
2026 context_set_render_offscreen(context, TRUE);
2029 static DWORD context_generate_rt_mask_no_fbo(const struct wined3d_device *device, const struct wined3d_surface *rt)
2031 if (!rt || rt->resource.format->id == WINED3DFMT_NULL)
2033 else if (rt->container.type == WINED3D_CONTAINER_SWAPCHAIN)
2034 return context_generate_rt_mask_from_surface(rt);
2036 return context_generate_rt_mask(device->offscreenBuffer);
2039 /* Context activation is done by the caller. */
2040 void context_apply_blit_state(struct wined3d_context *context, const struct wined3d_device *device)
2042 struct wined3d_surface *rt = context->current_rt;
2043 DWORD rt_mask, *cur_mask;
2045 if (wined3d_settings.offscreen_rendering_mode == ORM_FBO)
2047 context_validate_onscreen_formats(context, NULL);
2049 if (context->render_offscreen)
2051 surface_internal_preload(rt, SRGB_RGB);
2053 context_apply_fbo_state_blit(context, GL_FRAMEBUFFER, rt, NULL, rt->draw_binding);
2054 if (rt->resource.format->id != WINED3DFMT_NULL)
2061 context_bind_fbo(context, GL_FRAMEBUFFER, NULL);
2062 rt_mask = context_generate_rt_mask_from_surface(rt);
2067 rt_mask = context_generate_rt_mask_no_fbo(device, rt);
2070 cur_mask = context->current_fbo ? &context->current_fbo->rt_mask : &context->draw_buffers_mask;
2072 if (rt_mask != *cur_mask)
2074 context_apply_draw_buffers(context, rt_mask);
2075 *cur_mask = rt_mask;
2078 if (wined3d_settings.offscreen_rendering_mode == ORM_FBO)
2080 context_check_fbo_status(context, GL_FRAMEBUFFER);
2083 SetupForBlit(device, context);
2084 context_invalidate_state(context, STATE_FRAMEBUFFER);
2087 static BOOL context_validate_rt_config(UINT rt_count,
2088 struct wined3d_surface * const *rts, const struct wined3d_surface *ds)
2092 if (ds) return TRUE;
2094 for (i = 0; i < rt_count; ++i)
2096 if (rts[i] && rts[i]->resource.format->id != WINED3DFMT_NULL)
2100 WARN("Invalid render target config, need at least one attachment.\n");
2104 /* Context activation is done by the caller. */
2105 BOOL context_apply_clear_state(struct wined3d_context *context, const struct wined3d_device *device,
2106 UINT rt_count, const struct wined3d_fb_state *fb)
2108 const struct wined3d_gl_info *gl_info = context->gl_info;
2109 DWORD rt_mask = 0, *cur_mask;
2111 struct wined3d_surface **rts = fb->render_targets;
2113 if (isStateDirty(context, STATE_FRAMEBUFFER) || fb != &device->fb
2114 || rt_count != context->gl_info->limits.buffers)
2116 if (!context_validate_rt_config(rt_count, rts, fb->depth_stencil))
2119 if (wined3d_settings.offscreen_rendering_mode == ORM_FBO)
2121 context_validate_onscreen_formats(context, fb->depth_stencil);
2123 if (!rt_count || surface_is_offscreen(rts[0]))
2125 for (i = 0; i < rt_count; ++i)
2127 context->blit_targets[i] = rts[i];
2128 if (rts[i] && rts[i]->resource.format->id != WINED3DFMT_NULL)
2129 rt_mask |= (1 << i);
2131 while (i < context->gl_info->limits.buffers)
2133 context->blit_targets[i] = NULL;
2136 context_apply_fbo_state(context, GL_FRAMEBUFFER, context->blit_targets, fb->depth_stencil,
2137 rt_count ? rts[0]->draw_binding : SFLAG_INTEXTURE);
2138 gl_info->gl_ops.gl.p_glReadBuffer(GL_NONE);
2139 checkGLcall("glReadBuffer");
2143 context_apply_fbo_state(context, GL_FRAMEBUFFER, NULL, NULL, SFLAG_INDRAWABLE);
2144 rt_mask = context_generate_rt_mask_from_surface(rts[0]);
2147 /* If the framebuffer is not the device's fb the device's fb has to be reapplied
2148 * next draw. Otherwise we could mark the framebuffer state clean here, once the
2149 * state management allows this */
2150 context_invalidate_state(context, STATE_FRAMEBUFFER);
2154 rt_mask = context_generate_rt_mask_no_fbo(device, rt_count ? rts[0] : NULL);
2157 else if (wined3d_settings.offscreen_rendering_mode == ORM_FBO
2158 && (!rt_count || surface_is_offscreen(rts[0])))
2160 for (i = 0; i < rt_count; ++i)
2162 if (rts[i] && rts[i]->resource.format->id != WINED3DFMT_NULL) rt_mask |= (1 << i);
2167 rt_mask = context_generate_rt_mask_no_fbo(device, rt_count ? rts[0] : NULL);
2170 cur_mask = context->current_fbo ? &context->current_fbo->rt_mask : &context->draw_buffers_mask;
2172 if (rt_mask != *cur_mask)
2174 context_apply_draw_buffers(context, rt_mask);
2175 *cur_mask = rt_mask;
2176 context_invalidate_state(context, STATE_FRAMEBUFFER);
2179 if (wined3d_settings.offscreen_rendering_mode == ORM_FBO)
2181 context_check_fbo_status(context, GL_FRAMEBUFFER);
2184 if (context->last_was_blit)
2185 context->last_was_blit = FALSE;
2187 /* Blending and clearing should be orthogonal, but tests on the nvidia
2188 * driver show that disabling blending when clearing improves the clearing
2189 * performance incredibly. */
2190 gl_info->gl_ops.gl.p_glDisable(GL_BLEND);
2191 gl_info->gl_ops.gl.p_glEnable(GL_SCISSOR_TEST);
2192 checkGLcall("glEnable GL_SCISSOR_TEST");
2194 context_invalidate_state(context, STATE_RENDER(WINED3D_RS_ALPHABLENDENABLE));
2195 context_invalidate_state(context, STATE_RENDER(WINED3D_RS_SCISSORTESTENABLE));
2196 context_invalidate_state(context, STATE_SCISSORRECT);
2201 static DWORD find_draw_buffers_mask(const struct wined3d_context *context, const struct wined3d_device *device)
2203 const struct wined3d_state *state = &device->stateBlock->state;
2204 struct wined3d_surface **rts = state->fb->render_targets;
2205 struct wined3d_shader *ps = state->pixel_shader;
2206 DWORD rt_mask, rt_mask_bits;
2209 if (wined3d_settings.offscreen_rendering_mode != ORM_FBO) return context_generate_rt_mask_no_fbo(device, rts[0]);
2210 else if (!context->render_offscreen) return context_generate_rt_mask_from_surface(rts[0]);
2212 rt_mask = ps ? ps->reg_maps.rt_mask : 1;
2213 rt_mask &= device->valid_rt_mask;
2214 rt_mask_bits = rt_mask;
2216 while (rt_mask_bits)
2218 rt_mask_bits &= ~(1 << i);
2219 if (!rts[i] || rts[i]->resource.format->id == WINED3DFMT_NULL)
2220 rt_mask &= ~(1 << i);
2228 /* Context activation is done by the caller. */
2229 void context_state_fb(struct wined3d_context *context, const struct wined3d_state *state, DWORD state_id)
2231 const struct wined3d_device *device = context->swapchain->device;
2232 const struct wined3d_gl_info *gl_info = context->gl_info;
2233 const struct wined3d_fb_state *fb = state->fb;
2234 DWORD rt_mask = find_draw_buffers_mask(context, device);
2237 if (wined3d_settings.offscreen_rendering_mode == ORM_FBO)
2239 if (!context->render_offscreen)
2241 context_apply_fbo_state(context, GL_FRAMEBUFFER, NULL, NULL, SFLAG_INDRAWABLE);
2245 context_apply_fbo_state(context, GL_FRAMEBUFFER, fb->render_targets, fb->depth_stencil,
2246 fb->render_targets[0]->draw_binding);
2247 gl_info->gl_ops.gl.p_glReadBuffer(GL_NONE);
2248 checkGLcall("glReadBuffer");
2252 cur_mask = context->current_fbo ? &context->current_fbo->rt_mask : &context->draw_buffers_mask;
2253 if (rt_mask != *cur_mask)
2255 context_apply_draw_buffers(context, rt_mask);
2256 *cur_mask = rt_mask;
2260 /* Context activation is done by the caller. */
2261 void context_state_drawbuf(struct wined3d_context *context, const struct wined3d_state *state, DWORD state_id)
2263 const struct wined3d_device *device = context->swapchain->device;
2264 DWORD rt_mask, *cur_mask;
2266 if (isStateDirty(context, STATE_FRAMEBUFFER)) return;
2268 cur_mask = context->current_fbo ? &context->current_fbo->rt_mask : &context->draw_buffers_mask;
2269 rt_mask = find_draw_buffers_mask(context, device);
2270 if (rt_mask != *cur_mask)
2272 context_apply_draw_buffers(context, rt_mask);
2273 *cur_mask = rt_mask;
2277 /* Context activation is done by the caller. */
2278 BOOL context_apply_draw_state(struct wined3d_context *context, struct wined3d_device *device)
2280 const struct wined3d_state *state = &device->stateBlock->state;
2281 const struct StateEntry *state_table = context->state_table;
2282 const struct wined3d_fb_state *fb = state->fb;
2285 if (!context_validate_rt_config(context->gl_info->limits.buffers,
2286 fb->render_targets, fb->depth_stencil))
2289 if (wined3d_settings.offscreen_rendering_mode == ORM_FBO && isStateDirty(context, STATE_FRAMEBUFFER))
2291 context_validate_onscreen_formats(context, fb->depth_stencil);
2294 /* Preload resources before FBO setup. Texture preload in particular may
2295 * result in changes to the current FBO, due to using e.g. FBO blits for
2296 * updating a resource location. */
2297 device_update_tex_unit_map(device);
2298 device_preload_textures(device);
2299 if (isStateDirty(context, STATE_VDECL) || isStateDirty(context, STATE_STREAMSRC))
2300 device_update_stream_info(device, context->gl_info);
2301 if (state->index_buffer && !state->user_stream)
2303 if (device->strided_streams.all_vbo)
2304 wined3d_buffer_preload(state->index_buffer);
2306 buffer_get_sysmem(state->index_buffer, context->gl_info);
2309 for (i = 0; i < context->numDirtyEntries; ++i)
2311 DWORD rep = context->dirtyArray[i];
2312 DWORD idx = rep / (sizeof(*context->isStateDirty) * CHAR_BIT);
2313 BYTE shift = rep & ((sizeof(*context->isStateDirty) * CHAR_BIT) - 1);
2314 context->isStateDirty[idx] &= ~(1 << shift);
2315 state_table[rep].apply(context, state, rep);
2318 if (context->select_shader)
2320 device->shader_backend->shader_select(context,
2321 use_vs(state) ? WINED3D_SHADER_MODE_SHADER : WINED3D_SHADER_MODE_FFP,
2322 use_ps(state) ? WINED3D_SHADER_MODE_SHADER : WINED3D_SHADER_MODE_FFP);
2323 context->select_shader = 0;
2326 if (context->load_constants)
2328 device->shader_backend->shader_load_constants(context, use_ps(state), use_vs(state));
2329 context->load_constants = 0;
2332 if (wined3d_settings.offscreen_rendering_mode == ORM_FBO)
2334 context_check_fbo_status(context, GL_FRAMEBUFFER);
2337 context->numDirtyEntries = 0; /* This makes the whole list clean */
2338 context->last_was_blit = FALSE;
2343 static void context_setup_target(struct wined3d_context *context, struct wined3d_surface *target)
2345 BOOL old_render_offscreen = context->render_offscreen, render_offscreen;
2347 render_offscreen = surface_is_offscreen(target);
2348 if (context->current_rt == target && render_offscreen == old_render_offscreen) return;
2350 /* To compensate the lack of format switching with some offscreen rendering methods and on onscreen buffers
2351 * the alpha blend state changes with different render target formats. */
2352 if (!context->current_rt)
2354 context_invalidate_state(context, STATE_RENDER(WINED3D_RS_ALPHABLENDENABLE));
2358 const struct wined3d_format *old = context->current_rt->resource.format;
2359 const struct wined3d_format *new = target->resource.format;
2361 if (old->id != new->id)
2363 /* Disable blending when the alpha mask has changed and when a format doesn't support blending. */
2364 if ((old->alpha_size && !new->alpha_size) || (!old->alpha_size && new->alpha_size)
2365 || !(new->flags & WINED3DFMT_FLAG_POSTPIXELSHADER_BLENDING))
2366 context_invalidate_state(context, STATE_RENDER(WINED3D_RS_ALPHABLENDENABLE));
2368 /* Update sRGB writing when switching between formats that do/do not support sRGB writing */
2369 if ((old->flags & WINED3DFMT_FLAG_SRGB_WRITE) != (new->flags & WINED3DFMT_FLAG_SRGB_WRITE))
2370 context_invalidate_state(context, STATE_RENDER(WINED3D_RS_SRGBWRITEENABLE));
2373 /* When switching away from an offscreen render target, and we're not
2374 * using FBOs, we have to read the drawable into the texture. This is
2375 * done via PreLoad (and SFLAG_INDRAWABLE set on the surface). There
2376 * are some things that need care though. PreLoad needs a GL context,
2377 * and FindContext is called before the context is activated. It also
2378 * has to be called with the old rendertarget active, otherwise a
2379 * wrong drawable is read. */
2380 if (wined3d_settings.offscreen_rendering_mode != ORM_FBO
2381 && old_render_offscreen && context->current_rt != target)
2383 /* Read the back buffer of the old drawable into the destination texture. */
2384 if (context->current_rt->texture_name_srgb)
2385 surface_internal_preload(context->current_rt, SRGB_SRGB);
2386 surface_internal_preload(context->current_rt, SRGB_RGB);
2387 surface_modify_location(context->current_rt, SFLAG_INDRAWABLE, FALSE);
2391 context->current_rt = target;
2392 context_set_render_offscreen(context, render_offscreen);
2395 /* Do not call while under the GL lock. */
2396 struct wined3d_context *context_acquire(const struct wined3d_device *device, struct wined3d_surface *target)
2398 struct wined3d_context *current_context = context_get_current();
2399 struct wined3d_context *context;
2401 TRACE("device %p, target %p.\n", device, target);
2403 if (current_context && current_context->destroyed)
2404 current_context = NULL;
2409 && current_context->current_rt
2410 && current_context->swapchain->device == device)
2412 target = current_context->current_rt;
2416 struct wined3d_swapchain *swapchain = device->swapchains[0];
2417 if (swapchain->back_buffers)
2418 target = swapchain->back_buffers[0];
2420 target = swapchain->front_buffer;
2424 if (current_context && current_context->current_rt == target)
2426 context = current_context;
2428 else if (target->container.type == WINED3D_CONTAINER_SWAPCHAIN)
2430 TRACE("Rendering onscreen.\n");
2432 context = swapchain_get_context(target->container.u.swapchain);
2436 TRACE("Rendering offscreen.\n");
2438 /* Stay with the current context if possible. Otherwise use the
2439 * context for the primary swapchain. */
2440 if (current_context && current_context->swapchain->device == device)
2441 context = current_context;
2443 context = swapchain_get_context(device->swapchains[0]);
2446 context_update_window(context);
2447 context_setup_target(context, target);
2448 context_enter(context);
2449 if (!context->valid) return context;
2451 if (context != current_context)
2453 if (!context_set_current(context))
2454 ERR("Failed to activate the new context.\n");
2456 else if (context->restore_ctx)
2458 context_set_gl_context(context);