riched20: Implement IsEqual() for ranges.
[wine.git] / dlls / wined3d / context.c
bloba68d5d5707b91981ab0b7f4fd75adc6056189735
1 /*
2 * Context and render target management in wined3d
4 * Copyright 2007-2011, 2013 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
22 #include "config.h"
23 #include "wine/port.h"
25 #include <stdio.h>
26 #ifdef HAVE_FLOAT_H
27 # include <float.h>
28 #endif
30 #include "wined3d_private.h"
32 WINE_DEFAULT_DEBUG_CHANNEL(d3d);
33 WINE_DECLARE_DEBUG_CHANNEL(d3d_perf);
34 WINE_DECLARE_DEBUG_CHANNEL(d3d_synchronous);
36 #define WINED3D_MAX_FBO_ENTRIES 64
38 static DWORD wined3d_context_tls_idx;
40 /* FBO helper functions */
42 /* Context activation is done by the caller. */
43 static void context_bind_fbo(struct wined3d_context *context, GLenum target, GLuint fbo)
45 const struct wined3d_gl_info *gl_info = context->gl_info;
47 switch (target)
49 case GL_READ_FRAMEBUFFER:
50 if (context->fbo_read_binding == fbo) return;
51 context->fbo_read_binding = fbo;
52 break;
54 case GL_DRAW_FRAMEBUFFER:
55 if (context->fbo_draw_binding == fbo) return;
56 context->fbo_draw_binding = fbo;
57 break;
59 case GL_FRAMEBUFFER:
60 if (context->fbo_read_binding == fbo
61 && context->fbo_draw_binding == fbo) return;
62 context->fbo_read_binding = fbo;
63 context->fbo_draw_binding = fbo;
64 break;
66 default:
67 FIXME("Unhandled target %#x.\n", target);
68 break;
71 gl_info->fbo_ops.glBindFramebuffer(target, fbo);
72 checkGLcall("glBindFramebuffer()");
75 /* Context activation is done by the caller. */
76 static void context_clean_fbo_attachments(const struct wined3d_gl_info *gl_info, GLenum target)
78 unsigned int i;
80 for (i = 0; i < gl_info->limits.buffers; ++i)
82 gl_info->fbo_ops.glFramebufferTexture2D(target, GL_COLOR_ATTACHMENT0 + i, GL_TEXTURE_2D, 0, 0);
83 checkGLcall("glFramebufferTexture2D()");
85 gl_info->fbo_ops.glFramebufferTexture2D(target, GL_DEPTH_ATTACHMENT, GL_TEXTURE_2D, 0, 0);
86 checkGLcall("glFramebufferTexture2D()");
88 gl_info->fbo_ops.glFramebufferTexture2D(target, GL_STENCIL_ATTACHMENT, GL_TEXTURE_2D, 0, 0);
89 checkGLcall("glFramebufferTexture2D()");
92 /* Context activation is done by the caller. */
93 static void context_destroy_fbo(struct wined3d_context *context, GLuint fbo)
95 const struct wined3d_gl_info *gl_info = context->gl_info;
97 context_bind_fbo(context, GL_FRAMEBUFFER, fbo);
98 context_clean_fbo_attachments(gl_info, GL_FRAMEBUFFER);
99 context_bind_fbo(context, GL_FRAMEBUFFER, 0);
101 gl_info->fbo_ops.glDeleteFramebuffers(1, &fbo);
102 checkGLcall("glDeleteFramebuffers()");
105 static void context_attach_depth_stencil_rb(const struct wined3d_gl_info *gl_info,
106 GLenum fbo_target, DWORD format_flags, GLuint rb)
108 if (format_flags & WINED3DFMT_FLAG_DEPTH)
110 gl_info->fbo_ops.glFramebufferRenderbuffer(fbo_target, GL_DEPTH_ATTACHMENT, GL_RENDERBUFFER, rb);
111 checkGLcall("glFramebufferRenderbuffer()");
114 if (format_flags & WINED3DFMT_FLAG_STENCIL)
116 gl_info->fbo_ops.glFramebufferRenderbuffer(fbo_target, GL_STENCIL_ATTACHMENT, GL_RENDERBUFFER, rb);
117 checkGLcall("glFramebufferRenderbuffer()");
121 /* Context activation is done by the caller. */
122 static void context_attach_depth_stencil_fbo(struct wined3d_context *context,
123 GLenum fbo_target, struct wined3d_surface *depth_stencil, DWORD location)
125 const struct wined3d_gl_info *gl_info = context->gl_info;
127 TRACE("Attach depth stencil %p\n", depth_stencil);
129 if (depth_stencil)
131 DWORD format_flags = depth_stencil->resource.format_flags;
133 if (depth_stencil->current_renderbuffer)
135 context_attach_depth_stencil_rb(gl_info, fbo_target,
136 format_flags, depth_stencil->current_renderbuffer->id);
138 else
140 switch (location)
142 case WINED3D_LOCATION_TEXTURE_RGB:
143 case WINED3D_LOCATION_TEXTURE_SRGB:
144 wined3d_texture_prepare_texture(depth_stencil->container, context, FALSE);
146 if (format_flags & WINED3DFMT_FLAG_DEPTH)
148 gl_info->fbo_ops.glFramebufferTexture2D(fbo_target, GL_DEPTH_ATTACHMENT,
149 depth_stencil->texture_target, depth_stencil->container->texture_rgb.name,
150 depth_stencil->texture_level);
151 checkGLcall("glFramebufferTexture2D()");
154 if (format_flags & WINED3DFMT_FLAG_STENCIL)
156 gl_info->fbo_ops.glFramebufferTexture2D(fbo_target, GL_STENCIL_ATTACHMENT,
157 depth_stencil->texture_target, depth_stencil->container->texture_rgb.name,
158 depth_stencil->texture_level);
159 checkGLcall("glFramebufferTexture2D()");
161 break;
163 case WINED3D_LOCATION_RB_MULTISAMPLE:
164 surface_prepare_rb(depth_stencil, gl_info, TRUE);
165 context_attach_depth_stencil_rb(gl_info, fbo_target,
166 format_flags, depth_stencil->rb_multisample);
167 break;
169 case WINED3D_LOCATION_RB_RESOLVED:
170 surface_prepare_rb(depth_stencil, gl_info, FALSE);
171 context_attach_depth_stencil_rb(gl_info, fbo_target,
172 format_flags, depth_stencil->rb_resolved);
173 break;
175 default:
176 ERR("Unsupported location %s (%#x).\n", wined3d_debug_location(location), location);
177 break;
181 if (!(format_flags & WINED3DFMT_FLAG_DEPTH))
183 gl_info->fbo_ops.glFramebufferTexture2D(fbo_target, GL_DEPTH_ATTACHMENT, GL_TEXTURE_2D, 0, 0);
184 checkGLcall("glFramebufferTexture2D()");
187 if (!(format_flags & WINED3DFMT_FLAG_STENCIL))
189 gl_info->fbo_ops.glFramebufferTexture2D(fbo_target, GL_STENCIL_ATTACHMENT, GL_TEXTURE_2D, 0, 0);
190 checkGLcall("glFramebufferTexture2D()");
193 else
195 gl_info->fbo_ops.glFramebufferTexture2D(fbo_target, GL_DEPTH_ATTACHMENT, GL_TEXTURE_2D, 0, 0);
196 checkGLcall("glFramebufferTexture2D()");
198 gl_info->fbo_ops.glFramebufferTexture2D(fbo_target, GL_STENCIL_ATTACHMENT, GL_TEXTURE_2D, 0, 0);
199 checkGLcall("glFramebufferTexture2D()");
203 /* Context activation is done by the caller. */
204 static void context_attach_surface_fbo(struct wined3d_context *context,
205 GLenum fbo_target, DWORD idx, struct wined3d_surface *surface, DWORD location)
207 const struct wined3d_gl_info *gl_info = context->gl_info;
209 TRACE("Attach surface %p to %u\n", surface, idx);
211 if (surface && surface->resource.format->id != WINED3DFMT_NULL)
213 BOOL srgb;
215 switch (location)
217 case WINED3D_LOCATION_TEXTURE_RGB:
218 case WINED3D_LOCATION_TEXTURE_SRGB:
219 srgb = location == WINED3D_LOCATION_TEXTURE_SRGB;
220 wined3d_texture_prepare_texture(surface->container, context, srgb);
221 gl_info->fbo_ops.glFramebufferTexture2D(fbo_target, GL_COLOR_ATTACHMENT0 + idx,
222 surface->texture_target, surface_get_texture_name(surface, gl_info, srgb),
223 surface->texture_level);
224 checkGLcall("glFramebufferTexture2D()");
225 break;
227 case WINED3D_LOCATION_RB_MULTISAMPLE:
228 surface_prepare_rb(surface, gl_info, TRUE);
229 gl_info->fbo_ops.glFramebufferRenderbuffer(fbo_target, GL_COLOR_ATTACHMENT0 + idx,
230 GL_RENDERBUFFER, surface->rb_multisample);
231 checkGLcall("glFramebufferRenderbuffer()");
232 break;
234 case WINED3D_LOCATION_RB_RESOLVED:
235 surface_prepare_rb(surface, gl_info, FALSE);
236 gl_info->fbo_ops.glFramebufferRenderbuffer(fbo_target, GL_COLOR_ATTACHMENT0 + idx,
237 GL_RENDERBUFFER, surface->rb_resolved);
238 checkGLcall("glFramebufferRenderbuffer()");
239 break;
241 default:
242 ERR("Unsupported location %s (%#x).\n", wined3d_debug_location(location), location);
243 break;
246 else
248 gl_info->fbo_ops.glFramebufferTexture2D(fbo_target, GL_COLOR_ATTACHMENT0 + idx, GL_TEXTURE_2D, 0, 0);
249 checkGLcall("glFramebufferTexture2D()");
253 /* Context activation is done by the caller. */
254 void context_check_fbo_status(const struct wined3d_context *context, GLenum target)
256 const struct wined3d_gl_info *gl_info = context->gl_info;
257 GLenum status;
259 if (!FIXME_ON(d3d)) return;
261 status = gl_info->fbo_ops.glCheckFramebufferStatus(target);
262 if (status == GL_FRAMEBUFFER_COMPLETE)
264 TRACE("FBO complete\n");
266 else
268 const struct wined3d_surface *attachment;
269 unsigned int i;
271 FIXME("FBO status %s (%#x)\n", debug_fbostatus(status), status);
273 if (!context->current_fbo)
275 ERR("FBO 0 is incomplete, driver bug?\n");
276 return;
279 FIXME("\tColor Location %s (%#x).\n", wined3d_debug_location(context->current_fbo->color_location),
280 context->current_fbo->color_location);
281 FIXME("\tDepth Stencil Location %s (%#x).\n", wined3d_debug_location(context->current_fbo->ds_location),
282 context->current_fbo->ds_location);
284 /* Dump the FBO attachments */
285 for (i = 0; i < gl_info->limits.buffers; ++i)
287 attachment = context->current_fbo->render_targets[i];
288 if (attachment)
290 FIXME("\tColor attachment %d: (%p) %s %ux%u %u samples.\n",
291 i, attachment, debug_d3dformat(attachment->resource.format->id),
292 attachment->pow2Width, attachment->pow2Height, attachment->resource.multisample_type);
295 attachment = context->current_fbo->depth_stencil;
296 if (attachment)
298 FIXME("\tDepth attachment: (%p) %s %ux%u %u samples.\n",
299 attachment, debug_d3dformat(attachment->resource.format->id),
300 attachment->pow2Width, attachment->pow2Height, attachment->resource.multisample_type);
305 static inline DWORD context_generate_rt_mask(GLenum buffer)
307 /* Should take care of all the GL_FRONT/GL_BACK/GL_AUXi/GL_NONE... cases */
308 return buffer ? (1 << 31) | buffer : 0;
311 static inline DWORD context_generate_rt_mask_from_surface(const struct wined3d_surface *target)
313 return (1 << 31) | surface_get_gl_buffer(target);
316 static struct fbo_entry *context_create_fbo_entry(const struct wined3d_context *context,
317 struct wined3d_surface **render_targets, struct wined3d_surface *depth_stencil,
318 DWORD color_location, DWORD ds_location)
320 const struct wined3d_gl_info *gl_info = context->gl_info;
321 struct fbo_entry *entry;
323 entry = HeapAlloc(GetProcessHeap(), 0, sizeof(*entry));
324 entry->render_targets = HeapAlloc(GetProcessHeap(), 0, gl_info->limits.buffers * sizeof(*entry->render_targets));
325 memcpy(entry->render_targets, render_targets, gl_info->limits.buffers * sizeof(*entry->render_targets));
326 entry->depth_stencil = depth_stencil;
327 entry->color_location = color_location;
328 entry->ds_location = ds_location;
329 entry->rt_mask = context_generate_rt_mask(GL_COLOR_ATTACHMENT0);
330 entry->attached = FALSE;
331 gl_info->fbo_ops.glGenFramebuffers(1, &entry->id);
332 checkGLcall("glGenFramebuffers()");
333 TRACE("Created FBO %u.\n", entry->id);
335 return entry;
338 /* Context activation is done by the caller. */
339 static void context_reuse_fbo_entry(struct wined3d_context *context, GLenum target,
340 struct wined3d_surface **render_targets, struct wined3d_surface *depth_stencil,
341 DWORD color_location, DWORD ds_location, struct fbo_entry *entry)
343 const struct wined3d_gl_info *gl_info = context->gl_info;
345 context_bind_fbo(context, target, entry->id);
346 context_clean_fbo_attachments(gl_info, target);
348 memcpy(entry->render_targets, render_targets, gl_info->limits.buffers * sizeof(*entry->render_targets));
349 entry->depth_stencil = depth_stencil;
350 entry->color_location = color_location;
351 entry->ds_location = ds_location;
352 entry->attached = FALSE;
355 /* Context activation is done by the caller. */
356 static void context_destroy_fbo_entry(struct wined3d_context *context, struct fbo_entry *entry)
358 if (entry->id)
360 TRACE("Destroy FBO %u.\n", entry->id);
361 context_destroy_fbo(context, entry->id);
363 --context->fbo_entry_count;
364 list_remove(&entry->entry);
365 HeapFree(GetProcessHeap(), 0, entry->render_targets);
366 HeapFree(GetProcessHeap(), 0, entry);
369 /* Context activation is done by the caller. */
370 static struct fbo_entry *context_find_fbo_entry(struct wined3d_context *context, GLenum target,
371 struct wined3d_surface **render_targets, struct wined3d_surface *depth_stencil,
372 DWORD color_location, DWORD ds_location)
374 const struct wined3d_gl_info *gl_info = context->gl_info;
375 struct fbo_entry *entry;
377 if (depth_stencil && render_targets && render_targets[0])
379 if (depth_stencil->resource.width < render_targets[0]->resource.width ||
380 depth_stencil->resource.height < render_targets[0]->resource.height)
382 WARN("Depth stencil is smaller than the primary color buffer, disabling\n");
383 depth_stencil = NULL;
387 LIST_FOR_EACH_ENTRY(entry, &context->fbo_list, struct fbo_entry, entry)
389 if (!memcmp(entry->render_targets,
390 render_targets, gl_info->limits.buffers * sizeof(*entry->render_targets))
391 && entry->depth_stencil == depth_stencil && entry->color_location == color_location
392 && entry->ds_location == ds_location)
394 list_remove(&entry->entry);
395 list_add_head(&context->fbo_list, &entry->entry);
396 return entry;
400 if (context->fbo_entry_count < WINED3D_MAX_FBO_ENTRIES)
402 entry = context_create_fbo_entry(context, render_targets, depth_stencil, color_location, ds_location);
403 list_add_head(&context->fbo_list, &entry->entry);
404 ++context->fbo_entry_count;
406 else
408 entry = LIST_ENTRY(list_tail(&context->fbo_list), struct fbo_entry, entry);
409 context_reuse_fbo_entry(context, target, render_targets, depth_stencil, color_location, ds_location, entry);
410 list_remove(&entry->entry);
411 list_add_head(&context->fbo_list, &entry->entry);
414 return entry;
417 /* Context activation is done by the caller. */
418 static void context_apply_fbo_entry(struct wined3d_context *context, GLenum target, struct fbo_entry *entry)
420 const struct wined3d_gl_info *gl_info = context->gl_info;
421 unsigned int i;
422 GLuint read_binding, draw_binding;
424 if (entry->attached)
426 context_bind_fbo(context, target, entry->id);
427 return;
430 read_binding = context->fbo_read_binding;
431 draw_binding = context->fbo_draw_binding;
432 context_bind_fbo(context, GL_FRAMEBUFFER, entry->id);
434 /* Apply render targets */
435 for (i = 0; i < gl_info->limits.buffers; ++i)
437 context_attach_surface_fbo(context, target, i, entry->render_targets[i], entry->color_location);
440 /* Apply depth targets */
441 if (entry->depth_stencil)
442 surface_set_compatible_renderbuffer(entry->depth_stencil, entry->render_targets[0]);
443 context_attach_depth_stencil_fbo(context, target, entry->depth_stencil, entry->ds_location);
445 /* Set valid read and draw buffer bindings to satisfy pedantic pre-ES2_compatibility
446 * GL contexts requirements. */
447 gl_info->gl_ops.gl.p_glReadBuffer(GL_NONE);
448 context_set_draw_buffer(context, GL_NONE);
449 if (target != GL_FRAMEBUFFER)
451 if (target == GL_READ_FRAMEBUFFER)
452 context_bind_fbo(context, GL_DRAW_FRAMEBUFFER, draw_binding);
453 else
454 context_bind_fbo(context, GL_READ_FRAMEBUFFER, read_binding);
457 entry->attached = TRUE;
460 /* Context activation is done by the caller. */
461 static void context_apply_fbo_state(struct wined3d_context *context, GLenum target,
462 struct wined3d_surface **render_targets, struct wined3d_surface *depth_stencil,
463 DWORD color_location, DWORD ds_location)
465 struct fbo_entry *entry, *entry2;
467 LIST_FOR_EACH_ENTRY_SAFE(entry, entry2, &context->fbo_destroy_list, struct fbo_entry, entry)
469 context_destroy_fbo_entry(context, entry);
472 if (context->rebind_fbo)
474 context_bind_fbo(context, GL_FRAMEBUFFER, 0);
475 context->rebind_fbo = FALSE;
478 if (color_location == WINED3D_LOCATION_DRAWABLE)
480 context->current_fbo = NULL;
481 context_bind_fbo(context, target, 0);
483 else
485 context->current_fbo = context_find_fbo_entry(context, target, render_targets, depth_stencil,
486 color_location, ds_location);
487 context_apply_fbo_entry(context, target, context->current_fbo);
491 /* Context activation is done by the caller. */
492 void context_apply_fbo_state_blit(struct wined3d_context *context, GLenum target,
493 struct wined3d_surface *render_target, struct wined3d_surface *depth_stencil, DWORD location)
495 UINT clear_size = (context->gl_info->limits.buffers - 1) * sizeof(*context->blit_targets);
497 context->blit_targets[0] = render_target;
498 if (clear_size)
499 memset(&context->blit_targets[1], 0, clear_size);
500 context_apply_fbo_state(context, target, context->blit_targets, depth_stencil, location, location);
503 /* Context activation is done by the caller. */
504 void context_alloc_occlusion_query(struct wined3d_context *context, struct wined3d_occlusion_query *query)
506 const struct wined3d_gl_info *gl_info = context->gl_info;
508 if (context->free_occlusion_query_count)
510 query->id = context->free_occlusion_queries[--context->free_occlusion_query_count];
512 else
514 if (gl_info->supported[ARB_OCCLUSION_QUERY])
516 GL_EXTCALL(glGenQueries(1, &query->id));
517 checkGLcall("glGenQueries");
519 TRACE("Allocated occlusion query %u in context %p.\n", query->id, context);
521 else
523 WARN("Occlusion queries not supported, not allocating query id.\n");
524 query->id = 0;
528 query->context = context;
529 list_add_head(&context->occlusion_queries, &query->entry);
532 void context_free_occlusion_query(struct wined3d_occlusion_query *query)
534 struct wined3d_context *context = query->context;
536 list_remove(&query->entry);
537 query->context = NULL;
539 if (context->free_occlusion_query_count >= context->free_occlusion_query_size - 1)
541 UINT new_size = context->free_occlusion_query_size << 1;
542 GLuint *new_data = HeapReAlloc(GetProcessHeap(), 0, context->free_occlusion_queries,
543 new_size * sizeof(*context->free_occlusion_queries));
545 if (!new_data)
547 ERR("Failed to grow free list, leaking query %u in context %p.\n", query->id, context);
548 return;
551 context->free_occlusion_query_size = new_size;
552 context->free_occlusion_queries = new_data;
555 context->free_occlusion_queries[context->free_occlusion_query_count++] = query->id;
558 /* Context activation is done by the caller. */
559 void context_alloc_event_query(struct wined3d_context *context, struct wined3d_event_query *query)
561 const struct wined3d_gl_info *gl_info = context->gl_info;
563 if (context->free_event_query_count)
565 query->object = context->free_event_queries[--context->free_event_query_count];
567 else
569 if (gl_info->supported[ARB_SYNC])
571 /* Using ARB_sync, not much to do here. */
572 query->object.sync = NULL;
573 TRACE("Allocated event query %p in context %p.\n", query->object.sync, context);
575 else if (gl_info->supported[APPLE_FENCE])
577 GL_EXTCALL(glGenFencesAPPLE(1, &query->object.id));
578 checkGLcall("glGenFencesAPPLE");
580 TRACE("Allocated event query %u in context %p.\n", query->object.id, context);
582 else if(gl_info->supported[NV_FENCE])
584 GL_EXTCALL(glGenFencesNV(1, &query->object.id));
585 checkGLcall("glGenFencesNV");
587 TRACE("Allocated event query %u in context %p.\n", query->object.id, context);
589 else
591 WARN("Event queries not supported, not allocating query id.\n");
592 query->object.id = 0;
596 query->context = context;
597 list_add_head(&context->event_queries, &query->entry);
600 void context_free_event_query(struct wined3d_event_query *query)
602 struct wined3d_context *context = query->context;
604 list_remove(&query->entry);
605 query->context = NULL;
607 if (context->free_event_query_count >= context->free_event_query_size - 1)
609 UINT new_size = context->free_event_query_size << 1;
610 union wined3d_gl_query_object *new_data = HeapReAlloc(GetProcessHeap(), 0, context->free_event_queries,
611 new_size * sizeof(*context->free_event_queries));
613 if (!new_data)
615 ERR("Failed to grow free list, leaking query %u in context %p.\n", query->object.id, context);
616 return;
619 context->free_event_query_size = new_size;
620 context->free_event_queries = new_data;
623 context->free_event_queries[context->free_event_query_count++] = query->object;
626 /* Context activation is done by the caller. */
627 void context_alloc_timestamp_query(struct wined3d_context *context, struct wined3d_timestamp_query *query)
629 const struct wined3d_gl_info *gl_info = context->gl_info;
631 if (context->free_timestamp_query_count)
633 query->id = context->free_timestamp_queries[--context->free_timestamp_query_count];
635 else
637 GL_EXTCALL(glGenQueries(1, &query->id));
638 checkGLcall("glGenQueries");
640 TRACE("Allocated timestamp query %u in context %p.\n", query->id, context);
643 query->context = context;
644 list_add_head(&context->timestamp_queries, &query->entry);
647 void context_free_timestamp_query(struct wined3d_timestamp_query *query)
649 struct wined3d_context *context = query->context;
651 list_remove(&query->entry);
652 query->context = NULL;
654 if (context->free_timestamp_query_count >= context->free_timestamp_query_size - 1)
656 UINT new_size = context->free_timestamp_query_size << 1;
657 GLuint *new_data = HeapReAlloc(GetProcessHeap(), 0, context->free_timestamp_queries,
658 new_size * sizeof(*context->free_timestamp_queries));
660 if (!new_data)
662 ERR("Failed to grow free list, leaking query %u in context %p.\n", query->id, context);
663 return;
666 context->free_timestamp_query_size = new_size;
667 context->free_timestamp_queries = new_data;
670 context->free_timestamp_queries[context->free_timestamp_query_count++] = query->id;
673 typedef void (context_fbo_entry_func_t)(struct wined3d_context *context, struct fbo_entry *entry);
675 static void context_enum_surface_fbo_entries(const struct wined3d_device *device,
676 const struct wined3d_surface *surface, context_fbo_entry_func_t *callback)
678 UINT i;
680 for (i = 0; i < device->context_count; ++i)
682 struct wined3d_context *context = device->contexts[i];
683 const struct wined3d_gl_info *gl_info = context->gl_info;
684 struct fbo_entry *entry, *entry2;
686 if (context->current_rt == surface) context->current_rt = NULL;
688 LIST_FOR_EACH_ENTRY_SAFE(entry, entry2, &context->fbo_list, struct fbo_entry, entry)
690 UINT j;
692 if (entry->depth_stencil == surface)
694 callback(context, entry);
695 continue;
698 for (j = 0; j < gl_info->limits.buffers; ++j)
700 if (entry->render_targets[j] == surface)
702 callback(context, entry);
703 break;
710 static void context_queue_fbo_entry_destruction(struct wined3d_context *context, struct fbo_entry *entry)
712 list_remove(&entry->entry);
713 list_add_head(&context->fbo_destroy_list, &entry->entry);
716 void context_resource_released(const struct wined3d_device *device,
717 struct wined3d_resource *resource, enum wined3d_resource_type type)
719 if (!device->d3d_initialized) return;
721 switch (type)
723 case WINED3D_RTYPE_SURFACE:
724 context_enum_surface_fbo_entries(device, surface_from_resource(resource),
725 context_queue_fbo_entry_destruction);
726 break;
728 default:
729 break;
733 static void context_detach_fbo_entry(struct wined3d_context *context, struct fbo_entry *entry)
735 entry->attached = FALSE;
738 void context_resource_unloaded(const struct wined3d_device *device,
739 struct wined3d_resource *resource, enum wined3d_resource_type type)
741 switch (type)
743 case WINED3D_RTYPE_SURFACE:
744 context_enum_surface_fbo_entries(device, surface_from_resource(resource),
745 context_detach_fbo_entry);
746 break;
748 default:
749 break;
753 void context_surface_update(struct wined3d_context *context, const struct wined3d_surface *surface)
755 const struct wined3d_gl_info *gl_info = context->gl_info;
756 struct fbo_entry *entry = context->current_fbo;
757 unsigned int i;
759 if (!entry || context->rebind_fbo) return;
761 for (i = 0; i < gl_info->limits.buffers; ++i)
763 if (surface == entry->render_targets[i])
765 TRACE("Updated surface %p is bound as color attachment %u to the current FBO.\n", surface, i);
766 context->rebind_fbo = TRUE;
767 return;
771 if (surface == entry->depth_stencil)
773 TRACE("Updated surface %p is bound as depth attachment to the current FBO.\n", surface);
774 context->rebind_fbo = TRUE;
778 static BOOL context_restore_pixel_format(struct wined3d_context *ctx)
780 const struct wined3d_gl_info *gl_info = ctx->gl_info;
781 BOOL ret = FALSE;
783 if (ctx->restore_pf && IsWindow(ctx->restore_pf_win))
785 if (ctx->gl_info->supported[WGL_WINE_PIXEL_FORMAT_PASSTHROUGH])
787 HDC dc = GetDC(ctx->restore_pf_win);
788 if (dc)
790 if (!(ret = GL_EXTCALL(wglSetPixelFormatWINE(dc, ctx->restore_pf))))
792 ERR("wglSetPixelFormatWINE failed to restore pixel format %d on window %p.\n",
793 ctx->restore_pf, ctx->restore_pf_win);
795 ReleaseDC(ctx->restore_pf_win, dc);
798 else
800 ERR("can't restore pixel format %d on window %p\n", ctx->restore_pf, ctx->restore_pf_win);
804 ctx->restore_pf = 0;
805 ctx->restore_pf_win = NULL;
806 return ret;
809 static BOOL context_set_pixel_format(struct wined3d_context *context, HDC dc, BOOL private, int format)
811 const struct wined3d_gl_info *gl_info = context->gl_info;
812 int current;
814 if (dc == context->hdc && context->hdc_is_private && context->hdc_has_format)
815 return TRUE;
817 current = GetPixelFormat(dc);
818 if (current == format) goto success;
820 if (!current)
822 if (!SetPixelFormat(dc, format, NULL))
824 /* This may also happen if the dc belongs to a destroyed window. */
825 WARN("Failed to set pixel format %d on device context %p, last error %#x.\n",
826 format, dc, GetLastError());
827 return FALSE;
830 context->restore_pf = 0;
831 context->restore_pf_win = private ? NULL : WindowFromDC(dc);
832 goto success;
835 /* By default WGL doesn't allow pixel format adjustments but we need it
836 * here. For this reason there's a Wine specific wglSetPixelFormat()
837 * which allows us to set the pixel format multiple times. Only use it
838 * when really needed. */
839 if (gl_info->supported[WGL_WINE_PIXEL_FORMAT_PASSTHROUGH])
841 HWND win;
843 if (!GL_EXTCALL(wglSetPixelFormatWINE(dc, format)))
845 ERR("wglSetPixelFormatWINE failed to set pixel format %d on device context %p.\n",
846 format, dc);
847 return FALSE;
850 win = private ? NULL : WindowFromDC(dc);
851 if (win != context->restore_pf_win)
853 context_restore_pixel_format(context);
855 context->restore_pf = private ? 0 : current;
856 context->restore_pf_win = win;
859 goto success;
862 /* OpenGL doesn't allow pixel format adjustments. Print an error and
863 * continue using the old format. There's a big chance that the old
864 * format works although with a performance hit and perhaps rendering
865 * errors. */
866 ERR("Unable to set pixel format %d on device context %p. Already using format %d.\n",
867 format, dc, current);
868 return TRUE;
870 success:
871 if (dc == context->hdc && context->hdc_is_private)
872 context->hdc_has_format = TRUE;
873 return TRUE;
876 static BOOL context_set_gl_context(struct wined3d_context *ctx)
878 struct wined3d_swapchain *swapchain = ctx->swapchain;
879 BOOL backup = FALSE;
881 if (!context_set_pixel_format(ctx, ctx->hdc, ctx->hdc_is_private, ctx->pixel_format))
883 WARN("Failed to set pixel format %d on device context %p.\n",
884 ctx->pixel_format, ctx->hdc);
885 backup = TRUE;
888 if (backup || !wglMakeCurrent(ctx->hdc, ctx->glCtx))
890 HDC dc;
892 WARN("Failed to make GL context %p current on device context %p, last error %#x.\n",
893 ctx->glCtx, ctx->hdc, GetLastError());
894 ctx->valid = 0;
895 WARN("Trying fallback to the backup window.\n");
897 /* FIXME: If the context is destroyed it's no longer associated with
898 * a swapchain, so we can't use the swapchain to get a backup dc. To
899 * make this work windowless contexts would need to be handled by the
900 * device. */
901 if (ctx->destroyed)
903 FIXME("Unable to get backup dc for destroyed context %p.\n", ctx);
904 context_set_current(NULL);
905 return FALSE;
908 if (!(dc = swapchain_get_backup_dc(swapchain)))
910 context_set_current(NULL);
911 return FALSE;
914 if (!context_set_pixel_format(ctx, dc, TRUE, ctx->pixel_format))
916 ERR("Failed to set pixel format %d on device context %p.\n",
917 ctx->pixel_format, dc);
918 context_set_current(NULL);
919 return FALSE;
922 if (!wglMakeCurrent(dc, ctx->glCtx))
924 ERR("Fallback to backup window (dc %p) failed too, last error %#x.\n",
925 dc, GetLastError());
926 context_set_current(NULL);
927 return FALSE;
930 ctx->valid = 1;
932 ctx->needs_set = 0;
933 return TRUE;
936 static void context_restore_gl_context(const struct wined3d_gl_info *gl_info, HDC dc, HGLRC gl_ctx)
938 if (!wglMakeCurrent(dc, gl_ctx))
940 ERR("Failed to restore GL context %p on device context %p, last error %#x.\n",
941 gl_ctx, dc, GetLastError());
942 context_set_current(NULL);
946 static void context_update_window(struct wined3d_context *context)
948 if (context->win_handle == context->swapchain->win_handle)
949 return;
951 TRACE("Updating context %p window from %p to %p.\n",
952 context, context->win_handle, context->swapchain->win_handle);
954 if (context->hdc)
955 wined3d_release_dc(context->win_handle, context->hdc);
957 context->win_handle = context->swapchain->win_handle;
958 context->hdc_is_private = FALSE;
959 context->hdc_has_format = FALSE;
960 context->needs_set = 1;
961 context->valid = 1;
963 if (!(context->hdc = GetDC(context->win_handle)))
965 ERR("Failed to get a device context for window %p.\n", context->win_handle);
966 context->valid = 0;
970 static void context_destroy_gl_resources(struct wined3d_context *context)
972 const struct wined3d_gl_info *gl_info = context->gl_info;
973 struct wined3d_timestamp_query *timestamp_query;
974 struct wined3d_occlusion_query *occlusion_query;
975 struct wined3d_event_query *event_query;
976 struct fbo_entry *entry, *entry2;
977 HGLRC restore_ctx;
978 HDC restore_dc;
979 unsigned int i;
981 restore_ctx = wglGetCurrentContext();
982 restore_dc = wglGetCurrentDC();
984 if (restore_ctx == context->glCtx)
985 restore_ctx = NULL;
986 else if (context->valid)
987 context_set_gl_context(context);
989 LIST_FOR_EACH_ENTRY(timestamp_query, &context->timestamp_queries, struct wined3d_timestamp_query, entry)
991 if (context->valid)
992 GL_EXTCALL(glDeleteQueries(1, &timestamp_query->id));
993 timestamp_query->context = NULL;
996 LIST_FOR_EACH_ENTRY(occlusion_query, &context->occlusion_queries, struct wined3d_occlusion_query, entry)
998 if (context->valid && gl_info->supported[ARB_OCCLUSION_QUERY])
999 GL_EXTCALL(glDeleteQueries(1, &occlusion_query->id));
1000 occlusion_query->context = NULL;
1003 LIST_FOR_EACH_ENTRY(event_query, &context->event_queries, struct wined3d_event_query, entry)
1005 if (context->valid)
1007 if (gl_info->supported[ARB_SYNC])
1009 if (event_query->object.sync) GL_EXTCALL(glDeleteSync(event_query->object.sync));
1011 else if (gl_info->supported[APPLE_FENCE]) GL_EXTCALL(glDeleteFencesAPPLE(1, &event_query->object.id));
1012 else if (gl_info->supported[NV_FENCE]) GL_EXTCALL(glDeleteFencesNV(1, &event_query->object.id));
1014 event_query->context = NULL;
1017 LIST_FOR_EACH_ENTRY_SAFE(entry, entry2, &context->fbo_destroy_list, struct fbo_entry, entry)
1019 if (!context->valid) entry->id = 0;
1020 context_destroy_fbo_entry(context, entry);
1023 LIST_FOR_EACH_ENTRY_SAFE(entry, entry2, &context->fbo_list, struct fbo_entry, entry)
1025 if (!context->valid) entry->id = 0;
1026 context_destroy_fbo_entry(context, entry);
1029 if (context->valid)
1031 if (context->dummy_arbfp_prog)
1033 GL_EXTCALL(glDeleteProgramsARB(1, &context->dummy_arbfp_prog));
1036 if (gl_info->supported[ARB_TIMER_QUERY])
1037 GL_EXTCALL(glDeleteQueries(context->free_timestamp_query_count, context->free_timestamp_queries));
1039 if (gl_info->supported[ARB_OCCLUSION_QUERY])
1040 GL_EXTCALL(glDeleteQueries(context->free_occlusion_query_count, context->free_occlusion_queries));
1042 if (gl_info->supported[ARB_SYNC])
1044 for (i = 0; i < context->free_event_query_count; ++i)
1046 GL_EXTCALL(glDeleteSync(context->free_event_queries[i].sync));
1049 else if (gl_info->supported[APPLE_FENCE])
1051 for (i = 0; i < context->free_event_query_count; ++i)
1053 GL_EXTCALL(glDeleteFencesAPPLE(1, &context->free_event_queries[i].id));
1056 else if (gl_info->supported[NV_FENCE])
1058 for (i = 0; i < context->free_event_query_count; ++i)
1060 GL_EXTCALL(glDeleteFencesNV(1, &context->free_event_queries[i].id));
1064 checkGLcall("context cleanup");
1067 HeapFree(GetProcessHeap(), 0, context->free_timestamp_queries);
1068 HeapFree(GetProcessHeap(), 0, context->free_occlusion_queries);
1069 HeapFree(GetProcessHeap(), 0, context->free_event_queries);
1071 context_restore_pixel_format(context);
1072 if (restore_ctx)
1074 context_restore_gl_context(gl_info, restore_dc, restore_ctx);
1076 else if (wglGetCurrentContext() && !wglMakeCurrent(NULL, NULL))
1078 ERR("Failed to disable GL context.\n");
1081 wined3d_release_dc(context->win_handle, context->hdc);
1083 if (!wglDeleteContext(context->glCtx))
1085 DWORD err = GetLastError();
1086 ERR("wglDeleteContext(%p) failed, last error %#x.\n", context->glCtx, err);
1090 DWORD context_get_tls_idx(void)
1092 return wined3d_context_tls_idx;
1095 void context_set_tls_idx(DWORD idx)
1097 wined3d_context_tls_idx = idx;
1100 struct wined3d_context *context_get_current(void)
1102 return TlsGetValue(wined3d_context_tls_idx);
1105 BOOL context_set_current(struct wined3d_context *ctx)
1107 struct wined3d_context *old = context_get_current();
1109 if (old == ctx)
1111 TRACE("Already using D3D context %p.\n", ctx);
1112 return TRUE;
1115 if (old)
1117 if (old->destroyed)
1119 TRACE("Switching away from destroyed context %p.\n", old);
1120 context_destroy_gl_resources(old);
1121 HeapFree(GetProcessHeap(), 0, (void *)old->gl_info);
1122 HeapFree(GetProcessHeap(), 0, old);
1124 else
1126 old->current = 0;
1130 if (ctx)
1132 if (!ctx->valid)
1134 ERR("Trying to make invalid context %p current\n", ctx);
1135 return FALSE;
1138 TRACE("Switching to D3D context %p, GL context %p, device context %p.\n", ctx, ctx->glCtx, ctx->hdc);
1139 if (!context_set_gl_context(ctx))
1140 return FALSE;
1141 ctx->current = 1;
1143 else if(wglGetCurrentContext())
1145 TRACE("Clearing current D3D context.\n");
1146 if (!wglMakeCurrent(NULL, NULL))
1148 DWORD err = GetLastError();
1149 ERR("Failed to clear current GL context, last error %#x.\n", err);
1150 TlsSetValue(wined3d_context_tls_idx, NULL);
1151 return FALSE;
1155 return TlsSetValue(wined3d_context_tls_idx, ctx);
1158 void context_release(struct wined3d_context *context)
1160 TRACE("Releasing context %p, level %u.\n", context, context->level);
1162 if (WARN_ON(d3d))
1164 if (!context->level)
1165 WARN("Context %p is not active.\n", context);
1166 else if (context != context_get_current())
1167 WARN("Context %p is not the current context.\n", context);
1170 if (!--context->level)
1172 if (context_restore_pixel_format(context))
1173 context->needs_set = 1;
1174 if (context->restore_ctx)
1176 TRACE("Restoring GL context %p on device context %p.\n", context->restore_ctx, context->restore_dc);
1177 context_restore_gl_context(context->gl_info, context->restore_dc, context->restore_ctx);
1178 context->restore_ctx = NULL;
1179 context->restore_dc = NULL;
1184 static void context_enter(struct wined3d_context *context)
1186 TRACE("Entering context %p, level %u.\n", context, context->level + 1);
1188 if (!context->level++)
1190 const struct wined3d_context *current_context = context_get_current();
1191 HGLRC current_gl = wglGetCurrentContext();
1193 if (current_gl && (!current_context || current_context->glCtx != current_gl))
1195 TRACE("Another GL context (%p on device context %p) is already current.\n",
1196 current_gl, wglGetCurrentDC());
1197 context->restore_ctx = current_gl;
1198 context->restore_dc = wglGetCurrentDC();
1199 context->needs_set = 1;
1201 else if (!context->needs_set && !(context->hdc_is_private && context->hdc_has_format)
1202 && context->pixel_format != GetPixelFormat(context->hdc))
1203 context->needs_set = 1;
1207 void context_invalidate_state(struct wined3d_context *context, DWORD state)
1209 DWORD rep = context->state_table[state].representative;
1210 DWORD idx;
1211 BYTE shift;
1213 if (isStateDirty(context, rep)) return;
1215 context->dirtyArray[context->numDirtyEntries++] = rep;
1216 idx = rep / (sizeof(*context->isStateDirty) * CHAR_BIT);
1217 shift = rep & ((sizeof(*context->isStateDirty) * CHAR_BIT) - 1);
1218 context->isStateDirty[idx] |= (1 << shift);
1221 /* This function takes care of wined3d pixel format selection. */
1222 static int context_choose_pixel_format(const struct wined3d_device *device, HDC hdc,
1223 const struct wined3d_format *color_format, const struct wined3d_format *ds_format,
1224 BOOL auxBuffers, BOOL findCompatible)
1226 int iPixelFormat=0;
1227 BYTE redBits, greenBits, blueBits, alphaBits, colorBits;
1228 BYTE depthBits=0, stencilBits=0;
1229 unsigned int current_value;
1230 unsigned int cfg_count = device->adapter->cfg_count;
1231 unsigned int i;
1233 TRACE("device %p, dc %p, color_format %s, ds_format %s, aux_buffers %#x, find_compatible %#x.\n",
1234 device, hdc, debug_d3dformat(color_format->id), debug_d3dformat(ds_format->id),
1235 auxBuffers, findCompatible);
1237 if (!getColorBits(color_format, &redBits, &greenBits, &blueBits, &alphaBits, &colorBits))
1239 ERR("Unable to get color bits for format %s (%#x)!\n",
1240 debug_d3dformat(color_format->id), color_format->id);
1241 return 0;
1244 getDepthStencilBits(ds_format, &depthBits, &stencilBits);
1246 current_value = 0;
1247 for (i = 0; i < cfg_count; ++i)
1249 const struct wined3d_pixel_format *cfg = &device->adapter->cfgs[i];
1250 unsigned int value;
1252 /* For now only accept RGBA formats. Perhaps some day we will
1253 * allow floating point formats for pbuffers. */
1254 if (cfg->iPixelType != WGL_TYPE_RGBA_ARB)
1255 continue;
1256 /* In window mode we need a window drawable format and double buffering. */
1257 if (!(cfg->windowDrawable && cfg->doubleBuffer))
1258 continue;
1259 if (cfg->redSize < redBits)
1260 continue;
1261 if (cfg->greenSize < greenBits)
1262 continue;
1263 if (cfg->blueSize < blueBits)
1264 continue;
1265 if (cfg->alphaSize < alphaBits)
1266 continue;
1267 if (cfg->depthSize < depthBits)
1268 continue;
1269 if (stencilBits && cfg->stencilSize != stencilBits)
1270 continue;
1271 /* Check multisampling support. */
1272 if (cfg->numSamples)
1273 continue;
1275 value = 1;
1276 /* We try to locate a format which matches our requirements exactly. In case of
1277 * depth it is no problem to emulate 16-bit using e.g. 24-bit, so accept that. */
1278 if (cfg->depthSize == depthBits)
1279 value += 1;
1280 if (cfg->stencilSize == stencilBits)
1281 value += 2;
1282 if (cfg->alphaSize == alphaBits)
1283 value += 4;
1284 /* We like to have aux buffers in backbuffer mode */
1285 if (auxBuffers && cfg->auxBuffers)
1286 value += 8;
1287 if (cfg->redSize == redBits
1288 && cfg->greenSize == greenBits
1289 && cfg->blueSize == blueBits)
1290 value += 16;
1292 if (value > current_value)
1294 iPixelFormat = cfg->iPixelFormat;
1295 current_value = value;
1299 /* When findCompatible is set and no suitable format was found, let ChoosePixelFormat choose a pixel format in order not to crash. */
1300 if(!iPixelFormat && !findCompatible) {
1301 ERR("Can't find a suitable iPixelFormat\n");
1302 return FALSE;
1303 } else if(!iPixelFormat) {
1304 PIXELFORMATDESCRIPTOR pfd;
1306 TRACE("Falling back to ChoosePixelFormat as we weren't able to find an exactly matching pixel format\n");
1307 /* PixelFormat selection */
1308 ZeroMemory(&pfd, sizeof(pfd));
1309 pfd.nSize = sizeof(pfd);
1310 pfd.nVersion = 1;
1311 pfd.dwFlags = PFD_SUPPORT_OPENGL | PFD_DOUBLEBUFFER | PFD_DRAW_TO_WINDOW;/*PFD_GENERIC_ACCELERATED*/
1312 pfd.iPixelType = PFD_TYPE_RGBA;
1313 pfd.cAlphaBits = alphaBits;
1314 pfd.cColorBits = colorBits;
1315 pfd.cDepthBits = depthBits;
1316 pfd.cStencilBits = stencilBits;
1317 pfd.iLayerType = PFD_MAIN_PLANE;
1319 iPixelFormat = ChoosePixelFormat(hdc, &pfd);
1320 if(!iPixelFormat) {
1321 /* If this happens something is very wrong as ChoosePixelFormat barely fails */
1322 ERR("Can't find a suitable iPixelFormat\n");
1323 return FALSE;
1327 TRACE("Found iPixelFormat=%d for ColorFormat=%s, DepthStencilFormat=%s\n",
1328 iPixelFormat, debug_d3dformat(color_format->id), debug_d3dformat(ds_format->id));
1329 return iPixelFormat;
1332 /* Context activation is done by the caller. */
1333 static void bind_dummy_textures(const struct wined3d_device *device, const struct wined3d_context *context)
1335 const struct wined3d_gl_info *gl_info = context->gl_info;
1336 unsigned int i, count = min(MAX_COMBINED_SAMPLERS, gl_info->limits.combined_samplers);
1338 for (i = 0; i < count; ++i)
1340 GL_EXTCALL(glActiveTexture(GL_TEXTURE0 + i));
1341 checkGLcall("glActiveTexture");
1343 gl_info->gl_ops.gl.p_glBindTexture(GL_TEXTURE_2D, device->dummy_texture_2d[i]);
1344 checkGLcall("glBindTexture");
1346 if (gl_info->supported[ARB_TEXTURE_RECTANGLE])
1348 gl_info->gl_ops.gl.p_glBindTexture(GL_TEXTURE_RECTANGLE_ARB, device->dummy_texture_rect[i]);
1349 checkGLcall("glBindTexture");
1352 if (gl_info->supported[EXT_TEXTURE3D])
1354 gl_info->gl_ops.gl.p_glBindTexture(GL_TEXTURE_3D, device->dummy_texture_3d[i]);
1355 checkGLcall("glBindTexture");
1358 if (gl_info->supported[ARB_TEXTURE_CUBE_MAP])
1360 gl_info->gl_ops.gl.p_glBindTexture(GL_TEXTURE_CUBE_MAP, device->dummy_texture_cube[i]);
1361 checkGLcall("glBindTexture");
1366 BOOL context_debug_output_enabled(const struct wined3d_gl_info *gl_info)
1368 return gl_info->supported[ARB_DEBUG_OUTPUT]
1369 && (ERR_ON(d3d) || FIXME_ON(d3d) || WARN_ON(d3d_perf));
1372 static void WINE_GLAPI wined3d_debug_callback(GLenum source, GLenum type, GLuint id,
1373 GLenum severity, GLsizei length, const char *message, void *ctx)
1375 switch (type)
1377 case GL_DEBUG_TYPE_ERROR_ARB:
1378 ERR("%p: %s.\n", ctx, debugstr_an(message, length));
1379 break;
1381 case GL_DEBUG_TYPE_DEPRECATED_BEHAVIOR_ARB:
1382 case GL_DEBUG_TYPE_UNDEFINED_BEHAVIOR_ARB:
1383 case GL_DEBUG_TYPE_PORTABILITY_ARB:
1384 FIXME("%p: %s.\n", ctx, debugstr_an(message, length));
1385 break;
1387 case GL_DEBUG_TYPE_PERFORMANCE_ARB:
1388 WARN_(d3d_perf)("%p: %s.\n", ctx, debugstr_an(message, length));
1389 break;
1391 default:
1392 FIXME("ctx %p, type %#x: %s.\n", ctx, type, debugstr_an(message, length));
1393 break;
1397 struct wined3d_context *context_create(struct wined3d_swapchain *swapchain,
1398 struct wined3d_surface *target, const struct wined3d_format *ds_format)
1400 struct wined3d_device *device = swapchain->device;
1401 const struct wined3d_gl_info *gl_info = &device->adapter->gl_info;
1402 const struct wined3d_format *color_format;
1403 struct wined3d_context *ret;
1404 BOOL auxBuffers = FALSE;
1405 HGLRC ctx, share_ctx;
1406 int pixel_format;
1407 unsigned int s;
1408 int swap_interval;
1409 DWORD state;
1410 HDC hdc;
1411 BOOL hdc_is_private = FALSE;
1413 TRACE("swapchain %p, target %p, window %p.\n", swapchain, target, swapchain->win_handle);
1415 ret = HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, sizeof(*ret));
1416 if (!ret)
1417 return NULL;
1419 ret->blit_targets = HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY,
1420 gl_info->limits.buffers * sizeof(*ret->blit_targets));
1421 if (!ret->blit_targets)
1422 goto out;
1424 ret->draw_buffers = HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY,
1425 gl_info->limits.buffers * sizeof(*ret->draw_buffers));
1426 if (!ret->draw_buffers)
1427 goto out;
1429 ret->free_timestamp_query_size = 4;
1430 ret->free_timestamp_queries = HeapAlloc(GetProcessHeap(), 0,
1431 ret->free_timestamp_query_size * sizeof(*ret->free_timestamp_queries));
1432 if (!ret->free_timestamp_queries)
1433 goto out;
1434 list_init(&ret->timestamp_queries);
1436 ret->free_occlusion_query_size = 4;
1437 ret->free_occlusion_queries = HeapAlloc(GetProcessHeap(), 0,
1438 ret->free_occlusion_query_size * sizeof(*ret->free_occlusion_queries));
1439 if (!ret->free_occlusion_queries)
1440 goto out;
1442 list_init(&ret->occlusion_queries);
1444 ret->free_event_query_size = 4;
1445 ret->free_event_queries = HeapAlloc(GetProcessHeap(), 0,
1446 ret->free_event_query_size * sizeof(*ret->free_event_queries));
1447 if (!ret->free_event_queries)
1448 goto out;
1450 list_init(&ret->event_queries);
1451 list_init(&ret->fbo_list);
1452 list_init(&ret->fbo_destroy_list);
1454 if (!device->shader_backend->shader_allocate_context_data(ret))
1456 ERR("Failed to allocate shader backend context data.\n");
1457 goto out;
1459 if (!device->adapter->fragment_pipe->allocate_context_data(ret))
1461 ERR("Failed to allocate fragment pipeline context data.\n");
1462 goto out;
1465 /* Initialize the texture unit mapping to a 1:1 mapping */
1466 for (s = 0; s < MAX_COMBINED_SAMPLERS; ++s)
1468 if (s < gl_info->limits.fragment_samplers)
1470 ret->tex_unit_map[s] = s;
1471 ret->rev_tex_unit_map[s] = s;
1473 else
1475 ret->tex_unit_map[s] = WINED3D_UNMAPPED_STAGE;
1476 ret->rev_tex_unit_map[s] = WINED3D_UNMAPPED_STAGE;
1480 if (!(hdc = GetDC(swapchain->win_handle)))
1482 WARN("Failed to retrieve device context, trying swapchain backup.\n");
1484 if ((hdc = swapchain_get_backup_dc(swapchain)))
1485 hdc_is_private = TRUE;
1486 else
1488 ERR("Failed to retrieve a device context.\n");
1489 goto out;
1493 color_format = target->resource.format;
1495 /* In case of ORM_BACKBUFFER, make sure to request an alpha component for
1496 * X4R4G4B4/X8R8G8B8 as we might need it for the backbuffer. */
1497 if (wined3d_settings.offscreen_rendering_mode == ORM_BACKBUFFER)
1499 auxBuffers = TRUE;
1501 if (color_format->id == WINED3DFMT_B4G4R4X4_UNORM)
1502 color_format = wined3d_get_format(gl_info, WINED3DFMT_B4G4R4A4_UNORM);
1503 else if (color_format->id == WINED3DFMT_B8G8R8X8_UNORM)
1504 color_format = wined3d_get_format(gl_info, WINED3DFMT_B8G8R8A8_UNORM);
1507 /* DirectDraw supports 8bit paletted render targets and these are used by
1508 * old games like StarCraft and C&C. Most modern hardware doesn't support
1509 * 8bit natively so we perform some form of 8bit -> 32bit conversion. The
1510 * conversion (ab)uses the alpha component for storing the palette index.
1511 * For this reason we require a format with 8bit alpha, so request
1512 * A8R8G8B8. */
1513 if (color_format->id == WINED3DFMT_P8_UINT)
1514 color_format = wined3d_get_format(gl_info, WINED3DFMT_B8G8R8A8_UNORM);
1516 /* Try to find a pixel format which matches our requirements. */
1517 pixel_format = context_choose_pixel_format(device, hdc, color_format, ds_format, auxBuffers, FALSE);
1519 /* Try to locate a compatible format if we weren't able to find anything. */
1520 if (!pixel_format)
1522 TRACE("Trying to locate a compatible pixel format because an exact match failed.\n");
1523 pixel_format = context_choose_pixel_format(device, hdc, color_format, ds_format, auxBuffers, TRUE);
1526 /* If we still don't have a pixel format, something is very wrong as ChoosePixelFormat barely fails */
1527 if (!pixel_format)
1529 ERR("Can't find a suitable pixel format.\n");
1530 goto out;
1533 context_enter(ret);
1535 ret->gl_info = gl_info;
1537 if (!context_set_pixel_format(ret, hdc, hdc_is_private, pixel_format))
1539 ERR("Failed to set pixel format %d on device context %p.\n", pixel_format, hdc);
1540 context_release(ret);
1541 goto out;
1544 share_ctx = device->context_count ? device->contexts[0]->glCtx : NULL;
1545 if (gl_info->p_wglCreateContextAttribsARB)
1547 unsigned int ctx_attrib_idx = 0;
1548 GLint ctx_attribs[3];
1550 if (context_debug_output_enabled(gl_info))
1552 ctx_attribs[ctx_attrib_idx++] = WGL_CONTEXT_FLAGS_ARB;
1553 ctx_attribs[ctx_attrib_idx++] = WGL_CONTEXT_DEBUG_BIT_ARB;
1555 ctx_attribs[ctx_attrib_idx] = 0;
1557 if (!(ctx = gl_info->p_wglCreateContextAttribsARB(hdc, share_ctx, ctx_attribs)))
1559 ERR("Failed to create a WGL context.\n");
1560 context_release(ret);
1561 goto out;
1564 else
1566 if (!(ctx = wglCreateContext(hdc)))
1568 ERR("Failed to create a WGL context.\n");
1569 context_release(ret);
1570 goto out;
1573 if (share_ctx && !wglShareLists(share_ctx, ctx))
1575 ERR("wglShareLists(%p, %p) failed, last error %#x.\n", share_ctx, ctx, GetLastError());
1576 context_release(ret);
1577 if (!wglDeleteContext(ctx))
1578 ERR("wglDeleteContext(%p) failed, last error %#x.\n", ctx, GetLastError());
1579 goto out;
1583 if (!device_context_add(device, ret))
1585 ERR("Failed to add the newly created context to the context list\n");
1586 context_release(ret);
1587 if (!wglDeleteContext(ctx))
1588 ERR("wglDeleteContext(%p) failed, last error %#x.\n", ctx, GetLastError());
1589 goto out;
1592 ret->d3d_info = &device->adapter->d3d_info;
1593 ret->state_table = device->StateTable;
1595 /* Mark all states dirty to force a proper initialization of the states
1596 * on the first use of the context. */
1597 for (state = 0; state <= STATE_HIGHEST; ++state)
1599 if (ret->state_table[state].representative)
1600 context_invalidate_state(ret, state);
1603 ret->swapchain = swapchain;
1604 ret->current_rt = target;
1605 ret->tid = GetCurrentThreadId();
1607 ret->render_offscreen = wined3d_resource_is_offscreen(&target->container->resource);
1608 ret->draw_buffers_mask = context_generate_rt_mask(GL_BACK);
1609 ret->valid = 1;
1611 ret->glCtx = ctx;
1612 ret->win_handle = swapchain->win_handle;
1613 ret->hdc = hdc;
1614 ret->hdc_is_private = hdc_is_private;
1615 ret->hdc_has_format = TRUE;
1616 ret->pixel_format = pixel_format;
1617 ret->needs_set = 1;
1619 /* Set up the context defaults */
1620 if (!context_set_current(ret))
1622 ERR("Cannot activate context to set up defaults.\n");
1623 device_context_remove(device, ret);
1624 context_release(ret);
1625 if (!wglDeleteContext(ctx))
1626 ERR("wglDeleteContext(%p) failed, last error %#x.\n", ctx, GetLastError());
1627 goto out;
1630 if (context_debug_output_enabled(gl_info))
1632 GL_EXTCALL(glDebugMessageCallbackARB(wined3d_debug_callback, ret));
1633 if (TRACE_ON(d3d_synchronous))
1634 gl_info->gl_ops.gl.p_glEnable(GL_DEBUG_OUTPUT_SYNCHRONOUS_ARB);
1635 GL_EXTCALL(glDebugMessageControlARB(GL_DONT_CARE, GL_DONT_CARE, GL_DONT_CARE, 0, NULL, GL_FALSE));
1636 if (ERR_ON(d3d))
1638 GL_EXTCALL(glDebugMessageControlARB(GL_DONT_CARE, GL_DEBUG_TYPE_ERROR_ARB,
1639 GL_DONT_CARE, 0, NULL, GL_TRUE));
1641 if (FIXME_ON(d3d))
1643 GL_EXTCALL(glDebugMessageControlARB(GL_DONT_CARE, GL_DEBUG_TYPE_DEPRECATED_BEHAVIOR_ARB,
1644 GL_DONT_CARE, 0, NULL, GL_TRUE));
1645 GL_EXTCALL(glDebugMessageControlARB(GL_DONT_CARE, GL_DEBUG_TYPE_UNDEFINED_BEHAVIOR_ARB,
1646 GL_DONT_CARE, 0, NULL, GL_TRUE));
1647 GL_EXTCALL(glDebugMessageControlARB(GL_DONT_CARE, GL_DEBUG_TYPE_PORTABILITY_ARB,
1648 GL_DONT_CARE, 0, NULL, GL_TRUE));
1650 if (WARN_ON(d3d_perf))
1652 GL_EXTCALL(glDebugMessageControlARB(GL_DONT_CARE, GL_DEBUG_TYPE_PERFORMANCE_ARB,
1653 GL_DONT_CARE, 0, NULL, GL_TRUE));
1657 switch (swapchain->desc.swap_interval)
1659 case WINED3DPRESENT_INTERVAL_IMMEDIATE:
1660 swap_interval = 0;
1661 break;
1662 case WINED3DPRESENT_INTERVAL_DEFAULT:
1663 case WINED3DPRESENT_INTERVAL_ONE:
1664 swap_interval = 1;
1665 break;
1666 case WINED3DPRESENT_INTERVAL_TWO:
1667 swap_interval = 2;
1668 break;
1669 case WINED3DPRESENT_INTERVAL_THREE:
1670 swap_interval = 3;
1671 break;
1672 case WINED3DPRESENT_INTERVAL_FOUR:
1673 swap_interval = 4;
1674 break;
1675 default:
1676 FIXME("Unknown swap interval %#x.\n", swapchain->desc.swap_interval);
1677 swap_interval = 1;
1680 if (gl_info->supported[WGL_EXT_SWAP_CONTROL])
1682 if (!GL_EXTCALL(wglSwapIntervalEXT(swap_interval)))
1683 ERR("wglSwapIntervalEXT failed to set swap interval %d for context %p, last error %#x\n",
1684 swap_interval, ret, GetLastError());
1687 gl_info->gl_ops.gl.p_glGetIntegerv(GL_AUX_BUFFERS, &ret->aux_buffers);
1689 TRACE("Setting up the screen\n");
1691 gl_info->gl_ops.gl.p_glLightModeli(GL_LIGHT_MODEL_LOCAL_VIEWER, GL_TRUE);
1692 checkGLcall("glLightModeli(GL_LIGHT_MODEL_LOCAL_VIEWER, GL_TRUE);");
1694 gl_info->gl_ops.gl.p_glTexEnvf(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_COMBINE_EXT);
1695 checkGLcall("glTexEnvf(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_COMBINE_EXT);");
1697 gl_info->gl_ops.gl.p_glLightModeli(GL_LIGHT_MODEL_COLOR_CONTROL, GL_SEPARATE_SPECULAR_COLOR);
1698 checkGLcall("glLightModeli(GL_LIGHT_MODEL_COLOR_CONTROL, GL_SEPARATE_SPECULAR_COLOR);");
1700 gl_info->gl_ops.gl.p_glPixelStorei(GL_PACK_ALIGNMENT, device->surface_alignment);
1701 checkGLcall("glPixelStorei(GL_PACK_ALIGNMENT, device->surface_alignment);");
1702 gl_info->gl_ops.gl.p_glPixelStorei(GL_UNPACK_ALIGNMENT, 1);
1703 checkGLcall("glPixelStorei(GL_UNPACK_ALIGNMENT, device->surface_alignment);");
1705 if (gl_info->supported[ARB_VERTEX_BLEND])
1707 /* Direct3D always uses n-1 weights for n world matrices and uses
1708 * 1 - sum for the last one this is equal to GL_WEIGHT_SUM_UNITY_ARB.
1709 * Enabling it doesn't do anything unless GL_VERTEX_BLEND_ARB isn't
1710 * enabled as well. */
1711 gl_info->gl_ops.gl.p_glEnable(GL_WEIGHT_SUM_UNITY_ARB);
1712 checkGLcall("glEnable(GL_WEIGHT_SUM_UNITY_ARB)");
1714 if (gl_info->supported[NV_TEXTURE_SHADER2])
1716 /* Set up the previous texture input for all shader units. This applies to bump mapping, and in d3d
1717 * the previous texture where to source the offset from is always unit - 1.
1719 for (s = 1; s < gl_info->limits.textures; ++s)
1721 context_active_texture(ret, gl_info, s);
1722 gl_info->gl_ops.gl.p_glTexEnvi(GL_TEXTURE_SHADER_NV,
1723 GL_PREVIOUS_TEXTURE_INPUT_NV, GL_TEXTURE0_ARB + s - 1);
1724 checkGLcall("glTexEnvi(GL_TEXTURE_SHADER_NV, GL_PREVIOUS_TEXTURE_INPUT_NV, ...");
1727 if (gl_info->supported[ARB_FRAGMENT_PROGRAM])
1729 /* MacOS(radeon X1600 at least, but most likely others too) refuses to draw if GLSL and ARBFP are
1730 * enabled, but the currently bound arbfp program is 0. Enabling ARBFP with prog 0 is invalid, but
1731 * GLSL should bypass this. This causes problems in programs that never use the fixed function pipeline,
1732 * because the ARBFP extension is enabled by the ARBFP pipeline at context creation, but no program
1733 * is ever assigned.
1735 * So make sure a program is assigned to each context. The first real ARBFP use will set a different
1736 * program and the dummy program is destroyed when the context is destroyed.
1738 static const char dummy_program[] =
1739 "!!ARBfp1.0\n"
1740 "MOV result.color, fragment.color.primary;\n"
1741 "END\n";
1742 GL_EXTCALL(glGenProgramsARB(1, &ret->dummy_arbfp_prog));
1743 GL_EXTCALL(glBindProgramARB(GL_FRAGMENT_PROGRAM_ARB, ret->dummy_arbfp_prog));
1744 GL_EXTCALL(glProgramStringARB(GL_FRAGMENT_PROGRAM_ARB, GL_PROGRAM_FORMAT_ASCII_ARB, strlen(dummy_program), dummy_program));
1747 if (gl_info->supported[ARB_POINT_SPRITE])
1749 for (s = 0; s < gl_info->limits.textures; ++s)
1751 context_active_texture(ret, gl_info, s);
1752 gl_info->gl_ops.gl.p_glTexEnvi(GL_POINT_SPRITE_ARB, GL_COORD_REPLACE_ARB, GL_TRUE);
1753 checkGLcall("glTexEnvi(GL_POINT_SPRITE_ARB, GL_COORD_REPLACE_ARB, GL_TRUE)");
1757 if (gl_info->supported[ARB_PROVOKING_VERTEX])
1759 GL_EXTCALL(glProvokingVertex(GL_FIRST_VERTEX_CONVENTION));
1761 else if (gl_info->supported[EXT_PROVOKING_VERTEX])
1763 GL_EXTCALL(glProvokingVertexEXT(GL_FIRST_VERTEX_CONVENTION_EXT));
1765 ret->shader_update_mask = (1 << WINED3D_SHADER_TYPE_PIXEL)
1766 | (1 << WINED3D_SHADER_TYPE_VERTEX)
1767 | (1 << WINED3D_SHADER_TYPE_GEOMETRY);
1769 /* If this happens to be the first context for the device, dummy textures
1770 * are not created yet. In that case, they will be created (and bound) by
1771 * create_dummy_textures right after this context is initialized. */
1772 if (device->dummy_texture_2d[0])
1773 bind_dummy_textures(device, ret);
1775 TRACE("Created context %p.\n", ret);
1777 return ret;
1779 out:
1780 device->shader_backend->shader_free_context_data(ret);
1781 device->adapter->fragment_pipe->free_context_data(ret);
1782 HeapFree(GetProcessHeap(), 0, ret->free_event_queries);
1783 HeapFree(GetProcessHeap(), 0, ret->free_occlusion_queries);
1784 HeapFree(GetProcessHeap(), 0, ret->free_timestamp_queries);
1785 HeapFree(GetProcessHeap(), 0, ret->draw_buffers);
1786 HeapFree(GetProcessHeap(), 0, ret->blit_targets);
1787 HeapFree(GetProcessHeap(), 0, ret);
1788 return NULL;
1791 void context_destroy(struct wined3d_device *device, struct wined3d_context *context)
1793 BOOL destroy;
1795 TRACE("Destroying ctx %p\n", context);
1797 if (context->tid == GetCurrentThreadId() || !context->current)
1799 context_destroy_gl_resources(context);
1800 TlsSetValue(wined3d_context_tls_idx, NULL);
1801 destroy = TRUE;
1803 else
1805 /* Make a copy of gl_info for context_destroy_gl_resources use, the one
1806 in wined3d_adapter may go away in the meantime */
1807 struct wined3d_gl_info *gl_info = HeapAlloc(GetProcessHeap(), 0, sizeof(*gl_info));
1808 *gl_info = *context->gl_info;
1809 context->gl_info = gl_info;
1810 context->destroyed = 1;
1811 destroy = FALSE;
1814 device->shader_backend->shader_free_context_data(context);
1815 device->adapter->fragment_pipe->free_context_data(context);
1816 HeapFree(GetProcessHeap(), 0, context->draw_buffers);
1817 HeapFree(GetProcessHeap(), 0, context->blit_targets);
1818 device_context_remove(device, context);
1819 if (destroy) HeapFree(GetProcessHeap(), 0, context);
1822 /* Context activation is done by the caller. */
1823 static void set_blit_dimension(const struct wined3d_gl_info *gl_info, UINT width, UINT height)
1825 const GLdouble projection[] =
1827 2.0 / width, 0.0, 0.0, 0.0,
1828 0.0, 2.0 / height, 0.0, 0.0,
1829 0.0, 0.0, 2.0, 0.0,
1830 -1.0, -1.0, -1.0, 1.0,
1833 gl_info->gl_ops.gl.p_glMatrixMode(GL_PROJECTION);
1834 checkGLcall("glMatrixMode(GL_PROJECTION)");
1835 gl_info->gl_ops.gl.p_glLoadMatrixd(projection);
1836 checkGLcall("glLoadMatrixd");
1837 gl_info->gl_ops.gl.p_glViewport(0, 0, width, height);
1838 checkGLcall("glViewport");
1841 static void context_get_rt_size(const struct wined3d_context *context, SIZE *size)
1843 const struct wined3d_surface *rt = context->current_rt;
1845 if (rt->container->swapchain && rt->container->swapchain->front_buffer == rt->container)
1847 RECT window_size;
1849 GetClientRect(context->win_handle, &window_size);
1850 size->cx = window_size.right - window_size.left;
1851 size->cy = window_size.bottom - window_size.top;
1853 return;
1856 size->cx = rt->resource.width;
1857 size->cy = rt->resource.height;
1860 /*****************************************************************************
1861 * SetupForBlit
1863 * Sets up a context for DirectDraw blitting.
1864 * All texture units are disabled, texture unit 0 is set as current unit
1865 * fog, lighting, blending, alpha test, z test, scissor test, culling disabled
1866 * color writing enabled for all channels
1867 * register combiners disabled, shaders disabled
1868 * world matrix is set to identity, texture matrix 0 too
1869 * projection matrix is setup for drawing screen coordinates
1871 * Params:
1872 * This: Device to activate the context for
1873 * context: Context to setup
1875 *****************************************************************************/
1876 /* Context activation is done by the caller. */
1877 static void SetupForBlit(const struct wined3d_device *device, struct wined3d_context *context)
1879 int i;
1880 const struct wined3d_gl_info *gl_info = context->gl_info;
1881 DWORD sampler;
1882 SIZE rt_size;
1884 TRACE("Setting up context %p for blitting\n", context);
1886 context_get_rt_size(context, &rt_size);
1888 if (context->last_was_blit)
1890 if (context->blit_w != rt_size.cx || context->blit_h != rt_size.cy)
1892 set_blit_dimension(gl_info, rt_size.cx, rt_size.cy);
1893 context->blit_w = rt_size.cx;
1894 context->blit_h = rt_size.cy;
1895 /* No need to dirtify here, the states are still dirtified because
1896 * they weren't applied since the last SetupForBlit() call. */
1898 TRACE("Context is already set up for blitting, nothing to do\n");
1899 return;
1901 context->last_was_blit = TRUE;
1903 /* Disable all textures. The caller can then bind a texture it wants to blit
1904 * from
1906 * The blitting code uses (for now) the fixed function pipeline, so make sure to reset all fixed
1907 * function texture unit. No need to care for higher samplers
1909 for (i = gl_info->limits.textures - 1; i > 0 ; --i)
1911 sampler = context->rev_tex_unit_map[i];
1912 context_active_texture(context, gl_info, i);
1914 if (gl_info->supported[ARB_TEXTURE_CUBE_MAP])
1916 gl_info->gl_ops.gl.p_glDisable(GL_TEXTURE_CUBE_MAP_ARB);
1917 checkGLcall("glDisable GL_TEXTURE_CUBE_MAP_ARB");
1919 gl_info->gl_ops.gl.p_glDisable(GL_TEXTURE_3D);
1920 checkGLcall("glDisable GL_TEXTURE_3D");
1921 if (gl_info->supported[ARB_TEXTURE_RECTANGLE])
1923 gl_info->gl_ops.gl.p_glDisable(GL_TEXTURE_RECTANGLE_ARB);
1924 checkGLcall("glDisable GL_TEXTURE_RECTANGLE_ARB");
1926 gl_info->gl_ops.gl.p_glDisable(GL_TEXTURE_2D);
1927 checkGLcall("glDisable GL_TEXTURE_2D");
1929 gl_info->gl_ops.gl.p_glTexEnvi(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_REPLACE);
1930 checkGLcall("glTexEnvi(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_REPLACE);");
1932 if (sampler != WINED3D_UNMAPPED_STAGE)
1934 if (sampler < MAX_TEXTURES)
1935 context_invalidate_state(context, STATE_TEXTURESTAGE(sampler, WINED3D_TSS_COLOR_OP));
1936 context_invalidate_state(context, STATE_SAMPLER(sampler));
1939 if (gl_info->supported[ARB_SAMPLER_OBJECTS])
1940 GL_EXTCALL(glBindSampler(0, 0));
1941 context_active_texture(context, gl_info, 0);
1943 sampler = context->rev_tex_unit_map[0];
1945 if (gl_info->supported[ARB_TEXTURE_CUBE_MAP])
1947 gl_info->gl_ops.gl.p_glDisable(GL_TEXTURE_CUBE_MAP_ARB);
1948 checkGLcall("glDisable GL_TEXTURE_CUBE_MAP_ARB");
1950 gl_info->gl_ops.gl.p_glDisable(GL_TEXTURE_3D);
1951 checkGLcall("glDisable GL_TEXTURE_3D");
1952 if (gl_info->supported[ARB_TEXTURE_RECTANGLE])
1954 gl_info->gl_ops.gl.p_glDisable(GL_TEXTURE_RECTANGLE_ARB);
1955 checkGLcall("glDisable GL_TEXTURE_RECTANGLE_ARB");
1957 gl_info->gl_ops.gl.p_glDisable(GL_TEXTURE_2D);
1958 checkGLcall("glDisable GL_TEXTURE_2D");
1960 gl_info->gl_ops.gl.p_glTexEnvi(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_REPLACE);
1962 gl_info->gl_ops.gl.p_glMatrixMode(GL_TEXTURE);
1963 checkGLcall("glMatrixMode(GL_TEXTURE)");
1964 gl_info->gl_ops.gl.p_glLoadIdentity();
1965 checkGLcall("glLoadIdentity()");
1967 if (gl_info->supported[EXT_TEXTURE_LOD_BIAS])
1969 gl_info->gl_ops.gl.p_glTexEnvf(GL_TEXTURE_FILTER_CONTROL_EXT,
1970 GL_TEXTURE_LOD_BIAS_EXT, 0.0f);
1971 checkGLcall("glTexEnvf GL_TEXTURE_LOD_BIAS_EXT ...");
1974 if (sampler != WINED3D_UNMAPPED_STAGE)
1976 if (sampler < MAX_TEXTURES)
1978 context_invalidate_state(context, STATE_TRANSFORM(WINED3D_TS_TEXTURE0 + sampler));
1979 context_invalidate_state(context, STATE_TEXTURESTAGE(sampler, WINED3D_TSS_COLOR_OP));
1981 context_invalidate_state(context, STATE_SAMPLER(sampler));
1984 /* Other misc states */
1985 gl_info->gl_ops.gl.p_glDisable(GL_ALPHA_TEST);
1986 checkGLcall("glDisable(GL_ALPHA_TEST)");
1987 context_invalidate_state(context, STATE_RENDER(WINED3D_RS_ALPHATESTENABLE));
1988 gl_info->gl_ops.gl.p_glDisable(GL_LIGHTING);
1989 checkGLcall("glDisable GL_LIGHTING");
1990 context_invalidate_state(context, STATE_RENDER(WINED3D_RS_LIGHTING));
1991 gl_info->gl_ops.gl.p_glDisable(GL_DEPTH_TEST);
1992 checkGLcall("glDisable GL_DEPTH_TEST");
1993 context_invalidate_state(context, STATE_RENDER(WINED3D_RS_ZENABLE));
1994 glDisableWINE(GL_FOG);
1995 checkGLcall("glDisable GL_FOG");
1996 context_invalidate_state(context, STATE_RENDER(WINED3D_RS_FOGENABLE));
1997 gl_info->gl_ops.gl.p_glDisable(GL_BLEND);
1998 checkGLcall("glDisable GL_BLEND");
1999 context_invalidate_state(context, STATE_RENDER(WINED3D_RS_ALPHABLENDENABLE));
2000 gl_info->gl_ops.gl.p_glDisable(GL_CULL_FACE);
2001 checkGLcall("glDisable GL_CULL_FACE");
2002 context_invalidate_state(context, STATE_RENDER(WINED3D_RS_CULLMODE));
2003 gl_info->gl_ops.gl.p_glDisable(GL_STENCIL_TEST);
2004 checkGLcall("glDisable GL_STENCIL_TEST");
2005 context_invalidate_state(context, STATE_RENDER(WINED3D_RS_STENCILENABLE));
2006 gl_info->gl_ops.gl.p_glDisable(GL_SCISSOR_TEST);
2007 checkGLcall("glDisable GL_SCISSOR_TEST");
2008 context_invalidate_state(context, STATE_RENDER(WINED3D_RS_SCISSORTESTENABLE));
2009 if (gl_info->supported[ARB_POINT_SPRITE])
2011 gl_info->gl_ops.gl.p_glDisable(GL_POINT_SPRITE_ARB);
2012 checkGLcall("glDisable GL_POINT_SPRITE_ARB");
2013 context_invalidate_state(context, STATE_RENDER(WINED3D_RS_POINTSPRITEENABLE));
2015 gl_info->gl_ops.gl.p_glColorMask(GL_TRUE, GL_TRUE,GL_TRUE,GL_TRUE);
2016 checkGLcall("glColorMask");
2017 context_invalidate_state(context, STATE_RENDER(WINED3D_RS_COLORWRITEENABLE));
2018 context_invalidate_state(context, STATE_RENDER(WINED3D_RS_COLORWRITEENABLE1));
2019 context_invalidate_state(context, STATE_RENDER(WINED3D_RS_COLORWRITEENABLE2));
2020 context_invalidate_state(context, STATE_RENDER(WINED3D_RS_COLORWRITEENABLE3));
2021 if (gl_info->supported[EXT_SECONDARY_COLOR])
2023 gl_info->gl_ops.gl.p_glDisable(GL_COLOR_SUM_EXT);
2024 context_invalidate_state(context, STATE_RENDER(WINED3D_RS_SPECULARENABLE));
2025 checkGLcall("glDisable(GL_COLOR_SUM_EXT)");
2028 /* Setup transforms */
2029 gl_info->gl_ops.gl.p_glMatrixMode(GL_MODELVIEW);
2030 checkGLcall("glMatrixMode(GL_MODELVIEW)");
2031 gl_info->gl_ops.gl.p_glLoadIdentity();
2032 checkGLcall("glLoadIdentity()");
2033 context_invalidate_state(context, STATE_TRANSFORM(WINED3D_TS_WORLD_MATRIX(0)));
2035 context->last_was_rhw = TRUE;
2036 context_invalidate_state(context, STATE_VDECL); /* because of last_was_rhw = TRUE */
2038 gl_info->gl_ops.gl.p_glDisable(GL_CLIP_PLANE0); checkGLcall("glDisable(clip plane 0)");
2039 gl_info->gl_ops.gl.p_glDisable(GL_CLIP_PLANE1); checkGLcall("glDisable(clip plane 1)");
2040 gl_info->gl_ops.gl.p_glDisable(GL_CLIP_PLANE2); checkGLcall("glDisable(clip plane 2)");
2041 gl_info->gl_ops.gl.p_glDisable(GL_CLIP_PLANE3); checkGLcall("glDisable(clip plane 3)");
2042 gl_info->gl_ops.gl.p_glDisable(GL_CLIP_PLANE4); checkGLcall("glDisable(clip plane 4)");
2043 gl_info->gl_ops.gl.p_glDisable(GL_CLIP_PLANE5); checkGLcall("glDisable(clip plane 5)");
2044 context_invalidate_state(context, STATE_RENDER(WINED3D_RS_CLIPPING));
2046 set_blit_dimension(gl_info, rt_size.cx, rt_size.cy);
2048 /* Disable shaders */
2049 device->shader_backend->shader_disable(device->shader_priv, context);
2051 context->blit_w = rt_size.cx;
2052 context->blit_h = rt_size.cy;
2053 context_invalidate_state(context, STATE_VIEWPORT);
2054 context_invalidate_state(context, STATE_TRANSFORM(WINED3D_TS_PROJECTION));
2057 static inline BOOL is_rt_mask_onscreen(DWORD rt_mask)
2059 return rt_mask & (1 << 31);
2062 static inline GLenum draw_buffer_from_rt_mask(DWORD rt_mask)
2064 return rt_mask & ~(1 << 31);
2067 /* Context activation is done by the caller. */
2068 static void context_apply_draw_buffers(struct wined3d_context *context, DWORD rt_mask)
2070 const struct wined3d_gl_info *gl_info = context->gl_info;
2072 if (!rt_mask)
2074 gl_info->gl_ops.gl.p_glDrawBuffer(GL_NONE);
2075 checkGLcall("glDrawBuffer()");
2077 else if (is_rt_mask_onscreen(rt_mask))
2079 gl_info->gl_ops.gl.p_glDrawBuffer(draw_buffer_from_rt_mask(rt_mask));
2080 checkGLcall("glDrawBuffer()");
2082 else
2084 if (wined3d_settings.offscreen_rendering_mode == ORM_FBO)
2086 unsigned int i = 0;
2088 while (rt_mask)
2090 if (rt_mask & 1)
2091 context->draw_buffers[i] = GL_COLOR_ATTACHMENT0 + i;
2092 else
2093 context->draw_buffers[i] = GL_NONE;
2095 rt_mask >>= 1;
2096 ++i;
2099 if (gl_info->supported[ARB_DRAW_BUFFERS])
2101 GL_EXTCALL(glDrawBuffers(i, context->draw_buffers));
2102 checkGLcall("glDrawBuffers()");
2104 else
2106 gl_info->gl_ops.gl.p_glDrawBuffer(context->draw_buffers[0]);
2107 checkGLcall("glDrawBuffer()");
2110 else
2112 ERR("Unexpected draw buffers mask with backbuffer ORM.\n");
2117 /* Context activation is done by the caller. */
2118 void context_set_draw_buffer(struct wined3d_context *context, GLenum buffer)
2120 const struct wined3d_gl_info *gl_info = context->gl_info;
2121 DWORD *current_mask = context->current_fbo ? &context->current_fbo->rt_mask : &context->draw_buffers_mask;
2122 DWORD new_mask = context_generate_rt_mask(buffer);
2124 if (new_mask == *current_mask)
2125 return;
2127 gl_info->gl_ops.gl.p_glDrawBuffer(buffer);
2128 checkGLcall("glDrawBuffer()");
2130 *current_mask = new_mask;
2133 /* Context activation is done by the caller. */
2134 void context_active_texture(struct wined3d_context *context, const struct wined3d_gl_info *gl_info, unsigned int unit)
2136 GL_EXTCALL(glActiveTexture(GL_TEXTURE0 + unit));
2137 checkGLcall("glActiveTexture");
2138 context->active_texture = unit;
2141 void context_bind_texture(struct wined3d_context *context, GLenum target, GLuint name)
2143 const struct wined3d_gl_info *gl_info = context->gl_info;
2144 DWORD unit = context->active_texture;
2145 DWORD old_texture_type = context->texture_type[unit];
2147 if (name)
2149 gl_info->gl_ops.gl.p_glBindTexture(target, name);
2150 checkGLcall("glBindTexture");
2152 else
2154 target = GL_NONE;
2157 if (old_texture_type != target)
2159 const struct wined3d_device *device = context->swapchain->device;
2161 switch (old_texture_type)
2163 case GL_NONE:
2164 /* nothing to do */
2165 break;
2166 case GL_TEXTURE_2D:
2167 gl_info->gl_ops.gl.p_glBindTexture(GL_TEXTURE_2D, device->dummy_texture_2d[unit]);
2168 checkGLcall("glBindTexture");
2169 break;
2170 case GL_TEXTURE_RECTANGLE_ARB:
2171 gl_info->gl_ops.gl.p_glBindTexture(GL_TEXTURE_RECTANGLE_ARB, device->dummy_texture_rect[unit]);
2172 checkGLcall("glBindTexture");
2173 break;
2174 case GL_TEXTURE_CUBE_MAP:
2175 gl_info->gl_ops.gl.p_glBindTexture(GL_TEXTURE_CUBE_MAP, device->dummy_texture_cube[unit]);
2176 checkGLcall("glBindTexture");
2177 break;
2178 case GL_TEXTURE_3D:
2179 gl_info->gl_ops.gl.p_glBindTexture(GL_TEXTURE_3D, device->dummy_texture_3d[unit]);
2180 checkGLcall("glBindTexture");
2181 break;
2182 default:
2183 ERR("Unexpected texture target %#x\n", old_texture_type);
2186 context->texture_type[unit] = target;
2190 static void context_set_render_offscreen(struct wined3d_context *context, BOOL offscreen)
2192 if (context->render_offscreen == offscreen) return;
2194 context_invalidate_state(context, STATE_POINTSPRITECOORDORIGIN);
2195 context_invalidate_state(context, STATE_TRANSFORM(WINED3D_TS_PROJECTION));
2196 context_invalidate_state(context, STATE_VIEWPORT);
2197 context_invalidate_state(context, STATE_SCISSORRECT);
2198 context_invalidate_state(context, STATE_FRONTFACE);
2199 context->render_offscreen = offscreen;
2202 static BOOL match_depth_stencil_format(const struct wined3d_format *existing,
2203 const struct wined3d_format *required)
2205 BYTE existing_depth, existing_stencil, required_depth, required_stencil;
2207 if (existing == required)
2208 return TRUE;
2209 if ((existing->flags[WINED3D_GL_RES_TYPE_TEX_2D] & WINED3DFMT_FLAG_FLOAT)
2210 != (required->flags[WINED3D_GL_RES_TYPE_TEX_2D] & WINED3DFMT_FLAG_FLOAT))
2211 return FALSE;
2213 getDepthStencilBits(existing, &existing_depth, &existing_stencil);
2214 getDepthStencilBits(required, &required_depth, &required_stencil);
2216 if(existing_depth < required_depth) return FALSE;
2217 /* If stencil bits are used the exact amount is required - otherwise wrapping
2218 * won't work correctly */
2219 if(required_stencil && required_stencil != existing_stencil) return FALSE;
2220 return TRUE;
2223 /* The caller provides a context */
2224 static void context_validate_onscreen_formats(struct wined3d_context *context,
2225 const struct wined3d_rendertarget_view *depth_stencil)
2227 /* Onscreen surfaces are always in a swapchain */
2228 struct wined3d_swapchain *swapchain = context->current_rt->container->swapchain;
2230 if (context->render_offscreen || !depth_stencil) return;
2231 if (match_depth_stencil_format(swapchain->ds_format, depth_stencil->format)) return;
2233 /* TODO: If the requested format would satisfy the needs of the existing one(reverse match),
2234 * or no onscreen depth buffer was created, the OpenGL drawable could be changed to the new
2235 * format. */
2236 WARN("Depth stencil format is not supported by WGL, rendering the backbuffer in an FBO\n");
2238 /* The currently active context is the necessary context to access the swapchain's onscreen buffers */
2239 surface_load_location(context->current_rt, WINED3D_LOCATION_TEXTURE_RGB);
2240 swapchain->render_to_fbo = TRUE;
2241 swapchain_update_draw_bindings(swapchain);
2242 context_set_render_offscreen(context, TRUE);
2245 static DWORD context_generate_rt_mask_no_fbo(const struct wined3d_device *device, const struct wined3d_surface *rt)
2247 if (!rt || rt->resource.format->id == WINED3DFMT_NULL)
2248 return 0;
2249 else if (rt->container->swapchain)
2250 return context_generate_rt_mask_from_surface(rt);
2251 else
2252 return context_generate_rt_mask(device->offscreenBuffer);
2255 /* Context activation is done by the caller. */
2256 void context_apply_blit_state(struct wined3d_context *context, const struct wined3d_device *device)
2258 struct wined3d_surface *rt = context->current_rt;
2259 DWORD rt_mask, *cur_mask;
2261 if (wined3d_settings.offscreen_rendering_mode == ORM_FBO)
2263 context_validate_onscreen_formats(context, NULL);
2265 if (context->render_offscreen)
2267 wined3d_texture_load(rt->container, context, FALSE);
2269 context_apply_fbo_state_blit(context, GL_FRAMEBUFFER, rt, NULL, rt->container->resource.draw_binding);
2270 if (rt->resource.format->id != WINED3DFMT_NULL)
2271 rt_mask = 1;
2272 else
2273 rt_mask = 0;
2275 else
2277 context->current_fbo = NULL;
2278 context_bind_fbo(context, GL_FRAMEBUFFER, 0);
2279 rt_mask = context_generate_rt_mask_from_surface(rt);
2282 else
2284 rt_mask = context_generate_rt_mask_no_fbo(device, rt);
2287 cur_mask = context->current_fbo ? &context->current_fbo->rt_mask : &context->draw_buffers_mask;
2289 if (rt_mask != *cur_mask)
2291 context_apply_draw_buffers(context, rt_mask);
2292 *cur_mask = rt_mask;
2295 if (wined3d_settings.offscreen_rendering_mode == ORM_FBO)
2297 context_check_fbo_status(context, GL_FRAMEBUFFER);
2300 SetupForBlit(device, context);
2301 context_invalidate_state(context, STATE_FRAMEBUFFER);
2304 static BOOL context_validate_rt_config(UINT rt_count, struct wined3d_rendertarget_view * const *rts,
2305 const struct wined3d_rendertarget_view *ds)
2307 unsigned int i;
2309 if (ds) return TRUE;
2311 for (i = 0; i < rt_count; ++i)
2313 if (rts[i] && rts[i]->format->id != WINED3DFMT_NULL)
2314 return TRUE;
2317 WARN("Invalid render target config, need at least one attachment.\n");
2318 return FALSE;
2321 /* Context activation is done by the caller. */
2322 BOOL context_apply_clear_state(struct wined3d_context *context, const struct wined3d_device *device,
2323 UINT rt_count, const struct wined3d_fb_state *fb)
2325 struct wined3d_rendertarget_view **rts = fb->render_targets;
2326 struct wined3d_rendertarget_view *dsv = fb->depth_stencil;
2327 const struct wined3d_gl_info *gl_info = context->gl_info;
2328 DWORD rt_mask = 0, *cur_mask;
2329 UINT i;
2331 if (isStateDirty(context, STATE_FRAMEBUFFER) || fb != &device->fb
2332 || rt_count != context->gl_info->limits.buffers)
2334 if (!context_validate_rt_config(rt_count, rts, dsv))
2335 return FALSE;
2337 if (wined3d_settings.offscreen_rendering_mode == ORM_FBO)
2339 context_validate_onscreen_formats(context, dsv);
2341 if (!rt_count || wined3d_resource_is_offscreen(rts[0]->resource))
2343 for (i = 0; i < rt_count; ++i)
2345 context->blit_targets[i] = wined3d_rendertarget_view_get_surface(rts[i]);
2346 if (rts[i] && rts[i]->format->id != WINED3DFMT_NULL)
2347 rt_mask |= (1 << i);
2349 while (i < context->gl_info->limits.buffers)
2351 context->blit_targets[i] = NULL;
2352 ++i;
2354 context_apply_fbo_state(context, GL_FRAMEBUFFER, context->blit_targets,
2355 wined3d_rendertarget_view_get_surface(dsv),
2356 rt_count ? rts[0]->resource->draw_binding : 0,
2357 dsv ? dsv->resource->draw_binding : 0);
2359 else
2361 context_apply_fbo_state(context, GL_FRAMEBUFFER, NULL, NULL,
2362 WINED3D_LOCATION_DRAWABLE, WINED3D_LOCATION_DRAWABLE);
2363 rt_mask = context_generate_rt_mask_from_surface(wined3d_rendertarget_view_get_surface(rts[0]));
2366 /* If the framebuffer is not the device's fb the device's fb has to be reapplied
2367 * next draw. Otherwise we could mark the framebuffer state clean here, once the
2368 * state management allows this */
2369 context_invalidate_state(context, STATE_FRAMEBUFFER);
2371 else
2373 rt_mask = context_generate_rt_mask_no_fbo(device,
2374 rt_count ? wined3d_rendertarget_view_get_surface(rts[0]) : NULL);
2377 else if (wined3d_settings.offscreen_rendering_mode == ORM_FBO
2378 && (!rt_count || wined3d_resource_is_offscreen(rts[0]->resource)))
2380 for (i = 0; i < rt_count; ++i)
2382 if (rts[i] && rts[i]->format->id != WINED3DFMT_NULL)
2383 rt_mask |= (1 << i);
2386 else
2388 rt_mask = context_generate_rt_mask_no_fbo(device,
2389 rt_count ? wined3d_rendertarget_view_get_surface(rts[0]) : NULL);
2392 cur_mask = context->current_fbo ? &context->current_fbo->rt_mask : &context->draw_buffers_mask;
2394 if (rt_mask != *cur_mask)
2396 context_apply_draw_buffers(context, rt_mask);
2397 *cur_mask = rt_mask;
2398 context_invalidate_state(context, STATE_FRAMEBUFFER);
2401 if (wined3d_settings.offscreen_rendering_mode == ORM_FBO)
2403 context_check_fbo_status(context, GL_FRAMEBUFFER);
2406 if (context->last_was_blit)
2407 context->last_was_blit = FALSE;
2409 /* Blending and clearing should be orthogonal, but tests on the nvidia
2410 * driver show that disabling blending when clearing improves the clearing
2411 * performance incredibly. */
2412 gl_info->gl_ops.gl.p_glDisable(GL_BLEND);
2413 gl_info->gl_ops.gl.p_glEnable(GL_SCISSOR_TEST);
2414 checkGLcall("glEnable GL_SCISSOR_TEST");
2416 context_invalidate_state(context, STATE_RENDER(WINED3D_RS_ALPHABLENDENABLE));
2417 context_invalidate_state(context, STATE_RENDER(WINED3D_RS_SCISSORTESTENABLE));
2418 context_invalidate_state(context, STATE_SCISSORRECT);
2420 return TRUE;
2423 static DWORD find_draw_buffers_mask(const struct wined3d_context *context, const struct wined3d_device *device)
2425 const struct wined3d_state *state = &device->state;
2426 struct wined3d_rendertarget_view **rts = state->fb->render_targets;
2427 struct wined3d_shader *ps = state->shader[WINED3D_SHADER_TYPE_PIXEL];
2428 DWORD rt_mask, rt_mask_bits;
2429 unsigned int i;
2431 if (wined3d_settings.offscreen_rendering_mode != ORM_FBO)
2432 return context_generate_rt_mask_no_fbo(device, wined3d_rendertarget_view_get_surface(rts[0]));
2433 else if (!context->render_offscreen)
2434 return context_generate_rt_mask_from_surface(wined3d_rendertarget_view_get_surface(rts[0]));
2436 rt_mask = ps ? ps->reg_maps.rt_mask : 1;
2437 rt_mask &= context->d3d_info->valid_rt_mask;
2438 rt_mask_bits = rt_mask;
2439 i = 0;
2440 while (rt_mask_bits)
2442 rt_mask_bits &= ~(1 << i);
2443 if (!rts[i] || rts[i]->format->id == WINED3DFMT_NULL)
2444 rt_mask &= ~(1 << i);
2446 i++;
2449 return rt_mask;
2452 /* Context activation is done by the caller. */
2453 void context_state_fb(struct wined3d_context *context, const struct wined3d_state *state, DWORD state_id)
2455 const struct wined3d_device *device = context->swapchain->device;
2456 const struct wined3d_fb_state *fb = state->fb;
2457 DWORD rt_mask = find_draw_buffers_mask(context, device);
2458 DWORD *cur_mask;
2460 if (wined3d_settings.offscreen_rendering_mode == ORM_FBO)
2462 if (!context->render_offscreen)
2464 context_apply_fbo_state(context, GL_FRAMEBUFFER, NULL, NULL,
2465 WINED3D_LOCATION_DRAWABLE, WINED3D_LOCATION_DRAWABLE);
2467 else
2469 unsigned int i;
2471 for (i = 0; i < context->gl_info->limits.buffers; ++i)
2473 context->blit_targets[i] = wined3d_rendertarget_view_get_surface(fb->render_targets[i]);
2475 context_apply_fbo_state(context, GL_FRAMEBUFFER, context->blit_targets,
2476 wined3d_rendertarget_view_get_surface(fb->depth_stencil),
2477 fb->render_targets[0]->resource->draw_binding,
2478 fb->depth_stencil ? fb->depth_stencil->resource->draw_binding : 0);
2482 cur_mask = context->current_fbo ? &context->current_fbo->rt_mask : &context->draw_buffers_mask;
2483 if (rt_mask != *cur_mask)
2485 context_apply_draw_buffers(context, rt_mask);
2486 *cur_mask = rt_mask;
2490 static void context_map_stage(struct wined3d_context *context, DWORD stage, DWORD unit)
2492 DWORD i = context->rev_tex_unit_map[unit];
2493 DWORD j = context->tex_unit_map[stage];
2495 context->tex_unit_map[stage] = unit;
2496 if (i != WINED3D_UNMAPPED_STAGE && i != stage)
2497 context->tex_unit_map[i] = WINED3D_UNMAPPED_STAGE;
2499 context->rev_tex_unit_map[unit] = stage;
2500 if (j != WINED3D_UNMAPPED_STAGE && j != unit)
2501 context->rev_tex_unit_map[j] = WINED3D_UNMAPPED_STAGE;
2504 static void context_invalidate_texture_stage(struct wined3d_context *context, DWORD stage)
2506 DWORD i;
2508 for (i = 0; i <= WINED3D_HIGHEST_TEXTURE_STATE; ++i)
2509 context_invalidate_state(context, STATE_TEXTURESTAGE(stage, i));
2512 static void context_update_fixed_function_usage_map(struct wined3d_context *context,
2513 const struct wined3d_state *state)
2515 UINT i, start, end;
2517 context->fixed_function_usage_map = 0;
2518 for (i = 0; i < MAX_TEXTURES; ++i)
2520 enum wined3d_texture_op color_op = state->texture_states[i][WINED3D_TSS_COLOR_OP];
2521 enum wined3d_texture_op alpha_op = state->texture_states[i][WINED3D_TSS_ALPHA_OP];
2522 DWORD color_arg1 = state->texture_states[i][WINED3D_TSS_COLOR_ARG1] & WINED3DTA_SELECTMASK;
2523 DWORD color_arg2 = state->texture_states[i][WINED3D_TSS_COLOR_ARG2] & WINED3DTA_SELECTMASK;
2524 DWORD color_arg3 = state->texture_states[i][WINED3D_TSS_COLOR_ARG0] & WINED3DTA_SELECTMASK;
2525 DWORD alpha_arg1 = state->texture_states[i][WINED3D_TSS_ALPHA_ARG1] & WINED3DTA_SELECTMASK;
2526 DWORD alpha_arg2 = state->texture_states[i][WINED3D_TSS_ALPHA_ARG2] & WINED3DTA_SELECTMASK;
2527 DWORD alpha_arg3 = state->texture_states[i][WINED3D_TSS_ALPHA_ARG0] & WINED3DTA_SELECTMASK;
2529 /* Not used, and disable higher stages. */
2530 if (color_op == WINED3D_TOP_DISABLE)
2531 break;
2533 if (((color_arg1 == WINED3DTA_TEXTURE) && color_op != WINED3D_TOP_SELECT_ARG2)
2534 || ((color_arg2 == WINED3DTA_TEXTURE) && color_op != WINED3D_TOP_SELECT_ARG1)
2535 || ((color_arg3 == WINED3DTA_TEXTURE)
2536 && (color_op == WINED3D_TOP_MULTIPLY_ADD || color_op == WINED3D_TOP_LERP))
2537 || ((alpha_arg1 == WINED3DTA_TEXTURE) && alpha_op != WINED3D_TOP_SELECT_ARG2)
2538 || ((alpha_arg2 == WINED3DTA_TEXTURE) && alpha_op != WINED3D_TOP_SELECT_ARG1)
2539 || ((alpha_arg3 == WINED3DTA_TEXTURE)
2540 && (alpha_op == WINED3D_TOP_MULTIPLY_ADD || alpha_op == WINED3D_TOP_LERP)))
2541 context->fixed_function_usage_map |= (1 << i);
2543 if ((color_op == WINED3D_TOP_BUMPENVMAP || color_op == WINED3D_TOP_BUMPENVMAP_LUMINANCE)
2544 && i < MAX_TEXTURES - 1)
2545 context->fixed_function_usage_map |= (1 << (i + 1));
2548 if (i < context->lowest_disabled_stage)
2550 start = i;
2551 end = context->lowest_disabled_stage;
2553 else
2555 start = context->lowest_disabled_stage;
2556 end = i;
2559 context->lowest_disabled_stage = i;
2560 for (i = start + 1; i < end; ++i)
2562 context_invalidate_state(context, STATE_TEXTURESTAGE(i, WINED3D_TSS_COLOR_OP));
2566 static void context_map_fixed_function_samplers(struct wined3d_context *context,
2567 const struct wined3d_state *state)
2569 unsigned int i, tex;
2570 WORD ffu_map;
2571 const struct wined3d_d3d_info *d3d_info = context->d3d_info;
2573 context_update_fixed_function_usage_map(context, state);
2574 ffu_map = context->fixed_function_usage_map;
2576 if (d3d_info->limits.ffp_textures == d3d_info->limits.ffp_blend_stages
2577 || context->lowest_disabled_stage <= d3d_info->limits.ffp_textures)
2579 for (i = 0; ffu_map; ffu_map >>= 1, ++i)
2581 if (!(ffu_map & 1))
2582 continue;
2584 if (context->tex_unit_map[i] != i)
2586 context_map_stage(context, i, i);
2587 context_invalidate_state(context, STATE_SAMPLER(i));
2588 context_invalidate_texture_stage(context, i);
2591 return;
2594 /* Now work out the mapping */
2595 tex = 0;
2596 for (i = 0; ffu_map; ffu_map >>= 1, ++i)
2598 if (!(ffu_map & 1))
2599 continue;
2601 if (context->tex_unit_map[i] != tex)
2603 context_map_stage(context, i, tex);
2604 context_invalidate_state(context, STATE_SAMPLER(i));
2605 context_invalidate_texture_stage(context, i);
2608 ++tex;
2612 static void context_map_psamplers(struct wined3d_context *context, const struct wined3d_state *state)
2614 const struct wined3d_shader_resource_info *resource_info =
2615 state->shader[WINED3D_SHADER_TYPE_PIXEL]->reg_maps.resource_info;
2616 unsigned int i;
2617 const struct wined3d_d3d_info *d3d_info = context->d3d_info;
2619 for (i = 0; i < MAX_FRAGMENT_SAMPLERS; ++i)
2621 if (resource_info[i].type && context->tex_unit_map[i] != i)
2623 context_map_stage(context, i, i);
2624 context_invalidate_state(context, STATE_SAMPLER(i));
2625 if (i < d3d_info->limits.ffp_blend_stages)
2626 context_invalidate_texture_stage(context, i);
2631 static BOOL context_unit_free_for_vs(const struct wined3d_context *context,
2632 const struct wined3d_shader_resource_info *ps_resource_info,
2633 const struct wined3d_shader_resource_info *vs_resource_info, DWORD unit)
2635 DWORD current_mapping = context->rev_tex_unit_map[unit];
2637 /* Not currently used */
2638 if (current_mapping == WINED3D_UNMAPPED_STAGE)
2639 return TRUE;
2641 if (current_mapping < MAX_FRAGMENT_SAMPLERS)
2643 /* Used by a fragment sampler */
2645 if (!ps_resource_info)
2647 /* No pixel shader, check fixed function */
2648 return current_mapping >= MAX_TEXTURES || !(context->fixed_function_usage_map & (1 << current_mapping));
2651 /* Pixel shader, check the shader's sampler map */
2652 return !ps_resource_info[current_mapping].type;
2655 /* Used by a vertex sampler */
2656 return !vs_resource_info[current_mapping - MAX_FRAGMENT_SAMPLERS].type;
2659 static void context_map_vsamplers(struct wined3d_context *context, BOOL ps, const struct wined3d_state *state)
2661 const struct wined3d_shader_resource_info *vs_resource_info =
2662 state->shader[WINED3D_SHADER_TYPE_VERTEX]->reg_maps.resource_info;
2663 const struct wined3d_shader_resource_info *ps_resource_info = NULL;
2664 const struct wined3d_gl_info *gl_info = context->gl_info;
2665 int start = min(MAX_COMBINED_SAMPLERS, gl_info->limits.combined_samplers) - 1;
2666 int i;
2668 /* Note that we only care if a resource is used or not, not the
2669 * resource's specific type. Otherwise we'd need to call
2670 * shader_update_samplers() here for 1.x pixelshaders. */
2671 if (ps)
2672 ps_resource_info = state->shader[WINED3D_SHADER_TYPE_PIXEL]->reg_maps.resource_info;
2674 for (i = 0; i < MAX_VERTEX_SAMPLERS; ++i)
2676 DWORD vsampler_idx = i + MAX_FRAGMENT_SAMPLERS;
2677 if (vs_resource_info[i].type)
2679 if (context->tex_unit_map[vsampler_idx] != WINED3D_UNMAPPED_STAGE)
2681 /* Already mapped somewhere */
2682 continue;
2685 while (start >= 0)
2687 if (context_unit_free_for_vs(context, ps_resource_info, vs_resource_info, start))
2689 context_map_stage(context, vsampler_idx, start);
2690 context_invalidate_state(context, STATE_SAMPLER(vsampler_idx));
2692 --start;
2693 break;
2696 --start;
2702 static void context_update_tex_unit_map(struct wined3d_context *context, const struct wined3d_state *state)
2704 BOOL vs = use_vs(state);
2705 BOOL ps = use_ps(state);
2707 * Rules are:
2708 * -> Pixel shaders need a 1:1 map. In theory the shader input could be mapped too, but
2709 * that would be really messy and require shader recompilation
2710 * -> When the mapping of a stage is changed, sampler and ALL texture stage states have
2711 * to be reset. Because of that try to work with a 1:1 mapping as much as possible
2713 if (ps)
2714 context_map_psamplers(context, state);
2715 else
2716 context_map_fixed_function_samplers(context, state);
2718 if (vs)
2719 context_map_vsamplers(context, ps, state);
2722 /* Context activation is done by the caller. */
2723 void context_state_drawbuf(struct wined3d_context *context, const struct wined3d_state *state, DWORD state_id)
2725 const struct wined3d_device *device = context->swapchain->device;
2726 DWORD rt_mask, *cur_mask;
2728 if (isStateDirty(context, STATE_FRAMEBUFFER)) return;
2730 cur_mask = context->current_fbo ? &context->current_fbo->rt_mask : &context->draw_buffers_mask;
2731 rt_mask = find_draw_buffers_mask(context, device);
2732 if (rt_mask != *cur_mask)
2734 context_apply_draw_buffers(context, rt_mask);
2735 *cur_mask = rt_mask;
2739 static BOOL fixed_get_input(BYTE usage, BYTE usage_idx, unsigned int *regnum)
2741 if ((usage == WINED3D_DECL_USAGE_POSITION || usage == WINED3D_DECL_USAGE_POSITIONT) && !usage_idx)
2742 *regnum = WINED3D_FFP_POSITION;
2743 else if (usage == WINED3D_DECL_USAGE_BLEND_WEIGHT && !usage_idx)
2744 *regnum = WINED3D_FFP_BLENDWEIGHT;
2745 else if (usage == WINED3D_DECL_USAGE_BLEND_INDICES && !usage_idx)
2746 *regnum = WINED3D_FFP_BLENDINDICES;
2747 else if (usage == WINED3D_DECL_USAGE_NORMAL && !usage_idx)
2748 *regnum = WINED3D_FFP_NORMAL;
2749 else if (usage == WINED3D_DECL_USAGE_PSIZE && !usage_idx)
2750 *regnum = WINED3D_FFP_PSIZE;
2751 else if (usage == WINED3D_DECL_USAGE_COLOR && !usage_idx)
2752 *regnum = WINED3D_FFP_DIFFUSE;
2753 else if (usage == WINED3D_DECL_USAGE_COLOR && usage_idx == 1)
2754 *regnum = WINED3D_FFP_SPECULAR;
2755 else if (usage == WINED3D_DECL_USAGE_TEXCOORD && usage_idx < WINED3DDP_MAXTEXCOORD)
2756 *regnum = WINED3D_FFP_TEXCOORD0 + usage_idx;
2757 else
2759 FIXME("Unsupported input stream [usage=%s, usage_idx=%u].\n", debug_d3ddeclusage(usage), usage_idx);
2760 *regnum = ~0U;
2761 return FALSE;
2764 return TRUE;
2767 /* Context activation is done by the caller. */
2768 void context_stream_info_from_declaration(struct wined3d_context *context,
2769 const struct wined3d_state *state, struct wined3d_stream_info *stream_info)
2771 /* We need to deal with frequency data! */
2772 struct wined3d_vertex_declaration *declaration = state->vertex_declaration;
2773 BOOL use_vshader = use_vs(state);
2774 unsigned int i;
2776 stream_info->use_map = 0;
2777 stream_info->swizzle_map = 0;
2778 stream_info->position_transformed = declaration->position_transformed;
2780 /* Translate the declaration into strided data. */
2781 for (i = 0; i < declaration->element_count; ++i)
2783 const struct wined3d_vertex_declaration_element *element = &declaration->elements[i];
2784 const struct wined3d_stream_state *stream = &state->streams[element->input_slot];
2785 BOOL stride_used;
2786 unsigned int idx;
2788 TRACE("%p Element %p (%u of %u).\n", declaration->elements,
2789 element, i + 1, declaration->element_count);
2791 if (!stream->buffer)
2792 continue;
2794 TRACE("offset %u input_slot %u usage_idx %d.\n", element->offset, element->input_slot, element->usage_idx);
2796 if (use_vshader)
2798 if (element->output_slot == WINED3D_OUTPUT_SLOT_UNUSED)
2800 stride_used = FALSE;
2802 else if (element->output_slot == WINED3D_OUTPUT_SLOT_SEMANTIC)
2804 /* TODO: Assuming vertexdeclarations are usually used with the
2805 * same or a similar shader, it might be worth it to store the
2806 * last used output slot and try that one first. */
2807 stride_used = vshader_get_input(state->shader[WINED3D_SHADER_TYPE_VERTEX],
2808 element->usage, element->usage_idx, &idx);
2810 else
2812 idx = element->output_slot;
2813 stride_used = TRUE;
2816 else
2818 if (!element->ffp_valid)
2820 WARN("Skipping unsupported fixed function element of format %s and usage %s.\n",
2821 debug_d3dformat(element->format->id), debug_d3ddeclusage(element->usage));
2822 stride_used = FALSE;
2824 else
2826 stride_used = fixed_get_input(element->usage, element->usage_idx, &idx);
2830 if (stride_used)
2832 TRACE("Load %s array %u [usage %s, usage_idx %u, "
2833 "input_slot %u, offset %u, stride %u, format %s, class %s, step_rate %u].\n",
2834 use_vshader ? "shader": "fixed function", idx,
2835 debug_d3ddeclusage(element->usage), element->usage_idx, element->input_slot,
2836 element->offset, stream->stride, debug_d3dformat(element->format->id),
2837 debug_d3dinput_classification(element->input_slot_class), element->instance_data_step_rate);
2839 stream_info->elements[idx].format = element->format;
2840 stream_info->elements[idx].data.buffer_object = 0;
2841 stream_info->elements[idx].data.addr = (BYTE *)NULL + stream->offset + element->offset;
2842 stream_info->elements[idx].stride = stream->stride;
2843 stream_info->elements[idx].stream_idx = element->input_slot;
2844 if (stream->flags & WINED3DSTREAMSOURCE_INSTANCEDATA)
2846 stream_info->elements[idx].divisor = 1;
2848 else if (element->input_slot_class == WINED3D_INPUT_PER_INSTANCE_DATA)
2850 stream_info->elements[idx].divisor = element->instance_data_step_rate;
2851 if (!element->instance_data_step_rate)
2852 FIXME("Instance step rate 0 not implemented.\n");
2854 else
2856 stream_info->elements[idx].divisor = 0;
2859 if (!context->gl_info->supported[ARB_VERTEX_ARRAY_BGRA]
2860 && element->format->id == WINED3DFMT_B8G8R8A8_UNORM)
2862 stream_info->swizzle_map |= 1 << idx;
2864 stream_info->use_map |= 1 << idx;
2869 /* Context activation is done by the caller. */
2870 static void context_update_stream_info(struct wined3d_context *context, const struct wined3d_state *state)
2872 const struct wined3d_gl_info *gl_info = context->gl_info;
2873 const struct wined3d_d3d_info *d3d_info = context->d3d_info;
2874 struct wined3d_stream_info *stream_info = &context->stream_info;
2875 DWORD prev_all_vbo = stream_info->all_vbo;
2876 unsigned int i;
2877 WORD map;
2879 context_stream_info_from_declaration(context, state, stream_info);
2881 stream_info->all_vbo = 1;
2882 context->num_buffer_queries = 0;
2883 for (i = 0, map = stream_info->use_map; map; map >>= 1, ++i)
2885 struct wined3d_stream_info_element *element;
2886 struct wined3d_bo_address data;
2887 struct wined3d_buffer *buffer;
2889 if (!(map & 1))
2890 continue;
2892 element = &stream_info->elements[i];
2893 buffer = state->streams[element->stream_idx].buffer;
2895 /* We can't use VBOs if the base vertex index is negative. OpenGL
2896 * doesn't accept negative offsets (or rather offsets bigger than the
2897 * VBO, because the pointer is unsigned), so use system memory
2898 * sources. In most sane cases the pointer - offset will still be > 0,
2899 * otherwise it will wrap around to some big value. Hope that with the
2900 * indices the driver wraps it back internally. If not,
2901 * drawStridedSlow is needed, including a vertex buffer path. */
2902 if (state->load_base_vertex_index < 0)
2904 WARN_(d3d_perf)("load_base_vertex_index is < 0 (%d), not using VBOs.\n",
2905 state->load_base_vertex_index);
2906 element->data.buffer_object = 0;
2907 element->data.addr += (ULONG_PTR)buffer_get_sysmem(buffer, context);
2908 if ((UINT_PTR)element->data.addr < -state->load_base_vertex_index * element->stride)
2909 FIXME("System memory vertex data load offset is negative!\n");
2911 else
2913 buffer_internal_preload(buffer, context, state);
2914 buffer_get_memory(buffer, context, &data);
2915 element->data.buffer_object = data.buffer_object;
2916 element->data.addr += (ULONG_PTR)data.addr;
2919 if (!element->data.buffer_object)
2920 stream_info->all_vbo = 0;
2922 if (buffer->query)
2923 context->buffer_queries[context->num_buffer_queries++] = buffer->query;
2925 TRACE("Load array %u {%#x:%p}.\n", i, element->data.buffer_object, element->data.addr);
2928 if (use_vs(state))
2930 if (state->vertex_declaration->half_float_conv_needed && !stream_info->all_vbo)
2932 TRACE("Using drawStridedSlow with vertex shaders for FLOAT16 conversion.\n");
2933 context->use_immediate_mode_draw = TRUE;
2935 else
2937 context->use_immediate_mode_draw = FALSE;
2940 else
2942 WORD slow_mask = (1 << WINED3D_FFP_PSIZE);
2943 slow_mask |= -!gl_info->supported[ARB_VERTEX_ARRAY_BGRA]
2944 & ((1 << WINED3D_FFP_DIFFUSE) | (1 << WINED3D_FFP_SPECULAR));
2946 if (((stream_info->position_transformed && !d3d_info->xyzrhw)
2947 || (stream_info->use_map & slow_mask)) && !stream_info->all_vbo)
2948 context->use_immediate_mode_draw = TRUE;
2949 else
2950 context->use_immediate_mode_draw = FALSE;
2953 if (prev_all_vbo != stream_info->all_vbo)
2954 context_invalidate_state(context, STATE_INDEXBUFFER);
2957 /* Context activation is done by the caller. */
2958 static void context_preload_texture(struct wined3d_context *context,
2959 const struct wined3d_state *state, unsigned int idx)
2961 struct wined3d_texture *texture;
2963 if (!(texture = state->textures[idx]))
2964 return;
2966 wined3d_texture_load(texture, context, state->sampler_states[idx][WINED3D_SAMP_SRGB_TEXTURE]);
2969 /* Context activation is done by the caller. */
2970 static void context_preload_textures(struct wined3d_context *context, const struct wined3d_state *state)
2972 unsigned int i;
2974 if (use_vs(state))
2976 for (i = 0; i < MAX_VERTEX_SAMPLERS; ++i)
2978 if (state->shader[WINED3D_SHADER_TYPE_VERTEX]->reg_maps.resource_info[i].type)
2979 context_preload_texture(context, state, MAX_FRAGMENT_SAMPLERS + i);
2983 if (use_ps(state))
2985 for (i = 0; i < MAX_FRAGMENT_SAMPLERS; ++i)
2987 if (state->shader[WINED3D_SHADER_TYPE_PIXEL]->reg_maps.resource_info[i].type)
2988 context_preload_texture(context, state, i);
2991 else
2993 WORD ffu_map = context->fixed_function_usage_map;
2995 for (i = 0; ffu_map; ffu_map >>= 1, ++i)
2997 if (ffu_map & 1)
2998 context_preload_texture(context, state, i);
3003 static void context_bind_shader_resources(struct wined3d_context *context, const struct wined3d_state *state)
3005 const struct wined3d_gl_info *gl_info = context->gl_info;
3006 struct wined3d_shader_sampler_map_entry *entry;
3007 struct wined3d_shader_resource_view *view;
3008 struct wined3d_sampler *sampler;
3009 struct wined3d_texture *texture;
3010 struct wined3d_shader *shader;
3011 unsigned int i, j, count;
3013 static const struct
3015 enum wined3d_shader_type type;
3016 unsigned int base_idx;
3017 unsigned int count;
3019 shader_types[] =
3021 {WINED3D_SHADER_TYPE_PIXEL, 0, MAX_FRAGMENT_SAMPLERS},
3022 {WINED3D_SHADER_TYPE_VERTEX, MAX_FRAGMENT_SAMPLERS, MAX_VERTEX_SAMPLERS},
3025 for (i = 0; i < ARRAY_SIZE(shader_types); ++i)
3027 if (!(shader = state->shader[shader_types[i].type]))
3028 continue;
3030 count = shader->reg_maps.sampler_map.count;
3031 if (count > shader_types[i].count)
3033 FIXME("Shader %p needs %u samplers, but only %u are supported.\n",
3034 shader, count, shader_types[i].count);
3035 count = shader_types[i].count;
3038 for (j = 0; j < count; ++j)
3040 entry = &shader->reg_maps.sampler_map.entries[j];
3042 if (!(view = state->shader_resource_view[shader_types[i].type][entry->resource_idx]))
3044 WARN("No resource view bound at index %u, %u.\n", shader_types[i].type, entry->resource_idx);
3045 continue;
3048 if (view->resource->type == WINED3D_RTYPE_BUFFER)
3050 FIXME("Buffer shader resources not supported.\n");
3051 continue;
3054 if (!(sampler = state->sampler[shader_types[i].type][entry->sampler_idx]))
3056 WARN("No sampler object bound at index %u, %u.\n", shader_types[i].type, entry->sampler_idx);
3057 continue;
3060 texture = wined3d_texture_from_resource(view->resource);
3061 wined3d_texture_load(texture, context, FALSE);
3062 context_active_texture(context, gl_info, shader_types[i].base_idx + entry->bind_idx);
3063 wined3d_texture_bind(texture, context, FALSE);
3065 GL_EXTCALL(glBindSampler(shader_types[i].base_idx + entry->bind_idx, sampler->name));
3066 checkGLcall("glBindSampler");
3071 /* Context activation is done by the caller. */
3072 BOOL context_apply_draw_state(struct wined3d_context *context, struct wined3d_device *device)
3074 const struct wined3d_state *state = &device->state;
3075 const struct StateEntry *state_table = context->state_table;
3076 const struct wined3d_fb_state *fb = state->fb;
3077 unsigned int i, j;
3078 WORD map;
3080 if (!context_validate_rt_config(context->gl_info->limits.buffers,
3081 fb->render_targets, fb->depth_stencil))
3082 return FALSE;
3084 if (wined3d_settings.offscreen_rendering_mode == ORM_FBO && isStateDirty(context, STATE_FRAMEBUFFER))
3086 context_validate_onscreen_formats(context, fb->depth_stencil);
3089 /* Preload resources before FBO setup. Texture preload in particular may
3090 * result in changes to the current FBO, due to using e.g. FBO blits for
3091 * updating a resource location. */
3092 context_update_tex_unit_map(context, state);
3093 context_preload_textures(context, state);
3094 /* TODO: Right now the dependency on the vertex shader is necessary
3095 * since context_stream_info_from_declaration depends on the reg_maps of
3096 * the current VS but maybe it's possible to relax the coupling in some
3097 * situations at least. */
3098 if (isStateDirty(context, STATE_VDECL) || isStateDirty(context, STATE_STREAMSRC)
3099 || isStateDirty(context, STATE_SHADER(WINED3D_SHADER_TYPE_VERTEX)))
3101 context_update_stream_info(context, state);
3103 else
3105 for (i = 0, map = context->stream_info.use_map; map; map >>= 1, ++i)
3107 if (map & 1)
3108 buffer_mark_used(state->streams[context->stream_info.elements[i].stream_idx].buffer);
3111 if (state->index_buffer)
3113 if (context->stream_info.all_vbo)
3114 buffer_internal_preload(state->index_buffer, context, state);
3115 else
3116 buffer_get_sysmem(state->index_buffer, context);
3119 for (i = 0; i < WINED3D_SHADER_TYPE_COUNT; ++i)
3121 for (j = 0; j < WINED3D_MAX_CBS; ++j)
3123 if (state->cb[i][j])
3124 buffer_internal_preload(state->cb[i][j], context, state);
3128 for (i = 0; i < context->numDirtyEntries; ++i)
3130 DWORD rep = context->dirtyArray[i];
3131 DWORD idx = rep / (sizeof(*context->isStateDirty) * CHAR_BIT);
3132 BYTE shift = rep & ((sizeof(*context->isStateDirty) * CHAR_BIT) - 1);
3133 context->isStateDirty[idx] &= ~(1 << shift);
3134 state_table[rep].apply(context, state, rep);
3137 if (context->shader_update_mask)
3139 device->shader_backend->shader_select(device->shader_priv, context, state);
3140 context->shader_update_mask = 0;
3143 if (context->constant_update_mask)
3145 device->shader_backend->shader_load_constants(device->shader_priv, context, state);
3146 context->constant_update_mask = 0;
3149 if (context->update_shader_resource_bindings)
3151 context_bind_shader_resources(context, state);
3152 context->update_shader_resource_bindings = 0;
3155 if (wined3d_settings.offscreen_rendering_mode == ORM_FBO)
3157 context_check_fbo_status(context, GL_FRAMEBUFFER);
3160 context->numDirtyEntries = 0; /* This makes the whole list clean */
3161 context->last_was_blit = FALSE;
3163 return TRUE;
3166 static void context_setup_target(struct wined3d_context *context, struct wined3d_surface *target)
3168 BOOL old_render_offscreen = context->render_offscreen, render_offscreen;
3170 render_offscreen = wined3d_resource_is_offscreen(&target->container->resource);
3171 if (context->current_rt == target && render_offscreen == old_render_offscreen) return;
3173 /* To compensate the lack of format switching with some offscreen rendering methods and on onscreen buffers
3174 * the alpha blend state changes with different render target formats. */
3175 if (!context->current_rt)
3177 context_invalidate_state(context, STATE_RENDER(WINED3D_RS_ALPHABLENDENABLE));
3179 else
3181 const struct wined3d_format *old = context->current_rt->resource.format;
3182 const struct wined3d_format *new = target->resource.format;
3184 if (old->id != new->id)
3186 /* Disable blending when the alpha mask has changed and when a format doesn't support blending. */
3187 if ((old->alpha_size && !new->alpha_size) || (!old->alpha_size && new->alpha_size)
3188 || !(target->resource.format_flags & WINED3DFMT_FLAG_POSTPIXELSHADER_BLENDING))
3189 context_invalidate_state(context, STATE_RENDER(WINED3D_RS_ALPHABLENDENABLE));
3191 /* Update sRGB writing when switching between formats that do/do not support sRGB writing */
3192 if ((context->current_rt->resource.format_flags & WINED3DFMT_FLAG_SRGB_WRITE)
3193 != (target->resource.format_flags & WINED3DFMT_FLAG_SRGB_WRITE))
3194 context_invalidate_state(context, STATE_RENDER(WINED3D_RS_SRGBWRITEENABLE));
3197 /* When switching away from an offscreen render target, and we're not
3198 * using FBOs, we have to read the drawable into the texture. This is
3199 * done via PreLoad (and WINED3D_LOCATION_DRAWABLE set on the surface).
3200 * There are some things that need care though. PreLoad needs a GL context,
3201 * and FindContext is called before the context is activated. It also
3202 * has to be called with the old rendertarget active, otherwise a
3203 * wrong drawable is read. */
3204 if (wined3d_settings.offscreen_rendering_mode != ORM_FBO
3205 && old_render_offscreen && context->current_rt != target)
3207 struct wined3d_texture *texture = context->current_rt->container;
3209 /* Read the back buffer of the old drawable into the destination texture. */
3210 if (texture->texture_srgb.name)
3211 wined3d_texture_load(texture, context, TRUE);
3212 wined3d_texture_load(texture, context, FALSE);
3213 surface_invalidate_location(context->current_rt, WINED3D_LOCATION_DRAWABLE);
3217 context->current_rt = target;
3218 context_set_render_offscreen(context, render_offscreen);
3221 struct wined3d_context *context_acquire(const struct wined3d_device *device, struct wined3d_surface *target)
3223 struct wined3d_context *current_context = context_get_current();
3224 struct wined3d_context *context;
3226 TRACE("device %p, target %p.\n", device, target);
3228 if (current_context && current_context->destroyed)
3229 current_context = NULL;
3231 if (!target)
3233 if (current_context
3234 && current_context->current_rt
3235 && current_context->swapchain->device == device)
3237 target = current_context->current_rt;
3239 else
3241 struct wined3d_swapchain *swapchain = device->swapchains[0];
3242 if (swapchain->back_buffers)
3243 target = surface_from_resource(wined3d_texture_get_sub_resource(swapchain->back_buffers[0], 0));
3244 else
3245 target = surface_from_resource(wined3d_texture_get_sub_resource(swapchain->front_buffer, 0));
3249 if (current_context && current_context->current_rt == target)
3251 context = current_context;
3253 else if (target->container->swapchain)
3255 TRACE("Rendering onscreen.\n");
3257 context = swapchain_get_context(target->container->swapchain);
3259 else
3261 TRACE("Rendering offscreen.\n");
3263 /* Stay with the current context if possible. Otherwise use the
3264 * context for the primary swapchain. */
3265 if (current_context && current_context->swapchain->device == device)
3266 context = current_context;
3267 else
3268 context = swapchain_get_context(device->swapchains[0]);
3271 context_enter(context);
3272 context_update_window(context);
3273 context_setup_target(context, target);
3274 if (!context->valid) return context;
3276 if (context != current_context)
3278 if (!context_set_current(context))
3279 ERR("Failed to activate the new context.\n");
3281 else if (context->needs_set)
3283 context_set_gl_context(context);
3286 return context;