urlmon: Implemented CreateUriWithFragment.
[wine/multimedia.git] / dlls / wined3d / context.c
blobf80ab4f4915660fb9fb80bf5a92ab52136e912d2
1 /*
2 * Context and render target management in wined3d
4 * Copyright 2007-2008 Stefan Dösinger for CodeWeavers
5 * Copyright 2009 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
22 #include "config.h"
23 #include <stdio.h>
24 #ifdef HAVE_FLOAT_H
25 # include <float.h>
26 #endif
27 #include "wined3d_private.h"
29 WINE_DEFAULT_DEBUG_CHANNEL(d3d);
31 static DWORD wined3d_context_tls_idx;
33 /* FBO helper functions */
35 /* GL locking is done by the caller */
36 void context_bind_fbo(struct wined3d_context *context, GLenum target, GLuint *fbo)
38 const struct wined3d_gl_info *gl_info = context->gl_info;
39 GLuint f;
41 if (!fbo)
43 f = 0;
45 else
47 if (!*fbo)
49 gl_info->fbo_ops.glGenFramebuffers(1, fbo);
50 checkGLcall("glGenFramebuffers()");
51 TRACE("Created FBO %u.\n", *fbo);
53 f = *fbo;
56 switch (target)
58 case GL_READ_FRAMEBUFFER:
59 if (context->fbo_read_binding == f) return;
60 context->fbo_read_binding = f;
61 break;
63 case GL_DRAW_FRAMEBUFFER:
64 if (context->fbo_draw_binding == f) return;
65 context->fbo_draw_binding = f;
66 break;
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;
75 default:
76 FIXME("Unhandled target %#x.\n", target);
77 break;
80 gl_info->fbo_ops.glBindFramebuffer(target, f);
81 checkGLcall("glBindFramebuffer()");
84 /* GL locking is done by the caller */
85 static void context_clean_fbo_attachments(const struct wined3d_gl_info *gl_info, GLenum target)
87 unsigned int i;
89 for (i = 0; i < gl_info->limits.buffers; ++i)
91 gl_info->fbo_ops.glFramebufferTexture2D(target, GL_COLOR_ATTACHMENT0 + i, GL_TEXTURE_2D, 0, 0);
92 checkGLcall("glFramebufferTexture2D()");
94 gl_info->fbo_ops.glFramebufferTexture2D(target, GL_DEPTH_ATTACHMENT, GL_TEXTURE_2D, 0, 0);
95 checkGLcall("glFramebufferTexture2D()");
97 gl_info->fbo_ops.glFramebufferTexture2D(target, GL_STENCIL_ATTACHMENT, GL_TEXTURE_2D, 0, 0);
98 checkGLcall("glFramebufferTexture2D()");
101 /* GL locking is done by the caller */
102 static void context_destroy_fbo(struct wined3d_context *context, GLuint *fbo)
104 const struct wined3d_gl_info *gl_info = context->gl_info;
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);
110 gl_info->fbo_ops.glDeleteFramebuffers(1, fbo);
111 checkGLcall("glDeleteFramebuffers()");
114 /* GL locking is done by the caller */
115 static void context_apply_attachment_filter_states(IWineD3DSurfaceImpl *surface, DWORD location)
117 /* Update base texture states array */
118 if (surface->container.type == WINED3D_CONTAINER_TEXTURE)
120 IWineD3DBaseTextureImpl *texture_impl = surface->container.u.texture;
121 IWineD3DDeviceImpl *device = surface->resource.device;
122 BOOL update_minfilter = FALSE;
123 BOOL update_magfilter = FALSE;
124 struct gl_texture *gl_tex;
126 switch (location)
128 case SFLAG_INTEXTURE:
129 gl_tex = &texture_impl->baseTexture.texture_rgb;
130 break;
132 case SFLAG_INSRGBTEX:
133 gl_tex = &texture_impl->baseTexture.texture_srgb;
134 break;
136 default:
137 ERR("Unsupported location %s (%#x).\n", debug_surflocation(location), location);
138 IWineD3DBaseTexture_Release((IWineD3DBaseTexture *)texture_impl);
139 return;
142 if (gl_tex->states[WINED3DTEXSTA_MINFILTER] != WINED3DTEXF_POINT
143 || gl_tex->states[WINED3DTEXSTA_MIPFILTER] != WINED3DTEXF_NONE)
145 gl_tex->states[WINED3DTEXSTA_MINFILTER] = WINED3DTEXF_POINT;
146 gl_tex->states[WINED3DTEXSTA_MIPFILTER] = WINED3DTEXF_NONE;
147 update_minfilter = TRUE;
150 if (gl_tex->states[WINED3DTEXSTA_MAGFILTER] != WINED3DTEXF_POINT)
152 gl_tex->states[WINED3DTEXSTA_MAGFILTER] = WINED3DTEXF_POINT;
153 update_magfilter = TRUE;
156 if (texture_impl->baseTexture.bindCount)
158 WARN("Render targets should not be bound to a sampler\n");
159 IWineD3DDeviceImpl_MarkStateDirty(device, STATE_SAMPLER(texture_impl->baseTexture.sampler));
162 if (update_minfilter || update_magfilter)
164 GLenum target, bind_target;
165 GLint old_binding;
167 target = surface->texture_target;
168 if (target == GL_TEXTURE_2D)
170 bind_target = GL_TEXTURE_2D;
171 glGetIntegerv(GL_TEXTURE_BINDING_2D, &old_binding);
173 else if (target == GL_TEXTURE_RECTANGLE_ARB)
175 bind_target = GL_TEXTURE_RECTANGLE_ARB;
176 glGetIntegerv(GL_TEXTURE_BINDING_RECTANGLE_ARB, &old_binding);
178 else
180 bind_target = GL_TEXTURE_CUBE_MAP_ARB;
181 glGetIntegerv(GL_TEXTURE_BINDING_CUBE_MAP_ARB, &old_binding);
184 glBindTexture(bind_target, gl_tex->name);
185 if (update_minfilter) glTexParameteri(bind_target, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
186 if (update_magfilter) glTexParameteri(bind_target, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
187 glBindTexture(bind_target, old_binding);
190 checkGLcall("apply_attachment_filter_states()");
194 /* GL locking is done by the caller */
195 void context_attach_depth_stencil_fbo(struct wined3d_context *context,
196 GLenum fbo_target, IWineD3DSurfaceImpl *depth_stencil, BOOL use_render_buffer)
198 const struct wined3d_gl_info *gl_info = context->gl_info;
200 TRACE("Attach depth stencil %p\n", depth_stencil);
202 if (depth_stencil)
204 DWORD format_flags = depth_stencil->resource.format_desc->Flags;
206 if (use_render_buffer && depth_stencil->current_renderbuffer)
208 if (format_flags & WINED3DFMT_FLAG_DEPTH)
210 gl_info->fbo_ops.glFramebufferRenderbuffer(fbo_target, GL_DEPTH_ATTACHMENT,
211 GL_RENDERBUFFER, depth_stencil->current_renderbuffer->id);
212 checkGLcall("glFramebufferRenderbuffer()");
215 if (format_flags & WINED3DFMT_FLAG_STENCIL)
217 gl_info->fbo_ops.glFramebufferRenderbuffer(fbo_target, GL_STENCIL_ATTACHMENT,
218 GL_RENDERBUFFER, depth_stencil->current_renderbuffer->id);
219 checkGLcall("glFramebufferRenderbuffer()");
222 else
224 surface_prepare_texture(depth_stencil, gl_info, FALSE);
225 context_apply_attachment_filter_states(depth_stencil, SFLAG_INTEXTURE);
227 if (format_flags & WINED3DFMT_FLAG_DEPTH)
229 gl_info->fbo_ops.glFramebufferTexture2D(fbo_target, GL_DEPTH_ATTACHMENT,
230 depth_stencil->texture_target, depth_stencil->texture_name,
231 depth_stencil->texture_level);
232 checkGLcall("glFramebufferTexture2D()");
235 if (format_flags & WINED3DFMT_FLAG_STENCIL)
237 gl_info->fbo_ops.glFramebufferTexture2D(fbo_target, GL_STENCIL_ATTACHMENT,
238 depth_stencil->texture_target, depth_stencil->texture_name,
239 depth_stencil->texture_level);
240 checkGLcall("glFramebufferTexture2D()");
244 if (!(format_flags & WINED3DFMT_FLAG_DEPTH))
246 gl_info->fbo_ops.glFramebufferTexture2D(fbo_target, GL_DEPTH_ATTACHMENT, GL_TEXTURE_2D, 0, 0);
247 checkGLcall("glFramebufferTexture2D()");
250 if (!(format_flags & WINED3DFMT_FLAG_STENCIL))
252 gl_info->fbo_ops.glFramebufferTexture2D(fbo_target, GL_STENCIL_ATTACHMENT, GL_TEXTURE_2D, 0, 0);
253 checkGLcall("glFramebufferTexture2D()");
256 else
258 gl_info->fbo_ops.glFramebufferTexture2D(fbo_target, GL_DEPTH_ATTACHMENT, GL_TEXTURE_2D, 0, 0);
259 checkGLcall("glFramebufferTexture2D()");
261 gl_info->fbo_ops.glFramebufferTexture2D(fbo_target, GL_STENCIL_ATTACHMENT, GL_TEXTURE_2D, 0, 0);
262 checkGLcall("glFramebufferTexture2D()");
266 /* GL locking is done by the caller */
267 static void context_attach_surface_fbo(const struct wined3d_context *context,
268 GLenum fbo_target, DWORD idx, IWineD3DSurfaceImpl *surface, DWORD location)
270 const struct wined3d_gl_info *gl_info = context->gl_info;
272 TRACE("Attach surface %p to %u\n", surface, idx);
274 if (surface)
276 switch (location)
278 case SFLAG_INTEXTURE:
279 surface_prepare_texture(surface, gl_info, FALSE);
280 context_apply_attachment_filter_states(surface, location);
281 gl_info->fbo_ops.glFramebufferTexture2D(fbo_target, GL_COLOR_ATTACHMENT0 + idx,
282 surface->texture_target, surface->texture_name, surface->texture_level);
283 break;
285 case SFLAG_INSRGBTEX:
286 surface_prepare_texture(surface, gl_info, TRUE);
287 context_apply_attachment_filter_states(surface, location);
288 gl_info->fbo_ops.glFramebufferTexture2D(fbo_target, GL_COLOR_ATTACHMENT0 + idx,
289 surface->texture_target, surface->texture_name_srgb, surface->texture_level);
290 break;
292 default:
293 ERR("Unsupported location %s (%#x).\n", debug_surflocation(location), location);
294 break;
296 checkGLcall("glFramebufferTexture2D()");
298 else
300 gl_info->fbo_ops.glFramebufferTexture2D(fbo_target, GL_COLOR_ATTACHMENT0 + idx, GL_TEXTURE_2D, 0, 0);
301 checkGLcall("glFramebufferTexture2D()");
305 /* GL locking is done by the caller */
306 static void context_check_fbo_status(struct wined3d_context *context, GLenum target)
308 const struct wined3d_gl_info *gl_info = context->gl_info;
309 GLenum status;
311 status = gl_info->fbo_ops.glCheckFramebufferStatus(target);
312 if (status == GL_FRAMEBUFFER_COMPLETE)
314 TRACE("FBO complete\n");
315 } else {
316 IWineD3DSurfaceImpl *attachment;
317 unsigned int i;
318 FIXME("FBO status %s (%#x)\n", debug_fbostatus(status), status);
320 if (!context->current_fbo)
322 ERR("FBO 0 is incomplete, driver bug?\n");
323 return;
326 FIXME("\tLocation %s (%#x).\n", debug_surflocation(context->current_fbo->location),
327 context->current_fbo->location);
329 /* Dump the FBO attachments */
330 for (i = 0; i < gl_info->limits.buffers; ++i)
332 attachment = context->current_fbo->render_targets[i];
333 if (attachment)
335 FIXME("\tColor attachment %d: (%p) %s %ux%u\n",
336 i, attachment, debug_d3dformat(attachment->resource.format_desc->format),
337 attachment->pow2Width, attachment->pow2Height);
340 attachment = context->current_fbo->depth_stencil;
341 if (attachment)
343 FIXME("\tDepth attachment: (%p) %s %ux%u\n",
344 attachment, debug_d3dformat(attachment->resource.format_desc->format),
345 attachment->pow2Width, attachment->pow2Height);
350 static struct fbo_entry *context_create_fbo_entry(struct wined3d_context *context,
351 IWineD3DSurfaceImpl **render_targets, IWineD3DSurfaceImpl *depth_stencil, DWORD location)
353 const struct wined3d_gl_info *gl_info = context->gl_info;
354 struct fbo_entry *entry;
356 entry = HeapAlloc(GetProcessHeap(), 0, sizeof(*entry));
357 entry->render_targets = HeapAlloc(GetProcessHeap(), 0, gl_info->limits.buffers * sizeof(*entry->render_targets));
358 memcpy(entry->render_targets, render_targets, gl_info->limits.buffers * sizeof(*entry->render_targets));
359 entry->depth_stencil = depth_stencil;
360 entry->location = location;
361 entry->attached = FALSE;
362 entry->id = 0;
364 return entry;
367 /* GL locking is done by the caller */
368 static void context_reuse_fbo_entry(struct wined3d_context *context, GLenum target,
369 IWineD3DSurfaceImpl **render_targets, IWineD3DSurfaceImpl *depth_stencil,
370 DWORD location, struct fbo_entry *entry)
372 const struct wined3d_gl_info *gl_info = context->gl_info;
374 context_bind_fbo(context, target, &entry->id);
375 context_clean_fbo_attachments(gl_info, target);
377 memcpy(entry->render_targets, render_targets, gl_info->limits.buffers * sizeof(*entry->render_targets));
378 entry->depth_stencil = depth_stencil;
379 entry->location = location;
380 entry->attached = FALSE;
383 /* GL locking is done by the caller */
384 static void context_destroy_fbo_entry(struct wined3d_context *context, struct fbo_entry *entry)
386 if (entry->id)
388 TRACE("Destroy FBO %d\n", entry->id);
389 context_destroy_fbo(context, &entry->id);
391 --context->fbo_entry_count;
392 list_remove(&entry->entry);
393 HeapFree(GetProcessHeap(), 0, entry->render_targets);
394 HeapFree(GetProcessHeap(), 0, entry);
398 /* GL locking is done by the caller */
399 static struct fbo_entry *context_find_fbo_entry(struct wined3d_context *context, GLenum target,
400 IWineD3DSurfaceImpl **render_targets, IWineD3DSurfaceImpl *depth_stencil, DWORD location)
402 const struct wined3d_gl_info *gl_info = context->gl_info;
403 struct fbo_entry *entry;
405 LIST_FOR_EACH_ENTRY(entry, &context->fbo_list, struct fbo_entry, entry)
407 if (!memcmp(entry->render_targets,
408 render_targets, gl_info->limits.buffers * sizeof(*entry->render_targets))
409 && entry->depth_stencil == depth_stencil && entry->location == location)
411 list_remove(&entry->entry);
412 list_add_head(&context->fbo_list, &entry->entry);
413 return entry;
417 if (context->fbo_entry_count < WINED3D_MAX_FBO_ENTRIES)
419 entry = context_create_fbo_entry(context, render_targets, depth_stencil, location);
420 list_add_head(&context->fbo_list, &entry->entry);
421 ++context->fbo_entry_count;
423 else
425 entry = LIST_ENTRY(list_tail(&context->fbo_list), struct fbo_entry, entry);
426 context_reuse_fbo_entry(context, target, render_targets, depth_stencil, location, entry);
427 list_remove(&entry->entry);
428 list_add_head(&context->fbo_list, &entry->entry);
431 return entry;
434 /* GL locking is done by the caller */
435 static void context_apply_fbo_entry(struct wined3d_context *context, GLenum target, struct fbo_entry *entry)
437 const struct wined3d_gl_info *gl_info = context->gl_info;
438 unsigned int i;
440 context_bind_fbo(context, target, &entry->id);
442 if (!entry->attached)
444 /* Apply render targets */
445 for (i = 0; i < gl_info->limits.buffers; ++i)
447 context_attach_surface_fbo(context, target, i, entry->render_targets[i], entry->location);
450 /* Apply depth targets */
451 if (entry->depth_stencil)
453 surface_set_compatible_renderbuffer(entry->depth_stencil,
454 entry->render_targets[0]->pow2Width, entry->render_targets[0]->pow2Height);
456 context_attach_depth_stencil_fbo(context, target, entry->depth_stencil, TRUE);
458 entry->attached = TRUE;
460 else
462 for (i = 0; i < gl_info->limits.buffers; ++i)
464 if (entry->render_targets[i])
465 context_apply_attachment_filter_states(entry->render_targets[i], entry->location);
467 if (entry->depth_stencil)
468 context_apply_attachment_filter_states(entry->depth_stencil, SFLAG_INTEXTURE);
472 /* GL locking is done by the caller */
473 static void context_apply_fbo_state(struct wined3d_context *context, GLenum target,
474 IWineD3DSurfaceImpl **render_targets, IWineD3DSurfaceImpl *depth_stencil, DWORD location)
476 struct fbo_entry *entry, *entry2;
478 LIST_FOR_EACH_ENTRY_SAFE(entry, entry2, &context->fbo_destroy_list, struct fbo_entry, entry)
480 context_destroy_fbo_entry(context, entry);
483 if (context->rebind_fbo)
485 context_bind_fbo(context, GL_FRAMEBUFFER, NULL);
486 context->rebind_fbo = FALSE;
489 if (render_targets)
491 context->current_fbo = context_find_fbo_entry(context, target, render_targets, depth_stencil, location);
492 context_apply_fbo_entry(context, target, context->current_fbo);
494 else
496 context->current_fbo = NULL;
497 context_bind_fbo(context, target, NULL);
500 context_check_fbo_status(context, target);
503 /* GL locking is done by the caller */
504 void context_apply_fbo_state_blit(struct wined3d_context *context, GLenum target,
505 IWineD3DSurfaceImpl *render_target, IWineD3DSurfaceImpl *depth_stencil, DWORD location)
507 if (surface_is_offscreen(render_target))
509 UINT clear_size = (context->gl_info->limits.buffers - 1) * sizeof(*context->blit_targets);
510 context->blit_targets[0] = render_target;
511 if (clear_size) memset(&context->blit_targets[1], 0, clear_size);
512 context_apply_fbo_state(context, target, context->blit_targets, depth_stencil, location);
514 else
516 context_apply_fbo_state(context, target, NULL, NULL, location);
520 /* Context activation is done by the caller. */
521 void context_alloc_occlusion_query(struct wined3d_context *context, struct wined3d_occlusion_query *query)
523 const struct wined3d_gl_info *gl_info = context->gl_info;
525 if (context->free_occlusion_query_count)
527 query->id = context->free_occlusion_queries[--context->free_occlusion_query_count];
529 else
531 if (gl_info->supported[ARB_OCCLUSION_QUERY])
533 ENTER_GL();
534 GL_EXTCALL(glGenQueriesARB(1, &query->id));
535 checkGLcall("glGenQueriesARB");
536 LEAVE_GL();
538 TRACE("Allocated occlusion query %u in context %p.\n", query->id, context);
540 else
542 WARN("Occlusion queries not supported, not allocating query id.\n");
543 query->id = 0;
547 query->context = context;
548 list_add_head(&context->occlusion_queries, &query->entry);
551 void context_free_occlusion_query(struct wined3d_occlusion_query *query)
553 struct wined3d_context *context = query->context;
555 list_remove(&query->entry);
556 query->context = NULL;
558 if (context->free_occlusion_query_count >= context->free_occlusion_query_size - 1)
560 UINT new_size = context->free_occlusion_query_size << 1;
561 GLuint *new_data = HeapReAlloc(GetProcessHeap(), 0, context->free_occlusion_queries,
562 new_size * sizeof(*context->free_occlusion_queries));
564 if (!new_data)
566 ERR("Failed to grow free list, leaking query %u in context %p.\n", query->id, context);
567 return;
570 context->free_occlusion_query_size = new_size;
571 context->free_occlusion_queries = new_data;
574 context->free_occlusion_queries[context->free_occlusion_query_count++] = query->id;
577 /* Context activation is done by the caller. */
578 void context_alloc_event_query(struct wined3d_context *context, struct wined3d_event_query *query)
580 const struct wined3d_gl_info *gl_info = context->gl_info;
582 if (context->free_event_query_count)
584 query->object = context->free_event_queries[--context->free_event_query_count];
586 else
588 if (gl_info->supported[ARB_SYNC])
590 /* Using ARB_sync, not much to do here. */
591 query->object.sync = NULL;
592 TRACE("Allocated event query %p in context %p.\n", query->object.sync, context);
594 else if (gl_info->supported[APPLE_FENCE])
596 ENTER_GL();
597 GL_EXTCALL(glGenFencesAPPLE(1, &query->object.id));
598 checkGLcall("glGenFencesAPPLE");
599 LEAVE_GL();
601 TRACE("Allocated event query %u in context %p.\n", query->object.id, context);
603 else if(gl_info->supported[NV_FENCE])
605 ENTER_GL();
606 GL_EXTCALL(glGenFencesNV(1, &query->object.id));
607 checkGLcall("glGenFencesNV");
608 LEAVE_GL();
610 TRACE("Allocated event query %u in context %p.\n", query->object.id, context);
612 else
614 WARN("Event queries not supported, not allocating query id.\n");
615 query->object.id = 0;
619 query->context = context;
620 list_add_head(&context->event_queries, &query->entry);
623 void context_free_event_query(struct wined3d_event_query *query)
625 struct wined3d_context *context = query->context;
627 list_remove(&query->entry);
628 query->context = NULL;
630 if (context->free_event_query_count >= context->free_event_query_size - 1)
632 UINT new_size = context->free_event_query_size << 1;
633 union wined3d_gl_query_object *new_data = HeapReAlloc(GetProcessHeap(), 0, context->free_event_queries,
634 new_size * sizeof(*context->free_event_queries));
636 if (!new_data)
638 ERR("Failed to grow free list, leaking query %u in context %p.\n", query->object.id, context);
639 return;
642 context->free_event_query_size = new_size;
643 context->free_event_queries = new_data;
646 context->free_event_queries[context->free_event_query_count++] = query->object;
649 typedef void (context_fbo_entry_func_t)(struct wined3d_context *context, struct fbo_entry *entry);
651 static void context_enum_surface_fbo_entries(IWineD3DDeviceImpl *device,
652 IWineD3DSurfaceImpl *surface, context_fbo_entry_func_t *callback)
654 UINT i;
656 for (i = 0; i < device->numContexts; ++i)
658 struct wined3d_context *context = device->contexts[i];
659 const struct wined3d_gl_info *gl_info = context->gl_info;
660 struct fbo_entry *entry, *entry2;
662 if (context->current_rt == surface) context->current_rt = NULL;
664 LIST_FOR_EACH_ENTRY_SAFE(entry, entry2, &context->fbo_list, struct fbo_entry, entry)
666 UINT j;
668 if (entry->depth_stencil == surface)
670 callback(context, entry);
671 continue;
674 for (j = 0; j < gl_info->limits.buffers; ++j)
676 if (entry->render_targets[j] == surface)
678 callback(context, entry);
679 break;
686 static void context_queue_fbo_entry_destruction(struct wined3d_context *context, struct fbo_entry *entry)
688 list_remove(&entry->entry);
689 list_add_head(&context->fbo_destroy_list, &entry->entry);
692 void context_resource_released(IWineD3DDeviceImpl *device, IWineD3DResource *resource, WINED3DRESOURCETYPE type)
694 if (!device->d3d_initialized) return;
696 switch (type)
698 case WINED3DRTYPE_SURFACE:
699 context_enum_surface_fbo_entries(device, (IWineD3DSurfaceImpl *)resource,
700 context_queue_fbo_entry_destruction);
701 break;
703 default:
704 break;
708 static void context_detach_fbo_entry(struct wined3d_context *context, struct fbo_entry *entry)
710 entry->attached = FALSE;
713 void context_resource_unloaded(IWineD3DDeviceImpl *device, IWineD3DResource *resource, WINED3DRESOURCETYPE type)
715 switch (type)
717 case WINED3DRTYPE_SURFACE:
718 context_enum_surface_fbo_entries(device, (IWineD3DSurfaceImpl *)resource,
719 context_detach_fbo_entry);
720 break;
722 default:
723 break;
727 void context_surface_update(struct wined3d_context *context, IWineD3DSurfaceImpl *surface)
729 const struct wined3d_gl_info *gl_info = context->gl_info;
730 struct fbo_entry *entry = context->current_fbo;
731 unsigned int i;
733 if (!entry || context->rebind_fbo) return;
735 for (i = 0; i < gl_info->limits.buffers; ++i)
737 if (surface == entry->render_targets[i])
739 TRACE("Updated surface %p is bound as color attachment %u to the current FBO.\n", surface, i);
740 context->rebind_fbo = TRUE;
741 return;
745 if (surface == entry->depth_stencil)
747 TRACE("Updated surface %p is bound as depth attachment to the current FBO.\n", surface);
748 context->rebind_fbo = TRUE;
752 static BOOL context_set_pixel_format(const struct wined3d_gl_info *gl_info, HDC dc, int format)
754 int current = GetPixelFormat(dc);
756 if (current == format) return TRUE;
758 if (!current)
760 if (!SetPixelFormat(dc, format, NULL))
762 ERR("Failed to set pixel format %d on device context %p, last error %#x.\n",
763 format, dc, GetLastError());
764 return FALSE;
766 return TRUE;
769 /* By default WGL doesn't allow pixel format adjustments but we need it
770 * here. For this reason there's a Wine specific wglSetPixelFormat()
771 * which allows us to set the pixel format multiple times. Only use it
772 * when really needed. */
773 if (gl_info->supported[WGL_WINE_PIXEL_FORMAT_PASSTHROUGH])
775 if (!GL_EXTCALL(wglSetPixelFormatWINE(dc, format, NULL)))
777 ERR("wglSetPixelFormatWINE failed to set pixel format %d on device context %p.\n",
778 format, dc);
779 return FALSE;
781 return TRUE;
784 /* OpenGL doesn't allow pixel format adjustments. Print an error and
785 * continue using the old format. There's a big chance that the old
786 * format works although with a performance hit and perhaps rendering
787 * errors. */
788 ERR("Unable to set pixel format %d on device context %p. Already using format %d.\n",
789 format, dc, current);
790 return TRUE;
793 static void context_update_window(struct wined3d_context *context)
795 TRACE("Updating context %p window from %p to %p.\n",
796 context, context->win_handle, context->swapchain->win_handle);
798 if (context->valid)
800 if (!ReleaseDC(context->win_handle, context->hdc))
802 ERR("Failed to release device context %p, last error %#x.\n",
803 context->hdc, GetLastError());
806 else context->valid = 1;
808 context->win_handle = context->swapchain->win_handle;
810 if (!(context->hdc = GetDC(context->win_handle)))
812 ERR("Failed to get a device context for window %p.\n", context->win_handle);
813 goto err;
816 if (!context_set_pixel_format(context->gl_info, context->hdc, context->pixel_format))
818 ERR("Failed to set pixel format %d on device context %p.\n",
819 context->pixel_format, context->hdc);
820 goto err;
823 if (!pwglMakeCurrent(context->hdc, context->glCtx))
825 ERR("Failed to make GL context %p current on device context %p, last error %#x.\n",
826 context->glCtx, context->hdc, GetLastError());
827 goto err;
830 return;
832 err:
833 context->valid = 0;
836 static void context_validate(struct wined3d_context *context)
838 HWND wnd = WindowFromDC(context->hdc);
840 if (wnd != context->win_handle)
842 WARN("DC %p belongs to window %p instead of %p.\n",
843 context->hdc, wnd, context->win_handle);
844 context->valid = 0;
847 if (context->win_handle != context->swapchain->win_handle)
848 context_update_window(context);
851 static void context_destroy_gl_resources(struct wined3d_context *context)
853 const struct wined3d_gl_info *gl_info = context->gl_info;
854 struct wined3d_occlusion_query *occlusion_query;
855 struct wined3d_event_query *event_query;
856 struct fbo_entry *entry, *entry2;
857 HGLRC restore_ctx;
858 HDC restore_dc;
859 unsigned int i;
861 restore_ctx = pwglGetCurrentContext();
862 restore_dc = pwglGetCurrentDC();
864 context_validate(context);
865 if (context->valid && restore_ctx != context->glCtx) pwglMakeCurrent(context->hdc, context->glCtx);
866 else restore_ctx = NULL;
868 ENTER_GL();
870 LIST_FOR_EACH_ENTRY(occlusion_query, &context->occlusion_queries, struct wined3d_occlusion_query, entry)
872 if (context->valid && gl_info->supported[ARB_OCCLUSION_QUERY])
873 GL_EXTCALL(glDeleteQueriesARB(1, &occlusion_query->id));
874 occlusion_query->context = NULL;
877 LIST_FOR_EACH_ENTRY(event_query, &context->event_queries, struct wined3d_event_query, entry)
879 if (context->valid)
881 if (gl_info->supported[ARB_SYNC])
883 if (event_query->object.sync) GL_EXTCALL(glDeleteSync(event_query->object.sync));
885 else if (gl_info->supported[APPLE_FENCE]) GL_EXTCALL(glDeleteFencesAPPLE(1, &event_query->object.id));
886 else if (gl_info->supported[NV_FENCE]) GL_EXTCALL(glDeleteFencesNV(1, &event_query->object.id));
888 event_query->context = NULL;
891 LIST_FOR_EACH_ENTRY_SAFE(entry, entry2, &context->fbo_destroy_list, struct fbo_entry, entry)
893 if (!context->valid) entry->id = 0;
894 context_destroy_fbo_entry(context, entry);
897 LIST_FOR_EACH_ENTRY_SAFE(entry, entry2, &context->fbo_list, struct fbo_entry, entry)
899 if (!context->valid) entry->id = 0;
900 context_destroy_fbo_entry(context, entry);
903 if (context->valid)
905 if (context->dst_fbo)
907 TRACE("Destroy dst FBO %d\n", context->dst_fbo);
908 context_destroy_fbo(context, &context->dst_fbo);
910 if (context->dummy_arbfp_prog)
912 GL_EXTCALL(glDeleteProgramsARB(1, &context->dummy_arbfp_prog));
915 if (gl_info->supported[ARB_OCCLUSION_QUERY])
916 GL_EXTCALL(glDeleteQueriesARB(context->free_occlusion_query_count, context->free_occlusion_queries));
918 if (gl_info->supported[ARB_SYNC])
920 if (event_query->object.sync) GL_EXTCALL(glDeleteSync(event_query->object.sync));
922 else if (gl_info->supported[APPLE_FENCE])
924 for (i = 0; i < context->free_event_query_count; ++i)
926 GL_EXTCALL(glDeleteFencesAPPLE(1, &context->free_event_queries[i].id));
929 else if (gl_info->supported[NV_FENCE])
931 for (i = 0; i < context->free_event_query_count; ++i)
933 GL_EXTCALL(glDeleteFencesNV(1, &context->free_event_queries[i].id));
937 checkGLcall("context cleanup");
940 LEAVE_GL();
942 HeapFree(GetProcessHeap(), 0, context->free_occlusion_queries);
943 HeapFree(GetProcessHeap(), 0, context->free_event_queries);
945 if (restore_ctx)
947 if (!pwglMakeCurrent(restore_dc, restore_ctx))
949 DWORD err = GetLastError();
950 ERR("Failed to restore GL context %p on device context %p, last error %#x.\n",
951 restore_ctx, restore_dc, err);
954 else if (pwglGetCurrentContext() && !pwglMakeCurrent(NULL, NULL))
956 ERR("Failed to disable GL context.\n");
959 ReleaseDC(context->win_handle, context->hdc);
961 if (!pwglDeleteContext(context->glCtx))
963 DWORD err = GetLastError();
964 ERR("wglDeleteContext(%p) failed, last error %#x.\n", context->glCtx, err);
968 DWORD context_get_tls_idx(void)
970 return wined3d_context_tls_idx;
973 void context_set_tls_idx(DWORD idx)
975 wined3d_context_tls_idx = idx;
978 struct wined3d_context *context_get_current(void)
980 return TlsGetValue(wined3d_context_tls_idx);
983 BOOL context_set_current(struct wined3d_context *ctx)
985 struct wined3d_context *old = context_get_current();
987 if (old == ctx)
989 TRACE("Already using D3D context %p.\n", ctx);
990 return TRUE;
993 if (old)
995 if (old->destroyed)
997 TRACE("Switching away from destroyed context %p.\n", old);
998 context_destroy_gl_resources(old);
999 HeapFree(GetProcessHeap(), 0, old);
1001 else
1003 old->current = 0;
1007 if (ctx)
1009 TRACE("Switching to D3D context %p, GL context %p, device context %p.\n", ctx, ctx->glCtx, ctx->hdc);
1010 if (!pwglMakeCurrent(ctx->hdc, ctx->glCtx))
1012 DWORD err = GetLastError();
1013 ERR("Failed to make GL context %p current on device context %p, last error %#x.\n",
1014 ctx->glCtx, ctx->hdc, err);
1015 TlsSetValue(wined3d_context_tls_idx, NULL);
1016 return FALSE;
1018 ctx->current = 1;
1020 else if(pwglGetCurrentContext())
1022 TRACE("Clearing current D3D context.\n");
1023 if (!pwglMakeCurrent(NULL, NULL))
1025 DWORD err = GetLastError();
1026 ERR("Failed to clear current GL context, last error %#x.\n", err);
1027 TlsSetValue(wined3d_context_tls_idx, NULL);
1028 return FALSE;
1032 return TlsSetValue(wined3d_context_tls_idx, ctx);
1035 void context_release(struct wined3d_context *context)
1037 TRACE("Releasing context %p, level %u.\n", context, context->level);
1039 if (WARN_ON(d3d))
1041 if (!context->level)
1042 WARN("Context %p is not active.\n", context);
1043 else if (context != context_get_current())
1044 WARN("Context %p is not the current context.\n", context);
1047 if (!--context->level && context->restore_ctx)
1049 TRACE("Restoring GL context %p on device context %p.\n", context->restore_ctx, context->restore_dc);
1050 if (!pwglMakeCurrent(context->restore_dc, context->restore_ctx))
1052 DWORD err = GetLastError();
1053 ERR("Failed to restore GL context %p on device context %p, last error %#x.\n",
1054 context->restore_ctx, context->restore_dc, err);
1056 context->restore_ctx = NULL;
1057 context->restore_dc = NULL;
1061 static void context_enter(struct wined3d_context *context)
1063 TRACE("Entering context %p, level %u.\n", context, context->level + 1);
1065 if (!context->level++)
1067 const struct wined3d_context *current_context = context_get_current();
1068 HGLRC current_gl = pwglGetCurrentContext();
1070 if (current_gl && (!current_context || current_context->glCtx != current_gl))
1072 TRACE("Another GL context (%p on device context %p) is already current.\n",
1073 current_gl, pwglGetCurrentDC());
1074 context->restore_ctx = current_gl;
1075 context->restore_dc = pwglGetCurrentDC();
1080 /*****************************************************************************
1081 * Context_MarkStateDirty
1083 * Marks a state in a context dirty. Only one context, opposed to
1084 * IWineD3DDeviceImpl_MarkStateDirty, which marks the state dirty in all
1085 * contexts
1087 * Params:
1088 * context: Context to mark the state dirty in
1089 * state: State to mark dirty
1090 * StateTable: Pointer to the state table in use(for state grouping)
1092 *****************************************************************************/
1093 static void Context_MarkStateDirty(struct wined3d_context *context, DWORD state, const struct StateEntry *StateTable)
1095 DWORD rep = StateTable[state].representative;
1096 DWORD idx;
1097 BYTE shift;
1099 if (isStateDirty(context, rep)) return;
1101 context->dirtyArray[context->numDirtyEntries++] = rep;
1102 idx = rep / (sizeof(*context->isStateDirty) * CHAR_BIT);
1103 shift = rep & ((sizeof(*context->isStateDirty) * CHAR_BIT) - 1);
1104 context->isStateDirty[idx] |= (1 << shift);
1107 /* This function takes care of WineD3D pixel format selection. */
1108 static int WineD3D_ChoosePixelFormat(IWineD3DDeviceImpl *This, HDC hdc,
1109 const struct wined3d_format_desc *color_format_desc, const struct wined3d_format_desc *ds_format_desc,
1110 BOOL auxBuffers, int numSamples, BOOL findCompatible)
1112 int iPixelFormat=0;
1113 unsigned int matchtry;
1114 short redBits, greenBits, blueBits, alphaBits, colorBits;
1115 short depthBits=0, stencilBits=0;
1117 struct match_type {
1118 BOOL require_aux;
1119 BOOL exact_alpha;
1120 BOOL exact_color;
1121 } matches[] = {
1122 /* First, try without alpha match buffers. MacOS supports aux buffers only
1123 * on A8R8G8B8, and we prefer better offscreen rendering over an alpha match.
1124 * Then try without aux buffers - this is the most common cause for not
1125 * finding a pixel format. Also some drivers(the open source ones)
1126 * only offer 32 bit ARB pixel formats. First try without an exact alpha
1127 * match, then try without an exact alpha and color match.
1129 { TRUE, TRUE, TRUE },
1130 { TRUE, FALSE, TRUE },
1131 { FALSE, TRUE, TRUE },
1132 { FALSE, FALSE, TRUE },
1133 { TRUE, FALSE, FALSE },
1134 { FALSE, FALSE, FALSE },
1137 int i = 0;
1138 int nCfgs = This->adapter->nCfgs;
1140 TRACE("ColorFormat=%s, DepthStencilFormat=%s, auxBuffers=%d, numSamples=%d, findCompatible=%d\n",
1141 debug_d3dformat(color_format_desc->format), debug_d3dformat(ds_format_desc->format),
1142 auxBuffers, numSamples, findCompatible);
1144 if (!getColorBits(color_format_desc, &redBits, &greenBits, &blueBits, &alphaBits, &colorBits))
1146 ERR("Unable to get color bits for format %s (%#x)!\n",
1147 debug_d3dformat(color_format_desc->format), color_format_desc->format);
1148 return 0;
1151 getDepthStencilBits(ds_format_desc, &depthBits, &stencilBits);
1153 for(matchtry = 0; matchtry < (sizeof(matches) / sizeof(matches[0])) && !iPixelFormat; matchtry++) {
1154 for(i=0; i<nCfgs; i++) {
1155 BOOL exactDepthMatch = TRUE;
1156 WineD3D_PixelFormat *cfg = &This->adapter->cfgs[i];
1158 /* For now only accept RGBA formats. Perhaps some day we will
1159 * allow floating point formats for pbuffers. */
1160 if(cfg->iPixelType != WGL_TYPE_RGBA_ARB)
1161 continue;
1163 /* In window mode we need a window drawable format and double buffering. */
1164 if(!(cfg->windowDrawable && cfg->doubleBuffer))
1165 continue;
1167 /* We like to have aux buffers in backbuffer mode */
1168 if(auxBuffers && !cfg->auxBuffers && matches[matchtry].require_aux)
1169 continue;
1171 if(matches[matchtry].exact_color) {
1172 if(cfg->redSize != redBits)
1173 continue;
1174 if(cfg->greenSize != greenBits)
1175 continue;
1176 if(cfg->blueSize != blueBits)
1177 continue;
1178 } else {
1179 if(cfg->redSize < redBits)
1180 continue;
1181 if(cfg->greenSize < greenBits)
1182 continue;
1183 if(cfg->blueSize < blueBits)
1184 continue;
1186 if(matches[matchtry].exact_alpha) {
1187 if(cfg->alphaSize != alphaBits)
1188 continue;
1189 } else {
1190 if(cfg->alphaSize < alphaBits)
1191 continue;
1194 /* We try to locate a format which matches our requirements exactly. In case of
1195 * depth it is no problem to emulate 16-bit using e.g. 24-bit, so accept that. */
1196 if(cfg->depthSize < depthBits)
1197 continue;
1198 else if(cfg->depthSize > depthBits)
1199 exactDepthMatch = FALSE;
1201 /* In all cases make sure the number of stencil bits matches our requirements
1202 * even when we don't need stencil because it could affect performance EXCEPT
1203 * on cards which don't offer depth formats without stencil like the i915 drivers
1204 * on Linux. */
1205 if(stencilBits != cfg->stencilSize && !(This->adapter->brokenStencil && stencilBits <= cfg->stencilSize))
1206 continue;
1208 /* Check multisampling support */
1209 if(cfg->numSamples != numSamples)
1210 continue;
1212 /* When we have passed all the checks then we have found a format which matches our
1213 * requirements. Note that we only check for a limit number of capabilities right now,
1214 * so there can easily be a dozen of pixel formats which appear to be the 'same' but
1215 * can still differ in things like multisampling, stereo, SRGB and other flags.
1218 /* Exit the loop as we have found a format :) */
1219 if(exactDepthMatch) {
1220 iPixelFormat = cfg->iPixelFormat;
1221 break;
1222 } else if(!iPixelFormat) {
1223 /* In the end we might end up with a format which doesn't exactly match our depth
1224 * requirements. Accept the first format we found because formats with higher iPixelFormat
1225 * values tend to have more extended capabilities (e.g. multisampling) which we don't need. */
1226 iPixelFormat = cfg->iPixelFormat;
1231 /* When findCompatible is set and no suitable format was found, let ChoosePixelFormat choose a pixel format in order not to crash. */
1232 if(!iPixelFormat && !findCompatible) {
1233 ERR("Can't find a suitable iPixelFormat\n");
1234 return FALSE;
1235 } else if(!iPixelFormat) {
1236 PIXELFORMATDESCRIPTOR pfd;
1238 TRACE("Falling back to ChoosePixelFormat as we weren't able to find an exactly matching pixel format\n");
1239 /* PixelFormat selection */
1240 ZeroMemory(&pfd, sizeof(pfd));
1241 pfd.nSize = sizeof(pfd);
1242 pfd.nVersion = 1;
1243 pfd.dwFlags = PFD_SUPPORT_OPENGL | PFD_DOUBLEBUFFER | PFD_DRAW_TO_WINDOW;/*PFD_GENERIC_ACCELERATED*/
1244 pfd.iPixelType = PFD_TYPE_RGBA;
1245 pfd.cAlphaBits = alphaBits;
1246 pfd.cColorBits = colorBits;
1247 pfd.cDepthBits = depthBits;
1248 pfd.cStencilBits = stencilBits;
1249 pfd.iLayerType = PFD_MAIN_PLANE;
1251 iPixelFormat = ChoosePixelFormat(hdc, &pfd);
1252 if(!iPixelFormat) {
1253 /* If this happens something is very wrong as ChoosePixelFormat barely fails */
1254 ERR("Can't find a suitable iPixelFormat\n");
1255 return FALSE;
1259 TRACE("Found iPixelFormat=%d for ColorFormat=%s, DepthStencilFormat=%s\n",
1260 iPixelFormat, debug_d3dformat(color_format_desc->format), debug_d3dformat(ds_format_desc->format));
1261 return iPixelFormat;
1264 /*****************************************************************************
1265 * context_create
1267 * Creates a new context.
1269 * * Params:
1270 * This: Device to activate the context for
1271 * target: Surface this context will render to
1272 * win_handle: handle to the window which we are drawing to
1273 * pPresentParameters: contains the pixelformats to use for onscreen rendering
1275 *****************************************************************************/
1276 struct wined3d_context *context_create(IWineD3DSwapChainImpl *swapchain, IWineD3DSurfaceImpl *target,
1277 const struct wined3d_format_desc *ds_format_desc)
1279 IWineD3DDeviceImpl *device = swapchain->device;
1280 const struct wined3d_gl_info *gl_info = &device->adapter->gl_info;
1281 const struct wined3d_format_desc *color_format_desc;
1282 struct wined3d_context *ret;
1283 PIXELFORMATDESCRIPTOR pfd;
1284 BOOL auxBuffers = FALSE;
1285 int numSamples = 0;
1286 int pixel_format;
1287 unsigned int s;
1288 DWORD state;
1289 HGLRC ctx;
1290 HDC hdc;
1292 TRACE("swapchain %p, target %p, window %p.\n", swapchain, target, swapchain->win_handle);
1294 ret = HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, sizeof(*ret));
1295 if (!ret)
1297 ERR("Failed to allocate context memory.\n");
1298 return NULL;
1301 if (!(hdc = GetDC(swapchain->win_handle)))
1303 ERR("Failed to retrieve a device context.\n");
1304 goto out;
1307 color_format_desc = target->resource.format_desc;
1309 /* In case of ORM_BACKBUFFER, make sure to request an alpha component for
1310 * X4R4G4B4/X8R8G8B8 as we might need it for the backbuffer. */
1311 if (wined3d_settings.offscreen_rendering_mode == ORM_BACKBUFFER)
1313 auxBuffers = TRUE;
1315 if (color_format_desc->format == WINED3DFMT_B4G4R4X4_UNORM)
1316 color_format_desc = getFormatDescEntry(WINED3DFMT_B4G4R4A4_UNORM, gl_info);
1317 else if (color_format_desc->format == WINED3DFMT_B8G8R8X8_UNORM)
1318 color_format_desc = getFormatDescEntry(WINED3DFMT_B8G8R8A8_UNORM, gl_info);
1321 /* DirectDraw supports 8bit paletted render targets and these are used by
1322 * old games like Starcraft and C&C. Most modern hardware doesn't support
1323 * 8bit natively so we perform some form of 8bit -> 32bit conversion. The
1324 * conversion (ab)uses the alpha component for storing the palette index.
1325 * For this reason we require a format with 8bit alpha, so request
1326 * A8R8G8B8. */
1327 if (color_format_desc->format == WINED3DFMT_P8_UINT)
1328 color_format_desc = getFormatDescEntry(WINED3DFMT_B8G8R8A8_UNORM, gl_info);
1330 /* D3D only allows multisampling when SwapEffect is set to WINED3DSWAPEFFECT_DISCARD. */
1331 if (swapchain->presentParms.MultiSampleType && (swapchain->presentParms.SwapEffect == WINED3DSWAPEFFECT_DISCARD))
1333 if (!gl_info->supported[ARB_MULTISAMPLE])
1334 WARN("The application is requesting multisampling without support.\n");
1335 else
1337 TRACE("Requesting multisample type %#x.\n", swapchain->presentParms.MultiSampleType);
1338 numSamples = swapchain->presentParms.MultiSampleType;
1342 /* Try to find a pixel format which matches our requirements. */
1343 pixel_format = WineD3D_ChoosePixelFormat(device, hdc, color_format_desc, ds_format_desc,
1344 auxBuffers, numSamples, FALSE /* findCompatible */);
1346 /* Try to locate a compatible format if we weren't able to find anything. */
1347 if (!pixel_format)
1349 TRACE("Trying to locate a compatible pixel format because an exact match failed.\n");
1350 pixel_format = WineD3D_ChoosePixelFormat(device, hdc, color_format_desc, ds_format_desc,
1351 auxBuffers, 0 /* numSamples */, TRUE /* findCompatible */);
1354 /* If we still don't have a pixel format, something is very wrong as ChoosePixelFormat barely fails */
1355 if (!pixel_format)
1357 ERR("Can't find a suitable pixel format.\n");
1358 goto out;
1361 DescribePixelFormat(hdc, pixel_format, sizeof(pfd), &pfd);
1362 if (!context_set_pixel_format(gl_info, hdc, pixel_format))
1364 ERR("Failed to set pixel format %d on device context %p.\n", pixel_format, hdc);
1365 goto out;
1368 ctx = pwglCreateContext(hdc);
1369 if (device->numContexts)
1371 if (!pwglShareLists(device->contexts[0]->glCtx, ctx))
1373 DWORD err = GetLastError();
1374 ERR("wglShareLists(%p, %p) failed, last error %#x.\n",
1375 device->contexts[0]->glCtx, ctx, err);
1379 if(!ctx) {
1380 ERR("Failed to create a WGL context\n");
1381 goto out;
1384 if (!device_context_add(device, ret))
1386 ERR("Failed to add the newly created context to the context list\n");
1387 if (!pwglDeleteContext(ctx))
1389 DWORD err = GetLastError();
1390 ERR("wglDeleteContext(%p) failed, last error %#x.\n", ctx, err);
1392 goto out;
1395 ret->gl_info = gl_info;
1397 /* Mark all states dirty to force a proper initialization of the states
1398 * on the first use of the context. */
1399 for (state = 0; state <= STATE_HIGHEST; ++state)
1401 if (device->StateTable[state].representative)
1402 Context_MarkStateDirty(ret, state, device->StateTable);
1405 ret->swapchain = swapchain;
1406 ret->current_rt = target;
1407 ret->tid = GetCurrentThreadId();
1409 ret->render_offscreen = surface_is_offscreen(target);
1410 ret->draw_buffer_dirty = TRUE;
1411 ret->valid = 1;
1413 ret->glCtx = ctx;
1414 ret->win_handle = swapchain->win_handle;
1415 ret->hdc = hdc;
1416 ret->pixel_format = pixel_format;
1418 if (device->shader_backend->shader_dirtifyable_constants((IWineD3DDevice *)device))
1420 /* Create the dirty constants array and initialize them to dirty */
1421 ret->vshader_const_dirty = HeapAlloc(GetProcessHeap(), 0,
1422 sizeof(*ret->vshader_const_dirty) * device->d3d_vshader_constantF);
1423 ret->pshader_const_dirty = HeapAlloc(GetProcessHeap(), 0,
1424 sizeof(*ret->pshader_const_dirty) * device->d3d_pshader_constantF);
1425 memset(ret->vshader_const_dirty, 1,
1426 sizeof(*ret->vshader_const_dirty) * device->d3d_vshader_constantF);
1427 memset(ret->pshader_const_dirty, 1,
1428 sizeof(*ret->pshader_const_dirty) * device->d3d_pshader_constantF);
1431 ret->blit_targets = HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY,
1432 gl_info->limits.buffers * sizeof(*ret->blit_targets));
1433 if (!ret->blit_targets) goto out;
1435 ret->draw_buffers = HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY,
1436 gl_info->limits.buffers * sizeof(*ret->draw_buffers));
1437 if (!ret->draw_buffers) goto out;
1439 ret->free_occlusion_query_size = 4;
1440 ret->free_occlusion_queries = HeapAlloc(GetProcessHeap(), 0,
1441 ret->free_occlusion_query_size * sizeof(*ret->free_occlusion_queries));
1442 if (!ret->free_occlusion_queries) goto out;
1444 list_init(&ret->occlusion_queries);
1446 ret->free_event_query_size = 4;
1447 ret->free_event_queries = HeapAlloc(GetProcessHeap(), 0,
1448 ret->free_event_query_size * sizeof(*ret->free_event_queries));
1449 if (!ret->free_event_queries) goto out;
1451 list_init(&ret->event_queries);
1453 TRACE("Successfully created new context %p\n", ret);
1455 list_init(&ret->fbo_list);
1456 list_init(&ret->fbo_destroy_list);
1458 context_enter(ret);
1460 /* Set up the context defaults */
1461 if (!context_set_current(ret))
1463 ERR("Cannot activate context to set up defaults\n");
1464 context_release(ret);
1465 goto out;
1468 ENTER_GL();
1470 glGetIntegerv(GL_AUX_BUFFERS, &ret->aux_buffers);
1472 TRACE("Setting up the screen\n");
1473 /* Clear the screen */
1474 glClearColor(1.0f, 0.0f, 0.0f, 0.0f);
1475 checkGLcall("glClearColor");
1476 glClearIndex(0);
1477 glClearDepth(1);
1478 glClearStencil(0xffff);
1480 checkGLcall("glClear");
1482 glLightModeli(GL_LIGHT_MODEL_LOCAL_VIEWER, GL_TRUE);
1483 checkGLcall("glLightModeli(GL_LIGHT_MODEL_LOCAL_VIEWER, GL_TRUE);");
1485 glTexEnvf(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_COMBINE_EXT);
1486 checkGLcall("glTexEnvf(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_COMBINE_EXT);");
1488 glLightModeli(GL_LIGHT_MODEL_COLOR_CONTROL, GL_SEPARATE_SPECULAR_COLOR);
1489 checkGLcall("glLightModeli(GL_LIGHT_MODEL_COLOR_CONTROL, GL_SEPARATE_SPECULAR_COLOR);");
1491 glPixelStorei(GL_PACK_ALIGNMENT, device->surface_alignment);
1492 checkGLcall("glPixelStorei(GL_PACK_ALIGNMENT, device->surface_alignment);");
1493 glPixelStorei(GL_UNPACK_ALIGNMENT, device->surface_alignment);
1494 checkGLcall("glPixelStorei(GL_UNPACK_ALIGNMENT, device->surface_alignment);");
1496 if (gl_info->supported[APPLE_CLIENT_STORAGE])
1498 /* Most textures will use client storage if supported. Exceptions are non-native power of 2 textures
1499 * and textures in DIB sections(due to the memory protection).
1501 glPixelStorei(GL_UNPACK_CLIENT_STORAGE_APPLE, GL_TRUE);
1502 checkGLcall("glPixelStorei(GL_UNPACK_CLIENT_STORAGE_APPLE, GL_TRUE)");
1504 if (gl_info->supported[ARB_VERTEX_BLEND])
1506 /* Direct3D always uses n-1 weights for n world matrices and uses 1 - sum for the last one
1507 * this is equal to GL_WEIGHT_SUM_UNITY_ARB. Enabling it doesn't do anything unless
1508 * GL_VERTEX_BLEND_ARB isn't enabled too
1510 glEnable(GL_WEIGHT_SUM_UNITY_ARB);
1511 checkGLcall("glEnable(GL_WEIGHT_SUM_UNITY_ARB)");
1513 if (gl_info->supported[NV_TEXTURE_SHADER2])
1515 /* Set up the previous texture input for all shader units. This applies to bump mapping, and in d3d
1516 * the previous texture where to source the offset from is always unit - 1.
1518 for (s = 1; s < gl_info->limits.textures; ++s)
1520 GL_EXTCALL(glActiveTextureARB(GL_TEXTURE0_ARB + s));
1521 glTexEnvi(GL_TEXTURE_SHADER_NV, GL_PREVIOUS_TEXTURE_INPUT_NV, GL_TEXTURE0_ARB + s - 1);
1522 checkGLcall("glTexEnvi(GL_TEXTURE_SHADER_NV, GL_PREVIOUS_TEXTURE_INPUT_NV, ...");
1525 if (gl_info->supported[ARB_FRAGMENT_PROGRAM])
1527 /* MacOS(radeon X1600 at least, but most likely others too) refuses to draw if GLSL and ARBFP are
1528 * enabled, but the currently bound arbfp program is 0. Enabling ARBFP with prog 0 is invalid, but
1529 * GLSL should bypass this. This causes problems in programs that never use the fixed function pipeline,
1530 * because the ARBFP extension is enabled by the ARBFP pipeline at context creation, but no program
1531 * is ever assigned.
1533 * So make sure a program is assigned to each context. The first real ARBFP use will set a different
1534 * program and the dummy program is destroyed when the context is destroyed.
1536 const char *dummy_program =
1537 "!!ARBfp1.0\n"
1538 "MOV result.color, fragment.color.primary;\n"
1539 "END\n";
1540 GL_EXTCALL(glGenProgramsARB(1, &ret->dummy_arbfp_prog));
1541 GL_EXTCALL(glBindProgramARB(GL_FRAGMENT_PROGRAM_ARB, ret->dummy_arbfp_prog));
1542 GL_EXTCALL(glProgramStringARB(GL_FRAGMENT_PROGRAM_ARB, GL_PROGRAM_FORMAT_ASCII_ARB, strlen(dummy_program), dummy_program));
1545 for (s = 0; s < gl_info->limits.point_sprite_units; ++s)
1547 GL_EXTCALL(glActiveTextureARB(GL_TEXTURE0_ARB + s));
1548 glTexEnvi(GL_POINT_SPRITE_ARB, GL_COORD_REPLACE_ARB, GL_TRUE);
1549 checkGLcall("glTexEnvi(GL_POINT_SPRITE_ARB, GL_COORD_REPLACE_ARB, GL_TRUE)");
1552 if (gl_info->supported[WINED3D_GL_VERSION_2_0])
1554 /* Windows doesn't support to query the glPointParameteri function pointer, so use the
1555 * NV_POINT_SPRITE extension.
1557 if (glPointParameteri)
1559 glPointParameteri(GL_POINT_SPRITE_COORD_ORIGIN, GL_UPPER_LEFT);
1560 checkGLcall("glPointParameteri(GL_POINT_SPRITE_COORD_ORIGIN, GL_UPPER_LEFT)");
1562 else if (gl_info->supported[NV_POINT_SPRITE])
1564 GL_EXTCALL(glPointParameteriNV(GL_POINT_SPRITE_COORD_ORIGIN, GL_UPPER_LEFT));
1565 checkGLcall("glPointParameteriNV(GL_POINT_SPRITE_COORD_ORIGIN, GL_UPPER_LEFT)");
1569 if (gl_info->supported[ARB_PROVOKING_VERTEX])
1571 GL_EXTCALL(glProvokingVertex(GL_FIRST_VERTEX_CONVENTION));
1573 else if (gl_info->supported[EXT_PROVOKING_VERTEX])
1575 GL_EXTCALL(glProvokingVertexEXT(GL_FIRST_VERTEX_CONVENTION_EXT));
1578 LEAVE_GL();
1580 device->frag_pipe->enable_extension((IWineD3DDevice *)device, TRUE);
1582 TRACE("Created context %p.\n", ret);
1584 return ret;
1586 out:
1587 HeapFree(GetProcessHeap(), 0, ret->free_event_queries);
1588 HeapFree(GetProcessHeap(), 0, ret->free_occlusion_queries);
1589 HeapFree(GetProcessHeap(), 0, ret->draw_buffers);
1590 HeapFree(GetProcessHeap(), 0, ret->blit_targets);
1591 HeapFree(GetProcessHeap(), 0, ret->pshader_const_dirty);
1592 HeapFree(GetProcessHeap(), 0, ret->vshader_const_dirty);
1593 HeapFree(GetProcessHeap(), 0, ret);
1594 return NULL;
1597 /*****************************************************************************
1598 * context_destroy
1600 * Destroys a wined3d context
1602 * Params:
1603 * This: Device to activate the context for
1604 * context: Context to destroy
1606 *****************************************************************************/
1607 void context_destroy(IWineD3DDeviceImpl *This, struct wined3d_context *context)
1609 BOOL destroy;
1611 TRACE("Destroying ctx %p\n", context);
1613 if (context->tid == GetCurrentThreadId() || !context->current)
1615 context_destroy_gl_resources(context);
1616 TlsSetValue(wined3d_context_tls_idx, NULL);
1617 destroy = TRUE;
1619 else
1621 context->destroyed = 1;
1622 destroy = FALSE;
1625 HeapFree(GetProcessHeap(), 0, context->draw_buffers);
1626 HeapFree(GetProcessHeap(), 0, context->blit_targets);
1627 HeapFree(GetProcessHeap(), 0, context->vshader_const_dirty);
1628 HeapFree(GetProcessHeap(), 0, context->pshader_const_dirty);
1629 device_context_remove(This, context);
1630 if (destroy) HeapFree(GetProcessHeap(), 0, context);
1633 /* GL locking is done by the caller */
1634 static inline void set_blit_dimension(UINT width, UINT height) {
1635 glMatrixMode(GL_PROJECTION);
1636 checkGLcall("glMatrixMode(GL_PROJECTION)");
1637 glLoadIdentity();
1638 checkGLcall("glLoadIdentity()");
1639 glOrtho(0, width, height, 0, 0.0, -1.0);
1640 checkGLcall("glOrtho");
1641 glViewport(0, 0, width, height);
1642 checkGLcall("glViewport");
1645 /*****************************************************************************
1646 * SetupForBlit
1648 * Sets up a context for DirectDraw blitting.
1649 * All texture units are disabled, texture unit 0 is set as current unit
1650 * fog, lighting, blending, alpha test, z test, scissor test, culling disabled
1651 * color writing enabled for all channels
1652 * register combiners disabled, shaders disabled
1653 * world matrix is set to identity, texture matrix 0 too
1654 * projection matrix is setup for drawing screen coordinates
1656 * Params:
1657 * This: Device to activate the context for
1658 * context: Context to setup
1660 *****************************************************************************/
1661 /* Context activation is done by the caller. */
1662 static void SetupForBlit(IWineD3DDeviceImpl *This, struct wined3d_context *context)
1664 int i;
1665 const struct StateEntry *StateTable = This->StateTable;
1666 const struct wined3d_gl_info *gl_info = context->gl_info;
1667 UINT width = context->current_rt->currentDesc.Width;
1668 UINT height = context->current_rt->currentDesc.Height;
1669 DWORD sampler;
1671 TRACE("Setting up context %p for blitting\n", context);
1672 if(context->last_was_blit) {
1673 if(context->blit_w != width || context->blit_h != height) {
1674 ENTER_GL();
1675 set_blit_dimension(width, height);
1676 LEAVE_GL();
1677 context->blit_w = width; context->blit_h = height;
1678 /* No need to dirtify here, the states are still dirtified because they weren't
1679 * applied since the last SetupForBlit call. Otherwise last_was_blit would not
1680 * be set
1683 TRACE("Context is already set up for blitting, nothing to do\n");
1684 return;
1686 context->last_was_blit = TRUE;
1688 /* TODO: Use a display list */
1690 /* Disable shaders */
1691 ENTER_GL();
1692 This->shader_backend->shader_select(context, FALSE, FALSE);
1693 LEAVE_GL();
1695 Context_MarkStateDirty(context, STATE_VSHADER, StateTable);
1696 Context_MarkStateDirty(context, STATE_PIXELSHADER, StateTable);
1698 /* Call ENTER_GL() once for all gl calls below. In theory we should not call
1699 * helper functions in between gl calls. This function is full of Context_MarkStateDirty
1700 * which can safely be called from here, we only lock once instead locking/unlocking
1701 * after each GL call.
1703 ENTER_GL();
1705 /* Disable all textures. The caller can then bind a texture it wants to blit
1706 * from
1708 * The blitting code uses (for now) the fixed function pipeline, so make sure to reset all fixed
1709 * function texture unit. No need to care for higher samplers
1711 for (i = gl_info->limits.textures - 1; i > 0 ; --i)
1713 sampler = This->rev_tex_unit_map[i];
1714 GL_EXTCALL(glActiveTextureARB(GL_TEXTURE0_ARB + i));
1715 checkGLcall("glActiveTextureARB");
1717 if (gl_info->supported[ARB_TEXTURE_CUBE_MAP])
1719 glDisable(GL_TEXTURE_CUBE_MAP_ARB);
1720 checkGLcall("glDisable GL_TEXTURE_CUBE_MAP_ARB");
1722 glDisable(GL_TEXTURE_3D);
1723 checkGLcall("glDisable GL_TEXTURE_3D");
1724 if (gl_info->supported[ARB_TEXTURE_RECTANGLE])
1726 glDisable(GL_TEXTURE_RECTANGLE_ARB);
1727 checkGLcall("glDisable GL_TEXTURE_RECTANGLE_ARB");
1729 glDisable(GL_TEXTURE_2D);
1730 checkGLcall("glDisable GL_TEXTURE_2D");
1732 glTexEnvi(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_REPLACE);
1733 checkGLcall("glTexEnvi(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_REPLACE);");
1735 if (sampler != WINED3D_UNMAPPED_STAGE)
1737 if (sampler < MAX_TEXTURES) {
1738 Context_MarkStateDirty(context, STATE_TEXTURESTAGE(sampler, WINED3DTSS_COLOROP), StateTable);
1740 Context_MarkStateDirty(context, STATE_SAMPLER(sampler), StateTable);
1743 GL_EXTCALL(glActiveTextureARB(GL_TEXTURE0_ARB));
1744 checkGLcall("glActiveTextureARB");
1746 sampler = This->rev_tex_unit_map[0];
1748 if (gl_info->supported[ARB_TEXTURE_CUBE_MAP])
1750 glDisable(GL_TEXTURE_CUBE_MAP_ARB);
1751 checkGLcall("glDisable GL_TEXTURE_CUBE_MAP_ARB");
1753 glDisable(GL_TEXTURE_3D);
1754 checkGLcall("glDisable GL_TEXTURE_3D");
1755 if (gl_info->supported[ARB_TEXTURE_RECTANGLE])
1757 glDisable(GL_TEXTURE_RECTANGLE_ARB);
1758 checkGLcall("glDisable GL_TEXTURE_RECTANGLE_ARB");
1760 glDisable(GL_TEXTURE_2D);
1761 checkGLcall("glDisable GL_TEXTURE_2D");
1763 glTexEnvi(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_REPLACE);
1765 glMatrixMode(GL_TEXTURE);
1766 checkGLcall("glMatrixMode(GL_TEXTURE)");
1767 glLoadIdentity();
1768 checkGLcall("glLoadIdentity()");
1770 if (gl_info->supported[EXT_TEXTURE_LOD_BIAS])
1772 glTexEnvf(GL_TEXTURE_FILTER_CONTROL_EXT,
1773 GL_TEXTURE_LOD_BIAS_EXT,
1774 0.0f);
1775 checkGLcall("glTexEnvi GL_TEXTURE_LOD_BIAS_EXT ...");
1778 if (sampler != WINED3D_UNMAPPED_STAGE)
1780 if (sampler < MAX_TEXTURES) {
1781 Context_MarkStateDirty(context, STATE_TRANSFORM(WINED3DTS_TEXTURE0 + sampler), StateTable);
1782 Context_MarkStateDirty(context, STATE_TEXTURESTAGE(sampler, WINED3DTSS_COLOROP), StateTable);
1784 Context_MarkStateDirty(context, STATE_SAMPLER(sampler), StateTable);
1787 /* Other misc states */
1788 glDisable(GL_ALPHA_TEST);
1789 checkGLcall("glDisable(GL_ALPHA_TEST)");
1790 Context_MarkStateDirty(context, STATE_RENDER(WINED3DRS_ALPHATESTENABLE), StateTable);
1791 glDisable(GL_LIGHTING);
1792 checkGLcall("glDisable GL_LIGHTING");
1793 Context_MarkStateDirty(context, STATE_RENDER(WINED3DRS_LIGHTING), StateTable);
1794 glDisable(GL_DEPTH_TEST);
1795 checkGLcall("glDisable GL_DEPTH_TEST");
1796 Context_MarkStateDirty(context, STATE_RENDER(WINED3DRS_ZENABLE), StateTable);
1797 glDisableWINE(GL_FOG);
1798 checkGLcall("glDisable GL_FOG");
1799 Context_MarkStateDirty(context, STATE_RENDER(WINED3DRS_FOGENABLE), StateTable);
1800 glDisable(GL_BLEND);
1801 checkGLcall("glDisable GL_BLEND");
1802 Context_MarkStateDirty(context, STATE_RENDER(WINED3DRS_ALPHABLENDENABLE), StateTable);
1803 glDisable(GL_CULL_FACE);
1804 checkGLcall("glDisable GL_CULL_FACE");
1805 Context_MarkStateDirty(context, STATE_RENDER(WINED3DRS_CULLMODE), StateTable);
1806 glDisable(GL_STENCIL_TEST);
1807 checkGLcall("glDisable GL_STENCIL_TEST");
1808 Context_MarkStateDirty(context, STATE_RENDER(WINED3DRS_STENCILENABLE), StateTable);
1809 glDisable(GL_SCISSOR_TEST);
1810 checkGLcall("glDisable GL_SCISSOR_TEST");
1811 Context_MarkStateDirty(context, STATE_RENDER(WINED3DRS_SCISSORTESTENABLE), StateTable);
1812 if (gl_info->supported[ARB_POINT_SPRITE])
1814 glDisable(GL_POINT_SPRITE_ARB);
1815 checkGLcall("glDisable GL_POINT_SPRITE_ARB");
1816 Context_MarkStateDirty(context, STATE_RENDER(WINED3DRS_POINTSPRITEENABLE), StateTable);
1818 glColorMask(GL_TRUE, GL_TRUE,GL_TRUE,GL_TRUE);
1819 checkGLcall("glColorMask");
1820 Context_MarkStateDirty(context, STATE_RENDER(WINED3DRS_COLORWRITEENABLE), StateTable);
1821 Context_MarkStateDirty(context, STATE_RENDER(WINED3DRS_COLORWRITEENABLE1), StateTable);
1822 Context_MarkStateDirty(context, STATE_RENDER(WINED3DRS_COLORWRITEENABLE2), StateTable);
1823 Context_MarkStateDirty(context, STATE_RENDER(WINED3DRS_COLORWRITEENABLE3), StateTable);
1824 if (gl_info->supported[EXT_SECONDARY_COLOR])
1826 glDisable(GL_COLOR_SUM_EXT);
1827 Context_MarkStateDirty(context, STATE_RENDER(WINED3DRS_SPECULARENABLE), StateTable);
1828 checkGLcall("glDisable(GL_COLOR_SUM_EXT)");
1831 /* Setup transforms */
1832 glMatrixMode(GL_MODELVIEW);
1833 checkGLcall("glMatrixMode(GL_MODELVIEW)");
1834 glLoadIdentity();
1835 checkGLcall("glLoadIdentity()");
1836 Context_MarkStateDirty(context, STATE_TRANSFORM(WINED3DTS_WORLDMATRIX(0)), StateTable);
1838 context->last_was_rhw = TRUE;
1839 Context_MarkStateDirty(context, STATE_VDECL, StateTable); /* because of last_was_rhw = TRUE */
1841 glDisable(GL_CLIP_PLANE0); checkGLcall("glDisable(clip plane 0)");
1842 glDisable(GL_CLIP_PLANE1); checkGLcall("glDisable(clip plane 1)");
1843 glDisable(GL_CLIP_PLANE2); checkGLcall("glDisable(clip plane 2)");
1844 glDisable(GL_CLIP_PLANE3); checkGLcall("glDisable(clip plane 3)");
1845 glDisable(GL_CLIP_PLANE4); checkGLcall("glDisable(clip plane 4)");
1846 glDisable(GL_CLIP_PLANE5); checkGLcall("glDisable(clip plane 5)");
1847 Context_MarkStateDirty(context, STATE_RENDER(WINED3DRS_CLIPPING), StateTable);
1849 set_blit_dimension(width, height);
1851 LEAVE_GL();
1853 context->blit_w = width; context->blit_h = height;
1854 Context_MarkStateDirty(context, STATE_VIEWPORT, StateTable);
1855 Context_MarkStateDirty(context, STATE_TRANSFORM(WINED3DTS_PROJECTION), StateTable);
1858 This->frag_pipe->enable_extension((IWineD3DDevice *) This, FALSE);
1861 /*****************************************************************************
1862 * findThreadContextForSwapChain
1864 * Searches a swapchain for all contexts and picks one for the thread tid.
1865 * If none can be found the swapchain is requested to create a new context
1867 *****************************************************************************/
1868 static struct wined3d_context *findThreadContextForSwapChain(IWineD3DSwapChain *swapchain, DWORD tid)
1870 unsigned int i;
1872 for(i = 0; i < ((IWineD3DSwapChainImpl *) swapchain)->num_contexts; i++) {
1873 if(((IWineD3DSwapChainImpl *) swapchain)->context[i]->tid == tid) {
1874 return ((IWineD3DSwapChainImpl *) swapchain)->context[i];
1879 /* Create a new context for the thread */
1880 return swapchain_create_context_for_thread(swapchain);
1883 /*****************************************************************************
1884 * FindContext
1886 * Finds a context for the current render target and thread
1888 * Parameters:
1889 * target: Render target to find the context for
1890 * tid: Thread to activate the context for
1892 * Returns: The needed context
1894 *****************************************************************************/
1895 static struct wined3d_context *FindContext(IWineD3DDeviceImpl *This, IWineD3DSurfaceImpl *target)
1897 struct wined3d_context *current_context = context_get_current();
1898 DWORD tid = GetCurrentThreadId();
1899 struct wined3d_context *context;
1901 if (current_context && current_context->destroyed) current_context = NULL;
1903 if (!target)
1905 if (current_context
1906 && current_context->current_rt
1907 && current_context->swapchain->device == This)
1909 target = current_context->current_rt;
1911 else
1913 IWineD3DSwapChainImpl *swapchain = (IWineD3DSwapChainImpl *)This->swapchains[0];
1914 if (swapchain->back_buffers) target = swapchain->back_buffers[0];
1915 else target = swapchain->front_buffer;
1919 if (current_context && current_context->current_rt == target)
1921 context_validate(current_context);
1922 return current_context;
1925 if (target->container.type == WINED3D_CONTAINER_SWAPCHAIN)
1927 IWineD3DSwapChain *swapchain;
1929 TRACE("Rendering onscreen\n");
1931 swapchain = (IWineD3DSwapChain *)target->container.u.swapchain;
1932 context = findThreadContextForSwapChain(swapchain, tid);
1934 else
1936 TRACE("Rendering offscreen\n");
1938 /* Stay with the currently active context. */
1939 if (current_context && current_context->swapchain->device == This)
1941 context = current_context;
1943 else
1945 /* This may happen if the app jumps straight into offscreen rendering
1946 * Start using the context of the primary swapchain. tid == 0 is no problem
1947 * for findThreadContextForSwapChain.
1949 * Can also happen on thread switches - in that case findThreadContextForSwapChain
1950 * is perfect to call. */
1951 context = findThreadContextForSwapChain(This->swapchains[0], tid);
1955 context_validate(context);
1957 return context;
1960 /* Context activation is done by the caller. */
1961 static void context_apply_draw_buffer(struct wined3d_context *context, BOOL blit)
1963 const struct wined3d_gl_info *gl_info = context->gl_info;
1964 IWineD3DSurfaceImpl *rt = context->current_rt;
1965 IWineD3DDeviceImpl *device;
1967 device = rt->resource.device;
1968 if (!surface_is_offscreen(rt))
1970 ENTER_GL();
1971 glDrawBuffer(surface_get_gl_buffer(rt));
1972 checkGLcall("glDrawBuffer()");
1973 LEAVE_GL();
1975 else
1977 ENTER_GL();
1978 if (wined3d_settings.offscreen_rendering_mode == ORM_FBO)
1980 if (!blit)
1982 unsigned int i;
1984 for (i = 0; i < gl_info->limits.buffers; ++i)
1986 if (device->render_targets[i])
1987 context->draw_buffers[i] = GL_COLOR_ATTACHMENT0 + i;
1988 else
1989 context->draw_buffers[i] = GL_NONE;
1992 if (gl_info->supported[ARB_DRAW_BUFFERS])
1994 GL_EXTCALL(glDrawBuffersARB(gl_info->limits.buffers, context->draw_buffers));
1995 checkGLcall("glDrawBuffers()");
1997 else
1999 glDrawBuffer(context->draw_buffers[0]);
2000 checkGLcall("glDrawBuffer()");
2002 } else {
2003 glDrawBuffer(GL_COLOR_ATTACHMENT0);
2004 checkGLcall("glDrawBuffer()");
2007 else
2009 glDrawBuffer(device->offscreenBuffer);
2010 checkGLcall("glDrawBuffer()");
2012 LEAVE_GL();
2016 /* GL locking is done by the caller. */
2017 void context_set_draw_buffer(struct wined3d_context *context, GLenum buffer)
2019 glDrawBuffer(buffer);
2020 checkGLcall("glDrawBuffer()");
2021 context->draw_buffer_dirty = TRUE;
2024 static inline void context_set_render_offscreen(struct wined3d_context *context, const struct StateEntry *StateTable,
2025 BOOL offscreen)
2027 const struct wined3d_gl_info *gl_info = context->gl_info;
2029 if (context->render_offscreen == offscreen) return;
2031 if (gl_info->supported[WINED3D_GL_VERSION_2_0])
2033 /* Windows doesn't support to query the glPointParameteri function pointer, so use the
2034 * NV_POINT_SPRITE extension.
2036 if (glPointParameteri)
2038 glPointParameteri(GL_POINT_SPRITE_COORD_ORIGIN, offscreen ? GL_LOWER_LEFT : GL_UPPER_LEFT);
2039 checkGLcall("glPointParameteri(GL_POINT_SPRITE_COORD_ORIGIN, ...)");
2041 else if (gl_info->supported[NV_POINT_SPRITE])
2043 GL_EXTCALL(glPointParameteriNV(GL_POINT_SPRITE_COORD_ORIGIN, offscreen ? GL_LOWER_LEFT : GL_UPPER_LEFT));
2044 checkGLcall("glPointParameteriNV(GL_POINT_SPRITE_COORD_ORIGIN, ...)");
2048 Context_MarkStateDirty(context, STATE_TRANSFORM(WINED3DTS_PROJECTION), StateTable);
2049 Context_MarkStateDirty(context, STATE_VDECL, StateTable);
2050 Context_MarkStateDirty(context, STATE_VIEWPORT, StateTable);
2051 Context_MarkStateDirty(context, STATE_SCISSORRECT, StateTable);
2052 Context_MarkStateDirty(context, STATE_FRONTFACE, StateTable);
2053 context->render_offscreen = offscreen;
2056 static BOOL match_depth_stencil_format(const struct wined3d_format_desc *existing,
2057 const struct wined3d_format_desc *required)
2059 short existing_depth, existing_stencil, required_depth, required_stencil;
2061 if(existing == required) return TRUE;
2062 if((existing->Flags & WINED3DFMT_FLAG_FLOAT) != (required->Flags & WINED3DFMT_FLAG_FLOAT)) return FALSE;
2064 getDepthStencilBits(existing, &existing_depth, &existing_stencil);
2065 getDepthStencilBits(required, &required_depth, &required_stencil);
2067 if(existing_depth < required_depth) return FALSE;
2068 /* If stencil bits are used the exact amount is required - otherwise wrapping
2069 * won't work correctly */
2070 if(required_stencil && required_stencil != existing_stencil) return FALSE;
2071 return TRUE;
2073 /* The caller provides a context */
2074 static void context_validate_onscreen_formats(IWineD3DDeviceImpl *device,
2075 struct wined3d_context *context, IWineD3DSurfaceImpl *depth_stencil)
2077 /* Onscreen surfaces are always in a swapchain */
2078 IWineD3DSwapChainImpl *swapchain = context->current_rt->container.u.swapchain;
2080 if (context->render_offscreen || !depth_stencil) return;
2081 if (match_depth_stencil_format(swapchain->ds_format, depth_stencil->resource.format_desc)) return;
2083 /* TODO: If the requested format would satisfy the needs of the existing one(reverse match),
2084 * or no onscreen depth buffer was created, the OpenGL drawable could be changed to the new
2085 * format. */
2086 WARN("Depth stencil format is not supported by WGL, rendering the backbuffer in an FBO\n");
2088 /* The currently active context is the necessary context to access the swapchain's onscreen buffers */
2089 surface_load_location(context->current_rt, SFLAG_INTEXTURE, NULL);
2090 swapchain->render_to_fbo = TRUE;
2091 context_set_render_offscreen(context, device->StateTable, TRUE);
2094 /* Context activation is done by the caller. */
2095 void context_apply_blit_state(struct wined3d_context *context, IWineD3DDeviceImpl *device)
2097 if (wined3d_settings.offscreen_rendering_mode == ORM_FBO)
2099 context_validate_onscreen_formats(device, context, NULL);
2101 if (context->render_offscreen)
2103 FIXME("Applying blit state for an offscreen target with ORM_FBO. This should be avoided.\n");
2104 surface_internal_preload(context->current_rt, SRGB_RGB);
2106 ENTER_GL();
2107 context_apply_fbo_state_blit(context, GL_FRAMEBUFFER, context->current_rt, NULL, SFLAG_INTEXTURE);
2108 LEAVE_GL();
2110 else
2112 ENTER_GL();
2113 context_bind_fbo(context, GL_FRAMEBUFFER, NULL);
2114 LEAVE_GL();
2117 context->draw_buffer_dirty = TRUE;
2120 if (context->draw_buffer_dirty)
2122 context_apply_draw_buffer(context, TRUE);
2123 if (wined3d_settings.offscreen_rendering_mode != ORM_FBO)
2124 context->draw_buffer_dirty = FALSE;
2127 SetupForBlit(device, context);
2130 /* Context activation is done by the caller. */
2131 void context_apply_clear_state(struct wined3d_context *context, IWineD3DDeviceImpl *device,
2132 UINT rt_count, IWineD3DSurfaceImpl **rts, IWineD3DSurfaceImpl *depth_stencil)
2134 const struct StateEntry *state_table = device->StateTable;
2135 UINT i;
2137 if (wined3d_settings.offscreen_rendering_mode == ORM_FBO)
2139 context_validate_onscreen_formats(device, context, depth_stencil);
2141 ENTER_GL();
2143 if (surface_is_offscreen(rts[0]))
2145 for (i = 0; i < rt_count; ++i)
2147 context->blit_targets[i] = rts[i];
2149 while (i < context->gl_info->limits.buffers)
2151 context->blit_targets[i] = NULL;
2152 ++i;
2154 context_apply_fbo_state(context, GL_FRAMEBUFFER, context->blit_targets, depth_stencil, SFLAG_INTEXTURE);
2156 else
2158 context_apply_fbo_state(context, GL_FRAMEBUFFER, NULL, NULL, SFLAG_INDRAWABLE);
2161 LEAVE_GL();
2164 if (!surface_is_offscreen(rts[0]))
2166 ENTER_GL();
2167 context_set_draw_buffer(context, surface_get_gl_buffer(rts[0]));
2168 LEAVE_GL();
2170 else
2172 ENTER_GL();
2174 if (wined3d_settings.offscreen_rendering_mode == ORM_FBO)
2176 const struct wined3d_gl_info *gl_info = context->gl_info;
2177 for (i = 0; i < gl_info->limits.buffers; ++i)
2179 if (i < rt_count && rts[i])
2180 context->draw_buffers[i] = GL_COLOR_ATTACHMENT0 + i;
2181 else
2182 context->draw_buffers[i] = GL_NONE;
2184 GL_EXTCALL(glDrawBuffersARB(gl_info->limits.buffers, context->draw_buffers));
2185 checkGLcall("glDrawBuffers()");
2186 context->draw_buffer_dirty = TRUE;
2188 else
2190 glDrawBuffer(device->offscreenBuffer);
2191 checkGLcall("glDrawBuffer()");
2194 LEAVE_GL();
2197 if (context->last_was_blit)
2199 device->frag_pipe->enable_extension((IWineD3DDevice *)device, TRUE);
2202 /* Blending and clearing should be orthogonal, but tests on the nvidia
2203 * driver show that disabling blending when clearing improves the clearing
2204 * performance incredibly. */
2205 ENTER_GL();
2206 glDisable(GL_BLEND);
2207 glEnable(GL_SCISSOR_TEST);
2208 checkGLcall("glEnable GL_SCISSOR_TEST");
2209 LEAVE_GL();
2211 context->last_was_blit = FALSE;
2212 Context_MarkStateDirty(context, STATE_RENDER(WINED3DRS_ALPHABLENDENABLE), state_table);
2213 Context_MarkStateDirty(context, STATE_RENDER(WINED3DRS_SCISSORTESTENABLE), state_table);
2214 Context_MarkStateDirty(context, STATE_SCISSORRECT, state_table);
2217 /* Context activation is done by the caller. */
2218 void context_apply_draw_state(struct wined3d_context *context, IWineD3DDeviceImpl *device)
2220 const struct StateEntry *state_table = device->StateTable;
2221 unsigned int i;
2223 /* Preload resources before FBO setup. Texture preload in particular may
2224 * result in changes to the current FBO, due to using e.g. FBO blits for
2225 * updating a resource location. */
2226 IWineD3DDeviceImpl_FindTexUnitMap(device);
2227 device_preload_textures(device);
2228 if (isStateDirty(context, STATE_VDECL))
2229 device_update_stream_info(device, context->gl_info);
2231 if (wined3d_settings.offscreen_rendering_mode == ORM_FBO)
2233 context_validate_onscreen_formats(device, context, device->depth_stencil);
2235 if (!context->render_offscreen)
2237 ENTER_GL();
2238 context_apply_fbo_state(context, GL_FRAMEBUFFER, NULL, NULL, SFLAG_INDRAWABLE);
2239 LEAVE_GL();
2241 else
2243 ENTER_GL();
2244 context_apply_fbo_state(context, GL_FRAMEBUFFER, device->render_targets,
2245 device->depth_stencil, SFLAG_INTEXTURE);
2246 LEAVE_GL();
2250 if (context->draw_buffer_dirty)
2252 context_apply_draw_buffer(context, FALSE);
2253 context->draw_buffer_dirty = FALSE;
2256 if (context->last_was_blit)
2258 device->frag_pipe->enable_extension((IWineD3DDevice *)device, TRUE);
2261 ENTER_GL();
2262 for (i = 0; i < context->numDirtyEntries; ++i)
2264 DWORD rep = context->dirtyArray[i];
2265 DWORD idx = rep / (sizeof(*context->isStateDirty) * CHAR_BIT);
2266 BYTE shift = rep & ((sizeof(*context->isStateDirty) * CHAR_BIT) - 1);
2267 context->isStateDirty[idx] &= ~(1 << shift);
2268 state_table[rep].apply(rep, device->stateBlock, context);
2270 LEAVE_GL();
2271 context->numDirtyEntries = 0; /* This makes the whole list clean */
2272 context->last_was_blit = FALSE;
2275 static void context_setup_target(IWineD3DDeviceImpl *device,
2276 struct wined3d_context *context, IWineD3DSurfaceImpl *target)
2278 BOOL old_render_offscreen = context->render_offscreen, render_offscreen;
2279 const struct StateEntry *StateTable = device->StateTable;
2281 if (!target) return;
2282 render_offscreen = surface_is_offscreen(target);
2283 if (context->current_rt == target && render_offscreen == old_render_offscreen) return;
2285 /* To compensate the lack of format switching with some offscreen rendering methods and on onscreen buffers
2286 * the alpha blend state changes with different render target formats. */
2287 if (!context->current_rt)
2289 Context_MarkStateDirty(context, STATE_RENDER(WINED3DRS_ALPHABLENDENABLE), StateTable);
2291 else
2293 const struct wined3d_format_desc *old = context->current_rt->resource.format_desc;
2294 const struct wined3d_format_desc *new = target->resource.format_desc;
2296 if (old->format != new->format)
2298 /* Disable blending when the alpha mask has changed and when a format doesn't support blending. */
2299 if ((old->alpha_mask && !new->alpha_mask) || (!old->alpha_mask && new->alpha_mask)
2300 || !(new->Flags & WINED3DFMT_FLAG_POSTPIXELSHADER_BLENDING))
2302 Context_MarkStateDirty(context, STATE_RENDER(WINED3DRS_ALPHABLENDENABLE), StateTable);
2304 /* Update sRGB writing when switching between formats that do/do not support sRGB writing */
2305 if ((old->Flags & WINED3DFMT_FLAG_SRGB_WRITE) != (new->Flags & WINED3DFMT_FLAG_SRGB_WRITE))
2307 Context_MarkStateDirty(context, STATE_RENDER(WINED3DRS_SRGBWRITEENABLE), StateTable);
2311 /* When switching away from an offscreen render target, and we're not
2312 * using FBOs, we have to read the drawable into the texture. This is
2313 * done via PreLoad (and SFLAG_INDRAWABLE set on the surface). There
2314 * are some things that need care though. PreLoad needs a GL context,
2315 * and FindContext is called before the context is activated. It also
2316 * has to be called with the old rendertarget active, otherwise a
2317 * wrong drawable is read. */
2318 if (wined3d_settings.offscreen_rendering_mode != ORM_FBO
2319 && old_render_offscreen && context->current_rt != target)
2321 /* Read the back buffer of the old drawable into the destination texture. */
2322 if (context->current_rt->texture_name_srgb)
2324 surface_internal_preload(context->current_rt, SRGB_BOTH);
2326 else
2328 surface_internal_preload(context->current_rt, SRGB_RGB);
2331 surface_modify_location(context->current_rt, SFLAG_INDRAWABLE, FALSE);
2335 context->draw_buffer_dirty = TRUE;
2336 context->current_rt = target;
2337 context_set_render_offscreen(context, StateTable, render_offscreen);
2340 /*****************************************************************************
2341 * context_acquire
2343 * Finds a rendering context and drawable matching the device and render
2344 * target for the current thread, activates them and puts them into the
2345 * requested state.
2347 * Params:
2348 * This: Device to activate the context for
2349 * target: Requested render target
2350 * usage: Prepares the context for blitting, drawing or other actions
2352 *****************************************************************************/
2353 struct wined3d_context *context_acquire(IWineD3DDeviceImpl *device, IWineD3DSurfaceImpl *target)
2355 struct wined3d_context *current_context = context_get_current();
2356 struct wined3d_context *context;
2358 TRACE("device %p, target %p.\n", device, target);
2360 context = FindContext(device, target);
2361 context_setup_target(device, context, target);
2362 context_enter(context);
2363 if (!context->valid) return context;
2365 if (context != current_context)
2367 if (!context_set_current(context)) ERR("Failed to activate the new context.\n");
2368 else device->frag_pipe->enable_extension((IWineD3DDevice *)device, !context->last_was_blit);
2370 if (context->vshader_const_dirty)
2372 memset(context->vshader_const_dirty, 1,
2373 sizeof(*context->vshader_const_dirty) * device->d3d_vshader_constantF);
2374 device->highest_dirty_vs_const = device->d3d_vshader_constantF;
2376 if (context->pshader_const_dirty)
2378 memset(context->pshader_const_dirty, 1,
2379 sizeof(*context->pshader_const_dirty) * device->d3d_pshader_constantF);
2380 device->highest_dirty_ps_const = device->d3d_pshader_constantF;
2383 else if (context->restore_ctx)
2385 if (!pwglMakeCurrent(context->hdc, context->glCtx))
2387 DWORD err = GetLastError();
2388 ERR("Failed to make GL context %p current on device context %p, last error %#x.\n",
2389 context->hdc, context->glCtx, err);
2393 return context;