wined3d: Don't unnecessarily fallback to immediate mode for FFP draws with the PSIZE...
[wine.git] / dlls / wined3d / context.c
blob32813e914892a53731e1f7d26ab0aab99f10f2f7
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->container->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;
423 struct wined3d_surface *depth_stencil = entry->depth_stencil;
425 if (entry->attached)
427 context_bind_fbo(context, target, entry->id);
428 return;
431 read_binding = context->fbo_read_binding;
432 draw_binding = context->fbo_draw_binding;
433 context_bind_fbo(context, GL_FRAMEBUFFER, entry->id);
435 /* Apply render targets */
436 for (i = 0; i < gl_info->limits.buffers; ++i)
438 context_attach_surface_fbo(context, target, i, entry->render_targets[i], entry->color_location);
441 if (depth_stencil && entry->render_targets[0]
442 && (depth_stencil->resource.multisample_type
443 != entry->render_targets[0]->resource.multisample_type
444 || depth_stencil->resource.multisample_quality
445 != entry->render_targets[0]->resource.multisample_quality))
447 WARN("Color multisample type %u and quality %u, depth stencil has %u and %u, disabling ds buffer.\n",
448 entry->render_targets[0]->resource.multisample_quality,
449 entry->render_targets[0]->resource.multisample_type,
450 depth_stencil->resource.multisample_quality, depth_stencil->resource.multisample_type);
451 depth_stencil = NULL;
454 if (depth_stencil)
455 surface_set_compatible_renderbuffer(depth_stencil, entry->render_targets[0]);
456 context_attach_depth_stencil_fbo(context, target, depth_stencil, entry->ds_location);
458 /* Set valid read and draw buffer bindings to satisfy pedantic pre-ES2_compatibility
459 * GL contexts requirements. */
460 gl_info->gl_ops.gl.p_glReadBuffer(GL_NONE);
461 context_set_draw_buffer(context, GL_NONE);
462 if (target != GL_FRAMEBUFFER)
464 if (target == GL_READ_FRAMEBUFFER)
465 context_bind_fbo(context, GL_DRAW_FRAMEBUFFER, draw_binding);
466 else
467 context_bind_fbo(context, GL_READ_FRAMEBUFFER, read_binding);
470 entry->attached = TRUE;
473 /* Context activation is done by the caller. */
474 static void context_apply_fbo_state(struct wined3d_context *context, GLenum target,
475 struct wined3d_surface **render_targets, struct wined3d_surface *depth_stencil,
476 DWORD color_location, DWORD ds_location)
478 struct fbo_entry *entry, *entry2;
480 LIST_FOR_EACH_ENTRY_SAFE(entry, entry2, &context->fbo_destroy_list, struct fbo_entry, entry)
482 context_destroy_fbo_entry(context, entry);
485 if (context->rebind_fbo)
487 context_bind_fbo(context, GL_FRAMEBUFFER, 0);
488 context->rebind_fbo = FALSE;
491 if (color_location == WINED3D_LOCATION_DRAWABLE)
493 context->current_fbo = NULL;
494 context_bind_fbo(context, target, 0);
496 else
498 context->current_fbo = context_find_fbo_entry(context, target, render_targets, depth_stencil,
499 color_location, ds_location);
500 context_apply_fbo_entry(context, target, context->current_fbo);
504 /* Context activation is done by the caller. */
505 void context_apply_fbo_state_blit(struct wined3d_context *context, GLenum target,
506 struct wined3d_surface *render_target, struct wined3d_surface *depth_stencil, DWORD location)
508 UINT clear_size = (context->gl_info->limits.buffers - 1) * sizeof(*context->blit_targets);
510 context->blit_targets[0] = render_target;
511 if (clear_size)
512 memset(&context->blit_targets[1], 0, clear_size);
513 context_apply_fbo_state(context, target, context->blit_targets, depth_stencil, location, location);
516 /* Context activation is done by the caller. */
517 void context_alloc_occlusion_query(struct wined3d_context *context, struct wined3d_occlusion_query *query)
519 const struct wined3d_gl_info *gl_info = context->gl_info;
521 if (context->free_occlusion_query_count)
523 query->id = context->free_occlusion_queries[--context->free_occlusion_query_count];
525 else
527 if (gl_info->supported[ARB_OCCLUSION_QUERY])
529 GL_EXTCALL(glGenQueries(1, &query->id));
530 checkGLcall("glGenQueries");
532 TRACE("Allocated occlusion query %u in context %p.\n", query->id, context);
534 else
536 WARN("Occlusion queries not supported, not allocating query id.\n");
537 query->id = 0;
541 query->context = context;
542 list_add_head(&context->occlusion_queries, &query->entry);
545 void context_free_occlusion_query(struct wined3d_occlusion_query *query)
547 struct wined3d_context *context = query->context;
549 list_remove(&query->entry);
550 query->context = NULL;
552 if (context->free_occlusion_query_count >= context->free_occlusion_query_size - 1)
554 UINT new_size = context->free_occlusion_query_size << 1;
555 GLuint *new_data = HeapReAlloc(GetProcessHeap(), 0, context->free_occlusion_queries,
556 new_size * sizeof(*context->free_occlusion_queries));
558 if (!new_data)
560 ERR("Failed to grow free list, leaking query %u in context %p.\n", query->id, context);
561 return;
564 context->free_occlusion_query_size = new_size;
565 context->free_occlusion_queries = new_data;
568 context->free_occlusion_queries[context->free_occlusion_query_count++] = query->id;
571 /* Context activation is done by the caller. */
572 void context_alloc_event_query(struct wined3d_context *context, struct wined3d_event_query *query)
574 const struct wined3d_gl_info *gl_info = context->gl_info;
576 if (context->free_event_query_count)
578 query->object = context->free_event_queries[--context->free_event_query_count];
580 else
582 if (gl_info->supported[ARB_SYNC])
584 /* Using ARB_sync, not much to do here. */
585 query->object.sync = NULL;
586 TRACE("Allocated event query %p in context %p.\n", query->object.sync, context);
588 else if (gl_info->supported[APPLE_FENCE])
590 GL_EXTCALL(glGenFencesAPPLE(1, &query->object.id));
591 checkGLcall("glGenFencesAPPLE");
593 TRACE("Allocated event query %u in context %p.\n", query->object.id, context);
595 else if(gl_info->supported[NV_FENCE])
597 GL_EXTCALL(glGenFencesNV(1, &query->object.id));
598 checkGLcall("glGenFencesNV");
600 TRACE("Allocated event query %u in context %p.\n", query->object.id, context);
602 else
604 WARN("Event queries not supported, not allocating query id.\n");
605 query->object.id = 0;
609 query->context = context;
610 list_add_head(&context->event_queries, &query->entry);
613 void context_free_event_query(struct wined3d_event_query *query)
615 struct wined3d_context *context = query->context;
617 list_remove(&query->entry);
618 query->context = NULL;
620 if (context->free_event_query_count >= context->free_event_query_size - 1)
622 UINT new_size = context->free_event_query_size << 1;
623 union wined3d_gl_query_object *new_data = HeapReAlloc(GetProcessHeap(), 0, context->free_event_queries,
624 new_size * sizeof(*context->free_event_queries));
626 if (!new_data)
628 ERR("Failed to grow free list, leaking query %u in context %p.\n", query->object.id, context);
629 return;
632 context->free_event_query_size = new_size;
633 context->free_event_queries = new_data;
636 context->free_event_queries[context->free_event_query_count++] = query->object;
639 /* Context activation is done by the caller. */
640 void context_alloc_timestamp_query(struct wined3d_context *context, struct wined3d_timestamp_query *query)
642 const struct wined3d_gl_info *gl_info = context->gl_info;
644 if (context->free_timestamp_query_count)
646 query->id = context->free_timestamp_queries[--context->free_timestamp_query_count];
648 else
650 GL_EXTCALL(glGenQueries(1, &query->id));
651 checkGLcall("glGenQueries");
653 TRACE("Allocated timestamp query %u in context %p.\n", query->id, context);
656 query->context = context;
657 list_add_head(&context->timestamp_queries, &query->entry);
660 void context_free_timestamp_query(struct wined3d_timestamp_query *query)
662 struct wined3d_context *context = query->context;
664 list_remove(&query->entry);
665 query->context = NULL;
667 if (context->free_timestamp_query_count >= context->free_timestamp_query_size - 1)
669 UINT new_size = context->free_timestamp_query_size << 1;
670 GLuint *new_data = HeapReAlloc(GetProcessHeap(), 0, context->free_timestamp_queries,
671 new_size * sizeof(*context->free_timestamp_queries));
673 if (!new_data)
675 ERR("Failed to grow free list, leaking query %u in context %p.\n", query->id, context);
676 return;
679 context->free_timestamp_query_size = new_size;
680 context->free_timestamp_queries = new_data;
683 context->free_timestamp_queries[context->free_timestamp_query_count++] = query->id;
686 typedef void (context_fbo_entry_func_t)(struct wined3d_context *context, struct fbo_entry *entry);
688 static void context_enum_surface_fbo_entries(const struct wined3d_device *device,
689 const struct wined3d_surface *surface, context_fbo_entry_func_t *callback)
691 UINT i;
693 for (i = 0; i < device->context_count; ++i)
695 struct wined3d_context *context = device->contexts[i];
696 const struct wined3d_gl_info *gl_info = context->gl_info;
697 struct fbo_entry *entry, *entry2;
699 if (context->current_rt == surface) context->current_rt = NULL;
701 LIST_FOR_EACH_ENTRY_SAFE(entry, entry2, &context->fbo_list, struct fbo_entry, entry)
703 UINT j;
705 if (entry->depth_stencil == surface)
707 callback(context, entry);
708 continue;
711 for (j = 0; j < gl_info->limits.buffers; ++j)
713 if (entry->render_targets[j] == surface)
715 callback(context, entry);
716 break;
723 static void context_queue_fbo_entry_destruction(struct wined3d_context *context, struct fbo_entry *entry)
725 list_remove(&entry->entry);
726 list_add_head(&context->fbo_destroy_list, &entry->entry);
729 void context_resource_released(const struct wined3d_device *device,
730 struct wined3d_resource *resource, enum wined3d_resource_type type)
732 if (!device->d3d_initialized) return;
734 switch (type)
736 case WINED3D_RTYPE_SURFACE:
737 context_enum_surface_fbo_entries(device, surface_from_resource(resource),
738 context_queue_fbo_entry_destruction);
739 break;
741 default:
742 break;
746 static void context_detach_fbo_entry(struct wined3d_context *context, struct fbo_entry *entry)
748 entry->attached = FALSE;
751 void context_resource_unloaded(const struct wined3d_device *device,
752 struct wined3d_resource *resource, enum wined3d_resource_type type)
754 switch (type)
756 case WINED3D_RTYPE_SURFACE:
757 context_enum_surface_fbo_entries(device, surface_from_resource(resource),
758 context_detach_fbo_entry);
759 break;
761 default:
762 break;
766 void context_surface_update(struct wined3d_context *context, const struct wined3d_surface *surface)
768 const struct wined3d_gl_info *gl_info = context->gl_info;
769 struct fbo_entry *entry = context->current_fbo;
770 unsigned int i;
772 if (!entry || context->rebind_fbo) return;
774 for (i = 0; i < gl_info->limits.buffers; ++i)
776 if (surface == entry->render_targets[i])
778 TRACE("Updated surface %p is bound as color attachment %u to the current FBO.\n", surface, i);
779 context->rebind_fbo = TRUE;
780 return;
784 if (surface == entry->depth_stencil)
786 TRACE("Updated surface %p is bound as depth attachment to the current FBO.\n", surface);
787 context->rebind_fbo = TRUE;
791 static BOOL context_restore_pixel_format(struct wined3d_context *ctx)
793 const struct wined3d_gl_info *gl_info = ctx->gl_info;
794 BOOL ret = FALSE;
796 if (ctx->restore_pf && IsWindow(ctx->restore_pf_win))
798 if (ctx->gl_info->supported[WGL_WINE_PIXEL_FORMAT_PASSTHROUGH])
800 HDC dc = GetDC(ctx->restore_pf_win);
801 if (dc)
803 if (!(ret = GL_EXTCALL(wglSetPixelFormatWINE(dc, ctx->restore_pf))))
805 ERR("wglSetPixelFormatWINE failed to restore pixel format %d on window %p.\n",
806 ctx->restore_pf, ctx->restore_pf_win);
808 ReleaseDC(ctx->restore_pf_win, dc);
811 else
813 ERR("can't restore pixel format %d on window %p\n", ctx->restore_pf, ctx->restore_pf_win);
817 ctx->restore_pf = 0;
818 ctx->restore_pf_win = NULL;
819 return ret;
822 static BOOL context_set_pixel_format(struct wined3d_context *context, HDC dc, BOOL private, int format)
824 const struct wined3d_gl_info *gl_info = context->gl_info;
825 int current;
827 if (dc == context->hdc && context->hdc_is_private && context->hdc_has_format)
828 return TRUE;
830 current = GetPixelFormat(dc);
831 if (current == format) goto success;
833 if (!current)
835 if (!SetPixelFormat(dc, format, NULL))
837 /* This may also happen if the dc belongs to a destroyed window. */
838 WARN("Failed to set pixel format %d on device context %p, last error %#x.\n",
839 format, dc, GetLastError());
840 return FALSE;
843 context->restore_pf = 0;
844 context->restore_pf_win = private ? NULL : WindowFromDC(dc);
845 goto success;
848 /* By default WGL doesn't allow pixel format adjustments but we need it
849 * here. For this reason there's a Wine specific wglSetPixelFormat()
850 * which allows us to set the pixel format multiple times. Only use it
851 * when really needed. */
852 if (gl_info->supported[WGL_WINE_PIXEL_FORMAT_PASSTHROUGH])
854 HWND win;
856 if (!GL_EXTCALL(wglSetPixelFormatWINE(dc, format)))
858 ERR("wglSetPixelFormatWINE failed to set pixel format %d on device context %p.\n",
859 format, dc);
860 return FALSE;
863 win = private ? NULL : WindowFromDC(dc);
864 if (win != context->restore_pf_win)
866 context_restore_pixel_format(context);
868 context->restore_pf = private ? 0 : current;
869 context->restore_pf_win = win;
872 goto success;
875 /* OpenGL doesn't allow pixel format adjustments. Print an error and
876 * continue using the old format. There's a big chance that the old
877 * format works although with a performance hit and perhaps rendering
878 * errors. */
879 ERR("Unable to set pixel format %d on device context %p. Already using format %d.\n",
880 format, dc, current);
881 return TRUE;
883 success:
884 if (dc == context->hdc && context->hdc_is_private)
885 context->hdc_has_format = TRUE;
886 return TRUE;
889 static BOOL context_set_gl_context(struct wined3d_context *ctx)
891 struct wined3d_swapchain *swapchain = ctx->swapchain;
892 BOOL backup = FALSE;
894 if (!context_set_pixel_format(ctx, ctx->hdc, ctx->hdc_is_private, ctx->pixel_format))
896 WARN("Failed to set pixel format %d on device context %p.\n",
897 ctx->pixel_format, ctx->hdc);
898 backup = TRUE;
901 if (backup || !wglMakeCurrent(ctx->hdc, ctx->glCtx))
903 HDC dc;
905 WARN("Failed to make GL context %p current on device context %p, last error %#x.\n",
906 ctx->glCtx, ctx->hdc, GetLastError());
907 ctx->valid = 0;
908 WARN("Trying fallback to the backup window.\n");
910 /* FIXME: If the context is destroyed it's no longer associated with
911 * a swapchain, so we can't use the swapchain to get a backup dc. To
912 * make this work windowless contexts would need to be handled by the
913 * device. */
914 if (ctx->destroyed)
916 FIXME("Unable to get backup dc for destroyed context %p.\n", ctx);
917 context_set_current(NULL);
918 return FALSE;
921 if (!(dc = swapchain_get_backup_dc(swapchain)))
923 context_set_current(NULL);
924 return FALSE;
927 if (!context_set_pixel_format(ctx, dc, TRUE, ctx->pixel_format))
929 ERR("Failed to set pixel format %d on device context %p.\n",
930 ctx->pixel_format, dc);
931 context_set_current(NULL);
932 return FALSE;
935 if (!wglMakeCurrent(dc, ctx->glCtx))
937 ERR("Fallback to backup window (dc %p) failed too, last error %#x.\n",
938 dc, GetLastError());
939 context_set_current(NULL);
940 return FALSE;
943 ctx->valid = 1;
945 ctx->needs_set = 0;
946 return TRUE;
949 static void context_restore_gl_context(const struct wined3d_gl_info *gl_info, HDC dc, HGLRC gl_ctx)
951 if (!wglMakeCurrent(dc, gl_ctx))
953 ERR("Failed to restore GL context %p on device context %p, last error %#x.\n",
954 gl_ctx, dc, GetLastError());
955 context_set_current(NULL);
959 static void context_update_window(struct wined3d_context *context)
961 if (context->win_handle == context->swapchain->win_handle)
962 return;
964 TRACE("Updating context %p window from %p to %p.\n",
965 context, context->win_handle, context->swapchain->win_handle);
967 if (context->hdc)
968 wined3d_release_dc(context->win_handle, context->hdc);
970 context->win_handle = context->swapchain->win_handle;
971 context->hdc_is_private = FALSE;
972 context->hdc_has_format = FALSE;
973 context->needs_set = 1;
974 context->valid = 1;
976 if (!(context->hdc = GetDC(context->win_handle)))
978 ERR("Failed to get a device context for window %p.\n", context->win_handle);
979 context->valid = 0;
983 static void context_destroy_gl_resources(struct wined3d_context *context)
985 const struct wined3d_gl_info *gl_info = context->gl_info;
986 struct wined3d_timestamp_query *timestamp_query;
987 struct wined3d_occlusion_query *occlusion_query;
988 struct wined3d_event_query *event_query;
989 struct fbo_entry *entry, *entry2;
990 HGLRC restore_ctx;
991 HDC restore_dc;
992 unsigned int i;
994 restore_ctx = wglGetCurrentContext();
995 restore_dc = wglGetCurrentDC();
997 if (restore_ctx == context->glCtx)
998 restore_ctx = NULL;
999 else if (context->valid)
1000 context_set_gl_context(context);
1002 LIST_FOR_EACH_ENTRY(timestamp_query, &context->timestamp_queries, struct wined3d_timestamp_query, entry)
1004 if (context->valid)
1005 GL_EXTCALL(glDeleteQueries(1, &timestamp_query->id));
1006 timestamp_query->context = NULL;
1009 LIST_FOR_EACH_ENTRY(occlusion_query, &context->occlusion_queries, struct wined3d_occlusion_query, entry)
1011 if (context->valid && gl_info->supported[ARB_OCCLUSION_QUERY])
1012 GL_EXTCALL(glDeleteQueries(1, &occlusion_query->id));
1013 occlusion_query->context = NULL;
1016 LIST_FOR_EACH_ENTRY(event_query, &context->event_queries, struct wined3d_event_query, entry)
1018 if (context->valid)
1020 if (gl_info->supported[ARB_SYNC])
1022 if (event_query->object.sync) GL_EXTCALL(glDeleteSync(event_query->object.sync));
1024 else if (gl_info->supported[APPLE_FENCE]) GL_EXTCALL(glDeleteFencesAPPLE(1, &event_query->object.id));
1025 else if (gl_info->supported[NV_FENCE]) GL_EXTCALL(glDeleteFencesNV(1, &event_query->object.id));
1027 event_query->context = NULL;
1030 LIST_FOR_EACH_ENTRY_SAFE(entry, entry2, &context->fbo_destroy_list, struct fbo_entry, entry)
1032 if (!context->valid) entry->id = 0;
1033 context_destroy_fbo_entry(context, entry);
1036 LIST_FOR_EACH_ENTRY_SAFE(entry, entry2, &context->fbo_list, struct fbo_entry, entry)
1038 if (!context->valid) entry->id = 0;
1039 context_destroy_fbo_entry(context, entry);
1042 if (context->valid)
1044 if (context->dummy_arbfp_prog)
1046 GL_EXTCALL(glDeleteProgramsARB(1, &context->dummy_arbfp_prog));
1049 if (gl_info->supported[ARB_TIMER_QUERY])
1050 GL_EXTCALL(glDeleteQueries(context->free_timestamp_query_count, context->free_timestamp_queries));
1052 if (gl_info->supported[ARB_OCCLUSION_QUERY])
1053 GL_EXTCALL(glDeleteQueries(context->free_occlusion_query_count, context->free_occlusion_queries));
1055 if (gl_info->supported[ARB_SYNC])
1057 for (i = 0; i < context->free_event_query_count; ++i)
1059 GL_EXTCALL(glDeleteSync(context->free_event_queries[i].sync));
1062 else if (gl_info->supported[APPLE_FENCE])
1064 for (i = 0; i < context->free_event_query_count; ++i)
1066 GL_EXTCALL(glDeleteFencesAPPLE(1, &context->free_event_queries[i].id));
1069 else if (gl_info->supported[NV_FENCE])
1071 for (i = 0; i < context->free_event_query_count; ++i)
1073 GL_EXTCALL(glDeleteFencesNV(1, &context->free_event_queries[i].id));
1077 checkGLcall("context cleanup");
1080 HeapFree(GetProcessHeap(), 0, context->free_timestamp_queries);
1081 HeapFree(GetProcessHeap(), 0, context->free_occlusion_queries);
1082 HeapFree(GetProcessHeap(), 0, context->free_event_queries);
1084 context_restore_pixel_format(context);
1085 if (restore_ctx)
1087 context_restore_gl_context(gl_info, restore_dc, restore_ctx);
1089 else if (wglGetCurrentContext() && !wglMakeCurrent(NULL, NULL))
1091 ERR("Failed to disable GL context.\n");
1094 wined3d_release_dc(context->win_handle, context->hdc);
1096 if (!wglDeleteContext(context->glCtx))
1098 DWORD err = GetLastError();
1099 ERR("wglDeleteContext(%p) failed, last error %#x.\n", context->glCtx, err);
1103 DWORD context_get_tls_idx(void)
1105 return wined3d_context_tls_idx;
1108 void context_set_tls_idx(DWORD idx)
1110 wined3d_context_tls_idx = idx;
1113 struct wined3d_context *context_get_current(void)
1115 return TlsGetValue(wined3d_context_tls_idx);
1118 BOOL context_set_current(struct wined3d_context *ctx)
1120 struct wined3d_context *old = context_get_current();
1122 if (old == ctx)
1124 TRACE("Already using D3D context %p.\n", ctx);
1125 return TRUE;
1128 if (old)
1130 if (old->destroyed)
1132 TRACE("Switching away from destroyed context %p.\n", old);
1133 context_destroy_gl_resources(old);
1134 HeapFree(GetProcessHeap(), 0, (void *)old->gl_info);
1135 HeapFree(GetProcessHeap(), 0, old);
1137 else
1139 old->current = 0;
1143 if (ctx)
1145 if (!ctx->valid)
1147 ERR("Trying to make invalid context %p current\n", ctx);
1148 return FALSE;
1151 TRACE("Switching to D3D context %p, GL context %p, device context %p.\n", ctx, ctx->glCtx, ctx->hdc);
1152 if (!context_set_gl_context(ctx))
1153 return FALSE;
1154 ctx->current = 1;
1156 else if(wglGetCurrentContext())
1158 TRACE("Clearing current D3D context.\n");
1159 if (!wglMakeCurrent(NULL, NULL))
1161 DWORD err = GetLastError();
1162 ERR("Failed to clear current GL context, last error %#x.\n", err);
1163 TlsSetValue(wined3d_context_tls_idx, NULL);
1164 return FALSE;
1168 return TlsSetValue(wined3d_context_tls_idx, ctx);
1171 void context_release(struct wined3d_context *context)
1173 TRACE("Releasing context %p, level %u.\n", context, context->level);
1175 if (WARN_ON(d3d))
1177 if (!context->level)
1178 WARN("Context %p is not active.\n", context);
1179 else if (context != context_get_current())
1180 WARN("Context %p is not the current context.\n", context);
1183 if (!--context->level)
1185 if (context_restore_pixel_format(context))
1186 context->needs_set = 1;
1187 if (context->restore_ctx)
1189 TRACE("Restoring GL context %p on device context %p.\n", context->restore_ctx, context->restore_dc);
1190 context_restore_gl_context(context->gl_info, context->restore_dc, context->restore_ctx);
1191 context->restore_ctx = NULL;
1192 context->restore_dc = NULL;
1197 static void context_enter(struct wined3d_context *context)
1199 TRACE("Entering context %p, level %u.\n", context, context->level + 1);
1201 if (!context->level++)
1203 const struct wined3d_context *current_context = context_get_current();
1204 HGLRC current_gl = wglGetCurrentContext();
1206 if (current_gl && (!current_context || current_context->glCtx != current_gl))
1208 TRACE("Another GL context (%p on device context %p) is already current.\n",
1209 current_gl, wglGetCurrentDC());
1210 context->restore_ctx = current_gl;
1211 context->restore_dc = wglGetCurrentDC();
1212 context->needs_set = 1;
1214 else if (!context->needs_set && !(context->hdc_is_private && context->hdc_has_format)
1215 && context->pixel_format != GetPixelFormat(context->hdc))
1216 context->needs_set = 1;
1220 void context_invalidate_state(struct wined3d_context *context, DWORD state)
1222 DWORD rep = context->state_table[state].representative;
1223 DWORD idx;
1224 BYTE shift;
1226 if (isStateDirty(context, rep)) return;
1228 context->dirtyArray[context->numDirtyEntries++] = rep;
1229 idx = rep / (sizeof(*context->isStateDirty) * CHAR_BIT);
1230 shift = rep & ((sizeof(*context->isStateDirty) * CHAR_BIT) - 1);
1231 context->isStateDirty[idx] |= (1 << shift);
1234 /* This function takes care of wined3d pixel format selection. */
1235 static int context_choose_pixel_format(const struct wined3d_device *device, HDC hdc,
1236 const struct wined3d_format *color_format, const struct wined3d_format *ds_format,
1237 BOOL auxBuffers, BOOL findCompatible)
1239 int iPixelFormat=0;
1240 BYTE redBits, greenBits, blueBits, alphaBits, colorBits;
1241 BYTE depthBits=0, stencilBits=0;
1242 unsigned int current_value;
1243 unsigned int cfg_count = device->adapter->cfg_count;
1244 unsigned int i;
1246 TRACE("device %p, dc %p, color_format %s, ds_format %s, aux_buffers %#x, find_compatible %#x.\n",
1247 device, hdc, debug_d3dformat(color_format->id), debug_d3dformat(ds_format->id),
1248 auxBuffers, findCompatible);
1250 if (!getColorBits(color_format, &redBits, &greenBits, &blueBits, &alphaBits, &colorBits))
1252 ERR("Unable to get color bits for format %s (%#x)!\n",
1253 debug_d3dformat(color_format->id), color_format->id);
1254 return 0;
1257 getDepthStencilBits(ds_format, &depthBits, &stencilBits);
1259 current_value = 0;
1260 for (i = 0; i < cfg_count; ++i)
1262 const struct wined3d_pixel_format *cfg = &device->adapter->cfgs[i];
1263 unsigned int value;
1265 /* For now only accept RGBA formats. Perhaps some day we will
1266 * allow floating point formats for pbuffers. */
1267 if (cfg->iPixelType != WGL_TYPE_RGBA_ARB)
1268 continue;
1269 /* In window mode we need a window drawable format and double buffering. */
1270 if (!(cfg->windowDrawable && cfg->doubleBuffer))
1271 continue;
1272 if (cfg->redSize < redBits)
1273 continue;
1274 if (cfg->greenSize < greenBits)
1275 continue;
1276 if (cfg->blueSize < blueBits)
1277 continue;
1278 if (cfg->alphaSize < alphaBits)
1279 continue;
1280 if (cfg->depthSize < depthBits)
1281 continue;
1282 if (stencilBits && cfg->stencilSize != stencilBits)
1283 continue;
1284 /* Check multisampling support. */
1285 if (cfg->numSamples)
1286 continue;
1288 value = 1;
1289 /* We try to locate a format which matches our requirements exactly. In case of
1290 * depth it is no problem to emulate 16-bit using e.g. 24-bit, so accept that. */
1291 if (cfg->depthSize == depthBits)
1292 value += 1;
1293 if (cfg->stencilSize == stencilBits)
1294 value += 2;
1295 if (cfg->alphaSize == alphaBits)
1296 value += 4;
1297 /* We like to have aux buffers in backbuffer mode */
1298 if (auxBuffers && cfg->auxBuffers)
1299 value += 8;
1300 if (cfg->redSize == redBits
1301 && cfg->greenSize == greenBits
1302 && cfg->blueSize == blueBits)
1303 value += 16;
1305 if (value > current_value)
1307 iPixelFormat = cfg->iPixelFormat;
1308 current_value = value;
1312 /* When findCompatible is set and no suitable format was found, let ChoosePixelFormat choose a pixel format in order not to crash. */
1313 if(!iPixelFormat && !findCompatible) {
1314 ERR("Can't find a suitable iPixelFormat\n");
1315 return FALSE;
1316 } else if(!iPixelFormat) {
1317 PIXELFORMATDESCRIPTOR pfd;
1319 TRACE("Falling back to ChoosePixelFormat as we weren't able to find an exactly matching pixel format\n");
1320 /* PixelFormat selection */
1321 ZeroMemory(&pfd, sizeof(pfd));
1322 pfd.nSize = sizeof(pfd);
1323 pfd.nVersion = 1;
1324 pfd.dwFlags = PFD_SUPPORT_OPENGL | PFD_DOUBLEBUFFER | PFD_DRAW_TO_WINDOW;/*PFD_GENERIC_ACCELERATED*/
1325 pfd.iPixelType = PFD_TYPE_RGBA;
1326 pfd.cAlphaBits = alphaBits;
1327 pfd.cColorBits = colorBits;
1328 pfd.cDepthBits = depthBits;
1329 pfd.cStencilBits = stencilBits;
1330 pfd.iLayerType = PFD_MAIN_PLANE;
1332 iPixelFormat = ChoosePixelFormat(hdc, &pfd);
1333 if(!iPixelFormat) {
1334 /* If this happens something is very wrong as ChoosePixelFormat barely fails */
1335 ERR("Can't find a suitable iPixelFormat\n");
1336 return FALSE;
1340 TRACE("Found iPixelFormat=%d for ColorFormat=%s, DepthStencilFormat=%s\n",
1341 iPixelFormat, debug_d3dformat(color_format->id), debug_d3dformat(ds_format->id));
1342 return iPixelFormat;
1345 /* Context activation is done by the caller. */
1346 static void bind_dummy_textures(const struct wined3d_device *device, const struct wined3d_context *context)
1348 const struct wined3d_gl_info *gl_info = context->gl_info;
1349 unsigned int i, count = min(MAX_COMBINED_SAMPLERS, gl_info->limits.combined_samplers);
1351 for (i = 0; i < count; ++i)
1353 GL_EXTCALL(glActiveTexture(GL_TEXTURE0 + i));
1354 checkGLcall("glActiveTexture");
1356 gl_info->gl_ops.gl.p_glBindTexture(GL_TEXTURE_2D, device->dummy_texture_2d[i]);
1357 checkGLcall("glBindTexture");
1359 if (gl_info->supported[ARB_TEXTURE_RECTANGLE])
1361 gl_info->gl_ops.gl.p_glBindTexture(GL_TEXTURE_RECTANGLE_ARB, device->dummy_texture_rect[i]);
1362 checkGLcall("glBindTexture");
1365 if (gl_info->supported[EXT_TEXTURE3D])
1367 gl_info->gl_ops.gl.p_glBindTexture(GL_TEXTURE_3D, device->dummy_texture_3d[i]);
1368 checkGLcall("glBindTexture");
1371 if (gl_info->supported[ARB_TEXTURE_CUBE_MAP])
1373 gl_info->gl_ops.gl.p_glBindTexture(GL_TEXTURE_CUBE_MAP, device->dummy_texture_cube[i]);
1374 checkGLcall("glBindTexture");
1379 static BOOL context_debug_output_enabled(const struct wined3d_gl_info *gl_info)
1381 return gl_info->supported[ARB_DEBUG_OUTPUT]
1382 && (ERR_ON(d3d) || FIXME_ON(d3d) || WARN_ON(d3d_perf));
1385 static void WINE_GLAPI wined3d_debug_callback(GLenum source, GLenum type, GLuint id,
1386 GLenum severity, GLsizei length, const char *message, void *ctx)
1388 switch (type)
1390 case GL_DEBUG_TYPE_ERROR_ARB:
1391 ERR("%p: %s.\n", ctx, debugstr_an(message, length));
1392 break;
1394 case GL_DEBUG_TYPE_DEPRECATED_BEHAVIOR_ARB:
1395 case GL_DEBUG_TYPE_UNDEFINED_BEHAVIOR_ARB:
1396 case GL_DEBUG_TYPE_PORTABILITY_ARB:
1397 FIXME("%p: %s.\n", ctx, debugstr_an(message, length));
1398 break;
1400 case GL_DEBUG_TYPE_PERFORMANCE_ARB:
1401 WARN_(d3d_perf)("%p: %s.\n", ctx, debugstr_an(message, length));
1402 break;
1404 default:
1405 FIXME("ctx %p, type %#x: %s.\n", ctx, type, debugstr_an(message, length));
1406 break;
1410 HGLRC context_create_wgl_attribs(const struct wined3d_gl_info *gl_info, HDC hdc, HGLRC share_ctx)
1412 HGLRC ctx;
1413 unsigned int ctx_attrib_idx = 0;
1414 GLint ctx_attribs[7], ctx_flags = 0;
1416 if (context_debug_output_enabled(gl_info))
1417 ctx_flags = WGL_CONTEXT_DEBUG_BIT_ARB;
1418 ctx_attribs[ctx_attrib_idx++] = WGL_CONTEXT_MAJOR_VERSION_ARB;
1419 ctx_attribs[ctx_attrib_idx++] = gl_info->selected_gl_version >> 16;
1420 ctx_attribs[ctx_attrib_idx++] = WGL_CONTEXT_MINOR_VERSION_ARB;
1421 ctx_attribs[ctx_attrib_idx++] = gl_info->selected_gl_version & 0xffff;
1422 if (gl_info->selected_gl_version >= MAKEDWORD_VERSION(3, 2))
1423 ctx_flags |= WGL_CONTEXT_FORWARD_COMPATIBLE_BIT_ARB;
1424 if (ctx_flags)
1426 ctx_attribs[ctx_attrib_idx++] = WGL_CONTEXT_FLAGS_ARB;
1427 ctx_attribs[ctx_attrib_idx++] = ctx_flags;
1429 ctx_attribs[ctx_attrib_idx] = 0;
1431 if (!(ctx = gl_info->p_wglCreateContextAttribsARB(hdc, share_ctx, ctx_attribs)))
1433 if (ctx_flags & WGL_CONTEXT_FORWARD_COMPATIBLE_BIT_ARB)
1435 ctx_attribs[ctx_attrib_idx - 1] &= ~WGL_CONTEXT_FORWARD_COMPATIBLE_BIT_ARB;
1436 if (!(ctx = gl_info->p_wglCreateContextAttribsARB(hdc, share_ctx, ctx_attribs)))
1437 WARN("Failed to create a WGL context with wglCreateContextAttribsARB, last error %#x.\n",
1438 GetLastError());
1441 return ctx;
1444 struct wined3d_context *context_create(struct wined3d_swapchain *swapchain,
1445 struct wined3d_surface *target, const struct wined3d_format *ds_format)
1447 struct wined3d_device *device = swapchain->device;
1448 const struct wined3d_gl_info *gl_info = &device->adapter->gl_info;
1449 const struct wined3d_format *color_format;
1450 struct wined3d_context *ret;
1451 BOOL auxBuffers = FALSE;
1452 HGLRC ctx, share_ctx;
1453 int pixel_format;
1454 unsigned int s;
1455 int swap_interval;
1456 DWORD state;
1457 HDC hdc;
1458 BOOL hdc_is_private = FALSE;
1460 TRACE("swapchain %p, target %p, window %p.\n", swapchain, target, swapchain->win_handle);
1462 ret = HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, sizeof(*ret));
1463 if (!ret)
1464 return NULL;
1466 ret->blit_targets = HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY,
1467 gl_info->limits.buffers * sizeof(*ret->blit_targets));
1468 if (!ret->blit_targets)
1469 goto out;
1471 ret->draw_buffers = HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY,
1472 gl_info->limits.buffers * sizeof(*ret->draw_buffers));
1473 if (!ret->draw_buffers)
1474 goto out;
1476 ret->free_timestamp_query_size = 4;
1477 ret->free_timestamp_queries = HeapAlloc(GetProcessHeap(), 0,
1478 ret->free_timestamp_query_size * sizeof(*ret->free_timestamp_queries));
1479 if (!ret->free_timestamp_queries)
1480 goto out;
1481 list_init(&ret->timestamp_queries);
1483 ret->free_occlusion_query_size = 4;
1484 ret->free_occlusion_queries = HeapAlloc(GetProcessHeap(), 0,
1485 ret->free_occlusion_query_size * sizeof(*ret->free_occlusion_queries));
1486 if (!ret->free_occlusion_queries)
1487 goto out;
1489 list_init(&ret->occlusion_queries);
1491 ret->free_event_query_size = 4;
1492 ret->free_event_queries = HeapAlloc(GetProcessHeap(), 0,
1493 ret->free_event_query_size * sizeof(*ret->free_event_queries));
1494 if (!ret->free_event_queries)
1495 goto out;
1497 list_init(&ret->event_queries);
1498 list_init(&ret->fbo_list);
1499 list_init(&ret->fbo_destroy_list);
1501 if (!device->shader_backend->shader_allocate_context_data(ret))
1503 ERR("Failed to allocate shader backend context data.\n");
1504 goto out;
1506 if (!device->adapter->fragment_pipe->allocate_context_data(ret))
1508 ERR("Failed to allocate fragment pipeline context data.\n");
1509 goto out;
1512 /* Initialize the texture unit mapping to a 1:1 mapping */
1513 for (s = 0; s < MAX_COMBINED_SAMPLERS; ++s)
1515 if (s < gl_info->limits.fragment_samplers)
1517 ret->tex_unit_map[s] = s;
1518 ret->rev_tex_unit_map[s] = s;
1520 else
1522 ret->tex_unit_map[s] = WINED3D_UNMAPPED_STAGE;
1523 ret->rev_tex_unit_map[s] = WINED3D_UNMAPPED_STAGE;
1527 if (!(hdc = GetDC(swapchain->win_handle)))
1529 WARN("Failed to retrieve device context, trying swapchain backup.\n");
1531 if ((hdc = swapchain_get_backup_dc(swapchain)))
1532 hdc_is_private = TRUE;
1533 else
1535 ERR("Failed to retrieve a device context.\n");
1536 goto out;
1540 color_format = target->resource.format;
1542 /* In case of ORM_BACKBUFFER, make sure to request an alpha component for
1543 * X4R4G4B4/X8R8G8B8 as we might need it for the backbuffer. */
1544 if (wined3d_settings.offscreen_rendering_mode == ORM_BACKBUFFER)
1546 auxBuffers = TRUE;
1548 if (color_format->id == WINED3DFMT_B4G4R4X4_UNORM)
1549 color_format = wined3d_get_format(gl_info, WINED3DFMT_B4G4R4A4_UNORM);
1550 else if (color_format->id == WINED3DFMT_B8G8R8X8_UNORM)
1551 color_format = wined3d_get_format(gl_info, WINED3DFMT_B8G8R8A8_UNORM);
1554 /* DirectDraw supports 8bit paletted render targets and these are used by
1555 * old games like StarCraft and C&C. Most modern hardware doesn't support
1556 * 8bit natively so we perform some form of 8bit -> 32bit conversion. The
1557 * conversion (ab)uses the alpha component for storing the palette index.
1558 * For this reason we require a format with 8bit alpha, so request
1559 * A8R8G8B8. */
1560 if (color_format->id == WINED3DFMT_P8_UINT)
1561 color_format = wined3d_get_format(gl_info, WINED3DFMT_B8G8R8A8_UNORM);
1563 /* Try to find a pixel format which matches our requirements. */
1564 pixel_format = context_choose_pixel_format(device, hdc, color_format, ds_format, auxBuffers, FALSE);
1566 /* Try to locate a compatible format if we weren't able to find anything. */
1567 if (!pixel_format)
1569 TRACE("Trying to locate a compatible pixel format because an exact match failed.\n");
1570 pixel_format = context_choose_pixel_format(device, hdc, color_format, ds_format, auxBuffers, TRUE);
1573 /* If we still don't have a pixel format, something is very wrong as ChoosePixelFormat barely fails */
1574 if (!pixel_format)
1576 ERR("Can't find a suitable pixel format.\n");
1577 goto out;
1580 context_enter(ret);
1582 ret->gl_info = gl_info;
1584 if (!context_set_pixel_format(ret, hdc, hdc_is_private, pixel_format))
1586 ERR("Failed to set pixel format %d on device context %p.\n", pixel_format, hdc);
1587 context_release(ret);
1588 goto out;
1591 share_ctx = device->context_count ? device->contexts[0]->glCtx : NULL;
1592 if (gl_info->p_wglCreateContextAttribsARB)
1594 if (!(ctx = context_create_wgl_attribs(gl_info, hdc, share_ctx)))
1595 goto out;
1597 else
1599 if (!(ctx = wglCreateContext(hdc)))
1601 ERR("Failed to create a WGL context.\n");
1602 context_release(ret);
1603 goto out;
1606 if (share_ctx && !wglShareLists(share_ctx, ctx))
1608 ERR("wglShareLists(%p, %p) failed, last error %#x.\n", share_ctx, ctx, GetLastError());
1609 context_release(ret);
1610 if (!wglDeleteContext(ctx))
1611 ERR("wglDeleteContext(%p) failed, last error %#x.\n", ctx, GetLastError());
1612 goto out;
1616 if (!device_context_add(device, ret))
1618 ERR("Failed to add the newly created context to the context list\n");
1619 context_release(ret);
1620 if (!wglDeleteContext(ctx))
1621 ERR("wglDeleteContext(%p) failed, last error %#x.\n", ctx, GetLastError());
1622 goto out;
1625 ret->d3d_info = &device->adapter->d3d_info;
1626 ret->state_table = device->StateTable;
1628 /* Mark all states dirty to force a proper initialization of the states
1629 * on the first use of the context. */
1630 for (state = 0; state <= STATE_HIGHEST; ++state)
1632 if (ret->state_table[state].representative)
1633 context_invalidate_state(ret, state);
1636 ret->swapchain = swapchain;
1637 ret->current_rt = target;
1638 ret->tid = GetCurrentThreadId();
1640 ret->render_offscreen = wined3d_resource_is_offscreen(&target->container->resource);
1641 ret->draw_buffers_mask = context_generate_rt_mask(GL_BACK);
1642 ret->valid = 1;
1644 ret->glCtx = ctx;
1645 ret->win_handle = swapchain->win_handle;
1646 ret->hdc = hdc;
1647 ret->hdc_is_private = hdc_is_private;
1648 ret->hdc_has_format = TRUE;
1649 ret->pixel_format = pixel_format;
1650 ret->needs_set = 1;
1652 /* Set up the context defaults */
1653 if (!context_set_current(ret))
1655 ERR("Cannot activate context to set up defaults.\n");
1656 device_context_remove(device, ret);
1657 context_release(ret);
1658 if (!wglDeleteContext(ctx))
1659 ERR("wglDeleteContext(%p) failed, last error %#x.\n", ctx, GetLastError());
1660 goto out;
1663 if (context_debug_output_enabled(gl_info))
1665 GL_EXTCALL(glDebugMessageCallbackARB(wined3d_debug_callback, ret));
1666 if (TRACE_ON(d3d_synchronous))
1667 gl_info->gl_ops.gl.p_glEnable(GL_DEBUG_OUTPUT_SYNCHRONOUS_ARB);
1668 GL_EXTCALL(glDebugMessageControlARB(GL_DONT_CARE, GL_DONT_CARE, GL_DONT_CARE, 0, NULL, GL_FALSE));
1669 if (ERR_ON(d3d))
1671 GL_EXTCALL(glDebugMessageControlARB(GL_DONT_CARE, GL_DEBUG_TYPE_ERROR_ARB,
1672 GL_DONT_CARE, 0, NULL, GL_TRUE));
1674 if (FIXME_ON(d3d))
1676 GL_EXTCALL(glDebugMessageControlARB(GL_DONT_CARE, GL_DEBUG_TYPE_DEPRECATED_BEHAVIOR_ARB,
1677 GL_DONT_CARE, 0, NULL, GL_TRUE));
1678 GL_EXTCALL(glDebugMessageControlARB(GL_DONT_CARE, GL_DEBUG_TYPE_UNDEFINED_BEHAVIOR_ARB,
1679 GL_DONT_CARE, 0, NULL, GL_TRUE));
1680 GL_EXTCALL(glDebugMessageControlARB(GL_DONT_CARE, GL_DEBUG_TYPE_PORTABILITY_ARB,
1681 GL_DONT_CARE, 0, NULL, GL_TRUE));
1683 if (WARN_ON(d3d_perf))
1685 GL_EXTCALL(glDebugMessageControlARB(GL_DONT_CARE, GL_DEBUG_TYPE_PERFORMANCE_ARB,
1686 GL_DONT_CARE, 0, NULL, GL_TRUE));
1690 switch (swapchain->desc.swap_interval)
1692 case WINED3DPRESENT_INTERVAL_IMMEDIATE:
1693 swap_interval = 0;
1694 break;
1695 case WINED3DPRESENT_INTERVAL_DEFAULT:
1696 case WINED3DPRESENT_INTERVAL_ONE:
1697 swap_interval = 1;
1698 break;
1699 case WINED3DPRESENT_INTERVAL_TWO:
1700 swap_interval = 2;
1701 break;
1702 case WINED3DPRESENT_INTERVAL_THREE:
1703 swap_interval = 3;
1704 break;
1705 case WINED3DPRESENT_INTERVAL_FOUR:
1706 swap_interval = 4;
1707 break;
1708 default:
1709 FIXME("Unknown swap interval %#x.\n", swapchain->desc.swap_interval);
1710 swap_interval = 1;
1713 if (gl_info->supported[WGL_EXT_SWAP_CONTROL])
1715 if (!GL_EXTCALL(wglSwapIntervalEXT(swap_interval)))
1716 ERR("wglSwapIntervalEXT failed to set swap interval %d for context %p, last error %#x\n",
1717 swap_interval, ret, GetLastError());
1720 gl_info->gl_ops.gl.p_glGetIntegerv(GL_AUX_BUFFERS, &ret->aux_buffers);
1722 TRACE("Setting up the screen\n");
1724 gl_info->gl_ops.gl.p_glLightModeli(GL_LIGHT_MODEL_LOCAL_VIEWER, GL_TRUE);
1725 checkGLcall("glLightModeli(GL_LIGHT_MODEL_LOCAL_VIEWER, GL_TRUE);");
1727 gl_info->gl_ops.gl.p_glTexEnvf(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_COMBINE_EXT);
1728 checkGLcall("glTexEnvf(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_COMBINE_EXT);");
1730 gl_info->gl_ops.gl.p_glLightModeli(GL_LIGHT_MODEL_COLOR_CONTROL, GL_SEPARATE_SPECULAR_COLOR);
1731 checkGLcall("glLightModeli(GL_LIGHT_MODEL_COLOR_CONTROL, GL_SEPARATE_SPECULAR_COLOR);");
1733 gl_info->gl_ops.gl.p_glPixelStorei(GL_PACK_ALIGNMENT, device->surface_alignment);
1734 checkGLcall("glPixelStorei(GL_PACK_ALIGNMENT, device->surface_alignment);");
1735 gl_info->gl_ops.gl.p_glPixelStorei(GL_UNPACK_ALIGNMENT, 1);
1736 checkGLcall("glPixelStorei(GL_UNPACK_ALIGNMENT, device->surface_alignment);");
1738 if (!gl_info->supported[WINED3D_GL_LEGACY_CONTEXT])
1740 GLuint vao;
1742 GL_EXTCALL(glGenVertexArrays(1, &vao));
1743 GL_EXTCALL(glBindVertexArray(vao));
1744 checkGLcall("creating VAO");
1747 if (gl_info->supported[ARB_VERTEX_BLEND])
1749 /* Direct3D always uses n-1 weights for n world matrices and uses
1750 * 1 - sum for the last one this is equal to GL_WEIGHT_SUM_UNITY_ARB.
1751 * Enabling it doesn't do anything unless GL_VERTEX_BLEND_ARB isn't
1752 * enabled as well. */
1753 gl_info->gl_ops.gl.p_glEnable(GL_WEIGHT_SUM_UNITY_ARB);
1754 checkGLcall("glEnable(GL_WEIGHT_SUM_UNITY_ARB)");
1756 if (gl_info->supported[NV_TEXTURE_SHADER2])
1758 /* Set up the previous texture input for all shader units. This applies to bump mapping, and in d3d
1759 * the previous texture where to source the offset from is always unit - 1.
1761 for (s = 1; s < gl_info->limits.textures; ++s)
1763 context_active_texture(ret, gl_info, s);
1764 gl_info->gl_ops.gl.p_glTexEnvi(GL_TEXTURE_SHADER_NV,
1765 GL_PREVIOUS_TEXTURE_INPUT_NV, GL_TEXTURE0_ARB + s - 1);
1766 checkGLcall("glTexEnvi(GL_TEXTURE_SHADER_NV, GL_PREVIOUS_TEXTURE_INPUT_NV, ...");
1769 if (gl_info->supported[ARB_FRAGMENT_PROGRAM])
1771 /* MacOS(radeon X1600 at least, but most likely others too) refuses to draw if GLSL and ARBFP are
1772 * enabled, but the currently bound arbfp program is 0. Enabling ARBFP with prog 0 is invalid, but
1773 * GLSL should bypass this. This causes problems in programs that never use the fixed function pipeline,
1774 * because the ARBFP extension is enabled by the ARBFP pipeline at context creation, but no program
1775 * is ever assigned.
1777 * So make sure a program is assigned to each context. The first real ARBFP use will set a different
1778 * program and the dummy program is destroyed when the context is destroyed.
1780 static const char dummy_program[] =
1781 "!!ARBfp1.0\n"
1782 "MOV result.color, fragment.color.primary;\n"
1783 "END\n";
1784 GL_EXTCALL(glGenProgramsARB(1, &ret->dummy_arbfp_prog));
1785 GL_EXTCALL(glBindProgramARB(GL_FRAGMENT_PROGRAM_ARB, ret->dummy_arbfp_prog));
1786 GL_EXTCALL(glProgramStringARB(GL_FRAGMENT_PROGRAM_ARB, GL_PROGRAM_FORMAT_ASCII_ARB, strlen(dummy_program), dummy_program));
1789 if (gl_info->supported[ARB_POINT_SPRITE])
1791 for (s = 0; s < gl_info->limits.textures; ++s)
1793 context_active_texture(ret, gl_info, s);
1794 gl_info->gl_ops.gl.p_glTexEnvi(GL_POINT_SPRITE_ARB, GL_COORD_REPLACE_ARB, GL_TRUE);
1795 checkGLcall("glTexEnvi(GL_POINT_SPRITE_ARB, GL_COORD_REPLACE_ARB, GL_TRUE)");
1799 if (gl_info->supported[ARB_PROVOKING_VERTEX])
1801 GL_EXTCALL(glProvokingVertex(GL_FIRST_VERTEX_CONVENTION));
1803 else if (gl_info->supported[EXT_PROVOKING_VERTEX])
1805 GL_EXTCALL(glProvokingVertexEXT(GL_FIRST_VERTEX_CONVENTION_EXT));
1807 device->shader_backend->shader_init_context_state(ret);
1808 ret->shader_update_mask = (1 << WINED3D_SHADER_TYPE_PIXEL)
1809 | (1 << WINED3D_SHADER_TYPE_VERTEX)
1810 | (1 << WINED3D_SHADER_TYPE_GEOMETRY);
1812 /* If this happens to be the first context for the device, dummy textures
1813 * are not created yet. In that case, they will be created (and bound) by
1814 * create_dummy_textures right after this context is initialized. */
1815 if (device->dummy_texture_2d[0])
1816 bind_dummy_textures(device, ret);
1818 TRACE("Created context %p.\n", ret);
1820 return ret;
1822 out:
1823 device->shader_backend->shader_free_context_data(ret);
1824 device->adapter->fragment_pipe->free_context_data(ret);
1825 HeapFree(GetProcessHeap(), 0, ret->free_event_queries);
1826 HeapFree(GetProcessHeap(), 0, ret->free_occlusion_queries);
1827 HeapFree(GetProcessHeap(), 0, ret->free_timestamp_queries);
1828 HeapFree(GetProcessHeap(), 0, ret->draw_buffers);
1829 HeapFree(GetProcessHeap(), 0, ret->blit_targets);
1830 HeapFree(GetProcessHeap(), 0, ret);
1831 return NULL;
1834 void context_destroy(struct wined3d_device *device, struct wined3d_context *context)
1836 BOOL destroy;
1838 TRACE("Destroying ctx %p\n", context);
1840 if (context->tid == GetCurrentThreadId() || !context->current)
1842 context_destroy_gl_resources(context);
1843 TlsSetValue(wined3d_context_tls_idx, NULL);
1844 destroy = TRUE;
1846 else
1848 /* Make a copy of gl_info for context_destroy_gl_resources use, the one
1849 in wined3d_adapter may go away in the meantime */
1850 struct wined3d_gl_info *gl_info = HeapAlloc(GetProcessHeap(), 0, sizeof(*gl_info));
1851 *gl_info = *context->gl_info;
1852 context->gl_info = gl_info;
1853 context->destroyed = 1;
1854 destroy = FALSE;
1857 device->shader_backend->shader_free_context_data(context);
1858 device->adapter->fragment_pipe->free_context_data(context);
1859 HeapFree(GetProcessHeap(), 0, context->draw_buffers);
1860 HeapFree(GetProcessHeap(), 0, context->blit_targets);
1861 device_context_remove(device, context);
1862 if (destroy) HeapFree(GetProcessHeap(), 0, context);
1865 /* Context activation is done by the caller. */
1866 static void set_blit_dimension(const struct wined3d_gl_info *gl_info, UINT width, UINT height)
1868 const GLdouble projection[] =
1870 2.0 / width, 0.0, 0.0, 0.0,
1871 0.0, 2.0 / height, 0.0, 0.0,
1872 0.0, 0.0, 2.0, 0.0,
1873 -1.0, -1.0, -1.0, 1.0,
1876 gl_info->gl_ops.gl.p_glMatrixMode(GL_PROJECTION);
1877 checkGLcall("glMatrixMode(GL_PROJECTION)");
1878 gl_info->gl_ops.gl.p_glLoadMatrixd(projection);
1879 checkGLcall("glLoadMatrixd");
1880 gl_info->gl_ops.gl.p_glViewport(0, 0, width, height);
1881 checkGLcall("glViewport");
1884 static void context_get_rt_size(const struct wined3d_context *context, SIZE *size)
1886 const struct wined3d_surface *rt = context->current_rt;
1888 if (rt->container->swapchain && rt->container->swapchain->front_buffer == rt->container)
1890 RECT window_size;
1892 GetClientRect(context->win_handle, &window_size);
1893 size->cx = window_size.right - window_size.left;
1894 size->cy = window_size.bottom - window_size.top;
1896 return;
1899 size->cx = rt->resource.width;
1900 size->cy = rt->resource.height;
1903 /*****************************************************************************
1904 * SetupForBlit
1906 * Sets up a context for DirectDraw blitting.
1907 * All texture units are disabled, texture unit 0 is set as current unit
1908 * fog, lighting, blending, alpha test, z test, scissor test, culling disabled
1909 * color writing enabled for all channels
1910 * register combiners disabled, shaders disabled
1911 * world matrix is set to identity, texture matrix 0 too
1912 * projection matrix is setup for drawing screen coordinates
1914 * Params:
1915 * This: Device to activate the context for
1916 * context: Context to setup
1918 *****************************************************************************/
1919 /* Context activation is done by the caller. */
1920 static void SetupForBlit(const struct wined3d_device *device, struct wined3d_context *context)
1922 int i;
1923 const struct wined3d_gl_info *gl_info = context->gl_info;
1924 DWORD sampler;
1925 SIZE rt_size;
1927 TRACE("Setting up context %p for blitting\n", context);
1929 context_get_rt_size(context, &rt_size);
1931 if (context->last_was_blit)
1933 if (context->blit_w != rt_size.cx || context->blit_h != rt_size.cy)
1935 set_blit_dimension(gl_info, rt_size.cx, rt_size.cy);
1936 context->blit_w = rt_size.cx;
1937 context->blit_h = rt_size.cy;
1938 /* No need to dirtify here, the states are still dirtified because
1939 * they weren't applied since the last SetupForBlit() call. */
1941 TRACE("Context is already set up for blitting, nothing to do\n");
1942 return;
1944 context->last_was_blit = TRUE;
1946 /* Disable all textures. The caller can then bind a texture it wants to blit
1947 * from
1949 * The blitting code uses (for now) the fixed function pipeline, so make sure to reset all fixed
1950 * function texture unit. No need to care for higher samplers
1952 for (i = gl_info->limits.textures - 1; i > 0 ; --i)
1954 sampler = context->rev_tex_unit_map[i];
1955 context_active_texture(context, gl_info, i);
1957 if (gl_info->supported[ARB_TEXTURE_CUBE_MAP])
1959 gl_info->gl_ops.gl.p_glDisable(GL_TEXTURE_CUBE_MAP_ARB);
1960 checkGLcall("glDisable GL_TEXTURE_CUBE_MAP_ARB");
1962 gl_info->gl_ops.gl.p_glDisable(GL_TEXTURE_3D);
1963 checkGLcall("glDisable GL_TEXTURE_3D");
1964 if (gl_info->supported[ARB_TEXTURE_RECTANGLE])
1966 gl_info->gl_ops.gl.p_glDisable(GL_TEXTURE_RECTANGLE_ARB);
1967 checkGLcall("glDisable GL_TEXTURE_RECTANGLE_ARB");
1969 gl_info->gl_ops.gl.p_glDisable(GL_TEXTURE_2D);
1970 checkGLcall("glDisable GL_TEXTURE_2D");
1972 gl_info->gl_ops.gl.p_glTexEnvi(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_REPLACE);
1973 checkGLcall("glTexEnvi(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_REPLACE);");
1975 if (sampler != WINED3D_UNMAPPED_STAGE)
1977 if (sampler < MAX_TEXTURES)
1978 context_invalidate_state(context, STATE_TEXTURESTAGE(sampler, WINED3D_TSS_COLOR_OP));
1979 context_invalidate_state(context, STATE_SAMPLER(sampler));
1982 if (gl_info->supported[ARB_SAMPLER_OBJECTS])
1983 GL_EXTCALL(glBindSampler(0, 0));
1984 context_active_texture(context, gl_info, 0);
1986 sampler = context->rev_tex_unit_map[0];
1988 if (gl_info->supported[ARB_TEXTURE_CUBE_MAP])
1990 gl_info->gl_ops.gl.p_glDisable(GL_TEXTURE_CUBE_MAP_ARB);
1991 checkGLcall("glDisable GL_TEXTURE_CUBE_MAP_ARB");
1993 gl_info->gl_ops.gl.p_glDisable(GL_TEXTURE_3D);
1994 checkGLcall("glDisable GL_TEXTURE_3D");
1995 if (gl_info->supported[ARB_TEXTURE_RECTANGLE])
1997 gl_info->gl_ops.gl.p_glDisable(GL_TEXTURE_RECTANGLE_ARB);
1998 checkGLcall("glDisable GL_TEXTURE_RECTANGLE_ARB");
2000 gl_info->gl_ops.gl.p_glDisable(GL_TEXTURE_2D);
2001 checkGLcall("glDisable GL_TEXTURE_2D");
2003 gl_info->gl_ops.gl.p_glTexEnvi(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_REPLACE);
2005 gl_info->gl_ops.gl.p_glMatrixMode(GL_TEXTURE);
2006 checkGLcall("glMatrixMode(GL_TEXTURE)");
2007 gl_info->gl_ops.gl.p_glLoadIdentity();
2008 checkGLcall("glLoadIdentity()");
2010 if (gl_info->supported[EXT_TEXTURE_LOD_BIAS])
2012 gl_info->gl_ops.gl.p_glTexEnvf(GL_TEXTURE_FILTER_CONTROL_EXT,
2013 GL_TEXTURE_LOD_BIAS_EXT, 0.0f);
2014 checkGLcall("glTexEnvf GL_TEXTURE_LOD_BIAS_EXT ...");
2017 if (sampler != WINED3D_UNMAPPED_STAGE)
2019 if (sampler < MAX_TEXTURES)
2021 context_invalidate_state(context, STATE_TRANSFORM(WINED3D_TS_TEXTURE0 + sampler));
2022 context_invalidate_state(context, STATE_TEXTURESTAGE(sampler, WINED3D_TSS_COLOR_OP));
2024 context_invalidate_state(context, STATE_SAMPLER(sampler));
2027 /* Other misc states */
2028 gl_info->gl_ops.gl.p_glDisable(GL_ALPHA_TEST);
2029 checkGLcall("glDisable(GL_ALPHA_TEST)");
2030 context_invalidate_state(context, STATE_RENDER(WINED3D_RS_ALPHATESTENABLE));
2031 gl_info->gl_ops.gl.p_glDisable(GL_LIGHTING);
2032 checkGLcall("glDisable GL_LIGHTING");
2033 context_invalidate_state(context, STATE_RENDER(WINED3D_RS_LIGHTING));
2034 gl_info->gl_ops.gl.p_glDisable(GL_DEPTH_TEST);
2035 checkGLcall("glDisable GL_DEPTH_TEST");
2036 context_invalidate_state(context, STATE_RENDER(WINED3D_RS_ZENABLE));
2037 glDisableWINE(GL_FOG);
2038 checkGLcall("glDisable GL_FOG");
2039 context_invalidate_state(context, STATE_RENDER(WINED3D_RS_FOGENABLE));
2040 gl_info->gl_ops.gl.p_glDisable(GL_BLEND);
2041 checkGLcall("glDisable GL_BLEND");
2042 context_invalidate_state(context, STATE_RENDER(WINED3D_RS_ALPHABLENDENABLE));
2043 gl_info->gl_ops.gl.p_glDisable(GL_CULL_FACE);
2044 checkGLcall("glDisable GL_CULL_FACE");
2045 context_invalidate_state(context, STATE_RENDER(WINED3D_RS_CULLMODE));
2046 gl_info->gl_ops.gl.p_glDisable(GL_STENCIL_TEST);
2047 checkGLcall("glDisable GL_STENCIL_TEST");
2048 context_invalidate_state(context, STATE_RENDER(WINED3D_RS_STENCILENABLE));
2049 gl_info->gl_ops.gl.p_glDisable(GL_SCISSOR_TEST);
2050 checkGLcall("glDisable GL_SCISSOR_TEST");
2051 context_invalidate_state(context, STATE_RENDER(WINED3D_RS_SCISSORTESTENABLE));
2052 if (gl_info->supported[ARB_POINT_SPRITE])
2054 gl_info->gl_ops.gl.p_glDisable(GL_POINT_SPRITE_ARB);
2055 checkGLcall("glDisable GL_POINT_SPRITE_ARB");
2056 context_invalidate_state(context, STATE_RENDER(WINED3D_RS_POINTSPRITEENABLE));
2058 gl_info->gl_ops.gl.p_glColorMask(GL_TRUE, GL_TRUE,GL_TRUE,GL_TRUE);
2059 checkGLcall("glColorMask");
2060 context_invalidate_state(context, STATE_RENDER(WINED3D_RS_COLORWRITEENABLE));
2061 context_invalidate_state(context, STATE_RENDER(WINED3D_RS_COLORWRITEENABLE1));
2062 context_invalidate_state(context, STATE_RENDER(WINED3D_RS_COLORWRITEENABLE2));
2063 context_invalidate_state(context, STATE_RENDER(WINED3D_RS_COLORWRITEENABLE3));
2064 if (gl_info->supported[EXT_SECONDARY_COLOR])
2066 gl_info->gl_ops.gl.p_glDisable(GL_COLOR_SUM_EXT);
2067 context_invalidate_state(context, STATE_RENDER(WINED3D_RS_SPECULARENABLE));
2068 checkGLcall("glDisable(GL_COLOR_SUM_EXT)");
2071 /* Setup transforms */
2072 gl_info->gl_ops.gl.p_glMatrixMode(GL_MODELVIEW);
2073 checkGLcall("glMatrixMode(GL_MODELVIEW)");
2074 gl_info->gl_ops.gl.p_glLoadIdentity();
2075 checkGLcall("glLoadIdentity()");
2076 context_invalidate_state(context, STATE_TRANSFORM(WINED3D_TS_WORLD_MATRIX(0)));
2078 context->last_was_rhw = TRUE;
2079 context_invalidate_state(context, STATE_VDECL); /* because of last_was_rhw = TRUE */
2081 gl_info->gl_ops.gl.p_glDisable(GL_CLIP_PLANE0); checkGLcall("glDisable(clip plane 0)");
2082 gl_info->gl_ops.gl.p_glDisable(GL_CLIP_PLANE1); checkGLcall("glDisable(clip plane 1)");
2083 gl_info->gl_ops.gl.p_glDisable(GL_CLIP_PLANE2); checkGLcall("glDisable(clip plane 2)");
2084 gl_info->gl_ops.gl.p_glDisable(GL_CLIP_PLANE3); checkGLcall("glDisable(clip plane 3)");
2085 gl_info->gl_ops.gl.p_glDisable(GL_CLIP_PLANE4); checkGLcall("glDisable(clip plane 4)");
2086 gl_info->gl_ops.gl.p_glDisable(GL_CLIP_PLANE5); checkGLcall("glDisable(clip plane 5)");
2087 context_invalidate_state(context, STATE_RENDER(WINED3D_RS_CLIPPING));
2089 set_blit_dimension(gl_info, rt_size.cx, rt_size.cy);
2091 /* Disable shaders */
2092 device->shader_backend->shader_disable(device->shader_priv, context);
2094 context->blit_w = rt_size.cx;
2095 context->blit_h = rt_size.cy;
2096 context_invalidate_state(context, STATE_VIEWPORT);
2097 context_invalidate_state(context, STATE_TRANSFORM(WINED3D_TS_PROJECTION));
2100 static inline BOOL is_rt_mask_onscreen(DWORD rt_mask)
2102 return rt_mask & (1 << 31);
2105 static inline GLenum draw_buffer_from_rt_mask(DWORD rt_mask)
2107 return rt_mask & ~(1 << 31);
2110 /* Context activation is done by the caller. */
2111 static void context_apply_draw_buffers(struct wined3d_context *context, DWORD rt_mask)
2113 const struct wined3d_gl_info *gl_info = context->gl_info;
2115 if (!rt_mask)
2117 gl_info->gl_ops.gl.p_glDrawBuffer(GL_NONE);
2118 checkGLcall("glDrawBuffer()");
2120 else if (is_rt_mask_onscreen(rt_mask))
2122 gl_info->gl_ops.gl.p_glDrawBuffer(draw_buffer_from_rt_mask(rt_mask));
2123 checkGLcall("glDrawBuffer()");
2125 else
2127 if (wined3d_settings.offscreen_rendering_mode == ORM_FBO)
2129 unsigned int i = 0;
2131 while (rt_mask)
2133 if (rt_mask & 1)
2134 context->draw_buffers[i] = GL_COLOR_ATTACHMENT0 + i;
2135 else
2136 context->draw_buffers[i] = GL_NONE;
2138 rt_mask >>= 1;
2139 ++i;
2142 if (gl_info->supported[ARB_DRAW_BUFFERS])
2144 GL_EXTCALL(glDrawBuffers(i, context->draw_buffers));
2145 checkGLcall("glDrawBuffers()");
2147 else
2149 gl_info->gl_ops.gl.p_glDrawBuffer(context->draw_buffers[0]);
2150 checkGLcall("glDrawBuffer()");
2153 else
2155 ERR("Unexpected draw buffers mask with backbuffer ORM.\n");
2160 /* Context activation is done by the caller. */
2161 void context_set_draw_buffer(struct wined3d_context *context, GLenum buffer)
2163 const struct wined3d_gl_info *gl_info = context->gl_info;
2164 DWORD *current_mask = context->current_fbo ? &context->current_fbo->rt_mask : &context->draw_buffers_mask;
2165 DWORD new_mask = context_generate_rt_mask(buffer);
2167 if (new_mask == *current_mask)
2168 return;
2170 gl_info->gl_ops.gl.p_glDrawBuffer(buffer);
2171 checkGLcall("glDrawBuffer()");
2173 *current_mask = new_mask;
2176 /* Context activation is done by the caller. */
2177 void context_active_texture(struct wined3d_context *context, const struct wined3d_gl_info *gl_info, unsigned int unit)
2179 GL_EXTCALL(glActiveTexture(GL_TEXTURE0 + unit));
2180 checkGLcall("glActiveTexture");
2181 context->active_texture = unit;
2184 void context_bind_texture(struct wined3d_context *context, GLenum target, GLuint name)
2186 const struct wined3d_gl_info *gl_info = context->gl_info;
2187 DWORD unit = context->active_texture;
2188 DWORD old_texture_type = context->texture_type[unit];
2190 if (name)
2192 gl_info->gl_ops.gl.p_glBindTexture(target, name);
2193 checkGLcall("glBindTexture");
2195 else
2197 target = GL_NONE;
2200 if (old_texture_type != target)
2202 const struct wined3d_device *device = context->swapchain->device;
2204 switch (old_texture_type)
2206 case GL_NONE:
2207 /* nothing to do */
2208 break;
2209 case GL_TEXTURE_2D:
2210 gl_info->gl_ops.gl.p_glBindTexture(GL_TEXTURE_2D, device->dummy_texture_2d[unit]);
2211 checkGLcall("glBindTexture");
2212 break;
2213 case GL_TEXTURE_RECTANGLE_ARB:
2214 gl_info->gl_ops.gl.p_glBindTexture(GL_TEXTURE_RECTANGLE_ARB, device->dummy_texture_rect[unit]);
2215 checkGLcall("glBindTexture");
2216 break;
2217 case GL_TEXTURE_CUBE_MAP:
2218 gl_info->gl_ops.gl.p_glBindTexture(GL_TEXTURE_CUBE_MAP, device->dummy_texture_cube[unit]);
2219 checkGLcall("glBindTexture");
2220 break;
2221 case GL_TEXTURE_3D:
2222 gl_info->gl_ops.gl.p_glBindTexture(GL_TEXTURE_3D, device->dummy_texture_3d[unit]);
2223 checkGLcall("glBindTexture");
2224 break;
2225 default:
2226 ERR("Unexpected texture target %#x\n", old_texture_type);
2229 context->texture_type[unit] = target;
2233 static void context_set_render_offscreen(struct wined3d_context *context, BOOL offscreen)
2235 if (context->render_offscreen == offscreen) return;
2237 context_invalidate_state(context, STATE_POINTSPRITECOORDORIGIN);
2238 context_invalidate_state(context, STATE_TRANSFORM(WINED3D_TS_PROJECTION));
2239 context_invalidate_state(context, STATE_VIEWPORT);
2240 context_invalidate_state(context, STATE_SCISSORRECT);
2241 context_invalidate_state(context, STATE_FRONTFACE);
2242 context->render_offscreen = offscreen;
2245 static BOOL match_depth_stencil_format(const struct wined3d_format *existing,
2246 const struct wined3d_format *required)
2248 BYTE existing_depth, existing_stencil, required_depth, required_stencil;
2250 if (existing == required)
2251 return TRUE;
2252 if ((existing->flags[WINED3D_GL_RES_TYPE_TEX_2D] & WINED3DFMT_FLAG_FLOAT)
2253 != (required->flags[WINED3D_GL_RES_TYPE_TEX_2D] & WINED3DFMT_FLAG_FLOAT))
2254 return FALSE;
2256 getDepthStencilBits(existing, &existing_depth, &existing_stencil);
2257 getDepthStencilBits(required, &required_depth, &required_stencil);
2259 if(existing_depth < required_depth) return FALSE;
2260 /* If stencil bits are used the exact amount is required - otherwise wrapping
2261 * won't work correctly */
2262 if(required_stencil && required_stencil != existing_stencil) return FALSE;
2263 return TRUE;
2266 /* The caller provides a context */
2267 static void context_validate_onscreen_formats(struct wined3d_context *context,
2268 const struct wined3d_rendertarget_view *depth_stencil)
2270 /* Onscreen surfaces are always in a swapchain */
2271 struct wined3d_swapchain *swapchain = context->current_rt->container->swapchain;
2273 if (context->render_offscreen || !depth_stencil) return;
2274 if (match_depth_stencil_format(swapchain->ds_format, depth_stencil->format)) return;
2276 /* TODO: If the requested format would satisfy the needs of the existing one(reverse match),
2277 * or no onscreen depth buffer was created, the OpenGL drawable could be changed to the new
2278 * format. */
2279 WARN("Depth stencil format is not supported by WGL, rendering the backbuffer in an FBO\n");
2281 /* The currently active context is the necessary context to access the swapchain's onscreen buffers */
2282 surface_load_location(context->current_rt, WINED3D_LOCATION_TEXTURE_RGB);
2283 swapchain->render_to_fbo = TRUE;
2284 swapchain_update_draw_bindings(swapchain);
2285 context_set_render_offscreen(context, TRUE);
2288 static DWORD context_generate_rt_mask_no_fbo(const struct wined3d_device *device, const struct wined3d_surface *rt)
2290 if (!rt || rt->resource.format->id == WINED3DFMT_NULL)
2291 return 0;
2292 else if (rt->container->swapchain)
2293 return context_generate_rt_mask_from_surface(rt);
2294 else
2295 return context_generate_rt_mask(device->offscreenBuffer);
2298 /* Context activation is done by the caller. */
2299 void context_apply_blit_state(struct wined3d_context *context, const struct wined3d_device *device)
2301 struct wined3d_surface *rt = context->current_rt;
2302 DWORD rt_mask, *cur_mask;
2304 if (wined3d_settings.offscreen_rendering_mode == ORM_FBO)
2306 context_validate_onscreen_formats(context, NULL);
2308 if (context->render_offscreen)
2310 wined3d_texture_load(rt->container, context, FALSE);
2312 context_apply_fbo_state_blit(context, GL_FRAMEBUFFER, rt, NULL, rt->container->resource.draw_binding);
2313 if (rt->resource.format->id != WINED3DFMT_NULL)
2314 rt_mask = 1;
2315 else
2316 rt_mask = 0;
2318 else
2320 context->current_fbo = NULL;
2321 context_bind_fbo(context, GL_FRAMEBUFFER, 0);
2322 rt_mask = context_generate_rt_mask_from_surface(rt);
2325 else
2327 rt_mask = context_generate_rt_mask_no_fbo(device, rt);
2330 cur_mask = context->current_fbo ? &context->current_fbo->rt_mask : &context->draw_buffers_mask;
2332 if (rt_mask != *cur_mask)
2334 context_apply_draw_buffers(context, rt_mask);
2335 *cur_mask = rt_mask;
2338 if (wined3d_settings.offscreen_rendering_mode == ORM_FBO)
2340 context_check_fbo_status(context, GL_FRAMEBUFFER);
2343 SetupForBlit(device, context);
2344 context_invalidate_state(context, STATE_FRAMEBUFFER);
2347 static BOOL context_validate_rt_config(UINT rt_count, struct wined3d_rendertarget_view * const *rts,
2348 const struct wined3d_rendertarget_view *ds)
2350 unsigned int i;
2352 if (ds) return TRUE;
2354 for (i = 0; i < rt_count; ++i)
2356 if (rts[i] && rts[i]->format->id != WINED3DFMT_NULL)
2357 return TRUE;
2360 WARN("Invalid render target config, need at least one attachment.\n");
2361 return FALSE;
2364 /* Context activation is done by the caller. */
2365 BOOL context_apply_clear_state(struct wined3d_context *context, const struct wined3d_device *device,
2366 UINT rt_count, const struct wined3d_fb_state *fb)
2368 struct wined3d_rendertarget_view **rts = fb->render_targets;
2369 struct wined3d_rendertarget_view *dsv = fb->depth_stencil;
2370 const struct wined3d_gl_info *gl_info = context->gl_info;
2371 DWORD rt_mask = 0, *cur_mask;
2372 UINT i;
2374 if (isStateDirty(context, STATE_FRAMEBUFFER) || fb != &device->fb
2375 || rt_count != context->gl_info->limits.buffers)
2377 if (!context_validate_rt_config(rt_count, rts, dsv))
2378 return FALSE;
2380 if (wined3d_settings.offscreen_rendering_mode == ORM_FBO)
2382 context_validate_onscreen_formats(context, dsv);
2384 if (!rt_count || wined3d_resource_is_offscreen(rts[0]->resource))
2386 for (i = 0; i < rt_count; ++i)
2388 context->blit_targets[i] = wined3d_rendertarget_view_get_surface(rts[i]);
2389 if (rts[i] && rts[i]->format->id != WINED3DFMT_NULL)
2390 rt_mask |= (1 << i);
2392 while (i < context->gl_info->limits.buffers)
2394 context->blit_targets[i] = NULL;
2395 ++i;
2397 context_apply_fbo_state(context, GL_FRAMEBUFFER, context->blit_targets,
2398 wined3d_rendertarget_view_get_surface(dsv),
2399 rt_count ? rts[0]->resource->draw_binding : 0,
2400 dsv ? dsv->resource->draw_binding : 0);
2402 else
2404 context_apply_fbo_state(context, GL_FRAMEBUFFER, NULL, NULL,
2405 WINED3D_LOCATION_DRAWABLE, WINED3D_LOCATION_DRAWABLE);
2406 rt_mask = context_generate_rt_mask_from_surface(wined3d_rendertarget_view_get_surface(rts[0]));
2409 /* If the framebuffer is not the device's fb the device's fb has to be reapplied
2410 * next draw. Otherwise we could mark the framebuffer state clean here, once the
2411 * state management allows this */
2412 context_invalidate_state(context, STATE_FRAMEBUFFER);
2414 else
2416 rt_mask = context_generate_rt_mask_no_fbo(device,
2417 rt_count ? wined3d_rendertarget_view_get_surface(rts[0]) : NULL);
2420 else if (wined3d_settings.offscreen_rendering_mode == ORM_FBO
2421 && (!rt_count || wined3d_resource_is_offscreen(rts[0]->resource)))
2423 for (i = 0; i < rt_count; ++i)
2425 if (rts[i] && rts[i]->format->id != WINED3DFMT_NULL)
2426 rt_mask |= (1 << i);
2429 else
2431 rt_mask = context_generate_rt_mask_no_fbo(device,
2432 rt_count ? wined3d_rendertarget_view_get_surface(rts[0]) : NULL);
2435 cur_mask = context->current_fbo ? &context->current_fbo->rt_mask : &context->draw_buffers_mask;
2437 if (rt_mask != *cur_mask)
2439 context_apply_draw_buffers(context, rt_mask);
2440 *cur_mask = rt_mask;
2441 context_invalidate_state(context, STATE_FRAMEBUFFER);
2444 if (wined3d_settings.offscreen_rendering_mode == ORM_FBO)
2446 context_check_fbo_status(context, GL_FRAMEBUFFER);
2449 if (context->last_was_blit)
2450 context->last_was_blit = FALSE;
2452 /* Blending and clearing should be orthogonal, but tests on the nvidia
2453 * driver show that disabling blending when clearing improves the clearing
2454 * performance incredibly. */
2455 gl_info->gl_ops.gl.p_glDisable(GL_BLEND);
2456 gl_info->gl_ops.gl.p_glEnable(GL_SCISSOR_TEST);
2457 checkGLcall("glEnable GL_SCISSOR_TEST");
2459 context_invalidate_state(context, STATE_RENDER(WINED3D_RS_ALPHABLENDENABLE));
2460 context_invalidate_state(context, STATE_RENDER(WINED3D_RS_SCISSORTESTENABLE));
2461 context_invalidate_state(context, STATE_SCISSORRECT);
2463 return TRUE;
2466 static DWORD find_draw_buffers_mask(const struct wined3d_context *context, const struct wined3d_device *device)
2468 const struct wined3d_state *state = &device->state;
2469 struct wined3d_rendertarget_view **rts = state->fb->render_targets;
2470 struct wined3d_shader *ps = state->shader[WINED3D_SHADER_TYPE_PIXEL];
2471 DWORD rt_mask, rt_mask_bits;
2472 unsigned int i;
2474 if (wined3d_settings.offscreen_rendering_mode != ORM_FBO)
2475 return context_generate_rt_mask_no_fbo(device, wined3d_rendertarget_view_get_surface(rts[0]));
2476 else if (!context->render_offscreen)
2477 return context_generate_rt_mask_from_surface(wined3d_rendertarget_view_get_surface(rts[0]));
2479 rt_mask = ps ? ps->reg_maps.rt_mask : 1;
2480 rt_mask &= context->d3d_info->valid_rt_mask;
2481 rt_mask_bits = rt_mask;
2482 i = 0;
2483 while (rt_mask_bits)
2485 rt_mask_bits &= ~(1 << i);
2486 if (!rts[i] || rts[i]->format->id == WINED3DFMT_NULL)
2487 rt_mask &= ~(1 << i);
2489 i++;
2492 return rt_mask;
2495 /* Context activation is done by the caller. */
2496 void context_state_fb(struct wined3d_context *context, const struct wined3d_state *state, DWORD state_id)
2498 const struct wined3d_device *device = context->swapchain->device;
2499 const struct wined3d_fb_state *fb = state->fb;
2500 DWORD rt_mask = find_draw_buffers_mask(context, device);
2501 DWORD *cur_mask;
2503 if (wined3d_settings.offscreen_rendering_mode == ORM_FBO)
2505 if (!context->render_offscreen)
2507 context_apply_fbo_state(context, GL_FRAMEBUFFER, NULL, NULL,
2508 WINED3D_LOCATION_DRAWABLE, WINED3D_LOCATION_DRAWABLE);
2510 else
2512 unsigned int i;
2514 for (i = 0; i < context->gl_info->limits.buffers; ++i)
2516 context->blit_targets[i] = wined3d_rendertarget_view_get_surface(fb->render_targets[i]);
2518 context_apply_fbo_state(context, GL_FRAMEBUFFER, context->blit_targets,
2519 wined3d_rendertarget_view_get_surface(fb->depth_stencil),
2520 fb->render_targets[0]->resource->draw_binding,
2521 fb->depth_stencil ? fb->depth_stencil->resource->draw_binding : 0);
2525 cur_mask = context->current_fbo ? &context->current_fbo->rt_mask : &context->draw_buffers_mask;
2526 if (rt_mask != *cur_mask)
2528 context_apply_draw_buffers(context, rt_mask);
2529 *cur_mask = rt_mask;
2533 static void context_map_stage(struct wined3d_context *context, DWORD stage, DWORD unit)
2535 DWORD i = context->rev_tex_unit_map[unit];
2536 DWORD j = context->tex_unit_map[stage];
2538 context->tex_unit_map[stage] = unit;
2539 if (i != WINED3D_UNMAPPED_STAGE && i != stage)
2540 context->tex_unit_map[i] = WINED3D_UNMAPPED_STAGE;
2542 context->rev_tex_unit_map[unit] = stage;
2543 if (j != WINED3D_UNMAPPED_STAGE && j != unit)
2544 context->rev_tex_unit_map[j] = WINED3D_UNMAPPED_STAGE;
2547 static void context_invalidate_texture_stage(struct wined3d_context *context, DWORD stage)
2549 DWORD i;
2551 for (i = 0; i <= WINED3D_HIGHEST_TEXTURE_STATE; ++i)
2552 context_invalidate_state(context, STATE_TEXTURESTAGE(stage, i));
2555 static void context_update_fixed_function_usage_map(struct wined3d_context *context,
2556 const struct wined3d_state *state)
2558 UINT i, start, end;
2560 context->fixed_function_usage_map = 0;
2561 for (i = 0; i < MAX_TEXTURES; ++i)
2563 enum wined3d_texture_op color_op = state->texture_states[i][WINED3D_TSS_COLOR_OP];
2564 enum wined3d_texture_op alpha_op = state->texture_states[i][WINED3D_TSS_ALPHA_OP];
2565 DWORD color_arg1 = state->texture_states[i][WINED3D_TSS_COLOR_ARG1] & WINED3DTA_SELECTMASK;
2566 DWORD color_arg2 = state->texture_states[i][WINED3D_TSS_COLOR_ARG2] & WINED3DTA_SELECTMASK;
2567 DWORD color_arg3 = state->texture_states[i][WINED3D_TSS_COLOR_ARG0] & WINED3DTA_SELECTMASK;
2568 DWORD alpha_arg1 = state->texture_states[i][WINED3D_TSS_ALPHA_ARG1] & WINED3DTA_SELECTMASK;
2569 DWORD alpha_arg2 = state->texture_states[i][WINED3D_TSS_ALPHA_ARG2] & WINED3DTA_SELECTMASK;
2570 DWORD alpha_arg3 = state->texture_states[i][WINED3D_TSS_ALPHA_ARG0] & WINED3DTA_SELECTMASK;
2572 /* Not used, and disable higher stages. */
2573 if (color_op == WINED3D_TOP_DISABLE)
2574 break;
2576 if (((color_arg1 == WINED3DTA_TEXTURE) && color_op != WINED3D_TOP_SELECT_ARG2)
2577 || ((color_arg2 == WINED3DTA_TEXTURE) && color_op != WINED3D_TOP_SELECT_ARG1)
2578 || ((color_arg3 == WINED3DTA_TEXTURE)
2579 && (color_op == WINED3D_TOP_MULTIPLY_ADD || color_op == WINED3D_TOP_LERP))
2580 || ((alpha_arg1 == WINED3DTA_TEXTURE) && alpha_op != WINED3D_TOP_SELECT_ARG2)
2581 || ((alpha_arg2 == WINED3DTA_TEXTURE) && alpha_op != WINED3D_TOP_SELECT_ARG1)
2582 || ((alpha_arg3 == WINED3DTA_TEXTURE)
2583 && (alpha_op == WINED3D_TOP_MULTIPLY_ADD || alpha_op == WINED3D_TOP_LERP)))
2584 context->fixed_function_usage_map |= (1 << i);
2586 if ((color_op == WINED3D_TOP_BUMPENVMAP || color_op == WINED3D_TOP_BUMPENVMAP_LUMINANCE)
2587 && i < MAX_TEXTURES - 1)
2588 context->fixed_function_usage_map |= (1 << (i + 1));
2591 if (i < context->lowest_disabled_stage)
2593 start = i;
2594 end = context->lowest_disabled_stage;
2596 else
2598 start = context->lowest_disabled_stage;
2599 end = i;
2602 context->lowest_disabled_stage = i;
2603 for (i = start + 1; i < end; ++i)
2605 context_invalidate_state(context, STATE_TEXTURESTAGE(i, WINED3D_TSS_COLOR_OP));
2609 static void context_map_fixed_function_samplers(struct wined3d_context *context,
2610 const struct wined3d_state *state)
2612 unsigned int i, tex;
2613 WORD ffu_map;
2614 const struct wined3d_d3d_info *d3d_info = context->d3d_info;
2616 context_update_fixed_function_usage_map(context, state);
2617 ffu_map = context->fixed_function_usage_map;
2619 if (d3d_info->limits.ffp_textures == d3d_info->limits.ffp_blend_stages
2620 || context->lowest_disabled_stage <= d3d_info->limits.ffp_textures)
2622 for (i = 0; ffu_map; ffu_map >>= 1, ++i)
2624 if (!(ffu_map & 1))
2625 continue;
2627 if (context->tex_unit_map[i] != i)
2629 context_map_stage(context, i, i);
2630 context_invalidate_state(context, STATE_SAMPLER(i));
2631 context_invalidate_texture_stage(context, i);
2634 return;
2637 /* Now work out the mapping */
2638 tex = 0;
2639 for (i = 0; ffu_map; ffu_map >>= 1, ++i)
2641 if (!(ffu_map & 1))
2642 continue;
2644 if (context->tex_unit_map[i] != tex)
2646 context_map_stage(context, i, tex);
2647 context_invalidate_state(context, STATE_SAMPLER(i));
2648 context_invalidate_texture_stage(context, i);
2651 ++tex;
2655 static void context_map_psamplers(struct wined3d_context *context, const struct wined3d_state *state)
2657 const struct wined3d_shader_resource_info *resource_info =
2658 state->shader[WINED3D_SHADER_TYPE_PIXEL]->reg_maps.resource_info;
2659 unsigned int i;
2660 const struct wined3d_d3d_info *d3d_info = context->d3d_info;
2662 for (i = 0; i < MAX_FRAGMENT_SAMPLERS; ++i)
2664 if (resource_info[i].type && context->tex_unit_map[i] != i)
2666 context_map_stage(context, i, i);
2667 context_invalidate_state(context, STATE_SAMPLER(i));
2668 if (i < d3d_info->limits.ffp_blend_stages)
2669 context_invalidate_texture_stage(context, i);
2674 static BOOL context_unit_free_for_vs(const struct wined3d_context *context,
2675 const struct wined3d_shader_resource_info *ps_resource_info,
2676 const struct wined3d_shader_resource_info *vs_resource_info, DWORD unit)
2678 DWORD current_mapping = context->rev_tex_unit_map[unit];
2680 /* Not currently used */
2681 if (current_mapping == WINED3D_UNMAPPED_STAGE)
2682 return TRUE;
2684 if (current_mapping < MAX_FRAGMENT_SAMPLERS)
2686 /* Used by a fragment sampler */
2688 if (!ps_resource_info)
2690 /* No pixel shader, check fixed function */
2691 return current_mapping >= MAX_TEXTURES || !(context->fixed_function_usage_map & (1 << current_mapping));
2694 /* Pixel shader, check the shader's sampler map */
2695 return !ps_resource_info[current_mapping].type;
2698 /* Used by a vertex sampler */
2699 return !vs_resource_info[current_mapping - MAX_FRAGMENT_SAMPLERS].type;
2702 static void context_map_vsamplers(struct wined3d_context *context, BOOL ps, const struct wined3d_state *state)
2704 const struct wined3d_shader_resource_info *vs_resource_info =
2705 state->shader[WINED3D_SHADER_TYPE_VERTEX]->reg_maps.resource_info;
2706 const struct wined3d_shader_resource_info *ps_resource_info = NULL;
2707 const struct wined3d_gl_info *gl_info = context->gl_info;
2708 int start = min(MAX_COMBINED_SAMPLERS, gl_info->limits.combined_samplers) - 1;
2709 int i;
2711 /* Note that we only care if a resource is used or not, not the
2712 * resource's specific type. Otherwise we'd need to call
2713 * shader_update_samplers() here for 1.x pixelshaders. */
2714 if (ps)
2715 ps_resource_info = state->shader[WINED3D_SHADER_TYPE_PIXEL]->reg_maps.resource_info;
2717 for (i = 0; i < MAX_VERTEX_SAMPLERS; ++i)
2719 DWORD vsampler_idx = i + MAX_FRAGMENT_SAMPLERS;
2720 if (vs_resource_info[i].type)
2722 if (context->tex_unit_map[vsampler_idx] != WINED3D_UNMAPPED_STAGE)
2724 /* Already mapped somewhere */
2725 continue;
2728 while (start >= 0)
2730 if (context_unit_free_for_vs(context, ps_resource_info, vs_resource_info, start))
2732 context_map_stage(context, vsampler_idx, start);
2733 context_invalidate_state(context, STATE_SAMPLER(vsampler_idx));
2735 --start;
2736 break;
2739 --start;
2745 static void context_update_tex_unit_map(struct wined3d_context *context, const struct wined3d_state *state)
2747 BOOL vs = use_vs(state);
2748 BOOL ps = use_ps(state);
2750 * Rules are:
2751 * -> Pixel shaders need a 1:1 map. In theory the shader input could be mapped too, but
2752 * that would be really messy and require shader recompilation
2753 * -> When the mapping of a stage is changed, sampler and ALL texture stage states have
2754 * to be reset. Because of that try to work with a 1:1 mapping as much as possible
2756 if (ps)
2757 context_map_psamplers(context, state);
2758 else
2759 context_map_fixed_function_samplers(context, state);
2761 if (vs)
2762 context_map_vsamplers(context, ps, state);
2765 /* Context activation is done by the caller. */
2766 void context_state_drawbuf(struct wined3d_context *context, const struct wined3d_state *state, DWORD state_id)
2768 const struct wined3d_device *device = context->swapchain->device;
2769 DWORD rt_mask, *cur_mask;
2771 if (isStateDirty(context, STATE_FRAMEBUFFER)) return;
2773 cur_mask = context->current_fbo ? &context->current_fbo->rt_mask : &context->draw_buffers_mask;
2774 rt_mask = find_draw_buffers_mask(context, device);
2775 if (rt_mask != *cur_mask)
2777 context_apply_draw_buffers(context, rt_mask);
2778 *cur_mask = rt_mask;
2782 static BOOL fixed_get_input(BYTE usage, BYTE usage_idx, unsigned int *regnum)
2784 if ((usage == WINED3D_DECL_USAGE_POSITION || usage == WINED3D_DECL_USAGE_POSITIONT) && !usage_idx)
2785 *regnum = WINED3D_FFP_POSITION;
2786 else if (usage == WINED3D_DECL_USAGE_BLEND_WEIGHT && !usage_idx)
2787 *regnum = WINED3D_FFP_BLENDWEIGHT;
2788 else if (usage == WINED3D_DECL_USAGE_BLEND_INDICES && !usage_idx)
2789 *regnum = WINED3D_FFP_BLENDINDICES;
2790 else if (usage == WINED3D_DECL_USAGE_NORMAL && !usage_idx)
2791 *regnum = WINED3D_FFP_NORMAL;
2792 else if (usage == WINED3D_DECL_USAGE_PSIZE && !usage_idx)
2793 *regnum = WINED3D_FFP_PSIZE;
2794 else if (usage == WINED3D_DECL_USAGE_COLOR && !usage_idx)
2795 *regnum = WINED3D_FFP_DIFFUSE;
2796 else if (usage == WINED3D_DECL_USAGE_COLOR && usage_idx == 1)
2797 *regnum = WINED3D_FFP_SPECULAR;
2798 else if (usage == WINED3D_DECL_USAGE_TEXCOORD && usage_idx < WINED3DDP_MAXTEXCOORD)
2799 *regnum = WINED3D_FFP_TEXCOORD0 + usage_idx;
2800 else
2802 FIXME("Unsupported input stream [usage=%s, usage_idx=%u].\n", debug_d3ddeclusage(usage), usage_idx);
2803 *regnum = ~0U;
2804 return FALSE;
2807 return TRUE;
2810 /* Context activation is done by the caller. */
2811 void context_stream_info_from_declaration(struct wined3d_context *context,
2812 const struct wined3d_state *state, struct wined3d_stream_info *stream_info)
2814 /* We need to deal with frequency data! */
2815 struct wined3d_vertex_declaration *declaration = state->vertex_declaration;
2816 BOOL use_vshader = use_vs(state);
2817 BOOL generic_attributes = context->d3d_info->ffp_generic_attributes;
2818 unsigned int i;
2820 stream_info->use_map = 0;
2821 stream_info->swizzle_map = 0;
2822 stream_info->position_transformed = declaration->position_transformed;
2824 /* Translate the declaration into strided data. */
2825 for (i = 0; i < declaration->element_count; ++i)
2827 const struct wined3d_vertex_declaration_element *element = &declaration->elements[i];
2828 const struct wined3d_stream_state *stream = &state->streams[element->input_slot];
2829 BOOL stride_used;
2830 unsigned int idx;
2832 TRACE("%p Element %p (%u of %u).\n", declaration->elements,
2833 element, i + 1, declaration->element_count);
2835 if (!stream->buffer)
2836 continue;
2838 TRACE("offset %u input_slot %u usage_idx %d.\n", element->offset, element->input_slot, element->usage_idx);
2840 if (use_vshader)
2842 if (element->output_slot == WINED3D_OUTPUT_SLOT_UNUSED)
2844 stride_used = FALSE;
2846 else if (element->output_slot == WINED3D_OUTPUT_SLOT_SEMANTIC)
2848 /* TODO: Assuming vertexdeclarations are usually used with the
2849 * same or a similar shader, it might be worth it to store the
2850 * last used output slot and try that one first. */
2851 stride_used = vshader_get_input(state->shader[WINED3D_SHADER_TYPE_VERTEX],
2852 element->usage, element->usage_idx, &idx);
2854 else
2856 idx = element->output_slot;
2857 stride_used = TRUE;
2860 else
2862 if (!generic_attributes && !element->ffp_valid)
2864 WARN("Skipping unsupported fixed function element of format %s and usage %s.\n",
2865 debug_d3dformat(element->format->id), debug_d3ddeclusage(element->usage));
2866 stride_used = FALSE;
2868 else
2870 stride_used = fixed_get_input(element->usage, element->usage_idx, &idx);
2874 if (stride_used)
2876 TRACE("Load %s array %u [usage %s, usage_idx %u, "
2877 "input_slot %u, offset %u, stride %u, format %s, class %s, step_rate %u].\n",
2878 use_vshader ? "shader": "fixed function", idx,
2879 debug_d3ddeclusage(element->usage), element->usage_idx, element->input_slot,
2880 element->offset, stream->stride, debug_d3dformat(element->format->id),
2881 debug_d3dinput_classification(element->input_slot_class), element->instance_data_step_rate);
2883 stream_info->elements[idx].format = element->format;
2884 stream_info->elements[idx].data.buffer_object = 0;
2885 stream_info->elements[idx].data.addr = (BYTE *)NULL + stream->offset + element->offset;
2886 stream_info->elements[idx].stride = stream->stride;
2887 stream_info->elements[idx].stream_idx = element->input_slot;
2888 if (stream->flags & WINED3DSTREAMSOURCE_INSTANCEDATA)
2890 stream_info->elements[idx].divisor = 1;
2892 else if (element->input_slot_class == WINED3D_INPUT_PER_INSTANCE_DATA)
2894 stream_info->elements[idx].divisor = element->instance_data_step_rate;
2895 if (!element->instance_data_step_rate)
2896 FIXME("Instance step rate 0 not implemented.\n");
2898 else
2900 stream_info->elements[idx].divisor = 0;
2903 if (!context->gl_info->supported[ARB_VERTEX_ARRAY_BGRA]
2904 && element->format->id == WINED3DFMT_B8G8R8A8_UNORM)
2906 stream_info->swizzle_map |= 1 << idx;
2908 stream_info->use_map |= 1 << idx;
2913 /* Context activation is done by the caller. */
2914 static void context_update_stream_info(struct wined3d_context *context, const struct wined3d_state *state)
2916 const struct wined3d_gl_info *gl_info = context->gl_info;
2917 const struct wined3d_d3d_info *d3d_info = context->d3d_info;
2918 struct wined3d_stream_info *stream_info = &context->stream_info;
2919 DWORD prev_all_vbo = stream_info->all_vbo;
2920 unsigned int i;
2921 WORD map;
2923 context_stream_info_from_declaration(context, state, stream_info);
2925 stream_info->all_vbo = 1;
2926 context->num_buffer_queries = 0;
2927 for (i = 0, map = stream_info->use_map; map; map >>= 1, ++i)
2929 struct wined3d_stream_info_element *element;
2930 struct wined3d_bo_address data;
2931 struct wined3d_buffer *buffer;
2933 if (!(map & 1))
2934 continue;
2936 element = &stream_info->elements[i];
2937 buffer = state->streams[element->stream_idx].buffer;
2939 /* We can't use VBOs if the base vertex index is negative. OpenGL
2940 * doesn't accept negative offsets (or rather offsets bigger than the
2941 * VBO, because the pointer is unsigned), so use system memory
2942 * sources. In most sane cases the pointer - offset will still be > 0,
2943 * otherwise it will wrap around to some big value. Hope that with the
2944 * indices the driver wraps it back internally. If not,
2945 * drawStridedSlow is needed, including a vertex buffer path. */
2946 if (state->load_base_vertex_index < 0)
2948 WARN_(d3d_perf)("load_base_vertex_index is < 0 (%d), not using VBOs.\n",
2949 state->load_base_vertex_index);
2950 element->data.buffer_object = 0;
2951 element->data.addr += (ULONG_PTR)buffer_get_sysmem(buffer, context);
2952 if ((UINT_PTR)element->data.addr < -state->load_base_vertex_index * element->stride)
2953 FIXME("System memory vertex data load offset is negative!\n");
2955 else
2957 buffer_internal_preload(buffer, context, state);
2958 buffer_get_memory(buffer, context, &data);
2959 element->data.buffer_object = data.buffer_object;
2960 element->data.addr += (ULONG_PTR)data.addr;
2963 if (!element->data.buffer_object)
2964 stream_info->all_vbo = 0;
2966 if (buffer->query)
2967 context->buffer_queries[context->num_buffer_queries++] = buffer->query;
2969 TRACE("Load array %u {%#x:%p}.\n", i, element->data.buffer_object, element->data.addr);
2972 if (use_vs(state))
2974 if (state->vertex_declaration->half_float_conv_needed && !stream_info->all_vbo)
2976 TRACE("Using drawStridedSlow with vertex shaders for FLOAT16 conversion.\n");
2977 context->use_immediate_mode_draw = TRUE;
2979 else
2981 context->use_immediate_mode_draw = FALSE;
2984 else
2986 WORD slow_mask = -!d3d_info->ffp_generic_attributes & (1 << WINED3D_FFP_PSIZE);
2987 slow_mask |= -!gl_info->supported[ARB_VERTEX_ARRAY_BGRA]
2988 & ((1 << WINED3D_FFP_DIFFUSE) | (1 << WINED3D_FFP_SPECULAR));
2990 if (((stream_info->position_transformed && !d3d_info->xyzrhw)
2991 || (stream_info->use_map & slow_mask)) && !stream_info->all_vbo)
2992 context->use_immediate_mode_draw = TRUE;
2993 else
2994 context->use_immediate_mode_draw = FALSE;
2997 if (prev_all_vbo != stream_info->all_vbo)
2998 context_invalidate_state(context, STATE_INDEXBUFFER);
3001 /* Context activation is done by the caller. */
3002 static void context_preload_texture(struct wined3d_context *context,
3003 const struct wined3d_state *state, unsigned int idx)
3005 struct wined3d_texture *texture;
3007 if (!(texture = state->textures[idx]))
3008 return;
3010 wined3d_texture_load(texture, context, state->sampler_states[idx][WINED3D_SAMP_SRGB_TEXTURE]);
3013 /* Context activation is done by the caller. */
3014 static void context_preload_textures(struct wined3d_context *context, const struct wined3d_state *state)
3016 unsigned int i;
3018 if (use_vs(state))
3020 for (i = 0; i < MAX_VERTEX_SAMPLERS; ++i)
3022 if (state->shader[WINED3D_SHADER_TYPE_VERTEX]->reg_maps.resource_info[i].type)
3023 context_preload_texture(context, state, MAX_FRAGMENT_SAMPLERS + i);
3027 if (use_ps(state))
3029 for (i = 0; i < MAX_FRAGMENT_SAMPLERS; ++i)
3031 if (state->shader[WINED3D_SHADER_TYPE_PIXEL]->reg_maps.resource_info[i].type)
3032 context_preload_texture(context, state, i);
3035 else
3037 WORD ffu_map = context->fixed_function_usage_map;
3039 for (i = 0; ffu_map; ffu_map >>= 1, ++i)
3041 if (ffu_map & 1)
3042 context_preload_texture(context, state, i);
3047 static void context_bind_shader_resources(struct wined3d_context *context, const struct wined3d_state *state)
3049 const struct wined3d_gl_info *gl_info = context->gl_info;
3050 struct wined3d_shader_sampler_map_entry *entry;
3051 struct wined3d_shader_resource_view *view;
3052 struct wined3d_sampler *sampler;
3053 struct wined3d_texture *texture;
3054 struct wined3d_shader *shader;
3055 unsigned int i, j, count;
3057 static const struct
3059 enum wined3d_shader_type type;
3060 unsigned int base_idx;
3061 unsigned int count;
3063 shader_types[] =
3065 {WINED3D_SHADER_TYPE_PIXEL, 0, MAX_FRAGMENT_SAMPLERS},
3066 {WINED3D_SHADER_TYPE_VERTEX, MAX_FRAGMENT_SAMPLERS, MAX_VERTEX_SAMPLERS},
3069 for (i = 0; i < ARRAY_SIZE(shader_types); ++i)
3071 if (!(shader = state->shader[shader_types[i].type]))
3072 continue;
3074 count = shader->reg_maps.sampler_map.count;
3075 if (count > shader_types[i].count)
3077 FIXME("Shader %p needs %u samplers, but only %u are supported.\n",
3078 shader, count, shader_types[i].count);
3079 count = shader_types[i].count;
3082 for (j = 0; j < count; ++j)
3084 entry = &shader->reg_maps.sampler_map.entries[j];
3086 if (!(view = state->shader_resource_view[shader_types[i].type][entry->resource_idx]))
3088 WARN("No resource view bound at index %u, %u.\n", shader_types[i].type, entry->resource_idx);
3089 continue;
3092 if (view->resource->type == WINED3D_RTYPE_BUFFER)
3094 FIXME("Buffer shader resources not supported.\n");
3095 continue;
3098 if (!(sampler = state->sampler[shader_types[i].type][entry->sampler_idx]))
3100 WARN("No sampler object bound at index %u, %u.\n", shader_types[i].type, entry->sampler_idx);
3101 continue;
3104 texture = wined3d_texture_from_resource(view->resource);
3105 wined3d_texture_load(texture, context, FALSE);
3106 context_active_texture(context, gl_info, shader_types[i].base_idx + entry->bind_idx);
3107 wined3d_texture_bind(texture, context, FALSE);
3109 GL_EXTCALL(glBindSampler(shader_types[i].base_idx + entry->bind_idx, sampler->name));
3110 checkGLcall("glBindSampler");
3115 /* Context activation is done by the caller. */
3116 BOOL context_apply_draw_state(struct wined3d_context *context, struct wined3d_device *device)
3118 const struct wined3d_state *state = &device->state;
3119 const struct StateEntry *state_table = context->state_table;
3120 const struct wined3d_fb_state *fb = state->fb;
3121 unsigned int i, j;
3122 WORD map;
3124 if (!context_validate_rt_config(context->gl_info->limits.buffers,
3125 fb->render_targets, fb->depth_stencil))
3126 return FALSE;
3128 if (wined3d_settings.offscreen_rendering_mode == ORM_FBO && isStateDirty(context, STATE_FRAMEBUFFER))
3130 context_validate_onscreen_formats(context, fb->depth_stencil);
3133 /* Preload resources before FBO setup. Texture preload in particular may
3134 * result in changes to the current FBO, due to using e.g. FBO blits for
3135 * updating a resource location. */
3136 context_update_tex_unit_map(context, state);
3137 context_preload_textures(context, state);
3138 /* TODO: Right now the dependency on the vertex shader is necessary
3139 * since context_stream_info_from_declaration depends on the reg_maps of
3140 * the current VS but maybe it's possible to relax the coupling in some
3141 * situations at least. */
3142 if (isStateDirty(context, STATE_VDECL) || isStateDirty(context, STATE_STREAMSRC)
3143 || isStateDirty(context, STATE_SHADER(WINED3D_SHADER_TYPE_VERTEX)))
3145 context_update_stream_info(context, state);
3147 else
3149 for (i = 0, map = context->stream_info.use_map; map; map >>= 1, ++i)
3151 if (map & 1)
3152 buffer_mark_used(state->streams[context->stream_info.elements[i].stream_idx].buffer);
3155 if (state->index_buffer)
3157 if (context->stream_info.all_vbo)
3158 buffer_internal_preload(state->index_buffer, context, state);
3159 else
3160 buffer_get_sysmem(state->index_buffer, context);
3163 for (i = 0; i < WINED3D_SHADER_TYPE_COUNT; ++i)
3165 for (j = 0; j < WINED3D_MAX_CBS; ++j)
3167 if (state->cb[i][j])
3168 buffer_internal_preload(state->cb[i][j], context, state);
3172 for (i = 0; i < context->numDirtyEntries; ++i)
3174 DWORD rep = context->dirtyArray[i];
3175 DWORD idx = rep / (sizeof(*context->isStateDirty) * CHAR_BIT);
3176 BYTE shift = rep & ((sizeof(*context->isStateDirty) * CHAR_BIT) - 1);
3177 context->isStateDirty[idx] &= ~(1 << shift);
3178 state_table[rep].apply(context, state, rep);
3181 if (context->shader_update_mask)
3183 device->shader_backend->shader_select(device->shader_priv, context, state);
3184 context->shader_update_mask = 0;
3187 if (context->constant_update_mask)
3189 device->shader_backend->shader_load_constants(device->shader_priv, context, state);
3190 context->constant_update_mask = 0;
3193 if (context->update_shader_resource_bindings)
3195 context_bind_shader_resources(context, state);
3196 context->update_shader_resource_bindings = 0;
3199 if (wined3d_settings.offscreen_rendering_mode == ORM_FBO)
3201 context_check_fbo_status(context, GL_FRAMEBUFFER);
3204 context->numDirtyEntries = 0; /* This makes the whole list clean */
3205 context->last_was_blit = FALSE;
3207 return TRUE;
3210 static void context_setup_target(struct wined3d_context *context, struct wined3d_surface *target)
3212 BOOL old_render_offscreen = context->render_offscreen, render_offscreen;
3214 render_offscreen = wined3d_resource_is_offscreen(&target->container->resource);
3215 if (context->current_rt == target && render_offscreen == old_render_offscreen) return;
3217 /* To compensate the lack of format switching with some offscreen rendering methods and on onscreen buffers
3218 * the alpha blend state changes with different render target formats. */
3219 if (!context->current_rt)
3221 context_invalidate_state(context, STATE_RENDER(WINED3D_RS_ALPHABLENDENABLE));
3223 else
3225 const struct wined3d_format *old = context->current_rt->resource.format;
3226 const struct wined3d_format *new = target->resource.format;
3228 if (old->id != new->id)
3230 /* Disable blending when the alpha mask has changed and when a format doesn't support blending. */
3231 if ((old->alpha_size && !new->alpha_size) || (!old->alpha_size && new->alpha_size)
3232 || !(target->container->resource.format_flags & WINED3DFMT_FLAG_POSTPIXELSHADER_BLENDING))
3233 context_invalidate_state(context, STATE_RENDER(WINED3D_RS_ALPHABLENDENABLE));
3235 /* Update sRGB writing when switching between formats that do/do not support sRGB writing */
3236 if ((context->current_rt->container->resource.format_flags & WINED3DFMT_FLAG_SRGB_WRITE)
3237 != (target->container->resource.format_flags & WINED3DFMT_FLAG_SRGB_WRITE))
3238 context_invalidate_state(context, STATE_RENDER(WINED3D_RS_SRGBWRITEENABLE));
3241 /* When switching away from an offscreen render target, and we're not
3242 * using FBOs, we have to read the drawable into the texture. This is
3243 * done via PreLoad (and WINED3D_LOCATION_DRAWABLE set on the surface).
3244 * There are some things that need care though. PreLoad needs a GL context,
3245 * and FindContext is called before the context is activated. It also
3246 * has to be called with the old rendertarget active, otherwise a
3247 * wrong drawable is read. */
3248 if (wined3d_settings.offscreen_rendering_mode != ORM_FBO
3249 && old_render_offscreen && context->current_rt != target)
3251 struct wined3d_texture *texture = context->current_rt->container;
3253 /* Read the back buffer of the old drawable into the destination texture. */
3254 if (texture->texture_srgb.name)
3255 wined3d_texture_load(texture, context, TRUE);
3256 wined3d_texture_load(texture, context, FALSE);
3257 surface_invalidate_location(context->current_rt, WINED3D_LOCATION_DRAWABLE);
3261 context->current_rt = target;
3262 context_set_render_offscreen(context, render_offscreen);
3265 struct wined3d_context *context_acquire(const struct wined3d_device *device, struct wined3d_surface *target)
3267 struct wined3d_context *current_context = context_get_current();
3268 struct wined3d_context *context;
3270 TRACE("device %p, target %p.\n", device, target);
3272 if (current_context && current_context->destroyed)
3273 current_context = NULL;
3275 if (!target)
3277 if (current_context
3278 && current_context->current_rt
3279 && current_context->swapchain->device == device)
3281 target = current_context->current_rt;
3283 else
3285 struct wined3d_swapchain *swapchain = device->swapchains[0];
3286 if (swapchain->back_buffers)
3287 target = surface_from_resource(wined3d_texture_get_sub_resource(swapchain->back_buffers[0], 0));
3288 else
3289 target = surface_from_resource(wined3d_texture_get_sub_resource(swapchain->front_buffer, 0));
3293 if (current_context && current_context->current_rt == target)
3295 context = current_context;
3297 else if (target->container->swapchain)
3299 TRACE("Rendering onscreen.\n");
3301 context = swapchain_get_context(target->container->swapchain);
3303 else
3305 TRACE("Rendering offscreen.\n");
3307 /* Stay with the current context if possible. Otherwise use the
3308 * context for the primary swapchain. */
3309 if (current_context && current_context->swapchain->device == device)
3310 context = current_context;
3311 else
3312 context = swapchain_get_context(device->swapchains[0]);
3315 context_enter(context);
3316 context_update_window(context);
3317 context_setup_target(context, target);
3318 if (!context->valid) return context;
3320 if (context != current_context)
3322 if (!context_set_current(context))
3323 ERR("Failed to activate the new context.\n");
3325 else if (context->needs_set)
3327 context_set_gl_context(context);
3330 return context;